summaryrefslogtreecommitdiffstats
path: root/src/gui
diff options
context:
space:
mode:
Diffstat (limited to 'src/gui')
-rw-r--r--src/gui/QtGui.dynlist8
-rw-r--r--src/gui/accessible/accessible.pri25
-rw-r--r--src/gui/accessible/qaccessible.cpp1094
-rw-r--r--src/gui/accessible/qaccessible.h425
-rw-r--r--src/gui/accessible/qaccessible2.cpp205
-rw-r--r--src/gui/accessible/qaccessible2.h246
-rw-r--r--src/gui/accessible/qaccessible_mac.mm2469
-rw-r--r--src/gui/accessible/qaccessible_mac_carbon.cpp119
-rw-r--r--src/gui/accessible/qaccessible_mac_cocoa.mm239
-rw-r--r--src/gui/accessible/qaccessible_mac_p.h479
-rw-r--r--src/gui/accessible/qaccessible_unix.cpp134
-rw-r--r--src/gui/accessible/qaccessible_win.cpp1217
-rw-r--r--src/gui/accessible/qaccessiblebridge.cpp158
-rw-r--r--src/gui/accessible/qaccessiblebridge.h92
-rw-r--r--src/gui/accessible/qaccessibleobject.cpp410
-rw-r--r--src/gui/accessible/qaccessibleobject.h140
-rw-r--r--src/gui/accessible/qaccessibleplugin.cpp107
-rw-r--r--src/gui/accessible/qaccessibleplugin.h87
-rw-r--r--src/gui/accessible/qaccessiblewidget.cpp1031
-rw-r--r--src/gui/accessible/qaccessiblewidget.h141
-rw-r--r--src/gui/animation/animation.pri3
-rw-r--r--src/gui/animation/qguivariantanimation.cpp98
-rw-r--r--src/gui/dialogs/dialogs.pri106
-rw-r--r--src/gui/dialogs/images/fit-page-24.pngbin985 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/fit-page-32.pngbin1330 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/fit-width-24.pngbin706 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/fit-width-32.pngbin1004 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-first-24.pngbin796 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-first-32.pngbin985 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-last-24.pngbin792 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-last-32.pngbin984 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-next-24.pngbin782 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-next-32.pngbin948 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-previous-24.pngbin797 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/go-previous-32.pngbin945 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/layout-landscape-24.pngbin820 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/layout-landscape-32.pngbin1353 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/layout-portrait-24.pngbin817 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/layout-portrait-32.pngbin1330 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/page-setup-24.pngbin620 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/page-setup-32.pngbin1154 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/print-24.pngbin914 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/print-32.pngbin1202 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/qtlogo-64.pngbin2991 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/status-color.pngbin1475 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/status-gray-scale.pngbin1254 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/view-page-multi-24.pngbin390 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/view-page-multi-32.pngbin556 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/view-page-one-24.pngbin662 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/view-page-one-32.pngbin810 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/view-page-sided-24.pngbin700 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/view-page-sided-32.pngbin908 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/zoom-in-24.pngbin1302 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/zoom-in-32.pngbin1873 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/zoom-out-24.pngbin1247 -> 0 bytes
-rw-r--r--src/gui/dialogs/images/zoom-out-32.pngbin1749 -> 0 bytes
-rw-r--r--src/gui/dialogs/qabstractpagesetupdialog.cpp139
-rw-r--r--src/gui/dialogs/qabstractpagesetupdialog.h82
-rw-r--r--src/gui/dialogs/qabstractpagesetupdialog_p.h88
-rw-r--r--src/gui/dialogs/qabstractprintdialog.cpp499
-rw-r--r--src/gui/dialogs/qabstractprintdialog.h130
-rw-r--r--src/gui/dialogs/qabstractprintdialog_p.h99
-rw-r--r--src/gui/dialogs/qcolordialog.cpp2115
-rw-r--r--src/gui/dialogs/qcolordialog.h150
-rw-r--r--src/gui/dialogs/qcolordialog_mac.mm500
-rw-r--r--src/gui/dialogs/qcolordialog_p.h142
-rw-r--r--src/gui/dialogs/qcolordialog_symbian.cpp107
-rw-r--r--src/gui/dialogs/qdialog.cpp1272
-rw-r--r--src/gui/dialogs/qdialog.h140
-rw-r--r--src/gui/dialogs/qdialog_p.h113
-rw-r--r--src/gui/dialogs/qdialogsbinarycompat_win.cpp137
-rw-r--r--src/gui/dialogs/qerrormessage.cpp429
-rw-r--r--src/gui/dialogs/qerrormessage.h88
-rw-r--r--src/gui/dialogs/qfiledialog.cpp3486
-rw-r--r--src/gui/dialogs/qfiledialog.h331
-rw-r--r--src/gui/dialogs/qfiledialog.ui356
-rw-r--r--src/gui/dialogs/qfiledialog_embedded.ui340
-rw-r--r--src/gui/dialogs/qfiledialog_mac.mm1157
-rw-r--r--src/gui/dialogs/qfiledialog_p.h427
-rw-r--r--src/gui/dialogs/qfiledialog_symbian.cpp199
-rw-r--r--src/gui/dialogs/qfiledialog_win.cpp825
-rw-r--r--src/gui/dialogs/qfiledialog_win_p.h243
-rw-r--r--src/gui/dialogs/qfileinfogatherer.cpp355
-rw-r--r--src/gui/dialogs/qfileinfogatherer_p.h207
-rw-r--r--src/gui/dialogs/qfilesystemmodel.cpp2027
-rw-r--r--src/gui/dialogs/qfilesystemmodel.h180
-rw-r--r--src/gui/dialogs/qfilesystemmodel_p.h337
-rw-r--r--src/gui/dialogs/qfontdialog.cpp1077
-rw-r--r--src/gui/dialogs/qfontdialog.h147
-rw-r--r--src/gui/dialogs/qfontdialog_mac.mm699
-rw-r--r--src/gui/dialogs/qfontdialog_p.h166
-rw-r--r--src/gui/dialogs/qfscompleter_p.h82
-rw-r--r--src/gui/dialogs/qinputdialog.cpp1489
-rw-r--r--src/gui/dialogs/qinputdialog.h256
-rw-r--r--src/gui/dialogs/qmessagebox.cpp2751
-rw-r--r--src/gui/dialogs/qmessagebox.h365
-rw-r--r--src/gui/dialogs/qmessagebox.qrc5
-rw-r--r--src/gui/dialogs/qnspanelproxy_mac.mm228
-rw-r--r--src/gui/dialogs/qpagesetupdialog.cpp240
-rw-r--r--src/gui/dialogs/qpagesetupdialog.h112
-rw-r--r--src/gui/dialogs/qpagesetupdialog_mac.mm315
-rw-r--r--src/gui/dialogs/qpagesetupdialog_unix.cpp620
-rw-r--r--src/gui/dialogs/qpagesetupdialog_unix_p.h105
-rw-r--r--src/gui/dialogs/qpagesetupdialog_win.cpp168
-rw-r--r--src/gui/dialogs/qpagesetupwidget.ui353
-rw-r--r--src/gui/dialogs/qprintdialog.h174
-rw-r--r--src/gui/dialogs/qprintdialog.qdoc58
-rw-r--r--src/gui/dialogs/qprintdialog.qrc38
-rw-r--r--src/gui/dialogs/qprintdialog_mac.mm429
-rw-r--r--src/gui/dialogs/qprintdialog_unix.cpp1286
-rw-r--r--src/gui/dialogs/qprintdialog_win.cpp316
-rw-r--r--src/gui/dialogs/qprintpreviewdialog.cpp803
-rw-r--r--src/gui/dialogs/qprintpreviewdialog.h107
-rw-r--r--src/gui/dialogs/qprintpropertieswidget.ui70
-rw-r--r--src/gui/dialogs/qprintsettingsoutput.ui363
-rw-r--r--src/gui/dialogs/qprintwidget.ui116
-rw-r--r--src/gui/dialogs/qprogressdialog.cpp907
-rw-r--r--src/gui/dialogs/qprogressdialog.h145
-rw-r--r--src/gui/dialogs/qsidebar.cpp509
-rw-r--r--src/gui/dialogs/qsidebar_p.h158
-rw-r--r--src/gui/dialogs/qwizard.cpp3928
-rw-r--r--src/gui/dialogs/qwizard.h268
-rw-r--r--src/gui/dialogs/qwizard_win.cpp759
-rw-r--r--src/gui/dialogs/qwizard_win_p.h158
-rw-r--r--src/gui/effects/effects.pri6
-rw-r--r--src/gui/effects/qgraphicseffect.cpp1235
-rw-r--r--src/gui/effects/qgraphicseffect.h289
-rw-r--r--src/gui/effects/qgraphicseffect_p.h231
-rw-r--r--src/gui/effects/qpixmapfilter.cpp1381
-rw-r--r--src/gui/effects/qpixmapfilter_p.h196
-rw-r--r--src/gui/graphicsview/graphicsview.pri52
-rw-r--r--src/gui/graphicsview/qgraph_p.h286
-rw-r--r--src/gui/graphicsview/qgraphicsanchorlayout.cpp533
-rw-r--r--src/gui/graphicsview/qgraphicsanchorlayout.h128
-rw-r--r--src/gui/graphicsview/qgraphicsanchorlayout_p.cpp3015
-rw-r--r--src/gui/graphicsview/qgraphicsanchorlayout_p.h594
-rw-r--r--src/gui/graphicsview/qgraphicsgridlayout.cpp690
-rw-r--r--src/gui/graphicsview/qgraphicsgridlayout.h144
-rw-r--r--src/gui/graphicsview/qgraphicsitem.cpp11597
-rw-r--r--src/gui/graphicsview/qgraphicsitem.h1172
-rw-r--r--src/gui/graphicsview/qgraphicsitem_p.h891
-rw-r--r--src/gui/graphicsview/qgraphicsitemanimation.cpp599
-rw-r--r--src/gui/graphicsview/qgraphicsitemanimation.h120
-rw-r--r--src/gui/graphicsview/qgraphicslayout.cpp451
-rw-r--r--src/gui/graphicsview/qgraphicslayout.h98
-rw-r--r--src/gui/graphicsview/qgraphicslayout_p.cpp198
-rw-r--r--src/gui/graphicsview/qgraphicslayout_p.h154
-rw-r--r--src/gui/graphicsview/qgraphicslayoutitem.cpp935
-rw-r--r--src/gui/graphicsview/qgraphicslayoutitem.h155
-rw-r--r--src/gui/graphicsview/qgraphicslayoutitem_p.h103
-rw-r--r--src/gui/graphicsview/qgraphicslinearlayout.cpp568
-rw-r--r--src/gui/graphicsview/qgraphicslinearlayout.h119
-rw-r--r--src/gui/graphicsview/qgraphicsproxywidget.cpp1570
-rw-r--r--src/gui/graphicsview/qgraphicsproxywidget.h147
-rw-r--r--src/gui/graphicsview/qgraphicsproxywidget_p.h130
-rw-r--r--src/gui/graphicsview/qgraphicsscene.cpp6491
-rw-r--r--src/gui/graphicsview/qgraphicsscene.h329
-rw-r--r--src/gui/graphicsview/qgraphicsscene_bsp.cpp296
-rw-r--r--src/gui/graphicsview/qgraphicsscene_bsp_p.h132
-rw-r--r--src/gui/graphicsview/qgraphicsscene_p.h359
-rw-r--r--src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp719
-rw-r--r--src/gui/graphicsview/qgraphicsscenebsptreeindex_p.h206
-rw-r--r--src/gui/graphicsview/qgraphicssceneevent.cpp1674
-rw-r--r--src/gui/graphicsview/qgraphicssceneevent.h326
-rw-r--r--src/gui/graphicsview/qgraphicssceneindex.cpp648
-rw-r--r--src/gui/graphicsview/qgraphicssceneindex_p.h182
-rw-r--r--src/gui/graphicsview/qgraphicsscenelinearindex.cpp95
-rw-r--r--src/gui/graphicsview/qgraphicsscenelinearindex_p.h109
-rw-r--r--src/gui/graphicsview/qgraphicstransform.cpp594
-rw-r--r--src/gui/graphicsview/qgraphicstransform.h159
-rw-r--r--src/gui/graphicsview/qgraphicstransform_p.h78
-rw-r--r--src/gui/graphicsview/qgraphicsview.cpp3880
-rw-r--r--src/gui/graphicsview/qgraphicsview.h316
-rw-r--r--src/gui/graphicsview/qgraphicsview_p.h233
-rw-r--r--src/gui/graphicsview/qgraphicswidget.cpp2388
-rw-r--r--src/gui/graphicsview/qgraphicswidget.h257
-rw-r--r--src/gui/graphicsview/qgraphicswidget_p.cpp910
-rw-r--r--src/gui/graphicsview/qgraphicswidget_p.h226
-rw-r--r--src/gui/graphicsview/qgridlayoutengine.cpp1742
-rw-r--r--src/gui/graphicsview/qgridlayoutengine_p.h458
-rw-r--r--src/gui/graphicsview/qsimplex_p.cpp673
-rw-r--r--src/gui/graphicsview/qsimplex_p.h208
-rw-r--r--src/gui/gui.pro44
-rw-r--r--src/gui/guikernel/qplatformcursor_qpa.cpp1
-rw-r--r--src/gui/guikernel/qt_gui_pch.h (renamed from src/gui/kernel/qt_gui_pch.h)6
-rw-r--r--src/gui/inputmethod/inputmethod.pri27
-rw-r--r--src/gui/inputmethod/qcoefepinputcontext_p.h176
-rw-r--r--src/gui/inputmethod/qcoefepinputcontext_s60.cpp1200
-rw-r--r--src/gui/inputmethod/qinputcontext.cpp500
-rw-r--r--src/gui/inputmethod/qinputcontext.h139
-rw-r--r--src/gui/inputmethod/qinputcontext_p.h94
-rw-r--r--src/gui/inputmethod/qinputcontextfactory.cpp354
-rw-r--r--src/gui/inputmethod/qinputcontextfactory.h88
-rw-r--r--src/gui/inputmethod/qinputcontextplugin.cpp178
-rw-r--r--src/gui/inputmethod/qinputcontextplugin.h106
-rw-r--r--src/gui/inputmethod/qmacinputcontext_mac.cpp378
-rw-r--r--src/gui/inputmethod/qmacinputcontext_p.h97
-rw-r--r--src/gui/inputmethod/qwininputcontext_p.h111
-rw-r--r--src/gui/inputmethod/qwininputcontext_win.cpp847
-rw-r--r--src/gui/inputmethod/qximinputcontext_p.h142
-rw-r--r--src/gui/inputmethod/qximinputcontext_x11.cpp885
-rw-r--r--src/gui/itemviews/itemviews.pri70
-rw-r--r--src/gui/itemviews/qabstractitemdelegate.cpp393
-rw-r--r--src/gui/itemviews/qabstractitemdelegate.h134
-rw-r--r--src/gui/itemviews/qabstractitemview.cpp4241
-rw-r--r--src/gui/itemviews/qabstractitemview.h380
-rw-r--r--src/gui/itemviews/qabstractitemview_p.h457
-rw-r--r--src/gui/itemviews/qabstractproxymodel.cpp409
-rw-r--r--src/gui/itemviews/qabstractproxymodel.h116
-rw-r--r--src/gui/itemviews/qabstractproxymodel_p.h76
-rw-r--r--src/gui/itemviews/qbsptree.cpp145
-rw-r--r--src/gui/itemviews/qbsptree_p.h119
-rw-r--r--src/gui/itemviews/qcolumnview.cpp1168
-rw-r--r--src/gui/itemviews/qcolumnview.h123
-rw-r--r--src/gui/itemviews/qcolumnview_p.h189
-rw-r--r--src/gui/itemviews/qcolumnviewgrip.cpp194
-rw-r--r--src/gui/itemviews/qcolumnviewgrip_p.h104
-rw-r--r--src/gui/itemviews/qdatawidgetmapper.cpp849
-rw-r--r--src/gui/itemviews/qdatawidgetmapper.h128
-rw-r--r--src/gui/itemviews/qdirmodel.cpp1406
-rw-r--r--src/gui/itemviews/qdirmodel.h160
-rw-r--r--src/gui/itemviews/qfileiconprovider.cpp509
-rw-r--r--src/gui/itemviews/qfileiconprovider.h82
-rw-r--r--src/gui/itemviews/qheaderview.cpp3615
-rw-r--r--src/gui/itemviews/qheaderview.h250
-rw-r--r--src/gui/itemviews/qheaderview_p.h366
-rw-r--r--src/gui/itemviews/qitemdelegate.cpp1341
-rw-r--r--src/gui/itemviews/qitemdelegate.h141
-rw-r--r--src/gui/itemviews/qitemeditorfactory.cpp578
-rw-r--r--src/gui/itemviews/qitemeditorfactory.h124
-rw-r--r--src/gui/itemviews/qitemeditorfactory_p.h99
-rw-r--r--src/gui/itemviews/qitemselectionmodel.cpp1625
-rw-r--r--src/gui/itemviews/qitemselectionmodel.h255
-rw-r--r--src/gui/itemviews/qitemselectionmodel_p.h113
-rw-r--r--src/gui/itemviews/qlistview.cpp3213
-rw-r--r--src/gui/itemviews/qlistview.h203
-rw-r--r--src/gui/itemviews/qlistview_p.h492
-rw-r--r--src/gui/itemviews/qlistwidget.cpp1914
-rw-r--r--src/gui/itemviews/qlistwidget.h335
-rw-r--r--src/gui/itemviews/qlistwidget_p.h175
-rw-r--r--src/gui/itemviews/qproxymodel.cpp547
-rw-r--r--src/gui/itemviews/qproxymodel.h143
-rw-r--r--src/gui/itemviews/qproxymodel_p.h100
-rw-r--r--src/gui/itemviews/qsortfilterproxymodel.cpp2542
-rw-r--r--src/gui/itemviews/qsortfilterproxymodel.h201
-rw-r--r--src/gui/itemviews/qstandarditemmodel.cpp3115
-rw-r--r--src/gui/itemviews/qstandarditemmodel.h456
-rw-r--r--src/gui/itemviews/qstandarditemmodel_p.h192
-rw-r--r--src/gui/itemviews/qstringlistmodel.cpp308
-rw-r--r--src/gui/itemviews/qstringlistmodel.h91
-rw-r--r--src/gui/itemviews/qstyleditemdelegate.cpp765
-rw-r--r--src/gui/itemviews/qstyleditemdelegate.h116
-rw-r--r--src/gui/itemviews/qtableview.cpp3198
-rw-r--r--src/gui/itemviews/qtableview.h197
-rw-r--r--src/gui/itemviews/qtableview_p.h257
-rw-r--r--src/gui/itemviews/qtablewidget.cpp2685
-rw-r--r--src/gui/itemviews/qtablewidget.h377
-rw-r--r--src/gui/itemviews/qtablewidget_p.h222
-rw-r--r--src/gui/itemviews/qtreeview.cpp3755
-rw-r--r--src/gui/itemviews/qtreeview.h239
-rw-r--r--src/gui/itemviews/qtreeview_p.h251
-rw-r--r--src/gui/itemviews/qtreewidget.cpp3460
-rw-r--r--src/gui/itemviews/qtreewidget.h432
-rw-r--r--src/gui/itemviews/qtreewidget_p.h248
-rw-r--r--src/gui/itemviews/qtreewidgetitemiterator.cpp458
-rw-r--r--src/gui/itemviews/qtreewidgetitemiterator.h159
-rw-r--r--src/gui/itemviews/qtreewidgetitemiterator_p.h110
-rw-r--r--src/gui/itemviews/qwidgetitemdata_p.h88
-rw-r--r--src/gui/kernel/kernel.pri246
-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.cpp5687
-rw-r--r--src/gui/kernel/qapplication.h422
-rw-r--r--src/gui/kernel/qapplication_p.h626
-rw-r--r--src/gui/kernel/qapplication_qpa.cpp431
-rw-r--r--src/gui/kernel/qbackingstore.cpp1665
-rw-r--r--src/gui/kernel/qbackingstore_p.h278
-rw-r--r--src/gui/kernel/qboxlayout.cpp1550
-rw-r--r--src/gui/kernel/qboxlayout.h173
-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_qpa.cpp174
-rw-r--r--src/gui/kernel/qdesktopwidget_qpa_p.h81
-rw-r--r--src/gui/kernel/qformlayout.cpp2079
-rw-r--r--src/gui/kernel/qformlayout.h163
-rw-r--r--src/gui/kernel/qgesture.cpp1118
-rw-r--r--src/gui/kernel/qgesture.h328
-rw-r--r--src/gui/kernel/qgesture_p.h245
-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/qguiplatformplugin.cpp298
-rw-r--r--src/gui/kernel/qguiplatformplugin_p.h126
-rw-r--r--src/gui/kernel/qicon.cpp1165
-rw-r--r--src/gui/kernel/qicon.h143
-rw-r--r--src/gui/kernel/qicon_p.h139
-rw-r--r--src/gui/kernel/qiconengine.cpp324
-rw-r--r--src/gui/kernel/qiconengine.h104
-rw-r--r--src/gui/kernel/qiconengineplugin.cpp171
-rw-r--r--src/gui/kernel/qiconengineplugin.h104
-rw-r--r--src/gui/kernel/qiconloader.cpp573
-rw-r--r--src/gui/kernel/qiconloader_p.h192
-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/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/qsound.cpp367
-rw-r--r--src/gui/kernel/qsound.h90
-rw-r--r--src/gui/kernel/qsound_p.h100
-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/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.cpp12677
-rw-r--r--src/gui/kernel/qwidget.h1091
-rw-r--r--src/gui/kernel/qwidget_p.h1034
-rw-r--r--src/gui/kernel/qwidget_qpa.cpp824
-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/qwidgetwindow_qpa.cpp188
-rw-r--r--src/gui/kernel/qwidgetwindow_qpa_p.h83
-rw-r--r--src/gui/kernel/symbian.pri7
-rw-r--r--src/gui/kernel/win.pri4
-rw-r--r--src/gui/kernel/x11.pri4
-rw-r--r--src/gui/mac/images/copyarrowcursor.pngbin1976 -> 0 bytes
-rw-r--r--src/gui/mac/images/forbiddencursor.pngbin1745 -> 0 bytes
-rw-r--r--src/gui/mac/images/leopard-unified-toolbar-on.pngbin356 -> 0 bytes
-rw-r--r--src/gui/mac/images/pluscursor.pngbin688 -> 0 bytes
-rw-r--r--src/gui/mac/images/spincursor.pngbin748 -> 0 bytes
-rw-r--r--src/gui/mac/images/waitcursor.pngbin724 -> 0 bytes
-rw-r--r--src/gui/mac/macresources.qrc12
-rw-r--r--src/gui/mac/qt_menu.nib/classes.nib59
-rw-r--r--src/gui/mac/qt_menu.nib/info.nib18
-rw-r--r--src/gui/mac/qt_menu.nib/keyedobjects.nibbin5560 -> 0 bytes
-rw-r--r--src/gui/painting/qpaintdevice_qpa.cpp2
-rw-r--r--src/gui/platforms/mac/qapplication_mac.mm3134
-rw-r--r--src/gui/platforms/mac/qclipboard_mac.cpp634
-rw-r--r--src/gui/platforms/mac/qcocoaapplication_mac.mm222
-rw-r--r--src/gui/platforms/mac/qcocoaapplication_mac_p.h117
-rw-r--r--src/gui/platforms/mac/qcocoaapplicationdelegate_mac.mm354
-rw-r--r--src/gui/platforms/mac/qcocoaapplicationdelegate_mac_p.h128
-rw-r--r--src/gui/platforms/mac/qcocoaintrospection_mac.mm125
-rw-r--r--src/gui/platforms/mac/qcocoaintrospection_p.h84
-rw-r--r--src/gui/platforms/mac/qcocoamenuloader_mac.mm264
-rw-r--r--src/gui/platforms/mac/qcocoamenuloader_mac_p.h95
-rw-r--r--src/gui/platforms/mac/qcocoapanel_mac.mm70
-rw-r--r--src/gui/platforms/mac/qcocoapanel_mac_p.h83
-rw-r--r--src/gui/platforms/mac/qcocoasharedwindowmethods_mac_p.h610
-rw-r--r--src/gui/platforms/mac/qcocoaview_mac.mm1388
-rw-r--r--src/gui/platforms/mac/qcocoaview_mac_p.h87
-rw-r--r--src/gui/platforms/mac/qcocoawindow_mac.mm90
-rw-r--r--src/gui/platforms/mac/qcocoawindow_mac_p.h97
-rw-r--r--src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac.mm62
-rw-r--r--src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac_p.h61
-rw-r--r--src/gui/platforms/mac/qcocoawindowdelegate_mac.mm439
-rw-r--r--src/gui/platforms/mac/qcocoawindowdelegate_mac_p.h110
-rw-r--r--src/gui/platforms/mac/qcolormap_mac.cpp111
-rw-r--r--src/gui/platforms/mac/qcursor_mac.mm689
-rw-r--r--src/gui/platforms/mac/qdesktopwidget_mac.mm257
-rw-r--r--src/gui/platforms/mac/qdesktopwidget_mac_p.h75
-rw-r--r--src/gui/platforms/mac/qdnd_mac.mm753
-rw-r--r--src/gui/platforms/mac/qeventdispatcher_mac.mm1200
-rw-r--r--src/gui/platforms/mac/qeventdispatcher_mac_p.h224
-rw-r--r--src/gui/platforms/mac/qfont_mac.cpp165
-rw-r--r--src/gui/platforms/mac/qfontdatabase_mac.cpp466
-rw-r--r--src/gui/platforms/mac/qfontengine_coretext.mm880
-rw-r--r--src/gui/platforms/mac/qfontengine_coretext_p.h144
-rw-r--r--src/gui/platforms/mac/qfontengine_mac.mm1236
-rw-r--r--src/gui/platforms/mac/qfontengine_mac_p.h165
-rw-r--r--src/gui/platforms/mac/qkeymapper_mac.cpp1023
-rw-r--r--src/gui/platforms/mac/qmacdefines_mac.h180
-rw-r--r--src/gui/platforms/mac/qmacgesturerecognizer_mac.mm272
-rw-r--r--src/gui/platforms/mac/qmacgesturerecognizer_mac_p.h106
-rw-r--r--src/gui/platforms/mac/qmime_mac.cpp1310
-rw-r--r--src/gui/platforms/mac/qmultitouch_mac.mm218
-rw-r--r--src/gui/platforms/mac/qmultitouch_mac_p.h102
-rw-r--r--src/gui/platforms/mac/qnsframeview_mac_p.h154
-rw-r--r--src/gui/platforms/mac/qnsthemeframe_mac_p.h246
-rw-r--r--src/gui/platforms/mac/qnstitledframe_mac_p.h205
-rw-r--r--src/gui/platforms/mac/qpaintdevice_mac.cpp152
-rw-r--r--src/gui/platforms/mac/qpaintengine_mac.cpp1751
-rw-r--r--src/gui/platforms/mac/qpaintengine_mac_p.h254
-rw-r--r--src/gui/platforms/mac/qpixmap_mac.cpp1195
-rw-r--r--src/gui/platforms/mac/qpixmap_mac_p.h134
-rw-r--r--src/gui/platforms/mac/qprintengine_mac.mm911
-rw-r--r--src/gui/platforms/mac/qprintengine_mac_p.h166
-rw-r--r--src/gui/platforms/mac/qprinterinfo_mac.cpp120
-rw-r--r--src/gui/platforms/mac/qrawfont_mac.cpp83
-rw-r--r--src/gui/platforms/mac/qregion_mac.cpp286
-rw-r--r--src/gui/platforms/mac/qsound_mac.mm190
-rw-r--r--src/gui/platforms/mac/qt_cocoa_helpers_mac.mm1824
-rw-r--r--src/gui/platforms/mac/qt_cocoa_helpers_mac_p.h340
-rw-r--r--src/gui/platforms/mac/qt_mac.cpp174
-rw-r--r--src/gui/platforms/mac/qt_mac_p.h286
-rw-r--r--src/gui/platforms/mac/qtextengine_mac.cpp656
-rw-r--r--src/gui/platforms/mac/qwidget_mac.mm5420
-rw-r--r--src/gui/platforms/s60/qapplication_s60.cpp2712
-rw-r--r--src/gui/platforms/s60/qclipboard_s60.cpp331
-rw-r--r--src/gui/platforms/s60/qcolormap_s60.cpp107
-rw-r--r--src/gui/platforms/s60/qcursor_s60.cpp533
-rw-r--r--src/gui/platforms/s60/qdesktopwidget_s60.cpp316
-rw-r--r--src/gui/platforms/s60/qdnd_s60.cpp359
-rw-r--r--src/gui/platforms/s60/qeventdispatcher_s60.cpp196
-rw-r--r--src/gui/platforms/s60/qeventdispatcher_s60_p.h127
-rw-r--r--src/gui/platforms/s60/qfont_s60.cpp136
-rw-r--r--src/gui/platforms/s60/qfontdatabase_s60.cpp1091
-rw-r--r--src/gui/platforms/s60/qfontengine_s60.cpp569
-rw-r--r--src/gui/platforms/s60/qfontengine_s60_p.h167
-rw-r--r--src/gui/platforms/s60/qkeymapper_s60.cpp258
-rw-r--r--src/gui/platforms/s60/qpaintengine_s60.cpp145
-rw-r--r--src/gui/platforms/s60/qpaintengine_s60_p.h84
-rw-r--r--src/gui/platforms/s60/qpixmap_s60.cpp1040
-rw-r--r--src/gui/platforms/s60/qpixmap_s60_p.h141
-rw-r--r--src/gui/platforms/s60/qregion_s60.cpp52
-rw-r--r--src/gui/platforms/s60/qsoftkeymanager_s60.cpp440
-rw-r--r--src/gui/platforms/s60/qsoftkeymanager_s60_p.h113
-rw-r--r--src/gui/platforms/s60/qsound_s60.cpp224
-rw-r--r--src/gui/platforms/s60/qt_s60_p.h625
-rw-r--r--src/gui/platforms/s60/qwidget_s60.cpp1450
-rw-r--r--src/gui/platforms/win/qapplication_win.cpp4243
-rw-r--r--src/gui/platforms/win/qclipboard_win.cpp398
-rw-r--r--src/gui/platforms/win/qcolormap_win.cpp201
-rw-r--r--src/gui/platforms/win/qcursor_win.cpp492
-rw-r--r--src/gui/platforms/win/qdesktopwidget_win.cpp387
-rw-r--r--src/gui/platforms/win/qdnd_win.cpp1027
-rw-r--r--src/gui/platforms/win/qfont_win.cpp166
-rw-r--r--src/gui/platforms/win/qfontdatabase_win.cpp1348
-rw-r--r--src/gui/platforms/win/qfontengine_win.cpp1339
-rw-r--r--src/gui/platforms/win/qfontengine_win_p.h164
-rw-r--r--src/gui/platforms/win/qguifunctions_wince.cpp408
-rw-r--r--src/gui/platforms/win/qguifunctions_wince.h151
-rw-r--r--src/gui/platforms/win/qkeymapper_win.cpp1207
-rw-r--r--src/gui/platforms/win/qmime_win.cpp1556
-rw-r--r--src/gui/platforms/win/qole_win.cpp255
-rw-r--r--src/gui/platforms/win/qpaintdevice_win.cpp62
-rw-r--r--src/gui/platforms/win/qpixmap_win.cpp477
-rw-r--r--src/gui/platforms/win/qprintengine_win.cpp1776
-rw-r--r--src/gui/platforms/win/qprintengine_win_p.h261
-rw-r--r--src/gui/platforms/win/qprinterinfo_win.cpp122
-rw-r--r--src/gui/platforms/win/qrawfont_win.cpp707
-rw-r--r--src/gui/platforms/win/qregion_win.cpp149
-rw-r--r--src/gui/platforms/win/qsound_win.cpp205
-rw-r--r--src/gui/platforms/win/qwidget_win.cpp2139
-rw-r--r--src/gui/platforms/win/qwidget_wince.cpp675
-rw-r--r--src/gui/platforms/win/qwindowdefs_win.h132
-rw-r--r--src/gui/platforms/win/qwinnativepangesturerecognizer_win.cpp133
-rw-r--r--src/gui/platforms/win/qwinnativepangesturerecognizer_win_p.h80
-rw-r--r--src/gui/platforms/x11/qapplication_x11.cpp6239
-rw-r--r--src/gui/platforms/x11/qclipboard_x11.cpp1539
-rw-r--r--src/gui/platforms/x11/qcolormap_x11.cpp670
-rw-r--r--src/gui/platforms/x11/qcursor_x11.cpp637
-rw-r--r--src/gui/platforms/x11/qdesktopwidget_x11.cpp406
-rw-r--r--src/gui/platforms/x11/qdnd_x11.cpp2072
-rw-r--r--src/gui/platforms/x11/qeventdispatcher_x11.cpp191
-rw-r--r--src/gui/platforms/x11/qeventdispatcher_x11_p.h86
-rw-r--r--src/gui/platforms/x11/qfont_x11.cpp368
-rw-r--r--src/gui/platforms/x11/qfontdatabase_x11.cpp2146
-rw-r--r--src/gui/platforms/x11/qfontengine_x11.cpp1215
-rw-r--r--src/gui/platforms/x11/qfontengine_x11_p.h180
-rw-r--r--src/gui/platforms/x11/qkde.cpp176
-rw-r--r--src/gui/platforms/x11/qkde_p.h81
-rw-r--r--src/gui/platforms/x11/qkeymapper_x11.cpp1869
-rw-r--r--src/gui/platforms/x11/qkeymapper_x11_p.cpp489
-rw-r--r--src/gui/platforms/x11/qmotifdnd_x11.cpp1031
-rw-r--r--src/gui/platforms/x11/qpaintdevice_x11.cpp84
-rw-r--r--src/gui/platforms/x11/qpaintengine_x11.cpp2507
-rw-r--r--src/gui/platforms/x11/qpaintengine_x11_p.h246
-rw-r--r--src/gui/platforms/x11/qpixmap_x11.cpp2419
-rw-r--r--src/gui/platforms/x11/qpixmap_x11_p.h156
-rw-r--r--src/gui/platforms/x11/qregion_x11.cpp92
-rw-r--r--src/gui/platforms/x11/qsound_x11.cpp296
-rw-r--r--src/gui/platforms/x11/qt_x11_p.h757
-rw-r--r--src/gui/platforms/x11/qwidget_x11.cpp3146
-rw-r--r--src/gui/platforms/x11/qwidgetcreate_x11.cpp79
-rw-r--r--src/gui/platforms/x11/qx11embed_x11.cpp1808
-rw-r--r--src/gui/platforms/x11/qx11embed_x11.h132
-rw-r--r--src/gui/platforms/x11/qx11info_x11.cpp543
-rw-r--r--src/gui/platforms/x11/qx11info_x11.h123
-rw-r--r--src/gui/s60framework/qs60mainapplication.cpp165
-rw-r--r--src/gui/s60framework/qs60mainapplication.h93
-rw-r--r--src/gui/s60framework/qs60mainapplication_p.h66
-rw-r--r--src/gui/s60framework/qs60mainappui.cpp430
-rw-r--r--src/gui/s60framework/qs60mainappui.h152
-rw-r--r--src/gui/s60framework/qs60maindocument.cpp138
-rw-r--r--src/gui/s60framework/qs60maindocument.h92
-rw-r--r--src/gui/s60framework/s60framework.pri10
-rw-r--r--src/gui/s60framework/s60main.rss85
-rw-r--r--src/gui/statemachine/qbasickeyeventtransition.cpp208
-rw-r--r--src/gui/statemachine/qbasickeyeventtransition_p.h98
-rw-r--r--src/gui/statemachine/qbasicmouseeventtransition.cpp213
-rw-r--r--src/gui/statemachine/qbasicmouseeventtransition_p.h101
-rw-r--r--src/gui/statemachine/qguistatemachine.cpp500
-rw-r--r--src/gui/statemachine/qkeyeventtransition.cpp178
-rw-r--r--src/gui/statemachine/qkeyeventtransition.h88
-rw-r--r--src/gui/statemachine/qmouseeventtransition.cpp206
-rw-r--r--src/gui/statemachine/qmouseeventtransition.h92
-rw-r--r--src/gui/statemachine/statemachine.pri13
-rw-r--r--src/gui/styles/images/cdr-128.pngbin16418 -> 0 bytes
-rw-r--r--src/gui/styles/images/cdr-16.pngbin845 -> 0 bytes
-rw-r--r--src/gui/styles/images/cdr-32.pngbin2016 -> 0 bytes
-rw-r--r--src/gui/styles/images/closedock-16.pngbin516 -> 0 bytes
-rw-r--r--src/gui/styles/images/closedock-down-16.pngbin578 -> 0 bytes
-rw-r--r--src/gui/styles/images/computer-16.pngbin782 -> 0 bytes
-rw-r--r--src/gui/styles/images/computer-32.pngbin1807 -> 0 bytes
-rw-r--r--src/gui/styles/images/defaults60theme.blobbin74127 -> 0 bytes
-rw-r--r--src/gui/styles/images/desktop-16.pngbin773 -> 0 bytes
-rw-r--r--src/gui/styles/images/desktop-32.pngbin1103 -> 0 bytes
-rw-r--r--src/gui/styles/images/dirclosed-128.pngbin1386 -> 0 bytes
-rw-r--r--src/gui/styles/images/dirclosed-16.pngbin231 -> 0 bytes
-rw-r--r--src/gui/styles/images/dirclosed-32.pngbin474 -> 0 bytes
-rw-r--r--src/gui/styles/images/dirlink-128.pngbin5155 -> 0 bytes
-rw-r--r--src/gui/styles/images/dirlink-16.pngbin416 -> 0 bytes
-rw-r--r--src/gui/styles/images/dirlink-32.pngbin1046 -> 0 bytes
-rw-r--r--src/gui/styles/images/diropen-128.pngbin2075 -> 0 bytes
-rw-r--r--src/gui/styles/images/diropen-16.pngbin248 -> 0 bytes
-rw-r--r--src/gui/styles/images/diropen-32.pngbin633 -> 0 bytes
-rw-r--r--src/gui/styles/images/dockdock-16.pngbin438 -> 0 bytes
-rw-r--r--src/gui/styles/images/dockdock-down-16.pngbin406 -> 0 bytes
-rw-r--r--src/gui/styles/images/down-128.pngbin9550 -> 0 bytes
-rw-r--r--src/gui/styles/images/down-16.pngbin817 -> 0 bytes
-rw-r--r--src/gui/styles/images/down-32.pngbin1820 -> 0 bytes
-rw-r--r--src/gui/styles/images/dvd-128.pngbin14941 -> 0 bytes
-rw-r--r--src/gui/styles/images/dvd-16.pngbin892 -> 0 bytes
-rw-r--r--src/gui/styles/images/dvd-32.pngbin2205 -> 0 bytes
-rw-r--r--src/gui/styles/images/file-128.pngbin3997 -> 0 bytes
-rw-r--r--src/gui/styles/images/file-16.pngbin423 -> 0 bytes
-rw-r--r--src/gui/styles/images/file-32.pngbin713 -> 0 bytes
-rw-r--r--src/gui/styles/images/filecontents-128.pngbin8109 -> 0 bytes
-rw-r--r--src/gui/styles/images/filecontents-16.pngbin766 -> 0 bytes
-rw-r--r--src/gui/styles/images/filecontents-32.pngbin1712 -> 0 bytes
-rw-r--r--src/gui/styles/images/fileinfo-128.pngbin12002 -> 0 bytes
-rw-r--r--src/gui/styles/images/fileinfo-16.pngbin849 -> 0 bytes
-rw-r--r--src/gui/styles/images/fileinfo-32.pngbin2010 -> 0 bytes
-rw-r--r--src/gui/styles/images/filelink-128.pngbin5601 -> 0 bytes
-rw-r--r--src/gui/styles/images/filelink-16.pngbin566 -> 0 bytes
-rw-r--r--src/gui/styles/images/filelink-32.pngbin1192 -> 0 bytes
-rw-r--r--src/gui/styles/images/floppy-128.pngbin5074 -> 0 bytes
-rw-r--r--src/gui/styles/images/floppy-16.pngbin602 -> 0 bytes
-rw-r--r--src/gui/styles/images/floppy-32.pngbin1019 -> 0 bytes
-rw-r--r--src/gui/styles/images/fontbitmap-16.pngbin537 -> 0 bytes
-rw-r--r--src/gui/styles/images/fonttruetype-16.pngbin442 -> 0 bytes
-rw-r--r--src/gui/styles/images/harddrive-128.pngbin11250 -> 0 bytes
-rw-r--r--src/gui/styles/images/harddrive-16.pngbin802 -> 0 bytes
-rw-r--r--src/gui/styles/images/harddrive-32.pngbin1751 -> 0 bytes
-rw-r--r--src/gui/styles/images/left-128.pngbin9432 -> 0 bytes
-rw-r--r--src/gui/styles/images/left-16.pngbin826 -> 0 bytes
-rw-r--r--src/gui/styles/images/left-32.pngbin1799 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-pause-16.pngbin229 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-pause-32.pngbin185 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-play-16.pngbin262 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-play-32.pngbin413 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-seek-backward-16.pngbin384 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-seek-backward-32.pngbin548 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-seek-forward-16.pngbin370 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-seek-forward-32.pngbin524 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-skip-backward-16.pngbin396 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-skip-backward-32.pngbin570 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-skip-forward-16.pngbin384 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-skip-forward-32.pngbin549 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-stop-16.pngbin166 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-stop-32.pngbin176 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-volume-16.pngbin799 -> 0 bytes
-rw-r--r--src/gui/styles/images/media-volume-muted-16.pngbin668 -> 0 bytes
-rw-r--r--src/gui/styles/images/networkdrive-128.pngbin18075 -> 0 bytes
-rw-r--r--src/gui/styles/images/networkdrive-16.pngbin885 -> 0 bytes
-rw-r--r--src/gui/styles/images/networkdrive-32.pngbin2245 -> 0 bytes
-rw-r--r--src/gui/styles/images/newdirectory-128.pngbin7503 -> 0 bytes
-rw-r--r--src/gui/styles/images/newdirectory-16.pngbin870 -> 0 bytes
-rw-r--r--src/gui/styles/images/newdirectory-32.pngbin1590 -> 0 bytes
-rw-r--r--src/gui/styles/images/parentdir-128.pngbin8093 -> 0 bytes
-rw-r--r--src/gui/styles/images/parentdir-16.pngbin938 -> 0 bytes
-rw-r--r--src/gui/styles/images/parentdir-32.pngbin1603 -> 0 bytes
-rw-r--r--src/gui/styles/images/refresh-24.pngbin1654 -> 0 bytes
-rw-r--r--src/gui/styles/images/refresh-32.pngbin2431 -> 0 bytes
-rw-r--r--src/gui/styles/images/right-128.pngbin9367 -> 0 bytes
-rw-r--r--src/gui/styles/images/right-16.pngbin811 -> 0 bytes
-rw-r--r--src/gui/styles/images/right-32.pngbin1804 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-apply-128.pngbin5395 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-apply-16.pngbin611 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-apply-32.pngbin1279 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-cancel-128.pngbin7039 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-cancel-16.pngbin689 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-cancel-32.pngbin1573 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-clear-128.pngbin3094 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-clear-16.pngbin456 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-clear-32.pngbin866 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-close-128.pngbin4512 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-close-16.pngbin366 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-close-32.pngbin780 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-closetab-16.pngbin406 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-closetab-down-16.pngbin481 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-closetab-hover-16.pngbin570 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-delete-128.pngbin5414 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-delete-16.pngbin722 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-delete-32.pngbin1541 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-help-128.pngbin10765 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-help-16.pngbin840 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-help-32.pngbin2066 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-no-128.pngbin6520 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-no-16.pngbin701 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-no-32.pngbin1445 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-ok-128.pngbin4232 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-ok-16.pngbin584 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-ok-32.pngbin1246 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-open-128.pngbin5415 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-open-16.pngbin629 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-open-32.pngbin1154 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-save-128.pngbin4398 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-save-16.pngbin583 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-save-32.pngbin1092 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-yes-128.pngbin6554 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-yes-16.pngbin687 -> 0 bytes
-rw-r--r--src/gui/styles/images/standardbutton-yes-32.pngbin1504 -> 0 bytes
-rw-r--r--src/gui/styles/images/stop-24.pngbin1267 -> 0 bytes
-rw-r--r--src/gui/styles/images/stop-32.pngbin1878 -> 0 bytes
-rw-r--r--src/gui/styles/images/trash-128.pngbin3296 -> 0 bytes
-rw-r--r--src/gui/styles/images/trash-16.pngbin419 -> 0 bytes
-rw-r--r--src/gui/styles/images/trash-32.pngbin883 -> 0 bytes
-rw-r--r--src/gui/styles/images/up-128.pngbin9363 -> 0 bytes
-rw-r--r--src/gui/styles/images/up-16.pngbin814 -> 0 bytes
-rw-r--r--src/gui/styles/images/up-32.pngbin1798 -> 0 bytes
-rw-r--r--src/gui/styles/images/viewdetailed-128.pngbin4743 -> 0 bytes
-rw-r--r--src/gui/styles/images/viewdetailed-16.pngbin499 -> 0 bytes
-rw-r--r--src/gui/styles/images/viewdetailed-32.pngbin1092 -> 0 bytes
-rw-r--r--src/gui/styles/images/viewlist-128.pngbin4069 -> 0 bytes
-rw-r--r--src/gui/styles/images/viewlist-16.pngbin490 -> 0 bytes
-rw-r--r--src/gui/styles/images/viewlist-32.pngbin1006 -> 0 bytes
-rw-r--r--src/gui/styles/qcdestyle.cpp305
-rw-r--r--src/gui/styles/qcdestyle.h82
-rw-r--r--src/gui/styles/qcleanlooksstyle.cpp4466
-rw-r--r--src/gui/styles/qcleanlooksstyle.h114
-rw-r--r--src/gui/styles/qcleanlooksstyle_p.h80
-rw-r--r--src/gui/styles/qcommonstyle.cpp6085
-rw-r--r--src/gui/styles/qcommonstyle.h109
-rw-r--r--src/gui/styles/qcommonstyle_p.h113
-rw-r--r--src/gui/styles/qcommonstylepixmaps_p.h186
-rw-r--r--src/gui/styles/qdrawutil.cpp1053
-rw-r--r--src/gui/styles/qdrawutil.h175
-rw-r--r--src/gui/styles/qgtkpainter.cpp721
-rw-r--r--src/gui/styles/qgtkpainter_p.h129
-rw-r--r--src/gui/styles/qgtkstyle.cpp3563
-rw-r--r--src/gui/styles/qgtkstyle.h128
-rw-r--r--src/gui/styles/qgtkstyle_p.cpp1146
-rw-r--r--src/gui/styles/qgtkstyle_p.h531
-rw-r--r--src/gui/styles/qmacstyle.qdoc247
-rw-r--r--src/gui/styles/qmacstyle_mac.h148
-rw-r--r--src/gui/styles/qmacstyle_mac.mm6042
-rw-r--r--src/gui/styles/qmacstyle_mac_p.h241
-rw-r--r--src/gui/styles/qmacstylepixmaps_mac_p.h72
-rw-r--r--src/gui/styles/qmotifstyle.cpp2721
-rw-r--r--src/gui/styles/qmotifstyle.h128
-rw-r--r--src/gui/styles/qmotifstyle_p.h82
-rw-r--r--src/gui/styles/qplastiquestyle.cpp6011
-rw-r--r--src/gui/styles/qplastiquestyle.h119
-rw-r--r--src/gui/styles/qproxystyle.cpp420
-rw-r--r--src/gui/styles/qproxystyle.h114
-rw-r--r--src/gui/styles/qproxystyle_p.h79
-rw-r--r--src/gui/styles/qs60style.cpp3618
-rw-r--r--src/gui/styles/qs60style.h118
-rw-r--r--src/gui/styles/qs60style_p.h638
-rw-r--r--src/gui/styles/qs60style_s60.cpp1591
-rw-r--r--src/gui/styles/qs60style_simulated.cpp457
-rw-r--r--src/gui/styles/qs60style_stub.cpp131
-rw-r--r--src/gui/styles/qstyle.cpp2459
-rw-r--r--src/gui/styles/qstyle.h889
-rw-r--r--src/gui/styles/qstyle.qrc135
-rw-r--r--src/gui/styles/qstyle_p.h108
-rw-r--r--src/gui/styles/qstyle_s60.qrc137
-rw-r--r--src/gui/styles/qstyle_s60_simulated.qrc6
-rw-r--r--src/gui/styles/qstyle_wince.qrc97
-rw-r--r--src/gui/styles/qstylefactory.cpp271
-rw-r--r--src/gui/styles/qstylefactory.h66
-rw-r--r--src/gui/styles/qstylehelper.cpp378
-rw-r--r--src/gui/styles/qstylehelper_p.h89
-rw-r--r--src/gui/styles/qstyleoption.cpp5508
-rw-r--r--src/gui/styles/qstyleoption.h970
-rw-r--r--src/gui/styles/qstylepainter.cpp176
-rw-r--r--src/gui/styles/qstylepainter.h112
-rw-r--r--src/gui/styles/qstyleplugin.cpp115
-rw-r--r--src/gui/styles/qstyleplugin.h81
-rw-r--r--src/gui/styles/qstylesheetstyle.cpp5898
-rw-r--r--src/gui/styles/qstylesheetstyle_default.cpp512
-rw-r--r--src/gui/styles/qstylesheetstyle_p.h204
-rw-r--r--src/gui/styles/qwindowscestyle.cpp2429
-rw-r--r--src/gui/styles/qwindowscestyle.h103
-rw-r--r--src/gui/styles/qwindowscestyle_p.h118
-rw-r--r--src/gui/styles/qwindowsmobilestyle.cpp7283
-rw-r--r--src/gui/styles/qwindowsmobilestyle.h116
-rw-r--r--src/gui/styles/qwindowsmobilestyle_p.h136
-rw-r--r--src/gui/styles/qwindowsstyle.cpp3392
-rw-r--r--src/gui/styles/qwindowsstyle.h111
-rw-r--r--src/gui/styles/qwindowsstyle_p.h106
-rw-r--r--src/gui/styles/qwindowsvistastyle.cpp2670
-rw-r--r--src/gui/styles/qwindowsvistastyle.h108
-rw-r--r--src/gui/styles/qwindowsvistastyle_p.h220
-rw-r--r--src/gui/styles/qwindowsxpstyle.cpp4271
-rw-r--r--src/gui/styles/qwindowsxpstyle.h107
-rw-r--r--src/gui/styles/qwindowsxpstyle_p.h356
-rw-r--r--src/gui/styles/styles.pri194
-rw-r--r--src/gui/symbian/images/blank.pngbin91 -> 0 bytes
-rw-r--r--src/gui/symbian/images/busy12.pngbin253 -> 0 bytes
-rw-r--r--src/gui/symbian/images/busy3.pngbin251 -> 0 bytes
-rw-r--r--src/gui/symbian/images/busy6.pngbin253 -> 0 bytes
-rw-r--r--src/gui/symbian/images/busy9.pngbin255 -> 0 bytes
-rw-r--r--src/gui/symbian/images/closehand.pngbin190 -> 0 bytes
-rw-r--r--src/gui/symbian/images/cross.pngbin145 -> 0 bytes
-rw-r--r--src/gui/symbian/images/forbidden.pngbin256 -> 0 bytes
-rw-r--r--src/gui/symbian/images/handpoint.pngbin230 -> 0 bytes
-rw-r--r--src/gui/symbian/images/ibeam.pngbin176 -> 0 bytes
-rw-r--r--src/gui/symbian/images/openhand.pngbin201 -> 0 bytes
-rw-r--r--src/gui/symbian/images/pointer.pngbin222 -> 0 bytes
-rw-r--r--src/gui/symbian/images/sizeall.pngbin188 -> 0 bytes
-rw-r--r--src/gui/symbian/images/sizebdiag.pngbin192 -> 0 bytes
-rw-r--r--src/gui/symbian/images/sizefdiag.pngbin197 -> 0 bytes
-rw-r--r--src/gui/symbian/images/sizehor.pngbin175 -> 0 bytes
-rw-r--r--src/gui/symbian/images/sizever.pngbin171 -> 0 bytes
-rw-r--r--src/gui/symbian/images/splith.pngbin206 -> 0 bytes
-rw-r--r--src/gui/symbian/images/splitv.pngbin205 -> 0 bytes
-rw-r--r--src/gui/symbian/images/uparrow.pngbin157 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait1.pngbin219 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait10.pngbin220 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait11.pngbin220 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait12.pngbin213 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait2.pngbin219 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait3.pngbin210 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait4.pngbin215 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait5.pngbin217 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait6.pngbin213 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait7.pngbin215 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait8.pngbin217 -> 0 bytes
-rw-r--r--src/gui/symbian/images/wait9.pngbin209 -> 0 bytes
-rw-r--r--src/gui/symbian/images/whatsthis.pngbin254 -> 0 bytes
-rw-r--r--src/gui/symbian/qsymbianevent.cpp176
-rw-r--r--src/gui/symbian/qsymbianevent.h108
-rw-r--r--src/gui/symbian/symbianresources.qrc37
-rw-r--r--src/gui/to_be_moved/qdnd.cpp491
-rw-r--r--src/gui/to_be_moved/qdnd_p.h336
-rw-r--r--src/gui/to_be_moved/qdnd_qpa.cpp426
-rw-r--r--src/gui/to_be_moved/qdrag.cpp359
-rw-r--r--src/gui/to_be_moved/qdrag.h105
-rw-r--r--src/gui/to_be_moved/qlinecontrol.cpp1833
-rw-r--r--src/gui/to_be_moved/qlinecontrol_p.h456
-rw-r--r--src/gui/to_be_moved/qshortcut.cpp407
-rw-r--r--src/gui/to_be_moved/qshortcut.h107
-rw-r--r--src/gui/to_be_moved/qshortcutmap.cpp897
-rw-r--r--src/gui/to_be_moved/qshortcutmap_p.h123
-rw-r--r--src/gui/to_be_moved/qtextcontrol.cpp3148
-rw-r--r--src/gui/to_be_moved/qtextcontrol_p.h307
-rw-r--r--src/gui/to_be_moved/qtextcontrol_p_p.h238
-rw-r--r--src/gui/to_be_moved/to_be_moved.pri17
-rw-r--r--src/gui/util/qcompleter.cpp1833
-rw-r--r--src/gui/util/qcompleter.h171
-rw-r--r--src/gui/util/qcompleter_p.h264
-rw-r--r--src/gui/util/qflickgesture.cpp715
-rw-r--r--src/gui/util/qflickgesture_p.h113
-rw-r--r--src/gui/util/qscroller.cpp2059
-rw-r--r--src/gui/util/qscroller.h155
-rw-r--r--src/gui/util/qscroller_mac.mm71
-rw-r--r--src/gui/util/qscroller_p.h209
-rw-r--r--src/gui/util/qscrollerproperties.cpp393
-rw-r--r--src/gui/util/qscrollerproperties.h140
-rw-r--r--src/gui/util/qscrollerproperties_p.h94
-rw-r--r--src/gui/util/qsystemtrayicon.cpp674
-rw-r--r--src/gui/util/qsystemtrayicon.h132
-rw-r--r--src/gui/util/qsystemtrayicon_mac.mm578
-rw-r--r--src/gui/util/qsystemtrayicon_p.h186
-rw-r--r--src/gui/util/qsystemtrayicon_qpa.cpp96
-rw-r--r--src/gui/util/qsystemtrayicon_win.cpp524
-rw-r--r--src/gui/util/qsystemtrayicon_wince.cpp293
-rw-r--r--src/gui/util/qsystemtrayicon_x11.cpp401
-rw-r--r--src/gui/util/qundogroup.cpp499
-rw-r--r--src/gui/util/qundogroup.h110
-rw-r--r--src/gui/util/qundostack.cpp1127
-rw-r--r--src/gui/util/qundostack.h158
-rw-r--r--src/gui/util/qundostack_p.h111
-rw-r--r--src/gui/util/qundoview.cpp476
-rw-r--r--src/gui/util/qundoview.h102
-rw-r--r--src/gui/util/util.pri69
-rw-r--r--src/gui/widgets/qabstractbutton.cpp1470
-rw-r--r--src/gui/widgets/qabstractbutton.h180
-rw-r--r--src/gui/widgets/qabstractbutton_p.h110
-rw-r--r--src/gui/widgets/qabstractscrollarea.cpp1506
-rw-r--r--src/gui/widgets/qabstractscrollarea.h144
-rw-r--r--src/gui/widgets/qabstractscrollarea_p.h146
-rw-r--r--src/gui/widgets/qabstractslider.cpp1001
-rw-r--r--src/gui/widgets/qabstractslider.h184
-rw-r--r--src/gui/widgets/qabstractslider_p.h147
-rw-r--r--src/gui/widgets/qabstractspinbox.cpp2122
-rw-r--r--src/gui/widgets/qabstractspinbox.h181
-rw-r--r--src/gui/widgets/qabstractspinbox_p.h170
-rw-r--r--src/gui/widgets/qbuttongroup.cpp269
-rw-r--r--src/gui/widgets/qbuttongroup.h112
-rw-r--r--src/gui/widgets/qcalendartextnavigator_p.h112
-rw-r--r--src/gui/widgets/qcalendarwidget.cpp3104
-rw-r--r--src/gui/widgets/qcalendarwidget.h204
-rw-r--r--src/gui/widgets/qcheckbox.cpp447
-rw-r--r--src/gui/widgets/qcheckbox.h114
-rw-r--r--src/gui/widgets/qcocoamenu_mac.mm244
-rw-r--r--src/gui/widgets/qcocoamenu_mac_p.h82
-rw-r--r--src/gui/widgets/qcocoatoolbardelegate_mac.mm153
-rw-r--r--src/gui/widgets/qcocoatoolbardelegate_mac_p.h71
-rw-r--r--src/gui/widgets/qcombobox.cpp3365
-rw-r--r--src/gui/widgets/qcombobox.h339
-rw-r--r--src/gui/widgets/qcombobox_p.h421
-rw-r--r--src/gui/widgets/qcommandlinkbutton.cpp410
-rw-r--r--src/gui/widgets/qcommandlinkbutton.h85
-rw-r--r--src/gui/widgets/qdatetimeedit.cpp2642
-rw-r--r--src/gui/widgets/qdatetimeedit.h230
-rw-r--r--src/gui/widgets/qdatetimeedit_p.h183
-rw-r--r--src/gui/widgets/qdial.cpp546
-rw-r--r--src/gui/widgets/qdial.h122
-rw-r--r--src/gui/widgets/qdialogbuttonbox.cpp1285
-rw-r--r--src/gui/widgets/qdialogbuttonbox.h168
-rw-r--r--src/gui/widgets/qdockarealayout.cpp3334
-rw-r--r--src/gui/widgets/qdockarealayout_p.h308
-rw-r--r--src/gui/widgets/qdockwidget.cpp1606
-rw-r--r--src/gui/widgets/qdockwidget.h146
-rw-r--r--src/gui/widgets/qdockwidget_p.h207
-rw-r--r--src/gui/widgets/qeffects.cpp613
-rw-r--r--src/gui/widgets/qeffects_p.h84
-rw-r--r--src/gui/widgets/qfocusframe.cpp339
-rw-r--r--src/gui/widgets/qfocusframe.h82
-rw-r--r--src/gui/widgets/qfontcombobox.cpp474
-rw-r--r--src/gui/widgets/qfontcombobox.h112
-rw-r--r--src/gui/widgets/qframe.cpp564
-rw-r--r--src/gui/widgets/qframe.h148
-rw-r--r--src/gui/widgets/qframe_p.h84
-rw-r--r--src/gui/widgets/qgroupbox.cpp781
-rw-r--r--src/gui/widgets/qgroupbox.h122
-rw-r--r--src/gui/widgets/qlabel.cpp1718
-rw-r--r--src/gui/widgets/qlabel.h182
-rw-r--r--src/gui/widgets/qlabel_p.h153
-rw-r--r--src/gui/widgets/qlcdnumber.cpp1312
-rw-r--r--src/gui/widgets/qlcdnumber.h144
-rw-r--r--src/gui/widgets/qlineedit.cpp2360
-rw-r--r--src/gui/widgets/qlineedit.h299
-rw-r--r--src/gui/widgets/qlineedit_p.cpp292
-rw-r--r--src/gui/widgets/qlineedit_p.h156
-rw-r--r--src/gui/widgets/qmaccocoaviewcontainer_mac.h73
-rw-r--r--src/gui/widgets/qmaccocoaviewcontainer_mac.mm187
-rw-r--r--src/gui/widgets/qmacnativewidget_mac.h74
-rw-r--r--src/gui/widgets/qmacnativewidget_mac.mm133
-rw-r--r--src/gui/widgets/qmainwindow.cpp1686
-rw-r--r--src/gui/widgets/qmainwindow.h219
-rw-r--r--src/gui/widgets/qmainwindowlayout.cpp2017
-rw-r--r--src/gui/widgets/qmainwindowlayout_mac.mm607
-rw-r--r--src/gui/widgets/qmainwindowlayout_p.h357
-rw-r--r--src/gui/widgets/qmdiarea.cpp2678
-rw-r--r--src/gui/widgets/qmdiarea.h179
-rw-r--r--src/gui/widgets/qmdiarea_p.h285
-rw-r--r--src/gui/widgets/qmdisubwindow.cpp3547
-rw-r--r--src/gui/widgets/qmdisubwindow.h159
-rw-r--r--src/gui/widgets/qmdisubwindow_p.h348
-rw-r--r--src/gui/widgets/qmenu.cpp3525
-rw-r--r--src/gui/widgets/qmenu.h434
-rw-r--r--src/gui/widgets/qmenu_mac.mm2217
-rw-r--r--src/gui/widgets/qmenu_p.h393
-rw-r--r--src/gui/widgets/qmenu_symbian.cpp464
-rw-r--r--src/gui/widgets/qmenu_wince.cpp668
-rw-r--r--src/gui/widgets/qmenu_wince.rc231
-rw-r--r--src/gui/widgets/qmenu_wince_resource_p.h94
-rw-r--r--src/gui/widgets/qmenubar.cpp2508
-rw-r--r--src/gui/widgets/qmenubar.h367
-rw-r--r--src/gui/widgets/qmenubar_p.h283
-rw-r--r--src/gui/widgets/qmenudata.cpp96
-rw-r--r--src/gui/widgets/qmenudata.h80
-rw-r--r--src/gui/widgets/qplaintextedit.cpp2992
-rw-r--r--src/gui/widgets/qplaintextedit.h329
-rw-r--r--src/gui/widgets/qplaintextedit_p.h187
-rw-r--r--src/gui/widgets/qprintpreviewwidget.cpp844
-rw-r--r--src/gui/widgets/qprintpreviewwidget.h127
-rw-r--r--src/gui/widgets/qprogressbar.cpp595
-rw-r--r--src/gui/widgets/qprogressbar.h132
-rw-r--r--src/gui/widgets/qpushbutton.cpp784
-rw-r--r--src/gui/widgets/qpushbutton.h127
-rw-r--r--src/gui/widgets/qpushbutton_p.h90
-rw-r--r--src/gui/widgets/qradiobutton.cpp296
-rw-r--r--src/gui/widgets/qradiobutton.h89
-rw-r--r--src/gui/widgets/qrubberband.cpp336
-rw-r--r--src/gui/widgets/qrubberband.h104
-rw-r--r--src/gui/widgets/qscrollarea.cpp522
-rw-r--r--src/gui/widgets/qscrollarea.h101
-rw-r--r--src/gui/widgets/qscrollarea_p.h81
-rw-r--r--src/gui/widgets/qscrollbar.cpp764
-rw-r--r--src/gui/widgets/qscrollbar.h104
-rw-r--r--src/gui/widgets/qsizegrip.cpp570
-rw-r--r--src/gui/widgets/qsizegrip.h95
-rw-r--r--src/gui/widgets/qslider.cpp666
-rw-r--r--src/gui/widgets/qslider.h134
-rw-r--r--src/gui/widgets/qspinbox.cpp1327
-rw-r--r--src/gui/widgets/qspinbox.h188
-rw-r--r--src/gui/widgets/qsplashscreen.cpp330
-rw-r--r--src/gui/widgets/qsplashscreen.h99
-rw-r--r--src/gui/widgets/qsplitter.cpp1877
-rw-r--r--src/gui/widgets/qsplitter.h192
-rw-r--r--src/gui/widgets/qsplitter_p.h149
-rw-r--r--src/gui/widgets/qstackedwidget.cpp338
-rw-r--r--src/gui/widgets/qstackedwidget.h100
-rw-r--r--src/gui/widgets/qstatusbar.cpp847
-rw-r--r--src/gui/widgets/qstatusbar.h116
-rw-r--r--src/gui/widgets/qtabbar.cpp2376
-rw-r--r--src/gui/widgets/qtabbar.h226
-rw-r--r--src/gui/widgets/qtabbar_p.h263
-rw-r--r--src/gui/widgets/qtabwidget.cpp1516
-rw-r--r--src/gui/widgets/qtabwidget.h253
-rw-r--r--src/gui/widgets/qtextbrowser.cpp1275
-rw-r--r--src/gui/widgets/qtextbrowser.h140
-rw-r--r--src/gui/widgets/qtextedit.cpp2811
-rw-r--r--src/gui/widgets/qtextedit.h431
-rw-r--r--src/gui/widgets/qtextedit_p.h141
-rw-r--r--src/gui/widgets/qtoolbar.cpp1349
-rw-r--r--src/gui/widgets/qtoolbar.h188
-rw-r--r--src/gui/widgets/qtoolbar_p.h135
-rw-r--r--src/gui/widgets/qtoolbararealayout.cpp1391
-rw-r--r--src/gui/widgets/qtoolbararealayout_p.h248
-rw-r--r--src/gui/widgets/qtoolbarextension.cpp92
-rw-r--r--src/gui/widgets/qtoolbarextension_p.h80
-rw-r--r--src/gui/widgets/qtoolbarlayout.cpp742
-rw-r--r--src/gui/widgets/qtoolbarlayout_p.h134
-rw-r--r--src/gui/widgets/qtoolbarseparator.cpp91
-rw-r--r--src/gui/widgets/qtoolbarseparator_p.h88
-rw-r--r--src/gui/widgets/qtoolbox.cpp822
-rw-r--r--src/gui/widgets/qtoolbox.h148
-rw-r--r--src/gui/widgets/qtoolbutton.cpp1260
-rw-r--r--src/gui/widgets/qtoolbutton.h199
-rw-r--r--src/gui/widgets/qwidgetanimator.cpp117
-rw-r--r--src/gui/widgets/qwidgetanimator_p.h89
-rw-r--r--src/gui/widgets/qwidgetresizehandler.cpp547
-rw-r--r--src/gui/widgets/qwidgetresizehandler_p.h141
-rw-r--r--src/gui/widgets/qworkspace.cpp3377
-rw-r--r--src/gui/widgets/qworkspace.h137
-rw-r--r--src/gui/widgets/widgets.pri165
955 files changed, 2 insertions, 503264 deletions
diff --git a/src/gui/QtGui.dynlist b/src/gui/QtGui.dynlist
deleted file mode 100644
index ea47f598a7..0000000000
--- a/src/gui/QtGui.dynlist
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- extern "C++" {
- "qt_x11ft_convert_pattern(_FcPattern*, QByteArray*, int*, bool*)";
- "QApplication::x11ClientMessage(QWidget*, _XEvent*, bool)";
- "QApplication::notify(QObject*, QEvent*)";
- "QApplication::qwsEventFilter(QWSEvent*)";
- };
-};
diff --git a/src/gui/accessible/accessible.pri b/src/gui/accessible/accessible.pri
deleted file mode 100644
index 66a84bcce6..0000000000
--- a/src/gui/accessible/accessible.pri
+++ /dev/null
@@ -1,25 +0,0 @@
-# Qt accessibility module
-
-contains(QT_CONFIG, accessibility) {
- HEADERS += accessible/qaccessible.h \
- accessible/qaccessible2.h \
- accessible/qaccessibleobject.h \
- accessible/qaccessiblewidget.h \
- accessible/qaccessibleplugin.h
- SOURCES += accessible/qaccessible.cpp \
- accessible/qaccessible2.cpp \
- accessible/qaccessibleobject.cpp \
- accessible/qaccessiblewidget.cpp \
- accessible/qaccessibleplugin.cpp
-
- mac:!qpa {
- HEADERS += accessible/qaccessible_mac_p.h
- OBJECTIVE_SOURCES += accessible/qaccessible_mac.mm \
- accessible/qaccessible_mac_cocoa.mm
- } else:win32 {
- SOURCES += accessible/qaccessible_win.cpp
- } else {
- HEADERS += accessible/qaccessiblebridge.h
- SOURCES += accessible/qaccessible_unix.cpp accessible/qaccessiblebridge.cpp
- }
-}
diff --git a/src/gui/accessible/qaccessible.cpp b/src/gui/accessible/qaccessible.cpp
deleted file mode 100644
index abe68f8108..0000000000
--- a/src/gui/accessible/qaccessible.cpp
+++ /dev/null
@@ -1,1094 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessible.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qaccessibleplugin.h"
-#include "qaccessiblewidget.h"
-#include "qapplication.h"
-#include "qhash.h"
-#include "qmetaobject.h"
-#include "qmutex.h"
-#include <private/qfactoryloader_p.h>
-
-#include "qwidget.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAccessible
- \brief The QAccessible class provides enums and static functions
- relating to accessibility.
-
- \ingroup accessibility
-
-
- Accessible applications can be used by people who are not able to
- use applications by conventional means.
-
- The functions in this class are used for communication between
- accessible applications (also called AT Servers) and
- accessibility tools (AT Clients), such as screen readers and
- braille displays. Clients and servers communicate in the following way:
-
- \list
- \o \e{AT Servers} notify the clients about events through calls to the
- updateAccessibility() function.
-
- \o \e{AT Clients} request information about the objects in the server.
- The QAccessibleInterface class is the core interface, and encapsulates
- this information in a pure virtual API. Implementations of the interface
- are provided by Qt through the queryAccessibleInterface() API.
- \endlist
-
- The communication between servers and clients is initialized by
- the setRootObject() function. Function pointers can be installed
- to replace or extend the default behavior of the static functions
- in QAccessible.
-
- Qt supports Microsoft Active Accessibility (MSAA), Mac OS X
- Accessibility, and the Unix/X11 AT-SPI standard. Other backends
- can be supported using QAccessibleBridge.
-
- In addition to QAccessible's static functions, Qt offers one
- generic interface, QAccessibleInterface, that can be used to wrap
- all widgets and objects (e.g., QPushButton). This single
- interface provides all the metadata necessary for the assistive
- technologies. Qt provides implementations of this interface for
- its built-in widgets as plugins.
-
- When you develop custom widgets, you can create custom subclasses
- of QAccessibleInterface and distribute them as plugins (using
- QAccessiblePlugin) or compile them into the application.
- Likewise, Qt's predefined accessibility support can be built as
- plugin (the default) or directly into the Qt library. The main
- advantage of using plugins is that the accessibility classes are
- only loaded into memory if they are actually used; they don't
- slow down the common case where no assistive technology is being
- used.
-
- Qt also includes two convenience classes, QAccessibleObject and
- QAccessibleWidget, that inherit from QAccessibleInterface and
- provide the lowest common denominator of metadata (e.g., widget
- geometry, window title, basic help text). You can use them as
- base classes when wrapping your custom QObject or QWidget
- subclasses.
-
- \sa QAccessibleInterface
-*/
-
-/*!
- \enum QAccessible::Action
-
- This enum describes the possible types of action that can occur.
-
- \value DefaultAction
- \value Press
- \value SetFocus
- \value Increase
- \value Decrease
- \value Accept
- \value Cancel
- \value Select
- \value ClearSelection
- \value RemoveSelection
- \value ExtendSelection
- \value AddToSelection
-
- \value FirstStandardAction
- \value LastStandardAction
-*/
-
-/*!
- \enum QAccessible::Method
-
- This enum describes the possible types of methods that can be
- invoked on an accessible object.
-
- \value ListSupportedMethods
- \value SetCursorPosition
- \value GetCursorPosition
-
- \omitvalue ForegroundColor
- \omitvalue BackgroundColor
-
- \sa QAccessibleInterface::invokeMethod()
-*/
-
-/*!
- \fn QSet<Method> QAccessibleInterface::supportedMethods()
- \since 4.3
-
- Returns a QSet of \l{QAccessible::}{Method}s that are supported by this
- accessible interface.
-
- \sa QAccessible::Method invokeMethod()
-*/
-
-/*!
- \enum QAccessible::StateFlag
-
- This enum type defines bit flags that can be combined to indicate
- the state of an accessible object. The values are:
-
- \value Animated The object's appearance changes frequently.
- \value Busy The object cannot accept input at the moment.
- \value Checked The object's check box is checked.
- \value Collapsed The object is collapsed, e.g. a closed listview item, or an iconified window.
- \value DefaultButton The object represents the default button in a dialog.
- \value Expanded The object is expandable, and currently the children are visible.
- \value ExtSelectable The object supports extended selection.
- \value Focusable The object can receive focus. Only objects in the active window can receive focus.
- \value Focused The object has keyboard focus.
- \value HasPopup The object opens a popup.
- \value HotTracked The object's appearance is sensitive to the mouse cursor position.
- \value Invisible The object is not visible to the user.
- \value Linked The object is linked to another object, e.g. a hyperlink.
- \value Marqueed The object displays scrolling contents, e.g. a log view.
- \value Mixed The state of the object is not determined, e.g. a tri-state check box that is neither checked nor unchecked.
- \value Modal The object blocks input from other objects.
- \value Movable The object can be moved.
- \value MultiSelectable The object supports multiple selected items.
- \value Normal The normal state.
- \value Offscreen The object is clipped by the visible area. Objects that are off screen are also invisible.
- \value Pressed The object is pressed.
- \value Protected The object is password protected, e.g. a line edit for entering a Password.
- \value ReadOnly The object can usually be edited, but is explicitly set to read-only.
- \value Selectable The object is selectable.
- \value Selected The object is selected.
- \value SelfVoicing The object describes itself through speech or sound.
- \value Sizeable The object can be resized, e.g. top-level windows.
- \value Traversed The object is linked and has been visited.
- \value Unavailable The object is unavailable to the user, e.g. a disabled widget.
- \omitvalue Moveable
- \omitvalue HasInvokeExtension
-
- Implementations of QAccessibleInterface::state() return a combination
- of these flags.
-*/
-
-/*!
- \enum QAccessible::Event
-
- This enum type defines accessible event types.
-
- \value AcceleratorChanged
- \value Alert A system alert (e.g., a message from a QMessageBox)
- \value ContextHelpEnd Context help (QWhatsThis) for an object is finished.
- \value ContextHelpStart Context help (QWhatsThis) for an object is initiated.
- \value DefaultActionChanged The default QAccessible::Action for the accessible object changed
- \value DescriptionChanged The objects QAccessible::Description changed.
- \value DialogEnd A dialog (QDialog) is been hidden
- \value DialogStart A dialog (QDialog) has been set visible.
- \value DragDropEnd A Drag & Drop operation is about to finished.
- \value DragDropStart A Drag & Drop operation is about to be initiated.
- \value Focus An object has gained keyboard focus.
- \value ForegroundChanged A window has been activated (i.e., a new window has gained focus on the desktop)
- \value HelpChanged The QAccessible::Help text property of an object has changed
- \value LocationChanged An objects location on the screen changed
- \value MenuCommand A menu item is triggered.
- \value MenuEnd A menu has been closed (Qt uses PopupMenuEnd for all menus)
- \value MenuStart A menu has been opened on the menubar (Qt uses PopupMenuStart for all menus)
- \value NameChanged The QAccessible::Name property of an object has changed
- \value ObjectCreated A new object is created.
- \value ObjectDestroyed An object is deleted.
- \value ObjectHide An object is hidden (i.e., with QWidget::hide()). Any children the object that is hidden has do not send this event.
- It is not send when an object is hidden as it is being obcured by others.
- \value ObjectReorder A layout or item view has added, removed, or moved an object (Qt does not use this event).
- \value ObjectShow An object is displayed (i.e., with QWidget::show()).
- \value ParentChanged An objects parent object changed.
- \value PopupMenuEnd A popup menu has closed.
- \value PopupMenuStart A popupmenu has opened.
- \value ScrollingEnd A scrollbar scroll operation has ended (the mouse has released the slider handle)
- \value ScrollingStart A scrollbar scroll operation is about to start (i.e., the mouse has pressed on the slider handle)
- \value Selection The selection has changed in a menu or item view.
- \value SelectionAdd An item has been added to the selection in an item view.
- \value SelectionRemove An item has been removed from an item view selection.
- \value SelectionWithin Several changes to a selection has occurred in an item view.
- \value SoundPlayed A sound has been played by an object
- \value StateChanged The QAccessible::State of an object has changed.
- \value ValueChanged The QAccessible::Value of an object has changed.
-*/
-
-/*!
- \enum QAccessible::Role
-
- This enum defines the role of an accessible object. The roles are:
-
- \value AlertMessage An object that is used to alert the user.
- \value Animation An object that displays an animation.
- \value Application The application's main window.
- \value Assistant An object that provids interactive help.
- \value Border An object that represents a border.
- \value ButtonDropDown A button that drops down a list of items.
- \value ButtonDropGrid A button that drops down a grid.
- \value ButtonMenu A button that drops down a menu.
- \value Canvas An object that displays graphics that the user can interact with.
- \value Caret An object that represents the system caret (text cursor).
- \value Cell A cell in a table.
- \value Chart An object that displays a graphical representation of data.
- \value CheckBox An object that represents an option that can be checked or unchecked. Some options provide a "mixed" state, e.g. neither checked nor unchecked.
- \value Client The client area in a window.
- \value Clock A clock displaying time.
- \value Column A column of cells, usually within a table.
- \value ColumnHeader A header for a column of data.
- \value ComboBox A list of choices that the user can select from.
- \value Cursor An object that represents the mouse cursor.
- \value Dial An object that represents a dial or knob.
- \value Dialog A dialog box.
- \value Document A document window, usually in an MDI environment.
- \value EditableText Editable text
- \value Equation An object that represents a mathematical equation.
- \value Graphic A graphic or picture, e.g. an icon.
- \value Grip A grip that the user can drag to change the size of widgets.
- \value Grouping An object that represents a logical grouping of other objects.
- \value HelpBalloon An object that displays help in a separate, short lived window.
- \value HotkeyField A hotkey field that allows the user to enter a key sequence.
- \value Indicator An indicator that represents a current value or item.
- \value LayeredPane An object that can contain layered children, e.g. in a stack.
- \value Link A link to something else.
- \value List A list of items, from which the user can select one or more items.
- \value ListItem An item in a list of items.
- \value MenuBar A menu bar from which menus are opened by the user.
- \value MenuItem An item in a menu or menu bar.
- \value NoRole The object has no role. This usually indicates an invalid object.
- \value PageTab A page tab that the user can select to switch to a different page in a dialog.
- \value PageTabList A list of page tabs.
- \value Pane A generic container.
- \value PopupMenu A menu which lists options that the user can select to perform an action.
- \value ProgressBar The object displays the progress of an operation in progress.
- \value PropertyPage A property page where the user can change options and settings.
- \value PushButton A button.
- \value RadioButton An object that represents an option that is mutually exclusive with other options.
- \value Row A row of cells, usually within a table.
- \value RowHeader A header for a row of data.
- \value ScrollBar A scroll bar, which allows the user to scroll the visible area.
- \value Separator A separator that divides space into logical areas.
- \value Slider A slider that allows the user to select a value within a given range.
- \value Sound An object that represents a sound.
- \value SpinBox A spin box widget that allows the user to enter a value within a given range.
- \value Splitter A splitter distributing available space between its child widgets.
- \value StaticText Static text, such as labels for other widgets.
- \value StatusBar A status bar.
- \value Table A table representing data in a grid of rows and columns.
- \value TitleBar The title bar caption of a window.
- \value ToolBar A tool bar, which groups widgets that the user accesses frequently.
- \value ToolTip A tool tip which provides information about other objects.
- \value Tree A list of items in a tree structure.
- \value TreeItem An item in a tree structure.
- \value UserRole The first value to be used for user defined roles.
- \value Whitespace Blank space between other objects.
- \value Window A top level window.
-*/
-
-/*!
- \enum QAccessible::RelationFlag
-
- This enum type defines bit flags that can be combined to indicate
- the relationship between two accessible objects.
-
- \value Unrelated The objects are unrelated.
- \value Self The objects are the same.
- \value Ancestor The first object is a parent of the second object.
- \value Child The first object is a direct child of the second object.
- \value Descendent The first object is an indirect child of the second object.
- \value Sibling The objects are siblings.
-
- \value Up The first object is above the second object.
- \value Down The first object is below the second object.
- \value Left The first object is left of the second object.
- \value Right The first object is right of the second object.
- \value Covers The first object covers the second object.
- \value Covered The first object is covered by the second object.
-
- \value FocusChild The first object is the second object's focus child.
- \value Label The first object is the label of the second object.
- \value Labelled The first object is labelled by the second object.
- \value Controller The first object controls the second object.
- \value Controlled The first object is controlled by the second object.
-
- \omitvalue HierarchyMask
- \omitvalue GeometryMask
- \omitvalue LogicalMask
-
- Implementations of relationTo() return a combination of these flags.
- Some values are mutually exclusive.
-
- Implementations of navigate() can accept only one distinct value.
-*/
-
-/*!
- \enum QAccessible::Text
-
- This enum specifies string information that an accessible object
- returns.
-
- \value Name The name of the object. This can be used both
- as an identifier or a short description by
- accessible clients.
- \value Description A short text describing the object.
- \value Value The value of the object.
- \value Help A longer text giving information about how to use the object.
- \value Accelerator The keyboard shortcut that executes the object's default action.
- \value UserText The first value to be used for user defined text.
-*/
-
-/*!
- \fn QAccessibleInterface::~QAccessibleInterface()
-
- Destroys the object.
-*/
-
-/*!
- \fn void QAccessible::initialize()
- \internal
-*/
-
-/*!
- \fn void QAccessible::cleanup()
- \internal
-*/
-
-#ifndef QT_NO_LIBRARY
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QAccessibleFactoryInterface_iid, QLatin1String("/accessible")))
-#endif
-
-Q_GLOBAL_STATIC(QList<QAccessible::InterfaceFactory>, qAccessibleFactories)
-
-QAccessible::UpdateHandler QAccessible::updateHandler = 0;
-QAccessible::RootObjectHandler QAccessible::rootObjectHandler = 0;
-
-static bool accessibility_active = false;
-static bool cleanupAdded = false;
-static void qAccessibleCleanup()
-{
- qAccessibleFactories()->clear();
-}
-
-/*!
- \typedef QAccessible::InterfaceFactory
-
- This is a typedef for a pointer to a function with the following
- signature:
-
- \snippet doc/src/snippets/code/src_gui_accessible_qaccessible.cpp 1
-
- The function receives a QString and a QObject pointer, where the
- QString is the key identifying the interface. The QObject is used
- to pass on to the QAccessibleInterface so that it can hold a reference
- to it.
-
- If the key and the QObject does not have a corresponding
- QAccessibleInterface, a null-pointer will be returned.
-
- Installed factories are called by queryAccessibilityInterface() until
- one provides an interface.
-*/
-
-/*!
- \typedef QAccessible::UpdateHandler
-
- \internal
-
- A function pointer type. Use a function with this prototype to install
- your own update function.
-
- The function is called by updateAccessibility().
-*/
-
-/*!
- \typedef QAccessible::RootObjectHandler
-
- \internal
-
- A function pointer type. Use a function with this prototype to install
- your own root object handler.
-
- The function is called by setRootObject().
-*/
-
-/*!
- Installs the InterfaceFactory \a factory. The last factory added
- is the first one used by queryAccessibleInterface().
-*/
-void QAccessible::installFactory(InterfaceFactory factory)
-{
- if (!factory)
- return;
-
- if (!cleanupAdded) {
- qAddPostRoutine(qAccessibleCleanup);
- cleanupAdded = true;
- }
- if (qAccessibleFactories()->contains(factory))
- return;
- qAccessibleFactories()->append(factory);
-}
-
-/*!
- Removes \a factory from the list of installed InterfaceFactories.
-*/
-void QAccessible::removeFactory(InterfaceFactory factory)
-{
- qAccessibleFactories()->removeAll(factory);
-}
-
-/*!
- \internal
-
- Installs the given \a handler as the function to be used by
- updateAccessibility(), and returns the previously installed
- handler.
-*/
-QAccessible::UpdateHandler QAccessible::installUpdateHandler(UpdateHandler handler)
-{
- UpdateHandler old = updateHandler;
- updateHandler = handler;
- return old;
-}
-
-/*!
- Installs the given \a handler as the function to be used by setRootObject(),
- and returns the previously installed handler.
-*/
-QAccessible::RootObjectHandler QAccessible::installRootObjectHandler(RootObjectHandler handler)
-{
- RootObjectHandler old = rootObjectHandler;
- rootObjectHandler = handler;
- return old;
-}
-
-/*!
- If a QAccessibleInterface implementation exists for the given \a object,
- this function returns a pointer to the implementation; otherwise it
- returns 0.
-
- The function calls all installed factory functions (from most
- recently installed to least recently installed) until one is found
- that provides an interface for the class of \a object. If no
- factory can provide an accessibility implementation for the class
- the function loads installed accessibility plugins, and tests if
- any of the plugins can provide the implementation.
-
- If no implementation for the object's class is available, the
- function tries to find an implementation for the object's parent
- class, using the above strategy.
-
- \warning The caller is responsible for deleting the returned
- interface after use.
-*/
-QAccessibleInterface *QAccessible::queryAccessibleInterface(QObject *object)
-{
- accessibility_active = true;
- QAccessibleInterface *iface = 0;
- if (!object)
- return 0;
-
- QEvent e(QEvent::AccessibilityPrepare);
- QApplication::sendEvent(object, &e);
-
- const QMetaObject *mo = object->metaObject();
- while (mo) {
- const QLatin1String cn(mo->className());
- for (int i = qAccessibleFactories()->count(); i > 0; --i) {
- InterfaceFactory factory = qAccessibleFactories()->at(i - 1);
- iface = factory(cn, object);
- if (iface)
- return iface;
- }
-#ifndef QT_NO_LIBRARY
- QAccessibleFactoryInterface *factory = qobject_cast<QAccessibleFactoryInterface*>(loader()->instance(cn));
- if (factory) {
- iface = factory->create(cn, object);
- if (iface)
- return iface;
- }
-#endif
- mo = mo->superClass();
- }
-
- QWidget *widget = qobject_cast<QWidget*>(object);
- if (widget)
- return new QAccessibleWidget(widget);
- else if (object == qApp)
- return new QAccessibleApplication();
-
- return 0;
-}
-
-/*!
- Returns true if an accessibility implementation has been requested
- during the runtime of the application; otherwise returns false.
-
- Use this function to prevent potentially expensive notifications via
- updateAccessibility().
-*/
-bool QAccessible::isActive()
-{
- return accessibility_active;
-}
-
-/*!
- \fn void QAccessible::setRootObject(QObject *object)
-
- Sets the root accessible object of this application to \a object.
- All other accessible objects in the application can be reached by the
- client using object navigation.
-
- You should never need to call this function. Qt sets the QApplication
- object as the root object immediately before the event loop is entered
- in QApplication::exec().
-
- Use QAccessible::installRootObjectHandler() to redirect the function
- call to a customized handler function.
-
- \sa queryAccessibleInterface()
-*/
-
-/*!
- \fn void QAccessible::updateAccessibility(QObject *object, int child, Event reason)
-
- Notifies accessibility clients about a change in \a object's
- accessibility information.
-
- \a reason specifies the cause of the change, for example,
- \c ValueChange when the position of a slider has been changed. \a
- child is the (1-based) index of the child element that has changed.
- When \a child is 0, the object itself has changed.
-
- Call this function whenever the state of your accessible object or
- one of its sub-elements has been changed either programmatically
- (e.g. by calling QLabel::setText()) or by user interaction.
-
- If there are no accessibility tools listening to this event, the
- performance penalty for calling this function is small, but if determining
- the parameters of the call is expensive you can test isActive() to
- avoid unnecessary computations.
-*/
-
-
-/*!
- \class QAccessibleInterface
- \brief The QAccessibleInterface class defines an interface that exposes information
- about accessible objects.
-
- \ingroup accessibility
-
- Accessibility tools (also called AT Clients), such as screen readers
- or braille displays, require high-level information about
- accessible objects in an application. Accessible objects provide
- specialized input and output methods, making it possible for users
- to use accessibility tools with enabled applications (AT Servers).
-
- Every element that the user needs to interact with or react to is
- an accessible object, and should provide this information. These
- are mainly visual objects, such as widgets and widget elements, but
- can also be content, such as sounds.
-
- The AT client uses three basic concepts to acquire information
- about any accessible object in an application:
- \list
- \i \e Properties The client can read information about
- accessible objects. In some cases the client can also modify these
- properties; such as text in a line edit.
- \i \e Actions The client can invoke actions like pressing a button
- or .
- \i \e{Relationships and Navigation} The client can traverse from one
- accessible object to another, using the relationships between objects.
- \endlist
-
- The QAccessibleInterface defines the API for these three concepts.
-
- \section1 Relationships and Navigation
-
- The functions childCount() and indexOfChild() return the number of
- children of an accessible object and the index a child object has
- in its parent. The childAt() function returns the index of a child
- at a given position.
-
- The relationTo() function provides information about how two
- different objects relate to each other, and navigate() allows
- traversing from one object to another object with a given
- relationship.
-
- \section1 Properties
-
- The central property of an accessible objects is what role() it
- has. Different objects can have the same role, e.g. both the "Add
- line" element in a scroll bar and the \c OK button in a dialog have
- the same role, "button". The role implies what kind of
- interaction the user can perform with the user interface element.
-
- An object's state() property is a combination of different state
- flags and can describe both how the object's state differs from a
- "normal" state, e.g. it might be unavailable, and also how it
- behaves, e.g. it might be selectable.
-
- The text() property provides textual information about the object.
- An object usually has a name, but can provide extended information
- such as a description, help text, or information about any
- keyboard accelerators it provides. Some objects allow changing the
- text() property through the setText() function, but this
- information is in most cases read-only.
-
- The rect() property provides information about the geometry of an
- accessible object. This information is usually only available for
- visual objects.
-
- \section1 Actions and Selection
-
- To enable the user to interact with an accessible object the
- object must expose information about the actions that it can
- perform. userActionCount() returns the number of actions supported by
- an accessible object, and actionText() returns textual information
- about those actions. doAction() invokes an action.
-
- Objects that support selections can define actions to change the selection.
-
- \section2 Objects and children
-
- A QAccessibleInterface provides information about the accessible
- object, and can also provide information for the children of that
- object if those children don't provide a QAccessibleInterface
- implementation themselves. This is practical if the object has
- many similar children (e.g. items in a list view), or if the
- children are an integral part of the object itself, for example, the
- different sections in a scroll bar.
-
- If an accessible object provides information about its children
- through one QAccessibleInterface, the children are referenced
- using indexes. The index is 1-based for the children, i.e. 0
- refers to the object itself, 1 to the first child, 2 to the second
- child, and so on.
-
- All functions in QAccessibleInterface that take a child index
- relate to the object itself if the index is 0, or to the child
- specified. If a child provides its own interface implementation
- (which can be retrieved through navigation) asking the parent for
- information about that child will usually not succeed.
-
- \sa QAccessible
-*/
-
-/*!
- \fn bool QAccessibleInterface::isValid() const
-
- Returns true if all the data necessary to use this interface
- implementation is valid (e.g. all pointers are non-null);
- otherwise returns false.
-
- \sa object()
-*/
-
-/*!
- \fn QObject *QAccessibleInterface::object() const
-
- Returns a pointer to the QObject this interface implementation provides
- information for.
-
- \sa isValid()
-*/
-
-/*!
- \fn int QAccessibleInterface::childCount() const
-
- Returns the number of children that belong to this object. A child
- can provide accessibility information on its own (e.g. a child
- widget), or be a sub-element of this accessible object.
-
- All objects provide this information.
-
- \sa indexOfChild()
-*/
-
-/*!
- \fn int QAccessibleInterface::indexOfChild(const QAccessibleInterface *child) const
-
- Returns the 1-based index of the object \a child in this object's
- children list, or -1 if \a child is not a child of this object. 0
- is not a possible return value.
-
- All objects provide this information about their children.
-
- \sa childCount()
-*/
-
-/*!
- \fn QAccessible::Relation QAccessibleInterface::relationTo(int child,
-const QAccessibleInterface *other, int otherChild) const
-
- Returns the relationship between this object's \a child and the \a
- other object's \a otherChild. If \a child is 0 the object's own relation
- is returned.
-
- The returned value indicates the relation of the called object to
- the \a other object, e.g. if this object is a child of \a other
- the return value will be \c Child.
-
- The return value is a combination of the bit flags in the
- QAccessible::Relation enumeration.
-
- All objects provide this information.
-
- \sa indexOfChild(), navigate()
-*/
-
-/*!
- \fn int QAccessibleInterface::childAt(int x, int y) const
-
- Returns the 1-based index of the child that contains the screen
- coordinates (\a x, \a y). This function returns 0 if the point is
- positioned on the object itself. If the tested point is outside
- the boundaries of the object this function returns -1.
-
- This function is only relyable for visible objects (invisible
- object might not be laid out correctly).
-
- All visual objects provide this information.
-
- \sa rect()
-*/
-
-/*!
- \fn int QAccessibleInterface::navigate(RelationFlag relation, int entry, QAccessibleInterface
-**target) const
-
- Navigates from this object to an object that has a relationship
- \a relation to this object, and returns the respective object in
- \a target. It is the caller's responsibility to delete *\a target
- after use.
-
- If an object is found, \a target is set to point to the object, and
- the index of the child of \a target is returned. The return value
- is 0 if \a target itself is the requested object. \a target is set
- to null if this object is the target object (i.e. the requested
- object is a handled by this object).
-
- If no object is found \a target is set to null, and the return
- value is -1.
-
- The \a entry parameter has two different meanings:
- \list
- \i \e{Hierarchical and Logical relationships} -- if multiple objects with
- the requested relationship exist \a entry specifies which one to
- return. \a entry is 1-based, e.g. use 1 to get the first (and
- possibly only) object with the requested relationship.
-
- The following code demonstrates how to use this function to
- navigate to the first child of an object:
-
- \snippet doc/src/snippets/code/src_gui_accessible_qaccessible.cpp 0
-
- \i \e{Geometric relationships} -- the index of the child from
- which to start navigating in the specified direction. \a entry
- can be 0 to navigate to a sibling of this object, or non-null to
- navigate within contained children that don't provide their own
- accessible information.
- \endlist
-
- Note that the \c Descendent value for \a relation is not supported.
-
- All objects support navigation.
-
- \sa relationTo(), childCount()
-*/
-
-/*!
- \fn QString QAccessibleInterface::text(Text t, int child) const
-
- Returns the value of the text property \a t of the object, or of
- the object's child if \a child is not 0.
-
- The \l Name is a string used by clients to identify, find, or
- announce an accessible object for the user. All objects must have
- a name that is unique within their container. The name can be
- used differently by clients, so the name should both give a
- short description of the object and be unique.
-
- An accessible object's \l Description provides textual information
- about an object's visual appearance. The description is primarily
- used to provide greater context for vision-impaired users, but is
- also used for context searching or other applications. Not all
- objects have a description. An "OK" button would not need a
- description, but a tool button that shows a picture of a smiley
- would.
-
- The \l Value of an accessible object represents visual information
- contained by the object, e.g. the text in a line edit. Usually,
- the value can be modified by the user. Not all objects have a
- value, e.g. static text labels don't, and some objects have a
- state that already is the value, e.g. toggle buttons.
-
- The \l Help text provides information about the function and
- usage of an accessible object. Not all objects provide this
- information.
-
- The \l Accelerator is a keyboard shortcut that activates the
- object's default action. A keyboard shortcut is the underlined
- character in the text of a menu, menu item or widget, and is
- either the character itself, or a combination of this character
- and a modifier key like Alt, Ctrl or Shift. Command controls like
- tool buttons also have shortcut keys and usually display them in
- their tooltip.
-
- All objects provide a string for \l Name.
-
- \sa role(), state()
-*/
-
-/*!
- \fn void QAccessibleInterface::setText(Text t, int child, const QString &text)
-
- Sets the text property \a t of the object, or of the object's
- child if \a child is not 0, to \a text.
-
- Note that the text properties of most objects are read-only.
-
- \sa text()
-*/
-
-/*!
- \fn QRect QAccessibleInterface::rect(int child) const
-
- Returns the geometry of the object, or of the object's child if \a child
- is not 0. The geometry is in screen coordinates.
-
- This function is only reliable for visible objects (invisible
- objects might not be laid out correctly).
-
- All visual objects provide this information.
-
- \sa childAt()
-*/
-
-/*!
- \fn QAccessible::Role QAccessibleInterface::role(int child) const
-
- Returns the role of the object, or of the object's child if \a child
- is not 0. The role of an object is usually static.
-
- All accessible objects have a role.
-
- \sa text(), state()
-*/
-
-/*!
- \fn QAccessible::State QAccessibleInterface::state(int child) const
-
- Returns the current state of the object, or of the object's child if
- \a child is not 0. The returned value is a combination of the flags in
- the QAccessible::StateFlag enumeration.
-
- All accessible objects have a state.
-
- \sa text(), role()
-*/
-
-/*!
- \fn int QAccessibleInterface::userActionCount(int child) const
-
- Returns the number of custom actions of the object, or of the
- object's child if \a child is not 0.
-
- The \c Action type enumerates predefined actions: these
- are not included in the returned value.
-
- \sa actionText(), doAction()
-*/
-
-/*!
- \fn QString QAccessibleInterface::actionText(int action, Text t, int child) const
-
- Returns the text property \a t of the action \a action supported by
- the object, or of the object's child if \a child is not 0.
-
- \sa text(), userActionCount()
-*/
-
-/*!
- \fn bool QAccessibleInterface::doAction(int action, int child, const QVariantList &params)
-
- Asks the object, or the object's \a child if \a child is not 0, to
- execute \a action using the parameters, \a params. Returns true if
- the action could be executed; otherwise returns false.
-
- \a action can be a predefined or a custom action.
-
- \sa userActionCount(), actionText()
-*/
-
-/*!
- \fn QColor QAccessibleInterface::backgroundColor()
- \internal
-*/
-
-/*!
- \fn QAccessibleEditableTextInterface *QAccessibleInterface::editableTextInterface()
- \internal
-*/
-
-/*!
- \fn QColor QAccessibleInterface::foregroundColor()
- \internal
-*/
-
-/*!
- \fn QAccessibleTextInterface *QAccessibleInterface::textInterface()
- \internal
-*/
-
-/*!
- \fn QAccessibleValueInterface *QAccessibleInterface::valueInterface()
- \internal
-*/
-
-/*!
- \fn QAccessibleTableInterface *QAccessibleInterface::tableInterface()
- \internal
-*/
-
-/*!
- \fn QAccessibleActionInterface *QAccessibleInterface::actionInterface()
- \internal
-*/
-
-/*!
- \fn QAccessibleImageInterface *QAccessibleInterface::imageInterface()
- \internal
-*/
-
-/*!
- \class QAccessibleEvent
- \brief The QAccessibleEvent class is used to query addition
- accessibility information about complex widgets.
-
- The event can be of type QEvent::AccessibilityDescription or
- QEvent::AccessibilityHelp.
-
- Some QAccessibleInterface implementations send QAccessibleEvents
- to the widget they wrap to obtain the description or help text of
- a widget or of its children. The widget can answer by calling
- setValue() with the requested information.
-
- The default QWidget::event() implementation simply sets the text
- to be the widget's \l{QWidget::toolTip}{tooltip} (for \l
- AccessibilityDescription event) or its
- \l{QWidget::whatsThis}{"What's This?" text} (for \l
- AccessibilityHelp event).
-
- \ingroup accessibility
- \ingroup events
-*/
-
-/*!
- \fn QAccessibleEvent::QAccessibleEvent(Type type, int child)
-
- Constructs an accessibility event of the given \a type, which
- must be QEvent::AccessibilityDescription or
- QEvent::AccessibilityHelp.
-
- \a child is the (1-based) index of the child to which the request
- applies. If \a child is 0, the request is for the widget itself.
-
- \sa child()
-*/
-
-/*!
- \fn int QAccessibleEvent::child() const
-
- Returns the (1-based) index of the child to which the request
- applies. If the child is 0, the request is for the widget itself.
-*/
-
-/*!
- \fn QString QAccessibleEvent::value() const
-
- Returns the text set using setValue().
-
- \sa setValue()
-*/
-
-/*!
- \fn void QAccessibleEvent::setValue(const QString &text)
-
- Set the description or help text for the given child() to \a
- text, thereby answering the request.
-
- \sa value()
-*/
-
-/*!
- \since 4.2
-
- Invokes a \a method on \a child with the given parameters \a params
- and returns the result of the operation as QVariant.
-
- Note that the type of the returned QVariant depends on the action.
-
- Returns an invalid QVariant if the object doesn't support the action.
-*/
-QVariant QAccessibleInterface::invokeMethod(Method method, int child, const QVariantList &params)
-{
- if (!(state(0) & HasInvokeExtension))
- return QVariant();
-
- return static_cast<QAccessibleInterfaceEx *>(this)->invokeMethodEx(method, child, params);
-}
-
-QVariant QAccessibleInterfaceEx::virtual_hook(const QVariant &)
-{
- return QVariant();
-}
-
-/*! \internal */
-QAccessible2Interface *QAccessibleInterface::cast_helper(QAccessible2::InterfaceType t)
-{
- if (state(0) & HasInvokeExtension)
- return static_cast<QAccessibleInterfaceEx *>(this)->interface_cast(t);
- return 0;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/accessible/qaccessible.h b/src/gui/accessible/qaccessible.h
deleted file mode 100644
index be3d4b5ffc..0000000000
--- a/src/gui/accessible/qaccessible.h
+++ /dev/null
@@ -1,425 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLE_H
-#define QACCESSIBLE_H
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qset.h>
-#include <QtCore/qvector.h>
-#include <QtCore/qvariant.h>
-#include <QtGui/qcolor.h>
-#include <QtGui/qevent.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACCESSIBILITY
-
-class QAccessibleInterface;
-
-class Q_GUI_EXPORT QAccessible
-{
-public:
- enum Event {
- SoundPlayed = 0x0001,
- Alert = 0x0002,
- ForegroundChanged = 0x0003,
- MenuStart = 0x0004,
- MenuEnd = 0x0005,
- PopupMenuStart = 0x0006,
- PopupMenuEnd = 0x0007,
- ContextHelpStart = 0x000C,
- ContextHelpEnd = 0x000D,
- DragDropStart = 0x000E,
- DragDropEnd = 0x000F,
- DialogStart = 0x0010,
- DialogEnd = 0x0011,
- ScrollingStart = 0x0012,
- ScrollingEnd = 0x0013,
-
- MenuCommand = 0x0018,
-
- ObjectCreated = 0x8000,
- ObjectDestroyed = 0x8001,
- ObjectShow = 0x8002,
- ObjectHide = 0x8003,
- ObjectReorder = 0x8004,
- Focus = 0x8005,
- Selection = 0x8006,
- SelectionAdd = 0x8007,
- SelectionRemove = 0x8008,
- SelectionWithin = 0x8009,
- StateChanged = 0x800A,
- LocationChanged = 0x800B,
- NameChanged = 0x800C,
- DescriptionChanged = 0x800D,
- ValueChanged = 0x800E,
- ParentChanged = 0x800F,
- HelpChanged = 0x80A0,
- DefaultActionChanged = 0x80B0,
- AcceleratorChanged = 0x80C0
- };
-
- enum StateFlag {
- Normal = 0x00000000,
- Unavailable = 0x00000001,
- Selected = 0x00000002,
- Focused = 0x00000004,
- Pressed = 0x00000008,
- Checked = 0x00000010,
- Mixed = 0x00000020,
- ReadOnly = 0x00000040,
- HotTracked = 0x00000080,
- DefaultButton = 0x00000100,
- Expanded = 0x00000200,
- Collapsed = 0x00000400,
- Busy = 0x00000800,
- // Floating = 0x00001000,
- Marqueed = 0x00002000,
- Animated = 0x00004000,
- Invisible = 0x00008000,
- Offscreen = 0x00010000,
- Sizeable = 0x00020000,
- Movable = 0x00040000,
- SelfVoicing = 0x00080000,
- Focusable = 0x00100000,
- Selectable = 0x00200000,
- Linked = 0x00400000,
- Traversed = 0x00800000,
- MultiSelectable = 0x01000000,
- ExtSelectable = 0x02000000,
- //AlertLow = 0x04000000,
- //AlertMedium = 0x08000000,
- //AlertHigh = 0x10000000, /* reused for HasInvokeExtension */
- Protected = 0x20000000,
- HasPopup = 0x40000000,
- Modal = 0x80000000,
-
- HasInvokeExtension = 0x10000000 // internal
- };
- Q_DECLARE_FLAGS(State, StateFlag)
-
- enum Role {
- NoRole = 0x00000000,
- TitleBar = 0x00000001,
- MenuBar = 0x00000002,
- ScrollBar = 0x00000003,
- Grip = 0x00000004,
- Sound = 0x00000005,
- Cursor = 0x00000006,
- Caret = 0x00000007,
- AlertMessage = 0x00000008,
- Window = 0x00000009,
- Client = 0x0000000A,
- PopupMenu = 0x0000000B,
- MenuItem = 0x0000000C,
- ToolTip = 0x0000000D,
- Application = 0x0000000E,
- Document = 0x0000000F,
- Pane = 0x00000010,
- Chart = 0x00000011,
- Dialog = 0x00000012,
- Border = 0x00000013,
- Grouping = 0x00000014,
- Separator = 0x00000015,
- ToolBar = 0x00000016,
- StatusBar = 0x00000017,
- Table = 0x00000018,
- ColumnHeader = 0x00000019,
- RowHeader = 0x0000001A,
- Column = 0x0000001B,
- Row = 0x0000001C,
- Cell = 0x0000001D,
- Link = 0x0000001E,
- HelpBalloon = 0x0000001F,
- Assistant = 0x00000020,
- List = 0x00000021,
- ListItem = 0x00000022,
- Tree = 0x00000023,
- TreeItem = 0x00000024,
- PageTab = 0x00000025,
- PropertyPage = 0x00000026,
- Indicator = 0x00000027,
- Graphic = 0x00000028,
- StaticText = 0x00000029,
- EditableText = 0x0000002A, // Editable, selectable, etc.
- PushButton = 0x0000002B,
- CheckBox = 0x0000002C,
- RadioButton = 0x0000002D,
- ComboBox = 0x0000002E,
- // DropList = 0x0000002F,
- ProgressBar = 0x00000030,
- Dial = 0x00000031,
- HotkeyField = 0x00000032,
- Slider = 0x00000033,
- SpinBox = 0x00000034,
- Canvas = 0x00000035,
- Animation = 0x00000036,
- Equation = 0x00000037,
- ButtonDropDown = 0x00000038,
- ButtonMenu = 0x00000039,
- ButtonDropGrid = 0x0000003A,
- Whitespace = 0x0000003B,
- PageTabList = 0x0000003C,
- Clock = 0x0000003D,
- Splitter = 0x0000003E,
- // Additional Qt roles where enum value does not map directly to MSAA:
- LayeredPane = 0x0000003F,
- UserRole = 0x0000ffff
- };
-
- enum Text {
- Name = 0,
- Description,
- Value,
- Help,
- Accelerator,
- UserText = 0x0000ffff
- };
-
- enum RelationFlag {
- Unrelated = 0x00000000,
- Self = 0x00000001,
- Ancestor = 0x00000002,
- Child = 0x00000004,
- Descendent = 0x00000008,
- Sibling = 0x00000010,
- HierarchyMask = 0x000000ff,
-
- Up = 0x00000100,
- Down = 0x00000200,
- Left = 0x00000400,
- Right = 0x00000800,
- Covers = 0x00001000,
- Covered = 0x00002000,
- GeometryMask = 0x0000ff00,
-
- FocusChild = 0x00010000,
- Label = 0x00020000,
- Labelled = 0x00040000,
- Controller = 0x00080000,
- Controlled = 0x00100000,
- LogicalMask = 0x00ff0000
- };
- Q_DECLARE_FLAGS(Relation, RelationFlag)
-
- enum Action {
- DefaultAction = 0,
- Press = -1,
- FirstStandardAction = Press,
- SetFocus = -2,
- Increase = -3,
- Decrease = -4,
- Accept = -5,
- Cancel = -6,
- Select = -7,
- ClearSelection = -8,
- RemoveSelection = -9,
- ExtendSelection = -10,
- AddToSelection = -11,
- LastStandardAction = AddToSelection
- };
-
- enum Method {
- ListSupportedMethods = 0,
- SetCursorPosition = 1,
- GetCursorPosition = 2,
- ForegroundColor = 3,
- BackgroundColor = 4
- };
-
- typedef QAccessibleInterface*(*InterfaceFactory)(const QString &key, QObject*);
- typedef void(*UpdateHandler)(QObject*, int who, Event reason);
- typedef void(*RootObjectHandler)(QObject*);
-
- static void installFactory(InterfaceFactory);
- static void removeFactory(InterfaceFactory);
- static UpdateHandler installUpdateHandler(UpdateHandler);
- static RootObjectHandler installRootObjectHandler(RootObjectHandler);
-
- static QAccessibleInterface *queryAccessibleInterface(QObject *);
- static void updateAccessibility(QObject *, int who, Event reason);
- static bool isActive();
- static void setRootObject(QObject*);
-
- static void initialize();
- static void cleanup();
-
-private:
- static UpdateHandler updateHandler;
- static RootObjectHandler rootObjectHandler;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QAccessible::State)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QAccessible::Relation)
-QT_END_NAMESPACE
-Q_DECLARE_METATYPE(QSet<QAccessible::Method>)
-QT_BEGIN_NAMESPACE
-
-namespace QAccessible2
-{
- enum InterfaceType
- {
- TextInterface,
- EditableTextInterface,
- ValueInterface,
- TableInterface,
- ActionInterface,
- ImageInterface
- };
-}
-
-class QAccessible2Interface;
-class QAccessibleTextInterface;
-class QAccessibleEditableTextInterface;
-class QAccessibleValueInterface;
-class QAccessibleTableInterface;
-class QAccessibleActionInterface;
-class QAccessibleImageInterface;
-
-class Q_GUI_EXPORT QAccessibleInterface : public QAccessible
-{
-public:
- virtual ~QAccessibleInterface() {}
- // check for valid pointers
- virtual bool isValid() const = 0;
- virtual QObject *object() const = 0;
-
- // hierarchy
- virtual int childCount() const = 0;
- virtual int indexOfChild(const QAccessibleInterface *) const = 0;
-
- // relations
- virtual Relation relationTo(int child, const QAccessibleInterface *other,
- int otherChild) const = 0;
- virtual int childAt(int x, int y) const = 0;
-
- // navigation
- virtual int navigate(RelationFlag relation, int index, QAccessibleInterface **iface) const = 0;
-
- // properties and state
- virtual QString text(Text t, int child) const = 0;
- virtual void setText(Text t, int child, const QString &text) = 0;
- virtual QRect rect(int child) const = 0;
- virtual Role role(int child) const = 0;
- virtual State state(int child) const = 0;
-
- // action
- virtual int userActionCount(int child) const = 0;
- virtual QString actionText(int action, Text t, int child) const = 0;
- virtual bool doAction(int action, int child, const QVariantList &params = QVariantList()) = 0;
-
- QVariant invokeMethod(Method method, int child = 0,
- const QVariantList &params = QVariantList());
-
- inline QSet<Method> supportedMethods()
- { return qvariant_cast<QSet<Method> >(invokeMethod(ListSupportedMethods)); }
-
- inline QColor foregroundColor()
- { return qvariant_cast<QColor>(invokeMethod(ForegroundColor)); }
-
- inline QColor backgroundColor()
- { return qvariant_cast<QColor>(invokeMethod(BackgroundColor)); }
-
- inline QAccessibleTextInterface *textInterface()
- { return reinterpret_cast<QAccessibleTextInterface *>(cast_helper(QAccessible2::TextInterface)); }
-
- inline QAccessibleEditableTextInterface *editableTextInterface()
- { return reinterpret_cast<QAccessibleEditableTextInterface *>(cast_helper(QAccessible2::EditableTextInterface)); }
-
- inline QAccessibleValueInterface *valueInterface()
- { return reinterpret_cast<QAccessibleValueInterface *>(cast_helper(QAccessible2::ValueInterface)); }
-
- inline QAccessibleTableInterface *tableInterface()
- { return reinterpret_cast<QAccessibleTableInterface *>(cast_helper(QAccessible2::TableInterface)); }
-
- inline QAccessibleActionInterface *actionInterface()
- { return reinterpret_cast<QAccessibleActionInterface *>(cast_helper(QAccessible2::ActionInterface)); }
-
- inline QAccessibleImageInterface *imageInterface()
- { return reinterpret_cast<QAccessibleImageInterface *>(cast_helper(QAccessible2::ImageInterface)); }
-
-private:
- QAccessible2Interface *cast_helper(QAccessible2::InterfaceType);
-};
-
-class Q_GUI_EXPORT QAccessibleInterfaceEx: public QAccessibleInterface
-{
-public:
- virtual QVariant invokeMethodEx(Method method, int child, const QVariantList &params) = 0;
- virtual QVariant virtual_hook(const QVariant &data);
- virtual QAccessible2Interface *interface_cast(QAccessible2::InterfaceType)
- { return 0; }
-};
-
-
-class Q_GUI_EXPORT QAccessibleEvent : public QEvent
-{
-public:
- inline QAccessibleEvent(Type type, int child);
- inline int child() const { return c; }
- inline QString value() const { return val; }
- inline void setValue(const QString &aText) { val = aText; }
-
-private:
- int c;
- QString val;
-};
-
-inline QAccessibleEvent::QAccessibleEvent(Type atype, int achild)
- : QEvent(atype), c(achild) {}
-
-#define QAccessibleInterface_iid "com.trolltech.Qt.QAccessibleInterface"
-Q_DECLARE_INTERFACE(QAccessibleInterface, QAccessibleInterface_iid)
-
-#endif // QT_NO_ACCESSIBILITY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QACCESSIBLE_H
diff --git a/src/gui/accessible/qaccessible2.cpp b/src/gui/accessible/qaccessible2.cpp
deleted file mode 100644
index 36187f5315..0000000000
--- a/src/gui/accessible/qaccessible2.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessible2.h"
-#include "qapplication.h"
-#include "qclipboard.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \namespace QAccessible2
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessible2 namespace defines constants relating to
- IAccessible2-based interfaces
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-/*!
- \class QAccessibleTextInterface
-
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessibleTextInterface class implements support for
- the IAccessibleText interface.
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-/*!
- \class QAccessibleEditableTextInterface
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessibleEditableTextInterface class implements support for
- the IAccessibleEditableText interface.
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-/*!
- \class QAccessibleSimpleEditableTextInterface
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessibleSimpleEditableTextInterface class is a convenience class for
- text-based widgets.
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-/*!
- \class QAccessibleValueInterface
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessibleValueInterface class implements support for
- the IAccessibleValue interface.
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-/*!
- \class QAccessibleActionInterface
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessibleActionInterface class implements support for
- the IAccessibleAction interface.
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-/*!
- \class QAccessibleImageInterface
- \ingroup accessibility
- \internal
- \preliminary
-
- \brief The QAccessibleImageInterface class implements support for
- the IAccessibleImage interface.
-
- \link http://www.linux-foundation.org/en/Accessibility/IAccessible2 IAccessible2 Specification \endlink
-*/
-
-QAccessibleSimpleEditableTextInterface::QAccessibleSimpleEditableTextInterface(
- QAccessibleInterface *accessibleInterface)
- : iface(accessibleInterface)
-{
- Q_ASSERT(iface);
-}
-
-#ifndef QT_NO_CLIPBOARD
-static QString textForRange(QAccessibleInterface *iface, int startOffset, int endOffset)
-{
- return iface->text(QAccessible::Value, 0).mid(startOffset, endOffset - startOffset);
-}
-#endif
-
-void QAccessibleSimpleEditableTextInterface::copyText(int startOffset, int endOffset)
-{
-#ifdef QT_NO_CLIPBOARD
- Q_UNUSED(startOffset);
- Q_UNUSED(endOffset);
-#else
- QApplication::clipboard()->setText(textForRange(iface, startOffset, endOffset));
-#endif
-}
-
-void QAccessibleSimpleEditableTextInterface::deleteText(int startOffset, int endOffset)
-{
- QString txt = iface->text(QAccessible::Value, 0);
- txt.remove(startOffset, endOffset - startOffset);
- iface->setText(QAccessible::Value, 0, txt);
-}
-
-void QAccessibleSimpleEditableTextInterface::insertText(int offset, const QString &text)
-{
- QString txt = iface->text(QAccessible::Value, 0);
- txt.insert(offset, text);
- iface->setText(QAccessible::Value, 0, txt);
-}
-
-void QAccessibleSimpleEditableTextInterface::cutText(int startOffset, int endOffset)
-{
-#ifdef QT_NO_CLIPBOARD
- Q_UNUSED(startOffset);
- Q_UNUSED(endOffset);
-#else
- QString sub = textForRange(iface, startOffset, endOffset);
- deleteText(startOffset, endOffset);
- QApplication::clipboard()->setText(sub);
-#endif
-}
-
-void QAccessibleSimpleEditableTextInterface::pasteText(int offset)
-{
-#ifdef QT_NO_CLIPBOARD
- Q_UNUSED(offset);
-#else
- QString txt = iface->text(QAccessible::Value, 0);
- txt.insert(offset, QApplication::clipboard()->text());
- iface->setText(QAccessible::Value, 0, txt);
-#endif
-}
-
-void QAccessibleSimpleEditableTextInterface::replaceText(int startOffset, int endOffset, const QString &text)
-{
- QString txt = iface->text(QAccessible::Value, 0);
- txt.replace(startOffset, endOffset - startOffset, text);
- iface->setText(QAccessible::Value, 0, txt);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessible2.h b/src/gui/accessible/qaccessible2.h
deleted file mode 100644
index 65ab7166c6..0000000000
--- a/src/gui/accessible/qaccessible2.h
+++ /dev/null
@@ -1,246 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLE2_H
-#define QACCESSIBLE2_H
-
-#include <QtGui/qaccessible.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACCESSIBILITY
-
-namespace QAccessible2
-{
- enum CoordinateType
- {
- RelativeToScreen = 0,
- RelativeToParent = 1
- };
-
- enum BoundaryType {
- CharBoundary,
- WordBoundary,
- SentenceBoundary,
- ParagraphBoundary,
- LineBoundary,
- NoBoundary
- };
-}
-
-class Q_GUI_EXPORT QAccessible2Interface
-{
-public:
- virtual ~QAccessible2Interface() {}
-};
-
-// catch-all functions. If an accessible class doesn't implement interface T, return 0
-inline QAccessible2Interface *qAccessibleValueCastHelper() { return 0; }
-inline QAccessible2Interface *qAccessibleTextCastHelper() { return 0; }
-inline QAccessible2Interface *qAccessibleEditableTextCastHelper() { return 0; }
-inline QAccessible2Interface *qAccessibleTableCastHelper() { return 0; }
-inline QAccessible2Interface *qAccessibleActionCastHelper() { return 0; }
-inline QAccessible2Interface *qAccessibleImageCastHelper() { return 0; }
-
-#define Q_ACCESSIBLE_OBJECT \
- public: \
- QAccessible2Interface *interface_cast(QAccessible2::InterfaceType t) \
- { \
- switch (t) { \
- case QAccessible2::TextInterface: \
- return qAccessibleTextCastHelper(); \
- case QAccessible2::EditableTextInterface: \
- return qAccessibleEditableTextCastHelper(); \
- case QAccessible2::ValueInterface: \
- return qAccessibleValueCastHelper(); \
- case QAccessible2::TableInterface: \
- return qAccessibleTableCastHelper(); \
- case QAccessible2::ActionInterface: \
- return qAccessibleActionCastHelper(); \
- case QAccessible2::ImageInterface: \
- return qAccessibleImageCastHelper(); \
- } \
- return 0; \
- } \
- private:
-
-class Q_GUI_EXPORT QAccessibleTextInterface: public QAccessible2Interface
-{
-public:
- inline QAccessible2Interface *qAccessibleTextCastHelper() { return this; }
-
- virtual ~QAccessibleTextInterface() {}
-
- virtual void addSelection(int startOffset, int endOffset) = 0;
- virtual QString attributes(int offset, int *startOffset, int *endOffset) = 0;
- virtual int cursorPosition() = 0;
- virtual QRect characterRect(int offset, QAccessible2::CoordinateType coordType) = 0;
- virtual int selectionCount() = 0;
- virtual int offsetAtPoint(const QPoint &point, QAccessible2::CoordinateType coordType) = 0;
- virtual void selection(int selectionIndex, int *startOffset, int *endOffset) = 0;
- virtual QString text(int startOffset, int endOffset) = 0;
- virtual QString textBeforeOffset (int offset, QAccessible2::BoundaryType boundaryType,
- int *startOffset, int *endOffset) = 0;
- virtual QString textAfterOffset(int offset, QAccessible2::BoundaryType boundaryType,
- int *startOffset, int *endOffset) = 0;
- virtual QString textAtOffset(int offset, QAccessible2::BoundaryType boundaryType,
- int *startOffset, int *endOffset) = 0;
- virtual void removeSelection(int selectionIndex) = 0;
- virtual void setCursorPosition(int position) = 0;
- virtual void setSelection(int selectionIndex, int startOffset, int endOffset) = 0;
- virtual int characterCount() = 0;
- virtual void scrollToSubstring(int startIndex, int endIndex) = 0;
-};
-
-class Q_GUI_EXPORT QAccessibleEditableTextInterface: public QAccessible2Interface
-{
-public:
- inline QAccessible2Interface *qAccessibleEditableTextCastHelper() { return this; }
-
- virtual ~QAccessibleEditableTextInterface() {}
-
- virtual void copyText(int startOffset, int endOffset) = 0;
- virtual void deleteText(int startOffset, int endOffset) = 0;
- virtual void insertText(int offset, const QString &text) = 0;
- virtual void cutText(int startOffset, int endOffset) = 0;
- virtual void pasteText(int offset) = 0;
- virtual void replaceText(int startOffset, int endOffset, const QString &text) = 0;
- virtual void setAttributes(int startOffset, int endOffset, const QString &attributes) = 0;
-};
-
-class Q_GUI_EXPORT QAccessibleSimpleEditableTextInterface: public QAccessibleEditableTextInterface
-{
-public:
- QAccessibleSimpleEditableTextInterface(QAccessibleInterface *accessibleInterface);
-
- void copyText(int startOffset, int endOffset);
- void deleteText(int startOffset, int endOffset);
- void insertText(int offset, const QString &text);
- void cutText(int startOffset, int endOffset);
- void pasteText(int offset);
- void replaceText(int startOffset, int endOffset, const QString &text);
- inline void setAttributes(int, int, const QString &) {}
-
-private:
- QAccessibleInterface *iface;
-};
-
-class Q_GUI_EXPORT QAccessibleValueInterface: public QAccessible2Interface
-{
-public:
- inline QAccessible2Interface *qAccessibleValueCastHelper() { return this; }
-
- virtual ~QAccessibleValueInterface() {}
-
- virtual QVariant currentValue() = 0;
- virtual void setCurrentValue(const QVariant &value) = 0;
- virtual QVariant maximumValue() = 0;
- virtual QVariant minimumValue() = 0;
-};
-
-class Q_GUI_EXPORT QAccessibleTableInterface: public QAccessible2Interface
-{
-public:
- inline QAccessible2Interface *qAccessibleTableCastHelper() { return this; }
-
- virtual QAccessibleInterface *accessibleAt(int row, int column) = 0;
- virtual QAccessibleInterface *caption() = 0;
- virtual int childIndex(int rowIndex, int columnIndex) = 0;
- virtual QString columnDescription(int column) = 0;
- virtual int columnSpan(int row, int column) = 0;
- virtual QAccessibleInterface *columnHeader() = 0;
- virtual int columnIndex(int childIndex) = 0;
- virtual int columnCount() = 0;
- virtual int rowCount() = 0;
- virtual int selectedColumnCount() = 0;
- virtual int selectedRowCount() = 0;
- virtual QString rowDescription(int row) = 0;
- virtual int rowSpan(int row, int column) = 0;
- virtual QAccessibleInterface *rowHeader() = 0;
- virtual int rowIndex(int childIndex) = 0;
- virtual int selectedRows(int maxRows, QList<int> *rows) = 0;
- virtual int selectedColumns(int maxColumns, QList<int> *columns) = 0;
- virtual QAccessibleInterface *summary() = 0;
- virtual bool isColumnSelected(int column) = 0;
- virtual bool isRowSelected(int row) = 0;
- virtual bool isSelected(int row, int column) = 0;
- virtual void selectRow(int row) = 0;
- virtual void selectColumn(int column) = 0;
- virtual void unselectRow(int row) = 0;
- virtual void unselectColumn(int column) = 0;
- virtual void cellAtIndex(int index, int *row, int *column, int *rowSpan,
- int *columnSpan, bool *isSelected) = 0;
-};
-
-class Q_GUI_EXPORT QAccessibleActionInterface : public QAccessible2Interface
-{
-public:
- inline QAccessible2Interface *qAccessibleActionCastHelper() { return this; }
-
- virtual int actionCount() = 0;
- virtual void doAction(int actionIndex) = 0;
- virtual QString description(int actionIndex) = 0;
- virtual QString name(int actionIndex) = 0;
- virtual QString localizedName(int actionIndex) = 0;
- virtual QStringList keyBindings(int actionIndex) = 0;
-};
-
-class Q_GUI_EXPORT QAccessibleImageInterface : public QAccessible2Interface
-{
-public:
- inline QAccessible2Interface *qAccessibleImageCastHelper() { return this; }
-
- virtual QString imageDescription() = 0;
- virtual QSize imageSize() = 0;
- virtual QRect imagePosition(QAccessible2::CoordinateType coordType) = 0;
-};
-
-#endif // QT_NO_ACCESSIBILITY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/accessible/qaccessible_mac.mm b/src/gui/accessible/qaccessible_mac.mm
deleted file mode 100644
index d01c1c9733..0000000000
--- a/src/gui/accessible/qaccessible_mac.mm
+++ /dev/null
@@ -1,2469 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessible.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible_mac_p.h"
-#include "qhash.h"
-#include "qset.h"
-#include "qpointer.h"
-#include "qapplication.h"
-#include "qmainwindow.h"
-#include "qtextdocument.h"
-#include "qdebug.h"
-#include "qabstractslider.h"
-#include "qsplitter.h"
-#include "qtabwidget.h"
-#include "qlistview.h"
-#include "qtableview.h"
-#include "qdockwidget.h"
-
-#include <private/qt_mac_p.h>
-#include <private/qwidget_p.h>
-#include <CoreFoundation/CoreFoundation.h>
-
-QT_BEGIN_NAMESPACE
-
-/*
- Set up platform defines. There is a one-to-one correspondence between the
- Carbon and Cocoa roles and attributes, but the prefix and type changes.
-*/
-#ifdef QT_MAC_USE_COCOA
-typedef NSString * const QAXRoleType;
-#define QAXApplicationRole NSAccessibilityApplicationRole
-#define QAXButtonRole NSAccessibilityButtonRole
-#define QAXCancelAction NSAccessibilityCancelAction
-#define QAXCheckBoxRole NSAccessibilityCheckBoxRole
-#define QAXChildrenAttribute NSAccessibilityChildrenAttribute
-#define QAXCloseButtonAttribute NSAccessibilityCloseButtonAttribute
-#define QAXCloseButtonAttribute NSAccessibilityCloseButtonAttribute
-#define QAXColumnRole NSAccessibilityColumnRole
-#define QAXConfirmAction NSAccessibilityConfirmAction
-#define QAXContentsAttribute NSAccessibilityContentsAttribute
-#define QAXDecrementAction NSAccessibilityDecrementAction
-#define QAXDecrementArrowSubrole NSAccessibilityDecrementArrowSubrole
-#define QAXDecrementPageSubrole NSAccessibilityDecrementPageSubrole
-#define QAXDescriptionAttribute NSAccessibilityDescriptionAttribute
-#define QAXEnabledAttribute NSAccessibilityEnabledAttribute
-#define QAXExpandedAttribute NSAccessibilityExpandedAttribute
-#define QAXFocusedAttribute NSAccessibilityFocusedAttribute
-#define QAXFocusedUIElementChangedNotification NSAccessibilityFocusedUIElementChangedNotification
-#define QAXFocusedWindowChangedNotification NSAccessibilityFocusedWindowChangedNotification
-#define QAXGroupRole NSAccessibilityGroupRole
-#define QAXGrowAreaAttribute NSAccessibilityGrowAreaAttribute
-#define QAXGrowAreaRole NSAccessibilityGrowAreaRole
-#define QAXHelpAttribute NSAccessibilityHelpAttribute
-#define QAXHorizontalOrientationValue NSAccessibilityHorizontalOrientationValue
-#define QAXHorizontalScrollBarAttribute NSAccessibilityHorizontalScrollBarAttribute
-#define QAXIncrementAction NSAccessibilityIncrementAction
-#define QAXIncrementArrowSubrole NSAccessibilityIncrementArrowSubrole
-#define QAXIncrementPageSubrole NSAccessibilityIncrementPageSubrole
-#define QAXIncrementorRole NSAccessibilityIncrementorRole
-#define QAXLinkedUIElementsAttribute NSAccessibilityLinkedUIElementsAttribute
-#define QAXListRole NSAccessibilityListRole
-#define QAXMainAttribute NSAccessibilityMainAttribute
-#define QAXMaxValueAttribute NSAccessibilityMaxValueAttribute
-#define QAXMenuBarRole NSAccessibilityMenuBarRole
-#define QAXMenuButtonRole NSAccessibilityMenuButtonRole
-#define QAXMenuClosedNotification NSAccessibilityMenuClosedNotification
-#define QAXMenuItemRole NSAccessibilityMenuItemRole
-#define QAXMenuOpenedNotification NSAccessibilityMenuOpenedNotification
-#define QAXMenuRole NSAccessibilityMenuRole
-#define QAXMinValueAttribute NSAccessibilityMinValueAttribute
-#define QAXMinimizeButtonAttribute NSAccessibilityMinimizeButtonAttribute
-#define QAXMinimizedAttribute NSAccessibilityMinimizedAttribute
-#define QAXNextContentsAttribute NSAccessibilityNextContentsAttribute
-#define QAXOrientationAttribute NSAccessibilityOrientationAttribute
-#define QAXParentAttribute NSAccessibilityParentAttribute
-#define QAXPickAction NSAccessibilityPickAction
-#define QAXPopUpButtonRole NSAccessibilityPopUpButtonRole
-#define QAXPositionAttribute NSAccessibilityPositionAttribute
-#define QAXPressAction NSAccessibilityPressAction
-#define QAXPreviousContentsAttribute NSAccessibilityPreviousContentsAttribute
-#define QAXProgressIndicatorRole NSAccessibilityProgressIndicatorRole
-#define QAXRadioButtonRole NSAccessibilityRadioButtonRole
-#define QAXRoleAttribute NSAccessibilityRoleAttribute
-#define QAXRoleDescriptionAttribute NSAccessibilityRoleDescriptionAttribute
-#define QAXRowRole NSAccessibilityRowRole
-#define QAXRowsAttribute NSAccessibilityRowsAttribute
-#define QAXScrollAreaRole NSAccessibilityScrollAreaRole
-#define QAXScrollBarRole NSAccessibilityScrollBarRole
-#define QAXSelectedAttribute NSAccessibilitySelectedAttribute
-#define QAXSelectedChildrenAttribute NSAccessibilitySelectedChildrenAttribute
-#define QAXSelectedRowsAttribute NSAccessibilitySelectedRowsAttribute
-#define QAXSizeAttribute NSAccessibilitySizeAttribute
-#define QAXSliderRole NSAccessibilitySliderRole
-#define QAXSplitGroupRole NSAccessibilitySplitGroupRole
-#define QAXSplitterRole NSAccessibilitySplitterRole
-#define QAXSplittersAttribute NSAccessibilitySplittersAttribute
-#define QAXStaticTextRole NSAccessibilityStaticTextRole
-#define QAXSubroleAttribute NSAccessibilitySubroleAttribute
-#define QAXSubroleAttribute NSAccessibilitySubroleAttribute
-#define QAXTabGroupRole NSAccessibilityTabGroupRole
-#define QAXTableRole NSAccessibilityTableRole
-#define QAXTabsAttribute NSAccessibilityTabsAttribute
-#define QAXTextFieldRole NSAccessibilityTextFieldRole
-#define QAXTitleAttribute NSAccessibilityTitleAttribute
-#define QAXTitleUIElementAttribute NSAccessibilityTitleUIElementAttribute
-#define QAXToolbarButtonAttribute NSAccessibilityToolbarButtonAttribute
-#define QAXToolbarRole NSAccessibilityToolbarRole
-#define QAXTopLevelUIElementAttribute NSAccessibilityTopLevelUIElementAttribute
-#define QAXUnknownRole NSAccessibilityUnknownRole
-#define QAXValueAttribute NSAccessibilityValueAttribute
-#define QAXValueChangedNotification NSAccessibilityValueChangedNotification
-#define QAXValueIndicatorRole NSAccessibilityValueIndicatorRole
-#define QAXVerticalOrientationValue NSAccessibilityVerticalOrientationValue
-#define QAXVerticalScrollBarAttribute NSAccessibilityVerticalScrollBarAttribute
-#define QAXVisibleRowsAttribute NSAccessibilityVisibleRowsAttribute
-#define QAXWindowAttribute NSAccessibilityWindowAttribute
-#define QAXWindowCreatedNotification NSAccessibilityWindowCreatedNotification
-#define QAXWindowMovedNotification NSAccessibilityWindowMovedNotification
-#define QAXWindowRole NSAccessibilityWindowRole
-#define QAXZoomButtonAttribute NSAccessibilityZoomButtonAttribute
-#else
-typedef CFStringRef const QAXRoleType;
-#define QAXApplicationRole kAXApplicationRole
-#define QAXButtonRole kAXButtonRole
-#define QAXCancelAction kAXCancelAction
-#define QAXCheckBoxRole kAXCheckBoxRole
-#define QAXChildrenAttribute kAXChildrenAttribute
-#define QAXCloseButtonAttribute kAXCloseButtonAttribute
-#define QAXColumnRole kAXColumnRole
-#define QAXConfirmAction kAXConfirmAction
-#define QAXContentsAttribute kAXContentsAttribute
-#define QAXDecrementAction kAXDecrementAction
-#define QAXDecrementArrowSubrole kAXDecrementArrowSubrole
-#define QAXDecrementPageSubrole kAXDecrementPageSubrole
-#define QAXDescriptionAttribute kAXDescriptionAttribute
-#define QAXEnabledAttribute kAXEnabledAttribute
-#define QAXExpandedAttribute kAXExpandedAttribute
-#define QAXFocusedAttribute kAXFocusedAttribute
-#define QAXFocusedUIElementChangedNotification kAXFocusedUIElementChangedNotification
-#define QAXFocusedWindowChangedNotification kAXFocusedWindowChangedNotification
-#define QAXGroupRole kAXGroupRole
-#define QAXGrowAreaAttribute kAXGrowAreaAttribute
-#define QAXGrowAreaRole kAXGrowAreaRole
-#define QAXHelpAttribute kAXHelpAttribute
-#define QAXHorizontalOrientationValue kAXHorizontalOrientationValue
-#define QAXHorizontalScrollBarAttribute kAXHorizontalScrollBarAttribute
-#define QAXIncrementAction kAXIncrementAction
-#define QAXIncrementArrowSubrole kAXIncrementArrowSubrole
-#define QAXIncrementPageSubrole kAXIncrementPageSubrole
-#define QAXIncrementorRole kAXIncrementorRole
-#define QAXLinkedUIElementsAttribute kAXLinkedUIElementsAttribute
-#define QAXListRole kAXListRole
-#define QAXMainAttribute kAXMainAttribute
-#define QAXMaxValueAttribute kAXMaxValueAttribute
-#define QAXMenuBarRole kAXMenuBarRole
-#define QAXMenuButtonRole kAXMenuButtonRole
-#define QAXMenuClosedNotification kAXMenuClosedNotification
-#define QAXMenuItemRole kAXMenuItemRole
-#define QAXMenuOpenedNotification kAXMenuOpenedNotification
-#define QAXMenuRole kAXMenuRole
-#define QAXMinValueAttribute kAXMinValueAttribute
-#define QAXMinimizeButtonAttribute kAXMinimizeButtonAttribute
-#define QAXMinimizedAttribute kAXMinimizedAttribute
-#define QAXNextContentsAttribute kAXNextContentsAttribute
-#define QAXOrientationAttribute kAXOrientationAttribute
-#define QAXParentAttribute kAXParentAttribute
-#define QAXPickAction kAXPickAction
-#define QAXPopUpButtonRole kAXPopUpButtonRole
-#define QAXPositionAttribute kAXPositionAttribute
-#define QAXPressAction kAXPressAction
-#define QAXPreviousContentsAttribute kAXPreviousContentsAttribute
-#define QAXProgressIndicatorRole kAXProgressIndicatorRole
-#define QAXRadioButtonRole kAXRadioButtonRole
-#define QAXRoleAttribute kAXRoleAttribute
-#define QAXRoleDescriptionAttribute kAXRoleDescriptionAttribute
-#define QAXRowRole kAXRowRole
-#define QAXRowsAttribute kAXRowsAttribute
-#define QAXScrollAreaRole kAXScrollAreaRole
-#define QAXScrollBarRole kAXScrollBarRole
-#define QAXSelectedAttribute kAXSelectedAttribute
-#define QAXSelectedChildrenAttribute kAXSelectedChildrenAttribute
-#define QAXSelectedRowsAttribute kAXSelectedRowsAttribute
-#define QAXSizeAttribute kAXSizeAttribute
-#define QAXSliderRole kAXSliderRole
-#define QAXSplitGroupRole kAXSplitGroupRole
-#define QAXSplitterRole kAXSplitterRole
-#define QAXSplittersAttribute kAXSplittersAttribute
-#define QAXStaticTextRole kAXStaticTextRole
-#define QAXSubroleAttribute kAXSubroleAttribute
-#define QAXTabGroupRole kAXTabGroupRole
-#define QAXTableRole kAXTableRole
-#define QAXTabsAttribute kAXTabsAttribute
-#define QAXTextFieldRole kAXTextFieldRole
-#define QAXTitleAttribute kAXTitleAttribute
-#define QAXTitleUIElementAttribute kAXTitleUIElementAttribute
-#define QAXToolbarButtonAttribute kAXToolbarButtonAttribute
-#define QAXToolbarRole kAXToolbarRole
-#define QAXTopLevelUIElementAttribute kAXTopLevelUIElementAttribute
-#define QAXUnknownRole kAXUnknownRole
-#define QAXValueAttribute kAXValueAttribute
-#define QAXValueChangedNotification kAXValueChangedNotification
-#define QAXValueIndicatorRole kAXValueIndicatorRole
-#define QAXVerticalOrientationValue kAXVerticalOrientationValue
-#define QAXVerticalScrollBarAttribute kAXVerticalScrollBarAttribute
-#define QAXVisibleRowsAttribute kAXVisibleRowsAttribute
-#define QAXWindowAttribute kAXWindowAttribute
-#define QAXWindowCreatedNotification kAXWindowCreatedNotification
-#define QAXWindowMovedNotification kAXWindowMovedNotification
-#define QAXWindowRole kAXWindowRole
-#define QAXZoomButtonAttribute kAXZoomButtonAttribute
-#endif
-
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern bool qt_mac_is_macsheet(const QWidget *w); //qwidget_mac.cpp
-extern bool qt_mac_is_macdrawer(const QWidget *w); //qwidget_mac.cpp
-
-/*****************************************************************************
- QAccessible Bindings
- *****************************************************************************/
-//hardcoded bindings between control info and (known) QWidgets
-struct QAccessibleTextBinding {
- int qt;
- QAXRoleType mac;
- bool settable;
-} text_bindings[][10] = {
- { { QAccessible::MenuItem, QAXMenuItemRole, false },
- { -1, 0, false }
- },
- { { QAccessible::MenuBar, QAXMenuBarRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ScrollBar, QAXScrollBarRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Grip, QAXGrowAreaRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Window, QAXWindowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Dialog, QAXWindowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::AlertMessage, QAXWindowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ToolTip, QAXWindowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::HelpBalloon, QAXWindowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::PopupMenu, QAXMenuRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Application, QAXApplicationRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Pane, QAXGroupRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Grouping, QAXGroupRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Separator, QAXSplitterRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ToolBar, QAXToolbarRole, false },
- { -1, 0, false }
- },
- { { QAccessible::PageTab, QAXRadioButtonRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ButtonMenu, QAXMenuButtonRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ButtonDropDown, QAXPopUpButtonRole, false },
- { -1, 0, false }
- },
- { { QAccessible::SpinBox, QAXIncrementorRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Slider, QAXSliderRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ProgressBar, QAXProgressIndicatorRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ComboBox, QAXPopUpButtonRole, false },
- { -1, 0, false }
- },
- { { QAccessible::RadioButton, QAXRadioButtonRole, false },
- { -1, 0, false }
- },
- { { QAccessible::CheckBox, QAXCheckBoxRole, false },
- { -1, 0, false }
- },
- { { QAccessible::StaticText, QAXStaticTextRole, false },
- { QAccessible::Name, QAXValueAttribute, false },
- { -1, 0, false }
- },
- { { QAccessible::Table, QAXTableRole, false },
- { -1, 0, false }
- },
- { { QAccessible::StatusBar, QAXStaticTextRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Column, QAXColumnRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ColumnHeader, QAXColumnRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Row, QAXRowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::RowHeader, QAXRowRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Cell, QAXTextFieldRole, false },
- { -1, 0, false }
- },
- { { QAccessible::PushButton, QAXButtonRole, false },
- { -1, 0, false }
- },
- { { QAccessible::EditableText, QAXTextFieldRole, true },
- { -1, 0, false }
- },
- { { QAccessible::Link, QAXTextFieldRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Indicator, QAXValueIndicatorRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Splitter, QAXSplitGroupRole, false },
- { -1, 0, false }
- },
- { { QAccessible::List, QAXListRole, false },
- { -1, 0, false }
- },
- { { QAccessible::ListItem, QAXStaticTextRole, false },
- { -1, 0, false }
- },
- { { QAccessible::Cell, QAXStaticTextRole, false },
- { -1, 0, false }
- },
- { { -1, 0, false } }
-};
-
-class QAInterface;
-static CFStringRef macRole(const QAInterface &interface);
-
-QDebug operator<<(QDebug debug, const QAInterface &interface)
-{
- if (interface.isValid() == false)
- debug << "invalid interface";
- else
- debug << interface.object() << "id" << interface.id() << "role" << hex << interface.role();
- return debug;
-}
-
-// The root of the Qt accessible hiearchy.
-static QObject *rootObject = 0;
-
-
-bool QAInterface::operator==(const QAInterface &other) const
-{
- if (isValid() == false || other.isValid() == false)
- return (isValid() && other.isValid());
-
- // walk up the parent chain, comparing child indexes, until we reach
- // an interface that has a QObject.
- QAInterface currentThis = *this;
- QAInterface currentOther = other;
-
- while (currentThis.object() == 0) {
- if (currentOther.object() != 0)
- return false;
-
- // fail if the child indexes in the two hirearchies don't match.
- if (currentThis.parent().indexOfChild(currentThis) !=
- currentOther.parent().indexOfChild(currentOther))
- return false;
-
- currentThis = currentThis.parent();
- currentOther = currentOther.parent();
- }
-
- return (currentThis.object() == currentOther.object() && currentThis.id() == currentOther.id());
-}
-
-bool QAInterface::operator!=(const QAInterface &other) const
-{
- return !operator==(other);
-}
-
-uint qHash(const QAInterface &item)
-{
- if (item.isValid())
- return qHash(item.object()) + qHash(item.id());
- else
- return qHash(item.cachedObject()) + qHash(item.id());
-}
-
-QAInterface QAInterface::navigate(RelationFlag relation, int entry) const
-{
- if (!checkValid())
- return QAInterface();
-
- // On a QAccessibleInterface that handles its own children we can short-circut
- // the navigation if this QAInterface refers to one of the children:
- if (child != 0) {
- // The Ancestor interface will always be the same QAccessibleInterface with
- // a child value of 0.
- if (relation == QAccessible::Ancestor)
- return QAInterface(*this, 0);
-
- // The child hiearchy is only one level deep, so navigating to a child
- // of a child is not possible.
- if (relation == QAccessible::Child) {
- return QAInterface();
- }
- }
- QAccessibleInterface *child_iface = 0;
-
- const int status = base.interface->navigate(relation, entry, &child_iface);
-
- if (status == -1)
- return QAInterface(); // not found;
-
- // Check if target is a child of this interface.
- if (!child_iface) {
- return QAInterface(*this, status);
- } else {
- // Target is child_iface or a child of that (status decides).
- return QAInterface(child_iface, status);
- }
-}
-
-QAElement::QAElement()
-:elementRef(0)
-{}
-
-QAElement::QAElement(AXUIElementRef elementRef)
-:elementRef(elementRef)
-{
- if (elementRef != 0) {
- CFRetain(elementRef);
- CFRetain(object());
- }
-}
-
-QAElement::QAElement(const QAElement &element)
-:elementRef(element.elementRef)
-{
- if (elementRef != 0) {
- CFRetain(elementRef);
- CFRetain(object());
- }
-}
-
-QAElement::QAElement(HIObjectRef object, int child)
-{
-#ifndef QT_MAC_USE_COCOA
- if (object == 0) {
- elementRef = 0; // Create invalid QAElement.
- } else {
- elementRef = AXUIElementCreateWithHIObjectAndIdentifier(object, child);
- CFRetain(object);
- }
-#else
- Q_UNUSED(object);
- Q_UNUSED(child);
-#endif
-}
-
-QAElement::~QAElement()
-{
- if (elementRef != 0) {
- CFRelease(object());
- CFRelease(elementRef);
- }
-}
-
-void QAElement::operator=(const QAElement &other)
-{
- if (*this == other)
- return;
-
- if (elementRef != 0) {
- CFRelease(object());
- CFRelease(elementRef);
- }
-
- elementRef = other.elementRef;
-
- if (elementRef != 0) {
- CFRetain(elementRef);
- CFRetain(object());
- }
-}
-
-bool QAElement::operator==(const QAElement &other) const
-{
- if (elementRef == 0 || other.elementRef == 0)
- return (elementRef == other.elementRef);
-
- return CFEqual(elementRef, other.elementRef);
-}
-
-uint qHash(QAElement element)
-{
- return qHash(element.object()) + qHash(element.id());
-}
-
-#ifndef QT_MAC_USE_COCOA
-static QInterfaceFactory *createFactory(const QAInterface &interface);
-#endif
-Q_GLOBAL_STATIC(QAccessibleHierarchyManager, accessibleHierarchyManager);
-
-/*
- Reomves all accessibility info accosiated with the sender object.
-*/
-void QAccessibleHierarchyManager::objectDestroyed(QObject *object)
-{
- HIObjectRef hiObject = qobjectHiobjectHash.value(object);
- delete qobjectElementHash.value(object);
- qobjectElementHash.remove(object);
- hiobjectInterfaceHash.remove(hiObject);
-}
-
-/*
- Removes all stored items.
-*/
-void QAccessibleHierarchyManager::reset()
-{
- qDeleteAll(qobjectElementHash);
- qobjectElementHash.clear();
- hiobjectInterfaceHash.clear();
- qobjectHiobjectHash.clear();
-}
-
-QAccessibleHierarchyManager *QAccessibleHierarchyManager::instance()
-{
- return accessibleHierarchyManager();
-}
-
-#ifndef QT_MAC_USE_COCOA
-static bool isItemView(const QAInterface &interface)
-{
- QObject *object = interface.object();
- return (interface.role() == QAccessible::List || interface.role() == QAccessible::Table
- || (object && qobject_cast<QAbstractItemView *>(interface.object()))
- || (object && object->objectName() == QLatin1String("qt_scrollarea_viewport")
- && qobject_cast<QAbstractItemView *>(object->parent())));
-}
-#endif
-
-static bool isTabWidget(const QAInterface &interface)
-{
- if (QObject *object = interface.object())
- return (object->inherits("QTabWidget") && interface.id() == 0);
- return false;
-}
-
-static bool isStandaloneTabBar(const QAInterface &interface)
-{
- QObject *object = interface.object();
- if (interface.role() == QAccessible::PageTabList && object)
- return (qobject_cast<QTabWidget *>(object->parent()) == 0);
-
- return false;
-}
-
-static bool isEmbeddedTabBar(const QAInterface &interface)
-{
- QObject *object = interface.object();
- if (interface.role() == QAccessible::PageTabList && object)
- return (qobject_cast<QTabWidget *>(object->parent()));
-
- return false;
-}
-
-/*
- Decides if a QAInterface is interesting from an accessibility users point of view.
-*/
-bool isItInteresting(const QAInterface &interface)
-{
- // Mac accessibility does not have an attribute that corresponds to the Invisible/Offscreen
- // state, so we disable the interface here.
- const QAccessible::State state = interface.state();
- if (state & QAccessible::Invisible ||
- state & QAccessible::Offscreen )
- return false;
-
- const QAccessible::Role role = interface.role();
-
- if (QObject * const object = interface.object()) {
- const QString className = QLatin1String(object->metaObject()->className());
-
- // VoiceOver focusing on tool tips can be confusing. The contents of the
- // tool tip is avalible through the description attribute anyway, so
- // we disable accessibility for tool tips.
- if (className == QLatin1String("QTipLabel"))
- return false;
-
- // Hide TabBars that has a QTabWidget parent (the tab widget handles the accessibility)
- if (isEmbeddedTabBar(interface))
- return false;
-
- // Hide docked dockwidgets. ### causes infinitie loop in the apple accessibility code.
- /* if (QDockWidget *dockWidget = qobject_cast<QDockWidget *>(object)) {
- if (dockWidget->isFloating() == false)
- return false;
- }
- */
- }
-
- // Client is a generic role returned by plain QWidgets or other
- // widgets that does not have separate QAccessible interface, such
- // as the TabWidget. Return false unless macRole gives the interface
- // a special role.
- if (role == QAccessible::Client && macRole(interface) == CFStringRef(QAXUnknownRole))
- return false;
-
- // Some roles are not interesting:
- if (role == QAccessible::Border || // QFrame
- role == QAccessible::Application || // We use the system-provided application element.
- role == QAccessible::MenuItem) // The system also provides the menu items.
- return false;
-
- // It is probably better to access the toolbar buttons directly than having
- // to navigate through the toolbar.
- if (role == QAccessible::ToolBar)
- return false;
-
- return true;
-}
-
-QAElement QAccessibleHierarchyManager::registerInterface(QObject *object, int child)
-{
-#ifndef QT_MAC_USE_COCOA
- return registerInterface(QAInterface(QAccessible::queryAccessibleInterface(object), child));
-#else
- Q_UNUSED(object);
- Q_UNUSED(child);
- return QAElement();
-#endif
-}
-
-/*
- Creates a QAXUIelement that corresponds to the given QAInterface.
-*/
-QAElement QAccessibleHierarchyManager::registerInterface(const QAInterface &interface)
-{
-#ifndef QT_MAC_USE_COCOA
- if (interface.isValid() == false)
- return QAElement();
- QAInterface objectInterface = interface.objectInterface();
-
- QObject * qobject = objectInterface.object();
- HIObjectRef hiobject = objectInterface.hiObject();
- if (qobject == 0 || hiobject == 0)
- return QAElement();
-
- if (qobjectElementHash.contains(qobject) == false) {
- registerInterface(qobject, hiobject, createFactory(interface));
- HIObjectSetAccessibilityIgnored(hiobject, !isItInteresting(interface));
- }
-
- return QAElement(hiobject, interface.id());
-#else
- Q_UNUSED(interface);
- return QAElement();
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-#include "qaccessible_mac_carbon.cpp"
-#endif
-
-void QAccessibleHierarchyManager::registerInterface(QObject * qobject, HIObjectRef hiobject, QInterfaceFactory *interfaceFactory)
-{
-#ifndef QT_MAC_USE_COCOA
- if (qobjectElementHash.contains(qobject) == false) {
- qobjectElementHash.insert(qobject, interfaceFactory);
- qobjectHiobjectHash.insert(qobject, hiobject);
- connect(qobject, SIGNAL(destroyed(QObject *)), SLOT(objectDestroyed(QObject *)));
- }
-
- if (hiobjectInterfaceHash.contains(hiobject) == false) {
- hiobjectInterfaceHash.insert(hiobject, interfaceFactory);
- installAcessibilityEventHandler(hiobject);
- }
-#else
- Q_UNUSED(qobject);
- Q_UNUSED(hiobject);
- Q_UNUSED(interfaceFactory);
-#endif
-}
-
-void QAccessibleHierarchyManager::registerChildren(const QAInterface &interface)
-{
- QObject * const object = interface.object();
- if (object == 0)
- return;
-
- QInterfaceFactory *interfaceFactory = qobjectElementHash.value(object);
-
- if (interfaceFactory == 0)
- return;
-
- interfaceFactory->registerChildren();
-}
-
-QAInterface QAccessibleHierarchyManager::lookup(const AXUIElementRef &element)
-{
- if (element == 0)
- return QAInterface();
-#ifndef QT_MAC_USE_COCOA
- HIObjectRef hiObject = AXUIElementGetHIObject(element);
-
- QInterfaceFactory *factory = hiobjectInterfaceHash.value(hiObject);
- if (factory == 0) {
- return QAInterface();
- }
-
- UInt64 id;
- AXUIElementGetIdentifier(element, &id);
- return factory->interface(id);
-#else
- return QAInterface();
-#endif
-}
-
-QAInterface QAccessibleHierarchyManager::lookup(const QAElement &element)
-{
- return lookup(element.element());
-}
-
-QAElement QAccessibleHierarchyManager::lookup(const QAInterface &interface)
-{
- if (interface.isValid() == false)
- return QAElement();
-
- QInterfaceFactory *factory = qobjectElementHash.value(interface.objectInterface().object());
- if (factory == 0)
- return QAElement();
-
- return factory->element(interface);
-}
-
-QAElement QAccessibleHierarchyManager::lookup(QObject * const object, int id)
-{
- QInterfaceFactory *factory = qobjectElementHash.value(object);
- if (factory == 0)
- return QAElement();
-
- return factory->element(id);
-}
-
-/*
- Standard interface mapping, return the stored interface
- or HIObjectRef, and there is an one-to-one mapping between
- the identifier and child.
-*/
-class QStandardInterfaceFactory : public QInterfaceFactory
-{
-public:
- QStandardInterfaceFactory(const QAInterface &interface)
- : m_interface(interface), object(interface.hiObject())
- {
- CFRetain(object);
- }
-
- ~QStandardInterfaceFactory()
- {
- CFRelease(object);
- }
-
-
- QAInterface interface(UInt64 identifier)
- {
- const int child = identifier;
- return QAInterface(m_interface, child);
- }
-
- QAElement element(int id)
- {
- return QAElement(object, id);
- }
-
- QAElement element(const QAInterface &interface)
- {
- if (interface.object() == 0)
- return QAElement();
- return QAElement(object, interface.id());
- }
-
- void registerChildren()
- {
- const int childCount = m_interface.childCount();
- for (int i = 1; i <= childCount; ++i) {
- accessibleHierarchyManager()->registerInterface(m_interface.navigate(QAccessible::Child, i));
- }
- }
-
-private:
- QAInterface m_interface;
- HIObjectRef object;
-};
-
-/*
- Interface mapping where that creates one HIObject for each interface child.
-*/
-class QMultipleHIObjectFactory : public QInterfaceFactory
-{
-public:
- QMultipleHIObjectFactory(const QAInterface &interface)
- : m_interface(interface)
- { }
-
- ~QMultipleHIObjectFactory()
- {
- foreach (HIObjectRef object, objects) {
- CFRelease(object);
- }
- }
-
- QAInterface interface(UInt64 identifier)
- {
- const int child = identifier;
- return QAInterface(m_interface, child);
- }
-
- QAElement element(int child)
- {
- if (child == 0)
- return QAElement(m_interface.hiObject(), 0);
-
- if (child > objects.count())
- return QAElement();
-
- return QAElement(objects.at(child - 1), child);
- }
-
- void registerChildren()
- {
-#ifndef QT_MAC_USE_COCOA
- const int childCount = m_interface.childCount();
- for (int i = 1; i <= childCount; ++i) {
- HIObjectRef hiobject;
- HIObjectCreate(kObjectQtAccessibility, 0, &hiobject);
- objects.append(hiobject);
- accessibleHierarchyManager()->registerInterface(m_interface.object(), hiobject, this);
- HIObjectSetAccessibilityIgnored(hiobject, !isItInteresting(m_interface.navigate(QAccessible::Child, i)));
- }
-#endif
- }
-
-private:
- QAInterface m_interface;
- QList<HIObjectRef> objects;
-};
-
-class QItemViewInterfaceFactory : public QInterfaceFactory
-{
-public:
- QItemViewInterfaceFactory(const QAInterface &interface)
- : m_interface(interface), object(interface.hiObject())
- {
- CFRetain(object);
- columnCount = 0;
- if (QTableView * tableView = qobject_cast<QTableView *>(interface.parent().object())) {
- if (tableView->model())
- columnCount = tableView->model()->columnCount();
- if (tableView->verticalHeader())
- ++columnCount;
- }
- }
-
- ~QItemViewInterfaceFactory()
- {
- CFRelease(object);
- }
-
- QAInterface interface(UInt64 identifier)
- {
- if (identifier == 0)
- return m_interface;
-
- if (m_interface.role() == QAccessible::List)
- return m_interface.childAt(identifier);
-
- if (m_interface.role() == QAccessible::Table) {
- const int index = identifier;
- if (index == 0)
- return m_interface; // return the item view interface.
-
- const int rowIndex = (index - 1) / (columnCount + 1);
- const int cellIndex = (index - 1) % (columnCount + 1);
-/*
- qDebug() << "index" << index;
- qDebug() << "rowIndex" << rowIndex;
- qDebug() << "cellIndex" << cellIndex;
-*/
- const QAInterface rowInterface = m_interface.childAt(rowIndex + 1);
-
- if ((cellIndex) == 0) // Is it a row?
- return rowInterface;
- else {
- return rowInterface.childAt(cellIndex);
- }
- }
-
- return QAInterface();
- }
-
- QAElement element(int id)
- {
- if (id != 0) {
- return QAElement();
- }
- return QAElement(object, 0);
- }
-
- QAElement element(const QAInterface &interface)
- {
- if (interface.object() && interface.object() == m_interface.object()) {
- return QAElement(object, 0);
- } else if (m_interface.role() == QAccessible::List) {
- if (interface.parent().object() && interface.parent().object() == m_interface.object())
- return QAElement(object, m_interface.indexOfChild(interface));
- } else if (m_interface.role() == QAccessible::Table) {
- QAInterface currentInterface = interface;
- int index = 0;
-
- while (currentInterface.isValid() && currentInterface.object() == 0) {
- const QAInterface parentInterface = currentInterface.parent();
-/*
- qDebug() << "current index" << index;
- qDebug() << "current interface" << interface;
-
- qDebug() << "parent interface" << parentInterface;
- qDebug() << "grandparent interface" << parentInterface.parent();
- qDebug() << "childCount" << interface.childCount();
- qDebug() << "index of child" << parentInterface.indexOfChild(currentInterface);
-*/
- index += ((parentInterface.indexOfChild(currentInterface) - 1) * (currentInterface.childCount() + 1)) + 1;
- currentInterface = parentInterface;
-// qDebug() << "new current interface" << currentInterface;
- }
- if (currentInterface.object() == m_interface.object())
- return QAElement(object, index);
-
-
- }
- return QAElement();
- }
-
- void registerChildren()
- {
- // Item view child interfraces don't have their own qobjects, so there is nothing to register here.
- }
-
-private:
- QAInterface m_interface;
- HIObjectRef object;
- int columnCount; // for table views;
-};
-
-#ifndef QT_MAC_USE_COCOA
-static bool managesChildren(const QAInterface &interface)
-{
- return (interface.childCount() > 0 && interface.childAt(1).id() > 0);
-}
-
-static QInterfaceFactory *createFactory(const QAInterface &interface)
-{
- if (isItemView(interface)) {
- return new QItemViewInterfaceFactory(interface);
- } if (managesChildren(interface)) {
- return new QMultipleHIObjectFactory(interface);
- }
-
- return new QStandardInterfaceFactory(interface);
-}
-#endif
-
-QList<QAElement> lookup(const QList<QAInterface> &interfaces)
-{
- QList<QAElement> elements;
- foreach (const QAInterface &interface, interfaces)
- if (interface.isValid()) {
- const QAElement element = accessibleHierarchyManager()->lookup(interface);
- if (element.isValid())
- elements.append(element);
- }
- return elements;
-}
-
-// Debug output helpers:
-/*
-static QString nameForEventKind(UInt32 kind)
-{
- switch(kind) {
- case kEventAccessibleGetChildAtPoint: return QString("GetChildAtPoint"); break;
- case kEventAccessibleGetAllAttributeNames: return QString("GetAllAttributeNames"); break;
- case kEventAccessibleGetNamedAttribute: return QString("GetNamedAttribute"); break;
- case kEventAccessibleSetNamedAttribute: return QString("SetNamedAttribute"); break;
- case kEventAccessibleGetAllActionNames: return QString("GetAllActionNames"); break;
- case kEventAccessibleGetFocusedChild: return QString("GetFocusedChild"); break;
- default:
- return QString("Unknown accessibility event type: %1").arg(kind);
- break;
- };
-}
-*/
-#ifndef QT_MAC_USE_COCOA
-static bool qt_mac_append_cf_uniq(CFMutableArrayRef array, CFTypeRef value)
-{
- if (value == 0)
- return false;
-
- CFRange range;
- range.location = 0;
- range.length = CFArrayGetCount(array);
- if(!CFArrayContainsValue(array, range, value)) {
- CFArrayAppendValue(array, value);
- return true;
- }
- return false;
-}
-
-static OSStatus setAttributeValue(EventRef event, const QList<QAElement> &elements)
-{
- CFMutableArrayRef array = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
- foreach (const QAElement &element, elements) {
- if (element.isValid())
- CFArrayAppendValue(array, element.element());
- }
-
- const OSStatus err = SetEventParameter(event, kEventParamAccessibleAttributeValue,
- typeCFTypeRef, sizeof(array), &array);
- CFRelease(array);
- return err;
-}
-#endif //QT_MAC_USE_COCOA
-
-/*
- Gets the AccessibleObject parameter from an event.
-*/
-static inline AXUIElementRef getAccessibleObjectParameter(EventRef event)
-{
- AXUIElementRef element;
- GetEventParameter(event, kEventParamAccessibleObject, typeCFTypeRef, 0,
- sizeof(element), 0, &element);
- return element;
-}
-
-/*
- The application event handler makes sure that all top-level qt windows are registered
- before any accessibility events are handeled.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus applicationEventHandler(EventHandlerCallRef next_ref, EventRef event, void *)
-{
- QAInterface rootInterface(QAccessible::queryAccessibleInterface(rootObject ? rootObject : qApp), 0);
- accessibleHierarchyManager()->registerChildren(rootInterface);
-
- return CallNextEventHandler(next_ref, event);
-}
-
-/*
- Returns the value for element by combining the QAccessibility::Checked and
- QAccessibility::Mixed flags into an int value that the Mac accessibilty
- system understands. This works for check boxes, radio buttons, and the like.
- The return values are:
- 0: unchecked
- 1: checked
- 2: undecided
-*/
-static int buttonValue(QAInterface element)
-{
- const QAccessible::State state = element.state();
- if (state & QAccessible::Mixed)
- return 2;
- else if(state & QAccessible::Checked)
- return 1;
- else
- return 0;
-}
-
-static QString getValue(const QAInterface &interface)
-{
- const QAccessible::Role role = interface.role();
- if (role == QAccessible::RadioButton || role == QAccessible::CheckBox)
- return QString::number(buttonValue(interface));
- else
- return interface.text(QAccessible::Value);
-}
-#endif //QT_MAC_USE_COCOA
-
-/*
- Translates a QAccessible::Role into a mac accessibility role.
-*/
-static CFStringRef macRole(const QAInterface &interface)
-{
- const QAccessible::Role qtRole = interface.role();
-
-// qDebug() << "role for" << interface.object() << "interface role" << hex << qtRole;
-
- // Qt accessibility: QAccessible::Splitter contains QAccessible::Grip.
- // Mac accessibility: AXSplitGroup contains AXSplitter.
- if (qtRole == QAccessible::Grip) {
- const QAInterface parent = interface.parent();
- if (parent.isValid() && parent.role() == QAccessible::Splitter)
- return CFStringRef(QAXSplitterRole);
- }
-
- // Tab widgets and standalone tab bars get the kAXTabGroupRole. Accessibility
- // for tab bars emebedded in a tab widget is handled by the tab widget.
- if (isTabWidget(interface) || isStandaloneTabBar(interface))
- return kAXTabGroupRole;
-
- if (QObject *object = interface.object()) {
- // ### The interface for an abstract scroll area returns the generic "Client"
- // role, so we have to to an extra detect on the QObject here.
- if (object->inherits("QAbstractScrollArea") && interface.id() == 0)
- return CFStringRef(QAXScrollAreaRole);
-
- if (object->inherits("QDockWidget"))
- return CFStringRef(QAXUnknownRole);
- }
-
- int i = 0;
- int testRole = text_bindings[i][0].qt;
- while (testRole != -1) {
- if (testRole == qtRole)
- return CFStringRef(text_bindings[i][0].mac);
- ++i;
- testRole = text_bindings[i][0].qt;
- }
-
-// qDebug() << "got unknown role!" << interface << interface.parent();
-
- return CFStringRef(QAXUnknownRole);
-}
-
-/*
- Translates a QAccessible::Role and an attribute name into a QAccessible::Text, taking into
- account execptions listed in text_bindings.
-*/
-#ifndef QT_MAC_USE_COCOA
-static int textForRoleAndAttribute(QAccessible::Role role, CFStringRef attribute)
-{
- // Search for exception, return it if found.
- int testRole = text_bindings[0][0].qt;
- int i = 0;
- while (testRole != -1) {
- if (testRole == role) {
- int j = 1;
- int qtRole = text_bindings[i][j].qt;
- CFStringRef testAttribute = CFStringRef(text_bindings[i][j].mac);
- while (qtRole != -1) {
- if (CFStringCompare(attribute, testAttribute, 0) == kCFCompareEqualTo) {
- return (QAccessible::Text)qtRole;
- }
- ++j;
- testAttribute = CFStringRef(text_bindings[i][j].mac); /// ### custom compare
- qtRole = text_bindings[i][j].qt; /// ### custom compare
- }
- break;
- }
- ++i;
- testRole = text_bindings[i][0].qt;
- }
-
- // Return default mappping
- if (CFStringCompare(attribute, CFStringRef(QAXTitleAttribute), 0) == kCFCompareEqualTo)
- return QAccessible::Name;
- else if (CFStringCompare(attribute, CFStringRef(QAXValueAttribute), 0) == kCFCompareEqualTo)
- return QAccessible::Value;
- else if (CFStringCompare(attribute, CFStringRef(QAXHelpAttribute), 0) == kCFCompareEqualTo)
- return QAccessible::Help;
- else if (CFStringCompare(attribute, CFStringRef(QAXDescriptionAttribute), 0) == kCFCompareEqualTo)
- return QAccessible::Description;
- else
- return -1;
-}
-
-/*
- Returns the subrole string constant for the interface if it has one,
- else returns an empty string.
-*/
-static QCFString subrole(const QAInterface &interface)
-{
- const QAInterface parent = interface.parent();
- if (parent.isValid() == false)
- return QCFString();
-
- if (parent.role() == QAccessible::ScrollBar) {
- QCFString subrole;
- switch(interface.id()) {
- case 1: subrole = CFStringRef(QAXDecrementArrowSubrole); break;
- case 2: subrole = CFStringRef(QAXDecrementPageSubrole); break;
- case 4: subrole = CFStringRef(QAXIncrementPageSubrole); break;
- case 5: subrole = CFStringRef(QAXIncrementArrowSubrole); break;
- default:
- break;
- }
- return subrole;
- }
- return QCFString();
-}
-
-// Gets the scroll bar orientation by asking the QAbstractSlider object directly.
-static Qt::Orientation scrollBarOrientation(const QAInterface &scrollBar)
-{
- QObject *const object = scrollBar.object();
- if (QAbstractSlider * const sliderObject = qobject_cast<QAbstractSlider * const>(object))
- return sliderObject->orientation();
-
- return Qt::Vertical; // D'oh! The interface wasn't a scroll bar.
-}
-
-static QAInterface scrollAreaGetScrollBarInterface(const QAInterface &scrollArea, Qt::Orientation orientation)
-{
- if (macRole(scrollArea) != CFStringRef(CFStringRef(QAXScrollAreaRole)))
- return QAInterface();
-
- // Child 1 is the contents widget, 2 and 3 are the scroll bar containers wich contains possible scroll bars.
- for (int i = 2; i <= 3; ++i) {
- QAInterface scrollBarContainer = scrollArea.childAt(i);
- for (int i = 1; i <= scrollBarContainer.childCount(); ++i) {
- QAInterface scrollBar = scrollBarContainer.childAt(i);
- if (scrollBar.isValid() &&
- scrollBar.role() == QAccessible::ScrollBar &&
- scrollBarOrientation(scrollBar) == orientation)
- return scrollBar;
- }
- }
-
- return QAInterface();
-}
-
-static bool scrollAreaHasScrollBar(const QAInterface &scrollArea, Qt::Orientation orientation)
-{
- return scrollAreaGetScrollBarInterface(scrollArea, orientation).isValid();
-}
-
-static QAElement scrollAreaGetScrollBar(const QAInterface &scrollArea, Qt::Orientation orientation)
-{
- return accessibleHierarchyManager()->lookup(scrollAreaGetScrollBarInterface(scrollArea, orientation));
-}
-
-static QAElement scrollAreaGetContents(const QAInterface &scrollArea)
-{
- // Child 1 is the contents widget,
- return accessibleHierarchyManager()->lookup(scrollArea.navigate(QAccessible::Child, 1));
-}
-
-static QAElement tabWidgetGetContents(const QAInterface &interface)
-{
- // A kAXTabGroup has a kAXContents attribute, which consists of the
- // ui elements for the current tab page. Get the current tab page
- // from the QStackedWidget, where the current visible page can
- // be found at index 1.
- QAInterface stackedWidget = interface.childAt(1);
- accessibleHierarchyManager()->registerChildren(stackedWidget);
- QAInterface tabPageInterface = stackedWidget.childAt(1);
- return accessibleHierarchyManager()->lookup(tabPageInterface);
-}
-
-static QList<QAElement> tabBarGetTabs(const QAInterface &interface)
-{
- // Get the tabs by searching for children with the "PageTab" role.
- // This filters out the left/right navigation buttons.
- accessibleHierarchyManager()->registerChildren(interface);
- QList<QAElement> tabs;
- const int numChildren = interface.childCount();
- for (int i = 1; i < numChildren + 1; ++i) {
- QAInterface child = interface.navigate(QAccessible::Child, i);
- if (child.isValid() && child.role() == QAccessible::PageTab) {
- tabs.append(accessibleHierarchyManager()->lookup(child));
- }
- }
- return tabs;
-}
-
-static QList<QAElement> tabWidgetGetTabs(const QAInterface &interface)
-{
- // Each QTabWidget has two children, a QStackedWidget and a QTabBar.
- // Get the tabs from the QTabBar.
- return tabBarGetTabs(interface.childAt(2));
-}
-
-static QList<QAElement> tabWidgetGetChildren(const QAInterface &interface)
-{
- // The children for a kAXTabGroup should consist of the tabs and the
- // contents of the current open tab page.
- QList<QAElement> children = tabWidgetGetTabs(interface);
- children += tabWidgetGetContents(interface);
- return children;
-}
-#endif //QT_MAC_USE_COCOA
-
-/*
- Returns the label (buddy) interface for interface, or 0 if it has none.
-*/
-/*
-static QAInterface findLabel(const QAInterface &interface)
-{
- return interface.navigate(QAccessible::Label, 1);
-}
-*/
-/*
- Returns a list of interfaces this interface labels, or an empty list if it doesn't label any.
-*/
-/*
-static QList<QAInterface> findLabelled(const QAInterface &interface)
-{
- QList<QAInterface> interfaceList;
-
- int count = 1;
- const QAInterface labelled = interface.navigate(QAccessible::Labelled, count);
- while (labelled.isValid()) {
- interfaceList.append(labelled);
- ++count;
- }
- return interfaceList;
-}
-*/
-/*
- Tests if the given QAInterface has data for a mac attribute.
-*/
-#ifndef QT_MAC_USE_COCOA
-static bool supportsAttribute(CFStringRef attribute, const QAInterface &interface)
-{
- const int text = textForRoleAndAttribute(interface.role(), attribute);
-
- // Special case: Static texts don't have a title.
- if (interface.role() == QAccessible::StaticText && attribute == CFStringRef(QAXTitleAttribute))
- return false;
-
- // Return true if we the attribute matched a QAccessible::Role and we get text for that role from the interface.
- if (text != -1) {
- if (text == QAccessible::Value) // Special case for Value, see getValue()
- return !getValue(interface).isEmpty();
- else
- return !interface.text((QAccessible::Text)text).isEmpty();
- }
-
- if (CFStringCompare(attribute, CFStringRef(QAXChildrenAttribute), 0) == kCFCompareEqualTo) {
- if (interface.childCount() > 0)
- return true;
- }
-
- if (CFStringCompare(attribute, CFStringRef(QAXSubroleAttribute), 0) == kCFCompareEqualTo) {
- return (subrole(interface) != QCFString());
- }
-
- return false;
-}
-
-static void appendIfSupported(CFMutableArrayRef array, CFStringRef attribute, const QAInterface &interface)
-{
- if (supportsAttribute(attribute, interface))
- qt_mac_append_cf_uniq(array, attribute);
-}
-
-/*
- Returns the names of the attributes the give QAInterface supports.
-*/
-static OSStatus getAllAttributeNames(EventRef event, const QAInterface &interface, EventHandlerCallRef next_ref)
-{
- // Call system event handler.
- OSStatus err = CallNextEventHandler(next_ref, event);
- if(err != noErr && err != eventNotHandledErr)
- return err;
- CFMutableArrayRef attrs = 0;
- GetEventParameter(event, kEventParamAccessibleAttributeNames, typeCFMutableArrayRef, 0,
- sizeof(attrs), 0, &attrs);
-
- if (!attrs)
- return eventNotHandledErr;
-
- // Append attribute names that are always supported.
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXPositionAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXSizeAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXRoleAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXEnabledAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXWindowAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXTopLevelUIElementAttribute));
-
- // Append these names if the QInterafceItem returns any data for them.
- appendIfSupported(attrs, CFStringRef(QAXTitleAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXValueAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXDescriptionAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXLinkedUIElementsAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXHelpAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXTitleUIElementAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXChildrenAttribute), interface);
- appendIfSupported(attrs, CFStringRef(QAXSubroleAttribute), interface);
-
- // Append attribute names based on the interaface role.
- switch (interface.role()) {
- case QAccessible::Window:
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMainAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMinimizedAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXCloseButtonAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXZoomButtonAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMinimizeButtonAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXToolbarButtonAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXGrowAreaAttribute));
- break;
- case QAccessible::RadioButton:
- case QAccessible::CheckBox:
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMinValueAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMaxValueAttribute));
- break;
- case QAccessible::ScrollBar:
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXOrientationAttribute));
- break;
- case QAccessible::Splitter:
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXSplittersAttribute));
- break;
- case QAccessible::Table:
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXRowsAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXVisibleRowsAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXSelectedRowsAttribute));
- break;
- default:
- break;
- }
-
- // Append attribute names based on the mac accessibility role.
- const QCFString mac_role = macRole(interface);
- if (mac_role == CFStringRef(QAXSplitterRole)) {
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXPreviousContentsAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXNextContentsAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXOrientationAttribute));
- } else if (mac_role == CFStringRef(QAXScrollAreaRole)) {
- if (scrollAreaHasScrollBar(interface, Qt::Horizontal))
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXHorizontalScrollBarAttribute));
- if (scrollAreaHasScrollBar(interface, Qt::Vertical))
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXVerticalScrollBarAttribute));
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXContentsAttribute));
- } else if (mac_role == CFStringRef(QAXTabGroupRole)) {
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXTabsAttribute));
- // Only tab widgets can have the contents attribute, there is no way of getting
- // the contents from a QTabBar.
- if (isTabWidget(interface))
- qt_mac_append_cf_uniq(attrs, CFStringRef(QAXContentsAttribute));
- }
-
- return noErr;
-}
-
-static void handleStringAttribute(EventRef event, QAccessible::Text text, const QAInterface &interface)
-{
- QString str = interface.text(text);
- if (str.isEmpty())
- return;
-
- // Remove any html markup from the text string, or VoiceOver will read the html tags.
- static QTextDocument document;
- document.setHtml(str);
- str = document.toPlainText();
-
- CFStringRef cfstr = QCFString::toCFStringRef(str);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef, sizeof(cfstr), &cfstr);
-}
-
-/*
- Handles the parent attribute for a interface.
- There are basically three cases here:
- 1. interface is a HIView and has only HIView children.
- 2. interface is a HIView but has children that is not a HIView
- 3. interface is not a HIView.
-*/
-static OSStatus handleChildrenAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
- // Add the children for this interface to the global QAccessibelHierachyManager.
- accessibleHierarchyManager()->registerChildren(interface);
-
- if (isTabWidget(interface)) {
- QList<QAElement> children = tabWidgetGetChildren(interface);
- const int childCount = children.count();
-
- CFMutableArrayRef array = 0;
- array = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
- for (int i = 0; i < childCount; ++i) {
- qt_mac_append_cf_uniq(array, children.at(i).element());
- }
-
- OSStatus err;
- err = SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFArrayRef, sizeof(array), &array);
- if (err != noErr)
- qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__);
-
- return noErr;
- }
-
- const QList<QAElement> children = lookup(interface.children());
- const int childCount = children.count();
-
- OSStatus err = eventNotHandledErr;
- if (interface.isHIView())
- err = CallNextEventHandler(next_ref, event);
-
- CFMutableArrayRef array = 0;
- int arraySize = 0;
- if (err == noErr) {
- CFTypeRef obj = 0;
- err = GetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, NULL , sizeof(obj), NULL, &obj);
- if (err == noErr && obj != 0) {
- array = (CFMutableArrayRef)obj;
- arraySize = CFArrayGetCount(array);
- }
- }
-
- if (array) {
- CFArrayRemoveAllValues(array);
- for (int i = 0; i < childCount; ++i) {
- qt_mac_append_cf_uniq(array, children.at(i).element());
- }
- } else {
- array = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
- for (int i = 0; i < childCount; ++i) {
- qt_mac_append_cf_uniq(array, children.at(i).element());
- }
-
- err = SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFArrayRef, sizeof(array), &array);
- if (err != noErr)
- qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__);
- }
-
- return noErr;
-}
-
-/*
-
-*/
-static OSStatus handleParentAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
- OSStatus err = eventNotHandledErr;
- if (interface.isHIView()) {
- err = CallNextEventHandler(next_ref, event);
- }
- if (err == noErr)
- return err;
-
- const QAInterface parentInterface = interface.navigate(QAccessible::Ancestor, 1);
- const QAElement parentElement = accessibleHierarchyManager()->lookup(parentInterface);
-
- if (parentElement.isValid() == false)
- return eventNotHandledErr;
-
- AXUIElementRef elementRef = parentElement.element();
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, sizeof(elementRef), &elementRef);
- return noErr;
-}
-#endif
-
-struct IsWindowTest
-{
- static inline bool test(const QAInterface &interface)
- {
- return (interface.role() == QAccessible::Window);
- }
-};
-
-struct IsWindowAndNotDrawerOrSheetTest
-{
- static inline bool test(const QAInterface &interface)
- {
- QWidget * const widget = qobject_cast<QWidget*>(interface.object());
- return (interface.role() == QAccessible::Window &&
- widget && widget->isWindow() &&
- !qt_mac_is_macdrawer(widget) &&
- !qt_mac_is_macsheet(widget));
- }
-};
-
-/*
- Navigates up the iterfaces ancestor hierachy until a QAccessibleInterface that
- passes the Test is found. If we reach a interface that is a HIView we stop the
- search and call AXUIElementCopyAttributeValue.
-*/
-template <typename TestType>
-OSStatus navigateAncestors(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface, CFStringRef attribute)
-{
- if (interface.isHIView())
- return CallNextEventHandler(next_ref, event);
-
- QAInterface current = interface;
- QAElement element;
- while (current.isValid()) {
- if (TestType::test(interface)) {
- element = accessibleHierarchyManager()->lookup(current);
- break;
- }
-
- // If we reach an InterfaceItem that is a HiView we can hand of the search to
- // the system event handler. This is the common case.
- if (current.isHIView()) {
- CFTypeRef value = 0;
- const QAElement currentElement = accessibleHierarchyManager()->lookup(current);
- AXError err = AXUIElementCopyAttributeValue(currentElement.element(), attribute, &value);
- AXUIElementRef newElement = (AXUIElementRef)value;
-
- if (err == noErr)
- element = QAElement(newElement);
-
- if (newElement != 0)
- CFRelease(newElement);
- break;
- }
-
- QAInterface next = current.parent();
- if (next.isValid() == false)
- break;
- if (next == current)
- break;
- current = next;
- }
-
- if (element.isValid() == false)
- return eventNotHandledErr;
-
-
- AXUIElementRef elementRef = element.element();
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef,
- sizeof(elementRef), &elementRef);
- return noErr;
-}
-
-/*
- Returns the top-level window for an interface, which is the closest ancestor interface that
- has the Window role, but is not a sheet or a drawer.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus handleWindowAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
- return navigateAncestors<IsWindowAndNotDrawerOrSheetTest>(next_ref, event, interface, CFStringRef(QAXWindowAttribute));
-}
-
-/*
- Returns the top-level window for an interface, which is the closest ancestor interface that
- has the Window role. (Can also be a sheet or a drawer)
-*/
-static OSStatus handleTopLevelUIElementAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
- return navigateAncestors<IsWindowTest>(next_ref, event, interface, CFStringRef(QAXTopLevelUIElementAttribute));
-}
-
-/*
- Returns the tab buttons for an interface.
-*/
-static OSStatus handleTabsAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
- Q_UNUSED(next_ref);
- if (isTabWidget(interface))
- return setAttributeValue(event, tabWidgetGetTabs(interface));
- else
- return setAttributeValue(event, tabBarGetTabs(interface));
-}
-
-static OSStatus handlePositionAttribute(EventHandlerCallRef, EventRef event, const QAInterface &interface)
-{
- QPoint qpoint(interface.rect().topLeft());
- HIPoint point;
- point.x = qpoint.x();
- point.y = qpoint.y();
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeHIPoint, sizeof(point), &point);
- return noErr;
-}
-
-static OSStatus handleSizeAttribute(EventHandlerCallRef, EventRef event, const QAInterface &interface)
-{
- QSize qSize(interface.rect().size());
- HISize size;
- size.width = qSize.width();
- size.height = qSize.height();
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeHISize, sizeof(size), &size);
- return noErr;
-}
-
-static OSStatus handleSubroleAttribute(EventHandlerCallRef, EventRef event, const QAInterface &interface)
-{
- const QCFString role = subrole(interface);
- CFStringRef rolestr = (CFStringRef)role;
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, sizeof(rolestr), &rolestr);
- return noErr;
-}
-
-static OSStatus handleOrientationAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
- QObject *const object = interface.object();
- Qt::Orientation orientation;
- if (interface.role() == QAccessible::ScrollBar) {
- orientation = scrollBarOrientation(interface);
- } else if (QSplitterHandle * const splitter = qobject_cast<QSplitterHandle * const>(object)) {
- // Qt reports the layout orientation, but we want the splitter handle orientation.
- orientation = (splitter->orientation() == Qt::Horizontal) ? Qt::Vertical : Qt::Horizontal;
- } else {
- return CallNextEventHandler(next_ref, event);
- }
- const CFStringRef orientationString = (orientation == Qt::Vertical)
- ? CFStringRef(QAXVerticalOrientationValue) : CFStringRef(QAXHorizontalOrientationValue);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef, sizeof(orientationString), &orientationString);
- return noErr;
-}
-
-/*
- Figures out the next or previous contents for a splitter.
-*/
-static OSStatus handleSplitterContentsAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface, QCFString nextOrPrev)
-{
- if (interface.isValid() == false || interface.role() != QAccessible::Grip)
- return eventNotHandledErr;
-
- const QAInterface parent = interface.parent();
- if (parent.isValid() == false)
- return CallNextEventHandler(next_ref, event);
-
- if (parent.role() != QAccessible::Splitter)
- return CallNextEventHandler(next_ref, event);
-
- const QSplitter * const splitter = qobject_cast<const QSplitter * const>(parent.object());
- if (splitter == 0)
- return CallNextEventHandler(next_ref, event);
-
- QWidget * const splitterHandle = qobject_cast<QWidget * const>(interface.object());
- const int splitterHandleIndex = splitter->indexOf(splitterHandle);
- const int widgetIndex = (nextOrPrev == QCFString(CFStringRef(QAXPreviousContentsAttribute))) ? splitterHandleIndex - 1 : splitterHandleIndex;
- const QAElement contentsElement = accessibleHierarchyManager()->lookup(splitter->widget(widgetIndex), 0);
- return setAttributeValue(event, QList<QAElement>() << contentsElement);
-}
-
-/*
- Creates a list of all splitter handles the splitter contains.
-*/
-static OSStatus handleSplittersAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
- const QSplitter * const splitter = qobject_cast<const QSplitter * const>(interface.object());
- if (splitter == 0)
- return CallNextEventHandler(next_ref, event);
-
- accessibleHierarchyManager()->registerChildren(interface);
-
- QList<QAElement> handles;
- const int visibleSplitterCount = splitter->count() -1; // skip first handle, it's always invisible.
- for (int i = 0; i < visibleSplitterCount; ++i)
- handles.append(accessibleHierarchyManager()->lookup(splitter->handle(i + 1), 0));
-
- return setAttributeValue(event, handles);
-}
-
-// This handler gets the scroll bars for a scroll area
-static OSStatus handleScrollBarAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &scrollArea, Qt::Orientation orientation)
-{
- QAElement scrollBar = scrollAreaGetScrollBar(scrollArea, orientation);
- if (scrollBar.isValid() == false)
- return CallNextEventHandler(next_ref, event);
-
- AXUIElementRef elementRef = scrollBar.element();
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, sizeof(elementRef), &elementRef);
- return noErr;
-}
-
-// This handler gets the contents for a scroll area or tab widget.
-static OSStatus handleContentsAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
- const QCFString mac_role = macRole(interface);
-
- QAElement contents;
-
- if (mac_role == kAXTabGroupRole) {
- contents = tabWidgetGetContents(interface);
- } else {
- contents = scrollAreaGetContents(interface);
- if (contents.isValid() == false)
- return CallNextEventHandler(next_ref, event);
- }
-
- return setAttributeValue(event, QList<QAElement>() << contents);
-}
-
-static OSStatus handleRowsAttribute(EventHandlerCallRef, EventRef event, QAInterface &tableView)
-{
- QList<QAElement> rows = lookup(tableView.children());
-
- // kill the first row which is the horizontal header.
- rows.removeAt(0);
-
- return setAttributeValue(event, rows);
-}
-
-static OSStatus handleVisibleRowsAttribute(EventHandlerCallRef, EventRef event, QAInterface &tableView)
-{
- QList<QAElement> visibleRows;
-
- QList<QAInterface> rows = tableView.children();
- // kill the first row which is the horizontal header.
- rows.removeAt(0);
-
- foreach (const QAInterface &interface, rows)
- if ((interface.state() & QAccessible::Invisible) == false)
- visibleRows.append(accessibleHierarchyManager()->lookup(interface));
-
- return setAttributeValue(event, visibleRows);
-}
-
-static OSStatus handleSelectedRowsAttribute(EventHandlerCallRef, EventRef event, QAInterface &tableView)
-{
- QList<QAElement> selectedRows;
- foreach (const QAInterface &interface, tableView.children())
- if ((interface.state() & QAccessible::Selected))
- selectedRows.append(accessibleHierarchyManager()->lookup(interface));
-
- return setAttributeValue(event, selectedRows);
-}
-
-static OSStatus getNamedAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
- CFStringRef var;
- GetEventParameter(event, kEventParamAccessibleAttributeName, typeCFStringRef, 0,
- sizeof(var), 0, &var);
-
- if (CFStringCompare(var, CFStringRef(QAXChildrenAttribute), 0) == kCFCompareEqualTo) {
- return handleChildrenAttribute(next_ref, event, interface);
- } else if(CFStringCompare(var, CFStringRef(QAXTopLevelUIElementAttribute), 0) == kCFCompareEqualTo) {
- return handleTopLevelUIElementAttribute(next_ref, event, interface);
- } else if(CFStringCompare(var, CFStringRef(QAXWindowAttribute), 0) == kCFCompareEqualTo) {
- return handleWindowAttribute(next_ref, event, interface);
- } else if(CFStringCompare(var, CFStringRef(QAXParentAttribute), 0) == kCFCompareEqualTo) {
- return handleParentAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXPositionAttribute), 0) == kCFCompareEqualTo) {
- return handlePositionAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXSizeAttribute), 0) == kCFCompareEqualTo) {
- return handleSizeAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXRoleAttribute), 0) == kCFCompareEqualTo) {
- CFStringRef role = macRole(interface);
-// ###
-// QWidget * const widget = qobject_cast<QWidget *>(interface.object());
-// if (role == CFStringRef(QAXUnknownRole) && widget && widget->isWindow())
-// role = CFStringRef(QAXWindowRole);
-
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef,
- sizeof(role), &role);
-
- } else if (CFStringCompare(var, CFStringRef(QAXEnabledAttribute), 0) == kCFCompareEqualTo) {
- Boolean val = !((interface.state() & QAccessible::Unavailable))
- && !((interface.state() & QAccessible::Invisible));
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- } else if (CFStringCompare(var, CFStringRef(QAXExpandedAttribute), 0) == kCFCompareEqualTo) {
- Boolean val = (interface.state() & QAccessible::Expanded);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- } else if (CFStringCompare(var, CFStringRef(QAXSelectedAttribute), 0) == kCFCompareEqualTo) {
- Boolean val = (interface.state() & QAccessible::Selection);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- } else if (CFStringCompare(var, CFStringRef(QAXFocusedAttribute), 0) == kCFCompareEqualTo) {
- Boolean val = (interface.state() & QAccessible::Focus);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- } else if (CFStringCompare(var, CFStringRef(QAXSelectedChildrenAttribute), 0) == kCFCompareEqualTo) {
- const int cc = interface.childCount();
- QList<QAElement> selected;
- for (int i = 1; i <= cc; ++i) {
- const QAInterface child_iface = interface.navigate(QAccessible::Child, i);
- if (child_iface.isValid() && child_iface.state() & QAccessible::Selected)
- selected.append(accessibleHierarchyManager()->lookup(child_iface));
- }
-
- return setAttributeValue(event, selected);
-
- } else if (CFStringCompare(var, CFStringRef(QAXCloseButtonAttribute), 0) == kCFCompareEqualTo) {
- if(interface.object() && interface.object()->isWidgetType()) {
- Boolean val = true; //do we want to add a WState for this?
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXZoomButtonAttribute), 0) == kCFCompareEqualTo) {
- if(interface.object() && interface.object()->isWidgetType()) {
- QWidget *widget = (QWidget*)interface.object();
- Boolean val = (widget->windowFlags() & Qt::WindowMaximizeButtonHint);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXMinimizeButtonAttribute), 0) == kCFCompareEqualTo) {
- if(interface.object() && interface.object()->isWidgetType()) {
- QWidget *widget = (QWidget*)interface.object();
- Boolean val = (widget->windowFlags() & Qt::WindowMinimizeButtonHint);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXToolbarButtonAttribute), 0) == kCFCompareEqualTo) {
- if(interface.object() && interface.object()->isWidgetType()) {
- QWidget *widget = (QWidget*)interface.object();
- Boolean val = qobject_cast<QMainWindow *>(widget) != 0;
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXGrowAreaAttribute), 0) == kCFCompareEqualTo) {
- if(interface.object() && interface.object()->isWidgetType()) {
- Boolean val = true; //do we want to add a WState for this?
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXMinimizedAttribute), 0) == kCFCompareEqualTo) {
- if (interface.object() && interface.object()->isWidgetType()) {
- QWidget *widget = (QWidget*)interface.object();
- Boolean val = (widget->windowState() & Qt::WindowMinimized);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
- sizeof(val), &val);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXSubroleAttribute), 0) == kCFCompareEqualTo) {
- return handleSubroleAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXRoleDescriptionAttribute), 0) == kCFCompareEqualTo) {
-#if !defined(QT_MAC_USE_COCOA)
- if (HICopyAccessibilityRoleDescription) {
- const CFStringRef roleDescription = HICopyAccessibilityRoleDescription(macRole(interface), 0);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef,
- sizeof(roleDescription), &roleDescription);
- } else
-#endif
- {
- // Just use Qt::Description on 10.3
- handleStringAttribute(event, QAccessible::Description, interface);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXTitleAttribute), 0) == kCFCompareEqualTo) {
- const QAccessible::Role role = interface.role();
- const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
- handleStringAttribute(event, text, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXValueAttribute), 0) == kCFCompareEqualTo) {
- const QAccessible::Role role = interface.role();
- const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
- if (role == QAccessible::CheckBox || role == QAccessible::RadioButton) {
- int value = buttonValue(interface);
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeUInt32, sizeof(value), &value);
- } else {
- handleStringAttribute(event, text, interface);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXDescriptionAttribute), 0) == kCFCompareEqualTo) {
- const QAccessible::Role role = interface.role();
- const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
- handleStringAttribute(event, text, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXLinkedUIElementsAttribute), 0) == kCFCompareEqualTo) {
- return CallNextEventHandler(next_ref, event);
- } else if (CFStringCompare(var, CFStringRef(QAXHelpAttribute), 0) == kCFCompareEqualTo) {
- const QAccessible::Role role = interface.role();
- const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
- handleStringAttribute(event, text, interface);
- } else if (CFStringCompare(var, kAXTitleUIElementAttribute, 0) == kCFCompareEqualTo) {
- return CallNextEventHandler(next_ref, event);
- } else if (CFStringCompare(var, CFStringRef(QAXTabsAttribute), 0) == kCFCompareEqualTo) {
- return handleTabsAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXMinValueAttribute), 0) == kCFCompareEqualTo) {
- // tabs we first go to the tab bar which is child #2.
- QAInterface tabBarInterface = interface.childAt(2);
- return handleTabsAttribute(next_ref, event, tabBarInterface);
- } else if (CFStringCompare(var, CFStringRef(QAXMinValueAttribute), 0) == kCFCompareEqualTo) {
- if (interface.role() == QAccessible::RadioButton || interface.role() == QAccessible::CheckBox) {
- uint value = 0;
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeUInt32, sizeof(value), &value);
- } else {
- return CallNextEventHandler(next_ref, event);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXMaxValueAttribute), 0) == kCFCompareEqualTo) {
- if (interface.role() == QAccessible::RadioButton || interface.role() == QAccessible::CheckBox) {
- uint value = 2;
- SetEventParameter(event, kEventParamAccessibleAttributeValue, typeUInt32, sizeof(value), &value);
- } else {
- return CallNextEventHandler(next_ref, event);
- }
- } else if (CFStringCompare(var, CFStringRef(QAXOrientationAttribute), 0) == kCFCompareEqualTo) {
- return handleOrientationAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXPreviousContentsAttribute), 0) == kCFCompareEqualTo) {
- return handleSplitterContentsAttribute(next_ref, event, interface, CFStringRef(QAXPreviousContentsAttribute));
- } else if (CFStringCompare(var, CFStringRef(QAXNextContentsAttribute), 0) == kCFCompareEqualTo) {
- return handleSplitterContentsAttribute(next_ref, event, interface, CFStringRef(QAXNextContentsAttribute));
- } else if (CFStringCompare(var, CFStringRef(QAXSplittersAttribute), 0) == kCFCompareEqualTo) {
- return handleSplittersAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXHorizontalScrollBarAttribute), 0) == kCFCompareEqualTo) {
- return handleScrollBarAttribute(next_ref, event, interface, Qt::Horizontal);
- } else if (CFStringCompare(var, CFStringRef(QAXVerticalScrollBarAttribute), 0) == kCFCompareEqualTo) {
- return handleScrollBarAttribute(next_ref, event, interface, Qt::Vertical);
- } else if (CFStringCompare(var, CFStringRef(QAXContentsAttribute), 0) == kCFCompareEqualTo) {
- return handleContentsAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXRowsAttribute), 0) == kCFCompareEqualTo) {
- return handleRowsAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXVisibleRowsAttribute), 0) == kCFCompareEqualTo) {
- return handleVisibleRowsAttribute(next_ref, event, interface);
- } else if (CFStringCompare(var, CFStringRef(QAXSelectedRowsAttribute), 0) == kCFCompareEqualTo) {
- return handleSelectedRowsAttribute(next_ref, event, interface);
- } else {
- return CallNextEventHandler(next_ref, event);
- }
- return noErr;
-}
-
-static OSStatus isNamedAttributeSettable(EventRef event, const QAInterface &interface)
-{
- CFStringRef var;
- GetEventParameter(event, kEventParamAccessibleAttributeName, typeCFStringRef, 0,
- sizeof(var), 0, &var);
- Boolean settable = false;
- if (CFStringCompare(var, CFStringRef(QAXFocusedAttribute), 0) == kCFCompareEqualTo) {
- settable = true;
- } else {
- for (int r = 0; text_bindings[r][0].qt != -1; r++) {
- if(interface.role() == (QAccessible::Role)text_bindings[r][0].qt) {
- for (int a = 1; text_bindings[r][a].qt != -1; a++) {
- if (CFStringCompare(var, CFStringRef(text_bindings[r][a].mac), 0) == kCFCompareEqualTo) {
- settable = text_bindings[r][a].settable;
- break;
- }
- }
- }
- }
- }
- SetEventParameter(event, kEventParamAccessibleAttributeSettable, typeBoolean,
- sizeof(settable), &settable);
- return noErr;
-}
-
-static OSStatus getChildAtPoint(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
- Q_UNUSED(next_ref);
- if (interface.isValid() == false)
- return eventNotHandledErr;
-
- // Add the children for this interface to the global QAccessibelHierachyManager.
- accessibleHierarchyManager()->registerChildren(interface);
-
- Point where;
- GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, 0, sizeof(where), 0, &where);
- const QAInterface childInterface = interface.childAt(where.h, where.v);
-
- if (childInterface.isValid() == false || childInterface == interface)
- return eventNotHandledErr;
-
- const QAElement element = accessibleHierarchyManager()->lookup(childInterface);
- if (element.isValid() == false)
- return eventNotHandledErr;
-
- AXUIElementRef elementRef = element.element();
- CFRetain(elementRef);
- SetEventParameter(event, kEventParamAccessibleChild, typeCFTypeRef,
- sizeof(elementRef), &elementRef);
-
- return noErr;
-}
-
-/*
- Returns a list of actions the given interface supports.
- Currently implemented by getting the interface role and deciding based on that.
-*/
-static QList<QAccessible::Action> supportedPredefinedActions(const QAInterface &interface)
-{
- QList<QAccessible::Action> actions;
- switch (interface.role()) {
- default:
- // Most things can be pressed.
- actions.append(QAccessible::Press);
- break;
- }
-
- return actions;
-}
-
-/*
- Translates a predefined QAccessible::Action to a Mac action constant.
- Returns an empty string if the Qt Action has no mac equivalent.
-*/
-static QCFString translateAction(const QAccessible::Action action)
-{
- switch (action) {
- case QAccessible::Press:
- return CFStringRef(QAXPressAction);
- break;
- case QAccessible::Increase:
- return CFStringRef(QAXIncrementAction);
- break;
- case QAccessible::Decrease:
- return CFStringRef(QAXDecrementAction);
- break;
- case QAccessible::Accept:
- return CFStringRef(QAXConfirmAction);
- break;
- case QAccessible::Select:
- return CFStringRef(QAXPickAction);
- break;
- case QAccessible::Cancel:
- return CFStringRef(QAXCancelAction);
- break;
- default:
- return QCFString();
- break;
- }
-}
-
-/*
- Translates between a Mac action constant and a QAccessible::Action.
- Returns QAccessible::Default action if there is no Qt predefined equivalent.
-*/
-static QAccessible::Action translateAction(const CFStringRef actionName)
-{
- if(CFStringCompare(actionName, CFStringRef(QAXPressAction), 0) == kCFCompareEqualTo) {
- return QAccessible::Press;
- } else if(CFStringCompare(actionName, CFStringRef(QAXIncrementAction), 0) == kCFCompareEqualTo) {
- return QAccessible::Increase;
- } else if(CFStringCompare(actionName, CFStringRef(QAXDecrementAction), 0) == kCFCompareEqualTo) {
- return QAccessible::Decrease;
- } else if(CFStringCompare(actionName, CFStringRef(QAXConfirmAction), 0) == kCFCompareEqualTo) {
- return QAccessible::Accept;
- } else if(CFStringCompare(actionName, CFStringRef(QAXPickAction), 0) == kCFCompareEqualTo) {
- return QAccessible::Select;
- } else if(CFStringCompare(actionName, CFStringRef(QAXCancelAction), 0) == kCFCompareEqualTo) {
- return QAccessible::Cancel;
- } else {
- return QAccessible::DefaultAction;
- }
-}
-#endif // QT_MAC_USE_COCOA
-
-/*
- Copies the translated names all supported actions for an interface into the kEventParamAccessibleActionNames
- event parameter.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus getAllActionNames(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
- Q_UNUSED(next_ref);
-
- CFMutableArrayRef actions = 0;
- GetEventParameter(event, kEventParamAccessibleActionNames, typeCFMutableArrayRef, 0,
- sizeof(actions), 0, &actions);
-
- // Add supported predefined actions.
- const QList<QAccessible::Action> predefinedActions = supportedPredefinedActions(interface);
- for (int i = 0; i < predefinedActions.count(); ++i) {
- const QCFString action = translateAction(predefinedActions.at(i));
- if (action != QCFString())
- qt_mac_append_cf_uniq(actions, action);
- }
-
- // Add user actions
- const int actionCount = interface.userActionCount();
- for (int i = 0; i < actionCount; ++i) {
- const QString actionName = interface.actionText(i, QAccessible::Name);
- qt_mac_append_cf_uniq(actions, QCFString::toCFStringRef(actionName));
- }
-
- return noErr;
-}
-#endif
-
-/*
- Handles the perforNamedAction event.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus performNamedAction(EventHandlerCallRef next_ref, EventRef event, const QAInterface& interface)
-{
- Q_UNUSED(next_ref);
-
- CFStringRef act;
- GetEventParameter(event, kEventParamAccessibleActionName, typeCFStringRef, 0,
- sizeof(act), 0, &act);
-
- const QAccessible::Action action = translateAction(act);
-
- // Perform built-in action
- if (action != QAccessible::DefaultAction) {
- interface.doAction(action, QVariantList());
- return noErr;
- }
-
- // Search for user-defined actions and perform it if found.
- const int actCount = interface.userActionCount();
- const QString qAct = QCFString::toQString(act);
- for(int i = 0; i < actCount; i++) {
- if(interface.actionText(i, QAccessible::Name) == qAct) {
- interface.doAction(i, QVariantList());
- break;
- }
- }
- return noErr;
-}
-
-static OSStatus setNamedAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
- Q_UNUSED(next_ref);
- Q_UNUSED(event);
-
- CFStringRef var;
- GetEventParameter(event, kEventParamAccessibleAttributeName, typeCFStringRef, 0,
- sizeof(var), 0, &var);
- if(CFStringCompare(var, CFStringRef(QAXFocusedAttribute), 0) == kCFCompareEqualTo) {
- CFTypeRef val;
- if(GetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, 0,
- sizeof(val), 0, &val) == noErr) {
- if(CFGetTypeID(val) == CFBooleanGetTypeID() &&
- CFEqual(static_cast<CFBooleanRef>(val), kCFBooleanTrue)) {
- interface.doAction(QAccessible::SetFocus);
- }
- }
- } else {
- bool found = false;
- for(int r = 0; text_bindings[r][0].qt != -1; r++) {
- if(interface.role() == (QAccessible::Role)text_bindings[r][0].qt) {
- for(int a = 1; text_bindings[r][a].qt != -1; a++) {
- if(CFStringCompare(var, CFStringRef(text_bindings[r][a].mac), 0) == kCFCompareEqualTo) {
- if(!text_bindings[r][a].settable) {
- } else {
- CFTypeRef val;
- if(GetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, 0,
- sizeof(val), 0, &val) == noErr) {
- if(CFGetTypeID(val) == CFStringGetTypeID())
- interface.setText((QAccessible::Text)text_bindings[r][a].qt,
- QCFString::toQString(static_cast<CFStringRef>(val)));
-
- }
- }
- found = true;
- break;
- }
- }
- break;
- }
- }
- }
- return noErr;
-}
-
-/*
- This is the main accessibility event handler.
-*/
-static OSStatus accessibilityEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data)
-{
- Q_UNUSED(data)
-
- // Return if this event is not a AccessibleGetNamedAttribute event.
- const UInt32 eclass = GetEventClass(event);
- if (eclass != kEventClassAccessibility)
- return eventNotHandledErr;
-
- // Get the AXUIElementRef and QAInterface pointer
- AXUIElementRef element = 0;
- GetEventParameter(event, kEventParamAccessibleObject, typeCFTypeRef, 0, sizeof(element), 0, &element);
- QAInterface interface = accessibleHierarchyManager()->lookup(element);
- if (interface.isValid() == false)
- return eventNotHandledErr;
-
- const UInt32 ekind = GetEventKind(event);
- OSStatus status = noErr;
- switch (ekind) {
- case kEventAccessibleGetAllAttributeNames:
- status = getAllAttributeNames(event, interface, next_ref);
- break;
- case kEventAccessibleGetNamedAttribute:
- status = getNamedAttribute(next_ref, event, interface);
- break;
- case kEventAccessibleIsNamedAttributeSettable:
- status = isNamedAttributeSettable(event, interface);
- break;
- case kEventAccessibleGetChildAtPoint:
- status = getChildAtPoint(next_ref, event, interface);
- break;
- case kEventAccessibleGetAllActionNames:
- status = getAllActionNames(next_ref, event, interface);
- break;
- case kEventAccessibleGetFocusedChild:
- status = CallNextEventHandler(next_ref, event);
- break;
- case kEventAccessibleSetNamedAttribute:
- status = setNamedAttribute(next_ref, event, interface);
- break;
- case kEventAccessiblePerformNamedAction:
- status = performNamedAction(next_ref, event, interface);
- break;
- default:
- status = CallNextEventHandler(next_ref, event);
- break;
- };
- return status;
-}
-#endif
-
-void QAccessible::initialize()
-{
-#ifndef QT_MAC_USE_COCOA
- registerQtAccessibilityHIObjectSubclass();
- installApplicationEventhandler();
-#endif
-}
-
-// Sets thre root object for the application
-void QAccessible::setRootObject(QObject *object)
-{
- // Call installed root object handler if we have one
- if (rootObjectHandler) {
- rootObjectHandler(object);
- return;
- }
-
- rootObject = object;
-}
-
-void QAccessible::cleanup()
-{
- accessibleHierarchyManager()->reset();
-#ifndef QT_MAC_USE_COCOA
- removeEventhandler(applicationEventHandlerUPP);
- removeEventhandler(objectCreateEventHandlerUPP);
- removeEventhandler(accessibilityEventHandlerUPP);
-#endif
-}
-
-void QAccessible::updateAccessibility(QObject *object, int child, Event reason)
-{
- // Call installed update handler if we have one.
- if (updateHandler) {
- updateHandler(object, child, reason);
- return;
- }
-
-#ifndef QT_MAC_USE_COCOA
- // Return if the mac accessibility is not enabled.
- if(!AXAPIEnabled())
- return;
-
- // Work around crash, disable accessiblity for focus frames.
- if (qstrcmp(object->metaObject()->className(), "QFocusFrame") == 0)
- return;
-
-// qDebug() << "updateAccessibility" << object << child << hex << reason;
-
- if (reason == ObjectShow) {
- QAInterface interface = QAInterface(QAccessible::queryAccessibleInterface(object), child);
- accessibleHierarchyManager()->registerInterface(interface);
- }
-
- const QAElement element = accessibleHierarchyManager()->lookup(object, child);
- if (element.isValid() == false)
- return;
-
-
- CFStringRef notification = 0;
- if(object && object->isWidgetType() && reason == ObjectCreated) {
- notification = CFStringRef(QAXWindowCreatedNotification);
- } else if(reason == ValueChanged) {
- notification = CFStringRef(QAXValueChangedNotification);
- } else if(reason == MenuStart) {
- notification = CFStringRef(QAXMenuOpenedNotification);
- } else if(reason == MenuEnd) {
- notification = CFStringRef(QAXMenuClosedNotification);
- } else if(reason == LocationChanged) {
- notification = CFStringRef(QAXWindowMovedNotification);
- } else if(reason == ObjectShow || reason == ObjectHide ) {
- // When a widget is deleted we get a ObjectHide before the destroyed(QObject *)
- // signal is emitted (which makes sense). However, at this point we are in the
- // middle of the QWidget destructor which means that we have to be careful when
- // using the widget pointer. Since we can't control what the accessibilty interfaces
- // does when navigate() is called below we ignore the hide update in this case.
- // (the widget will be deleted soon anyway.)
- extern QWidgetPrivate * qt_widget_private(QWidget *);
- if (QWidget *widget = qobject_cast<QWidget*>(object)) {
- if (qt_widget_private(widget)->data.in_destructor)
- return;
-
- // Check widget parent as well, special case for preventing crash
- // when the viewport() of an abstract scroll area is hidden when
- // the QWidget destructor hides all its children.
- QWidget *parentWidget = widget->parentWidget();
- if (parentWidget && qt_widget_private(parentWidget)->data.in_destructor)
- return;
- }
-
- // There is no equivalent Mac notification for ObjectShow/Hide, so we call HIObjectSetAccessibilityIgnored
- // and isItIntersting which will mark the HIObject accociated with the element as ignored if the
- // QAccessible::Invisible state bit is set.
- QAInterface interface = accessibleHierarchyManager()->lookup(element);
- if (interface.isValid()) {
- HIObjectSetAccessibilityIgnored(element.object(), !isItInteresting(interface));
- }
-
- // If the interface manages its own children, also check if we should ignore those.
- if (isItemView(interface) == false && managesChildren(interface)) {
- for (int i = 1; i <= interface.childCount(); ++i) {
- QAInterface childInterface = interface.navigate(QAccessible::Child, i);
- if (childInterface.isValid() && childInterface.isHIView() == false) {
- const QAElement element = accessibleHierarchyManager()->lookup(childInterface);
- if (element.isValid()) {
- HIObjectSetAccessibilityIgnored(element.object(), !isItInteresting(childInterface));
- }
- }
- }
- }
-
- } else if(reason == Focus) {
- if(object && object->isWidgetType()) {
- QWidget *w = static_cast<QWidget*>(object);
- if(w->isWindow())
- notification = CFStringRef(QAXFocusedWindowChangedNotification);
- else
- notification = CFStringRef(QAXFocusedUIElementChangedNotification);
- }
- }
-
- if (!notification)
- return;
-
- AXNotificationHIObjectNotify(notification, element.object(), element.id());
-#endif
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessible_mac_carbon.cpp b/src/gui/accessible/qaccessible_mac_carbon.cpp
deleted file mode 100644
index 2e8a7628e8..0000000000
--- a/src/gui/accessible/qaccessible_mac_carbon.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-static OSStatus applicationEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data);
-static EventHandlerUPP applicationEventHandlerUPP = 0;
-static EventTypeSpec application_events[] = {
- { kEventClassAccessibility, kEventAccessibleGetChildAtPoint },
- { kEventClassAccessibility, kEventAccessibleGetNamedAttribute }
-};
-
-static CFStringRef kObjectQtAccessibility = CFSTR("com.trolltech.qt.accessibility");
-static EventHandlerUPP objectCreateEventHandlerUPP = 0;
-static EventTypeSpec objectCreateEvents[] = {
- { kEventClassHIObject, kEventHIObjectConstruct },
- { kEventClassHIObject, kEventHIObjectInitialize },
- { kEventClassHIObject, kEventHIObjectDestruct },
- { kEventClassHIObject, kEventHIObjectPrintDebugInfo }
-};
-
-static OSStatus accessibilityEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data);
-static EventHandlerUPP accessibilityEventHandlerUPP = 0;
-static EventTypeSpec accessibilityEvents[] = {
- { kEventClassAccessibility, kEventAccessibleGetChildAtPoint },
- { kEventClassAccessibility, kEventAccessibleGetFocusedChild },
- { kEventClassAccessibility, kEventAccessibleGetAllAttributeNames },
- { kEventClassAccessibility, kEventAccessibleGetNamedAttribute },
- { kEventClassAccessibility, kEventAccessibleSetNamedAttribute },
- { kEventClassAccessibility, kEventAccessibleIsNamedAttributeSettable },
- { kEventClassAccessibility, kEventAccessibleGetAllActionNames },
- { kEventClassAccessibility, kEventAccessiblePerformNamedAction },
- { kEventClassAccessibility, kEventAccessibleGetNamedActionDescription }
-};
-
-static void installAcessibilityEventHandler(HIObjectRef hiObject)
-{
- if (!accessibilityEventHandlerUPP)
- accessibilityEventHandlerUPP = NewEventHandlerUPP(accessibilityEventHandler);
-
- InstallHIObjectEventHandler(hiObject, accessibilityEventHandlerUPP,
- GetEventTypeCount(accessibilityEvents),
- accessibilityEvents, 0, 0);
-}
-
-static OSStatus objectCreateEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data)
-{
- Q_UNUSED(data)
- Q_UNUSED(event)
- Q_UNUSED(next_ref)
- return noErr;
-}
-
-static void registerQtAccessibilityHIObjectSubclass()
-{
- if (!objectCreateEventHandlerUPP)
- objectCreateEventHandlerUPP = NewEventHandlerUPP(objectCreateEventHandler);
- OSStatus err = HIObjectRegisterSubclass(kObjectQtAccessibility, 0, 0, objectCreateEventHandlerUPP,
- GetEventTypeCount(objectCreateEvents), objectCreateEvents, 0, 0);
- if (err && err != hiObjectClassExistsErr)
- qWarning("qaccessible_mac internal error: Could not register accessibility HIObject subclass");
-}
-
-static void installApplicationEventhandler()
-{
- if (!applicationEventHandlerUPP)
- applicationEventHandlerUPP = NewEventHandlerUPP(applicationEventHandler);
-
- OSStatus err = InstallApplicationEventHandler(applicationEventHandlerUPP,
- GetEventTypeCount(application_events), application_events,
- 0, 0);
-
- if (err && err != eventHandlerAlreadyInstalledErr)
- qWarning("qaccessible_mac internal error: Could not install application accessibility event handler");
-}
-
-static void removeEventhandler(EventHandlerUPP eventHandler)
-{
- if (eventHandler) {
- DisposeEventHandlerUPP(eventHandler);
- eventHandler = 0;
- }
-}
diff --git a/src/gui/accessible/qaccessible_mac_cocoa.mm b/src/gui/accessible/qaccessible_mac_cocoa.mm
deleted file mode 100644
index 60b967ab39..0000000000
--- a/src/gui/accessible/qaccessible_mac_cocoa.mm
+++ /dev/null
@@ -1,239 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessible.h"
-#include "qaccessible_mac_p.h"
-#include "qdebug.h"
-#include "qtabwidget.h"
-
-#include <private/qt_mac_p.h>
-#include <private/qcocoaview_mac_p.h>
-#include <private/qwidget_p.h>
-
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#ifdef QT_MAC_USE_COCOA
-
-QT_BEGIN_NAMESPACE
-
-//#define MAC_ACCESSIBILTY_DEVELOPER_MODE
-
-#ifndef QT_NO_DEBUG_STREAM
-#ifdef MAC_ACCESSIBILTY_DEVELOPER_MODE
-#define MAC_ACCESSIBILTY_DEBUG QT_PREPEND_NAMESPACE(qDebug)
-#else
-#define MAC_ACCESSIBILTY_DEBUG if (0) QT_PREPEND_NAMESPACE(qDebug)
-#endif
-#else
-#define MAC_ACCESSIBILTY_DEBUG if (0) QT_PREPEND_NAMESPACE(QNoDebug)
-#endif
-
-typedef QMap<QAccessible::Role, NSString *> QMacAccessibiltyRoleMap;
-Q_GLOBAL_STATIC(QMacAccessibiltyRoleMap, qMacAccessibiltyRoleMap);
-
-static QAInterface interfaceForView(QT_MANGLE_NAMESPACE(QCocoaView) *view)
-{
- return QAInterface(QAccessible::queryAccessibleInterface([view qt_qwidget]));
-}
-
-/*
- Set up mappings from Qt accessibilty roles to Mac accessibilty roles.
-*/
-static void populateRoleMap()
-{
- QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap();
- roleMap[QAccessible::MenuItem] = NSAccessibilityMenuItemRole;
- roleMap[QAccessible::MenuBar] = NSAccessibilityMenuBarRole;
- roleMap[QAccessible::ScrollBar] = NSAccessibilityScrollBarRole;
- roleMap[QAccessible::Grip] = NSAccessibilityGrowAreaRole;
- roleMap[QAccessible::Window] = NSAccessibilityWindowRole;
- roleMap[QAccessible::Dialog] = NSAccessibilityWindowRole;
- roleMap[QAccessible::AlertMessage] = NSAccessibilityWindowRole;
- roleMap[QAccessible::ToolTip] = NSAccessibilityWindowRole;
- roleMap[QAccessible::HelpBalloon] = NSAccessibilityWindowRole;
- roleMap[QAccessible::PopupMenu] = NSAccessibilityMenuRole;
- roleMap[QAccessible::Application] = NSAccessibilityApplicationRole;
- roleMap[QAccessible::Pane] = NSAccessibilityGroupRole;
- roleMap[QAccessible::Grouping] = NSAccessibilityGroupRole;
- roleMap[QAccessible::Separator] = NSAccessibilitySplitterRole;
- roleMap[QAccessible::ToolBar] = NSAccessibilityToolbarRole;
- roleMap[QAccessible::PageTab] = NSAccessibilityRadioButtonRole;
- roleMap[QAccessible::ButtonMenu] = NSAccessibilityMenuButtonRole;
- roleMap[QAccessible::ButtonDropDown] = NSAccessibilityPopUpButtonRole;
- roleMap[QAccessible::SpinBox] = NSAccessibilityIncrementorRole;
- roleMap[QAccessible::Slider] = NSAccessibilitySliderRole;
- roleMap[QAccessible::ProgressBar] = NSAccessibilityProgressIndicatorRole;
- roleMap[QAccessible::ComboBox] = NSAccessibilityPopUpButtonRole;
- roleMap[QAccessible::RadioButton] = NSAccessibilityRadioButtonRole;
- roleMap[QAccessible::CheckBox] = NSAccessibilityCheckBoxRole;
- roleMap[QAccessible::StaticText] = NSAccessibilityStaticTextRole;
- roleMap[QAccessible::Table] = NSAccessibilityTableRole;
- roleMap[QAccessible::StatusBar] = NSAccessibilityStaticTextRole;
- roleMap[QAccessible::Column] = NSAccessibilityColumnRole;
- roleMap[QAccessible::ColumnHeader] = NSAccessibilityColumnRole;
- roleMap[QAccessible::Row] = NSAccessibilityRowRole;
- roleMap[QAccessible::RowHeader] = NSAccessibilityRowRole;
- roleMap[QAccessible::Cell] = NSAccessibilityTextFieldRole;
- roleMap[QAccessible::PushButton] = NSAccessibilityButtonRole;
- roleMap[QAccessible::EditableText] = NSAccessibilityTextFieldRole;
- roleMap[QAccessible::Link] = NSAccessibilityTextFieldRole;
- roleMap[QAccessible::Indicator] = NSAccessibilityValueIndicatorRole;
- roleMap[QAccessible::Splitter] = NSAccessibilitySplitGroupRole;
- roleMap[QAccessible::List] = NSAccessibilityListRole;
- roleMap[QAccessible::ListItem] = NSAccessibilityStaticTextRole;
- roleMap[QAccessible::Cell] = NSAccessibilityStaticTextRole;
-}
-
-/*
- Returns a Mac accessibility role for the given interface, or
- NSAccessibilityUnknownRole if no role mapping is found.
-*/
-static NSString *macRoleForInterface(QAInterface interface)
-{
- const QAccessible::Role qtRole = interface.role();
- QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap();
-
- if (roleMap.isEmpty())
- populateRoleMap();
-
- MAC_ACCESSIBILTY_DEBUG() << "role for" << interface.object() << "interface role" << hex << qtRole;
-
- if (roleMap.contains(qtRole)) {
- MAC_ACCESSIBILTY_DEBUG() << "return" << roleMap[qtRole];
- return roleMap[qtRole];
- }
-
- MAC_ACCESSIBILTY_DEBUG() << "return NSAccessibilityUnknownRole";
- return NSAccessibilityUnknownRole;
-}
-
-/*
- Is the interface a QTabBar embedded in a QTabWidget?
- (as opposed to a stand-alone tab bar)
-*/
-static bool isEmbeddedTabBar(const QAInterface &interface)
-{
- QObject *object = interface.object();
- if (interface.role() == QAccessible::PageTabList && object)
- return (qobject_cast<QTabWidget *>(object->parent()));
-
- return false;
-}
-
-static bool isInterfaceIgnored(QAInterface interface)
-{
- // Mac accessibility does not have an attribute that corresponds to the
- // Invisible/Offscreen state. Use the ignore facility to disable them.
- const QAccessible::State state = interface.state();
- if (state & QAccessible::Invisible ||
- state & QAccessible::Offscreen )
- return false;
-
- // Hide QTabBars that has a QTabWidget parent (the QTabWidget handles the accessibility)
- if (isEmbeddedTabBar(interface))
- return false;
-
- if (QObject * const object = interface.object()) {
- const QString className = QLatin1String(object->metaObject()->className());
-
- // Prevent VoiceOver from focusing on tool tips by ignoring those
- // interfaces. Shifting VoiceOver focus to the tool tip is confusing
- // and the contents of the tool tip is avalible through the description
- // attribute anyway.
- if (className == QLatin1String("QTipLabel"))
- return false;
- }
-
- // Hide interfaces with an unknown role. When developing it's often useful to disable
- // this check to see all interfaces in the hierarchy.
-#ifndef MAC_ACCESSIBILTY_DEVELOPER_MODE
- return [macRoleForInterface(interface) isEqualToString: NSAccessibilityUnknownRole];
-#else
- return NO;
-#endif
-}
-
-QT_END_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaView) (Accessibility)
-
-- (BOOL)accessibilityIsIgnored
-{
- QT_PREPEND_NAMESPACE(QAInterface) interface = QT_PREPEND_NAMESPACE(interfaceForView)(self);
- return isInterfaceIgnored(interface);
-}
-
-- (NSArray *)accessibilityAttributeNames
-{
- QT_PREPEND_NAMESPACE(QAInterface) interface = QT_PREPEND_NAMESPACE(interfaceForView)(self);
-
- static NSArray *attributes = nil;
- if (attributes == nil) {
- attributes = [super accessibilityAttributeNames];
-
- }
- return attributes;
-}
-
-- (id)accessibilityAttributeValue:(NSString *)attribute
-{
- MAC_ACCESSIBILTY_DEBUG() << "accessibilityAttributeValue" << self <<
- QT_PREPEND_NAMESPACE(QCFString)::toQString(reinterpret_cast<CFStringRef>(attribute));
-
- QT_PREPEND_NAMESPACE(QAInterface) interface = QT_PREPEND_NAMESPACE(interfaceForView)(self);
-
- // Switch on the attribute name and call the appropriate handler function.
- // Pass the call on to the NSView class for attributes we don't handle.
- if ([attribute isEqualToString:@"AXRole"]) {
- return macRoleForInterface(interface);
- } else {
- return [super accessibilityAttributeValue:attribute];
- }
-}
-
-@end
-
-#endif // QT_MAC_USE_COCOA
-
-#endif // QT_NO_ACCESSIBILITY
-
diff --git a/src/gui/accessible/qaccessible_mac_p.h b/src/gui/accessible/qaccessible_mac_p.h
deleted file mode 100644
index 9acb5d3aef..0000000000
--- a/src/gui/accessible/qaccessible_mac_p.h
+++ /dev/null
@@ -1,479 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLE_MAC_P_H
-#define QACCESSIBLE_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include <qglobal.h>
-#include <private/qt_mac_p.h>
-#include <qaccessible.h>
-#include <qwidget.h>
-#include <qdebug.h>
-
-//#define Q_ACCESSIBLE_MAC_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-/*
- QAccessibleInterfaceWrapper wraps QAccessibleInterface and adds
- a ref count. QAccessibleInterfaceWrapper is a "by-value" class.
-*/
-class Q_AUTOTEST_EXPORT QAccessibleInterfaceWrapper
-{
-public:
- QAccessibleInterfaceWrapper()
- : interface(0), childrenIsRegistered(new bool(false)), refCount(new int(1)) { }
-
- QAccessibleInterfaceWrapper(QAccessibleInterface *interface)
- :interface(interface), childrenIsRegistered(new bool(false)), refCount(new int(1)) { }
-
- ~QAccessibleInterfaceWrapper()
- {
- if (--(*refCount) == 0) {
- delete interface;
- delete refCount;
- delete childrenIsRegistered;
- }
- }
-
- QAccessibleInterfaceWrapper(const QAccessibleInterfaceWrapper &other)
- :interface(other.interface), childrenIsRegistered(other.childrenIsRegistered), refCount(other.refCount)
- {
- ++(*refCount);
- }
-
- void operator=(const QAccessibleInterfaceWrapper &other)
- {
- if (other.interface == interface)
- return;
-
- if (--(*refCount) == 0) {
- delete interface;
- delete refCount;
- delete childrenIsRegistered;
- }
-
- interface = other.interface;
- childrenIsRegistered = other.childrenIsRegistered;
- refCount = other.refCount;
- ++(*refCount);
- }
-
- QAccessibleInterface *interface;
- bool *childrenIsRegistered;
-private:
- int *refCount;
-};
-
-/*
- QAInterface represents one accessiblity item. It hides the fact that
- one QAccessibleInterface may represent more than one item, and it also
- automates the memory management for QAccessibleInterfaces using the
- QAccessibleInterfaceWrapper wrapper class.
-
- It has the same API as QAccessibleInterface, minus the child parameter
- in the functions.
-*/
-class Q_AUTOTEST_EXPORT QAInterface : public QAccessible
-{
-public:
- QAInterface()
- : base(QAccessibleInterfaceWrapper())
- { }
-
- QAInterface(QAccessibleInterface *interface, int child = 0)
- {
- if (interface == 0 || child > interface->childCount()) {
- base = QAccessibleInterfaceWrapper();
- } else {
- base = QAccessibleInterfaceWrapper(interface);
- m_cachedObject = interface->object();
- this->child = child;
- }
- }
-
- QAInterface(QAccessibleInterfaceWrapper wrapper, int child = 0)
- :base(wrapper), m_cachedObject(wrapper.interface->object()), child(child)
- { }
-
- QAInterface(const QAInterface &other, int child)
- {
- if (other.isValid() == false || child > other.childCount()) {
- base = QAccessibleInterfaceWrapper();
- } else {
- base = other.base;
- m_cachedObject = other.m_cachedObject;
- this->child = child;
- }
- }
-
- bool operator==(const QAInterface &other) const;
- bool operator!=(const QAInterface &other) const;
-
- inline QString actionText (int action, Text text) const
- { return base.interface->actionText(action, text, child); }
-
- QAInterface childAt(int x, int y) const
- {
- if (!checkValid())
- return QAInterface();
-
- const int foundChild = base.interface->childAt(x, y);
-
- if (foundChild == -1)
- return QAInterface();
-
- if (child == 0)
- return navigate(QAccessible::Child, foundChild);
-
- if (foundChild == child)
- return *this;
- return QAInterface();
- }
-
- int indexOfChild(const QAInterface &child) const
- {
- if (!checkValid())
- return -1;
-
- if (*this != child.parent())
- return -1;
-
- if (object() == child.object())
- return child.id();
-
- return base.interface->indexOfChild(child.base.interface);
- }
-
- inline int childCount() const
- {
- if (!checkValid())
- return 0;
-
- if (child != 0)
- return 0;
- return base.interface->childCount();
- }
-
- QList<QAInterface> children() const
- {
- if (!checkValid())
- return QList<QAInterface>();
-
- QList<QAInterface> children;
- for (int i = 1; i <= childCount(); ++i) {
- children.append(navigate(QAccessible::Child, i));
- }
- return children;
- }
-
- QAInterface childAt(int index) const
- {
- return navigate(QAccessible::Child, index);
- }
-
- inline void doAction(int action, const QVariantList &params = QVariantList()) const
- {
- if (!checkValid())
- return;
-
- base.interface->doAction(action, child, params);
- }
-
- QAInterface navigate(RelationFlag relation, int entry) const;
-
- inline QObject * object() const
- {
- if (!checkValid())
- return 0;
-
- return base.interface->object();
- }
-
- QAInterface objectInterface() const
- {
- if (!checkValid())
- return QAInterface();
-
- QObject *obj = object();
- QAInterface current = *this;
- while (obj == 0)
- {
- QAInterface parent = current.parent();
- if (parent.isValid() == false)
- break;
- obj = parent.object();
- current = parent;
- }
- return current;
- }
-
- inline HIObjectRef hiObject() const
- {
- if (!checkValid())
- return 0;
- QWidget * const widget = qobject_cast<QWidget * const>(object());
- if (widget)
- return (HIObjectRef)widget->winId();
- else
- return 0;
- }
-
- inline QObject * cachedObject() const
- {
- if (!checkValid())
- return 0;
- return m_cachedObject;
- }
-
- inline QRect rect() const
- {
- if (!checkValid())
- return QRect();
- return base.interface->rect(child);
- }
-
- inline Role role() const
- {
- if (!checkValid())
- return QAccessible::NoRole;
- return base.interface->role(child);
- }
-
- inline void setText(Text t, const QString &text) const
- {
- if (!checkValid())
- return;
- base.interface->setText(t, child, text);
- }
-
- inline State state() const
- {
- if (!checkValid())
- return 0;
- return base.interface->state(child);
- }
-
- inline QString text (Text text) const
- {
- if (!checkValid())
- return QString();
- return base.interface->text(text, child);
- }
-
- inline QString value() const
- { return text(QAccessible::Value); }
-
- inline QString name() const
- { return text(QAccessible::Name); }
-
- inline int userActionCount() const
- {
- if (!checkValid())
- return 0;
- return base.interface->userActionCount(child);
- }
-
- inline QString className() const
- {
- if (!checkValid())
- return QString();
- return QLatin1String(base.interface->object()->metaObject()->className());
- }
-
- inline bool isHIView() const
- { return (child == 0 && object() != 0); }
-
- inline int id() const
- { return child; }
-
- inline bool isValid() const
- {
- return (base.interface != 0 && base.interface->isValid());
- }
-
- QAInterface parent() const
- { return navigate(QAccessible::Ancestor, 1); }
-
- QAccessibleInterfaceWrapper interfaceWrapper() const
- { return base; }
-
-protected:
- bool checkValid() const
- {
- const bool valid = isValid();
-#ifdef Q_ACCESSIBLE_MAC_DEBUG
- if (!valid)
- qFatal("QAccessible_mac: tried to use invalid interface.");
-#endif
- return valid;
- }
-
- QAccessibleInterfaceWrapper base;
- QObject *m_cachedObject;
- int child;
-};
-
-Q_AUTOTEST_EXPORT QDebug operator<<(QDebug debug, const QAInterface &interface);
-
-/*
- QAElement is a thin wrapper around an AXUIElementRef that automates
- the ref-counting.
-*/
-class Q_AUTOTEST_EXPORT QAElement
-{
-public:
- QAElement();
- explicit QAElement(AXUIElementRef elementRef);
- QAElement(const QAElement &element);
- QAElement(HIObjectRef, int child);
- ~QAElement();
-
- inline HIObjectRef object() const
- {
-#ifndef Q_WS_MAC64
- return AXUIElementGetHIObject(elementRef);
-#else
- return 0;
-#endif
- }
-
- inline int id() const
- {
- UInt64 theId;
-#ifndef QT_MAC_USE_COCOA
- AXUIElementGetIdentifier(elementRef, &theId);
-#else
- theId = 0;
-#endif
- return theId;
- }
-
- inline AXUIElementRef element() const
- {
- return elementRef;
- }
-
- inline bool isValid() const
- {
- return (elementRef != 0);
- }
-
- void operator=(const QAElement &other);
- bool operator==(const QAElement &other) const;
-private:
- AXUIElementRef elementRef;
-};
-
-
-class QInterfaceFactory
-{
-public:
- virtual QAInterface interface(UInt64 identifier) = 0;
- virtual QAElement element(int id) = 0;
- virtual QAElement element(const QAInterface &interface)
- {
- return element(interface.id());
- }
- virtual void registerChildren() = 0;
- virtual ~QInterfaceFactory() {}
-};
-
-/*
- QAccessibleHierarchyManager bridges the Mac and Qt accessibility hierarchies.
- There is a one-to-one relationship between QAElements on the Mac side
- and QAInterfaces on the Qt side, and this class provides lookup functions
- that translates between these to items.
-
- The identity of a QAInterface is determined by its QAccessibleInterface and
- child identifier, and the identity of a QAElement is determined by its
- HIObjectRef and identifier.
-
- QAccessibleHierarchyManager receives QObject::destroyed() signals and deletes
- the accessibility objects for destroyed objects.
-*/
-class Q_AUTOTEST_EXPORT QAccessibleHierarchyManager : public QObject
-{
-Q_OBJECT
-public:
- ~QAccessibleHierarchyManager() { reset(); }
- static QAccessibleHierarchyManager *instance();
- void reset();
-
- QAElement registerInterface(QObject *object, int child);
- QAElement registerInterface(const QAInterface &interface);
- void registerInterface(QObject *object, HIObjectRef hiobject, QInterfaceFactory *interfaceFactory);
-
- void registerChildren(const QAInterface &interface);
-
- QAInterface lookup(const AXUIElementRef &element);
- QAInterface lookup(const QAElement &element);
- QAElement lookup(const QAInterface &interface);
- QAElement lookup(QObject * const object, int id);
-private slots:
- void objectDestroyed(QObject *);
-private:
- typedef QHash<QObject *, QInterfaceFactory *> QObjectElementHash;
- typedef QHash<HIObjectRef, QInterfaceFactory *> HIObjectInterfaceHash;
- typedef QHash<QObject *, HIObjectRef> QObjectHIObjectHash;
-
- QObjectElementHash qobjectElementHash;
- HIObjectInterfaceHash hiobjectInterfaceHash;
- QObjectHIObjectHash qobjectHiobjectHash;
-};
-
-Q_AUTOTEST_EXPORT bool isItInteresting(const QAInterface &interface);
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/accessible/qaccessible_unix.cpp b/src/gui/accessible/qaccessible_unix.cpp
deleted file mode 100644
index f04d075543..0000000000
--- a/src/gui/accessible/qaccessible_unix.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessible.h"
-#include "qaccessiblebridge.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qcoreapplication.h"
-#include "qmutex.h"
-#include "qvector.h"
-#include "private/qfactoryloader_p.h"
-
-#include <stdlib.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_LIBRARY
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QAccessibleBridgeFactoryInterface_iid, QLatin1String("/accessiblebridge")))
-#endif
-Q_GLOBAL_STATIC(QVector<QAccessibleBridge *>, bridges)
-static bool isInit = false;
-
-void QAccessible::initialize()
-{
- if (isInit)
- return;
- isInit = true;
-
- if (qgetenv("QT_ACCESSIBILITY") != "1")
- return;
-#ifndef QT_NO_LIBRARY
- const QStringList l = loader()->keys();
- for (int i = 0; i < l.count(); ++i) {
- if (QAccessibleBridgeFactoryInterface *factory =
- qobject_cast<QAccessibleBridgeFactoryInterface*>(loader()->instance(l.at(i)))) {
- QAccessibleBridge * bridge = factory->create(l.at(i));
- if (bridge)
- bridges()->append(bridge);
- }
- }
-#endif
-}
-
-void QAccessible::cleanup()
-{
- qDeleteAll(*bridges());
-}
-
-void QAccessible::updateAccessibility(QObject *o, int who, Event reason)
-{
- Q_ASSERT(o);
-
- if (updateHandler) {
- updateHandler(o, who, reason);
- return;
- }
-
- initialize();
- if (bridges()->isEmpty())
- return;
-
- QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(o);
- if (!iface)
- return;
-
- for (int i = 0; i < bridges()->count(); ++i)
- bridges()->at(i)->notifyAccessibilityUpdate(reason, iface, who);
- delete iface;
-}
-
-void QAccessible::setRootObject(QObject *o)
-{
- if (rootObjectHandler) {
- rootObjectHandler(o);
- return;
- }
-
- initialize();
- if (bridges()->isEmpty())
- return;
-
- if (!o)
- return;
-
- for (int i = 0; i < bridges()->count(); ++i) {
- QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(o);
- bridges()->at(i)->setRootObject(iface);
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
-
diff --git a/src/gui/accessible/qaccessible_win.cpp b/src/gui/accessible/qaccessible_win.cpp
deleted file mode 100644
index caa21043d8..0000000000
--- a/src/gui/accessible/qaccessible_win.cpp
+++ /dev/null
@@ -1,1217 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessible.h"
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qapplication.h"
-#include <private/qsystemlibrary_p.h>
-#include "qmessagebox.h" // ### dependency
-#include "qt_windows.h"
-#include "qwidget.h"
-#include "qsettings.h"
-
-#include <winuser.h>
-#if !defined(WINABLEAPI)
-# if defined(Q_WS_WINCE)
-# include <bldver.h>
-# endif
-# include <winable.h>
-#endif
-
-#include <oleacc.h>
-#if !defined(Q_CC_BOR) && !defined (Q_CC_GNU)
-#include <comdef.h>
-#endif
-
-#ifdef Q_WS_WINCE
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-//#define DEBUG_SHOW_ATCLIENT_COMMANDS
-#ifdef DEBUG_SHOW_ATCLIENT_COMMANDS
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qdebug.h>
-QT_END_INCLUDE_NAMESPACE
-
-static const char *roleString(QAccessible::Role role)
-{
- static const char *roles[] = {
- "NoRole" /* = 0x00000000 */,
- "TitleBar" /* = 0x00000001 */,
- "MenuBar" /* = 0x00000002 */,
- "ScrollBar" /* = 0x00000003 */,
- "Grip" /* = 0x00000004 */,
- "Sound" /* = 0x00000005 */,
- "Cursor" /* = 0x00000006 */,
- "Caret" /* = 0x00000007 */,
- "AlertMessage" /* = 0x00000008 */,
- "Window" /* = 0x00000009 */,
- "Client" /* = 0x0000000A */,
- "PopupMenu" /* = 0x0000000B */,
- "MenuItem" /* = 0x0000000C */,
- "ToolTip" /* = 0x0000000D */,
- "Application" /* = 0x0000000E */,
- "Document" /* = 0x0000000F */,
- "Pane" /* = 0x00000010 */,
- "Chart" /* = 0x00000011 */,
- "Dialog" /* = 0x00000012 */,
- "Border" /* = 0x00000013 */,
- "Grouping" /* = 0x00000014 */,
- "Separator" /* = 0x00000015 */,
- "ToolBar" /* = 0x00000016 */,
- "StatusBar" /* = 0x00000017 */,
- "Table" /* = 0x00000018 */,
- "ColumnHeader" /* = 0x00000019 */,
- "RowHeader" /* = 0x0000001A */,
- "Column" /* = 0x0000001B */,
- "Row" /* = 0x0000001C */,
- "Cell" /* = 0x0000001D */,
- "Link" /* = 0x0000001E */,
- "HelpBalloon" /* = 0x0000001F */,
- "Assistant" /* = 0x00000020 */,
- "List" /* = 0x00000021 */,
- "ListItem" /* = 0x00000022 */,
- "Tree" /* = 0x00000023 */,
- "TreeItem" /* = 0x00000024 */,
- "PageTab" /* = 0x00000025 */,
- "PropertyPage" /* = 0x00000026 */,
- "Indicator" /* = 0x00000027 */,
- "Graphic" /* = 0x00000028 */,
- "StaticText" /* = 0x00000029 */,
- "EditableText" /* = 0x0000002A */, // Editable, selectable, etc.
- "PushButton" /* = 0x0000002B */,
- "CheckBox" /* = 0x0000002C */,
- "RadioButton" /* = 0x0000002D */,
- "ComboBox" /* = 0x0000002E */,
- "DropList" /* = 0x0000002F */, // commented out
- "ProgressBar" /* = 0x00000030 */,
- "Dial" /* = 0x00000031 */,
- "HotkeyField" /* = 0x00000032 */,
- "Slider" /* = 0x00000033 */,
- "SpinBox" /* = 0x00000034 */,
- "Canvas" /* = 0x00000035 */,
- "Animation" /* = 0x00000036 */,
- "Equation" /* = 0x00000037 */,
- "ButtonDropDown" /* = 0x00000038 */,
- "ButtonMenu" /* = 0x00000039 */,
- "ButtonDropGrid" /* = 0x0000003A */,
- "Whitespace" /* = 0x0000003B */,
- "PageTabList" /* = 0x0000003C */,
- "Clock" /* = 0x0000003D */,
- "Splitter" /* = 0x0000003E */,
- "LayeredPane" /* = 0x0000003F */,
- "UserRole" /* = 0x0000ffff*/
- };
-
- if (role >=0x40)
- role = QAccessible::UserRole;
- return roles[int(role)];
-}
-
-void showDebug(const char* funcName, const QAccessibleInterface *iface)
-{
- qDebug() << "Role:" << roleString(iface->role(0))
- << "Name:" << iface->text(QAccessible::Name, 0)
- << "State:" << QString::number(int(iface->state(0)), 16)
- << QLatin1String(funcName);
-}
-#else
-# define showDebug(f, iface)
-#endif
-
-void QAccessible::initialize()
-{
-
-}
-void QAccessible::cleanup()
-{
-
-}
-
-void QAccessible::updateAccessibility(QObject *o, int who, Event reason)
-{
- Q_ASSERT(o);
-
- if (updateHandler) {
- updateHandler(o, who, reason);
- return;
- }
-
- QString soundName;
- switch (reason) {
- case PopupMenuStart:
- soundName = QLatin1String("MenuPopup");
- break;
-
- case MenuCommand:
- soundName = QLatin1String("MenuCommand");
- break;
-
- case Alert:
- {
-#ifndef QT_NO_MESSAGEBOX
- QMessageBox *mb = qobject_cast<QMessageBox*>(o);
- if (mb) {
- switch (mb->icon()) {
- case QMessageBox::Warning:
- soundName = QLatin1String("SystemExclamation");
- break;
- case QMessageBox::Critical:
- soundName = QLatin1String("SystemHand");
- break;
- case QMessageBox::Information:
- soundName = QLatin1String("SystemAsterisk");
- break;
- default:
- break;
- }
- } else
-#endif // QT_NO_MESSAGEBOX
- {
- soundName = QLatin1String("SystemAsterisk");
- }
-
- }
- break;
- default:
- break;
- }
-
- if (soundName.size()) {
-#ifndef QT_NO_SETTINGS
- QSettings settings(QLatin1String("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\.Default\\") + soundName,
- QSettings::NativeFormat);
- QString file = settings.value(QLatin1String(".Current/.")).toString();
-#else
- QString file;
-#endif
- if (!file.isEmpty()) {
- PlaySound(reinterpret_cast<const wchar_t *>(soundName.utf16()), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT);
- }
- }
-
- if (!isActive())
- return;
-
- typedef void (WINAPI *PtrNotifyWinEvent)(DWORD, HWND, LONG, LONG);
-
-#if defined(Q_WS_WINCE) // ### TODO: check for NotifyWinEvent in CE 6.0
- // There is no user32.lib nor NotifyWinEvent for CE
- return;
-#else
- static PtrNotifyWinEvent ptrNotifyWinEvent = 0;
- static bool resolvedNWE = false;
- if (!resolvedNWE) {
- resolvedNWE = true;
- ptrNotifyWinEvent = (PtrNotifyWinEvent)QSystemLibrary::resolve(QLatin1String("user32"), "NotifyWinEvent");
- }
- if (!ptrNotifyWinEvent)
- return;
-
- // An event has to be associated with a window,
- // so find the first parent that is a widget.
- QWidget *w = 0;
- if (o->isWidgetType()) {
- w = (QWidget*)o;
- } else {
- QObject *p = o;
- while ((p = p->parent()) != 0) {
- if (p->isWidgetType()) {
- w = (QWidget*)p;
- break;
- }
- }
- }
-
- if (!w) {
- if (reason != QAccessible::ContextHelpStart &&
- reason != QAccessible::ContextHelpEnd)
- w = QApplication::focusWidget();
- if (!w) {
- w = QApplication::activeWindow();
-
- if (!w)
- return;
-
-// ### Fixme
-// if (!w) {
-// w = qApp->mainWidget();
-// if (!w)
-// return;
-// }
- }
- }
-
- if (reason != MenuCommand) { // MenuCommand is faked
- ptrNotifyWinEvent(reason, w->winId(), OBJID_CLIENT, who);
- }
-#endif // Q_WS_WINCE
-}
-
-void QAccessible::setRootObject(QObject *o)
-{
- if (rootObjectHandler) {
- rootObjectHandler(o);
- }
-}
-
-class QWindowsEnumerate : public IEnumVARIANT
-{
-public:
- QWindowsEnumerate(const QVector<int> &a)
- : ref(0), current(0),array(a)
- {
- }
-
- virtual ~QWindowsEnumerate() {}
-
- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, LPVOID *);
- ULONG STDMETHODCALLTYPE AddRef();
- ULONG STDMETHODCALLTYPE Release();
-
- HRESULT STDMETHODCALLTYPE Clone(IEnumVARIANT **ppEnum);
- HRESULT STDMETHODCALLTYPE Next(unsigned long celt, VARIANT FAR* rgVar, unsigned long FAR* pCeltFetched);
- HRESULT STDMETHODCALLTYPE Reset();
- HRESULT STDMETHODCALLTYPE Skip(unsigned long celt);
-
-private:
- ULONG ref;
- ULONG current;
- QVector<int> array;
-};
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::QueryInterface(REFIID id, LPVOID *iface)
-{
- *iface = 0;
- if (id == IID_IUnknown)
- *iface = (IUnknown*)this;
- else if (id == IID_IEnumVARIANT)
- *iface = (IEnumVARIANT*)this;
-
- if (*iface) {
- AddRef();
- return S_OK;
- }
-
- return E_NOINTERFACE;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsEnumerate::AddRef()
-{
- return ++ref;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsEnumerate::Release()
-{
- if (!--ref) {
- delete this;
- return 0;
- }
- return ref;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Clone(IEnumVARIANT **ppEnum)
-{
- QWindowsEnumerate *penum = 0;
- *ppEnum = 0;
-
- penum = new QWindowsEnumerate(array);
- if (!penum)
- return E_OUTOFMEMORY;
- penum->current = current;
- penum->array = array;
- penum->AddRef();
- *ppEnum = penum;
-
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Next(unsigned long celt, VARIANT FAR* rgVar, unsigned long FAR* pCeltFetched)
-{
- if (pCeltFetched)
- *pCeltFetched = 0;
-
- ULONG l;
- for (l = 0; l < celt; l++) {
- VariantInit(&rgVar[l]);
- if ((current+1) > (ULONG)array.size()) {
- *pCeltFetched = l;
- return S_FALSE;
- }
-
- rgVar[l].vt = VT_I4;
- rgVar[l].lVal = array[(int)current];
- ++current;
- }
- *pCeltFetched = l;
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Reset()
-{
- current = 0;
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Skip(unsigned long celt)
-{
- current += celt;
- if (current > (ULONG)array.size()) {
- current = array.size();
- return S_FALSE;
- }
- return S_OK;
-}
-
-/*
-*/
-class QWindowsAccessible : public IAccessible, IOleWindow, QAccessible
-{
-public:
- QWindowsAccessible(QAccessibleInterface *a)
- : ref(0), accessible(a)
- {
- }
-
- virtual ~QWindowsAccessible()
- {
- delete accessible;
- }
-
- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, LPVOID *);
- ULONG STDMETHODCALLTYPE AddRef();
- ULONG STDMETHODCALLTYPE Release();
-
- HRESULT STDMETHODCALLTYPE GetTypeInfoCount(unsigned int *);
- HRESULT STDMETHODCALLTYPE GetTypeInfo(unsigned int, unsigned long, ITypeInfo **);
- HRESULT STDMETHODCALLTYPE GetIDsOfNames(const _GUID &, wchar_t **, unsigned int, unsigned long, long *);
- HRESULT STDMETHODCALLTYPE Invoke(long, const _GUID &, unsigned long, unsigned short, tagDISPPARAMS *, tagVARIANT *, tagEXCEPINFO *, unsigned int *);
-
- HRESULT STDMETHODCALLTYPE accHitTest(long xLeft, long yTop, VARIANT *pvarID);
- HRESULT STDMETHODCALLTYPE accLocation(long *pxLeft, long *pyTop, long *pcxWidth, long *pcyHeight, VARIANT varID);
- HRESULT STDMETHODCALLTYPE accNavigate(long navDir, VARIANT varStart, VARIANT *pvarEnd);
- HRESULT STDMETHODCALLTYPE get_accChild(VARIANT varChildID, IDispatch** ppdispChild);
- HRESULT STDMETHODCALLTYPE get_accChildCount(long* pcountChildren);
- HRESULT STDMETHODCALLTYPE get_accParent(IDispatch** ppdispParent);
-
- HRESULT STDMETHODCALLTYPE accDoDefaultAction(VARIANT varID);
- HRESULT STDMETHODCALLTYPE get_accDefaultAction(VARIANT varID, BSTR* pszDefaultAction);
- HRESULT STDMETHODCALLTYPE get_accDescription(VARIANT varID, BSTR* pszDescription);
- HRESULT STDMETHODCALLTYPE get_accHelp(VARIANT varID, BSTR *pszHelp);
- HRESULT STDMETHODCALLTYPE get_accHelpTopic(BSTR *pszHelpFile, VARIANT varChild, long *pidTopic);
- HRESULT STDMETHODCALLTYPE get_accKeyboardShortcut(VARIANT varID, BSTR *pszKeyboardShortcut);
- HRESULT STDMETHODCALLTYPE get_accName(VARIANT varID, BSTR* pszName);
- HRESULT STDMETHODCALLTYPE put_accName(VARIANT varChild, BSTR szName);
- HRESULT STDMETHODCALLTYPE get_accRole(VARIANT varID, VARIANT *pvarRole);
- HRESULT STDMETHODCALLTYPE get_accState(VARIANT varID, VARIANT *pvarState);
- HRESULT STDMETHODCALLTYPE get_accValue(VARIANT varID, BSTR* pszValue);
- HRESULT STDMETHODCALLTYPE put_accValue(VARIANT varChild, BSTR szValue);
-
- HRESULT STDMETHODCALLTYPE accSelect(long flagsSelect, VARIANT varID);
- HRESULT STDMETHODCALLTYPE get_accFocus(VARIANT *pvarID);
- HRESULT STDMETHODCALLTYPE get_accSelection(VARIANT *pvarChildren);
-
- HRESULT STDMETHODCALLTYPE GetWindow(HWND *phwnd);
- HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(BOOL fEnterMode);
-
-private:
- ULONG ref;
- QAccessibleInterface *accessible;
-};
-
-static inline BSTR QStringToBSTR(const QString &str)
-{
- BSTR bstrVal;
-
- int wlen = str.length()+1;
- bstrVal = SysAllocStringByteLen(0, wlen*2);
- memcpy(bstrVal, str.unicode(), sizeof(QChar)*(wlen));
- bstrVal[wlen] = 0;
-
- return bstrVal;
-}
-
-/*
-*/
-IAccessible *qt_createWindowsAccessible(QAccessibleInterface *access)
-{
- QWindowsAccessible *acc = new QWindowsAccessible(access);
- IAccessible *iface;
- acc->QueryInterface(IID_IAccessible, (void**)&iface);
-
- return iface;
-}
-
-/*
- IUnknown
-*/
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::QueryInterface(REFIID id, LPVOID *iface)
-{
- *iface = 0;
- if (id == IID_IUnknown)
- *iface = (IUnknown*)(IDispatch*)this;
- else if (id == IID_IDispatch)
- *iface = (IDispatch*)this;
- else if (id == IID_IAccessible)
- *iface = (IAccessible*)this;
- else if (id == IID_IOleWindow)
- *iface = (IOleWindow*)this;
- else
- return E_NOINTERFACE;
-
- AddRef();
- return S_OK;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsAccessible::AddRef()
-{
- return ++ref;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsAccessible::Release()
-{
- if (!--ref) {
- delete this;
- return 0;
- }
- return ref;
-}
-
-/*
- IDispatch
-*/
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetTypeInfoCount(unsigned int * pctinfo)
-{
- // We don't use a type library
- *pctinfo = 0;
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetTypeInfo(unsigned int, unsigned long, ITypeInfo **pptinfo)
-{
- // We don't use a type library
- *pptinfo = 0;
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetIDsOfNames(const _GUID &, wchar_t **rgszNames, unsigned int, unsigned long, long *rgdispid)
-{
-#if !defined(Q_CC_BOR) && !defined(Q_CC_GNU)
- // PROPERTIES: Hierarchical
- if (_bstr_t(rgszNames[0]) == _bstr_t(L"accParent"))
- rgdispid[0] = DISPID_ACC_PARENT;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accChildCount"))
- rgdispid[0] = DISPID_ACC_CHILDCOUNT;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accChild"))
- rgdispid[0] = DISPID_ACC_CHILD;
-
- // PROPERTIES: Descriptional
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accName("))
- rgdispid[0] = DISPID_ACC_NAME;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accValue"))
- rgdispid[0] = DISPID_ACC_VALUE;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accDescription"))
- rgdispid[0] = DISPID_ACC_DESCRIPTION;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accRole"))
- rgdispid[0] = DISPID_ACC_ROLE;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accState"))
- rgdispid[0] = DISPID_ACC_STATE;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accHelp"))
- rgdispid[0] = DISPID_ACC_HELP;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accHelpTopic"))
- rgdispid[0] = DISPID_ACC_HELPTOPIC;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accKeyboardShortcut"))
- rgdispid[0] = DISPID_ACC_KEYBOARDSHORTCUT;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accFocus"))
- rgdispid[0] = DISPID_ACC_FOCUS;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accSelection"))
- rgdispid[0] = DISPID_ACC_SELECTION;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accDefaultAction"))
- rgdispid[0] = DISPID_ACC_DEFAULTACTION;
-
- // METHODS
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accSelect"))
- rgdispid[0] = DISPID_ACC_SELECT;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accLocation"))
- rgdispid[0] = DISPID_ACC_LOCATION;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accNavigate"))
- rgdispid[0] = DISPID_ACC_NAVIGATE;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accHitTest"))
- rgdispid[0] = DISPID_ACC_HITTEST;
- else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accDoDefaultAction"))
- rgdispid[0] = DISPID_ACC_DODEFAULTACTION;
- else
- return DISP_E_UNKNOWNINTERFACE;
-
- return S_OK;
-#else
- Q_UNUSED(rgszNames);
- Q_UNUSED(rgdispid);
-
- return DISP_E_MEMBERNOTFOUND;
-#endif
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::Invoke(long dispIdMember, const _GUID &, unsigned long, unsigned short wFlags, tagDISPPARAMS *pDispParams, tagVARIANT *pVarResult, tagEXCEPINFO *, unsigned int *)
-{
- HRESULT hr = DISP_E_MEMBERNOTFOUND;
-
- switch(dispIdMember)
- {
- case DISPID_ACC_PARENT:
- if (wFlags == DISPATCH_PROPERTYGET) {
- if (!pVarResult)
- return E_INVALIDARG;
- hr = get_accParent(&pVarResult->pdispVal);
- } else {
- hr = DISP_E_MEMBERNOTFOUND;
- }
- break;
-
- case DISPID_ACC_CHILDCOUNT:
- if (wFlags == DISPATCH_PROPERTYGET) {
- if (!pVarResult)
- return E_INVALIDARG;
- hr = get_accChildCount(&pVarResult->lVal);
- } else {
- hr = DISP_E_MEMBERNOTFOUND;
- }
- break;
-
- case DISPID_ACC_CHILD:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accChild(pDispParams->rgvarg[0], &pVarResult->pdispVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_NAME:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accName(pDispParams->rgvarg[0], &pVarResult->bstrVal);
- else if (wFlags == DISPATCH_PROPERTYPUT)
- hr = put_accName(pDispParams->rgvarg[0], pVarResult->bstrVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_VALUE:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accValue(pDispParams->rgvarg[0], &pVarResult->bstrVal);
- else if (wFlags == DISPATCH_PROPERTYPUT)
- hr = put_accValue(pDispParams->rgvarg[0], pVarResult->bstrVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_DESCRIPTION:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accDescription(pDispParams->rgvarg[0], &pVarResult->bstrVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_ROLE:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accRole(pDispParams->rgvarg[0], pVarResult);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_STATE:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accState(pDispParams->rgvarg[0], pVarResult);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_HELP:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accHelp(pDispParams->rgvarg[0], &pVarResult->bstrVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_HELPTOPIC:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accHelpTopic(&pDispParams->rgvarg[2].bstrVal, pDispParams->rgvarg[1], &pDispParams->rgvarg[0].lVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_KEYBOARDSHORTCUT:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accKeyboardShortcut(pDispParams->rgvarg[0], &pVarResult->bstrVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_FOCUS:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accFocus(pVarResult);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_SELECTION:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accSelection(pVarResult);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_DEFAULTACTION:
- if (wFlags == DISPATCH_PROPERTYGET)
- hr = get_accDefaultAction(pDispParams->rgvarg[0], &pVarResult->bstrVal);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_SELECT:
- if (wFlags == DISPATCH_METHOD)
- hr = accSelect(pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0]);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_LOCATION:
- if (wFlags == DISPATCH_METHOD)
- hr = accLocation(&pDispParams->rgvarg[4].lVal, &pDispParams->rgvarg[3].lVal, &pDispParams->rgvarg[2].lVal, &pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0]);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_NAVIGATE:
- if (wFlags == DISPATCH_METHOD)
- hr = accNavigate(pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0], pVarResult);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_HITTEST:
- if (wFlags == DISPATCH_METHOD)
- hr = accHitTest(pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0].lVal, pVarResult);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- case DISPID_ACC_DODEFAULTACTION:
- if (wFlags == DISPATCH_METHOD)
- hr = accDoDefaultAction(pDispParams->rgvarg[0]);
- else
- hr = DISP_E_MEMBERNOTFOUND;
- break;
-
- default:
- hr = DISP_E_MEMBERNOTFOUND;
- break;
- }
-
- if (!SUCCEEDED(hr)) {
- return hr;
- }
- return hr;
-}
-
-/*
- IAccessible
-*/
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accHitTest(long xLeft, long yTop, VARIANT *pvarID)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- int control = accessible->childAt(xLeft, yTop);
- if (control == -1) {
- (*pvarID).vt = VT_EMPTY;
- return S_FALSE;
- }
- QAccessibleInterface *acc = 0;
- if (control)
- accessible->navigate(Child, control, &acc);
- if (!acc) {
- (*pvarID).vt = VT_I4;
- (*pvarID).lVal = control;
- return S_OK;
- }
-
- QWindowsAccessible* wacc = new QWindowsAccessible(acc);
- IDispatch *iface = 0;
- wacc->QueryInterface(IID_IDispatch, (void**)&iface);
- if (iface) {
- (*pvarID).vt = VT_DISPATCH;
- (*pvarID).pdispVal = iface;
- return S_OK;
- } else {
- delete wacc;
- }
-
- (*pvarID).vt = VT_EMPTY;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accLocation(long *pxLeft, long *pyTop, long *pcxWidth, long *pcyHeight, VARIANT varID)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QRect rect = accessible->rect(varID.lVal);
- if (rect.isValid()) {
- *pxLeft = rect.x();
- *pyTop = rect.y();
- *pcxWidth = rect.width();
- *pcyHeight = rect.height();
- } else {
- *pxLeft = 0;
- *pyTop = 0;
- *pcxWidth = 0;
- *pcyHeight = 0;
- }
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accNavigate(long navDir, VARIANT varStart, VARIANT *pvarEnd)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QAccessibleInterface *acc = 0;
- int control = -1;
- switch(navDir) {
- case NAVDIR_FIRSTCHILD:
- control = accessible->navigate(Child, 1, &acc);
- break;
- case NAVDIR_LASTCHILD:
- control = accessible->navigate(Child, accessible->childCount(), &acc);
- break;
- case NAVDIR_NEXT:
- case NAVDIR_PREVIOUS:
- if (!varStart.lVal){
- QAccessibleInterface *parent = 0;
- accessible->navigate(Ancestor, 1, &parent);
- if (parent) {
- int index = parent->indexOfChild(accessible);
- index += (navDir == NAVDIR_NEXT) ? 1 : -1;
- if (index > 0 && index <= parent->childCount())
- control = parent->navigate(Child, index, &acc);
- delete parent;
- }
- } else {
- int index = varStart.lVal;
- index += (navDir == NAVDIR_NEXT) ? 1 : -1;
- if (index > 0 && index <= accessible->childCount())
- control = accessible->navigate(Child, index, &acc);
- }
- break;
- case NAVDIR_UP:
- control = accessible->navigate(Up, varStart.lVal, &acc);
- break;
- case NAVDIR_DOWN:
- control = accessible->navigate(Down, varStart.lVal, &acc);
- break;
- case NAVDIR_LEFT:
- control = accessible->navigate(Left, varStart.lVal, &acc);
- break;
- case NAVDIR_RIGHT:
- control = accessible->navigate(Right, varStart.lVal, &acc);
- break;
- default:
- break;
- }
- if (control == -1) {
- (*pvarEnd).vt = VT_EMPTY;
- return S_FALSE;
- }
- if (!acc) {
- (*pvarEnd).vt = VT_I4;
- (*pvarEnd).lVal = control;
- return S_OK;
- }
-
- QWindowsAccessible* wacc = new QWindowsAccessible(acc);
-
- IDispatch *iface = 0;
- wacc->QueryInterface(IID_IDispatch, (void**)&iface);
- if (iface) {
- (*pvarEnd).vt = VT_DISPATCH;
- (*pvarEnd).pdispVal = iface;
- return S_OK;
- } else {
- delete wacc;
- }
-
- (*pvarEnd).vt = VT_EMPTY;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accChild(VARIANT varChildID, IDispatch** ppdispChild)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- if (varChildID.vt == VT_EMPTY)
- return E_INVALIDARG;
-
- QAccessibleInterface *acc = 0;
- RelationFlag rel = varChildID.lVal ? Child : Self;
- accessible->navigate(rel, varChildID.lVal, &acc);
-
- if (acc) {
- QWindowsAccessible* wacc = new QWindowsAccessible(acc);
- wacc->QueryInterface(IID_IDispatch, (void**)ppdispChild);
- return S_OK;
- }
-
- *ppdispChild = 0;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accChildCount(long* pcountChildren)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- *pcountChildren = accessible->childCount();
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accParent(IDispatch** ppdispParent)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QAccessibleInterface *acc = 0;
- accessible->navigate(Ancestor, 1, &acc);
- if (acc) {
- QWindowsAccessible* wacc = new QWindowsAccessible(acc);
- wacc->QueryInterface(IID_IDispatch, (void**)ppdispParent);
-
- if (*ppdispParent)
- return S_OK;
- }
-
- *ppdispParent = 0;
- return S_FALSE;
-}
-
-/*
- Properties and methods
-*/
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accDoDefaultAction(VARIANT varID)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- return accessible->doAction(DefaultAction, varID.lVal, QVariantList()) ? S_OK : S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accDefaultAction(VARIANT varID, BSTR* pszDefaultAction)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QString def = accessible->actionText(DefaultAction, Name, varID.lVal);
- if (def.isEmpty()) {
- *pszDefaultAction = 0;
- return S_FALSE;
- }
-
- *pszDefaultAction = QStringToBSTR(def);
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accDescription(VARIANT varID, BSTR* pszDescription)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QString descr = accessible->text(Description, varID.lVal);
- if (descr.size()) {
- *pszDescription = QStringToBSTR(descr);
- return S_OK;
- }
-
- *pszDescription = 0;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accHelp(VARIANT varID, BSTR *pszHelp)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QString help = accessible->text(Help, varID.lVal);
- if (help.size()) {
- *pszHelp = QStringToBSTR(help);
- return S_OK;
- }
-
- *pszHelp = 0;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accHelpTopic(BSTR *, VARIANT, long *)
-{
- return DISP_E_MEMBERNOTFOUND;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accKeyboardShortcut(VARIANT varID, BSTR *pszKeyboardShortcut)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QString sc = accessible->text(Accelerator, varID.lVal);
- if (sc.size()) {
- *pszKeyboardShortcut = QStringToBSTR(sc);
- return S_OK;
- }
-
- *pszKeyboardShortcut = 0;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accName(VARIANT varID, BSTR* pszName)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QString n = accessible->text(Name, varID.lVal);
- if (n.size()) {
- *pszName = QStringToBSTR(n);
- return S_OK;
- }
-
- *pszName = 0;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::put_accName(VARIANT, BSTR)
-{
- showDebug(__FUNCTION__, accessible);
- return DISP_E_MEMBERNOTFOUND;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accRole(VARIANT varID, VARIANT *pvarRole)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- Role role = accessible->role(varID.lVal);
- if (role != NoRole) {
- if (role == LayeredPane)
- role = QAccessible::Pane;
- (*pvarRole).vt = VT_I4;
- (*pvarRole).lVal = role;
- } else {
- (*pvarRole).vt = VT_EMPTY;
- }
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accState(VARIANT varID, VARIANT *pvarState)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- (*pvarState).vt = VT_I4;
- (*pvarState).lVal = accessible->state(varID.lVal);
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accValue(VARIANT varID, BSTR* pszValue)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QString value = accessible->text(Value, varID.lVal);
- if (!value.isNull()) {
- *pszValue = QStringToBSTR(value);
- return S_OK;
- }
-
- *pszValue = 0;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::put_accValue(VARIANT, BSTR)
-{
- showDebug(__FUNCTION__, accessible);
- return DISP_E_MEMBERNOTFOUND;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accSelect(long flagsSelect, VARIANT varID)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- bool res = false;
-
- if (flagsSelect & SELFLAG_TAKEFOCUS)
- res = accessible->doAction(SetFocus, varID.lVal, QVariantList());
- if (flagsSelect & SELFLAG_TAKESELECTION) {
- accessible->doAction(ClearSelection, 0, QVariantList());
- res = accessible->doAction(AddToSelection, varID.lVal, QVariantList());
- }
- if (flagsSelect & SELFLAG_EXTENDSELECTION)
- res = accessible->doAction(ExtendSelection, varID.lVal, QVariantList());
- if (flagsSelect & SELFLAG_ADDSELECTION)
- res = accessible->doAction(AddToSelection, varID.lVal, QVariantList());
- if (flagsSelect & SELFLAG_REMOVESELECTION)
- res = accessible->doAction(RemoveSelection, varID.lVal, QVariantList());
-
- return res ? S_OK : S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accFocus(VARIANT *pvarID)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- QAccessibleInterface *acc = 0;
- int control = accessible->navigate(FocusChild, 1, &acc);
- if (control == -1) {
- (*pvarID).vt = VT_EMPTY;
- return S_FALSE;
- }
- if (!acc || control == 0) {
- (*pvarID).vt = VT_I4;
- (*pvarID).lVal = control ? control : CHILDID_SELF;
- return S_OK;
- }
-
- QWindowsAccessible* wacc = new QWindowsAccessible(acc);
- IDispatch *iface = 0;
- wacc->QueryInterface(IID_IDispatch, (void**)&iface);
- if (iface) {
- (*pvarID).vt = VT_DISPATCH;
- (*pvarID).pdispVal = iface;
- return S_OK;
- } else {
- delete wacc;
- }
-
- (*pvarID).vt = VT_EMPTY;
- return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accSelection(VARIANT *pvarChildren)
-{
- showDebug(__FUNCTION__, accessible);
- if (!accessible->isValid())
- return E_FAIL;
-
- int cc = accessible->childCount();
- QVector<int> sel(cc);
- int selIndex = 0;
- for (int i = 1; i <= cc; ++i) {
- QAccessibleInterface *child = 0;
- int i2 = accessible->navigate(Child, i, &child);
- bool isSelected = false;
- if (child) {
- isSelected = child->state(0) & Selected;
- delete child;
- child = 0;
- } else {
- isSelected = accessible->state(i2) & Selected;
- }
- if (isSelected)
- sel[selIndex++] = i;
- }
- sel.resize(selIndex);
- if (sel.isEmpty()) {
- (*pvarChildren).vt = VT_EMPTY;
- return S_FALSE;
- }
- if (sel.size() == 1) {
- (*pvarChildren).vt = VT_I4;
- (*pvarChildren).lVal = sel[0];
- return S_OK;
- }
- IEnumVARIANT *iface = new QWindowsEnumerate(sel);
- IUnknown *uiface;
- iface->QueryInterface(IID_IUnknown, (void**)&uiface);
- (*pvarChildren).vt = VT_UNKNOWN;
- (*pvarChildren).punkVal = uiface;
-
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetWindow(HWND *phwnd)
-{
- *phwnd = 0;
- if (!accessible->isValid())
- return E_UNEXPECTED;
-
- QObject *o = accessible->object();
- if (!o || !o->isWidgetType())
- return E_FAIL;
-
- *phwnd = static_cast<QWidget*>(o)->winId();
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::ContextSensitiveHelp(BOOL)
-{
- return S_OK;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessiblebridge.cpp b/src/gui/accessible/qaccessiblebridge.cpp
deleted file mode 100644
index e151bb6752..0000000000
--- a/src/gui/accessible/qaccessiblebridge.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessiblebridge.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAccessibleBridge
- \brief The QAccessibleBridge class is the base class for
- accessibility back-ends.
-
- \ingroup accessibility
-
- Qt supports Microsoft Active Accessibility (MSAA), Mac OS X
- Accessibility, and the Unix/X11 AT-SPI standard. By subclassing
- QAccessibleBridge, you can support other backends than the
- predefined ones.
-
- Currently, custom bridges are only supported on Unix. We might
- add support for them on other platforms as well if there is
- enough demand.
-
- \sa QAccessible, QAccessibleBridgePlugin
-*/
-
-/*!
- \fn QAccessibleBridge::~QAccessibleBridge()
-
- Destroys the accessibility bridge object.
-*/
-
-/*!
- \fn void QAccessibleBridge::setRootObject(QAccessibleInterface *object)
-
- This function is called by Qt at application startup to set the
- root accessible object of the application to \a object. All other
- accessible objects in the application can be reached by the
- client using object navigation.
-*/
-
-/*!
- \fn void QAccessibleBridge::notifyAccessibilityUpdate(int reason, QAccessibleInterface *interface, int child)
-
- This function is called by Qt to notify the bridge about a change
- in the accessibility information for object wrapped by the given
- \a interface.
-
- \a reason specifies the cause of the change. It can take values
- of type QAccessible::Event.
-
- \a child is the (1-based) index of the child element that has
- changed. When \a child is 0, the object itself has changed.
-
- \sa QAccessible::updateAccessibility()
-*/
-
-/*!
- \class QAccessibleBridgePlugin
- \brief The QAccessibleBridgePlugin class provides an abstract
- base for accessibility bridge plugins.
-
- \ingroup plugins
- \ingroup accessibility
-
- Writing an accessibility bridge plugin is achieved by subclassing
- this base class, reimplementing the pure virtual functions keys()
- and create(), and exporting the class with the
- Q_EXPORT_PLUGIN2() macro.
-
- \sa QAccessibleBridge, QAccessiblePlugin, {How to Create Qt Plugins}
-*/
-
-/*!
- Constructs an accessibility bridge plugin with the given \a
- parent. This is invoked automatically by the Q_EXPORT_PLUGIN2()
- macro.
-*/
-QAccessibleBridgePlugin::QAccessibleBridgePlugin(QObject *parent)
- : QObject(parent)
-{
-
-}
-
-/*!
- Destroys the accessibility bridge plugin.
-
- You never have to call this explicitly. Qt destroys a plugin
- automatically when it is no longer used.
-*/
-QAccessibleBridgePlugin::~QAccessibleBridgePlugin()
-{
-
-}
-
-/*!
- \fn QStringList QAccessibleBridgePlugin::keys() const
-
- Returns the list of keys this plugins supports.
-
- These keys must be the names of the bridges that this
- plugin provides.
-
- \sa create()
-*/
-
-/*!
- \fn QAccessibleBridge *QAccessibleBridgePlugin::create(const QString &key)
-
- Creates and returns the QAccessibleBridge object corresponding to
- the given \a key. Keys are case sensitive.
-
- \sa keys()
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessiblebridge.h b/src/gui/accessible/qaccessiblebridge.h
deleted file mode 100644
index d5e35df33f..0000000000
--- a/src/gui/accessible/qaccessiblebridge.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLEBRIDGE_H
-#define QACCESSIBLEBRIDGE_H
-
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACCESSIBILITY
-
-class QAccessibleInterface;
-
-class QAccessibleBridge
-{
-public:
- virtual ~QAccessibleBridge() {}
- virtual void setRootObject(QAccessibleInterface *) = 0;
- virtual void notifyAccessibilityUpdate(int, QAccessibleInterface*, int) = 0;
-};
-
-struct Q_GUI_EXPORT QAccessibleBridgeFactoryInterface : public QFactoryInterface
-{
- virtual QAccessibleBridge *create(const QString& name) = 0;
-};
-
-#define QAccessibleBridgeFactoryInterface_iid "com.trolltech.Qt.QAccessibleBridgeFactoryInterface"
-Q_DECLARE_INTERFACE(QAccessibleBridgeFactoryInterface, QAccessibleBridgeFactoryInterface_iid)
-
-class Q_GUI_EXPORT QAccessibleBridgePlugin : public QObject, public QAccessibleBridgeFactoryInterface
-{
- Q_OBJECT
- Q_INTERFACES(QAccessibleBridgeFactoryInterface:QFactoryInterface)
-public:
- explicit QAccessibleBridgePlugin(QObject *parent = 0);
- ~QAccessibleBridgePlugin();
-
- virtual QStringList keys() const = 0;
- virtual QAccessibleBridge *create(const QString &key) = 0;
-};
-
-#endif // QT_NO_ACCESSIBILITY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QACCESSIBLEBRIDGE_H
diff --git a/src/gui/accessible/qaccessibleobject.cpp b/src/gui/accessible/qaccessibleobject.cpp
deleted file mode 100644
index 1d2d1da806..0000000000
--- a/src/gui/accessible/qaccessibleobject.cpp
+++ /dev/null
@@ -1,410 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessibleobject.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qapplication.h"
-#include "qwidget.h"
-#include "qpointer.h"
-#include "qmetaobject.h"
-#include "qvarlengtharray.h"
-
-QT_BEGIN_NAMESPACE
-
-class QAccessibleObjectPrivate
-{
-public:
- QPointer<QObject> object;
-
- QList<QByteArray> actionList() const;
-};
-
-QList<QByteArray> QAccessibleObjectPrivate::actionList() const
-{
- QList<QByteArray> actionList;
-
- if (!object)
- return actionList;
-
- const QMetaObject *mo = object->metaObject();
- Q_ASSERT(mo);
-
- QByteArray defaultAction = QMetaObject::normalizedSignature(
- mo->classInfo(mo->indexOfClassInfo("DefaultSlot")).value());
-
- for (int i = 0; i < mo->methodCount(); ++i) {
- const QMetaMethod member = mo->method(i);
- if (member.methodType() != QMetaMethod::Slot && member.access() != QMetaMethod::Public)
- continue;
-
- if (!qstrcmp(member.tag(), "QACCESSIBLE_SLOT")) {
- if (member.signature() == defaultAction)
- actionList.prepend(defaultAction);
- else
- actionList << member.signature();
- }
- }
-
- return actionList;
-}
-
-/*!
- \class QAccessibleObject
- \brief The QAccessibleObject class implements parts of the
- QAccessibleInterface for QObjects.
-
- \ingroup accessibility
-
- This class is mainly provided for convenience. All subclasses of
- the QAccessibleInterface that provide implementations of non-widget objects
- should use this class as their base class.
-
- \sa QAccessible, QAccessibleWidget
-*/
-
-/*!
- Creates a QAccessibleObject for \a object.
-*/
-QAccessibleObject::QAccessibleObject(QObject *object)
-{
- d = new QAccessibleObjectPrivate;
- d->object = object;
-}
-
-/*!
- Destroys the QAccessibleObject.
-
- This only happens when a call to release() decrements the internal
- reference counter to zero.
-*/
-QAccessibleObject::~QAccessibleObject()
-{
- delete d;
-}
-
-/*!
- \reimp
-*/
-QObject *QAccessibleObject::object() const
-{
-#ifndef QT_NO_DEBUG
- if (!d->object)
- qWarning("QAccessibleInterface is invalid. Crash pending...");
-#endif
- return d->object;
-}
-
-/*!
- \reimp
-*/
-bool QAccessibleObject::isValid() const
-{
- return !d->object.isNull();
-}
-
-/*! \reimp */
-QRect QAccessibleObject::rect(int) const
-{
- return QRect();
-}
-
-/*! \reimp */
-void QAccessibleObject::setText(Text, int, const QString &)
-{
-}
-
-/*! \reimp */
-int QAccessibleObject::userActionCount(int) const
-{
- return 0;
-}
-
-/*! \reimp */
-bool QAccessibleObject::doAction(int, int, const QVariantList &)
-{
- return false;
-}
-
-static const char * const action_text[][5] =
-{
- // Name, Description, Value, Help, Accelerator
- { "Press", "", "", "", "Space" },
- { "SetFocus", "Passes focus to this widget", "", "", "" },
- { "Increase", "", "", "", "" },
- { "Decrease", "", "", "", "" },
- { "Accept", "", "", "", "" },
- { "Cancel", "", "", "", "" },
- { "Select", "", "", "", "" },
- { "ClearSelection", "", "", "", "" },
- { "RemoveSelection", "", "", "", "" },
- { "ExtendSelection", "", "", "", "" },
- { "AddToSelection", "", "", "", "" }
-};
-
-/*! \reimp */
-QString QAccessibleObject::actionText(int action, Text t, int child) const
-{
- if (child || action > FirstStandardAction || action < LastStandardAction || t > Accelerator)
- return QString();
-
- return QString::fromLatin1(action_text[-(action - FirstStandardAction)][t]);
-}
-
-
-/*!
- \class QAccessibleApplication
- \brief The QAccessibleApplication class implements the QAccessibleInterface for QApplication.
-
- \internal
-
- \ingroup accessibility
-*/
-
-/*!
- Creates a QAccessibleApplication for the QApplication object referenced by qApp.
-*/
-QAccessibleApplication::QAccessibleApplication()
-: QAccessibleObject(qApp)
-{
-}
-
-// all toplevel widgets except popups and the desktop
-static QWidgetList topLevelWidgets()
-{
- QWidgetList list;
- const QWidgetList tlw(QApplication::topLevelWidgets());
- for (int i = 0; i < tlw.count(); ++i) {
- QWidget *w = tlw.at(i);
- if (!(w->windowType() == Qt::Popup) && !(w->windowType() == Qt::Desktop))
- list.append(w);
- }
-
- return list;
-}
-
-/*! \reimp */
-int QAccessibleApplication::childCount() const
-{
- return topLevelWidgets().count();
-}
-
-/*! \reimp */
-int QAccessibleApplication::indexOfChild(const QAccessibleInterface *child) const
-{
- if (!child->object()->isWidgetType())
- return -1;
-
- const QWidgetList tlw(topLevelWidgets());
- int index = tlw.indexOf(static_cast<QWidget*>(child->object()));
- if (index != -1)
- ++index;
- return index;
-}
-
-/*! \reimp */
-int QAccessibleApplication::childAt(int x, int y) const
-{
- const QWidgetList tlw(topLevelWidgets());
- for (int i = 0; i < tlw.count(); ++i) {
- QWidget *w = tlw.at(i);
- if (w->frameGeometry().contains(x,y))
- return i+1;
- }
- return -1;
-}
-
-/*! \reimp */
-QAccessible::Relation QAccessibleApplication::relationTo(int child, const
- QAccessibleInterface *other, int otherChild) const
-{
- QObject *o = other ? other->object() : 0;
- if (!o)
- return Unrelated;
-
- if(o == object()) {
- if (child && !otherChild)
- return Child;
- if (!child && otherChild)
- return Ancestor;
- if (!child && !otherChild)
- return Self;
- }
-
- QWidgetList tlw(topLevelWidgets());
- if (tlw.contains(qobject_cast<QWidget*>(o)))
- return Ancestor;
-
- for (int i = 0; i < tlw.count(); ++i) {
- QWidget *w = tlw.at(i);
- QObjectList cl = w->findChildren<QObject *>(QString());
- if (cl.contains(o))
- return Ancestor;
- }
-
- return Unrelated;
-}
-
-/*! \reimp */
-int QAccessibleApplication::navigate(RelationFlag relation, int entry,
- QAccessibleInterface **target) const
-{
- if (!target)
- return -1;
-
- *target = 0;
- QObject *targetObject = 0;
-
- switch (relation) {
- case Self:
- targetObject = object();
- break;
- case Child:
- if (entry > 0 && entry <= childCount()) {
- const QWidgetList tlw(topLevelWidgets());
- if (tlw.count() >= entry)
- targetObject = tlw.at(entry-1);
- } else {
- return -1;
- }
- break;
- case FocusChild:
- targetObject = QApplication::activeWindow();
- break;
- default:
- break;
- }
- *target = QAccessible::queryAccessibleInterface(targetObject);
- return *target ? 0 : -1;
-}
-
-/*! \reimp */
-QString QAccessibleApplication::text(Text t, int) const
-{
- switch (t) {
- case Name:
- if (QApplication::activeWindow())
- return QApplication::activeWindow()->windowTitle();
- break;
- case Description:
- return QApplication::applicationFilePath();
- default:
- break;
- }
- return QString();
-}
-
-/*! \reimp */
-QAccessible::Role QAccessibleApplication::role(int) const
-{
- return Application;
-}
-
-/*! \reimp */
-QAccessible::State QAccessibleApplication::state(int) const
-{
- return QApplication::activeWindow() ? Focused : Normal;
-}
-
-/*! \reimp */
-int QAccessibleApplication::userActionCount(int) const
-{
- return 1;
-}
-
-/*! \reimp */
-bool QAccessibleApplication::doAction(int action, int child, const QVariantList &param)
-{
- if (action == 0 || action == 1) {
- QWidget *w = 0;
- w = QApplication::activeWindow();
- if (!w)
- w = topLevelWidgets().at(0);
- if (!w)
- return false;
- w->activateWindow();
- return true;
- }
- return QAccessibleObject::doAction(action, child, param);
-}
-
-/*! \reimp */
-QString QAccessibleApplication::actionText(int action, Text text, int child) const
-{
- QString str;
- if ((action == 0 || action == 1) && !child) switch (text) {
- case Name:
- return QApplication::tr("Activate");
- case Description:
- return QApplication::tr("Activates the program's main window");
- default:
- break;
- }
- return QAccessibleObject::actionText(action, text, child);
-}
-
-// ### Qt 5: remove me - binary compatibility hack
-QAccessibleObjectEx::QAccessibleObjectEx(QObject *object)
-{
- d = new QAccessibleObjectPrivate;
- d->object = object;
-}
-bool QAccessibleObjectEx::isValid() const
-{ return reinterpret_cast<const QAccessibleObject *>(this)->QAccessibleObject::isValid(); }
-QObject *QAccessibleObjectEx::object() const
-{ return reinterpret_cast<const QAccessibleObject *>(this)->QAccessibleObject::object(); }
-QRect QAccessibleObjectEx::rect(int child) const
-{ return reinterpret_cast<const QAccessibleObject *>(this)->QAccessibleObject::rect(child); }
-void QAccessibleObjectEx::setText(Text t, int child, const QString &text)
-{ reinterpret_cast<QAccessibleObject *>(this)->QAccessibleObject::setText(t, child, text); }
-int QAccessibleObjectEx::userActionCount(int child) const
-{ return reinterpret_cast<const QAccessibleObject *>(this)->QAccessibleObject::userActionCount(child); }
-bool QAccessibleObjectEx::doAction(int action, int child, const QVariantList &params)
-{ return reinterpret_cast<QAccessibleObject *>(this)->QAccessibleObject::doAction(action, child, params); }
-QString QAccessibleObjectEx::actionText(int action, Text t, int child) const
-{ return reinterpret_cast<const QAccessibleObject *>(this)->QAccessibleObject::actionText(action, t, child); }
-QAccessibleObjectEx::~QAccessibleObjectEx()
-{ delete d; }
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessibleobject.h b/src/gui/accessible/qaccessibleobject.h
deleted file mode 100644
index 0eb9399028..0000000000
--- a/src/gui/accessible/qaccessibleobject.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLEOBJECT_H
-#define QACCESSIBLEOBJECT_H
-
-#include <QtGui/qaccessible.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACCESSIBILITY
-
-class QAccessibleObjectPrivate;
-class QObject;
-
-class Q_GUI_EXPORT QAccessibleObject : public QAccessibleInterface
-{
-public:
- explicit QAccessibleObject(QObject *object);
-
- bool isValid() const;
- QObject *object() const;
-
- // properties
- QRect rect(int child) const;
- void setText(Text t, int child, const QString &text);
-
- // actions
- int userActionCount(int child) const;
- bool doAction(int action, int child, const QVariantList &params);
- QString actionText(int action, Text t, int child) const;
-
-protected:
- virtual ~QAccessibleObject();
-
-private:
- friend class QAccessibleObjectEx;
- QAccessibleObjectPrivate *d;
- Q_DISABLE_COPY(QAccessibleObject)
-};
-
-class Q_GUI_EXPORT QAccessibleObjectEx : public QAccessibleInterfaceEx
-{
-public:
- explicit QAccessibleObjectEx(QObject *object);
-
- bool isValid() const;
- QObject *object() const;
-
- // properties
- QRect rect(int child) const;
- void setText(Text t, int child, const QString &text);
-
- // actions
- int userActionCount(int child) const;
- bool doAction(int action, int child, const QVariantList &params);
- QString actionText(int action, Text t, int child) const;
-
-protected:
- virtual ~QAccessibleObjectEx();
-
-private:
- QAccessibleObjectPrivate *d;
- Q_DISABLE_COPY(QAccessibleObjectEx)
-};
-
-class Q_GUI_EXPORT QAccessibleApplication : public QAccessibleObject
-{
-public:
- QAccessibleApplication();
-
- // relations
- int childCount() const;
- int indexOfChild(const QAccessibleInterface*) const;
- Relation relationTo(int, const QAccessibleInterface *, int) const;
-
- // navigation
- int childAt(int x, int y) const;
- int navigate(RelationFlag, int, QAccessibleInterface **) const;
-
- // properties and state
- QString text(Text t, int child) const;
- Role role(int child) const;
- State state(int child) const;
-
- // actions
- int userActionCount(int child) const;
- bool doAction(int action, int child, const QVariantList &params);
- QString actionText(int action, Text t, int child) const;
-};
-
-#endif // QT_NO_ACCESSIBILITY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QACCESSIBLEOBJECT_H
diff --git a/src/gui/accessible/qaccessibleplugin.cpp b/src/gui/accessible/qaccessibleplugin.cpp
deleted file mode 100644
index f52d4b1807..0000000000
--- a/src/gui/accessible/qaccessibleplugin.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessibleplugin.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qaccessible.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAccessiblePlugin
- \brief The QAccessiblePlugin class provides an abstract base for
- accessibility plugins.
-
- \ingroup plugins
- \ingroup accessibility
-
- Writing an accessibility plugin is achieved by subclassing this
- base class, reimplementing the pure virtual functions keys() and
- create(), and exporting the class with the Q_EXPORT_PLUGIN2()
- macro.
-
- \sa QAccessibleBridgePlugin, {How to Create Qt Plugins}
-*/
-
-/*!
- Constructs an accessibility plugin with the given \a parent. This
- is invoked automatically by the Q_EXPORT_PLUGIN2() macro.
-*/
-QAccessiblePlugin::QAccessiblePlugin(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*!
- Destroys the accessibility plugin.
-
- You never have to call this explicitly. Qt destroys a plugin
- automatically when it is no longer used.
-*/
-QAccessiblePlugin::~QAccessiblePlugin()
-{
-}
-
-/*!
- \fn QStringList QAccessiblePlugin::keys() const
-
- Returns the list of keys this plugin supports.
-
- These keys must be the class names that this plugin provides
- an accessibility implementation for.
-
- \sa create()
-*/
-
-/*!
- \fn QAccessibleInterface *QAccessiblePlugin::create(const QString &key, QObject *object)
-
- Creates and returns a QAccessibleInterface implementation for the
- class \a key and the object \a object. Keys are case sensitive.
-
- \sa keys()
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessibleplugin.h b/src/gui/accessible/qaccessibleplugin.h
deleted file mode 100644
index dcf794e752..0000000000
--- a/src/gui/accessible/qaccessibleplugin.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLEPLUGIN_H
-#define QACCESSIBLEPLUGIN_H
-
-#include <QtGui/qaccessible.h>
-#include <QtCore/qfactoryinterface.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACCESSIBILITY
-
-class QStringList;
-class QAccessibleInterface;
-
-struct Q_GUI_EXPORT QAccessibleFactoryInterface : public QAccessible, public QFactoryInterface
-{
- virtual QAccessibleInterface* create(const QString &key, QObject *object) = 0;
-};
-
-#define QAccessibleFactoryInterface_iid "com.trolltech.Qt.QAccessibleFactoryInterface"
-Q_DECLARE_INTERFACE(QAccessibleFactoryInterface, QAccessibleFactoryInterface_iid)
-
-class QAccessiblePluginPrivate;
-
-class Q_GUI_EXPORT QAccessiblePlugin : public QObject, public QAccessibleFactoryInterface
-{
- Q_OBJECT
- Q_INTERFACES(QAccessibleFactoryInterface:QFactoryInterface)
-public:
- explicit QAccessiblePlugin(QObject *parent = 0);
- ~QAccessiblePlugin();
-
- virtual QStringList keys() const = 0;
- virtual QAccessibleInterface *create(const QString &key, QObject *object) = 0;
-};
-
-#endif // QT_NO_ACCESSIBILITY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QACCESSIBLEPLUGIN_H
diff --git a/src/gui/accessible/qaccessiblewidget.cpp b/src/gui/accessible/qaccessiblewidget.cpp
deleted file mode 100644
index 2b2cec0f02..0000000000
--- a/src/gui/accessible/qaccessiblewidget.cpp
+++ /dev/null
@@ -1,1031 +0,0 @@
-/****************************************************************************
-**
-** 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 "qaccessiblewidget.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qaction.h"
-#include "qapplication.h"
-#include "qgroupbox.h"
-#include "qlabel.h"
-#include "qtooltip.h"
-#include "qwhatsthis.h"
-#include "qwidget.h"
-#include "qdebug.h"
-#include <qmath.h>
-#include <QRubberBand>
-#include <QtGui/QFocusFrame>
-#include <QtGui/QMenu>
-
-QT_BEGIN_NAMESPACE
-
-static QList<QWidget*> childWidgets(const QWidget *widget)
-{
- QList<QObject*> list = widget->children();
- QList<QWidget*> widgets;
- for (int i = 0; i < list.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(list.at(i));
- if (w && !w->isWindow()
- && !qobject_cast<QFocusFrame*>(w)
-#if !defined(QT_NO_MENU)
- && !qobject_cast<QMenu*>(w)
-#endif
- && w->objectName() != QLatin1String("qt_rubberband"))
- widgets.append(w);
- }
- return widgets;
-}
-
-static QString buddyString(const QWidget *widget)
-{
- if (!widget)
- return QString();
- QWidget *parent = widget->parentWidget();
- if (!parent)
- return QString();
-#ifndef QT_NO_SHORTCUT
- QObjectList ol = parent->children();
- for (int i = 0; i < ol.size(); ++i) {
- QLabel *label = qobject_cast<QLabel*>(ol.at(i));
- if (label && label->buddy() == widget)
- return label->text();
- }
-#endif
-
-#ifndef QT_NO_GROUPBOX
- QGroupBox *groupbox = qobject_cast<QGroupBox*>(parent);
- if (groupbox)
- return groupbox->title();
-#endif
-
- return QString();
-}
-
-QString Q_GUI_EXPORT qt_accStripAmp(const QString &text)
-{
- return QString(text).remove(QLatin1Char('&'));
-}
-
-QString Q_GUI_EXPORT qt_accHotKey(const QString &text)
-{
-#ifndef QT_NO_SHORTCUT
- if (text.isEmpty())
- return text;
-
- int fa = 0;
- QChar ac;
- while ((fa = text.indexOf(QLatin1Char('&'), fa)) != -1) {
- ++fa;
- if (fa < text.length()) {
- // ignore "&&"
- if (text.at(fa) == QLatin1Char('&')) {
- ++fa;
- continue;
- } else {
- ac = text.at(fa);
- break;
- }
- }
- }
- if (ac.isNull())
- return QString();
- return (QString)QKeySequence(Qt::ALT) + ac.toUpper();
-#else
- Q_UNUSED(text);
- return QString();
-#endif
-}
-
-class QAccessibleWidgetPrivate : public QAccessible
-{
-public:
- QAccessibleWidgetPrivate()
- :role(Client)
- {}
-
- Role role;
- QString name;
- QString description;
- QString value;
- QString help;
- QString accelerator;
- QStringList primarySignals;
- const QAccessibleInterface *asking;
-};
-
-/*!
- \class QAccessibleWidget
- \brief The QAccessibleWidget class implements the QAccessibleInterface for QWidgets.
-
- \ingroup accessibility
-
- This class is convenient to use as a base class for custom
- implementations of QAccessibleInterfaces that provide information
- about widget objects.
-
- The class provides functions to retrieve the parentObject() (the
- widget's parent widget), and the associated widget(). Controlling
- signals can be added with addControllingSignal(), and setters are
- provided for various aspects of the interface implementation, for
- example setValue(), setDescription(), setAccelerator(), and
- setHelp().
-
- \sa QAccessible, QAccessibleObject
-*/
-
-/*!
- Creates a QAccessibleWidget object for widget \a w.
- \a role and \a name are optional parameters that set the object's
- role and name properties.
-*/
-QAccessibleWidget::QAccessibleWidget(QWidget *w, Role role, const QString &name)
-: QAccessibleObject(w)
-{
- Q_ASSERT(widget());
- d = new QAccessibleWidgetPrivate();
- d->role = role;
- d->name = name;
- d->asking = 0;
-}
-
-/*!
- Destroys this object.
-*/
-QAccessibleWidget::~QAccessibleWidget()
-{
- delete d;
-}
-
-/*!
- Returns the associated widget.
-*/
-QWidget *QAccessibleWidget::widget() const
-{
- return qobject_cast<QWidget*>(object());
-}
-
-/*!
- Returns the associated widget's parent object, which is either the
- parent widget, or qApp for top-level widgets.
-*/
-QObject *QAccessibleWidget::parentObject() const
-{
- QObject *parent = object()->parent();
- if (!parent)
- parent = qApp;
- return parent;
-}
-
-/*! \reimp */
-int QAccessibleWidget::childAt(int x, int y) const
-{
- QWidget *w = widget();
- if (!w->isVisible())
- return -1;
- QPoint gp = w->mapToGlobal(QPoint(0, 0));
- if (!QRect(gp.x(), gp.y(), w->width(), w->height()).contains(x, y))
- return -1;
-
- QWidgetList list = childWidgets(w);
- int ccount = childCount();
-
- // a complex child
- if (list.size() < ccount) {
- for (int i = 1; i <= ccount; ++i) {
- if (rect(i).contains(x, y))
- return i;
- }
- return 0;
- }
-
- QPoint rp = w->mapFromGlobal(QPoint(x, y));
- for (int i = 0; i<list.size(); ++i) {
- QWidget *child = list.at(i);
- if (!child->isWindow() && !child->isHidden() && child->geometry().contains(rp)) {
- return i + 1;
- }
- }
- return 0;
-}
-
-/*! \reimp */
-QRect QAccessibleWidget::rect(int child) const
-{
- if (child) {
- qWarning("QAccessibleWidget::rect: This implementation does not support subelements! "
- "(ID %d unknown for %s)", child, widget()->metaObject()->className());
- }
-
- QWidget *w = widget();
- if (!w->isVisible())
- return QRect();
- QPoint wpos = w->mapToGlobal(QPoint(0, 0));
-
- return QRect(wpos.x(), wpos.y(), w->width(), w->height());
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <private/qobject_p.h>
-QT_END_INCLUDE_NAMESPACE
-
-class QACConnectionObject : public QObject
-{
- Q_DECLARE_PRIVATE(QObject)
-public:
- inline bool isSender(const QObject *receiver, const char *signal) const
- { return d_func()->isSender(receiver, signal); }
- inline QObjectList receiverList(const char *signal) const
- { return d_func()->receiverList(signal); }
- inline QObjectList senderList() const
- { return d_func()->senderList(); }
-};
-
-/*!
- Registers \a signal as a controlling signal.
-
- An object is a Controller to any other object connected to a
- controlling signal.
-*/
-void QAccessibleWidget::addControllingSignal(const QString &signal)
-{
- QByteArray s = QMetaObject::normalizedSignature(signal.toAscii());
- if (object()->metaObject()->indexOfSignal(s) < 0)
- qWarning("Signal %s unknown in %s", s.constData(), object()->metaObject()->className());
- d->primarySignals << QLatin1String(s);
-}
-
-/*!
- Sets the value of this interface implementation to \a value.
-
- The default implementation of text() returns the set value for
- the Value text.
-
- Note that the object wrapped by this interface is not modified.
-*/
-void QAccessibleWidget::setValue(const QString &value)
-{
- d->value = value;
-}
-
-/*!
- Sets the description of this interface implementation to \a desc.
-
- The default implementation of text() returns the set value for
- the Description text.
-
- Note that the object wrapped by this interface is not modified.
-*/
-void QAccessibleWidget::setDescription(const QString &desc)
-{
- d->description = desc;
-}
-
-/*!
- Sets the help of this interface implementation to \a help.
-
- The default implementation of text() returns the set value for
- the Help text.
-
- Note that the object wrapped by this interface is not modified.
-*/
-void QAccessibleWidget::setHelp(const QString &help)
-{
- d->help = help;
-}
-
-/*!
- Sets the accelerator of this interface implementation to \a accel.
-
- The default implementation of text() returns the set value for
- the Accelerator text.
-
- Note that the object wrapped by this interface is not modified.
-*/
-void QAccessibleWidget::setAccelerator(const QString &accel)
-{
- d->accelerator = accel;
-}
-
-static inline bool isAncestor(const QObject *obj, const QObject *child)
-{
- while (child) {
- if (child == obj)
- return true;
- child = child->parent();
- }
- return false;
-}
-
-
-/*! \reimp */
-QAccessible::Relation QAccessibleWidget::relationTo(int child,
- const QAccessibleInterface *other, int otherChild) const
-{
- Relation relation = Unrelated;
- if (d->asking == this) // recursive call
- return relation;
-
- QObject *o = other ? other->object() : 0;
- if (!o)
- return relation;
-
- QWidget *focus = widget()->focusWidget();
- if (object() == focus && isAncestor(o, focus))
- relation |= FocusChild;
-
- QACConnectionObject *connectionObject = (QACConnectionObject*)object();
- for (int sig = 0; sig < d->primarySignals.count(); ++sig) {
- if (connectionObject->isSender(o, d->primarySignals.at(sig).toAscii())) {
- relation |= Controller;
- break;
- }
- }
- // test for passive relationships.
- // d->asking protects from endless recursion.
- d->asking = this;
- int inverse = other->relationTo(otherChild, this, child);
- d->asking = 0;
-
- if (inverse & Controller)
- relation |= Controlled;
- if (inverse & Label)
- relation |= Labelled;
-
- if(o == object()) {
- if (child && !otherChild)
- return relation | Child;
- if (!child && otherChild)
- return relation | Ancestor;
- if (!child && !otherChild)
- return relation | Self;
- }
-
- QObject *parent = object()->parent();
- if (o == parent)
- return relation | Child;
-
- if (o->parent() == parent) {
- relation |= Sibling;
- QAccessibleInterface *sibIface = QAccessible::queryAccessibleInterface(o);
- Q_ASSERT(sibIface);
- QRect wg = rect(0);
- QRect sg = sibIface->rect(0);
- if (wg.intersects(sg)) {
- QAccessibleInterface *pIface = 0;
- sibIface->navigate(Ancestor, 1, &pIface);
- if (pIface && !((sibIface->state(0) | state(0)) & Invisible)) {
- int wi = pIface->indexOfChild(this);
- int si = pIface->indexOfChild(sibIface);
-
- if (wi > si)
- relation |= QAccessible::Covers;
- else
- relation |= QAccessible::Covered;
- }
- delete pIface;
- } else {
- QPoint wc = wg.center();
- QPoint sc = sg.center();
- if (wc.x() < sc.x())
- relation |= QAccessible::Left;
- else if(wc.x() > sc.x())
- relation |= QAccessible::Right;
- if (wc.y() < sc.y())
- relation |= QAccessible::Up;
- else if (wc.y() > sc.y())
- relation |= QAccessible::Down;
- }
- delete sibIface;
-
- return relation;
- }
-
- if (isAncestor(o, object()))
- return relation | Descendent;
- if (isAncestor(object(), o))
- return relation | Ancestor;
-
- return relation;
-}
-
-/*! \reimp */
-int QAccessibleWidget::navigate(RelationFlag relation, int entry,
- QAccessibleInterface **target) const
-{
- if (!target)
- return -1;
-
- *target = 0;
- QObject *targetObject = 0;
-
- QWidgetList childList = childWidgets(widget());
- bool complexWidget = childList.size() < childCount();
-
- switch (relation) {
- // Hierarchical
- case Self:
- targetObject = object();
- break;
- case Child:
- if (complexWidget) {
- if (entry > 0 && entry <= childCount())
- return entry;
- return -1;
- }else {
- if (entry > 0 && childList.size() >= entry)
- targetObject = childList.at(entry - 1);
- }
- break;
- case Ancestor:
- {
- if (entry <= 0)
- return -1;
- targetObject = widget()->parentWidget();
- int i;
- for (i = entry; i > 1 && targetObject; --i)
- targetObject = targetObject->parent();
- if (!targetObject && i == 1)
- targetObject = qApp;
- }
- break;
- case Sibling:
- {
- QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(parentObject());
- if (!iface)
- return -1;
-
- iface->navigate(Child, entry, target);
- delete iface;
- if (*target)
- return 0;
- }
- break;
-
- // Geometrical
- case QAccessible::Left:
- if (complexWidget && entry) {
- if (entry < 2 || widget()->height() > widget()->width() + 20) // looks vertical
- return -1;
- return entry - 1;
- }
- // fall through
- case QAccessible::Right:
- if (complexWidget && entry) {
- if (entry >= childCount() || widget()->height() > widget()->width() + 20) // looks vertical
- return -1;
- return entry + 1;
- }
- // fall through
- case QAccessible::Up:
- if (complexWidget && entry) {
- if (entry < 2 || widget()->width() > widget()->height() + 20) // looks horizontal
- return - 1;
- return entry - 1;
- }
- // fall through
- case QAccessible::Down:
- if (complexWidget && entry) {
- if (entry >= childCount() || widget()->width() > widget()->height() + 20) // looks horizontal
- return - 1;
- return entry + 1;
- } else {
- QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
- if (!pIface)
- return -1;
-
- QRect startg = rect(0);
- QPoint startc = startg.center();
- QAccessibleInterface *candidate = 0;
- int mindist = 100000;
- int sibCount = pIface->childCount();
- for (int i = 0; i < sibCount; ++i) {
- QAccessibleInterface *sibling = 0;
- pIface->navigate(Child, i+1, &sibling);
- Q_ASSERT(sibling);
- if ((relationTo(0, sibling, 0) & Self) || (sibling->state(0) & QAccessible::Invisible)) {
- //ignore ourself and invisible siblings
- delete sibling;
- continue;
- }
-
- QRect sibg = sibling->rect(0);
- QPoint sibc = sibg.center();
- QPoint sibp;
- QPoint startp;
- QPoint distp;
- switch (relation) {
- case QAccessible::Left:
- startp = QPoint(startg.left(), startg.top() + startg.height() / 2);
- sibp = QPoint(sibg.right(), sibg.top() + sibg.height() / 2);
- if (QPoint(sibc - startc).x() >= 0) {
- delete sibling;
- continue;
- }
- distp = sibp - startp;
- break;
- case QAccessible::Right:
- startp = QPoint(startg.right(), startg.top() + startg.height() / 2);
- sibp = QPoint(sibg.left(), sibg.top() + sibg.height() / 2);
- if (QPoint(sibc - startc).x() <= 0) {
- delete sibling;
- continue;
- }
- distp = sibp - startp;
- break;
- case QAccessible::Up:
- startp = QPoint(startg.left() + startg.width() / 2, startg.top());
- sibp = QPoint(sibg.left() + sibg.width() / 2, sibg.bottom());
- if (QPoint(sibc - startc).y() >= 0) {
- delete sibling;
- continue;
- }
- distp = sibp - startp;
- break;
- case QAccessible::Down:
- startp = QPoint(startg.left() + startg.width() / 2, startg.bottom());
- sibp = QPoint(sibg.left() + sibg.width() / 2, sibg.top());
- if (QPoint(sibc - startc).y() <= 0) {
- delete sibling;
- continue;
- }
- distp = sibp - startp;
- break;
- default:
- break;
- }
-
- int dist = (int)qSqrt((qreal)distp.x() * distp.x() + distp.y() * distp.y());
- if (dist < mindist) {
- delete candidate;
- candidate = sibling;
- mindist = dist;
- } else {
- delete sibling;
- }
- }
- delete pIface;
- *target = candidate;
- if (*target)
- return 0;
- }
- break;
- case Covers:
- if (entry > 0) {
- QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
- if (!pIface)
- return -1;
-
- QRect r = rect(0);
- int sibCount = pIface->childCount();
- QAccessibleInterface *sibling = 0;
- for (int i = pIface->indexOfChild(this) + 1; i <= sibCount && entry; ++i) {
- pIface->navigate(Child, i, &sibling);
- if (!sibling || (sibling->state(0) & Invisible)) {
- delete sibling;
- sibling = 0;
- continue;
- }
- if (sibling->rect(0).intersects(r))
- --entry;
- if (!entry)
- break;
- delete sibling;
- sibling = 0;
- }
- delete pIface;
- *target = sibling;
- if (*target)
- return 0;
- }
- break;
- case Covered:
- if (entry > 0) {
- QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
- if (!pIface)
- return -1;
-
- QRect r = rect(0);
- int index = pIface->indexOfChild(this);
- QAccessibleInterface *sibling = 0;
- for (int i = 1; i < index && entry; ++i) {
- pIface->navigate(Child, i, &sibling);
- Q_ASSERT(sibling);
- if (!sibling || (sibling->state(0) & Invisible)) {
- delete sibling;
- sibling = 0;
- continue;
- }
- if (sibling->rect(0).intersects(r))
- --entry;
- if (!entry)
- break;
- delete sibling;
- sibling = 0;
- }
- delete pIface;
- *target = sibling;
- if (*target)
- return 0;
- }
- break;
-
- // Logical
- case FocusChild:
- {
- if (widget()->hasFocus()) {
- targetObject = object();
- break;
- }
-
- QWidget *fw = widget()->focusWidget();
- if (!fw)
- return -1;
-
- if (isAncestor(widget(), fw) || fw == widget())
- targetObject = fw;
- /* ###
- QWidget *parent = fw;
- while (parent && !targetObject) {
- parent = parent->parentWidget();
- if (parent == widget())
- targetObject = fw;
- }
- */
- }
- break;
- case Label:
- if (entry > 0) {
- QAccessibleInterface *pIface = QAccessible::queryAccessibleInterface(parentObject());
- if (!pIface)
- return -1;
-
- // first check for all siblings that are labels to us
- // ideally we would go through all objects and check, but that
- // will be too expensive
- int sibCount = pIface->childCount();
- QAccessibleInterface *candidate = 0;
- for (int i = 0; i < sibCount && entry; ++i) {
- pIface->navigate(Child, i+1, &candidate);
- Q_ASSERT(candidate);
- if (candidate->relationTo(0, this, 0) & Label)
- --entry;
- if (!entry)
- break;
- delete candidate;
- candidate = 0;
- }
- if (!candidate) {
- if (pIface->relationTo(0, this, 0) & Label)
- --entry;
- if (!entry)
- candidate = pIface;
- }
- if (pIface != candidate)
- delete pIface;
-
- *target = candidate;
- if (*target)
- return 0;
- }
- break;
- case Labelled: // only implemented in subclasses
- break;
- case Controller:
- if (entry > 0) {
- // check all senders we are connected to,
- // and figure out which one are controllers to us
- QACConnectionObject *connectionObject = (QACConnectionObject*)object();
- QObjectList allSenders = connectionObject->senderList();
- QObjectList senders;
- for (int s = 0; s < allSenders.size(); ++s) {
- QObject *sender = allSenders.at(s);
- QAccessibleInterface *candidate = QAccessible::queryAccessibleInterface(sender);
- if (!candidate)
- continue;
- if (candidate->relationTo(0, this, 0)&Controller)
- senders << sender;
- delete candidate;
- }
- if (entry <= senders.size())
- targetObject = senders.at(entry-1);
- }
- break;
- case Controlled:
- if (entry > 0) {
- QObjectList allReceivers;
- QACConnectionObject *connectionObject = (QACConnectionObject*)object();
- for (int sig = 0; sig < d->primarySignals.count(); ++sig) {
- QObjectList receivers = connectionObject->receiverList(d->primarySignals.at(sig).toAscii());
- allReceivers += receivers;
- }
- if (entry <= allReceivers.size())
- targetObject = allReceivers.at(entry-1);
- }
- break;
- default:
- break;
- }
-
- *target = QAccessible::queryAccessibleInterface(targetObject);
- return *target ? 0 : -1;
-}
-
-/*! \reimp */
-int QAccessibleWidget::childCount() const
-{
- QWidgetList cl = childWidgets(widget());
- return cl.size();
-}
-
-/*! \reimp */
-int QAccessibleWidget::indexOfChild(const QAccessibleInterface *child) const
-{
- QWidgetList cl = childWidgets(widget());
- int index = cl.indexOf(qobject_cast<QWidget *>(child->object()));
- if (index != -1)
- ++index;
- return index;
-}
-
-// from qwidget.cpp
-extern QString qt_setWindowTitle_helperHelper(const QString &, const QWidget*);
-
-/*! \reimp */
-QString QAccessibleWidget::text(Text t, int child) const
-{
- QString str;
-
- switch (t) {
- case Name:
- if (!d->name.isEmpty()) {
- str = d->name;
- } else if (!widget()->accessibleName().isEmpty()) {
- str = widget()->accessibleName();
- } else if (!child && widget()->isWindow()) {
- if (widget()->isMinimized())
- str = qt_setWindowTitle_helperHelper(widget()->windowIconText(), widget());
- else
- str = qt_setWindowTitle_helperHelper(widget()->windowTitle(), widget());
- } else {
- str = qt_accStripAmp(buddyString(widget()));
- }
- break;
- case Description:
- if (!d->description.isEmpty())
- str = d->description;
- else if (!widget()->accessibleDescription().isEmpty())
- str = widget()->accessibleDescription();
-#ifndef QT_NO_TOOLTIP
- else
- str = widget()->toolTip();
-#endif
- break;
- case Help:
- if (!d->help.isEmpty())
- str = d->help;
-#ifndef QT_NO_WHATSTHIS
- else
- str = widget()->whatsThis();
-#endif
- break;
- case Accelerator:
- if (!d->accelerator.isEmpty())
- str = d->accelerator;
- else
- str = qt_accHotKey(buddyString(widget()));
- break;
- case Value:
- str = d->value;
- break;
- default:
- break;
- }
- return str;
-}
-
-#ifndef QT_NO_ACTION
-
-/*! \reimp */
-int QAccessibleWidget::userActionCount(int child) const
-{
- if (child)
- return 0;
- return widget()->actions().count();
-}
-
-/*! \reimp */
-QString QAccessibleWidget::actionText(int action, Text t, int child) const
-{
- if (action == DefaultAction)
- action = SetFocus;
-
- if (action > 0 && !child) {
- QAction *act = widget()->actions().value(action - 1);
- if (act) {
- switch (t) {
- case Name:
- return act->text();
- case Description:
- return act->toolTip();
-#ifndef QT_NO_SHORTCUT
- case Accelerator:
- return act->shortcut().toString();
-#endif
- default:
- break;
- }
- }
- }
-
- return QAccessibleObject::actionText(action, t, child);
-}
-
-/*! \reimp */
-bool QAccessibleWidget::doAction(int action, int child, const QVariantList &params)
-{
- if (action == SetFocus || action == DefaultAction) {
- if (child || !widget()->isEnabled())
- return false;
- if (widget()->focusPolicy() != Qt::NoFocus)
- widget()->setFocus();
- else if (widget()->isWindow())
- widget()->activateWindow();
- else
- return false;
- return true;
- } else if (action > 0) {
- if (QAction *act = widget()->actions().value(action - 1)) {
- act->trigger();
- return true;
- }
- }
- return QAccessibleObject::doAction(action, child, params);
-}
-
-#endif // QT_NO_ACTION
-
-/*! \reimp */
-QAccessible::Role QAccessibleWidget::role(int child) const
-{
- if (!child)
- return d->role;
-
- QWidgetList childList = childWidgets(widget());
- if (childList.count() > 0 && child <= childList.count()) {
- QWidget *targetWidget = childList.at(child - 1);
- QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(targetWidget);
- if (iface) {
- QAccessible::Role role = iface->role(0);
- delete iface;
- return role;
- }
- }
-
- return NoRole;
-}
-
-/*! \reimp */
-QAccessible::State QAccessibleWidget::state(int child) const
-{
- if (child)
- return Normal;
-
- QAccessible::State state = Normal;
-
- QWidget *w = widget();
- if (w->testAttribute(Qt::WA_WState_Visible) == false)
- state |= Invisible;
- if (w->focusPolicy() != Qt::NoFocus && w->isActiveWindow())
- state |= Focusable;
- if (w->hasFocus())
- state |= Focused;
- if (!w->isEnabled())
- state |= Unavailable;
- if (w->isWindow()) {
- if (w->windowFlags() & Qt::WindowSystemMenuHint)
- state |= Movable;
- if (w->minimumSize() != w->maximumSize())
- state |= Sizeable;
- }
-
- return state;
-}
-
-// ### Qt 5: remove me - binary compatibility hack
-QAccessibleWidgetEx::QAccessibleWidgetEx(QWidget *o, Role role, const QString& name)
- : QAccessibleObjectEx(o)
-{
- Q_ASSERT(widget());
- d = new QAccessibleWidgetPrivate();
- d->role = role;
- d->name = name;
- d->asking = 0;
-}
-
-int QAccessibleWidgetEx::childCount() const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::childCount(); }
-int QAccessibleWidgetEx::indexOfChild(const QAccessibleInterface *child) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::indexOfChild(child); }
-QAccessible::Relation QAccessibleWidgetEx::relationTo(int child, const QAccessibleInterface *other, int otherChild) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::relationTo(child, other, otherChild); }
-
-int QAccessibleWidgetEx::childAt(int x, int y) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::childAt(x, y); }
-QRect QAccessibleWidgetEx::rect(int child) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::rect(child); }
-int QAccessibleWidgetEx::navigate(RelationFlag rel, int entry, QAccessibleInterface **target) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::navigate(rel, entry, target); }
-
-QString QAccessibleWidgetEx::text(Text t, int child) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::text(t, child); }
-QAccessible::Role QAccessibleWidgetEx::role(int child) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::role(child); }
-QAccessible::State QAccessibleWidgetEx::state(int child) const
-{ return (reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::state(child))
- | HasInvokeExtension; }
-
-QString QAccessibleWidgetEx::actionText(int action, Text t, int child) const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::actionText(action, t, child); }
-bool QAccessibleWidgetEx::doAction(int action, int child, const QVariantList &params)
-{ return reinterpret_cast<QAccessibleWidget *>(this)->QAccessibleWidget::doAction(action, child, params); }
-
-QAccessibleWidgetEx::~QAccessibleWidgetEx()
-{ delete d; }
-QWidget *QAccessibleWidgetEx::widget() const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::widget(); }
-QObject *QAccessibleWidgetEx::parentObject() const
-{ return reinterpret_cast<const QAccessibleWidget *>(this)->QAccessibleWidget::parentObject(); }
-
-void QAccessibleWidgetEx::addControllingSignal(const QString &signal)
-{ reinterpret_cast<QAccessibleWidget *>(this)->QAccessibleWidget::addControllingSignal(signal); }
-void QAccessibleWidgetEx::setValue(const QString &value)
-{ reinterpret_cast<QAccessibleWidget *>(this)->QAccessibleWidget::setValue(value); }
-void QAccessibleWidgetEx::setDescription(const QString &desc)
-{ reinterpret_cast<QAccessibleWidget *>(this)->QAccessibleWidget::setDescription(desc); }
-void QAccessibleWidgetEx::setHelp(const QString &help)
-{ reinterpret_cast<QAccessibleWidget *>(this)->QAccessibleWidget::setHelp(help); }
-void QAccessibleWidgetEx::setAccelerator(const QString &accel)
-{ reinterpret_cast<QAccessibleWidget *>(this)->QAccessibleWidget::setAccelerator(accel); }
-
-QVariant QAccessibleWidgetEx::invokeMethodEx(Method method, int child, const QVariantList & /*params*/)
-{
- if (child)
- return QVariant();
-
- switch (method) {
- case ListSupportedMethods: {
- QSet<QAccessible::Method> set;
- set << ListSupportedMethods << ForegroundColor << BackgroundColor;
- return QVariant::fromValue(set);
- }
- case ForegroundColor:
- return widget()->palette().color(widget()->foregroundRole());
- case BackgroundColor:
- return widget()->palette().color(widget()->backgroundRole());
- default:
- return QVariant();
- }
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessiblewidget.h b/src/gui/accessible/qaccessiblewidget.h
deleted file mode 100644
index ef22e05c60..0000000000
--- a/src/gui/accessible/qaccessiblewidget.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** 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 QACCESSIBLEWIDGET_H
-#define QACCESSIBLEWIDGET_H
-
-#include <QtGui/qaccessibleobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACCESSIBILITY
-
-class QAccessibleWidgetPrivate;
-
-class Q_GUI_EXPORT QAccessibleWidget : public QAccessibleObject
-{
-public:
- explicit QAccessibleWidget(QWidget *o, Role r = Client, const QString& name = QString());
-
- int childCount() const;
- int indexOfChild(const QAccessibleInterface *child) const;
- Relation relationTo(int child, const QAccessibleInterface *other, int otherChild) const;
-
- int childAt(int x, int y) const;
- QRect rect(int child) const;
- int navigate(RelationFlag rel, int entry, QAccessibleInterface **target) const;
-
- QString text(Text t, int child) const;
- Role role(int child) const;
- State state(int child) const;
-
-#ifndef QT_NO_ACTION
- int userActionCount(int child) const;
- QString actionText(int action, Text t, int child) const;
- bool doAction(int action, int child, const QVariantList &params);
-#endif
-
-protected:
- ~QAccessibleWidget();
- QWidget *widget() const;
- QObject *parentObject() const;
-
- void addControllingSignal(const QString &signal);
- void setValue(const QString &value);
- void setDescription(const QString &desc);
- void setHelp(const QString &help);
- void setAccelerator(const QString &accel);
-
-private:
- friend class QAccessibleWidgetEx;
- QAccessibleWidgetPrivate *d;
- Q_DISABLE_COPY(QAccessibleWidget)
-};
-
-class Q_GUI_EXPORT QAccessibleWidgetEx : public QAccessibleObjectEx
-{
-public:
- explicit QAccessibleWidgetEx(QWidget *o, Role r = Client, const QString& name = QString());
-
- int childCount() const;
- int indexOfChild(const QAccessibleInterface *child) const;
- Relation relationTo(int child, const QAccessibleInterface *other, int otherChild) const;
-
- int childAt(int x, int y) const;
- QRect rect(int child) const;
- int navigate(RelationFlag rel, int entry, QAccessibleInterface **target) const;
-
- QString text(Text t, int child) const;
- Role role(int child) const;
- State state(int child) const;
-
- QString actionText(int action, Text t, int child) const;
- bool doAction(int action, int child, const QVariantList &params);
-
- QVariant invokeMethodEx(Method method, int child, const QVariantList &params);
-
-protected:
- ~QAccessibleWidgetEx();
- QWidget *widget() const;
- QObject *parentObject() const;
-
- void addControllingSignal(const QString &signal);
- void setValue(const QString &value);
- void setDescription(const QString &desc);
- void setHelp(const QString &help);
- void setAccelerator(const QString &accel);
-
-private:
- QAccessibleWidgetPrivate *d;
- Q_DISABLE_COPY(QAccessibleWidgetEx)
-};
-
-#endif // QT_NO_ACCESSIBILITY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QACCESSIBLEWIDGET_H
diff --git a/src/gui/animation/animation.pri b/src/gui/animation/animation.pri
deleted file mode 100644
index 27763ca003..0000000000
--- a/src/gui/animation/animation.pri
+++ /dev/null
@@ -1,3 +0,0 @@
-# Qt gui animation module
-
-SOURCES += animation/qguivariantanimation.cpp
diff --git a/src/gui/animation/qguivariantanimation.cpp b/src/gui/animation/qguivariantanimation.cpp
deleted file mode 100644
index ccd27d5d91..0000000000
--- a/src/gui/animation/qguivariantanimation.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qvariantanimation.h>
-#include <private/qvariantanimation_p.h>
-
-#ifndef QT_NO_ANIMATION
-
-#include <QtGui/qcolor.h>
-#include <QtGui/qvector2d.h>
-#include <QtGui/qvector3d.h>
-#include <QtGui/qvector4d.h>
-#include <QtGui/qquaternion.h>
-
-QT_BEGIN_NAMESPACE
-
-template<> Q_INLINE_TEMPLATE QColor _q_interpolate(const QColor &f,const QColor &t, qreal progress)
-{
- return QColor(qBound(0,_q_interpolate(f.red(), t.red(), progress),255),
- qBound(0,_q_interpolate(f.green(), t.green(), progress),255),
- qBound(0,_q_interpolate(f.blue(), t.blue(), progress),255),
- qBound(0,_q_interpolate(f.alpha(), t.alpha(), progress),255));
-}
-
-template<> Q_INLINE_TEMPLATE QQuaternion _q_interpolate(const QQuaternion &f,const QQuaternion &t, qreal progress)
-{
- return QQuaternion::slerp(f, t, progress);
-}
-
-static int qRegisterGuiGetInterpolator()
-{
- qRegisterAnimationInterpolator<QColor>(_q_interpolateVariant<QColor>);
- qRegisterAnimationInterpolator<QVector2D>(_q_interpolateVariant<QVector2D>);
- qRegisterAnimationInterpolator<QVector3D>(_q_interpolateVariant<QVector3D>);
- qRegisterAnimationInterpolator<QVector4D>(_q_interpolateVariant<QVector4D>);
- qRegisterAnimationInterpolator<QQuaternion>(_q_interpolateVariant<QQuaternion>);
- return 1;
-}
-Q_CONSTRUCTOR_FUNCTION(qRegisterGuiGetInterpolator)
-
-static int qUnregisterGuiGetInterpolator()
-{
- // casts required by Sun CC 5.5
- qRegisterAnimationInterpolator<QColor>(
- (QVariant (*)(const QColor &, const QColor &, qreal))0);
- qRegisterAnimationInterpolator<QVector2D>(
- (QVariant (*)(const QVector2D &, const QVector2D &, qreal))0);
- qRegisterAnimationInterpolator<QVector3D>(
- (QVariant (*)(const QVector3D &, const QVector3D &, qreal))0);
- qRegisterAnimationInterpolator<QVector4D>(
- (QVariant (*)(const QVector4D &, const QVector4D &, qreal))0);
- qRegisterAnimationInterpolator<QQuaternion>(
- (QVariant (*)(const QQuaternion &, const QQuaternion &, qreal))0);
-
- return 1;
-}
-Q_DESTRUCTOR_FUNCTION(qUnregisterGuiGetInterpolator)
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_ANIMATION
diff --git a/src/gui/dialogs/dialogs.pri b/src/gui/dialogs/dialogs.pri
deleted file mode 100644
index 472787a20c..0000000000
--- a/src/gui/dialogs/dialogs.pri
+++ /dev/null
@@ -1,106 +0,0 @@
-# Qt dialogs module
-
-HEADERS += \
- dialogs/qabstractprintdialog.h \
- dialogs/qabstractprintdialog_p.h \
- dialogs/qabstractpagesetupdialog.h \
- dialogs/qabstractpagesetupdialog_p.h \
- dialogs/qcolordialog.h \
- dialogs/qcolordialog_p.h \
- dialogs/qfscompleter_p.h \
- dialogs/qdialog.h \
- dialogs/qdialog_p.h \
- dialogs/qerrormessage.h \
- dialogs/qfiledialog.h \
- dialogs/qfiledialog_p.h \
- dialogs/qfontdialog.h \
- dialogs/qfontdialog_p.h \
- dialogs/qinputdialog.h \
- dialogs/qmessagebox.h \
- dialogs/qpagesetupdialog.h \
- dialogs/qprintdialog.h \
- dialogs/qprogressdialog.h \
- dialogs/qsidebar_p.h \
- dialogs/qfilesystemmodel.h \
- dialogs/qfilesystemmodel_p.h \
- dialogs/qfileinfogatherer_p.h \
- dialogs/qwizard.h \
- dialogs/qprintpreviewdialog.h
-
-!qpa:mac {
- OBJECTIVE_SOURCES += dialogs/qfiledialog_mac.mm \
- dialogs/qfontdialog_mac.mm \
- dialogs/qnspanelproxy_mac.mm \
- dialogs/qpagesetupdialog_mac.mm \
- dialogs/qprintdialog_mac.mm
-
-# Compile qcolordialog_mac.mm with exception support, disregarding the -no-exceptions
-# configure option. (qcolordialog_mac needs to catch exceptions thrown by cocoa)
- EXCEPTION_SOURCES = dialogs/qcolordialog_mac.mm
- exceptions_compiler.commands = $$QMAKE_CXX -c
- exceptions_compiler.commands += $(CXXFLAGS) $(INCPATH) ${QMAKE_FILE_IN} -o ${QMAKE_FILE_OUT}
- exceptions_compiler.commands += -fexceptions
- exceptions_compiler.dependency_type = TYPE_C
- exceptions_compiler.output = ${QMAKE_VAR_OBJECTS_DIR}${QMAKE_FILE_BASE}$${first(QMAKE_EXT_OBJ)}
- exceptions_compiler.input = EXCEPTION_SOURCES
- exceptions_compiler.variable_out = OBJECTS
- exceptions_compiler.name = compiling[exceptopns] ${QMAKE_FILE_IN}
- silent:exceptions_compiler.commands = @echo compiling[exceptopns] ${QMAKE_FILE_IN} && $$exceptions_compiler.commands
- QMAKE_EXTRA_COMPILERS += exceptions_compiler
-}
-
-win32 {
- HEADERS += dialogs/qwizard_win_p.h \
- dialogs/qfiledialog_win_p.h
- SOURCES += dialogs/qdialogsbinarycompat_win.cpp \
- dialogs/qfiledialog_win.cpp \
- dialogs/qpagesetupdialog_win.cpp \
- dialogs/qprintdialog_win.cpp \
- dialogs/qwizard_win.cpp
-
- !win32-borland:!wince*: LIBS += -lshell32 # the filedialog needs this library
-}
-
-!mac:!symbian:unix|qpa {
- HEADERS += dialogs/qpagesetupdialog_unix_p.h
- SOURCES += dialogs/qprintdialog_unix.cpp \
- dialogs/qpagesetupdialog_unix.cpp
- FORMS += dialogs/qprintsettingsoutput.ui \
- dialogs/qprintwidget.ui \
- dialogs/qprintpropertieswidget.ui
-}
-
-wince*|symbian: FORMS += dialogs/qfiledialog_embedded.ui
-else: FORMS += dialogs/qfiledialog.ui
-
-INCLUDEPATH += $$PWD
-SOURCES += \
- dialogs/qabstractprintdialog.cpp \
- dialogs/qabstractpagesetupdialog.cpp \
- dialogs/qcolordialog.cpp \
- dialogs/qdialog.cpp \
- dialogs/qerrormessage.cpp \
- dialogs/qfiledialog.cpp \
- dialogs/qfontdialog.cpp \
- dialogs/qinputdialog.cpp \
- dialogs/qmessagebox.cpp \
- dialogs/qprogressdialog.cpp \
- dialogs/qsidebar.cpp \
- dialogs/qfilesystemmodel.cpp \
- dialogs/qfileinfogatherer.cpp \
- dialogs/qpagesetupdialog.cpp \
- dialogs/qwizard.cpp \
- dialogs/qprintpreviewdialog.cpp
-
-symbian:contains(QT_CONFIG, s60) {
- LIBS += -lCommonDialogs
- SOURCES += dialogs/qfiledialog_symbian.cpp \
- dialogs/qcolordialog_symbian.cpp
-}
-
-FORMS += dialogs/qpagesetupwidget.ui
-RESOURCES += dialogs/qprintdialog.qrc
-RESOURCES += dialogs/qmessagebox.qrc
-
-# Compensate for lack of platform defines in Symbian3
-symbian: DEFINES += SYMBIAN_VERSION_$$upper($$replace(SYMBIAN_VERSION,\\.,_))
diff --git a/src/gui/dialogs/images/fit-page-24.png b/src/gui/dialogs/images/fit-page-24.png
deleted file mode 100644
index c7b39d8853..0000000000
--- a/src/gui/dialogs/images/fit-page-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/fit-page-32.png b/src/gui/dialogs/images/fit-page-32.png
deleted file mode 100644
index 98bc12d3ed..0000000000
--- a/src/gui/dialogs/images/fit-page-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/fit-width-24.png b/src/gui/dialogs/images/fit-width-24.png
deleted file mode 100644
index a729ffda54..0000000000
--- a/src/gui/dialogs/images/fit-width-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/fit-width-32.png b/src/gui/dialogs/images/fit-width-32.png
deleted file mode 100644
index 470a8b45d0..0000000000
--- a/src/gui/dialogs/images/fit-width-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-first-24.png b/src/gui/dialogs/images/go-first-24.png
deleted file mode 100644
index 55315ffa38..0000000000
--- a/src/gui/dialogs/images/go-first-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-first-32.png b/src/gui/dialogs/images/go-first-32.png
deleted file mode 100644
index 0fe6f94b77..0000000000
--- a/src/gui/dialogs/images/go-first-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-last-24.png b/src/gui/dialogs/images/go-last-24.png
deleted file mode 100644
index 81061b80f2..0000000000
--- a/src/gui/dialogs/images/go-last-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-last-32.png b/src/gui/dialogs/images/go-last-32.png
deleted file mode 100644
index 887506107e..0000000000
--- a/src/gui/dialogs/images/go-last-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-next-24.png b/src/gui/dialogs/images/go-next-24.png
deleted file mode 100644
index 9a55ef3d86..0000000000
--- a/src/gui/dialogs/images/go-next-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-next-32.png b/src/gui/dialogs/images/go-next-32.png
deleted file mode 100644
index 6d98f50f4f..0000000000
--- a/src/gui/dialogs/images/go-next-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-previous-24.png b/src/gui/dialogs/images/go-previous-24.png
deleted file mode 100644
index 2ea769eb8d..0000000000
--- a/src/gui/dialogs/images/go-previous-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/go-previous-32.png b/src/gui/dialogs/images/go-previous-32.png
deleted file mode 100644
index 37ba0c4e8d..0000000000
--- a/src/gui/dialogs/images/go-previous-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/layout-landscape-24.png b/src/gui/dialogs/images/layout-landscape-24.png
deleted file mode 100644
index 6f89a31cb6..0000000000
--- a/src/gui/dialogs/images/layout-landscape-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/layout-landscape-32.png b/src/gui/dialogs/images/layout-landscape-32.png
deleted file mode 100644
index 6a94946c36..0000000000
--- a/src/gui/dialogs/images/layout-landscape-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/layout-portrait-24.png b/src/gui/dialogs/images/layout-portrait-24.png
deleted file mode 100644
index e0dbabc83b..0000000000
--- a/src/gui/dialogs/images/layout-portrait-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/layout-portrait-32.png b/src/gui/dialogs/images/layout-portrait-32.png
deleted file mode 100644
index d17468c0a4..0000000000
--- a/src/gui/dialogs/images/layout-portrait-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/page-setup-24.png b/src/gui/dialogs/images/page-setup-24.png
deleted file mode 100644
index 4bfafdace0..0000000000
--- a/src/gui/dialogs/images/page-setup-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/page-setup-32.png b/src/gui/dialogs/images/page-setup-32.png
deleted file mode 100644
index 2313b8fe3b..0000000000
--- a/src/gui/dialogs/images/page-setup-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/print-24.png b/src/gui/dialogs/images/print-24.png
deleted file mode 100644
index c6bf3e8672..0000000000
--- a/src/gui/dialogs/images/print-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/print-32.png b/src/gui/dialogs/images/print-32.png
deleted file mode 100644
index 5830888653..0000000000
--- a/src/gui/dialogs/images/print-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/qtlogo-64.png b/src/gui/dialogs/images/qtlogo-64.png
deleted file mode 100644
index 4f68e162de..0000000000
--- a/src/gui/dialogs/images/qtlogo-64.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/status-color.png b/src/gui/dialogs/images/status-color.png
deleted file mode 100644
index af3cbfa31c..0000000000
--- a/src/gui/dialogs/images/status-color.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/status-gray-scale.png b/src/gui/dialogs/images/status-gray-scale.png
deleted file mode 100644
index 4462588809..0000000000
--- a/src/gui/dialogs/images/status-gray-scale.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/view-page-multi-24.png b/src/gui/dialogs/images/view-page-multi-24.png
deleted file mode 100644
index 87241472ae..0000000000
--- a/src/gui/dialogs/images/view-page-multi-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/view-page-multi-32.png b/src/gui/dialogs/images/view-page-multi-32.png
deleted file mode 100644
index 130885a041..0000000000
--- a/src/gui/dialogs/images/view-page-multi-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/view-page-one-24.png b/src/gui/dialogs/images/view-page-one-24.png
deleted file mode 100644
index 4c6457b892..0000000000
--- a/src/gui/dialogs/images/view-page-one-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/view-page-one-32.png b/src/gui/dialogs/images/view-page-one-32.png
deleted file mode 100644
index 537193984e..0000000000
--- a/src/gui/dialogs/images/view-page-one-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/view-page-sided-24.png b/src/gui/dialogs/images/view-page-sided-24.png
deleted file mode 100644
index 2131305c41..0000000000
--- a/src/gui/dialogs/images/view-page-sided-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/view-page-sided-32.png b/src/gui/dialogs/images/view-page-sided-32.png
deleted file mode 100644
index e4d63f9992..0000000000
--- a/src/gui/dialogs/images/view-page-sided-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/zoom-in-24.png b/src/gui/dialogs/images/zoom-in-24.png
deleted file mode 100644
index d29b142b6c..0000000000
--- a/src/gui/dialogs/images/zoom-in-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/zoom-in-32.png b/src/gui/dialogs/images/zoom-in-32.png
deleted file mode 100644
index 34d70af37b..0000000000
--- a/src/gui/dialogs/images/zoom-in-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/zoom-out-24.png b/src/gui/dialogs/images/zoom-out-24.png
deleted file mode 100644
index 19703474f8..0000000000
--- a/src/gui/dialogs/images/zoom-out-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/images/zoom-out-32.png b/src/gui/dialogs/images/zoom-out-32.png
deleted file mode 100644
index b832206612..0000000000
--- a/src/gui/dialogs/images/zoom-out-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/dialogs/qabstractpagesetupdialog.cpp b/src/gui/dialogs/qabstractpagesetupdialog.cpp
deleted file mode 100644
index 080ddeaa85..0000000000
--- a/src/gui/dialogs/qabstractpagesetupdialog.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractpagesetupdialog.h"
-#include "qabstractpagesetupdialog_p.h"
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include <QtCore/qcoreapplication.h>
-#include <QtGui/qprinter.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QAbstractPageSetupDialog
-
- \brief The QAbstractPageSetupDialog class provides a base for
- implementations of page setup dialogs.
-*/
-
-/*!
- Constructs the page setup dialog for the printer \a printer with
- \a parent as parent widget.
-*/
-QAbstractPageSetupDialog::QAbstractPageSetupDialog(QPrinter *printer, QWidget *parent)
- : QDialog(*(new QAbstractPageSetupDialogPrivate), parent)
-{
- Q_D(QAbstractPageSetupDialog);
- setWindowTitle(QCoreApplication::translate("QPrintPreviewDialog", "Page Setup"));
- d->setPrinter(printer);
-}
-
-/*!
- \internal
-*/
-QAbstractPageSetupDialog::QAbstractPageSetupDialog(QAbstractPageSetupDialogPrivate &ptr,
- QPrinter *printer, QWidget *parent)
- : QDialog(ptr, parent)
-{
- Q_D(QAbstractPageSetupDialog);
- setWindowTitle(QCoreApplication::translate("QPrintPreviewDialog", "Page Setup"));
- d->setPrinter(printer);
-}
-
-QAbstractPageSetupDialog::~QAbstractPageSetupDialog()
-{
- Q_D(QAbstractPageSetupDialog);
- if (d->opts & QPageSetupDialog::OwnsPrinter)
- delete d->printer;
-}
-
-/*!
- Returns the printer that this page setup dialog is operating on.
-*/
-QPrinter *QAbstractPageSetupDialog::printer()
-{
- Q_D(QAbstractPageSetupDialog);
- return d->printer;
-}
-
-void QAbstractPageSetupDialogPrivate::setPrinter(QPrinter *newPrinter)
-{
- if (newPrinter) {
- printer = newPrinter;
- } else {
- printer = new QPrinter;
- opts |= QPageSetupDialog::OwnsPrinter;
- }
-#ifndef Q_WS_X11
- if (printer->outputFormat() != QPrinter::NativeFormat)
- qWarning("QPageSetupDialog: Cannot be used on non-native printers");
-#endif
-}
-
-/*!
- \fn int QAbstractPageSetupDialog::exec()
-
- This virtual function is called to pop up the dialog. It must be
- reimplemented in subclasses.
-*/
-
-/*!
- \reimp
-*/
-void QAbstractPageSetupDialog::done(int result)
-{
- Q_D(QAbstractPageSetupDialog);
- QDialog::done(result);
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, SIGNAL(accepted()),
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
-
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qabstractpagesetupdialog.h b/src/gui/dialogs/qabstractpagesetupdialog.h
deleted file mode 100644
index ac3ffa5451..0000000000
--- a/src/gui/dialogs/qabstractpagesetupdialog.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTPAGESETUPDIALOG_H
-#define QABSTRACTPAGESETUPDIALOG_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PRINTDIALOG
-
-class QAbstractPageSetupDialogPrivate;
-class QPrinter;
-
-// ### Qt 5: Remove this class
-class Q_GUI_EXPORT QAbstractPageSetupDialog : public QDialog
-{
- Q_DECLARE_PRIVATE(QAbstractPageSetupDialog)
- Q_OBJECT
-
-public:
- explicit QAbstractPageSetupDialog(QPrinter *printer, QWidget *parent = 0);
- QAbstractPageSetupDialog(QAbstractPageSetupDialogPrivate &ptr,
- QPrinter *printer, QWidget *parent = 0);
- ~QAbstractPageSetupDialog();
-
- virtual int exec() = 0;
- void done(int result);
-
- QPrinter *printer();
-};
-
-#endif // QT_NO_PRINTDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTPAGESETUPDIALOG_H
diff --git a/src/gui/dialogs/qabstractpagesetupdialog_p.h b/src/gui/dialogs/qabstractpagesetupdialog_p.h
deleted file mode 100644
index 3dbfdd5e26..0000000000
--- a/src/gui/dialogs/qabstractpagesetupdialog_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTPAGESETUPDIALOG_P_H
-#define QABSTRACTPAGESETUPDIALOG_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// to version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include "private/qdialog_p.h"
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include "qbytearray.h"
-#include "qpagesetupdialog.h"
-#include "qpointer.h"
-
-QT_BEGIN_NAMESPACE
-
-class QPrinter;
-
-class QAbstractPageSetupDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractPageSetupDialog)
-
-public:
- QAbstractPageSetupDialogPrivate() : printer(0) {}
-
- void setPrinter(QPrinter *newPrinter);
-
- QPrinter *printer;
- QPageSetupDialog::PageSetupDialogOptions opts;
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTDIALOG
-
-#endif // QABSTRACTPAGESETUPDIALOG_P_H
diff --git a/src/gui/dialogs/qabstractprintdialog.cpp b/src/gui/dialogs/qabstractprintdialog.cpp
deleted file mode 100644
index 004f6877e4..0000000000
--- a/src/gui/dialogs/qabstractprintdialog.cpp
+++ /dev/null
@@ -1,499 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractprintdialog_p.h"
-#include "qcoreapplication.h"
-#include "qprintdialog.h"
-#include "qprinter.h"
-#include "private/qprinter_p.h"
-
-#ifndef QT_NO_PRINTDIALOG
-
-QT_BEGIN_NAMESPACE
-
-// hack
-class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
-{
-};
-
-/*!
- \class QAbstractPrintDialog
- \brief The QAbstractPrintDialog class provides a base implementation for
- print dialogs used to configure printers.
-
- \ingroup printing
-
- This class implements getter and setter functions that are used to
- customize settings shown in print dialogs, but it is not used directly.
- Use QPrintDialog to display a print dialog in your application.
-
- In Symbian, there is no support for printing. Hence, this dialog should not
- be used in Symbian.
-
- \sa QPrintDialog, QPrinter, {Printing with Qt}
-*/
-
-/*!
- \enum QAbstractPrintDialog::PrintRange
-
- Used to specify the print range selection option.
-
- \value AllPages All pages should be printed.
- \value Selection Only the selection should be printed.
- \value PageRange The specified page range should be printed.
- \value CurrentPage Only the currently visible page should be printed.
-
- \sa QPrinter::PrintRange
-*/
-
-/*!
- \enum QAbstractPrintDialog::PrintDialogOption
-
- Used to specify which parts of the print dialog should be visible.
-
- \value None None of the options are enabled.
- \value PrintToFile The print to file option is enabled.
- \value PrintSelection The print selection option is enabled.
- \value PrintPageRange The page range selection option is enabled.
- \value PrintShowPageSize Show the page size + margins page only if this is enabled.
- \value PrintCollateCopies The collate copies option is enabled
- \value PrintCurrentPage The print current page option is enabled
-
- This value is obsolete and does nothing since Qt 4.5:
-
- \value DontUseSheet In previous versions of Qt, exec() the print dialog
- would create a sheet by default the dialog was given a parent.
- This is no longer supported in Qt 4.5. If you want to use sheets, use
- QPrintDialog::open() instead.
-*/
-
-/*!
- Constructs an abstract print dialog for \a printer with \a parent
- as parent widget.
-*/
-QAbstractPrintDialog::QAbstractPrintDialog(QPrinter *printer, QWidget *parent)
- : QDialog(*(new QAbstractPrintDialogPrivate), parent)
-{
- Q_D(QAbstractPrintDialog);
- setWindowTitle(QCoreApplication::translate("QPrintDialog", "Print"));
- d->setPrinter(printer);
-}
-
-/*!
- \internal
-*/
-QAbstractPrintDialog::QAbstractPrintDialog(QAbstractPrintDialogPrivate &ptr,
- QPrinter *printer,
- QWidget *parent)
- : QDialog(ptr, parent)
-{
- Q_D(QAbstractPrintDialog);
- setWindowTitle(QCoreApplication::translate("QPrintDialog", "Print"));
- d->setPrinter(printer);
-}
-
-/*!
- \internal
-*/
-QAbstractPrintDialog::~QAbstractPrintDialog()
-{
- Q_D(QAbstractPrintDialog);
- if (d->ownsPrinter)
- delete d->printer;
-}
-
-/*!
- Sets the given \a option to be enabled if \a on is true;
- otherwise, clears the given \a option.
-
- \sa options, testOption()
-*/
-void QPrintDialog::setOption(PrintDialogOption option, bool on)
-{
- Q_D(QPrintDialog);
- if (!(d->options & option) != !on)
- setOptions(d->options ^ option);
-}
-
-/*!
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QPrintDialog::testOption(PrintDialogOption option) const
-{
- Q_D(const QPrintDialog);
- return (d->options & option) != 0;
-}
-
-/*!
- \property QPrintDialog::options
- \brief the various options that affect the look and feel of the dialog
- \since 4.5
-
- By default, all options are disabled.
-
- Options should be set before showing the dialog. Setting them while the
- dialog is visible is not guaranteed to have an immediate effect on the
- dialog (depending on the option and on the platform).
-
- \sa setOption(), testOption()
-*/
-void QPrintDialog::setOptions(PrintDialogOptions options)
-{
- Q_D(QPrintDialog);
-
- PrintDialogOptions changed = (options ^ d->options);
- if (!changed)
- return;
-
- d->options = options;
-}
-
-QPrintDialog::PrintDialogOptions QPrintDialog::options() const
-{
- Q_D(const QPrintDialog);
- return d->options;
-}
-
-/*!
- \obsolete
-
- Use QPrintDialog::setOptions() instead.
-*/
-void QAbstractPrintDialog::setEnabledOptions(PrintDialogOptions options)
-{
- Q_D(QAbstractPrintDialog);
- d->options = options;
-}
-
-/*!
- \obsolete
-
- Use QPrintDialog::setOption(\a option, true) instead.
-*/
-void QAbstractPrintDialog::addEnabledOption(PrintDialogOption option)
-{
- Q_D(QAbstractPrintDialog);
- d->options |= option;
-}
-
-/*!
- \obsolete
-
- Use QPrintDialog::options() instead.
-*/
-QAbstractPrintDialog::PrintDialogOptions QAbstractPrintDialog::enabledOptions() const
-{
- Q_D(const QAbstractPrintDialog);
- return d->options;
-}
-
-/*!
- \obsolete
-
- Use QPrintDialog::testOption(\a option) instead.
-*/
-bool QAbstractPrintDialog::isOptionEnabled(PrintDialogOption option) const
-{
- Q_D(const QAbstractPrintDialog);
- return d->options & option;
-}
-
-/*!
- Sets the print range option in to be \a range.
- */
-void QAbstractPrintDialog::setPrintRange(PrintRange range)
-{
- Q_D(QAbstractPrintDialog);
- d->pd->printRange = QPrinter::PrintRange(range);
-}
-
-/*!
- Returns the print range.
-*/
-QAbstractPrintDialog::PrintRange QAbstractPrintDialog::printRange() const
-{
- Q_D(const QAbstractPrintDialog);
- return QAbstractPrintDialog::PrintRange(d->pd->printRange);
-}
-
-/*!
- Sets the page range in this dialog to be from \a min to \a max. This also
- enables the PrintPageRange option.
-*/
-void QAbstractPrintDialog::setMinMax(int min, int max)
-{
- Q_D(QAbstractPrintDialog);
- Q_ASSERT_X(min <= max, "QAbstractPrintDialog::setMinMax",
- "'min' must be less than or equal to 'max'");
- d->pd->minPage = min;
- d->pd->maxPage = max;
- d->options |= PrintPageRange;
-}
-
-/*!
- Returns the minimum page in the page range.
- By default, this value is set to 1.
-*/
-int QAbstractPrintDialog::minPage() const
-{
- Q_D(const QAbstractPrintDialog);
- return d->pd->minPage;
-}
-
-/*!
- Returns the maximum page in the page range. As of Qt 4.4, this
- function returns INT_MAX by default. Previous versions returned 1
- by default.
-*/
-int QAbstractPrintDialog::maxPage() const
-{
- Q_D(const QAbstractPrintDialog);
- return d->pd->maxPage;
-}
-
-/*!
- Sets the range in the print dialog to be from \a from to \a to.
-*/
-void QAbstractPrintDialog::setFromTo(int from, int to)
-{
- Q_D(QAbstractPrintDialog);
- Q_ASSERT_X(from <= to, "QAbstractPrintDialog::setFromTo",
- "'from' must be less than or equal to 'to'");
- d->pd->fromPage = from;
- d->pd->toPage = to;
-
- if (d->pd->minPage == 0 && d->pd->maxPage == 0)
- setMinMax(1, to);
-}
-
-/*!
- Returns the first page to be printed
- By default, this value is set to 0.
-*/
-int QAbstractPrintDialog::fromPage() const
-{
- Q_D(const QAbstractPrintDialog);
- return d->pd->fromPage;
-}
-
-/*!
- Returns the last page to be printed.
- By default, this value is set to 0.
-*/
-int QAbstractPrintDialog::toPage() const
-{
- Q_D(const QAbstractPrintDialog);
- return d->pd->toPage;
-}
-
-
-/*!
- Returns the printer that this printer dialog operates
- on.
-*/
-QPrinter *QAbstractPrintDialog::printer() const
-{
- Q_D(const QAbstractPrintDialog);
- return d->printer;
-}
-
-void QAbstractPrintDialogPrivate::setPrinter(QPrinter *newPrinter)
-{
- if (newPrinter) {
- printer = newPrinter;
- ownsPrinter = false;
- if (printer->fromPage() || printer->toPage())
- options |= QAbstractPrintDialog::PrintPageRange;
- } else {
- printer = new QPrinter;
- ownsPrinter = true;
- }
- pd = printer->d_func();
-}
-
-/*!
- \fn int QAbstractPrintDialog::exec()
-
- This virtual function is called to pop up the dialog. It must be
- reimplemented in subclasses.
-*/
-
-/*!
- \class QPrintDialog
-
- \brief The QPrintDialog class provides a dialog for specifying
- the printer's configuration.
-
- \ingroup standard-dialogs
- \ingroup printing
-
- The dialog allows users to change document-related settings, such
- as the paper size and orientation, type of print (color or
- grayscale), range of pages, and number of copies to print.
-
- Controls are also provided to enable users to choose from the
- printers available, including any configured network printers.
-
- Typically, QPrintDialog objects are constructed with a QPrinter
- object, and executed using the exec() function.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qabstractprintdialog.cpp 0
-
- If the dialog is accepted by the user, the QPrinter object is
- correctly configured for printing.
-
- \table
- \row
- \o \inlineimage plastique-printdialog.png
- \o \inlineimage plastique-printdialog-properties.png
- \endtable
-
- The printer dialog (shown above in Plastique style) enables access to common
- printing properties. On X11 platforms that use the CUPS printing system, the
- settings for each available printer can be modified via the dialog's
- \gui{Properties} push button.
-
- On Windows and Mac OS X, the native print dialog is used, which means that
- some QWidget and QDialog properties set on the dialog won't be respected.
- The native print dialog on Mac OS X does not support setting printer options,
- i.e. setOptions() and setOption() have no effect.
-
- In Qt 4.4, it was possible to use the static functions to show a sheet on
- Mac OS X. This is no longer supported in Qt 4.5. If you want this
- functionality, use QPrintDialog::open().
-
- \sa QPageSetupDialog, QPrinter, {Pixelator Example}, {Order Form Example},
- {Image Viewer Example}, {Scribble Example}
-*/
-
-/*!
- \fn QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
-
- Constructs a new modal printer dialog for the given \a printer
- with the given \a parent.
-*/
-
-/*!
- \fn QPrintDialog::~QPrintDialog()
-
- Destroys the print dialog.
-*/
-
-/*!
- \fn int QPrintDialog::exec()
- \reimp
-*/
-
-/*!
- \since 4.4
-
- Set a list of widgets as \a tabs to be shown on the print dialog, if supported.
-
- Currently this option is only supported on X11.
-
- Setting the option tabs will transfer their ownership to the print dialog.
-*/
-void QAbstractPrintDialog::setOptionTabs(const QList<QWidget*> &tabs)
-{
- Q_D(QAbstractPrintDialog);
- d->setTabs(tabs);
-}
-
-/*!
-
- \fn void QPrintDialog::accepted(QPrinter *printer)
-
- This signal is emitted when the user accepts the values set in the print dialog.
- The \a printer parameter includes the printer that the settings were applied to.
-*/
-
-/*!
- \fn QPrinter *QPrintDialog::printer()
-
- Returns the printer that this printer dialog operates
- on. This can be useful when using the QPrintDialog::open() method.
-*/
-
-/*!
- Closes the dialog and sets its result code to \a result. If this dialog
- is shown with exec(), done() causes the local event loop to finish,
- and exec() to return \a result.
-
- \sa QDialog::done()
-*/
-void QPrintDialog::done(int result)
-{
- Q_D(QPrintDialog);
- QDialog::done(result);
- if (result == Accepted)
- emit accepted(printer());
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, SIGNAL(accepted(QPrinter*)),
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
-}
-
-/*!
- \since 4.5
- \overload
-
- Opens the dialog and connects its accepted() signal to the slot specified
- by \a receiver and \a member.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QPrintDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QPrintDialog);
- connect(this, SIGNAL(accepted(QPrinter*)), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qabstractprintdialog.h b/src/gui/dialogs/qabstractprintdialog.h
deleted file mode 100644
index b9ac05ccff..0000000000
--- a/src/gui/dialogs/qabstractprintdialog.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTPRINTDIALOG_H
-#define QABSTRACTPRINTDIALOG_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PRINTER
-
-class QAbstractPrintDialogPrivate;
-class QPrinter;
-
-// ### Qt 5: remove this class
-class Q_GUI_EXPORT QAbstractPrintDialog : public QDialog
-{
- Q_DECLARE_PRIVATE(QAbstractPrintDialog)
- Q_OBJECT
-
-public:
- // Keep in sync with QPrinter::PrintRange
- enum PrintRange {
- AllPages,
- Selection,
- PageRange,
- CurrentPage
- };
-
- enum PrintDialogOption {
- None = 0x0000, // obsolete
- PrintToFile = 0x0001,
- PrintSelection = 0x0002,
- PrintPageRange = 0x0004,
- PrintShowPageSize = 0x0008,
- PrintCollateCopies = 0x0010,
- DontUseSheet = 0x0020,
- PrintCurrentPage = 0x0040
- };
-
- Q_DECLARE_FLAGS(PrintDialogOptions, PrintDialogOption)
-
-#ifndef QT_NO_PRINTDIALOG
- explicit QAbstractPrintDialog(QPrinter *printer, QWidget *parent = 0);
- ~QAbstractPrintDialog();
-
- virtual int exec() = 0;
-
- // obsolete
- void addEnabledOption(PrintDialogOption option);
- void setEnabledOptions(PrintDialogOptions options);
- PrintDialogOptions enabledOptions() const;
- bool isOptionEnabled(PrintDialogOption option) const;
-
- void setOptionTabs(const QList<QWidget*> &tabs);
-
- void setPrintRange(PrintRange range);
- PrintRange printRange() const;
-
- void setMinMax(int min, int max);
- int minPage() const;
- int maxPage() const;
-
- void setFromTo(int fromPage, int toPage);
- int fromPage() const;
- int toPage() const;
-
- QPrinter *printer() const;
-
-protected:
- QAbstractPrintDialog(QAbstractPrintDialogPrivate &ptr, QPrinter *printer, QWidget *parent = 0);
-
-private:
- Q_DISABLE_COPY(QAbstractPrintDialog)
-
-#endif // QT_NO_PRINTDIALOG
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QAbstractPrintDialog::PrintDialogOptions)
-
-#endif // QT_NO_PRINTER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTPRINTDIALOG_H
diff --git a/src/gui/dialogs/qabstractprintdialog_p.h b/src/gui/dialogs/qabstractprintdialog_p.h
deleted file mode 100644
index 1b5fa599f0..0000000000
--- a/src/gui/dialogs/qabstractprintdialog_p.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTPRINTDIALOG_P_H
-#define QABSTRACTPRINTDIALOG_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qdialog_p.h"
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include "QtGui/qabstractprintdialog.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_PRINTER
-
-class QPrinter;
-class QPrinterPrivate;
-
-class QAbstractPrintDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractPrintDialog)
-
-public:
- QAbstractPrintDialogPrivate()
- : printer(0), pd(0), ownsPrinter(false)
- , options(QAbstractPrintDialog::PrintToFile | QAbstractPrintDialog::PrintPageRange |
- QAbstractPrintDialog::PrintCollateCopies | QAbstractPrintDialog::PrintShowPageSize)
- {
- }
-
- QPrinter *printer;
- QPrinterPrivate *pd;
- bool ownsPrinter;
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-
- QAbstractPrintDialog::PrintDialogOptions options;
-
- virtual void setTabs(const QList<QWidget *> &) {}
- void setPrinter(QPrinter *newPrinter);
-};
-
-#endif //QT_NO_PRINTER
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTDIALOG
-
-#endif // QABSTRACTPRINTDIALOG_P_H
diff --git a/src/gui/dialogs/qcolordialog.cpp b/src/gui/dialogs/qcolordialog.cpp
deleted file mode 100644
index f99e6c2621..0000000000
--- a/src/gui/dialogs/qcolordialog.cpp
+++ /dev/null
@@ -1,2115 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolordialog_p.h"
-
-#ifndef QT_NO_COLORDIALOG
-
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qdrawutil.h"
-#include "qevent.h"
-#include "qimage.h"
-#include "qdrag.h"
-#include "qlabel.h"
-#include "qlayout.h"
-#include "qlineedit.h"
-#include "qmenu.h"
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qpushbutton.h"
-#include "qsettings.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qvalidator.h"
-#include "qmime.h"
-#include "qspinbox.h"
-#include "qdialogbuttonbox.h"
-#include "private/qguiplatformplugin_p.h"
-
-#ifdef Q_WS_S60
-#include "private/qt_s60_p.h"
-#endif
-
-#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
-# define QT_SMALL_COLORDIALOG
-#endif
-
-QT_BEGIN_NAMESPACE
-
-//////////// QWellArray BEGIN
-
-struct QWellArrayData;
-
-class QWellArray : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(int selectedColumn READ selectedColumn)
- Q_PROPERTY(int selectedRow READ selectedRow)
-
-public:
- QWellArray(int rows, int cols, QWidget* parent=0);
- ~QWellArray() {}
- QString cellContent(int row, int col) const;
-
- int selectedColumn() const { return selCol; }
- int selectedRow() const { return selRow; }
-
- virtual void setCurrent(int row, int col);
- virtual void setSelected(int row, int col);
-
- QSize sizeHint() const;
-
- virtual void setCellBrush(int row, int col, const QBrush &);
- QBrush cellBrush(int row, int col);
-
- inline int cellWidth() const
- { return cellw; }
-
- inline int cellHeight() const
- { return cellh; }
-
- inline int rowAt(int y) const
- { return y / cellh; }
-
- inline int columnAt(int x) const
- { if (isRightToLeft()) return ncols - (x / cellw) - 1; return x / cellw; }
-
- inline int rowY(int row) const
- { return cellh * row; }
-
- inline int columnX(int column) const
- { if (isRightToLeft()) return cellw * (ncols - column - 1); return cellw * column; }
-
- inline int numRows() const
- { return nrows; }
-
- inline int numCols() const
- {return ncols; }
-
- inline QRect cellRect() const
- { return QRect(0, 0, cellw, cellh); }
-
- inline QSize gridSize() const
- { return QSize(ncols * cellw, nrows * cellh); }
-
- QRect cellGeometry(int row, int column)
- {
- QRect r;
- if (row >= 0 && row < nrows && column >= 0 && column < ncols)
- r.setRect(columnX(column), rowY(row), cellw, cellh);
- return r;
- }
-
- inline void updateCell(int row, int column) { update(cellGeometry(row, column)); }
-
-signals:
- void selected(int row, int col);
-
-protected:
- virtual void paintCell(QPainter *, int row, int col, const QRect&);
- virtual void paintCellContents(QPainter *, int row, int col, const QRect&);
-
- void mousePressEvent(QMouseEvent*);
- void mouseReleaseEvent(QMouseEvent*);
- void keyPressEvent(QKeyEvent*);
- void focusInEvent(QFocusEvent*);
- void focusOutEvent(QFocusEvent*);
- void paintEvent(QPaintEvent *);
-
-private:
- Q_DISABLE_COPY(QWellArray)
-
- int nrows;
- int ncols;
- int cellw;
- int cellh;
- int curRow;
- int curCol;
- int selRow;
- int selCol;
- QWellArrayData *d;
-};
-
-void QWellArray::paintEvent(QPaintEvent *e)
-{
- QRect r = e->rect();
- int cx = r.x();
- int cy = r.y();
- int ch = r.height();
- int cw = r.width();
- int colfirst = columnAt(cx);
- int collast = columnAt(cx + cw);
- int rowfirst = rowAt(cy);
- int rowlast = rowAt(cy + ch);
-
- if (isRightToLeft()) {
- int t = colfirst;
- colfirst = collast;
- collast = t;
- }
-
- QPainter painter(this);
- QPainter *p = &painter;
- QRect rect(0, 0, cellWidth(), cellHeight());
-
-
- if (collast < 0 || collast >= ncols)
- collast = ncols-1;
- if (rowlast < 0 || rowlast >= nrows)
- rowlast = nrows-1;
-
- // Go through the rows
- for (int r = rowfirst; r <= rowlast; ++r) {
- // get row position and height
- int rowp = rowY(r);
-
- // Go through the columns in the row r
- // if we know from where to where, go through [colfirst, collast],
- // else go through all of them
- for (int c = colfirst; c <= collast; ++c) {
- // get position and width of column c
- int colp = columnX(c);
- // Translate painter and draw the cell
- rect.translate(colp, rowp);
- paintCell(p, r, c, rect);
- rect.translate(-colp, -rowp);
- }
- }
-}
-
-struct QWellArrayData {
- QBrush *brush;
-};
-
-QWellArray::QWellArray(int rows, int cols, QWidget *parent)
- : QWidget(parent)
- ,nrows(rows), ncols(cols)
-{
- d = 0;
- setFocusPolicy(Qt::StrongFocus);
- cellw = 28;
- cellh = 24;
- curCol = 0;
- curRow = 0;
- selCol = -1;
- selRow = -1;
-}
-
-QSize QWellArray::sizeHint() const
-{
- ensurePolished();
- return gridSize().boundedTo(QSize(640, 480));
-}
-
-
-void QWellArray::paintCell(QPainter* p, int row, int col, const QRect &rect)
-{
- int b = 3; //margin
-
- const QPalette & g = palette();
- QStyleOptionFrame opt;
- int dfw = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- opt.lineWidth = dfw;
- opt.midLineWidth = 1;
- opt.rect = rect.adjusted(b, b, -b, -b);
- opt.palette = g;
- opt.state = QStyle::State_Enabled | QStyle::State_Sunken;
- style()->drawPrimitive(QStyle::PE_Frame, &opt, p, this);
- b += dfw;
-
- if ((row == curRow) && (col == curCol)) {
- if (hasFocus()) {
- QStyleOptionFocusRect opt;
- opt.palette = g;
- opt.rect = rect;
- opt.state = QStyle::State_None | QStyle::State_KeyboardFocusChange;
- style()->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, p, this);
- }
- }
- paintCellContents(p, row, col, opt.rect.adjusted(dfw, dfw, -dfw, -dfw));
-}
-
-/*!
- Reimplement this function to change the contents of the well array.
- */
-void QWellArray::paintCellContents(QPainter *p, int row, int col, const QRect &r)
-{
- if (d) {
- p->fillRect(r, d->brush[row*numCols()+col]);
- } else {
- p->fillRect(r, Qt::white);
- p->setPen(Qt::black);
- p->drawLine(r.topLeft(), r.bottomRight());
- p->drawLine(r.topRight(), r.bottomLeft());
- }
-}
-
-void QWellArray::mousePressEvent(QMouseEvent *e)
-{
- // The current cell marker is set to the cell the mouse is pressed in
- QPoint pos = e->pos();
- setCurrent(rowAt(pos.y()), columnAt(pos.x()));
-}
-
-void QWellArray::mouseReleaseEvent(QMouseEvent * /* event */)
-{
- // The current cell marker is set to the cell the mouse is clicked in
- setSelected(curRow, curCol);
-}
-
-
-/*
- Sets the cell currently having the focus. This is not necessarily
- the same as the currently selected cell.
-*/
-
-void QWellArray::setCurrent(int row, int col)
-{
- if ((curRow == row) && (curCol == col))
- return;
-
- if (row < 0 || col < 0)
- row = col = -1;
-
- int oldRow = curRow;
- int oldCol = curCol;
-
- curRow = row;
- curCol = col;
-
- updateCell(oldRow, oldCol);
- updateCell(curRow, curCol);
-}
-
-/*
- Sets the currently selected cell to \a row, \a column. If \a row or
- \a column are less than zero, the current cell is unselected.
-
- Does not set the position of the focus indicator.
-*/
-void QWellArray::setSelected(int row, int col)
-{
- int oldRow = selRow;
- int oldCol = selCol;
-
- if (row < 0 || col < 0)
- row = col = -1;
-
- selCol = col;
- selRow = row;
-
- updateCell(oldRow, oldCol);
- updateCell(selRow, selCol);
- if (row >= 0)
- emit selected(row, col);
-
-#ifndef QT_NO_MENU
- if (isVisible() && qobject_cast<QMenu*>(parentWidget()))
- parentWidget()->close();
-#endif
-}
-
-void QWellArray::focusInEvent(QFocusEvent*)
-{
- updateCell(curRow, curCol);
-}
-
-void QWellArray::setCellBrush(int row, int col, const QBrush &b)
-{
- if (!d) {
- d = new QWellArrayData;
- int i = numRows()*numCols();
- d->brush = new QBrush[i];
- }
- if (row >= 0 && row < numRows() && col >= 0 && col < numCols())
- d->brush[row*numCols()+col] = b;
-}
-
-/*
- Returns the brush set for the cell at \a row, \a column. If no brush is
- set, Qt::NoBrush is returned.
-*/
-
-QBrush QWellArray::cellBrush(int row, int col)
-{
- if (d && row >= 0 && row < numRows() && col >= 0 && col < numCols())
- return d->brush[row*numCols()+col];
- return Qt::NoBrush;
-}
-
-
-
-/*!\reimp
-*/
-
-void QWellArray::focusOutEvent(QFocusEvent*)
-{
- updateCell(curRow, curCol);
-}
-
-/*\reimp
-*/
-void QWellArray::keyPressEvent(QKeyEvent* e)
-{
- switch(e->key()) { // Look at the key code
- case Qt::Key_Left: // If 'left arrow'-key,
- if(curCol > 0) // and cr't not in leftmost col
- setCurrent(curRow, curCol - 1); // set cr't to next left column
- break;
- case Qt::Key_Right: // Correspondingly...
- if(curCol < numCols()-1)
- setCurrent(curRow, curCol + 1);
- break;
- case Qt::Key_Up:
- if(curRow > 0)
- setCurrent(curRow - 1, curCol);
- break;
- case Qt::Key_Down:
- if(curRow < numRows()-1)
- setCurrent(curRow + 1, curCol);
- break;
-#if 0
- // bad idea that shouldn't have been implemented; very counterintuitive
- case Qt::Key_Return:
- case Qt::Key_Enter:
- /*
- ignore the key, so that the dialog get it, but still select
- the current row/col
- */
- e->ignore();
- // fallthrough intended
-#endif
- case Qt::Key_Space:
- setSelected(curRow, curCol);
- break;
- default: // If not an interesting key,
- e->ignore(); // we don't accept the event
- return;
- }
-
-}
-
-//////////// QWellArray END
-
-static bool initrgb = false;
-static QRgb stdrgb[6*8];
-static QRgb cusrgb[2*8];
-static bool customSet = false;
-
-
-static void initRGB()
-{
- if (initrgb)
- return;
- initrgb = true;
- int i = 0;
- for (int g = 0; g < 4; g++)
- for (int r = 0; r < 4; r++)
- for (int b = 0; b < 3; b++)
- stdrgb[i++] = qRgb(r * 255 / 3, g * 255 / 3, b * 255 / 2);
-
- for (i = 0; i < 2*8; i++)
- cusrgb[i] = 0xffffffff;
-}
-
-/*!
- Returns the number of custom colors supported by QColorDialog. All
- color dialogs share the same custom colors.
-*/
-int QColorDialog::customCount()
-{
- return 2 * 8;
-}
-
-/*!
- \since 4.5
-
- Returns the custom color at the given \a index as a QRgb value.
-*/
-QRgb QColorDialog::customColor(int index)
-{
- if (uint(index) >= uint(customCount()))
- return qRgb(255, 255, 255);
- initRGB();
- return cusrgb[index];
-}
-
-/*!
- Sets the custom color at \a index to the QRgb \a color value.
-
- \note This function does not apply to the Native Color Dialog on the Mac
- OS X platform. If you still require this function, use the
- QColorDialog::DontUseNativeDialog option.
-*/
-void QColorDialog::setCustomColor(int index, QRgb color)
-{
- if (uint(index) >= uint(customCount()))
- return;
- initRGB();
- customSet = true;
- cusrgb[index] = color;
-}
-
-/*!
- Sets the standard color at \a index to the QRgb \a color value.
-
- \note This function does not apply to the Native Color Dialog on the Mac
- OS X platform. If you still require this function, use the
- QColorDialog::DontUseNativeDialog option.
-*/
-
-void QColorDialog::setStandardColor(int index, QRgb color)
-{
- if (uint(index) >= uint(6 * 8))
- return;
- initRGB();
- stdrgb[index] = color;
-}
-
-static inline void rgb2hsv(QRgb rgb, int &h, int &s, int &v)
-{
- QColor c;
- c.setRgb(rgb);
- c.getHsv(&h, &s, &v);
-}
-
-class QColorWell : public QWellArray
-{
-public:
- QColorWell(QWidget *parent, int r, int c, QRgb *vals)
- :QWellArray(r, c, parent), values(vals), mousePressed(false), oldCurrent(-1, -1)
- { setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum)); }
-
-protected:
- void paintCellContents(QPainter *, int row, int col, const QRect&);
- void mousePressEvent(QMouseEvent *e);
- void mouseMoveEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QDragEnterEvent *e);
- void dragLeaveEvent(QDragLeaveEvent *e);
- void dragMoveEvent(QDragMoveEvent *e);
- void dropEvent(QDropEvent *e);
-#endif
-
-private:
- QRgb *values;
- bool mousePressed;
- QPoint pressPos;
- QPoint oldCurrent;
-
-};
-
-void QColorWell::paintCellContents(QPainter *p, int row, int col, const QRect &r)
-{
- int i = row + col*numRows();
- p->fillRect(r, QColor(values[i]));
-}
-
-void QColorWell::mousePressEvent(QMouseEvent *e)
-{
- oldCurrent = QPoint(selectedRow(), selectedColumn());
- QWellArray::mousePressEvent(e);
- mousePressed = true;
- pressPos = e->pos();
-}
-
-void QColorWell::mouseMoveEvent(QMouseEvent *e)
-{
- QWellArray::mouseMoveEvent(e);
-#ifndef QT_NO_DRAGANDDROP
- if (!mousePressed)
- return;
- if ((pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance()) {
- setCurrent(oldCurrent.x(), oldCurrent.y());
- int i = rowAt(pressPos.y()) + columnAt(pressPos.x()) * numRows();
- QColor col(values[i]);
- QMimeData *mime = new QMimeData;
- mime->setColorData(col);
- QPixmap pix(cellWidth(), cellHeight());
- pix.fill(col);
- QPainter p(&pix);
- p.drawRect(0, 0, pix.width() - 1, pix.height() - 1);
- p.end();
- QDrag *drg = new QDrag(this);
- drg->setMimeData(mime);
- drg->setPixmap(pix);
- mousePressed = false;
- drg->start();
- }
-#endif
-}
-
-#ifndef QT_NO_DRAGANDDROP
-void QColorWell::dragEnterEvent(QDragEnterEvent *e)
-{
- if (qvariant_cast<QColor>(e->mimeData()->colorData()).isValid())
- e->accept();
- else
- e->ignore();
-}
-
-void QColorWell::dragLeaveEvent(QDragLeaveEvent *)
-{
- if (hasFocus())
- parentWidget()->setFocus();
-}
-
-void QColorWell::dragMoveEvent(QDragMoveEvent *e)
-{
- if (qvariant_cast<QColor>(e->mimeData()->colorData()).isValid()) {
- setCurrent(rowAt(e->pos().y()), columnAt(e->pos().x()));
- e->accept();
- } else {
- e->ignore();
- }
-}
-
-void QColorWell::dropEvent(QDropEvent *e)
-{
- QColor col = qvariant_cast<QColor>(e->mimeData()->colorData());
- if (col.isValid()) {
- int i = rowAt(e->pos().y()) + columnAt(e->pos().x()) * numRows();
- values[i] = col.rgb();
- update();
- e->accept();
- } else {
- e->ignore();
- }
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-void QColorWell::mouseReleaseEvent(QMouseEvent *e)
-{
- if (!mousePressed)
- return;
- QWellArray::mouseReleaseEvent(e);
- mousePressed = false;
-}
-
-class QColorPicker : public QFrame
-{
- Q_OBJECT
-public:
- QColorPicker(QWidget* parent);
- ~QColorPicker();
-
-public slots:
- void setCol(int h, int s);
-
-signals:
- void newCol(int h, int s);
-
-protected:
- QSize sizeHint() const;
- void paintEvent(QPaintEvent*);
- void mouseMoveEvent(QMouseEvent *);
- void mousePressEvent(QMouseEvent *);
- void resizeEvent(QResizeEvent *);
-
-private:
- int hue;
- int sat;
-
- QPoint colPt();
- int huePt(const QPoint &pt);
- int satPt(const QPoint &pt);
- void setCol(const QPoint &pt);
-
- QPixmap pix;
-};
-
-static int pWidth = 220;
-static int pHeight = 200;
-
-class QColorLuminancePicker : public QWidget
-{
- Q_OBJECT
-public:
- QColorLuminancePicker(QWidget* parent=0);
- ~QColorLuminancePicker();
-
-public slots:
- void setCol(int h, int s, int v);
- void setCol(int h, int s);
-
-signals:
- void newHsv(int h, int s, int v);
-
-protected:
- void paintEvent(QPaintEvent*);
- void mouseMoveEvent(QMouseEvent *);
- void mousePressEvent(QMouseEvent *);
-
-private:
- enum { foff = 3, coff = 4 }; //frame and contents offset
- int val;
- int hue;
- int sat;
-
- int y2val(int y);
- int val2y(int val);
- void setVal(int v);
-
- QPixmap *pix;
-};
-
-
-int QColorLuminancePicker::y2val(int y)
-{
- int d = height() - 2*coff - 1;
- return 255 - (y - coff)*255/d;
-}
-
-int QColorLuminancePicker::val2y(int v)
-{
- int d = height() - 2*coff - 1;
- return coff + (255-v)*d/255;
-}
-
-QColorLuminancePicker::QColorLuminancePicker(QWidget* parent)
- :QWidget(parent)
-{
- hue = 100; val = 100; sat = 100;
- pix = 0;
- // setAttribute(WA_NoErase, true);
-}
-
-QColorLuminancePicker::~QColorLuminancePicker()
-{
- delete pix;
-}
-
-void QColorLuminancePicker::mouseMoveEvent(QMouseEvent *m)
-{
- setVal(y2val(m->y()));
-}
-void QColorLuminancePicker::mousePressEvent(QMouseEvent *m)
-{
- setVal(y2val(m->y()));
-}
-
-void QColorLuminancePicker::setVal(int v)
-{
- if (val == v)
- return;
- val = qMax(0, qMin(v,255));
- delete pix; pix=0;
- repaint();
- emit newHsv(hue, sat, val);
-}
-
-//receives from a hue,sat chooser and relays.
-void QColorLuminancePicker::setCol(int h, int s)
-{
- setCol(h, s, val);
- emit newHsv(h, s, val);
-}
-
-void QColorLuminancePicker::paintEvent(QPaintEvent *)
-{
- int w = width() - 5;
-
- QRect r(0, foff, w, height() - 2*foff);
- int wi = r.width() - 2;
- int hi = r.height() - 2;
- if (!pix || pix->height() != hi || pix->width() != wi) {
- delete pix;
- QImage img(wi, hi, QImage::Format_RGB32);
- int y;
- uint *pixel = (uint *) img.scanLine(0);
- for (y = 0; y < hi; y++) {
- const uint *end = pixel + wi;
- while (pixel < end) {
- QColor c;
- c.setHsv(hue, sat, y2val(y+coff));
- *pixel = c.rgb();
- ++pixel;
- }
- }
- pix = new QPixmap(QPixmap::fromImage(img));
- }
- QPainter p(this);
- p.drawPixmap(1, coff, *pix);
- const QPalette &g = palette();
- qDrawShadePanel(&p, r, g, true);
- p.setPen(g.foreground().color());
- p.setBrush(g.foreground());
- QPolygon a;
- int y = val2y(val);
- a.setPoints(3, w, y, w+5, y+5, w+5, y-5);
- p.eraseRect(w, 0, 5, height());
- p.drawPolygon(a);
-}
-
-void QColorLuminancePicker::setCol(int h, int s , int v)
-{
- val = v;
- hue = h;
- sat = s;
- delete pix; pix=0;
- repaint();
-}
-
-QPoint QColorPicker::colPt()
-{
- QRect r = contentsRect();
- return QPoint((360 - hue) * (r.width() - 1) / 360, (255 - sat) * (r.height() - 1) / 255);
-}
-
-int QColorPicker::huePt(const QPoint &pt)
-{
- QRect r = contentsRect();
- return 360 - pt.x() * 360 / (r.width() - 1);
-}
-
-int QColorPicker::satPt(const QPoint &pt)
-{
- QRect r = contentsRect();
- return 255 - pt.y() * 255 / (r.height() - 1);
-}
-
-void QColorPicker::setCol(const QPoint &pt)
-{
- setCol(huePt(pt), satPt(pt));
-}
-
-QColorPicker::QColorPicker(QWidget* parent)
- : QFrame(parent)
-{
- hue = 0; sat = 0;
- setCol(150, 255);
-
- setAttribute(Qt::WA_NoSystemBackground);
- setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed) );
-}
-
-QColorPicker::~QColorPicker()
-{
-}
-
-QSize QColorPicker::sizeHint() const
-{
- return QSize(pWidth + 2*frameWidth(), pHeight + 2*frameWidth());
-}
-
-void QColorPicker::setCol(int h, int s)
-{
- int nhue = qMin(qMax(0,h), 359);
- int nsat = qMin(qMax(0,s), 255);
- if (nhue == hue && nsat == sat)
- return;
-
- QRect r(colPt(), QSize(20,20));
- hue = nhue; sat = nsat;
- r = r.united(QRect(colPt(), QSize(20,20)));
- r.translate(contentsRect().x()-9, contentsRect().y()-9);
- // update(r);
- repaint(r);
-}
-
-void QColorPicker::mouseMoveEvent(QMouseEvent *m)
-{
- QPoint p = m->pos() - contentsRect().topLeft();
- setCol(p);
- emit newCol(hue, sat);
-}
-
-void QColorPicker::mousePressEvent(QMouseEvent *m)
-{
- QPoint p = m->pos() - contentsRect().topLeft();
- setCol(p);
- emit newCol(hue, sat);
-}
-
-void QColorPicker::paintEvent(QPaintEvent* )
-{
- QPainter p(this);
- drawFrame(&p);
- QRect r = contentsRect();
-
- p.drawPixmap(r.topLeft(), pix);
- QPoint pt = colPt() + r.topLeft();
- p.setPen(Qt::black);
-
- p.fillRect(pt.x()-9, pt.y(), 20, 2, Qt::black);
- p.fillRect(pt.x(), pt.y()-9, 2, 20, Qt::black);
-
-}
-
-void QColorPicker::resizeEvent(QResizeEvent *ev)
-{
- QFrame::resizeEvent(ev);
-
- int w = width() - frameWidth() * 2;
- int h = height() - frameWidth() * 2;
- QImage img(w, h, QImage::Format_RGB32);
- int x, y;
- uint *pixel = (uint *) img.scanLine(0);
- for (y = 0; y < h; y++) {
- const uint *end = pixel + w;
- x = 0;
- while (pixel < end) {
- QPoint p(x, y);
- QColor c;
- c.setHsv(huePt(p), satPt(p), 200);
- *pixel = c.rgb();
- ++pixel;
- ++x;
- }
- }
- pix = QPixmap::fromImage(img);
-}
-
-
-class QColSpinBox : public QSpinBox
-{
-public:
- QColSpinBox(QWidget *parent)
- : QSpinBox(parent) { setRange(0, 255); }
- void setValue(int i) {
- bool block = signalsBlocked();
- blockSignals(true);
- QSpinBox::setValue(i);
- blockSignals(block);
- }
-};
-
-class QColorShowLabel;
-
-class QColorShower : public QWidget
-{
- Q_OBJECT
-public:
- QColorShower(QColorDialog *parent);
-
- //things that don't emit signals
- void setHsv(int h, int s, int v);
-
- int currentAlpha() const
- { return (colorDialog->options() & QColorDialog::ShowAlphaChannel) ? alphaEd->value() : 255; }
- void setCurrentAlpha(int a) { alphaEd->setValue(a); rgbEd(); }
- void showAlpha(bool b);
- bool isAlphaVisible() const;
-
- QRgb currentColor() const { return curCol; }
- QColor currentQColor() const { return curQColor; }
- void retranslateStrings();
- void updateQColor();
-
-public slots:
- void setRgb(QRgb rgb);
-
-signals:
- void newCol(QRgb rgb);
- void currentColorChanged(const QColor &color);
-
-private slots:
- void rgbEd();
- void hsvEd();
-private:
- void showCurrentColor();
- int hue, sat, val;
- QRgb curCol;
- QColor curQColor;
- QLabel *lblHue;
- QLabel *lblSat;
- QLabel *lblVal;
- QLabel *lblRed;
- QLabel *lblGreen;
- QLabel *lblBlue;
- QColSpinBox *hEd;
- QColSpinBox *sEd;
- QColSpinBox *vEd;
- QColSpinBox *rEd;
- QColSpinBox *gEd;
- QColSpinBox *bEd;
- QColSpinBox *alphaEd;
- QLabel *alphaLab;
- QColorShowLabel *lab;
- bool rgbOriginal;
- QColorDialog *colorDialog;
-
- friend class QColorDialog;
- friend class QColorDialogPrivate;
-};
-
-class QColorShowLabel : public QFrame
-{
- Q_OBJECT
-
-public:
- QColorShowLabel(QWidget *parent) : QFrame(parent) {
- setFrameStyle(QFrame::Panel|QFrame::Sunken);
- setAcceptDrops(true);
- mousePressed = false;
- }
- void setColor(QColor c) { col = c; }
-
-signals:
- void colorDropped(QRgb);
-
-protected:
- void paintEvent(QPaintEvent *);
- void mousePressEvent(QMouseEvent *e);
- void mouseMoveEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QDragEnterEvent *e);
- void dragLeaveEvent(QDragLeaveEvent *e);
- void dropEvent(QDropEvent *e);
-#endif
-
-private:
- QColor col;
- bool mousePressed;
- QPoint pressPos;
-};
-
-void QColorShowLabel::paintEvent(QPaintEvent *e)
-{
- QPainter p(this);
- drawFrame(&p);
- p.fillRect(contentsRect()&e->rect(), col);
-}
-
-void QColorShower::showAlpha(bool b)
-{
- alphaLab->setVisible(b);
- alphaEd->setVisible(b);
-}
-
-inline bool QColorShower::isAlphaVisible() const
-{
- return alphaLab->isVisible();
-}
-
-void QColorShowLabel::mousePressEvent(QMouseEvent *e)
-{
- mousePressed = true;
- pressPos = e->pos();
-}
-
-void QColorShowLabel::mouseMoveEvent(QMouseEvent *e)
-{
-#ifdef QT_NO_DRAGANDDROP
- Q_UNUSED(e);
-#else
- if (!mousePressed)
- return;
- if ((pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance()) {
- QMimeData *mime = new QMimeData;
- mime->setColorData(col);
- QPixmap pix(30, 20);
- pix.fill(col);
- QPainter p(&pix);
- p.drawRect(0, 0, pix.width() - 1, pix.height() - 1);
- p.end();
- QDrag *drg = new QDrag(this);
- drg->setMimeData(mime);
- drg->setPixmap(pix);
- mousePressed = false;
- drg->start();
- }
-#endif
-}
-
-#ifndef QT_NO_DRAGANDDROP
-void QColorShowLabel::dragEnterEvent(QDragEnterEvent *e)
-{
- if (qvariant_cast<QColor>(e->mimeData()->colorData()).isValid())
- e->accept();
- else
- e->ignore();
-}
-
-void QColorShowLabel::dragLeaveEvent(QDragLeaveEvent *)
-{
-}
-
-void QColorShowLabel::dropEvent(QDropEvent *e)
-{
- QColor color = qvariant_cast<QColor>(e->mimeData()->colorData());
- if (color.isValid()) {
- col = color;
- repaint();
- emit colorDropped(col.rgb());
- e->accept();
- } else {
- e->ignore();
- }
-}
-#endif // QT_NO_DRAGANDDROP
-
-void QColorShowLabel::mouseReleaseEvent(QMouseEvent *)
-{
- if (!mousePressed)
- return;
- mousePressed = false;
-}
-
-QColorShower::QColorShower(QColorDialog *parent)
- : QWidget(parent)
-{
- colorDialog = parent;
-
- curCol = qRgb(255, 255, 255);
- curQColor = Qt::white;
-
- QGridLayout *gl = new QGridLayout(this);
- gl->setMargin(gl->spacing());
- lab = new QColorShowLabel(this);
-
-#ifdef QT_SMALL_COLORDIALOG
-# ifdef Q_WS_S60
- const bool nonTouchUI = !S60->hasTouchscreen;
-# elif defined Q_WS_MAEMO_5
- const bool nonTouchUI = false;
-# endif
-#endif
-
-#ifndef Q_WS_WINCE
-#ifdef QT_SMALL_COLORDIALOG
- lab->setMinimumHeight(60);
-#endif
- lab->setMinimumWidth(60);
-#else
- lab->setMinimumWidth(20);
-#endif
-
-// In S60, due to small screen and different screen layouts need to re-arrange the widgets.
-// For QVGA screens only the comboboxes and color label are visible.
-// For nHD screens only color and luminence pickers and color label are visible.
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lab, 0, 0, -1, 1);
-#else
- if (nonTouchUI)
- gl->addWidget(lab, 0, 0, 1, -1);
- else
- gl->addWidget(lab, 0, 0, -1, 1);
-#endif
- connect(lab, SIGNAL(colorDropped(QRgb)), this, SIGNAL(newCol(QRgb)));
- connect(lab, SIGNAL(colorDropped(QRgb)), this, SLOT(setRgb(QRgb)));
-
- hEd = new QColSpinBox(this);
- hEd->setRange(0, 359);
- lblHue = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- lblHue->setBuddy(hEd);
-#endif
- lblHue->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lblHue, 0, 1);
- gl->addWidget(hEd, 0, 2);
-#else
- if (nonTouchUI) {
- gl->addWidget(lblHue, 1, 0);
- gl->addWidget(hEd, 2, 0);
- } else {
- lblHue->hide();
- hEd->hide();
- }
-#endif
-
- sEd = new QColSpinBox(this);
- lblSat = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- lblSat->setBuddy(sEd);
-#endif
- lblSat->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lblSat, 1, 1);
- gl->addWidget(sEd, 1, 2);
-#else
- if (nonTouchUI) {
- gl->addWidget(lblSat, 1, 1);
- gl->addWidget(sEd, 2, 1);
- } else {
- lblSat->hide();
- sEd->hide();
- }
-#endif
-
- vEd = new QColSpinBox(this);
- lblVal = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- lblVal->setBuddy(vEd);
-#endif
- lblVal->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lblVal, 2, 1);
- gl->addWidget(vEd, 2, 2);
-#else
- if (nonTouchUI) {
- gl->addWidget(lblVal, 1, 2);
- gl->addWidget(vEd, 2, 2);
- } else {
- lblVal->hide();
- vEd->hide();
- }
-#endif
-
- rEd = new QColSpinBox(this);
- lblRed = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- lblRed->setBuddy(rEd);
-#endif
- lblRed->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lblRed, 0, 3);
- gl->addWidget(rEd, 0, 4);
-#else
- if (nonTouchUI) {
- gl->addWidget(lblRed, 3, 0);
- gl->addWidget(rEd, 4, 0);
- } else {
- lblRed->hide();
- rEd->hide();
- }
-#endif
-
- gEd = new QColSpinBox(this);
- lblGreen = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- lblGreen->setBuddy(gEd);
-#endif
- lblGreen->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lblGreen, 1, 3);
- gl->addWidget(gEd, 1, 4);
-#else
- if (nonTouchUI) {
- gl->addWidget(lblGreen, 3, 1);
- gl->addWidget(gEd, 4, 1);
- } else {
- lblGreen->hide();
- gEd->hide();
- }
-#endif
-
- bEd = new QColSpinBox(this);
- lblBlue = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- lblBlue->setBuddy(bEd);
-#endif
- lblBlue->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(lblBlue, 2, 3);
- gl->addWidget(bEd, 2, 4);
-#else
- if (nonTouchUI) {
- gl->addWidget(lblBlue, 3, 2);
- gl->addWidget(bEd, 4, 2);
- } else {
- lblBlue->hide();
- bEd->hide();
- }
-#endif
-
- alphaEd = new QColSpinBox(this);
- alphaLab = new QLabel(this);
-#ifndef QT_NO_SHORTCUT
- alphaLab->setBuddy(alphaEd);
-#endif
- alphaLab->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
-#if !defined(QT_SMALL_COLORDIALOG)
- gl->addWidget(alphaLab, 3, 1, 1, 3);
- gl->addWidget(alphaEd, 3, 4);
-#else
- if (nonTouchUI) {
- gl->addWidget(alphaLab, 1, 3, 3, 1);
- gl->addWidget(alphaEd, 4, 3);
- } else {
- alphaLab->hide();
- alphaEd->hide();
- }
-#endif
- alphaEd->hide();
- alphaLab->hide();
-
- connect(hEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
- connect(sEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
- connect(vEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
-
- connect(rEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(gEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(bEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
- connect(alphaEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
-
- retranslateStrings();
-}
-
-inline QRgb QColorDialogPrivate::currentColor() const { return cs->currentColor(); }
-inline int QColorDialogPrivate::currentAlpha() const { return cs->currentAlpha(); }
-inline void QColorDialogPrivate::setCurrentAlpha(int a) { cs->setCurrentAlpha(a); }
-inline void QColorDialogPrivate::showAlpha(bool b) { cs->showAlpha(b); }
-inline bool QColorDialogPrivate::isAlphaVisible() const { return cs->isAlphaVisible(); }
-
-QColor QColorDialogPrivate::currentQColor() const
-{
- return cs->currentQColor();
-}
-
-void QColorShower::showCurrentColor()
-{
- lab->setColor(currentColor());
- lab->repaint();
-}
-
-void QColorShower::rgbEd()
-{
- rgbOriginal = true;
- curCol = qRgba(rEd->value(), gEd->value(), bEd->value(), currentAlpha());
-
- rgb2hsv(currentColor(), hue, sat, val);
-
- hEd->setValue(hue);
- sEd->setValue(sat);
- vEd->setValue(val);
-
- showCurrentColor();
- emit newCol(currentColor());
- updateQColor();
-}
-
-void QColorShower::hsvEd()
-{
- rgbOriginal = false;
- hue = hEd->value();
- sat = sEd->value();
- val = vEd->value();
-
- QColor c;
- c.setHsv(hue, sat, val);
- curCol = c.rgb();
-
- rEd->setValue(qRed(currentColor()));
- gEd->setValue(qGreen(currentColor()));
- bEd->setValue(qBlue(currentColor()));
-
- showCurrentColor();
- emit newCol(currentColor());
- updateQColor();
-}
-
-void QColorShower::setRgb(QRgb rgb)
-{
- rgbOriginal = true;
- curCol = rgb;
-
- rgb2hsv(currentColor(), hue, sat, val);
-
- hEd->setValue(hue);
- sEd->setValue(sat);
- vEd->setValue(val);
-
- rEd->setValue(qRed(currentColor()));
- gEd->setValue(qGreen(currentColor()));
- bEd->setValue(qBlue(currentColor()));
-
- showCurrentColor();
- updateQColor();
-}
-
-void QColorShower::setHsv(int h, int s, int v)
-{
- if (h < -1 || (uint)s > 255 || (uint)v > 255)
- return;
-
- rgbOriginal = false;
- hue = h; val = v; sat = s;
- QColor c;
- c.setHsv(hue, sat, val);
- curCol = c.rgb();
-
- hEd->setValue(hue);
- sEd->setValue(sat);
- vEd->setValue(val);
-
- rEd->setValue(qRed(currentColor()));
- gEd->setValue(qGreen(currentColor()));
- bEd->setValue(qBlue(currentColor()));
-
- showCurrentColor();
- updateQColor();
-}
-
-void QColorShower::retranslateStrings()
-{
- lblHue->setText(QColorDialog::tr("Hu&e:"));
- lblSat->setText(QColorDialog::tr("&Sat:"));
- lblVal->setText(QColorDialog::tr("&Val:"));
- lblRed->setText(QColorDialog::tr("&Red:"));
- lblGreen->setText(QColorDialog::tr("&Green:"));
- lblBlue->setText(QColorDialog::tr("Bl&ue:"));
- alphaLab->setText(QColorDialog::tr("A&lpha channel:"));
-}
-
-void QColorShower::updateQColor()
-{
- QColor oldQColor(curQColor);
- curQColor.setRgba(qRgba(qRed(curCol), qGreen(curCol), qBlue(curCol), currentAlpha()));
- if (curQColor != oldQColor)
- emit currentColorChanged(curQColor);
-}
-
-//sets all widgets to display h,s,v
-void QColorDialogPrivate::_q_newHsv(int h, int s, int v)
-{
- cs->setHsv(h, s, v);
- cp->setCol(h, s);
- lp->setCol(h, s, v);
-}
-
-//sets all widgets to display rgb
-void QColorDialogPrivate::setCurrentColor(QRgb rgb)
-{
- cs->setRgb(rgb);
- _q_newColorTypedIn(rgb);
-}
-
-// hack; doesn't keep curCol in sync, so use with care
-void QColorDialogPrivate::setCurrentQColor(const QColor &color)
-{
- Q_Q(QColorDialog);
- if (cs->curQColor != color) {
- cs->curQColor = color;
- emit q->currentColorChanged(color);
- }
-}
-
-bool QColorDialogPrivate::selectColor(const QColor &col)
-{
- QRgb color = col.rgb();
- int i = 0, j = 0;
- // Check standard colors
- if (standard) {
- for (i = 0; i < 6; i++) {
- for (j = 0; j < 8; j++) {
- if (color == stdrgb[i + j*6]) {
- _q_newStandard(i, j);
- standard->setCurrent(i, j);
- standard->setSelected(i, j);
- standard->setFocus();
- return true;
- }
- }
- }
- }
- // Check custom colors
- if (custom) {
- for (i = 0; i < 2; i++) {
- for (j = 0; j < 8; j++) {
- if (color == cusrgb[i + j*2]) {
- _q_newCustom(i, j);
- custom->setCurrent(i, j);
- custom->setSelected(i, j);
- custom->setFocus();
- return true;
- }
- }
- }
- }
- return false;
-}
-
-//sets all widgets except cs to display rgb
-void QColorDialogPrivate::_q_newColorTypedIn(QRgb rgb)
-{
- int h, s, v;
- rgb2hsv(rgb, h, s, v);
- cp->setCol(h, s);
- lp->setCol(h, s, v);
-}
-
-void QColorDialogPrivate::_q_newCustom(int r, int c)
-{
- int i = r+2*c;
- setCurrentColor(cusrgb[i]);
- nextCust = i;
- if (standard)
- standard->setSelected(-1,-1);
-}
-
-void QColorDialogPrivate::_q_newStandard(int r, int c)
-{
- setCurrentColor(stdrgb[r+c*6]);
- if (custom)
- custom->setSelected(-1,-1);
-}
-
-void QColorDialogPrivate::init(const QColor &initial)
-{
- Q_Q(QColorDialog);
-
- q->setSizeGripEnabled(false);
- q->setWindowTitle(QColorDialog::tr("Select Color"));
-
- nativeDialogInUse = false;
-
- nextCust = 0;
- QVBoxLayout *mainLay = new QVBoxLayout(q);
- // there's nothing in this dialog that benefits from sizing up
- mainLay->setSizeConstraint(QLayout::SetFixedSize);
-
- QHBoxLayout *topLay = new QHBoxLayout();
- mainLay->addLayout(topLay);
-
- leftLay = 0;
-
-#if defined(Q_WS_WINCE) || defined(QT_SMALL_COLORDIALOG)
- smallDisplay = true;
- const int lumSpace = 20;
-#else
- // small displays (e.g. PDAs) cannot fit the full color dialog,
- // so just use the color picker.
- smallDisplay = (QApplication::desktop()->width() < 480 || QApplication::desktop()->height() < 350);
- const int lumSpace = topLay->spacing() / 2;
-#endif
-
- if (!smallDisplay) {
- leftLay = new QVBoxLayout;
- topLay->addLayout(leftLay);
- }
-
- initRGB();
-
-#ifndef QT_NO_SETTINGS
- if (!customSet) {
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- for (int i = 0; i < 2*8; ++i) {
- QVariant v = settings.value(QLatin1String("Qt/customColors/") + QString::number(i));
- if (v.isValid()) {
- QRgb rgb = v.toUInt();
- cusrgb[i] = rgb;
- }
- }
- }
-#endif
-
-#if defined(QT_SMALL_COLORDIALOG)
-# if defined(Q_WS_S60)
- const bool nonTouchUI = !S60->hasTouchscreen;
-# elif defined(Q_WS_MAEMO_5)
- const bool nonTouchUI = false;
-# endif
-#endif
-
- if (!smallDisplay) {
- standard = new QColorWell(q, 6, 8, stdrgb);
- lblBasicColors = new QLabel(q);
-#ifndef QT_NO_SHORTCUT
- lblBasicColors->setBuddy(standard);
-#endif
- q->connect(standard, SIGNAL(selected(int,int)), SLOT(_q_newStandard(int,int)));
- leftLay->addWidget(lblBasicColors);
- leftLay->addWidget(standard);
-
-#if !defined(Q_WS_WINCE)
- leftLay->addStretch();
-#endif
-
- custom = new QColorWell(q, 2, 8, cusrgb);
- custom->setAcceptDrops(true);
-
- q->connect(custom, SIGNAL(selected(int,int)), SLOT(_q_newCustom(int,int)));
- lblCustomColors = new QLabel(q);
-#ifndef QT_NO_SHORTCUT
- lblCustomColors->setBuddy(custom);
-#endif
- leftLay->addWidget(lblCustomColors);
- leftLay->addWidget(custom);
-
- addCusBt = new QPushButton(q);
- QObject::connect(addCusBt, SIGNAL(clicked()), q, SLOT(_q_addCustom()));
- leftLay->addWidget(addCusBt);
- } else {
- // better color picker size for small displays
-#if defined(QT_SMALL_COLORDIALOG)
- QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()).size();
- pWidth = pHeight = qMin(screenSize.width(), screenSize.height());
- pHeight -= 20;
- if(screenSize.height() > screenSize.width())
- pWidth -= 20;
-#else
- pWidth = 150;
- pHeight = 100;
-#endif
- custom = 0;
- standard = 0;
- }
-
- QVBoxLayout *rightLay = new QVBoxLayout;
- topLay->addLayout(rightLay);
-
- QHBoxLayout *pickLay = new QHBoxLayout;
- rightLay->addLayout(pickLay);
-
- QVBoxLayout *cLay = new QVBoxLayout;
- pickLay->addLayout(cLay);
- cp = new QColorPicker(q);
-
- cp->setFrameStyle(QFrame::Panel + QFrame::Sunken);
-
-#if defined(QT_SMALL_COLORDIALOG)
- if (!nonTouchUI) {
- pickLay->addWidget(cp);
- cLay->addSpacing(lumSpace);
- } else {
- cp->hide();
- }
-#else
- cLay->addSpacing(lumSpace);
- cLay->addWidget(cp);
-#endif
- cLay->addSpacing(lumSpace);
-
- lp = new QColorLuminancePicker(q);
-#if defined(QT_SMALL_COLORDIALOG)
- QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()).size();
- const int minDimension = qMin(screenSize.height(), screenSize.width());
- //set picker to be finger-usable
- int pickerWidth = !nonTouchUI ? minDimension/9 : minDimension/12;
- lp->setFixedWidth(pickerWidth);
- if (!nonTouchUI)
- pickLay->addWidget(lp);
- else
- lp->hide();
-#else
- lp->setFixedWidth(20);
- pickLay->addWidget(lp);
-#endif
-
- QObject::connect(cp, SIGNAL(newCol(int,int)), lp, SLOT(setCol(int,int)));
- QObject::connect(lp, SIGNAL(newHsv(int,int,int)), q, SLOT(_q_newHsv(int,int,int)));
-
- rightLay->addStretch();
-
- cs = new QColorShower(q);
- QObject::connect(cs, SIGNAL(newCol(QRgb)), q, SLOT(_q_newColorTypedIn(QRgb)));
- QObject::connect(cs, SIGNAL(currentColorChanged(QColor)),
- q, SIGNAL(currentColorChanged(QColor)));
-#if defined(QT_SMALL_COLORDIALOG)
- if (!nonTouchUI)
- pWidth -= cp->size().width();
- topLay->addWidget(cs);
-#else
- rightLay->addWidget(cs);
-#endif
-
- buttons = new QDialogButtonBox(q);
- mainLay->addWidget(buttons);
-
- ok = buttons->addButton(QDialogButtonBox::Ok);
- QObject::connect(ok, SIGNAL(clicked()), q, SLOT(accept()));
- ok->setDefault(true);
- cancel = buttons->addButton(QDialogButtonBox::Cancel);
- QObject::connect(cancel, SIGNAL(clicked()), q, SLOT(reject()));
-
- retranslateStrings();
-
-#ifdef Q_WS_MAC
- delegate = 0;
-#endif
-
- q->setCurrentColor(initial);
-}
-
-void QColorDialogPrivate::_q_addCustom()
-{
- cusrgb[nextCust] = cs->currentColor();
- if (custom)
- custom->update();
- nextCust = (nextCust+1) % 16;
-}
-
-void QColorDialogPrivate::retranslateStrings()
-{
- if (!smallDisplay) {
- lblBasicColors->setText(QColorDialog::tr("&Basic colors"));
- lblCustomColors->setText(QColorDialog::tr("&Custom colors"));
- addCusBt->setText(QColorDialog::tr("&Add to Custom Colors"));
- }
-
- cs->retranslateStrings();
-}
-
-static const Qt::WindowFlags DefaultWindowFlags =
- Qt::Dialog | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint
- | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
-
-/*!
- \class QColorDialog
- \brief The QColorDialog class provides a dialog widget for specifying colors.
-
- \ingroup standard-dialogs
-
- The color dialog's function is to allow users to choose colors.
- For example, you might use this in a drawing program to allow the
- user to set the brush color.
-
- The static functions provide modal color dialogs.
- \omit
- If you require a modeless dialog, use the QColorDialog constructor.
- \endomit
-
- The static getColor() function shows the dialog, and allows the user to
- specify a color. This function can also be used to let users choose a
- color with a level of transparency: pass the ShowAlphaChannel option as
- an additional argument.
-
- The user can store customCount() different custom colors. The
- custom colors are shared by all color dialogs, and remembered
- during the execution of the program. Use setCustomColor() to set
- the custom colors, and use customColor() to get them.
-
- Additional widgets that allow users to pick colors are available
- as \l{Qt Solutions}.
-
- The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
- how to use QColorDialog as well as other built-in Qt dialogs.
-
- \image plastique-colordialog.png A color dialog in the Plastique widget style.
-
- \sa QColor, QFileDialog, QPrintDialog, QFontDialog, {Standard Dialogs Example}
-*/
-
-/*!
- \since 4.5
-
- Constructs a color dialog with the given \a parent.
-*/
-QColorDialog::QColorDialog(QWidget *parent)
- : QDialog(*new QColorDialogPrivate, parent, DefaultWindowFlags)
-{
- Q_D(QColorDialog);
- d->init(Qt::white);
-}
-
-/*!
- \since 4.5
-
- Constructs a color dialog with the given \a parent and specified
- \a initial color.
-*/
-QColorDialog::QColorDialog(const QColor &initial, QWidget *parent)
- : QDialog(*new QColorDialogPrivate, parent, DefaultWindowFlags)
-{
- Q_D(QColorDialog);
- d->init(initial);
-}
-
-/*!
- \property QColorDialog::currentColor
- \brief the currently selected color in the dialog
-*/
-
-void QColorDialog::setCurrentColor(const QColor &color)
-{
- Q_D(QColorDialog);
- d->setCurrentColor(color.rgb());
- d->selectColor(color);
- d->setCurrentAlpha(color.alpha());
-
-#ifdef Q_WS_MAC
- d->setCurrentQColor(color);
- d->setCocoaPanelColor(color);
-#endif
- if (d->nativeDialogInUse)
- qt_guiPlatformPlugin()->colorDialogSetCurrentColor(this, color);
-}
-
-QColor QColorDialog::currentColor() const
-{
- Q_D(const QColorDialog);
- return d->currentQColor();
-}
-
-
-/*!
- Returns the color that the user selected by clicking the \gui{OK}
- or equivalent button.
-
- \note This color is not always the same as the color held by the
- \l currentColor property since the user can choose different colors
- before finally selecting the one to use.
-*/
-QColor QColorDialog::selectedColor() const
-{
- Q_D(const QColorDialog);
- return d->selectedQColor;
-}
-
-/*!
- Sets the given \a option to be enabled if \a on is true;
- otherwise, clears the given \a option.
-
- \sa options, testOption()
-*/
-void QColorDialog::setOption(ColorDialogOption option, bool on)
-{
- Q_D(QColorDialog);
- if (!(d->opts & option) != !on)
- setOptions(d->opts ^ option);
-}
-
-/*!
- \since 4.5
-
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QColorDialog::testOption(ColorDialogOption option) const
-{
- Q_D(const QColorDialog);
- return (d->opts & option) != 0;
-}
-
-/*!
- \property QColorDialog::options
- \brief the various options that affect the look and feel of the dialog
-
- By default, all options are disabled.
-
- Options should be set before showing the dialog. Setting them while the
- dialog is visible is not guaranteed to have an immediate effect on the
- dialog (depending on the option and on the platform).
-
- \sa setOption(), testOption()
-*/
-void QColorDialog::setOptions(ColorDialogOptions options)
-{
- Q_D(QColorDialog);
-
- ColorDialogOptions changed = (options ^ d->opts);
- if (!changed)
- return;
-
- d->opts = options;
- d->buttons->setVisible(!(options & NoButtons));
- d->showAlpha(options & ShowAlphaChannel);
-}
-
-QColorDialog::ColorDialogOptions QColorDialog::options() const
-{
- Q_D(const QColorDialog);
- return d->opts;
-}
-
-/*!
- \enum QColorDialog::ColorDialogOption
-
- \since 4.5
-
- This enum specifies various options that affect the look and feel
- of a color dialog.
-
- \value ShowAlphaChannel Allow the user to select the alpha component of a color.
- \value NoButtons Don't display \gui{OK} and \gui{Cancel} buttons. (Useful for "live dialogs".)
- \value DontUseNativeDialog Use Qt's standard color dialog on the Mac instead of Apple's
- native color panel.
-
- \sa options, setOption(), testOption(), windowModality()
-*/
-
-/*!
- \fn void QColorDialog::currentColorChanged(const QColor &color)
-
- This signal is emitted whenever the current color changes in the dialog.
- The current color is specified by \a color.
-
- \sa color, colorSelected()
-*/
-
-#ifdef Q_WS_MAC
-// can only have one Cocoa color panel active
-bool QColorDialogPrivate::sharedColorPanelAvailable = true;
-#endif
-
-/*!
- \fn void QColorDialog::colorSelected(const QColor &color);
-
- This signal is emitted just after the user has clicked \gui{OK} to
- select a color to use. The chosen color is specified by \a color.
-
- \sa color, currentColorChanged()
-*/
-
-/*!
- Changes the visibility of the dialog. If \a visible is true, the dialog
- is shown; otherwise, it is hidden.
-*/
-void QColorDialog::setVisible(bool visible)
-{
- Q_D(QColorDialog);
-
- if (visible){
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
- } else if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
-
- if (visible)
- d->selectedQColor = QColor();
-
-#if defined(Q_WS_MAC)
- if (visible) {
- if (d->delegate || (QColorDialogPrivate::sharedColorPanelAvailable &&
- !(testAttribute(Qt::WA_DontShowOnScreen) || (d->opts & DontUseNativeDialog)))){
- d->openCocoaColorPanel(currentColor(), parentWidget(), windowTitle(), options());
- QColorDialogPrivate::sharedColorPanelAvailable = false;
- setAttribute(Qt::WA_DontShowOnScreen);
- }
- setWindowFlags(windowModality() == Qt::WindowModal ? Qt::Sheet : DefaultWindowFlags);
- } else {
- if (d->delegate) {
- d->closeCocoaColorPanel();
- setAttribute(Qt::WA_DontShowOnScreen, false);
- }
- }
-#else
-
- if (!(d->opts & DontUseNativeDialog) && qt_guiPlatformPlugin()->colorDialogSetVisible(this, visible)) {
- d->nativeDialogInUse = true;
- // Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
- // updates the state correctly, but skips showing the non-native version:
- setAttribute(Qt::WA_DontShowOnScreen);
- } else {
- d->nativeDialogInUse = false;
- setAttribute(Qt::WA_DontShowOnScreen, false);
- }
-#endif
-
- QDialog::setVisible(visible);
-}
-
-/*!
- \overload
- \since 4.5
-
- Opens the dialog and connects its colorSelected() signal to the slot specified
- by \a receiver and \a member.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QColorDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QColorDialog);
- connect(this, SIGNAL(colorSelected(QColor)), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-/*!
- \fn QColorDialog::open()
-
- \since 4.5
- Shows the dialog as a \l{QDialog#Modal Dialogs}{window modal dialog},
- returning immediately.
-
- \sa QDialog::open()
-*/
-
-/*
- For Symbian color dialogs
-*/
-#ifdef Q_WS_S60
-extern QColor qtSymbianGetColor(const QColor &initial);
-#endif
-/*!
- \since 4.5
-
- Pops up a modal color dialog with the given window \a title (or "Select Color" if none is
- specified), lets the user choose a color, and returns that color. The color is initially set
- to \a initial. The dialog is a child of \a parent. It returns an invalid (see
- QColor::isValid()) color if the user cancels the dialog.
-
- The \a options argument allows you to customize the dialog.
-
- On Symbian, this static function will use the native color dialog and not a QColorDialog.
- On Symbian the parameters \a title and \a parent has no relevance and the
- \a options parameter is only used to define if the native color dialog is
- used or not.
-*/
-QColor QColorDialog::getColor(const QColor &initial, QWidget *parent, const QString &title,
- ColorDialogOptions options)
-{
-#ifdef Q_WS_S60
- if (!(options & DontUseNativeDialog))
- return qtSymbianGetColor(initial);
-#endif
- QColorDialog dlg(parent);
- if (!title.isEmpty())
- dlg.setWindowTitle(title);
- dlg.setOptions(options);
- dlg.setCurrentColor(initial);
- dlg.exec();
- return dlg.selectedColor();
-}
-
-/*!
- Pops up a modal color dialog, lets the user choose a color, and
- returns that color. The color is initially set to \a initial. The
- dialog is a child of \a parent. It returns an invalid (see
- QColor::isValid()) color if the user cancels the dialog.
-
- On Symbian, this static function will use the native
- color dialog and not a QColorDialog.
-*/
-
-QColor QColorDialog::getColor(const QColor &initial, QWidget *parent)
-{
-#ifdef Q_WS_S60
- return qtSymbianGetColor(initial);
-#endif
- return getColor(initial, parent, QString(), ColorDialogOptions(0));
-}
-
-
-/*!
- \obsolete
-
- Pops up a modal color dialog to allow the user to choose a color
- and an alpha channel (transparency) value. The color+alpha is
- initially set to \a initial. The dialog is a child of \a parent.
-
- If \a ok is non-null, \e *\a ok is set to true if the user clicked
- \gui{OK}, and to false if the user clicked Cancel.
-
- If the user clicks Cancel, the \a initial value is returned.
-
- Use QColorDialog::getColor() instead, passing the
- QColorDialog::ShowAlphaChannel option.
-*/
-
-QRgb QColorDialog::getRgba(QRgb initial, bool *ok, QWidget *parent)
-{
- QColor color(getColor(QColor(initial), parent, QString(), ShowAlphaChannel));
- QRgb result = color.isValid() ? color.rgba() : initial;
- if (ok)
- *ok = color.isValid();
- return result;
-}
-
-/*!
- Destroys the color dialog.
-*/
-
-QColorDialog::~QColorDialog()
-{
- Q_D(QColorDialog);
-#if defined(Q_WS_MAC)
- if (d->delegate) {
- d->releaseCocoaColorPanelDelegate();
- QColorDialogPrivate::sharedColorPanelAvailable = true;
- }
-#endif
-
-#ifndef QT_NO_SETTINGS
- if (!customSet) {
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- for (int i = 0; i < 2*8; ++i)
- settings.setValue(QLatin1String("Qt/customColors/") + QString::number(i), cusrgb[i]);
- }
-#endif
- if (d->nativeDialogInUse)
- qt_guiPlatformPlugin()->colorDialogDelete(this);
-
-}
-
-
-/*!
- \reimp
-*/
-void QColorDialog::changeEvent(QEvent *e)
-{
- Q_D(QColorDialog);
- if (e->type() == QEvent::LanguageChange)
- d->retranslateStrings();
- QDialog::changeEvent(e);
-}
-
-/*!
- Closes the dialog and sets its result code to \a result. If this dialog
- is shown with exec(), done() causes the local event loop to finish,
- and exec() to return \a result.
-
- \sa QDialog::done()
-*/
-void QColorDialog::done(int result)
-{
- Q_D(QColorDialog);
- QDialog::done(result);
- if (result == Accepted) {
- d->selectedQColor = d->currentQColor();
- emit colorSelected(d->selectedQColor);
- } else {
- d->selectedQColor = QColor();
- }
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, SIGNAL(colorSelected(QColor)),
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
-}
-
-QT_END_NAMESPACE
-
-#include "qcolordialog.moc"
-#include "moc_qcolordialog.cpp"
-
-#endif // QT_NO_COLORDIALOG
-
-/*!
- \fn QColor QColorDialog::getColor(const QColor &init, QWidget *parent, const char *name)
- \compat
-*/
-
-/*!
- \fn QRgb QColorDialog::getRgba(QRgb rgba, bool *ok, QWidget *parent, const char *name)
- \compat
-*/
diff --git a/src/gui/dialogs/qcolordialog.h b/src/gui/dialogs/qcolordialog.h
deleted file mode 100644
index 80a893d568..0000000000
--- a/src/gui/dialogs/qcolordialog.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOLORDIALOG_H
-#define QCOLORDIALOG_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_COLORDIALOG
-
-class QColorDialogPrivate;
-
-class Q_GUI_EXPORT QColorDialog : public QDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QColorDialog)
- Q_ENUMS(ColorDialogOption)
- Q_PROPERTY(QColor currentColor READ currentColor WRITE setCurrentColor
- NOTIFY currentColorChanged)
- Q_PROPERTY(ColorDialogOptions options READ options WRITE setOptions)
-
-public:
- enum ColorDialogOption {
- ShowAlphaChannel = 0x00000001,
- NoButtons = 0x00000002,
- DontUseNativeDialog = 0x00000004
- };
-
- Q_DECLARE_FLAGS(ColorDialogOptions, ColorDialogOption)
-
- explicit QColorDialog(QWidget *parent = 0);
- explicit QColorDialog(const QColor &initial, QWidget *parent = 0);
- ~QColorDialog();
-
- void setCurrentColor(const QColor &color);
- QColor currentColor() const;
-
- QColor selectedColor() const;
-
- void setOption(ColorDialogOption option, bool on = true);
- bool testOption(ColorDialogOption option) const;
- void setOptions(ColorDialogOptions options);
- ColorDialogOptions options() const;
-
-#ifdef Q_NO_USING_KEYWORD
- void open() { QDialog::open(); }
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
- void setVisible(bool visible);
-
- // ### Qt 5: merge overloads with title = QString()
- static QColor getColor(const QColor &initial, QWidget *parent, const QString &title,
- ColorDialogOptions options = 0);
- static QColor getColor(const QColor &initial = Qt::white, QWidget *parent = 0);
-
- // obsolete
- static QRgb getRgba(QRgb rgba = 0xffffffff, bool *ok = 0, QWidget *parent = 0);
-
- // ### Qt 5: use QColor in signatures
- static int customCount();
- static QRgb customColor(int index);
- static void setCustomColor(int index, QRgb color);
- static void setStandardColor(int index, QRgb color);
-
-#ifdef QT3_SUPPORT
- static QColor getColor(const QColor &init, QWidget *parent, const char *name)
- { Q_UNUSED(name); return getColor(init, parent); }
- static QRgb getRgba(QRgb rgba, bool *ok, QWidget *parent, const char *name)
- { Q_UNUSED(name); return getRgba(rgba, ok, parent); }
-#endif
-
-Q_SIGNALS:
- void currentColorChanged(const QColor &color);
- void colorSelected(const QColor &color);
-
-protected:
- void changeEvent(QEvent *event);
- void done(int result);
-
-private:
- Q_DISABLE_COPY(QColorDialog)
-
- Q_PRIVATE_SLOT(d_func(), void _q_addCustom())
- Q_PRIVATE_SLOT(d_func(), void _q_newHsv(int h, int s, int v))
- Q_PRIVATE_SLOT(d_func(), void _q_newColorTypedIn(QRgb rgb))
- Q_PRIVATE_SLOT(d_func(), void _q_newCustom(int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_newStandard(int, int))
-#if defined(Q_WS_MAC)
- Q_PRIVATE_SLOT(d_func(), void _q_macRunNativeAppModalPanel())
-#endif
-
- friend class QColorShower;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QColorDialog::ColorDialogOptions)
-
-#endif // QT_NO_COLORDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOLORDIALOG_H
diff --git a/src/gui/dialogs/qcolordialog_mac.mm b/src/gui/dialogs/qcolordialog_mac.mm
deleted file mode 100644
index ee9b19ad99..0000000000
--- a/src/gui/dialogs/qcolordialog_mac.mm
+++ /dev/null
@@ -1,500 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolordialog_p.h"
-#if !defined(QT_NO_COLORDIALOG) && defined(Q_WS_MAC)
-#include <qapplication.h>
-#include <qtimer.h>
-#include <qdialogbuttonbox.h>
-#include <qabstracteventdispatcher.h>
-#include <private/qapplication_p.h>
-#include <private/qt_mac_p.h>
-#include <qdebug.h>
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-
-#if !CGFLOAT_DEFINED
-typedef float CGFloat; // Should only not be defined on 32-bit platforms
-#endif
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-@protocol NSWindowDelegate <NSObject>
-- (void)windowDidResize:(NSNotification *)notification;
-- (BOOL)windowShouldClose:(id)window;
-@end
-#endif
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) : NSObject<NSWindowDelegate> {
- NSColorPanel *mColorPanel;
- NSView *mStolenContentView;
- NSButton *mOkButton;
- NSButton *mCancelButton;
- QColorDialogPrivate *mPriv;
- QColor *mQtColor;
- CGFloat mMinWidth; // currently unused
- CGFloat mExtraHeight; // currently unused
- BOOL mHackedPanel;
- NSInteger mResultCode;
- BOOL mDialogIsExecuting;
- BOOL mResultSet;
-}
-- (id)initWithColorPanel:(NSColorPanel *)panel
- stolenContentView:(NSView *)stolenContentView
- okButton:(NSButton *)okButton
- cancelButton:(NSButton *)cancelButton
- priv:(QColorDialogPrivate *)priv;
-- (void)colorChanged:(NSNotification *)notification;
-- (void)relayout;
-- (void)onOkClicked;
-- (void)onCancelClicked;
-- (void)updateQtColor;
-- (NSColorPanel *)colorPanel;
-- (QColor)qtColor;
-- (void)finishOffWithCode:(NSInteger)result;
-- (void)showColorPanel;
-- (void)exec;
-- (void)setResultSet:(BOOL)result;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate)
-- (id)initWithColorPanel:(NSColorPanel *)panel
- stolenContentView:(NSView *)stolenContentView
- okButton:(NSButton *)okButton
- cancelButton:(NSButton *)cancelButton
- priv:(QColorDialogPrivate *)priv
-{
- self = [super init];
-
- mColorPanel = panel;
- mStolenContentView = stolenContentView;
- mOkButton = okButton;
- mCancelButton = cancelButton;
- mPriv = priv;
- mMinWidth = 0.0;
- mExtraHeight = 0.0;
- mHackedPanel = (okButton != 0);
- mResultCode = NSCancelButton;
- mDialogIsExecuting = false;
- mResultSet = false;
-
- if (mHackedPanel) {
- [self relayout];
-
- [okButton setAction:@selector(onOkClicked)];
- [okButton setTarget:self];
-
- [cancelButton setAction:@selector(onCancelClicked)];
- [cancelButton setTarget:self];
- }
-
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(colorChanged:)
- name:NSColorPanelColorDidChangeNotification
- object:mColorPanel];
-
- mQtColor = new QColor();
- return self;
-}
-
-- (void)dealloc
-{
- QMacCocoaAutoReleasePool pool;
- if (mHackedPanel) {
- NSView *ourContentView = [mColorPanel contentView];
-
- // return stolen stuff to its rightful owner
- [mStolenContentView removeFromSuperview];
- [mColorPanel setContentView:mStolenContentView];
-
- [mOkButton release];
- [mCancelButton release];
- [ourContentView release];
- }
- [mColorPanel setDelegate:nil];
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- delete mQtColor;
- [super dealloc];
-}
-
-- (void)setResultSet:(BOOL)result
-{
- mResultSet = result;
-}
-
-- (BOOL)windowShouldClose:(id)window
-{
- Q_UNUSED(window);
- if (!mHackedPanel)
- [self updateQtColor];
- if (mDialogIsExecuting) {
- [self finishOffWithCode:NSCancelButton];
- } else {
- mResultSet = true;
- mPriv->colorDialog()->reject();
- }
- return true;
-}
-
-- (void)windowDidResize:(NSNotification *)notification
-{
- Q_UNUSED(notification);
- if (mHackedPanel)
- [self relayout];
-}
-
-- (void)colorChanged:(NSNotification *)notification
-{
- Q_UNUSED(notification);
- [self updateQtColor];
-}
-
-- (void)relayout
-{
- Q_ASSERT(mHackedPanel);
-
- NSRect rect = [[mStolenContentView superview] frame];
-
- // should a priori be kept in sync with qfontdialog_mac.mm
- const CGFloat ButtonMinWidth = 78.0; // 84.0 for Carbon
- const CGFloat ButtonMinHeight = 32.0;
- const CGFloat ButtonSpacing = 0.0;
- const CGFloat ButtonTopMargin = 0.0;
- const CGFloat ButtonBottomMargin = 7.0;
- const CGFloat ButtonSideMargin = 9.0;
-
- [mOkButton sizeToFit];
- NSSize okSizeHint = [mOkButton frame].size;
-
- [mCancelButton sizeToFit];
- NSSize cancelSizeHint = [mCancelButton frame].size;
-
- const CGFloat ButtonWidth = qMin(qMax(ButtonMinWidth,
- qMax(okSizeHint.width, cancelSizeHint.width)),
- CGFloat((rect.size.width - 2.0 * ButtonSideMargin - ButtonSpacing) * 0.5));
- const CGFloat ButtonHeight = qMax(ButtonMinHeight,
- qMax(okSizeHint.height, cancelSizeHint.height));
-
- NSRect okRect = { { rect.size.width - ButtonSideMargin - ButtonWidth,
- ButtonBottomMargin },
- { ButtonWidth, ButtonHeight } };
- [mOkButton setFrame:okRect];
- [mOkButton setNeedsDisplay:YES];
-
- NSRect cancelRect = { { okRect.origin.x - ButtonSpacing - ButtonWidth,
- ButtonBottomMargin },
- { ButtonWidth, ButtonHeight } };
- [mCancelButton setFrame:cancelRect];
- [mCancelButton setNeedsDisplay:YES];
-
- const CGFloat Y = ButtonBottomMargin + ButtonHeight + ButtonTopMargin;
- NSRect stolenCVRect = { { 0.0, Y },
- { rect.size.width, rect.size.height - Y } };
- [mStolenContentView setFrame:stolenCVRect];
- [mStolenContentView setNeedsDisplay:YES];
-
- [[mStolenContentView superview] setNeedsDisplay:YES];
- mMinWidth = 2 * ButtonSideMargin + ButtonSpacing + 2 * ButtonWidth;
- mExtraHeight = Y;
-}
-
-- (void)onOkClicked
-{
- Q_ASSERT(mHackedPanel);
- [[mStolenContentView window] close];
- [self updateQtColor];
- [self finishOffWithCode:NSOKButton];
-}
-
-- (void)onCancelClicked
-{
- if (mHackedPanel) {
- [[mStolenContentView window] close];
- delete mQtColor;
- mQtColor = new QColor();
- [self finishOffWithCode:NSCancelButton];
- }
-}
-
-- (void)updateQtColor
-{
- delete mQtColor;
- mQtColor = new QColor();
- NSColor *color = [mColorPanel color];
- NSString *colorSpaceName = [color colorSpaceName];
- if (colorSpaceName == NSDeviceCMYKColorSpace) {
- CGFloat cyan = 0, magenta = 0, yellow = 0, black = 0, alpha = 0;
- [color getCyan:&cyan magenta:&magenta yellow:&yellow black:&black alpha:&alpha];
- mQtColor->setCmykF(cyan, magenta, yellow, black, alpha);
- } else if (colorSpaceName == NSCalibratedRGBColorSpace || colorSpaceName == NSDeviceRGBColorSpace) {
- CGFloat red = 0, green = 0, blue = 0, alpha = 0;
- [color getRed:&red green:&green blue:&blue alpha:&alpha];
- mQtColor->setRgbF(red, green, blue, alpha);
- } else if (colorSpaceName == NSNamedColorSpace) {
- NSColor *tmpColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
- CGFloat red = 0, green = 0, blue = 0, alpha = 0;
- [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
- mQtColor->setRgbF(red, green, blue, alpha);
- } else {
- NSColorSpace *colorSpace = [color colorSpace];
- if ([colorSpace colorSpaceModel] == NSCMYKColorSpaceModel && [color numberOfComponents] == 5){
- CGFloat components[5];
- [color getComponents:components];
- mQtColor->setCmykF(components[0], components[1], components[2], components[3], components[4]);
- } else {
- NSColor *tmpColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
- CGFloat red = 0, green = 0, blue = 0, alpha = 0;
- [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
- mQtColor->setRgbF(red, green, blue, alpha);
- }
- }
-
- mPriv->setCurrentQColor(*mQtColor);
-}
-
-- (NSColorPanel *)colorPanel
-{
- return mColorPanel;
-}
-
-- (QColor)qtColor
-{
- return *mQtColor;
-}
-
-- (void)finishOffWithCode:(NSInteger)code
-{
- mResultCode = code;
- if (mDialogIsExecuting) {
- // We stop the current modal event loop. The control
- // will then return inside -(void)exec below.
- // It's important that the modal event loop is stopped before
- // we accept/reject QColorDialog, since QColorDialog has its
- // own event loop that needs to be stopped last.
- [NSApp stopModalWithCode:code];
- } else {
- // Since we are not in a modal event loop, we can safely close
- // down QColorDialog
- // Calling accept() or reject() can in turn call closeCocoaColorPanel.
- // This check will prevent any such recursion.
- if (!mResultSet) {
- mResultSet = true;
- if (mResultCode == NSCancelButton) {
- mPriv->colorDialog()->reject();
- } else {
- mPriv->colorDialog()->accept();
- }
- }
- }
-}
-
-- (void)showColorPanel
-{
- mDialogIsExecuting = false;
- [mColorPanel makeKeyAndOrderFront:mColorPanel];
-}
-
-- (void)exec
-{
- QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active);
- QMacCocoaAutoReleasePool pool;
- mDialogIsExecuting = true;
- bool modalEnded = false;
- while (!modalEnded) {
- @try {
- [NSApp runModalForWindow:mColorPanel];
- modalEnded = true;
- } @catch (NSException *) {
- // For some reason, NSColorPanel throws an exception when
- // clicking on 'SelectedMenuItemColor' from the 'Developer'
- // palette (tab three).
- }
- }
-
- QAbstractEventDispatcher::instance()->interrupt();
- if (mResultCode == NSCancelButton)
- mPriv->colorDialog()->reject();
- else
- mPriv->colorDialog()->accept();
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptNSPanelCtor();
-extern void macStopInterceptNSPanelCtor();
-extern NSButton *macCreateButton(const char *text, NSView *superview);
-
-void QColorDialogPrivate::openCocoaColorPanel(const QColor &initial,
- QWidget *parent, const QString &title, QColorDialog::ColorDialogOptions options)
-{
- Q_UNUSED(parent); // we would use the parent if only NSColorPanel could be a sheet
- QMacCocoaAutoReleasePool pool;
-
- if (!delegate) {
- /*
- The standard Cocoa color panel has no OK or Cancel button and
- is created as a utility window, whereas we want something like
- the Carbon color panel. We need to take the following steps:
-
- 1. Intercept the color panel constructor to turn off the
- NSUtilityWindowMask flag. This is done by temporarily
- replacing initWithContentRect:styleMask:backing:defer:
- in NSPanel by our own method.
-
- 2. Modify the color panel so that its content view is part
- of a new content view that contains it as well as two
- buttons (OK and Cancel).
-
- 3. Lay out the original content view and the buttons when
- the color panel is shown and whenever it is resized.
-
- 4. Clean up after ourselves.
- */
-
- bool hackColorPanel = !(options & QColorDialog::NoButtons);
-
- if (hackColorPanel)
- macStartInterceptNSPanelCtor();
- NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel];
- if (hackColorPanel)
- macStopInterceptNSPanelCtor();
-
- [colorPanel setHidesOnDeactivate:false];
-
- // set up the Cocoa color panel
- [colorPanel setShowsAlpha:options & QColorDialog::ShowAlphaChannel];
- [colorPanel setTitle:(NSString*)(CFStringRef)QCFString(title)];
-
- NSView *stolenContentView = 0;
- NSButton *okButton = 0;
- NSButton *cancelButton = 0;
-
- if (hackColorPanel) {
- // steal the color panel's contents view
- stolenContentView = [colorPanel contentView];
- [stolenContentView retain];
- [colorPanel setContentView:0];
-
- // create a new content view and add the stolen one as a subview
- NSRect frameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } };
- NSView *ourContentView = [[NSView alloc] initWithFrame:frameRect];
- [ourContentView addSubview:stolenContentView];
-
- // create OK and Cancel buttons and add these as subviews
- okButton = macCreateButton("&OK", ourContentView);
- cancelButton = macCreateButton("Cancel", ourContentView);
-
- [colorPanel setContentView:ourContentView];
- [colorPanel setDefaultButtonCell:[okButton cell]];
- }
-
- delegate = [[QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) alloc] initWithColorPanel:colorPanel
- stolenContentView:stolenContentView
- okButton:okButton
- cancelButton:cancelButton
- priv:this];
- [colorPanel setDelegate:static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate)];
- }
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) setResultSet:NO];
- setCocoaPanelColor(initial);
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) showColorPanel];
-}
-
-void QColorDialogPrivate::closeCocoaColorPanel()
-{
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) onCancelClicked];
-}
-
-void QColorDialogPrivate::releaseCocoaColorPanelDelegate()
-{
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) release];
-}
-
-void QColorDialogPrivate::mac_nativeDialogModalHelp()
-{
- // Do a queued meta-call to open the native modal dialog so it opens after the new
- // event loop has started to execute (in QDialog::exec). Using a timer rather than
- // a queued meta call is intentional to ensure that the call is only delivered when
- // [NSApp run] runs (timers are handeled special in cocoa). If NSApp is not
- // running (which is the case if e.g a top-most QEventLoop has been
- // interrupted, and the second-most event loop has not yet been reactivated (regardless
- // if [NSApp run] is still on the stack)), showing a native modal dialog will fail.
- if (delegate){
- Q_Q(QColorDialog);
- QTimer::singleShot(1, q, SLOT(_q_macRunNativeAppModalPanel()));
- }
-}
-
-void QColorDialogPrivate::_q_macRunNativeAppModalPanel()
-{
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) exec];
-}
-
-void QColorDialogPrivate::setCocoaPanelColor(const QColor &color)
-{
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *theDelegate = static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate);
- NSColor *nsColor;
- const QColor::Spec spec = color.spec();
- if (spec == QColor::Cmyk) {
- nsColor = [NSColor colorWithDeviceCyan:color.cyanF()
- magenta:color.magentaF()
- yellow:color.yellowF()
- black:color.blackF()
- alpha:color.alphaF()];
- } else {
- nsColor = [NSColor colorWithCalibratedRed:color.redF()
- green:color.greenF()
- blue:color.blueF()
- alpha:color.alphaF()];
- }
- [[theDelegate colorPanel] setColor:nsColor];
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qcolordialog_p.h b/src/gui/dialogs/qcolordialog_p.h
deleted file mode 100644
index 243e7277c5..0000000000
--- a/src/gui/dialogs/qcolordialog_p.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOLORDIALOG_P_H
-#define QCOLORDIALOG_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// to version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include "private/qdialog_p.h"
-#include "qcolordialog.h"
-
-#ifndef QT_NO_COLORDIALOG
-
-QT_BEGIN_NAMESPACE
-
-class QColorLuminancePicker;
-class QColorPicker;
-class QColorShower;
-class QDialogButtonBox;
-class QLabel;
-class QVBoxLayout;
-class QPushButton;
-class QWellArray;
-
-class QColorDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QColorDialog)
-
-public:
- void init(const QColor &initial);
- QRgb currentColor() const;
- QColor currentQColor() const;
- void setCurrentColor(QRgb rgb);
- void setCurrentQColor(const QColor &color);
- bool selectColor(const QColor &color);
-
- int currentAlpha() const;
- void setCurrentAlpha(int a);
- void showAlpha(bool b);
- bool isAlphaVisible() const;
- void retranslateStrings();
-
- void _q_addCustom();
-
- void _q_newHsv(int h, int s, int v);
- void _q_newColorTypedIn(QRgb rgb);
- void _q_newCustom(int, int);
- void _q_newStandard(int, int);
-
- QWellArray *custom;
- QWellArray *standard;
-
- QDialogButtonBox *buttons;
- QVBoxLayout *leftLay;
- QColorPicker *cp;
- QColorLuminancePicker *lp;
- QColorShower *cs;
- QLabel *lblBasicColors;
- QLabel *lblCustomColors;
- QPushButton *ok;
- QPushButton *cancel;
- QPushButton *addCusBt;
- QColor selectedQColor;
- int nextCust;
- bool smallDisplay;
- QColorDialog::ColorDialogOptions opts;
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
- bool nativeDialogInUse;
-
-#ifdef Q_WS_MAC
- void openCocoaColorPanel(const QColor &initial,
- QWidget *parent, const QString &title, QColorDialog::ColorDialogOptions options);
- void closeCocoaColorPanel();
- void releaseCocoaColorPanelDelegate();
- void setCocoaPanelColor(const QColor &color);
-
- inline void done(int result) { q_func()->done(result); }
- inline QColorDialog *colorDialog() { return q_func(); }
-
- void *delegate;
-
- static bool sharedColorPanelAvailable;
-
- void _q_macRunNativeAppModalPanel();
- void mac_nativeDialogModalHelp();
-#endif
-};
-
-#endif // QT_NO_COLORDIALOG
-
-QT_END_NAMESPACE
-
-#endif // QCOLORDIALOG_P_H
diff --git a/src/gui/dialogs/qcolordialog_symbian.cpp b/src/gui/dialogs/qcolordialog_symbian.cpp
deleted file mode 100644
index 3dbb5c11a9..0000000000
--- a/src/gui/dialogs/qcolordialog_symbian.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolordialog_p.h"
-
-#ifndef QT_NO_COLORDIALOG
-
-
-#include "qcolor.h"
-#include "private/qguiplatformplugin_p.h"
-
-#ifdef Q_WS_S60
-#include <AknColourSelectionGrid.h>
-#endif
-
-#include "private/qt_s60_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QColor launchSymbianColorDialog(QColor initial)
-{
- QColor currentColor = QColor::Invalid;
-#ifdef Q_WS_S60
- QT_TRAP_THROWING(
- CArrayFixFlat<TRgb>* array = new( ELeave ) CArrayFixFlat<TRgb>(17);
- CleanupStack::PushL(array);
- array->AppendL(KRgbBlack);
- array->AppendL(KRgbDarkGray);
- array->AppendL(KRgbDarkRed);
- array->AppendL(KRgbDarkGreen);
- array->AppendL(KRgbDarkYellow);
- array->AppendL(KRgbDarkBlue);
- array->AppendL(KRgbDarkMagenta);
- array->AppendL(KRgbDarkCyan);
- array->AppendL(KRgbRed);
- array->AppendL(KRgbGreen);
- array->AppendL(KRgbYellow);
- array->AppendL(KRgbBlue);
- array->AppendL(KRgbMagenta);
- array->AppendL(KRgbCyan);
- array->AppendL(KRgbGray);
- array->AppendL(KRgbWhite);
-
- TRgb initialColour(initial.red(), initial.green(), initial.blue(), initial.alpha());
-
- TBool noneChosen = EFalse; // If true shows the default colour button
- CAknColourSelectionGrid* colourSelectionGrid =
- CAknColourSelectionGrid::NewL(array, EFalse, noneChosen, initialColour);
- CleanupStack::PushL(colourSelectionGrid);
-
- if (colourSelectionGrid->ExecuteLD()) {
- currentColor.setRgb(initialColour.Red(), initialColour.Green(),
- initialColour.Blue(), initialColour.Alpha());
- }
- CleanupStack::Pop(colourSelectionGrid);
- CleanupStack::PopAndDestroy(array);
- );
-#endif
- return currentColor;
-}
-
-QColor qtSymbianGetColor(const QColor &initial)
-{
- return launchSymbianColorDialog(initial);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_COLORDIALOG
diff --git a/src/gui/dialogs/qdialog.cpp b/src/gui/dialogs/qdialog.cpp
deleted file mode 100644
index 6838d927a8..0000000000
--- a/src/gui/dialogs/qdialog.cpp
+++ /dev/null
@@ -1,1272 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdialog.h"
-
-
-#include "qevent.h"
-#include "qdesktopwidget.h"
-#include "qpushbutton.h"
-#include "qapplication.h"
-#include "qlayout.h"
-#include "qsizegrip.h"
-#include "qwhatsthis.h"
-#include "qmenu.h"
-#include "qcursor.h"
-#include "private/qdialog_p.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#if defined(Q_WS_WINCE)
-#include "qt_windows.h"
-#include "qmenubar.h"
-#include "qpointer.h"
-#include "qguifunctions_wince.h"
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wce.cpp
-extern bool qt_wince_is_smartphone(); //is defined in qguifunctions_wce.cpp
-#elif defined(Q_WS_X11)
-# include "../kernel/qt_x11_p.h"
-#elif defined(Q_OS_SYMBIAN)
-# include "qfiledialog.h"
-# include "qfontdialog.h"
-# include "qwizard.h"
-# include "private/qt_s60_p.h"
-#endif
-
-#if defined(Q_WS_S60)
-#include <AknUtils.h> // AknLayoutUtils
-#endif
-
-#ifndef SPI_GETSNAPTODEFBUTTON
-# define SPI_GETSNAPTODEFBUTTON 95
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QDialog
- \brief The QDialog class is the base class of dialog windows.
-
- \ingroup dialog-classes
- \ingroup abstractwidgets
-
-
- A dialog window is a top-level window mostly used for short-term
- tasks and brief communications with the user. QDialogs may be
- modal or modeless. QDialogs can
- provide a \link #return return
- value\endlink, and they can have \link #default default
- buttons\endlink. QDialogs can also have a QSizeGrip in their
- lower-right corner, using setSizeGripEnabled().
-
- Note that QDialog (an any other widget that has type Qt::Dialog) uses
- the parent widget slightly differently from other classes in Qt. A
- dialog is always a top-level widget, but if it has a parent, its
- default location is centered on top of the parent's top-level widget
- (if it is not top-level itself). It will also share the parent's
- taskbar entry.
-
- Use the overload of the QWidget::setParent() function to change
- the ownership of a QDialog widget. This function allows you to
- explicitly set the window flags of the reparented widget; using
- the overloaded function will clear the window flags specifying the
- window-system properties for the widget (in particular it will
- reset the Qt::Dialog flag).
-
- \section1 Modal Dialogs
-
- A \bold{modal} dialog is a dialog that blocks input to other
- visible windows in the same application. Dialogs that are used to
- request a file name from the user or that are used to set
- application preferences are usually modal. Dialogs can be
- \l{Qt::ApplicationModal}{application modal} (the default) or
- \l{Qt::WindowModal}{window modal}.
-
- When an application modal dialog is opened, the user must finish
- interacting with the dialog and close it before they can access
- any other window in the application. Window modal dialogs only
- block access to the window associated with the dialog, allowing
- the user to continue to use other windows in an application.
-
- The most common way to display a modal dialog is to call its
- exec() function. When the user closes the dialog, exec() will
- provide a useful \link #return return value\endlink. Typically,
- to get the dialog to close and return the appropriate value, we
- connect a default button, e.g. \gui OK, to the accept() slot and a
- \gui Cancel button to the reject() slot.
- Alternatively you can call the done() slot with \c Accepted or
- \c Rejected.
-
- An alternative is to call setModal(true) or setWindowModality(),
- then show(). Unlike exec(), show() returns control to the caller
- immediately. Calling setModal(true) is especially useful for
- progress dialogs, where the user must have the ability to interact
- with the dialog, e.g. to cancel a long running operation. If you
- use show() and setModal(true) together to perform a long operation,
- you must call QApplication::processEvents() periodically during
- processing to enable the user to interact with the dialog. (See
- QProgressDialog.)
-
- \section1 Modeless Dialogs
-
- A \bold{modeless} dialog is a dialog that operates
- independently of other windows in the same application. Find and
- replace dialogs in word-processors are often modeless to allow the
- user to interact with both the application's main window and with
- the dialog.
-
- Modeless dialogs are displayed using show(), which returns control
- to the caller immediately.
-
- If you invoke the \l{QWidget::show()}{show()} function after hiding
- a dialog, the dialog will be displayed in its original position. This is
- because the window manager decides the position for windows that
- have not been explicitly placed by the programmer. To preserve the
- position of a dialog that has been moved by the user, save its position
- in your \l{QWidget::closeEvent()}{closeEvent()} handler and then
- move the dialog to that position, before showing it again.
-
- \target default
- \section1 Default Button
-
- A dialog's \e default button is the button that's pressed when the
- user presses Enter (Return). This button is used to signify that
- the user accepts the dialog's settings and wants to close the
- dialog. Use QPushButton::setDefault(), QPushButton::isDefault()
- and QPushButton::autoDefault() to set and control the dialog's
- default button.
-
- \target escapekey
- \section1 Escape Key
-
- If the user presses the Esc key in a dialog, QDialog::reject()
- will be called. This will cause the window to close: The \link
- QCloseEvent close event \endlink cannot be \link
- QCloseEvent::ignore() ignored \endlink.
-
- \section1 Extensibility
-
- Extensibility is the ability to show the dialog in two ways: a
- partial dialog that shows the most commonly used options, and a
- full dialog that shows all the options. Typically an extensible
- dialog will initially appear as a partial dialog, but with a
- \gui More toggle button. If the user presses the \gui More button down,
- the dialog is expanded. The \l{Extension Example} shows how to achieve
- extensible dialogs using Qt.
-
- \target return
- \section1 Return Value (Modal Dialogs)
-
- Modal dialogs are often used in situations where a return value is
- required, e.g. to indicate whether the user pressed \gui OK or
- \gui Cancel. A dialog can be closed by calling the accept() or the
- reject() slots, and exec() will return \c Accepted or \c Rejected
- as appropriate. The exec() call returns the result of the dialog.
- The result is also available from result() if the dialog has not
- been destroyed.
-
- In order to modify your dialog's close behavior, you can reimplement
- the functions accept(), reject() or done(). The
- \l{QWidget::closeEvent()}{closeEvent()} function should only be
- reimplemented to preserve the dialog's position or to override the
- standard close or reject behavior.
-
- \target examples
- \section1 Code Examples
-
- A modal dialog:
-
- \snippet doc/src/snippets/dialogs/dialogs.cpp 1
-
- A modeless dialog:
-
- \snippet doc/src/snippets/dialogs/dialogs.cpp 0
-
- \sa QDialogButtonBox, QTabWidget, QWidget, QProgressDialog,
- {fowler}{GUI Design Handbook: Dialogs, Standard}, {Extension Example},
- {Standard Dialogs Example}
-*/
-
-/*! \enum QDialog::DialogCode
-
- The value returned by a modal dialog.
-
- \value Accepted
- \value Rejected
-*/
-
-/*!
- \property QDialog::sizeGripEnabled
- \brief whether the size grip is enabled
-
- A QSizeGrip is placed in the bottom-right corner of the dialog when this
- property is enabled. By default, the size grip is disabled.
-*/
-
-
-/*!
- Constructs a dialog with parent \a parent.
-
- A dialog is always a top-level widget, but if it has a parent, its
- default location is centered on top of the parent. It will also
- share the parent's taskbar entry.
-
- The widget flags \a f are passed on to the QWidget constructor.
- If, for example, you don't want a What's This button in the title bar
- of the dialog, pass Qt::WindowTitleHint | Qt::WindowSystemMenuHint in \a f.
-
- \sa QWidget::setWindowFlags()
-*/
-
-QDialog::QDialog(QWidget *parent, Qt::WindowFlags f)
- : QWidget(*new QDialogPrivate, parent,
- f | ((f & Qt::WindowType_Mask) == 0 ? Qt::Dialog : Qt::WindowType(0)))
-{
-#ifdef Q_WS_WINCE
- if (!qt_wince_is_smartphone())
- setWindowFlags(windowFlags() | Qt::WindowOkButtonHint | QFlag(qt_wince_is_mobile() ? 0 : Qt::WindowCancelButtonHint));
-#endif
-
-#ifdef Q_WS_S60
- if (S60->avkonComponentsSupportTransparency) {
- bool noSystemBackground = testAttribute(Qt::WA_NoSystemBackground);
- setAttribute(Qt::WA_TranslucentBackground); // also sets WA_NoSystemBackground
- setAttribute(Qt::WA_NoSystemBackground, noSystemBackground); // restore system background attribute
- }
-#endif
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \overload
- \obsolete
-*/
-QDialog::QDialog(QWidget *parent, const char *name, bool modal, Qt::WindowFlags f)
- : QWidget(*new QDialogPrivate, parent,
- f
- | QFlag(modal ? Qt::WShowModal : Qt::WindowType(0))
- | QFlag((f & Qt::WindowType_Mask) == 0 ? Qt::Dialog : Qt::WindowType(0))
- )
-{
- setObjectName(QString::fromAscii(name));
-}
-#endif
-
-/*!
- \overload
- \internal
-*/
-QDialog::QDialog(QDialogPrivate &dd, QWidget *parent, Qt::WindowFlags f)
- : QWidget(dd, parent, f | ((f & Qt::WindowType_Mask) == 0 ? Qt::Dialog : Qt::WindowType(0)))
-{
-#ifdef Q_WS_WINCE
- if (!qt_wince_is_smartphone())
- setWindowFlags(windowFlags() | Qt::WindowOkButtonHint | QFlag(qt_wince_is_mobile() ? 0 : Qt::WindowCancelButtonHint));
-#endif
-
-#ifdef Q_WS_S60
- if (S60->avkonComponentsSupportTransparency) {
- bool noSystemBackground = testAttribute(Qt::WA_NoSystemBackground);
- setAttribute(Qt::WA_TranslucentBackground); // also sets WA_NoSystemBackground
- setAttribute(Qt::WA_NoSystemBackground, noSystemBackground); // restore system background attribute
- }
-#endif
-}
-
-/*!
- Destroys the QDialog, deleting all its children.
-*/
-
-QDialog::~QDialog()
-{
- QT_TRY {
- // Need to hide() here, as our (to-be) overridden hide()
- // will not be called in ~QWidget.
- hide();
- } QT_CATCH(...) {
- // we're in the destructor - just swallow the exception
- }
-}
-
-/*!
- \internal
- This function is called by the push button \a pushButton when it
- becomes the default button. If \a pushButton is 0, the dialogs
- default default button becomes the default button. This is what a
- push button calls when it loses focus.
-*/
-void QDialogPrivate::setDefault(QPushButton *pushButton)
-{
- Q_Q(QDialog);
- bool hasMain = false;
- QList<QPushButton*> list = q->findChildren<QPushButton*>();
- for (int i=0; i<list.size(); ++i) {
- QPushButton *pb = list.at(i);
- if (pb->window() == q) {
- if (pb == mainDef)
- hasMain = true;
- if (pb != pushButton)
- pb->setDefault(false);
- }
- }
- if (!pushButton && hasMain)
- mainDef->setDefault(true);
- if (!hasMain)
- mainDef = pushButton;
-}
-
-/*!
- \internal
- This function sets the default default push button to \a pushButton.
- This function is called by QPushButton::setDefault().
-*/
-void QDialogPrivate::setMainDefault(QPushButton *pushButton)
-{
- mainDef = 0;
- setDefault(pushButton);
-}
-
-/*!
- \internal
- Hides the default button indicator. Called when non auto-default
- push button get focus.
- */
-void QDialogPrivate::hideDefault()
-{
- Q_Q(QDialog);
- QList<QPushButton*> list = q->findChildren<QPushButton*>();
- for (int i=0; i<list.size(); ++i) {
- list.at(i)->setDefault(false);
- }
-}
-
-void QDialogPrivate::resetModalitySetByOpen()
-{
- Q_Q(QDialog);
- if (resetModalityTo != -1 && !q->testAttribute(Qt::WA_SetWindowModality)) {
- // open() changed the window modality and the user didn't touch it afterwards; restore it
- q->setWindowModality(Qt::WindowModality(resetModalityTo));
- q->setAttribute(Qt::WA_SetWindowModality, wasModalitySet);
-#ifdef Q_WS_MAC
- Q_ASSERT(resetModalityTo != Qt::WindowModal);
- q->setParent(q->parentWidget(), Qt::Dialog);
-#endif
- }
- resetModalityTo = -1;
-}
-
-#if defined(Q_WS_WINCE) || defined(Q_OS_SYMBIAN)
-#ifdef Q_WS_WINCE_WM
-void QDialogPrivate::_q_doneAction()
-{
- //Done...
- QApplication::postEvent(q_func(), new QEvent(QEvent::OkRequest));
-}
-#endif
-
-/*!
- \reimp
-*/
-bool QDialog::event(QEvent *e)
-{
- bool result = QWidget::event(e);
-#ifdef Q_WS_WINCE
- if (e->type() == QEvent::OkRequest) {
- accept();
- result = true;
- }
-#elif defined(Q_WS_S60)
- if ((e->type() == QEvent::StyleChange) || (e->type() == QEvent::Resize )) {
- if (!testAttribute(Qt::WA_Moved)) {
- Qt::WindowStates state = windowState();
- adjustPosition(parentWidget());
- setAttribute(Qt::WA_Moved, false); // not really an explicit position
- if (state != windowState())
- setWindowState(state);
- }
- }
- // TODO is Symbian, non-S60 behaviour required?
-#endif
- return result;
-}
-#endif
-
-/*!
- Returns the modal dialog's result code, \c Accepted or \c Rejected.
-
- Do not call this function if the dialog was constructed with the
- Qt::WA_DeleteOnClose attribute.
-*/
-int QDialog::result() const
-{
- Q_D(const QDialog);
- return d->rescode;
-}
-
-/*!
- \fn void QDialog::setResult(int i)
-
- Sets the modal dialog's result code to \a i.
-
- \note We recommend that you use one of the values defined by
- QDialog::DialogCode.
-*/
-void QDialog::setResult(int r)
-{
- Q_D(QDialog);
- d->rescode = r;
-}
-
-/*!
- \since 4.5
-
- Shows the dialog as a \l{QDialog#Modal Dialogs}{window modal dialog},
- returning immediately.
-
- \sa exec(), show(), result(), setWindowModality()
-*/
-void QDialog::open()
-{
- Q_D(QDialog);
-
- Qt::WindowModality modality = windowModality();
- if (modality != Qt::WindowModal) {
- d->resetModalityTo = modality;
- d->wasModalitySet = testAttribute(Qt::WA_SetWindowModality);
- setWindowModality(Qt::WindowModal);
- setAttribute(Qt::WA_SetWindowModality, false);
-#ifdef Q_WS_MAC
- setParent(parentWidget(), Qt::Sheet);
-#endif
- }
-
- setResult(0);
- show();
-}
-
-/*!
- Shows the dialog as a \l{QDialog#Modal Dialogs}{modal dialog},
- blocking until the user closes it. The function returns a \l
- DialogCode result.
-
- If the dialog is \l{Qt::ApplicationModal}{application modal}, users cannot
- interact with any other window in the same application until they close
- the dialog. If the dialog is \l{Qt::ApplicationModal}{window modal}, only
- interaction with the parent window is blocked while the dialog is open.
- By default, the dialog is application modal.
-
- \sa open(), show(), result(), setWindowModality()
-*/
-
-int QDialog::exec()
-{
- Q_D(QDialog);
-
- if (d->eventLoop) {
- qWarning("QDialog::exec: Recursive call detected");
- return -1;
- }
-
- bool deleteOnClose = testAttribute(Qt::WA_DeleteOnClose);
- setAttribute(Qt::WA_DeleteOnClose, false);
-
- d->resetModalitySetByOpen();
-
- bool wasShowModal = testAttribute(Qt::WA_ShowModal);
- setAttribute(Qt::WA_ShowModal, true);
- setResult(0);
-
-//On Windows Mobile we create an empty menu to hide the current menu
-#ifdef Q_WS_WINCE_WM
-#ifndef QT_NO_MENUBAR
- QMenuBar *menuBar = 0;
- if (!findChild<QMenuBar *>())
- menuBar = new QMenuBar(this);
- if (qt_wince_is_smartphone()) {
- QAction *doneAction = new QAction(tr("Done"), this);
- menuBar->setDefaultAction(doneAction);
- connect(doneAction, SIGNAL(triggered()), this, SLOT(_q_doneAction()));
- }
-#endif //QT_NO_MENUBAR
-#endif //Q_WS_WINCE_WM
-
- bool showSystemDialogFullScreen = false;
-#ifdef Q_OS_SYMBIAN
- if (qobject_cast<QFileDialog *>(this) || qobject_cast<QFontDialog *>(this) ||
- qobject_cast<QWizard *>(this)) {
- showSystemDialogFullScreen = true;
- }
-#endif // Q_OS_SYMBIAN
-
- if (showSystemDialogFullScreen) {
- setWindowFlags(windowFlags() | Qt::WindowSoftkeysVisibleHint);
- setWindowState(Qt::WindowFullScreen);
- }
- show();
-
-#ifdef Q_WS_MAC
- d->mac_nativeDialogModalHelp();
-#endif
-
- QEventLoop eventLoop;
- d->eventLoop = &eventLoop;
- QPointer<QDialog> guard = this;
- (void) eventLoop.exec(QEventLoop::DialogExec);
- if (guard.isNull())
- return QDialog::Rejected;
- d->eventLoop = 0;
-
- setAttribute(Qt::WA_ShowModal, wasShowModal);
-
- int res = result();
- if (deleteOnClose)
- delete this;
-#ifdef Q_WS_WINCE_WM
-#ifndef QT_NO_MENUBAR
- else if (menuBar)
- delete menuBar;
-#endif //QT_NO_MENUBAR
-#endif //Q_WS_WINCE_WM
- return res;
-}
-
-
-/*!
- Closes the dialog and sets its result code to \a r. If this dialog
- is shown with exec(), done() causes the local event loop to finish,
- and exec() to return \a r.
-
- As with QWidget::close(), done() deletes the dialog if the
- Qt::WA_DeleteOnClose flag is set. If the dialog is the application's
- main widget, the application terminates. If the dialog is the
- last window closed, the QApplication::lastWindowClosed() signal is
- emitted.
-
- \sa accept(), reject(), QApplication::activeWindow(), QApplication::quit()
-*/
-
-void QDialog::done(int r)
-{
- Q_D(QDialog);
- hide();
- setResult(r);
-
- d->close_helper(QWidgetPrivate::CloseNoEvent);
- d->resetModalitySetByOpen();
-
- emit finished(r);
- if (r == Accepted)
- emit accepted();
- else if (r == Rejected)
- emit rejected();
-}
-
-/*!
- Hides the modal dialog and sets the result code to \c Accepted.
-
- \sa reject() done()
-*/
-
-void QDialog::accept()
-{
- done(Accepted);
-}
-
-/*!
- Hides the modal dialog and sets the result code to \c Rejected.
-
- \sa accept() done()
-*/
-
-void QDialog::reject()
-{
- done(Rejected);
-}
-
-/*! \reimp */
-bool QDialog::eventFilter(QObject *o, QEvent *e)
-{
- return QWidget::eventFilter(o, e);
-}
-
-/*****************************************************************************
- Event handlers
- *****************************************************************************/
-
-#ifndef QT_NO_CONTEXTMENU
-/*! \reimp */
-void QDialog::contextMenuEvent(QContextMenuEvent *e)
-{
-#if defined(QT_NO_WHATSTHIS) || defined(QT_NO_MENU)
- Q_UNUSED(e);
-#else
- QWidget *w = childAt(e->pos());
- if (!w) {
- w = rect().contains(e->pos()) ? this : 0;
- if (!w)
- return;
- }
- while (w && w->whatsThis().size() == 0 && !w->testAttribute(Qt::WA_CustomWhatsThis))
- w = w->isWindow() ? 0 : w->parentWidget();
- if (w) {
- QWeakPointer<QMenu> p = new QMenu(this);
- QAction *wt = p.data()->addAction(tr("What's This?"));
- if (p.data()->exec(e->globalPos()) == wt) {
- QHelpEvent e(QEvent::WhatsThis, w->rect().center(),
- w->mapToGlobal(w->rect().center()));
- QApplication::sendEvent(w, &e);
- }
- delete p.data();
- }
-#endif
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*! \reimp */
-void QDialog::keyPressEvent(QKeyEvent *e)
-{
- // Calls reject() if Escape is pressed. Simulates a button
- // click for the default button if Enter is pressed. Move focus
- // for the arrow keys. Ignore the rest.
-#ifdef Q_WS_MAC
- if(e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Period) {
- reject();
- } else
-#endif
- if (!e->modifiers() || (e->modifiers() & Qt::KeypadModifier && e->key() == Qt::Key_Enter)) {
- switch (e->key()) {
- case Qt::Key_Enter:
- case Qt::Key_Return: {
- QList<QPushButton*> list = findChildren<QPushButton*>();
- for (int i=0; i<list.size(); ++i) {
- QPushButton *pb = list.at(i);
- if (pb->isDefault() && pb->isVisible()) {
- if (pb->isEnabled())
- pb->click();
- return;
- }
- }
- }
- break;
- case Qt::Key_Escape:
- reject();
- break;
- default:
- e->ignore();
- return;
- }
- } else {
- e->ignore();
- }
-}
-
-/*! \reimp */
-void QDialog::closeEvent(QCloseEvent *e)
-{
-#ifndef QT_NO_WHATSTHIS
- if (isModal() && QWhatsThis::inWhatsThisMode())
- QWhatsThis::leaveWhatsThisMode();
-#endif
- if (isVisible()) {
- QPointer<QObject> that = this;
- reject();
- if (that && isVisible())
- e->ignore();
- } else {
- e->accept();
- }
-}
-
-/*****************************************************************************
- Geometry management.
- *****************************************************************************/
-
-/*! \reimp
-*/
-
-void QDialog::setVisible(bool visible)
-{
- Q_D(QDialog);
- if (visible) {
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
-
- if (!testAttribute(Qt::WA_Moved)) {
- Qt::WindowStates state = windowState();
- adjustPosition(parentWidget());
- setAttribute(Qt::WA_Moved, false); // not really an explicit position
- if (state != windowState())
- setWindowState(state);
- }
- QWidget::setVisible(visible);
- showExtension(d->doShowExtension);
- QWidget *fw = window()->focusWidget();
- if (!fw)
- fw = this;
-
- /*
- The following block is to handle a special case, and does not
- really follow propper logic in concern of autoDefault and TAB
- order. However, it's here to ease usage for the users. If a
- dialog has a default QPushButton, and first widget in the TAB
- order also is a QPushButton, then we give focus to the main
- default QPushButton. This simplifies code for the developers,
- and actually catches most cases... If not, then they simply
- have to use [widget*]->setFocus() themselves...
- */
- if (d->mainDef && fw->focusPolicy() == Qt::NoFocus) {
- QWidget *first = fw;
- while ((first = first->nextInFocusChain()) != fw && first->focusPolicy() == Qt::NoFocus)
- ;
- if (first != d->mainDef && qobject_cast<QPushButton*>(first))
- d->mainDef->setFocus();
- }
- if (!d->mainDef && isWindow()) {
- QWidget *w = fw;
- while ((w = w->nextInFocusChain()) != fw) {
- QPushButton *pb = qobject_cast<QPushButton *>(w);
- if (pb && pb->autoDefault() && pb->focusPolicy() != Qt::NoFocus) {
- pb->setDefault(true);
- break;
- }
- }
- }
- if (fw && !fw->hasFocus()) {
- QFocusEvent e(QEvent::FocusIn, Qt::TabFocusReason);
- QApplication::sendEvent(fw, &e);
- }
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DialogStart);
-#endif
-
- } else {
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
-
-#ifndef QT_NO_ACCESSIBILITY
- if (isVisible())
- QAccessible::updateAccessibility(this, 0, QAccessible::DialogEnd);
-#endif
-
- // Reimplemented to exit a modal event loop when the dialog is hidden.
- QWidget::setVisible(visible);
- if (d->eventLoop)
- d->eventLoop->exit();
- }
-#ifdef Q_WS_WIN
- if (d->mainDef && isActiveWindow()) {
- BOOL snapToDefault = false;
- if (SystemParametersInfo(SPI_GETSNAPTODEFBUTTON, 0, &snapToDefault, 0)) {
- if (snapToDefault)
- QCursor::setPos(d->mainDef->mapToGlobal(d->mainDef->rect().center()));
- }
- }
-#endif
-}
-
-/*!\reimp */
-void QDialog::showEvent(QShowEvent *event)
-{
- if (!event->spontaneous() && !testAttribute(Qt::WA_Moved)) {
- Qt::WindowStates state = windowState();
- adjustPosition(parentWidget());
- setAttribute(Qt::WA_Moved, false); // not really an explicit position
- if (state != windowState())
- setWindowState(state);
- }
-}
-
-/*! \internal */
-void QDialog::adjustPosition(QWidget* w)
-{
-#ifdef Q_WS_X11
- // if the WM advertises that it will place the windows properly for us, let it do it :)
- if (X11->isSupportedByWM(ATOM(_NET_WM_FULL_PLACEMENT)))
- return;
-#endif
-
-#ifdef Q_OS_SYMBIAN
- if (symbianAdjustedPosition())
- //dialog has already been positioned
- return;
-#endif
-
- QPoint p(0, 0);
- int extraw = 0, extrah = 0, scrn = 0;
- if (w)
- w = w->window();
- QRect desk;
- if (w) {
- scrn = QApplication::desktop()->screenNumber(w);
- } else if (QApplication::desktop()->isVirtualDesktop()) {
- scrn = QApplication::desktop()->screenNumber(QCursor::pos());
- } else {
- scrn = QApplication::desktop()->screenNumber(this);
- }
- desk = QApplication::desktop()->availableGeometry(scrn);
-
- QWidgetList list = QApplication::topLevelWidgets();
- for (int i = 0; (extraw == 0 || extrah == 0) && i < list.size(); ++i) {
- QWidget * current = list.at(i);
- if (current->isVisible()) {
- int framew = current->geometry().x() - current->x();
- int frameh = current->geometry().y() - current->y();
-
- extraw = qMax(extraw, framew);
- extrah = qMax(extrah, frameh);
- }
- }
-
- // sanity check for decoration frames. With embedding, we
- // might get extraordinary values
- if (extraw == 0 || extrah == 0 || extraw >= 10 || extrah >= 40) {
- extrah = 40;
- extraw = 10;
- }
-
-
- if (w) {
- // Use mapToGlobal rather than geometry() in case w might
- // be embedded in another application
- QPoint pp = w->mapToGlobal(QPoint(0,0));
- p = QPoint(pp.x() + w->width()/2,
- pp.y() + w->height()/ 2);
- } else {
- // p = middle of the desktop
- p = QPoint(desk.x() + desk.width()/2, desk.y() + desk.height()/2);
- }
-
- // p = origin of this
- p = QPoint(p.x()-width()/2 - extraw,
- p.y()-height()/2 - extrah);
-
-
- if (p.x() + extraw + width() > desk.x() + desk.width())
- p.setX(desk.x() + desk.width() - width() - extraw);
- if (p.x() < desk.x())
- p.setX(desk.x());
-
- if (p.y() + extrah + height() > desk.y() + desk.height())
- p.setY(desk.y() + desk.height() - height() - extrah);
- if (p.y() < desk.y())
- p.setY(desk.y());
-
- move(p);
-}
-
-#if defined(Q_OS_SYMBIAN)
-/*! \internal */
-bool QDialog::symbianAdjustedPosition()
-{
-#if defined(Q_WS_S60)
- QPoint p;
- QPoint oldPos = pos();
- if (isFullScreen()) {
- p.setX(0);
- p.setY(0);
- } else if (isMaximized()) {
- TRect statusPaneRect = TRect();
- if (S60->screenHeightInPixels > S60->screenWidthInPixels) {
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStatusPane, statusPaneRect);
- } else {
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, statusPaneRect);
- }
-
- p.setX(0);
- p.setY(statusPaneRect.Height());
- } else {
- // naive way to deduce screen orientation
- if (S60->screenHeightInPixels > S60->screenWidthInPixels) {
- int cbaHeight;
- TRect rect;
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EControlPane, rect);
- cbaHeight = rect.Height();
- p.setY(S60->screenHeightInPixels - height() - cbaHeight);
- p.setX(0);
- } else {
- const int scrollbarWidth = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
- TRect staConTopRect = TRect();
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, staConTopRect);
- if (staConTopRect.IsEmpty()) {
- TRect cbaRect = TRect();
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EControlPane, cbaRect);
- AknLayoutUtils::TAknCbaLocation cbaLocation = AknLayoutUtils::CbaLocation();
- switch (cbaLocation) {
- case AknLayoutUtils::EAknCbaLocationBottom:
- p.setY(S60->screenHeightInPixels - height() - cbaRect.Height());
- p.setX((S60->screenWidthInPixels - width()) >> 1);
- break;
- case AknLayoutUtils::EAknCbaLocationRight:
- p.setY((S60->screenHeightInPixels - height()) >> 1);
- p.setX(qMax(0,S60->screenWidthInPixels - width() - scrollbarWidth - cbaRect.Width()));
- break;
- case AknLayoutUtils::EAknCbaLocationLeft:
- p.setY((S60->screenHeightInPixels - height()) >> 1);
- p.setX(qMax(0,scrollbarWidth + cbaRect.Width()));
- break;
- }
- } else {
- p.setY((S60->screenHeightInPixels - height()) >> 1);
- p.setX(qMax(0,S60->screenWidthInPixels - width()));
- }
- }
- }
- if (oldPos != p || p.y() < 0)
- move(p);
- return true;
-#else
- // TODO - check positioning requirement for Symbian, non-s60
- return false;
-#endif
-}
-#endif
-
-/*!
- \obsolete
-
- If \a orientation is Qt::Horizontal, the extension will be displayed
- to the right of the dialog's main area. If \a orientation is
- Qt::Vertical, the extension will be displayed below the dialog's main
- area.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa setExtension()
-*/
-void QDialog::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QDialog);
- d->orientation = orientation;
-}
-
-/*!
- \obsolete
-
- Returns the dialog's extension orientation.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa extension()
-*/
-Qt::Orientation QDialog::orientation() const
-{
- Q_D(const QDialog);
- return d->orientation;
-}
-
-/*!
- \obsolete
-
- Sets the widget, \a extension, to be the dialog's extension,
- deleting any previous extension. The dialog takes ownership of the
- extension. Note that if 0 is passed any existing extension will be
- deleted. This function must only be called while the dialog is hidden.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa showExtension(), setOrientation()
-*/
-void QDialog::setExtension(QWidget* extension)
-{
- Q_D(QDialog);
- delete d->extension;
- d->extension = extension;
-
- if (!extension)
- return;
-
- if (extension->parentWidget() != this)
- extension->setParent(this);
- extension->hide();
-}
-
-/*!
- \obsolete
-
- Returns the dialog's extension or 0 if no extension has been
- defined.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa showExtension(), setOrientation()
-*/
-QWidget* QDialog::extension() const
-{
- Q_D(const QDialog);
- return d->extension;
-}
-
-
-/*!
- \obsolete
-
- If \a showIt is true, the dialog's extension is shown; otherwise the
- extension is hidden.
-
- Instead of using this functionality, we recommend that you simply call
- show() or hide() on the part of the dialog that you want to use as an
- extension. See the \l{Extension Example} for details.
-
- \sa show(), setExtension(), setOrientation()
-*/
-void QDialog::showExtension(bool showIt)
-{
- Q_D(QDialog);
- d->doShowExtension = showIt;
- if (!d->extension)
- return;
- if (!testAttribute(Qt::WA_WState_Visible))
- return;
- if (d->extension->isVisible() == showIt)
- return;
-
- if (showIt) {
- d->size = size();
- d->min = minimumSize();
- d->max = maximumSize();
- if (layout())
- layout()->setEnabled(false);
- QSize s(d->extension->sizeHint()
- .expandedTo(d->extension->minimumSize())
- .boundedTo(d->extension->maximumSize()));
- if (d->orientation == Qt::Horizontal) {
- int h = qMax(height(), s.height());
- d->extension->setGeometry(width(), 0, s.width(), h);
- setFixedSize(width() + s.width(), h);
- } else {
- int w = qMax(width(), s.width());
- d->extension->setGeometry(0, height(), w, s.height());
- setFixedSize(w, height() + s.height());
- }
- d->extension->show();
-#ifndef QT_NO_SIZEGRIP
- const bool sizeGripEnabled = isSizeGripEnabled();
- setSizeGripEnabled(false);
- d->sizeGripEnabled = sizeGripEnabled;
-#endif
- } else {
- d->extension->hide();
- // workaround for CDE window manager that won't shrink with (-1,-1)
- setMinimumSize(d->min.expandedTo(QSize(1, 1)));
- setMaximumSize(d->max);
- resize(d->size);
- if (layout())
- layout()->setEnabled(true);
-#ifndef QT_NO_SIZEGRIP
- setSizeGripEnabled(d->sizeGripEnabled);
-#endif
- }
-}
-
-
-/*! \reimp */
-QSize QDialog::sizeHint() const
-{
- Q_D(const QDialog);
- if (d->extension) {
- if (d->orientation == Qt::Horizontal)
- return QSize(QWidget::sizeHint().width(),
- qMax(QWidget::sizeHint().height(),d->extension->sizeHint().height()));
- else
- return QSize(qMax(QWidget::sizeHint().width(), d->extension->sizeHint().width()),
- QWidget::sizeHint().height());
- }
-#if defined(Q_WS_S60)
- // if size is not fixed, try to adjust it according to S60 layoutting
- if (minimumSize() != maximumSize()) {
- // In S60, dialogs are always the width of screen (in portrait, regardless of current layout)
- return QSize(qMin(S60->screenHeightInPixels, S60->screenWidthInPixels), QWidget::sizeHint().height());
- } else {
- return QWidget::sizeHint();
- }
-#else
- return QWidget::sizeHint();
-#endif //Q_WS_S60
-}
-
-
-/*! \reimp */
-QSize QDialog::minimumSizeHint() const
-{
- Q_D(const QDialog);
- if (d->extension) {
- if (d->orientation == Qt::Horizontal)
- return QSize(QWidget::minimumSizeHint().width(),
- qMax(QWidget::minimumSizeHint().height(), d->extension->minimumSizeHint().height()));
- else
- return QSize(qMax(QWidget::minimumSizeHint().width(), d->extension->minimumSizeHint().width()),
- QWidget::minimumSizeHint().height());
- }
-
- return QWidget::minimumSizeHint();
-}
-
-/*!
- \property QDialog::modal
- \brief whether show() should pop up the dialog as modal or modeless
-
- By default, this property is false and show() pops up the dialog
- as modeless. Setting his property to true is equivalent to setting
- QWidget::windowModality to Qt::ApplicationModal.
-
- exec() ignores the value of this property and always pops up the
- dialog as modal.
-
- \sa QWidget::windowModality, show(), exec()
-*/
-
-void QDialog::setModal(bool modal)
-{
- setAttribute(Qt::WA_ShowModal, modal);
-}
-
-
-bool QDialog::isSizeGripEnabled() const
-{
-#ifndef QT_NO_SIZEGRIP
- Q_D(const QDialog);
- return !!d->resizer;
-#else
- return false;
-#endif
-}
-
-
-void QDialog::setSizeGripEnabled(bool enabled)
-{
-#ifdef QT_NO_SIZEGRIP
- Q_UNUSED(enabled);
-#else
- Q_D(QDialog);
-#ifndef QT_NO_SIZEGRIP
- d->sizeGripEnabled = enabled;
- if (enabled && d->doShowExtension)
- return;
-#endif
- if (!enabled != !d->resizer) {
- if (enabled) {
- d->resizer = new QSizeGrip(this);
- // adjustSize() processes all events, which is suboptimal
- d->resizer->resize(d->resizer->sizeHint());
- if (isRightToLeft())
- d->resizer->move(rect().bottomLeft() -d->resizer->rect().bottomLeft());
- else
- d->resizer->move(rect().bottomRight() -d->resizer->rect().bottomRight());
- d->resizer->raise();
- d->resizer->show();
- } else {
- delete d->resizer;
- d->resizer = 0;
- }
- }
-#endif //QT_NO_SIZEGRIP
-}
-
-
-
-/*! \reimp */
-void QDialog::resizeEvent(QResizeEvent *)
-{
-#ifndef QT_NO_SIZEGRIP
- Q_D(QDialog);
- if (d->resizer) {
- if (isRightToLeft())
- d->resizer->move(rect().bottomLeft() -d->resizer->rect().bottomLeft());
- else
- d->resizer->move(rect().bottomRight() -d->resizer->rect().bottomRight());
- d->resizer->raise();
- }
-#endif
-}
-
-/*! \fn void QDialog::finished(int result)
- \since 4.1
-
- This signal is emitted when the dialog's \a result code has been
- set, either by the user or by calling done(), accept(), or
- reject().
-
- Note that this signal is \e not emitted when hiding the dialog
- with hide() or setVisible(false). This includes deleting the
- dialog while it is visible.
-
- \sa accepted(), rejected()
-*/
-
-/*! \fn void QDialog::accepted()
- \since 4.1
-
- This signal is emitted when the dialog has been accepted either by
- the user or by calling accept() or done() with the
- QDialog::Accepted argument.
-
- Note that this signal is \e not emitted when hiding the dialog
- with hide() or setVisible(false). This includes deleting the
- dialog while it is visible.
-
- \sa finished(), rejected()
-*/
-
-/*! \fn void QDialog::rejected()
- \since 4.1
-
- This signal is emitted when the dialog has been rejected either by
- the user or by calling reject() or done() with the
- QDialog::Rejected argument.
-
- Note that this signal is \e not emitted when hiding the dialog
- with hide() or setVisible(false). This includes deleting the
- dialog while it is visible.
-
- \sa finished(), accepted()
-*/
-
-QT_END_NAMESPACE
-#include "moc_qdialog.cpp"
diff --git a/src/gui/dialogs/qdialog.h b/src/gui/dialogs/qdialog.h
deleted file mode 100644
index ee23b7bf87..0000000000
--- a/src/gui/dialogs/qdialog.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** 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 QDIALOG_H
-#define QDIALOG_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QPushButton;
-class QDialogPrivate;
-
-class Q_GUI_EXPORT QDialog : public QWidget
-{
- Q_OBJECT
- friend class QPushButton;
-
- Q_PROPERTY(bool sizeGripEnabled READ isSizeGripEnabled WRITE setSizeGripEnabled)
- Q_PROPERTY(bool modal READ isModal WRITE setModal)
-
-public:
- explicit QDialog(QWidget *parent = 0, Qt::WindowFlags f = 0);
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QDialog(QWidget *parent, const char *name, bool modal = false,
- Qt::WindowFlags f = 0);
-#endif
- ~QDialog();
-
- enum DialogCode { Rejected, Accepted };
-
- int result() const;
-
- void setVisible(bool visible);
-
- void setOrientation(Qt::Orientation orientation);
- Qt::Orientation orientation() const;
-
- void setExtension(QWidget* extension);
- QWidget* extension() const;
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- void setSizeGripEnabled(bool);
- bool isSizeGripEnabled() const;
-
- void setModal(bool modal);
- void setResult(int r);
-
-Q_SIGNALS:
- void finished(int result);
- void accepted();
- void rejected();
-
-public Q_SLOTS:
- void open();
- int exec();
- virtual void done(int);
- virtual void accept();
- virtual void reject();
-
- void showExtension(bool);
-
-protected:
- QDialog(QDialogPrivate &, QWidget *parent, Qt::WindowFlags f = 0);
-
-#if defined(Q_WS_WINCE) || defined(Q_OS_SYMBIAN)
- bool event(QEvent *e);
-#endif
- void keyPressEvent(QKeyEvent *);
- void closeEvent(QCloseEvent *);
- void showEvent(QShowEvent *);
- void resizeEvent(QResizeEvent *);
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *);
-#endif
- bool eventFilter(QObject *, QEvent *);
- void adjustPosition(QWidget*);
-private:
- Q_DECLARE_PRIVATE(QDialog)
- Q_DISABLE_COPY(QDialog)
-
-#if defined(Q_OS_SYMBIAN)
- bool symbianAdjustedPosition();
-#endif
-
-
-#ifdef Q_WS_WINCE_WM
- Q_PRIVATE_SLOT(d_func(), void _q_doneAction())
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDIALOG_H
diff --git a/src/gui/dialogs/qdialog_p.h b/src/gui/dialogs/qdialog_p.h
deleted file mode 100644
index a2a948e951..0000000000
--- a/src/gui/dialogs/qdialog_p.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** 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 QDIALOG_P_H
-#define QDIALOG_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qwidget_p.h"
-#include "QtCore/qeventloop.h"
-#include "QtCore/qpointer.h"
-#include "QtGui/qdialog.h"
-#include "QtGui/qpushbutton.h"
-
-QT_BEGIN_NAMESPACE
-
-class QSizeGrip;
-
-class QDialogPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QDialog)
-public:
-
- QDialogPrivate()
- : mainDef(0), orientation(Qt::Horizontal),extension(0), doShowExtension(false),
-#ifndef QT_NO_SIZEGRIP
- resizer(0),
- sizeGripEnabled(false),
-#endif
- rescode(0), resetModalityTo(-1), wasModalitySet(true), eventLoop(0)
- {}
-
- QPointer<QPushButton> mainDef;
- Qt::Orientation orientation;
- QWidget *extension;
- bool doShowExtension;
- QSize size, min, max;
-#ifndef QT_NO_SIZEGRIP
- QSizeGrip *resizer;
- bool sizeGripEnabled;
-#endif
- QPoint lastRMBPress;
-
- void setDefault(QPushButton *);
- void setMainDefault(QPushButton *);
- void hideDefault();
- void resetModalitySetByOpen();
-
-#ifdef Q_WS_WINCE_WM
- void _q_doneAction();
-#endif
-
-#ifdef Q_WS_MAC
- virtual void mac_nativeDialogModalHelp() {}
-#endif
-
- int rescode;
- int resetModalityTo;
- bool wasModalitySet;
-
- QPointer<QEventLoop> eventLoop;
-};
-
-QT_END_NAMESPACE
-
-#endif // QDIALOG_P_H
diff --git a/src/gui/dialogs/qdialogsbinarycompat_win.cpp b/src/gui/dialogs/qdialogsbinarycompat_win.cpp
deleted file mode 100644
index beec2cd29c..0000000000
--- a/src/gui/dialogs/qdialogsbinarycompat_win.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/****************************************************************************
-**
-** 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>
-
-// ### Qt 5: eliminate this file
-
-/*
- This is evil. MSVC doesn't let us remove private symbols, nor change their
- visibility; yet there are some symbols we really needed to make public, e.g.,
- ~QColorDialog(), and then there were some totally needless symbols in our
- header files, e.g., setSelectedAlpha(). So we define a new version of
- QColorDialog & Co. with only the private symbols that we removed from the
- public header files. The friends are there only to prevent potential compiler
- warnings.
-
- It would have been nicer to export the missing symbols as mangled "C" symbols
- instead but unfortunately MSVC uses out-of-reach characters like @ and . in
- their mangled C++ symbols.
-*/
-
-#if QT_VERSION < 0x050000 && defined(Q_CC_MSVC)
-
-QT_BEGIN_NAMESPACE
-
-#include <QtGui/QColor>
-#include <QtGui/QFont>
-
-class QColorDialogPrivate;
-class QFontDialogPrivate;
-class QInputDialogPrivate;
-class QWidget;
-
-class Q_GUI_EXPORT QColorDialog
-{
-private:
- explicit QColorDialog(QWidget *, bool);
- ~QColorDialog();
-
- void setColor(const QColor &);
- QColor color() const;
- bool selectColor(const QColor &);
- void setSelectedAlpha(int);
- int selectedAlpha() const;
-
- friend class QColorDialogPrivate;
-};
-
-QColorDialog::QColorDialog(QWidget *, bool) {}
-QColorDialog::~QColorDialog() {}
-void QColorDialog::setColor(const QColor &) {}
-QColor QColorDialog::color() const { return QColor(); }
-bool QColorDialog::selectColor(const QColor &) { return false; }
-void QColorDialog::setSelectedAlpha(int) {}
-int QColorDialog::selectedAlpha() const { return 0; }
-
-class Q_GUI_EXPORT QFontDialog
-{
-private:
- explicit QFontDialog(QWidget *, bool, Qt::WindowFlags);
- ~QFontDialog();
-
- QFont font() const;
- void setFont(const QFont &);
- void updateFamilies();
- void updateStyles();
- void updateSizes();
-
- static QFont getFont(bool *, const QFont *, QWidget *);
-
- friend class QFontDialogPrivate;
-};
-
-QFontDialog::QFontDialog(QWidget *, bool, Qt::WindowFlags) {}
-QFontDialog::~QFontDialog() {}
-QFont QFontDialog::font() const { return QFont(); }
-void QFontDialog::setFont(const QFont &) { }
-void QFontDialog::updateFamilies() {}
-void QFontDialog::updateStyles() {}
-void QFontDialog::updateSizes() {}
-QFont QFontDialog::getFont(bool *, const QFont *, QWidget *) { return QFont(); }
-
-class Q_GUI_EXPORT QInputDialog
-{
-private:
- enum Type { LineEdit, SpinBox, DoubleSpinBox, ComboBox, EditableComboBox };
-
- QInputDialog(const QString &, QWidget *, Type, Qt::WindowFlags);
- QInputDialog(const QString &, const QString &, QWidget *, QWidget *, Qt::WindowFlags);
- ~QInputDialog();
-};
-
-QInputDialog::QInputDialog(const QString &, QWidget *, Type, Qt::WindowFlags) {}
-QInputDialog::QInputDialog(const QString &, const QString &, QWidget *, QWidget *, Qt::WindowFlags) {}
-QInputDialog::~QInputDialog() {}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qerrormessage.cpp b/src/gui/dialogs/qerrormessage.cpp
deleted file mode 100644
index 6d474cc4f9..0000000000
--- a/src/gui/dialogs/qerrormessage.cpp
+++ /dev/null
@@ -1,429 +0,0 @@
-/****************************************************************************
-**
-** 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 "qerrormessage.h"
-
-#ifndef QT_NO_ERRORMESSAGE
-
-#include "qapplication.h"
-#include "qcheckbox.h"
-#include "qlabel.h"
-#include "qlayout.h"
-#include "qmessagebox.h"
-#include "qpushbutton.h"
-#include "qstringlist.h"
-#include "qtextedit.h"
-#include "qdialog_p.h"
-#include "qpixmap.h"
-#include "qmetaobject.h"
-#include "qthread.h"
-#include "qqueue.h"
-#include "qset.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#ifdef Q_WS_WINCE
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_high_dpi(); //defined in qguifunctions_wince.cpp
-
-#include "qguifunctions_wince.h"
-#endif
-
-#if defined(QT_SOFTKEYS_ENABLED)
-#include <qaction.h>
-#endif
-#ifdef Q_WS_S60
-#include "private/qt_s60_p.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QErrorMessagePrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QErrorMessage)
-public:
- QPushButton * ok;
- QCheckBox * again;
- QTextEdit * errors;
- QLabel * icon;
-#ifdef QT_SOFTKEYS_ENABLED
- QAction *okAction;
-#endif
- QQueue<QPair<QString, QString> > pending;
- QSet<QString> doNotShow;
- QSet<QString> doNotShowType;
- QString currentMessage;
- QString currentType;
-
- bool nextPending();
- void retranslateStrings();
-};
-
-class QErrorMessageTextView : public QTextEdit
-{
-public:
- QErrorMessageTextView(QWidget *parent)
- : QTextEdit(parent) { setReadOnly(true); }
-
- virtual QSize minimumSizeHint() const;
- virtual QSize sizeHint() const;
-};
-
-QSize QErrorMessageTextView::minimumSizeHint() const
-{
-#ifdef Q_WS_WINCE
- if (qt_wince_is_mobile())
- if (qt_wince_is_high_dpi())
- return QSize(200, 200);
- else
- return QSize(100, 100);
- else
- return QSize(70, 70);
-#else
- return QSize(50, 50);
-#endif
-}
-
-QSize QErrorMessageTextView::sizeHint() const
-{
-#ifdef Q_WS_WINCE
- if (qt_wince_is_mobile())
- if (qt_wince_is_high_dpi())
- return QSize(400, 200);
- else
- return QSize(320, 120);
- else
- return QSize(300, 100);
-#else
-
-#ifdef Q_WS_S60
- const int smallerDimension = qMin(S60->screenHeightInPixels, S60->screenWidthInPixels);
- // In S60 layout data, error messages seem to be one third of the screen height (in portrait) minus two.
- return QSize(smallerDimension, smallerDimension/3-2);
-#else
- return QSize(250, 75);
-#endif //Q_WS_S60
-#endif //Q_WS_WINCE
-}
-
-/*!
- \class QErrorMessage
-
- \brief The QErrorMessage class provides an error message display dialog.
-
- \ingroup standard-dialog
-
- An error message widget consists of a text label and a checkbox. The
- checkbox lets the user control whether the same error message will be
- displayed again in the future, typically displaying the text,
- "Show this message again" translated into the appropriate local
- language.
-
- For production applications, the class can be used to display messages which
- the user only needs to see once. To use QErrorMessage like this, you create
- the dialog in the usual way, and show it by calling the showMessage() slot or
- connecting signals to it.
-
- The static qtHandler() function installs a message handler
- using qInstallMsgHandler() and creates a QErrorMessage that displays
- qDebug(), qWarning() and qFatal() messages. This is most useful in
- environments where no console is available to display warnings and
- error messages.
-
- In both cases QErrorMessage will queue pending messages and display
- them in order, with each new message being shown as soon as the user
- has accepted the previous message. Once the user has specified that a
- message is not to be shown again it is automatically skipped, and the
- dialog will show the next appropriate message in the queue.
-
- The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
- how to use QErrorMessage as well as other built-in Qt dialogs.
-
- \img qerrormessage.png
-
- \sa QMessageBox, QStatusBar::showMessage(), {Standard Dialogs Example}
-*/
-
-static QErrorMessage * qtMessageHandler = 0;
-
-static void deleteStaticcQErrorMessage() // post-routine
-{
- if (qtMessageHandler) {
- delete qtMessageHandler;
- qtMessageHandler = 0;
- }
-}
-
-static bool metFatal = false;
-
-static void jump(QtMsgType t, const char * m)
-{
- if (!qtMessageHandler)
- return;
-
- QString rich;
-
- switch (t) {
- case QtDebugMsg:
- default:
- rich = QErrorMessage::tr("Debug Message:");
- break;
- case QtWarningMsg:
- rich = QErrorMessage::tr("Warning:");
- break;
- case QtFatalMsg:
- rich = QErrorMessage::tr("Fatal Error:");
- }
- rich = QString::fromLatin1("<p><b>%1</b></p>").arg(rich);
- rich += Qt::convertFromPlainText(QLatin1String(m), Qt::WhiteSpaceNormal);
-
- // ### work around text engine quirk
- if (rich.endsWith(QLatin1String("</p>")))
- rich.chop(4);
-
- if (!metFatal) {
- if (QThread::currentThread() == qApp->thread()) {
- qtMessageHandler->showMessage(rich);
- } else {
- QMetaObject::invokeMethod(qtMessageHandler,
- "showMessage",
- Qt::QueuedConnection,
- Q_ARG(QString, rich));
- }
- metFatal = (t == QtFatalMsg);
- }
-}
-
-
-/*!
- Constructs and installs an error handler window with the given \a
- parent.
-*/
-
-QErrorMessage::QErrorMessage(QWidget * parent)
- : QDialog(*new QErrorMessagePrivate, parent)
-{
- Q_D(QErrorMessage);
- QGridLayout * grid = new QGridLayout(this);
- d->icon = new QLabel(this);
-#ifndef QT_NO_MESSAGEBOX
- d->icon->setPixmap(QMessageBox::standardIcon(QMessageBox::Information));
- d->icon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
-#endif
- grid->addWidget(d->icon, 0, 0, Qt::AlignTop);
- d->errors = new QErrorMessageTextView(this);
- grid->addWidget(d->errors, 0, 1);
- d->again = new QCheckBox(this);
- d->again->setChecked(true);
- grid->addWidget(d->again, 1, 1, Qt::AlignTop);
- d->ok = new QPushButton(this);
-#ifdef QT_SOFTKEYS_ENABLED
- d->okAction = new QAction(d->ok);
- d->okAction->setSoftKeyRole(QAction::PositiveSoftKey);
- connect(d->okAction, SIGNAL(triggered()), this, SLOT(accept()));
- addAction(d->okAction);
-#endif
-
-
-#if defined(Q_WS_WINCE) || defined(Q_WS_S60)
- d->ok->setFixedSize(0,0);
-#endif
- connect(d->ok, SIGNAL(clicked()), this, SLOT(accept()));
- d->ok->setFocus();
- grid->addWidget(d->ok, 2, 0, 1, 2, Qt::AlignCenter);
- grid->setColumnStretch(1, 42);
- grid->setRowStretch(0, 42);
- d->retranslateStrings();
-}
-
-
-/*!
- Destroys the error message dialog.
-*/
-
-QErrorMessage::~QErrorMessage()
-{
- if (this == qtMessageHandler) {
- qtMessageHandler = 0;
- QtMsgHandler tmp = qInstallMsgHandler(0);
- // in case someone else has later stuck in another...
- if (tmp != jump)
- qInstallMsgHandler(tmp);
- }
-}
-
-
-/*! \reimp */
-
-void QErrorMessage::done(int a)
-{
- Q_D(QErrorMessage);
- if (!d->again->isChecked() && !d->currentMessage.isEmpty() && d->currentType.isEmpty()) {
- d->doNotShow.insert(d->currentMessage);
- }
- if (!d->again->isChecked() && !d->currentType.isEmpty()) {
- d->doNotShowType.insert(d->currentType);
- }
- d->currentMessage.clear();
- d->currentType.clear();
- if (!d->nextPending()) {
- QDialog::done(a);
- if (this == qtMessageHandler && metFatal)
- exit(1);
- }
-}
-
-
-/*!
- Returns a pointer to a QErrorMessage object that outputs the
- default Qt messages. This function creates such an object, if there
- isn't one already.
-*/
-
-QErrorMessage * QErrorMessage::qtHandler()
-{
- if (!qtMessageHandler) {
- qtMessageHandler = new QErrorMessage(0);
- qAddPostRoutine(deleteStaticcQErrorMessage); // clean up
- qtMessageHandler->setWindowTitle(QApplication::applicationName());
- qInstallMsgHandler(jump);
- }
- return qtMessageHandler;
-}
-
-
-/*! \internal */
-
-bool QErrorMessagePrivate::nextPending()
-{
- while (!pending.isEmpty()) {
- QPair<QString,QString> pendingMessage = pending.dequeue();
- QString message = pendingMessage.first;
- QString type = pendingMessage.second;
- if (!message.isEmpty() && ((type.isEmpty() && !doNotShow.contains(message)) || (!type.isEmpty() && !doNotShowType.contains(type)))) {
-#ifndef QT_NO_TEXTHTMLPARSER
- errors->setHtml(message);
-#else
- errors->setPlainText(message);
-#endif
- currentMessage = message;
- currentType = type;
- return true;
- }
- }
- return false;
-}
-
-
-/*!
- Shows the given message, \a message, and returns immediately. If the user
- has requested for the message not to be shown again, this function does
- nothing.
-
- Normally, the message is displayed immediately. However, if there are
- pending messages, it will be queued to be displayed later.
-*/
-
-void QErrorMessage::showMessage(const QString &message)
-{
- Q_D(QErrorMessage);
- if (d->doNotShow.contains(message))
- return;
- d->pending.enqueue(qMakePair(message,QString()));
- if (!isVisible() && d->nextPending())
- show();
-}
-
-/*!
- \since 4.5
- \overload
-
- Shows the given message, \a message, and returns immediately. If the user
- has requested for messages of type, \a type, not to be shown again, this
- function does nothing.
-
- Normally, the message is displayed immediately. However, if there are
- pending messages, it will be queued to be displayed later.
-
- \sa showMessage()
-*/
-
-void QErrorMessage::showMessage(const QString &message, const QString &type)
-{
- Q_D(QErrorMessage);
- if (d->doNotShow.contains(message) && d->doNotShowType.contains(type))
- return;
- d->pending.push_back(qMakePair(message,type));
- if (!isVisible() && d->nextPending())
- show();
-}
-
-/*!
- \reimp
-*/
-void QErrorMessage::changeEvent(QEvent *e)
-{
- Q_D(QErrorMessage);
- if (e->type() == QEvent::LanguageChange) {
- d->retranslateStrings();
- }
- QDialog::changeEvent(e);
-}
-
-void QErrorMessagePrivate::retranslateStrings()
-{
- again->setText(QErrorMessage::tr("&Show this message again"));
- ok->setText(QErrorMessage::tr("&OK"));
-#ifdef QT_SOFTKEYS_ENABLED
- okAction->setText(ok->text());
-#endif
-}
-
-/*!
- \fn void QErrorMessage::message(const QString & message)
-
- Use showMessage(\a message) instead.
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ERRORMESSAGE
diff --git a/src/gui/dialogs/qerrormessage.h b/src/gui/dialogs/qerrormessage.h
deleted file mode 100644
index 500482c722..0000000000
--- a/src/gui/dialogs/qerrormessage.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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 QERRORMESSAGE_H
-#define QERRORMESSAGE_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ERRORMESSAGE
-
-class QErrorMessagePrivate;
-
-class Q_GUI_EXPORT QErrorMessage: public QDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QErrorMessage)
-public:
- explicit QErrorMessage(QWidget* parent = 0);
- ~QErrorMessage();
-
- static QErrorMessage * qtHandler();
-
-public Q_SLOTS:
- void showMessage(const QString &message);
- void showMessage(const QString &message, const QString &type);
-#ifdef QT3_SUPPORT
- inline QT_MOC_COMPAT void message(const QString &text) { showMessage(text); }
-#endif
-
-protected:
- void done(int);
- void changeEvent(QEvent *e);
-
-private:
- Q_DISABLE_COPY(QErrorMessage)
-};
-
-#endif // QT_NO_ERRORMESSAGE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QERRORMESSAGE_H
diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp
deleted file mode 100644
index 897a9164a2..0000000000
--- a/src/gui/dialogs/qfiledialog.cpp
+++ /dev/null
@@ -1,3486 +0,0 @@
-/****************************************************************************
-**
-** 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 <qvariant.h>
-#include <private/qwidgetitemdata_p.h>
-#include "qfiledialog.h"
-
-#ifndef QT_NO_FILEDIALOG
-#include "qfiledialog_p.h"
-#include <qfontmetrics.h>
-#include <qaction.h>
-#include <qheaderview.h>
-#include <qshortcut.h>
-#include <qgridlayout.h>
-#include <qmenu.h>
-#include <qmessagebox.h>
-#include <qinputdialog.h>
-#include <stdlib.h>
-#include <qsettings.h>
-#include <qdebug.h>
-#include <qapplication.h>
-#include <qstylepainter.h>
-#if !defined(Q_WS_WINCE) && !defined(Q_OS_SYMBIAN)
-#include "ui_qfiledialog.h"
-#else
-#define Q_EMBEDDED_SMALLSCREEN
-#include "ui_qfiledialog_embedded.h"
-#if defined(Q_OS_WINCE)
-extern bool qt_priv_ptr_valid;
-#endif
-#endif
-
-QT_BEGIN_NAMESPACE
-
-Q_GLOBAL_STATIC(QString, lastVisitedDir)
-
-/*
- \internal
-
- Exported hooks that can be used to customize the static functions.
- */
-typedef QString (*_qt_filedialog_existing_directory_hook)(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options);
-Q_GUI_EXPORT _qt_filedialog_existing_directory_hook qt_filedialog_existing_directory_hook = 0;
-
-typedef QString (*_qt_filedialog_open_filename_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
-Q_GUI_EXPORT _qt_filedialog_open_filename_hook qt_filedialog_open_filename_hook = 0;
-
-typedef QStringList (*_qt_filedialog_open_filenames_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
-Q_GUI_EXPORT _qt_filedialog_open_filenames_hook qt_filedialog_open_filenames_hook = 0;
-
-typedef QString (*_qt_filedialog_save_filename_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
-Q_GUI_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook = 0;
-
-/*!
- \class QFileDialog
- \brief The QFileDialog class provides a dialog that allow users to select files or directories.
- \ingroup standard-dialogs
-
-
- The QFileDialog class enables a user to traverse the file system in
- order to select one or many files or a directory.
-
- The easiest way to create a QFileDialog is to use the static
- functions. On Windows, Mac OS X, KDE and GNOME, these static functions will
- call the native file dialog when possible.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 0
-
- In the above example, a modal QFileDialog is created using a static
- function. The dialog initially displays the contents of the "/home/jana"
- directory, and displays files matching the patterns given in the
- string "Image Files (*.png *.jpg *.bmp)". The parent of the file dialog
- is set to \e this, and the window title is set to "Open Image".
-
- If you want to use multiple filters, separate each one with
- \e two semicolons. For example:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 1
-
- You can create your own QFileDialog without using the static
- functions. By calling setFileMode(), you can specify what the user must
- select in the dialog:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 2
-
- In the above example, the mode of the file dialog is set to
- AnyFile, meaning that the user can select any file, or even specify a
- file that doesn't exist. This mode is useful for creating a
- "Save As" file dialog. Use ExistingFile if the user must select an
- existing file, or \l Directory if only a directory may be selected.
- See the \l QFileDialog::FileMode enum for the complete list of modes.
-
- The fileMode property contains the mode of operation for the dialog;
- this indicates what types of objects the user is expected to select.
- Use setNameFilter() to set the dialog's file filter. For example:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 3
-
- In the above example, the filter is set to \c{"Images (*.png *.xpm *.jpg)"},
- this means that only files with the extension \c png, \c xpm,
- or \c jpg will be shown in the QFileDialog. You can apply
- several filters by using setNameFilters(). Use selectNameFilter() to select
- one of the filters you've given as the file dialog's default filter.
-
- The file dialog has two view modes: \l{QFileDialog::}{List} and
- \l{QFileDialog::}{Detail}.
- \l{QFileDialog::}{List} presents the contents of the current directory
- as a list of file and directory names. \l{QFileDialog::}{Detail} also
- displays a list of file and directory names, but provides additional
- information alongside each name, such as the file size and modification
- date. Set the mode with setViewMode():
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 4
-
- The last important function you will need to use when creating your
- own file dialog is selectedFiles().
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 5
-
- In the above example, a modal file dialog is created and shown. If
- the user clicked OK, the file they selected is put in \c fileName.
-
- The dialog's working directory can be set with setDirectory().
- Each file in the current directory can be selected using
- the selectFile() function.
-
- The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
- how to use QFileDialog as well as other built-in Qt dialogs.
-
- \sa QDir, QFileInfo, QFile, QPrintDialog, QColorDialog, QFontDialog, {Standard Dialogs Example},
- {Application Example}
-*/
-
-/*!
- \enum QFileDialog::AcceptMode
-
- \value AcceptOpen
- \value AcceptSave
-*/
-
-/*!
- \enum QFileDialog::ViewMode
-
- This enum describes the view mode of the file dialog; i.e. what
- information about each file will be displayed.
-
- \value Detail Displays an icon, a name, and details for each item in
- the directory.
- \value List Displays only an icon and a name for each item in the
- directory.
-
- \sa setViewMode()
-*/
-
-/*!
- \enum QFileDialog::FileMode
-
- This enum is used to indicate what the user may select in the file
- dialog; i.e. what the dialog will return if the user clicks OK.
-
- \value AnyFile The name of a file, whether it exists or not.
- \value ExistingFile The name of a single existing file.
- \value Directory The name of a directory. Both files and
- directories are displayed.
- \value ExistingFiles The names of zero or more existing files.
-
- This value is obsolete since Qt 4.5:
-
- \value DirectoryOnly Use \c Directory and setOption(ShowDirsOnly, true) instead.
-
- \sa setFileMode()
-*/
-
-/*!
- \enum QFileDialog::Option
-
- \value ShowDirsOnly Only show directories in the file dialog. By
- default both files and directories are shown. (Valid only in the
- \l Directory file mode.)
-
- \value DontResolveSymlinks Don't resolve symlinks in the file
- dialog. By default symlinks are resolved.
-
- \value DontConfirmOverwrite Don't ask for confirmation if an
- existing file is selected. By default confirmation is requested.
-
- \value DontUseNativeDialog Don't use the native file dialog. By
- default, the native file dialog is used unless you use a subclass
- of QFileDialog that contains the Q_OBJECT macro.
-
- \value ReadOnly Indicates that the model is readonly.
-
- \value HideNameFilterDetails Indicates if the file name filter details are
- hidden or not.
-
- \value DontUseSheet In previous versions of Qt, the static
- functions would create a sheet by default if the static function
- was given a parent. This is no longer supported and does nothing in Qt 4.5, The
- static functions will always be an application modal dialog. If
- you want to use sheets, use QFileDialog::open() instead.
-
-*/
-
-/*!
- \enum QFileDialog::DialogLabel
-
- \value LookIn
- \value FileName
- \value FileType
- \value Accept
- \value Reject
-*/
-
-/*!
- \fn void QFileDialog::filesSelected(const QStringList &selected)
-
- When the selection changes and the dialog is accepted, this signal is
- emitted with the (possibly empty) list of \a selected files.
-
- \sa currentChanged(), QDialog::Accepted
-*/
-
-
-/*!
- \fn void QFileDialog::fileSelected(const QString &file)
-
- When the selection changes and the dialog is accepted, this signal is
- emitted with the (possibly empty) selected \a file.
-
- \sa currentChanged(), QDialog::Accepted
-*/
-
-
-/*!
- \fn void QFileDialog::currentChanged(const QString &path)
-
- When the current file changes, this signal is emitted with the
- new file name as the \a path parameter.
-
- \sa filesSelected()
-*/
-
-/*!
- \fn void QFileDialog::directoryEntered(const QString &directory)
- \since 4.3
-
- This signal is emitted when the user enters a \a directory.
-*/
-
-/*!
- \fn void QFileDialog::filterSelected(const QString &filter)
- \since 4.3
-
- This signal is emitted when the user selects a \a filter.
-*/
-
-#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
-bool Q_GUI_EXPORT qt_use_native_dialogs = true; // for the benefit of testing tools, until we have a proper API
-#endif
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#ifdef Q_WS_WIN
-#include <qwindowsstyle.h>
-#endif
-#include <qshortcut.h>
-#ifdef Q_WS_MAC
-#include <qmacstyle_mac.h>
-#endif
-QT_END_INCLUDE_NAMESPACE
-
-/*!
- \fn QFileDialog::QFileDialog(QWidget *parent, Qt::WindowFlags flags)
-
- Constructs a file dialog with the given \a parent and widget \a flags.
-*/
-QFileDialog::QFileDialog(QWidget *parent, Qt::WindowFlags f)
- : QDialog(*new QFileDialogPrivate, parent, f)
-{
- Q_D(QFileDialog);
- d->init();
- d->lineEdit()->selectAll();
-}
-
-/*!
- Constructs a file dialog with the given \a parent and \a caption that
- initially displays the contents of the specified \a directory.
- The contents of the directory are filtered before being shown in the
- dialog, using a semicolon-separated list of filters specified by
- \a filter.
-*/
-QFileDialog::QFileDialog(QWidget *parent,
- const QString &caption,
- const QString &directory,
- const QString &filter)
- : QDialog(*new QFileDialogPrivate, parent, 0)
-{
- Q_D(QFileDialog);
- d->init(directory, filter, caption);
- d->lineEdit()->selectAll();
-}
-
-/*!
- \internal
-*/
-QFileDialog::QFileDialog(const QFileDialogArgs &args)
- : QDialog(*new QFileDialogPrivate, args.parent, 0)
-{
- Q_D(QFileDialog);
- d->init(args.directory, args.filter, args.caption);
- setFileMode(args.mode);
- setOptions(args.options);
- selectFile(args.selection);
- d->lineEdit()->selectAll();
-}
-
-/*!
- Destroys the file dialog.
-*/
-QFileDialog::~QFileDialog()
-{
- Q_D(QFileDialog);
-#ifndef QT_NO_SETTINGS
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- settings.beginGroup(QLatin1String("Qt"));
- settings.setValue(QLatin1String("filedialog"), saveState());
-#endif
- d->deleteNativeDialog_sys();
-}
-
-/*!
- \since 4.3
- Sets the \a urls that are located in the sidebar.
-
- For instance:
-
- \snippet doc/src/snippets/filedialogurls.cpp 0
-
- The file dialog will then look like this:
-
- \image filedialogurls.png
-
- \sa sidebarUrls()
-*/
-void QFileDialog::setSidebarUrls(const QList<QUrl> &urls)
-{
- Q_D(QFileDialog);
- d->qFileDialogUi->sidebar->setUrls(urls);
-}
-
-/*!
- \since 4.3
- Returns a list of urls that are currently in the sidebar
-*/
-QList<QUrl> QFileDialog::sidebarUrls() const
-{
- Q_D(const QFileDialog);
- return d->qFileDialogUi->sidebar->urls();
-}
-
-static const qint32 QFileDialogMagic = 0xbe;
-
-const char *qt_file_dialog_filter_reg_exp =
-"^(.*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$";
-
-/*!
- \since 4.3
- Saves the state of the dialog's layout, history and current directory.
-
- Typically this is used in conjunction with QSettings to remember the size
- for a future session. A version number is stored as part of the data.
-*/
-QByteArray QFileDialog::saveState() const
-{
- Q_D(const QFileDialog);
- int version = 3;
- QByteArray data;
- QDataStream stream(&data, QIODevice::WriteOnly);
-
- stream << qint32(QFileDialogMagic);
- stream << qint32(version);
- stream << d->qFileDialogUi->splitter->saveState();
- stream << d->qFileDialogUi->sidebar->urls();
- stream << history();
- stream << *lastVisitedDir();
- stream << d->qFileDialogUi->treeView->header()->saveState();
- stream << qint32(viewMode());
- return data;
-}
-
-/*!
- \since 4.3
- Restores the dialogs's layout, history and current directory to the \a state specified.
-
- Typically this is used in conjunction with QSettings to restore the size
- from a past session.
-
- Returns false if there are errors
-*/
-bool QFileDialog::restoreState(const QByteArray &state)
-{
- Q_D(QFileDialog);
- int version = 3;
- QByteArray sd = state;
- QDataStream stream(&sd, QIODevice::ReadOnly);
- if (stream.atEnd())
- return false;
- QByteArray splitterState;
- QByteArray headerData;
- QList<QUrl> bookmarks;
- QStringList history;
- QString currentDirectory;
- qint32 marker;
- qint32 v;
- qint32 viewMode;
- stream >> marker;
- stream >> v;
- if (marker != QFileDialogMagic || v != version)
- return false;
-
- stream >> splitterState
- >> bookmarks
- >> history
- >> currentDirectory
- >> headerData
- >> viewMode;
-
- if (!d->qFileDialogUi->splitter->restoreState(splitterState))
- return false;
- QList<int> list = d->qFileDialogUi->splitter->sizes();
- if (list.count() >= 2 && list.at(0) == 0 && list.at(1) == 0) {
- for (int i = 0; i < list.count(); ++i)
- list[i] = d->qFileDialogUi->splitter->widget(i)->sizeHint().width();
- d->qFileDialogUi->splitter->setSizes(list);
- }
-
- d->qFileDialogUi->sidebar->setUrls(bookmarks);
- while (history.count() > 5)
- history.pop_front();
- setHistory(history);
- setDirectory(lastVisitedDir()->isEmpty() ? currentDirectory : *lastVisitedDir());
- if (!d->qFileDialogUi->treeView->header()->restoreState(headerData))
- return false;
-
- setViewMode(ViewMode(viewMode));
- return true;
-}
-
-/*!
- \reimp
-*/
-void QFileDialog::changeEvent(QEvent *e)
-{
- Q_D(QFileDialog);
- if (e->type() == QEvent::LanguageChange) {
- d->retranslateWindowTitle();
- d->retranslateStrings();
- }
- QDialog::changeEvent(e);
-}
-
-QFileDialogPrivate::QFileDialogPrivate()
- :
-#ifndef QT_NO_PROXYMODEL
- proxyModel(0),
-#endif
- model(0),
- fileMode(QFileDialog::AnyFile),
- acceptMode(QFileDialog::AcceptOpen),
- currentHistoryLocation(-1),
- renameAction(0),
- deleteAction(0),
- showHiddenAction(0),
- useDefaultCaption(true),
- defaultFileTypes(true),
- fileNameLabelExplicitlySat(false),
- nativeDialogInUse(false),
-#ifdef Q_WS_MAC
- mDelegate(0),
-#ifndef QT_MAC_USE_COCOA
- mDialog(0),
- mDialogStarted(false),
- mDialogClosed(true),
-#endif
-#endif
- qFileDialogUi(0)
-{
-}
-
-QFileDialogPrivate::~QFileDialogPrivate()
-{
-}
-
-void QFileDialogPrivate::retranslateWindowTitle()
-{
- Q_Q(QFileDialog);
- if (!useDefaultCaption || setWindowTitle != q->windowTitle())
- return;
- if (acceptMode == QFileDialog::AcceptOpen) {
- if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory)
- q->setWindowTitle(QFileDialog::tr("Find Directory"));
- else
- q->setWindowTitle(QFileDialog::tr("Open"));
- } else
- q->setWindowTitle(QFileDialog::tr("Save As"));
-
- setWindowTitle = q->windowTitle();
-}
-
-void QFileDialogPrivate::setLastVisitedDirectory(const QString &dir)
-{
- *lastVisitedDir() = dir;
-}
-
-void QFileDialogPrivate::retranslateStrings()
-{
- Q_Q(QFileDialog);
- /* WIDGETS */
- if (defaultFileTypes)
- q->setNameFilter(QFileDialog::tr("All Files (*)"));
-
- QList<QAction*> actions = qFileDialogUi->treeView->header()->actions();
- QAbstractItemModel *abstractModel = model;
-#ifndef QT_NO_PROXYMODEL
- if (proxyModel)
- abstractModel = proxyModel;
-#endif
- int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 1);
- for (int i = 1; i < total; ++i) {
- actions.at(i - 1)->setText(QFileDialog::tr("Show ") + abstractModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString());
- }
-
- /* MENU ACTIONS */
- renameAction->setText(QFileDialog::tr("&Rename"));
- deleteAction->setText(QFileDialog::tr("&Delete"));
- showHiddenAction->setText(QFileDialog::tr("Show &hidden files"));
- newFolderAction->setText(QFileDialog::tr("&New Folder"));
- qFileDialogUi->retranslateUi(q);
-
- if (!fileNameLabelExplicitlySat){
- if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory) {
- q->setLabelText(QFileDialog::FileName, QFileDialog::tr("Directory:"));
- } else {
- q->setLabelText(QFileDialog::FileName, QFileDialog::tr("File &name:"));
- }
- fileNameLabelExplicitlySat = false;
- }
-}
-
-void QFileDialogPrivate::emitFilesSelected(const QStringList &files)
-{
- Q_Q(QFileDialog);
- emit q->filesSelected(files);
- if (files.count() == 1)
- emit q->fileSelected(files.first());
-}
-
-bool QFileDialogPrivate::canBeNativeDialog()
-{
- Q_Q(QFileDialog);
- if (nativeDialogInUse)
- return true;
- if (q->testAttribute(Qt::WA_DontShowOnScreen))
- return false;
- if (opts & QFileDialog::DontUseNativeDialog)
- return false;
-
- QLatin1String staticName(QFileDialog::staticMetaObject.className());
- QLatin1String dynamicName(q->metaObject()->className());
- return (staticName == dynamicName);
-}
-
-/*!
- \since 4.5
- Sets the given \a option to be enabled if \a on is true; otherwise,
- clears the given \a option.
-
- \sa options, testOption()
-*/
-void QFileDialog::setOption(Option option, bool on)
-{
- Q_D(QFileDialog);
- if (!(d->opts & option) != !on)
- setOptions(d->opts ^ option);
-}
-
-/*!
- \since 4.5
-
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QFileDialog::testOption(Option option) const
-{
- Q_D(const QFileDialog);
- return (d->opts & option) != 0;
-}
-
-/*!
- \property QFileDialog::options
- \brief the various options that affect the look and feel of the dialog
- \since 4.5
-
- By default, all options are disabled.
-
- Options should be set before showing the dialog. Setting them while the
- dialog is visible is not guaranteed to have an immediate effect on the
- dialog (depending on the option and on the platform).
-
- \sa setOption(), testOption()
-*/
-void QFileDialog::setOptions(Options options)
-{
- Q_D(QFileDialog);
-
- Options changed = (options ^ d->opts);
- if (!changed)
- return;
-
- d->opts = options;
- if (changed & DontResolveSymlinks)
- d->model->setResolveSymlinks(!(options & DontResolveSymlinks));
- if (changed & ReadOnly) {
- bool ro = (options & ReadOnly);
- d->model->setReadOnly(ro);
- d->qFileDialogUi->newFolderButton->setEnabled(!ro);
- d->renameAction->setEnabled(!ro);
- d->deleteAction->setEnabled(!ro);
- }
- if (changed & HideNameFilterDetails)
- setNameFilters(d->nameFilters);
-
- if (changed & ShowDirsOnly)
- setFilter((options & ShowDirsOnly) ? filter() & ~QDir::Files : filter() | QDir::Files);
-}
-
-QFileDialog::Options QFileDialog::options() const
-{
- Q_D(const QFileDialog);
- return d->opts;
-}
-
-/*!
- \overload
-
- \since 4.5
-
- This function connects one of its signals to the slot specified by \a receiver
- and \a member. The specific signal depends is filesSelected() if fileMode is
- ExistingFiles and fileSelected() if fileMode is anything else.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QFileDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QFileDialog);
- const char *signal = (fileMode() == ExistingFiles) ? SIGNAL(filesSelected(QStringList))
- : SIGNAL(fileSelected(QString));
- connect(this, signal, receiver, member);
- d->signalToDisconnectOnClose = signal;
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
-
- QDialog::open();
-}
-
-
-/*!
- \reimp
-*/
-void QFileDialog::setVisible(bool visible)
-{
- Q_D(QFileDialog);
- if (visible){
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
- } else if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
-
- if (d->canBeNativeDialog()){
- if (d->setVisible_sys(visible)){
- d->nativeDialogInUse = true;
- // Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
- // updates the state correctly, but skips showing the non-native version:
- setAttribute(Qt::WA_DontShowOnScreen);
-#ifndef QT_NO_FSCOMPLETER
- //So the completer don't try to complete and therefore to show a popup
- d->completer->setModel(0);
-#endif
- } else {
- d->nativeDialogInUse = false;
- setAttribute(Qt::WA_DontShowOnScreen, false);
-#ifndef QT_NO_FSCOMPLETER
- if (d->proxyModel != 0)
- d->completer->setModel(d->proxyModel);
- else
- d->completer->setModel(d->model);
-#endif
- }
- }
-
- if (!d->nativeDialogInUse)
- d->qFileDialogUi->fileNameEdit->setFocus();
-
- QDialog::setVisible(visible);
-}
-
-/*!
- \internal
- set the directory to url
-*/
-void QFileDialogPrivate::_q_goToUrl(const QUrl &url)
-{
- //The shortcut in the side bar may have a parent that is not fetched yet (e.g. an hidden file)
- //so we force the fetching
- QFileSystemModelPrivate::QFileSystemNode *node = model->d_func()->node(url.toLocalFile(), true);
- QModelIndex idx = model->d_func()->index(node);
- _q_enterDirectory(idx);
-}
-
-/*!
- \fn void QFileDialog::setDirectory(const QDir &directory)
-
- \overload
-*/
-
-/*!
- Sets the file dialog's current \a directory.
-*/
-void QFileDialog::setDirectory(const QString &directory)
-{
- Q_D(QFileDialog);
- QString newDirectory = directory;
- QFileInfo info(directory);
- //we remove .. and . from the given path if exist
- if (!directory.isEmpty())
- newDirectory = QDir::cleanPath(directory);
-
- if (!directory.isEmpty() && newDirectory.isEmpty())
- return;
-
- d->setLastVisitedDirectory(newDirectory);
-
- if (d->nativeDialogInUse){
- d->setDirectory_sys(newDirectory);
- return;
- }
- if (d->rootPath() == newDirectory)
- return;
- QModelIndex root = d->model->setRootPath(newDirectory);
- d->qFileDialogUi->newFolderButton->setEnabled(d->model->flags(root) & Qt::ItemIsDropEnabled);
- if (root != d->rootIndex()) {
-#ifndef QT_NO_FSCOMPLETER
- if (directory.endsWith(QLatin1Char('/')))
- d->completer->setCompletionPrefix(newDirectory);
- else
- d->completer->setCompletionPrefix(newDirectory + QLatin1Char('/'));
-#endif
- d->setRootIndex(root);
- }
- d->qFileDialogUi->listView->selectionModel()->clear();
-}
-
-/*!
- Returns the directory currently being displayed in the dialog.
-*/
-QDir QFileDialog::directory() const
-{
- Q_D(const QFileDialog);
- return QDir(d->nativeDialogInUse ? d->directory_sys() : d->rootPath());
-}
-
-/*!
- Selects the given \a filename in the file dialog.
-
- \sa selectedFiles()
-*/
-void QFileDialog::selectFile(const QString &filename)
-{
- Q_D(QFileDialog);
- if (filename.isEmpty())
- return;
-
- if (d->nativeDialogInUse){
- d->selectFile_sys(filename);
- return;
- }
-
- if (!QDir::isRelativePath(filename)) {
- QFileInfo info(filename);
- QString filenamePath = info.absoluteDir().path();
-
- if (d->model->rootPath() != filenamePath)
- setDirectory(filenamePath);
- }
-
- QModelIndex index = d->model->index(filename);
- QString file;
- if (!index.isValid()) {
- // save as dialog where we want to input a default value
- QString text = filename;
- if (QFileInfo(filename).isAbsolute()) {
- QString current = d->rootPath();
- text.remove(current);
- if (text.at(0) == QDir::separator()
-#ifdef Q_OS_WIN
- //On Windows both cases can happen
- || text.at(0) == QLatin1Char('/')
-#endif
- )
- text = text.remove(0,1);
- }
- file = text;
- } else {
- file = index.data().toString();
- }
- d->qFileDialogUi->listView->selectionModel()->clear();
- if (!isVisible() || !d->lineEdit()->hasFocus())
- d->lineEdit()->setText(file);
-}
-
-/**
- Returns the text in the line edit which can be one or more file names
- */
-QStringList QFileDialogPrivate::typedFiles() const
-{
- QStringList files;
- QString editText = lineEdit()->text();
- if (!editText.contains(QLatin1Char('"')))
- files << editText;
- else {
- // " is used to separate files like so: "file1" "file2" "file3" ...
- // ### need escape character for filenames with quotes (")
- QStringList tokens = editText.split(QLatin1Char('\"'));
- for (int i=0; i<tokens.size(); ++i) {
- if ((i % 2) == 0)
- continue; // Every even token is a separator
- files << toInternal(tokens.at(i));
- }
- }
- return addDefaultSuffixToFiles(files);
-}
-
-QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList filesToFix) const
-{
- QStringList files;
- for (int i=0; i<filesToFix.size(); ++i) {
- QString name = toInternal(filesToFix.at(i));
- QFileInfo info(name);
- // if the filename has no suffix, add the default suffix
- if (!defaultSuffix.isEmpty() && !info.isDir() && name.lastIndexOf(QLatin1Char('.')) == -1)
- name += QLatin1Char('.') + defaultSuffix;
- if (info.isAbsolute()) {
- files.append(name);
- } else {
- // at this point the path should only have Qt path separators.
- // This check is needed since we might be at the root directory
- // and on Windows it already ends with slash.
- QString path = rootPath();
- if (!path.endsWith(QLatin1Char('/')))
- path += QLatin1Char('/');
- path += name;
- files.append(path);
- }
- }
- return files;
-}
-
-
-/*!
- Returns a list of strings containing the absolute paths of the
- selected files in the dialog. If no files are selected, or
- the mode is not ExistingFiles or ExistingFile, selectedFiles() contains the current path in the viewport.
-
- \sa selectedNameFilter(), selectFile()
-*/
-QStringList QFileDialog::selectedFiles() const
-{
- Q_D(const QFileDialog);
- if (d->nativeDialogInUse)
- return d->addDefaultSuffixToFiles(d->selectedFiles_sys());
-
- QModelIndexList indexes = d->qFileDialogUi->listView->selectionModel()->selectedRows();
- QStringList files;
- for (int i = 0; i < indexes.count(); ++i)
- files.append(indexes.at(i).data(QFileSystemModel::FilePathRole).toString());
-
- if (files.isEmpty() && !d->lineEdit()->text().isEmpty())
- files = d->typedFiles();
-
- if (files.isEmpty() && !(d->fileMode == ExistingFile || d->fileMode == ExistingFiles))
- files.append(d->rootIndex().data(QFileSystemModel::FilePathRole).toString());
- return files;
-}
-
-/*
- Makes a list of filters from ;;-separated text.
- Used by the mac and windows implementations
-*/
-QStringList qt_make_filter_list(const QString &filter)
-{
- QString f(filter);
-
- if (f.isEmpty())
- return QStringList();
-
- QString sep(QLatin1String(";;"));
- int i = f.indexOf(sep, 0);
- if (i == -1) {
- if (f.indexOf(QLatin1Char('\n'), 0) != -1) {
- sep = QLatin1Char('\n');
- i = f.indexOf(sep, 0);
- }
- }
-
- return f.split(sep);
-}
-
-/*!
- \since 4.4
-
- Sets the filter used in the file dialog to the given \a filter.
-
- If \a filter contains a pair of parentheses containing one or more
- of \bold{anything*something}, separated by spaces, then only the
- text contained in the parentheses is used as the filter. This means
- that these calls are all equivalent:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 6
-
- \sa setNameFilters()
-*/
-void QFileDialog::setNameFilter(const QString &filter)
-{
- setNameFilters(qt_make_filter_list(filter));
-}
-
-/*!
- \obsolete
-
- Use setNameFilter() instead.
-*/
-void QFileDialog::setFilter(const QString &filter)
-{
- setNameFilter(filter);
-}
-
-/*!
- \property QFileDialog::nameFilterDetailsVisible
- \obsolete
- \brief This property holds whether the filter details is shown or not.
- \since 4.4
-
- When this property is true (the default), the filter details are shown
- in the combo box. When the property is set to false, these are hidden.
-
- Use setOption(HideNameFilterDetails, !\e enabled) or
- !testOption(HideNameFilterDetails).
-*/
-void QFileDialog::setNameFilterDetailsVisible(bool enabled)
-{
- setOption(HideNameFilterDetails, !enabled);
-}
-
-bool QFileDialog::isNameFilterDetailsVisible() const
-{
- return !testOption(HideNameFilterDetails);
-}
-
-
-/*
- Strip the filters by removing the details, e.g. (*.*).
-*/
-QStringList qt_strip_filters(const QStringList &filters)
-{
- QStringList strippedFilters;
- QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
- for (int i = 0; i < filters.count(); ++i) {
- QString filterName;
- int index = r.indexIn(filters[i]);
- if (index >= 0)
- filterName = r.cap(1);
- strippedFilters.append(filterName.simplified());
- }
- return strippedFilters;
-}
-
-
-/*!
- \since 4.4
-
- Sets the \a filters used in the file dialog.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 7
-*/
-void QFileDialog::setNameFilters(const QStringList &filters)
-{
- Q_D(QFileDialog);
- d->defaultFileTypes = (filters == QStringList(QFileDialog::tr("All Files (*)")));
- QStringList cleanedFilters;
- for (int i = 0; i < filters.count(); ++i) {
- cleanedFilters << filters[i].simplified();
- }
- d->nameFilters = cleanedFilters;
-
- if (d->nativeDialogInUse){
- d->setNameFilters_sys(cleanedFilters);
- return;
- }
-
- d->qFileDialogUi->fileTypeCombo->clear();
- if (cleanedFilters.isEmpty())
- return;
-
- if (testOption(HideNameFilterDetails))
- d->qFileDialogUi->fileTypeCombo->addItems(qt_strip_filters(cleanedFilters));
- else
- d->qFileDialogUi->fileTypeCombo->addItems(cleanedFilters);
-
- d->_q_useNameFilter(0);
-}
-
-/*!
- \obsolete
-
- Use setNameFilters() instead.
-*/
-void QFileDialog::setFilters(const QStringList &filters)
-{
- setNameFilters(filters);
-}
-
-/*!
- \since 4.4
-
- Returns the file type filters that are in operation on this file
- dialog.
-*/
-QStringList QFileDialog::nameFilters() const
-{
- return d_func()->nameFilters;
-}
-
-/*!
- \obsolete
-
- Use nameFilters() instead.
-*/
-
-QStringList QFileDialog::filters() const
-{
- return nameFilters();
-}
-
-/*!
- \since 4.4
-
- Sets the current file type \a filter. Multiple filters can be
- passed in \a filter by separating them with semicolons or spaces.
-
- \sa setNameFilter(), setNameFilters(), selectedNameFilter()
-*/
-void QFileDialog::selectNameFilter(const QString &filter)
-{
- Q_D(QFileDialog);
- if (d->nativeDialogInUse) {
- d->selectNameFilter_sys(filter);
- return;
- }
- int i;
- if (testOption(HideNameFilterDetails)) {
- i = d->qFileDialogUi->fileTypeCombo->findText(qt_strip_filters(qt_make_filter_list(filter)).first());
- } else {
- i = d->qFileDialogUi->fileTypeCombo->findText(filter);
- }
- if (i >= 0) {
- d->qFileDialogUi->fileTypeCombo->setCurrentIndex(i);
- d->_q_useNameFilter(d->qFileDialogUi->fileTypeCombo->currentIndex());
- }
-}
-
-/*!
- \obsolete
-
- Use selectNameFilter() instead.
-*/
-
-void QFileDialog::selectFilter(const QString &filter)
-{
- selectNameFilter(filter);
-}
-
-/*!
- \since 4.4
-
- Returns the filter that the user selected in the file dialog.
-
- \sa selectedFiles()
-*/
-QString QFileDialog::selectedNameFilter() const
-{
- Q_D(const QFileDialog);
- if (d->nativeDialogInUse)
- return d->selectedNameFilter_sys();
-
- return d->qFileDialogUi->fileTypeCombo->currentText();
-}
-
-/*!
- \obsolete
-
- Use selectedNameFilter() instead.
-*/
-QString QFileDialog::selectedFilter() const
-{
- return selectedNameFilter();
-}
-
-/*!
- \since 4.4
-
- Returns the filter that is used when displaying files.
-
- \sa setFilter()
-*/
-QDir::Filters QFileDialog::filter() const
-{
- Q_D(const QFileDialog);
- return d->model->filter();
-}
-
-/*!
- \since 4.4
-
- Sets the filter used by the model to \a filters. The filter is used
- to specify the kind of files that should be shown.
-
- \sa filter()
-*/
-
-void QFileDialog::setFilter(QDir::Filters filters)
-{
- Q_D(QFileDialog);
- d->model->setFilter(filters);
- if (d->nativeDialogInUse){
- d->setFilter_sys();
- return;
- }
-
- d->showHiddenAction->setChecked((filters & QDir::Hidden));
-}
-
-/*!
- \property QFileDialog::viewMode
- \brief the way files and directories are displayed in the dialog
-
- By default, the \c Detail mode is used to display information about
- files and directories.
-
- \sa ViewMode
-*/
-void QFileDialog::setViewMode(QFileDialog::ViewMode mode)
-{
- Q_D(QFileDialog);
- if (mode == Detail)
- d->_q_showDetailsView();
- else
- d->_q_showListView();
-}
-
-QFileDialog::ViewMode QFileDialog::viewMode() const
-{
- Q_D(const QFileDialog);
- return (d->qFileDialogUi->stackedWidget->currentWidget() == d->qFileDialogUi->listView->parent() ? QFileDialog::List : QFileDialog::Detail);
-}
-
-/*!
- \property QFileDialog::fileMode
- \brief the file mode of the dialog
-
- The file mode defines the number and type of items that the user is
- expected to select in the dialog.
-
- By default, this property is set to AnyFile.
-
- This function will set the labels for the FileName and
- \l{QFileDialog::}{Accept} \l{DialogLabel}s. It is possible to set
- custom text after the call to setFileMode().
-
- \sa FileMode
-*/
-void QFileDialog::setFileMode(QFileDialog::FileMode mode)
-{
- Q_D(QFileDialog);
- d->fileMode = mode;
- d->retranslateWindowTitle();
-
- // keep ShowDirsOnly option in sync with fileMode (BTW, DirectoryOnly is obsolete)
- setOption(ShowDirsOnly, mode == DirectoryOnly);
-
- // set selection mode and behavior
- QAbstractItemView::SelectionMode selectionMode;
- if (mode == QFileDialog::ExistingFiles)
- selectionMode = QAbstractItemView::ExtendedSelection;
- else
- selectionMode = QAbstractItemView::SingleSelection;
- d->qFileDialogUi->listView->setSelectionMode(selectionMode);
- d->qFileDialogUi->treeView->setSelectionMode(selectionMode);
- // set filter
- d->model->setFilter(d->filterForMode(filter()));
- // setup file type for directory
- QString buttonText = (d->acceptMode == AcceptOpen ? tr("&Open") : tr("&Save"));
- if (mode == DirectoryOnly || mode == Directory) {
- d->qFileDialogUi->fileTypeCombo->clear();
- d->qFileDialogUi->fileTypeCombo->addItem(tr("Directories"));
- d->qFileDialogUi->fileTypeCombo->setEnabled(false);
-
- if (!d->fileNameLabelExplicitlySat){
- setLabelText(FileName, tr("Directory:"));
- d->fileNameLabelExplicitlySat = false;
- }
- buttonText = tr("&Choose");
- } else {
- if (!d->fileNameLabelExplicitlySat){
- setLabelText(FileName, tr("File &name:"));
- d->fileNameLabelExplicitlySat = false;
- }
- }
- setLabelText(Accept, buttonText);
- if (d->nativeDialogInUse){
- d->setFilter_sys();
- return;
- }
-
- d->qFileDialogUi->fileTypeCombo->setEnabled(!testOption(ShowDirsOnly));
- d->_q_updateOkButton();
-}
-
-QFileDialog::FileMode QFileDialog::fileMode() const
-{
- Q_D(const QFileDialog);
- return d->fileMode;
-}
-
-/*!
- \property QFileDialog::acceptMode
- \brief the accept mode of the dialog
-
- The action mode defines whether the dialog is for opening or saving files.
-
- By default, this property is set to \l{AcceptOpen}.
-
- \sa AcceptMode
-*/
-void QFileDialog::setAcceptMode(QFileDialog::AcceptMode mode)
-{
- Q_D(QFileDialog);
- d->acceptMode = mode;
- bool directoryMode = (d->fileMode == Directory || d->fileMode == DirectoryOnly);
- QDialogButtonBox::StandardButton button = (mode == AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
- d->qFileDialogUi->buttonBox->setStandardButtons(button | QDialogButtonBox::Cancel);
- d->qFileDialogUi->buttonBox->button(button)->setEnabled(false);
- d->_q_updateOkButton();
- if (mode == AcceptOpen && directoryMode)
- setLabelText(Accept, tr("&Choose"));
- else
- setLabelText(Accept, (mode == AcceptOpen ? tr("&Open") : tr("&Save")));
- if (mode == AcceptSave) {
- d->qFileDialogUi->lookInCombo->setEditable(false);
- }
- d->retranslateWindowTitle();
-#if defined(Q_WS_MAC)
- d->deleteNativeDialog_sys();
- setAttribute(Qt::WA_DontShowOnScreen, false);
-#endif
-}
-
-/*
- Returns the file system model index that is the root index in the
- views
-*/
-QModelIndex QFileDialogPrivate::rootIndex() const {
- return mapToSource(qFileDialogUi->listView->rootIndex());
-}
-
-QAbstractItemView *QFileDialogPrivate::currentView() const {
- if (!qFileDialogUi->stackedWidget)
- return 0;
- if (qFileDialogUi->stackedWidget->currentWidget() == qFileDialogUi->listView->parent())
- return qFileDialogUi->listView;
- return qFileDialogUi->treeView;
-}
-
-QLineEdit *QFileDialogPrivate::lineEdit() const {
- return (QLineEdit*)qFileDialogUi->fileNameEdit;
-}
-
-/*
- Sets the view root index to be the file system model index
-*/
-void QFileDialogPrivate::setRootIndex(const QModelIndex &index) const {
- Q_ASSERT(index.isValid() ? index.model() == model : true);
- QModelIndex idx = mapFromSource(index);
- qFileDialogUi->treeView->setRootIndex(idx);
- qFileDialogUi->listView->setRootIndex(idx);
-}
-/*
- Select a file system model index
- returns the index that was selected (or not depending upon sortfilterproxymodel)
-*/
-QModelIndex QFileDialogPrivate::select(const QModelIndex &index) const {
- Q_ASSERT(index.isValid() ? index.model() == model : true);
-
- QModelIndex idx = mapFromSource(index);
- if (idx.isValid() && !qFileDialogUi->listView->selectionModel()->isSelected(idx))
- qFileDialogUi->listView->selectionModel()->select(idx,
- QItemSelectionModel::Select | QItemSelectionModel::Rows);
- return idx;
-}
-
-QFileDialog::AcceptMode QFileDialog::acceptMode() const
-{
- Q_D(const QFileDialog);
- return d->acceptMode;
-}
-
-/*!
- \property QFileDialog::readOnly
- \obsolete
- \brief Whether the filedialog is read-only
-
- If this property is set to false, the file dialog will allow renaming,
- and deleting of files and directories and creating directories.
-
- Use setOption(ReadOnly, \e enabled) or testOption(ReadOnly) instead.
-*/
-void QFileDialog::setReadOnly(bool enabled)
-{
- setOption(ReadOnly, enabled);
-}
-
-bool QFileDialog::isReadOnly() const
-{
- return testOption(ReadOnly);
-}
-
-/*!
- \property QFileDialog::resolveSymlinks
- \obsolete
- \brief whether the filedialog should resolve shortcuts
-
- If this property is set to true, the file dialog will resolve
- shortcuts or symbolic links.
-
- Use setOption(DontResolveSymlinks, !\a enabled) or
- !testOption(DontResolveSymlinks).
-*/
-void QFileDialog::setResolveSymlinks(bool enabled)
-{
- setOption(DontResolveSymlinks, !enabled);
-}
-
-bool QFileDialog::resolveSymlinks() const
-{
- return !testOption(DontResolveSymlinks);
-}
-
-/*!
- \property QFileDialog::confirmOverwrite
- \obsolete
- \brief whether the filedialog should ask before accepting a selected file,
- when the accept mode is AcceptSave
-
- Use setOption(DontConfirmOverwrite, !\e enabled) or
- !testOption(DontConfirmOverwrite) instead.
-*/
-void QFileDialog::setConfirmOverwrite(bool enabled)
-{
- setOption(DontConfirmOverwrite, !enabled);
-}
-
-bool QFileDialog::confirmOverwrite() const
-{
- return !testOption(DontConfirmOverwrite);
-}
-
-/*!
- \property QFileDialog::defaultSuffix
- \brief suffix added to the filename if no other suffix was specified
-
- This property specifies a string that will be added to the
- filename if it has no suffix already. The suffix is typically
- used to indicate the file type (e.g. "txt" indicates a text
- file).
-*/
-void QFileDialog::setDefaultSuffix(const QString &suffix)
-{
- Q_D(QFileDialog);
- d->defaultSuffix = suffix;
-}
-
-QString QFileDialog::defaultSuffix() const
-{
- Q_D(const QFileDialog);
- return d->defaultSuffix;
-}
-
-/*!
- Sets the browsing history of the filedialog to contain the given
- \a paths.
-*/
-void QFileDialog::setHistory(const QStringList &paths)
-{
- Q_D(QFileDialog);
- d->qFileDialogUi->lookInCombo->setHistory(paths);
-}
-
-void QFileDialogComboBox::setHistory(const QStringList &paths)
-{
- m_history = paths;
- // Only populate the first item, showPopup will populate the rest if needed
- QList<QUrl> list;
- QModelIndex idx = d_ptr->model->index(d_ptr->rootPath());
- //On windows the popup display the "C:\", convert to nativeSeparators
- QUrl url = QUrl::fromLocalFile(QDir::toNativeSeparators(idx.data(QFileSystemModel::FilePathRole).toString()));
- if (url.isValid())
- list.append(url);
- urlModel->setUrls(list);
-}
-
-/*!
- Returns the browsing history of the filedialog as a list of paths.
-*/
-QStringList QFileDialog::history() const
-{
- Q_D(const QFileDialog);
- QStringList currentHistory = d->qFileDialogUi->lookInCombo->history();
- //On windows the popup display the "C:\", convert to nativeSeparators
- QString newHistory = QDir::toNativeSeparators(d->rootIndex().data(QFileSystemModel::FilePathRole).toString());
- if (!currentHistory.contains(newHistory))
- currentHistory << newHistory;
- return currentHistory;
-}
-
-/*!
- Sets the item delegate used to render items in the views in the
- file dialog to the given \a delegate.
-
- \warning You should not share the same instance of a delegate between views.
- Doing so can cause incorrect or unintuitive editing behavior since each
- view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
- signal, and attempt to access, modify or close an editor that has already been closed.
-
- Note that the model used is QFileSystemModel. It has custom item data roles, which is
- described by the \l{QFileSystemModel::}{Roles} enum. You can use a QFileIconProvider if
- you only want custom icons.
-
- \sa itemDelegate(), setIconProvider(), QFileSystemModel
-*/
-void QFileDialog::setItemDelegate(QAbstractItemDelegate *delegate)
-{
- Q_D(QFileDialog);
- d->qFileDialogUi->listView->setItemDelegate(delegate);
- d->qFileDialogUi->treeView->setItemDelegate(delegate);
-}
-
-/*!
- Returns the item delegate used to render the items in the views in the filedialog.
-*/
-QAbstractItemDelegate *QFileDialog::itemDelegate() const
-{
- Q_D(const QFileDialog);
- return d->qFileDialogUi->listView->itemDelegate();
-}
-
-/*!
- Sets the icon provider used by the filedialog to the specified \a provider.
-*/
-void QFileDialog::setIconProvider(QFileIconProvider *provider)
-{
- Q_D(QFileDialog);
- d->model->setIconProvider(provider);
- //It forces the refresh of all entries in the side bar, then we can get new icons
- d->qFileDialogUi->sidebar->setUrls(d->qFileDialogUi->sidebar->urls());
-}
-
-/*!
- Returns the icon provider used by the filedialog.
-*/
-QFileIconProvider *QFileDialog::iconProvider() const
-{
- Q_D(const QFileDialog);
- return d->model->iconProvider();
-}
-
-/*!
- Sets the \a text shown in the filedialog in the specified \a label.
-*/
-void QFileDialog::setLabelText(DialogLabel label, const QString &text)
-{
- Q_D(QFileDialog);
- QPushButton *button;
- switch (label) {
- case LookIn:
- d->qFileDialogUi->lookInLabel->setText(text);
- break;
- case FileName:
- d->qFileDialogUi->fileNameLabel->setText(text);
- d->fileNameLabelExplicitlySat = true;
- break;
- case FileType:
- d->qFileDialogUi->fileTypeLabel->setText(text);
- break;
- case Accept:
- d->acceptLabel = text;
- if (acceptMode() == AcceptOpen)
- button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Open);
- else
- button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Save);
- if (button)
- button->setText(text);
- break;
- case Reject:
- button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Cancel);
- if (button)
- button->setText(text);
- break;
- }
-}
-
-/*!
- Returns the text shown in the filedialog in the specified \a label.
-*/
-QString QFileDialog::labelText(DialogLabel label) const
-{
- QPushButton *button;
- Q_D(const QFileDialog);
- switch (label) {
- case LookIn:
- return d->qFileDialogUi->lookInLabel->text();
- case FileName:
- return d->qFileDialogUi->fileNameLabel->text();
- case FileType:
- return d->qFileDialogUi->fileTypeLabel->text();
- case Accept:
- if (acceptMode() == AcceptOpen)
- button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Open);
- else
- button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Save);
- if (button)
- return button->text();
- case Reject:
- button = d->qFileDialogUi->buttonBox->button(QDialogButtonBox::Cancel);
- if (button)
- return button->text();
- }
- return QString();
-}
-
-/*
- For the native file dialogs
-*/
-
-#if defined(Q_WS_WIN)
-extern QString qt_win_get_open_file_name(const QFileDialogArgs &args,
- QString *initialDirectory,
- QString *selectedFilter);
-
-extern QString qt_win_get_save_file_name(const QFileDialogArgs &args,
- QString *initialDirectory,
- QString *selectedFilter);
-
-extern QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
- QString *initialDirectory,
- QString *selectedFilter);
-
-extern QString qt_win_get_existing_directory(const QFileDialogArgs &args);
-#endif
-
-/*
- For Symbian file dialogs
-*/
-#if defined(Q_WS_S60)
-extern QString qtSymbianGetOpenFileName(const QString &caption,
- const QString &dir,
- const QString &filter);
-
-extern QStringList qtSymbianGetOpenFileNames(const QString &caption,
- const QString &dir,
- const QString &filter);
-
-extern QString qtSymbianGetSaveFileName(const QString &caption,
- const QString &dir);
-
-extern QString qtSymbianGetExistingDirectory(const QString &caption,
- const QString &dir);
-#endif
-
-/*!
- This is a convenience static function that returns an existing file
- selected by the user. If the user presses Cancel, it returns a null string.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 8
-
- The function creates a modal file dialog with the given \a parent widget.
- If \a parent is not 0, the dialog will be shown centered over the parent
- widget.
-
- The file dialog's working directory will be set to \a dir. If \a dir
- includes a file name, the file will be selected. Only files that match the
- given \a filter are shown. The filter selected is set to \a selectedFilter.
- The parameters \a dir, \a selectedFilter, and \a filter may be empty
- strings. If you want multiple filters, separate them with ';;', for
- example:
-
- \code
- "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"
- \endcode
-
- The \a options argument holds various options about how to run the dialog,
- see the QFileDialog::Option enum for more information on the flags you can
- pass.
-
- The dialog's caption is set to \a caption. If \a caption is not specified
- then a default caption will be used.
-
- On Windows, Mac OS X and Symbian^3, this static function will use the
- native file dialog and not a QFileDialog.
-
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not 0 then it will position the
- dialog just below the parent's title bar.
-
- On Unix/X11, the normal behavior of the file dialog is to resolve and
- follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
- \a options includes DontResolveSymlinks, the file dialog will treat
- symlinks as regular directories.
-
- On Symbian^3 the parameter \a selectedFilter has no meaning and the
- \a options parameter is only used to define if the native file dialog is
- used.
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QFileDialog constructors.
-
- \sa getOpenFileNames(), getSaveFileName(), getExistingDirectory()
-*/
-QString QFileDialog::getOpenFileName(QWidget *parent,
- const QString &caption,
- const QString &dir,
- const QString &filter,
- QString *selectedFilter,
- Options options)
-{
- if (qt_filedialog_open_filename_hook && !(options & DontUseNativeDialog))
- return qt_filedialog_open_filename_hook(parent, caption, dir, filter, selectedFilter, options);
-#if defined(Q_WS_S60)
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
- return qtSymbianGetOpenFileName(caption, dir, filter);
-#endif
- QFileDialogArgs args;
- args.parent = parent;
- args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.selection = QFileDialogPrivate::initialSelection(dir);
- args.filter = filter;
- args.mode = ExistingFile;
- args.options = options;
-#if defined(Q_WS_WIN)
- if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog)) {
- return qt_win_get_open_file_name(args, &(args.directory), selectedFilter);
- }
-#endif
-
- // create a qt dialog
- QFileDialog dialog(args);
- if (selectedFilter)
- dialog.selectNameFilter(*selectedFilter);
- if (dialog.exec() == QDialog::Accepted) {
- if (selectedFilter)
- *selectedFilter = dialog.selectedFilter();
- return dialog.selectedFiles().value(0);
- }
- return QString();
-}
-
-/*!
- This is a convenience static function that will return one or more existing
- files selected by the user.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 9
-
- This function creates a modal file dialog with the given \a parent widget.
- If \a parent is not 0, the dialog will be shown centered over the parent
- widget.
-
- The file dialog's working directory will be set to \a dir. If \a dir
- includes a file name, the file will be selected. The filter is set to
- \a filter so that only those files which match the filter are shown. The
- filter selected is set to \a selectedFilter. The parameters \a dir,
- \a selectedFilter and \a filter may be empty strings. If you need multiple
- filters, separate them with ';;', for instance:
-
- \code
- "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"
- \endcode
-
- The dialog's caption is set to \a caption. If \a caption is not specified
- then a default caption will be used.
-
- On Windows, Mac OS X and Symbian^3, this static function will use the
- native file dialog and not a QFileDialog.
-
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not 0 then it will position the
- dialog just below the parent's title bar.
-
- On Unix/X11, the normal behavior of the file dialog is to resolve and
- follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}.
- The \a options argument holds various options about how to run the dialog,
- see the QFileDialog::Option enum for more information on the flags you can
- pass.
-
- \note If you want to iterate over the list of files, you should iterate
- over a copy. For example:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 10
-
- On Symbian^3 the parameter \a selectedFilter has no meaning and the
- \a options parameter is only used to define if the native file dialog is
- used. On Symbian^3, this function can only return a single filename.
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QFileDialog constructors.
-
- \sa getOpenFileName(), getSaveFileName(), getExistingDirectory()
-*/
-QStringList QFileDialog::getOpenFileNames(QWidget *parent,
- const QString &caption,
- const QString &dir,
- const QString &filter,
- QString *selectedFilter,
- Options options)
-{
- if (qt_filedialog_open_filenames_hook && !(options & DontUseNativeDialog))
- return qt_filedialog_open_filenames_hook(parent, caption, dir, filter, selectedFilter, options);
-#if defined(Q_WS_S60)
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
- return qtSymbianGetOpenFileNames(caption, dir, filter);
-#endif
- QFileDialogArgs args;
- args.parent = parent;
- args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.selection = QFileDialogPrivate::initialSelection(dir);
- args.filter = filter;
- args.mode = ExistingFiles;
- args.options = options;
-
-#if defined(Q_WS_WIN)
- if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog)) {
- return qt_win_get_open_file_names(args, &(args.directory), selectedFilter);
- }
-#endif
-
- // create a qt dialog
- QFileDialog dialog(args);
- if (selectedFilter)
- dialog.selectNameFilter(*selectedFilter);
- if (dialog.exec() == QDialog::Accepted) {
- if (selectedFilter)
- *selectedFilter = dialog.selectedFilter();
- return dialog.selectedFiles();
- }
- return QStringList();
-}
-
-/*!
- This is a convenience static function that will return a file name selected
- by the user. The file does not have to exist.
-
- It creates a modal file dialog with the given \a parent widget. If
- \a parent is not 0, the dialog will be shown centered over the parent
- widget.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 11
-
- The file dialog's working directory will be set to \a dir. If \a dir
- includes a file name, the file will be selected. Only files that match the
- \a filter are shown. The filter selected is set to \a selectedFilter. The
- parameters \a dir, \a selectedFilter, and \a filter may be empty strings.
- Multiple filters are separated with ';;'. For instance:
-
- \code
- "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"
- \endcode
-
- The \a options argument holds various options about how to run the dialog,
- see the QFileDialog::Option enum for more information on the flags you can
- pass.
-
- The default filter can be chosen by setting \a selectedFilter to the
- desired value.
-
- The dialog's caption is set to \a caption. If \a caption is not specified,
- a default caption will be used.
-
- On Windows, Mac OS X and Symbian^3, this static function will use the
- native file dialog and not a QFileDialog.
-
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not 0 then it will position the
- dialog just below the parent's title bar. On Mac OS X, with its native file
- dialog, the filter argument is ignored.
-
- On Unix/X11, the normal behavior of the file dialog is to resolve and
- follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
- \a options includes DontResolveSymlinks the file dialog will treat symlinks
- as regular directories.
-
- On Symbian^3 the parameters \a filter and \a selectedFilter have no
- meaning. The \a options parameter is only used to define if the native file
- dialog is used.
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QFileDialog constructors.
-
- \sa getOpenFileName(), getOpenFileNames(), getExistingDirectory()
-*/
-QString QFileDialog::getSaveFileName(QWidget *parent,
- const QString &caption,
- const QString &dir,
- const QString &filter,
- QString *selectedFilter,
- Options options)
-{
- if (qt_filedialog_save_filename_hook && !(options & DontUseNativeDialog))
- return qt_filedialog_save_filename_hook(parent, caption, dir, filter, selectedFilter, options);
-#if defined(Q_WS_S60)
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
- return qtSymbianGetSaveFileName(caption, dir);
-#endif
- QFileDialogArgs args;
- args.parent = parent;
- args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.selection = QFileDialogPrivate::initialSelection(dir);
- args.filter = filter;
- args.mode = AnyFile;
- args.options = options;
-
-#if defined(Q_WS_WIN)
- if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog)) {
- return qt_win_get_save_file_name(args, &(args.directory), selectedFilter);
- }
-#endif
-
- // create a qt dialog
- QFileDialog dialog(args);
- dialog.setAcceptMode(AcceptSave);
- if (selectedFilter)
- dialog.selectNameFilter(*selectedFilter);
- if (dialog.exec() == QDialog::Accepted) {
- if (selectedFilter)
- *selectedFilter = dialog.selectedFilter();
- return dialog.selectedFiles().value(0);
- }
-
- return QString();
-}
-
-/*!
- This is a convenience static function that will return an existing
- directory selected by the user.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp 12
-
- This function creates a modal file dialog with the given \a parent widget.
- If \a parent is not 0, the dialog will be shown centered over the parent
- widget.
-
- The dialog's working directory is set to \a dir, and the caption is set to
- \a caption. Either of these may be an empty string in which case the
- current directory and a default caption will be used respectively.
-
- The \a options argument holds various options about how to run the dialog,
- see the QFileDialog::Option enum for more information on the flags you can
- pass. To ensure a native file dialog, \l{QFileDialog::}{ShowDirsOnly} must
- be set.
-
- On Windows, Mac OS X and Symbian^3, this static function will use the
- native file dialog and not a QFileDialog. On Windows CE, if the device has
- no native file dialog, a QFileDialog will be used.
-
- On Unix/X11, the normal behavior of the file dialog is to resolve and
- follow symlinks. For example, if \c{/usr/tmp} is a symlink to \c{/var/tmp},
- the file dialog will change to \c{/var/tmp} after entering \c{/usr/tmp}. If
- \a options includes DontResolveSymlinks, the file dialog will treat
- symlinks as regular directories.
-
- On Windows the dialog will spin a blocking modal event loop that will not
- dispatch any QTimers, and if \a parent is not 0 then it will position the
- dialog just below the parent's title bar.
-
- On Symbian^3 the \a options parameter is only used to define if the native
- file dialog is used.
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QFileDialog constructors.
-
- \sa getOpenFileName(), getOpenFileNames(), getSaveFileName()
-*/
-QString QFileDialog::getExistingDirectory(QWidget *parent,
- const QString &caption,
- const QString &dir,
- Options options)
-{
- if (qt_filedialog_existing_directory_hook && !(options & DontUseNativeDialog))
- return qt_filedialog_existing_directory_hook(parent, caption, dir, options);
-#if defined(Q_WS_S60)
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0 && !(options & DontUseNativeDialog))
- return qtSymbianGetExistingDirectory(caption, dir);
-#endif
- QFileDialogArgs args;
- args.parent = parent;
- args.caption = caption;
- args.directory = QFileDialogPrivate::workingDirectory(dir);
- args.mode = (options & ShowDirsOnly ? DirectoryOnly : Directory);
- args.options = options;
-
-#if defined(Q_WS_WIN)
- if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog) && (options & ShowDirsOnly)
-#if defined(Q_WS_WINCE)
- && qt_priv_ptr_valid
-#endif
- ) {
- return qt_win_get_existing_directory(args);
- }
-#endif
-
- // create a qt dialog
- QFileDialog dialog(args);
- if (dialog.exec() == QDialog::Accepted) {
- return dialog.selectedFiles().value(0);
- }
- return QString();
-}
-
-inline static QString _qt_get_directory(const QString &path)
-{
- QFileInfo info = QFileInfo(QDir::current(), path);
- if (info.exists() && info.isDir())
- return QDir::cleanPath(info.absoluteFilePath());
- info.setFile(info.absolutePath());
- if (info.exists() && info.isDir())
- return info.absoluteFilePath();
- return QString();
-}
-/*
- Get the initial directory path
-
- \sa initialSelection()
- */
-QString QFileDialogPrivate::workingDirectory(const QString &path)
-{
- if (!path.isEmpty()) {
- QString directory = _qt_get_directory(path);
- if (!directory.isEmpty())
- return directory;
- }
- QString directory = _qt_get_directory(*lastVisitedDir());
- if (!directory.isEmpty())
- return directory;
- return QDir::currentPath();
-}
-
-/*
- Get the initial selection given a path. The initial directory
- can contain both the initial directory and initial selection
- /home/user/foo.txt
-
- \sa workingDirectory()
- */
-QString QFileDialogPrivate::initialSelection(const QString &path)
-{
- if (!path.isEmpty()) {
- QFileInfo info(path);
- if (!info.isDir())
- return info.fileName();
- }
- return QString();
-}
-
-/*!
- \reimp
-*/
-void QFileDialog::done(int result)
-{
- Q_D(QFileDialog);
-
- QDialog::done(result);
-
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, d->signalToDisconnectOnClose,
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
- d->signalToDisconnectOnClose.clear();
-}
-
-/*!
- \reimp
-*/
-void QFileDialog::accept()
-{
- Q_D(QFileDialog);
- QStringList files = selectedFiles();
- if (files.isEmpty())
- return;
- if (d->nativeDialogInUse){
- d->emitFilesSelected(files);
- QDialog::accept();
- return;
- }
-
- QString lineEditText = d->lineEdit()->text();
- // "hidden feature" type .. and then enter, and it will move up a dir
- // special case for ".."
- if (lineEditText == QLatin1String("..")) {
- d->_q_navigateToParent();
- bool block = d->qFileDialogUi->fileNameEdit->blockSignals(true);
- d->lineEdit()->selectAll();
- d->qFileDialogUi->fileNameEdit->blockSignals(block);
- return;
- }
-
- switch (d->fileMode) {
- case DirectoryOnly:
- case Directory: {
- QString fn = files.first();
- QFileInfo info(fn);
- if (!info.exists())
- info = QFileInfo(d->getEnvironmentVariable(fn));
- if (!info.exists()) {
-#ifndef QT_NO_MESSAGEBOX
- QString message = tr("%1\nDirectory not found.\nPlease verify the "
- "correct directory name was given.");
- QMessageBox::warning(this, windowTitle(), message.arg(info.fileName()));
-#endif // QT_NO_MESSAGEBOX
- return;
- }
- if (info.isDir()) {
- d->emitFilesSelected(files);
- QDialog::accept();
- }
- return;
- }
-
- case AnyFile: {
- QString fn = files.first();
- QFileInfo info(fn);
- if (info.isDir()) {
- setDirectory(info.absoluteFilePath());
- return;
- }
-
- if (!info.exists()) {
- int maxNameLength = d->maxNameLength(info.path());
- if (maxNameLength >= 0 && info.fileName().length() > maxNameLength)
- return;
- }
-
- // check if we have to ask for permission to overwrite the file
- if (!info.exists() || !confirmOverwrite() || acceptMode() == AcceptOpen) {
- d->emitFilesSelected(QStringList(fn));
- QDialog::accept();
-#ifndef QT_NO_MESSAGEBOX
- } else {
- if (QMessageBox::warning(this, windowTitle(),
- tr("%1 already exists.\nDo you want to replace it?")
- .arg(info.fileName()),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
- == QMessageBox::Yes) {
- d->emitFilesSelected(QStringList(fn));
- QDialog::accept();
- }
-#endif
- }
- return;
- }
-
- case ExistingFile:
- case ExistingFiles:
- for (int i = 0; i < files.count(); ++i) {
- QFileInfo info(files.at(i));
- if (!info.exists())
- info = QFileInfo(d->getEnvironmentVariable(files.at(i)));
- if (!info.exists()) {
-#ifndef QT_NO_MESSAGEBOX
- QString message = tr("%1\nFile not found.\nPlease verify the "
- "correct file name was given.");
- QMessageBox::warning(this, windowTitle(), message.arg(info.fileName()));
-#endif // QT_NO_MESSAGEBOX
- return;
- }
- if (info.isDir()) {
- setDirectory(info.absoluteFilePath());
- d->lineEdit()->clear();
- return;
- }
- }
- d->emitFilesSelected(files);
- QDialog::accept();
- return;
- }
-}
-
-/*!
- \internal
-
- Create widgets, layout and set default values
-*/
-void QFileDialogPrivate::init(const QString &directory, const QString &nameFilter,
- const QString &caption)
-{
- Q_Q(QFileDialog);
- if (!caption.isEmpty()) {
- useDefaultCaption = false;
- setWindowTitle = caption;
- q->setWindowTitle(caption);
- }
-
- createWidgets();
- createMenuActions();
- retranslateStrings();
- q->setFileMode(fileMode);
-
-#ifndef QT_NO_SETTINGS
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- settings.beginGroup(QLatin1String("Qt"));
- if (!directory.isEmpty())
- setLastVisitedDirectory(workingDirectory(directory));
- q->restoreState(settings.value(QLatin1String("filedialog")).toByteArray());
-#endif
-
-#if defined(Q_EMBEDDED_SMALLSCREEN)
- qFileDialogUi->lookInLabel->setVisible(false);
- qFileDialogUi->fileNameLabel->setVisible(false);
- qFileDialogUi->fileTypeLabel->setVisible(false);
- qFileDialogUi->sidebar->hide();
-#endif
- // Default case
- if (!nameFilter.isEmpty())
- q->setNameFilter(nameFilter);
- q->setAcceptMode(QFileDialog::AcceptOpen);
- q->setDirectory(workingDirectory(directory));
- q->selectFile(initialSelection(directory));
-
- _q_updateOkButton();
- q->resize(q->sizeHint());
-}
-
-/*!
- \internal
-
- Create the widgets, set properties and connections
-*/
-void QFileDialogPrivate::createWidgets()
-{
- Q_Q(QFileDialog);
- model = new QFileSystemModel(q);
- model->setObjectName(QLatin1String("qt_filesystem_model"));
-#ifdef Q_WS_MAC
- model->setNameFilterDisables(true);
-#else
- model->setNameFilterDisables(false);
-#endif
- model->d_func()->disableRecursiveSort = true;
- QFileDialog::connect(model, SIGNAL(fileRenamed(QString,QString,QString)), q, SLOT(_q_fileRenamed(QString,QString,QString)));
- QFileDialog::connect(model, SIGNAL(rootPathChanged(QString)),
- q, SLOT(_q_pathChanged(QString)));
- QFileDialog::connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- q, SLOT(_q_rowsInserted(QModelIndex)));
- model->setReadOnly(false);
-
- qFileDialogUi.reset(new Ui_QFileDialog());
- qFileDialogUi->setupUi(q);
-
- QList<QUrl> initialBookmarks;
- initialBookmarks << QUrl::fromLocalFile(QLatin1String(""))
- << QUrl::fromLocalFile(QDir::homePath());
- qFileDialogUi->sidebar->init(model, initialBookmarks);
- QFileDialog::connect(qFileDialogUi->sidebar, SIGNAL(goToUrl(QUrl)),
- q, SLOT(_q_goToUrl(QUrl)));
-
- QObject::connect(qFileDialogUi->buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
- QObject::connect(qFileDialogUi->buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
-
-
- qFileDialogUi->lookInCombo->init(this);
- QObject::connect(qFileDialogUi->lookInCombo, SIGNAL(activated(QString)), q, SLOT(_q_goToDirectory(QString)));
-
- qFileDialogUi->lookInCombo->setInsertPolicy(QComboBox::NoInsert);
- qFileDialogUi->lookInCombo->setDuplicatesEnabled(false);
-
- // filename
- qFileDialogUi->fileNameEdit->init(this);
-#ifndef QT_NO_SHORTCUT
- qFileDialogUi->fileNameLabel->setBuddy(qFileDialogUi->fileNameEdit);
-#endif
-#ifndef QT_NO_FSCOMPLETER
- completer = new QFSCompleter(model, q);
- qFileDialogUi->fileNameEdit->setCompleter(completer);
-#endif // QT_NO_FSCOMPLETER
- QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(textChanged(QString)),
- q, SLOT(_q_autoCompleteFileName(QString)));
- QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(textChanged(QString)),
- q, SLOT(_q_updateOkButton()));
-
- QObject::connect(qFileDialogUi->fileNameEdit, SIGNAL(returnPressed()), q, SLOT(accept()));
-
- // filetype
- qFileDialogUi->fileTypeCombo->setDuplicatesEnabled(false);
- qFileDialogUi->fileTypeCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
- qFileDialogUi->fileTypeCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
- QObject::connect(qFileDialogUi->fileTypeCombo, SIGNAL(activated(int)),
- q, SLOT(_q_useNameFilter(int)));
- QObject::connect(qFileDialogUi->fileTypeCombo, SIGNAL(activated(QString)),
- q, SIGNAL(filterSelected(QString)));
-
- qFileDialogUi->listView->init(this);
- qFileDialogUi->listView->setModel(model);
- QObject::connect(qFileDialogUi->listView, SIGNAL(activated(QModelIndex)),
- q, SLOT(_q_enterDirectory(QModelIndex)));
- QObject::connect(qFileDialogUi->listView, SIGNAL(customContextMenuRequested(QPoint)),
- q, SLOT(_q_showContextMenu(QPoint)));
-#ifndef QT_NO_SHORTCUT
- QShortcut *shortcut = new QShortcut(qFileDialogUi->listView);
- shortcut->setKey(QKeySequence(QLatin1String("Delete")));
- QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
-#endif
-
- qFileDialogUi->treeView->init(this);
- qFileDialogUi->treeView->setModel(model);
- QHeaderView *treeHeader = qFileDialogUi->treeView->header();
- QFontMetrics fm(q->font());
- treeHeader->resizeSection(0, fm.width(QLatin1String("wwwwwwwwwwwwwwwwwwwwwwwwww")));
- treeHeader->resizeSection(1, fm.width(QLatin1String("128.88 GB")));
- treeHeader->resizeSection(2, fm.width(QLatin1String("mp3Folder")));
- treeHeader->resizeSection(3, fm.width(QLatin1String("10/29/81 02:02PM")));
- treeHeader->setContextMenuPolicy(Qt::ActionsContextMenu);
-
- QActionGroup *showActionGroup = new QActionGroup(q);
- showActionGroup->setExclusive(false);
- QObject::connect(showActionGroup, SIGNAL(triggered(QAction*)),
- q, SLOT(_q_showHeader(QAction*)));;
-
- QAbstractItemModel *abstractModel = model;
-#ifndef QT_NO_PROXYMODEL
- if (proxyModel)
- abstractModel = proxyModel;
-#endif
- for (int i = 1; i < abstractModel->columnCount(QModelIndex()); ++i) {
- QAction *showHeader = new QAction(showActionGroup);
- showHeader->setCheckable(true);
- showHeader->setChecked(true);
- treeHeader->addAction(showHeader);
- }
-
- QScopedPointer<QItemSelectionModel> selModel(qFileDialogUi->treeView->selectionModel());
- qFileDialogUi->treeView->setSelectionModel(qFileDialogUi->listView->selectionModel());
-
- QObject::connect(qFileDialogUi->treeView, SIGNAL(activated(QModelIndex)),
- q, SLOT(_q_enterDirectory(QModelIndex)));
- QObject::connect(qFileDialogUi->treeView, SIGNAL(customContextMenuRequested(QPoint)),
- q, SLOT(_q_showContextMenu(QPoint)));
-#ifndef QT_NO_SHORTCUT
- shortcut = new QShortcut(qFileDialogUi->treeView);
- shortcut->setKey(QKeySequence(QLatin1String("Delete")));
- QObject::connect(shortcut, SIGNAL(activated()), q, SLOT(_q_deleteCurrent()));
-#endif
-
- // Selections
- QItemSelectionModel *selections = qFileDialogUi->listView->selectionModel();
- QObject::connect(selections, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- q, SLOT(_q_selectionChanged()));
- QObject::connect(selections, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_currentChanged(QModelIndex)));
- qFileDialogUi->splitter->setStretchFactor(qFileDialogUi->splitter->indexOf(qFileDialogUi->splitter->widget(1)), QSizePolicy::Expanding);
-
- createToolButtons();
-}
-
-void QFileDialogPrivate::_q_showHeader(QAction *action)
-{
- Q_Q(QFileDialog);
- QActionGroup *actionGroup = qobject_cast<QActionGroup*>(q->sender());
- qFileDialogUi->treeView->header()->setSectionHidden(actionGroup->actions().indexOf(action) + 1, !action->isChecked());
-}
-
-#ifndef QT_NO_PROXYMODEL
-/*!
- \since 4.3
-
- Sets the model for the views to the given \a proxyModel. This is useful if you
- want to modify the underlying model; for example, to add columns, filter
- data or add drives.
-
- Any existing proxy model will be removed, but not deleted. The file dialog
- will take ownership of the \a proxyModel.
-
- \sa proxyModel()
-*/
-void QFileDialog::setProxyModel(QAbstractProxyModel *proxyModel)
-{
- Q_D(QFileDialog);
- if ((!proxyModel && !d->proxyModel)
- || (proxyModel == d->proxyModel))
- return;
-
- QModelIndex idx = d->rootIndex();
- if (d->proxyModel) {
- disconnect(d->proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
- } else {
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
- }
-
- if (proxyModel != 0) {
- proxyModel->setParent(this);
- d->proxyModel = proxyModel;
- proxyModel->setSourceModel(d->model);
- d->qFileDialogUi->listView->setModel(d->proxyModel);
- d->qFileDialogUi->treeView->setModel(d->proxyModel);
-#ifndef QT_NO_FSCOMPLETER
- d->completer->setModel(d->proxyModel);
- d->completer->proxyModel = d->proxyModel;
-#endif
- connect(d->proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
- } else {
- d->proxyModel = 0;
- d->qFileDialogUi->listView->setModel(d->model);
- d->qFileDialogUi->treeView->setModel(d->model);
-#ifndef QT_NO_FSCOMPLETER
- d->completer->setModel(d->model);
- d->completer->sourceModel = d->model;
- d->completer->proxyModel = 0;
-#endif
- connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex)));
- }
- QScopedPointer<QItemSelectionModel> selModel(d->qFileDialogUi->treeView->selectionModel());
- d->qFileDialogUi->treeView->setSelectionModel(d->qFileDialogUi->listView->selectionModel());
-
- d->setRootIndex(idx);
-
- // reconnect selection
- QItemSelectionModel *selections = d->qFileDialogUi->listView->selectionModel();
- QObject::connect(selections, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(_q_selectionChanged()));
- QObject::connect(selections, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_currentChanged(QModelIndex)));
-}
-
-/*!
- Returns the proxy model used by the file dialog. By default no proxy is set.
-
- \sa setProxyModel()
-*/
-QAbstractProxyModel *QFileDialog::proxyModel() const
-{
- Q_D(const QFileDialog);
- return d->proxyModel;
-}
-#endif // QT_NO_PROXYMODEL
-
-/*!
- \internal
-
- Create tool buttons, set properties and connections
-*/
-void QFileDialogPrivate::createToolButtons()
-{
- Q_Q(QFileDialog);
- qFileDialogUi->backButton->setIcon(q->style()->standardIcon(QStyle::SP_ArrowBack, 0, q));
- qFileDialogUi->backButton->setAutoRaise(true);
- qFileDialogUi->backButton->setEnabled(false);
- QObject::connect(qFileDialogUi->backButton, SIGNAL(clicked()), q, SLOT(_q_navigateBackward()));
-
- qFileDialogUi->forwardButton->setIcon(q->style()->standardIcon(QStyle::SP_ArrowForward, 0, q));
- qFileDialogUi->forwardButton->setAutoRaise(true);
- qFileDialogUi->forwardButton->setEnabled(false);
- QObject::connect(qFileDialogUi->forwardButton, SIGNAL(clicked()), q, SLOT(_q_navigateForward()));
-
- qFileDialogUi->toParentButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogToParent, 0, q));
- qFileDialogUi->toParentButton->setAutoRaise(true);
- qFileDialogUi->toParentButton->setEnabled(false);
- QObject::connect(qFileDialogUi->toParentButton, SIGNAL(clicked()), q, SLOT(_q_navigateToParent()));
-
- qFileDialogUi->listModeButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogListView, 0, q));
- qFileDialogUi->listModeButton->setAutoRaise(true);
- qFileDialogUi->listModeButton->setDown(true);
- QObject::connect(qFileDialogUi->listModeButton, SIGNAL(clicked()), q, SLOT(_q_showListView()));
-
- qFileDialogUi->detailModeButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogDetailedView, 0, q));
- qFileDialogUi->detailModeButton->setAutoRaise(true);
- QObject::connect(qFileDialogUi->detailModeButton, SIGNAL(clicked()), q, SLOT(_q_showDetailsView()));
-
- QSize toolSize(qFileDialogUi->fileNameEdit->sizeHint().height(), qFileDialogUi->fileNameEdit->sizeHint().height());
- qFileDialogUi->backButton->setFixedSize(toolSize);
- qFileDialogUi->listModeButton->setFixedSize(toolSize);
- qFileDialogUi->detailModeButton->setFixedSize(toolSize);
- qFileDialogUi->forwardButton->setFixedSize(toolSize);
- qFileDialogUi->toParentButton->setFixedSize(toolSize);
-
- qFileDialogUi->newFolderButton->setIcon(q->style()->standardIcon(QStyle::SP_FileDialogNewFolder, 0, q));
- qFileDialogUi->newFolderButton->setFixedSize(toolSize);
- qFileDialogUi->newFolderButton->setAutoRaise(true);
- qFileDialogUi->newFolderButton->setEnabled(false);
- QObject::connect(qFileDialogUi->newFolderButton, SIGNAL(clicked()), q, SLOT(_q_createDirectory()));
-}
-
-/*!
- \internal
-
- Create actions which will be used in the right click.
-*/
-void QFileDialogPrivate::createMenuActions()
-{
- Q_Q(QFileDialog);
-
- QAction *goHomeAction = new QAction(q);
-#ifndef QT_NO_SHORTCUT
- goHomeAction->setShortcut(Qt::CTRL + Qt::Key_H + Qt::SHIFT);
-#endif
- QObject::connect(goHomeAction, SIGNAL(triggered()), q, SLOT(_q_goHome()));
- q->addAction(goHomeAction);
-
- // ### TODO add Desktop & Computer actions
-
- QAction *goToParent = new QAction(q);
- goToParent->setObjectName(QLatin1String("qt_goto_parent_action"));
-#ifndef QT_NO_SHORTCUT
- goToParent->setShortcut(Qt::CTRL + Qt::UpArrow);
-#endif
- QObject::connect(goToParent, SIGNAL(triggered()), q, SLOT(_q_navigateToParent()));
- q->addAction(goToParent);
-
- renameAction = new QAction(q);
- renameAction->setEnabled(false);
- renameAction->setObjectName(QLatin1String("qt_rename_action"));
- QObject::connect(renameAction, SIGNAL(triggered()), q, SLOT(_q_renameCurrent()));
-
- deleteAction = new QAction(q);
- deleteAction->setEnabled(false);
- deleteAction->setObjectName(QLatin1String("qt_delete_action"));
- QObject::connect(deleteAction, SIGNAL(triggered()), q, SLOT(_q_deleteCurrent()));
-
- showHiddenAction = new QAction(q);
- showHiddenAction->setObjectName(QLatin1String("qt_show_hidden_action"));
- showHiddenAction->setCheckable(true);
- QObject::connect(showHiddenAction, SIGNAL(triggered()), q, SLOT(_q_showHidden()));
-
- newFolderAction = new QAction(q);
- newFolderAction->setObjectName(QLatin1String("qt_new_folder_action"));
- QObject::connect(newFolderAction, SIGNAL(triggered()), q, SLOT(_q_createDirectory()));
-}
-
-void QFileDialogPrivate::_q_goHome()
-{
- Q_Q(QFileDialog);
- q->setDirectory(QDir::homePath());
-}
-
-/*!
- \internal
-
- Update history with new path, buttons, and combo
-*/
-void QFileDialogPrivate::_q_pathChanged(const QString &newPath)
-{
- Q_Q(QFileDialog);
- QDir dir(model->rootDirectory());
- qFileDialogUi->toParentButton->setEnabled(dir.exists());
- qFileDialogUi->sidebar->selectUrl(QUrl::fromLocalFile(newPath));
- q->setHistory(qFileDialogUi->lookInCombo->history());
-
- if (currentHistoryLocation < 0 || currentHistory.value(currentHistoryLocation) != QDir::toNativeSeparators(newPath)) {
- while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.count()) {
- currentHistory.removeLast();
- }
- currentHistory.append(QDir::toNativeSeparators(newPath));
- ++currentHistoryLocation;
- }
- qFileDialogUi->forwardButton->setEnabled(currentHistory.size() - currentHistoryLocation > 1);
- qFileDialogUi->backButton->setEnabled(currentHistoryLocation > 0);
-}
-
-/*!
- \internal
-
- Navigates to the last directory viewed in the dialog.
-*/
-void QFileDialogPrivate::_q_navigateBackward()
-{
- Q_Q(QFileDialog);
- if (!currentHistory.isEmpty() && currentHistoryLocation > 0) {
- --currentHistoryLocation;
- QString previousHistory = currentHistory.at(currentHistoryLocation);
- q->setDirectory(previousHistory);
- }
-}
-
-/*!
- \internal
-
- Navigates to the last directory viewed in the dialog.
-*/
-void QFileDialogPrivate::_q_navigateForward()
-{
- Q_Q(QFileDialog);
- if (!currentHistory.isEmpty() && currentHistoryLocation < currentHistory.size() - 1) {
- ++currentHistoryLocation;
- QString nextHistory = currentHistory.at(currentHistoryLocation);
- q->setDirectory(nextHistory);
- }
-}
-
-/*!
- \internal
-
- Navigates to the parent directory of the currently displayed directory
- in the dialog.
-*/
-void QFileDialogPrivate::_q_navigateToParent()
-{
- Q_Q(QFileDialog);
- QDir dir(model->rootDirectory());
- QString newDirectory;
- if (dir.isRoot()) {
- newDirectory = model->myComputer().toString();
- } else {
- dir.cdUp();
- newDirectory = dir.absolutePath();
- }
- q->setDirectory(newDirectory);
- emit q->directoryEntered(newDirectory);
-}
-
-/*!
- \internal
-
- Creates a new directory, first asking the user for a suitable name.
-*/
-void QFileDialogPrivate::_q_createDirectory()
-{
- Q_Q(QFileDialog);
- qFileDialogUi->listView->clearSelection();
-
- QString newFolderString = QFileDialog::tr("New Folder");
- QString folderName = newFolderString;
- QString prefix = q->directory().absolutePath() + QDir::separator();
- if (QFile::exists(prefix + folderName)) {
- qlonglong suffix = 2;
- while (QFile::exists(prefix + folderName)) {
- folderName = newFolderString + QString::number(suffix++);
- }
- }
-
- QModelIndex parent = rootIndex();
- QModelIndex index = model->mkdir(parent, folderName);
- if (!index.isValid())
- return;
-
- index = select(index);
- if (index.isValid()) {
- qFileDialogUi->treeView->setCurrentIndex(index);
- currentView()->edit(index);
- }
-}
-
-void QFileDialogPrivate::_q_showListView()
-{
- qFileDialogUi->listModeButton->setDown(true);
- qFileDialogUi->detailModeButton->setDown(false);
- qFileDialogUi->treeView->hide();
- qFileDialogUi->listView->show();
- qFileDialogUi->stackedWidget->setCurrentWidget(qFileDialogUi->listView->parentWidget());
- qFileDialogUi->listView->doItemsLayout();
-}
-
-void QFileDialogPrivate::_q_showDetailsView()
-{
- qFileDialogUi->listModeButton->setDown(false);
- qFileDialogUi->detailModeButton->setDown(true);
- qFileDialogUi->listView->hide();
- qFileDialogUi->treeView->show();
- qFileDialogUi->stackedWidget->setCurrentWidget(qFileDialogUi->treeView->parentWidget());
- qFileDialogUi->treeView->doItemsLayout();
-}
-
-/*!
- \internal
-
- Show the context menu for the file/dir under position
-*/
-void QFileDialogPrivate::_q_showContextMenu(const QPoint &position)
-{
-#ifdef QT_NO_MENU
- Q_UNUSED(position);
-#else
- Q_Q(QFileDialog);
- QAbstractItemView *view = 0;
- if (q->viewMode() == QFileDialog::Detail)
- view = qFileDialogUi->treeView;
- else
- view = qFileDialogUi->listView;
- QModelIndex index = view->indexAt(position);
- index = mapToSource(index.sibling(index.row(), 0));
-
- QMenu menu(view);
- if (index.isValid()) {
- // file context menu
- QFile::Permissions p(index.parent().data(QFileSystemModel::FilePermissions).toInt());
- renameAction->setEnabled(p & QFile::WriteUser);
- menu.addAction(renameAction);
- deleteAction->setEnabled(p & QFile::WriteUser);
- menu.addAction(deleteAction);
- menu.addSeparator();
- }
- menu.addAction(showHiddenAction);
- if (qFileDialogUi->newFolderButton->isVisible()) {
- newFolderAction->setEnabled(qFileDialogUi->newFolderButton->isEnabled());
- menu.addAction(newFolderAction);
- }
- menu.exec(view->viewport()->mapToGlobal(position));
-#endif // QT_NO_MENU
-}
-
-/*!
- \internal
-*/
-void QFileDialogPrivate::_q_renameCurrent()
-{
- Q_Q(QFileDialog);
- QModelIndex index = qFileDialogUi->listView->currentIndex();
- index = index.sibling(index.row(), 0);
- if (q->viewMode() == QFileDialog::List)
- qFileDialogUi->listView->edit(index);
- else
- qFileDialogUi->treeView->edit(index);
-}
-
-bool QFileDialogPrivate::removeDirectory(const QString &path)
-{
- QModelIndex modelIndex = model->index(path);
- return model->remove(modelIndex);
-}
-
-/*!
- \internal
-
- Deletes the currently selected item in the dialog.
-*/
-void QFileDialogPrivate::_q_deleteCurrent()
-{
- if (model->isReadOnly())
- return;
-
- QModelIndexList list = qFileDialogUi->listView->selectionModel()->selectedRows();
- for (int i = list.count() - 1; i >= 0; --i) {
- QModelIndex index = list.at(i);
- if (index == qFileDialogUi->listView->rootIndex())
- continue;
-
- index = mapToSource(index.sibling(index.row(), 0));
- if (!index.isValid())
- continue;
-
- QString fileName = index.data(QFileSystemModel::FileNameRole).toString();
- QString filePath = index.data(QFileSystemModel::FilePathRole).toString();
- bool isDir = model->isDir(index);
-
- QFile::Permissions p(index.parent().data(QFileSystemModel::FilePermissions).toInt());
-#ifndef QT_NO_MESSAGEBOX
- Q_Q(QFileDialog);
- if (!(p & QFile::WriteUser) && (QMessageBox::warning(q_func(), q_func()->windowTitle(),
- QFileDialog::tr("'%1' is write protected.\nDo you want to delete it anyway?")
- .arg(fileName),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No))
- return;
- else if (QMessageBox::warning(q_func(), q_func()->windowTitle(),
- QFileDialog::tr("Are sure you want to delete '%1'?")
- .arg(fileName),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
- return;
-
-#else
- if (!(p & QFile::WriteUser))
- return;
-#endif // QT_NO_MESSAGEBOX
-
- // the event loop has run, we can NOT reuse index because the model might have removed it.
- if (isDir) {
- if (!removeDirectory(filePath)) {
-#ifndef QT_NO_MESSAGEBOX
- QMessageBox::warning(q, q->windowTitle(),
- QFileDialog::tr("Could not delete directory."));
-#endif
- }
- } else {
- model->remove(index);
- }
- }
-}
-
-void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
-{
- if (text.startsWith(QLatin1String("//")) || text.startsWith(QLatin1Char('\\'))) {
- qFileDialogUi->listView->selectionModel()->clearSelection();
- return;
- }
-
- QStringList multipleFiles = typedFiles();
- if (multipleFiles.count() > 0) {
- QModelIndexList oldFiles = qFileDialogUi->listView->selectionModel()->selectedRows();
- QModelIndexList newFiles;
- for (int i = 0; i < multipleFiles.count(); ++i) {
- QModelIndex idx = model->index(multipleFiles.at(i));
- if (oldFiles.contains(idx))
- oldFiles.removeAll(idx);
- else
- newFiles.append(idx);
- }
- for (int i = 0; i < newFiles.count(); ++i)
- select(newFiles.at(i));
- if (lineEdit()->hasFocus())
- for (int i = 0; i < oldFiles.count(); ++i)
- qFileDialogUi->listView->selectionModel()->select(oldFiles.at(i),
- QItemSelectionModel::Toggle | QItemSelectionModel::Rows);
- }
-}
-
-/*!
- \internal
-*/
-void QFileDialogPrivate::_q_updateOkButton()
-{
- Q_Q(QFileDialog);
- QPushButton *button = qFileDialogUi->buttonBox->button((acceptMode == QFileDialog::AcceptOpen)
- ? QDialogButtonBox::Open : QDialogButtonBox::Save);
- if (!button)
- return;
-
- bool enableButton = true;
- bool isOpenDirectory = false;
-
- QStringList files = q->selectedFiles();
- QString lineEditText = lineEdit()->text();
-
- if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1Char('\\'))) {
- button->setEnabled(true);
- if (acceptMode == QFileDialog::AcceptSave)
- button->setText(acceptLabel);
- return;
- }
-
- if (files.isEmpty()) {
- enableButton = false;
- } else if (lineEditText == QLatin1String("..")) {
- isOpenDirectory = true;
- } else {
- switch (fileMode) {
- case QFileDialog::DirectoryOnly:
- case QFileDialog::Directory: {
- QString fn = files.first();
- QModelIndex idx = model->index(fn);
- if (!idx.isValid())
- idx = model->index(getEnvironmentVariable(fn));
- if (!idx.isValid() || !model->isDir(idx))
- enableButton = false;
- break;
- }
- case QFileDialog::AnyFile: {
- QString fn = files.first();
- QFileInfo info(fn);
- QModelIndex idx = model->index(fn);
- QString fileDir;
- QString fileName;
- if (info.isDir()) {
- fileDir = info.canonicalFilePath();
- } else {
- fileDir = fn.mid(0, fn.lastIndexOf(QLatin1Char('/')));
- fileName = fn.mid(fileDir.length() + 1);
- }
- if (lineEditText.contains(QLatin1String(".."))) {
- fileDir = info.canonicalFilePath();
- fileName = info.fileName();
- }
-
- if (fileDir == q->directory().canonicalPath() && fileName.isEmpty()) {
- enableButton = false;
- break;
- }
- if (idx.isValid() && model->isDir(idx)) {
- isOpenDirectory = true;
- enableButton = true;
- break;
- }
- if (!idx.isValid()) {
- int maxLength = maxNameLength(fileDir);
- enableButton = maxLength < 0 || fileName.length() <= maxLength;
- }
- break;
- }
- case QFileDialog::ExistingFile:
- case QFileDialog::ExistingFiles:
- for (int i = 0; i < files.count(); ++i) {
- QModelIndex idx = model->index(files.at(i));
- if (!idx.isValid())
- idx = model->index(getEnvironmentVariable(files.at(i)));
- if (!idx.isValid()) {
- enableButton = false;
- break;
- }
- if (idx.isValid() && model->isDir(idx)) {
- isOpenDirectory = true;
- break;
- }
- }
- break;
- default:
- break;
- }
- }
-
- button->setEnabled(enableButton);
- if (acceptMode == QFileDialog::AcceptSave)
- button->setText(isOpenDirectory ? QFileDialog::tr("&Open") : acceptLabel);
-}
-
-/*!
- \internal
-*/
-void QFileDialogPrivate::_q_currentChanged(const QModelIndex &index)
-{
- _q_updateOkButton();
- emit q_func()->currentChanged(index.data(QFileSystemModel::FilePathRole).toString());
-}
-
-/*!
- \internal
-
- This is called when the user double clicks on a file with the corresponding
- model item \a index.
-*/
-void QFileDialogPrivate::_q_enterDirectory(const QModelIndex &index)
-{
- Q_Q(QFileDialog);
- // My Computer or a directory
- QModelIndex sourceIndex = index.model() == proxyModel ? mapToSource(index) : index;
- QString path = sourceIndex.data(QFileSystemModel::FilePathRole).toString();
- if (path.isEmpty() || model->isDir(sourceIndex)) {
- q->setDirectory(path);
- emit q->directoryEntered(path);
- if (fileMode == QFileDialog::Directory
- || fileMode == QFileDialog::DirectoryOnly) {
- // ### find out why you have to do both of these.
- lineEdit()->setText(QString());
- lineEdit()->clear();
- }
- } else {
- q->accept();
- }
-}
-
-/*!
- \internal
-
- Changes the file dialog's current directory to the one specified
- by \a path.
-*/
-void QFileDialogPrivate::_q_goToDirectory(const QString &path)
-{
- #ifndef QT_NO_MESSAGEBOX
- Q_Q(QFileDialog);
-#endif
- QModelIndex index = qFileDialogUi->lookInCombo->model()->index(qFileDialogUi->lookInCombo->currentIndex(),
- qFileDialogUi->lookInCombo->modelColumn(),
- qFileDialogUi->lookInCombo->rootModelIndex());
- QString path2 = path;
- if (!index.isValid())
- index = mapFromSource(model->index(getEnvironmentVariable(path)));
- else {
- path2 = index.data(UrlRole).toUrl().toLocalFile();
- index = mapFromSource(model->index(path2));
- }
- QDir dir(path2);
- if (!dir.exists())
- dir = getEnvironmentVariable(path2);
-
- if (dir.exists() || path2.isEmpty() || path2 == model->myComputer().toString()) {
- _q_enterDirectory(index);
-#ifndef QT_NO_MESSAGEBOX
- } else {
- QString message = QFileDialog::tr("%1\nDirectory not found.\nPlease verify the "
- "correct directory name was given.");
- QMessageBox::warning(q, q->windowTitle(), message.arg(path2));
-#endif // QT_NO_MESSAGEBOX
- }
-}
-
-// Makes a list of filters from a normal filter string "Image Files (*.png *.jpg)"
-QStringList qt_clean_filter_list(const QString &filter)
-{
- QRegExp regexp(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
- QString f = filter;
- int i = regexp.indexIn(f);
- if (i >= 0)
- f = regexp.cap(2);
- return f.split(QLatin1Char(' '), QString::SkipEmptyParts);
-}
-
-/*!
- \internal
-
- Sets the current name filter to be nameFilter and
- update the qFileDialogUi->fileNameEdit when in AcceptSave mode with the new extension.
-*/
-void QFileDialogPrivate::_q_useNameFilter(int index)
-{
- if (index == nameFilters.size()) {
- QAbstractItemModel *comboModel = qFileDialogUi->fileTypeCombo->model();
- nameFilters.append(comboModel->index(comboModel->rowCount() - 1, 0).data().toString());
- }
-
- QString nameFilter = nameFilters.at(index);
- QStringList newNameFilters = qt_clean_filter_list(nameFilter);
- if (acceptMode == QFileDialog::AcceptSave) {
- QString newNameFilterExtension;
- if (newNameFilters.count() > 0)
- newNameFilterExtension = QFileInfo(newNameFilters.at(0)).suffix();
-
- QString fileName = lineEdit()->text();
- const QString fileNameExtension = QFileInfo(fileName).suffix();
- if (!fileNameExtension.isEmpty() && !newNameFilterExtension.isEmpty()) {
- const int fileNameExtensionLength = fileNameExtension.count();
- fileName.replace(fileName.count() - fileNameExtensionLength,
- fileNameExtensionLength, newNameFilterExtension);
- qFileDialogUi->listView->clearSelection();
- lineEdit()->setText(fileName);
- }
- }
-
- model->setNameFilters(newNameFilters);
-}
-
-/*!
- \internal
-
- This is called when the model index corresponding to the current file is changed
- from \a index to \a current.
-*/
-void QFileDialogPrivate::_q_selectionChanged()
-{
- QModelIndexList indexes = qFileDialogUi->listView->selectionModel()->selectedRows();
- bool stripDirs = (fileMode != QFileDialog::DirectoryOnly && fileMode != QFileDialog::Directory);
-
- QStringList allFiles;
- for (int i = 0; i < indexes.count(); ++i) {
- if (stripDirs && model->isDir(mapToSource(indexes.at(i))))
- continue;
- allFiles.append(indexes.at(i).data().toString());
- }
- if (allFiles.count() > 1)
- for (int i = 0; i < allFiles.count(); ++i) {
- allFiles.replace(i, QString(QLatin1Char('"') + allFiles.at(i) + QLatin1Char('"')));
- }
-
- QString finalFiles = allFiles.join(QLatin1String(" "));
- if (!finalFiles.isEmpty() && !lineEdit()->hasFocus() && lineEdit()->isVisible())
- lineEdit()->setText(finalFiles);
- else
- _q_updateOkButton();
-}
-
-/*!
- \internal
-
- Includes hidden files and directories in the items displayed in the dialog.
-*/
-void QFileDialogPrivate::_q_showHidden()
-{
- Q_Q(QFileDialog);
- QDir::Filters dirFilters = q->filter();
- if (showHiddenAction->isChecked())
- dirFilters |= QDir::Hidden;
- else
- dirFilters &= ~QDir::Hidden;
- q->setFilter(dirFilters);
-}
-
-/*!
- \internal
-
- When parent is root and rows have been inserted when none was there before
- then select the first one.
-*/
-void QFileDialogPrivate::_q_rowsInserted(const QModelIndex &parent)
-{
- if (!qFileDialogUi->treeView
- || parent != qFileDialogUi->treeView->rootIndex()
- || !qFileDialogUi->treeView->selectionModel()
- || qFileDialogUi->treeView->selectionModel()->hasSelection()
- || qFileDialogUi->treeView->model()->rowCount(parent) == 0)
- return;
-}
-
-void QFileDialogPrivate::_q_fileRenamed(const QString &path, const QString oldName, const QString newName)
-{
- if (fileMode == QFileDialog::Directory || fileMode == QFileDialog::DirectoryOnly) {
- if (path == rootPath() && lineEdit()->text() == oldName)
- lineEdit()->setText(newName);
- }
-}
-
-/*!
- \internal
-
- For the list and tree view watch keys to goto parent and back in the history
-
- returns true if handled
-*/
-bool QFileDialogPrivate::itemViewKeyboardEvent(QKeyEvent *event) {
-
- Q_Q(QFileDialog);
- switch (event->key()) {
- case Qt::Key_Backspace:
- _q_navigateToParent();
- return true;
- case Qt::Key_Back:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- return false;
-#endif
- case Qt::Key_Left:
- if (event->key() == Qt::Key_Back || event->modifiers() == Qt::AltModifier) {
- _q_navigateBackward();
- return true;
- }
- break;
- case Qt::Key_Escape:
- q->hide();
- return true;
- default:
- break;
- }
- return false;
-}
-
-QString QFileDialogPrivate::getEnvironmentVariable(const QString &string)
-{
-#ifdef Q_OS_UNIX
- if (string.size() > 1 && string.startsWith(QLatin1Char('$'))) {
- return QString::fromLocal8Bit(getenv(string.mid(1).toLatin1().constData()));
- }
-#else
- if (string.size() > 2 && string.startsWith(QLatin1Char('%')) && string.endsWith(QLatin1Char('%'))) {
- return QString::fromLocal8Bit(qgetenv(string.mid(1, string.size() - 2).toLatin1().constData()));
- }
-#endif
- return string;
-}
-
-void QFileDialogComboBox::init(QFileDialogPrivate *d_pointer) {
- d_ptr = d_pointer;
- urlModel = new QUrlModel(this);
- urlModel->showFullPath = true;
- urlModel->setFileSystemModel(d_ptr->model);
- setModel(urlModel);
-}
-
-void QFileDialogComboBox::showPopup()
-{
- if (model()->rowCount() > 1)
- QComboBox::showPopup();
-
- urlModel->setUrls(QList<QUrl>());
- QList<QUrl> list;
- QModelIndex idx = d_ptr->model->index(d_ptr->rootPath());
- while (idx.isValid()) {
- QUrl url = QUrl::fromLocalFile(idx.data(QFileSystemModel::FilePathRole).toString());
- if (url.isValid())
- list.append(url);
- idx = idx.parent();
- }
- // add "my computer"
- list.append(QUrl::fromLocalFile(QLatin1String("")));
- urlModel->addUrls(list, 0);
- idx = model()->index(model()->rowCount() - 1, 0);
-
- // append history
- QList<QUrl> urls;
- for (int i = 0; i < m_history.count(); ++i) {
- QUrl path = QUrl::fromLocalFile(m_history.at(i));
- if (!urls.contains(path))
- urls.prepend(path);
- }
- if (urls.count() > 0) {
- model()->insertRow(model()->rowCount());
- idx = model()->index(model()->rowCount()-1, 0);
- // ### TODO maybe add a horizontal line before this
- model()->setData(idx, QFileDialog::tr("Recent Places"));
- QStandardItemModel *m = qobject_cast<QStandardItemModel*>(model());
- if (m) {
- Qt::ItemFlags flags = m->flags(idx);
- flags &= ~Qt::ItemIsEnabled;
- m->item(idx.row(), idx.column())->setFlags(flags);
- }
- urlModel->addUrls(urls, -1, false);
- }
- setCurrentIndex(0);
-
- QComboBox::showPopup();
-}
-
-// Exact same as QComboBox::paintEvent(), except we elide the text.
-void QFileDialogComboBox::paintEvent(QPaintEvent *)
-{
- QStylePainter painter(this);
- painter.setPen(palette().color(QPalette::Text));
-
- // draw the combobox frame, focusrect and selected etc.
- QStyleOptionComboBox opt;
- initStyleOption(&opt);
-
- QRect editRect = style()->subControlRect(QStyle::CC_ComboBox, &opt,
- QStyle::SC_ComboBoxEditField, this);
- int size = editRect.width() - opt.iconSize.width() - 4;
- opt.currentText = opt.fontMetrics.elidedText(opt.currentText, Qt::ElideMiddle, size);
- painter.drawComplexControl(QStyle::CC_ComboBox, opt);
-
- // draw the icon and text
- painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
-}
-
-QFileDialogListView::QFileDialogListView(QWidget *parent) : QListView(parent)
-{
-}
-
-void QFileDialogListView::init(QFileDialogPrivate *d_pointer)
-{
- d_ptr = d_pointer;
- setSelectionBehavior(QAbstractItemView::SelectRows);
- setWrapping(true);
- setResizeMode(QListView::Adjust);
- setEditTriggers(QAbstractItemView::EditKeyPressed);
- setContextMenuPolicy(Qt::CustomContextMenu);
-#ifndef QT_NO_DRAGANDDROP
- setDragDropMode(QAbstractItemView::InternalMove);
-#endif
-}
-
-QSize QFileDialogListView::sizeHint() const
-{
- int height = qMax(10, sizeHintForRow(0));
- return QSize(QListView::sizeHint().width() * 2, height * 30);
-}
-
-void QFileDialogListView::keyPressEvent(QKeyEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
- QListView::keyPressEvent(e);
- return;
- }
-#endif // QT_KEYPAD_NAVIGATION
-
- if (!d_ptr->itemViewKeyboardEvent(e))
- QListView::keyPressEvent(e);
- e->accept();
-}
-
-QFileDialogTreeView::QFileDialogTreeView(QWidget *parent) : QTreeView(parent)
-{
-}
-
-void QFileDialogTreeView::init(QFileDialogPrivate *d_pointer)
-{
- d_ptr = d_pointer;
- setSelectionBehavior(QAbstractItemView::SelectRows);
- setRootIsDecorated(false);
- setItemsExpandable(false);
- setSortingEnabled(true);
- header()->setSortIndicator(0, Qt::AscendingOrder);
- header()->setStretchLastSection(false);
- setTextElideMode(Qt::ElideMiddle);
- setEditTriggers(QAbstractItemView::EditKeyPressed);
- setContextMenuPolicy(Qt::CustomContextMenu);
-#ifndef QT_NO_DRAGANDDROP
- setDragDropMode(QAbstractItemView::InternalMove);
-#endif
-}
-
-void QFileDialogTreeView::keyPressEvent(QKeyEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
- QTreeView::keyPressEvent(e);
- return;
- }
-#endif // QT_KEYPAD_NAVIGATION
-
- if (!d_ptr->itemViewKeyboardEvent(e))
- QTreeView::keyPressEvent(e);
- e->accept();
-}
-
-QSize QFileDialogTreeView::sizeHint() const
-{
- int height = qMax(10, sizeHintForRow(0));
- QSize sizeHint = header()->sizeHint();
- return QSize(sizeHint.width() * 4, height * 30);
-}
-
-/*!
- // FIXME: this is a hack to avoid propagating key press events
- // to the dialog and from there to the "Ok" button
-*/
-void QFileDialogLineEdit::keyPressEvent(QKeyEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
- QLineEdit::keyPressEvent(e);
- return;
- }
-#endif // QT_KEYPAD_NAVIGATION
-
- int key = e->key();
- QLineEdit::keyPressEvent(e);
- if (key != Qt::Key_Escape)
- e->accept();
- if (hideOnEsc && (key == Qt::Key_Escape || key == Qt::Key_Return || key == Qt::Key_Enter)) {
- e->accept();
- hide();
- d_ptr->currentView()->setFocus(Qt::ShortcutFocusReason);
- }
-}
-
-#ifndef QT_NO_FSCOMPLETER
-
-QString QFSCompleter::pathFromIndex(const QModelIndex &index) const
-{
- const QFileSystemModel *dirModel;
- if (proxyModel)
- dirModel = qobject_cast<const QFileSystemModel *>(proxyModel->sourceModel());
- else
- dirModel = sourceModel;
- QString currentLocation = dirModel->rootPath();
- QString path = index.data(QFileSystemModel::FilePathRole).toString();
- if (!currentLocation.isEmpty() && path.startsWith(currentLocation)) {
-#if defined(Q_OS_UNIX) || defined(Q_OS_WINCE)
- if (currentLocation == QDir::separator())
- return path.mid(currentLocation.length());
-#endif
- if (currentLocation.endsWith(QLatin1Char('/')))
- return path.mid(currentLocation.length());
- else
- return path.mid(currentLocation.length()+1);
- }
- return index.data(QFileSystemModel::FilePathRole).toString();
-}
-
-QStringList QFSCompleter::splitPath(const QString &path) const
-{
- if (path.isEmpty())
- return QStringList(completionPrefix());
-
- QString pathCopy = QDir::toNativeSeparators(path);
- QString sep = QDir::separator();
-#if defined(Q_OS_SYMBIAN)
- if (pathCopy == QLatin1String("\\"))
- return QStringList(pathCopy);
-#elif defined(Q_OS_WIN)
- if (pathCopy == QLatin1String("\\") || pathCopy == QLatin1String("\\\\"))
- return QStringList(pathCopy);
- QString doubleSlash(QLatin1String("\\\\"));
- if (pathCopy.startsWith(doubleSlash))
- pathCopy = pathCopy.mid(2);
- else
- doubleSlash.clear();
-#endif
-
- QRegExp re(QLatin1Char('[') + QRegExp::escape(sep) + QLatin1Char(']'));
-
-#if defined(Q_OS_SYMBIAN)
- QStringList parts = pathCopy.split(re, QString::SkipEmptyParts);
- if (pathCopy.endsWith(sep))
- parts.append(QString());
-#elif defined(Q_OS_WIN)
- QStringList parts = pathCopy.split(re, QString::SkipEmptyParts);
- if (!doubleSlash.isEmpty() && !parts.isEmpty())
- parts[0].prepend(doubleSlash);
- if (pathCopy.endsWith(sep))
- parts.append(QString());
-#else
- QStringList parts = pathCopy.split(re);
- if (path[0] == sep[0]) // read the "/" at the beginning as the split removed it
- parts[0] = sep[0];
-#endif
-
-#if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
- bool startsFromRoot = !parts.isEmpty() && parts[0].endsWith(QLatin1Char(':'));
-#else
- bool startsFromRoot = path[0] == sep[0];
-#endif
- if (parts.count() == 1 || (parts.count() > 1 && !startsFromRoot)) {
- const QFileSystemModel *dirModel;
- if (proxyModel)
- dirModel = qobject_cast<const QFileSystemModel *>(proxyModel->sourceModel());
- else
- dirModel = sourceModel;
- QString currentLocation = QDir::toNativeSeparators(dirModel->rootPath());
-#if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
- if (currentLocation.endsWith(QLatin1Char(':')))
- currentLocation.append(sep);
-#endif
- if (currentLocation.contains(sep) && path != currentLocation) {
- QStringList currentLocationList = splitPath(currentLocation);
- while (!currentLocationList.isEmpty()
- && parts.count() > 0
- && parts.at(0) == QLatin1String("..")) {
- parts.removeFirst();
- currentLocationList.removeLast();
- }
- if (!currentLocationList.isEmpty() && currentLocationList.last().isEmpty())
- currentLocationList.removeLast();
- return currentLocationList + parts;
- }
- }
- return parts;
-}
-
-#endif // QT_NO_COMPLETER
-
-#ifdef QT3_SUPPORT
-/*!
- Use selectedFiles() instead.
-
- \oldcode
- QString selected = dialog->selectedFile();
- \newcode
- QStringList files = dialog->selectedFiles();
- QString selected;
- if (!files.isEmpty())
- selected = files[0];
- \endcode
-*/
-QString QFileDialog::selectedFile() const
-{
- QStringList files = selectedFiles();
- return files.size() ? files.at(0) : QString();
-}
-
-/*!
- \typedef QFileDialog::Mode
-
- Use QFileDialog::FileMode instead.
-*/
-
-/*!
- \fn void QFileDialog::setMode(FileMode m)
-
- Use setFileMode() instead.
-*/
-
-/*!
- \fn FileMode QFileDialog::mode() const
-
- Use fileMode() instead.
-*/
-
-/*!
- \fn void QFileDialog::setDir(const QString &directory)
-
- Use setDirectory() instead.
-*/
-
-/*!
- \fn void QFileDialog::setDir( const QDir &directory )
-
- Use setDirectory() instead.
-*/
-
-/*!
- \fn QStringList QFileDialog::getOpenFileNames(const QString &filter,
- const QString &dir, QWidget *parent, const char* name,
- const QString &caption, QString *selectedFilter, bool resolveSymlinks)
-
- Use the getOpenFileNames() overload that takes \a parent as the first
- argument instead.
-*/
-
-/*!
- \fn QString QFileDialog::getOpenFileName(const QString &dir,
- const QString &filter, QWidget *parent = 0, const char *name,
- const QString &caption, QString *selectedFilter, bool resolveSymlinks)
-
- Use the getOpenFileName() overload that takes \a parent as the first
- argument instead.
-*/
-
-/*!
- \fn QString QFileDialog::getSaveFileName(const QString &dir,
- const QString &filter, QWidget *parent, const char *name,
- const QString &caption, QString *selectedFilter, bool resolveSymlinks)
-
- Use the getSaveFileName() overload that takes \a parent as the first
- argument instead.
-*/
-
-/*!
- \fn QString QFileDialog::getExistingDirectory(const QString &dir,
- QWidget *parent, const char *name, const QString &caption,
- bool dirOnly, bool resolveSymlinks)
-
- Use the getExistingDirectory() overload that takes \a parent as
- the first argument instead.
-*/
-
-#endif // QT3_SUPPORT
-
-QT_END_NAMESPACE
-
-#include "moc_qfiledialog.cpp"
-
-#endif // QT_NO_FILEDIALOG
diff --git a/src/gui/dialogs/qfiledialog.h b/src/gui/dialogs/qfiledialog.h
deleted file mode 100644
index fabb575a5a..0000000000
--- a/src/gui/dialogs/qfiledialog.h
+++ /dev/null
@@ -1,331 +0,0 @@
-/****************************************************************************
-**
-** 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 QFILEDIALOG_H
-#define QFILEDIALOG_H
-
-#include <QtCore/qdir.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_FILEDIALOG
-
-class QModelIndex;
-class QItemSelection;
-struct QFileDialogArgs;
-class QFileIconProvider;
-class QFileDialogPrivate;
-class QAbstractItemDelegate;
-class QAbstractProxyModel;
-class QUrl;
-
-class Q_GUI_EXPORT QFileDialog : public QDialog
-{
- Q_OBJECT
- Q_ENUMS(ViewMode FileMode AcceptMode Option)
- Q_FLAGS(Options)
- Q_PROPERTY(ViewMode viewMode READ viewMode WRITE setViewMode)
- Q_PROPERTY(FileMode fileMode READ fileMode WRITE setFileMode)
- Q_PROPERTY(AcceptMode acceptMode READ acceptMode WRITE setAcceptMode)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly DESIGNABLE false)
- Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks DESIGNABLE false)
- Q_PROPERTY(bool confirmOverwrite READ confirmOverwrite WRITE setConfirmOverwrite DESIGNABLE false)
- Q_PROPERTY(QString defaultSuffix READ defaultSuffix WRITE setDefaultSuffix)
- Q_PROPERTY(bool nameFilterDetailsVisible READ isNameFilterDetailsVisible
- WRITE setNameFilterDetailsVisible DESIGNABLE false)
- Q_PROPERTY(Options options READ options WRITE setOptions)
-
-public:
- enum ViewMode { Detail, List };
- enum FileMode { AnyFile, ExistingFile, Directory, ExistingFiles, DirectoryOnly };
- enum AcceptMode { AcceptOpen, AcceptSave };
- enum DialogLabel { LookIn, FileName, FileType, Accept, Reject };
-
- // ### Rename to FileDialogOption and FileDialogOptions for Qt 5.0
- enum Option
- {
- ShowDirsOnly = 0x00000001,
- DontResolveSymlinks = 0x00000002,
- DontConfirmOverwrite = 0x00000004,
- DontUseSheet = 0x00000008,
- DontUseNativeDialog = 0x00000010,
- ReadOnly = 0x00000020,
- HideNameFilterDetails = 0x00000040
- };
- Q_DECLARE_FLAGS(Options, Option)
-
- QFileDialog(QWidget *parent, Qt::WindowFlags f);
- explicit QFileDialog(QWidget *parent = 0,
- const QString &caption = QString(),
- const QString &directory = QString(),
- const QString &filter = QString());
- ~QFileDialog();
-
- void setDirectory(const QString &directory);
- inline void setDirectory(const QDir &directory);
- QDir directory() const;
-
- void selectFile(const QString &filename);
- QStringList selectedFiles() const;
-
-#ifdef QT_DEPRECATED
- QT_DEPRECATED void setFilter(const QString &filter);
- QT_DEPRECATED void setFilters(const QStringList &filters);
- QT_DEPRECATED QStringList filters() const;
- QT_DEPRECATED void selectFilter(const QString &filter);
- QT_DEPRECATED QString selectedFilter() const;
-#endif
- void setNameFilterDetailsVisible(bool enabled);
- bool isNameFilterDetailsVisible() const;
-
- void setNameFilter(const QString &filter);
- void setNameFilters(const QStringList &filters);
- QStringList nameFilters() const;
- void selectNameFilter(const QString &filter);
- QString selectedNameFilter() const;
-
- QDir::Filters filter() const;
- void setFilter(QDir::Filters filters);
-
- void setViewMode(ViewMode mode);
- ViewMode viewMode() const;
-
- void setFileMode(FileMode mode);
- FileMode fileMode() const;
-
- void setAcceptMode(AcceptMode mode);
- AcceptMode acceptMode() const;
-
- void setReadOnly(bool enabled);
- bool isReadOnly() const;
-
- void setResolveSymlinks(bool enabled);
- bool resolveSymlinks() const;
-
- void setSidebarUrls(const QList<QUrl> &urls);
- QList<QUrl> sidebarUrls() const;
-
- QByteArray saveState() const;
- bool restoreState(const QByteArray &state);
-
- void setConfirmOverwrite(bool enabled);
- bool confirmOverwrite() const;
-
- void setDefaultSuffix(const QString &suffix);
- QString defaultSuffix() const;
-
- void setHistory(const QStringList &paths);
- QStringList history() const;
-
- void setItemDelegate(QAbstractItemDelegate *delegate);
- QAbstractItemDelegate *itemDelegate() const;
-
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
-
- void setLabelText(DialogLabel label, const QString &text);
- QString labelText(DialogLabel label) const;
-
-#ifndef QT_NO_PROXYMODEL
- void setProxyModel(QAbstractProxyModel *model);
- QAbstractProxyModel *proxyModel() const;
-#endif
-
- void setOption(Option option, bool on = true);
- bool testOption(Option option) const;
- void setOptions(Options options);
- Options options() const;
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
- void setVisible(bool visible);
-
-Q_SIGNALS:
- void fileSelected(const QString &file);
- void filesSelected(const QStringList &files);
- void currentChanged(const QString &path);
- void directoryEntered(const QString &directory);
- void filterSelected(const QString &filter);
-
-public:
-#ifdef QT3_SUPPORT
- typedef FileMode Mode;
- inline QT3_SUPPORT void setMode(FileMode m) { setFileMode(m); }
- inline QT3_SUPPORT FileMode mode() const { return fileMode(); }
- inline QT3_SUPPORT void setDir(const QString &directory) { setDirectory(directory); }
- inline QT3_SUPPORT void setDir( const QDir &directory ) { setDirectory(directory); }
- QT3_SUPPORT QString selectedFile() const;
-#endif
-
- static QString getOpenFileName(QWidget *parent = 0,
- const QString &caption = QString(),
- const QString &dir = QString(),
- const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0);
-
- static QString getSaveFileName(QWidget *parent = 0,
- const QString &caption = QString(),
- const QString &dir = QString(),
- const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0);
-
- static QString getExistingDirectory(QWidget *parent = 0,
- const QString &caption = QString(),
- const QString &dir = QString(),
- Options options = ShowDirsOnly);
-
- static QStringList getOpenFileNames(QWidget *parent = 0,
- const QString &caption = QString(),
- const QString &dir = QString(),
- const QString &filter = QString(),
- QString *selectedFilter = 0,
- Options options = 0);
-
-#ifdef QT3_SUPPORT
- inline static QString QT3_SUPPORT getOpenFileName(const QString &dir,
- const QString &filter = QString(),
- QWidget *parent = 0, const char* name = 0,
- const QString &caption = QString(),
- QString *selectedFilter = 0,
- bool resolveSymlinks = true)
- { Q_UNUSED(name);
- return getOpenFileName(parent, caption, dir, filter, selectedFilter,
- resolveSymlinks ? Option(0) : DontResolveSymlinks); }
-
- inline static QString QT3_SUPPORT getSaveFileName(const QString &dir,
- const QString &filter = QString(),
- QWidget *parent = 0, const char* name = 0,
- const QString &caption = QString(),
- QString *selectedFilter = 0,
- bool resolveSymlinks = true)
- { Q_UNUSED(name);
- return getSaveFileName(parent, caption, dir, filter, selectedFilter,
- resolveSymlinks ? Option(0) : DontResolveSymlinks); }
-
- inline static QString QT3_SUPPORT getExistingDirectory(const QString &dir,
- QWidget *parent = 0,
- const char* name = 0,
- const QString &caption = QString(),
- bool dirOnly = true,
- bool resolveSymlinks = true)
- { Q_UNUSED(name);
- return getExistingDirectory(parent, caption, dir,
- Options((resolveSymlinks ? Option(0) : DontResolveSymlinks)
- | (dirOnly ? ShowDirsOnly : Option(0)))); }
-
- inline static QStringList QT3_SUPPORT getOpenFileNames(const QString &filter,
- const QString &dir = QString(),
- QWidget *parent = 0,
- const char* name = 0,
- const QString &caption = QString(),
- QString *selectedFilter = 0,
- bool resolveSymlinks = true)
- { Q_UNUSED(name);
- return getOpenFileNames(parent, caption, dir, filter, selectedFilter,
- resolveSymlinks ? Option(0) : DontResolveSymlinks); }
-#endif // QT3_SUPPORT
-
-protected:
- QFileDialog(const QFileDialogArgs &args);
- void done(int result);
- void accept();
- void changeEvent(QEvent *e);
-
-private:
- Q_DECLARE_PRIVATE(QFileDialog)
- Q_DISABLE_COPY(QFileDialog)
-
- Q_PRIVATE_SLOT(d_func(), void _q_pathChanged(const QString &))
-
- Q_PRIVATE_SLOT(d_func(), void _q_navigateBackward())
- Q_PRIVATE_SLOT(d_func(), void _q_navigateForward())
- Q_PRIVATE_SLOT(d_func(), void _q_navigateToParent())
- Q_PRIVATE_SLOT(d_func(), void _q_createDirectory())
- Q_PRIVATE_SLOT(d_func(), void _q_showListView())
- Q_PRIVATE_SLOT(d_func(), void _q_showDetailsView())
- Q_PRIVATE_SLOT(d_func(), void _q_showContextMenu(const QPoint &))
- Q_PRIVATE_SLOT(d_func(), void _q_renameCurrent())
- Q_PRIVATE_SLOT(d_func(), void _q_deleteCurrent())
- Q_PRIVATE_SLOT(d_func(), void _q_showHidden())
- Q_PRIVATE_SLOT(d_func(), void _q_updateOkButton())
- Q_PRIVATE_SLOT(d_func(), void _q_currentChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_enterDirectory(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_goToDirectory(const QString &path))
- Q_PRIVATE_SLOT(d_func(), void _q_useNameFilter(int index))
- Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_goToUrl(const QUrl &url))
- Q_PRIVATE_SLOT(d_func(), void _q_goHome())
- Q_PRIVATE_SLOT(d_func(), void _q_showHeader(QAction *))
- Q_PRIVATE_SLOT(d_func(), void _q_autoCompleteFileName(const QString &text))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsInserted(const QModelIndex & parent))
- Q_PRIVATE_SLOT(d_func(), void _q_fileRenamed(const QString &path,
- const QString oldName, const QString newName))
-#if defined(Q_WS_MAC)
- Q_PRIVATE_SLOT(d_func(), void _q_macRunNativeAppModalPanel())
-#endif
-};
-
-inline void QFileDialog::setDirectory(const QDir &adirectory)
-{ setDirectory(adirectory.absolutePath()); }
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QFileDialog::Options)
-
-#endif // QT_NO_FILEDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QFILEDIALOG_H
diff --git a/src/gui/dialogs/qfiledialog.ui b/src/gui/dialogs/qfiledialog.ui
deleted file mode 100644
index dcb08114e2..0000000000
--- a/src/gui/dialogs/qfiledialog.ui
+++ /dev/null
@@ -1,356 +0,0 @@
-<ui version="4.0" >
- <comment>*********************************************************************
-**
-** 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$
-**
-*********************************************************************</comment>
- <class>QFileDialog</class>
- <widget class="QDialog" name="QFileDialog" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>521</width>
- <height>316</height>
- </rect>
- </property>
- <property name="sizeGripEnabled" >
- <bool>true</bool>
- </property>
- <layout class="QGridLayout" >
- <item row="0" column="0" >
- <widget class="QLabel" name="lookInLabel" >
- <property name="text" >
- <string>Look in:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1" colspan="2" >
- <layout class="QHBoxLayout" >
- <item>
- <widget class="QFileDialogComboBox" name="lookInCombo" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Ignored" >
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>50</width>
- <height>0</height>
- </size>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="backButton" >
- <property name="toolTip" >
- <string>Back</string>
- </property>
- <property name="accessibleName">
- <string>Back</string>
- </property>
- <property name="accessibleDescription">
- <string>Go back</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="forwardButton" >
- <property name="toolTip" >
- <string>Forward</string>
- </property>
- <property name="accessibleName">
- <string>Forward</string>
- </property>
- <property name="accessibleDescription">
- <string>Go forward</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="toParentButton" >
- <property name="toolTip" >
- <string>Parent Directory</string>
- </property>
- <property name="accessibleName">
- <string>Parent Directory</string>
- </property>
- <property name="accessibleDescription">
- <string>Go to the parent directory</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="newFolderButton" >
- <property name="toolTip" >
- <string>Create New Folder</string>
- </property>
- <property name="accessibleName">
- <string>Create New Folder</string>
- </property>
- <property name="accessibleDescription">
- <string>Create a New Folder</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="listModeButton" >
- <property name="toolTip" >
- <string>List View</string>
- </property>
- <property name="accessibleName">
- <string>List View</string>
- </property>
- <property name="accessibleDescription">
- <string>Change to list view mode</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="detailModeButton" >
- <property name="toolTip" >
- <string>Detail View</string>
- </property>
- <property name="accessibleName">
- <string>Detail View</string>
- </property>
- <property name="accessibleDescription">
- <string>Change to detail view mode</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0" colspan="3" >
- <widget class="QSplitter" name="splitter" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <widget class="QSidebar" name="sidebar" />
- <widget class="QFrame" name="frame" >
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>0</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QStackedWidget" name="stackedWidget" >
- <property name="currentIndex" >
- <number>0</number>
- </property>
- <widget class="QWidget" name="page" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>0</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QFileDialogListView" name="listView" />
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="page_2" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>0</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QFileDialogTreeView" name="treeView" />
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QLabel" name="fileNameLabel" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Minimum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- </widget>
- </item>
- <item row="2" column="1" >
- <widget class="QFileDialogLineEdit" name="fileNameEdit" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Expanding" >
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item rowspan="2" row="2" column="2" >
- <widget class="QDialogButtonBox" name="buttonBox" >
- <property name="orientation" >
- <enum>Qt::Vertical</enum>
- </property>
- <property name="standardButtons" >
- <set>QDialogButtonBox::Cancel|QDialogButtonBox::NoButton|QDialogButtonBox::Ok</set>
- </property>
- </widget>
- </item>
- <item row="3" column="0" >
- <widget class="QLabel" name="fileTypeLabel" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Preferred" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Files of type:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1" >
- <widget class="QComboBox" name="fileTypeCombo" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>QFileDialogTreeView</class>
- <extends>QTreeView</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- <customwidget>
- <class>QFileDialogListView</class>
- <extends>QListView</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- <customwidget>
- <class>QSidebar</class>
- <extends>QListWidget</extends>
- <header>qsidebar_p.h</header>
- </customwidget>
- <customwidget>
- <class>QFileDialogLineEdit</class>
- <extends>QLineEdit</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- <customwidget>
- <class>QFileDialogComboBox</class>
- <extends>QComboBox</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- </customwidgets>
- <tabstops>
- <tabstop>lookInCombo</tabstop>
- <tabstop>backButton</tabstop>
- <tabstop>forwardButton</tabstop>
- <tabstop>toParentButton</tabstop>
- <tabstop>newFolderButton</tabstop>
- <tabstop>listModeButton</tabstop>
- <tabstop>detailModeButton</tabstop>
- <tabstop>sidebar</tabstop>
- <tabstop>listView</tabstop>
- <tabstop>fileNameEdit</tabstop>
- <tabstop>fileTypeCombo</tabstop>
- <tabstop>buttonBox</tabstop>
- <tabstop>treeView</tabstop>
- </tabstops>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/gui/dialogs/qfiledialog_embedded.ui b/src/gui/dialogs/qfiledialog_embedded.ui
deleted file mode 100644
index e8de400cab..0000000000
--- a/src/gui/dialogs/qfiledialog_embedded.ui
+++ /dev/null
@@ -1,340 +0,0 @@
-<ui version="4.0" >
- <comment>*********************************************************************
-**
-** 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$
-**
-*********************************************************************</comment>
- <class>QFileDialog</class>
- <widget class="QDialog" name="QFileDialog" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>240</width>
- <height>320</height>
- </rect>
- </property>
- <property name="sizeGripEnabled" >
- <bool>true</bool>
- </property>
- <layout class="QVBoxLayout" >
- <item>
- <widget class="QFileDialogComboBox" name="lookInCombo" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Expanding" >
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" >
- <item>
- <widget class="QToolButton" name="backButton" >
- <property name="toolTip" >
- <string>Back</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="forwardButton" >
- <property name="toolTip" >
- <string>Forward</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="toParentButton" >
- <property name="toolTip" >
- <string>Parent Directory</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="newFolderButton" >
- <property name="toolTip" >
- <string>Create New Folder</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="listModeButton" >
- <property name="toolTip" >
- <string>List View</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="detailModeButton" >
- <property name="toolTip" >
- <string>Detail View</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QSplitter" name="splitter" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <widget class="QSidebar" name="sidebar" />
- <widget class="QFrame" name="frame" >
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>0</number>
- </property>
- <property name="margin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QStackedWidget" name="stackedWidget" >
- <property name="currentIndex" >
- <number>0</number>
- </property>
- <widget class="QWidget" name="page" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>108</width>
- <height>164</height>
- </rect>
- </property>
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>0</number>
- </property>
- <property name="margin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QFileDialogListView" name="listView" />
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="page_2" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>100</width>
- <height>30</height>
- </rect>
- </property>
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>0</number>
- </property>
- <property name="margin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QFileDialogTreeView" name="treeView" />
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item>
- <layout class="QGridLayout" >
- <item row="0" column="0" >
- <widget class="QFileDialogLineEdit" name="fileNameEdit" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Expanding" >
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item rowspan="2" row="0" column="1" >
- <widget class="QDialogButtonBox" name="buttonBox" >
- <property name="orientation" >
- <enum>Qt::Vertical</enum>
- </property>
- <property name="standardButtons" >
- <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
- </property>
- </widget>
- </item>
- <item row="1" column="0" >
- <widget class="QComboBox" name="fileTypeCombo" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QLabel" name="fileNameLabel" >
- <property name="enabled" >
- <bool>false</bool>
- </property>
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Fixed" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="maximumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="fileTypeLabel" >
- <property name="enabled" >
- <bool>false</bool>
- </property>
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Fixed" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="text" >
- <string>Files of type:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="lookInLabel" >
- <property name="enabled" >
- <bool>false</bool>
- </property>
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Fixed" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="text" >
- <string>Look in:</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>QFileDialogTreeView</class>
- <extends>QTreeView</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- <customwidget>
- <class>QFileDialogListView</class>
- <extends>QListView</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- <customwidget>
- <class>QSidebar</class>
- <extends>QListWidget</extends>
- <header>qsidebar_p.h</header>
- </customwidget>
- <customwidget>
- <class>QFileDialogLineEdit</class>
- <extends>QLineEdit</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- <customwidget>
- <class>QFileDialogComboBox</class>
- <extends>QComboBox</extends>
- <header>qfiledialog_p.h</header>
- </customwidget>
- </customwidgets>
- <tabstops>
- <tabstop>lookInCombo</tabstop>
- <tabstop>backButton</tabstop>
- <tabstop>forwardButton</tabstop>
- <tabstop>toParentButton</tabstop>
- <tabstop>newFolderButton</tabstop>
- <tabstop>listModeButton</tabstop>
- <tabstop>detailModeButton</tabstop>
- <tabstop>sidebar</tabstop>
- <tabstop>listView</tabstop>
- <tabstop>fileNameEdit</tabstop>
- <tabstop>fileTypeCombo</tabstop>
- <tabstop>buttonBox</tabstop>
- <tabstop>treeView</tabstop>
- </tabstops>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/gui/dialogs/qfiledialog_mac.mm b/src/gui/dialogs/qfiledialog_mac.mm
deleted file mode 100644
index 832f9bfaf8..0000000000
--- a/src/gui/dialogs/qfiledialog_mac.mm
+++ /dev/null
@@ -1,1157 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfiledialog.h"
-
-#ifndef QT_NO_FILEDIALOG
-
-/*****************************************************************************
- QFileDialog debug facilities
- *****************************************************************************/
-//#define DEBUG_FILEDIALOG_FILTERS
-
-#include <qapplication.h>
-#include <private/qapplication_p.h>
-#include <private/qfiledialog_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <qregexp.h>
-#include <qbuffer.h>
-#include <qdebug.h>
-#include <qstringlist.h>
-#include <qaction.h>
-#include <qtextcodec.h>
-#include <qvarlengtharray.h>
-#include <qdesktopwidget.h>
-#include <stdlib.h>
-#include <qabstracteventdispatcher.h>
-#import <AppKit/NSSavePanel.h>
-#include "ui_qfiledialog.h"
-
-QT_BEGIN_NAMESPACE
-
-extern QStringList qt_make_filter_list(const QString &filter); // qfiledialog.cpp
-extern QStringList qt_clean_filter_list(const QString &filter); // qfiledialog.cpp
-extern const char *qt_file_dialog_filter_reg_exp; // qfiledialog.cpp
-extern bool qt_mac_is_macsheet(const QWidget *w); // qwidget_mac.mm
-
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QFileDialogPrivate)
-QT_FORWARD_DECLARE_CLASS(QString)
-QT_FORWARD_DECLARE_CLASS(QStringList)
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QAction)
-QT_FORWARD_DECLARE_CLASS(QFileInfo)
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate)
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
- : NSObject<NSOpenSavePanelDelegate>
-#else
- : NSObject
-#endif
-{
- @public
- NSOpenPanel *mOpenPanel;
- NSSavePanel *mSavePanel;
- NSView *mAccessoryView;
- NSPopUpButton *mPopUpButton;
- NSTextField *mTextField;
- QFileDialogPrivate *mPriv;
- NSString *mCurrentDir;
- bool mConfirmOverwrite;
- int mReturnCode;
-
- QT_PREPEND_NAMESPACE(QFileDialog::AcceptMode) mAcceptMode;
- QT_PREPEND_NAMESPACE(QDir::Filters) *mQDirFilter;
- QT_PREPEND_NAMESPACE(QFileDialog::FileMode) mFileMode;
- QT_PREPEND_NAMESPACE(QFileDialog::Options) *mFileOptions;
-
- QString *mLastFilterCheckPath;
- QString *mCurrentSelection;
- QStringList *mQDirFilterEntryList;
- QStringList *mNameFilterDropDownList;
- QStringList *mSelectedNameFilter;
-}
-
-- (NSString *)strip:(const QString &)label;
-- (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename;
-- (void)filterChanged:(id)sender;
-- (void)showModelessPanel;
-- (BOOL)runApplicationModalPanel;
-- (void)showWindowModalSheet:(QWidget *)docWidget;
-- (void)updateProperties;
-- (QStringList)acceptableExtensionsForSave;
-- (QString)removeExtensions:(const QString &)filter;
-- (void)createTextField;
-- (void)createPopUpButton:(const QString &)selectedFilter hideDetails:(BOOL)hideDetails;
-- (QStringList)findStrippedFilterWithVisualFilterName:(QString)name;
-- (void)createAccessory;
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate)
-
-- (id)initWithAcceptMode:(QT_PREPEND_NAMESPACE(QFileDialog::AcceptMode))acceptMode
- title:(const QString &)title
- hideNameFilterDetails:(bool)hideNameFilterDetails
- qDirFilter:(QT_PREPEND_NAMESPACE(QDir::Filters))qDirFilter
- fileOptions:(QT_PREPEND_NAMESPACE(QFileDialog::Options))fileOptions
- fileMode:(QT_PREPEND_NAMESPACE(QFileDialog::FileMode))fileMode
- selectFile:(const QString &)selectFile
- confirmOverwrite:(bool)confirm
- priv:(QFileDialogPrivate *)priv
-{
- self = [super init];
-
- mAcceptMode = acceptMode;
- if (mAcceptMode == QT_PREPEND_NAMESPACE(QFileDialog::AcceptOpen)){
- mOpenPanel = [NSOpenPanel openPanel];
- mSavePanel = mOpenPanel;
- } else {
- mSavePanel = [NSSavePanel savePanel];
- mOpenPanel = 0;
- }
-
- [mSavePanel setLevel:NSModalPanelWindowLevel];
- [mSavePanel setDelegate:self];
- mQDirFilter = new QT_PREPEND_NAMESPACE(QDir::Filters)(qDirFilter);
- mFileOptions = new QT_PREPEND_NAMESPACE(QFileDialog::Options)(fileOptions);
- mFileMode = fileMode;
- mConfirmOverwrite = confirm;
- mReturnCode = -1;
- mPriv = priv;
- mLastFilterCheckPath = new QString;
- mQDirFilterEntryList = new QStringList;
- mNameFilterDropDownList = new QStringList(priv->nameFilters);
- QString selectedVisualNameFilter = priv->qFileDialogUi->fileTypeCombo->currentText();
- mSelectedNameFilter = new QStringList([self findStrippedFilterWithVisualFilterName:selectedVisualNameFilter]);
-
- QFileInfo sel(selectFile);
- if (sel.isDir()){
- mCurrentDir = [qt_mac_QStringToNSString(sel.absoluteFilePath()) retain];
- mCurrentSelection = new QString;
- } else {
- mCurrentDir = [qt_mac_QStringToNSString(sel.absolutePath()) retain];
- mCurrentSelection = new QString(sel.absoluteFilePath());
- }
-
- [mSavePanel setTitle:qt_mac_QStringToNSString(title)];
- [self createPopUpButton:selectedVisualNameFilter hideDetails:hideNameFilterDetails];
- [self createTextField];
- [self createAccessory];
- [mSavePanel setAccessoryView:mNameFilterDropDownList->size() > 1 ? mAccessoryView : nil];
-
- if (mPriv){
- [mSavePanel setPrompt:[self strip:mPriv->acceptLabel]];
- if (mPriv->fileNameLabelExplicitlySat)
- [mSavePanel setNameFieldLabel:[self strip:mPriv->qFileDialogUi->fileNameLabel->text()]];
- }
-
- [self updateProperties];
- [mSavePanel retain];
- return self;
-}
-
-- (void)dealloc
-{
- delete mQDirFilter;
- delete mFileOptions;
- delete mLastFilterCheckPath;
- delete mQDirFilterEntryList;
- delete mNameFilterDropDownList;
- delete mSelectedNameFilter;
- delete mCurrentSelection;
-
- [mSavePanel orderOut:mSavePanel];
- [mSavePanel setAccessoryView:nil];
- [mPopUpButton release];
- [mTextField release];
- [mAccessoryView release];
- [mSavePanel setDelegate:nil];
- [mSavePanel release];
- [mCurrentDir release];
- [super dealloc];
-}
-
-- (NSString *)strip:(const QString &)label
-{
- QAction a(label, 0);
- return qt_mac_QStringToNSString(a.iconText());
-}
-
-- (void)closePanel
-{
- *mCurrentSelection = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)([mSavePanel filename]);
- [mSavePanel close];
-}
-
-- (void)showModelessPanel
-{
- if (mOpenPanel){
- QFileInfo info(*mCurrentSelection);
- NSString *filename = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.fileName());
- NSString *filepath = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.filePath());
- bool selectable = (mAcceptMode == QFileDialog::AcceptSave)
- || [self panel:nil shouldShowFilename:filepath];
- [mOpenPanel
- beginForDirectory:mCurrentDir
- file:selectable ? filename : nil
- types:nil
- modelessDelegate:self
- didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
- contextInfo:nil];
- }
-}
-
-- (BOOL)runApplicationModalPanel
-{
- QFileInfo info(*mCurrentSelection);
- NSString *filename = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.fileName());
- NSString *filepath = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.filePath());
- bool selectable = (mAcceptMode == QFileDialog::AcceptSave)
- || [self panel:nil shouldShowFilename:filepath];
- mReturnCode = [mSavePanel
- runModalForDirectory:mCurrentDir
- file:selectable ? filename : @"untitled"];
-
- QAbstractEventDispatcher::instance()->interrupt();
- return (mReturnCode == NSOKButton);
-}
-
-- (QT_PREPEND_NAMESPACE(QDialog::DialogCode))dialogResultCode
-{
- return (mReturnCode == NSOKButton) ? QT_PREPEND_NAMESPACE(QDialog::Accepted) : QT_PREPEND_NAMESPACE(QDialog::Rejected);
-}
-
-- (void)showWindowModalSheet:(QWidget *)docWidget
-{
- Q_UNUSED(docWidget);
- QFileInfo info(*mCurrentSelection);
- NSString *filename = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.fileName());
- NSString *filepath = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.filePath());
- bool selectable = (mAcceptMode == QFileDialog::AcceptSave)
- || [self panel:nil shouldShowFilename:filepath];
- [mSavePanel
- beginSheetForDirectory:mCurrentDir
- file:selectable ? filename : nil
-#ifdef QT_MAC_USE_COCOA
- modalForWindow:QT_PREPEND_NAMESPACE(qt_mac_window_for)(docWidget)
-#else
- modalForWindow:nil
-#endif
- modalDelegate:self
- didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
- contextInfo:nil];
-}
-
-- (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename
-{
- Q_UNUSED(sender);
-
- if ([filename length] == 0)
- return NO;
-
- // Always accept directories regardless of their names (unless it is a bundle):
- BOOL isDir;
- if ([[NSFileManager defaultManager] fileExistsAtPath:filename isDirectory:&isDir] && isDir) {
- if ([mSavePanel treatsFilePackagesAsDirectories] == NO) {
- if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filename] == NO)
- return YES;
- }
- }
-
- QString qtFileName = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)(filename);
- QFileInfo info(qtFileName.normalized(QT_PREPEND_NAMESPACE(QString::NormalizationForm_C)));
- QString path = info.absolutePath();
- if (path != *mLastFilterCheckPath){
- *mLastFilterCheckPath = path;
- *mQDirFilterEntryList = info.dir().entryList(*mQDirFilter);
- }
- // Check if the QDir filter accepts the file:
- if (!mQDirFilterEntryList->contains(info.fileName()))
- return NO;
-
- // No filter means accept everything
- if (mSelectedNameFilter->isEmpty())
- return YES;
- // Check if the current file name filter accepts the file:
- for (int i=0; i<mSelectedNameFilter->size(); ++i) {
- if (QDir::match(mSelectedNameFilter->at(i), qtFileName))
- return YES;
- }
- return NO;
-}
-
-- (NSString *)panel:(id)sender userEnteredFilename:(NSString *)filename confirmed:(BOOL)okFlag
-{
- Q_UNUSED(sender);
- if (!okFlag)
- return filename;
- if (mConfirmOverwrite)
- return filename;
-
- // User has clicked save, and no overwrite confirmation should occur.
- // To get the latter, we need to change the name we return (hence the prefix):
- return [@"___qt_very_unlikely_prefix_" stringByAppendingString:filename];
-}
-
-- (void)setNameFilters:(const QStringList &)filters hideDetails:(BOOL)hideDetails
-{
- [mPopUpButton removeAllItems];
- *mNameFilterDropDownList = filters;
- if (filters.size() > 0){
- for (int i=0; i<filters.size(); ++i) {
- QString filter = hideDetails ? [self removeExtensions:filters.at(i)] : filters.at(i);
- [mPopUpButton addItemWithTitle:QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(filter)];
- }
- [mPopUpButton selectItemAtIndex:0];
- [mSavePanel setAccessoryView:mAccessoryView];
- } else
- [mSavePanel setAccessoryView:nil];
-
- [self filterChanged:self];
-}
-
-- (void)filterChanged:(id)sender
-{
- // This mDelegate function is called when the _name_ filter changes.
- Q_UNUSED(sender);
- QString selection = mNameFilterDropDownList->value([mPopUpButton indexOfSelectedItem]);
- *mSelectedNameFilter = [self findStrippedFilterWithVisualFilterName:selection];
- [mSavePanel validateVisibleColumns];
- [self updateProperties];
- if (mPriv)
- mPriv->QNSOpenSavePanelDelegate_filterSelected([mPopUpButton indexOfSelectedItem]);
-}
-
-- (QString)currentNameFilter
-{
- return mNameFilterDropDownList->value([mPopUpButton indexOfSelectedItem]);
-}
-
-- (QStringList)selectedFiles
-{
- if (mOpenPanel)
- return QT_PREPEND_NAMESPACE(qt_mac_NSArrayToQStringList)([mOpenPanel filenames]);
- else{
- QStringList result;
- QString filename = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)([mSavePanel filename]);
- result << filename.remove(QLatin1String("___qt_very_unlikely_prefix_"));
- return result;
- }
-}
-
-- (void)updateProperties
-{
- // Call this functions if mFileMode, mFileOptions,
- // mNameFilterDropDownList or mQDirFilter changes.
- // The savepanel does not contain the neccessary functions for this.
- bool chooseFilesOnly = mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::ExistingFile)
- || mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::ExistingFiles);
- bool chooseDirsOnly = mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::Directory)
- || mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::DirectoryOnly)
- || *mFileOptions & QT_PREPEND_NAMESPACE(QFileDialog::ShowDirsOnly);
-
- [mOpenPanel setCanChooseFiles:!chooseDirsOnly];
- [mOpenPanel setCanChooseDirectories:!chooseFilesOnly];
- [mSavePanel setCanCreateDirectories:!(*mFileOptions & QT_PREPEND_NAMESPACE(QFileDialog::ReadOnly))];
- [mOpenPanel setAllowsMultipleSelection:(mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::ExistingFiles))];
- [mOpenPanel setResolvesAliases:!(*mFileOptions & QT_PREPEND_NAMESPACE(QFileDialog::DontResolveSymlinks))];
-
- QStringList ext = [self acceptableExtensionsForSave];
- if (mPriv && !ext.isEmpty() && !mPriv->defaultSuffix.isEmpty())
- ext.prepend(mPriv->defaultSuffix);
- [mSavePanel setAllowedFileTypes:ext.isEmpty() ? nil : QT_PREPEND_NAMESPACE(qt_mac_QStringListToNSMutableArray(ext))];
-
- if ([mSavePanel isVisible])
- [mOpenPanel validateVisibleColumns];
-}
-
-- (void)panelSelectionDidChange:(id)sender
-{
- Q_UNUSED(sender);
- if (mPriv) {
- QString selection = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString([mSavePanel filename]));
- if (selection != mCurrentSelection) {
- *mCurrentSelection = selection;
- mPriv->QNSOpenSavePanelDelegate_selectionChanged(selection);
- }
- }
-}
-
-- (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo
-{
- Q_UNUSED(panel);
- Q_UNUSED(contextInfo);
- mReturnCode = returnCode;
- if (mPriv)
- mPriv->QNSOpenSavePanelDelegate_panelClosed(returnCode == NSOKButton);
-}
-
-- (void)panel:(id)sender directoryDidChange:(NSString *)path
-{
- Q_UNUSED(sender);
- if (!mPriv)
- return;
- if ([path isEqualToString:mCurrentDir])
- return;
-
- [mCurrentDir release];
- mCurrentDir = [path retain];
- mPriv->QNSOpenSavePanelDelegate_directoryEntered(QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString(mCurrentDir)));
-}
-
-/*
- Returns a list of extensions (e.g. "png", "jpg", "gif")
- for the current name filter. If a filter do not conform
- to the format *.xyz or * or *.*, an empty list
- is returned meaning accept everything.
-*/
-- (QStringList)acceptableExtensionsForSave
-{
- QStringList result;
- for (int i=0; i<mSelectedNameFilter->count(); ++i) {
- const QString &filter = mSelectedNameFilter->at(i);
- if (filter.startsWith(QLatin1String("*."))
- && !filter.contains(QLatin1Char('?'))
- && filter.count(QLatin1Char('*')) == 1) {
- result += filter.mid(2);
- } else {
- return QStringList(); // Accept everything
- }
- }
- return result;
-}
-
-- (QString)removeExtensions:(const QString &)filter
-{
- QRegExp regExp(QT_PREPEND_NAMESPACE(QString::fromLatin1)(QT_PREPEND_NAMESPACE(qt_file_dialog_filter_reg_exp)));
- if (regExp.indexIn(filter) != -1)
- return regExp.cap(1).trimmed();
- return filter;
-}
-
-- (void)createTextField
-{
- NSRect textRect = { { 0.0, 3.0 }, { 100.0, 25.0 } };
- mTextField = [[NSTextField alloc] initWithFrame:textRect];
- [[mTextField cell] setFont:[NSFont systemFontOfSize:
- [NSFont systemFontSizeForControlSize:NSRegularControlSize]]];
- [mTextField setAlignment:NSRightTextAlignment];
- [mTextField setEditable:false];
- [mTextField setSelectable:false];
- [mTextField setBordered:false];
- [mTextField setDrawsBackground:false];
- if (mPriv){
- [mTextField setStringValue:[self strip:mPriv->qFileDialogUi->fileTypeLabel->text()]];
- } else
- [mTextField setStringValue:QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(QT_PREPEND_NAMESPACE(QFileDialog::tr)("Files of type:"))];
-}
-
-- (void)createPopUpButton:(const QString &)selectedFilter hideDetails:(BOOL)hideDetails
-{
- NSRect popUpRect = { { 100.0, 5.0 }, { 250.0, 25.0 } };
- mPopUpButton = [[NSPopUpButton alloc] initWithFrame:popUpRect pullsDown:NO];
- [mPopUpButton setTarget:self];
- [mPopUpButton setAction:@selector(filterChanged:)];
-
- QStringList *filters = mNameFilterDropDownList;
- if (filters->size() > 0){
- for (int i=0; i<mNameFilterDropDownList->size(); ++i) {
- QString filter = hideDetails ? [self removeExtensions:filters->at(i)] : filters->at(i);
- [mPopUpButton addItemWithTitle:QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(filter)];
- if (filters->at(i).startsWith(selectedFilter))
- [mPopUpButton selectItemAtIndex:i];
- }
- }
-}
-
-- (QStringList) findStrippedFilterWithVisualFilterName:(QString)name
-{
- for (int i=0; i<mNameFilterDropDownList->size(); ++i) {
- if (mNameFilterDropDownList->at(i).startsWith(name))
- return qt_clean_filter_list(mNameFilterDropDownList->at(i));
- }
- return QStringList();
-}
-
-- (void)createAccessory
-{
- NSRect accessoryRect = { { 0.0, 0.0 }, { 450.0, 33.0 } };
- mAccessoryView = [[NSView alloc] initWithFrame:accessoryRect];
- [mAccessoryView addSubview:mTextField];
- [mAccessoryView addSubview:mPopUpButton];
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_selectionChanged(const QString &newPath)
-{
- emit q_func()->currentChanged(newPath);
-}
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_panelClosed(bool accepted)
-{
- if (accepted)
- q_func()->accept();
- else
- q_func()->reject();
-}
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_directoryEntered(const QString &newDir)
-{
- setLastVisitedDirectory(newDir);
- emit q_func()->directoryEntered(newDir);
-}
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_filterSelected(int menuIndex)
-{
- emit q_func()->filterSelected(nameFilters.at(menuIndex));
-}
-
-extern OSErr qt_mac_create_fsref(const QString &, FSRef *); // qglobal.cpp
-extern void qt_mac_to_pascal_string(QString s, Str255 str, TextEncoding encoding=0, int len=-1); // qglobal.cpp
-
-void QFileDialogPrivate::setDirectory_sys(const QString &directory)
-{
-#ifndef QT_MAC_USE_COCOA
- if (directory == mCurrentLocation)
- return;
- mCurrentLocation = directory;
- emit q_func()->directoryEntered(mCurrentLocation);
-
- FSRef fsRef;
- if (qt_mac_create_fsref(directory, &fsRef) == noErr) {
- AEDesc desc;
- if (AECreateDesc(typeFSRef, &fsRef, sizeof(FSRef), &desc) == noErr)
- NavCustomControl(mDialog, kNavCtlSetLocation, (void*)&desc);
- }
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- [delegate->mSavePanel setDirectory:qt_mac_QStringToNSString(directory)];
-#endif
-}
-
-QString QFileDialogPrivate::directory_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
- return mCurrentLocation;
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- return qt_mac_NSStringToQString([delegate->mSavePanel directory]);
-#endif
-}
-
-void QFileDialogPrivate::selectFile_sys(const QString &filename)
-{
- QString filePath = filename;
- if (QDir::isRelativePath(filePath))
- filePath = QFileInfo(directory_sys(), filePath).filePath();
-
-#ifndef QT_MAC_USE_COCOA
- // Update the selection list immidiatly, so
- // subsequent calls to selectedFiles() gets correct:
- mCurrentSelectionList.clear();
- mCurrentSelectionList << filename;
- if (mCurrentSelection != filename){
- mCurrentSelection = filename;
- emit q_func()->currentChanged(mCurrentSelection);
- }
-
- AEDescList descList;
- if (AECreateList(0, 0, false, &descList) != noErr)
- return;
-
- FSRef fsRef;
- if (qt_mac_create_fsref(filePath, &fsRef) == noErr) {
- AEDesc desc;
- if (AECreateDesc(typeFSRef, &fsRef, sizeof(FSRef), &desc) == noErr){
- if (AEPutDesc(&descList, 0, &desc) == noErr)
- NavCustomControl(mDialog, kNavCtlSetSelection, (void*)&descList);
- }
- }
-
- // Type the file name into the save dialog's text field:
- UInt8 *strBuffer = (UInt8 *)malloc(1024);
- qt_mac_to_pascal_string(QFileInfo(filename).fileName(), strBuffer);
- NavCustomControl(mDialog, kNavCtlSetEditFileName, strBuffer);
- free(strBuffer);
-#else
- // There seems to no way to select a file once the dialog is running.
- // So do the next best thing, set the file's directory:
- setDirectory_sys(QFileInfo(filePath).absolutePath());
-#endif
-}
-
-QStringList QFileDialogPrivate::selectedFiles_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
- if (q_func()->acceptMode() == QFileDialog::AcceptOpen){
- return mCurrentSelectionList;
- } else {
- return QStringList() << mCurrentLocation + QLatin1Char('/')
- + QCFString::toQString(NavDialogGetSaveFileName(mDialog));
- }
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- return [delegate selectedFiles];
-#endif
-}
-
-void QFileDialogPrivate::setNameFilters_sys(const QStringList &filters)
-{
-#ifndef QT_MAC_USE_COCOA
- Q_UNUSED(filters);
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- bool hideDetails = q_func()->testOption(QFileDialog::HideNameFilterDetails);
- [delegate setNameFilters:filters hideDetails:hideDetails];
-#endif
-}
-
-void QFileDialogPrivate::setFilter_sys()
-{
-#ifndef QT_MAC_USE_COCOA
-#else
- Q_Q(QFileDialog);
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- *(delegate->mQDirFilter) = model->filter();
- delegate->mFileMode = fileMode;
- [delegate->mSavePanel setTitle:qt_mac_QStringToNSString(q->windowTitle())];
- [delegate->mSavePanel setPrompt:[delegate strip:acceptLabel]];
- if (fileNameLabelExplicitlySat)
- [delegate->mSavePanel setNameFieldLabel:[delegate strip:qFileDialogUi->fileNameLabel->text()]];
-
- [delegate updateProperties];
-#endif
-}
-
-void QFileDialogPrivate::selectNameFilter_sys(const QString &filter)
-{
- int index = nameFilters.indexOf(filter);
- if (index != -1) {
-#ifndef QT_MAC_USE_COCOA
- NavMenuItemSpec navSpec;
- bzero(&navSpec, sizeof(NavMenuItemSpec));
- navSpec.menuType = index;
- NavCustomControl(mDialog, kNavCtlSelectCustomType, &navSpec);
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- [delegate->mPopUpButton selectItemAtIndex:index];
- [delegate filterChanged:nil];
-#endif
- }
-}
-
-QString QFileDialogPrivate::selectedNameFilter_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
- int index = filterInfo.currentSelection;
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- int index = [delegate->mPopUpButton indexOfSelectedItem];
-#endif
- return index != -1 ? nameFilters.at(index) : QString();
-}
-
-void QFileDialogPrivate::deleteNativeDialog_sys()
-{
-#ifndef QT_MAC_USE_COCOA
- if (mDialog)
- NavDialogDispose(mDialog);
- mDialog = 0;
- mDialogStarted = false;
-#else
- QMacCocoaAutoReleasePool pool;
- [reinterpret_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate) release];
- mDelegate = 0;
-#endif
- nativeDialogInUse = false;
-}
-
-bool QFileDialogPrivate::setVisible_sys(bool visible)
-{
- Q_Q(QFileDialog);
- if (!visible == q->isHidden())
- return false;
-
- if (q->windowFlags() & Qt::WindowStaysOnTopHint) {
- // The native file dialog tries all it can to stay
- // on the NSModalPanel level. And it might also show
- // its own "create directory" dialog that we cannot control.
- // So we need to use the non-native version in this case...
- return false;
- }
-
-#ifndef QT_MAC_USE_COCOA
- return visible ? showCarbonNavServicesDialog() : hideCarbonNavServicesDialog();
-#else
- return visible ? showCocoaFilePanel() : hideCocoaFilePanel();
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-Boolean QFileDialogPrivate::qt_mac_filedialog_filter_proc(AEDesc *theItem, void *info,
- void *data, NavFilterModes)
-{
- QFileDialogPrivate *fileDialogPrivate = static_cast<QFileDialogPrivate *>(data);
-
- if (!fileDialogPrivate || fileDialogPrivate->filterInfo.filters.isEmpty()
- || (fileDialogPrivate->filterInfo.currentSelection < 0
- && fileDialogPrivate->filterInfo.currentSelection
- >= fileDialogPrivate->filterInfo.filters.size()))
- return true;
-
- NavFileOrFolderInfo *theInfo = static_cast<NavFileOrFolderInfo *>(info);
- QString file;
- QString path;
- const QtMacFilterName &fn
- = fileDialogPrivate->filterInfo.filters.at(fileDialogPrivate->filterInfo.currentSelection);
- if (theItem->descriptorType == typeFSRef) {
- FSRef ref;
- AEGetDescData(theItem, &ref, sizeof(ref));
- UInt8 str_buffer[1024];
- FSRefMakePath(&ref, str_buffer, 1024);
- path = QString::fromUtf8(reinterpret_cast<const char *>(str_buffer));
- int slsh = path.lastIndexOf(QLatin1Char('/'));
- if (slsh != -1)
- file = path.right(path.length() - slsh - 1);
- else
- file = path;
- }
- QStringList reg = fn.regexp.split(QLatin1String(";"));
- for (QStringList::const_iterator it = reg.constBegin(); it != reg.constEnd(); ++it) {
- QRegExp rg(*it, Qt::CaseInsensitive, QRegExp::Wildcard);
-#ifdef DEBUG_FILEDIALOG_FILTERS
- qDebug("QFileDialogPrivate::qt_mac_filedialog_filter_proc:%d, asked to filter.. %s (%s)", __LINE__,
- qPrintable(file), qPrintable(*it));
-#endif
- if (rg.exactMatch(file))
- return true;
- }
-
- if (theInfo->isFolder) {
- if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:qt_mac_QStringToNSString(path)])
- return false;
- return true;
- }
- return false;
-}
-
-void QFileDialogPrivate::qt_mac_filedialog_event_proc(const NavEventCallbackMessage msg,
- NavCBRecPtr p, NavCallBackUserData data)
-{
- QFileDialogPrivate *fileDialogPrivate = static_cast<QFileDialogPrivate *>(data);
-
- switch(msg) {
- case kNavCBPopupMenuSelect: {
- NavMenuItemSpec *s = static_cast<NavMenuItemSpec *>(p->eventData.eventDataParms.param);
- if (int(s->menuType) != fileDialogPrivate->filterInfo.currentSelection) {
- fileDialogPrivate->filterInfo.currentSelection = s->menuType;
- emit fileDialogPrivate->q_func()->filterSelected(fileDialogPrivate->nameFilters.at(s->menuType));
- }
- if (fileDialogPrivate->acceptMode == QFileDialog::AcceptSave) {
- QString base = QCFString::toQString(NavDialogGetSaveFileName(p->context));
- QFileInfo fi(base);
- base = fi.completeBaseName();
- const QtMacFilterName &fn = fileDialogPrivate->filterInfo.filters.at(
- fileDialogPrivate->filterInfo.currentSelection);
- QStringList reg = fn.regexp.split(QLatin1String(";"), QString::SkipEmptyParts);
- if (reg.count()) {
- QString r = reg.first();
- r = r.right(r.length()-1); // Strip the *
- base += r; //"." + QString::number(s->menuType);
- }
- NavDialogSetSaveFileName(p->context, QCFString::toCFStringRef(base));
- }
-#ifdef DEBUG_FILEDIALOG_FILTERS
- qDebug("QFileDialogPrivate::qt_mac_filedialog_event_proc:%d - Selected a filter: %ld", __LINE__, s->menuType);
-#endif
- break; }
- case kNavCBStart:{
- fileDialogPrivate->mDialogStarted = true;
- // Set selected file:
- QModelIndexList indexes = fileDialogPrivate->qFileDialogUi->listView->selectionModel()->selectedRows();
- QString selected;
- if (!indexes.isEmpty())
- selected = indexes.at(0).data(QFileSystemModel::FilePathRole).toString();
- else
- selected = fileDialogPrivate->typedFiles().value(0);
- fileDialogPrivate->selectFile_sys(selected);
- fileDialogPrivate->selectNameFilter_sys(fileDialogPrivate->qFileDialogUi->fileTypeCombo->currentText());
- break; }
- case kNavCBSelectEntry:{
- // Event: Current selection has changed.
- QStringList prevSelectionList = fileDialogPrivate->mCurrentSelectionList;
- fileDialogPrivate->mCurrentSelectionList.clear();
- QString fileNameToEmit;
-
- AEDescList *descList = (AEDescList *)p->eventData.eventDataParms.param;
- // Get the number of files selected:
- UInt8 strBuffer[1024];
- long count;
- OSErr err = AECountItems(descList, &count);
- if (err != noErr || !count)
- break;
-
- for (long index=1; index<=count; ++index) {
- FSRef ref;
- err = AEGetNthPtr(descList, index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
- if (err != noErr)
- break;
- FSRefMakePath(&ref, strBuffer, 1024);
- QString selected = QString::fromUtf8((const char *)strBuffer);
- fileDialogPrivate->mCurrentSelectionList << selected;
- if (!prevSelectionList.contains(selected))
- fileNameToEmit = selected;
- }
-
- if (!fileNameToEmit.isEmpty() && fileNameToEmit != fileDialogPrivate->mCurrentSelection)
- emit fileDialogPrivate->q_func()->currentChanged(fileNameToEmit);
- fileDialogPrivate->mCurrentSelection = fileNameToEmit;
- break; }
- case kNavCBShowDesktop:
- case kNavCBNewLocation:{
- // Event: Current directory has changed.
- AEDesc *desc = (AEDesc *)p->eventData.eventDataParms.param;
- FSRef ref;
- AEGetDescData(desc, &ref, sizeof(ref));
- UInt8 *strBuffer = (UInt8 *)malloc(1024);
- FSRefMakePath(&ref, strBuffer, 1024);
- QString newLocation = QString::fromUtf8((const char *)strBuffer);
- free(strBuffer);
- if (fileDialogPrivate->mCurrentLocation != newLocation){
- fileDialogPrivate->mCurrentLocation = newLocation;
- QFileDialog::FileMode mode = fileDialogPrivate->fileMode;
- if (mode == QFileDialog::AnyFile || mode == QFileDialog::ExistingFile
- || mode == QFileDialog::ExistingFiles){
- // When changing directory, the current selection is cleared if
- // we are supposed to be selecting files only:
- if (!fileDialogPrivate->mCurrentSelection.isEmpty()){
- fileDialogPrivate->mCurrentSelectionList.clear();
- fileDialogPrivate->mCurrentSelection.clear();
- emit fileDialogPrivate->q_func()->currentChanged(fileDialogPrivate->mCurrentSelection);
- }
- }
- fileDialogPrivate->setLastVisitedDirectory(newLocation);
- emit fileDialogPrivate->q_func()->directoryEntered(newLocation);
- }
- break; }
- case kNavCBAccept:
- fileDialogPrivate->mDialogClosed = true;
- fileDialogPrivate->q_func()->accept();
- break;
- case kNavCBCancel:
- fileDialogPrivate->mDialogClosed = true;
- fileDialogPrivate->q_func()->reject();
- break;
- }
-}
-
-static QFileDialogPrivate::QtMacFilterName qt_mac_extract_filter(const QString &rawFilter, bool showDetails)
-{
- QFileDialogPrivate::QtMacFilterName ret;
- ret.filter = rawFilter;
- QString result = rawFilter;
- QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
- int index = r.indexIn(result);
- if (index >= 0)
- result = r.cap(2);
-
- if (showDetails) {
- ret.description = rawFilter;
- } else {
- if (index >= 0)
- ret.description = r.cap(1).trimmed();
- if (ret.description.isEmpty())
- ret.description = result;
- }
- ret.regexp = result.replace(QLatin1Char(' '), QLatin1Char(';'));
- return ret;
-}
-
-static QList<QFileDialogPrivate::QtMacFilterName> qt_mac_make_filters_list(const QString &filter, bool showDetails)
-{
-#ifdef DEBUG_FILEDIALOG_FILTERS
- qDebug("QFileDialog:%d - Got filter (%s)", __LINE__, filter.latin1());
-#endif
-
- QList<QFileDialogPrivate::QtMacFilterName> ret;
- QString f(filter);
- if (f.isEmpty())
- f = QFileDialog::tr("All Files (*)");
- if (f.isEmpty())
- return ret;
- QStringList filts = qt_make_filter_list(f);
- for (QStringList::const_iterator it = filts.constBegin(); it != filts.constEnd(); ++it) {
- QFileDialogPrivate::QtMacFilterName filter = qt_mac_extract_filter(*it, showDetails);
-#ifdef DEBUG_FILEDIALOG_FILTERS
- qDebug("QFileDialog:%d Split out filter (%d) '%s' '%s' [%s]", __LINE__, ret.count(),
- filter->regxp.latin1(), filter->description.latin1(), (*it).latin1());
-#endif
- ret.append(filter);
- }
- return ret;
-}
-
-void QFileDialogPrivate::createNavServicesDialog()
-{
- Q_Q(QFileDialog);
- if (mDialog)
- deleteNativeDialog_sys();
-
- NavDialogCreationOptions navOptions;
- NavGetDefaultDialogCreationOptions(&navOptions);
-
- // Translate QFileDialog settings into NavDialog options:
- if (qt_mac_is_macsheet(q)) {
- navOptions.modality = kWindowModalityWindowModal;
- navOptions.parentWindow = qt_mac_window_for(q->parentWidget());
- } else if (q->windowModality() == Qt::ApplicationModal)
- navOptions.modality = kWindowModalityAppModal;
- else
- navOptions.modality = kWindowModalityNone;
- navOptions.optionFlags |= kNavSupportPackages;
- if (q->testOption(QFileDialog::DontConfirmOverwrite))
- navOptions.optionFlags |= kNavDontConfirmReplacement;
- if (fileMode != QFileDialog::ExistingFiles)
- navOptions.optionFlags &= ~kNavAllowMultipleFiles;
-
- navOptions.windowTitle = QCFString::toCFStringRef(q->windowTitle());
-
- navOptions.location.h = -1;
- navOptions.location.v = -1;
-
- QWidget *parent = q->parentWidget();
- if (parent && parent->isVisible()) {
- WindowClass wclass;
- GetWindowClass(qt_mac_window_for(parent), &wclass);
- parent = parent->window();
- QString s = parent->windowTitle();
- navOptions.clientName = QCFString::toCFStringRef(s);
- }
-
- filterInfo.currentSelection = 0;
- filterInfo.filters = qt_mac_make_filters_list(nameFilters.join(QLatin1String(";;")), q->isNameFilterDetailsVisible());
- QCFType<CFArrayRef> filterArray;
- if (filterInfo.filters.size() > 1) {
- int i = 0;
- CFStringRef *cfstringArray = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef)
- * filterInfo.filters.size()));
- for (i = 0; i < filterInfo.filters.size(); ++i) {
- cfstringArray[i] = QCFString::toCFStringRef(filterInfo.filters.at(i).description);
- }
- filterArray = CFArrayCreate(kCFAllocatorDefault,
- reinterpret_cast<const void **>(cfstringArray), filterInfo.filters.size(),
- &kCFTypeArrayCallBacks);
- navOptions.popupExtension = filterArray;
- free(cfstringArray);
- }
-
- if (q->acceptMode() == QFileDialog::AcceptSave) {
- if (NavCreatePutFileDialog(&navOptions, 'cute', kNavGenericSignature,
- QFileDialogPrivate::qt_mac_filedialog_event_proc, this, &mDialog)) {
- qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
- return;
- }
- } else if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory) {
- if (NavCreateChooseFolderDialog(&navOptions,
- QFileDialogPrivate::qt_mac_filedialog_event_proc, 0, this, &mDialog)) {
- qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
- return;
- }
- } else {
- if (NavCreateGetFileDialog(&navOptions, 0,
- QFileDialogPrivate::qt_mac_filedialog_event_proc, 0,
- QFileDialogPrivate::qt_mac_filedialog_filter_proc, this, &mDialog)) {
- qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
- return;
- }
- }
-
- // Set start-up directory:
- if (mCurrentLocation.isEmpty())
- mCurrentLocation = rootPath();
- FSRef fsRef;
- if (qt_mac_create_fsref(mCurrentLocation, &fsRef) == noErr) {
- AEDesc desc;
- if (AECreateDesc(typeFSRef, &fsRef, sizeof(FSRef), &desc) == noErr)
- NavCustomControl(mDialog, kNavCtlSetLocation, (void*)&desc);
- }
-}
-
-bool QFileDialogPrivate::showCarbonNavServicesDialog()
-{
- Q_Q(QFileDialog);
- if (q->acceptMode() == QFileDialog::AcceptSave && q->windowModality() == Qt::NonModal)
- return false; // cannot do native no-modal save dialogs.
- createNavServicesDialog();
- mDialogClosed = false;
- if (q->windowModality() != Qt::ApplicationModal)
- NavDialogRun(mDialog);
- return true;
-}
-
-bool QFileDialogPrivate::hideCarbonNavServicesDialog()
-{
- if (!mDialogClosed){
- mDialogClosed = true;
- NavCustomControl(mDialog, kNavCtlCancel, 0);
- }
- return true;
-}
-
-#else // Cocoa
-
-void QFileDialogPrivate::createNSOpenSavePanelDelegate()
-{
- Q_Q(QFileDialog);
- if (mDelegate)
- return;
-
- bool selectDir = q->selectedFiles().isEmpty();
- QString selection(selectDir ? q->directory().absolutePath() : q->selectedFiles().value(0));
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = [[QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) alloc]
- initWithAcceptMode:acceptMode
- title:q->windowTitle()
- hideNameFilterDetails:q->testOption(QFileDialog::HideNameFilterDetails)
- qDirFilter:model->filter()
- fileOptions:opts
- fileMode:fileMode
- selectFile:selection
- confirmOverwrite:!q->testOption(QFileDialog::DontConfirmOverwrite)
- priv:this];
-
- mDelegate = delegate;
-}
-
-bool QFileDialogPrivate::showCocoaFilePanel()
-{
- Q_Q(QFileDialog);
- QMacCocoaAutoReleasePool pool;
- createNSOpenSavePanelDelegate();
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- if (qt_mac_is_macsheet(q))
- [delegate showWindowModalSheet:q->parentWidget()];
- else
- [delegate showModelessPanel];
- return true;
-}
-
-bool QFileDialogPrivate::hideCocoaFilePanel()
-{
- if (!mDelegate){
- // Nothing to do. We return false to leave the question
- // open regarding whether or not to go native:
- return false;
- } else {
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- [delegate closePanel];
- // Even when we hide it, we are still using a
- // native dialog, so return true:
- return true;
- }
-}
-
-#endif
-
-void QFileDialogPrivate::mac_nativeDialogModalHelp()
-{
- // Do a queued meta-call to open the native modal dialog so it opens after the new
- // event loop has started to execute (in QDialog::exec). Using a timer rather than
- // a queued meta call is intentional to ensure that the call is only delivered when
- // [NSApp run] runs (timers are handeled special in cocoa). If NSApp is not
- // running (which is the case if e.g a top-most QEventLoop has been
- // interrupted, and the second-most event loop has not yet been reactivated (regardless
- // if [NSApp run] is still on the stack)), showing a native modal dialog will fail.
- if (nativeDialogInUse){
- Q_Q(QFileDialog);
- QTimer::singleShot(1, q, SLOT(_q_macRunNativeAppModalPanel()));
- }
-}
-
-void QFileDialogPrivate::_q_macRunNativeAppModalPanel()
-{
- QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active);
-#ifndef QT_MAC_USE_COCOA
- NavDialogRun(mDialog);
-#else
- Q_Q(QFileDialog);
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- [delegate runApplicationModalPanel];
- dialogResultCode_sys() == QDialog::Accepted ? q->accept() : q->reject();
-#endif
-}
-
-QDialog::DialogCode QFileDialogPrivate::dialogResultCode_sys()
-{
-#ifndef QT_MAC_USE_COCOA
- NavUserAction result = NavDialogGetUserAction(mDialog);
- if (result == kNavUserActionCancel || result == kNavUserActionNone)
- return QDialog::Rejected;
- else
- return QDialog::Accepted;
-#else
- QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
- return [delegate dialogResultCode];
-#endif
-}
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_FILEDIALOG
-
diff --git a/src/gui/dialogs/qfiledialog_p.h b/src/gui/dialogs/qfiledialog_p.h
deleted file mode 100644
index 882acdd758..0000000000
--- a/src/gui/dialogs/qfiledialog_p.h
+++ /dev/null
@@ -1,427 +0,0 @@
-/****************************************************************************
-**
-** 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 QFILEDIALOG_P_H
-#define QFILEDIALOG_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QT_NO_FILEDIALOG
-
-#include "qfiledialog.h"
-#include "private/qdialog_p.h"
-#include "qplatformdefs.h"
-
-#include "qfilesystemmodel_p.h"
-#include <qlistview.h>
-#include <qtreeview.h>
-#include <qcombobox.h>
-#include <qtoolbutton.h>
-#include <qlabel.h>
-#include <qevent.h>
-#include <qlineedit.h>
-#include <qurl.h>
-#include <qstackedwidget.h>
-#include <qdialogbuttonbox.h>
-#include <qabstractproxymodel.h>
-#include <qcompleter.h>
-#include <qpointer.h>
-#include <qdebug.h>
-#include "qsidebar_p.h"
-#include "qfscompleter_p.h"
-#include "private/qguiplatformplugin_p.h"
-
-
-#if defined (Q_OS_UNIX)
-#include <unistd.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QFileDialogListView;
-class QFileDialogTreeView;
-class QFileDialogLineEdit;
-class QGridLayout;
-class QCompleter;
-class QHBoxLayout;
-class Ui_QFileDialog;
-
-
-struct QFileDialogArgs
-{
- QFileDialogArgs() : parent(0), mode(QFileDialog::AnyFile) {}
-
- QWidget *parent;
- QString caption;
- QString directory;
- QString selection;
- QString filter;
- QFileDialog::FileMode mode;
- QFileDialog::Options options;
-};
-
-#define UrlRole (Qt::UserRole + 1)
-
-class Q_AUTOTEST_EXPORT QFileDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QFileDialog)
-
-public:
- QFileDialogPrivate();
-
- void createToolButtons();
- void createMenuActions();
- void createWidgets();
-
- void init(const QString &directory = QString(), const QString &nameFilter = QString(),
- const QString &caption = QString());
- bool itemViewKeyboardEvent(QKeyEvent *event);
- QString getEnvironmentVariable(const QString &string);
- static QString workingDirectory(const QString &path);
- static QString initialSelection(const QString &path);
- QStringList typedFiles() const;
- QStringList addDefaultSuffixToFiles(const QStringList filesToFix) const;
- bool removeDirectory(const QString &path);
-
- inline QModelIndex mapToSource(const QModelIndex &index) const;
- inline QModelIndex mapFromSource(const QModelIndex &index) const;
- inline QModelIndex rootIndex() const;
- inline void setRootIndex(const QModelIndex &index) const;
- inline QModelIndex select(const QModelIndex &index) const;
- inline QString rootPath() const;
-
- QLineEdit *lineEdit() const;
-
- int maxNameLength(const QString &path) {
-#if defined(Q_OS_UNIX)
- return ::pathconf(QFile::encodeName(path).data(), _PC_NAME_MAX);
-#elif defined(Q_OS_WIN)
-#ifndef Q_OS_WINCE
- DWORD maxLength;
- QString drive = path.left(3);
- if (::GetVolumeInformation(reinterpret_cast<const wchar_t *>(drive.utf16()), NULL, 0, NULL, &maxLength, NULL, NULL, 0) == FALSE)
- return -1;
- return maxLength;
-#else
- Q_UNUSED(path);
- return MAX_PATH;
-#endif //Q_OS_WINCE
-#else
- Q_UNUSED(path);
-#endif
- return -1;
- }
-
- QString basename(const QString &path) const
- {
- int separator = QDir::toNativeSeparators(path).lastIndexOf(QDir::separator());
- if (separator != -1)
- return path.mid(separator + 1);
- return path;
- }
-
- QDir::Filters filterForMode(QDir::Filters filters) const
- {
- if (fileMode == QFileDialog::DirectoryOnly) {
- filters |= QDir::Drives | QDir::AllDirs | QDir::Dirs;
- filters &= ~QDir::Files;
- } else {
- filters |= QDir::Drives | QDir::AllDirs | QDir::Files | QDir::Dirs;
- }
- return filters;
- }
-
- QAbstractItemView *currentView() const;
-
- static inline QString toInternal(const QString &path)
- {
-#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) || defined(Q_OS_SYMBIAN)
- QString n(path);
- for (int i = 0; i < (int)n.length(); ++i)
- if (n[i] == QLatin1Char('\\')) n[i] = QLatin1Char('/');
-#if defined(Q_OS_WINCE)
- if ((n.size() > 1) && (n.startsWith(QLatin1String("//"))))
- n = n.mid(1);
-#endif
- return n;
-#else // the compile should optimize away this
- return path;
-#endif
- }
-
- void setLastVisitedDirectory(const QString &dir);
- void retranslateWindowTitle();
- void retranslateStrings();
- void emitFilesSelected(const QStringList &files);
-
- void _q_goHome();
- void _q_pathChanged(const QString &);
- void _q_navigateBackward();
- void _q_navigateForward();
- void _q_navigateToParent();
- void _q_createDirectory();
- void _q_showListView();
- void _q_showDetailsView();
- void _q_showContextMenu(const QPoint &position);
- void _q_renameCurrent();
- void _q_deleteCurrent();
- void _q_showHidden();
- void _q_showHeader(QAction *);
- void _q_updateOkButton();
- void _q_currentChanged(const QModelIndex &index);
- void _q_enterDirectory(const QModelIndex &index);
- void _q_goToDirectory(const QString &);
- void _q_useNameFilter(int index);
- void _q_selectionChanged();
- void _q_goToUrl(const QUrl &url);
- void _q_autoCompleteFileName(const QString &);
- void _q_rowsInserted(const QModelIndex & parent);
- void _q_fileRenamed(const QString &path, const QString oldName, const QString newName);
-
- // layout
-#ifndef QT_NO_PROXYMODEL
- QAbstractProxyModel *proxyModel;
-#endif
-
- // data
- QStringList watching;
- QFileSystemModel *model;
-
-#ifndef QT_NO_FSCOMPLETER
- QFSCompleter *completer;
-#endif //QT_NO_FSCOMPLETER
-
- QFileDialog::FileMode fileMode;
- QFileDialog::AcceptMode acceptMode;
- bool confirmOverwrite;
- QString defaultSuffix;
- QString setWindowTitle;
-
- QStringList currentHistory;
- int currentHistoryLocation;
-
- QAction *renameAction;
- QAction *deleteAction;
- QAction *showHiddenAction;
- QAction *newFolderAction;
-
- bool useDefaultCaption;
- bool defaultFileTypes;
- bool fileNameLabelExplicitlySat;
- QStringList nameFilters;
-
- // Members for using native dialogs:
- bool nativeDialogInUse;
- // setVisible_sys returns true if it ends up showing a native
- // dialog. Returning false means that a non-native dialog must be
- // used instead.
- bool canBeNativeDialog();
- bool setVisible_sys(bool visible);
- void deleteNativeDialog_sys();
- QDialog::DialogCode dialogResultCode_sys();
-
- void setDirectory_sys(const QString &directory);
- QString directory_sys() const;
- void selectFile_sys(const QString &filename);
- QStringList selectedFiles_sys() const;
- void setFilter_sys();
- void setNameFilters_sys(const QStringList &filters);
- void selectNameFilter_sys(const QString &filter);
- QString selectedNameFilter_sys() const;
- //////////////////////////////////////////////
-
-#if defined(Q_WS_MAC)
- void *mDelegate;
-#ifndef QT_MAC_USE_COCOA
- NavDialogRef mDialog;
- bool mDialogStarted;
- bool mDialogClosed;
- QString mCurrentLocation;
- QString mCurrentSelection;
- QStringList mCurrentSelectionList;
-
- struct QtMacFilterName {
- QString description;
- QString regexp;
- QString filter;
- };
- struct QtMacNavFilterInfo {
- QtMacNavFilterInfo() : currentSelection(-1) {}
- int currentSelection;
- QList<QtMacFilterName> filters;
- } filterInfo;
-
- static void qt_mac_filedialog_event_proc(const NavEventCallbackMessage msg, NavCBRecPtr p,
- NavCallBackUserData data);
- static Boolean qt_mac_filedialog_filter_proc(AEDesc *theItem, void *info, void *data,
- NavFilterModes);
- bool showCarbonNavServicesDialog();
- bool hideCarbonNavServicesDialog();
- void createNavServicesDialog();
-#else
- bool showCocoaFilePanel();
- bool hideCocoaFilePanel();
-#endif
- void createNSOpenSavePanelDelegate();
- void QNSOpenSavePanelDelegate_selectionChanged(const QString &newPath);
- void QNSOpenSavePanelDelegate_panelClosed(bool accepted);
- void QNSOpenSavePanelDelegate_directoryEntered(const QString &newDir);
- void QNSOpenSavePanelDelegate_filterSelected(int menuIndex);
- void _q_macRunNativeAppModalPanel();
- void mac_nativeDialogModalHelp();
-#endif
-
- QScopedPointer<Ui_QFileDialog> qFileDialogUi;
-
- QString acceptLabel;
-
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
- QByteArray signalToDisconnectOnClose;
-
- QFileDialog::Options opts;
-
- ~QFileDialogPrivate();
-
-private:
- Q_DISABLE_COPY(QFileDialogPrivate)
-};
-
-class QFileDialogLineEdit : public QLineEdit
-{
-public:
- QFileDialogLineEdit(QWidget *parent = 0) : QLineEdit(parent), hideOnEsc(false), d_ptr(0){}
- void init(QFileDialogPrivate *d_pointer) {d_ptr = d_pointer; }
- void keyPressEvent(QKeyEvent *e);
- bool hideOnEsc;
-private:
- QFileDialogPrivate *d_ptr;
-};
-
-class QFileDialogComboBox : public QComboBox
-{
-public:
- QFileDialogComboBox(QWidget *parent = 0) : QComboBox(parent), urlModel(0) {}
- void init(QFileDialogPrivate *d_pointer);
- void showPopup();
- void setHistory(const QStringList &paths);
- QStringList history() const { return m_history; }
- void paintEvent(QPaintEvent *);
-
-private:
- QUrlModel *urlModel;
- QFileDialogPrivate *d_ptr;
- QStringList m_history;
-};
-
-class QFileDialogListView : public QListView
-{
-public:
- QFileDialogListView(QWidget *parent = 0);
- void init(QFileDialogPrivate *d_pointer);
- QSize sizeHint() const;
-protected:
- void keyPressEvent(QKeyEvent *e);
-private:
- QFileDialogPrivate *d_ptr;
-};
-
-class QFileDialogTreeView : public QTreeView
-{
-public:
- QFileDialogTreeView(QWidget *parent);
- void init(QFileDialogPrivate *d_pointer);
- QSize sizeHint() const;
-
-protected:
- void keyPressEvent(QKeyEvent *e);
-private:
- QFileDialogPrivate *d_ptr;
-};
-
-inline QModelIndex QFileDialogPrivate::mapToSource(const QModelIndex &index) const {
-#ifdef QT_NO_PROXYMODEL
- return index;
-#else
- return proxyModel ? proxyModel->mapToSource(index) : index;
-#endif
-}
-inline QModelIndex QFileDialogPrivate::mapFromSource(const QModelIndex &index) const {
-#ifdef QT_NO_PROXYMODEL
- return index;
-#else
- return proxyModel ? proxyModel->mapFromSource(index) : index;
-#endif
-}
-
-inline QString QFileDialogPrivate::rootPath() const {
- return model->rootPath();
-}
-
-#ifndef Q_WS_MAC
- // Dummies for platforms that don't use native dialogs:
- inline void QFileDialogPrivate::deleteNativeDialog_sys() { qt_guiPlatformPlugin()->fileDialogDelete(q_func()); }
- inline bool QFileDialogPrivate::setVisible_sys(bool visible) { return qt_guiPlatformPlugin()->fileDialogSetVisible(q_func(), visible); }
- inline QDialog::DialogCode QFileDialogPrivate::dialogResultCode_sys(){ return qt_guiPlatformPlugin()->fileDialogResultCode(q_func()); }
- inline void QFileDialogPrivate::setDirectory_sys(const QString &directory) { qt_guiPlatformPlugin()->fileDialogSetDirectory(q_func(), directory); }
- inline QString QFileDialogPrivate::directory_sys() const { return qt_guiPlatformPlugin()->fileDialogDirectory(q_func()); }
- inline void QFileDialogPrivate::selectFile_sys(const QString &filename) { qt_guiPlatformPlugin()->fileDialogSelectFile(q_func(), filename); }
- inline QStringList QFileDialogPrivate::selectedFiles_sys() const { return qt_guiPlatformPlugin()->fileDialogSelectedFiles(q_func()); }
- inline void QFileDialogPrivate::setFilter_sys() { qt_guiPlatformPlugin()->fileDialogSetFilter(q_func()); }
- inline void QFileDialogPrivate::setNameFilters_sys(const QStringList &filters) { qt_guiPlatformPlugin()->fileDialogSetNameFilters(q_func(), filters); }
- inline void QFileDialogPrivate::selectNameFilter_sys(const QString &filter) { qt_guiPlatformPlugin()->fileDialogSelectNameFilter(q_func(), filter); }
- inline QString QFileDialogPrivate::selectedNameFilter_sys() const { return qt_guiPlatformPlugin()->fileDialogSelectedNameFilter(q_func()); }
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_FILEDIALOG
-
-#endif // QFILEDIALOG_P_H
diff --git a/src/gui/dialogs/qfiledialog_symbian.cpp b/src/gui/dialogs/qfiledialog_symbian.cpp
deleted file mode 100644
index ed9895019f..0000000000
--- a/src/gui/dialogs/qfiledialog_symbian.cpp
+++ /dev/null
@@ -1,199 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfiledialog.h"
-
-#ifndef QT_NO_FILEDIALOG
-
-#include <private/qfiledialog_p.h>
-#if defined(Q_WS_S60) && defined(SYMBIAN_VERSION_SYMBIAN3)
-#include <driveinfo.h>
-#include <AknCommonDialogsDynMem.h>
-#include <CAknMemorySelectionDialogMultiDrive.h>
-#include <MAknFileFilter.h>
-#endif
-#include "private/qcore_symbian_p.h"
-
-QT_BEGIN_NAMESPACE
-
-extern QStringList qt_make_filter_list(const QString &filter); // defined in qfiledialog.cpp
-extern QStringList qt_clean_filter_list(const QString &filter); // defined in qfiledialog.cpp
-
-enum DialogMode { DialogOpen, DialogSave, DialogFolder };
-#if defined(Q_WS_S60) && defined(SYMBIAN_VERSION_SYMBIAN3)
-class CExtensionFilter : public MAknFileFilter
-{
-public:
- void setFilter(const QString filter)
- {
- QStringList unparsedFiltersList = qt_make_filter_list(filter);
- QStringList filterList;
- filterRxList.clear();
-
- foreach (QString unparsedFilter, unparsedFiltersList) {
- filterList << qt_clean_filter_list(unparsedFilter);
- }
- foreach (QString currentFilter, filterList) {
- QRegExp filterRx(currentFilter, Qt::CaseInsensitive, QRegExp::Wildcard);
- filterRxList << filterRx;
- }
- }
-
- TBool Accept(const TDesC &/*aDriveAndPath*/, const TEntry &aEntry) const
- {
- //If no filter for files, all can be accepted
- if (filterRxList.isEmpty())
- return ETrue;
-
- if (aEntry.IsDir())
- return ETrue;
-
- foreach (QRegExp rx, filterRxList) {
- QString fileName = qt_TDesC2QString(aEntry.iName);
- if (rx.exactMatch(fileName))
- return ETrue;
- }
-
- return EFalse;
- }
-
-private:
- QList<QRegExp> filterRxList;
-};
-#endif
-
-static QString launchSymbianDialog(const QString dialogCaption, const QString startDirectory,
- const QString filter, DialogMode dialogMode)
-{
- QString selection;
-#if defined(Q_WS_S60) && defined(SYMBIAN_VERSION_SYMBIAN3)
- TFileName startFolder;
- if (!startDirectory.isEmpty()) {
- QString dir = QDir::toNativeSeparators(QFileDialogPrivate::workingDirectory(startDirectory));
- startFolder = qt_QString2TPtrC(dir);
- }
- TInt types = AknCommonDialogsDynMem::EMemoryTypeMMCExternal|
- AknCommonDialogsDynMem::EMemoryTypeInternalMassStorage|
- AknCommonDialogsDynMem::EMemoryTypePhone;
-
- TPtrC titlePtr(qt_QString2TPtrC(dialogCaption));
- TFileName target;
- bool select = false;
- int tryCount = 2;
- while (tryCount--) {
- TInt err(KErrNone);
- TRAP(err,
- if (dialogMode == DialogOpen) {
- CExtensionFilter* extensionFilter = new (ELeave) CExtensionFilter;
- CleanupStack::PushL(extensionFilter);
- extensionFilter->setFilter(filter);
- select = AknCommonDialogsDynMem::RunSelectDlgLD(types, target,
- startFolder, 0, 0, titlePtr, extensionFilter);
- CleanupStack::Pop(extensionFilter);
- } else if (dialogMode == DialogSave) {
- QString defaultFileName = QFileDialogPrivate::initialSelection(startDirectory);
- target = qt_QString2TPtrC(defaultFileName);
- select = AknCommonDialogsDynMem::RunSaveDlgLD(types, target,
- startFolder, 0, 0, titlePtr);
- } else if (dialogMode == DialogFolder) {
- select = AknCommonDialogsDynMem::RunFolderSelectDlgLD(types, target, startFolder,
- 0, 0, titlePtr, NULL, NULL);
- }
- );
-
- if (err == KErrNone) {
- tryCount = 0;
- } else {
- // Symbian native file dialog doesn't allow accessing files outside C:/Data
- // It will always leave in that case, so default into QDir::rootPath() in error cases.
- QString dir = QDir::toNativeSeparators(QDir::rootPath());
- startFolder = qt_QString2TPtrC(dir);
- }
- }
- if (select) {
- QFileInfo fi(qt_TDesC2QString(target));
- selection = fi.absoluteFilePath();
- }
-#endif
- return selection;
-}
-
-QString qtSymbianGetOpenFileName(const QString &caption,
- const QString &dir,
- const QString &filter)
-{
- return launchSymbianDialog(caption, dir, filter, DialogOpen);
-}
-
-QStringList qtSymbianGetOpenFileNames(const QString &caption,
- const QString &dir,
- const QString &filter)
-{
- QString fileName;
- fileName.append(launchSymbianDialog(caption, dir, filter, DialogOpen));
- QStringList fileList;
- fileList << fileName;
-
- return fileList;
-}
-
-QString qtSymbianGetSaveFileName(const QString &caption,
- const QString &dir)
-{
- return launchSymbianDialog(caption, dir, QString(), DialogSave);
-}
-
-QString qtSymbianGetExistingDirectory(const QString &caption,
- const QString &dir)
-{
- QString folderCaption;
- if (!caption.isEmpty()) {
- folderCaption.append(caption);
- } else {
- // Title for folder selection dialog is mandatory
- folderCaption.append(QFileDialog::tr("Find Directory"));
- }
- return launchSymbianDialog(folderCaption, dir, QString(), DialogFolder);
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp
deleted file mode 100644
index 114f4bedbc..0000000000
--- a/src/gui/dialogs/qfiledialog_win.cpp
+++ /dev/null
@@ -1,825 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfiledialog.h"
-
-#ifndef QT_NO_FILEDIALOG
-
-#include <private/qfiledialog_p.h>
-#include <qapplication.h>
-#include <private/qapplication_p.h>
-#include <qt_windows.h>
-#include <qglobal.h>
-#include <qregexp.h>
-#include <qbuffer.h>
-#include <qdir.h>
-#include <qstringlist.h>
-#include <private/qsystemlibrary_p.h>
-#include "qfiledialog_win_p.h"
-
-#ifndef QT_NO_THREAD
-# include <private/qmutexpool_p.h>
-#endif
-
-#ifdef Q_WS_WINCE
-#include <commdlg.h>
-bool qt_priv_ptr_valid = false;
-#else
-//we have to declare them here because they're not present for all SDK/compilers
-static const IID QT_IID_IFileOpenDialog = {0xd57c7288, 0xd4ad, 0x4768, {0xbe, 0x02, 0x9d, 0x96, 0x95, 0x32, 0xd9, 0x60} };
-static const IID QT_IID_IShellItem = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe} };
-static const CLSID QT_CLSID_FileOpenDialog = {0xdc1c5a9c, 0xe88a, 0x4dde, {0xa5, 0xa1, 0x60, 0xf8, 0x2a, 0x20, 0xae, 0xf7} };
-#endif
-
-
-typedef qt_LPITEMIDLIST (WINAPI *PtrSHBrowseForFolder)(qt_BROWSEINFO*);
-static PtrSHBrowseForFolder ptrSHBrowseForFolder = 0;
-typedef BOOL (WINAPI *PtrSHGetPathFromIDList)(qt_LPITEMIDLIST, LPWSTR);
-static PtrSHGetPathFromIDList ptrSHGetPathFromIDList = 0;
-typedef HRESULT (WINAPI *PtrSHGetMalloc)(LPMALLOC *);
-static PtrSHGetMalloc ptrSHGetMalloc = 0;
-
-
-QT_BEGIN_NAMESPACE
-
-static void qt_win_resolve_libs()
-{
- static bool triedResolve = false;
-
- if (!triedResolve) {
-#ifndef QT_NO_THREAD
- // protect initialization
- QMutexLocker locker(QMutexPool::globalInstanceGet(&triedResolve));
- // check triedResolve again, since another thread may have already
- // done the initialization
- if (triedResolve) {
- // another thread did initialize the security function pointers,
- // so we shouldn't do it again.
- return;
- }
-#endif
-
- triedResolve = true;
-#if !defined(Q_WS_WINCE)
- QSystemLibrary lib(L"shell32");
- ptrSHBrowseForFolder = (PtrSHBrowseForFolder)lib.resolve("SHBrowseForFolderW");
- ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)lib.resolve("SHGetPathFromIDListW");
- ptrSHGetMalloc = (PtrSHGetMalloc)lib.resolve("SHGetMalloc");
-#else
- // CE stores them in a different lib and does not use unicode version
- HINSTANCE handle = LoadLibrary(L"Ceshell");
- ptrSHBrowseForFolder = (PtrSHBrowseForFolder)GetProcAddress(handle, L"SHBrowseForFolder");
- ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)GetProcAddress(handle, L"SHGetPathFromIDList");
- ptrSHGetMalloc = (PtrSHGetMalloc)GetProcAddress(handle, L"SHGetMalloc");
- if (ptrSHBrowseForFolder && ptrSHGetPathFromIDList && ptrSHGetMalloc)
- qt_priv_ptr_valid = true;
-#endif
- }
-}
-
-extern const char* qt_file_dialog_filter_reg_exp; // defined in qfiledialog.cpp
-extern QStringList qt_make_filter_list(const QString &filter);
-
-const int maxNameLen = 1023;
-const int maxMultiLen = 65535;
-
-// Returns the wildcard part of a filter.
-static QString qt_win_extract_filter(const QString &rawFilter)
-{
- QString result = rawFilter;
- QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
- int index = r.indexIn(result);
- if (index >= 0)
- result = r.cap(2);
- QStringList list = result.split(QLatin1Char(' '));
- for(QStringList::iterator it = list.begin(); it < list.end(); ++it) {
- if (*it == QLatin1String("*")) {
- *it = QLatin1String("*.*");
- break;
- }
- }
- return list.join(QLatin1String(";"));
-}
-
-static QStringList qt_win_make_filters_list(const QString &filter)
-{
- QString f(filter);
-
- if (f.isEmpty())
- f = QFileDialog::tr("All Files (*.*)");
-
- return qt_make_filter_list(f);
-}
-
-// Makes a NUL-oriented Windows filter from a Qt filter.
-static QString qt_win_filter(const QString &filter, bool hideFiltersDetails)
-{
- QStringList filterLst = qt_win_make_filters_list(filter);
- QStringList::Iterator it = filterLst.begin();
- QString winfilters;
- QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
- for (; it != filterLst.end(); ++it) {
- QString subfilter = *it;
- if (!subfilter.isEmpty()) {
- if (hideFiltersDetails) {
- int index = r.indexIn(subfilter);
- if (index >= 0)
- winfilters += r.cap(1);
- } else {
- winfilters += subfilter;
- }
- winfilters += QChar();
- winfilters += qt_win_extract_filter(subfilter);
- winfilters += QChar();
- }
- }
- winfilters += QChar();
- return winfilters;
-}
-
-static QString qt_win_selected_filter(const QString &filter, DWORD idx)
-{
- return qt_win_make_filters_list(filter).at((int)idx - 1);
-}
-
-static QString tFilters, tTitle, tInitDir;
-
-static OPENFILENAME* qt_win_make_OFN(QWidget *parent,
- const QString& initialSelection,
- const QString& initialDirectory,
- const QString& title,
- const QString& filters,
- QFileDialog::FileMode mode,
- QFileDialog::Options options)
-{
- if (parent)
- parent = parent->window();
- else
- parent = QApplication::activeWindow();
-
- tInitDir = QDir::toNativeSeparators(initialDirectory);
- tFilters = filters;
- tTitle = title;
- QString initSel = QDir::toNativeSeparators(initialSelection);
- if (!initSel.isEmpty()) {
- initSel.remove(QLatin1Char('<'));
- initSel.remove(QLatin1Char('>'));
- initSel.remove(QLatin1Char('\"'));
- initSel.remove(QLatin1Char('|'));
- }
-
- int maxLen = mode == QFileDialog::ExistingFiles ? maxMultiLen : maxNameLen;
- wchar_t *tInitSel = new wchar_t[maxLen + 1];
- if (initSel.length() > 0 && initSel.length() <= maxLen)
- memcpy(tInitSel, initSel.utf16(), (initSel.length()+1)*sizeof(QChar));
- else
- tInitSel[0] = 0;
-
- OPENFILENAME* ofn = new OPENFILENAME;
- memset(ofn, 0, sizeof(OPENFILENAME));
-
- ofn->lStructSize = sizeof(OPENFILENAME);
- ofn->hwndOwner = parent ? parent->winId() : 0;
- ofn->lpstrFilter = (wchar_t*)tFilters.utf16();
- ofn->lpstrFile = tInitSel;
- ofn->nMaxFile = maxLen;
- ofn->lpstrInitialDir = (wchar_t*)tInitDir.utf16();
- ofn->lpstrTitle = (wchar_t*)tTitle.utf16();
- ofn->Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_EXPLORER | OFN_PATHMUSTEXIST);
- if (mode == QFileDialog::ExistingFile ||
- mode == QFileDialog::ExistingFiles)
- ofn->Flags |= (OFN_FILEMUSTEXIST);
- if (mode == QFileDialog::ExistingFiles)
- ofn->Flags |= (OFN_ALLOWMULTISELECT);
- if (!(options & QFileDialog::DontConfirmOverwrite))
- ofn->Flags |= OFN_OVERWRITEPROMPT;
-
- return ofn;
-}
-
-static void qt_win_clean_up_OFN(OPENFILENAME **ofn)
-{
- delete [] (*ofn)->lpstrFile;
- delete *ofn;
- *ofn = 0;
-}
-
-extern void qt_win_eatMouseMove();
-
-QString qt_win_get_open_file_name(const QFileDialogArgs &args,
- QString *initialDirectory,
- QString *selectedFilter)
-{
- QString result;
-
- QString isel = args.selection;
-
- if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
- initialDirectory->remove(0, 5);
- QFileInfo fi(*initialDirectory);
-
- if (initialDirectory && !fi.isDir()) {
- *initialDirectory = fi.absolutePath();
- if (isel.isEmpty())
- isel = fi.fileName();
- }
-
- if (!fi.exists())
- *initialDirectory = QDir::homePath();
-
- DWORD selFilIdx = 0;
-
- int idx = 0;
- if (selectedFilter) {
- QStringList filterLst = qt_win_make_filters_list(args.filter);
- idx = filterLst.indexOf(*selectedFilter);
- }
-
- QDialog modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(args.parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
- OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
- args.directory, args.caption,
- qt_win_filter(args.filter, hideFiltersDetails),
- QFileDialog::ExistingFile,
- args.options);
- if (idx)
- ofn->nFilterIndex = idx + 1;
- if (GetOpenFileName(ofn)) {
- result = QString::fromWCharArray(ofn->lpstrFile);
- selFilIdx = ofn->nFilterIndex;
- }
- qt_win_clean_up_OFN(&ofn);
-
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- if (result.isEmpty())
- return result;
-
- fi = result;
- *initialDirectory = fi.path();
- if (selectedFilter)
- *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
- return fi.absoluteFilePath();
-}
-
-QString qt_win_get_save_file_name(const QFileDialogArgs &args,
- QString *initialDirectory,
- QString *selectedFilter)
-{
- QString result;
-
- QString isel = args.selection;
- if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
- initialDirectory->remove(0, 5);
- QFileInfo fi(*initialDirectory);
-
- if (initialDirectory && !fi.isDir()) {
- *initialDirectory = fi.absolutePath();
- if (isel.isEmpty())
- isel = fi.fileName();
- }
-
- if (!fi.exists())
- *initialDirectory = QDir::homePath();
-
- DWORD selFilIdx = 0;
-
- int idx = 0;
- if (selectedFilter) {
- QStringList filterLst = qt_win_make_filters_list(args.filter);
- idx = filterLst.indexOf(*selectedFilter);
- }
-
- QDialog modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(args.parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
- bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
- // This block is used below for the lpstrDefExt member.
- // Note that the current MSDN docs document this member wrong.
- // It should rather be documented as "the default extension if no extension was given and if the
- // current filter does not have a extension (e.g (*)). If the current filter have an extension, use
- // the extension of the current filter"
- QString defaultSaveExt;
- if (selectedFilter && !selectedFilter->isEmpty()) {
- defaultSaveExt = qt_win_extract_filter(*selectedFilter);
- // make sure we only have the extension
- int firstDot = defaultSaveExt.indexOf(QLatin1Char('.'));
- if (firstDot != -1) {
- defaultSaveExt.remove(0, firstDot + 1);
- } else {
- defaultSaveExt.clear();
- }
- }
-
- OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection,
- args.directory, args.caption,
- qt_win_filter(args.filter, hideFiltersDetails),
- QFileDialog::AnyFile,
- args.options);
-
- ofn->lpstrDefExt = (wchar_t*)defaultSaveExt.utf16();
-
- if (idx)
- ofn->nFilterIndex = idx + 1;
- if (GetSaveFileName(ofn)) {
- result = QString::fromWCharArray(ofn->lpstrFile);
- selFilIdx = ofn->nFilterIndex;
- }
- qt_win_clean_up_OFN(&ofn);
-
-#if defined(Q_WS_WINCE)
- int semIndex = result.indexOf(QLatin1Char(';'));
- if (semIndex >= 0)
- result = result.left(semIndex);
-#endif
-
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- if (result.isEmpty())
- return result;
-
- fi = result;
- *initialDirectory = fi.path();
- if (selectedFilter)
- *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
- return fi.absoluteFilePath();
-}
-
-
-#ifndef Q_WS_WINCE
-
-typedef HRESULT (WINAPI *PtrSHCreateItemFromParsingName)(PCWSTR pszPath, IBindCtx *pbc, REFIID riid, void **ppv);
-static PtrSHCreateItemFromParsingName pSHCreateItemFromParsingName = 0;
-
-static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd,
- const QString& initialSelection,
- const QString& initialDirectory,
- const QString& title,
- const QStringList& filterLst,
- QFileDialog::FileMode mode,
- QFileDialog::Options options)
-{
- if (!pSHCreateItemFromParsingName) {
- // This function is available only in Vista & above.
- QSystemLibrary shellLib(QLatin1String("Shell32"));
- pSHCreateItemFromParsingName = (PtrSHCreateItemFromParsingName)
- shellLib.resolve("SHCreateItemFromParsingName");
- if (!pSHCreateItemFromParsingName)
- return false;
- }
- HRESULT hr;
- QString winfilters;
- int numFilters = 0;
- quint32 currentOffset = 0;
- QList<quint32> offsets;
- QStringList::ConstIterator it = filterLst.begin();
- // Create the native filter string and save offset to each entry.
- for (; it != filterLst.end(); ++it) {
- QString subfilter = *it;
- if (!subfilter.isEmpty()) {
- offsets<<currentOffset;
- //Here the COMMON_ITEM_DIALOG API always add the details for the filter (e.g. *.txt)
- //so we don't need to handle the flag HideNameFilterDetails.
- winfilters += subfilter; // The name of the filter.
- winfilters += QChar();
- currentOffset += subfilter.size()+1;
- offsets<<currentOffset;
- QString spec = qt_win_extract_filter(subfilter);
- winfilters += spec; // The actual filter spec.
- winfilters += QChar();
- currentOffset += spec.size()+1;
- numFilters++;
- }
- }
- // Add the filters to the file dialog.
- if (numFilters) {
- wchar_t *szData = (wchar_t*)winfilters.utf16();
- qt_COMDLG_FILTERSPEC *filterSpec = new qt_COMDLG_FILTERSPEC[numFilters];
- for(int i = 0; i<numFilters; i++) {
- filterSpec[i].pszName = szData+offsets[i*2];
- filterSpec[i].pszSpec = szData+offsets[(i*2)+1];
- }
- hr = pfd->SetFileTypes(numFilters, filterSpec);
- delete []filterSpec;
- }
- // Set the starting folder.
- tInitDir = QDir::toNativeSeparators(initialDirectory);
- if (!tInitDir.isEmpty()) {
- IShellItem *psiDefaultFolder;
- hr = pSHCreateItemFromParsingName((wchar_t*)tInitDir.utf16(), NULL, QT_IID_IShellItem,
- reinterpret_cast<void**>(&psiDefaultFolder));
-
- if (SUCCEEDED(hr)) {
- hr = pfd->SetFolder(psiDefaultFolder);
- psiDefaultFolder->Release();
- }
- }
- // Set the currently selected file.
- QString initSel = QDir::toNativeSeparators(initialSelection);
- if (!initSel.isEmpty()) {
- initSel.remove(QLatin1Char('<'));
- initSel.remove(QLatin1Char('>'));
- initSel.remove(QLatin1Char('\"'));
- initSel.remove(QLatin1Char('|'));
- }
- if (!initSel.isEmpty()) {
- hr = pfd->SetFileName((wchar_t*)initSel.utf16());
- }
- // Set the title for the file dialog.
- if (!title.isEmpty()) {
- hr = pfd->SetTitle((wchar_t*)title.utf16());
- }
- // Set other flags for the dialog.
- DWORD newOptions;
- hr = pfd->GetOptions(&newOptions);
- if (SUCCEEDED(hr)) {
- newOptions |= FOS_NOCHANGEDIR;
- if (mode == QFileDialog::ExistingFile ||
- mode == QFileDialog::ExistingFiles)
- newOptions |= (FOS_FILEMUSTEXIST | FOS_PATHMUSTEXIST);
- if (mode == QFileDialog::ExistingFiles)
- newOptions |= FOS_ALLOWMULTISELECT;
- if (!(options & QFileDialog::DontConfirmOverwrite))
- newOptions |= FOS_OVERWRITEPROMPT;
- hr = pfd->SetOptions(newOptions);
- }
- return SUCCEEDED(hr);
-}
-
-static QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
- QString *initialDirectory,
- const QStringList &filterList,
- QString *selectedFilter,
- int selectedFilterIndex)
-{
- QStringList result;
- QDialog modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(args.parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
- // Multiple selection is allowed only in IFileOpenDialog.
- IFileOpenDialog *pfd = 0;
- HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, QT_IID_IFileOpenDialog,
- reinterpret_cast<void**>(&pfd));
-
- if (SUCCEEDED(hr)) {
- qt_win_set_IFileDialogOptions(pfd, args.selection,
- args.directory, args.caption,
- filterList, QFileDialog::ExistingFiles,
- args.options);
- // Set the currently selected filter (one-based index).
- hr = pfd->SetFileTypeIndex(selectedFilterIndex+1);
- QWidget *parentWindow = args.parent;
- if (parentWindow)
- parentWindow = parentWindow->window();
- else
- parentWindow = QApplication::activeWindow();
- // Show the file dialog.
- hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
- if (SUCCEEDED(hr)) {
- // Retrieve the results.
- IShellItemArray *psiaResults;
- hr = pfd->GetResults(&psiaResults);
- if (SUCCEEDED(hr)) {
- DWORD numItems = 0;
- psiaResults->GetCount(&numItems);
- for (DWORD i = 0; i<numItems; i++) {
- IShellItem *psi = 0;
- hr = psiaResults->GetItemAt(i, &psi);
- if (SUCCEEDED(hr)) {
- // Retrieve the file name from shell item.
- wchar_t *pszPath;
- hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
- if (SUCCEEDED(hr)) {
- QString fileName = QString::fromWCharArray(pszPath);
- result.append(fileName);
- CoTaskMemFree(pszPath);
- }
- psi->Release(); // Free the current item.
- }
- }
- psiaResults->Release(); // Free the array of items.
- }
- }
- }
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- if (!result.isEmpty()) {
- // Retrieve the current folder name.
- IShellItem *psi = 0;
- hr = pfd->GetFolder(&psi);
- if (SUCCEEDED(hr)) {
- wchar_t *pszPath;
- hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
- if (SUCCEEDED(hr)) {
- *initialDirectory = QString::fromWCharArray(pszPath);
- CoTaskMemFree(pszPath);
- }
- psi->Release();
- }
- // Retrieve the currently selected filter.
- if (selectedFilter) {
- quint32 filetype = 0;
- hr = pfd->GetFileTypeIndex(&filetype);
- if (SUCCEEDED(hr) && filetype && filetype <= (quint32)filterList.length()) {
- // This is a one-based index, not zero-based.
- *selectedFilter = filterList[filetype-1];
- }
- }
- }
- if (pfd)
- pfd->Release();
- return result;
-}
-
-QString qt_win_CID_get_existing_directory(const QFileDialogArgs &args)
-{
- QString result;
- QDialog modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(args.parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- IFileOpenDialog *pfd = 0;
- HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
- QT_IID_IFileOpenDialog, reinterpret_cast<void**>(&pfd));
-
- if (SUCCEEDED(hr)) {
- qt_win_set_IFileDialogOptions(pfd, args.selection,
- args.directory, args.caption,
- QStringList(), QFileDialog::ExistingFiles,
- args.options);
-
- // Set the FOS_PICKFOLDERS flag
- DWORD newOptions;
- hr = pfd->GetOptions(&newOptions);
- newOptions |= (FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
- if (SUCCEEDED(hr) && SUCCEEDED((hr = pfd->SetOptions(newOptions)))) {
- QWidget *parentWindow = args.parent;
- if (parentWindow)
- parentWindow = parentWindow->window();
- else
- parentWindow = QApplication::activeWindow();
-
- // Show the file dialog.
- hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
- if (SUCCEEDED(hr)) {
- // Retrieve the result
- IShellItem *psi = 0;
- hr = pfd->GetResult(&psi);
- if (SUCCEEDED(hr)) {
- // Retrieve the file name from shell item.
- wchar_t *pszPath;
- hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
- if (SUCCEEDED(hr)) {
- result = QString::fromWCharArray(pszPath);
- CoTaskMemFree(pszPath);
- }
- psi->Release(); // Free the current item.
- }
- }
- }
- }
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- if (pfd)
- pfd->Release();
- return result;
-}
-
-#endif
-
-QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
- QString *initialDirectory,
- QString *selectedFilter)
-{
- QFileInfo fi;
- QDir dir;
-
- if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
- initialDirectory->remove(0, 5);
- fi = QFileInfo(*initialDirectory);
-
- if (initialDirectory && !fi.isDir()) {
- *initialDirectory = fi.absolutePath();
- }
-
- if (!fi.exists())
- *initialDirectory = QDir::homePath();
-
- DWORD selFilIdx = 0;
-
- QStringList filterLst = qt_win_make_filters_list(args.filter);
- int idx = 0;
- if (selectedFilter) {
- idx = filterLst.indexOf(*selectedFilter);
- }
- // Windows Vista (& above) allows users to search from file dialogs. If user selects
- // multiple files belonging to different folders from these search results, the
- // GetOpenFileName() will return only one folder name for all the files. To retrieve
- // the correct path for all selected files, we have to use Common Item Dialog interfaces.
-#ifndef Q_WS_WINCE
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
- return qt_win_CID_get_open_file_names(args, initialDirectory, filterLst, selectedFilter, idx);
-#endif
-
- QStringList result;
- QDialog modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(args.parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
- OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
- args.directory, args.caption,
- qt_win_filter(args.filter, hideFiltersDetails),
- QFileDialog::ExistingFiles,
- args.options);
- if (idx)
- ofn->nFilterIndex = idx + 1;
- if (GetOpenFileName(ofn)) {
- QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile);
- selFilIdx = ofn->nFilterIndex;
- int offset = fileOrDir.length() + 1;
- if (ofn->lpstrFile[offset] == 0) {
- // Only one file selected; has full path
- fi.setFile(fileOrDir);
- QString res = fi.absoluteFilePath();
- if (!res.isEmpty())
- result.append(res);
- }
- else {
- // Several files selected; first string is path
- dir.setPath(fileOrDir);
- QString f;
- while(!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) {
- fi.setFile(dir, f);
- QString res = fi.absoluteFilePath();
- if (!res.isEmpty())
- result.append(res);
- offset += f.length() + 1;
- }
- }
- }
- qt_win_clean_up_OFN(&ofn);
-
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- if (!result.isEmpty()) {
- *initialDirectory = fi.path(); // only save the path if there is a result
- if (selectedFilter)
- *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
- }
- return result;
-}
-
-// MFC Directory Dialog. Contrib: Steve Williams (minor parts from Scott Powers)
-
-static int __stdcall winGetExistDirCallbackProc(HWND hwnd,
- UINT uMsg,
- LPARAM lParam,
- LPARAM lpData)
-{
- if (uMsg == BFFM_INITIALIZED && lpData != 0) {
- QString *initDir = (QString *)(lpData);
- if (!initDir->isEmpty()) {
- SendMessage(hwnd, BFFM_SETSELECTION, TRUE, LPARAM(initDir->utf16()));
- }
- } else if (uMsg == BFFM_SELCHANGED) {
- qt_win_resolve_libs();
- if (ptrSHGetPathFromIDList) {
- wchar_t path[MAX_PATH];
- ptrSHGetPathFromIDList(qt_LPITEMIDLIST(lParam), path);
- QString tmpStr = QString::fromWCharArray(path);
- if (!tmpStr.isEmpty())
- SendMessage(hwnd, BFFM_ENABLEOK, 1, 1);
- else
- SendMessage(hwnd, BFFM_ENABLEOK, 0, 0);
- SendMessage(hwnd, BFFM_SETSTATUSTEXT, 1, LPARAM(path));
- }
- }
- return 0;
-}
-
-QString qt_win_get_existing_directory(const QFileDialogArgs &args)
-{
-#ifndef Q_WS_WINCE
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
- return qt_win_CID_get_existing_directory(args);
-#endif
-
- QString currentDir = QDir::currentPath();
- QString result;
- QWidget *parent = args.parent;
- if (parent)
- parent = parent->window();
- else
- parent = QApplication::activeWindow();
- if (parent)
- parent->createWinId();
-
- QDialog modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- QString initDir = QDir::toNativeSeparators(args.directory);
- wchar_t path[MAX_PATH];
- wchar_t initPath[MAX_PATH];
- initPath[0] = 0;
- path[0] = 0;
- tTitle = args.caption;
-
- qt_BROWSEINFO bi;
-
- Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
- bi.hwndOwner = (parent ? parent->winId() : 0);
- bi.pidlRoot = NULL;
- //### This does not seem to be respected? - the dialog always displays "Browse for folder"
- bi.lpszTitle = (wchar_t*)tTitle.utf16();
- bi.pszDisplayName = initPath;
- bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
- bi.lpfn = winGetExistDirCallbackProc;
- bi.lParam = LPARAM(&initDir);
-
- qt_win_resolve_libs();
- if (ptrSHBrowseForFolder) {
- qt_LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder(&bi);
- if (pItemIDList) {
- ptrSHGetPathFromIDList(pItemIDList, path);
- IMalloc *pMalloc;
- if (ptrSHGetMalloc(&pMalloc) == NOERROR) {
- pMalloc->Free(pItemIDList);
- pMalloc->Release();
- result = QString::fromWCharArray(path);
- }
- }
- }
- tTitle = QString();
-
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- if (!result.isEmpty())
- result.replace(QLatin1Char('\\'), QLatin1Char('/'));
- return result;
-}
-
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qfiledialog_win_p.h b/src/gui/dialogs/qfiledialog_win_p.h
deleted file mode 100644
index 7580f0ad6b..0000000000
--- a/src/gui/dialogs/qfiledialog_win_p.h
+++ /dev/null
@@ -1,243 +0,0 @@
-/****************************************************************************
-**
-** 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 <objbase.h>
-#ifndef QFILEDIAG_WIN_P_H
-#define QFILEDIAG_WIN_P_H
-
-//these are the interface declarations needed for the file dialog on Vista and up
-
-//At some point we can hope that all compilers/sdk will support that interface
-//and we won't have to declare it ourselves
-
-//declarations
-#define FOS_OVERWRITEPROMPT 0x2
-#define FOS_STRICTFILETYPES 0x4
-#define FOS_NOCHANGEDIR 0x8
-#define FOS_PICKFOLDERS 0x20
-#define FOS_FORCEFILESYSTEM 0x40
-#define FOS_ALLNONSTORAGEITEMS 0x80
-#define FOS_NOVALIDATE 0x100
-#define FOS_ALLOWMULTISELECT 0x200
-#define FOS_PATHMUSTEXIST 0x800
-#define FOS_FILEMUSTEXIST 0x1000
-#define FOS_CREATEPROMPT 0x2000
-#define FOS_SHAREAWARE 0x4000
-#define FOS_NOREADONLYRETURN 0x8000
-#define FOS_NOTESTFILECREATE 0x10000
-#define FOS_HIDEMRUPLACES 0x20000
-#define FOS_HIDEPINNEDPLACES 0x40000
-#define FOS_NODEREFERENCELINKS 0x100000
-#define FOS_DONTADDTORECENT 0x2000000
-#define FOS_FORCESHOWHIDDEN 0x10000000
-#define FOS_DEFAULTNOMINIMODE 0x20000000
-#define FOS_FORCEPREVIEWPANEON 0x40000000
-
-typedef int GETPROPERTYSTOREFLAGS;
-#define GPS_DEFAULT 0x00000000
-#define GPS_HANDLERPROPERTIESONLY 0x00000001
-#define GPS_READWRITE 0x00000002
-#define GPS_TEMPORARY 0x00000004
-#define GPS_FASTPROPERTIESONLY 0x00000008
-#define GPS_OPENSLOWITEM 0x00000010
-#define GPS_DELAYCREATION 0x00000020
-#define GPS_BESTEFFORT 0x00000040
-#define GPS_MASK_VALID 0x0000007F
-
-typedef int (QT_WIN_CALLBACK* BFFCALLBACK)(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData);
-// message from browser
-#define BFFM_INITIALIZED 1
-#define BFFM_SELCHANGED 2
-#define BFFM_ENABLEOK (WM_USER + 101)
-#define BFFM_SETSELECTION (WM_USER + 103)
-#define BFFM_SETSTATUSTEXT (WM_USER + 104)
-
-// Browsing for directory.
-#define BIF_RETURNONLYFSDIRS 0x0001
-#define BIF_DONTGOBELOWDOMAIN 0x0002
-#define BIF_STATUSTEXT 0x0004
-#define BIF_RETURNFSANCESTORS 0x0008
-#define BIF_EDITBOX 0x0010
-#define BIF_VALIDATE 0x0020
-#define BIF_NEWDIALOGSTYLE 0x0040
-#define BIF_BROWSEINCLUDEURLS 0x0080
-#define BIF_UAHINT 0x0100
-#define BIF_NONEWFOLDERBUTTON 0x0200
-#define BIF_NOTRANSLATETARGETS 0x0400
-#define BIF_BROWSEFORCOMPUTER 0x1000
-#define BIF_BROWSEFORPRINTER 0x2000
-#define BIF_BROWSEINCLUDEFILES 0x4000
-#define BIF_SHAREABLE 0x8000
-
-//the enums
-typedef enum {
- SIATTRIBFLAGS_AND = 0x1,
- SIATTRIBFLAGS_OR = 0x2,
- SIATTRIBFLAGS_APPCOMPAT = 0x3,
- SIATTRIBFLAGS_MASK = 0x3
-} SIATTRIBFLAGS;
-typedef enum {
- SIGDN_NORMALDISPLAY = 0x00000000,
- SIGDN_PARENTRELATIVEPARSING = 0x80018001,
- SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
- SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
- SIGDN_PARENTRELATIVEEDITING = 0x80031001,
- SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
- SIGDN_FILESYSPATH = 0x80058000,
- SIGDN_URL = 0x80068000
-} SIGDN;
-typedef enum {
- FDAP_BOTTOM = 0x00000000,
- FDAP_TOP = 0x00000001
-} FDAP;
-typedef enum {
- FDESVR_DEFAULT = 0x00000000,
- FDESVR_ACCEPT = 0x00000001,
- FDESVR_REFUSE = 0x00000002
-} FDE_SHAREVIOLATION_RESPONSE;
-typedef FDE_SHAREVIOLATION_RESPONSE FDE_OVERWRITE_RESPONSE;
-
-//the structs
-typedef struct {
- LPCWSTR pszName;
- LPCWSTR pszSpec;
-} qt_COMDLG_FILTERSPEC;
-typedef struct {
- GUID fmtid;
- DWORD pid;
-} qt_PROPERTYKEY;
-
-typedef struct {
- USHORT cb;
- BYTE abID[1];
-} qt_SHITEMID, *qt_LPSHITEMID;
-typedef struct {
- qt_SHITEMID mkid;
-} qt_ITEMIDLIST, *qt_LPITEMIDLIST;
-typedef const qt_ITEMIDLIST *qt_LPCITEMIDLIST;
-typedef struct {
- HWND hwndOwner;
- qt_LPCITEMIDLIST pidlRoot;
- LPWSTR pszDisplayName;
- LPCWSTR lpszTitle;
- UINT ulFlags;
- BFFCALLBACK lpfn;
- LPARAM lParam;
- int iImage;
-} qt_BROWSEINFO;
-
-DECLARE_INTERFACE(IFileDialogEvents);
-DECLARE_INTERFACE_(IShellItem, IUnknown)
-{
- STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID bhid, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetParent)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(GetDisplayName)(THIS_ SIGDN sigdnName, LPWSTR *ppszName) PURE;
- STDMETHOD(GetAttributes)(THIS_ ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
- STDMETHOD(Compare)(THIS_ IShellItem *psi, DWORD hint, int *piOrder) PURE;
-};
-DECLARE_INTERFACE_(IShellItemFilter, IUnknown)
-{
- STDMETHOD(IncludeItem)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(GetEnumFlagsForItem)(THIS_ IShellItem *psi, DWORD *pgrfFlags) PURE;
-};
-DECLARE_INTERFACE_(IEnumShellItems, IUnknown)
-{
- STDMETHOD(Next)(THIS_ ULONG celt, IShellItem **rgelt, ULONG *pceltFetched) PURE;
- STDMETHOD(Skip)(THIS_ ULONG celt) PURE;
- STDMETHOD(Reset)(THIS_) PURE;
- STDMETHOD(Clone)(THIS_ IEnumShellItems **ppenum) PURE;
-};
-DECLARE_INTERFACE_(IShellItemArray, IUnknown)
-{
- STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID rbhid, REFIID riid, void **ppvOut) PURE;
- STDMETHOD(GetPropertyStore)(THIS_ GETPROPERTYSTOREFLAGS flags, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetPropertyDescriptionList)(THIS_ const qt_PROPERTYKEY *keyType, REFIID riid, void **ppv) PURE;
- STDMETHOD(GetAttributes)(THIS_ SIATTRIBFLAGS dwAttribFlags, ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
- STDMETHOD(GetCount)(THIS_ DWORD *pdwNumItems) PURE;
- STDMETHOD(GetItemAt)(THIS_ DWORD dwIndex, IShellItem **ppsi) PURE;
- STDMETHOD(EnumItems)(THIS_ IEnumShellItems **ppenumShellItems) PURE;
-};
-DECLARE_INTERFACE_(IModalWindow, IUnknown)
-{
- STDMETHOD(Show)(THIS_ HWND hwndParent) PURE;
-};
-DECLARE_INTERFACE_(IFileDialog, IModalWindow)
-{
- STDMETHOD(SetFileTypes)(THIS_ UINT cFileTypes, const qt_COMDLG_FILTERSPEC *rgFilterSpec) PURE;
- STDMETHOD(SetFileTypeIndex)(THIS_ UINT iFileType) PURE;
- STDMETHOD(GetFileTypeIndex)(THIS_ UINT *piFileType) PURE;
- STDMETHOD(Advise)(THIS_ IFileDialogEvents *pfde, DWORD *pdwCookie) PURE;
- STDMETHOD(Unadvise)(THIS_ DWORD dwCookie) PURE;
- STDMETHOD(SetOptions)(THIS_ DWORD fos) PURE;
- STDMETHOD(GetOptions)(THIS_ DWORD *pfos) PURE;
- STDMETHOD(SetDefaultFolder)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(SetFolder)(THIS_ IShellItem *psi) PURE;
- STDMETHOD(GetFolder)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(GetCurrentSelection)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(SetFileName)(THIS_ LPCWSTR pszName) PURE;
- STDMETHOD(GetFileName)(THIS_ LPWSTR *pszName) PURE;
- STDMETHOD(SetTitle)(THIS_ LPCWSTR pszTitle) PURE;
- STDMETHOD(SetOkButtonLabel)(THIS_ LPCWSTR pszText) PURE;
- STDMETHOD(SetFileNameLabel)(THIS_ LPCWSTR pszLabel) PURE;
- STDMETHOD(GetResult)(THIS_ IShellItem **ppsi) PURE;
- STDMETHOD(AddPlace)(THIS_ IShellItem *psi, FDAP fdap) PURE;
- STDMETHOD(SetDefaultExtension)(THIS_ LPCWSTR pszDefaultExtension) PURE;
- STDMETHOD(Close)(THIS_ HRESULT hr) PURE;
- STDMETHOD(SetClientGuid)(THIS_ REFGUID guid) PURE;
- STDMETHOD(ClearClientData)(THIS_) PURE;
- STDMETHOD(SetFilter)(THIS_ IShellItemFilter *pFilter) PURE;
-};
-DECLARE_INTERFACE_(IFileDialogEvents, IUnknown)
-{
- STDMETHOD(OnFileOk)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnFolderChanging)(THIS_ IFileDialog *pfd, IShellItem *psiFolder) PURE;
- STDMETHOD(OnFolderChange)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnSelectionChange)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnShareViolation)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_SHAREVIOLATION_RESPONSE *pResponse) PURE;
- STDMETHOD(OnTypeChange)(THIS_ IFileDialog *pfd) PURE;
- STDMETHOD(OnOverwrite)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_OVERWRITE_RESPONSE *pResponse) PURE;
-};
-DECLARE_INTERFACE_(IFileOpenDialog, IFileDialog)
-{
- STDMETHOD(GetResults)(THIS_ IShellItemArray **ppenum) PURE;
- STDMETHOD(GetSelectedItems)(THIS_ IShellItemArray **ppsai) PURE;
-};
-#endif \ No newline at end of file
diff --git a/src/gui/dialogs/qfileinfogatherer.cpp b/src/gui/dialogs/qfileinfogatherer.cpp
deleted file mode 100644
index b36b21e63d..0000000000
--- a/src/gui/dialogs/qfileinfogatherer.cpp
+++ /dev/null
@@ -1,355 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfileinfogatherer_p.h"
-#include <qdebug.h>
-#include <qfsfileengine.h>
-#include <qdiriterator.h>
-#ifndef Q_OS_WIN
-# include <unistd.h>
-# include <sys/types.h>
-#endif
-#if defined(Q_OS_VXWORKS)
-# include "qplatformdefs.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_FILESYSTEMMODEL
-
-#ifdef QT_BUILD_INTERNAL
-static bool fetchedRoot = false;
-Q_AUTOTEST_EXPORT void qt_test_resetFetchedRoot()
-{
- fetchedRoot = false;
-}
-
-Q_AUTOTEST_EXPORT bool qt_test_isFetchedRoot()
-{
- return fetchedRoot;
-}
-#endif
-
-/*!
- Creates thread
-*/
-QFileInfoGatherer::QFileInfoGatherer(QObject *parent)
- : QThread(parent), abort(false),
-#ifndef QT_NO_FILESYSTEMWATCHER
- watcher(0),
-#endif
- m_resolveSymlinks(false), m_iconProvider(&defaultProvider)
-{
-#ifdef Q_OS_WIN
- m_resolveSymlinks = true;
-#elif !defined(Q_OS_INTEGRITY)
- userId = getuid();
- groupId = getgid();
-#endif
-#ifndef QT_NO_FILESYSTEMWATCHER
- watcher = new QFileSystemWatcher(this);
- connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(list(QString)));
- connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(updateFile(QString)));
-#endif
- start(LowPriority);
-}
-
-/*!
- Destroys thread
-*/
-QFileInfoGatherer::~QFileInfoGatherer()
-{
- QMutexLocker locker(&mutex);
- abort = true;
- condition.wakeOne();
- locker.unlock();
- wait();
-}
-
-void QFileInfoGatherer::setResolveSymlinks(bool enable)
-{
- Q_UNUSED(enable);
-#ifdef Q_OS_WIN
- QMutexLocker locker(&mutex);
- m_resolveSymlinks = enable;
-#endif
-}
-
-bool QFileInfoGatherer::resolveSymlinks() const
-{
- return m_resolveSymlinks;
-}
-
-void QFileInfoGatherer::setIconProvider(QFileIconProvider *provider)
-{
- QMutexLocker locker(&mutex);
- m_iconProvider = provider;
-}
-
-QFileIconProvider *QFileInfoGatherer::iconProvider() const
-{
- return m_iconProvider;
-}
-
-/*!
- Fetch extended information for all \a files in \a path
-
- \sa updateFile(), update(), resolvedName()
-*/
-void QFileInfoGatherer::fetchExtendedInformation(const QString &path, const QStringList &files)
-{
- QMutexLocker locker(&mutex);
- // See if we already have this dir/file in our que
- int loc = this->path.lastIndexOf(path);
- while (loc > 0) {
- if (this->files.at(loc) == files) {
- return;
- }
- loc = this->path.lastIndexOf(path, loc - 1);
- }
- this->path.push(path);
- this->files.push(files);
- condition.wakeAll();
-}
-
-/*!
- Fetch extended information for all \a filePath
-
- \sa fetchExtendedInformation()
-*/
-void QFileInfoGatherer::updateFile(const QString &filePath)
-{
- QString dir = filePath.mid(0, filePath.lastIndexOf(QDir::separator()));
- QString fileName = filePath.mid(dir.length() + 1);
- fetchExtendedInformation(dir, QStringList(fileName));
-}
-
-/*
- List all files in \a directoryPath
-
- \sa listed()
-*/
-void QFileInfoGatherer::clear()
-{
-#ifndef QT_NO_FILESYSTEMWATCHER
- QMutexLocker locker(&mutex);
- watcher->removePaths(watcher->files());
- watcher->removePaths(watcher->directories());
-#endif
-}
-
-/*
- Remove a \a path from the watcher
-
- \sa listed()
-*/
-void QFileInfoGatherer::removePath(const QString &path)
-{
-#ifndef QT_NO_FILESYSTEMWATCHER
- QMutexLocker locker(&mutex);
- watcher->removePath(path);
-#endif
-}
-
-/*
- List all files in \a directoryPath
-
- \sa listed()
-*/
-void QFileInfoGatherer::list(const QString &directoryPath)
-{
- fetchExtendedInformation(directoryPath, QStringList());
-}
-
-/*
- Until aborted wait to fetch a directory or files
-*/
-void QFileInfoGatherer::run()
-{
- forever {
- bool updateFiles = false;
- QMutexLocker locker(&mutex);
- if (abort) {
- return;
- }
- if (this->path.isEmpty())
- condition.wait(&mutex);
- QString path;
- QStringList list;
- if (!this->path.isEmpty()) {
- path = this->path.first();
- list = this->files.first();
- this->path.pop_front();
- this->files.pop_front();
- updateFiles = true;
- }
- locker.unlock();
- if (updateFiles)
- getFileInfos(path, list);
- }
-}
-
-QExtendedInformation QFileInfoGatherer::getInfo(const QFileInfo &fileInfo) const
-{
- QExtendedInformation info(fileInfo);
- info.icon = m_iconProvider->icon(fileInfo);
- info.displayType = m_iconProvider->type(fileInfo);
-#ifndef QT_NO_FILESYSTEMWATCHER
- // ### Not ready to listen all modifications
- #if 0
- // Enable the next two commented out lines to get updates when the file sizes change...
- if (!fileInfo.exists() && !fileInfo.isSymLink()) {
- info.size = -1;
- //watcher->removePath(fileInfo.absoluteFilePath());
- } else {
- if (!fileInfo.absoluteFilePath().isEmpty() && fileInfo.exists() && fileInfo.isReadable()
- && !watcher->files().contains(fileInfo.absoluteFilePath())) {
- //watcher->addPath(fileInfo.absoluteFilePath());
- }
- }
- #endif
-#endif
-
- if (fileInfo.isSymLink() && m_resolveSymlinks) {
- QFileInfo resolvedInfo(fileInfo.symLinkTarget());
- resolvedInfo = resolvedInfo.canonicalFilePath();
- if (resolvedInfo.exists()) {
- emit nameResolved(fileInfo.filePath(), resolvedInfo.fileName());
- }
- }
- return info;
-}
-
-QString QFileInfoGatherer::translateDriveName(const QFileInfo &drive) const
-{
- QString driveName = drive.absoluteFilePath();
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (driveName.startsWith(QLatin1Char('/'))) // UNC host
- return drive.fileName();
-#endif
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- if (driveName.endsWith(QLatin1Char('/')))
- driveName.chop(1);
-#endif
- return driveName;
-}
-
-/*
- Get specific file info's, batch the files so update when we have 100
- items and every 200ms after that
- */
-void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &files)
-{
-#ifndef QT_NO_FILESYSTEMWATCHER
- if (files.isEmpty()
- && !watcher->directories().contains(path)
- && !path.isEmpty()
- && !path.startsWith(QLatin1String("//")) /*don't watch UNC path*/) {
- watcher->addPath(path);
- }
-#endif
-
- // List drives
- if (path.isEmpty()) {
-#ifdef QT_BUILD_INTERNAL
- fetchedRoot = true;
-#endif
- QFileInfoList infoList;
- if (files.isEmpty()) {
- infoList = QDir::drives();
- } else {
- for (int i = 0; i < files.count(); ++i)
- infoList << QFileInfo(files.at(i));
- }
- for (int i = infoList.count() - 1; i >= 0; --i) {
- QString driveName = translateDriveName(infoList.at(i));
- QList<QPair<QString,QFileInfo> > updatedFiles;
- updatedFiles.append(QPair<QString,QFileInfo>(driveName, infoList.at(i)));
- emit updates(path, updatedFiles);
- }
- return;
- }
-
- QElapsedTimer base;
- base.start();
- QFileInfo fileInfo;
- bool firstTime = true;
- QList<QPair<QString, QFileInfo> > updatedFiles;
- QStringList filesToCheck = files;
-
- QString itPath = QDir::fromNativeSeparators(files.isEmpty() ? path : QLatin1String(""));
- QDirIterator dirIt(itPath, QDir::AllEntries | QDir::System | QDir::Hidden);
- QStringList allFiles;
- while(!abort && dirIt.hasNext()) {
- dirIt.next();
- fileInfo = dirIt.fileInfo();
- allFiles.append(fileInfo.fileName());
- fetch(fileInfo, base, firstTime, updatedFiles, path);
- }
- if (!allFiles.isEmpty())
- emit newListOfFiles(path, allFiles);
-
- QStringList::const_iterator filesIt = filesToCheck.constBegin();
- while(!abort && filesIt != filesToCheck.constEnd()) {
- fileInfo.setFile(path + QDir::separator() + *filesIt);
- ++filesIt;
- fetch(fileInfo, base, firstTime, updatedFiles, path);
- }
- if (!updatedFiles.isEmpty())
- emit updates(path, updatedFiles);
- emit directoryLoaded(path);
-}
-
-void QFileInfoGatherer::fetch(const QFileInfo &fileInfo, QElapsedTimer &base, bool &firstTime, QList<QPair<QString, QFileInfo> > &updatedFiles, const QString &path) {
- updatedFiles.append(QPair<QString, QFileInfo>(fileInfo.fileName(), fileInfo));
- QElapsedTimer current;
- current.start();
- if ((firstTime && updatedFiles.count() > 100) || base.msecsTo(current) > 1000) {
- emit updates(path, updatedFiles);
- updatedFiles.clear();
- base = current;
- firstTime = false;
- }
-}
-
-#endif // QT_NO_FILESYSTEMMODEL
-
-QT_END_NAMESPACE
diff --git a/src/gui/dialogs/qfileinfogatherer_p.h b/src/gui/dialogs/qfileinfogatherer_p.h
deleted file mode 100644
index db308ef57e..0000000000
--- a/src/gui/dialogs/qfileinfogatherer_p.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/****************************************************************************
-**
-** 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 QFILEINFOGATHERER_H
-#define QFILEINFOGATHERER_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qthread.h>
-#include <qmutex.h>
-#include <qwaitcondition.h>
-#include <qfilesystemwatcher.h>
-#include <qfileiconprovider.h>
-#include <qfsfileengine.h>
-#include <qpair.h>
-#include <qstack.h>
-#include <qdatetime.h>
-#include <qdir.h>
-#include <qelapsedtimer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QExtendedInformation {
-public:
- enum Type { Dir, File, System };
-
- QExtendedInformation() {}
- QExtendedInformation(const QFileInfo &info) : mFileInfo(info) {}
-
- inline bool isDir() { return type() == Dir; }
- inline bool isFile() { return type() == File; }
- inline bool isSystem() { return type() == System; }
-
- bool operator ==(const QExtendedInformation &fileInfo) const {
- return mFileInfo == fileInfo.mFileInfo
- && displayType == fileInfo.displayType
- && permissions() == fileInfo.permissions();
- }
-
-#ifndef QT_NO_FSFILEENGINE
- bool isCaseSensitive() const {
- QFSFileEngine fe(mFileInfo.absoluteFilePath());
- return fe.caseSensitive();
- }
-#endif
-
- QFile::Permissions permissions() const {
- return mFileInfo.permissions();
- }
-
- Type type() const {
- if (mFileInfo.isDir()) {
- return QExtendedInformation::Dir;
- }
- if (mFileInfo.isFile()) {
- return QExtendedInformation::File;
- }
- if (!mFileInfo.exists() && mFileInfo.isSymLink()) {
- return QExtendedInformation::System;
- }
- return QExtendedInformation::System;
- }
-
- bool isSymLink() const {
- return mFileInfo.isSymLink();
- }
-
- bool isHidden() const {
- return mFileInfo.isHidden();
- }
-
- QFileInfo fileInfo() const {
- return mFileInfo;
- }
-
- QDateTime lastModified() const {
- return mFileInfo.lastModified();
- }
-
- qint64 size() const {
- qint64 size = -1;
- if (type() == QExtendedInformation::Dir)
- size = 0;
- if (type() == QExtendedInformation::File)
- size = mFileInfo.size();
- if (!mFileInfo.exists() && !mFileInfo.isSymLink())
- size = -1;
- return size;
- }
-
- QString displayType;
- QIcon icon;
-
-private :
- QFileInfo mFileInfo;
-};
-
-class QFileIconProvider;
-
-#ifndef QT_NO_FILESYSTEMMODEL
-
-class Q_AUTOTEST_EXPORT QFileInfoGatherer : public QThread
-{
-Q_OBJECT
-
-Q_SIGNALS:
- void updates(const QString &directory, const QList<QPair<QString, QFileInfo> > &updates);
- void newListOfFiles(const QString &directory, const QStringList &listOfFiles) const;
- void nameResolved(const QString &fileName, const QString &resolvedName) const;
- void directoryLoaded(const QString &path);
-
-public:
- QFileInfoGatherer(QObject *parent = 0);
- ~QFileInfoGatherer();
-
- void clear();
- void removePath(const QString &path);
- QExtendedInformation getInfo(const QFileInfo &info) const;
-
-public Q_SLOTS:
- void list(const QString &directoryPath);
- void fetchExtendedInformation(const QString &path, const QStringList &files);
- void updateFile(const QString &path);
- void setResolveSymlinks(bool enable);
- bool resolveSymlinks() const;
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
-
-protected:
- void run();
- void getFileInfos(const QString &path, const QStringList &files);
-
-private:
- void fetch(const QFileInfo &info, QElapsedTimer &base, bool &firstTime, QList<QPair<QString, QFileInfo> > &updatedFiles, const QString &path);
- QString translateDriveName(const QFileInfo &drive) const;
-
- QMutex mutex;
- QWaitCondition condition;
- volatile bool abort;
-
- QStack<QString> path;
- QStack<QStringList> files;
-
-#ifndef QT_NO_FILESYSTEMWATCHER
- QFileSystemWatcher *watcher;
-#endif
- bool m_resolveSymlinks;
- QFileIconProvider *m_iconProvider;
- QFileIconProvider defaultProvider;
-#ifndef Q_OS_WIN
- uint userId;
- uint groupId;
-#endif
-};
-#endif // QT_NO_FILESYSTEMMODEL
-
-
-QT_END_NAMESPACE
-#endif // QFILEINFOGATHERER_H
-
diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp
deleted file mode 100644
index cb8eb6ad66..0000000000
--- a/src/gui/dialogs/qfilesystemmodel.cpp
+++ /dev/null
@@ -1,2027 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfilesystemmodel_p.h"
-#include "qfilesystemmodel.h"
-#include <qlocale.h>
-#include <qmime.h>
-#include <qurl.h>
-#include <qdebug.h>
-#include <qmessagebox.h>
-#include <qapplication.h>
-
-#ifdef Q_OS_WIN
-#include <qt_windows.h>
-#endif
-#ifdef Q_OS_WIN32
-#include <QtCore/QVarLengthArray>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_FILESYSTEMMODEL
-
-/*!
- \enum QFileSystemModel::Roles
- \value FileIconRole
- \value FilePathRole
- \value FileNameRole
- \value FilePermissions
-*/
-
-/*!
- \class QFileSystemModel
- \since 4.4
-
- \brief The QFileSystemModel class provides a data model for the local filesystem.
-
- \ingroup model-view
-
- This class provides access to the local filesystem, providing functions
- for renaming and removing files and directories, and for creating new
- directories. In the simplest case, it can be used with a suitable display
- widget as part of a browser or filter.
-
- QFileSystemModel can be accessed using the standard interface provided by
- QAbstractItemModel, but it also provides some convenience functions that are
- specific to a directory model.
- The fileInfo(), isDir(), name(), and path() functions provide information
- about the underlying files and directories related to items in the model.
- Directories can be created and removed using mkdir(), rmdir().
-
- \note QFileSystemModel requires an instance of a GUI application.
-
- \section1 Example Usage
-
- A directory model that displays the contents of a default directory
- is usually constructed with a parent object:
-
- \snippet doc/src/snippets/shareddirmodel/main.cpp 2
-
- A tree view can be used to display the contents of the model
-
- \snippet doc/src/snippets/shareddirmodel/main.cpp 4
-
- and the contents of a particular directory can be displayed by
- setting the tree view's root index:
-
- \snippet doc/src/snippets/shareddirmodel/main.cpp 7
-
- The view's root index can be used to control how much of a
- hierarchical model is displayed. QDirModel provides a convenience
- function that returns a suitable model index for a path to a
- directory within the model.
-
- \section1 Caching and Performance
-
- QFileSystemModel will not fetch any files or directories until setRootPath()
- is called. This will prevent any unnecessary querying on the file system
- until that point such as listing the drives on Windows.
-
- Unlike QDirModel, QFileSystemModel uses a separate thread to populate
- itself so it will not cause the main thread to hang as the file system
- is being queried. Calls to rowCount() will return 0 until the model
- populates a directory.
-
- QFileSystemModel keeps a cache with file information. The cache is
- automatically kept up to date using the QFileSystemWatcher.
-
- \sa {Model Classes}
-*/
-
-/*!
- \fn bool QFileSystemModel::rmdir(const QModelIndex &index) const
-
- Removes the directory corresponding to the model item \a index in the
- file system model and \bold{deletes the corresponding directory from the
- file system}, returning true if successful. If the directory cannot be
- removed, false is returned.
-
- \warning This function deletes directories from the file system; it does
- \bold{not} move them to a location where they can be recovered.
-
- \sa remove()
-*/
-
-/*!
- \fn QIcon QFileSystemModel::fileName(const QModelIndex &index) const
-
- Returns the file name for the item stored in the model under the given
- \a index.
-*/
-
-/*!
- \fn QIcon QFileSystemModel::fileIcon(const QModelIndex &index) const
-
- Returns the icon for the item stored in the model under the given
- \a index.
-*/
-
-/*!
- \fn QFileInfo QFileSystemModel::fileInfo(const QModelIndex &index) const
-
- Returns the QFileInfo for the item stored in the model under the given
- \a index.
-*/
-
-/*!
- \fn void QFileSystemModel::rootPathChanged(const QString &newPath);
-
- This signal is emitted whenever the root path has been changed to a \a newPath.
-*/
-
-/*!
- \fn void QFileSystemModel::fileRenamed(const QString &path, const QString &oldName, const QString &newName)
-
- This signal is emitted whenever a file with the \a oldName is successfully
- renamed to \a newName. The file is located in in the directory \a path.
-*/
-
-/*!
- \since 4.7
- \fn void QFileSystemModel::directoryLoaded(const QString &path)
-
- This signal is emitted when the gatherer thread has finished to load the \a path.
-
-*/
-
-/*!
- \fn bool QFileSystemModel::remove(const QModelIndex &index) const
-
- Removes the model item \a index from the file system model and \bold{deletes the
- corresponding file from the file system}, returning true if successful. If the
- item cannot be removed, false is returned.
-
- \warning This function deletes files from the file system; it does \bold{not}
- move them to a location where they can be recovered.
-
- \sa rmdir()
-*/
-
-bool QFileSystemModel::remove(const QModelIndex &aindex) const
-{
- //### TODO optim
- QString path = filePath(aindex);
- QFileSystemModelPrivate * d = const_cast<QFileSystemModelPrivate*>(d_func());
- d->fileInfoGatherer.removePath(path);
- QDirIterator it(path,
- QDir::AllDirs | QDir:: Files | QDir::NoDotAndDotDot,
- QDirIterator::Subdirectories);
- QStringList children;
- while (it.hasNext())
- children.prepend(it.next());
- children.append(path);
-
- bool error = false;
- for (int i = 0; i < children.count(); ++i) {
- QFileInfo info(children.at(i));
- QModelIndex modelIndex = index(children.at(i));
- if (info.isDir()) {
- QDir dir;
- if (children.at(i) != path)
- error |= remove(modelIndex);
- error |= rmdir(modelIndex);
- } else {
- error |= QFile::remove(filePath(modelIndex));
- }
- }
- return error;
-}
-
-/*!
- Constructs a file system model with the given \a parent.
-*/
-QFileSystemModel::QFileSystemModel(QObject *parent)
- : QAbstractItemModel(*new QFileSystemModelPrivate, parent)
-{
- Q_D(QFileSystemModel);
- d->init();
-}
-
-/*!
- \internal
-*/
-QFileSystemModel::QFileSystemModel(QFileSystemModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- Q_D(QFileSystemModel);
- d->init();
-}
-
-/*!
- Destroys this file system model.
-*/
-QFileSystemModel::~QFileSystemModel()
-{
-}
-
-/*!
- \reimp
-*/
-QModelIndex QFileSystemModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- if (row < 0 || column < 0 || row >= rowCount(parent) || column >= columnCount(parent))
- return QModelIndex();
-
- // get the parent node
- QFileSystemModelPrivate::QFileSystemNode *parentNode = (d->indexValid(parent) ? d->node(parent) :
- const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&d->root));
- Q_ASSERT(parentNode);
-
- // now get the internal pointer for the index
- QString childName = parentNode->visibleChildren[d->translateVisibleLocation(parentNode, row)];
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = parentNode->children.value(childName);
- Q_ASSERT(indexNode);
-
- return createIndex(row, column, const_cast<QFileSystemModelPrivate::QFileSystemNode*>(indexNode));
-}
-
-/*!
- \overload
-
- Returns the model item index for the given \a path and \a column.
-*/
-QModelIndex QFileSystemModel::index(const QString &path, int column) const
-{
- Q_D(const QFileSystemModel);
- QFileSystemModelPrivate::QFileSystemNode *node = d->node(path, false);
- QModelIndex idx = d->index(node);
- if (idx.column() != column)
- idx = idx.sibling(idx.row(), column);
- return idx;
-}
-
-/*!
- \internal
-
- Return the QFileSystemNode that goes to index.
- */
-QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QModelIndex &index) const
-{
- if (!index.isValid())
- return const_cast<QFileSystemNode*>(&root);
- QFileSystemModelPrivate::QFileSystemNode *indexNode = static_cast<QFileSystemModelPrivate::QFileSystemNode*>(index.internalPointer());
- Q_ASSERT(indexNode);
- return indexNode;
-}
-
-#ifdef Q_OS_WIN32
-static QString qt_GetLongPathName(const QString &strShortPath)
-{
- if (strShortPath.isEmpty()
- || strShortPath == QLatin1String(".") || strShortPath == QLatin1String(".."))
- return strShortPath;
- if (strShortPath.length() == 2 && strShortPath.endsWith(QLatin1Char(':')))
- return strShortPath.toUpper();
- const QString absPath = QDir(strShortPath).absolutePath();
- if (absPath.startsWith(QLatin1String("//"))
- || absPath.startsWith(QLatin1String("\\\\"))) // unc
- return QDir::fromNativeSeparators(absPath);
- if (absPath.startsWith(QLatin1Char('/')))
- return QString();
- const QString inputString = QLatin1String("\\\\?\\") + QDir::toNativeSeparators(absPath);
- QVarLengthArray<TCHAR, MAX_PATH> buffer(MAX_PATH);
- DWORD result = ::GetLongPathName((wchar_t*)inputString.utf16(),
- buffer.data(),
- buffer.size());
- if (result > DWORD(buffer.size())) {
- buffer.resize(result);
- result = ::GetLongPathName((wchar_t*)inputString.utf16(),
- buffer.data(),
- buffer.size());
- }
- if (result > 4) {
- QString longPath = QString::fromWCharArray(buffer.data() + 4); // ignoring prefix
- longPath[0] = longPath.at(0).toUpper(); // capital drive letters
- return QDir::fromNativeSeparators(longPath);
- } else {
- return QDir::fromNativeSeparators(strShortPath);
- }
-}
-#endif
-
-/*!
- \internal
-
- Given a path return the matching QFileSystemNode or &root if invalid
-*/
-QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QString &path, bool fetch) const
-{
- Q_Q(const QFileSystemModel);
- Q_UNUSED(q);
- if (path.isEmpty() || path == myComputer() || path.startsWith(QLatin1Char(':')))
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
-
- // Construct the nodes up to the new root path if they need to be built
- QString absolutePath;
-#ifdef Q_OS_WIN32
- QString longPath = qt_GetLongPathName(path);
-#else
- QString longPath = path;
-#endif
- if (longPath == rootDir.path())
- absolutePath = rootDir.absolutePath();
- else
- absolutePath = QDir(longPath).absolutePath();
-
- // ### TODO can we use bool QAbstractFileEngine::caseSensitive() const?
- QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
- if ((pathElements.isEmpty())
-#if (!defined(Q_OS_WIN) || defined(Q_OS_WINCE)) && !defined(Q_OS_SYMBIAN)
- && QDir::fromNativeSeparators(longPath) != QLatin1String("/")
-#endif
- )
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
- QModelIndex index = QModelIndex(); // start with "My Computer"
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (absolutePath.startsWith(QLatin1String("//"))) { // UNC path
- QString host = QLatin1String("\\\\") + pathElements.first();
- if (absolutePath == QDir::fromNativeSeparators(host))
- absolutePath.append(QLatin1Char('/'));
- if (longPath.endsWith(QLatin1Char('/')) && !absolutePath.endsWith(QLatin1Char('/')))
- absolutePath.append(QLatin1Char('/'));
- int r = 0;
- QFileSystemModelPrivate::QFileSystemNode *rootNode = const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
- if (!root.children.contains(host.toLower())) {
- if (pathElements.count() == 1 && !absolutePath.endsWith(QLatin1Char('/')))
- return rootNode;
- QFileInfo info(host);
- if (!info.exists())
- return rootNode;
- QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this);
- p->addNode(rootNode, host,info);
- p->addVisibleFiles(rootNode, QStringList(host));
- }
- r = rootNode->visibleLocation(host);
- r = translateVisibleLocation(rootNode, r);
- index = q->index(r, 0, QModelIndex());
- pathElements.pop_front();
- } else
-#endif
-
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- {
- if (!pathElements.at(0).contains(QLatin1String(":"))) {
- // The reason we express it like this instead of with anonymous, temporary
- // variables, is to workaround a compiler crash with Q_CC_NOKIAX86.
- QString rootPath = QDir(longPath).rootPath();
- pathElements.prepend(rootPath);
- }
- if (pathElements.at(0).endsWith(QLatin1Char('/')))
- pathElements[0].chop(1);
- }
-#else
- // add the "/" item, since it is a valid path element on Unix
- if (absolutePath[0] == QLatin1Char('/'))
- pathElements.prepend(QLatin1String("/"));
-#endif
-
- QFileSystemModelPrivate::QFileSystemNode *parent = node(index);
-
- for (int i = 0; i < pathElements.count(); ++i) {
- QString element = pathElements.at(i);
-#ifdef Q_OS_WIN
- // On Windows, "filename......." and "filename" are equivalent Task #133928
- while (element.endsWith(QLatin1Char('.')))
- element.chop(1);
-#endif
- bool alreadyExisted = parent->children.contains(element);
-
- // we couldn't find the path element, we create a new node since we
- // _know_ that the path is valid
- if (alreadyExisted) {
- if ((parent->children.count() == 0)
- || (parent->caseSensitive()
- && parent->children.value(element)->fileName != element)
- || (!parent->caseSensitive()
- && parent->children.value(element)->fileName.toLower() != element.toLower()))
- alreadyExisted = false;
- }
-
- QFileSystemModelPrivate::QFileSystemNode *node;
- if (!alreadyExisted) {
- // Someone might call ::index("file://cookie/monster/doesn't/like/veggies"),
- // a path that doesn't exists, I.E. don't blindly create directories.
- QFileInfo info(absolutePath);
- if (!info.exists())
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
- QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this);
- node = p->addNode(parent, element,info);
-#ifndef QT_NO_FILESYSTEMWATCHER
- node->populate(fileInfoGatherer.getInfo(info));
-#endif
- } else {
- node = parent->children.value(element);
- }
-
- Q_ASSERT(node);
- if (!node->isVisible) {
- // It has been filtered out
- if (alreadyExisted && node->hasInformation() && !fetch)
- return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root);
-
- QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this);
- p->addVisibleFiles(parent, QStringList(element));
- if (!p->bypassFilters.contains(node))
- p->bypassFilters[node] = 1;
- QString dir = q->filePath(this->index(parent));
- if (!node->hasInformation() && fetch) {
- Fetching f;
- f.dir = dir;
- f.file = element;
- f.node = node;
- p->toFetch.append(f);
- p->fetchingTimer.start(0, const_cast<QFileSystemModel*>(q));
- }
- }
- parent = node;
- }
-
- return parent;
-}
-
-/*!
- \reimp
-*/
-void QFileSystemModel::timerEvent(QTimerEvent *event)
-{
- Q_D(QFileSystemModel);
- if (event->timerId() == d->fetchingTimer.timerId()) {
- d->fetchingTimer.stop();
-#ifndef QT_NO_FILESYSTEMWATCHER
- for (int i = 0; i < d->toFetch.count(); ++i) {
- const QFileSystemModelPrivate::QFileSystemNode *node = d->toFetch.at(i).node;
- if (!node->hasInformation()) {
- d->fileInfoGatherer.fetchExtendedInformation(d->toFetch.at(i).dir,
- QStringList(d->toFetch.at(i).file));
- } else {
- // qDebug() << "yah!, you saved a little gerbil soul";
- }
- }
-#endif
- d->toFetch.clear();
- }
-}
-
-/*!
- Returns true if the model item \a index represents a directory;
- otherwise returns false.
-*/
-bool QFileSystemModel::isDir(const QModelIndex &index) const
-{
- // This function is for public usage only because it could create a file info
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return true;
- QFileSystemModelPrivate::QFileSystemNode *n = d->node(index);
- if (n->hasInformation())
- return n->isDir();
- return fileInfo(index).isDir();
-}
-
-/*!
- Returns the size in bytes of \a index. If the file does not exist, 0 is returned.
- */
-qint64 QFileSystemModel::size(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return 0;
- return d->node(index)->size();
-}
-
-/*!
- Returns the type of file \a index such as "Directory" or "JPEG file".
- */
-QString QFileSystemModel::type(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return QString();
- return d->node(index)->type();
-}
-
-/*!
- Returns the date and time when \a index was last modified.
- */
-QDateTime QFileSystemModel::lastModified(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid())
- return QDateTime();
- return d->node(index)->lastModified();
-}
-
-/*!
- \reimp
-*/
-QModelIndex QFileSystemModel::parent(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- if (!d->indexValid(index))
- return QModelIndex();
-
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(index);
- Q_ASSERT(indexNode != 0);
- QFileSystemModelPrivate::QFileSystemNode *parentNode = (indexNode ? indexNode->parent : 0);
- if (parentNode == 0 || parentNode == &d->root)
- return QModelIndex();
-
- // get the parent's row
- QFileSystemModelPrivate::QFileSystemNode *grandParentNode = parentNode->parent;
- Q_ASSERT(grandParentNode->children.contains(parentNode->fileName));
- int visualRow = d->translateVisibleLocation(grandParentNode, grandParentNode->visibleLocation(grandParentNode->children.value(parentNode->fileName)->fileName));
- if (visualRow == -1)
- return QModelIndex();
- return createIndex(visualRow, 0, parentNode);
-}
-
-/*
- \internal
-
- return the index for node
-*/
-QModelIndex QFileSystemModelPrivate::index(const QFileSystemModelPrivate::QFileSystemNode *node) const
-{
- Q_Q(const QFileSystemModel);
- QFileSystemModelPrivate::QFileSystemNode *parentNode = (node ? node->parent : 0);
- if (node == &root || !parentNode)
- return QModelIndex();
-
- // get the parent's row
- Q_ASSERT(node);
- if (!node->isVisible)
- return QModelIndex();
-
- int visualRow = translateVisibleLocation(parentNode, parentNode->visibleLocation(node->fileName));
- return q->createIndex(visualRow, 0, const_cast<QFileSystemNode*>(node));
-}
-
-/*!
- \reimp
-*/
-bool QFileSystemModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- if (parent.column() > 0)
- return false;
-
- if (!parent.isValid()) // drives
- return true;
-
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent);
- Q_ASSERT(indexNode);
- return (indexNode->isDir());
-}
-
-/*!
- \reimp
- */
-bool QFileSystemModel::canFetchMore(const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- const QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent);
- return (!indexNode->populatedChildren);
-}
-
-/*!
- \reimp
- */
-void QFileSystemModel::fetchMore(const QModelIndex &parent)
-{
- Q_D(QFileSystemModel);
- if (!d->setRootPath)
- return;
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent);
- if (indexNode->populatedChildren)
- return;
- indexNode->populatedChildren = true;
- d->fileInfoGatherer.list(filePath(parent));
-}
-
-/*!
- \reimp
-*/
-int QFileSystemModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QFileSystemModel);
- if (parent.column() > 0)
- return 0;
-
- if (!parent.isValid())
- return d->root.visibleChildren.count();
-
- const QFileSystemModelPrivate::QFileSystemNode *parentNode = d->node(parent);
- return parentNode->visibleChildren.count();
-}
-
-/*!
- \reimp
-*/
-int QFileSystemModel::columnCount(const QModelIndex &parent) const
-{
- return (parent.column() > 0) ? 0 : 4;
-}
-
-/*!
- Returns the data stored under the given \a role for the item "My Computer".
-
- \sa Qt::ItemDataRole
- */
-QVariant QFileSystemModel::myComputer(int role) const
-{
- Q_D(const QFileSystemModel);
- switch (role) {
- case Qt::DisplayRole:
- return d->myComputer();
- case Qt::DecorationRole:
- return d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::Computer);
- }
- return QVariant();
-}
-
-/*!
- \reimp
-*/
-QVariant QFileSystemModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QFileSystemModel);
- if (!index.isValid() || index.model() != this)
- return QVariant();
-
- switch (role) {
- case Qt::EditRole:
- case Qt::DisplayRole:
- switch (index.column()) {
- case 0: return d->displayName(index);
- case 1: return d->size(index);
- case 2: return d->type(index);
- case 3: return d->time(index);
- default:
- qWarning("data: invalid display value column %d", index.column());
- break;
- }
- break;
- case FilePathRole:
- return filePath(index);
- case FileNameRole:
- return d->name(index);
- case Qt::DecorationRole:
- if (index.column() == 0) {
- QIcon icon = d->icon(index);
- if (icon.isNull()) {
- if (d->node(index)->isDir())
- icon = d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::Folder);
- else
- icon = d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::File);
- }
- return icon;
- }
- break;
- case Qt::TextAlignmentRole:
- if (index.column() == 1)
- return Qt::AlignRight;
- break;
- case FilePermissions:
- int p = permissions(index);
- return p;
- }
-
- return QVariant();
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::size(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
- const QFileSystemNode *n = node(index);
- if (n->isDir()) {
-#ifdef Q_OS_MAC
- return QLatin1String("--");
-#else
- return QLatin1String("");
-#endif
- // Windows - ""
- // OS X - "--"
- // Konqueror - "4 KB"
- // Nautilus - "9 items" (the number of children)
- }
- return size(n->size());
-}
-
-QString QFileSystemModelPrivate::size(qint64 bytes)
-{
- // According to the Si standard KB is 1000 bytes, KiB is 1024
- // but on windows sizes are calculated by dividing by 1024 so we do what they do.
- const qint64 kb = 1024;
- const qint64 mb = 1024 * kb;
- const qint64 gb = 1024 * mb;
- const qint64 tb = 1024 * gb;
- if (bytes >= tb)
- return QFileSystemModel::tr("%1 TB").arg(QLocale().toString(qreal(bytes) / tb, 'f', 3));
- if (bytes >= gb)
- return QFileSystemModel::tr("%1 GB").arg(QLocale().toString(qreal(bytes) / gb, 'f', 2));
- if (bytes >= mb)
- return QFileSystemModel::tr("%1 MB").arg(QLocale().toString(qreal(bytes) / mb, 'f', 1));
- if (bytes >= kb)
- return QFileSystemModel::tr("%1 KB").arg(QLocale().toString(bytes / kb));
- return QFileSystemModel::tr("%1 bytes").arg(QLocale().toString(bytes));
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::time(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
-#ifndef QT_NO_DATESTRING
- return node(index)->lastModified().toString(Qt::SystemLocaleDate);
-#else
- Q_UNUSED(index);
- return QString();
-#endif
-}
-
-/*
- \internal
-*/
-QString QFileSystemModelPrivate::type(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
- return node(index)->type();
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::name(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QString();
- QFileSystemNode *dirNode = node(index);
- if (dirNode->isSymLink() && fileInfoGatherer.resolveSymlinks()) {
- QString fullPath = QDir::fromNativeSeparators(filePath(index));
- if (resolvedSymLinks.contains(fullPath))
- return resolvedSymLinks[fullPath];
- }
- return dirNode->fileName;
-}
-
-/*!
- \internal
-*/
-QString QFileSystemModelPrivate::displayName(const QModelIndex &index) const
-{
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- QFileSystemNode *dirNode = node(index);
- if (!dirNode->volumeName.isNull())
- return dirNode->volumeName + QLatin1String(" (") + name(index) + QLatin1Char(')');
-#endif
- return name(index);
-}
-
-/*!
- \internal
-*/
-QIcon QFileSystemModelPrivate::icon(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QIcon();
- return node(index)->icon();
-}
-
-/*!
- \reimp
-*/
-bool QFileSystemModel::setData(const QModelIndex &idx, const QVariant &value, int role)
-{
- Q_D(QFileSystemModel);
- if (!idx.isValid()
- || idx.column() != 0
- || role != Qt::EditRole
- || (flags(idx) & Qt::ItemIsEditable) == 0) {
- return false;
- }
-
- QString newName = value.toString();
- QString oldName = idx.data().toString();
- if (newName == idx.data().toString())
- return true;
-
- if (newName.isEmpty()
- || newName.contains(QDir::separator())
- || !QDir(filePath(parent(idx))).rename(oldName, newName)) {
-#ifndef QT_NO_MESSAGEBOX
- QMessageBox::information(0, QFileSystemModel::tr("Invalid filename"),
- QFileSystemModel::tr("<b>The name \"%1\" can not be used.</b><p>Try using another name, with fewer characters or no punctuations marks.")
- .arg(newName),
- QMessageBox::Ok);
-#endif // QT_NO_MESSAGEBOX
- return false;
- } else {
- /*
- *After re-naming something we don't want the selection to change*
- - can't remove rows and later insert
- - can't quickly remove and insert
- - index pointer can't change because treeview doesn't use persistant index's
-
- - if this get any more complicated think of changing it to just
- use layoutChanged
- */
-
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(idx);
- QFileSystemModelPrivate::QFileSystemNode *parentNode = indexNode->parent;
- int visibleLocation = parentNode->visibleLocation(parentNode->children.value(indexNode->fileName)->fileName);
-
- d->addNode(parentNode, newName,indexNode->info->fileInfo());
- parentNode->visibleChildren.removeAt(visibleLocation);
- QFileSystemModelPrivate::QFileSystemNode * oldValue = parentNode->children.value(oldName);
- parentNode->children[newName] = oldValue;
- QFileInfo info(d->rootDir, newName);
- oldValue->fileName = newName;
- oldValue->parent = parentNode;
- oldValue->populate(d->fileInfoGatherer.getInfo(info));
- oldValue->isVisible = true;
-
- parentNode->children.remove(oldName);
- parentNode->visibleChildren.insert(visibleLocation, newName);
-
- d->delayedSort();
- emit fileRenamed(filePath(idx.parent()), oldName, newName);
- }
- return true;
-}
-
-/*!
- \reimp
-*/
-QVariant QFileSystemModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- switch (role) {
- case Qt::DecorationRole:
- if (section == 0) {
- // ### TODO oh man this is ugly and doesn't even work all the way!
- // it is still 2 pixels off
- QImage pixmap(16, 1, QImage::Format_Mono);
- pixmap.fill(0);
- pixmap.setAlphaChannel(pixmap.createAlphaMask());
- return pixmap;
- }
- break;
- case Qt::TextAlignmentRole:
- return Qt::AlignLeft;
- }
-
- if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
- return QAbstractItemModel::headerData(section, orientation, role);
-
- QString returnValue;
- switch (section) {
- case 0: returnValue = tr("Name");
- break;
- case 1: returnValue = tr("Size");
- break;
- case 2: returnValue =
-#ifdef Q_OS_MAC
- tr("Kind", "Match OS X Finder");
-#else
- tr("Type", "All other platforms");
-#endif
- break;
- // Windows - Type
- // OS X - Kind
- // Konqueror - File Type
- // Nautilus - Type
- case 3: returnValue = tr("Date Modified");
- break;
- default: return QVariant();
- }
- return returnValue;
-}
-
-/*!
- \reimp
-*/
-Qt::ItemFlags QFileSystemModel::flags(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (!index.isValid())
- return flags;
-
- QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(index);
- if (d->nameFilterDisables && !d->passNameFilters(indexNode)) {
- flags &= ~Qt::ItemIsEnabled;
- // ### TODO you shouldn't be able to set this as the current item, task 119433
- return flags;
- }
-
- flags |= Qt::ItemIsDragEnabled;
- if (d->readOnly)
- return flags;
- if ((index.column() == 0) && indexNode->permissions() & QFile::WriteUser) {
- flags |= Qt::ItemIsEditable;
- if (indexNode->isDir())
- flags |= Qt::ItemIsDropEnabled;
- }
- return flags;
-}
-
-/*!
- \internal
-*/
-void QFileSystemModelPrivate::_q_performDelayedSort()
-{
- Q_Q(QFileSystemModel);
- q->sort(sortColumn, sortOrder);
-}
-
-static inline QChar getNextChar(const QString &s, int location)
-{
- return (location < s.length()) ? s.at(location) : QChar();
-}
-
-/*!
- Natural number sort, skips spaces.
-
- Examples:
- 1, 2, 10, 55, 100
- 01.jpg, 2.jpg, 10.jpg
-
- Note on the algorithm:
- Only as many characters as necessary are looked at and at most they all
- are looked at once.
-
- Slower then QString::compare() (of course)
- */
-int QFileSystemModelPrivate::naturalCompare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
-{
- for (int l1 = 0, l2 = 0; l1 <= s1.count() && l2 <= s2.count(); ++l1, ++l2) {
- // skip spaces, tabs and 0's
- QChar c1 = getNextChar(s1, l1);
- while (c1.isSpace())
- c1 = getNextChar(s1, ++l1);
- QChar c2 = getNextChar(s2, l2);
- while (c2.isSpace())
- c2 = getNextChar(s2, ++l2);
-
- if (c1.isDigit() && c2.isDigit()) {
- while (c1.digitValue() == 0)
- c1 = getNextChar(s1, ++l1);
- while (c2.digitValue() == 0)
- c2 = getNextChar(s2, ++l2);
-
- int lookAheadLocation1 = l1;
- int lookAheadLocation2 = l2;
- int currentReturnValue = 0;
- // find the last digit, setting currentReturnValue as we go if it isn't equal
- for (
- QChar lookAhead1 = c1, lookAhead2 = c2;
- (lookAheadLocation1 <= s1.length() && lookAheadLocation2 <= s2.length());
- lookAhead1 = getNextChar(s1, ++lookAheadLocation1),
- lookAhead2 = getNextChar(s2, ++lookAheadLocation2)
- ) {
- bool is1ADigit = !lookAhead1.isNull() && lookAhead1.isDigit();
- bool is2ADigit = !lookAhead2.isNull() && lookAhead2.isDigit();
- if (!is1ADigit && !is2ADigit)
- break;
- if (!is1ADigit)
- return -1;
- if (!is2ADigit)
- return 1;
- if (currentReturnValue == 0) {
- if (lookAhead1 < lookAhead2) {
- currentReturnValue = -1;
- } else if (lookAhead1 > lookAhead2) {
- currentReturnValue = 1;
- }
- }
- }
- if (currentReturnValue != 0)
- return currentReturnValue;
- }
-
- if (cs == Qt::CaseInsensitive) {
- if (!c1.isLower()) c1 = c1.toLower();
- if (!c2.isLower()) c2 = c2.toLower();
- }
- int r = QString::localeAwareCompare(c1, c2);
- if (r < 0)
- return -1;
- if (r > 0)
- return 1;
- }
- // The two strings are the same (02 == 2) so fall back to the normal sort
- return QString::compare(s1, s2, cs);
-}
-
-/*
- \internal
- Helper functor used by sort()
-*/
-class QFileSystemModelSorter
-{
-public:
- inline QFileSystemModelSorter(int column) : sortColumn(column) {}
-
- bool compareNodes(const QFileSystemModelPrivate::QFileSystemNode *l,
- const QFileSystemModelPrivate::QFileSystemNode *r) const
- {
- switch (sortColumn) {
- case 0: {
-#ifndef Q_OS_MAC
- // place directories before files
- bool left = l->isDir();
- bool right = r->isDir();
- if (left ^ right)
- return left;
-#endif
- return QFileSystemModelPrivate::naturalCompare(l->fileName,
- r->fileName, Qt::CaseInsensitive) < 0;
- }
- case 1:
- // Directories go first
- if (l->isDir() && !r->isDir())
- return true;
- return l->size() < r->size();
- case 2:
- return l->type() < r->type();
- case 3:
- return l->lastModified() < r->lastModified();
- }
- Q_ASSERT(false);
- return false;
- }
-
- bool operator()(const QPair<QFileSystemModelPrivate::QFileSystemNode*, int> &l,
- const QPair<QFileSystemModelPrivate::QFileSystemNode*, int> &r) const
- {
- return compareNodes(l.first, r.first);
- }
-
-
-private:
- int sortColumn;
-};
-
-/*
- \internal
-
- Sort all of the children of parent
-*/
-void QFileSystemModelPrivate::sortChildren(int column, const QModelIndex &parent)
-{
- Q_Q(QFileSystemModel);
- QFileSystemModelPrivate::QFileSystemNode *indexNode = node(parent);
- if (indexNode->children.count() == 0)
- return;
-
- QList<QPair<QFileSystemModelPrivate::QFileSystemNode*, int> > values;
- QHash<QString, QFileSystemNode *>::const_iterator iterator;
- int i = 0;
- for(iterator = indexNode->children.begin() ; iterator != indexNode->children.end() ; ++iterator) {
- if (filtersAcceptsNode(iterator.value())) {
- values.append(QPair<QFileSystemModelPrivate::QFileSystemNode*, int>((iterator.value()), i));
- } else {
- iterator.value()->isVisible = false;
- }
- i++;
- }
- QFileSystemModelSorter ms(column);
- qStableSort(values.begin(), values.end(), ms);
- // First update the new visible list
- indexNode->visibleChildren.clear();
- //No more dirty item we reset our internal dirty index
- indexNode->dirtyChildrenIndex = -1;
- for (int i = 0; i < values.count(); ++i) {
- indexNode->visibleChildren.append(values.at(i).first->fileName);
- values.at(i).first->isVisible = true;
- }
-
- if (!disableRecursiveSort) {
- for (int i = 0; i < q->rowCount(parent); ++i) {
- const QModelIndex childIndex = q->index(i, 0, parent);
- QFileSystemModelPrivate::QFileSystemNode *indexNode = node(childIndex);
- //Only do a recursive sort on visible nodes
- if (indexNode->isVisible)
- sortChildren(column, childIndex);
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QFileSystemModel::sort(int column, Qt::SortOrder order)
-{
- Q_D(QFileSystemModel);
- if (d->sortOrder == order && d->sortColumn == column && !d->forceSort)
- return;
-
- emit layoutAboutToBeChanged();
- QModelIndexList oldList = persistentIndexList();
- QList<QPair<QFileSystemModelPrivate::QFileSystemNode*, int> > oldNodes;
- for (int i = 0; i < oldList.count(); ++i) {
- QPair<QFileSystemModelPrivate::QFileSystemNode*, int> pair(d->node(oldList.at(i)), oldList.at(i).column());
- oldNodes.append(pair);
- }
-
- if (!(d->sortColumn == column && d->sortOrder != order && !d->forceSort)) {
- //we sort only from where we are, don't need to sort all the model
- d->sortChildren(column, index(rootPath()));
- d->sortColumn = column;
- d->forceSort = false;
- }
- d->sortOrder = order;
-
- QModelIndexList newList;
- for (int i = 0; i < oldNodes.count(); ++i) {
- QModelIndex idx = d->index(oldNodes.at(i).first);
- idx = idx.sibling(idx.row(), oldNodes.at(i).second);
- newList.append(idx);
- }
- changePersistentIndexList(oldList, newList);
- emit layoutChanged();
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of items
- in the model.
-*/
-QStringList QFileSystemModel::mimeTypes() const
-{
- return QStringList(QLatin1String("text/uri-list"));
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a indexes. The format used to describe the items corresponding to the
- indexes is obtained from the mimeTypes() function.
-
- If the list of indexes is empty, 0 is returned rather than a serialized
- empty list.
-*/
-QMimeData *QFileSystemModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QUrl> urls;
- QList<QModelIndex>::const_iterator it = indexes.begin();
- for (; it != indexes.end(); ++it)
- if ((*it).column() == 0)
- urls << QUrl::fromLocalFile(filePath(*it));
- QMimeData *data = new QMimeData();
- data->setUrls(urls);
- return data;
-}
-
-/*!
- Handles the \a data supplied by a drag and drop operation that ended with
- the given \a action over the row in the model specified by the \a row and
- \a column and by the \a parent index.
-
- \sa supportedDropActions()
-*/
-bool QFileSystemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- Q_UNUSED(row);
- Q_UNUSED(column);
- if (!parent.isValid() || isReadOnly())
- return false;
-
- bool success = true;
- QString to = filePath(parent) + QDir::separator();
-
- QList<QUrl> urls = data->urls();
- QList<QUrl>::const_iterator it = urls.constBegin();
-
- switch (action) {
- case Qt::CopyAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::copy(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::LinkAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::link(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::MoveAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::rename(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- default:
- return false;
- }
-
- return success;
-}
-
-/*!
- \reimp
-*/
-Qt::DropActions QFileSystemModel::supportedDropActions() const
-{
- return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;
-}
-
-/*!
- Returns the path of the item stored in the model under the
- \a index given.
-*/
-QString QFileSystemModel::filePath(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- QString fullPath = d->filePath(index);
- QFileSystemModelPrivate::QFileSystemNode *dirNode = d->node(index);
- if (dirNode->isSymLink() && d->fileInfoGatherer.resolveSymlinks()
- && d->resolvedSymLinks.contains(fullPath)
- && dirNode->isDir()) {
- QFileInfo resolvedInfo(fullPath);
- resolvedInfo = resolvedInfo.canonicalFilePath();
- if (resolvedInfo.exists())
- return resolvedInfo.filePath();
- }
- return fullPath;
-}
-
-QString QFileSystemModelPrivate::filePath(const QModelIndex &index) const
-{
- Q_Q(const QFileSystemModel);
- Q_UNUSED(q);
- if (!index.isValid())
- return QString();
- Q_ASSERT(index.model() == q);
-
- QStringList path;
- QModelIndex idx = index;
- while (idx.isValid()) {
- QFileSystemModelPrivate::QFileSystemNode *dirNode = node(idx);
- if (dirNode)
- path.prepend(dirNode->fileName);
- idx = idx.parent();
- }
- QString fullPath = QDir::fromNativeSeparators(path.join(QDir::separator()));
-#if !defined(Q_OS_WIN) || defined(Q_OS_WINCE)
- if ((fullPath.length() > 2) && fullPath[0] == QLatin1Char('/') && fullPath[1] == QLatin1Char('/'))
- fullPath = fullPath.mid(1);
-#endif
-#if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
- if (fullPath.length() == 2 && fullPath.endsWith(QLatin1Char(':')))
- fullPath.append(QLatin1Char('/'));
-#endif
- return fullPath;
-}
-
-/*!
- Create a directory with the \a name in the \a parent model index.
-*/
-QModelIndex QFileSystemModel::mkdir(const QModelIndex &parent, const QString &name)
-{
- Q_D(QFileSystemModel);
- if (!parent.isValid())
- return parent;
-
- QDir dir(filePath(parent));
- if (!dir.mkdir(name))
- return QModelIndex();
- QFileSystemModelPrivate::QFileSystemNode *parentNode = d->node(parent);
- d->addNode(parentNode, name, QFileInfo());
- Q_ASSERT(parentNode->children.contains(name));
- QFileSystemModelPrivate::QFileSystemNode *node = parentNode->children[name];
- node->populate(d->fileInfoGatherer.getInfo(QFileInfo(dir.absolutePath() + QDir::separator() + name)));
- d->addVisibleFiles(parentNode, QStringList(name));
- return d->index(node);
-}
-
-/*!
- Returns the complete OR-ed together combination of QFile::Permission for the \a index.
- */
-QFile::Permissions QFileSystemModel::permissions(const QModelIndex &index) const
-{
- Q_D(const QFileSystemModel);
- QFile::Permissions p = d->node(index)->permissions();
- if (d->readOnly) {
- p ^= (QFile::WriteOwner | QFile::WriteUser
- | QFile::WriteGroup | QFile::WriteOther);
- }
- return p;
-}
-
-/*!
- Sets the directory that is being watched by the model to \a newPath by
- installing a \l{QFileSystemWatcher}{file system watcher} on it. Any
- changes to files and directories within this directory will be
- reflected in the model.
-
- If the path is changed, the rootPathChanged() signal will be emitted.
-
- \note This function does not change the structure of the model or
- modify the data available to views. In other words, the "root" of
- the model is \e not changed to include only files and directories
- within the directory specified by \a newPath in the file system.
- */
-QModelIndex QFileSystemModel::setRootPath(const QString &newPath)
-{
- Q_D(QFileSystemModel);
-#ifdef Q_OS_WIN
-#ifdef Q_OS_WIN32
- QString longNewPath = qt_GetLongPathName(newPath);
-#else
- QString longNewPath = QDir::fromNativeSeparators(newPath);
-#endif
-#else
- QString longNewPath = newPath;
-#endif
- QDir newPathDir(longNewPath);
- //we remove .. and . from the given path if exist
- if (!newPath.isEmpty()) {
- longNewPath = QDir::cleanPath(longNewPath);
- newPathDir.setPath(longNewPath);
- }
-
- d->setRootPath = true;
-
- //user don't ask for the root path ("") but the conversion failed
- if (!newPath.isEmpty() && longNewPath.isEmpty())
- return d->index(rootPath());
-
- if (d->rootDir.path() == longNewPath)
- return d->index(rootPath());
-
- bool showDrives = (longNewPath.isEmpty() || longNewPath == d->myComputer());
- if (!showDrives && !newPathDir.exists())
- return d->index(rootPath());
-
- //We remove the watcher on the previous path
- if (!rootPath().isEmpty() && rootPath() != QLatin1String(".")) {
- //This remove the watcher for the old rootPath
- d->fileInfoGatherer.removePath(rootPath());
- //This line "marks" the node as dirty, so the next fetchMore
- //call on the path will ask the gatherer to install a watcher again
- //But it doesn't re-fetch everything
- d->node(rootPath())->populatedChildren = false;
- }
-
- // We have a new valid root path
- d->rootDir = newPathDir;
- QModelIndex newRootIndex;
- if (showDrives) {
- // otherwise dir will become '.'
- d->rootDir.setPath(QLatin1String(""));
- } else {
- newRootIndex = d->index(newPathDir.path());
- }
- fetchMore(newRootIndex);
- emit rootPathChanged(longNewPath);
- d->forceSort = true;
- d->delayedSort();
- return newRootIndex;
-}
-
-/*!
- The currently set root path
-
- \sa rootDirectory()
-*/
-QString QFileSystemModel::rootPath() const
-{
- Q_D(const QFileSystemModel);
- return d->rootDir.path();
-}
-
-/*!
- The currently set directory
-
- \sa rootPath()
-*/
-QDir QFileSystemModel::rootDirectory() const
-{
- Q_D(const QFileSystemModel);
- QDir dir(d->rootDir);
- dir.setNameFilters(nameFilters());
- dir.setFilter(filter());
- return dir;
-}
-
-/*!
- Sets the \a provider of file icons for the directory model.
-*/
-void QFileSystemModel::setIconProvider(QFileIconProvider *provider)
-{
- Q_D(QFileSystemModel);
- d->fileInfoGatherer.setIconProvider(provider);
- d->root.updateIcon(provider, QString());
-}
-
-/*!
- Returns the file icon provider for this directory model.
-*/
-QFileIconProvider *QFileSystemModel::iconProvider() const
-{
- Q_D(const QFileSystemModel);
- return d->fileInfoGatherer.iconProvider();
-}
-
-/*!
- Sets the directory model's filter to that specified by \a filters.
-
- Note that the filter you set should always include the QDir::AllDirs enum value,
- otherwise QFileSystemModel won't be able to read the directory structure.
-
- \sa QDir::Filters
-*/
-void QFileSystemModel::setFilter(QDir::Filters filters)
-{
- Q_D(QFileSystemModel);
- if (d->filters == filters)
- return;
- d->filters = filters;
- // CaseSensitivity might have changed
- setNameFilters(nameFilters());
- d->forceSort = true;
- d->delayedSort();
-}
-
-/*!
- Returns the filter specified for the directory model.
-
- If a filter has not been set, the default filter is QDir::AllEntries |
- QDir::NoDotAndDotDot | QDir::AllDirs.
-
- \sa QDir::Filters
-*/
-QDir::Filters QFileSystemModel::filter() const
-{
- Q_D(const QFileSystemModel);
- return d->filters;
-}
-
-/*!
- \property QFileSystemModel::resolveSymlinks
- \brief Whether the directory model should resolve symbolic links
-
- This is only relevant on operating systems that support symbolic links.
-
- By default, this property is false.
-*/
-void QFileSystemModel::setResolveSymlinks(bool enable)
-{
- Q_D(QFileSystemModel);
- d->fileInfoGatherer.setResolveSymlinks(enable);
-}
-
-bool QFileSystemModel::resolveSymlinks() const
-{
- Q_D(const QFileSystemModel);
- return d->fileInfoGatherer.resolveSymlinks();
-}
-
-/*!
- \property QFileSystemModel::readOnly
- \brief Whether the directory model allows writing to the file system
-
- If this property is set to false, the directory model will allow renaming, copying
- and deleting of files and directories.
-
- This property is true by default
-*/
-void QFileSystemModel::setReadOnly(bool enable)
-{
- Q_D(QFileSystemModel);
- d->readOnly = enable;
-}
-
-bool QFileSystemModel::isReadOnly() const
-{
- Q_D(const QFileSystemModel);
- return d->readOnly;
-}
-
-/*!
- \property QFileSystemModel::nameFilterDisables
- \brief Whether files that don't pass the name filter are hidden or disabled
-
- This property is true by default
-*/
-void QFileSystemModel::setNameFilterDisables(bool enable)
-{
- Q_D(QFileSystemModel);
- if (d->nameFilterDisables == enable)
- return;
- d->nameFilterDisables = enable;
- d->forceSort = true;
- d->delayedSort();
-}
-
-bool QFileSystemModel::nameFilterDisables() const
-{
- Q_D(const QFileSystemModel);
- return d->nameFilterDisables;
-}
-
-/*!
- Sets the name \a filters to apply against the existing files.
-*/
-void QFileSystemModel::setNameFilters(const QStringList &filters)
-{
- // Prep the regexp's ahead of time
-#ifndef QT_NO_REGEXP
- Q_D(QFileSystemModel);
-
- if (!d->bypassFilters.isEmpty()) {
- // update the bypass filter to only bypass the stuff that must be kept around
- d->bypassFilters.clear();
- // We guarantee that rootPath will stick around
- QPersistentModelIndex root(index(rootPath()));
- QModelIndexList persistantList = persistentIndexList();
- for (int i = 0; i < persistantList.count(); ++i) {
- QFileSystemModelPrivate::QFileSystemNode *node;
- node = d->node(persistantList.at(i));
- while (node) {
- if (d->bypassFilters.contains(node))
- break;
- if (node->isDir())
- d->bypassFilters[node] = true;
- node = node->parent;
- }
- }
- }
-
- d->nameFilters.clear();
- const Qt::CaseSensitivity caseSensitive =
- (filter() & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive;
- for (int i = 0; i < filters.size(); ++i) {
- d->nameFilters << QRegExp(filters.at(i), caseSensitive, QRegExp::Wildcard);
- }
- d->forceSort = true;
- d->delayedSort();
-#endif
-}
-
-/*!
- Returns a list of filters applied to the names in the model.
-*/
-QStringList QFileSystemModel::nameFilters() const
-{
- Q_D(const QFileSystemModel);
- QStringList filters;
-#ifndef QT_NO_REGEXP
- for (int i = 0; i < d->nameFilters.size(); ++i) {
- filters << d->nameFilters.at(i).pattern();
- }
-#endif
- return filters;
-}
-
-/*!
- \reimp
-*/
-bool QFileSystemModel::event(QEvent *event)
-{
- Q_D(QFileSystemModel);
- if (event->type() == QEvent::LanguageChange) {
- d->root.retranslateStrings(d->fileInfoGatherer.iconProvider(), QString());
- return true;
- }
- return QAbstractItemModel::event(event);
-}
-
-bool QFileSystemModel::rmdir(const QModelIndex &aindex) const
-{
- QString path = filePath(aindex);
- QFileSystemModelPrivate * d = const_cast<QFileSystemModelPrivate*>(d_func());
- d->fileInfoGatherer.removePath(path);
- return QDir().rmdir(path);
-}
-
-/*!
- \internal
-
- Performed quick listing and see if any files have been added or removed,
- then fetch more information on visible files.
- */
-void QFileSystemModelPrivate::_q_directoryChanged(const QString &directory, const QStringList &files)
-{
- QFileSystemModelPrivate::QFileSystemNode *parentNode = node(directory, false);
- if (parentNode->children.count() == 0)
- return;
- QStringList toRemove;
-#if defined(Q_OS_SYMBIAN)
- // Filename case must be exact in qBinaryFind below, so create a list of all lowercase names.
- QStringList newFiles;
- for(int i = 0; i < files.size(); i++) {
- newFiles << files.at(i).toLower();
- }
-#else
- QStringList newFiles = files;
-#endif
- qSort(newFiles.begin(), newFiles.end());
- QHash<QString, QFileSystemNode*>::const_iterator i = parentNode->children.constBegin();
- while (i != parentNode->children.constEnd()) {
- QStringList::iterator iterator;
- iterator = qBinaryFind(newFiles.begin(), newFiles.end(),
-#if defined(Q_OS_SYMBIAN)
- i.value()->fileName.toLower());
-#else
- i.value()->fileName);
-#endif
- if (iterator == newFiles.end()) {
- toRemove.append(i.value()->fileName);
- }
- ++i;
- }
- for (int i = 0 ; i < toRemove.count() ; ++i )
- removeNode(parentNode, toRemove[i]);
-}
-
-/*!
- \internal
-
- Adds a new file to the children of parentNode
-
- *WARNING* this will change the count of children
-*/
-QFileSystemModelPrivate::QFileSystemNode* QFileSystemModelPrivate::addNode(QFileSystemNode *parentNode, const QString &fileName, const QFileInfo& info)
-{
- // In the common case, itemLocation == count() so check there first
- QFileSystemModelPrivate::QFileSystemNode *node = new QFileSystemModelPrivate::QFileSystemNode(fileName, parentNode);
-#ifndef QT_NO_FILESYSTEMWATCHER
- node->populate(info);
-#endif
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- //The parentNode is "" so we are listing the drives
- if (parentNode->fileName.isEmpty()) {
- wchar_t name[MAX_PATH + 1];
- //GetVolumeInformation requires to add trailing backslash
- const QString nodeName = fileName + QLatin1String("\\");
- BOOL success = ::GetVolumeInformation((wchar_t *)(nodeName.utf16()),
- name, MAX_PATH + 1, NULL, 0, NULL, NULL, 0);
- if (success && name[0])
- node->volumeName = QString::fromWCharArray(name);
- }
-#endif
- parentNode->children.insert(fileName, node);
- return node;
-}
-
-/*!
- \internal
-
- File at parentNode->children(itemLocation) has been removed, remove from the lists
- and emit signals if necessary
-
- *WARNING* this will change the count of children and could change visibleChildren
- */
-void QFileSystemModelPrivate::removeNode(QFileSystemModelPrivate::QFileSystemNode *parentNode, const QString& name)
-{
- Q_Q(QFileSystemModel);
- QModelIndex parent = index(parentNode);
- bool indexHidden = isHiddenByFilter(parentNode, parent);
-
- int vLocation = parentNode->visibleLocation(name);
- if (vLocation >= 0 && !indexHidden)
- q->beginRemoveRows(parent, translateVisibleLocation(parentNode, vLocation),
- translateVisibleLocation(parentNode, vLocation));
- QFileSystemNode * node = parentNode->children.take(name);
- delete node;
- // cleanup sort files after removing rather then re-sorting which is O(n)
- if (vLocation >= 0)
- parentNode->visibleChildren.removeAt(vLocation);
- if (vLocation >= 0 && !indexHidden)
- q->endRemoveRows();
-}
-
-/*
- \internal
- Helper functor used by addVisibleFiles()
-*/
-class QFileSystemModelVisibleFinder
-{
-public:
- inline QFileSystemModelVisibleFinder(QFileSystemModelPrivate::QFileSystemNode *node, QFileSystemModelSorter *sorter) : parentNode(node), sorter(sorter) {}
-
- bool operator()(const QString &, QString r) const
- {
- return sorter->compareNodes(parentNode->children.value(name), parentNode->children.value(r));
- }
-
- QString name;
-private:
- QFileSystemModelPrivate::QFileSystemNode *parentNode;
- QFileSystemModelSorter *sorter;
-};
-
-/*!
- \internal
-
- File at parentNode->children(itemLocation) was not visible before, but now should be
- and emit signals if necessary.
-
- *WARNING* this will change the visible count
- */
-void QFileSystemModelPrivate::addVisibleFiles(QFileSystemNode *parentNode, const QStringList &newFiles)
-{
- Q_Q(QFileSystemModel);
- QModelIndex parent = index(parentNode);
- bool indexHidden = isHiddenByFilter(parentNode, parent);
- if (!indexHidden) {
- q->beginInsertRows(parent, parentNode->visibleChildren.count() , parentNode->visibleChildren.count() + newFiles.count() - 1);
- }
-
- if (parentNode->dirtyChildrenIndex == -1)
- parentNode->dirtyChildrenIndex = parentNode->visibleChildren.count();
-
- for (int i = 0; i < newFiles.count(); ++i) {
- parentNode->visibleChildren.append(newFiles.at(i));
- parentNode->children[newFiles.at(i)]->isVisible = true;
- }
- if (!indexHidden)
- q->endInsertRows();
-}
-
-/*!
- \internal
-
- File was visible before, but now should NOT be
-
- *WARNING* this will change the visible count
- */
-void QFileSystemModelPrivate::removeVisibleFile(QFileSystemNode *parentNode, int vLocation)
-{
- Q_Q(QFileSystemModel);
- if (vLocation == -1)
- return;
- QModelIndex parent = index(parentNode);
- bool indexHidden = isHiddenByFilter(parentNode, parent);
- if (!indexHidden)
- q->beginRemoveRows(parent, translateVisibleLocation(parentNode, vLocation),
- translateVisibleLocation(parentNode, vLocation));
- parentNode->children[parentNode->visibleChildren.at(vLocation)]->isVisible = false;
- parentNode->visibleChildren.removeAt(vLocation);
- if (!indexHidden)
- q->endRemoveRows();
-}
-
-/*!
- \internal
-
- The thread has received new information about files,
- update and emit dataChanged if it has actually changed.
- */
-void QFileSystemModelPrivate::_q_fileSystemChanged(const QString &path, const QList<QPair<QString, QFileInfo> > &updates)
-{
- Q_Q(QFileSystemModel);
- QVector<QString> rowsToUpdate;
- QStringList newFiles;
- QFileSystemModelPrivate::QFileSystemNode *parentNode = node(path, false);
- QModelIndex parentIndex = index(parentNode);
- for (int i = 0; i < updates.count(); ++i) {
- QString fileName = updates.at(i).first;
- Q_ASSERT(!fileName.isEmpty());
- QExtendedInformation info = fileInfoGatherer.getInfo(updates.at(i).second);
- bool previouslyHere = parentNode->children.contains(fileName);
- if (!previouslyHere) {
- addNode(parentNode, fileName, info.fileInfo());
- }
- QFileSystemModelPrivate::QFileSystemNode * node = parentNode->children.value(fileName);
- bool isCaseSensitive = parentNode->caseSensitive();
- if (isCaseSensitive) {
- if (node->fileName != fileName)
- continue;
- } else {
- if (QString::compare(node->fileName,fileName,Qt::CaseInsensitive) != 0)
- continue;
- }
- if (isCaseSensitive) {
- Q_ASSERT(node->fileName == fileName);
- } else {
- node->fileName = fileName;
- }
-
- if (info.size() == -1 && !info.isSymLink()) {
- removeNode(parentNode, fileName);
- continue;
- }
- if (*node != info ) {
- node->populate(info);
- bypassFilters.remove(node);
- // brand new information.
- if (filtersAcceptsNode(node)) {
- if (!node->isVisible) {
- newFiles.append(fileName);
- } else {
- rowsToUpdate.append(fileName);
- }
- } else {
- if (node->isVisible) {
- int visibleLocation = parentNode->visibleLocation(fileName);
- removeVisibleFile(parentNode, visibleLocation);
- } else {
- // The file is not visible, don't do anything
- }
- }
- }
- }
-
- // bundle up all of the changed signals into as few as possible.
- qSort(rowsToUpdate.begin(), rowsToUpdate.end());
- QString min;
- QString max;
- for (int i = 0; i < rowsToUpdate.count(); ++i) {
- QString value = rowsToUpdate.at(i);
- //##TODO is there a way to bundle signals with QString as the content of the list?
- /*if (min.isEmpty()) {
- min = value;
- if (i != rowsToUpdate.count() - 1)
- continue;
- }
- if (i != rowsToUpdate.count() - 1) {
- if ((value == min + 1 && max.isEmpty()) || value == max + 1) {
- max = value;
- continue;
- }
- }*/
- max = value;
- min = value;
- int visibleMin = parentNode->visibleLocation(min);
- int visibleMax = parentNode->visibleLocation(max);
- if (visibleMin >= 0
- && visibleMin < parentNode->visibleChildren.count()
- && parentNode->visibleChildren.at(visibleMin) == min
- && visibleMax >= 0) {
- QModelIndex bottom = q->index(translateVisibleLocation(parentNode, visibleMin), 0, parentIndex);
- QModelIndex top = q->index(translateVisibleLocation(parentNode, visibleMax), 3, parentIndex);
- emit q->dataChanged(bottom, top);
- }
-
- /*min = QString();
- max = QString();*/
- }
-
- if (newFiles.count() > 0) {
- addVisibleFiles(parentNode, newFiles);
- }
-
- if (newFiles.count() > 0 || (sortColumn != 0 && rowsToUpdate.count() > 0)) {
- forceSort = true;
- delayedSort();
- }
-}
-
-/*!
- \internal
-*/
-void QFileSystemModelPrivate::_q_resolvedName(const QString &fileName, const QString &resolvedName)
-{
- resolvedSymLinks[fileName] = resolvedName;
-}
-
-/*!
- \internal
-*/
-void QFileSystemModelPrivate::init()
-{
- Q_Q(QFileSystemModel);
- qRegisterMetaType<QList<QPair<QString,QFileInfo> > >("QList<QPair<QString,QFileInfo> >");
- q->connect(&fileInfoGatherer, SIGNAL(newListOfFiles(QString,QStringList)),
- q, SLOT(_q_directoryChanged(QString,QStringList)));
- q->connect(&fileInfoGatherer, SIGNAL(updates(QString,QList<QPair<QString,QFileInfo> >)),
- q, SLOT(_q_fileSystemChanged(QString,QList<QPair<QString,QFileInfo> >)));
- q->connect(&fileInfoGatherer, SIGNAL(nameResolved(QString,QString)),
- q, SLOT(_q_resolvedName(QString,QString)));
- q->connect(&fileInfoGatherer, SIGNAL(directoryLoaded(QString)),
- q, SIGNAL(directoryLoaded(QString)));
- q->connect(&delayedSortTimer, SIGNAL(timeout()), q, SLOT(_q_performDelayedSort()), Qt::QueuedConnection);
-
- QHash<int, QByteArray> roles = q->roleNames();
- roles.insertMulti(QFileSystemModel::FileIconRole, "fileIcon"); // == Qt::decoration
- roles.insert(QFileSystemModel::FilePathRole, "filePath");
- roles.insert(QFileSystemModel::FileNameRole, "fileName");
- roles.insert(QFileSystemModel::FilePermissions, "filePermissions");
- q->setRoleNames(roles);
-}
-
-/*!
- \internal
-
- Returns false if node doesn't pass the filters otherwise true
-
- QDir::Modified is not supported
- QDir::Drives is not supported
-*/
-bool QFileSystemModelPrivate::filtersAcceptsNode(const QFileSystemNode *node) const
-{
- // always accept drives
- if (node->parent == &root || bypassFilters.contains(node))
- return true;
-
- // If we don't know anything yet don't accept it
- if (!node->hasInformation())
- return false;
-
- const bool filterPermissions = ((filters & QDir::PermissionMask)
- && (filters & QDir::PermissionMask) != QDir::PermissionMask);
- const bool hideDirs = !(filters & (QDir::Dirs | QDir::AllDirs));
- const bool hideFiles = !(filters & QDir::Files);
- const bool hideReadable = !(!filterPermissions || (filters & QDir::Readable));
- const bool hideWritable = !(!filterPermissions || (filters & QDir::Writable));
- const bool hideExecutable = !(!filterPermissions || (filters & QDir::Executable));
- const bool hideHidden = !(filters & QDir::Hidden);
- const bool hideSystem = !(filters & QDir::System);
- const bool hideSymlinks = (filters & QDir::NoSymLinks);
- const bool hideDotAndDotDot = (filters & QDir::NoDotAndDotDot);
-
- // Note that we match the behavior of entryList and not QFileInfo on this and this
- // incompatibility won't be fixed until Qt 5 at least
- bool isDotOrDot = ( (node->fileName == QLatin1String(".")
- || node->fileName == QLatin1String("..")));
- if ( (hideHidden && (!isDotOrDot && node->isHidden()))
- || (hideSystem && node->isSystem())
- || (hideDirs && node->isDir())
- || (hideFiles && node->isFile())
- || (hideSymlinks && node->isSymLink())
- || (hideReadable && node->isReadable())
- || (hideWritable && node->isWritable())
- || (hideExecutable && node->isExecutable())
- || (hideDotAndDotDot && isDotOrDot))
- return false;
-
- return nameFilterDisables || passNameFilters(node);
-}
-
-/*
- \internal
-
- Returns true if node passes the name filters and should be visible.
- */
-bool QFileSystemModelPrivate::passNameFilters(const QFileSystemNode *node) const
-{
-#ifndef QT_NO_REGEXP
- if (nameFilters.isEmpty())
- return true;
-
- // Check the name regularexpression filters
- if (!(node->isDir() && (filters & QDir::AllDirs))) {
- for (int i = 0; i < nameFilters.size(); ++i) {
- if (nameFilters.at(i).exactMatch(node->fileName))
- return true;
- }
- return false;
- }
-#endif
- return true;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qfilesystemmodel.cpp"
-
-#endif // QT_NO_FILESYSTEMMODEL
diff --git a/src/gui/dialogs/qfilesystemmodel.h b/src/gui/dialogs/qfilesystemmodel.h
deleted file mode 100644
index 8aa9875d13..0000000000
--- a/src/gui/dialogs/qfilesystemmodel.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/****************************************************************************
-**
-** 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 QFILESYSTEMMODEL_H
-#define QFILESYSTEMMODEL_H
-
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qpair.h>
-#include <QtCore/qdir.h>
-#include <QtGui/qicon.h>
-#include <QtCore/qdiriterator.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_FILESYSTEMMODEL
-
-class ExtendedInformation;
-class QFileSystemModelPrivate;
-class QFileIconProvider;
-
-class Q_GUI_EXPORT QFileSystemModel : public QAbstractItemModel
-{
- Q_OBJECT
- Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(bool nameFilterDisables READ nameFilterDisables WRITE setNameFilterDisables)
-
-Q_SIGNALS:
- void rootPathChanged(const QString &newPath);
- void fileRenamed(const QString &path, const QString &oldName, const QString &newName);
- void directoryLoaded(const QString &path);
-
-public:
- enum Roles {
- FileIconRole = Qt::DecorationRole,
- FilePathRole = Qt::UserRole + 1,
- FileNameRole = Qt::UserRole + 2,
- FilePermissions = Qt::UserRole + 3
- };
-
- explicit QFileSystemModel(QObject *parent = 0);
- ~QFileSystemModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex index(const QString &path, int column = 0) const;
- QModelIndex parent(const QModelIndex &child) const;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
- bool canFetchMore(const QModelIndex &parent) const;
- void fetchMore(const QModelIndex &parent);
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant myComputer(int role = Qt::DisplayRole) const;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
-
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
- Qt::DropActions supportedDropActions() const;
-
- // QFileSystemModel specific API
- QModelIndex setRootPath(const QString &path);
- QString rootPath() const;
- QDir rootDirectory() const;
-
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
-
- void setFilter(QDir::Filters filters);
- QDir::Filters filter() const;
-
- void setResolveSymlinks(bool enable);
- bool resolveSymlinks() const;
-
- void setReadOnly(bool enable);
- bool isReadOnly() const;
-
- void setNameFilterDisables(bool enable);
- bool nameFilterDisables() const;
-
- void setNameFilters(const QStringList &filters);
- QStringList nameFilters() const;
-
- QString filePath(const QModelIndex &index) const;
- bool isDir(const QModelIndex &index) const;
- qint64 size(const QModelIndex &index) const;
- QString type(const QModelIndex &index) const;
- QDateTime lastModified(const QModelIndex &index) const;
-
- QModelIndex mkdir(const QModelIndex &parent, const QString &name);
- bool rmdir(const QModelIndex &index) const; // ### Qt5: should not be const
- inline QString fileName(const QModelIndex &index) const;
- inline QIcon fileIcon(const QModelIndex &index) const;
- QFile::Permissions permissions(const QModelIndex &index) const;
- inline QFileInfo fileInfo(const QModelIndex &index) const;
- bool remove(const QModelIndex &index) const;
-
-protected:
- QFileSystemModel(QFileSystemModelPrivate &, QObject *parent = 0);
- void timerEvent(QTimerEvent *event);
- bool event(QEvent *event);
-
-private:
- Q_DECLARE_PRIVATE(QFileSystemModel)
- Q_DISABLE_COPY(QFileSystemModel)
-
- Q_PRIVATE_SLOT(d_func(), void _q_directoryChanged(const QString &directory, const QStringList &list))
- Q_PRIVATE_SLOT(d_func(), void _q_performDelayedSort())
- Q_PRIVATE_SLOT(d_func(), void _q_fileSystemChanged(const QString &path, const QList<QPair<QString, QFileInfo> > &))
- Q_PRIVATE_SLOT(d_func(), void _q_resolvedName(const QString &fileName, const QString &resolvedName))
-
- friend class QFileDialogPrivate;
-};
-
-inline QString QFileSystemModel::fileName(const QModelIndex &aindex) const
-{ return aindex.data(Qt::DisplayRole).toString(); }
-inline QIcon QFileSystemModel::fileIcon(const QModelIndex &aindex) const
-{ return qvariant_cast<QIcon>(aindex.data(Qt::DecorationRole)); }
-inline QFileInfo QFileSystemModel::fileInfo(const QModelIndex &aindex) const
-{ return QFileInfo(filePath(aindex)); }
-
-#endif // QT_NO_FILESYSTEMMODEL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QFILESYSTEMMODEL_H
-
diff --git a/src/gui/dialogs/qfilesystemmodel_p.h b/src/gui/dialogs/qfilesystemmodel_p.h
deleted file mode 100644
index e83bbd11d3..0000000000
--- a/src/gui/dialogs/qfilesystemmodel_p.h
+++ /dev/null
@@ -1,337 +0,0 @@
-/****************************************************************************
-**
-** 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 QFILESYSTEMMODEL_P_H
-#define QFILESYSTEMMODEL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qfilesystemmodel.h"
-
-#ifndef QT_NO_FILESYSTEMMODEL
-
-#include <private/qabstractitemmodel_p.h>
-#include <qabstractitemmodel.h>
-#include "qfileinfogatherer_p.h"
-#include <qpair.h>
-#include <qdir.h>
-#include <qicon.h>
-#include <qdir.h>
-#include <qicon.h>
-#include <qfileinfo.h>
-#include <qtimer.h>
-#include <qhash.h>
-
-QT_BEGIN_NAMESPACE
-
-class ExtendedInformation;
-class QFileSystemModelPrivate;
-class QFileIconProvider;
-
-class Q_AUTOTEST_EXPORT QFileSystemModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QFileSystemModel)
-
-public:
- class QFileSystemNode
- {
- public:
- QFileSystemNode(const QString &filename = QString(), QFileSystemNode *p = 0)
- : fileName(filename), populatedChildren(false), isVisible(false), dirtyChildrenIndex(-1), parent(p), info(0) {}
- ~QFileSystemNode() {
- QHash<QString, QFileSystemNode*>::const_iterator i = children.constBegin();
- while (i != children.constEnd()) {
- delete i.value();
- ++i;
- }
- delete info;
- info = 0;
- parent = 0;
- }
-
- QString fileName;
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- QString volumeName;
-#endif
-
- inline qint64 size() const { if (info && !info->isDir()) return info->size(); return 0; }
- inline QString type() const { if (info) return info->displayType; return QLatin1String(""); }
- inline QDateTime lastModified() const { if (info) return info->lastModified(); return QDateTime(); }
- inline QFile::Permissions permissions() const { if (info) return info->permissions(); return 0; }
- inline bool isReadable() const { return ((permissions() & QFile::ReadUser) != 0); }
- inline bool isWritable() const { return ((permissions() & QFile::WriteUser) != 0); }
- inline bool isExecutable() const { return ((permissions() & QFile::ExeUser) != 0); }
- inline bool isDir() const {
- if (info)
- return info->isDir();
- if (children.count() > 0)
- return true;
- return false;
- }
- inline bool isFile() const { if (info) return info->isFile(); return true; }
- inline bool isSystem() const { if (info) return info->isSystem(); return true; }
- inline bool isHidden() const { if (info) return info->isHidden(); return false; }
- inline bool isSymLink() const { if (info) return info->isSymLink(); return false; }
- inline bool caseSensitive() const { if (info) return info->isCaseSensitive(); return false; }
- inline QIcon icon() const { if (info) return info->icon; return QIcon(); }
-
- inline bool operator <(const QFileSystemNode &node) const {
- if (caseSensitive() || node.caseSensitive())
- return fileName < node.fileName;
- return QString::compare(fileName, node.fileName, Qt::CaseInsensitive) < 0;
- }
- inline bool operator >(const QString &name) const {
- if (caseSensitive())
- return fileName > name;
- return QString::compare(fileName, name, Qt::CaseInsensitive) > 0;
- }
- inline bool operator <(const QString &name) const {
- if (caseSensitive())
- return fileName < name;
- return QString::compare(fileName, name, Qt::CaseInsensitive) < 0;
- }
- inline bool operator !=(const QExtendedInformation &fileInfo) const {
- return !operator==(fileInfo);
- }
- bool operator ==(const QString &name) const {
- if (caseSensitive())
- return fileName == name;
- return QString::compare(fileName, name, Qt::CaseInsensitive) == 0;
- }
- bool operator ==(const QExtendedInformation &fileInfo) const {
- return info && (*info == fileInfo);
- }
-
- inline bool hasInformation() const { return info != 0; }
-
- void populate(const QExtendedInformation &fileInfo) {
- if (!info)
- info = new QExtendedInformation(fileInfo.fileInfo());
- (*info) = fileInfo;
- }
-
- // children shouldn't normally be accessed directly, use node()
- inline int visibleLocation(QString childName) {
- return visibleChildren.indexOf(childName);
- }
- void updateIcon(QFileIconProvider *iconProvider, const QString &path) {
- if (info)
- info->icon = iconProvider->icon(QFileInfo(path));
- QHash<QString, QFileSystemNode *>::const_iterator iterator;
- for(iterator = children.constBegin() ; iterator != children.constEnd() ; ++iterator) {
- //On windows the root (My computer) has no path so we don't want to add a / for nothing (e.g. /C:/)
- if (!path.isEmpty()) {
- if (path.endsWith(QLatin1Char('/')))
- iterator.value()->updateIcon(iconProvider, path + iterator.value()->fileName);
- else
- iterator.value()->updateIcon(iconProvider, path + QLatin1Char('/') + iterator.value()->fileName);
- } else
- iterator.value()->updateIcon(iconProvider, iterator.value()->fileName);
- }
- }
-
- void retranslateStrings(QFileIconProvider *iconProvider, const QString &path) {
- if (info)
- info->displayType = iconProvider->type(QFileInfo(path));
- QHash<QString, QFileSystemNode *>::const_iterator iterator;
- for(iterator = children.constBegin() ; iterator != children.constEnd() ; ++iterator) {
- //On windows the root (My computer) has no path so we don't want to add a / for nothing (e.g. /C:/)
- if (!path.isEmpty()) {
- if (path.endsWith(QLatin1Char('/')))
- iterator.value()->retranslateStrings(iconProvider, path + iterator.value()->fileName);
- else
- iterator.value()->retranslateStrings(iconProvider, path + QLatin1Char('/') + iterator.value()->fileName);
- } else
- iterator.value()->retranslateStrings(iconProvider, iterator.value()->fileName);
- }
- }
-
- bool populatedChildren;
- bool isVisible;
- QHash<QString,QFileSystemNode *> children;
- QList<QString> visibleChildren;
- int dirtyChildrenIndex;
- QFileSystemNode *parent;
-
-
- QExtendedInformation *info;
-
- };
-
- QFileSystemModelPrivate() :
- forceSort(true),
- sortColumn(0),
- sortOrder(Qt::AscendingOrder),
- readOnly(true),
- setRootPath(false),
- filters(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs),
- nameFilterDisables(true), // false on windows, true on mac and unix
- disableRecursiveSort(false)
- {
- delayedSortTimer.setSingleShot(true);
- }
-
- void init();
- /*
- \internal
-
- Return true if index which is owned by node is hidden by the filter.
- */
- inline bool isHiddenByFilter(QFileSystemNode *indexNode, const QModelIndex &index) const
- {
- return (indexNode != &root && !index.isValid());
- }
- QFileSystemNode *node(const QModelIndex &index) const;
- QFileSystemNode *node(const QString &path, bool fetch = true) const;
- inline QModelIndex index(const QString &path) { return index(node(path)); }
- QModelIndex index(const QFileSystemNode *node) const;
- bool filtersAcceptsNode(const QFileSystemNode *node) const;
- bool passNameFilters(const QFileSystemNode *node) const;
- void removeNode(QFileSystemNode *parentNode, const QString &name);
- QFileSystemNode* addNode(QFileSystemNode *parentNode, const QString &fileName, const QFileInfo &info);
- void addVisibleFiles(QFileSystemNode *parentNode, const QStringList &newFiles);
- void removeVisibleFile(QFileSystemNode *parentNode, int visibleLocation);
- void sortChildren(int column, const QModelIndex &parent);
-
- inline int translateVisibleLocation(QFileSystemNode *parent, int row) const {
- if (sortOrder != Qt::AscendingOrder) {
- if (parent->dirtyChildrenIndex == -1)
- return parent->visibleChildren.count() - row - 1;
-
- if (row < parent->dirtyChildrenIndex)
- return parent->dirtyChildrenIndex - row - 1;
- }
-
- return row;
- }
-
- inline static QString myComputer() {
- // ### TODO We should query the system to find out what the string should be
- // XP == "My Computer",
- // Vista == "Computer",
- // OS X == "Computer" (sometime user generated) "Benjamin's PowerBook G4"
-#ifdef Q_OS_WIN
- return QFileSystemModel::tr("My Computer");
-#else
- return QFileSystemModel::tr("Computer");
-#endif
- }
-
- inline void delayedSort() {
- if (!delayedSortTimer.isActive())
- delayedSortTimer.start(0);
- }
-
- static bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
- {
- return QString::compare(s1, s2, Qt::CaseInsensitive) < 0;
- }
-
- static bool nodeCaseInsensitiveLessThan(const QFileSystemModelPrivate::QFileSystemNode &s1, const QFileSystemModelPrivate::QFileSystemNode &s2)
- {
- return QString::compare(s1.fileName, s2.fileName, Qt::CaseInsensitive) < 0;
- }
-
- QIcon icon(const QModelIndex &index) const;
- QString name(const QModelIndex &index) const;
- QString displayName(const QModelIndex &index) const;
- QString filePath(const QModelIndex &index) const;
- QString size(const QModelIndex &index) const;
- static QString size(qint64 bytes);
- QString type(const QModelIndex &index) const;
- QString time(const QModelIndex &index) const;
-
- void _q_directoryChanged(const QString &directory, const QStringList &list);
- void _q_performDelayedSort();
- void _q_fileSystemChanged(const QString &path, const QList<QPair<QString, QFileInfo> > &);
- void _q_resolvedName(const QString &fileName, const QString &resolvedName);
-
- static int naturalCompare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs);
-
- QDir rootDir;
-#ifndef QT_NO_FILESYSTEMWATCHER
- QFileInfoGatherer fileInfoGatherer;
-#endif
- QTimer delayedSortTimer;
- bool forceSort;
- int sortColumn;
- Qt::SortOrder sortOrder;
- bool readOnly;
- bool setRootPath;
- QDir::Filters filters;
- QHash<const QFileSystemNode*, bool> bypassFilters;
- bool nameFilterDisables;
- //This flag is an optimization for the QFileDialog
- //It enable a sort which is not recursive, it means
- //we sort only what we see.
- bool disableRecursiveSort;
-#ifndef QT_NO_REGEXP
- QList<QRegExp> nameFilters;
-#endif
- // ### Qt 5: resolvedSymLinks goes away
- QHash<QString, QString> resolvedSymLinks;
-
- QFileSystemNode root;
-
- QBasicTimer fetchingTimer;
- struct Fetching {
- QString dir;
- QString file;
- const QFileSystemNode *node;
- };
- QList<Fetching> toFetch;
-
-};
-#endif // QT_NO_FILESYSTEMMODEL
-
-QT_END_NAMESPACE
-
-#endif
-
diff --git a/src/gui/dialogs/qfontdialog.cpp b/src/gui/dialogs/qfontdialog.cpp
deleted file mode 100644
index b58021d877..0000000000
--- a/src/gui/dialogs/qfontdialog.cpp
+++ /dev/null
@@ -1,1077 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwindowdefs.h"
-
-#ifndef QT_NO_FONTDIALOG
-
-#include "qfontdialog.h"
-#include "qfontdialog_p.h"
-
-#include <qapplication.h>
-#include <qcheckbox.h>
-#include <qcombobox.h>
-#include <qevent.h>
-#include <qfontdatabase.h>
-#include <qgroupbox.h>
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qpushbutton.h>
-#include <qstyle.h>
-#include <qdialogbuttonbox.h>
-#include <qheaderview.h>
-#include <qlistview.h>
-#include <qstringlistmodel.h>
-#include <qvalidator.h>
-#include <private/qdialog_p.h>
-#include <private/qfont_p.h>
-
-#if defined(Q_WS_S60)
-#include <QtGui/qdesktopwidget.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QFontListView : public QListView
-{
- Q_OBJECT
-public:
- QFontListView(QWidget *parent);
- inline QStringListModel *model() const {
- return static_cast<QStringListModel *>(QListView::model());
- }
- inline void setCurrentItem(int item) {
- QListView::setCurrentIndex(static_cast<QAbstractListModel*>(model())->index(item));
- }
- inline int currentItem() const {
- return QListView::currentIndex().row();
- }
- inline int count() const {
- return model()->rowCount();
- }
- inline QString currentText() const {
- int row = QListView::currentIndex().row();
- return row < 0 ? QString() : model()->stringList().at(row);
- }
- void currentChanged(const QModelIndex &current, const QModelIndex &previous) {
- QListView::currentChanged(current, previous);
- if (current.isValid())
- emit highlighted(current.row());
- }
- QString text(int i) const {
- return model()->stringList().at(i);
- }
-signals:
- void highlighted(int);
-};
-
-QFontListView::QFontListView(QWidget *parent)
- : QListView(parent)
-{
- setModel(new QStringListModel(parent));
- setEditTriggers(NoEditTriggers);
-}
-
-static const Qt::WindowFlags DefaultWindowFlags =
- Qt::Dialog | Qt::WindowSystemMenuHint;
-
-/*!
- \class QFontDialog
- \ingroup standard-dialogs
-
- \brief The QFontDialog class provides a dialog widget for selecting a font.
-
- A font dialog is created through one of the static getFont()
- functions.
-
- Examples:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp 0
-
- The dialog can also be used to set a widget's font directly:
- \snippet doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp 1
- If the user clicks OK the font they chose will be used for myWidget,
- and if they click Cancel the original font is used.
-
- \image plastique-fontdialog.png A font dialog in the Plastique widget style.
-
- \sa QFont, QFontInfo, QFontMetrics, QColorDialog, QFileDialog, QPrintDialog,
- {Standard Dialogs Example}
-*/
-
-/*!
- \since 4.5
-
- Constructs a standard font dialog.
-
- Use setCurrentFont() to set the initial font attributes.
-
- The \a parent parameter is passed to the QDialog constructor.
-
- \sa getFont()
-*/
-QFontDialog::QFontDialog(QWidget *parent)
- : QDialog(*new QFontDialogPrivate, parent, DefaultWindowFlags)
-{
- Q_D(QFontDialog);
- d->init();
-}
-
-/*!
- \since 4.5
-
- Constructs a standard font dialog with the given \a parent and specified
- \a initial color.
-*/
-QFontDialog::QFontDialog(const QFont &initial, QWidget *parent)
- : QDialog(*new QFontDialogPrivate, parent, DefaultWindowFlags)
-{
- Q_D(QFontDialog);
- d->init();
- setCurrentFont(initial);
-}
-
-void QFontDialogPrivate::init()
-{
- Q_Q(QFontDialog);
-
-#ifdef Q_WS_MAC
- nativeDialogInUse = false;
- delegate = 0;
-#endif
-
- q->setSizeGripEnabled(true);
- q->setWindowTitle(QFontDialog::tr("Select Font"));
-
- // grid
- familyEdit = new QLineEdit(q);
- familyEdit->setReadOnly(true);
- familyList = new QFontListView(q);
- familyEdit->setFocusProxy(familyList);
-
- familyAccel = new QLabel(q);
-#ifndef QT_NO_SHORTCUT
- familyAccel->setBuddy(familyList);
-#endif
- familyAccel->setIndent(2);
-
- styleEdit = new QLineEdit(q);
- styleEdit->setReadOnly(true);
- styleList = new QFontListView(q);
- styleEdit->setFocusProxy(styleList);
-
- styleAccel = new QLabel(q);
-#ifndef QT_NO_SHORTCUT
- styleAccel->setBuddy(styleList);
-#endif
- styleAccel->setIndent(2);
-
- sizeEdit = new QLineEdit(q);
- sizeEdit->setFocusPolicy(Qt::ClickFocus);
- QIntValidator *validator = new QIntValidator(1, 512, q);
- sizeEdit->setValidator(validator);
- sizeList = new QFontListView(q);
-
- sizeAccel = new QLabel(q);
-#ifndef QT_NO_SHORTCUT
- sizeAccel->setBuddy(sizeEdit);
-#endif
- sizeAccel->setIndent(2);
-
- // effects box
- effects = new QGroupBox(q);
- QVBoxLayout *vbox = new QVBoxLayout(effects);
- strikeout = new QCheckBox(effects);
- vbox->addWidget(strikeout);
- underline = new QCheckBox(effects);
- vbox->addWidget(underline);
-
- sample = new QGroupBox(q);
- QHBoxLayout *hbox = new QHBoxLayout(sample);
- sampleEdit = new QLineEdit(sample);
- sampleEdit->setSizePolicy(QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored));
- sampleEdit->setAlignment(Qt::AlignCenter);
- // Note that the sample text is *not* translated with tr(), as the
- // characters used depend on the charset encoding.
- sampleEdit->setText(QLatin1String("AaBbYyZz"));
- hbox->addWidget(sampleEdit);
-
- writingSystemCombo = new QComboBox(q);
-
- writingSystemAccel = new QLabel(q);
-#ifndef QT_NO_SHORTCUT
- writingSystemAccel->setBuddy(writingSystemCombo);
-#endif
- writingSystemAccel->setIndent(2);
-
- size = 0;
- smoothScalable = false;
-
- QObject::connect(writingSystemCombo, SIGNAL(activated(int)), q, SLOT(_q_writingSystemHighlighted(int)));
- QObject::connect(familyList, SIGNAL(highlighted(int)), q, SLOT(_q_familyHighlighted(int)));
- QObject::connect(styleList, SIGNAL(highlighted(int)), q, SLOT(_q_styleHighlighted(int)));
- QObject::connect(sizeList, SIGNAL(highlighted(int)), q, SLOT(_q_sizeHighlighted(int)));
- QObject::connect(sizeEdit, SIGNAL(textChanged(QString)), q, SLOT(_q_sizeChanged(QString)));
-
- QObject::connect(strikeout, SIGNAL(clicked()), q, SLOT(_q_updateSample()));
- QObject::connect(underline, SIGNAL(clicked()), q, SLOT(_q_updateSample()));
-
- for (int i = 0; i < QFontDatabase::WritingSystemsCount; ++i) {
- QFontDatabase::WritingSystem ws = QFontDatabase::WritingSystem(i);
- QString writingSystemName = QFontDatabase::writingSystemName(ws);
- if (writingSystemName.isEmpty())
- break;
- writingSystemCombo->addItem(writingSystemName);
- }
-
- updateFamilies();
- if (familyList->count() != 0)
- familyList->setCurrentItem(0);
-
- // grid layout
- QGridLayout *mainGrid = new QGridLayout(q);
-
- int spacing = mainGrid->spacing();
- if (spacing >= 0) { // uniform spacing
- mainGrid->setSpacing(0);
-
- mainGrid->setColumnMinimumWidth(1, spacing);
- mainGrid->setColumnMinimumWidth(3, spacing);
-
- int margin = 0;
- mainGrid->getContentsMargins(0, 0, 0, &margin);
-
- mainGrid->setRowMinimumHeight(3, margin);
- mainGrid->setRowMinimumHeight(6, 2);
- mainGrid->setRowMinimumHeight(8, margin);
- }
-
- mainGrid->addWidget(familyAccel, 0, 0);
- mainGrid->addWidget(familyEdit, 1, 0);
- mainGrid->addWidget(familyList, 2, 0);
-
- mainGrid->addWidget(styleAccel, 0, 2);
- mainGrid->addWidget(styleEdit, 1, 2);
- mainGrid->addWidget(styleList, 2, 2);
-
- mainGrid->addWidget(sizeAccel, 0, 4);
- mainGrid->addWidget(sizeEdit, 1, 4);
- mainGrid->addWidget(sizeList, 2, 4);
-
- mainGrid->setColumnStretch(0, 38);
- mainGrid->setColumnStretch(2, 24);
- mainGrid->setColumnStretch(4, 10);
-
- mainGrid->addWidget(effects, 4, 0);
-
- mainGrid->addWidget(sample, 4, 2, 4, 3);
-
- mainGrid->addWidget(writingSystemAccel, 5, 0);
- mainGrid->addWidget(writingSystemCombo, 7, 0);
-
- buttonBox = new QDialogButtonBox(q);
- mainGrid->addWidget(buttonBox, 9, 0, 1, 5);
-
- QPushButton *button
- = static_cast<QPushButton *>(buttonBox->addButton(QDialogButtonBox::Ok));
- QObject::connect(buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
- button->setDefault(true);
-
- buttonBox->addButton(QDialogButtonBox::Cancel);
- QObject::connect(buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
-
-#if defined(Q_WS_WINCE)
- q->resize(180, 120);
-#elif defined(Q_WS_S60)
- q->resize(QApplication::desktop()->availableGeometry(QCursor::pos()).size());
-#else
- q->resize(500, 360);
-#endif // Q_WS_WINCE
-
- sizeEdit->installEventFilter(q);
- familyList->installEventFilter(q);
- styleList->installEventFilter(q);
- sizeList->installEventFilter(q);
-
- familyList->setFocus();
- retranslateStrings();
-}
-
-/*!
- \internal
- Destroys the font dialog and frees up its storage.
-*/
-
-QFontDialog::~QFontDialog()
-{
-#ifdef Q_WS_MAC
- Q_D(QFontDialog);
- if (d->delegate) {
- d->closeCocoaFontPanel();
- return;
- }
-#endif
-}
-
-/*!
- Executes a modal font dialog and returns a font.
-
- If the user clicks \gui OK, the selected font is returned. If the user
- clicks \gui Cancel, the \a initial font is returned.
-
- The dialog is constructed with the given \a parent and the options specified
- in \a options. \a title is shown as the window title of the dialog and \a
- initial is the initially selected font. If the \a ok parameter is not-null,
- the value it refers to is set to true if the user clicks \gui OK, and set to
- false if the user clicks \gui Cancel.
-
- Examples:
- \snippet doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp 2
-
- The dialog can also be used to set a widget's font directly:
- \snippet doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp 3
- In this example, if the user clicks OK the font they chose will be
- used, and if they click Cancel the original font is used.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QFontDialog constructors.
-*/
-QFont QFontDialog::getFont(bool *ok, const QFont &initial, QWidget *parent, const QString &title,
- FontDialogOptions options)
-{
- return QFontDialogPrivate::getFont(ok, initial, parent, title, options);
-}
-
-/*!
- \overload
- \since 4.5
-*/
-QFont QFontDialog::getFont(bool *ok, const QFont &initial, QWidget *parent, const QString &title)
-{
- return QFontDialogPrivate::getFont(ok, initial, parent, title, 0);
-}
-
-/*!
- \overload
-*/
-QFont QFontDialog::getFont(bool *ok, const QFont &initial, QWidget *parent)
-{
- return QFontDialogPrivate::getFont(ok, initial, parent, QString(), 0);
-}
-
-/*!
- \overload
-
- Executes a modal font dialog and returns a font.
-
- If the user clicks \gui OK, the selected font is returned. If the user
- clicks \gui Cancel, the Qt default font is returned.
-
- The dialog is constructed with the given \a parent.
- If the \a ok parameter is not-null, the value it refers to is set
- to true if the user clicks \gui OK, and false if the user clicks
- \gui Cancel.
-
- Example:
- \snippet doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp 4
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QFontDialog constructors.
-*/
-QFont QFontDialog::getFont(bool *ok, QWidget *parent)
-{
- QFont initial;
- return QFontDialogPrivate::getFont(ok, initial, parent, QString(), 0);
-}
-
-QFont QFontDialogPrivate::getFont(bool *ok, const QFont &initial, QWidget *parent,
- const QString &title, QFontDialog::FontDialogOptions options)
-{
- QFontDialog dlg(parent);
- dlg.setOptions(options);
- dlg.setCurrentFont(initial);
- if (!title.isEmpty())
- dlg.setWindowTitle(title);
-
- int ret = (dlg.exec() || (options & QFontDialog::NoButtons));
- if (ok)
- *ok = !!ret;
- if (ret) {
- return dlg.selectedFont();
- } else {
- return initial;
- }
-}
-
-/*!
- \internal
- An event filter to make the Up, Down, PageUp and PageDown keys work
- correctly in the line edits. The source of the event is the object
- \a o and the event is \a e.
-*/
-
-bool QFontDialog::eventFilter(QObject *o , QEvent *e)
-{
- Q_D(QFontDialog);
- if (e->type() == QEvent::KeyPress) {
- QKeyEvent *k = (QKeyEvent *)e;
- if (o == d->sizeEdit &&
- (k->key() == Qt::Key_Up ||
- k->key() == Qt::Key_Down ||
- k->key() == Qt::Key_PageUp ||
- k->key() == Qt::Key_PageDown)) {
-
- int ci = d->sizeList->currentItem();
- (void)QApplication::sendEvent(d->sizeList, k);
-
- if (ci != d->sizeList->currentItem()
- && style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, this))
- d->sizeEdit->selectAll();
- return true;
- } else if ((o == d->familyList || o == d->styleList) &&
- (k->key() == Qt::Key_Return || k->key() == Qt::Key_Enter)) {
- k->accept();
- accept();
- return true;
- }
- } else if (e->type() == QEvent::FocusIn
- && style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, this)) {
- if (o == d->familyList)
- d->familyEdit->selectAll();
- else if (o == d->styleList)
- d->styleEdit->selectAll();
- else if (o == d->sizeList)
- d->sizeEdit->selectAll();
- } else if (e->type() == QEvent::MouseButtonPress && o == d->sizeList) {
- d->sizeEdit->setFocus();
- }
- return QDialog::eventFilter(o, e);
-}
-
-/*
- Updates the contents of the "font family" list box. This
- function can be reimplemented if you have special requirements.
-*/
-
-void QFontDialogPrivate::updateFamilies()
-{
- Q_Q(QFontDialog);
-
- enum match_t { MATCH_NONE = 0, MATCH_LAST_RESORT = 1, MATCH_APP = 2, MATCH_FAMILY = 3 };
-
- QStringList familyNames = fdb.families(writingSystem);
-
- familyList->model()->setStringList(familyNames);
-
- QString foundryName1, familyName1, foundryName2, familyName2;
- int bestFamilyMatch = -1;
- match_t bestFamilyType = MATCH_NONE;
-
- QFont f;
-
- // ##### do the right thing for a list of family names in the font.
- QFontDatabase::parseFontName(family, foundryName1, familyName1);
-
- QStringList::const_iterator it = familyNames.constBegin();
- int i = 0;
- for(; it != familyNames.constEnd(); ++it, ++i) {
- QFontDatabase::parseFontName(*it, foundryName2, familyName2);
-
- //try to match...
- if (familyName1 == familyName2) {
- bestFamilyType = MATCH_FAMILY;
- if (foundryName1 == foundryName2) {
- bestFamilyMatch = i;
- break;
- }
- if (bestFamilyMatch < MATCH_FAMILY)
- bestFamilyMatch = i;
- }
-
- //and try some fall backs
- match_t type = MATCH_NONE;
- if (bestFamilyType <= MATCH_NONE && familyName2 == f.lastResortFamily())
- type = MATCH_LAST_RESORT;
- if (bestFamilyType <= MATCH_LAST_RESORT && familyName2 == f.family())
- type = MATCH_APP;
- // ### add fallback for writingSystem
- if (type != MATCH_NONE) {
- bestFamilyType = type;
- bestFamilyMatch = i;
- }
- }
-
- if (i != -1 && bestFamilyType != MATCH_NONE)
- familyList->setCurrentItem(bestFamilyMatch);
- else
- familyList->setCurrentItem(0);
- familyEdit->setText(familyList->currentText());
- if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
- && familyList->hasFocus())
- familyEdit->selectAll();
-
- updateStyles();
-}
-
-/*
- Updates the contents of the "font style" list box. This
- function can be reimplemented if you have special requirements.
-*/
-void QFontDialogPrivate::updateStyles()
-{
- Q_Q(QFontDialog);
- QStringList styles = fdb.styles(familyList->currentText());
- styleList->model()->setStringList(styles);
-
- if (styles.isEmpty()) {
- styleEdit->clear();
- smoothScalable = false;
- } else {
- if (!style.isEmpty()) {
- bool found = false;
- bool first = true;
- QString cstyle = style;
-
- redo:
- for (int i = 0; i < (int)styleList->count(); i++) {
- if (cstyle == styleList->text(i)) {
- styleList->setCurrentItem(i);
- found = true;
- break;
- }
- }
- if (!found && first) {
- if (cstyle.contains(QLatin1String("Italic"))) {
- cstyle.replace(QLatin1String("Italic"), QLatin1String("Oblique"));
- first = false;
- goto redo;
- } else if (cstyle.contains(QLatin1String("Oblique"))) {
- cstyle.replace(QLatin1String("Oblique"), QLatin1String("Italic"));
- first = false;
- goto redo;
- }
- }
- if (!found)
- styleList->setCurrentItem(0);
- } else {
- styleList->setCurrentItem(0);
- }
-
- styleEdit->setText(styleList->currentText());
- if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
- && styleList->hasFocus())
- styleEdit->selectAll();
-
- smoothScalable = fdb.isSmoothlyScalable(familyList->currentText(), styleList->currentText());
- }
-
- updateSizes();
-}
-
-/*!
- \internal
- Updates the contents of the "font size" list box. This
- function can be reimplemented if you have special requirements.
-*/
-
-void QFontDialogPrivate::updateSizes()
-{
- Q_Q(QFontDialog);
-
- if (!familyList->currentText().isEmpty()) {
- QList<int> sizes = fdb.pointSizes(familyList->currentText(), styleList->currentText());
-
- int i = 0;
- int current = -1;
- QStringList str_sizes;
- for(QList<int>::const_iterator it = sizes.constBegin(); it != sizes.constEnd(); ++it) {
- str_sizes.append(QString::number(*it));
- if (current == -1 && *it >= size)
- current = i;
- ++i;
- }
- sizeList->model()->setStringList(str_sizes);
- if (current == -1) {
- // we request a size bigger than the ones in the list, select the biggest one
- current = sizeList->count() - 1;
- }
- sizeList->setCurrentItem(current);
-
- sizeEdit->blockSignals(true);
- sizeEdit->setText((smoothScalable ? QString::number(size) : sizeList->currentText()));
- if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
- && sizeList->hasFocus())
- sizeEdit->selectAll();
- sizeEdit->blockSignals(false);
- } else {
- sizeEdit->clear();
- }
-
- _q_updateSample();
-}
-
-void QFontDialogPrivate::_q_updateSample()
-{
- // compute new font
- int pSize = sizeEdit->text().toInt();
- QFont newFont(fdb.font(familyList->currentText(), style, pSize));
- newFont.setStrikeOut(strikeout->isChecked());
- newFont.setUnderline(underline->isChecked());
-
- if (familyList->currentText().isEmpty())
- sampleEdit->clear();
-
- updateSampleFont(newFont);
-}
-
-void QFontDialogPrivate::updateSampleFont(const QFont &newFont)
-{
- Q_Q(QFontDialog);
- if (newFont != sampleEdit->font()) {
- sampleEdit->setFont(newFont);
- emit q->currentFontChanged(newFont);
- }
-}
-
-/*!
- \internal
-*/
-void QFontDialogPrivate::_q_writingSystemHighlighted(int index)
-{
- writingSystem = QFontDatabase::WritingSystem(index);
- sampleEdit->setText(fdb.writingSystemSample(writingSystem));
- updateFamilies();
-}
-
-/*!
- \internal
-*/
-void QFontDialogPrivate::_q_familyHighlighted(int i)
-{
- Q_Q(QFontDialog);
- family = familyList->text(i);
- familyEdit->setText(family);
- if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
- && familyList->hasFocus())
- familyEdit->selectAll();
-
- updateStyles();
-}
-
-
-/*!
- \internal
-*/
-
-void QFontDialogPrivate::_q_styleHighlighted(int index)
-{
- Q_Q(QFontDialog);
- QString s = styleList->text(index);
- styleEdit->setText(s);
- if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
- && styleList->hasFocus())
- styleEdit->selectAll();
-
- style = s;
-
- updateSizes();
-}
-
-
-/*!
- \internal
-*/
-
-void QFontDialogPrivate::_q_sizeHighlighted(int index)
-{
- Q_Q(QFontDialog);
- QString s = sizeList->text(index);
- sizeEdit->setText(s);
- if (q->style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, q)
- && sizeEdit->hasFocus())
- sizeEdit->selectAll();
-
- size = s.toInt();
- _q_updateSample();
-}
-
-/*!
- \internal
- This slot is called if the user changes the font size.
- The size is passed in the \a s argument as a \e string.
-*/
-
-void QFontDialogPrivate::_q_sizeChanged(const QString &s)
-{
- // no need to check if the conversion is valid, since we have an QIntValidator in the size edit
- int size = s.toInt();
- if (this->size == size)
- return;
-
- this->size = size;
- if (sizeList->count() != 0) {
- int i;
- for (i = 0; i < sizeList->count() - 1; i++) {
- if (sizeList->text(i).toInt() >= this->size)
- break;
- }
- sizeList->blockSignals(true);
- sizeList->setCurrentItem(i);
- sizeList->blockSignals(false);
- }
- _q_updateSample();
-}
-
-void QFontDialogPrivate::retranslateStrings()
-{
- familyAccel->setText(QFontDialog::tr("&Font"));
- styleAccel->setText(QFontDialog::tr("Font st&yle"));
- sizeAccel->setText(QFontDialog::tr("&Size"));
-#ifndef Q_WS_S60
- // Removed the title due to lack of screen estate in small S60 screen.
- // The effects are descriptive without a title (strikeout, underline).
- effects->setTitle(QFontDialog::tr("Effects"));
-#endif
- strikeout->setText(QFontDialog::tr("Stri&keout"));
- underline->setText(QFontDialog::tr("&Underline"));
- sample->setTitle(QFontDialog::tr("Sample"));
- writingSystemAccel->setText(QFontDialog::tr("Wr&iting System"));
-}
-
-/*!
- \reimp
-*/
-void QFontDialog::changeEvent(QEvent *e)
-{
- Q_D(QFontDialog);
- if (e->type() == QEvent::LanguageChange) {
- d->retranslateStrings();
- }
- QDialog::changeEvent(e);
-}
-
-/*!
- \since 4.5
-
- \property QFontDialog::currentFont
- \brief the current font of the dialog.
-*/
-
-/*!
- \since 4.5
-
- Sets the font highlighted in the QFontDialog to the given \a font.
-
- \sa selectedFont()
-*/
-void QFontDialog::setCurrentFont(const QFont &font)
-{
- Q_D(QFontDialog);
- d->family = font.family();
- d->style = d->fdb.styleString(font);
- d->size = font.pointSize();
- if (d->size == -1) {
- QFontInfo fi(font);
- d->size = fi.pointSize();
- }
- d->strikeout->setChecked(font.strikeOut());
- d->underline->setChecked(font.underline());
- d->updateFamilies();
-
-#ifdef Q_WS_MAC
- if (d->delegate)
- QFontDialogPrivate::setFont(d->delegate, font);
-#endif
-}
-
-/*!
- \since 4.5
-
- Returns the current font.
-
- \sa selectedFont()
-*/
-QFont QFontDialog::currentFont() const
-{
- Q_D(const QFontDialog);
- return d->sampleEdit->font();
-}
-
-/*!
- Returns the font that the user selected by clicking the \gui{OK}
- or equivalent button.
-
- \note This font is not always the same as the font held by the
- \l currentFont property since the user can choose different fonts
- before finally selecting the one to use.
-*/
-QFont QFontDialog::selectedFont() const
-{
- Q_D(const QFontDialog);
- return d->selectedFont;
-}
-
-/*!
- \enum QFontDialog::FontDialogOption
- \since 4.5
-
- This enum specifies various options that affect the look and feel
- of a font dialog.
-
- \value NoButtons Don't display \gui{OK} and \gui{Cancel} buttons. (Useful for "live dialogs".)
- \value DontUseNativeDialog Use Qt's standard font dialog on the Mac instead of Apple's
- native font panel. (Currently, the native dialog is never used,
- but this is likely to change in future Qt releases.)
-
- \sa options, setOption(), testOption()
-*/
-
-/*!
- Sets the given \a option to be enabled if \a on is true;
- otherwise, clears the given \a option.
-
- \sa options, testOption()
-*/
-void QFontDialog::setOption(FontDialogOption option, bool on)
-{
- Q_D(QFontDialog);
- if (!(d->opts & option) != !on)
- setOptions(d->opts ^ option);
-}
-
-/*!
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QFontDialog::testOption(FontDialogOption option) const
-{
- Q_D(const QFontDialog);
- return (d->opts & option) != 0;
-}
-
-/*!
- \property QFontDialog::options
- \brief the various options that affect the look and feel of the dialog
- \since 4.5
-
- By default, all options are disabled.
-
- Options should be set before showing the dialog. Setting them while the
- dialog is visible is not guaranteed to have an immediate effect on the
- dialog (depending on the option and on the platform).
-
- \sa setOption(), testOption()
-*/
-void QFontDialog::setOptions(FontDialogOptions options)
-{
- Q_D(QFontDialog);
-
- FontDialogOptions changed = (options ^ d->opts);
- if (!changed)
- return;
-
- d->opts = options;
- d->buttonBox->setVisible(!(options & NoButtons));
-}
-
-QFontDialog::FontDialogOptions QFontDialog::options() const
-{
- Q_D(const QFontDialog);
- return d->opts;
-}
-
-#ifdef Q_WS_MAC
-// can only have one Cocoa font panel active
-bool QFontDialogPrivate::sharedFontPanelAvailable = true;
-#endif
-
-/*!
- \since 4.5
- \overload
-
- Opens the dialog and connects its fontSelected() signal to the slot specified
- by \a receiver and \a member.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QFontDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QFontDialog);
- connect(this, SIGNAL(fontSelected(QFont)), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-/*!
- \since 4.5
-
- \fn void QFontDialog::currentFontChanged(const QFont &font)
-
- This signal is emitted when the current font is changed. The new font is
- specified in \a font.
-
- The signal is emitted while a user is selecting a font. Ultimately, the
- chosen font may differ from the font currently selected.
-
- \sa currentFont, fontSelected(), selectedFont()
-*/
-
-/*!
- \since 4.5
-
- \fn void QFontDialog::fontSelected(const QFont &font)
-
- This signal is emitted when a font has been selected. The selected font is
- specified in \a font.
-
- The signal is only emitted when a user has chosen the final font to be
- used. It is not emitted while the user is changing the current font in the
- font dialog.
-
- \sa selectedFont(), currentFontChanged(), currentFont
-*/
-
-/*!
- \reimp
-*/
-void QFontDialog::setVisible(bool visible)
-{
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden) != visible)
- return;
-#ifdef Q_WS_MAC
- Q_D(QFontDialog);
- if (d->canBeNativeDialog()){
- if (d->setVisible_sys(visible)){
- d->nativeDialogInUse = true;
- // Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
- // updates the state correctly, but skips showing the non-native version:
- setAttribute(Qt::WA_DontShowOnScreen, true);
- } else {
- d->nativeDialogInUse = false;
- setAttribute(Qt::WA_DontShowOnScreen, false);
- }
- }
-#endif // Q_WS_MAC
- QDialog::setVisible(visible);
-}
-
-/*!
- Closes the dialog and sets its result code to \a result. If this dialog
- is shown with exec(), done() causes the local event loop to finish,
- and exec() to return \a result.
-
- \sa QDialog::done()
-*/
-void QFontDialog::done(int result)
-{
- Q_D(QFontDialog);
- QDialog::done(result);
- if (result == Accepted) {
- // We check if this is the same font we had before, if so we emit currentFontChanged
- QFont selectedFont = currentFont();
- if(selectedFont != d->selectedFont)
- emit(currentFontChanged(selectedFont));
- d->selectedFont = selectedFont;
- emit fontSelected(d->selectedFont);
- } else
- d->selectedFont = QFont();
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, SIGNAL(fontSelected(QFont)),
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
-}
-
-#ifdef Q_WS_MAC
-bool QFontDialogPrivate::canBeNativeDialog()
-{
- Q_Q(QFontDialog);
- if (nativeDialogInUse)
- return true;
- if (q->testAttribute(Qt::WA_DontShowOnScreen))
- return false;
- if (opts & QFontDialog::DontUseNativeDialog)
- return false;
-
- QLatin1String staticName(QFontDialog::staticMetaObject.className());
- QLatin1String dynamicName(q->metaObject()->className());
- return (staticName == dynamicName);
-}
-#endif // Q_WS_MAC
-
-/*!
- \fn QFont QFontDialog::getFont(bool *ok, const QFont &initial, QWidget* parent, const char* name)
- \since 4.5
-
- Call getFont(\a ok, \a initial, \a parent) instead.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QFontDialog constructors.
-
- The \a name parameter is ignored.
-*/
-
-/*!
- \fn QFont QFontDialog::getFont(bool *ok, QWidget* parent, const char* name)
-
- Call getFont(\a ok, \a parent) instead.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QFontDialog constructors.
-
- The \a name parameter is ignored.
-*/
-
-QT_END_NAMESPACE
-
-#include "qfontdialog.moc"
-#include "moc_qfontdialog.cpp"
-
-#endif // QT_NO_FONTDIALOG
diff --git a/src/gui/dialogs/qfontdialog.h b/src/gui/dialogs/qfontdialog.h
deleted file mode 100644
index a09f16d0a0..0000000000
--- a/src/gui/dialogs/qfontdialog.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTDIALOG_H
-#define QFONTDIALOG_H
-
-#include <QtGui/qwindowdefs.h>
-#include <QtGui/qdialog.h>
-#include <QtGui/qfont.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_FONTDIALOG
-
-class QFontDialogPrivate;
-
-class Q_GUI_EXPORT QFontDialog : public QDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QFontDialog)
- Q_ENUMS(FontDialogOption)
- Q_PROPERTY(QFont currentFont READ currentFont WRITE setCurrentFont NOTIFY currentFontChanged)
- Q_PROPERTY(FontDialogOptions options READ options WRITE setOptions)
-
-public:
- enum FontDialogOption {
- NoButtons = 0x00000001,
- DontUseNativeDialog = 0x00000002
- };
-
- Q_DECLARE_FLAGS(FontDialogOptions, FontDialogOption)
-
- explicit QFontDialog(QWidget *parent = 0);
- explicit QFontDialog(const QFont &initial, QWidget *parent = 0);
- ~QFontDialog();
-
- void setCurrentFont(const QFont &font);
- QFont currentFont() const;
-
- QFont selectedFont() const;
-
- void setOption(FontDialogOption option, bool on = true);
- bool testOption(FontDialogOption option) const;
- void setOptions(FontDialogOptions options);
- FontDialogOptions options() const;
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
- void setVisible(bool visible);
-
- // ### Qt 5: merge overloads
- static QFont getFont(bool *ok, const QFont &initial, QWidget *parent, const QString &title,
- FontDialogOptions options);
- static QFont getFont(bool *ok, const QFont &initial, QWidget *parent, const QString &title);
- static QFont getFont(bool *ok, const QFont &initial, QWidget *parent = 0);
- static QFont getFont(bool *ok, QWidget *parent = 0);
-
-#ifdef QT3_SUPPORT
- static QFont getFont(bool *ok, const QFont &initial, QWidget *parent, const char *name)
- { Q_UNUSED(name); return getFont(ok, initial, parent); }
- static QFont getFont(bool *ok, QWidget *parent, const char *name)
- { Q_UNUSED(name); return getFont(ok, parent); }
-#endif
-
-Q_SIGNALS:
- void currentFontChanged(const QFont &font);
- void fontSelected(const QFont &font);
-
-protected:
- void changeEvent(QEvent *event);
- void done(int result);
-
-private:
- // ### Qt 5: make protected
- bool eventFilter(QObject *object, QEvent *event);
-
- Q_DISABLE_COPY(QFontDialog)
-
- Q_PRIVATE_SLOT(d_func(), void _q_sizeChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_familyHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_writingSystemHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_styleHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_sizeHighlighted(int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSample())
-#if defined(Q_WS_MAC)
- Q_PRIVATE_SLOT(d_func(), void _q_macRunNativeAppModalPanel())
-#endif
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QFontDialog::FontDialogOptions)
-
-#endif // QT_NO_FONTDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QFONTDIALOG_H
diff --git a/src/gui/dialogs/qfontdialog_mac.mm b/src/gui/dialogs/qfontdialog_mac.mm
deleted file mode 100644
index 1552ad675f..0000000000
--- a/src/gui/dialogs/qfontdialog_mac.mm
+++ /dev/null
@@ -1,699 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfontdialog_p.h"
-#if !defined(QT_NO_FONTDIALOG) && defined(Q_WS_MAC)
-#include <qapplication.h>
-#include <qdialogbuttonbox.h>
-#include <qlineedit.h>
-#include <private/qapplication_p.h>
-#include <private/qfont_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qt_mac_p.h>
-#include <qabstracteventdispatcher.h>
-#include <qdebug.h>
-#include <private/qfontengine_coretext_p.h>
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-
-#if !CGFLOAT_DEFINED
-typedef float CGFloat; // Should only not be defined on 32-bit platforms
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptNSPanelCtor();
-extern void macStopInterceptNSPanelCtor();
-extern NSButton *macCreateButton(const char *text, NSView *superview);
-extern bool qt_mac_is_macsheet(const QWidget *w); // qwidget_mac.mm
-
-QT_END_NAMESPACE
-QT_USE_NAMESPACE
-
-// should a priori be kept in sync with qcolordialog_mac.mm
-const CGFloat ButtonMinWidth = 78.0;
-const CGFloat ButtonMinHeight = 32.0;
-const CGFloat ButtonSpacing = 0.0;
-const CGFloat ButtonTopMargin = 0.0;
-const CGFloat ButtonBottomMargin = 7.0;
-const CGFloat ButtonSideMargin = 9.0;
-
-// looks better with some margins
-const CGFloat DialogTopMargin = 7.0;
-const CGFloat DialogSideMargin = 9.0;
-
-const int StyleMask = NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask;
-
-@class QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate);
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSWindowDelegate <NSObject>
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize;
-@end
-
-#endif
-
-@interface QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) : NSObject <NSWindowDelegate> {
- NSFontPanel *mFontPanel;
- NSView *mStolenContentView;
- NSButton *mOkButton;
- NSButton *mCancelButton;
- QFontDialogPrivate *mPriv;
- QFont *mQtFont;
- BOOL mPanelHackedWithButtons;
- CGFloat mDialogExtraWidth;
- CGFloat mDialogExtraHeight;
- int mReturnCode;
- BOOL mAppModal;
-}
-- (id)initWithFontPanel:(NSFontPanel *)panel
- stolenContentView:(NSView *)stolenContentView
- okButton:(NSButton *)okButton
- cancelButton:(NSButton *)cancelButton
- priv:(QFontDialogPrivate *)priv
- extraWidth:(CGFloat)extraWidth
- extraHeight:(CGFloat)extraHeight;
-- (void)showModelessPanel;
-- (void)showWindowModalSheet:(QWidget *)docWidget;
-- (void)runApplicationModalPanel;
-- (BOOL)isAppModal;
-- (void)changeFont:(id)sender;
-- (void)changeAttributes:(id)sender;
-- (BOOL)windowShouldClose:(id)window;
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize;
-- (void)relayout;
-- (void)relayoutToContentSize:(NSSize)frameSize;
-- (void)onOkClicked;
-- (void)onCancelClicked;
-- (NSFontPanel *)fontPanel;
-- (NSWindow *)actualPanel;
-- (NSSize)dialogExtraSize;
-- (void)setQtFont:(const QFont &)newFont;
-- (QFont)qtFont;
-- (void)finishOffWithCode:(NSInteger)result;
-- (void)cleanUpAfterMyself;
-- (void)setSubwindowStacking;
-@end
-
-static QFont qfontForCocoaFont(NSFont *cocoaFont, const QFont &resolveFont)
-{
- QFont newFont;
- if (cocoaFont) {
- int pSize = qRound([cocoaFont pointSize]);
- QString family(qt_mac_NSStringToQString([cocoaFont familyName]));
- QString typeface(qt_mac_NSStringToQString([cocoaFont fontName]));
-
- int hyphenPos = typeface.indexOf(QLatin1Char('-'));
- if (hyphenPos != -1) {
- typeface.remove(0, hyphenPos + 1);
- } else {
- typeface = QLatin1String("Normal");
- }
-
- newFont = QFontDatabase().font(family, typeface, pSize);
- newFont.setUnderline(resolveFont.underline());
- newFont.setStrikeOut(resolveFont.strikeOut());
-
- }
- return newFont;
-}
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate)
-- (id)initWithFontPanel:(NSFontPanel *)panel
- stolenContentView:(NSView *)stolenContentView
- okButton:(NSButton *)okButton
- cancelButton:(NSButton *)cancelButton
- priv:(QFontDialogPrivate *)priv
- extraWidth:(CGFloat)extraWidth
- extraHeight:(CGFloat)extraHeight
-{
- self = [super init];
- mFontPanel = panel;
- mStolenContentView = stolenContentView;
- mOkButton = okButton;
- mCancelButton = cancelButton;
- mPriv = priv;
- mPanelHackedWithButtons = (okButton != 0);
- mDialogExtraWidth = extraWidth;
- mDialogExtraHeight = extraHeight;
- mReturnCode = -1;
- mAppModal = false;
-
- if (mPanelHackedWithButtons) {
- [self relayout];
-
- [okButton setAction:@selector(onOkClicked)];
- [okButton setTarget:self];
-
- [cancelButton setAction:@selector(onCancelClicked)];
- [cancelButton setTarget:self];
- }
-
- mQtFont = new QFont();
- return self;
-}
-
-- (void)setSubwindowStacking
-{
-#ifdef QT_MAC_USE_COCOA
- // Stack the native dialog in front of its parent, if any:
- QFontDialog *q = mPriv->fontDialog();
- if (!qt_mac_is_macsheet(q)) {
- if (QWidget *parent = q->parentWidget()) {
- if (parent->isWindow()) {
- [qt_mac_window_for(parent)
- addChildWindow:[mStolenContentView window] ordered:NSWindowAbove];
- }
- }
- }
-#endif
-}
-
-- (void)dealloc
-{
- delete mQtFont;
- [super dealloc];
-}
-
-- (void)showModelessPanel
-{
- mAppModal = false;
- NSWindow *ourPanel = [mStolenContentView window];
- [ourPanel makeKeyAndOrderFront:self];
-}
-
-- (void)runApplicationModalPanel
-{
- QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active);
- mAppModal = true;
- NSWindow *ourPanel = [mStolenContentView window];
- [ourPanel setReleasedWhenClosed:NO];
- [NSApp runModalForWindow:ourPanel];
- QAbstractEventDispatcher::instance()->interrupt();
-
- if (mReturnCode == NSOKButton)
- mPriv->fontDialog()->accept();
- else
- mPriv->fontDialog()->reject();
-}
-
-- (BOOL)isAppModal
-{
- return mAppModal;
-}
-
-- (void)showWindowModalSheet:(QWidget *)docWidget
-{
-#ifdef QT_MAC_USE_COCOA
- NSWindow *window = qt_mac_window_for(docWidget);
-#else
- WindowRef hiwindowRef = qt_mac_window_for(docWidget);
- NSWindow *window = [[NSWindow alloc] initWithWindowRef:hiwindowRef];
- CFRetain(hiwindowRef);
-#endif
-
- mAppModal = false;
- NSWindow *ourPanel = [mStolenContentView window];
- [NSApp beginSheet:ourPanel
- modalForWindow:window
- modalDelegate:0
- didEndSelector:0
- contextInfo:0 ];
-
-#ifndef QT_MAC_USE_COCOA
- CFRelease(hiwindowRef);
-#endif
-}
-
-- (void)changeFont:(id)sender
-{
- NSFont *dummyFont = [NSFont userFontOfSize:12.0];
- [self setQtFont:qfontForCocoaFont([sender convertFont:dummyFont], *mQtFont)];
- if (mPriv)
- mPriv->updateSampleFont(*mQtFont);
-}
-
-- (void)changeAttributes:(id)sender
-{
- NSDictionary *dummyAttribs = [NSDictionary dictionary];
- NSDictionary *attribs = [sender convertAttributes:dummyAttribs];
-
-#ifdef QT_MAC_USE_COCOA
- for (id key in attribs) {
-#else
- NSEnumerator *enumerator = [attribs keyEnumerator];
- id key;
- while((key = [enumerator nextObject])) {
-#endif
- NSNumber *number = static_cast<NSNumber *>([attribs objectForKey:key]);
- if ([key isEqual:NSUnderlineStyleAttributeName]) {
- mQtFont->setUnderline([number intValue] != NSUnderlineStyleNone);
- } else if ([key isEqual:NSStrikethroughStyleAttributeName]) {
- mQtFont->setStrikeOut([number intValue] != NSUnderlineStyleNone);
- }
- }
-
- if (mPriv)
- mPriv->updateSampleFont(*mQtFont);
-}
-
-- (BOOL)windowShouldClose:(id)window
-{
- Q_UNUSED(window);
- if (mPanelHackedWithButtons) {
- [self onCancelClicked];
- } else {
- [self finishOffWithCode:NSCancelButton];
- }
- return true;
-}
-
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize
-{
- if (mFontPanel == window) {
- proposedFrameSize = [static_cast<id <NSWindowDelegate> >(mFontPanel) windowWillResize:mFontPanel toSize:proposedFrameSize];
- } else {
- /*
- Ugly hack: NSFontPanel rearranges the layout of its main
- component in windowWillResize:toSize:. So we temporarily
- restore the stolen content view to its rightful owner,
- call windowWillResize:toSize:, and steal the content view
- again.
- */
- [mStolenContentView removeFromSuperview];
- [mFontPanel setContentView:mStolenContentView];
- NSSize extraSize = [self dialogExtraSize];
- proposedFrameSize.width -= extraSize.width;
- proposedFrameSize.height -= extraSize.height;
- proposedFrameSize = [static_cast<id <NSWindowDelegate> >(mFontPanel) windowWillResize:mFontPanel toSize:proposedFrameSize];
- NSRect frameRect = { { 0.0, 0.0 }, proposedFrameSize };
- [mFontPanel setFrame:frameRect display:NO];
- [mFontPanel setContentView:0];
- [[window contentView] addSubview:mStolenContentView];
- proposedFrameSize.width += extraSize.width;
- proposedFrameSize.height += extraSize.height;
- }
- if (mPanelHackedWithButtons) {
- NSRect frameRect = { { 0.0, 0.0 }, proposedFrameSize };
- NSRect contentRect = [NSWindow contentRectForFrameRect:frameRect styleMask:[window styleMask]];
- [self relayoutToContentSize:contentRect.size];
- }
- return proposedFrameSize;
-}
-
-- (void)relayout
-{
- [self relayoutToContentSize:[[mStolenContentView superview] frame].size];
-}
-
-- (void)relayoutToContentSize:(NSSize)frameSize
-{
- Q_ASSERT(mPanelHackedWithButtons);
-
- [mOkButton sizeToFit];
- NSSize okSizeHint = [mOkButton frame].size;
-
- [mCancelButton sizeToFit];
- NSSize cancelSizeHint = [mCancelButton frame].size;
-
- const CGFloat ButtonWidth = qMin(qMax(ButtonMinWidth,
- qMax(okSizeHint.width, cancelSizeHint.width)),
- CGFloat((frameSize.width - 2.0 * ButtonSideMargin - ButtonSpacing) * 0.5));
- const CGFloat ButtonHeight = qMax(ButtonMinHeight,
- qMax(okSizeHint.height, cancelSizeHint.height));
-
- const CGFloat X = DialogSideMargin;
- const CGFloat Y = ButtonBottomMargin + ButtonHeight + ButtonTopMargin;
-
- NSRect okRect = { { frameSize.width - ButtonSideMargin - ButtonWidth,
- ButtonBottomMargin },
- { ButtonWidth, ButtonHeight } };
- [mOkButton setFrame:okRect];
- [mOkButton setNeedsDisplay:YES];
-
- NSRect cancelRect = { { okRect.origin.x - ButtonSpacing - ButtonWidth,
- ButtonBottomMargin },
- { ButtonWidth, ButtonHeight } };
- [mCancelButton setFrame:cancelRect];
- [mCancelButton setNeedsDisplay:YES];
-
- NSRect stolenCVRect = { { X, Y },
- { frameSize.width - X - X, frameSize.height - Y - DialogTopMargin } };
- [mStolenContentView setFrame:stolenCVRect];
- [mStolenContentView setNeedsDisplay:YES];
-
- [[mStolenContentView superview] setNeedsDisplay:YES];
-}
-
-- (void)onOkClicked
-{
- Q_ASSERT(mPanelHackedWithButtons);
- NSFontManager *fontManager = [NSFontManager sharedFontManager];
- [self setQtFont:qfontForCocoaFont([fontManager convertFont:[fontManager selectedFont]],
- *mQtFont)];
- [self finishOffWithCode:NSOKButton];
-}
-
-- (void)onCancelClicked
-{
- Q_ASSERT(mPanelHackedWithButtons);
- [self finishOffWithCode:NSCancelButton];
-}
-
-- (NSFontPanel *)fontPanel
-{
- return mFontPanel;
-}
-
-- (NSWindow *)actualPanel
-{
- return [mStolenContentView window];
-}
-
-- (NSSize)dialogExtraSize
-{
- // this must be recomputed each time, because sometimes the
- // NSFontPanel has the NSDocModalWindowMask flag set, and sometimes
- // not -- which affects the frame rect vs. content rect measurements
-
- // take the different frame rectangles into account for dialogExtra{Width,Height}
- NSRect someRect = { { 0.0, 0.0 }, { 100000.0, 100000.0 } };
- NSRect sharedFontPanelContentRect = [mFontPanel contentRectForFrameRect:someRect];
- NSRect ourPanelContentRect = [NSWindow contentRectForFrameRect:someRect styleMask:StyleMask];
-
- NSSize result = { mDialogExtraWidth, mDialogExtraHeight };
- result.width -= ourPanelContentRect.size.width - sharedFontPanelContentRect.size.width;
- result.height -= ourPanelContentRect.size.height - sharedFontPanelContentRect.size.height;
- return result;
-}
-
-- (void)setQtFont:(const QFont &)newFont
-{
- delete mQtFont;
- mQtFont = new QFont(newFont);
-}
-
-- (QFont)qtFont
-{
- return *mQtFont;
-}
-
-- (void)finishOffWithCode:(NSInteger)code
-{
-#ifdef QT_MAC_USE_COCOA
- QFontDialog *q = mPriv->fontDialog();
- if (QWidget *parent = q->parentWidget()) {
- if (parent->isWindow()) {
- [qt_mac_window_for(parent) removeChildWindow:[mStolenContentView window]];
- }
- }
-#endif
-
- if(code == NSOKButton)
- mPriv->sampleEdit->setFont([self qtFont]);
-
- if (mAppModal) {
- mReturnCode = code;
- [NSApp stopModalWithCode:code];
- } else {
- if (code == NSOKButton)
- mPriv->fontDialog()->accept();
- else
- mPriv->fontDialog()->reject();
- }
-}
-
-- (void)cleanUpAfterMyself
-{
- if (mPanelHackedWithButtons) {
- NSView *ourContentView = [mFontPanel contentView];
-
- // return stolen stuff to its rightful owner
- [mStolenContentView removeFromSuperview];
- [mFontPanel setContentView:mStolenContentView];
-
- [mOkButton release];
- [mCancelButton release];
- [ourContentView release];
- }
- [mFontPanel setDelegate:nil];
- [[NSFontManager sharedFontManager] setDelegate:nil];
-#ifdef QT_MAC_USE_COCOA
- [[NSFontManager sharedFontManager] setTarget:nil];
-#endif
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-void QFontDialogPrivate::closeCocoaFontPanel()
-{
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *theDelegate = static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate);
- NSWindow *ourPanel = [theDelegate actualPanel];
- [ourPanel close];
- if ([theDelegate isAppModal])
- [ourPanel release];
- [theDelegate cleanUpAfterMyself];
- [theDelegate release];
- this->delegate = 0;
- sharedFontPanelAvailable = true;
-}
-
-void QFontDialogPrivate::setFont(void *delegate, const QFont &font)
-{
- QMacCocoaAutoReleasePool pool;
- QFontEngine *fe = font.d->engineForScript(QUnicodeTables::Common);
- NSFontManager *mgr = [NSFontManager sharedFontManager];
- const NSFont *nsFont = 0;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
- if (qstrcmp(fe->name(), "CoreText") == 0) {
- nsFont = reinterpret_cast<const NSFont *>(static_cast<QCoreTextFontEngineMulti *>(fe)->ctfont);
- } else
-#endif
- {
- int weight = 5;
- NSFontTraitMask mask = 0;
- if (font.style() == QFont::StyleItalic) {
- mask |= NSItalicFontMask;
- }
- if (font.weight() == QFont::Bold) {
- weight = 9;
- mask |= NSBoldFontMask;
- }
-
- NSFontManager *mgr = [NSFontManager sharedFontManager];
- QFontInfo fontInfo(font);
- nsFont = [mgr fontWithFamily:qt_mac_QStringToNSString(fontInfo.family())
- traits:mask
- weight:weight
- size:fontInfo.pointSize()];
- }
-
- [mgr setSelectedFont:const_cast<NSFont *>(nsFont) isMultiple:NO];
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate) setQtFont:font];
-}
-
-void QFontDialogPrivate::createNSFontPanelDelegate()
-{
- if (delegate)
- return;
-
- sharedFontPanelAvailable = false;
- QMacCocoaAutoReleasePool pool;
- bool sharedFontPanelExisted = [NSFontPanel sharedFontPanelExists];
- NSFontPanel *sharedFontPanel = [NSFontPanel sharedFontPanel];
- [sharedFontPanel setHidesOnDeactivate:false];
-
- // hack to ensure that QCocoaApplication's validModesForFontPanel:
- // implementation is honored
- if (!sharedFontPanelExisted) {
- [sharedFontPanel makeKeyAndOrderFront:sharedFontPanel];
- [sharedFontPanel close];
- }
-
- NSPanel *ourPanel = 0;
- NSView *stolenContentView = 0;
- NSButton *okButton = 0;
- NSButton *cancelButton = 0;
-
- CGFloat dialogExtraWidth = 0.0;
- CGFloat dialogExtraHeight = 0.0;
-
- // compute dialogExtra{Width,Height}
- dialogExtraWidth = 2.0 * DialogSideMargin;
- dialogExtraHeight = DialogTopMargin + ButtonTopMargin + ButtonMinHeight + ButtonBottomMargin;
-
- // compute initial contents rectangle
- NSRect contentRect = [sharedFontPanel contentRectForFrameRect:[sharedFontPanel frame]];
- contentRect.size.width += dialogExtraWidth;
- contentRect.size.height += dialogExtraHeight;
-
- // create the new panel
- ourPanel = [[NSPanel alloc] initWithContentRect:contentRect
- styleMask:StyleMask
- backing:NSBackingStoreBuffered
- defer:YES];
- [ourPanel setReleasedWhenClosed:YES];
- stolenContentView = [sharedFontPanel contentView];
-
- // steal the font panel's contents view
- [stolenContentView retain];
- [sharedFontPanel setContentView:0];
-
- {
- // create a new content view and add the stolen one as a subview
- NSRect frameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } };
- NSView *ourContentView = [[NSView alloc] initWithFrame:frameRect];
- [ourContentView addSubview:stolenContentView];
-
- // create OK and Cancel buttons and add these as subviews
- okButton = macCreateButton("&OK", ourContentView);
- cancelButton = macCreateButton("Cancel", ourContentView);
-
- [ourPanel setContentView:ourContentView];
- [ourPanel setDefaultButtonCell:[okButton cell]];
- }
-
- // create the delegate and set it
- QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *del = [[QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) alloc] initWithFontPanel:sharedFontPanel
- stolenContentView:stolenContentView
- okButton:okButton
- cancelButton:cancelButton
- priv:this
- extraWidth:dialogExtraWidth
- extraHeight:dialogExtraHeight];
- delegate = del;
- [ourPanel setDelegate:del];
-
- [[NSFontManager sharedFontManager] setDelegate:del];
-#ifdef QT_MAC_USE_COCOA
- [[NSFontManager sharedFontManager] setTarget:del];
-#endif
- setFont(del, q_func()->currentFont());
-
- {
- // hack to get correct initial layout
- NSRect frameRect = [ourPanel frame];
- frameRect.size.width += 1.0;
- [ourPanel setFrame:frameRect display:NO];
- frameRect.size.width -= 1.0;
- frameRect.size = [del windowWillResize:ourPanel toSize:frameRect.size];
- [ourPanel setFrame:frameRect display:NO];
- [ourPanel center];
- }
- [del setSubwindowStacking];
- NSString *title = @"Select font";
- [ourPanel setTitle:title];
-}
-
-void QFontDialogPrivate::mac_nativeDialogModalHelp()
-{
- // Copied from QFileDialogPrivate
- // Do a queued meta-call to open the native modal dialog so it opens after the new
- // event loop has started to execute (in QDialog::exec). Using a timer rather than
- // a queued meta call is intentional to ensure that the call is only delivered when
- // [NSApp run] runs (timers are handeled special in cocoa). If NSApp is not
- // running (which is the case if e.g a top-most QEventLoop has been
- // interrupted, and the second-most event loop has not yet been reactivated (regardless
- // if [NSApp run] is still on the stack)), showing a native modal dialog will fail.
- if (nativeDialogInUse) {
- Q_Q(QFontDialog);
- QTimer::singleShot(1, q, SLOT(_q_macRunNativeAppModalPanel()));
- }
-}
-
-// The problem with the native font dialog is that OS X does not
-// offer a proper dialog, but a panel (i.e. without Ok and Cancel buttons).
-// This means we need to "construct" a native dialog by taking the panel
-// and "adding" the buttons.
-void QFontDialogPrivate::_q_macRunNativeAppModalPanel()
-{
- createNSFontPanelDelegate();
- QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *del = static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate);
- [del runApplicationModalPanel];
-}
-
-bool QFontDialogPrivate::showCocoaFontPanel()
-{
- if (!sharedFontPanelAvailable)
- return false;
-
- Q_Q(QFontDialog);
- QMacCocoaAutoReleasePool pool;
- createNSFontPanelDelegate();
- QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *del = static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate);
- if (qt_mac_is_macsheet(q))
- [del showWindowModalSheet:q->parentWidget()];
- else
- [del showModelessPanel];
- return true;
-}
-
-bool QFontDialogPrivate::hideCocoaFontPanel()
-{
- if (!delegate){
- // Nothing to do. We return false to leave the question
- // open regarding whether or not to go native:
- return false;
- } else {
- closeCocoaFontPanel();
- // Even when we hide it, we are still using a
- // native dialog, so return true:
- return true;
- }
-}
-bool QFontDialogPrivate::setVisible_sys(bool visible)
-{
- Q_Q(QFontDialog);
- if (!visible == q->isHidden())
- return false;
-
- return visible ? showCocoaFontPanel() : hideCocoaFontPanel();
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qfontdialog_p.h b/src/gui/dialogs/qfontdialog_p.h
deleted file mode 100644
index 3179b89af7..0000000000
--- a/src/gui/dialogs/qfontdialog_p.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTDIALOG_P_H
-#define QFONTDIALOG_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include "private/qdialog_p.h"
-#include "qfontdatabase.h"
-#include "qfontdialog.h"
-
-#ifndef QT_NO_FONTDIALOG
-
-QT_BEGIN_NAMESPACE
-
-class QBoxLayout;
-class QCheckBox;
-class QComboBox;
-class QDialogButtonBox;
-class QFontListView;
-class QGroupBox;
-class QLabel;
-class QLineEdit;
-
-class QFontDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QFontDialog)
-
-public:
- inline QFontDialogPrivate()
- : writingSystem(QFontDatabase::Any)
- { }
-
- void updateFamilies();
- void updateStyles();
- void updateSizes();
-
- static QFont getFont(bool *ok, const QFont &initial, QWidget *parent,
- const QString &title, QFontDialog::FontDialogOptions options);
-
- void init();
- void _q_sizeChanged(const QString &);
- void _q_familyHighlighted(int);
- void _q_writingSystemHighlighted(int);
- void _q_styleHighlighted(int);
- void _q_sizeHighlighted(int);
- void _q_updateSample();
- void updateSampleFont(const QFont &newFont);
- void retranslateStrings();
-
- QLabel *familyAccel;
- QLineEdit *familyEdit;
- QFontListView *familyList;
-
- QLabel *styleAccel;
- QLineEdit *styleEdit;
- QFontListView *styleList;
-
- QLabel *sizeAccel;
- QLineEdit *sizeEdit;
- QFontListView *sizeList;
-
- QGroupBox *effects;
- QCheckBox *strikeout;
- QCheckBox *underline;
- QComboBox *color;
-
- QGroupBox *sample;
- QLineEdit *sampleEdit;
-
- QLabel *writingSystemAccel;
- QComboBox *writingSystemCombo;
-
- QBoxLayout *buttonLayout;
- QBoxLayout *effectsLayout;
- QBoxLayout *sampleLayout;
- QBoxLayout *sampleEditLayout;
-
- QDialogButtonBox *buttonBox;
-
- QFontDatabase fdb;
- QString family;
- QFontDatabase::WritingSystem writingSystem;
- QString style;
- int size;
- bool smoothScalable;
- QFont selectedFont;
- QFontDialog::FontDialogOptions opts;
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-
-#ifdef Q_WS_MAC
- static void setFont(void *delegate, const QFont &font);
-
- inline void done(int result) { q_func()->done(result); }
- inline QFontDialog *fontDialog() { return q_func(); }
-
- void *delegate;
- void closeCocoaFontPanel();
- bool nativeDialogInUse;
- bool canBeNativeDialog();
- bool setVisible_sys(bool visible);
- void createNSFontPanelDelegate();
- void _q_macRunNativeAppModalPanel();
- void mac_nativeDialogModalHelp();
- bool showCocoaFontPanel();
- bool hideCocoaFontPanel();
-
- static bool sharedFontPanelAvailable;
-#endif
-};
-
-#endif // QT_NO_FONTDIALOG
-
-QT_END_NAMESPACE
-
-#endif // QFONTDIALOG_P_H
diff --git a/src/gui/dialogs/qfscompleter_p.h b/src/gui/dialogs/qfscompleter_p.h
deleted file mode 100644
index 26a6698a6c..0000000000
--- a/src/gui/dialogs/qfscompleter_p.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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 QFSCOMPLETOR_P_H
-#define QFSCOMPLETOR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qcompleter.h"
-#include <QtGui/qfilesystemmodel.h>
-QT_BEGIN_NAMESPACE
-#ifndef QT_NO_FSCOMPLETER
-
-/*!
- QCompleter that can deal with QFileSystemModel
- */
-class QFSCompleter : public QCompleter {
-public:
- QFSCompleter(QFileSystemModel *model, QObject *parent = 0)
- : QCompleter(model, parent), proxyModel(0), sourceModel(model)
- {
-#if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
- setCaseSensitivity(Qt::CaseInsensitive);
-#endif
- }
- QString pathFromIndex(const QModelIndex &index) const;
- QStringList splitPath(const QString& path) const;
-
- QAbstractProxyModel *proxyModel;
- QFileSystemModel *sourceModel;
-};
-#endif // QT_NO_FSCOMPLETER
-QT_END_NAMESPACE
-#endif // QFSCOMPLETOR_P_H
-
diff --git a/src/gui/dialogs/qinputdialog.cpp b/src/gui/dialogs/qinputdialog.cpp
deleted file mode 100644
index f13b8f55c3..0000000000
--- a/src/gui/dialogs/qinputdialog.cpp
+++ /dev/null
@@ -1,1489 +0,0 @@
-/****************************************************************************
-**
-** 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 "qinputdialog.h"
-
-#ifndef QT_NO_INPUTDIALOG
-
-#include "qapplication.h"
-#include "qcombobox.h"
-#include "qdialogbuttonbox.h"
-#include "qlabel.h"
-#include "qlayout.h"
-#include "qlineedit.h"
-#include "qlistwidget.h"
-#include "qpushbutton.h"
-#include "qspinbox.h"
-#include "qstackedlayout.h"
-#include "qvalidator.h"
-#include "qevent.h"
-#include "qdialog_p.h"
-
-QT_USE_NAMESPACE
-
-static const char *signalForMember(const char *member)
-{
- static const int NumCandidates = 4;
- static const char * const candidateSignals[NumCandidates] = {
- SIGNAL(textValueSelected(QString)),
- SIGNAL(intValueSelected(int)),
- SIGNAL(doubleValueSelected(double)),
- SIGNAL(accepted())
- };
-
- QByteArray normalizedMember(QMetaObject::normalizedSignature(member));
-
- int i = 0;
- while (i < NumCandidates - 1) { // sic
- if (QMetaObject::checkConnectArgs(candidateSignals[i], normalizedMember))
- break;
- ++i;
- }
- return candidateSignals[i];
-}
-
-QT_BEGIN_NAMESPACE
-
-/*
- These internal classes add extra validation to QSpinBox and QDoubleSpinBox by emitting
- textChanged(bool) after events that may potentially change the visible text. Return or
- Enter key presses are not propagated if the visible text is invalid. Instead, the visible
- text is modified to the last valid value.
-*/
-class QInputDialogSpinBox : public QSpinBox
-{
- Q_OBJECT
-
-public:
- QInputDialogSpinBox(QWidget *parent)
- : QSpinBox(parent) {
- connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(notifyTextChanged()));
- connect(this, SIGNAL(editingFinished()), this, SLOT(notifyTextChanged()));
- }
-
-signals:
- void textChanged(bool);
-
-private slots:
- void notifyTextChanged() { emit textChanged(hasAcceptableInput()); }
-
-private:
- void keyPressEvent(QKeyEvent *event) {
- if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && !hasAcceptableInput()) {
-#ifndef QT_NO_PROPERTIES
- setProperty("value", property("value"));
-#endif
- } else {
- QSpinBox::keyPressEvent(event);
- }
- notifyTextChanged();
- }
-
- void mousePressEvent(QMouseEvent *event) {
- QSpinBox::mousePressEvent(event);
- notifyTextChanged();
- }
-};
-
-class QInputDialogDoubleSpinBox : public QDoubleSpinBox
-{
- Q_OBJECT
-
-public:
- QInputDialogDoubleSpinBox(QWidget *parent = 0)
- : QDoubleSpinBox(parent) {
- connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(notifyTextChanged()));
- connect(this, SIGNAL(editingFinished()), this, SLOT(notifyTextChanged()));
- }
-
-signals:
- void textChanged(bool);
-
-private slots:
- void notifyTextChanged() { emit textChanged(hasAcceptableInput()); }
-
-private:
- void keyPressEvent(QKeyEvent *event) {
- if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && !hasAcceptableInput()) {
-#ifndef QT_NO_PROPERTIES
- setProperty("value", property("value"));
-#endif
- } else {
- QDoubleSpinBox::keyPressEvent(event);
- }
- notifyTextChanged();
- }
-
- void mousePressEvent(QMouseEvent *event) {
- QDoubleSpinBox::mousePressEvent(event);
- notifyTextChanged();
- }
-};
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qinputdialog.moc"
-QT_END_INCLUDE_NAMESPACE
-
-class QInputDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QInputDialog)
-
-public:
- QInputDialogPrivate();
-
- void ensureLayout();
- void ensureLineEdit();
- void ensureComboBox();
- void ensureListView();
- void ensureIntSpinBox();
- void ensureDoubleSpinBox();
- void ensureEnabledConnection(QAbstractSpinBox *spinBox);
- void setInputWidget(QWidget *widget);
- void chooseRightTextInputWidget();
- void setComboBoxText(const QString &text);
- void setListViewText(const QString &text);
- QString listViewText() const;
- void ensureLayout() const { const_cast<QInputDialogPrivate *>(this)->ensureLayout(); }
- bool useComboBoxOrListView() const { return comboBox && comboBox->count() > 0; }
- void _q_textChanged(const QString &text);
- void _q_currentRowChanged(const QModelIndex &newIndex, const QModelIndex &oldIndex);
-
- mutable QLabel *label;
- mutable QDialogButtonBox *buttonBox;
- mutable QLineEdit *lineEdit;
- mutable QSpinBox *intSpinBox;
- mutable QDoubleSpinBox *doubleSpinBox;
- mutable QComboBox *comboBox;
- mutable QListView *listView;
- mutable QWidget *inputWidget;
- mutable QVBoxLayout *mainLayout;
- QInputDialog::InputDialogOptions opts;
- QString textValue;
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-};
-
-QInputDialogPrivate::QInputDialogPrivate()
- : label(0), buttonBox(0), lineEdit(0), intSpinBox(0), doubleSpinBox(0), comboBox(0), listView(0),
- inputWidget(0), mainLayout(0)
-{
-}
-
-void QInputDialogPrivate::ensureLayout()
-{
- Q_Q(QInputDialog);
-
- if (mainLayout)
- return;
-
- if (!inputWidget) {
- ensureLineEdit();
- inputWidget = lineEdit;
- }
-
- if (!label)
- label = new QLabel(QInputDialog::tr("Enter a value:"), q);
-#ifndef QT_NO_SHORTCUT
- label->setBuddy(inputWidget);
-#endif
- label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
-
- buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, q);
- QObject::connect(buttonBox, SIGNAL(accepted()), q, SLOT(accept()));
- QObject::connect(buttonBox, SIGNAL(rejected()), q, SLOT(reject()));
-
- mainLayout = new QVBoxLayout(q);
- //we want to let the input dialog grow to available size on Symbian.
-#ifndef Q_OS_SYMBIAN
- mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
-#else
- label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
-#endif
- mainLayout->addWidget(label);
- mainLayout->addWidget(inputWidget);
- mainLayout->addWidget(buttonBox);
- ensureEnabledConnection(qobject_cast<QAbstractSpinBox *>(inputWidget));
- inputWidget->show();
-}
-
-void QInputDialogPrivate::ensureLineEdit()
-{
- Q_Q(QInputDialog);
- if (!lineEdit) {
- lineEdit = new QLineEdit(q);
-#ifndef QT_NO_IM
- qt_widget_private(lineEdit)->inheritsInputMethodHints = 1;
-#endif
- lineEdit->hide();
- QObject::connect(lineEdit, SIGNAL(textChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
- }
-}
-
-void QInputDialogPrivate::ensureComboBox()
-{
- Q_Q(QInputDialog);
- if (!comboBox) {
- comboBox = new QComboBox(q);
-#ifndef QT_NO_IM
- qt_widget_private(comboBox)->inheritsInputMethodHints = 1;
-#endif
- comboBox->hide();
- QObject::connect(comboBox, SIGNAL(editTextChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
- QObject::connect(comboBox, SIGNAL(currentIndexChanged(QString)),
- q, SLOT(_q_textChanged(QString)));
- }
-}
-
-void QInputDialogPrivate::ensureListView()
-{
- Q_Q(QInputDialog);
- if (!listView) {
- ensureComboBox();
-
- listView = new QListView(q);
- listView->hide();
- listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
- listView->setSelectionMode(QAbstractItemView::SingleSelection);
- listView->setModel(comboBox->model());
- listView->setCurrentIndex(QModelIndex()); // ###
- QObject::connect(listView->selectionModel(),
- SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_currentRowChanged(QModelIndex,QModelIndex)));
- }
-}
-
-void QInputDialogPrivate::ensureIntSpinBox()
-{
- Q_Q(QInputDialog);
- if (!intSpinBox) {
- intSpinBox = new QInputDialogSpinBox(q);
- intSpinBox->hide();
- QObject::connect(intSpinBox, SIGNAL(valueChanged(int)),
- q, SIGNAL(intValueChanged(int)));
- }
-}
-
-void QInputDialogPrivate::ensureDoubleSpinBox()
-{
- Q_Q(QInputDialog);
- if (!doubleSpinBox) {
- doubleSpinBox = new QInputDialogDoubleSpinBox(q);
- doubleSpinBox->hide();
- QObject::connect(doubleSpinBox, SIGNAL(valueChanged(double)),
- q, SIGNAL(doubleValueChanged(double)));
- }
-}
-
-void QInputDialogPrivate::ensureEnabledConnection(QAbstractSpinBox *spinBox)
-{
- if (spinBox) {
- QAbstractButton *okButton = buttonBox->button(QDialogButtonBox::Ok);
- QObject::connect(spinBox, SIGNAL(textChanged(bool)), okButton, SLOT(setEnabled(bool)), Qt::UniqueConnection);
- }
-}
-
-void QInputDialogPrivate::setInputWidget(QWidget *widget)
-{
- Q_ASSERT(widget);
- if (inputWidget == widget)
- return;
-
- if (mainLayout) {
- Q_ASSERT(inputWidget);
- mainLayout->removeWidget(inputWidget);
- inputWidget->hide();
- mainLayout->insertWidget(1, widget);
- widget->show();
-
- // disconnect old input widget
- QAbstractButton *okButton = buttonBox->button(QDialogButtonBox::Ok);
- if (QAbstractSpinBox *spinBox = qobject_cast<QAbstractSpinBox *>(inputWidget))
- QObject::disconnect(spinBox, SIGNAL(textChanged(bool)), okButton, SLOT(setEnabled(bool)));
-
- // connect new input widget and update enabled state of OK button
- QAbstractSpinBox *spinBox = qobject_cast<QAbstractSpinBox *>(widget);
- ensureEnabledConnection(spinBox);
- okButton->setEnabled(!spinBox || spinBox->hasAcceptableInput());
- }
-
- inputWidget = widget;
-
- // synchronize the text shown in the new text editor with the current
- // textValue
- if (widget == lineEdit) {
- lineEdit->setText(textValue);
- } else if (widget == comboBox) {
- setComboBoxText(textValue);
- } else if (widget == listView) {
- setListViewText(textValue);
- ensureLayout();
- buttonBox->button(QDialogButtonBox::Ok)->setEnabled(listView->selectionModel()->hasSelection());
- }
-}
-
-void QInputDialogPrivate::chooseRightTextInputWidget()
-{
- QWidget *widget;
-
- if (useComboBoxOrListView()) {
- if ((opts & QInputDialog::UseListViewForComboBoxItems) && !comboBox->isEditable()) {
- ensureListView();
- widget = listView;
- } else {
- widget = comboBox;
- }
- } else {
- ensureLineEdit();
- widget = lineEdit;
- }
-
- setInputWidget(widget);
-
- if (inputWidget == comboBox) {
- _q_textChanged(comboBox->currentText());
- } else if (inputWidget == listView) {
- _q_textChanged(listViewText());
- }
-}
-
-void QInputDialogPrivate::setComboBoxText(const QString &text)
-{
- int index = comboBox->findText(text);
- if (index != -1) {
- comboBox->setCurrentIndex(index);
- } else if (comboBox->isEditable()) {
- comboBox->setEditText(text);
- }
-}
-
-void QInputDialogPrivate::setListViewText(const QString &text)
-{
- int row = comboBox->findText(text);
- if (row != -1) {
- QModelIndex index(comboBox->model()->index(row, 0));
- listView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Clear
- | QItemSelectionModel::SelectCurrent);
- }
-}
-
-QString QInputDialogPrivate::listViewText() const
-{
- if (listView->selectionModel()->hasSelection()) {
- int row = listView->selectionModel()->selectedRows().value(0).row();
- return comboBox->itemText(row);
- } else {
- return QString();
- }
-}
-
-void QInputDialogPrivate::_q_textChanged(const QString &text)
-{
- Q_Q(QInputDialog);
- if (textValue != text) {
- textValue = text;
- emit q->textValueChanged(text);
- }
-}
-
-void QInputDialogPrivate::_q_currentRowChanged(const QModelIndex &newIndex,
- const QModelIndex & /* oldIndex */)
-{
- _q_textChanged(comboBox->model()->data(newIndex).toString());
- buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
-}
-
-/*!
- \class QInputDialog
- \brief The QInputDialog class provides a simple convenience dialog to get a
- single value from the user.
- \ingroup standard-dialogs
-
-
- The input value can be a string, a number or an item from a list. A label
- must be set to tell the user what they should enter.
-
- Four static convenience functions are provided: getText(), getInt(),
- getDouble(), and getItem(). All the functions can be used in a similar way,
- for example:
-
- \snippet examples/dialogs/standarddialogs/dialog.cpp 3
-
- The \c ok variable is set to true if the user clicks \gui OK; otherwise it
- is set to false.
-
- \img inputdialogs.png Input Dialogs
-
- The \l{dialogs/standarddialogs}{Standard Dialogs} example shows how to use
- QInputDialog as well as other built-in Qt dialogs.
-
- \sa QMessageBox, {Standard Dialogs Example}
-*/
-
-/*!
- \enum QInputDialog::InputMode
- \since 4.5
-
- This enum describes the different modes of input that can be selected for
- the dialog.
-
- \value TextInput Used to input text strings.
- \value IntInput Used to input integers.
- \value DoubleInput Used to input floating point numbers with double
- precision accuracy.
-
- \sa inputMode
-*/
-
-/*!
- \since 4.5
-
- Constructs a new input dialog with the given \a parent and window \a flags.
-*/
-QInputDialog::QInputDialog(QWidget *parent, Qt::WindowFlags flags)
- : QDialog(*new QInputDialogPrivate, parent, flags)
-{
-}
-
-/*!
- \since 4.5
-
- Destroys the input dialog.
-*/
-QInputDialog::~QInputDialog()
-{
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::inputMode
-
- \brief the mode used for input
-
- This property help determines which widget is used for entering input into
- the dialog.
-*/
-void QInputDialog::setInputMode(InputMode mode)
-{
- Q_D(QInputDialog);
-
- QWidget *widget;
-
- /*
- Warning: Some functions in QInputDialog rely on implementation details
- of the code below. Look for the comments that accompany the calls to
- setInputMode() throughout this file before you change the code below.
- */
-
- switch (mode) {
- case IntInput:
- d->ensureIntSpinBox();
- widget = d->intSpinBox;
- break;
- case DoubleInput:
- d->ensureDoubleSpinBox();
- widget = d->doubleSpinBox;
- break;
- default:
- Q_ASSERT(mode == TextInput);
- d->chooseRightTextInputWidget();
- return;
- }
-
- d->setInputWidget(widget);
-}
-
-QInputDialog::InputMode QInputDialog::inputMode() const
-{
- Q_D(const QInputDialog);
-
- if (d->inputWidget) {
- if (d->inputWidget == d->intSpinBox) {
- return IntInput;
- } else if (d->inputWidget == d->doubleSpinBox) {
- return DoubleInput;
- }
- }
-
- return TextInput;
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::labelText
-
- \brief the text to for the label to describe what needs to be input
-*/
-void QInputDialog::setLabelText(const QString &text)
-{
- Q_D(QInputDialog);
- if (!d->label) {
- d->label = new QLabel(text, this);
- } else {
- d->label->setText(text);
- }
-#ifdef Q_OS_SYMBIAN
- d->label->setWordWrap(true);
-#endif
-}
-
-QString QInputDialog::labelText() const
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- return d->label->text();
-}
-
-/*!
- \enum QInputDialog::InputDialogOption
-
- \since 4.5
-
- This enum specifies various options that affect the look and feel
- of an input dialog.
-
- \value NoButtons Don't display \gui{OK} and \gui{Cancel} buttons. (Useful for "live dialogs".)
- \value UseListViewForComboBoxItems Use a QListView rather than a non-editable QComboBox for
- displaying the items set with setComboBoxItems().
-
- \sa options, setOption(), testOption()
-*/
-
-/*!
- Sets the given \a option to be enabled if \a on is true;
- otherwise, clears the given \a option.
-
- \sa options, testOption()
-*/
-void QInputDialog::setOption(InputDialogOption option, bool on)
-{
- Q_D(QInputDialog);
- if (!(d->opts & option) != !on)
- setOptions(d->opts ^ option);
-}
-
-/*!
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QInputDialog::testOption(InputDialogOption option) const
-{
- Q_D(const QInputDialog);
- return (d->opts & option) != 0;
-}
-
-/*!
- \property QInputDialog::options
- \brief the various options that affect the look and feel of the dialog
- \since 4.5
-
- By default, all options are disabled.
-
- \sa setOption(), testOption()
-*/
-void QInputDialog::setOptions(InputDialogOptions options)
-{
- Q_D(QInputDialog);
-
- InputDialogOptions changed = (options ^ d->opts);
- if (!changed)
- return;
-
- d->opts = options;
- d->ensureLayout();
-
- if (changed & NoButtons)
- d->buttonBox->setVisible(!(options & NoButtons));
- if ((changed & UseListViewForComboBoxItems) && inputMode() == TextInput)
- d->chooseRightTextInputWidget();
-}
-
-QInputDialog::InputDialogOptions QInputDialog::options() const
-{
- Q_D(const QInputDialog);
- return d->opts;
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::textValue
-
- \brief the text value for the input dialog
-
- This property is only relevant when the input dialog is used in
- TextInput mode.
-*/
-void QInputDialog::setTextValue(const QString &text)
-{
- Q_D(QInputDialog);
-
- setInputMode(TextInput);
- if (d->inputWidget == d->lineEdit) {
- d->lineEdit->setText(text);
- } else if (d->inputWidget == d->comboBox) {
- d->setComboBoxText(text);
- } else {
- d->setListViewText(text);
- }
-}
-
-QString QInputDialog::textValue() const
-{
- Q_D(const QInputDialog);
- return d->textValue;
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::textEchoMode
-
- \brief the echo mode for the text value
-
- This property is only relevant when the input dialog is used in
- TextInput mode.
-*/
-void QInputDialog::setTextEchoMode(QLineEdit::EchoMode mode)
-{
- Q_D(QInputDialog);
- d->ensureLineEdit();
- d->lineEdit->setEchoMode(mode);
-}
-
-QLineEdit::EchoMode QInputDialog::textEchoMode() const
-{
- Q_D(const QInputDialog);
- if (d->lineEdit) {
- return d->lineEdit->echoMode();
- } else {
- return QLineEdit::Normal;
- }
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::comboBoxEditable
-
- \brief whether or not the combo box is used in the input dialog is editable
-*/
-void QInputDialog::setComboBoxEditable(bool editable)
-{
- Q_D(QInputDialog);
- d->ensureComboBox();
- d->comboBox->setEditable(editable);
- if (inputMode() == TextInput)
- d->chooseRightTextInputWidget();
-}
-
-bool QInputDialog::isComboBoxEditable() const
-{
- Q_D(const QInputDialog);
- if (d->comboBox) {
- return d->comboBox->isEditable();
- } else {
- return false;
- }
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::comboBoxItems
-
- \brief the items used in the combobox for the input dialog
-*/
-void QInputDialog::setComboBoxItems(const QStringList &items)
-{
- Q_D(QInputDialog);
-
- d->ensureComboBox();
- d->comboBox->blockSignals(true);
- d->comboBox->clear();
- d->comboBox->addItems(items);
- d->comboBox->blockSignals(false);
-
- if (inputMode() == TextInput)
- d->chooseRightTextInputWidget();
-}
-
-QStringList QInputDialog::comboBoxItems() const
-{
- Q_D(const QInputDialog);
- QStringList result;
- if (d->comboBox) {
- const int count = d->comboBox->count();
- for (int i = 0; i < count; ++i)
- result.append(d->comboBox->itemText(i));
- }
- return result;
-}
-
-/*!
- \property QInputDialog::intValue
- \since 4.5
- \brief the current integer value accepted as input
-
- This property is only relevant when the input dialog is used in
- IntInput mode.
-*/
-void QInputDialog::setIntValue(int value)
-{
- Q_D(QInputDialog);
- setInputMode(IntInput);
- d->intSpinBox->setValue(value);
-}
-
-int QInputDialog::intValue() const
-{
- Q_D(const QInputDialog);
- if (d->intSpinBox) {
- return d->intSpinBox->value();
- } else {
- return 0;
- }
-}
-
-/*!
- \property QInputDialog::intMinimum
- \since 4.5
- \brief the minimum integer value accepted as input
-
- This property is only relevant when the input dialog is used in
- IntInput mode.
-*/
-void QInputDialog::setIntMinimum(int min)
-{
- Q_D(QInputDialog);
- d->ensureIntSpinBox();
- d->intSpinBox->setMinimum(min);
-}
-
-int QInputDialog::intMinimum() const
-{
- Q_D(const QInputDialog);
- if (d->intSpinBox) {
- return d->intSpinBox->minimum();
- } else {
- return 0;
- }
-}
-
-/*!
- \property QInputDialog::intMaximum
- \since 4.5
- \brief the maximum integer value accepted as input
-
- This property is only relevant when the input dialog is used in
- IntInput mode.
-*/
-void QInputDialog::setIntMaximum(int max)
-{
- Q_D(QInputDialog);
- d->ensureIntSpinBox();
- d->intSpinBox->setMaximum(max);
-}
-
-int QInputDialog::intMaximum() const
-{
- Q_D(const QInputDialog);
- if (d->intSpinBox) {
- return d->intSpinBox->maximum();
- } else {
- return 99;
- }
-}
-
-/*!
- Sets the range of integer values accepted by the dialog when used in
- IntInput mode, with minimum and maximum values specified by \a min and
- \a max respectively.
-*/
-void QInputDialog::setIntRange(int min, int max)
-{
- Q_D(QInputDialog);
- d->ensureIntSpinBox();
- d->intSpinBox->setRange(min, max);
-}
-
-/*!
- \property QInputDialog::intStep
- \since 4.5
- \brief the step by which the integer value is increased and decreased
-
- This property is only relevant when the input dialog is used in
- IntInput mode.
-*/
-void QInputDialog::setIntStep(int step)
-{
- Q_D(QInputDialog);
- d->ensureIntSpinBox();
- d->intSpinBox->setSingleStep(step);
-}
-
-int QInputDialog::intStep() const
-{
- Q_D(const QInputDialog);
- if (d->intSpinBox) {
- return d->intSpinBox->singleStep();
- } else {
- return 1;
- }
-}
-
-/*!
- \property QInputDialog::doubleValue
- \since 4.5
- \brief the current double precision floating point value accepted as input
-
- This property is only relevant when the input dialog is used in
- DoubleInput mode.
-*/
-void QInputDialog::setDoubleValue(double value)
-{
- Q_D(QInputDialog);
- setInputMode(DoubleInput);
- d->doubleSpinBox->setValue(value);
-}
-
-double QInputDialog::doubleValue() const
-{
- Q_D(const QInputDialog);
- if (d->doubleSpinBox) {
- return d->doubleSpinBox->value();
- } else {
- return 0.0;
- }
-}
-
-/*!
- \property QInputDialog::doubleMinimum
- \since 4.5
- \brief the minimum double precision floating point value accepted as input
-
- This property is only relevant when the input dialog is used in
- DoubleInput mode.
-*/
-void QInputDialog::setDoubleMinimum(double min)
-{
- Q_D(QInputDialog);
- d->ensureDoubleSpinBox();
- d->doubleSpinBox->setMinimum(min);
-}
-
-double QInputDialog::doubleMinimum() const
-{
- Q_D(const QInputDialog);
- if (d->doubleSpinBox) {
- return d->doubleSpinBox->minimum();
- } else {
- return 0.0;
- }
-}
-
-/*!
- \property QInputDialog::doubleMaximum
- \since 4.5
- \brief the maximum double precision floating point value accepted as input
-
- This property is only relevant when the input dialog is used in
- DoubleInput mode.
-*/
-void QInputDialog::setDoubleMaximum(double max)
-{
- Q_D(QInputDialog);
- d->ensureDoubleSpinBox();
- d->doubleSpinBox->setMaximum(max);
-}
-
-double QInputDialog::doubleMaximum() const
-{
- Q_D(const QInputDialog);
- if (d->doubleSpinBox) {
- return d->doubleSpinBox->maximum();
- } else {
- return 99.99;
- }
-}
-
-/*!
- Sets the range of double precision floating point values accepted by the
- dialog when used in DoubleInput mode, with minimum and maximum values
- specified by \a min and \a max respectively.
-*/
-void QInputDialog::setDoubleRange(double min, double max)
-{
- Q_D(QInputDialog);
- d->ensureDoubleSpinBox();
- d->doubleSpinBox->setRange(min, max);
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::doubleDecimals
-
- \brief sets the percision of the double spinbox in decimals
-
- \sa QDoubleSpinBox::setDecimals()
-*/
-void QInputDialog::setDoubleDecimals(int decimals)
-{
- Q_D(QInputDialog);
- d->ensureDoubleSpinBox();
- d->doubleSpinBox->setDecimals(decimals);
-}
-
-int QInputDialog::doubleDecimals() const
-{
- Q_D(const QInputDialog);
- if (d->doubleSpinBox) {
- return d->doubleSpinBox->decimals();
- } else {
- return 2;
- }
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::okButtonText
-
- \brief the text for the button used to accept the entry in the dialog
-*/
-void QInputDialog::setOkButtonText(const QString &text)
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- d->buttonBox->button(QDialogButtonBox::Ok)->setText(text);
-}
-
-QString QInputDialog::okButtonText() const
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- return d->buttonBox->button(QDialogButtonBox::Ok)->text();
-}
-
-/*!
- \since 4.5
-
- \property QInputDialog::cancelButtonText
- \brief the text for the button used to cancel the dialog
-*/
-void QInputDialog::setCancelButtonText(const QString &text)
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- d->buttonBox->button(QDialogButtonBox::Cancel)->setText(text);
-}
-
-QString QInputDialog::cancelButtonText() const
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- return d->buttonBox->button(QDialogButtonBox::Cancel)->text();
-}
-
-/*!
- \since 4.5
- \overload
-
- This function connects one of its signals to the slot specified by \a receiver
- and \a member. The specific signal depends on the arguments that are specified
- in \a member. These are:
-
- \list
- \o textValueSelected() if \a member has a QString for its first argument.
- \o intValueSelected() if \a member has an int for its first argument.
- \o doubleValueSelected() if \a member has a double for its first argument.
- \o accepted() if \a member has NO arguments.
- \endlist
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QInputDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QInputDialog);
- connect(this, signalForMember(member), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-/*!
- \reimp
-*/
-QSize QInputDialog::minimumSizeHint() const
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- return QDialog::minimumSizeHint();
-}
-
-/*!
- \reimp
-*/
-QSize QInputDialog::sizeHint() const
-{
- Q_D(const QInputDialog);
- d->ensureLayout();
- return QDialog::sizeHint();
-}
-
-/*!
- \reimp
-*/
-void QInputDialog::setVisible(bool visible)
-{
- Q_D(const QInputDialog);
- if (visible) {
- d->ensureLayout();
- d->inputWidget->setFocus();
- if (d->inputWidget == d->lineEdit) {
- d->lineEdit->selectAll();
- } else if (d->inputWidget == d->intSpinBox) {
- d->intSpinBox->selectAll();
- } else if (d->inputWidget == d->doubleSpinBox) {
- d->doubleSpinBox->selectAll();
- }
- }
- QDialog::setVisible(visible);
-}
-
-/*!
- Closes the dialog and sets its result code to \a result. If this dialog
- is shown with exec(), done() causes the local event loop to finish,
- and exec() to return \a result.
-
- \sa QDialog::done()
-*/
-void QInputDialog::done(int result)
-{
- Q_D(QInputDialog);
- QDialog::done(result);
- if (result) {
- InputMode mode = inputMode();
- switch (mode) {
- case DoubleInput:
- emit doubleValueSelected(doubleValue());
- break;
- case IntInput:
- emit intValueSelected(intValue());
- break;
- default:
- Q_ASSERT(mode == TextInput);
- emit textValueSelected(textValue());
- }
- }
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, signalForMember(d->memberToDisconnectOnClose),
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
-}
-
-/*!
- Static convenience function to get a string from the user.
-
- \a title is the text which is displayed in the title bar of the dialog.
- \a label is the text which is shown to the user (it should say what should
- be entered).
- \a text is the default text which is placed in the line edit.
- \a mode is the echo mode the line edit will use.
- \a inputMethodHints is the input method hints that will be used in the
- edit widget if an input method is active.
-
- If \a ok is nonnull \e *\a ok will be set to true if the user pressed
- \gui OK and to false if the user pressed \gui Cancel. The dialog's parent
- is \a parent. The dialog will be modal and uses the specified widget
- \a flags.
-
- If the dialog is accepted, this function returns the text in the dialog's
- line edit. If the dialog is rejected, a null QString is returned.
-
- Use this static function like this:
-
- \snippet examples/dialogs/standarddialogs/dialog.cpp 3
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QInputDialog constructors.
-
- \sa getInt(), getDouble(), getItem()
-*/
-
-QString QInputDialog::getText(QWidget *parent, const QString &title, const QString &label,
- QLineEdit::EchoMode mode, const QString &text, bool *ok,
- Qt::WindowFlags flags, Qt::InputMethodHints inputMethodHints)
-{
- QInputDialog dialog(parent, flags);
- dialog.setWindowTitle(title);
- dialog.setLabelText(label);
- dialog.setTextValue(text);
- dialog.setTextEchoMode(mode);
- dialog.setInputMethodHints(inputMethodHints);
-
- int ret = dialog.exec();
- if (ok)
- *ok = !!ret;
- if (ret) {
- return dialog.textValue();
- } else {
- return QString();
- }
-}
-
-/*!
- \internal
-*/
-// ### Qt 5: Use only the version above.
-QString QInputDialog::getText(QWidget *parent, const QString &title, const QString &label,
- QLineEdit::EchoMode mode, const QString &text, bool *ok,
- Qt::WindowFlags flags)
-{
- return getText(parent, title, label, mode, text, ok, flags, Qt::ImhNone);
-}
-
-/*!
- \since 4.5
-
- Static convenience function to get an integer input from the user.
-
- \a title is the text which is displayed in the title bar of the dialog.
- \a label is the text which is shown to the user (it should say what should
- be entered).
- \a value is the default integer which the spinbox will be set to.
- \a min and \a max are the minimum and maximum values the user may choose.
- \a step is the amount by which the values change as the user presses the
- arrow buttons to increment or decrement the value.
-
- If \a ok is nonnull *\a ok will be set to true if the user pressed \gui OK
- and to false if the user pressed \gui Cancel. The dialog's parent is
- \a parent. The dialog will be modal and uses the widget \a flags.
-
- On success, this function returns the integer which has been entered by the
- user; on failure, it returns the initial \a value.
-
- Use this static function like this:
-
- \snippet examples/dialogs/standarddialogs/dialog.cpp 0
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QInputDialog constructors.
-
- \sa getText(), getDouble(), getItem()
-*/
-
-int QInputDialog::getInt(QWidget *parent, const QString &title, const QString &label, int value,
- int min, int max, int step, bool *ok, Qt::WindowFlags flags)
-{
- QInputDialog dialog(parent, flags);
- dialog.setWindowTitle(title);
- dialog.setLabelText(label);
- dialog.setIntRange(min, max);
- dialog.setIntValue(value);
- dialog.setIntStep(step);
-
- int ret = dialog.exec();
- if (ok)
- *ok = !!ret;
- if (ret) {
- return dialog.intValue();
- } else {
- return value;
- }
-}
-
-/*!
- Static convenience function to get a floating point number from the user.
-
- \a title is the text which is displayed in the title bar of the dialog.
- \a label is the text which is shown to the user (it should say what should
- be entered).
- \a value is the default floating point number that the line edit will be
- set to.
- \a min and \a max are the minimum and maximum values the user may choose.
- \a decimals is the maximum number of decimal places the number may have.
-
- If \a ok is nonnull, *\a ok will be set to true if the user pressed \gui OK
- and to false if the user pressed \gui Cancel. The dialog's parent is
- \a parent. The dialog will be modal and uses the widget \a flags.
-
- This function returns the floating point number which has been entered by
- the user.
-
- Use this static function like this:
-
- \snippet examples/dialogs/standarddialogs/dialog.cpp 1
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QInputDialog constructors.
-
- \sa getText(), getInt(), getItem()
-*/
-
-double QInputDialog::getDouble(QWidget *parent, const QString &title, const QString &label,
- double value, double min, double max, int decimals, bool *ok,
- Qt::WindowFlags flags)
-{
- QInputDialog dialog(parent, flags);
- dialog.setWindowTitle(title);
- dialog.setLabelText(label);
- dialog.setDoubleDecimals(decimals);
- dialog.setDoubleRange(min, max);
- dialog.setDoubleValue(value);
-
- int ret = dialog.exec();
- if (ok)
- *ok = !!ret;
- if (ret) {
- return dialog.doubleValue();
- } else {
- return value;
- }
-}
-
-/*!
- Static convenience function to let the user select an item from a string
- list.
-
- \a title is the text which is displayed in the title bar of the dialog.
- \a label is the text which is shown to the user (it should say what should
- be entered).
- \a items is the string list which is inserted into the combobox.
- \a current is the number of the item which should be the current item.
- \a inputMethodHints is the input method hints that will be used if the
- combobox is editable and an input method is active.
-
- If \a editable is true the user can enter their own text; otherwise the
- user may only select one of the existing items.
-
- If \a ok is nonnull \e *\a ok will be set to true if the user pressed
- \gui OK and to false if the user pressed \gui Cancel. The dialog's parent
- is \a parent. The dialog will be modal and uses the widget \a flags.
-
- This function returns the text of the current item, or if \a editable is
- true, the current text of the combobox.
-
- Use this static function like this:
-
- \snippet examples/dialogs/standarddialogs/dialog.cpp 2
-
- \warning Do not delete \a parent during the execution of the dialog. If you
- want to do this, you should create the dialog yourself using one of the
- QInputDialog constructors.
-
- \sa getText(), getInt(), getDouble()
-*/
-
-QString QInputDialog::getItem(QWidget *parent, const QString &title, const QString &label,
- const QStringList &items, int current, bool editable, bool *ok,
- Qt::WindowFlags flags, Qt::InputMethodHints inputMethodHints)
-{
- QString text(items.value(current));
-
- QInputDialog dialog(parent, flags);
- dialog.setWindowTitle(title);
- dialog.setLabelText(label);
- dialog.setComboBoxItems(items);
- dialog.setTextValue(text);
- dialog.setComboBoxEditable(editable);
- dialog.setInputMethodHints(inputMethodHints);
-
- int ret = dialog.exec();
- if (ok)
- *ok = !!ret;
- if (ret) {
- return dialog.textValue();
- } else {
- return text;
- }
-}
-
-/*!
- \internal
-*/
-// ### Qt 5: Use only the version above.
-QString QInputDialog::getItem(QWidget *parent, const QString &title, const QString &label,
- const QStringList &items, int current, bool editable, bool *ok,
- Qt::WindowFlags flags)
-{
- return getItem(parent, title, label, items, current, editable, ok, flags, Qt::ImhNone);
-}
-
-/*!
- \obsolete
-
- Use getInt() instead.
-*/
-int QInputDialog::getInteger(QWidget *parent, const QString &title, const QString &label,
- int value, int min, int max, int step, bool *ok,
- Qt::WindowFlags flags)
-{
- return getInt(parent, title, label, value, min, max, step, ok, flags);
-}
-
-/*!
- \fn QString QInputDialog::getText(const QString &title, const QString &label,
- QLineEdit::EchoMode echo = QLineEdit::Normal,
- const QString &text = QString(), bool *ok = 0,
- QWidget *parent = 0, const char *name = 0, Qt::WindowFlags flags = 0)
-
- Call getText(\a parent, \a title, \a label, \a echo, \a text, \a
- ok, \a flags) instead.
-
- The \a name parameter is ignored.
-*/
-
-/*!
- \fn int QInputDialog::getInteger(const QString &title, const QString &label, int value = 0,
- int min = -2147483647, int max = 2147483647,
- int step = 1, bool *ok = 0,
- QWidget *parent = 0, const char *name = 0, Qt::WindowFlags flags = 0)
-
-
- Call getInteger(\a parent, \a title, \a label, \a value, \a
- min, \a max, \a step, \a ok, \a flags) instead.
-
- The \a name parameter is ignored.
-*/
-
-/*!
- \fn double QInputDialog::getDouble(const QString &title, const QString &label, double value = 0,
- double min = -2147483647, double max = 2147483647,
- int decimals = 1, bool *ok = 0,
- QWidget *parent = 0, const char *name = 0, Qt::WindowFlags flags = 0)
-
- Call getDouble(\a parent, \a title, \a label, \a value, \a
- min, \a max, \a decimals, \a ok, \a flags).
-
- The \a name parameter is ignored.
-*/
-
-/*!
- \fn QString QInputDialog::getItem(const QString &title, const QString &label, const QStringList &list,
- int current = 0, bool editable = true, bool *ok = 0,
- QWidget *parent = 0, const char *name = 0, Qt::WindowFlags flags = 0)
-
- Call getItem(\a parent, \a title, \a label, \a list, \a current,
- \a editable, \a ok, \a flags) instead.
-
- The \a name parameter is ignored.
-*/
-
-/*!
- \fn void QInputDialog::doubleValueChanged(double value)
-
- This signal is emitted whenever the double value changes in the dialog.
- The current value is specified by \a value.
-
- This signal is only relevant when the input dialog is used in
- DoubleInput mode.
-*/
-
-/*!
- \fn void QInputDialog::doubleValueSelected(double value)
-
- This signal is emitted whenever the user selects a double value by
- accepting the dialog; for example, by clicking the \gui{OK} button.
- The selected value is specified by \a value.
-
- This signal is only relevant when the input dialog is used in
- DoubleInput mode.
-*/
-
-/*!
- \fn void QInputDialog::intValueChanged(int value)
-
- This signal is emitted whenever the integer value changes in the dialog.
- The current value is specified by \a value.
-
- This signal is only relevant when the input dialog is used in
- IntInput mode.
-*/
-
-/*!
- \fn void QInputDialog::intValueSelected(int value)
-
- This signal is emitted whenever the user selects a integer value by
- accepting the dialog; for example, by clicking the \gui{OK} button.
- The selected value is specified by \a value.
-
- This signal is only relevant when the input dialog is used in
- IntInput mode.
-*/
-
-/*!
- \fn void QInputDialog::textValueChanged(const QString &text)
-
- This signal is emitted whenever the text string changes in the dialog.
- The current string is specified by \a text.
-
- This signal is only relevant when the input dialog is used in
- TextInput mode.
-*/
-
-/*!
- \fn void QInputDialog::textValueSelected(const QString &text)
-
- This signal is emitted whenever the user selects a text string by
- accepting the dialog; for example, by clicking the \gui{OK} button.
- The selected string is specified by \a text.
-
- This signal is only relevant when the input dialog is used in
- TextInput mode.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qinputdialog.cpp"
-
-#endif // QT_NO_INPUTDIALOG
diff --git a/src/gui/dialogs/qinputdialog.h b/src/gui/dialogs/qinputdialog.h
deleted file mode 100644
index b0e6fbb216..0000000000
--- a/src/gui/dialogs/qinputdialog.h
+++ /dev/null
@@ -1,256 +0,0 @@
-/****************************************************************************
-**
-** 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 QINPUTDIALOG_H
-#define QINPUTDIALOG_H
-
-#include <QtGui/qdialog.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qlineedit.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_INPUTDIALOG
-
-class QInputDialogPrivate;
-
-class Q_GUI_EXPORT QInputDialog : public QDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QInputDialog)
-// Q_ENUMS(InputMode InputDialogOption)
- QDOC_PROPERTY(InputMode inputMode READ inputMode WRITE setInputMode)
- QDOC_PROPERTY(QString labelText READ labelText WRITE setLabelText)
- QDOC_PROPERTY(InputDialogOptions options READ options WRITE setOptions)
- QDOC_PROPERTY(QString textValue READ textValue WRITE setTextValue NOTIFY textValueChanged)
- QDOC_PROPERTY(int intValue READ intValue WRITE setIntValue NOTIFY intValueChanged)
- QDOC_PROPERTY(int doubleValue READ doubleValue WRITE setDoubleValue NOTIFY doubleValueChanged)
- QDOC_PROPERTY(QLineEdit::EchoMode textEchoMode READ textEchoMode WRITE setTextEchoMode)
- QDOC_PROPERTY(bool comboBoxEditable READ isComboBoxEditable WRITE setComboBoxEditable)
- QDOC_PROPERTY(QStringList comboBoxItems READ comboBoxItems WRITE setComboBoxItems)
- QDOC_PROPERTY(int intMinimum READ intMinimum WRITE setIntMinimum)
- QDOC_PROPERTY(int intMaximum READ intMaximum WRITE setIntMaximum)
- QDOC_PROPERTY(int intStep READ intStep WRITE setIntStep)
- QDOC_PROPERTY(double doubleMinimum READ doubleMinimum WRITE setDoubleMinimum)
- QDOC_PROPERTY(double doubleMaximum READ doubleMaximum WRITE setDoubleMaximum)
- QDOC_PROPERTY(int doubleDecimals READ doubleDecimals WRITE setDoubleDecimals)
- QDOC_PROPERTY(QString okButtonText READ okButtonText WRITE setOkButtonText)
- QDOC_PROPERTY(QString cancelButtonText READ cancelButtonText WRITE setCancelButtonText)
-
-public:
- enum InputDialogOption {
- NoButtons = 0x00000001,
- UseListViewForComboBoxItems = 0x00000002
- };
-
- Q_DECLARE_FLAGS(InputDialogOptions, InputDialogOption)
-
- enum InputMode {
- TextInput,
- IntInput,
- DoubleInput
- };
-
- QInputDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QInputDialog();
-
- void setInputMode(InputMode mode);
- InputMode inputMode() const;
-
- void setLabelText(const QString &text);
- QString labelText() const;
-
- void setOption(InputDialogOption option, bool on = true);
- bool testOption(InputDialogOption option) const;
- void setOptions(InputDialogOptions options);
- InputDialogOptions options() const;
-
- void setTextValue(const QString &text);
- QString textValue() const;
-
- void setTextEchoMode(QLineEdit::EchoMode mode);
- QLineEdit::EchoMode textEchoMode() const;
-
- void setComboBoxEditable(bool editable);
- bool isComboBoxEditable() const;
-
- void setComboBoxItems(const QStringList &items);
- QStringList comboBoxItems() const;
-
- void setIntValue(int value);
- int intValue() const;
-
- void setIntMinimum(int min);
- int intMinimum() const;
-
- void setIntMaximum(int max);
- int intMaximum() const;
-
- void setIntRange(int min, int max);
-
- void setIntStep(int step);
- int intStep() const;
-
- void setDoubleValue(double value);
- double doubleValue() const;
-
- void setDoubleMinimum(double min);
- double doubleMinimum() const;
-
- void setDoubleMaximum(double max);
- double doubleMaximum() const;
-
- void setDoubleRange(double min, double max);
-
- void setDoubleDecimals(int decimals);
- int doubleDecimals() const;
-
- void setOkButtonText(const QString &text);
- QString okButtonText() const;
-
- void setCancelButtonText(const QString &text);
- QString cancelButtonText() const;
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
- QSize minimumSizeHint() const;
- QSize sizeHint() const;
-
- void setVisible(bool visible);
-
-#ifdef Q_QDOC
- static QString getText(QWidget *parent, const QString &title, const QString &label,
- QLineEdit::EchoMode echo = QLineEdit::Normal,
- const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0,
- Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
- static QString getItem(QWidget *parent, const QString &title, const QString &label,
- const QStringList &items, int current = 0, bool editable = true,
- bool *ok = 0, Qt::WindowFlags flags = 0,
- Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
-#else
- static QString getText(QWidget *parent, const QString &title, const QString &label,
- QLineEdit::EchoMode echo = QLineEdit::Normal,
- const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0);
- static QString getItem(QWidget *parent, const QString &title, const QString &label,
- const QStringList &items, int current = 0, bool editable = true,
- bool *ok = 0, Qt::WindowFlags flags = 0);
- static QString getText(QWidget *parent, const QString &title, const QString &label,
- QLineEdit::EchoMode echo,
- const QString &text, bool *ok, Qt::WindowFlags flags,
- Qt::InputMethodHints inputMethodHints);
- static QString getItem(QWidget *parent, const QString &title, const QString &label,
- const QStringList &items, int current, bool editable,
- bool *ok, Qt::WindowFlags flags,
- Qt::InputMethodHints inputMethodHints);
-#endif
- static int getInt(QWidget *parent, const QString &title, const QString &label, int value = 0,
- int minValue = -2147483647, int maxValue = 2147483647,
- int step = 1, bool *ok = 0, Qt::WindowFlags flags = 0);
- static double getDouble(QWidget *parent, const QString &title, const QString &label, double value = 0,
- double minValue = -2147483647, double maxValue = 2147483647,
- int decimals = 1, bool *ok = 0, Qt::WindowFlags flags = 0);
-
- // obsolete
- static int getInteger(QWidget *parent, const QString &title, const QString &label, int value = 0,
- int minValue = -2147483647, int maxValue = 2147483647,
- int step = 1, bool *ok = 0, Qt::WindowFlags flags = 0);
-
-#ifdef QT3_SUPPORT
- inline static QT3_SUPPORT QString getText(const QString &title, const QString &label,
- QLineEdit::EchoMode echo = QLineEdit::Normal,
- const QString &text = QString(), bool *ok = 0,
- QWidget *parent = 0, const char * = 0, Qt::WindowFlags flags = 0)
- { return getText(parent, title, label, echo, text, ok, flags); }
- inline static QT3_SUPPORT int getInteger(const QString &title, const QString &label, int value = 0,
- int minValue = -2147483647, int maxValue = 2147483647,
- int step = 1, bool *ok = 0,
- QWidget *parent = 0, const char * = 0, Qt::WindowFlags flags = 0)
- { return getInteger(parent, title, label, value, minValue, maxValue, step, ok, flags); }
- inline static QT3_SUPPORT double getDouble(const QString &title, const QString &label, double value = 0,
- double minValue = -2147483647, double maxValue = 2147483647,
- int decimals = 1, bool *ok = 0,
- QWidget *parent = 0, const char * = 0, Qt::WindowFlags flags = 0)
- { return getDouble(parent, title, label, value, minValue, maxValue, decimals, ok, flags); }
- inline static QT3_SUPPORT QString getItem(const QString &title, const QString &label, const QStringList &list,
- int current = 0, bool editable = true, bool *ok = 0,
- QWidget *parent = 0, const char * = 0, Qt::WindowFlags flags = 0)
- { return getItem(parent, title, label, list, current, editable, ok, flags); }
-#endif
-
-Q_SIGNALS:
- // ### emit signals!
- void textValueChanged(const QString &text);
- void textValueSelected(const QString &text);
- void intValueChanged(int value);
- void intValueSelected(int value);
- void doubleValueChanged(double value);
- void doubleValueSelected(double value);
-
-
-public:
- void done(int result); // ### Qt 5: Make protected.
-
-private:
- Q_DISABLE_COPY(QInputDialog)
- Q_PRIVATE_SLOT(d_func(), void _q_textChanged(const QString&))
- Q_PRIVATE_SLOT(d_func(), void _q_currentRowChanged(const QModelIndex&, const QModelIndex&))
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QInputDialog::InputDialogOptions)
-
-#endif // QT_NO_INPUTDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QINPUTDIALOG_H
diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp
deleted file mode 100644
index d6dbcf6e78..0000000000
--- a/src/gui/dialogs/qmessagebox.cpp
+++ /dev/null
@@ -1,2751 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtGui/qmessagebox.h>
-
-#ifndef QT_NO_MESSAGEBOX
-
-#include <QtGui/qdialogbuttonbox.h>
-#include "private/qlabel_p.h"
-#include "private/qapplication_p.h"
-#include <QtCore/qlist.h>
-#include <QtCore/qdebug.h>
-#include <QtGui/qstyle.h>
-#include <QtGui/qstyleoption.h>
-#include <QtGui/qgridlayout.h>
-#include <QtGui/qdesktopwidget.h>
-#include <QtGui/qpushbutton.h>
-#include <QtGui/qaccessible.h>
-#include <QtGui/qicon.h>
-#include <QtGui/qtextdocument.h>
-#include <QtGui/qapplication.h>
-#include <QtGui/qtextedit.h>
-#include <QtGui/qtextbrowser.h>
-#include <QtGui/qmenu.h>
-#include "qdialog_p.h"
-#include <QtGui/qfont.h>
-#include <QtGui/qfontmetrics.h>
-#include <QtGui/qclipboard.h>
-
-#ifndef QT_NO_STYLE_S60
-#include <qs60style.h>
-#endif
-
-#ifdef Q_WS_WINCE
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_smartphone();//defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_pocket_pc(); //defined in qguifunctions_wince.cpp
-
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-enum Button { Old_Ok = 1, Old_Cancel = 2, Old_Yes = 3, Old_No = 4, Old_Abort = 5, Old_Retry = 6,
- Old_Ignore = 7, Old_YesAll = 8, Old_NoAll = 9, Old_ButtonMask = 0xFF,
- NewButtonMask = 0xFFFFFC00 };
-
-enum DetailButtonLabel { ShowLabel = 0, HideLabel = 1 };
-#ifndef QT_NO_TEXTEDIT
-class QMessageBoxDetailsText : public QWidget
-{
-public:
- class TextEdit : public QTextEdit
- {
- public:
- TextEdit(QWidget *parent=0) : QTextEdit(parent) { }
- void contextMenuEvent(QContextMenuEvent * e)
- {
-#ifndef QT_NO_CONTEXTMENU
- QMenu *menu = createStandardContextMenu();
- menu->setAttribute(Qt::WA_DeleteOnClose);
- menu->popup(e->globalPos());
-#else
- Q_UNUSED(e);
-#endif
- }
- };
-
- QMessageBoxDetailsText(QWidget *parent=0)
- : QWidget(parent)
- {
- QVBoxLayout *layout = new QVBoxLayout;
- layout->setMargin(0);
- QFrame *line = new QFrame(this);
- line->setFrameShape(QFrame::HLine);
- line->setFrameShadow(QFrame::Sunken);
- layout->addWidget(line);
- textEdit = new TextEdit();
- textEdit->setFixedHeight(100);
- textEdit->setFocusPolicy(Qt::NoFocus);
- textEdit->setReadOnly(true);
- layout->addWidget(textEdit);
- setLayout(layout);
- }
- void setText(const QString &text) { textEdit->setPlainText(text); }
- QString text() const { return textEdit->toPlainText(); }
-private:
- TextEdit *textEdit;
-};
-#endif // QT_NO_TEXTEDIT
-
-class DetailButton : public QPushButton
-{
-public:
- DetailButton(QWidget *parent) : QPushButton(label(ShowLabel), parent)
- {
- setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- }
-
- QString label(DetailButtonLabel label) const
- { return label == ShowLabel ? QMessageBox::tr("Show Details...") : QMessageBox::tr("Hide Details..."); }
-
- void setLabel(DetailButtonLabel lbl)
- { setText(label(lbl)); }
-
- QSize sizeHint() const
- {
- ensurePolished();
- QStyleOptionButton opt;
- initStyleOption(&opt);
- const QFontMetrics fm = fontMetrics();
- opt.text = label(ShowLabel);
- QSize sz = fm.size(Qt::TextShowMnemonic, opt.text);
- QSize ret = style()->sizeFromContents(QStyle::CT_PushButton, &opt, sz, this).
- expandedTo(QApplication::globalStrut());
- opt.text = label(HideLabel);
- sz = fm.size(Qt::TextShowMnemonic, opt.text);
- ret.expandedTo(style()->sizeFromContents(QStyle::CT_PushButton, &opt, sz, this).
- expandedTo(QApplication::globalStrut()));
- return ret;
- }
-};
-
-
-class QMessageBoxPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QMessageBox)
-
-public:
- QMessageBoxPrivate() : escapeButton(0), defaultButton(0), clickedButton(0), detailsButton(0),
-#ifndef QT_NO_TEXTEDIT
- detailsText(0),
-#endif
- compatMode(false), autoAddOkButton(true),
- detectedEscapeButton(0), informativeLabel(0) { }
-
- void init(const QString &title = QString(), const QString &text = QString());
- void _q_buttonClicked(QAbstractButton *);
-
- QAbstractButton *findButton(int button0, int button1, int button2, int flags);
- void addOldButtons(int button0, int button1, int button2);
-
- QAbstractButton *abstractButtonForId(int id) const;
- int execReturnCode(QAbstractButton *button);
-
- void detectEscapeButton();
- void updateSize();
- int layoutMinimumWidth();
- void retranslateStrings();
-
-#ifdef Q_WS_WINCE
- void hideSpecial();
-#endif
-
- static int showOldMessageBox(QWidget *parent, QMessageBox::Icon icon,
- const QString &title, const QString &text,
- int button0, int button1, int button2);
- static int showOldMessageBox(QWidget *parent, QMessageBox::Icon icon,
- const QString &title, const QString &text,
- const QString &button0Text,
- const QString &button1Text,
- const QString &button2Text,
- int defaultButtonNumber,
- int escapeButtonNumber);
-
- static QMessageBox::StandardButton showNewMessageBox(QWidget *parent,
- QMessageBox::Icon icon, const QString& title, const QString& text,
- QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton);
-
- static QPixmap standardIcon(QMessageBox::Icon icon, QMessageBox *mb);
-
- QLabel *label;
- QMessageBox::Icon icon;
- QLabel *iconLabel;
- QDialogButtonBox *buttonBox;
- QList<QAbstractButton *> customButtonList;
- QAbstractButton *escapeButton;
- QPushButton *defaultButton;
- QAbstractButton *clickedButton;
- DetailButton *detailsButton;
-#ifndef QT_NO_TEXTEDIT
- QMessageBoxDetailsText *detailsText;
-#endif
- bool compatMode;
- bool autoAddOkButton;
- QAbstractButton *detectedEscapeButton;
- QLabel *informativeLabel;
-#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5)
- QTextBrowser *textBrowser;
-#endif
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
- QByteArray signalToDisconnectOnClose;
-};
-
-void QMessageBoxPrivate::init(const QString &title, const QString &text)
-{
- Q_Q(QMessageBox);
-
- label = new QLabel;
- label->setObjectName(QLatin1String("qt_msgbox_label"));
- label->setTextInteractionFlags(Qt::TextInteractionFlags(q->style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, 0, q)));
- label->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
- label->setOpenExternalLinks(true);
-#if defined(Q_WS_MAC)
- label->setContentsMargins(16, 0, 0, 0);
-#elif !defined(Q_WS_QWS)
- label->setContentsMargins(2, 0, 0, 0);
- label->setIndent(9);
-#endif
- icon = QMessageBox::NoIcon;
- iconLabel = new QLabel;
- iconLabel->setObjectName(QLatin1String("qt_msgboxex_icon_label"));
- iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
-
- buttonBox = new QDialogButtonBox;
- buttonBox->setObjectName(QLatin1String("qt_msgbox_buttonbox"));
- buttonBox->setCenterButtons(q->style()->styleHint(QStyle::SH_MessageBox_CenterButtons, 0, q));
- QObject::connect(buttonBox, SIGNAL(clicked(QAbstractButton*)),
- q, SLOT(_q_buttonClicked(QAbstractButton*)));
-
- QGridLayout *grid = new QGridLayout;
-#ifndef Q_WS_MAC
- grid->addWidget(iconLabel, 0, 0, 2, 1, Qt::AlignTop);
- grid->addWidget(label, 0, 1, 1, 1);
- // -- leave space for information label --
- grid->addWidget(buttonBox, 2, 0, 1, 2);
-#else
- grid->setMargin(0);
- grid->setVerticalSpacing(8);
- grid->setHorizontalSpacing(0);
- q->setContentsMargins(24, 15, 24, 20);
- grid->addWidget(iconLabel, 0, 0, 2, 1, Qt::AlignTop | Qt::AlignLeft);
- grid->addWidget(label, 0, 1, 1, 1);
- // -- leave space for information label --
- grid->setRowStretch(1, 100);
- grid->setRowMinimumHeight(2, 6);
- grid->addWidget(buttonBox, 3, 1, 1, 1);
-#endif
-
- grid->setSizeConstraint(QLayout::SetNoConstraint);
- q->setLayout(grid);
-
- if (!title.isEmpty() || !text.isEmpty()) {
- q->setWindowTitle(title);
- q->setText(text);
- }
- q->setModal(true);
-
-#ifdef Q_WS_MAC
- QFont f = q->font();
- f.setBold(true);
- label->setFont(f);
-#endif
- retranslateStrings();
-}
-
-int QMessageBoxPrivate::layoutMinimumWidth()
-{
- layout->activate();
- return layout->totalMinimumSize().width();
-}
-
-void QMessageBoxPrivate::updateSize()
-{
- Q_Q(QMessageBox);
-
- if (!q->isVisible())
- return;
-
- QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()).size();
-#if defined(Q_WS_QWS) || defined(Q_WS_WINCE) || defined(Q_OS_SYMBIAN)
- // the width of the screen, less the window border.
- int hardLimit = screenSize.width() - (q->frameGeometry().width() - q->geometry().width());
-#else
- int hardLimit = qMin(screenSize.width() - 480, 1000); // can never get bigger than this
- // on small screens allows the messagebox be the same size as the screen
- if (screenSize.width() <= 1024)
- hardLimit = screenSize.width();
-#endif
-#ifdef Q_WS_MAC
- int softLimit = qMin(screenSize.width()/2, 420);
-#elif defined(Q_WS_QWS)
- int softLimit = qMin(hardLimit, 500);
-#else
- // note: ideally on windows, hard and soft limits but it breaks compat
-#ifndef Q_WS_WINCE
- int softLimit = qMin(screenSize.width()/2, 500);
-#else
- int softLimit = qMin(screenSize.width() * 3 / 4, 500);
-#endif //Q_WS_WINCE
-#endif
-
- if (informativeLabel)
- informativeLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
-
- label->setWordWrap(false); // makes the label return min size
- int width = layoutMinimumWidth();
-
- if (width > softLimit) {
- label->setWordWrap(true);
- width = qMax(softLimit, layoutMinimumWidth());
-
- if (width > hardLimit) {
- label->d_func()->ensureTextControl();
- if (QTextControl *control = label->d_func()->control) {
- QTextOption opt = control->document()->defaultTextOption();
- opt.setWrapMode(QTextOption::WrapAnywhere);
- control->document()->setDefaultTextOption(opt);
- }
- width = hardLimit;
- }
- }
-#ifdef Q_WS_S60
- // in S60 portait messageBoxes should always occupy maximum width
- if (QApplication::desktop()->size().height() > QApplication::desktop()->size().width()){
- width = hardLimit;
- } else {
- // in landscape the messageBoxes should be of same width as in portrait
- width = qMin(QApplication::desktop()->size().height(), hardLimit);
- }
-#endif
-
- if (informativeLabel) {
- label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
- QSizePolicy policy(QSizePolicy::Minimum, QSizePolicy::Preferred);
- policy.setHeightForWidth(true);
- informativeLabel->setSizePolicy(policy);
- width = qMax(width, layoutMinimumWidth());
- if (width > hardLimit) { // longest word is really big, so wrap anywhere
- informativeLabel->d_func()->ensureTextControl();
- if (QTextControl *control = informativeLabel->d_func()->control) {
- QTextOption opt = control->document()->defaultTextOption();
- opt.setWrapMode(QTextOption::WrapAnywhere);
- control->document()->setDefaultTextOption(opt);
- }
- width = hardLimit;
- }
- policy.setHeightForWidth(label->wordWrap());
- label->setSizePolicy(policy);
- }
-
- QFontMetrics fm(QApplication::font("QWorkspaceTitleBar"));
- int windowTitleWidth = qMin(fm.width(q->windowTitle()) + 50, hardLimit);
- if (windowTitleWidth > width)
- width = windowTitleWidth;
-
- layout->activate();
- int height = (layout->hasHeightForWidth())
- ? layout->totalHeightForWidth(width)
- : layout->totalMinimumSize().height();
-
-#ifndef QT_NO_STYLE_S60
- QS60Style *s60Style = 0;
- s60Style = qobject_cast<QS60Style *>(QApplication::style());
-
- //use custom pixel metric to deduce the minimum height of the messagebox
- if (s60Style)
- height = qMax(height, s60Style->pixelMetric((QStyle::PixelMetric)PM_MessageBoxHeight));
-#endif
-
- q->setFixedSize(width, height);
- QCoreApplication::removePostedEvents(q, QEvent::LayoutRequest);
-}
-
-
-#ifdef Q_WS_WINCE
-/*!
- \internal
- Hides special buttons which are rather shown in the title bar
- on WinCE, to conserve screen space.
-*/
-
-void QMessageBoxPrivate::hideSpecial()
-{
- Q_Q(QMessageBox);
- QList<QPushButton*> list = q->findChildren<QPushButton*>();
- for (int i=0; i<list.size(); ++i) {
- QPushButton *pb = list.at(i);
- QString text = pb->text();
- text.remove(QChar::fromLatin1('&'));
- if (text == QApplication::translate("QMessageBox", "OK" ))
- pb->setFixedSize(0,0);
- }
-}
-#endif
-
-static int oldButton(int button)
-{
- switch (button & QMessageBox::ButtonMask) {
- case QMessageBox::Ok:
- return Old_Ok;
- case QMessageBox::Cancel:
- return Old_Cancel;
- case QMessageBox::Yes:
- return Old_Yes;
- case QMessageBox::No:
- return Old_No;
- case QMessageBox::Abort:
- return Old_Abort;
- case QMessageBox::Retry:
- return Old_Retry;
- case QMessageBox::Ignore:
- return Old_Ignore;
- case QMessageBox::YesToAll:
- return Old_YesAll;
- case QMessageBox::NoToAll:
- return Old_NoAll;
- default:
- return 0;
- }
-}
-
-int QMessageBoxPrivate::execReturnCode(QAbstractButton *button)
-{
- int ret = buttonBox->standardButton(button);
- if (ret == QMessageBox::NoButton) {
- ret = customButtonList.indexOf(button); // if button == 0, correctly sets ret = -1
- } else if (compatMode) {
- ret = oldButton(ret);
- }
- return ret;
-}
-
-void QMessageBoxPrivate::_q_buttonClicked(QAbstractButton *button)
-{
- Q_Q(QMessageBox);
-#ifndef QT_NO_TEXTEDIT
- if (detailsButton && detailsText && button == detailsButton) {
- detailsButton->setLabel(detailsText->isHidden() ? HideLabel : ShowLabel);
- detailsText->setHidden(!detailsText->isHidden());
- updateSize();
- } else
-#endif
- {
- clickedButton = button;
- q->done(execReturnCode(button)); // does not trigger closeEvent
- emit q->buttonClicked(button);
-
- if (receiverToDisconnectOnClose) {
- QObject::disconnect(q, signalToDisconnectOnClose, receiverToDisconnectOnClose,
- memberToDisconnectOnClose);
- receiverToDisconnectOnClose = 0;
- }
- signalToDisconnectOnClose.clear();
- memberToDisconnectOnClose.clear();
- }
-}
-
-/*!
- \class QMessageBox
-
- \brief The QMessageBox class provides a modal dialog for informing
- the user or for asking the user a question and receiving an answer.
-
- \ingroup standard-dialogs
-
-
- A message box displays a primary \l{QMessageBox::text}{text} to
- alert the user to a situation, an \l{QMessageBox::informativeText}
- {informative text} to further explain the alert or to ask the user
- a question, and an optional \l{QMessageBox::detailedText}
- {detailed text} to provide even more data if the user requests
- it. A message box can also display an \l{QMessageBox::icon} {icon}
- and \l{QMessageBox::standardButtons} {standard buttons} for
- accepting a user response.
-
- Two APIs for using QMessageBox are provided, the property-based
- API, and the static functions. Calling one of the static functions
- is the simpler approach, but it is less flexible than using the
- property-based API, and the result is less informative. Using the
- property-based API is recommended.
-
- \section1 The Property-based API
-
- To use the property-based API, construct an instance of
- QMessageBox, set the desired properties, and call exec() to show
- the message. The simplest configuration is to set only the
- \l{QMessageBox::text} {message text} property.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp 5
-
- The user must click the \gui{OK} button to dismiss the message
- box. The rest of the GUI is blocked until the message box is
- dismissed.
-
- \image msgbox1.png
-
- A better approach than just alerting the user to an event is to
- also ask the user what to do about it. Store the question in the
- \l{QMessageBox::informativeText} {informative text} property, and
- set the \l{QMessageBox::standardButtons} {standard buttons}
- property to the set of buttons you want as the set of user
- responses. The buttons are specified by combining values from
- StandardButtons using the bitwise OR operator. The display order
- for the buttons is platform-dependent. For example, on Windows,
- \gui{Save} is displayed to the left of \gui{Cancel}, whereas on
- Mac OS, the order is reversed.
-
- Mark one of your standard buttons to be your
- \l{QMessageBox::defaultButton()} {default button}.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp 6
-
- This is the approach recommended in the
- \l{http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGWindows/chapter_18_section_7.html}
- {Mac OS X Guidlines}. Similar guidlines apply for the other
- platforms, but note the different ways the
- \l{QMessageBox::informativeText} {informative text} is handled for
- different platforms.
-
- \image msgbox2.png
-
- The exec() slot returns the StandardButtons value of the button
- that was clicked.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp 7
-
- To give the user more information to help him answer the question,
- set the \l{QMessageBox::detailedText} {detailed text} property. If
- the \l{QMessageBox::detailedText} {detailed text} property is set,
- the \gui{Show Details...} button will be shown.
-
- \image msgbox3.png
-
- Clicking the \gui{Show Details...} button displays the detailed text.
-
- \image msgbox4.png
-
- \section2 Rich Text and the Text Format Property
-
- The \l{QMessageBox::detailedText} {detailed text} property is
- always interpreted as plain text. The \l{QMessageBox::text} {main
- text} and \l{QMessageBox::informativeText} {informative text}
- properties can be either plain text or rich text. These strings
- are interpreted according to the setting of the
- \l{QMessageBox::textFormat} {text format} property. The default
- setting is \l{Qt::AutoText} {auto-text}.
-
- Note that for some plain text strings containing XML
- meta-characters, the auto-text \l{Qt::mightBeRichText()} {rich
- text detection test} may fail causing your plain text string to be
- interpreted incorrectly as rich text. In these rare cases, use
- Qt::convertFromPlainText() to convert your plain text string to a
- visually equivalent rich text string, or set the
- \l{QMessageBox::textFormat} {text format} property explicitly with
- setTextFormat().
-
- \section2 Severity Levels and the Icon and Pixmap Properties
-
- QMessageBox supports four predefined message severity levels, or message
- types, which really only differ in the predefined icon they each show.
- Specify one of the four predefined message types by setting the
- \l{QMessageBox::icon}{icon} property to one of the
- \l{QMessageBox::Icon}{predefined icons}. The following rules are
- guidelines:
-
- \table
- \row
- \o \img qmessagebox-quest.png
- \o \l Question
- \o For asking a question during normal operations.
- \row
- \o \img qmessagebox-info.png
- \o \l Information
- \o For reporting information about normal operations.
- \row
- \o \img qmessagebox-warn.png
- \o \l Warning
- \o For reporting non-critical errors.
- \row
- \o \img qmessagebox-crit.png
- \o \l Critical
- \o For reporting critical errors.
- \endtable
-
- \l{QMessageBox::Icon}{Predefined icons} are not defined by QMessageBox, but
- provided by the style. The default value is \l{QMessageBox::NoIcon}
- {No Icon}. The message boxes are otherwise the same for all cases. When
- using a standard icon, use the one recommended in the table, or use the
- one recommended by the style guidelines for your platform. If none of the
- standard icons is right for your message box, you can use a custom icon by
- setting the \l{QMessageBox::iconPixmap}{icon pixmap} property instead of
- setting the \l{QMessageBox::icon}{icon} property.
-
- In summary, to set an icon, use \e{either} setIcon() for one of the
- standard icons, \e{or} setIconPixmap() for a custom icon.
-
- \section1 The Static Functions API
-
- Building message boxes with the static functions API, although
- convenient, is less flexible than using the property-based API,
- because the static function signatures lack parameters for setting
- the \l{QMessageBox::informativeText} {informative text} and
- \l{QMessageBox::detailedText} {detailed text} properties. One
- work-around for this has been to use the \c{title} parameter as
- the message box main text and the \c{text} parameter as the
- message box informative text. Because this has the obvious
- drawback of making a less readable message box, platform
- guidelines do not recommend it. The \e{Microsoft Windows User
- Interface Guidelines} recommend using the
- \l{QCoreApplication::applicationName} {application name} as the
- \l{QMessageBox::setWindowTitle()} {window's title}, which means
- that if you have an informative text in addition to your main
- text, you must concatenate it to the \c{text} parameter.
-
- Note that the static function signatures have changed with respect
- to their button parameters, which are now used to set the
- \l{QMessageBox::standardButtons} {standard buttons} and the
- \l{QMessageBox::defaultButton()} {default button}.
-
- Static functions are available for creating information(),
- question(), warning(), and critical() message boxes.
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp 0
-
- The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
- how to use QMessageBox and the other built-in Qt dialogs.
-
- \section1 Advanced Usage
-
- If the \l{QMessageBox::StandardButtons} {standard buttons} are not
- flexible enough for your message box, you can use the addButton()
- overload that takes a text and a ButtonRoleto to add custom
- buttons. The ButtonRole is used by QMessageBox to determine the
- ordering of the buttons on screen (which varies according to the
- platform). You can test the value of clickedButton() after calling
- exec(). For example,
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp 2
-
- \section1 Default and Escape Keys
-
- The default button (i.e., the button activated when \key Enter is
- pressed) can be specified using setDefaultButton(). If a default
- button is not specified, QMessageBox tries to find one based on
- the \l{ButtonRole} {button roles} of the buttons used in the
- message box.
-
- The escape button (the button activated when \key Esc is pressed)
- can be specified using setEscapeButton(). If an escape button is
- not specified, QMessageBox tries to find one using these rules:
-
- \list 1
-
- \o If there is only one button, it is the button activated when
- \key Esc is pressed.
-
- \o If there is a \l Cancel button, it is the button activated when
- \key Esc is pressed.
-
- \o If there is exactly one button having either
- \l{QMessageBox::RejectRole} {the Reject role} or the
- \l{QMessageBox::NoRole} {the No role}, it is the button
- activated when \key Esc is pressed.
-
- \endlist
-
- When an escape button can't be determined using these rules,
- pressing \key Esc has no effect.
-
- \sa QDialogButtonBox, {fowler}{GUI Design Handbook: Message Box}, {Standard Dialogs Example}, {Application Example}
-*/
-
-/*!
- \enum QMessageBox::StandardButton
- \since 4.2
-
- These enums describe flags for standard buttons. Each button has a
- defined \l ButtonRole.
-
- \value Ok An "OK" button defined with the \l AcceptRole.
- \value Open A "Open" button defined with the \l AcceptRole.
- \value Save A "Save" button defined with the \l AcceptRole.
- \value Cancel A "Cancel" button defined with the \l RejectRole.
- \value Close A "Close" button defined with the \l RejectRole.
- \value Discard A "Discard" or "Don't Save" button, depending on the platform,
- defined with the \l DestructiveRole.
- \value Apply An "Apply" button defined with the \l ApplyRole.
- \value Reset A "Reset" button defined with the \l ResetRole.
- \value RestoreDefaults A "Restore Defaults" button defined with the \l ResetRole.
- \value Help A "Help" button defined with the \l HelpRole.
- \value SaveAll A "Save All" button defined with the \l AcceptRole.
- \value Yes A "Yes" button defined with the \l YesRole.
- \value YesToAll A "Yes to All" button defined with the \l YesRole.
- \value No A "No" button defined with the \l NoRole.
- \value NoToAll A "No to All" button defined with the \l NoRole.
- \value Abort An "Abort" button defined with the \l RejectRole.
- \value Retry A "Retry" button defined with the \l AcceptRole.
- \value Ignore An "Ignore" button defined with the \l AcceptRole.
-
- \value NoButton An invalid button.
-
- \omitvalue FirstButton
- \omitvalue LastButton
-
- The following values are obsolete:
-
- \value YesAll Use YesToAll instead.
- \value NoAll Use NoToAll instead.
- \value Default Use the \c defaultButton argument of
- information(), warning(), etc. instead, or call
- setDefaultButton().
- \value Escape Call setEscapeButton() instead.
- \value FlagMask
- \value ButtonMask
-
- \sa ButtonRole, standardButtons
-*/
-
-/*!
- \fn void QMessageBox::buttonClicked(QAbstractButton *button)
-
- This signal is emitted whenever a button is clicked inside the QMessageBox.
- The button that was clicked in returned in \a button.
-*/
-
-/*!
- Constructs a message box with no text and no buttons. \a parent is
- passed to the QDialog constructor.
-
- On Mac OS X, if you want your message box to appear
- as a Qt::Sheet of its \a parent, set the message box's
- \l{setWindowModality()} {window modality} to Qt::WindowModal or use open().
- Otherwise, the message box will be a standard dialog.
-
-*/
-QMessageBox::QMessageBox(QWidget *parent)
- : QDialog(*new QMessageBoxPrivate, parent, Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint)
-{
- Q_D(QMessageBox);
- d->init();
-}
-
-/*!
- Constructs a message box with the given \a icon, \a title, \a
- text, and standard \a buttons. Standard or custom buttons can be
- added at any time using addButton(). The \a parent and \a f
- arguments are passed to the QDialog constructor.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- On Mac OS X, if \a parent is not 0 and you want your message box
- to appear as a Qt::Sheet of that parent, set the message box's
- \l{setWindowModality()} {window modality} to Qt::WindowModal
- (default). Otherwise, the message box will be a standard dialog.
-
- \sa setWindowTitle(), setText(), setIcon(), setStandardButtons()
-*/
-QMessageBox::QMessageBox(Icon icon, const QString &title, const QString &text,
- StandardButtons buttons, QWidget *parent,
- Qt::WindowFlags f)
-: QDialog(*new QMessageBoxPrivate, parent, f | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint)
-{
- Q_D(QMessageBox);
- d->init(title, text);
- setIcon(icon);
- if (buttons != NoButton)
- setStandardButtons(buttons);
-}
-
-/*!
- Destroys the message box.
-*/
-QMessageBox::~QMessageBox()
-{
-}
-
-/*!
- \since 4.2
-
- Adds the given \a button to the message box with the specified \a
- role.
-
- \sa removeButton(), button(), setStandardButtons()
-*/
-void QMessageBox::addButton(QAbstractButton *button, ButtonRole role)
-{
- Q_D(QMessageBox);
- if (!button)
- return;
- removeButton(button);
- d->buttonBox->addButton(button, (QDialogButtonBox::ButtonRole)role);
- d->customButtonList.append(button);
- d->autoAddOkButton = false;
-}
-
-/*!
- \since 4.2
- \overload
-
- Creates a button with the given \a text, adds it to the message box for the
- specified \a role, and returns it.
-*/
-QPushButton *QMessageBox::addButton(const QString& text, ButtonRole role)
-{
- Q_D(QMessageBox);
- QPushButton *pushButton = new QPushButton(text);
- addButton(pushButton, role);
- d->updateSize();
- return pushButton;
-}
-
-/*!
- \since 4.2
- \overload
-
- Adds a standard \a button to the message box if it is valid to do so, and
- returns the push button.
-
- \sa setStandardButtons()
-*/
-QPushButton *QMessageBox::addButton(StandardButton button)
-{
- Q_D(QMessageBox);
- QPushButton *pushButton = d->buttonBox->addButton((QDialogButtonBox::StandardButton)button);
- if (pushButton)
- d->autoAddOkButton = false;
- return pushButton;
-}
-
-/*!
- \since 4.2
-
- Removes \a button from the button box without deleting it.
-
- \sa addButton(), setStandardButtons()
-*/
-void QMessageBox::removeButton(QAbstractButton *button)
-{
- Q_D(QMessageBox);
- d->customButtonList.removeAll(button);
- if (d->escapeButton == button)
- d->escapeButton = 0;
- if (d->defaultButton == button)
- d->defaultButton = 0;
- d->buttonBox->removeButton(button);
- d->updateSize();
-}
-
-/*!
- \property QMessageBox::standardButtons
- \brief collection of standard buttons in the message box
- \since 4.2
-
- This property controls which standard buttons are used by the message box.
-
- By default, this property contains no standard buttons.
-
- \sa addButton()
-*/
-void QMessageBox::setStandardButtons(StandardButtons buttons)
-{
- Q_D(QMessageBox);
- d->buttonBox->setStandardButtons(QDialogButtonBox::StandardButtons(int(buttons)));
-
- QList<QAbstractButton *> buttonList = d->buttonBox->buttons();
- if (!buttonList.contains(d->escapeButton))
- d->escapeButton = 0;
- if (!buttonList.contains(d->defaultButton))
- d->defaultButton = 0;
- d->autoAddOkButton = false;
- d->updateSize();
-}
-
-QMessageBox::StandardButtons QMessageBox::standardButtons() const
-{
- Q_D(const QMessageBox);
- return QMessageBox::StandardButtons(int(d->buttonBox->standardButtons()));
-}
-
-/*!
- \since 4.2
-
- Returns the standard button enum value corresponding to the given \a button,
- or NoButton if the given \a button isn't a standard button.
-
- \sa button(), standardButtons()
-*/
-QMessageBox::StandardButton QMessageBox::standardButton(QAbstractButton *button) const
-{
- Q_D(const QMessageBox);
- return (QMessageBox::StandardButton)d->buttonBox->standardButton(button);
-}
-
-/*!
- \since 4.2
-
- Returns a pointer corresponding to the standard button \a which,
- or 0 if the standard button doesn't exist in this message box.
-
- \sa standardButtons, standardButton()
-*/
-QAbstractButton *QMessageBox::button(StandardButton which) const
-{
- Q_D(const QMessageBox);
- return d->buttonBox->button(QDialogButtonBox::StandardButton(which));
-}
-
-/*!
- \since 4.2
-
- Returns the button that is activated when escape is pressed.
-
- By default, QMessageBox attempts to automatically detect an
- escape button as follows:
-
- \list 1
- \o If there is only one button, it is made the escape button.
- \o If there is a \l Cancel button, it is made the escape button.
- \o On Mac OS X only, if there is exactly one button with the role
- QMessageBox::RejectRole, it is made the escape button.
- \endlist
-
- When an escape button could not be automatically detected, pressing
- \key Esc has no effect.
-
- \sa addButton()
-*/
-QAbstractButton *QMessageBox::escapeButton() const
-{
- Q_D(const QMessageBox);
- return d->escapeButton;
-}
-
-/*!
- \since 4.2
-
- Sets the button that gets activated when the \key Escape key is
- pressed to \a button.
-
- \sa addButton(), clickedButton()
-*/
-void QMessageBox::setEscapeButton(QAbstractButton *button)
-{
- Q_D(QMessageBox);
- if (d->buttonBox->buttons().contains(button))
- d->escapeButton = button;
-}
-
-/*!
- \since 4.3
-
- Sets the buttons that gets activated when the \key Escape key is
- pressed to \a button.
-
- \sa addButton(), clickedButton()
-*/
-void QMessageBox::setEscapeButton(QMessageBox::StandardButton button)
-{
- Q_D(QMessageBox);
- setEscapeButton(d->buttonBox->button(QDialogButtonBox::StandardButton(button)));
-}
-
-void QMessageBoxPrivate::detectEscapeButton()
-{
- if (escapeButton) { // escape button explicitly set
- detectedEscapeButton = escapeButton;
- return;
- }
-
- // Cancel button automatically becomes escape button
- detectedEscapeButton = buttonBox->button(QDialogButtonBox::Cancel);
- if (detectedEscapeButton)
- return;
-
- // If there is only one button, make it the escape button
- const QList<QAbstractButton *> buttons = buttonBox->buttons();
- if (buttons.count() == 1) {
- detectedEscapeButton = buttons.first();
- return;
- }
-
- // if the message box has one RejectRole button, make it the escape button
- for (int i = 0; i < buttons.count(); i++) {
- if (buttonBox->buttonRole(buttons.at(i)) == QDialogButtonBox::RejectRole) {
- if (detectedEscapeButton) { // already detected!
- detectedEscapeButton = 0;
- break;
- }
- detectedEscapeButton = buttons.at(i);
- }
- }
- if (detectedEscapeButton)
- return;
-
- // if the message box has one NoRole button, make it the escape button
- for (int i = 0; i < buttons.count(); i++) {
- if (buttonBox->buttonRole(buttons.at(i)) == QDialogButtonBox::NoRole) {
- if (detectedEscapeButton) { // already detected!
- detectedEscapeButton = 0;
- break;
- }
- detectedEscapeButton = buttons.at(i);
- }
- }
-}
-
-/*!
- \since 4.2
-
- Returns the button that was clicked by the user,
- or 0 if the user hit the \key Esc key and
- no \l{setEscapeButton()}{escape button} was set.
-
- If exec() hasn't been called yet, returns 0.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp 3
-
- \sa standardButton(), button()
-*/
-QAbstractButton *QMessageBox::clickedButton() const
-{
- Q_D(const QMessageBox);
- return d->clickedButton;
-}
-
-/*!
- \since 4.2
-
- Returns the button that should be the message box's
- \l{QPushButton::setDefault()}{default button}. Returns 0
- if no default button was set.
-
- \sa addButton(), QPushButton::setDefault()
-*/
-QPushButton *QMessageBox::defaultButton() const
-{
- Q_D(const QMessageBox);
- return d->defaultButton;
-}
-
-/*!
- \since 4.2
-
- Sets the message box's \l{QPushButton::setDefault()}{default button}
- to \a button.
-
- \sa addButton(), QPushButton::setDefault()
-*/
-void QMessageBox::setDefaultButton(QPushButton *button)
-{
- Q_D(QMessageBox);
- if (!d->buttonBox->buttons().contains(button))
- return;
- d->defaultButton = button;
- button->setDefault(true);
- button->setFocus();
-}
-
-/*!
- \since 4.3
-
- Sets the message box's \l{QPushButton::setDefault()}{default button}
- to \a button.
-
- \sa addButton(), QPushButton::setDefault()
-*/
-void QMessageBox::setDefaultButton(QMessageBox::StandardButton button)
-{
- Q_D(QMessageBox);
- setDefaultButton(d->buttonBox->button(QDialogButtonBox::StandardButton(button)));
-}
-
-/*!
- \property QMessageBox::text
- \brief the message box text to be displayed.
-
- The text will be interpreted either as a plain text or as rich text,
- depending on the text format setting (\l QMessageBox::textFormat).
- The default setting is Qt::AutoText, i.e., the message box will try
- to auto-detect the format of the text.
-
- The default value of this property is an empty string.
-
- \sa textFormat, QMessageBox::informativeText, QMessageBox::detailedText
-*/
-QString QMessageBox::text() const
-{
- Q_D(const QMessageBox);
- return d->label->text();
-}
-
-void QMessageBox::setText(const QString &text)
-{
- Q_D(QMessageBox);
- d->label->setText(text);
- d->label->setWordWrap(d->label->textFormat() == Qt::RichText
- || (d->label->textFormat() == Qt::AutoText && Qt::mightBeRichText(text)));
- d->updateSize();
-}
-
-/*!
- \enum QMessageBox::Icon
-
- This enum has the following values:
-
- \value NoIcon the message box does not have any icon.
-
- \value Question an icon indicating that
- the message is asking a question.
-
- \value Information an icon indicating that
- the message is nothing out of the ordinary.
-
- \value Warning an icon indicating that the
- message is a warning, but can be dealt with.
-
- \value Critical an icon indicating that
- the message represents a critical problem.
-
-*/
-
-/*!
- \property QMessageBox::icon
- \brief the message box's icon
-
- The icon of the message box can be specified with one of the
- values:
-
- \list
- \o QMessageBox::NoIcon
- \o QMessageBox::Question
- \o QMessageBox::Information
- \o QMessageBox::Warning
- \o QMessageBox::Critical
- \endlist
-
- The default is QMessageBox::NoIcon.
-
- The pixmap used to display the actual icon depends on the current
- \l{QWidget::style()} {GUI style}. You can also set a custom pixmap
- for the icon by setting the \l{QMessageBox::iconPixmap} {icon
- pixmap} property.
-
- \sa iconPixmap
-*/
-QMessageBox::Icon QMessageBox::icon() const
-{
- Q_D(const QMessageBox);
- return d->icon;
-}
-
-void QMessageBox::setIcon(Icon icon)
-{
- Q_D(QMessageBox);
- setIconPixmap(QMessageBoxPrivate::standardIcon((QMessageBox::Icon)icon,
- this));
- d->icon = icon;
-}
-
-/*!
- \property QMessageBox::iconPixmap
- \brief the current icon
-
- The icon currently used by the message box. Note that it's often
- hard to draw one pixmap that looks appropriate in all GUI styles;
- you may want to supply a different pixmap for each platform.
-
- By default, this property is undefined.
-
- \sa icon
-*/
-QPixmap QMessageBox::iconPixmap() const
-{
- Q_D(const QMessageBox);
- if (d->iconLabel && d->iconLabel->pixmap())
- return *d->iconLabel->pixmap();
- return QPixmap();
-}
-
-void QMessageBox::setIconPixmap(const QPixmap &pixmap)
-{
- Q_D(QMessageBox);
- d->iconLabel->setPixmap(pixmap);
- d->updateSize();
- d->icon = NoIcon;
-}
-
-/*!
- \property QMessageBox::textFormat
- \brief the format of the text displayed by the message box
-
- The current text format used by the message box. See the \l
- Qt::TextFormat enum for an explanation of the possible options.
-
- The default format is Qt::AutoText.
-
- \sa setText()
-*/
-Qt::TextFormat QMessageBox::textFormat() const
-{
- Q_D(const QMessageBox);
- return d->label->textFormat();
-}
-
-void QMessageBox::setTextFormat(Qt::TextFormat format)
-{
- Q_D(QMessageBox);
- d->label->setTextFormat(format);
- d->label->setWordWrap(format == Qt::RichText
- || (format == Qt::AutoText && Qt::mightBeRichText(d->label->text())));
- d->updateSize();
-}
-
-/*!
- \reimp
-*/
-bool QMessageBox::event(QEvent *e)
-{
- bool result =QDialog::event(e);
- switch (e->type()) {
- case QEvent::LayoutRequest:
- d_func()->updateSize();
- break;
- case QEvent::LanguageChange:
- d_func()->retranslateStrings();
- break;
-#ifdef Q_WS_WINCE
- case QEvent::OkRequest:
- case QEvent::HelpRequest: {
- QString bName =
- (e->type() == QEvent::OkRequest)
- ? QApplication::translate("QMessageBox", "OK")
- : QApplication::translate("QMessageBox", "Help");
- QList<QPushButton*> list = findChildren<QPushButton*>();
- for (int i=0; i<list.size(); ++i) {
- QPushButton *pb = list.at(i);
- if (pb->text() == bName) {
- if (pb->isEnabled())
- pb->click();
- return pb->isEnabled();
- }
- }
- }
-#endif
- default:
- break;
- }
- return result;
-}
-
-/*!
- \reimp
-*/
-void QMessageBox::resizeEvent(QResizeEvent *event)
-{
- QDialog::resizeEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QMessageBox::closeEvent(QCloseEvent *e)
-{
- Q_D(QMessageBox);
- if (!d->detectedEscapeButton) {
- e->ignore();
- return;
- }
- QDialog::closeEvent(e);
- d->clickedButton = d->detectedEscapeButton;
- setResult(d->execReturnCode(d->detectedEscapeButton));
-}
-
-/*!
- \reimp
-*/
-void QMessageBox::changeEvent(QEvent *ev)
-{
- Q_D(QMessageBox);
- switch (ev->type()) {
- case QEvent::StyleChange:
- {
- if (d->icon != NoIcon)
- setIcon(d->icon);
- Qt::TextInteractionFlags flags(style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, 0, this));
- d->label->setTextInteractionFlags(flags);
- d->buttonBox->setCenterButtons(style()->styleHint(QStyle::SH_MessageBox_CenterButtons, 0, this));
- if (d->informativeLabel)
- d->informativeLabel->setTextInteractionFlags(flags);
- // intentional fall through
- }
- case QEvent::FontChange:
- case QEvent::ApplicationFontChange:
-#ifdef Q_WS_MAC
- {
- QFont f = font();
- f.setBold(true);
- d->label->setFont(f);
- }
-#endif
- default:
- break;
- }
- QDialog::changeEvent(ev);
-}
-
-/*!
- \reimp
-*/
-void QMessageBox::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QMessageBox);
- if (e->key() == Qt::Key_Escape
-#ifdef Q_WS_MAC
- || (e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Period)
-#endif
- ) {
- if (d->detectedEscapeButton) {
-#ifdef Q_WS_MAC
- d->detectedEscapeButton->animateClick();
-#else
- d->detectedEscapeButton->click();
-#endif
- }
- return;
- }
-
-#if defined (Q_OS_WIN) && !defined(QT_NO_CLIPBOARD) && !defined(QT_NO_SHORTCUT)
- if (e == QKeySequence::Copy) {
- QString separator = QString::fromLatin1("---------------------------\n");
- QString textToCopy = separator;
- separator.prepend(QLatin1Char('\n'));
- textToCopy += windowTitle() + separator; // title
- textToCopy += d->label->text() + separator; // text
-
- if (d->informativeLabel)
- textToCopy += d->informativeLabel->text() + separator;
-
- QString buttonTexts;
- QList<QAbstractButton *> buttons = d->buttonBox->buttons();
- for (int i = 0; i < buttons.count(); i++) {
- buttonTexts += buttons[i]->text() + QLatin1String(" ");
- }
- textToCopy += buttonTexts + separator;
-
- QApplication::clipboard()->setText(textToCopy);
- return;
- }
-#endif //QT_NO_SHORTCUT QT_NO_CLIPBOARD Q_OS_WIN
-
-#ifndef QT_NO_SHORTCUT
- if (!(e->modifiers() & Qt::AltModifier)) {
- int key = e->key() & ~((int)Qt::MODIFIER_MASK|(int)Qt::UNICODE_ACCEL);
- if (key) {
- const QList<QAbstractButton *> buttons = d->buttonBox->buttons();
- for (int i = 0; i < buttons.count(); ++i) {
- QAbstractButton *pb = buttons.at(i);
- int acc = pb->shortcut() & ~((int)Qt::MODIFIER_MASK|(int)Qt::UNICODE_ACCEL);
- if (acc == key) {
- pb->animateClick();
- return;
- }
- }
- }
- }
-#endif
- QDialog::keyPressEvent(e);
-}
-
-#ifdef Q_WS_WINCE
-/*!
- \reimp
-*/
-void QMessageBox::setVisible(bool visible)
-{
- Q_D(QMessageBox);
- if (visible)
- d->hideSpecial();
- QDialog::setVisible(visible);
-}
-#endif
-
-
-/*!
- \overload
-
- Opens the dialog and connects its finished() or buttonClicked() signal to
- the slot specified by \a receiver and \a member. If the slot in \a member
- has a pointer for its first parameter the connection is to buttonClicked(),
- otherwise the connection is to finished().
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QMessageBox::open(QObject *receiver, const char *member)
-{
- Q_D(QMessageBox);
- const char *signal = member && strchr(member, '*') ? SIGNAL(buttonClicked(QAbstractButton*))
- : SIGNAL(finished(int));
- connect(this, signal, receiver, member);
- d->signalToDisconnectOnClose = signal;
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-/*!
- \since 4.5
-
- Returns a list of all the buttons that have been added to the message box.
-
- \sa buttonRole(), addButton(), removeButton()
-*/
-QList<QAbstractButton *> QMessageBox::buttons() const
-{
- Q_D(const QMessageBox);
- return d->buttonBox->buttons();
-}
-
-/*!
- \since 4.5
-
- Returns the button role for the specified \a button. This function returns
- \l InvalidRole if \a button is 0 or has not been added to the message box.
-
- \sa buttons(), addButton()
-*/
-QMessageBox::ButtonRole QMessageBox::buttonRole(QAbstractButton *button) const
-{
- Q_D(const QMessageBox);
- return QMessageBox::ButtonRole(d->buttonBox->buttonRole(button));
-}
-
-/*!
- \reimp
-*/
-void QMessageBox::showEvent(QShowEvent *e)
-{
- Q_D(QMessageBox);
- if (d->autoAddOkButton) {
- addButton(Ok);
-#if defined(Q_WS_WINCE)
- d->hideSpecial();
-#endif
- }
- if (d->detailsButton)
- addButton(d->detailsButton, QMessageBox::ActionRole);
- d->detectEscapeButton();
- d->updateSize();
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::Alert);
-#endif
-#ifdef Q_WS_WIN
- HMENU systemMenu = GetSystemMenu((HWND)winId(), FALSE);
- if (!d->detectedEscapeButton) {
- EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED);
- }
- else {
- EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED);
- }
-#endif
- QDialog::showEvent(e);
-}
-
-
-static QMessageBox::StandardButton showNewMessageBox(QWidget *parent,
- QMessageBox::Icon icon,
- const QString& title, const QString& text,
- QMessageBox::StandardButtons buttons,
- QMessageBox::StandardButton defaultButton)
-{
- // necessary for source compatibility with Qt 4.0 and 4.1
- // handles (Yes, No) and (Yes|Default, No)
- if (defaultButton && !(buttons & defaultButton))
- return (QMessageBox::StandardButton)
- QMessageBoxPrivate::showOldMessageBox(parent, icon, title,
- text, int(buttons),
- int(defaultButton), 0);
-
- QMessageBox msgBox(icon, title, text, QMessageBox::NoButton, parent);
- QDialogButtonBox *buttonBox = msgBox.findChild<QDialogButtonBox*>();
- Q_ASSERT(buttonBox != 0);
-
- uint mask = QMessageBox::FirstButton;
- while (mask <= QMessageBox::LastButton) {
- uint sb = buttons & mask;
- mask <<= 1;
- if (!sb)
- continue;
- QPushButton *button = msgBox.addButton((QMessageBox::StandardButton)sb);
- // Choose the first accept role as the default
- if (msgBox.defaultButton())
- continue;
- if ((defaultButton == QMessageBox::NoButton && buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
- || (defaultButton != QMessageBox::NoButton && sb == uint(defaultButton)))
- msgBox.setDefaultButton(button);
- }
- if (msgBox.exec() == -1)
- return QMessageBox::Cancel;
- return msgBox.standardButton(msgBox.clickedButton());
-}
-
-/*!
- \since 4.2
-
- Opens an information message box with the given \a title and
- \a text in front of the specified \a parent widget.
-
- The standard \a buttons are added to the message box.
- \a defaultButton specifies the button used when \key Enter is pressed.
- \a defaultButton must refer to a button that was given in \a buttons.
- If \a defaultButton is QMessageBox::NoButton, QMessageBox
- chooses a suitable default automatically.
-
- Returns the identity of the standard button that was clicked. If
- \key Esc was pressed instead, the \l{Default and Escape Keys}
- {escape button} is returned.
-
- The message box is an \l{Qt::ApplicationModal}{application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa question(), warning(), critical()
-*/
-QMessageBox::StandardButton QMessageBox::information(QWidget *parent, const QString &title,
- const QString& text, StandardButtons buttons,
- StandardButton defaultButton)
-{
- return showNewMessageBox(parent, Information, title, text, buttons,
- defaultButton);
-}
-
-
-/*!
- \since 4.2
-
- Opens a question message box with the given \a title and \a
- text in front of the specified \a parent widget.
-
- The standard \a buttons are added to the message box. \a
- defaultButton specifies the button used when \key Enter is
- pressed. \a defaultButton must refer to a button that was given in \a buttons.
- If \a defaultButton is QMessageBox::NoButton, QMessageBox
- chooses a suitable default automatically.
-
- Returns the identity of the standard button that was clicked. If
- \key Esc was pressed instead, the \l{Default and Escape Keys}
- {escape button} is returned.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), warning(), critical()
-*/
-QMessageBox::StandardButton QMessageBox::question(QWidget *parent, const QString &title,
- const QString& text, StandardButtons buttons,
- StandardButton defaultButton)
-{
- return showNewMessageBox(parent, Question, title, text, buttons, defaultButton);
-}
-
-/*!
- \since 4.2
-
- Opens a warning message box with the given \a title and \a
- text in front of the specified \a parent widget.
-
- The standard \a buttons are added to the message box. \a
- defaultButton specifies the button used when \key Enter is
- pressed. \a defaultButton must refer to a button that was given in \a buttons.
- If \a defaultButton is QMessageBox::NoButton, QMessageBox
- chooses a suitable default automatically.
-
- Returns the identity of the standard button that was clicked. If
- \key Esc was pressed instead, the \l{Default and Escape Keys}
- {escape button} is returned.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa question(), information(), critical()
-*/
-QMessageBox::StandardButton QMessageBox::warning(QWidget *parent, const QString &title,
- const QString& text, StandardButtons buttons,
- StandardButton defaultButton)
-{
- return showNewMessageBox(parent, Warning, title, text, buttons, defaultButton);
-}
-
-/*!
- \since 4.2
-
- Opens a critical message box with the given \a title and \a
- text in front of the specified \a parent widget.
-
- The standard \a buttons are added to the message box. \a
- defaultButton specifies the button used when \key Enter is
- pressed. \a defaultButton must refer to a button that was given in \a buttons.
- If \a defaultButton is QMessageBox::NoButton, QMessageBox
- chooses a suitable default automatically.
-
- Returns the identity of the standard button that was clicked. If
- \key Esc was pressed instead, the \l{Default and Escape Keys}
- {escape button} is returned.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa question(), warning(), information()
-*/
-QMessageBox::StandardButton QMessageBox::critical(QWidget *parent, const QString &title,
- const QString& text, StandardButtons buttons,
- StandardButton defaultButton)
-{
- return showNewMessageBox(parent, Critical, title, text, buttons, defaultButton);
-}
-
-/*!
- Displays a simple about box with title \a title and text \a
- text. The about box's parent is \a parent.
-
- about() looks for a suitable icon in four locations:
-
- \list 1
- \o It prefers \link QWidget::windowIcon() parent->icon() \endlink
- if that exists.
- \o If not, it tries the top-level widget containing \a parent.
- \o If that fails, it tries the \link
- QApplication::activeWindow() active window. \endlink
- \o As a last resort it uses the Information icon.
- \endlist
-
- The about box has a single button labelled "OK". On Mac OS X, the
- about box is popped up as a modeless window; on other platforms,
- it is currently application modal.
-
- \sa QWidget::windowIcon(), QApplication::activeWindow()
-*/
-void QMessageBox::about(QWidget *parent, const QString &title, const QString &text)
-{
-#ifdef Q_WS_MAC
- static QPointer<QMessageBox> oldMsgBox;
-
- if (oldMsgBox && oldMsgBox->text() == text) {
- oldMsgBox->show();
- oldMsgBox->raise();
- oldMsgBox->activateWindow();
- return;
- }
-#endif
-
- QMessageBox *msgBox = new QMessageBox(title, text, Information, 0, 0, 0, parent
-#ifdef Q_WS_MAC
- , Qt::WindowTitleHint | Qt::WindowSystemMenuHint
-#endif
- );
- msgBox->setAttribute(Qt::WA_DeleteOnClose);
- QIcon icon = msgBox->windowIcon();
- QSize size = icon.actualSize(QSize(64, 64));
- msgBox->setIconPixmap(icon.pixmap(size));
-
- // should perhaps be a style hint
-#ifdef Q_WS_MAC
- oldMsgBox = msgBox;
-#if 0
- // ### doesn't work until close button is enabled in title bar
- msgBox->d_func()->autoAddOkButton = false;
-#else
- msgBox->d_func()->buttonBox->setCenterButtons(true);
-#endif
- msgBox->show();
-#else
- msgBox->exec();
-#endif
-}
-
-/*!
- Displays a simple message box about Qt, with the given \a title
- and centered over \a parent (if \a parent is not 0). 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.
-
- QApplication provides this functionality as a slot.
-
- On Mac OS X, the about box is popped up as a modeless window; on
- other platforms, it is currently application modal.
-
- \sa QApplication::aboutQt()
-*/
-void QMessageBox::aboutQt(QWidget *parent, const QString &title)
-{
-#ifdef Q_WS_MAC
- static QPointer<QMessageBox> oldMsgBox;
-
- if (oldMsgBox) {
- oldMsgBox->show();
- oldMsgBox->raise();
- oldMsgBox->activateWindow();
- return;
- }
-#endif
-
- QString translatedTextAboutQtCaption;
- translatedTextAboutQtCaption = QMessageBox::tr(
- "<h3>About Qt</h3>"
- "<p>This program uses Qt version %1.</p>"
- ).arg(QLatin1String(QT_VERSION_STR));
- QString translatedTextAboutQtText;
- translatedTextAboutQtText = QMessageBox::tr(
- "<p>Qt is a C++ toolkit for cross-platform application "
- "development.</p>"
- "<p>Qt provides single-source portability across MS&nbsp;Windows, "
- "Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. "
- "Qt is also available for embedded devices as Qt for Embedded Linux "
- "and Qt for Windows CE.</p>"
- "<p>Qt is available under three different licensing options designed "
- "to accommodate the needs of our various users.</p>"
- "<p>Qt licensed under our commercial license agreement is appropriate "
- "for development of proprietary/commercial software where you do not "
- "want to share any source code with third parties or otherwise cannot "
- "comply with the terms of the GNU LGPL version 2.1 or GNU GPL version "
- "3.0.</p>"
- "<p>Qt licensed under the GNU LGPL version 2.1 is appropriate for the "
- "development of Qt applications (proprietary or open source) provided "
- "you can comply with the terms and conditions of the GNU LGPL version "
- "2.1.</p>"
- "<p>Qt licensed under the GNU General Public License version 3.0 is "
- "appropriate for the development of Qt applications where you wish to "
- "use such applications in combination with software subject to the "
- "terms of the GNU GPL version 3.0 or where you are otherwise willing "
- "to comply with the terms of the GNU GPL version 3.0.</p>"
- "<p>Please see <a href=\"http://qt.nokia.com/products/licensing\">qt.nokia.com/products/licensing</a> "
- "for an overview of Qt licensing.</p>"
- "<p>Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).</p>"
- "<p>Qt is a Nokia product. See <a href=\"http://qt.nokia.com/\">qt.nokia.com</a> "
- "for more information.</p>"
- );
- QMessageBox *msgBox = new QMessageBox(parent);
- msgBox->setAttribute(Qt::WA_DeleteOnClose);
- msgBox->setWindowTitle(title.isEmpty() ? tr("About Qt") : title);
- msgBox->setText(translatedTextAboutQtCaption);
- msgBox->setInformativeText(translatedTextAboutQtText);
-
- QPixmap pm(QLatin1String(":/trolltech/qmessagebox/images/qtlogo-64.png"));
- if (!pm.isNull())
- msgBox->setIconPixmap(pm);
-#if defined(Q_WS_WINCE)
- msgBox->setDefaultButton(msgBox->addButton(QMessageBox::Ok));
-#endif
-
- // should perhaps be a style hint
-#ifdef Q_WS_MAC
- oldMsgBox = msgBox;
-#if 0
- // ### doesn't work until close button is enabled in title bar
- msgBox->d_func()->autoAddOkButton = false;
-#else
- msgBox->d_func()->buttonBox->setCenterButtons(true);
-#endif
- msgBox->show();
-#else
- msgBox->exec();
-#endif
-}
-
-/*!
- \internal
-*/
-QSize QMessageBox::sizeHint() const
-{
- // ### Qt 5: remove
- return QDialog::sizeHint();
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Source and binary compatibility routines for 4.0 and 4.1
-
-static QMessageBox::StandardButton newButton(int button)
-{
- // this is needed for source compatibility with Qt 4.0 and 4.1
- if (button == QMessageBox::NoButton || (button & NewButtonMask))
- return QMessageBox::StandardButton(button & QMessageBox::ButtonMask);
-
-#if QT_VERSION < 0x050000
- // this is needed for binary compatibility with Qt 4.0 and 4.1
- switch (button & Old_ButtonMask) {
- case Old_Ok:
- return QMessageBox::Ok;
- case Old_Cancel:
- return QMessageBox::Cancel;
- case Old_Yes:
- return QMessageBox::Yes;
- case Old_No:
- return QMessageBox::No;
- case Old_Abort:
- return QMessageBox::Abort;
- case Old_Retry:
- return QMessageBox::Retry;
- case Old_Ignore:
- return QMessageBox::Ignore;
- case Old_YesAll:
- return QMessageBox::YesToAll;
- case Old_NoAll:
- return QMessageBox::NoToAll;
- default:
- return QMessageBox::NoButton;
- }
-#endif
-}
-
-static bool detectedCompat(int button0, int button1, int button2)
-{
- if (button0 != 0 && !(button0 & NewButtonMask))
- return true;
- if (button1 != 0 && !(button1 & NewButtonMask))
- return true;
- if (button2 != 0 && !(button2 & NewButtonMask))
- return true;
- return false;
-}
-
-QAbstractButton *QMessageBoxPrivate::findButton(int button0, int button1, int button2, int flags)
-{
- Q_Q(QMessageBox);
- int button = 0;
-
- if (button0 & flags) {
- button = button0;
- } else if (button1 & flags) {
- button = button1;
- } else if (button2 & flags) {
- button = button2;
- }
- return q->button(newButton(button));
-}
-
-void QMessageBoxPrivate::addOldButtons(int button0, int button1, int button2)
-{
- Q_Q(QMessageBox);
- q->addButton(newButton(button0));
- q->addButton(newButton(button1));
- q->addButton(newButton(button2));
- q->setDefaultButton(
- static_cast<QPushButton *>(findButton(button0, button1, button2, QMessageBox::Default)));
- q->setEscapeButton(findButton(button0, button1, button2, QMessageBox::Escape));
- compatMode = detectedCompat(button0, button1, button2);
-}
-
-QAbstractButton *QMessageBoxPrivate::abstractButtonForId(int id) const
-{
- Q_Q(const QMessageBox);
- QAbstractButton *result = customButtonList.value(id);
- if (result)
- return result;
- if (id & QMessageBox::FlagMask) // for compatibility with Qt 4.0/4.1 (even if it is silly)
- return 0;
- return q->button(newButton(id));
-}
-
-int QMessageBoxPrivate::showOldMessageBox(QWidget *parent, QMessageBox::Icon icon,
- const QString &title, const QString &text,
- int button0, int button1, int button2)
-{
- QMessageBox messageBox(icon, title, text, QMessageBox::NoButton, parent);
- messageBox.d_func()->addOldButtons(button0, button1, button2);
- return messageBox.exec();
-}
-
-int QMessageBoxPrivate::showOldMessageBox(QWidget *parent, QMessageBox::Icon icon,
- const QString &title, const QString &text,
- const QString &button0Text,
- const QString &button1Text,
- const QString &button2Text,
- int defaultButtonNumber,
- int escapeButtonNumber)
-{
- QMessageBox messageBox(icon, title, text, QMessageBox::NoButton, parent);
- QString myButton0Text = button0Text;
- if (myButton0Text.isEmpty())
- myButton0Text = QDialogButtonBox::tr("OK");
- messageBox.addButton(myButton0Text, QMessageBox::ActionRole);
- if (!button1Text.isEmpty())
- messageBox.addButton(button1Text, QMessageBox::ActionRole);
- if (!button2Text.isEmpty())
- messageBox.addButton(button2Text, QMessageBox::ActionRole);
-
- const QList<QAbstractButton *> &buttonList = messageBox.d_func()->customButtonList;
- messageBox.setDefaultButton(static_cast<QPushButton *>(buttonList.value(defaultButtonNumber)));
- messageBox.setEscapeButton(buttonList.value(escapeButtonNumber));
-
- return messageBox.exec();
-}
-
-void QMessageBoxPrivate::retranslateStrings()
-{
-#ifndef QT_NO_TEXTEDIT
- if (detailsButton)
- detailsButton->setLabel(detailsText->isHidden() ? ShowLabel : HideLabel);
-#endif
-}
-
-/*!
- \obsolete
-
- Constructs a message box with a \a title, a \a text, an \a icon,
- and up to three buttons.
-
- The \a icon must be one of the following:
- \list
- \o QMessageBox::NoIcon
- \o QMessageBox::Question
- \o QMessageBox::Information
- \o QMessageBox::Warning
- \o QMessageBox::Critical
- \endlist
-
- Each button, \a button0, \a button1 and \a button2, can have one
- of the following values:
- \list
- \o QMessageBox::NoButton
- \o QMessageBox::Ok
- \o QMessageBox::Cancel
- \o QMessageBox::Yes
- \o QMessageBox::No
- \o QMessageBox::Abort
- \o QMessageBox::Retry
- \o QMessageBox::Ignore
- \o QMessageBox::YesAll
- \o QMessageBox::NoAll
- \endlist
-
- Use QMessageBox::NoButton for the later parameters to have fewer
- than three buttons in your message box. If you don't specify any
- buttons at all, QMessageBox will provide an Ok button.
-
- One of the buttons can be OR-ed with the QMessageBox::Default
- flag to make it the default button (clicked when Enter is
- pressed).
-
- One of the buttons can be OR-ed with the QMessageBox::Escape flag
- to make it the cancel or close button (clicked when \key Esc is
- pressed).
-
- \snippet doc/src/snippets/dialogs/dialogs.cpp 2
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- The \a parent and \a f arguments are passed to
- the QDialog constructor.
-
- \sa setWindowTitle(), setText(), setIcon()
-*/
-QMessageBox::QMessageBox(const QString &title, const QString &text, Icon icon,
- int button0, int button1, int button2, QWidget *parent,
- Qt::WindowFlags f)
- : QDialog(*new QMessageBoxPrivate, parent,
- f /*| Qt::MSWindowsFixedSizeDialogHint #### */| Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint)
-{
- Q_D(QMessageBox);
- d->init(title, text);
- setIcon(icon);
- d->addOldButtons(button0, button1, button2);
-}
-
-/*!
- \obsolete
-
- Opens an information message box with the given \a title and the
- \a text. The dialog may have up to three buttons. Each of the
- buttons, \a button0, \a button1 and \a button2 may be set to one
- of the following values:
-
- \list
- \o QMessageBox::NoButton
- \o QMessageBox::Ok
- \o QMessageBox::Cancel
- \o QMessageBox::Yes
- \o QMessageBox::No
- \o QMessageBox::Abort
- \o QMessageBox::Retry
- \o QMessageBox::Ignore
- \o QMessageBox::YesAll
- \o QMessageBox::NoAll
- \endlist
-
- If you don't want all three buttons, set the last button, or last
- two buttons to QMessageBox::NoButton.
-
- One button can be OR-ed with QMessageBox::Default, and one
- button can be OR-ed with QMessageBox::Escape.
-
- Returns the identity (QMessageBox::Ok, or QMessageBox::No, etc.)
- of the button that was clicked.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa question(), warning(), critical()
-*/
-int QMessageBox::information(QWidget *parent, const QString &title, const QString& text,
- int button0, int button1, int button2)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Information, title, text,
- button0, button1, button2);
-}
-
-/*!
- \obsolete
- \overload
-
- Displays an information message box with the given \a title and
- \a text, as well as one, two or three buttons. Returns the index
- of the button that was clicked (0, 1 or 2).
-
- \a button0Text is the text of the first button, and is optional.
- If \a button0Text is not supplied, "OK" (translated) will be
- used. \a button1Text is the text of the second button, and is
- optional. \a button2Text is the text of the third button, and is
- optional. \a defaultButtonNumber (0, 1 or 2) is the index of the
- default button; pressing Return or Enter is the same as clicking
- the default button. It defaults to 0 (the first button). \a
- escapeButtonNumber is the index of the escape button; pressing
- \key Esc is the same as clicking this button. It defaults to -1;
- supply 0, 1 or 2 to make pressing \key Esc equivalent to clicking
- the relevant button.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa question(), warning(), critical()
-*/
-
-int QMessageBox::information(QWidget *parent, const QString &title, const QString& text,
- const QString& button0Text, const QString& button1Text,
- const QString& button2Text, int defaultButtonNumber,
- int escapeButtonNumber)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Information, title, text,
- button0Text, button1Text, button2Text,
- defaultButtonNumber, escapeButtonNumber);
-}
-
-/*!
- \obsolete
-
- Opens a question message box with the given \a title and \a text.
- The dialog may have up to three buttons. Each of the buttons, \a
- button0, \a button1 and \a button2 may be set to one of the
- following values:
-
- \list
- \o QMessageBox::NoButton
- \o QMessageBox::Ok
- \o QMessageBox::Cancel
- \o QMessageBox::Yes
- \o QMessageBox::No
- \o QMessageBox::Abort
- \o QMessageBox::Retry
- \o QMessageBox::Ignore
- \o QMessageBox::YesAll
- \o QMessageBox::NoAll
- \endlist
-
- If you don't want all three buttons, set the last button, or last
- two buttons to QMessageBox::NoButton.
-
- One button can be OR-ed with QMessageBox::Default, and one
- button can be OR-ed with QMessageBox::Escape.
-
- Returns the identity (QMessageBox::Yes, or QMessageBox::No, etc.)
- of the button that was clicked.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), warning(), critical()
-*/
-int QMessageBox::question(QWidget *parent, const QString &title, const QString& text,
- int button0, int button1, int button2)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Question, title, text,
- button0, button1, button2);
-}
-
-/*!
- \obsolete
- \overload
-
- Displays a question message box with the given \a title and \a
- text, as well as one, two or three buttons. Returns the index of
- the button that was clicked (0, 1 or 2).
-
- \a button0Text is the text of the first button, and is optional.
- If \a button0Text is not supplied, "OK" (translated) will be used.
- \a button1Text is the text of the second button, and is optional.
- \a button2Text is the text of the third button, and is optional.
- \a defaultButtonNumber (0, 1 or 2) is the index of the default
- button; pressing Return or Enter is the same as clicking the
- default button. It defaults to 0 (the first button). \a
- escapeButtonNumber is the index of the Escape button; pressing
- Escape is the same as clicking this button. It defaults to -1;
- supply 0, 1 or 2 to make pressing Escape equivalent to clicking
- the relevant button.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), warning(), critical()
-*/
-int QMessageBox::question(QWidget *parent, const QString &title, const QString& text,
- const QString& button0Text, const QString& button1Text,
- const QString& button2Text, int defaultButtonNumber,
- int escapeButtonNumber)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Question, title, text,
- button0Text, button1Text, button2Text,
- defaultButtonNumber, escapeButtonNumber);
-}
-
-
-/*!
- \obsolete
-
- Opens a warning message box with the given \a title and \a text.
- The dialog may have up to three buttons. Each of the button
- parameters, \a button0, \a button1 and \a button2 may be set to
- one of the following values:
-
- \list
- \o QMessageBox::NoButton
- \o QMessageBox::Ok
- \o QMessageBox::Cancel
- \o QMessageBox::Yes
- \o QMessageBox::No
- \o QMessageBox::Abort
- \o QMessageBox::Retry
- \o QMessageBox::Ignore
- \o QMessageBox::YesAll
- \o QMessageBox::NoAll
- \endlist
-
- If you don't want all three buttons, set the last button, or last
- two buttons to QMessageBox::NoButton.
-
- One button can be OR-ed with QMessageBox::Default, and one
- button can be OR-ed with QMessageBox::Escape.
-
- Returns the identity (QMessageBox::Ok or QMessageBox::No or ...)
- of the button that was clicked.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), question(), critical()
-*/
-int QMessageBox::warning(QWidget *parent, const QString &title, const QString& text,
- int button0, int button1, int button2)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Warning, title, text,
- button0, button1, button2);
-}
-
-/*!
- \obsolete
- \overload
-
- Displays a warning message box with the given \a title and \a
- text, as well as one, two, or three buttons. Returns the number
- of the button that was clicked (0, 1, or 2).
-
- \a button0Text is the text of the first button, and is optional.
- If \a button0Text is not supplied, "OK" (translated) will be used.
- \a button1Text is the text of the second button, and is optional,
- and \a button2Text is the text of the third button, and is
- optional. \a defaultButtonNumber (0, 1 or 2) is the index of the
- default button; pressing Return or Enter is the same as clicking
- the default button. It defaults to 0 (the first button). \a
- escapeButtonNumber is the index of the Escape button; pressing
- Escape is the same as clicking this button. It defaults to -1;
- supply 0, 1, or 2 to make pressing Escape equivalent to clicking
- the relevant button.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), question(), critical()
-*/
-int QMessageBox::warning(QWidget *parent, const QString &title, const QString& text,
- const QString& button0Text, const QString& button1Text,
- const QString& button2Text, int defaultButtonNumber,
- int escapeButtonNumber)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Warning, title, text,
- button0Text, button1Text, button2Text,
- defaultButtonNumber, escapeButtonNumber);
-}
-
-/*!
- \obsolete
-
- Opens a critical message box with the given \a title and \a text.
- The dialog may have up to three buttons. Each of the button
- parameters, \a button0, \a button1 and \a button2 may be set to
- one of the following values:
-
- \list
- \o QMessageBox::NoButton
- \o QMessageBox::Ok
- \o QMessageBox::Cancel
- \o QMessageBox::Yes
- \o QMessageBox::No
- \o QMessageBox::Abort
- \o QMessageBox::Retry
- \o QMessageBox::Ignore
- \o QMessageBox::YesAll
- \o QMessageBox::NoAll
- \endlist
-
- If you don't want all three buttons, set the last button, or last
- two buttons to QMessageBox::NoButton.
-
- One button can be OR-ed with QMessageBox::Default, and one
- button can be OR-ed with QMessageBox::Escape.
-
- Returns the identity (QMessageBox::Ok, or QMessageBox::No, etc.)
- of the button that was clicked.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), question(), warning()
-*/
-
-int QMessageBox::critical(QWidget *parent, const QString &title, const QString& text,
- int button0, int button1, int button2)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Critical, title, text,
- button0, button1, button2);
-}
-
-/*!
- \obsolete
- \overload
-
- Displays a critical error message box with the given \a title and
- \a text, as well as one, two, or three buttons. Returns the
- number of the button that was clicked (0, 1 or 2).
-
- \a button0Text is the text of the first button, and is optional.
- If \a button0Text is not supplied, "OK" (translated) will be used.
- \a button1Text is the text of the second button, and is optional,
- and \a button2Text is the text of the third button, and is
- optional. \a defaultButtonNumber (0, 1 or 2) is the index of the
- default button; pressing Return or Enter is the same as clicking
- the default button. It defaults to 0 (the first button). \a
- escapeButtonNumber is the index of the Escape button; pressing
- Escape is the same as clicking this button. It defaults to -1;
- supply 0, 1, or 2 to make pressing Escape equivalent to clicking
- the relevant button.
-
- The message box is an \l{Qt::ApplicationModal} {application modal}
- dialog box.
-
- \warning Do not delete \a parent during the execution of the dialog.
- If you want to do this, you should create the dialog
- yourself using one of the QMessageBox constructors.
-
- \sa information(), question(), warning()
-*/
-int QMessageBox::critical(QWidget *parent, const QString &title, const QString& text,
- const QString& button0Text, const QString& button1Text,
- const QString& button2Text, int defaultButtonNumber,
- int escapeButtonNumber)
-{
- return QMessageBoxPrivate::showOldMessageBox(parent, Critical, title, text,
- button0Text, button1Text, button2Text,
- defaultButtonNumber, escapeButtonNumber);
-}
-
-
-/*!
- \obsolete
-
- Returns the text of the message box button \a button, or
- an empty string if the message box does not contain the button.
-
- Use button() and QPushButton::text() instead.
-*/
-QString QMessageBox::buttonText(int button) const
-{
- Q_D(const QMessageBox);
-
- if (QAbstractButton *abstractButton = d->abstractButtonForId(button)) {
- return abstractButton->text();
- } else if (d->buttonBox->buttons().isEmpty() && (button == Ok || button == Old_Ok)) {
- // for compatibility with Qt 4.0/4.1
- return QDialogButtonBox::tr("OK");
- }
- return QString();
-}
-
-/*!
- \obsolete
-
- Sets the text of the message box button \a button to \a text.
- Setting the text of a button that is not in the message box is
- silently ignored.
-
- Use addButton() instead.
-*/
-void QMessageBox::setButtonText(int button, const QString &text)
-{
- Q_D(QMessageBox);
- if (QAbstractButton *abstractButton = d->abstractButtonForId(button)) {
- abstractButton->setText(text);
- } else if (d->buttonBox->buttons().isEmpty() && (button == Ok || button == Old_Ok)) {
- // for compatibility with Qt 4.0/4.1
- addButton(QMessageBox::Ok)->setText(text);
- }
-}
-
-#ifndef QT_NO_TEXTEDIT
-/*!
- \property QMessageBox::detailedText
- \brief the text to be displayed in the details area.
- \since 4.2
-
- The text will be interpreted as a plain text.
-
- By default, this property contains an empty string.
-
- \sa QMessageBox::text, QMessageBox::informativeText
-*/
-QString QMessageBox::detailedText() const
-{
- Q_D(const QMessageBox);
- return d->detailsText ? d->detailsText->text() : QString();
-}
-
-void QMessageBox::setDetailedText(const QString &text)
-{
- Q_D(QMessageBox);
- if (text.isEmpty()) {
- delete d->detailsText;
- d->detailsText = 0;
- removeButton(d->detailsButton);
- delete d->detailsButton;
- d->detailsButton = 0;
- return;
- }
-
- if (!d->detailsText) {
- d->detailsText = new QMessageBoxDetailsText(this);
- QGridLayout* grid = qobject_cast<QGridLayout*>(layout());
- if (grid)
- grid->addWidget(d->detailsText, grid->rowCount(), 0, 1, grid->columnCount());
- d->detailsText->hide();
- }
- if (!d->detailsButton)
- d->detailsButton = new DetailButton(this);
- d->detailsText->setText(text);
-}
-#endif // QT_NO_TEXTEDIT
-
-/*!
- \property QMessageBox::informativeText
-
- \brief the informative text that provides a fuller description for
- the message
-
- \since 4.2
-
- Infromative text can be used to expand upon the text() to give more
- information to the user. On the Mac, this text appears in small
- system font below the text(). On other platforms, it is simply
- appended to the existing text.
-
- By default, this property contains an empty string.
-
- \sa QMessageBox::text, QMessageBox::detailedText
-*/
-QString QMessageBox::informativeText() const
-{
- Q_D(const QMessageBox);
- return d->informativeLabel ? d->informativeLabel->text() : QString();
-}
-
-void QMessageBox::setInformativeText(const QString &text)
-{
- Q_D(QMessageBox);
- if (text.isEmpty()) {
- layout()->removeWidget(d->informativeLabel);
- delete d->informativeLabel;
- d->informativeLabel = 0;
-#ifndef Q_WS_MAC
- d->label->setContentsMargins(2, 0, 0, 0);
-#endif
- d->updateSize();
- return;
- }
-
- if (!d->informativeLabel) {
- QLabel *label = new QLabel;
- label->setObjectName(QLatin1String("qt_msgbox_informativelabel"));
- label->setTextInteractionFlags(Qt::TextInteractionFlags(style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, 0, this)));
- label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
- label->setOpenExternalLinks(true);
- label->setWordWrap(true);
-#ifndef Q_WS_MAC
- d->label->setContentsMargins(2, 0, 0, 0);
- label->setContentsMargins(2, 0, 0, 6);
- label->setIndent(9);
-#else
- label->setContentsMargins(16, 0, 0, 0);
- // apply a smaller font the information label on the mac
- label->setFont(qt_app_fonts_hash()->value("QTipLabel"));
-#endif
- label->setWordWrap(true);
- QGridLayout *grid = static_cast<QGridLayout *>(layout());
-#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5)
- label->hide();
- QTextBrowser *textBrowser = new QTextBrowser(this);
- textBrowser->setOpenExternalLinks(true);
- grid->addWidget(textBrowser, 1, 1, 1, 1);
- d->textBrowser = textBrowser;
-#else
- grid->addWidget(label, 1, 1, 1, 1);
-#endif
- d->informativeLabel = label;
- }
- d->informativeLabel->setText(text);
-
-#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5)
- //We need to put the informative label inside textBrowser to enable scrolling of long texts.
- d->textBrowser->setText(d->informativeLabel->text());
-#endif
-
- d->updateSize();
-}
-
-/*!
- \since 4.2
-
- This function shadows QWidget::setWindowTitle().
-
- Sets the title of the message box to \a title. On Mac OS X,
- the window title is ignored (as required by the Mac OS X
- Guidelines).
-*/
-void QMessageBox::setWindowTitle(const QString &title)
-{
- // Message boxes on the mac do not have a title
-#ifndef Q_WS_MAC
- QDialog::setWindowTitle(title);
-#else
- Q_UNUSED(title);
-#endif
-}
-
-
-/*!
- \since 4.2
-
- This function shadows QWidget::setWindowModality().
-
- Sets the modality of the message box to \a windowModality.
-
- On Mac OS X, if the modality is set to Qt::WindowModal and the message box
- has a parent, then the message box will be a Qt::Sheet, otherwise the
- message box will be a standard dialog.
-*/
-void QMessageBox::setWindowModality(Qt::WindowModality windowModality)
-{
- QDialog::setWindowModality(windowModality);
-
- if (parentWidget() && windowModality == Qt::WindowModal)
- setParent(parentWidget(), Qt::Sheet);
- else
- setParent(parentWidget(), Qt::Dialog);
- setDefaultButton(d_func()->defaultButton);
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \compat
-
- Constructs a message box with the given \a parent, \a name, and
- window flags, \a f.
- The window title is specified by \a title, and the message box
- displays message text and an icon specified by \a text and \a icon.
-
- The buttons that the user can access to respond to the message are
- defined by \a button0, \a button1, and \a button2.
-*/
-QMessageBox::QMessageBox(const QString& title,
- const QString &text, Icon icon,
- int button0, int button1, int button2,
- QWidget *parent, const char *name,
- bool modal, Qt::WindowFlags f)
- : QDialog(*new QMessageBoxPrivate, parent,
- f | Qt::WStyle_Customize | Qt::WStyle_DialogBorder | Qt::WStyle_Title | Qt::WStyle_SysMenu | Qt::WindowCloseButtonHint)
-{
- Q_D(QMessageBox);
- setObjectName(QString::fromAscii(name));
- d->init(title, text);
- d->addOldButtons(button0, button1, button2);
- setModal(modal);
- setIcon(icon);
-}
-
-/*!
- \compat
- Constructs a message box with the given \a parent and \a name.
-*/
-QMessageBox::QMessageBox(QWidget *parent, const char *name)
- : QDialog(*new QMessageBoxPrivate, parent,
- Qt::WStyle_Customize | Qt::WStyle_DialogBorder | Qt::WStyle_Title | Qt::WStyle_SysMenu | Qt::WindowCloseButtonHint)
-{
- Q_D(QMessageBox);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Returns the pixmap used for a standard icon. This
- allows the pixmaps to be used in more complex message boxes.
- \a icon specifies the required icon, e.g. QMessageBox::Information,
- QMessageBox::Warning or QMessageBox::Critical.
-
- \a style is unused.
-*/
-
-QPixmap QMessageBox::standardIcon(Icon icon, Qt::GUIStyle style)
-{
- Q_UNUSED(style);
- return QMessageBox::standardIcon(icon);
-}
-
-/*!
- \fn int QMessageBox::message(const QString &title, const QString &text,
- const QString &buttonText, QWidget *parent = 0,
- const char *name = 0)
-
- Opens a modal message box with the given \a title and showing the
- given \a text. The message box has a single button which has the
- given \a buttonText (or tr("OK")). The message box is centred over
- its \a parent and is called \a name.
-
- Use information(), warning(), question(), or critical() instead.
-
- \oldcode
- QMessageBox::message(tr("My App"), tr("All occurrences replaced."),
- tr("Close"), this);
- \newcode
- QMessageBox::information(this, tr("My App"),
- tr("All occurrences replaced."),
- QMessageBox::Close);
- \endcode
-*/
-
-/*!
- \fn bool QMessageBox::query(const QString &caption,
- const QString& text,
- const QString& yesButtonText,
- const QString& noButtonText,
- QWidget *parent, const char *name)
-
- \obsolete
-
- Queries the user using a modal message box with up to two buttons.
- The message box has the given \a caption (although some window
- managers don't show it), and shows the given \a text. The left
- button has the \a yesButtonText (or tr("OK")), and the right button
- has the \a noButtonText (or isn't shown). The message box is centred
- over its \a parent and is called \a name.
-
- Use information(), question(), warning(), or critical() instead.
-*/
-
-#endif
-
-QPixmap QMessageBoxPrivate::standardIcon(QMessageBox::Icon icon, QMessageBox *mb)
-{
- QStyle *style = mb ? mb->style() : QApplication::style();
- int iconSize = style->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, mb);
- QIcon tmpIcon;
- switch (icon) {
- case QMessageBox::Information:
- tmpIcon = style->standardIcon(QStyle::SP_MessageBoxInformation, 0, mb);
- break;
- case QMessageBox::Warning:
- tmpIcon = style->standardIcon(QStyle::SP_MessageBoxWarning, 0, mb);
- break;
- case QMessageBox::Critical:
- tmpIcon = style->standardIcon(QStyle::SP_MessageBoxCritical, 0, mb);
- break;
- case QMessageBox::Question:
- tmpIcon = style->standardIcon(QStyle::SP_MessageBoxQuestion, 0, mb);
- default:
- break;
- }
- if (!tmpIcon.isNull())
- return tmpIcon.pixmap(iconSize, iconSize);
- return QPixmap();
-}
-
-/*!
- \obsolete
-
- Returns the pixmap used for a standard icon. This allows the
- pixmaps to be used in more complex message boxes. \a icon
- specifies the required icon, e.g. QMessageBox::Question,
- QMessageBox::Information, QMessageBox::Warning or
- QMessageBox::Critical.
-
- Call QStyle::standardIcon() with QStyle::SP_MessageBoxInformation etc.
- instead.
-*/
-
-QPixmap QMessageBox::standardIcon(Icon icon)
-{
- return QMessageBoxPrivate::standardIcon(icon, 0);
-}
-
-/*!
- \typedef QMessageBox::Button
- \obsolete
-
- Use QMessageBox::StandardButton instead.
-*/
-
-/*!
- \fn int QMessageBox::information(QWidget *parent, const QString &title,
- const QString& text, StandardButton button0,
- StandardButton button1)
- \fn int QMessageBox::warning(QWidget *parent, const QString &title,
- const QString& text, StandardButton button0,
- StandardButton button1)
- \fn int QMessageBox::critical(QWidget *parent, const QString &title,
- const QString& text, StandardButton button0,
- StandardButton button1)
- \fn int QMessageBox::question(QWidget *parent, const QString &title,
- const QString& text, StandardButton button0,
- StandardButton button1)
- \internal
-
- ### Needed for Qt 4 source compatibility
-*/
-
-/*!
- \fn int QMessageBox::exec()
-
- Shows the message box as a \l{QDialog#Modal Dialogs}{modal dialog},
- blocking until the user closes it.
-
- When using a QMessageBox with standard buttons, this functions returns a
- \l StandardButton value indicating the standard button that was clicked.
- When using QMessageBox with custom buttons, this function returns an
- opaque value; use clickedButton() to determine which button was clicked.
-
- Users cannot interact with any other window in the same
- application until they close the dialog, either by clicking a
- button or by using a mechanism provided by the window system.
-
- \sa show(), result()
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qmessagebox.cpp"
-
-#endif // QT_NO_MESSAGEBOX
diff --git a/src/gui/dialogs/qmessagebox.h b/src/gui/dialogs/qmessagebox.h
deleted file mode 100644
index 37ddb38e2d..0000000000
--- a/src/gui/dialogs/qmessagebox.h
+++ /dev/null
@@ -1,365 +0,0 @@
-/****************************************************************************
-**
-** 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 QMESSAGEBOX_H
-#define QMESSAGEBOX_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_MESSAGEBOX
-
-class QLabel;
-class QMessageBoxPrivate;
-class QAbstractButton;
-
-class Q_GUI_EXPORT QMessageBox : public QDialog
-{
- Q_OBJECT
- Q_ENUMS(Icon)
- Q_FLAGS(StandardButtons)
- Q_PROPERTY(QString text READ text WRITE setText)
- // ### Qt 5: Rename 'icon' 'standardIcon' and 'iconPixmap' 'icon' (and use QIcon?)
- Q_PROPERTY(Icon icon READ icon WRITE setIcon)
- Q_PROPERTY(QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap)
- Q_PROPERTY(Qt::TextFormat textFormat READ textFormat WRITE setTextFormat)
- Q_PROPERTY(StandardButtons standardButtons READ standardButtons WRITE setStandardButtons)
-#ifndef QT_NO_TEXTEDIT
- Q_PROPERTY(QString detailedText READ detailedText WRITE setDetailedText)
-#endif
- Q_PROPERTY(QString informativeText READ informativeText WRITE setInformativeText)
-
-public:
- enum Icon {
- NoIcon = 0,
- Information = 1,
- Warning = 2,
- Critical = 3,
- Question = 4
- };
-
- enum ButtonRole {
- // keep this in sync with QDialogButtonBox::ButtonRole
- InvalidRole = -1,
- AcceptRole,
- RejectRole,
- DestructiveRole,
- ActionRole,
- HelpRole,
- YesRole,
- NoRole,
- ResetRole,
- ApplyRole,
-
- NRoles
- };
-
- enum StandardButton {
- // keep this in sync with QDialogButtonBox::StandardButton
- NoButton = 0x00000000,
- Ok = 0x00000400,
- Save = 0x00000800,
- SaveAll = 0x00001000,
- Open = 0x00002000,
- Yes = 0x00004000,
- YesToAll = 0x00008000,
- No = 0x00010000,
- NoToAll = 0x00020000,
- Abort = 0x00040000,
- Retry = 0x00080000,
- Ignore = 0x00100000,
- Close = 0x00200000,
- Cancel = 0x00400000,
- Discard = 0x00800000,
- Help = 0x01000000,
- Apply = 0x02000000,
- Reset = 0x04000000,
- RestoreDefaults = 0x08000000,
-
- FirstButton = Ok, // internal
- LastButton = RestoreDefaults, // internal
-
- YesAll = YesToAll, // obsolete
- NoAll = NoToAll, // obsolete
-
- Default = 0x00000100, // obsolete
- Escape = 0x00000200, // obsolete
- FlagMask = 0x00000300, // obsolete
- ButtonMask = ~FlagMask // obsolete
- };
- typedef StandardButton Button; // obsolete
-
- Q_DECLARE_FLAGS(StandardButtons, StandardButton)
-
- explicit QMessageBox(QWidget *parent = 0);
- QMessageBox(Icon icon, const QString &title, const QString &text,
- StandardButtons buttons = NoButton, QWidget *parent = 0,
- Qt::WindowFlags flags = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
- ~QMessageBox();
-
- void addButton(QAbstractButton *button, ButtonRole role);
- QPushButton *addButton(const QString &text, ButtonRole role);
- QPushButton *addButton(StandardButton button);
- void removeButton(QAbstractButton *button);
-
-#ifdef Q_WS_WINCE
- void setVisible(bool visible);
-#endif
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
- QList<QAbstractButton *> buttons() const;
- ButtonRole buttonRole(QAbstractButton *button) const;
-
- void setStandardButtons(StandardButtons buttons);
- StandardButtons standardButtons() const;
- StandardButton standardButton(QAbstractButton *button) const;
- QAbstractButton *button(StandardButton which) const;
-
- QPushButton *defaultButton() const;
- void setDefaultButton(QPushButton *button);
- void setDefaultButton(StandardButton button);
-
- QAbstractButton *escapeButton() const;
- void setEscapeButton(QAbstractButton *button);
- void setEscapeButton(StandardButton button);
-
- QAbstractButton *clickedButton() const;
-
- QString text() const;
- void setText(const QString &text);
-
- Icon icon() const;
- void setIcon(Icon);
-
- QPixmap iconPixmap() const;
- void setIconPixmap(const QPixmap &pixmap);
-
- Qt::TextFormat textFormat() const;
- void setTextFormat(Qt::TextFormat format);
-
- static StandardButton information(QWidget *parent, const QString &title,
- const QString &text, StandardButtons buttons = Ok,
- StandardButton defaultButton = NoButton);
- // ### Qt 5: Replace Ok with Yes|No in question() function.
- // Also consider if Ok == Yes and Cancel == No.
- static StandardButton question(QWidget *parent, const QString &title,
- const QString &text, StandardButtons buttons = Ok,
- StandardButton defaultButton = NoButton);
- static StandardButton warning(QWidget *parent, const QString &title,
- const QString &text, StandardButtons buttons = Ok,
- StandardButton defaultButton = NoButton);
- static StandardButton critical(QWidget *parent, const QString &title,
- const QString &text, StandardButtons buttons = Ok,
- StandardButton defaultButton = NoButton);
- static void about(QWidget *parent, const QString &title, const QString &text);
- static void aboutQt(QWidget *parent, const QString &title = QString());
-
- QSize sizeHint() const;
-
- // the following functions are obsolete:
-
- QMessageBox(const QString &title, const QString &text, Icon icon,
- int button0, int button1, int button2,
- QWidget *parent = 0,
- Qt::WindowFlags f = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
-
- static int information(QWidget *parent, const QString &title,
- const QString& text,
- int button0, int button1 = 0, int button2 = 0);
- static int information(QWidget *parent, const QString &title,
- const QString& text,
- const QString& button0Text,
- const QString& button1Text = QString(),
- const QString& button2Text = QString(),
- int defaultButtonNumber = 0,
- int escapeButtonNumber = -1);
- inline static StandardButton information(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1 = NoButton)
- { return information(parent, title, text, StandardButtons(button0), button1); }
-
- static int question(QWidget *parent, const QString &title,
- const QString& text,
- int button0, int button1 = 0, int button2 = 0);
- static int question(QWidget *parent, const QString &title,
- const QString& text,
- const QString& button0Text,
- const QString& button1Text = QString(),
- const QString& button2Text = QString(),
- int defaultButtonNumber = 0,
- int escapeButtonNumber = -1);
- inline static int question(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1)
- { return question(parent, title, text, StandardButtons(button0), button1); }
-
- static int warning(QWidget *parent, const QString &title,
- const QString& text,
- int button0, int button1, int button2 = 0);
- static int warning(QWidget *parent, const QString &title,
- const QString& text,
- const QString& button0Text,
- const QString& button1Text = QString(),
- const QString& button2Text = QString(),
- int defaultButtonNumber = 0,
- int escapeButtonNumber = -1);
- inline static int warning(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1)
- { return warning(parent, title, text, StandardButtons(button0), button1); }
-
- static int critical(QWidget *parent, const QString &title,
- const QString& text,
- int button0, int button1, int button2 = 0);
- static int critical(QWidget *parent, const QString &title,
- const QString& text,
- const QString& button0Text,
- const QString& button1Text = QString(),
- const QString& button2Text = QString(),
- int defaultButtonNumber = 0,
- int escapeButtonNumber = -1);
- inline static int critical(QWidget *parent, const QString &title,
- const QString& text,
- StandardButton button0, StandardButton button1)
- { return critical(parent, title, text, StandardButtons(button0), button1); }
-
- QString buttonText(int button) const;
- void setButtonText(int button, const QString &text);
-
- QString informativeText() const;
- void setInformativeText(const QString &text);
-
-#ifndef QT_NO_TEXTEDIT
- QString detailedText() const;
- void setDetailedText(const QString &text);
-#endif
-
- void setWindowTitle(const QString &title);
- void setWindowModality(Qt::WindowModality windowModality);
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QMessageBox(const QString &title, const QString &text, Icon icon,
- int button0, int button1, int button2,
- QWidget *parent, const char *name, bool modal,
- Qt::WindowFlags f = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
- QT3_SUPPORT_CONSTRUCTOR QMessageBox(QWidget *parent, const char *name);
-
- static QT3_SUPPORT QPixmap standardIcon(Icon icon, Qt::GUIStyle);
- static QT3_SUPPORT int message(const QString &title,
- const QString& text,
- const QString& buttonText=QString(),
- QWidget *parent = 0, const char * = 0) {
- return QMessageBox::information(parent, title, text,
- buttonText.isEmpty() ? tr("OK") : buttonText) == 0;
- }
- static QT3_SUPPORT bool query(const QString &title,
- const QString& text,
- const QString& yesButtonText = QString(),
- const QString& noButtonText = QString(),
- QWidget *parent = 0, const char * = 0) {
- return QMessageBox::information(parent, title, text,
- yesButtonText.isEmpty() ? tr("OK") : yesButtonText,
- noButtonText) == 0;
- }
-#endif
-
- static QPixmap standardIcon(Icon icon);
-
-Q_SIGNALS:
- void buttonClicked(QAbstractButton *button);
-
-#ifdef qdoc
-public Q_SLOTS:
- int exec();
-#endif
-
-protected:
- bool event(QEvent *e);
- void resizeEvent(QResizeEvent *event);
- void showEvent(QShowEvent *event);
- void closeEvent(QCloseEvent *event);
- void keyPressEvent(QKeyEvent *event);
- void changeEvent(QEvent *event);
-
-private:
- Q_PRIVATE_SLOT(d_func(), void _q_buttonClicked(QAbstractButton *))
-
- Q_DISABLE_COPY(QMessageBox)
- Q_DECLARE_PRIVATE(QMessageBox)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QMessageBox::StandardButtons)
-
-#define QT_REQUIRE_VERSION(argc, argv, str) { QString s = QString::fromLatin1(str);\
-QString sq = QString::fromLatin1(qVersion()); \
-if ((sq.section(QChar::fromLatin1('.'),0,0).toInt()<<16)+\
-(sq.section(QChar::fromLatin1('.'),1,1).toInt()<<8)+\
-sq.section(QChar::fromLatin1('.'),2,2).toInt()<(s.section(QChar::fromLatin1('.'),0,0).toInt()<<16)+\
-(s.section(QChar::fromLatin1('.'),1,1).toInt()<<8)+\
-s.section(QChar::fromLatin1('.'),2,2).toInt()) { \
-if (!qApp){ \
- new QApplication(argc,argv); \
-} \
-QString s = QApplication::tr("Executable '%1' requires Qt "\
- "%2, found Qt %3.").arg(qAppName()).arg(QString::fromLatin1(\
-str)).arg(QString::fromLatin1(qVersion())); QMessageBox::critical(0, QApplication::tr(\
-"Incompatible Qt Library Error"), s, QMessageBox::Abort, 0); qFatal("%s", s.toLatin1().data()); }}
-
-#endif // QT_NO_MESSAGEBOX
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMESSAGEBOX_H
diff --git a/src/gui/dialogs/qmessagebox.qrc b/src/gui/dialogs/qmessagebox.qrc
deleted file mode 100644
index 8e6d7af671..0000000000
--- a/src/gui/dialogs/qmessagebox.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/qmessagebox">
- <file>images/qtlogo-64.png</file>
-</qresource>
-</RCC>
diff --git a/src/gui/dialogs/qnspanelproxy_mac.mm b/src/gui/dialogs/qnspanelproxy_mac.mm
deleted file mode 100644
index 5c8ef24688..0000000000
--- a/src/gui/dialogs/qnspanelproxy_mac.mm
+++ /dev/null
@@ -1,228 +0,0 @@
-/****************************************************************************
-**
-** 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 <qdialogbuttonbox.h>
-#if defined(Q_WS_MAC)
-#include <private/qt_mac_p.h>
-#include <private/qcocoaintrospection_p.h>
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-#import <objc/objc-class.h>
-
-QT_BEGIN_NAMESPACE
-static QWidget *currentWindow = 0;
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QNSPanelProxy);
-
-@interface QT_MANGLE_NAMESPACE(QNSPanelProxy) : NSWindow {
-}
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation;
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen;
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation;
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSPanelProxy)
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation
-{
- // remove evil flag
- windowStyle &= ~NSUtilityWindowMask;
- self = [self qt_fakeInitWithContentRect:contentRect styleMask:windowStyle
- backing:bufferingType defer:deferCreation];
- return self;
-}
-
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen
-{
- // remove evil flag
- windowStyle &= ~NSUtilityWindowMask;
- return [self qt_fakeInitWithContentRect:contentRect styleMask:windowStyle
- backing:bufferingType defer:deferCreation screen:screen];
-}
-
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation
-{
- Q_UNUSED(contentRect);
- Q_UNUSED(windowStyle);
- Q_UNUSED(bufferingType);
- Q_UNUSED(deferCreation);
- return nil;
-}
-
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen
-{
- Q_UNUSED(contentRect);
- Q_UNUSED(windowStyle);
- Q_UNUSED(bufferingType);
- Q_UNUSED(deferCreation);
- Q_UNUSED(screen);
- return nil;
-}
-@end
-
-@class QT_MANGLE_NAMESPACE(QNSWindowProxy);
-
-@interface QT_MANGLE_NAMESPACE(QNSWindowProxy) : NSWindow {
-}
-- (void)setTitle:(NSString *)title;
-- (void)qt_fakeSetTitle:(NSString *)title;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSWindowProxy)
-- (void)setTitle:(NSString *)title
-{
- QCFString cftitle(currentWindow->windowTitle());
-
- // evil reverse engineering
- if ([title isEqualToString:@"Print"]
- || [title isEqualToString:@"Page Setup"]
- || [[self className] isEqualToString:@"PMPrintingWindow"])
- title = (NSString *)(static_cast<CFStringRef>(cftitle));
- return [self qt_fakeSetTitle:title];
-}
-
-- (void)qt_fakeSetTitle:(NSString *)title
-{
- Q_UNUSED(title);
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-/*
- Intercept the NSColorPanel constructor if the shared
- color panel doesn't exist yet. What's going on here is
- quite wacky, because we want to override the NSPanel
- constructor and at the same time call the old NSPanel
- constructor. So what we do is we effectively rename the
- old NSPanel constructor qt_fakeInitWithContentRect:...
- and have the new one call the old one.
-*/
-void macStartInterceptNSPanelCtor()
-{
- qt_cocoa_change_implementation(
- [NSPanel class],
- @selector(initWithContentRect:styleMask:backing:defer:),
- [QT_MANGLE_NAMESPACE(QNSPanelProxy) class],
- @selector(initWithContentRect:styleMask:backing:defer:),
- @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:));
- qt_cocoa_change_implementation(
- [NSPanel class],
- @selector(initWithContentRect:styleMask:backing:defer:screen:),
- [QT_MANGLE_NAMESPACE(QNSPanelProxy) class],
- @selector(initWithContentRect:styleMask:backing:defer:screen:),
- @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:screen:));
-}
-
-/*
- Restore things as they were.
-*/
-void macStopInterceptNSPanelCtor()
-{
- qt_cocoa_change_back_implementation(
- [NSPanel class],
- @selector(initWithContentRect:styleMask:backing:defer:screen:),
- @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:screen:));
- qt_cocoa_change_back_implementation(
- [NSPanel class],
- @selector(initWithContentRect:styleMask:backing:defer:),
- @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:));
-}
-
-/*
- Intercept the NSPrintPanel and NSPageLayout setTitle: calls. The
- hack is similar as for NSColorPanel above.
-*/
-void macStartInterceptWindowTitle(QWidget *window)
-{
- currentWindow = window;
- qt_cocoa_change_implementation(
- [NSWindow class],
- @selector(setTitle:),
- [QT_MANGLE_NAMESPACE(QNSWindowProxy) class],
- @selector(setTitle:),
- @selector(qt_fakeSetTitle:));
-}
-
-/*
- Restore things as they were.
-*/
-void macStopInterceptWindowTitle()
-{
- currentWindow = 0;
- qt_cocoa_change_back_implementation(
- [NSWindow class],
- @selector(setTitle:),
- @selector(qt_fakeSetTitle:));
-}
-
-/*
- Doesn't really belong in here.
-*/
-NSButton *macCreateButton(const char *text, NSView *superview)
-{
- static const NSRect buttonFrameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } };
-
- NSButton *button = [[NSButton alloc] initWithFrame:buttonFrameRect];
- [button setButtonType:NSMomentaryLightButton];
- [button setBezelStyle:NSRoundedBezelStyle];
- [button setTitle:(NSString*)(CFStringRef)QCFString(QDialogButtonBox::tr(text)
- .remove(QLatin1Char('&')))];
- [[button cell] setFont:[NSFont systemFontOfSize:
- [NSFont systemFontSizeForControlSize:NSRegularControlSize]]];
- [superview addSubview:button];
- return button;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qpagesetupdialog.cpp b/src/gui/dialogs/qpagesetupdialog.cpp
deleted file mode 100644
index 4037e1cff8..0000000000
--- a/src/gui/dialogs/qpagesetupdialog.cpp
+++ /dev/null
@@ -1,240 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qabstractpagesetupdialog_p.h>
-
-#ifndef QT_NO_PRINTDIALOG
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QPageSetupDialog
-
- \brief The QPageSetupDialog class provides a configuration dialog
- for the page-related options on a printer.
-
- \ingroup standard-dialogs
- \ingroup printing
-
- On Windows and Mac OS X the page setup dialog is implemented using
- the native page setup dialogs.
-
- Note that on Windows and Mac OS X custom paper sizes won't be
- reflected in the native page setup dialogs. Additionally, custom
- page margins set on a QPrinter won't show in the native Mac OS X
- page setup dialog.
-
- In Symbian, there is no support for printing. Hence, this dialog should not
- be used in Symbian.
-
- \sa QPrinter, QPrintDialog
-*/
-
-
-/*!
- \fn QPageSetupDialog::QPageSetupDialog(QPrinter *printer, QWidget *parent)
-
- Constructs a page setup dialog that configures \a printer with \a
- parent as the parent widget.
-*/
-
-/*!
- \since 4.5
-
- \fn QPageSetupDialog::QPageSetupDialog(QWidget *parent)
-
- Constructs a page setup dialog that configures a default-constructed
- QPrinter with \a parent as the parent widget.
-
- \sa printer()
-*/
-
-/*!
- \fn QPrinter *QPageSetupDialog::printer()
-
- Returns the printer that was passed to the QPageSetupDialog
- constructor.
-*/
-
-// hack
-class QPageSetupDialogPrivate : public QAbstractPageSetupDialogPrivate
-{
-};
-
-/*!
- \enum QPageSetupDialog::PageSetupDialogOption
- \since 4.4
-
- Used to specify options to the page setup dialog
-
- This value is obsolete and does nothing since Qt 4.5:
-
- \value DontUseSheet In previous versions of QDialog::exec() the
- page setup dialog would create a sheet by default if the dialog
- was given a parent. This is no longer supported from Qt 4.5. If
- you want to use sheets, use QPageSetupDialog::open() instead.
-
- \omitvalue None
- \omitvalue OwnsPrinter
-*/
-
-/*!
- Sets the given \a option to be enabled if \a on is true;
- otherwise, clears the given \a option.
-
- \sa options, testOption()
-*/
-void QPageSetupDialog::setOption(PageSetupDialogOption option, bool on)
-{
- Q_D(QPageSetupDialog);
- if (!(d->opts & option) != !on)
- setOptions(d->opts ^ option);
-}
-
-/*!
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption()
-*/
-bool QPageSetupDialog::testOption(PageSetupDialogOption option) const
-{
- Q_D(const QPageSetupDialog);
- return (d->opts & option) != 0;
-}
-
-/*!
- \property QPageSetupDialog::options
- \brief the various options that affect the look and feel of the dialog
- \since 4.5
-
- By default, all options are disabled.
-
- Options should be set before showing the dialog. Setting them while the
- dialog is visible is not guaranteed to have an immediate effect on the
- dialog (depending on the option and on the platform).
-
- \sa setOption(), testOption()
-*/
-void QPageSetupDialog::setOptions(PageSetupDialogOptions options)
-{
- Q_D(QPageSetupDialog);
-
- PageSetupDialogOptions changed = (options ^ d->opts);
- if (!changed)
- return;
-
- d->opts = options;
-}
-
-QPageSetupDialog::PageSetupDialogOptions QPageSetupDialog::options() const
-{
- Q_D(const QPageSetupDialog);
- return d->opts;
-}
-
-/*!
- \obsolete
-
- Use setOption(\a option, true) instead.
-*/
-void QPageSetupDialog::addEnabledOption(PageSetupDialogOption option)
-{
- setOption(option, true);
-}
-
-/*!
- \obsolete
-
- Use setOptions(\a options) instead.
-*/
-void QPageSetupDialog::setEnabledOptions(PageSetupDialogOptions options)
-{
- setOptions(options);
-}
-
-/*!
- \obsolete
-
- Use options() instead.
-*/
-QPageSetupDialog::PageSetupDialogOptions QPageSetupDialog::enabledOptions() const
-{
- return options();
-}
-
-/*!
- \obsolete
-
- Use testOption(\a option) instead.
-*/
-bool QPageSetupDialog::isOptionEnabled(PageSetupDialogOption option) const
-{
- return testOption(option);
-}
-
-/*!
- \overload
- \since 4.5
-
- Opens the dialog and connects its accepted() signal to the slot specified
- by \a receiver and \a member.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QPageSetupDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QPageSetupDialog);
- connect(this, SIGNAL(accepted()), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-#if defined(Q_WS_MAC) || defined(Q_OS_WIN)
-/*! \fn void QPageSetupDialog::setVisible(bool visible)
- \reimp
-*/
-#endif
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qpagesetupdialog.h b/src/gui/dialogs/qpagesetupdialog.h
deleted file mode 100644
index 184af251da..0000000000
--- a/src/gui/dialogs/qpagesetupdialog.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** 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 QPAGESETUPDIALOG_H
-#define QPAGESETUPDIALOG_H
-
-#include <QtGui/qabstractpagesetupdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PRINTDIALOG
-
-class QPageSetupDialogPrivate;
-
-class Q_GUI_EXPORT QPageSetupDialog : public QAbstractPageSetupDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPageSetupDialog)
- Q_ENUMS(PageSetupDialogOption)
- Q_PROPERTY(PageSetupDialogOptions options READ options WRITE setOptions)
-
-public:
- enum PageSetupDialogOption {
- None = 0x00000000, // internal
- DontUseSheet = 0x00000001,
- OwnsPrinter = 0x80000000 // internal
- };
-
- Q_DECLARE_FLAGS(PageSetupDialogOptions, PageSetupDialogOption)
-
- explicit QPageSetupDialog(QPrinter *printer, QWidget *parent = 0);
- explicit QPageSetupDialog(QWidget *parent = 0);
-
- // obsolete
- void addEnabledOption(PageSetupDialogOption option);
- void setEnabledOptions(PageSetupDialogOptions options);
- PageSetupDialogOptions enabledOptions() const;
- bool isOptionEnabled(PageSetupDialogOption option) const;
-
- void setOption(PageSetupDialogOption option, bool on = true);
- bool testOption(PageSetupDialogOption option) const;
- void setOptions(PageSetupDialogOptions options);
- PageSetupDialogOptions options() const;
-
-#if defined(Q_WS_MAC) || defined(Q_OS_WIN)
- virtual void setVisible(bool visible);
-#endif
- virtual int exec();
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
-#ifdef qdoc
- QPrinter *printer();
-#endif
-};
-
-#endif // QT_NO_PRINTDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPAGESETUPDIALOG_H
diff --git a/src/gui/dialogs/qpagesetupdialog_mac.mm b/src/gui/dialogs/qpagesetupdialog_mac.mm
deleted file mode 100644
index fa3f47378f..0000000000
--- a/src/gui/dialogs/qpagesetupdialog_mac.mm
+++ /dev/null
@@ -1,315 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpagesetupdialog.h"
-
-#include <qhash.h>
-#include <private/qapplication_p.h>
-#include <private/qprintengine_mac_p.h>
-#include <private/qabstractpagesetupdialog_p.h>
-
-#ifndef QT_NO_PRINTDIALOG
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate) : NSObject {
- QMacPrintEnginePrivate *pe;
-}
-- (id)initWithMacPrintEngine:(QMacPrintEnginePrivate *)printEngine;
-- (void)pageLayoutDidEnd:(NSPageLayout *)pageLayout
- returnCode:(int)returnCode contextInfo:(void *)contextInfo;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate)
-- (id)initWithMacPrintEngine:(QMacPrintEnginePrivate *)printEngine
-{
- self = [super init];
- if (self) {
- pe = printEngine;
- }
- return self;
-
-}
-- (void)pageLayoutDidEnd:(NSPageLayout *)pageLayout
- returnCode:(int)returnCode contextInfo:(void *)contextInfo
-{
- Q_UNUSED(pageLayout);
- QPageSetupDialog *dialog = static_cast<QPageSetupDialog *>(contextInfo);
- if (returnCode == NSOKButton) {
- PMRect paperRect;
- PMGetUnadjustedPaperRect(pe->format, &paperRect);
- pe->customSize = QSizeF(paperRect.right - paperRect.left,
- paperRect.bottom - paperRect.top);
- }
- dialog->done((returnCode == NSOKButton) ? QDialog::Accepted : QDialog::Rejected);
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptWindowTitle(QWidget *window);
-extern void macStopInterceptWindowTitle();
-
-class QPageSetupDialogPrivate : public QAbstractPageSetupDialogPrivate
-{
- Q_DECLARE_PUBLIC(QPageSetupDialog)
-
-public:
- QPageSetupDialogPrivate() : ep(0)
-#ifndef QT_MAC_USE_COCOA
- ,upp(0)
-#else
- ,pageLayout(0)
-#endif
- {}
-
- ~QPageSetupDialogPrivate() {
-#ifndef QT_MAC_USE_COCOA
- if (upp) {
- DisposePMSheetDoneUPP(upp);
- upp = 0;
- }
- QHash<PMPrintSession, QPageSetupDialogPrivate *>::iterator it = sheetCallbackMap.begin();
- while (it != sheetCallbackMap.end()) {
- if (it.value() == this) {
- it = sheetCallbackMap.erase(it);
- } else {
- ++it;
- }
- }
-#endif
- }
-
-#ifndef QT_MAC_USE_COCOA
- void openCarbonPageLayout(Qt::WindowModality modality);
- void closeCarbonPageLayout();
- static void pageSetupDialogSheetDoneCallback(PMPrintSession printSession, WindowRef /*documentWindow*/, Boolean accepted) {
- QPageSetupDialogPrivate *priv = sheetCallbackMap.value(printSession);
- if (!priv) {
- qWarning("%s:%d: QPageSetupDialog::exec: Could not retrieve data structure, "
- "you most likely now have an infinite modal loop", __FILE__, __LINE__);
- return;
- }
- priv->q_func()->done(accepted ? QDialog::Accepted : QDialog::Rejected);
- }
-#else
- void openCocoaPageLayout(Qt::WindowModality modality);
- void closeCocoaPageLayout();
-#endif
-
- QMacPrintEnginePrivate *ep;
-#ifndef QT_MAC_USE_COCOA
- PMSheetDoneUPP upp;
- static QHash<PMPrintSession, QPageSetupDialogPrivate*> sheetCallbackMap;
-#else
- NSPageLayout *pageLayout;
-#endif
-};
-
-#ifndef QT_MAC_USE_COCOA
-QHash<PMPrintSession, QPageSetupDialogPrivate*> QPageSetupDialogPrivate::sheetCallbackMap;
-void QPageSetupDialogPrivate::openCarbonPageLayout(Qt::WindowModality modality)
-{
- Q_Q(QPageSetupDialog);
- // If someone is reusing a QPrinter object, the end released all our old
- // information. In this case, we must reinitialize.
- if (ep->session == 0)
- ep->initialize();
-
- sheetCallbackMap.insert(ep->session, this);
- if (modality == Qt::ApplicationModal) {
- QWidget modal_widg(0, Qt::Window);
- modal_widg.setObjectName(QLatin1String(__FILE__ "__modal_dlg"));
- modal_widg.createWinId();
- QApplicationPrivate::enterModal(&modal_widg);
- QApplicationPrivate::native_modal_dialog_active = true;
- Boolean accepted;
- PMSessionPageSetupDialog(ep->session, ep->format, &accepted);
- QApplicationPrivate::leaveModal(&modal_widg);
- QApplicationPrivate::native_modal_dialog_active = false;
- pageSetupDialogSheetDoneCallback(ep->session, 0, accepted);
- } else {
- // Window Modal means that we use a sheet at the moment, there's no other way to do it correctly.
- if (!upp)
- upp = NewPMSheetDoneUPP(QPageSetupDialogPrivate::pageSetupDialogSheetDoneCallback);
- PMSessionUseSheets(ep->session, qt_mac_window_for(q->parentWidget()), upp);
- Boolean unused;
- PMSessionPageSetupDialog(ep->session, ep->format, &unused);
- }
-}
-
-void QPageSetupDialogPrivate::closeCarbonPageLayout()
-{
- // if the margins have changed, we have to use the margins from the new
- // PMFormat object
- if (q_func()->result() == QDialog::Accepted) {
- PMPaper paper;
- PMPaperMargins margins;
- PMGetPageFormatPaper(ep->format, &paper);
- PMPaperGetMargins(paper, &margins);
- ep->leftMargin = margins.left;
- ep->topMargin = margins.top;
- ep->rightMargin = margins.right;
- ep->bottomMargin = margins.bottom;
-
- PMRect paperRect;
- PMGetUnadjustedPaperRect(ep->format, &paperRect);
- ep->customSize = QSizeF(paperRect.right - paperRect.left,
- paperRect.bottom - paperRect.top);
- }
- sheetCallbackMap.remove(ep->session);
-}
-#else
-void QPageSetupDialogPrivate::openCocoaPageLayout(Qt::WindowModality modality)
-{
- Q_Q(QPageSetupDialog);
-
- // If someone is reusing a QPrinter object, the end released all our old
- // information. In this case, we must reinitialize.
- if (ep->session == 0)
- ep->initialize();
-
- macStartInterceptWindowTitle(q);
- pageLayout = [NSPageLayout pageLayout];
- // Keep a copy to this since we plan on using it for a bit.
- [pageLayout retain];
- QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate) *delegate = [[QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate) alloc] initWithMacPrintEngine:ep];
-
- if (modality == Qt::ApplicationModal) {
- int rval = [pageLayout runModalWithPrintInfo:ep->printInfo];
- [delegate pageLayoutDidEnd:pageLayout returnCode:rval contextInfo:q];
- } else {
- Q_ASSERT(q->parentWidget());
- [pageLayout beginSheetWithPrintInfo:ep->printInfo
- modalForWindow:qt_mac_window_for(q->parentWidget())
- delegate:delegate
- didEndSelector:@selector(pageLayoutDidEnd:returnCode:contextInfo:)
- contextInfo:q];
- }
-
- macStopInterceptWindowTitle();
-}
-
-void QPageSetupDialogPrivate::closeCocoaPageLayout()
-{
- // NSPageLayout can change the session behind our back and then our
- // d->ep->session object will become a dangling pointer. Update it
- // based on the "current" session
- ep->session = static_cast<PMPrintSession>([ep->printInfo PMPrintSession]);
-
- [pageLayout release];
- pageLayout = 0;
-}
-#endif
-
-QPageSetupDialog::QPageSetupDialog(QPrinter *printer, QWidget *parent)
- : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), printer, parent)
-{
- Q_D(QPageSetupDialog);
- d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPageSetupDialog::QPageSetupDialog(QWidget *parent)
- : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), 0, parent)
-{
- Q_D(QPageSetupDialog);
- d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-void QPageSetupDialog::setVisible(bool visible)
-{
- Q_D(QPageSetupDialog);
-
- if (d->printer->outputFormat() != QPrinter::NativeFormat)
- return;
-
-#ifndef QT_MAC_USE_COCOA
- bool isCurrentlyVisible = d->sheetCallbackMap.contains(d->ep->session);
-#else
- bool isCurrentlyVisible = (d->pageLayout != 0);
-#endif
- if (!visible == !isCurrentlyVisible)
- return;
-
- if (visible) {
-#ifndef QT_MAC_USE_COCOA
- d->openCarbonPageLayout(parentWidget() ? Qt::WindowModal
- : Qt::ApplicationModal);
-#else
- d->openCocoaPageLayout(parentWidget() ? Qt::WindowModal
- : Qt::ApplicationModal);
-#endif
- return;
- } else {
-#ifndef QT_MAC_USE_COCOA
- d->closeCarbonPageLayout();
-#else
- if (d->pageLayout) {
- d->closeCocoaPageLayout();
- return;
- }
-#endif
- }
-}
-
-int QPageSetupDialog::exec()
-{
- Q_D(QPageSetupDialog);
-
- if (d->printer->outputFormat() != QPrinter::NativeFormat)
- return Rejected;
-
-#ifndef QT_MAC_USE_COCOA
- d->openCarbonPageLayout(Qt::ApplicationModal);
- d->closeCarbonPageLayout();
-#else
- QMacCocoaAutoReleasePool pool;
- d->openCocoaPageLayout(Qt::ApplicationModal);
- d->closeCocoaPageLayout();
-#endif
- return result();
-}
-
-QT_END_NAMESPACE
-
-#endif /* QT_NO_PRINTDIALOG */
diff --git a/src/gui/dialogs/qpagesetupdialog_unix.cpp b/src/gui/dialogs/qpagesetupdialog_unix.cpp
deleted file mode 100644
index a4e0927e8c..0000000000
--- a/src/gui/dialogs/qpagesetupdialog_unix.cpp
+++ /dev/null
@@ -1,620 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpagesetupdialog.h"
-
-#ifndef QT_NO_PRINTDIALOG
-#include "qpagesetupdialog_unix_p.h"
-
-#include "qpainter.h"
-#include "qprintdialog.h"
-#include "qdialogbuttonbox.h"
-#include <ui_qpagesetupwidget.h>
-
-#include <QtGui/qprinter.h>
-#include <private/qabstractpagesetupdialog_p.h>
-#include <private/qprinter_p.h>
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-# include <private/qcups_p.h>
-# include <cups/cups.h>
-# include <private/qpdf_p.h>
-#endif
-
-
-QT_BEGIN_NAMESPACE
-
-QSizeF qt_printerPaperSize(QPrinter::Orientation, QPrinter::PaperSize, QPrinter::Unit, int);
-
-// Disabled until we have support for papersources on unix
-// #define PSD_ENABLE_PAPERSOURCE
-
-static void populatePaperSizes(QComboBox* cb)
-{
- cb->addItem(QPrintDialog::tr("A0"), QPrinter::A0);
- cb->addItem(QPrintDialog::tr("A1"), QPrinter::A1);
- cb->addItem(QPrintDialog::tr("A2"), QPrinter::A2);
- cb->addItem(QPrintDialog::tr("A3"), QPrinter::A3);
- cb->addItem(QPrintDialog::tr("A4"), QPrinter::A4);
- cb->addItem(QPrintDialog::tr("A5"), QPrinter::A5);
- cb->addItem(QPrintDialog::tr("A6"), QPrinter::A6);
- cb->addItem(QPrintDialog::tr("A7"), QPrinter::A7);
- cb->addItem(QPrintDialog::tr("A8"), QPrinter::A8);
- cb->addItem(QPrintDialog::tr("A9"), QPrinter::A9);
- cb->addItem(QPrintDialog::tr("B0"), QPrinter::B0);
- cb->addItem(QPrintDialog::tr("B1"), QPrinter::B1);
- cb->addItem(QPrintDialog::tr("B2"), QPrinter::B2);
- cb->addItem(QPrintDialog::tr("B3"), QPrinter::B3);
- cb->addItem(QPrintDialog::tr("B4"), QPrinter::B4);
- cb->addItem(QPrintDialog::tr("B5"), QPrinter::B5);
- cb->addItem(QPrintDialog::tr("B6"), QPrinter::B6);
- cb->addItem(QPrintDialog::tr("B7"), QPrinter::B7);
- cb->addItem(QPrintDialog::tr("B8"), QPrinter::B8);
- cb->addItem(QPrintDialog::tr("B9"), QPrinter::B9);
- cb->addItem(QPrintDialog::tr("B10"), QPrinter::B10);
- cb->addItem(QPrintDialog::tr("C5E"), QPrinter::C5E);
- cb->addItem(QPrintDialog::tr("DLE"), QPrinter::DLE);
- cb->addItem(QPrintDialog::tr("Executive"), QPrinter::Executive);
- cb->addItem(QPrintDialog::tr("Folio"), QPrinter::Folio);
- cb->addItem(QPrintDialog::tr("Ledger"), QPrinter::Ledger);
- cb->addItem(QPrintDialog::tr("Legal"), QPrinter::Legal);
- cb->addItem(QPrintDialog::tr("Letter"), QPrinter::Letter);
- cb->addItem(QPrintDialog::tr("Tabloid"), QPrinter::Tabloid);
- cb->addItem(QPrintDialog::tr("US Common #10 Envelope"), QPrinter::Comm10E);
- cb->addItem(QPrintDialog::tr("Custom"), QPrinter::Custom);
-}
-
-
-static QSizeF sizeForOrientation(QPrinter::Orientation orientation, const QSizeF &size)
-{
- return (orientation == QPrinter::Portrait) ? size : QSizeF(size.height(), size.width());
-}
-
-#ifdef PSD_ENABLE_PAPERSOURCE
-static const char *paperSourceNames[] = {
- "Only One",
- "Lower",
- "Middle",
- "Manual",
- "Envelope",
- "Envelope manual",
- "Auto",
- "Tractor",
- "Small format",
- "Large format",
- "Large capacity",
- "Cassette",
- "Form source",
- 0
-};
-
-struct PaperSourceNames
-{
- PaperSourceNames(const char *nam, QPrinter::PaperSource ps)
- : paperSource(ps), name(nam) {}
- QPrinter::PaperSource paperSource;
- const char *name;
-};
-#endif
-
-
-class QPagePreview : public QWidget
-{
-public:
- QPagePreview(QWidget *parent) : QWidget(parent)
- {
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- setMinimumSize(50, 50);
- }
-
- void setPaperSize(const QSizeF& size)
- {
- m_size = size;
- update();
- }
-
- void setMargins(qreal left, qreal top, qreal right, qreal bottom)
- {
- m_left = left;
- m_top = top;
- m_right = right;
- m_bottom = bottom;
- update();
- }
-
-protected:
- void paintEvent(QPaintEvent *)
- {
- QRect pageRect;
- QSizeF adjustedSize(m_size);
- adjustedSize.scale(width()-10, height()-10, Qt::KeepAspectRatio);
- pageRect = QRect(QPoint(0,0), adjustedSize.toSize());
- pageRect.moveCenter(rect().center());
-
- qreal width_factor = pageRect.width() / m_size.width();
- qreal height_factor = pageRect.height() / m_size.height();
- int leftSize = qRound(m_left*width_factor);
- int topSize = qRound(m_top*height_factor);
- int rightSize = qRound(m_right*width_factor);
- int bottomSize = qRound(m_bottom * height_factor);
- QRect marginRect(pageRect.x()+leftSize,
- pageRect.y()+topSize,
- pageRect.width() - (leftSize+rightSize+1),
- pageRect.height() - (topSize+bottomSize+1));
-
- QPainter p(this);
- QColor shadow(palette().mid().color());
- for (int i=1; i<6; ++i) {
- shadow.setAlpha(180-i*30);
- QRect offset(pageRect.adjusted(i, i, i, i));
- p.setPen(shadow);
- p.drawLine(offset.left(), offset.bottom(), offset.right(), offset.bottom());
- p.drawLine(offset.right(), offset.top(), offset.right(), offset.bottom()-1);
- }
- p.fillRect(pageRect, palette().light());
-
- if (marginRect.isValid()) {
- p.setPen(QPen(palette().color(QPalette::Dark), 0, Qt::DotLine));
- p.drawRect(marginRect);
-
- marginRect.adjust(2, 2, -1, -1);
- p.setClipRect(marginRect);
- QFont font;
- font.setPointSizeF(font.pointSizeF()*0.25);
- p.setFont(font);
- p.setPen(palette().color(QPalette::Dark));
- QString text(QLatin1String("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi."));
- for (int i=0; i<3; ++i)
- text += text;
- p.drawText(marginRect, Qt::TextWordWrap|Qt::AlignVCenter, text);
- }
- }
-
-private:
- // all these are in points
- qreal m_left, m_top, m_right, m_bottom;
- QSizeF m_size;
-};
-
-
-class QPageSetupDialogPrivate : public QAbstractPageSetupDialogPrivate
-{
- Q_DECLARE_PUBLIC(QPageSetupDialog)
-
-public:
- ~QPageSetupDialogPrivate();
- void init();
-
- QPageSetupWidget *widget;
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- QCUPSSupport *cups;
-#endif
-};
-
-QPageSetupDialogPrivate::~QPageSetupDialogPrivate()
-{
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- delete cups;
-#endif
-}
-
-void QPageSetupDialogPrivate::init()
-{
- Q_Q(QPageSetupDialog);
-
- widget = new QPageSetupWidget(q);
- widget->setPrinter(printer);
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- if (printer->outputFormat() == QPrinter::NativeFormat && QCUPSSupport::isAvailable()) {
- cups = new QCUPSSupport;
- widget->selectPrinter(cups);
- } else {
- cups = 0;
- }
-#endif
-
- QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok
- | QDialogButtonBox::Cancel,
- Qt::Horizontal, q);
- QObject::connect(buttons, SIGNAL(accepted()), q, SLOT(accept()));
- QObject::connect(buttons, SIGNAL(rejected()), q, SLOT(reject()));
-
- QVBoxLayout *lay = new QVBoxLayout(q);
- lay->addWidget(widget);
- lay->addWidget(buttons);
-}
-
-QPageSetupWidget::QPageSetupWidget(QWidget *parent)
- : QWidget(parent),
- m_printer(0),
- m_blockSignals(false),
- m_cups(0)
-{
- widget.setupUi(this);
-
- QString suffix = (QLocale::system().measurementSystem() == QLocale::ImperialSystem)
- ? QString::fromLatin1(" in")
- : QString::fromLatin1(" mm");
- widget.topMargin->setSuffix(suffix);
- widget.bottomMargin->setSuffix(suffix);
- widget.leftMargin->setSuffix(suffix);
- widget.rightMargin->setSuffix(suffix);
- widget.paperWidth->setSuffix(suffix);
- widget.paperHeight->setSuffix(suffix);
-
- QVBoxLayout *lay = new QVBoxLayout(widget.preview);
- widget.preview->setLayout(lay);
- m_pagePreview = new QPagePreview(widget.preview);
- lay->addWidget(m_pagePreview);
-
- setAttribute(Qt::WA_WState_Polished, false);
-
-#ifdef PSD_ENABLE_PAPERSOURCE
- for (int i=0; paperSourceNames[i]; ++i)
- widget.paperSource->insertItem(paperSourceNames[i]);
-#else
- widget.paperSourceLabel->setVisible(false);
- widget.paperSource->setVisible(false);
-#endif
-
- widget.reverseLandscape->setVisible(false);
- widget.reversePortrait->setVisible(false);
-
- populatePaperSizes(widget.paperSize);
-
- QStringList units;
- units << tr("Centimeters (cm)") << tr("Millimeters (mm)") << tr("Inches (in)") << tr("Points (pt)");
- widget.unit->addItems(units);
- connect(widget.unit, SIGNAL(activated(int)), this, SLOT(unitChanged(int)));
- widget.unit->setCurrentIndex((QLocale::system().measurementSystem() == QLocale::ImperialSystem) ? 2 : 1);
-
- connect(widget.paperSize, SIGNAL(currentIndexChanged(int)), this, SLOT(_q_paperSizeChanged()));
- connect(widget.paperWidth, SIGNAL(valueChanged(double)), this, SLOT(_q_paperSizeChanged()));
- connect(widget.paperHeight, SIGNAL(valueChanged(double)), this, SLOT(_q_paperSizeChanged()));
-
- connect(widget.leftMargin, SIGNAL(valueChanged(double)), this, SLOT(setLeftMargin(double)));
- connect(widget.topMargin, SIGNAL(valueChanged(double)), this, SLOT(setTopMargin(double)));
- connect(widget.rightMargin, SIGNAL(valueChanged(double)), this, SLOT(setRightMargin(double)));
- connect(widget.bottomMargin, SIGNAL(valueChanged(double)), this, SLOT(setBottomMargin(double)));
-
- connect(widget.portrait, SIGNAL(clicked()), this, SLOT(_q_pageOrientationChanged()));
- connect(widget.landscape, SIGNAL(clicked()), this, SLOT(_q_pageOrientationChanged()));
-}
-
-void QPageSetupWidget::setPrinter(QPrinter *printer)
-{
- m_printer = printer;
- m_blockSignals = true;
- selectPdfPsPrinter(printer);
- printer->getPageMargins(&m_leftMargin, &m_topMargin, &m_rightMargin, &m_bottomMargin, QPrinter::Point);
- unitChanged(widget.unit->currentIndex());
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
- m_paperSize = printer->paperSize(QPrinter::Point);
- widget.paperWidth->setValue(m_paperSize.width() / m_currentMultiplier);
- widget.paperHeight->setValue(m_paperSize.height() / m_currentMultiplier);
-
- widget.landscape->setChecked(printer->orientation() == QPrinter::Landscape);
-
-#ifdef PSD_ENABLE_PAPERSOURCE
- widget.paperSource->setCurrentItem(printer->paperSource());
-#endif
- Q_ASSERT(m_blockSignals);
- m_blockSignals = false;
- _q_paperSizeChanged();
-}
-
-// set gui data on printer
-void QPageSetupWidget::setupPrinter() const
-{
- QPrinter::Orientation orientation = widget.portrait->isChecked()
- ? QPrinter::Portrait
- : QPrinter::Landscape;
- m_printer->setOrientation(orientation);
- // paper format
- QVariant val = widget.paperSize->itemData(widget.paperSize->currentIndex());
- int ps = m_printer->pageSize();
- if (val.type() == QVariant::Int) {
- ps = val.toInt();
- }
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- else if (m_cups && QCUPSSupport::isAvailable() && m_cups->currentPPD()) {
- QByteArray cupsPageSize = val.toByteArray();
- QPrintEngine *engine = m_printer->printEngine();
- engine->setProperty(PPK_CupsStringPageSize, QString::fromLatin1(cupsPageSize));
- engine->setProperty(PPK_CupsOptions, m_cups->options());
-
- QRect pageRect = m_cups->pageRect(cupsPageSize);
- engine->setProperty(PPK_CupsPageRect, pageRect);
-
- QRect paperRect = m_cups->paperRect(cupsPageSize);
- engine->setProperty(PPK_CupsPaperRect, paperRect);
-
- for(ps = 0; ps < QPrinter::NPaperSize; ++ps) {
- QPdf::PaperSize size = QPdf::paperSize(QPrinter::PaperSize(ps));
- if (size.width == paperRect.width() && size.height == paperRect.height())
- break;
- }
- }
-#endif
- if (ps == QPrinter::Custom)
- m_printer->setPaperSize(sizeForOrientation(orientation, m_paperSize), QPrinter::Point);
- else
- m_printer->setPaperSize(static_cast<QPrinter::PaperSize>(ps));
-
-#ifdef PSD_ENABLE_PAPERSOURCE
- m_printer->setPaperSource((QPrinter::PaperSource)widget.paperSource->currentIndex());
-#endif
- m_printer->setPageMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin, QPrinter::Point);
-
-}
-
-void QPageSetupWidget::selectPrinter(QCUPSSupport *cups)
-{
- m_cups = cups;
- widget.paperSize->clear();
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- if (m_cups && QCUPSSupport::isAvailable()) {
- const ppd_option_t* pageSizes = m_cups->pageSizes();
- const int numChoices = pageSizes ? pageSizes->num_choices : 0;
-
- int cupsDefaultSize = 0;
- QSize qtPreferredSize = m_printer->paperSize(QPrinter::Point).toSize();
- bool preferredSizeMatched = false;
- for (int i = 0; i < numChoices; ++i) {
- widget.paperSize->addItem(QString::fromLocal8Bit(pageSizes->choices[i].text), QByteArray(pageSizes->choices[i].choice));
- if (static_cast<int>(pageSizes->choices[i].marked) == 1)
- cupsDefaultSize = i;
- if (m_printer->d_func()->hasUserSetPageSize) {
- QRect cupsPaperSize = m_cups->paperRect(pageSizes->choices[i].choice);
- QSize diff = cupsPaperSize.size() - qtPreferredSize;
- if (qAbs(diff.width()) < 5 && qAbs(diff.height()) < 5) {
- widget.paperSize->setCurrentIndex(i);
- preferredSizeMatched = true;
- }
- }
- }
- if (!preferredSizeMatched)
- widget.paperSize->setCurrentIndex(cupsDefaultSize);
- if (m_printer->d_func()->hasCustomPageMargins) {
- m_printer->getPageMargins(&m_leftMargin, &m_topMargin, &m_rightMargin, &m_bottomMargin, QPrinter::Point);
- } else {
- QByteArray cupsPaperSizeChoice = widget.paperSize->itemData(widget.paperSize->currentIndex()).toByteArray();
- QRect paper = m_cups->paperRect(cupsPaperSizeChoice);
- QRect content = m_cups->pageRect(cupsPaperSizeChoice);
-
- m_leftMargin = content.x() - paper.x();
- m_topMargin = content.y() - paper.y();
- m_rightMargin = paper.right() - content.right();
- m_bottomMargin = paper.bottom() - content.bottom();
- }
- }
-#endif
- if (widget.paperSize->count() == 0) {
- populatePaperSizes(widget.paperSize);
- widget.paperSize->setCurrentIndex(widget.paperSize->findData(
- QLocale::system().measurementSystem() == QLocale::ImperialSystem ? QPrinter::Letter : QPrinter::A4));
- }
-
- unitChanged(widget.unit->currentIndex());
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
-}
-
-void QPageSetupWidget::selectPdfPsPrinter(const QPrinter *p)
-{
- m_cups = 0;
- widget.paperSize->clear();
- populatePaperSizes(widget.paperSize);
- widget.paperSize->setCurrentIndex(widget.paperSize->findData(p->paperSize()));
-
- m_leftMargin = 90;
- m_topMargin = 72;
- m_bottomMargin = 72;
- m_rightMargin = 90;
- unitChanged(widget.unit->currentIndex());
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
-}
-
-// Updates size/preview after the combobox has been changed.
-void QPageSetupWidget::_q_paperSizeChanged()
-{
- QVariant val = widget.paperSize->itemData(widget.paperSize->currentIndex());
- int index = m_printer->pageSize();
- if (val.type() == QVariant::Int) {
- index = val.toInt();
- }
-
- if (m_blockSignals) return;
- m_blockSignals = true;
-
- QPrinter::PaperSize size = QPrinter::PaperSize(index);
- QPrinter::Orientation orientation = widget.portrait->isChecked()
- ? QPrinter::Portrait
- : QPrinter::Landscape;
-
- bool custom = size == QPrinter::Custom;
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- custom = custom ? !m_cups : custom;
-#endif
-
- widget.paperWidth->setEnabled(custom);
- widget.paperHeight->setEnabled(custom);
- widget.widthLabel->setEnabled(custom);
- widget.heightLabel->setEnabled(custom);
- if (custom) {
- m_paperSize.setWidth( widget.paperWidth->value() * m_currentMultiplier);
- m_paperSize.setHeight( widget.paperHeight->value() * m_currentMultiplier);
- m_pagePreview->setPaperSize(m_paperSize);
- } else {
- Q_ASSERT(m_printer);
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- if (m_cups) { // combobox is filled with cups based data
- QByteArray cupsPageSize = widget.paperSize->itemData(widget.paperSize->currentIndex()).toByteArray();
- m_paperSize = m_cups->paperRect(cupsPageSize).size();
- if (orientation == QPrinter::Landscape)
- m_paperSize = QSizeF(m_paperSize.height(), m_paperSize.width()); // swap
- }
- else
-#endif
- m_paperSize = qt_printerPaperSize(orientation, size, QPrinter::Point, 1);
-
- m_pagePreview->setPaperSize(m_paperSize);
- widget.paperWidth->setValue(m_paperSize.width() / m_currentMultiplier);
- widget.paperHeight->setValue(m_paperSize.height() / m_currentMultiplier);
- }
- m_blockSignals = false;
-}
-
-void QPageSetupWidget::_q_pageOrientationChanged()
-{
- if (QPrinter::PaperSize(widget.paperSize->currentIndex()) == QPrinter::Custom) {
- double tmp = widget.paperWidth->value();
- widget.paperWidth->setValue(widget.paperHeight->value());
- widget.paperHeight->setValue(tmp);
- }
- _q_paperSizeChanged();
-}
-
-extern double qt_multiplierForUnit(QPrinter::Unit unit, int resolution);
-
-void QPageSetupWidget::unitChanged(int item)
-{
- QString suffix;
- switch(item) {
- case 0:
- m_currentMultiplier = 10 * qt_multiplierForUnit(QPrinter::Millimeter, 1);
- suffix = QString::fromLatin1(" cm");
- break;
- case 2:
- m_currentMultiplier = qt_multiplierForUnit(QPrinter::Inch, 1);
- suffix = QString::fromLatin1(" in");
- break;
- case 3:
- m_currentMultiplier = qt_multiplierForUnit(QPrinter::Point, 1);
- suffix = QString::fromLatin1(" pt");
- break;
- case 1:
- default:
- m_currentMultiplier = qt_multiplierForUnit(QPrinter::Millimeter, 1);
- suffix = QString::fromLatin1(" mm");
- break;
- }
- const bool old = m_blockSignals;
- m_blockSignals = true;
- widget.topMargin->setSuffix(suffix);
- widget.leftMargin->setSuffix(suffix);
- widget.rightMargin->setSuffix(suffix);
- widget.bottomMargin->setSuffix(suffix);
- widget.paperWidth->setSuffix(suffix);
- widget.paperHeight->setSuffix(suffix);
- widget.topMargin->setValue(m_topMargin / m_currentMultiplier);
- widget.leftMargin->setValue(m_leftMargin / m_currentMultiplier);
- widget.rightMargin->setValue(m_rightMargin / m_currentMultiplier);
- widget.bottomMargin->setValue(m_bottomMargin / m_currentMultiplier);
- widget.paperWidth->setValue(m_paperSize.width() / m_currentMultiplier);
- widget.paperHeight->setValue(m_paperSize.height() / m_currentMultiplier);
- m_blockSignals = old;
-}
-
-void QPageSetupWidget::setTopMargin(double newValue)
-{
- if (m_blockSignals) return;
- m_topMargin = newValue * m_currentMultiplier;
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
-}
-
-void QPageSetupWidget::setBottomMargin(double newValue)
-{
- if (m_blockSignals) return;
- m_bottomMargin = newValue * m_currentMultiplier;
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
-}
-
-void QPageSetupWidget::setLeftMargin(double newValue)
-{
- if (m_blockSignals) return;
- m_leftMargin = newValue * m_currentMultiplier;
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
-}
-
-void QPageSetupWidget::setRightMargin(double newValue)
-{
- if (m_blockSignals) return;
- m_rightMargin = newValue * m_currentMultiplier;
- m_pagePreview->setMargins(m_leftMargin, m_topMargin, m_rightMargin, m_bottomMargin);
-}
-
-
-
-QPageSetupDialog::QPageSetupDialog(QPrinter *printer, QWidget *parent)
- : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), printer, parent)
-{
- Q_D(QPageSetupDialog);
- d->init();
-}
-
-
-QPageSetupDialog::QPageSetupDialog(QWidget *parent)
- : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), 0, parent)
-{
- Q_D(QPageSetupDialog);
- d->init();
-}
-
-/*!
- \internal
-*/
-int QPageSetupDialog::exec()
-{
- Q_D(QPageSetupDialog);
-
- int ret = QDialog::exec();
- if (ret == Accepted)
- d->widget->setupPrinter();
- return ret;
-}
-
-
-QT_END_NAMESPACE
-
-#include "moc_qpagesetupdialog.cpp"
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qpagesetupdialog_unix_p.h b/src/gui/dialogs/qpagesetupdialog_unix_p.h
deleted file mode 100644
index fea70b6bfe..0000000000
--- a/src/gui/dialogs/qpagesetupdialog_unix_p.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/****************************************************************************
-**
-** 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 QPAGESETUPWIDGET_H
-#define QPAGESETUPWIDGET_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// to version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include "qglobal.h"
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include <ui_qpagesetupwidget.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPrinter;
-class QPagePreview;
-class QCUPSSupport;
-
-class QPageSetupWidget : public QWidget {
- Q_OBJECT
-public:
- QPageSetupWidget(QWidget *parent = 0);
- QPageSetupWidget(QPrinter *printer, QWidget *parent = 0);
- void setPrinter(QPrinter *printer);
- /// copy information from the widget and apply that to the printer.
- void setupPrinter() const;
- void selectPrinter(QCUPSSupport *m_cups);
- void selectPdfPsPrinter(const QPrinter *p);
-
-private slots:
- void _q_pageOrientationChanged();
- void _q_paperSizeChanged();
- void unitChanged(int item);
- void setTopMargin(double newValue);
- void setBottomMargin(double newValue);
- void setLeftMargin(double newValue);
- void setRightMargin(double newValue);
-
-private:
- Ui::QPageSetupWidget widget;
- QPagePreview *m_pagePreview;
- QPrinter *m_printer;
- qreal m_leftMargin;
- qreal m_topMargin;
- qreal m_rightMargin;
- qreal m_bottomMargin;
- QSizeF m_paperSize;
- qreal m_currentMultiplier;
- bool m_blockSignals;
- QCUPSSupport *m_cups;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTDIALOG
-#endif
diff --git a/src/gui/dialogs/qpagesetupdialog_win.cpp b/src/gui/dialogs/qpagesetupdialog_win.cpp
deleted file mode 100644
index d74da7c2fc..0000000000
--- a/src/gui/dialogs/qpagesetupdialog_win.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpagesetupdialog.h"
-
-#ifndef QT_NO_PRINTDIALOG
-#include <qapplication.h>
-
-#include <private/qprintengine_win_p.h>
-#include <private/qabstractpagesetupdialog_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPageSetupDialogPrivate : public QAbstractPageSetupDialogPrivate
-{
-};
-
-QPageSetupDialog::QPageSetupDialog(QPrinter *printer, QWidget *parent)
- : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), printer, parent)
-{
-}
-
-QPageSetupDialog::QPageSetupDialog(QWidget *parent)
- : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), 0, parent)
-{
-}
-
-int QPageSetupDialog::exec()
-{
- Q_D(QPageSetupDialog);
-
- if (d->printer->outputFormat() != QPrinter::NativeFormat)
- return Rejected;
-
- QWin32PrintEngine *engine = static_cast<QWin32PrintEngine*>(d->printer->paintEngine());
- QWin32PrintEnginePrivate *ep = static_cast<QWin32PrintEnginePrivate *>(engine->d_ptr.data());
-
- PAGESETUPDLG psd;
- memset(&psd, 0, sizeof(PAGESETUPDLG));
- psd.lStructSize = sizeof(PAGESETUPDLG);
-
- // we need a temp DEVMODE struct if we don't have a global DEVMODE
- HGLOBAL hDevMode = 0;
- int devModeSize = 0;
- if (!ep->globalDevMode) {
- devModeSize = sizeof(DEVMODE) + ep->devMode->dmDriverExtra;
- hDevMode = GlobalAlloc(GHND, devModeSize);
- if (hDevMode) {
- void *dest = GlobalLock(hDevMode);
- memcpy(dest, ep->devMode, devModeSize);
- GlobalUnlock(hDevMode);
- }
- psd.hDevMode = hDevMode;
- } else {
- psd.hDevMode = ep->devMode;
- }
-
- HGLOBAL *tempDevNames = ep->createDevNames();
- psd.hDevNames = tempDevNames;
-
- QWidget *parent = parentWidget();
- parent = parent ? parent->window() : QApplication::activeWindow();
- Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
- psd.hwndOwner = parent ? parent->winId() : 0;
-
- QRect paperRect = d->printer->paperRect();
- QRect pageRect = d->printer->pageRect();
-
- psd.Flags = PSD_MARGINS;
- double multiplier = 1;
- switch (QLocale::system().measurementSystem()) {
- case QLocale::MetricSystem:
- psd.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS;
- multiplier = 1;
- break;
- case QLocale::ImperialSystem:
- psd.Flags |= PSD_INTHOUSANDTHSOFINCHES;
- multiplier = 25.4/10;
- break;
- }
-
- QRect marginRect = ep->getPageMargins();
- psd.rtMargin.left = marginRect.left() / multiplier;
- psd.rtMargin.top = marginRect.top() / multiplier;
- psd.rtMargin.right = marginRect.width() / multiplier;;
- psd.rtMargin.bottom = marginRect.height() / multiplier;;
-
- bool result = PageSetupDlg(&psd);
- if (result) {
- ep->readDevnames(psd.hDevNames);
- ep->readDevmode(psd.hDevMode);
-
- QRect theseMargins = QRect(psd.rtMargin.left * multiplier,
- psd.rtMargin.top * multiplier,
- psd.rtMargin.right * multiplier,
- psd.rtMargin.bottom * multiplier);
-
- if (theseMargins != marginRect) {
- ep->setPageMargins(psd.rtMargin.left * multiplier,
- psd.rtMargin.top * multiplier,
- psd.rtMargin.right * multiplier,
- psd.rtMargin.bottom * multiplier);
- }
-
- ep->updateCustomPaperSize();
-
- // copy from our temp DEVMODE struct
- if (!ep->globalDevMode && hDevMode) {
- void *src = GlobalLock(hDevMode);
- memcpy(ep->devMode, src, devModeSize);
- GlobalUnlock(hDevMode);
- }
- }
-
- if (!ep->globalDevMode && hDevMode)
- GlobalFree(hDevMode);
- GlobalFree(tempDevNames);
- done(result);
- return result;
-}
-
-void QPageSetupDialog::setVisible(bool visible)
-{
- if (!visible)
- return;
- exec();
-}
-
-QT_END_NAMESPACE
-#endif
diff --git a/src/gui/dialogs/qpagesetupwidget.ui b/src/gui/dialogs/qpagesetupwidget.ui
deleted file mode 100644
index ace2ab8f44..0000000000
--- a/src/gui/dialogs/qpagesetupwidget.ui
+++ /dev/null
@@ -1,353 +0,0 @@
-<ui version="4.0" >
- <class>QPageSetupWidget</class>
- <widget class="QWidget" name="QPageSetupWidget" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>416</width>
- <height>488</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Form</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_3" >
- <property name="margin" >
- <number>0</number>
- </property>
- <item row="0" column="0" colspan="2" >
- <layout class="QHBoxLayout" name="horizontalLayout_4" >
- <item>
- <widget class="QComboBox" name="unit" />
- </item>
- <item>
- <spacer name="horizontalSpacer_3" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item row="1" column="0" colspan="2" >
- <widget class="QGroupBox" name="groupBox_2" >
- <property name="title" >
- <string>Paper</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_2" >
- <item row="0" column="0" >
- <widget class="QLabel" name="pageSizeLabel" >
- <property name="text" >
- <string>Page size:</string>
- </property>
- <property name="buddy" >
- <cstring>paperSize</cstring>
- </property>
- </widget>
- </item>
- <item row="0" column="1" >
- <widget class="QComboBox" name="paperSize" />
- </item>
- <item row="1" column="0" >
- <widget class="QLabel" name="widthLabel" >
- <property name="text" >
- <string>Width:</string>
- </property>
- <property name="buddy" >
- <cstring>paperWidth</cstring>
- </property>
- </widget>
- </item>
- <item row="1" column="1" >
- <layout class="QHBoxLayout" name="horizontalLayout_3" >
- <item>
- <widget class="QDoubleSpinBox" name="paperWidth" >
- <property name="maximum" >
- <double>9999.989999999999782</double>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="heightLabel" >
- <property name="text" >
- <string>Height:</string>
- </property>
- <property name="buddy" >
- <cstring>paperHeight</cstring>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDoubleSpinBox" name="paperHeight" >
- <property name="maximum" >
- <double>9999.989999999999782</double>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0" >
- <widget class="QLabel" name="paperSourceLabel" >
- <property name="text" >
- <string>Paper source:</string>
- </property>
- <property name="buddy" >
- <cstring>paperSource</cstring>
- </property>
- </widget>
- </item>
- <item row="2" column="1" >
- <widget class="QComboBox" name="paperSource" />
- </item>
- <item row="1" column="2" >
- <spacer name="horizontalSpacer_4" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QGroupBox" name="groupBox_3" >
- <property name="title" >
- <string>Orientation</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout" >
- <item>
- <widget class="QRadioButton" name="portrait" >
- <property name="text" >
- <string>Portrait</string>
- </property>
- <property name="checked" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="landscape" >
- <property name="text" >
- <string>Landscape</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="reverseLandscape" >
- <property name="text" >
- <string>Reverse landscape</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="reversePortrait" >
- <property name="text" >
- <string>Reverse portrait</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_5" >
- <property name="orientation" >
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- <item rowspan="2" row="2" column="1" >
- <widget class="QWidget" native="1" name="preview" />
- </item>
- <item row="3" column="0" >
- <widget class="QGroupBox" name="groupBox" >
- <property name="title" >
- <string>Margins</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout_2" >
- <item>
- <layout class="QGridLayout" name="gridLayout" >
- <item row="0" column="1" >
- <widget class="QDoubleSpinBox" name="topMargin" >
- <property name="toolTip" >
- <string>top margin</string>
- </property>
- <property name="accessibleName" >
- <string>top margin</string>
- </property>
- <property name="alignment" >
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="maximum" >
- <double>999.990000000000009</double>
- </property>
- </widget>
- </item>
- <item row="1" column="0" colspan="3" >
- <layout class="QHBoxLayout" name="horizontalLayout" >
- <item>
- <spacer name="horizontalSpacer_7" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>0</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QDoubleSpinBox" name="leftMargin" >
- <property name="toolTip" >
- <string>left margin</string>
- </property>
- <property name="accessibleName" >
- <string>left margin</string>
- </property>
- <property name="alignment" >
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="maximum" >
- <double>999.990000000000009</double>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType" >
- <enum>QSizePolicy::MinimumExpanding</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QDoubleSpinBox" name="rightMargin" >
- <property name="toolTip" >
- <string>right margin</string>
- </property>
- <property name="accessibleName" >
- <string>right margin</string>
- </property>
- <property name="alignment" >
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="maximum" >
- <double>999.990000000000009</double>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer_8" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>0</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item row="2" column="1" >
- <widget class="QDoubleSpinBox" name="bottomMargin" >
- <property name="toolTip" >
- <string>bottom margin</string>
- </property>
- <property name="accessibleName" >
- <string>bottom margin</string>
- </property>
- <property name="alignment" >
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="maximum" >
- <double>999.990000000000009</double>
- </property>
- </widget>
- </item>
- <item row="0" column="2" >
- <spacer name="horizontalSpacer_2" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType" >
- <enum>QSizePolicy::MinimumExpanding</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>0</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item row="0" column="0" >
- <spacer name="horizontalSpacer_5" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType" >
- <enum>QSizePolicy::MinimumExpanding</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>0</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item row="4" column="0" >
- <spacer name="verticalSpacer" >
- <property name="orientation" >
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0" >
- <size>
- <width>20</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/gui/dialogs/qprintdialog.h b/src/gui/dialogs/qprintdialog.h
deleted file mode 100644
index 05431608c4..0000000000
--- a/src/gui/dialogs/qprintdialog.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** 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 QPRINTDIALOG_H
-#define QPRINTDIALOG_H
-
-#include <QtGui/qabstractprintdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PRINTDIALOG
-
-class QPrintDialogPrivate;
-class QPushButton;
-class QPrinter;
-
-#if defined (Q_OS_UNIX) && !defined(QTOPIA_PRINTDIALOG) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
-class QUnixPrintWidgetPrivate;
-
-class Q_GUI_EXPORT QUnixPrintWidget : public QWidget
-{
- Q_OBJECT
-
-public:
- QUnixPrintWidget(QPrinter *printer, QWidget *parent = 0);
- ~QUnixPrintWidget();
- void updatePrinter();
-
-private:
- friend class QPrintDialogPrivate;
- friend class QUnixPrintWidgetPrivate;
- QUnixPrintWidgetPrivate *d;
- Q_PRIVATE_SLOT(d, void _q_printerChanged(int))
- Q_PRIVATE_SLOT(d, void _q_btnBrowseClicked())
- Q_PRIVATE_SLOT(d, void _q_btnPropertiesClicked())
-};
-#endif
-
-class Q_GUI_EXPORT QPrintDialog : public QAbstractPrintDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPrintDialog)
- Q_ENUMS(PrintDialogOption)
- Q_PROPERTY(PrintDialogOptions options READ options WRITE setOptions)
-
-public:
- explicit QPrintDialog(QPrinter *printer, QWidget *parent = 0);
- explicit QPrintDialog(QWidget *parent = 0);
- ~QPrintDialog();
-
- int exec();
-#if defined (Q_OS_UNIX) && !defined(QTOPIA_PRINTDIALOG) && !defined(Q_WS_MAC)
- virtual void accept();
-#endif
- void done(int result);
-
-#if defined (Q_OS_UNIX) && defined (QT3_SUPPORT)
- QT3_SUPPORT void setPrinter(QPrinter *, bool = false);
- QT3_SUPPORT QPrinter *printer() const;
- QT3_SUPPORT void addButton(QPushButton *button);
-#endif
-
- void setOption(PrintDialogOption option, bool on = true);
- bool testOption(PrintDialogOption option) const;
- void setOptions(PrintDialogOptions options);
- PrintDialogOptions options() const;
-
-#if defined(Q_OS_UNIX) || defined(Q_WS_MAC) || defined(Q_OS_WIN)
- void setVisible(bool visible);
-#endif
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
-#ifdef qdoc
- QPrinter *printer();
-#endif
-
-#ifdef QTOPIA_PRINTDIALOG
-public:
- bool eventFilter(QObject *, QEvent *);
-#endif
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void accepted() { QDialog::accepted(); }
-#endif
-#else
- using QDialog::accepted;
-#endif
-
-Q_SIGNALS:
- void accepted(QPrinter *printer);
-
-private:
-#ifndef QTOPIA_PRINTDIALOG
- Q_PRIVATE_SLOT(d_func(), void _q_chbPrintLastFirstToggled(bool))
-#if defined (Q_OS_UNIX) && !defined (Q_OS_MAC)
- Q_PRIVATE_SLOT(d_func(), void _q_collapseOrExpandDialog())
-#endif
-# if defined(Q_OS_UNIX) && !defined (Q_OS_MAC) && !defined(QT_NO_MESSAGEBOX)
- Q_PRIVATE_SLOT(d_func(), void _q_checkFields())
-# endif
-#else // QTOPIA_PRINTDIALOG
- Q_PRIVATE_SLOT(d_func(), void _q_okClicked())
- Q_PRIVATE_SLOT(d_func(),void _q_printerOrFileSelected(QAbstractButton *b))
- Q_PRIVATE_SLOT(d_func(),void _q_paperSizeSelected(int))
- Q_PRIVATE_SLOT(d_func(), void _q_orientSelected(int))
- Q_PRIVATE_SLOT(d_func(), void _q_pageOrderSelected(int))
- Q_PRIVATE_SLOT(d_func(), void _q_colorModeSelected(QAbstractButton *))
- Q_PRIVATE_SLOT(d_func(), void _q_setNumCopies(int))
- Q_PRIVATE_SLOT(d_func(), void _q_printRangeSelected(int))
- Q_PRIVATE_SLOT(d_func(), void _q_setFirstPage(int))
- Q_PRIVATE_SLOT(d_func(), void _q_setLastPage(int))
- Q_PRIVATE_SLOT(d_func(), void _q_fileNameEditChanged(const QString &text))
-#endif // QTOPIA_PRINTDIALOG
- friend class QUnixPrintWidget;
-};
-
-#endif // QT_NO_PRINTDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPRINTDIALOG_H
diff --git a/src/gui/dialogs/qprintdialog.qdoc b/src/gui/dialogs/qprintdialog.qdoc
deleted file mode 100644
index 0fff9dd450..0000000000
--- a/src/gui/dialogs/qprintdialog.qdoc
+++ /dev/null
@@ -1,58 +0,0 @@
-/****************************************************************************
-**
-** 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 documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** 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 Free Documentation License
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of this
-** file.
-**
-** If you have questions regarding the use of this file, please contact
-** Nokia at qt-info@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifdef QT3_SUPPORT
-/*!
- \fn QPrinter *QPrintDialog::printer() const
-
- Returns a pointer to the printer this dialog configures, or 0 if
- this dialog does not operate on any printer.
-
- This function is available for Unix platforms only.
-*/
-
-/*!
- \fn void QPrintDialog::setPrinter(QPrinter *printer, bool pickupSettings)
-
- Sets this dialog to configure printer \a printer, or no printer if \a printer
- is null. If \a pickupSettings is true, the dialog reads most of
- its settings from \a printer. If \a pickupSettings is false (the
- default) the dialog keeps its old settings.
-
- This function is available for Unix platforms only.
-*/
-
-/*!
- \fn void QPrintDialog::addButton(QPushButton *button)
-
- Adds the \a button to the layout of the print dialog. The added
- buttons are arranged from the left to the right below the
- last groupbox of the printdialog.
-
- This function is available for Unix platforms only.
-*/
-#endif
diff --git a/src/gui/dialogs/qprintdialog.qrc b/src/gui/dialogs/qprintdialog.qrc
deleted file mode 100644
index f54eb6b5ee..0000000000
--- a/src/gui/dialogs/qprintdialog.qrc
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/dialogs/qprintpreviewdialog">
-<file>images/fit-page-24.png</file>
-<file>images/fit-page-32.png</file>
-<file>images/fit-width-24.png</file>
-<file>images/fit-width-32.png</file>
-<file>images/go-first-24.png</file>
-<file>images/go-first-32.png</file>
-<file>images/go-last-24.png</file>
-<file>images/go-last-32.png</file>
-<file>images/go-next-24.png</file>
-<file>images/go-next-32.png</file>
-<file>images/go-previous-24.png</file>
-<file>images/go-previous-32.png</file>
-<file>images/layout-landscape-24.png</file>
-<file>images/layout-landscape-32.png</file>
-<file>images/layout-portrait-24.png</file>
-<file>images/layout-portrait-32.png</file>
-<file>images/page-setup-24.png</file>
-<file>images/page-setup-32.png</file>
-<file>images/print-24.png</file>
-<file>images/print-32.png</file>
-<file>images/view-page-multi-24.png</file>
-<file>images/view-page-multi-32.png</file>
-<file>images/view-page-one-24.png</file>
-<file>images/view-page-one-32.png</file>
-<file>images/view-page-sided-24.png</file>
-<file>images/view-page-sided-32.png</file>
-<file>images/zoom-in-24.png</file>
-<file>images/zoom-in-32.png</file>
-<file>images/zoom-out-24.png</file>
-<file>images/zoom-out-32.png</file>
-</qresource>
-<qresource prefix="/trolltech/dialogs/qprintdialog">
-<file>images/status-color.png</file>
-<file>images/status-gray-scale.png</file>
-</qresource>
-</RCC>
diff --git a/src/gui/dialogs/qprintdialog_mac.mm b/src/gui/dialogs/qprintdialog_mac.mm
deleted file mode 100644
index ed60b1016f..0000000000
--- a/src/gui/dialogs/qprintdialog_mac.mm
+++ /dev/null
@@ -1,429 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_PRINTDIALOG
-
-#include <private/qt_mac_p.h>
-
-#include <qhash.h>
-#include <qprintdialog.h>
-#include <private/qapplication_p.h>
-#include <private/qabstractprintdialog_p.h>
-#include <private/qprintengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
-{
- Q_DECLARE_PUBLIC(QPrintDialog)
-
-public:
- QPrintDialogPrivate() : ep(0), printPanel(0)
-#ifndef QT_MAC_USE_COCOA
- ,upp(0)
-#endif
- {}
-#ifndef QT_MAC_USE_COCOA
- ~QPrintDialogPrivate() {
- if (upp) {
- DisposePMSheetDoneUPP(upp);
- upp = 0;
- }
- QHash<PMPrintSession, QPrintDialogPrivate *>::iterator it = sheetCallbackMap.begin();
- while (it != sheetCallbackMap.end()) {
- if (it.value() == this) {
- it = sheetCallbackMap.erase(it);
- } else {
- ++it;
- }
- }
- }
-#endif
-
-#ifndef QT_MAC_USE_COCOA
- void openCarbonPrintPanel(Qt::WindowModality modality);
- void closeCarbonPrintPanel();
- static void printDialogSheetDoneCallback(PMPrintSession printSession, WindowRef /*documentWindow*/, Boolean accepted) {
- QPrintDialogPrivate *priv = sheetCallbackMap.value(printSession);
- if (!priv) {
- qWarning("%s:%d: QPrintDialog::exec: Could not retrieve data structure, "
- "you most likely now have an infinite loop", __FILE__, __LINE__);
- return;
- }
- priv->q_func()->done(accepted ? QDialog::Accepted : QDialog::Rejected);
- priv->closeCarbonPrintPanel();
- }
-#else
- void openCocoaPrintPanel(Qt::WindowModality modality);
- void closeCocoaPrintPanel();
-#endif
- void initBeforeRun();
-
- inline QPrintDialog *printDialog() { return q_func(); }
-
- inline void _q_printToFileChanged(int) {}
- inline void _q_rbPrintRangeToggled(bool) {}
- inline void _q_printerChanged(int) {}
-#ifndef QT_NO_MESSAGEBOX
- inline void _q_checkFields() {}
-#endif
- inline void _q_chbPrintLastFirstToggled(bool) {}
- inline void _q_paperSizeChanged(int) {}
- inline void _q_btnBrowseClicked() {}
- inline void _q_btnPropertiesClicked() {}
-
- QMacPrintEnginePrivate *ep;
- NSPrintPanel *printPanel;
-#ifndef QT_MAC_USE_COCOA
- PMSheetDoneUPP upp;
- static QHash<PMPrintSession, QPrintDialogPrivate *> sheetCallbackMap;
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-
-@class QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate) : NSObject {
-}
-- (void)printPanelDidEnd:(NSPrintPanel *)printPanel
- returnCode:(int)returnCode contextInfo:(void *)contextInfo;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate)
-- (void)printPanelDidEnd:(NSPrintPanel *)printPanel
- returnCode:(int)returnCode contextInfo:(void *)contextInfo
-{
- Q_UNUSED(printPanel);
-
- QPrintDialogPrivate *d = static_cast<QPrintDialogPrivate *>(contextInfo);
- QPrintDialog *dialog = d->printDialog();
-
- if (returnCode == NSOKButton) {
- UInt32 frompage, topage;
- PMGetFirstPage(d->ep->settings, &frompage);
- PMGetLastPage(d->ep->settings, &topage);
- topage = qMin(UInt32(INT_MAX), topage);
- dialog->setFromTo(frompage, topage);
-
- // OK, I need to map these values back let's see
- // If from is 1 and to is INT_MAX, then print it all
- // (Apologies to the folks with more than INT_MAX pages)
- if (dialog->fromPage() == 1 && dialog->toPage() == INT_MAX) {
- dialog->setPrintRange(QPrintDialog::AllPages);
- dialog->setFromTo(0, 0);
- } else {
- dialog->setPrintRange(QPrintDialog::PageRange); // In a way a lie, but it shouldn't hurt.
- // Carbon hands us back a very large number here even for ALL, set it to max
- // in that case to follow the behavior of the other print dialogs.
- if (dialog->maxPage() < dialog->toPage())
- dialog->setFromTo(dialog->fromPage(), dialog->maxPage());
- }
- // Keep us in sync with file output
- PMDestinationType dest;
-
- // If the user selected print to file, the session has been
- // changed behind our back and our d->ep->session object is a
- // dangling pointer. Update it based on the "current" session
- d->ep->session = static_cast<PMPrintSession>([d->ep->printInfo PMPrintSession]);
-
- PMSessionGetDestinationType(d->ep->session, d->ep->settings, &dest);
- if (dest == kPMDestinationFile) {
- QCFType<CFURLRef> file;
- PMSessionCopyDestinationLocation(d->ep->session, d->ep->settings, &file);
- UInt8 localFile[2048]; // Assuming there's a POSIX file system here.
- CFURLGetFileSystemRepresentation(file, true, localFile, sizeof(localFile));
- d->ep->outputFilename
- = QString::fromUtf8(reinterpret_cast<const char *>(localFile));
- } else {
- // Keep output format.
- QPrinter::OutputFormat format;
- format = d->printer->outputFormat();
- d->printer->setOutputFileName(QString());
- d->printer->setOutputFormat(format);
- }
- }
-
- dialog->done((returnCode == NSOKButton) ? QDialog::Accepted : QDialog::Rejected);
-}
-@end
-
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptWindowTitle(QWidget *window);
-extern void macStopInterceptWindowTitle();
-
-
-void QPrintDialogPrivate::initBeforeRun()
-{
- Q_Q(QPrintDialog);
- // If someone is reusing a QPrinter object, the end released all our old
- // information. In this case, we must reinitialize.
- if (ep->session == 0)
- ep->initialize();
-
-
- // It seems the only way that PM lets you use all is if the minimum
- // for the page range is 1. This _kind of_ makes sense if you think about
- // it. However, calling PMSetFirstPage() or PMSetLastPage() always enforces
- // the range.
- PMSetPageRange(ep->settings, q->minPage(), q->maxPage());
- if (q->printRange() == QAbstractPrintDialog::PageRange) {
- PMSetFirstPage(ep->settings, q->fromPage(), false);
- PMSetLastPage(ep->settings, q->toPage(), false);
- }
-}
-
-#ifndef QT_MAC_USE_COCOA
-QHash<PMPrintSession, QPrintDialogPrivate *> QPrintDialogPrivate::sheetCallbackMap;
-void QPrintDialogPrivate::openCarbonPrintPanel(Qt::WindowModality modality)
-{
- Q_Q(QPrintDialog);
- initBeforeRun();
- sheetCallbackMap.insert(ep->session, this);
- if (modality == Qt::ApplicationModal) {
- QWidget modal_widg(0, Qt::Window);
- modal_widg.setObjectName(QLatin1String(__FILE__ "__modal_dlg"));
- modal_widg.createWinId();
- QApplicationPrivate::enterModal(&modal_widg);
- QApplicationPrivate::native_modal_dialog_active = true;
- Boolean acceptStatus;
- PMSessionPrintDialog(ep->session, ep->settings, ep->format, &acceptStatus);
- QApplicationPrivate::leaveModal(&modal_widg);
- QApplicationPrivate::native_modal_dialog_active = false;
- printDialogSheetDoneCallback(ep->session, 0, acceptStatus);
- } else {
- // Window Modal means that we use a sheet at the moment, there's no other way to do it correctly.
- if (!upp)
- upp = NewPMSheetDoneUPP(QPrintDialogPrivate::printDialogSheetDoneCallback);
- PMSessionUseSheets(ep->session, qt_mac_window_for(q->parentWidget()), upp);
- QApplicationPrivate::native_modal_dialog_active = true;
- Boolean unused;
- PMSessionPrintDialog(ep->session, ep->settings, ep->format, &unused);
- }
-}
-
-void QPrintDialogPrivate::closeCarbonPrintPanel()
-{
- Q_Q(QPrintDialog);
- QApplicationPrivate::native_modal_dialog_active = false;
- if (q->result() == QDialog::Accepted) {
- UInt32 frompage, topage;
- PMGetFirstPage(ep->settings, &frompage);
- PMGetLastPage(ep->settings, &topage);
- topage = qMin(UInt32(INT_MAX), topage);
- q->setFromTo(frompage, topage);
-
- // OK, I need to map these values back let's see
- // If from is 1 and to is INT_MAX, then print it all
- // (Apologies to the folks with more than INT_MAX pages)
- // ...that's a joke.
- if (q->fromPage() == 1 && q->toPage() == INT_MAX) {
- q->setPrintRange(QAbstractPrintDialog::AllPages);
- q->setFromTo(0,0);
- } else {
- q->setPrintRange(QAbstractPrintDialog::PageRange); // In a way a lie, but it shouldn't hurt.
- // Carbon hands us back a very large number here even for ALL, set it to max
- // in that case to follow the behavior of the other print dialogs.
- if (q->maxPage() < q->toPage())
- q->setFromTo(q->fromPage(), q->maxPage());
- }
- // Keep us in sync with file output
- PMDestinationType dest;
- PMSessionGetDestinationType(ep->session, ep->settings, &dest);
- if (dest == kPMDestinationFile) {
- QCFType<CFURLRef> file;
- PMSessionCopyDestinationLocation(ep->session, ep->settings, &file);
- UInt8 localFile[2048]; // Assuming there's a POSIX file system here.
- CFURLGetFileSystemRepresentation(file, true, localFile, sizeof(localFile));
- ep->outputFilename = QString::fromUtf8(reinterpret_cast<const char *>(localFile));
- } else {
- ep->outputFilename = QString();
- }
- }
- sheetCallbackMap.remove(ep->session);
-}
-#else
-void QPrintDialogPrivate::openCocoaPrintPanel(Qt::WindowModality modality)
-{
- Q_Q(QPrintDialog);
-
- initBeforeRun();
-
- QPrintDialog::PrintDialogOptions qtOptions = q->options();
- NSPrintPanelOptions macOptions = NSPrintPanelShowsCopies;
- if (qtOptions & QPrintDialog::PrintPageRange)
- macOptions |= NSPrintPanelShowsPageRange;
- if (qtOptions & QPrintDialog::PrintShowPageSize)
- macOptions |= NSPrintPanelShowsPaperSize | NSPrintPanelShowsPageSetupAccessory
- | NSPrintPanelShowsOrientation;
-
- macStartInterceptWindowTitle(q);
- printPanel = [NSPrintPanel printPanel];
- QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate) *delegate = [[QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate) alloc] init];
- [printPanel setOptions:macOptions];
-
- if (modality == Qt::ApplicationModal) {
- int rval = [printPanel runModalWithPrintInfo:ep->printInfo];
- [delegate printPanelDidEnd:printPanel returnCode:rval contextInfo:this];
- } else {
- Q_ASSERT(q->parentWidget());
- NSWindow *windowRef = qt_mac_window_for(q->parentWidget());
- [printPanel beginSheetWithPrintInfo:ep->printInfo
- modalForWindow:windowRef
- delegate:delegate
- didEndSelector:@selector(printPanelDidEnd:returnCode:contextInfo:)
- contextInfo:this];
- }
-
- macStopInterceptWindowTitle();
-}
-
-void QPrintDialogPrivate::closeCocoaPrintPanel()
-{
- // ###
-}
-#endif
-
-static bool warnIfNotNative(QPrinter *printer)
-{
- if (printer->outputFormat() != QPrinter::NativeFormat) {
- qWarning("QPrintDialog: Cannot be used on non-native printers");
- return false;
- }
- return true;
-}
-
-
-QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
- : QAbstractPrintDialog(*(new QPrintDialogPrivate), printer, parent)
-{
- Q_D(QPrintDialog);
- if (!warnIfNotNative(d->printer))
- return;
- d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::QPrintDialog(QWidget *parent)
- : QAbstractPrintDialog(*(new QPrintDialogPrivate), 0, parent)
-{
- Q_D(QPrintDialog);
- if (!warnIfNotNative(d->printer))
- return;
- d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::~QPrintDialog()
-{
-}
-
-int QPrintDialog::exec()
-{
- Q_D(QPrintDialog);
- if (!warnIfNotNative(d->printer))
- return QDialog::Rejected;
-
-#ifndef QT_MAC_USE_COCOA
- d->openCarbonPrintPanel(Qt::ApplicationModal);
-#else
- QMacCocoaAutoReleasePool pool;
-
- d->openCocoaPrintPanel(Qt::ApplicationModal);
- d->closeCocoaPrintPanel();
-#endif
- return result();
-}
-
-#ifdef QT3_SUPPORT
-QPrinter *QPrintDialog::printer() const
-{
- Q_D(const QPrintDialog);
- return d->printer;
-}
-#endif
-
-/*!
- \reimp
-*/
-void QPrintDialog::setVisible(bool visible)
-{
- Q_D(QPrintDialog);
-
- bool isCurrentlyVisible = (d->printPanel != 0);
-
- if (!visible == !isCurrentlyVisible)
- return;
-
- if (d->printer->outputFormat() != QPrinter::NativeFormat)
- return;
-
- if (visible) {
-#ifndef QT_MAC_USE_COCOA
- d->openCarbonPrintPanel(parentWidget() ? Qt::WindowModal
- : Qt::ApplicationModal);
-#else
- d->openCocoaPrintPanel(parentWidget() ? Qt::WindowModal
- : Qt::ApplicationModal);
-#endif
- return;
- } else {
- if (d->printPanel) {
-#ifndef QT_MAC_USE_COCOA
- d->closeCarbonPrintPanel();
-#else
- d->closeCocoaPrintPanel();
-#endif
- return;
- }
- }
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qprintdialog.cpp"
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qprintdialog_unix.cpp b/src/gui/dialogs/qprintdialog_unix.cpp
deleted file mode 100644
index c6a1474b21..0000000000
--- a/src/gui/dialogs/qprintdialog_unix.cpp
+++ /dev/null
@@ -1,1286 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include "private/qabstractprintdialog_p.h"
-#include <QtGui/qmessagebox.h>
-#include "qprintdialog.h"
-#include "qfiledialog.h"
-#include <QtCore/qdir.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qfilesystemmodel.h>
-#include <QtGui/qstyleditemdelegate.h>
-#include <QtGui/qprinter.h>
-
-#include <QtGui/qdialogbuttonbox.h>
-
-#include "qfscompleter_p.h"
-#include "ui_qprintpropertieswidget.h"
-#include "ui_qprintsettingsoutput.h"
-#include "ui_qprintwidget.h"
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-# include <private/qcups_p.h>
-# include <cups/cups.h>
-# include <private/qpdf_p.h>
-#else
-# include <QtCore/qlibrary.h>
-#endif
-
-#include <private/qprinterinfo_unix_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QOptionTreeItem;
-class QPPDOptionsModel;
-
-class QPrintPropertiesDialog : public QDialog
-{
- Q_OBJECT
-public:
- QPrintPropertiesDialog(QAbstractPrintDialog *parent = 0);
- ~QPrintPropertiesDialog();
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- void setCups(QCUPSSupport *cups) { m_cups = cups; }
- void addItemToOptions(QOptionTreeItem *parent, QList<const ppd_option_t*>& options, QList<const char*>& markedOptions) const;
-#endif
-
- void selectPrinter();
- void selectPdfPsPrinter(const QPrinter *p);
-
- /// copy printer properties to the widget
- void applyPrinterProperties(QPrinter *p);
- void setupPrinter() const;
-
-protected:
- void showEvent(QShowEvent* event);
-
-private:
- Ui::QPrintPropertiesWidget widget;
- QDialogButtonBox *m_buttons;
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- QCUPSSupport *m_cups;
- QPPDOptionsModel *m_cupsOptionsModel;
-#endif
-};
-
-class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
-{
- Q_DECLARE_PUBLIC(QPrintDialog)
- Q_DECLARE_TR_FUNCTIONS(QPrintDialog)
-public:
- QPrintDialogPrivate();
- ~QPrintDialogPrivate();
-
- void init();
- /// copy printer properties to the widget
- void applyPrinterProperties(QPrinter *p);
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- void selectPrinter(QCUPSSupport *cups);
-#endif
-
- void _q_chbPrintLastFirstToggled(bool);
-#ifndef QT_NO_MESSAGEBOX
- void _q_checkFields();
-#endif
- void _q_collapseOrExpandDialog();
-
- void setupPrinter();
- void updateWidgets();
-
- virtual void setTabs(const QList<QWidget*> &tabs);
-
- Ui::QPrintSettingsOutput options;
- QUnixPrintWidget *top;
- QWidget *bottom;
- QDialogButtonBox *buttons;
- QPushButton *collapseButton;
-};
-
-#if defined (Q_OS_UNIX)
-class QUnixPrintWidgetPrivate
-{
-public:
- QUnixPrintWidgetPrivate(QUnixPrintWidget *q);
- ~QUnixPrintWidgetPrivate();
-
- /// copy printer properties to the widget
- void applyPrinterProperties(QPrinter *p);
- bool checkFields();
- void setupPrinter();
- void setOptionsPane(QPrintDialogPrivate *pane);
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- void setCupsProperties();
-#endif
-
-// slots
- void _q_printerChanged(int index);
- void _q_btnPropertiesClicked();
- void _q_btnBrowseClicked();
-
- QUnixPrintWidget * const parent;
- QPrintPropertiesDialog *propertiesDialog;
- Ui::QPrintWidget widget;
- QAbstractPrintDialog * q;
- QPrinter *printer;
- QList<QPrinterDescription> lprPrinters;
- void updateWidget();
-
-private:
- QPrintDialogPrivate *optionsPane;
- bool filePrintersAdded;
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- QCUPSSupport* cups;
- int cupsPrinterCount;
- const cups_dest_t* cupsPrinters;
- const ppd_file_t* cupsPPD;
-#endif
-};
-#endif
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-class QOptionTreeItem
-{
-public:
- enum ItemType { Root, Group, Option, Choice };
-
- QOptionTreeItem(ItemType t, int i, const void* p, const char* desc, QOptionTreeItem* pi)
- : type(t),
- index(i),
- ptr(p),
- description(desc),
- selected(-1),
- selDescription(0),
- parentItem(pi) {}
-
- ~QOptionTreeItem() {
- while (!childItems.isEmpty())
- delete childItems.takeFirst();
- }
-
- ItemType type;
- int index;
- const void* ptr;
- const char* description;
- int selected;
- const char* selDescription;
- QOptionTreeItem* parentItem;
- QList<QOptionTreeItem*> childItems;
-};
-
-class QPPDOptionsModel : public QAbstractItemModel
-{
- friend class QPPDOptionsEditor;
-public:
- QPPDOptionsModel(QCUPSSupport *cups, QObject *parent = 0);
- ~QPPDOptionsModel();
-
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- Qt::ItemFlags flags(const QModelIndex& index) const;
- QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;
-
- QOptionTreeItem* rootItem;
- QCUPSSupport *cups;
- const ppd_file_t* ppd;
- void parseItems();
- void parseGroups(QOptionTreeItem* parent);
- void parseOptions(QOptionTreeItem* parent);
- void parseChoices(QOptionTreeItem* parent);
-};
-
-class QPPDOptionsEditor : public QStyledItemDelegate
-{
- Q_OBJECT
-public:
- QPPDOptionsEditor(QObject* parent = 0) : QStyledItemDelegate(parent) {}
- ~QPPDOptionsEditor() {}
-
- QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void setEditorData(QWidget* editor, const QModelIndex& index) const;
- void setModelData( QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const;
-
-private slots:
- void cbChanged(int index);
-
-};
-
-#endif
-
-////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-QPrintPropertiesDialog::QPrintPropertiesDialog(QAbstractPrintDialog *parent)
- : QDialog(parent)
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- , m_cups(0), m_cupsOptionsModel(0)
-#endif
-{
- QVBoxLayout *lay = new QVBoxLayout(this);
- this->setLayout(lay);
- QWidget *content = new QWidget(this);
- widget.setupUi(content);
- m_buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
- lay->addWidget(content);
- lay->addWidget(m_buttons);
-
- connect(m_buttons->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept()));
- connect(m_buttons->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(reject()));
-}
-
-QPrintPropertiesDialog::~QPrintPropertiesDialog()
-{
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- delete m_cupsOptionsModel;
-#else
- delete widget.cupsPropertiesPage;
-#endif
-}
-
-void QPrintPropertiesDialog::applyPrinterProperties(QPrinter *p)
-{
- widget.pageSetup->setPrinter(p);
-}
-
-void QPrintPropertiesDialog::setupPrinter() const
-{
- widget.pageSetup->setupPrinter();
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- QPPDOptionsModel* model = static_cast<QPPDOptionsModel*>(widget.treeView->model());
- if (model) {
- QOptionTreeItem* rootItem = model->rootItem;
- QList<const ppd_option_t*> options;
- QList<const char*> markedOptions;
-
- addItemToOptions(rootItem, options, markedOptions);
- model->cups->saveOptions(options, markedOptions);
- }
-#endif
-}
-
-void QPrintPropertiesDialog::selectPrinter()
-{
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- widget.pageSetup->selectPrinter(m_cups);
- widget.treeView->setModel(0);
- if (m_cups && QCUPSSupport::isAvailable()) {
-
- if (m_cupsOptionsModel == 0) {
- m_cupsOptionsModel = new QPPDOptionsModel(m_cups);
-
- widget.treeView->setItemDelegate(new QPPDOptionsEditor(this));
- } else {
- // update the model
- m_cupsOptionsModel->parseItems();
- }
-
- if (m_cupsOptionsModel->rowCount() > 0) {
- widget.treeView->setModel(m_cupsOptionsModel);
-
- for (int i = 0; i < m_cupsOptionsModel->rowCount(); ++i)
- widget.treeView->expand(m_cupsOptionsModel->index(i,0));
-
- widget.tabs->setTabEnabled(1, true); // enable the advanced tab
- } else {
- widget.tabs->setTabEnabled(1, false);
- }
-
- } else
-#endif
- {
- widget.cupsPropertiesPage->setEnabled(false);
- widget.pageSetup->selectPrinter(0);
- }
-}
-
-void QPrintPropertiesDialog::selectPdfPsPrinter(const QPrinter *p)
-{
- widget.treeView->setModel(0);
- widget.pageSetup->selectPdfPsPrinter(p);
- widget.tabs->setTabEnabled(1, false); // disable the advanced tab
-}
-
-void QPrintPropertiesDialog::showEvent(QShowEvent* event)
-{
- widget.treeView->resizeColumnToContents(0);
- event->accept();
-}
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-void QPrintPropertiesDialog::addItemToOptions(QOptionTreeItem *parent, QList<const ppd_option_t*>& options, QList<const char*>& markedOptions) const
-{
- for (int i = 0; i < parent->childItems.count(); ++i) {
- QOptionTreeItem *itm = parent->childItems.at(i);
- if (itm->type == QOptionTreeItem::Option) {
- const ppd_option_t* opt = reinterpret_cast<const ppd_option_t*>(itm->ptr);
- options << opt;
- if (qstrcmp(opt->defchoice, opt->choices[itm->selected].choice) != 0) {
- markedOptions << opt->keyword << opt->choices[itm->selected].choice;
- }
- } else {
- addItemToOptions(itm, options, markedOptions);
- }
- }
-}
-#endif
-
-QPrintDialogPrivate::QPrintDialogPrivate()
- : top(0), bottom(0), buttons(0), collapseButton(0)
-{
-}
-
-QPrintDialogPrivate::~QPrintDialogPrivate()
-{
-}
-
-void QPrintDialogPrivate::init()
-{
- Q_Q(QPrintDialog);
-
- top = new QUnixPrintWidget(0, q);
- bottom = new QWidget(q);
- options.setupUi(bottom);
- options.color->setIconSize(QSize(32, 32));
- options.color->setIcon(QIcon(QLatin1String(":/trolltech/dialogs/qprintdialog/images/status-color.png")));
- options.grayscale->setIconSize(QSize(32, 32));
- options.grayscale->setIcon(QIcon(QLatin1String(":/trolltech/dialogs/qprintdialog/images/status-gray-scale.png")));
- top->d->setOptionsPane(this);
-
- buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, q);
- collapseButton = new QPushButton(QPrintDialog::tr("&Options >>"), buttons);
- buttons->addButton(collapseButton, QDialogButtonBox::ResetRole);
- bottom->setVisible(false);
-
- QPushButton *printButton = buttons->button(QDialogButtonBox::Ok);
- printButton->setText(QPrintDialog::tr("&Print"));
- printButton->setDefault(true);
-
- QVBoxLayout *lay = new QVBoxLayout(q);
- q->setLayout(lay);
- lay->addWidget(top);
- lay->addWidget(bottom);
- lay->addWidget(buttons);
-
- QPrinter* p = q->printer();
-
- applyPrinterProperties(p);
-
-#ifdef QT_NO_MESSAGEBOX
- QObject::connect(buttons, SIGNAL(accepted()), q, SLOT(accept()));
-#else
- QObject::connect(buttons, SIGNAL(accepted()), q, SLOT(_q_checkFields()));
-#endif
- QObject::connect(buttons, SIGNAL(rejected()), q, SLOT(reject()));
-
- QObject::connect(options.reverse, SIGNAL(toggled(bool)),
- q, SLOT(_q_chbPrintLastFirstToggled(bool)));
-
- QObject::connect(collapseButton, SIGNAL(released()), q, SLOT(_q_collapseOrExpandDialog()));
-}
-
-void QPrintDialogPrivate::applyPrinterProperties(QPrinter *p)
-{
- if (p->colorMode() == QPrinter::Color)
- options.color->setChecked(true);
- else
- options.grayscale->setChecked(true);
-
- switch(p->duplex()) {
- case QPrinter::DuplexNone:
- options.noDuplex->setChecked(true); break;
- case QPrinter::DuplexLongSide:
- case QPrinter::DuplexAuto:
- options.duplexLong->setChecked(true); break;
- case QPrinter::DuplexShortSide:
- options.duplexShort->setChecked(true); break;
- }
- options.copies->setValue(p->copyCount());
- options.collate->setChecked(p->collateCopies());
- options.reverse->setChecked(p->pageOrder() == QPrinter::LastPageFirst);
- top->d->applyPrinterProperties(p);
-}
-
-void QPrintDialogPrivate::_q_chbPrintLastFirstToggled(bool checked)
-{
- Q_Q(QPrintDialog);
- if (checked)
- q->printer()->setPageOrder(QPrinter::LastPageFirst);
- else
- q->printer()->setPageOrder(QPrinter::FirstPageFirst);
-}
-
-void QPrintDialogPrivate::_q_collapseOrExpandDialog()
-{
- int collapseHeight = 0;
- Q_Q(QPrintDialog);
- QWidget *widgetToHide = bottom;
- if (widgetToHide->isVisible()) {
- collapseButton->setText(QPrintDialog::tr("&Options >>"));
- collapseHeight = widgetToHide->y() + widgetToHide->height() - (top->y() + top->height());
- }
- else
- collapseButton->setText(QPrintDialog::tr("&Options <<"));
- widgetToHide->setVisible(! widgetToHide->isVisible());
- if (! widgetToHide->isVisible()) { // make it shrink
- q->layout()->activate();
- q->resize( QSize(q->width(), q->height() - collapseHeight) );
- }
-}
-
-#ifndef QT_NO_MESSAGEBOX
-void QPrintDialogPrivate::_q_checkFields()
-{
- Q_Q(QPrintDialog);
- if (top->d->checkFields())
- q->accept();
-}
-#endif // QT_NO_MESSAGEBOX
-
-void QPrintDialogPrivate::setupPrinter()
-{
- Q_Q(QPrintDialog);
- QPrinter* p = q->printer();
-
- if (options.duplex->isEnabled()) {
- if (options.noDuplex->isChecked())
- p->setDuplex(QPrinter::DuplexNone);
- else if (options.duplexLong->isChecked())
- p->setDuplex(QPrinter::DuplexLongSide);
- else
- p->setDuplex(QPrinter::DuplexShortSide);
- }
-
- p->setColorMode( options.color->isChecked() ? QPrinter::Color : QPrinter::GrayScale );
-
- // print range
- if (options.printAll->isChecked()) {
- p->setPrintRange(QPrinter::AllPages);
- p->setFromTo(0,0);
- } else if (options.printSelection->isChecked()) {
- p->setPrintRange(QPrinter::Selection);
- p->setFromTo(0,0);
- } else if (options.printCurrentPage->isChecked()) {
- p->setPrintRange(QPrinter::CurrentPage);
- p->setFromTo(0,0);
- } else if (options.printRange->isChecked()) {
- p->setPrintRange(QPrinter::PageRange);
- p->setFromTo(options.from->value(), qMax(options.from->value(), options.to->value()));
- }
-
- // copies
- p->setCopyCount(options.copies->value());
- p->setCollateCopies(options.collate->isChecked());
-
- top->d->setupPrinter();
-}
-
-void QPrintDialogPrivate::updateWidgets()
-{
- Q_Q(QPrintDialog);
- options.gbPrintRange->setVisible(q->isOptionEnabled(QPrintDialog::PrintPageRange) ||
- q->isOptionEnabled(QPrintDialog::PrintSelection) ||
- q->isOptionEnabled(QPrintDialog::PrintCurrentPage));
-
- options.printRange->setEnabled(q->isOptionEnabled(QPrintDialog::PrintPageRange));
- options.printSelection->setVisible(q->isOptionEnabled(QPrintDialog::PrintSelection));
- options.printCurrentPage->setVisible(q->isOptionEnabled(QPrintDialog::PrintCurrentPage));
- options.collate->setVisible(q->isOptionEnabled(QPrintDialog::PrintCollateCopies));
-
- switch (q->printRange()) {
- case QPrintDialog::AllPages:
- options.printAll->setChecked(true);
- break;
- case QPrintDialog::Selection:
- options.printSelection->setChecked(true);
- break;
- case QPrintDialog::PageRange:
- options.printRange->setChecked(true);
- break;
- case QPrintDialog::CurrentPage:
- if (q->isOptionEnabled(QPrintDialog::PrintCurrentPage))
- options.printCurrentPage->setChecked(true);
- break;
- default:
- break;
- }
- const int minPage = qMax(1, qMin(q->minPage() , q->maxPage()));
- const int maxPage = qMax(1, q->maxPage() == INT_MAX ? 9999 : q->maxPage());
-
- options.from->setMinimum(minPage);
- options.to->setMinimum(minPage);
- options.from->setMaximum(maxPage);
- options.to->setMaximum(maxPage);
-
- options.from->setValue(q->fromPage());
- options.to->setValue(q->toPage());
- top->d->updateWidget();
-}
-
-void QPrintDialogPrivate::setTabs(const QList<QWidget*> &tabWidgets)
-{
- while(options.tabs->count() > 2)
- delete options.tabs->widget(2);
-
- QList<QWidget*>::ConstIterator iter = tabWidgets.begin();
- while(iter != tabWidgets.constEnd()) {
- QWidget *tab = *iter;
- options.tabs->addTab(tab, tab->windowTitle());
- ++iter;
- }
-}
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-void QPrintDialogPrivate::selectPrinter(QCUPSSupport *cups)
-{
- options.duplex->setEnabled(cups && cups->ppdOption("Duplex"));
-}
-#endif
-
-////////////////////////////////////////////////////////////////////////////////
-
-QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
- : QAbstractPrintDialog(*(new QPrintDialogPrivate), printer, parent)
-{
- Q_D(QPrintDialog);
- d->init();
-}
-
-/*!
- Constructs a print dialog with the given \a parent.
-*/
-QPrintDialog::QPrintDialog(QWidget *parent)
- : QAbstractPrintDialog(*(new QPrintDialogPrivate), 0, parent)
-{
- Q_D(QPrintDialog);
- d->init();
-}
-
-QPrintDialog::~QPrintDialog()
-{
-}
-
-void QPrintDialog::setVisible(bool visible)
-{
- Q_D(QPrintDialog);
-
- if (visible)
- d->updateWidgets();
-
- QAbstractPrintDialog::setVisible(visible);
-}
-
-int QPrintDialog::exec()
-{
- return QDialog::exec();
-}
-
-void QPrintDialog::accept()
-{
- Q_D(QPrintDialog);
- d->setupPrinter();
- QDialog::accept();
-}
-
-#ifdef QT3_SUPPORT
-QPrinter *QPrintDialog::printer() const
-{
- Q_D(const QPrintDialog);
- return d->printer;
-}
-
-void QPrintDialog::setPrinter(QPrinter *printer, bool pickupSettings)
-{
- if (!printer)
- return;
-
- Q_D(QPrintDialog);
- d->printer = printer;
-
- if (pickupSettings)
- d->applyPrinterProperties(printer);
-}
-
-void QPrintDialog::addButton(QPushButton *button)
-{
- Q_D(QPrintDialog);
- d->buttons->addButton(button, QDialogButtonBox::HelpRole);
-}
-#endif // QT3_SUPPORT
-
-#if defined (Q_OS_UNIX)
-
-/*! \internal
-*/
-QUnixPrintWidgetPrivate::QUnixPrintWidgetPrivate(QUnixPrintWidget *p)
- : parent(p), propertiesDialog(0), printer(0), optionsPane(0), filePrintersAdded(false)
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- , cups(0), cupsPrinterCount(0), cupsPrinters(0), cupsPPD(0)
-#endif
-{
- q = 0;
- if (parent)
- q = qobject_cast<QAbstractPrintDialog*> (parent->parent());
-
- widget.setupUi(parent);
-
- int currentPrinterIndex = 0;
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- cups = new QCUPSSupport;
- if (QCUPSSupport::isAvailable()) {
- cupsPPD = cups->currentPPD();
- cupsPrinterCount = cups->availablePrintersCount();
- cupsPrinters = cups->availablePrinters();
-
- for (int i = 0; i < cupsPrinterCount; ++i) {
- QString printerName(QString::fromLocal8Bit(cupsPrinters[i].name));
- if (cupsPrinters[i].instance)
- printerName += QLatin1Char('/') + QString::fromLocal8Bit(cupsPrinters[i].instance);
-
- widget.printers->addItem(printerName);
- if (cupsPrinters[i].is_default)
- widget.printers->setCurrentIndex(i);
- }
- // the model depends on valid ppd. so before enabling the
- // properties button we make sure the ppd is in fact valid.
- if (cupsPrinterCount && cups->currentPPD()) {
- widget.properties->setEnabled(true);
- }
- currentPrinterIndex = cups->currentPrinterIndex();
- } else {
-#endif
- currentPrinterIndex = qt_getLprPrinters(lprPrinters);
- // populating printer combo
- QList<QPrinterDescription>::const_iterator i = lprPrinters.constBegin();
- for(; i != lprPrinters.constEnd(); ++i)
- widget.printers->addItem((*i).name);
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- }
-#endif
-
-#if !defined(QT_NO_FILESYSTEMMODEL) && !defined(QT_NO_COMPLETER)
- QFileSystemModel *fsm = new QFileSystemModel(widget.filename);
- fsm->setRootPath(QDir::homePath());
- widget.filename->setCompleter(new QCompleter(fsm, widget.filename));
-#endif
- _q_printerChanged(currentPrinterIndex);
-
- QObject::connect(widget.printers, SIGNAL(currentIndexChanged(int)),
- parent, SLOT(_q_printerChanged(int)));
- QObject::connect(widget.fileBrowser, SIGNAL(clicked()), parent, SLOT(_q_btnBrowseClicked()));
- QObject::connect(widget.properties, SIGNAL(clicked()), parent, SLOT(_q_btnPropertiesClicked()));
-
- // disable features that QPrinter does not yet support.
- widget.preview->setVisible(false);
-}
-
-void QUnixPrintWidgetPrivate::updateWidget()
-{
- const bool printToFile = q == 0 || q->isOptionEnabled(QPrintDialog::PrintToFile);
- if (printToFile && !filePrintersAdded) {
- if (widget.printers->count())
- widget.printers->insertSeparator(widget.printers->count());
- widget.printers->addItem(QPrintDialog::tr("Print to File (PDF)"));
- filePrintersAdded = true;
- }
- if (!printToFile && filePrintersAdded) {
- widget.printers->removeItem(widget.printers->count()-1);
- widget.printers->removeItem(widget.printers->count()-1);
- if (widget.printers->count())
- widget.printers->removeItem(widget.printers->count()-1); // remove separator
- filePrintersAdded = false;
- }
- if (printer && filePrintersAdded && (printer->outputFormat() != QPrinter::NativeFormat
- || printer->printerName().isEmpty()))
- {
- if (printer->outputFormat() == QPrinter::PdfFormat)
- widget.printers->setCurrentIndex(widget.printers->count() - 1);
- widget.filename->setEnabled(true);
- widget.lOutput->setEnabled(true);
- }
-
- widget.filename->setVisible(printToFile);
- widget.lOutput->setVisible(printToFile);
- widget.fileBrowser->setVisible(printToFile);
-
- widget.properties->setVisible(q->isOptionEnabled(QAbstractPrintDialog::PrintShowPageSize));
-}
-
-QUnixPrintWidgetPrivate::~QUnixPrintWidgetPrivate()
-{
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- delete cups;
-#endif
-}
-
-void QUnixPrintWidgetPrivate::_q_printerChanged(int index)
-{
- if (index < 0)
- return;
- const int printerCount = widget.printers->count();
- widget.filename->setEnabled(false);
- widget.lOutput->setEnabled(false);
-
- if (filePrintersAdded) {
- Q_ASSERT(index != printerCount - 3); // separator
- if (index == printerCount - 1) { // PDF
- widget.location->setText(QPrintDialog::tr("Local file"));
- widget.type->setText(QPrintDialog::tr("Write PDF file"));
- widget.properties->setEnabled(true);
- widget.filename->setEnabled(true);
- QString filename = widget.filename->text();
- QString suffix = QFileInfo(filename).suffix();
- widget.filename->setText(filename);
- widget.lOutput->setEnabled(true);
- if (propertiesDialog)
- propertiesDialog->selectPdfPsPrinter(printer);
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- if (optionsPane)
- optionsPane->selectPrinter(0);
-#endif
- return;
- }
- }
-
- widget.location->setText(QString());
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- if (QCUPSSupport::isAvailable()) {
- cups->setCurrentPrinter(index);
-
- const cups_option_t *opt = cups->printerOption(QString::fromLatin1("printer-location"));
- QString location;
- if (opt)
- location = QString::fromLocal8Bit(opt->value);
- widget.location->setText(location);
-
- cupsPPD = cups->currentPPD();
- // set printer type line
- QString type;
- if (cupsPPD)
- type = QString::fromLocal8Bit(cupsPPD->manufacturer) + QLatin1String(" - ") + QString::fromLocal8Bit(cupsPPD->modelname);
- widget.type->setText(type);
- if (propertiesDialog)
- propertiesDialog->selectPrinter();
- if (optionsPane)
- optionsPane->selectPrinter(cups);
- } else {
- if (optionsPane)
- optionsPane->selectPrinter(0);
-#endif
- if (lprPrinters.count() > 0) {
- QString type = lprPrinters.at(index).name + QLatin1Char('@') + lprPrinters.at(index).host;
- if (!lprPrinters.at(index).comment.isEmpty())
- type += QLatin1String(", ") + lprPrinters.at(index).comment;
- widget.type->setText(type);
- if (propertiesDialog)
- propertiesDialog->selectPrinter();
- }
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- }
-#endif
-}
-
-void QUnixPrintWidgetPrivate::setOptionsPane(QPrintDialogPrivate *pane)
-{
- optionsPane = pane;
- if (optionsPane)
- _q_printerChanged(widget.printers->currentIndex());
-}
-
-void QUnixPrintWidgetPrivate::_q_btnBrowseClicked()
-{
- QString filename = widget.filename->text();
-#ifndef QT_NO_FILEDIALOG
- filename = QFileDialog::getSaveFileName(parent, QPrintDialog::tr("Print To File ..."), filename,
- QString(), 0, QFileDialog::DontConfirmOverwrite);
-#else
- filename.clear();
-#endif
- if (!filename.isEmpty()) {
- widget.filename->setText(filename);
- widget.printers->setCurrentIndex(widget.printers->count() - 1); // the pdf one
- }
-}
-
-void QUnixPrintWidgetPrivate::applyPrinterProperties(QPrinter *p)
-{
- if (p == 0)
- return;
- printer = p;
- if (p->outputFileName().isEmpty()) {
- QString home = QString::fromLocal8Bit(qgetenv("HOME").constData());
- QString cur = QDir::currentPath();
- if (home.at(home.length()-1) != QLatin1Char('/'))
- home += QLatin1Char('/');
- if (cur.at(cur.length()-1) != QLatin1Char('/'))
- cur += QLatin1Char('/');
- if (cur.left(home.length()) != home)
- cur = home;
-#ifdef Q_WS_X11
- if (p->docName().isEmpty()) {
- cur += QLatin1String("print.pdf");
- } else {
- QRegExp re(QString::fromLatin1("(.*)\\.\\S+"));
- if (re.exactMatch(p->docName()))
- cur += re.cap(1);
- else
- cur += p->docName();
- cur += QLatin1String(".pdf");
- }
-#endif
- widget.filename->setText(cur);
- }
- else
- widget.filename->setText( p->outputFileName() );
- QString printer = p->printerName();
- if (!printer.isEmpty()) {
- for (int i = 0; i < widget.printers->count(); ++i) {
- if (widget.printers->itemText(i) == printer) {
- widget.printers->setCurrentIndex(i);
- break;
- }
- }
- }
- // PDF and PS printers are not added to the dialog yet, we'll handle those cases in QUnixPrintWidgetPrivate::updateWidget
-
- if (propertiesDialog)
- propertiesDialog->applyPrinterProperties(p);
-}
-
-#ifndef QT_NO_MESSAGEBOX
-bool QUnixPrintWidgetPrivate::checkFields()
-{
- if (widget.filename->isEnabled()) {
- QString file = widget.filename->text();
- QFile f(file);
- QFileInfo fi(f);
- bool exists = fi.exists();
- bool opened = false;
- if (exists && fi.isDir()) {
- QMessageBox::warning(q, q->windowTitle(),
- QPrintDialog::tr("%1 is a directory.\nPlease choose a different file name.").arg(file));
- return false;
- } else if ((exists && !fi.isWritable()) || !(opened = f.open(QFile::Append))) {
- QMessageBox::warning(q, q->windowTitle(),
- QPrintDialog::tr("File %1 is not writable.\nPlease choose a different file name.").arg(file));
- return false;
- } else if (exists) {
- int ret = QMessageBox::question(q, q->windowTitle(),
- QPrintDialog::tr("%1 already exists.\nDo you want to overwrite it?").arg(file),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
- if (ret == QMessageBox::No)
- return false;
- }
- if (opened) {
- f.close();
- if (!exists)
- f.remove();
- }
- }
-
- // Every test passed. Accept the dialog.
- return true;
-}
-#endif // QT_NO_MESSAGEBOX
-
-void QUnixPrintWidgetPrivate::_q_btnPropertiesClicked()
-{
- if (!propertiesDialog) {
- propertiesDialog = new QPrintPropertiesDialog(q);
- propertiesDialog->setResult(QDialog::Rejected);
- }
-
- if (propertiesDialog->result() == QDialog::Rejected) {
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- propertiesDialog->setCups(cups);
-#endif
- propertiesDialog->applyPrinterProperties(q->printer());
-
- if (q->isOptionEnabled(QPrintDialog::PrintToFile)
- && (widget.printers->currentIndex() == widget.printers->count() - 1)) // PDF
- propertiesDialog->selectPdfPsPrinter(q->printer());
- else
- propertiesDialog->selectPrinter();
- }
- propertiesDialog->exec();
-}
-
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-void QUnixPrintWidgetPrivate::setCupsProperties()
-{
- if (cups && QCUPSSupport::isAvailable() && cups->pageSizes()) {
- QPrintEngine *engine = printer->printEngine();
- const ppd_option_t* pageSizes = cups->pageSizes();
- QByteArray cupsPageSize;
- for (int i = 0; i < pageSizes->num_choices; ++i) {
- if (static_cast<int>(pageSizes->choices[i].marked) == 1)
- cupsPageSize = pageSizes->choices[i].choice;
- }
- engine->setProperty(PPK_CupsStringPageSize, QString::fromLatin1(cupsPageSize));
- engine->setProperty(PPK_CupsOptions, cups->options());
-
- QRect pageRect = cups->pageRect(cupsPageSize);
- engine->setProperty(PPK_CupsPageRect, pageRect);
-
- QRect paperRect = cups->paperRect(cupsPageSize);
- engine->setProperty(PPK_CupsPaperRect, paperRect);
-
- for (int ps = 0; ps < QPrinter::NPaperSize; ++ps) {
- QPdf::PaperSize size = QPdf::paperSize(QPrinter::PaperSize(ps));
- if (size.width == paperRect.width() && size.height == paperRect.height())
- printer->setPaperSize(static_cast<QPrinter::PaperSize>(ps));
- }
- }
-}
-#endif
-
-void QUnixPrintWidgetPrivate::setupPrinter()
-{
- const int printerCount = widget.printers->count();
- const int index = widget.printers->currentIndex();
-
- if (filePrintersAdded && index == printerCount - 1) { // PDF
- printer->setPrinterName(QString());
- Q_ASSERT(index != printerCount - 3); // separator
- printer->setOutputFormat(QPrinter::PdfFormat);
- QString path = widget.filename->text();
- if (QDir::isRelativePath(path))
- path = QDir::homePath() + QDir::separator() + path;
- printer->setOutputFileName(path);
- }
- else {
- printer->setPrinterName(widget.printers->currentText());
- printer->setOutputFileName(QString());
- }
-
- if (propertiesDialog && propertiesDialog->result() == QDialog::Accepted)
- propertiesDialog->setupPrinter();
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
- if (!propertiesDialog)
- setCupsProperties();
-#endif
-}
-
-
-/*! \internal
-*/
-QUnixPrintWidget::QUnixPrintWidget(QPrinter *printer, QWidget *parent)
- : QWidget(parent), d(new QUnixPrintWidgetPrivate(this))
-{
- d->applyPrinterProperties(printer);
-}
-
-/*! \internal
-*/
-QUnixPrintWidget::~QUnixPrintWidget()
-{
- delete d;
-}
-
-/*! \internal
-
- Updates the printer with the states held in the QUnixPrintWidget.
-*/
-void QUnixPrintWidget::updatePrinter()
-{
- d->setupPrinter();
-}
-
-#endif
-
-////////////////////////////////////////////////////////////////////////////////
-#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
-
-QPPDOptionsModel::QPPDOptionsModel(QCUPSSupport *c, QObject *parent)
- : QAbstractItemModel(parent), rootItem(0), cups(c), ppd(c->currentPPD())
-{
- parseItems();
-}
-
-QPPDOptionsModel::~QPPDOptionsModel()
-{
-}
-
-int QPPDOptionsModel::columnCount(const QModelIndex&) const
-{
- return 2;
-}
-
-int QPPDOptionsModel::rowCount(const QModelIndex& parent) const
-{
- QOptionTreeItem* itm;
- if (!parent.isValid())
- itm = rootItem;
- else
- itm = reinterpret_cast<QOptionTreeItem*>(parent.internalPointer());
-
- if (itm->type == QOptionTreeItem::Option)
- return 0;
-
- return itm->childItems.count();
-}
-
-QVariant QPPDOptionsModel::data(const QModelIndex& index, int role) const
-{
- switch(role) {
- case Qt::FontRole: {
- QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());
- if (itm && itm->type == QOptionTreeItem::Group){
- QFont font = QApplication::font();
- font.setBold(true);
- return QVariant(font);
- }
- return QVariant();
- }
- break;
-
- case Qt::DisplayRole: {
- QOptionTreeItem* itm;
- if (!index.isValid())
- itm = rootItem;
- else
- itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());
-
- if (index.column() == 0)
- return cups->unicodeString(itm->description);
- else if (itm->type == QOptionTreeItem::Option && itm->selected > -1)
- return cups->unicodeString(itm->selDescription);
- else
- return QVariant();
- }
- break;
-
- default:
- return QVariant();
- }
- if (role != Qt::DisplayRole)
- return QVariant();
-}
-
-QModelIndex QPPDOptionsModel::index(int row, int column, const QModelIndex& parent) const
-{
- QOptionTreeItem* itm;
- if (!parent.isValid())
- itm = rootItem;
- else
- itm = reinterpret_cast<QOptionTreeItem*>(parent.internalPointer());
-
- return createIndex(row, column, itm->childItems.at(row));
-}
-
-
-QModelIndex QPPDOptionsModel::parent(const QModelIndex& index) const
-{
- if (!index.isValid())
- return QModelIndex();
-
- QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());
-
- if (itm->parentItem && itm->parentItem != rootItem)
- return createIndex(itm->parentItem->index, 0, itm->parentItem);
- else
- return QModelIndex();
-}
-
-Qt::ItemFlags QPPDOptionsModel::flags(const QModelIndex& index) const
-{
- if (!index.isValid() || reinterpret_cast<QOptionTreeItem*>(index.internalPointer())->type == QOptionTreeItem::Group)
- return Qt::ItemIsEnabled;
-
- if (index.column() == 1)
- return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
-
- return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
-}
-
-void QPPDOptionsModel::parseItems()
-{
- emit layoutAboutToBeChanged();
- ppd = cups->currentPPD();
- delete rootItem;
- rootItem = new QOptionTreeItem(QOptionTreeItem::Root, 0, ppd, "Root Item", 0);
- parseGroups(rootItem);
- emit layoutChanged();
-}
-
-void QPPDOptionsModel::parseGroups(QOptionTreeItem* parent)
-{
- if (parent->type == QOptionTreeItem::Root) {
-
- const ppd_file_t* ppdFile = reinterpret_cast<const ppd_file_t*>(parent->ptr);
-
- if (ppdFile) {
- for (int i = 0; i < ppdFile->num_groups; ++i) {
- QOptionTreeItem* group = new QOptionTreeItem(QOptionTreeItem::Group, i, &ppdFile->groups[i], ppdFile->groups[i].text, parent);
- parent->childItems.append(group);
- parseGroups(group); // parse possible subgroups
- parseOptions(group); // parse options
- }
- }
- } else if (parent->type == QOptionTreeItem::Group) {
-
- const ppd_group_t* group = reinterpret_cast<const ppd_group_t*>(parent->ptr);
-
- if (group) {
- for (int i = 0; i < group->num_subgroups; ++i) {
- QOptionTreeItem* subgroup = new QOptionTreeItem(QOptionTreeItem::Group, i, &group->subgroups[i], group->subgroups[i].text, parent);
- parent->childItems.append(subgroup);
- parseGroups(subgroup); // parse possible subgroups
- parseOptions(subgroup); // parse options
- }
- }
- }
-}
-
-void QPPDOptionsModel::parseOptions(QOptionTreeItem* parent)
-{
- const ppd_group_t* group = reinterpret_cast<const ppd_group_t*>(parent->ptr);
- for (int i = 0; i < group->num_options; ++i) {
- QOptionTreeItem* opt = new QOptionTreeItem(QOptionTreeItem::Option, i, &group->options[i], group->options[i].text, parent);
- parent->childItems.append(opt);
- parseChoices(opt);
- }
-}
-
-void QPPDOptionsModel::parseChoices(QOptionTreeItem* parent)
-{
- const ppd_option_t* option = reinterpret_cast<const ppd_option_t*>(parent->ptr);
- bool marked = false;
- for (int i = 0; i < option->num_choices; ++i) {
- QOptionTreeItem* choice = new QOptionTreeItem(QOptionTreeItem::Choice, i, &option->choices[i], option->choices[i].text, parent);
- if (static_cast<int>(option->choices[i].marked) == 1) {
- parent->selected = i;
- parent->selDescription = option->choices[i].text;
- marked = true;
- } else if (!marked && qstrcmp(option->choices[i].choice, option->defchoice) == 0) {
- parent->selected = i;
- parent->selDescription = option->choices[i].text;
- }
- parent->childItems.append(choice);
- }
-}
-
-QVariant QPPDOptionsModel::headerData(int section, Qt::Orientation, int role) const
-{
- if (role != Qt::DisplayRole)
- return QVariant();
-
- switch(section){
- case 0:
- return QVariant(QApplication::translate("QPPDOptionsModel", "Name"));
- case 1:
- return QVariant(QApplication::translate("QPPDOptionsModel", "Value"));
- default:
- return QVariant();
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-QWidget* QPPDOptionsEditor::createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex& index) const
-{
- if (index.column() == 1 && reinterpret_cast<QOptionTreeItem*>(index.internalPointer())->type == QOptionTreeItem::Option)
- return new QComboBox(parent);
- else
- return 0;
-}
-
-void QPPDOptionsEditor::setEditorData(QWidget* editor, const QModelIndex& index) const
-{
- if (index.column() != 1)
- return;
-
- QComboBox* cb = static_cast<QComboBox*>(editor);
- QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());
-
- if (itm->selected == -1)
- cb->addItem(QString());
-
- for (int i = 0; i < itm->childItems.count(); ++i)
- cb->addItem(QString::fromLocal8Bit(itm->childItems.at(i)->description));
-
- if (itm->selected > -1)
- cb->setCurrentIndex(itm->selected);
-
- connect(cb, SIGNAL(currentIndexChanged(int)), this, SLOT(cbChanged(int)));
-}
-
-void QPPDOptionsEditor::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
-{
- QComboBox* cb = static_cast<QComboBox*>(editor);
- QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());
-
- if (itm->selected == cb->currentIndex())
- return;
-
- const ppd_option_t* opt = reinterpret_cast<const ppd_option_t*>(itm->ptr);
- QPPDOptionsModel* m = static_cast<QPPDOptionsModel*>(model);
-
- if (m->cups->markOption(opt->keyword, opt->choices[cb->currentIndex()].choice) == 0) {
- itm->selected = cb->currentIndex();
- itm->selDescription = reinterpret_cast<const ppd_option_t*>(itm->ptr)->choices[itm->selected].text;
- }
-}
-
-void QPPDOptionsEditor::cbChanged(int)
-{
-/*
- emit commitData(static_cast<QWidget*>(sender()));
-*/
-}
-
-#endif
-
-QT_END_NAMESPACE
-
-#include "moc_qprintdialog.cpp"
-#include "qprintdialog_unix.moc"
-#include "qrc_qprintdialog.cpp"
-
-#endif // QT_NO_PRINTDIALOG
-
diff --git a/src/gui/dialogs/qprintdialog_win.cpp b/src/gui/dialogs/qprintdialog_win.cpp
deleted file mode 100644
index 4f6866b2df..0000000000
--- a/src/gui/dialogs/qprintdialog_win.cpp
+++ /dev/null
@@ -1,316 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_PRINTDIALOG
-
-#include "qprintdialog.h"
-
-#include <qwidget.h>
-#include <qapplication.h>
-#include <qmessagebox.h>
-#include <private/qapplication_p.h>
-
-#include <private/qabstractprintdialog_p.h>
-#include <private/qprintengine_win_p.h>
-#include <private/qprinter_p.h>
-
-#if !defined(PD_NOCURRENTPAGE)
-#define PD_NOCURRENTPAGE 0x00800000
-#define PD_RESULT_PRINT 1
-#define PD_RESULT_APPLY 2
-#define START_PAGE_GENERAL 0XFFFFFFFF
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern void qt_win_eatMouseMove();
-
-class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
-{
- Q_DECLARE_PUBLIC(QPrintDialog)
-public:
- QPrintDialogPrivate()
- : ep(0)
- {
- }
-
- inline void _q_printToFileChanged(int) {}
- inline void _q_rbPrintRangeToggled(bool) {}
- inline void _q_printerChanged(int) {}
- inline void _q_chbPrintLastFirstToggled(bool) {}
- inline void _q_paperSizeChanged(int) {}
- inline void _q_btnBrowseClicked() {}
- inline void _q_btnPropertiesClicked() {}
- int openWindowsPrintDialogModally();
-
- QWin32PrintEnginePrivate *ep;
-};
-
-static void qt_win_setup_PRINTDLGEX(PRINTDLGEX *pd, QWidget *parent,
- QPrintDialog *pdlg,
- QPrintDialogPrivate *d, HGLOBAL *tempDevNames)
-{
- DEVMODE *devMode = d->ep->devMode;
-
- if (devMode) {
- int size = sizeof(DEVMODE) + devMode->dmDriverExtra;
- pd->hDevMode = GlobalAlloc(GHND, size);
- {
- void *dest = GlobalLock(pd->hDevMode);
- memcpy(dest, devMode, size);
- GlobalUnlock(pd->hDevMode);
- }
- } else {
- pd->hDevMode = NULL;
- }
- pd->hDevNames = tempDevNames;
-
- pd->Flags = PD_RETURNDC;
- pd->Flags |= PD_USEDEVMODECOPIESANDCOLLATE;
-
- if (!pdlg->isOptionEnabled(QPrintDialog::PrintSelection))
- pd->Flags |= PD_NOSELECTION;
- if (pdlg->isOptionEnabled(QPrintDialog::PrintPageRange)) {
- pd->nMinPage = pdlg->minPage();
- pd->nMaxPage = pdlg->maxPage();
- }
-
- if(!pdlg->isOptionEnabled(QPrintDialog::PrintToFile))
- pd->Flags |= PD_DISABLEPRINTTOFILE;
-
- if (pdlg->printRange() == QPrintDialog::Selection)
- pd->Flags |= PD_SELECTION;
- else if (pdlg->printRange() == QPrintDialog::PageRange)
- pd->Flags |= PD_PAGENUMS;
- else
- pd->Flags |= PD_ALLPAGES;
-
- // As stated by MSDN, to enable collate option when minpage==maxpage==0
- // set the PD_NOPAGENUMS flag
- if (pd->nMinPage==0 && pd->nMaxPage==0)
- pd->Flags |= PD_NOPAGENUMS;
-
- // Disable Current Page option if not required as default is Enabled
- if (!pdlg->isOptionEnabled(QPrintDialog::PrintCurrentPage))
- pd->Flags |= PD_NOCURRENTPAGE;
-
- // Default to showing the General tab first
- pd->nStartPage = START_PAGE_GENERAL;
-
- // We don't support more than one page range in the QPrinter API yet.
- pd->nPageRanges = 1;
- pd->nMaxPageRanges = 1;
-
- if (d->ep->printToFile)
- pd->Flags |= PD_PRINTTOFILE;
- Q_ASSERT(parent);
- pd->hwndOwner = parent->window()->winId();
- pd->lpPageRanges[0].nFromPage = qMax(pdlg->fromPage(), pdlg->minPage());
- pd->lpPageRanges[0].nToPage = (pdlg->toPage() > 0) ? qMin(pdlg->toPage(), pdlg->maxPage()) : 1;
- pd->nCopies = d->ep->num_copies;
-}
-
-static void qt_win_read_back_PRINTDLGEX(PRINTDLGEX *pd, QPrintDialog *pdlg, QPrintDialogPrivate *d)
-{
- if (pd->Flags & PD_SELECTION) {
- pdlg->setPrintRange(QPrintDialog::Selection);
- pdlg->setFromTo(0, 0);
- } else if (pd->Flags & PD_PAGENUMS) {
- pdlg->setPrintRange(QPrintDialog::PageRange);
- pdlg->setFromTo(pd->lpPageRanges[0].nFromPage, pd->lpPageRanges[0].nToPage);
- } else if (pd->Flags & PD_CURRENTPAGE) {
- pdlg->setPrintRange(QPrintDialog::CurrentPage);
- pdlg->setFromTo(0, 0);
- } else { // PD_ALLPAGES
- pdlg->setPrintRange(QPrintDialog::AllPages);
- pdlg->setFromTo(0, 0);
- }
-
- d->ep->printToFile = (pd->Flags & PD_PRINTTOFILE) != 0;
-
- d->ep->readDevnames(pd->hDevNames);
- d->ep->readDevmode(pd->hDevMode);
- d->ep->updateCustomPaperSize();
-
- if (d->ep->printToFile && d->ep->fileName.isEmpty())
- d->ep->fileName = d->ep->port;
- else if (!d->ep->printToFile && d->ep->fileName == QLatin1String("FILE:"))
- d->ep->fileName.clear();
-}
-
-static bool warnIfNotNative(QPrinter *printer)
-{
- if (printer->outputFormat() != QPrinter::NativeFormat) {
- qWarning("QPrintDialog: Cannot be used on non-native printers");
- return false;
- }
- return true;
-}
-
-QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
- : QAbstractPrintDialog( *(new QPrintDialogPrivate), printer, parent)
-{
- Q_D(QPrintDialog);
- if (!warnIfNotNative(d->printer))
- return;
- d->ep = static_cast<QWin32PrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::QPrintDialog(QWidget *parent)
- : QAbstractPrintDialog( *(new QPrintDialogPrivate), 0, parent)
-{
- Q_D(QPrintDialog);
- if (!warnIfNotNative(d->printer))
- return;
- d->ep = static_cast<QWin32PrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::~QPrintDialog()
-{
-}
-
-int QPrintDialog::exec()
-{
- if (!warnIfNotNative(printer()))
- return 0;
-
- Q_D(QPrintDialog);
- return d->openWindowsPrintDialogModally();
-}
-
-int QPrintDialogPrivate::openWindowsPrintDialogModally()
-{
- Q_Q(QPrintDialog);
- QWidget *parent = q->parentWidget();
- if (parent)
- parent = parent->window();
- else
- parent = QApplication::activeWindow();
-
- // If there is no window, fall back to the print dialog itself
- if (parent == 0)
- parent = q;
-
- QWidget modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- HGLOBAL *tempDevNames = ep->createDevNames();
-
- bool done;
- bool result;
- bool doPrinting;
-
- PRINTPAGERANGE pageRange;
- PRINTDLGEX pd;
- memset(&pd, 0, sizeof(PRINTDLGEX));
- pd.lStructSize = sizeof(PRINTDLGEX);
- pd.lpPageRanges = &pageRange;
- qt_win_setup_PRINTDLGEX(&pd, parent, q, this, tempDevNames);
-
- do {
- done = true;
- doPrinting = false;
- result = (PrintDlgEx(&pd) == S_OK);
- if (result && (pd.dwResultAction == PD_RESULT_PRINT
- || pd.dwResultAction == PD_RESULT_APPLY))
- {
- doPrinting = (pd.dwResultAction == PD_RESULT_PRINT);
- if ((pd.Flags & PD_PAGENUMS)
- && (pd.lpPageRanges[0].nFromPage > pd.lpPageRanges[0].nToPage))
- {
- pd.lpPageRanges[0].nFromPage = 1;
- pd.lpPageRanges[0].nToPage = 1;
- done = false;
- }
- if (pd.hDC == 0)
- result = false;
- }
-
- if (!done) {
- QMessageBox::warning(0, QPrintDialog::tr("Print"),
- QPrintDialog::tr("The 'From' value cannot be greater than the 'To' value."),
- QPrintDialog::tr("OK"));
- }
- } while (!done);
-
- QApplicationPrivate::leaveModal(&modal_widget);
-
- qt_win_eatMouseMove();
-
- // write values back...
- if (result && (pd.dwResultAction == PD_RESULT_PRINT
- || pd.dwResultAction == PD_RESULT_APPLY))
- {
- qt_win_read_back_PRINTDLGEX(&pd, q, this);
- // update printer validity
- printer->d_func()->validPrinter = !ep->name.isEmpty();
- }
-
- // Cleanup...
- GlobalFree(tempDevNames);
-
- q->done(result && doPrinting);
-
- return result && doPrinting;
-}
-
-void QPrintDialog::setVisible(bool visible)
-{
- Q_D(QPrintDialog);
-
- // its always modal, so we cannot hide a native print dialog
- if (!visible)
- return;
-
- if (!warnIfNotNative(d->printer))
- return;
-
- (void)d->openWindowsPrintDialogModally();
- return;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qprintdialog.cpp"
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qprintpreviewdialog.cpp b/src/gui/dialogs/qprintpreviewdialog.cpp
deleted file mode 100644
index 950500d739..0000000000
--- a/src/gui/dialogs/qprintpreviewdialog.cpp
+++ /dev/null
@@ -1,803 +0,0 @@
-/****************************************************************************
-**
-** 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 "qprintpreviewdialog.h"
-#include "qprintpreviewwidget.h"
-#include <private/qprinter_p.h>
-#include "private/qdialog_p.h"
-#include "qprintdialog.h"
-
-#include <QtGui/qaction.h>
-#include <QtGui/qboxlayout.h>
-#include <QtGui/qcombobox.h>
-#include <QtGui/qlabel.h>
-#include <QtGui/qlineedit.h>
-#include <QtGui/qpagesetupdialog.h>
-#include <QtGui/qprinter.h>
-#include <QtGui/qstyle.h>
-#include <QtGui/qtoolbutton.h>
-#include <QtGui/qvalidator.h>
-#include <QtGui/qfiledialog.h>
-#include <QtGui/qmainwindow.h>
-#include <QtGui/qtoolbar.h>
-#include <QtGui/qformlayout.h>
-#include <QtCore/QCoreApplication>
-
-#include <math.h>
-
-#ifndef QT_NO_PRINTPREVIEWDIALOG
-
-QT_BEGIN_NAMESPACE
-
-namespace {
-class QPrintPreviewMainWindow : public QMainWindow
-{
-public:
- QPrintPreviewMainWindow(QWidget *parent) : QMainWindow(parent) {}
- QMenu *createPopupMenu() { return 0; }
-};
-
-class ZoomFactorValidator : public QDoubleValidator
-{
-public:
- ZoomFactorValidator(QObject* parent)
- : QDoubleValidator(parent) {}
- ZoomFactorValidator(qreal bottom, qreal top, int decimals, QObject *parent)
- : QDoubleValidator(bottom, top, decimals, parent) {}
-
- State validate(QString &input, int &pos) const
- {
- bool replacePercent = false;
- if (input.endsWith(QLatin1Char('%'))) {
- input = input.left(input.length() - 1);
- replacePercent = true;
- }
- State state = QDoubleValidator::validate(input, pos);
- if (replacePercent)
- input += QLatin1Char('%');
- const int num_size = 4;
- if (state == Intermediate) {
- int i = input.indexOf(QLocale::system().decimalPoint());
- if ((i == -1 && input.size() > num_size)
- || (i != -1 && i > num_size))
- return Invalid;
- }
- return state;
- }
-};
-
-class LineEdit : public QLineEdit
-{
- Q_OBJECT
-public:
- LineEdit(QWidget* parent = 0)
- : QLineEdit(parent)
- {
- setContextMenuPolicy(Qt::NoContextMenu);
- connect(this, SIGNAL(returnPressed()), SLOT(handleReturnPressed()));
- }
-
-protected:
- void focusInEvent(QFocusEvent *e)
- {
- origText = text();
- QLineEdit::focusInEvent(e);
- }
-
- void focusOutEvent(QFocusEvent *e)
- {
- if (isModified() && !hasAcceptableInput())
- setText(origText);
- QLineEdit::focusOutEvent(e);
- }
-
-private slots:
- void handleReturnPressed()
- {
- origText = text();
- }
-
-private:
- QString origText;
-};
-} // anonymous namespace
-
-class QPrintPreviewDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QPrintPreviewDialog)
-public:
- QPrintPreviewDialogPrivate()
- : printDialog(0), ownPrinter(false),
- initialized(false) {}
-
- // private slots
- void _q_fit(QAction *action);
- void _q_zoomIn();
- void _q_zoomOut();
- void _q_navigate(QAction *action);
- void _q_setMode(QAction *action);
- void _q_pageNumEdited();
- void _q_print();
- void _q_pageSetup();
- void _q_previewChanged();
- void _q_zoomFactorChanged();
-
- void init(QPrinter *printer = 0);
- void populateScene();
- void layoutPages();
- void setupActions();
- void updateNavActions();
- void setFitting(bool on);
- bool isFitting();
- void updatePageNumLabel();
- void updateZoomFactor();
-
- QPrintDialog *printDialog;
- QPrintPreviewWidget *preview;
- QPrinter *printer;
- bool ownPrinter;
- bool initialized;
-
- // widgets:
- QLineEdit *pageNumEdit;
- QLabel *pageNumLabel;
- QComboBox *zoomFactor;
-
- // actions:
- QActionGroup* navGroup;
- QAction *nextPageAction;
- QAction *prevPageAction;
- QAction *firstPageAction;
- QAction *lastPageAction;
-
- QActionGroup* fitGroup;
- QAction *fitWidthAction;
- QAction *fitPageAction;
-
- QActionGroup* zoomGroup;
- QAction *zoomInAction;
- QAction *zoomOutAction;
-
- QActionGroup* orientationGroup;
- QAction *portraitAction;
- QAction *landscapeAction;
-
- QActionGroup* modeGroup;
- QAction *singleModeAction;
- QAction *facingModeAction;
- QAction *overviewModeAction;
-
- QActionGroup *printerGroup;
- QAction *printAction;
- QAction *pageSetupAction;
-#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
- QAction *closeAction;
-#endif
-
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-};
-
-void QPrintPreviewDialogPrivate::init(QPrinter *_printer)
-{
- Q_Q(QPrintPreviewDialog);
-
- if (_printer) {
- preview = new QPrintPreviewWidget(_printer, q);
- printer = _printer;
- } else {
- ownPrinter = true;
- printer = new QPrinter;
- preview = new QPrintPreviewWidget(printer, q);
- }
- QObject::connect(preview, SIGNAL(paintRequested(QPrinter*)), q, SIGNAL(paintRequested(QPrinter*)));
- QObject::connect(preview, SIGNAL(previewChanged()), q, SLOT(_q_previewChanged()));
- setupActions();
-
- pageNumEdit = new LineEdit;
- pageNumEdit->setAlignment(Qt::AlignRight);
- pageNumEdit->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
- pageNumLabel = new QLabel;
- QObject::connect(pageNumEdit, SIGNAL(editingFinished()), q, SLOT(_q_pageNumEdited()));
-
- zoomFactor = new QComboBox;
- zoomFactor->setEditable(true);
- zoomFactor->setMinimumContentsLength(7);
- zoomFactor->setInsertPolicy(QComboBox::NoInsert);
- LineEdit *zoomEditor = new LineEdit;
- zoomEditor->setValidator(new ZoomFactorValidator(1, 1000, 1, zoomEditor));
- zoomFactor->setLineEdit(zoomEditor);
- static const short factorsX2[] = { 25, 50, 100, 200, 250, 300, 400, 800, 1600 };
- for (int i = 0; i < int(sizeof(factorsX2) / sizeof(factorsX2[0])); ++i)
- zoomFactor->addItem(QPrintPreviewDialog::tr("%1%").arg(factorsX2[i] / 2.0));
- QObject::connect(zoomFactor->lineEdit(), SIGNAL(editingFinished()),
- q, SLOT(_q_zoomFactorChanged()));
- QObject::connect(zoomFactor, SIGNAL(currentIndexChanged(int)),
- q, SLOT(_q_zoomFactorChanged()));
-
- QPrintPreviewMainWindow *mw = new QPrintPreviewMainWindow(q);
- QToolBar *toolbar = new QToolBar(mw);
- toolbar->addAction(fitWidthAction);
- toolbar->addAction(fitPageAction);
- toolbar->addSeparator();
- toolbar->addWidget(zoomFactor);
- toolbar->addAction(zoomOutAction);
- toolbar->addAction(zoomInAction);
- toolbar->addSeparator();
- toolbar->addAction(portraitAction);
- toolbar->addAction(landscapeAction);
- toolbar->addSeparator();
- toolbar->addAction(firstPageAction);
- toolbar->addAction(prevPageAction);
-
- // this is to ensure the label text and the editor text are
- // aligned in all styles - the extra QVBoxLayout is a workaround
- // for bug in QFormLayout
- QWidget *pageEdit = new QWidget(toolbar);
- QVBoxLayout *vboxLayout = new QVBoxLayout;
- vboxLayout->setContentsMargins(0, 0, 0, 0);
-#ifdef Q_WS_MAC
- // We query the widgets about their size and then we fix the size.
- // This should do the trick for the laying out part...
- QSize pageNumEditSize, pageNumLabelSize;
- pageNumEditSize = pageNumEdit->minimumSizeHint();
- pageNumLabelSize = pageNumLabel->minimumSizeHint();
- pageNumEdit->resize(pageNumEditSize);
- pageNumLabel->resize(pageNumLabelSize);
-#endif
- QFormLayout *formLayout = new QFormLayout;
-#ifdef Q_WS_MAC
- // We have to change the growth policy in Mac.
- formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
-#endif
- formLayout->setWidget(0, QFormLayout::LabelRole, pageNumEdit);
- formLayout->setWidget(0, QFormLayout::FieldRole, pageNumLabel);
- vboxLayout->addLayout(formLayout);
- vboxLayout->setAlignment(Qt::AlignVCenter);
- pageEdit->setLayout(vboxLayout);
- toolbar->addWidget(pageEdit);
-
- toolbar->addAction(nextPageAction);
- toolbar->addAction(lastPageAction);
- toolbar->addSeparator();
- toolbar->addAction(singleModeAction);
- toolbar->addAction(facingModeAction);
- toolbar->addAction(overviewModeAction);
- toolbar->addSeparator();
- toolbar->addAction(pageSetupAction);
- toolbar->addAction(printAction);
-#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
- toolbar->addAction(closeAction);
-#endif
-
- // Cannot use the actions' triggered signal here, since it doesn't autorepeat
- QToolButton *zoomInButton = static_cast<QToolButton *>(toolbar->widgetForAction(zoomInAction));
- QToolButton *zoomOutButton = static_cast<QToolButton *>(toolbar->widgetForAction(zoomOutAction));
- zoomInButton->setAutoRepeat(true);
- zoomInButton->setAutoRepeatInterval(200);
- zoomInButton->setAutoRepeatDelay(200);
- zoomOutButton->setAutoRepeat(true);
- zoomOutButton->setAutoRepeatInterval(200);
- zoomOutButton->setAutoRepeatDelay(200);
- QObject::connect(zoomInButton, SIGNAL(clicked()), q, SLOT(_q_zoomIn()));
- QObject::connect(zoomOutButton, SIGNAL(clicked()), q, SLOT(_q_zoomOut()));
-
- mw->addToolBar(toolbar);
- mw->setCentralWidget(preview);
- // QMainWindows are always created as top levels, force it to be a
- // plain widget
- mw->setParent(q, Qt::Widget);
-
- QVBoxLayout *topLayout = new QVBoxLayout;
- topLayout->addWidget(mw);
- topLayout->setMargin(0);
- q->setLayout(topLayout);
-
- QString caption = QCoreApplication::translate("QPrintPreviewDialog", "Print Preview");
- if (!printer->docName().isEmpty())
- caption += QString::fromLatin1(": ") + printer->docName();
- q->setWindowTitle(caption);
-
- if (!printer->isValid()
-#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
- || printer->outputFormat() != QPrinter::NativeFormat
-#endif
- )
- pageSetupAction->setEnabled(false);
- preview->setFocus();
-}
-
-static inline void qt_setupActionIcon(QAction *action, const QLatin1String &name)
-{
- QLatin1String imagePrefix(":/trolltech/dialogs/qprintpreviewdialog/images/");
- QIcon icon;
- icon.addFile(imagePrefix + name + QLatin1String("-24.png"), QSize(24, 24));
- icon.addFile(imagePrefix + name + QLatin1String("-32.png"), QSize(32, 32));
- action->setIcon(icon);
-}
-
-void QPrintPreviewDialogPrivate::setupActions()
-{
- Q_Q(QPrintPreviewDialog);
-
- // Navigation
- navGroup = new QActionGroup(q);
- navGroup->setExclusive(false);
- nextPageAction = navGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Next page"));
- prevPageAction = navGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Previous page"));
- firstPageAction = navGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "First page"));
- lastPageAction = navGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Last page"));
- qt_setupActionIcon(nextPageAction, QLatin1String("go-next"));
- qt_setupActionIcon(prevPageAction, QLatin1String("go-previous"));
- qt_setupActionIcon(firstPageAction, QLatin1String("go-first"));
- qt_setupActionIcon(lastPageAction, QLatin1String("go-last"));
- QObject::connect(navGroup, SIGNAL(triggered(QAction*)), q, SLOT(_q_navigate(QAction*)));
-
-
- fitGroup = new QActionGroup(q);
- fitWidthAction = fitGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Fit width"));
- fitPageAction = fitGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Fit page"));
- fitWidthAction->setObjectName(QLatin1String("fitWidthAction"));
- fitPageAction->setObjectName(QLatin1String("fitPageAction"));
- fitWidthAction->setCheckable(true);
- fitPageAction->setCheckable(true);
- qt_setupActionIcon(fitWidthAction, QLatin1String("fit-width"));
- qt_setupActionIcon(fitPageAction, QLatin1String("fit-page"));
- QObject::connect(fitGroup, SIGNAL(triggered(QAction*)), q, SLOT(_q_fit(QAction*)));
-
- // Zoom
- zoomGroup = new QActionGroup(q);
- zoomInAction = zoomGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Zoom in"));
- zoomOutAction = zoomGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Zoom out"));
- qt_setupActionIcon(zoomInAction, QLatin1String("zoom-in"));
- qt_setupActionIcon(zoomOutAction, QLatin1String("zoom-out"));
-
- // Portrait/Landscape
- orientationGroup = new QActionGroup(q);
- portraitAction = orientationGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Portrait"));
- landscapeAction = orientationGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Landscape"));
- portraitAction->setCheckable(true);
- landscapeAction->setCheckable(true);
- qt_setupActionIcon(portraitAction, QLatin1String("layout-portrait"));
- qt_setupActionIcon(landscapeAction, QLatin1String("layout-landscape"));
- QObject::connect(portraitAction, SIGNAL(triggered(bool)), preview, SLOT(setPortraitOrientation()));
- QObject::connect(landscapeAction, SIGNAL(triggered(bool)), preview, SLOT(setLandscapeOrientation()));
-
- // Display mode
- modeGroup = new QActionGroup(q);
- singleModeAction = modeGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Show single page"));
- facingModeAction = modeGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Show facing pages"));
- overviewModeAction = modeGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Show overview of all pages"));
- qt_setupActionIcon(singleModeAction, QLatin1String("view-page-one"));
- qt_setupActionIcon(facingModeAction, QLatin1String("view-page-sided"));
- qt_setupActionIcon(overviewModeAction, QLatin1String("view-page-multi"));
- singleModeAction->setObjectName(QLatin1String("singleModeAction"));
- facingModeAction->setObjectName(QLatin1String("facingModeAction"));
- overviewModeAction->setObjectName(QLatin1String("overviewModeAction"));
-
- singleModeAction->setCheckable(true);
- facingModeAction->setCheckable(true);
- overviewModeAction->setCheckable(true);
- QObject::connect(modeGroup, SIGNAL(triggered(QAction*)), q, SLOT(_q_setMode(QAction*)));
-
- // Print
- printerGroup = new QActionGroup(q);
- printAction = printerGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Print"));
- pageSetupAction = printerGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Page setup"));
- qt_setupActionIcon(printAction, QLatin1String("print"));
- qt_setupActionIcon(pageSetupAction, QLatin1String("page-setup"));
- QObject::connect(printAction, SIGNAL(triggered(bool)), q, SLOT(_q_print()));
- QObject::connect(pageSetupAction, SIGNAL(triggered(bool)), q, SLOT(_q_pageSetup()));
-#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
- closeAction = printerGroup->addAction(QCoreApplication::translate("QPrintPreviewDialog", "Close"));
- QObject::connect(closeAction, SIGNAL(triggered(bool)), q, SLOT(reject()));
-#endif
-
- // Initial state:
- fitPageAction->setChecked(true);
- singleModeAction->setChecked(true);
- if (preview->orientation() == QPrinter::Portrait)
- portraitAction->setChecked(true);
- else
- landscapeAction->setChecked(true);
-}
-
-
-bool QPrintPreviewDialogPrivate::isFitting()
-{
- return (fitGroup->isExclusive()
- && (fitWidthAction->isChecked() || fitPageAction->isChecked()));
-}
-
-
-void QPrintPreviewDialogPrivate::setFitting(bool on)
-{
- if (isFitting() == on)
- return;
- fitGroup->setExclusive(on);
- if (on) {
- QAction* action = fitWidthAction->isChecked() ? fitWidthAction : fitPageAction;
- action->setChecked(true);
- if (fitGroup->checkedAction() != action) {
- // work around exclusitivity problem
- fitGroup->removeAction(action);
- fitGroup->addAction(action);
- }
- } else {
- fitWidthAction->setChecked(false);
- fitPageAction->setChecked(false);
- }
-}
-
-void QPrintPreviewDialogPrivate::updateNavActions()
-{
- int curPage = preview->currentPage();
- int numPages = preview->pageCount();
- nextPageAction->setEnabled(curPage < numPages);
- prevPageAction->setEnabled(curPage > 1);
- firstPageAction->setEnabled(curPage > 1);
- lastPageAction->setEnabled(curPage < numPages);
- pageNumEdit->setText(QString::number(curPage));
-}
-
-void QPrintPreviewDialogPrivate::updatePageNumLabel()
-{
- Q_Q(QPrintPreviewDialog);
-
- int numPages = preview->pageCount();
- int maxChars = QString::number(numPages).length();
- pageNumLabel->setText(QString::fromLatin1("/ %1").arg(numPages));
- int cyphersWidth = q->fontMetrics().width(QString().fill(QLatin1Char('8'), maxChars));
- int maxWidth = pageNumEdit->minimumSizeHint().width() + cyphersWidth;
- pageNumEdit->setMinimumWidth(maxWidth);
- pageNumEdit->setMaximumWidth(maxWidth);
- pageNumEdit->setValidator(new QIntValidator(1, numPages, pageNumEdit));
- // any old one will be deleted later along with its parent pageNumEdit
-}
-
-void QPrintPreviewDialogPrivate::updateZoomFactor()
-{
- zoomFactor->lineEdit()->setText(QString().sprintf("%.1f%%", preview->zoomFactor()*100));
-}
-
-void QPrintPreviewDialogPrivate::_q_fit(QAction* action)
-{
- setFitting(true);
- if (action == fitPageAction)
- preview->fitInView();
- else
- preview->fitToWidth();
-}
-
-void QPrintPreviewDialogPrivate::_q_zoomIn()
-{
- setFitting(false);
- preview->zoomIn();
- updateZoomFactor();
-}
-
-void QPrintPreviewDialogPrivate::_q_zoomOut()
-{
- setFitting(false);
- preview->zoomOut();
- updateZoomFactor();
-}
-
-void QPrintPreviewDialogPrivate::_q_pageNumEdited()
-{
- bool ok = false;
- int res = pageNumEdit->text().toInt(&ok);
- if (ok)
- preview->setCurrentPage(res);
-}
-
-void QPrintPreviewDialogPrivate::_q_navigate(QAction* action)
-{
- int curPage = preview->currentPage();
- if (action == prevPageAction)
- preview->setCurrentPage(curPage - 1);
- else if (action == nextPageAction)
- preview->setCurrentPage(curPage + 1);
- else if (action == firstPageAction)
- preview->setCurrentPage(1);
- else if (action == lastPageAction)
- preview->setCurrentPage(preview->pageCount());
- updateNavActions();
-}
-
-void QPrintPreviewDialogPrivate::_q_setMode(QAction* action)
-{
- if (action == overviewModeAction) {
- preview->setViewMode(QPrintPreviewWidget::AllPagesView);
- setFitting(false);
- fitGroup->setEnabled(false);
- navGroup->setEnabled(false);
- pageNumEdit->setEnabled(false);
- pageNumLabel->setEnabled(false);
- } else if (action == facingModeAction) {
- preview->setViewMode(QPrintPreviewWidget::FacingPagesView);
- } else {
- preview->setViewMode(QPrintPreviewWidget::SinglePageView);
- }
- if (action == facingModeAction || action == singleModeAction) {
- fitGroup->setEnabled(true);
- navGroup->setEnabled(true);
- pageNumEdit->setEnabled(true);
- pageNumLabel->setEnabled(true);
- setFitting(true);
- }
-}
-
-void QPrintPreviewDialogPrivate::_q_print()
-{
- Q_Q(QPrintPreviewDialog);
-
-#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
- if (printer->outputFormat() != QPrinter::NativeFormat) {
- QString title;
- QString suffix;
- if (printer->outputFormat() == QPrinter::PdfFormat) {
- title = QCoreApplication::translate("QPrintPreviewDialog", "Export to PDF");
- suffix = QLatin1String(".pdf");
- } else {
- title = QCoreApplication::translate("QPrintPreviewDialog", "Export to PostScript");
- suffix = QLatin1String(".ps");
- }
- QString fileName = QFileDialog::getSaveFileName(q, title, printer->outputFileName(),
- QLatin1Char('*') + suffix);
- if (!fileName.isEmpty()) {
- if (QFileInfo(fileName).suffix().isEmpty())
- fileName.append(suffix);
- printer->setOutputFileName(fileName);
- }
- if (!printer->outputFileName().isEmpty())
- preview->print();
- q->accept();
- return;
- }
-#endif
-
- if (!printDialog)
- printDialog = new QPrintDialog(printer, q);
- if (printDialog->exec() == QDialog::Accepted) {
- preview->print();
- q->accept();
- }
-}
-
-void QPrintPreviewDialogPrivate::_q_pageSetup()
-{
- Q_Q(QPrintPreviewDialog);
-
- QPageSetupDialog pageSetup(printer, q);
- if (pageSetup.exec() == QDialog::Accepted) {
- // update possible orientation changes
- if (preview->orientation() == QPrinter::Portrait) {
- portraitAction->setChecked(true);
- preview->setPortraitOrientation();
- }else {
- landscapeAction->setChecked(true);
- preview->setLandscapeOrientation();
- }
- }
-}
-
-void QPrintPreviewDialogPrivate::_q_previewChanged()
-{
- updateNavActions();
- updatePageNumLabel();
- updateZoomFactor();
-}
-
-void QPrintPreviewDialogPrivate::_q_zoomFactorChanged()
-{
- QString text = zoomFactor->lineEdit()->text();
- bool ok;
- qreal factor = text.remove(QLatin1Char('%')).toFloat(&ok);
- factor = qMax(qreal(1.0), qMin(qreal(1000.0), factor));
- if (ok) {
- preview->setZoomFactor(factor/100.0);
- zoomFactor->setEditText(QString::fromLatin1("%1%").arg(factor));
- setFitting(false);
- }
-}
-
-///////////////////////////////////////////////////////////////////////////
-
-/*!
- \class QPrintPreviewDialog
- \since 4.4
-
- \brief The QPrintPreviewDialog class provides a dialog for
- previewing and configuring page layouts for printer output.
-
- \ingroup standard-dialogs
- \ingroup printing
-
- Using QPrintPreviewDialog in your existing application is
- straightforward:
-
- \list 1
- \o Create the QPrintPreviewDialog.
-
- You can construct a QPrintPreviewDialog with an existing QPrinter
- object, or you can have QPrintPreviewDialog create one for you,
- which will be the system default printer.
-
- \o Connect the paintRequested() signal to a slot.
-
- When the dialog needs to generate a set of preview pages, the
- paintRequested() signal will be emitted. You can use the exact
- same code for the actual printing as for having the preview
- generated, including calling QPrinter::newPage() to start a new
- page in the preview. Connect a slot to the paintRequested()
- signal, where you draw onto the QPrinter object that is passed
- into the slot.
-
- \o Call exec().
-
- Call QPrintPreviewDialog::exec() to show the preview dialog.
- \endlist
-
- In Symbian, there is no support for printing. Hence, this dialog should not
- be used in Symbian.
-
- \sa QPrinter, QPrintDialog, QPageSetupDialog, QPrintPreviewWidget
-*/
-
-/*!
- Constructs a QPrintPreviewDialog based on \a printer and with \a
- parent as the parent widget. The widget flags \a flags are passed on
- to the QWidget constructor.
-
- \sa QWidget::setWindowFlags()
-*/
-QPrintPreviewDialog::QPrintPreviewDialog(QPrinter* printer, QWidget *parent, Qt::WindowFlags flags)
- : QDialog(*new QPrintPreviewDialogPrivate, parent, flags)
-{
- Q_D(QPrintPreviewDialog);
- d->init(printer);
-}
-
-/*!
- \overload
- \fn QPrintPreviewDialog::QPrintPreviewDialog(QWidget *parent, Qt::WindowFlags flags)
-
- This will create an internal QPrinter object, which will use the
- system default printer.
-*/
-QPrintPreviewDialog::QPrintPreviewDialog(QWidget *parent, Qt::WindowFlags f)
- : QDialog(*new QPrintPreviewDialogPrivate, parent, f)
-{
- Q_D(QPrintPreviewDialog);
- d->init();
-}
-
-/*!
- Destroys the QPrintPreviewDialog.
-*/
-QPrintPreviewDialog::~QPrintPreviewDialog()
-{
- Q_D(QPrintPreviewDialog);
- if (d->ownPrinter)
- delete d->printer;
- delete d->printDialog;
-}
-
-/*!
- \reimp
-*/
-void QPrintPreviewDialog::setVisible(bool visible)
-{
- Q_D(QPrintPreviewDialog);
- // this will make the dialog get a decent default size
- if (visible && !d->initialized) {
- d->preview->updatePreview();
- d->initialized = true;
- }
- QDialog::setVisible(visible);
-}
-
-/*!
- \reimp
-*/
-void QPrintPreviewDialog::done(int result)
-{
- Q_D(QPrintPreviewDialog);
- QDialog::done(result);
- if (d->receiverToDisconnectOnClose) {
- disconnect(this, SIGNAL(finished(int)),
- d->receiverToDisconnectOnClose, d->memberToDisconnectOnClose);
- d->receiverToDisconnectOnClose = 0;
- }
- d->memberToDisconnectOnClose.clear();
-}
-
-/*!
- \overload
- \since 4.5
-
- Opens the dialog and connects its finished(int) signal to the slot specified
- by \a receiver and \a member.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QPrintPreviewDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QPrintPreviewDialog);
- // the int parameter isn't very useful here; we could just as well connect
- // to reject(), but this feels less robust somehow
- connect(this, SIGNAL(finished(int)), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-/*!
- Returns a pointer to the QPrinter object this dialog is currently
- operating on.
-*/
-QPrinter *QPrintPreviewDialog::printer()
-{
- Q_D(QPrintPreviewDialog);
- return d->printer;
-}
-
-/*!
- \fn void QPrintPreviewDialog::paintRequested(QPrinter *printer)
-
- This signal is emitted when the QPrintPreviewDialog needs to generate
- a set of preview pages.
-
- The \a printer instance supplied is the paint device onto which you should
- paint the contents of each page, using the QPrinter instance in the same way
- as you would when printing directly.
-*/
-
-
-QT_END_NAMESPACE
-
-#include "moc_qprintpreviewdialog.cpp"
-#include "qprintpreviewdialog.moc"
-
-#endif // QT_NO_PRINTPREVIEWDIALOG
-
-
diff --git a/src/gui/dialogs/qprintpreviewdialog.h b/src/gui/dialogs/qprintpreviewdialog.h
deleted file mode 100644
index a49455b520..0000000000
--- a/src/gui/dialogs/qprintpreviewdialog.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** 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 QPRINTPREVIEWDIALOG_H
-#define QPRINTPREVIEWDIALOG_H
-
-#include <QtGui/qdialog.h>
-
-#ifndef QT_NO_PRINTPREVIEWDIALOG
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QGraphicsView;
-class QPrintPreviewDialogPrivate;
-
-class Q_GUI_EXPORT QPrintPreviewDialog : public QDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPrintPreviewDialog)
-
-public:
- explicit QPrintPreviewDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- explicit QPrintPreviewDialog(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QPrintPreviewDialog();
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
- QPrinter *printer();
-
- void setVisible(bool visible);
- void done(int result);
-
-Q_SIGNALS:
- void paintRequested(QPrinter *printer);
-
-private:
- Q_PRIVATE_SLOT(d_func(), void _q_fit(QAction *action))
- Q_PRIVATE_SLOT(d_func(), void _q_zoomIn())
- Q_PRIVATE_SLOT(d_func(), void _q_zoomOut())
- Q_PRIVATE_SLOT(d_func(), void _q_navigate(QAction *action))
- Q_PRIVATE_SLOT(d_func(), void _q_setMode(QAction *action))
- Q_PRIVATE_SLOT(d_func(), void _q_pageNumEdited())
- Q_PRIVATE_SLOT(d_func(), void _q_print())
- Q_PRIVATE_SLOT(d_func(), void _q_pageSetup())
- Q_PRIVATE_SLOT(d_func(), void _q_previewChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_zoomFactorChanged())
-
- void *dummy; // ### Qt 5 - remove me
-};
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_PRINTPREVIEWDIALOG
-
-#endif // QPRINTPREVIEWDIALOG_H
diff --git a/src/gui/dialogs/qprintpropertieswidget.ui b/src/gui/dialogs/qprintpropertieswidget.ui
deleted file mode 100644
index 26fa09599e..0000000000
--- a/src/gui/dialogs/qprintpropertieswidget.ui
+++ /dev/null
@@ -1,70 +0,0 @@
-<ui version="4.0" >
- <class>QPrintPropertiesWidget</class>
- <widget class="QWidget" name="QPrintPropertiesWidget" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>396</width>
- <height>288</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Form</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_4" >
- <property name="margin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QTabWidget" name="tabs" >
- <property name="currentIndex" >
- <number>0</number>
- </property>
- <widget class="QWidget" name="tabPage" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>392</width>
- <height>261</height>
- </rect>
- </property>
- <attribute name="title" >
- <string>Page</string>
- </attribute>
- <layout class="QHBoxLayout" name="horizontalLayout" >
- <item>
- <widget class="QPageSetupWidget" native="1" name="pageSetup" />
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="cupsPropertiesPage" >
- <attribute name="title" >
- <string>Advanced</string>
- </attribute>
- <layout class="QHBoxLayout" name="horizontalLayout_2" >
- <item>
- <widget class="QTreeView" name="treeView" >
- <property name="alternatingRowColors" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>QPageSetupWidget</class>
- <extends>QWidget</extends>
- <header>qpagesetupdialog_unix_p.h</header>
- <container>1</container>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/gui/dialogs/qprintsettingsoutput.ui b/src/gui/dialogs/qprintsettingsoutput.ui
deleted file mode 100644
index be916790fb..0000000000
--- a/src/gui/dialogs/qprintsettingsoutput.ui
+++ /dev/null
@@ -1,363 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QPrintSettingsOutput</class>
- <widget class="QWidget" name="QPrintSettingsOutput">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>426</width>
- <height>171</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Form</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <property name="margin">
- <number>0</number>
- </property>
- <item>
- <widget class="QTabWidget" name="tabs">
- <property name="currentIndex">
- <number>0</number>
- </property>
- <widget class="QWidget" name="copiesTab">
- <attribute name="title">
- <string>Copies</string>
- </attribute>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QGroupBox" name="gbPrintRange">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="title">
- <string>Print range</string>
- </property>
- <layout class="QVBoxLayout" name="_3">
- <property name="spacing">
- <number>4</number>
- </property>
- <property name="margin">
- <number>6</number>
- </property>
- <item>
- <widget class="QRadioButton" name="printAll">
- <property name="text">
- <string>Print all</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="_4">
- <property name="spacing">
- <number>6</number>
- </property>
- <property name="margin">
- <number>0</number>
- </property>
- <item>
- <widget class="QRadioButton" name="printRange">
- <property name="text">
- <string>Pages from</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QSpinBox" name="from">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="minimum">
- <number>1</number>
- </property>
- <property name="maximum">
- <number>999</number>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="label_3">
- <property name="text">
- <string>to</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QSpinBox" name="to">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="minimum">
- <number>1</number>
- </property>
- <property name="maximum">
- <number>999</number>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>0</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QRadioButton" name="printCurrentPage">
- <property name="text">
- <string>Current Page</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="printSelection">
- <property name="text">
- <string>Selection</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>1</width>
- <height>1</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="groupBox">
- <property name="title">
- <string>Output Settings</string>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Copies:</string>
- </property>
- <property name="buddy">
- <cstring>copies</cstring>
- </property>
- </widget>
- </item>
- <item row="0" column="1" colspan="2">
- <widget class="QSpinBox" name="copies">
- <property name="minimum">
- <number>1</number>
- </property>
- <property name="maximum">
- <number>999</number>
- </property>
- </widget>
- </item>
- <item row="0" column="3">
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>91</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item row="1" column="0" colspan="2">
- <widget class="QCheckBox" name="collate">
- <property name="text">
- <string>Collate</string>
- </property>
- </widget>
- </item>
- <item row="1" column="2" rowspan="2" colspan="2">
- <widget class="QLabel" name="outputIcon">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Ignored" vsizetype="Ignored">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item row="2" column="0" colspan="2">
- <widget class="QCheckBox" name="reverse">
- <property name="text">
- <string>Reverse</string>
- </property>
- </widget>
- </item>
- <item row="3" column="0" colspan="4">
- <spacer name="verticalSpacer_2">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>0</width>
- <height>1</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="optionsTab">
- <attribute name="title">
- <string>Options</string>
- </attribute>
- <layout class="QGridLayout" name="gridLayout_2">
- <item row="0" column="1">
- <widget class="QGroupBox" name="colorMode">
- <property name="title">
- <string>Color Mode</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_4">
- <item row="2" column="0">
- <spacer name="verticalSpacer_6">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>1</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- <item row="0" column="0">
- <widget class="QRadioButton" name="color">
- <property name="text">
- <string>Color</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1" rowspan="3">
- <widget class="QLabel" name="colorIcon"/>
- </item>
- <item row="1" column="0">
- <widget class="QRadioButton" name="grayscale">
- <property name="text">
- <string>Grayscale</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item row="0" column="0">
- <widget class="QGroupBox" name="duplex">
- <property name="title">
- <string>Duplex Printing</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QRadioButton" name="noDuplex">
- <property name="text">
- <string>None</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="duplexLong">
- <property name="text">
- <string>Long side</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="duplexShort">
- <property name="text">
- <string>Short side</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_42">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>1</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections>
- <connection>
- <sender>printRange</sender>
- <signal>toggled(bool)</signal>
- <receiver>from</receiver>
- <slot>setEnabled(bool)</slot>
- <hints>
- <hint type="sourcelabel">
- <x>76</x>
- <y>59</y>
- </hint>
- <hint type="destinationlabel">
- <x>122</x>
- <y>57</y>
- </hint>
- </hints>
- </connection>
- <connection>
- <sender>printRange</sender>
- <signal>toggled(bool)</signal>
- <receiver>to</receiver>
- <slot>setEnabled(bool)</slot>
- <hints>
- <hint type="sourcelabel">
- <x>69</x>
- <y>67</y>
- </hint>
- <hint type="destinationlabel">
- <x>215</x>
- <y>67</y>
- </hint>
- </hints>
- </connection>
- </connections>
-</ui>
diff --git a/src/gui/dialogs/qprintwidget.ui b/src/gui/dialogs/qprintwidget.ui
deleted file mode 100644
index 8a4f3bde0a..0000000000
--- a/src/gui/dialogs/qprintwidget.ui
+++ /dev/null
@@ -1,116 +0,0 @@
-<ui version="4.0" >
- <class>QPrintWidget</class>
- <widget class="QWidget" name="QPrintWidget" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>443</width>
- <height>175</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Form</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout_2" >
- <property name="margin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QGroupBox" name="printerGroup" >
- <property name="title" >
- <string>Printer</string>
- </property>
- <layout class="QGridLayout" name="gridLayout" >
- <item row="0" column="0" >
- <widget class="QLabel" name="label" >
- <property name="text" >
- <string>&amp;Name:</string>
- </property>
- <property name="buddy" >
- <cstring>printers</cstring>
- </property>
- </widget>
- </item>
- <item row="0" column="1" >
- <widget class="QComboBox" name="printers" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Preferred" >
- <horstretch>3</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item row="0" column="2" >
- <widget class="QPushButton" name="properties" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Minimum" >
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>P&amp;roperties</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0" >
- <widget class="QLabel" name="label_2" >
- <property name="text" >
- <string>Location:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1" >
- <widget class="QLabel" name="location" />
- </item>
- <item row="1" column="2" >
- <widget class="QCheckBox" name="preview" >
- <property name="text" >
- <string>Preview</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QLabel" name="label_3" >
- <property name="text" >
- <string>Type:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1" >
- <widget class="QLabel" name="type" />
- </item>
- <item row="3" column="0" >
- <widget class="QLabel" name="lOutput" >
- <property name="text" >
- <string>Output &amp;file:</string>
- </property>
- <property name="buddy" >
- <cstring>filename</cstring>
- </property>
- </widget>
- </item>
- <item row="3" column="1" colspan="2" >
- <layout class="QHBoxLayout" name="horizontalLayout" >
- <item>
- <widget class="QLineEdit" name="filename" />
- </item>
- <item>
- <widget class="QToolButton" name="fileBrowser" >
- <property name="text" >
- <string>...</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/gui/dialogs/qprogressdialog.cpp b/src/gui/dialogs/qprogressdialog.cpp
deleted file mode 100644
index a3fff9b617..0000000000
--- a/src/gui/dialogs/qprogressdialog.cpp
+++ /dev/null
@@ -1,907 +0,0 @@
-/****************************************************************************
-**
-** 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 "qprogressdialog.h"
-
-#ifndef QT_NO_PROGRESSDIALOG
-
-#include "qshortcut.h"
-#include "qpainter.h"
-#include "qdrawutil.h"
-#include "qlabel.h"
-#include "qprogressbar.h"
-#include "qapplication.h"
-#include "qstyle.h"
-#include "qpushbutton.h"
-#include "qcursor.h"
-#include "qtimer.h"
-#include "qelapsedtimer.h"
-#include <private/qdialog_p.h>
-#include <limits.h>
-
-#if defined(QT_SOFTKEYS_ENABLED)
-#include <qaction.h>
-#endif
-#ifdef Q_WS_S60
-#include <QtGui/qdesktopwidget.h>
-#endif
-
-
-QT_BEGIN_NAMESPACE
-
-// If the operation is expected to take this long (as predicted by
-// progress time), show the progress dialog.
-static const int defaultShowTime = 4000;
-// Wait at least this long before attempting to make a prediction.
-static const int minWaitTime = 50;
-
-class QProgressDialogPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QProgressDialog)
-
-public:
- QProgressDialogPrivate() : label(0), cancel(0), bar(0),
- shown_once(false),
- cancellation_flag(false),
- showTime(defaultShowTime),
-#ifndef QT_NO_SHORTCUT
- escapeShortcut(0),
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- cancelAction(0),
-#endif
- useDefaultCancelText(false)
- {
- }
-
- void init(const QString &labelText, const QString &cancelText, int min, int max);
- void layout();
- void retranslateStrings();
- void _q_disconnectOnClose();
-
- QLabel *label;
- QPushButton *cancel;
- QProgressBar *bar;
- QTimer *forceTimer;
- bool shown_once;
- bool cancellation_flag;
- QElapsedTimer starttime;
-#ifndef QT_NO_CURSOR
- QCursor parentCursor;
-#endif
- int showTime;
- bool autoClose;
- bool autoReset;
- bool forceHide;
-#ifndef QT_NO_SHORTCUT
- QShortcut *escapeShortcut;
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- QAction *cancelAction;
-#endif
- bool useDefaultCancelText;
- QPointer<QObject> receiverToDisconnectOnClose;
- QByteArray memberToDisconnectOnClose;
-};
-
-void QProgressDialogPrivate::init(const QString &labelText, const QString &cancelText,
- int min, int max)
-{
- Q_Q(QProgressDialog);
- label = new QLabel(labelText, q);
- int align = q->style()->styleHint(QStyle::SH_ProgressDialog_TextLabelAlignment, 0, q);
- label->setAlignment(Qt::Alignment(align));
- bar = new QProgressBar(q);
- bar->setRange(min, max);
- autoClose = true;
- autoReset = true;
- forceHide = false;
- QObject::connect(q, SIGNAL(canceled()), q, SLOT(cancel()));
- forceTimer = new QTimer(q);
- QObject::connect(forceTimer, SIGNAL(timeout()), q, SLOT(forceShow()));
- if (useDefaultCancelText) {
- retranslateStrings();
- } else {
- q->setCancelButtonText(cancelText);
- }
-}
-
-void QProgressDialogPrivate::layout()
-{
- Q_Q(QProgressDialog);
- int sp = q->style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
- int mtb = q->style()->pixelMetric(QStyle::PM_DefaultTopLevelMargin);
- int mlr = qMin(q->width() / 10, mtb);
- const bool centered =
- bool(q->style()->styleHint(QStyle::SH_ProgressDialog_CenterCancelButton, 0, q));
-
- int additionalSpacing = 0;
-#ifdef Q_OS_SYMBIAN
- //In Symbian, we need to have wider margins for dialog borders, as the actual border is some pixels
- //inside the dialog area (to enable transparent borders)
- additionalSpacing = mlr;
-#endif
-
- QSize cs = cancel ? cancel->sizeHint() : QSize(0,0);
- QSize bh = bar->sizeHint();
- int cspc;
- int lh = 0;
-
- // Find spacing and sizes that fit. It is important that a progress
- // dialog can be made very small if the user demands it so.
- for (int attempt=5; attempt--;) {
- cspc = cancel ? cs.height() + sp : 0;
- lh = qMax(0, q->height() - mtb - bh.height() - sp - cspc);
-
- if (lh < q->height()/4) {
- // Getting cramped
- sp /= 2;
- mtb /= 2;
- if (cancel) {
- cs.setHeight(qMax(4,cs.height()-sp-2));
- }
- bh.setHeight(qMax(4,bh.height()-sp-1));
- } else {
- break;
- }
- }
-
- if (cancel) {
- cancel->setGeometry(
- centered ? q->width()/2 - cs.width()/2 : q->width() - mlr - cs.width(),
- q->height() - mtb - cs.height(),
- cs.width(), cs.height());
- }
-
- if (label)
- label->setGeometry(mlr, additionalSpacing, q->width() - mlr * 2, lh);
- bar->setGeometry(mlr, lh + sp + additionalSpacing, q->width() - mlr * 2, bh.height());
-}
-
-void QProgressDialogPrivate::retranslateStrings()
-{
- Q_Q(QProgressDialog);
- if (useDefaultCancelText)
- q->setCancelButtonText(QProgressDialog::tr("Cancel"));
-}
-
-void QProgressDialogPrivate::_q_disconnectOnClose()
-{
- Q_Q(QProgressDialog);
- if (receiverToDisconnectOnClose) {
- QObject::disconnect(q, SIGNAL(canceled()), receiverToDisconnectOnClose,
- memberToDisconnectOnClose);
- receiverToDisconnectOnClose = 0;
- }
- memberToDisconnectOnClose.clear();
-}
-
-/*!
- \class QProgressDialog
- \brief The QProgressDialog class provides feedback on the progress of a slow operation.
- \ingroup standard-dialogs
-
-
- A progress dialog is used to give the user an indication of how long
- an operation is going to take, and to demonstrate that the
- application has not frozen. It can also give the user an opportunity
- to abort the operation.
-
- A common problem with progress dialogs is that it is difficult to know
- when to use them; operations take different amounts of time on different
- hardware. QProgressDialog offers a solution to this problem:
- it estimates the time the operation will take (based on time for
- steps), and only shows itself if that estimate is beyond minimumDuration()
- (4 seconds by default).
-
- Use setMinimum() and setMaximum() or the constructor to set the number of
- "steps" in the operation and call setValue() as the operation
- progresses. The number of steps can be chosen arbitrarily. It can be the
- number of files copied, the number of bytes received, the number of
- iterations through the main loop of your algorithm, or some other
- suitable unit. Progress starts at the value set by setMinimum(),
- and the progress dialog shows that the operation has finished when
- you call setValue() with the value set by setMaximum() as its argument.
-
- The dialog automatically resets and hides itself at the end of the
- operation. Use setAutoReset() and setAutoClose() to change this
- behavior. Note that if you set a new maximum (using setMaximum() or
- setRange()) that equals your current value(), the dialog will not
- close regardless.
-
- There are two ways of using QProgressDialog: modal and modeless.
-
- Compared to a modeless QProgressDialog, a modal QProgressDialog is simpler
- to use for the programmer. Do the operation in a loop, call \l setValue() at
- intervals, and check for cancellation with wasCanceled(). For example:
-
- \snippet doc/src/snippets/dialogs/dialogs.cpp 3
-
- A modeless progress dialog is suitable for operations that take
- place in the background, where the user is able to interact with the
- application. Such operations are typically based on QTimer (or
- QObject::timerEvent()), QSocketNotifier, or QUrlOperator; or performed
- in a separate thread. A QProgressBar in the status bar of your main window
- is often an alternative to a modeless progress dialog.
-
- You need to have an event loop to be running, connect the
- canceled() signal to a slot that stops the operation, and call \l
- setValue() at intervals. For example:
-
- \snippet doc/src/snippets/dialogs/dialogs.cpp 4
- \codeline
- \snippet doc/src/snippets/dialogs/dialogs.cpp 5
- \codeline
- \snippet doc/src/snippets/dialogs/dialogs.cpp 6
-
- In both modes the progress dialog may be customized by
- replacing the child widgets with custom widgets by using setLabel(),
- setBar(), and setCancelButton().
- The functions setLabelText() and setCancelButtonText()
- set the texts shown.
-
- \image plastique-progressdialog.png A progress dialog shown in the Plastique widget style.
-
- \sa QDialog, QProgressBar, {fowler}{GUI Design Handbook: Progress Indicator},
- {Find Files Example}, {Pixelator Example}
-*/
-
-
-/*!
- Constructs a progress dialog.
-
- Default settings:
- \list
- \i The label text is empty.
- \i The cancel button text is (translated) "Cancel".
- \i minimum is 0;
- \i maximum is 100
- \endlist
-
- The \a parent argument is dialog's parent widget. The widget flags, \a f, are
- passed to the QDialog::QDialog() constructor.
-
- \sa setLabelText(), setCancelButtonText(), setCancelButton(),
- setMinimum(), setMaximum()
-*/
-
-QProgressDialog::QProgressDialog(QWidget *parent, Qt::WindowFlags f)
- : QDialog(*(new QProgressDialogPrivate), parent, f)
-{
- Q_D(QProgressDialog);
- d->useDefaultCancelText = true;
- d->init(QString::fromLatin1(""), QString(), 0, 100);
-}
-
-/*!
- Constructs a progress dialog.
-
- The \a labelText is the text used to remind the user what is progressing.
-
- The \a cancelButtonText is the text to display on the cancel button. If
- QString() is passed then no cancel button is shown.
-
- The \a minimum and \a maximum is the number of steps in the operation for
- which this progress dialog shows progress. For example, if the
- operation is to examine 50 files, this value minimum value would be 0,
- and the maximum would be 50. Before examining the first file, call
- setValue(0). As each file is processed call setValue(1), setValue(2),
- etc., finally calling setValue(50) after examining the last file.
-
- The \a parent argument is the dialog's parent widget. The parent, \a parent, and
- widget flags, \a f, are passed to the QDialog::QDialog() constructor.
-
- \sa setLabelText(), setLabel(), setCancelButtonText(), setCancelButton(),
- setMinimum(), setMaximum()
-*/
-
-QProgressDialog::QProgressDialog(const QString &labelText,
- const QString &cancelButtonText,
- int minimum, int maximum,
- QWidget *parent, Qt::WindowFlags f)
- : QDialog(*(new QProgressDialogPrivate), parent, f)
-{
- Q_D(QProgressDialog);
- d->init(labelText, cancelButtonText, minimum, maximum);
-}
-
-
-/*!
- Destroys the progress dialog.
-*/
-
-QProgressDialog::~QProgressDialog()
-{
-}
-
-/*!
- \fn void QProgressDialog::canceled()
-
- This signal is emitted when the cancel button is clicked.
- It is connected to the cancel() slot by default.
-
- \sa wasCanceled()
-*/
-
-
-/*!
- Sets the label to \a label. The progress dialog resizes to fit. The
- label becomes owned by the progress dialog and will be deleted when
- necessary, so do not pass the address of an object on the stack.
-
- \sa setLabelText()
-*/
-
-void QProgressDialog::setLabel(QLabel *label)
-{
- Q_D(QProgressDialog);
- delete d->label;
- d->label = label;
- if (label) {
- if (label->parentWidget() == this) {
- label->hide(); // until we resize
- } else {
- label->setParent(this, 0);
- }
- }
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
- if (label)
- label->show();
-}
-
-
-/*!
- \property QProgressDialog::labelText
- \brief the label's text
-
- The default text is an empty string.
-*/
-
-QString QProgressDialog::labelText() const
-{
- Q_D(const QProgressDialog);
- if (d->label)
- return d->label->text();
- return QString();
-}
-
-void QProgressDialog::setLabelText(const QString &text)
-{
- Q_D(QProgressDialog);
- if (d->label) {
- d->label->setText(text);
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
- }
-}
-
-
-/*!
- Sets the cancel button to the push button, \a cancelButton. The
- progress dialog takes ownership of this button which will be deleted
- when necessary, so do not pass the address of an object that is on
- the stack, i.e. use new() to create the button. If 0 is passed then
- no cancel button will be shown.
-
- \sa setCancelButtonText()
-*/
-
-void QProgressDialog::setCancelButton(QPushButton *cancelButton)
-{
- Q_D(QProgressDialog);
- delete d->cancel;
- d->cancel = cancelButton;
- if (cancelButton) {
- if (cancelButton->parentWidget() == this) {
- cancelButton->hide(); // until we resize
- } else {
- cancelButton->setParent(this, 0);
- }
- connect(d->cancel, SIGNAL(clicked()), this, SIGNAL(canceled()));
-#ifndef QT_NO_SHORTCUT
- d->escapeShortcut = new QShortcut(Qt::Key_Escape, this, SIGNAL(canceled()));
-#endif
- } else {
-#ifndef QT_NO_SHORTCUT
- delete d->escapeShortcut;
- d->escapeShortcut = 0;
-#endif
- }
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
- if (cancelButton)
-#if !defined(QT_SOFTKEYS_ENABLED)
- cancelButton->show();
-#else
- {
- d->cancelAction = new QAction(cancelButton->text(), cancelButton);
- d->cancelAction->setSoftKeyRole(QAction::NegativeSoftKey);
- connect(d->cancelAction, SIGNAL(triggered()), this, SIGNAL(canceled()));
- addAction(d->cancelAction);
- }
-#endif
-}
-
-/*!
- Sets the cancel button's text to \a cancelButtonText. If the text
- is set to QString() then it will cause the cancel button to be
- hidden and deleted.
-
- \sa setCancelButton()
-*/
-
-void QProgressDialog::setCancelButtonText(const QString &cancelButtonText)
-{
- Q_D(QProgressDialog);
- d->useDefaultCancelText = false;
-
- if (!cancelButtonText.isNull()) {
- if (d->cancel) {
- d->cancel->setText(cancelButtonText);
-#ifdef QT_SOFTKEYS_ENABLED
- d->cancelAction->setText(cancelButtonText);
-#endif
- } else {
- setCancelButton(new QPushButton(cancelButtonText, this));
- }
- } else {
- setCancelButton(0);
- }
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
-}
-
-
-/*!
- Sets the progress bar widget to \a bar. The progress dialog resizes to
- fit. The progress dialog takes ownership of the progress \a bar which
- will be deleted when necessary, so do not use a progress bar
- allocated on the stack.
-*/
-
-void QProgressDialog::setBar(QProgressBar *bar)
-{
- Q_D(QProgressDialog);
- if (!bar) {
- qWarning("QProgressDialog::setBar: Cannot set a null progress bar");
- return;
- }
-#ifndef QT_NO_DEBUG
- if (value() > 0)
- qWarning("QProgressDialog::setBar: Cannot set a new progress bar "
- "while the old one is active");
-#endif
- delete d->bar;
- d->bar = bar;
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
-}
-
-
-/*!
- \property QProgressDialog::wasCanceled
- \brief whether the dialog was canceled
-*/
-
-bool QProgressDialog::wasCanceled() const
-{
- Q_D(const QProgressDialog);
- return d->cancellation_flag;
-}
-
-
-/*!
- \property QProgressDialog::maximum
- \brief the highest value represented by the progress bar
-
- The default is 0.
-
- \sa minimum, setRange()
-*/
-
-int QProgressDialog::maximum() const
-{
- Q_D(const QProgressDialog);
- return d->bar->maximum();
-}
-
-void QProgressDialog::setMaximum(int maximum)
-{
- Q_D(QProgressDialog);
- d->bar->setMaximum(maximum);
-}
-
-/*!
- \property QProgressDialog::minimum
- \brief the lowest value represented by the progress bar
-
- The default is 0.
-
- \sa maximum, setRange()
-*/
-
-int QProgressDialog::minimum() const
-{
- Q_D(const QProgressDialog);
- return d->bar->minimum();
-}
-
-void QProgressDialog::setMinimum(int minimum)
-{
- Q_D(QProgressDialog);
- d->bar->setMinimum(minimum);
-}
-
-/*!
- Sets the progress dialog's minimum and maximum values
- to \a minimum and \a maximum, respectively.
-
- If \a maximum is smaller than \a minimum, \a minimum becomes the only
- legal value.
-
- If the current value falls outside the new range, the progress
- dialog is reset with reset().
-
- \sa minimum, maximum
-*/
-void QProgressDialog::setRange(int minimum, int maximum)
-{
- Q_D(QProgressDialog);
- d->bar->setRange(minimum, maximum);
-}
-
-
-/*!
- Resets the progress dialog.
- The progress dialog becomes hidden if autoClose() is true.
-
- \sa setAutoClose(), setAutoReset()
-*/
-
-void QProgressDialog::reset()
-{
- Q_D(QProgressDialog);
-#ifndef QT_NO_CURSOR
- if (value() >= 0) {
- if (parentWidget())
- parentWidget()->setCursor(d->parentCursor);
- }
-#endif
- if (d->autoClose || d->forceHide)
- hide();
- d->bar->reset();
- d->cancellation_flag = false;
- d->shown_once = false;
- d->forceTimer->stop();
-
- /*
- I wish we could disconnect the user slot provided to open() here but
- unfortunately reset() is usually called before the slot has been invoked.
- (reset() is itself invoked when canceled() is emitted.)
- */
- if (d->receiverToDisconnectOnClose)
- QMetaObject::invokeMethod(this, "_q_disconnectOnClose", Qt::QueuedConnection);
-}
-
-/*!
- Resets the progress dialog. wasCanceled() becomes true until
- the progress dialog is reset.
- The progress dialog becomes hidden.
-*/
-
-void QProgressDialog::cancel()
-{
- Q_D(QProgressDialog);
- d->forceHide = true;
- reset();
- d->forceHide = false;
- d->cancellation_flag = true;
-}
-
-
-int QProgressDialog::value() const
-{
- Q_D(const QProgressDialog);
- return d->bar->value();
-}
-
-/*!
- \property QProgressDialog::value
- \brief the current amount of progress made.
-
- For the progress dialog to work as expected, you should initially set
- this property to 0 and finally set it to
- QProgressDialog::maximum(); you can call setValue() any number of times
- in-between.
-
- \warning If the progress dialog is modal
- (see QProgressDialog::QProgressDialog()),
- setValue() calls QApplication::processEvents(), so take care that
- this does not cause undesirable re-entrancy in your code. For example,
- don't use a QProgressDialog inside a paintEvent()!
-
- \sa minimum, maximum
-*/
-void QProgressDialog::setValue(int progress)
-{
- Q_D(QProgressDialog);
- if (progress == d->bar->value()
- || (d->bar->value() == -1 && progress == d->bar->maximum()))
- return;
-
- d->bar->setValue(progress);
-
- if (d->shown_once) {
- if (isModal())
- QApplication::processEvents();
- } else {
- if (progress == 0) {
- d->starttime.start();
- d->forceTimer->start(d->showTime);
- return;
- } else {
- bool need_show;
- int elapsed = d->starttime.elapsed();
- if (elapsed >= d->showTime) {
- need_show = true;
- } else {
- if (elapsed > minWaitTime) {
- int estimate;
- int totalSteps = maximum() - minimum();
- int myprogress = progress - minimum();
- if ((totalSteps - myprogress) >= INT_MAX / elapsed)
- estimate = (totalSteps - myprogress) / myprogress * elapsed;
- else
- estimate = elapsed * (totalSteps - myprogress) / myprogress;
- need_show = estimate >= d->showTime;
- } else {
- need_show = false;
- }
- }
- if (need_show) {
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
- show();
- d->shown_once = true;
- }
- }
-#ifdef Q_WS_MAC
- QApplication::flush();
-#endif
- }
-
- if (progress == d->bar->maximum() && d->autoReset)
- reset();
-}
-
-/*!
- Returns a size that fits the contents of the progress dialog.
- The progress dialog resizes itself as required, so you should not
- need to call this yourself.
-*/
-
-QSize QProgressDialog::sizeHint() const
-{
- Q_D(const QProgressDialog);
- QSize sh = d->label ? d->label->sizeHint() : QSize(0, 0);
- QSize bh = d->bar->sizeHint();
- int margin = style()->pixelMetric(QStyle::PM_DefaultTopLevelMargin);
- int spacing = style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
- int h = margin * 2 + bh.height() + sh.height() + spacing;
- if (d->cancel)
- h += d->cancel->sizeHint().height() + spacing;
-#ifdef Q_WS_S60
- if (QApplication::desktop()->size().height() > QApplication::desktop()->size().width())
- return QSize(qMax(QApplication::desktop()->size().width(), sh.width() + 2 * margin), h);
- else
- return QSize(qMax(QApplication::desktop()->size().height(), sh.width() + 2 * margin), h);
-#else
- return QSize(qMax(200, sh.width() + 2 * margin), h);
-#endif
-}
-
-/*!\reimp
-*/
-void QProgressDialog::resizeEvent(QResizeEvent *)
-{
- Q_D(QProgressDialog);
- d->layout();
-}
-
-/*!
- \reimp
-*/
-void QProgressDialog::changeEvent(QEvent *ev)
-{
- Q_D(QProgressDialog);
- if (ev->type() == QEvent::StyleChange) {
- d->layout();
- } else if (ev->type() == QEvent::LanguageChange) {
- d->retranslateStrings();
- }
- QDialog::changeEvent(ev);
-}
-
-/*!
- \property QProgressDialog::minimumDuration
- \brief the time that must pass before the dialog appears
-
- If the expected duration of the task is less than the
- minimumDuration, the dialog will not appear at all. This prevents
- the dialog popping up for tasks that are quickly over. For tasks
- that are expected to exceed the minimumDuration, the dialog will
- pop up after the minimumDuration time or as soon as any progress
- is set.
-
- If set to 0, the dialog is always shown as soon as any progress is
- set. The default is 4000 milliseconds.
-*/
-void QProgressDialog::setMinimumDuration(int ms)
-{
- Q_D(QProgressDialog);
- d->showTime = ms;
- if (d->bar->value() == 0) {
- d->forceTimer->stop();
- d->forceTimer->start(ms);
- }
-}
-
-int QProgressDialog::minimumDuration() const
-{
- Q_D(const QProgressDialog);
- return d->showTime;
-}
-
-
-/*!
- \reimp
-*/
-
-void QProgressDialog::closeEvent(QCloseEvent *e)
-{
- emit canceled();
- QDialog::closeEvent(e);
-}
-
-/*!
- \property QProgressDialog::autoReset
- \brief whether the progress dialog calls reset() as soon as value() equals maximum()
-
- The default is true.
-
- \sa setAutoClose()
-*/
-
-void QProgressDialog::setAutoReset(bool b)
-{
- Q_D(QProgressDialog);
- d->autoReset = b;
-}
-
-bool QProgressDialog::autoReset() const
-{
- Q_D(const QProgressDialog);
- return d->autoReset;
-}
-
-/*!
- \property QProgressDialog::autoClose
- \brief whether the dialog gets hidden by reset()
-
- The default is true.
-
- \sa setAutoReset()
-*/
-
-void QProgressDialog::setAutoClose(bool close)
-{
- Q_D(QProgressDialog);
- d->autoClose = close;
-}
-
-bool QProgressDialog::autoClose() const
-{
- Q_D(const QProgressDialog);
- return d->autoClose;
-}
-
-/*!
- \reimp
-*/
-
-void QProgressDialog::showEvent(QShowEvent *e)
-{
- Q_D(QProgressDialog);
- QDialog::showEvent(e);
- int w = qMax(isVisible() ? width() : 0, sizeHint().width());
- int h = qMax(isVisible() ? height() : 0, sizeHint().height());
- resize(w, h);
- d->forceTimer->stop();
-}
-
-/*!
- Shows the dialog if it is still hidden after the algorithm has been started
- and minimumDuration milliseconds have passed.
-
- \sa setMinimumDuration()
-*/
-
-void QProgressDialog::forceShow()
-{
- Q_D(QProgressDialog);
- d->forceTimer->stop();
- if (d->shown_once || d->cancellation_flag)
- return;
-
- show();
- d->shown_once = true;
-}
-
-/*!
- \since 4.5
- \overload
-
- Opens the dialog and connects its accepted() signal to the slot specified
- by \a receiver and \a member.
-
- The signal will be disconnected from the slot when the dialog is closed.
-*/
-void QProgressDialog::open(QObject *receiver, const char *member)
-{
- Q_D(QProgressDialog);
- connect(this, SIGNAL(canceled()), receiver, member);
- d->receiverToDisconnectOnClose = receiver;
- d->memberToDisconnectOnClose = member;
- QDialog::open();
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qprogressdialog.cpp"
-
-#endif // QT_NO_PROGRESSDIALOG
diff --git a/src/gui/dialogs/qprogressdialog.h b/src/gui/dialogs/qprogressdialog.h
deleted file mode 100644
index 21a40c152f..0000000000
--- a/src/gui/dialogs/qprogressdialog.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/****************************************************************************
-**
-** 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 QPROGRESSDIALOG_H
-#define QPROGRESSDIALOG_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PROGRESSDIALOG
-
-class QPushButton;
-class QLabel;
-class QProgressBar;
-class QTimer;
-class QProgressDialogPrivate;
-
-class Q_GUI_EXPORT QProgressDialog : public QDialog
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QProgressDialog)
- Q_PROPERTY(bool wasCanceled READ wasCanceled)
- Q_PROPERTY(int minimum READ minimum WRITE setMinimum)
- Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
- Q_PROPERTY(int value READ value WRITE setValue)
- Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)
- Q_PROPERTY(bool autoClose READ autoClose WRITE setAutoClose)
- Q_PROPERTY(int minimumDuration READ minimumDuration WRITE setMinimumDuration)
- Q_PROPERTY(QString labelText READ labelText WRITE setLabelText)
-
-public:
- explicit QProgressDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- QProgressDialog(const QString &labelText, const QString &cancelButtonText,
- int minimum, int maximum, QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QProgressDialog();
-
- void setLabel(QLabel *label);
- void setCancelButton(QPushButton *button);
- void setBar(QProgressBar *bar);
-
- bool wasCanceled() const;
-
- int minimum() const;
- int maximum() const;
-
- int value() const;
-
- QSize sizeHint() const;
-
- QString labelText() const;
- int minimumDuration() const;
-
- void setAutoReset(bool reset);
- bool autoReset() const;
- void setAutoClose(bool close);
- bool autoClose() const;
-
-#ifdef Q_NO_USING_KEYWORD
-#ifndef Q_QDOC
- void open() { QDialog::open(); }
-#endif
-#else
- using QDialog::open;
-#endif
- void open(QObject *receiver, const char *member);
-
-public Q_SLOTS:
- void cancel();
- void reset();
- void setMaximum(int maximum);
- void setMinimum(int minimum);
- void setRange(int minimum, int maximum);
- void setValue(int progress);
- void setLabelText(const QString &text);
- void setCancelButtonText(const QString &text);
- void setMinimumDuration(int ms);
-
-Q_SIGNALS:
- void canceled();
-
-protected:
- void resizeEvent(QResizeEvent *event);
- void closeEvent(QCloseEvent *event);
- void changeEvent(QEvent *event);
- void showEvent(QShowEvent *event);
-
-protected Q_SLOTS:
- void forceShow();
-
-private:
- Q_DISABLE_COPY(QProgressDialog)
-
- Q_PRIVATE_SLOT(d_func(), void _q_disconnectOnClose())
-};
-
-#endif // QT_NO_PROGRESSDIALOG
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPROGRESSDIALOG_H
diff --git a/src/gui/dialogs/qsidebar.cpp b/src/gui/dialogs/qsidebar.cpp
deleted file mode 100644
index 2869e1262b..0000000000
--- a/src/gui/dialogs/qsidebar.cpp
+++ /dev/null
@@ -1,509 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsidebar_p.h"
-#include "qfilesystemmodel.h"
-
-#ifndef QT_NO_FILEDIALOG
-
-#include <qaction.h>
-#include <qurl.h>
-#include <qmenu.h>
-#include <qmimedata.h>
-#include <qevent.h>
-#include <qdebug.h>
-#include <qfileiconprovider.h>
-#include <qfiledialog.h>
-
-QT_BEGIN_NAMESPACE
-
-void QSideBarDelegate::initStyleOption(QStyleOptionViewItem *option,
- const QModelIndex &index) const
-{
- QStyledItemDelegate::initStyleOption(option,index);
- QVariant value = index.data(QUrlModel::EnabledRole);
- if (value.isValid()) {
- //If the bookmark/entry is not enabled then we paint it in gray
- if (!qvariant_cast<bool>(value))
- option->state &= ~QStyle::State_Enabled;
- }
-}
-
-/*!
- QUrlModel lets you have indexes from a QFileSystemModel to a list. When QFileSystemModel
- changes them QUrlModel will automatically update.
-
- Example usage: File dialog sidebar and combo box
- */
-QUrlModel::QUrlModel(QObject *parent) : QStandardItemModel(parent), showFullPath(false), fileSystemModel(0)
-{
-}
-
-/*!
- \reimp
-*/
-QStringList QUrlModel::mimeTypes() const
-{
- return QStringList(QLatin1String("text/uri-list"));
-}
-
-/*!
- \reimp
-*/
-Qt::ItemFlags QUrlModel::flags(const QModelIndex &index) const
-{
- Qt::ItemFlags flags = QStandardItemModel::flags(index);
- if (index.isValid()) {
- flags &= ~Qt::ItemIsEditable;
- // ### some future version could support "moving" urls onto a folder
- flags &= ~Qt::ItemIsDropEnabled;
- }
-
- if (index.data(Qt::DecorationRole).isNull())
- flags &= ~Qt::ItemIsEnabled;
-
- return flags;
-}
-
-/*!
- \reimp
-*/
-QMimeData *QUrlModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QUrl> list;
- for (int i = 0; i < indexes.count(); ++i) {
- if (indexes.at(i).column() == 0)
- list.append(indexes.at(i).data(UrlRole).toUrl());
- }
- QMimeData *data = new QMimeData();
- data->setUrls(list);
- return data;
-}
-
-#ifndef QT_NO_DRAGANDDROP
-
-/*!
- Decide based upon the data if it should be accepted or not
-
- We only accept dirs and not files
-*/
-bool QUrlModel::canDrop(QDragEnterEvent *event)
-{
- if (!event->mimeData()->formats().contains(mimeTypes().first()))
- return false;
-
- const QList<QUrl> list = event->mimeData()->urls();
- for (int i = 0; i < list.count(); ++i) {
- QModelIndex idx = fileSystemModel->index(list.at(0).toLocalFile());
- if (!fileSystemModel->isDir(idx))
- return false;
- }
- return true;
-}
-
-/*!
- \reimp
-*/
-bool QUrlModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- if (!data->formats().contains(mimeTypes().first()))
- return false;
- Q_UNUSED(action);
- Q_UNUSED(column);
- Q_UNUSED(parent);
- addUrls(data->urls(), row);
- return true;
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- \reimp
-
- If the role is the UrlRole then handle otherwise just pass to QStandardItemModel
-*/
-bool QUrlModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (value.type() == QVariant::Url) {
- QUrl url = value.toUrl();
- QModelIndex dirIndex = fileSystemModel->index(url.toLocalFile());
- //On windows the popup display the "C:\", convert to nativeSeparators
- if (showFullPath)
- QStandardItemModel::setData(index, QDir::toNativeSeparators(fileSystemModel->data(dirIndex, QFileSystemModel::FilePathRole).toString()));
- else {
- QStandardItemModel::setData(index, QDir::toNativeSeparators(fileSystemModel->data(dirIndex, QFileSystemModel::FilePathRole).toString()), Qt::ToolTipRole);
- QStandardItemModel::setData(index, fileSystemModel->data(dirIndex).toString());
- }
- QStandardItemModel::setData(index, fileSystemModel->data(dirIndex, Qt::DecorationRole),
- Qt::DecorationRole);
- QStandardItemModel::setData(index, url, UrlRole);
- return true;
- }
- return QStandardItemModel::setData(index, value, role);
-}
-
-void QUrlModel::setUrl(const QModelIndex &index, const QUrl &url, const QModelIndex &dirIndex)
-{
- setData(index, url, UrlRole);
- if (url.path().isEmpty()) {
- setData(index, fileSystemModel->myComputer());
- setData(index, fileSystemModel->myComputer(Qt::DecorationRole), Qt::DecorationRole);
- } else {
- QString newName;
- if (showFullPath) {
- //On windows the popup display the "C:\", convert to nativeSeparators
- newName = QDir::toNativeSeparators(dirIndex.data(QFileSystemModel::FilePathRole).toString());
- } else {
- newName = dirIndex.data().toString();
- }
-
- QIcon newIcon = qvariant_cast<QIcon>(dirIndex.data(Qt::DecorationRole));
- if (!dirIndex.isValid()) {
- newIcon = fileSystemModel->iconProvider()->icon(QFileIconProvider::Folder);
- newName = QFileInfo(url.toLocalFile()).fileName();
- if (!invalidUrls.contains(url))
- invalidUrls.append(url);
- //The bookmark is invalid then we set to false the EnabledRole
- setData(index, false, EnabledRole);
- } else {
- //The bookmark is valid then we set to true the EnabledRole
- setData(index, true, EnabledRole);
- }
-
- // Make sure that we have at least 32x32 images
- const QSize size = newIcon.actualSize(QSize(32,32));
- if (size.width() < 32) {
- QPixmap smallPixmap = newIcon.pixmap(QSize(32, 32));
- newIcon.addPixmap(smallPixmap.scaledToWidth(32, Qt::SmoothTransformation));
- }
-
- if (index.data().toString() != newName)
- setData(index, newName);
- QIcon oldIcon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
- if (oldIcon.cacheKey() != newIcon.cacheKey())
- setData(index, newIcon, Qt::DecorationRole);
- }
-}
-
-void QUrlModel::setUrls(const QList<QUrl> &list)
-{
- removeRows(0, rowCount());
- invalidUrls.clear();
- watching.clear();
- addUrls(list, 0);
-}
-
-/*!
- Add urls \a list into the list at \a row. If move then movie
- existing ones to row.
-
- \sa dropMimeData()
-*/
-void QUrlModel::addUrls(const QList<QUrl> &list, int row, bool move)
-{
- if (row == -1)
- row = rowCount();
- row = qMin(row, rowCount());
- for (int i = list.count() - 1; i >= 0; --i) {
- QUrl url = list.at(i);
- if (!url.isValid() || url.scheme() != QLatin1String("file"))
- continue;
- //this makes sure the url is clean
- const QString cleanUrl = QDir::cleanPath(url.toLocalFile());
- url = QUrl::fromLocalFile(cleanUrl);
-
- for (int j = 0; move && j < rowCount(); ++j) {
- QString local = index(j, 0).data(UrlRole).toUrl().toLocalFile();
-#if defined(Q_OS_WIN)
- if (index(j, 0).data(UrlRole).toUrl().toLocalFile().toLower() == cleanUrl.toLower()) {
-#else
- if (index(j, 0).data(UrlRole).toUrl().toLocalFile() == cleanUrl) {
-#endif
- removeRow(j);
- if (j <= row)
- row--;
- break;
- }
- }
- row = qMax(row, 0);
- QModelIndex idx = fileSystemModel->index(cleanUrl);
- if (!fileSystemModel->isDir(idx))
- continue;
- insertRows(row, 1);
- setUrl(index(row, 0), url, idx);
- watching.append(qMakePair(idx, cleanUrl));
- }
-}
-
-/*!
- Return the complete list of urls in a QList.
-*/
-QList<QUrl> QUrlModel::urls() const
-{
- QList<QUrl> list;
- for (int i = 0; i < rowCount(); ++i)
- list.append(data(index(i, 0), UrlRole).toUrl());
- return list;
-}
-
-/*!
- QFileSystemModel to get index's from, clears existing rows
-*/
-void QUrlModel::setFileSystemModel(QFileSystemModel *model)
-{
- if (model == fileSystemModel)
- return;
- if (fileSystemModel != 0) {
- disconnect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex)));
- disconnect(model, SIGNAL(layoutChanged()),
- this, SLOT(layoutChanged()));
- disconnect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(layoutChanged()));
- }
- fileSystemModel = model;
- if (fileSystemModel != 0) {
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(layoutChanged()),
- this, SLOT(layoutChanged()));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(layoutChanged()));
- }
- clear();
- insertColumns(0, 1);
-}
-
-/*
- If one of the index's we are watching has changed update our internal data
-*/
-void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- QModelIndex parent = topLeft.parent();
- for (int i = 0; i < watching.count(); ++i) {
- QModelIndex index = watching.at(i).first;
- if (index.model() && topLeft.model()) {
- Q_ASSERT(index.model() == topLeft.model());
- }
- if ( index.row() >= topLeft.row()
- && index.row() <= bottomRight.row()
- && index.column() >= topLeft.column()
- && index.column() <= bottomRight.column()
- && index.parent() == parent) {
- changed(watching.at(i).second);
- }
- }
-}
-
-/*!
- Re-get all of our data, anything could have changed!
- */
-void QUrlModel::layoutChanged()
-{
- QStringList paths;
- for (int i = 0; i < watching.count(); ++i)
- paths.append(watching.at(i).second);
- watching.clear();
- for (int i = 0; i < paths.count(); ++i) {
- QString path = paths.at(i);
- QModelIndex newIndex = fileSystemModel->index(path);
- watching.append(QPair<QModelIndex, QString>(newIndex, path));
- if (newIndex.isValid())
- changed(path);
- }
-}
-
-/*!
- The following path changed data update our copy of that data
-
- \sa layoutChanged() dataChanged()
-*/
-void QUrlModel::changed(const QString &path)
-{
- for (int i = 0; i < rowCount(); ++i) {
- QModelIndex idx = index(i, 0);
- if (idx.data(UrlRole).toUrl().toLocalFile() == path) {
- setData(idx, idx.data(UrlRole).toUrl());
- }
- }
-}
-
-QSidebar::QSidebar(QWidget *parent) : QListView(parent)
-{
-}
-
-void QSidebar::init(QFileSystemModel *model, const QList<QUrl> &newUrls)
-{
- // ### TODO make icon size dynamic
- setIconSize(QSize(24,24));
- setUniformItemSizes(true);
- urlModel = new QUrlModel(this);
- urlModel->setFileSystemModel(model);
- setModel(urlModel);
- setItemDelegate(new QSideBarDelegate(this));
-
- connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(clicked(QModelIndex)));
-#ifndef QT_NO_DRAGANDDROP
- setDragDropMode(QAbstractItemView::DragDrop);
-#endif
- setContextMenuPolicy(Qt::CustomContextMenu);
- connect(this, SIGNAL(customContextMenuRequested(QPoint)),
- this, SLOT(showContextMenu(QPoint)));
- urlModel->setUrls(newUrls);
- setCurrentIndex(this->model()->index(0,0));
-}
-
-QSidebar::~QSidebar()
-{
-}
-
-#ifndef QT_NO_DRAGANDDROP
-void QSidebar::dragEnterEvent(QDragEnterEvent *event)
-{
- if (urlModel->canDrop(event))
- QListView::dragEnterEvent(event);
-}
-#endif // QT_NO_DRAGANDDROP
-
-QSize QSidebar::sizeHint() const
-{
- if (model())
- return QListView::sizeHintForIndex(model()->index(0, 0)) + QSize(2 * frameWidth(), 2 * frameWidth());
- return QListView::sizeHint();
-}
-
-void QSidebar::selectUrl(const QUrl &url)
-{
- disconnect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(clicked(QModelIndex)));
-
- selectionModel()->clear();
- for (int i = 0; i < model()->rowCount(); ++i) {
- if (model()->index(i, 0).data(QUrlModel::UrlRole).toUrl() == url) {
- selectionModel()->select(model()->index(i, 0), QItemSelectionModel::Select);
- break;
- }
- }
-
- connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(clicked(QModelIndex)));
-}
-
-#ifndef QT_NO_MENU
-/*!
- \internal
-
- \sa removeEntry()
-*/
-void QSidebar::showContextMenu(const QPoint &position)
-{
- QList<QAction *> actions;
- if (indexAt(position).isValid()) {
- QAction *action = new QAction(QFileDialog::tr("Remove"), this);
- if (indexAt(position).data(QUrlModel::UrlRole).toUrl().path().isEmpty())
- action->setEnabled(false);
- connect(action, SIGNAL(triggered()), this, SLOT(removeEntry()));
- actions.append(action);
- }
- if (actions.count() > 0)
- QMenu::exec(actions, mapToGlobal(position));
-}
-#endif // QT_NO_MENU
-
-/*!
- \internal
-
- \sa showContextMenu()
-*/
-void QSidebar::removeEntry()
-{
- QList<QModelIndex> idxs = selectionModel()->selectedIndexes();
- QList<QPersistentModelIndex> indexes;
- for (int i = 0; i < idxs.count(); i++)
- indexes.append(idxs.at(i));
-
- for (int i = 0; i < indexes.count(); ++i)
- if (!indexes.at(i).data(QUrlModel::UrlRole).toUrl().path().isEmpty())
- model()->removeRow(indexes.at(i).row());
-}
-
-/*!
- \internal
-
- \sa goToUrl()
-*/
-void QSidebar::clicked(const QModelIndex &index)
-{
- QUrl url = model()->index(index.row(), 0).data(QUrlModel::UrlRole).toUrl();
- emit goToUrl(url);
- selectUrl(url);
-}
-
-/*!
- \reimp
- Don't automatically select something
- */
-void QSidebar::focusInEvent(QFocusEvent *event)
-{
- QAbstractScrollArea::focusInEvent(event);
- viewport()->update();
-}
-
-/*!
- \reimp
- */
-bool QSidebar::event(QEvent * event)
-{
- if (event->type() == QEvent::KeyRelease) {
- QKeyEvent* ke = (QKeyEvent*) event;
- if (ke->key() == Qt::Key_Delete) {
- removeEntry();
- return true;
- }
- }
- return QListView::event(event);
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qsidebar_p.h b/src/gui/dialogs/qsidebar_p.h
deleted file mode 100644
index 188f4d7f0f..0000000000
--- a/src/gui/dialogs/qsidebar_p.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************************
-**
-** 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 QSIDEBAR_H
-#define QSIDEBAR_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qlistwidget.h>
-#include <qstandarditemmodel.h>
-#include <qstyleditemdelegate.h>
-#include <qurl.h>
-
-#ifndef QT_NO_FILEDIALOG
-
-QT_BEGIN_NAMESPACE
-
-class QFileSystemModel;
-
-class QSideBarDelegate : public QStyledItemDelegate
-{
- public:
- QSideBarDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) {}
- void initStyleOption(QStyleOptionViewItem *option,
- const QModelIndex &index) const;
-};
-
-class Q_AUTOTEST_EXPORT QUrlModel : public QStandardItemModel
-{
- Q_OBJECT
-
-public:
- enum Roles {
- UrlRole = Qt::UserRole + 1,
- EnabledRole = Qt::UserRole + 2
- };
-
- QUrlModel(QObject *parent = 0);
-
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
-#ifndef QT_NO_DRAGANDDROP
- bool canDrop(QDragEnterEvent *event);
- bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
-#endif
- Qt::ItemFlags flags(const QModelIndex &index) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole);
-
- void setUrls(const QList<QUrl> &list);
- void addUrls(const QList<QUrl> &urls, int row = -1, bool move = true);
- QList<QUrl> urls() const;
- void setFileSystemModel(QFileSystemModel *model);
- bool showFullPath;
-
-private Q_SLOTS:
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void layoutChanged();
-
-private:
- void setUrl(const QModelIndex &index, const QUrl &url, const QModelIndex &dirIndex);
- void changed(const QString &path);
- void addIndexToWatch(const QString &path, const QModelIndex &index);
- QFileSystemModel *fileSystemModel;
- QList<QPair<QModelIndex, QString> > watching;
- QList<QUrl> invalidUrls;
-};
-
-class Q_AUTOTEST_EXPORT QSidebar : public QListView
-{
- Q_OBJECT
-
-Q_SIGNALS:
- void goToUrl(const QUrl &url);
-
-public:
- QSidebar(QWidget *parent = 0);
- void init(QFileSystemModel *model, const QList<QUrl> &newUrls);
- ~QSidebar();
-
- QSize sizeHint() const;
-
- void setUrls(const QList<QUrl> &list) { urlModel->setUrls(list); }
- void addUrls(const QList<QUrl> &list, int row) { urlModel->addUrls(list, row); }
- QList<QUrl> urls() const { return urlModel->urls(); }
-
- void selectUrl(const QUrl &url);
-
-protected:
- bool event(QEvent * e);
- void focusInEvent(QFocusEvent *event);
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QDragEnterEvent *event);
-#endif
-
-private Q_SLOTS:
- void clicked(const QModelIndex &index);
-#ifndef QT_NO_MENU
- void showContextMenu(const QPoint &position);
-#endif
- void removeEntry();
-
-private:
- QUrlModel *urlModel;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_FILEDIALOG
-
-#endif // QSIDEBAR_H
-
diff --git a/src/gui/dialogs/qwizard.cpp b/src/gui/dialogs/qwizard.cpp
deleted file mode 100644
index ce5118f91d..0000000000
--- a/src/gui/dialogs/qwizard.cpp
+++ /dev/null
@@ -1,3928 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwizard.h"
-
-#ifndef QT_NO_WIZARD
-
-#include "qabstractspinbox.h"
-#include "qalgorithms.h"
-#include "qapplication.h"
-#include "qboxlayout.h"
-#include "qlayoutitem.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qframe.h"
-#include "qlabel.h"
-#include "qlineedit.h"
-#include "qpainter.h"
-#include "qpushbutton.h"
-#include "qset.h"
-#include "qstyle.h"
-#include "qvarlengtharray.h"
-#if defined(Q_WS_MAC)
-#include "private/qt_mac_p.h"
-#include "qlibrary.h"
-#elif !defined(QT_NO_STYLE_WINDOWSVISTA)
-#include "qwizard_win_p.h"
-#include "qtimer.h"
-#endif
-
-#include "private/qdialog_p.h"
-#include <qdebug.h>
-
-#ifdef Q_WS_WINCE
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wce.cpp
-#endif
-
-#include <string.h> // for memset()
-
-#ifdef QT_SOFTKEYS_ENABLED
-#include "qaction.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// These fudge terms were needed a few places to obtain pixel-perfect results
-const int GapBetweenLogoAndRightEdge = 5;
-const int ModernHeaderTopMargin = 2;
-const int ClassicHMargin = 4;
-const int MacButtonTopMargin = 13;
-const int MacLayoutLeftMargin = 20;
-//const int MacLayoutTopMargin = 14; // Unused. Save some space and avoid warning.
-const int MacLayoutRightMargin = 20;
-const int MacLayoutBottomMargin = 17;
-
-static void changeSpacerSize(QLayout *layout, int index, int width, int height)
-{
- QSpacerItem *spacer = layout->itemAt(index)->spacerItem();
- if (!spacer)
- return;
- spacer->changeSize(width, height);
-}
-
-static QWidget *iWantTheFocus(QWidget *ancestor)
-{
- const int MaxIterations = 100;
-
- QWidget *candidate = ancestor;
- for (int i = 0; i < MaxIterations; ++i) {
- candidate = candidate->nextInFocusChain();
- if (!candidate)
- break;
-
- if (candidate->focusPolicy() & Qt::TabFocus) {
- if (candidate != ancestor && ancestor->isAncestorOf(candidate))
- return candidate;
- }
- }
- return 0;
-}
-
-static bool objectInheritsXAndXIsCloserThanY(const QObject *object, const QByteArray &classX,
- const QByteArray &classY)
-{
- const QMetaObject *metaObject = object->metaObject();
- while (metaObject) {
- if (metaObject->className() == classX)
- return true;
- if (metaObject->className() == classY)
- return false;
- metaObject = metaObject->superClass();
- }
- return false;
-}
-
-const int NFallbackDefaultProperties = 7;
-
-const struct {
- const char *className;
- const char *property;
- const char *changedSignal;
-} fallbackProperties[NFallbackDefaultProperties] = {
- // If you modify this list, make sure to update the documentation (and the auto test)
- { "QAbstractButton", "checked", SIGNAL(toggled(bool)) },
- { "QAbstractSlider", "value", SIGNAL(valueChanged(int)) },
- { "QComboBox", "currentIndex", SIGNAL(currentIndexChanged(int)) },
- { "QDateTimeEdit", "dateTime", SIGNAL(dateTimeChanged(QDateTime)) },
- { "QLineEdit", "text", SIGNAL(textChanged(QString)) },
- { "QListWidget", "currentRow", SIGNAL(currentRowChanged(int)) },
- { "QSpinBox", "value", SIGNAL(valueChanged(int)) }
-};
-
-class QWizardDefaultProperty
-{
-public:
- QByteArray className;
- QByteArray property;
- QByteArray changedSignal;
-
- inline QWizardDefaultProperty() {}
- inline QWizardDefaultProperty(const char *className, const char *property,
- const char *changedSignal)
- : className(className), property(property), changedSignal(changedSignal) {}
-};
-
-class QWizardField
-{
-public:
- inline QWizardField() {}
- QWizardField(QWizardPage *page, const QString &spec, QObject *object, const char *property,
- const char *changedSignal);
-
- void resolve(const QVector<QWizardDefaultProperty> &defaultPropertyTable);
- void findProperty(const QWizardDefaultProperty *properties, int propertyCount);
-
- QWizardPage *page;
- QString name;
- bool mandatory;
- QObject *object;
- QByteArray property;
- QByteArray changedSignal;
- QVariant initialValue;
-};
-
-QWizardField::QWizardField(QWizardPage *page, const QString &spec, QObject *object,
- const char *property, const char *changedSignal)
- : page(page), name(spec), mandatory(false), object(object), property(property),
- changedSignal(changedSignal)
-{
- if (name.endsWith(QLatin1Char('*'))) {
- name.chop(1);
- mandatory = true;
- }
-}
-
-void QWizardField::resolve(const QVector<QWizardDefaultProperty> &defaultPropertyTable)
-{
- if (property.isEmpty())
- findProperty(defaultPropertyTable.constData(), defaultPropertyTable.count());
- initialValue = object->property(property);
-}
-
-void QWizardField::findProperty(const QWizardDefaultProperty *properties, int propertyCount)
-{
- QByteArray className;
-
- for (int i = 0; i < propertyCount; ++i) {
- if (objectInheritsXAndXIsCloserThanY(object, properties[i].className, className)) {
- className = properties[i].className;
- property = properties[i].property;
- changedSignal = properties[i].changedSignal;
- }
- }
-}
-
-class QWizardLayoutInfo
-{
-public:
- inline QWizardLayoutInfo()
- : topLevelMarginLeft(-1), topLevelMarginRight(-1), topLevelMarginTop(-1),
- topLevelMarginBottom(-1), childMarginLeft(-1), childMarginRight(-1),
- childMarginTop(-1), childMarginBottom(-1), hspacing(-1), vspacing(-1),
- wizStyle(QWizard::ClassicStyle), header(false), watermark(false), title(false),
- subTitle(false), extension(false), sideWidget(false) {}
-
- int topLevelMarginLeft;
- int topLevelMarginRight;
- int topLevelMarginTop;
- int topLevelMarginBottom;
- int childMarginLeft;
- int childMarginRight;
- int childMarginTop;
- int childMarginBottom;
- int hspacing;
- int vspacing;
- int buttonSpacing;
- QWizard::WizardStyle wizStyle;
- bool header;
- bool watermark;
- bool title;
- bool subTitle;
- bool extension;
- bool sideWidget;
-
- bool operator==(const QWizardLayoutInfo &other);
- inline bool operator!=(const QWizardLayoutInfo &other) { return !operator==(other); }
-};
-
-bool QWizardLayoutInfo::operator==(const QWizardLayoutInfo &other)
-{
- return topLevelMarginLeft == other.topLevelMarginLeft
- && topLevelMarginRight == other.topLevelMarginRight
- && topLevelMarginTop == other.topLevelMarginTop
- && topLevelMarginBottom == other.topLevelMarginBottom
- && childMarginLeft == other.childMarginLeft
- && childMarginRight == other.childMarginRight
- && childMarginTop == other.childMarginTop
- && childMarginBottom == other.childMarginBottom
- && hspacing == other.hspacing
- && vspacing == other.vspacing
- && buttonSpacing == other.buttonSpacing
- && wizStyle == other.wizStyle
- && header == other.header
- && watermark == other.watermark
- && title == other.title
- && subTitle == other.subTitle
- && extension == other.extension
- && sideWidget == other.sideWidget;
-}
-
-class QWizardHeader : public QWidget
-{
-public:
- enum RulerType { Ruler };
-
- inline QWizardHeader(RulerType /* ruler */, QWidget *parent = 0)
- : QWidget(parent) { setFixedHeight(2); }
- QWizardHeader(QWidget *parent = 0);
-
- void setup(const QWizardLayoutInfo &info, const QString &title,
- const QString &subTitle, const QPixmap &logo, const QPixmap &banner,
- Qt::TextFormat titleFormat, Qt::TextFormat subTitleFormat);
-
-protected:
- void paintEvent(QPaintEvent *event);
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-private:
- bool vistaDisabled() const;
-#endif
-private:
- QLabel *titleLabel;
- QLabel *subTitleLabel;
- QLabel *logoLabel;
- QGridLayout *layout;
- QPixmap bannerPixmap;
-};
-
-QWizardHeader::QWizardHeader(QWidget *parent)
- : QWidget(parent)
-{
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
- setBackgroundRole(QPalette::Base);
-
- titleLabel = new QLabel(this);
- titleLabel->setBackgroundRole(QPalette::Base);
-
- subTitleLabel = new QLabel(this);
- subTitleLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);
- subTitleLabel->setWordWrap(true);
-
- logoLabel = new QLabel(this);
-
- QFont font = titleLabel->font();
- font.setBold(true);
- titleLabel->setFont(font);
-
- layout = new QGridLayout(this);
- layout->setMargin(0);
- layout->setSpacing(0);
-
- layout->setRowMinimumHeight(3, 1);
- layout->setRowStretch(4, 1);
-
- layout->setColumnStretch(2, 1);
- layout->setColumnMinimumWidth(4, 2 * GapBetweenLogoAndRightEdge);
- layout->setColumnMinimumWidth(6, GapBetweenLogoAndRightEdge);
-
- layout->addWidget(titleLabel, 2, 1, 1, 2);
- layout->addWidget(subTitleLabel, 4, 2);
- layout->addWidget(logoLabel, 1, 5, 5, 1);
-}
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-bool QWizardHeader::vistaDisabled() const
-{
- bool styleDisabled = false;
- QWizard *wiz = parentWidget() ? qobject_cast <QWizard *>(parentWidget()->parentWidget()) : 0;
- if (wiz) {
- // Designer dosen't support the Vista style for Wizards. This property is used to turn
- // off the Vista style.
- const QVariant v = wiz->property("_q_wizard_vista_off");
- styleDisabled = v.isValid() && v.toBool();
- }
- return styleDisabled;
-}
-#endif
-
-void QWizardHeader::setup(const QWizardLayoutInfo &info, const QString &title,
- const QString &subTitle, const QPixmap &logo, const QPixmap &banner,
- Qt::TextFormat titleFormat, Qt::TextFormat subTitleFormat)
-{
- bool modern = ((info.wizStyle == QWizard::ModernStyle)
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- || ((info.wizStyle == QWizard::AeroStyle
- && QVistaHelper::vistaState() == QVistaHelper::Classic) || vistaDisabled())
-#endif
- );
-
- layout->setRowMinimumHeight(0, modern ? ModernHeaderTopMargin : 0);
- layout->setRowMinimumHeight(1, modern ? info.topLevelMarginTop - ModernHeaderTopMargin - 1 : 0);
- layout->setRowMinimumHeight(6, (modern ? 3 : GapBetweenLogoAndRightEdge) + 2);
-
- int minColumnWidth0 = modern ? info.topLevelMarginLeft + info.topLevelMarginRight : 0;
- int minColumnWidth1 = modern ? info.topLevelMarginLeft + info.topLevelMarginRight + 1
- : info.topLevelMarginLeft + ClassicHMargin;
- layout->setColumnMinimumWidth(0, minColumnWidth0);
- layout->setColumnMinimumWidth(1, minColumnWidth1);
-
- titleLabel->setTextFormat(titleFormat);
- titleLabel->setText(title);
- logoLabel->setPixmap(logo);
-
- subTitleLabel->setTextFormat(subTitleFormat);
- subTitleLabel->setText(QLatin1String("Pq\nPq"));
- int desiredSubTitleHeight = subTitleLabel->sizeHint().height();
- subTitleLabel->setText(subTitle);
-
- if (modern) {
- bannerPixmap = banner;
- } else {
- bannerPixmap = QPixmap();
- }
-
- if (bannerPixmap.isNull()) {
- /*
- There is no widthForHeight() function, so we simulate it with a loop.
- */
- int candidateSubTitleWidth = qMin(512, 2 * QApplication::desktop()->width() / 3);
- int delta = candidateSubTitleWidth >> 1;
- while (delta > 0) {
- if (subTitleLabel->heightForWidth(candidateSubTitleWidth - delta)
- <= desiredSubTitleHeight)
- candidateSubTitleWidth -= delta;
- delta >>= 1;
- }
-
- subTitleLabel->setMinimumSize(candidateSubTitleWidth, desiredSubTitleHeight);
-
- QSize size = layout->totalMinimumSize();
- setMinimumSize(size);
- setMaximumSize(QWIDGETSIZE_MAX, size.height());
- } else {
- subTitleLabel->setMinimumSize(0, 0);
- setFixedSize(banner.size() + QSize(0, 2));
- }
- updateGeometry();
-}
-
-void QWizardHeader::paintEvent(QPaintEvent * /* event */)
-{
- QPainter painter(this);
- painter.drawPixmap(0, 0, bannerPixmap);
-
- int x = width() - 2;
- int y = height() - 2;
- const QPalette &pal = palette();
- painter.setPen(pal.mid().color());
- painter.drawLine(0, y, x, y);
- painter.setPen(pal.base().color());
- painter.drawPoint(x + 1, y);
- painter.drawLine(0, y + 1, x + 1, y + 1);
-}
-
-// We save one vtable by basing QWizardRuler on QWizardHeader
-class QWizardRuler : public QWizardHeader
-{
-public:
- inline QWizardRuler(QWidget *parent = 0)
- : QWizardHeader(Ruler, parent) {}
-};
-
-class QWatermarkLabel : public QLabel
-{
-public:
- QWatermarkLabel(QWidget *parent, QWidget *sideWidget) : QLabel(parent), m_sideWidget(sideWidget) {
- m_layout = new QVBoxLayout(this);
- if (m_sideWidget)
- m_layout->addWidget(m_sideWidget);
- }
-
- QSize minimumSizeHint() const {
- if (!pixmap() && !pixmap()->isNull())
- return pixmap()->size();
- return QFrame::minimumSizeHint();
- }
-
- void setSideWidget(QWidget *widget) {
- if (m_sideWidget == widget)
- return;
- if (m_sideWidget) {
- m_layout->removeWidget(m_sideWidget);
- m_sideWidget->hide();
- }
- m_sideWidget = widget;
- if (m_sideWidget)
- m_layout->addWidget(m_sideWidget);
- }
- QWidget *sideWidget() const {
- return m_sideWidget;
- }
-private:
- QVBoxLayout *m_layout;
- QWidget *m_sideWidget;
-};
-
-class QWizardPagePrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QWizardPage)
-
-public:
- enum TriState { Tri_Unknown = -1, Tri_False, Tri_True };
-
- inline QWizardPagePrivate()
- : wizard(0), completeState(Tri_Unknown), explicitlyFinal(false), commit(false) {}
-
- bool cachedIsComplete() const;
- void _q_maybeEmitCompleteChanged();
- void _q_updateCachedCompleteState();
-
- QWizard *wizard;
- QString title;
- QString subTitle;
- QPixmap pixmaps[QWizard::NPixmaps];
- QVector<QWizardField> pendingFields;
- mutable TriState completeState;
- bool explicitlyFinal;
- bool commit;
- QMap<int, QString> buttonCustomTexts;
-};
-
-bool QWizardPagePrivate::cachedIsComplete() const
-{
- Q_Q(const QWizardPage);
- if (completeState == Tri_Unknown)
- completeState = q->isComplete() ? Tri_True : Tri_False;
- return completeState == Tri_True;
-}
-
-void QWizardPagePrivate::_q_maybeEmitCompleteChanged()
-{
- Q_Q(QWizardPage);
- TriState newState = q->isComplete() ? Tri_True : Tri_False;
- if (newState != completeState)
- emit q->completeChanged();
-}
-
-void QWizardPagePrivate::_q_updateCachedCompleteState()
-{
- Q_Q(QWizardPage);
- completeState = q->isComplete() ? Tri_True : Tri_False;
-}
-
-class QWizardAntiFlickerWidget : public QWidget
-{
- QWizard *wizard;
- QWizardPrivate *wizardPrivate;
-public:
- QWizardAntiFlickerWidget(QWizard *wizard, QWizardPrivate *wizardPrivate)
- : QWidget(wizard)
- , wizard(wizard)
- , wizardPrivate(wizardPrivate) {}
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-protected:
- void paintEvent(QPaintEvent *);
-#endif
-};
-
-class QWizardPrivate : public QDialogPrivate
-{
- Q_DECLARE_PUBLIC(QWizard)
-
-public:
- typedef QMap<int, QWizardPage *> PageMap;
-
- enum Direction {
- Backward,
- Forward
- };
-
- inline QWizardPrivate()
- : start(-1)
- , startSetByUser(false)
- , current(-1)
- , canContinue(false)
- , canFinish(false)
- , disableUpdatesCount(0)
- , opts(0)
- , buttonsHaveCustomLayout(false)
- , titleFmt(Qt::AutoText)
- , subTitleFmt(Qt::AutoText)
- , placeholderWidget1(0)
- , placeholderWidget2(0)
- , headerWidget(0)
- , watermarkLabel(0)
- , sideWidget(0)
- , titleLabel(0)
- , subTitleLabel(0)
- , bottomRuler(0)
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- , vistaInitPending(false)
- , vistaState(QVistaHelper::Dirty)
- , vistaStateChanged(false)
- , inHandleAeroStyleChange(false)
-#endif
- , minimumWidth(0)
- , minimumHeight(0)
- , maximumWidth(QWIDGETSIZE_MAX)
- , maximumHeight(QWIDGETSIZE_MAX)
- {
- for (int i = 0; i < QWizard::NButtons; ++i) {
- btns[i] = 0;
-#ifdef QT_SOFTKEYS_ENABLED
- softKeys[i] = 0;
-#endif
- }
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
- vistaInitPending = true;
-#endif
- }
-
- void init();
- void reset();
- void cleanupPagesNotInHistory();
- void addField(const QWizardField &field);
- void removeFieldAt(int index);
- void switchToPage(int newId, Direction direction);
- QWizardLayoutInfo layoutInfoForCurrentPage();
- void recreateLayout(const QWizardLayoutInfo &info);
- void updateLayout();
- void updateMinMaxSizes(const QWizardLayoutInfo &info);
- void updateCurrentPage();
- bool ensureButton(QWizard::WizardButton which) const;
- void connectButton(QWizard::WizardButton which) const;
- void updateButtonTexts();
- void updateButtonLayout();
- void setButtonLayout(const QWizard::WizardButton *array, int size);
- bool buttonLayoutContains(QWizard::WizardButton which);
- void updatePixmap(QWizard::WizardPixmap which);
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- bool vistaDisabled() const;
- bool isVistaThemeEnabled(QVistaHelper::VistaState state) const;
- void handleAeroStyleChange();
-#endif
- bool isVistaThemeEnabled() const;
- void disableUpdates();
- void enableUpdates();
- void _q_emitCustomButtonClicked();
- void _q_updateButtonStates();
- void _q_handleFieldObjectDestroyed(QObject *);
- void setStyle(QStyle *style);
-#ifdef Q_WS_MAC
- static QPixmap findDefaultBackgroundPixmap();
-#endif
-
- PageMap pageMap;
- QVector<QWizardField> fields;
- QMap<QString, int> fieldIndexMap;
- QVector<QWizardDefaultProperty> defaultPropertyTable;
- QList<int> history;
- QSet<int> initialized; // ### remove and move bit to QWizardPage?
- int start;
- bool startSetByUser;
- int current;
- bool canContinue;
- bool canFinish;
- QWizardLayoutInfo layoutInfo;
- int disableUpdatesCount;
-
- QWizard::WizardStyle wizStyle;
- QWizard::WizardOptions opts;
- QMap<int, QString> buttonCustomTexts;
- bool buttonsHaveCustomLayout;
- QList<QWizard::WizardButton> buttonsCustomLayout;
- Qt::TextFormat titleFmt;
- Qt::TextFormat subTitleFmt;
- mutable QPixmap defaultPixmaps[QWizard::NPixmaps];
-
- union {
- // keep in sync with QWizard::WizardButton
- mutable struct {
- QAbstractButton *back;
- QAbstractButton *next;
- QAbstractButton *commit;
- QAbstractButton *finish;
- QAbstractButton *cancel;
- QAbstractButton *help;
- } btn;
- mutable QAbstractButton *btns[QWizard::NButtons];
- };
- QWizardAntiFlickerWidget *antiFlickerWidget;
- QWidget *placeholderWidget1;
- QWidget *placeholderWidget2;
- QWizardHeader *headerWidget;
- QWatermarkLabel *watermarkLabel;
- QWidget *sideWidget;
- QFrame *pageFrame;
- QLabel *titleLabel;
- QLabel *subTitleLabel;
- QWizardRuler *bottomRuler;
-#ifdef QT_SOFTKEYS_ENABLED
- mutable QAction *softKeys[QWizard::NButtons];
-#endif
-
- QVBoxLayout *pageVBoxLayout;
- QHBoxLayout *buttonLayout;
- QGridLayout *mainLayout;
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- QVistaHelper *vistaHelper;
- bool vistaInitPending;
- QVistaHelper::VistaState vistaState;
- bool vistaStateChanged;
- bool inHandleAeroStyleChange;
-#endif
- int minimumWidth;
- int minimumHeight;
- int maximumWidth;
- int maximumHeight;
-};
-
-static QString buttonDefaultText(int wstyle, int which, const QWizardPrivate *wizardPrivate)
-{
-#if defined(QT_NO_STYLE_WINDOWSVISTA)
- Q_UNUSED(wizardPrivate);
-#endif
- const bool macStyle = (wstyle == QWizard::MacStyle);
- switch (which) {
- case QWizard::BackButton:
- return macStyle ? QWizard::tr("Go Back") : QWizard::tr("< &Back");
- case QWizard::NextButton:
- if (macStyle)
- return QWizard::tr("Continue");
- else
- return wizardPrivate->isVistaThemeEnabled()
- ? QWizard::tr("&Next") : QWizard::tr("&Next >");
- case QWizard::CommitButton:
- return QWizard::tr("Commit");
- case QWizard::FinishButton:
- return macStyle ? QWizard::tr("Done") : QWizard::tr("&Finish");
- case QWizard::CancelButton:
- return QWizard::tr("Cancel");
- case QWizard::HelpButton:
- return macStyle ? QWizard::tr("Help") : QWizard::tr("&Help");
- default:
- return QString();
- }
-}
-
-void QWizardPrivate::init()
-{
- Q_Q(QWizard);
-
- antiFlickerWidget = new QWizardAntiFlickerWidget(q, this);
- wizStyle = QWizard::WizardStyle(q->style()->styleHint(QStyle::SH_WizardStyle, 0, q));
- if (wizStyle == QWizard::MacStyle) {
- opts = (QWizard::NoDefaultButton | QWizard::NoCancelButton);
- } else if (wizStyle == QWizard::ModernStyle) {
- opts = QWizard::HelpButtonOnRight;
- }
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- vistaHelper = new QVistaHelper(q);
-#endif
-
- // create these buttons right away; create the other buttons as necessary
- ensureButton(QWizard::BackButton);
- ensureButton(QWizard::NextButton);
- ensureButton(QWizard::CommitButton);
- ensureButton(QWizard::FinishButton);
-
- pageFrame = new QFrame(antiFlickerWidget);
- pageFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
-
- pageVBoxLayout = new QVBoxLayout(pageFrame);
- pageVBoxLayout->setSpacing(0);
- pageVBoxLayout->addSpacing(0);
- QSpacerItem *spacerItem = new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding);
- pageVBoxLayout->addItem(spacerItem);
-
- buttonLayout = new QHBoxLayout;
- mainLayout = new QGridLayout(antiFlickerWidget);
- mainLayout->setSizeConstraint(QLayout::SetNoConstraint);
-
- updateButtonLayout();
-
- for (int i = 0; i < NFallbackDefaultProperties; ++i)
- defaultPropertyTable.append(QWizardDefaultProperty(fallbackProperties[i].className,
- fallbackProperties[i].property,
- fallbackProperties[i].changedSignal));
-}
-
-void QWizardPrivate::reset()
-{
- Q_Q(QWizard);
- if (current != -1) {
- q->currentPage()->hide();
- cleanupPagesNotInHistory();
- for (int i = history.count() - 1; i >= 0; --i)
- q->cleanupPage(history.at(i));
- history.clear();
- initialized.clear();
-
- current = -1;
- emit q->currentIdChanged(-1);
- }
-}
-
-void QWizardPrivate::cleanupPagesNotInHistory()
-{
- Q_Q(QWizard);
-
- const QSet<int> original = initialized;
- QSet<int>::const_iterator i = original.constBegin();
- QSet<int>::const_iterator end = original.constEnd();
-
- for (; i != end; ++i) {
- if (!history.contains(*i)) {
- q->cleanupPage(*i);
- initialized.remove(*i);
- }
- }
-}
-
-void QWizardPrivate::addField(const QWizardField &field)
-{
- Q_Q(QWizard);
-
- QWizardField myField = field;
- myField.resolve(defaultPropertyTable);
-
- if (fieldIndexMap.contains(myField.name)) {
- qWarning("QWizardPage::addField: Duplicate field '%s'", qPrintable(myField.name));
- return;
- }
-
- fieldIndexMap.insert(myField.name, fields.count());
- fields += myField;
- if (myField.mandatory && !myField.changedSignal.isEmpty())
- QObject::connect(myField.object, myField.changedSignal,
- myField.page, SLOT(_q_maybeEmitCompleteChanged()));
- QObject::connect(
- myField.object, SIGNAL(destroyed(QObject*)), q,
- SLOT(_q_handleFieldObjectDestroyed(QObject*)));
-}
-
-void QWizardPrivate::removeFieldAt(int index)
-{
- Q_Q(QWizard);
-
- const QWizardField &field = fields.at(index);
- fieldIndexMap.remove(field.name);
- if (field.mandatory && !field.changedSignal.isEmpty())
- QObject::disconnect(field.object, field.changedSignal,
- field.page, SLOT(_q_maybeEmitCompleteChanged()));
- QObject::disconnect(
- field.object, SIGNAL(destroyed(QObject*)), q,
- SLOT(_q_handleFieldObjectDestroyed(QObject*)));
- fields.remove(index);
-}
-
-void QWizardPrivate::switchToPage(int newId, Direction direction)
-{
- Q_Q(QWizard);
-
- disableUpdates();
-
- int oldId = current;
- if (QWizardPage *oldPage = q->currentPage()) {
- oldPage->hide();
-
- if (direction == Backward) {
- if (!(opts & QWizard::IndependentPages)) {
- q->cleanupPage(oldId);
- initialized.remove(oldId);
- }
- Q_ASSERT(history.last() == oldId);
- history.removeLast();
- Q_ASSERT(history.last() == newId);
- }
- }
-
- current = newId;
-
- QWizardPage *newPage = q->currentPage();
- if (newPage) {
- if (direction == Forward) {
- if (!initialized.contains(current)) {
- initialized.insert(current);
- q->initializePage(current);
- }
- history.append(current);
- }
- newPage->show();
- }
-
- canContinue = (q->nextId() != -1);
- canFinish = (newPage && newPage->isFinalPage());
-
- _q_updateButtonStates();
- updateButtonTexts();
-
- const QWizard::WizardButton nextOrCommit =
- newPage && newPage->isCommitPage() ? QWizard::CommitButton : QWizard::NextButton;
- QAbstractButton *nextOrFinishButton =
- btns[canContinue ? nextOrCommit : QWizard::FinishButton];
- QWidget *candidate = 0;
-
- /*
- If there is no default button and the Next or Finish button
- is enabled, give focus directly to it as a convenience to the
- user. This is the normal case on Mac OS X.
-
- Otherwise, give the focus to the new page's first child that
- can handle it. If there is no such child, give the focus to
- Next or Finish.
- */
- if ((opts & QWizard::NoDefaultButton) && nextOrFinishButton->isEnabled()) {
- candidate = nextOrFinishButton;
- } else if (newPage) {
- candidate = iWantTheFocus(newPage);
- }
- if (!candidate)
- candidate = nextOrFinishButton;
- candidate->setFocus();
-
- if (wizStyle == QWizard::MacStyle)
- q->updateGeometry();
-
- enableUpdates();
- updateLayout();
-
- emit q->currentIdChanged(current);
-}
-
-// keep in sync with QWizard::WizardButton
-static const char * const buttonSlots[QWizard::NStandardButtons] = {
- SLOT(back()), SLOT(next()), SLOT(next()), SLOT(accept()), SLOT(reject()),
- SIGNAL(helpRequested())
-};
-
-QWizardLayoutInfo QWizardPrivate::layoutInfoForCurrentPage()
-{
- Q_Q(QWizard);
- QStyle *style = q->style();
-
- QWizardLayoutInfo info;
-
- const int layoutHorizontalSpacing = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing);
- info.topLevelMarginLeft = style->pixelMetric(QStyle::PM_LayoutLeftMargin, 0, q);
- info.topLevelMarginRight = style->pixelMetric(QStyle::PM_LayoutRightMargin, 0, q);
- info.topLevelMarginTop = style->pixelMetric(QStyle::PM_LayoutTopMargin, 0, q);
- info.topLevelMarginBottom = style->pixelMetric(QStyle::PM_LayoutBottomMargin, 0, q);
- info.childMarginLeft = style->pixelMetric(QStyle::PM_LayoutLeftMargin, 0, titleLabel);
- info.childMarginRight = style->pixelMetric(QStyle::PM_LayoutRightMargin, 0, titleLabel);
- info.childMarginTop = style->pixelMetric(QStyle::PM_LayoutTopMargin, 0, titleLabel);
- info.childMarginBottom = style->pixelMetric(QStyle::PM_LayoutBottomMargin, 0, titleLabel);
- info.hspacing = (layoutHorizontalSpacing == -1)
- ? style->layoutSpacing(QSizePolicy::DefaultType, QSizePolicy::DefaultType, Qt::Horizontal)
- : layoutHorizontalSpacing;
- info.vspacing = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing);
- info.buttonSpacing = (layoutHorizontalSpacing == -1)
- ? style->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal)
- : layoutHorizontalSpacing;
-
- if (wizStyle == QWizard::MacStyle)
- info.buttonSpacing = 12;
-
- info.wizStyle = wizStyle;
- if ((info.wizStyle == QWizard::AeroStyle)
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- && (QVistaHelper::vistaState() == QVistaHelper::Classic || vistaDisabled())
-#endif
- )
- info.wizStyle = QWizard::ModernStyle;
-
- QString titleText;
- QString subTitleText;
- QPixmap backgroundPixmap;
- QPixmap watermarkPixmap;
-
- if (QWizardPage *page = q->currentPage()) {
- titleText = page->title();
- subTitleText = page->subTitle();
- backgroundPixmap = page->pixmap(QWizard::BackgroundPixmap);
- watermarkPixmap = page->pixmap(QWizard::WatermarkPixmap);
- }
-
- info.header = (info.wizStyle == QWizard::ClassicStyle || info.wizStyle == QWizard::ModernStyle)
- && !(opts & QWizard::IgnoreSubTitles) && !subTitleText.isEmpty();
- info.sideWidget = sideWidget;
- info.watermark = (info.wizStyle != QWizard::MacStyle) && (info.wizStyle != QWizard::AeroStyle)
- && !watermarkPixmap.isNull();
- info.title = !info.header && !titleText.isEmpty();
- info.subTitle = !(opts & QWizard::IgnoreSubTitles) && !info.header && !subTitleText.isEmpty();
- info.extension = (info.watermark || info.sideWidget) && (opts & QWizard::ExtendedWatermarkPixmap);
-
- return info;
-}
-
-void QWizardPrivate::recreateLayout(const QWizardLayoutInfo &info)
-{
- Q_Q(QWizard);
-
- /*
- Start by undoing the main layout.
- */
- for (int i = mainLayout->count() - 1; i >= 0; --i) {
- QLayoutItem *item = mainLayout->takeAt(i);
- if (item->layout()) {
- item->layout()->setParent(0);
- } else {
- delete item;
- }
- }
- for (int i = mainLayout->columnCount() - 1; i >= 0; --i)
- mainLayout->setColumnMinimumWidth(i, 0);
- for (int i = mainLayout->rowCount() - 1; i >= 0; --i)
- mainLayout->setRowMinimumHeight(i, 0);
-
- /*
- Now, recreate it.
- */
-
- bool mac = (info.wizStyle == QWizard::MacStyle);
- bool classic = (info.wizStyle == QWizard::ClassicStyle);
- bool modern = (info.wizStyle == QWizard::ModernStyle);
- bool aero = (info.wizStyle == QWizard::AeroStyle);
- int deltaMarginLeft = info.topLevelMarginLeft - info.childMarginLeft;
- int deltaMarginRight = info.topLevelMarginRight - info.childMarginRight;
- int deltaMarginTop = info.topLevelMarginTop - info.childMarginTop;
- int deltaMarginBottom = info.topLevelMarginBottom - info.childMarginBottom;
- int deltaVSpacing = info.topLevelMarginBottom - info.vspacing;
-
- int row = 0;
- int numColumns;
- if (mac) {
- numColumns = 3;
- } else if (info.watermark || info.sideWidget) {
- numColumns = 2;
- } else {
- numColumns = 1;
- }
- int pageColumn = qMin(1, numColumns - 1);
-
- if (mac) {
- mainLayout->setMargin(0);
- mainLayout->setSpacing(0);
- buttonLayout->setContentsMargins(MacLayoutLeftMargin, MacButtonTopMargin, MacLayoutRightMargin, MacLayoutBottomMargin);
- pageVBoxLayout->setMargin(7);
- } else {
- if (modern) {
- mainLayout->setMargin(0);
- mainLayout->setSpacing(0);
- pageVBoxLayout->setContentsMargins(deltaMarginLeft, deltaMarginTop,
- deltaMarginRight, deltaMarginBottom);
- buttonLayout->setContentsMargins(info.topLevelMarginLeft, info.topLevelMarginTop,
- info.topLevelMarginRight, info.topLevelMarginBottom);
- } else {
- mainLayout->setContentsMargins(info.topLevelMarginLeft, info.topLevelMarginTop,
- info.topLevelMarginRight, info.topLevelMarginBottom);
- mainLayout->setHorizontalSpacing(info.hspacing);
- mainLayout->setVerticalSpacing(info.vspacing);
- pageVBoxLayout->setContentsMargins(0, 0, 0, 0);
- buttonLayout->setContentsMargins(0, 0, 0, 0);
- }
- }
- buttonLayout->setSpacing(info.buttonSpacing);
-
- if (info.header) {
- if (!headerWidget)
- headerWidget = new QWizardHeader(antiFlickerWidget);
- headerWidget->setAutoFillBackground(modern);
- mainLayout->addWidget(headerWidget, row++, 0, 1, numColumns);
- }
- if (headerWidget)
- headerWidget->setVisible(info.header);
-
- int watermarkStartRow = row;
-
- if (mac)
- mainLayout->setRowMinimumHeight(row++, 10);
-
- if (info.title) {
- if (!titleLabel) {
- titleLabel = new QLabel(antiFlickerWidget);
- titleLabel->setBackgroundRole(QPalette::Base);
- titleLabel->setWordWrap(true);
- }
-
- QFont titleFont = q->font();
- titleFont.setPointSize(titleFont.pointSize() + (mac ? 3 : 4));
- titleFont.setBold(true);
- titleLabel->setPalette(QPalette());
-
- if (aero) {
- // ### hardcoded for now:
- titleFont = QFont(QLatin1String("Segoe UI"), 12);
- QPalette pal(titleLabel->palette());
- pal.setColor(QPalette::Text, "#003399");
- titleLabel->setPalette(pal);
- }
-
- titleLabel->setFont(titleFont);
- const int aeroTitleIndent = 25; // ### hardcoded for now - should be calculated somehow
- if (aero)
- titleLabel->setIndent(aeroTitleIndent);
- else if (mac)
- titleLabel->setIndent(2);
- else if (classic)
- titleLabel->setIndent(info.childMarginLeft);
- else
- titleLabel->setIndent(info.topLevelMarginLeft);
- if (modern) {
- if (!placeholderWidget1) {
- placeholderWidget1 = new QWidget(antiFlickerWidget);
- placeholderWidget1->setBackgroundRole(QPalette::Base);
- }
- placeholderWidget1->setFixedHeight(info.topLevelMarginLeft + 2);
- mainLayout->addWidget(placeholderWidget1, row++, pageColumn);
- }
- mainLayout->addWidget(titleLabel, row++, pageColumn);
- if (modern) {
- if (!placeholderWidget2) {
- placeholderWidget2 = new QWidget(antiFlickerWidget);
- placeholderWidget2->setBackgroundRole(QPalette::Base);
- }
- placeholderWidget2->setFixedHeight(5);
- mainLayout->addWidget(placeholderWidget2, row++, pageColumn);
- }
- if (mac)
- mainLayout->setRowMinimumHeight(row++, 7);
- }
- if (placeholderWidget1)
- placeholderWidget1->setVisible(info.title && modern);
- if (placeholderWidget2)
- placeholderWidget2->setVisible(info.title && modern);
-
- if (info.subTitle) {
- if (!subTitleLabel) {
- subTitleLabel = new QLabel(pageFrame);
- subTitleLabel->setWordWrap(true);
-
- subTitleLabel->setContentsMargins(info.childMarginLeft , 0,
- info.childMarginRight , 0);
-
- pageVBoxLayout->insertWidget(1, subTitleLabel);
- }
- }
-
- // ### try to replace with margin.
- changeSpacerSize(pageVBoxLayout, 0, 0, info.subTitle ? info.childMarginLeft : 0);
-
- int hMargin = mac ? 1 : 0;
- int vMargin = hMargin;
-
- pageFrame->setFrameStyle(mac ? (QFrame::Box | QFrame::Raised) : QFrame::NoFrame);
- pageFrame->setLineWidth(0);
- pageFrame->setMidLineWidth(hMargin);
-
- if (info.header) {
- if (modern) {
- hMargin = info.topLevelMarginLeft;
- vMargin = deltaMarginBottom;
- } else if (classic) {
- hMargin = deltaMarginLeft + ClassicHMargin;
- vMargin = 0;
- }
- }
-
- if (aero) {
- int leftMargin = 18; // ### hardcoded for now - should be calculated somehow
- int topMargin = vMargin;
- int rightMargin = hMargin; // ### for now
- int bottomMargin = vMargin;
- pageFrame->setContentsMargins(leftMargin, topMargin, rightMargin, bottomMargin);
- } else {
- pageFrame->setContentsMargins(hMargin, vMargin, hMargin, vMargin);
- }
-
- if ((info.watermark || info.sideWidget) && !watermarkLabel) {
- watermarkLabel = new QWatermarkLabel(antiFlickerWidget, sideWidget);
- watermarkLabel->setBackgroundRole(QPalette::Base);
- watermarkLabel->setMinimumHeight(1);
- watermarkLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
- watermarkLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- }
-
- //bool wasSemiTransparent = pageFrame->testAttribute(Qt::WA_SetPalette);
- const bool wasSemiTransparent =
- pageFrame->palette().brush(QPalette::Window).color().alpha() < 255
- || pageFrame->palette().brush(QPalette::Base).color().alpha() < 255;
- if (mac) {
- if (!wasSemiTransparent) {
- QPalette pal = pageFrame->palette();
- pal.setBrush(QPalette::Window, QColor(255, 255, 255, 153));
- // ### The next line is required to ensure visual semitransparency when
- // ### switching from ModernStyle to MacStyle. See TAG1 below.
- pal.setBrush(QPalette::Base, QColor(255, 255, 255, 153));
- pageFrame->setPalette(pal);
- pageFrame->setAutoFillBackground(true);
- antiFlickerWidget->setAutoFillBackground(false);
- }
- } else {
- if (wasSemiTransparent)
- pageFrame->setPalette(QPalette());
-
- bool baseBackground = (modern && !info.header); // ### TAG1
- pageFrame->setBackgroundRole(baseBackground ? QPalette::Base : QPalette::Window);
-
- if (titleLabel)
- titleLabel->setAutoFillBackground(baseBackground);
- pageFrame->setAutoFillBackground(baseBackground);
- if (watermarkLabel)
- watermarkLabel->setAutoFillBackground(baseBackground);
- if (placeholderWidget1)
- placeholderWidget1->setAutoFillBackground(baseBackground);
- if (placeholderWidget2)
- placeholderWidget2->setAutoFillBackground(baseBackground);
-
- if (aero) {
- QPalette pal = pageFrame->palette();
- pal.setBrush(QPalette::Window, QColor(255, 255, 255));
- pageFrame->setPalette(pal);
- pageFrame->setAutoFillBackground(true);
- pal = antiFlickerWidget->palette();
- pal.setBrush(QPalette::Window, QColor(255, 255, 255));
- antiFlickerWidget->setPalette(pal);
- antiFlickerWidget->setAutoFillBackground(true);
- }
- }
-
- mainLayout->addWidget(pageFrame, row++, pageColumn);
-
- int watermarkEndRow = row;
- if (classic)
- mainLayout->setRowMinimumHeight(row++, deltaVSpacing);
-
- if (aero) {
- buttonLayout->setContentsMargins(9, 9, 9, 9);
- mainLayout->setContentsMargins(0, 11, 0, 0);
- }
-
- int buttonStartColumn = info.extension ? 1 : 0;
- int buttonNumColumns = info.extension ? 1 : numColumns;
-
- if (classic || modern) {
- if (!bottomRuler)
- bottomRuler = new QWizardRuler(antiFlickerWidget);
- mainLayout->addWidget(bottomRuler, row++, buttonStartColumn, 1, buttonNumColumns);
- }
-
- if (classic)
- mainLayout->setRowMinimumHeight(row++, deltaVSpacing);
-
- mainLayout->addLayout(buttonLayout, row++, buttonStartColumn, 1, buttonNumColumns);
-
- if (info.watermark || info.sideWidget) {
- if (info.extension)
- watermarkEndRow = row;
- mainLayout->addWidget(watermarkLabel, watermarkStartRow, 0,
- watermarkEndRow - watermarkStartRow, 1);
- }
-
- mainLayout->setColumnMinimumWidth(0, mac && !info.watermark ? 181 : 0);
- if (mac)
- mainLayout->setColumnMinimumWidth(2, 21);
-
- if (headerWidget)
- headerWidget->setVisible(info.header);
- if (titleLabel)
- titleLabel->setVisible(info.title);
- if (subTitleLabel)
- subTitleLabel->setVisible(info.subTitle);
- if (bottomRuler)
- bottomRuler->setVisible(classic || modern);
- if (watermarkLabel)
- watermarkLabel->setVisible(info.watermark || info.sideWidget);
-
- layoutInfo = info;
-}
-
-void QWizardPrivate::updateLayout()
-{
- Q_Q(QWizard);
-
- disableUpdates();
-
- QWizardLayoutInfo info = layoutInfoForCurrentPage();
- if (layoutInfo != info)
- recreateLayout(info);
- QWizardPage *page = q->currentPage();
-
- // If the page can expand vertically, let it stretch "infinitely" more
- // than the QSpacerItem at the bottom. Otherwise, let the QSpacerItem
- // stretch "infinitely" more than the page. Change the bottom item's
- // policy accordingly. The case that the page has no layout is basically
- // for Designer, only.
- if (page) {
- bool expandPage = !page->layout();
- if (!expandPage) {
- const QLayoutItem *pageItem = pageVBoxLayout->itemAt(pageVBoxLayout->indexOf(page));
- expandPage = pageItem->expandingDirections() & Qt::Vertical;
- }
- QSpacerItem *bottomSpacer = pageVBoxLayout->itemAt(pageVBoxLayout->count() - 1)->spacerItem();
- Q_ASSERT(bottomSpacer);
- bottomSpacer->changeSize(0, 0, QSizePolicy::Ignored, expandPage ? QSizePolicy::Ignored : QSizePolicy::MinimumExpanding);
- pageVBoxLayout->invalidate();
- }
-
- if (info.header) {
- Q_ASSERT(page);
- headerWidget->setup(info, page->title(), page->subTitle(),
- page->pixmap(QWizard::LogoPixmap), page->pixmap(QWizard::BannerPixmap),
- titleFmt, subTitleFmt);
- }
-
- if (info.watermark || info.sideWidget) {
- QPixmap pix;
- if (info.watermark) {
- if (page)
- pix = page->pixmap(QWizard::WatermarkPixmap);
- else
- pix = q->pixmap(QWizard::WatermarkPixmap);
- }
- watermarkLabel->setPixmap(pix); // in case there is no watermark and we show the side widget we need to clear the watermark
- }
-
- if (info.title) {
- Q_ASSERT(page);
- titleLabel->setTextFormat(titleFmt);
- titleLabel->setText(page->title());
- }
- if (info.subTitle) {
- Q_ASSERT(page);
- subTitleLabel->setTextFormat(subTitleFmt);
- subTitleLabel->setText(page->subTitle());
- }
-
- enableUpdates();
- updateMinMaxSizes(info);
-}
-
-void QWizardPrivate::updateMinMaxSizes(const QWizardLayoutInfo &info)
-{
- Q_Q(QWizard);
-
- int extraHeight = 0;
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (isVistaThemeEnabled())
- extraHeight = vistaHelper->titleBarSize() + vistaHelper->topOffset();
-#endif
- QSize minimumSize = mainLayout->totalMinimumSize() + QSize(0, extraHeight);
- QSize maximumSize = mainLayout->totalMaximumSize();
- if (info.header && headerWidget->maximumWidth() != QWIDGETSIZE_MAX) {
- minimumSize.setWidth(headerWidget->maximumWidth());
- maximumSize.setWidth(headerWidget->maximumWidth());
- }
- if (info.watermark && !info.sideWidget) {
- minimumSize.setHeight(mainLayout->totalSizeHint().height());
- maximumSize.setHeight(mainLayout->totalSizeHint().height());
- }
- if (q->minimumWidth() == minimumWidth) {
- minimumWidth = minimumSize.width();
- q->setMinimumWidth(minimumWidth);
- }
- if (q->minimumHeight() == minimumHeight) {
- minimumHeight = minimumSize.height();
- q->setMinimumHeight(minimumHeight);
- }
- if (q->maximumWidth() == maximumWidth) {
- maximumWidth = maximumSize.width();
- q->setMaximumWidth(maximumWidth);
- }
- if (q->maximumHeight() == maximumHeight) {
- maximumHeight = maximumSize.height();
- q->setMaximumHeight(maximumHeight);
- }
-}
-
-void QWizardPrivate::updateCurrentPage()
-{
- Q_Q(QWizard);
- if (q->currentPage()) {
- canContinue = (q->nextId() != -1);
- canFinish = q->currentPage()->isFinalPage();
- } else {
- canContinue = false;
- canFinish = false;
- }
- _q_updateButtonStates();
- updateButtonTexts();
-}
-
-bool QWizardPrivate::ensureButton(QWizard::WizardButton which) const
-{
- Q_Q(const QWizard);
- if (uint(which) >= QWizard::NButtons)
- return false;
-
- if (!btns[which]) {
- QPushButton *pushButton = new QPushButton(antiFlickerWidget);
- QStyle *style = q->style();
- if (style != QApplication::style()) // Propagate style
- pushButton->setStyle(style);
- // Make navigation buttons detectable as passive interactor in designer
- switch (which) {
- case QWizard::CommitButton:
- case QWizard::FinishButton:
- case QWizard::CancelButton:
- break;
- default: {
- QString objectName = QLatin1String("__qt__passive_wizardbutton");
- objectName += QString::number(which);
- pushButton->setObjectName(objectName);
- }
- break;
- }
-#ifdef Q_WS_MAC
- pushButton->setAutoDefault(false);
-#endif
- pushButton->hide();
-#ifdef Q_CC_HPACC
- const_cast<QWizardPrivate *>(this)->btns[which] = pushButton;
-#else
- btns[which] = pushButton;
-#endif
- if (which < QWizard::NStandardButtons)
- pushButton->setText(buttonDefaultText(wizStyle, which, this));
-
-#ifdef QT_SOFTKEYS_ENABLED
- QAction *softKey = new QAction(pushButton->text(), pushButton);
- QAction::SoftKeyRole softKeyRole;
- switch(which) {
- case QWizard::NextButton:
- case QWizard::FinishButton:
- case QWizard::CancelButton:
- softKeyRole = QAction::NegativeSoftKey;
- break;
- case QWizard::BackButton:
- case QWizard::CommitButton:
- case QWizard::HelpButton:
- case QWizard::CustomButton1:
- case QWizard::CustomButton2:
- case QWizard::CustomButton3:
- default:
- softKeyRole = QAction::PositiveSoftKey;
- break;
- }
- softKey->setSoftKeyRole(softKeyRole);
- softKeys[which] = softKey;
-#endif
- connectButton(which);
- }
- return true;
-}
-
-void QWizardPrivate::connectButton(QWizard::WizardButton which) const
-{
- Q_Q(const QWizard);
- if (which < QWizard::NStandardButtons) {
- QObject::connect(btns[which], SIGNAL(clicked()), q, buttonSlots[which]);
- } else {
- QObject::connect(btns[which], SIGNAL(clicked()), q, SLOT(_q_emitCustomButtonClicked()));
- }
-
-#ifdef QT_SOFTKEYS_ENABLED
- QObject::connect(softKeys[which], SIGNAL(triggered()), btns[which], SIGNAL(clicked()));
-#endif
-}
-
-void QWizardPrivate::updateButtonTexts()
-{
- Q_Q(QWizard);
- for (int i = 0; i < QWizard::NButtons; ++i) {
- if (btns[i]) {
- if (q->currentPage() && (q->currentPage()->d_func()->buttonCustomTexts.contains(i)))
- btns[i]->setText(q->currentPage()->d_func()->buttonCustomTexts.value(i));
- else if (buttonCustomTexts.contains(i))
- btns[i]->setText(buttonCustomTexts.value(i));
- else if (i < QWizard::NStandardButtons)
- btns[i]->setText(buttonDefaultText(wizStyle, i, this));
-#ifdef QT_SOFTKEYS_ENABLED
- softKeys[i]->setText(btns[i]->text());
-#endif
- }
- }
-}
-
-void QWizardPrivate::updateButtonLayout()
-{
- if (buttonsHaveCustomLayout) {
- QVarLengthArray<QWizard::WizardButton> array(buttonsCustomLayout.count());
- for (int i = 0; i < buttonsCustomLayout.count(); ++i)
- array[i] = buttonsCustomLayout.at(i);
- setButtonLayout(array.constData(), array.count());
- } else {
- // Positions:
- // Help Stretch Custom1 Custom2 Custom3 Cancel Back Next Commit Finish Cancel Help
-
- const int ArraySize = 12;
- QWizard::WizardButton array[ArraySize];
- memset(array, -1, sizeof(array));
- Q_ASSERT(array[0] == QWizard::NoButton);
-
- if (opts & QWizard::HaveHelpButton) {
- int i = (opts & QWizard::HelpButtonOnRight) ? 11 : 0;
- array[i] = QWizard::HelpButton;
- }
- array[1] = QWizard::Stretch;
- if (opts & QWizard::HaveCustomButton1)
- array[2] = QWizard::CustomButton1;
- if (opts & QWizard::HaveCustomButton2)
- array[3] = QWizard::CustomButton2;
- if (opts & QWizard::HaveCustomButton3)
- array[4] = QWizard::CustomButton3;
-
- if (!(opts & QWizard::NoCancelButton)) {
- int i = (opts & QWizard::CancelButtonOnLeft) ? 5 : 10;
- array[i] = QWizard::CancelButton;
- }
- array[6] = QWizard::BackButton;
- array[7] = QWizard::NextButton;
- array[8] = QWizard::CommitButton;
- array[9] = QWizard::FinishButton;
-
- setButtonLayout(array, ArraySize);
- }
-}
-
-void QWizardPrivate::setButtonLayout(const QWizard::WizardButton *array, int size)
-{
- QWidget *prev = pageFrame;
-
- for (int i = buttonLayout->count() - 1; i >= 0; --i) {
- QLayoutItem *item = buttonLayout->takeAt(i);
- if (QWidget *widget = item->widget())
- widget->hide();
- delete item;
- }
-
- for (int i = 0; i < size; ++i) {
- QWizard::WizardButton which = array[i];
- if (which == QWizard::Stretch) {
- buttonLayout->addStretch(1);
- } else if (which != QWizard::NoButton) {
- ensureButton(which);
- buttonLayout->addWidget(btns[which]);
-
- // Back, Next, Commit, and Finish are handled in _q_updateButtonStates()
- if (which != QWizard::BackButton && which != QWizard::NextButton
- && which != QWizard::CommitButton && which != QWizard::FinishButton)
- btns[which]->show();
-
- if (prev)
- QWidget::setTabOrder(prev, btns[which]);
- prev = btns[which];
- }
- }
-
- _q_updateButtonStates();
-}
-
-bool QWizardPrivate::buttonLayoutContains(QWizard::WizardButton which)
-{
- return !buttonsHaveCustomLayout || buttonsCustomLayout.contains(which);
-}
-
-void QWizardPrivate::updatePixmap(QWizard::WizardPixmap which)
-{
- Q_Q(QWizard);
- if (which == QWizard::BackgroundPixmap) {
- if (wizStyle == QWizard::MacStyle) {
- q->update();
- q->updateGeometry();
- }
- } else {
- updateLayout();
- }
-}
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-bool QWizardPrivate::vistaDisabled() const
-{
- Q_Q(const QWizard);
- const QVariant v = q->property("_q_wizard_vista_off");
- return v.isValid() && v.toBool();
-}
-
-bool QWizardPrivate::isVistaThemeEnabled(QVistaHelper::VistaState state) const
-{
- return wizStyle == QWizard::AeroStyle
- && QVistaHelper::vistaState() == state
- && !vistaDisabled();
-}
-
-void QWizardPrivate::handleAeroStyleChange()
-{
- Q_Q(QWizard);
-
- if (inHandleAeroStyleChange)
- return; // prevent recursion
- inHandleAeroStyleChange = true;
-
- vistaHelper->disconnectBackButton();
- q->removeEventFilter(vistaHelper);
-
- if (isVistaThemeEnabled()) {
- if (isVistaThemeEnabled(QVistaHelper::VistaAero)) {
- vistaHelper->setDWMTitleBar(QVistaHelper::ExtendedTitleBar);
- q->installEventFilter(vistaHelper);
- q->setMouseTracking(true);
- antiFlickerWidget->move(0, vistaHelper->titleBarSize() + vistaHelper->topOffset());
- vistaHelper->backButton()->move(
- 0, vistaHelper->topOffset() // ### should ideally work without the '+ 1'
- - qMin(vistaHelper->topOffset(), vistaHelper->topPadding() + 1));
- } else {
- vistaHelper->setDWMTitleBar(QVistaHelper::NormalTitleBar);
- q->setMouseTracking(true);
- antiFlickerWidget->move(0, vistaHelper->topOffset());
- vistaHelper->backButton()->move(0, -1); // ### should ideally work with (0, 0)
- }
- vistaHelper->setTitleBarIconAndCaptionVisible(false);
- QObject::connect(
- vistaHelper->backButton(), SIGNAL(clicked()), q, buttonSlots[QWizard::BackButton]);
- vistaHelper->backButton()->show();
- } else {
- q->setMouseTracking(true); // ### original value possibly different
-#ifndef QT_NO_CURSOR
- q->unsetCursor(); // ### ditto
-#endif
- antiFlickerWidget->move(0, 0);
- vistaHelper->hideBackButton();
- vistaHelper->setTitleBarIconAndCaptionVisible(true);
- }
-
- _q_updateButtonStates();
-
- if (q->isVisible())
- vistaHelper->setWindowPosHack();
-
- inHandleAeroStyleChange = false;
-}
-#endif
-
-bool QWizardPrivate::isVistaThemeEnabled() const
-{
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- return isVistaThemeEnabled(QVistaHelper::VistaAero)
- || isVistaThemeEnabled(QVistaHelper::VistaBasic);
-#else
- return false;
-#endif
-}
-
-void QWizardPrivate::disableUpdates()
-{
- Q_Q(QWizard);
- if (disableUpdatesCount++ == 0) {
- q->setUpdatesEnabled(false);
- antiFlickerWidget->hide();
- }
-}
-
-void QWizardPrivate::enableUpdates()
-{
- Q_Q(QWizard);
- if (--disableUpdatesCount == 0) {
- antiFlickerWidget->show();
- q->setUpdatesEnabled(true);
- }
-}
-
-void QWizardPrivate::_q_emitCustomButtonClicked()
-{
- Q_Q(QWizard);
- QObject *button = q->sender();
- for (int i = QWizard::NStandardButtons; i < QWizard::NButtons; ++i) {
- if (btns[i] == button) {
- emit q->customButtonClicked(QWizard::WizardButton(i));
- break;
- }
- }
-}
-
-void QWizardPrivate::_q_updateButtonStates()
-{
- Q_Q(QWizard);
-
- disableUpdates();
-
- const QWizardPage *page = q->currentPage();
- bool complete = page && page->isComplete();
-
- btn.back->setEnabled(history.count() > 1
- && !q->page(history.at(history.count() - 2))->isCommitPage()
- && (!canFinish || !(opts & QWizard::DisabledBackButtonOnLastPage)));
- btn.next->setEnabled(canContinue && complete);
- btn.commit->setEnabled(canContinue && complete);
- btn.finish->setEnabled(canFinish && complete);
-
- const bool backButtonVisible = buttonLayoutContains(QWizard::BackButton)
- && (history.count() > 1 || !(opts & QWizard::NoBackButtonOnStartPage))
- && (canContinue || !(opts & QWizard::NoBackButtonOnLastPage));
- bool commitPage = page && page->isCommitPage();
- btn.back->setVisible(backButtonVisible);
- btn.next->setVisible(buttonLayoutContains(QWizard::NextButton) && !commitPage
- && (canContinue || (opts & QWizard::HaveNextButtonOnLastPage)));
- btn.commit->setVisible(buttonLayoutContains(QWizard::CommitButton) && commitPage
- && canContinue);
- btn.finish->setVisible(buttonLayoutContains(QWizard::FinishButton)
- && (canFinish || (opts & QWizard::HaveFinishButtonOnEarlyPages)));
-
- bool useDefault = !(opts & QWizard::NoDefaultButton);
- if (QPushButton *nextPush = qobject_cast<QPushButton *>(btn.next))
- nextPush->setDefault(canContinue && useDefault && !commitPage);
- if (QPushButton *commitPush = qobject_cast<QPushButton *>(btn.commit))
- commitPush->setDefault(canContinue && useDefault && commitPage);
- if (QPushButton *finishPush = qobject_cast<QPushButton *>(btn.finish))
- finishPush->setDefault(!canContinue && useDefault);
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (isVistaThemeEnabled()) {
- vistaHelper->backButton()->setEnabled(btn.back->isEnabled());
- vistaHelper->backButton()->setVisible(backButtonVisible);
- btn.back->setVisible(false);
- }
-#endif
-
-#ifdef QT_SOFTKEYS_ENABLED
- QAbstractButton *wizardButton;
- for (int i = 0; i < QWizard::NButtons; ++i) {
- wizardButton = btns[i];
- if (wizardButton && !wizardButton->testAttribute(Qt::WA_WState_Hidden)) {
- wizardButton->hide();
- q->addAction(softKeys[i]);
- } else {
- q->removeAction(softKeys[i]);
- }
- }
-#endif
-
- enableUpdates();
-}
-
-void QWizardPrivate::_q_handleFieldObjectDestroyed(QObject *object)
-{
- QVector<QWizardField>::iterator it = fields.begin();
- while (it != fields.end()) {
- const QWizardField &field = *it;
- if (field.object == object) {
- fieldIndexMap.remove(field.name);
- it = fields.erase(it);
- } else {
- ++it;
- }
- }
-}
-
-void QWizardPrivate::setStyle(QStyle *style)
-{
- for (int i = 0; i < QWizard::NButtons; i++)
- if (btns[i])
- btns[i]->setStyle(style);
- const PageMap::const_iterator pcend = pageMap.constEnd();
- for (PageMap::const_iterator it = pageMap.constBegin(); it != pcend; ++it)
- it.value()->setStyle(style);
-}
-
-#ifdef Q_WS_MAC
-
-QPixmap QWizardPrivate::findDefaultBackgroundPixmap()
-{
- QCFType<CFURLRef> url;
- const int ExpectedImageWidth = 242;
- const int ExpectedImageHeight = 414;
- if (LSFindApplicationForInfo(kLSUnknownCreator, CFSTR("com.apple.KeyboardSetupAssistant"),
- 0, 0, &url) == noErr) {
- QCFType<CFBundleRef> bundle = CFBundleCreate(kCFAllocatorDefault, url);
- if (bundle) {
- url = CFBundleCopyResourceURL(bundle, CFSTR("Background"), CFSTR("tif"), 0);
- if (url) {
- QCFType<CGImageSourceRef> imageSource = CGImageSourceCreateWithURL(url, 0);
- QCFType<CGImageRef> image = CGImageSourceCreateImageAtIndex(imageSource, 0, 0);
- if (image) {
- int width = CGImageGetWidth(image);
- int height = CGImageGetHeight(image);
- if (width == ExpectedImageWidth && height == ExpectedImageHeight)
- return QPixmap::fromMacCGImageRef(image);
- }
- }
- }
- }
- return QPixmap();
-
-}
-
-#endif
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-void QWizardAntiFlickerWidget::paintEvent(QPaintEvent *)
-{
- if (wizardPrivate->isVistaThemeEnabled()) {
- int leftMargin, topMargin, rightMargin, bottomMargin;
- wizardPrivate->buttonLayout->getContentsMargins(
- &leftMargin, &topMargin, &rightMargin, &bottomMargin);
- const int buttonLayoutTop = wizardPrivate->buttonLayout->contentsRect().top() - topMargin;
- QPainter painter(this);
- const QBrush brush(QColor(240, 240, 240)); // ### hardcoded for now
- painter.fillRect(0, buttonLayoutTop, width(), height() - buttonLayoutTop, brush);
- painter.setPen(QPen(QBrush(QColor(223, 223, 223)), 0)); // ### hardcoded for now
- painter.drawLine(0, buttonLayoutTop, width(), buttonLayoutTop);
- if (wizardPrivate->isVistaThemeEnabled(QVistaHelper::VistaBasic)) {
- if (window()->isActiveWindow())
- painter.setPen(QPen(QBrush(QColor(169, 191, 214)), 0)); // ### hardcoded for now
- else
- painter.setPen(QPen(QBrush(QColor(182, 193, 204)), 0)); // ### hardcoded for now
- painter.drawLine(0, 0, width(), 0);
- }
- }
-}
-#endif
-
-/*!
- \class QWizard
- \since 4.3
- \brief The QWizard class provides a framework for wizards.
-
- A wizard (also called an assistant on Mac OS X) is a special type
- of input dialog that consists of a sequence of pages. A wizard's
- purpose is to guide the user through a process step by step.
- Wizards are useful for complex or infrequent tasks that users may
- find difficult to learn.
-
- QWizard inherits QDialog and represents a wizard. Each page is a
- QWizardPage (a QWidget subclass). To create your own wizards, you
- can use these classes directly, or you can subclass them for more
- control.
-
- Topics:
-
- \tableofcontents
-
- \section1 A Trivial Example
-
- The following example illustrates how to create wizard pages and
- add them to a wizard. For more advanced examples, see
- \l{dialogs/classwizard}{Class Wizard} and \l{dialogs/licensewizard}{License
- Wizard}.
-
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 1
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 3
- \dots
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 4
- \codeline
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 5
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 7
- \dots
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 8
- \codeline
- \snippet examples/dialogs/trivialwizard/trivialwizard.cpp 10
-
- \section1 Wizard Look and Feel
-
- QWizard supports four wizard looks:
-
- \list
- \o ClassicStyle
- \o ModernStyle
- \o MacStyle
- \o AeroStyle
- \endlist
-
- You can explicitly set the look to use using setWizardStyle()
- (e.g., if you want the same look on all platforms).
-
- \table
- \header \o ClassicStyle
- \o ModernStyle
- \o MacStyle
- \o AeroStyle
- \row \o \inlineimage qtwizard-classic1.png
- \o \inlineimage qtwizard-modern1.png
- \o \inlineimage qtwizard-mac1.png
- \o \inlineimage qtwizard-aero1.png
- \row \o \inlineimage qtwizard-classic2.png
- \o \inlineimage qtwizard-modern2.png
- \o \inlineimage qtwizard-mac2.png
- \o \inlineimage qtwizard-aero2.png
- \endtable
-
- Note: AeroStyle has effect only on a Windows Vista system with alpha compositing enabled.
- ModernStyle is used as a fallback when this condition is not met.
-
- In addition to the wizard style, there are several options that
- control the look and feel of the wizard. These can be set using
- setOption() or setOptions(). For example, HaveHelpButton makes
- QWizard show a \gui Help button along with the other wizard
- buttons.
-
- You can even change the order of the wizard buttons to any
- arbitrary order using setButtonLayout(), and you can add up to
- three custom buttons (e.g., a \gui Print button) to the button
- row. This is achieved by calling setButton() or setButtonText()
- with CustomButton1, CustomButton2, or CustomButton3 to set up the
- button, and by enabling the HaveCustomButton1, HaveCustomButton2,
- or HaveCustomButton3 options. Whenever the user clicks a custom
- button, customButtonClicked() is emitted. For example:
-
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 29
-
- \section1 Elements of a Wizard Page
-
- Wizards consist of a sequence of \l{QWizardPage}s. At any time,
- only one page is shown. A page has the following attributes:
-
- \list
- \o A \l{QWizardPage::}{title}.
- \o A \l{QWizardPage::}{subTitle}.
- \o A set of pixmaps, which may or may not be honored, depending
- on the wizard's style:
- \list
- \o WatermarkPixmap (used by ClassicStyle and ModernStyle)
- \o BannerPixmap (used by ModernStyle)
- \o LogoPixmap (used by ClassicStyle and ModernStyle)
- \o BackgroundPixmap (used by MacStyle)
- \endlist
- \endlist
-
- The diagram belows shows how QWizard renders these attributes,
- assuming they are all present and ModernStyle is used:
-
- \image qtwizard-nonmacpage.png
-
- When a \l{QWizardPage::}{subTitle} is set, QWizard displays it
- in a header, in which case it also uses the BannerPixmap and the
- LogoPixmap to decorate the header. The WatermarkPixmap is
- displayed on the left side, below the header. At the bottom,
- there is a row of buttons allowing the user to navigate through
- the pages.
-
- The page itself (the \l{QWizardPage} widget) occupies the area
- between the header, the watermark, and the button row. Typically,
- the page is a QWizardPage on which a QGridLayout is installed,
- with standard child widgets (\l{QLabel}s, \l{QLineEdit}s, etc.).
-
- If the wizard's style is MacStyle, the page looks radically
- different:
-
- \image qtwizard-macpage.png
-
- The watermark, banner, and logo pixmaps are ignored by the
- MacStyle. If the BackgroundPixmap is set, it is used as the
- background for the wizard; otherwise, a default "assistant" image
- is used.
-
- The title and subtitle are set by calling
- QWizardPage::setTitle() and QWizardPage::setSubTitle() on the
- individual pages. They may be plain text or HTML (see titleFormat
- and subTitleFormat). The pixmaps can be set globally for the
- entire wizard using setPixmap(), or on a per-page basis using
- QWizardPage::setPixmap().
-
- \target field mechanism
- \section1 Registering and Using Fields
-
- In many wizards, the contents of a page may affect the default
- values of the fields of a later page. To make it easy to
- communicate between pages, QWizard supports a "field" mechanism
- that allows you to register a field (e.g., a QLineEdit) on a page
- and to access its value from any page. It is also possible to
- specify mandatory fields (i.e., fields that must be filled before
- the user can advance to the next page).
-
- To register a field, call QWizardPage::registerField() field.
- For example:
-
- \snippet examples/dialogs/classwizard/classwizard.cpp 8
- \dots
- \snippet examples/dialogs/classwizard/classwizard.cpp 10
- \snippet examples/dialogs/classwizard/classwizard.cpp 11
- \dots
- \snippet examples/dialogs/classwizard/classwizard.cpp 13
-
- The above code registers three fields, \c className, \c
- baseClass, and \c qobjectMacro, which are associated with three
- child widgets. The asterisk (\c *) next to \c className denotes a
- mandatory field.
-
- \target initialize page
- The fields of any page are accessible from any other page. For
- example:
-
- \snippet examples/dialogs/classwizard/classwizard.cpp 17
-
- Here, we call QWizardPage::field() to access the contents of the
- \c className field (which was defined in the \c ClassInfoPage)
- and use it to initialize the \c OuputFilePage. The field's
- contents is returned as a QVariant.
-
- When we create a field using QWizardPage::registerField(), we
- pass a unique field name and a widget. We can also provide a Qt
- property name and a "changed" signal (a signal that is emitted
- when the property changes) as third and fourth arguments;
- however, this is not necessary for the most common Qt widgets,
- such as QLineEdit, QCheckBox, and QComboBox, because QWizard
- knows which properties to look for.
-
- \target mandatory fields
-
- If an asterisk (\c *) is appended to the name when the property
- is registered, the field is a \e{mandatory field}. When a page has
- mandatory fields, the \gui Next and/or \gui Finish buttons are
- enabled only when all mandatory fields are filled.
-
- To consider a field "filled", QWizard simply checks that the
- field's current value doesn't equal the original value (the value
- it had when initializePage() was called). For QLineEdit and
- QAbstractSpinBox subclasses, QWizard also checks that
- \l{QLineEdit::hasAcceptableInput()}{hasAcceptableInput()} returns
- true, to honor any validator or mask.
-
- QWizard's mandatory field mechanism is provided for convenience.
- A more powerful (but also more cumbersome) alternative is to
- reimplement QWizardPage::isComplete() and to emit the
- QWizardPage::completeChanged() signal whenever the page becomes
- complete or incomplete.
-
- The enabled/disabled state of the \gui Next and/or \gui Finish
- buttons is one way to perform validation on the user input.
- Another way is to reimplement validateCurrentPage() (or
- QWizardPage::validatePage()) to perform some last-minute
- validation (and show an error message if the user has entered
- incomplete or invalid information). If the function returns true,
- the next page is shown (or the wizard finishes); otherwise, the
- current page stays up.
-
- \section1 Creating Linear Wizards
-
- Most wizards have a linear structure, with page 1 followed by
- page 2 and so on until the last page. The \l{dialogs/classwizard}{Class
- Wizard} example is such a wizard. With QWizard, linear wizards
- are created by instantiating the \l{QWizardPage}s and inserting
- them using addPage(). By default, the pages are shown in the
- order in which they were added. For example:
-
- \snippet examples/dialogs/classwizard/classwizard.cpp 0
- \dots
- \snippet examples/dialogs/classwizard/classwizard.cpp 2
-
- When a page is about to be shown, QWizard calls initializePage()
- (which in turn calls QWizardPage::initializePage()) to fill the
- page with default values. By default, this function does nothing,
- but it can be reimplemented to initialize the page's contents
- based on other pages' fields (see the \l{initialize page}{example
- above}).
-
- If the user presses \gui Back, cleanupPage() is called (which in
- turn calls QWizardPage::cleanupPage()). The default
- implementation resets the page's fields to their original values
- (the values they had before initializePage() was called). If you
- want the \gui Back button to be non-destructive and keep the
- values entered by the user, simply enable the IndependentPages
- option.
-
- \section1 Creating Non-Linear Wizards
-
- Some wizards are more complex in that they allow different
- traversal paths based on the information provided by the user.
- The \l{dialogs/licensewizard}{License Wizard} example illustrates this.
- It provides five wizard pages; depending on which options are
- selected, the user can reach different pages.
-
- \image licensewizard-flow.png
-
- In complex wizards, pages are identified by IDs. These IDs are
- typically defined using an enum. For example:
-
- \snippet examples/dialogs/licensewizard/licensewizard.h 0
- \dots
- \snippet examples/dialogs/licensewizard/licensewizard.h 2
- \dots
- \snippet examples/dialogs/licensewizard/licensewizard.h 3
-
- The pages are inserted using setPage(), which takes an ID and an
- instance of QWizardPage (or of a subclass):
-
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 1
- \dots
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 8
-
- By default, the pages are shown in increasing ID order. To
- provide a dynamic order that depends on the options chosen by the
- user, we must reimplement QWizardPage::nextId(). For example:
-
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 18
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 23
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 24
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 25
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 26
-
- It would also be possible to put all the logic in one place, in a
- QWizard::nextId() reimplementation. For example:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qwizard.cpp 0
-
- To start at another page than the page with the lowest ID, call
- setStartId().
-
- To test whether a page has been visited or not, call
- hasVisitedPage(). For example:
-
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 27
-
- \sa QWizardPage, {Class Wizard Example}, {License Wizard Example}
-*/
-
-/*!
- \enum QWizard::WizardButton
-
- This enum specifies the buttons in a wizard.
-
- \value BackButton The \gui Back button (\gui {Go Back} on Mac OS X)
- \value NextButton The \gui Next button (\gui Continue on Mac OS X)
- \value CommitButton The \gui Commit button
- \value FinishButton The \gui Finish button (\gui Done on Mac OS X)
- \value CancelButton The \gui Cancel button (see also NoCancelButton)
- \value HelpButton The \gui Help button (see also HaveHelpButton)
- \value CustomButton1 The first user-defined button (see also HaveCustomButton1)
- \value CustomButton2 The second user-defined button (see also HaveCustomButton2)
- \value CustomButton3 The third user-defined button (see also HaveCustomButton3)
-
- The following value is only useful when calling setButtonLayout():
-
- \value Stretch A horizontal stretch in the button layout
-
- \omitvalue NoButton
- \omitvalue NStandardButtons
- \omitvalue NButtons
-
- \sa setButton(), setButtonText(), setButtonLayout(), customButtonClicked()
-*/
-
-/*!
- \enum QWizard::WizardPixmap
-
- This enum specifies the pixmaps that can be associated with a page.
-
- \value WatermarkPixmap The tall pixmap on the left side of a ClassicStyle or ModernStyle page
- \value LogoPixmap The small pixmap on the right side of a ClassicStyle or ModernStyle page header
- \value BannerPixmap The pixmap that occupies the background of a ModernStyle page header
- \value BackgroundPixmap The pixmap that occupies the background of a MacStyle wizard
-
- \omitvalue NPixmaps
-
- \sa setPixmap(), QWizardPage::setPixmap(), {Elements of a Wizard Page}
-*/
-
-/*!
- \enum QWizard::WizardStyle
-
- This enum specifies the different looks supported by QWizard.
-
- \value ClassicStyle Classic Windows look
- \value ModernStyle Modern Windows look
- \value MacStyle Mac OS X look
- \value AeroStyle Windows Aero look
-
- \omitvalue NStyles
-
- \sa setWizardStyle(), WizardOption, {Wizard Look and Feel}
-*/
-
-/*!
- \enum QWizard::WizardOption
-
- This enum specifies various options that affect the look and feel
- of a wizard.
-
- \value IndependentPages The pages are independent of each other
- (i.e., they don't derive values from each
- other).
- \value IgnoreSubTitles Don't show any subtitles, even if they are set.
- \value ExtendedWatermarkPixmap Extend any WatermarkPixmap all the
- way down to the window's edge.
- \value NoDefaultButton Don't make the \gui Next or \gui Finish button the
- dialog's \l{QPushButton::setDefault()}{default button}.
- \value NoBackButtonOnStartPage Don't show the \gui Back button on the start page.
- \value NoBackButtonOnLastPage Don't show the \gui Back button on the last page.
- \value DisabledBackButtonOnLastPage Disable the \gui Back button on the last page.
- \value HaveNextButtonOnLastPage Show the (disabled) \gui Next button on the last page.
- \value HaveFinishButtonOnEarlyPages Show the (disabled) \gui Finish button on non-final pages.
- \value NoCancelButton Don't show the \gui Cancel button.
- \value CancelButtonOnLeft Put the \gui Cancel button on the left of \gui Back (rather than on
- the right of \gui Finish or \gui Next).
- \value HaveHelpButton Show the \gui Help button.
- \value HelpButtonOnRight Put the \gui Help button on the far right of the button layout
- (rather than on the far left).
- \value HaveCustomButton1 Show the first user-defined button (CustomButton1).
- \value HaveCustomButton2 Show the second user-defined button (CustomButton2).
- \value HaveCustomButton3 Show the third user-defined button (CustomButton3).
-
- \sa setOptions(), setOption(), testOption()
-*/
-
-/*!
- Constructs a wizard with the given \a parent and window \a flags.
-
- \sa parent(), windowFlags()
-*/
-QWizard::QWizard(QWidget *parent, Qt::WindowFlags flags)
- : QDialog(*new QWizardPrivate, parent, flags)
-{
- Q_D(QWizard);
- d->init();
-#ifdef Q_WS_WINCE
- if (!qt_wince_is_mobile())
- setWindowFlags(windowFlags() & ~Qt::WindowOkButtonHint);
-#endif
-}
-
-/*!
- Destroys the wizard and its pages, releasing any allocated resources.
-*/
-QWizard::~QWizard()
-{
- Q_D(QWizard);
- delete d->buttonLayout;
-}
-
-/*!
- Adds the given \a page to the wizard, and returns the page's ID.
-
- The ID is guaranteed to be larger than any other ID in the
- QWizard so far.
-
- \sa setPage(), page(), pageAdded()
-*/
-int QWizard::addPage(QWizardPage *page)
-{
- Q_D(QWizard);
- int theid = 0;
- if (!d->pageMap.isEmpty())
- theid = (d->pageMap.constEnd() - 1).key() + 1;
- setPage(theid, page);
- return theid;
-}
-
-/*!
- \fn void QWizard::setPage(int id, QWizardPage *page)
-
- Adds the given \a page to the wizard with the given \a id.
-
- \note Adding a page may influence the value of the startId property
- in case it was not set explicitly.
-
- \sa addPage(), page(), pageAdded()
-*/
-void QWizard::setPage(int theid, QWizardPage *page)
-{
- Q_D(QWizard);
-
- if (!page) {
- qWarning("QWizard::setPage: Cannot insert null page");
- return;
- }
-
- if (theid == -1) {
- qWarning("QWizard::setPage: Cannot insert page with ID -1");
- return;
- }
-
- if (d->pageMap.contains(theid)) {
- qWarning("QWizard::setPage: Page with duplicate ID %d ignored", theid);
- return;
- }
-
- page->setParent(d->pageFrame);
-
- QVector<QWizardField> &pendingFields = page->d_func()->pendingFields;
- for (int i = 0; i < pendingFields.count(); ++i)
- d->addField(pendingFields.at(i));
- pendingFields.clear();
-
- connect(page, SIGNAL(completeChanged()), this, SLOT(_q_updateButtonStates()));
-
- d->pageMap.insert(theid, page);
- page->d_func()->wizard = this;
-
- int n = d->pageVBoxLayout->count();
-
- // disable layout to prevent layout updates while adding
- bool pageVBoxLayoutEnabled = d->pageVBoxLayout->isEnabled();
- d->pageVBoxLayout->setEnabled(false);
-
- d->pageVBoxLayout->insertWidget(n - 1, page);
-
- // hide new page and reset layout to old status
- page->hide();
- d->pageVBoxLayout->setEnabled(pageVBoxLayoutEnabled);
-
- if (!d->startSetByUser && d->pageMap.constBegin().key() == theid)
- d->start = theid;
- emit pageAdded(theid);
-}
-
-/*!
- Removes the page with the given \a id. cleanupPage() will be called if necessary.
-
- \note Removing a page may influence the value of the startId property.
-
- \since 4.5
- \sa addPage(), setPage(), pageRemoved(), startId()
-*/
-void QWizard::removePage(int id)
-{
- Q_D(QWizard);
-
- QWizardPage *removedPage = 0;
-
- // update startItem accordingly
- if (d->pageMap.count() > 0) { // only if we have any pages
- if (d->start == id) {
- const int firstId = d->pageMap.constBegin().key();
- if (firstId == id) {
- if (d->pageMap.count() > 1)
- d->start = (++d->pageMap.constBegin()).key(); // secondId
- else
- d->start = -1; // removing the last page
- } else { // startSetByUser has to be "true" here
- d->start = firstId;
- }
- d->startSetByUser = false;
- }
- }
-
- if (d->pageMap.contains(id))
- emit pageRemoved(id);
-
- if (!d->history.contains(id)) {
- // Case 1: removing a page not in the history
- removedPage = d->pageMap.take(id);
- d->updateCurrentPage();
- } else if (id != d->current) {
- // Case 2: removing a page in the history before the current page
- removedPage = d->pageMap.take(id);
- d->history.removeOne(id);
- d->_q_updateButtonStates();
- } else if (d->history.count() == 1) {
- // Case 3: removing the current page which is the first (and only) one in the history
- d->reset();
- removedPage = d->pageMap.take(id);
- if (d->pageMap.isEmpty())
- d->updateCurrentPage();
- else
- restart();
- } else {
- // Case 4: removing the current page which is not the first one in the history
- back();
- removedPage = d->pageMap.take(id);
- d->updateCurrentPage();
- }
-
- if (removedPage) {
- if (d->initialized.contains(id)) {
- cleanupPage(id);
- d->initialized.remove(id);
- }
-
- d->pageVBoxLayout->removeWidget(removedPage);
-
- for (int i = d->fields.count() - 1; i >= 0; --i) {
- if (d->fields.at(i).page == removedPage) {
- removedPage->d_func()->pendingFields += d->fields.at(i);
- d->removeFieldAt(i);
- }
- }
- }
-}
-
-/*!
- \fn QWizardPage *QWizard::page(int id) const
-
- Returns the page with the given \a id, or 0 if there is no such
- page.
-
- \sa addPage(), setPage()
-*/
-QWizardPage *QWizard::page(int theid) const
-{
- Q_D(const QWizard);
- return d->pageMap.value(theid);
-}
-
-/*!
- \fn bool QWizard::hasVisitedPage(int id) const
-
- Returns true if the page history contains page \a id; otherwise,
- returns false.
-
- Pressing \gui Back marks the current page as "unvisited" again.
-
- \sa visitedPages()
-*/
-bool QWizard::hasVisitedPage(int theid) const
-{
- Q_D(const QWizard);
- return d->history.contains(theid);
-}
-
-/*!
- Returns the list of IDs of visited pages, in the order in which the pages
- were visited.
-
- Pressing \gui Back marks the current page as "unvisited" again.
-
- \sa hasVisitedPage()
-*/
-QList<int> QWizard::visitedPages() const
-{
- Q_D(const QWizard);
- return d->history;
-}
-
-/*!
- Returns the list of page IDs.
- \since 4.5
-*/
-QList<int> QWizard::pageIds() const
-{
- Q_D(const QWizard);
- return d->pageMap.keys();
-}
-
-/*!
- \property QWizard::startId
- \brief the ID of the first page
-
- If this property isn't explicitly set, this property defaults to
- the lowest page ID in this wizard, or -1 if no page has been
- inserted yet.
-
- \sa restart(), nextId()
-*/
-void QWizard::setStartId(int theid)
-{
- Q_D(QWizard);
- int newStart = theid;
- if (theid == -1)
- newStart = d->pageMap.count() ? d->pageMap.constBegin().key() : -1;
-
- if (d->start == newStart) {
- d->startSetByUser = theid != -1;
- return;
- }
-
- if (!d->pageMap.contains(newStart)) {
- qWarning("QWizard::setStartId: Invalid page ID %d", newStart);
- return;
- }
- d->start = newStart;
- d->startSetByUser = theid != -1;
-}
-
-int QWizard::startId() const
-{
- Q_D(const QWizard);
- return d->start;
-}
-
-/*!
- Returns a pointer to the current page, or 0 if there is no current
- page (e.g., before the wizard is shown).
-
- This is equivalent to calling page(currentId()).
-
- \sa page(), currentId(), restart()
-*/
-QWizardPage *QWizard::currentPage() const
-{
- Q_D(const QWizard);
- return page(d->current);
-}
-
-/*!
- \property QWizard::currentId
- \brief the ID of the current page
-
- This property cannot be set directly. To change the current page,
- call next(), back(), or restart().
-
- By default, this property has a value of -1, indicating that no page is
- currently shown.
-
- \sa currentIdChanged(), currentPage()
-*/
-int QWizard::currentId() const
-{
- Q_D(const QWizard);
- return d->current;
-}
-
-/*!
- Sets the value of the field called \a name to \a value.
-
- This function can be used to set fields on any page of the wizard.
-
- \sa QWizardPage::registerField(), QWizardPage::setField(), field()
-*/
-void QWizard::setField(const QString &name, const QVariant &value)
-{
- Q_D(QWizard);
-
- int index = d->fieldIndexMap.value(name, -1);
- if (index != -1) {
- const QWizardField &field = d->fields.at(index);
- if (!field.object->setProperty(field.property, value))
- qWarning("QWizard::setField: Couldn't write to property '%s'",
- field.property.constData());
- return;
- }
-
- qWarning("QWizard::setField: No such field '%s'", qPrintable(name));
-}
-
-/*!
- Returns the value of the field called \a name.
-
- This function can be used to access fields on any page of the wizard.
-
- \sa QWizardPage::registerField(), QWizardPage::field(), setField()
-*/
-QVariant QWizard::field(const QString &name) const
-{
- Q_D(const QWizard);
-
- int index = d->fieldIndexMap.value(name, -1);
- if (index != -1) {
- const QWizardField &field = d->fields.at(index);
- return field.object->property(field.property);
- }
-
- qWarning("QWizard::field: No such field '%s'", qPrintable(name));
- return QVariant();
-}
-
-/*!
- \property QWizard::wizardStyle
- \brief the look and feel of the wizard
-
- By default, QWizard uses the AeroStyle on a Windows Vista system with alpha compositing
- enabled, regardless of the current widget style. If this is not the case, the default
- wizard style depends on the current widget style as follows: MacStyle is the default if
- the current widget style is QMacStyle, ModernStyle is the default if the current widget
- style is QWindowsStyle, and ClassicStyle is the default in all other cases.
-
- \sa {Wizard Look and Feel}, options
-*/
-void QWizard::setWizardStyle(WizardStyle style)
-{
- Q_D(QWizard);
-
- const bool styleChange = style != d->wizStyle;
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- const bool aeroStyleChange =
- d->vistaInitPending || d->vistaStateChanged || (styleChange && (style == AeroStyle || d->wizStyle == AeroStyle));
- d->vistaStateChanged = false;
- d->vistaInitPending = false;
-#endif
-
- if (styleChange
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- || aeroStyleChange
-#endif
- ) {
- d->disableUpdates();
- d->wizStyle = style;
- d->updateButtonTexts();
- d->updateLayout();
- updateGeometry();
- d->enableUpdates();
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (aeroStyleChange)
- d->handleAeroStyleChange();
-#endif
- }
-}
-
-QWizard::WizardStyle QWizard::wizardStyle() const
-{
- Q_D(const QWizard);
- return d->wizStyle;
-}
-
-/*!
- Sets the given \a option to be enabled if \a on is true;
- otherwise, clears the given \a option.
-
- \sa options, testOption(), setWizardStyle()
-*/
-void QWizard::setOption(WizardOption option, bool on)
-{
- Q_D(QWizard);
- if (!(d->opts & option) != !on)
- setOptions(d->opts ^ option);
-}
-
-/*!
- Returns true if the given \a option is enabled; otherwise, returns
- false.
-
- \sa options, setOption(), setWizardStyle()
-*/
-bool QWizard::testOption(WizardOption option) const
-{
- Q_D(const QWizard);
- return (d->opts & option) != 0;
-}
-
-/*!
- \property QWizard::options
- \brief the various options that affect the look and feel of the wizard
-
- By default, the following options are set (depending on the platform):
-
- \list
- \o Windows: HelpButtonOnRight.
- \o Mac OS X: NoDefaultButton and NoCancelButton.
- \o X11 and QWS (Qt for Embedded Linux): none.
- \endlist
-
- \sa wizardStyle
-*/
-void QWizard::setOptions(WizardOptions options)
-{
- Q_D(QWizard);
-
- WizardOptions changed = (options ^ d->opts);
- if (!changed)
- return;
-
- d->disableUpdates();
-
- d->opts = options;
- if ((changed & IndependentPages) && !(d->opts & IndependentPages))
- d->cleanupPagesNotInHistory();
-
- if (changed & (NoDefaultButton | HaveHelpButton | HelpButtonOnRight | NoCancelButton
- | CancelButtonOnLeft | HaveCustomButton1 | HaveCustomButton2
- | HaveCustomButton3)) {
- d->updateButtonLayout();
- } else if (changed & (NoBackButtonOnStartPage | NoBackButtonOnLastPage
- | HaveNextButtonOnLastPage | HaveFinishButtonOnEarlyPages
- | DisabledBackButtonOnLastPage)) {
- d->_q_updateButtonStates();
- }
-
- d->enableUpdates();
- d->updateLayout();
-}
-
-QWizard::WizardOptions QWizard::options() const
-{
- Q_D(const QWizard);
- return d->opts;
-}
-
-/*!
- Sets the text on button \a which to be \a text.
-
- By default, the text on buttons depends on the wizardStyle. For
- example, on Mac OS X, the \gui Next button is called \gui
- Continue.
-
- To add extra buttons to the wizard (e.g., a \gui Print button),
- one way is to call setButtonText() with CustomButton1,
- CustomButton2, or CustomButton3 to set their text, and make the
- buttons visible using the HaveCustomButton1, HaveCustomButton2,
- and/or HaveCustomButton3 options.
-
- Button texts may also be set on a per-page basis using QWizardPage::setButtonText().
-
- \sa setButton(), button(), setButtonLayout(), setOptions(), QWizardPage::setButtonText()
-*/
-void QWizard::setButtonText(WizardButton which, const QString &text)
-{
- Q_D(QWizard);
-
- if (!d->ensureButton(which))
- return;
-
- d->buttonCustomTexts.insert(which, text);
-
- if (!currentPage() || !currentPage()->d_func()->buttonCustomTexts.contains(which))
- d->btns[which]->setText(text);
-}
-
-/*!
- Returns the text on button \a which.
-
- If a text has ben set using setButtonText(), this text is returned.
-
- By default, the text on buttons depends on the wizardStyle. For
- example, on Mac OS X, the \gui Next button is called \gui
- Continue.
-
- \sa button(), setButton(), setButtonText(), QWizardPage::buttonText(),
- QWizardPage::setButtonText()
-*/
-QString QWizard::buttonText(WizardButton which) const
-{
- Q_D(const QWizard);
-
- if (!d->ensureButton(which))
- return QString();
-
- if (d->buttonCustomTexts.contains(which))
- return d->buttonCustomTexts.value(which);
-
- const QString defText = buttonDefaultText(d->wizStyle, which, d);
- if(!defText.isNull())
- return defText;
-
- return d->btns[which]->text();
-}
-
-/*!
- Sets the order in which buttons are displayed to \a layout, where
- \a layout is a list of \l{WizardButton}s.
-
- The default layout depends on the options (e.g., whether
- HelpButtonOnRight) that are set. You can call this function if
- you need more control over the buttons' layout than what \l
- options already provides.
-
- You can specify horizontal stretches in the layout using \l
- Stretch.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_dialogs_qwizard.cpp 1
-
- \sa setButton(), setButtonText(), setOptions()
-*/
-void QWizard::setButtonLayout(const QList<WizardButton> &layout)
-{
- Q_D(QWizard);
-
- for (int i = 0; i < layout.count(); ++i) {
- WizardButton button1 = layout.at(i);
-
- if (button1 == NoButton || button1 == Stretch)
- continue;
- if (!d->ensureButton(button1))
- return;
-
- // O(n^2), but n is very small
- for (int j = 0; j < i; ++j) {
- WizardButton button2 = layout.at(j);
- if (button2 == button1) {
- qWarning("QWizard::setButtonLayout: Duplicate button in layout");
- return;
- }
- }
- }
-
- d->buttonsHaveCustomLayout = true;
- d->buttonsCustomLayout = layout;
- d->updateButtonLayout();
-}
-
-/*!
- Sets the button corresponding to role \a which to \a button.
-
- To add extra buttons to the wizard (e.g., a \gui Print button),
- one way is to call setButton() with CustomButton1 to
- CustomButton3, and make the buttons visible using the
- HaveCustomButton1 to HaveCustomButton3 options.
-
- \sa setButtonText(), setButtonLayout(), options
-*/
-void QWizard::setButton(WizardButton which, QAbstractButton *button)
-{
- Q_D(QWizard);
-
- if (uint(which) >= NButtons || d->btns[which] == button)
- return;
-
- if (QAbstractButton *oldButton = d->btns[which]) {
- d->buttonLayout->removeWidget(oldButton);
- delete oldButton;
- }
-
- d->btns[which] = button;
- if (button) {
- button->setParent(d->antiFlickerWidget);
- d->buttonCustomTexts.insert(which, button->text());
- d->connectButton(which);
- } else {
- d->buttonCustomTexts.remove(which); // ### what about page-specific texts set for 'which'
- d->ensureButton(which); // (QWizardPage::setButtonText())? Clear them as well?
- }
-
- d->updateButtonLayout();
-}
-
-/*!
- Returns the button corresponding to role \a which.
-
- \sa setButton(), setButtonText()
-*/
-QAbstractButton *QWizard::button(WizardButton which) const
-{
- Q_D(const QWizard);
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (d->wizStyle == AeroStyle && which == BackButton)
- return d->vistaHelper->backButton();
-#endif
- if (!d->ensureButton(which))
- return 0;
- return d->btns[which];
-}
-
-/*!
- \property QWizard::titleFormat
- \brief the text format used by page titles
-
- The default format is Qt::AutoText.
-
- \sa QWizardPage::title, subTitleFormat
-*/
-void QWizard::setTitleFormat(Qt::TextFormat format)
-{
- Q_D(QWizard);
- d->titleFmt = format;
- d->updateLayout();
-}
-
-Qt::TextFormat QWizard::titleFormat() const
-{
- Q_D(const QWizard);
- return d->titleFmt;
-}
-
-/*!
- \property QWizard::subTitleFormat
- \brief the text format used by page subtitles
-
- The default format is Qt::AutoText.
-
- \sa QWizardPage::title, titleFormat
-*/
-void QWizard::setSubTitleFormat(Qt::TextFormat format)
-{
- Q_D(QWizard);
- d->subTitleFmt = format;
- d->updateLayout();
-}
-
-Qt::TextFormat QWizard::subTitleFormat() const
-{
- Q_D(const QWizard);
- return d->subTitleFmt;
-}
-
-/*!
- Sets the pixmap for role \a which to \a pixmap.
-
- The pixmaps are used by QWizard when displaying a page. Which
- pixmaps are actually used depend on the \l{Wizard Look and
- Feel}{wizard style}.
-
- Pixmaps can also be set for a specific page using
- QWizardPage::setPixmap().
-
- \sa QWizardPage::setPixmap(), {Elements of a Wizard Page}
-*/
-void QWizard::setPixmap(WizardPixmap which, const QPixmap &pixmap)
-{
- Q_D(QWizard);
- Q_ASSERT(uint(which) < NPixmaps);
- d->defaultPixmaps[which] = pixmap;
- d->updatePixmap(which);
-}
-
-/*!
- Returns the pixmap set for role \a which.
-
- By default, the only pixmap that is set is the BackgroundPixmap on
- Mac OS X.
-
- \sa QWizardPage::pixmap(), {Elements of a Wizard Page}
-*/
-QPixmap QWizard::pixmap(WizardPixmap which) const
-{
- Q_D(const QWizard);
- Q_ASSERT(uint(which) < NPixmaps);
-#ifdef Q_WS_MAC
- if (which == BackgroundPixmap && d->defaultPixmaps[BackgroundPixmap].isNull())
- d->defaultPixmaps[BackgroundPixmap] = d->findDefaultBackgroundPixmap();
-#endif
- return d->defaultPixmaps[which];
-}
-
-/*!
- Sets the default property for \a className to be \a property,
- and the associated change signal to be \a changedSignal.
-
- The default property is used when an instance of \a className (or
- of one of its subclasses) is passed to
- QWizardPage::registerField() and no property is specified.
-
- QWizard knows the most common Qt widgets. For these (or their
- subclasses), you don't need to specify a \a property or a \a
- changedSignal. The table below lists these widgets:
-
- \table
- \header \o Widget \o Property \o Change Notification Signal
- \row \o QAbstractButton \o bool \l{QAbstractButton::}{checked} \o \l{QAbstractButton::}{toggled()}
- \row \o QAbstractSlider \o int \l{QAbstractSlider::}{value} \o \l{QAbstractSlider::}{valueChanged()}
- \row \o QComboBox \o int \l{QComboBox::}{currentIndex} \o \l{QComboBox::}{currentIndexChanged()}
- \row \o QDateTimeEdit \o QDateTime \l{QDateTimeEdit::}{dateTime} \o \l{QDateTimeEdit::}{dateTimeChanged()}
- \row \o QLineEdit \o QString \l{QLineEdit::}{text} \o \l{QLineEdit::}{textChanged()}
- \row \o QListWidget \o int \l{QListWidget::}{currentRow} \o \l{QListWidget::}{currentRowChanged()}
- \row \o QSpinBox \o int \l{QSpinBox::}{value} \o \l{QSpinBox::}{valueChanged()}
- \endtable
-
- \sa QWizardPage::registerField()
-*/
-void QWizard::setDefaultProperty(const char *className, const char *property,
- const char *changedSignal)
-{
- Q_D(QWizard);
- for (int i = d->defaultPropertyTable.count() - 1; i >= 0; --i) {
- if (qstrcmp(d->defaultPropertyTable.at(i).className, className) == 0) {
- d->defaultPropertyTable.remove(i);
- break;
- }
- }
- d->defaultPropertyTable.append(QWizardDefaultProperty(className, property, changedSignal));
-}
-
-/*!
- \since 4.7
-
- Sets the given \a widget to be shown on the left side of the wizard.
- For styles which use the WatermarkPixmap (ClassicStyle and ModernStyle)
- the side widget is displayed on top of the watermark, for other styles
- or when the watermark is not provided the side widget is displayed
- on the left side of the wizard.
-
- Passing 0 shows no side widget.
-
- When the \a widget is not 0 the wizard reparents it.
-
- Any previous side widget is hidden.
-
- You may call setSideWidget() with the same widget at different
- times.
-
- All widgets set here will be deleted by the wizard when it is
- destroyed unless you separately reparent the widget after setting
- some other side widget (or 0).
-
- By default, no side widget is present.
-*/
-void QWizard::setSideWidget(QWidget *widget)
-{
- Q_D(QWizard);
-
- d->sideWidget = widget;
- if (d->watermarkLabel) {
- d->watermarkLabel->setSideWidget(widget);
- d->updateLayout();
- }
-}
-
-/*!
- \since 4.7
-
- Returns the widget on the left side of the wizard or 0.
-
- By default, no side widget is present.
-*/
-QWidget *QWizard::sideWidget() const
-{
- Q_D(const QWizard);
-
- return d->sideWidget;
-}
-
-/*!
- \reimp
-*/
-void QWizard::setVisible(bool visible)
-{
- Q_D(QWizard);
- if (visible) {
- if (d->current == -1)
- restart();
- }
- QDialog::setVisible(visible);
-}
-
-/*!
- \reimp
-*/
-QSize QWizard::sizeHint() const
-{
- Q_D(const QWizard);
- QSize result = d->mainLayout->totalSizeHint();
-#ifdef Q_WS_S60
- QSize extra(QApplication::desktop()->availableGeometry(QCursor::pos()).size());
-#else
- QSize extra(500, 360);
-#endif
- if (d->wizStyle == MacStyle && d->current != -1) {
- QSize pixmap(currentPage()->pixmap(BackgroundPixmap).size());
- extra.setWidth(616);
- if (!pixmap.isNull()) {
- extra.setHeight(pixmap.height());
-
- /*
- The width isn't always reliable as a size hint, as
- some wizard backgrounds just cover the leftmost area.
- Use a rule of thumb to determine if the width is
- reliable or not.
- */
- if (pixmap.width() >= pixmap.height())
- extra.setWidth(pixmap.width());
- }
- }
- return result.expandedTo(extra);
-}
-
-/*!
- \fn void QWizard::currentIdChanged(int id)
-
- This signal is emitted when the current page changes, with the new
- current \a id.
-
- \sa currentId(), currentPage()
-*/
-
-/*!
- \fn void QWizard::pageAdded(int id)
-
- \since 4.7
-
- This signal is emitted whenever a page is added to the
- wizard. The page's \a id is passed as parameter.
-
- \sa addPage(), setPage(), startId()
-*/
-
-/*!
- \fn void QWizard::pageRemoved(int id)
-
- \since 4.7
-
- This signal is emitted whenever a page is removed from the
- wizard. The page's \a id is passed as parameter.
-
- \sa removePage(), startId()
-*/
-
-/*!
- \fn void QWizard::helpRequested()
-
- This signal is emitted when the user clicks the \gui Help button.
-
- By default, no \gui Help button is shown. Call
- setOption(HaveHelpButton, true) to have one.
-
- Example:
-
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 0
- \dots
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 5
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 7
- \dots
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 8
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 10
- \dots
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 12
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 14
- \codeline
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 15
-
- \sa customButtonClicked()
-*/
-
-/*!
- \fn void QWizard::customButtonClicked(int which)
-
- This signal is emitted when the user clicks a custom button. \a
- which can be CustomButton1, CustomButton2, or CustomButton3.
-
- By default, no custom button is shown. Call setOption() with
- HaveCustomButton1, HaveCustomButton2, or HaveCustomButton3 to have
- one, and use setButtonText() or setButton() to configure it.
-
- \sa helpRequested()
-*/
-
-/*!
- Goes back to the previous page.
-
- This is equivalent to pressing the \gui Back button.
-
- \sa next(), accept(), reject(), restart()
-*/
-void QWizard::back()
-{
- Q_D(QWizard);
- int n = d->history.count() - 2;
- if (n < 0)
- return;
- d->switchToPage(d->history.at(n), QWizardPrivate::Backward);
-}
-
-/*!
- Advances to the next page.
-
- This is equivalent to pressing the \gui Next or \gui Commit button.
-
- \sa nextId(), back(), accept(), reject(), restart()
-*/
-void QWizard::next()
-{
- Q_D(QWizard);
-
- if (d->current == -1)
- return;
-
- if (validateCurrentPage()) {
- int next = nextId();
- if (next != -1) {
- if (d->history.contains(next)) {
- qWarning("QWizard::next: Page %d already met", next);
- return;
- }
- if (!d->pageMap.contains(next)) {
- qWarning("QWizard::next: No such page %d", next);
- return;
- }
- d->switchToPage(next, QWizardPrivate::Forward);
- }
- }
-}
-
-/*!
- Restarts the wizard at the start page. This function is called automatically when the
- wizard is shown.
-
- \sa startId()
-*/
-void QWizard::restart()
-{
- Q_D(QWizard);
- d->disableUpdates();
- d->reset();
- d->switchToPage(startId(), QWizardPrivate::Forward);
- d->enableUpdates();
-}
-
-/*!
- \reimp
-*/
-bool QWizard::event(QEvent *event)
-{
- Q_D(QWizard);
- if (event->type() == QEvent::StyleChange) { // Propagate style
- d->setStyle(style());
- d->updateLayout();
- }
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- else if (event->type() == QEvent::Show && d->vistaInitPending) {
- d->vistaInitPending = false;
- d->wizStyle = AeroStyle;
- d->handleAeroStyleChange();
- }
- else if (d->isVistaThemeEnabled()) {
- d->vistaHelper->mouseEvent(event);
- }
-#endif
- return QDialog::event(event);
-}
-
-/*!
- \reimp
-*/
-void QWizard::resizeEvent(QResizeEvent *event)
-{
- Q_D(QWizard);
- int heightOffset = 0;
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (d->isVistaThemeEnabled()) {
- heightOffset = d->vistaHelper->topOffset();
- if (d->isVistaThemeEnabled(QVistaHelper::VistaAero))
- heightOffset += d->vistaHelper->titleBarSize();
- }
-#endif
- d->antiFlickerWidget->resize(event->size().width(), event->size().height() - heightOffset);
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- if (d->isVistaThemeEnabled())
- d->vistaHelper->resizeEvent(event);
-#endif
- QDialog::resizeEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QWizard::paintEvent(QPaintEvent * event)
-{
- Q_D(QWizard);
- if (d->wizStyle == MacStyle && currentPage()) {
- QPixmap backgroundPixmap = currentPage()->pixmap(BackgroundPixmap);
- if (backgroundPixmap.isNull())
- return;
-
- QPainter painter(this);
- painter.drawPixmap(0, (height() - backgroundPixmap.height()) / 2, backgroundPixmap);
- }
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- else if (d->isVistaThemeEnabled()) {
- if (d->isVistaThemeEnabled(QVistaHelper::VistaBasic)) {
- QPainter painter(this);
- QColor color = d->vistaHelper->basicWindowFrameColor();
- painter.fillRect(0, 0, width(), QVistaHelper::topOffset(), color);
- }
- d->vistaHelper->paintEvent(event);
- }
-#else
- Q_UNUSED(event);
-#endif
-}
-
-#if defined(Q_WS_WIN)
-/*!
- \reimp
-*/
-bool QWizard::winEvent(MSG *message, long *result)
-{
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
- Q_D(QWizard);
- if (d->isVistaThemeEnabled()) {
- const bool winEventResult = d->vistaHelper->handleWinEvent(message, result);
- if (QVistaHelper::vistaState() != d->vistaState) {
- d->vistaState = QVistaHelper::vistaState();
- d->vistaStateChanged = true;
- setWizardStyle(AeroStyle);
- }
- return winEventResult;
- } else {
- return QDialog::winEvent(message, result);
- }
-#else
- return QDialog::winEvent(message, result);
-#endif
-}
-#endif
-
-/*!
- \reimp
-*/
-void QWizard::done(int result)
-{
- Q_D(QWizard);
- // canceling leaves the wizard in a known state
- if (result == Rejected) {
- d->reset();
- } else {
- if (!validateCurrentPage())
- return;
- }
- QDialog::done(result);
-}
-
-/*!
- \fn void QWizard::initializePage(int id)
-
- This virtual function is called by QWizard to prepare page \a id
- just before it is shown either as a result of QWizard::restart()
- being called, or as a result of the user clicking \gui Next. (However, if the \l
- QWizard::IndependentPages option is set, this function is only
- called the first time the page is shown.)
-
- By reimplementing this function, you can ensure that the page's
- fields are properly initialized based on fields from previous
- pages.
-
- The default implementation calls QWizardPage::initializePage() on
- page(\a id).
-
- \sa QWizardPage::initializePage(), cleanupPage()
-*/
-void QWizard::initializePage(int theid)
-{
- QWizardPage *page = this->page(theid);
- if (page)
- page->initializePage();
-}
-
-/*!
- \fn void QWizard::cleanupPage(int id)
-
- This virtual function is called by QWizard to clean up page \a id just before the
- user leaves it by clicking \gui Back (unless the \l QWizard::IndependentPages option is set).
-
- The default implementation calls QWizardPage::cleanupPage() on
- page(\a id).
-
- \sa QWizardPage::cleanupPage(), initializePage()
-*/
-void QWizard::cleanupPage(int theid)
-{
- QWizardPage *page = this->page(theid);
- if (page)
- page->cleanupPage();
-}
-
-/*!
- This virtual function is called by QWizard when the user clicks
- \gui Next or \gui Finish to perform some last-minute validation.
- If it returns true, the next page is shown (or the wizard
- finishes); otherwise, the current page stays up.
-
- The default implementation calls QWizardPage::validatePage() on
- the currentPage().
-
- When possible, it is usually better style to disable the \gui
- Next or \gui Finish button (by specifying \l{mandatory fields} or
- by reimplementing QWizardPage::isComplete()) than to reimplement
- validateCurrentPage().
-
- \sa QWizardPage::validatePage(), currentPage()
-*/
-bool QWizard::validateCurrentPage()
-{
- QWizardPage *page = currentPage();
- if (!page)
- return true;
-
- return page->validatePage();
-}
-
-/*!
- This virtual function is called by QWizard to find out which page
- to show when the user clicks the \gui Next button.
-
- The return value is the ID of the next page, or -1 if no page follows.
-
- The default implementation calls QWizardPage::nextId() on the
- currentPage().
-
- By reimplementing this function, you can specify a dynamic page
- order.
-
- \sa QWizardPage::nextId(), currentPage()
-*/
-int QWizard::nextId() const
-{
- const QWizardPage *page = currentPage();
- if (!page)
- return -1;
-
- return page->nextId();
-}
-
-/*!
- \class QWizardPage
- \since 4.3
- \brief The QWizardPage class is the base class for wizard pages.
-
- QWizard represents a wizard. Each page is a QWizardPage. When
- you create your own wizards, you can use QWizardPage directly,
- or you can subclass it for more control.
-
- A page has the following attributes, which are rendered by
- QWizard: a \l title, a \l subTitle, and a \l{setPixmap()}{set of
- pixmaps}. See \l{Elements of a Wizard Page} for details. Once a
- page is added to the wizard (using QWizard::addPage() or
- QWizard::setPage()), wizard() returns a pointer to the
- associated QWizard object.
-
- Page provides five virtual functions that can be reimplemented to
- provide custom behavior:
-
- \list
- \o initializePage() is called to initialize the page's contents
- when the user clicks the wizard's \gui Next button. If you
- want to derive the page's default from what the user entered
- on previous pages, this is the function to reimplement.
- \o cleanupPage() is called to reset the page's contents when the
- user clicks the wizard's \gui Back button.
- \o validatePage() validates the page when the user clicks \gui
- Next or \gui Finish. It is often used to show an error message
- if the user has entered incomplete or invalid information.
- \o nextId() returns the ID of the next page. It is useful when
- \l{creating non-linear wizards}, which allow different
- traversal paths based on the information provided by the user.
- \o isComplete() is called to determine whether the \gui Next
- and/or \gui Finish button should be enabled or disabled. If
- you reimplement isComplete(), also make sure that
- completeChanged() is emitted whenever the complete state
- changes.
- \endlist
-
- Normally, the \gui Next button and the \gui Finish button of a
- wizard are mutually exclusive. If isFinalPage() returns true, \gui
- Finish is available; otherwise, \gui Next is available. By
- default, isFinalPage() is true only when nextId() returns -1. If
- you want to show \gui Next and \gui Final simultaneously for a
- page (letting the user perform an "early finish"), call
- setFinalPage(true) on that page. For wizards that support early
- finishes, you might also want to set the
- \l{QWizard::}{HaveNextButtonOnLastPage} and
- \l{QWizard::}{HaveFinishButtonOnEarlyPages} options on the
- wizard.
-
- In many wizards, the contents of a page may affect the default
- values of the fields of a later page. To make it easy to
- communicate between pages, QWizard supports a \l{Registering and
- Using Fields}{"field" mechanism} that allows you to register a
- field (e.g., a QLineEdit) on a page and to access its value from
- any page. Fields are global to the entire wizard and make it easy
- for any single page to access information stored by another page,
- without having to put all the logic in QWizard or having the
- pages know explicitly about each other. Fields are registered
- using registerField() and can be accessed at any time using
- field() and setField().
-
- \sa QWizard, {Class Wizard Example}, {License Wizard Example}
-*/
-
-/*!
- Constructs a wizard page with the given \a parent.
-
- When the page is inserted into a wizard using QWizard::addPage()
- or QWizard::setPage(), the parent is automatically set to be the
- wizard.
-
- \sa wizard()
-*/
-QWizardPage::QWizardPage(QWidget *parent)
- : QWidget(*new QWizardPagePrivate, parent, 0)
-{
- connect(this, SIGNAL(completeChanged()), this, SLOT(_q_updateCachedCompleteState()));
-}
-
-/*!
- \property QWizardPage::title
- \brief the title of the page
-
- The title is shown by the QWizard, above the actual page. All
- pages should have a title.
-
- The title may be plain text or HTML, depending on the value of the
- \l{QWizard::titleFormat} property.
-
- By default, this property contains an empty string.
-
- \sa subTitle, {Elements of a Wizard Page}
-*/
-void QWizardPage::setTitle(const QString &title)
-{
- Q_D(QWizardPage);
- d->title = title;
- if (d->wizard && d->wizard->currentPage() == this)
- d->wizard->d_func()->updateLayout();
-}
-
-QString QWizardPage::title() const
-{
- Q_D(const QWizardPage);
- return d->title;
-}
-
-/*!
- \property QWizardPage::subTitle
- \brief the subtitle of the page
-
- The subtitle is shown by the QWizard, between the title and the
- actual page. Subtitles are optional. In
- \l{QWizard::ClassicStyle}{ClassicStyle} and
- \l{QWizard::ModernStyle}{ModernStyle}, using subtitles is
- necessary to make the header appear. In
- \l{QWizard::MacStyle}{MacStyle}, the subtitle is shown as a text
- label just above the actual page.
-
- The subtitle may be plain text or HTML, depending on the value of
- the \l{QWizard::subTitleFormat} property.
-
- By default, this property contains an empty string.
-
- \sa title, QWizard::IgnoreSubTitles, {Elements of a Wizard Page}
-*/
-void QWizardPage::setSubTitle(const QString &subTitle)
-{
- Q_D(QWizardPage);
- d->subTitle = subTitle;
- if (d->wizard && d->wizard->currentPage() == this)
- d->wizard->d_func()->updateLayout();
-}
-
-QString QWizardPage::subTitle() const
-{
- Q_D(const QWizardPage);
- return d->subTitle;
-}
-
-/*!
- Sets the pixmap for role \a which to \a pixmap.
-
- The pixmaps are used by QWizard when displaying a page. Which
- pixmaps are actually used depend on the \l{Wizard Look and
- Feel}{wizard style}.
-
- Pixmaps can also be set for the entire wizard using
- QWizard::setPixmap(), in which case they apply for all pages that
- don't specify a pixmap.
-
- \sa QWizard::setPixmap(), {Elements of a Wizard Page}
-*/
-void QWizardPage::setPixmap(QWizard::WizardPixmap which, const QPixmap &pixmap)
-{
- Q_D(QWizardPage);
- Q_ASSERT(uint(which) < QWizard::NPixmaps);
- d->pixmaps[which] = pixmap;
- if (d->wizard && d->wizard->currentPage() == this)
- d->wizard->d_func()->updatePixmap(which);
-}
-
-/*!
- Returns the pixmap set for role \a which.
-
- Pixmaps can also be set for the entire wizard using
- QWizard::setPixmap(), in which case they apply for all pages that
- don't specify a pixmap.
-
- \sa QWizard::pixmap(), {Elements of a Wizard Page}
-*/
-QPixmap QWizardPage::pixmap(QWizard::WizardPixmap which) const
-{
- Q_D(const QWizardPage);
- Q_ASSERT(uint(which) < QWizard::NPixmaps);
-
- const QPixmap &pixmap = d->pixmaps[which];
- if (!pixmap.isNull())
- return pixmap;
-
- if (wizard())
- return wizard()->pixmap(which);
-
- return pixmap;
-}
-
-/*!
- This virtual function is called by QWizard::initializePage() to
- prepare the page just before it is shown either as a result of QWizard::restart()
- being called, or as a result of the user clicking \gui Next.
- (However, if the \l QWizard::IndependentPages option is set, this function is only
- called the first time the page is shown.)
-
- By reimplementing this function, you can ensure that the page's
- fields are properly initialized based on fields from previous
- pages. For example:
-
- \snippet examples/dialogs/classwizard/classwizard.cpp 17
-
- The default implementation does nothing.
-
- \sa QWizard::initializePage(), cleanupPage(), QWizard::IndependentPages
-*/
-void QWizardPage::initializePage()
-{
-}
-
-/*!
- This virtual function is called by QWizard::cleanupPage() when
- the user leaves the page by clicking \gui Back (unless the \l QWizard::IndependentPages
- option is set).
-
- The default implementation resets the page's fields to their
- original values (the values they had before initializePage() was
- called).
-
- \sa QWizard::cleanupPage(), initializePage(), QWizard::IndependentPages
-*/
-void QWizardPage::cleanupPage()
-{
- Q_D(QWizardPage);
- if (d->wizard) {
- QVector<QWizardField> &fields = d->wizard->d_func()->fields;
- for (int i = 0; i < fields.count(); ++i) {
- const QWizardField &field = fields.at(i);
- if (field.page == this)
- field.object->setProperty(field.property, field.initialValue);
- }
- }
-}
-
-/*!
- This virtual function is called by QWizard::validateCurrentPage()
- when the user clicks \gui Next or \gui Finish to perform some
- last-minute validation. If it returns true, the next page is shown
- (or the wizard finishes); otherwise, the current page stays up.
-
- The default implementation returns true.
-
- When possible, it is usually better style to disable the \gui
- Next or \gui Finish button (by specifying \l{mandatory fields} or
- reimplementing isComplete()) than to reimplement validatePage().
-
- \sa QWizard::validateCurrentPage(), isComplete()
-*/
-bool QWizardPage::validatePage()
-{
- return true;
-}
-
-/*!
- This virtual function is called by QWizard to determine whether
- the \gui Next or \gui Finish button should be enabled or
- disabled.
-
- The default implementation returns true if all \l{mandatory
- fields} are filled; otherwise, it returns false.
-
- If you reimplement this function, make sure to emit completeChanged(),
- from the rest of your implementation, whenever the value of isComplete()
- changes. This ensures that QWizard updates the enabled or disabled state of
- its buttons. An example of the reimplementation is
- available \l{http://qt.nokia.com/doc/qq/qq22-qwizard.html#validatebeforeitstoolate}
- {here}.
-
- \sa completeChanged(), isFinalPage()
-*/
-bool QWizardPage::isComplete() const
-{
- Q_D(const QWizardPage);
-
- if (!d->wizard)
- return true;
-
- const QVector<QWizardField> &wizardFields = d->wizard->d_func()->fields;
- for (int i = wizardFields.count() - 1; i >= 0; --i) {
- const QWizardField &field = wizardFields.at(i);
- if (field.page == this && field.mandatory) {
- QVariant value = field.object->property(field.property);
- if (value == field.initialValue)
- return false;
-
-#ifndef QT_NO_LINEEDIT
- if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(field.object)) {
- if (!lineEdit->hasAcceptableInput())
- return false;
- }
-#endif
-#ifndef QT_NO_SPINBOX
- if (QAbstractSpinBox *spinBox = qobject_cast<QAbstractSpinBox *>(field.object)) {
- if (!spinBox->hasAcceptableInput())
- return false;
- }
-#endif
- }
- }
- return true;
-}
-
-/*!
- Explicitly sets this page to be final if \a finalPage is true.
-
- After calling setFinalPage(true), isFinalPage() returns true and the \gui
- Finish button is visible (and enabled if isComplete() returns
- true).
-
- After calling setFinalPage(false), isFinalPage() returns true if
- nextId() returns -1; otherwise, it returns false.
-
- \sa isComplete(), QWizard::HaveFinishButtonOnEarlyPages
-*/
-void QWizardPage::setFinalPage(bool finalPage)
-{
- Q_D(QWizardPage);
- d->explicitlyFinal = finalPage;
- QWizard *wizard = this->wizard();
- if (wizard && wizard->currentPage() == this)
- wizard->d_func()->updateCurrentPage();
-}
-
-/*!
- This function is called by QWizard to determine whether the \gui
- Finish button should be shown for this page or not.
-
- By default, it returns true if there is no next page
- (i.e., nextId() returns -1); otherwise, it returns false.
-
- By explicitly calling setFinalPage(true), you can let the user perform an
- "early finish".
-
- \sa isComplete(), QWizard::HaveFinishButtonOnEarlyPages
-*/
-bool QWizardPage::isFinalPage() const
-{
- Q_D(const QWizardPage);
- if (d->explicitlyFinal)
- return true;
-
- QWizard *wizard = this->wizard();
- if (wizard && wizard->currentPage() == this) {
- // try to use the QWizard implementation if possible
- return wizard->nextId() == -1;
- } else {
- return nextId() == -1;
- }
-}
-
-/*!
- Sets this page to be a commit page if \a commitPage is true; otherwise,
- sets it to be a normal page.
-
- A commit page is a page that represents an action which cannot be undone
- by clicking \gui Back or \gui Cancel.
-
- A \gui Commit button replaces the \gui Next button on a commit page. Clicking this
- button simply calls QWizard::next() just like clicking \gui Next does.
-
- A page entered directly from a commit page has its \gui Back button disabled.
-
- \sa isCommitPage()
-*/
-void QWizardPage::setCommitPage(bool commitPage)
-{
- Q_D(QWizardPage);
- d->commit = commitPage;
- QWizard *wizard = this->wizard();
- if (wizard && wizard->currentPage() == this)
- wizard->d_func()->updateCurrentPage();
-}
-
-/*!
- Returns true if this page is a commit page; otherwise returns false.
-
- \sa setCommitPage()
-*/
-bool QWizardPage::isCommitPage() const
-{
- Q_D(const QWizardPage);
- return d->commit;
-}
-
-/*!
- Sets the text on button \a which to be \a text on this page.
-
- By default, the text on buttons depends on the QWizard::wizardStyle,
- but may be redefined for the wizard as a whole using QWizard::setButtonText().
-
- \sa buttonText(), QWizard::setButtonText(), QWizard::buttonText()
-*/
-void QWizardPage::setButtonText(QWizard::WizardButton which, const QString &text)
-{
- Q_D(QWizardPage);
- d->buttonCustomTexts.insert(which, text);
- if (wizard() && wizard()->currentPage() == this && wizard()->d_func()->btns[which])
- wizard()->d_func()->btns[which]->setText(text);
-}
-
-/*!
- Returns the text on button \a which on this page.
-
- If a text has ben set using setButtonText(), this text is returned.
- Otherwise, if a text has been set using QWizard::setButtonText(),
- this text is returned.
-
- By default, the text on buttons depends on the QWizard::wizardStyle.
- For example, on Mac OS X, the \gui Next button is called \gui
- Continue.
-
- \sa setButtonText(), QWizard::buttonText(), QWizard::setButtonText()
-*/
-QString QWizardPage::buttonText(QWizard::WizardButton which) const
-{
- Q_D(const QWizardPage);
-
- if (d->buttonCustomTexts.contains(which))
- return d->buttonCustomTexts.value(which);
-
- if (wizard())
- return wizard()->buttonText(which);
-
- return QString();
-}
-
-/*!
- This virtual function is called by QWizard::nextId() to find
- out which page to show when the user clicks the \gui Next button.
-
- The return value is the ID of the next page, or -1 if no page follows.
-
- By default, this function returns the lowest ID greater than the ID
- of the current page, or -1 if there is no such ID.
-
- By reimplementing this function, you can specify a dynamic page
- order. For example:
-
- \snippet examples/dialogs/licensewizard/licensewizard.cpp 18
-
- \sa QWizard::nextId()
-*/
-int QWizardPage::nextId() const
-{
- Q_D(const QWizardPage);
-
- if (!d->wizard)
- return -1;
-
- bool foundCurrentPage = false;
-
- const QWizardPrivate::PageMap &pageMap = d->wizard->d_func()->pageMap;
- QWizardPrivate::PageMap::const_iterator i = pageMap.constBegin();
- QWizardPrivate::PageMap::const_iterator end = pageMap.constEnd();
-
- for (; i != end; ++i) {
- if (i.value() == this) {
- foundCurrentPage = true;
- } else if (foundCurrentPage) {
- return i.key();
- }
- }
- return -1;
-}
-
-/*!
- \fn void QWizardPage::completeChanged()
-
- This signal is emitted whenever the complete state of the page
- (i.e., the value of isComplete()) changes.
-
- If you reimplement isComplete(), make sure to emit
- completeChanged() whenever the value of isComplete() changes, to
- ensure that QWizard updates the enabled or disabled state of its
- buttons.
-
- \sa isComplete()
-*/
-
-/*!
- Sets the value of the field called \a name to \a value.
-
- This function can be used to set fields on any page of the wizard.
- It is equivalent to calling
- wizard()->\l{QWizard::setField()}{setField(\a name, \a value)}.
-
- \sa QWizard::setField(), field(), registerField()
-*/
-void QWizardPage::setField(const QString &name, const QVariant &value)
-{
- Q_D(QWizardPage);
- if (!d->wizard)
- return;
- d->wizard->setField(name, value);
-}
-
-/*!
- Returns the value of the field called \a name.
-
- This function can be used to access fields on any page of the
- wizard. It is equivalent to calling
- wizard()->\l{QWizard::field()}{field(\a name)}.
-
- Example:
-
- \snippet examples/dialogs/classwizard/classwizard.cpp 17
-
- \sa QWizard::field(), setField(), registerField()
-*/
-QVariant QWizardPage::field(const QString &name) const
-{
- Q_D(const QWizardPage);
- if (!d->wizard)
- return QVariant();
- return d->wizard->field(name);
-}
-
-/*!
- Creates a field called \a name associated with the given \a
- property of the given \a widget. From then on, that property
- becomes accessible using field() and setField().
-
- Fields are global to the entire wizard and make it easy for any
- single page to access information stored by another page, without
- having to put all the logic in QWizard or having the pages know
- explicitly about each other.
-
- If \a name ends with an asterisk (\c *), the field is a mandatory
- field. When a page has mandatory fields, the \gui Next and/or
- \gui Finish buttons are enabled only when all mandatory fields
- are filled. This requires a \a changedSignal to be specified, to
- tell QWizard to recheck the value stored by the mandatory field.
-
- QWizard knows the most common Qt widgets. For these (or their
- subclasses), you don't need to specify a \a property or a \a
- changedSignal. The table below lists these widgets:
-
- \table
- \header \o Widget \o Property \o Change Notification Signal
- \row \o QAbstractButton \o bool \l{QAbstractButton::}{checked} \o \l{QAbstractButton::}{toggled()}
- \row \o QAbstractSlider \o int \l{QAbstractSlider::}{value} \o \l{QAbstractSlider::}{valueChanged()}
- \row \o QComboBox \o int \l{QComboBox::}{currentIndex} \o \l{QComboBox::}{currentIndexChanged()}
- \row \o QDateTimeEdit \o QDateTime \l{QDateTimeEdit::}{dateTime} \o \l{QDateTimeEdit::}{dateTimeChanged()}
- \row \o QLineEdit \o QString \l{QLineEdit::}{text} \o \l{QLineEdit::}{textChanged()}
- \row \o QListWidget \o int \l{QListWidget::}{currentRow} \o \l{QListWidget::}{currentRowChanged()}
- \row \o QSpinBox \o int \l{QSpinBox::}{value} \o \l{QSpinBox::}{valueChanged()}
- \endtable
-
- You can use QWizard::setDefaultProperty() to add entries to this
- table or to override existing entries.
-
- To consider a field "filled", QWizard simply checks that their
- current value doesn't equal their original value (the value they
- had before initializePage() was called). For QLineEdit, it also
- checks that
- \l{QLineEdit::hasAcceptableInput()}{hasAcceptableInput()} returns
- true, to honor any validator or mask.
-
- QWizard's mandatory field mechanism is provided for convenience.
- It can be bypassed by reimplementing QWizardPage::isComplete().
-
- \sa field(), setField(), QWizard::setDefaultProperty()
-*/
-void QWizardPage::registerField(const QString &name, QWidget *widget, const char *property,
- const char *changedSignal)
-{
- Q_D(QWizardPage);
- QWizardField field(this, name, widget, property, changedSignal);
- if (d->wizard) {
- d->wizard->d_func()->addField(field);
- } else {
- d->pendingFields += field;
- }
-}
-
-/*!
- Returns the wizard associated with this page, or 0 if this page
- hasn't been inserted into a QWizard yet.
-
- \sa QWizard::addPage(), QWizard::setPage()
-*/
-QWizard *QWizardPage::wizard() const
-{
- Q_D(const QWizardPage);
- return d->wizard;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qwizard.cpp"
-
-#endif // QT_NO_WIZARD
diff --git a/src/gui/dialogs/qwizard.h b/src/gui/dialogs/qwizard.h
deleted file mode 100644
index 148a5924b9..0000000000
--- a/src/gui/dialogs/qwizard.h
+++ /dev/null
@@ -1,268 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIZARD_H
-#define QWIZARD_H
-
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_WIZARD
-
-class QAbstractButton;
-class QWizardPage;
-class QWizardPrivate;
-
-class Q_GUI_EXPORT QWizard : public QDialog
-{
- Q_OBJECT
- Q_ENUMS(WizardStyle WizardOption)
- Q_FLAGS(WizardOptions)
- Q_PROPERTY(WizardStyle wizardStyle READ wizardStyle WRITE setWizardStyle)
- Q_PROPERTY(WizardOptions options READ options WRITE setOptions)
- Q_PROPERTY(Qt::TextFormat titleFormat READ titleFormat WRITE setTitleFormat)
- Q_PROPERTY(Qt::TextFormat subTitleFormat READ subTitleFormat WRITE setSubTitleFormat)
- Q_PROPERTY(int startId READ startId WRITE setStartId)
- Q_PROPERTY(int currentId READ currentId NOTIFY currentIdChanged)
-
-public:
- enum WizardButton {
- BackButton,
- NextButton,
- CommitButton,
- FinishButton,
- CancelButton,
- HelpButton,
- CustomButton1,
- CustomButton2,
- CustomButton3,
- Stretch,
-
- NoButton = -1,
- NStandardButtons = 6,
- NButtons = 9
- };
-
- enum WizardPixmap {
- WatermarkPixmap,
- LogoPixmap,
- BannerPixmap,
- BackgroundPixmap,
- NPixmaps
- };
-
- enum WizardStyle {
- ClassicStyle,
- ModernStyle,
- MacStyle,
- AeroStyle,
- NStyles
- };
-
- enum WizardOption {
- IndependentPages = 0x00000001,
- IgnoreSubTitles = 0x00000002,
- ExtendedWatermarkPixmap = 0x00000004,
- NoDefaultButton = 0x00000008,
- NoBackButtonOnStartPage = 0x00000010,
- NoBackButtonOnLastPage = 0x00000020,
- DisabledBackButtonOnLastPage = 0x00000040,
- HaveNextButtonOnLastPage = 0x00000080,
- HaveFinishButtonOnEarlyPages = 0x00000100,
- NoCancelButton = 0x00000200,
- CancelButtonOnLeft = 0x00000400,
- HaveHelpButton = 0x00000800,
- HelpButtonOnRight = 0x00001000,
- HaveCustomButton1 = 0x00002000,
- HaveCustomButton2 = 0x00004000,
- HaveCustomButton3 = 0x00008000
- };
-
- Q_DECLARE_FLAGS(WizardOptions, WizardOption)
-
- explicit QWizard(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QWizard();
-
- int addPage(QWizardPage *page);
- void setPage(int id, QWizardPage *page);
- void removePage(int id);
- QWizardPage *page(int id) const;
- bool hasVisitedPage(int id) const;
- QList<int> visitedPages() const; // ### visitedIds()?
- QList<int> pageIds() const;
- void setStartId(int id);
- int startId() const;
- QWizardPage *currentPage() const;
- int currentId() const;
-
- virtual bool validateCurrentPage();
- virtual int nextId() const;
-
- void setField(const QString &name, const QVariant &value);
- QVariant field(const QString &name) const;
-
- void setWizardStyle(WizardStyle style);
- WizardStyle wizardStyle() const;
-
- void setOption(WizardOption option, bool on = true);
- bool testOption(WizardOption option) const;
- void setOptions(WizardOptions options);
- WizardOptions options() const;
-
- void setButtonText(WizardButton which, const QString &text);
- QString buttonText(WizardButton which) const;
- void setButtonLayout(const QList<WizardButton> &layout);
- void setButton(WizardButton which, QAbstractButton *button);
- QAbstractButton *button(WizardButton which) const;
-
- void setTitleFormat(Qt::TextFormat format);
- Qt::TextFormat titleFormat() const;
- void setSubTitleFormat(Qt::TextFormat format);
- Qt::TextFormat subTitleFormat() const;
- void setPixmap(WizardPixmap which, const QPixmap &pixmap);
- QPixmap pixmap(WizardPixmap which) const;
-
- void setSideWidget(QWidget *widget);
- QWidget *sideWidget() const;
-
- void setDefaultProperty(const char *className, const char *property,
- const char *changedSignal);
-
- void setVisible(bool visible);
- QSize sizeHint() const;
-
-Q_SIGNALS:
- void currentIdChanged(int id);
- void helpRequested();
- void customButtonClicked(int which);
- void pageAdded(int id);
- void pageRemoved(int id);
-
-public Q_SLOTS:
- void back();
- void next();
- void restart();
-
-protected:
- bool event(QEvent *event);
- void resizeEvent(QResizeEvent *event);
- void paintEvent(QPaintEvent *event);
-#if defined(Q_WS_WIN)
- bool winEvent(MSG * message, long * result);
-#endif
- void done(int result);
- virtual void initializePage(int id);
- virtual void cleanupPage(int id);
-
-private:
- Q_DISABLE_COPY(QWizard)
- Q_DECLARE_PRIVATE(QWizard)
- Q_PRIVATE_SLOT(d_func(), void _q_emitCustomButtonClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_updateButtonStates())
- Q_PRIVATE_SLOT(d_func(), void _q_handleFieldObjectDestroyed(QObject *))
-
- friend class QWizardPage;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QWizard::WizardOptions)
-
-class QWizardPagePrivate;
-
-class Q_GUI_EXPORT QWizardPage : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(QString title READ title WRITE setTitle)
- Q_PROPERTY(QString subTitle READ subTitle WRITE setSubTitle)
-
-public:
- QWizardPage(QWidget *parent = 0);
-
- void setTitle(const QString &title);
- QString title() const;
- void setSubTitle(const QString &subTitle);
- QString subTitle() const;
- void setPixmap(QWizard::WizardPixmap which, const QPixmap &pixmap);
- QPixmap pixmap(QWizard::WizardPixmap which) const;
- void setFinalPage(bool finalPage);
- bool isFinalPage() const;
- void setCommitPage(bool commitPage);
- bool isCommitPage() const;
- void setButtonText(QWizard::WizardButton which, const QString &text);
- QString buttonText(QWizard::WizardButton which) const;
-
- virtual void initializePage();
- virtual void cleanupPage();
- virtual bool validatePage();
- virtual bool isComplete() const;
- virtual int nextId() const;
-
-Q_SIGNALS:
- void completeChanged();
-
-protected:
- void setField(const QString &name, const QVariant &value);
- QVariant field(const QString &name) const;
- void registerField(const QString &name, QWidget *widget, const char *property = 0,
- const char *changedSignal = 0);
- QWizard *wizard() const;
-
-private:
- Q_DISABLE_COPY(QWizardPage)
- Q_DECLARE_PRIVATE(QWizardPage)
- Q_PRIVATE_SLOT(d_func(), void _q_maybeEmitCompleteChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_updateCachedCompleteState())
-
- friend class QWizard;
- friend class QWizardPrivate;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_WIZARD
-
-#endif // QWIZARD_H
diff --git a/src/gui/dialogs/qwizard_win.cpp b/src/gui/dialogs/qwizard_win.cpp
deleted file mode 100644
index 3480c6853c..0000000000
--- a/src/gui/dialogs/qwizard_win.cpp
+++ /dev/null
@@ -1,759 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_WIZARD
-#ifndef QT_NO_STYLE_WINDOWSVISTA
-
-#include "qwizard_win_p.h"
-#include <private/qsystemlibrary_p.h>
-#include "qwizard.h"
-#include "qpaintengine.h"
-#include "qapplication.h"
-#include <QtGui/QMouseEvent>
-#include <QtGui/QDesktopWidget>
-
-// Note, these tests are duplicates in qwindowsxpstyle_p.h.
-#ifdef Q_CC_GNU
-# include <w32api.h>
-# if (__W32API_MAJOR_VERSION >= 3 || (__W32API_MAJOR_VERSION == 2 && __W32API_MINOR_VERSION >= 5))
-# ifdef _WIN32_WINNT
-# undef _WIN32_WINNT
-# endif
-# define _WIN32_WINNT 0x0501
-# include <commctrl.h>
-# endif
-#endif
-
-#include <uxtheme.h>
-
-QT_BEGIN_NAMESPACE
-
-//DWM related
-typedef struct { //MARGINS
- int cxLeftWidth; // width of left border that retains its size
- int cxRightWidth; // width of right border that retains its size
- int cyTopHeight; // height of top border that retains its size
- int cyBottomHeight; // height of bottom border that retains its size
-} WIZ_MARGINS;
-typedef struct { //DTTOPTS
- DWORD dwSize;
- DWORD dwFlags;
- COLORREF crText;
- COLORREF crBorder;
- COLORREF crShadow;
- int eTextShadowType;
- POINT ptShadowOffset;
- int iBorderSize;
- int iFontPropId;
- int iColorPropId;
- int iStateId;
- BOOL fApplyOverlay;
- int iGlowSize;
-} WIZ_DTTOPTS;
-
-typedef struct {
- DWORD dwFlags;
- DWORD dwMask;
-} WIZ_WTA_OPTIONS;
-
-#define WIZ_WM_THEMECHANGED 0x031A
-#define WIZ_WM_DWMCOMPOSITIONCHANGED 0x031E
-
-enum WIZ_WINDOWTHEMEATTRIBUTETYPE {
- WIZ_WTA_NONCLIENT = 1
-};
-
-#define WIZ_WTNCA_NODRAWCAPTION 0x00000001
-#define WIZ_WTNCA_NODRAWICON 0x00000002
-
-#define WIZ_DT_CENTER 0x00000001 //DT_CENTER
-#define WIZ_DT_VCENTER 0x00000004
-#define WIZ_DT_SINGLELINE 0x00000020
-#define WIZ_DT_NOPREFIX 0x00000800
-
-enum WIZ_NAVIGATIONPARTS { //NAVIGATIONPARTS
- WIZ_NAV_BACKBUTTON = 1,
- WIZ_NAV_FORWARDBUTTON = 2,
- WIZ_NAV_MENUBUTTON = 3,
-};
-
-enum WIZ_NAV_BACKBUTTONSTATES { //NAV_BACKBUTTONSTATES
- WIZ_NAV_BB_NORMAL = 1,
- WIZ_NAV_BB_HOT = 2,
- WIZ_NAV_BB_PRESSED = 3,
- WIZ_NAV_BB_DISABLED = 4,
-};
-
-#define WIZ_TMT_CAPTIONFONT (801) //TMT_CAPTIONFONT
-#define WIZ_DTT_COMPOSITED (1UL << 13) //DTT_COMPOSITED
-#define WIZ_DTT_GLOWSIZE (1UL << 11) //DTT_GLOWSIZE
-
-#define WIZ_WM_NCMOUSELEAVE 674 //WM_NCMOUSELEAVE
-
-#define WIZ_WP_CAPTION 1 //WP_CAPTION
-#define WIZ_CS_ACTIVE 1 //CS_ACTIVE
-#define WIZ_TMT_FILLCOLORHINT 3821 //TMT_FILLCOLORHINT
-#define WIZ_TMT_BORDERCOLORHINT 3822 //TMT_BORDERCOLORHINT
-
-typedef BOOL (WINAPI *PtrDwmDefWindowProc)(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *plResult);
-typedef HRESULT (WINAPI *PtrDwmIsCompositionEnabled)(BOOL* pfEnabled);
-typedef HRESULT (WINAPI *PtrDwmExtendFrameIntoClientArea)(HWND hWnd, const WIZ_MARGINS* pMarInset);
-typedef HRESULT (WINAPI *PtrSetWindowThemeAttribute)(HWND hwnd, enum WIZ_WINDOWTHEMEATTRIBUTETYPE eAttribute, PVOID pvAttribute, DWORD cbAttribute);
-
-static PtrDwmDefWindowProc pDwmDefWindowProc = 0;
-static PtrDwmIsCompositionEnabled pDwmIsCompositionEnabled = 0;
-static PtrDwmExtendFrameIntoClientArea pDwmExtendFrameIntoClientArea = 0;
-static PtrSetWindowThemeAttribute pSetWindowThemeAttribute = 0;
-
-//Theme related
-typedef bool (WINAPI *PtrIsAppThemed)();
-typedef bool (WINAPI *PtrIsThemeActive)();
-typedef HANDLE (WINAPI *PtrOpenThemeData)(HWND hwnd, LPCWSTR pszClassList);
-typedef HRESULT (WINAPI *PtrCloseThemeData)(HANDLE hTheme);
-typedef HRESULT (WINAPI *PtrGetThemeSysFont)(HANDLE hTheme, int iFontId, LOGFONTW *plf);
-typedef HRESULT (WINAPI *PtrDrawThemeTextEx)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, LPCWSTR pszText, int cchText, DWORD dwTextFlags, LPRECT pRect, const WIZ_DTTOPTS *pOptions);
-typedef HRESULT (WINAPI *PtrDrawThemeBackground)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const RECT *pClipRect);
-typedef HRESULT (WINAPI *PtrGetThemePartSize)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, OPTIONAL RECT *prc, enum THEMESIZE eSize, OUT SIZE *psz);
-typedef HRESULT (WINAPI *PtrGetThemeColor)(HANDLE hTheme, int iPartId, int iStateId, int iPropId, OUT COLORREF *pColor);
-
-static PtrIsAppThemed pIsAppThemed = 0;
-static PtrIsThemeActive pIsThemeActive = 0;
-static PtrOpenThemeData pOpenThemeData = 0;
-static PtrCloseThemeData pCloseThemeData = 0;
-static PtrGetThemeSysFont pGetThemeSysFont = 0;
-static PtrDrawThemeTextEx pDrawThemeTextEx = 0;
-static PtrDrawThemeBackground pDrawThemeBackground = 0;
-static PtrGetThemePartSize pGetThemePartSize = 0;
-static PtrGetThemeColor pGetThemeColor = 0;
-
-bool QVistaHelper::is_vista = false;
-QVistaHelper::VistaState QVistaHelper::cachedVistaState = QVistaHelper::Dirty;
-
-/******************************************************************************
-** QVistaBackButton
-*/
-
-QVistaBackButton::QVistaBackButton(QWidget *widget)
- : QAbstractButton(widget)
-{
- setFocusPolicy(Qt::NoFocus);
-}
-
-QSize QVistaBackButton::sizeHint() const
-{
- ensurePolished();
- int size = int(QStyleHelper::dpiScaled(32));
- int width = size, height = size;
-/*
- HANDLE theme = pOpenThemeData(0, L"Navigation");
- SIZE size;
- if (pGetThemePartSize(theme, 0, WIZ_NAV_BACKBUTTON, WIZ_NAV_BB_NORMAL, 0, TS_TRUE, &size) == S_OK) {
- width = size.cx;
- height = size.cy;
- }
-*/
- return QSize(width, height);
-}
-
-void QVistaBackButton::enterEvent(QEvent *event)
-{
- if (isEnabled())
- update();
- QAbstractButton::enterEvent(event);
-}
-
-void QVistaBackButton::leaveEvent(QEvent *event)
-{
- if (isEnabled())
- update();
- QAbstractButton::leaveEvent(event);
-}
-
-void QVistaBackButton::paintEvent(QPaintEvent *)
-{
- QPainter p(this);
- QRect r = rect();
- HANDLE theme = pOpenThemeData(0, L"Navigation");
- //RECT rect;
- RECT clipRect;
- int xoffset = QWidget::mapToParent(r.topLeft()).x() - 1;
- int yoffset = QWidget::mapToParent(r.topLeft()).y() - 1;
-
- clipRect.top = r.top() + yoffset;
- clipRect.bottom = r.bottom() + yoffset;
- clipRect.left = r.left() + xoffset;
- clipRect.right = r.right() + xoffset;
-
- int state = WIZ_NAV_BB_NORMAL;
- if (!isEnabled())
- state = WIZ_NAV_BB_DISABLED;
- else if (isDown())
- state = WIZ_NAV_BB_PRESSED;
- else if (underMouse())
- state = WIZ_NAV_BB_HOT;
-
- pDrawThemeBackground(theme, p.paintEngine()->getDC(), WIZ_NAV_BACKBUTTON, state, &clipRect, &clipRect);
-}
-
-/******************************************************************************
-** QVistaHelper
-*/
-
-QVistaHelper::QVistaHelper(QWizard *wizard)
- : QObject(wizard)
- , pressed(false)
- , wizard(wizard)
- , backButton_(0)
-{
- is_vista = resolveSymbols();
- if (is_vista)
- backButton_ = new QVistaBackButton(wizard);
-
- // Handle diff between Windows 7 and Vista
- iconSpacing = QStyleHelper::dpiScaled(7);
- textSpacing = QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7 ?
- iconSpacing : QStyleHelper::dpiScaled(20);
-}
-
-QVistaHelper::~QVistaHelper()
-{
-}
-
-bool QVistaHelper::isCompositionEnabled()
-{
- bool value = is_vista;
- if (is_vista) {
- HRESULT hr;
- BOOL bEnabled;
-
- hr = pDwmIsCompositionEnabled(&bEnabled);
- value = (SUCCEEDED(hr) && bEnabled);
- }
- return value;
-}
-
-bool QVistaHelper::isThemeActive()
-{
- return is_vista && pIsThemeActive();
-}
-
-QVistaHelper::VistaState QVistaHelper::vistaState()
-{
- if (cachedVistaState == Dirty)
- cachedVistaState =
- isCompositionEnabled() ? VistaAero : isThemeActive() ? VistaBasic : Classic;
- return cachedVistaState;
-}
-
-QColor QVistaHelper::basicWindowFrameColor()
-{
- DWORD rgb;
- HANDLE hTheme = pOpenThemeData(QApplication::desktop()->winId(), L"WINDOW");
- pGetThemeColor(
- hTheme, WIZ_WP_CAPTION, WIZ_CS_ACTIVE,
- wizard->isActiveWindow() ? WIZ_TMT_FILLCOLORHINT : WIZ_TMT_BORDERCOLORHINT,
- &rgb);
- BYTE r = GetRValue(rgb);
- BYTE g = GetGValue(rgb);
- BYTE b = GetBValue(rgb);
- return QColor(r, g, b);
-}
-
-bool QVistaHelper::setDWMTitleBar(TitleBarChangeType type)
-{
- bool value = false;
- if (vistaState() == VistaAero) {
- WIZ_MARGINS mar = {0};
- if (type == NormalTitleBar)
- mar.cyTopHeight = 0;
- else
- mar.cyTopHeight = titleBarSize() + topOffset();
- HRESULT hr = pDwmExtendFrameIntoClientArea(wizard->winId(), &mar);
- value = SUCCEEDED(hr);
- }
- return value;
-}
-
-void QVistaHelper::drawTitleBar(QPainter *painter)
-{
- HDC hdc = painter->paintEngine()->getDC();
-
- if (vistaState() == VistaAero)
- drawBlackRect(QRect(0, 0, wizard->width(),
- titleBarSize() + topOffset()), hdc);
- Q_ASSERT(backButton_);
- const int btnTop = backButton_->mapToParent(QPoint()).y();
- const int btnHeight = backButton_->size().height();
- const int verticalCenter = (btnTop + btnHeight / 2) - 1;
-
- const QString text = wizard->window()->windowTitle();
- const QFont font = QApplication::font("QWorkspaceTitleBar");
- const QFontMetrics fontMetrics(font);
- const QRect brect = fontMetrics.boundingRect(text);
- int textHeight = brect.height();
- int textWidth = brect.width();
- int glowOffset = 0;
-
- if (vistaState() == VistaAero) {
- textHeight += 2 * glowSize();
- textWidth += 2 * glowSize();
- glowOffset = glowSize();
- }
-
- drawTitleText(
- painter, text,
- QRect(titleOffset() - glowOffset, verticalCenter - textHeight / 2, textWidth, textHeight),
- hdc);
-
- if (!wizard->windowIcon().isNull()) {
- QRect rect(leftMargin(), verticalCenter - iconSize() / 2, iconSize(), iconSize());
- HICON hIcon = wizard->windowIcon().pixmap(iconSize()).toWinHICON();
- DrawIconEx(hdc, rect.left(), rect.top(), hIcon, 0, 0, 0, NULL, DI_NORMAL | DI_COMPAT);
- DestroyIcon(hIcon);
- }
-}
-
-void QVistaHelper::setTitleBarIconAndCaptionVisible(bool visible)
-{
- if (is_vista) {
- WIZ_WTA_OPTIONS opt;
- opt.dwFlags = WIZ_WTNCA_NODRAWICON | WIZ_WTNCA_NODRAWCAPTION;
- if (visible)
- opt.dwMask = 0;
- else
- opt.dwMask = WIZ_WTNCA_NODRAWICON | WIZ_WTNCA_NODRAWCAPTION;
- pSetWindowThemeAttribute(wizard->winId(), WIZ_WTA_NONCLIENT, &opt, sizeof(WIZ_WTA_OPTIONS));
- }
-}
-
-bool QVistaHelper::winEvent(MSG* msg, long* result)
-{
- bool retval = true;
-
- switch (msg->message) {
- case WM_NCHITTEST: {
- LRESULT lResult;
- pDwmDefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam, &lResult);
- if (lResult == HTCLOSE || lResult == HTMAXBUTTON || lResult == HTMINBUTTON || lResult == HTHELP)
- *result = lResult;
- else
- *result = DefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam);
- break;
- }
- case WM_NCMOUSEMOVE:
- case WM_NCLBUTTONDOWN:
- case WM_NCLBUTTONUP:
- case WIZ_WM_NCMOUSELEAVE: {
- LRESULT lResult;
- pDwmDefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam, &lResult);
- *result = DefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam);
- break;
- }
- case WM_NCCALCSIZE: {
- NCCALCSIZE_PARAMS* lpncsp = (NCCALCSIZE_PARAMS*)msg->lParam;
- *result = DefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam);
- lpncsp->rgrc[0].top -= (vistaState() == VistaAero ? titleBarSize() : 0);
- break;
- }
- default:
- retval = false;
- }
-
- return retval;
-}
-
-void QVistaHelper::setMouseCursor(QPoint pos)
-{
-#ifndef QT_NO_CURSOR
- if (rtTop.contains(pos))
- wizard->setCursor(Qt::SizeVerCursor);
- else
- wizard->setCursor(Qt::ArrowCursor);
-#endif
-}
-
-void QVistaHelper::mouseEvent(QEvent *event)
-{
- switch (event->type()) {
- case QEvent::MouseMove:
- mouseMoveEvent(static_cast<QMouseEvent *>(event));
- break;
- case QEvent::MouseButtonPress:
- mousePressEvent(static_cast<QMouseEvent *>(event));
- break;
- case QEvent::MouseButtonRelease:
- mouseReleaseEvent(static_cast<QMouseEvent *>(event));
- break;
- default:
- break;
- }
-}
-
-// The following hack ensures that the titlebar is updated correctly
-// when the wizard style changes to and from AeroStyle. Specifically,
-// this function causes a Windows message of type WM_NCCALCSIZE to
-// be triggered.
-void QVistaHelper::setWindowPosHack()
-{
- const int x = wizard->geometry().x(); // ignored by SWP_NOMOVE
- const int y = wizard->geometry().y(); // ignored by SWP_NOMOVE
- const int w = wizard->width();
- const int h = wizard->height();
- SetWindowPos(wizard->winId(), 0, x, y, w, h, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
-}
-
-// The following hack allows any QWidget subclass to access
-// QWidgetPrivate::topData() without being declared as a
-// friend by QWidget.
-class QHackWidget : public QWidget
-{
-public:
- Q_DECLARE_PRIVATE(QWidget)
- QTLWExtra* topData() { return d_func()->topData(); }
-};
-
-void QVistaHelper::collapseTopFrameStrut()
-{
- QTLWExtra *top = ((QHackWidget *)wizard)->d_func()->topData();
- int x1, y1, x2, y2;
- top->frameStrut.getCoords(&x1, &y1, &x2, &y2);
- top->frameStrut.setCoords(x1, 0, x2, y2);
-}
-
-bool QVistaHelper::handleWinEvent(MSG *message, long *result)
-{
- if (message->message == WIZ_WM_THEMECHANGED || message->message == WIZ_WM_DWMCOMPOSITIONCHANGED)
- cachedVistaState = Dirty;
-
- bool status = false;
- if (wizard->wizardStyle() == QWizard::AeroStyle && vistaState() == VistaAero) {
- status = winEvent(message, result);
- if (message->message == WM_NCCALCSIZE) {
- if (status)
- collapseTopFrameStrut();
- } else if (message->message == WM_NCPAINT) {
- wizard->update();
- }
- }
- return status;
-}
-
-void QVistaHelper::resizeEvent(QResizeEvent * event)
-{
- Q_UNUSED(event);
- rtTop = QRect (0, 0, wizard->width(), frameSize());
- int height = captionSize() + topOffset();
- if (vistaState() == VistaBasic)
- height -= titleBarSize();
- rtTitle = QRect (0, frameSize(), wizard->width(), height);
-}
-
-void QVistaHelper::paintEvent(QPaintEvent *event)
-{
- Q_UNUSED(event);
- QPainter painter(wizard);
- drawTitleBar(&painter);
-}
-
-void QVistaHelper::mouseMoveEvent(QMouseEvent *event)
-{
- if (wizard->windowState() & Qt::WindowMaximized) {
- event->ignore();
- return;
- }
-
- QRect rect = wizard->geometry();
- if (pressed) {
- switch (change) {
- case resizeTop:
- {
- const int dy = event->pos().y() - pressedPos.y();
- if ((dy > 0 && rect.height() > wizard->minimumHeight())
- || (dy < 0 && rect.height() < wizard->maximumHeight()))
- rect.setTop(rect.top() + dy);
- }
- break;
- case movePosition: {
- QPoint newPos = event->pos() - pressedPos;
- rect.moveLeft(rect.left() + newPos.x());
- rect.moveTop(rect.top() + newPos.y());
- break; }
- default:
- break;
- }
- wizard->setGeometry(rect);
-
- } else if (vistaState() == VistaAero) {
- setMouseCursor(event->pos());
- }
- event->ignore();
-}
-
-void QVistaHelper::mousePressEvent(QMouseEvent *event)
-{
- change = noChange;
-
- if (wizard->windowState() & Qt::WindowMaximized) {
- event->ignore();
- return;
- }
-
- if (rtTitle.contains(event->pos())) {
- change = movePosition;
- } else if (rtTop.contains(event->pos()))
- change = (vistaState() == VistaAero) ? resizeTop : movePosition;
-
- if (change != noChange) {
- if (vistaState() == VistaAero)
- setMouseCursor(event->pos());
- pressed = true;
- pressedPos = event->pos();
- } else {
- event->ignore();
- }
-}
-
-void QVistaHelper::mouseReleaseEvent(QMouseEvent *event)
-{
- change = noChange;
- if (pressed) {
- pressed = false;
- wizard->releaseMouse();
- if (vistaState() == VistaAero)
- setMouseCursor(event->pos());
- }
- event->ignore();
-}
-
-bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
-{
- if (obj != wizard)
- return QObject::eventFilter(obj, event);
-
- if (event->type() == QEvent::MouseMove) {
- QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
- long result;
- MSG msg;
- msg.message = WM_NCHITTEST;
- msg.wParam = 0;
- msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
- msg.hwnd = wizard->winId();
- winEvent(&msg, &result);
- msg.wParam = result;
- msg.message = WM_NCMOUSEMOVE;
- winEvent(&msg, &result);
- } else if (event->type() == QEvent::MouseButtonPress) {
- QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
- long result;
- MSG msg;
- msg.message = WM_NCHITTEST;
- msg.wParam = 0;
- msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
- msg.hwnd = wizard->winId();
- winEvent(&msg, &result);
- msg.wParam = result;
- msg.message = WM_NCLBUTTONDOWN;
- winEvent(&msg, &result);
- } else if (event->type() == QEvent::MouseButtonRelease) {
- QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
- long result;
- MSG msg;
- msg.message = WM_NCHITTEST;
- msg.wParam = 0;
- msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
- msg.hwnd = wizard->winId();
- winEvent(&msg, &result);
- msg.wParam = result;
- msg.message = WM_NCLBUTTONUP;
- winEvent(&msg, &result);
- }
-
- return false;
-}
-
-HFONT QVistaHelper::getCaptionFont(HANDLE hTheme)
-{
- LOGFONT lf = {0};
-
- if (!hTheme)
- pGetThemeSysFont(hTheme, WIZ_TMT_CAPTIONFONT, &lf);
- else
- {
- NONCLIENTMETRICS ncm = {sizeof(NONCLIENTMETRICS)};
- SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, false);
- lf = ncm.lfMessageFont;
- }
- return CreateFontIndirect(&lf);
-}
-
-bool QVistaHelper::drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc)
-{
- bool value = false;
- if (vistaState() == VistaAero) {
- HANDLE hTheme = pOpenThemeData(QApplication::desktop()->winId(), L"WINDOW");
- if (!hTheme) return false;
- // Set up a memory DC and bitmap that we'll draw into
- HDC dcMem;
- HBITMAP bmp;
- BITMAPINFO dib = {{0}};
- dcMem = CreateCompatibleDC(hdc);
-
- dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- dib.bmiHeader.biWidth = rect.width();
- dib.bmiHeader.biHeight = -rect.height();
- dib.bmiHeader.biPlanes = 1;
- dib.bmiHeader.biBitCount = 32;
- dib.bmiHeader.biCompression = BI_RGB;
-
- bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
-
- // Set up the DC
- HFONT hCaptionFont = getCaptionFont(hTheme);
- HBITMAP hOldBmp = (HBITMAP)SelectObject(dcMem, (HGDIOBJ) bmp);
- HFONT hOldFont = (HFONT)SelectObject(dcMem, (HGDIOBJ) hCaptionFont);
-
- // Draw the text!
- WIZ_DTTOPTS dto = { sizeof(WIZ_DTTOPTS) };
- const UINT uFormat = WIZ_DT_SINGLELINE|WIZ_DT_CENTER|WIZ_DT_VCENTER|WIZ_DT_NOPREFIX;
- RECT rctext ={0,0, rect.width(), rect.height()};
-
- dto.dwFlags = WIZ_DTT_COMPOSITED|WIZ_DTT_GLOWSIZE;
- dto.iGlowSize = glowSize();
-
- pDrawThemeTextEx(hTheme, dcMem, 0, 0, (LPCWSTR)text.utf16(), -1, uFormat, &rctext, &dto );
- BitBlt(hdc, rect.left(), rect.top(), rect.width(), rect.height(), dcMem, 0, 0, SRCCOPY);
- SelectObject(dcMem, (HGDIOBJ) hOldBmp);
- SelectObject(dcMem, (HGDIOBJ) hOldFont);
- DeleteObject(bmp);
- DeleteObject(hCaptionFont);
- DeleteDC(dcMem);
- //ReleaseDC(hwnd, hdc);
- } else if (vistaState() == VistaBasic) {
- painter->drawText(rect, text);
- }
- return value;
-}
-
-bool QVistaHelper::drawBlackRect(const QRect &rect, HDC hdc)
-{
- bool value = false;
- if (vistaState() == VistaAero) {
- // Set up a memory DC and bitmap that we'll draw into
- HDC dcMem;
- HBITMAP bmp;
- BITMAPINFO dib = {{0}};
- dcMem = CreateCompatibleDC(hdc);
-
- dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- dib.bmiHeader.biWidth = rect.width();
- dib.bmiHeader.biHeight = -rect.height();
- dib.bmiHeader.biPlanes = 1;
- dib.bmiHeader.biBitCount = 32;
- dib.bmiHeader.biCompression = BI_RGB;
-
- bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
- HBITMAP hOldBmp = (HBITMAP)SelectObject(dcMem, (HGDIOBJ) bmp);
-
- BitBlt(hdc, rect.left(), rect.top(), rect.width(), rect.height(), dcMem, 0, 0, SRCCOPY);
- SelectObject(dcMem, (HGDIOBJ) hOldBmp);
-
- DeleteObject(bmp);
- DeleteDC(dcMem);
- }
- return value;
-}
-
-bool QVistaHelper::resolveSymbols()
-{
- static bool tried = false;
- if (!tried) {
- tried = true;
- QSystemLibrary dwmLib(L"dwmapi");
- pDwmIsCompositionEnabled =
- (PtrDwmIsCompositionEnabled)dwmLib.resolve("DwmIsCompositionEnabled");
- if (pDwmIsCompositionEnabled) {
- pDwmDefWindowProc = (PtrDwmDefWindowProc)dwmLib.resolve("DwmDefWindowProc");
- pDwmExtendFrameIntoClientArea =
- (PtrDwmExtendFrameIntoClientArea)dwmLib.resolve("DwmExtendFrameIntoClientArea");
- }
- QSystemLibrary themeLib(L"uxtheme");
- pIsAppThemed = (PtrIsAppThemed)themeLib.resolve("IsAppThemed");
- if (pIsAppThemed) {
- pDrawThemeBackground = (PtrDrawThemeBackground)themeLib.resolve("DrawThemeBackground");
- pGetThemePartSize = (PtrGetThemePartSize)themeLib.resolve("GetThemePartSize");
- pGetThemeColor = (PtrGetThemeColor)themeLib.resolve("GetThemeColor");
- pIsThemeActive = (PtrIsThemeActive)themeLib.resolve("IsThemeActive");
- pOpenThemeData = (PtrOpenThemeData)themeLib.resolve("OpenThemeData");
- pCloseThemeData = (PtrCloseThemeData)themeLib.resolve("CloseThemeData");
- pGetThemeSysFont = (PtrGetThemeSysFont)themeLib.resolve("GetThemeSysFont");
- pDrawThemeTextEx = (PtrDrawThemeTextEx)themeLib.resolve("DrawThemeTextEx");
- pSetWindowThemeAttribute = (PtrSetWindowThemeAttribute)themeLib.resolve("SetWindowThemeAttribute");
- }
- }
-
- return (
- pDwmIsCompositionEnabled != 0
- && pDwmDefWindowProc != 0
- && pDwmExtendFrameIntoClientArea != 0
- && pIsAppThemed != 0
- && pDrawThemeBackground != 0
- && pGetThemePartSize != 0
- && pGetThemeColor != 0
- && pIsThemeActive != 0
- && pOpenThemeData != 0
- && pCloseThemeData != 0
- && pGetThemeSysFont != 0
- && pDrawThemeTextEx != 0
- && pSetWindowThemeAttribute != 0
- );
-}
-
-int QVistaHelper::titleOffset()
-{
- int iconOffset = wizard ->windowIcon().isNull() ? 0 : iconSize() + textSpacing;
- return leftMargin() + iconOffset;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSVISTA
-
-#endif // QT_NO_WIZARD
diff --git a/src/gui/dialogs/qwizard_win_p.h b/src/gui/dialogs/qwizard_win_p.h
deleted file mode 100644
index b76f08264d..0000000000
--- a/src/gui/dialogs/qwizard_win_p.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIZARD_WIN_P_H
-#define QWIZARD_WIN_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QT_NO_WIZARD
-#ifndef QT_NO_STYLE_WINDOWSVISTA
-
-#include <qt_windows.h>
-#include <qobject.h>
-#include <qwidget.h>
-#include <qabstractbutton.h>
-#include <QtGui/private/qwidget_p.h>
-#include <QtGui/private/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QVistaBackButton : public QAbstractButton
-{
-public:
- QVistaBackButton(QWidget *widget);
-
- QSize sizeHint() const;
- inline QSize minimumSizeHint() const
- { return sizeHint(); }
-
- void enterEvent(QEvent *event);
- void leaveEvent(QEvent *event);
- void paintEvent(QPaintEvent *event);
-};
-
-class QWizard;
-
-class QVistaHelper : public QObject
-{
-public:
- QVistaHelper(QWizard *wizard);
- ~QVistaHelper();
- enum TitleBarChangeType { NormalTitleBar, ExtendedTitleBar };
- bool setDWMTitleBar(TitleBarChangeType type);
- void setTitleBarIconAndCaptionVisible(bool visible);
- void mouseEvent(QEvent *event);
- bool handleWinEvent(MSG *message, long *result);
- void resizeEvent(QResizeEvent *event);
- void paintEvent(QPaintEvent *event);
- QVistaBackButton *backButton() const { return backButton_; }
- void disconnectBackButton() { if (backButton_) backButton_->disconnect(); }
- void hideBackButton() { if (backButton_) backButton_->hide(); }
- void setWindowPosHack();
- QColor basicWindowFrameColor();
- enum VistaState { VistaAero, VistaBasic, Classic, Dirty };
- static VistaState vistaState();
- static int titleBarSize() { return frameSize() + captionSize(); }
- static int topPadding() { // padding under text
- return int(QStyleHelper::dpiScaled(
- QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7 ? 4 : 6));
- }
- static int topOffset() {
- static int aeroOffset = QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7 ?
- QStyleHelper::dpiScaled(4) : QStyleHelper::dpiScaled(13);
- return (titleBarSize() + (vistaState() == VistaAero ? aeroOffset : 3)); }
-private:
- static HFONT getCaptionFont(HANDLE hTheme);
- bool drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc);
- static bool drawBlackRect(const QRect &rect, HDC hdc);
-
- static int frameSize() { return GetSystemMetrics(SM_CYSIZEFRAME); }
- static int captionSize() { return GetSystemMetrics(SM_CYCAPTION); }
-
- static int backButtonSize() { return int(QStyleHelper::dpiScaled(30)); }
- static int iconSize() { return 16; } // Standard Aero
- static int glowSize() { return 10; }
- int leftMargin() { return backButton_->isVisible() ? backButtonSize() + iconSpacing : 0; }
-
- int titleOffset();
- bool resolveSymbols();
- void drawTitleBar(QPainter *painter);
- void setMouseCursor(QPoint pos);
- void collapseTopFrameStrut();
- bool winEvent(MSG *message, long *result);
- void mouseMoveEvent(QMouseEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- bool eventFilter(QObject *obj, QEvent *event);
-
- static bool is_vista;
- static VistaState cachedVistaState;
- static bool isCompositionEnabled();
- static bool isThemeActive();
- enum Changes { resizeTop, movePosition, noChange } change;
- QPoint pressedPos;
- bool pressed;
- QRect rtTop;
- QRect rtTitle;
- QWizard *wizard;
- QVistaBackButton *backButton_;
-
- int titleBarOffset; // Extra spacing above the text
- int iconSpacing; // Space between button and icon
- int textSpacing; // Space between icon and text
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSVISTA
-#endif // QT_NO_WIZARD
-#endif // QWIZARD_WIN_P_H
diff --git a/src/gui/effects/effects.pri b/src/gui/effects/effects.pri
deleted file mode 100644
index a21f941866..0000000000
--- a/src/gui/effects/effects.pri
+++ /dev/null
@@ -1,6 +0,0 @@
-HEADERS += effects/qgraphicseffect.h \
- effects/qgraphicseffect_p.h \
- effects/qpixmapfilter_p.h
-
-SOURCES += effects/qgraphicseffect.cpp \
- effects/qpixmapfilter.cpp
diff --git a/src/gui/effects/qgraphicseffect.cpp b/src/gui/effects/qgraphicseffect.cpp
deleted file mode 100644
index 7ba38f6d3a..0000000000
--- a/src/gui/effects/qgraphicseffect.cpp
+++ /dev/null
@@ -1,1235 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsEffect
- \brief The QGraphicsEffect class is the base class for all graphics
- effects.
- \since 4.6
- \ingroup multimedia
- \ingroup graphicsview-api
-
- Effects alter the appearance of elements by hooking into the rendering
- pipeline and operating between the source (e.g., a QGraphicsPixmapItem)
- and the destination device (e.g., QGraphicsView's viewport). Effects can be
- disabled by calling setEnabled(false). If effects are disabled, the source
- is rendered directly.
-
- To add a visual effect to a QGraphicsItem, for example, you can use one of
- the standard effects, or alternately, create your own effect by creating a
- subclass of QGraphicsEffect. The effect can then be installed on the item
- using QGraphicsItem::setGraphicsEffect().
-
- Qt provides the following standard effects:
-
- \list
- \o QGraphicsBlurEffect - blurs the item by a given radius
- \o QGraphicsDropShadowEffect - renders a dropshadow behind the item
- \o QGraphicsColorizeEffect - renders the item in shades of any given color
- \o QGraphicsOpacityEffect - renders the item with an opacity
- \endlist
-
- \table
- \row
- \o{2,1} \img graphicseffect-plain.png
- \row
- \o \img graphicseffect-blur.png
- \o \img graphicseffect-colorize.png
- \row
- \o \img graphicseffect-opacity.png
- \o \img graphicseffect-drop-shadow.png
- \endtable
-
- \img graphicseffect-widget.png
-
- For more information on how to use each effect, refer to the specific
- effect's documentation.
-
- To create your own custom effect, create a subclass of QGraphicsEffect (or
- any other existing effects) and reimplement the virtual function draw().
- This function is called whenever the effect needs to redraw. The draw()
- function takes the painter with which to draw as an argument. For more
- information, refer to the documenation for draw(). In the draw() function
- you can call sourcePixmap() to get a pixmap of the graphics effect source
- which you can then process.
-
- If your effect changes, use update() to request for a redraw. If your
- custom effect changes the bounding rectangle of the source, e.g., a radial
- glow effect may need to apply an extra margin, you can reimplement the
- virtual boundingRectFor() function, and call updateBoundingRect()
- to notify the framework whenever this rectangle changes. The virtual
- sourceChanged() function is called to notify the effects that
- the source has changed in some way - e.g., if the source is a
- QGraphicsRectItem and its rectangle parameters have changed.
-
- \sa QGraphicsItem::setGraphicsEffect(), QWidget::setGraphicsEffect()
-*/
-
-#include "qgraphicseffect_p.h"
-#include "private/qgraphicsitem_p.h"
-
-#include <QtGui/qgraphicsitem.h>
-
-#include <QtGui/qimage.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qpaintengine.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qdebug.h>
-#include <private/qdrawhelper_p.h>
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QGraphicsEffectSource
- \brief The QGraphicsEffectSource class represents the source on which a
- QGraphicsEffect is installed on.
-
- When a QGraphicsEffect is installed on a QGraphicsItem, for example, this
- class will act as a wrapper around QGraphicsItem. Then, calling update() is
- effectively the same as calling QGraphicsItem::update().
-
- QGraphicsEffectSource also provides a pixmap() function which creates a
- pixmap with the source painted into it.
-
- \sa QGraphicsItem::setGraphicsEffect(), QWidget::setGraphicsEffect().
-*/
-
-/*!
- \internal
-*/
-QGraphicsEffectSource::QGraphicsEffectSource(QGraphicsEffectSourcePrivate &dd, QObject *parent)
- : QObject(dd, parent)
-{}
-
-/*!
- Destroys the effect source.
-*/
-QGraphicsEffectSource::~QGraphicsEffectSource()
-{}
-
-/*!
- Returns the bounding rectangle of the source mapped to the given \a system.
-
- \sa draw()
-*/
-QRectF QGraphicsEffectSource::boundingRect(Qt::CoordinateSystem system) const
-{
- return d_func()->boundingRect(system);
-}
-
-/*!
- Returns the bounding rectangle of the source mapped to the given \a system.
-
- Calling this function with Qt::DeviceCoordinates outside of
- QGraphicsEffect::draw() will give undefined results, as there is no device
- context available.
-
- \sa draw()
-*/
-QRectF QGraphicsEffect::sourceBoundingRect(Qt::CoordinateSystem system) const
-{
- Q_D(const QGraphicsEffect);
- if (d->source)
- return d->source->boundingRect(system);
- return QRectF();
-}
-
-/*!
- Returns a pointer to the item if this source is a QGraphicsItem; otherwise
- returns 0.
-
- \sa widget()
-*/
-const QGraphicsItem *QGraphicsEffectSource::graphicsItem() const
-{
- return d_func()->graphicsItem();
-}
-
-/*!
- Returns a pointer to the widget if this source is a QWidget; otherwise
- returns 0.
-
- \sa graphicsItem()
-*/
-const QWidget *QGraphicsEffectSource::widget() const
-{
- return d_func()->widget();
-}
-
-/*!
- Returns a pointer to the style options (used when drawing the source) if
- available; otherwise returns 0.
-
- \sa graphicsItem(), widget()
-*/
-const QStyleOption *QGraphicsEffectSource::styleOption() const
-{
- return d_func()->styleOption();
-}
-
-/*!
- Draws the source using the given \a painter.
-
- This function should only be called from QGraphicsEffect::draw().
-
- \sa QGraphicsEffect::draw()
-*/
-void QGraphicsEffectSource::draw(QPainter *painter)
-{
- Q_D(const QGraphicsEffectSource);
-
- QPixmap pm;
- if (QPixmapCache::find(d->m_cacheKey, &pm)) {
- QTransform restoreTransform;
- if (d->m_cachedSystem == Qt::DeviceCoordinates) {
- restoreTransform = painter->worldTransform();
- painter->setWorldTransform(QTransform());
- }
-
- painter->drawPixmap(d->m_cachedOffset, pm);
-
- if (d->m_cachedSystem == Qt::DeviceCoordinates)
- painter->setWorldTransform(restoreTransform);
- } else {
- d_func()->draw(painter);
- }
-}
-
-/*!
- Draws the source directly using the given \a painter.
-
- This function should only be called from QGraphicsEffect::draw().
-
- For example:
-
- \snippet doc/src/snippets/code/src_gui_effects_qgraphicseffect.cpp 0
-
- \sa QGraphicsEffect::draw()
-*/
-void QGraphicsEffect::drawSource(QPainter *painter)
-{
- Q_D(const QGraphicsEffect);
- if (d->source)
- d->source->draw(painter);
-}
-
-/*!
- Schedules a redraw of the source. Call this function whenever the source
- needs to be redrawn.
-
- \sa QGraphicsEffect::updateBoundingRect(), QWidget::update(),
- QGraphicsItem::update(),
-*/
-void QGraphicsEffectSource::update()
-{
- d_func()->update();
-}
-
-/*!
- Returns true if the source effectively is a pixmap, e.g., a
- QGraphicsPixmapItem.
-
- This function is useful for optimization purposes. For instance, there's no
- point in drawing the source in device coordinates to avoid pixmap scaling
- if this function returns true - the source pixmap will be scaled anyways.
-*/
-bool QGraphicsEffectSource::isPixmap() const
-{
- return d_func()->isPixmap();
-}
-
-/*!
- Returns true if the source effectively is a pixmap, e.g., a
- QGraphicsPixmapItem.
-
- This function is useful for optimization purposes. For instance, there's no
- point in drawing the source in device coordinates to avoid pixmap scaling
- if this function returns true - the source pixmap will be scaled anyways.
-*/
-bool QGraphicsEffect::sourceIsPixmap() const
-{
- return source() ? source()->isPixmap() : false;
-}
-
-/*!
- Returns a pixmap with the source painted into it.
-
- The \a system specifies which coordinate system to be used for the source.
- The optional \a offset parameter returns the offset where the pixmap should
- be painted at using the current painter.
-
- The \a mode determines how much of the effect the pixmap will contain.
- By default, the pixmap will contain the whole effect.
-
- The returned pixmap is bound to the current painter's device rectangle when
- \a system is Qt::DeviceCoordinates.
-
- \sa QGraphicsEffect::draw(), boundingRect()
-*/
-QPixmap QGraphicsEffectSource::pixmap(Qt::CoordinateSystem system, QPoint *offset, QGraphicsEffect::PixmapPadMode mode) const
-{
- Q_D(const QGraphicsEffectSource);
-
- // Shortcut, no cache for childless pixmap items...
- const QGraphicsItem *item = graphicsItem();
- if (system == Qt::LogicalCoordinates && mode == QGraphicsEffect::NoPad && item && isPixmap()) {
- const QGraphicsPixmapItem *pixmapItem = static_cast<const QGraphicsPixmapItem *>(item);
- if (offset)
- *offset = pixmapItem->offset().toPoint();
- return pixmapItem->pixmap();
- }
-
- if (system == Qt::DeviceCoordinates && item
- && !static_cast<const QGraphicsItemEffectSourcePrivate *>(d_func())->info) {
- qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
- return QPixmap();
- }
-
- QPixmap pm;
- if (item && d->m_cachedSystem == system && d->m_cachedMode == mode)
- QPixmapCache::find(d->m_cacheKey, &pm);
-
- if (pm.isNull()) {
- pm = d->pixmap(system, &d->m_cachedOffset, mode);
- d->m_cachedSystem = system;
- d->m_cachedMode = mode;
-
- d->invalidateCache();
- d->m_cacheKey = QPixmapCache::insert(pm);
- }
-
- if (offset)
- *offset = d->m_cachedOffset;
-
- return pm;
-}
-
-/*!
- Returns a pixmap with the source painted into it.
-
- The \a system specifies which coordinate system to be used for the source.
- The optional \a offset parameter returns the offset where the pixmap should
- be painted at using the current painter. For control on how the pixmap is
- padded use the \a mode parameter.
-
- The returned pixmap is clipped to the current painter's device rectangle when
- \a system is Qt::DeviceCoordinates.
-
- Calling this function with Qt::DeviceCoordinates outside of
- QGraphicsEffect::draw() will give undefined results, as there is no device
- context available.
-
- \sa draw(), boundingRect()
-*/
-QPixmap QGraphicsEffect::sourcePixmap(Qt::CoordinateSystem system, QPoint *offset, QGraphicsEffect::PixmapPadMode mode) const
-{
- Q_D(const QGraphicsEffect);
- if (d->source)
- return d->source->pixmap(system, offset, mode);
- return QPixmap();
-}
-
-QGraphicsEffectSourcePrivate::~QGraphicsEffectSourcePrivate()
-{
- invalidateCache();
-}
-
-void QGraphicsEffectSourcePrivate::setCachedOffset(const QPoint &offset)
-{
- m_cachedOffset = offset;
-}
-
-void QGraphicsEffectSourcePrivate::invalidateCache(InvalidateReason reason) const
-{
- if (m_cachedMode != QGraphicsEffect::PadToEffectiveBoundingRect
- && (reason == EffectRectChanged
- || (reason == TransformChanged && m_cachedSystem == Qt::LogicalCoordinates))) {
- return;
- }
-
- QPixmapCache::remove(m_cacheKey);
-}
-
-/*!
- Constructs a new QGraphicsEffect instance having the
- specified \a parent.
-*/
-QGraphicsEffect::QGraphicsEffect(QObject *parent)
- : QObject(*new QGraphicsEffectPrivate, parent)
-{
-}
-
-/*!
- \internal
-*/
-QGraphicsEffect::QGraphicsEffect(QGraphicsEffectPrivate &dd, QObject *parent)
- : QObject(dd, parent)
-{
-}
-
-/*!
- Removes the effect from the source, and destroys the graphics effect.
-*/
-QGraphicsEffect::~QGraphicsEffect()
-{
- Q_D(QGraphicsEffect);
- d->setGraphicsEffectSource(0);
-}
-
-/*!
- Returns the effective bounding rectangle for this effect, i.e., the
- bounding rectangle of the source in device coordinates, adjusted by
- any margins applied by the effect itself.
-
- \sa boundingRectFor(), updateBoundingRect()
-*/
-QRectF QGraphicsEffect::boundingRect() const
-{
- Q_D(const QGraphicsEffect);
- if (d->source)
- return boundingRectFor(d->source->boundingRect());
- return QRectF();
-}
-
-/*!
- Returns the effective bounding rectangle for this effect, given the
- provided \a rect in the device coordinates. When writing
- you own custom effect, you must call updateBoundingRect() whenever any
- parameters are changed that may cause this this function to return a
- different value.
-
- \sa sourceBoundingRect()
-*/
-QRectF QGraphicsEffect::boundingRectFor(const QRectF &rect) const
-{
- return rect;
-}
-
-/*!
- \property QGraphicsEffect::enabled
- \brief whether the effect is enabled or not.
-
- If an effect is disabled, the source will be rendered with as normal, with
- no interference from the effect. If the effect is enabled, the source will
- be rendered with the effect applied.
-
- This property is enabled by default.
-
- Using this property, you can disable certain effects on slow platforms, in
- order to ensure that the user interface is responsive.
-*/
-bool QGraphicsEffect::isEnabled() const
-{
- Q_D(const QGraphicsEffect);
- return d->isEnabled;
-}
-
-void QGraphicsEffect::setEnabled(bool enable)
-{
- Q_D(QGraphicsEffect);
- if (d->isEnabled == enable)
- return;
-
- d->isEnabled = enable;
- if (d->source) {
- d->source->d_func()->effectBoundingRectChanged();
- d->source->d_func()->invalidateCache();
- }
- emit enabledChanged(enable);
-}
-
-/*!
- \fn void QGraphicsEffect::enabledChanged(bool enabled)
-
- This signal is emitted whenever the effect is enabled or disabled.
- The \a enabled parameter holds the effects's new enabled state.
-
- \sa isEnabled()
-*/
-
-/*!
- Schedules a redraw of the effect. Call this function whenever the effect
- needs to be redrawn. This function does not trigger a redraw of the source.
-
- \sa updateBoundingRect()
-*/
-void QGraphicsEffect::update()
-{
- Q_D(QGraphicsEffect);
- if (d->source)
- d->source->update();
-}
-
-/*!
- \internal
-
- Returns a pointer to the source, which provides extra context information
- that can be useful for the effect.
-
- \sa draw()
-*/
-QGraphicsEffectSource *QGraphicsEffect::source() const
-{
- Q_D(const QGraphicsEffect);
- return d->source;
-}
-
-/*!
- This function notifies the effect framework when the effect's bounding
- rectangle has changed. As a custom effect author, you must call this
- function whenever you change any parameters that will cause the virtual
- boundingRectFor() function to return a different value.
-
- This function will call update() if this is necessary.
-
- \sa boundingRectFor(), boundingRect(), sourceBoundingRect()
-*/
-void QGraphicsEffect::updateBoundingRect()
-{
- Q_D(QGraphicsEffect);
- if (d->source) {
- d->source->d_func()->effectBoundingRectChanged();
- d->source->d_func()->invalidateCache(QGraphicsEffectSourcePrivate::EffectRectChanged);
- }
-}
-
-/*!
- \fn virtual void QGraphicsEffect::draw(QPainter *painter) = 0
-
- This pure virtual function draws the effect and is called whenever the
- source needs to be drawn.
-
- Reimplement this function in a QGraphicsEffect subclass to provide the
- effect's drawing implementation, using \a painter.
-
- For example:
-
- \snippet doc/src/snippets/code/src_gui_effects_qgraphicseffect.cpp 1
-
- This function should not be called explicitly by the user, since it is
- meant for reimplementation purposes only.
-*/
-
-/*!
- \enum QGraphicsEffect::ChangeFlag
-
- This enum describes what has changed in QGraphicsEffectSource.
-
- \value SourceAttached The effect is installed on a source.
- \value SourceDetached The effect is uninstalled on a source.
- \value SourceBoundingRectChanged The bounding rect of the source has
- changed.
- \value SourceInvalidated The visual appearance of the source has changed.
-*/
-
-/*!
- \enum QGraphicsEffect::PixmapPadMode
-
- This enum describes how the pixmap returned from sourcePixmap should be
- padded.
-
- \value NoPad The pixmap should not receive any additional
- padding.
- \value PadToTransparentBorder The pixmap should be padded
- to ensure it has a completely transparent border.
- \value PadToEffectiveBoundingRect The pixmap should be padded to
- match the effective bounding rectangle of the effect.
-*/
-
-/*!
- This virtual function is called by QGraphicsEffect to notify the effect
- that the source has changed. If the effect applies any cache, then this
- cache must be purged in order to reflect the new appearance of the source.
-
- The \a flags describes what has changed.
-*/
-void QGraphicsEffect::sourceChanged(ChangeFlags flags)
-{
- Q_UNUSED(flags);
-}
-
-/*!
- \class QGraphicsColorizeEffect
- \brief The QGraphicsColorizeEffect class provides a colorize effect.
- \since 4.6
-
- A colorize effect renders the source with a tint of its color(). The color
- can be modified using the setColor() function.
-
- By default, the color is light blue (QColor(0, 0, 192)).
-
- \img graphicseffect-colorize.png
-
- \sa QGraphicsDropShadowEffect, QGraphicsBlurEffect, QGraphicsOpacityEffect
-*/
-
-/*!
- Constructs a new QGraphicsColorizeEffect instance.
- The \a parent parameter is passed to QGraphicsEffect's constructor.
-*/
-QGraphicsColorizeEffect::QGraphicsColorizeEffect(QObject *parent)
- : QGraphicsEffect(*new QGraphicsColorizeEffectPrivate, parent)
-{
-}
-
-/*!
- Destroys the effect.
-*/
-QGraphicsColorizeEffect::~QGraphicsColorizeEffect()
-{
-}
-
-/*!
- \property QGraphicsColorizeEffect::color
- \brief the color of the effect.
-
- By default, the color is light blue (QColor(0, 0, 192)).
-*/
-QColor QGraphicsColorizeEffect::color() const
-{
- Q_D(const QGraphicsColorizeEffect);
- return d->filter->color();
-}
-
-void QGraphicsColorizeEffect::setColor(const QColor &color)
-{
- Q_D(QGraphicsColorizeEffect);
- if (d->filter->color() == color)
- return;
-
- d->filter->setColor(color);
- update();
- emit colorChanged(color);
-}
-
-/*!
- \property QGraphicsColorizeEffect::strength
- \brief the strength of the effect.
-
- By default, the strength is 1.0.
- A strength 0.0 equals to no effect, while 1.0 means full colorization.
-*/
-qreal QGraphicsColorizeEffect::strength() const
-{
- Q_D(const QGraphicsColorizeEffect);
- return d->filter->strength();
-}
-
-void QGraphicsColorizeEffect::setStrength(qreal strength)
-{
- Q_D(QGraphicsColorizeEffect);
- if (qFuzzyCompare(d->filter->strength(), strength))
- return;
-
- d->filter->setStrength(strength);
- d->opaque = !qFuzzyIsNull(strength);
- update();
- emit strengthChanged(strength);
-}
-
-/*! \fn void QGraphicsColorizeEffect::strengthChanged(qreal strength)
- This signal is emitted whenever setStrength() changes the colorize
- strength property. \a strength contains the new strength value of
- the colorize effect.
- */
-
-/*!
- \fn void QGraphicsColorizeEffect::colorChanged(const QColor &color)
-
- This signal is emitted whenever the effect's color changes.
- The \a color parameter holds the effect's new color.
-*/
-
-/*!
- \reimp
-*/
-void QGraphicsColorizeEffect::draw(QPainter *painter)
-{
- Q_D(QGraphicsColorizeEffect);
-
- if (!d->opaque) {
- drawSource(painter);
- return;
- }
-
- QPoint offset;
- if (sourceIsPixmap()) {
- // No point in drawing in device coordinates (pixmap will be scaled anyways).
- const QPixmap pixmap = sourcePixmap(Qt::LogicalCoordinates, &offset, NoPad);
- if (!pixmap.isNull())
- d->filter->draw(painter, offset, pixmap);
-
- return;
- }
-
- // Draw pixmap in deviceCoordinates to avoid pixmap scaling.
- const QPixmap pixmap = sourcePixmap(Qt::DeviceCoordinates, &offset);
- if (pixmap.isNull())
- return;
-
- QTransform restoreTransform = painter->worldTransform();
- painter->setWorldTransform(QTransform());
- d->filter->draw(painter, offset, pixmap);
- painter->setWorldTransform(restoreTransform);
-}
-
-/*!
- \class QGraphicsBlurEffect
- \brief The QGraphicsBlurEffect class provides a blur effect.
- \since 4.6
-
- A blur effect blurs the source. This effect is useful for reducing details,
- such as when the source loses focus and you want to draw attention to other
- elements. The level of detail can be modified using the setBlurRadius()
- function. Use setBlurHints() to choose the blur hints.
-
- By default, the blur radius is 5 pixels. The blur radius is specified in
- device coordinates.
-
- \img graphicseffect-blur.png
-
- \sa QGraphicsDropShadowEffect, QGraphicsColorizeEffect, QGraphicsOpacityEffect
-*/
-
-/*!
- \enum QGraphicsBlurEffect::BlurHint
- \since 4.6
-
- This enum describes the possible hints that can be used to control how
- blur effects are applied. The hints might not have an effect in all the
- paint engines.
-
- \value PerformanceHint Indicates that rendering performance is the most important factor,
- at the potential cost of lower quality.
-
- \value QualityHint Indicates that rendering quality is the most important factor,
- at the potential cost of lower performance.
-
- \value AnimationHint Indicates that the blur radius is going to be animated, hinting
- that the implementation can keep a cache of blurred verisons of the source.
- Do not use this hint if the source is going to be dynamically changing.
-
- \sa blurHints(), setBlurHints()
-*/
-
-
-/*!
- Constructs a new QGraphicsBlurEffect instance.
- The \a parent parameter is passed to QGraphicsEffect's constructor.
-*/
-QGraphicsBlurEffect::QGraphicsBlurEffect(QObject *parent)
- : QGraphicsEffect(*new QGraphicsBlurEffectPrivate, parent)
-{
- Q_D(QGraphicsBlurEffect);
- d->filter->setBlurHints(QGraphicsBlurEffect::PerformanceHint);
-}
-
-/*!
- Destroys the effect.
-*/
-QGraphicsBlurEffect::~QGraphicsBlurEffect()
-{
-}
-
-/*!
- \property QGraphicsBlurEffect::blurRadius
- \brief the blur radius of the effect.
-
- Using a smaller radius results in a sharper appearance, whereas a bigger
- radius results in a more blurred appearance.
-
- By default, the blur radius is 5 pixels.
-
- The radius is given in device coordinates, meaning it is
- unaffected by scale.
-*/
-qreal QGraphicsBlurEffect::blurRadius() const
-{
- Q_D(const QGraphicsBlurEffect);
- return d->filter->radius();
-}
-
-void QGraphicsBlurEffect::setBlurRadius(qreal radius)
-{
- Q_D(QGraphicsBlurEffect);
- if (qFuzzyCompare(d->filter->radius(), radius))
- return;
-
- d->filter->setRadius(radius);
- updateBoundingRect();
- emit blurRadiusChanged(radius);
-}
-
-/*!
- \fn void QGraphicsBlurEffect::blurRadiusChanged(qreal radius)
-
- This signal is emitted whenever the effect's blur radius changes.
- The \a radius parameter holds the effect's new blur radius.
-*/
-
-/*!
- \property QGraphicsBlurEffect::blurHints
- \brief the blur hint of the effect.
-
- Use the PerformanceHint hint to say that you want a faster blur,
- the QualityHint hint to say that you prefer a higher quality blur,
- or the AnimationHint when you want to animate the blur radius.
-
- By default, the blur hint is PerformanceHint.
-*/
-QGraphicsBlurEffect::BlurHints QGraphicsBlurEffect::blurHints() const
-{
- Q_D(const QGraphicsBlurEffect);
- return d->filter->blurHints();
-}
-
-void QGraphicsBlurEffect::setBlurHints(QGraphicsBlurEffect::BlurHints hints)
-{
- Q_D(QGraphicsBlurEffect);
- if (d->filter->blurHints() == hints)
- return;
-
- d->filter->setBlurHints(hints);
- emit blurHintsChanged(hints);
-}
-
-/*!
- \fn void QGraphicsBlurEffect::blurHintsChanged(QGraphicsBlurEffect::BlurHints hints)
-
- This signal is emitted whenever the effect's blur hints changes.
- The \a hints parameter holds the effect's new blur hints.
-*/
-
-/*!
- \reimp
-*/
-QRectF QGraphicsBlurEffect::boundingRectFor(const QRectF &rect) const
-{
- Q_D(const QGraphicsBlurEffect);
- return d->filter->boundingRectFor(rect);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsBlurEffect::draw(QPainter *painter)
-{
- Q_D(QGraphicsBlurEffect);
- if (d->filter->radius() < 1) {
- drawSource(painter);
- return;
- }
-
- PixmapPadMode mode = PadToEffectiveBoundingRect;
- if (painter->paintEngine()->type() == QPaintEngine::OpenGL2)
- mode = NoPad;
-
- QPoint offset;
- QPixmap pixmap = sourcePixmap(Qt::LogicalCoordinates, &offset, mode);
- if (pixmap.isNull())
- return;
-
- d->filter->draw(painter, offset, pixmap);
-}
-
-/*!
- \class QGraphicsDropShadowEffect
- \brief The QGraphicsDropShadowEffect class provides a drop shadow effect.
- \since 4.6
-
- A drop shadow effect renders the source with a drop shadow. The color of
- the drop shadow can be modified using the setColor() function. The drop
- shadow offset can be modified using the setOffset() function and the blur
- radius of the drop shadow can be changed with the setBlurRadius()
- function.
-
- By default, the drop shadow is a semi-transparent dark gray
- (QColor(63, 63, 63, 180)) shadow, blurred with a radius of 1 at an offset
- of 8 pixels towards the lower right. The drop shadow offset is specified
- in device coordinates.
-
- \img graphicseffect-drop-shadow.png
-
- \sa QGraphicsBlurEffect, QGraphicsColorizeEffect, QGraphicsOpacityEffect
-*/
-
-/*!
- Constructs a new QGraphicsDropShadowEffect instance.
- The \a parent parameter is passed to QGraphicsEffect's constructor.
-*/
-QGraphicsDropShadowEffect::QGraphicsDropShadowEffect(QObject *parent)
- : QGraphicsEffect(*new QGraphicsDropShadowEffectPrivate, parent)
-{
-}
-
-/*!
- Destroys the effect.
-*/
-QGraphicsDropShadowEffect::~QGraphicsDropShadowEffect()
-{
-}
-
-/*!
- \property QGraphicsDropShadowEffect::offset
- \brief the shadow offset in pixels.
-
- By default, the offset is 8 pixels towards the lower right.
-
- The offset is given in device coordinates, which means it is
- unaffected by scale.
-
- \sa xOffset(), yOffset(), blurRadius(), color()
-*/
-QPointF QGraphicsDropShadowEffect::offset() const
-{
- Q_D(const QGraphicsDropShadowEffect);
- return d->filter->offset();
-}
-
-void QGraphicsDropShadowEffect::setOffset(const QPointF &offset)
-{
- Q_D(QGraphicsDropShadowEffect);
- if (d->filter->offset() == offset)
- return;
-
- d->filter->setOffset(offset);
- updateBoundingRect();
- emit offsetChanged(offset);
-}
-
-/*!
- \property QGraphicsDropShadowEffect::xOffset
- \brief the horizontal shadow offset in pixels.
-
- By default, the horizontal shadow offset is 8 pixels.
-
-
-
- \sa yOffset(), offset()
-*/
-
-/*!
- \property QGraphicsDropShadowEffect::yOffset
- \brief the vertical shadow offset in pixels.
-
- By default, the vertical shadow offset is 8 pixels.
-
- \sa xOffset(), offset()
-*/
-
-/*!
- \fn void QGraphicsDropShadowEffect::offsetChanged(const QPointF &offset)
-
- This signal is emitted whenever the effect's shadow offset changes.
- The \a offset parameter holds the effect's new shadow offset.
-*/
-
-/*!
- \property QGraphicsDropShadowEffect::blurRadius
- \brief the blur radius in pixels of the drop shadow.
-
- Using a smaller radius results in a sharper shadow, whereas using a bigger
- radius results in a more blurred shadow.
-
- By default, the blur radius is 1 pixel.
-
- \sa color(), offset().
-*/
-qreal QGraphicsDropShadowEffect::blurRadius() const
-{
- Q_D(const QGraphicsDropShadowEffect);
- return d->filter->blurRadius();
-}
-
-void QGraphicsDropShadowEffect::setBlurRadius(qreal blurRadius)
-{
- Q_D(QGraphicsDropShadowEffect);
- if (qFuzzyCompare(d->filter->blurRadius(), blurRadius))
- return;
-
- d->filter->setBlurRadius(blurRadius);
- updateBoundingRect();
- emit blurRadiusChanged(blurRadius);
-}
-
-/*!
- \fn void QGraphicsDropShadowEffect::blurRadiusChanged(qreal blurRadius)
-
- This signal is emitted whenever the effect's blur radius changes.
- The \a blurRadius parameter holds the effect's new blur radius.
-*/
-
-/*!
- \property QGraphicsDropShadowEffect::color
- \brief the color of the drop shadow.
-
- By default, the drop color is a semi-transparent dark gray
- (QColor(63, 63, 63, 180)).
-
- \sa offset(), blurRadius()
-*/
-QColor QGraphicsDropShadowEffect::color() const
-{
- Q_D(const QGraphicsDropShadowEffect);
- return d->filter->color();
-}
-
-void QGraphicsDropShadowEffect::setColor(const QColor &color)
-{
- Q_D(QGraphicsDropShadowEffect);
- if (d->filter->color() == color)
- return;
-
- d->filter->setColor(color);
- update();
- emit colorChanged(color);
-}
-
-/*!
- \fn void QGraphicsDropShadowEffect::colorChanged(const QColor &color)
-
- This signal is emitted whenever the effect's color changes.
- The \a color parameter holds the effect's new color.
-*/
-
-/*!
- \reimp
-*/
-QRectF QGraphicsDropShadowEffect::boundingRectFor(const QRectF &rect) const
-{
- Q_D(const QGraphicsDropShadowEffect);
- return d->filter->boundingRectFor(rect);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsDropShadowEffect::draw(QPainter *painter)
-{
- Q_D(QGraphicsDropShadowEffect);
- if (d->filter->blurRadius() <= 0 && d->filter->offset().isNull()) {
- drawSource(painter);
- return;
- }
-
- PixmapPadMode mode = PadToEffectiveBoundingRect;
- if (painter->paintEngine()->type() == QPaintEngine::OpenGL2)
- mode = NoPad;
-
- // Draw pixmap in device coordinates to avoid pixmap scaling.
- QPoint offset;
- const QPixmap pixmap = sourcePixmap(Qt::DeviceCoordinates, &offset, mode);
- if (pixmap.isNull())
- return;
-
- QTransform restoreTransform = painter->worldTransform();
- painter->setWorldTransform(QTransform());
- d->filter->draw(painter, offset, pixmap);
- painter->setWorldTransform(restoreTransform);
-}
-
-/*!
- \class QGraphicsOpacityEffect
- \brief The QGraphicsOpacityEffect class provides an opacity effect.
- \since 4.6
-
- An opacity effect renders the source with an opacity. This effect is useful
- for making the source semi-transparent, similar to a fade-in/fade-out
- sequence. The opacity can be modified using the setOpacity() function.
-
- By default, the opacity is 0.7.
-
- \img graphicseffect-opacity.png
-
- \sa QGraphicsDropShadowEffect, QGraphicsBlurEffect, QGraphicsColorizeEffect
-*/
-
-/*!
- Constructs a new QGraphicsOpacityEffect instance.
- The \a parent parameter is passed to QGraphicsEffect's constructor.
-*/
-QGraphicsOpacityEffect::QGraphicsOpacityEffect(QObject *parent)
- : QGraphicsEffect(*new QGraphicsOpacityEffectPrivate, parent)
-{
-}
-
-/*!
- Destroys the effect.
-*/
-QGraphicsOpacityEffect::~QGraphicsOpacityEffect()
-{
-}
-
-/*!
- \property QGraphicsOpacityEffect::opacity
- \brief the opacity of the effect.
-
- The value should be in the range of 0.0 to 1.0, where 0.0 is
- fully transparent and 1.0 is fully opaque.
-
- By default, the opacity is 0.7.
-
- \sa setOpacityMask()
-*/
-qreal QGraphicsOpacityEffect::opacity() const
-{
- Q_D(const QGraphicsOpacityEffect);
- return d->opacity;
-}
-
-void QGraphicsOpacityEffect::setOpacity(qreal opacity)
-{
- Q_D(QGraphicsOpacityEffect);
- opacity = qBound(qreal(0.0), opacity, qreal(1.0));
-
- if (qFuzzyCompare(d->opacity, opacity))
- return;
-
- d->opacity = opacity;
- if ((d->isFullyTransparent = qFuzzyIsNull(d->opacity)))
- d->isFullyOpaque = 0;
- else
- d->isFullyOpaque = qFuzzyIsNull(d->opacity - 1);
- update();
- emit opacityChanged(opacity);
-}
-
-/*!
- \fn void QGraphicsOpacityEffect::opacityChanged(qreal opacity)
-
- This signal is emitted whenever the effect's opacity changes.
- The \a opacity parameter holds the effect's new opacity.
-*/
-
-/*!
- \property QGraphicsOpacityEffect::opacityMask
- \brief the opacity mask of the effect.
-
- An opacity mask allows you apply opacity to portions of an element.
-
- For example:
-
- \snippet doc/src/snippets/code/src_gui_effects_qgraphicseffect.cpp 2
-
- There is no opacity mask by default.
-
- \sa setOpacity()
-*/
-QBrush QGraphicsOpacityEffect::opacityMask() const
-{
- Q_D(const QGraphicsOpacityEffect);
- return d->opacityMask;
-}
-
-void QGraphicsOpacityEffect::setOpacityMask(const QBrush &mask)
-{
- Q_D(QGraphicsOpacityEffect);
- if (d->opacityMask == mask)
- return;
-
- d->opacityMask = mask;
- d->hasOpacityMask = (mask.style() != Qt::NoBrush);
- update();
-
- emit opacityMaskChanged(mask);
-}
-
-/*!
- \fn void QGraphicsOpacityEffect::opacityMaskChanged(const QBrush &mask)
-
- This signal is emitted whenever the effect's opacity mask changes.
- The \a mask parameter holds the effect's new opacity mask.
-*/
-
-/*!
- \reimp
-*/
-void QGraphicsOpacityEffect::draw(QPainter *painter)
-{
- Q_D(QGraphicsOpacityEffect);
-
- // Transparent; nothing to draw.
- if (d->isFullyTransparent)
- return;
-
- // Opaque; draw directly without going through a pixmap.
- if (d->isFullyOpaque && !d->hasOpacityMask) {
- drawSource(painter);
- return;
- }
-
- QPoint offset;
- Qt::CoordinateSystem system = sourceIsPixmap() ? Qt::LogicalCoordinates : Qt::DeviceCoordinates;
- QPixmap pixmap = sourcePixmap(system, &offset, QGraphicsEffect::NoPad);
- if (pixmap.isNull())
- return;
-
- painter->save();
- painter->setOpacity(d->opacity);
-
- if (d->hasOpacityMask) {
- QPainter pixmapPainter(&pixmap);
- pixmapPainter.setRenderHints(painter->renderHints());
- pixmapPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
- if (system == Qt::DeviceCoordinates) {
- QTransform worldTransform = painter->worldTransform();
- worldTransform *= QTransform::fromTranslate(-offset.x(), -offset.y());
- pixmapPainter.setWorldTransform(worldTransform);
- pixmapPainter.fillRect(sourceBoundingRect(), d->opacityMask);
- } else {
- pixmapPainter.translate(-offset);
- pixmapPainter.fillRect(pixmap.rect(), d->opacityMask);
- }
- }
-
- if (system == Qt::DeviceCoordinates)
- painter->setWorldTransform(QTransform());
-
- painter->drawPixmap(offset, pixmap);
- painter->restore();
-}
-
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSEFFECT
diff --git a/src/gui/effects/qgraphicseffect.h b/src/gui/effects/qgraphicseffect.h
deleted file mode 100644
index 9f5e94db89..0000000000
--- a/src/gui/effects/qgraphicseffect.h
+++ /dev/null
@@ -1,289 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSEFFECT_H
-#define QGRAPHICSEFFECT_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qrect.h>
-#include <QtGui/qcolor.h>
-#include <QtGui/qbrush.h>
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QGraphicsItem;
-class QStyleOption;
-class QPainter;
-class QPixmap;
-
-class QGraphicsEffectSource;
-
-class QGraphicsEffectPrivate;
-class Q_GUI_EXPORT QGraphicsEffect : public QObject
-{
- Q_OBJECT
- Q_FLAGS(ChangeFlags)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)
-public:
- enum ChangeFlag {
- SourceAttached = 0x1,
- SourceDetached = 0x2,
- SourceBoundingRectChanged = 0x4,
- SourceInvalidated = 0x8
- };
- Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag)
-
- enum PixmapPadMode {
- NoPad,
- PadToTransparentBorder,
- PadToEffectiveBoundingRect
- };
-
- QGraphicsEffect(QObject *parent = 0);
- virtual ~QGraphicsEffect();
-
- virtual QRectF boundingRectFor(const QRectF &sourceRect) const;
- QRectF boundingRect() const;
-
- bool isEnabled() const;
-
-public Q_SLOTS:
- void setEnabled(bool enable);
- void update();
-
-Q_SIGNALS:
- void enabledChanged(bool enabled);
-
-protected:
- QGraphicsEffect(QGraphicsEffectPrivate &d, QObject *parent = 0);
- virtual void draw(QPainter *painter) = 0;
- virtual void sourceChanged(ChangeFlags flags);
- void updateBoundingRect();
-
- bool sourceIsPixmap() const;
- QRectF sourceBoundingRect(Qt::CoordinateSystem system = Qt::LogicalCoordinates) const;
- void drawSource(QPainter *painter);
- QPixmap sourcePixmap(Qt::CoordinateSystem system = Qt::LogicalCoordinates,
- QPoint *offset = 0,
- PixmapPadMode mode = PadToEffectiveBoundingRect) const;
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsEffect)
- Q_DISABLE_COPY(QGraphicsEffect)
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
- friend class QGraphicsScenePrivate;
- friend class QWidget;
- friend class QWidgetPrivate;
-
-public:
- QGraphicsEffectSource *source() const; // internal
-
-};
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsEffect::ChangeFlags)
-
-class QGraphicsColorizeEffectPrivate;
-class Q_GUI_EXPORT QGraphicsColorizeEffect: public QGraphicsEffect
-{
- Q_OBJECT
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
- Q_PROPERTY(qreal strength READ strength WRITE setStrength NOTIFY strengthChanged)
-public:
- QGraphicsColorizeEffect(QObject *parent = 0);
- ~QGraphicsColorizeEffect();
-
- QColor color() const;
- qreal strength() const;
-
-public Q_SLOTS:
- void setColor(const QColor &c);
- void setStrength(qreal strength);
-
-Q_SIGNALS:
- void colorChanged(const QColor &color);
- void strengthChanged(qreal strength);
-
-protected:
- void draw(QPainter *painter);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsColorizeEffect)
- Q_DISABLE_COPY(QGraphicsColorizeEffect)
-};
-
-class QGraphicsBlurEffectPrivate;
-class Q_GUI_EXPORT QGraphicsBlurEffect: public QGraphicsEffect
-{
- Q_OBJECT
- Q_FLAGS(BlurHint BlurHints)
- Q_PROPERTY(qreal blurRadius READ blurRadius WRITE setBlurRadius NOTIFY blurRadiusChanged)
- Q_PROPERTY(BlurHints blurHints READ blurHints WRITE setBlurHints NOTIFY blurHintsChanged)
-public:
- enum BlurHint {
- PerformanceHint = 0x00,
- QualityHint = 0x01,
- AnimationHint = 0x02
- };
- Q_DECLARE_FLAGS(BlurHints, BlurHint)
-
- QGraphicsBlurEffect(QObject *parent = 0);
- ~QGraphicsBlurEffect();
-
- QRectF boundingRectFor(const QRectF &rect) const;
- qreal blurRadius() const;
- BlurHints blurHints() const;
-
-public Q_SLOTS:
- void setBlurRadius(qreal blurRadius);
- void setBlurHints(BlurHints hints);
-
-Q_SIGNALS:
- void blurRadiusChanged(qreal blurRadius);
- void blurHintsChanged(BlurHints hints);
-
-protected:
- void draw(QPainter *painter);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsBlurEffect)
- Q_DISABLE_COPY(QGraphicsBlurEffect)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsBlurEffect::BlurHints)
-
-class QGraphicsDropShadowEffectPrivate;
-class Q_GUI_EXPORT QGraphicsDropShadowEffect: public QGraphicsEffect
-{
- Q_OBJECT
- Q_PROPERTY(QPointF offset READ offset WRITE setOffset NOTIFY offsetChanged)
- Q_PROPERTY(qreal xOffset READ xOffset WRITE setXOffset NOTIFY offsetChanged)
- Q_PROPERTY(qreal yOffset READ yOffset WRITE setYOffset NOTIFY offsetChanged)
- Q_PROPERTY(qreal blurRadius READ blurRadius WRITE setBlurRadius NOTIFY blurRadiusChanged)
- Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
-public:
- QGraphicsDropShadowEffect(QObject *parent = 0);
- ~QGraphicsDropShadowEffect();
-
- QRectF boundingRectFor(const QRectF &rect) const;
- QPointF offset() const;
-
- inline qreal xOffset() const
- { return offset().x(); }
-
- inline qreal yOffset() const
- { return offset().y(); }
-
- qreal blurRadius() const;
- QColor color() const;
-
-public Q_SLOTS:
- void setOffset(const QPointF &ofs);
-
- inline void setOffset(qreal dx, qreal dy)
- { setOffset(QPointF(dx, dy)); }
-
- inline void setOffset(qreal d)
- { setOffset(QPointF(d, d)); }
-
- inline void setXOffset(qreal dx)
- { setOffset(QPointF(dx, yOffset())); }
-
- inline void setYOffset(qreal dy)
- { setOffset(QPointF(xOffset(), dy)); }
-
- void setBlurRadius(qreal blurRadius);
- void setColor(const QColor &color);
-
-Q_SIGNALS:
- void offsetChanged(const QPointF &offset);
- void blurRadiusChanged(qreal blurRadius);
- void colorChanged(const QColor &color);
-
-protected:
- void draw(QPainter *painter);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsDropShadowEffect)
- Q_DISABLE_COPY(QGraphicsDropShadowEffect)
-};
-
-class QGraphicsOpacityEffectPrivate;
-class Q_GUI_EXPORT QGraphicsOpacityEffect: public QGraphicsEffect
-{
- Q_OBJECT
- Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged)
- Q_PROPERTY(QBrush opacityMask READ opacityMask WRITE setOpacityMask NOTIFY opacityMaskChanged)
-public:
- QGraphicsOpacityEffect(QObject *parent = 0);
- ~QGraphicsOpacityEffect();
-
- qreal opacity() const;
- QBrush opacityMask() const;
-
-public Q_SLOTS:
- void setOpacity(qreal opacity);
- void setOpacityMask(const QBrush &mask);
-
-Q_SIGNALS:
- void opacityChanged(qreal opacity);
- void opacityMaskChanged(const QBrush &mask);
-
-protected:
- void draw(QPainter *painter);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsOpacityEffect)
- Q_DISABLE_COPY(QGraphicsOpacityEffect)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-#endif //QT_NO_GRAPHICSEFFECT
-
-#endif // QGRAPHICSEFFECT_H
-
diff --git a/src/gui/effects/qgraphicseffect_p.h b/src/gui/effects/qgraphicseffect_p.h
deleted file mode 100644
index cd1ae38ff8..0000000000
--- a/src/gui/effects/qgraphicseffect_p.h
+++ /dev/null
@@ -1,231 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSEFFECT_P_H
-#define QGRAPHICSEFFECT_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qgraphicseffect.h"
-
-#include <QPixmapCache>
-
-#include <private/qobject_p.h>
-#include <private/qpixmapfilter_p.h>
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QT_BEGIN_NAMESPACE
-
-class QGraphicsEffectSourcePrivate;
-class Q_GUI_EXPORT QGraphicsEffectSource : public QObject
-{
- Q_OBJECT
-public:
- ~QGraphicsEffectSource();
- const QGraphicsItem *graphicsItem() const;
- const QWidget *widget() const;
- const QStyleOption *styleOption() const;
-
- bool isPixmap() const;
- void draw(QPainter *painter);
- void update();
-
- QRectF boundingRect(Qt::CoordinateSystem coordinateSystem = Qt::LogicalCoordinates) const;
- QRect deviceRect() const;
- QPixmap pixmap(Qt::CoordinateSystem system = Qt::LogicalCoordinates,
- QPoint *offset = 0,
- QGraphicsEffect::PixmapPadMode mode = QGraphicsEffect::PadToEffectiveBoundingRect) const;
-
-protected:
- QGraphicsEffectSource(QGraphicsEffectSourcePrivate &dd, QObject *parent = 0);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsEffectSource)
- Q_DISABLE_COPY(QGraphicsEffectSource)
- friend class QGraphicsEffect;
- friend class QGraphicsEffectPrivate;
- friend class QGraphicsScenePrivate;
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
- friend class QWidget;
- friend class QWidgetPrivate;
-};
-
-class QGraphicsEffectSourcePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsEffectSource)
-public:
- QGraphicsEffectSourcePrivate()
- : QObjectPrivate()
- , m_cachedSystem(Qt::DeviceCoordinates)
- , m_cachedMode(QGraphicsEffect::PadToTransparentBorder)
- {}
-
- enum InvalidateReason
- {
- TransformChanged,
- EffectRectChanged,
- SourceChanged
- };
-
- virtual ~QGraphicsEffectSourcePrivate();
- virtual void detach() = 0;
- virtual QRectF boundingRect(Qt::CoordinateSystem system) const = 0;
- virtual QRect deviceRect() const = 0;
- virtual const QGraphicsItem *graphicsItem() const = 0;
- virtual const QWidget *widget() const = 0;
- virtual const QStyleOption *styleOption() const = 0;
- virtual void draw(QPainter *p) = 0;
- virtual void update() = 0;
- virtual bool isPixmap() const = 0;
- virtual QPixmap pixmap(Qt::CoordinateSystem system, QPoint *offset = 0,
- QGraphicsEffect::PixmapPadMode mode = QGraphicsEffect::PadToTransparentBorder) const = 0;
- virtual void effectBoundingRectChanged() = 0;
-
- void setCachedOffset(const QPoint &offset);
- void invalidateCache(InvalidateReason reason = SourceChanged) const;
- Qt::CoordinateSystem currentCachedSystem() const { return m_cachedSystem; }
- QGraphicsEffect::PixmapPadMode currentCachedMode() const { return m_cachedMode; }
-
- friend class QGraphicsScenePrivate;
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
-
-private:
- mutable Qt::CoordinateSystem m_cachedSystem;
- mutable QGraphicsEffect::PixmapPadMode m_cachedMode;
- mutable QPoint m_cachedOffset;
- mutable QPixmapCache::Key m_cacheKey;
-};
-
-class Q_GUI_EXPORT QGraphicsEffectPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsEffect)
-public:
- QGraphicsEffectPrivate() : source(0), isEnabled(1) {}
-
- inline void setGraphicsEffectSource(QGraphicsEffectSource *newSource)
- {
- QGraphicsEffect::ChangeFlags flags;
- if (source) {
- flags |= QGraphicsEffect::SourceDetached;
- source->d_func()->invalidateCache();
- source->d_func()->detach();
- delete source;
- }
- source = newSource;
- if (newSource)
- flags |= QGraphicsEffect::SourceAttached;
- q_func()->sourceChanged(flags);
- }
-
- QGraphicsEffectSource *source;
- QRectF boundingRect;
- quint32 isEnabled : 1;
- quint32 padding : 31; // feel free to use
-};
-
-
-class QGraphicsColorizeEffectPrivate : public QGraphicsEffectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsColorizeEffect)
-public:
- QGraphicsColorizeEffectPrivate()
- : opaque(true)
- {
- filter = new QPixmapColorizeFilter;
- }
- ~QGraphicsColorizeEffectPrivate() { delete filter; }
-
- QPixmapColorizeFilter *filter;
- quint32 opaque : 1;
- quint32 padding : 31;
-};
-
-class QGraphicsBlurEffectPrivate : public QGraphicsEffectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsBlurEffect)
-public:
- QGraphicsBlurEffectPrivate() : filter(new QPixmapBlurFilter) {}
- ~QGraphicsBlurEffectPrivate() { delete filter; }
-
- QPixmapBlurFilter *filter;
-};
-
-class QGraphicsDropShadowEffectPrivate : public QGraphicsEffectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsDropShadowEffect)
-public:
- QGraphicsDropShadowEffectPrivate() : filter(new QPixmapDropShadowFilter) {}
- ~QGraphicsDropShadowEffectPrivate() { delete filter; }
-
- QPixmapDropShadowFilter *filter;
-};
-
-class QGraphicsOpacityEffectPrivate : public QGraphicsEffectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsOpacityEffect)
-public:
- QGraphicsOpacityEffectPrivate()
- : opacity(qreal(0.7)), isFullyTransparent(0), isFullyOpaque(0), hasOpacityMask(0) {}
- ~QGraphicsOpacityEffectPrivate() {}
-
- qreal opacity;
- QBrush opacityMask;
- uint isFullyTransparent : 1;
- uint isFullyOpaque : 1;
- uint hasOpacityMask : 1;
-};
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSEFFECT
-#endif // QGRAPHICSEFFECT_P_H
-
diff --git a/src/gui/effects/qpixmapfilter.cpp b/src/gui/effects/qpixmapfilter.cpp
deleted file mode 100644
index ecab3d7a41..0000000000
--- a/src/gui/effects/qpixmapfilter.cpp
+++ /dev/null
@@ -1,1381 +0,0 @@
-/****************************************************************************
-**
-** 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 <QDebug>
-
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qpixmapfilter_p.h"
-#include "qvarlengtharray.h"
-
-#include "private/qguiapplication_p.h"
-#include "private/qpaintengineex_p.h"
-#include "private/qpaintengine_raster_p.h"
-#include "qmath.h"
-#include "private/qmath_p.h"
-#include "private/qmemrotate_p.h"
-#include "private/qdrawhelper_p.h"
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QT_BEGIN_NAMESPACE
-
-class QPixmapFilterPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QPixmapFilter)
-public:
- QPixmapFilter::FilterType type;
-};
-
-/*!
- \class QPixmapFilter
- \since 4.5
- \ingroup painting
-
- \brief The QPixmapFilter class provides the basic functionality for
- pixmap filter classes. Pixmap filter can be for example colorize or blur.
-
- QPixmapFilter is the base class for every pixmap filter. QPixmapFilter is
- an abstract class and cannot itself be instantiated. It provides a standard
- interface for filter processing.
-
- \internal
-*/
-
-/*!
- \enum QPixmapFilter::FilterType
-
- \internal
-
- This enum describes the types of filter that can be applied to pixmaps.
-
- \value ConvolutionFilter A filter that is used to calculate the convolution
- of the image with a kernel. See
- QPixmapConvolutionFilter for more information.
- \value ColorizeFilter A filter that is used to change the overall color
- of an image. See QPixmapColorizeFilter for more
- information.
- \value DropShadowFilter A filter that is used to add a drop shadow to an
- image. See QPixmapDropShadowFilter for more
- information.
- \value BlurFilter A filter that is used to blur an image using
- a simple blur radius. See QPixmapBlurFilter
- for more information.
-
- \value UserFilter The first filter type that can be used for
- application-specific purposes.
-*/
-
-
-/*!
- Constructs a default QPixmapFilter with the given \a type.
-
- This constructor should be used when subclassing QPixmapFilter to
- create custom user filters.
-
- \internal
-*/
-QPixmapFilter::QPixmapFilter(FilterType type, QObject *parent)
- : QObject(*new QPixmapFilterPrivate, parent)
-{
- d_func()->type = type;
-}
-
-
-
-/*!
- \internal
-*/
-QPixmapFilter::QPixmapFilter(QPixmapFilterPrivate&d, QPixmapFilter::FilterType type, QObject *parent)
- : QObject(d, parent)
-{
- d_func()->type = type;
-}
-
-
-/*!
- Destroys the pixmap filter.
-
- \internal
-*/
-QPixmapFilter::~QPixmapFilter()
-{
-}
-
-/*!
- Returns the type of the filter. All standard pixmap filter classes
- are associated with a unique value.
-
- \internal
-*/
-QPixmapFilter::FilterType QPixmapFilter::type() const
-{
- Q_D(const QPixmapFilter);
- return d->type;
-}
-
-/*!
- Returns the bounding rectangle that is affected by the pixmap
- filter if the filter is applied to the specified \a rect.
-
- \internal
-*/
-QRectF QPixmapFilter::boundingRectFor(const QRectF &rect) const
-{
- return rect;
-}
-
-/*!
- \fn void QPixmapFilter::draw(QPainter *painter, const QPointF &p, const QPixmap &src, const QRectF& srcRect) const
-
- Uses \a painter to draw filtered result of \a src at the point
- specified by \a p. If \a srcRect is specified the it will
- be used as a source rectangle to only draw a part of the source.
-
- draw() will affect the area which boundingRectFor() returns.
-
- \internal
-*/
-
-/*!
- \class QPixmapConvolutionFilter
- \since 4.5
- \ingroup painting
-
- \brief The QPixmapConvolutionFilter class provides convolution
- filtering for pixmaps.
-
- QPixmapConvolutionFilter implements a convolution pixmap filter,
- which is applied when \l{QPixmapFilter::}{draw()} is called. A
- convolution filter lets you distort an image by setting the values
- of a matrix of qreal values called its
- \l{setConvolutionKernel()}{kernel}. The matrix's values are
- usually between -1.0 and 1.0.
-
- \omit
- In convolution filtering, the pixel value is calculated from the
- neighboring pixels based on the weighting convolution kernel.
- This needs explaining to be useful.
- \endomit
-
- Example:
- \snippet doc/src/snippets/code/src_gui_image_qpixmapfilter.cpp 1
-
- \sa {Pixmap Filters Example}, QPixmapColorizeFilter, QPixmapDropShadowFilter
-
-
- \internal
-*/
-
-class QPixmapConvolutionFilterPrivate : public QPixmapFilterPrivate
-{
-public:
- QPixmapConvolutionFilterPrivate(): convolutionKernel(0), kernelWidth(0), kernelHeight(0), convoluteAlpha(false) {}
- ~QPixmapConvolutionFilterPrivate() {
- delete[] convolutionKernel;
- }
-
- qreal *convolutionKernel;
- int kernelWidth;
- int kernelHeight;
- bool convoluteAlpha;
-};
-
-
-/*!
- Constructs a pixmap convolution filter.
-
- By default there is no convolution kernel.
-
- \internal
-*/
-QPixmapConvolutionFilter::QPixmapConvolutionFilter(QObject *parent)
- : QPixmapFilter(*new QPixmapConvolutionFilterPrivate, ConvolutionFilter, parent)
-{
- Q_D(QPixmapConvolutionFilter);
- d->convoluteAlpha = true;
-}
-
-/*!
- Destructor of pixmap convolution filter.
-
- \internal
-*/
-QPixmapConvolutionFilter::~QPixmapConvolutionFilter()
-{
-}
-
-/*!
- Sets convolution kernel with the given number of \a rows and \a columns.
- Values from \a kernel are copied to internal data structure.
-
- To preserve the intensity of the pixmap, the sum of all the
- values in the convolution kernel should add up to 1.0. A sum
- greater than 1.0 produces a lighter result and a sum less than 1.0
- produces a darker and transparent result.
-
- \internal
-*/
-void QPixmapConvolutionFilter::setConvolutionKernel(const qreal *kernel, int rows, int columns)
-{
- Q_D(QPixmapConvolutionFilter);
- delete [] d->convolutionKernel;
- d->convolutionKernel = new qreal[rows * columns];
- memcpy(d->convolutionKernel, kernel, sizeof(qreal) * rows * columns);
- d->kernelWidth = columns;
- d->kernelHeight = rows;
-}
-
-/*!
- Gets the convolution kernel data.
-
- \internal
-*/
-const qreal *QPixmapConvolutionFilter::convolutionKernel() const
-{
- Q_D(const QPixmapConvolutionFilter);
- return d->convolutionKernel;
-}
-
-/*!
- Gets the number of rows in the convolution kernel.
-
- \internal
-*/
-int QPixmapConvolutionFilter::rows() const
-{
- Q_D(const QPixmapConvolutionFilter);
- return d->kernelHeight;
-}
-
-/*!
- Gets the number of columns in the convolution kernel.
-
- \internal
-*/
-int QPixmapConvolutionFilter::columns() const
-{
- Q_D(const QPixmapConvolutionFilter);
- return d->kernelWidth;
-}
-
-
-/*!
- \internal
-*/
-QRectF QPixmapConvolutionFilter::boundingRectFor(const QRectF &rect) const
-{
- Q_D(const QPixmapConvolutionFilter);
- return rect.adjusted(-d->kernelWidth / 2, -d->kernelHeight / 2, (d->kernelWidth - 1) / 2, (d->kernelHeight - 1) / 2);
-}
-
-// Convolutes the image
-static void convolute(
- QImage *destImage,
- const QPointF &pos,
- const QImage &srcImage,
- const QRectF &srcRect,
- QPainter::CompositionMode mode,
- qreal *kernel,
- int kernelWidth,
- int kernelHeight )
-{
- const QImage processImage = (srcImage.format() != QImage::Format_ARGB32_Premultiplied ) ? srcImage.convertToFormat(QImage::Format_ARGB32_Premultiplied) : srcImage;
- // TODO: support also other formats directly without copying
-
- int *fixedKernel = new int[kernelWidth*kernelHeight];
- for(int i = 0; i < kernelWidth*kernelHeight; i++)
- {
- fixedKernel[i] = (int)(65536 * kernel[i]);
- }
- QRectF trect = srcRect.isNull() ? processImage.rect() : srcRect;
- trect.moveTo(pos);
- QRectF bounded = trect.adjusted(-kernelWidth / 2, -kernelHeight / 2, (kernelWidth - 1) / 2, (kernelHeight - 1) / 2);
- QRect rect = bounded.toAlignedRect();
- QRect targetRect = rect.intersected(destImage->rect());
-
- QRectF srect = srcRect.isNull() ? processImage.rect() : srcRect;
- QRectF sbounded = srect.adjusted(-kernelWidth / 2, -kernelHeight / 2, (kernelWidth - 1) / 2, (kernelHeight - 1) / 2);
- QPoint srcStartPoint = sbounded.toAlignedRect().topLeft()+(targetRect.topLeft()-rect.topLeft());
-
- const uint *sourceStart = (uint*)processImage.scanLine(0);
- uint *outputStart = (uint*)destImage->scanLine(0);
-
- int yk = srcStartPoint.y();
- for (int y = targetRect.top(); y <= targetRect.bottom(); y++) {
- uint* output = outputStart + (destImage->bytesPerLine()/sizeof(uint))*y+targetRect.left();
- int xk = srcStartPoint.x();
- for(int x = targetRect.left(); x <= targetRect.right(); x++) {
- int r = 0;
- int g = 0;
- int b = 0;
- int a = 0;
-
- // some out of bounds pre-checking to avoid inner-loop ifs
- int kernely = -kernelHeight/2;
- int starty = 0;
- int endy = kernelHeight;
- if(yk+kernely+endy >= srcImage.height())
- endy = kernelHeight-((yk+kernely+endy)-srcImage.height())-1;
- if(yk+kernely < 0)
- starty = -(yk+kernely);
-
- int kernelx = -kernelWidth/2;
- int startx = 0;
- int endx = kernelWidth;
- if(xk+kernelx+endx >= srcImage.width())
- endx = kernelWidth-((xk+kernelx+endx)-srcImage.width())-1;
- if(xk+kernelx < 0)
- startx = -(xk+kernelx);
-
- for (int ys = starty; ys < endy; ys ++) {
- const uint *pix = sourceStart + (processImage.bytesPerLine()/sizeof(uint))*(yk+kernely+ys) + ((xk+kernelx+startx));
- const uint *endPix = pix+endx-startx;
- int kernelPos = ys*kernelWidth+startx;
- while (pix < endPix) {
- int factor = fixedKernel[kernelPos++];
- a += (((*pix) & 0xff000000)>>24) * factor;
- r += (((*pix) & 0x00ff0000)>>16) * factor;
- g += (((*pix) & 0x0000ff00)>>8 ) * factor;
- b += (((*pix) & 0x000000ff) ) * factor;
- pix++;
- }
- }
-
- r = qBound((int)0, r >> 16, (int)255);
- g = qBound((int)0, g >> 16, (int)255);
- b = qBound((int)0, b >> 16, (int)255);
- a = qBound((int)0, a >> 16, (int)255);
- // composition mode checking could be moved outside of loop
- if(mode == QPainter::CompositionMode_Source) {
- uint color = (a<<24)+(r<<16)+(g<<8)+b;
- *output++ = color;
- } else {
- uint current = *output;
- uchar ca = (current&0xff000000)>>24;
- uchar cr = (current&0x00ff0000)>>16;
- uchar cg = (current&0x0000ff00)>>8;
- uchar cb = (current&0x000000ff);
- uint color =
- (((ca*(255-a) >> 8)+a) << 24)+
- (((cr*(255-a) >> 8)+r) << 16)+
- (((cg*(255-a) >> 8)+g) << 8)+
- (((cb*(255-a) >> 8)+b));
- *output++ = color;;
- }
- xk++;
- }
- yk++;
- }
- delete[] fixedKernel;
-}
-
-/*!
- \internal
-*/
-void QPixmapConvolutionFilter::draw(QPainter *painter, const QPointF &p, const QPixmap &src, const QRectF& srcRect) const
-{
- Q_D(const QPixmapConvolutionFilter);
- if (!painter->isActive())
- return;
-
- if(d->kernelWidth<=0 || d->kernelHeight <= 0)
- return;
-
- if (src.isNull())
- return;
-
- QPixmapFilter *filter = painter->paintEngine() && painter->paintEngine()->isExtended() ?
- static_cast<QPaintEngineEx *>(painter->paintEngine())->pixmapFilter(type(), this) : 0;
- QPixmapConvolutionFilter *convolutionFilter = static_cast<QPixmapConvolutionFilter*>(filter);
- if (convolutionFilter) {
- convolutionFilter->setConvolutionKernel(d->convolutionKernel, d->kernelWidth, d->kernelHeight);
- convolutionFilter->d_func()->convoluteAlpha = d->convoluteAlpha;
- convolutionFilter->draw(painter, p, src, srcRect);
- return;
- }
-
- // falling back to raster implementation
-
- QImage *target = 0;
- if (painter->paintEngine()->paintDevice()->devType() == QInternal::Image) {
- target = static_cast<QImage *>(painter->paintEngine()->paintDevice());
-
- QTransform mat = painter->combinedTransform();
-
- if (mat.type() > QTransform::TxTranslate) {
- // Disabled because of transformation...
- target = 0;
- } else {
- QRasterPaintEngine *pe = static_cast<QRasterPaintEngine *>(painter->paintEngine());
- if (pe->clipType() == QRasterPaintEngine::ComplexClip)
- // disabled because of complex clipping...
- target = 0;
- else {
- QRectF clip = pe->clipBoundingRect();
- QRectF rect = boundingRectFor(srcRect.isEmpty() ? src.rect() : srcRect);
- QTransform x = painter->deviceTransform();
- if (!clip.contains(rect.translated(x.dx() + p.x(), x.dy() + p.y()))) {
- target = 0;
- }
-
- }
- }
- }
-
- if (target) {
- QTransform x = painter->deviceTransform();
- QPointF offset(x.dx(), x.dy());
-
- convolute(target, p+offset, src.toImage(), srcRect, QPainter::CompositionMode_SourceOver, d->convolutionKernel, d->kernelWidth, d->kernelHeight);
- } else {
- QRect srect = srcRect.isNull() ? src.rect() : srcRect.toRect();
- QRect rect = boundingRectFor(srect).toRect();
- QImage result = QImage(rect.size(), QImage::Format_ARGB32_Premultiplied);
- QPoint offset = srect.topLeft() - rect.topLeft();
- convolute(&result,
- offset,
- src.toImage(),
- srect,
- QPainter::CompositionMode_Source,
- d->convolutionKernel,
- d->kernelWidth,
- d->kernelHeight);
- painter->drawImage(p - offset, result);
- }
-}
-
-/*!
- \class QPixmapBlurFilter
- \since 4.6
- \ingroup multimedia
-
- \brief The QPixmapBlurFilter class provides blur filtering
- for pixmaps.
-
- QPixmapBlurFilter implements a blur pixmap filter,
- which is applied when \l{QPixmapFilter::}{draw()} is called.
-
- The filter lets you specialize the radius of the blur as well
- as hints as to whether to prefer performance or quality.
-
- By default, the blur effect is produced by applying an exponential
- filter generated from the specified blurRadius(). Paint engines
- may override this with a custom blur that is faster on the
- underlying hardware.
-
- \sa {Pixmap Filters Example}, QPixmapConvolutionFilter, QPixmapDropShadowFilter
-
- \internal
-*/
-
-class QPixmapBlurFilterPrivate : public QPixmapFilterPrivate
-{
-public:
- QPixmapBlurFilterPrivate() : radius(5), hints(QGraphicsBlurEffect::PerformanceHint) {}
-
- qreal radius;
- QGraphicsBlurEffect::BlurHints hints;
-};
-
-
-/*!
- Constructs a pixmap blur filter.
-
- \internal
-*/
-QPixmapBlurFilter::QPixmapBlurFilter(QObject *parent)
- : QPixmapFilter(*new QPixmapBlurFilterPrivate, BlurFilter, parent)
-{
-}
-
-/*!
- Destructor of pixmap blur filter.
-
- \internal
-*/
-QPixmapBlurFilter::~QPixmapBlurFilter()
-{
-}
-
-/*!
- Sets the radius of the blur filter. Higher radius produces increased blurriness.
-
- \internal
-*/
-void QPixmapBlurFilter::setRadius(qreal radius)
-{
- Q_D(QPixmapBlurFilter);
- d->radius = radius;
-}
-
-/*!
- Gets the radius of the blur filter.
-
- \internal
-*/
-qreal QPixmapBlurFilter::radius() const
-{
- Q_D(const QPixmapBlurFilter);
- return d->radius;
-}
-
-/*!
- Setting the blur hints to PerformanceHint causes the implementation
- to trade off visual quality to blur the image faster. Setting the
- blur hints to QualityHint causes the implementation to improve
- visual quality at the expense of speed.
-
- AnimationHint causes the implementation to optimize for animating
- the blur radius, possibly by caching blurred versions of the source
- pixmap.
-
- The implementation is free to ignore this value if it only has a single
- blur algorithm.
-
- \internal
-*/
-void QPixmapBlurFilter::setBlurHints(QGraphicsBlurEffect::BlurHints hints)
-{
- Q_D(QPixmapBlurFilter);
- d->hints = hints;
-}
-
-/*!
- Gets the blur hints of the blur filter.
-
- \internal
-*/
-QGraphicsBlurEffect::BlurHints QPixmapBlurFilter::blurHints() const
-{
- Q_D(const QPixmapBlurFilter);
- return d->hints;
-}
-
-const qreal radiusScale = qreal(2.5);
-
-/*!
- \internal
-*/
-QRectF QPixmapBlurFilter::boundingRectFor(const QRectF &rect) const
-{
- Q_D(const QPixmapBlurFilter);
- const qreal delta = radiusScale * d->radius + 1;
- return rect.adjusted(-delta, -delta, delta, delta);
-}
-
-template <int shift>
-inline int qt_static_shift(int value)
-{
- if (shift == 0)
- return value;
- else if (shift > 0)
- return value << (uint(shift) & 0x1f);
- else
- return value >> (uint(-shift) & 0x1f);
-}
-
-template<int aprec, int zprec>
-inline void qt_blurinner(uchar *bptr, int &zR, int &zG, int &zB, int &zA, int alpha)
-{
- QRgb *pixel = (QRgb *)bptr;
-
-#define Z_MASK (0xff << zprec)
- const int A_zprec = qt_static_shift<zprec - 24>(*pixel) & Z_MASK;
- const int R_zprec = qt_static_shift<zprec - 16>(*pixel) & Z_MASK;
- const int G_zprec = qt_static_shift<zprec - 8>(*pixel) & Z_MASK;
- const int B_zprec = qt_static_shift<zprec>(*pixel) & Z_MASK;
-#undef Z_MASK
-
- const int zR_zprec = zR >> aprec;
- const int zG_zprec = zG >> aprec;
- const int zB_zprec = zB >> aprec;
- const int zA_zprec = zA >> aprec;
-
- zR += alpha * (R_zprec - zR_zprec);
- zG += alpha * (G_zprec - zG_zprec);
- zB += alpha * (B_zprec - zB_zprec);
- zA += alpha * (A_zprec - zA_zprec);
-
-#define ZA_MASK (0xff << (zprec + aprec))
- *pixel =
- qt_static_shift<24 - zprec - aprec>(zA & ZA_MASK)
- | qt_static_shift<16 - zprec - aprec>(zR & ZA_MASK)
- | qt_static_shift<8 - zprec - aprec>(zG & ZA_MASK)
- | qt_static_shift<-zprec - aprec>(zB & ZA_MASK);
-#undef ZA_MASK
-}
-
-const int alphaIndex = (QSysInfo::ByteOrder == QSysInfo::BigEndian ? 0 : 3);
-
-template<int aprec, int zprec>
-inline void qt_blurinner_alphaOnly(uchar *bptr, int &z, int alpha)
-{
- const int A_zprec = int(*(bptr)) << zprec;
- const int z_zprec = z >> aprec;
- z += alpha * (A_zprec - z_zprec);
- *(bptr) = z >> (zprec + aprec);
-}
-
-template<int aprec, int zprec, bool alphaOnly>
-inline void qt_blurrow(QImage & im, int line, int alpha)
-{
- uchar *bptr = im.scanLine(line);
-
- int zR = 0, zG = 0, zB = 0, zA = 0;
-
- if (alphaOnly && im.format() != QImage::Format_Indexed8)
- bptr += alphaIndex;
-
- const int stride = im.depth() >> 3;
- const int im_width = im.width();
- for (int index = 0; index < im_width; ++index) {
- if (alphaOnly)
- qt_blurinner_alphaOnly<aprec, zprec>(bptr, zA, alpha);
- else
- qt_blurinner<aprec, zprec>(bptr, zR, zG, zB, zA, alpha);
- bptr += stride;
- }
-
- bptr -= stride;
-
- for (int index = im_width - 2; index >= 0; --index) {
- bptr -= stride;
- if (alphaOnly)
- qt_blurinner_alphaOnly<aprec, zprec>(bptr, zA, alpha);
- else
- qt_blurinner<aprec, zprec>(bptr, zR, zG, zB, zA, alpha);
- }
-}
-
-/*
-* expblur(QImage &img, int radius)
-*
-* Based on exponential blur algorithm by Jani Huhtanen
-*
-* In-place blur of image 'img' with kernel
-* of approximate radius 'radius'.
-*
-* Blurs with two sided exponential impulse
-* response.
-*
-* aprec = precision of alpha parameter
-* in fixed-point format 0.aprec
-*
-* zprec = precision of state parameters
-* zR,zG,zB and zA in fp format 8.zprec
-*/
-template <int aprec, int zprec, bool alphaOnly>
-void expblur(QImage &img, qreal radius, bool improvedQuality = false, int transposed = 0)
-{
- // halve the radius if we're using two passes
- if (improvedQuality)
- radius *= qreal(0.5);
-
- Q_ASSERT(img.format() == QImage::Format_ARGB32_Premultiplied
- || img.format() == QImage::Format_RGB32
- || img.format() == QImage::Format_Indexed8);
-
- // choose the alpha such that pixels at radius distance from a fully
- // saturated pixel will have an alpha component of no greater than
- // the cutOffIntensity
- const qreal cutOffIntensity = 2;
- int alpha = radius <= qreal(1e-5)
- ? ((1 << aprec)-1)
- : qRound((1<<aprec)*(1 - qPow(cutOffIntensity * (1 / qreal(255)), 1 / radius)));
-
- int img_height = img.height();
- for (int row = 0; row < img_height; ++row) {
- for (int i = 0; i <= int(improvedQuality); ++i)
- qt_blurrow<aprec, zprec, alphaOnly>(img, row, alpha);
- }
-
- QImage temp(img.height(), img.width(), img.format());
- if (transposed >= 0) {
- if (img.depth() == 8) {
- qt_memrotate270(reinterpret_cast<const quint8*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint8*>(temp.bits()),
- temp.bytesPerLine());
- } else {
- qt_memrotate270(reinterpret_cast<const quint32*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint32*>(temp.bits()),
- temp.bytesPerLine());
- }
- } else {
- if (img.depth() == 8) {
- qt_memrotate90(reinterpret_cast<const quint8*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint8*>(temp.bits()),
- temp.bytesPerLine());
- } else {
- qt_memrotate90(reinterpret_cast<const quint32*>(img.bits()),
- img.width(), img.height(), img.bytesPerLine(),
- reinterpret_cast<quint32*>(temp.bits()),
- temp.bytesPerLine());
- }
- }
-
- img_height = temp.height();
- for (int row = 0; row < img_height; ++row) {
- for (int i = 0; i <= int(improvedQuality); ++i)
- qt_blurrow<aprec, zprec, alphaOnly>(temp, row, alpha);
- }
-
- if (transposed == 0) {
- if (img.depth() == 8) {
- qt_memrotate90(reinterpret_cast<const quint8*>(temp.bits()),
- temp.width(), temp.height(), temp.bytesPerLine(),
- reinterpret_cast<quint8*>(img.bits()),
- img.bytesPerLine());
- } else {
- qt_memrotate90(reinterpret_cast<const quint32*>(temp.bits()),
- temp.width(), temp.height(), temp.bytesPerLine(),
- reinterpret_cast<quint32*>(img.bits()),
- img.bytesPerLine());
- }
- } else {
- img = temp;
- }
-}
-#define AVG(a,b) ( ((((a)^(b)) & 0xfefefefeUL) >> 1) + ((a)&(b)) )
-#define AVG16(a,b) ( ((((a)^(b)) & 0xf7deUL) >> 1) + ((a)&(b)) )
-
-Q_GUI_EXPORT QImage qt_halfScaled(const QImage &source)
-{
- if (source.width() < 2 || source.height() < 2)
- return QImage();
-
- QImage srcImage = source;
-
- if (source.format() == QImage::Format_Indexed8) {
- // assumes grayscale
- QImage dest(source.width() / 2, source.height() / 2, srcImage.format());
-
- const uchar *src = reinterpret_cast<const uchar*>(const_cast<const QImage &>(srcImage).bits());
- int sx = srcImage.bytesPerLine();
- int sx2 = sx << 1;
-
- uchar *dst = reinterpret_cast<uchar*>(dest.bits());
- int dx = dest.bytesPerLine();
- int ww = dest.width();
- int hh = dest.height();
-
- for (int y = hh; y; --y, dst += dx, src += sx2) {
- const uchar *p1 = src;
- const uchar *p2 = src + sx;
- uchar *q = dst;
- for (int x = ww; x; --x, ++q, p1 += 2, p2 += 2)
- *q = ((int(p1[0]) + int(p1[1]) + int(p2[0]) + int(p2[1])) + 2) >> 2;
- }
-
- return dest;
- } else if (source.format() == QImage::Format_ARGB8565_Premultiplied) {
- QImage dest(source.width() / 2, source.height() / 2, srcImage.format());
-
- const uchar *src = reinterpret_cast<const uchar*>(const_cast<const QImage &>(srcImage).bits());
- int sx = srcImage.bytesPerLine();
- int sx2 = sx << 1;
-
- uchar *dst = reinterpret_cast<uchar*>(dest.bits());
- int dx = dest.bytesPerLine();
- int ww = dest.width();
- int hh = dest.height();
-
- for (int y = hh; y; --y, dst += dx, src += sx2) {
- const uchar *p1 = src;
- const uchar *p2 = src + sx;
- uchar *q = dst;
- for (int x = ww; x; --x, q += 3, p1 += 6, p2 += 6) {
- // alpha
- q[0] = AVG(AVG(p1[0], p1[3]), AVG(p2[0], p2[3]));
- // rgb
- const quint16 p16_1 = (p1[2] << 8) | p1[1];
- const quint16 p16_2 = (p1[5] << 8) | p1[4];
- const quint16 p16_3 = (p2[2] << 8) | p2[1];
- const quint16 p16_4 = (p2[5] << 8) | p2[4];
- const quint16 result = AVG16(AVG16(p16_1, p16_2), AVG16(p16_3, p16_4));
- q[1] = result & 0xff;
- q[2] = result >> 8;
- }
- }
-
- return dest;
- } else if (source.format() != QImage::Format_ARGB32_Premultiplied
- && source.format() != QImage::Format_RGB32)
- {
- srcImage = source.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- }
-
- QImage dest(source.width() / 2, source.height() / 2, srcImage.format());
-
- const quint32 *src = reinterpret_cast<const quint32*>(const_cast<const QImage &>(srcImage).bits());
- int sx = srcImage.bytesPerLine() >> 2;
- int sx2 = sx << 1;
-
- quint32 *dst = reinterpret_cast<quint32*>(dest.bits());
- int dx = dest.bytesPerLine() >> 2;
- int ww = dest.width();
- int hh = dest.height();
-
- for (int y = hh; y; --y, dst += dx, src += sx2) {
- const quint32 *p1 = src;
- const quint32 *p2 = src + sx;
- quint32 *q = dst;
- for (int x = ww; x; --x, q++, p1 += 2, p2 += 2)
- *q = AVG(AVG(p1[0], p1[1]), AVG(p2[0], p2[1]));
- }
-
- return dest;
-}
-
-Q_GUI_EXPORT void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0)
-{
- if (blurImage.format() != QImage::Format_ARGB32_Premultiplied
- && blurImage.format() != QImage::Format_RGB32)
- {
- blurImage = blurImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- }
-
- qreal scale = 1;
- if (radius >= 4 && blurImage.width() >= 2 && blurImage.height() >= 2) {
- blurImage = qt_halfScaled(blurImage);
- scale = 2;
- radius *= qreal(0.5);
- }
-
- if (alphaOnly)
- expblur<12, 10, true>(blurImage, radius, quality, transposed);
- else
- expblur<12, 10, false>(blurImage, radius, quality, transposed);
-
- if (p) {
- p->scale(scale, scale);
- p->setRenderHint(QPainter::SmoothPixmapTransform);
- p->drawImage(QRect(0, 0, blurImage.width(), blurImage.height()), blurImage);
- }
-}
-
-Q_GUI_EXPORT void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed = 0)
-{
- if (blurImage.format() == QImage::Format_Indexed8)
- expblur<12, 10, true>(blurImage, radius, quality, transposed);
- else
- expblur<12, 10, false>(blurImage, radius, quality, transposed);
-}
-
-Q_GUI_EXPORT bool qt_scaleForTransform(const QTransform &transform, qreal *scale);
-
-/*!
- \internal
-*/
-void QPixmapBlurFilter::draw(QPainter *painter, const QPointF &p, const QPixmap &src, const QRectF &rect) const
-{
- Q_D(const QPixmapBlurFilter);
- if (!painter->isActive())
- return;
-
- if (src.isNull())
- return;
-
- QRectF srcRect = rect;
- if (srcRect.isNull())
- srcRect = src.rect();
-
- if (d->radius <= 1) {
- painter->drawPixmap(srcRect.translated(p), src, srcRect);
- return;
- }
-
- qreal scaledRadius = radiusScale * d->radius;
- qreal scale;
- if (qt_scaleForTransform(painter->transform(), &scale))
- scaledRadius /= scale;
-
- QPixmapFilter *filter = painter->paintEngine() && painter->paintEngine()->isExtended() ?
- static_cast<QPaintEngineEx *>(painter->paintEngine())->pixmapFilter(type(), this) : 0;
- QPixmapBlurFilter *blurFilter = static_cast<QPixmapBlurFilter*>(filter);
- if (blurFilter) {
- blurFilter->setRadius(scaledRadius);
- blurFilter->setBlurHints(d->hints);
- blurFilter->draw(painter, p, src, srcRect);
- return;
- }
-
- QImage srcImage;
- QImage destImage;
-
- if (srcRect == src.rect()) {
- srcImage = src.toImage();
- } else {
- QRect rect = srcRect.toAlignedRect().intersected(src.rect());
- srcImage = src.copy(rect).toImage();
- }
-
- QTransform transform = painter->worldTransform();
- painter->translate(p);
- qt_blurImage(painter, srcImage, scaledRadius, (d->hints & QGraphicsBlurEffect::QualityHint), false);
- painter->setWorldTransform(transform);
-}
-
-// grayscales the image to dest (could be same). If rect isn't defined
-// destination image size is used to determine the dimension of grayscaling
-// process.
-static void grayscale(const QImage &image, QImage &dest, const QRect& rect = QRect())
-{
- QRect destRect = rect;
- QRect srcRect = rect;
- if (rect.isNull()) {
- srcRect = dest.rect();
- destRect = dest.rect();
- }
- if (&image != &dest) {
- destRect.moveTo(QPoint(0, 0));
- }
-
- unsigned int *data = (unsigned int *)image.bits();
- unsigned int *outData = (unsigned int *)dest.bits();
-
- if (dest.size() == image.size() && image.rect() == srcRect) {
- // a bit faster loop for grayscaling everything
- int pixels = dest.width() * dest.height();
- for (int i = 0; i < pixels; ++i) {
- int val = qGray(data[i]);
- outData[i] = qRgba(val, val, val, qAlpha(data[i]));
- }
- } else {
- int yd = destRect.top();
- for (int y = srcRect.top(); y <= srcRect.bottom() && y < image.height(); y++) {
- data = (unsigned int*)image.scanLine(y);
- outData = (unsigned int*)dest.scanLine(yd++);
- int xd = destRect.left();
- for (int x = srcRect.left(); x <= srcRect.right() && x < image.width(); x++) {
- int val = qGray(data[x]);
- outData[xd++] = qRgba(val, val, val, qAlpha(data[x]));
- }
- }
- }
-}
-
-/*!
- \class QPixmapColorizeFilter
- \since 4.5
- \ingroup painting
-
- \brief The QPixmapColorizeFilter class provides colorizing
- filtering for pixmaps.
-
- A colorize filter gives the pixmap a tint of its color(). The
- filter first grayscales the pixmap and then converts those to
- colorized values using QPainter::CompositionMode_Screen with the
- chosen color. The alpha-channel is not changed.
-
- Example:
- \snippet doc/src/snippets/code/src_gui_image_qpixmapfilter.cpp 0
-
- \sa QPainter::CompositionMode
-
- \internal
-*/
-class QPixmapColorizeFilterPrivate : public QPixmapFilterPrivate
-{
- Q_DECLARE_PUBLIC(QPixmapColorizeFilter)
-public:
- QColor color;
- qreal strength;
- quint32 opaque : 1;
- quint32 alphaBlend : 1;
- quint32 padding : 30;
-};
-
-/*!
- Constructs an pixmap colorize filter.
-
- Default color value for colorizing is QColor(0, 0, 192).
-
- \internal
-*/
-QPixmapColorizeFilter::QPixmapColorizeFilter(QObject *parent)
- : QPixmapFilter(*new QPixmapColorizeFilterPrivate, ColorizeFilter, parent)
-{
- Q_D(QPixmapColorizeFilter);
- d->color = QColor(0, 0, 192);
- d->strength = qreal(1);
- d->opaque = true;
- d->alphaBlend = false;
-}
-
-/*!
- Gets the color of the colorize filter.
-
- \internal
-*/
-QColor QPixmapColorizeFilter::color() const
-{
- Q_D(const QPixmapColorizeFilter);
- return d->color;
-}
-
-/*!
- Sets the color of the colorize filter to the \a color specified.
-
- \internal
-*/
-void QPixmapColorizeFilter::setColor(const QColor &color)
-{
- Q_D(QPixmapColorizeFilter);
- d->color = color;
-}
-
-/*!
- Gets the strength of the colorize filter, 1.0 means full colorized while
- 0.0 equals to no filtering at all.
-
- \internal
-*/
-qreal QPixmapColorizeFilter::strength() const
-{
- Q_D(const QPixmapColorizeFilter);
- return d->strength;
-}
-
-/*!
- Sets the strength of the colorize filter to \a strength.
-
- \internal
-*/
-void QPixmapColorizeFilter::setStrength(qreal strength)
-{
- Q_D(QPixmapColorizeFilter);
- d->strength = qBound(qreal(0), strength, qreal(1));
- d->opaque = !qFuzzyIsNull(d->strength);
- d->alphaBlend = !qFuzzyIsNull(d->strength - 1);
-}
-
-/*!
- \internal
-*/
-void QPixmapColorizeFilter::draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect) const
-{
- Q_D(const QPixmapColorizeFilter);
-
- if (src.isNull())
- return;
-
- QPixmapFilter *filter = painter->paintEngine() && painter->paintEngine()->isExtended() ?
- static_cast<QPaintEngineEx *>(painter->paintEngine())->pixmapFilter(type(), this) : 0;
- QPixmapColorizeFilter *colorizeFilter = static_cast<QPixmapColorizeFilter*>(filter);
- if (colorizeFilter) {
- colorizeFilter->setColor(d->color);
- colorizeFilter->setStrength(d->strength);
- colorizeFilter->draw(painter, dest, src, srcRect);
- return;
- }
-
- // falling back to raster implementation
-
- if (!d->opaque) {
- painter->drawPixmap(dest, src, srcRect);
- return;
- }
-
- QImage srcImage;
- QImage destImage;
-
- if (srcRect.isNull()) {
- srcImage = src.toImage();
- srcImage = srcImage.convertToFormat(srcImage.hasAlphaChannel() ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
- destImage = QImage(srcImage.size(), srcImage.format());
- } else {
- QRect rect = srcRect.toAlignedRect().intersected(src.rect());
-
- srcImage = src.copy(rect).toImage();
- srcImage = srcImage.convertToFormat(srcImage.hasAlphaChannel() ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
- destImage = QImage(rect.size(), srcImage.format());
- }
-
- // do colorizing
- QPainter destPainter(&destImage);
- grayscale(srcImage, destImage, srcImage.rect());
- destPainter.setCompositionMode(QPainter::CompositionMode_Screen);
- destPainter.fillRect(srcImage.rect(), d->color);
- destPainter.end();
-
- if (d->alphaBlend) {
- // alpha blending srcImage and destImage
- QImage buffer = srcImage;
- QPainter bufPainter(&buffer);
- bufPainter.setOpacity(d->strength);
- bufPainter.drawImage(0, 0, destImage);
- bufPainter.end();
- destImage = buffer;
- }
-
- if (srcImage.hasAlphaChannel())
- destImage.setAlphaChannel(srcImage.alphaChannel());
-
- painter->drawImage(dest, destImage);
-}
-
-class QPixmapDropShadowFilterPrivate : public QPixmapFilterPrivate
-{
-public:
- QPixmapDropShadowFilterPrivate()
- : offset(8, 8), color(63, 63, 63, 180), radius(1) {}
-
- QPointF offset;
- QColor color;
- qreal radius;
-};
-
-/*!
- \class QPixmapDropShadowFilter
- \since 4.5
- \ingroup painting
-
- \brief The QPixmapDropShadowFilter class is a convenience class
- for drawing pixmaps with drop shadows.
-
- The drop shadow is produced by taking a copy of the source pixmap
- and applying a color to the copy using a
- QPainter::CompositionMode_DestinationIn operation. This produces a
- homogeneously-colored pixmap which is then drawn using a
- QPixmapConvolutionFilter at an offset. The original pixmap is
- drawn on top.
-
- The QPixmapDropShadowFilter class provides some customization
- options to specify how the drop shadow should appear. The color of
- the drop shadow can be modified using the setColor() function, the
- drop shadow offset can be modified using the setOffset() function,
- and the blur radius of the drop shadow can be changed through the
- setBlurRadius() function.
-
- By default, the drop shadow is a dark gray shadow, blurred with a
- radius of 1 at an offset of 8 pixels towards the lower right.
-
- Example:
- \snippet doc/src/snippets/code/src_gui_image_qpixmapfilter.cpp 2
-
- \sa QPixmapColorizeFilter, QPixmapConvolutionFilter
-
- \internal
- */
-
-/*!
- Constructs drop shadow filter.
-
- \internal
-*/
-QPixmapDropShadowFilter::QPixmapDropShadowFilter(QObject *parent)
- : QPixmapFilter(*new QPixmapDropShadowFilterPrivate, DropShadowFilter, parent)
-{
-}
-
-/*!
- Destroys drop shadow filter.
-
- \internal
-*/
-QPixmapDropShadowFilter::~QPixmapDropShadowFilter()
-{
-}
-
-/*!
- Returns the radius in pixels of the blur on the drop shadow.
-
- A smaller radius results in a sharper shadow.
-
- \sa color(), offset()
-
- \internal
-*/
-qreal QPixmapDropShadowFilter::blurRadius() const
-{
- Q_D(const QPixmapDropShadowFilter);
- return d->radius;
-}
-
-/*!
- Sets the radius in pixels of the blur on the drop shadow to the \a radius specified.
-
- Using a smaller radius results in a sharper shadow.
-
- \sa setColor(), setOffset()
-
- \internal
-*/
-void QPixmapDropShadowFilter::setBlurRadius(qreal radius)
-{
- Q_D(QPixmapDropShadowFilter);
- d->radius = radius;
-}
-
-/*!
- Returns the color of the drop shadow.
-
- \sa blurRadius(), offset()
-
- \internal
-*/
-QColor QPixmapDropShadowFilter::color() const
-{
- Q_D(const QPixmapDropShadowFilter);
- return d->color;
-}
-
-/*!
- Sets the color of the drop shadow to the \a color specified.
-
- \sa setBlurRadius(), setOffset()
-
- \internal
-*/
-void QPixmapDropShadowFilter::setColor(const QColor &color)
-{
- Q_D(QPixmapDropShadowFilter);
- d->color = color;
-}
-
-/*!
- Returns the shadow offset in pixels.
-
- \sa blurRadius(), color()
-
- \internal
-*/
-QPointF QPixmapDropShadowFilter::offset() const
-{
- Q_D(const QPixmapDropShadowFilter);
- return d->offset;
-}
-
-/*!
- Sets the shadow offset in pixels to the \a offset specified.
-
- \sa setBlurRadius(), setColor()
-
- \internal
-*/
-void QPixmapDropShadowFilter::setOffset(const QPointF &offset)
-{
- Q_D(QPixmapDropShadowFilter);
- d->offset = offset;
-}
-
-/*!
- \fn void QPixmapDropShadowFilter::setOffset(qreal dx, qreal dy)
- \overload
-
- Sets the shadow offset in pixels to be the displacement specified by the
- horizontal \a dx and vertical \a dy coordinates.
-
- \sa setBlurRadius(), setColor()
-
- \internal
-*/
-
-/*!
- \internal
- */
-QRectF QPixmapDropShadowFilter::boundingRectFor(const QRectF &rect) const
-{
- Q_D(const QPixmapDropShadowFilter);
- return rect.united(rect.translated(d->offset).adjusted(-d->radius, -d->radius, d->radius, d->radius));
-}
-
-/*!
- \internal
- */
-void QPixmapDropShadowFilter::draw(QPainter *p,
- const QPointF &pos,
- const QPixmap &px,
- const QRectF &src) const
-{
- Q_D(const QPixmapDropShadowFilter);
-
- if (px.isNull())
- return;
-
- QPixmapFilter *filter = p->paintEngine() && p->paintEngine()->isExtended() ?
- static_cast<QPaintEngineEx *>(p->paintEngine())->pixmapFilter(type(), this) : 0;
- QPixmapDropShadowFilter *dropShadowFilter = static_cast<QPixmapDropShadowFilter*>(filter);
- if (dropShadowFilter) {
- dropShadowFilter->setColor(d->color);
- dropShadowFilter->setBlurRadius(d->radius);
- dropShadowFilter->setOffset(d->offset);
- dropShadowFilter->draw(p, pos, px, src);
- return;
- }
-
- QImage tmp(px.size(), QImage::Format_ARGB32_Premultiplied);
- tmp.fill(0);
- QPainter tmpPainter(&tmp);
- tmpPainter.setCompositionMode(QPainter::CompositionMode_Source);
- tmpPainter.drawPixmap(d->offset, px);
- tmpPainter.end();
-
- // blur the alpha channel
- QImage blurred(tmp.size(), QImage::Format_ARGB32_Premultiplied);
- blurred.fill(0);
- QPainter blurPainter(&blurred);
- qt_blurImage(&blurPainter, tmp, d->radius, false, true);
- blurPainter.end();
-
- tmp = blurred;
-
- // blacken the image...
- tmpPainter.begin(&tmp);
- tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
- tmpPainter.fillRect(tmp.rect(), d->color);
- tmpPainter.end();
-
- // draw the blurred drop shadow...
- p->drawImage(pos, tmp);
-
- // Draw the actual pixmap...
- p->drawPixmap(pos, px, src);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSEFFECT
diff --git a/src/gui/effects/qpixmapfilter_p.h b/src/gui/effects/qpixmapfilter_p.h
deleted file mode 100644
index 961866c19b..0000000000
--- a/src/gui/effects/qpixmapfilter_p.h
+++ /dev/null
@@ -1,196 +0,0 @@
-/****************************************************************************
-**
-** 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 QPIXMAPFILTER_H
-#define QPIXMAPFILTER_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qnamespace.h>
-#include <QtGui/qpixmap.h>
-#include <QtGui/qgraphicseffect.h>
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QPainter;
-class QPixmapData;
-
-class QPixmapFilterPrivate;
-
-class Q_GUI_EXPORT QPixmapFilter : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPixmapFilter)
-public:
- virtual ~QPixmapFilter() = 0;
-
- enum FilterType {
- ConvolutionFilter,
- ColorizeFilter,
- DropShadowFilter,
- BlurFilter,
-
- UserFilter = 1024
- };
-
- FilterType type() const;
-
- virtual QRectF boundingRectFor(const QRectF &rect) const;
-
- virtual void draw(QPainter *painter, const QPointF &p, const QPixmap &src, const QRectF &srcRect = QRectF()) const = 0;
-
-protected:
- QPixmapFilter(QPixmapFilterPrivate &d, FilterType type, QObject *parent);
- QPixmapFilter(FilterType type, QObject *parent);
-};
-
-class QPixmapConvolutionFilterPrivate;
-
-class Q_GUI_EXPORT QPixmapConvolutionFilter : public QPixmapFilter
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPixmapConvolutionFilter)
-
-public:
- QPixmapConvolutionFilter(QObject *parent = 0);
- ~QPixmapConvolutionFilter();
-
- void setConvolutionKernel(const qreal *matrix, int rows, int columns);
-
- QRectF boundingRectFor(const QRectF &rect) const;
- void draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect = QRectF()) const;
-
-private:
- friend class QGLPixmapConvolutionFilter;
- friend class QVGPixmapConvolutionFilter;
- const qreal *convolutionKernel() const;
- int rows() const;
- int columns() const;
-};
-
-class QPixmapBlurFilterPrivate;
-
-class Q_GUI_EXPORT QPixmapBlurFilter : public QPixmapFilter
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPixmapBlurFilter)
-
-public:
- QPixmapBlurFilter(QObject *parent = 0);
- ~QPixmapBlurFilter();
-
- void setRadius(qreal radius);
- void setBlurHints(QGraphicsBlurEffect::BlurHints hints);
-
- qreal radius() const;
- QGraphicsBlurEffect::BlurHints blurHints() const;
-
- QRectF boundingRectFor(const QRectF &rect) const;
- void draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect = QRectF()) const;
-
-private:
- friend class QGLPixmapBlurFilter;
-};
-
-class QPixmapColorizeFilterPrivate;
-
-class Q_GUI_EXPORT QPixmapColorizeFilter : public QPixmapFilter
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPixmapColorizeFilter)
-
-public:
- QPixmapColorizeFilter(QObject *parent = 0);
-
- void setColor(const QColor& color);
- QColor color() const;
-
- void setStrength(qreal strength);
- qreal strength() const;
-
- void draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect = QRectF()) const;
-};
-
-class QPixmapDropShadowFilterPrivate;
-
-class Q_GUI_EXPORT QPixmapDropShadowFilter : public QPixmapFilter
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPixmapDropShadowFilter)
-
-public:
- QPixmapDropShadowFilter(QObject *parent = 0);
- ~QPixmapDropShadowFilter();
-
- QRectF boundingRectFor(const QRectF &rect) const;
- void draw(QPainter *p, const QPointF &pos, const QPixmap &px, const QRectF &src = QRectF()) const;
-
- qreal blurRadius() const;
- void setBlurRadius(qreal radius);
-
- QColor color() const;
- void setColor(const QColor &color);
-
- QPointF offset() const;
- void setOffset(const QPointF &offset);
- inline void setOffset(qreal dx, qreal dy) { setOffset(QPointF(dx, dy)); }
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //QT_NO_GRAPHICSEFFECT
-#endif // QPIXMAPFILTER_H
diff --git a/src/gui/graphicsview/graphicsview.pri b/src/gui/graphicsview/graphicsview.pri
deleted file mode 100644
index 547d7ce7ae..0000000000
--- a/src/gui/graphicsview/graphicsview.pri
+++ /dev/null
@@ -1,52 +0,0 @@
-# Qt graphicsview module
-HEADERS += graphicsview/qgraphicsgridlayout.h \
- graphicsview/qgraphicsitem.h \
- graphicsview/qgraphicsitem_p.h \
- graphicsview/qgraphicsitemanimation.h \
- graphicsview/qgraphicslayout.h \
- graphicsview/qgraphicslayout_p.h \
- graphicsview/qgraphicslayoutitem.h \
- graphicsview/qgraphicslayoutitem_p.h \
- graphicsview/qgraphicslinearlayout.h \
- graphicsview/qgraphicsproxywidget.h \
- graphicsview/qgraphicsscene.h \
- graphicsview/qgraphicsscene_bsp_p.h \
- graphicsview/qgraphicsscene_p.h \
- graphicsview/qgraphicsscenebsptreeindex_p.h \
- graphicsview/qgraphicssceneevent.h \
- graphicsview/qgraphicssceneindex_p.h \
- graphicsview/qgraphicsscenelinearindex_p.h \
- graphicsview/qgraphicstransform.h \
- graphicsview/qgraphicstransform_p.h \
- graphicsview/qgraphicsview.h \
- graphicsview/qgraphicsview_p.h \
- graphicsview/qgraphicswidget.h \
- graphicsview/qgraphicswidget_p.h \
- graphicsview/qgridlayoutengine_p.h \
- graphicsview/qgraph_p.h \
- graphicsview/qsimplex_p.h \
- graphicsview/qgraphicsanchorlayout_p.h \
- graphicsview/qgraphicsanchorlayout.h
-
-SOURCES += graphicsview/qgraphicsgridlayout.cpp \
- graphicsview/qgraphicsitem.cpp \
- graphicsview/qgraphicsitemanimation.cpp \
- graphicsview/qgraphicslayout.cpp \
- graphicsview/qgraphicslayout_p.cpp \
- graphicsview/qgraphicslayoutitem.cpp \
- graphicsview/qgraphicslinearlayout.cpp \
- graphicsview/qgraphicsproxywidget.cpp \
- graphicsview/qgraphicsscene.cpp \
- graphicsview/qgraphicsscene_bsp.cpp \
- graphicsview/qgraphicsscenebsptreeindex.cpp \
- graphicsview/qgraphicssceneevent.cpp \
- graphicsview/qgraphicssceneindex.cpp \
- graphicsview/qgraphicsscenelinearindex.cpp \
- graphicsview/qgraphicstransform.cpp \
- graphicsview/qgraphicsview.cpp \
- graphicsview/qgraphicswidget.cpp \
- graphicsview/qgraphicswidget_p.cpp \
- graphicsview/qgridlayoutengine.cpp \
- graphicsview/qsimplex_p.cpp \
- graphicsview/qgraphicsanchorlayout_p.cpp \
- graphicsview/qgraphicsanchorlayout.cpp
diff --git a/src/gui/graphicsview/qgraph_p.h b/src/gui/graphicsview/qgraph_p.h
deleted file mode 100644
index 094fbd1c2a..0000000000
--- a/src/gui/graphicsview/qgraph_p.h
+++ /dev/null
@@ -1,286 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPH_P_H
-#define QGRAPH_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/QHash>
-#include <QtCore/QQueue>
-#include <QtCore/QString>
-#include <QtCore/QDebug>
-
-#include <float.h>
-
-QT_BEGIN_NAMESPACE
-
-template <typename Vertex, typename EdgeData>
-class Graph
-{
-public:
- Graph() {}
-
- class const_iterator {
- public:
- const_iterator(const Graph *graph, bool begin) : g(graph){
- if (begin) {
- row = g->m_graph.constBegin();
- //test if the graph is empty
- if (row != g->m_graph.constEnd())
- {
- column = (*row)->constBegin();
- }
- } else {
- row = g->m_graph.constEnd();
- }
- }
-
- inline Vertex *operator*() {
- return column.key();
- }
-
- inline Vertex *from() const {
- return row.key();
- }
-
- inline Vertex *to() const {
- return column.key();
- }
-
- inline bool operator==(const const_iterator &o) const { return !(*this != o); }
- inline bool operator!=(const const_iterator &o) const {
- if (row == g->m_graph.end()) {
- return row != o.row;
- } else {
- return row != o.row || column != o.column;
- }
- }
- inline const_iterator& operator=(const const_iterator &o) const { row = o.row; column = o.column; return *this;}
-
- // prefix
- const_iterator &operator++() {
- if (row != g->m_graph.constEnd()) {
- ++column;
- if (column == (*row)->constEnd()) {
- ++row;
- if (row != g->m_graph.constEnd()) {
- column = (*row)->constBegin();
- }
- }
- }
- return *this;
- }
-
- private:
- const Graph *g;
- Q_TYPENAME QHash<Vertex *, QHash<Vertex *, EdgeData *> * >::const_iterator row;
- Q_TYPENAME QHash<Vertex *, EdgeData *>::const_iterator column;
- };
-
- const_iterator constBegin() const {
- return const_iterator(this,true);
- }
-
- const_iterator constEnd() const {
- return const_iterator(this,false);
- }
-
- /*!
- * \internal
- *
- * If there is an edge between \a first and \a second, it will return a structure
- * containing the data associated with the edge, otherwise it will return 0.
- *
- */
- EdgeData *edgeData(Vertex* first, Vertex* second) {
- QHash<Vertex *, EdgeData *> *row = m_graph.value(first);
- return row ? row->value(second) : 0;
- }
-
- void createEdge(Vertex *first, Vertex *second, EdgeData *data)
- {
- // Creates a bidirectional edge
-#if defined(QT_DEBUG) && 0
- qDebug("Graph::createEdge(): %s",
- qPrintable(QString::fromAscii("%1-%2")
- .arg(first->toString()).arg(second->toString())));
-#endif
- if (edgeData(first, second)) {
-#ifdef QT_DEBUG
- qWarning("%s-%s already has an edge", qPrintable(first->toString()), qPrintable(second->toString()));
-#endif
- }
- createDirectedEdge(first, second, data);
- createDirectedEdge(second, first, data);
- }
-
- void removeEdge(Vertex *first, Vertex *second)
- {
- // Removes a bidirectional edge
-#if defined(QT_DEBUG) && 0
- qDebug("Graph::removeEdge(): %s",
- qPrintable(QString::fromAscii("%1-%2")
- .arg(first->toString()).arg(second->toString())));
-#endif
- EdgeData *data = edgeData(first, second);
- removeDirectedEdge(first, second);
- removeDirectedEdge(second, first);
- if (data) delete data;
- }
-
- EdgeData *takeEdge(Vertex* first, Vertex* second)
- {
-#if defined(QT_DEBUG) && 0
- qDebug("Graph::takeEdge(): %s",
- qPrintable(QString::fromAscii("%1-%2")
- .arg(first->toString()).arg(second->toString())));
-#endif
- // Removes a bidirectional edge
- EdgeData *data = edgeData(first, second);
- if (data) {
- removeDirectedEdge(first, second);
- removeDirectedEdge(second, first);
- }
- return data;
- }
-
- QList<Vertex *> adjacentVertices(Vertex *vertex) const
- {
- QHash<Vertex *, EdgeData *> *row = m_graph.value(vertex);
- QList<Vertex *> l;
- if (row)
- l = row->keys();
- return l;
- }
-
- QSet<Vertex*> vertices() const {
- QSet<Vertex *> setOfVertices;
- for (const_iterator it = constBegin(); it != constEnd(); ++it) {
- setOfVertices.insert(*it);
- }
- return setOfVertices;
- }
-
- QList<QPair<Vertex*, Vertex*> > connections() const {
- QList<QPair<Vertex*, Vertex*> > conns;
- for (const_iterator it = constBegin(); it != constEnd(); ++it) {
- Vertex *from = it.from();
- Vertex *to = it.to();
- // do not return (from,to) *and* (to,from)
- if (from < to) {
- conns.append(qMakePair(from, to));
- }
- }
- return conns;
- }
-
-#if defined(QT_DEBUG)
- QString serializeToDot() { // traversal
- QString strVertices;
- QString edges;
-
- QSet<Vertex *> setOfVertices = vertices();
- for (Q_TYPENAME QSet<Vertex*>::const_iterator it = setOfVertices.begin(); it != setOfVertices.end(); ++it) {
- Vertex *v = *it;
- QList<Vertex*> adjacents = adjacentVertices(v);
- for (int i = 0; i < adjacents.count(); ++i) {
- Vertex *v1 = adjacents.at(i);
- EdgeData *data = edgeData(v, v1);
- bool forward = data->from == v;
- if (forward) {
- edges += QString::fromAscii("\"%1\"->\"%2\" [label=\"[%3,%4,%5,%6,%7]\" color=\"#000000\"] \n")
- .arg(v->toString())
- .arg(v1->toString())
- .arg(data->minSize)
- .arg(data->minPrefSize)
- .arg(data->prefSize)
- .arg(data->maxPrefSize)
- .arg(data->maxSize)
- ;
- }
- }
- strVertices += QString::fromAscii("\"%1\" [label=\"%2\"]\n").arg(v->toString()).arg(v->toString());
- }
- return QString::fromAscii("%1\n%2\n").arg(strVertices).arg(edges);
- }
-#endif
-
-protected:
- void createDirectedEdge(Vertex *from, Vertex *to, EdgeData *data)
- {
- QHash<Vertex *, EdgeData *> *adjacentToFirst = m_graph.value(from);
- if (!adjacentToFirst) {
- adjacentToFirst = new QHash<Vertex *, EdgeData *>();
- m_graph.insert(from, adjacentToFirst);
- }
- adjacentToFirst->insert(to, data);
- }
-
- void removeDirectedEdge(Vertex *from, Vertex *to)
- {
- QHash<Vertex *, EdgeData *> *adjacentToFirst = m_graph.value(from);
- Q_ASSERT(adjacentToFirst);
-
- adjacentToFirst->remove(to);
- if (adjacentToFirst->isEmpty()) {
- //nobody point to 'from' so we can remove it from the graph
- m_graph.remove(from);
- delete adjacentToFirst;
- }
- }
-
-private:
- QHash<Vertex *, QHash<Vertex *, EdgeData *> *> m_graph;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout.cpp b/src/gui/graphicsview/qgraphicsanchorlayout.cpp
deleted file mode 100644
index 9bb5424641..0000000000
--- a/src/gui/graphicsview/qgraphicsanchorlayout.cpp
+++ /dev/null
@@ -1,533 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsAnchorLayout
- \brief The QGraphicsAnchorLayout class provides a layout where one can anchor widgets
- together in Graphics View.
- \since 4.6
- \ingroup appearance
- \ingroup geomanagement
- \ingroup graphicsview-api
-
- The anchor layout allows developers to specify how widgets should be placed relative to
- each other, and to the layout itself. The specification is made by adding anchors to the
- layout by calling addAnchor(), addAnchors() or addCornerAnchors().
-
- Existing anchors in the layout can be accessed with the anchor() function.
- Items that are anchored are automatically added to the layout, and if items
- are removed, all their anchors will be automatically removed.
-
- \div {class="float-left"}
- \inlineimage simpleanchorlayout-example.png Using an anchor layout to align simple colored widgets.
- \enddiv
-
- Anchors are always set up between edges of an item, where the "center" is also considered to
- be an edge. Consider the following example:
-
- \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding anchors
-
- Here, the right edge of item \c a is anchored to the left edge of item \c b and the bottom
- edge of item \c a is anchored to the top edge of item \c b, with the result that
- item \c b will be placed diagonally to the right and below item \c b.
-
- The addCornerAnchors() function provides a simpler way of anchoring the corners
- of two widgets than the two individual calls to addAnchor() shown in the code
- above. Here, we see how a widget can be anchored to the top-left corner of the enclosing
- layout:
-
- \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding a corner anchor
-
- In cases where anchors are used to match the widths or heights of widgets, it is
- convenient to use the addAnchors() function. As with the other functions for specifying
- anchors, it can also be used to anchor a widget to a layout.
-
- \clearfloat
- \section1 Size Hints and Size Policies in an Anchor Layout
-
- QGraphicsAnchorLayout respects each item's size hints and size policies.
- Note that there are some properties of QSizePolicy that are \l{Known issues}{not respected}.
-
- \section1 Spacing within an Anchor Layout
-
- The layout may distribute some space between the items. If the spacing has not been
- explicitly specified, the actual amount of space will usually be 0.
-
- However, if the first edge is the \e opposite of the second edge (e.g., the right edge
- of the first widget is anchored to the left edge of the second widget), the size of the
- anchor will be queried from the style through a pixel metric:
- \l{QStyle::}{PM_LayoutHorizontalSpacing} for horizontal anchors and
- \l{QStyle::}{PM_LayoutVerticalSpacing} for vertical anchors.
-
- If the spacing is negative, the items will overlap to some extent.
-
-
- \section1 Known issues
- There are some features that QGraphicsAnchorLayout currently does not support.
- This might change in the future, so avoid using these features if you want to
- avoid any future regressions in behaviour:
- \list
-
- \o Stretch factors are not respected.
-
- \o QSizePolicy::ExpandFlag is not respected.
-
- \o Height for width is not respected.
-
- \endlist
-
- \sa QGraphicsLinearLayout, QGraphicsGridLayout, QGraphicsLayout
-*/
-
-/*!
- \class QGraphicsAnchor
- \brief The QGraphicsAnchor class represents an anchor between two items in a
- QGraphicsAnchorLayout.
- \since 4.6
- \ingroup appearance
- \ingroup geomanagement
- \ingroup graphicsview-api
-
- The graphics anchor provides an API that enables you to query and manipulate the
- properties an anchor has. When an anchor is added to the layout with
- QGraphicsAnchorLayout::addAnchor(), a QGraphicsAnchor instance is returned where the properties
- are initialized to their default values. The properties can then be further changed, and they
- will be picked up the next time the layout is activated.
-
- \sa QGraphicsAnchorLayout::anchor()
-
-*/
-#include "qgraphicsanchorlayout_p.h"
-#ifndef QT_NO_GRAPHICSVIEW
-QT_BEGIN_NAMESPACE
-
-QGraphicsAnchor::QGraphicsAnchor(QGraphicsAnchorLayout *parentLayout)
- : QObject(*(new QGraphicsAnchorPrivate))
-{
- Q_D(QGraphicsAnchor);
- Q_ASSERT(parentLayout);
- d->layoutPrivate = parentLayout->d_func();
-}
-
-/*!
- Removes the QGraphicsAnchor object from the layout and destroys it.
-*/
-QGraphicsAnchor::~QGraphicsAnchor()
-{
-}
-
-/*!
- \property QGraphicsAnchor::sizePolicy
- \brief the size policy for the QGraphicsAnchor.
-
- By setting the size policy on an anchor you can configure how the anchor can resize itself
- from its preferred spacing. For instance, if the anchor has the size policy
- QSizePolicy::Minimum, the spacing is the minimum size of the anchor. However, its size
- can grow up to the anchors maximum size. If the default size policy is QSizePolicy::Fixed,
- the anchor can neither grow or shrink, which means that the only size the anchor can have
- is the spacing. QSizePolicy::Fixed is the default size policy.
- QGraphicsAnchor always has a minimum spacing of 0 and a very large maximum spacing.
-
- \sa QGraphicsAnchor::spacing
-*/
-
-void QGraphicsAnchor::setSizePolicy(QSizePolicy::Policy policy)
-{
- Q_D(QGraphicsAnchor);
- d->setSizePolicy(policy);
-}
-
-QSizePolicy::Policy QGraphicsAnchor::sizePolicy() const
-{
- Q_D(const QGraphicsAnchor);
- return d->sizePolicy;
-}
-
-/*!
- \property QGraphicsAnchor::spacing
- \brief the preferred space between items in the QGraphicsAnchorLayout.
-
- Depending on the anchor type, the default spacing is either
- 0 or a value returned from the style.
-
- \sa QGraphicsAnchorLayout::addAnchor()
-*/
-void QGraphicsAnchor::setSpacing(qreal spacing)
-{
- Q_D(QGraphicsAnchor);
- d->setSpacing(spacing);
-}
-
-qreal QGraphicsAnchor::spacing() const
-{
- Q_D(const QGraphicsAnchor);
- return d->spacing();
-}
-
-void QGraphicsAnchor::unsetSpacing()
-{
- Q_D(QGraphicsAnchor);
- d->unsetSpacing();
-}
-
-/*!
- Constructs a QGraphicsAnchorLayout instance. \a parent is passed to
- QGraphicsLayout's constructor.
- */
-QGraphicsAnchorLayout::QGraphicsAnchorLayout(QGraphicsLayoutItem *parent)
- : QGraphicsLayout(*new QGraphicsAnchorLayoutPrivate(), parent)
-{
- Q_D(QGraphicsAnchorLayout);
- d->createLayoutEdges();
-}
-
-/*!
- Destroys the QGraphicsAnchorLayout object.
-*/
-QGraphicsAnchorLayout::~QGraphicsAnchorLayout()
-{
- Q_D(QGraphicsAnchorLayout);
-
- for (int i = count() - 1; i >= 0; --i) {
- QGraphicsLayoutItem *item = d->items.at(i);
- removeAt(i);
- if (item) {
- if (item->ownedByLayout())
- delete item;
- }
- }
-
- d->removeCenterConstraints(this, QGraphicsAnchorLayoutPrivate::Horizontal);
- d->removeCenterConstraints(this, QGraphicsAnchorLayoutPrivate::Vertical);
- d->deleteLayoutEdges();
-
- Q_ASSERT(d->itemCenterConstraints[0].isEmpty());
- Q_ASSERT(d->itemCenterConstraints[1].isEmpty());
- Q_ASSERT(d->items.isEmpty());
- Q_ASSERT(d->m_vertexList.isEmpty());
-}
-
-/*!
- Creates an anchor between the edge \a firstEdge of item \a firstItem and the edge \a secondEdge
- of item \a secondItem. The spacing of the anchor is picked up from the style. Anchors
- between a layout edge and an item edge will have a size of 0.
- If there is already an anchor between the edges, the the new anchor will replace the old one.
-
- \a firstItem and \a secondItem are automatically added to the layout if they are not part
- of the layout. This means that count() can increase by up to 2.
-
- The spacing an anchor will get depends on the type of anchor. For instance, anchors from the
- Right edge of one item to the Left edge of another (or vice versa) will use the default
- horizontal spacing. The same behaviour applies to Bottom to Top anchors, (but they will use
- the default vertical spacing). For all other anchor combinations, the spacing will be 0.
- All anchoring functions will follow this rule.
-
- The spacing can also be set manually by using QGraphicsAnchor::setSpacing() method.
-
- Calling this function where \a firstItem or \a secondItem are ancestors of the layout have
- undefined behaviour.
-
- \sa addAnchors(), addCornerAnchors()
- */
-QGraphicsAnchor *
-QGraphicsAnchorLayout::addAnchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem, Qt::AnchorPoint secondEdge)
-{
- Q_D(QGraphicsAnchorLayout);
- QGraphicsAnchor *a = d->addAnchor(firstItem, firstEdge, secondItem, secondEdge);
- invalidate();
- return a;
-}
-
-/*!
- Returns the anchor between the anchor points defined by \a firstItem and \a firstEdge and
- \a secondItem and \a secondEdge. If there is no such anchor, the function will return 0.
-*/
-QGraphicsAnchor *
-QGraphicsAnchorLayout::anchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem, Qt::AnchorPoint secondEdge)
-{
- Q_D(QGraphicsAnchorLayout);
- return d->getAnchor(firstItem, firstEdge, secondItem, secondEdge);
-}
-
-/*!
- Creates two anchors between \a firstItem and \a secondItem specified by the corners,
- \a firstCorner and \a secondCorner, where one is for the horizontal edge and another
- one for the vertical edge.
-
- This is a convenience function, since anchoring corners can be expressed as anchoring
- two edges. For instance:
-
- \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding a corner anchor in two steps
-
- This can also be achieved with the following line of code:
-
- \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding a corner anchor
-
- If there is already an anchor between the edge pairs, it will be replaced by the anchors that
- this function specifies.
-
- \a firstItem and \a secondItem are automatically added to the layout if they are not part of the
- layout. This means that count() can increase by up to 2.
-
- \sa addAnchor(), addAnchors()
-*/
-void QGraphicsAnchorLayout::addCornerAnchors(QGraphicsLayoutItem *firstItem,
- Qt::Corner firstCorner,
- QGraphicsLayoutItem *secondItem,
- Qt::Corner secondCorner)
-{
- Q_D(QGraphicsAnchorLayout);
-
- // Horizontal anchor
- Qt::AnchorPoint firstEdge = (firstCorner & 1 ? Qt::AnchorRight: Qt::AnchorLeft);
- Qt::AnchorPoint secondEdge = (secondCorner & 1 ? Qt::AnchorRight: Qt::AnchorLeft);
- if (d->addAnchor(firstItem, firstEdge, secondItem, secondEdge)) {
- // Vertical anchor
- firstEdge = (firstCorner & 2 ? Qt::AnchorBottom: Qt::AnchorTop);
- secondEdge = (secondCorner & 2 ? Qt::AnchorBottom: Qt::AnchorTop);
- d->addAnchor(firstItem, firstEdge, secondItem, secondEdge);
-
- invalidate();
- }
-}
-
-/*!
- Anchors two or four edges of \a firstItem with the corresponding
- edges of \a secondItem, so that \a firstItem has the same size as
- \a secondItem in the dimensions specified by \a orientations.
-
- For example, the following example anchors the left and right edges of two items
- to match their widths:
-
- \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding anchors to match sizes in two steps
-
- This can also be achieved using the following line of code:
-
- \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding anchors to match sizes
-
- \sa addAnchor(), addCornerAnchors()
-*/
-void QGraphicsAnchorLayout::addAnchors(QGraphicsLayoutItem *firstItem,
- QGraphicsLayoutItem *secondItem,
- Qt::Orientations orientations)
-{
- bool ok = true;
- if (orientations & Qt::Horizontal) {
- // Currently, if the first is ok, then the rest of the calls should be ok
- ok = addAnchor(secondItem, Qt::AnchorLeft, firstItem, Qt::AnchorLeft) != 0;
- if (ok)
- addAnchor(firstItem, Qt::AnchorRight, secondItem, Qt::AnchorRight);
- }
- if (orientations & Qt::Vertical && ok) {
- addAnchor(secondItem, Qt::AnchorTop, firstItem, Qt::AnchorTop);
- addAnchor(firstItem, Qt::AnchorBottom, secondItem, Qt::AnchorBottom);
- }
-}
-
-/*!
- Sets the default horizontal spacing for the anchor layout to \a spacing.
-
- \sa horizontalSpacing(), setVerticalSpacing(), setSpacing()
-*/
-void QGraphicsAnchorLayout::setHorizontalSpacing(qreal spacing)
-{
- Q_D(QGraphicsAnchorLayout);
-
- d->spacings[0] = spacing;
- invalidate();
-}
-
-/*!
- Sets the default vertical spacing for the anchor layout to \a spacing.
-
- \sa verticalSpacing(), setHorizontalSpacing(), setSpacing()
-*/
-void QGraphicsAnchorLayout::setVerticalSpacing(qreal spacing)
-{
- Q_D(QGraphicsAnchorLayout);
-
- d->spacings[1] = spacing;
- invalidate();
-}
-
-/*!
- Sets the default horizontal and the default vertical spacing for the anchor layout to \a spacing.
-
- If an item is anchored with no spacing associated with the anchor, it will use the default
- spacing.
-
- QGraphicsAnchorLayout does not support negative spacings. Setting a negative value will unset the
- previous spacing and make the layout use the spacing provided by the current widget style.
-
- \sa setHorizontalSpacing(), setVerticalSpacing()
-*/
-void QGraphicsAnchorLayout::setSpacing(qreal spacing)
-{
- Q_D(QGraphicsAnchorLayout);
-
- d->spacings[0] = d->spacings[1] = spacing;
- invalidate();
-}
-
-/*!
- Returns the default horizontal spacing for the anchor layout.
-
- \sa verticalSpacing(), setHorizontalSpacing()
-*/
-qreal QGraphicsAnchorLayout::horizontalSpacing() const
-{
- Q_D(const QGraphicsAnchorLayout);
- return d->styleInfo().defaultSpacing(Qt::Horizontal);
-}
-
-/*!
- Returns the default vertical spacing for the anchor layout.
-
- \sa horizontalSpacing(), setVerticalSpacing()
-*/
-qreal QGraphicsAnchorLayout::verticalSpacing() const
-{
- Q_D(const QGraphicsAnchorLayout);
- return d->styleInfo().defaultSpacing(Qt::Vertical);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsAnchorLayout::setGeometry(const QRectF &geom)
-{
- Q_D(QGraphicsAnchorLayout);
-
- QGraphicsLayout::setGeometry(geom);
- d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Horizontal);
- d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Vertical);
- d->setItemsGeometries(geom);
-}
-
-/*!
- Removes the layout item at \a index without destroying it. Ownership of
- the item is transferred to the caller.
-
- Removing an item will also remove any of the anchors associated with it.
-
- \sa itemAt(), count()
-*/
-void QGraphicsAnchorLayout::removeAt(int index)
-{
- Q_D(QGraphicsAnchorLayout);
- QGraphicsLayoutItem *item = d->items.value(index);
-
- if (!item)
- return;
-
- // Removing an item affects both horizontal and vertical graphs
- d->removeCenterConstraints(item, QGraphicsAnchorLayoutPrivate::Horizontal);
- d->removeCenterConstraints(item, QGraphicsAnchorLayoutPrivate::Vertical);
- d->removeAnchors(item);
- d->items.remove(index);
-
- item->setParentLayoutItem(0);
- invalidate();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsAnchorLayout::count() const
-{
- Q_D(const QGraphicsAnchorLayout);
- return d->items.size();
-}
-
-/*!
- \reimp
-*/
-QGraphicsLayoutItem *QGraphicsAnchorLayout::itemAt(int index) const
-{
- Q_D(const QGraphicsAnchorLayout);
- return d->items.value(index);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsAnchorLayout::invalidate()
-{
- Q_D(QGraphicsAnchorLayout);
- QGraphicsLayout::invalidate();
- d->calculateGraphCacheDirty = true;
- d->styleInfoDirty = true;
-}
-
-/*!
- \reimp
-*/
-QSizeF QGraphicsAnchorLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- Q_UNUSED(constraint);
- Q_D(const QGraphicsAnchorLayout);
-
- // Some setup calculations are delayed until the information is
- // actually needed, avoiding unnecessary recalculations when
- // adding multiple anchors.
-
- // sizeHint() / effectiveSizeHint() already have a cache
- // mechanism, using invalidate() to force recalculation. However
- // sizeHint() is called three times after invalidation (for max,
- // min and pref), but we just need do our setup once.
-
- const_cast<QGraphicsAnchorLayoutPrivate *>(d)->calculateGraphs();
-
- // ### apply constraint!
- QSizeF engineSizeHint(
- d->sizeHints[QGraphicsAnchorLayoutPrivate::Horizontal][which],
- d->sizeHints[QGraphicsAnchorLayoutPrivate::Vertical][which]);
-
- qreal left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
-
- return engineSizeHint + QSizeF(left + right, top + bottom);
-}
-
-QT_END_NAMESPACE
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout.h b/src/gui/graphicsview/qgraphicsanchorlayout.h
deleted file mode 100644
index cdb14bc3ba..0000000000
--- a/src/gui/graphicsview/qgraphicsanchorlayout.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSANCHORLAYOUT_H
-#define QGRAPHICSANCHORLAYOUT_H
-
-#include <QtGui/qgraphicsitem.h>
-#include <QtGui/qgraphicslayout.h>
-
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsAnchorPrivate;
-class QGraphicsAnchorLayout;
-class QGraphicsAnchorLayoutPrivate;
-
-class Q_GUI_EXPORT QGraphicsAnchor : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing RESET unsetSpacing)
- Q_PROPERTY(QSizePolicy::Policy sizePolicy READ sizePolicy WRITE setSizePolicy)
-public:
- void setSpacing(qreal spacing);
- void unsetSpacing();
- qreal spacing() const;
- void setSizePolicy(QSizePolicy::Policy policy);
- QSizePolicy::Policy sizePolicy() const;
- ~QGraphicsAnchor();
-private:
- QGraphicsAnchor(QGraphicsAnchorLayout *parent);
-
- Q_DECLARE_PRIVATE(QGraphicsAnchor)
-
- friend class QGraphicsAnchorLayoutPrivate;
- friend struct AnchorData;
-};
-
-class Q_GUI_EXPORT QGraphicsAnchorLayout : public QGraphicsLayout
-{
-public:
- QGraphicsAnchorLayout(QGraphicsLayoutItem *parent = 0);
- virtual ~QGraphicsAnchorLayout();
-
- QGraphicsAnchor *addAnchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem, Qt::AnchorPoint secondEdge);
- QGraphicsAnchor *anchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem, Qt::AnchorPoint secondEdge);
-
- void addCornerAnchors(QGraphicsLayoutItem *firstItem, Qt::Corner firstCorner,
- QGraphicsLayoutItem *secondItem, Qt::Corner secondCorner);
-
- void addAnchors(QGraphicsLayoutItem *firstItem,
- QGraphicsLayoutItem *secondItem,
- Qt::Orientations orientations = Qt::Horizontal | Qt::Vertical);
-
- void setHorizontalSpacing(qreal spacing);
- void setVerticalSpacing(qreal spacing);
- void setSpacing(qreal spacing);
- qreal horizontalSpacing() const;
- qreal verticalSpacing() const;
-
- void removeAt(int index);
- void setGeometry(const QRectF &rect);
- int count() const;
- QGraphicsLayoutItem *itemAt(int index) const;
-
- void invalidate();
-protected:
- QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsAnchorLayout)
- Q_DECLARE_PRIVATE(QGraphicsAnchorLayout)
-
- friend class QGraphicsAnchor;
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp
deleted file mode 100644
index 48cbec3d62..0000000000
--- a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp
+++ /dev/null
@@ -1,3015 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtGui/qwidget.h>
-#include <QtGui/qapplication.h>
-#include <QtCore/qlinkedlist.h>
-#include <QtCore/qstack.h>
-
-#ifdef QT_DEBUG
-#include <QtCore/qfile.h>
-#endif
-
-#include "qgraphicsanchorlayout_p.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-QT_BEGIN_NAMESPACE
-
-// To ensure that all variables inside the simplex solver are non-negative,
-// we limit the size of anchors in the interval [-limit, limit]. Then before
-// sending them to the simplex solver we add "limit" as an offset, so that
-// they are actually calculated in the interval [0, 2 * limit]
-// To avoid numerical errors in platforms where we use single precision,
-// we use a tighter limit for the variables range.
-const qreal g_offset = (sizeof(qreal) == sizeof(double)) ? QWIDGETSIZE_MAX : QWIDGETSIZE_MAX / 32;
-
-QGraphicsAnchorPrivate::QGraphicsAnchorPrivate(int version)
- : QObjectPrivate(version), layoutPrivate(0), data(0),
- sizePolicy(QSizePolicy::Fixed), preferredSize(0),
- hasSize(true)
-{
-}
-
-QGraphicsAnchorPrivate::~QGraphicsAnchorPrivate()
-{
- if (data) {
- // The QGraphicsAnchor was already deleted at this moment. We must clean
- // the dangling pointer to avoid double deletion in the AnchorData dtor.
- data->graphicsAnchor = 0;
-
- layoutPrivate->removeAnchor(data->from, data->to);
- }
-}
-
-void QGraphicsAnchorPrivate::setSizePolicy(QSizePolicy::Policy policy)
-{
- if (sizePolicy != policy) {
- sizePolicy = policy;
- layoutPrivate->q_func()->invalidate();
- }
-}
-
-void QGraphicsAnchorPrivate::setSpacing(qreal value)
-{
- if (!data) {
- qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
- return;
- }
-
- if (hasSize && (preferredSize == value))
- return;
-
- // The anchor has an user-defined size
- hasSize = true;
- preferredSize = value;
-
- layoutPrivate->q_func()->invalidate();
-}
-
-void QGraphicsAnchorPrivate::unsetSpacing()
-{
- if (!data) {
- qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
- return;
- }
-
- // Return to standard direction
- hasSize = false;
-
- layoutPrivate->q_func()->invalidate();
-}
-
-qreal QGraphicsAnchorPrivate::spacing() const
-{
- if (!data) {
- qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
- return 0;
- }
-
- return preferredSize;
-}
-
-
-static void applySizePolicy(QSizePolicy::Policy policy,
- qreal minSizeHint, qreal prefSizeHint, qreal maxSizeHint,
- qreal *minSize, qreal *prefSize,
- qreal *maxSize)
-{
- // minSize, prefSize and maxSize are initialized
- // with item's preferred Size: this is QSizePolicy::Fixed.
- //
- // Then we check each flag to find the resultant QSizePolicy,
- // according to the following table:
- //
- // constant value
- // QSizePolicy::Fixed 0
- // QSizePolicy::Minimum GrowFlag
- // QSizePolicy::Maximum ShrinkFlag
- // QSizePolicy::Preferred GrowFlag | ShrinkFlag
- // QSizePolicy::Ignored GrowFlag | ShrinkFlag | IgnoreFlag
-
- if (policy & QSizePolicy::ShrinkFlag)
- *minSize = minSizeHint;
- else
- *minSize = prefSizeHint;
-
- if (policy & QSizePolicy::GrowFlag)
- *maxSize = maxSizeHint;
- else
- *maxSize = prefSizeHint;
-
- // Note that these two initializations are affected by the previous flags
- if (policy & QSizePolicy::IgnoreFlag)
- *prefSize = *minSize;
- else
- *prefSize = prefSizeHint;
-}
-
-AnchorData::~AnchorData()
-{
- if (graphicsAnchor) {
- // Remove reference to ourself to avoid double removal in
- // QGraphicsAnchorPrivate dtor.
- graphicsAnchor->d_func()->data = 0;
-
- delete graphicsAnchor;
- }
-}
-
-
-void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo)
-{
- QSizePolicy::Policy policy;
- qreal minSizeHint;
- qreal prefSizeHint;
- qreal maxSizeHint;
-
- if (item) {
- // It is an internal anchor, fetch size information from the item
- if (isLayoutAnchor) {
- minSize = 0;
- prefSize = 0;
- maxSize = QWIDGETSIZE_MAX;
- if (isCenterAnchor)
- maxSize /= 2;
-
- minPrefSize = prefSize;
- maxPrefSize = maxSize;
- return;
- } else {
- if (orientation == QGraphicsAnchorLayoutPrivate::Horizontal) {
- policy = item->sizePolicy().horizontalPolicy();
- minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).width();
- prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).width();
- maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).width();
- } else {
- policy = item->sizePolicy().verticalPolicy();
- minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).height();
- prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).height();
- maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).height();
- }
-
- if (isCenterAnchor) {
- minSizeHint /= 2;
- prefSizeHint /= 2;
- maxSizeHint /= 2;
- }
- }
- } else {
- // It is a user-created anchor, fetch size information from the associated QGraphicsAnchor
- Q_ASSERT(graphicsAnchor);
- QGraphicsAnchorPrivate *anchorPrivate = graphicsAnchor->d_func();
-
- // Policy, min and max sizes are straightforward
- policy = anchorPrivate->sizePolicy;
- minSizeHint = 0;
- maxSizeHint = QWIDGETSIZE_MAX;
-
- // Preferred Size
- if (anchorPrivate->hasSize) {
- // Anchor has user-defined size
- prefSizeHint = anchorPrivate->preferredSize;
- } else {
- // Fetch size information from style
- const Qt::Orientation orient = Qt::Orientation(QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge) + 1);
- qreal s = styleInfo->defaultSpacing(orient);
- if (s < 0) {
- QSizePolicy::ControlType controlTypeFrom = from->m_item->sizePolicy().controlType();
- QSizePolicy::ControlType controlTypeTo = to->m_item->sizePolicy().controlType();
- s = styleInfo->perItemSpacing(controlTypeFrom, controlTypeTo, orient);
-
- // ### Currently we do not support negative anchors inside the graph.
- // To avoid those being created by a negative style spacing, we must
- // make this test.
- if (s < 0)
- s = 0;
- }
- prefSizeHint = s;
- }
- }
-
- // Fill minSize, prefSize and maxSize based on policy and sizeHints
- applySizePolicy(policy, minSizeHint, prefSizeHint, maxSizeHint,
- &minSize, &prefSize, &maxSize);
-
- minPrefSize = prefSize;
- maxPrefSize = maxSize;
-
- // Set the anchor effective sizes to preferred.
- //
- // Note: The idea here is that all items should remain at their
- // preferred size unless where that's impossible. In cases where
- // the item is subject to restrictions (anchored to the layout
- // edges, for instance), the simplex solver will be run to
- // recalculate and override the values we set here.
- sizeAtMinimum = prefSize;
- sizeAtPreferred = prefSize;
- sizeAtMaximum = prefSize;
-}
-
-void ParallelAnchorData::updateChildrenSizes()
-{
- firstEdge->sizeAtMinimum = sizeAtMinimum;
- firstEdge->sizeAtPreferred = sizeAtPreferred;
- firstEdge->sizeAtMaximum = sizeAtMaximum;
-
- if (secondForward()) {
- secondEdge->sizeAtMinimum = sizeAtMinimum;
- secondEdge->sizeAtPreferred = sizeAtPreferred;
- secondEdge->sizeAtMaximum = sizeAtMaximum;
- } else {
- secondEdge->sizeAtMinimum = -sizeAtMinimum;
- secondEdge->sizeAtPreferred = -sizeAtPreferred;
- secondEdge->sizeAtMaximum = -sizeAtMaximum;
- }
-
- firstEdge->updateChildrenSizes();
- secondEdge->updateChildrenSizes();
-}
-
-/*
- \internal
-
- Initialize the parallel anchor size hints using the sizeHint information from
- its children.
-
- Note that parallel groups can lead to unfeasibility, so during calculation, we can
- find out one unfeasibility. Because of that this method return boolean. This can't
- happen in sequential, so there the method is void.
- */
-bool ParallelAnchorData::calculateSizeHints()
-{
- // Normalize second child sizes.
- // A negative anchor of sizes min, minPref, pref, maxPref and max, is equivalent
- // to a forward anchor of sizes -max, -maxPref, -pref, -minPref, -min
- qreal secondMin;
- qreal secondMinPref;
- qreal secondPref;
- qreal secondMaxPref;
- qreal secondMax;
-
- if (secondForward()) {
- secondMin = secondEdge->minSize;
- secondMinPref = secondEdge->minPrefSize;
- secondPref = secondEdge->prefSize;
- secondMaxPref = secondEdge->maxPrefSize;
- secondMax = secondEdge->maxSize;
- } else {
- secondMin = -secondEdge->maxSize;
- secondMinPref = -secondEdge->maxPrefSize;
- secondPref = -secondEdge->prefSize;
- secondMaxPref = -secondEdge->minPrefSize;
- secondMax = -secondEdge->minSize;
- }
-
- minSize = qMax(firstEdge->minSize, secondMin);
- maxSize = qMin(firstEdge->maxSize, secondMax);
-
- // This condition means that the maximum size of one anchor being simplified is smaller than
- // the minimum size of the other anchor. The consequence is that there won't be a valid size
- // for this parallel setup.
- if (minSize > maxSize) {
- return false;
- }
-
- // Preferred size calculation
- // The calculation of preferred size is done as follows:
- //
- // 1) Check whether one of the child anchors is the layout structural anchor
- // If so, we can simply copy the preferred information from the other child,
- // after bounding it to our minimum and maximum sizes.
- // If not, then we proceed with the actual calculations.
- //
- // 2) The whole algorithm for preferred size calculation is based on the fact
- // that, if a given anchor cannot remain at its preferred size, it'd rather
- // grow than shrink.
- //
- // What happens though is that while this affirmative is true for simple
- // anchors, it may not be true for sequential anchors that have one or more
- // reversed anchors inside it. That happens because when a sequential anchor
- // grows, any reversed anchors inside it may be required to shrink, something
- // we try to avoid, as said above.
- //
- // To overcome this, besides their actual preferred size "prefSize", each anchor
- // exports what we call "minPrefSize" and "maxPrefSize". These two values define
- // a surrounding interval where, if required to move, the anchor would rather
- // remain inside.
- //
- // For standard anchors, this area simply represents the region between
- // prefSize and maxSize, which makes sense since our first affirmation.
- // For composed anchors, these values are calculated as to reduce the global
- // "damage", that is, to reduce the total deviation and the total amount of
- // anchors that had to shrink.
-
- if (firstEdge->isLayoutAnchor) {
- prefSize = qBound(minSize, secondPref, maxSize);
- minPrefSize = qBound(minSize, secondMinPref, maxSize);
- maxPrefSize = qBound(minSize, secondMaxPref, maxSize);
- } else if (secondEdge->isLayoutAnchor) {
- prefSize = qBound(minSize, firstEdge->prefSize, maxSize);
- minPrefSize = qBound(minSize, firstEdge->minPrefSize, maxSize);
- maxPrefSize = qBound(minSize, firstEdge->maxPrefSize, maxSize);
- } else {
- // Calculate the intersection between the "preferred" regions of each child
- const qreal lowerBoundary =
- qBound(minSize, qMax(firstEdge->minPrefSize, secondMinPref), maxSize);
- const qreal upperBoundary =
- qBound(minSize, qMin(firstEdge->maxPrefSize, secondMaxPref), maxSize);
- const qreal prefMean =
- qBound(minSize, (firstEdge->prefSize + secondPref) / 2, maxSize);
-
- if (lowerBoundary < upperBoundary) {
- // If there is an intersection between the two regions, this intersection
- // will be used as the preferred region of the parallel anchor itself.
- // The preferred size will be the bounded average between the two preferred
- // sizes.
- prefSize = qBound(lowerBoundary, prefMean, upperBoundary);
- minPrefSize = lowerBoundary;
- maxPrefSize = upperBoundary;
- } else {
- // If there is no intersection, we have to attribute "damage" to at least
- // one of the children. The minimum total damage is achieved in points
- // inside the region that extends from (1) the upper boundary of the lower
- // region to (2) the lower boundary of the upper region.
- // Then, we expose this region as _our_ preferred region and once again,
- // use the bounded average as our preferred size.
- prefSize = qBound(upperBoundary, prefMean, lowerBoundary);
- minPrefSize = upperBoundary;
- maxPrefSize = lowerBoundary;
- }
- }
-
- // See comment in AnchorData::refreshSizeHints() about sizeAt* values
- sizeAtMinimum = prefSize;
- sizeAtPreferred = prefSize;
- sizeAtMaximum = prefSize;
-
- return true;
-}
-
-/*!
- \internal
- returns the factor in the interval [-1, 1].
- -1 is at Minimum
- 0 is at Preferred
- 1 is at Maximum
-*/
-static QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> getFactor(qreal value, qreal min,
- qreal minPref, qreal pref,
- qreal maxPref, qreal max)
-{
- QGraphicsAnchorLayoutPrivate::Interval interval;
- qreal lower;
- qreal upper;
-
- if (value < minPref) {
- interval = QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred;
- lower = min;
- upper = minPref;
- } else if (value < pref) {
- interval = QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred;
- lower = minPref;
- upper = pref;
- } else if (value < maxPref) {
- interval = QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred;
- lower = pref;
- upper = maxPref;
- } else {
- interval = QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum;
- lower = maxPref;
- upper = max;
- }
-
- qreal progress;
- if (upper == lower) {
- progress = 0;
- } else {
- progress = (value - lower) / (upper - lower);
- }
-
- return qMakePair(interval, progress);
-}
-
-static qreal interpolate(const QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> &factor,
- qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
-{
- qreal lower;
- qreal upper;
-
- switch (factor.first) {
- case QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred:
- lower = min;
- upper = minPref;
- break;
- case QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred:
- lower = minPref;
- upper = pref;
- break;
- case QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred:
- lower = pref;
- upper = maxPref;
- break;
- case QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum:
- lower = maxPref;
- upper = max;
- break;
- }
-
- return lower + factor.second * (upper - lower);
-}
-
-void SequentialAnchorData::updateChildrenSizes()
-{
- // Band here refers if the value is in the Minimum To Preferred
- // band (the lower band) or the Preferred To Maximum (the upper band).
-
- const QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> minFactor =
- getFactor(sizeAtMinimum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
- const QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> prefFactor =
- getFactor(sizeAtPreferred, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
- const QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> maxFactor =
- getFactor(sizeAtMaximum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
-
- // XXX This is not safe if Vertex simplification takes place after the sequential
- // anchor is created. In that case, "prev" will be a group-vertex, different from
- // "from" or "to", that _contains_ one of them.
- AnchorVertex *prev = from;
-
- for (int i = 0; i < m_edges.count(); ++i) {
- AnchorData *e = m_edges.at(i);
-
- const bool edgeIsForward = (e->from == prev);
- if (edgeIsForward) {
- e->sizeAtMinimum = interpolate(minFactor, e->minSize, e->minPrefSize,
- e->prefSize, e->maxPrefSize, e->maxSize);
- e->sizeAtPreferred = interpolate(prefFactor, e->minSize, e->minPrefSize,
- e->prefSize, e->maxPrefSize, e->maxSize);
- e->sizeAtMaximum = interpolate(maxFactor, e->minSize, e->minPrefSize,
- e->prefSize, e->maxPrefSize, e->maxSize);
- prev = e->to;
- } else {
- Q_ASSERT(prev == e->to);
- e->sizeAtMinimum = interpolate(minFactor, e->maxSize, e->maxPrefSize,
- e->prefSize, e->minPrefSize, e->minSize);
- e->sizeAtPreferred = interpolate(prefFactor, e->maxSize, e->maxPrefSize,
- e->prefSize, e->minPrefSize, e->minSize);
- e->sizeAtMaximum = interpolate(maxFactor, e->maxSize, e->maxPrefSize,
- e->prefSize, e->minPrefSize, e->minSize);
- prev = e->from;
- }
-
- e->updateChildrenSizes();
- }
-}
-
-void SequentialAnchorData::calculateSizeHints()
-{
- minSize = 0;
- prefSize = 0;
- maxSize = 0;
- minPrefSize = 0;
- maxPrefSize = 0;
-
- AnchorVertex *prev = from;
-
- for (int i = 0; i < m_edges.count(); ++i) {
- AnchorData *edge = m_edges.at(i);
-
- const bool edgeIsForward = (edge->from == prev);
- if (edgeIsForward) {
- minSize += edge->minSize;
- prefSize += edge->prefSize;
- maxSize += edge->maxSize;
- minPrefSize += edge->minPrefSize;
- maxPrefSize += edge->maxPrefSize;
- prev = edge->to;
- } else {
- Q_ASSERT(prev == edge->to);
- minSize -= edge->maxSize;
- prefSize -= edge->prefSize;
- maxSize -= edge->minSize;
- minPrefSize -= edge->maxPrefSize;
- maxPrefSize -= edge->minPrefSize;
- prev = edge->from;
- }
- }
-
- // See comment in AnchorData::refreshSizeHints() about sizeAt* values
- sizeAtMinimum = prefSize;
- sizeAtPreferred = prefSize;
- sizeAtMaximum = prefSize;
-}
-
-#ifdef QT_DEBUG
-void AnchorData::dump(int indent) {
- if (type == Parallel) {
- qDebug("%*s type: parallel:", indent, "");
- ParallelAnchorData *p = static_cast<ParallelAnchorData *>(this);
- p->firstEdge->dump(indent+2);
- p->secondEdge->dump(indent+2);
- } else if (type == Sequential) {
- SequentialAnchorData *s = static_cast<SequentialAnchorData *>(this);
- int kids = s->m_edges.count();
- qDebug("%*s type: sequential(%d):", indent, "", kids);
- for (int i = 0; i < kids; ++i) {
- s->m_edges.at(i)->dump(indent+2);
- }
- } else {
- qDebug("%*s type: Normal:", indent, "");
- }
-}
-
-#endif
-
-QSimplexConstraint *GraphPath::constraint(const GraphPath &path) const
-{
- // Calculate
- QSet<AnchorData *> cPositives;
- QSet<AnchorData *> cNegatives;
- QSet<AnchorData *> intersection;
-
- cPositives = positives + path.negatives;
- cNegatives = negatives + path.positives;
-
- intersection = cPositives & cNegatives;
-
- cPositives -= intersection;
- cNegatives -= intersection;
-
- // Fill
- QSimplexConstraint *c = new QSimplexConstraint;
- QSet<AnchorData *>::iterator i;
- for (i = cPositives.begin(); i != cPositives.end(); ++i)
- c->variables.insert(*i, 1.0);
-
- for (i = cNegatives.begin(); i != cNegatives.end(); ++i)
- c->variables.insert(*i, -1.0);
-
- return c;
-}
-
-#ifdef QT_DEBUG
-QString GraphPath::toString() const
-{
- QString string(QLatin1String("Path: "));
- foreach(AnchorData *edge, positives)
- string += QString::fromAscii(" (+++) %1").arg(edge->toString());
-
- foreach(AnchorData *edge, negatives)
- string += QString::fromAscii(" (---) %1").arg(edge->toString());
-
- return string;
-}
-#endif
-
-QGraphicsAnchorLayoutPrivate::QGraphicsAnchorLayoutPrivate()
- : calculateGraphCacheDirty(true), styleInfoDirty(true)
-{
- for (int i = 0; i < NOrientations; ++i) {
- for (int j = 0; j < 3; ++j) {
- sizeHints[i][j] = -1;
- }
- interpolationProgress[i] = -1;
-
- spacings[i] = -1;
- graphHasConflicts[i] = false;
-
- layoutFirstVertex[i] = 0;
- layoutCentralVertex[i] = 0;
- layoutLastVertex[i] = 0;
- }
-}
-
-Qt::AnchorPoint QGraphicsAnchorLayoutPrivate::oppositeEdge(Qt::AnchorPoint edge)
-{
- switch (edge) {
- case Qt::AnchorLeft:
- edge = Qt::AnchorRight;
- break;
- case Qt::AnchorRight:
- edge = Qt::AnchorLeft;
- break;
- case Qt::AnchorTop:
- edge = Qt::AnchorBottom;
- break;
- case Qt::AnchorBottom:
- edge = Qt::AnchorTop;
- break;
- default:
- break;
- }
- return edge;
-}
-
-
-/*!
- * \internal
- *
- * helper function in order to avoid overflowing anchor sizes
- * the returned size will never be larger than FLT_MAX
- *
- */
-inline static qreal checkAdd(qreal a, qreal b)
-{
- if (FLT_MAX - b < a)
- return FLT_MAX;
- return a + b;
-}
-
-/*!
- \internal
-
- Adds \a newAnchor to the graph.
-
- Returns the newAnchor itself if it could be added without further changes to the graph. If a
- new parallel anchor had to be created, then returns the new parallel anchor. If a parallel anchor
- had to be created and it results in an unfeasible setup, \a feasible is set to false, otherwise
- true.
-
- Note that in the case a new parallel anchor is created, it might also take over some constraints
- from its children anchors.
-*/
-AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *newAnchor, bool *feasible)
-{
- Orientation orientation = Orientation(newAnchor->orientation);
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- *feasible = true;
-
- // If already exists one anchor where newAnchor is supposed to be, we create a parallel
- // anchor.
- if (AnchorData *oldAnchor = g.takeEdge(newAnchor->from, newAnchor->to)) {
- ParallelAnchorData *parallel = new ParallelAnchorData(oldAnchor, newAnchor);
-
- // The parallel anchor will "replace" its children anchors in
- // every center constraint that they appear.
-
- // ### If the dependent (center) anchors had reference(s) to their constraints, we
- // could avoid traversing all the itemCenterConstraints.
- QList<QSimplexConstraint *> &constraints = itemCenterConstraints[orientation];
-
- AnchorData *children[2] = { oldAnchor, newAnchor };
- QList<QSimplexConstraint *> *childrenConstraints[2] = { &parallel->m_firstConstraints,
- &parallel->m_secondConstraints };
-
- for (int i = 0; i < 2; ++i) {
- AnchorData *child = children[i];
- QList<QSimplexConstraint *> *childConstraints = childrenConstraints[i];
-
- // We need to fix the second child constraints if the parallel group will have the
- // opposite direction of the second child anchor. For the point of view of external
- // entities, this anchor was reversed. So if at some point we say that the parallel
- // has a value of 20, this mean that the second child (when reversed) will be
- // assigned -20.
- const bool needsReverse = i == 1 && !parallel->secondForward();
-
- if (!child->isCenterAnchor)
- continue;
-
- parallel->isCenterAnchor = true;
-
- for (int j = 0; j < constraints.count(); ++j) {
- QSimplexConstraint *c = constraints[j];
- if (c->variables.contains(child)) {
- childConstraints->append(c);
- qreal v = c->variables.take(child);
- if (needsReverse)
- v *= -1;
- c->variables.insert(parallel, v);
- }
- }
- }
-
- // At this point we can identify that the parallel anchor is not feasible, e.g. one
- // anchor minimum size is bigger than the other anchor maximum size.
- *feasible = parallel->calculateSizeHints();
- newAnchor = parallel;
- }
-
- g.createEdge(newAnchor->from, newAnchor->to, newAnchor);
- return newAnchor;
-}
-
-/*!
- \internal
-
- Takes the sequence of vertices described by (\a before, \a vertices, \a after) and removes
- all anchors connected to the vertices in \a vertices, returning one simplified anchor between
- \a before and \a after.
-
- Note that this function doesn't add the created anchor to the graph. This should be done by
- the caller.
-*/
-static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph,
- AnchorVertex *before,
- const QVector<AnchorVertex*> &vertices,
- AnchorVertex *after)
-{
-#if defined(QT_DEBUG) && 0
- QString strVertices;
- for (int i = 0; i < vertices.count(); ++i) {
- strVertices += QString::fromAscii("%1 - ").arg(vertices.at(i)->toString());
- }
- QString strPath = QString::fromAscii("%1 - %2%3").arg(before->toString(), strVertices, after->toString());
- qDebug("simplifying [%s] to [%s - %s]", qPrintable(strPath), qPrintable(before->toString()), qPrintable(after->toString()));
-#endif
-
- AnchorVertex *prev = before;
- QVector<AnchorData *> edges;
-
- // Take from the graph, the edges that will be simplificated
- for (int i = 0; i < vertices.count(); ++i) {
- AnchorVertex *next = vertices.at(i);
- AnchorData *ad = graph->takeEdge(prev, next);
- Q_ASSERT(ad);
- edges.append(ad);
- prev = next;
- }
-
- // Take the last edge (not covered in the loop above)
- AnchorData *ad = graph->takeEdge(vertices.last(), after);
- Q_ASSERT(ad);
- edges.append(ad);
-
- // Create sequence
- SequentialAnchorData *sequence = new SequentialAnchorData(vertices, edges);
- sequence->from = before;
- sequence->to = after;
-
- sequence->calculateSizeHints();
-
- return sequence;
-}
-
-/*!
- \internal
-
- The purpose of this function is to simplify the graph.
- Simplification serves two purposes:
- 1. Reduce the number of edges in the graph, (thus the number of variables to the equation
- solver is reduced, and the solver performs better).
- 2. Be able to do distribution of sequences of edges more intelligently (esp. with sequential
- anchors)
-
- It is essential that it must be possible to restore simplified anchors back to their "original"
- form. This is done by restoreSimplifiedAnchor().
-
- There are two types of simplification that can be done:
- 1. Sequential simplification
- Sequential simplification means that all sequences of anchors will be merged into one single
- anchor. Only anhcors that points in the same direction will be merged.
- 2. Parallel simplification
- If a simplified sequential anchor is about to be inserted between two vertices in the graph
- and there already exist an anchor between those two vertices, a parallel anchor will be
- created that serves as a placeholder for the sequential anchor and the anchor that was
- already between the two vertices.
-
- The process of simplification can be described as:
-
- 1. Simplify all sequences of anchors into one anchor.
- If no further simplification was done, go to (3)
- - If there already exist an anchor where the sequential anchor is supposed to be inserted,
- take that anchor out of the graph
- - Then create a parallel anchor that holds the sequential anchor and the anchor just taken
- out of the graph.
- 2. Go to (1)
- 3. Done
-
- When creating the parallel anchors, the algorithm might identify unfeasible situations. In this
- case the simplification process stops and returns false. Otherwise returns true.
-*/
-bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Orientation orientation)
-{
- if (items.isEmpty())
- return true;
-
-#if defined(QT_DEBUG) && 0
- qDebug("Simplifying Graph for %s",
- orientation == Horizontal ? "Horizontal" : "Vertical");
-
- static int count = 0;
- if (orientation == Horizontal) {
- count++;
- dumpGraph(QString::fromAscii("%1-full").arg(count));
- }
-#endif
-
- // Vertex simplification
- if (!simplifyVertices(orientation)) {
- restoreVertices(orientation);
- return false;
- }
-
- // Anchor simplification
- bool dirty;
- bool feasible = true;
- do {
- dirty = simplifyGraphIteration(orientation, &feasible);
- } while (dirty && feasible);
-
- // Note that if we are not feasible, we fallback and make sure that the graph is fully restored
- if (!feasible) {
- restoreSimplifiedGraph(orientation);
- restoreVertices(orientation);
- return false;
- }
-
-#if defined(QT_DEBUG) && 0
- dumpGraph(QString::fromAscii("%1-simplified-%2").arg(count).arg(
- QString::fromAscii(orientation == Horizontal ? "Horizontal" : "Vertical")));
-#endif
-
- return true;
-}
-
-static AnchorVertex *replaceVertex_helper(AnchorData *data, AnchorVertex *oldV, AnchorVertex *newV)
-{
- AnchorVertex *other;
- if (data->from == oldV) {
- data->from = newV;
- other = data->to;
- } else {
- data->to = newV;
- other = data->from;
- }
- return other;
-}
-
-bool QGraphicsAnchorLayoutPrivate::replaceVertex(Orientation orientation, AnchorVertex *oldV,
- AnchorVertex *newV, const QList<AnchorData *> &edges)
-{
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- bool feasible = true;
-
- for (int i = 0; i < edges.count(); ++i) {
- AnchorData *ad = edges[i];
- AnchorVertex *otherV = replaceVertex_helper(ad, oldV, newV);
-
-#if defined(QT_DEBUG)
- ad->name = QString::fromAscii("%1 --to--> %2").arg(ad->from->toString()).arg(ad->to->toString());
-#endif
-
- bool newFeasible;
- AnchorData *newAnchor = addAnchorMaybeParallel(ad, &newFeasible);
- feasible &= newFeasible;
-
- if (newAnchor != ad) {
- // A parallel was created, we mark that in the list of anchors created by vertex
- // simplification. This is needed because we want to restore them in a separate step
- // from the restoration of anchor simplification.
- anchorsFromSimplifiedVertices[orientation].append(newAnchor);
- }
-
- g.takeEdge(oldV, otherV);
- }
-
- return feasible;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Orientation orientation)
-{
- Q_Q(QGraphicsAnchorLayout);
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
-
- // We'll walk through vertices
- QStack<AnchorVertex *> stack;
- stack.push(layoutFirstVertex[orientation]);
- QSet<AnchorVertex *> visited;
-
- while (!stack.isEmpty()) {
- AnchorVertex *v = stack.pop();
- visited.insert(v);
-
- // Each adjacent of 'v' is a possible vertex to be merged. So we traverse all of
- // them. Since once a merge is made, we might add new adjacents, and we don't want to
- // pass two times through one adjacent. The 'index' is used to track our position.
- QList<AnchorVertex *> adjacents = g.adjacentVertices(v);
- int index = 0;
-
- while (index < adjacents.count()) {
- AnchorVertex *next = adjacents.at(index);
- index++;
-
- AnchorData *data = g.edgeData(v, next);
- const bool bothLayoutVertices = v->m_item == q && next->m_item == q;
- const bool zeroSized = !data->minSize && !data->maxSize;
-
- if (!bothLayoutVertices && zeroSized) {
-
- // Create a new vertex pair, note that we keep a list of those vertices so we can
- // easily process them when restoring the graph.
- AnchorVertexPair *newV = new AnchorVertexPair(v, next, data);
- simplifiedVertices[orientation].append(newV);
-
- // Collect the anchors of both vertices, the new vertex pair will take their place
- // in those anchors
- const QList<AnchorVertex *> &vAdjacents = g.adjacentVertices(v);
- const QList<AnchorVertex *> &nextAdjacents = g.adjacentVertices(next);
-
- for (int i = 0; i < vAdjacents.count(); ++i) {
- AnchorVertex *adjacent = vAdjacents.at(i);
- if (adjacent != next) {
- AnchorData *ad = g.edgeData(v, adjacent);
- newV->m_firstAnchors.append(ad);
- }
- }
-
- for (int i = 0; i < nextAdjacents.count(); ++i) {
- AnchorVertex *adjacent = nextAdjacents.at(i);
- if (adjacent != v) {
- AnchorData *ad = g.edgeData(next, adjacent);
- newV->m_secondAnchors.append(ad);
-
- // We'll also add new vertices to the adjacent list of the new 'v', to be
- // created as a vertex pair and replace the current one.
- if (!adjacents.contains(adjacent))
- adjacents.append(adjacent);
- }
- }
-
- // ### merge this loop into the ones that calculated m_firstAnchors/m_secondAnchors?
- // Make newV take the place of v and next
- bool feasible = replaceVertex(orientation, v, newV, newV->m_firstAnchors);
- feasible &= replaceVertex(orientation, next, newV, newV->m_secondAnchors);
-
- // Update the layout vertex information if one of the vertices is a layout vertex.
- AnchorVertex *layoutVertex = 0;
- if (v->m_item == q)
- layoutVertex = v;
- else if (next->m_item == q)
- layoutVertex = next;
-
- if (layoutVertex) {
- // Layout vertices always have m_item == q...
- newV->m_item = q;
- changeLayoutVertex(orientation, layoutVertex, newV);
- }
-
- g.takeEdge(v, next);
-
- // If a non-feasibility is found, we leave early and cancel the simplification
- if (!feasible)
- return false;
-
- v = newV;
- visited.insert(newV);
-
- } else if (!visited.contains(next) && !stack.contains(next)) {
- // If the adjacent is not fit for merge and it wasn't visited by the outermost
- // loop, we add it to the stack.
- stack.push(next);
- }
- }
- }
-
- return true;
-}
-
-/*!
- \internal
-
- One iteration of the simplification algorithm. Returns true if another iteration is needed.
-
- The algorithm walks the graph in depth-first order, and only collects vertices that has two
- edges connected to it. If the vertex does not have two edges or if it is a layout edge, it
- will take all the previously collected vertices and try to create a simplified sequential
- anchor representing all the previously collected vertices. Once the simplified anchor is
- inserted, the collected list is cleared in order to find the next sequence to simplify.
-
- Note that there are some catches to this that are not covered by the above explanation, see
- the function comments for more details.
-*/
-bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutPrivate::Orientation orientation,
- bool *feasible)
-{
- Q_Q(QGraphicsAnchorLayout);
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
-
- QSet<AnchorVertex *> visited;
- QStack<QPair<AnchorVertex *, AnchorVertex *> > stack;
- stack.push(qMakePair(static_cast<AnchorVertex *>(0), layoutFirstVertex[orientation]));
- QVector<AnchorVertex*> candidates;
-
- // Walk depth-first, in the stack we store start of the candidate sequence (beforeSequence)
- // and the vertex to be visited.
- while (!stack.isEmpty()) {
- QPair<AnchorVertex *, AnchorVertex *> pair = stack.pop();
- AnchorVertex *beforeSequence = pair.first;
- AnchorVertex *v = pair.second;
-
- // The basic idea is to determine whether we found an end of sequence,
- // if that's the case, we stop adding vertices to the candidate list
- // and do a simplification step.
- //
- // A vertex can trigger an end of sequence if
- // (a) it is a layout vertex, we don't simplify away the layout vertices;
- // (b) it does not have exactly 2 adjacents;
- // (c) its next adjacent is already visited (a cycle in the graph).
- // (d) the next anchor is a center anchor.
-
- const QList<AnchorVertex *> &adjacents = g.adjacentVertices(v);
- const bool isLayoutVertex = v->m_item == q;
- AnchorVertex *afterSequence = v;
- bool endOfSequence = false;
-
- //
- // Identify the end cases.
- //
-
- // Identifies cases (a) and (b)
- endOfSequence = isLayoutVertex || adjacents.count() != 2;
-
- if (!endOfSequence) {
- // This is a tricky part. We peek at the next vertex to find out whether
- //
- // - we already visited the next vertex (c);
- // - the next anchor is a center (d).
- //
- // Those are needed to identify the remaining end of sequence cases. Note that unlike
- // (a) and (b), we preempt the end of sequence by looking into the next vertex.
-
- // Peek at the next vertex
- AnchorVertex *after;
- if (candidates.isEmpty())
- after = (beforeSequence == adjacents.last() ? adjacents.first() : adjacents.last());
- else
- after = (candidates.last() == adjacents.last() ? adjacents.first() : adjacents.last());
-
- // ### At this point we assumed that candidates will not contain 'after', this may not hold
- // when simplifying FLOATing anchors.
- Q_ASSERT(!candidates.contains(after));
-
- const AnchorData *data = g.edgeData(v, after);
- Q_ASSERT(data);
- const bool cycleFound = visited.contains(after);
-
- // Now cases (c) and (d)...
- endOfSequence = cycleFound || data->isCenterAnchor;
-
- if (!endOfSequence) {
- // If it's not an end of sequence, then the vertex didn't trigger neither of the
- // previously three cases, so it can be added to the candidates list.
- candidates.append(v);
- } else if (cycleFound && (beforeSequence != after)) {
- afterSequence = after;
- candidates.append(v);
- }
- }
-
- //
- // Add next non-visited vertices to the stack.
- //
- for (int i = 0; i < adjacents.count(); ++i) {
- AnchorVertex *next = adjacents.at(i);
- if (visited.contains(next))
- continue;
-
- // If current vertex is an end of sequence, and it'll reset the candidates list. So
- // the next vertices will build candidates lists with the current vertex as 'before'
- // vertex. If it's not an end of sequence, we keep the original 'before' vertex,
- // since we are keeping the candidates list.
- if (endOfSequence)
- stack.push(qMakePair(v, next));
- else
- stack.push(qMakePair(beforeSequence, next));
- }
-
- visited.insert(v);
-
- if (!endOfSequence || candidates.isEmpty())
- continue;
-
- //
- // Create a sequence for (beforeSequence, candidates, afterSequence).
- //
-
- // One restriction we have is to not simplify half of an anchor and let the other half
- // unsimplified. So we remove center edges before and after the sequence.
- const AnchorData *firstAnchor = g.edgeData(beforeSequence, candidates.first());
- if (firstAnchor->isCenterAnchor) {
- beforeSequence = candidates.first();
- candidates.remove(0);
-
- // If there's not candidates to be simplified, leave.
- if (candidates.isEmpty())
- continue;
- }
-
- const AnchorData *lastAnchor = g.edgeData(candidates.last(), afterSequence);
- if (lastAnchor->isCenterAnchor) {
- afterSequence = candidates.last();
- candidates.remove(candidates.count() - 1);
-
- if (candidates.isEmpty())
- continue;
- }
-
- //
- // Add the sequence to the graph.
- //
-
- AnchorData *sequence = createSequence(&g, beforeSequence, candidates, afterSequence);
-
- // If 'beforeSequence' and 'afterSequence' already had an anchor between them, we'll
- // create a parallel anchor between the new sequence and the old anchor.
- bool newFeasible;
- AnchorData *newAnchor = addAnchorMaybeParallel(sequence, &newFeasible);
-
- if (!newFeasible) {
- *feasible = false;
- return false;
- }
-
- // When a new parallel anchor is create in the graph, we finish the iteration and return
- // true to indicate a new iteration is needed. This happens because a parallel anchor
- // changes the number of adjacents one vertex has, possibly opening up oportunities for
- // building candidate lists (when adjacents == 2).
- if (newAnchor != sequence)
- return true;
-
- // If there was no parallel simplification, we'll keep walking the graph. So we clear the
- // candidates list to start again.
- candidates.clear();
- }
-
- return false;
-}
-
-void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
-{
-#if 0
- static const char *anchortypes[] = {"Normal",
- "Sequential",
- "Parallel"};
- qDebug("Restoring %s edge.", anchortypes[int(edge->type)]);
-#endif
-
- Graph<AnchorVertex, AnchorData> &g = graph[edge->orientation];
-
- if (edge->type == AnchorData::Normal) {
- g.createEdge(edge->from, edge->to, edge);
-
- } else if (edge->type == AnchorData::Sequential) {
- SequentialAnchorData *sequence = static_cast<SequentialAnchorData *>(edge);
-
- for (int i = 0; i < sequence->m_edges.count(); ++i) {
- AnchorData *data = sequence->m_edges.at(i);
- restoreSimplifiedAnchor(data);
- }
-
- delete sequence;
-
- } else if (edge->type == AnchorData::Parallel) {
-
- // Skip parallel anchors that were created by vertex simplification, they will be processed
- // later, when restoring vertex simplification.
- // ### we could improve this check bit having a bit inside 'edge'
- if (anchorsFromSimplifiedVertices[edge->orientation].contains(edge))
- return;
-
- ParallelAnchorData* parallel = static_cast<ParallelAnchorData*>(edge);
- restoreSimplifiedConstraints(parallel);
-
- // ### Because of the way parallel anchors are created in the anchor simplification
- // algorithm, we know that one of these will be a sequence, so it'll be safe if the other
- // anchor create an edge between the same vertices as the parallel.
- Q_ASSERT(parallel->firstEdge->type == AnchorData::Sequential
- || parallel->secondEdge->type == AnchorData::Sequential);
- restoreSimplifiedAnchor(parallel->firstEdge);
- restoreSimplifiedAnchor(parallel->secondEdge);
-
- delete parallel;
- }
-}
-
-void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorData *parallel)
-{
- if (!parallel->isCenterAnchor)
- return;
-
- for (int i = 0; i < parallel->m_firstConstraints.count(); ++i) {
- QSimplexConstraint *c = parallel->m_firstConstraints.at(i);
- qreal v = c->variables[parallel];
- c->variables.remove(parallel);
- c->variables.insert(parallel->firstEdge, v);
- }
-
- // When restoring, we might have to revert constraints back. See comments on
- // addAnchorMaybeParallel().
- const bool needsReverse = !parallel->secondForward();
-
- for (int i = 0; i < parallel->m_secondConstraints.count(); ++i) {
- QSimplexConstraint *c = parallel->m_secondConstraints.at(i);
- qreal v = c->variables[parallel];
- if (needsReverse)
- v *= -1;
- c->variables.remove(parallel);
- c->variables.insert(parallel->secondEdge, v);
- }
-}
-
-void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Orientation orientation)
-{
-#if 0
- qDebug("Restoring Simplified Graph for %s",
- orientation == Horizontal ? "Horizontal" : "Vertical");
-#endif
-
- // Restore anchor simplification
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- QList<QPair<AnchorVertex*, AnchorVertex*> > connections = g.connections();
- for (int i = 0; i < connections.count(); ++i) {
- AnchorVertex *v1 = connections.at(i).first;
- AnchorVertex *v2 = connections.at(i).second;
- AnchorData *edge = g.edgeData(v1, v2);
-
- // We restore only sequential anchors and parallels that were not created by
- // vertex simplification.
- if (edge->type == AnchorData::Sequential
- || (edge->type == AnchorData::Parallel &&
- !anchorsFromSimplifiedVertices[orientation].contains(edge))) {
-
- g.takeEdge(v1, v2);
- restoreSimplifiedAnchor(edge);
- }
- }
-
- restoreVertices(orientation);
-}
-
-void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- QList<AnchorVertexPair *> &toRestore = simplifiedVertices[orientation];
-
- // Since we keep a list of parallel anchors and vertices that were created during vertex
- // simplification, we can now iterate on those lists instead of traversing the graph
- // recursively.
-
- // First, restore the constraints changed when we created parallel anchors. Note that this
- // works at this point because the constraints doesn't depend on vertex information and at
- // this point it's always safe to identify whether the second child is forward or backwards.
- // In the next step, we'll change the anchors vertices so that would not be possible anymore.
- QList<AnchorData *> &parallelAnchors = anchorsFromSimplifiedVertices[orientation];
-
- for (int i = parallelAnchors.count() - 1; i >= 0; --i) {
- ParallelAnchorData *parallel = static_cast<ParallelAnchorData *>(parallelAnchors.at(i));
- restoreSimplifiedConstraints(parallel);
- }
-
- // Then, we will restore the vertices in the inverse order of creation, this way we ensure that
- // the vertex being restored was not wrapped by another simplification.
- for (int i = toRestore.count() - 1; i >= 0; --i) {
- AnchorVertexPair *pair = toRestore.at(i);
- QList<AnchorVertex *> adjacents = g.adjacentVertices(pair);
-
- // Restore the removed edge, this will also restore both vertices 'first' and 'second' to
- // the graph structure.
- AnchorVertex *first = pair->m_first;
- AnchorVertex *second = pair->m_second;
- g.createEdge(first, second, pair->m_removedAnchor);
-
- // Restore the anchors for the first child vertex
- for (int j = 0; j < pair->m_firstAnchors.count(); ++j) {
- AnchorData *ad = pair->m_firstAnchors.at(j);
- Q_ASSERT(ad->from == pair || ad->to == pair);
-
- replaceVertex_helper(ad, pair, first);
- g.createEdge(ad->from, ad->to, ad);
- }
-
- // Restore the anchors for the second child vertex
- for (int j = 0; j < pair->m_secondAnchors.count(); ++j) {
- AnchorData *ad = pair->m_secondAnchors.at(j);
- Q_ASSERT(ad->from == pair || ad->to == pair);
-
- replaceVertex_helper(ad, pair, second);
- g.createEdge(ad->from, ad->to, ad);
- }
-
- for (int j = 0; j < adjacents.count(); ++j) {
- g.takeEdge(pair, adjacents.at(j));
- }
-
- // The pair simplified a layout vertex, so place back the correct vertex in the variable
- // that track layout vertices
- if (pair->m_item == q) {
- AnchorVertex *layoutVertex = first->m_item == q ? first : second;
- Q_ASSERT(layoutVertex->m_item == q);
- changeLayoutVertex(orientation, pair, layoutVertex);
- }
-
- delete pair;
- }
- qDeleteAll(parallelAnchors);
- parallelAnchors.clear();
- toRestore.clear();
-}
-
-QGraphicsAnchorLayoutPrivate::Orientation
-QGraphicsAnchorLayoutPrivate::edgeOrientation(Qt::AnchorPoint edge)
-{
- return edge > Qt::AnchorRight ? Vertical : Horizontal;
-}
-
-/*!
- \internal
-
- Create internal anchors to connect the layout edges (Left to Right and
- Top to Bottom).
-
- These anchors doesn't have size restrictions, that will be enforced by
- other anchors and items in the layout.
-*/
-void QGraphicsAnchorLayoutPrivate::createLayoutEdges()
-{
- Q_Q(QGraphicsAnchorLayout);
- QGraphicsLayoutItem *layout = q;
-
- // Horizontal
- AnchorData *data = new AnchorData;
- addAnchor_helper(layout, Qt::AnchorLeft, layout,
- Qt::AnchorRight, data);
- data->maxSize = QWIDGETSIZE_MAX;
-
- // Save a reference to layout vertices
- layoutFirstVertex[Horizontal] = internalVertex(layout, Qt::AnchorLeft);
- layoutCentralVertex[Horizontal] = 0;
- layoutLastVertex[Horizontal] = internalVertex(layout, Qt::AnchorRight);
-
- // Vertical
- data = new AnchorData;
- addAnchor_helper(layout, Qt::AnchorTop, layout,
- Qt::AnchorBottom, data);
- data->maxSize = QWIDGETSIZE_MAX;
-
- // Save a reference to layout vertices
- layoutFirstVertex[Vertical] = internalVertex(layout, Qt::AnchorTop);
- layoutCentralVertex[Vertical] = 0;
- layoutLastVertex[Vertical] = internalVertex(layout, Qt::AnchorBottom);
-}
-
-void QGraphicsAnchorLayoutPrivate::deleteLayoutEdges()
-{
- Q_Q(QGraphicsAnchorLayout);
-
- Q_ASSERT(!internalVertex(q, Qt::AnchorHorizontalCenter));
- Q_ASSERT(!internalVertex(q, Qt::AnchorVerticalCenter));
-
- removeAnchor_helper(internalVertex(q, Qt::AnchorLeft),
- internalVertex(q, Qt::AnchorRight));
- removeAnchor_helper(internalVertex(q, Qt::AnchorTop),
- internalVertex(q, Qt::AnchorBottom));
-}
-
-void QGraphicsAnchorLayoutPrivate::createItemEdges(QGraphicsLayoutItem *item)
-{
- items.append(item);
-
- // Create horizontal and vertical internal anchors for the item and
- // refresh its size hint / policy values.
- AnchorData *data = new AnchorData;
- addAnchor_helper(item, Qt::AnchorLeft, item, Qt::AnchorRight, data);
- data->refreshSizeHints();
-
- data = new AnchorData;
- addAnchor_helper(item, Qt::AnchorTop, item, Qt::AnchorBottom, data);
- data->refreshSizeHints();
-}
-
-/*!
- \internal
-
- By default, each item in the layout is represented internally as
- a single anchor in each direction. For instance, from Left to Right.
-
- However, to support anchorage of items to the center of items, we
- must split this internal anchor into two half-anchors. From Left
- to Center and then from Center to Right, with the restriction that
- these anchors must have the same time at all times.
-*/
-void QGraphicsAnchorLayoutPrivate::createCenterAnchors(
- QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- Orientation orientation;
- switch (centerEdge) {
- case Qt::AnchorHorizontalCenter:
- orientation = Horizontal;
- break;
- case Qt::AnchorVerticalCenter:
- orientation = Vertical;
- break;
- default:
- // Don't create center edges unless needed
- return;
- }
-
- // Check if vertex already exists
- if (internalVertex(item, centerEdge))
- return;
-
- // Orientation code
- Qt::AnchorPoint firstEdge;
- Qt::AnchorPoint lastEdge;
-
- if (orientation == Horizontal) {
- firstEdge = Qt::AnchorLeft;
- lastEdge = Qt::AnchorRight;
- } else {
- firstEdge = Qt::AnchorTop;
- lastEdge = Qt::AnchorBottom;
- }
-
- AnchorVertex *first = internalVertex(item, firstEdge);
- AnchorVertex *last = internalVertex(item, lastEdge);
- Q_ASSERT(first && last);
-
- // Create new anchors
- QSimplexConstraint *c = new QSimplexConstraint;
-
- AnchorData *data = new AnchorData;
- c->variables.insert(data, 1.0);
- addAnchor_helper(item, firstEdge, item, centerEdge, data);
- data->isCenterAnchor = true;
- data->dependency = AnchorData::Master;
- data->refreshSizeHints();
-
- data = new AnchorData;
- c->variables.insert(data, -1.0);
- addAnchor_helper(item, centerEdge, item, lastEdge, data);
- data->isCenterAnchor = true;
- data->dependency = AnchorData::Slave;
- data->refreshSizeHints();
-
- itemCenterConstraints[orientation].append(c);
-
- // Remove old one
- removeAnchor_helper(first, last);
-
- if (item == q) {
- layoutCentralVertex[orientation] = internalVertex(q, centerEdge);
- }
-}
-
-void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
- QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge,
- bool substitute)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- Orientation orientation;
- switch (centerEdge) {
- case Qt::AnchorHorizontalCenter:
- orientation = Horizontal;
- break;
- case Qt::AnchorVerticalCenter:
- orientation = Vertical;
- break;
- default:
- // Don't remove edges that not the center ones
- return;
- }
-
- // Orientation code
- Qt::AnchorPoint firstEdge;
- Qt::AnchorPoint lastEdge;
-
- if (orientation == Horizontal) {
- firstEdge = Qt::AnchorLeft;
- lastEdge = Qt::AnchorRight;
- } else {
- firstEdge = Qt::AnchorTop;
- lastEdge = Qt::AnchorBottom;
- }
-
- AnchorVertex *center = internalVertex(item, centerEdge);
- if (!center)
- return;
- AnchorVertex *first = internalVertex(item, firstEdge);
-
- Q_ASSERT(first);
- Q_ASSERT(center);
-
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
-
-
- AnchorData *oldData = g.edgeData(first, center);
- // Remove center constraint
- for (int i = itemCenterConstraints[orientation].count() - 1; i >= 0; --i) {
- if (itemCenterConstraints[orientation].at(i)->variables.contains(oldData)) {
- delete itemCenterConstraints[orientation].takeAt(i);
- break;
- }
- }
-
- if (substitute) {
- // Create the new anchor that should substitute the left-center-right anchors.
- AnchorData *data = new AnchorData;
- addAnchor_helper(item, firstEdge, item, lastEdge, data);
- data->refreshSizeHints();
-
- // Remove old anchors
- removeAnchor_helper(first, center);
- removeAnchor_helper(center, internalVertex(item, lastEdge));
-
- } else {
- // this is only called from removeAnchors()
- // first, remove all non-internal anchors
- QList<AnchorVertex*> adjacents = g.adjacentVertices(center);
- for (int i = 0; i < adjacents.count(); ++i) {
- AnchorVertex *v = adjacents.at(i);
- if (v->m_item != item) {
- removeAnchor_helper(center, internalVertex(v->m_item, v->m_edge));
- }
- }
- // when all non-internal anchors is removed it will automatically merge the
- // center anchor into a left-right (or top-bottom) anchor. We must also delete that.
- // by this time, the center vertex is deleted and merged into a non-centered internal anchor
- removeAnchor_helper(first, internalVertex(item, lastEdge));
- }
-
- if (item == q) {
- layoutCentralVertex[orientation] = 0;
- }
-}
-
-
-void QGraphicsAnchorLayoutPrivate::removeCenterConstraints(QGraphicsLayoutItem *item,
- Orientation orientation)
-{
- // Remove the item center constraints associated to this item
- // ### This is a temporary solution. We should probably use a better
- // data structure to hold items and/or their associated constraints
- // so that we can remove those easily
-
- AnchorVertex *first = internalVertex(item, orientation == Horizontal ?
- Qt::AnchorLeft :
- Qt::AnchorTop);
- AnchorVertex *center = internalVertex(item, orientation == Horizontal ?
- Qt::AnchorHorizontalCenter :
- Qt::AnchorVerticalCenter);
-
- // Skip if no center constraints exist
- if (!center)
- return;
-
- Q_ASSERT(first);
- AnchorData *internalAnchor = graph[orientation].edgeData(first, center);
-
- // Look for our anchor in all item center constraints, then remove it
- for (int i = 0; i < itemCenterConstraints[orientation].size(); ++i) {
- if (itemCenterConstraints[orientation].at(i)->variables.contains(internalAnchor)) {
- delete itemCenterConstraints[orientation].takeAt(i);
- break;
- }
- }
-}
-
-/*!
- * \internal
- * Implements the high level "addAnchor" feature. Called by the public API
- * addAnchor method.
- *
- * The optional \a spacing argument defines the size of the anchor. If not provided,
- * the anchor size is either 0 or not-set, depending on type of anchor created (see
- * matrix below).
- *
- * All anchors that remain with size not-set will assume the standard spacing,
- * set either by the layout style or through the "setSpacing" layout API.
- */
-QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::addAnchor(QGraphicsLayoutItem *firstItem,
- Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem,
- Qt::AnchorPoint secondEdge,
- qreal *spacing)
-{
- Q_Q(QGraphicsAnchorLayout);
- if ((firstItem == 0) || (secondItem == 0)) {
- qWarning("QGraphicsAnchorLayout::addAnchor(): "
- "Cannot anchor NULL items");
- return 0;
- }
-
- if (firstItem == secondItem) {
- qWarning("QGraphicsAnchorLayout::addAnchor(): "
- "Cannot anchor the item to itself");
- return 0;
- }
-
- if (edgeOrientation(secondEdge) != edgeOrientation(firstEdge)) {
- qWarning("QGraphicsAnchorLayout::addAnchor(): "
- "Cannot anchor edges of different orientations");
- return 0;
- }
-
- const QGraphicsLayoutItem *parentWidget = q->parentLayoutItem();
- if (firstItem == parentWidget || secondItem == parentWidget) {
- qWarning("QGraphicsAnchorLayout::addAnchor(): "
- "You cannot add the parent of the layout to the layout.");
- return 0;
- }
-
- // In QGraphicsAnchorLayout, items are represented in its internal
- // graph as four anchors that connect:
- // - Left -> HCenter
- // - HCenter-> Right
- // - Top -> VCenter
- // - VCenter -> Bottom
-
- // Ensure that the internal anchors have been created for both items.
- if (firstItem != q && !items.contains(firstItem)) {
- createItemEdges(firstItem);
- addChildLayoutItem(firstItem);
- }
- if (secondItem != q && !items.contains(secondItem)) {
- createItemEdges(secondItem);
- addChildLayoutItem(secondItem);
- }
-
- // Create center edges if needed
- createCenterAnchors(firstItem, firstEdge);
- createCenterAnchors(secondItem, secondEdge);
-
- // Use heuristics to find out what the user meant with this anchor.
- correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge);
-
- AnchorData *data = new AnchorData;
- QGraphicsAnchor *graphicsAnchor = acquireGraphicsAnchor(data);
-
- addAnchor_helper(firstItem, firstEdge, secondItem, secondEdge, data);
-
- if (spacing) {
- graphicsAnchor->setSpacing(*spacing);
- } else {
- // If firstItem or secondItem is the layout itself, the spacing will default to 0.
- // Otherwise, the following matrix is used (questionmark means that the spacing
- // is queried from the style):
- // from
- // to Left HCenter Right
- // Left 0 0 ?
- // HCenter 0 0 0
- // Right ? 0 0
- if (firstItem == q
- || secondItem == q
- || pickEdge(firstEdge, Horizontal) == Qt::AnchorHorizontalCenter
- || oppositeEdge(firstEdge) != secondEdge) {
- graphicsAnchor->setSpacing(0);
- } else {
- graphicsAnchor->unsetSpacing();
- }
- }
-
- return graphicsAnchor;
-}
-
-/*
- \internal
-
- This method adds an AnchorData to the internal graph. It is responsible for doing
- the boilerplate part of such task.
-
- If another AnchorData exists between the mentioned vertices, it is deleted and
- the new one is inserted.
-*/
-void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstItem,
- Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem,
- Qt::AnchorPoint secondEdge,
- AnchorData *data)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- const Orientation orientation = edgeOrientation(firstEdge);
-
- // Create or increase the reference count for the related vertices.
- AnchorVertex *v1 = addInternalVertex(firstItem, firstEdge);
- AnchorVertex *v2 = addInternalVertex(secondItem, secondEdge);
-
- // Remove previous anchor
- if (graph[orientation].edgeData(v1, v2)) {
- removeAnchor_helper(v1, v2);
- }
-
- // If its an internal anchor, set the associated item
- if (firstItem == secondItem)
- data->item = firstItem;
-
- data->orientation = orientation;
-
- // Create a bi-directional edge in the sense it can be transversed both
- // from v1 or v2. "data" however is shared between the two references
- // so we still know that the anchor direction is from 1 to 2.
- data->from = v1;
- data->to = v2;
-#ifdef QT_DEBUG
- data->name = QString::fromAscii("%1 --to--> %2").arg(v1->toString()).arg(v2->toString());
-#endif
- // ### bit to track internal anchors, since inside AnchorData methods
- // we don't have access to the 'q' pointer.
- data->isLayoutAnchor = (data->item == q);
-
- graph[orientation].createEdge(v1, v2, data);
-}
-
-QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::getAnchor(QGraphicsLayoutItem *firstItem,
- Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem,
- Qt::AnchorPoint secondEdge)
-{
- // Do not expose internal anchors
- if (firstItem == secondItem)
- return 0;
-
- const Orientation orientation = edgeOrientation(firstEdge);
- AnchorVertex *v1 = internalVertex(firstItem, firstEdge);
- AnchorVertex *v2 = internalVertex(secondItem, secondEdge);
-
- QGraphicsAnchor *graphicsAnchor = 0;
-
- AnchorData *data = graph[orientation].edgeData(v1, v2);
- if (data) {
- // We could use "acquireGraphicsAnchor" here, but to avoid a regression where
- // an internal anchor was wrongly exposed, I want to ensure no new
- // QGraphicsAnchor instances are created by this call.
- // This assumption must hold because anchors are either user-created (and already
- // have their public object created), or they are internal (and must not reach
- // this point).
- Q_ASSERT(data->graphicsAnchor);
- graphicsAnchor = data->graphicsAnchor;
- }
- return graphicsAnchor;
-}
-
-/*!
- * \internal
- *
- * Implements the high level "removeAnchor" feature. Called by
- * the QAnchorData destructor.
- */
-void QGraphicsAnchorLayoutPrivate::removeAnchor(AnchorVertex *firstVertex,
- AnchorVertex *secondVertex)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- // Save references to items while it's safe to assume the vertices exist
- QGraphicsLayoutItem *firstItem = firstVertex->m_item;
- QGraphicsLayoutItem *secondItem = secondVertex->m_item;
-
- // Delete the anchor (may trigger deletion of center vertices)
- removeAnchor_helper(firstVertex, secondVertex);
-
- // Ensure no dangling pointer is left behind
- firstVertex = secondVertex = 0;
-
- // Checking if the item stays in the layout or not
- bool keepFirstItem = false;
- bool keepSecondItem = false;
-
- QPair<AnchorVertex *, int> v;
- int refcount = -1;
-
- if (firstItem != q) {
- for (int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
- v = m_vertexList.value(qMakePair(firstItem, static_cast<Qt::AnchorPoint>(i)));
- if (v.first) {
- if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
- refcount = 2;
- else
- refcount = 1;
-
- if (v.second > refcount) {
- keepFirstItem = true;
- break;
- }
- }
- }
- } else
- keepFirstItem = true;
-
- if (secondItem != q) {
- for (int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
- v = m_vertexList.value(qMakePair(secondItem, static_cast<Qt::AnchorPoint>(i)));
- if (v.first) {
- if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
- refcount = 2;
- else
- refcount = 1;
-
- if (v.second > refcount) {
- keepSecondItem = true;
- break;
- }
- }
- }
- } else
- keepSecondItem = true;
-
- if (!keepFirstItem)
- q->removeAt(items.indexOf(firstItem));
-
- if (!keepSecondItem)
- q->removeAt(items.indexOf(secondItem));
-
- // Removing anchors invalidates the layout
- q->invalidate();
-}
-
-/*
- \internal
-
- Implements the low level "removeAnchor" feature. Called by
- private methods.
-*/
-void QGraphicsAnchorLayoutPrivate::removeAnchor_helper(AnchorVertex *v1, AnchorVertex *v2)
-{
- Q_ASSERT(v1 && v2);
-
- // Remove edge from graph
- const Orientation o = edgeOrientation(v1->m_edge);
- graph[o].removeEdge(v1, v2);
-
- // Decrease vertices reference count (may trigger a deletion)
- removeInternalVertex(v1->m_item, v1->m_edge);
- removeInternalVertex(v2->m_item, v2->m_edge);
-}
-
-AnchorVertex *QGraphicsAnchorLayoutPrivate::addInternalVertex(QGraphicsLayoutItem *item,
- Qt::AnchorPoint edge)
-{
- QPair<QGraphicsLayoutItem *, Qt::AnchorPoint> pair(item, edge);
- QPair<AnchorVertex *, int> v = m_vertexList.value(pair);
-
- if (!v.first) {
- Q_ASSERT(v.second == 0);
- v.first = new AnchorVertex(item, edge);
- }
- v.second++;
- m_vertexList.insert(pair, v);
- return v.first;
-}
-
-/**
- * \internal
- *
- * returns the AnchorVertex that was dereferenced, also when it was removed.
- * returns 0 if it did not exist.
- */
-void QGraphicsAnchorLayoutPrivate::removeInternalVertex(QGraphicsLayoutItem *item,
- Qt::AnchorPoint edge)
-{
- QPair<QGraphicsLayoutItem *, Qt::AnchorPoint> pair(item, edge);
- QPair<AnchorVertex *, int> v = m_vertexList.value(pair);
-
- if (!v.first) {
- qWarning("This item with this edge is not in the graph");
- return;
- }
-
- v.second--;
- if (v.second == 0) {
- // Remove reference and delete vertex
- m_vertexList.remove(pair);
- delete v.first;
- } else {
- // Update reference count
- m_vertexList.insert(pair, v);
-
- if ((v.second == 2) &&
- ((edge == Qt::AnchorHorizontalCenter) ||
- (edge == Qt::AnchorVerticalCenter))) {
- removeCenterAnchors(item, edge, true);
- }
- }
-}
-
-void QGraphicsAnchorLayoutPrivate::removeVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge)
-{
- if (AnchorVertex *v = internalVertex(item, edge)) {
- Graph<AnchorVertex, AnchorData> &g = graph[edgeOrientation(edge)];
- const QList<AnchorVertex *> allVertices = graph[edgeOrientation(edge)].adjacentVertices(v);
- AnchorVertex *v2;
- foreach (v2, allVertices) {
- g.removeEdge(v, v2);
- removeInternalVertex(item, edge);
- removeInternalVertex(v2->m_item, v2->m_edge);
- }
- }
-}
-
-void QGraphicsAnchorLayoutPrivate::removeAnchors(QGraphicsLayoutItem *item)
-{
- // remove the center anchor first!!
- removeCenterAnchors(item, Qt::AnchorHorizontalCenter, false);
- removeVertex(item, Qt::AnchorLeft);
- removeVertex(item, Qt::AnchorRight);
-
- removeCenterAnchors(item, Qt::AnchorVerticalCenter, false);
- removeVertex(item, Qt::AnchorTop);
- removeVertex(item, Qt::AnchorBottom);
-}
-
-/*!
- \internal
-
- Use heuristics to determine the correct orientation of a given anchor.
-
- After API discussions, we decided we would like expressions like
- anchor(A, Left, B, Right) to mean the same as anchor(B, Right, A, Left).
- The problem with this is that anchors could become ambiguous, for
- instance, what does the anchor A, B of size X mean?
-
- "pos(B) = pos(A) + X" or "pos(A) = pos(B) + X" ?
-
- To keep the API user friendly and at the same time, keep our algorithm
- deterministic, we use an heuristic to determine a direction for each
- added anchor and then keep it. The heuristic is based on the fact
- that people usually avoid overlapping items, therefore:
-
- "A, RIGHT to B, LEFT" means that B is to the LEFT of A.
- "B, LEFT to A, RIGHT" is corrected to the above anchor.
-
- Special correction is also applied when one of the items is the
- layout. We handle Layout Left as if it was another items's Right
- and Layout Right as another item's Left.
-*/
-void QGraphicsAnchorLayoutPrivate::correctEdgeDirection(QGraphicsLayoutItem *&firstItem,
- Qt::AnchorPoint &firstEdge,
- QGraphicsLayoutItem *&secondItem,
- Qt::AnchorPoint &secondEdge)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- if ((firstItem != q) && (secondItem != q)) {
- // If connection is between widgets (not the layout itself)
- // Ensure that "right-edges" sit to the left of "left-edges".
- if (firstEdge < secondEdge) {
- qSwap(firstItem, secondItem);
- qSwap(firstEdge, secondEdge);
- }
- } else if (firstItem == q) {
- // If connection involves the right or bottom of a layout, ensure
- // the layout is the second item.
- if ((firstEdge == Qt::AnchorRight) || (firstEdge == Qt::AnchorBottom)) {
- qSwap(firstItem, secondItem);
- qSwap(firstEdge, secondEdge);
- }
- } else if ((secondEdge != Qt::AnchorRight) && (secondEdge != Qt::AnchorBottom)) {
- // If connection involves the left, center or top of layout, ensure
- // the layout is the first item.
- qSwap(firstItem, secondItem);
- qSwap(firstEdge, secondEdge);
- }
-}
-
-QLayoutStyleInfo &QGraphicsAnchorLayoutPrivate::styleInfo() const
-{
- if (styleInfoDirty) {
- Q_Q(const QGraphicsAnchorLayout);
- //### Fix this if QGV ever gets support for Metal style or different Aqua sizes.
- QWidget *wid = 0;
-
- QGraphicsLayoutItem *parent = q->parentLayoutItem();
- while (parent && parent->isLayout()) {
- parent = parent->parentLayoutItem();
- }
- QGraphicsWidget *w = 0;
- if (parent) {
- QGraphicsItem *parentItem = parent->graphicsItem();
- if (parentItem && parentItem->isWidget())
- w = static_cast<QGraphicsWidget*>(parentItem);
- }
-
- QStyle *style = w ? w->style() : QApplication::style();
- cachedStyleInfo = QLayoutStyleInfo(style, wid);
- cachedStyleInfo.setDefaultSpacing(Qt::Horizontal, spacings[0]);
- cachedStyleInfo.setDefaultSpacing(Qt::Vertical, spacings[1]);
-
- styleInfoDirty = false;
- }
- return cachedStyleInfo;
-}
-
-/*!
- \internal
-
- Called on activation. Uses Linear Programming to define minimum, preferred
- and maximum sizes for the layout. Also calculates the sizes that each item
- should assume when the layout is in one of such situations.
-*/
-void QGraphicsAnchorLayoutPrivate::calculateGraphs()
-{
- if (!calculateGraphCacheDirty)
- return;
- calculateGraphs(Horizontal);
- calculateGraphs(Vertical);
- calculateGraphCacheDirty = false;
-}
-
-// ### Maybe getGraphParts could return the variables when traversing, at least
-// for trunk...
-QList<AnchorData *> getVariables(QList<QSimplexConstraint *> constraints)
-{
- QSet<AnchorData *> variableSet;
- for (int i = 0; i < constraints.count(); ++i) {
- const QSimplexConstraint *c = constraints.at(i);
- foreach (QSimplexVariable *var, c->variables.keys()) {
- variableSet += static_cast<AnchorData *>(var);
- }
- }
- return variableSet.toList();
-}
-
-/*!
- \internal
-
- Calculate graphs is the method that puts together all the helper routines
- so that the AnchorLayout can calculate the sizes of each item.
-
- In a nutshell it should do:
-
- 1) Refresh anchor nominal sizes, that is, the size that each anchor would
- have if no other restrictions applied. This is done by quering the
- layout style and the sizeHints of the items belonging to the layout.
-
- 2) Simplify the graph by grouping together parallel and sequential anchors
- into "group anchors". These have equivalent minimum, preferred and maximum
- sizeHints as the anchors they replace.
-
- 3) Check if we got to a trivial case. In some cases, the whole graph can be
- simplified into a single anchor. If so, use this information. If not,
- then call the Simplex solver to calculate the anchors sizes.
-
- 4) Once the root anchors had its sizes calculated, propagate that to the
- anchors they represent.
-*/
-void QGraphicsAnchorLayoutPrivate::calculateGraphs(
- QGraphicsAnchorLayoutPrivate::Orientation orientation)
-{
-#if defined(QT_DEBUG) || defined(Q_AUTOTEST_EXPORT)
- lastCalculationUsedSimplex[orientation] = false;
-#endif
-
- static bool simplificationEnabled = qgetenv("QT_ANCHORLAYOUT_NO_SIMPLIFICATION").isEmpty();
-
- // Reset the nominal sizes of each anchor based on the current item sizes
- refreshAllSizeHints(orientation);
-
- // Simplify the graph
- if (simplificationEnabled && !simplifyGraph(orientation)) {
- qWarning("QGraphicsAnchorLayout: anchor setup is not feasible.");
- graphHasConflicts[orientation] = true;
- return;
- }
-
- // Traverse all graph edges and store the possible paths to each vertex
- findPaths(orientation);
-
- // From the paths calculated above, extract the constraints that the current
- // anchor setup impose, to our Linear Programming problem.
- constraintsFromPaths(orientation);
-
- // Split the constraints and anchors into groups that should be fed to the
- // simplex solver independently. Currently we find two groups:
- //
- // 1) The "trunk", that is, the set of anchors (items) that are connected
- // to the two opposite sides of our layout, and thus need to stretch in
- // order to fit in the current layout size.
- //
- // 2) The floating or semi-floating anchors (items) that are those which
- // are connected to only one (or none) of the layout sides, thus are not
- // influenced by the layout size.
- QList<QList<QSimplexConstraint *> > parts = getGraphParts(orientation);
-
- // Now run the simplex solver to calculate Minimum, Preferred and Maximum sizes
- // of the "trunk" set of constraints and variables.
- // ### does trunk always exist? empty = trunk is the layout left->center->right
- QList<QSimplexConstraint *> trunkConstraints = parts.at(0);
- QList<AnchorData *> trunkVariables = getVariables(trunkConstraints);
-
- // For minimum and maximum, use the path between the two layout sides as the
- // objective function.
- AnchorVertex *v = layoutLastVertex[orientation];
- GraphPath trunkPath = graphPaths[orientation].value(v);
-
- bool feasible = calculateTrunk(orientation, trunkPath, trunkConstraints, trunkVariables);
-
- // For the other parts that not the trunk, solve only for the preferred size
- // that is the size they will remain at, since they are not stretched by the
- // layout.
-
- // Skipping the first (trunk)
- for (int i = 1; i < parts.count(); ++i) {
- if (!feasible)
- break;
-
- QList<QSimplexConstraint *> partConstraints = parts.at(i);
- QList<AnchorData *> partVariables = getVariables(partConstraints);
- Q_ASSERT(!partVariables.isEmpty());
- feasible &= calculateNonTrunk(partConstraints, partVariables);
- }
-
- // Propagate the new sizes down the simplified graph, ie. tell the
- // group anchors to set their children anchors sizes.
- updateAnchorSizes(orientation);
-
- graphHasConflicts[orientation] = !feasible;
-
- // Clean up our data structures. They are not needed anymore since
- // distribution uses just interpolation.
- qDeleteAll(constraints[orientation]);
- constraints[orientation].clear();
- graphPaths[orientation].clear(); // ###
-
- if (simplificationEnabled)
- restoreSimplifiedGraph(orientation);
-}
-
-/*!
- \internal
-
- Shift all the constraints by a certain amount. This allows us to deal with negative values in
- the linear program if they are bounded by a certain limit. Functions should be careful to
- call it again with a negative amount, to shift the constraints back.
-*/
-static void shiftConstraints(const QList<QSimplexConstraint *> &constraints, qreal amount)
-{
- for (int i = 0; i < constraints.count(); ++i) {
- QSimplexConstraint *c = constraints.at(i);
- qreal multiplier = 0;
- foreach (qreal v, c->variables.values()) {
- multiplier += v;
- }
- c->constant += multiplier * amount;
- }
-}
-
-/*!
- \internal
-
- Calculate the sizes for all anchors which are part of the trunk. This works
- on top of a (possibly) simplified graph.
-*/
-bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Orientation orientation, const GraphPath &path,
- const QList<QSimplexConstraint *> &constraints,
- const QList<AnchorData *> &variables)
-{
- bool feasible = true;
- bool needsSimplex = !constraints.isEmpty();
-
-#if 0
- qDebug("Simplex %s for trunk of %s", needsSimplex ? "used" : "NOT used",
- orientation == Horizontal ? "Horizontal" : "Vertical");
-#endif
-
- if (needsSimplex) {
-
- QList<QSimplexConstraint *> sizeHintConstraints = constraintsFromSizeHints(variables);
- QList<QSimplexConstraint *> allConstraints = constraints + sizeHintConstraints;
-
- shiftConstraints(allConstraints, g_offset);
-
- // Solve min and max size hints
- qreal min, max;
- feasible = solveMinMax(allConstraints, path, &min, &max);
-
- if (feasible) {
- solvePreferred(constraints, variables);
-
- // Calculate and set the preferred size for the layout,
- // from the edge sizes that were calculated above.
- qreal pref(0.0);
- foreach (const AnchorData *ad, path.positives) {
- pref += ad->sizeAtPreferred;
- }
- foreach (const AnchorData *ad, path.negatives) {
- pref -= ad->sizeAtPreferred;
- }
-
- sizeHints[orientation][Qt::MinimumSize] = min;
- sizeHints[orientation][Qt::PreferredSize] = pref;
- sizeHints[orientation][Qt::MaximumSize] = max;
- }
-
- qDeleteAll(sizeHintConstraints);
- shiftConstraints(constraints, -g_offset);
-
- } else {
- // No Simplex is necessary because the path was simplified all the way to a single
- // anchor.
- Q_ASSERT(path.positives.count() == 1);
- Q_ASSERT(path.negatives.count() == 0);
-
- AnchorData *ad = path.positives.toList()[0];
- ad->sizeAtMinimum = ad->minSize;
- ad->sizeAtPreferred = ad->prefSize;
- ad->sizeAtMaximum = ad->maxSize;
-
- sizeHints[orientation][Qt::MinimumSize] = ad->sizeAtMinimum;
- sizeHints[orientation][Qt::PreferredSize] = ad->sizeAtPreferred;
- sizeHints[orientation][Qt::MaximumSize] = ad->sizeAtMaximum;
- }
-
-#if defined(QT_DEBUG) || defined(Q_AUTOTEST_EXPORT)
- lastCalculationUsedSimplex[orientation] = needsSimplex;
-#endif
-
- return feasible;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(const QList<QSimplexConstraint *> &constraints,
- const QList<AnchorData *> &variables)
-{
- shiftConstraints(constraints, g_offset);
- bool feasible = solvePreferred(constraints, variables);
-
- if (feasible) {
- // Propagate size at preferred to other sizes. Semi-floats always will be
- // in their sizeAtPreferred.
- for (int j = 0; j < variables.count(); ++j) {
- AnchorData *ad = variables.at(j);
- Q_ASSERT(ad);
- ad->sizeAtMinimum = ad->sizeAtPreferred;
- ad->sizeAtMaximum = ad->sizeAtPreferred;
- }
- }
-
- shiftConstraints(constraints, -g_offset);
- return feasible;
-}
-
-/*!
- \internal
-
- Traverse the graph refreshing the size hints. Edges will query their associated
- item or graphicsAnchor for their size hints.
-*/
-void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Orientation orientation)
-{
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- QList<QPair<AnchorVertex *, AnchorVertex *> > vertices = g.connections();
-
- QLayoutStyleInfo styleInf = styleInfo();
- for (int i = 0; i < vertices.count(); ++i) {
- AnchorData *data = g.edgeData(vertices.at(i).first, vertices.at(i).second);
- data->refreshSizeHints(&styleInf);
- }
-}
-
-/*!
- \internal
-
- This method walks the graph using a breadth-first search to find paths
- between the root vertex and each vertex on the graph. The edges
- directions in each path are considered and they are stored as a
- positive edge (left-to-right) or negative edge (right-to-left).
-
- The list of paths is used later to generate a list of constraints.
- */
-void QGraphicsAnchorLayoutPrivate::findPaths(Orientation orientation)
-{
- QQueue<QPair<AnchorVertex *, AnchorVertex *> > queue;
-
- QSet<AnchorData *> visited;
-
- AnchorVertex *root = layoutFirstVertex[orientation];
-
- graphPaths[orientation].insert(root, GraphPath());
-
- foreach (AnchorVertex *v, graph[orientation].adjacentVertices(root)) {
- queue.enqueue(qMakePair(root, v));
- }
-
- while(!queue.isEmpty()) {
- QPair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
- AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
-
- if (visited.contains(edge))
- continue;
-
- visited.insert(edge);
- GraphPath current = graphPaths[orientation].value(pair.first);
-
- if (edge->from == pair.first)
- current.positives.insert(edge);
- else
- current.negatives.insert(edge);
-
- graphPaths[orientation].insert(pair.second, current);
-
- foreach (AnchorVertex *v,
- graph[orientation].adjacentVertices(pair.second)) {
- queue.enqueue(qMakePair(pair.second, v));
- }
- }
-
- // We will walk through every reachable items (non-float) store them in a temporary set.
- // We them create a set of all items and subtract the non-floating items from the set in
- // order to get the floating items. The floating items is then stored in m_floatItems
- identifyFloatItems(visited, orientation);
-}
-
-/*!
- \internal
-
- Each vertex on the graph that has more than one path to it
- represents a contra int to the sizes of the items in these paths.
-
- This method walks the list of paths to each vertex, generate
- the constraints and store them in a list so they can be used later
- by the Simplex solver.
-*/
-void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Orientation orientation)
-{
- foreach (AnchorVertex *vertex, graphPaths[orientation].uniqueKeys())
- {
- int valueCount = graphPaths[orientation].count(vertex);
- if (valueCount == 1)
- continue;
-
- QList<GraphPath> pathsToVertex = graphPaths[orientation].values(vertex);
- for (int i = 1; i < valueCount; ++i) {
- constraints[orientation] += \
- pathsToVertex[0].constraint(pathsToVertex.at(i));
- }
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsAnchorLayoutPrivate::updateAnchorSizes(Orientation orientation)
-{
- Graph<AnchorVertex, AnchorData> &g = graph[orientation];
- const QList<QPair<AnchorVertex *, AnchorVertex *> > &vertices = g.connections();
-
- for (int i = 0; i < vertices.count(); ++i) {
- AnchorData *ad = g.edgeData(vertices.at(i).first, vertices.at(i).second);
- ad->updateChildrenSizes();
- }
-}
-
-/*!
- \internal
-
- Create LP constraints for each anchor based on its minimum and maximum
- sizes, as specified in its size hints
-*/
-QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHints(
- const QList<AnchorData *> &anchors)
-{
- if (anchors.isEmpty())
- return QList<QSimplexConstraint *>();
-
- // Look for the layout edge. That can be either the first half in case the
- // layout is split in two, or the whole layout anchor.
- Orientation orient = Orientation(anchors.first()->orientation);
- AnchorData *layoutEdge = 0;
- if (layoutCentralVertex[orient]) {
- layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutCentralVertex[orient]);
- } else {
- layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutLastVertex[orient]);
- }
-
- // If maxSize is less then "infinite", that means there are other anchors
- // grouped together with this one. We can't ignore its maximum value so we
- // set back the variable to NULL to prevent the continue condition from being
- // satisfied in the loop below.
- const qreal expectedMax = layoutCentralVertex[orient] ? QWIDGETSIZE_MAX / 2 : QWIDGETSIZE_MAX;
- qreal actualMax;
- if (layoutEdge->from == layoutFirstVertex[orient]) {
- actualMax = layoutEdge->maxSize;
- } else {
- actualMax = -layoutEdge->minSize;
- }
- if (actualMax != expectedMax) {
- layoutEdge = 0;
- }
-
- // For each variable, create constraints based on size hints
- QList<QSimplexConstraint *> anchorConstraints;
- bool unboundedProblem = true;
- for (int i = 0; i < anchors.size(); ++i) {
- AnchorData *ad = anchors.at(i);
-
- // Anchors that have their size directly linked to another one don't need constraints
- // For exammple, the second half of an item has exactly the same size as the first half
- // thus constraining the latter is enough.
- if (ad->dependency == AnchorData::Slave)
- continue;
-
- // To use negative variables inside simplex, we shift them so the minimum negative value is
- // mapped to zero before solving. To make sure that it works, we need to guarantee that the
- // variables are all inside a certain boundary.
- qreal boundedMin = qBound(-g_offset, ad->minSize, g_offset);
- qreal boundedMax = qBound(-g_offset, ad->maxSize, g_offset);
-
- if ((boundedMin == boundedMax) || qFuzzyCompare(boundedMin, boundedMax)) {
- QSimplexConstraint *c = new QSimplexConstraint;
- c->variables.insert(ad, 1.0);
- c->constant = boundedMin;
- c->ratio = QSimplexConstraint::Equal;
- anchorConstraints += c;
- unboundedProblem = false;
- } else {
- QSimplexConstraint *c = new QSimplexConstraint;
- c->variables.insert(ad, 1.0);
- c->constant = boundedMin;
- c->ratio = QSimplexConstraint::MoreOrEqual;
- anchorConstraints += c;
-
- // We avoid adding restrictions to the layout internal anchors. That's
- // to prevent unnecessary fair distribution from happening due to this
- // artificial restriction.
- if (ad == layoutEdge)
- continue;
-
- c = new QSimplexConstraint;
- c->variables.insert(ad, 1.0);
- c->constant = boundedMax;
- c->ratio = QSimplexConstraint::LessOrEqual;
- anchorConstraints += c;
- unboundedProblem = false;
- }
- }
-
- // If no upper boundary restriction was added, add one to avoid unbounded problem
- if (unboundedProblem) {
- QSimplexConstraint *c = new QSimplexConstraint;
- c->variables.insert(layoutEdge, 1.0);
- // The maximum size that the layout can take
- c->constant = g_offset;
- c->ratio = QSimplexConstraint::LessOrEqual;
- anchorConstraints += c;
- }
-
- return anchorConstraints;
-}
-
-/*!
- \internal
-*/
-QList< QList<QSimplexConstraint *> >
-QGraphicsAnchorLayoutPrivate::getGraphParts(Orientation orientation)
-{
- Q_ASSERT(layoutFirstVertex[orientation] && layoutLastVertex[orientation]);
-
- AnchorData *edgeL1 = 0;
- AnchorData *edgeL2 = 0;
-
- // The layout may have a single anchor between Left and Right or two half anchors
- // passing through the center
- if (layoutCentralVertex[orientation]) {
- edgeL1 = graph[orientation].edgeData(layoutFirstVertex[orientation], layoutCentralVertex[orientation]);
- edgeL2 = graph[orientation].edgeData(layoutCentralVertex[orientation], layoutLastVertex[orientation]);
- } else {
- edgeL1 = graph[orientation].edgeData(layoutFirstVertex[orientation], layoutLastVertex[orientation]);
- }
-
- QLinkedList<QSimplexConstraint *> remainingConstraints;
- for (int i = 0; i < constraints[orientation].count(); ++i) {
- remainingConstraints += constraints[orientation].at(i);
- }
- for (int i = 0; i < itemCenterConstraints[orientation].count(); ++i) {
- remainingConstraints += itemCenterConstraints[orientation].at(i);
- }
-
- QList<QSimplexConstraint *> trunkConstraints;
- QSet<QSimplexVariable *> trunkVariables;
-
- trunkVariables += edgeL1;
- if (edgeL2)
- trunkVariables += edgeL2;
-
- bool dirty;
- do {
- dirty = false;
-
- QLinkedList<QSimplexConstraint *>::iterator it = remainingConstraints.begin();
- while (it != remainingConstraints.end()) {
- QSimplexConstraint *c = *it;
- bool match = false;
-
- // Check if this constraint have some overlap with current
- // trunk variables...
- foreach (QSimplexVariable *ad, trunkVariables) {
- if (c->variables.contains(ad)) {
- match = true;
- break;
- }
- }
-
- // If so, we add it to trunk, and erase it from the
- // remaining constraints.
- if (match) {
- trunkConstraints += c;
- trunkVariables += QSet<QSimplexVariable *>::fromList(c->variables.keys());
- it = remainingConstraints.erase(it);
- dirty = true;
- } else {
- // Note that we don't erase the constraint if it's not
- // a match, since in a next iteration of a do-while we
- // can pass on it again and it will be a match.
- //
- // For example: if trunk share a variable with
- // remainingConstraints[1] and it shares with
- // remainingConstraints[0], we need a second iteration
- // of the do-while loop to match both.
- ++it;
- }
- }
- } while (dirty);
-
- QList< QList<QSimplexConstraint *> > result;
- result += trunkConstraints;
-
- if (!remainingConstraints.isEmpty()) {
- QList<QSimplexConstraint *> nonTrunkConstraints;
- QLinkedList<QSimplexConstraint *>::iterator it = remainingConstraints.begin();
- while (it != remainingConstraints.end()) {
- nonTrunkConstraints += *it;
- ++it;
- }
- result += nonTrunkConstraints;
- }
-
- return result;
-}
-
-/*!
- \internal
-
- Use all visited Anchors on findPaths() so we can identify non-float Items.
-*/
-void QGraphicsAnchorLayoutPrivate::identifyFloatItems(const QSet<AnchorData *> &visited, Orientation orientation)
-{
- QSet<QGraphicsLayoutItem *> nonFloating;
-
- foreach (const AnchorData *ad, visited)
- identifyNonFloatItems_helper(ad, &nonFloating);
-
- QSet<QGraphicsLayoutItem *> allItems;
- foreach (QGraphicsLayoutItem *item, items)
- allItems.insert(item);
- m_floatItems[orientation] = allItems - nonFloating;
-}
-
-
-/*!
- \internal
-
- Given an anchor, if it is an internal anchor and Normal we must mark it's item as non-float.
- If the anchor is Sequential or Parallel, we must iterate on its children recursively until we reach
- internal anchors (items).
-*/
-void QGraphicsAnchorLayoutPrivate::identifyNonFloatItems_helper(const AnchorData *ad, QSet<QGraphicsLayoutItem *> *nonFloatingItemsIdentifiedSoFar)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- switch(ad->type) {
- case AnchorData::Normal:
- if (ad->item && ad->item != q)
- nonFloatingItemsIdentifiedSoFar->insert(ad->item);
- break;
- case AnchorData::Sequential:
- foreach (const AnchorData *d, static_cast<const SequentialAnchorData *>(ad)->m_edges)
- identifyNonFloatItems_helper(d, nonFloatingItemsIdentifiedSoFar);
- break;
- case AnchorData::Parallel:
- identifyNonFloatItems_helper(static_cast<const ParallelAnchorData *>(ad)->firstEdge, nonFloatingItemsIdentifiedSoFar);
- identifyNonFloatItems_helper(static_cast<const ParallelAnchorData *>(ad)->secondEdge, nonFloatingItemsIdentifiedSoFar);
- break;
- }
-}
-
-/*!
- \internal
-
- Use the current vertices distance to calculate and set the geometry of
- each item.
-*/
-void QGraphicsAnchorLayoutPrivate::setItemsGeometries(const QRectF &geom)
-{
- Q_Q(QGraphicsAnchorLayout);
- AnchorVertex *firstH, *secondH, *firstV, *secondV;
-
- qreal top;
- qreal left;
- qreal right;
-
- q->getContentsMargins(&left, &top, &right, 0);
- const Qt::LayoutDirection visualDir = visualDirection();
- if (visualDir == Qt::RightToLeft)
- qSwap(left, right);
-
- left += geom.left();
- top += geom.top();
- right = geom.right() - right;
-
- foreach (QGraphicsLayoutItem *item, items) {
- QRectF newGeom;
- QSizeF itemPreferredSize = item->effectiveSizeHint(Qt::PreferredSize);
- if (m_floatItems[Horizontal].contains(item)) {
- newGeom.setLeft(0);
- newGeom.setRight(itemPreferredSize.width());
- } else {
- firstH = internalVertex(item, Qt::AnchorLeft);
- secondH = internalVertex(item, Qt::AnchorRight);
-
- if (visualDir == Qt::LeftToRight) {
- newGeom.setLeft(left + firstH->distance);
- newGeom.setRight(left + secondH->distance);
- } else {
- newGeom.setLeft(right - secondH->distance);
- newGeom.setRight(right - firstH->distance);
- }
- }
-
- if (m_floatItems[Vertical].contains(item)) {
- newGeom.setTop(0);
- newGeom.setBottom(itemPreferredSize.height());
- } else {
- firstV = internalVertex(item, Qt::AnchorTop);
- secondV = internalVertex(item, Qt::AnchorBottom);
-
- newGeom.setTop(top + firstV->distance);
- newGeom.setBottom(top + secondV->distance);
- }
-
- item->setGeometry(newGeom);
- }
-}
-
-/*!
- \internal
-
- Calculate the position of each vertex based on the paths to each of
- them as well as the current edges sizes.
-*/
-void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(
- QGraphicsAnchorLayoutPrivate::Orientation orientation)
-{
- QQueue<QPair<AnchorVertex *, AnchorVertex *> > queue;
- QSet<AnchorVertex *> visited;
-
- // Get root vertex
- AnchorVertex *root = layoutFirstVertex[orientation];
-
- root->distance = 0;
- visited.insert(root);
-
- // Add initial edges to the queue
- foreach (AnchorVertex *v, graph[orientation].adjacentVertices(root)) {
- queue.enqueue(qMakePair(root, v));
- }
-
- // Do initial calculation required by "interpolateEdge()"
- setupEdgesInterpolation(orientation);
-
- // Traverse the graph and calculate vertex positions
- while (!queue.isEmpty()) {
- QPair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
- AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
-
- if (visited.contains(pair.second))
- continue;
-
- visited.insert(pair.second);
- interpolateEdge(pair.first, edge);
-
- QList<AnchorVertex *> adjacents = graph[orientation].adjacentVertices(pair.second);
- for (int i = 0; i < adjacents.count(); ++i) {
- if (!visited.contains(adjacents.at(i)))
- queue.enqueue(qMakePair(pair.second, adjacents.at(i)));
- }
- }
-}
-
-/*!
- \internal
-
- Calculate interpolation parameters based on current Layout Size.
- Must be called once before calling "interpolateEdgeSize()" for
- the edges.
-*/
-void QGraphicsAnchorLayoutPrivate::setupEdgesInterpolation(
- Orientation orientation)
-{
- Q_Q(QGraphicsAnchorLayout);
-
- qreal current;
- current = (orientation == Horizontal) ? q->contentsRect().width() : q->contentsRect().height();
-
- QPair<Interval, qreal> result;
- result = getFactor(current,
- sizeHints[orientation][Qt::MinimumSize],
- sizeHints[orientation][Qt::PreferredSize],
- sizeHints[orientation][Qt::PreferredSize],
- sizeHints[orientation][Qt::PreferredSize],
- sizeHints[orientation][Qt::MaximumSize]);
-
- interpolationInterval[orientation] = result.first;
- interpolationProgress[orientation] = result.second;
-}
-
-/*!
- \internal
-
- Calculate the current Edge size based on the current Layout size and the
- size the edge is supposed to have when the layout is at its:
-
- - minimum size,
- - preferred size,
- - maximum size.
-
- These three key values are calculated in advance using linear
- programming (more expensive) or the simplification algorithm, then
- subsequential resizes of the parent layout require a simple
- interpolation.
-*/
-void QGraphicsAnchorLayoutPrivate::interpolateEdge(AnchorVertex *base, AnchorData *edge)
-{
- const Orientation orientation = Orientation(edge->orientation);
- const QPair<Interval, qreal> factor(interpolationInterval[orientation],
- interpolationProgress[orientation]);
-
- qreal edgeDistance = interpolate(factor, edge->sizeAtMinimum, edge->sizeAtPreferred,
- edge->sizeAtPreferred, edge->sizeAtPreferred,
- edge->sizeAtMaximum);
-
- Q_ASSERT(edge->from == base || edge->to == base);
-
- // Calculate the distance for the vertex opposite to the base
- if (edge->from == base) {
- edge->to->distance = base->distance + edgeDistance;
- } else {
- edge->from->distance = base->distance - edgeDistance;
- }
-}
-
-bool QGraphicsAnchorLayoutPrivate::solveMinMax(const QList<QSimplexConstraint *> &constraints,
- GraphPath path, qreal *min, qreal *max)
-{
- QSimplex simplex;
- bool feasible = simplex.setConstraints(constraints);
- if (feasible) {
- // Obtain the objective constraint
- QSimplexConstraint objective;
- QSet<AnchorData *>::const_iterator iter;
- for (iter = path.positives.constBegin(); iter != path.positives.constEnd(); ++iter)
- objective.variables.insert(*iter, 1.0);
-
- for (iter = path.negatives.constBegin(); iter != path.negatives.constEnd(); ++iter)
- objective.variables.insert(*iter, -1.0);
-
- const qreal objectiveOffset = (path.positives.count() - path.negatives.count()) * g_offset;
- simplex.setObjective(&objective);
-
- // Calculate minimum values
- *min = simplex.solveMin() - objectiveOffset;
-
- // Save sizeAtMinimum results
- QList<AnchorData *> variables = getVariables(constraints);
- for (int i = 0; i < variables.size(); ++i) {
- AnchorData *ad = static_cast<AnchorData *>(variables.at(i));
- ad->sizeAtMinimum = ad->result - g_offset;
- }
-
- // Calculate maximum values
- *max = simplex.solveMax() - objectiveOffset;
-
- // Save sizeAtMaximum results
- for (int i = 0; i < variables.size(); ++i) {
- AnchorData *ad = static_cast<AnchorData *>(variables.at(i));
- ad->sizeAtMaximum = ad->result - g_offset;
- }
- }
- return feasible;
-}
-
-enum slackType { Grower = -1, Shrinker = 1 };
-static QPair<QSimplexVariable *, QSimplexConstraint *> createSlack(QSimplexConstraint *sizeConstraint,
- qreal interval, slackType type)
-{
- QSimplexVariable *slack = new QSimplexVariable;
- sizeConstraint->variables.insert(slack, type);
-
- QSimplexConstraint *limit = new QSimplexConstraint;
- limit->variables.insert(slack, 1.0);
- limit->ratio = QSimplexConstraint::LessOrEqual;
- limit->constant = interval;
-
- return qMakePair(slack, limit);
-}
-
-bool QGraphicsAnchorLayoutPrivate::solvePreferred(const QList<QSimplexConstraint *> &constraints,
- const QList<AnchorData *> &variables)
-{
- QList<QSimplexConstraint *> preferredConstraints;
- QList<QSimplexVariable *> preferredVariables;
- QSimplexConstraint objective;
-
- // Fill the objective coefficients for this variable. In the
- // end the objective function will be
- //
- // z = n * (A_shrinker_hard + A_grower_hard + B_shrinker_hard + B_grower_hard + ...) +
- // (A_shrinker_soft + A_grower_soft + B_shrinker_soft + B_grower_soft + ...)
- //
- // where n is the number of variables that have
- // slacks. Note that here we use the number of variables
- // as coefficient, this is to mark the "shrinker slack
- // variable" less likely to get value than the "grower
- // slack variable".
-
- // This will fill the values for the structural constraints
- // and we now fill the values for the slack constraints (one per variable),
- // which have this form (the constant A_pref was set when creating the slacks):
- //
- // A + A_shrinker_hard + A_shrinker_soft - A_grower_hard - A_grower_soft = A_pref
- //
- for (int i = 0; i < variables.size(); ++i) {
- AnchorData *ad = variables.at(i);
-
- // The layout original structure anchors are not relevant in preferred size calculation
- if (ad->isLayoutAnchor)
- continue;
-
- // By default, all variables are equal to their preferred size. If they have room to
- // grow or shrink, such flexibility will be added by the additional variables below.
- QSimplexConstraint *sizeConstraint = new QSimplexConstraint;
- preferredConstraints += sizeConstraint;
- sizeConstraint->variables.insert(ad, 1.0);
- sizeConstraint->constant = ad->prefSize + g_offset;
-
- // Can easily shrink
- QPair<QSimplexVariable *, QSimplexConstraint *> slack;
- const qreal softShrinkInterval = ad->prefSize - ad->minPrefSize;
- if (softShrinkInterval) {
- slack = createSlack(sizeConstraint, softShrinkInterval, Shrinker);
- preferredVariables += slack.first;
- preferredConstraints += slack.second;
-
- // Add to objective with ratio == 1 (soft)
- objective.variables.insert(slack.first, 1.0);
- }
-
- // Can easily grow
- const qreal softGrowInterval = ad->maxPrefSize - ad->prefSize;
- if (softGrowInterval) {
- slack = createSlack(sizeConstraint, softGrowInterval, Grower);
- preferredVariables += slack.first;
- preferredConstraints += slack.second;
-
- // Add to objective with ratio == 1 (soft)
- objective.variables.insert(slack.first, 1.0);
- }
-
- // Can shrink if really necessary
- const qreal hardShrinkInterval = ad->minPrefSize - ad->minSize;
- if (hardShrinkInterval) {
- slack = createSlack(sizeConstraint, hardShrinkInterval, Shrinker);
- preferredVariables += slack.first;
- preferredConstraints += slack.second;
-
- // Add to objective with ratio == N (hard)
- objective.variables.insert(slack.first, variables.size());
- }
-
- // Can grow if really necessary
- const qreal hardGrowInterval = ad->maxSize - ad->maxPrefSize;
- if (hardGrowInterval) {
- slack = createSlack(sizeConstraint, hardGrowInterval, Grower);
- preferredVariables += slack.first;
- preferredConstraints += slack.second;
-
- // Add to objective with ratio == N (hard)
- objective.variables.insert(slack.first, variables.size());
- }
- }
-
- QSimplex *simplex = new QSimplex;
- bool feasible = simplex->setConstraints(constraints + preferredConstraints);
- if (feasible) {
- simplex->setObjective(&objective);
-
- // Calculate minimum values
- simplex->solveMin();
-
- // Save sizeAtPreferred results
- for (int i = 0; i < variables.size(); ++i) {
- AnchorData *ad = variables.at(i);
- ad->sizeAtPreferred = ad->result - g_offset;
- }
-
- // Make sure we delete the simplex solver -before- we delete the
- // constraints used by it.
- delete simplex;
- }
- // Delete constraints and variables we created.
- qDeleteAll(preferredConstraints);
- qDeleteAll(preferredVariables);
-
- return feasible;
-}
-
-/*!
- \internal
- Returns true if there are no arrangement that satisfies all constraints.
- Otherwise returns false.
-
- \sa addAnchor()
-*/
-bool QGraphicsAnchorLayoutPrivate::hasConflicts() const
-{
- QGraphicsAnchorLayoutPrivate *that = const_cast<QGraphicsAnchorLayoutPrivate*>(this);
- that->calculateGraphs();
-
- bool floatConflict = !m_floatItems[0].isEmpty() || !m_floatItems[1].isEmpty();
-
- return graphHasConflicts[0] || graphHasConflicts[1] || floatConflict;
-}
-
-#ifdef QT_DEBUG
-void QGraphicsAnchorLayoutPrivate::dumpGraph(const QString &name)
-{
- QFile file(QString::fromAscii("anchorlayout.%1.dot").arg(name));
- if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
- qWarning("Could not write to %s", file.fileName().toLocal8Bit().constData());
-
- QString str = QString::fromAscii("digraph anchorlayout {\nnode [shape=\"rect\"]\n%1}");
- QString dotContents = graph[0].serializeToDot();
- dotContents += graph[1].serializeToDot();
- file.write(str.arg(dotContents).toLocal8Bit());
-
- file.close();
-}
-#endif
-
-QT_END_NAMESPACE
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout_p.h b/src/gui/graphicsview/qgraphicsanchorlayout_p.h
deleted file mode 100644
index 9a91c3c8df..0000000000
--- a/src/gui/graphicsview/qgraphicsanchorlayout_p.h
+++ /dev/null
@@ -1,594 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSANCHORLAYOUT_P_H
-#define QGRAPHICSANCHORLAYOUT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QGraphicsWidget>
-#include <private/qobject_p.h>
-
-#include "qgraphicslayout_p.h"
-#include "qgraphicsanchorlayout.h"
-#include "qgraph_p.h"
-#include "qsimplex_p.h"
-#ifndef QT_NO_GRAPHICSVIEW
-QT_BEGIN_NAMESPACE
-
-/*
- The public QGraphicsAnchorLayout interface represents an anchorage point
- as a pair of a <QGraphicsLayoutItem *> and a <Qt::AnchorPoint>.
-
- Internally though, it has a graph of anchorage points (vertices) and
- anchors (edges), represented by the AnchorVertex and AnchorData structs
- respectively.
-*/
-
-/*!
- \internal
-
- Represents a vertex (anchorage point) in the internal graph
-*/
-struct AnchorVertex {
- enum Type {
- Normal = 0,
- Pair
- };
-
- AnchorVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge)
- : m_item(item), m_edge(edge), m_type(Normal) {}
-
- AnchorVertex()
- : m_item(0), m_edge(Qt::AnchorPoint(0)), m_type(Normal) {}
-
-#ifdef QT_DEBUG
- inline QString toString() const;
-#endif
-
- QGraphicsLayoutItem *m_item;
- Qt::AnchorPoint m_edge;
- uint m_type : 1;
-
- // Current distance from this vertex to the layout edge (Left or Top)
- // Value is calculated from the current anchors sizes.
- qreal distance;
-};
-
-/*!
- \internal
-
- Represents an edge (anchor) in the internal graph.
-*/
-struct AnchorData : public QSimplexVariable {
- enum Type {
- Normal = 0,
- Sequential,
- Parallel
- };
-
- enum Dependency {
- Independent = 0,
- Master,
- Slave
- };
-
- AnchorData()
- : QSimplexVariable(), from(0), to(0),
- minSize(0), prefSize(0), maxSize(0),
- minPrefSize(0), maxPrefSize(0),
- sizeAtMinimum(0), sizeAtPreferred(0),
- sizeAtMaximum(0), item(0), graphicsAnchor(0),
- type(Normal), isLayoutAnchor(false),
- isCenterAnchor(false), orientation(0),
- dependency(Independent) {}
- virtual ~AnchorData();
-
- virtual void updateChildrenSizes() {}
- void refreshSizeHints(const QLayoutStyleInfo *styleInfo = 0);
-
-#ifdef QT_DEBUG
- void dump(int indent = 2);
- inline QString toString() const;
- QString name;
-#endif
-
- // Anchor is semantically directed
- AnchorVertex *from;
- AnchorVertex *to;
-
- // Nominal sizes
- // These are the intrinsic size restrictions for a given item. They are
- // used as input for the calculation of the actual sizes.
- // These values are filled by the refreshSizeHints method, based on the
- // anchor size policy, the size hints of the item it (possibly) represents
- // and the layout spacing information.
- qreal minSize;
- qreal prefSize;
- qreal maxSize;
-
- qreal minPrefSize;
- qreal maxPrefSize;
-
- // Calculated sizes
- // These attributes define which sizes should that anchor be in when the
- // layout is at its minimum, preferred or maximum sizes. Values are
- // calculated by the Simplex solver based on the current layout setup.
- qreal sizeAtMinimum;
- qreal sizeAtPreferred;
- qreal sizeAtMaximum;
-
- // References to the classes that represent this anchor in the public world
- // An anchor may represent a LayoutItem, it may also be acessible externally
- // through a GraphicsAnchor "handler".
- QGraphicsLayoutItem *item;
- QGraphicsAnchor *graphicsAnchor;
-
- uint type : 2; // either Normal, Sequential or Parallel
- uint isLayoutAnchor : 1; // if this anchor is an internal layout anchor
- uint isCenterAnchor : 1;
- uint orientation : 1;
- uint dependency : 2; // either Independent, Master or Slave
-};
-
-#ifdef QT_DEBUG
-inline QString AnchorData::toString() const
-{
- return QString::fromAscii("Anchor(%1)").arg(name);
-}
-#endif
-
-struct SequentialAnchorData : public AnchorData
-{
- SequentialAnchorData(const QVector<AnchorVertex *> &vertices, const QVector<AnchorData *> &edges)
- : AnchorData(), m_children(vertices), m_edges(edges)
- {
- type = AnchorData::Sequential;
- orientation = m_edges.at(0)->orientation;
-#ifdef QT_DEBUG
- name = QString::fromAscii("%1 -- %2").arg(vertices.first()->toString(), vertices.last()->toString());
-#endif
- }
-
- virtual void updateChildrenSizes();
- void calculateSizeHints();
-
- QVector<AnchorVertex*> m_children; // list of vertices in the sequence
- QVector<AnchorData*> m_edges; // keep the list of edges too.
-};
-
-struct ParallelAnchorData : public AnchorData
-{
- ParallelAnchorData(AnchorData *first, AnchorData *second)
- : AnchorData(), firstEdge(first), secondEdge(second)
- {
- type = AnchorData::Parallel;
- orientation = first->orientation;
-
- // This assert whether the child anchors share their vertices
- Q_ASSERT(((first->from == second->from) && (first->to == second->to)) ||
- ((first->from == second->to) && (first->to == second->from)));
-
- // Our convention will be that the parallel group anchor will have the same
- // direction as the first anchor.
- from = first->from;
- to = first->to;
-#ifdef QT_DEBUG
- name = QString::fromAscii("%1 | %2").arg(first->toString(), second->toString());
-#endif
- }
-
- virtual void updateChildrenSizes();
- bool calculateSizeHints();
-
- bool secondForward() const {
- // We have the convention that the first children will define the direction of the
- // pararell group. Note that we can't rely on 'this->from' or 'this->to' because they
- // might be changed by vertex simplification.
- return firstEdge->from == secondEdge->from;
- }
-
- AnchorData* firstEdge;
- AnchorData* secondEdge;
-
- QList<QSimplexConstraint *> m_firstConstraints;
- QList<QSimplexConstraint *> m_secondConstraints;
-};
-
-struct AnchorVertexPair : public AnchorVertex {
- AnchorVertexPair(AnchorVertex *v1, AnchorVertex *v2, AnchorData *data)
- : AnchorVertex(), m_first(v1), m_second(v2), m_removedAnchor(data) {
- m_type = AnchorVertex::Pair;
- }
-
- AnchorVertex *m_first;
- AnchorVertex *m_second;
-
- AnchorData *m_removedAnchor;
- QList<AnchorData *> m_firstAnchors;
- QList<AnchorData *> m_secondAnchors;
-};
-
-#ifdef QT_DEBUG
-inline QString AnchorVertex::toString() const
-{
- if (!this) {
- return QLatin1String("NULL");
- } else if (m_type == Pair) {
- const AnchorVertexPair *vp = static_cast<const AnchorVertexPair *>(this);
- return QString::fromAscii("(%1, %2)").arg(vp->m_first->toString()).arg(vp->m_second->toString());
- } else if (!m_item) {
- return QString::fromAscii("NULL_%1").arg(quintptr(this));
- }
- QString edge;
- switch (m_edge) {
- case Qt::AnchorLeft:
- edge = QLatin1String("Left");
- break;
- case Qt::AnchorHorizontalCenter:
- edge = QLatin1String("HorizontalCenter");
- break;
- case Qt::AnchorRight:
- edge = QLatin1String("Right");
- break;
- case Qt::AnchorTop:
- edge = QLatin1String("Top");
- break;
- case Qt::AnchorVerticalCenter:
- edge = QLatin1String("VerticalCenter");
- break;
- case Qt::AnchorBottom:
- edge = QLatin1String("Bottom");
- break;
- default:
- edge = QLatin1String("None");
- break;
- }
- QString itemName;
- if (m_item->isLayout()) {
- itemName = QLatin1String("layout");
- } else {
- if (QGraphicsItem *item = m_item->graphicsItem()) {
- itemName = item->data(0).toString();
- }
- }
- edge.insert(0, QLatin1String("%1_"));
- return edge.arg(itemName);
-}
-#endif
-
-/*!
- \internal
-
- Representation of a valid path for a given vertex in the graph.
- In this struct, "positives" is the set of anchors that have been
- traversed in the forward direction, while "negatives" is the set
- with the ones walked backwards.
-
- This paths are compared against each other to produce LP Constraints,
- the exact order in which the anchors were traversed is not relevant.
-*/
-class GraphPath
-{
-public:
- GraphPath() {}
-
- QSimplexConstraint *constraint(const GraphPath &path) const;
-#ifdef QT_DEBUG
- QString toString() const;
-#endif
- QSet<AnchorData *> positives;
- QSet<AnchorData *> negatives;
-};
-
-class QGraphicsAnchorLayoutPrivate;
-/*!
- \internal
-*/
-class QGraphicsAnchorPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsAnchor)
-
-public:
- explicit QGraphicsAnchorPrivate(int version = QObjectPrivateVersion);
- ~QGraphicsAnchorPrivate();
-
- void setSpacing(qreal value);
- void unsetSpacing();
- qreal spacing() const;
-
- void setSizePolicy(QSizePolicy::Policy policy);
-
- QGraphicsAnchorLayoutPrivate *layoutPrivate;
- AnchorData *data;
-
- // Size information for user controlled anchor
- QSizePolicy::Policy sizePolicy;
- qreal preferredSize;
-
- uint hasSize : 1; // if false, get size from style.
-};
-
-
-
-
-/*!
- \internal
-
- QGraphicsAnchorLayout private methods and attributes.
-*/
-class Q_AUTOTEST_EXPORT QGraphicsAnchorLayoutPrivate : public QGraphicsLayoutPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsAnchorLayout)
-
-public:
- // When the layout geometry is different from its Minimum, Preferred
- // or Maximum values, interpolation is used to calculate the geometries
- // of the items.
- //
- // Interval represents which interpolation interval are we operating in.
- enum Interval {
- MinimumToMinPreferred = 0,
- MinPreferredToPreferred,
- PreferredToMaxPreferred,
- MaxPreferredToMaximum
- };
-
- // Several structures internal to the layout are duplicated to handle
- // both Horizontal and Vertical restrictions.
- //
- // Orientation is used to reference the right structure in each context
- enum Orientation {
- Horizontal = 0,
- Vertical,
- NOrientations
- };
-
- QGraphicsAnchorLayoutPrivate();
-
- static QGraphicsAnchorLayoutPrivate *get(QGraphicsAnchorLayout *q)
- {
- return q ? q->d_func() : 0;
- }
-
- static Qt::AnchorPoint oppositeEdge(
- Qt::AnchorPoint edge);
-
- static Orientation edgeOrientation(Qt::AnchorPoint edge);
-
- static Qt::AnchorPoint pickEdge(Qt::AnchorPoint edge, Orientation orientation)
- {
- if (orientation == Vertical && int(edge) <= 2)
- return (Qt::AnchorPoint)(edge + 3);
- else if (orientation == Horizontal && int(edge) >= 3) {
- return (Qt::AnchorPoint)(edge - 3);
- }
- return edge;
- }
-
- // Init methods
- void createLayoutEdges();
- void deleteLayoutEdges();
- void createItemEdges(QGraphicsLayoutItem *item);
- void createCenterAnchors(QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge);
- void removeCenterAnchors(QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge, bool substitute = true);
- void removeCenterConstraints(QGraphicsLayoutItem *item, Orientation orientation);
-
- QGraphicsAnchor *acquireGraphicsAnchor(AnchorData *data)
- {
- Q_Q(QGraphicsAnchorLayout);
- if (!data->graphicsAnchor) {
- data->graphicsAnchor = new QGraphicsAnchor(q);
- data->graphicsAnchor->d_func()->data = data;
- }
- return data->graphicsAnchor;
- }
-
- // function used by the 4 API functions
- QGraphicsAnchor *addAnchor(QGraphicsLayoutItem *firstItem,
- Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem,
- Qt::AnchorPoint secondEdge,
- qreal *spacing = 0);
-
- // Helper for Anchor Manipulation methods
- void addAnchor_helper(QGraphicsLayoutItem *firstItem,
- Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem,
- Qt::AnchorPoint secondEdge,
- AnchorData *data);
-
- QGraphicsAnchor *getAnchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge,
- QGraphicsLayoutItem *secondItem, Qt::AnchorPoint secondEdge);
-
- void removeAnchor(AnchorVertex *firstVertex, AnchorVertex *secondVertex);
- void removeAnchor_helper(AnchorVertex *v1, AnchorVertex *v2);
-
- void removeAnchors(QGraphicsLayoutItem *item);
-
- void removeVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge);
-
- void correctEdgeDirection(QGraphicsLayoutItem *&firstItem,
- Qt::AnchorPoint &firstEdge,
- QGraphicsLayoutItem *&secondItem,
- Qt::AnchorPoint &secondEdge);
-
- QLayoutStyleInfo &styleInfo() const;
-
- AnchorData *addAnchorMaybeParallel(AnchorData *newAnchor, bool *feasible);
-
- // Activation
- void calculateGraphs();
- void calculateGraphs(Orientation orientation);
-
- // Simplification
- bool simplifyGraph(Orientation orientation);
- bool simplifyVertices(Orientation orientation);
- bool simplifyGraphIteration(Orientation orientation, bool *feasible);
-
- bool replaceVertex(Orientation orientation, AnchorVertex *oldV,
- AnchorVertex *newV, const QList<AnchorData *> &edges);
-
-
- void restoreSimplifiedGraph(Orientation orientation);
- void restoreSimplifiedAnchor(AnchorData *edge);
- void restoreSimplifiedConstraints(ParallelAnchorData *parallel);
- void restoreVertices(Orientation orientation);
-
- bool calculateTrunk(Orientation orientation, const GraphPath &trunkPath,
- const QList<QSimplexConstraint *> &constraints,
- const QList<AnchorData *> &variables);
- bool calculateNonTrunk(const QList<QSimplexConstraint *> &constraints,
- const QList<AnchorData *> &variables);
-
- // Support functions for calculateGraph()
- void refreshAllSizeHints(Orientation orientation);
- void findPaths(Orientation orientation);
- void constraintsFromPaths(Orientation orientation);
- void updateAnchorSizes(Orientation orientation);
- QList<QSimplexConstraint *> constraintsFromSizeHints(const QList<AnchorData *> &anchors);
- QList<QList<QSimplexConstraint *> > getGraphParts(Orientation orientation);
- void identifyFloatItems(const QSet<AnchorData *> &visited, Orientation orientation);
- void identifyNonFloatItems_helper(const AnchorData *ad, QSet<QGraphicsLayoutItem *> *nonFloatingItemsIdentifiedSoFar);
-
- inline AnchorVertex *internalVertex(const QPair<QGraphicsLayoutItem*, Qt::AnchorPoint> &itemEdge) const
- {
- return m_vertexList.value(itemEdge).first;
- }
-
- inline AnchorVertex *internalVertex(const QGraphicsLayoutItem *item, Qt::AnchorPoint edge) const
- {
- return internalVertex(qMakePair(const_cast<QGraphicsLayoutItem *>(item), edge));
- }
-
- inline void changeLayoutVertex(Orientation orientation, AnchorVertex *oldV, AnchorVertex *newV)
- {
- if (layoutFirstVertex[orientation] == oldV)
- layoutFirstVertex[orientation] = newV;
- else if (layoutCentralVertex[orientation] == oldV)
- layoutCentralVertex[orientation] = newV;
- else if (layoutLastVertex[orientation] == oldV)
- layoutLastVertex[orientation] = newV;
- }
-
-
- AnchorVertex *addInternalVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge);
- void removeInternalVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge);
-
- // Geometry interpolation methods
- void setItemsGeometries(const QRectF &geom);
-
- void calculateVertexPositions(Orientation orientation);
- void setupEdgesInterpolation(Orientation orientation);
- void interpolateEdge(AnchorVertex *base, AnchorData *edge);
-
- // Linear Programming solver methods
- bool solveMinMax(const QList<QSimplexConstraint *> &constraints,
- GraphPath path, qreal *min, qreal *max);
- bool solvePreferred(const QList<QSimplexConstraint *> &constraints,
- const QList<AnchorData *> &variables);
- bool hasConflicts() const;
-
-#ifdef QT_DEBUG
- void dumpGraph(const QString &name = QString());
-#endif
-
-
- qreal spacings[NOrientations];
- // Size hints from simplex engine
- qreal sizeHints[2][3];
-
- // Items
- QVector<QGraphicsLayoutItem *> items;
-
- // Mapping between high level anchorage points (Item, Edge) to low level
- // ones (Graph Vertices)
-
- QHash<QPair<QGraphicsLayoutItem*, Qt::AnchorPoint>, QPair<AnchorVertex *, int> > m_vertexList;
-
- // Internal graph of anchorage points and anchors, for both orientations
- Graph<AnchorVertex, AnchorData> graph[2];
-
- AnchorVertex *layoutFirstVertex[2];
- AnchorVertex *layoutCentralVertex[2];
- AnchorVertex *layoutLastVertex[2];
-
- // Combined anchors in order of creation
- QList<AnchorVertexPair *> simplifiedVertices[2];
- QList<AnchorData *> anchorsFromSimplifiedVertices[2];
-
- // Graph paths and constraints, for both orientations
- QMultiHash<AnchorVertex *, GraphPath> graphPaths[2];
- QList<QSimplexConstraint *> constraints[2];
- QList<QSimplexConstraint *> itemCenterConstraints[2];
-
- // The interpolation interval and progress based on the current size
- // as well as the key values (minimum, preferred and maximum)
- Interval interpolationInterval[2];
- qreal interpolationProgress[2];
-
- bool graphHasConflicts[2];
- QSet<QGraphicsLayoutItem *> m_floatItems[2];
-
-#if defined(QT_DEBUG) || defined(Q_AUTOTEST_EXPORT)
- bool lastCalculationUsedSimplex[2];
-#endif
-
- uint calculateGraphCacheDirty : 1;
- mutable uint styleInfoDirty : 1;
- mutable QLayoutStyleInfo cachedStyleInfo;
-
- friend class QGraphicsAnchorPrivate;
-};
-
-QT_END_NAMESPACE
-#endif //QT_NO_GRAPHICSVIEW
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsgridlayout.cpp b/src/gui/graphicsview/qgraphicsgridlayout.cpp
deleted file mode 100644
index f6eec1d405..0000000000
--- a/src/gui/graphicsview/qgraphicsgridlayout.cpp
+++ /dev/null
@@ -1,690 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsGridLayout
- \brief The QGraphicsGridLayout class provides a grid layout for managing
- widgets in Graphics View.
- \since 4.4
-
- \ingroup graphicsview-api
-
- The most common way to use QGraphicsGridLayout is to construct an object
- on the heap with no parent, add widgets and layouts by calling addItem(),
- and finally assign the layout to a widget by calling
- QGraphicsWidget::setLayout(). QGraphicsGridLayout automatically computes
- the dimensions of the grid as you add items.
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp 0
-
- The layout takes ownership of the items. In some cases when the layout
- item also inherits from QGraphicsItem (such as QGraphicsWidget) there will be a
- ambiguity in ownership because the layout item belongs to two ownership hierarchies.
- See the documentation of QGraphicsLayoutItem::setOwnedByLayout() how to handle
- this.
- You can access each item in the layout by calling count() and itemAt(). Calling
- removeAt() will remove an item from the layout, without
- destroying it.
-
- \section1 Size Hints and Size Policies in QGraphicsGridLayout
-
- QGraphicsGridLayout respects each item's size hints and size policies,
- and when a cell in the grid has more space than the items can fill, each item
- is arranged according to the layout's alignment for that item. You can set
- an alignment for each item by calling setAlignment(), and check the
- alignment for any item by calling alignment(). You can also set the alignment
- for an entire row or column by calling setRowAlignment() and setColumnAlignment()
- respectively. By default, items are aligned to the top left.
-
-
- \sa QGraphicsLinearLayout, QGraphicsWidget
-*/
-
-#include "qglobal.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qapplication.h"
-#include "qwidget.h"
-#include "qgraphicslayout_p.h"
-#include "qgraphicslayoutitem.h"
-#include "qgraphicsgridlayout.h"
-#include "qgraphicswidget.h"
-#include "qgridlayoutengine_p.h"
-#include <QtCore/qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsGridLayoutPrivate : public QGraphicsLayoutPrivate
-{
-public:
- QGraphicsGridLayoutPrivate() { }
- QLayoutStyleInfo styleInfo() const;
-
- QGridLayoutEngine engine;
-#ifdef QT_DEBUG
- void dump(int indent) const;
-#endif
-};
-
-Q_GLOBAL_STATIC(QWidget, globalStyleInfoWidget);
-
-QLayoutStyleInfo QGraphicsGridLayoutPrivate::styleInfo() const
-{
- QGraphicsItem *item = parentItem();
- QStyle *style = (item && item->isWidget()) ? static_cast<QGraphicsWidget*>(item)->style() : QApplication::style();
- return QLayoutStyleInfo(style, globalStyleInfoWidget());
-}
-
-/*!
- Constructs a QGraphicsGridLayout instance. \a parent is passed to
- QGraphicsLayout's constructor.
-*/
-QGraphicsGridLayout::QGraphicsGridLayout(QGraphicsLayoutItem *parent)
- : QGraphicsLayout(*new QGraphicsGridLayoutPrivate(), parent)
-{
-}
-
-/*!
- Destroys the QGraphicsGridLayout object.
-*/
-QGraphicsGridLayout::~QGraphicsGridLayout()
-{
- for (int i = count() - 1; i >= 0; --i) {
- QGraphicsLayoutItem *item = itemAt(i);
- // The following lines can be removed, but this removes the item
- // from the layout more efficiently than the implementation of
- // ~QGraphicsLayoutItem.
- removeAt(i);
- if (item) {
- item->setParentLayoutItem(0);
- if (item->ownedByLayout())
- delete item;
- }
- }
-}
-
-/*!
- Adds \a item to the grid on \a row and \a column. You can specify a
- \a rowSpan and \a columnSpan and an optional \a alignment.
-*/
-void QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column,
- int rowSpan, int columnSpan, Qt::Alignment alignment)
-{
- Q_D(QGraphicsGridLayout);
- if (row < 0 || column < 0) {
- qWarning("QGraphicsGridLayout::addItem: invalid row/column: %d",
- row < 0 ? row : column);
- return;
- }
- if (columnSpan < 1 || rowSpan < 1) {
- qWarning("QGraphicsGridLayout::addItem: invalid row span/column span: %d",
- rowSpan < 1 ? rowSpan : columnSpan);
- return;
- }
- if (!item) {
- qWarning("QGraphicsGridLayout::addItem: cannot add null item");
- return;
- }
- if (item == this) {
- qWarning("QGraphicsGridLayout::addItem: cannot insert itself");
- return;
- }
-
- d->addChildLayoutItem(item);
-
- new QGridLayoutItem(&d->engine, item, row, column, rowSpan, columnSpan, alignment);
- invalidate();
-}
-
-/*!
- \fn QGraphicsGridLayout::addItem(QGraphicsLayoutItem *item, int row, int column, Qt::Alignment alignment = 0)
-
- Adds \a item to the grid on \a row and \a column. You can specify
- an optional \a alignment for \a item.
-*/
-
-/*!
- Sets the default horizontal spacing for the grid layout to \a spacing.
-*/
-void QGraphicsGridLayout::setHorizontalSpacing(qreal spacing)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setSpacing(spacing, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the default horizontal spacing for the grid layout.
-*/
-qreal QGraphicsGridLayout::horizontalSpacing() const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.spacing(d->styleInfo(), Qt::Horizontal);
-}
-
-/*!
- Sets the default vertical spacing for the grid layout to \a spacing.
-*/
-void QGraphicsGridLayout::setVerticalSpacing(qreal spacing)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setSpacing(spacing, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the default vertical spacing for the grid layout.
-*/
-qreal QGraphicsGridLayout::verticalSpacing() const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.spacing(d->styleInfo(), Qt::Vertical);
-}
-
-/*!
- Sets the grid layout's default spacing, both vertical and
- horizontal, to \a spacing.
-
- \sa rowSpacing(), columnSpacing()
-*/
-void QGraphicsGridLayout::setSpacing(qreal spacing)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
- invalidate();
-}
-
-/*!
- Sets the spacing for \a row to \a spacing.
-*/
-void QGraphicsGridLayout::setRowSpacing(int row, qreal spacing)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSpacing(row, spacing, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the row spacing for \a row.
-*/
-qreal QGraphicsGridLayout::rowSpacing(int row) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSpacing(row, Qt::Vertical);
-}
-
-/*!
- Sets the spacing for \a column to \a spacing.
-*/
-void QGraphicsGridLayout::setColumnSpacing(int column, qreal spacing)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSpacing(column, spacing, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the column spacing for \a column.
-*/
-qreal QGraphicsGridLayout::columnSpacing(int column) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSpacing(column, Qt::Horizontal);
-}
-
-/*!
- Sets the stretch factor for \a row to \a stretch.
-*/
-void QGraphicsGridLayout::setRowStretchFactor(int row, int stretch)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowStretchFactor(row, stretch, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the stretch factor for \a row.
-*/
-int QGraphicsGridLayout::rowStretchFactor(int row) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowStretchFactor(row, Qt::Vertical);
-}
-
-/*!
- Sets the stretch factor for \a column to \a stretch.
-*/
-void QGraphicsGridLayout::setColumnStretchFactor(int column, int stretch)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowStretchFactor(column, stretch, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the stretch factor for \a column.
-*/
-int QGraphicsGridLayout::columnStretchFactor(int column) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowStretchFactor(column, Qt::Horizontal);
-}
-
-/*!
- Sets the minimum height for row, \a row, to \a height.
-*/
-void QGraphicsGridLayout::setRowMinimumHeight(int row, qreal height)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::MinimumSize, row, height, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the minimum height for row, \a row.
-*/
-qreal QGraphicsGridLayout::rowMinimumHeight(int row) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSizeHint(Qt::MinimumSize, row, Qt::Vertical);
-}
-
-/*!
- Sets the preferred height for row, \a row, to \a height.
-*/
-void QGraphicsGridLayout::setRowPreferredHeight(int row, qreal height)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::PreferredSize, row, height, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the preferred height for row, \a row.
-*/
-qreal QGraphicsGridLayout::rowPreferredHeight(int row) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSizeHint(Qt::PreferredSize, row, Qt::Vertical);
-}
-
-/*!
- Sets the maximum height for row, \a row, to \a height.
-*/
-void QGraphicsGridLayout::setRowMaximumHeight(int row, qreal height)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::MaximumSize, row, height, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the maximum height for row, \a row.
-*/
-qreal QGraphicsGridLayout::rowMaximumHeight(int row) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSizeHint(Qt::MaximumSize, row, Qt::Vertical);
-}
-
-/*!
- Sets the fixed height for row, \a row, to \a height.
-*/
-void QGraphicsGridLayout::setRowFixedHeight(int row, qreal height)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::MinimumSize, row, height, Qt::Vertical);
- d->engine.setRowSizeHint(Qt::MaximumSize, row, height, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Sets the minimum width for \a column to \a width.
-*/
-void QGraphicsGridLayout::setColumnMinimumWidth(int column, qreal width)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::MinimumSize, column, width, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the minimum width for \a column.
-*/
-qreal QGraphicsGridLayout::columnMinimumWidth(int column) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSizeHint(Qt::MinimumSize, column, Qt::Horizontal);
-}
-
-/*!
- Sets the preferred width for \a column to \a width.
-*/
-void QGraphicsGridLayout::setColumnPreferredWidth(int column, qreal width)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::PreferredSize, column, width, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the preferred width for \a column.
-*/
-qreal QGraphicsGridLayout::columnPreferredWidth(int column) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSizeHint(Qt::PreferredSize, column, Qt::Horizontal);
-}
-
-/*!
- Sets the maximum width of \a column to \a width.
-*/
-void QGraphicsGridLayout::setColumnMaximumWidth(int column, qreal width)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::MaximumSize, column, width, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the maximum width for \a column.
-*/
-qreal QGraphicsGridLayout::columnMaximumWidth(int column) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowSizeHint(Qt::MaximumSize, column, Qt::Horizontal);
-}
-
-/*!
- Sets the fixed width of \a column to \a width.
-*/
-void QGraphicsGridLayout::setColumnFixedWidth(int column, qreal width)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowSizeHint(Qt::MinimumSize, column, width, Qt::Horizontal);
- d->engine.setRowSizeHint(Qt::MaximumSize, column, width, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Sets the alignment of \a row to \a alignment.
-*/
-void QGraphicsGridLayout::setRowAlignment(int row, Qt::Alignment alignment)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowAlignment(row, alignment, Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the alignment of \a row.
-*/
-Qt::Alignment QGraphicsGridLayout::rowAlignment(int row) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowAlignment(row, Qt::Vertical);
-}
-
-/*!
- Sets the alignment for \a column to \a alignment.
-*/
-void QGraphicsGridLayout::setColumnAlignment(int column, Qt::Alignment alignment)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setRowAlignment(column, alignment, Qt::Horizontal);
- invalidate();
-}
-
-/*!
- Returns the alignment for \a column.
-*/
-Qt::Alignment QGraphicsGridLayout::columnAlignment(int column) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.rowAlignment(column, Qt::Horizontal);
-}
-
-/*!
- Sets the alignment for \a item to \a alignment.
-*/
-void QGraphicsGridLayout::setAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment)
-{
- Q_D(QGraphicsGridLayout);
- d->engine.setAlignment(item, alignment);
- invalidate();
-}
-
-/*!
- Returns the alignment for \a item.
-*/
-Qt::Alignment QGraphicsGridLayout::alignment(QGraphicsLayoutItem *item) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.alignment(item);
-}
-
-/*!
- Returns the number of rows in the grid layout. This is always one more
- than the index of the last row that is occupied by a layout item (empty
- rows are counted except for those at the end).
-*/
-int QGraphicsGridLayout::rowCount() const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.effectiveLastRow(Qt::Vertical) + 1;
-}
-
-/*!
- Returns the number of columns in the grid layout. This is always one more
- than the index of the last column that is occupied by a layout item (empty
- columns are counted except for those at the end).
-*/
-int QGraphicsGridLayout::columnCount() const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.effectiveLastRow(Qt::Horizontal) + 1;
-}
-
-/*!
- Returns a pointer to the layout item at (\a row, \a column).
-*/
-QGraphicsLayoutItem *QGraphicsGridLayout::itemAt(int row, int column) const
-{
- Q_D(const QGraphicsGridLayout);
- if (row < 0 || row >= rowCount() || column < 0 || column >= columnCount()) {
- qWarning("QGraphicsGridLayout::itemAt: invalid row, column %d, %d", row, column);
- return 0;
- }
- if (QGridLayoutItem *item = d->engine.itemAt(row, column))
- return item->layoutItem();
- return 0;
-}
-
-/*!
- Returns the number of layout items in this grid layout.
-*/
-int QGraphicsGridLayout::count() const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.itemCount();
-}
-
-/*!
- Returns the layout item at \a index, or 0 if there is no layout item at
- this index.
-*/
-QGraphicsLayoutItem *QGraphicsGridLayout::itemAt(int index) const
-{
- Q_D(const QGraphicsGridLayout);
- if (index < 0 || index >= d->engine.itemCount()) {
- qWarning("QGraphicsGridLayout::itemAt: invalid index %d", index);
- return 0;
- }
- QGraphicsLayoutItem *item = 0;
- if (QGridLayoutItem *gridItem = d->engine.itemAt(index))
- item = gridItem->layoutItem();
- return item;
-}
-
-/*!
- Removes the layout item at \a index without destroying it. Ownership of
- the item is transferred to the caller.
-
- \sa addItem()
-*/
-void QGraphicsGridLayout::removeAt(int index)
-{
- Q_D(QGraphicsGridLayout);
- if (index < 0 || index >= d->engine.itemCount()) {
- qWarning("QGraphicsGridLayout::removeAt: invalid index %d", index);
- return;
- }
- if (QGridLayoutItem *gridItem = d->engine.itemAt(index)) {
- if (QGraphicsLayoutItem *layoutItem = gridItem->layoutItem())
- layoutItem->setParentLayoutItem(0);
- d->engine.removeItem(gridItem);
-
- // recalculate rowInfo.count if we remove an item that is on the right/bottommost row
- for (int j = 0; j < NOrientations; ++j) {
- // 0: Hor, 1: Ver
- const Qt::Orientation orient = (j == 0 ? Qt::Horizontal : Qt::Vertical);
- const int oldCount = d->engine.rowCount(orient);
- if (gridItem->lastRow(orient) == oldCount - 1) {
- const int newCount = d->engine.effectiveLastRow(orient) + 1;
- d->engine.removeRows(newCount, oldCount - newCount, orient);
- }
- }
-
- delete gridItem;
- invalidate();
- }
-}
-
-/*!
- Removes the layout item \a item without destroying it.
- Ownership of the item is transferred to the caller.
-
- \sa addItem()
-*/
-void QGraphicsGridLayout::removeItem(QGraphicsLayoutItem *item)
-{
- Q_D(QGraphicsGridLayout);
- int index = d->engine.indexOf(item);
- removeAt(index);
-}
-/*!
- \reimp
-*/
-void QGraphicsGridLayout::invalidate()
-{
- Q_D(QGraphicsGridLayout);
- d->engine.invalidate();
- QGraphicsLayout::invalidate();
-}
-
-#ifdef QT_DEBUG
-void QGraphicsGridLayoutPrivate::dump(int indent) const
-{
- if (qt_graphicsLayoutDebug()) {
- engine.dump(indent + 1);
- }
-}
-#endif
-
-/*!
- Sets the bounding geometry of the grid layout to \a rect.
-*/
-void QGraphicsGridLayout::setGeometry(const QRectF &rect)
-{
- Q_D(QGraphicsGridLayout);
- QGraphicsLayout::setGeometry(rect);
- QRectF effectiveRect = geometry();
- qreal left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- Qt::LayoutDirection visualDir = d->visualDirection();
- d->engine.setVisualDirection(visualDir);
- if (visualDir == Qt::RightToLeft)
- qSwap(left, right);
- effectiveRect.adjust(+left, +top, -right, -bottom);
- d->engine.setGeometries(d->styleInfo(), effectiveRect);
-#ifdef QT_DEBUG
- if (qt_graphicsLayoutDebug()) {
- static int counter = 0;
- qDebug("==== BEGIN DUMP OF QGraphicsGridLayout (%d)====", counter++);
- d->dump(1);
- qDebug("==== END DUMP OF QGraphicsGridLayout ====");
- }
-#endif
-}
-
-/*!
- \reimp
-*/
-QSizeF QGraphicsGridLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- Q_D(const QGraphicsGridLayout);
- qreal left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- const QSizeF extraMargins(left + right, top + bottom);
- return d->engine.sizeHint(d->styleInfo(), which , constraint - extraMargins) + extraMargins;
-}
-
-
-#if 0
-// ### kill? (implement and kill?)
-QRect QGraphicsGridLayout::cellRect(int row, int column, int rowSpan, int columnSpan) const
-{
- Q_D(const QGraphicsGridLayout);
- return QRect();
-// return d->engine.cellRect(parentLayoutable(), contentsGeometry(), row, column, rowSpan, columnSpan);
-}
-
-QSizePolicy::ControlTypes QGraphicsGridLayout::controlTypes(LayoutSide side) const
-{
- Q_D(const QGraphicsGridLayout);
- return d->engine.controlTypes(side);
-}
-#endif
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsgridlayout.h b/src/gui/graphicsview/qgraphicsgridlayout.h
deleted file mode 100644
index f493eb6153..0000000000
--- a/src/gui/graphicsview/qgraphicsgridlayout.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSGRIDLAYOUT_H
-#define QGRAPHICSGRIDLAYOUT_H
-
-#include <QtGui/qgraphicsitem.h>
-#include <QtGui/qgraphicslayout.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsGridLayoutPrivate;
-
-class Q_GUI_EXPORT QGraphicsGridLayout : public QGraphicsLayout
-{
-public:
- QGraphicsGridLayout(QGraphicsLayoutItem *parent = 0);
- virtual ~QGraphicsGridLayout();
-
- void addItem(QGraphicsLayoutItem *item, int row, int column, int rowSpan, int columnSpan,
- Qt::Alignment alignment = 0);
- inline void addItem(QGraphicsLayoutItem *item, int row, int column, Qt::Alignment alignment = 0);
-
- void setHorizontalSpacing(qreal spacing);
- qreal horizontalSpacing() const;
- void setVerticalSpacing(qreal spacing);
- qreal verticalSpacing() const;
- void setSpacing(qreal spacing);
-
- void setRowSpacing(int row, qreal spacing);
- qreal rowSpacing(int row) const;
- void setColumnSpacing(int column, qreal spacing);
- qreal columnSpacing(int column) const;
-
- void setRowStretchFactor(int row, int stretch);
- int rowStretchFactor(int row) const;
- void setColumnStretchFactor(int column, int stretch);
- int columnStretchFactor(int column) const;
-
- void setRowMinimumHeight(int row, qreal height);
- qreal rowMinimumHeight(int row) const;
- void setRowPreferredHeight(int row, qreal height);
- qreal rowPreferredHeight(int row) const;
- void setRowMaximumHeight(int row, qreal height);
- qreal rowMaximumHeight(int row) const;
- void setRowFixedHeight(int row, qreal height);
-
- void setColumnMinimumWidth(int column, qreal width);
- qreal columnMinimumWidth(int column) const;
- void setColumnPreferredWidth(int column, qreal width);
- qreal columnPreferredWidth(int column) const;
- void setColumnMaximumWidth(int column, qreal width);
- qreal columnMaximumWidth(int column) const;
- void setColumnFixedWidth(int column, qreal width);
-
- void setRowAlignment(int row, Qt::Alignment alignment);
- Qt::Alignment rowAlignment(int row) const;
- void setColumnAlignment(int column, Qt::Alignment alignment);
- Qt::Alignment columnAlignment(int column) const;
-
- void setAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment);
- Qt::Alignment alignment(QGraphicsLayoutItem *item) const;
-
- int rowCount() const;
- int columnCount() const;
-
- QGraphicsLayoutItem *itemAt(int row, int column) const;
-
- // inherited from QGraphicsLayout
- int count() const;
- QGraphicsLayoutItem *itemAt(int index) const;
- void removeAt(int index);
- void removeItem(QGraphicsLayoutItem *item);
-
- void invalidate();
-
- // inherited from QGraphicsLayoutItem
- void setGeometry(const QRectF &rect);
- QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
-
- // ####
- //QRect cellRect(int row, int column, int rowSpan = 1, int columnSpan = 1) const;
- //QSizePolicy::ControlTypes controlTypes(LayoutSide side) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsGridLayout)
- Q_DECLARE_PRIVATE(QGraphicsGridLayout)
-};
-
-inline void QGraphicsGridLayout::addItem(QGraphicsLayoutItem *aitem, int arow, int acolumn, Qt::Alignment aalignment)
-{ addItem(aitem, arow, acolumn, 1, 1, aalignment); }
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
-
diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp
deleted file mode 100644
index e67fe82045..0000000000
--- a/src/gui/graphicsview/qgraphicsitem.cpp
+++ /dev/null
@@ -1,11597 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsItem
- \brief The QGraphicsItem class is the base class for all graphical
- items in a QGraphicsScene.
- \since 4.2
-
- \ingroup graphicsview-api
-
- It provides a light-weight foundation for writing your own custom items.
- This includes defining the item's geometry, collision detection, its
- painting implementation and item interaction through its event handlers.
- QGraphicsItem is part of the \l{Graphics View Framework}
-
- \image graphicsview-items.png
-
- For convenience, Qt provides a set of standard graphics items for the most
- common shapes. These are:
-
- \list
- \o QGraphicsEllipseItem provides an ellipse item
- \o QGraphicsLineItem provides a line item
- \o QGraphicsPathItem provides an arbitrary path item
- \o QGraphicsPixmapItem provides a pixmap item
- \o QGraphicsPolygonItem provides a polygon item
- \o QGraphicsRectItem provides a rectangular item
- \o QGraphicsSimpleTextItem provides a simple text label item
- \o QGraphicsTextItem provides an advanced text browser item
- \endlist
-
- All of an item's geometric information is based on its local coordinate
- system. The item's position, pos(), is the only function that does not
- operate in local coordinates, as it returns a position in parent
- coordinates. \l {The Graphics View Coordinate System} describes the coordinate
- system in detail.
-
- You can set whether an item should be visible (i.e., drawn, and accepting
- events), by calling setVisible(). Hiding an item will also hide its
- children. Similarly, you can enable or disable an item by calling
- setEnabled(). If you disable an item, all its children will also be
- disabled. By default, items are both visible and enabled. To toggle
- whether an item is selected or not, first enable selection by setting
- the ItemIsSelectable flag, and then call setSelected(). Normally,
- selection is toggled by the scene, as a result of user interaction.
-
- To write your own graphics item, you first create a subclass of
- QGraphicsItem, and then start by implementing its two pure virtual public
- functions: boundingRect(), which returns an estimate of the area painted
- by the item, and paint(), which implements the actual painting. For
- example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 0
-
- The boundingRect() function has many different purposes.
- QGraphicsScene bases its item index on boundingRect(), and
- QGraphicsView uses it both for culling invisible items, and for
- determining the area that needs to be recomposed when drawing
- overlapping items. In addition, QGraphicsItem's collision
- detection mechanisms use boundingRect() to provide an efficient
- cut-off. The fine grained collision algorithm in
- collidesWithItem() is based on calling shape(), which returns an
- accurate outline of the item's shape as a QPainterPath.
-
- QGraphicsScene expects all items boundingRect() and shape() to
- remain unchanged unless it is notified. If you want to change an
- item's geometry in any way, you must first call
- prepareGeometryChange() to allow QGraphicsScene to update its
- bookkeeping.
-
- Collision detection can be done in two ways:
-
- \list 1
-
- \o Reimplement shape() to return an accurate shape for your item,
- and rely on the default implementation of collidesWithItem() to do
- shape-shape intersection. This can be rather expensive if the
- shapes are complex.
-
- \o Reimplement collidesWithItem() to provide your own custom item
- and shape collision algorithm.
-
- \endlist
-
- The contains() function can be called to determine whether the item \e
- contains a point or not. This function can also be reimplemented by the
- item. The default behavior of contains() is based on calling shape().
-
- Items can contain other items, and also be contained by other items. All
- items can have a parent item and a list of children. Unless the item has
- no parent, its position is in \e parent coordinates (i.e., the parent's
- local coordinates). Parent items propagate both their position and their
- transformation to all children.
-
- \img graphicsview-parentchild.png
-
- \target Transformations
- \section1 Transformations
-
- QGraphicsItem supports projective transformations in addition to its base
- position, pos(). There are several ways to change an item's transformation.
- For simple transformations, you can call either of the convenience
- functions setRotation() or setScale(), or you can pass any transformation
- matrix to setTransform(). For advanced transformation control you also have
- the option of setting several combined transformations by calling
- setTransformations().
-
- Item transformations accumulate from parent to child, so if both a parent
- and child item are rotated 90 degrees, the child's total transformation
- will be 180 degrees. Similarly, if the item's parent is scaled to 2x its
- original size, its children will also be twice as large. An item's
- transformation does not affect its own local geometry; all geometry
- functions (e.g., contains(), update(), and all the mapping functions) still
- operate in local coordinates. For convenience, QGraphicsItem provides the
- functions sceneTransform(), which returns the item's total transformation
- matrix (including its position and all parents' positions and
- transformations), and scenePos(), which returns its position in scene
- coordinates. To reset an item's matrix, call resetTransform().
-
- Certain transformation operations produce a different outcome depending on
- the order in which they are applied. For example, if you scale an
- transform, and then rotate it, you may get a different result than if the
- transform was rotated first. However, the order you set the transformation
- properties on QGraphicsItem does not affect the resulting transformation;
- QGraphicsItem always applies the properties in a fixed, defined order:
-
- \list
- \o The item's base transform is applied (transform())
- \o The item's transformations list is applied in order (transformations())
- \o The item is rotated relative to its transform origin point (rotation(), transformOriginPoint())
- \o The item is scaled relative to its transform origin point (scale(), transformOriginPoint())
- \endlist
-
- \section1 Painting
-
- The paint() function is called by QGraphicsView to paint the item's
- contents. The item has no background or default fill of its own; whatever
- is behind the item will shine through all areas that are not explicitly
- painted in this function. You can call update() to schedule a repaint,
- optionally passing the rectangle that needs a repaint. Depending on
- whether or not the item is visible in a view, the item may or may not be
- repainted; there is no equivalent to QWidget::repaint() in QGraphicsItem.
-
- Items are painted by the view, starting with the parent items and then
- drawing children, in ascending stacking order. You can set an item's
- stacking order by calling setZValue(), and test it by calling
- zValue(), where items with low z-values are painted before items with
- high z-values. Stacking order applies to sibling items; parents are always
- drawn before their children.
-
- \section1 Sorting
-
- All items are drawn in a defined, stable order, and this same order decides
- which items will receive mouse input first when you click on the scene.
- Normally you don't have to worry about sorting, as the items follow a
- "natural order", following the logical structure of the scene.
-
- An item's children are stacked on top of the parent, and sibling items are
- stacked by insertion order (i.e., in the same order that they were either
- added to the scene, or added to the same parent). If you add item A, and
- then B, then B will be on top of A. If you then add C, the items' stacking
- order will be A, then B, then C.
-
- \image graphicsview-zorder.png
-
- This example shows the stacking order of all limbs of the robot from the
- \l{graphicsview/dragdroprobot}{Drag and Drop Robot} example. The torso is
- the root item (all other items are children or descendants of the torso),
- so it is drawn first. Next, the head is drawn, as it is the first item in
- the torso's list of children. Then the upper left arm is drawn. As the
- lower arm is a child of the upper arm, the lower arm is then drawn,
- followed by the upper arm's next sibling, which is the upper right arm, and
- so on.
-
- For advanced users, there are ways to alter how your items are sorted:
-
- \list
- \o You can call setZValue() on an item to explicitly stack it on top of, or
- under, other sibling items. The default Z value for an item is 0. Items
- with the same Z value are stacked by insertion order.
-
- \o You can call stackBefore() to reorder the list of children. This will
- directly modify the insertion order.
-
- \o You can set the ItemStacksBehindParent flag to stack a child item behind
- its parent.
- \endlist
-
- The stacking order of two sibling items also counts for each item's
- children and descendant items. So if one item is on top of another, then
- all its children will also be on top of all the other item's children as
- well.
-
- \section1 Events
-
- QGraphicsItem receives events from QGraphicsScene through the virtual
- function sceneEvent(). This function distributes the most common events
- to a set of convenience event handlers:
-
- \list
- \o contextMenuEvent() handles context menu events
- \o focusInEvent() and focusOutEvent() handle focus in and out events
- \o hoverEnterEvent(), hoverMoveEvent(), and hoverLeaveEvent() handles
- hover enter, move and leave events
- \o inputMethodEvent() handles input events, for accessibility support
- \o keyPressEvent() and keyReleaseEvent() handle key press and release events
- \o mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(), and
- mouseDoubleClickEvent() handles mouse press, move, release, click and
- doubleclick events
- \endlist
-
- You can filter events for any other item by installing event filters. This
- functionality is separate from Qt's regular event filters (see
- QObject::installEventFilter()), which only work on subclasses of QObject. After
- installing your item as an event filter for another item by calling
- installSceneEventFilter(), the filtered events will be received by the virtual
- function sceneEventFilter(). You can remove item event filters by calling
- removeSceneEventFilter().
-
- \section1 Custom Data
-
- Sometimes it's useful to register custom data with an item, be it a custom
- item, or a standard item. You can call setData() on any item to store data
- in it using a key-value pair (the key being an integer, and the value is a
- QVariant). To get custom data from an item, call data(). This
- functionality is completely untouched by Qt itself; it is provided for the
- user's convenience.
-
- \sa QGraphicsScene, QGraphicsView, {Graphics View Framework}
-*/
-
-/*!
- \variable QGraphicsItem::Type
-
- The type value returned by the virtual type() function in standard
- graphics item classes in Qt. All such standard graphics item
- classes in Qt are associated with a unique value for Type,
- e.g. the value returned by QGraphicsPathItem::type() is 2.
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 18
-*/
-
-/*!
- \variable QGraphicsItem::UserType
-
- The lowest permitted type value for custom items (subclasses
- of QGraphicsItem or any of the standard items). This value is
- used in conjunction with a reimplementation of QGraphicsItem::type()
- and declaring a Type enum value. Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 1
-
- \note UserType = 65536
-*/
-
-/*!
- \enum QGraphicsItem::GraphicsItemFlag
-
- This enum describes different flags that you can set on an item to
- toggle different features in the item's behavior.
-
- All flags are disabled by default.
-
- \value ItemIsMovable The item supports interactive movement using
- the mouse. By clicking on the item and then dragging, the item
- will move together with the mouse cursor. If the item has
- children, all children are also moved. If the item is part of a
- selection, all selected items are also moved. This feature is
- provided as a convenience through the base implementation of
- QGraphicsItem's mouse event handlers.
-
- \value ItemIsSelectable The item supports selection. Enabling this
- feature will enable setSelected() to toggle selection for the
- item. It will also let the item be selected automatically as a
- result of calling QGraphicsScene::setSelectionArea(), by clicking
- on an item, or by using rubber band selection in QGraphicsView.
-
- \value ItemIsFocusable The item supports keyboard input focus (i.e., it is
- an input item). Enabling this flag will allow the item to accept focus,
- which again allows the delivery of key events to
- QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent().
-
- \value ItemClipsToShape The item clips to its own shape. The item cannot
- draw or receive mouse, tablet, drag and drop or hover events outside its
- shape. It is disabled by default. This behavior is enforced by
- QGraphicsView::drawItems() or QGraphicsScene::drawItems(). This flag was
- introduced in Qt 4.3.
-
- \value ItemClipsChildrenToShape The item clips the painting of all its
- descendants to its own shape. Items that are either direct or indirect
- children of this item cannot draw outside this item's shape. By default,
- this flag is disabled; children can draw anywhere. This behavior is
- enforced by QGraphicsView::drawItems() or
- QGraphicsScene::drawItems(). This flag was introduced in Qt 4.3.
-
- \value ItemIgnoresTransformations The item ignores inherited
- transformations (i.e., its position is still anchored to its parent, but
- the parent or view rotation, zoom or shear transformations are ignored).
- This flag is useful for keeping text label items horizontal and unscaled,
- so they will still be readable if the view is transformed. When set, the
- item's view geometry and scene geometry will be maintained separately. You
- must call deviceTransform() to map coordinates and detect collisions in
- the view. By default, this flag is disabled. This flag was introduced in
- Qt 4.3. \note With this flag set you can still scale the item itself, and
- that scale transformation will influence the item's children.
-
- \value ItemIgnoresParentOpacity The item ignores its parent's opacity. The
- item's effective opacity is the same as its own; it does not combine with
- the parent's opacity. This flags allows your item to keep its absolute
- opacity even if the parent is semitransparent. This flag was introduced in
- Qt 4.5.
-
- \value ItemDoesntPropagateOpacityToChildren The item doesn't propagate its
- opacity to its children. This flag allows you to create a semitransparent
- item that does not affect the opacity of its children. This flag was
- introduced in Qt 4.5.
-
- \value ItemStacksBehindParent The item is stacked behind its parent. By
- default, child items are stacked on top of the parent item. But setting
- this flag, the child will be stacked behind it. This flag is useful for
- drop shadow effects and for decoration objects that follow the parent
- item's geometry without drawing on top of it. This flag was introduced
- in Qt 4.5.
-
- \value ItemUsesExtendedStyleOption The item makes use of either
- \l{QStyleOptionGraphicsItem::} {exposedRect} or
- \l{QStyleOptionGraphicsItem::} {matrix} in
- QStyleOptionGraphicsItem. By default, the
- \l{QStyleOptionGraphicsItem::} {exposedRect} is initialized to the
- item's boundingRect() and the
- \l{QStyleOptionGraphicsItem::}{matrix} is untransformed. You can
- enable this flag for the style options to be set up with more
- fine-grained values. Note that
- QStyleOptionGraphicsItem::levelOfDetail is unaffected by this flag
- and always initialized to 1. Use
- QStyleOptionGraphicsItem::levelOfDetailFromTransform() if you need
- a higher value. This flag was introduced in Qt 4.6.
-
- \value ItemHasNoContents The item does not paint anything (i.e., calling
- paint() on the item has no effect). You should set this flag on items that
- do not need to be painted to ensure that Graphics View avoids unnecessary
- painting preparations. This flag was introduced in Qt 4.6.
-
- \value ItemSendsGeometryChanges The item enables itemChange()
- notifications for ItemPositionChange, ItemPositionHasChanged,
- ItemMatrixChange, ItemTransformChange, ItemTransformHasChanged,
- ItemRotationChange, ItemRotationHasChanged, ItemScaleChange, ItemScaleHasChanged,
- ItemTransformOriginPointChange, and ItemTransformOriginPointHasChanged. For
- performance reasons, these notifications are disabled by default. You must
- enable this flag to receive notifications for position and transform
- changes. This flag was introduced in Qt 4.6.
-
- \value ItemAcceptsInputMethod The item supports input methods typically
- used for Asian languages.
- This flag was introduced in Qt 4.6.
-
- \value ItemNegativeZStacksBehindParent The item automatically
- stacks behind it's parent if it's z-value is negative. This flag
- enables setZValue() to toggle ItemStacksBehindParent. This flag
- was introduced in Qt 4.6.
-
- \value ItemIsPanel The item is a panel. A panel provides activation and
- contained focus handling. Only one panel can be active at a time (see
- QGraphicsItem::isActive()). When no panel is active, QGraphicsScene
- activates all non-panel items. Window items (i.e.,
- QGraphicsItem::isWindow() returns true) are panels. This flag was
- introduced in Qt 4.6.
-
- \omitvalue ItemIsFocusScope \omit Internal only (for now). \endomit
-
- \value ItemSendsScenePositionChanges The item enables itemChange()
- notifications for ItemScenePositionHasChanged. For performance reasons,
- these notifications are disabled by default. You must enable this flag
- to receive notifications for scene position changes. This flag was
- introduced in Qt 4.6.
-
- \omitvalue ItemStopsClickFocusPropagation \omit The item stops propagating
- click focus to items underneath when being clicked on. This flag
- allows you create a non-focusable item that can be clicked on without
- changing the focus. \endomit
-
- \omitvalue ItemStopsFocusHandling \omit Same as
- ItemStopsClickFocusPropagation, but also suppresses focus-out. This flag
- allows you to completely take over focus handling.
- This flag was introduced in Qt 4.7. \endomit
-*/
-
-/*!
- \enum QGraphicsItem::GraphicsItemChange
-
- This enum describes the state changes that are notified by
- QGraphicsItem::itemChange(). The notifications are sent as the state
- changes, and in some cases, adjustments can be made (see the documentation
- for each change for details).
-
- Note: Be careful with calling functions on the QGraphicsItem itself inside
- itemChange(), as certain function calls can lead to unwanted
- recursion. For example, you cannot call setPos() in itemChange() on an
- ItemPositionChange notification, as the setPos() function will again call
- itemChange(ItemPositionChange). Instead, you can return the new, adjusted
- position from itemChange().
-
- \value ItemEnabledChange The item's enabled state changes. If the item is
- presently enabled, it will become disabled, and vice verca. The value
- argument is the new enabled state (i.e., true or false). Do not call
- setEnabled() in itemChange() as this notification is delivered. Instead,
- you can return the new state from itemChange().
-
- \value ItemEnabledHasChanged The item's enabled state has changed. The
- value argument is the new enabled state (i.e., true or false). Do not call
- setEnabled() in itemChange() as this notification is delivered. The return
- value is ignored.
-
- \value ItemMatrixChange The item's affine transformation matrix is
- changing. This value is obsolete; you can use ItemTransformChange instead.
-
- \value ItemPositionChange The item's position changes. This notification
- is sent if the ItemSendsGeometryChanges flag is enabled, and when the
- item's local position changes, relative to its parent (i.e., as a result
- of calling setPos() or moveBy()). The value argument is the new position
- (i.e., a QPointF). You can call pos() to get the original position. Do
- not call setPos() or moveBy() in itemChange() as this notification is
- delivered; instead, you can return the new, adjusted position from
- itemChange(). After this notification, QGraphicsItem immediately sends the
- ItemPositionHasChanged notification if the position changed.
-
- \value ItemPositionHasChanged The item's position has changed. This
- notification is sent if the ItemSendsGeometryChanges flag is enabled, and
- after the item's local position, relative to its parent, has changed. The
- value argument is the new position (the same as pos()), and QGraphicsItem
- ignores the return value for this notification (i.e., a read-only
- notification).
-
- \value ItemTransformChange The item's transformation matrix changes. This
- notification is send if the ItemSendsGeometryChanges flag is enabled, and
- when the item's local transformation matrix changes (i.e., as a result of
- calling setTransform(). The value argument is the new matrix (i.e., a
- QTransform); to get the old matrix, call transform(). Do not call
- setTransform() or set any of the transformation properties in itemChange()
- as this notification is delivered; instead, you can return the new matrix
- from itemChange(). This notification is not sent if you change the
- transformation properties.
-
- \value ItemTransformHasChanged The item's transformation matrix has
- changed either because setTransform is called, or one of the
- transformation properties is changed. This notification is sent if the
- ItemSendsGeometryChanges flag is enabled, and after the item's local
- transformation matrix has changed. The value argument is the new matrix
- (same as transform()), and QGraphicsItem ignores the return value for this
- notification (i.e., a read-only notification).
-
- \value ItemRotationChange The item's rotation property changes. This
- notification is sent if the ItemSendsGeometryChanges flag is enabled, and
- when the item's rotation property changes (i.e., as a result of calling
- setRotation()). The value argument is the new rotation (i.e., a double);
- to get the old rotation, call rotation(). Do not call setRotation() in
- itemChange() as this notification is delivered; instead, you can return
- the new rotation from itemChange().
-
- \value ItemRotationHasChanged The item's rotation property has changed.
- This notification is sent if the ItemSendsGeometryChanges flag is enabled,
- and after the item's rotation property has changed. The value argument is
- the new rotation (i.e., a double), and QGraphicsItem ignores the return
- value for this notification (i.e., a read-only notification). Do not call
- setRotation() in itemChange() as this notification is delivered.
-
- \value ItemScaleChange The item's scale property changes. This notification
- is sent if the ItemSendsGeometryChanges flag is enabled, and when the item's
- scale property changes (i.e., as a result of calling setScale()). The value
- argument is the new scale (i.e., a double); to get the old scale, call
- scale(). Do not call setScale() in itemChange() as this notification is
- delivered; instead, you can return the new scale from itemChange().
-
- \value ItemScaleHasChanged The item's scale property has changed. This
- notification is sent if the ItemSendsGeometryChanges flag is enabled, and
- after the item's scale property has changed. The value argument is the new
- scale (i.e., a double), and QGraphicsItem ignores the return value for this
- notification (i.e., a read-only notification). Do not call setScale() in
- itemChange() as this notification is delivered.
-
- \value ItemTransformOriginPointChange The item's transform origin point
- property changes. This notification is sent if the ItemSendsGeometryChanges
- flag is enabled, and when the item's transform origin point property changes
- (i.e., as a result of calling setTransformOriginPoint()). The value argument
- is the new origin point (i.e., a QPointF); to get the old origin point, call
- transformOriginPoint(). Do not call setTransformOriginPoint() in itemChange()
- as this notification is delivered; instead, you can return the new transform
- origin point from itemChange().
-
- \value ItemTransformOriginPointHasChanged The item's transform origin point
- property has changed. This notification is sent if the ItemSendsGeometryChanges
- flag is enabled, and after the item's transform origin point property has
- changed. The value argument is the new origin point (i.e., a QPointF), and
- QGraphicsItem ignores the return value for this notification (i.e., a read-only
- notification). Do not call setTransformOriginPoint() in itemChange() as this
- notification is delivered.
-
- \value ItemSelectedChange The item's selected state changes. If the item is
- presently selected, it will become unselected, and vice verca. The value
- argument is the new selected state (i.e., true or false). Do not call
- setSelected() in itemChange() as this notification is delivered; instead, you
- can return the new selected state from itemChange().
-
- \value ItemSelectedHasChanged The item's selected state has changed. The
- value argument is the new selected state (i.e., true or false). Do not
- call setSelected() in itemChange() as this notification is delivered. The
- return value is ignored.
-
- \value ItemVisibleChange The item's visible state changes. If the item is
- presently visible, it will become invisible, and vice verca. The value
- argument is the new visible state (i.e., true or false). Do not call
- setVisible() in itemChange() as this notification is delivered; instead,
- you can return the new visible state from itemChange().
-
- \value ItemVisibleHasChanged The item's visible state has changed. The
- value argument is the new visible state (i.e., true or false). Do not call
- setVisible() in itemChange() as this notification is delivered. The return
- value is ignored.
-
- \value ItemParentChange The item's parent changes. The value argument is
- the new parent item (i.e., a QGraphicsItem pointer). Do not call
- setParentItem() in itemChange() as this notification is delivered;
- instead, you can return the new parent from itemChange().
-
- \value ItemParentHasChanged The item's parent has changed. The value
- argument is the new parent (i.e., a pointer to a QGraphicsItem). Do not
- call setParentItem() in itemChange() as this notification is
- delivered. The return value is ignored.
-
- \value ItemChildAddedChange A child is added to this item. The value
- argument is the new child item (i.e., a QGraphicsItem pointer). Do not
- pass this item to any item's setParentItem() function as this notification
- is delivered. The return value is unused; you cannot adjust anything in
- this notification. Note that the new child might not be fully constructed
- when this notification is sent; calling pure virtual functions on
- the child can lead to a crash.
-
- \value ItemChildRemovedChange A child is removed from this item. The value
- argument is the child item that is about to be removed (i.e., a
- QGraphicsItem pointer). The return value is unused; you cannot adjust
- anything in this notification.
-
- \value ItemSceneChange The item is moved to a new scene. This notification is
- also sent when the item is added to its initial scene, and when it is removed.
- The item's scene() is the old scene (or 0 if the item has not been added to a
- scene yet). The value argument is the new scene (i.e., a QGraphicsScene
- pointer), or a null pointer if the item is removed from a scene. Do not
- override this change by passing this item to QGraphicsScene::addItem() as this
- notification is delivered; instead, you can return the new scene from
- itemChange(). Use this feature with caution; objecting to a scene change can
- quickly lead to unwanted recursion.
-
- \value ItemSceneHasChanged The item's scene has changed. The item's scene() is
- the new scene. This notification is also sent when the item is added to its
- initial scene, and when it is removed.The value argument is the new scene
- (i.e., a pointer to a QGraphicsScene). Do not call setScene() in itemChange()
- as this notification is delivered. The return value is ignored.
-
- \value ItemCursorChange The item's cursor changes. The value argument is
- the new cursor (i.e., a QCursor). Do not call setCursor() in itemChange()
- as this notification is delivered. Instead, you can return a new cursor
- from itemChange().
-
- \value ItemCursorHasChanged The item's cursor has changed. The value
- argument is the new cursor (i.e., a QCursor). Do not call setCursor() as
- this notification is delivered. The return value is ignored.
-
- \value ItemToolTipChange The item's tooltip changes. The value argument is
- the new tooltip (i.e., a QToolTip). Do not call setToolTip() in
- itemChange() as this notification is delivered. Instead, you can return a
- new tooltip from itemChange().
-
- \value ItemToolTipHasChanged The item's tooltip has changed. The value
- argument is the new tooltip (i.e., a QToolTip). Do not call setToolTip()
- as this notification is delivered. The return value is ignored.
-
- \value ItemFlagsChange The item's flags change. The value argument is the
- new flags (i.e., a quint32). Do not call setFlags() in itemChange() as
- this notification is delivered. Instead, you can return the new flags from
- itemChange().
-
- \value ItemFlagsHaveChanged The item's flags have changed. The value
- argument is the new flags (i.e., a quint32). Do not call setFlags() in
- itemChange() as this notification is delivered. The return value is
- ignored.
-
- \value ItemZValueChange The item's Z-value changes. The value argument is
- the new Z-value (i.e., a double). Do not call setZValue() in itemChange()
- as this notification is delivered. Instead, you can return a new Z-value
- from itemChange().
-
- \value ItemZValueHasChanged The item's Z-value has changed. The value
- argument is the new Z-value (i.e., a double). Do not call setZValue() as
- this notification is delivered. The return value is ignored.
-
- \value ItemOpacityChange The item's opacity changes. The value argument is
- the new opacity (i.e., a double). Do not call setOpacity() in itemChange()
- as this notification is delivered. Instead, you can return a new opacity
- from itemChange().
-
- \value ItemOpacityHasChanged The item's opacity has changed. The value
- argument is the new opacity (i.e., a double). Do not call setOpacity() as
- this notification is delivered. The return value is ignored.
-
- \value ItemScenePositionHasChanged The item's scene position has changed.
- This notification is sent if the ItemSendsScenePositionChanges flag is
- enabled, and after the item's scene position has changed (i.e., the
- position or transformation of the item itself or the position or
- transformation of any ancestor has changed). The value argument is the
- new scene position (the same as scenePos()), and QGraphicsItem ignores
- the return value for this notification (i.e., a read-only notification).
-*/
-
-/*!
- \enum QGraphicsItem::CacheMode
- \since 4.4
-
- This enum describes QGraphicsItem's cache modes. Caching is used to speed
- up rendering by allocating and rendering to an off-screen pixel buffer,
- which can be reused when the item requires redrawing. For some paint
- devices, the cache is stored directly in graphics memory, which makes
- rendering very quick.
-
- \value NoCache The default; all item caching is
- disabled. QGraphicsItem::paint() is called every time the item needs
- redrawing.
-
- \value ItemCoordinateCache Caching is enabled for the item's logical
- (local) coordinate system. QGraphicsItem creates an off-screen pixel
- buffer with a configurable size / resolution that you can pass to
- QGraphicsItem::setCacheMode(). Rendering quality will typically degrade,
- depending on the resolution of the cache and the item transformation. The
- first time the item is redrawn, it will render itself into the cache, and
- the cache is then reused for every subsequent expose. The cache is also
- reused as the item is transformed. To adjust the resolution of the cache,
- you can call setCacheMode() again.
-
- \value DeviceCoordinateCache Caching is enabled at the paint device level,
- in device coordinates. This mode is for items that can move, but are not
- rotated, scaled or sheared. If the item is transformed directly or
- indirectly, the cache will be regenerated automatically. Unlike
- ItemCoordinateCacheMode, DeviceCoordinateCache always renders at maximum
- quality.
-
- \sa QGraphicsItem::setCacheMode()
-*/
-
-/*!
- \enum QGraphicsItem::Extension
- \internal
-
- Note: This is provided as a hook to avoid future problems related
- to adding virtual functions. See also extension(),
- supportsExtension() and setExtension().
-*/
-
-/*!
- \enum QGraphicsItem::PanelModality
- \since 4.6
-
- This enum specifies the behavior of a modal panel. A modal panel
- is one that blocks input to other panels. Note that items that
- are children of a modal panel are not blocked.
-
- The values are:
-
- \value NonModal The panel is not modal and does not block input to
- other panels. This is the default value for panels.
-
- \value PanelModal The panel is modal to a single item hierarchy
- and blocks input to its parent pane, all grandparent panels, and
- all siblings of its parent and grandparent panels.
-
- \value SceneModal The window is modal to the entire scene and
- blocks input to all panels.
-
- \sa QGraphicsItem::setPanelModality(), QGraphicsItem::panelModality(), QGraphicsItem::ItemIsPanel
-*/
-
-#include "qgraphicsitem.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicsscene.h"
-#include "qgraphicsscene_p.h"
-#include "qgraphicssceneevent.h"
-#include "qgraphicsview.h"
-#include "qgraphicswidget.h"
-#include "qgraphicsproxywidget.h"
-#include "qgraphicsscenebsptreeindex_p.h"
-#include <QtCore/qbitarray.h>
-#include <QtCore/qdebug.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qstack.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qnumeric.h>
-#include <QtGui/qapplication.h>
-#include <QtGui/qbitmap.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qpainterpath.h>
-#include <QtGui/qpixmapcache.h>
-#include <QtGui/qstyleoption.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qinputcontext.h>
-#include <QtGui/qgraphicseffect.h>
-#ifndef QT_NO_ACCESSIBILITY
-# include "qaccessible.h"
-#endif
-
-#include <private/qgraphicsitem_p.h>
-#include <private/qgraphicswidget_p.h>
-#include <private/qtextcontrol_p.h>
-#include <private/qtextdocumentlayout_p.h>
-#include <private/qtextengine_p.h>
-#include <private/qwidget_p.h>
-#include <private/qapplication_p.h>
-
-#ifdef Q_WS_X11
-#include <private/qt_x11_p.h>
-#include <private/qpixmap_x11_p.h>
-#endif
-
-#include <private/qgesturemanager_p.h>
-
-#include <math.h>
-
-QT_BEGIN_NAMESPACE
-
-static inline void _q_adjustRect(QRect *rect)
-{
- Q_ASSERT(rect);
- if (!rect->width())
- rect->adjust(0, 0, 1, 0);
- if (!rect->height())
- rect->adjust(0, 0, 0, 1);
-}
-
-/*
- ### Move this into QGraphicsItemPrivate
- */
-class QGraphicsItemCustomDataStore
-{
-public:
- QMap<const QGraphicsItem *, QMap<int, QVariant> > data;
-};
-Q_GLOBAL_STATIC(QGraphicsItemCustomDataStore, qt_dataStore)
-
-/*!
- \internal
-
- Returns a QPainterPath of \a path when stroked with the \a pen.
- Ignoring dash pattern.
-*/
-static QPainterPath qt_graphicsItem_shapeFromPath(const QPainterPath &path, const QPen &pen)
-{
- // We unfortunately need this hack as QPainterPathStroker will set a width of 1.0
- // if we pass a value of 0.0 to QPainterPathStroker::setWidth()
- const qreal penWidthZero = qreal(0.00000001);
-
- if (path == QPainterPath())
- return path;
- QPainterPathStroker ps;
- ps.setCapStyle(pen.capStyle());
- if (pen.widthF() <= 0.0)
- ps.setWidth(penWidthZero);
- else
- ps.setWidth(pen.widthF());
- ps.setJoinStyle(pen.joinStyle());
- ps.setMiterLimit(pen.miterLimit());
- QPainterPath p = ps.createStroke(path);
- p.addPath(path);
- return p;
-}
-
-/*!
- \internal
-
- Propagates the ancestor flag \a flag with value \a enabled to all this
- item's children. If \a root is false, the flag is also set on this item
- (default is true).
-*/
-void QGraphicsItemPrivate::updateAncestorFlag(QGraphicsItem::GraphicsItemFlag childFlag,
- AncestorFlag flag, bool enabled, bool root)
-{
- Q_Q(QGraphicsItem);
- if (root) {
- // For root items only. This is the item that has either enabled or
- // disabled \a childFlag, or has been reparented.
- switch (int(childFlag)) {
- case -2:
- flag = AncestorFiltersChildEvents;
- enabled = q->filtersChildEvents();
- break;
- case -1:
- flag = AncestorHandlesChildEvents;
- enabled = q->handlesChildEvents();
- break;
- case QGraphicsItem::ItemClipsChildrenToShape:
- flag = AncestorClipsChildren;
- enabled = flags & QGraphicsItem::ItemClipsChildrenToShape;
- break;
- case QGraphicsItem::ItemIgnoresTransformations:
- flag = AncestorIgnoresTransformations;
- enabled = flags & QGraphicsItem::ItemIgnoresTransformations;
- break;
- default:
- return;
- }
-
- if (parent) {
- // Inherit the enabled-state from our parents.
- if ((parent->d_ptr->ancestorFlags & flag)
- || (int(parent->d_ptr->flags & childFlag) == childFlag)
- || (childFlag == -1 && parent->d_ptr->handlesChildEvents)
- || (childFlag == -2 && parent->d_ptr->filtersDescendantEvents)) {
- enabled = true;
- ancestorFlags |= flag;
- } else {
- ancestorFlags &= ~flag;
- }
- } else {
- // Top-level root items don't have any ancestors, so there are no
- // ancestor flags either.
- ancestorFlags = 0;
- }
- } else {
- // Don't set or propagate the ancestor flag if it's already correct.
- if (((ancestorFlags & flag) && enabled) || (!(ancestorFlags & flag) && !enabled))
- return;
-
- // Set the flag.
- if (enabled)
- ancestorFlags |= flag;
- else
- ancestorFlags &= ~flag;
-
- // Don't process children if the item has the main flag set on itself.
- if ((childFlag != -1 && int(flags & childFlag) == childFlag)
- || (int(childFlag) == -1 && handlesChildEvents)
- || (int(childFlag) == -2 && filtersDescendantEvents))
- return;
- }
-
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->updateAncestorFlag(childFlag, flag, enabled, false);
-}
-
-void QGraphicsItemPrivate::updateAncestorFlags()
-{
- int flags = 0;
- if (parent) {
- // Inherit the parent's ancestor flags.
- QGraphicsItemPrivate *pd = parent->d_ptr.data();
- flags = pd->ancestorFlags;
-
- // Add in flags from the parent.
- if (pd->filtersDescendantEvents)
- flags |= AncestorFiltersChildEvents;
- if (pd->handlesChildEvents)
- flags |= AncestorHandlesChildEvents;
- if (pd->flags & QGraphicsItem::ItemClipsChildrenToShape)
- flags |= AncestorClipsChildren;
- if (pd->flags & QGraphicsItem::ItemIgnoresTransformations)
- flags |= AncestorIgnoresTransformations;
- }
-
- if (ancestorFlags == flags)
- return; // No change; stop propagation.
- ancestorFlags = flags;
-
- // Propagate to children recursively.
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->updateAncestorFlags();
-}
-
-/*!
- \internal
-
- Propagates item group membership.
-*/
-void QGraphicsItemPrivate::setIsMemberOfGroup(bool enabled)
-{
- Q_Q(QGraphicsItem);
- isMemberOfGroup = enabled;
- if (!qgraphicsitem_cast<QGraphicsItemGroup *>(q)) {
- foreach (QGraphicsItem *child, children)
- child->d_func()->setIsMemberOfGroup(enabled);
- }
-}
-
-/*!
- \internal
-
- Maps any item pos properties of \a event to \a item's coordinate system.
-*/
-void QGraphicsItemPrivate::remapItemPos(QEvent *event, QGraphicsItem *item)
-{
- Q_Q(QGraphicsItem);
- switch (event->type()) {
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseDoubleClick: {
- QGraphicsSceneMouseEvent *mouseEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
- mouseEvent->setPos(item->mapFromItem(q, mouseEvent->pos()));
- mouseEvent->setLastPos(item->mapFromItem(q, mouseEvent->pos()));
- for (int i = 0x1; i <= 0x10; i <<= 1) {
- if (mouseEvent->buttons() & i) {
- Qt::MouseButton button = Qt::MouseButton(i);
- mouseEvent->setButtonDownPos(button, item->mapFromItem(q, mouseEvent->buttonDownPos(button)));
- }
- }
- break;
- }
- case QEvent::GraphicsSceneWheel: {
- QGraphicsSceneWheelEvent *wheelEvent = static_cast<QGraphicsSceneWheelEvent *>(event);
- wheelEvent->setPos(item->mapFromItem(q, wheelEvent->pos()));
- break;
- }
- case QEvent::GraphicsSceneContextMenu: {
- QGraphicsSceneContextMenuEvent *contextEvent = static_cast<QGraphicsSceneContextMenuEvent *>(event);
- contextEvent->setPos(item->mapFromItem(q, contextEvent->pos()));
- break;
- }
- case QEvent::GraphicsSceneHoverMove: {
- QGraphicsSceneHoverEvent *hoverEvent = static_cast<QGraphicsSceneHoverEvent *>(event);
- hoverEvent->setPos(item->mapFromItem(q, hoverEvent->pos()));
- break;
- }
- default:
- break;
- }
-}
-
-/*!
- \internal
-
- Maps the point \a pos from scene to item coordinates. If \a view is passed and the item
- is untransformable, this function will correctly map \a pos from the scene using the
- view's transformation.
-*/
-QPointF QGraphicsItemPrivate::genericMapFromScene(const QPointF &pos,
- const QWidget *viewport) const
-{
- Q_Q(const QGraphicsItem);
- if (!itemIsUntransformable())
- return q->mapFromScene(pos);
- QGraphicsView *view = 0;
- if (viewport)
- view = qobject_cast<QGraphicsView *>(viewport->parentWidget());
- if (!view)
- return q->mapFromScene(pos);
- // ### More ping pong than needed.
- return q->deviceTransform(view->viewportTransform()).inverted().map(view->mapFromScene(pos));
-}
-
-/*!
- \internal
-
- Combines this item's position and transform onto \a transform.
-
- If you need to change this function (e.g., adding more transformation
- modes / options), make sure to change all places marked with COMBINE.
-*/
-void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransform *viewTransform) const
-{
- // COMBINE
- if (viewTransform && itemIsUntransformable()) {
- *x = q_ptr->deviceTransform(*viewTransform);
- } else {
- if (transformData)
- *x *= transformData->computedFullTransform();
- if (!pos.isNull())
- *x *= QTransform::fromTranslate(pos.x(), pos.y());
- }
-}
-
-/*!
- \internal
-
- Combines this item's position and transform onto \a transform.
-
- If you need to change this function (e.g., adding more transformation
- modes / options), make sure to change QGraphicsItem::deviceTransform() as
- well.
-*/
-void QGraphicsItemPrivate::combineTransformFromParent(QTransform *x, const QTransform *viewTransform) const
-{
- // COMBINE
- if (viewTransform && itemIsUntransformable()) {
- *x = q_ptr->deviceTransform(*viewTransform);
- } else {
- x->translate(pos.x(), pos.y());
- if (transformData)
- *x = transformData->computedFullTransform(x);
- }
-}
-
-void QGraphicsItemPrivate::updateSceneTransformFromParent()
-{
- if (parent) {
- Q_ASSERT(!parent->d_ptr->dirtySceneTransform);
- if (parent->d_ptr->sceneTransformTranslateOnly) {
- sceneTransform = QTransform::fromTranslate(parent->d_ptr->sceneTransform.dx() + pos.x(),
- parent->d_ptr->sceneTransform.dy() + pos.y());
- } else {
- sceneTransform = parent->d_ptr->sceneTransform;
- sceneTransform.translate(pos.x(), pos.y());
- }
- if (transformData) {
- sceneTransform = transformData->computedFullTransform(&sceneTransform);
- sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate);
- } else {
- sceneTransformTranslateOnly = parent->d_ptr->sceneTransformTranslateOnly;
- }
- } else if (!transformData) {
- sceneTransform = QTransform::fromTranslate(pos.x(), pos.y());
- sceneTransformTranslateOnly = 1;
- } else if (transformData->onlyTransform) {
- sceneTransform = transformData->transform;
- if (!pos.isNull())
- sceneTransform *= QTransform::fromTranslate(pos.x(), pos.y());
- sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate);
- } else if (pos.isNull()) {
- sceneTransform = transformData->computedFullTransform();
- sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate);
- } else {
- sceneTransform = QTransform::fromTranslate(pos.x(), pos.y());
- sceneTransform = transformData->computedFullTransform(&sceneTransform);
- sceneTransformTranslateOnly = (sceneTransform.type() <= QTransform::TxTranslate);
- }
- dirtySceneTransform = 0;
-}
-
-/*!
- \internal
-
- This helper function helped us add input method query support in
- Qt 4.4.1 without having to reimplement the inputMethodQuery()
- function in QGraphicsProxyWidget. ### Qt 5: Remove. We cannot
- remove it in 4.5+ even if we do reimplement the function properly,
- because apps compiled with 4.4 will not be able to call the
- reimplementation.
-*/
-QVariant QGraphicsItemPrivate::inputMethodQueryHelper(Qt::InputMethodQuery query) const
-{
- Q_UNUSED(query);
- return QVariant();
-}
-
-/*!
- \internal
-
- Make sure not to trigger any pure virtual function calls (e.g.,
- prepareGeometryChange) if the item is in its destructor, i.e.
- inDestructor is 1.
-*/
-void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, const QVariant *newParentVariant,
- const QVariant *thisPointerVariant)
-{
- Q_Q(QGraphicsItem);
- if (newParent == parent)
- return;
-
- if (isWidget)
- static_cast<QGraphicsWidgetPrivate *>(this)->fixFocusChainBeforeReparenting((newParent &&
- newParent->isWidget()) ? static_cast<QGraphicsWidget *>(newParent) : 0,
- scene);
- if (scene) {
- // Deliver the change to the index
- if (scene->d_func()->indexMethod != QGraphicsScene::NoIndex)
- scene->d_func()->index->itemChange(q, QGraphicsItem::ItemParentChange, newParent);
-
- // Disable scene pos notifications for old ancestors
- if (scenePosDescendants || (flags & QGraphicsItem::ItemSendsScenePositionChanges))
- scene->d_func()->setScenePosItemEnabled(q, false);
- }
-
- if (subFocusItem && parent) {
- // Make sure none of the old parents point to this guy.
- subFocusItem->d_ptr->clearSubFocus(parent);
- }
-
- // We anticipate geometry changes. If the item is deleted, it will be
- // removed from the index at a later stage, and the whole scene will be
- // updated.
- if (!inDestructor)
- q_ptr->prepareGeometryChange();
-
- if (parent) {
- // Remove from current parent
- parent->d_ptr->removeChild(q);
- if (thisPointerVariant)
- parent->itemChange(QGraphicsItem::ItemChildRemovedChange, *thisPointerVariant);
- }
-
- // Update toplevelitem list. If this item is being deleted, its parent
- // will be 0 but we don't want to register/unregister it in the TLI list.
- if (scene && !inDestructor) {
- if (parent && !newParent) {
- scene->d_func()->registerTopLevelItem(q);
- } else if (!parent && newParent) {
- scene->d_func()->unregisterTopLevelItem(q);
- }
- }
-
- // Ensure any last parent focus scope does not point to this item or any of
- // its descendents.
- QGraphicsItem *p = parent;
- QGraphicsItem *parentFocusScopeItem = 0;
- while (p) {
- if (p->d_ptr->flags & QGraphicsItem::ItemIsFocusScope) {
- // If this item's focus scope's focus scope item points
- // to this item or a descendent, then clear it.
- QGraphicsItem *fsi = p->d_ptr->focusScopeItem;
- if (q_ptr == fsi || q_ptr->isAncestorOf(fsi)) {
- parentFocusScopeItem = fsi;
- p->d_ptr->focusScopeItem = 0;
- fsi->d_ptr->focusScopeItemChange(false);
- }
- break;
- }
- p = p->d_ptr->parent;
- }
-
- // Update graphics effect optimization flag
- if (newParent && (graphicsEffect || mayHaveChildWithGraphicsEffect))
- newParent->d_ptr->updateChildWithGraphicsEffectFlagRecursively();
-
- // Update focus scope item ptr in new scope.
- QGraphicsItem *newFocusScopeItem = subFocusItem ? subFocusItem : parentFocusScopeItem;
- if (newFocusScopeItem && newParent) {
- if (subFocusItem) {
- // Find the subFocusItem's topmost focus scope.
- QGraphicsItem *ancestorScope = 0;
- QGraphicsItem *p = subFocusItem->d_ptr->parent;
- while (p) {
- if (p->d_ptr->flags & QGraphicsItem::ItemIsFocusScope)
- ancestorScope = p;
- if (p->d_ptr->flags & QGraphicsItem::ItemIsPanel)
- break;
- p = p->d_ptr->parent;
- }
- if (ancestorScope)
- newFocusScopeItem = ancestorScope;
- }
-
- QGraphicsItem *p = newParent;
- while (p) {
- if (p->d_ptr->flags & QGraphicsItem::ItemIsFocusScope) {
- p->d_ptr->focusScopeItem = newFocusScopeItem;
- newFocusScopeItem->d_ptr->focusScopeItemChange(true);
- // Ensure the new item is no longer the subFocusItem. The
- // only way to set focus on a child of a focus scope is
- // by setting focus on the scope itself.
- if (subFocusItem && !p->focusItem())
- subFocusItem->d_ptr->clearSubFocus();
- break;
- }
- p = p->d_ptr->parent;
- }
- }
-
- // Resolve depth.
- invalidateDepthRecursively();
-
- if ((parent = newParent)) {
- if (parent->d_func()->scene && parent->d_func()->scene != scene) {
- // Move this item to its new parent's scene
- parent->d_func()->scene->addItem(q);
- } else if (!parent->d_func()->scene && scene) {
- // Remove this item from its former scene
- scene->removeItem(q);
- }
-
- parent->d_ptr->addChild(q);
- if (thisPointerVariant)
- parent->itemChange(QGraphicsItem::ItemChildAddedChange, *thisPointerVariant);
- if (scene) {
- // Re-enable scene pos notifications for new ancestors
- if (scenePosDescendants || (flags & QGraphicsItem::ItemSendsScenePositionChanges))
- scene->d_func()->setScenePosItemEnabled(q, true);
- }
-
- // Propagate dirty flags to the new parent
- markParentDirty(/*updateBoundingRect=*/true);
-
- // Inherit ancestor flags from the new parent.
- updateAncestorFlags();
-
- // Update item visible / enabled.
- if (parent->d_ptr->visible != visible) {
- if (!parent->d_ptr->visible || !explicitlyHidden)
- setVisibleHelper(parent->d_ptr->visible, /* explicit = */ false, /* update = */ false);
- }
- if (parent->isEnabled() != enabled) {
- if (!parent->d_ptr->enabled || !explicitlyDisabled)
- setEnabledHelper(parent->d_ptr->enabled, /* explicit = */ false, /* update = */ false);
- }
-
- // Auto-activate if visible and the parent is active.
- if (visible && parent->isActive())
- q->setActive(true);
- } else {
- // Inherit ancestor flags from the new parent.
- updateAncestorFlags();
-
- if (!inDestructor) {
- // Update item visible / enabled.
- if (!visible && !explicitlyHidden)
- setVisibleHelper(true, /* explicit = */ false);
- if (!enabled && !explicitlyDisabled)
- setEnabledHelper(true, /* explicit = */ false);
- }
- }
-
- dirtySceneTransform = 1;
- if (!inDestructor && (transformData || (newParent && newParent->d_ptr->transformData)))
- transformChanged();
-
- // Restore the sub focus chain.
- if (subFocusItem) {
- subFocusItem->d_ptr->setSubFocus(newParent);
- if (parent && parent->isActive())
- subFocusItem->setFocus();
- }
-
- // Deliver post-change notification
- if (newParentVariant)
- q->itemChange(QGraphicsItem::ItemParentHasChanged, *newParentVariant);
-
- if (isObject)
- emit static_cast<QGraphicsObject *>(q)->parentChanged();
-}
-
-/*!
- \internal
-
- Returns the bounding rect of this item's children (excluding itself).
-*/
-void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rect, QGraphicsItem *topMostEffectItem)
-{
- Q_Q(QGraphicsItem);
-
- QRectF childrenRect;
- QRectF *result = rect;
- rect = &childrenRect;
- const bool setTopMostEffectItem = !topMostEffectItem;
-
- for (int i = 0; i < children.size(); ++i) {
- QGraphicsItem *child = children.at(i);
- QGraphicsItemPrivate *childd = child->d_ptr.data();
- if (setTopMostEffectItem)
- topMostEffectItem = child;
- bool hasPos = !childd->pos.isNull();
- if (hasPos || childd->transformData) {
- // COMBINE
- QTransform matrix = childd->transformToParent();
- if (x)
- matrix *= *x;
- *rect |= matrix.mapRect(child->d_ptr->effectiveBoundingRect(topMostEffectItem));
- if (!childd->children.isEmpty())
- childd->childrenBoundingRectHelper(&matrix, rect, topMostEffectItem);
- } else {
- if (x)
- *rect |= x->mapRect(child->d_ptr->effectiveBoundingRect(topMostEffectItem));
- else
- *rect |= child->d_ptr->effectiveBoundingRect(topMostEffectItem);
- if (!childd->children.isEmpty())
- childd->childrenBoundingRectHelper(x, rect, topMostEffectItem);
- }
- }
-
- if (flags & QGraphicsItem::ItemClipsChildrenToShape){
- if (x)
- *rect &= x->mapRect(q->boundingRect());
- else
- *rect &= q->boundingRect();
- }
-
- *result |= *rect;
-}
-
-void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform,
- const QRegion &exposedRegion, bool allItems) const
-{
- Q_ASSERT(option);
- Q_Q(const QGraphicsItem);
-
- // Initialize standard QStyleOption values.
- const QRectF brect = q->boundingRect();
- option->state = QStyle::State_None;
- option->rect = brect.toRect();
- option->levelOfDetail = 1;
- option->exposedRect = brect;
- if (selected)
- option->state |= QStyle::State_Selected;
- if (enabled)
- option->state |= QStyle::State_Enabled;
- if (q->hasFocus())
- option->state |= QStyle::State_HasFocus;
- if (scene) {
- if (scene->d_func()->hoverItems.contains(q_ptr))
- option->state |= QStyle::State_MouseOver;
- if (q == scene->mouseGrabberItem())
- option->state |= QStyle::State_Sunken;
- }
-
- if (!(flags & QGraphicsItem::ItemUsesExtendedStyleOption))
- return;
-
- // Initialize QStyleOptionGraphicsItem specific values (matrix, exposedRect).
- option->matrix = worldTransform.toAffine(); //### discards perspective
-
- if (!allItems) {
- // Determine the item's exposed area
- option->exposedRect = QRectF();
- const QTransform reverseMap = worldTransform.inverted();
- const QVector<QRect> exposedRects(exposedRegion.rects());
- for (int i = 0; i < exposedRects.size(); ++i) {
- option->exposedRect |= reverseMap.mapRect(QRectF(exposedRects.at(i)));
- if (option->exposedRect.contains(brect))
- break;
- }
- option->exposedRect &= brect;
- }
-}
-
-/*!
- \internal
-
- Empty all cached pixmaps from the pixmap cache.
-*/
-void QGraphicsItemCache::purge()
-{
- QPixmapCache::remove(key);
- key = QPixmapCache::Key();
- QMutableMapIterator<QPaintDevice *, DeviceData> it(deviceData);
- while (it.hasNext()) {
- DeviceData &data = it.next().value();
- QPixmapCache::remove(data.key);
- data.cacheIndent = QPoint();
- }
- deviceData.clear();
- allExposed = true;
- exposed.clear();
-}
-
-/*!
- Constructs a QGraphicsItem with the given \a parent item.
- It does not modify the parent object returned by QObject::parent().
-
- If \a parent is 0, you can add the item to a scene by calling
- QGraphicsScene::addItem(). The item will then become a top-level item.
-
- \sa QGraphicsScene::addItem(), setParentItem()
-*/
-QGraphicsItem::QGraphicsItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : d_ptr(new QGraphicsItemPrivate)
-{
- d_ptr->q_ptr = this;
- setParentItem(parent);
-
- if (scene && parent && parent->scene() != scene) {
- qWarning("QGraphicsItem::QGraphicsItem: ignoring scene (%p), which is"
- " different from parent's scene (%p)",
- scene, parent->scene());
- return;
- }
- if (scene && !parent)
- scene->addItem(this);
-}
-
-/*!
- \internal
-*/
-QGraphicsItem::QGraphicsItem(QGraphicsItemPrivate &dd, QGraphicsItem *parent,
- QGraphicsScene *scene)
- : d_ptr(&dd)
-{
- d_ptr->q_ptr = this;
- setParentItem(parent);
-
- if (scene && parent && parent->scene() != scene) {
- qWarning("QGraphicsItem::QGraphicsItem: ignoring scene (%p), which is"
- " different from parent's scene (%p)",
- scene, parent->scene());
- return;
- }
- if (scene && !parent)
- scene->addItem(this);
-}
-
-/*!
- Destroys the QGraphicsItem and all its children. If this item is currently
- associated with a scene, the item will be removed from the scene before it
- is deleted.
-
- \note It is more efficient to remove the item from the QGraphicsScene before
- destroying the item.
-*/
-QGraphicsItem::~QGraphicsItem()
-{
- if (d_ptr->isObject) {
- QGraphicsObject *o = static_cast<QGraphicsObject *>(this);
- QObjectPrivate *p = QObjectPrivate::get(o);
- p->wasDeleted = true;
- if (p->declarativeData) {
- QAbstractDeclarativeData::destroyed(p->declarativeData, o);
- p->declarativeData = 0;
- }
- }
-
- d_ptr->inDestructor = 1;
- d_ptr->removeExtraItemCache();
-
-#ifndef QT_NO_GESTURES
- if (d_ptr->isObject && !d_ptr->gestureContext.isEmpty()) {
- QGraphicsObject *o = static_cast<QGraphicsObject *>(this);
- if (QGestureManager *manager = QGestureManager::instance()) {
- foreach (Qt::GestureType type, d_ptr->gestureContext.keys())
- manager->cleanupCachedGestures(o, type);
- }
- }
-#endif
-
- clearFocus();
-
- // Update focus scope item ptr.
- QGraphicsItem *p = d_ptr->parent;
- while (p) {
- if (p->flags() & ItemIsFocusScope) {
- if (p->d_ptr->focusScopeItem == this)
- p->d_ptr->focusScopeItem = 0;
- break;
- }
- p = p->d_ptr->parent;
- }
-
- if (!d_ptr->children.isEmpty()) {
- while (!d_ptr->children.isEmpty())
- delete d_ptr->children.first();
- Q_ASSERT(d_ptr->children.isEmpty());
- }
-
- if (d_ptr->scene) {
- d_ptr->scene->d_func()->removeItemHelper(this);
- } else {
- d_ptr->resetFocusProxy();
- setParentItem(0);
- }
-
-#ifndef QT_NO_GRAPHICSEFFECT
- delete d_ptr->graphicsEffect;
-#endif //QT_NO_GRAPHICSEFFECT
- if (d_ptr->transformData) {
- for(int i = 0; i < d_ptr->transformData->graphicsTransforms.size(); ++i) {
- QGraphicsTransform *t = d_ptr->transformData->graphicsTransforms.at(i);
- static_cast<QGraphicsTransformPrivate *>(t->d_ptr.data())->item = 0;
- delete t;
- }
- }
- delete d_ptr->transformData;
-
- if (QGraphicsItemCustomDataStore *dataStore = qt_dataStore())
- dataStore->data.remove(this);
-}
-
-/*!
- Returns the current scene for the item, or 0 if the item is not stored in
- a scene.
-
- To add or move an item to a scene, call QGraphicsScene::addItem().
-*/
-QGraphicsScene *QGraphicsItem::scene() const
-{
- return d_ptr->scene;
-}
-
-/*!
- Returns a pointer to this item's item group, or 0 if this item is not
- member of a group.
-
- \sa QGraphicsItemGroup, QGraphicsScene::createItemGroup()
-*/
-QGraphicsItemGroup *QGraphicsItem::group() const
-{
- if (!d_ptr->isMemberOfGroup)
- return 0;
- QGraphicsItem *parent = const_cast<QGraphicsItem *>(this);
- while ((parent = parent->d_ptr->parent)) {
- if (QGraphicsItemGroup *group = qgraphicsitem_cast<QGraphicsItemGroup *>(parent))
- return group;
- }
- // Unreachable; if d_ptr->isMemberOfGroup is != 0, then one parent of this
- // item is a group item.
- return 0;
-}
-
-/*!
- Adds this item to the item group \a group. If \a group is 0, this item is
- removed from any current group and added as a child of the previous
- group's parent.
-
- \sa group(), QGraphicsScene::createItemGroup()
-*/
-void QGraphicsItem::setGroup(QGraphicsItemGroup *group)
-{
- if (!group) {
- if (QGraphicsItemGroup *group = this->group())
- group->removeFromGroup(this);
- } else {
- group->addToGroup(this);
- }
-}
-
-/*!
- Returns a pointer to this item's parent item. If this item does not have a
- parent, 0 is returned.
-
- \sa setParentItem(), childItems()
-*/
-QGraphicsItem *QGraphicsItem::parentItem() const
-{
- return d_ptr->parent;
-}
-
-/*!
- Returns this item's top-level item. The top-level item is the item's
- topmost ancestor item whose parent is 0. If an item has no parent, its own
- pointer is returned (i.e., a top-level item is its own top-level item).
-
- \sa parentItem()
-*/
-QGraphicsItem *QGraphicsItem::topLevelItem() const
-{
- QGraphicsItem *parent = const_cast<QGraphicsItem *>(this);
- while (QGraphicsItem *grandPa = parent->parentItem())
- parent = grandPa;
- return parent;
-}
-
-/*!
- \since 4.6
-
- Returns a pointer to the item's parent, cast to a QGraphicsObject. returns 0 if the parent item
- is not a QGraphicsObject.
-
- \sa parentItem(), childItems()
-*/
-QGraphicsObject *QGraphicsItem::parentObject() const
-{
- QGraphicsItem *p = d_ptr->parent;
- return (p && p->d_ptr->isObject) ? static_cast<QGraphicsObject *>(p) : 0;
-}
-
-/*!
- \since 4.4
-
- Returns a pointer to the item's parent widget. The item's parent widget is
- the closest parent item that is a widget.
-
- \sa parentItem(), childItems()
-*/
-QGraphicsWidget *QGraphicsItem::parentWidget() const
-{
- QGraphicsItem *p = parentItem();
- while (p && !p->isWidget())
- p = p->parentItem();
- return (p && p->isWidget()) ? static_cast<QGraphicsWidget *>(p) : 0;
-}
-
-/*!
- \since 4.4
-
- Returns a pointer to the item's top level widget (i.e., the item's
- ancestor whose parent is 0, or whose parent is not a widget), or 0 if this
- item does not have a top level widget. If the item is its own top level
- widget, this function returns a pointer to the item itself.
-*/
-QGraphicsWidget *QGraphicsItem::topLevelWidget() const
-{
- if (const QGraphicsWidget *p = parentWidget())
- return p->topLevelWidget();
- return isWidget() ? static_cast<QGraphicsWidget *>(const_cast<QGraphicsItem *>(this)) : 0;
-}
-
-/*!
- \since 4.4
-
- Returns the item's window, or 0 if this item does not have a window. If
- the item is a window, it will return itself. Otherwise it will return the
- closest ancestor that is a window.
-
- \sa QGraphicsWidget::isWindow()
-*/
-QGraphicsWidget *QGraphicsItem::window() const
-{
- QGraphicsItem *p = panel();
- if (p && p->isWindow())
- return static_cast<QGraphicsWidget *>(p);
- return 0;
-}
-
-/*!
- \since 4.6
-
- Returns the item's panel, or 0 if this item does not have a panel. If the
- item is a panel, it will return itself. Otherwise it will return the
- closest ancestor that is a panel.
-
- \sa isPanel(), ItemIsPanel
-*/
-QGraphicsItem *QGraphicsItem::panel() const
-{
- if (d_ptr->flags & ItemIsPanel)
- return const_cast<QGraphicsItem *>(this);
- return d_ptr->parent ? d_ptr->parent->panel() : 0;
-}
-
-/*!
- \since 4.6
-
- Return the graphics item cast to a QGraphicsObject, if the class is actually a
- graphics object, 0 otherwise.
-*/
-QGraphicsObject *QGraphicsItem::toGraphicsObject()
-{
- return d_ptr->isObject ? static_cast<QGraphicsObject *>(this) : 0;
-}
-
-/*!
- \since 4.6
-
- Return the graphics item cast to a QGraphicsObject, if the class is actually a
- graphics object, 0 otherwise.
-*/
-const QGraphicsObject *QGraphicsItem::toGraphicsObject() const
-{
- return d_ptr->isObject ? static_cast<const QGraphicsObject *>(this) : 0;
-}
-
-/*!
- Sets this item's parent item to \a newParent. If this item already
- has a parent, it is first removed from the previous parent. If \a
- newParent is 0, this item will become a top-level item.
-
- Note that this implicitly adds this graphics item to the scene of
- the parent. You should not \l{QGraphicsScene::addItem()}{add} the
- item to the scene yourself.
-
- Calling this function on an item that is an ancestor of \a newParent
- have undefined behaviour.
-
- \sa parentItem(), childItems()
-*/
-void QGraphicsItem::setParentItem(QGraphicsItem *newParent)
-{
- if (newParent == this) {
- qWarning("QGraphicsItem::setParentItem: cannot assign %p as a parent of itself", this);
- return;
- }
- if (newParent == d_ptr->parent)
- return;
-
- const QVariant newParentVariant(itemChange(QGraphicsItem::ItemParentChange,
- QVariant::fromValue<QGraphicsItem *>(newParent)));
- newParent = qvariant_cast<QGraphicsItem *>(newParentVariant);
- if (newParent == d_ptr->parent)
- return;
-
- const QVariant thisPointerVariant(QVariant::fromValue<QGraphicsItem *>(this));
- d_ptr->setParentItemHelper(newParent, &newParentVariant, &thisPointerVariant);
-}
-
-/*!
- \obsolete
-
- Use childItems() instead.
-
- \sa setParentItem()
-*/
-QList<QGraphicsItem *> QGraphicsItem::children() const
-{
- return childItems();
-}
-
-/*!
- \since 4.4
-
- Returns a list of this item's children.
-
- The items are sorted by stacking order. This takes into account both the
- items' insertion order and their Z-values.
-
- \sa setParentItem(), zValue(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsItem::childItems() const
-{
- const_cast<QGraphicsItem *>(this)->d_ptr->ensureSortedChildren();
- return d_ptr->children;
-}
-
-/*!
- \since 4.4
- Returns true if this item is a widget (i.e., QGraphicsWidget); otherwise,
- returns false.
-*/
-bool QGraphicsItem::isWidget() const
-{
- return d_ptr->isWidget;
-}
-
-/*!
- \since 4.4
- Returns true if the item is a QGraphicsWidget window, otherwise returns
- false.
-
- \sa QGraphicsWidget::windowFlags()
-*/
-bool QGraphicsItem::isWindow() const
-{
- return d_ptr->isWidget && (static_cast<const QGraphicsWidget *>(this)->windowType() & Qt::Window);
-}
-
-/*!
- \since 4.6
- Returns true if the item is a panel; otherwise returns false.
-
- \sa QGraphicsItem::panel(), ItemIsPanel
-*/
-bool QGraphicsItem::isPanel() const
-{
- return d_ptr->flags & ItemIsPanel;
-}
-
-/*!
- Returns this item's flags. The flags describe what configurable features
- of the item are enabled and not. For example, if the flags include
- ItemIsFocusable, the item can accept input focus.
-
- By default, no flags are enabled.
-
- \sa setFlags(), setFlag()
-*/
-QGraphicsItem::GraphicsItemFlags QGraphicsItem::flags() const
-{
- return GraphicsItemFlags(d_ptr->flags);
-}
-
-/*!
- If \a enabled is true, the item flag \a flag is enabled; otherwise, it is
- disabled.
-
- \sa flags(), setFlags()
-*/
-void QGraphicsItem::setFlag(GraphicsItemFlag flag, bool enabled)
-{
- if (enabled)
- setFlags(GraphicsItemFlags(d_ptr->flags) | flag);
- else
- setFlags(GraphicsItemFlags(d_ptr->flags) & ~flag);
-}
-
-/*!
- \internal
-
- Sets the flag \a flag on \a item and all its children, to \a enabled.
-*/
-static void _q_qgraphicsItemSetFlag(QGraphicsItem *item, QGraphicsItem::GraphicsItemFlag flag,
- bool enabled)
-{
- if (item->flags() & flag) {
- // If this item already has the correct flag set, we don't have to
- // propagate it.
- return;
- }
- item->setFlag(flag, enabled);
- foreach (QGraphicsItem *child, item->children())
- _q_qgraphicsItemSetFlag(child, flag, enabled);
-}
-
-/*!
- Sets the item flags to \a flags. All flags in \a flags are enabled; all
- flags not in \a flags are disabled.
-
- If the item had focus and \a flags does not enable ItemIsFocusable, the
- item loses focus as a result of calling this function. Similarly, if the
- item was selected, and \a flags does not enabled ItemIsSelectable, the
- item is automatically unselected.
-
- By default, no flags are enabled. (QGraphicsWidget enables the
- ItemSendsGeometryChanges flag by default in order to track position
- changes.)
-
- \sa flags(), setFlag()
-*/
-void QGraphicsItem::setFlags(GraphicsItemFlags flags)
-{
- // Notify change and check for adjustment.
- if (quint32(d_ptr->flags) == quint32(flags))
- return;
- flags = GraphicsItemFlags(itemChange(ItemFlagsChange, quint32(flags)).toUInt());
- if (quint32(d_ptr->flags) == quint32(flags))
- return;
- if (d_ptr->scene && d_ptr->scene->d_func()->indexMethod != QGraphicsScene::NoIndex)
- d_ptr->scene->d_func()->index->itemChange(this, ItemFlagsChange, &flags);
-
- // Flags that alter the geometry of the item (or its children).
- const quint32 geomChangeFlagsMask = (ItemClipsChildrenToShape | ItemClipsToShape | ItemIgnoresTransformations | ItemIsSelectable);
- bool fullUpdate = (quint32(flags) & geomChangeFlagsMask) != (d_ptr->flags & geomChangeFlagsMask);
- if (fullUpdate)
- d_ptr->updatePaintedViewBoundingRects(/*children=*/true);
-
- // Keep the old flags to compare the diff.
- GraphicsItemFlags oldFlags = GraphicsItemFlags(d_ptr->flags);
-
- // Update flags.
- d_ptr->flags = flags;
-
- if (!(d_ptr->flags & ItemIsFocusable) && hasFocus()) {
- // Clear focus on the item if it has focus when the focusable flag
- // is unset.
- clearFocus();
- }
-
- if (!(d_ptr->flags & ItemIsSelectable) && isSelected()) {
- // Unselect the item if it is selected when the selectable flag is
- // unset.
- setSelected(false);
- }
-
- if ((flags & ItemClipsChildrenToShape) != (oldFlags & ItemClipsChildrenToShape)) {
- // Item children clipping changes. Propagate the ancestor flag to
- // all children.
- d_ptr->updateAncestorFlag(ItemClipsChildrenToShape);
- // The childrenBoundingRect is clipped to the boundingRect in case of ItemClipsChildrenToShape,
- // which means we have to invalidate the cached childrenBoundingRect whenever this flag changes.
- d_ptr->dirtyChildrenBoundingRect = 1;
- d_ptr->markParentDirty(true);
- }
-
- if ((flags & ItemIgnoresTransformations) != (oldFlags & ItemIgnoresTransformations)) {
- // Item children clipping changes. Propagate the ancestor flag to
- // all children.
- d_ptr->updateAncestorFlag(ItemIgnoresTransformations);
- }
-
- if ((flags & ItemNegativeZStacksBehindParent) != (oldFlags & ItemNegativeZStacksBehindParent)) {
- // NB! We change the flags directly here, so we must also update d_ptr->flags.
- // Note that this has do be done before the ItemStacksBehindParent check
- // below; otherwise we will loose the change.
-
- // Update stack-behind.
- if (d_ptr->z < qreal(0.0))
- flags |= ItemStacksBehindParent;
- else
- flags &= ~ItemStacksBehindParent;
- d_ptr->flags = flags;
- }
-
- if ((flags & ItemStacksBehindParent) != (oldFlags & ItemStacksBehindParent)) {
- // NB! This check has to come after the ItemNegativeZStacksBehindParent
- // check above. Be careful.
-
- // Ensure child item sorting is up to date when toggling this flag.
- if (d_ptr->parent)
- d_ptr->parent->d_ptr->needSortChildren = 1;
- else if (d_ptr->scene)
- d_ptr->scene->d_func()->needSortTopLevelItems = 1;
- }
-
- if ((flags & ItemAcceptsInputMethod) != (oldFlags & ItemAcceptsInputMethod)) {
- // Update input method sensitivity in any views.
- if (d_ptr->scene)
- d_ptr->scene->d_func()->updateInputMethodSensitivityInViews();
- }
-
-
- if ((d_ptr->panelModality != NonModal)
- && d_ptr->scene
- && (flags & ItemIsPanel) != (oldFlags & ItemIsPanel)) {
- // update the panel's modal state
- if (flags & ItemIsPanel)
- d_ptr->scene->d_func()->enterModal(this);
- else
- d_ptr->scene->d_func()->leaveModal(this);
- }
-
- if (d_ptr->scene) {
- if ((flags & ItemSendsScenePositionChanges) != (oldFlags & ItemSendsScenePositionChanges)) {
- if (flags & ItemSendsScenePositionChanges)
- d_ptr->scene->d_func()->registerScenePosItem(this);
- else
- d_ptr->scene->d_func()->unregisterScenePosItem(this);
- }
- d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true);
- }
-
- // Notify change.
- itemChange(ItemFlagsHaveChanged, quint32(flags));
-}
-
-/*!
- \since 4.4
- Returns the cache mode for this item. The default mode is NoCache (i.e.,
- cache is disabled and all painting is immediate).
-
- \sa setCacheMode()
-*/
-QGraphicsItem::CacheMode QGraphicsItem::cacheMode() const
-{
- return QGraphicsItem::CacheMode(d_ptr->cacheMode);
-}
-
-/*!
- \since 4.4
- Sets the item's cache mode to \a mode.
-
- The optional \a logicalCacheSize argument is used only by
- ItemCoordinateCache mode, and describes the resolution of the cache
- buffer; if \a logicalCacheSize is (100, 100), QGraphicsItem will fit the
- item into 100x100 pixels in graphics memory, regardless of the logical
- size of the item itself. By default QGraphicsItem uses the size of
- boundingRect(). For all other cache modes than ItemCoordinateCache, \a
- logicalCacheSize is ignored.
-
- Caching can speed up rendering if your item spends a significant time
- redrawing itself. In some cases the cache can also slow down rendering, in
- particular when the item spends less time redrawing than QGraphicsItem
- spends redrawing from the cache. When enabled, the item's paint() function
- will be called only once for each call to update(); for any subsequent
- repaint requests, the Graphics View framework will redraw from the
- cache. This approach works particularly well with QGLWidget, which stores
- all the cache as OpenGL textures.
-
- Be aware that QPixmapCache's cache limit may need to be changed to obtain
- optimal performance.
-
- You can read more about the different cache modes in the CacheMode
- documentation.
-
- \sa CacheMode, QPixmapCache::setCacheLimit()
-*/
-void QGraphicsItem::setCacheMode(CacheMode mode, const QSize &logicalCacheSize)
-{
- CacheMode lastMode = CacheMode(d_ptr->cacheMode);
- d_ptr->cacheMode = mode;
- bool noVisualChange = (mode == NoCache && lastMode == NoCache)
- || (mode == NoCache && lastMode == DeviceCoordinateCache)
- || (mode == DeviceCoordinateCache && lastMode == NoCache)
- || (mode == DeviceCoordinateCache && lastMode == DeviceCoordinateCache);
- if (mode == NoCache) {
- d_ptr->removeExtraItemCache();
- } else {
- QGraphicsItemCache *cache = d_ptr->extraItemCache();
-
- // Reset old cache
- cache->purge();
-
- if (mode == ItemCoordinateCache) {
- if (lastMode == mode && cache->fixedSize == logicalCacheSize)
- noVisualChange = true;
- cache->fixedSize = logicalCacheSize;
- }
- }
- if (!noVisualChange)
- update();
-}
-
-/*!
- \since 4.6
-
- Returns the modality for this item.
-*/
-QGraphicsItem::PanelModality QGraphicsItem::panelModality() const
-{
- return d_ptr->panelModality;
-}
-
-/*!
- \since 4.6
-
- Sets the modality for this item to \a panelModality.
-
- Changing the modality of a visible item takes effect immediately.
-*/
-void QGraphicsItem::setPanelModality(PanelModality panelModality)
-{
- if (d_ptr->panelModality == panelModality)
- return;
-
- PanelModality previousModality = d_ptr->panelModality;
- bool enterLeaveModal = (isPanel() && d_ptr->scene && isVisible());
- if (enterLeaveModal && panelModality == NonModal)
- d_ptr->scene->d_func()->leaveModal(this);
- d_ptr->panelModality = panelModality;
- if (enterLeaveModal && d_ptr->panelModality != NonModal)
- d_ptr->scene->d_func()->enterModal(this, previousModality);
-}
-
-/*!
- \since 4.6
-
- Returns true if this item is blocked by a modal panel, false otherwise. If \a blockingPanel is
- non-zero, \a blockingPanel will be set to the modal panel that is blocking this item. If this
- item is not blocked, \a blockingPanel will not be set by this function.
-
- This function always returns false for items not in a scene.
-
- \sa panelModality() setPanelModality() PanelModality
-*/
-bool QGraphicsItem::isBlockedByModalPanel(QGraphicsItem **blockingPanel) const
-{
- if (!d_ptr->scene)
- return false;
-
-
- QGraphicsItem *dummy = 0;
- if (!blockingPanel)
- blockingPanel = &dummy;
-
- QGraphicsScenePrivate *scene_d = d_ptr->scene->d_func();
- if (scene_d->modalPanels.isEmpty())
- return false;
-
- // ###
- if (!scene_d->popupWidgets.isEmpty() && scene_d->popupWidgets.first() == this)
- return false;
-
- for (int i = 0; i < scene_d->modalPanels.count(); ++i) {
- QGraphicsItem *modalPanel = scene_d->modalPanels.at(i);
- if (modalPanel->panelModality() == QGraphicsItem::SceneModal) {
- // Scene modal panels block all non-descendents.
- if (modalPanel != this && !modalPanel->isAncestorOf(this)) {
- *blockingPanel = modalPanel;
- return true;
- }
- } else {
- // Window modal panels block ancestors and siblings/cousins.
- if (modalPanel != this
- && !modalPanel->isAncestorOf(this)
- && commonAncestorItem(modalPanel)) {
- *blockingPanel = modalPanel;
- return true;
- }
- }
- }
- return false;
-}
-
-#ifndef QT_NO_TOOLTIP
-/*!
- Returns the item's tool tip, or an empty QString if no tool tip has been
- set.
-
- \sa setToolTip(), QToolTip
-*/
-QString QGraphicsItem::toolTip() const
-{
- return d_ptr->extra(QGraphicsItemPrivate::ExtraToolTip).toString();
-}
-
-/*!
- Sets the item's tool tip to \a toolTip. If \a toolTip is empty, the item's
- tool tip is cleared.
-
- \sa toolTip(), QToolTip
-*/
-void QGraphicsItem::setToolTip(const QString &toolTip)
-{
- const QVariant toolTipVariant(itemChange(ItemToolTipChange, toolTip));
- d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant.toString());
- itemChange(ItemToolTipHasChanged, toolTipVariant);
-}
-#endif // QT_NO_TOOLTIP
-
-#ifndef QT_NO_CURSOR
-/*!
- Returns the current cursor shape for the item. The mouse cursor
- will assume this shape when it's over this item. See the \link
- Qt::CursorShape list of predefined cursor objects\endlink for a
- range of useful shapes.
-
- An editor item might want to use an I-beam cursor:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 2
-
- If no cursor has been set, the cursor of the item beneath is used.
-
- \sa setCursor(), hasCursor(), unsetCursor(), QWidget::cursor,
- QApplication::overrideCursor()
-*/
-QCursor QGraphicsItem::cursor() const
-{
- return qvariant_cast<QCursor>(d_ptr->extra(QGraphicsItemPrivate::ExtraCursor));
-}
-
-/*!
- Sets the current cursor shape for the item to \a cursor. The mouse cursor
- will assume this shape when it's over this item. See the \link
- Qt::CursorShape list of predefined cursor objects\endlink for a range of
- useful shapes.
-
- An editor item might want to use an I-beam cursor:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 3
-
- If no cursor has been set, the cursor of the item beneath is used.
-
- \sa cursor(), hasCursor(), unsetCursor(), QWidget::cursor,
- QApplication::overrideCursor()
-*/
-void QGraphicsItem::setCursor(const QCursor &cursor)
-{
- const QVariant cursorVariant(itemChange(ItemCursorChange, QVariant::fromValue<QCursor>(cursor)));
- d_ptr->setExtra(QGraphicsItemPrivate::ExtraCursor, qvariant_cast<QCursor>(cursorVariant));
- d_ptr->hasCursor = 1;
- if (d_ptr->scene) {
- d_ptr->scene->d_func()->allItemsUseDefaultCursor = false;
- foreach (QGraphicsView *view, d_ptr->scene->views()) {
- view->viewport()->setMouseTracking(true);
- // Note: Some of this logic is duplicated in QGraphicsView's mouse events.
- if (view->underMouse()) {
- foreach (QGraphicsItem *itemUnderCursor, view->items(view->mapFromGlobal(QCursor::pos()))) {
- if (itemUnderCursor->hasCursor()) {
- QMetaObject::invokeMethod(view, "_q_setViewportCursor",
- Q_ARG(QCursor, itemUnderCursor->cursor()));
- break;
- }
- }
- break;
- }
- }
- }
- itemChange(ItemCursorHasChanged, cursorVariant);
-}
-
-/*!
- Returns true if this item has a cursor set; otherwise, false is returned.
-
- By default, items don't have any cursor set. cursor() will return a
- standard pointing arrow cursor.
-
- \sa unsetCursor()
-*/
-bool QGraphicsItem::hasCursor() const
-{
- return d_ptr->hasCursor;
-}
-
-/*!
- Clears the cursor from this item.
-
- \sa hasCursor(), setCursor()
-*/
-void QGraphicsItem::unsetCursor()
-{
- d_ptr->unsetExtra(QGraphicsItemPrivate::ExtraCursor);
- d_ptr->hasCursor = 0;
- if (d_ptr->scene) {
- foreach (QGraphicsView *view, d_ptr->scene->views()) {
- if (view->underMouse() && view->itemAt(view->mapFromGlobal(QCursor::pos())) == this) {
- QMetaObject::invokeMethod(view, "_q_unsetViewportCursor");
- break;
- }
- }
- }
-}
-
-#endif // QT_NO_CURSOR
-
-/*!
- Returns true if the item is visible; otherwise, false is returned.
-
- Note that the item's general visibility is unrelated to whether or not it
- is actually being visualized by a QGraphicsView.
-
- \sa setVisible()
-*/
-bool QGraphicsItem::isVisible() const
-{
- return d_ptr->visible;
-}
-
-/*!
- \since 4.4
- Returns true if the item is visible to \a parent; otherwise, false is
- returned. \a parent can be 0, in which case this function will return
- whether the item is visible to the scene or not.
-
- An item may not be visible to its ancestors even if isVisible() is true. If
- any ancestor is hidden, the item itself will be implicitly hidden, in which
- case this function will return false.
-
- \sa isVisible(), setVisible()
-*/
-bool QGraphicsItem::isVisibleTo(const QGraphicsItem *parent) const
-{
- if (!d_ptr->visible)
- return false;
- if (parent == this)
- return true;
- if (parentItem() && parentItem()->isVisibleTo(parent))
- return true;
- if (!parent && !parentItem())
- return true;
- return false;
-}
-
-/*!
- \internal
-
- Sets this item's visibility to \a newVisible. If \a explicitly is true,
- this item will be "explicitly" \a newVisible; otherwise, it.. will not be.
-*/
-void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bool update)
-{
- Q_Q(QGraphicsItem);
-
- // Update explicit bit.
- if (explicitly)
- explicitlyHidden = newVisible ? 0 : 1;
-
- // Check if there's nothing to do.
- if (visible == quint32(newVisible))
- return;
-
- // Don't show child if parent is not visible
- if (parent && newVisible && !parent->d_ptr->visible)
- return;
-
- // Modify the property.
- const QVariant newVisibleVariant(q_ptr->itemChange(QGraphicsItem::ItemVisibleChange,
- quint32(newVisible)));
- newVisible = newVisibleVariant.toBool();
- if (visible == quint32(newVisible))
- return;
- visible = newVisible;
-
- // Schedule redrawing
- if (update) {
- QGraphicsItemCache *c = (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData));
- if (c)
- c->purge();
- if (scene) {
-#ifndef QT_NO_GRAPHICSEFFECT
- invalidateParentGraphicsEffectsRecursively();
-#endif //QT_NO_GRAPHICSEFFECT
- scene->d_func()->markDirty(q_ptr, QRectF(), /*invalidateChildren=*/false, /*force=*/true);
- }
- }
-
- // Certain properties are dropped as an item becomes invisible.
- bool hasFocus = q_ptr->hasFocus();
- if (!newVisible) {
- if (scene) {
- if (scene->d_func()->mouseGrabberItems.contains(q))
- q->ungrabMouse();
- if (scene->d_func()->keyboardGrabberItems.contains(q))
- q->ungrabKeyboard();
- if (q->isPanel() && panelModality != QGraphicsItem::NonModal)
- scene->d_func()->leaveModal(q_ptr);
- }
- if (hasFocus && scene) {
- // Hiding the closest non-panel ancestor of the focus item
- QGraphicsItem *focusItem = scene->focusItem();
- bool clear = true;
- if (isWidget && !focusItem->isPanel()) {
- do {
- if (focusItem == q_ptr) {
- clear = !static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true);
- break;
- }
- } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel());
- }
- if (clear)
- clearFocusHelper(/* giveFocusToParent = */ false);
- }
- if (q_ptr->isSelected())
- q_ptr->setSelected(false);
- } else {
- geometryChanged = 1;
- paintedViewBoundingRectsNeedRepaint = 1;
- if (scene) {
- if (isWidget) {
- QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(q_ptr);
- if (widget->windowType() == Qt::Popup)
- scene->d_func()->addPopup(widget);
- }
- if (q->isPanel() && panelModality != QGraphicsItem::NonModal) {
- scene->d_func()->enterModal(q_ptr);
- }
- }
- }
-
- // Update children with explicitly = false.
- const bool updateChildren = update && !(flags & QGraphicsItem::ItemClipsChildrenToShape);
- foreach (QGraphicsItem *child, children) {
- if (!newVisible || !child->d_ptr->explicitlyHidden)
- child->d_ptr->setVisibleHelper(newVisible, false, updateChildren);
- }
-
- // Update activation
- if (scene && q->isPanel()) {
- if (newVisible) {
- if (parent && parent->isActive())
- q->setActive(true);
- } else {
- if (q->isActive())
- scene->setActivePanel(parent);
- }
- }
-
- // Enable subfocus
- if (scene) {
- if (newVisible) {
- // Item is shown
- QGraphicsItem *p = parent;
- bool done = false;
- while (p) {
- if (p->flags() & QGraphicsItem::ItemIsFocusScope) {
- QGraphicsItem *fsi = p->d_ptr->focusScopeItem;
- if (q_ptr == fsi || q_ptr->isAncestorOf(fsi)) {
- done = true;
- while (fsi->d_ptr->focusScopeItem && fsi->d_ptr->focusScopeItem->isVisible())
- fsi = fsi->d_ptr->focusScopeItem;
- fsi->d_ptr->setFocusHelper(Qt::OtherFocusReason, /* climb = */ true,
- /* focusFromHide = */ false);
- }
- break;
- }
- p = p->d_ptr->parent;
- }
- if (!done) {
- QGraphicsItem *fi = subFocusItem;
- if (fi && fi != scene->focusItem()) {
- scene->setFocusItem(fi);
- } else if (flags & QGraphicsItem::ItemIsFocusScope &&
- !scene->focusItem() &&
- q->isAncestorOf(scene->d_func()->lastFocusItem)) {
- q_ptr->setFocus();
- }
- }
- } else {
- // Item is hidden
- if (hasFocus) {
- QGraphicsItem *p = parent;
- while (p) {
- if (p->flags() & QGraphicsItem::ItemIsFocusScope) {
- if (p->d_ptr->visible) {
- p->d_ptr->setFocusHelper(Qt::OtherFocusReason, /* climb = */ true,
- /* focusFromHide = */ true);
- }
- break;
- }
- p = p->d_ptr->parent;
- }
- }
- }
- }
-
- // Deliver post-change notification.
- q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisibleVariant);
-
- if (isObject)
- emit static_cast<QGraphicsObject *>(q_ptr)->visibleChanged();
-}
-
-/*!
- If \a visible is true, the item is made visible. Otherwise, the item is
- made invisible. Invisible items are not painted, nor do they receive any
- events. In particular, mouse events pass right through invisible items,
- and are delivered to any item that may be behind. Invisible items are also
- unselectable, they cannot take input focus, and are not detected by
- QGraphicsScene's item location functions.
-
- If an item becomes invisible while grabbing the mouse, (i.e., while it is
- receiving mouse events,) it will automatically lose the mouse grab, and
- the grab is not regained by making the item visible again; it must receive
- a new mouse press to regain the mouse grab.
-
- Similarly, an invisible item cannot have focus, so if the item has focus
- when it becomes invisible, it will lose focus, and the focus is not
- regained by simply making the item visible again.
-
- If you hide a parent item, all its children will also be hidden. If you
- show a parent item, all children will be shown, unless they have been
- explicitly hidden (i.e., if you call setVisible(false) on a child, it will
- not be reshown even if its parent is hidden, and then shown again).
-
- Items are visible by default; it is unnecessary to call
- setVisible() on a new item.
-
- \sa isVisible(), show(), hide()
-*/
-void QGraphicsItem::setVisible(bool visible)
-{
- d_ptr->setVisibleHelper(visible, /* explicit = */ true);
-}
-
-/*!
- \fn void QGraphicsItem::hide()
-
- Hides the item. (Items are visible by default.)
-
- This convenience function is equivalent to calling \c setVisible(false).
-
- \sa show(), setVisible()
-*/
-
-/*!
- \fn void QGraphicsItem::show()
-
- Shows the item. (Items are visible by default.)
-
- This convenience function is equivalent to calling \c setVisible(true).
-
- \sa hide(), setVisible()
-*/
-
-/*!
- Returns true if the item is enabled; otherwise, false is returned.
-
- \sa setEnabled()
-*/
-bool QGraphicsItem::isEnabled() const
-{
- return d_ptr->enabled;
-}
-
-/*!
- \internal
-
- Sets this item's visibility to \a newEnabled. If \a explicitly is true,
- this item will be "explicitly" \a newEnabled; otherwise, it.. will not be.
-*/
-void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bool update)
-{
- // Update explicit bit.
- if (explicitly)
- explicitlyDisabled = newEnabled ? 0 : 1;
-
- // Check if there's nothing to do.
- if (enabled == quint32(newEnabled))
- return;
-
- // Certain properties are dropped when an item is disabled.
- if (!newEnabled) {
- if (scene && scene->mouseGrabberItem() == q_ptr)
- q_ptr->ungrabMouse();
- if (q_ptr->hasFocus()) {
- // Disabling the closest non-panel ancestor of the focus item
- // causes focus to pop to the next item, otherwise it's cleared.
- QGraphicsItem *focusItem = scene->focusItem();
- bool clear = true;
- if (isWidget && !focusItem->isPanel() && q_ptr->isAncestorOf(focusItem)) {
- do {
- if (focusItem == q_ptr) {
- clear = !static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true);
- break;
- }
- } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel());
- }
- if (clear)
- q_ptr->clearFocus();
- }
- if (q_ptr->isSelected())
- q_ptr->setSelected(false);
- }
-
- // Modify the property.
- const QVariant newEnabledVariant(q_ptr->itemChange(QGraphicsItem::ItemEnabledChange,
- quint32(newEnabled)));
- enabled = newEnabledVariant.toBool();
-
- // Schedule redraw.
- if (update)
- q_ptr->update();
-
- foreach (QGraphicsItem *child, children) {
- if (!newEnabled || !child->d_ptr->explicitlyDisabled)
- child->d_ptr->setEnabledHelper(newEnabled, /* explicitly = */ false);
- }
-
- // Deliver post-change notification.
- q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabledVariant);
-
- if (isObject)
- emit static_cast<QGraphicsObject *>(q_ptr)->enabledChanged();
-}
-
-/*!
- If \a enabled is true, the item is enabled; otherwise, it is disabled.
-
- Disabled items are visible, but they do not receive any events, and cannot
- take focus nor be selected. Mouse events are discarded; they are not
- propagated unless the item is also invisible, or if it does not accept
- mouse events (see acceptedMouseButtons()). A disabled item cannot become the
- mouse grabber, and as a result of this, an item loses the grab if it
- becomes disabled when grabbing the mouse, just like it loses focus if it
- had focus when it was disabled.
-
- Disabled items are traditionally drawn using grayed-out colors (see \l
- QPalette::Disabled).
-
- If you disable a parent item, all its children will also be disabled. If
- you enable a parent item, all children will be enabled, unless they have
- been explicitly disabled (i.e., if you call setEnabled(false) on a child,
- it will not be reenabled if its parent is disabled, and then enabled
- again).
-
- Items are enabled by default.
-
- \note If you install an event filter, you can still intercept events
- before they are delivered to items; this mechanism disregards the item's
- enabled state.
-
- \sa isEnabled()
-*/
-void QGraphicsItem::setEnabled(bool enabled)
-{
- d_ptr->setEnabledHelper(enabled, /* explicitly = */ true);
-}
-
-/*!
- Returns true if this item is selected; otherwise, false is returned.
-
- Items that are in a group inherit the group's selected state.
-
- Items are not selected by default.
-
- \sa setSelected(), QGraphicsScene::setSelectionArea()
-*/
-bool QGraphicsItem::isSelected() const
-{
- if (QGraphicsItemGroup *group = this->group())
- return group->isSelected();
- return d_ptr->selected;
-}
-
-/*!
- If \a selected is true and this item is selectable, this item is selected;
- otherwise, it is unselected.
-
- If the item is in a group, the whole group's selected state is toggled by
- this function. If the group is selected, all items in the group are also
- selected, and if the group is not selected, no item in the group is
- selected.
-
- Only visible, enabled, selectable items can be selected. If \a selected
- is true and this item is either invisible or disabled or unselectable,
- this function does nothing.
-
- By default, items cannot be selected. To enable selection, set the
- ItemIsSelectable flag.
-
- This function is provided for convenience, allowing individual toggling of
- the selected state of an item. However, a more common way of selecting
- items is to call QGraphicsScene::setSelectionArea(), which will call this
- function for all visible, enabled, and selectable items within a specified
- area on the scene.
-
- \sa isSelected(), QGraphicsScene::selectedItems()
-*/
-void QGraphicsItem::setSelected(bool selected)
-{
- if (QGraphicsItemGroup *group = this->group()) {
- group->setSelected(selected);
- return;
- }
-
- if (!(d_ptr->flags & ItemIsSelectable) || !d_ptr->enabled || !d_ptr->visible)
- selected = false;
- if (d_ptr->selected == selected)
- return;
- const QVariant newSelectedVariant(itemChange(ItemSelectedChange, quint32(selected)));
- bool newSelected = newSelectedVariant.toBool();
- if (d_ptr->selected == newSelected)
- return;
- d_ptr->selected = newSelected;
-
- update();
- if (d_ptr->scene) {
- QGraphicsScenePrivate *sceneD = d_ptr->scene->d_func();
- if (selected) {
- sceneD->selectedItems << this;
- } else {
- // QGraphicsScene::selectedItems() lazily pulls out all items that are
- // no longer selected.
- }
- if (!sceneD->selectionChanging)
- emit d_ptr->scene->selectionChanged();
- }
-
- // Deliver post-change notification.
- itemChange(QGraphicsItem::ItemSelectedHasChanged, newSelectedVariant);
-}
-
-/*!
- \since 4.5
-
- Returns this item's local opacity, which is between 0.0 (transparent) and
- 1.0 (opaque). This value is combined with parent and ancestor values into
- the effectiveOpacity(). The effective opacity decides how the item is
- rendered.
-
- The opacity property decides the state of the painter passed to the
- paint() function. If the item is cached, i.e., ItemCoordinateCache or
- DeviceCoordinateCache, the effective property will be applied to the item's
- cache as it is rendered.
-
- The default opacity is 1.0; fully opaque.
-
- \sa setOpacity(), paint(), ItemIgnoresParentOpacity,
- ItemDoesntPropagateOpacityToChildren
-*/
-qreal QGraphicsItem::opacity() const
-{
- return d_ptr->opacity;
-}
-
-/*!
- \since 4.5
-
- Returns this item's \e effective opacity, which is between 0.0
- (transparent) and 1.0 (opaque). This value is a combination of this item's
- local opacity, and its parent and ancestors' opacities. The effective
- opacity decides how the item is rendered.
-
- \sa opacity(), setOpacity(), paint(), ItemIgnoresParentOpacity,
- ItemDoesntPropagateOpacityToChildren
-*/
-qreal QGraphicsItem::effectiveOpacity() const
-{
- return d_ptr->effectiveOpacity();
-}
-
-/*!
- \since 4.5
-
- Sets this item's local \a opacity, between 0.0 (transparent) and 1.0
- (opaque). The item's local opacity is combined with parent and ancestor
- opacities into the effectiveOpacity().
-
- By default, opacity propagates from parent to child, so if a parent's
- opacity is 0.5 and the child is also 0.5, the child's effective opacity
- will be 0.25.
-
- The opacity property decides the state of the painter passed to the
- paint() function. If the item is cached, i.e., ItemCoordinateCache or
- DeviceCoordinateCache, the effective property will be applied to the
- item's cache as it is rendered.
-
- There are two item flags that affect how the item's opacity is combined
- with the parent: ItemIgnoresParentOpacity and
- ItemDoesntPropagateOpacityToChildren.
-
- \sa opacity(), effectiveOpacity()
-*/
-void QGraphicsItem::setOpacity(qreal opacity)
-{
- // Notify change.
- const QVariant newOpacityVariant(itemChange(ItemOpacityChange, opacity));
-
- // Normalized opacity
- qreal newOpacity = qBound(qreal(0), newOpacityVariant.toReal(), qreal(1));
-
- // No change? Done.
- if (newOpacity == d_ptr->opacity)
- return;
-
- bool wasFullyTransparent = d_ptr->isOpacityNull();
- d_ptr->opacity = newOpacity;
-
- // Notify change.
- itemChange(ItemOpacityHasChanged, newOpacityVariant);
-
- // Update.
- if (d_ptr->scene) {
-#ifndef QT_NO_GRAPHICSEFFECT
- d_ptr->invalidateParentGraphicsEffectsRecursively();
- if (!(d_ptr->flags & ItemDoesntPropagateOpacityToChildren))
- d_ptr->invalidateChildGraphicsEffectsRecursively(QGraphicsItemPrivate::OpacityChanged);
-#endif //QT_NO_GRAPHICSEFFECT
- d_ptr->scene->d_func()->markDirty(this, QRectF(),
- /*invalidateChildren=*/true,
- /*force=*/false,
- /*ignoreOpacity=*/d_ptr->isOpacityNull());
- if (wasFullyTransparent)
- d_ptr->paintedViewBoundingRectsNeedRepaint = 1;
- }
-
- if (d_ptr->isObject)
- emit static_cast<QGraphicsObject *>(this)->opacityChanged();
-}
-
-/*!
- Returns a pointer to this item's effect if it has one; otherwise 0.
-
- \since 4.6
-*/
-#ifndef QT_NO_GRAPHICSEFFECT
-QGraphicsEffect *QGraphicsItem::graphicsEffect() const
-{
- return d_ptr->graphicsEffect;
-}
-
-/*!
- Sets \a effect as the item's effect. If there already is an effect installed
- on this item, QGraphicsItem will delete the existing effect before installing
- the new \a effect.
-
- If \a effect is the installed on a different item, setGraphicsEffect() will remove
- the effect from the item and install it on this item.
-
- QGraphicsItem takes ownership of \a effect.
-
- \note This function will apply the effect on itself and all its children.
-
- \since 4.6
-*/
-void QGraphicsItem::setGraphicsEffect(QGraphicsEffect *effect)
-{
- if (d_ptr->graphicsEffect == effect)
- return;
-
- if (d_ptr->graphicsEffect) {
- delete d_ptr->graphicsEffect;
- d_ptr->graphicsEffect = 0;
- } else if (d_ptr->parent) {
- d_ptr->parent->d_ptr->updateChildWithGraphicsEffectFlagRecursively();
- }
-
- if (effect) {
- // Set new effect.
- QGraphicsEffectSourcePrivate *sourced = new QGraphicsItemEffectSourcePrivate(this);
- QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
- d_ptr->graphicsEffect = effect;
- effect->d_func()->setGraphicsEffectSource(source);
- prepareGeometryChange();
- }
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-void QGraphicsItemPrivate::updateChildWithGraphicsEffectFlagRecursively()
-{
-#ifndef QT_NO_GRAPHICSEFFECT
- QGraphicsItemPrivate *itemPrivate = this;
- do {
- // parent chain already notified?
- if (itemPrivate->mayHaveChildWithGraphicsEffect)
- return;
- itemPrivate->mayHaveChildWithGraphicsEffect = 1;
- } while ((itemPrivate = itemPrivate->parent ? itemPrivate->parent->d_ptr.data() : 0));
-#endif
-}
-
-/*!
- \internal
- \since 4.6
- Returns the effective bounding rect of the given item space rect.
- If the item has no effect, the rect is returned unmodified.
- If the item has an effect, the effective rect can be extend beyond the
- item's bounding rect, depending on the effect.
-
- \sa boundingRect()
-*/
-QRectF QGraphicsItemPrivate::effectiveBoundingRect(const QRectF &rect) const
-{
-#ifndef QT_NO_GRAPHICSEFFECT
- Q_Q(const QGraphicsItem);
- QGraphicsEffect *effect = graphicsEffect;
- if (scene && effect && effect->isEnabled()) {
- if (scene->d_func()->views.isEmpty())
- return effect->boundingRectFor(rect);
- QRectF sceneRect = q->mapRectToScene(rect);
- QRectF sceneEffectRect;
- foreach (QGraphicsView *view, scene->views()) {
- QRectF deviceRect = view->d_func()->mapRectFromScene(sceneRect);
- QRect deviceEffectRect = effect->boundingRectFor(deviceRect).toAlignedRect();
- sceneEffectRect |= view->d_func()->mapRectToScene(deviceEffectRect);
- }
- return q->mapRectFromScene(sceneEffectRect);
- }
-#endif //QT_NO_GRAPHICSEFFECT
- return rect;
-}
-
-/*!
- \internal
- \since 4.6
- Returns the effective bounding rect of the item.
- If the item has no effect, this is the same as the item's bounding rect.
- If the item has an effect, the effective rect can be larger than the item's
- bouding rect, depending on the effect.
-
- \sa boundingRect()
-*/
-QRectF QGraphicsItemPrivate::effectiveBoundingRect(QGraphicsItem *topMostEffectItem) const
-{
-#ifndef QT_NO_GRAPHICSEFFECT
- Q_Q(const QGraphicsItem);
- QRectF brect = effectiveBoundingRect(q_ptr->boundingRect());
- if (ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren || topMostEffectItem == q)
- return brect;
-
- const QGraphicsItem *effectParent = parent;
- while (effectParent) {
- QGraphicsEffect *effect = effectParent->d_ptr->graphicsEffect;
- if (scene && effect && effect->isEnabled()) {
- const QRectF brectInParentSpace = q->mapRectToItem(effectParent, brect);
- const QRectF effectRectInParentSpace = effectParent->d_ptr->effectiveBoundingRect(brectInParentSpace);
- brect = effectParent->mapRectToItem(q, effectRectInParentSpace);
- }
- if (effectParent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren
- || topMostEffectItem == effectParent) {
- return brect;
- }
- effectParent = effectParent->d_ptr->parent;
- }
-
- return brect;
-#else //QT_NO_GRAPHICSEFFECT
- return q_ptr->boundingRect();
-#endif //QT_NO_GRAPHICSEFFECT
-
-}
-
-/*!
- \internal
- \since 4.6
- Returns the effective bounding rect of this item in scene coordinates,
- by combining sceneTransform() with boundingRect(), taking into account
- the effect that the item might have.
-
- If the item has no effect, this is the same as sceneBoundingRect().
-
- \sa effectiveBoundingRect(), sceneBoundingRect()
-*/
-QRectF QGraphicsItemPrivate::sceneEffectiveBoundingRect() const
-{
- // Find translate-only offset
- // COMBINE
- QPointF offset;
- const QGraphicsItem *parentItem = q_ptr;
- const QGraphicsItemPrivate *itemd;
- do {
- itemd = parentItem->d_ptr.data();
- if (itemd->transformData)
- break;
- offset += itemd->pos;
- } while ((parentItem = itemd->parent));
-
- QRectF br = effectiveBoundingRect();
- br.translate(offset);
- return !parentItem ? br : parentItem->sceneTransform().mapRect(br);
-}
-
-/*!
- Returns true if this item can accept drag and drop events; otherwise,
- returns false. By default, items do not accept drag and drop events; items
- are transparent to drag and drop.
-
- \sa setAcceptDrops()
-*/
-bool QGraphicsItem::acceptDrops() const
-{
- return d_ptr->acceptDrops;
-}
-
-/*!
- If \a on is true, this item will accept drag and drop events; otherwise,
- it is transparent for drag and drop events. By default, items do not
- accept drag and drop events.
-
- \sa acceptDrops()
-*/
-void QGraphicsItem::setAcceptDrops(bool on)
-{
- d_ptr->acceptDrops = on;
-}
-
-/*!
- Returns the mouse buttons that this item accepts mouse events for. By
- default, all mouse buttons are accepted.
-
- If an item accepts a mouse button, it will become the mouse
- grabber item when a mouse press event is delivered for that mouse
- button. However, if the item does not accept the button,
- QGraphicsScene will forward the mouse events to the first item
- beneath it that does.
-
- \sa setAcceptedMouseButtons(), mousePressEvent()
-*/
-Qt::MouseButtons QGraphicsItem::acceptedMouseButtons() const
-{
- return Qt::MouseButtons(d_ptr->acceptedMouseButtons);
-}
-
-/*!
- Sets the mouse \a buttons that this item accepts mouse events for.
-
- By default, all mouse buttons are accepted. If an item accepts a
- mouse button, it will become the mouse grabber item when a mouse
- press event is delivered for that button. However, if the item
- does not accept the mouse button, QGraphicsScene will forward the
- mouse events to the first item beneath it that does.
-
- To disable mouse events for an item (i.e., make it transparent for mouse
- events), call setAcceptedMouseButtons(0).
-
- \sa acceptedMouseButtons(), mousePressEvent()
-*/
-void QGraphicsItem::setAcceptedMouseButtons(Qt::MouseButtons buttons)
-{
- if (Qt::MouseButtons(d_ptr->acceptedMouseButtons) != buttons) {
- if (buttons == 0 && d_ptr->scene && d_ptr->scene->mouseGrabberItem() == this
- && d_ptr->scene->d_func()->lastMouseGrabberItemHasImplicitMouseGrab) {
- ungrabMouse();
- }
- d_ptr->acceptedMouseButtons = quint32(buttons);
- }
-}
-
-/*!
- \since 4.4
-
- Returns true if an item accepts hover events
- (QGraphicsSceneHoverEvent); otherwise, returns false. By default,
- items do not accept hover events.
-
- \sa setAcceptedMouseButtons()
-*/
-bool QGraphicsItem::acceptHoverEvents() const
-{
- return d_ptr->acceptsHover;
-}
-
-/*!
- \obsolete
-
- Call acceptHoverEvents() instead.
-*/
-bool QGraphicsItem::acceptsHoverEvents() const
-{
- return d_ptr->acceptsHover;
-}
-
-/*!
- \since 4.4
-
- If \a enabled is true, this item will accept hover events;
- otherwise, it will ignore them. By default, items do not accept
- hover events.
-
- Hover events are delivered when there is no current mouse grabber
- item. They are sent when the mouse cursor enters an item, when it
- moves around inside the item, and when the cursor leaves an
- item. Hover events are commonly used to highlight an item when
- it's entered, and for tracking the mouse cursor as it hovers over
- the item (equivalent to QWidget::mouseTracking).
-
- Parent items receive hover enter events before their children, and
- leave events after their children. The parent does not receive a
- hover leave event if the cursor enters a child, though; the parent
- stays "hovered" until the cursor leaves its area, including its
- children's areas.
-
- If a parent item handles child events, it will receive hover move,
- drag move, and drop events as the cursor passes through its
- children, but it does not receive hover enter and hover leave, nor
- drag enter and drag leave events on behalf of its children.
-
- A QGraphicsWidget with window decorations will accept hover events
- regardless of the value of acceptHoverEvents().
-
- \sa acceptHoverEvents(), hoverEnterEvent(), hoverMoveEvent(),
- hoverLeaveEvent()
-*/
-void QGraphicsItem::setAcceptHoverEvents(bool enabled)
-{
- if (d_ptr->acceptsHover == quint32(enabled))
- return;
- d_ptr->acceptsHover = quint32(enabled);
- if (d_ptr->acceptsHover && d_ptr->scene && d_ptr->scene->d_func()->allItemsIgnoreHoverEvents) {
- d_ptr->scene->d_func()->allItemsIgnoreHoverEvents = false;
- d_ptr->scene->d_func()->enableMouseTrackingOnViews();
- }
-}
-
-/*!
- \obsolete
-
- Use setAcceptHoverEvents(\a enabled) instead.
-*/
-void QGraphicsItem::setAcceptsHoverEvents(bool enabled)
-{
- setAcceptHoverEvents(enabled);
-}
-
-/*! \since 4.6
-
- Returns true if an item accepts \l{QTouchEvent}{touch events};
- otherwise, returns false. By default, items do not accept touch events.
-
- \sa setAcceptTouchEvents()
-*/
-bool QGraphicsItem::acceptTouchEvents() const
-{
- return d_ptr->acceptTouchEvents;
-}
-
-/*!
- \since 4.6
-
- If \a enabled is true, this item will accept \l{QTouchEvent}{touch events};
- otherwise, it will ignore them. By default, items do not accept
- touch events.
-*/
-void QGraphicsItem::setAcceptTouchEvents(bool enabled)
-{
- if (d_ptr->acceptTouchEvents == quint32(enabled))
- return;
- d_ptr->acceptTouchEvents = quint32(enabled);
- if (d_ptr->acceptTouchEvents && d_ptr->scene && d_ptr->scene->d_func()->allItemsIgnoreTouchEvents) {
- d_ptr->scene->d_func()->allItemsIgnoreTouchEvents = false;
- d_ptr->scene->d_func()->enableTouchEventsOnViews();
- }
-}
-
-/*!
- \since 4.6
-
- Returns true if this item filters child events (i.e., all events
- intended for any of its children are instead sent to this item);
- otherwise, false is returned.
-
- The default value is false; child events are not filtered.
-
- \sa setFiltersChildEvents()
-*/
-bool QGraphicsItem::filtersChildEvents() const
-{
- return d_ptr->filtersDescendantEvents;
-}
-
-/*!
- \since 4.6
-
- If \a enabled is true, this item is set to filter all events for
- all its children (i.e., all events intented for any of its
- children are instead sent to this item); otherwise, if \a enabled
- is false, this item will only handle its own events. The default
- value is false.
-
- \sa filtersChildEvents()
-*/
-void QGraphicsItem::setFiltersChildEvents(bool enabled)
-{
- if (d_ptr->filtersDescendantEvents == enabled)
- return;
-
- d_ptr->filtersDescendantEvents = enabled;
- d_ptr->updateAncestorFlag(QGraphicsItem::GraphicsItemFlag(-2));
-}
-
-/*!
- \obsolete
-
- Returns true if this item handles child events (i.e., all events
- intended for any of its children are instead sent to this item);
- otherwise, false is returned.
-
- This property is useful for item groups; it allows one item to
- handle events on behalf of its children, as opposed to its
- children handling their events individually.
-
- The default is to return false; children handle their own events.
- The exception for this is if the item is a QGraphicsItemGroup, then
- it defaults to return true.
-
- \sa setHandlesChildEvents()
-*/
-bool QGraphicsItem::handlesChildEvents() const
-{
- return d_ptr->handlesChildEvents;
-}
-
-/*!
- \obsolete
-
- If \a enabled is true, this item is set to handle all events for
- all its children (i.e., all events intented for any of its
- children are instead sent to this item); otherwise, if \a enabled
- is false, this item will only handle its own events. The default
- value is false.
-
- This property is useful for item groups; it allows one item to
- handle events on behalf of its children, as opposed to its
- children handling their events individually.
-
- If a child item accepts hover events, its parent will receive
- hover move events as the cursor passes through the child, but it
- does not receive hover enter and hover leave events on behalf of
- its child.
-
- \sa handlesChildEvents()
-*/
-void QGraphicsItem::setHandlesChildEvents(bool enabled)
-{
- if (d_ptr->handlesChildEvents == enabled)
- return;
-
- d_ptr->handlesChildEvents = enabled;
- d_ptr->updateAncestorFlag(QGraphicsItem::GraphicsItemFlag(-1));
-}
-/*!
- \since 4.6
- Returns true if this item is active; otherwise returns false.
-
- An item can only be active if the scene is active. An item is active
- if it is, or is a descendent of, an active panel. Items in non-active
- panels are not active.
-
- Items that are not part of a panel follow scene activation when the
- scene has no active panel.
-
- Only active items can gain input focus.
-
- \sa QGraphicsScene::isActive(), QGraphicsScene::activePanel(), panel(), isPanel()
-*/
-bool QGraphicsItem::isActive() const
-{
- if (!d_ptr->scene || !d_ptr->scene->isActive())
- return false;
- return panel() == d_ptr->scene->activePanel();
-}
-
-/*!
- \since 4.6
-
- If \a active is true, and the scene is active, this item's panel will be
- activated. Otherwise, the panel is deactivated.
-
- If the item is not part of an active scene, \a active will decide what
- happens to the panel when the scene becomes active or the item is added to
- the scene. If true, the item's panel will be activated when the item is
- either added to the scene or the scene is activated. Otherwise, the item
- will stay inactive independent of the scene's activated state.
-
- \sa isPanel(), QGraphicsScene::setActivePanel(), QGraphicsScene::isActive()
-*/
-void QGraphicsItem::setActive(bool active)
-{
- d_ptr->explicitActivate = 1;
- d_ptr->wantsActive = active;
- if (d_ptr->scene) {
- if (active) {
- // Activate this item.
- d_ptr->scene->setActivePanel(this);
- } else {
- // Deactivate this item, and reactivate the last active item
- // (if any).
- QGraphicsItem *lastActive = d_ptr->scene->d_func()->lastActivePanel;
- d_ptr->scene->setActivePanel(lastActive != this ? lastActive : 0);
- }
- }
-}
-
-/*!
- Returns true if this item is active, and it or its \l{focusProxy()}{focus
- proxy} has keyboard input focus; otherwise, returns false.
-
- \sa focusItem(), setFocus(), QGraphicsScene::setFocusItem(), isActive()
-*/
-bool QGraphicsItem::hasFocus() const
-{
- if (!d_ptr->scene || !d_ptr->scene->isActive())
- return false;
-
- if (d_ptr->focusProxy)
- return d_ptr->focusProxy->hasFocus();
-
- if (d_ptr->scene->d_func()->focusItem != this)
- return false;
-
- return panel() == d_ptr->scene->d_func()->activePanel;
-}
-
-/*!
- Gives keyboard input focus to this item. The \a focusReason argument will
- be passed into any \l{QFocusEvent}{focus event} generated by this function;
- it is used to give an explanation of what caused the item to get focus.
-
- Only enabled items that set the ItemIsFocusable flag can accept keyboard
- focus.
-
- If this item is not visible, not active, or not associated with a scene,
- it will not gain immediate input focus. However, it will be registered as
- the preferred focus item for its subtree of items, should it later become
- visible.
-
- As a result of calling this function, this item will receive a
- \l{focusInEvent()}{focus in event} with \a focusReason. If another item
- already has focus, that item will first receive a \l{focusOutEvent()}
- {focus out event} indicating that it has lost input focus.
-
- \sa clearFocus(), hasFocus(), focusItem(), focusProxy()
-*/
-void QGraphicsItem::setFocus(Qt::FocusReason focusReason)
-{
- d_ptr->setFocusHelper(focusReason, /* climb = */ true, /* focusFromHide = */ false);
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::setFocusHelper(Qt::FocusReason focusReason, bool climb, bool focusFromHide)
-{
- // Disabled / unfocusable items cannot accept focus.
- if (!q_ptr->isEnabled() || !(flags & QGraphicsItem::ItemIsFocusable))
- return;
-
- // Find focus proxy.
- QGraphicsItem *f = q_ptr;
- while (f->d_ptr->focusProxy)
- f = f->d_ptr->focusProxy;
-
- // Return if it already has focus.
- if (scene && scene->focusItem() == f)
- return;
-
- // Update focus scope item ptr.
- QGraphicsItem *p = parent;
- while (p) {
- if (p->flags() & QGraphicsItem::ItemIsFocusScope) {
- QGraphicsItem *oldFocusScopeItem = p->d_ptr->focusScopeItem;
- p->d_ptr->focusScopeItem = q_ptr;
- if (!p->focusItem() && !focusFromHide) {
- if (oldFocusScopeItem)
- oldFocusScopeItem->d_ptr->focusScopeItemChange(false);
- focusScopeItemChange(true);
- // If you call setFocus on a child of a focus scope that
- // doesn't currently have a focus item, then stop.
- return;
- }
- break;
- }
- p = p->d_ptr->parent;
- }
-
- if (climb) {
- while (f->d_ptr->focusScopeItem && f->d_ptr->focusScopeItem->isVisible())
- f = f->d_ptr->focusScopeItem;
- }
-
- // Update the child focus chain.
- QGraphicsItem *commonAncestor = 0;
- if (scene && scene->focusItem()) {
- commonAncestor = scene->focusItem()->commonAncestorItem(f);
- scene->focusItem()->d_ptr->clearSubFocus(scene->focusItem(), commonAncestor);
- }
-
- f->d_ptr->setSubFocus(f, commonAncestor);
-
- // Update the scene's focus item.
- if (scene) {
- QGraphicsItem *p = q_ptr->panel();
- if ((!p && scene->isActive()) || (p && p->isActive())) {
- // Visible items immediately gain focus from scene.
- scene->d_func()->setFocusItemHelper(f, focusReason);
- }
- }
-}
-
-/*!
- Takes keyboard input focus from the item.
-
- If it has focus, a \l{focusOutEvent()}{focus out event} is sent to this
- item to tell it that it is about to lose the focus.
-
- Only items that set the ItemIsFocusable flag, or widgets that set an
- appropriate focus policy, can accept keyboard focus.
-
- \sa setFocus(), hasFocus(), QGraphicsWidget::focusPolicy
-*/
-void QGraphicsItem::clearFocus()
-{
- d_ptr->clearFocusHelper(/* giveFocusToParent = */ true);
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::clearFocusHelper(bool giveFocusToParent)
-{
- if (giveFocusToParent) {
- // Pass focus to the closest parent focus scope
- if (!inDestructor) {
- QGraphicsItem *p = parent;
- while (p) {
- if (p->flags() & QGraphicsItem::ItemIsFocusScope) {
- if (p->d_ptr->focusScopeItem == q_ptr) {
- p->d_ptr->focusScopeItem = 0;
- if (!q_ptr->hasFocus()) //if it has focus, focusScopeItemChange is called elsewhere
- focusScopeItemChange(false);
- }
- if (q_ptr->hasFocus())
- p->d_ptr->setFocusHelper(Qt::OtherFocusReason, /* climb = */ false,
- /* focusFromHide = */ false);
- return;
- }
- p = p->d_ptr->parent;
- }
- }
- }
-
- if (q_ptr->hasFocus()) {
- // Invisible items with focus must explicitly clear subfocus.
- clearSubFocus(q_ptr);
-
- // If this item has the scene's input focus, clear it.
- scene->setFocusItem(0);
- }
-}
-
-/*!
- \since 4.6
-
- Returns this item's focus proxy, or 0 if this item has no
- focus proxy.
-
- \sa setFocusProxy(), setFocus(), hasFocus()
-*/
-QGraphicsItem *QGraphicsItem::focusProxy() const
-{
- return d_ptr->focusProxy;
-}
-
-/*!
- \since 4.6
-
- Sets the item's focus proxy to \a item.
-
- If an item has a focus proxy, the focus proxy will receive
- input focus when the item gains input focus. The item itself
- will still have focus (i.e., hasFocus() will return true),
- but only the focus proxy will receive the keyboard input.
-
- A focus proxy can itself have a focus proxy, and so on. In
- such case, keyboard input will be handled by the outermost
- focus proxy.
-
- The focus proxy \a item must belong to the same scene as
- this item.
-
- \sa focusProxy(), setFocus(), hasFocus()
-*/
-void QGraphicsItem::setFocusProxy(QGraphicsItem *item)
-{
- if (item == d_ptr->focusProxy)
- return;
- if (item == this) {
- qWarning("QGraphicsItem::setFocusProxy: cannot assign self as focus proxy");
- return;
- }
- if (item) {
- if (item->d_ptr->scene != d_ptr->scene) {
- qWarning("QGraphicsItem::setFocusProxy: focus proxy must be in same scene");
- return;
- }
- for (QGraphicsItem *f = item->focusProxy(); f != 0; f = f->focusProxy()) {
- if (f == this) {
- qWarning("QGraphicsItem::setFocusProxy: %p is already in the focus proxy chain", item);
- return;
- }
- }
- }
-
- QGraphicsItem *lastFocusProxy = d_ptr->focusProxy;
- if (lastFocusProxy)
- lastFocusProxy->d_ptr->focusProxyRefs.removeOne(&d_ptr->focusProxy);
- d_ptr->focusProxy = item;
- if (item)
- item->d_ptr->focusProxyRefs << &d_ptr->focusProxy;
-}
-
-/*!
- \since 4.6
-
- If this item, a child or descendant of this item currently has input
- focus, this function will return a pointer to that item. If
- no descendant has input focus, 0 is returned.
-
- \sa hasFocus(), setFocus(), QWidget::focusWidget()
-*/
-QGraphicsItem *QGraphicsItem::focusItem() const
-{
- return d_ptr->subFocusItem;
-}
-
-/*!
- \internal
-
- Returns this item's focus scope item.
-*/
-QGraphicsItem *QGraphicsItem::focusScopeItem() const
-{
- return d_ptr->focusScopeItem;
-}
-
-/*!
- \since 4.4
- Grabs the mouse input.
-
- This item will receive all mouse events for the scene until any of the
- following events occurs:
-
- \list
- \o The item becomes invisible
- \o The item is removed from the scene
- \o The item is deleted
- \o The item call ungrabMouse()
- \o Another item calls grabMouse(); the item will regain the mouse grab
- when the other item calls ungrabMouse().
- \endlist
-
- When an item gains the mouse grab, it receives a QEvent::GrabMouse
- event. When it loses the mouse grab, it receives a QEvent::UngrabMouse
- event. These events can be used to detect when your item gains or loses
- the mouse grab through other means than receiving mouse button events.
-
- It is almost never necessary to explicitly grab the mouse in Qt, as Qt
- grabs and releases it sensibly. In particular, Qt grabs the mouse when you
- press a mouse button, and keeps the mouse grabbed until you release the
- last mouse button. Also, Qt::Popup widgets implicitly call grabMouse()
- when shown, and ungrabMouse() when hidden.
-
- Note that only visible items can grab mouse input. Calling grabMouse() on
- an invisible item has no effect.
-
- Keyboard events are not affected.
-
- \sa QGraphicsScene::mouseGrabberItem(), ungrabMouse(), grabKeyboard()
-*/
-void QGraphicsItem::grabMouse()
-{
- if (!d_ptr->scene) {
- qWarning("QGraphicsItem::grabMouse: cannot grab mouse without scene");
- return;
- }
- if (!d_ptr->visible) {
- qWarning("QGraphicsItem::grabMouse: cannot grab mouse while invisible");
- return;
- }
- d_ptr->scene->d_func()->grabMouse(this);
-}
-
-/*!
- \since 4.4
- Releases the mouse grab.
-
- \sa grabMouse(), ungrabKeyboard()
-*/
-void QGraphicsItem::ungrabMouse()
-{
- if (!d_ptr->scene) {
- qWarning("QGraphicsItem::ungrabMouse: cannot ungrab mouse without scene");
- return;
- }
- d_ptr->scene->d_func()->ungrabMouse(this);
-}
-
-/*!
- \since 4.4
- Grabs the keyboard input.
-
- The item will receive all keyboard input to the scene until one of the
- following events occur:
-
- \list
- \o The item becomes invisible
- \o The item is removed from the scene
- \o The item is deleted
- \o The item calls ungrabKeyboard()
- \o Another item calls grabKeyboard(); the item will regain the keyboard grab
- when the other item calls ungrabKeyboard().
- \endlist
-
- When an item gains the keyboard grab, it receives a QEvent::GrabKeyboard
- event. When it loses the keyboard grab, it receives a
- QEvent::UngrabKeyboard event. These events can be used to detect when your
- item gains or loses the keyboard grab through other means than gaining
- input focus.
-
- It is almost never necessary to explicitly grab the keyboard in Qt, as Qt
- grabs and releases it sensibly. In particular, Qt grabs the keyboard when
- your item gains input focus, and releases it when your item loses input
- focus, or when the item is hidden.
-
- Note that only visible items can grab keyboard input. Calling
- grabKeyboard() on an invisible item has no effect.
-
- Keyboard events are not affected.
-
- \sa ungrabKeyboard(), grabMouse(), setFocus()
-*/
-void QGraphicsItem::grabKeyboard()
-{
- if (!d_ptr->scene) {
- qWarning("QGraphicsItem::grabKeyboard: cannot grab keyboard without scene");
- return;
- }
- if (!d_ptr->visible) {
- qWarning("QGraphicsItem::grabKeyboard: cannot grab keyboard while invisible");
- return;
- }
- d_ptr->scene->d_func()->grabKeyboard(this);
-}
-
-/*!
- \since 4.4
- Releases the keyboard grab.
-
- \sa grabKeyboard(), ungrabMouse()
-*/
-void QGraphicsItem::ungrabKeyboard()
-{
- if (!d_ptr->scene) {
- qWarning("QGraphicsItem::ungrabKeyboard: cannot ungrab keyboard without scene");
- return;
- }
- d_ptr->scene->d_func()->ungrabKeyboard(this);
-}
-
-/*!
- Returns the position of the item in parent coordinates. If the item has no
- parent, its position is given in scene coordinates.
-
- The position of the item describes its origin (local coordinate
- (0, 0)) in parent coordinates; this function returns the same as
- mapToParent(0, 0).
-
- For convenience, you can also call scenePos() to determine the
- item's position in scene coordinates, regardless of its parent.
-
- \sa x(), y(), setPos(), transform(), {The Graphics View Coordinate System}
-*/
-QPointF QGraphicsItem::pos() const
-{
- return d_ptr->pos;
-}
-
-/*!
- \fn QGraphicsItem::x() const
-
- This convenience function is equivalent to calling pos().x().
-
- \sa y()
-*/
-
-/*!
- \since 4.6
-
- Set's the \a x coordinate of the item's position. Equivalent to
- calling setPos(x, y()).
-
- \sa x(), setPos()
-*/
-void QGraphicsItem::setX(qreal x)
-{
- if (d_ptr->inDestructor)
- return;
-
- if (qIsNaN(x))
- return;
-
- setPos(QPointF(x, d_ptr->pos.y()));
-}
-
-/*!
- \fn QGraphicsItem::y() const
-
- This convenience function is equivalent to calling pos().y().
-
- \sa x()
-*/
-
-/*!
- \since 4.6
-
- Set's the \a y coordinate of the item's position. Equivalent to
- calling setPos(x(), y).
-
- \sa x(), setPos()
-*/
-void QGraphicsItem::setY(qreal y)
-{
- if (d_ptr->inDestructor)
- return;
-
- if (qIsNaN(y))
- return;
-
- setPos(QPointF(d_ptr->pos.x(), y));
-}
-
-/*!
- Returns the item's position in scene coordinates. This is
- equivalent to calling \c mapToScene(0, 0).
-
- \sa pos(), sceneTransform(), {The Graphics View Coordinate System}
-*/
-QPointF QGraphicsItem::scenePos() const
-{
- return mapToScene(0, 0);
-}
-
-/*!
- \internal
-
- Sets the position \a pos.
-*/
-void QGraphicsItemPrivate::setPosHelper(const QPointF &pos)
-{
- Q_Q(QGraphicsItem);
- inSetPosHelper = 1;
- if (scene)
- q->prepareGeometryChange();
- QPointF oldPos = this->pos;
- this->pos = pos;
- dirtySceneTransform = 1;
- inSetPosHelper = 0;
- if (isObject) {
- if (pos.x() != oldPos.x())
- emit static_cast<QGraphicsObject *>(q_ptr)->xChanged();
- if (pos.y() != oldPos.y())
- emit static_cast<QGraphicsObject *>(q_ptr)->yChanged();
- }
-}
-
-/*!
- \internal
-
- Sets the transform \a transform.
-*/
-void QGraphicsItemPrivate::setTransformHelper(const QTransform &transform)
-{
- q_ptr->prepareGeometryChange();
- transformData->transform = transform;
- dirtySceneTransform = 1;
- transformChanged();
-}
-
-/*!
- Sets the position of the item to \a pos, which is in parent
- coordinates. For items with no parent, \a pos is in scene
- coordinates.
-
- The position of the item describes its origin (local coordinate
- (0, 0)) in parent coordinates.
-
- \sa pos(), scenePos(), {The Graphics View Coordinate System}
-*/
-void QGraphicsItem::setPos(const QPointF &pos)
-{
- if (d_ptr->pos == pos)
- return;
-
- if (d_ptr->inDestructor)
- return;
-
- // Update and repositition.
- if (!(d_ptr->flags & (ItemSendsGeometryChanges | ItemSendsScenePositionChanges))) {
- d_ptr->setPosHelper(pos);
- if (d_ptr->isWidget)
- static_cast<QGraphicsWidget *>(this)->d_func()->setGeometryFromSetPos();
- if (d_ptr->scenePosDescendants)
- d_ptr->sendScenePosChange();
- return;
- }
-
- // Notify the item that the position is changing.
- const QVariant newPosVariant(itemChange(ItemPositionChange, QVariant::fromValue<QPointF>(pos)));
- QPointF newPos = newPosVariant.toPointF();
- if (newPos == d_ptr->pos)
- return;
-
- // Update and repositition.
- d_ptr->setPosHelper(newPos);
-
- // Send post-notification.
- itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant);
- d_ptr->sendScenePosChange();
-}
-
-/*!
- \fn void QGraphicsItem::setPos(qreal x, qreal y)
- \overload
-
- This convenience function is equivalent to calling setPos(QPointF(\a x, \a
- y)).
-*/
-
-/*!
- \fn void QGraphicsItem::moveBy(qreal dx, qreal dy)
-
- Moves the item by \a dx points horizontally, and \a dy point
- vertically. This function is equivalent to calling setPos(pos() +
- QPointF(\a dx, \a dy)).
-*/
-
-/*!
- If this item is part of a scene that is viewed by a QGraphicsView, this
- convenience function will attempt to scroll the view to ensure that \a
- rect is visible inside the view's viewport. If \a rect is a null rect (the
- default), QGraphicsItem will default to the item's bounding rect. \a xmargin
- and \a ymargin are the number of pixels the view should use for margins.
-
- If the specified rect cannot be reached, the contents are scrolled to the
- nearest valid position.
-
- If this item is not viewed by a QGraphicsView, this function does nothing.
-
- \sa QGraphicsView::ensureVisible()
-*/
-void QGraphicsItem::ensureVisible(const QRectF &rect, int xmargin, int ymargin)
-{
- if (d_ptr->scene) {
- QRectF sceneRect;
- if (!rect.isNull())
- sceneRect = sceneTransform().mapRect(rect);
- else
- sceneRect = sceneBoundingRect();
- foreach (QGraphicsView *view, d_ptr->scene->d_func()->views)
- view->ensureVisible(sceneRect, xmargin, ymargin);
- }
-}
-
-/*!
- \fn void QGraphicsItem::ensureVisible(qreal x, qreal y, qreal w, qreal h,
- int xmargin = 50, int ymargin = 50)
-
- This convenience function is equivalent to calling
- ensureVisible(QRectF(\a x, \a y, \a w, \a h), \a xmargin, \a ymargin):
-*/
-
-/*!
- \obsolete
-
- Returns the item's affine transformation matrix. This is a subset or the
- item's full transformation matrix, and might not represent the item's full
- transformation.
-
- Use transform() instead.
-
- \sa setTransform(), sceneTransform()
-*/
-QMatrix QGraphicsItem::matrix() const
-{
- return transform().toAffine();
-}
-
-/*!
- \since 4.3
-
- Returns this item's transformation matrix.
-
- The transformation matrix is combined with the item's rotation(), scale()
- and transformations() into a combined transformations for the item.
-
- The default transformation matrix is an identity matrix.
-
- \sa setTransform(), sceneTransform()
-*/
-QTransform QGraphicsItem::transform() const
-{
- if (!d_ptr->transformData)
- return QTransform();
- return d_ptr->transformData->transform;
-}
-
-/*!
- \since 4.6
-
- Returns the clockwise rotation, in degrees, around the Z axis. The default
- value is 0 (i.e., the item is not rotated).
-
- The rotation is combined with the item's scale(), transform() and
- transformations() to map the item's coordinate system to the parent item.
-
- \sa setRotation(), transformOriginPoint(), {Transformations}
-*/
-qreal QGraphicsItem::rotation() const
-{
- if (!d_ptr->transformData)
- return 0;
- return d_ptr->transformData->rotation;
-}
-
-/*!
- \since 4.6
-
- Sets the clockwise rotation \a angle, in degrees, around the Z axis. The
- default value is 0 (i.e., the item is not rotated). Assigning a negative
- value will rotate the item counter-clockwise. Normally the rotation angle
- is in the range (-360, 360), but it's also possible to assign values
- outside of this range (e.g., a rotation of 370 degrees is the same as a
- rotation of 10 degrees).
-
- The item is rotated around its transform origin point, which by default
- is (0, 0). You can select a different transformation origin by calling
- setTransformOriginPoint().
-
- The rotation is combined with the item's scale(), transform() and
- transformations() to map the item's coordinate system to the parent item.
-
- \sa rotation(), setTransformOriginPoint(), {Transformations}
-*/
-void QGraphicsItem::setRotation(qreal angle)
-{
- prepareGeometryChange();
- qreal newRotation = angle;
-
- if (d_ptr->flags & ItemSendsGeometryChanges) {
- // Notify the item that the rotation is changing.
- const QVariant newRotationVariant(itemChange(ItemRotationChange, angle));
- newRotation = newRotationVariant.toReal();
- }
-
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
-
- if (d_ptr->transformData->rotation == newRotation)
- return;
-
- d_ptr->transformData->rotation = newRotation;
- d_ptr->transformData->onlyTransform = false;
- d_ptr->dirtySceneTransform = 1;
-
- // Send post-notification.
- if (d_ptr->flags & ItemSendsGeometryChanges)
- itemChange(ItemRotationHasChanged, newRotation);
-
- if (d_ptr->isObject)
- emit static_cast<QGraphicsObject *>(this)->rotationChanged();
-
- d_ptr->transformChanged();
-}
-
-/*!
- \since 4.6
-
- Returns the scale factor of the item. The default scale factor is 1.0
- (i.e., the item is not scaled).
-
- The scale is combined with the item's rotation(), transform() and
- transformations() to map the item's coordinate system to the parent item.
-
- \sa setScale(), rotation(), {Transformations}
-*/
-qreal QGraphicsItem::scale() const
-{
- if (!d_ptr->transformData)
- return 1.;
- return d_ptr->transformData->scale;
-}
-
-/*!
- \since 4.6
-
- Sets the scale \a factor of the item. The default scale factor is 1.0
- (i.e., the item is not scaled). A scale factor of 0.0 will collapse the
- item to a single point. If you provide a negative scale factor, the
- item will be flipped and mirrored (i.e., rotated 180 degrees).
-
- The item is scaled around its transform origin point, which by default
- is (0, 0). You can select a different transformation origin by calling
- setTransformOriginPoint().
-
- The scale is combined with the item's rotation(), transform() and
- transformations() to map the item's coordinate system to the parent item.
-
- \sa scale(), setTransformOriginPoint(), {Transformations Example}
-*/
-void QGraphicsItem::setScale(qreal factor)
-{
- prepareGeometryChange();
- qreal newScale = factor;
-
- if (d_ptr->flags & ItemSendsGeometryChanges) {
- // Notify the item that the scale is changing.
- const QVariant newScaleVariant(itemChange(ItemScaleChange, factor));
- newScale = newScaleVariant.toReal();
- }
-
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
-
- if (d_ptr->transformData->scale == newScale)
- return;
-
- d_ptr->transformData->scale = newScale;
- d_ptr->transformData->onlyTransform = false;
- d_ptr->dirtySceneTransform = 1;
-
- // Send post-notification.
- if (d_ptr->flags & ItemSendsGeometryChanges)
- itemChange(ItemScaleHasChanged, newScale);
-
- if (d_ptr->isObject)
- emit static_cast<QGraphicsObject *>(this)->scaleChanged();
-
- d_ptr->transformChanged();
-}
-
-
-/*!
- \since 4.6
-
- Returns a list of graphics transforms that currently apply to this item.
-
- QGraphicsTransform is for applying and controlling a chain of individual
- transformation operations on an item. It's particularly useful in
- animations, where each transform operation needs to be interpolated
- independently, or differently.
-
- The transformations are combined with the item's rotation(), scale() and
- transform() to map the item's coordinate system to the parent item.
-
- \sa scale(), rotation(), transformOriginPoint(), {Transformations}
-*/
-QList<QGraphicsTransform *> QGraphicsItem::transformations() const
-{
- if (!d_ptr->transformData)
- return QList<QGraphicsTransform *>();
- return d_ptr->transformData->graphicsTransforms;
-}
-
-/*!
- \since 4.6
-
- Sets a list of graphics \a transformations (QGraphicsTransform) that
- currently apply to this item.
-
- If all you want is to rotate or scale an item, you should call setRotation()
- or setScale() instead. If you want to set an arbitrary transformation on
- an item, you can call setTransform().
-
- QGraphicsTransform is for applying and controlling a chain of individual
- transformation operations on an item. It's particularly useful in
- animations, where each transform operation needs to be interpolated
- independently, or differently.
-
- The transformations are combined with the item's rotation(), scale() and
- transform() to map the item's coordinate system to the parent item.
-
- \sa scale(), setTransformOriginPoint(), {Transformations}
-*/
-void QGraphicsItem::setTransformations(const QList<QGraphicsTransform *> &transformations)
-{
- prepareGeometryChange();
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
- d_ptr->transformData->graphicsTransforms = transformations;
- for (int i = 0; i < transformations.size(); ++i)
- transformations.at(i)->d_func()->setItem(this);
- d_ptr->transformData->onlyTransform = false;
- d_ptr->dirtySceneTransform = 1;
- d_ptr->transformChanged();
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::prependGraphicsTransform(QGraphicsTransform *t)
-{
- if (!transformData)
- transformData = new QGraphicsItemPrivate::TransformData;
- if (!transformData->graphicsTransforms.contains(t))
- transformData->graphicsTransforms.prepend(t);
-
- Q_Q(QGraphicsItem);
- t->d_func()->setItem(q);
- transformData->onlyTransform = false;
- dirtySceneTransform = 1;
- transformChanged();
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::appendGraphicsTransform(QGraphicsTransform *t)
-{
- if (!transformData)
- transformData = new QGraphicsItemPrivate::TransformData;
- if (!transformData->graphicsTransforms.contains(t))
- transformData->graphicsTransforms.append(t);
-
- Q_Q(QGraphicsItem);
- t->d_func()->setItem(q);
- transformData->onlyTransform = false;
- dirtySceneTransform = 1;
- transformChanged();
-}
-
-/*!
- \since 4.6
-
- Returns the origin point for the transformation in item coordinates.
-
- The default is QPointF(0,0).
-
- \sa setTransformOriginPoint(), {Transformations}
-*/
-QPointF QGraphicsItem::transformOriginPoint() const
-{
- if (!d_ptr->transformData)
- return QPointF(0,0);
- return QPointF(d_ptr->transformData->xOrigin, d_ptr->transformData->yOrigin);
-}
-
-/*!
- \since 4.6
-
- Sets the \a origin point for the transformation in item coordinates.
-
- \sa transformOriginPoint(), {Transformations}
-*/
-void QGraphicsItem::setTransformOriginPoint(const QPointF &origin)
-{
- prepareGeometryChange();
- QPointF newOrigin = origin;
-
- if (d_ptr->flags & ItemSendsGeometryChanges) {
- // Notify the item that the origin point is changing.
- const QVariant newOriginVariant(itemChange(ItemTransformOriginPointChange,
- QVariant::fromValue<QPointF>(origin)));
- newOrigin = newOriginVariant.toPointF();
- }
-
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
-
- if (d_ptr->transformData->xOrigin == newOrigin.x()
- && d_ptr->transformData->yOrigin == newOrigin.y()) {
- return;
- }
-
- d_ptr->transformData->xOrigin = newOrigin.x();
- d_ptr->transformData->yOrigin = newOrigin.y();
- d_ptr->transformData->onlyTransform = false;
- d_ptr->dirtySceneTransform = 1;
-
- // Send post-notification.
- if (d_ptr->flags & ItemSendsGeometryChanges)
- itemChange(ItemTransformOriginPointHasChanged, QVariant::fromValue<QPointF>(newOrigin));
-}
-
-/*!
- \fn void QGraphicsItem::setTransformOriginPoint(qreal x, qreal y)
-
- \since 4.6
- \overload
-
- Sets the origin point for the transformation in item coordinates.
- This is equivalent to calling setTransformOriginPoint(QPointF(\a x, \a y)).
-
- \sa setTransformOriginPoint(), {Transformations}
-*/
-
-
-/*!
- \obsolete
-
- Use sceneTransform() instead.
-
- \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}
-*/
-QMatrix QGraphicsItem::sceneMatrix() const
-{
- d_ptr->ensureSceneTransform();
- return d_ptr->sceneTransform.toAffine();
-}
-
-
-/*!
- \since 4.3
-
- Returns this item's scene transformation matrix. This matrix can be used
- to map coordinates and geometrical shapes from this item's local
- coordinate system to the scene's coordinate system. To map coordinates
- from the scene, you must first invert the returned matrix.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 4
-
- Unlike transform(), which returns only an item's local transformation, this
- function includes the item's (and any parents') position, and all the transfomation properties.
-
- \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}, {Transformations}
-*/
-QTransform QGraphicsItem::sceneTransform() const
-{
- d_ptr->ensureSceneTransform();
- return d_ptr->sceneTransform;
-}
-
-/*!
- \since 4.3
-
- Returns this item's device transformation matrix, using \a
- viewportTransform to map from scene to device coordinates. This matrix can
- be used to map coordinates and geometrical shapes from this item's local
- coordinate system to the viewport's (or any device's) coordinate
- system. To map coordinates from the viewport, you must first invert the
- returned matrix.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 5
-
- This function is the same as combining this item's scene transform with
- the view's viewport transform, but it also understands the
- ItemIgnoresTransformations flag. The device transform can be used to do
- accurate coordinate mapping (and collision detection) for untransformable
- items.
-
- \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate
- System}, itemTransform()
-*/
-QTransform QGraphicsItem::deviceTransform(const QTransform &viewportTransform) const
-{
- // Ensure we return the standard transform if we're not untransformable.
- if (!d_ptr->itemIsUntransformable()) {
- d_ptr->ensureSceneTransform();
- return d_ptr->sceneTransform * viewportTransform;
- }
-
- // Find the topmost item that ignores view transformations.
- const QGraphicsItem *untransformedAncestor = this;
- QList<const QGraphicsItem *> parents;
- while (untransformedAncestor && ((untransformedAncestor->d_ptr->ancestorFlags
- & QGraphicsItemPrivate::AncestorIgnoresTransformations))) {
- parents.prepend(untransformedAncestor);
- untransformedAncestor = untransformedAncestor->parentItem();
- }
-
- if (!untransformedAncestor) {
- // Assert in debug mode, continue in release.
- Q_ASSERT_X(untransformedAncestor, "QGraphicsItem::deviceTransform",
- "Invalid object structure!");
- return QTransform();
- }
-
- // First translate the base untransformable item.
- untransformedAncestor->d_ptr->ensureSceneTransform();
- QPointF mappedPoint = (untransformedAncestor->d_ptr->sceneTransform * viewportTransform).map(QPointF(0, 0));
-
- // COMBINE
- QTransform matrix = QTransform::fromTranslate(mappedPoint.x(), mappedPoint.y());
- if (untransformedAncestor->d_ptr->transformData)
- matrix = untransformedAncestor->d_ptr->transformData->computedFullTransform(&matrix);
-
- // Then transform and translate all children.
- for (int i = 0; i < parents.size(); ++i) {
- const QGraphicsItem *parent = parents.at(i);
- parent->d_ptr->combineTransformFromParent(&matrix);
- }
-
- return matrix;
-}
-
-/*!
- \since 4.5
-
- Returns a QTransform that maps coordinates from this item to \a other. If
- \a ok is not null, and if there is no such transform, the boolean pointed
- to by \a ok will be set to false; otherwise it will be set to true.
-
- This transform provides an alternative to the mapToItem() or mapFromItem()
- functions, by returning the appropriate transform so that you can map
- shapes and coordinates yourself. It also helps you write more efficient
- code when repeatedly mapping between the same two items.
-
- \note In rare circumstances, there is no transform that maps between two
- items.
-
- \sa mapToItem(), mapFromItem(), deviceTransform()
-*/
-QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) const
-{
- // Catch simple cases first.
- if (other == 0) {
- qWarning("QGraphicsItem::itemTransform: null pointer passed");
- return QTransform();
- }
- if (other == this) {
- if (ok)
- *ok = true;
- return QTransform();
- }
-
- QGraphicsItem *parent = d_ptr->parent;
- const QGraphicsItem *otherParent = other->d_ptr->parent;
-
- // This is other's child
- if (parent == other) {
- if (ok)
- *ok = true;
- QTransform x;
- d_ptr->combineTransformFromParent(&x);
- return x;
- }
-
- // This is other's parent
- if (otherParent == this) {
- const QPointF &otherPos = other->d_ptr->pos;
- if (other->d_ptr->transformData) {
- QTransform otherToParent;
- other->d_ptr->combineTransformFromParent(&otherToParent);
- return otherToParent.inverted(ok);
- }
- if (ok)
- *ok = true;
- return QTransform::fromTranslate(-otherPos.x(), -otherPos.y());
- }
-
- // Siblings
- if (parent == otherParent) {
- // COMBINE
- const QPointF &itemPos = d_ptr->pos;
- const QPointF &otherPos = other->d_ptr->pos;
- if (!d_ptr->transformData && !other->d_ptr->transformData) {
- QPointF delta = itemPos - otherPos;
- if (ok)
- *ok = true;
- return QTransform::fromTranslate(delta.x(), delta.y());
- }
-
- QTransform itemToParent;
- d_ptr->combineTransformFromParent(&itemToParent);
- QTransform otherToParent;
- other->d_ptr->combineTransformFromParent(&otherToParent);
- return itemToParent * otherToParent.inverted(ok);
- }
-
- // Find the closest common ancestor. If the two items don't share an
- // ancestor, then the only way is to combine their scene transforms.
- const QGraphicsItem *commonAncestor = commonAncestorItem(other);
- if (!commonAncestor) {
- d_ptr->ensureSceneTransform();
- other->d_ptr->ensureSceneTransform();
- return d_ptr->sceneTransform * other->d_ptr->sceneTransform.inverted(ok);
- }
-
- // If the two items are cousins (in sibling branches), map both to the
- // common ancestor, and combine the two transforms.
- bool cousins = other != commonAncestor && this != commonAncestor;
- if (cousins) {
- bool good = false;
- QTransform thisToScene = itemTransform(commonAncestor, &good);
- QTransform otherToScene(Qt::Uninitialized);
- if (good)
- otherToScene = other->itemTransform(commonAncestor, &good);
- if (!good) {
- if (ok)
- *ok = false;
- return QTransform();
- }
- return thisToScene * otherToScene.inverted(ok);
- }
-
- // One is an ancestor of the other; walk the chain.
- bool parentOfOther = isAncestorOf(other);
- const QGraphicsItem *child = parentOfOther ? other : this;
- const QGraphicsItem *root = parentOfOther ? this : other;
-
- QTransform x;
- const QGraphicsItem *p = child;
- do {
- p->d_ptr.data()->combineTransformToParent(&x);
- } while ((p = p->d_ptr->parent) && p != root);
- if (parentOfOther)
- return x.inverted(ok);
- if (ok)
- *ok = true;
- return x;
-}
-
-/*!
- \obsolete
-
- Sets the item's affine transformation matrix. This is a subset or the
- item's full transformation matrix, and might not represent the item's full
- transformation.
-
- Use setTransform() instead.
-
- \sa transform(), {The Graphics View Coordinate System}
-*/
-void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine)
-{
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
-
- QTransform newTransform(combine ? QTransform(matrix) * d_ptr->transformData->transform : QTransform(matrix));
- if (d_ptr->transformData->transform == newTransform)
- return;
-
- // Update and set the new transformation.
- if (!(d_ptr->flags & ItemSendsGeometryChanges)) {
- d_ptr->setTransformHelper(newTransform);
- return;
- }
-
- // Notify the item that the transformation matrix is changing.
- const QVariant newMatrixVariant = QVariant::fromValue<QMatrix>(newTransform.toAffine());
- newTransform = QTransform(qvariant_cast<QMatrix>(itemChange(ItemMatrixChange, newMatrixVariant)));
- if (d_ptr->transformData->transform == newTransform)
- return;
-
- // Update and set the new transformation.
- d_ptr->setTransformHelper(newTransform);
-
- // Send post-notification.
- itemChange(ItemTransformHasChanged, QVariant::fromValue<QTransform>(newTransform));
-}
-
-/*!
- \since 4.3
-
- Sets the item's current transformation matrix to \a matrix.
-
- If \a combine is true, then \a matrix is combined with the current matrix;
- otherwise, \a matrix \e replaces the current matrix. \a combine is false
- by default.
-
- To simplify interation with items using a transformed view, QGraphicsItem
- provides mapTo... and mapFrom... functions that can translate between
- items' and the scene's coordinates. For example, you can call mapToScene()
- to map an item coordiate to a scene coordinate, or mapFromScene() to map
- from scene coordinates to item coordinates.
-
- The transformation matrix is combined with the item's rotation(), scale()
- and transformations() into a combined transformation that maps the item's
- coordinate system to its parent.
-
- \sa transform(), setRotation(), setScale(), setTransformOriginPoint(), {The Graphics View Coordinate System}, {Transformations}
-*/
-void QGraphicsItem::setTransform(const QTransform &matrix, bool combine)
-{
- if (!d_ptr->transformData)
- d_ptr->transformData = new QGraphicsItemPrivate::TransformData;
-
- QTransform newTransform(combine ? matrix * d_ptr->transformData->transform : matrix);
- if (d_ptr->transformData->transform == newTransform)
- return;
-
- // Update and set the new transformation.
- if (!(d_ptr->flags & (ItemSendsGeometryChanges | ItemSendsScenePositionChanges))) {
- d_ptr->setTransformHelper(newTransform);
- if (d_ptr->scenePosDescendants)
- d_ptr->sendScenePosChange();
- return;
- }
-
- // Notify the item that the transformation matrix is changing.
- const QVariant newTransformVariant(itemChange(ItemTransformChange,
- QVariant::fromValue<QTransform>(newTransform)));
- newTransform = qvariant_cast<QTransform>(newTransformVariant);
- if (d_ptr->transformData->transform == newTransform)
- return;
-
- // Update and set the new transformation.
- d_ptr->setTransformHelper(newTransform);
-
- // Send post-notification.
- itemChange(ItemTransformHasChanged, newTransformVariant);
- d_ptr->sendScenePosChange();
-}
-
-/*!
- \obsolete
-
- Use resetTransform() instead.
-*/
-void QGraphicsItem::resetMatrix()
-{
- resetTransform();
-}
-
-/*!
- \since 4.3
-
- Resets this item's transformation matrix to the identity matrix or
- all the transformation properties to their default values.
- This is equivalent to calling \c setTransform(QTransform()).
-
- \sa setTransform(), transform()
-*/
-void QGraphicsItem::resetTransform()
-{
- setTransform(QTransform(), false);
-}
-
-/*!
- \obsolete
-
- Use
-
- \code
- setRotation(rotation() + angle);
- \endcode
-
- instead.
-
- Rotates the current item transformation \a angle degrees clockwise around
- its origin. To translate around an arbitrary point (x, y), you need to
- combine translation and rotation with setTransform().
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 6
-
- \sa setTransform(), transform(), scale(), shear(), translate()
-*/
-void QGraphicsItem::rotate(qreal angle)
-{
- setTransform(QTransform().rotate(angle), true);
-}
-
-/*!
- \obsolete
-
- Use
-
- \code
- setTransform(QTransform::fromScale(sx, sy), true);
- \endcode
-
- instead.
-
- Scales the current item transformation by (\a sx, \a sy) around its
- origin. To scale from an arbitrary point (x, y), you need to combine
- translation and scaling with setTransform().
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 7
-
- \sa setTransform(), transform()
-*/
-void QGraphicsItem::scale(qreal sx, qreal sy)
-{
- setTransform(QTransform::fromScale(sx, sy), true);
-}
-
-/*!
- \obsolete
-
- Use
-
- \code
- setTransform(QTransform().shear(sh, sv), true);
- \endcode
-
- instead.
-
- Shears the current item transformation by (\a sh, \a sv).
-
- \sa setTransform(), transform()
-*/
-void QGraphicsItem::shear(qreal sh, qreal sv)
-{
- setTransform(QTransform().shear(sh, sv), true);
-}
-
-/*!
- \obsolete
-
- Use setPos() or setTransformOriginPoint() instead. For identical
- behavior, use
-
- \code
- setTransform(QTransform::fromTranslate(dx, dy), true);
- \endcode
-
- Translates the current item transformation by (\a dx, \a dy).
-
- If all you want is to move an item, you should call moveBy() or
- setPos() instead; this function changes the item's translation,
- which is conceptually separate from its position.
-
- \sa setTransform(), transform()
-*/
-void QGraphicsItem::translate(qreal dx, qreal dy)
-{
- setTransform(QTransform::fromTranslate(dx, dy), true);
-}
-
-/*!
- This virtual function is called twice for all items by the
- QGraphicsScene::advance() slot. In the first phase, all items are called
- with \a phase == 0, indicating that items on the scene are about to
- advance, and then all items are called with \a phase == 1. Reimplement
- this function to update your item if you need simple scene-controlled
- animation.
-
- The default implementation does nothing.
-
- For individual item animation, an alternative to this function is to
- either use QGraphicsItemAnimation, or to multiple-inherit from QObject and
- QGraphicsItem, and animate your item using QObject::startTimer() and
- QObject::timerEvent().
-
- \sa QGraphicsItemAnimation, QTimeLine
-*/
-void QGraphicsItem::advance(int phase)
-{
- Q_UNUSED(phase);
-}
-
-/*!
- Returns the Z-value of the item. The Z-value affects the stacking order of
- sibling (neighboring) items.
-
- The default Z-value is 0.
-
- \sa setZValue(), {QGraphicsItem#Sorting}{Sorting}, stackBefore(), ItemStacksBehindParent
-*/
-qreal QGraphicsItem::zValue() const
-{
- return d_ptr->z;
-}
-
-/*!
- Sets the Z-value of the item to \a z. The Z value decides the stacking
- order of sibling (neighboring) items. A sibling item of high Z value will
- always be drawn on top of another sibling item with a lower Z value.
-
- If you restore the Z value, the item's insertion order will decide its
- stacking order.
-
- The Z-value does not affect the item's size in any way.
-
- The default Z-value is 0.
-
- \sa zValue(), {QGraphicsItem#Sorting}{Sorting}, stackBefore(), ItemStacksBehindParent
-*/
-void QGraphicsItem::setZValue(qreal z)
-{
- const QVariant newZVariant(itemChange(ItemZValueChange, z));
- qreal newZ = newZVariant.toReal();
- if (newZ == d_ptr->z)
- return;
-
- if (d_ptr->scene && d_ptr->scene->d_func()->indexMethod != QGraphicsScene::NoIndex) {
- // Z Value has changed, we have to notify the index.
- d_ptr->scene->d_func()->index->itemChange(this, ItemZValueChange, &newZ);
- }
-
- d_ptr->z = newZ;
- if (d_ptr->parent)
- d_ptr->parent->d_ptr->needSortChildren = 1;
- else if (d_ptr->scene)
- d_ptr->scene->d_func()->needSortTopLevelItems = 1;
-
- if (d_ptr->scene)
- d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true);
-
- itemChange(ItemZValueHasChanged, newZVariant);
-
- if (d_ptr->flags & ItemNegativeZStacksBehindParent)
- setFlag(QGraphicsItem::ItemStacksBehindParent, z < qreal(0.0));
-
- if (d_ptr->isObject)
- emit static_cast<QGraphicsObject *>(this)->zChanged();
-}
-
-/*!
- \internal
-
- Ensures that the list of children is sorted by insertion order, and that
- the siblingIndexes are packed (no gaps), and start at 0.
-
- ### This function is almost identical to
- QGraphicsScenePrivate::ensureSequentialTopLevelSiblingIndexes().
-*/
-void QGraphicsItemPrivate::ensureSequentialSiblingIndex()
-{
- if (!sequentialOrdering) {
- qSort(children.begin(), children.end(), insertionOrder);
- sequentialOrdering = 1;
- needSortChildren = 1;
- }
- if (holesInSiblingIndex) {
- holesInSiblingIndex = 0;
- for (int i = 0; i < children.size(); ++i)
- children[i]->d_ptr->siblingIndex = i;
- }
-}
-
-/*!
- \internal
-*/
-inline void QGraphicsItemPrivate::sendScenePosChange()
-{
- Q_Q(QGraphicsItem);
- if (scene) {
- if (flags & QGraphicsItem::ItemSendsScenePositionChanges)
- q->itemChange(QGraphicsItem::ItemScenePositionHasChanged, q->scenePos());
- if (scenePosDescendants) {
- foreach (QGraphicsItem *item, scene->d_func()->scenePosItems) {
- if (q->isAncestorOf(item))
- item->itemChange(QGraphicsItem::ItemScenePositionHasChanged, item->scenePos());
- }
- }
- }
-}
-
-/*!
- \since 4.6
-
- Stacks this item before \a sibling, which must be a sibling item (i.e., the
- two items must share the same parent item, or must both be toplevel items).
- The \a sibling must have the same Z value as this item, otherwise calling
- this function will have no effect.
-
- By default, all sibling items are stacked by insertion order (i.e., the
- first item you add is drawn before the next item you add). If two items' Z
- values are different, then the item with the highest Z value is drawn on
- top. When the Z values are the same, the insertion order will decide the
- stacking order.
-
- \sa setZValue(), ItemStacksBehindParent, {QGraphicsItem#Sorting}{Sorting}
-*/
-void QGraphicsItem::stackBefore(const QGraphicsItem *sibling)
-{
- if (sibling == this)
- return;
- if (!sibling || d_ptr->parent != sibling->parentItem()) {
- qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling);
- return;
- }
- QList<QGraphicsItem *> *siblings = d_ptr->parent
- ? &d_ptr->parent->d_ptr->children
- : (d_ptr->scene ? &d_ptr->scene->d_func()->topLevelItems : 0);
- if (!siblings) {
- qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling);
- return;
- }
-
- // First, make sure that the sibling indexes have no holes. This also
- // marks the children list for sorting.
- if (d_ptr->parent)
- d_ptr->parent->d_ptr->ensureSequentialSiblingIndex();
- else
- d_ptr->scene->d_func()->ensureSequentialTopLevelSiblingIndexes();
-
- // Only move items with the same Z value, and that need moving.
- int siblingIndex = sibling->d_ptr->siblingIndex;
- int myIndex = d_ptr->siblingIndex;
- if (myIndex >= siblingIndex) {
- siblings->move(myIndex, siblingIndex);
- // Fixup the insertion ordering.
- for (int i = 0; i < siblings->size(); ++i) {
- int &index = siblings->at(i)->d_ptr->siblingIndex;
- if (i != siblingIndex && index >= siblingIndex && index <= myIndex)
- ++index;
- }
- d_ptr->siblingIndex = siblingIndex;
- for (int i = 0; i < siblings->size(); ++i) {
- int &index = siblings->at(i)->d_ptr->siblingIndex;
- if (i != siblingIndex && index >= siblingIndex && index <= myIndex)
- siblings->at(i)->d_ptr->siblingOrderChange();
- }
- d_ptr->siblingOrderChange();
- }
-}
-
-/*!
- Returns the bounding rect of this item's descendants (i.e., its
- children, their children, etc.) in local coordinates. The
- rectangle will contain all descendants after they have been mapped
- to local coordinates. If the item has no children, this function
- returns an empty QRectF.
-
- This does not include this item's own bounding rect; it only returns
- its descendants' accumulated bounding rect. If you need to include this
- item's bounding rect, you can add boundingRect() to childrenBoundingRect()
- using QRectF::operator|().
-
- This function is linear in complexity; it determines the size of the
- returned bounding rect by iterating through all descendants.
-
- \sa boundingRect(), sceneBoundingRect()
-*/
-QRectF QGraphicsItem::childrenBoundingRect() const
-{
- if (!d_ptr->dirtyChildrenBoundingRect)
- return d_ptr->childrenBoundingRect;
-
- d_ptr->childrenBoundingRect = QRectF();
- d_ptr->childrenBoundingRectHelper(0, &d_ptr->childrenBoundingRect, 0);
- d_ptr->dirtyChildrenBoundingRect = 0;
- return d_ptr->childrenBoundingRect;
-}
-
-/*!
- \fn virtual QRectF QGraphicsItem::boundingRect() const = 0
-
- This pure virtual function defines the outer bounds of the item as
- a rectangle; all painting must be restricted to inside an item's
- bounding rect. QGraphicsView uses this to determine whether the
- item requires redrawing.
-
- Although the item's shape can be arbitrary, the bounding rect is
- always rectangular, and it is unaffected by the items'
- transformation.
-
- If you want to change the item's bounding rectangle, you must first call
- prepareGeometryChange(). This notifies the scene of the imminent change,
- so that its can update its item geometry index; otherwise, the scene will
- be unaware of the item's new geometry, and the results are undefined
- (typically, rendering artifacts are left around in the view).
-
- Reimplement this function to let QGraphicsView determine what
- parts of the widget, if any, need to be redrawn.
-
- Note: For shapes that paint an outline / stroke, it is important
- to include half the pen width in the bounding rect. It is not
- necessary to compensate for antialiasing, though.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 8
-
- \sa boundingRegion(), shape(), contains(), {The Graphics View Coordinate
- System}, prepareGeometryChange()
-*/
-
-/*!
- Returns the bounding rect of this item in scene coordinates, by combining
- sceneTransform() with boundingRect().
-
- \sa boundingRect(), {The Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::sceneBoundingRect() const
-{
- // Find translate-only offset
- // COMBINE
- QPointF offset;
- const QGraphicsItem *parentItem = this;
- const QGraphicsItemPrivate *itemd;
- do {
- itemd = parentItem->d_ptr.data();
- if (itemd->transformData)
- break;
- offset += itemd->pos;
- } while ((parentItem = itemd->parent));
-
- QRectF br = boundingRect();
- br.translate(offset);
- if (!parentItem)
- return br;
- if (parentItem->d_ptr->hasTranslateOnlySceneTransform()) {
- br.translate(parentItem->d_ptr->sceneTransform.dx(), parentItem->d_ptr->sceneTransform.dy());
- return br;
- }
- return parentItem->d_ptr->sceneTransform.mapRect(br);
-}
-
-/*!
- Returns the shape of this item as a QPainterPath in local
- coordinates. The shape is used for many things, including collision
- detection, hit tests, and for the QGraphicsScene::items() functions.
-
- The default implementation calls boundingRect() to return a simple
- rectangular shape, but subclasses can reimplement this function to return
- a more accurate shape for non-rectangular items. For example, a round item
- may choose to return an elliptic shape for better collision detection. For
- example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 9
-
- The outline of a shape can vary depending on the width and style of the
- pen used when drawing. If you want to include this outline in the item's
- shape, you can create a shape from the stroke using QPainterPathStroker.
-
- This function is called by the default implementations of contains() and
- collidesWithPath().
-
- \sa boundingRect(), contains(), prepareGeometryChange(), QPainterPathStroker
-*/
-QPainterPath QGraphicsItem::shape() const
-{
- QPainterPath path;
- path.addRect(boundingRect());
- return path;
-}
-
-/*!
- Returns true if this item is clipped. An item is clipped if it has either
- set the \l ItemClipsToShape flag, or if it or any of its ancestors has set
- the \l ItemClipsChildrenToShape flag.
-
- Clipping affects the item's appearance (i.e., painting), as well as mouse
- and hover event delivery.
-
- \sa clipPath(), shape(), setFlags()
-*/
-bool QGraphicsItem::isClipped() const
-{
- Q_D(const QGraphicsItem);
- return (d->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
- || (d->flags & QGraphicsItem::ItemClipsToShape);
-}
-
-/*!
- \since 4.5
-
- Returns this item's clip path, or an empty QPainterPath if this item is
- not clipped. The clip path constrains the item's appearance and
- interaction (i.e., restricts the area the item can draw, and it also
- restricts the area that the item receives events).
-
- You can enable clipping by setting the ItemClipsToShape or
- ItemClipsChildrenToShape flags. The item's clip path is calculated by
- intersecting all clipping ancestors' shapes. If the item sets
- ItemClipsToShape, the final clip is intersected with the item's own shape.
-
- \note Clipping introduces a performance penalty for all items involved;
- you should generally avoid using clipping if you can (e.g., if your items
- always draw inside boundingRect() or shape() boundaries, clipping is not
- necessary).
-
- \sa isClipped(), shape(), setFlags()
-*/
-QPainterPath QGraphicsItem::clipPath() const
-{
- Q_D(const QGraphicsItem);
- if (!isClipped())
- return QPainterPath();
-
- const QRectF thisBoundingRect(boundingRect());
- if (thisBoundingRect.isEmpty())
- return QPainterPath();
-
- QPainterPath clip;
- // Start with the item's bounding rect.
- clip.addRect(thisBoundingRect);
-
- if (d->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) {
- const QGraphicsItem *parent = this;
- const QGraphicsItem *lastParent = this;
-
- // Intersect any in-between clips starting at the top and moving downwards.
- while ((parent = parent->d_ptr->parent)) {
- if (parent->d_ptr->flags & ItemClipsChildrenToShape) {
- // Map clip to the current parent and intersect with its shape/clipPath
- clip = lastParent->itemTransform(parent).map(clip);
- clip = clip.intersected(parent->shape());
- if (clip.isEmpty())
- return clip;
- lastParent = parent;
- }
-
- if (!(parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren))
- break;
- }
-
- if (lastParent != this) {
- // Map clip back to the item's transform.
- // ### what if itemtransform fails
- clip = lastParent->itemTransform(this).map(clip);
- }
- }
-
- if (d->flags & ItemClipsToShape)
- clip = clip.intersected(shape());
-
- return clip;
-}
-
-/*!
- Returns true if this item contains \a point, which is in local
- coordinates; otherwise, false is returned. It is most often called from
- QGraphicsView to determine what item is under the cursor, and for that
- reason, the implementation of this function should be as light-weight as
- possible.
-
- By default, this function calls shape(), but you can reimplement it in a
- subclass to provide a (perhaps more efficient) implementation.
-
- \sa shape(), boundingRect(), collidesWithPath()
-*/
-bool QGraphicsItem::contains(const QPointF &point) const
-{
- return isClipped() ? clipPath().contains(point) : shape().contains(point);
-}
-
-/*!
-
- Returns true if this item collides with \a other; otherwise
- returns false.
-
- The \a mode is applied to \a other, and the resulting shape or
- bounding rectangle is then compared to this item's shape. The
- default value for \a mode is Qt::IntersectsItemShape; \a other
- collides with this item if it either intersects, contains, or is
- contained by this item's shape (see Qt::ItemSelectionMode for
- details).
-
- The default implementation is based on shape intersection, and it calls
- shape() on both items. Because the complexity of arbitrary shape-shape
- intersection grows with an order of magnitude when the shapes are complex,
- this operation can be noticably time consuming. You have the option of
- reimplementing this function in a subclass of QGraphicsItem to provide a
- custom algorithm. This allows you to make use of natural constraints in
- the shapes of your own items, in order to improve the performance of the
- collision detection. For instance, two untransformed perfectly circular
- items' collision can be determined very efficiently by comparing their
- positions and radii.
-
- Keep in mind that when reimplementing this function and calling shape() or
- boundingRect() on \a other, the returned coordinates must be mapped to
- this item's coordinate system before any intersection can take place.
-
- \sa contains(), shape()
-*/
-bool QGraphicsItem::collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode) const
-{
- if (other == this)
- return true;
- if (!other)
- return false;
- // The items share the same clip if their closest clipper is the same, or
- // if one clips the other.
- bool clips = (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren);
- bool otherClips = (other->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren);
- if (clips || otherClips) {
- const QGraphicsItem *closestClipper = isAncestorOf(other) ? this : parentItem();
- while (closestClipper && !(closestClipper->flags() & ItemClipsChildrenToShape))
- closestClipper = closestClipper->parentItem();
- const QGraphicsItem *otherClosestClipper = other->isAncestorOf(this) ? other : other->parentItem();
- while (otherClosestClipper && !(otherClosestClipper->flags() & ItemClipsChildrenToShape))
- otherClosestClipper = otherClosestClipper->parentItem();
- if (closestClipper == otherClosestClipper) {
- d_ptr->localCollisionHack = 1;
- bool res = collidesWithPath(mapFromItem(other, other->shape()), mode);
- d_ptr->localCollisionHack = 0;
- return res;
- }
- }
-
- QPainterPath otherShape = other->isClipped() ? other->clipPath() : other->shape();
- return collidesWithPath(mapFromItem(other, otherShape), mode);
-}
-
-/*!
- Returns true if this item collides with \a path.
-
- The collision is determined by \a mode. The default value for \a mode is
- Qt::IntersectsItemShape; \a path collides with this item if it either
- intersects, contains, or is contained by this item's shape.
-
- Note that this function checks whether the item's shape or
- bounding rectangle (depending on \a mode) is contained within \a
- path, and not whether \a path is contained within the items shape
- or bounding rectangle.
-
- \sa collidesWithItem(), contains(), shape()
-*/
-bool QGraphicsItem::collidesWithPath(const QPainterPath &path, Qt::ItemSelectionMode mode) const
-{
- if (path.isEmpty()) {
- // No collision with empty paths.
- return false;
- }
-
- QRectF rectA(boundingRect());
- _q_adjustRect(&rectA);
- QRectF rectB(path.controlPointRect());
- _q_adjustRect(&rectB);
- if (!rectA.intersects(rectB)) {
- // This we can determine efficiently. If the two rects neither
- // intersect nor contain eachother, then the two items do not collide.
- return false;
- }
-
- // For further testing, we need this item's shape or bounding rect.
- QPainterPath thisShape;
- if (mode == Qt::IntersectsItemShape || mode == Qt::ContainsItemShape)
- thisShape = (isClipped() && !d_ptr->localCollisionHack) ? clipPath() : shape();
- else
- thisShape.addRect(rectA);
-
- if (thisShape == QPainterPath()) {
- // Empty shape? No collision.
- return false;
- }
-
- // Use QPainterPath boolean operations to determine the collision, O(N*logN).
- if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
- return path.intersects(thisShape);
- return path.contains(thisShape);
-}
-
-/*!
- Returns a list of all items that collide with this item.
-
- The way collisions are detected is determined by applying \a mode
- to items that are compared to this item, i.e., each item's shape
- or bounding rectangle is checked against this item's shape. The
- default value for \a mode is Qt::IntersectsItemShape.
-
- \sa collidesWithItem()
-*/
-QList<QGraphicsItem *> QGraphicsItem::collidingItems(Qt::ItemSelectionMode mode) const
-{
- if (d_ptr->scene)
- return d_ptr->scene->collidingItems(this, mode);
- return QList<QGraphicsItem *>();
-}
-
-/*!
- Returns true if this item's bounding rect is completely obscured by the
- opaque shape of any of colliding items above it (i.e., with a higher Z
- value than this item).
-
- Its implementation is based on calling isObscuredBy(), which you can
- reimplement to provide a custom obscurity algorithm.
-
- \sa opaqueArea()
-*/
-bool QGraphicsItem::isObscured() const
-{
- return isObscured(QRectF());
-}
-
-/*!
- \internal
-
- Item obscurity helper function.
-
- Returns true if the subrect \a rect of \a item's bounding rect is obscured
- by \a other (i.e., \a other's opaque area covers \a item's \a rect
- completely. \a other is assumed to already be "on top of" \a item
- wrt. stacking order.
-*/
-static bool qt_QGraphicsItem_isObscured(const QGraphicsItem *item,
- const QGraphicsItem *other,
- const QRectF &rect)
-{
- return other->mapToItem(item, other->opaqueArea()).contains(rect);
-}
-
-/*!
- \overload
- \since 4.3
-
- Returns true if \a rect is completely obscured by the opaque shape of any
- of colliding items above it (i.e., with a higher Z value than this item).
-
- Unlike the default isObscured() function, this function does not call
- isObscuredBy().
-
- \sa opaqueArea()
-*/
-bool QGraphicsItem::isObscured(const QRectF &rect) const
-{
- Q_D(const QGraphicsItem);
- if (!d->scene)
- return false;
-
- QRectF br = boundingRect();
- QRectF testRect = rect.isNull() ? br : rect;
-
- foreach (QGraphicsItem *item, d->scene->items(mapToScene(br), Qt::IntersectsItemBoundingRect)) {
- if (item == this)
- break;
- if (qt_QGraphicsItem_isObscured(this, item, testRect))
- return true;
- }
- return false;
-}
-
-/*!
- \fn bool QGraphicsItem::isObscured(qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling isObscured(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Returns true if this item's bounding rect is completely obscured by the
- opaque shape of \a item.
-
- The base implementation maps \a item's opaqueArea() to this item's
- coordinate system, and then checks if this item's boundingRect() is fully
- contained within the mapped shape.
-
- You can reimplement this function to provide a custom algorithm for
- determining whether this item is obscured by \a item.
-
- \sa opaqueArea(), isObscured()
-*/
-bool QGraphicsItem::isObscuredBy(const QGraphicsItem *item) const
-{
- if (!item)
- return false;
- return qt_closestItemFirst(item, this)
- && qt_QGraphicsItem_isObscured(this, item, boundingRect());
-}
-
-/*!
- This virtual function returns a shape representing the area where this
- item is opaque. An area is opaque if it is filled using an opaque brush or
- color (i.e., not transparent).
-
- This function is used by isObscuredBy(), which is called by underlying
- items to determine if they are obscured by this item.
-
- The default implementation returns an empty QPainterPath, indicating that
- this item is completely transparent and does not obscure any other items.
-
- \sa isObscuredBy(), isObscured(), shape()
-*/
-QPainterPath QGraphicsItem::opaqueArea() const
-{
- return QPainterPath();
-}
-
-/*!
- \since 4.4
-
- Returns the bounding region for this item. The coordinate space of the
- returned region depends on \a itemToDeviceTransform. If you pass an
- identity QTransform as a parameter, this function will return a local
- coordinate region.
-
- The bounding region describes a coarse outline of the item's visual
- contents. Although it's expensive to calculate, it's also more precise
- than boundingRect(), and it can help to avoid unnecessary repainting when
- an item is updated. This is particularly efficient for thin items (e.g.,
- lines or simple polygons). You can tune the granularity for the bounding
- region by calling setBoundingRegionGranularity(). The default granularity
- is 0; in which the item's bounding region is the same as its bounding
- rect.
-
- \a itemToDeviceTransform is the transformation from item coordinates to
- device coordinates. If you want this function to return a QRegion in scene
- coordinates, you can pass sceneTransform() as an argument.
-
- \sa boundingRegionGranularity()
-*/
-QRegion QGraphicsItem::boundingRegion(const QTransform &itemToDeviceTransform) const
-{
- // ### Ideally we would have a better way to generate this region,
- // preferably something in the lines of QPainterPath::toRegion(QTransform)
- // coupled with a way to generate a painter path from a set of painter
- // operations (e.g., QPicture::toPainterPath() or so). The current
- // approach generates a bitmap with the size of the item's bounding rect
- // in device coordinates, scaled by b.r.granularity, then paints the item
- // into the bitmap, converts the result to a QRegion and scales the region
- // back to device space with inverse granularity.
- qreal granularity = boundingRegionGranularity();
- QRect deviceRect = itemToDeviceTransform.mapRect(boundingRect()).toRect();
- _q_adjustRect(&deviceRect);
- if (granularity == 0.0)
- return QRegion(deviceRect);
-
- int pad = 1;
- QSize bitmapSize(qMax(1, int(deviceRect.width() * granularity) + pad * 2),
- qMax(1, int(deviceRect.height() * granularity) + pad * 2));
- QImage mask(bitmapSize, QImage::Format_ARGB32_Premultiplied);
- mask.fill(0);
- QPainter p(&mask);
- p.setRenderHints(QPainter::Antialiasing);
-
- // Transform painter (### this code is from QGraphicsScene::drawItemHelper
- // and doesn't work properly with perspective transformations).
- QPointF viewOrigo = itemToDeviceTransform.map(QPointF(0, 0));
- QPointF offset = viewOrigo - deviceRect.topLeft();
- p.scale(granularity, granularity);
- p.translate(offset);
- p.translate(pad, pad);
- p.setWorldTransform(itemToDeviceTransform, true);
- p.translate(itemToDeviceTransform.inverted().map(QPointF(0, 0)));
-
- // Render
- QStyleOptionGraphicsItem option;
- const_cast<QGraphicsItem *>(this)->paint(&p, &option, 0);
- p.end();
-
- // Transform QRegion back to device space
- QTransform unscale = QTransform::fromScale(1 / granularity, 1 / granularity);
- QRegion r;
- QBitmap colorMask = QBitmap::fromImage(mask.createMaskFromColor(0));
- foreach (const QRect &rect, QRegion( colorMask ).rects()) {
- QRect xrect = unscale.mapRect(rect).translated(deviceRect.topLeft() - QPoint(pad, pad));
- r += xrect.adjusted(-1, -1, 1, 1) & deviceRect;
- }
- return r;
-}
-
-/*!
- \since 4.4
-
- Returns the item's bounding region granularity; a value between and
- including 0 and 1. The default value is 0 (i.e., the lowest granularity,
- where the bounding region corresponds to the item's bounding rectangle).
-
-\omit
-### NOTE
-\endomit
-
- \sa setBoundingRegionGranularity()
-*/
-qreal QGraphicsItem::boundingRegionGranularity() const
-{
- return d_ptr->hasBoundingRegionGranularity
- ? qvariant_cast<qreal>(d_ptr->extra(QGraphicsItemPrivate::ExtraBoundingRegionGranularity))
- : 0;
-}
-
-/*!
- \since 4.4
- Sets the bounding region granularity to \a granularity; a value between
- and including 0 and 1. The default value is 0 (i.e., the lowest
- granularity, where the bounding region corresponds to the item's bounding
- rectangle).
-
- The granularity is used by boundingRegion() to calculate how fine the
- bounding region of the item should be. The highest achievable granularity
- is 1, where boundingRegion() will return the finest outline possible for
- the respective device (e.g., for a QGraphicsView viewport, this gives you
- a pixel-perfect bounding region). The lowest possible granularity is
- 0. The value of \a granularity describes the ratio between device
- resolution and the resolution of the bounding region (e.g., a value of
- 0.25 will provide a region where each chunk corresponds to 4x4 device
- units / pixels).
-
- \sa boundingRegionGranularity()
-*/
-void QGraphicsItem::setBoundingRegionGranularity(qreal granularity)
-{
- if (granularity < 0.0 || granularity > 1.0) {
- qWarning("QGraphicsItem::setBoundingRegionGranularity: invalid granularity %g", granularity);
- return;
- }
- if (granularity == 0.0) {
- d_ptr->unsetExtra(QGraphicsItemPrivate::ExtraBoundingRegionGranularity);
- d_ptr->hasBoundingRegionGranularity = 0;
- return;
- }
- d_ptr->hasBoundingRegionGranularity = 1;
- d_ptr->setExtra(QGraphicsItemPrivate::ExtraBoundingRegionGranularity,
- QVariant::fromValue<qreal>(granularity));
-}
-
-/*!
- \fn virtual void QGraphicsItem::paint(QPainter *painter, const
- QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0
-
- This function, which is usually called by QGraphicsView, paints the
- contents of an item in local coordinates.
-
- Reimplement this function in a QGraphicsItem subclass to provide the
- item's painting implementation, using \a painter. The \a option parameter
- provides style options for the item, such as its state, exposed area and
- its level-of-detail hints. The \a widget argument is optional. If
- provided, it points to the widget that is being painted on; otherwise, it
- is 0. For cached painting, \a widget is always 0.
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 10
-
- The painter's pen is 0-width by default, and its pen is initialized to the
- QPalette::Text brush from the paint device's palette. The brush is
- initialized to QPalette::Window.
-
- Make sure to constrain all painting inside the boundaries of
- boundingRect() to avoid rendering artifacts (as QGraphicsView does not
- clip the painter for you). In particular, when QPainter renders the
- outline of a shape using an assigned QPen, half of the outline will be
- drawn outside, and half inside, the shape you're rendering (e.g., with a
- pen width of 2 units, you must draw outlines 1 unit inside
- boundingRect()). QGraphicsItem does not support use of cosmetic pens with
- a non-zero width.
-
- All painting is done in local coordinates.
-
- \sa setCacheMode(), QPen::width(), {Item Coordinates}, ItemUsesExtendedStyleOption
-*/
-
-/*!
- \internal
- Returns true if we can discard an update request; otherwise false.
-*/
-bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreVisibleBit, bool ignoreDirtyBit,
- bool ignoreOpacity) const
-{
- // No scene, or if the scene is updating everything, means we have nothing
- // to do. The only exception is if the scene tracks the growing scene rect.
- return !scene
- || (!visible && !ignoreVisibleBit && !this->ignoreVisible)
- || (!ignoreDirtyBit && fullUpdatePending)
- || (!ignoreOpacity && !this->ignoreOpacity && childrenCombineOpacity() && isFullyTransparent());
-}
-
-/*!
- \internal
-*/
-int QGraphicsItemPrivate::depth() const
-{
- if (itemDepth == -1)
- const_cast<QGraphicsItemPrivate *>(this)->resolveDepth();
-
- return itemDepth;
-}
-
-/*!
- \internal
-*/
-#ifndef QT_NO_GRAPHICSEFFECT
-void QGraphicsItemPrivate::invalidateParentGraphicsEffectsRecursively()
-{
- QGraphicsItemPrivate *itemPrivate = this;
- do {
- if (itemPrivate->graphicsEffect) {
- itemPrivate->notifyInvalidated = 1;
-
- if (!itemPrivate->updateDueToGraphicsEffect)
- static_cast<QGraphicsItemEffectSourcePrivate *>(itemPrivate->graphicsEffect->d_func()->source->d_func())->invalidateCache();
- }
- } while ((itemPrivate = itemPrivate->parent ? itemPrivate->parent->d_ptr.data() : 0));
-}
-
-void QGraphicsItemPrivate::invalidateChildGraphicsEffectsRecursively(QGraphicsItemPrivate::InvalidateReason reason)
-{
- if (!mayHaveChildWithGraphicsEffect)
- return;
-
- for (int i = 0; i < children.size(); ++i) {
- QGraphicsItemPrivate *childPrivate = children.at(i)->d_ptr.data();
- if (reason == OpacityChanged && (childPrivate->flags & QGraphicsItem::ItemIgnoresParentOpacity))
- continue;
- if (childPrivate->graphicsEffect) {
- childPrivate->notifyInvalidated = 1;
- static_cast<QGraphicsItemEffectSourcePrivate *>(childPrivate->graphicsEffect->d_func()->source->d_func())->invalidateCache();
- }
-
- childPrivate->invalidateChildGraphicsEffectsRecursively(reason);
- }
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::invalidateDepthRecursively()
-{
- if (itemDepth == -1)
- return;
-
- itemDepth = -1;
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->invalidateDepthRecursively();
-}
-
-/*!
- \internal
-
- Resolves the stacking depth of this object and all its ancestors.
-*/
-void QGraphicsItemPrivate::resolveDepth()
-{
- if (!parent)
- itemDepth = 0;
- else {
- if (parent->d_ptr->itemDepth == -1)
- parent->d_ptr->resolveDepth();
- itemDepth = parent->d_ptr->itemDepth + 1;
- }
-}
-
-/*!
- \internal
-
- ### This function is almost identical to
- QGraphicsScenePrivate::registerTopLevelItem().
-*/
-void QGraphicsItemPrivate::addChild(QGraphicsItem *child)
-{
- // Remove all holes from the sibling index list. Now the max index
- // number is equal to the size of the children list.
- ensureSequentialSiblingIndex();
- needSortChildren = 1; // ### maybe 0
- child->d_ptr->siblingIndex = children.size();
- children.append(child);
- if (isObject)
- emit static_cast<QGraphicsObject *>(q_ptr)->childrenChanged();
-}
-
-/*!
- \internal
-
- ### This function is almost identical to
- QGraphicsScenePrivate::unregisterTopLevelItem().
-*/
-void QGraphicsItemPrivate::removeChild(QGraphicsItem *child)
-{
- // When removing elements in the middle of the children list,
- // there will be a "gap" in the list of sibling indexes (0,1,3,4).
- if (!holesInSiblingIndex)
- holesInSiblingIndex = child->d_ptr->siblingIndex != children.size() - 1;
- if (sequentialOrdering && !holesInSiblingIndex)
- children.removeAt(child->d_ptr->siblingIndex);
- else
- children.removeOne(child);
- // NB! Do not use children.removeAt(child->d_ptr->siblingIndex) because
- // the child is not guaranteed to be at the index after the list is sorted.
- // (see ensureSortedChildren()).
- child->d_ptr->siblingIndex = -1;
- if (isObject)
- emit static_cast<QGraphicsObject *>(q_ptr)->childrenChanged();
-}
-
-/*!
- \internal
-*/
-QGraphicsItemCache *QGraphicsItemPrivate::maybeExtraItemCache() const
-{
- return (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData));
-}
-
-/*!
- \internal
-*/
-QGraphicsItemCache *QGraphicsItemPrivate::extraItemCache() const
-{
- QGraphicsItemCache *c = (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData));
- if (!c) {
- QGraphicsItemPrivate *that = const_cast<QGraphicsItemPrivate *>(this);
- c = new QGraphicsItemCache;
- that->setExtra(ExtraCacheData, QVariant::fromValue<void *>(c));
- }
- return c;
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::removeExtraItemCache()
-{
- QGraphicsItemCache *c = (QGraphicsItemCache *)qvariant_cast<void *>(extra(ExtraCacheData));
- if (c) {
- c->purge();
- delete c;
- }
- unsetExtra(ExtraCacheData);
-}
-
-void QGraphicsItemPrivate::updatePaintedViewBoundingRects(bool updateChildren)
-{
- if (!scene)
- return;
-
- for (int i = 0; i < scene->d_func()->views.size(); ++i) {
- QGraphicsViewPrivate *viewPrivate = scene->d_func()->views.at(i)->d_func();
- QRect rect = paintedViewBoundingRects.value(viewPrivate->viewport);
- rect.translate(viewPrivate->dirtyScrollOffset);
- viewPrivate->updateRect(rect);
- }
-
- if (updateChildren) {
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->updatePaintedViewBoundingRects(true);
- }
-}
-
-// Traverses all the ancestors up to the top-level and updates the pointer to
-// always point to the top-most item that has a dirty scene transform.
-// It then backtracks to the top-most dirty item and start calculating the
-// scene transform by combining the item's transform (+pos) with the parent's
-// cached scene transform (which we at this point know for sure is valid).
-void QGraphicsItemPrivate::ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem)
-{
- Q_ASSERT(topMostDirtyItem);
-
- if (dirtySceneTransform)
- *topMostDirtyItem = q_ptr;
-
- if (parent)
- parent->d_ptr->ensureSceneTransformRecursive(topMostDirtyItem);
-
- if (*topMostDirtyItem == q_ptr) {
- if (!dirtySceneTransform)
- return; // OK, neither my ancestors nor I have dirty scene transforms.
- *topMostDirtyItem = 0;
- } else if (*topMostDirtyItem) {
- return; // Continue backtrack.
- }
-
- // This item and all its descendants have dirty scene transforms.
- // We're about to validate this item's scene transform, so we have to
- // invalidate all the children; otherwise there's no way for the descendants
- // to detect that the ancestor has changed.
- invalidateChildrenSceneTransform();
-
- // COMBINE my transform with the parent's scene transform.
- updateSceneTransformFromParent();
- Q_ASSERT(!dirtySceneTransform);
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::setSubFocus(QGraphicsItem *rootItem, QGraphicsItem *stopItem)
-{
- // Update focus child chain. Stop at panels, or if this item
- // is hidden, stop at the first item with a visible parent.
- QGraphicsItem *parent = rootItem ? rootItem : q_ptr;
- if (parent->panel() != q_ptr->panel())
- return;
-
- do {
- // Clear any existing ancestor's subFocusItem.
- if (parent != q_ptr && parent->d_ptr->subFocusItem) {
- if (parent->d_ptr->subFocusItem == q_ptr)
- break;
- parent->d_ptr->subFocusItem->d_ptr->clearSubFocus(0, stopItem);
- }
- parent->d_ptr->subFocusItem = q_ptr;
- parent->d_ptr->subFocusItemChange();
- } while (!parent->isPanel() && (parent = parent->d_ptr->parent) && (visible || !parent->d_ptr->visible));
-
- if (scene && !scene->isActive()) {
- scene->d_func()->passiveFocusItem = subFocusItem;
- scene->d_func()->lastFocusItem = subFocusItem;
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsItemPrivate::clearSubFocus(QGraphicsItem *rootItem, QGraphicsItem *stopItem)
-{
- // Reset sub focus chain.
- QGraphicsItem *parent = rootItem ? rootItem : q_ptr;
- do {
- if (parent->d_ptr->subFocusItem != q_ptr)
- break;
- parent->d_ptr->subFocusItem = 0;
- if (parent != stopItem && !parent->isAncestorOf(stopItem))
- parent->d_ptr->subFocusItemChange();
- } while (!parent->isPanel() && (parent = parent->d_ptr->parent));
-}
-
-/*!
- \internal
-
- Sets the focusProxy pointer to 0 for all items that have this item as their
- focusProxy. ### Qt 5: Use QPointer instead.
-*/
-void QGraphicsItemPrivate::resetFocusProxy()
-{
- for (int i = 0; i < focusProxyRefs.size(); ++i)
- *focusProxyRefs.at(i) = 0;
- focusProxyRefs.clear();
-}
-
-/*!
- \internal
-
- Subclasses can reimplement this function to be notified when subFocusItem
- changes.
-*/
-void QGraphicsItemPrivate::subFocusItemChange()
-{
-}
-
-/*!
- \internal
-
- Subclasses can reimplement this function to be notified when an item
- becomes a focusScopeItem (or is no longer a focusScopeItem).
-*/
-void QGraphicsItemPrivate::focusScopeItemChange(bool isSubFocusItem)
-{
- Q_UNUSED(isSubFocusItem);
-}
-
-/*!
- \internal
-
- Subclasses can reimplement this function to be notified when its
- siblingIndex order is changed.
-*/
-void QGraphicsItemPrivate::siblingOrderChange()
-{
-}
-
-/*!
- \internal
-
- Tells us if it is a proxy widget
-*/
-bool QGraphicsItemPrivate::isProxyWidget() const
-{
- return false;
-}
-
-/*!
- Schedules a redraw of the area covered by \a rect in this item. You can
- call this function whenever your item needs to be redrawn, such as if it
- changes appearance or size.
-
- This function does not cause an immediate paint; instead it schedules a
- paint request that is processed by QGraphicsView after control reaches the
- event loop. The item will only be redrawn if it is visible in any
- associated view.
-
- As a side effect of the item being repainted, other items that overlap the
- area \a rect may also be repainted.
-
- If the item is invisible (i.e., isVisible() returns false), this function
- does nothing.
-
- \sa paint(), boundingRect()
-*/
-void QGraphicsItem::update(const QRectF &rect)
-{
- if (rect.isEmpty() && !rect.isNull())
- return;
-
- // Make sure we notify effects about invalidated source.
-#ifndef QT_NO_GRAPHICSEFFECT
- d_ptr->invalidateParentGraphicsEffectsRecursively();
-#endif //QT_NO_GRAPHICSEFFECT
-
- if (CacheMode(d_ptr->cacheMode) != NoCache) {
- // Invalidate cache.
- QGraphicsItemCache *cache = d_ptr->extraItemCache();
- if (!cache->allExposed) {
- if (rect.isNull()) {
- cache->allExposed = true;
- cache->exposed.clear();
- } else {
- cache->exposed.append(rect);
- }
- }
- // Only invalidate cache; item is already dirty.
- if (d_ptr->fullUpdatePending)
- return;
- }
-
- if (d_ptr->scene)
- d_ptr->scene->d_func()->markDirty(this, rect);
-}
-
-/*!
- \since 4.4
- Scrolls the contents of \a rect by \a dx, \a dy. If \a rect is a null rect
- (the default), the item's bounding rect is scrolled.
-
- Scrolling provides a fast alternative to simply redrawing when the
- contents of the item (or parts of the item) are shifted vertically or
- horizontally. Depending on the current transformation and the capabilities
- of the paint device (i.e., the viewport), this operation may consist of
- simply moving pixels from one location to another using memmove(). In most
- cases this is faster than rerendering the entire area.
-
- After scrolling, the item will issue an update for the newly exposed
- areas. If scrolling is not supported (e.g., you are rendering to an OpenGL
- viewport, which does not benefit from scroll optimizations), this function
- is equivalent to calling update(\a rect).
-
- \bold{Note:} Scrolling is only supported when QGraphicsItem::ItemCoordinateCache
- is enabled; in all other cases calling this function is equivalent to calling
- update(\a rect). If you for sure know that the item is opaque and not overlapped
- by other items, you can map the \a rect to viewport coordinates and scroll the
- viewport.
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 19
-
- \sa boundingRect()
-*/
-void QGraphicsItem::scroll(qreal dx, qreal dy, const QRectF &rect)
-{
- Q_D(QGraphicsItem);
- if (dx == 0.0 && dy == 0.0)
- return;
- if (!d->scene)
- return;
-
- // Accelerated scrolling means moving pixels from one location to another
- // and only redraw the newly exposed area. The following requirements must
- // be fulfilled in order to do that:
- //
- // 1) Item is opaque.
- // 2) Item is not overlapped by other items.
- //
- // There's (yet) no way to detect whether an item is opaque or not, which means
- // we cannot do accelerated scrolling unless the cache is enabled. In case of using
- // DeviceCoordinate cache we also have to take the device transform into account in
- // order to determine whether we can do accelerated scrolling or not. That's left out
- // for simplicity here, but it is definitely something we can consider in the future
- // as a performance improvement.
- if (d->cacheMode != QGraphicsItem::ItemCoordinateCache
- || !qFuzzyIsNull(dx - int(dx)) || !qFuzzyIsNull(dy - int(dy))) {
- update(rect);
- return;
- }
-
- QGraphicsItemCache *cache = d->extraItemCache();
- if (cache->allExposed || cache->fixedSize.isValid()) {
- // Cache is either invalidated or item is scaled (see QGraphicsItem::setCacheMode).
- update(rect);
- return;
- }
-
- // Find pixmap in cache.
- QPixmap cachedPixmap;
- if (!QPixmapCache::find(cache->key, &cachedPixmap)) {
- update(rect);
- return;
- }
-
- QRect scrollRect = (rect.isNull() ? boundingRect() : rect).toAlignedRect();
- if (!scrollRect.intersects(cache->boundingRect))
- return; // Nothing to scroll.
-
- // Remove from cache to avoid deep copy when modifying.
- QPixmapCache::remove(cache->key);
-
- QRegion exposed;
- cachedPixmap.scroll(dx, dy, scrollRect.translated(-cache->boundingRect.topLeft()), &exposed);
-
- // Reinsert into cache.
- cache->key = QPixmapCache::insert(cachedPixmap);
-
- // Translate the existing expose.
- for (int i = 0; i < cache->exposed.size(); ++i) {
- QRectF &e = cache->exposed[i];
- if (!rect.isNull() && !e.intersects(rect))
- continue;
- e.translate(dx, dy);
- }
-
- // Append newly exposed areas. Note that the exposed region is currently
- // in pixmap coordinates, so we have to translate it to item coordinates.
- exposed.translate(cache->boundingRect.topLeft());
- const QVector<QRect> exposedRects = exposed.rects();
- for (int i = 0; i < exposedRects.size(); ++i)
- cache->exposed += exposedRects.at(i);
-
- // Trigger update. This will redraw the newly exposed area and make sure
- // the pixmap is re-blitted in case there are overlapping items.
- d->scene->d_func()->markDirty(this, rect);
-}
-
-/*!
- \fn void QGraphicsItem::update(qreal x, qreal y, qreal width, qreal height)
- \overload
-
- This convenience function is equivalent to calling update(QRectF(\a x, \a
- y, \a width, \a height)).
-*/
-
-/*!
- Maps the point \a point, which is in this item's coordinate system, to \a
- item's coordinate system, and returns the mapped coordinate.
-
- If \a item is 0, this function returns the same as mapToScene().
-
- \sa itemTransform(), mapToParent(), mapToScene(), transform(), mapFromItem(), {The Graphics
- View Coordinate System}
-*/
-QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPointF &point) const
-{
- if (item)
- return itemTransform(item).map(point);
- return mapToScene(point);
-}
-
-/*!
- \fn QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal x, qreal y) const
- \overload
-
- This convenience function is equivalent to calling mapToItem(\a item,
- QPointF(\a x, \a y)).
-*/
-
-/*!
- Maps the point \a point, which is in this item's coordinate system, to its
- parent's coordinate system, and returns the mapped coordinate. If the item
- has no parent, \a point will be mapped to the scene's coordinate system.
-
- \sa mapToItem(), mapToScene(), transform(), mapFromParent(), {The Graphics
- View Coordinate System}
-*/
-QPointF QGraphicsItem::mapToParent(const QPointF &point) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return point + d_ptr->pos;
- return d_ptr->transformToParent().map(point);
-}
-
-/*!
- \fn QPointF QGraphicsItem::mapToParent(qreal x, qreal y) const
- \overload
-
- This convenience function is equivalent to calling mapToParent(QPointF(\a
- x, \a y)).
-*/
-
-/*!
- Maps the point \a point, which is in this item's coordinate system, to the
- scene's coordinate system, and returns the mapped coordinate.
-
- \sa mapToItem(), mapToParent(), transform(), mapFromScene(), {The Graphics
- View Coordinate System}
-*/
-QPointF QGraphicsItem::mapToScene(const QPointF &point) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return QPointF(point.x() + d_ptr->sceneTransform.dx(), point.y() + d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.map(point);
-}
-
-/*!
- \fn QPointF QGraphicsItem::mapToScene(qreal x, qreal y) const
- \overload
-
- This convenience function is equivalent to calling mapToScene(QPointF(\a
- x, \a y)).
-*/
-
-/*!
- Maps the rectangle \a rect, which is in this item's coordinate system, to
- \a item's coordinate system, and returns the mapped rectangle as a polygon.
-
- If \a item is 0, this function returns the same as mapToScene().
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QRectF &rect) const
-{
- if (item)
- return itemTransform(item).map(rect);
- return mapToScene(rect);
-}
-
-/*!
- \fn QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling mapToItem(item, QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Maps the rectangle \a rect, which is in this item's coordinate system, to
- its parent's coordinate system, and returns the mapped rectangle as a
- polygon. If the item has no parent, \a rect will be mapped to the scene's
- coordinate system.
-
- \sa mapToScene(), mapToItem(), mapFromParent(), {The Graphics View
- Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapToParent(const QRectF &rect) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return rect.translated(d_ptr->pos);
- return d_ptr->transformToParent().map(rect);
-}
-
-/*!
- \fn QPolygonF QGraphicsItem::mapToParent(qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling mapToParent(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Maps the rectangle \a rect, which is in this item's coordinate system, to
- the scene's coordinate system, and returns the mapped rectangle as a polygon.
-
- \sa mapToParent(), mapToItem(), mapFromScene(), {The Graphics View
- Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapToScene(const QRectF &rect) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return rect.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.map(rect);
-}
-
-/*!
- \fn QPolygonF QGraphicsItem::mapToScene(qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling mapToScene(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- \since 4.5
-
- Maps the rectangle \a rect, which is in this item's coordinate system, to
- \a item's coordinate system, and returns the mapped rectangle as a new
- rectangle (i.e., the bounding rectangle of the resulting polygon).
-
- If \a item is 0, this function returns the same as mapRectToScene().
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, const QRectF &rect) const
-{
- if (item)
- return itemTransform(item).mapRect(rect);
- return mapRectToScene(rect);
-}
-
-/*!
- \fn QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const
- \since 4.5
-
- This convenience function is equivalent to calling mapRectToItem(item, QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- \since 4.5
-
- Maps the rectangle \a rect, which is in this item's coordinate system, to
- its parent's coordinate system, and returns the mapped rectangle as a new
- rectangle (i.e., the bounding rectangle of the resulting polygon).
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::mapRectToParent(const QRectF &rect) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return rect.translated(d_ptr->pos);
- return d_ptr->transformToParent().mapRect(rect);
-}
-
-/*!
- \fn QRectF QGraphicsItem::mapRectToParent(qreal x, qreal y, qreal w, qreal h) const
- \since 4.5
-
- This convenience function is equivalent to calling mapRectToParent(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- \since 4.5
-
- Maps the rectangle \a rect, which is in this item's coordinate system, to
- the scene coordinate system, and returns the mapped rectangle as a new
- rectangle (i.e., the bounding rectangle of the resulting polygon).
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::mapRectToScene(const QRectF &rect) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return rect.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.mapRect(rect);
-}
-
-/*!
- \fn QRectF QGraphicsItem::mapRectToScene(qreal x, qreal y, qreal w, qreal h) const
- \since 4.5
-
- This convenience function is equivalent to calling mapRectToScene(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- \since 4.5
-
- Maps the rectangle \a rect, which is in \a item's coordinate system, to
- this item's coordinate system, and returns the mapped rectangle as a new
- rectangle (i.e., the bounding rectangle of the resulting polygon).
-
- If \a item is 0, this function returns the same as mapRectFromScene().
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, const QRectF &rect) const
-{
- if (item)
- return item->itemTransform(this).mapRect(rect);
- return mapRectFromScene(rect);
-}
-
-/*!
- \fn QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const
- \since 4.5
-
- This convenience function is equivalent to calling mapRectFromItem(item, QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- \since 4.5
-
- Maps the rectangle \a rect, which is in this item's parent's coordinate
- system, to this item's coordinate system, and returns the mapped rectangle
- as a new rectangle (i.e., the bounding rectangle of the resulting
- polygon).
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::mapRectFromParent(const QRectF &rect) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return rect.translated(-d_ptr->pos);
- return d_ptr->transformToParent().inverted().mapRect(rect);
-}
-
-/*!
- \fn QRectF QGraphicsItem::mapRectFromParent(qreal x, qreal y, qreal w, qreal h) const
- \since 4.5
-
- This convenience function is equivalent to calling mapRectFromParent(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- \since 4.5
-
- Maps the rectangle \a rect, which is in scene coordinates, to this item's
- coordinate system, and returns the mapped rectangle as a new rectangle
- (i.e., the bounding rectangle of the resulting polygon).
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QRectF QGraphicsItem::mapRectFromScene(const QRectF &rect) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return rect.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.inverted().mapRect(rect);
-}
-
-/*!
- \fn QRectF QGraphicsItem::mapRectFromScene(qreal x, qreal y, qreal w, qreal h) const
- \since 4.5
-
- This convenience function is equivalent to calling mapRectFromScene(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Maps the polygon \a polygon, which is in this item's coordinate system, to
- \a item's coordinate system, and returns the mapped polygon.
-
- If \a item is 0, this function returns the same as mapToScene().
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPolygonF &polygon) const
-{
- if (item)
- return itemTransform(item).map(polygon);
- return mapToScene(polygon);
-}
-
-/*!
- Maps the polygon \a polygon, which is in this item's coordinate system, to
- its parent's coordinate system, and returns the mapped polygon. If the
- item has no parent, \a polygon will be mapped to the scene's coordinate
- system.
-
- \sa mapToScene(), mapToItem(), mapFromParent(), {The Graphics View
- Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapToParent(const QPolygonF &polygon) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return polygon.translated(d_ptr->pos);
- return d_ptr->transformToParent().map(polygon);
-}
-
-/*!
- Maps the polygon \a polygon, which is in this item's coordinate system, to
- the scene's coordinate system, and returns the mapped polygon.
-
- \sa mapToParent(), mapToItem(), mapFromScene(), {The Graphics View
- Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapToScene(const QPolygonF &polygon) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return polygon.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.map(polygon);
-}
-
-/*!
- Maps the path \a path, which is in this item's coordinate system, to
- \a item's coordinate system, and returns the mapped path.
-
- If \a item is 0, this function returns the same as mapToScene().
-
- \sa itemTransform(), mapToParent(), mapToScene(), mapFromItem(), {The
- Graphics View Coordinate System}
-*/
-QPainterPath QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPainterPath &path) const
-{
- if (item)
- return itemTransform(item).map(path);
- return mapToScene(path);
-}
-
-/*!
- Maps the path \a path, which is in this item's coordinate system, to
- its parent's coordinate system, and returns the mapped path. If the
- item has no parent, \a path will be mapped to the scene's coordinate
- system.
-
- \sa mapToScene(), mapToItem(), mapFromParent(), {The Graphics View
- Coordinate System}
-*/
-QPainterPath QGraphicsItem::mapToParent(const QPainterPath &path) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return path.translated(d_ptr->pos);
- return d_ptr->transformToParent().map(path);
-}
-
-/*!
- Maps the path \a path, which is in this item's coordinate system, to
- the scene's coordinate system, and returns the mapped path.
-
- \sa mapToParent(), mapToItem(), mapFromScene(), {The Graphics View
- Coordinate System}
-*/
-QPainterPath QGraphicsItem::mapToScene(const QPainterPath &path) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return path.translated(d_ptr->sceneTransform.dx(), d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.map(path);
-}
-
-/*!
- Maps the point \a point, which is in \a item's coordinate system, to this
- item's coordinate system, and returns the mapped coordinate.
-
- If \a item is 0, this function returns the same as mapFromScene().
-
- \sa itemTransform(), mapFromParent(), mapFromScene(), transform(), mapToItem(), {The Graphics
- View Coordinate System}
-*/
-QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPointF &point) const
-{
- if (item)
- return item->itemTransform(this).map(point);
- return mapFromScene(point);
-}
-
-/*!
- \fn QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal x, qreal y) const
- \overload
-
- This convenience function is equivalent to calling mapFromItem(\a item,
- QPointF(\a x, \a y)).
-*/
-
-/*!
- Maps the point \a point, which is in this item's parent's coordinate
- system, to this item's coordinate system, and returns the mapped
- coordinate.
-
- \sa mapFromItem(), mapFromScene(), transform(), mapToParent(), {The Graphics
- View Coordinate System}
-*/
-QPointF QGraphicsItem::mapFromParent(const QPointF &point) const
-{
- // COMBINE
- if (d_ptr->transformData)
- return d_ptr->transformToParent().inverted().map(point);
- return point - d_ptr->pos;
-}
-
-/*!
- \fn QPointF QGraphicsItem::mapFromParent(qreal x, qreal y) const
- \overload
-
- This convenience function is equivalent to calling
- mapFromParent(QPointF(\a x, \a y)).
-*/
-
-/*!
- Maps the point \a point, which is in this item's scene's coordinate
- system, to this item's coordinate system, and returns the mapped
- coordinate.
-
- \sa mapFromItem(), mapFromParent(), transform(), mapToScene(), {The Graphics
- View Coordinate System}
-*/
-QPointF QGraphicsItem::mapFromScene(const QPointF &point) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return QPointF(point.x() - d_ptr->sceneTransform.dx(), point.y() - d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.inverted().map(point);
-}
-
-/*!
- \fn QPointF QGraphicsItem::mapFromScene(qreal x, qreal y) const
- \overload
-
- This convenience function is equivalent to calling mapFromScene(QPointF(\a
- x, \a y)).
-*/
-
-/*!
- Maps the rectangle \a rect, which is in \a item's coordinate system, to
- this item's coordinate system, and returns the mapped rectangle as a
- polygon.
-
- If \a item is 0, this function returns the same as mapFromScene()
-
- \sa itemTransform(), mapToItem(), mapFromParent(), transform(), {The Graphics View Coordinate
- System}
-*/
-QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QRectF &rect) const
-{
- if (item)
- return item->itemTransform(this).map(rect);
- return mapFromScene(rect);
-}
-
-/*!
- \fn QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling mapFromItem(item, QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Maps the rectangle \a rect, which is in this item's parent's coordinate
- system, to this item's coordinate system, and returns the mapped rectangle
- as a polygon.
-
- \sa mapToParent(), mapFromItem(), transform(), {The Graphics View Coordinate
- System}
-*/
-QPolygonF QGraphicsItem::mapFromParent(const QRectF &rect) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return rect.translated(-d_ptr->pos);
- return d_ptr->transformToParent().inverted().map(rect);
-}
-
-/*!
- \fn QPolygonF QGraphicsItem::mapFromParent(qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling mapFromItem(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Maps the rectangle \a rect, which is in this item's scene's coordinate
- system, to this item's coordinate system, and returns the mapped rectangle
- as a polygon.
-
- \sa mapToScene(), mapFromItem(), transform(), {The Graphics View Coordinate
- System}
-*/
-QPolygonF QGraphicsItem::mapFromScene(const QRectF &rect) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return rect.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.inverted().map(rect);
-}
-
-/*!
- \fn QPolygonF QGraphicsItem::mapFromScene(qreal x, qreal y, qreal w, qreal h) const
- \since 4.3
-
- This convenience function is equivalent to calling mapFromScene(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Maps the polygon \a polygon, which is in \a item's coordinate system, to
- this item's coordinate system, and returns the mapped polygon.
-
- If \a item is 0, this function returns the same as mapFromScene().
-
- \sa itemTransform(), mapToItem(), mapFromParent(), transform(), {The
- Graphics View Coordinate System}
-*/
-QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPolygonF &polygon) const
-{
- if (item)
- return item->itemTransform(this).map(polygon);
- return mapFromScene(polygon);
-}
-
-/*!
- Maps the polygon \a polygon, which is in this item's parent's coordinate
- system, to this item's coordinate system, and returns the mapped polygon.
-
- \sa mapToParent(), mapToItem(), transform(), {The Graphics View Coordinate
- System}
-*/
-QPolygonF QGraphicsItem::mapFromParent(const QPolygonF &polygon) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return polygon.translated(-d_ptr->pos);
- return d_ptr->transformToParent().inverted().map(polygon);
-}
-
-/*!
- Maps the polygon \a polygon, which is in this item's scene's coordinate
- system, to this item's coordinate system, and returns the mapped polygon.
-
- \sa mapToScene(), mapFromParent(), transform(), {The Graphics View Coordinate
- System}
-*/
-QPolygonF QGraphicsItem::mapFromScene(const QPolygonF &polygon) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return polygon.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.inverted().map(polygon);
-}
-
-/*!
- Maps the path \a path, which is in \a item's coordinate system, to
- this item's coordinate system, and returns the mapped path.
-
- If \a item is 0, this function returns the same as mapFromScene().
-
- \sa itemTransform(), mapFromParent(), mapFromScene(), mapToItem(), {The
- Graphics View Coordinate System}
-*/
-QPainterPath QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPainterPath &path) const
-{
- if (item)
- return item->itemTransform(this).map(path);
- return mapFromScene(path);
-}
-
-/*!
- Maps the path \a path, which is in this item's parent's coordinate
- system, to this item's coordinate system, and returns the mapped path.
-
- \sa mapFromScene(), mapFromItem(), mapToParent(), {The Graphics View
- Coordinate System}
-*/
-QPainterPath QGraphicsItem::mapFromParent(const QPainterPath &path) const
-{
- // COMBINE
- if (!d_ptr->transformData)
- return path.translated(-d_ptr->pos);
- return d_ptr->transformToParent().inverted().map(path);
-}
-
-/*!
- Maps the path \a path, which is in this item's scene's coordinate
- system, to this item's coordinate system, and returns the mapped path.
-
- \sa mapFromParent(), mapFromItem(), mapToScene(), {The Graphics View
- Coordinate System}
-*/
-QPainterPath QGraphicsItem::mapFromScene(const QPainterPath &path) const
-{
- if (d_ptr->hasTranslateOnlySceneTransform())
- return path.translated(-d_ptr->sceneTransform.dx(), -d_ptr->sceneTransform.dy());
- return d_ptr->sceneTransform.inverted().map(path);
-}
-
-/*!
- Returns true if this item is an ancestor of \a child (i.e., if this item
- is \a child's parent, or one of \a child's parent's ancestors).
-
- \sa parentItem()
-*/
-bool QGraphicsItem::isAncestorOf(const QGraphicsItem *child) const
-{
- if (!child || child == this)
- return false;
- if (child->d_ptr->depth() < d_ptr->depth())
- return false;
- const QGraphicsItem *ancestor = child;
- while ((ancestor = ancestor->d_ptr->parent)) {
- if (ancestor == this)
- return true;
- }
- return false;
-}
-
-/*!
- \since 4.4
-
- Returns the closest common ancestor item of this item and \a other, or 0
- if either \a other is 0, or there is no common ancestor.
-
- \sa isAncestorOf()
-*/
-QGraphicsItem *QGraphicsItem::commonAncestorItem(const QGraphicsItem *other) const
-{
- if (!other)
- return 0;
- if (other == this)
- return const_cast<QGraphicsItem *>(this);
- const QGraphicsItem *thisw = this;
- const QGraphicsItem *otherw = other;
- int thisDepth = d_ptr->depth();
- int otherDepth = other->d_ptr->depth();
- while (thisDepth > otherDepth) {
- thisw = thisw->d_ptr->parent;
- --thisDepth;
- }
- while (otherDepth > thisDepth) {
- otherw = otherw->d_ptr->parent;
- --otherDepth;
- }
- while (thisw && thisw != otherw) {
- thisw = thisw->d_ptr->parent;
- otherw = otherw->d_ptr->parent;
- }
- return const_cast<QGraphicsItem *>(thisw);
-}
-
-/*!
- \since 4,4
- Returns true if this item is currently under the mouse cursor in one of
- the views; otherwise, false is returned.
-
- \sa QGraphicsScene::views(), QCursor::pos()
-*/
-bool QGraphicsItem::isUnderMouse() const
-{
- Q_D(const QGraphicsItem);
- if (!d->scene)
- return false;
-
- QPoint cursorPos = QCursor::pos();
- foreach (QGraphicsView *view, d->scene->views()) {
- if (contains(mapFromScene(view->mapToScene(view->mapFromGlobal(cursorPos)))))
- return true;
- }
- return false;
-}
-
-/*!
- Returns this item's custom data for the key \a key as a QVariant.
-
- Custom item data is useful for storing arbitrary properties in any
- item. Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 11
-
- Qt does not use this feature for storing data; it is provided solely
- for the convenience of the user.
-
- \sa setData()
-*/
-QVariant QGraphicsItem::data(int key) const
-{
- QGraphicsItemCustomDataStore *store = qt_dataStore();
- if (!store->data.contains(this))
- return QVariant();
- return store->data.value(this).value(key);
-}
-
-/*!
- Sets this item's custom data for the key \a key to \a value.
-
- Custom item data is useful for storing arbitrary properties for any
- item. Qt does not use this feature for storing data; it is provided solely
- for the convenience of the user.
-
- \sa data()
-*/
-void QGraphicsItem::setData(int key, const QVariant &value)
-{
- qt_dataStore()->data[this][key] = value;
-}
-
-/*!
- \fn T qgraphicsitem_cast(QGraphicsItem *item)
- \relates QGraphicsItem
- \since 4.2
-
- Returns the given \a item cast to type T if \a item is of type T;
- otherwise, 0 is returned.
-
- \note To make this function work correctly with custom items, reimplement
- the \l{QGraphicsItem::}{type()} function for each custom QGraphicsItem
- subclass.
-
- \sa QGraphicsItem::type(), QGraphicsItem::UserType
-*/
-
-/*!
- Returns the type of an item as an int. All standard graphicsitem classes
- are associated with a unique value; see QGraphicsItem::Type. This type
- information is used by qgraphicsitem_cast() to distinguish between types.
-
- The default implementation (in QGraphicsItem) returns UserType.
-
- To enable use of qgraphicsitem_cast() with a custom item, reimplement this
- function and declare a Type enum value equal to your custom item's type.
- Custom items must return a value larger than or equal to UserType (65536).
-
- For example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp QGraphicsItem type
-
- \sa UserType
-*/
-int QGraphicsItem::type() const
-{
- return (int)UserType;
-}
-
-/*!
- Installs an event filter for this item on \a filterItem, causing
- all events for this item to first pass through \a filterItem's
- sceneEventFilter() function.
-
- To filter another item's events, install this item as an event filter
- for the other item. Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 12
-
- An item can only filter events for other items in the same
- scene. Also, an item cannot filter its own events; instead, you
- can reimplement sceneEvent() directly.
-
- Items must belong to a scene for scene event filters to be installed and
- used.
-
- \sa removeSceneEventFilter(), sceneEventFilter(), sceneEvent()
-*/
-void QGraphicsItem::installSceneEventFilter(QGraphicsItem *filterItem)
-{
- if (!d_ptr->scene) {
- qWarning("QGraphicsItem::installSceneEventFilter: event filters can only be installed"
- " on items in a scene.");
- return;
- }
- if (d_ptr->scene != filterItem->scene()) {
- qWarning("QGraphicsItem::installSceneEventFilter: event filters can only be installed"
- " on items in the same scene.");
- return;
- }
- d_ptr->scene->d_func()->installSceneEventFilter(this, filterItem);
-}
-
-/*!
- Removes an event filter on this item from \a filterItem.
-
- \sa installSceneEventFilter()
-*/
-void QGraphicsItem::removeSceneEventFilter(QGraphicsItem *filterItem)
-{
- if (!d_ptr->scene || d_ptr->scene != filterItem->scene())
- return;
- d_ptr->scene->d_func()->removeSceneEventFilter(this, filterItem);
-}
-
-/*!
- Filters events for the item \a watched. \a event is the filtered
- event.
-
- Reimplementing this function in a subclass makes it possible
- for the item to be used as an event filter for other items,
- intercepting all the events send to those items before they are
- able to respond.
-
- Reimplementations must return true to prevent further processing of
- a given event, ensuring that it will not be delivered to the watched
- item, or return false to indicate that the event should be propagated
- further by the event system.
-
- \sa installSceneEventFilter()
-*/
-bool QGraphicsItem::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
-{
- Q_UNUSED(watched);
- Q_UNUSED(event);
- return false;
-}
-
-/*!
- This virtual function receives events to this item. Reimplement
- this function to intercept events before they are dispatched to
- the specialized event handlers contextMenuEvent(), focusInEvent(),
- focusOutEvent(), hoverEnterEvent(), hoverMoveEvent(),
- hoverLeaveEvent(), keyPressEvent(), keyReleaseEvent(),
- mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(), and
- mouseDoubleClickEvent().
-
- Returns true if the event was recognized and handled; otherwise, (e.g., if
- the event type was not recognized,) false is returned.
-
- \a event is the intercepted event.
-*/
-bool QGraphicsItem::sceneEvent(QEvent *event)
-{
- if (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorHandlesChildEvents) {
- if (event->type() == QEvent::HoverEnter || event->type() == QEvent::HoverLeave
- || event->type() == QEvent::DragEnter || event->type() == QEvent::DragLeave) {
- // Hover enter and hover leave events for children are ignored;
- // hover move events are forwarded.
- return true;
- }
-
- QGraphicsItem *handler = this;
- do {
- handler = handler->d_ptr->parent;
- Q_ASSERT(handler);
- } while (handler->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorHandlesChildEvents);
- // Forward the event to the closest parent that handles child
- // events, mapping existing item-local coordinates to its
- // coordinate system.
- d_ptr->remapItemPos(event, handler);
- handler->sceneEvent(event);
- return true;
- }
-
- if (event->type() == QEvent::FocusOut) {
- focusOutEvent(static_cast<QFocusEvent *>(event));
- return true;
- }
-
- if (!d_ptr->visible) {
- // Eaten
- return true;
- }
-
- switch (event->type()) {
- case QEvent::FocusIn:
- focusInEvent(static_cast<QFocusEvent *>(event));
- break;
- case QEvent::GraphicsSceneContextMenu:
- contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
- break;
- case QEvent::GraphicsSceneDragEnter:
- dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneDragMove:
- dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneDragLeave:
- dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneDrop:
- dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneHoverEnter:
- hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
- break;
- case QEvent::GraphicsSceneHoverMove:
- hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
- break;
- case QEvent::GraphicsSceneHoverLeave:
- hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
- break;
- case QEvent::GraphicsSceneMouseMove:
- mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneMousePress:
- mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneMouseRelease:
- mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneMouseDoubleClick:
- mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneWheel:
- wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
- break;
- case QEvent::KeyPress: {
- QKeyEvent *k = static_cast<QKeyEvent *>(event);
- if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
- if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
- bool res = false;
- if (k->key() == Qt::Key_Backtab
- || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
- if (d_ptr->isWidget) {
- res = static_cast<QGraphicsWidget *>(this)->focusNextPrevChild(false);
- } else if (d_ptr->scene) {
- res = d_ptr->scene->focusNextPrevChild(false);
- }
- } else if (k->key() == Qt::Key_Tab) {
- if (d_ptr->isWidget) {
- res = static_cast<QGraphicsWidget *>(this)->focusNextPrevChild(true);
- } else if (d_ptr->scene) {
- res = d_ptr->scene->focusNextPrevChild(true);
- }
- }
- if (!res)
- event->ignore();
- return true;
- }
- }
- keyPressEvent(static_cast<QKeyEvent *>(event));
- break;
- }
- case QEvent::KeyRelease:
- keyReleaseEvent(static_cast<QKeyEvent *>(event));
- break;
- case QEvent::InputMethod:
- inputMethodEvent(static_cast<QInputMethodEvent *>(event));
- break;
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- // Propagate panel activation.
- if (d_ptr->scene) {
- for (int i = 0; i < d_ptr->children.size(); ++i) {
- QGraphicsItem *child = d_ptr->children.at(i);
- if (child->isVisible() && !child->isPanel()) {
- if (!(child->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorHandlesChildEvents))
- d_ptr->scene->sendEvent(child, event);
- }
- }
- }
- break;
- default:
- return false;
- }
-
- return true;
-}
-
-/*!
- This event handler can be reimplemented in a subclass to process context
- menu events. The \a event parameter contains details about the event to
- be handled.
-
- If you ignore the event, (i.e., by calling QEvent::ignore(),) \a event
- will propagate to any item beneath this item. If no items accept the
- event, it will be ignored by the scene, and propagate to the view.
-
- It's common to open a QMenu in response to receiving a context menu
- event. Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 13
-
- The default implementation ignores the event.
-
- \sa sceneEvent()
-*/
-void QGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- drag enter events for this item. Drag enter events are generated as the
- cursor enters the item's area.
-
- By accepting the event, (i.e., by calling QEvent::accept(),) the item will
- accept drop events, in addition to receiving drag move and drag
- leave. Otherwise, the event will be ignored and propagate to the item
- beneath. If the event is accepted, the item will receive a drag move event
- before control goes back to the event loop.
-
- A common implementation of dragEnterEvent accepts or ignores \a event
- depending on the associated mime data in \a event. Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 14
-
- Items do not receive drag and drop events by default; to enable this
- feature, call \c setAcceptDrops(true).
-
- The default implementation does nothing.
-
- \sa dropEvent(), dragMoveEvent(), dragLeaveEvent()
-*/
-void QGraphicsItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsItem);
- // binary compatibility workaround between 4.4 and 4.5
- if (d->isProxyWidget())
- static_cast<QGraphicsProxyWidget*>(this)->dragEnterEvent(event);
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- drag leave events for this item. Drag leave events are generated as the
- cursor leaves the item's area. Most often you will not need to reimplement
- this function, but it can be useful for resetting state in your item
- (e.g., highlighting).
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no effect.
-
- Items do not receive drag and drop events by default; to enable this
- feature, call \c setAcceptDrops(true).
-
- The default implementation does nothing.
-
- \sa dragEnterEvent(), dropEvent(), dragMoveEvent()
-*/
-void QGraphicsItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsItem);
- // binary compatibility workaround between 4.4 and 4.5
- if (d->isProxyWidget())
- static_cast<QGraphicsProxyWidget*>(this)->dragLeaveEvent(event);
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- drag move events for this item. Drag move events are generated as the
- cursor moves around inside the item's area. Most often you will not need
- to reimplement this function; it is used to indicate that only parts of
- the item can accept drops.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event toggles whether
- or not the item will accept drops at the position from the event. By
- default, \a event is accepted, indicating that the item allows drops at
- the specified position.
-
- Items do not receive drag and drop events by default; to enable this
- feature, call \c setAcceptDrops(true).
-
- The default implementation does nothing.
-
- \sa dropEvent(), dragEnterEvent(), dragLeaveEvent()
-*/
-void QGraphicsItem::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsItem);
- // binary compatibility workaround between 4.4 and 4.5
- if (d->isProxyWidget())
- static_cast<QGraphicsProxyWidget*>(this)->dragMoveEvent(event);
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- drop events for this item. Items can only receive drop events if the last
- drag move event was accepted.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no effect.
-
- Items do not receive drag and drop events by default; to enable this
- feature, call \c setAcceptDrops(true).
-
- The default implementation does nothing.
-
- \sa dragEnterEvent(), dragMoveEvent(), dragLeaveEvent()
-*/
-void QGraphicsItem::dropEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsItem);
- // binary compatibility workaround between 4.4 and 4.5
- if (d->isProxyWidget())
- static_cast<QGraphicsProxyWidget*>(this)->dropEvent(event);
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- focus in events for this item. The default implementation calls
- ensureVisible().
-
- \sa focusOutEvent(), sceneEvent(), setFocus()
-*/
-void QGraphicsItem::focusInEvent(QFocusEvent *event)
-{
- Q_UNUSED(event);
- update();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- focus out events for this item. The default implementation does nothing.
-
- \sa focusInEvent(), sceneEvent(), setFocus()
-*/
-void QGraphicsItem::focusOutEvent(QFocusEvent *event)
-{
- Q_UNUSED(event);
- update();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- hover enter events for this item. The default implementation calls
- update(); otherwise it does nothing.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no effect.
-
- \sa hoverMoveEvent(), hoverLeaveEvent(), sceneEvent(), setAcceptHoverEvents()
-*/
-void QGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
- update();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- hover move events for this item. The default implementation does nothing.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no effect.
-
- \sa hoverEnterEvent(), hoverLeaveEvent(), sceneEvent(), setAcceptHoverEvents()
-*/
-void QGraphicsItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- hover leave events for this item. The default implementation calls
- update(); otherwise it does nothing.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no effect.
-
- \sa hoverEnterEvent(), hoverMoveEvent(), sceneEvent(), setAcceptHoverEvents()
-*/
-void QGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
- update();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to
- receive key press events for this item. The default implementation
- ignores the event. If you reimplement this handler, the event will by
- default be accepted.
-
- Note that key events are only received for items that set the
- ItemIsFocusable flag, and that have keyboard input focus.
-
- \sa keyReleaseEvent(), setFocus(), QGraphicsScene::setFocusItem(),
- sceneEvent()
-*/
-void QGraphicsItem::keyPressEvent(QKeyEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- key release events for this item. The default implementation
- ignores the event. If you reimplement this handler, the event will by
- default be accepted.
-
- Note that key events are only received for items that set the
- ItemIsFocusable flag, and that have keyboard input focus.
-
- \sa keyPressEvent(), setFocus(), QGraphicsScene::setFocusItem(),
- sceneEvent()
-*/
-void QGraphicsItem::keyReleaseEvent(QKeyEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to
- receive mouse press events for this item. Mouse press events are
- only delivered to items that accept the mouse button that is
- pressed. By default, an item accepts all mouse buttons, but you
- can change this by calling setAcceptedMouseButtons().
-
- The mouse press event decides which item should become the mouse
- grabber (see QGraphicsScene::mouseGrabberItem()). If you do not
- reimplement this function, the press event will propagate to any
- topmost item beneath this item, and no other mouse events will be
- delivered to this item.
-
- If you do reimplement this function, \a event will by default be
- accepted (see QEvent::accept()), and this item is then the mouse
- grabber. This allows the item to receive future move, release and
- doubleclick events. If you call QEvent::ignore() on \a event, this
- item will lose the mouse grab, and \a event will propagate to any
- topmost item beneath. No further mouse events will be delivered to
- this item unless a new mouse press event is received.
-
- The default implementation handles basic item interaction, such as
- selection and moving. If you want to keep the base implementation
- when reimplementing this function, call
- QGraphicsItem::mousePressEvent() in your reimplementation.
-
- The event is \l{QEvent::ignore()}d for items that are neither
- \l{QGraphicsItem::ItemIsMovable}{movable} nor
- \l{QGraphicsItem::ItemIsSelectable}{selectable}.
-
- \sa mouseMoveEvent(), mouseReleaseEvent(),
- mouseDoubleClickEvent(), sceneEvent()
-*/
-void QGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- if (event->button() == Qt::LeftButton && (flags() & ItemIsSelectable)) {
- bool multiSelect = (event->modifiers() & Qt::ControlModifier) != 0;
- if (!multiSelect) {
- if (!d_ptr->selected) {
- if (QGraphicsScene *scene = d_ptr->scene) {
- ++scene->d_func()->selectionChanging;
- scene->clearSelection();
- --scene->d_func()->selectionChanging;
- }
- setSelected(true);
- }
- }
- } else if (!(flags() & ItemIsMovable)) {
- event->ignore();
- }
- if (d_ptr->isWidget) {
- // Qt::Popup closes when you click outside.
- QGraphicsWidget *w = static_cast<QGraphicsWidget *>(this);
- if ((w->windowFlags() & Qt::Popup) == Qt::Popup) {
- event->accept();
- if (!w->rect().contains(event->pos()))
- w->close();
- }
- }
-}
-
-/*!
- obsolete
-*/
-bool _qt_movableAncestorIsSelected(const QGraphicsItem *item)
-{
- const QGraphicsItem *parent = item->parentItem();
- return parent && (((parent->flags() & QGraphicsItem::ItemIsMovable) && parent->isSelected()) || _qt_movableAncestorIsSelected(parent));
-}
-
-bool QGraphicsItemPrivate::movableAncestorIsSelected(const QGraphicsItem *item)
-{
- const QGraphicsItem *parent = item->d_ptr->parent;
- return parent && (((parent->flags() & QGraphicsItem::ItemIsMovable) && parent->isSelected()) || _qt_movableAncestorIsSelected(parent));
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to
- receive mouse move events for this item. If you do receive this
- event, you can be certain that this item also received a mouse
- press event, and that this item is the current mouse grabber.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no
- effect.
-
- The default implementation handles basic item interaction, such as
- selection and moving. If you want to keep the base implementation
- when reimplementing this function, call
- QGraphicsItem::mouseMoveEvent() in your reimplementation.
-
- Please note that mousePressEvent() decides which graphics item it
- is that receives mouse events. See the mousePressEvent()
- description for details.
-
- \sa mousePressEvent(), mouseReleaseEvent(),
- mouseDoubleClickEvent(), sceneEvent()
-*/
-void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
-{
- if ((event->buttons() & Qt::LeftButton) && (flags() & ItemIsMovable)) {
- // Determine the list of items that need to be moved.
- QList<QGraphicsItem *> selectedItems;
- QMap<QGraphicsItem *, QPointF> initialPositions;
- if (d_ptr->scene) {
- selectedItems = d_ptr->scene->selectedItems();
- initialPositions = d_ptr->scene->d_func()->movingItemsInitialPositions;
- if (initialPositions.isEmpty()) {
- foreach (QGraphicsItem *item, selectedItems)
- initialPositions[item] = item->pos();
- initialPositions[this] = pos();
- }
- d_ptr->scene->d_func()->movingItemsInitialPositions = initialPositions;
- }
-
- // Find the active view.
- QGraphicsView *view = 0;
- if (event->widget())
- view = qobject_cast<QGraphicsView *>(event->widget()->parentWidget());
-
- // Move all selected items
- int i = 0;
- bool movedMe = false;
- while (i <= selectedItems.size()) {
- QGraphicsItem *item = 0;
- if (i < selectedItems.size())
- item = selectedItems.at(i);
- else
- item = this;
- if (item == this) {
- // Slightly clumsy-looking way to ensure that "this" is part
- // of the list of items to move, this is to avoid allocations
- // (appending this item to the list of selected items causes a
- // detach).
- if (movedMe)
- break;
- movedMe = true;
- }
-
- if ((item->flags() & ItemIsMovable) && !QGraphicsItemPrivate::movableAncestorIsSelected(item)) {
- QPointF currentParentPos;
- QPointF buttonDownParentPos;
- if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations) {
- // Items whose ancestors ignore transformations need to
- // map screen coordinates to local coordinates, then map
- // those to the parent.
- QTransform viewToItemTransform = (item->deviceTransform(view->viewportTransform())).inverted();
- currentParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->screenPos()))));
- buttonDownParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton)))));
- } else if (item->flags() & ItemIgnoresTransformations) {
- // Root items that ignore transformations need to
- // calculate their diff by mapping viewport coordinates
- // directly to parent coordinates.
- // COMBINE
- QTransform itemTransform;
- if (item->d_ptr->transformData)
- itemTransform = item->d_ptr->transformData->computedFullTransform();
- itemTransform.translate(item->d_ptr->pos.x(), item->d_ptr->pos.y());
- QTransform viewToParentTransform = itemTransform
- * (item->sceneTransform() * view->viewportTransform()).inverted();
- currentParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->screenPos())));
- buttonDownParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton))));
- } else {
- // All other items simply map from the scene.
- currentParentPos = item->mapToParent(item->mapFromScene(event->scenePos()));
- buttonDownParentPos = item->mapToParent(item->mapFromScene(event->buttonDownScenePos(Qt::LeftButton)));
- }
-
- item->setPos(initialPositions.value(item) + currentParentPos - buttonDownParentPos);
-
- if (item->flags() & ItemIsSelectable)
- item->setSelected(true);
- }
- ++i;
- }
-
- } else {
- event->ignore();
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to
- receive mouse release events for this item.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no
- effect.
-
- The default implementation handles basic item interaction, such as
- selection and moving. If you want to keep the base implementation
- when reimplementing this function, call
- QGraphicsItem::mouseReleaseEvent() in your reimplementation.
-
- Please note that mousePressEvent() decides which graphics item it
- is that receives mouse events. See the mousePressEvent()
- description for details.
-
- \sa mousePressEvent(), mouseMoveEvent(), mouseDoubleClickEvent(),
- sceneEvent()
-*/
-void QGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
-{
- if (flags() & ItemIsSelectable) {
- bool multiSelect = (event->modifiers() & Qt::ControlModifier) != 0;
- if (event->scenePos() == event->buttonDownScenePos(Qt::LeftButton)) {
- // The item didn't move
- if (multiSelect) {
- setSelected(!isSelected());
- } else {
- bool selectionChanged = false;
- if (QGraphicsScene *scene = d_ptr->scene) {
- ++scene->d_func()->selectionChanging;
- // Clear everything but this item. Bypass
- // QGraphicsScene::clearSelection()'s default behavior by
- // temporarily removing this item from the selection list.
- if (d_ptr->selected) {
- scene->d_func()->selectedItems.remove(this);
- foreach (QGraphicsItem *item, scene->d_func()->selectedItems) {
- if (item->isSelected()) {
- selectionChanged = true;
- break;
- }
- }
- }
- scene->clearSelection();
- if (d_ptr->selected)
- scene->d_func()->selectedItems.insert(this);
- --scene->d_func()->selectionChanging;
- if (selectionChanged)
- emit d_ptr->scene->selectionChanged();
- }
- setSelected(true);
- }
- }
- }
- if (d_ptr->scene && !event->buttons())
- d_ptr->scene->d_func()->movingItemsInitialPositions.clear();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to
- receive mouse doubleclick events for this item.
-
- When doubleclicking an item, the item will first receive a mouse
- press event, followed by a release event (i.e., a click), then a
- doubleclick event, and finally a release event.
-
- Calling QEvent::ignore() or QEvent::accept() on \a event has no
- effect.
-
- The default implementation calls mousePressEvent(). If you want to
- keep the base implementation when reimplementing this function,
- call QGraphicsItem::mouseDoubleClickEvent() in your
- reimplementation.
-
- Note that an item will not receive double click events if it is
- neither \l {QGraphicsItem::ItemIsSelectable}{selectable} nor
- \l{QGraphicsItem::ItemIsMovable}{movable} (single mouse clicks are
- ignored in this case, and that stops the generation of double
- clicks).
-
- \sa mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(), sceneEvent()
-*/
-void QGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
-{
- mousePressEvent(event);
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- wheel events for this item. If you reimplement this function, \a event
- will be accepted by default.
-
- If you ignore the event, (i.e., by calling QEvent::ignore(),) it will
- propagate to any item beneath this item. If no items accept the event, it
- will be ignored by the scene, and propagate to the view (e.g., the view's
- vertical scroll bar).
-
- The default implementation ignores the event.
-
- \sa sceneEvent()
-*/
-void QGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented to receive
- input method events for this item. The default implementation ignores the
- event.
-
- \sa inputMethodQuery(), sceneEvent()
-*/
-void QGraphicsItem::inputMethodEvent(QInputMethodEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This method is only relevant for input items. It is used by the
- input method to query a set of properties of the item to be able
- to support complex input method operations, such as support for
- surrounding text and reconversions. \a query specifies which
- property is queried.
-
- \sa inputMethodEvent(), QInputMethodEvent, QInputContext
-*/
-QVariant QGraphicsItem::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- if (isWidget()) {
- // ### Qt 5: Remove. The reimplementation in
- // QGraphicsProxyWidget solves this problem (but requires a
- // recompile to take effect).
- return d_ptr->inputMethodQueryHelper(query);
- }
-
- Q_UNUSED(query);
- return QVariant();
-}
-
-/*!
- Returns the current input method hints of this item.
-
- Input method hints are only relevant for input items.
- The hints are used by the input method to indicate how it should operate.
- For example, if the Qt::ImhNumbersOnly flag is set, the input method may change
- its visual components to reflect that only numbers can be entered.
-
- The effect may vary between input method implementations.
-
- \since 4.6
-
- \sa setInputMethodHints(), inputMethodQuery(), QInputContext
-*/
-Qt::InputMethodHints QGraphicsItem::inputMethodHints() const
-{
- Q_D(const QGraphicsItem);
- return d->imHints;
-}
-
-/*!
- Sets the current input method hints of this item to \a hints.
-
- \since 4.6
-
- \sa inputMethodHints(), inputMethodQuery(), QInputContext
-*/
-void QGraphicsItem::setInputMethodHints(Qt::InputMethodHints hints)
-{
- Q_D(QGraphicsItem);
- d->imHints = hints;
- if (!hasFocus())
- return;
- d->scene->d_func()->updateInputMethodSensitivityInViews();
-#if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN))
- QWidget *fw = QApplication::focusWidget();
- if (!fw)
- return;
- for (int i = 0 ; i < scene()->views().count() ; ++i)
- if (scene()->views().at(i) == fw)
- if (QInputContext *inputContext = fw->inputContext())
- inputContext->update();
-#endif
-}
-
-/*!
- Updates the item's micro focus.
-
- \since 4.7
-
- \sa QInputContext
-*/
-void QGraphicsItem::updateMicroFocus()
-{
-#if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN))
- if (QWidget *fw = QApplication::focusWidget()) {
- if (scene()) {
- for (int i = 0 ; i < scene()->views().count() ; ++i) {
- if (scene()->views().at(i) == fw)
- if (QInputContext *inputContext = fw->inputContext())
- inputContext->update();
- }
- }
-#ifndef QT_NO_ACCESSIBILITY
- // ##### is this correct
- QAccessible::updateAccessibility(fw, 0, QAccessible::StateChanged);
-#endif
- }
-#endif
-}
-
-/*!
- This virtual function is called by QGraphicsItem to notify custom items
- that some part of the item's state changes. By reimplementing this
- function, your can react to a change, and in some cases, (depending on \a
- change,) adjustments can be made.
-
- \a change is the parameter of the item that is changing. \a value is the
- new value; the type of the value depends on \a change.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 15
-
- The default implementation does nothing, and returns \a value.
-
- Note: Certain QGraphicsItem functions cannot be called in a
- reimplementation of this function; see the GraphicsItemChange
- documentation for details.
-
- \sa GraphicsItemChange
-*/
-QVariant QGraphicsItem::itemChange(GraphicsItemChange change, const QVariant &value)
-{
- Q_UNUSED(change);
- return value;
-}
-
-/*!
- \internal
-
- Note: This is provided as a hook to avoid future problems related
- to adding virtual functions.
-*/
-bool QGraphicsItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-
- Note: This is provided as a hook to avoid future problems related
- to adding virtual functions.
-*/
-void QGraphicsItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-
- Note: This is provided as a hook to avoid future problems related
- to adding virtual functions.
-*/
-QVariant QGraphicsItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \internal
-
- Adds this item to the scene's index. Called in conjunction with
- removeFromIndex() to ensure the index bookkeeping is correct when
- the item's position, transformation or shape changes.
-*/
-void QGraphicsItem::addToIndex()
-{
- if (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) {
- // ### add to child index only if applicable
- return;
- }
- if (d_ptr->scene)
- d_ptr->scene->d_func()->index->addItem(this);
-}
-
-/*!
- \internal
-
- Removes this item from the scene's index. Called in conjunction
- with addToIndex() to ensure the index bookkeeping is correct when
- the item's position, transformation or shape changes.
-*/
-void QGraphicsItem::removeFromIndex()
-{
- if (d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) {
- // ### remove from child index only if applicable
- return;
- }
- if (d_ptr->scene)
- d_ptr->scene->d_func()->index->removeItem(this);
-}
-
-/*!
- Prepares the item for a geometry change. Call this function before
- changing the bounding rect of an item to keep QGraphicsScene's index up to
- date.
-
- prepareGeometryChange() will call update() if this is necessary.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 16
-
- \sa boundingRect()
-*/
-void QGraphicsItem::prepareGeometryChange()
-{
- if (d_ptr->inDestructor)
- return;
- if (d_ptr->scene) {
- d_ptr->scene->d_func()->dirtyGrowingItemsBoundingRect = true;
- d_ptr->geometryChanged = 1;
- d_ptr->paintedViewBoundingRectsNeedRepaint = 1;
- d_ptr->notifyBoundingRectChanged = !d_ptr->inSetPosHelper;
-
- QGraphicsScenePrivate *scenePrivate = d_ptr->scene->d_func();
- scenePrivate->index->prepareBoundingRectChange(this);
- scenePrivate->markDirty(this, QRectF(), /*invalidateChildren=*/true, /*force=*/false,
- /*ignoreOpacity=*/ false, /*removingItemFromScene=*/ false,
- /*updateBoundingRect=*/true);
-
- // For compatibility reasons, we have to update the item's old geometry
- // if someone is connected to the changed signal or the scene has no views.
- // Note that this has to be done *after* markDirty to ensure that
- // _q_processDirtyItems is called before _q_emitUpdated.
- if (scenePrivate->isSignalConnected(scenePrivate->changedSignalIndex)
- || scenePrivate->views.isEmpty()) {
- if (d_ptr->hasTranslateOnlySceneTransform()) {
- d_ptr->scene->update(boundingRect().translated(d_ptr->sceneTransform.dx(),
- d_ptr->sceneTransform.dy()));
- } else {
- d_ptr->scene->update(d_ptr->sceneTransform.mapRect(boundingRect()));
- }
- }
- }
-
- d_ptr->markParentDirty(/*updateBoundingRect=*/true);
-}
-
-/*!
- \internal
-
- Highlights \a item as selected.
-
- NOTE: This function is a duplicate of qt_graphicsItem_highlightSelected() in
- qgraphicssvgitem.cpp!
-*/
-static void qt_graphicsItem_highlightSelected(
- QGraphicsItem *item, QPainter *painter, const QStyleOptionGraphicsItem *option)
-{
- const QRectF murect = painter->transform().mapRect(QRectF(0, 0, 1, 1));
- if (qFuzzyIsNull(qMax(murect.width(), murect.height())))
- return;
-
- const QRectF mbrect = painter->transform().mapRect(item->boundingRect());
- if (qMin(mbrect.width(), mbrect.height()) < qreal(1.0))
- return;
-
- qreal itemPenWidth;
- switch (item->type()) {
- case QGraphicsEllipseItem::Type:
- itemPenWidth = static_cast<QGraphicsEllipseItem *>(item)->pen().widthF();
- break;
- case QGraphicsPathItem::Type:
- itemPenWidth = static_cast<QGraphicsPathItem *>(item)->pen().widthF();
- break;
- case QGraphicsPolygonItem::Type:
- itemPenWidth = static_cast<QGraphicsPolygonItem *>(item)->pen().widthF();
- break;
- case QGraphicsRectItem::Type:
- itemPenWidth = static_cast<QGraphicsRectItem *>(item)->pen().widthF();
- break;
- case QGraphicsSimpleTextItem::Type:
- itemPenWidth = static_cast<QGraphicsSimpleTextItem *>(item)->pen().widthF();
- break;
- case QGraphicsLineItem::Type:
- itemPenWidth = static_cast<QGraphicsLineItem *>(item)->pen().widthF();
- break;
- default:
- itemPenWidth = 1.0;
- }
- const qreal pad = itemPenWidth / 2;
-
- const qreal penWidth = 0; // cosmetic pen
-
- const QColor fgcolor = option->palette.windowText().color();
- const QColor bgcolor( // ensure good contrast against fgcolor
- fgcolor.red() > 127 ? 0 : 255,
- fgcolor.green() > 127 ? 0 : 255,
- fgcolor.blue() > 127 ? 0 : 255);
-
- painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(item->boundingRect().adjusted(pad, pad, -pad, -pad));
-
- painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine));
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(item->boundingRect().adjusted(pad, pad, -pad, -pad));
-}
-
-/*!
- \class QGraphicsObject
- \brief The QGraphicsObject class provides a base class for all graphics items that
- require signals, slots and properties.
- \since 4.6
- \ingroup graphicsview-api
-
- The class extends a QGraphicsItem with QObject's signal/slot and property mechanisms.
- It maps many of QGraphicsItem's basic setters and getters to properties and adds notification
- signals for many of them.
-
- \section1 Parents and Children
-
- Each graphics object can be constructed with a parent item. This ensures that the
- item will be destroyed when its parent item is destroyed. Although QGraphicsObject
- inherits from both QObject and QGraphicsItem, you should use the functions provided
- by QGraphicsItem, \e not QObject, to manage the relationships between parent and
- child items.
-
- The relationships between items can be explored using the parentItem() and childItems()
- functions. In the hierarchy of items in a scene, the parentObject() and parentWidget()
- functions are the equivalent of the QWidget::parent() and QWidget::parentWidget()
- functions for QWidget subclasses.
-
- \sa QGraphicsWidget
-*/
-
-/*!
- Constructs a QGraphicsObject with \a parent.
-*/
-QGraphicsObject::QGraphicsObject(QGraphicsItem *parent)
- : QGraphicsItem(parent)
-{
- QGraphicsItem::d_ptr->isObject = true;
-}
-
-/*!
- \internal
-*/
-QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene)
- : QGraphicsItem(dd, parent, scene)
-{
- QGraphicsItem::d_ptr->isObject = true;
-}
-
-#ifndef QT_NO_GESTURES
-/*!
- Subscribes the graphics object to the given \a gesture with specific \a flags.
-
- \sa ungrabGesture(), QGestureEvent
-*/
-void QGraphicsObject::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
-{
- bool contains = QGraphicsItem::d_ptr->gestureContext.contains(gesture);
- QGraphicsItem::d_ptr->gestureContext.insert(gesture, flags);
- if (!contains && QGraphicsItem::d_ptr->scene)
- QGraphicsItem::d_ptr->scene->d_func()->grabGesture(this, gesture);
-}
-
-/*!
- Unsubscribes the graphics object from the given \a gesture.
-
- \sa grabGesture(), QGestureEvent
-*/
-void QGraphicsObject::ungrabGesture(Qt::GestureType gesture)
-{
- if (QGraphicsItem::d_ptr->gestureContext.remove(gesture) && QGraphicsItem::d_ptr->scene)
- QGraphicsItem::d_ptr->scene->d_func()->ungrabGesture(this, gesture);
-}
-#endif // QT_NO_GESTURES
-
-/*!
- Updates the item's micro focus. This is slot for convenience.
-
- \since 4.7
-
- \sa QInputContext
-*/
-void QGraphicsObject::updateMicroFocus()
-{
- QGraphicsItem::updateMicroFocus();
-}
-
-void QGraphicsItemPrivate::children_append(QDeclarativeListProperty<QGraphicsObject> *list, QGraphicsObject *item)
-{
- if (item) {
- QGraphicsObject *graphicsObject = static_cast<QGraphicsObject *>(list->object);
- if (QGraphicsItemPrivate::get(graphicsObject)->sendParentChangeNotification) {
- item->setParentItem(graphicsObject);
- } else {
- QGraphicsItemPrivate::get(item)->setParentItemHelper(graphicsObject, 0, 0);
- }
- }
-}
-
-int QGraphicsItemPrivate::children_count(QDeclarativeListProperty<QGraphicsObject> *list)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- return d->children.count();
-}
-
-QGraphicsObject *QGraphicsItemPrivate::children_at(QDeclarativeListProperty<QGraphicsObject> *list, int index)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- if (index >= 0 && index < d->children.count())
- return d->children.at(index)->toGraphicsObject();
- else
- return 0;
-}
-
-void QGraphicsItemPrivate::children_clear(QDeclarativeListProperty<QGraphicsObject> *list)
-{
- QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object));
- int childCount = d->children.count();
- if (d->sendParentChangeNotification) {
- for (int index = 0; index < childCount; index++)
- d->children.at(0)->setParentItem(0);
- } else {
- for (int index = 0; index < childCount; index++)
- QGraphicsItemPrivate::get(d->children.at(0))->setParentItemHelper(0, 0, 0);
- }
-}
-
-/*!
- Returns a list of this item's children.
-
- The items are sorted by stacking order. This takes into account both the
- items' insertion order and their Z-values.
-
-*/
-QDeclarativeListProperty<QGraphicsObject> QGraphicsItemPrivate::childrenList()
-{
- Q_Q(QGraphicsItem);
- if (isObject) {
- QGraphicsObject *that = static_cast<QGraphicsObject *>(q);
- return QDeclarativeListProperty<QGraphicsObject>(that, &children, children_append,
- children_count, children_at, children_clear);
- } else {
- //QGraphicsItem is not supported for this property
- return QDeclarativeListProperty<QGraphicsObject>();
- }
-}
-
-/*!
- \internal
- Returns the width of the item
- Reimplemented by QGraphicsWidget
-*/
-qreal QGraphicsItemPrivate::width() const
-{
- return 0;
-}
-
-/*!
- \internal
- Set the width of the item
- Reimplemented by QGraphicsWidget
-*/
-void QGraphicsItemPrivate::setWidth(qreal w)
-{
- Q_UNUSED(w);
-}
-
-/*!
- \internal
- Reset the width of the item
- Reimplemented by QGraphicsWidget
-*/
-void QGraphicsItemPrivate::resetWidth()
-{
-}
-
-/*!
- \internal
- Returns the height of the item
- Reimplemented by QGraphicsWidget
-*/
-qreal QGraphicsItemPrivate::height() const
-{
- return 0;
-}
-
-/*!
- \internal
- Set the height of the item
- Reimplemented by QGraphicsWidget
-*/
-void QGraphicsItemPrivate::setHeight(qreal h)
-{
- Q_UNUSED(h);
-}
-
-/*!
- \internal
- Reset the height of the item
- Reimplemented by QGraphicsWidget
-*/
-void QGraphicsItemPrivate::resetHeight()
-{
-}
-
-/*!
- \property QGraphicsObject::children
- \since 4.7
- \internal
-*/
-
-/*!
- \property QGraphicsObject::width
- \since 4.7
- \internal
-*/
-
-/*!
- \property QGraphicsObject::height
- \since 4.7
- \internal
-*/
-
-/*!
- \property QGraphicsObject::parent
- \brief the parent of the item
-
- \note The item's parent is set independently of the parent object returned
- by QObject::parent().
-
- \sa QGraphicsItem::setParentItem(), QGraphicsItem::parentObject()
-*/
-
-/*!
- \property QGraphicsObject::opacity
- \brief the opacity of the item
-
- \sa QGraphicsItem::setOpacity(), QGraphicsItem::opacity()
-*/
-
-/*!
- \fn QGraphicsObject::opacityChanged()
-
- This signal gets emitted whenever the opacity of the item changes
-
- \sa QGraphicsItem::opacity()
-*/
-
-/*!
- \fn QGraphicsObject::parentChanged()
-
- This signal gets emitted whenever the parent of the item changes
-*/
-
-/*!
- \property QGraphicsObject::pos
- \brief the position of the item
-
- Describes the items position.
-
- \sa QGraphicsItem::setPos(), QGraphicsItem::pos()
-*/
-
-/*!
- \property QGraphicsObject::x
- \brief the x position of the item
-
- Describes the items x position.
-
- \sa QGraphicsItem::setX(), setPos(), xChanged()
-*/
-
-/*!
- \fn QGraphicsObject::xChanged()
-
- This signal gets emitted whenever the x position of the item changes
-
- \sa pos()
-*/
-
-/*!
- \property QGraphicsObject::y
- \brief the y position of the item
-
- Describes the items y position.
-
- \sa QGraphicsItem::setY(), setPos(), yChanged()
-*/
-
-/*!
- \fn QGraphicsObject::yChanged()
-
- This signal gets emitted whenever the y position of the item changes.
-
- \sa pos()
-*/
-
-/*!
- \property QGraphicsObject::z
- \brief the z value of the item
-
- Describes the items z value.
-
- \sa QGraphicsItem::setZValue(), zValue(), zChanged()
-*/
-
-/*!
- \fn QGraphicsObject::zChanged()
-
- This signal gets emitted whenever the z value of the item changes.
-
- \sa pos()
-*/
-
-/*!
- \property QGraphicsObject::rotation
- This property holds the rotation of the item in degrees.
-
- This specifies how many degrees to rotate the item around its transformOrigin.
- The default rotation is 0 degrees (i.e. not rotated at all).
-*/
-
-/*!
- \fn QGraphicsObject::rotationChanged()
-
- This signal gets emitted whenever the roation of the item changes.
-*/
-
-/*!
- \property QGraphicsObject::scale
- This property holds the scale of the item.
-
- A scale of less than 1 means the item will be displayed smaller than
- normal, and a scale of greater than 1 means the item will be
- displayed larger than normal. A negative scale means the item will
- be mirrored.
-
- By default, items are displayed at a scale of 1 (i.e. at their
- normal size).
-
- Scaling is from the item's transformOrigin.
-*/
-
-/*!
- \fn void QGraphicsObject::scaleChanged()
-
- This signal is emitted when the scale of the item changes.
-*/
-
-
-/*!
- \property QGraphicsObject::enabled
- \brief whether the item is enabled or not
-
- This property is declared in QGraphicsItem.
-
- By default, this property is true.
-
- \sa QGraphicsItem::isEnabled(), QGraphicsItem::setEnabled()
- \sa QGraphicsObject::enabledChanged()
-*/
-
-/*!
- \fn void QGraphicsObject::enabledChanged()
-
- This signal gets emitted whenever the item get's enabled or disabled.
-
- \sa isEnabled()
-*/
-
-/*!
- \property QGraphicsObject::visible
- \brief whether the item is visible or not
-
- This property is declared in QGraphicsItem.
-
- By default, this property is true.
-
- \sa QGraphicsItem::isVisible(), QGraphicsItem::setVisible(), visibleChanged()
-*/
-
-/*!
- \fn QGraphicsObject::visibleChanged()
-
- This signal gets emitted whenever the visibility of the item changes
-
- \sa visible
-*/
-
-/*!
- \fn const QObjectList &QGraphicsObject::children() const
- \internal
-
- This function returns the same value as QObject::children(). It's
- provided to differentiate between the obsolete member
- QGraphicsItem::children() and QObject::children(). QGraphicsItem now
- provides childItems() instead.
-*/
-
-/*!
- \property QGraphicsObject::transformOriginPoint
- \brief the transformation origin
-
- This property sets a specific point in the items coordiante system as the
- origin for scale and rotation.
-
- \sa scale, rotation, QGraphicsItem::transformOriginPoint()
-*/
-
-/*!
- \fn void QGraphicsObject::widthChanged()
- \internal
-*/
-
-/*!
- \fn void QGraphicsObject::heightChanged()
- \internal
-*/
-
-/*!
-
- \fn QGraphicsObject::childrenChanged()
-
- This signal gets emitted whenever the children list changes
- \internal
-*/
-
-/*!
- \property QGraphicsObject::effect
- \since 4.7
- \brief the effect attached to this item
-
- \sa QGraphicsItem::setGraphicsEffect(), QGraphicsItem::graphicsEffect()
-*/
-
-/*!
- \class QAbstractGraphicsShapeItem
- \brief The QAbstractGraphicsShapeItem class provides a common base for
- all path items.
- \since 4.2
- \ingroup graphicsview-api
-
- This class does not fully implement an item by itself; in particular, it
- does not implement boundingRect() and paint(), which are inherited by
- QGraphicsItem.
-
- You can subclass this item to provide a simple base implementation of
- accessors for the item's pen and brush.
-
- \sa QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsPathItem,
- QGraphicsPolygonItem, QGraphicsTextItem, QGraphicsLineItem,
- QGraphicsPixmapItem, {Graphics View Framework}
-*/
-
-class QAbstractGraphicsShapeItemPrivate : public QGraphicsItemPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractGraphicsShapeItem)
-public:
-
- QBrush brush;
- QPen pen;
-
- // Cached bounding rectangle
- mutable QRectF boundingRect;
-};
-
-/*!
- Constructs a QAbstractGraphicsShapeItem. \a parent is passed to
- QGraphicsItem's constructor.
-*/
-QAbstractGraphicsShapeItem::QAbstractGraphicsShapeItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QAbstractGraphicsShapeItemPrivate, parent, scene)
-{
-}
-
-/*!
- \internal
-*/
-QAbstractGraphicsShapeItem::QAbstractGraphicsShapeItem(QAbstractGraphicsShapeItemPrivate &dd,
- QGraphicsItem *parent,
- QGraphicsScene *scene)
- : QGraphicsItem(dd, parent, scene)
-{
-}
-
-/*!
- Destroys a QAbstractGraphicsShapeItem.
-*/
-QAbstractGraphicsShapeItem::~QAbstractGraphicsShapeItem()
-{
-}
-
-/*!
- Returns the item's pen. If no pen has been set, this function returns
- QPen(), a default black solid line pen with 0 width.
-*/
-QPen QAbstractGraphicsShapeItem::pen() const
-{
- Q_D(const QAbstractGraphicsShapeItem);
- return d->pen;
-}
-
-/*!
- Sets the pen for this item to \a pen.
-
- The pen is used to draw the item's outline.
-
- \sa pen()
-*/
-void QAbstractGraphicsShapeItem::setPen(const QPen &pen)
-{
- Q_D(QAbstractGraphicsShapeItem);
- if (d->pen == pen)
- return;
- prepareGeometryChange();
- d->pen = pen;
- d->boundingRect = QRectF();
- update();
-}
-
-/*!
- Returns the item's brush, or an empty brush if no brush has been set.
-
- \sa setBrush()
-*/
-QBrush QAbstractGraphicsShapeItem::brush() const
-{
- Q_D(const QAbstractGraphicsShapeItem);
- return d->brush;
-}
-
-/*!
- Sets the item's brush to \a brush.
-
- The item's brush is used to fill the item.
-
- If you use a brush with a QGradient, the gradient
- is relative to the item's coordinate system.
-
- \sa brush()
-*/
-void QAbstractGraphicsShapeItem::setBrush(const QBrush &brush)
-{
- Q_D(QAbstractGraphicsShapeItem);
- if (d->brush == brush)
- return;
- d->brush = brush;
- update();
-}
-
-/*!
- \reimp
-*/
-bool QAbstractGraphicsShapeItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QGraphicsItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QAbstractGraphicsShapeItem::opaqueArea() const
-{
- Q_D(const QAbstractGraphicsShapeItem);
- if (d->brush.isOpaque())
- return isClipped() ? clipPath() : shape();
- return QGraphicsItem::opaqueArea();
-}
-
-/*!
- \class QGraphicsPathItem
- \brief The QGraphicsPathItem class provides a path item that you
- can add to a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- To set the item's path, pass a QPainterPath to QGraphicsPathItem's
- constructor, or call the setPath() function. The path() function
- returns the current path.
-
- \image graphicsview-pathitem.png
-
- QGraphicsPathItem uses the path to provide a reasonable
- implementation of boundingRect(), shape(), and contains(). The
- paint() function draws the path using the item's associated pen
- and brush, which you can set by calling the setPen() and
- setBrush() functions.
-
- \sa QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsPolygonItem,
- QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics
- View Framework}
-*/
-
-class QGraphicsPathItemPrivate : public QAbstractGraphicsShapeItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsPathItem)
-public:
- QPainterPath path;
-};
-
-/*!
- Constructs a QGraphicsPath item using \a path as the default path. \a
- parent is passed to QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsPathItem::QGraphicsPathItem(const QPainterPath &path,
- QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsPathItemPrivate, parent, scene)
-{
- if (!path.isEmpty())
- setPath(path);
-}
-
-/*!
- Constructs a QGraphicsPath. \a parent is passed to
- QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsPathItem::QGraphicsPathItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsPathItemPrivate, parent, scene)
-{
-}
-
-/*!
- Destroys the QGraphicsPathItem.
-*/
-QGraphicsPathItem::~QGraphicsPathItem()
-{
-}
-
-/*!
- Returns the item's path as a QPainterPath. If no item has been set, an
- empty QPainterPath is returned.
-
- \sa setPath()
-*/
-QPainterPath QGraphicsPathItem::path() const
-{
- Q_D(const QGraphicsPathItem);
- return d->path;
-}
-
-/*!
- Sets the item's path to be the given \a path.
-
- \sa path()
-*/
-void QGraphicsPathItem::setPath(const QPainterPath &path)
-{
- Q_D(QGraphicsPathItem);
- if (d->path == path)
- return;
- prepareGeometryChange();
- d->path = path;
- d->boundingRect = QRectF();
- update();
-}
-
-/*!
- \reimp
-*/
-QRectF QGraphicsPathItem::boundingRect() const
-{
- Q_D(const QGraphicsPathItem);
- if (d->boundingRect.isNull()) {
- qreal pw = pen().widthF();
- if (pw == 0.0)
- d->boundingRect = d->path.controlPointRect();
- else {
- d->boundingRect = shape().controlPointRect();
- }
- }
- return d->boundingRect;
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsPathItem::shape() const
-{
- Q_D(const QGraphicsPathItem);
- return qt_graphicsItem_shapeFromPath(d->path, d->pen);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsPathItem::contains(const QPointF &point) const
-{
- return QAbstractGraphicsShapeItem::contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsPathItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- Q_D(QGraphicsPathItem);
- Q_UNUSED(widget);
- painter->setPen(d->pen);
- painter->setBrush(d->brush);
- painter->drawPath(d->path);
-
- if (option->state & QStyle::State_Selected)
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsPathItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QAbstractGraphicsShapeItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsPathItem::opaqueArea() const
-{
- return QAbstractGraphicsShapeItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsPathItem::type() const
-{
- return Type;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsPathItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsPathItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsPathItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsRectItem
- \brief The QGraphicsRectItem class provides a rectangle item that you
- can add to a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- To set the item's rectangle, pass a QRectF to QGraphicsRectItem's
- constructor, or call the setRect() function. The rect() function
- returns the current rectangle.
-
- \image graphicsview-rectitem.png
-
- QGraphicsRectItem uses the rectangle and the pen width to provide
- a reasonable implementation of boundingRect(), shape(), and
- contains(). The paint() function draws the rectangle using the
- item's associated pen and brush, which you can set by calling the
- setPen() and setBrush() functions.
-
- \note The rendering of invalid rectangles, such as those with negative
- widths or heights, is undefined. If you cannot be sure that you are
- using valid rectangles (for example, if you are creating
- rectangles using data from an unreliable source) then you should
- use QRectF::normalized() to create normalized rectangles, and use
- those instead.
-
- \sa QGraphicsPathItem, QGraphicsEllipseItem, QGraphicsPolygonItem,
- QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics
- View Framework}
-*/
-
-class QGraphicsRectItemPrivate : public QAbstractGraphicsShapeItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsRectItem)
-public:
- QRectF rect;
-};
-
-/*!
- Constructs a QGraphicsRectItem, using \a rect as the default rectangle.
- \a parent is passed to QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsRectItem::QGraphicsRectItem(const QRectF &rect, QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsRectItemPrivate, parent, scene)
-{
- setRect(rect);
-}
-
-/*!
- \fn QGraphicsRectItem::QGraphicsRectItem(qreal x, qreal y, qreal width, qreal height,
- QGraphicsItem *parent)
-
- Constructs a QGraphicsRectItem with a default rectangle defined
- by (\a x, \a y) and the given \a width and \a height.
-
- \a parent is passed to QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsRectItem::QGraphicsRectItem(qreal x, qreal y, qreal w, qreal h,
- QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsRectItemPrivate, parent, scene)
-{
- setRect(QRectF(x, y, w, h));
-}
-
-/*!
- Constructs a QGraphicsRectItem. \a parent is passed to
- QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsRectItem::QGraphicsRectItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsRectItemPrivate, parent, scene)
-{
-}
-
-/*!
- Destroys the QGraphicsRectItem.
-*/
-QGraphicsRectItem::~QGraphicsRectItem()
-{
-}
-
-/*!
- Returns the item's rectangle.
-
- \sa setRect()
-*/
-QRectF QGraphicsRectItem::rect() const
-{
- Q_D(const QGraphicsRectItem);
- return d->rect;
-}
-
-/*!
- \fn void QGraphicsRectItem::setRect(const QRectF &rectangle)
-
- Sets the item's rectangle to be the given \a rectangle.
-
- \sa rect()
-*/
-void QGraphicsRectItem::setRect(const QRectF &rect)
-{
- Q_D(QGraphicsRectItem);
- if (d->rect == rect)
- return;
- prepareGeometryChange();
- d->rect = rect;
- d->boundingRect = QRectF();
- update();
-}
-
-/*!
- \fn void QGraphicsRectItem::setRect(qreal x, qreal y, qreal width, qreal height)
- \fn void QGraphicsEllipseItem::setRect(qreal x, qreal y, qreal width, qreal height)
-
- Sets the item's rectangle to the rectangle defined by (\a x, \a y)
- and the given \a width and \a height.
-
- This convenience function is equivalent to calling \c
- {setRect(QRectF(x, y, width, height))}
-
- \sa rect()
-*/
-
-/*!
- \reimp
-*/
-QRectF QGraphicsRectItem::boundingRect() const
-{
- Q_D(const QGraphicsRectItem);
- if (d->boundingRect.isNull()) {
- qreal halfpw = pen().widthF() / 2;
- d->boundingRect = d->rect;
- if (halfpw > 0.0)
- d->boundingRect.adjust(-halfpw, -halfpw, halfpw, halfpw);
- }
- return d->boundingRect;
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsRectItem::shape() const
-{
- Q_D(const QGraphicsRectItem);
- QPainterPath path;
- path.addRect(d->rect);
- return qt_graphicsItem_shapeFromPath(path, d->pen);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsRectItem::contains(const QPointF &point) const
-{
- return QAbstractGraphicsShapeItem::contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- Q_D(QGraphicsRectItem);
- Q_UNUSED(widget);
- painter->setPen(d->pen);
- painter->setBrush(d->brush);
- painter->drawRect(d->rect);
-
- if (option->state & QStyle::State_Selected)
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsRectItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QAbstractGraphicsShapeItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsRectItem::opaqueArea() const
-{
- return QAbstractGraphicsShapeItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsRectItem::type() const
-{
- return Type;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsRectItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsRectItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsRectItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsEllipseItem
- \brief The QGraphicsEllipseItem class provides an ellipse item that you
- can add to a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- QGraphicsEllipseItem respresents an ellipse with a fill and an outline,
- and you can also use it for ellipse segments (see startAngle(),
- spanAngle()).
-
- \table
- \row
- \o \inlineimage graphicsview-ellipseitem.png
- \o \inlineimage graphicsview-ellipseitem-pie.png
- \endtable
-
- To set the item's ellipse, pass a QRectF to QGraphicsEllipseItem's
- constructor, or call setRect(). The rect() function returns the
- current ellipse geometry.
-
- QGraphicsEllipseItem uses the rect and the pen width to provide a
- reasonable implementation of boundingRect(), shape(), and contains(). The
- paint() function draws the ellipse using the item's associated pen and
- brush, which you can set by calling setPen() and setBrush().
-
- \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsPolygonItem,
- QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics
- View Framework}
-*/
-
-class QGraphicsEllipseItemPrivate : public QAbstractGraphicsShapeItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsEllipseItem)
-public:
- inline QGraphicsEllipseItemPrivate()
- : startAngle(0), spanAngle(360 * 16)
- { }
-
- QRectF rect;
- int startAngle;
- int spanAngle;
-};
-
-/*!
- Constructs a QGraphicsEllipseItem using \a rect as the default rectangle.
- \a parent is passed to QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsEllipseItem::QGraphicsEllipseItem(const QRectF &rect, QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsEllipseItemPrivate, parent, scene)
-{
- setRect(rect);
-}
-
-/*!
- \fn QGraphicsEllipseItem::QGraphicsEllipseItem(qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent)
- \since 4.3
-
- Constructs a QGraphicsEllipseItem using the rectangle defined by (\a x, \a
- y) and the given \a width and \a height, as the default rectangle. \a
- parent is passed to QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsEllipseItem::QGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h,
- QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsEllipseItemPrivate, parent, scene)
-{
- setRect(x,y,w,h);
-}
-
-
-
-/*!
- Constructs a QGraphicsEllipseItem. \a parent is passed to
- QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsEllipseItem::QGraphicsEllipseItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsEllipseItemPrivate, parent, scene)
-{
-}
-
-/*!
- Destroys the QGraphicsEllipseItem.
-*/
-QGraphicsEllipseItem::~QGraphicsEllipseItem()
-{
-}
-
-/*!
- Returns the item's ellipse geometry as a QRectF.
-
- \sa setRect(), QPainter::drawEllipse()
-*/
-QRectF QGraphicsEllipseItem::rect() const
-{
- Q_D(const QGraphicsEllipseItem);
- return d->rect;
-}
-
-/*!
- Sets the item's ellipse geometry to \a rect. The rectangle's left edge
- defines the left edge of the ellipse, and the rectangle's top edge
- describes the top of the ellipse. The height and width of the rectangle
- describe the height and width of the ellipse.
-
- \sa rect(), QPainter::drawEllipse()
-*/
-void QGraphicsEllipseItem::setRect(const QRectF &rect)
-{
- Q_D(QGraphicsEllipseItem);
- if (d->rect == rect)
- return;
- prepareGeometryChange();
- d->rect = rect;
- d->boundingRect = QRectF();
- update();
-}
-
-/*!
- Returns the start angle for an ellipse segment in 16ths of a degree. This
- angle is used together with spanAngle() for representing an ellipse
- segment (a pie). By default, the start angle is 0.
-
- \sa setStartAngle(), spanAngle()
-*/
-int QGraphicsEllipseItem::startAngle() const
-{
- Q_D(const QGraphicsEllipseItem);
- return d->startAngle;
-}
-
-/*!
- Sets the start angle for an ellipse segment to \a angle, which is in 16ths
- of a degree. This angle is used together with spanAngle() for representing
- an ellipse segment (a pie). By default, the start angle is 0.
-
- \sa startAngle(), setSpanAngle(), QPainter::drawPie()
-*/
-void QGraphicsEllipseItem::setStartAngle(int angle)
-{
- Q_D(QGraphicsEllipseItem);
- if (angle != d->startAngle) {
- prepareGeometryChange();
- d->boundingRect = QRectF();
- d->startAngle = angle;
- update();
- }
-}
-
-/*!
- Returns the span angle of an ellipse segment in 16ths of a degree. This
- angle is used together with startAngle() for representing an ellipse
- segment (a pie). By default, this function returns 5760 (360 * 16, a full
- ellipse).
-
- \sa setSpanAngle(), startAngle()
-*/
-int QGraphicsEllipseItem::spanAngle() const
-{
- Q_D(const QGraphicsEllipseItem);
- return d->spanAngle;
-}
-
-/*!
- Sets the span angle for an ellipse segment to \a angle, which is in 16ths
- of a degree. This angle is used together with startAngle() to represent an
- ellipse segment (a pie). By default, the span angle is 5760 (360 * 16, a
- full ellipse).
-
- \sa spanAngle(), setStartAngle(), QPainter::drawPie()
-*/
-void QGraphicsEllipseItem::setSpanAngle(int angle)
-{
- Q_D(QGraphicsEllipseItem);
- if (angle != d->spanAngle) {
- prepareGeometryChange();
- d->boundingRect = QRectF();
- d->spanAngle = angle;
- update();
- }
-}
-
-/*!
- \reimp
-*/
-QRectF QGraphicsEllipseItem::boundingRect() const
-{
- Q_D(const QGraphicsEllipseItem);
- if (d->boundingRect.isNull()) {
- qreal pw = pen().widthF();
- if (pw == 0.0 && d->spanAngle == 360 * 16)
- d->boundingRect = d->rect;
- else
- d->boundingRect = shape().controlPointRect();
- }
- return d->boundingRect;
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsEllipseItem::shape() const
-{
- Q_D(const QGraphicsEllipseItem);
- QPainterPath path;
- if (d->rect.isNull())
- return path;
- if (d->spanAngle != 360 * 16) {
- path.moveTo(d->rect.center());
- path.arcTo(d->rect, d->startAngle / 16.0, d->spanAngle / 16.0);
- } else {
- path.addEllipse(d->rect);
- }
-
- return qt_graphicsItem_shapeFromPath(path, d->pen);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsEllipseItem::contains(const QPointF &point) const
-{
- return QAbstractGraphicsShapeItem::contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsEllipseItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- Q_D(QGraphicsEllipseItem);
- Q_UNUSED(widget);
- painter->setPen(d->pen);
- painter->setBrush(d->brush);
- if ((d->spanAngle != 0) && (qAbs(d->spanAngle) % (360 * 16) == 0))
- painter->drawEllipse(d->rect);
- else
- painter->drawPie(d->rect, d->startAngle, d->spanAngle);
-
- if (option->state & QStyle::State_Selected)
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsEllipseItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QAbstractGraphicsShapeItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsEllipseItem::opaqueArea() const
-{
- return QAbstractGraphicsShapeItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsEllipseItem::type() const
-{
- return Type;
-}
-
-
-/*!
- \internal
-*/
-bool QGraphicsEllipseItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsEllipseItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsEllipseItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsPolygonItem
- \brief The QGraphicsPolygonItem class provides a polygon item that you
- can add to a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- To set the item's polygon, pass a QPolygonF to
- QGraphicsPolygonItem's constructor, or call the setPolygon()
- function. The polygon() function returns the current polygon.
-
- \image graphicsview-polygonitem.png
-
- QGraphicsPolygonItem uses the polygon and the pen width to provide
- a reasonable implementation of boundingRect(), shape(), and
- contains(). The paint() function draws the polygon using the
- item's associated pen and brush, which you can set by calling the
- setPen() and setBrush() functions.
-
- \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem,
- QGraphicsTextItem, QGraphicsLineItem, QGraphicsPixmapItem, {Graphics
- View Framework}
-*/
-
-class QGraphicsPolygonItemPrivate : public QAbstractGraphicsShapeItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsPolygonItem)
-public:
- inline QGraphicsPolygonItemPrivate()
- : fillRule(Qt::OddEvenFill)
- { }
-
- QPolygonF polygon;
- Qt::FillRule fillRule;
-};
-
-/*!
- Constructs a QGraphicsPolygonItem with \a polygon as the default
- polygon. \a parent is passed to QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsPolygonItem::QGraphicsPolygonItem(const QPolygonF &polygon,
- QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsPolygonItemPrivate, parent, scene)
-{
- setPolygon(polygon);
-}
-
-/*!
- Constructs a QGraphicsPolygonItem. \a parent is passed to
- QAbstractGraphicsShapeItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsPolygonItem::QGraphicsPolygonItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsPolygonItemPrivate, parent, scene)
-{
-}
-
-/*!
- Destroys the QGraphicsPolygonItem.
-*/
-QGraphicsPolygonItem::~QGraphicsPolygonItem()
-{
-}
-
-/*!
- Returns the item's polygon, or an empty polygon if no polygon
- has been set.
-
- \sa setPolygon()
-*/
-QPolygonF QGraphicsPolygonItem::polygon() const
-{
- Q_D(const QGraphicsPolygonItem);
- return d->polygon;
-}
-
-/*!
- Sets the item's polygon to be the given \a polygon.
-
- \sa polygon()
-*/
-void QGraphicsPolygonItem::setPolygon(const QPolygonF &polygon)
-{
- Q_D(QGraphicsPolygonItem);
- if (d->polygon == polygon)
- return;
- prepareGeometryChange();
- d->polygon = polygon;
- d->boundingRect = QRectF();
- update();
-}
-
-/*!
- Returns the fill rule of the polygon. The default fill rule is
- Qt::OddEvenFill.
-
- \sa setFillRule(), QPainterPath::fillRule(), QPainter::drawPolygon()
-*/
-Qt::FillRule QGraphicsPolygonItem::fillRule() const
-{
- Q_D(const QGraphicsPolygonItem);
- return d->fillRule;
-}
-
-/*!
- Sets the fill rule of the polygon to \a rule. The default fill rule is
- Qt::OddEvenFill.
-
- \sa fillRule(), QPainterPath::fillRule(), QPainter::drawPolygon()
-*/
-void QGraphicsPolygonItem::setFillRule(Qt::FillRule rule)
-{
- Q_D(QGraphicsPolygonItem);
- if (rule != d->fillRule) {
- d->fillRule = rule;
- update();
- }
-}
-
-/*!
- \reimp
-*/
-QRectF QGraphicsPolygonItem::boundingRect() const
-{
- Q_D(const QGraphicsPolygonItem);
- if (d->boundingRect.isNull()) {
- qreal pw = pen().widthF();
- if (pw == 0.0)
- d->boundingRect = d->polygon.boundingRect();
- else
- d->boundingRect = shape().controlPointRect();
- }
- return d->boundingRect;
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsPolygonItem::shape() const
-{
- Q_D(const QGraphicsPolygonItem);
- QPainterPath path;
- path.addPolygon(d->polygon);
- return qt_graphicsItem_shapeFromPath(path, d->pen);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsPolygonItem::contains(const QPointF &point) const
-{
- return QAbstractGraphicsShapeItem::contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsPolygonItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- Q_D(QGraphicsPolygonItem);
- Q_UNUSED(widget);
- painter->setPen(d->pen);
- painter->setBrush(d->brush);
- painter->drawPolygon(d->polygon, d->fillRule);
-
- if (option->state & QStyle::State_Selected)
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsPolygonItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QAbstractGraphicsShapeItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsPolygonItem::opaqueArea() const
-{
- return QAbstractGraphicsShapeItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsPolygonItem::type() const
-{
- return Type;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsPolygonItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsPolygonItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsPolygonItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsLineItem
- \brief The QGraphicsLineItem class provides a line item that you can add to a
- QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- To set the item's line, pass a QLineF to QGraphicsLineItem's
- constructor, or call the setLine() function. The line() function
- returns the current line. By default the line is black with a
- width of 0, but you can change this by calling setPen().
-
- \img graphicsview-lineitem.png
-
- QGraphicsLineItem uses the line and the pen width to provide a reasonable
- implementation of boundingRect(), shape(), and contains(). The paint()
- function draws the line using the item's associated pen.
-
- \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem,
- QGraphicsTextItem, QGraphicsPolygonItem, QGraphicsPixmapItem,
- {Graphics View Framework}
-*/
-
-class QGraphicsLineItemPrivate : public QGraphicsItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsLineItem)
-public:
- QLineF line;
- QPen pen;
-};
-
-/*!
- Constructs a QGraphicsLineItem, using \a line as the default line. \a
- parent is passed to QGraphicsItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsLineItem::QGraphicsLineItem(const QLineF &line, QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QGraphicsLineItemPrivate, parent, scene)
-{
- setLine(line);
-}
-
-/*!
- Constructs a QGraphicsLineItem, using the line between (\a x1, \a y1) and
- (\a x2, \a y2) as the default line. \a parent is passed to
- QGraphicsItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsLineItem::QGraphicsLineItem(qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QGraphicsLineItemPrivate, parent, scene)
-{
- setLine(x1, y1, x2, y2);
-}
-
-
-
-/*!
- Constructs a QGraphicsLineItem. \a parent is passed to QGraphicsItem's
- constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsLineItem::QGraphicsLineItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QGraphicsLineItemPrivate, parent, scene)
-{
-}
-
-/*!
- Destroys the QGraphicsLineItem.
-*/
-QGraphicsLineItem::~QGraphicsLineItem()
-{
-}
-
-/*!
- Returns the item's pen, or a black solid 0-width pen if no pen has
- been set.
-
- \sa setPen()
-*/
-QPen QGraphicsLineItem::pen() const
-{
- Q_D(const QGraphicsLineItem);
- return d->pen;
-}
-
-/*!
- Sets the item's pen to \a pen. If no pen is set, the line will be painted
- using a black solid 0-width pen.
-
- \sa pen()
-*/
-void QGraphicsLineItem::setPen(const QPen &pen)
-{
- Q_D(QGraphicsLineItem);
- if (d->pen == pen)
- return;
- prepareGeometryChange();
- d->pen = pen;
- update();
-}
-
-/*!
- Returns the item's line, or a null line if no line has been set.
-
- \sa setLine()
-*/
-QLineF QGraphicsLineItem::line() const
-{
- Q_D(const QGraphicsLineItem);
- return d->line;
-}
-
-/*!
- Sets the item's line to be the given \a line.
-
- \sa line()
-*/
-void QGraphicsLineItem::setLine(const QLineF &line)
-{
- Q_D(QGraphicsLineItem);
- if (d->line == line)
- return;
- prepareGeometryChange();
- d->line = line;
- update();
-}
-
-/*!
- \fn void QGraphicsLineItem::setLine(qreal x1, qreal y1, qreal x2, qreal y2)
- \overload
-
- Sets the item's line to be the line between (\a x1, \a y1) and (\a
- x2, \a y2).
-
- This is the same as calling \c {setLine(QLineF(x1, y1, x2, y2))}.
-*/
-
-/*!
- \reimp
-*/
-QRectF QGraphicsLineItem::boundingRect() const
-{
- Q_D(const QGraphicsLineItem);
- if (d->pen.widthF() == 0.0) {
- const qreal x1 = d->line.p1().x();
- const qreal x2 = d->line.p2().x();
- const qreal y1 = d->line.p1().y();
- const qreal y2 = d->line.p2().y();
- qreal lx = qMin(x1, x2);
- qreal rx = qMax(x1, x2);
- qreal ty = qMin(y1, y2);
- qreal by = qMax(y1, y2);
- return QRectF(lx, ty, rx - lx, by - ty);
- }
- return shape().controlPointRect();
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsLineItem::shape() const
-{
- Q_D(const QGraphicsLineItem);
- QPainterPath path;
- if (d->line == QLineF())
- return path;
-
- path.moveTo(d->line.p1());
- path.lineTo(d->line.p2());
- return qt_graphicsItem_shapeFromPath(path, d->pen);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsLineItem::contains(const QPointF &point) const
-{
- return QGraphicsItem::contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsLineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- Q_D(QGraphicsLineItem);
- Q_UNUSED(widget);
- painter->setPen(d->pen);
- painter->drawLine(d->line);
-
- if (option->state & QStyle::State_Selected)
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsLineItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QGraphicsItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsLineItem::opaqueArea() const
-{
- return QGraphicsItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsLineItem::type() const
-{
- return Type;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsLineItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsLineItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsLineItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsPixmapItem
- \brief The QGraphicsPixmapItem class provides a pixmap item that you can add to
- a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- To set the item's pixmap, pass a QPixmap to QGraphicsPixmapItem's
- constructor, or call the setPixmap() function. The pixmap()
- function returns the current pixmap.
-
- QGraphicsPixmapItem uses pixmap's optional alpha mask to provide a
- reasonable implementation of boundingRect(), shape(), and contains().
-
- \image graphicsview-pixmapitem.png
-
- The pixmap is drawn at the item's (0, 0) coordinate, as returned by
- offset(). You can change the drawing offset by calling setOffset().
-
- You can set the pixmap's transformation mode by calling
- setTransformationMode(). By default, Qt::FastTransformation is used, which
- provides fast, non-smooth scaling. Qt::SmoothTransformation enables
- QPainter::SmoothPixmapTransform on the painter, and the quality depends on
- the platform and viewport. The result is usually not as good as calling
- QPixmap::scale() directly. Call transformationMode() to get the current
- transformation mode for the item.
-
- \sa QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem,
- QGraphicsTextItem, QGraphicsPolygonItem, QGraphicsLineItem,
- {Graphics View Framework}
-*/
-
-/*!
- \enum QGraphicsPixmapItem::ShapeMode
-
- This enum describes how QGraphicsPixmapItem calculates its shape and
- opaque area.
-
- The default value is MaskShape.
-
- \value MaskShape The shape is determined by calling QPixmap::mask().
- This shape includes only the opaque pixels of the pixmap.
- Because the shape is more complex, however, it can be slower than the other modes,
- and uses more memory.
-
- \value BoundingRectShape The shape is determined by tracing the outline of
- the pixmap. This is the fastest shape mode, but it does not take into account
- any transparent areas on the pixmap.
-
- \value HeuristicMaskShape The shape is determine by calling
- QPixmap::createHeuristicMask(). The performance and memory consumption
- is similar to MaskShape.
-*/
-extern QPainterPath qt_regionToPath(const QRegion &region);
-
-class QGraphicsPixmapItemPrivate : public QGraphicsItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsPixmapItem)
-public:
- QGraphicsPixmapItemPrivate()
- : transformationMode(Qt::FastTransformation),
- shapeMode(QGraphicsPixmapItem::MaskShape),
- hasShape(false)
- {}
-
- QPixmap pixmap;
- Qt::TransformationMode transformationMode;
- QPointF offset;
- QGraphicsPixmapItem::ShapeMode shapeMode;
- QPainterPath shape;
- bool hasShape;
-
- void updateShape()
- {
- shape = QPainterPath();
- switch (shapeMode) {
- case QGraphicsPixmapItem::MaskShape: {
- QBitmap mask = pixmap.mask();
- if (!mask.isNull()) {
- shape = qt_regionToPath(QRegion(mask).translated(offset.toPoint()));
- break;
- }
- // FALL THROUGH
- }
- case QGraphicsPixmapItem::BoundingRectShape:
- shape.addRect(QRectF(offset.x(), offset.y(), pixmap.width(), pixmap.height()));
- break;
- case QGraphicsPixmapItem::HeuristicMaskShape:
-#ifndef QT_NO_IMAGE_HEURISTIC_MASK
- shape = qt_regionToPath(QRegion(pixmap.createHeuristicMask()).translated(offset.toPoint()));
-#else
- shape.addRect(QRectF(offset.x(), offset.y(), pixmap.width(), pixmap.height()));
-#endif
- break;
- }
- }
-};
-
-/*!
- Constructs a QGraphicsPixmapItem, using \a pixmap as the default pixmap.
- \a parent is passed to QGraphicsItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsPixmapItem::QGraphicsPixmapItem(const QPixmap &pixmap,
- QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QGraphicsPixmapItemPrivate, parent, scene)
-{
- setPixmap(pixmap);
-}
-
-/*!
- Constructs a QGraphicsPixmapItem. \a parent is passed to QGraphicsItem's
- constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsPixmapItem::QGraphicsPixmapItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QGraphicsPixmapItemPrivate, parent, scene)
-{
-}
-
-/*!
- Destroys the QGraphicsPixmapItem.
-*/
-QGraphicsPixmapItem::~QGraphicsPixmapItem()
-{
-}
-
-/*!
- Sets the item's pixmap to \a pixmap.
-
- \sa pixmap()
-*/
-void QGraphicsPixmapItem::setPixmap(const QPixmap &pixmap)
-{
- Q_D(QGraphicsPixmapItem);
- prepareGeometryChange();
- d->pixmap = pixmap;
- d->hasShape = false;
- update();
-}
-
-/*!
- Returns the item's pixmap, or an invalid QPixmap if no pixmap has been
- set.
-
- \sa setPixmap()
-*/
-QPixmap QGraphicsPixmapItem::pixmap() const
-{
- Q_D(const QGraphicsPixmapItem);
- return d->pixmap;
-}
-
-/*!
- Returns the transformation mode of the pixmap. The default mode is
- Qt::FastTransformation, which provides quick transformation with no
- smoothing.
-
- \sa setTransformationMode()
-*/
-Qt::TransformationMode QGraphicsPixmapItem::transformationMode() const
-{
- Q_D(const QGraphicsPixmapItem);
- return d->transformationMode;
-}
-
-/*!
- Sets the pixmap item's transformation mode to \a mode, and toggles an
- update of the item. The default mode is Qt::FastTransformation, which
- provides quick transformation with no smoothing.
-
- Qt::SmoothTransformation enables QPainter::SmoothPixmapTransform on the
- painter, and the quality depends on the platform and viewport. The result
- is usually not as good as calling QPixmap::scale() directly.
-
- \sa transformationMode()
-*/
-void QGraphicsPixmapItem::setTransformationMode(Qt::TransformationMode mode)
-{
- Q_D(QGraphicsPixmapItem);
- if (mode != d->transformationMode) {
- d->transformationMode = mode;
- update();
- }
-}
-
-/*!
- Returns the pixmap item's \e offset, which defines the point of the
- top-left corner of the pixmap, in local coordinates.
-
- \sa setOffset()
-*/
-QPointF QGraphicsPixmapItem::offset() const
-{
- Q_D(const QGraphicsPixmapItem);
- return d->offset;
-}
-
-/*!
- Sets the pixmap item's offset to \a offset. QGraphicsPixmapItem will draw
- its pixmap using \a offset for its top-left corner.
-
- \sa offset()
-*/
-void QGraphicsPixmapItem::setOffset(const QPointF &offset)
-{
- Q_D(QGraphicsPixmapItem);
- if (d->offset == offset)
- return;
- prepareGeometryChange();
- d->offset = offset;
- d->hasShape = false;
- update();
-}
-
-/*!
- \fn void QGraphicsPixmapItem::setOffset(qreal x, qreal y)
- \since 4.3
-
- This convenience function is equivalent to calling setOffset(QPointF(\a x, \a y)).
-*/
-
-/*!
- \reimp
-*/
-QRectF QGraphicsPixmapItem::boundingRect() const
-{
- Q_D(const QGraphicsPixmapItem);
- if (d->pixmap.isNull())
- return QRectF();
- if (d->flags & ItemIsSelectable) {
- qreal pw = 1.0;
- return QRectF(d->offset, d->pixmap.size()).adjusted(-pw/2, -pw/2, pw/2, pw/2);
- } else {
- return QRectF(d->offset, d->pixmap.size());
- }
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsPixmapItem::shape() const
-{
- Q_D(const QGraphicsPixmapItem);
- if (!d->hasShape) {
- QGraphicsPixmapItemPrivate *thatD = const_cast<QGraphicsPixmapItemPrivate *>(d);
- thatD->updateShape();
- thatD->hasShape = true;
- }
- return d_func()->shape;
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsPixmapItem::contains(const QPointF &point) const
-{
- return QGraphicsItem::contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsPixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- Q_D(QGraphicsPixmapItem);
- Q_UNUSED(widget);
-
- painter->setRenderHint(QPainter::SmoothPixmapTransform,
- (d->transformationMode == Qt::SmoothTransformation));
-
- painter->drawPixmap(d->offset, d->pixmap);
-
- if (option->state & QStyle::State_Selected)
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsPixmapItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QGraphicsItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsPixmapItem::opaqueArea() const
-{
- return shape();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsPixmapItem::type() const
-{
- return Type;
-}
-
-/*!
- Returns the item's shape mode. The shape mode describes how
- QGraphicsPixmapItem calculates its shape. The default mode is MaskShape.
-
- \sa setShapeMode(), ShapeMode
-*/
-QGraphicsPixmapItem::ShapeMode QGraphicsPixmapItem::shapeMode() const
-{
- return d_func()->shapeMode;
-}
-
-/*!
- Sets the item's shape mode to \a mode. The shape mode describes how
- QGraphicsPixmapItem calculates its shape. The default mode is MaskShape.
-
- \sa shapeMode(), ShapeMode
-*/
-void QGraphicsPixmapItem::setShapeMode(ShapeMode mode)
-{
- Q_D(QGraphicsPixmapItem);
- if (d->shapeMode == mode)
- return;
- d->shapeMode = mode;
- d->hasShape = false;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsPixmapItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsPixmapItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsPixmapItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsTextItem
- \brief The QGraphicsTextItem class provides a text item that you can add to
- a QGraphicsScene to display formatted text.
- \since 4.2
- \ingroup graphicsview-api
-
- If you only need to show plain text in an item, consider using QGraphicsSimpleTextItem
- instead.
-
- To set the item's text, pass a QString to QGraphicsTextItem's
- constructor, or call setHtml()/setPlainText().
-
- QGraphicsTextItem uses the text's formatted size and the associated font
- to provide a reasonable implementation of boundingRect(), shape(),
- and contains(). You can set the font by calling setFont().
-
- It is possible to make the item editable by setting the Qt::TextEditorInteraction flag
- using setTextInteractionFlags().
-
- The item's preferred text width can be set using setTextWidth() and obtained
- using textWidth().
-
- \note In order to align HTML text in the center, the item's text width must be set.
-
- \img graphicsview-textitem.png
-
- \note QGraphicsTextItem accepts \l{QGraphicsItem::acceptHoverEvents()}{hover events}
- by default. You can change this with \l{QGraphicsItem::}{setAcceptHoverEvents()}.
-
- \sa QGraphicsSimpleTextItem, QGraphicsPathItem, QGraphicsRectItem,
- QGraphicsEllipseItem, QGraphicsPixmapItem, QGraphicsPolygonItem,
- QGraphicsLineItem, {Graphics View Framework}
-*/
-
-class QGraphicsTextItemPrivate
-{
-public:
- QGraphicsTextItemPrivate()
- : control(0), pageNumber(0), useDefaultImpl(false), tabChangesFocus(false), clickCausedFocus(0)
- { }
-
- mutable QTextControl *control;
- QTextControl *textControl() const;
-
- inline QPointF controlOffset() const
- { return QPointF(0., pageNumber * control->document()->pageSize().height()); }
- inline void sendControlEvent(QEvent *e)
- { if (control) control->processEvent(e, controlOffset()); }
-
- void _q_updateBoundingRect(const QSizeF &);
- void _q_update(QRectF);
- void _q_ensureVisible(QRectF);
- bool _q_mouseOnEdge(QGraphicsSceneMouseEvent *);
-
- QRectF boundingRect;
- int pageNumber;
- bool useDefaultImpl;
- bool tabChangesFocus;
-
- uint clickCausedFocus : 1;
-
- QGraphicsTextItem *qq;
-};
-
-
-/*!
- Constructs a QGraphicsTextItem, using \a text as the default plain
- text. \a parent is passed to QGraphicsItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsTextItem::QGraphicsTextItem(const QString &text, QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsObject(*new QGraphicsItemPrivate, parent, scene), dd(new QGraphicsTextItemPrivate)
-{
- dd->qq = this;
- if (!text.isEmpty())
- setPlainText(text);
- setAcceptDrops(true);
- setAcceptHoverEvents(true);
- setFlags(ItemUsesExtendedStyleOption);
-}
-
-/*!
- Constructs a QGraphicsTextItem. \a parent is passed to QGraphicsItem's
- constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsTextItem::QGraphicsTextItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsObject(*new QGraphicsItemPrivate, parent, scene), dd(new QGraphicsTextItemPrivate)
-{
- dd->qq = this;
- setAcceptDrops(true);
- setAcceptHoverEvents(true);
- setFlag(ItemUsesExtendedStyleOption);
-}
-
-/*!
- Destroys the QGraphicsTextItem.
-*/
-QGraphicsTextItem::~QGraphicsTextItem()
-{
- delete dd;
-}
-
-/*!
- Returns the item's text converted to HTML, or an empty QString if no text has been set.
-
- \sa setHtml()
-*/
-QString QGraphicsTextItem::toHtml() const
-{
-#ifndef QT_NO_TEXTHTMLPARSER
- if (dd->control)
- return dd->control->toHtml();
-#endif
- return QString();
-}
-
-/*!
- Sets the item's text to \a text, assuming that text is HTML formatted. If
- the item has keyboard input focus, this function will also call
- ensureVisible() to ensure that the text is visible in all viewports.
-
- \sa toHtml(), hasFocus(), QGraphicsSimpleTextItem
-*/
-void QGraphicsTextItem::setHtml(const QString &text)
-{
- dd->textControl()->setHtml(text);
-}
-
-/*!
- Returns the item's text converted to plain text, or an empty QString if no text has been set.
-
- \sa setPlainText()
-*/
-QString QGraphicsTextItem::toPlainText() const
-{
- if (dd->control)
- return dd->control->toPlainText();
- return QString();
-}
-
-/*!
- Sets the item's text to \a text. If the item has keyboard input focus,
- this function will also call ensureVisible() to ensure that the text is
- visible in all viewports.
-
- \sa toHtml(), hasFocus()
-*/
-void QGraphicsTextItem::setPlainText(const QString &text)
-{
- dd->textControl()->setPlainText(text);
-}
-
-/*!
- Returns the item's font, which is used to render the text.
-
- \sa setFont()
-*/
-QFont QGraphicsTextItem::font() const
-{
- if (!dd->control)
- return QFont();
- return dd->control->document()->defaultFont();
-}
-
-/*!
- Sets the font used to render the text item to \a font.
-
- \sa font()
-*/
-void QGraphicsTextItem::setFont(const QFont &font)
-{
- dd->textControl()->document()->setDefaultFont(font);
-}
-
-/*!
- Sets the color for unformatted text to \a col.
-*/
-void QGraphicsTextItem::setDefaultTextColor(const QColor &col)
-{
- QTextControl *c = dd->textControl();
- QPalette pal = c->palette();
- QColor old = pal.color(QPalette::Text);
- pal.setColor(QPalette::Text, col);
- c->setPalette(pal);
- if (old != col)
- update();
-}
-
-/*!
- Returns the default text color that is used to for unformatted text.
-*/
-QColor QGraphicsTextItem::defaultTextColor() const
-{
- return dd->textControl()->palette().color(QPalette::Text);
-}
-
-/*!
- \reimp
-*/
-QRectF QGraphicsTextItem::boundingRect() const
-{
- return dd->boundingRect;
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsTextItem::shape() const
-{
- if (!dd->control)
- return QPainterPath();
- QPainterPath path;
- path.addRect(dd->boundingRect);
- return path;
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsTextItem::contains(const QPointF &point) const
-{
- return dd->boundingRect.contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- Q_UNUSED(widget);
- if (dd->control) {
- painter->save();
- QRectF r = option->exposedRect;
- painter->translate(-dd->controlOffset());
- r.translate(dd->controlOffset());
-
- QTextDocument *doc = dd->control->document();
- QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout());
-
- // the layout might need to expand the root frame to
- // the viewport if NoWrap is set
- if (layout)
- layout->setViewport(dd->boundingRect);
-
- dd->control->drawContents(painter, r);
-
- if (layout)
- layout->setViewport(QRect());
-
- painter->restore();
- }
-
- if (option->state & (QStyle::State_Selected | QStyle::State_HasFocus))
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsTextItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QGraphicsItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsTextItem::opaqueArea() const
-{
- return QGraphicsItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsTextItem::type() const
-{
- return Type;
-}
-
-/*!
- Sets the preferred width for the item's text. If the actual text
- is wider than the specified width then it will be broken into
- multiple lines.
-
- If \a width is set to -1 then the text will not be broken into
- multiple lines unless it is enforced through an explicit line
- break or a new paragraph.
-
- The default value is -1.
-
- Note that QGraphicsTextItem keeps a QTextDocument internally,
- which is used to calculate the text width.
-
- \sa textWidth(), QTextDocument::setTextWidth()
-*/
-void QGraphicsTextItem::setTextWidth(qreal width)
-{
- dd->textControl()->setTextWidth(width);
-}
-
-/*!
- Returns the text width.
-
- The width is calculated with the QTextDocument that
- QGraphicsTextItem keeps internally.
-
- \sa setTextWidth(), QTextDocument::textWidth()
-*/
-qreal QGraphicsTextItem::textWidth() const
-{
- if (!dd->control)
- return -1;
- return dd->control->textWidth();
-}
-
-/*!
- Adjusts the text item to a reasonable size.
-*/
-void QGraphicsTextItem::adjustSize()
-{
- if (dd->control)
- dd->control->adjustSize();
-}
-
-/*!
- Sets the text document \a document on the item.
-*/
-void QGraphicsTextItem::setDocument(QTextDocument *document)
-{
- dd->textControl()->setDocument(document);
- dd->_q_updateBoundingRect(dd->control->size());
-}
-
-/*!
- Returns the item's text document.
-*/
-QTextDocument *QGraphicsTextItem::document() const
-{
- return dd->textControl()->document();
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsTextItem::sceneEvent(QEvent *event)
-{
- QEvent::Type t = event->type();
- if (!dd->tabChangesFocus && (t == QEvent::KeyPress || t == QEvent::KeyRelease)) {
- int k = ((QKeyEvent *)event)->key();
- if (k == Qt::Key_Tab || k == Qt::Key_Backtab) {
- dd->sendControlEvent(event);
- return true;
- }
- }
- bool result = QGraphicsItem::sceneEvent(event);
-
- // Ensure input context is updated.
- switch (event->type()) {
- case QEvent::ContextMenu:
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- case QEvent::GraphicsSceneDragEnter:
- case QEvent::GraphicsSceneDragLeave:
- case QEvent::GraphicsSceneDragMove:
- case QEvent::GraphicsSceneDrop:
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverLeave:
- case QEvent::GraphicsSceneHoverMove:
- case QEvent::GraphicsSceneMouseDoubleClick:
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- // Reset the focus widget's input context, regardless
- // of how this item gained or lost focus.
- if (QWidget *fw = qApp->focusWidget()) {
-#ifndef QT_NO_IM
- if (QInputContext *qic = fw->inputContext()) {
- if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut)
- qic->reset();
- else
- qic->update();
- }
-#endif //QT_NO_IM
- }
- break;
- case QEvent::ShortcutOverride:
- dd->sendControlEvent(event);
- return true;
- default:
- break;
- }
-
- return result;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- if ((QGraphicsItem::d_ptr->flags & (ItemIsSelectable | ItemIsMovable))
- && (event->buttons() & Qt::LeftButton) && dd->_q_mouseOnEdge(event)) {
- // User left-pressed on edge of selectable/movable item, use
- // base impl.
- dd->useDefaultImpl = true;
- } else if (event->buttons() == event->button()
- && dd->control->textInteractionFlags() == Qt::NoTextInteraction) {
- // User pressed first button on non-interactive item.
- dd->useDefaultImpl = true;
- }
- if (dd->useDefaultImpl) {
- QGraphicsItem::mousePressEvent(event);
- if (!event->isAccepted())
- dd->useDefaultImpl = false;
- return;
- }
-
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
-{
- if (dd->useDefaultImpl) {
- QGraphicsItem::mouseMoveEvent(event);
- return;
- }
-
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
-{
- if (dd->useDefaultImpl) {
- QGraphicsItem::mouseReleaseEvent(event);
- if (dd->control->textInteractionFlags() == Qt::NoTextInteraction
- && !event->buttons()) {
- // User released last button on non-interactive item.
- dd->useDefaultImpl = false;
- } else if ((event->buttons() & Qt::LeftButton) == 0) {
- // User released the left button on an interactive item.
- dd->useDefaultImpl = false;
- }
- return;
- }
-
- QWidget *widget = event->widget();
- if (widget && (dd->control->textInteractionFlags() & Qt::TextEditable) && boundingRect().contains(event->pos())) {
- qt_widget_private(widget)->handleSoftwareInputPanel(event->button(), dd->clickCausedFocus);
- }
- dd->clickCausedFocus = 0;
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
-{
- if (dd->useDefaultImpl) {
- QGraphicsItem::mouseDoubleClickEvent(event);
- return;
- }
-
- if (!hasFocus()) {
- QGraphicsItem::mouseDoubleClickEvent(event);
- return;
- }
-
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::keyPressEvent(QKeyEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::keyReleaseEvent(QKeyEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::focusInEvent(QFocusEvent *event)
-{
- dd->sendControlEvent(event);
- if (event->reason() == Qt::MouseFocusReason) {
- dd->clickCausedFocus = 1;
- }
- update();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::focusOutEvent(QFocusEvent *event)
-{
- dd->sendControlEvent(event);
- update();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::dropEvent(QGraphicsSceneDragDropEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::inputMethodEvent(QInputMethodEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsTextItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
-{
- dd->sendControlEvent(event);
-}
-
-/*!
- \reimp
-*/
-QVariant QGraphicsTextItem::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- QVariant v;
- if (dd->control)
- v = dd->control->inputMethodQuery(query);
- if (v.type() == QVariant::RectF)
- v = v.toRectF().translated(-dd->controlOffset());
- else if (v.type() == QVariant::PointF)
- v = v.toPointF() - dd->controlOffset();
- else if (v.type() == QVariant::Rect)
- v = v.toRect().translated(-dd->controlOffset().toPoint());
- else if (v.type() == QVariant::Point)
- v = v.toPoint() - dd->controlOffset().toPoint();
- return v;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsTextItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsTextItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsTextItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \internal
-*/
-void QGraphicsTextItemPrivate::_q_update(QRectF rect)
-{
- if (rect.isValid()) {
- rect.translate(-controlOffset());
- } else {
- rect = boundingRect;
- }
- if (rect.intersects(boundingRect))
- qq->update(rect);
-}
-
-/*!
- \internal
-*/
-void QGraphicsTextItemPrivate::_q_updateBoundingRect(const QSizeF &size)
-{
- if (!control) return; // can't happen
- const QSizeF pageSize = control->document()->pageSize();
- // paged items have a constant (page) size
- if (size == boundingRect.size() || pageSize.height() != -1)
- return;
- qq->prepareGeometryChange();
- boundingRect.setSize(size);
- qq->update();
-}
-
-/*!
- \internal
-*/
-void QGraphicsTextItemPrivate::_q_ensureVisible(QRectF rect)
-{
- if (qq->hasFocus()) {
- rect.translate(-controlOffset());
- qq->ensureVisible(rect, /*xmargin=*/0, /*ymargin=*/0);
- }
-}
-
-QTextControl *QGraphicsTextItemPrivate::textControl() const
-{
- if (!control) {
- QGraphicsTextItem *that = const_cast<QGraphicsTextItem *>(qq);
- control = new QTextControl(that);
- control->setTextInteractionFlags(Qt::NoTextInteraction);
-
- QObject::connect(control, SIGNAL(updateRequest(QRectF)),
- qq, SLOT(_q_update(QRectF)));
- QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)),
- qq, SLOT(_q_updateBoundingRect(QSizeF)));
- QObject::connect(control, SIGNAL(visibilityRequest(QRectF)),
- qq, SLOT(_q_ensureVisible(QRectF)));
- QObject::connect(control, SIGNAL(linkActivated(QString)),
- qq, SIGNAL(linkActivated(QString)));
- QObject::connect(control, SIGNAL(linkHovered(QString)),
- qq, SIGNAL(linkHovered(QString)));
-
- const QSizeF pgSize = control->document()->pageSize();
- if (pgSize.height() != -1) {
- qq->prepareGeometryChange();
- that->dd->boundingRect.setSize(pgSize);
- qq->update();
- } else {
- that->dd->_q_updateBoundingRect(control->size());
- }
- }
- return control;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsTextItemPrivate::_q_mouseOnEdge(QGraphicsSceneMouseEvent *event)
-{
- QPainterPath path;
- path.addRect(qq->boundingRect());
-
- QPainterPath docPath;
- const QTextFrameFormat format = control->document()->rootFrame()->frameFormat();
- docPath.addRect(
- qq->boundingRect().adjusted(
- format.leftMargin(),
- format.topMargin(),
- -format.rightMargin(),
- -format.bottomMargin()));
-
- return path.subtracted(docPath).contains(event->pos());
-}
-
-/*!
- \fn QGraphicsTextItem::linkActivated(const QString &link)
-
- This signal is emitted when the user clicks on a link on a text item
- that enables Qt::LinksAccessibleByMouse or Qt::LinksAccessibleByKeyboard.
- \a link is the link that was clicked.
-
- \sa setTextInteractionFlags()
-*/
-
-/*!
- \fn QGraphicsTextItem::linkHovered(const QString &link)
-
- This signal is emitted when the user hovers over a link on a text item
- that enables Qt::LinksAccessibleByMouse. \a link is
- the link that was hovered over.
-
- \sa setTextInteractionFlags()
-*/
-
-/*!
- Sets the flags \a flags to specify how the text item should react to user
- input.
-
- The default for a QGraphicsTextItem is Qt::NoTextInteraction. This function
- also affects the ItemIsFocusable QGraphicsItem flag by setting it if \a flags
- is different from Qt::NoTextInteraction and clearing it otherwise.
-
- By default, the text is read-only. To transform the item into an editor,
- set the Qt::TextEditable flag.
-*/
-void QGraphicsTextItem::setTextInteractionFlags(Qt::TextInteractionFlags flags)
-{
- if (flags == Qt::NoTextInteraction)
- setFlags(this->flags() & ~(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod));
- else
- setFlags(this->flags() | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod);
-
- dd->textControl()->setTextInteractionFlags(flags);
-}
-
-/*!
- Returns the current text interaction flags.
-
- \sa setTextInteractionFlags()
-*/
-Qt::TextInteractionFlags QGraphicsTextItem::textInteractionFlags() const
-{
- if (!dd->control)
- return Qt::NoTextInteraction;
- return dd->control->textInteractionFlags();
-}
-
-/*!
- \since 4.5
-
- If \a b is true, the \gui Tab key will cause the widget to change focus;
- otherwise, the tab key will insert a tab into the document.
-
- In some occasions text edits should not allow the user to input tabulators
- or change indentation using the \gui Tab key, as this breaks the focus
- chain. The default is false.
-
- \sa tabChangesFocus(), ItemIsFocusable, textInteractionFlags()
-*/
-void QGraphicsTextItem::setTabChangesFocus(bool b)
-{
- dd->tabChangesFocus = b;
-}
-
-/*!
- \since 4.5
-
- Returns true if the \gui Tab key will cause the widget to change focus;
- otherwise, false is returned.
-
- By default, this behavior is disabled, and this function will return false.
-
- \sa setTabChangesFocus()
-*/
-bool QGraphicsTextItem::tabChangesFocus() const
-{
- return dd->tabChangesFocus;
-}
-
-/*!
- \property QGraphicsTextItem::openExternalLinks
-
- Specifies whether QGraphicsTextItem should automatically open links using
- QDesktopServices::openUrl() instead of emitting the
- linkActivated signal.
-
- The default value is false.
-*/
-void QGraphicsTextItem::setOpenExternalLinks(bool open)
-{
- dd->textControl()->setOpenExternalLinks(open);
-}
-
-bool QGraphicsTextItem::openExternalLinks() const
-{
- if (!dd->control)
- return false;
- return dd->control->openExternalLinks();
-}
-
-/*!
- \property QGraphicsTextItem::textCursor
-
- This property represents the visible text cursor in an editable
- text item.
-
- By default, if the item's text has not been set, this property
- contains a null text cursor; otherwise it contains a text cursor
- placed at the start of the item's document.
-*/
-void QGraphicsTextItem::setTextCursor(const QTextCursor &cursor)
-{
- dd->textControl()->setTextCursor(cursor);
-}
-
-QTextCursor QGraphicsTextItem::textCursor() const
-{
- if (!dd->control)
- return QTextCursor();
- return dd->control->textCursor();
-}
-
-class QGraphicsSimpleTextItemPrivate : public QAbstractGraphicsShapeItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSimpleTextItem)
-public:
- inline QGraphicsSimpleTextItemPrivate() {
- pen.setStyle(Qt::NoPen);
- brush.setStyle(Qt::SolidPattern);
- }
- QString text;
- QFont font;
- QRectF boundingRect;
-
- void updateBoundingRect();
-};
-
-static QRectF setupTextLayout(QTextLayout *layout)
-{
- layout->setCacheEnabled(true);
- layout->beginLayout();
- while (layout->createLine().isValid())
- ;
- layout->endLayout();
- qreal maxWidth = 0;
- qreal y = 0;
- for (int i = 0; i < layout->lineCount(); ++i) {
- QTextLine line = layout->lineAt(i);
- maxWidth = qMax(maxWidth, line.naturalTextWidth());
- line.setPosition(QPointF(0, y));
- y += line.height();
- }
- return QRectF(0, 0, maxWidth, y);
-}
-
-void QGraphicsSimpleTextItemPrivate::updateBoundingRect()
-{
- Q_Q(QGraphicsSimpleTextItem);
- QRectF br;
- if (text.isEmpty()) {
- br = QRectF();
- } else {
- QString tmp = text;
- tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
- QStackTextEngine engine(tmp, font);
- QTextLayout layout(&engine);
- br = setupTextLayout(&layout);
- }
- if (br != boundingRect) {
- q->prepareGeometryChange();
- boundingRect = br;
- q->update();
- }
-}
-
-/*!
- \class QGraphicsSimpleTextItem
- \brief The QGraphicsSimpleTextItem class provides a simple text path item
- that you can add to a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
- To set the item's text, you can either pass a QString to
- QGraphicsSimpleTextItem's constructor, or call setText() to change the
- text later. To set the text fill color, call setBrush().
-
- The simple text item can have both a fill and an outline; setBrush() will
- set the text fill (i.e., text color), and setPen() sets the pen that will
- be used to draw the text outline. (The latter can be slow, especially for
- complex pens, and items with long text content.) If all you want is to
- draw a simple line of text, you should call setBrush() only, and leave the
- pen unset; QGraphicsSimpleTextItem's pen is by default Qt::NoPen.
-
- QGraphicsSimpleTextItem uses the text's formatted size and the associated
- font to provide a reasonable implementation of boundingRect(), shape(),
- and contains(). You can set the font by calling setFont().
-
- QGraphicsSimpleText does not display rich text; instead, you can use
- QGraphicsTextItem, which provides full text control capabilities.
-
- \img graphicsview-simpletextitem.png
-
- \sa QGraphicsTextItem, QGraphicsPathItem, QGraphicsRectItem,
- QGraphicsEllipseItem, QGraphicsPixmapItem, QGraphicsPolygonItem,
- QGraphicsLineItem, {Graphics View Framework}
-*/
-
-/*!
- Constructs a QGraphicsSimpleTextItem.
-
- \a parent is passed to QGraphicsItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsSimpleTextItem::QGraphicsSimpleTextItem(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsSimpleTextItemPrivate, parent, scene)
-{
-}
-
-/*!
- Constructs a QGraphicsSimpleTextItem, using \a text as the default plain text.
-
- \a parent is passed to QGraphicsItem's constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsSimpleTextItem::QGraphicsSimpleTextItem(const QString &text, QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QAbstractGraphicsShapeItem(*new QGraphicsSimpleTextItemPrivate, parent, scene)
-{
- setText(text);
-}
-
-/*!
- Destroys the QGraphicsSimpleTextItem.
-*/
-QGraphicsSimpleTextItem::~QGraphicsSimpleTextItem()
-{
-}
-
-/*!
- Sets the item's text to \a text. The text will be displayed as
- plain text. Newline characters ('\n') as well as characters of
- type QChar::LineSeparator will cause item to break the text into
- multiple lines.
-*/
-void QGraphicsSimpleTextItem::setText(const QString &text)
-{
- Q_D(QGraphicsSimpleTextItem);
- if (d->text == text)
- return;
- d->text = text;
- d->updateBoundingRect();
- update();
-}
-
-/*!
- Returns the item's text.
-*/
-QString QGraphicsSimpleTextItem::text() const
-{
- Q_D(const QGraphicsSimpleTextItem);
- return d->text;
-}
-
-/*!
- Sets the font that is used to draw the item's text to \a font.
-*/
-void QGraphicsSimpleTextItem::setFont(const QFont &font)
-{
- Q_D(QGraphicsSimpleTextItem);
- d->font = font;
- d->updateBoundingRect();
-}
-
-/*!
- Returns the font that is used to draw the item's text.
-*/
-QFont QGraphicsSimpleTextItem::font() const
-{
- Q_D(const QGraphicsSimpleTextItem);
- return d->font;
-}
-
-/*!
- \reimp
-*/
-QRectF QGraphicsSimpleTextItem::boundingRect() const
-{
- Q_D(const QGraphicsSimpleTextItem);
- return d->boundingRect;
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsSimpleTextItem::shape() const
-{
- Q_D(const QGraphicsSimpleTextItem);
- QPainterPath path;
- path.addRect(d->boundingRect);
- return path;
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsSimpleTextItem::contains(const QPointF &point) const
-{
- Q_D(const QGraphicsSimpleTextItem);
- return d->boundingRect.contains(point);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- Q_UNUSED(widget);
- Q_D(QGraphicsSimpleTextItem);
-
- painter->setFont(d->font);
-
- QString tmp = d->text;
- tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
- QStackTextEngine engine(tmp, d->font);
- QTextLayout layout(&engine);
- setupTextLayout(&layout);
-
- QPen p;
- p.setBrush(d->brush);
- painter->setPen(p);
- if (d->pen.style() == Qt::NoPen && d->brush.style() == Qt::SolidPattern) {
- painter->setBrush(Qt::NoBrush);
- } else {
- QTextLayout::FormatRange range;
- range.start = 0;
- range.length = layout.text().length();
- range.format.setTextOutline(d->pen);
- QList<QTextLayout::FormatRange> formats;
- formats.append(range);
- layout.setAdditionalFormats(formats);
- }
-
- layout.draw(painter, QPointF(0, 0));
-
- if (option->state & (QStyle::State_Selected | QStyle::State_HasFocus))
- qt_graphicsItem_highlightSelected(this, painter, option);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsSimpleTextItem::isObscuredBy(const QGraphicsItem *item) const
-{
- return QAbstractGraphicsShapeItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsSimpleTextItem::opaqueArea() const
-{
- return QAbstractGraphicsShapeItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsSimpleTextItem::type() const
-{
- return Type;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsSimpleTextItem::supportsExtension(Extension extension) const
-{
- Q_UNUSED(extension);
- return false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSimpleTextItem::setExtension(Extension extension, const QVariant &variant)
-{
- Q_UNUSED(extension);
- Q_UNUSED(variant);
-}
-
-/*!
- \internal
-*/
-QVariant QGraphicsSimpleTextItem::extension(const QVariant &variant) const
-{
- Q_UNUSED(variant);
- return QVariant();
-}
-
-/*!
- \class QGraphicsItemGroup
- \brief The QGraphicsItemGroup class provides a container that treats
- a group of items as a single item.
- \since 4.2
- \ingroup graphicsview-api
-
- A QGraphicsItemGroup is a special type of compound item that
- treats itself and all its children as one item (i.e., all events
- and geometries for all children are merged together). It's common
- to use item groups in presentation tools, when the user wants to
- group several smaller items into one big item in order to simplify
- moving and copying of items.
-
- If all you want is to store items inside other items, you can use
- any QGraphicsItem directly by passing a suitable parent to
- setParentItem().
-
- The boundingRect() function of QGraphicsItemGroup returns the
- bounding rectangle of all items in the item group.
- QGraphicsItemGroup ignores the ItemIgnoresTransformations flag on
- its children (i.e., with respect to the geometry of the group
- item, the children are treated as if they were transformable).
-
- There are two ways to construct an item group. The easiest and
- most common approach is to pass a list of items (e.g., all
- selected items) to QGraphicsScene::createItemGroup(), which
- returns a new QGraphicsItemGroup item. The other approach is to
- manually construct a QGraphicsItemGroup item, add it to the scene
- calling QGraphicsScene::addItem(), and then add items to the group
- manually, one at a time by calling addToGroup(). To dismantle
- ("ungroup") an item group, you can either call
- QGraphicsScene::destroyItemGroup(), or you can manually remove all
- items from the group by calling removeFromGroup().
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 17
-
- The operation of adding and removing items preserves the items'
- scene-relative position and transformation, as opposed to calling
- setParentItem(), where only the child item's parent-relative
- position and transformation are kept.
-
- The addtoGroup() function reparents the target item to this item
- group, keeping the item's position and transformation intact
- relative to the scene. Visually, this means that items added via
- addToGroup() will remain completely unchanged as a result of this
- operation, regardless of the item or the group's current position
- or transformation; although the item's position and matrix are
- likely to change.
-
- The removeFromGroup() function has similar semantics to
- setParentItem(); it reparents the item to the parent item of the
- item group. As with addToGroup(), the item's scene-relative
- position and transformation remain intact.
-
- \sa QGraphicsItem, {Graphics View Framework}
-*/
-
-class QGraphicsItemGroupPrivate : public QGraphicsItemPrivate
-{
-public:
- QRectF itemsBoundingRect;
-};
-
-/*!
- Constructs a QGraphicsItemGroup. \a parent is passed to QGraphicsItem's
- constructor.
-
- \sa QGraphicsScene::addItem()
-*/
-QGraphicsItemGroup::QGraphicsItemGroup(QGraphicsItem *parent
-#ifndef Q_QDOC
- // obsolete argument
- , QGraphicsScene *scene
-#endif
- )
- : QGraphicsItem(*new QGraphicsItemGroupPrivate, parent, scene)
-{
- setHandlesChildEvents(true);
-}
-
-/*!
- Destroys the QGraphicsItemGroup.
-*/
-QGraphicsItemGroup::~QGraphicsItemGroup()
-{
-}
-
-/*!
- Adds the given \a item to this item group. The item will be
- reparented to this group, but its position and transformation
- relative to the scene will stay intact.
-
- \sa removeFromGroup(), QGraphicsScene::createItemGroup()
-*/
-void QGraphicsItemGroup::addToGroup(QGraphicsItem *item)
-{
- Q_D(QGraphicsItemGroup);
- if (!item) {
- qWarning("QGraphicsItemGroup::addToGroup: cannot add null item");
- return;
- }
- if (item == this) {
- qWarning("QGraphicsItemGroup::addToGroup: cannot add a group to itself");
- return;
- }
-
- // COMBINE
- bool ok;
- QTransform itemTransform = item->itemTransform(this, &ok);
-
- if (!ok) {
- qWarning("QGraphicsItemGroup::addToGroup: could not find a valid transformation from item to group coordinates");
- return;
- }
-
- QTransform newItemTransform(itemTransform);
- item->setPos(mapFromItem(item, 0, 0));
- item->setParentItem(this);
-
- // removing position from translation component of the new transform
- if (!item->pos().isNull())
- newItemTransform *= QTransform::fromTranslate(-item->x(), -item->y());
-
- // removing additional transformations properties applied with itemTransform()
- QPointF origin = item->transformOriginPoint();
- QMatrix4x4 m;
- QList<QGraphicsTransform*> transformList = item->transformations();
- for (int i = 0; i < transformList.size(); ++i)
- transformList.at(i)->applyTo(&m);
- newItemTransform *= m.toTransform().inverted();
- newItemTransform.translate(origin.x(), origin.y());
- newItemTransform.rotate(-item->rotation());
- newItemTransform.scale(1/item->scale(), 1/item->scale());
- newItemTransform.translate(-origin.x(), -origin.y());
-
- // ### Expensive, we could maybe use dirtySceneTransform bit for optimization
-
- item->setTransform(newItemTransform);
- item->d_func()->setIsMemberOfGroup(true);
- prepareGeometryChange();
- d->itemsBoundingRect |= itemTransform.mapRect(item->boundingRect() | item->childrenBoundingRect());
- update();
-}
-
-/*!
- Removes the specified \a item from this group. The item will be
- reparented to this group's parent item, or to 0 if this group has
- no parent. Its position and transformation relative to the scene
- will stay intact.
-
- \sa addToGroup(), QGraphicsScene::destroyItemGroup()
-*/
-void QGraphicsItemGroup::removeFromGroup(QGraphicsItem *item)
-{
- Q_D(QGraphicsItemGroup);
- if (!item) {
- qWarning("QGraphicsItemGroup::removeFromGroup: cannot remove null item");
- return;
- }
-
- QGraphicsItem *newParent = d_ptr->parent;
-
- // COMBINE
- bool ok;
- QTransform itemTransform;
- if (newParent)
- itemTransform = item->itemTransform(newParent, &ok);
- else
- itemTransform = item->sceneTransform();
-
- QPointF oldPos = item->mapToItem(newParent, 0, 0);
- item->setParentItem(newParent);
- item->setPos(oldPos);
-
- // removing position from translation component of the new transform
- if (!item->pos().isNull())
- itemTransform *= QTransform::fromTranslate(-item->x(), -item->y());
-
- // removing additional transformations properties applied
- // with itemTransform() or sceneTransform()
- QPointF origin = item->transformOriginPoint();
- QMatrix4x4 m;
- QList<QGraphicsTransform*> transformList = item->transformations();
- for (int i = 0; i < transformList.size(); ++i)
- transformList.at(i)->applyTo(&m);
- itemTransform *= m.toTransform().inverted();
- itemTransform.translate(origin.x(), origin.y());
- itemTransform.rotate(-item->rotation());
- itemTransform.scale(1 / item->scale(), 1 / item->scale());
- itemTransform.translate(-origin.x(), -origin.y());
-
- // ### Expensive, we could maybe use dirtySceneTransform bit for optimization
-
- item->setTransform(itemTransform);
- item->d_func()->setIsMemberOfGroup(item->group() != 0);
-
- // ### Quite expensive. But removeFromGroup() isn't called very often.
- prepareGeometryChange();
- d->itemsBoundingRect = childrenBoundingRect();
-}
-
-/*!
- \reimp
-
- Returns the bounding rect of this group item, and all its children.
-*/
-QRectF QGraphicsItemGroup::boundingRect() const
-{
- Q_D(const QGraphicsItemGroup);
- return d->itemsBoundingRect;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsItemGroup::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- Q_UNUSED(widget);
- if (option->state & QStyle::State_Selected) {
- Q_D(QGraphicsItemGroup);
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(d->itemsBoundingRect);
- }
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsItemGroup::isObscuredBy(const QGraphicsItem *item) const
-{
- return QGraphicsItem::isObscuredBy(item);
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsItemGroup::opaqueArea() const
-{
- return QGraphicsItem::opaqueArea();
-}
-
-/*!
- \reimp
-*/
-int QGraphicsItemGroup::type() const
-{
- return Type;
-}
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QRectF QGraphicsItemEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
-{
- const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
- if (!info && deviceCoordinates) {
- // Device coordinates without info not yet supported.
- qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
- return QRectF();
- }
-
- QRectF rect = item->boundingRect();
- if (!item->d_ptr->children.isEmpty())
- rect |= item->childrenBoundingRect();
-
- if (deviceCoordinates) {
- Q_ASSERT(info->painter);
- rect = info->painter->worldTransform().mapRect(rect);
- }
-
- return rect;
-}
-
-void QGraphicsItemEffectSourcePrivate::draw(QPainter *painter)
-{
- if (!info) {
- qWarning("QGraphicsEffectSource::draw: Can only begin as a result of QGraphicsEffect::draw");
- return;
- }
-
- Q_ASSERT(item->d_ptr->scene);
- QGraphicsScenePrivate *scened = item->d_ptr->scene->d_func();
- if (painter == info->painter) {
- scened->draw(item, painter, info->viewTransform, info->transformPtr, info->exposedRegion,
- info->widget, info->opacity, info->effectTransform, info->wasDirtySceneTransform,
- info->drawItem);
- } else {
- QTransform effectTransform = info->painter->worldTransform().inverted();
- effectTransform *= painter->worldTransform();
- scened->draw(item, painter, info->viewTransform, info->transformPtr, info->exposedRegion,
- info->widget, info->opacity, &effectTransform, info->wasDirtySceneTransform,
- info->drawItem);
- }
-}
-
-// sourceRect must be in the given coordinate system
-QRect QGraphicsItemEffectSourcePrivate::paddedEffectRect(Qt::CoordinateSystem system, QGraphicsEffect::PixmapPadMode mode, const QRectF &sourceRect, bool *unpadded) const
-{
- QRectF effectRectF;
-
- if (unpadded)
- *unpadded = false;
-
- if (mode == QGraphicsEffect::PadToEffectiveBoundingRect) {
- if (info) {
- QRectF deviceRect = system == Qt::DeviceCoordinates ? sourceRect : info->painter->worldTransform().mapRect(sourceRect);
- effectRectF = item->graphicsEffect()->boundingRectFor(deviceRect);
- if (unpadded)
- *unpadded = (effectRectF.size() == sourceRect.size());
- if (info && system == Qt::LogicalCoordinates)
- effectRectF = info->painter->worldTransform().inverted().mapRect(effectRectF);
- } else {
- // no choice but to send a logical coordinate bounding rect to boundingRectFor
- effectRectF = item->graphicsEffect()->boundingRectFor(sourceRect);
- }
- } else if (mode == QGraphicsEffect::PadToTransparentBorder) {
- // adjust by 1.5 to account for cosmetic pens
- effectRectF = sourceRect.adjusted(-1.5, -1.5, 1.5, 1.5);
- } else {
- effectRectF = sourceRect;
- if (unpadded)
- *unpadded = true;
- }
-
- return effectRectF.toAlignedRect();
-}
-
-QPixmap QGraphicsItemEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
- QGraphicsEffect::PixmapPadMode mode) const
-{
- const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
- if (!info && deviceCoordinates) {
- // Device coordinates without info not yet supported.
- qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
- return QPixmap();
- }
- if (!item->d_ptr->scene)
- return QPixmap();
- QGraphicsScenePrivate *scened = item->d_ptr->scene->d_func();
-
- bool unpadded;
- const QRectF sourceRect = boundingRect(system);
- QRect effectRect = paddedEffectRect(system, mode, sourceRect, &unpadded);
-
- if (offset)
- *offset = effectRect.topLeft();
-
- bool untransformed = !deviceCoordinates
- || info->painter->worldTransform().type() <= QTransform::TxTranslate;
- if (untransformed && unpadded && isPixmap()) {
- if (offset)
- *offset = boundingRect(system).topLeft().toPoint();
- return static_cast<QGraphicsPixmapItem *>(item)->pixmap();
- }
-
- if (effectRect.isEmpty())
- return QPixmap();
-
- QPixmap pixmap(effectRect.size());
- pixmap.fill(Qt::transparent);
- QPainter pixmapPainter(&pixmap);
- pixmapPainter.setRenderHints(info ? info->painter->renderHints() : QPainter::TextAntialiasing);
-
- QTransform effectTransform = QTransform::fromTranslate(-effectRect.x(), -effectRect.y());
- if (deviceCoordinates && info->effectTransform)
- effectTransform *= *info->effectTransform;
-
- if (!info) {
- // Logical coordinates without info.
- QTransform sceneTransform = item->sceneTransform();
- QTransform newEffectTransform = sceneTransform.inverted();
- newEffectTransform *= effectTransform;
- scened->draw(item, &pixmapPainter, 0, &sceneTransform, 0, 0, qreal(1.0),
- &newEffectTransform, false, true);
- } else if (deviceCoordinates) {
- // Device coordinates with info.
- scened->draw(item, &pixmapPainter, info->viewTransform, info->transformPtr, 0,
- info->widget, info->opacity, &effectTransform, info->wasDirtySceneTransform,
- info->drawItem);
- } else {
- // Item coordinates with info.
- QTransform newEffectTransform = info->transformPtr->inverted();
- newEffectTransform *= effectTransform;
- scened->draw(item, &pixmapPainter, info->viewTransform, info->transformPtr, 0,
- info->widget, info->opacity, &newEffectTransform, info->wasDirtySceneTransform,
- info->drawItem);
- }
-
- pixmapPainter.end();
-
- return pixmap;
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug debug, QGraphicsItem *item)
-{
- if (!item) {
- debug << "QGraphicsItem(0)";
- return debug;
- }
-
- if (QGraphicsObject *o = item->toGraphicsObject())
- debug << o->metaObject()->className();
- else
- debug << "QGraphicsItem";
- debug << "(this =" << (void*)item
- << ", parent =" << (void*)item->parentItem()
- << ", pos =" << item->pos()
- << ", z =" << item->zValue() << ", flags = "
- << item->flags() << ")";
- return debug;
-}
-
-QDebug operator<<(QDebug debug, QGraphicsObject *item)
-{
- if (!item) {
- debug << "QGraphicsObject(0)";
- return debug;
- }
-
- debug.nospace() << item->metaObject()->className() << '(' << (void*)item;
- if (!item->objectName().isEmpty())
- debug << ", name = " << item->objectName();
- debug.nospace() << ", parent = " << ((void*)item->parentItem())
- << ", pos = " << item->pos()
- << ", z = " << item->zValue() << ", flags = "
- << item->flags() << ')';
- return debug.space();
-}
-
-QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change)
-{
- const char *str = "UnknownChange";
- switch (change) {
- case QGraphicsItem::ItemChildAddedChange:
- str = "ItemChildAddedChange";
- break;
- case QGraphicsItem::ItemChildRemovedChange:
- str = "ItemChildRemovedChange";
- break;
- case QGraphicsItem::ItemCursorChange:
- str = "ItemCursorChange";
- break;
- case QGraphicsItem::ItemCursorHasChanged:
- str = "ItemCursorHasChanged";
- break;
- case QGraphicsItem::ItemEnabledChange:
- str = "ItemEnabledChange";
- break;
- case QGraphicsItem::ItemEnabledHasChanged:
- str = "ItemEnabledHasChanged";
- break;
- case QGraphicsItem::ItemFlagsChange:
- str = "ItemFlagsChange";
- break;
- case QGraphicsItem::ItemFlagsHaveChanged:
- str = "ItemFlagsHaveChanged";
- break;
- case QGraphicsItem::ItemMatrixChange:
- str = "ItemMatrixChange";
- break;
- case QGraphicsItem::ItemParentChange:
- str = "ItemParentChange";
- break;
- case QGraphicsItem::ItemParentHasChanged:
- str = "ItemParentHasChanged";
- break;
- case QGraphicsItem::ItemPositionChange:
- str = "ItemPositionChange";
- break;
- case QGraphicsItem::ItemPositionHasChanged:
- str = "ItemPositionHasChanged";
- break;
- case QGraphicsItem::ItemSceneChange:
- str = "ItemSceneChange";
- break;
- case QGraphicsItem::ItemSceneHasChanged:
- str = "ItemSceneHasChanged";
- break;
- case QGraphicsItem::ItemSelectedChange:
- str = "ItemSelectedChange";
- break;
- case QGraphicsItem::ItemSelectedHasChanged:
- str = "ItemSelectedHasChanged";
- break;
- case QGraphicsItem::ItemToolTipChange:
- str = "ItemToolTipChange";
- break;
- case QGraphicsItem::ItemToolTipHasChanged:
- str = "ItemToolTipHasChanged";
- break;
- case QGraphicsItem::ItemTransformChange:
- str = "ItemTransformChange";
- break;
- case QGraphicsItem::ItemTransformHasChanged:
- str = "ItemTransformHasChanged";
- break;
- case QGraphicsItem::ItemVisibleChange:
- str = "ItemVisibleChange";
- break;
- case QGraphicsItem::ItemVisibleHasChanged:
- str = "ItemVisibleHasChanged";
- break;
- case QGraphicsItem::ItemZValueChange:
- str = "ItemZValueChange";
- break;
- case QGraphicsItem::ItemZValueHasChanged:
- str = "ItemZValueHasChanged";
- break;
- case QGraphicsItem::ItemOpacityChange:
- str = "ItemOpacityChange";
- break;
- case QGraphicsItem::ItemOpacityHasChanged:
- str = "ItemOpacityHasChanged";
- break;
- case QGraphicsItem::ItemScenePositionHasChanged:
- str = "ItemScenePositionHasChanged";
- break;
- case QGraphicsItem::ItemRotationChange:
- str = "ItemRotationChange";
- break;
- case QGraphicsItem::ItemRotationHasChanged:
- str = "ItemRotationHasChanged";
- break;
- case QGraphicsItem::ItemScaleChange:
- str = "ItemScaleChange";
- break;
- case QGraphicsItem::ItemScaleHasChanged:
- str = "ItemScaleHasChanged";
- break;
- case QGraphicsItem::ItemTransformOriginPointChange:
- str = "ItemTransformOriginPointChange";
- break;
- case QGraphicsItem::ItemTransformOriginPointHasChanged:
- str = "ItemTransformOriginPointHasChanged";
- break;
- }
- debug << str;
- return debug;
-}
-
-QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag)
-{
- const char *str = "UnknownFlag";
- switch (flag) {
- case QGraphicsItem::ItemIsMovable:
- str = "ItemIsMovable";
- break;
- case QGraphicsItem::ItemIsSelectable:
- str = "ItemIsSelectable";
- break;
- case QGraphicsItem::ItemIsFocusable:
- str = "ItemIsFocusable";
- break;
- case QGraphicsItem::ItemClipsToShape:
- str = "ItemClipsToShape";
- break;
- case QGraphicsItem::ItemClipsChildrenToShape:
- str = "ItemClipsChildrenToShape";
- break;
- case QGraphicsItem::ItemIgnoresTransformations:
- str = "ItemIgnoresTransformations";
- break;
- case QGraphicsItem::ItemIgnoresParentOpacity:
- str = "ItemIgnoresParentOpacity";
- break;
- case QGraphicsItem::ItemDoesntPropagateOpacityToChildren:
- str = "ItemDoesntPropagateOpacityToChildren";
- break;
- case QGraphicsItem::ItemStacksBehindParent:
- str = "ItemStacksBehindParent";
- break;
- case QGraphicsItem::ItemUsesExtendedStyleOption:
- str = "ItemUsesExtendedStyleOption";
- break;
- case QGraphicsItem::ItemHasNoContents:
- str = "ItemHasNoContents";
- break;
- case QGraphicsItem::ItemSendsGeometryChanges:
- str = "ItemSendsGeometryChanges";
- break;
- case QGraphicsItem::ItemAcceptsInputMethod:
- str = "ItemAcceptsInputMethod";
- break;
- case QGraphicsItem::ItemNegativeZStacksBehindParent:
- str = "ItemNegativeZStacksBehindParent";
- break;
- case QGraphicsItem::ItemIsPanel:
- str = "ItemIsPanel";
- break;
- case QGraphicsItem::ItemIsFocusScope:
- str = "ItemIsFocusScope";
- break;
- case QGraphicsItem::ItemSendsScenePositionChanges:
- str = "ItemSendsScenePositionChanges";
- break;
- case QGraphicsItem::ItemStopsClickFocusPropagation:
- str = "ItemStopsClickFocusPropagation";
- break;
- case QGraphicsItem::ItemStopsFocusHandling:
- str = "ItemStopsFocusHandling";
- break;
- }
- debug << str;
- return debug;
-}
-
-QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags)
-{
- debug << '(';
- bool f = false;
- for (int i = 0; i < 17; ++i) {
- if (flags & (1 << i)) {
- if (f)
- debug << '|';
- f = true;
- debug << QGraphicsItem::GraphicsItemFlag(int(flags & (1 << i)));
- }
- }
- debug << ')';
- return debug;
-}
-
-#endif
-
-QT_END_NAMESPACE
-
-#include "moc_qgraphicsitem.cpp"
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h
deleted file mode 100644
index 67c9cd3e2a..0000000000
--- a/src/gui/graphicsview/qgraphicsitem.h
+++ /dev/null
@@ -1,1172 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSITEM_H
-#define QGRAPHICSITEM_H
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qscopedpointer.h>
-#include <QtGui/qpainterpath.h>
-#include <QtGui/qpixmap.h>
-
-class tst_QGraphicsItem;
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QBrush;
-class QCursor;
-class QFocusEvent;
-class QGraphicsEffect;
-class QGraphicsItemGroup;
-class QGraphicsObject;
-class QGraphicsSceneContextMenuEvent;
-class QGraphicsSceneDragDropEvent;
-class QGraphicsSceneEvent;
-class QGraphicsSceneHoverEvent;
-class QGraphicsSceneMouseEvent;
-class QGraphicsSceneWheelEvent;
-class QGraphicsScene;
-class QGraphicsTransform;
-class QGraphicsWidget;
-class QInputMethodEvent;
-class QKeyEvent;
-class QMatrix;
-class QMenu;
-class QPainter;
-class QPen;
-class QPointF;
-class QRectF;
-class QStyleOptionGraphicsItem;
-
-class QGraphicsItemPrivate;
-class Q_GUI_EXPORT QGraphicsItem
-{
-public:
- enum GraphicsItemFlag {
- ItemIsMovable = 0x1,
- ItemIsSelectable = 0x2,
- ItemIsFocusable = 0x4,
- ItemClipsToShape = 0x8,
- ItemClipsChildrenToShape = 0x10,
- ItemIgnoresTransformations = 0x20,
- ItemIgnoresParentOpacity = 0x40,
- ItemDoesntPropagateOpacityToChildren = 0x80,
- ItemStacksBehindParent = 0x100,
- ItemUsesExtendedStyleOption = 0x200,
- ItemHasNoContents = 0x400,
- ItemSendsGeometryChanges = 0x800,
- ItemAcceptsInputMethod = 0x1000,
- ItemNegativeZStacksBehindParent = 0x2000,
- ItemIsPanel = 0x4000,
- ItemIsFocusScope = 0x8000, // internal
- ItemSendsScenePositionChanges = 0x10000,
- ItemStopsClickFocusPropagation = 0x20000,
- ItemStopsFocusHandling = 0x40000
- // NB! Don't forget to increase the d_ptr->flags bit field by 1 when adding a new flag.
- };
- Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag)
-
- enum GraphicsItemChange {
- ItemPositionChange,
- ItemMatrixChange,
- ItemVisibleChange,
- ItemEnabledChange,
- ItemSelectedChange,
- ItemParentChange,
- ItemChildAddedChange,
- ItemChildRemovedChange,
- ItemTransformChange,
- ItemPositionHasChanged,
- ItemTransformHasChanged,
- ItemSceneChange,
- ItemVisibleHasChanged,
- ItemEnabledHasChanged,
- ItemSelectedHasChanged,
- ItemParentHasChanged,
- ItemSceneHasChanged,
- ItemCursorChange,
- ItemCursorHasChanged,
- ItemToolTipChange,
- ItemToolTipHasChanged,
- ItemFlagsChange,
- ItemFlagsHaveChanged,
- ItemZValueChange,
- ItemZValueHasChanged,
- ItemOpacityChange,
- ItemOpacityHasChanged,
- ItemScenePositionHasChanged,
- ItemRotationChange,
- ItemRotationHasChanged,
- ItemScaleChange,
- ItemScaleHasChanged,
- ItemTransformOriginPointChange,
- ItemTransformOriginPointHasChanged
- };
-
- enum CacheMode {
- NoCache,
- ItemCoordinateCache,
- DeviceCoordinateCache
- };
-
- enum PanelModality
- {
- NonModal,
- PanelModal,
- SceneModal
- };
-
- QGraphicsItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- virtual ~QGraphicsItem();
-
- QGraphicsScene *scene() const;
-
- QGraphicsItem *parentItem() const;
- QGraphicsItem *topLevelItem() const;
- QGraphicsObject *parentObject() const;
- QGraphicsWidget *parentWidget() const;
- QGraphicsWidget *topLevelWidget() const;
- QGraphicsWidget *window() const;
- QGraphicsItem *panel() const;
- void setParentItem(QGraphicsItem *parent);
- QList<QGraphicsItem *> children() const; // ### obsolete
- QList<QGraphicsItem *> childItems() const;
- bool isWidget() const;
- bool isWindow() const;
- bool isPanel() const;
-
- QGraphicsObject *toGraphicsObject();
- const QGraphicsObject *toGraphicsObject() const;
-
- QGraphicsItemGroup *group() const;
- void setGroup(QGraphicsItemGroup *group);
-
- GraphicsItemFlags flags() const;
- void setFlag(GraphicsItemFlag flag, bool enabled = true);
- void setFlags(GraphicsItemFlags flags);
-
- CacheMode cacheMode() const;
- void setCacheMode(CacheMode mode, const QSize &cacheSize = QSize());
-
- PanelModality panelModality() const;
- void setPanelModality(PanelModality panelModality);
- bool isBlockedByModalPanel(QGraphicsItem **blockingPanel = 0) const;
-
-#ifndef QT_NO_TOOLTIP
- QString toolTip() const;
- void setToolTip(const QString &toolTip);
-#endif
-
-#ifndef QT_NO_CURSOR
- QCursor cursor() const;
- void setCursor(const QCursor &cursor);
- bool hasCursor() const;
- void unsetCursor();
-#endif
-
- bool isVisible() const;
- bool isVisibleTo(const QGraphicsItem *parent) const;
- void setVisible(bool visible);
- inline void hide() { setVisible(false); }
- inline void show() { setVisible(true); }
-
- bool isEnabled() const;
- void setEnabled(bool enabled);
-
- bool isSelected() const;
- void setSelected(bool selected);
-
- bool acceptDrops() const;
- void setAcceptDrops(bool on);
-
- qreal opacity() const;
- qreal effectiveOpacity() const;
- void setOpacity(qreal opacity);
-
-#ifndef QT_NO_GRAPHICSEFFECT
- // Effect
- QGraphicsEffect *graphicsEffect() const;
- void setGraphicsEffect(QGraphicsEffect *effect);
-#endif //QT_NO_GRAPHICSEFFECT
-
- Qt::MouseButtons acceptedMouseButtons() const;
- void setAcceptedMouseButtons(Qt::MouseButtons buttons);
-
- bool acceptsHoverEvents() const; // ### obsolete
- void setAcceptsHoverEvents(bool enabled); // ### obsolete
- bool acceptHoverEvents() const;
- void setAcceptHoverEvents(bool enabled);
- bool acceptTouchEvents() const;
- void setAcceptTouchEvents(bool enabled);
-
- bool filtersChildEvents() const;
- void setFiltersChildEvents(bool enabled);
-
- bool handlesChildEvents() const;
- void setHandlesChildEvents(bool enabled);
-
- bool isActive() const;
- void setActive(bool active);
-
- bool hasFocus() const;
- void setFocus(Qt::FocusReason focusReason = Qt::OtherFocusReason);
- void clearFocus();
-
- QGraphicsItem *focusProxy() const;
- void setFocusProxy(QGraphicsItem *item);
-
- QGraphicsItem *focusItem() const;
- QGraphicsItem *focusScopeItem() const;
-
- void grabMouse();
- void ungrabMouse();
- void grabKeyboard();
- void ungrabKeyboard();
-
- // Positioning in scene coordinates
- QPointF pos() const;
- inline qreal x() const { return pos().x(); }
- void setX(qreal x);
- inline qreal y() const { return pos().y(); }
- void setY(qreal y);
- QPointF scenePos() const;
- void setPos(const QPointF &pos);
- inline void setPos(qreal x, qreal y);
- inline void moveBy(qreal dx, qreal dy) { setPos(pos().x() + dx, pos().y() + dy); }
-
- void ensureVisible(const QRectF &rect = QRectF(), int xmargin = 50, int ymargin = 50);
- inline void ensureVisible(qreal x, qreal y, qreal w, qreal h, int xmargin = 50, int ymargin = 50);
-
- // Local transformation
- QMatrix matrix() const;
- QMatrix sceneMatrix() const;
- void setMatrix(const QMatrix &matrix, bool combine = false);
- void resetMatrix();
- QTransform transform() const;
- QTransform sceneTransform() const;
- QTransform deviceTransform(const QTransform &viewportTransform) const;
- QTransform itemTransform(const QGraphicsItem *other, bool *ok = 0) const;
- void setTransform(const QTransform &matrix, bool combine = false);
- void resetTransform();
-
- void rotate(qreal angle); // ### obsolete
- void scale(qreal sx, qreal sy); // ### obsolete
- void shear(qreal sh, qreal sv); // ### obsolete
- void translate(qreal dx, qreal dy); // ### obsolete
-
- void setRotation(qreal angle);
- qreal rotation() const;
-
- void setScale(qreal scale);
- qreal scale() const;
-
- QList<QGraphicsTransform *> transformations() const;
- void setTransformations(const QList<QGraphicsTransform *> &transformations);
-
- QPointF transformOriginPoint() const;
- void setTransformOriginPoint(const QPointF &origin);
- inline void setTransformOriginPoint(qreal ax, qreal ay)
- { setTransformOriginPoint(QPointF(ax,ay)); }
-
- virtual void advance(int phase);
-
- // Stacking order
- qreal zValue() const;
- void setZValue(qreal z);
- void stackBefore(const QGraphicsItem *sibling);
-
- // Hit test
- virtual QRectF boundingRect() const = 0;
- QRectF childrenBoundingRect() const;
- QRectF sceneBoundingRect() const;
- virtual QPainterPath shape() const;
- bool isClipped() const;
- QPainterPath clipPath() const;
- virtual bool contains(const QPointF &point) const;
- virtual bool collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- virtual bool collidesWithPath(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- QList<QGraphicsItem *> collidingItems(Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- bool isObscured() const;
- bool isObscured(const QRectF &rect) const; // ### Qt 5: merge with isObscured(), add QRectF arg to isObscuredBy()
- inline bool isObscured(qreal x, qreal y, qreal w, qreal h) const;
- virtual bool isObscuredBy(const QGraphicsItem *item) const;
- virtual QPainterPath opaqueArea() const;
-
- QRegion boundingRegion(const QTransform &itemToDeviceTransform) const;
- qreal boundingRegionGranularity() const;
- void setBoundingRegionGranularity(qreal granularity);
-
- // Drawing
- virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0;
- void update(const QRectF &rect = QRectF());
- inline void update(qreal x, qreal y, qreal width, qreal height);
- void scroll(qreal dx, qreal dy, const QRectF &rect = QRectF());
-
- // Coordinate mapping
- QPointF mapToItem(const QGraphicsItem *item, const QPointF &point) const;
- QPointF mapToParent(const QPointF &point) const;
- QPointF mapToScene(const QPointF &point) const;
- QPolygonF mapToItem(const QGraphicsItem *item, const QRectF &rect) const;
- QPolygonF mapToParent(const QRectF &rect) const;
- QPolygonF mapToScene(const QRectF &rect) const;
- QRectF mapRectToItem(const QGraphicsItem *item, const QRectF &rect) const;
- QRectF mapRectToParent(const QRectF &rect) const;
- QRectF mapRectToScene(const QRectF &rect) const;
- QPolygonF mapToItem(const QGraphicsItem *item, const QPolygonF &polygon) const;
- QPolygonF mapToParent(const QPolygonF &polygon) const;
- QPolygonF mapToScene(const QPolygonF &polygon) const;
- QPainterPath mapToItem(const QGraphicsItem *item, const QPainterPath &path) const;
- QPainterPath mapToParent(const QPainterPath &path) const;
- QPainterPath mapToScene(const QPainterPath &path) const;
- QPointF mapFromItem(const QGraphicsItem *item, const QPointF &point) const;
- QPointF mapFromParent(const QPointF &point) const;
- QPointF mapFromScene(const QPointF &point) const;
- QPolygonF mapFromItem(const QGraphicsItem *item, const QRectF &rect) const;
- QPolygonF mapFromParent(const QRectF &rect) const;
- QPolygonF mapFromScene(const QRectF &rect) const;
- QRectF mapRectFromItem(const QGraphicsItem *item, const QRectF &rect) const;
- QRectF mapRectFromParent(const QRectF &rect) const;
- QRectF mapRectFromScene(const QRectF &rect) const;
- QPolygonF mapFromItem(const QGraphicsItem *item, const QPolygonF &polygon) const;
- QPolygonF mapFromParent(const QPolygonF &polygon) const;
- QPolygonF mapFromScene(const QPolygonF &polygon) const;
- QPainterPath mapFromItem(const QGraphicsItem *item, const QPainterPath &path) const;
- QPainterPath mapFromParent(const QPainterPath &path) const;
- QPainterPath mapFromScene(const QPainterPath &path) const;
-
- inline QPointF mapToItem(const QGraphicsItem *item, qreal x, qreal y) const;
- inline QPointF mapToParent(qreal x, qreal y) const;
- inline QPointF mapToScene(qreal x, qreal y) const;
- inline QPolygonF mapToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
- inline QPolygonF mapToParent(qreal x, qreal y, qreal w, qreal h) const;
- inline QPolygonF mapToScene(qreal x, qreal y, qreal w, qreal h) const;
- inline QRectF mapRectToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
- inline QRectF mapRectToParent(qreal x, qreal y, qreal w, qreal h) const;
- inline QRectF mapRectToScene(qreal x, qreal y, qreal w, qreal h) const;
- inline QPointF mapFromItem(const QGraphicsItem *item, qreal x, qreal y) const;
- inline QPointF mapFromParent(qreal x, qreal y) const;
- inline QPointF mapFromScene(qreal x, qreal y) const;
- inline QPolygonF mapFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
- inline QPolygonF mapFromParent(qreal x, qreal y, qreal w, qreal h) const;
- inline QPolygonF mapFromScene(qreal x, qreal y, qreal w, qreal h) const;
- inline QRectF mapRectFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
- inline QRectF mapRectFromParent(qreal x, qreal y, qreal w, qreal h) const;
- inline QRectF mapRectFromScene(qreal x, qreal y, qreal w, qreal h) const;
-
- bool isAncestorOf(const QGraphicsItem *child) const;
- QGraphicsItem *commonAncestorItem(const QGraphicsItem *other) const;
- bool isUnderMouse() const;
-
- // Custom data
- QVariant data(int key) const;
- void setData(int key, const QVariant &value);
-
- Qt::InputMethodHints inputMethodHints() const;
- void setInputMethodHints(Qt::InputMethodHints hints);
-
- enum {
- Type = 1,
- UserType = 65536
- };
- virtual int type() const;
-
- void installSceneEventFilter(QGraphicsItem *filterItem);
- void removeSceneEventFilter(QGraphicsItem *filterItem);
-
-protected:
- void updateMicroFocus();
- virtual bool sceneEventFilter(QGraphicsItem *watched, QEvent *event);
- virtual bool sceneEvent(QEvent *event);
- virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
- virtual void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
- virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
- virtual void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
- virtual void dropEvent(QGraphicsSceneDragDropEvent *event);
- virtual void focusInEvent(QFocusEvent *event);
- virtual void focusOutEvent(QFocusEvent *event);
- virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
- virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
- virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
- virtual void keyPressEvent(QKeyEvent *event);
- virtual void keyReleaseEvent(QKeyEvent *event);
- virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
- virtual void wheelEvent(QGraphicsSceneWheelEvent *event);
- virtual void inputMethodEvent(QInputMethodEvent *event);
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
- virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value);
-
- enum Extension {
- UserExtension = 0x80000000
- };
- virtual bool supportsExtension(Extension extension) const;
- virtual void setExtension(Extension extension, const QVariant &variant);
- virtual QVariant extension(const QVariant &variant) const;
-
-protected:
- QGraphicsItem(QGraphicsItemPrivate &dd,
- QGraphicsItem *parent, QGraphicsScene *scene);
- QScopedPointer<QGraphicsItemPrivate> d_ptr;
-
- void addToIndex();
- void removeFromIndex();
- void prepareGeometryChange();
-
-private:
- Q_DISABLE_COPY(QGraphicsItem)
- Q_DECLARE_PRIVATE(QGraphicsItem)
- friend class QGraphicsItemGroup;
- friend class QGraphicsScene;
- friend class QGraphicsScenePrivate;
- friend class QGraphicsSceneFindItemBspTreeVisitor;
- friend class QGraphicsSceneBspTree;
- friend class QGraphicsView;
- friend class QGraphicsViewPrivate;
- friend class QGraphicsObject;
- friend class QGraphicsWidget;
- friend class QGraphicsWidgetPrivate;
- friend class QGraphicsProxyWidgetPrivate;
- friend class QGraphicsSceneIndex;
- friend class QGraphicsSceneIndexPrivate;
- friend class QGraphicsSceneBspTreeIndex;
- friend class QGraphicsSceneBspTreeIndexPrivate;
- friend class QGraphicsItemEffectSourcePrivate;
- friend class QGraphicsTransformPrivate;
-#ifndef QT_NO_GESTURES
- friend class QGestureManager;
-#endif
- friend class ::tst_QGraphicsItem;
- friend bool qt_closestLeaf(const QGraphicsItem *, const QGraphicsItem *);
- friend bool qt_closestItemFirst(const QGraphicsItem *, const QGraphicsItem *);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsItem::GraphicsItemFlags)
-Q_DECLARE_INTERFACE(QGraphicsItem, "com.trolltech.Qt.QGraphicsItem")
-
-inline void QGraphicsItem::setPos(qreal ax, qreal ay)
-{ setPos(QPointF(ax, ay)); }
-inline void QGraphicsItem::ensureVisible(qreal ax, qreal ay, qreal w, qreal h, int xmargin, int ymargin)
-{ ensureVisible(QRectF(ax, ay, w, h), xmargin, ymargin); }
-inline void QGraphicsItem::update(qreal ax, qreal ay, qreal width, qreal height)
-{ update(QRectF(ax, ay, width, height)); }
-inline bool QGraphicsItem::isObscured(qreal ax, qreal ay, qreal w, qreal h) const
-{ return isObscured(QRectF(ax, ay, w, h)); }
-inline QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal ax, qreal ay) const
-{ return mapToItem(item, QPointF(ax, ay)); }
-inline QPointF QGraphicsItem::mapToParent(qreal ax, qreal ay) const
-{ return mapToParent(QPointF(ax, ay)); }
-inline QPointF QGraphicsItem::mapToScene(qreal ax, qreal ay) const
-{ return mapToScene(QPointF(ax, ay)); }
-inline QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal ax, qreal ay) const
-{ return mapFromItem(item, QPointF(ax, ay)); }
-inline QPointF QGraphicsItem::mapFromParent(qreal ax, qreal ay) const
-{ return mapFromParent(QPointF(ax, ay)); }
-inline QPointF QGraphicsItem::mapFromScene(qreal ax, qreal ay) const
-{ return mapFromScene(QPointF(ax, ay)); }
-inline QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapToItem(item, QRectF(ax, ay, w, h)); }
-inline QPolygonF QGraphicsItem::mapToParent(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapToParent(QRectF(ax, ay, w, h)); }
-inline QPolygonF QGraphicsItem::mapToScene(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapToScene(QRectF(ax, ay, w, h)); }
-inline QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapRectToItem(item, QRectF(ax, ay, w, h)); }
-inline QRectF QGraphicsItem::mapRectToParent(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapRectToParent(QRectF(ax, ay, w, h)); }
-inline QRectF QGraphicsItem::mapRectToScene(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapRectToScene(QRectF(ax, ay, w, h)); }
-inline QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapFromItem(item, QRectF(ax, ay, w, h)); }
-inline QPolygonF QGraphicsItem::mapFromParent(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapFromParent(QRectF(ax, ay, w, h)); }
-inline QPolygonF QGraphicsItem::mapFromScene(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapFromScene(QRectF(ax, ay, w, h)); }
-inline QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapRectFromItem(item, QRectF(ax, ay, w, h)); }
-inline QRectF QGraphicsItem::mapRectFromParent(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapRectFromParent(QRectF(ax, ay, w, h)); }
-inline QRectF QGraphicsItem::mapRectFromScene(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapRectFromScene(QRectF(ax, ay, w, h)); }
-
-
-class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem
-{
- Q_OBJECT
- Q_PROPERTY(QGraphicsObject * parent READ parentObject WRITE setParentItem NOTIFY parentChanged DESIGNABLE false)
- Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged FINAL)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged)
- Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged FINAL)
- Q_PROPERTY(QPointF pos READ pos WRITE setPos FINAL)
- Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged FINAL)
- Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged FINAL)
- Q_PROPERTY(qreal z READ zValue WRITE setZValue NOTIFY zChanged FINAL)
- Q_PROPERTY(qreal rotation READ rotation WRITE setRotation NOTIFY rotationChanged)
- Q_PROPERTY(qreal scale READ scale WRITE setScale NOTIFY scaleChanged)
- Q_PROPERTY(QPointF transformOriginPoint READ transformOriginPoint WRITE setTransformOriginPoint)
-#ifndef QT_NO_GRAPHICSEFFECT
- Q_PROPERTY(QGraphicsEffect *effect READ graphicsEffect WRITE setGraphicsEffect)
-#endif
- Q_PRIVATE_PROPERTY(QGraphicsItem::d_func(), QDeclarativeListProperty<QGraphicsObject> children READ childrenList DESIGNABLE false NOTIFY childrenChanged)
- Q_PRIVATE_PROPERTY(QGraphicsItem::d_func(), qreal width READ width WRITE setWidth NOTIFY widthChanged RESET resetWidth FINAL)
- Q_PRIVATE_PROPERTY(QGraphicsItem::d_func(), qreal height READ height WRITE setHeight NOTIFY heightChanged RESET resetHeight FINAL)
- Q_CLASSINFO("DefaultProperty", "children")
- Q_INTERFACES(QGraphicsItem)
-public:
- QGraphicsObject(QGraphicsItem *parent = 0);
-
- // ### Qt 5: Disambiguate
-#ifdef Q_NO_USING_KEYWORD
- const QObjectList &children() const { return QObject::children(); }
-#else
- using QObject::children;
-#endif
-
-#ifndef QT_NO_GESTURES
- void grabGesture(Qt::GestureType type, Qt::GestureFlags flags = Qt::GestureFlags());
- void ungrabGesture(Qt::GestureType type);
-#endif
-
-protected Q_SLOTS:
- void updateMicroFocus();
-
-Q_SIGNALS:
- void parentChanged();
- void opacityChanged();
- void visibleChanged();
- void enabledChanged();
- void xChanged();
- void yChanged();
- void zChanged();
- void rotationChanged();
- void scaleChanged();
- void childrenChanged();
- void widthChanged();
- void heightChanged();
-
-protected:
- QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene);
-private:
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
-};
-
-
-class QAbstractGraphicsShapeItemPrivate;
-class Q_GUI_EXPORT QAbstractGraphicsShapeItem : public QGraphicsItem
-{
-public:
- QAbstractGraphicsShapeItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QAbstractGraphicsShapeItem();
-
- QPen pen() const;
- void setPen(const QPen &pen);
-
- QBrush brush() const;
- void setBrush(const QBrush &brush);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
-protected:
- QAbstractGraphicsShapeItem(QAbstractGraphicsShapeItemPrivate &dd,
- QGraphicsItem *parent, QGraphicsScene *scene);
-
-private:
- Q_DISABLE_COPY(QAbstractGraphicsShapeItem)
- Q_DECLARE_PRIVATE(QAbstractGraphicsShapeItem)
-};
-
-class QGraphicsPathItemPrivate;
-class Q_GUI_EXPORT QGraphicsPathItem : public QAbstractGraphicsShapeItem
-{
-public:
- QGraphicsPathItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsPathItem(const QPainterPath &path, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsPathItem();
-
- QPainterPath path() const;
- void setPath(const QPainterPath &path);
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 2 };
- int type() const;
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsPathItem)
- Q_DECLARE_PRIVATE(QGraphicsPathItem)
-};
-
-class QGraphicsRectItemPrivate;
-class Q_GUI_EXPORT QGraphicsRectItem : public QAbstractGraphicsShapeItem
-{
-public:
- QGraphicsRectItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsRectItem(const QRectF &rect, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsRectItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsRectItem();
-
- QRectF rect() const;
- void setRect(const QRectF &rect);
- inline void setRect(qreal x, qreal y, qreal w, qreal h);
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 3 };
- int type() const;
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsRectItem)
- Q_DECLARE_PRIVATE(QGraphicsRectItem)
-};
-
-inline void QGraphicsRectItem::setRect(qreal ax, qreal ay, qreal w, qreal h)
-{ setRect(QRectF(ax, ay, w, h)); }
-
-class QGraphicsEllipseItemPrivate;
-class Q_GUI_EXPORT QGraphicsEllipseItem : public QAbstractGraphicsShapeItem
-{
-public:
- QGraphicsEllipseItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsEllipseItem(const QRectF &rect, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsEllipseItem();
-
- QRectF rect() const;
- void setRect(const QRectF &rect);
- inline void setRect(qreal x, qreal y, qreal w, qreal h);
-
- int startAngle() const;
- void setStartAngle(int angle);
-
- int spanAngle() const;
- void setSpanAngle(int angle);
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 4 };
- int type() const;
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsEllipseItem)
- Q_DECLARE_PRIVATE(QGraphicsEllipseItem)
-};
-
-inline void QGraphicsEllipseItem::setRect(qreal ax, qreal ay, qreal w, qreal h)
-{ setRect(QRectF(ax, ay, w, h)); }
-
-class QGraphicsPolygonItemPrivate;
-class Q_GUI_EXPORT QGraphicsPolygonItem : public QAbstractGraphicsShapeItem
-{
-public:
- QGraphicsPolygonItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsPolygonItem(const QPolygonF &polygon,
- QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsPolygonItem();
-
- QPolygonF polygon() const;
- void setPolygon(const QPolygonF &polygon);
-
- Qt::FillRule fillRule() const;
- void setFillRule(Qt::FillRule rule);
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 5 };
- int type() const;
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsPolygonItem)
- Q_DECLARE_PRIVATE(QGraphicsPolygonItem)
-};
-
-class QGraphicsLineItemPrivate;
-class Q_GUI_EXPORT QGraphicsLineItem : public QGraphicsItem
-{
-public:
- QGraphicsLineItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsLineItem(const QLineF &line, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsLineItem(qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsLineItem();
-
- QPen pen() const;
- void setPen(const QPen &pen);
-
- QLineF line() const;
- void setLine(const QLineF &line);
- inline void setLine(qreal x1, qreal y1, qreal x2, qreal y2)
- { setLine(QLineF(x1, y1, x2, y2)); }
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 6 };
- int type() const;
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsLineItem)
- Q_DECLARE_PRIVATE(QGraphicsLineItem)
-};
-
-class QGraphicsPixmapItemPrivate;
-class Q_GUI_EXPORT QGraphicsPixmapItem : public QGraphicsItem
-{
-public:
- enum ShapeMode {
- MaskShape,
- BoundingRectShape,
- HeuristicMaskShape
- };
-
- QGraphicsPixmapItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsPixmapItem(const QPixmap &pixmap, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsPixmapItem();
-
- QPixmap pixmap() const;
- void setPixmap(const QPixmap &pixmap);
-
- Qt::TransformationMode transformationMode() const;
- void setTransformationMode(Qt::TransformationMode mode);
-
- QPointF offset() const;
- void setOffset(const QPointF &offset);
- inline void setOffset(qreal x, qreal y);
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 7 };
- int type() const;
-
- ShapeMode shapeMode() const;
- void setShapeMode(ShapeMode mode);
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsPixmapItem)
- Q_DECLARE_PRIVATE(QGraphicsPixmapItem)
-};
-
-inline void QGraphicsPixmapItem::setOffset(qreal ax, qreal ay)
-{ setOffset(QPointF(ax, ay)); }
-
-class QGraphicsTextItemPrivate;
-class QTextDocument;
-class QTextCursor;
-class Q_GUI_EXPORT QGraphicsTextItem : public QGraphicsObject
-{
- Q_OBJECT
- QDOC_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
- QDOC_PROPERTY(QTextCursor textCursor READ textCursor WRITE setTextCursor)
-
-public:
- QGraphicsTextItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsTextItem(const QString &text, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsTextItem();
-
- QString toHtml() const;
- void setHtml(const QString &html);
-
- QString toPlainText() const;
- void setPlainText(const QString &text);
-
- QFont font() const;
- void setFont(const QFont &font);
-
- void setDefaultTextColor(const QColor &c);
- QColor defaultTextColor() const;
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 8 };
- int type() const;
-
- void setTextWidth(qreal width);
- qreal textWidth() const;
-
- void adjustSize();
-
- void setDocument(QTextDocument *document);
- QTextDocument *document() const;
-
- void setTextInteractionFlags(Qt::TextInteractionFlags flags);
- Qt::TextInteractionFlags textInteractionFlags() const;
-
- void setTabChangesFocus(bool b);
- bool tabChangesFocus() const;
-
- void setOpenExternalLinks(bool open);
- bool openExternalLinks() const;
-
- void setTextCursor(const QTextCursor &cursor);
- QTextCursor textCursor() const;
-
-Q_SIGNALS:
- void linkActivated(const QString &);
- void linkHovered(const QString &);
-
-protected:
- bool sceneEvent(QEvent *event);
- void mousePressEvent(QGraphicsSceneMouseEvent *event);
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
- void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
- void keyPressEvent(QKeyEvent *event);
- void keyReleaseEvent(QKeyEvent *event);
- void focusInEvent(QFocusEvent *event);
- void focusOutEvent(QFocusEvent *event);
- void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
- void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
- void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
- void dropEvent(QGraphicsSceneDragDropEvent *event);
- void inputMethodEvent(QInputMethodEvent *event);
- void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
- void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
-
- QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsTextItem)
- Q_PRIVATE_SLOT(dd, void _q_updateBoundingRect(const QSizeF &))
- Q_PRIVATE_SLOT(dd, void _q_update(QRectF))
- Q_PRIVATE_SLOT(dd, void _q_ensureVisible(QRectF))
- QGraphicsTextItemPrivate *dd;
- friend class QGraphicsTextItemPrivate;
-};
-
-class QGraphicsSimpleTextItemPrivate;
-class Q_GUI_EXPORT QGraphicsSimpleTextItem : public QAbstractGraphicsShapeItem
-{
-public:
- QGraphicsSimpleTextItem(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- QGraphicsSimpleTextItem(const QString &text, QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsSimpleTextItem();
-
- void setText(const QString &text);
- QString text() const;
-
- void setFont(const QFont &font);
- QFont font() const;
-
- QRectF boundingRect() const;
- QPainterPath shape() const;
- bool contains(const QPointF &point) const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 9 };
- int type() const;
-
-protected:
- bool supportsExtension(Extension extension) const;
- void setExtension(Extension extension, const QVariant &variant);
- QVariant extension(const QVariant &variant) const;
-
-private:
- Q_DISABLE_COPY(QGraphicsSimpleTextItem)
- Q_DECLARE_PRIVATE(QGraphicsSimpleTextItem)
-};
-
-class QGraphicsItemGroupPrivate;
-class Q_GUI_EXPORT QGraphicsItemGroup : public QGraphicsItem
-{
-public:
- QGraphicsItemGroup(QGraphicsItem *parent = 0
-#ifndef Q_QDOC
- // ### obsolete argument
- , QGraphicsScene *scene = 0
-#endif
- );
- ~QGraphicsItemGroup();
-
- void addToGroup(QGraphicsItem *item);
- void removeFromGroup(QGraphicsItem *item);
-
- QRectF boundingRect() const;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
-
- bool isObscuredBy(const QGraphicsItem *item) const;
- QPainterPath opaqueArea() const;
-
- enum { Type = 10 };
- int type() const;
-
-private:
- Q_DISABLE_COPY(QGraphicsItemGroup)
- Q_DECLARE_PRIVATE(QGraphicsItemGroup)
-};
-
-template <class T> inline T qgraphicsitem_cast(QGraphicsItem *item)
-{
- return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type)
- || (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0;
-}
-
-template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item)
-{
- return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type)
- || (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem *item);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsObject *item);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags);
-#endif
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QGraphicsItem *)
-Q_DECLARE_METATYPE(QGraphicsScene *)
-
-QT_BEGIN_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QGRAPHICSITEM_H
diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h
deleted file mode 100644
index 90ff43f93c..0000000000
--- a/src/gui/graphicsview/qgraphicsitem_p.h
+++ /dev/null
@@ -1,891 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSITEM_P_H
-#define QGRAPHICSITEM_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 "qgraphicsitem.h"
-#include "qset.h"
-#include "qpixmapcache.h"
-#include <private/qgraphicsview_p.h>
-#include "qgraphicstransform.h"
-#include <private/qgraphicstransform_p.h>
-
-#include <private/qgraphicseffect_p.h>
-#include <qgraphicseffect.h>
-
-#include <QtCore/qpoint.h>
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsItemPrivate;
-
-#ifndef QDECLARATIVELISTPROPERTY
-#define QDECLARATIVELISTPROPERTY
-template<typename T>
-class QDeclarativeListProperty {
-public:
- typedef void (*AppendFunction)(QDeclarativeListProperty<T> *, T*);
- typedef int (*CountFunction)(QDeclarativeListProperty<T> *);
- typedef T *(*AtFunction)(QDeclarativeListProperty<T> *, int);
- typedef void (*ClearFunction)(QDeclarativeListProperty<T> *);
-
- QDeclarativeListProperty()
- : object(0), data(0), append(0), count(0), at(0), clear(0), dummy1(0), dummy2(0) {}
- QDeclarativeListProperty(QObject *o, QList<T *> &list)
- : object(o), data(&list), append(qlist_append), count(qlist_count), at(qlist_at),
- clear(qlist_clear), dummy1(0), dummy2(0) {}
- QDeclarativeListProperty(QObject *o, void *d, AppendFunction a, CountFunction c = 0, AtFunction t = 0,
- ClearFunction r = 0)
- : object(o), data(d), append(a), count(c), at(t), clear(r), dummy1(0), dummy2(0) {}
-
- bool operator==(const QDeclarativeListProperty &o) const {
- return object == o.object &&
- data == o.data &&
- append == o.append &&
- count == o.count &&
- at == o.at &&
- clear == o.clear;
- }
-
- QObject *object;
- void *data;
-
- AppendFunction append;
-
- CountFunction count;
- AtFunction at;
-
- ClearFunction clear;
-
- void *dummy1;
- void *dummy2;
-
-private:
- static void qlist_append(QDeclarativeListProperty *p, T *v) {
- ((QList<T *> *)p->data)->append(v);
- }
- static int qlist_count(QDeclarativeListProperty *p) {
- return ((QList<T *> *)p->data)->count();
- }
- static T *qlist_at(QDeclarativeListProperty *p, int idx) {
- return ((QList<T *> *)p->data)->at(idx);
- }
- static void qlist_clear(QDeclarativeListProperty *p) {
- return ((QList<T *> *)p->data)->clear();
- }
-};
-#endif
-
-class QGraphicsItemCache
-{
-public:
- QGraphicsItemCache() : allExposed(false) { }
-
- // ItemCoordinateCache only
- QRect boundingRect;
- QSize fixedSize;
- QPixmapCache::Key key;
-
- // DeviceCoordinateCache only
- struct DeviceData {
- DeviceData() {}
- QTransform lastTransform;
- QPoint cacheIndent;
- QPixmapCache::Key key;
- };
- QMap<QPaintDevice *, DeviceData> deviceData;
-
- // List of logical exposed rects
- QVector<QRectF> exposed;
- bool allExposed;
-
- // Empty cache
- void purge();
-};
-
-class Q_GUI_EXPORT QGraphicsItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsItem)
-public:
- enum Extra {
- ExtraToolTip,
- ExtraCursor,
- ExtraCacheData,
- ExtraMaxDeviceCoordCacheSize,
- ExtraBoundingRegionGranularity
- };
-
- enum AncestorFlag {
- NoFlag = 0,
- AncestorHandlesChildEvents = 0x1,
- AncestorClipsChildren = 0x2,
- AncestorIgnoresTransformations = 0x4,
- AncestorFiltersChildEvents = 0x8
- };
-
- inline QGraphicsItemPrivate()
- : z(0),
- opacity(1.),
- scene(0),
- parent(0),
- transformData(0),
- graphicsEffect(0),
- index(-1),
- siblingIndex(-1),
- itemDepth(-1),
- focusProxy(0),
- subFocusItem(0),
- focusScopeItem(0),
- imHints(Qt::ImhNone),
- panelModality(QGraphicsItem::NonModal),
- acceptedMouseButtons(0x1f),
- visible(1),
- explicitlyHidden(0),
- enabled(1),
- explicitlyDisabled(0),
- selected(0),
- acceptsHover(0),
- acceptDrops(0),
- isMemberOfGroup(0),
- handlesChildEvents(0),
- itemDiscovered(0),
- hasCursor(0),
- ancestorFlags(0),
- cacheMode(0),
- hasBoundingRegionGranularity(0),
- isWidget(0),
- dirty(0),
- dirtyChildren(0),
- localCollisionHack(0),
- inSetPosHelper(0),
- needSortChildren(0),
- allChildrenDirty(0),
- fullUpdatePending(0),
- dirtyChildrenBoundingRect(1),
- flags(0),
- paintedViewBoundingRectsNeedRepaint(0),
- dirtySceneTransform(1),
- geometryChanged(1),
- inDestructor(0),
- isObject(0),
- ignoreVisible(0),
- ignoreOpacity(0),
- acceptTouchEvents(0),
- acceptedTouchBeginEvent(0),
- filtersDescendantEvents(0),
- sceneTransformTranslateOnly(0),
- notifyBoundingRectChanged(0),
- notifyInvalidated(0),
- mouseSetsFocus(1),
- explicitActivate(0),
- wantsActive(0),
- holesInSiblingIndex(0),
- sequentialOrdering(1),
- updateDueToGraphicsEffect(0),
- scenePosDescendants(0),
- pendingPolish(0),
- mayHaveChildWithGraphicsEffect(0),
- isDeclarativeItem(0),
- sendParentChangeNotification(0),
- globalStackingOrder(-1),
- q_ptr(0)
- {
- }
-
- inline virtual ~QGraphicsItemPrivate()
- { }
-
- static const QGraphicsItemPrivate *get(const QGraphicsItem *item)
- {
- return item->d_ptr.data();
- }
- static QGraphicsItemPrivate *get(QGraphicsItem *item)
- {
- return item->d_ptr.data();
- }
-
- void updateChildWithGraphicsEffectFlagRecursively();
- void updateAncestorFlag(QGraphicsItem::GraphicsItemFlag childFlag,
- AncestorFlag flag = NoFlag, bool enabled = false, bool root = true);
- void updateAncestorFlags();
- void setIsMemberOfGroup(bool enabled);
- void remapItemPos(QEvent *event, QGraphicsItem *item);
- QPointF genericMapFromScene(const QPointF &pos, const QWidget *viewport) const;
- inline bool itemIsUntransformable() const
- {
- return (flags & QGraphicsItem::ItemIgnoresTransformations)
- || (ancestorFlags & AncestorIgnoresTransformations);
- }
-
- void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const;
- void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const;
- virtual void updateSceneTransformFromParent();
-
- // ### Qt 5: Remove. Workaround for reimplementation added after Qt 4.4.
- virtual QVariant inputMethodQueryHelper(Qt::InputMethodQuery query) const;
- static bool movableAncestorIsSelected(const QGraphicsItem *item);
-
- virtual void setPosHelper(const QPointF &pos);
- void setTransformHelper(const QTransform &transform);
- void prependGraphicsTransform(QGraphicsTransform *t);
- void appendGraphicsTransform(QGraphicsTransform *t);
- void setVisibleHelper(bool newVisible, bool explicitly, bool update = true);
- void setEnabledHelper(bool newEnabled, bool explicitly, bool update = true);
- bool discardUpdateRequest(bool ignoreVisibleBit = false,
- bool ignoreDirtyBit = false, bool ignoreOpacity = false) const;
- virtual void transformChanged() {}
- int depth() const;
-#ifndef QT_NO_GRAPHICSEFFECT
- enum InvalidateReason {
- OpacityChanged
- };
- void invalidateParentGraphicsEffectsRecursively();
- void invalidateChildGraphicsEffectsRecursively(InvalidateReason reason);
-#endif //QT_NO_GRAPHICSEFFECT
- void invalidateDepthRecursively();
- void resolveDepth();
- void addChild(QGraphicsItem *child);
- void removeChild(QGraphicsItem *child);
- QDeclarativeListProperty<QGraphicsObject> childrenList();
- void setParentItemHelper(QGraphicsItem *parent, const QVariant *newParentVariant,
- const QVariant *thisPointerVariant);
- void childrenBoundingRectHelper(QTransform *x, QRectF *rect, QGraphicsItem *topMostEffectItem);
- void initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform,
- const QRegion &exposedRegion, bool allItems = false) const;
- QRectF effectiveBoundingRect(QGraphicsItem *topMostEffectItem = 0) const;
- QRectF sceneEffectiveBoundingRect() const;
-
- QRectF effectiveBoundingRect(const QRectF &rect) const;
-
- virtual void resolveFont(uint inheritedMask)
- {
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->resolveFont(inheritedMask);
- }
-
- virtual void resolvePalette(uint inheritedMask)
- {
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->resolveFont(inheritedMask);
- }
-
- virtual bool isProxyWidget() const;
-
- inline QVariant extra(Extra type) const
- {
- for (int i = 0; i < extras.size(); ++i) {
- const ExtraStruct &extra = extras.at(i);
- if (extra.type == type)
- return extra.value;
- }
- return QVariant();
- }
-
- inline void setExtra(Extra type, const QVariant &value)
- {
- int index = -1;
- for (int i = 0; i < extras.size(); ++i) {
- if (extras.at(i).type == type) {
- index = i;
- break;
- }
- }
-
- if (index == -1) {
- extras << ExtraStruct(type, value);
- } else {
- extras[index].value = value;
- }
- }
-
- inline void unsetExtra(Extra type)
- {
- for (int i = 0; i < extras.size(); ++i) {
- if (extras.at(i).type == type) {
- extras.removeAt(i);
- return;
- }
- }
- }
-
- struct ExtraStruct {
- ExtraStruct(Extra type, QVariant value)
- : type(type), value(value)
- { }
-
- Extra type;
- QVariant value;
-
- bool operator<(Extra extra) const
- { return type < extra; }
- };
-
- QList<ExtraStruct> extras;
-
- QGraphicsItemCache *maybeExtraItemCache() const;
- QGraphicsItemCache *extraItemCache() const;
- void removeExtraItemCache();
-
- void updatePaintedViewBoundingRects(bool updateChildren);
- void ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem);
- inline void ensureSceneTransform()
- {
- QGraphicsItem *that = q_func();
- ensureSceneTransformRecursive(&that);
- }
-
- inline bool hasTranslateOnlySceneTransform()
- {
- ensureSceneTransform();
- return sceneTransformTranslateOnly;
- }
-
- inline void invalidateChildrenSceneTransform()
- {
- for (int i = 0; i < children.size(); ++i)
- children.at(i)->d_ptr->dirtySceneTransform = 1;
- }
-
- inline qreal calcEffectiveOpacity() const
- {
- qreal o = opacity;
- QGraphicsItem *p = parent;
- int myFlags = flags;
- while (p) {
- int parentFlags = p->d_ptr->flags;
-
- // If I have a parent, and I don't ignore my parent's opacity, and my
- // parent propagates to me, then combine my local opacity with my parent's
- // effective opacity into my effective opacity.
- if ((myFlags & QGraphicsItem::ItemIgnoresParentOpacity)
- || (parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) {
- break;
- }
-
- o *= p->d_ptr->opacity;
- p = p->d_ptr->parent;
- myFlags = parentFlags;
- }
- return o;
- }
-
- inline bool isOpacityNull() const
- { return (opacity < qreal(0.001)); }
-
- static inline bool isOpacityNull(qreal opacity)
- { return (opacity < qreal(0.001)); }
-
- inline bool isFullyTransparent() const
- {
- if (isOpacityNull())
- return true;
- if (!parent)
- return false;
-
- return isOpacityNull(calcEffectiveOpacity());
- }
-
- inline qreal effectiveOpacity() const {
- if (!parent || !opacity)
- return opacity;
-
- return calcEffectiveOpacity();
- }
-
- inline qreal combineOpacityFromParent(qreal parentOpacity) const
- {
- if (parent && !(flags & QGraphicsItem::ItemIgnoresParentOpacity)
- && !(parent->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) {
- return parentOpacity * opacity;
- }
- return opacity;
- }
-
- inline bool childrenCombineOpacity() const
- {
- if (!children.size())
- return true;
- if (flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)
- return false;
-
- for (int i = 0; i < children.size(); ++i) {
- if (children.at(i)->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity)
- return false;
- }
- return true;
- }
-
- inline bool childrenClippedToShape() const
- { return (flags & QGraphicsItem::ItemClipsChildrenToShape) || children.isEmpty(); }
-
- inline bool isInvisible() const
- {
- return !visible || (childrenCombineOpacity() && isFullyTransparent());
- }
-
- inline void markParentDirty(bool updateBoundingRect = false);
-
- void setFocusHelper(Qt::FocusReason focusReason, bool climb, bool focusFromHide);
- void clearFocusHelper(bool giveFocusToParent);
- void setSubFocus(QGraphicsItem *rootItem = 0, QGraphicsItem *stopItem = 0);
- void clearSubFocus(QGraphicsItem *rootItem = 0, QGraphicsItem *stopItem = 0);
- void resetFocusProxy();
- virtual void subFocusItemChange();
- virtual void focusScopeItemChange(bool isSubFocusItem);
-
- static void children_append(QDeclarativeListProperty<QGraphicsObject> *list, QGraphicsObject *item);
- static int children_count(QDeclarativeListProperty<QGraphicsObject> *list);
- static QGraphicsObject *children_at(QDeclarativeListProperty<QGraphicsObject> *list, int);
- static void children_clear(QDeclarativeListProperty<QGraphicsObject> *list);
-
- inline QTransform transformToParent() const;
- inline void ensureSortedChildren();
- static inline bool insertionOrder(QGraphicsItem *a, QGraphicsItem *b);
- void ensureSequentialSiblingIndex();
- inline void sendScenePosChange();
- virtual void siblingOrderChange();
-
- // Private Properties
- virtual qreal width() const;
- virtual void setWidth(qreal);
- virtual void resetWidth();
-
- virtual qreal height() const;
- virtual void setHeight(qreal);
- virtual void resetHeight();
-
- QRectF childrenBoundingRect;
- QRectF needsRepaint;
- QMap<QWidget *, QRect> paintedViewBoundingRects;
- QPointF pos;
- qreal z;
- qreal opacity;
- QGraphicsScene *scene;
- QGraphicsItem *parent;
- QList<QGraphicsItem *> children;
- struct TransformData;
- TransformData *transformData;
- QGraphicsEffect *graphicsEffect;
- QTransform sceneTransform;
- int index;
- int siblingIndex;
- int itemDepth; // Lazily calculated when calling depth().
- QGraphicsItem *focusProxy;
- QList<QGraphicsItem **> focusProxyRefs;
- QGraphicsItem *subFocusItem;
- QGraphicsItem *focusScopeItem;
- Qt::InputMethodHints imHints;
- QGraphicsItem::PanelModality panelModality;
-#ifndef QT_NO_GESTURES
- QMap<Qt::GestureType, Qt::GestureFlags> gestureContext;
-#endif
-
- // Packed 32 bits
- quint32 acceptedMouseButtons : 5;
- quint32 visible : 1;
- quint32 explicitlyHidden : 1;
- quint32 enabled : 1;
- quint32 explicitlyDisabled : 1;
- quint32 selected : 1;
- quint32 acceptsHover : 1;
- quint32 acceptDrops : 1;
- quint32 isMemberOfGroup : 1;
- quint32 handlesChildEvents : 1;
- quint32 itemDiscovered : 1;
- quint32 hasCursor : 1;
- quint32 ancestorFlags : 4;
- quint32 cacheMode : 2;
- quint32 hasBoundingRegionGranularity : 1;
- quint32 isWidget : 1;
- quint32 dirty : 1;
- quint32 dirtyChildren : 1;
- quint32 localCollisionHack : 1;
- quint32 inSetPosHelper : 1;
- quint32 needSortChildren : 1;
- quint32 allChildrenDirty : 1;
- quint32 fullUpdatePending : 1;
- quint32 dirtyChildrenBoundingRect : 1;
-
- // Packed 32 bits
- quint32 flags : 19;
- quint32 paintedViewBoundingRectsNeedRepaint : 1;
- quint32 dirtySceneTransform : 1;
- quint32 geometryChanged : 1;
- quint32 inDestructor : 1;
- quint32 isObject : 1;
- quint32 ignoreVisible : 1;
- quint32 ignoreOpacity : 1;
- quint32 acceptTouchEvents : 1;
- quint32 acceptedTouchBeginEvent : 1;
- quint32 filtersDescendantEvents : 1;
- quint32 sceneTransformTranslateOnly : 1;
- quint32 notifyBoundingRectChanged : 1;
- quint32 notifyInvalidated : 1;
-
- // New 32 bits
- quint32 mouseSetsFocus : 1;
- quint32 explicitActivate : 1;
- quint32 wantsActive : 1;
- quint32 holesInSiblingIndex : 1;
- quint32 sequentialOrdering : 1;
- quint32 updateDueToGraphicsEffect : 1;
- quint32 scenePosDescendants : 1;
- quint32 pendingPolish : 1;
- quint32 mayHaveChildWithGraphicsEffect : 1;
- quint32 isDeclarativeItem : 1;
- quint32 sendParentChangeNotification : 1;
- quint32 padding : 21;
-
- // Optional stacking order
- int globalStackingOrder;
- QGraphicsItem *q_ptr;
-};
-
-struct QGraphicsItemPrivate::TransformData
-{
- QTransform transform;
- qreal scale;
- qreal rotation;
- qreal xOrigin;
- qreal yOrigin;
- QList<QGraphicsTransform *> graphicsTransforms;
- bool onlyTransform;
-
- TransformData() :
- scale(1.0), rotation(0.0),
- xOrigin(0.0), yOrigin(0.0),
- onlyTransform(true)
- { }
-
- QTransform computedFullTransform(QTransform *postmultiplyTransform = 0) const
- {
- if (onlyTransform) {
- if (!postmultiplyTransform || postmultiplyTransform->isIdentity())
- return transform;
- if (transform.isIdentity())
- return *postmultiplyTransform;
- return transform * *postmultiplyTransform;
- }
-
- QTransform x(transform);
- if (!graphicsTransforms.isEmpty()) {
- QMatrix4x4 m;
- for (int i = 0; i < graphicsTransforms.size(); ++i)
- graphicsTransforms.at(i)->applyTo(&m);
- x *= m.toTransform();
- }
- x.translate(xOrigin, yOrigin);
- x.rotate(rotation);
- x.scale(scale, scale);
- x.translate(-xOrigin, -yOrigin);
- if (postmultiplyTransform)
- x *= *postmultiplyTransform;
- return x;
- }
-};
-
-struct QGraphicsItemPaintInfo
-{
- inline QGraphicsItemPaintInfo(const QTransform *const xform1, const QTransform *const xform2,
- const QTransform *const xform3,
- QRegion *r, QWidget *w, QStyleOptionGraphicsItem *opt,
- QPainter *p, qreal o, bool b1, bool b2)
- : viewTransform(xform1), transformPtr(xform2), effectTransform(xform3), exposedRegion(r), widget(w),
- option(opt), painter(p), opacity(o), wasDirtySceneTransform(b1), drawItem(b2)
- {}
-
- const QTransform *viewTransform;
- const QTransform *transformPtr;
- const QTransform *effectTransform;
- QRegion *exposedRegion;
- QWidget *widget;
- QStyleOptionGraphicsItem *option;
- QPainter *painter;
- qreal opacity;
- quint32 wasDirtySceneTransform : 1;
- quint32 drawItem : 1;
-};
-
-#ifndef QT_NO_GRAPHICSEFFECT
-class QGraphicsItemEffectSourcePrivate : public QGraphicsEffectSourcePrivate
-{
-public:
- QGraphicsItemEffectSourcePrivate(QGraphicsItem *i)
- : QGraphicsEffectSourcePrivate(), item(i), info(0)
- {}
-
- inline void detach()
- {
- item->d_ptr->graphicsEffect = 0;
- item->prepareGeometryChange();
- }
-
- inline const QGraphicsItem *graphicsItem() const
- { return item; }
-
- inline const QWidget *widget() const
- { return 0; }
-
- inline void update() {
- item->d_ptr->updateDueToGraphicsEffect = true;
- item->update();
- item->d_ptr->updateDueToGraphicsEffect = false;
- }
-
- inline void effectBoundingRectChanged()
- { item->prepareGeometryChange(); }
-
- inline bool isPixmap() const
- {
- return item->type() == QGraphicsPixmapItem::Type
- && !(item->flags() & QGraphicsItem::ItemIsSelectable)
- && item->d_ptr->children.size() == 0;
- //|| (item->d_ptr->isObject && qobject_cast<QDeclarativeImage *>(q_func()));
- }
-
- inline const QStyleOption *styleOption() const
- { return info ? info->option : 0; }
-
- inline QRect deviceRect() const
- {
- if (!info || !info->widget) {
- qWarning("QGraphicsEffectSource::deviceRect: Not yet implemented, lacking device context");
- return QRect();
- }
- return info->widget->rect();
- }
-
- QRectF boundingRect(Qt::CoordinateSystem system) const;
- void draw(QPainter *);
- QPixmap pixmap(Qt::CoordinateSystem system,
- QPoint *offset,
- QGraphicsEffect::PixmapPadMode mode) const;
- QRect paddedEffectRect(Qt::CoordinateSystem system, QGraphicsEffect::PixmapPadMode mode, const QRectF &sourceRect, bool *unpadded = 0) const;
-
- QGraphicsItem *item;
- QGraphicsItemPaintInfo *info;
- QTransform lastEffectTransform;
-};
-#endif //QT_NO_GRAPHICSEFFECT
-
-/*!
- Returns true if \a item1 is on top of \a item2.
- The items don't need to be siblings.
-
- \internal
-*/
-inline bool qt_closestItemFirst(const QGraphicsItem *item1, const QGraphicsItem *item2)
-{
- // Siblings? Just check their z-values.
- const QGraphicsItemPrivate *d1 = item1->d_ptr.data();
- const QGraphicsItemPrivate *d2 = item2->d_ptr.data();
- if (d1->parent == d2->parent)
- return qt_closestLeaf(item1, item2);
-
- // Find common ancestor, and each item's ancestor closest to the common
- // ancestor.
- int item1Depth = d1->depth();
- int item2Depth = d2->depth();
- const QGraphicsItem *p = item1;
- const QGraphicsItem *t1 = item1;
- while (item1Depth > item2Depth && (p = p->d_ptr->parent)) {
- if (p == item2) {
- // item2 is one of item1's ancestors; item1 is on top
- return !(t1->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
- }
- t1 = p;
- --item1Depth;
- }
- p = item2;
- const QGraphicsItem *t2 = item2;
- while (item2Depth > item1Depth && (p = p->d_ptr->parent)) {
- if (p == item1) {
- // item1 is one of item2's ancestors; item1 is not on top
- return (t2->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent);
- }
- t2 = p;
- --item2Depth;
- }
-
- // item1Ancestor is now at the same level as item2Ancestor, but not the same.
- const QGraphicsItem *p1 = t1;
- const QGraphicsItem *p2 = t2;
- while (t1 && t1 != t2) {
- p1 = t1;
- p2 = t2;
- t1 = t1->d_ptr->parent;
- t2 = t2->d_ptr->parent;
- }
-
- // in case we have a common ancestor, we compare the immediate children in the ancestor's path.
- // otherwise we compare the respective items' topLevelItems directly.
- return qt_closestLeaf(p1, p2);
-}
-
-/*!
- Returns true if \a item2 is on top of \a item1.
- The items don't need to be siblings.
-
- \internal
-*/
-inline bool qt_closestItemLast(const QGraphicsItem *item1, const QGraphicsItem *item2)
-{
- return qt_closestItemFirst(item2, item1);
-}
-
-/*!
- \internal
-*/
-inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
-{
- // Return true if sibling item1 is on top of item2.
- const QGraphicsItemPrivate *d1 = item1->d_ptr.data();
- const QGraphicsItemPrivate *d2 = item2->d_ptr.data();
- bool f1 = d1->flags & QGraphicsItem::ItemStacksBehindParent;
- bool f2 = d2->flags & QGraphicsItem::ItemStacksBehindParent;
- if (f1 != f2)
- return f2;
- if (d1->z != d2->z)
- return d1->z > d2->z;
- return d1->siblingIndex > d2->siblingIndex;
-}
-
-/*!
- \internal
-*/
-inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2)
-{ return qt_closestLeaf(item2, item1); }
-
-/*
- return the full transform of the item to the parent. This include the position and all the transform data
-*/
-inline QTransform QGraphicsItemPrivate::transformToParent() const
-{
- QTransform matrix;
- combineTransformToParent(&matrix);
- return matrix;
-}
-
-/*!
- \internal
-*/
-inline void QGraphicsItemPrivate::ensureSortedChildren()
-{
- if (needSortChildren) {
- needSortChildren = 0;
- sequentialOrdering = 1;
- if (children.isEmpty())
- return;
- qSort(children.begin(), children.end(), qt_notclosestLeaf);
- for (int i = 0; i < children.size(); ++i) {
- if (children.at(i)->d_ptr->siblingIndex != i) {
- sequentialOrdering = 0;
- break;
- }
- }
- }
-}
-
-/*!
- \internal
-*/
-inline bool QGraphicsItemPrivate::insertionOrder(QGraphicsItem *a, QGraphicsItem *b)
-{
- return a->d_ptr->siblingIndex < b->d_ptr->siblingIndex;
-}
-
-/*!
- \internal
-*/
-inline void QGraphicsItemPrivate::markParentDirty(bool updateBoundingRect)
-{
- QGraphicsItemPrivate *parentp = this;
-#ifndef QT_NO_GRAPHICSEFFECT
- if (updateBoundingRect && parentp->graphicsEffect && !parentp->inSetPosHelper) {
- parentp->notifyInvalidated = 1;
- static_cast<QGraphicsItemEffectSourcePrivate *>(parentp->graphicsEffect->d_func()
- ->source->d_func())->invalidateCache();
- }
-#endif
- while (parentp->parent) {
- parentp = parentp->parent->d_ptr.data();
- parentp->dirtyChildren = 1;
-
- if (updateBoundingRect) {
- parentp->dirtyChildrenBoundingRect = 1;
- // ### Only do this if the parent's effect applies to the entire subtree.
- parentp->notifyBoundingRectChanged = 1;
- }
-#ifndef QT_NO_GRAPHICSEFFECT
- if (parentp->graphicsEffect) {
- if (updateBoundingRect) {
- static_cast<QGraphicsItemEffectSourcePrivate *>(parentp->graphicsEffect->d_func()
- ->source->d_func())->invalidateCache();
- parentp->notifyInvalidated = 1;
- }
- if (parentp->scene && parentp->graphicsEffect->isEnabled()) {
- parentp->dirty = 1;
- parentp->fullUpdatePending = 1;
- }
- }
-#endif
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsitemanimation.cpp b/src/gui/graphicsview/qgraphicsitemanimation.cpp
deleted file mode 100644
index 7eedc8dd3d..0000000000
--- a/src/gui/graphicsview/qgraphicsitemanimation.cpp
+++ /dev/null
@@ -1,599 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsItemAnimation
- \brief The QGraphicsItemAnimation class provides simple animation
- support for QGraphicsItem.
- \since 4.2
- \ingroup graphicsview-api
- \deprecated
-
- The QGraphicsItemAnimation class animates a QGraphicsItem. You can
- schedule changes to the item's transformation matrix at
- specified steps. The QGraphicsItemAnimation class has a
- current step value. When this value changes the transformations
- scheduled at that step are performed. The current step of the
- animation is set with the \c setStep() function.
-
- QGraphicsItemAnimation will do a simple linear interpolation
- between the nearest adjacent scheduled changes to calculate the
- matrix. For instance, if you set the position of an item at values
- 0.0 and 1.0, the animation will show the item moving in a straight
- line between these positions. The same is true for scaling and
- rotation.
-
- It is usual to use the class with a QTimeLine. The timeline's
- \l{QTimeLine::}{valueChanged()} signal is then connected to the
- \c setStep() slot. For example, you can set up an item for rotation
- by calling \c setRotationAt() for different step values.
- The animations timeline is set with the setTimeLine() function.
-
- An example animation with a timeline follows:
-
- \snippet doc/src/snippets/timeline/main.cpp 0
-
- Note that steps lie between 0.0 and 1.0. It may be necessary to use
- \l{QTimeLine::}{setUpdateInterval()}. The default update interval
- is 40 ms. A scheduled transformation cannot be removed when set,
- so scheduling several transformations of the same kind (e.g.,
- rotations) at the same step is not recommended.
-
- \sa QTimeLine, {Graphics View Framework}
-*/
-
-#include "qgraphicsitemanimation.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicsitem.h"
-
-#include <QtCore/qtimeline.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qpointer.h>
-#include <QtCore/qpair.h>
-#include <QtGui/qmatrix.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsItemAnimationPrivate
-{
-public:
- inline QGraphicsItemAnimationPrivate()
- : q(0), timeLine(0), item(0), step(0)
- { }
-
- QGraphicsItemAnimation *q;
-
- QPointer<QTimeLine> timeLine;
- QGraphicsItem *item;
-
- QPointF startPos;
- QMatrix startMatrix;
-
- qreal step;
-
- struct Pair {
- Pair(qreal a, qreal b) : step(a), value(b) {}
- bool operator <(const Pair &other) const
- { return step < other.step; }
- bool operator==(const Pair &other) const
- { return step == other.step; }
- qreal step;
- qreal value;
- };
- QList<Pair> xPosition;
- QList<Pair> yPosition;
- QList<Pair> rotation;
- QList<Pair> verticalScale;
- QList<Pair> horizontalScale;
- QList<Pair> verticalShear;
- QList<Pair> horizontalShear;
- QList<Pair> xTranslation;
- QList<Pair> yTranslation;
-
- qreal linearValueForStep(qreal step, QList<Pair> *source, qreal defaultValue = 0);
- void insertUniquePair(qreal step, qreal value, QList<Pair> *binList, const char* method);
-};
-
-qreal QGraphicsItemAnimationPrivate::linearValueForStep(qreal step, QList<Pair> *source, qreal defaultValue)
-{
- if (source->isEmpty())
- return defaultValue;
- step = qMin<qreal>(qMax<qreal>(step, 0), 1);
-
- if (step == 1)
- return source->last().value;
-
- qreal stepBefore = 0;
- qreal stepAfter = 1;
- qreal valueBefore = source->first().step == 0 ? source->first().value : defaultValue;
- qreal valueAfter = source->last().value;
-
- // Find the closest step and value before the given step.
- for (int i = 0; i < source->size() && step >= source->at(i).step; ++i) {
- stepBefore = source->at(i).step;
- valueBefore = source->at(i).value;
- }
-
- // Find the closest step and value after the given step.
- for (int j = source->size() - 1; j >= 0 && step < source->at(j).step; --j) {
- stepAfter = source->at(j).step;
- valueAfter = source->at(j).value;
- }
-
- // Do a simple linear interpolation.
- return valueBefore + (valueAfter - valueBefore) * ((step - stepBefore) / (stepAfter - stepBefore));
-}
-
-void QGraphicsItemAnimationPrivate::insertUniquePair(qreal step, qreal value, QList<Pair> *binList, const char* method)
-{
- if (step < 0.0 || step > 1.0) {
- qWarning("QGraphicsItemAnimation::%s: invalid step = %f", method, step);
- return;
- }
-
- Pair pair(step, value);
-
- QList<Pair>::iterator result = qBinaryFind(binList->begin(), binList->end(), pair);
- if (result != binList->end())
- result->value = value;
- else {
- *binList << pair;
- qSort(binList->begin(), binList->end());
- }
-}
-
-/*!
- Constructs an animation object with the given \a parent.
-*/
-QGraphicsItemAnimation::QGraphicsItemAnimation(QObject *parent)
- : QObject(parent), d(new QGraphicsItemAnimationPrivate)
-{
- d->q = this;
-}
-
-/*!
- Destroys the animation object.
-*/
-QGraphicsItemAnimation::~QGraphicsItemAnimation()
-{
- delete d;
-}
-
-/*!
- Returns the item on which the animation object operates.
-
- \sa setItem()
-*/
-QGraphicsItem *QGraphicsItemAnimation::item() const
-{
- return d->item;
-}
-
-/*!
- Sets the specified \a item to be used in the animation.
-
- \sa item()
-*/
-void QGraphicsItemAnimation::setItem(QGraphicsItem *item)
-{
- d->item = item;
- d->startPos = d->item->pos();
-}
-
-/*!
- Returns the timeline object used to control the rate at which the animation
- occurs.
-
- \sa setTimeLine()
-*/
-QTimeLine *QGraphicsItemAnimation::timeLine() const
-{
- return d->timeLine;
-}
-
-/*!
- Sets the timeline object used to control the rate of animation to the \a timeLine
- specified.
-
- \sa timeLine()
-*/
-void QGraphicsItemAnimation::setTimeLine(QTimeLine *timeLine)
-{
- if (d->timeLine == timeLine)
- return;
- if (d->timeLine)
- delete d->timeLine;
- if (!timeLine)
- return;
- d->timeLine = timeLine;
- connect(timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(setStep(qreal)));
-}
-
-/*!
- Returns the position of the item at the given \a step value.
-
- \sa setPosAt()
-*/
-QPointF QGraphicsItemAnimation::posAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::posAt: invalid step = %f", step);
-
- return QPointF(d->linearValueForStep(step, &d->xPosition, d->startPos.x()),
- d->linearValueForStep(step, &d->yPosition, d->startPos.y()));
-}
-
-/*!
- \fn void QGraphicsItemAnimation::setPosAt(qreal step, const QPointF &point)
-
- Sets the position of the item at the given \a step value to the \a point specified.
-
- \sa posAt()
-*/
-void QGraphicsItemAnimation::setPosAt(qreal step, const QPointF &pos)
-{
- d->insertUniquePair(step, pos.x(), &d->xPosition, "setPosAt");
- d->insertUniquePair(step, pos.y(), &d->yPosition, "setPosAt");
-}
-
-/*!
- Returns all explicitly inserted positions.
-
- \sa posAt(), setPosAt()
-*/
-QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::posList() const
-{
- QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->xPosition.size(); ++i)
- list << QPair<qreal, QPointF>(d->xPosition.at(i).step, QPointF(d->xPosition.at(i).value, d->yPosition.at(i).value));
-
- return list;
-}
-
-/*!
- Returns the matrix used to transform the item at the specified \a step value.
-*/
-QMatrix QGraphicsItemAnimation::matrixAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::matrixAt: invalid step = %f", step);
-
- QMatrix matrix;
- if (!d->rotation.isEmpty())
- matrix.rotate(rotationAt(step));
- if (!d->verticalScale.isEmpty())
- matrix.scale(horizontalScaleAt(step), verticalScaleAt(step));
- if (!d->verticalShear.isEmpty())
- matrix.shear(horizontalShearAt(step), verticalShearAt(step));
- if (!d->xTranslation.isEmpty())
- matrix.translate(xTranslationAt(step), yTranslationAt(step));
- return matrix;
-}
-
-/*!
- Returns the angle at which the item is rotated at the specified \a step value.
-
- \sa setRotationAt()
-*/
-qreal QGraphicsItemAnimation::rotationAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::rotationAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->rotation);
-}
-
-/*!
- Sets the rotation of the item at the given \a step value to the \a angle specified.
-
- \sa rotationAt()
-*/
-void QGraphicsItemAnimation::setRotationAt(qreal step, qreal angle)
-{
- d->insertUniquePair(step, angle, &d->rotation, "setRotationAt");
-}
-
-/*!
- Returns all explicitly inserted rotations.
-
- \sa rotationAt(), setRotationAt()
-*/
-QList<QPair<qreal, qreal> > QGraphicsItemAnimation::rotationList() const
-{
- QList<QPair<qreal, qreal> > list;
- for (int i = 0; i < d->rotation.size(); ++i)
- list << QPair<qreal, qreal>(d->rotation.at(i).step, d->rotation.at(i).value);
-
- return list;
-}
-
-/*!
- Returns the horizontal translation of the item at the specified \a step value.
-
- \sa setTranslationAt()
-*/
-qreal QGraphicsItemAnimation::xTranslationAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::xTranslationAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->xTranslation);
-}
-
-/*!
- Returns the vertical translation of the item at the specified \a step value.
-
- \sa setTranslationAt()
-*/
-qreal QGraphicsItemAnimation::yTranslationAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::yTranslationAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->yTranslation);
-}
-
-/*!
- Sets the translation of the item at the given \a step value using the horizontal
- and vertical coordinates specified by \a dx and \a dy.
-
- \sa xTranslationAt(), yTranslationAt()
-*/
-void QGraphicsItemAnimation::setTranslationAt(qreal step, qreal dx, qreal dy)
-{
- d->insertUniquePair(step, dx, &d->xTranslation, "setTranslationAt");
- d->insertUniquePair(step, dy, &d->yTranslation, "setTranslationAt");
-}
-
-/*!
- Returns all explicitly inserted translations.
-
- \sa xTranslationAt(), yTranslationAt(), setTranslationAt()
-*/
-QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::translationList() const
-{
- QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->xTranslation.size(); ++i)
- list << QPair<qreal, QPointF>(d->xTranslation.at(i).step, QPointF(d->xTranslation.at(i).value, d->yTranslation.at(i).value));
-
- return list;
-}
-
-/*!
- Returns the vertical scale for the item at the specified \a step value.
-
- \sa setScaleAt()
-*/
-qreal QGraphicsItemAnimation::verticalScaleAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::verticalScaleAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->verticalScale, 1);
-}
-
-/*!
- Returns the horizontal scale for the item at the specified \a step value.
-
- \sa setScaleAt()
-*/
-qreal QGraphicsItemAnimation::horizontalScaleAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::horizontalScaleAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->horizontalScale, 1);
-}
-
-/*!
- Sets the scale of the item at the given \a step value using the horizontal and
- vertical scale factors specified by \a sx and \a sy.
-
- \sa verticalScaleAt(), horizontalScaleAt()
-*/
-void QGraphicsItemAnimation::setScaleAt(qreal step, qreal sx, qreal sy)
-{
- d->insertUniquePair(step, sx, &d->horizontalScale, "setScaleAt");
- d->insertUniquePair(step, sy, &d->verticalScale, "setScaleAt");
-}
-
-/*!
- Returns all explicitly inserted scales.
-
- \sa verticalScaleAt(), horizontalScaleAt(), setScaleAt()
-*/
-QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::scaleList() const
-{
- QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->horizontalScale.size(); ++i)
- list << QPair<qreal, QPointF>(d->horizontalScale.at(i).step, QPointF(d->horizontalScale.at(i).value, d->verticalScale.at(i).value));
-
- return list;
-}
-
-/*!
- Returns the vertical shear for the item at the specified \a step value.
-
- \sa setShearAt()
-*/
-qreal QGraphicsItemAnimation::verticalShearAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::verticalShearAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->verticalShear, 0);
-}
-
-/*!
- Returns the horizontal shear for the item at the specified \a step value.
-
- \sa setShearAt()
-*/
-qreal QGraphicsItemAnimation::horizontalShearAt(qreal step) const
-{
- if (step < 0.0 || step > 1.0)
- qWarning("QGraphicsItemAnimation::horizontalShearAt: invalid step = %f", step);
-
- return d->linearValueForStep(step, &d->horizontalShear, 0);
-}
-
-/*!
- Sets the shear of the item at the given \a step value using the horizontal and
- vertical shear factors specified by \a sh and \a sv.
-
- \sa verticalShearAt(), horizontalShearAt()
-*/
-void QGraphicsItemAnimation::setShearAt(qreal step, qreal sh, qreal sv)
-{
- d->insertUniquePair(step, sh, &d->horizontalShear, "setShearAt");
- d->insertUniquePair(step, sv, &d->verticalShear, "setShearAt");
-}
-
-/*!
- Returns all explicitly inserted shears.
-
- \sa verticalShearAt(), horizontalShearAt(), setShearAt()
-*/
-QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::shearList() const
-{
- QList<QPair<qreal, QPointF> > list;
- for (int i = 0; i < d->horizontalShear.size(); ++i)
- list << QPair<qreal, QPointF>(d->horizontalShear.at(i).step, QPointF(d->horizontalShear.at(i).value, d->verticalShear.at(i).value));
-
- return list;
-}
-
-/*!
- Clears the scheduled transformations used for the animation, but
- retains the item and timeline.
-*/
-void QGraphicsItemAnimation::clear()
-{
- d->xPosition.clear();
- d->yPosition.clear();
- d->rotation.clear();
- d->verticalScale.clear();
- d->horizontalScale.clear();
- d->verticalShear.clear();
- d->horizontalShear.clear();
- d->xTranslation.clear();
- d->yTranslation.clear();
-}
-
-/*!
- \fn void QGraphicsItemAnimation::setStep(qreal step)
-
- Sets the current \a step value for the animation, causing the
- transformations scheduled at this step to be performed.
-*/
-void QGraphicsItemAnimation::setStep(qreal x)
-{
- if (x < 0.0 || x > 1.0) {
- qWarning("QGraphicsItemAnimation::setStep: invalid step = %f", x);
- return;
- }
-
- beforeAnimationStep(x);
-
- d->step = x;
- if (d->item) {
- if (!d->xPosition.isEmpty() || !d->yPosition.isEmpty())
- d->item->setPos(posAt(x));
- if (!d->rotation.isEmpty()
- || !d->verticalScale.isEmpty()
- || !d->horizontalScale.isEmpty()
- || !d->verticalShear.isEmpty()
- || !d->horizontalShear.isEmpty()
- || !d->xTranslation.isEmpty()
- || !d->yTranslation.isEmpty()) {
- d->item->setMatrix(d->startMatrix * matrixAt(x));
- }
- }
-
- afterAnimationStep(x);
-}
-
-/*!
- Resets the item to its starting position and transformation.
-
- \obsolete
-
- You can call setStep(0) instead.
-*/
-void QGraphicsItemAnimation::reset()
-{
- if (!d->item)
- return;
- d->startPos = d->item->pos();
- d->startMatrix = d->item->matrix();
-}
-
-/*!
- \fn void QGraphicsItemAnimation::beforeAnimationStep(qreal step)
-
- This method is meant to be overridden by subclassed that needs to
- execute additional code before a new step takes place. The
- animation \a step is provided for use in cases where the action
- depends on its value.
-*/
-void QGraphicsItemAnimation::beforeAnimationStep(qreal step)
-{
- Q_UNUSED(step);
-}
-
-/*!
- \fn void QGraphicsItemAnimation::afterAnimationStep(qreal step)
-
- This method is meant to be overridden in subclasses that need to
- execute additional code after a new step has taken place. The
- animation \a step is provided for use in cases where the action
- depends on its value.
-*/
-void QGraphicsItemAnimation::afterAnimationStep(qreal step)
-{
- Q_UNUSED(step);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsitemanimation.h b/src/gui/graphicsview/qgraphicsitemanimation.h
deleted file mode 100644
index 5dfbf4b81e..0000000000
--- a/src/gui/graphicsview/qgraphicsitemanimation.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSITEMANIMATION_H
-#define QGRAPHICSITEMANIMATION_H
-
-#include <QtCore/qobject.h>
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QGraphicsItem;
-class QMatrix;
-class QPointF;
-class QTimeLine;
-template <class T1, class T2> struct QPair;
-
-class QGraphicsItemAnimationPrivate;
-class Q_GUI_EXPORT QGraphicsItemAnimation : public QObject
-{
- Q_OBJECT
-public:
- QGraphicsItemAnimation(QObject *parent = 0);
- virtual ~QGraphicsItemAnimation();
-
- QGraphicsItem *item() const;
- void setItem(QGraphicsItem *item);
-
- QTimeLine *timeLine() const;
- void setTimeLine(QTimeLine *timeLine);
-
- QPointF posAt(qreal step) const;
- QList<QPair<qreal, QPointF> > posList() const;
- void setPosAt(qreal step, const QPointF &pos);
-
- QMatrix matrixAt(qreal step) const;
-
- qreal rotationAt(qreal step) const;
- QList<QPair<qreal, qreal> > rotationList() const;
- void setRotationAt(qreal step, qreal angle);
-
- qreal xTranslationAt(qreal step) const;
- qreal yTranslationAt(qreal step) const;
- QList<QPair<qreal, QPointF> > translationList() const;
- void setTranslationAt(qreal step, qreal dx, qreal dy);
-
- qreal verticalScaleAt(qreal step) const;
- qreal horizontalScaleAt(qreal step) const;
- QList<QPair<qreal, QPointF> > scaleList() const;
- void setScaleAt(qreal step, qreal sx, qreal sy);
-
- qreal verticalShearAt(qreal step) const;
- qreal horizontalShearAt(qreal step) const;
- QList<QPair<qreal, QPointF> > shearList() const;
- void setShearAt(qreal step, qreal sh, qreal sv);
-
- void clear();
-
-public Q_SLOTS:
- void setStep(qreal x);
- void reset();
-
-protected:
- virtual void beforeAnimationStep(qreal step);
- virtual void afterAnimationStep(qreal step);
-
-private:
- Q_DISABLE_COPY(QGraphicsItemAnimation)
- QGraphicsItemAnimationPrivate *d;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_GRAPHICSVIEW
-#endif
diff --git a/src/gui/graphicsview/qgraphicslayout.cpp b/src/gui/graphicsview/qgraphicslayout.cpp
deleted file mode 100644
index 904a3deda2..0000000000
--- a/src/gui/graphicsview/qgraphicslayout.cpp
+++ /dev/null
@@ -1,451 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-#include "qgraphicslayout.h"
-#include "qgraphicslayout_p.h"
-#include "qgraphicslayoutitem.h"
-#include "qgraphicslayoutitem_p.h"
-#include "qgraphicswidget.h"
-#include "qgraphicswidget_p.h"
-#include "qgraphicsscene.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QGraphicsLayout
- \brief The QGraphicsLayout class provides the base class for all layouts
- in Graphics View.
- \since 4.4
- \ingroup graphicsview-api
-
- QGraphicsLayout is an abstract class that defines a virtual API for
- arranging QGraphicsWidget children and other QGraphicsLayoutItem objects
- for a QGraphicsWidget. QGraphicsWidget assigns responsibility to a
- QGraphicsLayout through QGraphicsWidget::setLayout(). As the widget
- is resized, the layout will automatically arrange the widget's children.
- QGraphicsLayout inherits QGraphicsLayoutItem, so, it can be managed by
- any layout, including its own subclasses.
-
- \section1 Writing a Custom Layout
-
- You can use QGraphicsLayout as a base to write your own custom layout
- (e.g., a flowlayout), but it is more common to use one of its subclasses
- instead - QGraphicsLinearLayout or QGraphicsGridLayout. When creating
- a custom layout, the following functions must be reimplemented as a bare
- minimum:
-
- \table
- \header \o Function \o Description
- \row \o QGraphicsLayoutItem::setGeometry()
- \o Notifies you when the geometry of the layout is set. You can
- store the geometry in your own layout class in a reimplementation
- of this function.
- \row \o QGraphicsLayoutItem::sizeHint()
- \o Returns the layout's size hints.
- \row \o QGraphicsLayout::count()
- \o Returns the number of items in your layout.
- \row \o QGraphicsLayout::itemAt()
- \o Returns a pointer to an item in your layout.
- \row \o QGraphicsLayout::removeAt()
- \o Removes an item from your layout without destroying it.
- \endtable
-
- For more details on how to implement each function, refer to the individual
- function documentation.
-
- Each layout defines its own API for arranging widgets and layout items.
- For example, with a grid layout, you require a row and a
- column index with optional row and column spans, alignment, spacing, and more.
- A linear layout, however, requires a single row or column index to position its
- items. For a grid layout, the order of insertion does not affect the layout in
- any way, but for a linear layout, the order is essential. When writing your own
- layout subclass, you are free to choose the API that best suits your layout.
-
- \section1 Activating the Layout
-
- When the layout's geometry changes, QGraphicsLayout immediately rearranges
- all of its managed items by calling setGeometry() on each item. This
- rearrangement is called \e activating the layout.
-
- QGraphicsLayout updates its own geometry to match the contentsRect() of the
- QGraphicsLayoutItem it is managing. Thus, it will automatically rearrange all
- its items when the widget is resized. QGraphicsLayout caches the sizes of all
- its managed items to avoid calling setGeometry() too often.
-
- \note A QGraphicsLayout will have the same geometry as the contentsRect()
- of the widget (not the layout) it is assigned to.
-
- \section2 Activating the Layout Implicitly
-
- The layout can be activated implicitly using one of two ways: by calling
- activate() or by calling invalidate(). Calling activate() activates the layout
- immediately. In contrast, calling invalidate() is delayed, as it posts a
- \l{QEvent::LayoutRequest}{LayoutRequest} event to the managed widget. Due
- to event compression, the activate() will only be called once after control has
- returned to the event loop. This is referred to as \e invalidating the layout.
- Invalidating the layout also invalidates any cached information. Also, the
- invalidate() function is a virtual function. So, you can invalidate your own
- cache in a subclass of QGraphicsLayout by reimplementing this function.
-
- \section1 Event Handling
-
- QGraphicsLayout listens to events for the widget it manages through the
- virtual widgetEvent() event handler. When the layout is assigned to a
- widget, all events delivered to the widget are first processed by
- widgetEvent(). This allows the layout to be aware of any relevant state
- changes on the widget such as visibility changes or layout direction changes.
-
- \section1 Margin Handling
-
- The margins of a QGraphicsLayout can be modified by reimplementing
- setContentsMargins() and getContentsMargins().
-
-*/
-
-/*!
- Contructs a QGraphicsLayout object.
-
- \a parent is passed to QGraphicsLayoutItem's constructor and the
- QGraphicsLayoutItem's isLayout argument is set to \e true.
-
- If \a parent is a QGraphicsWidget the layout will be installed
- on that widget. (Note that installing a layout will delete the old one
- installed.)
-*/
-QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutItem *parent)
- : QGraphicsLayoutItem(*new QGraphicsLayoutPrivate)
-{
- setParentLayoutItem(parent);
- if (parent && !parent->isLayout()) {
- // If a layout has a parent that is not a layout it must be a QGraphicsWidget.
- QGraphicsItem *itemParent = parent->graphicsItem();
- if (itemParent && itemParent->isWidget()) {
- static_cast<QGraphicsWidget *>(itemParent)->d_func()->setLayout_helper(this);
- } else {
- qWarning("QGraphicsLayout::QGraphicsLayout: Attempt to create a layout with a parent that is"
- " neither a QGraphicsWidget nor QGraphicsLayout");
- }
- }
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, QSizePolicy::DefaultType);
- setOwnedByLayout(true);
-}
-
-/*!
- \internal
-*/
-QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutPrivate &dd, QGraphicsLayoutItem *parent)
- : QGraphicsLayoutItem(dd)
-{
- setParentLayoutItem(parent);
- if (parent && !parent->isLayout()) {
- // If a layout has a parent that is not a layout it must be a QGraphicsWidget.
- QGraphicsItem *itemParent = parent->graphicsItem();
- if (itemParent && itemParent->isWidget()) {
- static_cast<QGraphicsWidget *>(itemParent)->d_func()->setLayout_helper(this);
- } else {
- qWarning("QGraphicsLayout::QGraphicsLayout: Attempt to create a layout with a parent that is"
- " neither a QGraphicsWidget nor QGraphicsLayout");
- }
- }
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, QSizePolicy::DefaultType);
- setOwnedByLayout(true);
-}
-
-/*!
- Destroys the QGraphicsLayout object.
-*/
-QGraphicsLayout::~QGraphicsLayout()
-{
-}
-
-/*!
- Sets the contents margins to \a left, \a top, \a right and \a bottom. The
- default contents margins for toplevel layouts are style dependent
- (by querying the pixelMetric for QStyle::PM_LayoutLeftMargin,
- QStyle::PM_LayoutTopMargin, QStyle::PM_LayoutRightMargin and
- QStyle::PM_LayoutBottomMargin).
-
- For sublayouts the default margins are 0.
-
- Changing the contents margins automatically invalidates the layout.
-
- \sa invalidate()
-*/
-void QGraphicsLayout::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom)
-{
- Q_D(QGraphicsLayout);
- if (d->left == left && d->top == top && d->right == right && d->bottom == bottom)
- return;
- d->left = left;
- d->right = right;
- d->top = top;
- d->bottom = bottom;
- invalidate();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsLayout::getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const
-{
- Q_D(const QGraphicsLayout);
- d->getMargin(left, d->left, QStyle::PM_LayoutLeftMargin);
- d->getMargin(top, d->top, QStyle::PM_LayoutTopMargin);
- d->getMargin(right, d->right, QStyle::PM_LayoutRightMargin);
- d->getMargin(bottom, d->bottom, QStyle::PM_LayoutBottomMargin);
-}
-
-/*!
- Activates the layout, causing all items in the layout to be immediately
- rearranged. This function is based on calling count() and itemAt(), and
- then calling setGeometry() on all items sequentially. When activated,
- the layout will adjust its geometry to its parent's contentsRect().
- The parent will then invalidate any layout of its own.
-
- If called in sequence or recursively, e.g., by one of the arranged items
- in response to being resized, this function will do nothing.
-
- Note that the layout is free to use geometry caching to optimize this
- process. To forcefully invalidate any such cache, you can call
- invalidate() before calling activate().
-
- \sa invalidate()
-*/
-void QGraphicsLayout::activate()
-{
- Q_D(QGraphicsLayout);
- if (d->activated)
- return;
-
- d->activateRecursive(this);
-
- // we don't call activate on a sublayout, but somebody might.
- // Therefore, we walk to the parentitem of the toplevel layout.
- QGraphicsLayoutItem *parentItem = this;
- while (parentItem && parentItem->isLayout())
- parentItem = parentItem->parentLayoutItem();
- if (!parentItem)
- return;
- Q_ASSERT(!parentItem->isLayout());
-
- setGeometry(parentItem->contentsRect()); // relayout children
-
- // ### bug, should be parentItem ?
- parentLayoutItem()->updateGeometry(); // bubble up; will set activated to false
- // ### too many resizes? maybe we should walk up the chain to the
- // ### top-level layouted layoutItem and call activate there.
-}
-
-/*!
- Returns true if the layout is currently being activated; otherwise,
- returns false. If the layout is being activated, this means that it is
- currently in the process of rearranging its items (i.e., the activate()
- function has been called, and has not yet returned).
-
- \sa activate(), invalidate()
-*/
-bool QGraphicsLayout::isActivated() const
-{
- Q_D(const QGraphicsLayout);
- return d->activated;
-}
-
-/*!
- Clears any cached geometry and size hint information in the layout, and
- posts a \l{QEvent::LayoutRequest}{LayoutRequest} event to the managed
- parent QGraphicsLayoutItem.
-
- \sa activate(), setGeometry()
-*/
-void QGraphicsLayout::invalidate()
-{
- // only mark layouts as invalid (activated = false) if we can post a LayoutRequest event.
- QGraphicsLayoutItem *layoutItem = this;
- while (layoutItem && layoutItem->isLayout()) {
- // we could call updateGeometry(), but what if that method
- // does not call the base implementation? In addition, updateGeometry()
- // does more than we need.
- layoutItem->d_func()->sizeHintCacheDirty = true;
- layoutItem->d_func()->sizeHintWithConstraintCacheDirty = true;
- layoutItem = layoutItem->parentLayoutItem();
- }
- if (layoutItem) {
- layoutItem->d_func()->sizeHintCacheDirty = true;
- layoutItem->d_func()->sizeHintWithConstraintCacheDirty = true;
- }
-
- bool postIt = layoutItem ? !layoutItem->isLayout() : false;
- if (postIt) {
- layoutItem = this;
- while (layoutItem && layoutItem->isLayout()
- && static_cast<QGraphicsLayout*>(layoutItem)->d_func()->activated) {
- static_cast<QGraphicsLayout*>(layoutItem)->d_func()->activated = false;
- layoutItem = layoutItem->parentLayoutItem();
- }
- if (layoutItem && !layoutItem->isLayout()) {
- // If a layout has a parent that is not a layout it must be a QGraphicsWidget.
- QApplication::postEvent(static_cast<QGraphicsWidget *>(layoutItem), new QEvent(QEvent::LayoutRequest));
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QGraphicsLayout::updateGeometry()
-{
- QGraphicsLayoutItem::updateGeometry();
- if (QGraphicsLayoutItem *parentItem = parentLayoutItem()) {
- if (parentItem->isLayout()) {
- parentItem->updateGeometry();
- } else {
- invalidate();
- }
- }
-}
-
-/*!
- This virtual event handler receives all events for the managed
- widget. QGraphicsLayout uses this event handler to listen for layout
- related events such as geometry changes, layout changes or layout
- direction changes.
-
- \a e is a pointer to the event.
-
- You can reimplement this event handler to track similar events for your
- own custom layout.
-
- \sa QGraphicsWidget::event(), QGraphicsItem::sceneEvent()
-*/
-void QGraphicsLayout::widgetEvent(QEvent *e)
-{
- switch (e->type()) {
- case QEvent::GraphicsSceneResize:
- if (isActivated()) {
- setGeometry(parentLayoutItem()->contentsRect());
- } else {
- activate(); // relies on that activate() will call updateGeometry()
- }
- break;
- case QEvent::LayoutRequest:
- activate();
- break;
- case QEvent::LayoutDirectionChange:
- invalidate();
- break;
- default:
- break;
- }
-}
-
-/*!
- \fn virtual int QGraphicsLayout::count() const = 0
-
- This pure virtual function must be reimplemented in a subclass of
- QGraphicsLayout to return the number of items in the layout.
-
- The subclass is free to decide how to store the items.
-
- \sa itemAt(), removeAt()
-*/
-
-/*!
- \fn virtual QGraphicsLayoutItem *QGraphicsLayout::itemAt(int i) const = 0
-
- This pure virtual function must be reimplemented in a subclass of
- QGraphicsLayout to return a pointer to the item at index \a i. The
- reimplementation can assume that \a i is valid (i.e., it respects the
- value of count()).
- Together with count(), it is provided as a means of iterating over all items in a layout.
-
- The subclass is free to decide how to store the items, and the visual arrangement
- does not have to be reflected through this function.
-
- \sa count(), removeAt()
-*/
-
-/*!
- \fn virtual void QGraphicsLayout::removeAt(int index) = 0
-
- This pure virtual function must be reimplemented in a subclass of
- QGraphicsLayout to remove the item at \a index. The
- reimplementation can assume that \a index is valid (i.e., it
- respects the value of count()).
-
- The implementation must ensure that the parentLayoutItem() of
- the removed item does not point to this layout, since the item is
- considered to be removed from the layout hierarchy.
-
- If the layout is to be reused between applications, we recommend
- that the layout deletes the item, but the graphics view framework
- does not depend on this.
-
- The subclass is free to decide how to store the items.
-
- \sa itemAt(), count()
-*/
-
-/*!
- \since 4.6
-
- This function is a convenience function provided for custom layouts, and will go through
- all items in the layout and reparent their graphics items to the closest QGraphicsWidget
- ancestor of the layout.
-
- If \a layoutItem is already in a different layout, it will be removed from that layout.
-
- If custom layouts want special behaviour they can ignore to use this function, and implement
- their own behaviour.
-
- \sa graphicsItem()
- */
-void QGraphicsLayout::addChildLayoutItem(QGraphicsLayoutItem *layoutItem)
-{
- Q_D(QGraphicsLayout);
- d->addChildLayoutItem(layoutItem);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicslayout.h b/src/gui/graphicsview/qgraphicslayout.h
deleted file mode 100644
index c622fb881e..0000000000
--- a/src/gui/graphicsview/qgraphicslayout.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSLAYOUT_H
-#define QGRAPHICSLAYOUT_H
-
-#include <QtGui/qgraphicslayoutitem.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsLayoutPrivate;
-class QGraphicsLayoutItem;
-class QGraphicsWidget;
-
-class Q_GUI_EXPORT QGraphicsLayout : public QGraphicsLayoutItem
-{
-public:
- QGraphicsLayout(QGraphicsLayoutItem *parent = 0);
- ~QGraphicsLayout();
-
- void setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
- void getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const;
-
- void activate();
- bool isActivated() const;
- virtual void invalidate();
- virtual void updateGeometry();
-
- virtual void widgetEvent(QEvent *e);
-
- virtual int count() const = 0;
- virtual QGraphicsLayoutItem *itemAt(int i) const = 0;
- virtual void removeAt(int index) = 0;
-
-protected:
- QGraphicsLayout(QGraphicsLayoutPrivate &, QGraphicsLayoutItem *);
- void addChildLayoutItem(QGraphicsLayoutItem *layoutItem);
-
-private:
- Q_DISABLE_COPY(QGraphicsLayout)
- Q_DECLARE_PRIVATE(QGraphicsLayout)
- friend class QGraphicsWidget;
-};
-
-Q_DECLARE_INTERFACE(QGraphicsLayout, "com.trolltech.Qt.QGraphicsLayout")
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
-
diff --git a/src/gui/graphicsview/qgraphicslayout_p.cpp b/src/gui/graphicsview/qgraphicslayout_p.cpp
deleted file mode 100644
index c325602cc6..0000000000
--- a/src/gui/graphicsview/qgraphicslayout_p.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicslayout_p.h"
-#include "qgraphicslayout.h"
-#include "qgraphicswidget.h"
-#include "qapplication.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
-
- \a mw is the new parent. all items in the layout will be a child of \a mw.
- */
-void QGraphicsLayoutPrivate::reparentChildItems(QGraphicsItem *newParent)
-{
- Q_Q(QGraphicsLayout);
- int n = q->count();
- //bool mwVisible = mw && mw->isVisible();
- for (int i = 0; i < n; ++i) {
- QGraphicsLayoutItem *layoutChild = q->itemAt(i);
- if (!layoutChild) {
- // Skip stretch items
- continue;
- }
- if (layoutChild->isLayout()) {
- QGraphicsLayout *l = static_cast<QGraphicsLayout*>(layoutChild);
- l->d_func()->reparentChildItems(newParent);
- } else if (QGraphicsItem *itemChild = layoutChild->graphicsItem()){
- QGraphicsItem *childParent = itemChild->parentItem();
-#ifdef QT_DEBUG
- if (childParent && childParent != newParent && itemChild->isWidget() && qt_graphicsLayoutDebug()) {
- QGraphicsWidget *w = static_cast<QGraphicsWidget*>(layoutChild);
- qWarning("QGraphicsLayout::addChildLayout: widget %s \"%s\" in wrong parent; moved to correct parent",
- w->metaObject()->className(), w->objectName().toLocal8Bit().constData());
- }
-#endif
- if (childParent != newParent)
- itemChild->setParentItem(newParent);
- }
- }
-}
-
-void QGraphicsLayoutPrivate::getMargin(qreal *result, qreal userMargin, QStyle::PixelMetric pm) const
-{
- if (!result)
- return;
- Q_Q(const QGraphicsLayout);
-
- QGraphicsLayoutItem *parent = q->parentLayoutItem();
- if (userMargin >= 0.0) {
- *result = userMargin;
- } else if (!parent) {
- *result = 0.0;
- } else if (parent->isLayout()) { // sublayouts have 0 margin by default
- *result = 0.0;
- } else {
- *result = 0.0;
- if (QGraphicsItem *layoutParentItem = parentItem()) {
- if (layoutParentItem->isWidget())
- *result = (qreal)static_cast<QGraphicsWidget*>(layoutParentItem)->style()->pixelMetric(pm, 0);
- }
- }
-}
-
-Qt::LayoutDirection QGraphicsLayoutPrivate::visualDirection() const
-{
- if (QGraphicsItem *maybeWidget = parentItem()) {
- if (maybeWidget->isWidget())
- return static_cast<QGraphicsWidget*>(maybeWidget)->layoutDirection();
- }
- return QApplication::layoutDirection();
-}
-
-static bool removeLayoutItemFromLayout(QGraphicsLayout *lay, QGraphicsLayoutItem *layoutItem)
-{
- if (!lay)
- return false;
-
- for (int i = lay->count() - 1; i >= 0; --i) {
- QGraphicsLayoutItem *child = lay->itemAt(i);
- if (child && child->isLayout()) {
- if (removeLayoutItemFromLayout(static_cast<QGraphicsLayout*>(child), layoutItem))
- return true;
- } else if (child == layoutItem) {
- lay->removeAt(i);
- return true;
- }
- }
- return false;
-}
-
-/*!
- \internal
-
- This function is called from subclasses to add a layout item \a layoutItem
- to a layout.
-
- It takes care of automatically reparenting graphics items, if needed.
-
- If \a layoutItem is a is already in a layout, it will remove it from that layout.
-
-*/
-void QGraphicsLayoutPrivate::addChildLayoutItem(QGraphicsLayoutItem *layoutItem)
-{
- Q_Q(QGraphicsLayout);
- if (QGraphicsLayoutItem *maybeLayout = layoutItem->parentLayoutItem()) {
- if (maybeLayout->isLayout())
- removeLayoutItemFromLayout(static_cast<QGraphicsLayout*>(maybeLayout), layoutItem);
- }
- layoutItem->setParentLayoutItem(q);
- if (layoutItem->isLayout()) {
- if (QGraphicsItem *parItem = parentItem()) {
- static_cast<QGraphicsLayout*>(layoutItem)->d_func()->reparentChildItems(parItem);
- }
- } else {
- if (QGraphicsItem *item = layoutItem->graphicsItem()) {
- QGraphicsItem *newParent = parentItem();
- QGraphicsItem *oldParent = item->parentItem();
- if (oldParent == newParent || !newParent)
- return;
-
-#ifdef QT_DEBUG
- if (oldParent && item->isWidget()) {
- QGraphicsWidget *w = static_cast<QGraphicsWidget*>(item);
- qWarning("QGraphicsLayout::addChildLayoutItem: %s \"%s\" in wrong parent; moved to correct parent",
- w->metaObject()->className(), w->objectName().toLocal8Bit().constData());
- }
-#endif
-
- item->setParentItem(newParent);
- }
- }
-}
-
-void QGraphicsLayoutPrivate::activateRecursive(QGraphicsLayoutItem *item)
-{
- if (item->isLayout()) {
- QGraphicsLayout *layout = static_cast<QGraphicsLayout *>(item);
- if (layout->d_func()->activated)
- layout->invalidate();
-
- for (int i = layout->count() - 1; i >= 0; --i) {
- QGraphicsLayoutItem *childItem = layout->itemAt(i);
- if (childItem)
- activateRecursive(childItem);
- }
- layout->d_func()->activated = true;
- }
-}
-
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicslayout_p.h b/src/gui/graphicsview/qgraphicslayout_p.h
deleted file mode 100644
index 5358ec3cf4..0000000000
--- a/src/gui/graphicsview/qgraphicslayout_p.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSLAYOUT_P_H
-#define QGRAPHICSLAYOUT_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 <QtCore/qglobal.h>
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-#include "qgraphicslayout.h"
-#include "qgraphicslayoutitem_p.h"
-#include <QtGui/qstyle.h>
-#include <QtGui/qwidget.h>
-#include <QtGui/qstyleoption.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsLayoutItem;
-class QGraphicsWidget;
-
-#ifdef QT_DEBUG
-inline bool qt_graphicsLayoutDebug()
-{
- static int checked_env = -1;
- if(checked_env == -1)
- checked_env = !!qgetenv("QT_GRAPHICSLAYOUT_DEBUG").toInt();
- return checked_env;
-}
-#endif
-
-
-class QLayoutStyleInfo
-{
-public:
- inline QLayoutStyleInfo() { invalidate(); }
- inline QLayoutStyleInfo(QStyle *style, QWidget *widget)
- : m_valid(true), m_style(style), m_widget(widget)
- {
- Q_ASSERT(style);
- if (widget) //###
- m_styleOption.initFrom(widget);
- m_defaultSpacing[0] = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing);
- m_defaultSpacing[1] = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing);
- }
-
- inline void invalidate() { m_valid = false; m_style = 0; m_widget = 0; }
-
- inline QStyle *style() const { return m_style; }
- inline QWidget *widget() const { return m_widget; }
-
- inline bool operator==(const QLayoutStyleInfo &other)
- { return m_style == other.m_style && m_widget == other.m_widget; }
- inline bool operator!=(const QLayoutStyleInfo &other)
- { return !(*this == other); }
-
- inline void setDefaultSpacing(Qt::Orientation o, qreal spacing){
- if (spacing >= 0)
- m_defaultSpacing[o - 1] = spacing;
- }
-
- inline qreal defaultSpacing(Qt::Orientation o) const {
- return m_defaultSpacing[o - 1];
- }
-
- inline qreal perItemSpacing(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation) const
- {
- Q_ASSERT(style());
- return style()->layoutSpacing(control1, control2, orientation, &m_styleOption, widget());
- }
-private:
- bool m_valid;
- QStyle *m_style;
- QWidget *m_widget;
- QStyleOption m_styleOption;
- qreal m_defaultSpacing[2];
-};
-
-class Q_AUTOTEST_EXPORT QGraphicsLayoutPrivate : public QGraphicsLayoutItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsLayout)
-
-public:
- QGraphicsLayoutPrivate() : QGraphicsLayoutItemPrivate(0, true), left(-1.0), top(-1.0), right(-1.0), bottom(-1.0),
- activated(true) { }
-
- void reparentChildItems(QGraphicsItem *newParent);
- void getMargin(qreal *result, qreal userMargin, QStyle::PixelMetric pm) const;
- Qt::LayoutDirection visualDirection() const;
-
- void addChildLayoutItem(QGraphicsLayoutItem *item);
- void activateRecursive(QGraphicsLayoutItem *item);
-
- qreal left, top, right, bottom;
- bool activated;
-};
-
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicslayoutitem.cpp b/src/gui/graphicsview/qgraphicslayoutitem.cpp
deleted file mode 100644
index c064e01502..0000000000
--- a/src/gui/graphicsview/qgraphicslayoutitem.cpp
+++ /dev/null
@@ -1,935 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicslayout.h"
-#include "qgraphicsscene.h"
-#include "qgraphicslayoutitem.h"
-#include "qgraphicslayoutitem_p.h"
-#include "qwidget.h"
-#include "qgraphicswidget.h"
-
-#include <QtDebug>
-
-QT_BEGIN_NAMESPACE
-
-/*
- COMBINE_SIZE() is identical to combineSize(), except that it
- doesn't evaluate 'size' unless necessary.
-*/
-#define COMBINE_SIZE(result, size) \
- do { \
- if ((result).width() < 0 || (result).height() < 0) \
- combineSize((result), (size)); \
- } while (false)
-
-static void combineSize(QSizeF &result, const QSizeF &size)
-{
- if (result.width() < 0)
- result.setWidth(size.width());
- if (result.height() < 0)
- result.setHeight(size.height());
-}
-
-static void boundSize(QSizeF &result, const QSizeF &size)
-{
- if (size.width() >= 0 && size.width() < result.width())
- result.setWidth(size.width());
- if (size.height() >= 0 && size.height() < result.height())
- result.setHeight(size.height());
-}
-
-static void expandSize(QSizeF &result, const QSizeF &size)
-{
- if (size.width() >= 0 && size.width() > result.width())
- result.setWidth(size.width());
- if (size.height() >= 0 && size.height() > result.height())
- result.setHeight(size.height());
-}
-
-static void normalizeHints(qreal &minimum, qreal &preferred, qreal &maximum, qreal &descent)
-{
- if (minimum >= 0 && maximum >= 0 && minimum > maximum)
- minimum = maximum;
-
- if (preferred >= 0) {
- if (minimum >= 0 && preferred < minimum) {
- preferred = minimum;
- } else if (maximum >= 0 && preferred > maximum) {
- preferred = maximum;
- }
- }
-
- if (minimum >= 0 && descent > minimum)
- descent = minimum;
-}
-
-/*!
- \internal
-*/
-QGraphicsLayoutItemPrivate::QGraphicsLayoutItemPrivate(QGraphicsLayoutItem *par, bool layout)
- : parent(par), userSizeHints(0), isLayout(layout), ownedByLayout(false), graphicsItem(0)
-{
-}
-
-/*!
- \internal
-*/
-QGraphicsLayoutItemPrivate::~QGraphicsLayoutItemPrivate()
-{
- // Remove any lazily allocated data
- delete[] userSizeHints;
-}
-
-/*!
- \internal
-*/
-void QGraphicsLayoutItemPrivate::init()
-{
- sizeHintCacheDirty = true;
- sizeHintWithConstraintCacheDirty = true;
-}
-
-/*!
- \internal
-*/
-QSizeF *QGraphicsLayoutItemPrivate::effectiveSizeHints(const QSizeF &constraint) const
-{
- Q_Q(const QGraphicsLayoutItem);
- QSizeF *sizeHintCache;
- const bool hasConstraint = constraint.width() >= 0 || constraint.height() >= 0;
- if (hasConstraint) {
- if (!sizeHintWithConstraintCacheDirty && constraint == cachedConstraint)
- return cachedSizeHintsWithConstraints;
- sizeHintCache = cachedSizeHintsWithConstraints;
- } else {
- if (!sizeHintCacheDirty)
- return cachedSizeHints;
- sizeHintCache = cachedSizeHints;
- }
-
- for (int i = 0; i < Qt::NSizeHints; ++i) {
- sizeHintCache[i] = constraint;
- if (userSizeHints)
- combineSize(sizeHintCache[i], userSizeHints[i]);
- }
-
- QSizeF &minS = sizeHintCache[Qt::MinimumSize];
- QSizeF &prefS = sizeHintCache[Qt::PreferredSize];
- QSizeF &maxS = sizeHintCache[Qt::MaximumSize];
- QSizeF &descentS = sizeHintCache[Qt::MinimumDescent];
-
- normalizeHints(minS.rwidth(), prefS.rwidth(), maxS.rwidth(), descentS.rwidth());
- normalizeHints(minS.rheight(), prefS.rheight(), maxS.rheight(), descentS.rheight());
-
- // if the minimum, preferred and maximum sizes contradict each other
- // (e.g. the minimum is larger than the maximum) we give priority to
- // the maximum size, then the minimum size and finally the preferred size
- COMBINE_SIZE(maxS, q->sizeHint(Qt::MaximumSize, maxS));
- combineSize(maxS, QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
- expandSize(maxS, prefS);
- expandSize(maxS, minS);
- boundSize(maxS, QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
-
- COMBINE_SIZE(minS, q->sizeHint(Qt::MinimumSize, minS));
- expandSize(minS, QSizeF(0, 0));
- boundSize(minS, prefS);
- boundSize(minS, maxS);
-
- COMBINE_SIZE(prefS, q->sizeHint(Qt::PreferredSize, prefS));
- expandSize(prefS, minS);
- boundSize(prefS, maxS);
-
- // Not supported yet
- // COMBINE_SIZE(descentS, q->sizeHint(Qt::MinimumDescent, constraint));
-
- if (hasConstraint) {
- cachedConstraint = constraint;
- sizeHintWithConstraintCacheDirty = false;
- } else {
- sizeHintCacheDirty = false;
- }
- return sizeHintCache;
-}
-
-
-/*!
- \internal
-
- Returns the parent item of this layout, or 0 if this layout is
- not installed on any widget.
-
- If this is the item that the layout is installed on, it will return "itself".
-
- If the layout is a sub-layout, this function returns the parent
- widget of the parent layout.
-
- Note that it will traverse up the layout item hierarchy instead of just calling
- QGraphicsItem::parentItem(). This is on purpose.
-
- \sa parent()
-*/
-QGraphicsItem *QGraphicsLayoutItemPrivate::parentItem() const
-{
- Q_Q(const QGraphicsLayoutItem);
-
- const QGraphicsLayoutItem *parent = q;
- while (parent && parent->isLayout()) {
- parent = parent->parentLayoutItem();
- }
- return parent ? parent->graphicsItem() : 0;
-}
-
-/*!
- \internal
-
- Ensures that userSizeHints is allocated.
- This function must be called before any dereferencing.
-*/
-void QGraphicsLayoutItemPrivate::ensureUserSizeHints()
-{
- if (!userSizeHints)
- userSizeHints = new QSizeF[Qt::NSizeHints];
-}
-
-/*!
- \internal
-
- Sets the user size hint \a which to \a size. Use an invalid size to unset the size hint.
- */
-void QGraphicsLayoutItemPrivate::setSize(Qt::SizeHint which, const QSizeF &size)
-{
- Q_Q(QGraphicsLayoutItem);
-
- if (userSizeHints) {
- if (size == userSizeHints[which])
- return;
- } else if (size.width() < 0 && size.height() < 0) {
- return;
- }
-
- ensureUserSizeHints();
- userSizeHints[which] = size;
- q->updateGeometry();
-}
-
-/*!
- \internal
-
- Sets the width of the user size hint \a which to \a width.
- */
-void QGraphicsLayoutItemPrivate::setSizeComponent(
- Qt::SizeHint which, SizeComponent component, qreal value)
-{
- Q_Q(QGraphicsLayoutItem);
- ensureUserSizeHints();
- qreal &userValue = (component == Width)
- ? userSizeHints[which].rwidth()
- : userSizeHints[which].rheight();
- if (value == userValue)
- return;
- userValue = value;
- q->updateGeometry();
-}
-
-
-bool QGraphicsLayoutItemPrivate::hasHeightForWidth() const
-{
- Q_Q(const QGraphicsLayoutItem);
- if (isLayout) {
- const QGraphicsLayout *l = static_cast<const QGraphicsLayout *>(q);
- for (int i = l->count() - 1; i >= 0; --i) {
- if (QGraphicsLayoutItemPrivate::get(l->itemAt(i))->hasHeightForWidth())
- return true;
- }
- } else if (QGraphicsItem *item = q->graphicsItem()) {
- if (item->isWidget()) {
- QGraphicsWidget *w = static_cast<QGraphicsWidget *>(item);
- if (w->layout()) {
- return QGraphicsLayoutItemPrivate::get(w->layout())->hasHeightForWidth();
- }
- }
- }
- return q->sizePolicy().hasHeightForWidth();
-}
-
-bool QGraphicsLayoutItemPrivate::hasWidthForHeight() const
-{
- Q_Q(const QGraphicsLayoutItem);
- if (isLayout) {
- const QGraphicsLayout *l = static_cast<const QGraphicsLayout *>(q);
- for (int i = l->count() - 1; i >= 0; --i) {
- if (QGraphicsLayoutItemPrivate::get(l->itemAt(i))->hasWidthForHeight())
- return true;
- }
- } else if (QGraphicsItem *item = q->graphicsItem()) {
- if (item->isWidget()) {
- QGraphicsWidget *w = static_cast<QGraphicsWidget *>(item);
- if (w->layout()) {
- return QGraphicsLayoutItemPrivate::get(w->layout())->hasWidthForHeight();
- }
- }
- }
- return q->sizePolicy().hasWidthForHeight();
-}
-
-/*!
- \class QGraphicsLayoutItem
- \brief The QGraphicsLayoutItem class can be inherited to allow your custom
- items to be managed by layouts.
- \since 4.4
- \ingroup graphicsview-api
-
- QGraphicsLayoutItem is an abstract class that defines a set of virtual
- functions describing sizes, size policies, and size hints for any object
- arranged by QGraphicsLayout. The API contains functions relevant
- for both the item itself and for the user of the item as most of
- QGraphicsLayoutItem's functions are also part of the subclass' public API.
-
- In most cases, existing layout-aware classes such as QGraphicsWidget and
- QGraphicsLayout already provide the functionality you require. However,
- subclassing these classes will enable you to create both graphical
- elements that work well with layouts (QGraphicsWidget) or custom layouts
- (QGraphicsLayout).
-
- \section1 Subclassing QGraphicsLayoutItem
-
- If you create a subclass of QGraphicsLayoutItem and reimplement its
- virtual functions, you will enable the layout to resize and position your
- item along with other QGraphicsLayoutItems including QGraphicsWidget
- and QGraphicsLayout.
-
- You can start by reimplementing important functions: the protected
- sizeHint() function, as well as the public setGeometry()
- function. If you want your items to be aware of immediate geometry
- changes, you can also reimplement updateGeometry().
-
- The geometry, size hint, and size policy affect the item's size and
- position. Calling setGeometry() will always resize and reposition the item
- immediately. Normally, this function is called by QGraphicsLayout after
- the layout has been activated, but it can also be called by the item's user
- at any time.
-
- The sizeHint() function returns the item' minimum, preferred and maximum
- size hints. You can override these properties by calling setMinimumSize(),
- setPreferredSize() or setMaximumSize(). You can also use functions such as
- setMinimumWidth() or setMaximumHeight() to set only the width or height
- component if desired.
-
- The effectiveSizeHint() function, on the other hand, returns a size hint
- for any given Qt::SizeHint, and guarantees that the returned size is bound
- to the minimum and maximum sizes and size hints. You can set the item's
- vertical and horizontal size policy by calling setSizePolicy(). The
- sizePolicy property is used by the layout system to describe how this item
- prefers to grow or shrink.
-
- \section1 Nesting QGraphicsLayoutItems
-
- QGraphicsLayoutItems can be nested within other QGraphicsLayoutItems,
- similar to layouts that can contain sublayouts. This is done either by
- passing a QGraphicsLayoutItem pointer to QGraphicsLayoutItem's
- protected constructor, or by calling setParentLayoutItem(). The
- parentLayoutItem() function returns a pointer to the item's layoutItem
- parent. If the item's parent is 0 or if the parent does not inherit
- from QGraphicsItem, the parentLayoutItem() function then returns 0.
- isLayout() returns true if the QGraphicsLayoutItem subclass is itself a
- layout, or false otherwise.
-
- Qt uses QGraphicsLayoutItem to provide layout functionality in the
- \l{Graphics View Framework}, but in the future its use may spread
- throughout Qt itself.
-
- \sa QGraphicsWidget, QGraphicsLayout, QGraphicsLinearLayout,
- QGraphicsGridLayout
-*/
-
-/*!
- Constructs the QGraphicsLayoutItem object. \a parent becomes the object's
- parent. If \a isLayout is true the item is a layout, otherwise
- \a isLayout is false.
-*/
-QGraphicsLayoutItem::QGraphicsLayoutItem(QGraphicsLayoutItem *parent, bool isLayout)
- : d_ptr(new QGraphicsLayoutItemPrivate(parent, isLayout))
-{
- Q_D(QGraphicsLayoutItem);
- d->init();
- d->sizePolicy = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
- d->q_ptr = this;
-}
-
-/*!
- \internal
-*/
-QGraphicsLayoutItem::QGraphicsLayoutItem(QGraphicsLayoutItemPrivate &dd)
- : d_ptr(&dd)
-{
- Q_D(QGraphicsLayoutItem);
- d->init();
- d->q_ptr = this;
-}
-
-/*!
- Destroys the QGraphicsLayoutItem object.
-*/
-QGraphicsLayoutItem::~QGraphicsLayoutItem()
-{
- QGraphicsLayoutItem *parentLI = parentLayoutItem();
- if (parentLI && parentLI->isLayout()) {
- QGraphicsLayout *lay = static_cast<QGraphicsLayout*>(parentLI);
- // this is not optimal
- for (int i = lay->count() - 1; i >= 0; --i) {
- if (lay->itemAt(i) == this) {
- lay->removeAt(i);
- break;
- }
- }
- }
-}
-
-/*!
- \fn virtual QSizeF QGraphicsLayoutItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const = 0;
-
- This pure virtual function returns the size hint for \a which of the
- QGraphicsLayoutItem, using the width or height of \a constraint to
- constrain the output.
-
- Reimplement this function in a subclass of QGraphicsLayoutItem to
- provide the necessary size hints for your items.
-
- \sa effectiveSizeHint()
-*/
-
-/*!
- Sets the size policy to \a policy. The size policy describes how the item
- should grow horizontally and vertically when arranged in a layout.
-
- QGraphicsLayoutItem's default size policy is (QSizePolicy::Fixed,
- QSizePolicy::Fixed, QSizePolicy::DefaultType), but it is common for
- subclasses to change the default. For example, QGraphicsWidget defaults
- to (QSizePolicy::Preferred, QSizePolicy::Preferred,
- QSizePolicy::DefaultType).
-
- \sa sizePolicy(), QWidget::sizePolicy()
-*/
-void QGraphicsLayoutItem::setSizePolicy(const QSizePolicy &policy)
-{
- Q_D(QGraphicsLayoutItem);
- if (d->sizePolicy == policy)
- return;
- d->sizePolicy = policy;
- updateGeometry();
-}
-
-/*!
- \overload
-
- This function is equivalent to calling
- setSizePolicy(QSizePolicy(\a hPolicy, \a vPolicy, \a controlType)).
-
- \sa sizePolicy(), QWidget::sizePolicy()
-*/
-void QGraphicsLayoutItem::setSizePolicy(QSizePolicy::Policy hPolicy,
- QSizePolicy::Policy vPolicy,
- QSizePolicy::ControlType controlType)
-{
- setSizePolicy(QSizePolicy(hPolicy, vPolicy, controlType));
-}
-
-/*!
- Returns the current size policy.
-
- \sa setSizePolicy(), QWidget::sizePolicy()
-*/
-QSizePolicy QGraphicsLayoutItem::sizePolicy() const
-{
- Q_D(const QGraphicsLayoutItem);
- return d->sizePolicy;
-}
-
-/*!
- Sets the minimum size to \a size. This property overrides sizeHint() for
- Qt::MinimumSize and ensures that effectiveSizeHint() will never return
- a size smaller than \a size. In order to unset the minimum size, use an
- invalid size.
-
- \sa minimumSize(), maximumSize(), preferredSize(), Qt::MinimumSize,
- sizeHint(), setMinimumWidth(), setMinimumHeight()
-*/
-void QGraphicsLayoutItem::setMinimumSize(const QSizeF &size)
-{
- d_ptr->setSize(Qt::MinimumSize, size);
-}
-
-/*!
- \fn QGraphicsLayoutItem::setMinimumSize(qreal w, qreal h)
-
- This convenience function is equivalent to calling
- setMinimumSize(QSizeF(\a w, \a h)).
-
- \sa minimumSize(), setMaximumSize(), setPreferredSize(), sizeHint()
-*/
-
-/*!
- Returns the minimum size.
-
- \sa setMinimumSize(), preferredSize(), maximumSize(), Qt::MinimumSize,
- sizeHint()
-*/
-QSizeF QGraphicsLayoutItem::minimumSize() const
-{
- return effectiveSizeHint(Qt::MinimumSize);
-}
-
-/*!
- Sets the minimum width to \a width.
-
- \sa minimumWidth(), setMinimumSize(), minimumSize()
-*/
-void QGraphicsLayoutItem::setMinimumWidth(qreal width)
-{
- d_ptr->setSizeComponent(Qt::MinimumSize, d_ptr->Width, width);
-}
-
-/*!
- Sets the minimum height to \a height.
-
- \sa minimumHeight(), setMinimumSize(), minimumSize()
-*/
-void QGraphicsLayoutItem::setMinimumHeight(qreal height)
-{
- d_ptr->setSizeComponent(Qt::MinimumSize, d_ptr->Height, height);
-}
-
-
-/*!
- Sets the preferred size to \a size. This property overrides sizeHint() for
- Qt::PreferredSize and provides the default value for effectiveSizeHint().
- In order to unset the preferred size, use an invalid size.
-
- \sa preferredSize(), minimumSize(), maximumSize(), Qt::PreferredSize,
- sizeHint()
-*/
-void QGraphicsLayoutItem::setPreferredSize(const QSizeF &size)
-{
- d_ptr->setSize(Qt::PreferredSize, size);
-}
-
-/*!
- \fn QGraphicsLayoutItem::setPreferredSize(qreal w, qreal h)
-
- This convenience function is equivalent to calling
- setPreferredSize(QSizeF(\a w, \a h)).
-
- \sa preferredSize(), setMaximumSize(), setMinimumSize(), sizeHint()
-*/
-
-/*!
- Returns the preferred size.
-
- \sa setPreferredSize(), minimumSize(), maximumSize(), Qt::PreferredSize,
- sizeHint()
-*/
-QSizeF QGraphicsLayoutItem::preferredSize() const
-{
- return effectiveSizeHint(Qt::PreferredSize);
-}
-
-/*!
- Sets the preferred height to \a height.
-
- \sa preferredWidth(), setPreferredSize(), preferredSize()
-*/
-void QGraphicsLayoutItem::setPreferredHeight(qreal height)
-{
- d_ptr->setSizeComponent(Qt::PreferredSize, d_ptr->Height, height);
-}
-
-/*!
- Sets the preferred width to \a width.
-
- \sa preferredHeight(), setPreferredSize(), preferredSize()
-*/
-void QGraphicsLayoutItem::setPreferredWidth(qreal width)
-{
- d_ptr->setSizeComponent(Qt::PreferredSize, d_ptr->Width, width);
-}
-
-/*!
- Sets the maximum size to \a size. This property overrides sizeHint() for
- Qt::MaximumSize and ensures that effectiveSizeHint() will never return a
- size larger than \a size. In order to unset the maximum size, use an
- invalid size.
-
- \sa maximumSize(), minimumSize(), preferredSize(), Qt::MaximumSize,
- sizeHint()
-*/
-void QGraphicsLayoutItem::setMaximumSize(const QSizeF &size)
-{
- d_ptr->setSize(Qt::MaximumSize, size);
-}
-
-/*!
- \fn QGraphicsLayoutItem::setMaximumSize(qreal w, qreal h)
-
- This convenience function is equivalent to calling
- setMaximumSize(QSizeF(\a w, \a h)).
-
- \sa maximumSize(), setMinimumSize(), setPreferredSize(), sizeHint()
-*/
-
-/*!
- Returns the maximum size.
-
- \sa setMaximumSize(), minimumSize(), preferredSize(), Qt::MaximumSize,
- sizeHint()
-*/
-QSizeF QGraphicsLayoutItem::maximumSize() const
-{
- return effectiveSizeHint(Qt::MaximumSize);
-}
-
-/*!
- Sets the maximum width to \a width.
-
- \sa maximumWidth(), setMaximumSize(), maximumSize()
-*/
-void QGraphicsLayoutItem::setMaximumWidth(qreal width)
-{
- d_ptr->setSizeComponent(Qt::MaximumSize, d_ptr->Width, width);
-}
-
-/*!
- Sets the maximum height to \a height.
-
- \sa maximumHeight(), setMaximumSize(), maximumSize()
-*/
-void QGraphicsLayoutItem::setMaximumHeight(qreal height)
-{
- d_ptr->setSizeComponent(Qt::MaximumSize, d_ptr->Height, height);
-}
-
-/*!
- \fn qreal QGraphicsLayoutItem::minimumWidth() const
-
- Returns the minimum width.
-
- \sa setMinimumWidth(), setMinimumSize(), minimumSize()
-*/
-
-/*!
- \fn qreal QGraphicsLayoutItem::minimumHeight() const
-
- Returns the minimum height.
-
- \sa setMinimumHeight(), setMinimumSize(), minimumSize()
-*/
-
-/*!
- \fn qreal QGraphicsLayoutItem::preferredWidth() const
-
- Returns the preferred width.
-
- \sa setPreferredWidth(), setPreferredSize(), preferredSize()
-*/
-
-/*!
- \fn qreal QGraphicsLayoutItem::preferredHeight() const
-
- Returns the preferred height.
-
- \sa setPreferredHeight(), setPreferredSize(), preferredSize()
-*/
-
-/*!
- \fn qreal QGraphicsLayoutItem::maximumWidth() const
-
- Returns the maximum width.
-
- \sa setMaximumWidth(), setMaximumSize(), maximumSize()
-*/
-
-/*!
- \fn qreal QGraphicsLayoutItem::maximumHeight() const
-
- Returns the maximum height.
-
- \sa setMaximumHeight(), setMaximumSize(), maximumSize()
-*/
-
-/*!
- \fn virtual void QGraphicsLayoutItem::setGeometry(const QRectF &rect)
-
- This virtual function sets the geometry of the QGraphicsLayoutItem to
- \a rect, which is in parent coordinates (e.g., the top-left corner of \a rect
- is equivalent to the item's position in parent coordinates).
-
- You must reimplement this function in a subclass of QGraphicsLayoutItem to
- receive geometry updates. The layout will call this function when it does a
- rearrangement.
-
- If \a rect is outside of the bounds of minimumSize and maximumSize, it
- will be adjusted to its closest size so that it is within the legal
- bounds.
-
- \sa geometry()
-*/
-void QGraphicsLayoutItem::setGeometry(const QRectF &rect)
-{
- Q_D(QGraphicsLayoutItem);
- QSizeF effectiveSize = rect.size().expandedTo(effectiveSizeHint(Qt::MinimumSize))
- .boundedTo(effectiveSizeHint(Qt::MaximumSize));
- d->geom = QRectF(rect.topLeft(), effectiveSize);
-}
-
-/*!
- \fn QRectF QGraphicsLayoutItem::geometry() const
-
- Returns the item's geometry (e.g., position and size) as a
- QRectF. This function is equivalent to QRectF(pos(), size()).
-
- \sa setGeometry()
-*/
-QRectF QGraphicsLayoutItem::geometry() const
-{
- Q_D(const QGraphicsLayoutItem);
- return d->geom;
-}
-
-/*!
- This virtual function provides the \a left, \a top, \a right and \a bottom
- contents margins for this QGraphicsLayoutItem. The default implementation
- assumes all contents margins are 0. The parameters point to values stored
- in qreals. If any of the pointers is 0, that value will not be updated.
-
- \sa QGraphicsWidget::setContentsMargins()
-*/
-void QGraphicsLayoutItem::getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const
-{
- if (left)
- *left = 0;
- if (top)
- *top = 0;
- if (right)
- *right = 0;
- if (bottom)
- *bottom = 0;
-}
-
-/*!
- Returns the contents rect in local coordinates.
-
- The contents rect defines the subrectangle used by an associated layout
- when arranging subitems. This function is a convenience function that
- adjusts the item's geometry() by its contents margins. Note that
- getContentsMargins() is a virtual function that you can reimplement to
- return the item's contents margins.
-
- \sa getContentsMargins(), geometry()
-*/
-QRectF QGraphicsLayoutItem::contentsRect() const
-{
- qreal left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- return QRectF(QPointF(), geometry().size()).adjusted(+left, +top, -right, -bottom);
-}
-
-/*!
- Returns the effective size hint for this QGraphicsLayoutItem.
-
- \a which is the size hint in question.
- \a constraint is an optional argument that defines a special constrain
- when calculating the effective size hint. By default, \a constraint is
- QSizeF(-1, -1), which means there is no constraint to the size hint.
-
- If you want to specify the widget's size hint for a given width or height,
- you can provide the fixed dimension in \a constraint. This is useful for
- widgets that can grow only either vertically or horizontally, and need to
- set either their width or their height to a special value.
-
- For example, a text paragraph item fit into a column width of 200 may
- grow vertically. You can pass QSizeF(200, -1) as a constraint to get a
- suitable minimum, preferred and maximum height).
-
- You can adjust the effective size hint by reimplementing sizeHint()
- in a QGraphicsLayoutItem subclass, or by calling one of the following
- functions: setMinimumSize(), setPreferredSize, or setMaximumSize()
- (or a combination of both).
-
- This function caches each of the size hints and guarantees that
- sizeHint() will be called only once for each value of \a which - unless
- \a constraint is not specified and updateGeometry() has been called.
-
- \sa sizeHint()
-*/
-QSizeF QGraphicsLayoutItem::effectiveSizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- Q_D(const QGraphicsLayoutItem);
-
- if (!d->userSizeHints && constraint.isValid())
- return constraint;
-
- // ### should respect size policy???
- return d_ptr->effectiveSizeHints(constraint)[which];
-}
-
-/*!
- This virtual function discards any cached size hint information. You
- should always call this function if you change the return value of the
- sizeHint() function. Subclasses must always call the base implementation
- when reimplementing this function.
-
- \sa effectiveSizeHint()
-*/
-void QGraphicsLayoutItem::updateGeometry()
-{
- Q_D(QGraphicsLayoutItem);
- d->sizeHintCacheDirty = true;
- d->sizeHintWithConstraintCacheDirty = true;
-}
-
-/*!
- Returns the parent of this QGraphicsLayoutItem, or 0 if there is no parent,
- or if the parent does not inherit from QGraphicsLayoutItem
- (QGraphicsLayoutItem is often used through multiple inheritance with
- QObject-derived classes).
-
- \sa setParentLayoutItem()
-*/
-QGraphicsLayoutItem *QGraphicsLayoutItem::parentLayoutItem() const
-{
- return d_func()->parent;
-}
-
-/*!
- Sets the parent of this QGraphicsLayoutItem to \a parent.
-
- \sa parentLayoutItem()
-*/
-void QGraphicsLayoutItem::setParentLayoutItem(QGraphicsLayoutItem *parent)
-{
- d_func()->parent = parent;
-}
-
-/*!
- Returns true if this QGraphicsLayoutItem is a layout (e.g., is inherited
- by an object that arranges other QGraphicsLayoutItem objects); otherwise
- returns false.
-
- \sa QGraphicsLayout
-*/
-bool QGraphicsLayoutItem::isLayout() const
-{
- return d_func()->isLayout;
-}
-
-/*!
- \since 4.6
-
- Returns whether a layout should delete this item in its destructor.
- If its true, then the layout will delete it. If its false, then it is
- assumed that another object has the ownership of it, and the layout won't
- delete this item.
-
- If the item inherits both QGraphicsItem and QGraphicsLayoutItem (such
- as QGraphicsWidget does) the item is really part of two ownership
- hierarchies. This property informs what the layout should do with its
- child items when it is destructed. In the case of QGraphicsWidget, it
- is preferred that when the layout is deleted it won't delete its children
- (since they are also part of the graphics item hierarchy).
-
- By default this value is initialized to false in QGraphicsLayoutItem,
- but it is overridden by QGraphicsLayout to return true. This is because
- QGraphicsLayout is not normally part of the QGraphicsItem hierarchy, so the
- parent layout should delete it.
- Subclasses might override this default behaviour by calling
- setOwnedByLayout(true).
-
- \sa setOwnedByLayout()
-*/
-bool QGraphicsLayoutItem::ownedByLayout() const
-{
- return d_func()->ownedByLayout;
-}
-/*!
- \since 4.6
-
- Sets whether a layout should delete this item in its destructor or not.
- \a ownership must be true to in order for the layout to delete it.
- \sa ownedByLayout()
-*/
-void QGraphicsLayoutItem::setOwnedByLayout(bool ownership)
-{
- d_func()->ownedByLayout = ownership;
-}
-
-/*!
- * Returns the QGraphicsItem that this layout item represents.
- * For QGraphicsWidget it will return itself. For custom items it can return an
- * aggregated value.
- *
- * \sa setGraphicsItem()
- */
-QGraphicsItem *QGraphicsLayoutItem::graphicsItem() const
-{
- return d_func()->graphicsItem;
-}
-
-/*!
- * If the QGraphicsLayoutItem represents a QGraphicsItem, and it wants to take
- * advantage of the automatic reparenting capabilities of QGraphicsLayout it
- * should set this value.
- * Note that if you delete \a item and not delete the layout item, you are
- * responsible of calling setGraphicsItem(0) in order to avoid having a
- * dangling pointer.
- *
- * \sa graphicsItem()
- */
-void QGraphicsLayoutItem::setGraphicsItem(QGraphicsItem *item)
-{
- d_func()->graphicsItem = item;
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicslayoutitem.h b/src/gui/graphicsview/qgraphicslayoutitem.h
deleted file mode 100644
index 7112dd06fc..0000000000
--- a/src/gui/graphicsview/qgraphicslayoutitem.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSLAYOUTITEM_H
-#define QGRAPHICSLAYOUTITEM_H
-
-#include <QtCore/qscopedpointer.h>
-#include <QtGui/qsizepolicy.h>
-#include <QtGui/qevent.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsLayoutItemPrivate;
-class QGraphicsItem;
-class Q_GUI_EXPORT QGraphicsLayoutItem
-{
-public:
- QGraphicsLayoutItem(QGraphicsLayoutItem *parent = 0, bool isLayout = false);
- virtual ~QGraphicsLayoutItem();
-
- void setSizePolicy(const QSizePolicy &policy);
- void setSizePolicy(QSizePolicy::Policy hPolicy, QSizePolicy::Policy vPolicy, QSizePolicy::ControlType controlType = QSizePolicy::DefaultType);
- QSizePolicy sizePolicy() const;
-
- void setMinimumSize(const QSizeF &size);
- inline void setMinimumSize(qreal w, qreal h);
- QSizeF minimumSize() const;
- void setMinimumWidth(qreal width);
- inline qreal minimumWidth() const;
- void setMinimumHeight(qreal height);
- inline qreal minimumHeight() const;
-
- void setPreferredSize(const QSizeF &size);
- inline void setPreferredSize(qreal w, qreal h);
- QSizeF preferredSize() const;
- void setPreferredWidth(qreal width);
- inline qreal preferredWidth() const;
- void setPreferredHeight(qreal height);
- inline qreal preferredHeight() const;
-
- void setMaximumSize(const QSizeF &size);
- inline void setMaximumSize(qreal w, qreal h);
- QSizeF maximumSize() const;
- void setMaximumWidth(qreal width);
- inline qreal maximumWidth() const;
- void setMaximumHeight(qreal height);
- inline qreal maximumHeight() const;
-
- virtual void setGeometry(const QRectF &rect);
- QRectF geometry() const;
- virtual void getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const;
- QRectF contentsRect() const;
-
- QSizeF effectiveSizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
-
- virtual void updateGeometry(); //### rename to sizeHintChanged()
-
- QGraphicsLayoutItem *parentLayoutItem() const;
- void setParentLayoutItem(QGraphicsLayoutItem *parent);
-
- bool isLayout() const;
- // ###Qt5: Make automatic reparenting work regardless of item/object/widget type.
- QGraphicsItem *graphicsItem() const;
- bool ownedByLayout() const;
-
-protected:
- void setGraphicsItem(QGraphicsItem *item);
- void setOwnedByLayout(bool ownedByLayout);
- QGraphicsLayoutItem(QGraphicsLayoutItemPrivate &dd);
-
- virtual QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const = 0;
- QScopedPointer<QGraphicsLayoutItemPrivate> d_ptr;
-
-private:
- QSizeF *effectiveSizeHints(const QSizeF &constraint) const;
- Q_DECLARE_PRIVATE(QGraphicsLayoutItem)
-
- friend class QGraphicsLayout;
-};
-
-Q_DECLARE_INTERFACE(QGraphicsLayoutItem, "com.trolltech.Qt.QGraphicsLayoutItem")
-
-inline void QGraphicsLayoutItem::setMinimumSize(qreal aw, qreal ah)
-{ setMinimumSize(QSizeF(aw, ah)); }
-inline void QGraphicsLayoutItem::setPreferredSize(qreal aw, qreal ah)
-{ setPreferredSize(QSizeF(aw, ah)); }
-inline void QGraphicsLayoutItem::setMaximumSize(qreal aw, qreal ah)
-{ setMaximumSize(QSizeF(aw, ah)); }
-
-inline qreal QGraphicsLayoutItem::minimumWidth() const
-{ return effectiveSizeHint(Qt::MinimumSize).width(); }
-inline qreal QGraphicsLayoutItem::minimumHeight() const
-{ return effectiveSizeHint(Qt::MinimumSize).height(); }
-
-inline qreal QGraphicsLayoutItem::preferredWidth() const
-{ return effectiveSizeHint(Qt::PreferredSize).width(); }
-inline qreal QGraphicsLayoutItem::preferredHeight() const
-{ return effectiveSizeHint(Qt::PreferredSize).height(); }
-
-inline qreal QGraphicsLayoutItem::maximumWidth() const
-{ return effectiveSizeHint(Qt::MaximumSize).width(); }
-inline qreal QGraphicsLayoutItem::maximumHeight() const
-{ return effectiveSizeHint(Qt::MaximumSize).height(); }
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicslayoutitem_p.h b/src/gui/graphicsview/qgraphicslayoutitem_p.h
deleted file mode 100644
index 85481b7a46..0000000000
--- a/src/gui/graphicsview/qgraphicslayoutitem_p.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSLAYOUTITEM_P_H
-#define QGRAPHICSLAYOUTITEM_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 <QtCore/QSizeF>
-#include <QtGui/QSizePolicy>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsLayoutItem;
-class Q_AUTOTEST_EXPORT QGraphicsLayoutItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsLayoutItem)
-public:
- virtual ~QGraphicsLayoutItemPrivate();
- QGraphicsLayoutItemPrivate(QGraphicsLayoutItem *parent, bool isLayout);
- static QGraphicsLayoutItemPrivate *get(QGraphicsLayoutItem *q) { return q->d_func();}
- static const QGraphicsLayoutItemPrivate *get(const QGraphicsLayoutItem *q) { return q->d_func();}
-
- void init();
- QSizeF *effectiveSizeHints(const QSizeF &constraint) const;
- QGraphicsItem *parentItem() const;
- void ensureUserSizeHints();
- void setSize(Qt::SizeHint which, const QSizeF &size);
- enum SizeComponent { Width, Height };
- void setSizeComponent(Qt::SizeHint which, SizeComponent component, qreal value);
-
- bool hasHeightForWidth() const;
- bool hasWidthForHeight() const;
-
- QSizePolicy sizePolicy;
- QGraphicsLayoutItem *parent;
-
- QSizeF *userSizeHints;
- mutable QSizeF cachedSizeHints[Qt::NSizeHints];
- mutable QSizeF cachedConstraint;
- mutable QSizeF cachedSizeHintsWithConstraints[Qt::NSizeHints];
-
- mutable quint32 sizeHintCacheDirty : 1;
- mutable quint32 sizeHintWithConstraintCacheDirty : 1;
- quint32 isLayout : 1;
- quint32 ownedByLayout : 1;
-
- QGraphicsLayoutItem *q_ptr;
- QRectF geom;
- QGraphicsItem *graphicsItem;
-};
-
-QT_END_NAMESPACE
-
-#endif //QGRAPHICSLAYOUTITEM_P_H
-
diff --git a/src/gui/graphicsview/qgraphicslinearlayout.cpp b/src/gui/graphicsview/qgraphicslinearlayout.cpp
deleted file mode 100644
index 5591638395..0000000000
--- a/src/gui/graphicsview/qgraphicslinearlayout.cpp
+++ /dev/null
@@ -1,568 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsLinearLayout
- \brief The QGraphicsLinearLayout class provides a horizontal or vertical
- layout for managing widgets in Graphics View.
- \since 4.4
- \ingroup graphicsview-api
-
- The default orientation for a linear layout is Qt::Horizontal. You can
- choose a vertical orientation either by calling setOrientation(), or by
- passing Qt::Vertical to QGraphicsLinearLayout's constructor.
-
- The most common way to use QGraphicsLinearLayout is to construct an object
- on the heap with no parent, add widgets and layouts by calling addItem(),
- and finally assign the layout to a widget by calling
- QGraphicsWidget::setLayout().
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp 0
-
- You can add widgets, layouts, stretches (addStretch(), insertStretch() or
- setStretchFactor()), and spacings (setItemSpacing()) to a linear
- layout. The layout takes ownership of the items. In some cases when the layout
- item also inherits from QGraphicsItem (such as QGraphicsWidget) there will be a
- ambiguity in ownership because the layout item belongs to two ownership hierarchies.
- See the documentation of QGraphicsLayoutItem::setOwnedByLayout() how to handle
- this.
- You can access each item in the layout by calling count() and itemAt(). Calling
- removeAt() or removeItem() will remove an item from the layout, without
- destroying it.
-
- \section1 Size Hints and Size Policies in QGraphicsLinearLayout
-
- QGraphicsLinearLayout respects each item's size hints and size policies,
- and when the layout contains more space than the items can fill, each item
- is arranged according to the layout's alignment for that item. You can set
- an alignment for each item by calling setAlignment(), and check the
- alignment for any item by calling alignment(). By default, items are
- aligned to the top left.
-
- \section1 Spacing within QGraphicsLinearLayout
-
- Between the items, the layout distributes some space. The actual amount of
- space depends on the managed widget's current style, but the common
- spacing is 4. You can also set your own spacing by calling setSpacing(),
- and get the current spacing value by calling spacing(). If you want to
- configure individual spacing for your items, you can call setItemSpacing().
-
- \section1 Stretch Factor in QGraphicsLinearLayout
-
- You can assign a stretch factor to each item to control how much space it
- will get compared to the other items. By default, two identical widgets
- arranged in a linear layout will have the same size, but if the first
- widget has a stretch factor of 1 and the second widget has a stretch
- factor of 2, the first widget will get 1/3 of the available space, and the
- second will get 2/3.
-
- QGraphicsLinearLayout calculates the distribution of sizes by adding up
- the stretch factors of all items, and then dividing the available space
- accordingly. The default stretch factor is 0 for all items; a factor of 0
- means the item does not have any defined stretch factor; effectively this
- is the same as setting the stretch factor to 1. The stretch factor only
- applies to the available space in the lengthwise direction of the layout
- (following its orientation). If you want to control both the item's
- horizontal and vertical stretch, you can use QGraphicsGridLayout instead.
-
- \section1 QGraphicsLinearLayout Compared to Other Layouts
-
- QGraphicsLinearLayout is very similar to QVBoxLayout and QHBoxLayout, but
- in contrast to these classes, it is used to manage QGraphicsWidget and
- QGraphicsLayout instead of QWidget and QLayout.
-
- \sa QGraphicsGridLayout, QGraphicsWidget
-*/
-
-#include "qapplication.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qwidget.h"
-#include "qgraphicslayout_p.h"
-#include "qgraphicslayoutitem.h"
-#include "qgraphicslinearlayout.h"
-#include "qgraphicswidget.h"
-#include "qgridlayoutengine_p.h"
-#ifdef QT_DEBUG
-#include <QtCore/qdebug.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsLinearLayoutPrivate : public QGraphicsLayoutPrivate
-{
-public:
- QGraphicsLinearLayoutPrivate(Qt::Orientation orientation) : orientation(orientation) { }
-
- void removeGridItem(QGridLayoutItem *gridItem);
- QLayoutStyleInfo styleInfo() const;
- void fixIndex(int *index) const;
- int gridRow(int index) const;
- int gridColumn(int index) const;
-
- Qt::Orientation orientation;
- QGridLayoutEngine engine;
-};
-
-void QGraphicsLinearLayoutPrivate::removeGridItem(QGridLayoutItem *gridItem)
-{
- int index = gridItem->firstRow(orientation);
- engine.removeItem(gridItem);
- engine.removeRows(index, 1, orientation);
-}
-
-void QGraphicsLinearLayoutPrivate::fixIndex(int *index) const
-{
- int count = engine.rowCount(orientation);
- if (uint(*index) > uint(count))
- *index = count;
-}
-
-int QGraphicsLinearLayoutPrivate::gridRow(int index) const
-{
- if (orientation == Qt::Horizontal)
- return 0;
- return int(qMin(uint(index), uint(engine.rowCount())));
-}
-
-int QGraphicsLinearLayoutPrivate::gridColumn(int index) const
-{
- if (orientation == Qt::Vertical)
- return 0;
- return int(qMin(uint(index), uint(engine.columnCount())));
-}
-
-Q_GLOBAL_STATIC(QWidget, globalStyleInfoWidget)
-
-QLayoutStyleInfo QGraphicsLinearLayoutPrivate::styleInfo() const
-{
- QGraphicsItem *item = parentItem();
- QStyle *style = (item && item->isWidget()) ? static_cast<QGraphicsWidget*>(item)->style() : QApplication::style();
- return QLayoutStyleInfo(style, globalStyleInfoWidget());
-}
-
-/*!
- Constructs a QGraphicsLinearLayout instance. You can pass the
- \a orientation for the layout, either horizontal or vertical, and
- \a parent is passed to QGraphicsLayout's constructor.
-*/
-QGraphicsLinearLayout::QGraphicsLinearLayout(Qt::Orientation orientation, QGraphicsLayoutItem *parent)
- : QGraphicsLayout(*new QGraphicsLinearLayoutPrivate(orientation), parent)
-{
-}
-
-/*!
- Constructs a QGraphicsLinearLayout instance using Qt::Horizontal
- orientation. \a parent is passed to QGraphicsLayout's constructor.
-*/
-QGraphicsLinearLayout::QGraphicsLinearLayout(QGraphicsLayoutItem *parent)
- : QGraphicsLayout(*new QGraphicsLinearLayoutPrivate(Qt::Horizontal), parent)
-{
-}
-
-/*!
- Destroys the QGraphicsLinearLayout object.
-*/
-QGraphicsLinearLayout::~QGraphicsLinearLayout()
-{
- for (int i = count() - 1; i >= 0; --i) {
- QGraphicsLayoutItem *item = itemAt(i);
- // The following lines can be removed, but this removes the item
- // from the layout more efficiently than the implementation of
- // ~QGraphicsLayoutItem.
- removeAt(i);
- if (item) {
- item->setParentLayoutItem(0);
- if (item->ownedByLayout())
- delete item;
- }
- }
-}
-
-/*!
- Change the layout orientation to \a orientation. Changing the layout
- orientation will automatically invalidate the layout.
-
- \sa orientation()
-*/
-void QGraphicsLinearLayout::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QGraphicsLinearLayout);
- if (orientation != d->orientation) {
- d->engine.transpose();
- d->orientation = orientation;
- invalidate();
- }
-}
-
-/*!
- Returns the layout orientation.
- \sa setOrientation()
- */
-Qt::Orientation QGraphicsLinearLayout::orientation() const
-{
- Q_D(const QGraphicsLinearLayout);
- return d->orientation;
-}
-
-/*!
- \fn void QGraphicsLinearLayout::addItem(QGraphicsLayoutItem *item)
-
- This convenience function is equivalent to calling
- insertItem(-1, \a item).
-*/
-
-/*!
- \fn void QGraphicsLinearLayout::addStretch(int stretch)
-
- This convenience function is equivalent to calling
- insertStretch(-1, \a stretch).
-*/
-
-/*!
- Inserts \a item into the layout at \a index, or before any item that is
- currently at \a index.
-
- \sa addItem(), itemAt(), insertStretch(), setItemSpacing()
-*/
-void QGraphicsLinearLayout::insertItem(int index, QGraphicsLayoutItem *item)
-{
- Q_D(QGraphicsLinearLayout);
- if (!item) {
- qWarning("QGraphicsLinearLayout::insertItem: cannot insert null item");
- return;
- }
- if (item == this) {
- qWarning("QGraphicsLinearLayout::insertItem: cannot insert itself");
- return;
- }
- Q_ASSERT(item);
-
- //the order of the following instructions is very important because
- //invalidating the layout before adding the child item will make the layout happen
- //before we try to paint the item
- invalidate();
- d->addChildLayoutItem(item);
-
- d->fixIndex(&index);
- d->engine.insertRow(index, d->orientation);
- new QGridLayoutItem(&d->engine, item, d->gridRow(index), d->gridColumn(index), 1, 1, 0, index);
-}
-
-/*!
- Inserts a stretch of \a stretch at \a index, or before any item that is
- currently at \a index.
-
- \sa addStretch(), setStretchFactor(), setItemSpacing(), insertItem()
-*/
-void QGraphicsLinearLayout::insertStretch(int index, int stretch)
-{
- Q_D(QGraphicsLinearLayout);
- d->fixIndex(&index);
- d->engine.insertRow(index, d->orientation);
- d->engine.setRowStretchFactor(index, stretch, d->orientation);
- invalidate();
-}
-
-/*!
- Removes \a item from the layout without destroying it. Ownership of
- \a item is transferred to the caller.
-
- \sa removeAt(), insertItem()
-*/
-void QGraphicsLinearLayout::removeItem(QGraphicsLayoutItem *item)
-{
- Q_D(QGraphicsLinearLayout);
- if (QGridLayoutItem *gridItem = d->engine.findLayoutItem(item)) {
- item->setParentLayoutItem(0);
- d->removeGridItem(gridItem);
- delete gridItem;
- invalidate();
- }
-}
-
-/*!
- Removes the item at \a index without destroying it. Ownership of the item
- is transferred to the caller.
-
- \sa removeItem(), insertItem()
-*/
-void QGraphicsLinearLayout::removeAt(int index)
-{
- Q_D(QGraphicsLinearLayout);
- if (index < 0 || index >= d->engine.itemCount()) {
- qWarning("QGraphicsLinearLayout::removeAt: invalid index %d", index);
- return;
- }
- if (QGridLayoutItem *gridItem = d->engine.itemAt(index)) {
- if (QGraphicsLayoutItem *layoutItem = gridItem->layoutItem())
- layoutItem->setParentLayoutItem(0);
- d->removeGridItem(gridItem);
- delete gridItem;
- invalidate();
- }
-}
-
-/*!
- Sets the layout's spacing to \a spacing. Spacing refers to the
- vertical and horizontal distances between items.
-
- \sa setItemSpacing(), setStretchFactor(), QGraphicsGridLayout::setSpacing()
-*/
-void QGraphicsLinearLayout::setSpacing(qreal spacing)
-{
- Q_D(QGraphicsLinearLayout);
- if (spacing < 0) {
- qWarning("QGraphicsLinearLayout::setSpacing: invalid spacing %g", spacing);
- return;
- }
- d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
- invalidate();
-}
-
-/*!
- Returns the layout's spacing. Spacing refers to the
- vertical and horizontal distances between items.
-
- \sa setSpacing()
- */
-qreal QGraphicsLinearLayout::spacing() const
-{
- Q_D(const QGraphicsLinearLayout);
- return d->engine.spacing(d->styleInfo(), d->orientation);
-}
-
-/*!
- Sets the spacing after item at \a index to \a spacing.
-*/
-void QGraphicsLinearLayout::setItemSpacing(int index, qreal spacing)
-{
- Q_D(QGraphicsLinearLayout);
- d->engine.setRowSpacing(index, spacing, d->orientation);
- invalidate();
-}
-/*!
- Returns the spacing after item at \a index.
-*/
-qreal QGraphicsLinearLayout::itemSpacing(int index) const
-{
- Q_D(const QGraphicsLinearLayout);
- return d->engine.rowSpacing(index, d->orientation);
-}
-
-/*!
- Sets the stretch factor for \a item to \a stretch. If an item's stretch
- factor changes, this function will invalidate the layout.
-
- Setting \a stretch to 0 removes the stretch factor from the item, and is
- effectively equivalent to setting \a stretch to 1.
-
- \sa stretchFactor()
-*/
-void QGraphicsLinearLayout::setStretchFactor(QGraphicsLayoutItem *item, int stretch)
-{
- Q_D(QGraphicsLinearLayout);
- if (!item) {
- qWarning("QGraphicsLinearLayout::setStretchFactor: cannot assign"
- " a stretch factor to a null item");
- return;
- }
- if (stretchFactor(item) == stretch)
- return;
- d->engine.setStretchFactor(item, stretch, d->orientation);
- invalidate();
-}
-
-/*!
- Returns the stretch factor for \a item. The default stretch factor is 0,
- meaning that the item has no assigned stretch factor.
-
- \sa setStretchFactor()
-*/
-int QGraphicsLinearLayout::stretchFactor(QGraphicsLayoutItem *item) const
-{
- Q_D(const QGraphicsLinearLayout);
- if (!item) {
- qWarning("QGraphicsLinearLayout::setStretchFactor: cannot return"
- " a stretch factor for a null item");
- return 0;
- }
- return d->engine.stretchFactor(item, d->orientation);
-}
-
-/*!
- Sets the alignment of \a item to \a alignment. If \a item's alignment
- changes, the layout is automatically invalidated.
-
- \sa alignment(), invalidate()
-*/
-void QGraphicsLinearLayout::setAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment)
-{
- Q_D(QGraphicsLinearLayout);
- if (this->alignment(item) == alignment)
- return;
- d->engine.setAlignment(item, alignment);
- invalidate();
-}
-
-/*!
- Returns the alignment for \a item. The default alignment is
- Qt::AlignTop | Qt::AlignLeft.
-
- The alignment decides how the item is positioned within its assigned space
- in the case where there's more space available in the layout than the
- widgets can occupy.
-
- \sa setAlignment()
-*/
-Qt::Alignment QGraphicsLinearLayout::alignment(QGraphicsLayoutItem *item) const
-{
- Q_D(const QGraphicsLinearLayout);
- return d->engine.alignment(item);
-}
-
-#if 0 // ###
-QSizePolicy::ControlTypes QGraphicsLinearLayout::controlTypes(LayoutSide side) const
-{
- return d->engine.controlTypes(side);
-}
-#endif
-
-/*!
- \reimp
-*/
-int QGraphicsLinearLayout::count() const
-{
- Q_D(const QGraphicsLinearLayout);
- return d->engine.itemCount();
-}
-
-/*!
- \reimp
- When iterating from 0 and up, it will return the items in the visual arranged order.
-*/
-QGraphicsLayoutItem *QGraphicsLinearLayout::itemAt(int index) const
-{
- Q_D(const QGraphicsLinearLayout);
- if (index < 0 || index >= d->engine.itemCount()) {
- qWarning("QGraphicsLinearLayout::itemAt: invalid index %d", index);
- return 0;
- }
- QGraphicsLayoutItem *item = 0;
- if (QGridLayoutItem *gridItem = d->engine.itemAt(index))
- item = gridItem->layoutItem();
- return item;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsLinearLayout::setGeometry(const QRectF &rect)
-{
- Q_D(QGraphicsLinearLayout);
- QGraphicsLayout::setGeometry(rect);
- QRectF effectiveRect = geometry();
- qreal left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- Qt::LayoutDirection visualDir = d->visualDirection();
- d->engine.setVisualDirection(visualDir);
- if (visualDir == Qt::RightToLeft)
- qSwap(left, right);
- effectiveRect.adjust(+left, +top, -right, -bottom);
-#ifdef QT_DEBUG
- if (qt_graphicsLayoutDebug()) {
- static int counter = 0;
- qDebug() << counter++ << "QGraphicsLinearLayout::setGeometry - " << rect;
- dump(1);
- }
-#endif
- d->engine.setGeometries(d->styleInfo(), effectiveRect);
-#ifdef QT_DEBUG
- if (qt_graphicsLayoutDebug()) {
- qDebug() << "post dump";
- dump(1);
- }
-#endif
-}
-
-/*!
- \reimp
-*/
-QSizeF QGraphicsLinearLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- Q_D(const QGraphicsLinearLayout);
- qreal left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- const QSizeF extraMargins(left + right, top + bottom);
- return d->engine.sizeHint(d->styleInfo(), which , constraint - extraMargins) + extraMargins;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsLinearLayout::invalidate()
-{
- Q_D(QGraphicsLinearLayout);
- d->engine.invalidate();
- QGraphicsLayout::invalidate();
-}
-
-/*!
- \internal
-*/
-void QGraphicsLinearLayout::dump(int indent) const
-{
-#ifdef QT_DEBUG
- if (qt_graphicsLayoutDebug()) {
- Q_D(const QGraphicsLinearLayout);
- qDebug("%*s%s layout", indent, "",
- d->orientation == Qt::Horizontal ? "Horizontal" : "Vertical");
- d->engine.dump(indent + 1);
- }
-#else
- Q_UNUSED(indent);
-#endif
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicslinearlayout.h b/src/gui/graphicsview/qgraphicslinearlayout.h
deleted file mode 100644
index 60749dbdaf..0000000000
--- a/src/gui/graphicsview/qgraphicslinearlayout.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSLINEARLAYOUT_H
-#define QGRAPHICSLINEARLAYOUT_H
-
-#include <QtGui/qgraphicsitem.h>
-#include <QtGui/qgraphicslayout.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsLinearLayoutPrivate;
-
-class Q_GUI_EXPORT QGraphicsLinearLayout : public QGraphicsLayout
-{
-public:
- QGraphicsLinearLayout(QGraphicsLayoutItem *parent = 0);
- QGraphicsLinearLayout(Qt::Orientation orientation, QGraphicsLayoutItem *parent = 0);
- virtual ~QGraphicsLinearLayout();
-
- void setOrientation(Qt::Orientation orientation);
- Qt::Orientation orientation() const;
-
- inline void addItem(QGraphicsLayoutItem *item) { insertItem(-1, item); }
- inline void addStretch(int stretch = 1) { insertStretch(-1, stretch); }
-
- void insertItem(int index, QGraphicsLayoutItem *item);
- void insertStretch(int index, int stretch = 1);
-
- void removeItem(QGraphicsLayoutItem *item);
- void removeAt(int index);
-
- void setSpacing(qreal spacing);
- qreal spacing() const;
- void setItemSpacing(int index, qreal spacing);
- qreal itemSpacing(int index) const;
-
- void setStretchFactor(QGraphicsLayoutItem *item, int stretch);
- int stretchFactor(QGraphicsLayoutItem *item) const;
-
- void setAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment);
- Qt::Alignment alignment(QGraphicsLayoutItem *item) const;
-
- void setGeometry(const QRectF &rect);
-
- int count() const;
- QGraphicsLayoutItem *itemAt(int index) const;
-
- void invalidate();
- QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
-
-#if 0 // ###
- Q5SizePolicy::ControlTypes controlTypes(LayoutSide side) const;
-#endif
-
- void dump(int indent = 0) const;
-
-protected:
-#if 0
- QSize contentsSizeHint(Qt::SizeHint which, const QSize &constraint = QSize()) const;
-#endif
-
-private:
- Q_DISABLE_COPY(QGraphicsLinearLayout)
- Q_DECLARE_PRIVATE(QGraphicsLinearLayout)
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
-
diff --git a/src/gui/graphicsview/qgraphicsproxywidget.cpp b/src/gui/graphicsview/qgraphicsproxywidget.cpp
deleted file mode 100644
index e6142e66ac..0000000000
--- a/src/gui/graphicsview/qgraphicsproxywidget.cpp
+++ /dev/null
@@ -1,1570 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicslayout.h"
-#include "qgraphicsproxywidget.h"
-#include "private/qgraphicsproxywidget_p.h"
-#include "private/qwidget_p.h"
-#include "private/qapplication_p.h"
-
-#include <QtCore/qdebug.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qgraphicsscene.h>
-#include <QtGui/qgraphicssceneevent.h>
-#include <QtGui/qlayout.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qstyleoption.h>
-#include <QtGui/qgraphicsview.h>
-#include <QtGui/qlistview.h>
-#include <QtGui/qlineedit.h>
-#include <QtGui/qtextedit.h>
-
-QT_BEGIN_NAMESPACE
-
-//#define GRAPHICSPROXYWIDGET_DEBUG
-
-/*!
- \class QGraphicsProxyWidget
- \brief The QGraphicsProxyWidget class provides a proxy layer for embedding
- a QWidget in a QGraphicsScene.
- \since 4.4
- \ingroup graphicsview-api
-
- QGraphicsProxyWidget embeds QWidget-based widgets, for example, a
- QPushButton, QFontComboBox, or even QFileDialog, into
- QGraphicsScene. It forwards events between the two objects and
- translates between QWidget's integer-based geometry and
- QGraphicsWidget's qreal-based geometry. QGraphicsProxyWidget
- supports all core features of QWidget, including tab focus,
- keyboard input, Drag & Drop, and popups. You can also embed
- complex widgets, e.g., widgets with subwidgets.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp 0
-
- QGraphicsProxyWidget takes care of automatically embedding popup children
- of embedded widgets through creating a child proxy for each popup. This
- means that when an embedded QComboBox shows its popup list, a new
- QGraphicsProxyWidget is created automatically, embedding the popup, and
- positioning it correctly. This only works if the popup is child of the
- embedded widget (for example QToolButton::setMenu() requires the QMenu instance
- to be child of the QToolButton).
-
- \section1 Embedding a Widget with QGraphicsProxyWidget
-
- There are two ways to embed a widget using QGraphicsProxyWidget. The most
- common way is to pass a widget pointer to QGraphicsScene::addWidget()
- together with any relevant \l Qt::WindowFlags. This function returns a
- pointer to a QGraphicsProxyWidget. You can then choose to reparent or
- position either the proxy, or the embedded widget itself.
-
- For example, in the code snippet below, we embed a group box into the proxy:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp 1
-
- The image below is the output obtained with its contents margin and
- contents rect labeled.
-
- \image qgraphicsproxywidget-embed.png
-
- Alternatively, you can start by creating a new QGraphicsProxyWidget item,
- and then call setWidget() to embed a QWidget later. The widget() function
- returns a pointer to the embedded widget. QGraphicsProxyWidget shares
- ownership with QWidget, so if either of the two widgets are destroyed, the
- other widget will be automatically destroyed as well.
-
- \section1 Synchronizing Widget States
-
- QGraphicsProxyWidget keeps its state in sync with the embedded widget. For
- example, if the proxy is hidden or disabled, the embedded widget will be
- hidden or disabled as well, and vice versa. When the widget is embedded by
- calling addWidget(), QGraphicsProxyWidget copies the state from the widget
- into the proxy, and after that, the two will stay synchronized where
- possible. By default, when you embed a widget into a proxy, both the widget
- and the proxy will be visible because a QGraphicsWidget is visible when
- created (you do not have to call show()). If you explicitly hide the
- embedded widget, the proxy will also become invisible.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp 2
-
- QGraphicsProxyWidget maintains symmetry for the following states:
-
- \table
- \header \o QWidget state \o QGraphicsProxyWidget state \o Notes
- \row \o QWidget::enabled
- \o QGraphicsProxyWidget::enabled
- \o
- \row \o QWidget::visible
- \o QGraphicsProxyWidget::visible
- \o The explicit state is also symmetric.
- \row \o QWidget::geometry
- \o QGraphicsProxyWidget::geometry
- \o Geometry is only guaranteed to be symmetric while
- the embedded widget is visible.
- \row \o QWidget::layoutDirection
- \o QGraphicsProxyWidget::layoutDirection
- \o
- \row \o QWidget::style
- \o QGraphicsProxyWidget::style
- \o
- \row \o QWidget::palette
- \o QGraphicsProxyWidget::palette
- \o
- \row \o QWidget::font
- \o QGraphicsProxyWidget::font
- \o
- \row \o QWidget::cursor
- \o QGraphicsProxyWidget::cursor
- \o The embedded widget overrides the proxy widget
- cursor. The proxy cursor changes depending on
- which embedded subwidget is currently under the
- mouse.
- \row \o QWidget::sizeHint()
- \o QGraphicsProxyWidget::sizeHint()
- \o All size hint functionality from the embedded
- widget is forwarded by the proxy.
- \row \o QWidget::getContentsMargins()
- \o QGraphicsProxyWidget::getContentsMargins()
- \o Updated once by setWidget().
- \row \o QWidget::windowTitle
- \o QGraphicsProxyWidget::windowTitle
- \o Updated once by setWidget().
- \endtable
-
- \note QGraphicsScene keeps the embedded widget in a special state that
- prevents it from disturbing other widgets (both embedded and not embedded)
- while the widget is embedded. In this state, the widget may differ slightly
- in behavior from when it is not embedded.
-
- \warning This class is provided for convenience when bridging
- QWidgets and QGraphicsItems, it should not be used for
- high-performance scenarios.
-
- \sa QGraphicsScene::addWidget(), QGraphicsWidget
-*/
-
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *);
-Q_GUI_EXPORT extern bool qt_tab_all_widgets;
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::init()
-{
- Q_Q(QGraphicsProxyWidget);
- q->setFocusPolicy(Qt::WheelFocus);
- q->setAcceptDrops(true);
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneHoverEvent *event)
-{
- QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);
- mouseEvent.setPos(event->pos());
- mouseEvent.setScreenPos(event->screenPos());
- mouseEvent.setButton(Qt::NoButton);
- mouseEvent.setButtons(0);
- mouseEvent.setModifiers(event->modifiers());
- sendWidgetMouseEvent(&mouseEvent);
- event->setAccepted(mouseEvent.isAccepted());
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneMouseEvent *event)
-{
- if (!event || !widget || !widget->isVisible())
- return;
- Q_Q(QGraphicsProxyWidget);
-
- // Find widget position and receiver.
- QPointF pos = event->pos();
- QPointer<QWidget> alienWidget = widget->childAt(pos.toPoint());
- QPointer<QWidget> receiver = alienWidget ? alienWidget : widget;
-
- if (QWidgetPrivate::nearestGraphicsProxyWidget(receiver) != q)
- return; //another proxywidget will handle the events
-
- // Translate QGraphicsSceneMouse events to QMouseEvents.
- QEvent::Type type = QEvent::None;
- switch (event->type()) {
- case QEvent::GraphicsSceneMousePress:
- type = QEvent::MouseButtonPress;
- if (!embeddedMouseGrabber)
- embeddedMouseGrabber = receiver;
- else
- receiver = embeddedMouseGrabber;
- break;
- case QEvent::GraphicsSceneMouseRelease:
- type = QEvent::MouseButtonRelease;
- if (embeddedMouseGrabber)
- receiver = embeddedMouseGrabber;
- break;
- case QEvent::GraphicsSceneMouseDoubleClick:
- type = QEvent::MouseButtonDblClick;
- if (!embeddedMouseGrabber)
- embeddedMouseGrabber = receiver;
- else
- receiver = embeddedMouseGrabber;
- break;
- case QEvent::GraphicsSceneMouseMove:
- type = QEvent::MouseMove;
- if (embeddedMouseGrabber)
- receiver = embeddedMouseGrabber;
- break;
- default:
- Q_ASSERT_X(false, "QGraphicsProxyWidget", "internal error");
- break;
- }
-
- if (!lastWidgetUnderMouse) {
- QApplicationPrivate::dispatchEnterLeave(embeddedMouseGrabber ? embeddedMouseGrabber : receiver, 0);
- lastWidgetUnderMouse = receiver;
- }
-
- // Map event position from us to the receiver
- pos = mapToReceiver(pos, receiver);
-
- // Send mouse event.
- QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(type, pos,
- receiver->mapToGlobal(pos.toPoint()), event->button(),
- event->buttons(), event->modifiers());
-
- QWidget *embeddedMouseGrabberPtr = (QWidget *)embeddedMouseGrabber;
- QApplicationPrivate::sendMouseEvent(receiver, mouseEvent, alienWidget, widget,
- &embeddedMouseGrabberPtr, lastWidgetUnderMouse, event->spontaneous());
- embeddedMouseGrabber = embeddedMouseGrabberPtr;
-
- // Handle enter/leave events when last button is released from mouse
- // grabber child widget.
- if (embeddedMouseGrabber && type == QEvent::MouseButtonRelease && !event->buttons()) {
- Q_Q(QGraphicsProxyWidget);
- if (q->rect().contains(event->pos()) && q->acceptsHoverEvents())
- lastWidgetUnderMouse = alienWidget ? alienWidget : widget;
- else // released on the frame our outside the item, or doesn't accept hover events.
- lastWidgetUnderMouse = 0;
-
- QApplicationPrivate::dispatchEnterLeave(lastWidgetUnderMouse, embeddedMouseGrabber);
- embeddedMouseGrabber = 0;
-
-#ifndef QT_NO_CURSOR
- // ### Restore the cursor, don't override it.
- if (!lastWidgetUnderMouse)
- q->unsetCursor();
-#endif
- }
-
- event->setAccepted(mouseEvent->isAccepted());
- delete mouseEvent;
-}
-
-void QGraphicsProxyWidgetPrivate::sendWidgetKeyEvent(QKeyEvent *event)
-{
- Q_Q(QGraphicsProxyWidget);
- if (!event || !widget || !widget->isVisible())
- return;
-
- QPointer<QWidget> receiver = widget->focusWidget();
- if (!receiver)
- receiver = widget;
- Q_ASSERT(receiver);
-
- do {
- bool res = QApplication::sendEvent(receiver, event);
- if ((res && event->isAccepted()) || (q->isWindow() && receiver == widget))
- break;
- receiver = receiver->parentWidget();
- } while (receiver);
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::removeSubFocusHelper(QWidget *widget, Qt::FocusReason reason)
-{
- QFocusEvent event(QEvent::FocusOut, reason);
- QPointer<QWidget> widgetGuard = widget;
- QApplication::sendEvent(widget, &event);
- if (widgetGuard && event.isAccepted())
- QApplication::sendEvent(widget->style(), &event);
-}
-
-/*!
- \internal
-
- Reimplemented from QGraphicsItemPrivate. ### Qt 5: Move impl to
- reimplementation QGraphicsProxyWidget::inputMethodQuery().
-*/
-QVariant QGraphicsProxyWidgetPrivate::inputMethodQueryHelper(Qt::InputMethodQuery query) const
-{
- Q_Q(const QGraphicsProxyWidget);
- if (!widget || !q->hasFocus())
- return QVariant();
-
- QWidget *focusWidget = widget->focusWidget();
- if (!focusWidget)
- focusWidget = widget;
- QVariant v = focusWidget->inputMethodQuery(query);
- QPointF focusWidgetPos = q->subWidgetRect(focusWidget).topLeft();
- switch (v.type()) {
- case QVariant::RectF:
- v = v.toRectF().translated(focusWidgetPos);
- break;
- case QVariant::PointF:
- v = v.toPointF() + focusWidgetPos;
- break;
- case QVariant::Rect:
- v = v.toRect().translated(focusWidgetPos.toPoint());
- break;
- case QVariant::Point:
- v = v.toPoint() + focusWidgetPos.toPoint();
- break;
- default:
- break;
- }
- return v;
-}
-
-/*!
- \internal
- Some of the logic is shared with QApplicationPrivate::focusNextPrevChild_helper
-*/
-QWidget *QGraphicsProxyWidgetPrivate::findFocusChild(QWidget *child, bool next) const
-{
- if (!widget)
- return 0;
-
- // Run around the focus chain until we find a widget that can take tab focus.
- if (!child) {
- child = next ? (QWidget *)widget : widget->d_func()->focus_prev;
- } else {
- child = next ? child->d_func()->focus_next : child->d_func()->focus_prev;
- if ((next && child == widget) || (!next && child == widget->d_func()->focus_prev)) {
- return 0;
- }
- }
-
- QWidget *oldChild = child;
- uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
- do {
- if (child->isEnabled()
- && child->isVisibleTo(widget)
- && ((child->focusPolicy() & focus_flag) == focus_flag)
- && !(child->d_func()->extra && child->d_func()->extra->focus_proxy)) {
- return child;
- }
- child = next ? child->d_func()->focus_next : child->d_func()->focus_prev;
- } while (child != oldChild && !(next && child == widget) && !(!next && child == widget->d_func()->focus_prev));
- return 0;
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::_q_removeWidgetSlot()
-{
- Q_Q(QGraphicsProxyWidget);
- widget = 0;
- delete q;
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::updateWidgetGeometryFromProxy()
-{
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::updateProxyGeometryFromWidget()
-{
- Q_Q(QGraphicsProxyWidget);
- if (!widget)
- return;
-
- QRectF widgetGeometry = widget->geometry();
- QWidget *parentWidget = widget->parentWidget();
- if (widget->isWindow()) {
- QGraphicsProxyWidget *proxyParent = 0;
- if (parentWidget && (proxyParent = qobject_cast<QGraphicsProxyWidget *>(q->parentWidget()))) {
- // Nested window proxy (e.g., combobox popup), map widget to the
- // parent widget's global coordinates, and map that to the parent
- // proxy's child coordinates.
- widgetGeometry.moveTo(proxyParent->subWidgetRect(parentWidget).topLeft()
- + parentWidget->mapFromGlobal(widget->pos()));
- }
- }
-
- // Adjust to size hint if the widget has never been resized.
- if (!widget->size().isValid())
- widgetGeometry.setSize(widget->sizeHint());
-
- // Assign new geometry.
- posChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- sizeChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- q->setGeometry(widgetGeometry);
- posChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- sizeChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
-}
-
-/*!
- \internal
-*/
-void QGraphicsProxyWidgetPrivate::updateProxyInputMethodAcceptanceFromWidget()
-{
- Q_Q(QGraphicsProxyWidget);
- if (!widget)
- return;
-
- QWidget *focusWidget = widget->focusWidget();
- if (!focusWidget)
- focusWidget = widget;
- q->setFlag(QGraphicsItem::ItemAcceptsInputMethod,
- focusWidget->testAttribute(Qt::WA_InputMethodEnabled));
-}
-
-/*!
- \internal
-
- Embeds \a subWin as a subwindow of this proxy widget. \a subWin must be a top-level
- widget and a descendant of the widget managed by this proxy. A separate subproxy
- will be created as a child of this proxy widget to manage \a subWin.
-*/
-void QGraphicsProxyWidgetPrivate::embedSubWindow(QWidget *subWin)
-{
- QWExtra *extra;
- if (!((extra = subWin->d_func()->extra) && extra->proxyWidget)) {
- QGraphicsProxyWidget *subProxy = new QGraphicsProxyWidget(q_func(), subWin->windowFlags());
- subProxy->d_func()->setWidget_helper(subWin, false);
- }
-}
-
-/*!
- \internal
-
- Removes ("unembeds") \a subWin and deletes the proxy holder item. This can
- happen when QWidget::setParent() reparents the embedded window out of
- "embedded space".
-*/
-void QGraphicsProxyWidgetPrivate::unembedSubWindow(QWidget *subWin)
-{
- foreach (QGraphicsItem *child, children) {
- if (child->isWidget()) {
- if (QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(child))) {
- if (proxy->widget() == subWin) {
- proxy->setWidget(0);
- scene->removeItem(proxy);
- delete proxy;
- return;
- }
- }
- }
- }
-}
-
-bool QGraphicsProxyWidgetPrivate::isProxyWidget() const
-{
- return true;
-}
-
-/*!
- \internal
-*/
-QPointF QGraphicsProxyWidgetPrivate::mapToReceiver(const QPointF &pos, const QWidget *receiver) const
-{
- QPointF p = pos;
- // Map event position from us to the receiver, preserving its
- // precision (don't use QWidget::mapFrom here).
- while (receiver && receiver != widget) {
- p -= QPointF(receiver->pos());
- receiver = receiver->parentWidget();
- }
- return p;
-}
-
-/*!
- Constructs a new QGraphicsProxy widget. \a parent and \a wFlags are passed
- to QGraphicsItem's constructor.
-*/
-QGraphicsProxyWidget::QGraphicsProxyWidget(QGraphicsItem *parent, Qt::WindowFlags wFlags)
- : QGraphicsWidget(*new QGraphicsProxyWidgetPrivate, parent, 0, wFlags)
-{
- Q_D(QGraphicsProxyWidget);
- d->init();
-}
-
-/*!
- Destroys the proxy widget and any embedded widget.
-*/
-QGraphicsProxyWidget::~QGraphicsProxyWidget()
-{
- Q_D(QGraphicsProxyWidget);
- if (d->widget) {
- QObject::disconnect(d->widget, SIGNAL(destroyed()), this, SLOT(_q_removeWidgetSlot()));
- delete d->widget;
- }
-}
-
-/*!
- Embeds \a widget into this proxy widget. The embedded widget must reside
- exclusively either inside or outside of Graphics View. You cannot embed a
- widget as long as it is is visible elsewhere in the UI, at the same time.
-
- \a widget must be a top-level widget whose parent is 0.
-
- When the widget is embedded, its state (e.g., visible, enabled, geometry,
- size hints) is copied into the proxy widget. If the embedded widget is
- explicitly hidden or disabled, the proxy widget will become explicitly
- hidden or disabled after embedding is complete. The class documentation
- has a full overview over the shared state.
-
- QGraphicsProxyWidget's window flags determine whether the widget, after
- embedding, will be given window decorations or not.
-
- After this function returns, QGraphicsProxyWidget will keep its state
- synchronized with that of \a widget whenever possible.
-
- If a widget is already embedded by this proxy when this function is
- called, that widget will first be automatically unembedded. Passing 0 for
- the \a widget argument will only unembed the widget, and the ownership of
- the currently embedded widget will be passed on to the caller.
- Every child widget that are embedded will also be embedded and their proxy
- widget destroyed.
-
- Note that widgets with the Qt::WA_PaintOnScreen widget attribute
- set and widgets that wrap an external application or controller
- cannot be embedded. Examples are QGLWidget and QAxWidget.
-
- \sa widget()
-*/
-void QGraphicsProxyWidget::setWidget(QWidget *widget)
-{
- Q_D(QGraphicsProxyWidget);
- d->setWidget_helper(widget, true);
-}
-
-void QGraphicsProxyWidgetPrivate::setWidget_helper(QWidget *newWidget, bool autoShow)
-{
- Q_Q(QGraphicsProxyWidget);
- if (newWidget == widget)
- return;
- if (widget) {
- QObject::disconnect(widget, SIGNAL(destroyed()), q, SLOT(_q_removeWidgetSlot()));
- widget->removeEventFilter(q);
- widget->setAttribute(Qt::WA_DontShowOnScreen, false);
- widget->d_func()->extra->proxyWidget = 0;
- resolveFont(inheritedFontResolveMask);
- resolvePalette(inheritedPaletteResolveMask);
- widget->update();
-
- foreach (QGraphicsItem *child, q->childItems()) {
- if (child->d_ptr->isProxyWidget()) {
- QGraphicsProxyWidget *childProxy = static_cast<QGraphicsProxyWidget *>(child);
- QWidget * parent = childProxy->widget();
- while (parent->parentWidget() != 0) {
- if (parent == widget)
- break;
- parent = parent->parentWidget();
- }
- if (!childProxy->widget() || parent != widget)
- continue;
- childProxy->setWidget(0);
- delete childProxy;
- }
- }
-
- widget = 0;
-#ifndef QT_NO_CURSOR
- q->unsetCursor();
-#endif
- q->setAcceptHoverEvents(false);
- if (!newWidget)
- q->update();
- }
- if (!newWidget)
- return;
- if (!newWidget->isWindow()) {
- QWExtra *extra = newWidget->parentWidget()->d_func()->extra;
- if (!extra || !extra->proxyWidget) {
- qWarning("QGraphicsProxyWidget::setWidget: cannot embed widget %p "
- "which is not a toplevel widget, and is not a child of an embedded widget", newWidget);
- return;
- }
- }
-
- // Register this proxy within the widget's private.
- // ### This is a bit backdoorish
- QWExtra *extra = newWidget->d_func()->extra;
- if (!extra) {
- newWidget->d_func()->createExtra();
- extra = newWidget->d_func()->extra;
- }
- QGraphicsProxyWidget **proxyWidget = &extra->proxyWidget;
- if (*proxyWidget) {
- if (*proxyWidget != q) {
- qWarning("QGraphicsProxyWidget::setWidget: cannot embed widget %p"
- "; already embedded", newWidget);
- }
- return;
- }
- *proxyWidget = q;
-
- newWidget->setAttribute(Qt::WA_DontShowOnScreen);
- newWidget->ensurePolished();
- // Do not wait for this widget to close before the app closes ###
- // shouldn't this widget inherit the attribute?
- newWidget->setAttribute(Qt::WA_QuitOnClose, false);
- q->setAcceptHoverEvents(true);
-
- if (newWidget->testAttribute(Qt::WA_NoSystemBackground))
- q->setAttribute(Qt::WA_NoSystemBackground);
- if (newWidget->testAttribute(Qt::WA_OpaquePaintEvent))
- q->setAttribute(Qt::WA_OpaquePaintEvent);
-
- widget = newWidget;
-
- // Changes only go from the widget to the proxy.
- enabledChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- visibleChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- posChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- sizeChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
-
- if ((autoShow && !newWidget->testAttribute(Qt::WA_WState_ExplicitShowHide)) || !newWidget->testAttribute(Qt::WA_WState_Hidden)) {
- newWidget->show();
- }
-
- // Copy the state from the widget onto the proxy.
-#ifndef QT_NO_CURSOR
- if (newWidget->testAttribute(Qt::WA_SetCursor))
- q->setCursor(widget->cursor());
-#endif
- q->setEnabled(newWidget->isEnabled());
- q->setVisible(newWidget->isVisible());
- q->setLayoutDirection(newWidget->layoutDirection());
- if (newWidget->testAttribute(Qt::WA_SetStyle))
- q->setStyle(widget->style());
-
- resolveFont(inheritedFontResolveMask);
- resolvePalette(inheritedPaletteResolveMask);
-
- if (!newWidget->testAttribute(Qt::WA_Resized))
- newWidget->adjustSize();
-
- int left, top, right, bottom;
- newWidget->getContentsMargins(&left, &top, &right, &bottom);
- q->setContentsMargins(left, top, right, bottom);
- q->setWindowTitle(newWidget->windowTitle());
-
- // size policies and constraints..
- q->setSizePolicy(newWidget->sizePolicy());
- QSize sz = newWidget->minimumSize();
- q->setMinimumSize(sz.isNull() ? QSizeF() : QSizeF(sz));
- sz = newWidget->maximumSize();
- q->setMaximumSize(sz.isNull() ? QSizeF() : QSizeF(sz));
-
- updateProxyGeometryFromWidget();
-
- updateProxyInputMethodAcceptanceFromWidget();
-
- // Hook up the event filter to keep the state up to date.
- newWidget->installEventFilter(q);
- QObject::connect(newWidget, SIGNAL(destroyed()), q, SLOT(_q_removeWidgetSlot()));
-
- // Changes no longer go only from the widget to the proxy.
- enabledChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- visibleChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- posChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- sizeChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
-}
-
-/*!
- Returns a pointer to the embedded widget.
-
- \sa setWidget()
-*/
-QWidget *QGraphicsProxyWidget::widget() const
-{
- Q_D(const QGraphicsProxyWidget);
- return d->widget;
-}
-
-/*!
- Returns the rectangle for \a widget, which must be a descendant of
- widget(), or widget() itself, in this proxy item's local coordinates.
-
- If no widget is embedded, \a widget is 0, or \a widget is not a
- descendant of the embedded widget, this function returns an empty QRectF.
-
- \sa widget()
-*/
-QRectF QGraphicsProxyWidget::subWidgetRect(const QWidget *widget) const
-{
- Q_D(const QGraphicsProxyWidget);
- if (!widget || !d->widget)
- return QRectF();
- if (d->widget == widget || d->widget->isAncestorOf(widget))
- return QRectF(widget->mapTo(d->widget, QPoint(0, 0)), widget->size());
- return QRectF();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::setGeometry(const QRectF &rect)
-{
- Q_D(QGraphicsProxyWidget);
- bool proxyResizesWidget = !d->posChangeMode && !d->sizeChangeMode;
- if (proxyResizesWidget) {
- d->posChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- d->sizeChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- }
- QGraphicsWidget::setGeometry(rect);
- if (proxyResizesWidget) {
- d->posChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- d->sizeChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
-}
-
-/*!
- \reimp
-*/
-QVariant QGraphicsProxyWidget::itemChange(GraphicsItemChange change,
- const QVariant &value)
-{
- Q_D(QGraphicsProxyWidget);
-
- switch (change) {
- case ItemPositionChange:
- // The item's position is either changed directly on the proxy, in
- // which case the position change should propagate to the widget,
- // otherwise it happens as a side effect when filtering QEvent::Move.
- if (!d->posChangeMode)
- d->posChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- break;
- case ItemPositionHasChanged:
- // Move the internal widget if we're in widget-to-proxy
- // mode. Otherwise the widget has already moved.
- if (d->widget && d->posChangeMode != QGraphicsProxyWidgetPrivate::WidgetToProxyMode)
- d->widget->move(value.toPoint());
- if (d->posChangeMode == QGraphicsProxyWidgetPrivate::ProxyToWidgetMode)
- d->posChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- break;
- case ItemVisibleChange:
- if (!d->visibleChangeMode)
- d->visibleChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- break;
- case ItemVisibleHasChanged:
- if (d->widget && d->visibleChangeMode != QGraphicsProxyWidgetPrivate::WidgetToProxyMode)
- d->widget->setVisible(isVisible());
- if (d->visibleChangeMode == QGraphicsProxyWidgetPrivate::ProxyToWidgetMode)
- d->visibleChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- break;
- case ItemEnabledChange:
- if (!d->enabledChangeMode)
- d->enabledChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- break;
- case ItemEnabledHasChanged:
- if (d->widget && d->enabledChangeMode != QGraphicsProxyWidgetPrivate::WidgetToProxyMode)
- d->widget->setEnabled(isEnabled());
- if (d->enabledChangeMode == QGraphicsProxyWidgetPrivate::ProxyToWidgetMode)
- d->enabledChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- break;
- default:
- break;
- }
- return QGraphicsWidget::itemChange(change, value);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsProxyWidget::event(QEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
- if (!d->widget)
- return QGraphicsWidget::event(event);
-
- switch (event->type()) {
- case QEvent::StyleChange:
- // Propagate style changes to the embedded widget.
- if (!d->styleChangeMode) {
- d->styleChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- d->widget->setStyle(style());
- d->styleChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
- break;
- case QEvent::FontChange: {
- // Propagate to widget.
- QWidgetPrivate *wd = d->widget->d_func();
- int mask = d->font.resolve() | d->inheritedFontResolveMask;
- wd->inheritedFontResolveMask = mask;
- wd->resolveFont();
- break;
- }
- case QEvent::PaletteChange: {
- // Propagate to widget.
- QWidgetPrivate *wd = d->widget->d_func();
- int mask = d->palette.resolve() | d->inheritedPaletteResolveMask;
- wd->inheritedPaletteResolveMask = mask;
- wd->resolvePalette();
- break;
- }
- case QEvent::InputMethod: {
- // Forward input method events if the focus widget enables
- // input methods.
- // ### Qt 4.5: this code must also go into a reimplementation
- // of inputMethodEvent().
- QWidget *focusWidget = d->widget->focusWidget();
- if (focusWidget && focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
- QApplication::sendEvent(focusWidget, event);
- break;
- }
- case QEvent::ShortcutOverride: {
- QWidget *focusWidget = d->widget->focusWidget();
- while (focusWidget) {
- QApplication::sendEvent(focusWidget, event);
- if (event->isAccepted())
- return true;
- focusWidget = focusWidget->parentWidget();
- }
- return false;
- }
- case QEvent::KeyPress: {
- QKeyEvent *k = static_cast<QKeyEvent *>(event);
- if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
- if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
- QWidget *focusWidget = d->widget->focusWidget();
- while (focusWidget) {
- bool res = QApplication::sendEvent(focusWidget, event);
- if ((res && event->isAccepted()) || (isWindow() && focusWidget == d->widget)) {
- event->accept();
- break;
- }
- focusWidget = focusWidget->parentWidget();
- }
- return true;
- }
- }
- break;
- }
-#ifndef QT_NO_TOOLTIP
- case QEvent::GraphicsSceneHelp: {
- // Propagate the help event (for tooltip) to the widget under mouse
- if (d->lastWidgetUnderMouse) {
- QGraphicsSceneHelpEvent *he = static_cast<QGraphicsSceneHelpEvent *>(event);
- QPoint pos = d->mapToReceiver(mapFromScene(he->scenePos()), d->lastWidgetUnderMouse).toPoint();
- QHelpEvent e(QEvent::ToolTip, pos, he->screenPos());
- QApplication::sendEvent(d->lastWidgetUnderMouse, &e);
- event->setAccepted(e.isAccepted());
- return e.isAccepted();
- }
- break;
- }
- case QEvent::ToolTipChange: {
- // Propagate tooltip change to the widget
- if (!d->tooltipChangeMode) {
- d->tooltipChangeMode = QGraphicsProxyWidgetPrivate::ProxyToWidgetMode;
- d->widget->setToolTip(toolTip());
- d->tooltipChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
- break;
- }
-#endif
- default:
- break;
- }
- return QGraphicsWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsProxyWidget::eventFilter(QObject *object, QEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-
- if (object == d->widget) {
- switch (event->type()) {
- case QEvent::LayoutRequest:
- updateGeometry();
- break;
- case QEvent::Resize:
- // If the widget resizes itself, we resize the proxy too.
- // Prevent feed-back by checking the geometry change mode.
- if (!d->sizeChangeMode)
- d->updateProxyGeometryFromWidget();
- break;
- case QEvent::Move:
- // If the widget moves itself, we move the proxy too. Prevent
- // feed-back by checking the geometry change mode.
- if (!d->posChangeMode)
- d->updateProxyGeometryFromWidget();
- break;
- case QEvent::Hide:
- case QEvent::Show:
- // If the widget toggles its visible state, the proxy will follow.
- if (!d->visibleChangeMode) {
- d->visibleChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- setVisible(event->type() == QEvent::Show);
- d->visibleChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
- break;
- case QEvent::EnabledChange:
- // If the widget toggles its enabled state, the proxy will follow.
- if (!d->enabledChangeMode) {
- d->enabledChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- setEnabled(d->widget->isEnabled());
- d->enabledChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
- break;
- case QEvent::StyleChange:
- // Propagate style changes to the proxy.
- if (!d->styleChangeMode) {
- d->styleChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- setStyle(d->widget->style());
- d->styleChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
- break;
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTipChange:
- // Propagate tooltip change to the proxy.
- if (!d->tooltipChangeMode) {
- d->tooltipChangeMode = QGraphicsProxyWidgetPrivate::WidgetToProxyMode;
- setToolTip(d->widget->toolTip());
- d->tooltipChangeMode = QGraphicsProxyWidgetPrivate::NoMode;
- }
- break;
-#endif
- default:
- break;
- }
- }
- return QGraphicsWidget::eventFilter(object, event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::showEvent(QShowEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::hideEvent(QHideEvent *event)
-{
- Q_UNUSED(event);
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
- if (!event || !d->widget || !d->widget->isVisible() || !hasFocus())
- return;
-
- // Find widget position and receiver.
- QPointF pos = event->pos();
- QPointer<QWidget> alienWidget = d->widget->childAt(pos.toPoint());
- QPointer<QWidget> receiver = alienWidget ? alienWidget : d->widget;
-
- // Map event position from us to the receiver
- pos = d->mapToReceiver(pos, receiver);
-
- QPoint globalPos = receiver->mapToGlobal(pos.toPoint());
- //If the receiver by-pass the proxy its popups
- //will be top level QWidgets therefore they need
- //the screen position. mapToGlobal expect the widget to
- //have proper coordinates in regards of the windowing system
- //but it's not true because the widget is embedded.
- if (bypassGraphicsProxyWidget(receiver))
- globalPos = event->screenPos();
-
- // Send mouse event. ### Doesn't propagate the event.
- QContextMenuEvent contextMenuEvent(QContextMenuEvent::Reason(event->reason()),
- pos.toPoint(), globalPos, event->modifiers());
- QApplication::sendEvent(receiver, &contextMenuEvent);
-
- event->setAccepted(contextMenuEvent.isAccepted());
-}
-#endif // QT_NO_CONTEXTMENU
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
-{
-#ifdef QT_NO_DRAGANDDROP
- Q_UNUSED(event);
-#else
- Q_D(QGraphicsProxyWidget);
- if (!d->widget)
- return;
-
- QDragEnterEvent proxyDragEnter(event->pos().toPoint(), event->dropAction(), event->mimeData(), event->buttons(), event->modifiers());
- proxyDragEnter.setAccepted(event->isAccepted());
- QApplication::sendEvent(d->widget, &proxyDragEnter);
- event->setAccepted(proxyDragEnter.isAccepted());
- if (proxyDragEnter.isAccepted()) // we discard answerRect
- event->setDropAction(proxyDragEnter.dropAction());
-#endif
-}
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_UNUSED(event);
-#ifndef QT_NO_DRAGANDDROP
- Q_D(QGraphicsProxyWidget);
- if (!d->widget || !d->dragDropWidget)
- return;
- QDragLeaveEvent proxyDragLeave;
- QApplication::sendEvent(d->dragDropWidget, &proxyDragLeave);
- d->dragDropWidget = 0;
-#endif
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
-{
-#ifdef QT_NO_DRAGANDDROP
- Q_UNUSED(event);
-#else
- Q_D(QGraphicsProxyWidget);
- if (!d->widget)
- return;
- QPointF p = event->pos();
- event->ignore();
- QPointer<QWidget> subWidget = d->widget->childAt(p.toPoint());
- QPointer<QWidget> receiver = subWidget ? subWidget : d->widget;
- bool eventDelivered = false;
- for (; receiver; receiver = receiver->parentWidget()) {
- if (!receiver->isEnabled() || !receiver->acceptDrops())
- continue;
- // Map event position from us to the receiver
- QPoint receiverPos = d->mapToReceiver(p, receiver).toPoint();
- if (receiver != d->dragDropWidget) {
- // Try to enter before we leave
- QDragEnterEvent dragEnter(receiverPos, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
- dragEnter.setDropAction(event->proposedAction());
- QApplication::sendEvent(receiver, &dragEnter);
- event->setAccepted(dragEnter.isAccepted());
- event->setDropAction(dragEnter.dropAction());
- if (!event->isAccepted()) {
- // propagate to the parent widget
- continue;
- }
-
- d->lastDropAction = event->dropAction();
-
- if (d->dragDropWidget) {
- QDragLeaveEvent dragLeave;
- QApplication::sendEvent(d->dragDropWidget, &dragLeave);
- }
- d->dragDropWidget = receiver;
- }
-
- QDragMoveEvent dragMove(receiverPos, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
- event->setDropAction(d->lastDropAction);
- QApplication::sendEvent(receiver, &dragMove);
- event->setAccepted(dragMove.isAccepted());
- event->setDropAction(dragMove.dropAction());
- if (event->isAccepted())
- d->lastDropAction = event->dropAction();
- eventDelivered = true;
- break;
- }
-
- if (!eventDelivered) {
- if (d->dragDropWidget) {
- // Leave the last drag drop item
- QDragLeaveEvent dragLeave;
- QApplication::sendEvent(d->dragDropWidget, &dragLeave);
- d->dragDropWidget = 0;
- }
- // Propagate
- event->setDropAction(Qt::IgnoreAction);
- }
-#endif
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::dropEvent(QGraphicsSceneDragDropEvent *event)
-{
-#ifdef QT_NO_DRAGANDDROP
- Q_UNUSED(event);
-#else
- Q_D(QGraphicsProxyWidget);
- if (d->widget && d->dragDropWidget) {
- QPoint widgetPos = d->mapToReceiver(event->pos(), d->dragDropWidget).toPoint();
- QDropEvent dropEvent(widgetPos, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
- QApplication::sendEvent(d->dragDropWidget, &dropEvent);
- event->setAccepted(dropEvent.isAccepted());
- d->dragDropWidget = 0;
- }
-#endif
-}
-#endif
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
- Q_D(QGraphicsProxyWidget);
- // If hoverMove was compressed away, make sure we update properly here.
- if (d->lastWidgetUnderMouse) {
- QApplicationPrivate::dispatchEnterLeave(0, d->lastWidgetUnderMouse);
- d->lastWidgetUnderMouse = 0;
- }
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::hoverMoveEvent";
-#endif
- // Ignore events on the window frame.
- if (!d->widget || !rect().contains(event->pos())) {
- if (d->lastWidgetUnderMouse) {
- QApplicationPrivate::dispatchEnterLeave(0, d->lastWidgetUnderMouse);
- d->lastWidgetUnderMouse = 0;
- }
- return;
- }
-
- d->embeddedMouseGrabber = 0;
- d->sendWidgetMouseEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::grabMouseEvent(QEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::ungrabMouseEvent(QEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
- Q_UNUSED(event);
- d->embeddedMouseGrabber = 0;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::mouseMoveEvent";
-#endif
- d->sendWidgetMouseEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::mousePressEvent";
-#endif
- d->sendWidgetMouseEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::mouseDoubleClickEvent";
-#endif
- d->sendWidgetMouseEvent(event);
-}
-
-/*!
- \reimp
-*/
-#ifndef QT_NO_WHEELEVENT
-void QGraphicsProxyWidget::wheelEvent(QGraphicsSceneWheelEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::wheelEvent";
-#endif
- if (!d->widget)
- return;
-
- QPointF pos = event->pos();
- QPointer<QWidget> receiver = d->widget->childAt(pos.toPoint());
- if (!receiver)
- receiver = d->widget;
-
- // Map event position from us to the receiver
- pos = d->mapToReceiver(pos, receiver);
-
- // Send mouse event.
- QWheelEvent wheelEvent(pos.toPoint(), event->screenPos(), event->delta(),
- event->buttons(), event->modifiers(), event->orientation());
- QPointer<QWidget> focusWidget = d->widget->focusWidget();
- extern bool qt_sendSpontaneousEvent(QObject *, QEvent *);
- qt_sendSpontaneousEvent(receiver, &wheelEvent);
- event->setAccepted(wheelEvent.isAccepted());
-
- // ### Remove, this should be done by proper focusIn/focusOut events.
- if (focusWidget && !focusWidget->hasFocus()) {
- focusWidget->update();
- focusWidget = d->widget->focusWidget();
- if (focusWidget && focusWidget->hasFocus())
- focusWidget->update();
- }
-}
-#endif
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::mouseReleaseEvent";
-#endif
- d->sendWidgetMouseEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::keyPressEvent";
-#endif
- d->sendWidgetKeyEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::keyReleaseEvent(QKeyEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::keyReleaseEvent";
-#endif
- d->sendWidgetKeyEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::focusInEvent(QFocusEvent *event)
-{
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::focusInEvent";
-#endif
- Q_D(QGraphicsProxyWidget);
-
- if (d->focusFromWidgetToProxy) {
- // Prevent recursion when the proxy autogains focus through the
- // embedded widget calling setFocus(). ### Could be done with event
- // filter on FocusIn instead?
- return;
- }
-
- d->proxyIsGivingFocus = true;
-
- switch (event->reason()) {
- case Qt::TabFocusReason: {
- if (QWidget *focusChild = d->findFocusChild(0, true))
- focusChild->setFocus(event->reason());
- break;
- }
- case Qt::BacktabFocusReason:
- if (QWidget *focusChild = d->findFocusChild(0, false))
- focusChild->setFocus(event->reason());
- break;
- default:
- if (d->widget && d->widget->focusWidget()) {
- d->widget->focusWidget()->setFocus(event->reason());
- }
- break;
- }
-
- d->proxyIsGivingFocus = false;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::focusOutEvent(QFocusEvent *event)
-{
-#ifdef GRAPHICSPROXYWIDGET_DEBUG
- qDebug() << "QGraphicsProxyWidget::focusOutEvent";
-#endif
- Q_D(QGraphicsProxyWidget);
- if (d->widget) {
- // We need to explicitly remove subfocus from the embedded widget's
- // focus widget.
- if (QWidget *focusWidget = d->widget->focusWidget())
- d->removeSubFocusHelper(focusWidget, event->reason());
- }
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsProxyWidget::focusNextPrevChild(bool next)
-{
- Q_D(QGraphicsProxyWidget);
- if (!d->widget || !d->scene)
- return QGraphicsWidget::focusNextPrevChild(next);
-
- Qt::FocusReason reason = next ? Qt::TabFocusReason : Qt::BacktabFocusReason;
- QWidget *lastFocusChild = d->widget->focusWidget();
- if (QWidget *newFocusChild = d->findFocusChild(lastFocusChild, next)) {
- newFocusChild->setFocus(reason);
- return true;
- }
-
- return QGraphicsWidget::focusNextPrevChild(next);
-}
-
-/*!
- \reimp
-*/
-QSizeF QGraphicsProxyWidget::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- Q_D(const QGraphicsProxyWidget);
- if (!d->widget)
- return QGraphicsWidget::sizeHint(which, constraint);
-
- QSizeF sh;
- switch (which) {
- case Qt::PreferredSize:
- if (QLayout *l = d->widget->layout())
- sh = l->sizeHint();
- else
- sh = d->widget->sizeHint();
- break;
- case Qt::MinimumSize:
- if (QLayout *l = d->widget->layout())
- sh = l->minimumSize();
- else
- sh = d->widget->minimumSizeHint();
- break;
- case Qt::MaximumSize:
- if (QLayout *l = d->widget->layout())
- sh = l->maximumSize();
- else
- sh = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
- break;
- case Qt::MinimumDescent:
- sh = constraint;
- break;
- default:
- break;
- }
- return sh;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
-{
- Q_D(QGraphicsProxyWidget);
- if (d->widget) {
- if (d->sizeChangeMode != QGraphicsProxyWidgetPrivate::WidgetToProxyMode)
- d->widget->resize(event->newSize().toSize());
- }
- QGraphicsWidget::resizeEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsProxyWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- Q_D(QGraphicsProxyWidget);
- Q_UNUSED(widget);
- if (!d->widget || !d->widget->isVisible())
- return;
-
- // Filter out repaints on the window frame.
- const QRect exposedWidgetRect = (option->exposedRect & rect()).toAlignedRect();
- if (exposedWidgetRect.isEmpty())
- return;
-
- // Disable QPainter's default pen being cosmetic. This allows widgets and
- // styles to follow Qt's existing defaults without getting ugly cosmetic
- // lines when scaled.
- bool restore = !(painter->renderHints() & QPainter::NonCosmeticDefaultPen);
- painter->setRenderHints(QPainter::NonCosmeticDefaultPen, true);
-
- d->widget->render(painter, exposedWidgetRect.topLeft(), exposedWidgetRect);
-
- // Restore the render hints if necessary.
- if (restore)
- painter->setRenderHints(QPainter::NonCosmeticDefaultPen, false);
-}
-
-/*!
- \reimp
-*/
-int QGraphicsProxyWidget::type() const
-{
- return Type;
-}
-
-/*!
- \since 4.5
-
- Creates a proxy widget for the given \a child of the widget
- contained in this proxy.
-
- This function makes it possible to acquire proxies for
- non top-level widgets. For instance, you can embed a dialog,
- and then transform only one of its widgets.
-
- If the widget is already embedded, return the existing proxy widget.
-
- \sa newProxyWidget(), QGraphicsScene::addWidget()
-*/
-QGraphicsProxyWidget *QGraphicsProxyWidget::createProxyForChildWidget(QWidget *child)
-{
- QGraphicsProxyWidget *proxy = child->graphicsProxyWidget();
- if (proxy)
- return proxy;
- if (!child->parentWidget()) {
- qWarning("QGraphicsProxyWidget::createProxyForChildWidget: top-level widget not in a QGraphicsScene");
- return 0;
- }
-
- QGraphicsProxyWidget *parentProxy = createProxyForChildWidget(child->parentWidget());
- if (!parentProxy)
- return 0;
-
- if (!QMetaObject::invokeMethod(parentProxy, "newProxyWidget", Qt::DirectConnection,
- Q_RETURN_ARG(QGraphicsProxyWidget*, proxy), Q_ARG(const QWidget*, child)))
- return 0;
- proxy->setParent(parentProxy);
- proxy->setWidget(child);
- return proxy;
-}
-
-/*!
- \fn QGraphicsProxyWidget *QGraphicsProxyWidget::newProxyWidget(const QWidget *child)
- \since 4.5
-
- Creates a proxy widget for the given \a child of the widget contained in this
- proxy.
-
- You should not call this function directly; use
- QGraphicsProxyWidget::createProxyForChildWidget() instead.
-
- This function is a fake virtual slot that you can reimplement in
- your subclass in order to control how new proxy widgets are
- created. The default implementation returns a proxy created with
- the QGraphicsProxyWidget() constructor with this proxy widget as
- the parent.
-
- \sa createProxyForChildWidget()
-*/
-QGraphicsProxyWidget *QGraphicsProxyWidget::newProxyWidget(const QWidget *)
-{
- return new QGraphicsProxyWidget(this);
-}
-
-
-
-QT_END_NAMESPACE
-
-#include "moc_qgraphicsproxywidget.cpp"
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsproxywidget.h b/src/gui/graphicsview/qgraphicsproxywidget.h
deleted file mode 100644
index b2ffe2f7d1..0000000000
--- a/src/gui/graphicsview/qgraphicsproxywidget.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSPROXYWIDGET_H
-#define QGRAPHICSPROXYWIDGET_H
-
-#include <QtGui/qgraphicswidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsProxyWidgetPrivate;
-
-class Q_GUI_EXPORT QGraphicsProxyWidget : public QGraphicsWidget
-{
- Q_OBJECT
-public:
- QGraphicsProxyWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
- ~QGraphicsProxyWidget();
-
- void setWidget(QWidget *widget);
- QWidget *widget() const;
-
- QRectF subWidgetRect(const QWidget *widget) const;
-
- void setGeometry(const QRectF &rect);
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
-
- enum {
- Type = 12
- };
- int type() const;
-
- QGraphicsProxyWidget *createProxyForChildWidget(QWidget *child);
-
-protected:
- QVariant itemChange(GraphicsItemChange change, const QVariant &value);
-
- bool event(QEvent *event);
- bool eventFilter(QObject *object, QEvent *event);
-
- void showEvent(QShowEvent *event);
- void hideEvent(QHideEvent *event);
-
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
-#endif
-
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
- void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
- void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
- void dropEvent(QGraphicsSceneDragDropEvent *event);
-#endif
-
- void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
- void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
- void grabMouseEvent(QEvent *event);
- void ungrabMouseEvent(QEvent *event);
-
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- void mousePressEvent(QGraphicsSceneMouseEvent *event);
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QGraphicsSceneWheelEvent *event);
-#endif
-
- void keyPressEvent(QKeyEvent *event);
- void keyReleaseEvent(QKeyEvent *event);
-
- void focusInEvent(QFocusEvent *event);
- void focusOutEvent(QFocusEvent *event);
- bool focusNextPrevChild(bool next);
- // ### Qt 4.5:
- // QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
- // void inputMethodEvent(QInputMethodEvent *event);
-
- QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
- void resizeEvent(QGraphicsSceneResizeEvent *event);
-
-protected Q_SLOTS:
- QGraphicsProxyWidget *newProxyWidget(const QWidget *);
-
-private:
- Q_DISABLE_COPY(QGraphicsProxyWidget)
- Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QGraphicsProxyWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_removeWidgetSlot())
-
- friend class QWidget;
- friend class QWidgetPrivate;
- friend class QGraphicsItem;
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
-
diff --git a/src/gui/graphicsview/qgraphicsproxywidget_p.h b/src/gui/graphicsview/qgraphicsproxywidget_p.h
deleted file mode 100644
index e1a96b0021..0000000000
--- a/src/gui/graphicsview/qgraphicsproxywidget_p.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSPROXYWIDGET_P_H
-#define QGRAPHICSPROXYWIDGET_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 "qgraphicsproxywidget.h"
-#include "private/qgraphicswidget_p.h"
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsProxyWidgetPrivate : public QGraphicsWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsProxyWidget)
-public:
- QGraphicsProxyWidgetPrivate()
- : dragDropWidget(0),
- posChangeMode(NoMode),
- sizeChangeMode(NoMode),
- visibleChangeMode(NoMode),
- enabledChangeMode(NoMode),
- styleChangeMode(NoMode),
- paletteChangeMode(NoMode),
- tooltipChangeMode(NoMode),
- focusFromWidgetToProxy(0)
- { }
- void init();
- void sendWidgetMouseEvent(QGraphicsSceneMouseEvent *event);
- void sendWidgetMouseEvent(QGraphicsSceneHoverEvent *event);
- void sendWidgetKeyEvent(QKeyEvent *event);
- void setWidget_helper(QWidget *widget, bool autoShow);
-
- QWidget *findFocusChild(QWidget *child, bool next) const;
- void removeSubFocusHelper(QWidget *widget, Qt::FocusReason reason);
-
- // ### Qt 5: Remove. Workaround for reimplementation added after Qt 4.4.
- QVariant inputMethodQueryHelper(Qt::InputMethodQuery query) const;
-
- void _q_removeWidgetSlot();
-
- void embedSubWindow(QWidget *);
- void unembedSubWindow(QWidget *);
-
- bool isProxyWidget() const;
-
- QPointer<QWidget> widget;
- QPointer<QWidget> lastWidgetUnderMouse;
- QPointer<QWidget> embeddedMouseGrabber;
- QWidget *dragDropWidget;
- Qt::DropAction lastDropAction;
-
- void updateWidgetGeometryFromProxy();
- void updateProxyGeometryFromWidget();
-
- void updateProxyInputMethodAcceptanceFromWidget();
-
- QPointF mapToReceiver(const QPointF &pos, const QWidget *receiver) const;
-
- enum ChangeMode {
- NoMode,
- ProxyToWidgetMode,
- WidgetToProxyMode
- };
- quint32 posChangeMode : 2;
- quint32 sizeChangeMode : 2;
- quint32 visibleChangeMode : 2;
- quint32 enabledChangeMode : 2;
- quint32 styleChangeMode : 2;
- quint32 paletteChangeMode : 2;
- quint32 tooltipChangeMode : 2;
- quint32 focusFromWidgetToProxy : 1;
- quint32 proxyIsGivingFocus : 1;
-};
-
-QT_END_NAMESPACE
-
-#endif
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp
deleted file mode 100644
index 0713d09296..0000000000
--- a/src/gui/graphicsview/qgraphicsscene.cpp
+++ /dev/null
@@ -1,6491 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsScene
- \brief The QGraphicsScene class provides a surface for managing a large
- number of 2D graphical items.
- \since 4.2
- \ingroup graphicsview-api
-
-
- The class serves as a container for QGraphicsItems. It is used together
- with QGraphicsView for visualizing graphical items, such as lines,
- rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
- part of the \l{Graphics View Framework}.
-
- QGraphicsScene also provides functionality that lets you efficiently
- determine both the location of items, and for determining what items are
- visible within an arbitrary area on the scene. With the QGraphicsView
- widget, you can either visualize the whole scene, or zoom in and view only
- parts of the scene.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 0
-
- Note that QGraphicsScene has no visual appearance of its own; it only
- manages the items. You need to create a QGraphicsView widget to visualize
- the scene.
-
- To add items to a scene, you start off by constructing a QGraphicsScene
- object. Then, you have two options: either add your existing QGraphicsItem
- objects by calling addItem(), or you can call one of the convenience
- functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
- addRect(), or addText(), which all return a pointer to the newly added item.
- The dimensions of the items added with these functions are relative to the
- item's coordinate system, and the items position is initialized to (0,
- 0) in the scene.
-
- You can then visualize the scene using QGraphicsView. When the scene
- changes, (e.g., when an item moves or is transformed) QGraphicsScene
- emits the changed() signal. To remove an item, call removeItem().
-
- QGraphicsScene uses an indexing algorithm to manage the location of items
- efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
- algorithm suitable for large scenes where most items remain static (i.e.,
- do not move around). You can choose to disable this index by calling
- setItemIndexMethod(). For more information about the available indexing
- algorithms, see the itemIndexMethod property.
-
- The scene's bounding rect is set by calling setSceneRect(). Items can be
- placed at any position on the scene, and the size of the scene is by
- default unlimited. The scene rect is used only for internal bookkeeping,
- maintaining the scene's item index. If the scene rect is unset,
- QGraphicsScene will use the bounding area of all items, as returned by
- itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
- relatively time consuming function, as it operates by collecting
- positional information for every item on the scene. Because of this, you
- should always set the scene rect when operating on large scenes.
-
- One of QGraphicsScene's greatest strengths is its ability to efficiently
- determine the location of items. Even with millions of items on the scene,
- the items() functions can determine the location of an item within few
- milliseconds. There are several overloads to items(): one that finds items
- at a certain position, one that finds items inside or intersecting with a
- polygon or a rectangle, and more. The list of returned items is sorted by
- stacking order, with the topmost item being the first item in the list.
- For convenience, there is also an itemAt() function that returns the
- topmost item at a given position.
-
- QGraphicsScene maintains selection information for the scene. To select
- items, call setSelectionArea(), and to clear the current selection, call
- clearSelection(). Call selectedItems() to get the list of all selected
- items.
-
- \section1 Event Handling and Propagation
-
- Another responsibility that QGraphicsScene has, is to propagate events
- from QGraphicsView. To send an event to a scene, you construct an event
- that inherits QEvent, and then send it using, for example,
- QApplication::sendEvent(). event() is responsible for dispatching
- the event to the individual items. Some common events are handled by
- convenience event handlers. For example, key press events are handled by
- keyPressEvent(), and mouse press events are handled by mousePressEvent().
-
- Key events are delivered to the \e {focus item}. To set the focus item,
- you can either call setFocusItem(), passing an item that accepts focus, or
- the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
- get the current focus item. For compatibility with widgets, the scene also
- maintains its own focus information. By default, the scene does not have
- focus, and all key events are discarded. If setFocus() is called, or if an
- item on the scene gains focus, the scene automatically gains focus. If the
- scene has focus, hasFocus() will return true, and key events will be
- forwarded to the focus item, if any. If the scene loses focus, (i.e.,
- someone calls clearFocus()) while an item has focus, the scene will
- maintain its item focus information, and once the scene regains focus, it
- will make sure the last focus item regains focus.
-
- For mouse-over effects, QGraphicsScene dispatches \e {hover
- events}. If an item accepts hover events (see
- QGraphicsItem::acceptHoverEvents()), it will receive a \l
- {QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
- its area. As the mouse continues moving inside the item's area,
- QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
- events. When the mouse leaves the item's area, the item will
- receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
-
- All mouse events are delivered to the current \e {mouse grabber}
- item. An item becomes the scene's mouse grabber if it accepts
- mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
- receives a mouse press. It stays the mouse grabber until it
- receives a mouse release when no other mouse buttons are
- pressed. You can call mouseGrabberItem() to determine what item is
- currently grabbing the mouse.
-
- \sa QGraphicsItem, QGraphicsView
-*/
-
-/*!
- \enum QGraphicsScene::SceneLayer
- \since 4.3
-
- This enum describes the rendering layers in a QGraphicsScene. When
- QGraphicsScene draws the scene contents, it renders each of these layers
- separately, in order.
-
- Each layer represents a flag that can be OR'ed together when calling
- functions such as invalidate() or QGraphicsView::invalidateScene().
-
- \value ItemLayer The item layer. QGraphicsScene renders all items are in
- this layer by calling the virtual function drawItems(). The item layer is
- drawn after the background layer, but before the foreground layer.
-
- \value BackgroundLayer The background layer. QGraphicsScene renders the
- scene's background in this layer by calling the virtual function
- drawBackground(). The background layer is drawn first of all layers.
-
- \value ForegroundLayer The foreground layer. QGraphicsScene renders the
- scene's foreground in this layer by calling the virtual function
- drawForeground(). The foreground layer is drawn last of all layers.
-
- \value AllLayers All layers; this value represents a combination of all
- three layers.
-
- \sa invalidate(), QGraphicsView::invalidateScene()
-*/
-
-/*!
- \enum QGraphicsScene::ItemIndexMethod
-
- This enum describes the indexing algorithms QGraphicsScene provides for
- managing positional information about items on the scene.
-
- \value BspTreeIndex A Binary Space Partitioning tree is applied. All
- QGraphicsScene's item location algorithms are of an order close to
- logarithmic complexity, by making use of binary search. Adding, moving and
- removing items is logarithmic. This approach is best for static scenes
- (i.e., scenes where most items do not move).
-
- \value NoIndex No index is applied. Item location is of linear complexity,
- as all items on the scene are searched. Adding, moving and removing items,
- however, is done in constant time. This approach is ideal for dynamic
- scenes, where many items are added, moved or removed continuously.
-
- \sa setItemIndexMethod(), bspTreeDepth
-*/
-
-#include "qgraphicsscene.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicsitem.h"
-#include "qgraphicsitem_p.h"
-#include "qgraphicslayout.h"
-#include "qgraphicsscene_p.h"
-#include "qgraphicssceneevent.h"
-#include "qgraphicsview.h"
-#include "qgraphicsview_p.h"
-#include "qgraphicswidget.h"
-#include "qgraphicswidget_p.h"
-#include "qgraphicssceneindex_p.h"
-#include "qgraphicsscenebsptreeindex_p.h"
-#include "qgraphicsscenelinearindex_p.h"
-
-#include <QtCore/qdebug.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qmath.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qset.h>
-#include <QtCore/qstack.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/QMetaMethod>
-#include <QtGui/qapplication.h>
-#include <QtGui/qdesktopwidget.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qgraphicslayout.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qgraphicswidget.h>
-#include <QtGui/qmatrix.h>
-#include <QtGui/qpaintengine.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qpixmapcache.h>
-#include <QtGui/qpolygon.h>
-#include <QtGui/qstyleoption.h>
-#include <QtGui/qtooltip.h>
-#include <QtGui/qtransform.h>
-#include <QtGui/qinputcontext.h>
-#include <QtGui/qgraphicseffect.h>
-#include <private/qapplication_p.h>
-#include <private/qobject_p.h>
-#ifdef Q_WS_X11
-#include <private/qt_x11_p.h>
-#endif
-#include <private/qgraphicseffect_p.h>
-#include <private/qgesturemanager_p.h>
-#include <private/qpathclipper_p.h>
-
-// #define GESTURE_DEBUG
-#ifndef GESTURE_DEBUG
-# define DEBUG if (0) qDebug
-#else
-# define DEBUG qDebug
-#endif
-
-QT_BEGIN_NAMESPACE
-
-bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
-
-static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
-{
- hover->setWidget(mouseEvent->widget());
- hover->setPos(mouseEvent->pos());
- hover->setScenePos(mouseEvent->scenePos());
- hover->setScreenPos(mouseEvent->screenPos());
- hover->setLastPos(mouseEvent->lastPos());
- hover->setLastScenePos(mouseEvent->lastScenePos());
- hover->setLastScreenPos(mouseEvent->lastScreenPos());
- hover->setModifiers(mouseEvent->modifiers());
- hover->setAccepted(mouseEvent->isAccepted());
-}
-
-/*!
- \internal
-*/
-QGraphicsScenePrivate::QGraphicsScenePrivate()
- : indexMethod(QGraphicsScene::BspTreeIndex),
- index(0),
- lastItemCount(0),
- hasSceneRect(false),
- dirtyGrowingItemsBoundingRect(true),
- updateAll(false),
- calledEmitUpdated(false),
- processDirtyItemsEmitted(false),
- needSortTopLevelItems(true),
- holesInTopLevelSiblingIndex(false),
- topLevelSequentialOrdering(true),
- scenePosDescendantsUpdatePending(false),
- stickyFocus(false),
- hasFocus(false),
- lastMouseGrabberItemHasImplicitMouseGrab(false),
- allItemsIgnoreHoverEvents(true),
- allItemsUseDefaultCursor(true),
- painterStateProtection(true),
- sortCacheEnabled(false),
- allItemsIgnoreTouchEvents(true),
- selectionChanging(0),
- rectAdjust(2),
- focusItem(0),
- lastFocusItem(0),
- passiveFocusItem(0),
- tabFocusFirst(0),
- activePanel(0),
- lastActivePanel(0),
- activationRefCount(0),
- childExplicitActivation(0),
- lastMouseGrabberItem(0),
- dragDropItem(0),
- enterWidget(0),
- lastDropAction(Qt::IgnoreAction),
- style(0)
-{
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::init()
-{
- Q_Q(QGraphicsScene);
-
- index = new QGraphicsSceneBspTreeIndex(q);
-
- // Keep this index so we can check for connected slots later on.
- changedSignalIndex = signalIndex("changed(QList<QRectF>)");
- processDirtyItemsIndex = q->metaObject()->indexOfSlot("_q_processDirtyItems()");
- polishItemsIndex = q->metaObject()->indexOfSlot("_q_polishItems()");
-
- qApp->d_func()->scene_list.append(q);
- q->update();
-}
-
-/*!
- \internal
-*/
-QGraphicsScenePrivate *QGraphicsScenePrivate::get(QGraphicsScene *q)
-{
- return q->d_func();
-}
-
-void QGraphicsScenePrivate::_q_emitUpdated()
-{
- Q_Q(QGraphicsScene);
- calledEmitUpdated = false;
-
- if (dirtyGrowingItemsBoundingRect) {
- if (!hasSceneRect) {
- const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
- growingItemsBoundingRect |= q->itemsBoundingRect();
- if (oldGrowingItemsBoundingRect != growingItemsBoundingRect)
- emit q->sceneRectChanged(growingItemsBoundingRect);
- }
- dirtyGrowingItemsBoundingRect = false;
- }
-
- // Ensure all views are connected if anything is connected. This disables
- // the optimization that items send updates directly to the views, but it
- // needs to happen in order to keep compatibility with the behavior from
- // Qt 4.4 and backward.
- if (isSignalConnected(changedSignalIndex)) {
- for (int i = 0; i < views.size(); ++i) {
- QGraphicsView *view = views.at(i);
- if (!view->d_func()->connectedToScene) {
- view->d_func()->connectedToScene = true;
- q->connect(q, SIGNAL(changed(QList<QRectF>)),
- views.at(i), SLOT(updateScene(QList<QRectF>)));
- }
- }
- } else {
- if (views.isEmpty()) {
- updateAll = false;
- return;
- }
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->processPendingUpdates();
- // It's important that we update all views before we dispatch, hence two for-loops.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->dispatchPendingUpdateRequests();
- return;
- }
-
- // Notify the changes to anybody interested.
- QList<QRectF> oldUpdatedRects;
- oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects;
- updateAll = false;
- updatedRects.clear();
- emit q->changed(oldUpdatedRects);
-}
-
-/*!
- \internal
-
- ### This function is almost identical to QGraphicsItemPrivate::addChild().
-*/
-void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item)
-{
- item->d_ptr->ensureSequentialSiblingIndex();
- needSortTopLevelItems = true; // ### maybe false
- item->d_ptr->siblingIndex = topLevelItems.size();
- topLevelItems.append(item);
-}
-
-/*!
- \internal
-
- ### This function is almost identical to QGraphicsItemPrivate::removeChild().
-*/
-void QGraphicsScenePrivate::unregisterTopLevelItem(QGraphicsItem *item)
-{
- if (!holesInTopLevelSiblingIndex)
- holesInTopLevelSiblingIndex = item->d_ptr->siblingIndex != topLevelItems.size() - 1;
- if (topLevelSequentialOrdering && !holesInTopLevelSiblingIndex)
- topLevelItems.removeAt(item->d_ptr->siblingIndex);
- else
- topLevelItems.removeOne(item);
- // NB! Do not use topLevelItems.removeAt(item->d_ptr->siblingIndex) because
- // the item is not guaranteed to be at the index after the list is sorted
- // (see ensureSortedTopLevelItems()).
- item->d_ptr->siblingIndex = -1;
- if (topLevelSequentialOrdering)
- topLevelSequentialOrdering = !holesInTopLevelSiblingIndex;
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::_q_polishItems()
-{
- if (unpolishedItems.isEmpty())
- return;
-
- const QVariant booleanTrueVariant(true);
- QGraphicsItem *item = 0;
- QGraphicsItemPrivate *itemd = 0;
- const int oldUnpolishedCount = unpolishedItems.count();
-
- for (int i = 0; i < oldUnpolishedCount; ++i) {
- item = unpolishedItems.at(i);
- if (!item)
- continue;
- itemd = item->d_ptr.data();
- itemd->pendingPolish = false;
- if (!itemd->explicitlyHidden) {
- item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant);
- item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant);
- }
- if (itemd->isWidget) {
- QEvent event(QEvent::Polish);
- QApplication::sendEvent((QGraphicsWidget *)item, &event);
- }
- }
-
- if (unpolishedItems.count() == oldUnpolishedCount) {
- // No new items were added to the vector.
- unpolishedItems.clear();
- } else {
- // New items were appended; keep them and remove the old ones.
- unpolishedItems.remove(0, oldUnpolishedCount);
- unpolishedItems.squeeze();
- QMetaObject::invokeMethod(q_ptr, "_q_polishItems", Qt::QueuedConnection);
- }
-}
-
-void QGraphicsScenePrivate::_q_processDirtyItems()
-{
- processDirtyItemsEmitted = false;
-
- if (updateAll) {
- Q_ASSERT(calledEmitUpdated);
- // No need for further processing (except resetting the dirty states).
- // The growingItemsBoundingRect is updated in _q_emitUpdated.
- for (int i = 0; i < topLevelItems.size(); ++i)
- resetDirtyItem(topLevelItems.at(i), /*recursive=*/true);
- return;
- }
-
- const bool wasPendingSceneUpdate = calledEmitUpdated;
- const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
-
- // Process items recursively.
- for (int i = 0; i < topLevelItems.size(); ++i)
- processDirtyItemsRecursive(topLevelItems.at(i));
-
- dirtyGrowingItemsBoundingRect = false;
- if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect)
- emit q_func()->sceneRectChanged(growingItemsBoundingRect);
-
- if (wasPendingSceneUpdate)
- return;
-
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->processPendingUpdates();
-
- if (calledEmitUpdated) {
- // We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive
- // and we cannot wait for the control to reach the eventloop before the
- // changed signal is emitted, so we emit it now.
- _q_emitUpdated();
- }
-
- // Immediately dispatch all pending update requests on the views.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->dispatchPendingUpdateRequests();
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::setScenePosItemEnabled(QGraphicsItem *item, bool enabled)
-{
- QGraphicsItem *p = item->d_ptr->parent;
- while (p) {
- p->d_ptr->scenePosDescendants = enabled;
- p = p->d_ptr->parent;
- }
- if (!enabled && !scenePosDescendantsUpdatePending) {
- scenePosDescendantsUpdatePending = true;
- QMetaObject::invokeMethod(q_func(), "_q_updateScenePosDescendants", Qt::QueuedConnection);
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::registerScenePosItem(QGraphicsItem *item)
-{
- scenePosItems.insert(item);
- setScenePosItemEnabled(item, true);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::unregisterScenePosItem(QGraphicsItem *item)
-{
- scenePosItems.remove(item);
- setScenePosItemEnabled(item, false);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::_q_updateScenePosDescendants()
-{
- foreach (QGraphicsItem *item, scenePosItems) {
- QGraphicsItem *p = item->d_ptr->parent;
- while (p) {
- p->d_ptr->scenePosDescendants = 1;
- p = p->d_ptr->parent;
- }
- }
- scenePosDescendantsUpdatePending = false;
-}
-
-/*!
- \internal
-
- Schedules an item for removal. This function leaves some stale indexes
- around in the BSP tree if called from the item's destructor; these will
- be cleaned up the next time someone triggers purgeRemovedItems().
-
- Note: This function might get called from QGraphicsItem's destructor. \a item is
- being destroyed, so we cannot call any pure virtual functions on it (such
- as boundingRect()). Also, it is unnecessary to update the item's own state
- in any way.
-*/
-void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
-{
- Q_Q(QGraphicsScene);
-
- // Clear focus on the item to remove any reference in the focusWidget chain.
- item->clearFocus();
-
- markDirty(item, QRectF(), /*invalidateChildren=*/false, /*force=*/false,
- /*ignoreOpacity=*/false, /*removingItemFromScene=*/true);
-
- if (item->d_ptr->inDestructor) {
- // The item is actually in its destructor, we call the special method in the index.
- index->deleteItem(item);
- } else {
- // Can potentially call item->boundingRect() (virtual function), that's why
- // we only can call this function if the item is not in its destructor.
- index->removeItem(item);
- }
-
- item->d_ptr->clearSubFocus();
-
- if (item->flags() & QGraphicsItem::ItemSendsScenePositionChanges)
- unregisterScenePosItem(item);
-
- QGraphicsScene *oldScene = item->d_func()->scene;
- item->d_func()->scene = 0;
-
- //We need to remove all children first because they might use their parent
- //attributes (e.g. sceneTransform).
- if (!item->d_ptr->inDestructor) {
- // Remove all children recursively
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- q->removeItem(item->d_ptr->children.at(i));
- }
-
- if (!item->d_ptr->inDestructor && item == tabFocusFirst) {
- QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
- widget->d_func()->fixFocusChainBeforeReparenting(0, oldScene, 0);
- }
-
- // Unregister focus proxy.
- item->d_ptr->resetFocusProxy();
-
- // Remove from parent, or unregister from toplevels.
- if (QGraphicsItem *parentItem = item->parentItem()) {
- if (parentItem->scene()) {
- Q_ASSERT_X(parentItem->scene() == q, "QGraphicsScene::removeItem",
- "Parent item's scene is different from this item's scene");
- item->setParentItem(0);
- }
- } else {
- unregisterTopLevelItem(item);
- }
-
- // Reset the mouse grabber and focus item data.
- if (item == focusItem)
- focusItem = 0;
- if (item == lastFocusItem)
- lastFocusItem = 0;
- if (item == passiveFocusItem)
- passiveFocusItem = 0;
- if (item == activePanel) {
- // ### deactivate...
- activePanel = 0;
- }
- if (item == lastActivePanel)
- lastActivePanel = 0;
-
- // Cancel active touches
- {
- QMap<int, QGraphicsItem *>::iterator it = itemForTouchPointId.begin();
- while (it != itemForTouchPointId.end()) {
- if (it.value() == item) {
- sceneCurrentTouchPoints.remove(it.key());
- it = itemForTouchPointId.erase(it);
- } else {
- ++it;
- }
- }
- }
-
- // Disable selectionChanged() for individual items
- ++selectionChanging;
- int oldSelectedItemsSize = selectedItems.size();
-
- // Update selected & hovered item bookkeeping
- selectedItems.remove(item);
- hoverItems.removeAll(item);
- cachedItemsUnderMouse.removeAll(item);
- if (item->d_ptr->pendingPolish) {
- const int unpolishedIndex = unpolishedItems.indexOf(item);
- if (unpolishedIndex != -1)
- unpolishedItems[unpolishedIndex] = 0;
- item->d_ptr->pendingPolish = false;
- }
- resetDirtyItem(item);
-
- //We remove all references of item from the sceneEventFilter arrays
- QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
- while (iterator != sceneEventFilters.end()) {
- if (iterator.value() == item || iterator.key() == item)
- iterator = sceneEventFilters.erase(iterator);
- else
- ++iterator;
- }
-
- if (item->isPanel() && item->isVisible() && item->panelModality() != QGraphicsItem::NonModal)
- leaveModal(item);
-
- // Reset the mouse grabber and focus item data.
- if (mouseGrabberItems.contains(item))
- ungrabMouse(item, /* item is dying */ item->d_ptr->inDestructor);
-
- // Reset the keyboard grabber
- if (keyboardGrabberItems.contains(item))
- ungrabKeyboard(item, /* item is dying */ item->d_ptr->inDestructor);
-
- // Reset the last mouse grabber item
- if (item == lastMouseGrabberItem)
- lastMouseGrabberItem = 0;
-
- // Reset the current drop item
- if (item == dragDropItem)
- dragDropItem = 0;
-
- // Reenable selectionChanged() for individual items
- --selectionChanging;
- if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
- emit q->selectionChanged();
-
-#ifndef QT_NO_GESTURES
- QHash<QGesture *, QGraphicsObject *>::iterator it;
- for (it = gestureTargets.begin(); it != gestureTargets.end();) {
- if (it.value() == item)
- it = gestureTargets.erase(it);
- else
- ++it;
- }
-
- QGraphicsObject *dummy = static_cast<QGraphicsObject *>(item);
- cachedTargetItems.removeOne(dummy);
- cachedItemGestures.remove(dummy);
- cachedAlreadyDeliveredGestures.remove(dummy);
-
- foreach (Qt::GestureType gesture, item->d_ptr->gestureContext.keys())
- ungrabGesture(item, gesture);
-#endif // QT_NO_GESTURES
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::setActivePanelHelper(QGraphicsItem *item, bool duringActivationEvent)
-{
- Q_Q(QGraphicsScene);
- if (item && item->scene() != q) {
- qWarning("QGraphicsScene::setActivePanel: item %p must be part of this scene",
- item);
- return;
- }
-
- // Ensure the scene has focus when we change panel activation.
- q->setFocus(Qt::ActiveWindowFocusReason);
-
- // Find the item's panel.
- QGraphicsItem *panel = item ? item->panel() : 0;
- lastActivePanel = panel ? activePanel : 0;
- if (panel == activePanel || (!q->isActive() && !duringActivationEvent))
- return;
-
- // Deactivate the last active panel.
- if (activePanel) {
- if (QGraphicsItem *fi = activePanel->focusItem()) {
- // Remove focus from the current focus item.
- if (fi == q->focusItem())
- q->setFocusItem(0, Qt::ActiveWindowFocusReason);
- }
-
- QEvent event(QEvent::WindowDeactivate);
- q->sendEvent(activePanel, &event);
- } else if (panel && !duringActivationEvent) {
- // Deactivate the scene if changing activation to a panel.
- QEvent event(QEvent::WindowDeactivate);
- foreach (QGraphicsItem *item, q->items()) {
- if (item->isVisible() && !item->isPanel() && !item->parentItem())
- q->sendEvent(item, &event);
- }
- }
-
- // Update activate state.
- activePanel = panel;
- QEvent event(QEvent::ActivationChange);
- QApplication::sendEvent(q, &event);
-
- // Activate
- if (panel) {
- QEvent event(QEvent::WindowActivate);
- q->sendEvent(panel, &event);
-
- // Set focus on the panel's focus item.
- if (QGraphicsItem *focusItem = panel->focusItem())
- focusItem->setFocus(Qt::ActiveWindowFocusReason);
- } else if (q->isActive()) {
- // Activate the scene
- QEvent event(QEvent::WindowActivate);
- foreach (QGraphicsItem *item, q->items()) {
- if (item->isVisible() && !item->isPanel() && !item->parentItem())
- q->sendEvent(item, &event);
- }
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::setFocusItemHelper(QGraphicsItem *item,
- Qt::FocusReason focusReason)
-{
- Q_Q(QGraphicsScene);
- if (item == focusItem)
- return;
-
- // Clear focus if asked to set focus on something that can't
- // accept input focus.
- if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
- || !item->isVisible() || !item->isEnabled())) {
- item = 0;
- }
-
- // Set focus on the scene if an item requests focus.
- if (item) {
- q->setFocus(focusReason);
- if (item == focusItem)
- return;
- }
-
- if (focusItem) {
- lastFocusItem = focusItem;
-
-#ifndef QT_NO_IM
- if (lastFocusItem
- && (lastFocusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) {
- // Close any external input method panel. This happens
- // automatically by removing WA_InputMethodEnabled on
- // the views, but if we are changing focus, we have to
- // do it ourselves.
- for (int i = 0; i < views.size(); ++i)
- if (views.at(i)->inputContext())
- views.at(i)->inputContext()->reset();
- }
-
- focusItem = 0;
- QFocusEvent event(QEvent::FocusOut, focusReason);
- sendEvent(lastFocusItem, &event);
-#endif //QT_NO_IM
- }
-
- // This handles the case that the item has been removed from the
- // scene in response to the FocusOut event.
- if (item && item->scene() != q)
- item = 0;
-
- if (item)
- focusItem = item;
- updateInputMethodSensitivityInViews();
- if (item) {
- QFocusEvent event(QEvent::FocusIn, focusReason);
- sendEvent(item, &event);
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
-{
- Q_ASSERT(widget);
- Q_ASSERT(!popupWidgets.contains(widget));
- popupWidgets << widget;
- if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
- focusWidget->setFocus(Qt::PopupFocusReason);
- } else {
- grabKeyboard((QGraphicsItem *)widget);
- if (focusItem && popupWidgets.size() == 1) {
- QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
- sendEvent(focusItem, &event);
- }
- }
- grabMouse((QGraphicsItem *)widget);
-}
-
-/*!
- \internal
-
- Remove \a widget from the popup list. Important notes:
-
- \a widget is guaranteed to be in the list of popups, but it might not be
- the last entry; you can hide any item in the pop list before the others,
- and this must cause all later mouse grabbers to lose the grab.
-*/
-void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
-{
- Q_ASSERT(widget);
- int index = popupWidgets.indexOf(widget);
- Q_ASSERT(index != -1);
-
- for (int i = popupWidgets.size() - 1; i >= index; --i) {
- QGraphicsWidget *widget = popupWidgets.takeLast();
- ungrabMouse(widget, itemIsDying);
- if (focusItem && popupWidgets.isEmpty()) {
- QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
- sendEvent(focusItem, &event);
- } else if (keyboardGrabberItems.contains(static_cast<QGraphicsItem *>(widget))) {
- ungrabKeyboard(static_cast<QGraphicsItem *>(widget), itemIsDying);
- }
- if (!itemIsDying && widget->isVisible()) {
- widget->QGraphicsItem::d_ptr->setVisibleHelper(false, /* explicit = */ false);
- }
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
-{
- // Append to list of mouse grabber items, and send a mouse grab event.
- if (mouseGrabberItems.contains(item)) {
- if (mouseGrabberItems.last() == item) {
- Q_ASSERT(!implicit);
- if (!lastMouseGrabberItemHasImplicitMouseGrab) {
- qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
- } else {
- // Upgrade to an explicit mouse grab
- lastMouseGrabberItemHasImplicitMouseGrab = false;
- }
- } else {
- qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
- mouseGrabberItems.last());
- }
- return;
- }
-
- // Send ungrab event to the last grabber.
- if (!mouseGrabberItems.isEmpty()) {
- QGraphicsItem *last = mouseGrabberItems.last();
- if (lastMouseGrabberItemHasImplicitMouseGrab) {
- // Implicit mouse grab is immediately lost.
- last->ungrabMouse();
- } else {
- // Just send ungrab event to current grabber.
- QEvent ungrabEvent(QEvent::UngrabMouse);
- sendEvent(last, &ungrabEvent);
- }
- }
-
- mouseGrabberItems << item;
- lastMouseGrabberItemHasImplicitMouseGrab = implicit;
-
- // Send grab event to current grabber.
- QEvent grabEvent(QEvent::GrabMouse);
- sendEvent(item, &grabEvent);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
-{
- int index = mouseGrabberItems.indexOf(item);
- if (index == -1) {
- qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
- return;
- }
-
- if (item != mouseGrabberItems.last()) {
- // Recursively ungrab the next mouse grabber until we reach this item
- // to ensure state consistency.
- ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
- }
- if (!popupWidgets.isEmpty() && item == popupWidgets.last()) {
- // If the item is a popup, go via removePopup to ensure state
- // consistency and that it gets hidden correctly - beware that
- // removePopup() reenters this function to continue removing the grab.
- removePopup((QGraphicsWidget *)item, itemIsDying);
- return;
- }
-
- // Send notification about mouse ungrab.
- if (!itemIsDying) {
- QEvent event(QEvent::UngrabMouse);
- sendEvent(item, &event);
- }
-
- // Remove the item from the list of grabbers. Whenever this happens, we
- // reset the implicitGrab (there can be only ever be one implicit grabber
- // in a scene, and it is always the latest grabber; if the implicit grab
- // is lost, it is not automatically regained.
- mouseGrabberItems.takeLast();
- lastMouseGrabberItemHasImplicitMouseGrab = false;
-
- // Send notification about mouse regrab. ### It's unfortunate that all the
- // items get a GrabMouse event, but this is a rare case with a simple
- // implementation and it does ensure a consistent state.
- if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
- QGraphicsItem *last = mouseGrabberItems.last();
- QEvent event(QEvent::GrabMouse);
- sendEvent(last, &event);
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::clearMouseGrabber()
-{
- if (!mouseGrabberItems.isEmpty())
- mouseGrabberItems.first()->ungrabMouse();
- lastMouseGrabberItem = 0;
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
-{
- if (keyboardGrabberItems.contains(item)) {
- if (keyboardGrabberItems.last() == item)
- qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
- else
- qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
- keyboardGrabberItems.last());
- return;
- }
-
- // Send ungrab event to the last grabber.
- if (!keyboardGrabberItems.isEmpty()) {
- // Just send ungrab event to current grabber.
- QEvent ungrabEvent(QEvent::UngrabKeyboard);
- sendEvent(keyboardGrabberItems.last(), &ungrabEvent);
- }
-
- keyboardGrabberItems << item;
-
- // Send grab event to current grabber.
- QEvent grabEvent(QEvent::GrabKeyboard);
- sendEvent(item, &grabEvent);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
-{
- int index = keyboardGrabberItems.lastIndexOf(item);
- if (index == -1) {
- qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
- return;
- }
- if (item != keyboardGrabberItems.last()) {
- // Recursively ungrab the topmost keyboard grabber until we reach this
- // item to ensure state consistency.
- ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
- }
-
- // Send notification about keyboard ungrab.
- if (!itemIsDying) {
- QEvent event(QEvent::UngrabKeyboard);
- sendEvent(item, &event);
- }
-
- // Remove the item from the list of grabbers.
- keyboardGrabberItems.takeLast();
-
- // Send notification about mouse regrab.
- if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
- QGraphicsItem *last = keyboardGrabberItems.last();
- QEvent event(QEvent::GrabKeyboard);
- sendEvent(last, &event);
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::clearKeyboardGrabber()
-{
- if (!keyboardGrabberItems.isEmpty())
- ungrabKeyboard(keyboardGrabberItems.first());
-}
-
-void QGraphicsScenePrivate::enableMouseTrackingOnViews()
-{
- foreach (QGraphicsView *view, views)
- view->viewport()->setMouseTracking(true);
-}
-
-/*!
- Returns all items for the screen position in \a event.
-*/
-QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &/*screenPos*/,
- const QPointF &scenePos,
- QWidget *widget) const
-{
- Q_Q(const QGraphicsScene);
- QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
- if (!view)
- return q->items(scenePos, Qt::IntersectsItemShape, Qt::DescendingOrder, QTransform());
-
- const QRectF pointRect(scenePos, QSizeF(1, 1));
- if (!view->isTransformed())
- return q->items(pointRect, Qt::IntersectsItemShape, Qt::DescendingOrder);
-
- const QTransform viewTransform = view->viewportTransform();
- return q->items(pointRect, Qt::IntersectsItemShape,
- Qt::DescendingOrder, viewTransform);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
-{
- for (int i = 0x1; i <= 0x10; i <<= 1) {
- if (event->buttons() & i) {
- mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
- mouseGrabberItems.last()->d_ptr->genericMapFromScene(event->scenePos(),
- event->widget()));
- mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
- mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
- }
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
-{
- sceneEventFilters.insert(watched, filter);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
-{
- if (!sceneEventFilters.contains(watched))
- return;
-
- QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
- QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
- do {
- if (it.value() == filter)
- it = sceneEventFilters.erase(it);
- else
- ++it;
- } while (it != end);
-}
-
-/*!
- \internal
-*/
-bool QGraphicsScenePrivate::filterDescendantEvent(QGraphicsItem *item, QEvent *event)
-{
- if (item && (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorFiltersChildEvents)) {
- QGraphicsItem *parent = item->parentItem();
- while (parent) {
- if (parent->d_ptr->filtersDescendantEvents && parent->sceneEventFilter(item, event))
- return true;
- if (!(parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorFiltersChildEvents))
- return false;
- parent = parent->parentItem();
- }
- }
- return false;
-}
-
-/*!
- \internal
-*/
-bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
-{
- if (item && !sceneEventFilters.contains(item))
- return false;
-
- QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
- QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
- while (it != end) {
- // ### The filterer and filteree might both be deleted.
- if (it.value()->sceneEventFilter(it.key(), event))
- return true;
- ++it;
- }
- return false;
-}
-
-/*!
- \internal
-
- This is the final dispatch point for any events from the scene to the
- item. It filters the event first - if the filter returns true, the event
- is considered to have been eaten by the filter, and is therefore stopped
- (the default filter returns false). Then/otherwise, if the item is
- enabled, the event is sent; otherwise it is stopped.
-*/
-bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
-{
- if (QGraphicsObject *object = item->toGraphicsObject()) {
-#ifndef QT_NO_GESTURES
- QGestureManager *gestureManager = QApplicationPrivate::instance()->gestureManager;
- if (gestureManager) {
- if (gestureManager->filterEvent(object, event))
- return true;
- }
-#endif // QT_NO_GESTURES
- }
-
- if (filterEvent(item, event))
- return false;
- if (filterDescendantEvent(item, event))
- return false;
- if (!item || !item->isEnabled())
- return false;
- if (QGraphicsObject *o = item->toGraphicsObject()) {
- bool spont = event->spontaneous();
- if (spont ? qt_sendSpontaneousEvent(o, event) : QApplication::sendEvent(o, event))
- return true;
- event->spont = spont;
- }
- return item->sceneEvent(event);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
- QGraphicsSceneDragDropEvent *source)
-{
- dest->setWidget(source->widget());
- dest->setPos(source->pos());
- dest->setScenePos(source->scenePos());
- dest->setScreenPos(source->screenPos());
- dest->setButtons(source->buttons());
- dest->setModifiers(source->modifiers());
- dest->setPossibleActions(source->possibleActions());
- dest->setProposedAction(source->proposedAction());
- dest->setDropAction(source->dropAction());
- dest->setSource(source->source());
- dest->setMimeData(source->mimeData());
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
- QGraphicsSceneDragDropEvent *dragDropEvent)
-{
- dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
- sendEvent(item, dragDropEvent);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
- QGraphicsSceneHoverEvent *hoverEvent)
-{
- QGraphicsSceneHoverEvent event(type);
- event.setWidget(hoverEvent->widget());
- event.setPos(item->d_ptr->genericMapFromScene(hoverEvent->scenePos(), hoverEvent->widget()));
- event.setScenePos(hoverEvent->scenePos());
- event.setScreenPos(hoverEvent->screenPos());
- event.setLastPos(item->d_ptr->genericMapFromScene(hoverEvent->lastScenePos(), hoverEvent->widget()));
- event.setLastScenePos(hoverEvent->lastScenePos());
- event.setLastScreenPos(hoverEvent->lastScreenPos());
- event.setModifiers(hoverEvent->modifiers());
- sendEvent(item, &event);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
-{
- if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
- // ### This is a temporary fix for until we get proper mouse
- // grab events.
- clearMouseGrabber();
- return;
- }
-
- QGraphicsItem *item = mouseGrabberItems.last();
- if (item->isBlockedByModalPanel())
- return;
-
- for (int i = 0x1; i <= 0x10; i <<= 1) {
- Qt::MouseButton button = Qt::MouseButton(i);
- mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget())));
- mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
- mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
- }
- mouseEvent->setPos(item->d_ptr->genericMapFromScene(mouseEvent->scenePos(), mouseEvent->widget()));
- mouseEvent->setLastPos(item->d_ptr->genericMapFromScene(mouseEvent->lastScenePos(), mouseEvent->widget()));
- sendEvent(item, mouseEvent);
-}
-
-/*!
- \internal
-*/
-void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
-{
- Q_Q(QGraphicsScene);
-
- // Ignore by default, unless we find a mouse grabber that accepts it.
- mouseEvent->ignore();
-
- // Deliver to any existing mouse grabber.
- if (!mouseGrabberItems.isEmpty()) {
- if (mouseGrabberItems.last()->isBlockedByModalPanel())
- return;
- // The event is ignored by default, but we disregard the event's
- // accepted state after delivery; the mouse is grabbed, after all.
- sendMouseEvent(mouseEvent);
- return;
- }
-
- // Start by determining the number of items at the current position.
- // Reuse value from earlier calculations if possible.
- if (cachedItemsUnderMouse.isEmpty()) {
- cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
- mouseEvent->scenePos(),
- mouseEvent->widget());
- }
-
- // Update window activation.
- QGraphicsItem *topItem = cachedItemsUnderMouse.value(0);
- QGraphicsWidget *newActiveWindow = topItem ? topItem->window() : 0;
- if (newActiveWindow && newActiveWindow->isBlockedByModalPanel(&topItem)) {
- // pass activation to the blocking modal window
- newActiveWindow = topItem ? topItem->window() : 0;
- }
-
- if (newActiveWindow != q->activeWindow())
- q->setActiveWindow(newActiveWindow);
-
- // Set focus on the topmost enabled item that can take focus.
- bool setFocus = false;
-
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
- if (item->isBlockedByModalPanel()
- || (item->d_ptr->flags & QGraphicsItem::ItemStopsFocusHandling)) {
- // Make sure we don't clear focus.
- setFocus = true;
- break;
- }
- if (item->isEnabled() && ((item->flags() & QGraphicsItem::ItemIsFocusable))) {
- if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
- setFocus = true;
- if (item != q->focusItem() && item->d_ptr->mouseSetsFocus)
- q->setFocusItem(item, Qt::MouseFocusReason);
- break;
- }
- }
- if (item->isPanel())
- break;
- if (item->d_ptr->flags & QGraphicsItem::ItemStopsClickFocusPropagation)
- break;
- }
-
- // Check for scene modality.
- bool sceneModality = false;
- for (int i = 0; i < modalPanels.size(); ++i) {
- if (modalPanels.at(i)->panelModality() == QGraphicsItem::SceneModal) {
- sceneModality = true;
- break;
- }
- }
-
- // If nobody could take focus, clear it.
- if (!stickyFocus && !setFocus && !sceneModality)
- q->setFocusItem(0, Qt::MouseFocusReason);
-
- // Any item will do.
- if (sceneModality && cachedItemsUnderMouse.isEmpty())
- cachedItemsUnderMouse << modalPanels.first();
-
- // Find a mouse grabber by sending mouse press events to all mouse grabber
- // candidates one at a time, until the event is accepted. It's accepted by
- // default, so the receiver has to explicitly ignore it for it to pass
- // through.
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
- if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
- // Skip items that don't accept the event's mouse button.
- continue;
- }
-
- // Check if this item is blocked by a modal panel and deliver the mouse event to the
- // blocking panel instead of this item if blocked.
- (void) item->isBlockedByModalPanel(&item);
-
- grabMouse(item, /* implicit = */ true);
- mouseEvent->accept();
-
- // check if the item we are sending to are disabled (before we send the event)
- bool disabled = !item->isEnabled();
- bool isPanel = item->isPanel();
- if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick
- && item != lastMouseGrabberItem && lastMouseGrabberItem) {
- // If this item is different from the item that received the last
- // mouse event, and mouseEvent is a doubleclick event, then the
- // event is converted to a press. Known limitation:
- // Triple-clicking will not generate a doubleclick, though.
- QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
- mousePress.spont = mouseEvent->spont;
- mousePress.accept();
- mousePress.setButton(mouseEvent->button());
- mousePress.setButtons(mouseEvent->buttons());
- mousePress.setScreenPos(mouseEvent->screenPos());
- mousePress.setScenePos(mouseEvent->scenePos());
- mousePress.setModifiers(mouseEvent->modifiers());
- mousePress.setWidget(mouseEvent->widget());
- mousePress.setButtonDownPos(mouseEvent->button(),
- mouseEvent->buttonDownPos(mouseEvent->button()));
- mousePress.setButtonDownScenePos(mouseEvent->button(),
- mouseEvent->buttonDownScenePos(mouseEvent->button()));
- mousePress.setButtonDownScreenPos(mouseEvent->button(),
- mouseEvent->buttonDownScreenPos(mouseEvent->button()));
- sendMouseEvent(&mousePress);
- mouseEvent->setAccepted(mousePress.isAccepted());
- } else {
- sendMouseEvent(mouseEvent);
- }
-
- bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.last() != item;
- if (disabled) {
- ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
- break;
- }
- if (mouseEvent->isAccepted()) {
- if (!mouseGrabberItems.isEmpty())
- storeMouseButtonsForMouseGrabber(mouseEvent);
- lastMouseGrabberItem = item;
- return;
- }
- ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
-
- // Don't propagate through panels.
- if (isPanel)
- break;
- }
-
- // Is the event still ignored? Then the mouse press goes to the scene.
- // Reset the mouse grabber, clear the selection, clear focus, and leave
- // the event ignored so that it can propagate through the originating
- // view.
- if (!mouseEvent->isAccepted()) {
- clearMouseGrabber();
-
- QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
- bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
- if (!dontClearSelection) {
- // Clear the selection if the originating view isn't in scroll
- // hand drag mode. The view will clear the selection if no drag
- // happened.
- q->clearSelection();
- }
- }
-}
-
-/*!
- \internal
-
- Ensures that the list of toplevels is sorted by insertion order, and that
- the siblingIndexes are packed (no gaps), and start at 0.
-
- ### This function is almost identical to
- QGraphicsItemPrivate::ensureSequentialSiblingIndex().
-*/
-void QGraphicsScenePrivate::ensureSequentialTopLevelSiblingIndexes()
-{
- if (!topLevelSequentialOrdering) {
- qSort(topLevelItems.begin(), topLevelItems.end(), QGraphicsItemPrivate::insertionOrder);
- topLevelSequentialOrdering = true;
- needSortTopLevelItems = 1;
- }
- if (holesInTopLevelSiblingIndex) {
- holesInTopLevelSiblingIndex = 0;
- for (int i = 0; i < topLevelItems.size(); ++i)
- topLevelItems[i]->d_ptr->siblingIndex = i;
- }
-}
-
-/*!
- \internal
-
- Set the font and propagate the changes if the font is different from the
- current font.
-*/
-void QGraphicsScenePrivate::setFont_helper(const QFont &font)
-{
- if (this->font == font && this->font.resolve() == font.resolve())
- return;
- updateFont(font);
-}
-
-/*!
- \internal
-
- Resolve the scene's font against the application font, and propagate the
- changes too all items in the scene.
-*/
-void QGraphicsScenePrivate::resolveFont()
-{
- QFont naturalFont = QApplication::font();
- naturalFont.resolve(0);
- QFont resolvedFont = font.resolve(naturalFont);
- updateFont(resolvedFont);
-}
-
-/*!
- \internal
-
- Update the font, and whether or not it has changed, reresolve all fonts in
- the scene.
-*/
-void QGraphicsScenePrivate::updateFont(const QFont &font)
-{
- Q_Q(QGraphicsScene);
-
- // Update local font setting.
- this->font = font;
-
- // Resolve the fonts of all top-level widget items, or widget items
- // whose parent is not a widget.
- foreach (QGraphicsItem *item, q->items()) {
- if (!item->parentItem()) {
- // Resolvefont for an item is a noop operation, but
- // every item can be a widget, or can have a widget
- // childre.
- item->d_ptr->resolveFont(font.resolve());
- }
- }
-
- // Send the scene a FontChange event.
- QEvent event(QEvent::FontChange);
- QApplication::sendEvent(q, &event);
-}
-
-/*!
- \internal
-
- Set the palette and propagate the changes if the palette is different from
- the current palette.
-*/
-void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
-{
- if (this->palette == palette && this->palette.resolve() == palette.resolve())
- return;
- updatePalette(palette);
-}
-
-/*!
- \internal
-
- Resolve the scene's palette against the application palette, and propagate
- the changes too all items in the scene.
-*/
-void QGraphicsScenePrivate::resolvePalette()
-{
- QPalette naturalPalette = QApplication::palette();
- naturalPalette.resolve(0);
- QPalette resolvedPalette = palette.resolve(naturalPalette);
- updatePalette(resolvedPalette);
-}
-
-/*!
- \internal
-
- Update the palette, and whether or not it has changed, reresolve all
- palettes in the scene.
-*/
-void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
-{
- Q_Q(QGraphicsScene);
-
- // Update local palette setting.
- this->palette = palette;
-
- // Resolve the palettes of all top-level widget items, or widget items
- // whose parent is not a widget.
- foreach (QGraphicsItem *item, q->items()) {
- if (!item->parentItem()) {
- // Resolvefont for an item is a noop operation, but
- // every item can be a widget, or can have a widget
- // childre.
- item->d_ptr->resolvePalette(palette.resolve());
- }
- }
-
- // Send the scene a PaletteChange event.
- QEvent event(QEvent::PaletteChange);
- QApplication::sendEvent(q, &event);
-}
-
-/*!
- Constructs a QGraphicsScene object. The \a parent parameter is
- passed to QObject's constructor.
-*/
-QGraphicsScene::QGraphicsScene(QObject *parent)
- : QObject(*new QGraphicsScenePrivate, parent)
-{
- d_func()->init();
-}
-
-/*!
- Constructs a QGraphicsScene object, using \a sceneRect for its
- scene rectangle. The \a parent parameter is passed to QObject's
- constructor.
-
- \sa sceneRect
-*/
-QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
- : QObject(*new QGraphicsScenePrivate, parent)
-{
- d_func()->init();
- setSceneRect(sceneRect);
-}
-
-/*!
- Constructs a QGraphicsScene object, using the rectangle specified
- by (\a x, \a y), and the given \a width and \a height for its
- scene rectangle. The \a parent parameter is passed to QObject's
- constructor.
-
- \sa sceneRect
-*/
-QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
- : QObject(*new QGraphicsScenePrivate, parent)
-{
- d_func()->init();
- setSceneRect(x, y, width, height);
-}
-
-/*!
- Removes and deletes all items from the scene object
- before destroying the scene object. The scene object
- is removed from the application's global scene list,
- and it is removed from all associated views.
-*/
-QGraphicsScene::~QGraphicsScene()
-{
- Q_D(QGraphicsScene);
-
- // Remove this scene from qApp's global scene list.
- qApp->d_func()->scene_list.removeAll(this);
-
- clear();
-
- // Remove this scene from all associated views.
- for (int j = 0; j < d->views.size(); ++j)
- d->views.at(j)->setScene(0);
-}
-
-/*!
- \property QGraphicsScene::sceneRect
- \brief the scene rectangle; the bounding rectangle of the scene
-
- The scene rectangle defines the extent of the scene. It is
- primarily used by QGraphicsView to determine the view's default
- scrollable area, and by QGraphicsScene to manage item indexing.
-
- If unset, or if set to a null QRectF, sceneRect() will return the largest
- bounding rect of all items on the scene since the scene was created (i.e.,
- a rectangle that grows when items are added to or moved in the scene, but
- never shrinks).
-
- \sa width(), height(), QGraphicsView::sceneRect
-*/
-QRectF QGraphicsScene::sceneRect() const
-{
- Q_D(const QGraphicsScene);
- if (d->hasSceneRect)
- return d->sceneRect;
-
- if (d->dirtyGrowingItemsBoundingRect) {
- // Lazily update the growing items bounding rect
- QGraphicsScenePrivate *thatd = const_cast<QGraphicsScenePrivate *>(d);
- QRectF oldGrowingBoundingRect = thatd->growingItemsBoundingRect;
- thatd->growingItemsBoundingRect |= itemsBoundingRect();
- thatd->dirtyGrowingItemsBoundingRect = false;
- if (oldGrowingBoundingRect != thatd->growingItemsBoundingRect)
- emit const_cast<QGraphicsScene *>(this)->sceneRectChanged(thatd->growingItemsBoundingRect);
- }
- return d->growingItemsBoundingRect;
-}
-void QGraphicsScene::setSceneRect(const QRectF &rect)
-{
- Q_D(QGraphicsScene);
- if (rect != d->sceneRect) {
- d->hasSceneRect = !rect.isNull();
- d->sceneRect = rect;
- emit sceneRectChanged(d->hasSceneRect ? rect : d->growingItemsBoundingRect);
- }
-}
-
-/*!
- \fn qreal QGraphicsScene::width() const
-
- This convenience function is equivalent to calling sceneRect().width().
-
- \sa height()
-*/
-
-/*!
- \fn qreal QGraphicsScene::height() const
-
- This convenience function is equivalent to calling \c sceneRect().height().
-
- \sa width()
-*/
-
-/*!
- Renders the \a source rect from scene into \a target, using \a painter. This
- function is useful for capturing the contents of the scene onto a paint
- device, such as a QImage (e.g., to take a screenshot), or for printing
- with QPrinter. For example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 1
-
- If \a source is a null rect, this function will use sceneRect() to
- determine what to render. If \a target is a null rect, the dimensions of \a
- painter's paint device will be used.
-
- The source rect contents will be transformed according to \a
- aspectRatioMode to fit into the target rect. By default, the aspect ratio
- is kept, and \a source is scaled to fit in \a target.
-
- \sa QGraphicsView::render()
-*/
-void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
- Qt::AspectRatioMode aspectRatioMode)
-{
- // ### Switch to using the recursive rendering algorithm instead.
-
- // Default source rect = scene rect
- QRectF sourceRect = source;
- if (sourceRect.isNull())
- sourceRect = sceneRect();
-
- // Default target rect = device rect
- QRectF targetRect = target;
- if (targetRect.isNull()) {
- if (painter->device()->devType() == QInternal::Picture)
- targetRect = sourceRect;
- else
- targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
- }
-
- // Find the ideal x / y scaling ratio to fit \a source into \a target.
- qreal xratio = targetRect.width() / sourceRect.width();
- qreal yratio = targetRect.height() / sourceRect.height();
-
- // Scale according to the aspect ratio mode.
- switch (aspectRatioMode) {
- case Qt::KeepAspectRatio:
- xratio = yratio = qMin(xratio, yratio);
- break;
- case Qt::KeepAspectRatioByExpanding:
- xratio = yratio = qMax(xratio, yratio);
- break;
- case Qt::IgnoreAspectRatio:
- break;
- }
-
- // Find all items to draw, and reverse the list (we want to draw
- // in reverse order).
- QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
- QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
- int numItems = itemList.size();
- for (int i = 0; i < numItems; ++i)
- itemArray[numItems - i - 1] = itemList.at(i);
- itemList.clear();
-
- painter->save();
-
- // Transform the painter.
- painter->setClipRect(targetRect, Qt::IntersectClip);
- QTransform painterTransform;
- painterTransform *= QTransform()
- .translate(targetRect.left(), targetRect.top())
- .scale(xratio, yratio)
- .translate(-sourceRect.left(), -sourceRect.top());
- painter->setWorldTransform(painterTransform, true);
-
- // Two unit vectors.
- QLineF v1(0, 0, 1, 0);
- QLineF v2(0, 0, 0, 1);
-
- // Generate the style options
- QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
- for (int i = 0; i < numItems; ++i)
- itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterTransform, targetRect.toRect());
-
- // Render the scene.
- drawBackground(painter, sourceRect);
- drawItems(painter, numItems, itemArray, styleOptionArray);
- drawForeground(painter, sourceRect);
-
- delete [] itemArray;
- delete [] styleOptionArray;
-
- painter->restore();
-}
-
-/*!
- \property QGraphicsScene::itemIndexMethod
- \brief the item indexing method.
-
- QGraphicsScene applies an indexing algorithm to the scene, to speed up
- item discovery functions like items() and itemAt(). Indexing is most
- efficient for static scenes (i.e., where items don't move around). For
- dynamic scenes, or scenes with many animated items, the index bookkeeping
- can outweight the fast lookup speeds.
-
- For the common case, the default index method BspTreeIndex works fine. If
- your scene uses many animations and you are experiencing slowness, you can
- disable indexing by calling \c setItemIndexMethod(NoIndex).
-
- \sa bspTreeDepth
-*/
-QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
-{
- Q_D(const QGraphicsScene);
- return d->indexMethod;
-}
-void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
-{
- Q_D(QGraphicsScene);
- if (d->indexMethod == method)
- return;
-
- d->indexMethod = method;
-
- QList<QGraphicsItem *> oldItems = d->index->items(Qt::DescendingOrder);
- delete d->index;
- if (method == BspTreeIndex)
- d->index = new QGraphicsSceneBspTreeIndex(this);
- else
- d->index = new QGraphicsSceneLinearIndex(this);
- for (int i = oldItems.size() - 1; i >= 0; --i)
- d->index->addItem(oldItems.at(i));
-}
-
-/*!
- \property QGraphicsScene::bspTreeDepth
- \brief the depth of QGraphicsScene's BSP index tree
- \since 4.3
-
- This property has no effect when NoIndex is used.
-
- This value determines the depth of QGraphicsScene's BSP tree. The depth
- directly affects QGraphicsScene's performance and memory usage; the latter
- growing exponentially with the depth of the tree. With an optimal tree
- depth, QGraphicsScene can instantly determine the locality of items, even
- for scenes with thousands or millions of items. This also greatly improves
- rendering performance.
-
- By default, the value is 0, in which case Qt will guess a reasonable
- default depth based on the size, location and number of items in the
- scene. If these parameters change frequently, however, you may experience
- slowdowns as QGraphicsScene retunes the depth internally. You can avoid
- potential slowdowns by fixating the tree depth through setting this
- property.
-
- The depth of the tree and the size of the scene rectangle decide the
- granularity of the scene's partitioning. The size of each scene segment is
- determined by the following algorithm:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 2
-
- The BSP tree has an optimal size when each segment contains between 0 and
- 10 items.
-
- \sa itemIndexMethod
-*/
-int QGraphicsScene::bspTreeDepth() const
-{
- Q_D(const QGraphicsScene);
- QGraphicsSceneBspTreeIndex *bspTree = qobject_cast<QGraphicsSceneBspTreeIndex *>(d->index);
- return bspTree ? bspTree->bspTreeDepth() : 0;
-}
-void QGraphicsScene::setBspTreeDepth(int depth)
-{
- Q_D(QGraphicsScene);
- if (depth < 0) {
- qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
- return;
- }
-
- QGraphicsSceneBspTreeIndex *bspTree = qobject_cast<QGraphicsSceneBspTreeIndex *>(d->index);
- if (!bspTree) {
- qWarning("QGraphicsScene::setBspTreeDepth: can not apply if indexing method is not BSP");
- return;
- }
- bspTree->setBspTreeDepth(depth);
-}
-
-/*!
- \property QGraphicsScene::sortCacheEnabled
- \brief whether sort caching is enabled
- \since 4.5
- \obsolete
-
- Since Qt 4.6, this property has no effect.
-*/
-bool QGraphicsScene::isSortCacheEnabled() const
-{
- Q_D(const QGraphicsScene);
- return d->sortCacheEnabled;
-}
-void QGraphicsScene::setSortCacheEnabled(bool enabled)
-{
- Q_D(QGraphicsScene);
- if (d->sortCacheEnabled == enabled)
- return;
- d->sortCacheEnabled = enabled;
-}
-
-/*!
- Calculates and returns the bounding rect of all items on the scene. This
- function works by iterating over all items, and because if this, it can
- be slow for large scenes.
-
- \sa sceneRect()
-*/
-QRectF QGraphicsScene::itemsBoundingRect() const
-{
- // Does not take untransformable items into account.
- QRectF boundingRect;
- foreach (QGraphicsItem *item, items())
- boundingRect |= item->sceneBoundingRect();
- return boundingRect;
-}
-
-/*!
- Returns a list of all items in the scene in descending stacking order.
-
- \sa addItem(), removeItem(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items() const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(Qt::DescendingOrder);
-}
-
-/*!
- Returns an ordered list of all items on the scene. \a order decides the
- stacking order.
-
- \sa addItem(), removeItem(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(Qt::SortOrder order) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(order);
-}
-
-/*!
- \obsolete
-
- Returns all visible items at position \a pos in the scene. The items are
- listed in descending stacking order (i.e., the first item in the list is the
- top-most item, and the last item is the bottom-most item).
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(pos, Qt::IntersectsItemShape, Qt::DescendingOrder);
-}
-
-/*!
- \overload
- \obsolete
-
- Returns all visible items that, depending on \a mode, are either inside or
- intersect with the specified \a rectangle.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a rectangle are returned.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(rectangle, mode, Qt::DescendingOrder);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode) const
- \obsolete
- \since 4.3
-
- This convenience function is equivalent to calling items(QRectF(\a x, \a y, \a w, \a h), \a mode).
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-*/
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
- \overload
- \since 4.6
-
- \brief Returns all visible items that, depending on \a mode, are
- either inside or intersect with the rectangle defined by \a x, \a y,
- \a w and \a h, in a list sorted using \a order.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-*/
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
- \overload
- \obsolete
-
- Returns all visible items that, depending on \a mode, are either inside or
- intersect with the polygon \a polygon.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a polygon are returned.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(polygon, mode, Qt::DescendingOrder);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
- \overload
- \obsolete
-
- Returns all visible items that, depending on \a path, are either inside or
- intersect with the path \a path.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a path are returned.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(path, mode, Qt::DescendingOrder);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
- \since 4.6
-
- \brief Returns all visible items that, depending on \a mode, are at
- the specified \a pos in a list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with \a pos are returned.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(pos, mode, order, deviceTransform);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
- \overload
- \since 4.6
-
- \brief Returns all visible items that, depending on \a mode, are
- either inside or intersect with the specified \a rect and return a
- list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a rect are returned.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(rect, mode, order, deviceTransform);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
- \overload
- \since 4.6
-
- \brief Returns all visible items that, depending on \a mode, are
- either inside or intersect with the specified \a polygon and return
- a list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a polygon are returned.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(polygon, mode, order, deviceTransform);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
- \overload
- \since 4.6
-
- \brief Returns all visible items that, depending on \a mode, are
- either inside or intersect with the specified \a path and return a
- list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a path are returned.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsScene);
- return d->index->items(path, mode, order, deviceTransform);
-}
-
-/*!
- Returns a list of all items that collide with \a item. Collisions are
- determined by calling QGraphicsItem::collidesWithItem(); the collision
- detection is determined by \a mode. By default, all items whose shape
- intersects \a item or is contained inside \a item's shape are returned.
-
- The items are returned in descending stacking order (i.e., the first item
- in the list is the uppermost item, and the last item is the lowermost
- item).
-
- \sa items(), itemAt(), QGraphicsItem::collidesWithItem(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
- Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsScene);
- if (!item) {
- qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
- return QList<QGraphicsItem *>();
- }
-
- // Does not support ItemIgnoresTransformations.
- QList<QGraphicsItem *> tmp;
- foreach (QGraphicsItem *itemInVicinity, d->index->estimateItems(item->sceneBoundingRect(), Qt::DescendingOrder)) {
- if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
- tmp << itemInVicinity;
- }
- return tmp;
-}
-
-/*!
- \overload
- \obsolete
-
- Returns the topmost visible item at the specified \a position, or 0 if
- there are no items at this position.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-
- \sa items(), collidingItems(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position) const
-{
- QList<QGraphicsItem *> itemsAtPoint = items(position);
- return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
-}
-
-/*!
- \since 4.6
-
- Returns the topmost visible item at the specified \a position, or 0
- if there are no items at this position.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa items(), collidingItems(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position, const QTransform &deviceTransform) const
-{
- QList<QGraphicsItem *> itemsAtPoint = items(position, Qt::IntersectsItemShape,
- Qt::DescendingOrder, deviceTransform);
- return itemsAtPoint.isEmpty() ? 0 : itemsAtPoint.first();
-}
-
-/*!
- \fn QGraphicsScene::itemAt(qreal x, qreal y, const QTransform &deviceTransform) const
- \overload
- \since 4.6
-
- Returns the topmost item at the position specified by (\a x, \a
- y), or 0 if there are no items at this position.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- This convenience function is equivalent to calling \c
- {itemAt(QPointF(x, y), deviceTransform)}.
-*/
-
-/*!
- \fn QGraphicsScene::itemAt(qreal x, qreal y) const
- \overload
- \obsolete
-
- Returns the topmost item at the position specified by (\a x, \a
- y), or 0 if there are no items at this position.
-
- This convenience function is equivalent to calling \c
- {itemAt(QPointF(x, y))}.
-
- This function is deprecated and returns incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-*/
-
-/*!
- Returns a list of all currently selected items. The items are
- returned in no particular order.
-
- \sa setSelectionArea()
-*/
-QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
-{
- Q_D(const QGraphicsScene);
-
- // Optimization: Lazily removes items that are not selected.
- QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
- QSet<QGraphicsItem *> actuallySelectedSet;
- foreach (QGraphicsItem *item, that->d_func()->selectedItems) {
- if (item->isSelected())
- actuallySelectedSet << item;
- }
-
- that->d_func()->selectedItems = actuallySelectedSet;
-
- return d->selectedItems.values();
-}
-
-/*!
- Returns the selection area that was previously set with
- setSelectionArea(), or an empty QPainterPath if no selection area has been
- set.
-
- \sa setSelectionArea()
-*/
-QPainterPath QGraphicsScene::selectionArea() const
-{
- Q_D(const QGraphicsScene);
- return d->selectionArea;
-}
-
-/*!
- \since 4.6
-
- Sets the selection area to \a path. All items within this area are
- immediately selected, and all items outside are unselected. You can get
- the list of all selected items by calling selectedItems().
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- For an item to be selected, it must be marked as \e selectable
- (QGraphicsItem::ItemIsSelectable).
-
- \sa clearSelection(), selectionArea()
-*/
-void QGraphicsScene::setSelectionArea(const QPainterPath &path, const QTransform &deviceTransform)
-{
- setSelectionArea(path, Qt::IntersectsItemShape, deviceTransform);
-}
-
-/*!
- \obsolete
- \overload
-
- Sets the selection area to \a path.
-
- This function is deprecated and leads to incorrect results if the scene
- contains items that ignore transformations. Use the overload that takes
- a QTransform instead.
-*/
-void QGraphicsScene::setSelectionArea(const QPainterPath &path)
-{
- setSelectionArea(path, Qt::IntersectsItemShape, QTransform());
-}
-
-/*!
- \obsolete
- \overload
- \since 4.3
-
- Sets the selection area to \a path using \a mode to determine if items are
- included in the selection area.
-
- \sa clearSelection(), selectionArea()
-*/
-void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode)
-{
- setSelectionArea(path, mode, QTransform());
-}
-
-/*!
- \overload
- \since 4.6
-
- Sets the selection area to \a path using \a mode to determine if items are
- included in the selection area.
-
- \a deviceTransform is the transformation that applies to the view, and needs to
- be provided if the scene contains items that ignore transformations.
-
- \sa clearSelection(), selectionArea()
-*/
-void QGraphicsScene::setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode,
- const QTransform &deviceTransform)
-{
- Q_D(QGraphicsScene);
-
- // Note: with boolean path operations, we can improve performance here
- // quite a lot by "growing" the old path instead of replacing it. That
- // allows us to only check the intersect area for changes, instead of
- // reevaluating the whole path over again.
- d->selectionArea = path;
-
- QSet<QGraphicsItem *> unselectItems = d->selectedItems;
-
- // Disable emitting selectionChanged() for individual items.
- ++d->selectionChanging;
- bool changed = false;
-
- // Set all items in path to selected.
- foreach (QGraphicsItem *item, items(path, mode, Qt::DescendingOrder, deviceTransform)) {
- if (item->flags() & QGraphicsItem::ItemIsSelectable) {
- if (!item->isSelected())
- changed = true;
- unselectItems.remove(item);
- item->setSelected(true);
- }
- }
-
- // Unselect all items outside path.
- foreach (QGraphicsItem *item, unselectItems) {
- item->setSelected(false);
- changed = true;
- }
-
- // Reenable emitting selectionChanged() for individual items.
- --d->selectionChanging;
-
- if (!d->selectionChanging && changed)
- emit selectionChanged();
-}
-
-/*!
- Clears the current selection.
-
- \sa setSelectionArea(), selectedItems()
-*/
-void QGraphicsScene::clearSelection()
-{
- Q_D(QGraphicsScene);
-
- // Disable emitting selectionChanged
- ++d->selectionChanging;
- bool changed = !d->selectedItems.isEmpty();
-
- foreach (QGraphicsItem *item, d->selectedItems)
- item->setSelected(false);
- d->selectedItems.clear();
-
- // Reenable emitting selectionChanged() for individual items.
- --d->selectionChanging;
-
- if (!d->selectionChanging && changed)
- emit selectionChanged();
-}
-
-/*!
- \since 4.4
-
- Removes and deletes all items from the scene, but otherwise leaves the
- state of the scene unchanged.
-
- \sa addItem()
-*/
-void QGraphicsScene::clear()
-{
- Q_D(QGraphicsScene);
- // NB! We have to clear the index before deleting items; otherwise the
- // index might try to access dangling item pointers.
- d->index->clear();
- // NB! QGraphicsScenePrivate::unregisterTopLevelItem() removes items
- while (!d->topLevelItems.isEmpty())
- delete d->topLevelItems.first();
- Q_ASSERT(d->topLevelItems.isEmpty());
- d->lastItemCount = 0;
- d->allItemsIgnoreHoverEvents = true;
- d->allItemsUseDefaultCursor = true;
- d->allItemsIgnoreTouchEvents = true;
-}
-
-/*!
- Groups all items in \a items into a new QGraphicsItemGroup, and returns a
- pointer to the group. The group is created with the common ancestor of \a
- items as its parent, and with position (0, 0). The items are all
- reparented to the group, and their positions and transformations are
- mapped to the group. If \a items is empty, this function will return an
- empty top-level QGraphicsItemGroup.
-
- QGraphicsScene has ownership of the group item; you do not need to delete
- it. To dismantle (ungroup) a group, call destroyItemGroup().
-
- \sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
-*/
-QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
-{
- // Build a list of the first item's ancestors
- QList<QGraphicsItem *> ancestors;
- int n = 0;
- if (!items.isEmpty()) {
- QGraphicsItem *parent = items.at(n++);
- while ((parent = parent->parentItem()))
- ancestors.append(parent);
- }
-
- // Find the common ancestor for all items
- QGraphicsItem *commonAncestor = 0;
- if (!ancestors.isEmpty()) {
- while (n < items.size()) {
- int commonIndex = -1;
- QGraphicsItem *parent = items.at(n++);
- do {
- int index = ancestors.indexOf(parent, qMax(0, commonIndex));
- if (index != -1) {
- commonIndex = index;
- break;
- }
- } while ((parent = parent->parentItem()));
-
- if (commonIndex == -1) {
- commonAncestor = 0;
- break;
- }
-
- commonAncestor = ancestors.at(commonIndex);
- }
- }
-
- // Create a new group at that level
- QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
- if (!commonAncestor)
- addItem(group);
- foreach (QGraphicsItem *item, items)
- group->addToGroup(item);
- return group;
-}
-
-/*!
- Reparents all items in \a group to \a group's parent item, then removes \a
- group from the scene, and finally deletes it. The items' positions and
- transformations are mapped from the group to the group's parent.
-
- \sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
-*/
-void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
-{
- foreach (QGraphicsItem *item, group->children())
- group->removeFromGroup(item);
- removeItem(group);
- delete group;
-}
-
-/*!
- Adds or moves the \a item and all its childen to this scene.
- This scene takes ownership of the \a item.
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns
- true), QGraphicsScene will emit changed() once control goes back
- to the event loop.
-
- If the item is already in a different scene, it will first be
- removed from its old scene, and then added to this scene as a
- top-level.
-
- QGraphicsScene will send ItemSceneChange notifications to \a item
- while it is added to the scene. If item does not currently belong
- to a scene, only one notification is sent. If it does belong to
- scene already (i.e., it is moved to this scene), QGraphicsScene
- will send an addition notification as the item is removed from its
- previous scene.
-
- If the item is a panel, the scene is active, and there is no
- active panel in the scene, then the item will be activated.
-
- \sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
- addRect(), addText(), addWidget(), {QGraphicsItem#Sorting}{Sorting}
-*/
-void QGraphicsScene::addItem(QGraphicsItem *item)
-{
- Q_D(QGraphicsScene);
- if (!item) {
- qWarning("QGraphicsScene::addItem: cannot add null item");
- return;
- }
- if (item->d_ptr->scene == this) {
- qWarning("QGraphicsScene::addItem: item has already been added to this scene");
- return;
- }
- // Remove this item from its existing scene
- if (QGraphicsScene *oldScene = item->d_ptr->scene)
- oldScene->removeItem(item);
-
- // Notify the item that its scene is changing, and allow the item to
- // react.
- const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
- QVariant::fromValue<QGraphicsScene *>(this)));
- QGraphicsScene *targetScene = qvariant_cast<QGraphicsScene *>(newSceneVariant);
- if (targetScene != this) {
- if (targetScene && item->d_ptr->scene != targetScene)
- targetScene->addItem(item);
- return;
- }
-
- // QDeclarativeItems do not rely on initial itemChanged message, as the componentComplete
- // function allows far more opportunity for delayed-construction optimization.
- if (!item->d_ptr->isDeclarativeItem) {
- if (d->unpolishedItems.isEmpty()) {
- QMetaMethod method = metaObject()->method(d->polishItemsIndex);
- method.invoke(this, Qt::QueuedConnection);
- }
- d->unpolishedItems.append(item);
- item->d_ptr->pendingPolish = true;
- }
-
- // Detach this item from its parent if the parent's scene is different
- // from this scene.
- if (QGraphicsItem *itemParent = item->d_ptr->parent) {
- if (itemParent->d_ptr->scene != this)
- item->setParentItem(0);
- }
-
- // Add the item to this scene
- item->d_func()->scene = targetScene;
-
- // Add the item in the index
- d->index->addItem(item);
-
- // Add to list of toplevels if this item is a toplevel.
- if (!item->d_ptr->parent)
- d->registerTopLevelItem(item);
-
- // Add to list of items that require an update. We cannot assume that the
- // item is fully constructed, so calling item->update() can lead to a pure
- // virtual function call to boundingRect().
- d->markDirty(item);
- d->dirtyGrowingItemsBoundingRect = true;
-
- // Disable selectionChanged() for individual items
- ++d->selectionChanging;
- int oldSelectedItemSize = d->selectedItems.size();
-
- // Enable mouse tracking if the item accepts hover events or has a cursor set.
- if (d->allItemsIgnoreHoverEvents && d->itemAcceptsHoverEvents_helper(item)) {
- d->allItemsIgnoreHoverEvents = false;
- d->enableMouseTrackingOnViews();
- }
-#ifndef QT_NO_CURSOR
- if (d->allItemsUseDefaultCursor && item->d_ptr->hasCursor) {
- d->allItemsUseDefaultCursor = false;
- if (d->allItemsIgnoreHoverEvents) // already enabled otherwise
- d->enableMouseTrackingOnViews();
- }
-#endif //QT_NO_CURSOR
-
- // Enable touch events if the item accepts touch events.
- if (d->allItemsIgnoreTouchEvents && item->d_ptr->acceptTouchEvents) {
- d->allItemsIgnoreTouchEvents = false;
- d->enableTouchEventsOnViews();
- }
-
-#ifndef QT_NO_GESTURES
- foreach (Qt::GestureType gesture, item->d_ptr->gestureContext.keys())
- d->grabGesture(item, gesture);
-#endif
-
- // Update selection lists
- if (item->isSelected())
- d->selectedItems << item;
- if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
- d->addPopup(static_cast<QGraphicsWidget *>(item));
- if (item->isPanel() && item->isVisible() && item->panelModality() != QGraphicsItem::NonModal)
- d->enterModal(item);
-
- // Update creation order focus chain. Make sure to leave the widget's
- // internal tab order intact.
- if (item->isWidget()) {
- QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
- if (!d->tabFocusFirst) {
- // No first tab focus widget - make this the first tab focus
- // widget.
- d->tabFocusFirst = widget;
- } else if (!widget->parentWidget()) {
- // Adding a widget that is not part of a tab focus chain.
- QGraphicsWidget *last = d->tabFocusFirst->d_func()->focusPrev;
- QGraphicsWidget *lastNew = widget->d_func()->focusPrev;
- last->d_func()->focusNext = widget;
- widget->d_func()->focusPrev = last;
- d->tabFocusFirst->d_func()->focusPrev = lastNew;
- lastNew->d_func()->focusNext = d->tabFocusFirst;
- }
- }
-
- // Add all children recursively
- item->d_ptr->ensureSortedChildren();
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- addItem(item->d_ptr->children.at(i));
-
- // Resolve font and palette.
- item->d_ptr->resolveFont(d->font.resolve());
- item->d_ptr->resolvePalette(d->palette.resolve());
-
-
- // Reenable selectionChanged() for individual items
- --d->selectionChanging;
- if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
- emit selectionChanged();
-
- // Deliver post-change notification
- item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
-
- // Update explicit activation
- bool autoActivate = true;
- if (!d->childExplicitActivation && item->d_ptr->explicitActivate)
- d->childExplicitActivation = item->d_ptr->wantsActive ? 1 : 2;
- if (d->childExplicitActivation && item->isPanel()) {
- if (d->childExplicitActivation == 1)
- setActivePanel(item);
- else
- autoActivate = false;
- d->childExplicitActivation = 0;
- } else if (!item->d_ptr->parent) {
- d->childExplicitActivation = 0;
- }
-
- // Auto-activate this item's panel if nothing else has been activated
- if (autoActivate) {
- if (!d->lastActivePanel && !d->activePanel && item->isPanel()) {
- if (isActive())
- setActivePanel(item);
- else
- d->lastActivePanel = item;
- }
- }
-
- if (item->d_ptr->flags & QGraphicsItem::ItemSendsScenePositionChanges)
- d->registerScenePosItem(item);
-
- // Ensure that newly added items that have subfocus set, gain
- // focus automatically if there isn't a focus item already.
- if (!d->focusItem && item != d->lastFocusItem && item->focusItem() == item)
- item->focusItem()->setFocus();
-
- d->updateInputMethodSensitivityInViews();
-}
-
-/*!
- Creates and adds an ellipse item to the scene, and returns the item
- pointer. The geometry of the ellipse is defined by \a rect, and its pen
- and brush are initialized to \a pen and \a brush.
-
- Note that the item's geometry is provided in item coordinates, and its
- position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
- addWidget()
-*/
-QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
-{
- QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
- item->setPen(pen);
- item->setBrush(brush);
- addItem(item);
- return item;
-}
-
-/*!
- \fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
- \since 4.3
-
- This convenience function is equivalent to calling addEllipse(QRectF(\a x,
- \a y, \a w, \a h), \a pen, \a brush).
-*/
-
-/*!
- Creates and adds a line item to the scene, and returns the item
- pointer. The geometry of the line is defined by \a line, and its pen
- is initialized to \a pen.
-
- Note that the item's geometry is provided in item coordinates, and its
- position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
- addWidget()
-*/
-QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
-{
- QGraphicsLineItem *item = new QGraphicsLineItem(line);
- item->setPen(pen);
- addItem(item);
- return item;
-}
-
-/*!
- \fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
- \since 4.3
-
- This convenience function is equivalent to calling addLine(QLineF(\a x1,
- \a y1, \a x2, \a y2), \a pen).
-*/
-
-/*!
- Creates and adds a path item to the scene, and returns the item
- pointer. The geometry of the path is defined by \a path, and its pen and
- brush are initialized to \a pen and \a brush.
-
- Note that the item's geometry is provided in item coordinates, and its
- position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
- addWidget()
-*/
-QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
-{
- QGraphicsPathItem *item = new QGraphicsPathItem(path);
- item->setPen(pen);
- item->setBrush(brush);
- addItem(item);
- return item;
-}
-
-/*!
- Creates and adds a pixmap item to the scene, and returns the item
- pointer. The pixmap is defined by \a pixmap.
-
- Note that the item's geometry is provided in item coordinates, and its
- position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
- addWidget()
-*/
-QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
-{
- QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
- addItem(item);
- return item;
-}
-
-/*!
- Creates and adds a polygon item to the scene, and returns the item
- pointer. The polygon is defined by \a polygon, and its pen and
- brush are initialized to \a pen and \a brush.
-
- Note that the item's geometry is provided in item coordinates, and its
- position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
- addWidget()
-*/
-QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
- const QPen &pen, const QBrush &brush)
-{
- QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
- item->setPen(pen);
- item->setBrush(brush);
- addItem(item);
- return item;
-}
-
-/*!
- Creates and adds a rectangle item to the scene, and returns the item
- pointer. The geometry of the rectangle is defined by \a rect, and its pen
- and brush are initialized to \a pen and \a brush.
-
- Note that the item's geometry is provided in item coordinates, and its
- position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
- 100) is added, its top-left corner will be at (50, 50) relative to the
- origin in the items coordinate system.
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addLine(), addPixmap(), addPixmap(), addText(),
- addItem(), addWidget()
-*/
-QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
-{
- QGraphicsRectItem *item = new QGraphicsRectItem(rect);
- item->setPen(pen);
- item->setBrush(brush);
- addItem(item);
- return item;
-}
-
-/*!
- \fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
- \since 4.3
-
- This convenience function is equivalent to calling addRect(QRectF(\a x,
- \a y, \a w, \a h), \a pen, \a brush).
-*/
-
-/*!
- Creates and adds a text item to the scene, and returns the item
- pointer. The text string is initialized to \a text, and its font
- is initialized to \a font.
-
- The item's position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
- addItem(), addWidget()
-*/
-QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
-{
- QGraphicsTextItem *item = new QGraphicsTextItem(text);
- item->setFont(font);
- addItem(item);
- return item;
-}
-
-/*!
- Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
- item pointer. The text string is initialized to \a text, and its font is
- initialized to \a font.
-
- The item's position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- \sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
- addItem(), addWidget()
-*/
-QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
-{
- QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
- item->setFont(font);
- addItem(item);
- return item;
-}
-
-/*!
- Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
- and returns a pointer to the proxy. \a wFlags set the default window flags
- for the embedding proxy widget.
-
- The item's position is initialized to (0, 0).
-
- If the item is visible (i.e., QGraphicsItem::isVisible() returns true),
- QGraphicsScene will emit changed() once control goes back to the event
- loop.
-
- Note that widgets with the Qt::WA_PaintOnScreen widget attribute
- set and widgets that wrap an external application or controller
- are not supported. Examples are QGLWidget and QAxWidget.
-
- \sa addEllipse(), addLine(), addPixmap(), addPixmap(), addRect(),
- addText(), addSimpleText(), addItem()
-*/
-QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
-{
- QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, wFlags);
- proxy->setWidget(widget);
- addItem(proxy);
- return proxy;
-}
-
-/*!
- Removes the item \a item and all its children from the scene. The
- ownership of \a item is passed on to the caller (i.e.,
- QGraphicsScene will no longer delete \a item when destroyed).
-
- \sa addItem()
-*/
-void QGraphicsScene::removeItem(QGraphicsItem *item)
-{
- // ### Refactoring: This function shares much functionality with _q_removeItemLater()
- Q_D(QGraphicsScene);
- if (!item) {
- qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
- return;
- }
- if (item->scene() != this) {
- qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
- " is different from this scene (%p)",
- item, item->scene(), this);
- return;
- }
-
- // Notify the item that it's scene is changing to 0, allowing the item to
- // react.
- const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
- QVariant::fromValue<QGraphicsScene *>(0)));
- QGraphicsScene *targetScene = qvariant_cast<QGraphicsScene *>(newSceneVariant);
- if (targetScene != 0 && targetScene != this) {
- targetScene->addItem(item);
- return;
- }
-
- d->removeItemHelper(item);
-
- // Deliver post-change notification
- item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
-
- d->updateInputMethodSensitivityInViews();
-}
-
-/*!
- When the scene is active, this functions returns the scene's current focus
- item, or 0 if no item currently has focus. When the scene is inactive, this
- functions returns the item that will gain input focus when the scene becomes
- active.
-
- The focus item receives keyboard input when the scene receives a
- key event.
-
- \sa setFocusItem(), QGraphicsItem::hasFocus(), isActive()
-*/
-QGraphicsItem *QGraphicsScene::focusItem() const
-{
- Q_D(const QGraphicsScene);
- return isActive() ? d->focusItem : d->passiveFocusItem;
-}
-
-/*!
- Sets the scene's focus item to \a item, with the focus reason \a
- focusReason, after removing focus from any previous item that may have had
- focus.
-
- If \a item is 0, or if it either does not accept focus (i.e., it does not
- have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
- or not enabled, this function only removes focus from any previous
- focusitem.
-
- If item is not 0, and the scene does not currently have focus (i.e.,
- hasFocus() returns false), this function will call setFocus()
- automatically.
-
- \sa focusItem(), hasFocus(), setFocus()
-*/
-void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
-{
- Q_D(QGraphicsScene);
- if (item)
- item->setFocus(focusReason);
- else
- d->setFocusItemHelper(item, focusReason);
-}
-
-/*!
- Returns true if the scene has focus; otherwise returns false. If the scene
- has focus, it will will forward key events from QKeyEvent to any item that
- has focus.
-
- \sa setFocus(), setFocusItem()
-*/
-bool QGraphicsScene::hasFocus() const
-{
- Q_D(const QGraphicsScene);
- return d->hasFocus;
-}
-
-/*!
- Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
- focusReason as the reason. If the scene regains focus after having
- previously lost it while an item had focus, the last focus item will
- receive focus with \a focusReason as the reason.
-
- If the scene already has focus, this function does nothing.
-
- \sa hasFocus(), clearFocus(), setFocusItem()
-*/
-void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
-{
- Q_D(QGraphicsScene);
- if (d->hasFocus || !isActive())
- return;
- QFocusEvent event(QEvent::FocusIn, focusReason);
- QCoreApplication::sendEvent(this, &event);
-}
-
-/*!
- Clears focus from the scene. If any item has focus when this function is
- called, it will lose focus, and regain focus again once the scene regains
- focus.
-
- A scene that does not have focus ignores key events.
-
- \sa hasFocus(), setFocus(), setFocusItem()
-*/
-void QGraphicsScene::clearFocus()
-{
- Q_D(QGraphicsScene);
- if (d->hasFocus) {
- d->hasFocus = false;
- d->passiveFocusItem = d->focusItem;
- setFocusItem(0, Qt::OtherFocusReason);
- }
-}
-
-/*!
- \property QGraphicsScene::stickyFocus
- \brief whether clicking into the scene background will clear focus
-
- \since 4.6
-
- In a QGraphicsScene with stickyFocus set to true, focus will remain
- unchanged when the user clicks into the scene background or on an item
- that does not accept focus. Otherwise, focus will be cleared.
-
- By default, this property is false.
-
- Focus changes in response to a mouse press. You can reimplement
- mousePressEvent() in a subclass of QGraphicsScene to toggle this property
- based on where the user has clicked.
-
- \sa clearFocus(), setFocusItem()
-*/
-void QGraphicsScene::setStickyFocus(bool enabled)
-{
- Q_D(QGraphicsScene);
- d->stickyFocus = enabled;
-}
-bool QGraphicsScene::stickyFocus() const
-{
- Q_D(const QGraphicsScene);
- return d->stickyFocus;
-}
-
-/*!
- Returns the current mouse grabber item, or 0 if no item is currently
- grabbing the mouse. The mouse grabber item is the item that receives all
- mouse events sent to the scene.
-
- An item becomes a mouse grabber when it receives and accepts a
- mouse press event, and it stays the mouse grabber until either of
- the following events occur:
-
- \list
- \o If the item receives a mouse release event when there are no other
- buttons pressed, it loses the mouse grab.
- \o If the item becomes invisible (i.e., someone calls \c {item->setVisible(false)}),
- or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false)}),
- it loses the mouse grab.
- \o If the item is removed from the scene, it loses the mouse grab.
- \endlist
-
- If the item loses its mouse grab, the scene will ignore all mouse events
- until a new item grabs the mouse (i.e., until a new item receives a mouse
- press event).
-*/
-QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
-{
- Q_D(const QGraphicsScene);
- return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
-}
-
-/*!
- \property QGraphicsScene::backgroundBrush
- \brief the background brush of the scene.
-
- Set this property to changes the scene's background to a different color,
- gradient or texture. The default background brush is Qt::NoBrush. The
- background is drawn before (behind) the items.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 3
-
- QGraphicsScene::render() calls drawBackground() to draw the scene
- background. For more detailed control over how the background is drawn,
- you can reimplement drawBackground() in a subclass of QGraphicsScene.
-*/
-QBrush QGraphicsScene::backgroundBrush() const
-{
- Q_D(const QGraphicsScene);
- return d->backgroundBrush;
-}
-void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
-{
- Q_D(QGraphicsScene);
- d->backgroundBrush = brush;
- foreach (QGraphicsView *view, d->views) {
- view->resetCachedContent();
- view->viewport()->update();
- }
- update();
-}
-
-/*!
- \property QGraphicsScene::foregroundBrush
- \brief the foreground brush of the scene.
-
- Change this property to set the scene's foreground to a different
- color, gradient or texture.
-
- The foreground is drawn after (on top of) the items. The default
- foreground brush is Qt::NoBrush ( i.e. the foreground is not
- drawn).
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 4
-
- QGraphicsScene::render() calls drawForeground() to draw the scene
- foreground. For more detailed control over how the foreground is
- drawn, you can reimplement the drawForeground() function in a
- QGraphicsScene subclass.
-*/
-QBrush QGraphicsScene::foregroundBrush() const
-{
- Q_D(const QGraphicsScene);
- return d->foregroundBrush;
-}
-void QGraphicsScene::setForegroundBrush(const QBrush &brush)
-{
- Q_D(QGraphicsScene);
- d->foregroundBrush = brush;
- foreach (QGraphicsView *view, views())
- view->viewport()->update();
- update();
-}
-
-/*!
- This method is used by input methods to query a set of properties of
- the scene to be able to support complex input method operations as support
- for surrounding text and reconversions.
-
- The \a query parameter specifies which property is queried.
-
- \sa QWidget::inputMethodQuery()
-*/
-QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- Q_D(const QGraphicsScene);
- if (!d->focusItem || !(d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod))
- return QVariant();
- const QTransform matrix = d->focusItem->sceneTransform();
- QVariant value = d->focusItem->inputMethodQuery(query);
- if (value.type() == QVariant::RectF)
- value = matrix.mapRect(value.toRectF());
- else if (value.type() == QVariant::PointF)
- value = matrix.map(value.toPointF());
- else if (value.type() == QVariant::Rect)
- value = matrix.mapRect(value.toRect());
- else if (value.type() == QVariant::Point)
- value = matrix.map(value.toPoint());
- return value;
-}
-
-/*!
- \fn void QGraphicsScene::update(const QRectF &rect)
- Schedules a redraw of the area \a rect on the scene.
-
- \sa sceneRect(), changed()
-*/
-void QGraphicsScene::update(const QRectF &rect)
-{
- Q_D(QGraphicsScene);
- if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
- return;
-
- // Check if anyone's connected; if not, we can send updates directly to
- // the views. Otherwise or if there are no views, use old behavior.
- bool directUpdates = !(d->isSignalConnected(d->changedSignalIndex)) && !d->views.isEmpty();
- if (rect.isNull()) {
- d->updateAll = true;
- d->updatedRects.clear();
- if (directUpdates) {
- // Update all views.
- for (int i = 0; i < d->views.size(); ++i)
- d->views.at(i)->d_func()->fullUpdatePending = true;
- }
- } else {
- if (directUpdates) {
- // Update all views.
- for (int i = 0; i < d->views.size(); ++i) {
- QGraphicsView *view = d->views.at(i);
- if (view->isTransformed())
- view->d_func()->updateRectF(view->viewportTransform().mapRect(rect));
- else
- view->d_func()->updateRectF(rect);
- }
- } else {
- d->updatedRects << rect;
- }
- }
-
- if (!d->calledEmitUpdated) {
- d->calledEmitUpdated = true;
- QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
- }
-}
-
-/*!
- \fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
- \overload
- \since 4.3
-
- This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
- \a h));
-*/
-
-/*!
- Invalidates and schedules a redraw of the \a layers in \a rect on the
- scene. Any cached content in \a layers is unconditionally invalidated and
- redrawn.
-
- You can use this function overload to notify QGraphicsScene of changes to
- the background or the foreground of the scene. This function is commonly
- used for scenes with tile-based backgrounds to notify changes when
- QGraphicsView has enabled
- \l{QGraphicsView::CacheBackground}{CacheBackground}.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp 5
-
- Note that QGraphicsView currently supports background caching only (see
- QGraphicsView::CacheBackground). This function is equivalent to calling
- update() if any layer but BackgroundLayer is passed.
-
- \sa QGraphicsView::resetCachedContent()
-*/
-void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
-{
- foreach (QGraphicsView *view, views())
- view->invalidateScene(rect, layers);
- update(rect);
-}
-
-/*!
- \fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
- \overload
- \since 4.3
-
- This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
- y, \a w, \a h), \a layers);
-*/
-
-/*!
- Returns a list of all the views that display this scene.
-
- \sa QGraphicsView::scene()
-*/
-QList <QGraphicsView *> QGraphicsScene::views() const
-{
- Q_D(const QGraphicsScene);
- return d->views;
-}
-
-/*!
- This slot \e advances the scene by one step, by calling
- QGraphicsItem::advance() for all items on the scene. This is done in two
- phases: in the first phase, all items are notified that the scene is about
- to change, and in the second phase all items are notified that they can
- move. In the first phase, QGraphicsItem::advance() is called passing a
- value of 0 as an argument, and 1 is passed in the second phase.
-
- \sa QGraphicsItem::advance(), QGraphicsItemAnimation, QTimeLine
-*/
-void QGraphicsScene::advance()
-{
- for (int i = 0; i < 2; ++i) {
- foreach (QGraphicsItem *item, items())
- item->advance(i);
- }
-}
-
-/*!
- Processes the event \a event, and dispatches it to the respective
- event handlers.
-
- In addition to calling the convenience event handlers, this
- function is responsible for converting mouse move events to hover
- events for when there is no mouse grabber item. Hover events are
- delivered directly to items; there is no convenience function for
- them.
-
- Unlike QWidget, QGraphicsScene does not have the convenience functions
- \l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
- function to obtain those events instead.
-
- \sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
- mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
- mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
-*/
-bool QGraphicsScene::event(QEvent *event)
-{
- Q_D(QGraphicsScene);
-
- switch (event->type()) {
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseDoubleClick:
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverLeave:
- case QEvent::GraphicsSceneHoverMove:
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- // Reset the under-mouse list to ensure that this event gets fresh
- // item-under-mouse data. Be careful about this list; if people delete
- // items from inside event handlers, this list can quickly end up
- // having stale pointers in it. We need to clear it before dispatching
- // events that use it.
- // ### this should only be cleared if we received a new mouse move event,
- // which relies on us fixing the replay mechanism in QGraphicsView.
- d->cachedItemsUnderMouse.clear();
- default:
- break;
- }
-
- switch (event->type()) {
- case QEvent::GraphicsSceneDragEnter:
- dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneDragMove:
- dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneDragLeave:
- dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneDrop:
- dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
- break;
- case QEvent::GraphicsSceneContextMenu:
- contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
- break;
- case QEvent::KeyPress:
- if (!d->focusItem) {
- QKeyEvent *k = static_cast<QKeyEvent *>(event);
- if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
- if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
- bool res = false;
- if (k->key() == Qt::Key_Backtab
- || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
- res = focusNextPrevChild(false);
- } else if (k->key() == Qt::Key_Tab) {
- res = focusNextPrevChild(true);
- }
- if (!res)
- event->ignore();
- return true;
- }
- }
- }
- keyPressEvent(static_cast<QKeyEvent *>(event));
- break;
- case QEvent::KeyRelease:
- keyReleaseEvent(static_cast<QKeyEvent *>(event));
- break;
- case QEvent::ShortcutOverride: {
- QGraphicsItem *parent = focusItem();
- while (parent) {
- d->sendEvent(parent, event);
- if (event->isAccepted())
- return true;
- parent = parent->parentItem();
- }
- }
- return false;
- case QEvent::GraphicsSceneMouseMove:
- {
- QGraphicsSceneMouseEvent *mouseEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
- d->lastSceneMousePos = mouseEvent->scenePos();
- mouseMoveEvent(mouseEvent);
- break;
- }
- case QEvent::GraphicsSceneMousePress:
- mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneMouseRelease:
- mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneMouseDoubleClick:
- mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneWheel:
- wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
- break;
- case QEvent::FocusIn:
- focusInEvent(static_cast<QFocusEvent *>(event));
- break;
- case QEvent::FocusOut:
- focusOutEvent(static_cast<QFocusEvent *>(event));
- break;
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverLeave:
- case QEvent::GraphicsSceneHoverMove:
- {
- QGraphicsSceneHoverEvent *hoverEvent = static_cast<QGraphicsSceneHoverEvent *>(event);
- d->lastSceneMousePos = hoverEvent->scenePos();
- d->dispatchHoverEvent(hoverEvent);
- break;
- }
- case QEvent::Leave:
- // hackieshly unpacking the viewport pointer from the leave event.
- d->leaveScene(reinterpret_cast<QWidget *>(event->d));
- break;
- case QEvent::GraphicsSceneHelp:
- helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
- break;
- case QEvent::InputMethod:
- inputMethodEvent(static_cast<QInputMethodEvent *>(event));
- break;
- case QEvent::WindowActivate:
- if (!d->activationRefCount++) {
- if (d->lastActivePanel) {
- // Activate the last panel.
- d->setActivePanelHelper(d->lastActivePanel, true);
- } else if (d->tabFocusFirst && d->tabFocusFirst->isPanel()) {
- // Activate the panel of the first item in the tab focus
- // chain.
- d->setActivePanelHelper(d->tabFocusFirst, true);
- } else {
- // Activate all toplevel items.
- QEvent event(QEvent::WindowActivate);
- foreach (QGraphicsItem *item, items()) {
- if (item->isVisible() && !item->isPanel() && !item->parentItem())
- sendEvent(item, &event);
- }
- }
- }
- break;
- case QEvent::WindowDeactivate:
- if (!--d->activationRefCount) {
- if (d->activePanel) {
- // Deactivate the active panel (but keep it so we can
- // reactivate it later).
- QGraphicsItem *lastActivePanel = d->activePanel;
- d->setActivePanelHelper(0, true);
- d->lastActivePanel = lastActivePanel;
- } else {
- // Activate all toplevel items.
- QEvent event(QEvent::WindowDeactivate);
- foreach (QGraphicsItem *item, items()) {
- if (item->isVisible() && !item->isPanel() && !item->parentItem())
- sendEvent(item, &event);
- }
- }
- }
- break;
- case QEvent::ApplicationFontChange: {
- // Resolve the existing scene font.
- d->resolveFont();
- break;
- }
- case QEvent::FontChange:
- // Update the entire scene when the font changes.
- update();
- break;
- case QEvent::ApplicationPaletteChange: {
- // Resolve the existing scene palette.
- d->resolvePalette();
- break;
- }
- case QEvent::PaletteChange:
- // Update the entire scene when the palette changes.
- update();
- break;
- case QEvent::StyleChange:
- // Reresolve all widgets' styles. Update all top-level widgets'
- // geometries that do not have an explicit style set.
- update();
- break;
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- d->touchEventHandler(static_cast<QTouchEvent *>(event));
- break;
-#ifndef QT_NO_GESTURES
- case QEvent::Gesture:
- case QEvent::GestureOverride:
- d->gestureEventHandler(static_cast<QGestureEvent *>(event));
- break;
-#endif // QT_NO_GESTURES
- default:
- return QObject::event(event);
- }
- return true;
-}
-
-/*!
- \reimp
-
- QGraphicsScene filters QApplication's events to detect palette and font
- changes.
-*/
-bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
-{
- if (watched != qApp)
- return false;
-
- switch (event->type()) {
- case QEvent::ApplicationPaletteChange:
- QApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
- break;
- case QEvent::ApplicationFontChange:
- QApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange));
- break;
- default:
- break;
- }
- return false;
-}
-
-/*!
- This event handler, for event \a contextMenuEvent, can be reimplemented in
- a subclass to receive context menu events. The default implementation
- forwards the event to the topmost item that accepts context menu events at
- the position of the event. If no items accept context menu events at this
- position, the event is ignored.
-
- \sa QGraphicsItem::contextMenuEvent()
-*/
-void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
-{
- Q_D(QGraphicsScene);
- // Ignore by default.
- contextMenuEvent->ignore();
-
- // Send the event to all items at this position until one item accepts the
- // event.
- foreach (QGraphicsItem *item, d->itemsAtPosition(contextMenuEvent->screenPos(),
- contextMenuEvent->scenePos(),
- contextMenuEvent->widget())) {
- contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
- contextMenuEvent->widget()));
- contextMenuEvent->accept();
- if (!d->sendEvent(item, contextMenuEvent))
- break;
-
- if (contextMenuEvent->isAccepted())
- break;
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a subclass
- to receive drag enter events for the scene.
-
- The default implementation accepts the event and prepares the scene to
- accept drag move events.
-
- \sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
- dropEvent()
-*/
-void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsScene);
- d->dragDropItem = 0;
- d->lastDropAction = Qt::IgnoreAction;
- event->accept();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a subclass
- to receive drag move events for the scene.
-
- \sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
- dropEvent()
-*/
-void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsScene);
- event->ignore();
-
- if (!d->mouseGrabberItems.isEmpty()) {
- // Mouse grabbers that start drag events lose the mouse grab.
- d->clearMouseGrabber();
- d->mouseGrabberButtonDownPos.clear();
- d->mouseGrabberButtonDownScenePos.clear();
- d->mouseGrabberButtonDownScreenPos.clear();
- }
-
- bool eventDelivered = false;
-
- // Find the topmost enabled items under the cursor. They are all
- // candidates for accepting drag & drop events.
- foreach (QGraphicsItem *item, d->itemsAtPosition(event->screenPos(),
- event->scenePos(),
- event->widget())) {
- if (!item->isEnabled() || !item->acceptDrops())
- continue;
-
- if (item != d->dragDropItem) {
- // Enter the new drag drop item. If it accepts the event, we send
- // the leave to the parent item.
- QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
- d->cloneDragDropEvent(&dragEnter, event);
- dragEnter.setDropAction(event->proposedAction());
- d->sendDragDropEvent(item, &dragEnter);
- event->setAccepted(dragEnter.isAccepted());
- event->setDropAction(dragEnter.dropAction());
- if (!event->isAccepted()) {
- // Propagate to the item under
- continue;
- }
-
- d->lastDropAction = event->dropAction();
-
- if (d->dragDropItem) {
- // Leave the last drag drop item. A perfect implementation
- // would set the position of this event to the point where
- // this event and the last event intersect with the item's
- // shape, but that's not easy to do. :-)
- QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
- d->cloneDragDropEvent(&dragLeave, event);
- d->sendDragDropEvent(d->dragDropItem, &dragLeave);
- }
-
- // We've got a new drag & drop item
- d->dragDropItem = item;
- }
-
- // Send the move event.
- event->setDropAction(d->lastDropAction);
- event->accept();
- d->sendDragDropEvent(item, event);
- if (event->isAccepted())
- d->lastDropAction = event->dropAction();
- eventDelivered = true;
- break;
- }
-
- if (!eventDelivered) {
- if (d->dragDropItem) {
- // Leave the last drag drop item
- QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
- d->cloneDragDropEvent(&dragLeave, event);
- d->sendDragDropEvent(d->dragDropItem, &dragLeave);
- d->dragDropItem = 0;
- }
- // Propagate
- event->setDropAction(Qt::IgnoreAction);
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a subclass
- to receive drag leave events for the scene.
-
- \sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
- dropEvent()
-*/
-void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_D(QGraphicsScene);
- if (d->dragDropItem) {
- // Leave the last drag drop item
- d->sendDragDropEvent(d->dragDropItem, event);
- d->dragDropItem = 0;
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a subclass
- to receive drop events for the scene.
-
- \sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
- dragLeaveEvent()
-*/
-void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
-{
- Q_UNUSED(event);
- Q_D(QGraphicsScene);
- if (d->dragDropItem) {
- // Drop on the last drag drop item
- d->sendDragDropEvent(d->dragDropItem, event);
- d->dragDropItem = 0;
- }
-}
-
-/*!
- This event handler, for event \a focusEvent, can be reimplemented in a
- subclass to receive focus in events.
-
- The default implementation sets focus on the scene, and then on the last
- focus item.
-
- \sa QGraphicsItem::focusOutEvent()
-*/
-void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
-{
- Q_D(QGraphicsScene);
-
- d->hasFocus = true;
- switch (focusEvent->reason()) {
- case Qt::TabFocusReason:
- if (!focusNextPrevChild(true))
- focusEvent->ignore();
- break;
- case Qt::BacktabFocusReason:
- if (!focusNextPrevChild(false))
- focusEvent->ignore();
- break;
- default:
- if (d->passiveFocusItem) {
- // Set focus on the last focus item
- setFocusItem(d->passiveFocusItem, focusEvent->reason());
- }
- break;
- }
-}
-
-/*!
- This event handler, for event \a focusEvent, can be reimplemented in a
- subclass to receive focus out events.
-
- The default implementation removes focus from any focus item, then removes
- focus from the scene.
-
- \sa QGraphicsItem::focusInEvent()
-*/
-void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
-{
- Q_D(QGraphicsScene);
- d->hasFocus = false;
- d->passiveFocusItem = d->focusItem;
- setFocusItem(0, focusEvent->reason());
-
- // Remove all popups when the scene loses focus.
- if (!d->popupWidgets.isEmpty())
- d->removePopup(d->popupWidgets.first());
-}
-
-/*!
- This event handler, for event \a helpEvent, can be
- reimplemented in a subclass to receive help events. The events
- are of type QEvent::ToolTip, which are created when a tooltip is
- requested.
-
- The default implementation shows the tooltip of the topmost
- item, i.e., the item with the highest z-value, at the mouse
- cursor position. If no item has a tooltip set, this function
- does nothing.
-
- \sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
-*/
-void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
-{
-#ifdef QT_NO_TOOLTIP
- Q_UNUSED(helpEvent);
-#else
- // Find the first item that does tooltips
- Q_D(QGraphicsScene);
- QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
- helpEvent->scenePos(),
- helpEvent->widget());
- QGraphicsItem *toolTipItem = 0;
- for (int i = 0; i < itemsAtPos.size(); ++i) {
- QGraphicsItem *tmp = itemsAtPos.at(i);
- if (tmp->d_func()->isProxyWidget()) {
- // if the item is a proxy widget, the event is forwarded to it
- sendEvent(tmp, helpEvent);
- if (helpEvent->isAccepted())
- return;
- }
- if (!tmp->toolTip().isEmpty()) {
- toolTipItem = tmp;
- break;
- }
- }
-
- // Show or hide the tooltip
- QString text;
- QPoint point;
- if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
- text = toolTipItem->toolTip();
- point = helpEvent->screenPos();
- }
- QToolTip::showText(point, text, helpEvent->widget());
- helpEvent->setAccepted(!text.isEmpty());
-#endif
-}
-
-bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
-{
- return (item->d_ptr->acceptsHover
- || (item->d_ptr->isWidget
- && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration()))
- && !item->isBlockedByModalPanel();
-}
-
-/*!
- This event handler, for event \a hoverEvent, can be reimplemented in a
- subclass to receive hover enter events. The default implementation
- forwards the event to the topmost item that accepts hover events at the
- scene position from the event.
-
- \sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
-*/
-bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
-{
- if (allItemsIgnoreHoverEvents)
- return false;
-
- // Find the first item that accepts hover events, reusing earlier
- // calculated data is possible.
- if (cachedItemsUnderMouse.isEmpty()) {
- cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
- hoverEvent->scenePos(),
- hoverEvent->widget());
- }
-
- QGraphicsItem *item = 0;
- for (int i = 0; i < cachedItemsUnderMouse.size(); ++i) {
- QGraphicsItem *tmp = cachedItemsUnderMouse.at(i);
- if (itemAcceptsHoverEvents_helper(tmp)) {
- item = tmp;
- break;
- }
- }
-
- // Find the common ancestor item for the new topmost hoverItem and the
- // last item in the hoverItem list.
- QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.last()) : 0;
- while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
- commonAncestorItem = commonAncestorItem->parentItem();
- if (commonAncestorItem && commonAncestorItem->panel() != item->panel()) {
- // The common ancestor isn't in the same panel as the two hovered
- // items.
- commonAncestorItem = 0;
- }
-
- // Check if the common ancestor item is known.
- int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
- // Send hover leaves to any existing hovered children of the common
- // ancestor item.
- for (int i = hoverItems.size() - 1; i > index; --i) {
- QGraphicsItem *lastItem = hoverItems.takeLast();
- if (itemAcceptsHoverEvents_helper(lastItem))
- sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
- }
-
- // Item is a child of a known item. Generate enter events for the
- // missing links.
- QList<QGraphicsItem *> parents;
- QGraphicsItem *parent = item;
- while (parent && parent != commonAncestorItem) {
- parents.prepend(parent);
- if (parent->isPanel()) {
- // Stop at the panel - we don't deliver beyond this point.
- break;
- }
- parent = parent->parentItem();
- }
- for (int i = 0; i < parents.size(); ++i) {
- parent = parents.at(i);
- hoverItems << parent;
- if (itemAcceptsHoverEvents_helper(parent))
- sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
- }
-
- // Generate a move event for the item itself
- if (item
- && !hoverItems.isEmpty()
- && item == hoverItems.last()) {
- sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
- return true;
- }
- return false;
-}
-
-/*!
- \internal
-
- Handles all actions necessary to clean up the scene when the mouse leaves
- the view.
-*/
-void QGraphicsScenePrivate::leaveScene(QWidget *viewport)
-{
-#ifndef QT_NO_TOOLTIP
- QToolTip::hideText();
-#endif
- QGraphicsView *view = qobject_cast<QGraphicsView *>(viewport->parent());
- // Send HoverLeave events to all existing hover items, topmost first.
- QGraphicsSceneHoverEvent hoverEvent;
- hoverEvent.setWidget(viewport);
-
- if (view) {
- QPoint cursorPos = QCursor::pos();
- hoverEvent.setScenePos(view->mapToScene(viewport->mapFromGlobal(cursorPos)));
- hoverEvent.setLastScenePos(hoverEvent.scenePos());
- hoverEvent.setScreenPos(cursorPos);
- hoverEvent.setLastScreenPos(hoverEvent.screenPos());
- }
-
- while (!hoverItems.isEmpty()) {
- QGraphicsItem *lastItem = hoverItems.takeLast();
- if (itemAcceptsHoverEvents_helper(lastItem))
- sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
- }
-}
-
-/*!
- This event handler, for event \a keyEvent, can be reimplemented in a
- subclass to receive keypress events. The default implementation forwards
- the event to current focus item.
-
- \sa QGraphicsItem::keyPressEvent(), focusItem()
-*/
-void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
-{
- // ### Merge this function with keyReleaseEvent; they are identical
- // ### (except this comment).
- Q_D(QGraphicsScene);
- QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
- if (!item)
- item = focusItem();
- if (item) {
- QGraphicsItem *p = item;
- do {
- // Accept the event by default
- keyEvent->accept();
- // Send it; QGraphicsItem::keyPressEvent ignores it. If the event
- // is filtered out, stop propagating it.
- if (p->isBlockedByModalPanel())
- break;
- if (!d->sendEvent(p, keyEvent))
- break;
- } while (!keyEvent->isAccepted() && !p->isPanel() && (p = p->parentItem()));
- } else {
- keyEvent->ignore();
- }
-}
-
-/*!
- This event handler, for event \a keyEvent, can be reimplemented in a
- subclass to receive key release events. The default implementation
- forwards the event to current focus item.
-
- \sa QGraphicsItem::keyReleaseEvent(), focusItem()
-*/
-void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
-{
- // ### Merge this function with keyPressEvent; they are identical (except
- // ### this comment).
- Q_D(QGraphicsScene);
- QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.last() : 0;
- if (!item)
- item = focusItem();
- if (item) {
- QGraphicsItem *p = item;
- do {
- // Accept the event by default
- keyEvent->accept();
- // Send it; QGraphicsItem::keyPressEvent ignores it. If the event
- // is filtered out, stop propagating it.
- if (p->isBlockedByModalPanel())
- break;
- if (!d->sendEvent(p, keyEvent))
- break;
- } while (!keyEvent->isAccepted() && !p->isPanel() && (p = p->parentItem()));
- } else {
- keyEvent->ignore();
- }
-}
-
-/*!
- This event handler, for event \a mouseEvent, can be reimplemented
- in a subclass to receive mouse press events for the scene.
-
- The default implementation depends on the state of the scene. If
- there is a mouse grabber item, then the event is sent to the mouse
- grabber. Otherwise, it is forwarded to the topmost item that
- accepts mouse events at the scene position from the event, and
- that item promptly becomes the mouse grabber item.
-
- If there is no item at the given position on the scene, the
- selection area is reset, any focus item loses its input focus, and
- the event is then ignored.
-
- \sa QGraphicsItem::mousePressEvent(),
- QGraphicsItem::setAcceptedMouseButtons()
-*/
-void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
-{
- Q_D(QGraphicsScene);
- if (d->mouseGrabberItems.isEmpty()) {
- // Dispatch hover events
- QGraphicsSceneHoverEvent hover;
- _q_hoverFromMouseEvent(&hover, mouseEvent);
- d->dispatchHoverEvent(&hover);
- }
-
- d->mousePressEventHandler(mouseEvent);
-}
-
-/*!
- This event handler, for event \a mouseEvent, can be reimplemented
- in a subclass to receive mouse move events for the scene.
-
- The default implementation depends on the mouse grabber state. If there is
- a mouse grabber item, the event is sent to the mouse grabber. If there
- are any items that accept hover events at the current position, the event
- is translated into a hover event and accepted; otherwise it's ignored.
-
- \sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
- QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
-*/
-void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
-{
- Q_D(QGraphicsScene);
- if (d->mouseGrabberItems.isEmpty()) {
- if (mouseEvent->buttons())
- return;
- QGraphicsSceneHoverEvent hover;
- _q_hoverFromMouseEvent(&hover, mouseEvent);
- mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
- return;
- }
-
- // Forward the event to the mouse grabber
- d->sendMouseEvent(mouseEvent);
- mouseEvent->accept();
-}
-
-/*!
- This event handler, for event \a mouseEvent, can be reimplemented
- in a subclass to receive mouse release events for the scene.
-
- The default implementation depends on the mouse grabber state. If
- there is no mouse grabber, the event is ignored. Otherwise, if
- there is a mouse grabber item, the event is sent to the mouse
- grabber. If this mouse release represents the last pressed button
- on the mouse, the mouse grabber item then loses the mouse grab.
-
- \sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
- QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
-*/
-void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
-{
- Q_D(QGraphicsScene);
- if (d->mouseGrabberItems.isEmpty()) {
- mouseEvent->ignore();
- return;
- }
-
- // Forward the event to the mouse grabber
- d->sendMouseEvent(mouseEvent);
- mouseEvent->accept();
-
- // Reset the mouse grabber when the last mouse button has been released.
- if (!mouseEvent->buttons()) {
- if (!d->mouseGrabberItems.isEmpty()) {
- d->lastMouseGrabberItem = d->mouseGrabberItems.last();
- if (d->lastMouseGrabberItemHasImplicitMouseGrab)
- d->mouseGrabberItems.last()->ungrabMouse();
- } else {
- d->lastMouseGrabberItem = 0;
- }
-
- // Generate a hoverevent
- QGraphicsSceneHoverEvent hoverEvent;
- _q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
- d->dispatchHoverEvent(&hoverEvent);
- }
-}
-
-/*!
- This event handler, for event \a mouseEvent, can be reimplemented
- in a subclass to receive mouse doubleclick events for the scene.
-
- If someone doubleclicks on the scene, the scene will first receive
- a mouse press event, followed by a release event (i.e., a click),
- then a doubleclick event, and finally a release event. If the
- doubleclick event is delivered to a different item than the one
- that received the first press and release, it will be delivered as
- a press event. However, tripleclick events are not delivered as
- doubleclick events in this case.
-
- The default implementation is similar to mousePressEvent().
-
- \sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
- QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
-*/
-void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
-{
- Q_D(QGraphicsScene);
- d->mousePressEventHandler(mouseEvent);
-}
-
-/*!
- This event handler, for event \a wheelEvent, can be reimplemented in a
- subclass to receive mouse wheel events for the scene.
-
- By default, the event is delivered to the topmost visible item under the
- cursor. If ignored, the event propagates to the item beneath, and again
- until the event is accepted, or it reaches the scene. If no items accept
- the event, it is ignored.
-
- \sa QGraphicsItem::wheelEvent()
-*/
-void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
-{
- Q_D(QGraphicsScene);
- QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
- wheelEvent->scenePos(),
- wheelEvent->widget());
-
-#ifdef Q_WS_MAC
- // On Mac, ignore the event if the first item under the mouse is not the last opened
- // popup (or one of its descendant)
- if (!d->popupWidgets.isEmpty() && !wheelCandidates.isEmpty() && wheelCandidates.first() != d->popupWidgets.back() && !d->popupWidgets.back()->isAncestorOf(wheelCandidates.first())) {
- wheelEvent->accept();
- return;
- }
-#else
- // Find the first popup under the mouse (including the popup's descendants) starting from the last.
- // Remove all popups after the one found, or all or them if no popup is under the mouse.
- // Then continue with the event.
- QList<QGraphicsWidget *>::const_iterator iter = d->popupWidgets.end();
- while (--iter >= d->popupWidgets.begin() && !wheelCandidates.isEmpty()) {
- if (wheelCandidates.first() == *iter || (*iter)->isAncestorOf(wheelCandidates.first()))
- break;
- d->removePopup(*iter);
- }
-#endif
-
- bool hasSetFocus = false;
- foreach (QGraphicsItem *item, wheelCandidates) {
- if (!hasSetFocus && item->isEnabled()
- && ((item->flags() & QGraphicsItem::ItemIsFocusable) && item->d_ptr->mouseSetsFocus)) {
- if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
- hasSetFocus = true;
- if (item != focusItem())
- setFocusItem(item, Qt::MouseFocusReason);
- }
- }
-
- wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
- wheelEvent->widget()));
- wheelEvent->accept();
- bool isPanel = item->isPanel();
- d->sendEvent(item, wheelEvent);
- if (isPanel || wheelEvent->isAccepted())
- break;
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive input method events for the scene.
-
- The default implementation forwards the event to the focusItem().
- If no item currently has focus or the current focus item does not
- accept input methods, this function does nothing.
-
- \sa QGraphicsItem::inputMethodEvent()
-*/
-void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
-{
- Q_D(QGraphicsScene);
- if (d->focusItem && (d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod))
- d->sendEvent(d->focusItem, event);
-}
-
-/*!
- Draws the background of the scene using \a painter, before any items and
- the foreground are drawn. Reimplement this function to provide a custom
- background for the scene.
-
- All painting is done in \e scene coordinates. The \a rect
- parameter is the exposed rectangle.
-
- If all you want is to define a color, texture, or gradient for the
- background, you can call setBackgroundBrush() instead.
-
- \sa drawForeground(), drawItems()
-*/
-void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
-{
- Q_D(QGraphicsScene);
-
- if (d->backgroundBrush.style() != Qt::NoBrush) {
- if (d->painterStateProtection)
- painter->save();
- painter->setBrushOrigin(0, 0);
- painter->fillRect(rect, backgroundBrush());
- if (d->painterStateProtection)
- painter->restore();
- }
-}
-
-/*!
- Draws the foreground of the scene using \a painter, after the background
- and all items have been drawn. Reimplement this function to provide a
- custom foreground for the scene.
-
- All painting is done in \e scene coordinates. The \a rect
- parameter is the exposed rectangle.
-
- If all you want is to define a color, texture or gradient for the
- foreground, you can call setForegroundBrush() instead.
-
- \sa drawBackground(), drawItems()
-*/
-void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
-{
- Q_D(QGraphicsScene);
-
- if (d->foregroundBrush.style() != Qt::NoBrush) {
- if (d->painterStateProtection)
- painter->save();
- painter->setBrushOrigin(0, 0);
- painter->fillRect(rect, foregroundBrush());
- if (d->painterStateProtection)
- painter->restore();
- }
-}
-
-static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
- const QStyleOptionGraphicsItem *option, QWidget *widget,
- bool useWindowOpacity, bool painterStateProtection)
-{
- if (!item->isWidget()) {
- item->paint(painter, option, widget);
- return;
- }
- QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
- QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
- const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
- ? proxy->widget()->windowOpacity() : 1.0;
- const qreal oldPainterOpacity = painter->opacity();
-
- if (qFuzzyIsNull(windowOpacity))
- return;
- // Set new painter opacity.
- if (windowOpacity < 1.0)
- painter->setOpacity(oldPainterOpacity * windowOpacity);
-
- // set layoutdirection on the painter
- Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
- painter->setLayoutDirection(widgetItem->layoutDirection());
-
- if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
- && !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
- if (painterStateProtection)
- painter->save();
- widgetItem->paintWindowFrame(painter, option, widget);
- if (painterStateProtection)
- painter->restore();
- } else if (widgetItem->autoFillBackground()) {
- painter->fillRect(option->exposedRect, widgetItem->palette().window());
- }
-
- widgetItem->paint(painter, option, widget);
-
- // Restore layoutdirection on the painter.
- painter->setLayoutDirection(oldLayoutDirection);
- // Restore painter opacity.
- if (windowOpacity < 1.0)
- painter->setOpacity(oldPainterOpacity);
-}
-
-static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
- const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
- const QStyleOptionGraphicsItem *option, bool painterStateProtection)
-{
- QPixmap subPix;
- QPainter pixmapPainter;
- QRect br = pixmapExposed.boundingRect();
-
- // Don't use subpixmap if we get a full update.
- if (pixmapExposed.isEmpty() || (pixmapExposed.rectCount() == 1 && br.contains(pix->rect()))) {
- pix->fill(Qt::transparent);
- pixmapPainter.begin(pix);
- } else {
- subPix = QPixmap(br.size());
- subPix.fill(Qt::transparent);
- pixmapPainter.begin(&subPix);
- pixmapPainter.translate(-br.topLeft());
- if (!pixmapExposed.isEmpty()) {
- // Applied to subPix; paint is adjusted to the coordinate space is
- // correct.
- pixmapPainter.setClipRegion(pixmapExposed);
- }
- }
-
- pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
- pixmapPainter.setRenderHints(renderHints, true);
- pixmapPainter.setWorldTransform(itemToPixmap, true);
-
- // Render.
- _q_paintItem(item, &pixmapPainter, option, 0, false, painterStateProtection);
- pixmapPainter.end();
-
- if (!subPix.isNull()) {
- // Blit the subpixmap into the main pixmap.
- pixmapPainter.begin(pix);
- pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
- pixmapPainter.setClipRegion(pixmapExposed);
- pixmapPainter.drawPixmap(br.topLeft(), subPix);
- pixmapPainter.end();
- }
-}
-
-// Copied from qpaintengine_vg.cpp
-// Returns true for 90, 180, and 270 degree rotations.
-static inline bool transformIsSimple(const QTransform& transform)
-{
- QTransform::TransformationType type = transform.type();
- if (type <= QTransform::TxScale) {
- return true;
- } else if (type == QTransform::TxRotate) {
- // Check for 90, and 270 degree rotations.
- qreal m11 = transform.m11();
- qreal m12 = transform.m12();
- qreal m21 = transform.m21();
- qreal m22 = transform.m22();
- if (m11 == 0.0f && m22 == 0.0f) {
- if (m12 == 1.0f && m21 == -1.0f)
- return true; // 90 degrees.
- else if (m12 == -1.0f && m21 == 1.0f)
- return true; // 270 degrees.
- else if (m12 == -1.0f && m21 == -1.0f)
- return true; // 90 degrees inverted y.
- else if (m12 == 1.0f && m21 == 1.0f)
- return true; // 270 degrees inverted y.
- }
- }
- return false;
-}
-
-/*!
- \internal
-
- Draws items directly, or using cache.
-*/
-void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
- const QStyleOptionGraphicsItem *option, QWidget *widget,
- bool painterStateProtection)
-{
- QGraphicsItemPrivate *itemd = item->d_ptr.data();
- QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
-
- // Render directly, using no cache.
- if (cacheMode == QGraphicsItem::NoCache
-#ifdef Q_WS_X11
- || !X11->use_xrender
-#endif
- ) {
- _q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
- return;
- }
-
- const qreal oldPainterOpacity = painter->opacity();
- qreal newPainterOpacity = oldPainterOpacity;
- QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
- if (proxy && proxy->widget()) {
- const qreal windowOpacity = proxy->widget()->windowOpacity();
- if (windowOpacity < 1.0)
- newPainterOpacity *= windowOpacity;
- }
-
- // Item's (local) bounding rect
- QRectF brect = item->boundingRect();
- QRectF adjustedBrect(brect);
- _q_adjustRect(&adjustedBrect);
- if (adjustedBrect.isEmpty())
- return;
-
- // Fetch the off-screen transparent buffer and exposed area info.
- QPixmapCache::Key pixmapKey;
- QPixmap pix;
- bool pixmapFound;
- QGraphicsItemCache *itemCache = itemd->extraItemCache();
- if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
- pixmapKey = itemCache->key;
- } else {
- pixmapKey = itemCache->deviceData.value(widget).key;
- }
-
- // Find pixmap in cache.
- pixmapFound = QPixmapCache::find(pixmapKey, &pix);
-
- // Render using item coordinate cache mode.
- if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
- QSize pixmapSize;
- bool fixedCacheSize = false;
- QRect br = brect.toAlignedRect();
- if ((fixedCacheSize = itemCache->fixedSize.isValid())) {
- pixmapSize = itemCache->fixedSize;
- } else {
- pixmapSize = br.size();
- }
-
- // Create or recreate the pixmap.
- int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
- QSize adjustSize(adjust*2, adjust*2);
- br.adjust(-adjust, -adjust, adjust, adjust);
- if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
- pix = QPixmap(pixmapSize + adjustSize);
- itemCache->boundingRect = br;
- itemCache->exposed.clear();
- itemCache->allExposed = true;
- } else if (itemCache->boundingRect != br) {
- itemCache->boundingRect = br;
- itemCache->exposed.clear();
- itemCache->allExposed = true;
- }
-
- // Redraw any newly exposed areas.
- if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
-
- //We know that we will modify the pixmap, removing it from the cache
- //will detach the one we have and avoid a deep copy
- if (pixmapFound)
- QPixmapCache::remove(pixmapKey);
-
- // Fit the item's bounding rect into the pixmap's coordinates.
- QTransform itemToPixmap;
- if (fixedCacheSize) {
- const QPointF scale(pixmapSize.width() / brect.width(), pixmapSize.height() / brect.height());
- itemToPixmap.scale(scale.x(), scale.y());
- }
- itemToPixmap.translate(-br.x(), -br.y());
-
- // Generate the item's exposedRect and map its list of expose
- // rects to device coordinates.
- styleOptionTmp = *option;
- QRegion pixmapExposed;
- QRectF exposedRect;
- if (!itemCache->allExposed) {
- for (int i = 0; i < itemCache->exposed.size(); ++i) {
- QRectF r = itemCache->exposed.at(i);
- exposedRect |= r;
- pixmapExposed += itemToPixmap.mapRect(r).toAlignedRect();
- }
- } else {
- exposedRect = brect;
- }
- styleOptionTmp.exposedRect = exposedRect;
-
- // Render.
- _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
- &styleOptionTmp, painterStateProtection);
-
- // insert this pixmap into the cache.
- itemCache->key = QPixmapCache::insert(pix);
-
- // Reset expose data.
- itemCache->allExposed = false;
- itemCache->exposed.clear();
- }
-
- // Redraw the exposed area using the transformed painter. Depending on
- // the hardware, this may be a server-side operation, or an expensive
- // qpixmap-image-transform-pixmap roundtrip.
- if (newPainterOpacity != oldPainterOpacity) {
- painter->setOpacity(newPainterOpacity);
- painter->drawPixmap(br.topLeft(), pix);
- painter->setOpacity(oldPainterOpacity);
- } else {
- painter->drawPixmap(br.topLeft(), pix);
- }
- return;
- }
-
- // Render using device coordinate cache mode.
- if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
- // Find the item's bounds in device coordinates.
- QRectF deviceBounds = painter->worldTransform().mapRect(brect);
- QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
- if (deviceRect.isEmpty())
- return;
- QRect viewRect = widget ? widget->rect() : QRect();
- if (widget && !viewRect.intersects(deviceRect))
- return;
-
- // Resort to direct rendering if the device rect exceeds the
- // (optional) maximum bounds. (QGraphicsSvgItem uses this).
- QSize maximumCacheSize =
- itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
- if (!maximumCacheSize.isEmpty()
- && (deviceRect.width() > maximumCacheSize.width()
- || deviceRect.height() > maximumCacheSize.height())) {
- _q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
- oldPainterOpacity != newPainterOpacity, painterStateProtection);
- return;
- }
-
- // Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
- // If the world transform is rotated we always recreate the cache to avoid
- // wrong blending.
- bool pixModified = false;
- QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
- bool invertable = true;
- QTransform diff = deviceData->lastTransform.inverted(&invertable);
- if (invertable)
- diff *= painter->worldTransform();
- deviceData->lastTransform = painter->worldTransform();
- bool allowPartialCacheExposure = false;
- bool simpleTransform = invertable && diff.type() <= QTransform::TxTranslate
- && transformIsSimple(painter->worldTransform());
- if (!simpleTransform) {
- pixModified = true;
- itemCache->allExposed = true;
- itemCache->exposed.clear();
- deviceData->cacheIndent = QPoint();
- pix = QPixmap();
- } else if (!viewRect.isNull()) {
- allowPartialCacheExposure = deviceData->cacheIndent != QPoint();
- }
-
- // Allow partial cache exposure if the device rect isn't fully contained and
- // deviceRect is 20% taller or wider than the viewRect.
- if (!allowPartialCacheExposure && !viewRect.isNull() && !viewRect.contains(deviceRect)) {
- allowPartialCacheExposure = (viewRect.width() * 1.2 < deviceRect.width())
- || (viewRect.height() * 1.2 < deviceRect.height());
- }
-
- QRegion scrollExposure;
- if (allowPartialCacheExposure) {
- // Part of pixmap is drawn. Either device contains viewrect (big
- // item covers whole screen) or parts of device are outside the
- // viewport. In either case the device rect must be the intersect
- // between the two.
- int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
- int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
- QPoint newCacheIndent(dx, dy);
- deviceRect &= viewRect;
-
- if (pix.isNull()) {
- deviceData->cacheIndent = QPoint();
- itemCache->allExposed = true;
- itemCache->exposed.clear();
- pixModified = true;
- }
-
- // Copy / "scroll" the old pixmap onto the new ole and calculate
- // scrolled exposure.
- if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size()) {
- QPoint diff = newCacheIndent - deviceData->cacheIndent;
- QPixmap newPix(deviceRect.size());
- // ### Investigate removing this fill (test with Plasma and
- // graphicssystem raster).
- newPix.fill(Qt::transparent);
- if (!pix.isNull()) {
- QPainter newPixPainter(&newPix);
- newPixPainter.drawPixmap(-diff, pix);
- newPixPainter.end();
- }
- QRegion exposed;
- exposed += newPix.rect();
- if (!pix.isNull())
- exposed -= QRect(-diff, pix.size());
- scrollExposure = exposed;
-
- pix = newPix;
- pixModified = true;
- }
- deviceData->cacheIndent = newCacheIndent;
- } else {
- // Full pixmap is drawn.
- deviceData->cacheIndent = QPoint();
-
- // Auto-adjust the pixmap size.
- if (deviceRect.size() != pix.size()) {
- // exposed needs to cover the whole pixmap
- pix = QPixmap(deviceRect.size());
- pixModified = true;
- itemCache->allExposed = true;
- itemCache->exposed.clear();
- }
- }
-
- // Check for newly invalidated areas.
- if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
- //We know that we will modify the pixmap, removing it from the cache
- //will detach the one we have and avoid a deep copy
- if (pixmapFound)
- QPixmapCache::remove(pixmapKey);
-
- // Construct an item-to-pixmap transform.
- QPointF p = deviceRect.topLeft();
- QTransform itemToPixmap = painter->worldTransform();
- if (!p.isNull())
- itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
-
- // Map the item's logical expose to pixmap coordinates.
- QRegion pixmapExposed = scrollExposure;
- if (!itemCache->allExposed) {
- const QVector<QRectF> &exposed = itemCache->exposed;
- for (int i = 0; i < exposed.size(); ++i)
- pixmapExposed += itemToPixmap.mapRect(exposed.at(i)).toRect().adjusted(-1, -1, 1, 1);
- }
-
- // Calculate the style option's exposedRect.
- QRectF br;
- if (itemCache->allExposed) {
- br = item->boundingRect();
- } else {
- const QVector<QRectF> &exposed = itemCache->exposed;
- for (int i = 0; i < exposed.size(); ++i)
- br |= exposed.at(i);
- QTransform pixmapToItem = itemToPixmap.inverted();
- foreach (QRect r, scrollExposure.rects())
- br |= pixmapToItem.mapRect(r);
- }
- styleOptionTmp = *option;
- styleOptionTmp.exposedRect = br.adjusted(-1, -1, 1, 1);
-
- // Render the exposed areas.
- _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
- &styleOptionTmp, painterStateProtection);
-
- // Reset expose data.
- pixModified = true;
- itemCache->allExposed = false;
- itemCache->exposed.clear();
- }
-
- if (pixModified) {
- // Insert this pixmap into the cache.
- deviceData->key = QPixmapCache::insert(pix);
- }
-
- // Redraw the exposed area using an untransformed painter. This
- // effectively becomes a bitblit that does not transform the cache.
- QTransform restoreTransform = painter->worldTransform();
- painter->setWorldTransform(QTransform());
- if (newPainterOpacity != oldPainterOpacity) {
- painter->setOpacity(newPainterOpacity);
- painter->drawPixmap(deviceRect.topLeft(), pix);
- painter->setOpacity(oldPainterOpacity);
- } else {
- painter->drawPixmap(deviceRect.topLeft(), pix);
- }
- painter->setWorldTransform(restoreTransform);
- return;
- }
-}
-
-void QGraphicsScenePrivate::drawItems(QPainter *painter, const QTransform *const viewTransform,
- QRegion *exposedRegion, QWidget *widget)
-{
- // Make sure we don't have unpolished items before we draw.
- if (!unpolishedItems.isEmpty())
- _q_polishItems();
-
- updateAll = false;
- QRectF exposedSceneRect;
- if (exposedRegion && indexMethod != QGraphicsScene::NoIndex) {
- exposedSceneRect = exposedRegion->boundingRect().adjusted(-1, -1, 1, 1);
- if (viewTransform)
- exposedSceneRect = viewTransform->inverted().mapRect(exposedSceneRect);
- }
- const QList<QGraphicsItem *> tli = index->estimateTopLevelItems(exposedSceneRect, Qt::AscendingOrder);
- for (int i = 0; i < tli.size(); ++i)
- drawSubtreeRecursive(tli.at(i), painter, viewTransform, exposedRegion, widget);
-}
-
-void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter,
- const QTransform *const viewTransform,
- QRegion *exposedRegion, QWidget *widget,
- qreal parentOpacity, const QTransform *const effectTransform)
-{
- Q_ASSERT(item);
-
- if (!item->d_ptr->visible)
- return;
-
- const bool itemHasContents = !(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents);
- const bool itemHasChildren = !item->d_ptr->children.isEmpty();
- if (!itemHasContents && !itemHasChildren)
- return; // Item has neither contents nor children!(?)
-
- const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
- const bool itemIsFullyTransparent = QGraphicsItemPrivate::isOpacityNull(opacity);
- if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity()))
- return;
-
- QTransform transform(Qt::Uninitialized);
- QTransform *transformPtr = 0;
- bool translateOnlyTransform = false;
-#define ENSURE_TRANSFORM_PTR \
- if (!transformPtr) { \
- Q_ASSERT(!itemIsUntransformable); \
- if (viewTransform) { \
- transform = item->d_ptr->sceneTransform; \
- transform *= *viewTransform; \
- transformPtr = &transform; \
- } else { \
- transformPtr = &item->d_ptr->sceneTransform; \
- translateOnlyTransform = item->d_ptr->sceneTransformTranslateOnly; \
- } \
- }
-
- // Update the item's scene transform if the item is transformable;
- // otherwise calculate the full transform,
- bool wasDirtyParentSceneTransform = false;
- const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable();
- if (itemIsUntransformable) {
- transform = item->deviceTransform(viewTransform ? *viewTransform : QTransform());
- transformPtr = &transform;
- } else if (item->d_ptr->dirtySceneTransform) {
- item->d_ptr->updateSceneTransformFromParent();
- Q_ASSERT(!item->d_ptr->dirtySceneTransform);
- wasDirtyParentSceneTransform = true;
- }
-
- const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
- bool drawItem = itemHasContents && !itemIsFullyTransparent;
- if (drawItem) {
- const QRectF brect = adjustedItemEffectiveBoundingRect(item);
- ENSURE_TRANSFORM_PTR
- QRect viewBoundingRect = translateOnlyTransform ? brect.translated(transformPtr->dx(), transformPtr->dy()).toAlignedRect()
- : transformPtr->mapRect(brect).toAlignedRect();
- viewBoundingRect.adjust(-int(rectAdjust), -int(rectAdjust), rectAdjust, rectAdjust);
- if (widget)
- item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect);
- drawItem = exposedRegion ? exposedRegion->intersects(viewBoundingRect)
- : !viewBoundingRect.normalized().isEmpty();
- if (!drawItem) {
- if (!itemHasChildren)
- return;
- if (itemClipsChildrenToShape) {
- if (wasDirtyParentSceneTransform)
- item->d_ptr->invalidateChildrenSceneTransform();
- return;
- }
- }
- } // else we know for sure this item has children we must process.
-
- if (itemHasChildren && itemClipsChildrenToShape)
- ENSURE_TRANSFORM_PTR;
-
-#ifndef QT_NO_GRAPHICSEFFECT
- if (item->d_ptr->graphicsEffect && item->d_ptr->graphicsEffect->isEnabled()) {
- ENSURE_TRANSFORM_PTR;
- QGraphicsItemPaintInfo info(viewTransform, transformPtr, effectTransform, exposedRegion, widget, &styleOptionTmp,
- painter, opacity, wasDirtyParentSceneTransform, itemHasContents && !itemIsFullyTransparent);
- QGraphicsEffectSource *source = item->d_ptr->graphicsEffect->d_func()->source;
- QGraphicsItemEffectSourcePrivate *sourced = static_cast<QGraphicsItemEffectSourcePrivate *>
- (source->d_func());
- sourced->info = &info;
- const QTransform restoreTransform = painter->worldTransform();
- if (effectTransform)
- painter->setWorldTransform(*transformPtr * *effectTransform);
- else
- painter->setWorldTransform(*transformPtr);
- painter->setOpacity(opacity);
-
- if (sourced->currentCachedSystem() != Qt::LogicalCoordinates
- && sourced->lastEffectTransform != painter->worldTransform())
- {
- if (sourced->lastEffectTransform.type() <= QTransform::TxTranslate
- && painter->worldTransform().type() <= QTransform::TxTranslate)
- {
- QRectF sourceRect = sourced->boundingRect(Qt::DeviceCoordinates);
- QRect effectRect = sourced->paddedEffectRect(Qt::DeviceCoordinates, sourced->currentCachedMode(), sourceRect);
-
- sourced->setCachedOffset(effectRect.topLeft());
- } else {
- sourced->invalidateCache(QGraphicsEffectSourcePrivate::TransformChanged);
- }
-
- sourced->lastEffectTransform = painter->worldTransform();
- }
-
- item->d_ptr->graphicsEffect->draw(painter);
- painter->setWorldTransform(restoreTransform);
- sourced->info = 0;
- } else
-#endif //QT_NO_GRAPHICSEFFECT
- {
- draw(item, painter, viewTransform, transformPtr, exposedRegion, widget, opacity,
- effectTransform, wasDirtyParentSceneTransform, drawItem);
- }
-}
-
-static inline void setClip(QPainter *painter, QGraphicsItem *item)
-{
- painter->save();
- QRectF clipRect;
- const QPainterPath clipPath(item->shape());
- if (QPathClipper::pathToRect(clipPath, &clipRect))
- painter->setClipRect(clipRect, Qt::IntersectClip);
- else
- painter->setClipPath(clipPath, Qt::IntersectClip);
-}
-
-static inline void setWorldTransform(QPainter *painter, const QTransform *const transformPtr,
- const QTransform *effectTransform)
-{
- Q_ASSERT(transformPtr);
- if (effectTransform)
- painter->setWorldTransform(*transformPtr * *effectTransform);
- else
- painter->setWorldTransform(*transformPtr);
-}
-
-void QGraphicsScenePrivate::draw(QGraphicsItem *item, QPainter *painter, const QTransform *const viewTransform,
- const QTransform *const transformPtr, QRegion *exposedRegion, QWidget *widget,
- qreal opacity, const QTransform *effectTransform,
- bool wasDirtyParentSceneTransform, bool drawItem)
-{
- const bool itemIsFullyTransparent = QGraphicsItemPrivate::isOpacityNull(opacity);
- const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
- const bool itemHasChildren = !item->d_ptr->children.isEmpty();
- bool setChildClip = itemClipsChildrenToShape;
- bool itemHasChildrenStackedBehind = false;
-
- int i = 0;
- if (itemHasChildren) {
- if (itemClipsChildrenToShape)
- setWorldTransform(painter, transformPtr, effectTransform);
-
- item->d_ptr->ensureSortedChildren();
- // Items with the 'ItemStacksBehindParent' flag are put in front of the list
- // so all we have to do is to check the first item.
- itemHasChildrenStackedBehind = (item->d_ptr->children.at(0)->d_ptr->flags
- & QGraphicsItem::ItemStacksBehindParent);
-
- if (itemHasChildrenStackedBehind) {
- if (itemClipsChildrenToShape) {
- setClip(painter, item);
- setChildClip = false;
- }
-
- // Draw children behind
- for (i = 0; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
- if (wasDirtyParentSceneTransform)
- child->d_ptr->dirtySceneTransform = 1;
- if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
- break;
- if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
- continue;
- drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, opacity, effectTransform);
- }
- }
- }
-
- // Draw item
- if (drawItem) {
- Q_ASSERT(!itemIsFullyTransparent);
- Q_ASSERT(!(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents));
- Q_ASSERT(transformPtr);
- item->d_ptr->initStyleOption(&styleOptionTmp, *transformPtr, exposedRegion
- ? *exposedRegion : QRegion(), exposedRegion == 0);
-
- const bool itemClipsToShape = item->d_ptr->flags & QGraphicsItem::ItemClipsToShape;
- bool restorePainterClip = false;
-
- if (!itemHasChildren || !itemClipsChildrenToShape) {
- // Item does not have children or clip children to shape.
- setWorldTransform(painter, transformPtr, effectTransform);
- if ((restorePainterClip = itemClipsToShape))
- setClip(painter, item);
- } else if (itemHasChildrenStackedBehind){
- // Item clips children to shape and has children stacked behind, which means
- // the painter is already clipped to the item's shape.
- if (itemClipsToShape) {
- // The clip is already correct. Ensure correct world transform.
- setWorldTransform(painter, transformPtr, effectTransform);
- } else {
- // Remove clip (this also ensures correct world transform).
- painter->restore();
- setChildClip = true;
- }
- } else if (itemClipsToShape) {
- // Item clips children and itself to shape. It does not have hildren stacked
- // behind, which means the clip has not yet been set. We set it now and re-use it
- // for the children.
- setClip(painter, item);
- setChildClip = false;
- }
-
- if (painterStateProtection && !restorePainterClip)
- painter->save();
-
- painter->setOpacity(opacity);
- if (!item->d_ptr->cacheMode && !item->d_ptr->isWidget)
- item->paint(painter, &styleOptionTmp, widget);
- else
- drawItemHelper(item, painter, &styleOptionTmp, widget, painterStateProtection);
-
- if (painterStateProtection || restorePainterClip)
- painter->restore();
-
- static int drawRect = qgetenv("QT_DRAW_SCENE_ITEM_RECTS").toInt();
- if (drawRect) {
- QPen oldPen = painter->pen();
- QBrush oldBrush = painter->brush();
- quintptr ptr = reinterpret_cast<quintptr>(item);
- const QColor color = QColor::fromHsv(ptr % 255, 255, 255);
- painter->setPen(color);
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(adjustedItemBoundingRect(item));
- painter->setPen(oldPen);
- painter->setBrush(oldBrush);
- }
- }
-
- // Draw children in front
- if (itemHasChildren) {
- if (setChildClip)
- setClip(painter, item);
-
- for (; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
- if (wasDirtyParentSceneTransform)
- child->d_ptr->dirtySceneTransform = 1;
- if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
- continue;
- drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, opacity, effectTransform);
- }
-
- // Restore child clip
- if (itemClipsChildrenToShape)
- painter->restore();
- }
-}
-
-void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren,
- bool force, bool ignoreOpacity, bool removingItemFromScene,
- bool updateBoundingRect)
-{
- Q_ASSERT(item);
- if (updateAll)
- return;
-
- if (removingItemFromScene && !ignoreOpacity && !item->d_ptr->ignoreOpacity) {
- // If any of the item's ancestors ignore opacity, it means that the opacity
- // was set to 0 (and the update request has not yet been processed). That
- // also means that we have to ignore the opacity for the item itself; otherwise
- // things like: parent->setOpacity(0); scene->removeItem(child) won't work.
- // Note that we only do this when removing items from the scene. In all other
- // cases the ignoreOpacity bit propagates properly in processDirtyItems, but
- // since the item is removed immediately it won't be processed there.
- QGraphicsItem *p = item->d_ptr->parent;
- while (p) {
- if (p->d_ptr->ignoreOpacity) {
- item->d_ptr->ignoreOpacity = true;
- break;
- }
- p = p->d_ptr->parent;
- }
- }
-
- if (item->d_ptr->discardUpdateRequest(/*ignoreVisibleBit=*/force,
- /*ignoreDirtyBit=*/removingItemFromScene || invalidateChildren,
- /*ignoreOpacity=*/ignoreOpacity)) {
- if (item->d_ptr->dirty) {
- // The item is already marked as dirty and will be processed later. However,
- // we have to make sure ignoreVisible and ignoreOpacity are set properly;
- // otherwise things like: item->update(); item->hide() (force is now true)
- // won't work as expected.
- if (force)
- item->d_ptr->ignoreVisible = 1;
- if (ignoreOpacity)
- item->d_ptr->ignoreOpacity = 1;
- }
- return;
- }
-
- const bool fullItemUpdate = rect.isNull();
- if (!fullItemUpdate && rect.isEmpty())
- return;
-
- if (!processDirtyItemsEmitted) {
- QMetaMethod method = q_ptr->metaObject()->method(processDirtyItemsIndex);
- method.invoke(q_ptr, Qt::QueuedConnection);
-// QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection);
- processDirtyItemsEmitted = true;
- }
-
- if (removingItemFromScene) {
- // Note that this function can be called from the item's destructor, so
- // do NOT call any virtual functions on it within this block.
- if (isSignalConnected(changedSignalIndex) || views.isEmpty()) {
- // This block of code is kept for compatibility. Since 4.5, by default
- // QGraphicsView does not connect the signal and we use the below
- // method of delivering updates.
- q_func()->update();
- return;
- }
-
- for (int i = 0; i < views.size(); ++i) {
- QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func();
- QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport);
- rect.translate(viewPrivate->dirtyScrollOffset);
- viewPrivate->updateRect(rect);
- }
- return;
- }
-
- bool hasNoContents = item->d_ptr->flags & QGraphicsItem::ItemHasNoContents;
- if (!hasNoContents) {
- item->d_ptr->dirty = 1;
- if (fullItemUpdate)
- item->d_ptr->fullUpdatePending = 1;
- else if (!item->d_ptr->fullUpdatePending)
- item->d_ptr->needsRepaint |= rect;
- } else if (item->d_ptr->graphicsEffect) {
- invalidateChildren = true;
- }
-
- if (invalidateChildren) {
- item->d_ptr->allChildrenDirty = 1;
- item->d_ptr->dirtyChildren = 1;
- }
-
- if (force)
- item->d_ptr->ignoreVisible = 1;
- if (ignoreOpacity)
- item->d_ptr->ignoreOpacity = 1;
-
- if (!updateBoundingRect)
- item->d_ptr->markParentDirty();
-}
-
-static inline bool updateHelper(QGraphicsViewPrivate *view, QGraphicsItemPrivate *item,
- const QRectF &rect, bool itemIsUntransformable)
-{
- Q_ASSERT(view);
- Q_ASSERT(item);
-
- QGraphicsItem *itemq = static_cast<QGraphicsItem *>(item->q_ptr);
- QGraphicsView *viewq = static_cast<QGraphicsView *>(view->q_ptr);
-
- if (itemIsUntransformable) {
- const QTransform xform = itemq->deviceTransform(viewq->viewportTransform());
- if (!item->hasBoundingRegionGranularity)
- return view->updateRectF(xform.mapRect(rect));
- return view->updateRegion(rect, xform);
- }
-
- if (item->sceneTransformTranslateOnly && view->identityMatrix) {
- const qreal dx = item->sceneTransform.dx();
- const qreal dy = item->sceneTransform.dy();
- QRectF r(rect);
- r.translate(dx - view->horizontalScroll(), dy - view->verticalScroll());
- return view->updateRectF(r);
- }
-
- if (!viewq->isTransformed()) {
- if (!item->hasBoundingRegionGranularity)
- return view->updateRectF(item->sceneTransform.mapRect(rect));
- return view->updateRegion(rect, item->sceneTransform);
- }
-
- QTransform xform = item->sceneTransform;
- xform *= viewq->viewportTransform();
- if (!item->hasBoundingRegionGranularity)
- return view->updateRectF(xform.mapRect(rect));
- return view->updateRegion(rect, xform);
-}
-
-void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren,
- qreal parentOpacity)
-{
- Q_Q(QGraphicsScene);
- Q_ASSERT(item);
- Q_ASSERT(!updateAll);
-
- if (!item->d_ptr->dirty && !item->d_ptr->dirtyChildren) {
- resetDirtyItem(item);
- return;
- }
-
- const bool itemIsHidden = !item->d_ptr->ignoreVisible && !item->d_ptr->visible;
- if (itemIsHidden) {
- resetDirtyItem(item, /*recursive=*/true);
- return;
- }
-
- bool itemHasContents = !(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents);
- const bool itemHasChildren = !item->d_ptr->children.isEmpty();
- if (!itemHasContents) {
- if (!itemHasChildren) {
- resetDirtyItem(item);
- return; // Item has neither contents nor children!(?)
- }
- if (item->d_ptr->graphicsEffect)
- itemHasContents = true;
- }
-
- const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
- const bool itemIsFullyTransparent = !item->d_ptr->ignoreOpacity
- && QGraphicsItemPrivate::isOpacityNull(opacity);
- if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity())) {
- resetDirtyItem(item, /*recursive=*/itemHasChildren);
- return;
- }
-
- bool wasDirtyParentSceneTransform = item->d_ptr->dirtySceneTransform;
- const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable();
- if (wasDirtyParentSceneTransform && !itemIsUntransformable) {
- item->d_ptr->updateSceneTransformFromParent();
- Q_ASSERT(!item->d_ptr->dirtySceneTransform);
- }
-
- const bool wasDirtyParentViewBoundingRects = item->d_ptr->paintedViewBoundingRectsNeedRepaint;
- if (itemIsFullyTransparent || !itemHasContents || dirtyAncestorContainsChildren) {
- // Make sure we don't process invisible items or items with no content.
- item->d_ptr->dirty = 0;
- item->d_ptr->fullUpdatePending = 0;
- // Might have a dirty view bounding rect otherwise.
- if (itemIsFullyTransparent || !itemHasContents)
- item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
- }
-
- if (!hasSceneRect && item->d_ptr->geometryChanged && item->d_ptr->visible) {
- // Update growingItemsBoundingRect.
- if (item->d_ptr->sceneTransformTranslateOnly) {
- growingItemsBoundingRect |= item->boundingRect().translated(item->d_ptr->sceneTransform.dx(),
- item->d_ptr->sceneTransform.dy());
- } else {
- growingItemsBoundingRect |= item->d_ptr->sceneTransform.mapRect(item->boundingRect());
- }
- }
-
- // Process item.
- if (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
- const bool useCompatUpdate = views.isEmpty() || isSignalConnected(changedSignalIndex);
- const QRectF itemBoundingRect = adjustedItemEffectiveBoundingRect(item);
-
- if (useCompatUpdate && !itemIsUntransformable && qFuzzyIsNull(item->boundingRegionGranularity())) {
- // This block of code is kept for compatibility. Since 4.5, by default
- // QGraphicsView does not connect the signal and we use the below
- // method of delivering updates.
- if (item->d_ptr->sceneTransformTranslateOnly) {
- q->update(itemBoundingRect.translated(item->d_ptr->sceneTransform.dx(),
- item->d_ptr->sceneTransform.dy()));
- } else {
- QRectF rect = item->d_ptr->sceneTransform.mapRect(itemBoundingRect);
- if (!rect.isEmpty())
- q->update(rect);
- }
- } else {
- QRectF dirtyRect;
- bool uninitializedDirtyRect = true;
-
- for (int j = 0; j < views.size(); ++j) {
- QGraphicsView *view = views.at(j);
- QGraphicsViewPrivate *viewPrivate = view->d_func();
- QRect &paintedViewBoundingRect = item->d_ptr->paintedViewBoundingRects[viewPrivate->viewport];
- if (viewPrivate->fullUpdatePending
- || viewPrivate->viewportUpdateMode == QGraphicsView::NoViewportUpdate) {
- // Okay, if we have a full update pending or no viewport update, this item's
- // paintedViewBoundingRect will be updated correctly in the next paintEvent if
- // it is inside the viewport, but for now we can pretend that it is outside.
- paintedViewBoundingRect = QRect(-1, -1, -1, -1);
- continue;
- }
-
- if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
- paintedViewBoundingRect.translate(viewPrivate->dirtyScrollOffset);
- if (!viewPrivate->updateRect(paintedViewBoundingRect))
- paintedViewBoundingRect = QRect(-1, -1, -1, -1); // Outside viewport.
- }
-
- if (!item->d_ptr->dirty)
- continue;
-
- if (!item->d_ptr->paintedViewBoundingRectsNeedRepaint
- && paintedViewBoundingRect.x() == -1 && paintedViewBoundingRect.y() == -1
- && paintedViewBoundingRect.width() == -1 && paintedViewBoundingRect.height() == -1) {
- continue; // Outside viewport.
- }
-
- if (uninitializedDirtyRect) {
- dirtyRect = itemBoundingRect;
- if (!item->d_ptr->fullUpdatePending) {
- _q_adjustRect(&item->d_ptr->needsRepaint);
- dirtyRect &= item->d_ptr->needsRepaint;
- }
- uninitializedDirtyRect = false;
- }
-
- if (dirtyRect.isEmpty())
- continue; // Discard updates outside the bounding rect.
-
- if (!updateHelper(viewPrivate, item->d_ptr.data(), dirtyRect, itemIsUntransformable)
- && item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
- paintedViewBoundingRect = QRect(-1, -1, -1, -1); // Outside viewport.
- }
- }
- }
- }
-
- // Process children.
- if (itemHasChildren && item->d_ptr->dirtyChildren) {
- const bool itemClipsChildrenToShape = item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape;
- // Items with no content are threated as 'dummy' items which means they are never drawn and
- // 'processed', so the painted view bounding rect is never up-to-date. This means that whenever
- // such an item changes geometry, its children have to take care of the update regardless
- // of whether the item clips children to shape or not.
- const bool bypassUpdateClip = !itemHasContents && wasDirtyParentViewBoundingRects;
- if (itemClipsChildrenToShape && !bypassUpdateClip) {
- // Make sure child updates are clipped to the item's bounding rect.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->setUpdateClip(item);
- }
- if (!dirtyAncestorContainsChildren) {
- dirtyAncestorContainsChildren = item->d_ptr->fullUpdatePending
- && itemClipsChildrenToShape;
- }
- const bool allChildrenDirty = item->d_ptr->allChildrenDirty;
- const bool parentIgnoresVisible = item->d_ptr->ignoreVisible;
- const bool parentIgnoresOpacity = item->d_ptr->ignoreOpacity;
- for (int i = 0; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
- if (wasDirtyParentSceneTransform)
- child->d_ptr->dirtySceneTransform = 1;
- if (wasDirtyParentViewBoundingRects)
- child->d_ptr->paintedViewBoundingRectsNeedRepaint = 1;
- if (parentIgnoresVisible)
- child->d_ptr->ignoreVisible = 1;
- if (parentIgnoresOpacity)
- child->d_ptr->ignoreOpacity = 1;
- if (allChildrenDirty) {
- child->d_ptr->dirty = 1;
- child->d_ptr->fullUpdatePending = 1;
- child->d_ptr->dirtyChildren = 1;
- child->d_ptr->allChildrenDirty = 1;
- }
- processDirtyItemsRecursive(child, dirtyAncestorContainsChildren, opacity);
- }
-
- if (itemClipsChildrenToShape) {
- // Reset updateClip.
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->setUpdateClip(0);
- }
- } else if (wasDirtyParentSceneTransform) {
- item->d_ptr->invalidateChildrenSceneTransform();
- }
-
- resetDirtyItem(item);
-}
-
-/*!
- \obsolete
-
- Paints the given \a items using the provided \a painter, after the
- background has been drawn, and before the foreground has been
- drawn. All painting is done in \e scene coordinates. Before
- drawing each item, the painter must be transformed using
- QGraphicsItem::sceneTransform().
-
- The \a options parameter is the list of style option objects for
- each item in \a items. The \a numItems parameter is the number of
- items in \a items and options in \a options. The \a widget
- parameter is optional; if specified, it should point to the widget
- that is being painted on.
-
- The default implementation prepares the painter matrix, and calls
- QGraphicsItem::paint() on all items. Reimplement this function to
- provide custom painting of all items for the scene; gaining
- complete control over how each item is drawn. In some cases this
- can increase drawing performance significantly.
-
- Example:
-
- \snippet doc/src/snippets/graphicssceneadditemsnippet.cpp 0
-
- Since Qt 4.6, this function is not called anymore unless
- the QGraphicsView::IndirectPainting flag is given as an Optimization
- flag.
-
- \sa drawBackground(), drawForeground()
-*/
-void QGraphicsScene::drawItems(QPainter *painter,
- int numItems,
- QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[], QWidget *widget)
-{
- Q_D(QGraphicsScene);
- // Make sure we don't have unpolished items before we draw.
- if (!d->unpolishedItems.isEmpty())
- d->_q_polishItems();
-
- const qreal opacity = painter->opacity();
- QTransform viewTransform = painter->worldTransform();
- Q_UNUSED(options);
-
- // Determine view, expose and flags.
- QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
- QRegion *expose = 0;
- const quint32 oldRectAdjust = d->rectAdjust;
- if (view) {
- d->updateAll = false;
- expose = &view->d_func()->exposedRegion;
- if (view->d_func()->optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
- d->rectAdjust = 1;
- else
- d->rectAdjust = 2;
- }
-
- // Find all toplevels, they are already sorted.
- QList<QGraphicsItem *> topLevelItems;
- for (int i = 0; i < numItems; ++i) {
- QGraphicsItem *item = items[i]->topLevelItem();
- if (!item->d_ptr->itemDiscovered) {
- topLevelItems << item;
- item->d_ptr->itemDiscovered = 1;
- d->drawSubtreeRecursive(item, painter, &viewTransform, expose, widget);
- }
- }
-
- d->rectAdjust = oldRectAdjust;
- // Reset discovery bits.
- for (int i = 0; i < topLevelItems.size(); ++i)
- topLevelItems.at(i)->d_ptr->itemDiscovered = 0;
-
- painter->setWorldTransform(viewTransform);
- painter->setOpacity(opacity);
-}
-
-/*!
- \since 4.4
-
- Finds a new widget to give the keyboard focus to, as appropriate for Tab
- and Shift+Tab, and returns true if it can find a new widget, or false if
- it cannot. If \a next is true, this function searches forward; if \a next
- is false, it searches backward.
-
- You can reimplement this function in a subclass of QGraphicsScene to
- provide fine-grained control over how tab focus passes inside your
- scene. The default implementation is based on the tab focus chain defined
- by QGraphicsWidget::setTabOrder().
-*/
-bool QGraphicsScene::focusNextPrevChild(bool next)
-{
- Q_D(QGraphicsScene);
-
- QGraphicsItem *item = focusItem();
- if (item && !item->isWidget()) {
- // Tab out of the scene.
- return false;
- }
- if (!item) {
- if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
- // Restore focus to the last focusable non-widget item that had
- // focus.
- setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
- return true;
- }
- }
- if (!d->tabFocusFirst) {
- // No widgets...
- return false;
- }
-
- // The item must be a widget.
- QGraphicsWidget *widget = 0;
- if (!item) {
- widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
- } else {
- QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
- widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
- if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
- return false;
- }
- QGraphicsWidget *widgetThatHadFocus = widget;
-
- // Run around the focus chain until we find a widget that can take tab focus.
- do {
- if (widget->flags() & QGraphicsItem::ItemIsFocusable
- && widget->isEnabled() && widget->isVisibleTo(0)
- && (widget->focusPolicy() & Qt::TabFocus)
- && (!item || !item->isPanel() || item->isAncestorOf(widget))
- ) {
- setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
- return true;
- }
- widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
- if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
- return false;
- } while (widget != widgetThatHadFocus);
-
- return false;
-}
-
-/*!
- \fn QGraphicsScene::changed(const QList<QRectF> &region)
-
- This signal is emitted by QGraphicsScene when control reaches the
- event loop, if the scene content changes. The \a region parameter
- contains a list of scene rectangles that indicate the area that
- has been changed.
-
- \sa QGraphicsView::updateScene()
-*/
-
-/*!
- \fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
-
- This signal is emitted by QGraphicsScene whenever the scene rect changes.
- The \a rect parameter is the new scene rectangle.
-
- \sa QGraphicsView::updateSceneRect()
-*/
-
-/*!
- \fn QGraphicsScene::selectionChanged()
- \since 4.3
-
- This signal is emitted by QGraphicsScene whenever the selection
- changes. You can call selectedItems() to get the new list of selected
- items.
-
- The selection changes whenever an item is selected or unselected, a
- selection area is set, cleared or otherwise changed, if a preselected item
- is added to the scene, or if a selected item is removed from the scene.
-
- QGraphicsScene emits this signal only once for group selection operations.
- For example, if you set a selection area, select or unselect a
- QGraphicsItemGroup, or if you add or remove from the scene a parent item
- that contains several selected items, selectionChanged() is emitted only
- once after the operation has completed (instead of once for each item).
-
- \sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
-*/
-
-/*!
- \since 4.4
-
- Returns the scene's style, or the same as QApplication::style() if the
- scene has not been explicitly assigned a style.
-
- \sa setStyle()
-*/
-QStyle *QGraphicsScene::style() const
-{
- Q_D(const QGraphicsScene);
- // ### This function, and the use of styles in general, is non-reentrant.
- return d->style ? d->style : QApplication::style();
-}
-
-/*!
- \since 4.4
-
- Sets or replaces the style of the scene to \a style, and reparents the
- style to this scene. Any previously assigned style is deleted. The scene's
- style defaults to QApplication::style(), and serves as the default for all
- QGraphicsWidget items in the scene.
-
- Changing the style, either directly by calling this function, or
- indirectly by calling QApplication::setStyle(), will automatically update
- the style for all widgets in the scene that do not have a style explicitly
- assigned to them.
-
- If \a style is 0, QGraphicsScene will revert to QApplication::style().
-
- \sa style()
-*/
-void QGraphicsScene::setStyle(QStyle *style)
-{
- Q_D(QGraphicsScene);
- // ### This function, and the use of styles in general, is non-reentrant.
- if (style == d->style)
- return;
-
- // Delete the old style,
- delete d->style;
- if ((d->style = style))
- d->style->setParent(this);
-
- // Notify the scene.
- QEvent event(QEvent::StyleChange);
- QApplication::sendEvent(this, &event);
-
- // Notify all widgets that don't have a style explicitly set.
- foreach (QGraphicsItem *item, items()) {
- if (item->isWidget()) {
- QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
- if (!widget->testAttribute(Qt::WA_SetStyle))
- QApplication::sendEvent(widget, &event);
- }
- }
-}
-
-/*!
- \property QGraphicsScene::font
- \since 4.4
- \brief the scene's default font
-
- This property provides the scene's font. The scene font defaults to,
- and resolves all its entries from, QApplication::font.
-
- If the scene's font changes, either directly through setFont() or
- indirectly when the application font changes, QGraphicsScene first
- sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
- sends \l{QEvent::FontChange}{FontChange} events to all top-level
- widget items in the scene. These items respond by resolving their own
- fonts to the scene, and they then notify their children, who again
- notify their children, and so on, until all widget items have updated
- their fonts.
-
- Changing the scene font, (directly or indirectly through
- QApplication::setFont(),) automatically schedules a redraw the entire
- scene.
-
- \sa QWidget::font, QApplication::setFont(), palette, style()
-*/
-QFont QGraphicsScene::font() const
-{
- Q_D(const QGraphicsScene);
- return d->font;
-}
-void QGraphicsScene::setFont(const QFont &font)
-{
- Q_D(QGraphicsScene);
- QFont naturalFont = QApplication::font();
- naturalFont.resolve(0);
- QFont resolvedFont = font.resolve(naturalFont);
- d->setFont_helper(resolvedFont);
-}
-
-/*!
- \property QGraphicsScene::palette
- \since 4.4
- \brief the scene's default palette
-
- This property provides the scene's palette. The scene palette defaults to,
- and resolves all its entries from, QApplication::palette.
-
- If the scene's palette changes, either directly through setPalette() or
- indirectly when the application palette changes, QGraphicsScene first
- sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
- sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
- widget items in the scene. These items respond by resolving their own
- palettes to the scene, and they then notify their children, who again
- notify their children, and so on, until all widget items have updated
- their palettes.
-
- Changing the scene palette, (directly or indirectly through
- QApplication::setPalette(),) automatically schedules a redraw the entire
- scene.
-
- \sa QWidget::palette, QApplication::setPalette(), font, style()
-*/
-QPalette QGraphicsScene::palette() const
-{
- Q_D(const QGraphicsScene);
- return d->palette;
-}
-void QGraphicsScene::setPalette(const QPalette &palette)
-{
- Q_D(QGraphicsScene);
- QPalette naturalPalette = QApplication::palette();
- naturalPalette.resolve(0);
- QPalette resolvedPalette = palette.resolve(naturalPalette);
- d->setPalette_helper(resolvedPalette);
-}
-
-/*!
- \since 4.6
-
- Returns true if the scene is active (e.g., it's viewed by
- at least one QGraphicsView that is active); otherwise returns false.
-
- \sa QGraphicsItem::isActive(), QWidget::isActiveWindow()
-*/
-bool QGraphicsScene::isActive() const
-{
- Q_D(const QGraphicsScene);
- return d->activationRefCount > 0;
-}
-
-/*!
- \since 4.6
- Returns the current active panel, or 0 if no panel is currently active.
-
- \sa QGraphicsScene::setActivePanel()
-*/
-QGraphicsItem *QGraphicsScene::activePanel() const
-{
- Q_D(const QGraphicsScene);
- return d->activePanel;
-}
-
-/*!
- \since 4.6
- Activates \a item, which must be an item in this scene. You
- can also pass 0 for \a item, in which case QGraphicsScene will
- deactivate any currently active panel.
-
- If the scene is currently inactive, \a item remains inactive until the
- scene becomes active (or, ir \a item is 0, no item will be activated).
-
- \sa activePanel(), isActive(), QGraphicsItem::isActive()
-*/
-void QGraphicsScene::setActivePanel(QGraphicsItem *item)
-{
- Q_D(QGraphicsScene);
- d->setActivePanelHelper(item, false);
-}
-
-/*!
- \since 4.4
-
- Returns the current active window, or 0 if no window is currently
- active.
-
- \sa QGraphicsScene::setActiveWindow()
-*/
-QGraphicsWidget *QGraphicsScene::activeWindow() const
-{
- Q_D(const QGraphicsScene);
- if (d->activePanel && d->activePanel->isWindow())
- return static_cast<QGraphicsWidget *>(d->activePanel);
- return 0;
-}
-
-/*!
- \since 4.4
- Activates \a widget, which must be a widget in this scene. You can also
- pass 0 for \a widget, in which case QGraphicsScene will deactivate any
- currently active window.
-
- \sa activeWindow(), QGraphicsWidget::isActiveWindow()
-*/
-void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
-{
- if (widget && widget->scene() != this) {
- qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
- widget);
- return;
- }
-
- // Activate the widget's panel (all windows are panels).
- QGraphicsItem *panel = widget ? widget->panel() : 0;
- setActivePanel(panel);
-
- // Raise
- if (panel) {
- QList<QGraphicsItem *> siblingWindows;
- QGraphicsItem *parent = panel->parentItem();
- // Raise ### inefficient for toplevels
- foreach (QGraphicsItem *sibling, parent ? parent->children() : items()) {
- if (sibling != panel && sibling->isWindow())
- siblingWindows << sibling;
- }
-
- // Find the highest z value.
- qreal z = panel->zValue();
- for (int i = 0; i < siblingWindows.size(); ++i)
- z = qMax(z, siblingWindows.at(i)->zValue());
-
- // This will probably never overflow.
- const qreal litt = qreal(0.001);
- panel->setZValue(z + litt);
- }
-}
-
-/*!
- \since 4.6
-
- Sends event \a event to item \a item through possible event filters.
-
- The event is sent only if the item is enabled.
-
- Returns \c false if the event was filtered or if the item is disabled.
- Otherwise returns the value that was returned from the event handler.
-
- \sa QGraphicsItem::sceneEvent(), QGraphicsItem::sceneEventFilter()
-*/
-bool QGraphicsScene::sendEvent(QGraphicsItem *item, QEvent *event)
-{
- Q_D(QGraphicsScene);
- if (!item) {
- qWarning("QGraphicsScene::sendEvent: cannot send event to a null item");
- return false;
- }
- if (item->scene() != this) {
- qWarning("QGraphicsScene::sendEvent: item %p's scene (%p)"
- " is different from this scene (%p)",
- item, item->scene(), this);
- return false;
- }
- return d->sendEvent(item, event);
-}
-
-void QGraphicsScenePrivate::addView(QGraphicsView *view)
-{
- views << view;
-#ifndef QT_NO_GESTURES
- foreach (Qt::GestureType gesture, grabbedGestures.keys())
- view->viewport()->grabGesture(gesture);
-#endif
-}
-
-void QGraphicsScenePrivate::removeView(QGraphicsView *view)
-{
- views.removeAll(view);
-}
-
-void QGraphicsScenePrivate::updateTouchPointsForItem(QGraphicsItem *item, QTouchEvent *touchEvent)
-{
- QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
- for (int i = 0; i < touchPoints.count(); ++i) {
- QTouchEvent::TouchPoint &touchPoint = touchPoints[i];
- touchPoint.setRect(item->mapFromScene(touchPoint.sceneRect()).boundingRect());
- touchPoint.setStartPos(item->d_ptr->genericMapFromScene(touchPoint.startScenePos(), touchEvent->widget()));
- touchPoint.setLastPos(item->d_ptr->genericMapFromScene(touchPoint.lastScenePos(), touchEvent->widget()));
- }
- touchEvent->setTouchPoints(touchPoints);
-}
-
-int QGraphicsScenePrivate::findClosestTouchPointId(const QPointF &scenePos)
-{
- int closestTouchPointId = -1;
- qreal closestDistance = qreal(0.);
- foreach (const QTouchEvent::TouchPoint &touchPoint, sceneCurrentTouchPoints) {
- qreal distance = QLineF(scenePos, touchPoint.scenePos()).length();
- if (closestTouchPointId == -1|| distance < closestDistance) {
- closestTouchPointId = touchPoint.id();
- closestDistance = distance;
- }
- }
- return closestTouchPointId;
-}
-
-void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
-{
- typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
- QHash<QGraphicsItem *, StatesAndTouchPoints> itemsNeedingEvents;
-
- for (int i = 0; i < sceneTouchEvent->touchPoints().count(); ++i) {
- const QTouchEvent::TouchPoint &touchPoint = sceneTouchEvent->touchPoints().at(i);
-
- // update state
- QGraphicsItem *item = 0;
- if (touchPoint.state() == Qt::TouchPointPressed) {
- if (sceneTouchEvent->deviceType() == QTouchEvent::TouchPad) {
- // on touch-pad devices, send all touch points to the same item
- item = itemForTouchPointId.isEmpty()
- ? 0
- : itemForTouchPointId.constBegin().value();
- }
-
- if (!item) {
- // determine which item this touch point will go to
- cachedItemsUnderMouse = itemsAtPosition(touchPoint.screenPos().toPoint(),
- touchPoint.scenePos(),
- sceneTouchEvent->widget());
- item = cachedItemsUnderMouse.isEmpty() ? 0 : cachedItemsUnderMouse.first();
- }
-
- if (sceneTouchEvent->deviceType() == QTouchEvent::TouchScreen) {
- // on touch-screens, combine this touch point with the closest one we find
- int closestTouchPointId = findClosestTouchPointId(touchPoint.scenePos());
- QGraphicsItem *closestItem = itemForTouchPointId.value(closestTouchPointId);
- if (!item || (closestItem && cachedItemsUnderMouse.contains(closestItem)))
- item = closestItem;
- }
- if (!item)
- continue;
-
- itemForTouchPointId.insert(touchPoint.id(), item);
- sceneCurrentTouchPoints.insert(touchPoint.id(), touchPoint);
- } else if (touchPoint.state() == Qt::TouchPointReleased) {
- item = itemForTouchPointId.take(touchPoint.id());
- if (!item)
- continue;
-
- sceneCurrentTouchPoints.remove(touchPoint.id());
- } else {
- item = itemForTouchPointId.value(touchPoint.id());
- if (!item)
- continue;
- Q_ASSERT(sceneCurrentTouchPoints.contains(touchPoint.id()));
- sceneCurrentTouchPoints[touchPoint.id()] = touchPoint;
- }
-
- StatesAndTouchPoints &statesAndTouchPoints = itemsNeedingEvents[item];
- statesAndTouchPoints.first |= touchPoint.state();
- statesAndTouchPoints.second.append(touchPoint);
- }
-
- if (itemsNeedingEvents.isEmpty()) {
- sceneTouchEvent->accept();
- return;
- }
-
- bool ignoreSceneTouchEvent = true;
- QHash<QGraphicsItem *, StatesAndTouchPoints>::ConstIterator it = itemsNeedingEvents.constBegin();
- const QHash<QGraphicsItem *, StatesAndTouchPoints>::ConstIterator end = itemsNeedingEvents.constEnd();
- for (; it != end; ++it) {
- QGraphicsItem *item = it.key();
-
- (void) item->isBlockedByModalPanel(&item);
-
- // determine event type from the state mask
- QEvent::Type eventType;
- switch (it.value().first) {
- case Qt::TouchPointPressed:
- // all touch points have pressed state
- eventType = QEvent::TouchBegin;
- break;
- case Qt::TouchPointReleased:
- // all touch points have released state
- eventType = QEvent::TouchEnd;
- break;
- case Qt::TouchPointStationary:
- // don't send the event if nothing changed
- continue;
- default:
- // all other combinations
- eventType = QEvent::TouchUpdate;
- break;
- }
-
- QTouchEvent touchEvent(eventType);
- touchEvent.setWidget(sceneTouchEvent->widget());
- touchEvent.setDeviceType(sceneTouchEvent->deviceType());
- touchEvent.setModifiers(sceneTouchEvent->modifiers());
- touchEvent.setTouchPointStates(it.value().first);
- touchEvent.setTouchPoints(it.value().second);
-
- 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
- item->d_ptr->acceptedTouchBeginEvent = true;
- bool res = sendTouchBeginEvent(item, &touchEvent)
- && touchEvent.isAccepted();
- if (!res) {
- // forget about these touch points, we didn't handle them
- for (int i = 0; i < touchEvent.touchPoints().count(); ++i) {
- const QTouchEvent::TouchPoint &touchPoint = touchEvent.touchPoints().at(i);
- itemForTouchPointId.remove(touchPoint.id());
- sceneCurrentTouchPoints.remove(touchPoint.id());
- }
- ignoreSceneTouchEvent = false;
- }
- break;
- }
- default:
- if (item->d_ptr->acceptedTouchBeginEvent) {
- updateTouchPointsForItem(item, &touchEvent);
- (void) sendEvent(item, &touchEvent);
- ignoreSceneTouchEvent = false;
- }
- break;
- }
- }
- sceneTouchEvent->setAccepted(ignoreSceneTouchEvent);
-}
-
-bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEvent *touchEvent)
-{
- Q_Q(QGraphicsScene);
-
- if (cachedItemsUnderMouse.isEmpty() || cachedItemsUnderMouse.first() != origin) {
- const QTouchEvent::TouchPoint &firstTouchPoint = touchEvent->touchPoints().first();
- cachedItemsUnderMouse = itemsAtPosition(firstTouchPoint.screenPos().toPoint(),
- firstTouchPoint.scenePos(),
- touchEvent->widget());
- }
- Q_ASSERT(cachedItemsUnderMouse.first() == origin);
-
- // Set focus on the topmost enabled item that can take focus.
- bool setFocus = false;
-
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
- if (item->isEnabled() && ((item->flags() & QGraphicsItem::ItemIsFocusable) && item->d_ptr->mouseSetsFocus)) {
- if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
- setFocus = true;
- if (item != q->focusItem())
- q->setFocusItem(item, Qt::MouseFocusReason);
- break;
- }
- }
- if (item->isPanel())
- break;
- if (item->d_ptr->flags & QGraphicsItem::ItemStopsClickFocusPropagation)
- break;
- if (item->d_ptr->flags & QGraphicsItem::ItemStopsFocusHandling) {
- // Make sure we don't clear focus.
- setFocus = true;
- break;
- }
- }
-
- // If nobody could take focus, clear it.
- if (!stickyFocus && !setFocus)
- q->setFocusItem(0, Qt::MouseFocusReason);
-
- bool res = false;
- bool eventAccepted = touchEvent->isAccepted();
- foreach (QGraphicsItem *item, cachedItemsUnderMouse) {
- // first, try to deliver the touch event
- updateTouchPointsForItem(item, touchEvent);
- bool acceptTouchEvents = item->acceptTouchEvents();
- touchEvent->setAccepted(acceptTouchEvents);
- res = acceptTouchEvents && sendEvent(item, touchEvent);
- eventAccepted = touchEvent->isAccepted();
- if (itemForTouchPointId.value(touchEvent->touchPoints().first().id()) == 0) {
- // item was deleted
- item = 0;
- } else {
- item->d_ptr->acceptedTouchBeginEvent = (res && eventAccepted);
- }
- touchEvent->spont = false;
- if (res && eventAccepted) {
- // the first item 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);
- itemForTouchPointId[touchPoint.id()] = item; // can be zero
- }
- break;
- }
- if (item && item->isPanel())
- break;
- }
-
- touchEvent->setAccepted(eventAccepted);
- return res;
-}
-
-void QGraphicsScenePrivate::enableTouchEventsOnViews()
-{
- foreach (QGraphicsView *view, views)
- view->viewport()->setAttribute(Qt::WA_AcceptTouchEvents, true);
-}
-
-void QGraphicsScenePrivate::updateInputMethodSensitivityInViews()
-{
- for (int i = 0; i < views.size(); ++i)
- views.at(i)->d_func()->updateInputMethodSensitivity();
-}
-
-void QGraphicsScenePrivate::enterModal(QGraphicsItem *panel, QGraphicsItem::PanelModality previousModality)
-{
- Q_Q(QGraphicsScene);
- Q_ASSERT(panel && panel->isPanel());
-
- QGraphicsItem::PanelModality panelModality = panel->d_ptr->panelModality;
- if (previousModality != QGraphicsItem::NonModal) {
- // the panel is changing from one modality type to another... temporarily set it back so
- // that blockedPanels is populated correctly
- panel->d_ptr->panelModality = previousModality;
- }
-
- QSet<QGraphicsItem *> blockedPanels;
- QList<QGraphicsItem *> items = q->items(); // ### store panels separately
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel() && item->isBlockedByModalPanel())
- blockedPanels.insert(item);
- }
- // blockedPanels contains all currently blocked panels
-
- if (previousModality != QGraphicsItem::NonModal) {
- // reset the modality to the proper value, since we changed it above
- panel->d_ptr->panelModality = panelModality;
- // remove this panel so that it will be reinserted at the front of the stack
- modalPanels.removeAll(panel);
- }
-
- modalPanels.prepend(panel);
-
- if (!hoverItems.isEmpty()) {
- // send GraphicsSceneHoverLeave events to newly blocked hoverItems
- QGraphicsSceneHoverEvent hoverEvent;
- hoverEvent.setScenePos(lastSceneMousePos);
- dispatchHoverEvent(&hoverEvent);
- }
-
- if (!mouseGrabberItems.isEmpty() && lastMouseGrabberItemHasImplicitMouseGrab) {
- QGraphicsItem *item = mouseGrabberItems.last();
- if (item->isBlockedByModalPanel())
- ungrabMouse(item, /*itemIsDying =*/ false);
- }
-
- QEvent windowBlockedEvent(QEvent::WindowBlocked);
- QEvent windowUnblockedEvent(QEvent::WindowUnblocked);
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel()) {
- if (!blockedPanels.contains(item) && item->isBlockedByModalPanel()) {
- // send QEvent::WindowBlocked to newly blocked panels
- sendEvent(item, &windowBlockedEvent);
- } else if (blockedPanels.contains(item) && !item->isBlockedByModalPanel()) {
- // send QEvent::WindowUnblocked to unblocked panels when downgrading
- // a panel from SceneModal to PanelModal
- sendEvent(item, &windowUnblockedEvent);
- }
- }
- }
-}
-
-void QGraphicsScenePrivate::leaveModal(QGraphicsItem *panel)
-{
- Q_Q(QGraphicsScene);
- Q_ASSERT(panel && panel->isPanel());
-
- QSet<QGraphicsItem *> blockedPanels;
- QList<QGraphicsItem *> items = q->items(); // ### same as above
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel() && item->isBlockedByModalPanel())
- blockedPanels.insert(item);
- }
-
- modalPanels.removeAll(panel);
-
- QEvent e(QEvent::WindowUnblocked);
- for (int i = 0; i < items.count(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item->isPanel() && blockedPanels.contains(item) && !item->isBlockedByModalPanel())
- sendEvent(item, &e);
- }
-
- // send GraphicsSceneHoverEnter events to newly unblocked items
- QGraphicsSceneHoverEvent hoverEvent;
- hoverEvent.setScenePos(lastSceneMousePos);
- dispatchHoverEvent(&hoverEvent);
-}
-
-#ifndef QT_NO_GESTURES
-void QGraphicsScenePrivate::gestureTargetsAtHotSpots(const QSet<QGesture *> &gestures,
- Qt::GestureFlag flag,
- QHash<QGraphicsObject *, QSet<QGesture *> > *targets,
- QSet<QGraphicsObject *> *itemsSet,
- QSet<QGesture *> *normal,
- QSet<QGesture *> *conflicts)
-{
- QSet<QGesture *> normalGestures; // that are not in conflicted state.
- foreach (QGesture *gesture, gestures) {
- if (!gesture->hasHotSpot())
- continue;
- const Qt::GestureType gestureType = gesture->gestureType();
- QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), gesture->d_func()->sceneHotSpot, 0);
- for (int j = 0; j < items.size(); ++j) {
- QGraphicsItem *item = items.at(j);
-
- // Check if the item is blocked by a modal panel and use it as
- // a target instead of this item.
- (void) item->isBlockedByModalPanel(&item);
-
- if (QGraphicsObject *itemobj = item->toGraphicsObject()) {
- QGraphicsItemPrivate *d = item->QGraphicsItem::d_func();
- QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator it =
- d->gestureContext.find(gestureType);
- if (it != d->gestureContext.end() && (!flag || (it.value() & flag))) {
- if (normalGestures.contains(gesture)) {
- normalGestures.remove(gesture);
- if (conflicts)
- conflicts->insert(gesture);
- } else {
- normalGestures.insert(gesture);
- }
- if (targets)
- (*targets)[itemobj].insert(gesture);
- if (itemsSet)
- (*itemsSet).insert(itemobj);
- }
- }
- // Don't propagate through panels.
- if (item->isPanel())
- break;
- }
- }
- if (normal)
- *normal = normalGestures;
-}
-
-void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
-{
- QWidget *viewport = event->widget();
- if (!viewport)
- return;
- QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(viewport->parent());
- if (!graphicsView)
- return;
-
- QList<QGesture *> allGestures = event->gestures();
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "Gestures:" << allGestures;
-
- QSet<QGesture *> startedGestures;
- QPoint delta = viewport->mapFromGlobal(QPoint());
- QTransform toScene = QTransform::fromTranslate(delta.x(), delta.y())
- * graphicsView->viewportTransform().inverted();
- foreach (QGesture *gesture, allGestures) {
- // cache scene coordinates of the hot spot
- if (gesture->hasHotSpot()) {
- gesture->d_func()->sceneHotSpot = toScene.map(gesture->hotSpot());
- } else {
- gesture->d_func()->sceneHotSpot = QPointF();
- }
-
- QGraphicsObject *target = gestureTargets.value(gesture, 0);
- if (!target) {
- // when we are not in started mode but don't have a target
- // then the only one interested in gesture is the view/scene
- if (gesture->state() == Qt::GestureStarted)
- startedGestures.insert(gesture);
- }
- }
-
- if (!startedGestures.isEmpty()) {
- QSet<QGesture *> normalGestures; // that have just one target
- QSet<QGesture *> conflictedGestures; // that have multiple possible targets
- gestureTargetsAtHotSpots(startedGestures, Qt::GestureFlag(0), &cachedItemGestures, 0,
- &normalGestures, &conflictedGestures);
- cachedTargetItems = cachedItemGestures.keys();
- qSort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "Normal gestures:" << normalGestures
- << "Conflicting gestures:" << conflictedGestures;
-
- // deliver conflicted gestures as override events AND remember
- // initial gesture targets
- if (!conflictedGestures.isEmpty()) {
- for (int i = 0; i < cachedTargetItems.size(); ++i) {
- QWeakPointer<QGraphicsObject> item = cachedTargetItems.at(i);
-
- // get gestures to deliver to the current item
- QSet<QGesture *> gestures = conflictedGestures & cachedItemGestures.value(item.data());
- if (gestures.isEmpty())
- continue;
-
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "delivering override to"
- << item.data() << gestures;
- // send gesture override
- QGestureEvent ev(gestures.toList());
- ev.t = QEvent::GestureOverride;
- ev.setWidget(event->widget());
- // mark event and individual gestures as ignored
- ev.ignore();
- foreach(QGesture *g, gestures)
- ev.setAccepted(g, false);
- sendEvent(item.data(), &ev);
- // mark all accepted gestures to deliver them as normal gesture events
- foreach (QGesture *g, gestures) {
- if (ev.isAccepted() || ev.isAccepted(g)) {
- conflictedGestures.remove(g);
- // mark the item as a gesture target
- if (item) {
- gestureTargets.insert(g, item.data());
- QHash<QGraphicsObject *, QSet<QGesture *> >::iterator it, e;
- it = cachedItemGestures.begin();
- e = cachedItemGestures.end();
- for(; it != e; ++it)
- it.value().remove(g);
- cachedItemGestures[item.data()].insert(g);
- }
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "override was accepted:"
- << g << item.data();
- }
- // remember the first item that received the override event
- // as it most likely become a target if no one else accepts
- // the override event
- if (!gestureTargets.contains(g) && item)
- gestureTargets.insert(g, item.data());
-
- }
- if (conflictedGestures.isEmpty())
- break;
- }
- }
- // remember the initial target item for each gesture that was not in
- // the conflicted state.
- if (!normalGestures.isEmpty()) {
- for (int i = 0; i < cachedTargetItems.size() && !normalGestures.isEmpty(); ++i) {
- QGraphicsObject *item = cachedTargetItems.at(i);
-
- // get gestures to deliver to the current item
- foreach (QGesture *g, cachedItemGestures.value(item)) {
- if (!gestureTargets.contains(g)) {
- gestureTargets.insert(g, item);
- normalGestures.remove(g);
- }
- }
- }
- }
- }
-
-
- // deliver all gesture events
- QSet<QGesture *> undeliveredGestures;
- QSet<QGesture *> parentPropagatedGestures;
- foreach (QGesture *gesture, allGestures) {
- if (QGraphicsObject *target = gestureTargets.value(gesture, 0)) {
- cachedItemGestures[target].insert(gesture);
- cachedTargetItems.append(target);
- undeliveredGestures.insert(gesture);
- QGraphicsItemPrivate *d = target->QGraphicsItem::d_func();
- const Qt::GestureFlags flags = d->gestureContext.value(gesture->gestureType());
- if (flags & Qt::IgnoredGesturesPropagateToParent)
- parentPropagatedGestures.insert(gesture);
- } else {
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "no target for" << gesture << "at"
- << gesture->hotSpot() << gesture->d_func()->sceneHotSpot;
- }
- }
- qSort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
- for (int i = 0; i < cachedTargetItems.size(); ++i) {
- QWeakPointer<QGraphicsObject> receiver = cachedTargetItems.at(i);
- QSet<QGesture *> gestures =
- undeliveredGestures & cachedItemGestures.value(receiver.data());
- gestures -= cachedAlreadyDeliveredGestures.value(receiver.data());
-
- if (gestures.isEmpty())
- continue;
-
- cachedAlreadyDeliveredGestures[receiver.data()] += gestures;
- const bool isPanel = receiver.data()->isPanel();
-
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "delivering to"
- << receiver.data() << gestures;
- QGestureEvent ev(gestures.toList());
- ev.setWidget(event->widget());
- sendEvent(receiver.data(), &ev);
- QSet<QGesture *> ignoredGestures;
- foreach (QGesture *g, gestures) {
- if (!ev.isAccepted() && !ev.isAccepted(g)) {
- // if the gesture was ignored by its target, we will update the
- // targetItems list with a possible target items (items that
- // want to receive partial gestures).
- // ### wont' work if the target was destroyed in the event
- // we will just stop delivering it.
- if (receiver && receiver.data() == gestureTargets.value(g, 0))
- ignoredGestures.insert(g);
- } else {
- if (receiver && g->state() == Qt::GestureStarted) {
- // someone accepted the propagated initial GestureStarted
- // event, let it be the new target for all following events.
- gestureTargets[g] = receiver.data();
- }
- undeliveredGestures.remove(g);
- }
- }
- if (undeliveredGestures.isEmpty())
- break;
-
- // ignoredGestures list is only filled when delivering to the gesture
- // target item, so it is safe to assume item == target.
- if (!ignoredGestures.isEmpty() && !isPanel) {
- // look for new potential targets for gestures that were ignored
- // and should be propagated.
-
- QSet<QGraphicsObject *> targetsSet = cachedTargetItems.toSet();
-
- if (receiver) {
- // first if the gesture should be propagated to parents only
- for (QSet<QGesture *>::iterator it = ignoredGestures.begin();
- it != ignoredGestures.end();) {
- if (parentPropagatedGestures.contains(*it)) {
- QGesture *gesture = *it;
- const Qt::GestureType gestureType = gesture->gestureType();
- QGraphicsItem *item = receiver.data();
- while (item) {
- if (QGraphicsObject *obj = item->toGraphicsObject()) {
- if (item->d_func()->gestureContext.contains(gestureType)) {
- targetsSet.insert(obj);
- cachedItemGestures[obj].insert(gesture);
- }
- }
- if (item->isPanel())
- break;
- item = item->parentItem();
- }
-
- it = ignoredGestures.erase(it);
- continue;
- }
- ++it;
- }
- }
-
- gestureTargetsAtHotSpots(ignoredGestures, Qt::ReceivePartialGestures,
- &cachedItemGestures, &targetsSet, 0, 0);
-
- cachedTargetItems = targetsSet.toList();
- qSort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
- DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
- << "new targets:" << cachedTargetItems;
- i = -1; // start delivery again
- continue;
- }
- }
-
- foreach (QGesture *g, startedGestures) {
- if (g->gestureCancelPolicy() == QGesture::CancelAllInContext) {
- DEBUG() << "lets try to cancel some";
- // find gestures in context in Qt::GestureStarted or Qt::GestureUpdated state and cancel them
- cancelGesturesForChildren(g);
- }
- }
-
- // forget about targets for gestures that have ended
- foreach (QGesture *g, allGestures) {
- switch (g->state()) {
- case Qt::GestureFinished:
- case Qt::GestureCanceled:
- gestureTargets.remove(g);
- break;
- default:
- break;
- }
- }
-
- cachedTargetItems.clear();
- cachedItemGestures.clear();
- cachedAlreadyDeliveredGestures.clear();
-}
-
-void QGraphicsScenePrivate::cancelGesturesForChildren(QGesture *original)
-{
- Q_ASSERT(original);
- QGraphicsItem *originalItem = gestureTargets.value(original);
- if (originalItem == 0) // we only act on accepted gestures, which implies it has a target.
- return;
-
- // iterate over all active gestures and for each find the owner
- // if the owner is part of our sub-hierarchy, cancel it.
-
- QSet<QGesture *> canceledGestures;
- QHash<QGesture *, QGraphicsObject *>::Iterator iter = gestureTargets.begin();
- while (iter != gestureTargets.end()) {
- QGraphicsObject *item = iter.value();
- // note that we don't touch the gestures for our originalItem
- if (item != originalItem && originalItem->isAncestorOf(item)) {
- DEBUG() << " found a gesture to cancel" << iter.key();
- iter.key()->d_func()->state = Qt::GestureCanceled;
- canceledGestures << iter.key();
- }
- ++iter;
- }
-
- // sort them per target item by cherry picking from almostCanceledGestures and delivering
- QSet<QGesture *> almostCanceledGestures = canceledGestures;
- QSet<QGesture *>::Iterator setIter;
- while (!almostCanceledGestures.isEmpty()) {
- QGraphicsObject *target = 0;
- QSet<QGesture*> gestures;
- setIter = almostCanceledGestures.begin();
- // sort per target item
- while (setIter != almostCanceledGestures.end()) {
- QGraphicsObject *item = gestureTargets.value(*setIter);
- if (target == 0)
- target = item;
- if (target == item) {
- gestures << *setIter;
- setIter = almostCanceledGestures.erase(setIter);
- } else {
- ++setIter;
- }
- }
- Q_ASSERT(target);
-
- QList<QGesture *> list = gestures.toList();
- QGestureEvent ev(list);
- sendEvent(target, &ev);
-
- foreach (QGesture *g, list) {
- if (ev.isAccepted() || ev.isAccepted(g))
- gestures.remove(g);
- }
-
- foreach (QGesture *g, gestures) {
- if (!g->hasHotSpot())
- continue;
-
- QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), g->d_func()->sceneHotSpot, 0);
- for (int j = 0; j < items.size(); ++j) {
- QGraphicsObject *item = items.at(j)->toGraphicsObject();
- if (!item)
- continue;
- QGraphicsItemPrivate *d = item->QGraphicsItem::d_func();
- if (d->gestureContext.contains(g->gestureType())) {
- QList<QGesture *> list;
- list << g;
- QGestureEvent ev(list);
- sendEvent(item, &ev);
- if (ev.isAccepted() || ev.isAccepted(g))
- break; // successfully delivered
- }
- }
- }
- }
-
- QGestureManager *gestureManager = QApplicationPrivate::instance()->gestureManager;
- Q_ASSERT(gestureManager); // it would be very odd if we got called without a manager.
- for (setIter = canceledGestures.begin(); setIter != canceledGestures.end(); ++setIter) {
- gestureManager->recycle(*setIter);
- gestureTargets.remove(*setIter);
- }
-}
-
-void QGraphicsScenePrivate::grabGesture(QGraphicsItem *, Qt::GestureType gesture)
-{
- (void)QGestureManager::instance(); // create a gesture manager
- if (!grabbedGestures[gesture]++) {
- foreach (QGraphicsView *view, views)
- view->viewport()->grabGesture(gesture);
- }
-}
-
-void QGraphicsScenePrivate::ungrabGesture(QGraphicsItem *item, Qt::GestureType gesture)
-{
- // we know this can only be an object
- Q_ASSERT(item->d_ptr->isObject);
- QGraphicsObject *obj = static_cast<QGraphicsObject *>(item);
- QGestureManager::instance()->cleanupCachedGestures(obj, gesture);
- if (!--grabbedGestures[gesture]) {
- foreach (QGraphicsView *view, views)
- view->viewport()->ungrabGesture(gesture);
- }
-}
-#endif // QT_NO_GESTURES
-
-QT_END_NAMESPACE
-
-#include "moc_qgraphicsscene.cpp"
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsscene.h b/src/gui/graphicsview/qgraphicsscene.h
deleted file mode 100644
index c17ab96074..0000000000
--- a/src/gui/graphicsview/qgraphicsscene.h
+++ /dev/null
@@ -1,329 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSSCENE_H
-#define QGRAPHICSSCENE_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qrect.h>
-#include <QtGui/qbrush.h>
-#include <QtGui/qfont.h>
-#include <QtGui/qtransform.h>
-#include <QtGui/qmatrix.h>
-#include <QtGui/qpen.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-template<typename T> class QList;
-class QFocusEvent;
-class QFont;
-class QFontMetrics;
-class QGraphicsEllipseItem;
-class QGraphicsItem;
-class QGraphicsItemGroup;
-class QGraphicsLineItem;
-class QGraphicsPathItem;
-class QGraphicsPixmapItem;
-class QGraphicsPolygonItem;
-class QGraphicsProxyWidget;
-class QGraphicsRectItem;
-class QGraphicsSceneContextMenuEvent;
-class QGraphicsSceneDragDropEvent;
-class QGraphicsSceneEvent;
-class QGraphicsSceneHelpEvent;
-class QGraphicsSceneHoverEvent;
-class QGraphicsSceneMouseEvent;
-class QGraphicsSceneWheelEvent;
-class QGraphicsSimpleTextItem;
-class QGraphicsTextItem;
-class QGraphicsView;
-class QGraphicsWidget;
-class QGraphicsSceneIndex;
-class QHelpEvent;
-class QInputMethodEvent;
-class QKeyEvent;
-class QLineF;
-class QPainterPath;
-class QPixmap;
-class QPointF;
-class QPolygonF;
-class QRectF;
-class QSizeF;
-class QStyle;
-class QStyleOptionGraphicsItem;
-
-class QGraphicsScenePrivate;
-class Q_GUI_EXPORT QGraphicsScene : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QBrush backgroundBrush READ backgroundBrush WRITE setBackgroundBrush)
- Q_PROPERTY(QBrush foregroundBrush READ foregroundBrush WRITE setForegroundBrush)
- Q_PROPERTY(ItemIndexMethod itemIndexMethod READ itemIndexMethod WRITE setItemIndexMethod)
- Q_PROPERTY(QRectF sceneRect READ sceneRect WRITE setSceneRect)
- Q_PROPERTY(int bspTreeDepth READ bspTreeDepth WRITE setBspTreeDepth)
- Q_PROPERTY(QPalette palette READ palette WRITE setPalette)
- Q_PROPERTY(QFont font READ font WRITE setFont)
- Q_PROPERTY(bool sortCacheEnabled READ isSortCacheEnabled WRITE setSortCacheEnabled)
- Q_PROPERTY(bool stickyFocus READ stickyFocus WRITE setStickyFocus)
-
-public:
- enum ItemIndexMethod {
- BspTreeIndex,
- NoIndex = -1
- };
-
- enum SceneLayer {
- ItemLayer = 0x1,
- BackgroundLayer = 0x2,
- ForegroundLayer = 0x4,
- AllLayers = 0xffff
- };
- Q_DECLARE_FLAGS(SceneLayers, SceneLayer)
-
- QGraphicsScene(QObject *parent = 0);
- QGraphicsScene(const QRectF &sceneRect, QObject *parent = 0);
- QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent = 0);
- virtual ~QGraphicsScene();
-
- QRectF sceneRect() const;
- inline qreal width() const { return sceneRect().width(); }
- inline qreal height() const { return sceneRect().height(); }
- void setSceneRect(const QRectF &rect);
- inline void setSceneRect(qreal x, qreal y, qreal w, qreal h)
- { setSceneRect(QRectF(x, y, w, h)); }
-
- void render(QPainter *painter,
- const QRectF &target = QRectF(), const QRectF &source = QRectF(),
- Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio);
-
- ItemIndexMethod itemIndexMethod() const;
- void setItemIndexMethod(ItemIndexMethod method);
-
- bool isSortCacheEnabled() const;
- void setSortCacheEnabled(bool enabled);
-
- int bspTreeDepth() const;
- void setBspTreeDepth(int depth);
-
- QRectF itemsBoundingRect() const;
-
- QList<QGraphicsItem *> items() const;
- QList<QGraphicsItem *> items(Qt::SortOrder order) const; // ### Qt 5: unify
-
- QList<QGraphicsItem *> items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- QList<QGraphicsItem *> items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- QList<QGraphicsItem *> items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
-
- QList<QGraphicsItem *> items(const QPointF &pos) const; // ### obsolete
- QList<QGraphicsItem *> items(const QRectF &rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; // ### obsolete
- QList<QGraphicsItem *> items(const QPolygonF &polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; // ### obsolete
- QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const; // ### obsolete
-
- QList<QGraphicsItem *> collidingItems(const QGraphicsItem *item, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
-
- QGraphicsItem *itemAt(const QPointF &pos) const; // ### obsolete
- QGraphicsItem *itemAt(const QPointF &pos, const QTransform &deviceTransform) const;
-
- inline QList<QGraphicsItem *> items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
- { return items(QRectF(x, y, w, h), mode); } // ### obsolete
- inline QList<QGraphicsItem *> items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode, Qt::SortOrder order,
- const QTransform &deviceTransform = QTransform()) const
- { return items(QRectF(x, y, w, h), mode, order, deviceTransform); }
- inline QGraphicsItem *itemAt(qreal x, qreal y) const // ### obsolete
- { return itemAt(QPointF(x, y)); }
- inline QGraphicsItem *itemAt(qreal x, qreal y, const QTransform &deviceTransform) const
- { return itemAt(QPointF(x, y), deviceTransform); }
-
- QList<QGraphicsItem *> selectedItems() const;
- QPainterPath selectionArea() const;
- void setSelectionArea(const QPainterPath &path); // ### obsolete
- void setSelectionArea(const QPainterPath &path, const QTransform &deviceTransform);
- void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode); // ### obsolete
- void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode, const QTransform &deviceTransform);
-
- QGraphicsItemGroup *createItemGroup(const QList<QGraphicsItem *> &items);
- void destroyItemGroup(QGraphicsItemGroup *group);
-
- void addItem(QGraphicsItem *item);
- QGraphicsEllipseItem *addEllipse(const QRectF &rect, const QPen &pen = QPen(), const QBrush &brush = QBrush());
- QGraphicsLineItem *addLine(const QLineF &line, const QPen &pen = QPen());
- QGraphicsPathItem *addPath(const QPainterPath &path, const QPen &pen = QPen(), const QBrush &brush = QBrush());
- QGraphicsPixmapItem *addPixmap(const QPixmap &pixmap);
- QGraphicsPolygonItem *addPolygon(const QPolygonF &polygon, const QPen &pen = QPen(), const QBrush &brush = QBrush());
- QGraphicsRectItem *addRect(const QRectF &rect, const QPen &pen = QPen(), const QBrush &brush = QBrush());
- QGraphicsTextItem *addText(const QString &text, const QFont &font = QFont());
- QGraphicsSimpleTextItem *addSimpleText(const QString &text, const QFont &font = QFont());
- QGraphicsProxyWidget *addWidget(QWidget *widget, Qt::WindowFlags wFlags = 0);
- inline QGraphicsEllipseItem *addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen = QPen(), const QBrush &brush = QBrush())
- { return addEllipse(QRectF(x, y, w, h), pen, brush); }
- inline QGraphicsLineItem *addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen = QPen())
- { return addLine(QLineF(x1, y1, x2, y2), pen); }
- inline QGraphicsRectItem *addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen = QPen(), const QBrush &brush = QBrush())
- { return addRect(QRectF(x, y, w, h), pen, brush); }
- void removeItem(QGraphicsItem *item);
-
- QGraphicsItem *focusItem() const;
- void setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason = Qt::OtherFocusReason);
- bool hasFocus() const;
- void setFocus(Qt::FocusReason focusReason = Qt::OtherFocusReason);
- void clearFocus();
-
- void setStickyFocus(bool enabled);
- bool stickyFocus() const;
-
- QGraphicsItem *mouseGrabberItem() const;
-
- QBrush backgroundBrush() const;
- void setBackgroundBrush(const QBrush &brush);
-
- QBrush foregroundBrush() const;
- void setForegroundBrush(const QBrush &brush);
-
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
- QList <QGraphicsView *> views() const;
-
- inline void update(qreal x, qreal y, qreal w, qreal h)
- { update(QRectF(x, y, w, h)); }
- inline void invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers = AllLayers)
- { invalidate(QRectF(x, y, w, h), layers); }
-
- QStyle *style() const;
- void setStyle(QStyle *style);
-
- QFont font() const;
- void setFont(const QFont &font);
-
- QPalette palette() const;
- void setPalette(const QPalette &palette);
-
- bool isActive() const;
- QGraphicsItem *activePanel() const;
- void setActivePanel(QGraphicsItem *item);
- QGraphicsWidget *activeWindow() const;
- void setActiveWindow(QGraphicsWidget *widget);
-
- bool sendEvent(QGraphicsItem *item, QEvent *event);
-
-public Q_SLOTS:
- void update(const QRectF &rect = QRectF());
- void invalidate(const QRectF &rect = QRectF(), SceneLayers layers = AllLayers);
- void advance();
- void clearSelection();
- void clear();
-
-protected:
- bool event(QEvent *event);
- bool eventFilter(QObject *watched, QEvent *event);
- virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
- virtual void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
- virtual void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
- virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
- virtual void dropEvent(QGraphicsSceneDragDropEvent *event);
- virtual void focusInEvent(QFocusEvent *event);
- virtual void focusOutEvent(QFocusEvent *event);
- virtual void helpEvent(QGraphicsSceneHelpEvent *event);
- virtual void keyPressEvent(QKeyEvent *event);
- virtual void keyReleaseEvent(QKeyEvent *event);
- virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
- virtual void wheelEvent(QGraphicsSceneWheelEvent *event);
- virtual void inputMethodEvent(QInputMethodEvent *event);
-
- virtual void drawBackground(QPainter *painter, const QRectF &rect);
- virtual void drawForeground(QPainter *painter, const QRectF &rect);
- virtual void drawItems(QPainter *painter, int numItems,
- QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[],
- QWidget *widget = 0);
-
-protected Q_SLOTS:
- bool focusNextPrevChild(bool next);
-
-Q_SIGNALS:
- void changed(const QList<QRectF> &region);
- void sceneRectChanged(const QRectF &rect);
- void selectionChanged();
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsScene)
- Q_DISABLE_COPY(QGraphicsScene)
- Q_PRIVATE_SLOT(d_func(), void _q_emitUpdated())
- Q_PRIVATE_SLOT(d_func(), void _q_polishItems())
- Q_PRIVATE_SLOT(d_func(), void _q_processDirtyItems())
- Q_PRIVATE_SLOT(d_func(), void _q_updateScenePosDescendants())
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
- friend class QGraphicsObject;
- friend class QGraphicsView;
- friend class QGraphicsViewPrivate;
- friend class QGraphicsWidget;
- friend class QGraphicsWidgetPrivate;
- friend class QGraphicsEffect;
- friend class QGraphicsSceneIndex;
- friend class QGraphicsSceneIndexPrivate;
- friend class QGraphicsSceneBspTreeIndex;
- friend class QGraphicsSceneBspTreeIndexPrivate;
- friend class QGraphicsItemEffectSourcePrivate;
-#ifndef QT_NO_GESTURES
- friend class QGesture;
-#endif
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsScene::SceneLayers)
-
-#endif // QT_NO_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsscene_bsp.cpp b/src/gui/graphicsview/qgraphicsscene_bsp.cpp
deleted file mode 100644
index 3716debcc4..0000000000
--- a/src/gui/graphicsview/qgraphicsscene_bsp.cpp
+++ /dev/null
@@ -1,296 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgraphicsscene_bsp_p.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include <QtCore/qstring.h>
-#include <private/qgraphicsitem_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsSceneInsertItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
-{
-public:
- QGraphicsItem *item;
-
- void visit(QList<QGraphicsItem *> *items)
- { items->prepend(item); }
-};
-
-class QGraphicsSceneRemoveItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
-{
-public:
- QGraphicsItem *item;
-
- void visit(QList<QGraphicsItem *> *items)
- { items->removeAll(item); }
-};
-
-class QGraphicsSceneFindItemBspTreeVisitor : public QGraphicsSceneBspTreeVisitor
-{
-public:
- QList<QGraphicsItem *> *foundItems;
- bool onlyTopLevelItems;
-
- void visit(QList<QGraphicsItem *> *items)
- {
- for (int i = 0; i < items->size(); ++i) {
- QGraphicsItem *item = items->at(i);
- if (onlyTopLevelItems && item->d_ptr->parent)
- item = item->topLevelItem();
- if (!item->d_func()->itemDiscovered && item->d_ptr->visible) {
- item->d_func()->itemDiscovered = 1;
- foundItems->prepend(item);
- }
- }
- }
-};
-
-QGraphicsSceneBspTree::QGraphicsSceneBspTree()
- : leafCnt(0)
-{
- insertVisitor = new QGraphicsSceneInsertItemBspTreeVisitor;
- removeVisitor = new QGraphicsSceneRemoveItemBspTreeVisitor;
- findVisitor = new QGraphicsSceneFindItemBspTreeVisitor;
-}
-
-QGraphicsSceneBspTree::~QGraphicsSceneBspTree()
-{
- delete insertVisitor;
- delete removeVisitor;
- delete findVisitor;
-}
-
-void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth)
-{
- this->rect = rect;
- leafCnt = 0;
- nodes.resize((1 << (depth + 1)) - 1);
- nodes.fill(Node());
- leaves.resize(1 << depth);
- leaves.fill(QList<QGraphicsItem *>());
-
- initialize(rect, depth, 0);
-}
-
-void QGraphicsSceneBspTree::clear()
-{
- leafCnt = 0;
- nodes.clear();
- leaves.clear();
-}
-
-void QGraphicsSceneBspTree::insertItem(QGraphicsItem *item, const QRectF &rect)
-{
- insertVisitor->item = item;
- climbTree(insertVisitor, rect);
-}
-
-void QGraphicsSceneBspTree::removeItem(QGraphicsItem *item, const QRectF &rect)
-{
- removeVisitor->item = item;
- climbTree(removeVisitor, rect);
-}
-
-void QGraphicsSceneBspTree::removeItems(const QSet<QGraphicsItem *> &items)
-{
- for (int i = 0; i < leaves.size(); ++i) {
- QList<QGraphicsItem *> newItemList;
- const QList<QGraphicsItem *> &oldItemList = leaves[i];
- for (int j = 0; j < oldItemList.size(); ++j) {
- QGraphicsItem *item = oldItemList.at(j);
- if (!items.contains(item))
- newItemList << item;
- }
- leaves[i] = newItemList;
- }
-}
-
-QList<QGraphicsItem *> QGraphicsSceneBspTree::items(const QRectF &rect, bool onlyTopLevelItems) const
-{
- QList<QGraphicsItem *> tmp;
- findVisitor->foundItems = &tmp;
- findVisitor->onlyTopLevelItems = onlyTopLevelItems;
- climbTree(findVisitor, rect);
- // Reset discovery bits.
- for (int i = 0; i < tmp.size(); ++i)
- tmp.at(i)->d_ptr->itemDiscovered = 0;
- return tmp;
-}
-
-int QGraphicsSceneBspTree::leafCount() const
-{
- return leafCnt;
-}
-
-QString QGraphicsSceneBspTree::debug(int index) const
-{
- const Node *node = &nodes.at(index);
-
- QString tmp;
- if (node->type == Node::Leaf) {
- QRectF rect = rectForIndex(index);
- if (!leaves[node->leafIndex].isEmpty()) {
- tmp += QString::fromLatin1("[%1, %2, %3, %4] contains %5 items\n")
- .arg(rect.left()).arg(rect.top())
- .arg(rect.width()).arg(rect.height())
- .arg(leaves[node->leafIndex].size());
- }
- } else {
- if (node->type == Node::Horizontal) {
- tmp += debug(firstChildIndex(index));
- tmp += debug(firstChildIndex(index) + 1);
- } else {
- tmp += debug(firstChildIndex(index));
- tmp += debug(firstChildIndex(index) + 1);
- }
- }
-
- return tmp;
-}
-
-void QGraphicsSceneBspTree::initialize(const QRectF &rect, int depth, int index)
-{
- Node *node = &nodes[index];
- if (index == 0) {
- node->type = Node::Horizontal;
- node->offset = rect.center().x();
- }
-
- if (depth) {
- Node::Type type;
- QRectF rect1, rect2;
- qreal offset1, offset2;
-
- if (node->type == Node::Horizontal) {
- type = Node::Vertical;
- rect1.setRect(rect.left(), rect.top(), rect.width(), rect.height() / 2);
- rect2.setRect(rect1.left(), rect1.bottom(), rect1.width(), rect.height() - rect1.height());
- offset1 = rect1.center().x();
- offset2 = rect2.center().x();
- } else {
- type = Node::Horizontal;
- rect1.setRect(rect.left(), rect.top(), rect.width() / 2, rect.height());
- rect2.setRect(rect1.right(), rect1.top(), rect.width() - rect1.width(), rect1.height());
- offset1 = rect1.center().y();
- offset2 = rect2.center().y();
- }
-
- int childIndex = firstChildIndex(index);
-
- Node *child = &nodes[childIndex];
- child->offset = offset1;
- child->type = type;
-
- child = &nodes[childIndex + 1];
- child->offset = offset2;
- child->type = type;
-
- initialize(rect1, depth - 1, childIndex);
- initialize(rect2, depth - 1, childIndex + 1);
- } else {
- node->type = Node::Leaf;
- node->leafIndex = leafCnt++;
- }
-}
-
-void QGraphicsSceneBspTree::climbTree(QGraphicsSceneBspTreeVisitor *visitor, const QRectF &rect, int index) const
-{
- if (nodes.isEmpty())
- return;
-
- const Node &node = nodes.at(index);
- const int childIndex = firstChildIndex(index);
-
- switch (node.type) {
- case Node::Leaf: {
- visitor->visit(const_cast<QList<QGraphicsItem*>*>(&leaves[node.leafIndex]));
- break;
- }
- case Node::Vertical:
- if (rect.left() < node.offset) {
- climbTree(visitor, rect, childIndex);
- if (rect.right() >= node.offset)
- climbTree(visitor, rect, childIndex + 1);
- } else {
- climbTree(visitor, rect, childIndex + 1);
- }
- break;
- case Node::Horizontal:
- if (rect.top() < node.offset) {
- climbTree(visitor, rect, childIndex);
- if (rect.bottom() >= node.offset)
- climbTree(visitor, rect, childIndex + 1);
- } else {
- climbTree(visitor, rect, childIndex + 1);
- }
- }
-}
-
-QRectF QGraphicsSceneBspTree::rectForIndex(int index) const
-{
- if (index <= 0)
- return rect;
-
- int parentIdx = parentIndex(index);
- QRectF rect = rectForIndex(parentIdx);
- const Node *parent = &nodes.at(parentIdx);
-
- if (parent->type == Node::Horizontal) {
- if (index & 1)
- rect.setRight(parent->offset);
- else
- rect.setLeft(parent->offset);
- } else {
- if (index & 1)
- rect.setBottom(parent->offset);
- else
- rect.setTop(parent->offset);
- }
-
- return rect;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsscene_bsp_p.h b/src/gui/graphicsview/qgraphicsscene_bsp_p.h
deleted file mode 100644
index 4f230eff79..0000000000
--- a/src/gui/graphicsview/qgraphicsscene_bsp_p.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSSCENEBSPTREE_P_H
-#define QGRAPHICSSCENEBSPTREE_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 <QtCore/qlist.h>
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-#include <QtCore/qrect.h>
-#include <QtCore/qset.h>
-#include <QtCore/qvector.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsItem;
-class QGraphicsSceneBspTreeVisitor;
-class QGraphicsSceneInsertItemBspTreeVisitor;
-class QGraphicsSceneRemoveItemBspTreeVisitor;
-class QGraphicsSceneFindItemBspTreeVisitor;
-
-class QGraphicsSceneBspTree
-{
-public:
- struct Node
- {
- enum Type { Horizontal, Vertical, Leaf };
- union {
- qreal offset;
- int leafIndex;
- };
- Type type;
- };
-
- QGraphicsSceneBspTree();
- ~QGraphicsSceneBspTree();
-
- void initialize(const QRectF &rect, int depth);
- void clear();
-
- void insertItem(QGraphicsItem *item, const QRectF &rect);
- void removeItem(QGraphicsItem *item, const QRectF &rect);
- void removeItems(const QSet<QGraphicsItem *> &items);
-
- QList<QGraphicsItem *> items(const QRectF &rect, bool onlyTopLevelItems = false) const;
- int leafCount() const;
-
- inline int firstChildIndex(int index) const
- { return index * 2 + 1; }
-
- inline int parentIndex(int index) const
- { return index > 0 ? ((index & 1) ? ((index - 1) / 2) : ((index - 2) / 2)) : -1; }
-
- QString debug(int index) const;
-
-private:
- void initialize(const QRectF &rect, int depth, int index);
- void climbTree(QGraphicsSceneBspTreeVisitor *visitor, const QRectF &rect, int index = 0) const;
- QRectF rectForIndex(int index) const;
-
- QVector<Node> nodes;
- QVector<QList<QGraphicsItem *> > leaves;
- int leafCnt;
- QRectF rect;
-
- QGraphicsSceneInsertItemBspTreeVisitor *insertVisitor;
- QGraphicsSceneRemoveItemBspTreeVisitor *removeVisitor;
- QGraphicsSceneFindItemBspTreeVisitor *findVisitor;
-};
-
-class QGraphicsSceneBspTreeVisitor
-{
-public:
- virtual ~QGraphicsSceneBspTreeVisitor() { }
- virtual void visit(QList<QGraphicsItem *> *items) = 0;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
-
-#endif // QGRAPHICSSCENEBSPTREE_P_H
diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h
deleted file mode 100644
index 9460a4dc51..0000000000
--- a/src/gui/graphicsview/qgraphicsscene_p.h
+++ /dev/null
@@ -1,359 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSSCENE_P_H
-#define QGRAPHICSSCENE_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 "qgraphicsscene.h"
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-#include "qgraphicssceneevent.h"
-#include "qgraphicsview.h"
-#include "qgraphicsview_p.h"
-#include "qgraphicsitem_p.h"
-
-#include <private/qobject_p.h>
-#include <QtCore/qbitarray.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qmap.h>
-#include <QtCore/qset.h>
-#include <QtGui/qfont.h>
-#include <QtGui/qpalette.h>
-#include <QtGui/qstyle.h>
-#include <QtGui/qstyleoption.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsSceneIndex;
-class QGraphicsView;
-class QGraphicsWidget;
-
-class Q_AUTOTEST_EXPORT QGraphicsScenePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsScene)
-public:
- QGraphicsScenePrivate();
- void init();
-
- static QGraphicsScenePrivate *get(QGraphicsScene *q);
-
- int changedSignalIndex;
- int processDirtyItemsIndex;
- int polishItemsIndex;
-
- QGraphicsScene::ItemIndexMethod indexMethod;
- QGraphicsSceneIndex *index;
-
- int lastItemCount;
-
- QRectF sceneRect;
-
- quint32 hasSceneRect : 1;
- quint32 dirtyGrowingItemsBoundingRect : 1;
- quint32 updateAll : 1;
- quint32 calledEmitUpdated : 1;
- quint32 processDirtyItemsEmitted : 1;
- quint32 needSortTopLevelItems : 1;
- quint32 holesInTopLevelSiblingIndex : 1;
- quint32 topLevelSequentialOrdering : 1;
- quint32 scenePosDescendantsUpdatePending : 1;
- quint32 stickyFocus : 1;
- quint32 hasFocus : 1;
- quint32 lastMouseGrabberItemHasImplicitMouseGrab : 1;
- quint32 allItemsIgnoreHoverEvents : 1;
- quint32 allItemsUseDefaultCursor : 1;
- quint32 painterStateProtection : 1;
- quint32 sortCacheEnabled : 1; // for compatibility
- quint32 allItemsIgnoreTouchEvents : 1;
- quint32 padding : 15;
-
- QRectF growingItemsBoundingRect;
-
- void _q_emitUpdated();
- QList<QRectF> updatedRects;
-
- QPainterPath selectionArea;
- int selectionChanging;
- QSet<QGraphicsItem *> selectedItems;
- QVector<QGraphicsItem *> unpolishedItems;
- QList<QGraphicsItem *> topLevelItems;
-
- QMap<QGraphicsItem *, QPointF> movingItemsInitialPositions;
- void registerTopLevelItem(QGraphicsItem *item);
- void unregisterTopLevelItem(QGraphicsItem *item);
- void _q_updateLater();
- void _q_polishItems();
-
- void _q_processDirtyItems();
-
- QSet<QGraphicsItem *> scenePosItems;
- void setScenePosItemEnabled(QGraphicsItem *item, bool enabled);
- void registerScenePosItem(QGraphicsItem *item);
- void unregisterScenePosItem(QGraphicsItem *item);
- void _q_updateScenePosDescendants();
-
- void removeItemHelper(QGraphicsItem *item);
-
- QBrush backgroundBrush;
- QBrush foregroundBrush;
-
- quint32 rectAdjust;
- QGraphicsItem *focusItem;
- QGraphicsItem *lastFocusItem;
- QGraphicsItem *passiveFocusItem;
- QGraphicsWidget *tabFocusFirst;
- QGraphicsItem *activePanel;
- QGraphicsItem *lastActivePanel;
- int activationRefCount;
- int childExplicitActivation;
- void setActivePanelHelper(QGraphicsItem *item, bool duringActivationEvent);
- void setFocusItemHelper(QGraphicsItem *item, Qt::FocusReason focusReason);
-
- QList<QGraphicsWidget *> popupWidgets;
- void addPopup(QGraphicsWidget *widget);
- void removePopup(QGraphicsWidget *widget, bool itemIsDying = false);
-
- QGraphicsItem *lastMouseGrabberItem;
- QList<QGraphicsItem *> mouseGrabberItems;
- void grabMouse(QGraphicsItem *item, bool implicit = false);
- void ungrabMouse(QGraphicsItem *item, bool itemIsDying = false);
- void clearMouseGrabber();
-
- QList<QGraphicsItem *> keyboardGrabberItems;
- void grabKeyboard(QGraphicsItem *item);
- void ungrabKeyboard(QGraphicsItem *item, bool itemIsDying = false);
- void clearKeyboardGrabber();
-
- QGraphicsItem *dragDropItem;
- QGraphicsWidget *enterWidget;
- Qt::DropAction lastDropAction;
- QList<QGraphicsItem *> cachedItemsUnderMouse;
- QList<QGraphicsItem *> hoverItems;
- QPointF lastSceneMousePos;
- void enableMouseTrackingOnViews();
- QMap<Qt::MouseButton, QPointF> mouseGrabberButtonDownPos;
- QMap<Qt::MouseButton, QPointF> mouseGrabberButtonDownScenePos;
- QMap<Qt::MouseButton, QPoint> mouseGrabberButtonDownScreenPos;
- QList<QGraphicsItem *> itemsAtPosition(const QPoint &screenPos,
- const QPointF &scenePos,
- QWidget *widget) const;
- void storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event);
-
- QList<QGraphicsView *> views;
- void addView(QGraphicsView *view);
- void removeView(QGraphicsView *view);
-
- QMultiMap<QGraphicsItem *, QGraphicsItem *> sceneEventFilters;
- void installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter);
- void removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter);
- bool filterDescendantEvent(QGraphicsItem *item, QEvent *event);
- bool filterEvent(QGraphicsItem *item, QEvent *event);
- bool sendEvent(QGraphicsItem *item, QEvent *event);
-
- bool dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent);
- bool itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const;
- void leaveScene(QWidget *viewport);
-
- void cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
- QGraphicsSceneDragDropEvent *source);
- void sendDragDropEvent(QGraphicsItem *item,
- QGraphicsSceneDragDropEvent *dragDropEvent);
- void sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
- QGraphicsSceneHoverEvent *hoverEvent);
- void sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent);
- void mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent);
- QGraphicsWidget *windowForItem(const QGraphicsItem *item) const;
-
- void drawItemHelper(QGraphicsItem *item, QPainter *painter,
- const QStyleOptionGraphicsItem *option, QWidget *widget,
- bool painterStateProtection);
-
- void drawItems(QPainter *painter, const QTransform *const viewTransform,
- QRegion *exposedRegion, QWidget *widget);
-
- void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform *const,
- QRegion *exposedRegion, QWidget *widget, qreal parentOpacity = qreal(1.0),
- const QTransform *const effectTransform = 0);
- void draw(QGraphicsItem *, QPainter *, const QTransform *const, const QTransform *const,
- QRegion *, QWidget *, qreal, const QTransform *const, bool, bool);
-
- void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false,
- bool force = false, bool ignoreOpacity = false, bool removingItemFromScene = false,
- bool updateBoundingRect = false);
- void processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren = false,
- qreal parentOpacity = qreal(1.0));
-
- inline void resetDirtyItem(QGraphicsItem *item, bool recursive = false)
- {
- Q_ASSERT(item);
- item->d_ptr->dirty = 0;
- item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
- item->d_ptr->geometryChanged = 0;
- if (!item->d_ptr->dirtyChildren)
- recursive = false;
- item->d_ptr->dirtyChildren = 0;
- item->d_ptr->needsRepaint = QRectF();
- item->d_ptr->allChildrenDirty = 0;
- item->d_ptr->fullUpdatePending = 0;
- item->d_ptr->ignoreVisible = 0;
- item->d_ptr->ignoreOpacity = 0;
-#ifndef QT_NO_GRAPHICSEFFECT
- QGraphicsEffect::ChangeFlags flags;
- if (item->d_ptr->notifyBoundingRectChanged) {
- flags |= QGraphicsEffect::SourceBoundingRectChanged;
- item->d_ptr->notifyBoundingRectChanged = 0;
- }
- if (item->d_ptr->notifyInvalidated) {
- flags |= QGraphicsEffect::SourceInvalidated;
- item->d_ptr->notifyInvalidated = 0;
- }
-#endif //QT_NO_GRAPHICSEFFECT
- if (recursive) {
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- resetDirtyItem(item->d_ptr->children.at(i), recursive);
- }
-#ifndef QT_NO_GRAPHICSEFFECT
- if (flags && item->d_ptr->graphicsEffect)
- item->d_ptr->graphicsEffect->sourceChanged(flags);
-#endif //QT_NO_GRAPHICSEFFECT
- }
-
- inline void ensureSortedTopLevelItems()
- {
- if (needSortTopLevelItems) {
- qSort(topLevelItems.begin(), topLevelItems.end(), qt_notclosestLeaf);
- topLevelSequentialOrdering = false;
- needSortTopLevelItems = false;
- }
- }
-
- void ensureSequentialTopLevelSiblingIndexes();
-
- QStyle *style;
- QFont font;
- void setFont_helper(const QFont &font);
- void resolveFont();
- void updateFont(const QFont &font);
- QPalette palette;
- void setPalette_helper(const QPalette &palette);
- void resolvePalette();
- void updatePalette(const QPalette &palette);
-
- QStyleOptionGraphicsItem styleOptionTmp;
-
- QMap<int, QTouchEvent::TouchPoint> sceneCurrentTouchPoints;
- QMap<int, QGraphicsItem *> itemForTouchPointId;
- static void updateTouchPointsForItem(QGraphicsItem *item, QTouchEvent *touchEvent);
- int findClosestTouchPointId(const QPointF &scenePos);
- void touchEventHandler(QTouchEvent *touchEvent);
- bool sendTouchBeginEvent(QGraphicsItem *item, QTouchEvent *touchEvent);
- void enableTouchEventsOnViews();
-
- QList<QGraphicsObject *> cachedTargetItems;
-#ifndef QT_NO_GESTURES
- QHash<QGraphicsObject *, QSet<QGesture *> > cachedItemGestures;
- QHash<QGraphicsObject *, QSet<QGesture *> > cachedAlreadyDeliveredGestures;
- QHash<QGesture *, QGraphicsObject *> gestureTargets;
- QHash<Qt::GestureType, int> grabbedGestures;
- void gestureEventHandler(QGestureEvent *event);
- void gestureTargetsAtHotSpots(const QSet<QGesture *> &gestures,
- Qt::GestureFlag flag,
- QHash<QGraphicsObject *, QSet<QGesture *> > *targets,
- QSet<QGraphicsObject *> *itemsSet = 0,
- QSet<QGesture *> *normal = 0,
- QSet<QGesture *> *conflicts = 0);
- void cancelGesturesForChildren(QGesture *original);
- void grabGesture(QGraphicsItem *, Qt::GestureType gesture);
- void ungrabGesture(QGraphicsItem *, Qt::GestureType gesture);
-#endif // QT_NO_GESTURES
-
- void updateInputMethodSensitivityInViews();
-
- QList<QGraphicsItem *> modalPanels;
- void enterModal(QGraphicsItem *item,
- QGraphicsItem::PanelModality panelModality = QGraphicsItem::NonModal);
- void leaveModal(QGraphicsItem *item);
-};
-
-// QRectF::intersects() returns false always if either the source or target
-// rectangle's width or height are 0. This works around that problem.
-static inline void _q_adjustRect(QRectF *rect)
-{
- Q_ASSERT(rect);
- if (!rect->width())
- rect->adjust(qreal(-0.00001), 0, qreal(0.00001), 0);
- if (!rect->height())
- rect->adjust(0, qreal(-0.00001), 0, qreal(0.00001));
-}
-
-static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item)
-{
- Q_ASSERT(item);
- QRectF boundingRect(item->boundingRect());
- _q_adjustRect(&boundingRect);
- return boundingRect;
-}
-
-static inline QRectF adjustedItemEffectiveBoundingRect(const QGraphicsItem *item)
-{
- Q_ASSERT(item);
- QRectF boundingRect(QGraphicsItemPrivate::get(item)->effectiveBoundingRect());
- _q_adjustRect(&boundingRect);
- return boundingRect;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp b/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp
deleted file mode 100644
index 92e4a55952..0000000000
--- a/src/gui/graphicsview/qgraphicsscenebsptreeindex.cpp
+++ /dev/null
@@ -1,719 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsSceneBspTreeIndex
- \brief The QGraphicsSceneBspTreeIndex class provides an implementation of
- a BSP indexing algorithm for discovering items in QGraphicsScene.
- \since 4.6
- \ingroup graphicsview-api
-
- \internal
-
- QGraphicsSceneBspTreeIndex index use a BSP(Binary Space Partitioning)
- implementation to discover items quickly. This implementation is
- very efficient for static scene. It has a depth that you can set.
- The depth directly affects performance and memory usage; the latter
- growing exponentially with the depth of the tree. With an optimal tree
- depth, the index can instantly determine the locality of items, even
- for scenes with thousands or millions of items. This also greatly improves
- rendering performance.
-
- By default, the value is 0, in which case Qt will guess a reasonable
- default depth based on the size, location and number of items in the
- scene. If these parameters change frequently, however, you may experience
- slowdowns as the index retunes the depth internally. You can avoid
- potential slowdowns by fixating the tree depth through setting this
- property.
-
- The depth of the tree and the size of the scene rectangle decide the
- granularity of the scene's partitioning. The size of each scene segment is
- determined by the following algorithm:
-
- The BSP tree has an optimal size when each segment contains between 0 and
- 10 items.
-
- \sa QGraphicsScene, QGraphicsView, QGraphicsSceneIndex
-*/
-
-#include <QtCore/qglobal.h>
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include <private/qgraphicsscene_p.h>
-#include <private/qgraphicsscenebsptreeindex_p.h>
-#include <private/qgraphicssceneindex_p.h>
-
-#include <QtCore/qmath.h>
-#include <QtCore/qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-static inline int intmaxlog(int n)
-{
- return (n > 0 ? qMax(qCeil(qLn(qreal(n)) / qLn(qreal(2))), 5) : 0);
-}
-
-/*!
- Constructs a private scene bsp index.
-*/
-QGraphicsSceneBspTreeIndexPrivate::QGraphicsSceneBspTreeIndexPrivate(QGraphicsScene *scene)
- : QGraphicsSceneIndexPrivate(scene),
- bspTreeDepth(0),
- indexTimerId(0),
- restartIndexTimer(false),
- regenerateIndex(true),
- lastItemCount(0),
- purgePending(false),
- sortCacheEnabled(false),
- updatingSortCache(false)
-{
-}
-
-
-/*!
- This method will update the BSP index by removing the items from the temporary
- unindexed list and add them in the indexedItems list. This will also
- update the growingItemsBoundingRect if needed. This will update the BSP
- implementation as well.
-
- \internal
-*/
-void QGraphicsSceneBspTreeIndexPrivate::_q_updateIndex()
-{
- Q_Q(QGraphicsSceneBspTreeIndex);
- if (!indexTimerId)
- return;
-
- q->killTimer(indexTimerId);
- indexTimerId = 0;
-
- purgeRemovedItems();
-
- // Add unindexedItems to indexedItems
- for (int i = 0; i < unindexedItems.size(); ++i) {
- if (QGraphicsItem *item = unindexedItems.at(i)) {
- Q_ASSERT(!item->d_ptr->itemDiscovered);
- if (!freeItemIndexes.isEmpty()) {
- int freeIndex = freeItemIndexes.takeFirst();
- item->d_func()->index = freeIndex;
- indexedItems[freeIndex] = item;
- } else {
- item->d_func()->index = indexedItems.size();
- indexedItems << item;
- }
- }
- }
-
- // Determine whether we should regenerate the BSP tree.
- if (bspTreeDepth == 0) {
- int oldDepth = intmaxlog(lastItemCount);
- bspTreeDepth = intmaxlog(indexedItems.size());
- static const int slack = 100;
- if (bsp.leafCount() == 0 || (oldDepth != bspTreeDepth && qAbs(lastItemCount - indexedItems.size()) > slack)) {
- // ### Crude algorithm.
- regenerateIndex = true;
- }
- }
-
- // Regenerate the tree.
- if (regenerateIndex) {
- regenerateIndex = false;
- bsp.initialize(sceneRect, bspTreeDepth);
- unindexedItems = indexedItems;
- lastItemCount = indexedItems.size();
- }
-
- // Insert all unindexed items into the tree.
- for (int i = 0; i < unindexedItems.size(); ++i) {
- if (QGraphicsItem *item = unindexedItems.at(i)) {
- if (item->d_ptr->itemIsUntransformable()) {
- untransformableItems << item;
- continue;
- }
- if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)
- continue;
-
- bsp.insertItem(item, item->d_ptr->sceneEffectiveBoundingRect());
- }
- }
- unindexedItems.clear();
-}
-
-
-/*!
- \internal
-
- Removes stale pointers from all data structures.
-*/
-void QGraphicsSceneBspTreeIndexPrivate::purgeRemovedItems()
-{
- if (!purgePending && removedItems.isEmpty())
- return;
-
- // Remove stale items from the BSP tree.
- bsp.removeItems(removedItems);
- // Purge this list.
- removedItems.clear();
- freeItemIndexes.clear();
- for (int i = 0; i < indexedItems.size(); ++i) {
- if (!indexedItems.at(i))
- freeItemIndexes << i;
- }
- purgePending = false;
-}
-
-/*!
- \internal
-
- Starts or restarts the timer used for reindexing unindexed items.
-*/
-void QGraphicsSceneBspTreeIndexPrivate::startIndexTimer(int interval)
-{
- Q_Q(QGraphicsSceneBspTreeIndex);
- if (indexTimerId) {
- restartIndexTimer = true;
- } else {
- indexTimerId = q->startTimer(interval);
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneBspTreeIndexPrivate::resetIndex()
-{
- purgeRemovedItems();
- for (int i = 0; i < indexedItems.size(); ++i) {
- if (QGraphicsItem *item = indexedItems.at(i)) {
- item->d_ptr->index = -1;
- Q_ASSERT(!item->d_ptr->itemDiscovered);
- unindexedItems << item;
- }
- }
- indexedItems.clear();
- freeItemIndexes.clear();
- untransformableItems.clear();
- regenerateIndex = true;
- startIndexTimer();
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneBspTreeIndexPrivate::climbTree(QGraphicsItem *item, int *stackingOrder)
-{
- if (!item->d_ptr->children.isEmpty()) {
- QList<QGraphicsItem *> childList = item->d_ptr->children;
- qSort(childList.begin(), childList.end(), qt_closestLeaf);
- for (int i = 0; i < childList.size(); ++i) {
- QGraphicsItem *item = childList.at(i);
- if (!(item->flags() & QGraphicsItem::ItemStacksBehindParent))
- climbTree(childList.at(i), stackingOrder);
- }
- item->d_ptr->globalStackingOrder = (*stackingOrder)++;
- for (int i = 0; i < childList.size(); ++i) {
- QGraphicsItem *item = childList.at(i);
- if (item->flags() & QGraphicsItem::ItemStacksBehindParent)
- climbTree(childList.at(i), stackingOrder);
- }
- } else {
- item->d_ptr->globalStackingOrder = (*stackingOrder)++;
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneBspTreeIndexPrivate::_q_updateSortCache()
-{
- Q_Q(QGraphicsSceneBspTreeIndex);
- _q_updateIndex();
-
- if (!sortCacheEnabled || !updatingSortCache)
- return;
-
- updatingSortCache = false;
- int stackingOrder = 0;
-
- QList<QGraphicsItem *> topLevels;
- const QList<QGraphicsItem *> items = q->items();
- for (int i = 0; i < items.size(); ++i) {
- QGraphicsItem *item = items.at(i);
- if (item && !item->d_ptr->parent)
- topLevels << item;
- }
-
- qSort(topLevels.begin(), topLevels.end(), qt_closestLeaf);
- for (int i = 0; i < topLevels.size(); ++i)
- climbTree(topLevels.at(i), &stackingOrder);
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneBspTreeIndexPrivate::invalidateSortCache()
-{
- Q_Q(QGraphicsSceneBspTreeIndex);
- if (!sortCacheEnabled || updatingSortCache)
- return;
-
- updatingSortCache = true;
- QMetaObject::invokeMethod(q, "_q_updateSortCache", Qt::QueuedConnection);
-}
-
-void QGraphicsSceneBspTreeIndexPrivate::addItem(QGraphicsItem *item, bool recursive)
-{
- if (!item)
- return;
-
- // Prevent reusing a recently deleted pointer: purge all removed item from our lists.
- purgeRemovedItems();
-
- // Invalidate any sort caching; arrival of a new item means we need to resort.
- // Update the scene's sort cache settings.
- item->d_ptr->globalStackingOrder = -1;
- invalidateSortCache();
-
- // Indexing requires sceneBoundingRect(), but because \a item might
- // not be completely constructed at this point, we need to store it in
- // a temporary list and schedule an indexing for later.
- if (item->d_ptr->index == -1) {
- Q_ASSERT(!unindexedItems.contains(item));
- unindexedItems << item;
- startIndexTimer(0);
- } else {
- Q_ASSERT(indexedItems.contains(item));
- qWarning("QGraphicsSceneBspTreeIndex::addItem: item has already been added to this BSP");
- }
-
- if (recursive) {
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- addItem(item->d_ptr->children.at(i), recursive);
- }
-}
-
-void QGraphicsSceneBspTreeIndexPrivate::removeItem(QGraphicsItem *item, bool recursive,
- bool moveToUnindexedItems)
-{
- if (!item)
- return;
-
- if (item->d_ptr->index != -1) {
- Q_ASSERT(item->d_ptr->index < indexedItems.size());
- Q_ASSERT(indexedItems.at(item->d_ptr->index) == item);
- Q_ASSERT(!item->d_ptr->itemDiscovered);
- freeItemIndexes << item->d_ptr->index;
- indexedItems[item->d_ptr->index] = 0;
- item->d_ptr->index = -1;
-
- if (item->d_ptr->itemIsUntransformable()) {
- untransformableItems.removeOne(item);
- } else if (item->d_ptr->inDestructor) {
- // Avoid virtual function calls from the destructor.
- purgePending = true;
- removedItems << item;
- } else if (!(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
- bsp.removeItem(item, item->d_ptr->sceneEffectiveBoundingRect());
- }
- } else {
- unindexedItems.removeOne(item);
- }
- invalidateSortCache(); // ### Only do this when removing from BSP?
-
- Q_ASSERT(item->d_ptr->index == -1);
- Q_ASSERT(!indexedItems.contains(item));
- Q_ASSERT(!unindexedItems.contains(item));
- Q_ASSERT(!untransformableItems.contains(item));
-
- if (moveToUnindexedItems)
- addItem(item);
-
- if (recursive) {
- for (int i = 0; i < item->d_ptr->children.size(); ++i)
- removeItem(item->d_ptr->children.at(i), recursive, moveToUnindexedItems);
- }
-}
-
-QList<QGraphicsItem *> QGraphicsSceneBspTreeIndexPrivate::estimateItems(const QRectF &rect, Qt::SortOrder order,
- bool onlyTopLevelItems)
-{
- Q_Q(QGraphicsSceneBspTreeIndex);
- if (onlyTopLevelItems && rect.isNull())
- return q->QGraphicsSceneIndex::estimateTopLevelItems(rect, order);
-
- purgeRemovedItems();
- _q_updateSortCache();
- Q_ASSERT(unindexedItems.isEmpty());
-
- QList<QGraphicsItem *> rectItems = bsp.items(rect, onlyTopLevelItems);
- if (onlyTopLevelItems) {
- for (int i = 0; i < untransformableItems.size(); ++i) {
- QGraphicsItem *item = untransformableItems.at(i);
- if (!item->d_ptr->parent) {
- rectItems << item;
- } else {
- item = item->topLevelItem();
- if (!rectItems.contains(item))
- rectItems << item;
- }
- }
- } else {
- rectItems += untransformableItems;
- }
-
- sortItems(&rectItems, order, sortCacheEnabled, onlyTopLevelItems);
- return rectItems;
-}
-
-/*!
- Sort a list of \a itemList in a specific \a order and use the cache if requested.
-
- \internal
-*/
-void QGraphicsSceneBspTreeIndexPrivate::sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
- bool sortCacheEnabled, bool onlyTopLevelItems)
-{
- if (order == Qt::SortOrder(-1))
- return;
-
- if (onlyTopLevelItems) {
- if (order == Qt::DescendingOrder)
- qSort(itemList->begin(), itemList->end(), qt_closestLeaf);
- else if (order == Qt::AscendingOrder)
- qSort(itemList->begin(), itemList->end(), qt_notclosestLeaf);
- return;
- }
-
- if (sortCacheEnabled) {
- if (order == Qt::DescendingOrder) {
- qSort(itemList->begin(), itemList->end(), closestItemFirst_withCache);
- } else if (order == Qt::AscendingOrder) {
- qSort(itemList->begin(), itemList->end(), closestItemLast_withCache);
- }
- } else {
- if (order == Qt::DescendingOrder) {
- qSort(itemList->begin(), itemList->end(), qt_closestItemFirst);
- } else if (order == Qt::AscendingOrder) {
- qSort(itemList->begin(), itemList->end(), qt_closestItemLast);
- }
- }
-}
-
-/*!
- Constructs a BSP scene index for the given \a scene.
-*/
-QGraphicsSceneBspTreeIndex::QGraphicsSceneBspTreeIndex(QGraphicsScene *scene)
- : QGraphicsSceneIndex(*new QGraphicsSceneBspTreeIndexPrivate(scene), scene)
-{
-
-}
-
-QGraphicsSceneBspTreeIndex::~QGraphicsSceneBspTreeIndex()
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- for (int i = 0; i < d->indexedItems.size(); ++i) {
- // Ensure item bits are reset properly.
- if (QGraphicsItem *item = d->indexedItems.at(i)) {
- Q_ASSERT(!item->d_ptr->itemDiscovered);
- item->d_ptr->index = -1;
- }
- }
-}
-
-/*!
- \internal
- Clear the all the BSP index.
-*/
-void QGraphicsSceneBspTreeIndex::clear()
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- d->bsp.clear();
- d->lastItemCount = 0;
- d->freeItemIndexes.clear();
- for (int i = 0; i < d->indexedItems.size(); ++i) {
- // Ensure item bits are reset properly.
- if (QGraphicsItem *item = d->indexedItems.at(i)) {
- Q_ASSERT(!item->d_ptr->itemDiscovered);
- item->d_ptr->index = -1;
- }
- }
- d->indexedItems.clear();
- d->unindexedItems.clear();
- d->untransformableItems.clear();
- d->regenerateIndex = true;
-}
-
-/*!
- Add the \a item into the BSP index.
-*/
-void QGraphicsSceneBspTreeIndex::addItem(QGraphicsItem *item)
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- d->addItem(item);
-}
-
-/*!
- Remove the \a item from the BSP index.
-*/
-void QGraphicsSceneBspTreeIndex::removeItem(QGraphicsItem *item)
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- d->removeItem(item);
-}
-
-/*!
- \internal
- Update the BSP when the \a item 's bounding rect has changed.
-*/
-void QGraphicsSceneBspTreeIndex::prepareBoundingRectChange(const QGraphicsItem *item)
-{
- if (!item)
- return;
-
- if (item->d_ptr->index == -1 || item->d_ptr->itemIsUntransformable()
- || (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) {
- return; // Item is not in BSP tree; nothing to do.
- }
-
- Q_D(QGraphicsSceneBspTreeIndex);
- QGraphicsItem *thatItem = const_cast<QGraphicsItem *>(item);
- d->removeItem(thatItem, /*recursive=*/false, /*moveToUnindexedItems=*/true);
- for (int i = 0; i < item->d_ptr->children.size(); ++i) // ### Do we really need this?
- prepareBoundingRectChange(item->d_ptr->children.at(i));
-}
-
-/*!
- Returns an estimation visible items that are either inside or
- intersect with the specified \a rect and return a list sorted using \a order.
-
- \a deviceTransform is the transformation apply to the view.
-
-*/
-QList<QGraphicsItem *> QGraphicsSceneBspTreeIndex::estimateItems(const QRectF &rect, Qt::SortOrder order) const
-{
- Q_D(const QGraphicsSceneBspTreeIndex);
- return const_cast<QGraphicsSceneBspTreeIndexPrivate*>(d)->estimateItems(rect, order);
-}
-
-QList<QGraphicsItem *> QGraphicsSceneBspTreeIndex::estimateTopLevelItems(const QRectF &rect, Qt::SortOrder order) const
-{
- Q_D(const QGraphicsSceneBspTreeIndex);
- return const_cast<QGraphicsSceneBspTreeIndexPrivate*>(d)->estimateItems(rect, order, /*onlyTopLevels=*/true);
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneBspTreeIndex::items(Qt::SortOrder order = Qt::DescendingOrder) const;
-
- Return all items in the BSP index and sort them using \a order.
-*/
-QList<QGraphicsItem *> QGraphicsSceneBspTreeIndex::items(Qt::SortOrder order) const
-{
- Q_D(const QGraphicsSceneBspTreeIndex);
- const_cast<QGraphicsSceneBspTreeIndexPrivate*>(d)->purgeRemovedItems();
- QList<QGraphicsItem *> itemList;
-
- // If freeItemIndexes is empty, we know there are no holes in indexedItems and
- // unindexedItems.
- if (d->freeItemIndexes.isEmpty()) {
- if (d->unindexedItems.isEmpty()) {
- itemList = d->indexedItems;
- } else {
- itemList = d->indexedItems + d->unindexedItems;
- }
- } else {
- // Rebuild the list of items to avoid holes. ### We could also just
- // compress the item lists at this point.
- foreach (QGraphicsItem *item, d->indexedItems + d->unindexedItems) {
- if (item)
- itemList << item;
- }
- }
- if (order != -1) {
- //We sort descending order
- d->sortItems(&itemList, order, d->sortCacheEnabled);
- }
- return itemList;
-}
-
-/*!
- \property QGraphicsSceneBspTreeIndex::bspTreeDepth
- \brief the depth of the BSP index tree
- \since 4.6
-
- This value determines the depth of BSP tree. The depth
- directly affects performance and memory usage; the latter
- growing exponentially with the depth of the tree. With an optimal tree
- depth, the index can instantly determine the locality of items, even
- for scenes with thousands or millions of items. This also greatly improves
- rendering performance.
-
- By default, the value is 0, in which case Qt will guess a reasonable
- default depth based on the size, location and number of items in the
- scene. If these parameters change frequently, however, you may experience
- slowdowns as the index retunes the depth internally. You can avoid
- potential slowdowns by fixating the tree depth through setting this
- property.
-
- The depth of the tree and the size of the scene rectangle decide the
- granularity of the scene's partitioning. The size of each scene segment is
- determined by the following algorithm:
-
- The BSP tree has an optimal size when each segment contains between 0 and
- 10 items.
-
-*/
-int QGraphicsSceneBspTreeIndex::bspTreeDepth()
-{
- Q_D(const QGraphicsSceneBspTreeIndex);
- return d->bspTreeDepth;
-}
-
-void QGraphicsSceneBspTreeIndex::setBspTreeDepth(int depth)
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- if (d->bspTreeDepth == depth)
- return;
- d->bspTreeDepth = depth;
- d->resetIndex();
-}
-
-/*!
- \internal
-
- This method react to the \a rect change of the scene and
- reset the BSP tree index.
-*/
-void QGraphicsSceneBspTreeIndex::updateSceneRect(const QRectF &rect)
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- d->sceneRect = rect;
- d->resetIndex();
-}
-
-/*!
- \internal
-
- This method react to the \a change of the \a item and use the \a value to
- update the BSP tree if necessary.
-*/
-void QGraphicsSceneBspTreeIndex::itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const void *const value)
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- switch (change) {
- case QGraphicsItem::ItemFlagsChange: {
- // Handle ItemIgnoresTransformations
- QGraphicsItem::GraphicsItemFlags newFlags = *static_cast<const QGraphicsItem::GraphicsItemFlags *>(value);
- bool ignoredTransform = item->d_ptr->flags & QGraphicsItem::ItemIgnoresTransformations;
- bool willIgnoreTransform = newFlags & QGraphicsItem::ItemIgnoresTransformations;
- bool clipsChildren = item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape;
- bool willClipChildren = newFlags & QGraphicsItem::ItemClipsChildrenToShape;
- if ((ignoredTransform != willIgnoreTransform) || (clipsChildren != willClipChildren)) {
- QGraphicsItem *thatItem = const_cast<QGraphicsItem *>(item);
- // Remove item and its descendants from the index and append
- // them to the list of unindexed items. Then, when the index
- // is updated, they will be put into the bsp-tree or the list
- // of untransformable items.
- d->removeItem(thatItem, /*recursive=*/true, /*moveToUnidexedItems=*/true);
- }
- break;
- }
- case QGraphicsItem::ItemZValueChange:
- d->invalidateSortCache();
- break;
- case QGraphicsItem::ItemParentChange: {
- d->invalidateSortCache();
- // Handle ItemIgnoresTransformations
- const QGraphicsItem *newParent = static_cast<const QGraphicsItem *>(value);
- bool ignoredTransform = item->d_ptr->itemIsUntransformable();
- bool willIgnoreTransform = (item->d_ptr->flags & QGraphicsItem::ItemIgnoresTransformations)
- || (newParent && newParent->d_ptr->itemIsUntransformable());
- bool ancestorClippedChildren = item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren;
- bool ancestorWillClipChildren = newParent
- && ((newParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)
- || (newParent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren));
- if ((ignoredTransform != willIgnoreTransform) || (ancestorClippedChildren != ancestorWillClipChildren)) {
- QGraphicsItem *thatItem = const_cast<QGraphicsItem *>(item);
- // Remove item and its descendants from the index and append
- // them to the list of unindexed items. Then, when the index
- // is updated, they will be put into the bsp-tree or the list
- // of untransformable items.
- d->removeItem(thatItem, /*recursive=*/true, /*moveToUnidexedItems=*/true);
- }
- break;
- }
- default:
- break;
- }
-}
-/*!
- \reimp
-
- Used to catch the timer event.
-
- \internal
-*/
-bool QGraphicsSceneBspTreeIndex::event(QEvent *event)
-{
- Q_D(QGraphicsSceneBspTreeIndex);
- switch (event->type()) {
- case QEvent::Timer:
- if (d->indexTimerId && static_cast<QTimerEvent *>(event)->timerId() == d->indexTimerId) {
- if (d->restartIndexTimer) {
- d->restartIndexTimer = false;
- } else {
- // this call will kill the timer
- d->_q_updateIndex();
- }
- }
- // Fallthrough intended - support timers in subclasses.
- default:
- return QObject::event(event);
- }
- return true;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qgraphicsscenebsptreeindex_p.cpp"
-
-#endif // QT_NO_GRAPHICSVIEW
-
diff --git a/src/gui/graphicsview/qgraphicsscenebsptreeindex_p.h b/src/gui/graphicsview/qgraphicsscenebsptreeindex_p.h
deleted file mode 100644
index fadf9d8a74..0000000000
--- a/src/gui/graphicsview/qgraphicsscenebsptreeindex_p.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/****************************************************************************
-**
-** 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 QtCore 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-#ifndef QGRAPHICSBSPTREEINDEX_H
-#define QGRAPHICSBSPTREEINDEX_H
-
-#include <QtCore/qglobal.h>
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-#include "qgraphicssceneindex_p.h"
-#include "qgraphicsitem_p.h"
-#include "qgraphicsscene_bsp_p.h"
-
-#include <QtCore/qrect.h>
-#include <QtCore/qlist.h>
-
-QT_BEGIN_NAMESPACE
-
-static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000;
-
-class QGraphicsScene;
-class QGraphicsSceneBspTreeIndexPrivate;
-
-class Q_AUTOTEST_EXPORT QGraphicsSceneBspTreeIndex : public QGraphicsSceneIndex
-{
- Q_OBJECT
- Q_PROPERTY(int bspTreeDepth READ bspTreeDepth WRITE setBspTreeDepth)
-public:
- QGraphicsSceneBspTreeIndex(QGraphicsScene *scene = 0);
- ~QGraphicsSceneBspTreeIndex();
-
- QList<QGraphicsItem *> estimateItems(const QRectF &rect, Qt::SortOrder order) const;
- QList<QGraphicsItem *> estimateTopLevelItems(const QRectF &rect, Qt::SortOrder order) const;
- QList<QGraphicsItem *> items(Qt::SortOrder order = Qt::DescendingOrder) const;
-
- int bspTreeDepth();
- void setBspTreeDepth(int depth);
-
-protected Q_SLOTS:
- void updateSceneRect(const QRectF &rect);
-
-protected:
- bool event(QEvent *event);
- void clear();
-
- void addItem(QGraphicsItem *item);
- void removeItem(QGraphicsItem *item);
- void prepareBoundingRectChange(const QGraphicsItem *item);
-
- void itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const void *const value);
-
-private :
- Q_DECLARE_PRIVATE(QGraphicsSceneBspTreeIndex)
- Q_DISABLE_COPY(QGraphicsSceneBspTreeIndex)
- Q_PRIVATE_SLOT(d_func(), void _q_updateSortCache())
- Q_PRIVATE_SLOT(d_func(), void _q_updateIndex())
-
- friend class QGraphicsScene;
- friend class QGraphicsScenePrivate;
-};
-
-class QGraphicsSceneBspTreeIndexPrivate : public QGraphicsSceneIndexPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneBspTreeIndex)
-public:
- QGraphicsSceneBspTreeIndexPrivate(QGraphicsScene *scene);
-
- QGraphicsSceneBspTree bsp;
- QRectF sceneRect;
- int bspTreeDepth;
- int indexTimerId;
- bool restartIndexTimer;
- bool regenerateIndex;
- int lastItemCount;
-
- QList<QGraphicsItem *> indexedItems;
- QList<QGraphicsItem *> unindexedItems;
- QList<QGraphicsItem *> untransformableItems;
- QList<int> freeItemIndexes;
-
- bool purgePending;
- QSet<QGraphicsItem *> removedItems;
- void purgeRemovedItems();
-
- void _q_updateIndex();
- void startIndexTimer(int interval = QGRAPHICSSCENE_INDEXTIMER_TIMEOUT);
- void resetIndex();
-
- void _q_updateSortCache();
- bool sortCacheEnabled;
- bool updatingSortCache;
- void invalidateSortCache();
- void addItem(QGraphicsItem *item, bool recursive = false);
- void removeItem(QGraphicsItem *item, bool recursive = false, bool moveToUnindexedItems = false);
- QList<QGraphicsItem *> estimateItems(const QRectF &, Qt::SortOrder, bool b = false);
-
- static void climbTree(QGraphicsItem *item, int *stackingOrder);
-
- static inline bool closestItemFirst_withCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
- {
- return item1->d_ptr->globalStackingOrder < item2->d_ptr->globalStackingOrder;
- }
- static inline bool closestItemLast_withCache(const QGraphicsItem *item1, const QGraphicsItem *item2)
- {
- return item1->d_ptr->globalStackingOrder >= item2->d_ptr->globalStackingOrder;
- }
-
- static void sortItems(QList<QGraphicsItem *> *itemList, Qt::SortOrder order,
- bool cached, bool onlyTopLevelItems = false);
-};
-
-static inline bool QRectF_intersects(const QRectF &s, const QRectF &r)
-{
- qreal xp = s.left();
- qreal yp = s.top();
- qreal w = s.width();
- qreal h = s.height();
- qreal l1 = xp;
- qreal r1 = xp;
- if (w < 0)
- l1 += w;
- else
- r1 += w;
-
- qreal l2 = r.left();
- qreal r2 = r.left();
- if (w < 0)
- l2 += r.width();
- else
- r2 += r.width();
-
- if (l1 >= r2 || l2 >= r1)
- return false;
-
- qreal t1 = yp;
- qreal b1 = yp;
- if (h < 0)
- t1 += h;
- else
- b1 += h;
-
- qreal t2 = r.top();
- qreal b2 = r.top();
- if (r.height() < 0)
- t2 += r.height();
- else
- b2 += r.height();
-
- return !(t1 >= b2 || t2 >= b1);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
-
-#endif // QGRAPHICSBSPTREEINDEX_H
diff --git a/src/gui/graphicsview/qgraphicssceneevent.cpp b/src/gui/graphicsview/qgraphicssceneevent.cpp
deleted file mode 100644
index 1b1f3db0aa..0000000000
--- a/src/gui/graphicsview/qgraphicssceneevent.cpp
+++ /dev/null
@@ -1,1674 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsSceneEvent
- \brief The QGraphicsSceneEvent class provides a base class for all
- graphics view related events.
- \since 4.2
- \ingroup graphicsview-api
-
- When a QGraphicsView receives Qt mouse, keyboard, and drag and
- drop events (QMouseEvent, QKeyEvent, QDragEvent, etc.), it
- translates them into instances of QGraphicsSceneEvent subclasses
- and forwards them to the QGraphicsScene it displays. The scene
- then forwards the events to the relevant items.
-
- For example, when a QGraphicsView receives a QMouseEvent of type
- MousePress as a response to a user click, the view sends a
- QGraphicsSceneMouseEvent of type GraphicsSceneMousePress to the
- underlying QGraphicsScene through its
- \l{QGraphicsScene::}{mousePressEvent()} function. The default
- QGraphicsScene::mousePressEvent() implementation determines which
- item was clicked and forwards the event to
- QGraphicsItem::mousePressEvent().
-
- \omit ### Beskrive widget() \endomit
-
- Subclasses such as QGraphicsSceneMouseEvent and
- QGraphicsSceneContextMenuEvent provide the coordinates from the
- original QEvent in screen, scene, and item coordinates (see
- \l{QGraphicsSceneMouseEvent::}{screenPos()},
- \l{QGraphicsSceneMouseEvent::}{scenePos()}, and
- \l{QGraphicsSceneMouseEvent::}{pos()}). The item coordinates are
- set by the QGraphicsScene before it forwards the event to the
- event to a QGraphicsItem. The mouse events also add the
- possibility to retrieve the coordinates from the last event
- received by the view (see
- \l{QGraphicsSceneMouseEvent::}{lastScreenPos()},
- \l{QGraphicsSceneMouseEvent::}{lastScenePos()}, and
- \l{QGraphicsSceneMouseEvent::}{lastPos()}).
-
- \sa QEvent
-*/
-
-/*!
- \class QGraphicsSceneMouseEvent
- \brief The QGraphicsSceneMouseEvent class provides mouse events
- in the graphics view framework.
- \since 4.2
- \ingroup graphicsview-api
-
- When a QGraphicsView receives a QMouseEvent, it translates it to a
- QGraphicsSceneMouseEvent. The event is then forwarded to the
- QGraphicsScene associated with the view. If the event is not
- handled by the scene, the view may use it, e.g., for the
- \l{QGraphicsView::}{DragMode}.
-
- In addition to containing the item, scene, and screen coordinates
- of the event (as pos(), scenePos(), and screenPos()), mouse
- events also contain the coordinates of the previous mouse
- event received by the view. These can be retrieved with
- lastPos(), lastScreenPos(), and lastScenePos().
-
- \sa QGraphicsSceneContextMenuEvent,
- QGraphicsSceneHoverEvent, QGraphicsSceneWheelEvent,
- QMouseEvent
-*/
-
-/*!
- \class QGraphicsSceneWheelEvent
- \brief The QGraphicsSceneWheelEvent class provides wheel events
- in the graphics view framework.
- \brief The QGraphicsSceneWheelEvent class provides wheel events in the
- graphics view framework.
- \since 4.2
- \ingroup graphicsview-api
-
- \l{QWheelEvent}{QWheelEvent}s received by a QGraphicsView are translated
- into QGraphicsSceneWheelEvents; it translates the QWheelEvent::globalPos()
- into item, scene, and screen coordinates (pos(), scenePos(), and
- screenPos()).
-
- \sa QGraphicsSceneMouseEvent, QGraphicsSceneContextMenuEvent,
- QGraphicsSceneHoverEvent, QWheelEvent
-*/
-
-/*!
- \class QGraphicsSceneContextMenuEvent
- \brief The QGraphicsSceneContextMenuEvent class provides context
- menu events in the graphics view framework.
- \since 4.2
- \ingroup graphicsview-api
-
- A QContextMenuEvent received by a QGraphicsView is translated
- into a QGraphicsSceneContextMenuEvent. The
- QContextMenuEvent::globalPos() is translated into item, scene, and
- screen coordinates (pos(), scenePos(), and screenPos()).
-
- \sa QGraphicsSceneMouseEvent, QGraphicsSceneWheelEvent,
- QContextMenuEvent
-*/
-
-/*!
- \enum QGraphicsSceneContextMenuEvent::Reason
-
- This enum describes the reason why the context event was sent.
-
- \value Mouse The mouse caused the event to be sent. On most
- platforms, this means the right mouse button was clicked.
-
- \value Keyboard The keyboard caused this event to be sent. On
- Windows and Mac OS X, this means the menu button was pressed.
-
- \value Other The event was sent by some other means (i.e. not
- by the mouse or keyboard).
-*/
-
-/*!
- \class QGraphicsSceneHoverEvent
- \brief The QGraphicsSceneHoverEvent class provides hover events
- in the graphics view framework.
- \since 4.2
- \ingroup graphicsview-api
-
- When a QGraphicsView receives a QHoverEvent event, it translates
- it into QGraphicsSceneHoverEvent. The event is then forwarded to
- the QGraphicsScene associated with the view.
-
- \sa QGraphicsSceneMouseEvent, QGraphicsSceneContextMenuEvent,
- QGraphicsSceneWheelEvent, QHoverEvent
-*/
-
-/*!
- \class QGraphicsSceneHelpEvent
- \brief The QGraphicsSceneHelpEvent class provides events when a
- tooltip is requested.
- \since 4.2
- \ingroup graphicsview-api
-
- When a QGraphicsView receives a QEvent of type
- QEvent::ToolTip, it creates a QGraphicsSceneHelpEvent, which is
- forwarded to the scene. You can set a tooltip on a QGraphicsItem
- with \l{QGraphicsItem::}{setToolTip()}; by default QGraphicsScene
- displays the tooltip of the QGraphicsItem with the highest
- z-value (i.e, the top-most item) under the mouse position.
-
- QGraphicsView does not forward events when
- \l{QWhatsThis}{"What's This"} and \l{QStatusTipEvent}{status tip}
- help is requested. If you need this, you can reimplement
- QGraphicsView::viewportEvent() and forward QStatusTipEvent
- events and \l{QEvent}{QEvents} of type QEvent::WhatsThis to the
- scene.
-
- \sa QEvent
-*/
-
-/*!
- \class QGraphicsSceneDragDropEvent
- \brief The QGraphicsSceneDragDropEvent class provides events for
- drag and drop in the graphics view framework.
- \since 4.2
- \ingroup graphicsview-api
-
- QGraphicsView inherits the drag and drop functionality provided
- by QWidget. When it receives a drag and drop event, it translates
- it to a QGraphicsSceneDragDropEvent.
-
- QGraphicsSceneDragDropEvent stores events of type
- GraphicsSceneDragEnter, GraphicsSceneDragLeave,
- GraphicsSceneDragMove, or GraphicsSceneDrop.
-
- QGraphicsSceneDragDropEvent contains the position of the mouse
- cursor in both item, scene, and screen coordinates; this can be
- retrieved with pos(), scenePos(), and screenPos().
-
- The scene sends the event to the first QGraphicsItem under the
- mouse cursor that accepts drops; a graphics item is set to accept
- drops with \l{QGraphicsItem::}{setAcceptDrops()}.
-*/
-
-/*!
- \class QGraphicsSceneResizeEvent
- \brief The QGraphicsSceneResizeEvent class provides events for widget
- resizing in the graphics view framework.
- \since 4.4
- \ingroup graphicsview-api
-
- A QGraphicsWidget sends itself a QGraphicsSceneResizeEvent immediately
- when its geometry changes.
-
- It's similar to QResizeEvent, but its sizes, oldSize() and newSize(), use
- QSizeF instead of QSize.
-
- \sa QGraphicsWidget::setGeometry(), QGraphicsWidget::resize()
-*/
-
-/*!
- \class QGraphicsSceneMoveEvent
- \brief The QGraphicsSceneMoveEvent class provides events for widget
- moving in the graphics view framework.
- \since 4.4
- \ingroup graphicsview-api
-
- A QGraphicsWidget sends itself a QGraphicsSceneMoveEvent immediately when
- its local position changes. The delivery is implemented as part of
- QGraphicsItem::itemChange().
-
- It's similar to QMoveEvent, but its positions, oldPos() and newPos(), use
- QPointF instead of QPoint.
-
- \sa QGraphicsItem::setPos(), QGraphicsItem::ItemPositionChange,
- QGraphicsItem::ItemPositionHasChanged
-*/
-
-#include "qgraphicssceneevent.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#ifndef QT_NO_DEBUG
-#include <QtCore/qdebug.h>
-#endif
-#include <QtCore/qmap.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qsize.h>
-#include <QtCore/qstring.h>
-#include "qgraphicsview.h"
-#include "qgraphicsitem.h"
-#include <QtGui/qgesture.h>
-#include <private/qevent_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsSceneEventPrivate
-{
-public:
- inline QGraphicsSceneEventPrivate()
- : widget(0),
- q_ptr(0)
- { }
-
- inline virtual ~QGraphicsSceneEventPrivate()
- { }
-
- QWidget *widget;
- QGraphicsSceneEvent *q_ptr;
-};
-
-/*!
- \internal
-
- Constructs a generic graphics scene event of the specified \a type.
-*/
-QGraphicsSceneEvent::QGraphicsSceneEvent(Type type)
- : QEvent(type), d_ptr(new QGraphicsSceneEventPrivate)
-{
- d_ptr->q_ptr = this;
-}
-
-/*!
- \internal
-
- Constructs a generic graphics scene event.
-*/
-QGraphicsSceneEvent::QGraphicsSceneEvent(QGraphicsSceneEventPrivate &dd, Type type)
- : QEvent(type), d_ptr(&dd)
-{
- d_ptr->q_ptr = this;
-}
-
-/*!
- Destroys the event.
-*/
-QGraphicsSceneEvent::~QGraphicsSceneEvent()
-{
-}
-
-/*!
- Returns the widget where the event originated, or 0 if the event
- originates from another application.
-*/
-QWidget *QGraphicsSceneEvent::widget() const
-{
- return d_ptr->widget;
-}
-
-/*!
- \internal
-
- Sets the \a widget related to this event.
-
- \sa widget()
-*/
-void QGraphicsSceneEvent::setWidget(QWidget *widget)
-{
- d_ptr->widget = widget;
-}
-
-class QGraphicsSceneMouseEventPrivate : public QGraphicsSceneEventPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneMouseEvent)
-public:
- inline QGraphicsSceneMouseEventPrivate()
- : button(Qt::NoButton),
- buttons(0), modifiers(0)
- { }
-
- QPointF pos;
- QPointF scenePos;
- QPoint screenPos;
- QPointF lastPos;
- QPointF lastScenePos;
- QPoint lastScreenPos;
- QMap<Qt::MouseButton, QPointF> buttonDownPos;
- QMap<Qt::MouseButton, QPointF> buttonDownScenePos;
- QMap<Qt::MouseButton, QPoint> buttonDownScreenPos;
- Qt::MouseButton button;
- Qt::MouseButtons buttons;
- Qt::KeyboardModifiers modifiers;
-};
-
-/*!
- \internal
-
- Constructs a generic graphics scene mouse event of the specified \a type.
-*/
-QGraphicsSceneMouseEvent::QGraphicsSceneMouseEvent(Type type)
- : QGraphicsSceneEvent(*new QGraphicsSceneMouseEventPrivate, type)
-{
-}
-
-/*!
- Destroys the event.
-*/
-QGraphicsSceneMouseEvent::~QGraphicsSceneMouseEvent()
-{
-}
-
-/*!
- Returns the mouse cursor position in item coordinates.
-
- \sa scenePos(), screenPos(), lastPos()
-*/
-QPointF QGraphicsSceneMouseEvent::pos() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->pos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->pos = pos;
-}
-
-/*!
- Returns the mouse cursor position in scene coordinates.
-
- \sa pos(), screenPos(), lastScenePos()
-*/
-QPointF QGraphicsSceneMouseEvent::scenePos() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->scenePos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->scenePos = pos;
-}
-
-/*!
- Returns the mouse cursor position in screen coordinates.
-
- \sa pos(), scenePos(), lastScreenPos()
-*/
-QPoint QGraphicsSceneMouseEvent::screenPos() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->screenPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->screenPos = pos;
-}
-
-/*!
- Returns the mouse cursor position in item coordinates where the specified
- \a button was clicked.
-
- \sa buttonDownScenePos(), buttonDownScreenPos(), pos()
-*/
-QPointF QGraphicsSceneMouseEvent::buttonDownPos(Qt::MouseButton button) const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->buttonDownPos.value(button);
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setButtonDownPos(Qt::MouseButton button, const QPointF &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->buttonDownPos.insert(button, pos);
-}
-
-/*!
- Returns the mouse cursor position in scene coordinates where the
- specified \a button was clicked.
-
- \sa buttonDownPos(), buttonDownScreenPos(), scenePos()
-*/
-QPointF QGraphicsSceneMouseEvent::buttonDownScenePos(Qt::MouseButton button) const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->buttonDownScenePos.value(button);
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setButtonDownScenePos(Qt::MouseButton button, const QPointF &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->buttonDownScenePos.insert(button, pos);
-}
-
-/*!
- Returns the mouse cursor position in screen coordinates where the
- specified \a button was clicked.
-
- \sa screenPos(), buttonDownPos(), buttonDownScenePos()
-*/
-QPoint QGraphicsSceneMouseEvent::buttonDownScreenPos(Qt::MouseButton button) const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->buttonDownScreenPos.value(button);
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setButtonDownScreenPos(Qt::MouseButton button, const QPoint &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->buttonDownScreenPos.insert(button, pos);
-}
-
-/*!
- Returns the last recorded mouse cursor position in item
- coordinates.
-
- \sa lastScenePos(), lastScreenPos(), pos()
-*/
-QPointF QGraphicsSceneMouseEvent::lastPos() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->lastPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setLastPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->lastPos = pos;
-}
-
-/*!
- Returns the last recorded mouse cursor position in scene
- coordinates. The last recorded position is the position of
- the previous mouse event received by the view that created
- the event.
-
- \sa lastPos(), lastScreenPos(), scenePos()
-*/
-QPointF QGraphicsSceneMouseEvent::lastScenePos() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->lastScenePos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setLastScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->lastScenePos = pos;
-}
-
-/*!
- Returns the last recorded mouse cursor position in screen
- coordinates. The last recorded position is the position of
- the previous mouse event received by the view that created
- the event.
-
- \sa lastPos(), lastScenePos(), screenPos()
-*/
-QPoint QGraphicsSceneMouseEvent::lastScreenPos() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->lastScreenPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setLastScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->lastScreenPos = pos;
-}
-
-/*!
- Returns the combination of mouse buttons that were pressed at the
- time the event was sent.
-
- \sa button(), modifiers()
-*/
-Qt::MouseButtons QGraphicsSceneMouseEvent::buttons() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->buttons;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setButtons(Qt::MouseButtons buttons)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->buttons = buttons;
-}
-
-/*!
- Returns the mouse button (if any) that caused the event.
-
- \sa buttons(), modifiers()
-*/
-Qt::MouseButton QGraphicsSceneMouseEvent::button() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->button;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setButton(Qt::MouseButton button)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->button = button;
-}
-
-/*!
- Returns the keyboard modifiers in use at the time the event was
- sent.
-
- \sa buttons(), button()
-*/
-Qt::KeyboardModifiers QGraphicsSceneMouseEvent::modifiers() const
-{
- Q_D(const QGraphicsSceneMouseEvent);
- return d->modifiers;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMouseEvent::setModifiers(Qt::KeyboardModifiers modifiers)
-{
- Q_D(QGraphicsSceneMouseEvent);
- d->modifiers = modifiers;
-}
-
-class QGraphicsSceneWheelEventPrivate : public QGraphicsSceneEventPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneWheelEvent)
-public:
- inline QGraphicsSceneWheelEventPrivate()
- : buttons(0), modifiers(0), delta(0), orientation(Qt::Horizontal)
- { }
-
- QPointF pos;
- QPointF scenePos;
- QPoint screenPos;
- Qt::MouseButtons buttons;
- Qt::KeyboardModifiers modifiers;
- int delta;
- Qt::Orientation orientation;
-};
-
-/*!
- \internal
-
- Constructs a QGraphicsSceneWheelEvent of type \a type, which
- is always QEvent::GraphicsSceneWheel.
-*/
-QGraphicsSceneWheelEvent::QGraphicsSceneWheelEvent(Type type)
- : QGraphicsSceneEvent(*new QGraphicsSceneWheelEventPrivate, type)
-{
-}
-
-/*!
- Destroys the QGraphicsSceneWheelEvent.
-*/
-QGraphicsSceneWheelEvent::~QGraphicsSceneWheelEvent()
-{
-}
-
-/*!
- Returns the position of the cursor in item coordinates when the
- wheel event occurred.
-
- \sa scenePos(), screenPos()
-*/
-QPointF QGraphicsSceneWheelEvent::pos() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->pos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->pos = pos;
-}
-
-/*!
- Returns the position of the cursor in scene coordinates when the wheel
- event occurred.
-
- \sa pos(), screenPos()
-*/
-QPointF QGraphicsSceneWheelEvent::scenePos() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->scenePos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->scenePos = pos;
-}
-
-/*!
- Returns the position of the cursor in screen coordinates when the wheel
- event occurred.
-
- \sa pos(), scenePos()
-*/
-QPoint QGraphicsSceneWheelEvent::screenPos() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->screenPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->screenPos = pos;
-}
-
-/*!
- Returns the mouse buttons that were pressed when the wheel event occurred.
-
- \sa modifiers()
-*/
-Qt::MouseButtons QGraphicsSceneWheelEvent::buttons() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->buttons;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setButtons(Qt::MouseButtons buttons)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->buttons = buttons;
-}
-
-/*!
- Returns the keyboard modifiers that were active when the wheel event
- occurred.
-
- \sa buttons()
-*/
-Qt::KeyboardModifiers QGraphicsSceneWheelEvent::modifiers() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->modifiers;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setModifiers(Qt::KeyboardModifiers modifiers)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->modifiers = modifiers;
-}
-
-/*!
- Returns the distance that the wheel is rotated, in eighths (1/8s)
- of a degree. A positive value indicates that the wheel was
- rotated forwards away from the user; a negative value indicates
- that the wheel was rotated backwards toward the user.
-
- Most mouse types work in steps of 15 degrees, in which case the delta
- value is a multiple of 120 (== 15 * 8).
-*/
-int QGraphicsSceneWheelEvent::delta() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->delta;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setDelta(int delta)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->delta = delta;
-}
-
-/*!
- Returns the wheel orientation.
-*/
-Qt::Orientation QGraphicsSceneWheelEvent::orientation() const
-{
- Q_D(const QGraphicsSceneWheelEvent);
- return d->orientation;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneWheelEvent::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QGraphicsSceneWheelEvent);
- d->orientation = orientation;
-}
-
-class QGraphicsSceneContextMenuEventPrivate : public QGraphicsSceneEventPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneContextMenuEvent)
- public:
- inline QGraphicsSceneContextMenuEventPrivate()
- : modifiers(0), reason(QGraphicsSceneContextMenuEvent::Other)
- { }
-
- QPointF pos;
- QPointF scenePos;
- QPoint screenPos;
- Qt::KeyboardModifiers modifiers;
- QGraphicsSceneContextMenuEvent::Reason reason;
-};
-
-/*!
- \internal
-
- Constructs a graphics scene context menu event of the specified \a type.
-*/
-QGraphicsSceneContextMenuEvent::QGraphicsSceneContextMenuEvent(Type type)
- : QGraphicsSceneEvent(*new QGraphicsSceneContextMenuEventPrivate, type)
-{
-}
-
-/*!
- Destroys the event.
-*/
-QGraphicsSceneContextMenuEvent::~QGraphicsSceneContextMenuEvent()
-{
-}
-
-/*!
- Returns the position of the mouse cursor in item coordinates at the moment
- the context menu was requested.
-
- \sa scenePos(), screenPos()
-*/
-QPointF QGraphicsSceneContextMenuEvent::pos() const
-{
- Q_D(const QGraphicsSceneContextMenuEvent);
- return d->pos;
-}
-
-/*!
- \fn void QGraphicsSceneContextMenuEvent::setPos(const QPointF &point)
- \internal
-
- Sets the position associated with the context menu to the given \a point
- in item coordinates.
-*/
-void QGraphicsSceneContextMenuEvent::setPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneContextMenuEvent);
- d->pos = pos;
-}
-
-/*!
- Returns the position of the mouse cursor in scene coordinates at the moment the
- the context menu was requested.
-
- \sa pos(), screenPos()
-*/
-QPointF QGraphicsSceneContextMenuEvent::scenePos() const
-{
- Q_D(const QGraphicsSceneContextMenuEvent);
- return d->scenePos;
-}
-
-/*!
- \fn void QGraphicsSceneContextMenuEvent::setScenePos(const QPointF &point)
- \internal
-
- Sets the position associated with the context menu to the given \a point
- in scene coordinates.
-*/
-void QGraphicsSceneContextMenuEvent::setScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneContextMenuEvent);
- d->scenePos = pos;
-}
-
-/*!
- Returns the position of the mouse cursor in screen coordinates at the moment the
- the context menu was requested.
-
- \sa pos(), scenePos()
-*/
-QPoint QGraphicsSceneContextMenuEvent::screenPos() const
-{
- Q_D(const QGraphicsSceneContextMenuEvent);
- return d->screenPos;
-}
-
-/*!
- \fn void QGraphicsSceneContextMenuEvent::setScreenPos(const QPoint &point)
- \internal
-
- Sets the position associated with the context menu to the given \a point
- in screen coordinates.
-*/
-void QGraphicsSceneContextMenuEvent::setScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneContextMenuEvent);
- d->screenPos = pos;
-}
-
-/*!
- Returns the keyboard modifiers in use when the context menu was requested.
-*/
-Qt::KeyboardModifiers QGraphicsSceneContextMenuEvent::modifiers() const
-{
- Q_D(const QGraphicsSceneContextMenuEvent);
- return d->modifiers;
-}
-
-/*!
- \internal
-
- Sets the keyboard modifiers associated with the context menu to the \a
- modifiers specified.
-*/
-void QGraphicsSceneContextMenuEvent::setModifiers(Qt::KeyboardModifiers modifiers)
-{
- Q_D(QGraphicsSceneContextMenuEvent);
- d->modifiers = modifiers;
-}
-
-/*!
- Returns the reason for the context menu event.
-
- \sa QGraphicsSceneContextMenuEvent::Reason
-*/
-QGraphicsSceneContextMenuEvent::Reason QGraphicsSceneContextMenuEvent::reason() const
-{
- Q_D(const QGraphicsSceneContextMenuEvent);
- return d->reason;
-}
-
-/*!
- \internal
- Sets the reason for the context menu event to \a reason.
-
- \sa reason()
-*/
-void QGraphicsSceneContextMenuEvent::setReason(Reason reason)
-{
- Q_D(QGraphicsSceneContextMenuEvent);
- d->reason = reason;
-}
-
-class QGraphicsSceneHoverEventPrivate : public QGraphicsSceneEventPrivate
-{
-public:
- QPointF pos;
- QPointF scenePos;
- QPoint screenPos;
- QPointF lastPos;
- QPointF lastScenePos;
- QPoint lastScreenPos;
- Qt::KeyboardModifiers modifiers;
-};
-
-/*!
- \internal
-
- Constructs a graphics scene hover event of the specified \a type.
-*/
-QGraphicsSceneHoverEvent::QGraphicsSceneHoverEvent(Type type)
- : QGraphicsSceneEvent(*new QGraphicsSceneHoverEventPrivate, type)
-{
-}
-
-/*!
- Destroys the event.
-*/
-QGraphicsSceneHoverEvent::~QGraphicsSceneHoverEvent()
-{
-}
-
-/*!
- Returns the position of the mouse cursor in item coordinates at the moment
- the hover event was sent.
-
- \sa scenePos(), screenPos()
-*/
-QPointF QGraphicsSceneHoverEvent::pos() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->pos;
-}
-
-/*!
- \fn void QGraphicsSceneHoverEvent::setPos(const QPointF &point)
- \internal
-
- Sets the position associated with the hover event to the given \a point in
- item coordinates.
-*/
-void QGraphicsSceneHoverEvent::setPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->pos = pos;
-}
-
-/*!
- Returns the position of the mouse cursor in scene coordinates at the
- moment the hover event was sent.
-
- \sa pos(), screenPos()
-*/
-QPointF QGraphicsSceneHoverEvent::scenePos() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->scenePos;
-}
-
-/*!
- \fn void QGraphicsSceneHoverEvent::setScenePos(const QPointF &point)
- \internal
-
- Sets the position associated with the hover event to the given \a point in
- scene coordinates.
-*/
-void QGraphicsSceneHoverEvent::setScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->scenePos = pos;
-}
-
-/*!
- Returns the position of the mouse cursor in screen coordinates at the
- moment the hover event was sent.
-
- \sa pos(), scenePos()
-*/
-QPoint QGraphicsSceneHoverEvent::screenPos() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->screenPos;
-}
-
-/*!
- \fn void QGraphicsSceneHoverEvent::setScreenPos(const QPoint &point)
- \internal
-
- Sets the position associated with the hover event to the given \a point in
- screen coordinates.
-*/
-void QGraphicsSceneHoverEvent::setScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->screenPos = pos;
-}
-
-/*!
- \since 4.4
-
- Returns the last recorded mouse cursor position in item coordinates.
-
- \sa lastScenePos(), lastScreenPos(), pos()
-*/
-QPointF QGraphicsSceneHoverEvent::lastPos() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->lastPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneHoverEvent::setLastPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->lastPos = pos;
-}
-
-/*!
- \since 4.4
-
- Returns the last recorded, the scene coordinates of the previous mouse or
- hover event received by the view, that created the event mouse cursor
- position in scene coordinates.
-
- \sa lastPos(), lastScreenPos(), scenePos()
-*/
-QPointF QGraphicsSceneHoverEvent::lastScenePos() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->lastScenePos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneHoverEvent::setLastScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->lastScenePos = pos;
-}
-
-/*!
- \since 4.4
-
- Returns the last recorded mouse cursor position in screen coordinates. The
- last recorded position is the position of the previous mouse or hover
- event received by the view that created the event.
-
- \sa lastPos(), lastScenePos(), screenPos()
-*/
-QPoint QGraphicsSceneHoverEvent::lastScreenPos() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->lastScreenPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneHoverEvent::setLastScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->lastScreenPos = pos;
-}
-
-/*!
- \since 4.4
-
- Returns the keyboard modifiers at the moment the hover event was sent.
-*/
-Qt::KeyboardModifiers QGraphicsSceneHoverEvent::modifiers() const
-{
- Q_D(const QGraphicsSceneHoverEvent);
- return d->modifiers;
-}
-
-/*!
- \fn void QGraphicsSceneHoverEvent::setModifiers(Qt::KeyboardModifiers modifiers)
- \internal
-
- Sets the modifiers for the current hover event to \a modifiers.
-*/
-void QGraphicsSceneHoverEvent::setModifiers(Qt::KeyboardModifiers modifiers)
-{
- Q_D(QGraphicsSceneHoverEvent);
- d->modifiers = modifiers;
-}
-
-class QGraphicsSceneHelpEventPrivate : public QGraphicsSceneEventPrivate
-{
-public:
- QPointF scenePos;
- QPoint screenPos;
-};
-
-/*!
- \internal
-
- Constructs a graphics scene help event of the specified \a type.
-*/
-QGraphicsSceneHelpEvent::QGraphicsSceneHelpEvent(Type type)
- : QGraphicsSceneEvent(*new QGraphicsSceneHelpEventPrivate, type)
-{
-}
-
-/*!
- Destroys the event.
-*/
-QGraphicsSceneHelpEvent::~QGraphicsSceneHelpEvent()
-{
-}
-
-/*!
- Returns the position of the mouse cursor in scene coordinates at the
- moment the help event was sent.
-
- \sa screenPos()
-*/
-QPointF QGraphicsSceneHelpEvent::scenePos() const
-{
- Q_D(const QGraphicsSceneHelpEvent);
- return d->scenePos;
-}
-
-/*!
- \fn void QGraphicsSceneHelpEvent::setScenePos(const QPointF &point)
- \internal
-
- Sets the position associated with the context menu to the given \a point
- in scene coordinates.
-*/
-void QGraphicsSceneHelpEvent::setScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneHelpEvent);
- d->scenePos = pos;
-}
-
-/*!
- Returns the position of the mouse cursor in screen coordinates at the
- moment the help event was sent.
-
- \sa scenePos()
-*/
-QPoint QGraphicsSceneHelpEvent::screenPos() const
-{
- Q_D(const QGraphicsSceneHelpEvent);
- return d->screenPos;
-}
-
-/*!
- \fn void QGraphicsSceneHelpEvent::setScreenPos(const QPoint &point)
- \internal
-
- Sets the position associated with the context menu to the given \a point
- in screen coordinates.
-*/
-void QGraphicsSceneHelpEvent::setScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneHelpEvent);
- d->screenPos = pos;
-}
-
-class QGraphicsSceneDragDropEventPrivate : public QGraphicsSceneEventPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneDragDropEvent)
-public:
- inline QGraphicsSceneDragDropEventPrivate()
- : source(0), mimeData(0)
- { }
-
- QPointF pos;
- QPointF scenePos;
- QPoint screenPos;
- Qt::MouseButtons buttons;
- Qt::KeyboardModifiers modifiers;
- Qt::DropActions possibleActions;
- Qt::DropAction proposedAction;
- Qt::DropAction dropAction;
- QWidget *source;
- const QMimeData *mimeData;
-};
-
-/*!
- \internal
-
- Constructs a new QGraphicsSceneDragDropEvent of the
- specified \a type. The type can be either
- QEvent::GraphicsSceneDragEnter, QEvent::GraphicsSceneDragLeave,
- QEvent::GraphicsSceneDragMove, or QEvent::GraphicsSceneDrop.
-*/
-QGraphicsSceneDragDropEvent::QGraphicsSceneDragDropEvent(Type type)
- : QGraphicsSceneEvent(*new QGraphicsSceneDragDropEventPrivate, type)
-{
-}
-
-/*!
- Destroys the object.
-*/
-QGraphicsSceneDragDropEvent::~QGraphicsSceneDragDropEvent()
-{
-}
-
-/*!
- Returns the mouse position of the event relative to the
- view that sent the event.
-
- \sa QGraphicsView, screenPos(), scenePos()
-*/
-QPointF QGraphicsSceneDragDropEvent::pos() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->pos;
-}
-
-/*!
- \internal
- Sets the position of the mouse to \a pos; this should be
- relative to the widget that generated the event, which normally
- is a QGraphicsView.
-
- \sa pos(), setScenePos(), setScreenPos()
-*/
-
-void QGraphicsSceneDragDropEvent::setPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->pos = pos;
-}
-
-/*!
- Returns the position of the mouse in scene coordinates.
-
- \sa pos(), screenPos()
-*/
-QPointF QGraphicsSceneDragDropEvent::scenePos() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->scenePos;
-}
-
-/*!
- \internal
- Sets the scene position of the mouse to \a pos.
-
- \sa scenePos(), setScreenPos(), setPos()
-*/
-void QGraphicsSceneDragDropEvent::setScenePos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->scenePos = pos;
-}
-
-/*!
- Returns the position of the mouse relative to the screen.
-
- \sa pos(), scenePos()
-*/
-QPoint QGraphicsSceneDragDropEvent::screenPos() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->screenPos;
-}
-
-/*!
- \internal
- Sets the mouse position relative to the screen to \a pos.
-
- \sa screenPos(), setScenePos(), setPos()
-*/
-void QGraphicsSceneDragDropEvent::setScreenPos(const QPoint &pos)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->screenPos = pos;
-}
-
-/*!
- Returns a Qt::MouseButtons value indicating which buttons
- were pressed on the mouse when this mouse event was
- generated.
-
- \sa Qt::MouseButtons
-*/
-Qt::MouseButtons QGraphicsSceneDragDropEvent::buttons() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->buttons;
-}
-
-/*!
- \internal
- Sets the mouse buttons that were pressed when the event was
- created to \a buttons.
-
- \sa Qt::MouseButtons, buttons()
-*/
-void QGraphicsSceneDragDropEvent::setButtons(Qt::MouseButtons buttons)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->buttons = buttons;
-}
-
-/*!
- Returns the keyboard modifiers that were pressed when the drag
- and drop event was created.
-
- \sa Qt::KeyboardModifiers
-*/
-Qt::KeyboardModifiers QGraphicsSceneDragDropEvent::modifiers() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->modifiers;
-}
-
-/*!
- \internal
- Sets the keyboard modifiers that were pressed when the event
- was created to \a modifiers.
-
- \sa Qt::KeyboardModifiers, modifiers()
-*/
-
-void QGraphicsSceneDragDropEvent::setModifiers(Qt::KeyboardModifiers modifiers)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->modifiers = modifiers;
-}
-
-/*!
- Returns the possible drop actions that the drag and
- drop can result in.
-
- \sa Qt::DropActions
-*/
-
-Qt::DropActions QGraphicsSceneDragDropEvent::possibleActions() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->possibleActions;
-}
-
-/*!
- \internal
- Sets the possible drop actions that the drag can
- result in to \a actions.
-
- \sa Qt::DropActions, possibleActions()
-*/
-void QGraphicsSceneDragDropEvent::setPossibleActions(Qt::DropActions actions)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->possibleActions = actions;
-}
-
-/*!
- Returns the drop action that is proposed, i.e., preferred.
- The action must be one of the possible actions as defined by
- \c possibleActions().
-
- \sa Qt::DropAction, possibleActions()
-*/
-
-Qt::DropAction QGraphicsSceneDragDropEvent::proposedAction() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->proposedAction;
-}
-
-/*!
- \internal
- Sets the proposed action to \a action. The proposed action
- is a Qt::DropAction that is one of the possible actions as
- given by \c possibleActions().
-
- \sa proposedAction(), Qt::DropAction, possibleActions()
-*/
-
-void QGraphicsSceneDragDropEvent::setProposedAction(Qt::DropAction action)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->proposedAction = action;
-}
-
-/*!
- Sets the proposed action as accepted, i.e, the drop action
- is set to the proposed action. This is equal to:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp 0
-
- When using this function, one should not call \c accept().
-
- \sa dropAction(), setDropAction(), proposedAction()
-*/
-
-void QGraphicsSceneDragDropEvent::acceptProposedAction()
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->dropAction = d->proposedAction;
-}
-
-/*!
- Returns the action that was performed in this drag and drop.
- This should be set by the receiver of the drop and is
- returned by QDrag::exec().
-
- \sa setDropAction(), acceptProposedAction()
-*/
-
-Qt::DropAction QGraphicsSceneDragDropEvent::dropAction() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->dropAction;
-}
-
-/*!
- This function lets the receiver of the drop set the drop
- action that was performed to \a action, which should be one
- of the
- \l{QGraphicsSceneDragDropEvent::possibleActions()}{possible
- actions}. Call \c accept() in stead of \c
- acceptProposedAction() if you use this function.
-
- \sa dropAction(), accept(), possibleActions()
-*/
-void QGraphicsSceneDragDropEvent::setDropAction(Qt::DropAction action)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->dropAction = action;
-}
-
-/*!
- This function returns the QGraphicsView that created the
- QGraphicsSceneDragDropEvent.
-*/
-QWidget *QGraphicsSceneDragDropEvent::source() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->source;
-}
-
-/*!
- \internal
- This function set the source widget, i.e., the widget that
- created the drop event, to \a source.
-*/
-void QGraphicsSceneDragDropEvent::setSource(QWidget *source)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->source = source;
-}
-
-/*!
- This function returns the MIME data of the event.
-*/
-const QMimeData *QGraphicsSceneDragDropEvent::mimeData() const
-{
- Q_D(const QGraphicsSceneDragDropEvent);
- return d->mimeData;
-}
-
-/*!
- \internal
- This function sets the MIME data for the event.
-*/
-void QGraphicsSceneDragDropEvent::setMimeData(const QMimeData *data)
-{
- Q_D(QGraphicsSceneDragDropEvent);
- d->mimeData = data;
-}
-
-class QGraphicsSceneResizeEventPrivate : public QGraphicsSceneEventPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneResizeEvent)
-public:
- inline QGraphicsSceneResizeEventPrivate()
- { }
-
- QSizeF oldSize;
- QSizeF newSize;
-};
-
-/*!
- Constructs a QGraphicsSceneResizeEvent.
-*/
-QGraphicsSceneResizeEvent::QGraphicsSceneResizeEvent()
- : QGraphicsSceneEvent(*new QGraphicsSceneResizeEventPrivate, QEvent::GraphicsSceneResize)
-{
-}
-
-/*!
- Destroys the QGraphicsSceneResizeEvent.
-*/
-QGraphicsSceneResizeEvent::~QGraphicsSceneResizeEvent()
-{
-}
-
-/*!
- Returns the old size (i.e., the size immediately before the widget was
- resized).
-
- \sa newSize(), QGraphicsWidget::resize()
-*/
-QSizeF QGraphicsSceneResizeEvent::oldSize() const
-{
- Q_D(const QGraphicsSceneResizeEvent);
- return d->oldSize;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneResizeEvent::setOldSize(const QSizeF &size)
-{
- Q_D(QGraphicsSceneResizeEvent);
- d->oldSize = size;
-}
-
-/*!
- Returns the new size (i.e., the current size).
-
- \sa oldSize(), QGraphicsWidget::resize()
-*/
-QSizeF QGraphicsSceneResizeEvent::newSize() const
-{
- Q_D(const QGraphicsSceneResizeEvent);
- return d->newSize;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneResizeEvent::setNewSize(const QSizeF &size)
-{
- Q_D(QGraphicsSceneResizeEvent);
- d->newSize = size;
-}
-
-class QGraphicsSceneMoveEventPrivate : public QGraphicsSceneEventPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneMoveEvent)
-public:
- inline QGraphicsSceneMoveEventPrivate()
- { }
-
- QPointF oldPos;
- QPointF newPos;
-};
-
-/*!
- Constructs a QGraphicsSceneMoveEvent.
-*/
-QGraphicsSceneMoveEvent::QGraphicsSceneMoveEvent()
- : QGraphicsSceneEvent(*new QGraphicsSceneMoveEventPrivate, QEvent::GraphicsSceneMove)
-{
-}
-
-/*!
- Destroys the QGraphicsSceneMoveEvent.
-*/
-QGraphicsSceneMoveEvent::~QGraphicsSceneMoveEvent()
-{
-}
-
-/*!
- Returns the old position (i.e., the position immediately before the widget
- was moved).
-
- \sa newPos(), QGraphicsItem::setPos()
-*/
-QPointF QGraphicsSceneMoveEvent::oldPos() const
-{
- Q_D(const QGraphicsSceneMoveEvent);
- return d->oldPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMoveEvent::setOldPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneMoveEvent);
- d->oldPos = pos;
-}
-
-/*!
- Returns the new position (i.e., the current position).
-
- \sa oldPos(), QGraphicsItem::setPos()
-*/
-QPointF QGraphicsSceneMoveEvent::newPos() const
-{
- Q_D(const QGraphicsSceneMoveEvent);
- return d->newPos;
-}
-
-/*!
- \internal
-*/
-void QGraphicsSceneMoveEvent::setNewPos(const QPointF &pos)
-{
- Q_D(QGraphicsSceneMoveEvent);
- d->newPos = pos;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicssceneevent.h b/src/gui/graphicsview/qgraphicssceneevent.h
deleted file mode 100644
index afaa33c9ce..0000000000
--- a/src/gui/graphicsview/qgraphicssceneevent.h
+++ /dev/null
@@ -1,326 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSSCENEEVENT_H
-#define QGRAPHICSSCENEEVENT_H
-
-#include <QtCore/qcoreevent.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qscopedpointer.h>
-#include <QtCore/qrect.h>
-#include <QtGui/qpolygon.h>
-#include <QtCore/qset.h>
-#include <QtCore/qhash.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QMimeData;
-class QPointF;
-class QSizeF;
-class QWidget;
-
-class QGraphicsSceneEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneEvent : public QEvent
-{
-public:
- QGraphicsSceneEvent(Type type);
- ~QGraphicsSceneEvent();
-
- QWidget *widget() const;
- void setWidget(QWidget *widget);
-
-protected:
- QGraphicsSceneEvent(QGraphicsSceneEventPrivate &dd, Type type = None);
- QScopedPointer<QGraphicsSceneEventPrivate> d_ptr;
- Q_DECLARE_PRIVATE(QGraphicsSceneEvent)
-private:
- Q_DISABLE_COPY(QGraphicsSceneEvent)
-};
-
-class QGraphicsSceneMouseEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneMouseEvent : public QGraphicsSceneEvent
-{
-public:
- QGraphicsSceneMouseEvent(Type type = None);
- ~QGraphicsSceneMouseEvent();
-
- QPointF pos() const;
- void setPos(const QPointF &pos);
-
- QPointF scenePos() const;
- void setScenePos(const QPointF &pos);
-
- QPoint screenPos() const;
- void setScreenPos(const QPoint &pos);
-
- QPointF buttonDownPos(Qt::MouseButton button) const;
- void setButtonDownPos(Qt::MouseButton button, const QPointF &pos);
-
- QPointF buttonDownScenePos(Qt::MouseButton button) const;
- void setButtonDownScenePos(Qt::MouseButton button, const QPointF &pos);
-
- QPoint buttonDownScreenPos(Qt::MouseButton button) const;
- void setButtonDownScreenPos(Qt::MouseButton button, const QPoint &pos);
-
- QPointF lastPos() const;
- void setLastPos(const QPointF &pos);
-
- QPointF lastScenePos() const;
- void setLastScenePos(const QPointF &pos);
-
- QPoint lastScreenPos() const;
- void setLastScreenPos(const QPoint &pos);
-
- Qt::MouseButtons buttons() const;
- void setButtons(Qt::MouseButtons buttons);
-
- Qt::MouseButton button() const;
- void setButton(Qt::MouseButton button);
-
- Qt::KeyboardModifiers modifiers() const;
- void setModifiers(Qt::KeyboardModifiers modifiers);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsSceneMouseEvent)
- Q_DISABLE_COPY(QGraphicsSceneMouseEvent)
-};
-
-class QGraphicsSceneWheelEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneWheelEvent : public QGraphicsSceneEvent
-{
-public:
- QGraphicsSceneWheelEvent(Type type = None);
- ~QGraphicsSceneWheelEvent();
-
- QPointF pos() const;
- void setPos(const QPointF &pos);
-
- QPointF scenePos() const;
- void setScenePos(const QPointF &pos);
-
- QPoint screenPos() const;
- void setScreenPos(const QPoint &pos);
-
- Qt::MouseButtons buttons() const;
- void setButtons(Qt::MouseButtons buttons);
-
- Qt::KeyboardModifiers modifiers() const;
- void setModifiers(Qt::KeyboardModifiers modifiers);
-
- int delta() const;
- void setDelta(int delta);
-
- Qt::Orientation orientation() const;
- void setOrientation(Qt::Orientation orientation);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsSceneWheelEvent)
- Q_DISABLE_COPY(QGraphicsSceneWheelEvent)
-};
-
-class QGraphicsSceneContextMenuEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneContextMenuEvent : public QGraphicsSceneEvent
-{
-public:
- enum Reason { Mouse, Keyboard, Other };
-
- QGraphicsSceneContextMenuEvent(Type type = None);
- ~QGraphicsSceneContextMenuEvent();
-
- QPointF pos() const;
- void setPos(const QPointF &pos);
-
- QPointF scenePos() const;
- void setScenePos(const QPointF &pos);
-
- QPoint screenPos() const;
- void setScreenPos(const QPoint &pos);
-
- Qt::KeyboardModifiers modifiers() const;
- void setModifiers(Qt::KeyboardModifiers modifiers);
-
- Reason reason() const;
- void setReason(Reason reason);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsSceneContextMenuEvent)
- Q_DISABLE_COPY(QGraphicsSceneContextMenuEvent)
-};
-
-class QGraphicsSceneHoverEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneHoverEvent : public QGraphicsSceneEvent
-{
-public:
- QGraphicsSceneHoverEvent(Type type = None);
- ~QGraphicsSceneHoverEvent();
-
- QPointF pos() const;
- void setPos(const QPointF &pos);
-
- QPointF scenePos() const;
- void setScenePos(const QPointF &pos);
-
- QPoint screenPos() const;
- void setScreenPos(const QPoint &pos);
-
- QPointF lastPos() const;
- void setLastPos(const QPointF &pos);
-
- QPointF lastScenePos() const;
- void setLastScenePos(const QPointF &pos);
-
- QPoint lastScreenPos() const;
- void setLastScreenPos(const QPoint &pos);
-
- Qt::KeyboardModifiers modifiers() const;
- void setModifiers(Qt::KeyboardModifiers modifiers);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsSceneHoverEvent)
- Q_DISABLE_COPY(QGraphicsSceneHoverEvent)
-};
-
-class QGraphicsSceneHelpEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneHelpEvent : public QGraphicsSceneEvent
-{
-public:
- QGraphicsSceneHelpEvent(Type type = None);
- ~QGraphicsSceneHelpEvent();
-
- QPointF scenePos() const;
- void setScenePos(const QPointF &pos);
-
- QPoint screenPos() const;
- void setScreenPos(const QPoint &pos);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsSceneHelpEvent)
- Q_DISABLE_COPY(QGraphicsSceneHelpEvent)
-};
-
-class QGraphicsSceneDragDropEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneDragDropEvent : public QGraphicsSceneEvent
-{
-public:
- QGraphicsSceneDragDropEvent(Type type = None);
- ~QGraphicsSceneDragDropEvent();
-
- QPointF pos() const;
- void setPos(const QPointF &pos);
-
- QPointF scenePos() const;
- void setScenePos(const QPointF &pos);
-
- QPoint screenPos() const;
- void setScreenPos(const QPoint &pos);
-
- Qt::MouseButtons buttons() const;
- void setButtons(Qt::MouseButtons buttons);
-
- Qt::KeyboardModifiers modifiers() const;
- void setModifiers(Qt::KeyboardModifiers modifiers);
-
- Qt::DropActions possibleActions() const;
- void setPossibleActions(Qt::DropActions actions);
-
- Qt::DropAction proposedAction() const;
- void setProposedAction(Qt::DropAction action);
- void acceptProposedAction();
-
- Qt::DropAction dropAction() const;
- void setDropAction(Qt::DropAction action);
-
- QWidget *source() const;
- void setSource(QWidget *source);
-
- const QMimeData *mimeData() const;
- void setMimeData(const QMimeData *data);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsSceneDragDropEvent)
- Q_DISABLE_COPY(QGraphicsSceneDragDropEvent)
-};
-
-class QGraphicsSceneResizeEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneResizeEvent : public QGraphicsSceneEvent
-{
- Q_DECLARE_PRIVATE(QGraphicsSceneResizeEvent)
- Q_DISABLE_COPY(QGraphicsSceneResizeEvent)
-public:
- QGraphicsSceneResizeEvent();
- ~QGraphicsSceneResizeEvent();
-
- QSizeF oldSize() const;
- void setOldSize(const QSizeF &size);
-
- QSizeF newSize() const;
- void setNewSize(const QSizeF &size);
-};
-
-class QGraphicsSceneMoveEventPrivate;
-class Q_GUI_EXPORT QGraphicsSceneMoveEvent : public QGraphicsSceneEvent
-{
- Q_DECLARE_PRIVATE(QGraphicsSceneMoveEvent)
- Q_DISABLE_COPY(QGraphicsSceneMoveEvent)
-public:
- QGraphicsSceneMoveEvent();
- ~QGraphicsSceneMoveEvent();
-
- QPointF oldPos() const;
- void setOldPos(const QPointF &pos);
-
- QPointF newPos() const;
- void setNewPos(const QPointF &pos);
-};
-
-#endif // QT_NO_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicssceneindex.cpp b/src/gui/graphicsview/qgraphicssceneindex.cpp
deleted file mode 100644
index 964e9cb0ef..0000000000
--- a/src/gui/graphicsview/qgraphicssceneindex.cpp
+++ /dev/null
@@ -1,648 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-/*!
- \class QGraphicsSceneIndex
- \brief The QGraphicsSceneIndex class provides a base class to implement
- a custom indexing algorithm for discovering items in QGraphicsScene.
- \since 4.6
- \ingroup graphicsview-api
-
- \internal
-
- The QGraphicsSceneIndex class provides a base class to implement
- a custom indexing algorithm for discovering items in QGraphicsScene. You
- need to subclass it and reimplement addItem, removeItem, estimateItems
- and items in order to have an functional indexing.
-
- \sa QGraphicsScene, QGraphicsView
-*/
-
-#include "qdebug.h"
-#include "qgraphicsscene.h"
-#include "qgraphicsitem_p.h"
-#include "qgraphicsscene_p.h"
-#include "qgraphicswidget.h"
-#include "qgraphicssceneindex_p.h"
-#include "qgraphicsscenebsptreeindex_p.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsSceneIndexRectIntersector : public QGraphicsSceneIndexIntersector
-{
-public:
- bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
- const QTransform &deviceTransform) const
- {
- QRectF brect = item->boundingRect();
- _q_adjustRect(&brect);
-
- // ### Add test for this (without making things slower?)
- Q_UNUSED(exposeRect);
-
- bool keep = true;
- const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item);
- if (itemd->itemIsUntransformable()) {
- // Untransformable items; map the scene rect to item coordinates.
- const QTransform transform = item->deviceTransform(deviceTransform);
- QRectF itemRect = (deviceTransform * transform.inverted()).mapRect(sceneRect);
- if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
- keep = itemRect.contains(brect) && itemRect != brect;
- else
- keep = itemRect.intersects(brect);
- if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
- QPainterPath itemPath;
- itemPath.addRect(itemRect);
- keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode);
- }
- } else {
- Q_ASSERT(!itemd->dirtySceneTransform);
- const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly
- ? brect.translated(itemd->sceneTransform.dx(),
- itemd->sceneTransform.dy())
- : itemd->sceneTransform.mapRect(brect);
- if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
- keep = sceneRect != brect && sceneRect.contains(itemSceneBoundingRect);
- else
- keep = sceneRect.intersects(itemSceneBoundingRect);
- if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
- QPainterPath rectPath;
- rectPath.addRect(sceneRect);
- if (itemd->sceneTransformTranslateOnly)
- rectPath.translate(-itemd->sceneTransform.dx(), -itemd->sceneTransform.dy());
- else
- rectPath = itemd->sceneTransform.inverted().map(rectPath);
- keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, rectPath, mode);
- }
- }
- return keep;
- }
-
- QRectF sceneRect;
-};
-
-class QGraphicsSceneIndexPointIntersector : public QGraphicsSceneIndexIntersector
-{
-public:
- bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
- const QTransform &deviceTransform) const
- {
- QRectF brect = item->boundingRect();
- _q_adjustRect(&brect);
-
- // ### Add test for this (without making things slower?)
- Q_UNUSED(exposeRect);
-
- bool keep = false;
- const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item);
- if (itemd->itemIsUntransformable()) {
- // Untransformable items; map the scene point to item coordinates.
- const QTransform transform = item->deviceTransform(deviceTransform);
- QPointF itemPoint = (deviceTransform * transform.inverted()).map(scenePoint);
- keep = brect.contains(itemPoint);
- if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
- QPainterPath pointPath;
- pointPath.addRect(QRectF(itemPoint, QSizeF(1, 1)));
- keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, pointPath, mode);
- }
- } else {
- Q_ASSERT(!itemd->dirtySceneTransform);
- QRectF sceneBoundingRect = itemd->sceneTransformTranslateOnly
- ? brect.translated(itemd->sceneTransform.dx(),
- itemd->sceneTransform.dy())
- : itemd->sceneTransform.mapRect(brect);
- keep = sceneBoundingRect.intersects(QRectF(scenePoint, QSizeF(1, 1)));
- if (keep) {
- QPointF p = itemd->sceneTransformTranslateOnly
- ? QPointF(scenePoint.x() - itemd->sceneTransform.dx(),
- scenePoint.y() - itemd->sceneTransform.dy())
- : itemd->sceneTransform.inverted().map(scenePoint);
- keep = item->contains(p);
- }
- }
-
- return keep;
- }
-
- QPointF scenePoint;
-};
-
-class QGraphicsSceneIndexPathIntersector : public QGraphicsSceneIndexIntersector
-{
-public:
- bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
- const QTransform &deviceTransform) const
- {
- QRectF brect = item->boundingRect();
- _q_adjustRect(&brect);
-
- // ### Add test for this (without making things slower?)
- Q_UNUSED(exposeRect);
-
- bool keep = true;
- const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item);
- if (itemd->itemIsUntransformable()) {
- // Untransformable items; map the scene rect to item coordinates.
- const QTransform transform = item->deviceTransform(deviceTransform);
- QPainterPath itemPath = (deviceTransform * transform.inverted()).map(scenePath);
- if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
- keep = itemPath.contains(brect);
- else
- keep = itemPath.intersects(brect);
- if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape))
- keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode);
- } else {
- Q_ASSERT(!itemd->dirtySceneTransform);
- const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly
- ? brect.translated(itemd->sceneTransform.dx(),
- itemd->sceneTransform.dy())
- : itemd->sceneTransform.mapRect(brect);
- if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
- keep = scenePath.contains(itemSceneBoundingRect);
- else
- keep = scenePath.intersects(itemSceneBoundingRect);
- if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
- QPainterPath itemPath = itemd->sceneTransformTranslateOnly
- ? scenePath.translated(-itemd->sceneTransform.dx(),
- -itemd->sceneTransform.dy())
- : itemd->sceneTransform.inverted().map(scenePath);
- keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode);
- }
- }
- return keep;
- }
-
- QPainterPath scenePath;
-};
-
-/*!
- Constructs a private scene index.
-*/
-QGraphicsSceneIndexPrivate::QGraphicsSceneIndexPrivate(QGraphicsScene *scene) : scene(scene)
-{
- pointIntersector = new QGraphicsSceneIndexPointIntersector;
- rectIntersector = new QGraphicsSceneIndexRectIntersector;
- pathIntersector = new QGraphicsSceneIndexPathIntersector;
-}
-
-/*!
- Destructor of private scene index.
-*/
-QGraphicsSceneIndexPrivate::~QGraphicsSceneIndexPrivate()
-{
- delete pointIntersector;
- delete rectIntersector;
- delete pathIntersector;
-}
-
-/*!
- \internal
-
- Checks if item collides with the path and mode, but also checks that if it
- doesn't collide, maybe its frame rect will.
-*/
-bool QGraphicsSceneIndexPrivate::itemCollidesWithPath(const QGraphicsItem *item,
- const QPainterPath &path,
- Qt::ItemSelectionMode mode)
-{
- if (item->collidesWithPath(path, mode))
- return true;
- if (item->isWidget()) {
- // Check if this is a window, and if its frame rect collides.
- const QGraphicsWidget *widget = static_cast<const QGraphicsWidget *>(item);
- if (widget->isWindow()) {
- QRectF frameRect = widget->windowFrameRect();
- QPainterPath framePath;
- framePath.addRect(frameRect);
- bool intersects = path.intersects(frameRect);
- if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
- return intersects || path.contains(frameRect.topLeft())
- || framePath.contains(path.elementAt(0));
- return !intersects && path.contains(frameRect.topLeft());
- }
- }
- return false;
-}
-
-/*!
- \internal
- This function returns the items in ascending order.
-*/
-void QGraphicsSceneIndexPrivate::recursive_items_helper(QGraphicsItem *item, QRectF exposeRect,
- QGraphicsSceneIndexIntersector *intersector,
- QList<QGraphicsItem *> *items,
- const QTransform &viewTransform,
- Qt::ItemSelectionMode mode,
- qreal parentOpacity) const
-{
- Q_ASSERT(item);
- if (!item->d_ptr->visible)
- return;
-
- const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
- const bool itemIsFullyTransparent = QGraphicsItemPrivate::isOpacityNull(opacity);
- const bool itemHasChildren = !item->d_ptr->children.isEmpty();
- if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity()))
- return;
-
- // Update the item's scene transform if dirty.
- const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable();
- const bool wasDirtyParentSceneTransform = item->d_ptr->dirtySceneTransform && !itemIsUntransformable;
- if (wasDirtyParentSceneTransform) {
- item->d_ptr->updateSceneTransformFromParent();
- Q_ASSERT(!item->d_ptr->dirtySceneTransform);
- }
-
- const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
- bool processItem = !itemIsFullyTransparent;
- if (processItem) {
- processItem = intersector->intersect(item, exposeRect, mode, viewTransform);
- if (!processItem && (!itemHasChildren || itemClipsChildrenToShape)) {
- if (wasDirtyParentSceneTransform)
- item->d_ptr->invalidateChildrenSceneTransform();
- return;
- }
- } // else we know for sure this item has children we must process.
-
- int i = 0;
- if (itemHasChildren) {
- // Sort children.
- item->d_ptr->ensureSortedChildren();
-
- // Clip to shape.
- if (itemClipsChildrenToShape && !itemIsUntransformable) {
- QPainterPath mappedShape = item->d_ptr->sceneTransformTranslateOnly
- ? item->shape().translated(item->d_ptr->sceneTransform.dx(),
- item->d_ptr->sceneTransform.dy())
- : item->d_ptr->sceneTransform.map(item->shape());
- exposeRect &= mappedShape.controlPointRect();
- }
-
- // Process children behind
- for (i = 0; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
- if (wasDirtyParentSceneTransform)
- child->d_ptr->dirtySceneTransform = 1;
- if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
- break;
- if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
- continue;
- recursive_items_helper(child, exposeRect, intersector, items, viewTransform,
- mode, opacity);
- }
- }
-
- // Process item
- if (processItem)
- items->append(item);
-
- // Process children in front
- if (itemHasChildren) {
- for (; i < item->d_ptr->children.size(); ++i) {
- QGraphicsItem *child = item->d_ptr->children.at(i);
- if (wasDirtyParentSceneTransform)
- child->d_ptr->dirtySceneTransform = 1;
- if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
- continue;
- recursive_items_helper(child, exposeRect, intersector, items, viewTransform,
- mode, opacity);
- }
- }
-}
-
-void QGraphicsSceneIndexPrivate::init()
-{
- if (!scene)
- return;
-
- QObject::connect(scene, SIGNAL(sceneRectChanged(QRectF)),
- q_func(), SLOT(updateSceneRect(QRectF)));
-}
-
-/*!
- Constructs an abstract scene index for a given \a scene.
-*/
-QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsScene *scene)
-: QObject(*new QGraphicsSceneIndexPrivate(scene), scene)
-{
- d_func()->init();
-}
-
-/*!
- \internal
-*/
-QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsSceneIndexPrivate &dd, QGraphicsScene *scene)
- : QObject(dd, scene)
-{
- d_func()->init();
-}
-
-/*!
- Destroys the scene index.
-*/
-QGraphicsSceneIndex::~QGraphicsSceneIndex()
-{
-
-}
-
-/*!
- Returns the scene of this index.
-*/
-QGraphicsScene* QGraphicsSceneIndex::scene() const
-{
- Q_D(const QGraphicsSceneIndex);
- return d->scene;
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos,
- Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform
- &deviceTransform) const
-
- Returns all visible items that, depending on \a mode, are at the specified
- \a pos and return a list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with \a pos are returned.
-
- \a deviceTransform is the transformation apply to the view.
-
- This method use the estimation of the index (estimateItems) and refine the
- list to get an exact result. If you want to implement your own refinement
- algorithm you can reimplement this method.
-
- \sa estimateItems()
-
-*/
-QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
-
- Q_D(const QGraphicsSceneIndex);
- QList<QGraphicsItem *> itemList;
- d->pointIntersector->scenePoint = pos;
- d->items_helper(QRectF(pos, QSizeF(1, 1)), d->pointIntersector, &itemList, deviceTransform, mode, order);
- return itemList;
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect,
- Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform
- &deviceTransform) const
-
- \overload
-
- Returns all visible items that, depending on \a mode, are either inside or
- intersect with the specified \a rect and return a list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a rect are returned.
-
- \a deviceTransform is the transformation apply to the view.
-
- This method use the estimation of the index (estimateItems) and refine
- the list to get an exact result. If you want to implement your own
- refinement algorithm you can reimplement this method.
-
- \sa estimateItems()
-
-*/
-QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsSceneIndex);
- QRectF exposeRect = rect;
- _q_adjustRect(&exposeRect);
- QList<QGraphicsItem *> itemList;
- d->rectIntersector->sceneRect = rect;
- d->items_helper(exposeRect, d->rectIntersector, &itemList, deviceTransform, mode, order);
- return itemList;
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF
- &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const
- QTransform &deviceTransform) const
-
- \overload
-
- Returns all visible items that, depending on \a mode, are either inside or
- intersect with the specified \a polygon and return a list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a polygon are returned.
-
- \a deviceTransform is the transformation apply to the view.
-
- This method use the estimation of the index (estimateItems) and refine
- the list to get an exact result. If you want to implement your own
- refinement algorithm you can reimplement this method.
-
- \sa estimateItems()
-
-*/
-QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsSceneIndex);
- QList<QGraphicsItem *> itemList;
- QRectF exposeRect = polygon.boundingRect();
- _q_adjustRect(&exposeRect);
- QPainterPath path;
- path.addPolygon(polygon);
- d->pathIntersector->scenePath = path;
- d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order);
- return itemList;
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath
- &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform
- &deviceTransform) const
-
- \overload
-
- Returns all visible items that, depending on \a mode, are either inside or
- intersect with the specified \a path and return a list sorted using \a order.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a path are returned.
-
- \a deviceTransform is the transformation apply to the view.
-
- This method use the estimation of the index (estimateItems) and refine
- the list to get an exact result. If you want to implement your own
- refinement algorithm you can reimplement this method.
-
- \sa estimateItems()
-
-*/
-QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath &path, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform) const
-{
- Q_D(const QGraphicsSceneIndex);
- QList<QGraphicsItem *> itemList;
- QRectF exposeRect = path.controlPointRect();
- _q_adjustRect(&exposeRect);
- d->pathIntersector->scenePath = path;
- d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order);
- return itemList;
-}
-
-/*!
- This virtual function return an estimation of items at position \a point.
- This method return a list sorted using \a order.
-*/
-QList<QGraphicsItem *> QGraphicsSceneIndex::estimateItems(const QPointF &point, Qt::SortOrder order) const
-{
- return estimateItems(QRectF(point, QSize(1, 1)), order);
-}
-
-QList<QGraphicsItem *> QGraphicsSceneIndex::estimateTopLevelItems(const QRectF &rect, Qt::SortOrder order) const
-{
- Q_D(const QGraphicsSceneIndex);
- Q_UNUSED(rect);
- QGraphicsScenePrivate *scened = d->scene->d_func();
- scened->ensureSortedTopLevelItems();
- if (order == Qt::DescendingOrder) {
- QList<QGraphicsItem *> sorted;
- for (int i = scened->topLevelItems.size() - 1; i >= 0; --i)
- sorted << scened->topLevelItems.at(i);
- return sorted;
- }
- return scened->topLevelItems;
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(Qt::SortOrder order = Qt::DescendingOrder) const
-
- This pure virtual function all items in the index and sort them using
- \a order.
-*/
-
-
-/*!
- Notifies the index that the scene's scene rect has changed. \a rect
- is thew new scene rect.
-
- \sa QGraphicsScene::sceneRect()
-*/
-void QGraphicsSceneIndex::updateSceneRect(const QRectF &rect)
-{
- Q_UNUSED(rect);
-}
-
-/*!
- This virtual function removes all items in the scene index.
-*/
-void QGraphicsSceneIndex::clear()
-{
- const QList<QGraphicsItem *> allItems = items();
- for (int i = 0 ; i < allItems.size(); ++i)
- removeItem(allItems.at(i));
-}
-
-/*!
- \fn virtual void QGraphicsSceneIndex::addItem(QGraphicsItem *item) = 0
-
- This pure virtual function inserts an \a item to the scene index.
-
- \sa removeItem(), deleteItem()
-*/
-
-/*!
- \fn virtual void QGraphicsSceneIndex::removeItem(QGraphicsItem *item) = 0
-
- This pure virtual function removes an \a item to the scene index.
-
- \sa addItem(), deleteItem()
-*/
-
-/*!
- This method is called when an \a item has been deleted.
- The default implementation call removeItem. Be carefull,
- if your implementation of removeItem use pure virtual method
- of QGraphicsItem like boundingRect(), then you should reimplement
- this method.
-
- \sa addItem(), removeItem()
-*/
-void QGraphicsSceneIndex::deleteItem(QGraphicsItem *item)
-{
- removeItem(item);
-}
-
-/*!
- This virtual function is called by QGraphicsItem to notify the index
- that some part of the \a item 's state changes. By reimplementing this
- function, your can react to a change, and in some cases, (depending on \a
- change,) adjustments in the index can be made.
-
- \a change is the parameter of the item that is changing. \a value is the
- value that changed; the type of the value depends on \a change.
-
- The default implementation does nothing.
-
- \sa QGraphicsItem::GraphicsItemChange
-*/
-void QGraphicsSceneIndex::itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const void *const value)
-{
- Q_UNUSED(item);
- Q_UNUSED(change);
- Q_UNUSED(value);
-}
-
-/*!
- Notify the index for a geometry change of an \a item.
-
- \sa QGraphicsItem::prepareGeometryChange()
-*/
-void QGraphicsSceneIndex::prepareBoundingRectChange(const QGraphicsItem *item)
-{
- Q_UNUSED(item);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qgraphicssceneindex_p.cpp"
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicssceneindex_p.h b/src/gui/graphicsview/qgraphicssceneindex_p.h
deleted file mode 100644
index e498e822fa..0000000000
--- a/src/gui/graphicsview/qgraphicssceneindex_p.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/****************************************************************************
-**
-** 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 QtCore 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 QGRAPHICSSCENEINDEX_H
-#define QGRAPHICSSCENEINDEX_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 "qgraphicsscene_p.h"
-#include "qgraphicsscene.h"
-#include <private/qobject_p.h>
-
-#include <QtCore/qnamespace.h>
-#include <QtCore/qobject.h>
-#include <QtGui/qtransform.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsSceneIndexIntersector;
-class QGraphicsSceneIndexPointIntersector;
-class QGraphicsSceneIndexRectIntersector;
-class QGraphicsSceneIndexPathIntersector;
-class QGraphicsSceneIndexPrivate;
-class QPointF;
-class QRectF;
-template<typename T> class QList;
-
-class Q_AUTOTEST_EXPORT QGraphicsSceneIndex : public QObject
-{
- Q_OBJECT
-
-public:
- QGraphicsSceneIndex(QGraphicsScene *scene = 0);
- virtual ~QGraphicsSceneIndex();
-
- QGraphicsScene *scene() const;
-
- virtual QList<QGraphicsItem *> items(Qt::SortOrder order = Qt::DescendingOrder) const = 0;
- virtual QList<QGraphicsItem *> items(const QPointF &pos, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- virtual QList<QGraphicsItem *> items(const QRectF &rect, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- virtual QList<QGraphicsItem *> items(const QPolygonF &polygon, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- virtual QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode,
- Qt::SortOrder order, const QTransform &deviceTransform = QTransform()) const;
- virtual QList<QGraphicsItem *> estimateItems(const QPointF &point, Qt::SortOrder order) const;
- virtual QList<QGraphicsItem *> estimateItems(const QRectF &rect, Qt::SortOrder order) const = 0;
- virtual QList<QGraphicsItem *> estimateTopLevelItems(const QRectF &, Qt::SortOrder order) const;
-
-protected Q_SLOTS:
- virtual void updateSceneRect(const QRectF &rect);
-
-protected:
- virtual void clear();
- virtual void addItem(QGraphicsItem *item) = 0;
- virtual void removeItem(QGraphicsItem *item) = 0;
- virtual void deleteItem(QGraphicsItem *item);
-
- virtual void itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange, const void *const value);
- virtual void prepareBoundingRectChange(const QGraphicsItem *item);
-
- QGraphicsSceneIndex(QGraphicsSceneIndexPrivate &dd, QGraphicsScene *scene);
-
- friend class QGraphicsScene;
- friend class QGraphicsScenePrivate;
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
- friend class QGraphicsSceneBspTreeIndex;
-private:
- Q_DISABLE_COPY(QGraphicsSceneIndex)
- Q_DECLARE_PRIVATE(QGraphicsSceneIndex)
-};
-
-class QGraphicsSceneIndexPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsSceneIndex)
-public:
- QGraphicsSceneIndexPrivate(QGraphicsScene *scene);
- ~QGraphicsSceneIndexPrivate();
-
- void init();
- static bool itemCollidesWithPath(const QGraphicsItem *item, const QPainterPath &path, Qt::ItemSelectionMode mode);
-
- void recursive_items_helper(QGraphicsItem *item, QRectF exposeRect,
- QGraphicsSceneIndexIntersector *intersector, QList<QGraphicsItem *> *items,
- const QTransform &viewTransform,
- Qt::ItemSelectionMode mode, qreal parentOpacity = 1.0) const;
- inline void items_helper(const QRectF &rect, QGraphicsSceneIndexIntersector *intersector,
- QList<QGraphicsItem *> *items, const QTransform &viewTransform,
- Qt::ItemSelectionMode mode, Qt::SortOrder order) const;
-
- QGraphicsScene *scene;
- QGraphicsSceneIndexPointIntersector *pointIntersector;
- QGraphicsSceneIndexRectIntersector *rectIntersector;
- QGraphicsSceneIndexPathIntersector *pathIntersector;
-};
-
-inline void QGraphicsSceneIndexPrivate::items_helper(const QRectF &rect, QGraphicsSceneIndexIntersector *intersector,
- QList<QGraphicsItem *> *items, const QTransform &viewTransform,
- Qt::ItemSelectionMode mode, Qt::SortOrder order) const
-{
- Q_Q(const QGraphicsSceneIndex);
- const QList<QGraphicsItem *> tli = q->estimateTopLevelItems(rect, Qt::AscendingOrder);
- for (int i = 0; i < tli.size(); ++i)
- recursive_items_helper(tli.at(i), rect, intersector, items, viewTransform, mode);
- if (order == Qt::DescendingOrder) {
- const int n = items->size();
- for (int i = 0; i < n / 2; ++i)
- items->swap(i, n - i - 1);
- }
-}
-
-class QGraphicsSceneIndexIntersector
-{
-public:
- QGraphicsSceneIndexIntersector() { }
- virtual ~QGraphicsSceneIndexIntersector() { }
- virtual bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
- const QTransform &deviceTransform) const = 0;
-};
-
-#endif // QT_NO_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QGRAPHICSSCENEINDEX_H
diff --git a/src/gui/graphicsview/qgraphicsscenelinearindex.cpp b/src/gui/graphicsview/qgraphicsscenelinearindex.cpp
deleted file mode 100644
index 074d43961a..0000000000
--- a/src/gui/graphicsview/qgraphicsscenelinearindex.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsSceneLinearIndex
- \brief The QGraphicsSceneLinearIndex class provides an implementation of
- a linear indexing algorithm for discovering items in QGraphicsScene.
- \since 4.6
- \ingroup graphicsview-api
- \internal
-
- QGraphicsSceneLinearIndex index is default linear implementation to discover items.
- It basically store all items in a list and return them to the scene.
-
- \sa QGraphicsScene, QGraphicsView, QGraphicsSceneIndex, QGraphicsSceneBspTreeIndex
-*/
-
-#include <private/qgraphicsscenelinearindex_p.h>
-
-/*!
- \fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0):
-
- Construct a linear index for the given \a scene.
-*/
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsSceneLinearIndex::items(Qt::SortOrder order = Qt::DescendingOrder) const;
-
- Return all items in the index and sort them using \a order.
-*/
-
-
-/*!
- \fn virtual QList<QGraphicsItem *> QGraphicsSceneLinearIndex::estimateItems(const QRectF &rect, Qt::SortOrder order) const
-
- Returns an estimation visible items that are either inside or
- intersect with the specified \a rect and return a list sorted using \a order.
-*/
-
-/*!
- \fn void QGraphicsSceneLinearIndex::clear()
- \internal
- Clear the all the BSP index.
-*/
-
-/*!
- \fn virtual void QGraphicsSceneLinearIndex::addItem(QGraphicsItem *item)
-
- Add the \a item into the index.
-*/
-
-/*!
- \fn virtual void QGraphicsSceneLinearIndex::removeItem(QGraphicsItem *item)
-
- Add the \a item from the index.
-*/
-
diff --git a/src/gui/graphicsview/qgraphicsscenelinearindex_p.h b/src/gui/graphicsview/qgraphicsscenelinearindex_p.h
deleted file mode 100644
index ef72f57faf..0000000000
--- a/src/gui/graphicsview/qgraphicsscenelinearindex_p.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/****************************************************************************
-**
-** 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 QtCore 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 QGRAPHICSSCENELINEARINDEX_H
-#define QGRAPHICSSCENELINEARINDEX_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 <QtCore/qglobal.h>
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-#include <QtCore/qrect.h>
-#include <QtCore/qlist.h>
-#include <QtGui/qgraphicsitem.h>
-#include <private/qgraphicssceneindex_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_AUTOTEST_EXPORT QGraphicsSceneLinearIndex : public QGraphicsSceneIndex
-{
- Q_OBJECT
-
-public:
- QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0) : QGraphicsSceneIndex(scene)
- { }
-
- QList<QGraphicsItem *> items(Qt::SortOrder order = Qt::DescendingOrder) const
- { Q_UNUSED(order); return m_items; }
-
- virtual QList<QGraphicsItem *> estimateItems(const QRectF &rect, Qt::SortOrder order) const
- {
- Q_UNUSED(rect);
- Q_UNUSED(order);
- return m_items;
- }
-
-protected :
- virtual void clear()
- { m_items.clear(); }
-
- virtual void addItem(QGraphicsItem *item)
- { m_items << item; }
-
- virtual void removeItem(QGraphicsItem *item)
- { m_items.removeOne(item); }
-
-private:
- QList<QGraphicsItem*> m_items;
-};
-
-#endif // QT_NO_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QGRAPHICSSCENELINEARINDEX_H
diff --git a/src/gui/graphicsview/qgraphicstransform.cpp b/src/gui/graphicsview/qgraphicstransform.cpp
deleted file mode 100644
index 513c41f46f..0000000000
--- a/src/gui/graphicsview/qgraphicstransform.cpp
+++ /dev/null
@@ -1,594 +0,0 @@
-/****************************************************************************
-**
-** 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 QtDeclarative 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$
-**
-****************************************************************************/
-
-/*!
- \class QGraphicsTransform
- \brief The QGraphicsTransform class is an abstract base class for building
- advanced transformations on QGraphicsItems.
- \since 4.6
- \ingroup graphicsview-api
-
- As an alternative to QGraphicsItem::transform, QGraphicsTransform lets you
- create and control advanced transformations that can be configured
- independently using specialized properties.
-
- QGraphicsItem allows you to assign any number of QGraphicsTransform
- instances to one QGraphicsItem. Each QGraphicsTransform is applied in
- order, one at a time, to the QGraphicsItem it's assigned to.
-
- QGraphicsTransform is particularly useful for animations. Whereas
- QGraphicsItem::setTransform() lets you assign any transform directly to an
- item, there is no direct way to interpolate between two different
- transformations (e.g., when transitioning between two states, each for
- which the item has a different arbitrary transform assigned). Using
- QGraphicsTransform you can interpolate the property values of each
- independent transformation. The resulting operation is then combined into a
- single transform which is applied to QGraphicsItem.
-
- Transformations are computed in true 3D space using QMatrix4x4.
- When the transformation is applied to a QGraphicsItem, it will be
- projected back to a 2D QTransform. When multiple QGraphicsTransform
- objects are applied to a QGraphicsItem, all of the transformations
- are computed in true 3D space, with the projection back to 2D
- only occurring after the last QGraphicsTransform is applied.
- The exception to this is QGraphicsRotation, which projects back to
- 2D after each rotation to preserve the perspective effect around
- the X and Y axes.
-
- If you want to create your own configurable transformation, you can create
- a subclass of QGraphicsTransform (or any or the existing subclasses), and
- reimplement the pure virtual applyTo() function, which takes a pointer to a
- QMatrix4x4. Each operation you would like to apply should be exposed as
- properties (e.g., customTransform->setVerticalShear(2.5)). Inside you
- reimplementation of applyTo(), you can modify the provided transform
- respectively.
-
- QGraphicsTransform can be used together with QGraphicsItem::setTransform(),
- QGraphicsItem::setRotation(), and QGraphicsItem::setScale().
-
- \sa QGraphicsItem::transform(), QGraphicsScale, QGraphicsRotation
-*/
-
-#include "qgraphicstransform.h"
-#include "qgraphicsitem_p.h"
-#include "qgraphicstransform_p.h"
-#include <QDebug>
-#include <QtCore/qmath.h>
-#include <QtCore/qnumeric.h>
-
-#ifndef QT_NO_GRAPHICSVIEW
-QT_BEGIN_NAMESPACE
-void QGraphicsTransformPrivate::setItem(QGraphicsItem *i)
-{
- if (item == i)
- return;
-
- if (item) {
- Q_Q(QGraphicsTransform);
- QGraphicsItemPrivate *d_ptr = item->d_ptr.data();
-
- item->prepareGeometryChange();
- Q_ASSERT(d_ptr->transformData);
- d_ptr->transformData->graphicsTransforms.removeAll(q);
- d_ptr->dirtySceneTransform = 1;
- item = 0;
- }
-
- item = i;
-}
-
-void QGraphicsTransformPrivate::updateItem(QGraphicsItem *item)
-{
- item->prepareGeometryChange();
- item->d_ptr->dirtySceneTransform = 1;
-}
-
-/*!
- Constructs a new QGraphicsTransform with the given \a parent.
-*/
-QGraphicsTransform::QGraphicsTransform(QObject *parent)
- : QObject(*new QGraphicsTransformPrivate, parent)
-{
-}
-
-/*!
- Destroys the graphics transform.
-*/
-QGraphicsTransform::~QGraphicsTransform()
-{
- Q_D(QGraphicsTransform);
- d->setItem(0);
-}
-
-/*!
- \internal
-*/
-QGraphicsTransform::QGraphicsTransform(QGraphicsTransformPrivate &p, QObject *parent)
- : QObject(p, parent)
-{
-}
-
-/*!
- \fn void QGraphicsTransform::applyTo(QMatrix4x4 *matrix) const
-
- This pure virtual method has to be reimplemented in derived classes.
-
- It applies this transformation to \a matrix.
-
- \sa QGraphicsItem::transform(), QMatrix4x4::toTransform()
-*/
-
-/*!
- Notifies that this transform operation has changed its parameters in such a
- way that applyTo() will return a different result than before.
-
- When implementing you own custom graphics transform, you must call this
- function every time you change a parameter, to let QGraphicsItem know that
- its transformation needs to be updated.
-
- \sa applyTo()
-*/
-void QGraphicsTransform::update()
-{
- Q_D(QGraphicsTransform);
- if (d->item)
- d->updateItem(d->item);
-}
-
-/*!
- \class QGraphicsScale
- \brief The QGraphicsScale class provides a scale transformation.
- \since 4.6
-
- QGraphicsScene provides certain parameters to help control how the scale
- should be applied.
-
- The origin is the point that the item is scaled from (i.e., it stays fixed
- relative to the parent as the rest of the item grows). By default the
- origin is QPointF(0, 0).
-
- The parameters xScale, yScale, and zScale describe the scale factors to
- apply in horizontal, vertical, and depth directions. They can take on any
- value, including 0 (to collapse the item to a point) or negative value.
- A negative xScale value will mirror the item horizontally. A negative yScale
- value will flip the item vertically. A negative zScale will flip the
- item end for end.
-
- \sa QGraphicsTransform, QGraphicsItem::setScale(), QTransform::scale()
-*/
-
-class QGraphicsScalePrivate : public QGraphicsTransformPrivate
-{
-public:
- QGraphicsScalePrivate()
- : xScale(1), yScale(1), zScale(1) {}
- QVector3D origin;
- qreal xScale;
- qreal yScale;
- qreal zScale;
-};
-
-/*!
- Constructs an empty QGraphicsScale object with the given \a parent.
-*/
-QGraphicsScale::QGraphicsScale(QObject *parent)
- : QGraphicsTransform(*new QGraphicsScalePrivate, parent)
-{
-}
-
-/*!
- Destroys the graphics scale.
-*/
-QGraphicsScale::~QGraphicsScale()
-{
-}
-
-/*!
- \property QGraphicsScale::origin
- \brief the origin of the scale in 3D space.
-
- All scaling will be done relative to this point (i.e., this point
- will stay fixed, relative to the parent, when the item is scaled).
-
- \sa xScale, yScale, zScale
-*/
-QVector3D QGraphicsScale::origin() const
-{
- Q_D(const QGraphicsScale);
- return d->origin;
-}
-void QGraphicsScale::setOrigin(const QVector3D &point)
-{
- Q_D(QGraphicsScale);
- if (d->origin == point)
- return;
- d->origin = point;
- update();
- emit originChanged();
-}
-
-/*!
- \property QGraphicsScale::xScale
- \brief the horizontal scale factor.
-
- The scale factor can be any real number; the default value is 1.0. If you
- set the factor to 0.0, the item will be collapsed to a single point. If you
- provide a negative value, the item will be mirrored horizontally around its
- origin.
-
- \sa yScale, zScale, origin
-*/
-qreal QGraphicsScale::xScale() const
-{
- Q_D(const QGraphicsScale);
- return d->xScale;
-}
-void QGraphicsScale::setXScale(qreal scale)
-{
- Q_D(QGraphicsScale);
- if (d->xScale == scale)
- return;
- d->xScale = scale;
- update();
- emit xScaleChanged();
- emit scaleChanged();
-}
-
-/*!
- \property QGraphicsScale::yScale
- \brief the vertical scale factor.
-
- The scale factor can be any real number; the default value is 1.0. If you
- set the factor to 0.0, the item will be collapsed to a single point. If you
- provide a negative value, the item will be flipped vertically around its
- origin.
-
- \sa xScale, zScale, origin
-*/
-qreal QGraphicsScale::yScale() const
-{
- Q_D(const QGraphicsScale);
- return d->yScale;
-}
-void QGraphicsScale::setYScale(qreal scale)
-{
- Q_D(QGraphicsScale);
- if (d->yScale == scale)
- return;
- d->yScale = scale;
- update();
- emit yScaleChanged();
- emit scaleChanged();
-}
-
-/*!
- \property QGraphicsScale::zScale
- \brief the depth scale factor.
-
- The scale factor can be any real number; the default value is 1.0. If you
- set the factor to 0.0, the item will be collapsed to a single point. If you
- provide a negative value, the item will be flipped end for end around its
- origin.
-
- \sa xScale, yScale, origin
-*/
-qreal QGraphicsScale::zScale() const
-{
- Q_D(const QGraphicsScale);
- return d->zScale;
-}
-void QGraphicsScale::setZScale(qreal scale)
-{
- Q_D(QGraphicsScale);
- if (d->zScale == scale)
- return;
- d->zScale = scale;
- update();
- emit zScaleChanged();
- emit scaleChanged();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsScale::applyTo(QMatrix4x4 *matrix) const
-{
- Q_D(const QGraphicsScale);
- matrix->translate(d->origin);
- matrix->scale(d->xScale, d->yScale, d->zScale);
- matrix->translate(-d->origin);
-}
-
-/*!
- \fn QGraphicsScale::originChanged()
-
- QGraphicsScale emits this signal when its origin changes.
-
- \sa QGraphicsScale::origin
-*/
-
-/*!
- \fn QGraphicsScale::xScaleChanged()
- \since 4.7
-
- This signal is emitted whenever the \l xScale property changes.
-*/
-
-/*!
- \fn QGraphicsScale::yScaleChanged()
- \since 4.7
-
- This signal is emitted whenever the \l yScale property changes.
-*/
-
-/*!
- \fn QGraphicsScale::zScaleChanged()
- \since 4.7
-
- This signal is emitted whenever the \l zScale property changes.
-*/
-
-/*!
- \fn QGraphicsScale::scaleChanged()
-
- This signal is emitted whenever the xScale, yScale, or zScale
- of the object changes.
-
- \sa QGraphicsScale::xScale, QGraphicsScale::yScale
- \sa QGraphicsScale::zScale
-*/
-
-/*!
- \class QGraphicsRotation
- \brief The QGraphicsRotation class provides a rotation transformation around
- a given axis.
- \since 4.6
-
- You can provide the desired axis by assigning a QVector3D to the axis property
- or by passing a member if Qt::Axis to the setAxis convenience function.
- By default the axis is (0, 0, 1) i.e., rotation around the Z axis.
-
- The angle property, which is provided by QGraphicsRotation, now
- describes the number of degrees to rotate around this axis.
-
- QGraphicsRotation provides certain parameters to help control how the
- rotation should be applied.
-
- The origin is the point that the item is rotated around (i.e., it stays
- fixed relative to the parent as the rest of the item is rotated). By
- default the origin is QPointF(0, 0).
-
- The angle property provides the number of degrees to rotate the item
- clockwise around the origin. This value also be negative, indicating a
- counter-clockwise rotation. For animation purposes it may also be useful to
- provide rotation angles exceeding (-360, 360) degrees, for instance to
- animate how an item rotates several times.
-
- Note: the final rotation is the combined effect of a rotation in
- 3D space followed by a projection back to 2D. If several rotations
- are performed in succession, they will not behave as expected unless
- they were all around the Z axis.
-
- \sa QGraphicsTransform, QGraphicsItem::setRotation(), QTransform::rotate()
-*/
-
-class QGraphicsRotationPrivate : public QGraphicsTransformPrivate
-{
-public:
- QGraphicsRotationPrivate()
- : angle(0), axis(0, 0, 1) {}
- QVector3D origin;
- qreal angle;
- QVector3D axis;
-};
-
-/*!
- Constructs a new QGraphicsRotation with the given \a parent.
-*/
-QGraphicsRotation::QGraphicsRotation(QObject *parent)
- : QGraphicsTransform(*new QGraphicsRotationPrivate, parent)
-{
-}
-
-/*!
- Destroys the graphics rotation.
-*/
-QGraphicsRotation::~QGraphicsRotation()
-{
-}
-
-/*!
- \property QGraphicsRotation::origin
- \brief the origin of the rotation in 3D space.
-
- All rotations will be done relative to this point (i.e., this point
- will stay fixed, relative to the parent, when the item is rotated).
-
- \sa angle
-*/
-QVector3D QGraphicsRotation::origin() const
-{
- Q_D(const QGraphicsRotation);
- return d->origin;
-}
-void QGraphicsRotation::setOrigin(const QVector3D &point)
-{
- Q_D(QGraphicsRotation);
- if (d->origin == point)
- return;
- d->origin = point;
- update();
- emit originChanged();
-}
-
-/*!
- \property QGraphicsRotation::angle
- \brief the angle for clockwise rotation, in degrees.
-
- The angle can be any real number; the default value is 0.0. A value of 180
- will rotate 180 degrees, clockwise. If you provide a negative number, the
- item will be rotated counter-clockwise. Normally the rotation angle will be
- in the range (-360, 360), but you can also provide numbers outside of this
- range (e.g., a angle of 370 degrees gives the same result as 10 degrees).
- Setting the angle to NaN results in no rotation.
-
- \sa origin
-*/
-qreal QGraphicsRotation::angle() const
-{
- Q_D(const QGraphicsRotation);
- return d->angle;
-}
-void QGraphicsRotation::setAngle(qreal angle)
-{
- Q_D(QGraphicsRotation);
- if (d->angle == angle)
- return;
- d->angle = angle;
- update();
- emit angleChanged();
-}
-
-/*!
- \fn QGraphicsRotation::originChanged()
-
- This signal is emitted whenever the origin has changed.
-
- \sa QGraphicsRotation::origin
-*/
-
-/*!
- \fn void QGraphicsRotation::angleChanged()
-
- This signal is emitted whenever the angle has changed.
-
- \sa QGraphicsRotation::angle
-*/
-
-/*!
- \property QGraphicsRotation::axis
- \brief a rotation axis, specified by a vector in 3D space.
-
- This can be any axis in 3D space. By default the axis is (0, 0, 1),
- which is aligned with the Z axis. If you provide another axis,
- QGraphicsRotation will provide a transformation that rotates
- around this axis. For example, if you would like to rotate an item
- around its X axis, you could pass (1, 0, 0) as the axis.
-
- \sa QTransform, QGraphicsRotation::angle
-*/
-QVector3D QGraphicsRotation::axis() const
-{
- Q_D(const QGraphicsRotation);
- return d->axis;
-}
-void QGraphicsRotation::setAxis(const QVector3D &axis)
-{
- Q_D(QGraphicsRotation);
- if (d->axis == axis)
- return;
- d->axis = axis;
- update();
- emit axisChanged();
-}
-
-/*!
- \fn void QGraphicsRotation::setAxis(Qt::Axis axis)
-
- Convenience function to set the axis to \a axis.
-
- Note: the Qt::YAxis rotation for QTransform is inverted from the
- correct mathematical rotation in 3D space. The QGraphicsRotation
- class implements a correct mathematical rotation. The following
- two sequences of code will perform the same transformation:
-
- \code
- QTransform t;
- t.rotate(45, Qt::YAxis);
-
- QGraphicsRotation r;
- r.setAxis(Qt::YAxis);
- r.setAngle(-45);
- \endcode
-*/
-void QGraphicsRotation::setAxis(Qt::Axis axis)
-{
- switch (axis)
- {
- case Qt::XAxis:
- setAxis(QVector3D(1, 0, 0));
- break;
- case Qt::YAxis:
- setAxis(QVector3D(0, 1, 0));
- break;
- case Qt::ZAxis:
- setAxis(QVector3D(0, 0, 1));
- break;
- }
-}
-
-/*!
- \reimp
-*/
-void QGraphicsRotation::applyTo(QMatrix4x4 *matrix) const
-{
- Q_D(const QGraphicsRotation);
-
- if (d->angle == 0. || d->axis.isNull() || qIsNaN(d->angle))
- return;
-
- matrix->translate(d->origin);
- matrix->projectedRotate(d->angle, d->axis.x(), d->axis.y(), d->axis.z());
- matrix->translate(-d->origin);
-}
-
-/*!
- \fn void QGraphicsRotation::axisChanged()
-
- This signal is emitted whenever the axis of the object changes.
-
- \sa QGraphicsRotation::axis
-*/
-
-#include "moc_qgraphicstransform.cpp"
-
-QT_END_NAMESPACE
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicstransform.h b/src/gui/graphicsview/qgraphicstransform.h
deleted file mode 100644
index e2dd05b5be..0000000000
--- a/src/gui/graphicsview/qgraphicstransform.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSTRANSFORM_H
-#define QGRAPHICSTRANSFORM_H
-
-#include <QtCore/QObject>
-#include <QtGui/QVector3D>
-#include <QtGui/QTransform>
-#include <QtGui/QMatrix4x4>
-
-#ifndef QT_NO_GRAPHICSVIEW
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QGraphicsItem;
-class QGraphicsTransformPrivate;
-
-class Q_GUI_EXPORT QGraphicsTransform : public QObject
-{
- Q_OBJECT
-public:
- QGraphicsTransform(QObject *parent = 0);
- ~QGraphicsTransform();
-
- virtual void applyTo(QMatrix4x4 *matrix) const = 0;
-
-protected Q_SLOTS:
- void update();
-
-protected:
- QGraphicsTransform(QGraphicsTransformPrivate &p, QObject *parent);
-
-private:
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
- Q_DECLARE_PRIVATE(QGraphicsTransform)
-};
-
-class QGraphicsScalePrivate;
-
-class Q_GUI_EXPORT QGraphicsScale : public QGraphicsTransform
-{
- Q_OBJECT
-
- Q_PROPERTY(QVector3D origin READ origin WRITE setOrigin NOTIFY originChanged)
- Q_PROPERTY(qreal xScale READ xScale WRITE setXScale NOTIFY xScaleChanged)
- Q_PROPERTY(qreal yScale READ yScale WRITE setYScale NOTIFY yScaleChanged)
- Q_PROPERTY(qreal zScale READ zScale WRITE setZScale NOTIFY zScaleChanged)
-public:
- QGraphicsScale(QObject *parent = 0);
- ~QGraphicsScale();
-
- QVector3D origin() const;
- void setOrigin(const QVector3D &point);
-
- qreal xScale() const;
- void setXScale(qreal);
-
- qreal yScale() const;
- void setYScale(qreal);
-
- qreal zScale() const;
- void setZScale(qreal);
-
- void applyTo(QMatrix4x4 *matrix) const;
-
-Q_SIGNALS:
- void originChanged();
- void xScaleChanged();
- void yScaleChanged();
- void zScaleChanged();
- void scaleChanged();
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsScale)
-};
-
-class QGraphicsRotationPrivate;
-
-class Q_GUI_EXPORT QGraphicsRotation : public QGraphicsTransform
-{
- Q_OBJECT
-
- Q_PROPERTY(QVector3D origin READ origin WRITE setOrigin NOTIFY originChanged)
- Q_PROPERTY(qreal angle READ angle WRITE setAngle NOTIFY angleChanged)
- Q_PROPERTY(QVector3D axis READ axis WRITE setAxis NOTIFY axisChanged)
-public:
- QGraphicsRotation(QObject *parent = 0);
- ~QGraphicsRotation();
-
- QVector3D origin() const;
- void setOrigin(const QVector3D &point);
-
- qreal angle() const;
- void setAngle(qreal);
-
- QVector3D axis() const;
- void setAxis(const QVector3D &axis);
- void setAxis(Qt::Axis axis);
-
- void applyTo(QMatrix4x4 *matrix) const;
-
-Q_SIGNALS:
- void originChanged();
- void angleChanged();
- void axisChanged();
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsRotation)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-#endif //QT_NO_GRAPHICSVIEW
-
-#endif // QFXTRANSFORM_H
diff --git a/src/gui/graphicsview/qgraphicstransform_p.h b/src/gui/graphicsview/qgraphicstransform_p.h
deleted file mode 100644
index 2a0bf859e3..0000000000
--- a/src/gui/graphicsview/qgraphicstransform_p.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSTRANSFORM_P_H
-#define QGRAPHICSTRANSFORM_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 "private/qobject_p.h"
-#ifndef QT_NO_GRAPHICSVIEW
-QT_BEGIN_NAMESPACE
-
-class QGraphicsItem;
-
-class QGraphicsTransformPrivate : public QObjectPrivate {
-public:
- Q_DECLARE_PUBLIC(QGraphicsTransform)
-
- QGraphicsTransformPrivate()
- : QObjectPrivate(), item(0) {}
-
- QGraphicsItem *item;
-
- void setItem(QGraphicsItem *item);
- static void updateItem(QGraphicsItem *item);
-};
-
-QT_END_NAMESPACE
-#endif //QT_NO_GRAPHCISVIEW
-
-#endif // QGRAPHICSTRANSFORM_P_H
diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp
deleted file mode 100644
index 488a36af49..0000000000
--- a/src/gui/graphicsview/qgraphicsview.cpp
+++ /dev/null
@@ -1,3880 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-static const int QGRAPHICSVIEW_REGION_RECT_THRESHOLD = 50;
-
-static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < 2^9
-
-/*!
- \class QGraphicsView
- \brief The QGraphicsView class provides a widget for displaying the
- contents of a QGraphicsScene.
- \since 4.2
- \ingroup graphicsview-api
-
-
- QGraphicsView visualizes the contents of a QGraphicsScene in a scrollable
- viewport. To create a scene with geometrical items, see QGraphicsScene's
- documentation. QGraphicsView is part of the \l{Graphics View Framework}.
-
- To visualize a scene, you start by constructing a QGraphicsView object,
- passing the address of the scene you want to visualize to QGraphicsView's
- constructor. Alternatively, you can call setScene() to set the scene at a
- later point. After you call show(), the view will by default scroll to the
- center of the scene and display any items that are visible at this
- point. For example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 0
-
- You can explicitly scroll to any position on the scene by using the
- scroll bars, or by calling centerOn(). By passing a point to centerOn(),
- QGraphicsView will scroll its viewport to ensure that the point is
- centered in the view. An overload is provided for scrolling to a
- QGraphicsItem, in which case QGraphicsView will see to that the center of
- the item is centered in the view. If all you want is to ensure that a
- certain area is visible, (but not necessarily centered,) you can call
- ensureVisible() instead.
-
- QGraphicsView can be used to visualize a whole scene, or only parts of it.
- The visualized area is by default detected automatically when the view is
- displayed for the first time (by calling
- QGraphicsScene::itemsBoundingRect()). To set the visualized area rectangle
- yourself, you can call setSceneRect(). This will adjust the scroll bars'
- ranges appropriately. Note that although the scene supports a virtually
- unlimited size, the range of the scroll bars will never exceed the range of
- an integer (INT_MIN, INT_MAX).
-
- QGraphicsView visualizes the scene by calling render(). By default, the
- items are drawn onto the viewport by using a regular QPainter, and using
- default render hints. To change the default render hints that
- QGraphicsView passes to QPainter when painting items, you can call
- setRenderHints().
-
- By default, QGraphicsView provides a regular QWidget for the viewport
- widget. You can access this widget by calling viewport(), or you can
- replace it by calling setViewport(). To render using OpenGL, simply call
- setViewport(new QGLWidget). QGraphicsView takes ownership of the viewport
- widget.
-
- QGraphicsView supports affine transformations, using QTransform. You can
- either pass a matrix to setTransform(), or you can call one of the
- convenience functions rotate(), scale(), translate() or shear(). The most
- two common transformations are scaling, which is used to implement
- zooming, and rotation. QGraphicsView keeps the center of the view fixed
- during a transformation. Because of the scene alignment (setAligment()),
- translating the view will have no visual impact.
-
- You can interact with the items on the scene by using the mouse and
- keyboard. QGraphicsView translates the mouse and key events into \e scene
- events, (events that inherit QGraphicsSceneEvent,), and forward them to
- the visualized scene. In the end, it's the individual item that handles
- the events and reacts to them. For example, if you click on a selectable
- item, the item will typically let the scene know that it has been
- selected, and it will also redraw itself to display a selection
- rectangle. Similiary, if you click and drag the mouse to move a movable
- item, it's the item that handles the mouse moves and moves itself. Item
- interaction is enabled by default, and you can toggle it by calling
- setInteractive().
-
- You can also provide your own custom scene interaction, by creating a
- subclass of QGraphicsView, and reimplementing the mouse and key event
- handlers. To simplify how you programmatically interact with items in the
- view, QGraphicsView provides the mapping functions mapToScene() and
- mapFromScene(), and the item accessors items() and itemAt(). These
- functions allow you to map points, rectangles, polygons and paths between
- view coordinates and scene coordinates, and to find items on the scene
- using view coordinates.
-
- \img graphicsview-view.png
-
- \sa QGraphicsScene, QGraphicsItem, QGraphicsSceneEvent
-*/
-
-/*!
- \enum QGraphicsView::ViewportAnchor
-
- This enums describe the possible anchors that QGraphicsView can
- use when the user resizes the view or when the view is
- transformed.
-
- \value NoAnchor No anchor, i.e. the view leaves the scene's
- position unchanged.
- \value AnchorViewCenter The scene point at the center of the view
- is used as the anchor.
- \value AnchorUnderMouse The point under the mouse is used as the anchor.
-
- \sa resizeAnchor, transformationAnchor
-*/
-
-/*!
- \enum QGraphicsView::ViewportUpdateMode
-
- \since 4.3
-
- This enum describes how QGraphicsView updates its viewport when the scene
- contents change or are exposed.
-
- \value FullViewportUpdate When any visible part of the scene changes or is
- reexposed, QGraphicsView will update the entire viewport. This approach is
- fastest when QGraphicsView spends more time figuring out what to draw than
- it would spend drawing (e.g., when very many small items are repeatedly
- updated). This is the preferred update mode for viewports that do not
- support partial updates, such as QGLWidget, and for viewports that need to
- disable scroll optimization.
-
- \value MinimalViewportUpdate QGraphicsView will determine the minimal
- viewport region that requires a redraw, minimizing the time spent drawing
- by avoiding a redraw of areas that have not changed. This is
- QGraphicsView's default mode. Although this approach provides the best
- performance in general, if there are many small visible changes on the
- scene, QGraphicsView might end up spending more time finding the minimal
- approach than it will spend drawing.
-
- \value SmartViewportUpdate QGraphicsView will attempt to find an optimal
- update mode by analyzing the areas that require a redraw.
-
- \value BoundingRectViewportUpdate The bounding rectangle of all changes in
- the viewport will be redrawn. This mode has the advantage that
- QGraphicsView searches only one region for changes, minimizing time spent
- determining what needs redrawing. The disadvantage is that areas that have
- not changed also need to be redrawn.
-
- \value NoViewportUpdate QGraphicsView will never update its viewport when
- the scene changes; the user is expected to control all updates. This mode
- disables all (potentially slow) item visibility testing in QGraphicsView,
- and is suitable for scenes that either require a fixed frame rate, or where
- the viewport is otherwise updated externally.
-
- \sa viewportUpdateMode
-*/
-
-/*!
- \enum QGraphicsView::OptimizationFlag
-
- \since 4.3
-
- This enum describes flags that you can enable to improve rendering
- performance in QGraphicsView. By default, none of these flags are set.
- Note that setting a flag usually imposes a side effect, and this effect
- can vary between paint devices and platforms.
-
- \value DontClipPainter This value is obsolete and has no effect.
-
- \value DontSavePainterState When rendering, QGraphicsView protects the
- painter state (see QPainter::save()) when rendering the background or
- foreground, and when rendering each item. This allows you to leave the
- painter in an altered state (i.e., you can call QPainter::setPen() or
- QPainter::setBrush() without restoring the state after painting). However,
- if the items consistently do restore the state, you should enable this
- flag to prevent QGraphicsView from doing the same.
-
- \value DontAdjustForAntialiasing Disables QGraphicsView's antialiasing
- auto-adjustment of exposed areas. Items that render antialiased lines on
- the boundaries of their QGraphicsItem::boundingRect() can end up rendering
- parts of the line outside. To prevent rendering artifacts, QGraphicsView
- expands all exposed regions by 2 pixels in all directions. If you enable
- this flag, QGraphicsView will no longer perform these adjustments,
- minimizing the areas that require redrawing, which improves performance. A
- common side effect is that items that do draw with antialiasing can leave
- painting traces behind on the scene as they are moved.
-
- \value IndirectPainting Since Qt 4.6, restore the old painting algorithm
- that calls QGraphicsView::drawItems() and QGraphicsScene::drawItems().
- To be used only for compatibility with old code.
-*/
-
-/*!
- \enum QGraphicsView::CacheModeFlag
-
- This enum describes the flags that you can set for a QGraphicsView's cache
- mode.
-
- \value CacheNone All painting is done directly onto the viewport.
-
- \value CacheBackground The background is cached. This affects both custom
- backgrounds, and backgrounds based on the backgroundBrush property. When
- this flag is enabled, QGraphicsView will allocate one pixmap with the full
- size of the viewport.
-
- \sa cacheMode
-*/
-
-/*!
- \enum QGraphicsView::DragMode
-
- This enum describes the default action for the view when pressing and
- dragging the mouse over the viewport.
-
- \value NoDrag Nothing happens; the mouse event is ignored.
-
- \value ScrollHandDrag The cursor changes into a pointing hand, and
- dragging the mouse around will scroll the scrolbars. This mode works both
- in \l{QGraphicsView::interactive}{interactive} and non-interactive mode.
-
- \value RubberBandDrag A rubber band will appear. Dragging the mouse will
- set the rubber band geometry, and all items covered by the rubber band are
- selected. This mode is disabled for non-interactive views.
-
- \sa dragMode, QGraphicsScene::setSelectionArea()
-*/
-
-#include "qgraphicsview.h"
-#include "qgraphicsview_p.h"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicsitem.h"
-#include "qgraphicsitem_p.h"
-#include "qgraphicsscene.h"
-#include "qgraphicsscene_p.h"
-#include "qgraphicssceneevent.h"
-#include "qgraphicswidget.h"
-
-#include <QtCore/qdatetime.h>
-#include <QtCore/qdebug.h>
-#include <QtCore/qmath.h>
-#include <QtGui/qapplication.h>
-#include <QtGui/qdesktopwidget.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qlayout.h>
-#include <QtGui/qtransform.h>
-#include <QtGui/qmatrix.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qscrollbar.h>
-#include <QtGui/qstyleoption.h>
-#include <QtGui/qinputcontext.h>
-#ifdef Q_WS_X11
-#include <QtGui/qpaintengine.h>
-#include <private/qt_x11_p.h>
-#endif
-
-#include <private/qevent_p.h>
-
-QT_BEGIN_NAMESPACE
-
-bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
-
-inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for single precision
-{
- if (d <= (qreal) INT_MIN)
- return INT_MIN;
- else if (d >= (qreal) INT_MAX)
- return INT_MAX;
- return d >= 0.0 ? int(d + 0.5) : int(d - int(d-1) + 0.5) + int(d-1);
-}
-
-void QGraphicsViewPrivate::translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent)
-{
- QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
- for (int i = 0; i < touchPoints.count(); ++i) {
- QTouchEvent::TouchPoint &touchPoint = touchPoints[i];
- // the scene will set the item local pos, startPos, lastPos, and rect before delivering to
- // an item, but for now those functions are returning the view's local coordinates
- touchPoint.setSceneRect(d->mapToScene(touchPoint.rect()));
- touchPoint.setStartScenePos(d->mapToScene(touchPoint.startPos()));
- touchPoint.setLastScenePos(d->mapToScene(touchPoint.lastPos()));
-
- // screenPos, startScreenPos, lastScreenPos, and screenRect are already set
- }
-
- touchEvent->setTouchPoints(touchPoints);
-}
-
-/*!
- \internal
-*/
-QGraphicsViewPrivate::QGraphicsViewPrivate()
- : renderHints(QPainter::TextAntialiasing),
- dragMode(QGraphicsView::NoDrag),
- sceneInteractionAllowed(true), hasSceneRect(false),
- connectedToScene(false),
- useLastMouseEvent(false),
- identityMatrix(true),
- dirtyScroll(true),
- accelerateScrolling(true),
- keepLastCenterPoint(true),
- transforming(false),
- handScrolling(false),
- mustAllocateStyleOptions(false),
- mustResizeBackgroundPixmap(true),
- fullUpdatePending(true),
- hasUpdateClip(false),
- mousePressButton(Qt::NoButton),
- leftIndent(0), topIndent(0),
- lastMouseEvent(QEvent::None, QPoint(), Qt::NoButton, 0, 0),
- alignment(Qt::AlignCenter),
- transformationAnchor(QGraphicsView::AnchorViewCenter), resizeAnchor(QGraphicsView::NoAnchor),
- viewportUpdateMode(QGraphicsView::MinimalViewportUpdate),
- optimizationFlags(0),
- scene(0),
-#ifndef QT_NO_RUBBERBAND
- rubberBanding(false),
- rubberBandSelectionMode(Qt::IntersectsItemShape),
-#endif
- handScrollMotions(0), cacheMode(0),
-#ifndef QT_NO_CURSOR
- hasStoredOriginalCursor(false),
-#endif
- lastDragDropEvent(0),
- updateSceneSlotReimplementedChecked(false)
-{
- styleOptions.reserve(QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS);
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::recalculateContentSize()
-{
- Q_Q(QGraphicsView);
-
- QSize maxSize = q->maximumViewportSize();
- int width = maxSize.width();
- int height = maxSize.height();
- QRectF viewRect = matrix.mapRect(q->sceneRect());
-
- bool frameOnlyAround = (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, 0, q));
- if (frameOnlyAround) {
- if (hbarpolicy == Qt::ScrollBarAlwaysOn)
- height -= frameWidth * 2;
- if (vbarpolicy == Qt::ScrollBarAlwaysOn)
- width -= frameWidth * 2;
- }
-
- // Adjust the maximum width and height of the viewport based on the width
- // of visible scroll bars.
- int scrollBarExtent = q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q);
- if (frameOnlyAround)
- scrollBarExtent += frameWidth * 2;
-
- bool useHorizontalScrollBar = (viewRect.width() > width) && hbarpolicy != Qt::ScrollBarAlwaysOff;
- bool useVerticalScrollBar = (viewRect.height() > height) && vbarpolicy != Qt::ScrollBarAlwaysOff;
- if (useHorizontalScrollBar && !useVerticalScrollBar) {
- if (viewRect.height() > height - scrollBarExtent)
- useVerticalScrollBar = true;
- }
- if (useVerticalScrollBar && !useHorizontalScrollBar) {
- if (viewRect.width() > width - scrollBarExtent)
- useHorizontalScrollBar = true;
- }
- if (useHorizontalScrollBar && hbarpolicy != Qt::ScrollBarAlwaysOn)
- height -= scrollBarExtent;
- if (useVerticalScrollBar && vbarpolicy != Qt::ScrollBarAlwaysOn)
- width -= scrollBarExtent;
-
- // Setting the ranges of these scroll bars can/will cause the values to
- // change, and scrollContentsBy() will be called correspondingly. This
- // will reset the last center point.
- QPointF savedLastCenterPoint = lastCenterPoint;
-
- // Remember the former indent settings
- qreal oldLeftIndent = leftIndent;
- qreal oldTopIndent = topIndent;
-
- // If the whole scene fits horizontally, we center the scene horizontally,
- // and ignore the horizontal scroll bars.
- int left = q_round_bound(viewRect.left());
- int right = q_round_bound(viewRect.right() - width);
- if (left >= right) {
- hbar->setRange(0, 0);
-
- switch (alignment & Qt::AlignHorizontal_Mask) {
- case Qt::AlignLeft:
- leftIndent = -viewRect.left();
- break;
- case Qt::AlignRight:
- leftIndent = width - viewRect.width() - viewRect.left() - 1;
- break;
- case Qt::AlignHCenter:
- default:
- leftIndent = width / 2 - (viewRect.left() + viewRect.right()) / 2;
- break;
- }
- } else {
- hbar->setRange(left, right);
- hbar->setPageStep(width);
- hbar->setSingleStep(width / 20);
- leftIndent = 0;
- }
-
- // If the whole scene fits vertically, we center the scene vertically, and
- // ignore the vertical scroll bars.
- int top = q_round_bound(viewRect.top());
- int bottom = q_round_bound(viewRect.bottom() - height);
- if (top >= bottom) {
- vbar->setRange(0, 0);
-
- switch (alignment & Qt::AlignVertical_Mask) {
- case Qt::AlignTop:
- topIndent = -viewRect.top();
- break;
- case Qt::AlignBottom:
- topIndent = height - viewRect.height() - viewRect.top() - 1;
- break;
- case Qt::AlignVCenter:
- default:
- topIndent = height / 2 - (viewRect.top() + viewRect.bottom()) / 2;
- break;
- }
- } else {
- vbar->setRange(top, bottom);
- vbar->setPageStep(height);
- vbar->setSingleStep(height / 20);
- topIndent = 0;
- }
-
- // Restorethe center point from before the ranges changed.
- lastCenterPoint = savedLastCenterPoint;
-
- // Issue a full update if the indents change.
- // ### If the transform is still the same, we can get away with just a
- // scroll instead.
- if (oldLeftIndent != leftIndent || oldTopIndent != topIndent) {
- dirtyScroll = true;
- updateAll();
- } else if (q->isRightToLeft() && !leftIndent) {
- // In reverse mode, the horizontal scroll always changes after the content
- // size has changed, as the scroll is calculated by summing the min and
- // max values of the range and subtracting the current value. In normal
- // mode the scroll remains unchanged unless the indent has changed.
- dirtyScroll = true;
- }
-
- if (cacheMode & QGraphicsView::CacheBackground) {
- // Invalidate the background pixmap
- mustResizeBackgroundPixmap = true;
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor)
-{
- Q_Q(QGraphicsView);
- switch (anchor) {
- case QGraphicsView::AnchorUnderMouse: {
- if (q->underMouse()) {
- // Last scene pos: lastMouseMoveScenePoint
- // Current mouse pos:
- QPointF transformationDiff = q->mapToScene(viewport->rect().center())
- - q->mapToScene(viewport->mapFromGlobal(QCursor::pos()));
- q->centerOn(lastMouseMoveScenePoint + transformationDiff);
- } else {
- q->centerOn(lastCenterPoint);
- }
- break;
- }
- case QGraphicsView::AnchorViewCenter:
- q->centerOn(lastCenterPoint);
- break;
- case QGraphicsView::NoAnchor:
- break;
- }
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::updateLastCenterPoint()
-{
- Q_Q(QGraphicsView);
- lastCenterPoint = q->mapToScene(viewport->rect().center());
-}
-
-/*!
- \internal
-
- Returns the horizontal scroll value (the X value of the left edge of the
- viewport).
-*/
-qint64 QGraphicsViewPrivate::horizontalScroll() const
-{
- if (dirtyScroll)
- const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
- return scrollX;
-}
-
-/*!
- \internal
-
- Returns the vertical scroll value (the X value of the top edge of the
- viewport).
-*/
-qint64 QGraphicsViewPrivate::verticalScroll() const
-{
- if (dirtyScroll)
- const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
- return scrollY;
-}
-
-/*!
- \internal
-
- Maps the given rectangle to the scene using QTransform::mapRect()
-*/
-QRectF QGraphicsViewPrivate::mapRectToScene(const QRect &rect) const
-{
- if (dirtyScroll)
- const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
- QRectF scrolled = QRectF(rect.translated(scrollX, scrollY));
- return identityMatrix ? scrolled : matrix.inverted().mapRect(scrolled);
-}
-
-
-/*!
- \internal
-
- Maps the given rectangle from the scene using QTransform::mapRect()
-*/
-QRectF QGraphicsViewPrivate::mapRectFromScene(const QRectF &rect) const
-{
- if (dirtyScroll)
- const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
- return (identityMatrix ? rect : matrix.mapRect(rect)).translated(-scrollX, -scrollY);
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::updateScroll()
-{
- Q_Q(QGraphicsView);
- scrollX = qint64(-leftIndent);
- if (q->isRightToLeft()) {
- if (!leftIndent) {
- scrollX += hbar->minimum();
- scrollX += hbar->maximum();
- scrollX -= hbar->value();
- }
- } else {
- scrollX += hbar->value();
- }
-
- scrollY = qint64(vbar->value() - topIndent);
-
- dirtyScroll = false;
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::replayLastMouseEvent()
-{
- if (!useLastMouseEvent || !scene)
- return;
- mouseMoveEventHandler(&lastMouseEvent);
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::storeMouseEvent(QMouseEvent *event)
-{
- useLastMouseEvent = true;
- lastMouseEvent = QMouseEvent(QEvent::MouseMove, event->pos(), event->globalPos(),
- event->button(), event->buttons(), event->modifiers());
-}
-
-void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
-{
- Q_Q(QGraphicsView);
-
- storeMouseEvent(event);
- lastMouseEvent.setAccepted(false);
-
- if (!sceneInteractionAllowed)
- return;
- if (handScrolling)
- return;
- if (!scene)
- return;
-
- QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);
- mouseEvent.setWidget(viewport);
- mouseEvent.setButtonDownScenePos(mousePressButton, mousePressScenePoint);
- mouseEvent.setButtonDownScreenPos(mousePressButton, mousePressScreenPoint);
- mouseEvent.setScenePos(q->mapToScene(event->pos()));
- mouseEvent.setScreenPos(event->globalPos());
- mouseEvent.setLastScenePos(lastMouseMoveScenePoint);
- mouseEvent.setLastScreenPos(lastMouseMoveScreenPoint);
- mouseEvent.setButtons(event->buttons());
- mouseEvent.setButton(event->button());
- mouseEvent.setModifiers(event->modifiers());
- lastMouseMoveScenePoint = mouseEvent.scenePos();
- lastMouseMoveScreenPoint = mouseEvent.screenPos();
- mouseEvent.setAccepted(false);
- if (event->spontaneous())
- qt_sendSpontaneousEvent(scene, &mouseEvent);
- else
- QApplication::sendEvent(scene, &mouseEvent);
-
- // Remember whether the last event was accepted or not.
- lastMouseEvent.setAccepted(mouseEvent.isAccepted());
-
- if (mouseEvent.isAccepted() && mouseEvent.buttons() != 0) {
- // The event was delivered to a mouse grabber; the press is likely to
- // have set a cursor, and we must not change it.
- return;
- }
-
-#ifndef QT_NO_CURSOR
- // If all the items ignore hover events, we don't look-up any items
- // in QGraphicsScenePrivate::dispatchHoverEvent, hence the
- // cachedItemsUnderMouse list will be empty. We therefore do the look-up
- // for cursor items here if not all items use the default cursor.
- if (scene->d_func()->allItemsIgnoreHoverEvents && !scene->d_func()->allItemsUseDefaultCursor
- && scene->d_func()->cachedItemsUnderMouse.isEmpty()) {
- scene->d_func()->cachedItemsUnderMouse = scene->d_func()->itemsAtPosition(mouseEvent.screenPos(),
- mouseEvent.scenePos(),
- mouseEvent.widget());
- }
- // Find the topmost item under the mouse with a cursor.
- foreach (QGraphicsItem *item, scene->d_func()->cachedItemsUnderMouse) {
- if (item->hasCursor()) {
- _q_setViewportCursor(item->cursor());
- return;
- }
- }
-
- // No items with cursors found; revert to the view cursor.
- if (hasStoredOriginalCursor) {
- // Restore the original viewport cursor.
- hasStoredOriginalCursor = false;
- viewport->setCursor(originalCursor);
- }
-#endif
-}
-
-/*!
- \internal
-*/
-#ifndef QT_NO_RUBBERBAND
-QRegion QGraphicsViewPrivate::rubberBandRegion(const QWidget *widget, const QRect &rect) const
-{
- QStyleHintReturnMask mask;
- QStyleOptionRubberBand option;
- option.initFrom(widget);
- option.rect = rect;
- option.opaque = false;
- option.shape = QRubberBand::Rectangle;
-
- QRegion tmp;
- tmp += rect;
- if (widget->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, widget, &mask))
- tmp &= mask.region;
- return tmp;
-}
-#endif
-
-/*!
- \internal
-*/
-#ifndef QT_NO_CURSOR
-void QGraphicsViewPrivate::_q_setViewportCursor(const QCursor &cursor)
-{
- if (!hasStoredOriginalCursor) {
- hasStoredOriginalCursor = true;
- originalCursor = viewport->cursor();
- }
- viewport->setCursor(cursor);
-}
-#endif
-
-/*!
- \internal
-*/
-#ifndef QT_NO_CURSOR
-void QGraphicsViewPrivate::_q_unsetViewportCursor()
-{
- Q_Q(QGraphicsView);
- foreach (QGraphicsItem *item, q->items(lastMouseEvent.pos())) {
- if (item->hasCursor()) {
- _q_setViewportCursor(item->cursor());
- return;
- }
- }
-
- // Restore the original viewport cursor.
- if (hasStoredOriginalCursor) {
- hasStoredOriginalCursor = false;
- if (dragMode == QGraphicsView::ScrollHandDrag)
- viewport->setCursor(Qt::OpenHandCursor);
- else
- viewport->setCursor(originalCursor);
- }
-}
-#endif
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::storeDragDropEvent(const QGraphicsSceneDragDropEvent *event)
-{
- delete lastDragDropEvent;
- lastDragDropEvent = new QGraphicsSceneDragDropEvent(event->type());
- lastDragDropEvent->setScenePos(event->scenePos());
- lastDragDropEvent->setScreenPos(event->screenPos());
- lastDragDropEvent->setButtons(event->buttons());
- lastDragDropEvent->setModifiers(event->modifiers());
- lastDragDropEvent->setPossibleActions(event->possibleActions());
- lastDragDropEvent->setProposedAction(event->proposedAction());
- lastDragDropEvent->setDropAction(event->dropAction());
- lastDragDropEvent->setMimeData(event->mimeData());
- lastDragDropEvent->setWidget(event->widget());
- lastDragDropEvent->setSource(event->source());
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::populateSceneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
- QDropEvent *source)
-{
-#ifndef QT_NO_DRAGANDDROP
- Q_Q(QGraphicsView);
- dest->setScenePos(q->mapToScene(source->pos()));
- dest->setScreenPos(q->mapToGlobal(source->pos()));
- dest->setButtons(source->mouseButtons());
- dest->setModifiers(source->keyboardModifiers());
- dest->setPossibleActions(source->possibleActions());
- dest->setProposedAction(source->proposedAction());
- dest->setDropAction(source->dropAction());
- dest->setMimeData(source->mimeData());
- dest->setWidget(viewport);
- dest->setSource(source->source());
-#else
- Q_UNUSED(dest)
- Q_UNUSED(source)
-#endif
-}
-
-/*!
- \internal
-*/
-QRect QGraphicsViewPrivate::mapToViewRect(const QGraphicsItem *item, const QRectF &rect) const
-{
- Q_Q(const QGraphicsView);
- if (dirtyScroll)
- const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
-
- if (item->d_ptr->itemIsUntransformable()) {
- QTransform itv = item->deviceTransform(q->viewportTransform());
- return itv.mapRect(rect).toAlignedRect();
- }
-
- // Translate-only
- // COMBINE
- QPointF offset;
- const QGraphicsItem *parentItem = item;
- const QGraphicsItemPrivate *itemd;
- do {
- itemd = parentItem->d_ptr.data();
- if (itemd->transformData)
- break;
- offset += itemd->pos;
- } while ((parentItem = itemd->parent));
-
- QRectF baseRect = rect.translated(offset.x(), offset.y());
- if (!parentItem) {
- if (identityMatrix) {
- baseRect.translate(-scrollX, -scrollY);
- return baseRect.toAlignedRect();
- }
- return matrix.mapRect(baseRect).translated(-scrollX, -scrollY).toAlignedRect();
- }
-
- QTransform tr = parentItem->sceneTransform();
- if (!identityMatrix)
- tr *= matrix;
- QRectF r = tr.mapRect(baseRect);
- r.translate(-scrollX, -scrollY);
- return r.toAlignedRect();
-}
-
-/*!
- \internal
-*/
-QRegion QGraphicsViewPrivate::mapToViewRegion(const QGraphicsItem *item, const QRectF &rect) const
-{
- Q_Q(const QGraphicsView);
- if (dirtyScroll)
- const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
-
- // Accurate bounding region
- QTransform itv = item->deviceTransform(q->viewportTransform());
- return item->boundingRegion(itv) & itv.mapRect(rect).toAlignedRect();
-}
-
-/*!
- \internal
-*/
-void QGraphicsViewPrivate::processPendingUpdates()
-{
- if (!scene)
- return;
-
- if (fullUpdatePending) {
- viewport->update();
- } else if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) {
- viewport->update(dirtyBoundingRect);
- } else {
- viewport->update(dirtyRegion); // Already adjusted in updateRect/Region.
- }
-
- dirtyBoundingRect = QRect();
- dirtyRegion = QRegion();
-}
-
-static inline bool intersectsViewport(const QRect &r, int width, int height)
-{ return !(r.left() > width) && !(r.right() < 0) && !(r.top() >= height) && !(r.bottom() < 0); }
-
-static inline bool containsViewport(const QRect &r, int width, int height)
-{ return r.left() <= 0 && r.top() <= 0 && r.right() >= width - 1 && r.bottom() >= height - 1; }
-
-static inline void QRect_unite(QRect *rect, const QRect &other)
-{
- if (rect->isEmpty()) {
- *rect = other;
- } else {
- rect->setCoords(qMin(rect->left(), other.left()), qMin(rect->top(), other.top()),
- qMax(rect->right(), other.right()), qMax(rect->bottom(), other.bottom()));
- }
-}
-
-/*
- Calling this function results in update rects being clipped to the item's
- bounding rect. Note that updates prior to this function call is not clipped.
- The clip is removed by passing 0.
-*/
-void QGraphicsViewPrivate::setUpdateClip(QGraphicsItem *item)
-{
- Q_Q(QGraphicsView);
- // We simply ignore the request if the update mode is either FullViewportUpdate
- // or NoViewportUpdate; in that case there's no point in clipping anything.
- if (!item || viewportUpdateMode == QGraphicsView::NoViewportUpdate
- || viewportUpdateMode == QGraphicsView::FullViewportUpdate) {
- hasUpdateClip = false;
- return;
- }
-
- // Calculate the clip (item's bounding rect in view coordinates).
- // Optimized version of:
- // QRect clip = item->deviceTransform(q->viewportTransform())
- // .mapRect(item->boundingRect()).toAlignedRect();
- QRect clip;
- if (item->d_ptr->itemIsUntransformable()) {
- QTransform xform = item->deviceTransform(q->viewportTransform());
- clip = xform.mapRect(item->boundingRect()).toAlignedRect();
- } else if (item->d_ptr->sceneTransformTranslateOnly && identityMatrix) {
- QRectF r(item->boundingRect());
- r.translate(item->d_ptr->sceneTransform.dx() - horizontalScroll(),
- item->d_ptr->sceneTransform.dy() - verticalScroll());
- clip = r.toAlignedRect();
- } else if (!q->isTransformed()) {
- clip = item->d_ptr->sceneTransform.mapRect(item->boundingRect()).toAlignedRect();
- } else {
- QTransform xform = item->d_ptr->sceneTransform;
- xform *= q->viewportTransform();
- clip = xform.mapRect(item->boundingRect()).toAlignedRect();
- }
-
- if (hasUpdateClip) {
- // Intersect with old clip.
- updateClip &= clip;
- } else {
- updateClip = clip;
- hasUpdateClip = true;
- }
-}
-
-bool QGraphicsViewPrivate::updateRegion(const QRectF &rect, const QTransform &xform)
-{
- if (rect.isEmpty())
- return false;
-
- if (viewportUpdateMode != QGraphicsView::MinimalViewportUpdate
- && viewportUpdateMode != QGraphicsView::SmartViewportUpdate) {
- // No point in updating with QRegion granularity; use the rect instead.
- return updateRectF(xform.mapRect(rect));
- }
-
- // Update mode is either Minimal or Smart, so we have to do a potentially slow operation,
- // which is clearly documented here: QGraphicsItem::setBoundingRegionGranularity.
- const QRegion region = xform.map(QRegion(rect.toAlignedRect()));
- QRect viewRect = region.boundingRect();
- const bool dontAdjustForAntialiasing = optimizationFlags & QGraphicsView::DontAdjustForAntialiasing;
- if (dontAdjustForAntialiasing)
- viewRect.adjust(-1, -1, 1, 1);
- else
- viewRect.adjust(-2, -2, 2, 2);
- if (!intersectsViewport(viewRect, viewport->width(), viewport->height()))
- return false; // Update region for sure outside viewport.
-
- const QVector<QRect> &rects = region.rects();
- for (int i = 0; i < rects.size(); ++i) {
- viewRect = rects.at(i);
- if (dontAdjustForAntialiasing)
- viewRect.adjust(-1, -1, 1, 1);
- else
- viewRect.adjust(-2, -2, 2, 2);
- if (hasUpdateClip)
- viewRect &= updateClip;
- dirtyRegion += viewRect;
- }
-
- return true;
-}
-
-// NB! Assumes the rect 'r' is already aligned and adjusted for antialiasing.
-// For QRectF use updateRectF(const QRectF &) to ensure proper adjustments.
-bool QGraphicsViewPrivate::updateRect(const QRect &r)
-{
- if (fullUpdatePending || viewportUpdateMode == QGraphicsView::NoViewportUpdate
- || !intersectsViewport(r, viewport->width(), viewport->height())) {
- return false;
- }
-
- switch (viewportUpdateMode) {
- case QGraphicsView::FullViewportUpdate:
- fullUpdatePending = true;
- viewport->update();
- break;
- case QGraphicsView::BoundingRectViewportUpdate:
- if (hasUpdateClip)
- QRect_unite(&dirtyBoundingRect, r & updateClip);
- else
- QRect_unite(&dirtyBoundingRect, r);
- if (containsViewport(dirtyBoundingRect, viewport->width(), viewport->height())) {
- fullUpdatePending = true;
- viewport->update();
- }
- break;
- case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE
- case QGraphicsView::MinimalViewportUpdate:
- if (hasUpdateClip)
- dirtyRegion += r & updateClip;
- else
- dirtyRegion += r;
- break;
- default:
- break;
- }
-
- return true;
-}
-
-QStyleOptionGraphicsItem *QGraphicsViewPrivate::allocStyleOptionsArray(int numItems)
-{
- if (mustAllocateStyleOptions || (numItems > styleOptions.capacity()))
- // too many items, let's allocate on-the-fly
- return new QStyleOptionGraphicsItem[numItems];
-
- // expand only whenever necessary
- if (numItems > styleOptions.size())
- styleOptions.resize(numItems);
-
- mustAllocateStyleOptions = true;
- return styleOptions.data();
-}
-
-void QGraphicsViewPrivate::freeStyleOptionsArray(QStyleOptionGraphicsItem *array)
-{
- mustAllocateStyleOptions = false;
- if (array != styleOptions.data())
- delete [] array;
-}
-
-extern QPainterPath qt_regionToPath(const QRegion &region);
-
-/*!
- ### Adjustments in findItems: mapToScene(QRect) forces us to adjust the
- input rectangle by (0, 0, 1, 1), because it uses QRect::bottomRight()
- (etc) when mapping the rectangle to a polygon (which is _wrong_). In
- addition, as QGraphicsItem::boundingRect() is defined in logical space,
- but the default pen for QPainter is cosmetic with a width of 0, QPainter
- is at risk of painting 1 pixel outside the bounding rect. Therefore we
- must search for items with an adjustment of (-1, -1, 1, 1).
-*/
-QList<QGraphicsItem *> QGraphicsViewPrivate::findItems(const QRegion &exposedRegion, bool *allItems,
- const QTransform &viewTransform) const
-{
- Q_Q(const QGraphicsView);
-
- // Step 1) If all items are contained within the expose region, then
- // return a list of all visible items. ### the scene's growing bounding
- // rect does not take into account untransformable items.
- const QRectF exposedRegionSceneBounds = q->mapToScene(exposedRegion.boundingRect().adjusted(-1, -1, 1, 1))
- .boundingRect();
- if (exposedRegionSceneBounds.contains(scene->sceneRect())) {
- Q_ASSERT(allItems);
- *allItems = true;
-
- // All items are guaranteed within the exposed region.
- return scene->items(Qt::AscendingOrder);
- }
-
- // Step 2) If the expose region is a simple rect and the view is only
- // translated or scaled, search for items using
- // QGraphicsScene::items(QRectF).
- bool simpleRectLookup = exposedRegion.rectCount() == 1 && matrix.type() <= QTransform::TxScale;
- if (simpleRectLookup) {
- return scene->items(exposedRegionSceneBounds,
- Qt::IntersectsItemBoundingRect,
- Qt::AscendingOrder, viewTransform);
- }
-
- // If the region is complex or the view has a complex transform, adjust
- // the expose region, convert it to a path, and then search for items
- // using QGraphicsScene::items(QPainterPath);
- QRegion adjustedRegion;
- foreach (const QRect &r, exposedRegion.rects())
- adjustedRegion += r.adjusted(-1, -1, 1, 1);
-
- const QPainterPath exposedScenePath(q->mapToScene(qt_regionToPath(adjustedRegion)));
- return scene->items(exposedScenePath, Qt::IntersectsItemBoundingRect,
- Qt::AscendingOrder, viewTransform);
-}
-
-/*!
- \internal
-
- Enables input methods for the view if and only if the current focus item of
- the scene accepts input methods. Call function whenever that condition has
- potentially changed.
-*/
-void QGraphicsViewPrivate::updateInputMethodSensitivity()
-{
- Q_Q(QGraphicsView);
- QGraphicsItem *focusItem = 0;
- bool enabled = scene && (focusItem = scene->focusItem())
- && (focusItem->d_ptr->flags & QGraphicsItem::ItemAcceptsInputMethod);
- q->setAttribute(Qt::WA_InputMethodEnabled, enabled);
- q->viewport()->setAttribute(Qt::WA_InputMethodEnabled, enabled);
-
- if (!enabled) {
- q->setInputMethodHints(0);
- return;
- }
-
- QGraphicsProxyWidget *proxy = focusItem->d_ptr->isWidget && focusItem->d_ptr->isProxyWidget()
- ? static_cast<QGraphicsProxyWidget *>(focusItem) : 0;
- if (!proxy) {
- q->setInputMethodHints(focusItem->inputMethodHints());
- } else if (QWidget *widget = proxy->widget()) {
- if (QWidget *fw = widget->focusWidget())
- widget = fw;
- q->setInputMethodHints(widget->inputMethodHints());
- } else {
- q->setInputMethodHints(0);
- }
-}
-
-/*!
- Constructs a QGraphicsView. \a parent is passed to QWidget's constructor.
-*/
-QGraphicsView::QGraphicsView(QWidget *parent)
- : QAbstractScrollArea(*new QGraphicsViewPrivate, parent)
-{
- setViewport(0);
- setAcceptDrops(true);
- setBackgroundRole(QPalette::Base);
- // Investigate leaving these disabled by default.
- setAttribute(Qt::WA_InputMethodEnabled);
- viewport()->setAttribute(Qt::WA_InputMethodEnabled);
-}
-
-/*!
- Constructs a QGraphicsView and sets the visualized scene to \a
- scene. \a parent is passed to QWidget's constructor.
-*/
-QGraphicsView::QGraphicsView(QGraphicsScene *scene, QWidget *parent)
- : QAbstractScrollArea(*new QGraphicsViewPrivate, parent)
-{
- setScene(scene);
- setViewport(0);
- setAcceptDrops(true);
- setBackgroundRole(QPalette::Base);
- // Investigate leaving these disabled by default.
- setAttribute(Qt::WA_InputMethodEnabled);
- viewport()->setAttribute(Qt::WA_InputMethodEnabled);
-}
-
-/*!
- \internal
- */
-QGraphicsView::QGraphicsView(QGraphicsViewPrivate &dd, QWidget *parent)
- : QAbstractScrollArea(dd, parent)
-{
- setViewport(0);
- setAcceptDrops(true);
- setBackgroundRole(QPalette::Base);
- // Investigate leaving these disabled by default.
- setAttribute(Qt::WA_InputMethodEnabled);
- viewport()->setAttribute(Qt::WA_InputMethodEnabled);
-}
-
-/*!
- Destructs the QGraphicsView object.
-*/
-QGraphicsView::~QGraphicsView()
-{
- Q_D(QGraphicsView);
- if (d->scene)
- d->scene->d_func()->views.removeAll(this);
- delete d->lastDragDropEvent;
-}
-
-/*!
- \reimp
-*/
-QSize QGraphicsView::sizeHint() const
-{
- Q_D(const QGraphicsView);
- if (d->scene) {
- QSizeF baseSize = d->matrix.mapRect(sceneRect()).size();
- baseSize += QSizeF(d->frameWidth * 2, d->frameWidth * 2);
- return baseSize.boundedTo((3 * QApplication::desktop()->size()) / 4).toSize();
- }
- return QAbstractScrollArea::sizeHint();
-}
-
-/*!
- \property QGraphicsView::renderHints
- \brief the default render hints for the view
-
- These hints are
- used to initialize QPainter before each visible item is drawn. QPainter
- uses render hints to toggle rendering features such as antialiasing and
- smooth pixmap transformation.
-
- QPainter::TextAntialiasing is enabled by default.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 1
-*/
-QPainter::RenderHints QGraphicsView::renderHints() const
-{
- Q_D(const QGraphicsView);
- return d->renderHints;
-}
-void QGraphicsView::setRenderHints(QPainter::RenderHints hints)
-{
- Q_D(QGraphicsView);
- if (hints == d->renderHints)
- return;
- d->renderHints = hints;
- d->updateAll();
-}
-
-/*!
- If \a enabled is true, the render hint \a hint is enabled; otherwise it
- is disabled.
-
- \sa renderHints
-*/
-void QGraphicsView::setRenderHint(QPainter::RenderHint hint, bool enabled)
-{
- Q_D(QGraphicsView);
- QPainter::RenderHints oldHints = d->renderHints;
- if (enabled)
- d->renderHints |= hint;
- else
- d->renderHints &= ~hint;
- if (oldHints != d->renderHints)
- d->updateAll();
-}
-
-/*!
- \property QGraphicsView::alignment
- \brief the alignment of the scene in the view when the whole
- scene is visible.
-
- If the whole scene is visible in the view, (i.e., there are no visible
- scroll bars,) the view's alignment will decide where the scene will be
- rendered in the view. For example, if the alignment is Qt::AlignCenter,
- which is default, the scene will be centered in the view, and if the
- alignment is (Qt::AlignLeft | Qt::AlignTop), the scene will be rendered in
- the top-left corner of the view.
-*/
-Qt::Alignment QGraphicsView::alignment() const
-{
- Q_D(const QGraphicsView);
- return d->alignment;
-}
-void QGraphicsView::setAlignment(Qt::Alignment alignment)
-{
- Q_D(QGraphicsView);
- if (d->alignment != alignment) {
- d->alignment = alignment;
- d->recalculateContentSize();
- }
-}
-
-/*!
- \property QGraphicsView::transformationAnchor
- \brief how the view should position the scene during transformations.
-
- QGraphicsView uses this property to decide how to position the scene in
- the viewport when the transformation matrix changes, and the coordinate
- system of the view is transformed. The default behavior, AnchorViewCenter,
- ensures that the scene point at the center of the view remains unchanged
- during transformations (e.g., when rotating, the scene will appear to
- rotate around the center of the view).
-
- Note that the effect of this property is noticeable when only a part of the
- scene is visible (i.e., when there are scroll bars). Otherwise, if the
- whole scene fits in the view, QGraphicsScene uses the view \l alignment to
- position the scene in the view.
-
- \sa alignment, resizeAnchor
-*/
-QGraphicsView::ViewportAnchor QGraphicsView::transformationAnchor() const
-{
- Q_D(const QGraphicsView);
- return d->transformationAnchor;
-}
-void QGraphicsView::setTransformationAnchor(ViewportAnchor anchor)
-{
- Q_D(QGraphicsView);
- d->transformationAnchor = anchor;
-
- // Ensure mouse tracking is enabled in the case we are using AnchorUnderMouse
- // in order to have up-to-date information for centering the view.
- if (d->transformationAnchor == AnchorUnderMouse)
- d->viewport->setMouseTracking(true);
-}
-
-/*!
- \property QGraphicsView::resizeAnchor
- \brief how the view should position the scene when the view is resized.
-
- QGraphicsView uses this property to decide how to position the scene in
- the viewport when the viewport widget's size changes. The default
- behavior, NoAnchor, leaves the scene's position unchanged during a resize;
- the top-left corner of the view will appear to be anchored while resizing.
-
- Note that the effect of this property is noticeable when only a part of the
- scene is visible (i.e., when there are scroll bars). Otherwise, if the
- whole scene fits in the view, QGraphicsScene uses the view \l alignment to
- position the scene in the view.
-
- \sa alignment, transformationAnchor, Qt::WNorthWestGravity
-*/
-QGraphicsView::ViewportAnchor QGraphicsView::resizeAnchor() const
-{
- Q_D(const QGraphicsView);
- return d->resizeAnchor;
-}
-void QGraphicsView::setResizeAnchor(ViewportAnchor anchor)
-{
- Q_D(QGraphicsView);
- d->resizeAnchor = anchor;
-
- // Ensure mouse tracking is enabled in the case we are using AnchorUnderMouse
- // in order to have up-to-date information for centering the view.
- if (d->resizeAnchor == AnchorUnderMouse)
- d->viewport->setMouseTracking(true);
-}
-
-/*!
- \property QGraphicsView::viewportUpdateMode
- \brief how the viewport should update its contents.
-
- \since 4.3
-
- QGraphicsView uses this property to decide how to update areas of the
- scene that have been reexposed or changed. Usually you do not need to
- modify this property, but there are some cases where doing so can improve
- rendering performance. See the ViewportUpdateMode documentation for
- specific details.
-
- The default value is MinimalViewportUpdate, where QGraphicsView will
- update as small an area of the viewport as possible when the contents
- change.
-
- \sa ViewportUpdateMode, cacheMode
-*/
-QGraphicsView::ViewportUpdateMode QGraphicsView::viewportUpdateMode() const
-{
- Q_D(const QGraphicsView);
- return d->viewportUpdateMode;
-}
-void QGraphicsView::setViewportUpdateMode(ViewportUpdateMode mode)
-{
- Q_D(QGraphicsView);
- d->viewportUpdateMode = mode;
-}
-
-/*!
- \property QGraphicsView::optimizationFlags
- \brief flags that can be used to tune QGraphicsView's performance.
-
- \since 4.3
-
- QGraphicsView uses clipping, extra bounding rect adjustments, and certain
- other aids to improve rendering quality and performance for the common
- case graphics scene. However, depending on the target platform, the scene,
- and the viewport in use, some of these operations can degrade performance.
-
- The effect varies from flag to flag; see the OptimizationFlags
- documentation for details.
-
- By default, no optimization flags are enabled.
-
- \sa setOptimizationFlag()
-*/
-QGraphicsView::OptimizationFlags QGraphicsView::optimizationFlags() const
-{
- Q_D(const QGraphicsView);
- return d->optimizationFlags;
-}
-void QGraphicsView::setOptimizationFlags(OptimizationFlags flags)
-{
- Q_D(QGraphicsView);
- d->optimizationFlags = flags;
-}
-
-/*!
- Enables \a flag if \a enabled is true; otherwise disables \a flag.
-
- \sa optimizationFlags
-*/
-void QGraphicsView::setOptimizationFlag(OptimizationFlag flag, bool enabled)
-{
- Q_D(QGraphicsView);
- if (enabled)
- d->optimizationFlags |= flag;
- else
- d->optimizationFlags &= ~flag;
-}
-
-/*!
- \property QGraphicsView::dragMode
- \brief the behavior for dragging the mouse over the scene while
- the left mouse button is pressed.
-
- This property defines what should happen when the user clicks on the scene
- background and drags the mouse (e.g., scrolling the viewport contents
- using a pointing hand cursor, or selecting multiple items with a rubber
- band). The default value, NoDrag, does nothing.
-
- This behavior only affects mouse clicks that are not handled by any item.
- You can define a custom behavior by creating a subclass of QGraphicsView
- and reimplementing mouseMoveEvent().
-*/
-QGraphicsView::DragMode QGraphicsView::dragMode() const
-{
- Q_D(const QGraphicsView);
- return d->dragMode;
-}
-void QGraphicsView::setDragMode(DragMode mode)
-{
- Q_D(QGraphicsView);
- if (d->dragMode == mode)
- return;
-
-#ifndef QT_NO_CURSOR
- if (d->dragMode == ScrollHandDrag)
- viewport()->unsetCursor();
-#endif
-
- // If dragMode is unset while dragging, e.g. via a keyEvent, we
- // don't unset the handScrolling state. When enabling scrolling
- // again the mouseMoveEvent will automatically start scrolling,
- // without a mousePress
- if (d->dragMode == ScrollHandDrag && mode == NoDrag && d->handScrolling)
- d->handScrolling = false;
-
- d->dragMode = mode;
-
-#ifndef QT_NO_CURSOR
- if (d->dragMode == ScrollHandDrag) {
- // Forget the stored viewport cursor when we enter scroll hand drag mode.
- d->hasStoredOriginalCursor = false;
- viewport()->setCursor(Qt::OpenHandCursor);
- }
-#endif
-}
-
-#ifndef QT_NO_RUBBERBAND
-/*!
- \property QGraphicsView::rubberBandSelectionMode
- \brief the behavior for selecting items with a rubber band selection rectangle.
- \since 4.3
-
- This property defines how items are selected when using the RubberBandDrag
- drag mode.
-
- The default value is Qt::IntersectsItemShape; all items whose shape
- intersects with or is contained by the rubber band are selected.
-
- \sa dragMode, items()
-*/
-Qt::ItemSelectionMode QGraphicsView::rubberBandSelectionMode() const
-{
- Q_D(const QGraphicsView);
- return d->rubberBandSelectionMode;
-}
-void QGraphicsView::setRubberBandSelectionMode(Qt::ItemSelectionMode mode)
-{
- Q_D(QGraphicsView);
- d->rubberBandSelectionMode = mode;
-}
-#endif
-
-/*!
- \property QGraphicsView::cacheMode
- \brief which parts of the view are cached
-
- QGraphicsView can cache pre-rendered content in a QPixmap, which is then
- drawn onto the viewport. The purpose of such caching is to speed up the
- total rendering time for areas that are slow to render. Texture, gradient
- and alpha blended backgrounds, for example, can be notibly slow to render;
- especially with a transformed view. The CacheBackground flag enables
- caching of the view's background. For example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 2
-
- The cache is invalidated every time the view is transformed. However, when
- scrolling, only partial invalidation is required.
-
- By default, nothing is cached.
-
- \sa resetCachedContent(), QPixmapCache
-*/
-QGraphicsView::CacheMode QGraphicsView::cacheMode() const
-{
- Q_D(const QGraphicsView);
- return d->cacheMode;
-}
-void QGraphicsView::setCacheMode(CacheMode mode)
-{
- Q_D(QGraphicsView);
- if (mode == d->cacheMode)
- return;
- d->cacheMode = mode;
- resetCachedContent();
-}
-
-/*!
- Resets any cached content. Calling this function will clear
- QGraphicsView's cache. If the current cache mode is \l CacheNone, this
- function does nothing.
-
- This function is called automatically for you when the backgroundBrush or
- QGraphicsScene::backgroundBrush properties change; you only need to call
- this function if you have reimplemented QGraphicsScene::drawBackground()
- or QGraphicsView::drawBackground() to draw a custom background, and need
- to trigger a full redraw.
-
- \sa cacheMode()
-*/
-void QGraphicsView::resetCachedContent()
-{
- Q_D(QGraphicsView);
- if (d->cacheMode == CacheNone)
- return;
-
- if (d->cacheMode & CacheBackground) {
- // Background caching is enabled.
- d->mustResizeBackgroundPixmap = true;
- d->updateAll();
- } else if (d->mustResizeBackgroundPixmap) {
- // Background caching is disabled.
- // Cleanup, free some resources.
- d->mustResizeBackgroundPixmap = false;
- d->backgroundPixmap = QPixmap();
- d->backgroundPixmapExposed = QRegion();
- }
-}
-
-/*!
- Invalidates and schedules a redraw of \a layers inside \a rect. \a rect is
- in scene coordinates. Any cached content for \a layers inside \a rect is
- unconditionally invalidated and redrawn.
-
- You can call this function to notify QGraphicsView of changes to the
- background or the foreground of the scene. It is commonly used for scenes
- with tile-based backgrounds to notify changes when QGraphicsView has
- enabled background caching.
-
- Note that QGraphicsView currently supports background caching only (see
- QGraphicsView::CacheBackground). This function is equivalent to calling update() if any
- layer but QGraphicsScene::BackgroundLayer is passed.
-
- \sa QGraphicsScene::invalidate(), update()
-*/
-void QGraphicsView::invalidateScene(const QRectF &rect, QGraphicsScene::SceneLayers layers)
-{
- Q_D(QGraphicsView);
- if ((layers & QGraphicsScene::BackgroundLayer) && !d->mustResizeBackgroundPixmap) {
- QRect viewRect = mapFromScene(rect).boundingRect();
- if (viewport()->rect().intersects(viewRect)) {
- // The updated background area is exposed; schedule this area for
- // redrawing.
- d->backgroundPixmapExposed += viewRect;
- if (d->scene)
- d->scene->update(rect);
- }
- }
-}
-
-/*!
- \property QGraphicsView::interactive
- \brief whether the view allowed scene interaction.
-
- If enabled, this view is set to allow scene interaction. Otherwise, this
- view will not allow interaction, and any mouse or key events are ignored
- (i.e., it will act as a read-only view).
-
- By default, this property is true.
-*/
-bool QGraphicsView::isInteractive() const
-{
- Q_D(const QGraphicsView);
- return d->sceneInteractionAllowed;
-}
-void QGraphicsView::setInteractive(bool allowed)
-{
- Q_D(QGraphicsView);
- d->sceneInteractionAllowed = allowed;
-}
-
-/*!
- Returns a pointer to the scene that is currently visualized in the
- view. If no scene is currently visualized, 0 is returned.
-
- \sa setScene()
-*/
-QGraphicsScene *QGraphicsView::scene() const
-{
- Q_D(const QGraphicsView);
- return d->scene;
-}
-
-/*!
- Sets the current scene to \a scene. If \a scene is already being
- viewed, this function does nothing.
-
- When a scene is set on a view, the QGraphicsScene::changed() signal
- is automatically connected to this view's updateScene() slot, and the
- view's scroll bars are adjusted to fit the size of the scene.
-*/
-void QGraphicsView::setScene(QGraphicsScene *scene)
-{
- Q_D(QGraphicsView);
- if (d->scene == scene)
- return;
-
- // Always update the viewport when the scene changes.
- d->updateAll();
-
- // Remove the previously assigned scene.
- if (d->scene) {
- disconnect(d->scene, SIGNAL(changed(QList<QRectF>)),
- this, SLOT(updateScene(QList<QRectF>)));
- disconnect(d->scene, SIGNAL(sceneRectChanged(QRectF)),
- this, SLOT(updateSceneRect(QRectF)));
- d->scene->d_func()->removeView(this);
- d->connectedToScene = false;
-
- if (isActiveWindow() && isVisible()) {
- QEvent windowDeactivate(QEvent::WindowDeactivate);
- QApplication::sendEvent(d->scene, &windowDeactivate);
- }
- if(hasFocus())
- d->scene->clearFocus();
- }
-
- // Assign the new scene and update the contents (scrollbars, etc.)).
- if ((d->scene = scene)) {
- connect(d->scene, SIGNAL(sceneRectChanged(QRectF)),
- this, SLOT(updateSceneRect(QRectF)));
- d->updateSceneSlotReimplementedChecked = false;
- d->scene->d_func()->addView(this);
- d->recalculateContentSize();
- d->lastCenterPoint = sceneRect().center();
- d->keepLastCenterPoint = true;
- // We are only interested in mouse tracking if items accept
- // hover events or use non-default cursors.
- if (!d->scene->d_func()->allItemsIgnoreHoverEvents
- || !d->scene->d_func()->allItemsUseDefaultCursor) {
- d->viewport->setMouseTracking(true);
- }
-
- // enable touch events if any items is interested in them
- if (!d->scene->d_func()->allItemsIgnoreTouchEvents)
- d->viewport->setAttribute(Qt::WA_AcceptTouchEvents);
-
- if (isActiveWindow() && isVisible()) {
- QEvent windowActivate(QEvent::WindowActivate);
- QApplication::sendEvent(d->scene, &windowActivate);
- }
- } else {
- d->recalculateContentSize();
- }
-
- d->updateInputMethodSensitivity();
-
- if (d->scene && hasFocus())
- d->scene->setFocus();
-}
-
-/*!
- \property QGraphicsView::sceneRect
- \brief the area of the scene visualized by this view.
-
- The scene rectangle defines the extent of the scene, and in the view's case,
- this means the area of the scene that you can navigate using the scroll
- bars.
-
- If unset, or if a null QRectF is set, this property has the same value as
- QGraphicsScene::sceneRect, and it changes with
- QGraphicsScene::sceneRect. Otherwise, the view's scene rect is unaffected
- by the scene.
-
- Note that, although the scene supports a virtually unlimited size, the
- range of the scroll bars will never exceed the range of an integer
- (INT_MIN, INT_MAX). When the scene is larger than the scroll bars' values,
- you can choose to use translate() to navigate the scene instead.
-
- By default, this property contains a rectangle at the origin with zero
- width and height.
-
- \sa QGraphicsScene::sceneRect
-*/
-QRectF QGraphicsView::sceneRect() const
-{
- Q_D(const QGraphicsView);
- if (d->hasSceneRect)
- return d->sceneRect;
- if (d->scene)
- return d->scene->sceneRect();
- return QRectF();
-}
-void QGraphicsView::setSceneRect(const QRectF &rect)
-{
- Q_D(QGraphicsView);
- d->hasSceneRect = !rect.isNull();
- d->sceneRect = rect;
- d->recalculateContentSize();
-}
-
-/*!
- Returns the current transformation matrix for the view. If no current
- transformation is set, the identity matrix is returned.
-
- \sa setMatrix(), transform(), rotate(), scale(), shear(), translate()
-*/
-QMatrix QGraphicsView::matrix() const
-{
- Q_D(const QGraphicsView);
- return d->matrix.toAffine();
-}
-
-/*!
- Sets the view's current transformation matrix to \a matrix.
-
- If \a combine is true, then \a matrix is combined with the current matrix;
- otherwise, \a matrix \e replaces the current matrix. \a combine is false
- by default.
-
- The transformation matrix tranforms the scene into view coordinates. Using
- the default transformation, provided by the identity matrix, one pixel in
- the view represents one unit in the scene (e.g., a 10x10 rectangular item
- is drawn using 10x10 pixels in the view). If a 2x2 scaling matrix is
- applied, the scene will be drawn in 1:2 (e.g., a 10x10 rectangular item is
- then drawn using 20x20 pixels in the view).
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 3
-
- To simplify interation with items using a transformed view, QGraphicsView
- provides mapTo... and mapFrom... functions that can translate between
- scene and view coordinates. For example, you can call mapToScene() to map
- a view coordinate to a floating point scene coordinate, or mapFromScene()
- to map from floating point scene coordinates to view coordinates.
-
- \sa matrix(), setTransform(), rotate(), scale(), shear(), translate()
-*/
-void QGraphicsView::setMatrix(const QMatrix &matrix, bool combine)
-{
- setTransform(QTransform(matrix), combine);
-}
-
-/*!
- Resets the view transformation matrix to the identity matrix.
-
- \sa resetTransform()
-*/
-void QGraphicsView::resetMatrix()
-{
- resetTransform();
-}
-
-/*!
- Rotates the current view transformation \a angle degrees clockwise.
-
- \sa setTransform(), transform(), scale(), shear(), translate()
-*/
-void QGraphicsView::rotate(qreal angle)
-{
- Q_D(QGraphicsView);
- QTransform matrix = d->matrix;
- matrix.rotate(angle);
- setTransform(matrix);
-}
-
-/*!
- Scales the current view transformation by (\a sx, \a sy).
-
- \sa setTransform(), transform(), rotate(), shear(), translate()
-*/
-void QGraphicsView::scale(qreal sx, qreal sy)
-{
- Q_D(QGraphicsView);
- QTransform matrix = d->matrix;
- matrix.scale(sx, sy);
- setTransform(matrix);
-}
-
-/*!
- Shears the current view transformation by (\a sh, \a sv).
-
- \sa setTransform(), transform(), rotate(), scale(), translate()
-*/
-void QGraphicsView::shear(qreal sh, qreal sv)
-{
- Q_D(QGraphicsView);
- QTransform matrix = d->matrix;
- matrix.shear(sh, sv);
- setTransform(matrix);
-}
-
-/*!
- Translates the current view transformation by (\a dx, \a dy).
-
- \sa setTransform(), transform(), rotate(), shear()
-*/
-void QGraphicsView::translate(qreal dx, qreal dy)
-{
- Q_D(QGraphicsView);
- QTransform matrix = d->matrix;
- matrix.translate(dx, dy);
- setTransform(matrix);
-}
-
-/*!
- Scrolls the contents of the viewport to ensure that the scene
- coordinate \a pos, is centered in the view.
-
- Because \a pos is a floating point coordinate, and the scroll bars operate
- on integer coordinates, the centering is only an approximation.
-
- \note If the item is close to or outside the border, it will be visible
- in the view, but not centered.
-
- \sa ensureVisible()
-*/
-void QGraphicsView::centerOn(const QPointF &pos)
-{
- Q_D(QGraphicsView);
- qreal width = viewport()->width();
- qreal height = viewport()->height();
- QPointF viewPoint = d->matrix.map(pos);
- QPointF oldCenterPoint = pos;
-
- if (!d->leftIndent) {
- if (isRightToLeft()) {
- qint64 horizontal = 0;
- horizontal += horizontalScrollBar()->minimum();
- horizontal += horizontalScrollBar()->maximum();
- horizontal -= int(viewPoint.x() - width / 2.0);
- horizontalScrollBar()->setValue(horizontal);
- } else {
- horizontalScrollBar()->setValue(int(viewPoint.x() - width / 2.0));
- }
- }
- if (!d->topIndent)
- verticalScrollBar()->setValue(int(viewPoint.y() - height / 2.0));
- d->lastCenterPoint = oldCenterPoint;
-}
-
-/*!
- \fn QGraphicsView::centerOn(qreal x, qreal y)
- \overload
-
- This function is provided for convenience. It's equivalent to calling
- centerOn(QPointF(\a x, \a y)).
-*/
-
-/*!
- \overload
-
- Scrolls the contents of the viewport to ensure that \a item
- is centered in the view.
-
- \sa ensureVisible()
-*/
-void QGraphicsView::centerOn(const QGraphicsItem *item)
-{
- centerOn(item->sceneBoundingRect().center());
-}
-
-/*!
- Scrolls the contents of the viewport so that the scene rectangle \a rect
- is visible, with margins specified in pixels by \a xmargin and \a
- ymargin. If the specified rect cannot be reached, the contents are
- scrolled to the nearest valid position. The default value for both margins
- is 50 pixels.
-
- \sa centerOn()
-*/
-void QGraphicsView::ensureVisible(const QRectF &rect, int xmargin, int ymargin)
-{
- Q_D(QGraphicsView);
- qreal width = viewport()->width();
- qreal height = viewport()->height();
- QRectF viewRect = d->matrix.mapRect(rect);
-
- qreal left = d->horizontalScroll();
- qreal right = left + width;
- qreal top = d->verticalScroll();
- qreal bottom = top + height;
-
- if (viewRect.left() <= left + xmargin) {
- // need to scroll from the left
- if (!d->leftIndent)
- horizontalScrollBar()->setValue(int(viewRect.left() - xmargin - 0.5));
- }
- if (viewRect.right() >= right - xmargin) {
- // need to scroll from the right
- if (!d->leftIndent)
- horizontalScrollBar()->setValue(int(viewRect.right() - width + xmargin + 0.5));
- }
- if (viewRect.top() <= top + ymargin) {
- // need to scroll from the top
- if (!d->topIndent)
- verticalScrollBar()->setValue(int(viewRect.top() - ymargin - 0.5));
- }
- if (viewRect.bottom() >= bottom - ymargin) {
- // need to scroll from the bottom
- if (!d->topIndent)
- verticalScrollBar()->setValue(int(viewRect.bottom() - height + ymargin + 0.5));
- }
-}
-
-/*!
- \fn QGraphicsView::ensureVisible(qreal x, qreal y, qreal w, qreal h,
- int xmargin, int ymargin)
- \overload
-
- This function is provided for convenience. It's equivalent to calling
- ensureVisible(QRectF(\a x, \a y, \a w, \a h), \a xmargin, \a ymargin).
-*/
-
-/*!
- \overload
-
- Scrolls the contents of the viewport so that the center of item \a item is
- visible, with margins specified in pixels by \a xmargin and \a ymargin. If
- the specified point cannot be reached, the contents are scrolled to the
- nearest valid position. The default value for both margins is 50 pixels.
-
- \sa centerOn()
-*/
-void QGraphicsView::ensureVisible(const QGraphicsItem *item, int xmargin, int ymargin)
-{
- ensureVisible(item->sceneBoundingRect(), xmargin, ymargin);
-}
-
-/*!
- Scales the view matrix and scrolls the scroll bars to ensure that the
- scene rectangle \a rect fits inside the viewport. \a rect must be inside
- the scene rect; otherwise, fitInView() cannot guarantee that the whole
- rect is visible.
-
- This function keeps the view's rotation, translation, or shear. The view
- is scaled according to \a aspectRatioMode. \a rect will be centered in the
- view if it does not fit tightly.
-
- It's common to call fitInView() from inside a reimplementation of
- resizeEvent(), to ensure that the whole scene, or parts of the scene,
- scales automatically to fit the new size of the viewport as the view is
- resized. Note though, that calling fitInView() from inside resizeEvent()
- can lead to unwanted resize recursion, if the new transformation toggles
- the automatic state of the scrollbars. You can toggle the scrollbar
- policies to always on or always off to prevent this (see
- horizontalScrollBarPolicy() and verticalScrollBarPolicy()).
-
- If \a rect is empty, or if the viewport is too small, this
- function will do nothing.
-
- \sa setTransform(), ensureVisible(), centerOn()
-*/
-void QGraphicsView::fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRatioMode)
-{
- Q_D(QGraphicsView);
- if (!d->scene || rect.isNull())
- return;
-
- // Reset the view scale to 1:1.
- QRectF unity = d->matrix.mapRect(QRectF(0, 0, 1, 1));
- if (unity.isEmpty())
- return;
- scale(1 / unity.width(), 1 / unity.height());
-
- // Find the ideal x / y scaling ratio to fit \a rect in the view.
- int margin = 2;
- QRectF viewRect = viewport()->rect().adjusted(margin, margin, -margin, -margin);
- if (viewRect.isEmpty())
- return;
- QRectF sceneRect = d->matrix.mapRect(rect);
- if (sceneRect.isEmpty())
- return;
- qreal xratio = viewRect.width() / sceneRect.width();
- qreal yratio = viewRect.height() / sceneRect.height();
-
- // Respect the aspect ratio mode.
- switch (aspectRatioMode) {
- case Qt::KeepAspectRatio:
- xratio = yratio = qMin(xratio, yratio);
- break;
- case Qt::KeepAspectRatioByExpanding:
- xratio = yratio = qMax(xratio, yratio);
- break;
- case Qt::IgnoreAspectRatio:
- break;
- }
-
- // Scale and center on the center of \a rect.
- scale(xratio, yratio);
- centerOn(rect.center());
-}
-
-/*!
- \fn void QGraphicsView::fitInView(qreal x, qreal y, qreal w, qreal h,
- Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio)
-
- \overload
-
- This convenience function is equivalent to calling
- fitInView(QRectF(\a x, \a y, \a w, \a h), \a aspectRatioMode).
-
- \sa ensureVisible(), centerOn()
-*/
-
-/*!
- \overload
-
- Ensures that \a item fits tightly inside the view, scaling the view
- according to \a aspectRatioMode.
-
- \sa ensureVisible(), centerOn()
-*/
-void QGraphicsView::fitInView(const QGraphicsItem *item, Qt::AspectRatioMode aspectRatioMode)
-{
- QPainterPath path = item->isClipped() ? item->clipPath() : item->shape();
- if (item->d_ptr->hasTranslateOnlySceneTransform()) {
- path.translate(item->d_ptr->sceneTransform.dx(), item->d_ptr->sceneTransform.dy());
- fitInView(path.boundingRect(), aspectRatioMode);
- } else {
- fitInView(item->d_ptr->sceneTransform.map(path).boundingRect(), aspectRatioMode);
- }
-}
-
-/*!
- Renders the \a source rect, which is in view coordinates, from the scene
- into \a target, which is in paint device coordinates, using \a
- painter. This function is useful for capturing the contents of the view
- onto a paint device, such as a QImage (e.g., to take a screenshot), or for
- printing to QPrinter. For example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 4
-
- If \a source is a null rect, this function will use viewport()->rect() to
- determine what to draw. If \a target is a null rect, the full dimensions
- of \a painter's paint device (e.g., for a QPrinter, the page size) will be
- used.
-
- The source rect contents will be transformed according to \a
- aspectRatioMode to fit into the target rect. By default, the aspect ratio
- is kept, and \a source is scaled to fit in \a target.
-
- \sa QGraphicsScene::render()
-*/
-void QGraphicsView::render(QPainter *painter, const QRectF &target, const QRect &source,
- Qt::AspectRatioMode aspectRatioMode)
-{
- // ### Switch to using the recursive rendering algorithm instead.
-
- Q_D(QGraphicsView);
- if (!d->scene || !(painter && painter->isActive()))
- return;
-
- // Default source rect = viewport rect
- QRect sourceRect = source;
- if (source.isNull())
- sourceRect = viewport()->rect();
-
- // Default target rect = device rect
- QRectF targetRect = target;
- if (target.isNull()) {
- if (painter->device()->devType() == QInternal::Picture)
- targetRect = sourceRect;
- else
- targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
- }
-
- // Find the ideal x / y scaling ratio to fit \a source into \a target.
- qreal xratio = targetRect.width() / sourceRect.width();
- qreal yratio = targetRect.height() / sourceRect.height();
-
- // Scale according to the aspect ratio mode.
- switch (aspectRatioMode) {
- case Qt::KeepAspectRatio:
- xratio = yratio = qMin(xratio, yratio);
- break;
- case Qt::KeepAspectRatioByExpanding:
- xratio = yratio = qMax(xratio, yratio);
- break;
- case Qt::IgnoreAspectRatio:
- break;
- }
-
- // Find all items to draw, and reverse the list (we want to draw
- // in reverse order).
- QPolygonF sourceScenePoly = mapToScene(sourceRect.adjusted(-1, -1, 1, 1));
- QList<QGraphicsItem *> itemList = d->scene->items(sourceScenePoly,
- Qt::IntersectsItemBoundingRect);
- QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
- int numItems = itemList.size();
- for (int i = 0; i < numItems; ++i)
- itemArray[numItems - i - 1] = itemList.at(i);
- itemList.clear();
-
- // Setup painter matrix.
- QTransform moveMatrix = QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll());
- QTransform painterMatrix = d->matrix * moveMatrix;
- painterMatrix *= QTransform()
- .translate(targetRect.left(), targetRect.top())
- .scale(xratio, yratio)
- .translate(-sourceRect.left(), -sourceRect.top());
-
- // Generate the style options
- QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems);
- for (int i = 0; i < numItems; ++i)
- itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterMatrix, targetRect.toRect());
-
- painter->save();
-
- // Clip in device coordinates to avoid QRegion transformations.
- painter->setClipRect(targetRect);
- QPainterPath path;
- path.addPolygon(sourceScenePoly);
- path.closeSubpath();
- painter->setClipPath(painterMatrix.map(path), Qt::IntersectClip);
-
- // Transform the painter.
- painter->setTransform(painterMatrix, true);
-
- // Render the scene.
- QRectF sourceSceneRect = sourceScenePoly.boundingRect();
- drawBackground(painter, sourceSceneRect);
- drawItems(painter, numItems, itemArray, styleOptionArray);
- drawForeground(painter, sourceSceneRect);
-
- delete [] itemArray;
- d->freeStyleOptionsArray(styleOptionArray);
-
- painter->restore();
-}
-
-/*!
- Returns a list of all the items in the associated scene, in descending
- stacking order (i.e., the first item in the returned list is the uppermost
- item).
-
- \sa QGraphicsScene::items(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsView::items() const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return QList<QGraphicsItem *>();
- return d->scene->items();
-}
-
-/*!
- Returns a list of all the items at the position \a pos in the view. The
- items are listed in descending stacking order (i.e., the first item in the
- list is the uppermost item, and the last item is the lowermost item). \a
- pos is in viewport coordinates.
-
- This function is most commonly called from within mouse event handlers in
- a subclass in QGraphicsView. \a pos is in untransformed viewport
- coordinates, just like QMouseEvent::pos().
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 5
-
- \sa QGraphicsScene::items(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsView::items(const QPoint &pos) const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return QList<QGraphicsItem *>();
- // ### Unify these two, and use the items(QPointF) version in
- // QGraphicsScene instead. The scene items function could use the viewport
- // transform to map the point to a rect/polygon.
- if ((d->identityMatrix || d->matrix.type() <= QTransform::TxScale)) {
- // Use the rect version
- QTransform xinv = viewportTransform().inverted();
- return d->scene->items(xinv.mapRect(QRectF(pos.x(), pos.y(), 1, 1)),
- Qt::IntersectsItemShape,
- Qt::DescendingOrder,
- viewportTransform());
- }
- // Use the polygon version
- return d->scene->items(mapToScene(pos.x(), pos.y(), 1, 1),
- Qt::IntersectsItemShape,
- Qt::DescendingOrder,
- viewportTransform());
-}
-
-/*!
- \fn QGraphicsView::items(int x, int y) const
-
- This function is provided for convenience. It's equivalent to calling
- items(QPoint(\a x, \a y)).
-*/
-
-/*!
- \overload
-
- Returns a list of all the items that, depending on \a mode, are either
- contained by or intersect with \a rect. \a rect is in viewport
- coordinates.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a rect are returned.
-
- The items are sorted in descending stacking order (i.e., the first item in
- the returned list is the uppermost item).
-
- \sa itemAt(), items(), mapToScene(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsView::items(const QRect &rect, Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return QList<QGraphicsItem *>();
- return d->scene->items(mapToScene(rect), mode, Qt::DescendingOrder, viewportTransform());
-}
-
-/*!
- \fn QList<QGraphicsItem *> QGraphicsView::items(int x, int y, int w, int h, Qt::ItemSelectionMode mode) const
- \since 4.3
-
- This convenience function is equivalent to calling items(QRectF(\a x, \a
- y, \a w, \a h), \a mode).
-*/
-
-/*!
- \overload
-
- Returns a list of all the items that, depending on \a mode, are either
- contained by or intersect with \a polygon. \a polygon is in viewport
- coordinates.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a polygon are returned.
-
- The items are sorted by descending stacking order (i.e., the first item in
- the returned list is the uppermost item).
-
- \sa itemAt(), items(), mapToScene(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsView::items(const QPolygon &polygon, Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return QList<QGraphicsItem *>();
- return d->scene->items(mapToScene(polygon), mode, Qt::DescendingOrder, viewportTransform());
-}
-
-/*!
- \overload
-
- Returns a list of all the items that, depending on \a mode, are either
- contained by or intersect with \a path. \a path is in viewport
- coordinates.
-
- The default value for \a mode is Qt::IntersectsItemShape; all items whose
- exact shape intersects with or is contained by \a path are returned.
-
- \sa itemAt(), items(), mapToScene(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QList<QGraphicsItem *> QGraphicsView::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return QList<QGraphicsItem *>();
- return d->scene->items(mapToScene(path), mode, Qt::DescendingOrder, viewportTransform());
-}
-
-/*!
- Returns the item at position \a pos, which is in viewport coordinates.
- If there are several items at this position, this function returns
- the topmost item.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 6
-
- \sa items(), {QGraphicsItem#Sorting}{Sorting}
-*/
-QGraphicsItem *QGraphicsView::itemAt(const QPoint &pos) const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return 0;
- QList<QGraphicsItem *> itemsAtPos = items(pos);
- return itemsAtPos.isEmpty() ? 0 : itemsAtPos.first();
-}
-
-/*!
- \overload
- \fn QGraphicsItem *QGraphicsView::itemAt(int x, int y) const
-
- This function is provided for convenience. It's equivalent to
- calling itemAt(QPoint(\a x, \a y)).
-*/
-
-/*!
- Returns the viewport coordinate \a point mapped to scene coordinates.
-
- Note: It can be useful to map the whole rectangle covered by the pixel at
- \a point instead of the point itself. To do this, you can call
- mapToScene(QRect(\a point, QSize(2, 2))).
-
- \sa mapFromScene()
-*/
-QPointF QGraphicsView::mapToScene(const QPoint &point) const
-{
- Q_D(const QGraphicsView);
- QPointF p = point;
- p.rx() += d->horizontalScroll();
- p.ry() += d->verticalScroll();
- return d->identityMatrix ? p : d->matrix.inverted().map(p);
-}
-
-/*!
- \fn QGraphicsView::mapToScene(int x, int y) const
-
- This function is provided for convenience. It's equivalent to calling
- mapToScene(QPoint(\a x, \a y)).
-*/
-
-/*!
- Returns the viewport rectangle \a rect mapped to a scene coordinate
- polygon.
-
- \sa mapFromScene()
-*/
-QPolygonF QGraphicsView::mapToScene(const QRect &rect) const
-{
- Q_D(const QGraphicsView);
- if (!rect.isValid())
- return QPolygonF();
-
- QPointF scrollOffset(d->horizontalScroll(), d->verticalScroll());
- QRect r = rect.adjusted(0, 0, 1, 1);
- QPointF tl = scrollOffset + r.topLeft();
- QPointF tr = scrollOffset + r.topRight();
- QPointF br = scrollOffset + r.bottomRight();
- QPointF bl = scrollOffset + r.bottomLeft();
-
- QPolygonF poly(4);
- if (!d->identityMatrix) {
- QTransform x = d->matrix.inverted();
- poly[0] = x.map(tl);
- poly[1] = x.map(tr);
- poly[2] = x.map(br);
- poly[3] = x.map(bl);
- } else {
- poly[0] = tl;
- poly[1] = tr;
- poly[2] = br;
- poly[3] = bl;
- }
- return poly;
-}
-
-/*!
- \fn QGraphicsView::mapToScene(int x, int y, int w, int h) const
-
- This function is provided for convenience. It's equivalent to calling
- mapToScene(QRect(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Returns the viewport polygon \a polygon mapped to a scene coordinate
- polygon.
-
- \sa mapFromScene()
-*/
-QPolygonF QGraphicsView::mapToScene(const QPolygon &polygon) const
-{
- QPolygonF poly;
- foreach (const QPoint &point, polygon)
- poly << mapToScene(point);
- return poly;
-}
-
-/*!
- Returns the viewport painter path \a path mapped to a scene coordinate
- painter path.
-
- \sa mapFromScene()
-*/
-QPainterPath QGraphicsView::mapToScene(const QPainterPath &path) const
-{
- Q_D(const QGraphicsView);
- QTransform matrix = QTransform::fromTranslate(d->horizontalScroll(), d->verticalScroll());
- matrix *= d->matrix.inverted();
- return matrix.map(path);
-}
-
-/*!
- Returns the scene coordinate \a point to viewport coordinates.
-
- \sa mapToScene()
-*/
-QPoint QGraphicsView::mapFromScene(const QPointF &point) const
-{
- Q_D(const QGraphicsView);
- QPointF p = d->identityMatrix ? point : d->matrix.map(point);
- p.rx() -= d->horizontalScroll();
- p.ry() -= d->verticalScroll();
- return p.toPoint();
-}
-
-/*!
- \fn QGraphicsView::mapFromScene(qreal x, qreal y) const
-
- This function is provided for convenience. It's equivalent to
- calling mapFromScene(QPointF(\a x, \a y)).
-*/
-
-/*!
- Returns the scene rectangle \a rect to a viewport coordinate
- polygon.
-
- \sa mapToScene()
-*/
-QPolygon QGraphicsView::mapFromScene(const QRectF &rect) const
-{
- Q_D(const QGraphicsView);
- QPointF tl;
- QPointF tr;
- QPointF br;
- QPointF bl;
- if (!d->identityMatrix) {
- const QTransform &x = d->matrix;
- tl = x.map(rect.topLeft());
- tr = x.map(rect.topRight());
- br = x.map(rect.bottomRight());
- bl = x.map(rect.bottomLeft());
- } else {
- tl = rect.topLeft();
- tr = rect.topRight();
- br = rect.bottomRight();
- bl = rect.bottomLeft();
- }
- QPointF scrollOffset(d->horizontalScroll(), d->verticalScroll());
- tl -= scrollOffset;
- tr -= scrollOffset;
- br -= scrollOffset;
- bl -= scrollOffset;
-
- QPolygon poly(4);
- poly[0] = tl.toPoint();
- poly[1] = tr.toPoint();
- poly[2] = br.toPoint();
- poly[3] = bl.toPoint();
- return poly;
-}
-
-/*!
- \fn QGraphicsView::mapFromScene(qreal x, qreal y, qreal w, qreal h) const
-
- This function is provided for convenience. It's equivalent to
- calling mapFromScene(QRectF(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Returns the scene coordinate polygon \a polygon to a viewport coordinate
- polygon.
-
- \sa mapToScene()
-*/
-QPolygon QGraphicsView::mapFromScene(const QPolygonF &polygon) const
-{
- QPolygon poly;
- foreach (const QPointF &point, polygon)
- poly << mapFromScene(point);
- return poly;
-}
-
-/*!
- Returns the scene coordinate painter path \a path to a viewport coordinate
- painter path.
-
- \sa mapToScene()
-*/
-QPainterPath QGraphicsView::mapFromScene(const QPainterPath &path) const
-{
- Q_D(const QGraphicsView);
- QTransform matrix = d->matrix;
- matrix *= QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll());
- return matrix.map(path);
-}
-
-/*!
- \reimp
-*/
-QVariant QGraphicsView::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- Q_D(const QGraphicsView);
- if (!d->scene)
- return QVariant();
-
- QVariant value = d->scene->inputMethodQuery(query);
- if (value.type() == QVariant::RectF)
- value = d->mapRectFromScene(value.toRectF());
- else if (value.type() == QVariant::PointF)
- value = mapFromScene(value.toPointF());
- else if (value.type() == QVariant::Rect)
- value = d->mapRectFromScene(value.toRect()).toRect();
- else if (value.type() == QVariant::Point)
- value = mapFromScene(value.toPoint());
- return value;
-}
-
-/*!
- \property QGraphicsView::backgroundBrush
- \brief the background brush of the scene.
-
- This property sets the background brush for the scene in this view. It is
- used to override the scene's own background, and defines the behavior of
- drawBackground(). To provide custom background drawing for this view, you
- can reimplement drawBackground() instead.
-
- By default, this property contains a brush with the Qt::NoBrush pattern.
-
- \sa QGraphicsScene::backgroundBrush, foregroundBrush
-*/
-QBrush QGraphicsView::backgroundBrush() const
-{
- Q_D(const QGraphicsView);
- return d->backgroundBrush;
-}
-void QGraphicsView::setBackgroundBrush(const QBrush &brush)
-{
- Q_D(QGraphicsView);
- d->backgroundBrush = brush;
- d->updateAll();
-
- if (d->cacheMode & CacheBackground) {
- // Invalidate the background pixmap
- d->mustResizeBackgroundPixmap = true;
- }
-}
-
-/*!
- \property QGraphicsView::foregroundBrush
- \brief the foreground brush of the scene.
-
- This property sets the foreground brush for the scene in this view. It is
- used to override the scene's own foreground, and defines the behavior of
- drawForeground(). To provide custom foreground drawing for this view, you
- can reimplement drawForeground() instead.
-
- By default, this property contains a brush with the Qt::NoBrush pattern.
-
- \sa QGraphicsScene::foregroundBrush, backgroundBrush
-*/
-QBrush QGraphicsView::foregroundBrush() const
-{
- Q_D(const QGraphicsView);
- return d->foregroundBrush;
-}
-void QGraphicsView::setForegroundBrush(const QBrush &brush)
-{
- Q_D(QGraphicsView);
- d->foregroundBrush = brush;
- d->updateAll();
-}
-
-/*!
- Schedules an update of the scene rectangles \a rects.
-
- \sa QGraphicsScene::changed()
-*/
-void QGraphicsView::updateScene(const QList<QRectF> &rects)
-{
- // ### Note: Since 4.5, this slot is only called if the user explicitly
- // establishes a connection between the scene and the view, as the scene
- // and view are no longer connected. We need to keep it working (basically
- // leave it as it is), but the new delivery path is through
- // QGraphicsScenePrivate::itemUpdate().
- Q_D(QGraphicsView);
- if (d->fullUpdatePending || d->viewportUpdateMode == QGraphicsView::NoViewportUpdate)
- return;
-
- // Extract and reset dirty scene rect info.
- QVector<QRect> dirtyViewportRects;
- const QVector<QRect> &dirtyRects = d->dirtyRegion.rects();
- for (int i = 0; i < dirtyRects.size(); ++i)
- dirtyViewportRects += dirtyRects.at(i);
- d->dirtyRegion = QRegion();
- d->dirtyBoundingRect = QRect();
-
- bool fullUpdate = !d->accelerateScrolling || d->viewportUpdateMode == QGraphicsView::FullViewportUpdate;
- bool boundingRectUpdate = (d->viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate)
- || (d->viewportUpdateMode == QGraphicsView::SmartViewportUpdate
- && ((dirtyViewportRects.size() + rects.size()) >= QGRAPHICSVIEW_REGION_RECT_THRESHOLD));
-
- QRegion updateRegion;
- QRect boundingRect;
- QRect viewportRect = viewport()->rect();
- bool redraw = false;
- QTransform transform = viewportTransform();
-
- // Convert scene rects to viewport rects.
- foreach (const QRectF &rect, rects) {
- QRect xrect = transform.mapRect(rect).toAlignedRect();
- if (!(d->optimizationFlags & DontAdjustForAntialiasing))
- xrect.adjust(-2, -2, 2, 2);
- else
- xrect.adjust(-1, -1, 1, 1);
- if (!viewportRect.intersects(xrect))
- continue;
- dirtyViewportRects << xrect;
- }
-
- foreach (const QRect &rect, dirtyViewportRects) {
- // Add the exposed rect to the update region. In rect update
- // mode, we only count the bounding rect of items.
- if (!boundingRectUpdate) {
- updateRegion += rect;
- } else {
- boundingRect |= rect;
- }
- redraw = true;
- if (fullUpdate) {
- // If fullUpdate is true and we found a visible dirty rect,
- // we're done.
- break;
- }
- }
-
- if (!redraw)
- return;
-
- if (fullUpdate)
- viewport()->update();
- else if (boundingRectUpdate)
- viewport()->update(boundingRect);
- else
- viewport()->update(updateRegion);
-}
-
-/*!
- Notifies QGraphicsView that the scene's scene rect has changed. \a rect
- is the new scene rect. If the view already has an explicitly set scene
- rect, this function does nothing.
-
- \sa sceneRect, QGraphicsScene::sceneRectChanged()
-*/
-void QGraphicsView::updateSceneRect(const QRectF &rect)
-{
- Q_D(QGraphicsView);
- if (!d->hasSceneRect) {
- d->sceneRect = rect;
- d->recalculateContentSize();
- }
-}
-
-/*!
- This slot is called by QAbstractScrollArea after setViewport() has been
- called. Reimplement this function in a subclass of QGraphicsView to
- initialize the new viewport \a widget before it is used.
-
- \sa setViewport()
-*/
-void QGraphicsView::setupViewport(QWidget *widget)
-{
- Q_D(QGraphicsView);
-
- if (!widget) {
- qWarning("QGraphicsView::setupViewport: cannot initialize null widget");
- return;
- }
-
- const bool isGLWidget = widget->inherits("QGLWidget");
-
- d->accelerateScrolling = !(isGLWidget);
-
- widget->setFocusPolicy(Qt::StrongFocus);
-
- if (!isGLWidget) {
- // autoFillBackground enables scroll acceleration.
- widget->setAutoFillBackground(true);
- }
-
- // We are only interested in mouse tracking if items
- // accept hover events or use non-default cursors or if
- // AnchorUnderMouse is used as transformation or resize anchor.
- if ((d->scene && (!d->scene->d_func()->allItemsIgnoreHoverEvents
- || !d->scene->d_func()->allItemsUseDefaultCursor))
- || d->transformationAnchor == AnchorUnderMouse
- || d->resizeAnchor == AnchorUnderMouse) {
- widget->setMouseTracking(true);
- }
-
- // enable touch events if any items is interested in them
- if (d->scene && !d->scene->d_func()->allItemsIgnoreTouchEvents)
- widget->setAttribute(Qt::WA_AcceptTouchEvents);
-
-#ifndef QT_NO_GESTURES
- if (d->scene) {
- foreach (Qt::GestureType gesture, d->scene->d_func()->grabbedGestures.keys())
- widget->grabGesture(gesture);
- }
-#endif
-
- widget->setAcceptDrops(acceptDrops());
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsView::event(QEvent *event)
-{
- Q_D(QGraphicsView);
-
- if (d->sceneInteractionAllowed) {
- switch (event->type()) {
- case QEvent::ShortcutOverride:
- if (d->scene)
- return QApplication::sendEvent(d->scene, event);
- break;
- case QEvent::KeyPress:
- if (d->scene) {
- QKeyEvent *k = static_cast<QKeyEvent *>(event);
- if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
- // Send the key events to the scene. This will invoke the
- // scene's tab focus handling, and if the event is
- // accepted, we return (prevent further event delivery),
- // and the base implementation will call QGraphicsView's
- // focusNextPrevChild() function. If the event is ignored,
- // we fall back to standard tab focus handling.
- QApplication::sendEvent(d->scene, event);
- if (event->isAccepted())
- return true;
- // Ensure the event doesn't propagate just because the
- // scene ignored it. If the event propagates, then tab
- // handling will be called twice (this and parent).
- event->accept();
- }
- }
- break;
- default:
- break;
- }
- }
-
- return QAbstractScrollArea::event(event);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsView::viewportEvent(QEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene)
- return QAbstractScrollArea::viewportEvent(event);
-
- switch (event->type()) {
- case QEvent::Enter:
- QApplication::sendEvent(d->scene, event);
- break;
- case QEvent::WindowActivate:
- QApplication::sendEvent(d->scene, event);
- break;
- case QEvent::WindowDeactivate:
- // ### This is a temporary fix for until we get proper mouse
- // grab events. mouseGrabberItem should be set to 0 if we lose
- // the mouse grab.
- // Remove all popups when the scene loses focus.
- if (!d->scene->d_func()->popupWidgets.isEmpty())
- d->scene->d_func()->removePopup(d->scene->d_func()->popupWidgets.first());
- QApplication::sendEvent(d->scene, event);
- break;
- case QEvent::Show:
- if (d->scene && isActiveWindow()) {
- QEvent windowActivate(QEvent::WindowActivate);
- QApplication::sendEvent(d->scene, &windowActivate);
- }
- break;
- case QEvent::Hide:
- // spontaneous event will generate a WindowDeactivate.
- if (!event->spontaneous() && d->scene && isActiveWindow()) {
- QEvent windowDeactivate(QEvent::WindowDeactivate);
- QApplication::sendEvent(d->scene, &windowDeactivate);
- }
- break;
- case QEvent::Leave:
- // ### This is a temporary fix for until we get proper mouse grab
- // events. activeMouseGrabberItem should be set to 0 if we lose the
- // mouse grab.
- if ((QApplication::activePopupWidget() && QApplication::activePopupWidget() != window())
- || (QApplication::activeModalWidget() && QApplication::activeModalWidget() != window())
- || (QApplication::activeWindow() != window())) {
- if (!d->scene->d_func()->popupWidgets.isEmpty())
- d->scene->d_func()->removePopup(d->scene->d_func()->popupWidgets.first());
- }
- d->useLastMouseEvent = false;
- // a hack to pass a viewport pointer to the scene inside the leave event
- Q_ASSERT(event->d == 0);
- event->d = reinterpret_cast<QEventPrivate *>(viewport());
- QApplication::sendEvent(d->scene, event);
- break;
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTip: {
- QHelpEvent *toolTip = static_cast<QHelpEvent *>(event);
- QGraphicsSceneHelpEvent helpEvent(QEvent::GraphicsSceneHelp);
- helpEvent.setWidget(viewport());
- helpEvent.setScreenPos(toolTip->globalPos());
- helpEvent.setScenePos(mapToScene(toolTip->pos()));
- QApplication::sendEvent(d->scene, &helpEvent);
- toolTip->setAccepted(helpEvent.isAccepted());
- return true;
- }
-#endif
- case QEvent::Paint:
- // Reset full update
- d->fullUpdatePending = false;
- d->dirtyScrollOffset = QPoint();
- if (d->scene) {
- // Check if this view reimplements the updateScene slot; if it
- // does, we can't do direct update delivery and have to fall back
- // to connecting the changed signal.
- if (!d->updateSceneSlotReimplementedChecked) {
- d->updateSceneSlotReimplementedChecked = true;
- const QMetaObject *mo = metaObject();
- if (mo != &QGraphicsView::staticMetaObject) {
- if (mo->indexOfSlot("updateScene(QList<QRectF>)")
- != QGraphicsView::staticMetaObject.indexOfSlot("updateScene(QList<QRectF>)")) {
- connect(d->scene, SIGNAL(changed(QList<QRectF>)),
- this, SLOT(updateScene(QList<QRectF>)));
- }
- }
- }
- }
- break;
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- {
- if (!isEnabled())
- return false;
-
- if (d->scene && d->sceneInteractionAllowed) {
- // Convert and deliver the touch event to the scene.
- QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
- touchEvent->setWidget(viewport());
- QGraphicsViewPrivate::translateTouchEvent(d, touchEvent);
- (void) QApplication::sendEvent(d->scene, touchEvent);
- }
-
- return true;
- }
-#ifndef QT_NO_GESTURES
- case QEvent::Gesture:
- case QEvent::GestureOverride:
- {
- if (!isEnabled())
- return false;
-
- if (d->scene && d->sceneInteractionAllowed) {
- QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event);
- gestureEvent->setWidget(viewport());
- (void) QApplication::sendEvent(d->scene, gestureEvent);
- }
- return true;
- }
-#endif // QT_NO_GESTURES
- default:
- break;
- }
-
- return QAbstractScrollArea::viewportEvent(event);
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \reimp
-*/
-void QGraphicsView::contextMenuEvent(QContextMenuEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
-
- d->mousePressViewPoint = event->pos();
- d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
- d->mousePressScreenPoint = event->globalPos();
- d->lastMouseMoveScenePoint = d->mousePressScenePoint;
- d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
-
- QGraphicsSceneContextMenuEvent contextEvent(QEvent::GraphicsSceneContextMenu);
- contextEvent.setWidget(viewport());
- contextEvent.setScenePos(d->mousePressScenePoint);
- contextEvent.setScreenPos(d->mousePressScreenPoint);
- contextEvent.setModifiers(event->modifiers());
- contextEvent.setReason((QGraphicsSceneContextMenuEvent::Reason)(event->reason()));
- contextEvent.setAccepted(event->isAccepted());
- QApplication::sendEvent(d->scene, &contextEvent);
- event->setAccepted(contextEvent.isAccepted());
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*!
- \reimp
-*/
-void QGraphicsView::dropEvent(QDropEvent *event)
-{
-#ifndef QT_NO_DRAGANDDROP
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
-
- // Generate a scene event.
- QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDrop);
- d->populateSceneDragDropEvent(&sceneEvent, event);
-
- // Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
-
- // Accept the originating event if the scene accepted the scene event.
- event->setAccepted(sceneEvent.isAccepted());
- if (sceneEvent.isAccepted())
- event->setDropAction(sceneEvent.dropAction());
-
- delete d->lastDragDropEvent;
- d->lastDragDropEvent = 0;
-
-#else
- Q_UNUSED(event)
-#endif
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::dragEnterEvent(QDragEnterEvent *event)
-{
-#ifndef QT_NO_DRAGANDDROP
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
-
- // Disable replaying of mouse move events.
- d->useLastMouseEvent = false;
-
- // Generate a scene event.
- QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDragEnter);
- d->populateSceneDragDropEvent(&sceneEvent, event);
-
- // Store it for later use.
- d->storeDragDropEvent(&sceneEvent);
-
- // Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
-
- // Accept the originating event if the scene accepted the scene event.
- if (sceneEvent.isAccepted()) {
- event->setAccepted(true);
- event->setDropAction(sceneEvent.dropAction());
- }
-#else
- Q_UNUSED(event)
-#endif
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::dragLeaveEvent(QDragLeaveEvent *event)
-{
-#ifndef QT_NO_DRAGANDDROP
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
- if (!d->lastDragDropEvent) {
- qWarning("QGraphicsView::dragLeaveEvent: drag leave received before drag enter");
- return;
- }
-
- // Generate a scene event.
- QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDragLeave);
- sceneEvent.setScenePos(d->lastDragDropEvent->scenePos());
- sceneEvent.setScreenPos(d->lastDragDropEvent->screenPos());
- sceneEvent.setButtons(d->lastDragDropEvent->buttons());
- sceneEvent.setModifiers(d->lastDragDropEvent->modifiers());
- sceneEvent.setPossibleActions(d->lastDragDropEvent->possibleActions());
- sceneEvent.setProposedAction(d->lastDragDropEvent->proposedAction());
- sceneEvent.setDropAction(d->lastDragDropEvent->dropAction());
- sceneEvent.setMimeData(d->lastDragDropEvent->mimeData());
- sceneEvent.setWidget(d->lastDragDropEvent->widget());
- sceneEvent.setSource(d->lastDragDropEvent->source());
- delete d->lastDragDropEvent;
- d->lastDragDropEvent = 0;
-
- // Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
-
- // Accept the originating event if the scene accepted the scene event.
- if (sceneEvent.isAccepted())
- event->setAccepted(true);
-#else
- Q_UNUSED(event)
-#endif
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::dragMoveEvent(QDragMoveEvent *event)
-{
-#ifndef QT_NO_DRAGANDDROP
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
-
- // Generate a scene event.
- QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDragMove);
- d->populateSceneDragDropEvent(&sceneEvent, event);
-
- // Store it for later use.
- d->storeDragDropEvent(&sceneEvent);
-
- // Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
-
- // Ignore the originating event if the scene ignored the scene event.
- event->setAccepted(sceneEvent.isAccepted());
- if (sceneEvent.isAccepted())
- event->setDropAction(sceneEvent.dropAction());
-#else
- Q_UNUSED(event)
-#endif
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::focusInEvent(QFocusEvent *event)
-{
- Q_D(QGraphicsView);
- d->updateInputMethodSensitivity();
- QAbstractScrollArea::focusInEvent(event);
- if (d->scene)
- QApplication::sendEvent(d->scene, event);
- // Pass focus on if the scene cannot accept focus.
- if (!d->scene || !event->isAccepted())
- QAbstractScrollArea::focusInEvent(event);
-}
-
-/*!
- \reimp
-*/
-bool QGraphicsView::focusNextPrevChild(bool next)
-{
- return QAbstractScrollArea::focusNextPrevChild(next);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::focusOutEvent(QFocusEvent *event)
-{
- Q_D(QGraphicsView);
- QAbstractScrollArea::focusOutEvent(event);
- if (d->scene)
- QApplication::sendEvent(d->scene, event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed) {
- QAbstractScrollArea::keyPressEvent(event);
- return;
- }
- QApplication::sendEvent(d->scene, event);
- if (!event->isAccepted())
- QAbstractScrollArea::keyPressEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::keyReleaseEvent(QKeyEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
- QApplication::sendEvent(d->scene, event);
- if (!event->isAccepted())
- QAbstractScrollArea::keyReleaseEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed)
- return;
-
- d->storeMouseEvent(event);
- d->mousePressViewPoint = event->pos();
- d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
- d->mousePressScreenPoint = event->globalPos();
- d->lastMouseMoveScenePoint = d->mousePressScenePoint;
- d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
- d->mousePressButton = event->button();
-
- QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseDoubleClick);
- mouseEvent.setWidget(viewport());
- mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
- mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
- mouseEvent.setScenePos(mapToScene(d->mousePressViewPoint));
- mouseEvent.setScreenPos(d->mousePressScreenPoint);
- mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
- mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
- mouseEvent.setButtons(event->buttons());
- mouseEvent.setButtons(event->buttons());
- mouseEvent.setAccepted(false);
- mouseEvent.setButton(event->button());
- mouseEvent.setModifiers(event->modifiers());
- if (event->spontaneous())
- qt_sendSpontaneousEvent(d->scene, &mouseEvent);
- else
- QApplication::sendEvent(d->scene, &mouseEvent);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QGraphicsView);
-
- // Store this event for replaying, finding deltas, and for
- // scroll-dragging; even in non-interactive mode, scroll hand dragging is
- // allowed, so we store the event at the very top of this function.
- d->storeMouseEvent(event);
- d->lastMouseEvent.setAccepted(false);
-
- if (d->sceneInteractionAllowed) {
- // Store some of the event's button-down data.
- d->mousePressViewPoint = event->pos();
- d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
- d->mousePressScreenPoint = event->globalPos();
- d->lastMouseMoveScenePoint = d->mousePressScenePoint;
- d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
- d->mousePressButton = event->button();
-
- if (d->scene) {
- // Convert and deliver the mouse event to the scene.
- QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);
- mouseEvent.setWidget(viewport());
- mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
- mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
- mouseEvent.setScenePos(d->mousePressScenePoint);
- mouseEvent.setScreenPos(d->mousePressScreenPoint);
- mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
- mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
- mouseEvent.setButtons(event->buttons());
- mouseEvent.setButton(event->button());
- mouseEvent.setModifiers(event->modifiers());
- mouseEvent.setAccepted(false);
- if (event->spontaneous())
- qt_sendSpontaneousEvent(d->scene, &mouseEvent);
- else
- QApplication::sendEvent(d->scene, &mouseEvent);
-
- // Update the original mouse event accepted state.
- bool isAccepted = mouseEvent.isAccepted();
- event->setAccepted(isAccepted);
-
- // Update the last mouse event accepted state.
- d->lastMouseEvent.setAccepted(isAccepted);
-
- if (isAccepted)
- return;
- }
- }
-
-#ifndef QT_NO_RUBBERBAND
- if (d->dragMode == QGraphicsView::RubberBandDrag && !d->rubberBanding) {
- if (d->sceneInteractionAllowed) {
- // Rubberbanding is only allowed in interactive mode.
- event->accept();
- d->rubberBanding = true;
- d->rubberBandRect = QRect();
- if (d->scene) {
- // Initiating a rubber band always clears the selection.
- d->scene->clearSelection();
- }
- }
- } else
-#endif
- if (d->dragMode == QGraphicsView::ScrollHandDrag && event->button() == Qt::LeftButton) {
- // Left-button press in scroll hand mode initiates hand scrolling.
- event->accept();
- d->handScrolling = true;
- d->handScrollMotions = 0;
-#ifndef QT_NO_CURSOR
- viewport()->setCursor(Qt::ClosedHandCursor);
-#endif
- }
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QGraphicsView);
-
-#ifndef QT_NO_RUBBERBAND
- if (d->dragMode == QGraphicsView::RubberBandDrag && d->sceneInteractionAllowed) {
- d->storeMouseEvent(event);
- if (d->rubberBanding) {
- // Check for enough drag distance
- if ((d->mousePressViewPoint - event->pos()).manhattanLength()
- < QApplication::startDragDistance()) {
- return;
- }
-
- // Update old rubberband
- if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate && !d->rubberBandRect.isEmpty()) {
- if (d->viewportUpdateMode != FullViewportUpdate)
- viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect));
- else
- d->updateAll();
- }
-
- // Stop rubber banding if the user has let go of all buttons (even
- // if we didn't get the release events).
- if (!event->buttons()) {
- d->rubberBanding = false;
- d->rubberBandRect = QRect();
- return;
- }
-
- // Update rubberband position
- const QPoint &mp = d->mousePressViewPoint;
- QPoint ep = event->pos();
- d->rubberBandRect = QRect(qMin(mp.x(), ep.x()), qMin(mp.y(), ep.y()),
- qAbs(mp.x() - ep.x()) + 1, qAbs(mp.y() - ep.y()) + 1);
-
- // Update new rubberband
- if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate){
- if (d->viewportUpdateMode != FullViewportUpdate)
- viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect));
- else
- d->updateAll();
- }
- // Set the new selection area
- QPainterPath selectionArea;
- selectionArea.addPolygon(mapToScene(d->rubberBandRect));
- selectionArea.closeSubpath();
- if (d->scene)
- d->scene->setSelectionArea(selectionArea, d->rubberBandSelectionMode,
- viewportTransform());
- return;
- }
- } else
-#endif // QT_NO_RUBBERBAND
- if (d->dragMode == QGraphicsView::ScrollHandDrag) {
- if (d->handScrolling) {
- QScrollBar *hBar = horizontalScrollBar();
- QScrollBar *vBar = verticalScrollBar();
- QPoint delta = event->pos() - d->lastMouseEvent.pos();
- hBar->setValue(hBar->value() + (isRightToLeft() ? delta.x() : -delta.x()));
- vBar->setValue(vBar->value() - delta.y());
-
- // Detect how much we've scrolled to disambiguate scrolling from
- // clicking.
- ++d->handScrollMotions;
- }
- }
-
- d->mouseMoveEventHandler(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QGraphicsView);
-
-#ifndef QT_NO_RUBBERBAND
- if (d->dragMode == QGraphicsView::RubberBandDrag && d->sceneInteractionAllowed && !event->buttons()) {
- if (d->rubberBanding) {
- if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate){
- if (d->viewportUpdateMode != FullViewportUpdate)
- viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect));
- else
- d->updateAll();
- }
- d->rubberBanding = false;
- d->rubberBandRect = QRect();
- }
- } else
-#endif
- if (d->dragMode == QGraphicsView::ScrollHandDrag && event->button() == Qt::LeftButton) {
-#ifndef QT_NO_CURSOR
- // Restore the open hand cursor. ### There might be items
- // under the mouse that have a valid cursor at this time, so
- // we could repeat the steps from mouseMoveEvent().
- viewport()->setCursor(Qt::OpenHandCursor);
-#endif
- d->handScrolling = false;
-
- if (d->scene && d->sceneInteractionAllowed && !d->lastMouseEvent.isAccepted() && d->handScrollMotions <= 6) {
- // If we've detected very little motion during the hand drag, and
- // no item accepted the last event, we'll interpret that as a
- // click to the scene, and reset the selection.
- d->scene->clearSelection();
- }
- }
-
- d->storeMouseEvent(event);
-
- if (!d->sceneInteractionAllowed)
- return;
-
- if (!d->scene)
- return;
-
- QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseRelease);
- mouseEvent.setWidget(viewport());
- mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
- mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
- mouseEvent.setScenePos(mapToScene(event->pos()));
- mouseEvent.setScreenPos(event->globalPos());
- mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
- mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
- mouseEvent.setButtons(event->buttons());
- mouseEvent.setButton(event->button());
- mouseEvent.setModifiers(event->modifiers());
- mouseEvent.setAccepted(false);
- if (event->spontaneous())
- qt_sendSpontaneousEvent(d->scene, &mouseEvent);
- else
- QApplication::sendEvent(d->scene, &mouseEvent);
-
- // Update the last mouse event selected state.
- d->lastMouseEvent.setAccepted(mouseEvent.isAccepted());
-
-#ifndef QT_NO_CURSOR
- if (mouseEvent.isAccepted() && mouseEvent.buttons() == 0 && viewport()->testAttribute(Qt::WA_SetCursor)) {
- // The last mouse release on the viewport will trigger clearing the cursor.
- d->_q_unsetViewportCursor();
- }
-#endif
-}
-
-#ifndef QT_NO_WHEELEVENT
-/*!
- \reimp
-*/
-void QGraphicsView::wheelEvent(QWheelEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene || !d->sceneInteractionAllowed) {
- QAbstractScrollArea::wheelEvent(event);
- return;
- }
-
- event->ignore();
-
- QGraphicsSceneWheelEvent wheelEvent(QEvent::GraphicsSceneWheel);
- wheelEvent.setWidget(viewport());
- wheelEvent.setScenePos(mapToScene(event->pos()));
- wheelEvent.setScreenPos(event->globalPos());
- wheelEvent.setButtons(event->buttons());
- wheelEvent.setModifiers(event->modifiers());
- wheelEvent.setDelta(event->delta());
- wheelEvent.setOrientation(event->orientation());
- wheelEvent.setAccepted(false);
- QApplication::sendEvent(d->scene, &wheelEvent);
- event->setAccepted(wheelEvent.isAccepted());
- if (!event->isAccepted())
- QAbstractScrollArea::wheelEvent(event);
-}
-#endif // QT_NO_WHEELEVENT
-
-/*!
- \reimp
-*/
-void QGraphicsView::paintEvent(QPaintEvent *event)
-{
- Q_D(QGraphicsView);
- if (!d->scene) {
- QAbstractScrollArea::paintEvent(event);
- return;
- }
-
- // Set up painter state protection.
- d->scene->d_func()->painterStateProtection = !(d->optimizationFlags & DontSavePainterState);
-
- // Determine the exposed region
- d->exposedRegion = event->region();
- QRectF exposedSceneRect = mapToScene(d->exposedRegion.boundingRect()).boundingRect();
-
- // Set up the painter
- QPainter painter(viewport());
-#ifndef QT_NO_RUBBERBAND
- if (d->rubberBanding && !d->rubberBandRect.isEmpty())
- painter.save();
-#endif
- // Set up render hints
- painter.setRenderHints(painter.renderHints(), false);
- painter.setRenderHints(d->renderHints, true);
-
- // Set up viewport transform
- const bool viewTransformed = isTransformed();
- if (viewTransformed)
- painter.setWorldTransform(viewportTransform());
- const QTransform viewTransform = painter.worldTransform();
-
- // Draw background
- if ((d->cacheMode & CacheBackground)
-#ifdef Q_WS_X11
- && X11->use_xrender
-#endif
- ) {
- // Recreate the background pixmap, and flag the whole background as
- // exposed.
- if (d->mustResizeBackgroundPixmap) {
- d->backgroundPixmap = QPixmap(viewport()->size());
- QBrush bgBrush = viewport()->palette().brush(viewport()->backgroundRole());
- if (!bgBrush.isOpaque())
- d->backgroundPixmap.fill(Qt::transparent);
- QPainter p(&d->backgroundPixmap);
- p.fillRect(0, 0, d->backgroundPixmap.width(), d->backgroundPixmap.height(), bgBrush);
- d->backgroundPixmapExposed = QRegion(viewport()->rect());
- d->mustResizeBackgroundPixmap = false;
- }
-
- // Redraw exposed areas
- if (!d->backgroundPixmapExposed.isEmpty()) {
- QPainter backgroundPainter(&d->backgroundPixmap);
- backgroundPainter.setClipRegion(d->backgroundPixmapExposed, Qt::ReplaceClip);
- if (viewTransformed)
- backgroundPainter.setTransform(viewTransform);
- QRectF backgroundExposedSceneRect = mapToScene(d->backgroundPixmapExposed.boundingRect()).boundingRect();
- drawBackground(&backgroundPainter, backgroundExposedSceneRect);
- d->backgroundPixmapExposed = QRegion();
- }
-
- // Blit the background from the background pixmap
- if (viewTransformed) {
- painter.setWorldTransform(QTransform());
- painter.drawPixmap(QPoint(), d->backgroundPixmap);
- painter.setWorldTransform(viewTransform);
- } else {
- painter.drawPixmap(QPoint(), d->backgroundPixmap);
- }
- } else {
- if (!(d->optimizationFlags & DontSavePainterState))
- painter.save();
- drawBackground(&painter, exposedSceneRect);
- if (!(d->optimizationFlags & DontSavePainterState))
- painter.restore();
- }
-
- // Items
- if (!(d->optimizationFlags & IndirectPainting)) {
- const quint32 oldRectAdjust = d->scene->d_func()->rectAdjust;
- if (d->optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
- d->scene->d_func()->rectAdjust = 1;
- else
- d->scene->d_func()->rectAdjust = 2;
- d->scene->d_func()->drawItems(&painter, viewTransformed ? &viewTransform : 0,
- &d->exposedRegion, viewport());
- d->scene->d_func()->rectAdjust = oldRectAdjust;
- // Make sure the painter's world transform is restored correctly when
- // drawing without painter state protection (DontSavePainterState).
- // We only change the worldTransform() so there's no need to do a full-blown
- // save() and restore(). Also note that we don't have to do this in case of
- // IndirectPainting (the else branch), because in that case we always save()
- // and restore() in QGraphicsScene::drawItems().
- if (!d->scene->d_func()->painterStateProtection)
- painter.setOpacity(1.0);
- painter.setWorldTransform(viewTransform);
- } else {
- // Make sure we don't have unpolished items before we draw
- if (!d->scene->d_func()->unpolishedItems.isEmpty())
- d->scene->d_func()->_q_polishItems();
- // We reset updateAll here (after we've issued polish events)
- // so that we can discard update requests coming from polishEvent().
- d->scene->d_func()->updateAll = false;
-
- // Find all exposed items
- bool allItems = false;
- QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems, viewTransform);
- if (!itemList.isEmpty()) {
- // Generate the style options.
- const int numItems = itemList.size();
- QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid.
- QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems);
- QTransform transform(Qt::Uninitialized);
- for (int i = 0; i < numItems; ++i) {
- QGraphicsItem *item = itemArray[i];
- QGraphicsItemPrivate *itemd = item->d_ptr.data();
- itemd->initStyleOption(&styleOptionArray[i], viewTransform, d->exposedRegion, allItems);
- // Cache the item's area in view coordinates.
- // Note that we have to do this here in case the base class implementation
- // (QGraphicsScene::drawItems) is not called. If it is, we'll do this
- // operation twice, but that's the price one has to pay for using indirect
- // painting :-/.
- const QRectF brect = adjustedItemEffectiveBoundingRect(item);
- if (!itemd->itemIsUntransformable()) {
- transform = item->sceneTransform();
- if (viewTransformed)
- transform *= viewTransform;
- } else {
- transform = item->deviceTransform(viewTransform);
- }
- itemd->paintedViewBoundingRects.insert(d->viewport, transform.mapRect(brect).toRect());
- }
- // Draw the items.
- drawItems(&painter, numItems, itemArray, styleOptionArray);
- d->freeStyleOptionsArray(styleOptionArray);
- }
- }
-
- // Foreground
- drawForeground(&painter, exposedSceneRect);
-
-#ifndef QT_NO_RUBBERBAND
- // Rubberband
- if (d->rubberBanding && !d->rubberBandRect.isEmpty()) {
- painter.restore();
- QStyleOptionRubberBand option;
- option.initFrom(viewport());
- option.rect = d->rubberBandRect;
- option.shape = QRubberBand::Rectangle;
-
- QStyleHintReturnMask mask;
- if (viewport()->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, viewport(), &mask)) {
- // painter clipping for masked rubberbands
- painter.setClipRegion(mask.region, Qt::IntersectClip);
- }
-
- viewport()->style()->drawControl(QStyle::CE_RubberBand, &option, &painter, viewport());
- }
-#endif
-
- painter.end();
-
- // Restore painter state protection.
- d->scene->d_func()->painterStateProtection = true;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::resizeEvent(QResizeEvent *event)
-{
- Q_D(QGraphicsView);
- // Save the last center point - the resize may scroll the view, which
- // changes the center point.
- QPointF oldLastCenterPoint = d->lastCenterPoint;
-
- QAbstractScrollArea::resizeEvent(event);
- d->recalculateContentSize();
-
- // Restore the center point again.
- if (d->resizeAnchor == NoAnchor && !d->keepLastCenterPoint) {
- d->updateLastCenterPoint();
- } else {
- d->lastCenterPoint = oldLastCenterPoint;
- }
- d->centerView(d->resizeAnchor);
- d->keepLastCenterPoint = false;
-
- if (d->cacheMode & CacheBackground) {
- // Invalidate the background pixmap
- d->mustResizeBackgroundPixmap = true;
- }
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::scrollContentsBy(int dx, int dy)
-{
- Q_D(QGraphicsView);
- d->dirtyScroll = true;
- if (d->transforming)
- return;
- if (isRightToLeft())
- dx = -dx;
-
- if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate) {
- if (d->viewportUpdateMode != QGraphicsView::FullViewportUpdate) {
- if (d->accelerateScrolling) {
-#ifndef QT_NO_RUBBERBAND
- // Update new and old rubberband regions
- if (!d->rubberBandRect.isEmpty()) {
- QRegion rubberBandRegion(d->rubberBandRegion(viewport(), d->rubberBandRect));
- rubberBandRegion += rubberBandRegion.translated(-dx, -dy);
- viewport()->update(rubberBandRegion);
- }
-#endif
- d->dirtyScrollOffset.rx() += dx;
- d->dirtyScrollOffset.ry() += dy;
- d->dirtyRegion.translate(dx, dy);
- viewport()->scroll(dx, dy);
- } else {
- d->updateAll();
- }
- } else {
- d->updateAll();
- }
- }
-
- d->updateLastCenterPoint();
-
- if ((d->cacheMode & CacheBackground)
-#ifdef Q_WS_X11
- && X11->use_xrender
-#endif
- ) {
- // Scroll the background pixmap
- QRegion exposed;
- if (!d->backgroundPixmap.isNull())
- d->backgroundPixmap.scroll(dx, dy, d->backgroundPixmap.rect(), &exposed);
-
- // Invalidate the background pixmap
- d->backgroundPixmapExposed.translate(dx, dy);
- d->backgroundPixmapExposed += exposed;
- }
-
- // Always replay on scroll.
- if (d->sceneInteractionAllowed)
- d->replayLastMouseEvent();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::showEvent(QShowEvent *event)
-{
- Q_D(QGraphicsView);
- d->recalculateContentSize();
- d->centerView(d->transformationAnchor);
- QAbstractScrollArea::showEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsView::inputMethodEvent(QInputMethodEvent *event)
-{
- Q_D(QGraphicsView);
- if (d->scene)
- QApplication::sendEvent(d->scene, event);
-}
-
-/*!
- Draws the background of the scene using \a painter, before any items and
- the foreground are drawn. Reimplement this function to provide a custom
- background for this view.
-
- If all you want is to define a color, texture or gradient for the
- background, you can call setBackgroundBrush() instead.
-
- All painting is done in \e scene coordinates. \a rect is the exposed
- rectangle.
-
- The default implementation fills \a rect using the view's backgroundBrush.
- If no such brush is defined (the default), the scene's drawBackground()
- function is called instead.
-
- \sa drawForeground(), QGraphicsScene::drawBackground()
-*/
-void QGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
-{
- Q_D(QGraphicsView);
- if (d->scene && d->backgroundBrush.style() == Qt::NoBrush) {
- d->scene->drawBackground(painter, rect);
- return;
- }
-
- painter->fillRect(rect, d->backgroundBrush);
-}
-
-/*!
- Draws the foreground of the scene using \a painter, after the background
- and all items are drawn. Reimplement this function to provide a custom
- foreground for this view.
-
- If all you want is to define a color, texture or gradient for the
- foreground, you can call setForegroundBrush() instead.
-
- All painting is done in \e scene coordinates. \a rect is the exposed
- rectangle.
-
- The default implementation fills \a rect using the view's foregroundBrush.
- If no such brush is defined (the default), the scene's drawForeground()
- function is called instead.
-
- \sa drawBackground(), QGraphicsScene::drawForeground()
-*/
-void QGraphicsView::drawForeground(QPainter *painter, const QRectF &rect)
-{
- Q_D(QGraphicsView);
- if (d->scene && d->foregroundBrush.style() == Qt::NoBrush) {
- d->scene->drawForeground(painter, rect);
- return;
- }
-
- painter->fillRect(rect, d->foregroundBrush);
-}
-
-/*!
- \obsolete
-
- Draws the items \a items in the scene using \a painter, after the
- background and before the foreground are drawn. \a numItems is the number
- of items in \a items and options in \a options. \a options is a list of
- styleoptions; one for each item. Reimplement this function to provide
- custom item drawing for this view.
-
- The default implementation calls the scene's drawItems() function.
-
- Since Qt 4.6, this function is not called anymore unless
- the QGraphicsView::IndirectPainting flag is given as an Optimization
- flag.
-
- \sa drawForeground(), drawBackground(), QGraphicsScene::drawItems()
-*/
-void QGraphicsView::drawItems(QPainter *painter, int numItems,
- QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[])
-{
- Q_D(QGraphicsView);
- if (d->scene) {
- QWidget *widget = painter->device() == viewport() ? viewport() : 0;
- d->scene->drawItems(painter, numItems, items, options, widget);
- }
-}
-
-/*!
- Returns the current transformation matrix for the view. If no current
- transformation is set, the identity matrix is returned.
-
- \sa setTransform(), rotate(), scale(), shear(), translate()
-*/
-QTransform QGraphicsView::transform() const
-{
- Q_D(const QGraphicsView);
- return d->matrix;
-}
-
-/*!
- Returns a matrix that maps viewport coordinates to scene coordinates.
-
- \sa mapToScene(), mapFromScene()
-*/
-QTransform QGraphicsView::viewportTransform() const
-{
- Q_D(const QGraphicsView);
- QTransform moveMatrix = QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll());
- return d->identityMatrix ? moveMatrix : d->matrix * moveMatrix;
-}
-
-/*!
- \since 4.6
-
- Returns true if the view is transformed (i.e., a non-identity transform
- has been assigned, or the scrollbars are adjusted).
-
- \sa setTransform(), horizontalScrollBar(), verticalScrollBar()
-*/
-bool QGraphicsView::isTransformed() const
-{
- Q_D(const QGraphicsView);
- return !d->identityMatrix || d->horizontalScroll() || d->verticalScroll();
-}
-
-/*!
- Sets the view's current transformation matrix to \a matrix.
-
- If \a combine is true, then \a matrix is combined with the current matrix;
- otherwise, \a matrix \e replaces the current matrix. \a combine is false
- by default.
-
- The transformation matrix tranforms the scene into view coordinates. Using
- the default transformation, provided by the identity matrix, one pixel in
- the view represents one unit in the scene (e.g., a 10x10 rectangular item
- is drawn using 10x10 pixels in the view). If a 2x2 scaling matrix is
- applied, the scene will be drawn in 1:2 (e.g., a 10x10 rectangular item is
- then drawn using 20x20 pixels in the view).
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp 7
-
- To simplify interation with items using a transformed view, QGraphicsView
- provides mapTo... and mapFrom... functions that can translate between
- scene and view coordinates. For example, you can call mapToScene() to map
- a view coordiate to a floating point scene coordinate, or mapFromScene()
- to map from floating point scene coordinates to view coordinates.
-
- \sa transform(), rotate(), scale(), shear(), translate()
-*/
-void QGraphicsView::setTransform(const QTransform &matrix, bool combine )
-{
- Q_D(QGraphicsView);
- QTransform oldMatrix = d->matrix;
- if (!combine)
- d->matrix = matrix;
- else
- d->matrix = matrix * d->matrix;
- if (oldMatrix == d->matrix)
- return;
-
- d->identityMatrix = d->matrix.isIdentity();
- d->transforming = true;
- if (d->scene) {
- d->recalculateContentSize();
- d->centerView(d->transformationAnchor);
- } else {
- d->updateLastCenterPoint();
- }
-
- if (d->sceneInteractionAllowed)
- d->replayLastMouseEvent();
- d->transforming = false;
-
- // Any matrix operation requires a full update.
- d->updateAll();
-}
-
-/*!
- Resets the view transformation to the identity matrix.
-
- \sa transform(), setTransform()
-*/
-void QGraphicsView::resetTransform()
-{
- setTransform(QTransform());
-}
-
-QPointF QGraphicsViewPrivate::mapToScene(const QPointF &point) const
-{
- QPointF p = point;
- p.rx() += horizontalScroll();
- p.ry() += verticalScroll();
- return identityMatrix ? p : matrix.inverted().map(p);
-}
-
-QRectF QGraphicsViewPrivate::mapToScene(const QRectF &rect) const
-{
- QPointF scrollOffset(horizontalScroll(), verticalScroll());
- QPointF tl = scrollOffset + rect.topLeft();
- QPointF tr = scrollOffset + rect.topRight();
- QPointF br = scrollOffset + rect.bottomRight();
- QPointF bl = scrollOffset + rect.bottomLeft();
-
- QPolygonF poly(4);
- if (!identityMatrix) {
- QTransform x = matrix.inverted();
- poly[0] = x.map(tl);
- poly[1] = x.map(tr);
- poly[2] = x.map(br);
- poly[3] = x.map(bl);
- } else {
- poly[0] = tl;
- poly[1] = tr;
- poly[2] = br;
- poly[3] = bl;
- }
- return poly.boundingRect();
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qgraphicsview.cpp"
-
-#endif // QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h
deleted file mode 100644
index b2a7bdb226..0000000000
--- a/src/gui/graphicsview/qgraphicsview.h
+++ /dev/null
@@ -1,316 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSVIEW_H
-#define QGRAPHICSVIEW_H
-
-#include <QtCore/qmetatype.h>
-#include <QtGui/qpainter.h>
-#include <QtGui/qscrollarea.h>
-#include <QtGui/qgraphicsscene.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsItem;
-class QPainterPath;
-class QPolygonF;
-class QStyleOptionGraphicsItem;
-
-class QGraphicsViewPrivate;
-class Q_GUI_EXPORT QGraphicsView : public QAbstractScrollArea
-{
- Q_OBJECT
- Q_FLAGS(QPainter::RenderHints CacheMode OptimizationFlags)
- Q_ENUMS(ViewportAnchor DragMode ViewportUpdateMode)
- Q_PROPERTY(QBrush backgroundBrush READ backgroundBrush WRITE setBackgroundBrush)
- Q_PROPERTY(QBrush foregroundBrush READ foregroundBrush WRITE setForegroundBrush)
- Q_PROPERTY(bool interactive READ isInteractive WRITE setInteractive)
- Q_PROPERTY(QRectF sceneRect READ sceneRect WRITE setSceneRect)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
- Q_PROPERTY(QPainter::RenderHints renderHints READ renderHints WRITE setRenderHints)
- Q_PROPERTY(DragMode dragMode READ dragMode WRITE setDragMode)
- Q_PROPERTY(CacheMode cacheMode READ cacheMode WRITE setCacheMode)
- Q_PROPERTY(ViewportAnchor transformationAnchor READ transformationAnchor WRITE setTransformationAnchor)
- Q_PROPERTY(ViewportAnchor resizeAnchor READ resizeAnchor WRITE setResizeAnchor)
- Q_PROPERTY(ViewportUpdateMode viewportUpdateMode READ viewportUpdateMode WRITE setViewportUpdateMode)
-#ifndef QT_NO_RUBBERBAND
- Q_PROPERTY(Qt::ItemSelectionMode rubberBandSelectionMode READ rubberBandSelectionMode WRITE setRubberBandSelectionMode)
-#endif
- Q_PROPERTY(OptimizationFlags optimizationFlags READ optimizationFlags WRITE setOptimizationFlags)
-
-public:
- enum ViewportAnchor {
- NoAnchor,
- AnchorViewCenter,
- AnchorUnderMouse
- };
-
- enum CacheModeFlag {
- CacheNone = 0x0,
- CacheBackground = 0x1
- };
- Q_DECLARE_FLAGS(CacheMode, CacheModeFlag)
-
- enum DragMode {
- NoDrag,
- ScrollHandDrag,
- RubberBandDrag
- };
-
- enum ViewportUpdateMode {
- FullViewportUpdate,
- MinimalViewportUpdate,
- SmartViewportUpdate,
- NoViewportUpdate,
- BoundingRectViewportUpdate
- };
-
- enum OptimizationFlag {
- DontClipPainter = 0x1, // obsolete
- DontSavePainterState = 0x2,
- DontAdjustForAntialiasing = 0x4,
- IndirectPainting = 0x8
- };
- Q_DECLARE_FLAGS(OptimizationFlags, OptimizationFlag)
-
- QGraphicsView(QWidget *parent = 0);
- QGraphicsView(QGraphicsScene *scene, QWidget *parent = 0);
- ~QGraphicsView();
-
- QSize sizeHint() const;
-
- QPainter::RenderHints renderHints() const;
- void setRenderHint(QPainter::RenderHint hint, bool enabled = true);
- void setRenderHints(QPainter::RenderHints hints);
-
- Qt::Alignment alignment() const;
- void setAlignment(Qt::Alignment alignment);
-
- ViewportAnchor transformationAnchor() const;
- void setTransformationAnchor(ViewportAnchor anchor);
-
- ViewportAnchor resizeAnchor() const;
- void setResizeAnchor(ViewportAnchor anchor);
-
- ViewportUpdateMode viewportUpdateMode() const;
- void setViewportUpdateMode(ViewportUpdateMode mode);
-
- OptimizationFlags optimizationFlags() const;
- void setOptimizationFlag(OptimizationFlag flag, bool enabled = true);
- void setOptimizationFlags(OptimizationFlags flags);
-
- DragMode dragMode() const;
- void setDragMode(DragMode mode);
-
-#ifndef QT_NO_RUBBERBAND
- Qt::ItemSelectionMode rubberBandSelectionMode() const;
- void setRubberBandSelectionMode(Qt::ItemSelectionMode mode);
-#endif
-
- CacheMode cacheMode() const;
- void setCacheMode(CacheMode mode);
- void resetCachedContent();
-
- bool isInteractive() const;
- void setInteractive(bool allowed);
-
- QGraphicsScene *scene() const;
- void setScene(QGraphicsScene *scene);
-
- QRectF sceneRect() const;
- void setSceneRect(const QRectF &rect);
- inline void setSceneRect(qreal x, qreal y, qreal w, qreal h);
-
- QMatrix matrix() const;
- void setMatrix(const QMatrix &matrix, bool combine = false);
- void resetMatrix();
- QTransform transform() const;
- QTransform viewportTransform() const;
- bool isTransformed() const;
- void setTransform(const QTransform &matrix, bool combine = false);
- void resetTransform();
- void rotate(qreal angle);
- void scale(qreal sx, qreal sy);
- void shear(qreal sh, qreal sv);
- void translate(qreal dx, qreal dy);
-
- void centerOn(const QPointF &pos);
- inline void centerOn(qreal x, qreal y);
- void centerOn(const QGraphicsItem *item);
- void ensureVisible(const QRectF &rect, int xmargin = 50, int ymargin = 50);
- inline void ensureVisible(qreal x, qreal y, qreal w, qreal h, int xmargin = 50, int ymargin = 50);
- void ensureVisible(const QGraphicsItem *item, int xmargin = 50, int ymargin = 50);
- void fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRadioMode = Qt::IgnoreAspectRatio);
- inline void fitInView(qreal x, qreal y, qreal w, qreal h,
- Qt::AspectRatioMode aspectRadioMode = Qt::IgnoreAspectRatio);
- void fitInView(const QGraphicsItem *item,
- Qt::AspectRatioMode aspectRadioMode = Qt::IgnoreAspectRatio);
-
- void render(QPainter *painter, const QRectF &target = QRectF(), const QRect &source = QRect(),
- Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio);
-
- QList<QGraphicsItem *> items() const;
- QList<QGraphicsItem *> items(const QPoint &pos) const;
- inline QList<QGraphicsItem *> items(int x, int y) const;
- QList<QGraphicsItem *> items(const QRect &rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- inline QList<QGraphicsItem *> items(int x, int y, int w, int h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- QList<QGraphicsItem *> items(const QPolygon &polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
- QGraphicsItem *itemAt(const QPoint &pos) const;
- inline QGraphicsItem *itemAt(int x, int y) const;
-
- QPointF mapToScene(const QPoint &point) const;
- QPolygonF mapToScene(const QRect &rect) const;
- QPolygonF mapToScene(const QPolygon &polygon) const;
- QPainterPath mapToScene(const QPainterPath &path) const;
- QPoint mapFromScene(const QPointF &point) const;
- QPolygon mapFromScene(const QRectF &rect) const;
- QPolygon mapFromScene(const QPolygonF &polygon) const;
- QPainterPath mapFromScene(const QPainterPath &path) const;
- inline QPointF mapToScene(int x, int y) const;
- inline QPolygonF mapToScene(int x, int y, int w, int h) const;
- inline QPoint mapFromScene(qreal x, qreal y) const;
- inline QPolygon mapFromScene(qreal x, qreal y, qreal w, qreal h) const;
-
- QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
- QBrush backgroundBrush() const;
- void setBackgroundBrush(const QBrush &brush);
-
- QBrush foregroundBrush() const;
- void setForegroundBrush(const QBrush &brush);
-
-public Q_SLOTS:
- void updateScene(const QList<QRectF> &rects);
- void invalidateScene(const QRectF &rect = QRectF(), QGraphicsScene::SceneLayers layers = QGraphicsScene::AllLayers);
- void updateSceneRect(const QRectF &rect);
-
-protected Q_SLOTS:
- void setupViewport(QWidget *widget);
-
-protected:
- QGraphicsView(QGraphicsViewPrivate &, QWidget *parent = 0);
- bool event(QEvent *event);
- bool viewportEvent(QEvent *event);
-
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *event);
-#endif
- void dragEnterEvent(QDragEnterEvent *event);
- void dragLeaveEvent(QDragLeaveEvent *event);
- void dragMoveEvent(QDragMoveEvent *event);
- void dropEvent(QDropEvent *event);
- void focusInEvent(QFocusEvent *event);
- bool focusNextPrevChild(bool next);
- void focusOutEvent(QFocusEvent *event);
- void keyPressEvent(QKeyEvent *event);
- void keyReleaseEvent(QKeyEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *event);
-#endif
- void paintEvent(QPaintEvent *event);
- void resizeEvent(QResizeEvent *event);
- void scrollContentsBy(int dx, int dy);
- void showEvent(QShowEvent *event);
- void inputMethodEvent(QInputMethodEvent *event);
-
- virtual void drawBackground(QPainter *painter, const QRectF &rect);
- virtual void drawForeground(QPainter *painter, const QRectF &rect);
- virtual void drawItems(QPainter *painter, int numItems,
- QGraphicsItem *items[],
- const QStyleOptionGraphicsItem options[]);
-
-private:
- Q_DECLARE_PRIVATE(QGraphicsView)
- Q_DISABLE_COPY(QGraphicsView)
-#ifndef QT_NO_CURSOR
- Q_PRIVATE_SLOT(d_func(), void _q_setViewportCursor(const QCursor &))
- Q_PRIVATE_SLOT(d_func(), void _q_unsetViewportCursor())
-#endif
- friend class QGraphicsSceneWidget;
- friend class QGraphicsScene;
- friend class QGraphicsScenePrivate;
- friend class QGraphicsItemPrivate;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsView::CacheMode)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsView::OptimizationFlags)
-
-inline void QGraphicsView::setSceneRect(qreal ax, qreal ay, qreal aw, qreal ah)
-{ setSceneRect(QRectF(ax, ay, aw, ah)); }
-inline void QGraphicsView::centerOn(qreal ax, qreal ay)
-{ centerOn(QPointF(ax, ay)); }
-inline void QGraphicsView::ensureVisible(qreal ax, qreal ay, qreal aw, qreal ah, int xmargin, int ymargin)
-{ ensureVisible(QRectF(ax, ay, aw, ah), xmargin, ymargin); }
-inline void QGraphicsView::fitInView(qreal ax, qreal ay, qreal w, qreal h, Qt::AspectRatioMode mode)
-{ fitInView(QRectF(ax, ay, w, h), mode); }
-inline QList<QGraphicsItem *> QGraphicsView::items(int ax, int ay) const
-{ return items(QPoint(ax, ay)); }
-inline QList<QGraphicsItem *> QGraphicsView::items(int ax, int ay, int w, int h, Qt::ItemSelectionMode mode) const
-{ return items(QRect(ax, ay, w, h), mode); }
-inline QGraphicsItem *QGraphicsView::itemAt(int ax, int ay) const
-{ return itemAt(QPoint(ax, ay)); }
-inline QPointF QGraphicsView::mapToScene(int ax, int ay) const
-{ return mapToScene(QPoint(ax, ay)); }
-inline QPolygonF QGraphicsView::mapToScene(int ax, int ay, int w, int h) const
-{ return mapToScene(QRect(ax, ay, w, h)); }
-inline QPoint QGraphicsView::mapFromScene(qreal ax, qreal ay) const
-{ return mapFromScene(QPointF(ax, ay)); }
-inline QPolygon QGraphicsView::mapFromScene(qreal ax, qreal ay, qreal w, qreal h) const
-{ return mapFromScene(QRectF(ax, ay, w, h)); }
-
-#endif // QT_NO_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QGRAPHICSVIEW_H
diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h
deleted file mode 100644
index 5572b7e770..0000000000
--- a/src/gui/graphicsview/qgraphicsview_p.h
+++ /dev/null
@@ -1,233 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSVIEW_P_H
-#define QGRAPHICSVIEW_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 "qgraphicsview.h"
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-#include <QtGui/qevent.h>
-#include <QtCore/qcoreapplication.h>
-#include "qgraphicssceneevent.h"
-#include <QtGui/qstyleoption.h>
-#include <private/qabstractscrollarea_p.h>
-#include <private/qapplication_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class Q_GUI_EXPORT QGraphicsViewPrivate : public QAbstractScrollAreaPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsView)
-public:
- QGraphicsViewPrivate();
-
- void recalculateContentSize();
- void centerView(QGraphicsView::ViewportAnchor anchor);
-
- QPainter::RenderHints renderHints;
-
- QGraphicsView::DragMode dragMode;
-
- quint32 sceneInteractionAllowed : 1;
- quint32 hasSceneRect : 1;
- quint32 connectedToScene : 1;
- quint32 useLastMouseEvent : 1;
- quint32 identityMatrix : 1;
- quint32 dirtyScroll : 1;
- quint32 accelerateScrolling : 1;
- quint32 keepLastCenterPoint : 1;
- quint32 transforming : 1;
- quint32 handScrolling : 1;
- quint32 mustAllocateStyleOptions : 1;
- quint32 mustResizeBackgroundPixmap : 1;
- quint32 fullUpdatePending : 1;
- quint32 hasUpdateClip : 1;
- quint32 padding : 18;
-
- QRectF sceneRect;
- void updateLastCenterPoint();
-
- qint64 horizontalScroll() const;
- qint64 verticalScroll() const;
-
- QRectF mapRectToScene(const QRect &rect) const;
- QRectF mapRectFromScene(const QRectF &rect) const;
-
- QRect updateClip;
- QPointF mousePressItemPoint;
- QPointF mousePressScenePoint;
- QPoint mousePressViewPoint;
- QPoint mousePressScreenPoint;
- QPointF lastMouseMoveScenePoint;
- QPoint lastMouseMoveScreenPoint;
- QPoint dirtyScrollOffset;
- Qt::MouseButton mousePressButton;
- QTransform matrix;
- qint64 scrollX, scrollY;
- void updateScroll();
-
- qreal leftIndent;
- qreal topIndent;
-
- // Replaying mouse events
- QMouseEvent lastMouseEvent;
- void replayLastMouseEvent();
- void storeMouseEvent(QMouseEvent *event);
- void mouseMoveEventHandler(QMouseEvent *event);
-
- QPointF lastCenterPoint;
- Qt::Alignment alignment;
-
- QGraphicsView::ViewportAnchor transformationAnchor;
- QGraphicsView::ViewportAnchor resizeAnchor;
- QGraphicsView::ViewportUpdateMode viewportUpdateMode;
- QGraphicsView::OptimizationFlags optimizationFlags;
-
- QPointer<QGraphicsScene> scene;
-#ifndef QT_NO_RUBBERBAND
- QRect rubberBandRect;
- QRegion rubberBandRegion(const QWidget *widget, const QRect &rect) const;
- bool rubberBanding;
- Qt::ItemSelectionMode rubberBandSelectionMode;
-#endif
- int handScrollMotions;
-
- QGraphicsView::CacheMode cacheMode;
-
- QVector<QStyleOptionGraphicsItem> styleOptions;
- QStyleOptionGraphicsItem *allocStyleOptionsArray(int numItems);
- void freeStyleOptionsArray(QStyleOptionGraphicsItem *array);
-
- QBrush backgroundBrush;
- QBrush foregroundBrush;
- QPixmap backgroundPixmap;
- QRegion backgroundPixmapExposed;
-
-#ifndef QT_NO_CURSOR
- QCursor originalCursor;
- bool hasStoredOriginalCursor;
- void _q_setViewportCursor(const QCursor &cursor);
- void _q_unsetViewportCursor();
-#endif
-
- QGraphicsSceneDragDropEvent *lastDragDropEvent;
- void storeDragDropEvent(const QGraphicsSceneDragDropEvent *event);
- void populateSceneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
- QDropEvent *source);
-
- QRect mapToViewRect(const QGraphicsItem *item, const QRectF &rect) const;
- QRegion mapToViewRegion(const QGraphicsItem *item, const QRectF &rect) const;
- QRegion dirtyRegion;
- QRect dirtyBoundingRect;
- void processPendingUpdates();
- inline void updateAll()
- {
- viewport->update();
- fullUpdatePending = true;
- dirtyBoundingRect = QRect();
- dirtyRegion = QRegion();
- }
-
- inline void dispatchPendingUpdateRequests()
- {
-#ifdef Q_WS_MAC
- // QWidget::update() works slightly different on the Mac without the raster engine;
- // it's not part of our backing store so it needs special threatment.
- if (QApplicationPrivate::graphics_system_name != QLatin1String("raster")) {
- // At this point either HIViewSetNeedsDisplay (Carbon) or setNeedsDisplay: YES (Cocoa)
- // is called, which means there's a pending update request. We want to dispatch it
- // now because otherwise graphics view updates would require two
- // round-trips in the event loop before the item is painted.
- extern void qt_mac_dispatchPendingUpdateRequests(QWidget *);
- qt_mac_dispatchPendingUpdateRequests(viewport->window());
- } else
-#endif // !Q_WS_MAC
- {
- if (qt_widget_private(viewport)->paintOnScreen())
- QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest);
- else
- QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest);
- }
- }
-
- void setUpdateClip(QGraphicsItem *);
-
- inline bool updateRectF(const QRectF &rect)
- {
- if (rect.isEmpty())
- return false;
- if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
- return updateRect(rect.toAlignedRect().adjusted(-1, -1, 1, 1));
- return updateRect(rect.toAlignedRect().adjusted(-2, -2, 2, 2));
- }
-
- bool updateRect(const QRect &rect);
- bool updateRegion(const QRectF &rect, const QTransform &xform);
- bool updateSceneSlotReimplementedChecked;
- QRegion exposedRegion;
-
- QList<QGraphicsItem *> findItems(const QRegion &exposedRegion, bool *allItems,
- const QTransform &viewTransform) const;
-
- QPointF mapToScene(const QPointF &point) const;
- QRectF mapToScene(const QRectF &rect) const;
- static void translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent);
- void updateInputMethodSensitivity();
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GRAPHICSVIEW
-
-#endif
diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp
deleted file mode 100644
index 675a5c5c77..0000000000
--- a/src/gui/graphicsview/qgraphicswidget.cpp
+++ /dev/null
@@ -1,2388 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include "qgraphicswidget.h"
-#include "qgraphicswidget_p.h"
-#include "qgraphicslayout.h"
-#include "qgraphicslayout_p.h"
-#include "qgraphicsscene.h"
-#include "qgraphicssceneevent.h"
-
-#ifndef QT_NO_ACTION
-#include <private/qaction_p.h>
-#endif
-#include <private/qapplication_p.h>
-#include <private/qgraphicsscene_p.h>
-#ifndef QT_NO_SHORTCUT
-#include <private/qshortcutmap_p.h>
-#endif
-#include <QtCore/qmutex.h>
-#include <QtGui/qapplication.h>
-#include <QtGui/qgraphicsview.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qpalette.h>
-#include <QtGui/qstyleoption.h>
-
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QGraphicsWidget
- \brief The QGraphicsWidget class is the base class for all widget
- items in a QGraphicsScene.
- \since 4.4
- \ingroup graphicsview-api
-
- QGraphicsWidget is an extended base item that provides extra functionality
- over QGraphicsItem. It is similar to QWidget in many ways:
-
- \list
- \o Provides a \l palette, a \l font and a \l style().
- \o Has a defined geometry().
- \o Supports layouts with setLayout() and layout().
- \o Supports shortcuts and actions with grabShortcut() and insertAction()
- \endlist
-
- Unlike QGraphicsItem, QGraphicsWidget is not an abstract class; you can
- create instances of a QGraphicsWidget without having to subclass it.
- This approach is useful for widgets that only serve the purpose of
- organizing child widgets into a layout.
-
- QGraphicsWidget can be used as a base item for your own custom item if
- you require advanced input focus handling, e.g., tab focus and activation, or
- layouts.
-
- Since QGraphicsWidget resembles QWidget and has similar API, it is
- easier to port a widget from QWidget to QGraphicsWidget, instead of
- QGraphicsItem.
-
- \note QWidget-based widgets can be directly embedded into a
- QGraphicsScene using QGraphicsProxyWidget.
-
- Noticeable differences between QGraphicsWidget and QWidget are:
-
- \table
- \header \o QGraphicsWidget
- \o QWidget
- \row \o Coordinates and geometry are defined with qreals (doubles or
- floats, depending on the platform).
- \o QWidget uses integer geometry (QPoint, QRect).
- \row \o The widget is already visible by default; you do not have to
- call show() to display the widget.
- \o QWidget is hidden by default until you call show().
- \row \o A subset of widget attributes are supported.
- \o All widget attributes are supported.
- \row \o A top-level item's style defaults to QGraphicsScene::style
- \o A top-level widget's style defaults to QApplication::style
- \row \o Graphics View provides a custom drag and drop framework, different
- from QWidget.
- \o Standard drag and drop framework.
- \row \o Widget items do not support modality.
- \o Full modality support.
- \endtable
-
- QGraphicsWidget supports a subset of Qt's widget attributes,
- (Qt::WidgetAttribute), as shown in the table below. Any attributes not
- listed in this table are unsupported, or otherwise unused.
-
- \table
- \header \o Widget Attribute \o Usage
- \row \o Qt::WA_SetLayoutDirection
- \o Set by setLayoutDirection(), cleared by
- unsetLayoutDirection(). You can test this attribute to
- check if the widget has been explicitly assigned a
- \l{QGraphicsWidget::layoutDirection()}
- {layoutDirection}. If the attribute is not set, the
- \l{QGraphicsWidget::layoutDirection()}
- {layoutDirection()} is inherited.
- \row \o Qt::WA_RightToLeft
- \o Toggled by setLayoutDirection(). Inherited from the
- parent/scene. If set, the widget's layout will order
- horizontally arranged widgets from right to left.
- \row \o Qt::WA_SetStyle
- \o Set and cleared by setStyle(). If this attribute is
- set, the widget has been explicitly assigned a style.
- If it is unset, the widget will use the scene's or the
- application's style.
- \row \o Qt::WA_Resized
- \o Set by setGeometry() and resize().
- \row \o Qt::WA_SetPalette
- \o Set by setPalette().
- \row \o Qt::WA_SetFont
- \o Set by setPalette().
- \row \o Qt::WA_WindowPropagation
- \o Enables propagation to window widgets.
- \endtable
-
- Although QGraphicsWidget inherits from both QObject and QGraphicsItem,
- you should use the functions provided by QGraphicsItem, \e not QObject, to
- manage the relationships between parent and child items. These functions
- control the stacking order of items as well as their ownership.
-
- \note The QObject::parent() should always return 0 for QGraphicsWidgets,
- but this policy is not strictly defined.
-
- \sa QGraphicsProxyWidget, QGraphicsItem, {Widgets and Layouts}
-*/
-
-/*!
- Constructs a QGraphicsWidget instance. The optional \a parent argument is
- passed to QGraphicsItem's constructor. The optional \a wFlags argument
- specifies the widget's window flags (e.g., whether the widget should be a
- window, a tool, a popup, etc).
-*/
-QGraphicsWidget::QGraphicsWidget(QGraphicsItem *parent, Qt::WindowFlags wFlags)
- : QGraphicsObject(*new QGraphicsWidgetPrivate, 0, 0), QGraphicsLayoutItem(0, false)
-{
- Q_D(QGraphicsWidget);
- d->init(parent, wFlags);
-}
-
-/*!
- \internal
-
- Constructs a new QGraphicsWidget, using \a dd as parent.
-*/
-QGraphicsWidget::QGraphicsWidget(QGraphicsWidgetPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene, Qt::WindowFlags wFlags)
- : QGraphicsObject(dd, 0, scene), QGraphicsLayoutItem(0, false)
-{
- Q_D(QGraphicsWidget);
- d->init(parent, wFlags);
-}
-
-/*
- \internal
- \class QGraphicsWidgetStyles
-
- We use this thread-safe class to maintain a hash of styles for widgets
- styles. Note that QApplication::style() itself isn't thread-safe, QStyle
- isn't thread-safe, and we don't have a thread-safe factory for creating
- the default style, nor cloning a style.
-*/
-class QGraphicsWidgetStyles
-{
-public:
- QStyle *styleForWidget(const QGraphicsWidget *widget) const
- {
- QMutexLocker locker(&mutex);
- return styles.value(widget, 0);
- }
-
- void setStyleForWidget(QGraphicsWidget *widget, QStyle *style)
- {
- QMutexLocker locker(&mutex);
- if (style)
- styles[widget] = style;
- else
- styles.remove(widget);
- }
-
-private:
- QMap<const QGraphicsWidget *, QStyle *> styles;
- mutable QMutex mutex;
-};
-Q_GLOBAL_STATIC(QGraphicsWidgetStyles, widgetStyles)
-
-/*!
- Destroys the QGraphicsWidget instance.
-*/
-QGraphicsWidget::~QGraphicsWidget()
-{
- Q_D(QGraphicsWidget);
-#ifndef QT_NO_ACTION
- // Remove all actions from this widget
- for (int i = 0; i < d->actions.size(); ++i) {
- QActionPrivate *apriv = d->actions.at(i)->d_func();
- apriv->graphicsWidgets.removeAll(this);
- }
- d->actions.clear();
-#endif
-
- if (QGraphicsScene *scn = scene()) {
- QGraphicsScenePrivate *sceneD = scn->d_func();
- if (sceneD->tabFocusFirst == this)
- sceneD->tabFocusFirst = (d->focusNext == this ? 0 : d->focusNext);
- }
- d->focusPrev->d_func()->focusNext = d->focusNext;
- d->focusNext->d_func()->focusPrev = d->focusPrev;
-
- // Play it really safe
- d->focusNext = this;
- d->focusPrev = this;
-
- clearFocus();
-
- //we check if we have a layout previously
- if (d->layout) {
- QGraphicsLayout *temp = d->layout;
- foreach (QGraphicsItem * item, childItems()) {
- // In case of a custom layout which doesn't remove and delete items, we ensure that
- // the parent layout item does not point to the deleted layout. This code is here to
- // avoid regression from 4.4 to 4.5, because according to 4.5 docs it is not really needed.
- if (item->isWidget()) {
- QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
- if (widget->parentLayoutItem() == d->layout)
- widget->setParentLayoutItem(0);
- }
- }
- d->layout = 0;
- delete temp;
- }
-
- // Remove this graphics widget from widgetStyles
- widgetStyles()->setStyleForWidget(this, 0);
-}
-
-/*!
- \property QGraphicsWidget::size
- \brief the size of the widget
-
- Calling resize() resizes the widget to a \a size bounded by minimumSize()
- and maximumSize(). This property only affects the widget's width and
- height (e.g., its right and bottom edges); the widget's position and
- top-left corner remains unaffected.
-
- Resizing a widget triggers the widget to immediately receive a
- \l{QEvent::GraphicsSceneResize}{GraphicsSceneResize} event with the
- widget's old and new size. If the widget has a layout assigned when this
- event arrives, the layout will be activated and it will automatically
- update any child widgets's geometry.
-
- This property does not affect any layout of the parent widget. If the
- widget itself is managed by a parent layout; e.g., it has a parent widget
- with a layout assigned, that layout will not activate.
-
- By default, this property contains a size with zero width and height.
-
- \sa setGeometry(), QGraphicsSceneResizeEvent, QGraphicsLayout
-*/
-QSizeF QGraphicsWidget::size() const
-{
- return QGraphicsLayoutItem::geometry().size();
-}
-
-void QGraphicsWidget::resize(const QSizeF &size)
-{
- setGeometry(QRectF(pos(), size));
-}
-
-/*!
- \fn void QGraphicsWidget::resize(qreal w, qreal h)
-
- This convenience function is equivalent to calling resize(QSizeF(w, h)).
-
- \sa setGeometry(), setTransform()
-*/
-
-/*!
- \property QGraphicsWidget::sizePolicy
- \brief the size policy for the widget
- \sa sizePolicy(), setSizePolicy(), QWidget::sizePolicy()
-*/
-
-/*!
- \fn QGraphicsWidget::geometryChanged()
-
- This signal gets emitted whenever the geometry is changed in setGeometry().
-*/
-
-/*!
- \property QGraphicsWidget::geometry
- \brief the geometry of the widget
-
- Sets the item's geometry to \a rect. The item's position and size are
- modified as a result of calling this function. The item is first moved,
- then resized.
-
- A side effect of calling this function is that the widget will receive
- a move event and a resize event. Also, if the widget has a layout
- assigned, the layout will activate.
-
- \sa geometry(), resize()
-*/
-void QGraphicsWidget::setGeometry(const QRectF &rect)
-{
- QGraphicsWidgetPrivate *wd = QGraphicsWidget::d_func();
- QGraphicsLayoutItemPrivate *d = QGraphicsLayoutItem::d_ptr.data();
- QRectF newGeom;
- QPointF oldPos = d->geom.topLeft();
- if (!wd->inSetPos) {
- setAttribute(Qt::WA_Resized);
- newGeom = rect;
- newGeom.setSize(rect.size().expandedTo(effectiveSizeHint(Qt::MinimumSize))
- .boundedTo(effectiveSizeHint(Qt::MaximumSize)));
- if (newGeom == d->geom)
- return;
-
- // setPos triggers ItemPositionChange, which can adjust position
- wd->inSetGeometry = 1;
- setPos(newGeom.topLeft());
- wd->inSetGeometry = 0;
- newGeom.moveTopLeft(pos());
-
- if (newGeom == d->geom)
- return;
-
- // Update and prepare to change the geometry (remove from index) if the size has changed.
- if (wd->scene) {
- if (rect.topLeft() == d->geom.topLeft()) {
- prepareGeometryChange();
- }
- }
- }
-
- // Update the layout item geometry
- bool moved = oldPos != pos();
- if (moved) {
- // Send move event.
- QGraphicsSceneMoveEvent event;
- event.setOldPos(oldPos);
- event.setNewPos(pos());
- QApplication::sendEvent(this, &event);
- if (wd->inSetPos) {
- //set the new pos
- d->geom.moveTopLeft(pos());
- emit geometryChanged();
- return;
- }
- }
- QSizeF oldSize = size();
- QGraphicsLayoutItem::setGeometry(newGeom);
- // Send resize event
- bool resized = newGeom.size() != oldSize;
- if (resized) {
- QGraphicsSceneResizeEvent re;
- re.setOldSize(oldSize);
- re.setNewSize(newGeom.size());
- if (oldSize.width() != newGeom.size().width())
- emit widthChanged();
- if (oldSize.height() != newGeom.size().height())
- emit heightChanged();
- QApplication::sendEvent(this, &re);
- }
- emit geometryChanged();
-}
-
-/*!
- \fn QRectF QGraphicsWidget::rect() const
-
- Returns the item's local rect as a QRectF. This function is equivalent
- to QRectF(QPointF(), size()).
-
- \sa setGeometry(), resize()
-*/
-
-/*!
- \fn void QGraphicsWidget::setGeometry(qreal x, qreal y, qreal w, qreal h)
-
- This convenience function is equivalent to calling setGeometry(QRectF(
- \a x, \a y, \a w, \a h)).
-
- \sa geometry(), resize()
-*/
-
-/*!
- \property QGraphicsWidget::minimumSize
- \brief the minimum size of the widget
-
- \sa setMinimumSize(), minimumSize(), preferredSize, maximumSize
-*/
-
-/*!
- \property QGraphicsWidget::preferredSize
- \brief the preferred size of the widget
-
- \sa setPreferredSize(), preferredSize(), minimumSize, maximumSize
-*/
-
-/*!
- \property QGraphicsWidget::maximumSize
- \brief the maximum size of the widget
-
- \sa setMaximumSize(), maximumSize(), minimumSize, preferredSize
-*/
-
-/*!
- Sets the widget's contents margins to \a left, \a top, \a right and \a
- bottom.
-
- Contents margins are used by the assigned layout to define the placement
- of subwidgets and layouts. Margins are particularly useful for widgets
- that constrain subwidgets to only a section of its own geometry. For
- example, a group box with a layout will place subwidgets inside its frame,
- but below the title.
-
- Changing a widget's contents margins will always trigger an update(), and
- any assigned layout will be activated automatically. The widget will then
- receive a \l{QEvent::ContentsRectChange}{ContentsRectChange} event.
-
- \sa getContentsMargins(), setGeometry()
-*/
-void QGraphicsWidget::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom)
-{
- Q_D(QGraphicsWidget);
-
- if (!d->margins && left == 0 && top == 0 && right == 0 && bottom == 0)
- return;
- d->ensureMargins();
- if (left == d->margins[d->Left]
- && top == d->margins[d->Top]
- && right == d->margins[d->Right]
- && bottom == d->margins[d->Bottom])
- return;
-
- d->margins[d->Left] = left;
- d->margins[d->Top] = top;
- d->margins[d->Right] = right;
- d->margins[d->Bottom] = bottom;
-
- if (QGraphicsLayout *l = d->layout)
- l->invalidate();
- else
- updateGeometry();
-
- QEvent e(QEvent::ContentsRectChange);
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- Gets the widget's contents margins. The margins are stored in \a left, \a
- top, \a right and \a bottom, as pointers to qreals. Each argument can
- be \e {omitted} by passing 0.
-
- \sa setContentsMargins()
-*/
-void QGraphicsWidget::getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const
-{
- Q_D(const QGraphicsWidget);
- if (left || top || right || bottom)
- d->ensureMargins();
- if (left)
- *left = d->margins[d->Left];
- if (top)
- *top = d->margins[d->Top];
- if (right)
- *right = d->margins[d->Right];
- if (bottom)
- *bottom = d->margins[d->Bottom];
-}
-
-/*!
- Sets the widget's window frame margins to \a left, \a top, \a right and
- \a bottom. The default frame margins are provided by the style, and they
- depend on the current window flags.
-
- If you would like to draw your own window decoration, you can set your
- own frame margins to override the default margins.
-
- \sa unsetWindowFrameMargins(), getWindowFrameMargins(), windowFrameRect()
-*/
-void QGraphicsWidget::setWindowFrameMargins(qreal left, qreal top, qreal right, qreal bottom)
-{
- Q_D(QGraphicsWidget);
-
- if (!d->windowFrameMargins && left == 0 && top == 0 && right == 0 && bottom == 0)
- return;
- d->ensureWindowFrameMargins();
- bool unchanged =
- d->windowFrameMargins[d->Left] == left
- && d->windowFrameMargins[d->Top] == top
- && d->windowFrameMargins[d->Right] == right
- && d->windowFrameMargins[d->Bottom] == bottom;
- if (d->setWindowFrameMargins && unchanged)
- return;
- if (!unchanged)
- prepareGeometryChange();
- d->windowFrameMargins[d->Left] = left;
- d->windowFrameMargins[d->Top] = top;
- d->windowFrameMargins[d->Right] = right;
- d->windowFrameMargins[d->Bottom] = bottom;
- d->setWindowFrameMargins = true;
-}
-
-/*!
- Gets the widget's window frame margins. The margins are stored in \a left,
- \a top, \a right and \a bottom as pointers to qreals. Each argument can
- be \e {omitted} by passing 0.
-
- \sa setWindowFrameMargins(), windowFrameRect()
-*/
-void QGraphicsWidget::getWindowFrameMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const
-{
- Q_D(const QGraphicsWidget);
- if (left || top || right || bottom)
- d->ensureWindowFrameMargins();
- if (left)
- *left = d->windowFrameMargins[d->Left];
- if (top)
- *top = d->windowFrameMargins[d->Top];
- if (right)
- *right = d->windowFrameMargins[d->Right];
- if (bottom)
- *bottom = d->windowFrameMargins[d->Bottom];
-}
-
-/*!
- Resets the window frame margins to the default value, provided by the style.
-
- \sa setWindowFrameMargins(), getWindowFrameMargins(), windowFrameRect()
-*/
-void QGraphicsWidget::unsetWindowFrameMargins()
-{
- Q_D(QGraphicsWidget);
- if ((d->windowFlags & Qt::Window) && (d->windowFlags & Qt::WindowType_Mask) != Qt::Popup &&
- (d->windowFlags & Qt::WindowType_Mask) != Qt::ToolTip && !(d->windowFlags & Qt::FramelessWindowHint)) {
- QStyleOptionTitleBar bar;
- d->initStyleOptionTitleBar(&bar);
- QStyle *style = this->style();
- qreal margin = style->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth);
- qreal titleBarHeight = d->titleBarHeight(bar);
- setWindowFrameMargins(margin, titleBarHeight, margin, margin);
- } else {
- setWindowFrameMargins(0, 0, 0, 0);
- }
- d->setWindowFrameMargins = false;
-}
-
-/*!
- Returns the widget's geometry in parent coordinates including any window
- frame.
-
- \sa windowFrameRect(), getWindowFrameMargins(), setWindowFrameMargins()
-*/
-QRectF QGraphicsWidget::windowFrameGeometry() const
-{
- Q_D(const QGraphicsWidget);
- return d->windowFrameMargins
- ? geometry().adjusted(-d->windowFrameMargins[d->Left], -d->windowFrameMargins[d->Top],
- d->windowFrameMargins[d->Right], d->windowFrameMargins[d->Bottom])
- : geometry();
-}
-
-/*!
- Returns the widget's local rect including any window frame.
-
- \sa windowFrameGeometry(), getWindowFrameMargins(), setWindowFrameMargins()
-*/
-QRectF QGraphicsWidget::windowFrameRect() const
-{
- Q_D(const QGraphicsWidget);
- return d->windowFrameMargins
- ? rect().adjusted(-d->windowFrameMargins[d->Left], -d->windowFrameMargins[d->Top],
- d->windowFrameMargins[d->Right], d->windowFrameMargins[d->Bottom])
- : rect();
-}
-
-/*!
- Populates a style option object for this widget based on its current
- state, and stores the output in \a option. The default implementation
- populates \a option with the following properties.
-
- \table
- \header
- \o Style Option Property
- \o Value
- \row
- \o state & QStyle::State_Enabled
- \o Corresponds to QGraphicsItem::isEnabled().
- \row
- \o state & QStyle::State_HasFocus
- \o Corresponds to QGraphicsItem::hasFocus().
- \row
- \o state & QStyle::State_MouseOver
- \o Corresponds to QGraphicsItem::isUnderMouse().
- \row
- \o direction
- \o Corresponds to QGraphicsWidget::layoutDirection().
- \row
- \o rect
- \o Corresponds to QGraphicsWidget::rect().toRect().
- \row
- \o palette
- \o Corresponds to QGraphicsWidget::palette().
- \row
- \o fontMetrics
- \o Corresponds to QFontMetrics(QGraphicsWidget::font()).
- \endtable
-
- Subclasses of QGraphicsWidget should call the base implementation, and
- then test the type of \a option using qstyleoption_cast<>() or test
- QStyleOption::Type before storing widget-specific options.
-
- For example:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp 0
-
- \sa QStyleOption::initFrom()
-*/
-void QGraphicsWidget::initStyleOption(QStyleOption *option) const
-{
- Q_ASSERT(option);
-
- option->state = QStyle::State_None;
- if (isEnabled())
- option->state |= QStyle::State_Enabled;
- if (hasFocus())
- option->state |= QStyle::State_HasFocus;
- // if (window->testAttribute(Qt::WA_KeyboardFocusChange)) // ### Window
- // option->state |= QStyle::State_KeyboardFocusChange;
- if (isUnderMouse())
- option->state |= QStyle::State_MouseOver;
- if (QGraphicsWidget *w = window()) {
- if (w->isActiveWindow())
- option->state |= QStyle::State_Active;
- }
- if (isWindow())
- option->state |= QStyle::State_Window;
- /*
- ###
-#ifdef Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QGraphicsWidget *w); //qwidget_mac.cpp
- if (!(option->state & QStyle::State_Active) && !qt_mac_can_clickThrough(widget))
- option->state &= ~QStyle::State_Enabled;
-
- switch (QMacStyle::widgetSizePolicy(widget)) {
- case QMacStyle::SizeSmall:
- option->state |= QStyle::State_Small;
- break;
- case QMacStyle::SizeMini:
- option->state |= QStyle::State_Mini;
- break;
- default:
- ;
- }
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- if (widget->hasEditFocus())
- state |= QStyle::State_HasEditFocus;
-#endif
- */
- option->direction = layoutDirection();
- option->rect = rect().toRect(); // ### truncation!
- option->palette = palette();
- if (!isEnabled()) {
- option->palette.setCurrentColorGroup(QPalette::Disabled);
- } else if (isActiveWindow()) {
- option->palette.setCurrentColorGroup(QPalette::Active);
- } else {
- option->palette.setCurrentColorGroup(QPalette::Inactive);
- }
- option->fontMetrics = QFontMetrics(font());
-}
-
-/*!
- \reimp
-*/
-QSizeF QGraphicsWidget::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- Q_D(const QGraphicsWidget);
- QSizeF sh;
- if (d->layout) {
- QSizeF marginSize(0,0);
- if (d->margins) {
- marginSize = QSizeF(d->margins[d->Left] + d->margins[d->Right],
- d->margins[d->Top] + d->margins[d->Bottom]);
- }
- sh = d->layout->effectiveSizeHint(which, constraint - marginSize);
- sh += marginSize;
- } else {
- switch (which) {
- case Qt::MinimumSize:
- sh = QSizeF(0, 0);
- break;
- case Qt::PreferredSize:
- sh = QSizeF(50, 50); //rather arbitrary
- break;
- case Qt::MaximumSize:
- sh = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
- break;
- default:
- qWarning("QGraphicsWidget::sizeHint(): Don't know how to handle the value of 'which'");
- break;
- }
- }
- return sh;
-}
-
-/*!
- \property QGraphicsWidget::layout
- \brief The layout of the widget
-
- Any existing layout manager is deleted before the new layout is assigned. If
- \a layout is 0, the widget is left without a layout. Existing subwidgets'
- geometries will remain unaffected.
-
- QGraphicsWidget takes ownership of \a layout.
-
- All widgets that are currently managed by \a layout or all of its
- sublayouts, are automatically reparented to this item. The layout is then
- invalidated, and the child widget geometries are adjusted according to
- this item's geometry() and contentsMargins(). Children who are not
- explicitly managed by \a layout remain unaffected by the layout after
- it has been assigned to this widget.
-
- If no layout is currently managing this widget, layout() will return 0.
-
-*/
-
-/*!
- \fn void QGraphicsWidget::layoutChanged()
- This signal gets emitted whenever the layout of the item changes
- \internal
-*/
-
-/*!
- Returns this widget's layout, or 0 if no layout is currently managing this
- widget.
-
- \sa setLayout()
-*/
-QGraphicsLayout *QGraphicsWidget::layout() const
-{
- Q_D(const QGraphicsWidget);
- return d->layout;
-}
-
-/*!
- \fn void QGraphicsWidget::setLayout(QGraphicsLayout *layout)
-
- Sets the layout for this widget to \a layout. Any existing layout manager
- is deleted before the new layout is assigned. If \a layout is 0, the
- widget is left without a layout. Existing subwidgets' geometries will
- remain unaffected.
-
- All widgets that are currently managed by \a layout or all of its
- sublayouts, are automatically reparented to this item. The layout is then
- invalidated, and the child widget geometries are adjusted according to
- this item's geometry() and contentsMargins(). Children who are not
- explicitly managed by \a layout remain unaffected by the layout after
- it has been assigned to this widget.
-
- QGraphicsWidget takes ownership of \a layout.
-
- \sa layout(), QGraphicsLinearLayout::addItem(), QGraphicsLayout::invalidate()
-*/
-void QGraphicsWidget::setLayout(QGraphicsLayout *l)
-{
- Q_D(QGraphicsWidget);
- if (d->layout == l)
- return;
- d->setLayout_helper(l);
- if (!l)
- return;
-
- // Prevent assigning a layout that is already assigned to another widget.
- QGraphicsLayoutItem *oldParent = l->parentLayoutItem();
- if (oldParent && oldParent != this) {
- qWarning("QGraphicsWidget::setLayout: Attempting to set a layout on %s"
- " \"%s\", when the layout already has a parent",
- metaObject()->className(), qPrintable(objectName()));
- return;
- }
-
- // Install and activate the layout.
- l->setParentLayoutItem(this);
- l->d_func()->reparentChildItems(this);
- l->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Adjusts the size of the widget to its effective preferred size hint.
-
- This function is called implicitly when the item is shown for the first
- time.
-
- \sa effectiveSizeHint(), Qt::MinimumSize
-*/
-void QGraphicsWidget::adjustSize()
-{
- QSizeF sz = effectiveSizeHint(Qt::PreferredSize);
- // What if sz is not valid?!
- if (sz.isValid())
- resize(sz);
-}
-
-/*!
- \property QGraphicsWidget::layoutDirection
- \brief the layout direction for this widget.
-
- This property modifies this widget's and all of its descendants'
- Qt::WA_RightToLeft attribute. It also sets this widget's
- Qt::WA_SetLayoutDirection attribute.
-
- The widget's layout direction determines the order in which the layout
- manager horizontally arranges subwidgets of this widget. The default
- value depends on the language and locale of the application, and is
- typically in the same direction as words are read and written. With
- Qt::LeftToRight, the layout starts placing subwidgets from the left
- side of this widget towards the right. Qt::RightToLeft does the opposite -
- the layout will place widgets starting from the right edge moving towards
- the left.
-
- Subwidgets inherit their layout direction from the parent. Top-level
- widget items inherit their layout direction from
- QGraphicsScene::layoutDirection. If you change a widget's layout direction
- by calling setLayoutDirection(), the widget will send itself a
- \l{QEvent::LayoutDirectionChange}{LayoutDirectionChange} event, and then
- propagate the new layout direction to all its descendants.
-
- \sa QWidget::layoutDirection, QApplication::layoutDirection
-*/
-Qt::LayoutDirection QGraphicsWidget::layoutDirection() const
-{
- return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
-}
-void QGraphicsWidget::setLayoutDirection(Qt::LayoutDirection direction)
-{
- Q_D(QGraphicsWidget);
- setAttribute(Qt::WA_SetLayoutDirection, true);
- d->setLayoutDirection_helper(direction);
-}
-void QGraphicsWidget::unsetLayoutDirection()
-{
- Q_D(QGraphicsWidget);
- setAttribute(Qt::WA_SetLayoutDirection, false);
- d->resolveLayoutDirection();
-}
-
-/*!
- Returns a pointer to the widget's style. If this widget does not have any
- explicitly assigned style, the scene's style is returned instead. In turn,
- if the scene does not have any assigned style, this function returns
- QApplication::style().
-
- \sa setStyle()
-*/
-QStyle *QGraphicsWidget::style() const
-{
- if (QStyle *style = widgetStyles()->styleForWidget(this))
- return style;
- // ### This is not thread-safe. QApplication::style() is not thread-safe.
- return scene() ? scene()->style() : QApplication::style();
-}
-
-/*!
- Sets the widget's style to \a style. QGraphicsWidget does \e not take
- ownership of \a style.
-
- If no style is assigned, or \a style is 0, the widget will use
- QGraphicsScene::style() (if this has been set). Otherwise the widget will
- use QApplication::style().
-
- This function sets the Qt::WA_SetStyle attribute if \a style is not 0;
- otherwise it clears the attribute.
-
- \sa style()
-*/
-void QGraphicsWidget::setStyle(QStyle *style)
-{
- setAttribute(Qt::WA_SetStyle, style != 0);
- widgetStyles()->setStyleForWidget(this, style);
-
- // Deliver StyleChange to the widget itself (doesn't propagate).
- QEvent event(QEvent::StyleChange);
- QApplication::sendEvent(this, &event);
-}
-
-/*!
- \property QGraphicsWidget::font
- \brief the widgets' font
-
- This property provides the widget's font.
-
- QFont consists of font properties that have been explicitly defined and
- properties implicitly inherited from the widget's parent. Hence, font()
- can return a different font compared to the one set with setFont().
- This scheme allows you to define single entries in a font without
- affecting the font's inherited entries.
-
- When a widget's font changes, it resolves its entries against its
- parent widget. If the widget does not have a parent widget, it resolves
- its entries against the scene. The widget then sends itself a
- \l{QEvent::FontChange}{FontChange} event and notifies all its
- descendants so that they can resolve their fonts as well.
-
- By default, this property contains the application's default font.
-
- \sa QApplication::font(), QGraphicsScene::font, QFont::resolve()
-*/
-QFont QGraphicsWidget::font() const
-{
- Q_D(const QGraphicsWidget);
- QFont fnt = d->font;
- fnt.resolve(fnt.resolve() | d->inheritedFontResolveMask);
- return fnt;
-}
-void QGraphicsWidget::setFont(const QFont &font)
-{
- Q_D(QGraphicsWidget);
- setAttribute(Qt::WA_SetFont, font.resolve() != 0);
-
- QFont naturalFont = d->naturalWidgetFont();
- QFont resolvedFont = font.resolve(naturalFont);
- d->setFont_helper(resolvedFont);
-}
-
-/*!
- \property QGraphicsWidget::palette
- \brief the widget's palette
-
- This property provides the widget's palette. The palette provides colors
- and brushes for color groups (e.g., QPalette::Button) and states (e.g.,
- QPalette::Inactive), loosely defining the general look of the widget and
- its children.
-
- QPalette consists of color groups that have been explicitly defined, and
- groups that are implicitly inherited from the widget's parent. Because of
- this, palette() can return a different palette than what has been set with
- setPalette(). This scheme allows you to define single entries in a palette
- without affecting the palette's inherited entries.
-
- When a widget's palette changes, it resolves its entries against its
- parent widget, or if it doesn't have a parent widget, it resolves against
- the scene. It then sends itself a \l{QEvent::PaletteChange}{PaletteChange}
- event, and notifies all its descendants so they can resolve their palettes
- as well.
-
- By default, this property contains the application's default palette.
-
- \sa QApplication::palette(), QGraphicsScene::palette, QPalette::resolve()
-*/
-QPalette QGraphicsWidget::palette() const
-{
- Q_D(const QGraphicsWidget);
- return d->palette;
-}
-void QGraphicsWidget::setPalette(const QPalette &palette)
-{
- Q_D(QGraphicsWidget);
- setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
-
- QPalette naturalPalette = d->naturalWidgetPalette();
- QPalette resolvedPalette = palette.resolve(naturalPalette);
- d->setPalette_helper(resolvedPalette);
-}
-
-/*!
- \property QGraphicsWidget::autoFillBackground
- \brief whether the widget background is filled automatically
- \since 4.7
-
- If enabled, this property will cause Qt to fill the background of the
- widget before invoking the paint() method. The color used is defined by the
- QPalette::Window color role from the widget's \l{QPalette}{palette}.
-
- In addition, Windows are always filled with QPalette::Window, unless the
- WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
-
- By default, this property is false.
-
- \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
-*/
-bool QGraphicsWidget::autoFillBackground() const
-{
- Q_D(const QGraphicsWidget);
- return d->autoFillBackground;
-}
-void QGraphicsWidget::setAutoFillBackground(bool enabled)
-{
- Q_D(QGraphicsWidget);
- if (d->autoFillBackground != enabled) {
- d->autoFillBackground = enabled;
- update();
- }
-}
-
-/*!
- If this widget is currently managed by a layout, this function notifies
- the layout that the widget's size hints have changed and the layout
- may need to resize and reposition the widget accordingly.
-
- Call this function if the widget's sizeHint() has changed.
-
- \sa QGraphicsLayout::invalidate()
-*/
-void QGraphicsWidget::updateGeometry()
-{
- QGraphicsLayoutItem::updateGeometry();
- QGraphicsLayoutItem *parentItem = parentLayoutItem();
-
- if (parentItem && parentItem->isLayout()) {
- parentItem->updateGeometry();
- } else {
- if (parentItem) {
- QGraphicsWidget *parentWid = parentWidget(); //###
- if (parentWid->isVisible())
- QApplication::postEvent(parentWid, new QEvent(QEvent::LayoutRequest));
- }
- bool wasResized = testAttribute(Qt::WA_Resized);
- resize(size()); // this will restrict the size
- setAttribute(Qt::WA_Resized, wasResized);
- }
-}
-
-/*!
- \reimp
-
- QGraphicsWidget uses the base implementation of this function to catch and
- deliver events related to state changes in the item. Because of this, it is
- very important that subclasses call the base implementation.
-
- \a change specifies the type of change, and \a value is the new value.
-
- For example, QGraphicsWidget uses ItemVisibleChange to deliver
- \l{QEvent::Show} {Show} and \l{QEvent::Hide}{Hide} events,
- ItemPositionHasChanged to deliver \l{QEvent::Move}{Move} events,
- and ItemParentChange both to deliver \l{QEvent::ParentChange}
- {ParentChange} events, and for managing the focus chain.
-
- QGraphicsWidget enables the ItemSendsGeometryChanges flag by default in
- order to track position changes.
-
- \sa QGraphicsItem::itemChange()
-*/
-QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value)
-{
- Q_D(QGraphicsWidget);
- switch (change) {
- case ItemEnabledHasChanged: {
- // Send EnabledChange after the enabled state has changed.
- QEvent event(QEvent::EnabledChange);
- QApplication::sendEvent(this, &event);
- break;
- }
- case ItemVisibleChange:
- if (value.toBool()) {
- // Send Show event before the item has been shown.
- QShowEvent event;
- QApplication::sendEvent(this, &event);
- bool resized = testAttribute(Qt::WA_Resized);
- if (!resized) {
- adjustSize();
- setAttribute(Qt::WA_Resized, false);
- }
- }
- break;
- case ItemVisibleHasChanged:
- if (!value.toBool()) {
- // Send Hide event after the item has been hidden.
- QHideEvent event;
- QApplication::sendEvent(this, &event);
- }
- break;
- case ItemPositionHasChanged:
- d->setGeometryFromSetPos();
- break;
- case ItemParentChange: {
- // Deliver ParentAboutToChange.
- QEvent event(QEvent::ParentAboutToChange);
- QApplication::sendEvent(this, &event);
- break;
- }
- case ItemParentHasChanged: {
- // Deliver ParentChange.
- QEvent event(QEvent::ParentChange);
- QApplication::sendEvent(this, &event);
- break;
- }
- case ItemCursorHasChanged: {
- // Deliver CursorChange.
- QEvent event(QEvent::CursorChange);
- QApplication::sendEvent(this, &event);
- break;
- }
- case ItemToolTipHasChanged: {
- // Deliver ToolTipChange.
- QEvent event(QEvent::ToolTipChange);
- QApplication::sendEvent(this, &event);
- break;
- }
- default:
- break;
- }
- return QGraphicsItem::itemChange(change, value);
-}
-
-/*!
- \internal
-
- This virtual function is used to notify changes to any property (both
- dynamic properties, and registered with Q_PROPERTY) in the
- widget. Depending on the property itself, the notification can be
- delivered before or after the value has changed.
-
- \a propertyName is the name of the property (e.g., "size" or "font"), and
- \a value is the (proposed) new value of the property. The function returns
- the new value, which may be different from \a value if the notification
- supports adjusting the property value. The base implementation simply
- returns \a value for any \a propertyName.
-
- QGraphicsWidget delivers notifications for the following properties:
-
- \table \o propertyName \o Property
- \row \o layoutDirection \o QGraphicsWidget::layoutDirection
- \row \o size \o QGraphicsWidget::size
- \row \o font \o QGraphicsWidget::font
- \row \o palette \o QGraphicsWidget::palette
- \endtable
-
- \sa itemChange()
-*/
-QVariant QGraphicsWidget::propertyChange(const QString &propertyName, const QVariant &value)
-{
- Q_UNUSED(propertyName);
- return value;
-}
-
-/*!
- QGraphicsWidget's implementation of sceneEvent() simply passes \a event to
- QGraphicsWidget::event(). You can handle all events for your widget in
- event() or in any of the convenience functions; you should not have to
- reimplement this function in a subclass of QGraphicsWidget.
-
- \sa QGraphicsItem::sceneEvent()
-*/
-bool QGraphicsWidget::sceneEvent(QEvent *event)
-{
- return QGraphicsItem::sceneEvent(event);
-}
-
-/*!
- This event handler, for \a event, receives events for the window frame if
- this widget is a window. Its base implementation provides support for
- default window frame interaction such as moving, resizing, etc.
-
- You can reimplement this handler in a subclass of QGraphicsWidget to
- provide your own custom window frame interaction support.
-
- Returns true if \a event has been recognized and processed; otherwise,
- returns false.
-
- \sa event()
-*/
-bool QGraphicsWidget::windowFrameEvent(QEvent *event)
-{
- Q_D(QGraphicsWidget);
- switch (event->type()) {
- case QEvent::GraphicsSceneMousePress:
- d->windowFrameMousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneMouseMove:
- d->ensureWindowData();
- if (d->windowData->grabbedSection != Qt::NoSection) {
- d->windowFrameMouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- event->accept();
- }
- break;
- case QEvent::GraphicsSceneMouseRelease:
- d->windowFrameMouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
- break;
- case QEvent::GraphicsSceneHoverMove:
- d->windowFrameHoverMoveEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
- break;
- case QEvent::GraphicsSceneHoverLeave:
- d->windowFrameHoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
- break;
- default:
- break;
- }
- return event->isAccepted();
-}
-
-/*!
- \since 4.4
-
- Returns the window frame section at position \a pos, or
- Qt::NoSection if there is no window frame section at this
- position.
-
- This function is used in QGraphicsWidget's base implementation for window
- frame interaction.
-
- You can reimplement this function if you want to customize how a window
- can be interactively moved or resized. For instance, if you only want to
- allow a window to be resized by the bottom right corner, you can
- reimplement this function to return Qt::NoSection for all sections except
- Qt::BottomRightSection.
-
- \sa windowFrameEvent(), paintWindowFrame(), windowFrameGeometry()
-*/
-Qt::WindowFrameSection QGraphicsWidget::windowFrameSectionAt(const QPointF &pos) const
-{
- Q_D(const QGraphicsWidget);
-
- const QRectF r = windowFrameRect();
- if (!r.contains(pos))
- return Qt::NoSection;
-
- const qreal left = r.left();
- const qreal top = r.top();
- const qreal right = r.right();
- const qreal bottom = r.bottom();
- const qreal x = pos.x();
- const qreal y = pos.y();
-
- const qreal cornerMargin = 20;
- //### Not sure of this one, it should be the same value for all edges.
- const qreal windowFrameWidth = d->windowFrameMargins
- ? d->windowFrameMargins[d->Left] : 0;
-
- Qt::WindowFrameSection s = Qt::NoSection;
- if (x <= left + cornerMargin) {
- if (y <= top + windowFrameWidth || (x <= left + windowFrameWidth && y <= top + cornerMargin)) {
- s = Qt::TopLeftSection;
- } else if (y >= bottom - windowFrameWidth || (x <= left + windowFrameWidth && y >= bottom - windowFrameWidth)) {
- s = Qt::BottomLeftSection;
- } else if (x <= left + windowFrameWidth) {
- s = Qt::LeftSection;
- }
- } else if (x >= right - cornerMargin) {
- if (y <= top + windowFrameWidth || (x >= right - windowFrameWidth && y <= top + cornerMargin)) {
- s = Qt::TopRightSection;
- } else if (y >= bottom - windowFrameWidth || (x >= right - windowFrameWidth && y >= bottom - windowFrameWidth)) {
- s = Qt::BottomRightSection;
- } else if (x >= right - windowFrameWidth) {
- s = Qt::RightSection;
- }
- } else if (y <= top + windowFrameWidth) {
- s = Qt::TopSection;
- } else if (y >= bottom - windowFrameWidth) {
- s = Qt::BottomSection;
- }
- if (s == Qt::NoSection) {
- QRectF r1 = r;
- r1.setHeight(d->windowFrameMargins
- ? d->windowFrameMargins[d->Top] : 0);
- if (r1.contains(pos))
- s = Qt::TitleBarArea;
- }
- return s;
-}
-
-/*!
- \reimp
-
- Handles the \a event. QGraphicsWidget handles the following
- events:
-
- \table \o Event \o Usage
- \row \o Polish
- \o Delivered to the widget some time after it has been
- shown.
- \row \o GraphicsSceneMove
- \o Delivered to the widget after its local position has
- changed.
- \row \o GraphicsSceneResize
- \o Delivered to the widget after its size has changed.
- \row \o Show
- \o Delivered to the widget before it has been shown.
- \row \o Hide
- \o Delivered to the widget after it has been hidden.
- \row \o PaletteChange
- \o Delivered to the widget after its palette has changed.
- \row \o FontChange
- \o Delivered to the widget after its font has changed.
- \row \o EnabledChange
- \o Delivered to the widget after its enabled state has
- changed.
- \row \o StyleChange
- \o Delivered to the widget after its style has changed.
- \row \o LayoutDirectionChange
- \o Delivered to the widget after its layout direction has
- changed.
- \row \o ContentsRectChange
- \o Delivered to the widget after its contents margins/
- contents rect has changed.
- \endtable
-*/
-bool QGraphicsWidget::event(QEvent *event)
-{
- Q_D(QGraphicsWidget);
- // Forward the event to the layout first.
- if (d->layout)
- d->layout->widgetEvent(event);
-
- // Handle the event itself.
- switch (event->type()) {
- case QEvent::GraphicsSceneMove:
- moveEvent(static_cast<QGraphicsSceneMoveEvent *>(event));
- break;
- case QEvent::GraphicsSceneResize:
- resizeEvent(static_cast<QGraphicsSceneResizeEvent *>(event));
- break;
- case QEvent::Show:
- showEvent(static_cast<QShowEvent *>(event));
- break;
- case QEvent::Hide:
- hideEvent(static_cast<QHideEvent *>(event));
- break;
- case QEvent::Polish:
- polishEvent();
- d->polished = true;
- if (!d->font.isCopyOf(QApplication::font()))
- d->updateFont(d->font);
- break;
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- update();
- break;
- // Taken from QWidget::event
- case QEvent::ActivationChange:
- case QEvent::EnabledChange:
- case QEvent::FontChange:
- case QEvent::StyleChange:
- case QEvent::PaletteChange:
- case QEvent::ParentChange:
- case QEvent::ContentsRectChange:
- case QEvent::LayoutDirectionChange:
- changeEvent(event);
- break;
- case QEvent::Close:
- closeEvent((QCloseEvent *)event);
- break;
- case QEvent::GrabMouse:
- grabMouseEvent(event);
- break;
- case QEvent::UngrabMouse:
- ungrabMouseEvent(event);
- break;
- case QEvent::GrabKeyboard:
- grabKeyboardEvent(event);
- break;
- case QEvent::UngrabKeyboard:
- ungrabKeyboardEvent(event);
- break;
- case QEvent::GraphicsSceneMousePress:
- if (d->hasDecoration() && windowFrameEvent(event))
- return true;
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseDoubleClick:
- d->ensureWindowData();
- if (d->hasDecoration() && d->windowData->grabbedSection != Qt::NoSection)
- return windowFrameEvent(event);
- break;
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverMove:
- case QEvent::GraphicsSceneHoverLeave:
- if (d->hasDecoration()) {
- windowFrameEvent(event);
- // Filter out hover events if they were sent to us only because of the
- // decoration (special case in QGraphicsScenePrivate::dispatchHoverEvent).
- if (!acceptsHoverEvents())
- return true;
- }
- break;
- default:
- break;
- }
- return QObject::event(event);
-}
-
-/*!
- This event handler can be reimplemented to handle state changes.
-
- The state being changed in this event can be retrieved through \a event.
-
- Change events include: QEvent::ActivationChange, QEvent::EnabledChange,
- QEvent::FontChange, QEvent::StyleChange, QEvent::PaletteChange,
- QEvent::ParentChange, QEvent::LayoutDirectionChange, and
- QEvent::ContentsRectChange.
-*/
-void QGraphicsWidget::changeEvent(QEvent *event)
-{
- Q_D(QGraphicsWidget);
- switch (event->type()) {
- case QEvent::StyleChange:
- // ### Don't unset if the margins are explicitly set.
- unsetWindowFrameMargins();
- if (d->layout)
- d->layout->invalidate();
- case QEvent::FontChange:
- update();
- updateGeometry();
- break;
- case QEvent::PaletteChange:
- update();
- break;
- case QEvent::ParentChange:
- d->resolveFont(d->inheritedFontResolveMask);
- d->resolvePalette(d->inheritedPaletteResolveMask);
- break;
- default:
- break;
- }
-}
-
-/*!
- This event handler, for \a event, can be reimplemented in a subclass to
- receive widget close events. The default implementation accepts the
- event.
-
- \sa close(), QCloseEvent
-*/
-void QGraphicsWidget::closeEvent(QCloseEvent *event)
-{
- event->accept();
-}
-
-/*!
- \reimp
-*/
-void QGraphicsWidget::focusInEvent(QFocusEvent *event)
-{
- Q_UNUSED(event);
- if (focusPolicy() != Qt::NoFocus)
- update();
-}
-
-/*!
- Finds a new widget to give the keyboard focus to, as appropriate for Tab
- and Shift+Tab, and returns true if it can find a new widget; returns false
- otherwise. If \a next is true, this function searches forward; if \a next
- is false, it searches backward.
-
- Sometimes, you will want to reimplement this function to provide special
- focus handling for your widget and its subwidgets. For example, a web
- browser might reimplement it to move its current active link forward or
- backward, and call the base implementation only when it reaches the last
- or first link on the page.
-
- Child widgets call focusNextPrevChild() on their parent widgets, but only
- the window that contains the child widgets decides where to redirect
- focus. By reimplementing this function for an object, you gain control of
- focus traversal for all child widgets.
-
- \sa focusPolicy()
-*/
-bool QGraphicsWidget::focusNextPrevChild(bool next)
-{
- Q_D(QGraphicsWidget);
- // Let the parent's focusNextPrevChild implementation decide what to do.
- QGraphicsWidget *parent = 0;
- if (!isWindow() && (parent = parentWidget()))
- return parent->focusNextPrevChild(next);
- if (!d->scene)
- return false;
- if (d->scene->focusNextPrevChild(next))
- return true;
- if (isWindow()) {
- setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
- if (hasFocus())
- return true;
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsWidget::focusOutEvent(QFocusEvent *event)
-{
- Q_UNUSED(event);
- if (focusPolicy() != Qt::NoFocus)
- update();
-}
-
-/*!
- This event handler, for \l{QEvent::Hide}{Hide} events, is delivered after
- the widget has been hidden, for example, setVisible(false) has been called
- for the widget or one of its ancestors when the widget was previously
- shown.
-
- You can reimplement this event handler to detect when your widget is
- hidden. Calling QEvent::accept() or QEvent::ignore() on \a event has no
- effect.
-
- \sa showEvent(), QWidget::hideEvent(), ItemVisibleChange
-*/
-void QGraphicsWidget::hideEvent(QHideEvent *event)
-{
- ///### focusNextPrevChild(true), don't lose focus when the focus widget
- // is hidden.
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for \l{QEvent::GraphicsSceneMove}{GraphicsSceneMove}
- events, is delivered after the widget has moved (e.g., its local position
- has changed).
-
- This event is only delivered when the item is moved locally. Calling
- setTransform() or moving any of the item's ancestors does not affect the
- item's local position.
-
- You can reimplement this event handler to detect when your widget has
- moved. Calling QEvent::accept() or QEvent::ignore() on \a event has no
- effect.
-
- \sa ItemPositionChange, ItemPositionHasChanged
-*/
-void QGraphicsWidget::moveEvent(QGraphicsSceneMoveEvent *event)
-{
- // ### Last position is always == current position
- Q_UNUSED(event);
-}
-
-/*!
- This event is delivered to the item by the scene at some point after it
- has been constructed, but before it is shown or otherwise accessed through
- the scene. You can use this event handler to do last-minute initializations
- of the widget which require the item to be fully constructed.
-
- The base implementation does nothing.
-*/
-void QGraphicsWidget::polishEvent()
-{
-}
-
-/*!
- This event handler, for
- \l{QEvent::GraphicsSceneResize}{GraphicsSceneResize} events, is
- delivered after the widget has been resized (i.e., its local size has
- changed). \a event contains both the old and the new size.
-
- This event is only delivered when the widget is resized locally; calling
- setTransform() on the widget or any of its ancestors or view, does not
- affect the widget's local size.
-
- You can reimplement this event handler to detect when your widget has been
- resized. Calling QEvent::accept() or QEvent::ignore() on \a event has no
- effect.
-
- \sa geometry(), setGeometry()
-*/
-void QGraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for \l{QEvent::Show}{Show} events, is delivered before
- the widget has been shown, for example, setVisible(true) has been called
- for the widget or one of its ancestors when the widget was previously
- hidden.
-
- You can reimplement this event handler to detect when your widget is
- shown. Calling QEvent::accept() or QEvent::ignore() on \a event has no
- effect.
-
- \sa hideEvent(), QWidget::showEvent(), ItemVisibleChange
-*/
-void QGraphicsWidget::showEvent(QShowEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- \reimp
-*/
-void QGraphicsWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for \a event, can be reimplemented in a subclass to
- receive notifications for Qt::GrabMouse events.
-
- \sa grabMouse(), grabKeyboard()
-*/
-void QGraphicsWidget::grabMouseEvent(QEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for \a event, can be reimplemented in a subclass to
- receive notifications for Qt::UngrabMouse events.
-
- \sa ungrabMouse(), ungrabKeyboard()
-*/
-void QGraphicsWidget::ungrabMouseEvent(QEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for \a event, can be reimplemented in a subclass to
- receive notifications for Qt::GrabKeyboard events.
-
- \sa grabKeyboard(), grabMouse()
-*/
-void QGraphicsWidget::grabKeyboardEvent(QEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- This event handler, for \a event, can be reimplemented in a subclass to
- receive notifications for Qt::UngrabKeyboard events.
-
- \sa ungrabKeyboard(), ungrabMouse()
-*/
-void QGraphicsWidget::ungrabKeyboardEvent(QEvent *event)
-{
- Q_UNUSED(event);
-}
-
-/*!
- Returns the widgets window type.
-
- \sa windowFlags(), isWindow(), isPanel()
-*/
-Qt::WindowType QGraphicsWidget::windowType() const
-{
- return Qt::WindowType(int(windowFlags()) & Qt::WindowType_Mask);
-}
-
-/*!
- \property QGraphicsWidget::windowFlags
- \brief the widget's window flags
-
- Window flags are a combination of a window type (e.g., Qt::Dialog) and
- several flags giving hints on the behavior of the window. The behavior
- is platform-dependent.
-
- By default, this property contains no window flags.
-
- Windows are panels. If you set the Qt::Window flag, the ItemIsPanel flag
- will be set automatically. If you clear the Qt::Window flag, the
- ItemIsPanel flag is also cleared. Note that the ItemIsPanel flag can be
- set independently of Qt::Window.
-
- \sa isWindow(), isPanel()
-*/
-Qt::WindowFlags QGraphicsWidget::windowFlags() const
-{
- Q_D(const QGraphicsWidget);
- return d->windowFlags;
-}
-void QGraphicsWidget::setWindowFlags(Qt::WindowFlags wFlags)
-{
- Q_D(QGraphicsWidget);
- if (d->windowFlags == wFlags)
- return;
- bool wasPopup = (d->windowFlags & Qt::WindowType_Mask) == Qt::Popup;
-
- d->adjustWindowFlags(&wFlags);
- d->windowFlags = wFlags;
- if (!d->setWindowFrameMargins)
- unsetWindowFrameMargins();
-
- setFlag(ItemIsPanel, d->windowFlags & Qt::Window);
-
- bool isPopup = (d->windowFlags & Qt::WindowType_Mask) == Qt::Popup;
- if (d->scene && isVisible() && wasPopup != isPopup) {
- // Popup state changed; update implicit mouse grab.
- if (!isPopup)
- d->scene->d_func()->removePopup(this);
- else
- d->scene->d_func()->addPopup(this);
- }
-
- if (d->scene && d->scene->d_func()->allItemsIgnoreHoverEvents && d->hasDecoration()) {
- d->scene->d_func()->allItemsIgnoreHoverEvents = false;
- d->scene->d_func()->enableMouseTrackingOnViews();
- }
-}
-
-/*!
- Returns true if this widget's window is in the active window, or if the
- widget does not have a window but is in an active scene (i.e., a scene
- that currently has focus).
-
- The active window is the window that either contains a child widget that
- currently has input focus, or that itself has input focus.
-
- \sa QGraphicsScene::activeWindow(), QGraphicsScene::setActiveWindow(), isActive()
-*/
-bool QGraphicsWidget::isActiveWindow() const
-{
- return isActive();
-}
-
-/*!
- \property QGraphicsWidget::windowTitle
- \brief This property holds the window title (caption).
-
- This property is only used for windows.
-
- By default, if no title has been set, this property contains an
- empty string.
-*/
-void QGraphicsWidget::setWindowTitle(const QString &title)
-{
- Q_D(QGraphicsWidget);
- d->ensureWindowData();
- d->windowData->windowTitle = title;
-}
-QString QGraphicsWidget::windowTitle() const
-{
- Q_D(const QGraphicsWidget);
- return d->windowData ? d->windowData->windowTitle : QString();
-}
-
-/*!
- \property QGraphicsWidget::focusPolicy
- \brief the way the widget accepts keyboard focus
-
- The focus policy is Qt::TabFocus if the widget accepts keyboard focus by
- tabbing, Qt::ClickFocus if the widget accepts focus by clicking,
- Qt::StrongFocus if it accepts both, and Qt::NoFocus (the default) if it
- does not accept focus at all.
-
- You must enable keyboard focus for a widget if it processes keyboard
- events. This is normally done from the widget's constructor. For instance,
- the QLineEdit constructor calls setFocusPolicy(Qt::StrongFocus).
-
- If you enable a focus policy (i.e., not Qt::NoFocus), QGraphicsWidget will
- automatically enable the ItemIsFocusable flag. Setting Qt::NoFocus on a
- widget will clear the ItemIsFocusable flag. If the widget currently has
- keyboard focus, the widget will automatically lose focus.
-
- \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
-*/
-Qt::FocusPolicy QGraphicsWidget::focusPolicy() const
-{
- Q_D(const QGraphicsWidget);
- return d->focusPolicy;
-}
-void QGraphicsWidget::setFocusPolicy(Qt::FocusPolicy policy)
-{
- Q_D(QGraphicsWidget);
- if (d->focusPolicy == policy)
- return;
- d->focusPolicy = policy;
- if (hasFocus() && policy == Qt::NoFocus)
- clearFocus();
- setFlag(ItemIsFocusable, policy != Qt::NoFocus);
-}
-
-/*!
- If this widget, a child or descendant of this widget currently has input
- focus, this function will return a pointer to that widget. If
- no descendant widget has input focus, 0 is returned.
-
- \sa QGraphicsItem::focusItem(), QWidget::focusWidget()
-*/
-QGraphicsWidget *QGraphicsWidget::focusWidget() const
-{
- Q_D(const QGraphicsWidget);
- if (d->subFocusItem && d->subFocusItem->d_ptr->isWidget)
- return static_cast<QGraphicsWidget *>(d->subFocusItem);
- return 0;
-}
-
-#ifndef QT_NO_SHORTCUT
-/*!
- \since 4.5
-
- Adds a shortcut to Qt's shortcut system that watches for the given key \a
- sequence in the given \a context. If the \a context is
- Qt::ApplicationShortcut, the shortcut applies to the application as a
- whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
- or to the window itself, Qt::WindowShortcut. For widgets that are not part
- of a window (i.e., top-level widgets and their children),
- Qt::WindowShortcut shortcuts apply to the scene.
-
- If the same key \a sequence has been grabbed by several widgets,
- when the key \a sequence occurs a QEvent::Shortcut event is sent
- to all the widgets to which it applies in a non-deterministic
- order, but with the ``ambiguous'' flag set to true.
-
- \warning You should not normally need to use this function;
- instead create \l{QAction}s with the shortcut key sequences you
- require (if you also want equivalent menu options and toolbar
- buttons), or create \l{QShortcut}s if you just need key sequences.
- Both QAction and QShortcut handle all the event filtering for you,
- and provide signals which are triggered when the user triggers the
- key sequence, so are much easier to use than this low-level
- function.
-
- \sa releaseShortcut() setShortcutEnabled() QWidget::grabShortcut()
-*/
-int QGraphicsWidget::grabShortcut(const QKeySequence &sequence, Qt::ShortcutContext context)
-{
- Q_ASSERT(qApp);
- if (sequence.isEmpty())
- return 0;
- // ### setAttribute(Qt::WA_GrabbedShortcut);
- return qApp->d_func()->shortcutMap.addShortcut(this, sequence, context);
-}
-
-/*!
- \since 4.5
-
- Removes the shortcut with the given \a id from Qt's shortcut
- system. The widget will no longer receive QEvent::Shortcut events
- for the shortcut's key sequence (unless it has other shortcuts
- with the same key sequence).
-
- \warning You should not normally need to use this function since
- Qt's shortcut system removes shortcuts automatically when their
- parent widget is destroyed. It is best to use QAction or
- QShortcut to handle shortcuts, since they are easier to use than
- this low-level function. Note also that this is an expensive
- operation.
-
- \sa grabShortcut() setShortcutEnabled() , QWidget::releaseShortcut()
-*/
-void QGraphicsWidget::releaseShortcut(int id)
-{
- Q_ASSERT(qApp);
- if (id)
- qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
-}
-
-/*!
- \since 4.5
-
- If \a enabled is true, the shortcut with the given \a id is
- enabled; otherwise the shortcut is disabled.
-
- \warning You should not normally need to use this function since
- Qt's shortcut system enables/disables shortcuts automatically as
- widgets become hidden/visible and gain or lose focus. It is best
- to use QAction or QShortcut to handle shortcuts, since they are
- easier to use than this low-level function.
-
- \sa grabShortcut() releaseShortcut(), QWidget::setShortcutEnabled()
-*/
-void QGraphicsWidget::setShortcutEnabled(int id, bool enabled)
-{
- Q_ASSERT(qApp);
- if (id)
- qApp->d_func()->shortcutMap.setShortcutEnabled(enabled, id, this, 0);
-}
-
-/*!
- \since 4.5
-
- If \a enabled is true, auto repeat of the shortcut with the
- given \a id is enabled; otherwise it is disabled.
-
- \sa grabShortcut() releaseShortcut() QWidget::setShortcutAutoRepeat()
-*/
-void QGraphicsWidget::setShortcutAutoRepeat(int id, bool enabled)
-{
- Q_ASSERT(qApp);
- if (id)
- qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enabled, id, this, 0);
-}
-#endif
-
-#ifndef QT_NO_ACTION
-/*!
- \since 4.5
-
- Appends the action \a action to this widget's list of actions.
-
- All QGraphicsWidgets have a list of \l{QAction}s, however they can be
- represented graphically in many different ways. The default use of the
- QAction list (as returned by actions()) is to create a context QMenu.
-
- A QGraphicsWidget should only have one of each action and adding an action
- it already has will not cause the same action to be in the widget twice.
-
- \sa removeAction(), insertAction(), actions(), QWidget::addAction()
-*/
-void QGraphicsWidget::addAction(QAction *action)
-{
- insertAction(0, action);
-}
-
-/*!
- \since 4.5
-
- Appends the actions \a actions to this widget's list of actions.
-
- \sa removeAction(), QMenu, addAction(), QWidget::addActions()
-*/
-void QGraphicsWidget::addActions(QList<QAction *> actions)
-{
- for (int i = 0; i < actions.count(); ++i)
- insertAction(0, actions.at(i));
-}
-
-/*!
- \since 4.5
-
- Inserts the action \a action to this widget's list of actions,
- before the action \a before. It appends the action if \a before is 0 or
- \a before is not a valid action for this widget.
-
- A QGraphicsWidget should only have one of each action.
-
- \sa removeAction(), addAction(), QMenu, actions(),
- QWidget::insertActions()
-*/
-void QGraphicsWidget::insertAction(QAction *before, QAction *action)
-{
- if (!action) {
- qWarning("QWidget::insertAction: Attempt to insert null action");
- return;
- }
-
- Q_D(QGraphicsWidget);
- int index = d->actions.indexOf(action);
- if (index != -1)
- d->actions.removeAt(index);
-
- int pos = d->actions.indexOf(before);
- if (pos < 0) {
- before = 0;
- pos = d->actions.size();
- }
- d->actions.insert(pos, action);
-
- if (index == -1) {
- QActionPrivate *apriv = action->d_func();
- apriv->graphicsWidgets.append(this);
- }
-
- QActionEvent e(QEvent::ActionAdded, action, before);
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- \since 4.5
-
- Inserts the actions \a actions to this widget's list of actions,
- before the action \a before. It appends the action if \a before is 0 or
- \a before is not a valid action for this widget.
-
- A QGraphicsWidget can have at most one of each action.
-
- \sa removeAction(), QMenu, insertAction(), QWidget::insertActions()
-*/
-void QGraphicsWidget::insertActions(QAction *before, QList<QAction *> actions)
-{
- for (int i = 0; i < actions.count(); ++i)
- insertAction(before, actions.at(i));
-}
-
-/*!
- \since 4.5
-
- Removes the action \a action from this widget's list of actions.
-
- \sa insertAction(), actions(), insertAction(), QWidget::removeAction()
-*/
-void QGraphicsWidget::removeAction(QAction *action)
-{
- if (!action)
- return;
-
- Q_D(QGraphicsWidget);
-
- QActionPrivate *apriv = action->d_func();
- apriv->graphicsWidgets.removeAll(this);
-
- if (d->actions.removeAll(action)) {
- QActionEvent e(QEvent::ActionRemoved, action);
- QApplication::sendEvent(this, &e);
- }
-}
-
-/*!
- \since 4.5
-
- Returns the (possibly empty) list of this widget's actions.
-
- \sa insertAction(), removeAction(), QWidget::actions(),
- QAction::associatedWidgets(), QAction::associatedGraphicsWidgets()
-*/
-QList<QAction *> QGraphicsWidget::actions() const
-{
- Q_D(const QGraphicsWidget);
- return d->actions;
-}
-#endif
-
-/*!
- Moves the \a second widget around the ring of focus widgets so that
- keyboard focus moves from the \a first widget to the \a second widget when
- the Tab key is pressed.
-
- Note that since the tab order of the \a second widget is changed, you
- should order a chain like this:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp 1
-
- \e not like this:
-
- \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp 2
-
- If \a first is 0, this indicates that \a second should be the first widget
- to receive input focus should the scene gain Tab focus (i.e., the user
- hits Tab so that focus passes into the scene). If \a second is 0, this
- indicates that \a first should be the first widget to gain focus if the
- scene gained BackTab focus.
-
- By default, tab order is defined implicitly using widget creation order.
-
- \sa focusPolicy, {Keyboard Focus}
-*/
-void QGraphicsWidget::setTabOrder(QGraphicsWidget *first, QGraphicsWidget *second)
-{
- if (!first && !second) {
- qWarning("QGraphicsWidget::setTabOrder(0, 0) is undefined");
- return;
- }
- if ((first && second) && first->scene() != second->scene()) {
- qWarning("QGraphicsWidget::setTabOrder: scenes %p and %p are different",
- first->scene(), second->scene());
- return;
- }
- QGraphicsScene *scene = first ? first->scene() : second->scene();
- if (!scene && (!first || !second)) {
- qWarning("QGraphicsWidget::setTabOrder: assigning tab order from/to the"
- " scene requires the item to be in a scene.");
- return;
- }
-
- // If either first or second are 0, the scene's tabFocusFirst is updated
- // to point to the first item in the scene's focus chain. Then first or
- // second are set to point to tabFocusFirst.
- QGraphicsScenePrivate *sceneD = scene->d_func();
- if (!first) {
- sceneD->tabFocusFirst = second;
- return;
- }
- if (!second) {
- sceneD->tabFocusFirst = first->d_func()->focusNext;
- return;
- }
-
- // Both first and second are != 0.
- QGraphicsWidget *firstFocusNext = first->d_func()->focusNext;
- if (firstFocusNext == second) {
- // Nothing to do.
- return;
- }
-
- // Update the focus chain.
- QGraphicsWidget *secondFocusPrev = second->d_func()->focusPrev;
- QGraphicsWidget *secondFocusNext = second->d_func()->focusNext;
- firstFocusNext->d_func()->focusPrev = second;
- first->d_func()->focusNext = second;
- second->d_func()->focusNext = firstFocusNext;
- second->d_func()->focusPrev = first;
- secondFocusPrev->d_func()->focusNext = secondFocusNext;
- secondFocusNext->d_func()->focusPrev = secondFocusPrev;
-
- Q_ASSERT(first->d_func()->focusNext->d_func()->focusPrev == first);
- Q_ASSERT(first->d_func()->focusPrev->d_func()->focusNext == first);
-
- Q_ASSERT(second->d_func()->focusNext->d_func()->focusPrev == second);
- Q_ASSERT(second->d_func()->focusPrev->d_func()->focusNext == second);
-
-}
-
-/*!
- If \a on is true, this function enables \a attribute; otherwise
- \a attribute is disabled.
-
- See the class documentation for QGraphicsWidget for a complete list of
- which attributes are supported, and what they are for.
-
- \sa testAttribute(), QWidget::setAttribute()
-*/
-void QGraphicsWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
-{
- Q_D(QGraphicsWidget);
- // ### most flags require some immediate action
- // ### we might want to qWarn use of unsupported attributes
- // ### we might want to not use Qt::WidgetAttribute, but roll our own instead
- d->setAttribute(attribute, on);
-}
-
-/*!
- Returns true if \a attribute is enabled for this widget; otherwise,
- returns false.
-
- \sa setAttribute()
-*/
-bool QGraphicsWidget::testAttribute(Qt::WidgetAttribute attribute) const
-{
- Q_D(const QGraphicsWidget);
- return d->testAttribute(attribute);
-}
-
-/*!
- \reimp
-*/
-int QGraphicsWidget::type() const
-{
- return Type;
-}
-
-/*!
- \reimp
-*/
-void QGraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- Q_UNUSED(painter);
- Q_UNUSED(option);
- Q_UNUSED(widget);
-}
-
-/*!
- This virtual function is called by QGraphicsScene to draw the window frame
- for windows using \a painter, \a option, and \a widget, in local
- coordinates. The base implementation uses the current style to render the
- frame and title bar.
-
- You can reimplement this function in a subclass of QGraphicsWidget to
- provide custom rendering of the widget's window frame.
-
- \sa QGraphicsItem::paint()
-*/
-void QGraphicsWidget::paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option,
- QWidget *widget)
-{
- const bool fillBackground = !testAttribute(Qt::WA_OpaquePaintEvent)
- && !testAttribute(Qt::WA_NoSystemBackground);
- QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(this);
- const bool embeddedWidgetFillsOwnBackground = proxy && proxy->widget();
-
- if (rect().contains(option->exposedRect)) {
- if (fillBackground && !embeddedWidgetFillsOwnBackground)
- painter->fillRect(option->exposedRect, palette().window());
- return;
- }
-
- Q_D(QGraphicsWidget);
-
- QRect windowFrameRect = QRect(QPoint(), windowFrameGeometry().size().toSize());
- QStyleOptionTitleBar bar;
- bar.QStyleOption::operator=(*option);
- d->initStyleOptionTitleBar(&bar); // this clear flags in bar.state
- d->ensureWindowData();
- if (d->windowData->buttonMouseOver)
- bar.state |= QStyle::State_MouseOver;
- else
- bar.state &= ~QStyle::State_MouseOver;
- if (d->windowData->buttonSunken)
- bar.state |= QStyle::State_Sunken;
- else
- bar.state &= ~QStyle::State_Sunken;
-
- bar.rect = windowFrameRect;
-
- // translate painter to make the style happy
- const QPointF styleOrigin = this->windowFrameRect().topLeft();
- painter->translate(styleOrigin);
-
-#ifdef Q_WS_MAC
- const QSize pixmapSize = windowFrameRect.size();
- if (pixmapSize.width() <= 0 || pixmapSize.height() <= 0)
- return;
- QPainter *realPainter = painter;
- QPixmap pm(pixmapSize);
- painter = new QPainter(&pm);
-#endif
-
- // Fill background
- QStyleHintReturnMask mask;
- bool setMask = style()->styleHint(QStyle::SH_WindowFrame_Mask, &bar, widget, &mask) && !mask.region.isEmpty();
- bool hasBorder = !style()->styleHint(QStyle::SH_TitleBar_NoBorder, &bar, widget);
- int frameWidth = style()->pixelMetric(QStyle::PM_MDIFrameWidth, &bar, widget);
- if (setMask) {
- painter->save();
- painter->setClipRegion(mask.region, Qt::IntersectClip);
- }
- if (fillBackground) {
- if (embeddedWidgetFillsOwnBackground) {
- // Don't fill the background twice.
- QPainterPath windowFrameBackground;
- windowFrameBackground.addRect(windowFrameRect);
- // Adjust with 0.5 to avoid border artifacts between
- // widget background and frame background.
- windowFrameBackground.addRect(rect().translated(-styleOrigin).adjusted(0.5, 0.5, -0.5, -0.5));
- painter->fillPath(windowFrameBackground, palette().window());
- } else {
- painter->fillRect(windowFrameRect, palette().window());
- }
- }
- painter->setRenderHint(QPainter::NonCosmeticDefaultPen);
-
- // Draw title
- int height = (int)d->titleBarHeight(bar);
- bar.rect.setHeight(height);
- if (hasBorder) // Frame is painted by PE_FrameWindow
- bar.rect.adjust(frameWidth, frameWidth, -frameWidth, 0);
-
- painter->save();
- painter->setFont(QApplication::font("QWorkspaceTitleBar"));
- style()->drawComplexControl(QStyle::CC_TitleBar, &bar, painter, widget);
- painter->restore();
- if (setMask)
- painter->restore();
- // Draw window frame
- QStyleOptionFrame frameOptions;
- frameOptions.QStyleOption::operator=(*option);
- initStyleOption(&frameOptions);
- if (!hasBorder)
- painter->setClipRect(windowFrameRect.adjusted(0, +height, 0, 0), Qt::IntersectClip);
- if (hasFocus()) {
- frameOptions.state |= QStyle::State_HasFocus;
- } else {
- frameOptions.state &= ~QStyle::State_HasFocus;
- }
- bool isActive = isActiveWindow();
- if (isActive) {
- frameOptions.state |= QStyle::State_Active;
- } else {
- frameOptions.state &= ~QStyle::State_Active;
- }
-
- frameOptions.palette.setCurrentColorGroup(isActive ? QPalette::Active : QPalette::Normal);
- frameOptions.rect = windowFrameRect;
- frameOptions.lineWidth = style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, widget);
- frameOptions.midLineWidth = 1;
- style()->drawPrimitive(QStyle::PE_FrameWindow, &frameOptions, painter, widget);
-
-#ifdef Q_WS_MAC
- realPainter->drawPixmap(QPoint(), pm);
- delete painter;
-#endif
-}
-
-/*!
- \reimp
-*/
-QRectF QGraphicsWidget::boundingRect() const
-{
- return windowFrameRect();
-}
-
-/*!
- \reimp
-*/
-QPainterPath QGraphicsWidget::shape() const
-{
- QPainterPath path;
- path.addRect(rect());
- return path;
-}
-
-/*!
- Call this function to close the widget.
-
- Returns true if the widget was closed; otherwise returns false.
- This slot will first send a QCloseEvent to the widget, which may or may
- not accept the event. If the event was ignored, nothing happens. If the
- event was accepted, it will hide() the widget.
-
- If the widget has the Qt::WA_DeleteOnClose attribute set it will be
- deleted.
-*/
-bool QGraphicsWidget::close()
-{
- QCloseEvent closeEvent;
- QApplication::sendEvent(this, &closeEvent);
- if (!closeEvent.isAccepted()) {
- return false;
- }
- // hide
- if (isVisible()) {
- hide();
- }
- if (testAttribute(Qt::WA_DeleteOnClose)) {
- deleteLater();
- }
- return true;
-}
-
-#ifdef Q_NO_USING_KEYWORD
-/*!
- \fn const QObjectList &QGraphicsWidget::children() const
- \internal
-
- This function returns the same value as QObject::children(). It's
- provided to differentiate between the obsolete member
- QGraphicsItem::children() and QObject::children(). QGraphicsItem now
- provides childItems() instead.
-*/
-#endif
-
-#if 0
-void QGraphicsWidget::dumpFocusChain()
-{
- qDebug() << "=========== Dumping focus chain ==============";
- int i = 0;
- QGraphicsWidget *next = this;
- QSet<QGraphicsWidget*> visited;
- do {
- if (!next) {
- qWarning("Found a focus chain that is not circular, (next == 0)");
- break;
- }
- qDebug() << i++ << QString::number(uint(next), 16) << next->className() << next->data(0) << QString::fromAscii("focusItem:%1").arg(next->hasFocus() ? '1' : '0') << QLatin1String("next:") << next->d_func()->focusNext->data(0) << QLatin1String("prev:") << next->d_func()->focusPrev->data(0);
- if (visited.contains(next)) {
- qWarning("Already visited this node. However, I expected to dump until I found myself.");
- break;
- }
- visited << next;
- next = next->d_func()->focusNext;
- } while (next != this);
-}
-#endif
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h
deleted file mode 100644
index 6cbe579608..0000000000
--- a/src/gui/graphicsview/qgraphicswidget.h
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSWIDGET_H
-#define QGRAPHICSWIDGET_H
-
-#include <QtGui/qfont.h>
-#include <QtGui/qgraphicslayoutitem.h>
-#include <QtGui/qgraphicsitem.h>
-#include <QtGui/qpalette.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QFont;
-class QFontMetrics;
-class QGraphicsLayout;
-class QGraphicsSceneMoveEvent;
-class QGraphicsWidgetPrivate;
-class QGraphicsSceneResizeEvent;
-class QStyle;
-class QStyleOption;
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsWidgetPrivate;
-
-class Q_GUI_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphicsLayoutItem
-{
- Q_OBJECT
- Q_INTERFACES(QGraphicsItem QGraphicsLayoutItem)
- Q_PROPERTY(QPalette palette READ palette WRITE setPalette)
- Q_PROPERTY(QFont font READ font WRITE setFont)
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection RESET unsetLayoutDirection)
- Q_PROPERTY(QSizeF size READ size WRITE resize NOTIFY geometryChanged)
- Q_PROPERTY(QSizeF minimumSize READ minimumSize WRITE setMinimumSize)
- Q_PROPERTY(QSizeF preferredSize READ preferredSize WRITE setPreferredSize)
- Q_PROPERTY(QSizeF maximumSize READ maximumSize WRITE setMaximumSize)
- Q_PROPERTY(QSizePolicy sizePolicy READ sizePolicy WRITE setSizePolicy)
- Q_PROPERTY(Qt::FocusPolicy focusPolicy READ focusPolicy WRITE setFocusPolicy)
- Q_PROPERTY(Qt::WindowFlags windowFlags READ windowFlags WRITE setWindowFlags)
- Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle)
- Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry NOTIFY geometryChanged)
- Q_PROPERTY(bool autoFillBackground READ autoFillBackground WRITE setAutoFillBackground)
- Q_PROPERTY(QGraphicsLayout* layout READ layout WRITE setLayout NOTIFY layoutChanged)
-public:
- QGraphicsWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
- ~QGraphicsWidget();
- QGraphicsLayout *layout() const;
- void setLayout(QGraphicsLayout *layout);
- void adjustSize();
-
- Qt::LayoutDirection layoutDirection() const;
- void setLayoutDirection(Qt::LayoutDirection direction);
- void unsetLayoutDirection();
-
- QStyle *style() const;
- void setStyle(QStyle *style);
-
- QFont font() const;
- void setFont(const QFont &font);
-
- QPalette palette() const;
- void setPalette(const QPalette &palette);
-
- bool autoFillBackground() const;
- void setAutoFillBackground(bool enabled);
-
- void resize(const QSizeF &size);
- inline void resize(qreal w, qreal h) { resize(QSizeF(w, h)); }
- QSizeF size() const;
-
- void setGeometry(const QRectF &rect);
- inline void setGeometry(qreal x, qreal y, qreal w, qreal h);
- inline QRectF rect() const { return QRectF(QPointF(), size()); }
-
- void setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
- void getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const;
-
- void setWindowFrameMargins(qreal left, qreal top, qreal right, qreal bottom);
- void getWindowFrameMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const;
- void unsetWindowFrameMargins();
- QRectF windowFrameGeometry() const;
- QRectF windowFrameRect() const;
-
- // Window handling
- Qt::WindowFlags windowFlags() const;
- Qt::WindowType windowType() const;
- void setWindowFlags(Qt::WindowFlags wFlags);
- bool isActiveWindow() const;
- void setWindowTitle(const QString &title);
- QString windowTitle() const;
-
- // Focus handling
- Qt::FocusPolicy focusPolicy() const;
- void setFocusPolicy(Qt::FocusPolicy policy);
- static void setTabOrder(QGraphicsWidget *first, QGraphicsWidget *second);
- QGraphicsWidget *focusWidget() const;
-
-#ifndef QT_NO_SHORTCUT
- int grabShortcut(const QKeySequence &sequence, Qt::ShortcutContext context = Qt::WindowShortcut);
- void releaseShortcut(int id);
- void setShortcutEnabled(int id, bool enabled = true);
- void setShortcutAutoRepeat(int id, bool enabled = true);
-#endif
-
-#ifndef QT_NO_ACTION
- //actions
- void addAction(QAction *action);
- void addActions(QList<QAction*> actions);
- void insertAction(QAction *before, QAction *action);
- void insertActions(QAction *before, QList<QAction*> actions);
- void removeAction(QAction *action);
- QList<QAction*> actions() const;
-#endif
-
- void setAttribute(Qt::WidgetAttribute attribute, bool on = true);
- bool testAttribute(Qt::WidgetAttribute attribute) const;
-
- enum {
- Type = 11
- };
- int type() const;
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
- virtual void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
- QRectF boundingRect() const;
- QPainterPath shape() const;
-
-#if 0
- void dumpFocusChain();
-#endif
-
- // ### Qt 5: Disambiguate
-#ifdef Q_NO_USING_KEYWORD
- const QObjectList &children() const { return QObject::children(); }
-#else
- using QObject::children;
-#endif
-
-Q_SIGNALS:
- void geometryChanged();
- void layoutChanged();
-
-public Q_SLOTS:
- bool close();
-
-protected:
- virtual void initStyleOption(QStyleOption *option) const;
-
- QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
- void updateGeometry();
-
- // Notification
- QVariant itemChange(GraphicsItemChange change, const QVariant &value);
- virtual QVariant propertyChange(const QString &propertyName, const QVariant &value);
-
- // Scene events
- bool sceneEvent(QEvent *event);
- virtual bool windowFrameEvent(QEvent *e);
- virtual Qt::WindowFrameSection windowFrameSectionAt(const QPointF& pos) const;
-
- // Base event handlers
- bool event(QEvent *event);
- //virtual void actionEvent(QActionEvent *event);
- virtual void changeEvent(QEvent *event);
- virtual void closeEvent(QCloseEvent *event);
- //void create(WId window = 0, bool initializeWindow = true, bool destroyOldWindow = true);
- //void destroy(bool destroyWindow = true, bool destroySubWindows = true);
- void focusInEvent(QFocusEvent *event);
- virtual bool focusNextPrevChild(bool next);
- void focusOutEvent(QFocusEvent *event);
- virtual void hideEvent(QHideEvent *event);
- //virtual bool macEvent(EventHandlerCallRef caller, EventRef event);
- //virtual int metric(PaintDeviceMetric m ) const;
- virtual void moveEvent(QGraphicsSceneMoveEvent *event);
- virtual void polishEvent();
- //virtual bool qwsEvent(QWSEvent *event);
- //void resetInputContext ();
- virtual void resizeEvent(QGraphicsSceneResizeEvent *event);
- virtual void showEvent(QShowEvent *event);
- //virtual void tabletEvent(QTabletEvent *event);
- //virtual bool winEvent(MSG *message, long *result);
- //virtual bool x11Event(XEvent *event);
- virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
- virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
- virtual void grabMouseEvent(QEvent *event);
- virtual void ungrabMouseEvent(QEvent *event);
- virtual void grabKeyboardEvent(QEvent *event);
- virtual void ungrabKeyboardEvent(QEvent *event);
- QGraphicsWidget(QGraphicsWidgetPrivate &, QGraphicsItem *parent, QGraphicsScene *, Qt::WindowFlags wFlags = 0);
-
-private:
- Q_DISABLE_COPY(QGraphicsWidget)
- Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QGraphicsWidget)
- friend class QGraphicsScene;
- friend class QGraphicsScenePrivate;
- friend class QGraphicsView;
- friend class QGraphicsItem;
- friend class QGraphicsItemPrivate;
- friend class QGraphicsLayout;
- friend class QWidget;
- friend class QApplication;
-};
-
-inline void QGraphicsWidget::setGeometry(qreal ax, qreal ay, qreal aw, qreal ah)
-{ setGeometry(QRectF(ax, ay, aw, ah)); }
-
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
-
diff --git a/src/gui/graphicsview/qgraphicswidget_p.cpp b/src/gui/graphicsview/qgraphicswidget_p.cpp
deleted file mode 100644
index 45800551cb..0000000000
--- a/src/gui/graphicsview/qgraphicswidget_p.cpp
+++ /dev/null
@@ -1,910 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include <QtCore/qdebug.h>
-#include <QtCore/qnumeric.h>
-#include "qgraphicswidget_p.h"
-#include "qgraphicslayoutitem_p.h"
-#include "qgraphicslayout.h"
-#include "qgraphicsscene_p.h"
-#include <QtGui/qapplication.h>
-#include <QtGui/qgraphicsscene.h>
-#include <QtGui/qstyleoption.h>
-#include <QtGui/QStyleOptionTitleBar>
-#include <QtGui/QGraphicsSceneMouseEvent>
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-# include <QMacStyle>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-void QGraphicsWidgetPrivate::init(QGraphicsItem *parentItem, Qt::WindowFlags wFlags)
-{
- Q_Q(QGraphicsWidget);
-
- attributes = 0;
- isWidget = 1; // QGraphicsItem::isWidget() returns true.
- focusNext = focusPrev = q;
- focusPolicy = Qt::NoFocus;
-
- adjustWindowFlags(&wFlags);
- windowFlags = wFlags;
-
- if (parentItem)
- setParentItemHelper(parentItem, 0, 0);
-
- q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::DefaultType));
- q->setGraphicsItem(q);
-
- resolveLayoutDirection();
- q->unsetWindowFrameMargins();
- flags |= QGraphicsItem::ItemUsesExtendedStyleOption;
- flags |= QGraphicsItem::ItemSendsGeometryChanges;
- if (windowFlags & Qt::Window)
- flags |= QGraphicsItem::ItemIsPanel;
-}
-
-qreal QGraphicsWidgetPrivate::titleBarHeight(const QStyleOptionTitleBar &options) const
-{
- Q_Q(const QGraphicsWidget);
- int height = q->style()->pixelMetric(QStyle::PM_TitleBarHeight, &options);
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle*>(q->style())) {
- height -=4;
- }
-#endif
- return (qreal)height;
-}
-
-/*!
- \internal
-*/
-QGraphicsWidgetPrivate::~QGraphicsWidgetPrivate()
-{
- // Remove any lazily allocated data
- delete[] margins;
- delete[] windowFrameMargins;
- delete windowData;
-}
-
-/*!
- \internal
-
- Ensures that margins is allocated.
- This function must be called before any dereferencing.
-*/
-void QGraphicsWidgetPrivate::ensureMargins() const
-{
- if (!margins) {
- margins = new qreal[4];
- for (int i = 0; i < 4; ++i)
- margins[i] = 0;
- }
-}
-
-/*!
- \internal
-
- Ensures that windowFrameMargins is allocated.
- This function must be called before any dereferencing.
-*/
-void QGraphicsWidgetPrivate::ensureWindowFrameMargins() const
-{
- if (!windowFrameMargins) {
- windowFrameMargins = new qreal[4];
- for (int i = 0; i < 4; ++i)
- windowFrameMargins[i] = 0;
- }
-}
-
-/*!
- \internal
-
- Ensures that windowData is allocated.
- This function must be called before any dereferencing.
-*/
-void QGraphicsWidgetPrivate::ensureWindowData()
-{
- if (!windowData)
- windowData = new WindowData;
-}
-
-void QGraphicsWidgetPrivate::setPalette_helper(const QPalette &palette)
-{
- if (this->palette == palette && this->palette.resolve() == palette.resolve())
- return;
- updatePalette(palette);
-}
-
-void QGraphicsWidgetPrivate::resolvePalette(uint inheritedMask)
-{
- inheritedPaletteResolveMask = inheritedMask;
- QPalette naturalPalette = naturalWidgetPalette();
- QPalette resolvedPalette = palette.resolve(naturalPalette);
- updatePalette(resolvedPalette);
-}
-
-void QGraphicsWidgetPrivate::updatePalette(const QPalette &palette)
-{
- Q_Q(QGraphicsWidget);
- // Update local palette setting.
- this->palette = palette;
-
- // Calculate new mask.
- if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation))
- inheritedPaletteResolveMask = 0;
- int mask = palette.resolve() | inheritedPaletteResolveMask;
-
- // Propagate to children.
- for (int i = 0; i < children.size(); ++i) {
- QGraphicsItem *item = children.at(i);
- if (item->isWidget()) {
- QGraphicsWidget *w = static_cast<QGraphicsWidget *>(item);
- if (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
- w->d_func()->resolvePalette(mask);
- } else {
- item->d_ptr->resolvePalette(mask);
- }
- }
-
- // Notify change.
- QEvent event(QEvent::PaletteChange);
- QApplication::sendEvent(q, &event);
-}
-
-void QGraphicsWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
-{
- Q_Q(QGraphicsWidget);
- if ((direction == Qt::RightToLeft) == (testAttribute(Qt::WA_RightToLeft)))
- return;
- q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
-
- // Propagate this change to all children.
- for (int i = 0; i < children.size(); ++i) {
- QGraphicsItem *item = children.at(i);
- if (item->isWidget()) {
- QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
- if (widget->parentWidget() && !widget->testAttribute(Qt::WA_SetLayoutDirection))
- widget->d_func()->setLayoutDirection_helper(direction);
- }
- }
-
- // Send the notification event to this widget item.
- QEvent e(QEvent::LayoutDirectionChange);
- QApplication::sendEvent(q, &e);
-}
-
-void QGraphicsWidgetPrivate::resolveLayoutDirection()
-{
- Q_Q(QGraphicsWidget);
- if (q->testAttribute(Qt::WA_SetLayoutDirection)) {
- return;
- }
- if (QGraphicsWidget *parentWidget = q->parentWidget()) {
- setLayoutDirection_helper(parentWidget->layoutDirection());
- } else if (scene) {
- // ### shouldn't the scene have a layoutdirection really? how does
- // ### QGraphicsWidget get changes from QApplication::layoutDirection?
- setLayoutDirection_helper(QApplication::layoutDirection());
- } else {
- setLayoutDirection_helper(QApplication::layoutDirection());
- }
-}
-
-QPalette QGraphicsWidgetPrivate::naturalWidgetPalette() const
-{
- Q_Q(const QGraphicsWidget);
- QPalette palette;
- if (QGraphicsWidget *parent = q->parentWidget()) {
- palette = parent->palette();
- } else if (scene) {
- palette = scene->palette();
- }
- palette.resolve(0);
- return palette;
-}
-
-void QGraphicsWidgetPrivate::setFont_helper(const QFont &font)
-{
- if (this->font == font && this->font.resolve() == font.resolve())
- return;
- updateFont(font);
-}
-
-void QGraphicsWidgetPrivate::resolveFont(uint inheritedMask)
-{
- Q_Q(QGraphicsWidget);
- inheritedFontResolveMask = inheritedMask;
- if (QGraphicsWidget *p = q->parentWidget())
- inheritedFontResolveMask |= p->d_func()->inheritedFontResolveMask;
- QFont naturalFont = naturalWidgetFont();
- QFont resolvedFont = font.resolve(naturalFont);
- updateFont(resolvedFont);
-}
-
-void QGraphicsWidgetPrivate::updateFont(const QFont &font)
-{
- Q_Q(QGraphicsWidget);
- // Update the local font setting.
- this->font = font;
-
- // Calculate new mask.
- if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation))
- inheritedFontResolveMask = 0;
- int mask = font.resolve() | inheritedFontResolveMask;
-
- // Propagate to children.
- for (int i = 0; i < children.size(); ++i) {
- QGraphicsItem *item = children.at(i);
- if (item->isWidget()) {
- QGraphicsWidget *w = static_cast<QGraphicsWidget *>(item);
- if (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
- w->d_func()->resolveFont(mask);
- } else {
- item->d_ptr->resolveFont(mask);
- }
- }
-
- if (!polished)
- return;
- // Notify change.
- QEvent event(QEvent::FontChange);
- QApplication::sendEvent(q, &event);
-}
-
-QFont QGraphicsWidgetPrivate::naturalWidgetFont() const
-{
- Q_Q(const QGraphicsWidget);
- QFont naturalFont; // ### no application font support
- if (QGraphicsWidget *parent = q->parentWidget()) {
- naturalFont = parent->font();
- } else if (scene) {
- naturalFont = scene->font();
- }
- naturalFont.resolve(0);
- return naturalFont;
-}
-
-void QGraphicsWidgetPrivate::initStyleOptionTitleBar(QStyleOptionTitleBar *option)
-{
- Q_Q(QGraphicsWidget);
- ensureWindowData();
- q->initStyleOption(option);
- option->rect.setHeight(titleBarHeight(*option));
- option->titleBarFlags = windowFlags;
- option->subControls = QStyle::SC_TitleBarCloseButton | QStyle::SC_TitleBarLabel | QStyle::SC_TitleBarSysMenu;
- option->activeSubControls = windowData->hoveredSubControl;
- bool isActive = q->isActiveWindow();
- if (isActive) {
- option->state |= QStyle::State_Active;
- option->titleBarState = Qt::WindowActive;
- option->titleBarState |= QStyle::State_Active;
- } else {
- option->state &= ~QStyle::State_Active;
- option->titleBarState = Qt::WindowNoState;
- }
- QFont windowTitleFont = QApplication::font("QWorkspaceTitleBar");
- QRect textRect = q->style()->subControlRect(QStyle::CC_TitleBar, option, QStyle::SC_TitleBarLabel, 0);
- option->text = QFontMetrics(windowTitleFont).elidedText(
- windowData->windowTitle, Qt::ElideRight, textRect.width());
-}
-
-void QGraphicsWidgetPrivate::adjustWindowFlags(Qt::WindowFlags *flags)
-{
- bool customize = (*flags & (Qt::CustomizeWindowHint
- | Qt::FramelessWindowHint
- | Qt::WindowTitleHint
- | Qt::WindowSystemMenuHint
- | Qt::WindowMinimizeButtonHint
- | Qt::WindowMaximizeButtonHint
- | Qt::WindowContextHelpButtonHint));
-
- uint type = (*flags & Qt::WindowType_Mask);
- if (customize)
- ;
- else if (type == Qt::Dialog || type == Qt::Sheet)
- *flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint;
- else if (type == Qt::Tool)
- *flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint;
- else if (type == Qt::Window || type == Qt::SubWindow)
- *flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint
- | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint;
-}
-
-void QGraphicsWidgetPrivate::windowFrameMouseReleaseEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_Q(QGraphicsWidget);
- ensureWindowData();
- if (windowData->grabbedSection != Qt::NoSection) {
- if (windowData->grabbedSection == Qt::TitleBarArea) {
- windowData->buttonSunken = false;
- QStyleOptionTitleBar bar;
- initStyleOptionTitleBar(&bar);
- // make sure that the coordinates (rect and pos) we send to the style are positive.
- bar.rect = q->windowFrameRect().toRect();
- bar.rect.moveTo(0,0);
- bar.rect.setHeight(q->style()->pixelMetric(QStyle::PM_TitleBarHeight, &bar));
- QPointF pos = event->pos();
- if (windowFrameMargins) {
- pos.rx() += windowFrameMargins[Left];
- pos.ry() += windowFrameMargins[Top];
- }
- bar.subControls = QStyle::SC_TitleBarCloseButton;
- if (q->style()->subControlRect(QStyle::CC_TitleBar, &bar,
- QStyle::SC_TitleBarCloseButton,
- event->widget()).contains(pos.toPoint())) {
- q->close();
- }
- }
- if (!(static_cast<QGraphicsSceneMouseEvent *>(event)->buttons()))
- windowData->grabbedSection = Qt::NoSection;
- event->accept();
- }
-}
-
-void QGraphicsWidgetPrivate::windowFrameMousePressEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_Q(QGraphicsWidget);
- if (event->button() != Qt::LeftButton)
- return;
-
- ensureWindowData();
- windowData->startGeometry = q->geometry();
- windowData->grabbedSection = q->windowFrameSectionAt(event->pos());
- ensureWindowData();
- if (windowData->grabbedSection == Qt::TitleBarArea
- && windowData->hoveredSubControl == QStyle::SC_TitleBarCloseButton) {
- windowData->buttonSunken = true;
- q->update();
- }
- event->setAccepted(windowData->grabbedSection != Qt::NoSection);
-}
-
-/*!
- Used to calculate the
- Precondition:
- \a widget should support either hfw or wfh
-
- If \a heightForWidth is set to false, this function will query the width for height
- instead. \a width will then be interpreted as height, \a minh and \a maxh will be interpreted
- as minimum width and maximum width.
- */
-static qreal minimumHeightForWidth(qreal width, qreal minh, qreal maxh,
- const QGraphicsWidget *widget,
- bool heightForWidth = true)
-{
- qreal minimumHeightForWidth = -1;
- const bool hasHFW = QGraphicsLayoutItemPrivate::get(widget)->hasHeightForWidth();
- if (hasHFW == heightForWidth) {
- minimumHeightForWidth = hasHFW
- ? widget->effectiveSizeHint(Qt::MinimumSize, QSizeF(width, -1)).height()
- : widget->effectiveSizeHint(Qt::MinimumSize, QSizeF(-1, width)).width(); //"width" is here height!
- } else {
- // widthForHeight
- const qreal constraint = width;
- while (maxh - minh > 0.1) {
- qreal middle = minh + (maxh - minh)/2;
- // ### really bad, if we are a widget with a layout it will call
- // layout->effectiveSizeHint(Qt::MiniumumSize), which again will call
- // sizeHint three times because of how the cache works
- qreal hfw = hasHFW
- ? widget->effectiveSizeHint(Qt::MinimumSize, QSizeF(middle, -1)).height()
- : widget->effectiveSizeHint(Qt::MinimumSize, QSizeF(-1, middle)).width();
- if (hfw > constraint) {
- minh = middle;
- } else if (hfw <= constraint) {
- maxh = middle;
- }
- }
- minimumHeightForWidth = maxh;
- }
- return minimumHeightForWidth;
-}
-
-static qreal minimumWidthForHeight(qreal height, qreal minw, qreal maxw,
- const QGraphicsWidget *widget)
-{
- return minimumHeightForWidth(height, minw, maxw, widget, false);
-}
-
-static QSizeF closestAcceptableSize(const QSizeF &proposed,
- const QGraphicsWidget *widget)
-{
- const QSizeF current = widget->size();
-
- qreal minw = proposed.width();
- qreal maxw = current.width();
- qreal minh = proposed.height();
- qreal maxh = current.height();
-
- qreal middlew = maxw;
- qreal middleh = maxh;
- qreal min_hfw;
- min_hfw = minimumHeightForWidth(maxw, minh, maxh, widget);
-
- do {
- if (maxw - minw < 0.1) {
- // we still havent found anything, cut off binary search
- minw = maxw;
- minh = maxh;
- }
- middlew = minw + (maxw - minw)/2.0;
- middleh = minh + (maxh - minh)/2.0;
-
- min_hfw = minimumHeightForWidth(middlew, minh, maxh, widget);
-
- if (min_hfw > middleh) {
- minw = middlew;
- minh = middleh;
- } else if (min_hfw <= middleh) {
- maxw = middlew;
- maxh = middleh;
- }
- } while (maxw != minw);
-
- min_hfw = minimumHeightForWidth(middlew, minh, maxh, widget);
-
- QSizeF result;
- if (min_hfw < maxh) {
- result = QSizeF(middlew, min_hfw);
- } else {
- // Needed because of the cut-off we do above.
- result = QSizeF(minimumWidthForHeight(maxh, proposed.width(), current.width(), widget), maxh);
- }
- return result;
-}
-
-static void _q_boundGeometryToSizeConstraints(const QRectF &startGeometry,
- QRectF *rect, Qt::WindowFrameSection section,
- const QSizeF &min, const QSizeF &max,
- const QGraphicsWidget *widget)
-{
- const QRectF proposedRect = *rect;
- qreal width = qBound(min.width(), proposedRect.width(), max.width());
- qreal height = qBound(min.height(), proposedRect.height(), max.height());
-
- const bool hasHFW = QGraphicsLayoutItemPrivate::get(widget)->hasHeightForWidth();
- const bool hasWFH = QGraphicsLayoutItemPrivate::get(widget)->hasWidthForHeight();
-
- const bool widthChanged = proposedRect.width() != widget->size().width();
- const bool heightChanged = proposedRect.height() != widget->size().height();
-
- if (hasHFW || hasWFH) {
- if (widthChanged || heightChanged) {
- qreal minExtent;
- qreal maxExtent;
- qreal constraint;
- qreal proposed;
- if (hasHFW) {
- minExtent = min.height();
- maxExtent = max.height();
- constraint = width;
- proposed = proposedRect.height();
- } else {
- // width for height
- minExtent = min.width();
- maxExtent = max.width();
- constraint = height;
- proposed = proposedRect.width();
- }
- if (minimumHeightForWidth(constraint, minExtent, maxExtent, widget, hasHFW) > proposed) {
- QSizeF effectiveSize = closestAcceptableSize(QSizeF(width, height), widget);
- width = effectiveSize.width();
- height = effectiveSize.height();
- }
- }
- }
-
- switch (section) {
- case Qt::LeftSection:
- rect->setRect(startGeometry.right() - qRound(width), startGeometry.top(),
- qRound(width), startGeometry.height());
- break;
- case Qt::TopLeftSection:
- rect->setRect(startGeometry.right() - qRound(width), startGeometry.bottom() - qRound(height),
- qRound(width), qRound(height));
- break;
- case Qt::TopSection:
- rect->setRect(startGeometry.left(), startGeometry.bottom() - qRound(height),
- startGeometry.width(), qRound(height));
- break;
- case Qt::TopRightSection:
- rect->setTop(rect->bottom() - qRound(height));
- rect->setWidth(qRound(width));
- break;
- case Qt::RightSection:
- rect->setWidth(qRound(width));
- break;
- case Qt::BottomRightSection:
- rect->setWidth(qRound(width));
- rect->setHeight(qRound(height));
- break;
- case Qt::BottomSection:
- rect->setHeight(qRound(height));
- break;
- case Qt::BottomLeftSection:
- rect->setRect(startGeometry.right() - qRound(width), startGeometry.top(),
- qRound(width), qRound(height));
- break;
- default:
- break;
- }
-}
-
-void QGraphicsWidgetPrivate::windowFrameMouseMoveEvent(QGraphicsSceneMouseEvent *event)
-{
- Q_Q(QGraphicsWidget);
- ensureWindowData();
- if (!(event->buttons() & Qt::LeftButton) || windowData->hoveredSubControl != QStyle::SC_TitleBarLabel)
- return;
-
- QLineF delta(q->mapFromScene(event->buttonDownScenePos(Qt::LeftButton)), event->pos());
- QLineF parentDelta(q->mapToParent(delta.p1()), q->mapToParent(delta.p2()));
- QLineF parentXDelta(q->mapToParent(QPointF(delta.p1().x(), 0)), q->mapToParent(QPointF(delta.p2().x(), 0)));
- QLineF parentYDelta(q->mapToParent(QPointF(0, delta.p1().y())), q->mapToParent(QPointF(0, delta.p2().y())));
-
- QRectF newGeometry;
- switch (windowData->grabbedSection) {
- case Qt::LeftSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft()
- + QPointF(parentXDelta.dx(), parentXDelta.dy()),
- windowData->startGeometry.size() - QSizeF(delta.dx(), delta.dy()));
- break;
- case Qt::TopLeftSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft()
- + QPointF(parentDelta.dx(), parentDelta.dy()),
- windowData->startGeometry.size() - QSizeF(delta.dx(), delta.dy()));
- break;
- case Qt::TopSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft()
- + QPointF(parentYDelta.dx(), parentYDelta.dy()),
- windowData->startGeometry.size() - QSizeF(0, delta.dy()));
- break;
- case Qt::TopRightSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft()
- + QPointF(parentYDelta.dx(), parentYDelta.dy()),
- windowData->startGeometry.size() - QSizeF(-delta.dx(), delta.dy()));
- break;
- case Qt::RightSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft(),
- windowData->startGeometry.size() + QSizeF(delta.dx(), 0));
- break;
- case Qt::BottomRightSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft(),
- windowData->startGeometry.size() + QSizeF(delta.dx(), delta.dy()));
- break;
- case Qt::BottomSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft(),
- windowData->startGeometry.size() + QSizeF(0, delta.dy()));
- break;
- case Qt::BottomLeftSection:
- newGeometry = QRectF(windowData->startGeometry.topLeft()
- + QPointF(parentXDelta.dx(), parentXDelta.dy()),
- windowData->startGeometry.size() - QSizeF(delta.dx(), -delta.dy()));
- break;
- case Qt::TitleBarArea:
- newGeometry = QRectF(windowData->startGeometry.topLeft()
- + QPointF(parentDelta.dx(), parentDelta.dy()),
- windowData->startGeometry.size());
- break;
- case Qt::NoSection:
- break;
- }
-
- if (windowData->grabbedSection != Qt::NoSection) {
- _q_boundGeometryToSizeConstraints(windowData->startGeometry, &newGeometry,
- windowData->grabbedSection,
- q->effectiveSizeHint(Qt::MinimumSize),
- q->effectiveSizeHint(Qt::MaximumSize),
- q);
- q->setGeometry(newGeometry);
- }
-}
-
-void QGraphicsWidgetPrivate::windowFrameHoverMoveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_Q(QGraphicsWidget);
- if (!hasDecoration())
- return;
-
- ensureWindowData();
-
- if (q->rect().contains(event->pos())) {
- if (windowData->buttonMouseOver || windowData->hoveredSubControl != QStyle::SC_None)
- windowFrameHoverLeaveEvent(event);
- return;
- }
-
- bool wasMouseOver = windowData->buttonMouseOver;
- QRect oldButtonRect = windowData->buttonRect;
- windowData->buttonRect = QRect();
- windowData->buttonMouseOver = false;
- QPointF pos = event->pos();
- QStyleOptionTitleBar bar;
- // make sure that the coordinates (rect and pos) we send to the style are positive.
- if (windowFrameMargins) {
- pos.rx() += windowFrameMargins[Left];
- pos.ry() += windowFrameMargins[Top];
- }
- initStyleOptionTitleBar(&bar);
- bar.rect = q->windowFrameRect().toRect();
- bar.rect.moveTo(0,0);
- bar.rect.setHeight(int(titleBarHeight(bar)));
-
- Qt::CursorShape cursorShape = Qt::ArrowCursor;
- bool needsSetCursorCall = true;
- switch (q->windowFrameSectionAt(event->pos())) {
- case Qt::TopLeftSection:
- case Qt::BottomRightSection:
- cursorShape = Qt::SizeFDiagCursor;
- break;
- case Qt::TopRightSection:
- case Qt::BottomLeftSection:
- cursorShape = Qt::SizeBDiagCursor;
- break;
- case Qt::LeftSection:
- case Qt::RightSection:
- cursorShape = Qt::SizeHorCursor;
- break;
- case Qt::TopSection:
- case Qt::BottomSection:
- cursorShape = Qt::SizeVerCursor;
- break;
- case Qt::TitleBarArea:
- windowData->buttonRect = q->style()->subControlRect(
- QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarCloseButton, 0);
-#ifdef Q_WS_MAC
- // On mac we should hover if we are in the 'area' of the buttons
- windowData->buttonRect |= q->style()->subControlRect(
- QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMinButton, 0);
- windowData->buttonRect |= q->style()->subControlRect(
- QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMaxButton, 0);
-#endif
- if (windowData->buttonRect.contains(pos.toPoint()))
- windowData->buttonMouseOver = true;
- event->ignore();
- break;
- default:
- needsSetCursorCall = false;
- event->ignore();
- }
-#ifndef QT_NO_CURSOR
- if (needsSetCursorCall)
- q->setCursor(cursorShape);
-#endif
- // update buttons if we hover over them
- windowData->hoveredSubControl = q->style()->hitTestComplexControl(QStyle::CC_TitleBar, &bar, pos.toPoint(), 0);
- if (windowData->hoveredSubControl != QStyle::SC_TitleBarCloseButton)
- windowData->hoveredSubControl = QStyle::SC_TitleBarLabel;
-
- if (windowData->buttonMouseOver != wasMouseOver) {
- if (!oldButtonRect.isNull())
- q->update(QRectF(oldButtonRect).translated(q->windowFrameRect().topLeft()));
- if (!windowData->buttonRect.isNull())
- q->update(QRectF(windowData->buttonRect).translated(q->windowFrameRect().topLeft()));
- }
-}
-
-void QGraphicsWidgetPrivate::windowFrameHoverLeaveEvent(QGraphicsSceneHoverEvent *event)
-{
- Q_UNUSED(event);
- Q_Q(QGraphicsWidget);
- if (hasDecoration()) {
- // ### restore the cursor, don't override it
-#ifndef QT_NO_CURSOR
- q->unsetCursor();
-#endif
-
- ensureWindowData();
-
- bool needsUpdate = false;
- if (windowData->hoveredSubControl == QStyle::SC_TitleBarCloseButton
- || windowData->buttonMouseOver)
- needsUpdate = true;
-
- // update the hover state (of buttons etc...)
- windowData->hoveredSubControl = QStyle::SC_None;
- windowData->buttonMouseOver = false;
- windowData->buttonRect = QRect();
- if (needsUpdate)
- q->update(windowData->buttonRect);
- }
-}
-
-bool QGraphicsWidgetPrivate::hasDecoration() const
-{
- return (windowFlags & Qt::Window) && (windowFlags & Qt::WindowTitleHint);
-}
-
-/**
- * is called after a reparent has taken place to fix up the focus chain(s)
- */
-void QGraphicsWidgetPrivate::fixFocusChainBeforeReparenting(QGraphicsWidget *newParent, QGraphicsScene *oldScene, QGraphicsScene *newScene)
-{
- Q_Q(QGraphicsWidget);
-
- Q_ASSERT(focusNext && focusPrev);
-
- QGraphicsWidget *n = q; //last one in 'new' list
- QGraphicsWidget *o = 0; //last one in 'old' list
-
- QGraphicsWidget *w = focusNext;
-
- QGraphicsWidget *firstOld = 0;
- bool wasPreviousNew = true;
-
- while (w != q) {
- bool isCurrentNew = q->isAncestorOf(w);
- if (isCurrentNew) {
- if (!wasPreviousNew) {
- n->d_func()->focusNext = w;
- w->d_func()->focusPrev = n;
- }
- n = w;
- } else /*if (!isCurrentNew)*/ {
- if (wasPreviousNew) {
- if (o) {
- o->d_func()->focusNext = w;
- w->d_func()->focusPrev = o;
- } else {
- firstOld = w;
- }
- }
- o = w;
- }
- w = w->d_func()->focusNext;
- wasPreviousNew = isCurrentNew;
- }
-
- // repair the 'old' chain
- if (firstOld) {
- o->d_func()->focusNext = firstOld;
- firstOld->d_func()->focusPrev = o;
- }
-
- // update tabFocusFirst for oldScene if the item is going to be removed from oldScene
- if (newParent)
- newScene = newParent->scene();
-
- if (oldScene && newScene != oldScene)
- oldScene->d_func()->tabFocusFirst = (firstOld && firstOld->scene() == oldScene) ? firstOld : 0;
-
- QGraphicsItem *topLevelItem = newParent ? newParent->topLevelItem() : 0;
- QGraphicsWidget *topLevel = 0;
- if (topLevelItem && topLevelItem->isWidget())
- topLevel = static_cast<QGraphicsWidget *>(topLevelItem);
-
- if (topLevel && newParent) {
- QGraphicsWidget *last = topLevel->d_func()->focusPrev;
- // link last with new chain
- last->d_func()->focusNext = q;
- focusPrev = last;
-
- // link last in chain with
- topLevel->d_func()->focusPrev = n;
- n->d_func()->focusNext = topLevel;
- } else {
- // q is the start of the focus chain
- n->d_func()->focusNext = q;
- focusPrev = n;
- }
-
-}
-
-void QGraphicsWidgetPrivate::setLayout_helper(QGraphicsLayout *l)
-{
- delete (this->layout);
- layout = l;
- if (!l) {
- Q_Q(QGraphicsWidget);
- q->updateGeometry();
- }
-}
-
-qreal QGraphicsWidgetPrivate::width() const
-{
- Q_Q(const QGraphicsWidget);
- return q->geometry().width();
-}
-
-void QGraphicsWidgetPrivate::setWidth(qreal w)
-{
- if (qIsNaN(w))
- return;
- Q_Q(QGraphicsWidget);
- if (q->geometry().width() == w)
- return;
-
- QRectF oldGeom = q->geometry();
-
- q->setGeometry(QRectF(q->x(), q->y(), w, height()));
-}
-
-void QGraphicsWidgetPrivate::resetWidth()
-{
- Q_Q(QGraphicsWidget);
- q->setGeometry(QRectF(q->x(), q->y(), 0, height()));
-}
-
-qreal QGraphicsWidgetPrivate::height() const
-{
- Q_Q(const QGraphicsWidget);
- return q->geometry().height();
-}
-
-void QGraphicsWidgetPrivate::setHeight(qreal h)
-{
- if (qIsNaN(h))
- return;
- Q_Q(QGraphicsWidget);
- if (q->geometry().height() == h)
- return;
-
- QRectF oldGeom = q->geometry();
-
- q->setGeometry(QRectF(q->x(), q->y(), width(), h));
-}
-
-void QGraphicsWidgetPrivate::resetHeight()
-{
- Q_Q(QGraphicsWidget);
- q->setGeometry(QRectF(q->x(), q->y(), width(), 0));
-}
-
-void QGraphicsWidgetPrivate::setGeometryFromSetPos()
-{
- if (inSetGeometry)
- return;
- Q_Q(QGraphicsWidget);
- inSetPos = 1;
- // Ensure setGeometry is called (avoid recursion when setPos is
- // called from within setGeometry).
- q->setGeometry(QRectF(pos, q->size()));
- inSetPos = 0 ;
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgraphicswidget_p.h b/src/gui/graphicsview/qgraphicswidget_p.h
deleted file mode 100644
index 4379eafbde..0000000000
--- a/src/gui/graphicsview/qgraphicswidget_p.h
+++ /dev/null
@@ -1,226 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRAPHICSWIDGET_P_H
-#define QGRAPHICSWIDGET_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 <private/qobject_p.h>
-#include "qgraphicsitem_p.h"
-#include "qgraphicswidget.h"
-#include <QtGui/qfont.h>
-#include <QtGui/qpalette.h>
-#include <QtGui/qsizepolicy.h>
-#include <QtGui/qstyle.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsLayout;
-class QStyleOptionTitleBar;
-
-#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-class QGraphicsWidgetPrivate : public QGraphicsItemPrivate
-{
- Q_DECLARE_PUBLIC(QGraphicsWidget)
-public:
- QGraphicsWidgetPrivate()
- : margins(0),
- layout(0),
- inheritedPaletteResolveMask(0),
- inheritedFontResolveMask(0),
- inSetGeometry(0),
- polished(0),
- inSetPos(0),
- autoFillBackground(0),
- focusPolicy(Qt::NoFocus),
- focusNext(0),
- focusPrev(0),
- windowFlags(0),
- windowData(0),
- setWindowFrameMargins(false),
- windowFrameMargins(0)
- { }
- virtual ~QGraphicsWidgetPrivate();
-
- void init(QGraphicsItem *parentItem, Qt::WindowFlags wFlags);
- qreal titleBarHeight(const QStyleOptionTitleBar &options) const;
-
- // Margins
- enum {Left, Top, Right, Bottom};
- mutable qreal *margins;
- void ensureMargins() const;
-
- void fixFocusChainBeforeReparenting(QGraphicsWidget *newParent, QGraphicsScene *oldScene, QGraphicsScene *newScene = 0);
- void setLayout_helper(QGraphicsLayout *l);
-
- // Layouts
- QGraphicsLayout *layout;
- void setLayoutDirection_helper(Qt::LayoutDirection direction);
- void resolveLayoutDirection();
-
- // Style
- QPalette palette;
- uint inheritedPaletteResolveMask;
- void setPalette_helper(const QPalette &palette);
- void resolvePalette(uint inheritedMask);
- void updatePalette(const QPalette &palette);
- QPalette naturalWidgetPalette() const;
- QFont font;
- uint inheritedFontResolveMask;
- void setFont_helper(const QFont &font);
- void resolveFont(uint inheritedMask);
- void updateFont(const QFont &font);
- QFont naturalWidgetFont() const;
-
- // Window specific
- void initStyleOptionTitleBar(QStyleOptionTitleBar *option);
- void adjustWindowFlags(Qt::WindowFlags *wFlags);
- void windowFrameMouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- void windowFrameMousePressEvent(QGraphicsSceneMouseEvent *event);
- void windowFrameMouseMoveEvent(QGraphicsSceneMouseEvent *event);
- void windowFrameHoverMoveEvent(QGraphicsSceneHoverEvent *event);
- void windowFrameHoverLeaveEvent(QGraphicsSceneHoverEvent *event);
- bool hasDecoration() const;
-
- // Private Properties
- qreal width() const;
- void setWidth(qreal);
- void resetWidth();
-
- qreal height() const;
- void setHeight(qreal);
- void resetHeight();
- void setGeometryFromSetPos();
-
- // State
- inline int attributeToBitIndex(Qt::WidgetAttribute att) const
- {
- int bit = -1;
- switch (att) {
- case Qt::WA_SetLayoutDirection: bit = 0; break;
- case Qt::WA_RightToLeft: bit = 1; break;
- case Qt::WA_SetStyle: bit = 2; break;
- case Qt::WA_Resized: bit = 3; break;
- case Qt::WA_DeleteOnClose: bit = 4; break;
- case Qt::WA_NoSystemBackground: bit = 5; break;
- case Qt::WA_OpaquePaintEvent: bit = 6; break;
- case Qt::WA_SetPalette: bit = 7; break;
- case Qt::WA_SetFont: bit = 8; break;
- case Qt::WA_WindowPropagation: bit = 9; break;
- default: break;
- }
- return bit;
- }
- inline void setAttribute(Qt::WidgetAttribute att, bool value)
- {
- int bit = attributeToBitIndex(att);
- if (bit == -1) {
- qWarning("QGraphicsWidget::setAttribute: unsupported attribute %d", int(att));
- return;
- }
- if (value)
- attributes |= (1 << bit);
- else
- attributes &= ~(1 << bit);
- }
- inline bool testAttribute(Qt::WidgetAttribute att) const
- {
- int bit = attributeToBitIndex(att);
- if (bit == -1)
- return false;
- return (attributes & (1 << bit)) != 0;
- }
- quint32 attributes : 10;
- quint32 inSetGeometry : 1;
- quint32 polished: 1;
- quint32 inSetPos : 1;
- quint32 autoFillBackground : 1;
-
- // Focus
- Qt::FocusPolicy focusPolicy;
- QGraphicsWidget *focusNext;
- QGraphicsWidget *focusPrev;
-
- // Windows
- Qt::WindowFlags windowFlags;
- struct WindowData {
- QString windowTitle;
- QStyle::SubControl hoveredSubControl;
- Qt::WindowFrameSection grabbedSection;
- uint buttonMouseOver : 1;
- uint buttonSunken : 1;
- QRectF startGeometry;
- QRect buttonRect;
- WindowData()
- : hoveredSubControl(QStyle::SC_None)
- , grabbedSection(Qt::NoSection)
- , buttonMouseOver(false)
- , buttonSunken(false)
- {}
- } *windowData;
- void ensureWindowData();
-
- bool setWindowFrameMargins;
- mutable qreal *windowFrameMargins;
- void ensureWindowFrameMargins() const;
-
-#ifndef QT_NO_ACTION
- QList<QAction *> actions;
-#endif
-};
-
-#endif //!defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
-
-QT_END_NAMESPACE
-
-#endif //QGRAPHICSWIDGET_P_H
-
diff --git a/src/gui/graphicsview/qgridlayoutengine.cpp b/src/gui/graphicsview/qgridlayoutengine.cpp
deleted file mode 100644
index b8586cef21..0000000000
--- a/src/gui/graphicsview/qgridlayoutengine.cpp
+++ /dev/null
@@ -1,1742 +0,0 @@
-/****************************************************************************
-**
-** 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"
-
-#ifndef QT_NO_GRAPHICSVIEW
-
-#include <math.h>
-
-#include "qgraphicslayoutitem.h"
-#include "qgridlayoutengine_p.h"
-#include "qstyleoption.h"
-#include "qvarlengtharray.h"
-
-#include <QtDebug>
-#include <QtCore/qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-template <typename T>
-static void insertOrRemoveItems(QVector<T> &items, int index, int delta)
-{
- int count = items.count();
- if (index < count) {
- if (delta > 0) {
- items.insert(index, delta, T());
- } else if (delta < 0) {
- items.remove(index, qMin(-delta, count - index));
- }
- }
-}
-
-static qreal growthFactorBelowPreferredSize(qreal desired, qreal sumAvailable, qreal sumDesired)
-{
- Q_ASSERT(sumDesired != 0.0);
- return desired * qPow(sumAvailable / sumDesired, desired / sumDesired);
-}
-
-static qreal fixedDescent(qreal descent, qreal ascent, qreal targetSize)
-{
- if (descent < 0.0)
- return -1.0;
-
- Q_ASSERT(descent >= 0.0);
- Q_ASSERT(ascent >= 0.0);
- Q_ASSERT(targetSize >= ascent + descent);
-
- qreal extra = targetSize - (ascent + descent);
- return descent + (extra / 2.0);
-}
-
-static qreal compare(const QGridLayoutBox &box1, const QGridLayoutBox &box2, int which)
-{
- qreal size1 = box1.q_sizes(which);
- qreal size2 = box2.q_sizes(which);
-
- if (which == MaximumSize) {
- return size2 - size1;
- } else {
- return size1 - size2;
- }
-}
-
-void QGridLayoutBox::add(const QGridLayoutBox &other, int stretch, qreal spacing)
-{
- Q_ASSERT(q_minimumDescent < 0.0);
-
- q_minimumSize += other.q_minimumSize + spacing;
- q_preferredSize += other.q_preferredSize + spacing;
- q_maximumSize += ((stretch == 0) ? other.q_preferredSize : other.q_maximumSize) + spacing;
-}
-
-void QGridLayoutBox::combine(const QGridLayoutBox &other)
-{
- q_minimumDescent = qMax(q_minimumDescent, other.q_minimumDescent);
- q_minimumAscent = qMax(q_minimumAscent, other.q_minimumAscent);
-
- q_minimumSize = qMax(q_minimumAscent + q_minimumDescent,
- qMax(q_minimumSize, other.q_minimumSize));
- qreal maxMax;
- if (q_maximumSize == FLT_MAX && other.q_maximumSize != FLT_MAX)
- maxMax = other.q_maximumSize;
- else if (other.q_maximumSize == FLT_MAX && q_maximumSize != FLT_MAX)
- maxMax = q_maximumSize;
- else
- maxMax = qMax(q_maximumSize, other.q_maximumSize);
-
- q_maximumSize = qMax(q_minimumSize, maxMax);
- q_preferredSize = qBound(q_minimumSize, qMax(q_preferredSize, other.q_preferredSize),
- q_maximumSize);
-}
-
-void QGridLayoutBox::normalize()
-{
- q_maximumSize = qMax(qreal(0.0), q_maximumSize);
- q_minimumSize = qBound(qreal(0.0), q_minimumSize, q_maximumSize);
- q_preferredSize = qBound(q_minimumSize, q_preferredSize, q_maximumSize);
- q_minimumDescent = qMin(q_minimumDescent, q_minimumSize);
-
- Q_ASSERT((q_minimumDescent < 0.0) == (q_minimumAscent < 0.0));
-}
-
-#ifdef QT_DEBUG
-void QGridLayoutBox::dump(int indent) const
-{
- qDebug("%*sBox (%g <= %g <= %g [%g/%g])", indent, "", q_minimumSize, q_preferredSize,
- q_maximumSize, q_minimumAscent, q_minimumDescent);
-}
-#endif
-
-bool operator==(const QGridLayoutBox &box1, const QGridLayoutBox &box2)
-{
- for (int i = 0; i < NSizes; ++i) {
- if (box1.q_sizes(i) != box2.q_sizes(i))
- return false;
- }
- return box1.q_minimumDescent == box2.q_minimumDescent
- && box1.q_minimumAscent == box2.q_minimumAscent;
-}
-
-void QGridLayoutRowData::reset(int count)
-{
- ignore.fill(false, count);
- boxes.fill(QGridLayoutBox(), count);
- multiCellMap.clear();
- stretches.fill(0, count);
- spacings.fill(0.0, count);
- hasIgnoreFlag = false;
-}
-
-void QGridLayoutRowData::distributeMultiCells(const QGridLayoutRowInfo &rowInfo)
-{
- MultiCellMap::const_iterator i = multiCellMap.constBegin();
- for (; i != multiCellMap.constEnd(); ++i) {
- int start = i.key().first;
- int span = i.key().second;
- int end = start + span;
- const QGridLayoutBox &box = i.value().q_box;
- int stretch = i.value().q_stretch;
-
- QGridLayoutBox totalBox = this->totalBox(start, end);
- QVarLengthArray<QGridLayoutBox> extras(span);
- QVarLengthArray<qreal> dummy(span);
- QVarLengthArray<qreal> newSizes(span);
-
- for (int j = 0; j < NSizes; ++j) {
- qreal extra = compare(box, totalBox, j);
- if (extra > 0.0) {
- calculateGeometries(start, end, box.q_sizes(j), dummy.data(), newSizes.data(),
- 0, totalBox, rowInfo);
-
- for (int k = 0; k < span; ++k)
- extras[k].q_sizes(j) = newSizes[k];
- }
- }
-
- for (int k = 0; k < span; ++k) {
- boxes[start + k].combine(extras[k]);
- if (stretch != 0)
- stretches[start + k] = qMax(stretches[start + k], stretch);
- }
- }
- multiCellMap.clear();
-}
-
-void QGridLayoutRowData::calculateGeometries(int start, int end, qreal targetSize, qreal *positions,
- qreal *sizes, qreal *descents,
- const QGridLayoutBox &totalBox,
- const QGridLayoutRowInfo &rowInfo)
-{
- Q_ASSERT(end > start);
-
- targetSize = qMax(totalBox.q_minimumSize, targetSize);
-
- int n = end - start;
- QVarLengthArray<qreal> newSizes(n);
- QVarLengthArray<qreal> factors(n);
- qreal sumFactors = 0.0;
- int sumStretches = 0;
- qreal sumAvailable;
-
- for (int i = 0; i < n; ++i) {
- if (stretches[start + i] > 0)
- sumStretches += stretches[start + i];
- }
-
- if (targetSize < totalBox.q_preferredSize) {
- stealBox(start, end, MinimumSize, positions, sizes);
-
- sumAvailable = targetSize - totalBox.q_minimumSize;
- if (sumAvailable > 0.0) {
- qreal sumDesired = totalBox.q_preferredSize - totalBox.q_minimumSize;
-
- for (int i = 0; i < n; ++i) {
- if (ignore.testBit(start + i)) {
- factors[i] = 0.0;
- continue;
- }
-
- const QGridLayoutBox &box = boxes.at(start + i);
- qreal desired = box.q_preferredSize - box.q_minimumSize;
- factors[i] = growthFactorBelowPreferredSize(desired, sumAvailable, sumDesired);
- sumFactors += factors[i];
- }
-
- for (int i = 0; i < n; ++i) {
- Q_ASSERT(sumFactors > 0.0);
- qreal delta = sumAvailable * factors[i] / sumFactors;
- newSizes[i] = sizes[i] + delta;
- }
- }
- } else {
- bool isLargerThanMaximum = (targetSize > totalBox.q_maximumSize);
- if (isLargerThanMaximum) {
- stealBox(start, end, MaximumSize, positions, sizes);
- sumAvailable = targetSize - totalBox.q_maximumSize;
- } else {
- stealBox(start, end, PreferredSize, positions, sizes);
- sumAvailable = targetSize - totalBox.q_preferredSize;
- }
-
- if (sumAvailable > 0.0) {
- qreal sumCurrentAvailable = sumAvailable;
- bool somethingHasAMaximumSize = false;
-
- qreal sumSizes = 0.0;
- for (int i = 0; i < n; ++i)
- sumSizes += sizes[i];
-
- for (int i = 0; i < n; ++i) {
- if (ignore.testBit(start + i)) {
- newSizes[i] = 0.0;
- factors[i] = 0.0;
- continue;
- }
-
- const QGridLayoutBox &box = boxes.at(start + i);
- qreal boxSize;
-
- qreal desired;
- if (isLargerThanMaximum) {
- boxSize = box.q_maximumSize;
- desired = rowInfo.boxes.value(start + i).q_maximumSize - boxSize;
- } else {
- boxSize = box.q_preferredSize;
- desired = box.q_maximumSize - boxSize;
- }
- if (desired == 0.0) {
- newSizes[i] = sizes[i];
- factors[i] = 0.0;
- } else {
- Q_ASSERT(desired > 0.0);
-
- int stretch = stretches[start + i];
- if (sumStretches == 0) {
- if (hasIgnoreFlag) {
- factors[i] = (stretch < 0) ? 1.0 : 0.0;
- } else {
- factors[i] = (stretch < 0) ? sizes[i] : 0.0;
- }
- } else if (stretch == sumStretches) {
- factors[i] = 1.0;
- } else if (stretch <= 0) {
- factors[i] = 0.0;
- } else {
- qreal ultimateSize;
- qreal ultimateSumSizes;
- qreal x = ((stretch * sumSizes)
- - (sumStretches * boxSize))
- / (sumStretches - stretch);
- if (x >= 0.0) {
- ultimateSize = boxSize + x;
- ultimateSumSizes = sumSizes + x;
- } else {
- ultimateSize = boxSize;
- ultimateSumSizes = (sumStretches * boxSize)
- / stretch;
- }
-
- /*
- We multiply these by 1.5 to give some space for a smooth transition
- (at the expense of the stretch factors, which are not fully respected
- during the transition).
- */
- ultimateSize = ultimateSize * 3 / 2;
- ultimateSumSizes = ultimateSumSizes * 3 / 2;
-
- qreal beta = ultimateSumSizes - sumSizes;
- if (!beta) {
- factors[i] = 1;
- } else {
- qreal alpha = qMin(sumCurrentAvailable, beta);
- qreal ultimateFactor = (stretch * ultimateSumSizes / sumStretches)
- - (boxSize);
- qreal transitionalFactor = sumCurrentAvailable * (ultimateSize - boxSize) / beta;
-
- factors[i] = ((alpha * ultimateFactor)
- + ((beta - alpha) * transitionalFactor)) / beta;
- }
-
- }
- sumFactors += factors[i];
- if (desired < sumCurrentAvailable)
- somethingHasAMaximumSize = true;
-
- newSizes[i] = -1.0;
- }
- }
-
- bool keepGoing = somethingHasAMaximumSize;
- while (keepGoing) {
- keepGoing = false;
-
- for (int i = 0; i < n; ++i) {
- if (newSizes[i] >= 0.0)
- continue;
-
- qreal maxBoxSize;
- if (isLargerThanMaximum)
- maxBoxSize = rowInfo.boxes.value(start + i).q_maximumSize;
- else
- maxBoxSize = boxes.at(start + i).q_maximumSize;
-
- qreal avail = sumCurrentAvailable * factors[i] / sumFactors;
- if (sizes[i] + avail >= maxBoxSize) {
- newSizes[i] = maxBoxSize;
- sumCurrentAvailable -= maxBoxSize - sizes[i];
- sumFactors -= factors[i];
- keepGoing = (sumCurrentAvailable > 0.0);
- if (!keepGoing)
- break;
- }
- }
- }
-
- for (int i = 0; i < n; ++i) {
- if (newSizes[i] < 0.0) {
- qreal delta = (sumFactors == 0.0) ? 0.0
- : sumCurrentAvailable * factors[i] / sumFactors;
- newSizes[i] = sizes[i] + delta;
- }
- }
- }
- }
-
- if (sumAvailable > 0) {
- qreal offset = 0;
- for (int i = 0; i < n; ++i) {
- qreal delta = newSizes[i] - sizes[i];
- positions[i] += offset;
- sizes[i] += delta;
- offset += delta;
- }
-
-#if 0 // some "pixel allocation"
- int surplus = targetSize - (positions[n - 1] + sizes[n - 1]);
- Q_ASSERT(surplus >= 0 && surplus <= n);
-
- int prevSurplus = -1;
- while (surplus > 0 && surplus != prevSurplus) {
- prevSurplus = surplus;
-
- int offset = 0;
- for (int i = 0; i < n; ++i) {
- const QGridLayoutBox &box = boxes.at(start + i);
- int delta = (!ignore.testBit(start + i) && surplus > 0
- && factors[i] > 0 && sizes[i] < box.q_maximumSize)
- ? 1 : 0;
-
- positions[i] += offset;
- sizes[i] += delta;
- offset += delta;
- surplus -= delta;
- }
- }
- Q_ASSERT(surplus == 0);
-#endif
- }
-
- if (descents) {
- for (int i = 0; i < n; ++i) {
- if (ignore.testBit(start + i))
- continue;
- const QGridLayoutBox &box = boxes.at(start + i);
- descents[i] = fixedDescent(box.q_minimumDescent, box.q_minimumAscent, sizes[i]);
- }
- }
-}
-
-QGridLayoutBox QGridLayoutRowData::totalBox(int start, int end) const
-{
- QGridLayoutBox result;
- if (start < end) {
- result.q_maximumSize = 0.0;
- qreal nextSpacing = 0.0;
- for (int i = start; i < end; ++i) {
- result.add(boxes.at(i), stretches.at(i), nextSpacing);
- nextSpacing = spacings.at(i);
- }
- }
- return result;
-}
-
-void QGridLayoutRowData::stealBox(int start, int end, int which, qreal *positions, qreal *sizes)
-{
- qreal offset = 0.0;
- qreal nextSpacing = 0.0;
-
- for (int i = start; i < end; ++i) {
- qreal avail = 0.0;
-
- if (!ignore.testBit(i)) {
- const QGridLayoutBox &box = boxes.at(i);
- avail = box.q_sizes(which);
- offset += nextSpacing;
- nextSpacing = spacings.at(i);
- }
-
- *positions++ = offset;
- *sizes++ = avail;
- offset += avail;
- }
-}
-
-#ifdef QT_DEBUG
-void QGridLayoutRowData::dump(int indent) const
-{
- qDebug("%*sData", indent, "");
-
- for (int i = 0; i < ignore.count(); ++i) {
- qDebug("%*s Row %d (stretch %d, spacing %g)", indent, "", i, stretches.at(i),
- spacings.at(i));
- if (ignore.testBit(i))
- qDebug("%*s Ignored", indent, "");
- boxes.at(i).dump(indent + 2);
- }
-
- MultiCellMap::const_iterator it = multiCellMap.constBegin();
- while (it != multiCellMap.constEnd()) {
- qDebug("%*s Multi-cell entry <%d, %d> (stretch %d)", indent, "", it.key().first,
- it.key().second, it.value().q_stretch);
- it.value().q_box.dump(indent + 2);
- }
-}
-#endif
-
-QGridLayoutItem::QGridLayoutItem(QGridLayoutEngine *engine, QGraphicsLayoutItem *layoutItem,
- int row, int column, int rowSpan, int columnSpan,
- Qt::Alignment alignment, int itemAtIndex)
- : q_engine(engine), q_layoutItem(layoutItem), q_alignment(alignment)
-{
- q_firstRows[Hor] = column;
- q_firstRows[Ver] = row;
- q_rowSpans[Hor] = columnSpan;
- q_rowSpans[Ver] = rowSpan;
- q_stretches[Hor] = -1;
- q_stretches[Ver] = -1;
-
- q_engine->insertItem(this, itemAtIndex);
-}
-
-int QGridLayoutItem::firstRow(Qt::Orientation orientation) const
-{
- return q_firstRows[orientation == Qt::Vertical];
-}
-
-int QGridLayoutItem::firstColumn(Qt::Orientation orientation) const
-{
- return q_firstRows[orientation == Qt::Horizontal];
-}
-
-int QGridLayoutItem::lastRow(Qt::Orientation orientation) const
-{
- return firstRow(orientation) + rowSpan(orientation) - 1;
-}
-
-int QGridLayoutItem::lastColumn(Qt::Orientation orientation) const
-{
- return firstColumn(orientation) + columnSpan(orientation) - 1;
-}
-
-int QGridLayoutItem::rowSpan(Qt::Orientation orientation) const
-{
- return q_rowSpans[orientation == Qt::Vertical];
-}
-
-int QGridLayoutItem::columnSpan(Qt::Orientation orientation) const
-{
- return q_rowSpans[orientation == Qt::Horizontal];
-}
-
-void QGridLayoutItem::setFirstRow(int row, Qt::Orientation orientation)
-{
- q_firstRows[orientation == Qt::Vertical] = row;
-}
-
-void QGridLayoutItem::setRowSpan(int rowSpan, Qt::Orientation orientation)
-{
- q_rowSpans[orientation == Qt::Vertical] = rowSpan;
-}
-
-int QGridLayoutItem::stretchFactor(Qt::Orientation orientation) const
-{
- int stretch = q_stretches[orientation == Qt::Vertical];
- if (stretch >= 0)
- return stretch;
-
- QSizePolicy::Policy policy = sizePolicy(orientation);
-
- if (policy & QSizePolicy::ExpandFlag) {
- return 1;
- } else if (policy & QSizePolicy::GrowFlag) {
- return -1; // because we max it up
- } else {
- return 0;
- }
-}
-
-void QGridLayoutItem::setStretchFactor(int stretch, Qt::Orientation orientation)
-{
- Q_ASSERT(stretch >= 0); // ### deal with too big stretches
- q_stretches[orientation == Qt::Vertical] = stretch;
-}
-
-QSizePolicy::Policy QGridLayoutItem::sizePolicy(Qt::Orientation orientation) const
-{
- QSizePolicy sizePolicy(q_layoutItem->sizePolicy());
- return (orientation == Qt::Horizontal) ? sizePolicy.horizontalPolicy()
- : sizePolicy.verticalPolicy();
-}
-
-/*
- returns true if the size policy returns true for either hasHeightForWidth()
- or hasWidthForHeight()
- */
-bool QGridLayoutItem::hasDynamicConstraint() const
-{
- return QGraphicsLayoutItemPrivate::get(q_layoutItem)->hasHeightForWidth()
- || QGraphicsLayoutItemPrivate::get(q_layoutItem)->hasWidthForHeight();
-}
-
-Qt::Orientation QGridLayoutItem::dynamicConstraintOrientation() const
-{
- if (QGraphicsLayoutItemPrivate::get(q_layoutItem)->hasHeightForWidth())
- return Qt::Vertical;
- else //if (QGraphicsLayoutItemPrivate::get(q_layoutItem)->hasWidthForHeight())
- return Qt::Horizontal;
-}
-
-QSizePolicy::ControlTypes QGridLayoutItem::controlTypes(LayoutSide /* side */) const
-{
- return q_layoutItem->sizePolicy().controlType();
-}
-
-QSizeF QGridLayoutItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
-{
- return q_layoutItem->effectiveSizeHint(which, constraint);
-}
-
-QGridLayoutBox QGridLayoutItem::box(Qt::Orientation orientation, qreal constraint) const
-{
- QGridLayoutBox result;
- QSizePolicy::Policy policy = sizePolicy(orientation);
-
- if (orientation == Qt::Horizontal) {
- QSizeF constraintSize(-1.0, constraint);
-
- result.q_preferredSize = sizeHint(Qt::PreferredSize, constraintSize).width();
-
- if (policy & QSizePolicy::ShrinkFlag) {
- result.q_minimumSize = sizeHint(Qt::MinimumSize, constraintSize).width();
- } else {
- result.q_minimumSize = result.q_preferredSize;
- }
-
- if (policy & (QSizePolicy::GrowFlag | QSizePolicy::ExpandFlag)) {
- result.q_maximumSize = sizeHint(Qt::MaximumSize, constraintSize).width();
- } else {
- result.q_maximumSize = result.q_preferredSize;
- }
- } else {
- QSizeF constraintSize(constraint, -1.0);
-
- result.q_preferredSize = sizeHint(Qt::PreferredSize, constraintSize).height();
-
- if (policy & QSizePolicy::ShrinkFlag) {
- result.q_minimumSize = sizeHint(Qt::MinimumSize, constraintSize).height();
- } else {
- result.q_minimumSize = result.q_preferredSize;
- }
-
- if (policy & (QSizePolicy::GrowFlag | QSizePolicy::ExpandFlag)) {
- result.q_maximumSize = sizeHint(Qt::MaximumSize, constraintSize).height();
- } else {
- result.q_maximumSize = result.q_preferredSize;
- }
-
- result.q_minimumDescent = sizeHint(Qt::MinimumDescent, constraintSize).height();
- if (result.q_minimumDescent >= 0.0)
- result.q_minimumAscent = result.q_minimumSize - result.q_minimumDescent;
- }
- if (policy & QSizePolicy::IgnoreFlag)
- result.q_preferredSize = result.q_minimumSize;
-
- return result;
-}
-
-QRectF QGridLayoutItem::geometryWithin(qreal x, qreal y, qreal width, qreal height,
- qreal rowDescent) const
-{
- rowDescent = -1.0; // ### This disables the descent
-
- QGridLayoutBox vBox = box(Qt::Vertical);
- if (vBox.q_minimumDescent < 0.0 || rowDescent < 0.0) {
- qreal cellWidth = width;
- qreal cellHeight = height;
-
-
- QSizeF size = effectiveMaxSize(QSizeF(-1,-1));
- if (hasDynamicConstraint()) {
- if (dynamicConstraintOrientation() == Qt::Vertical) {
- if (size.width() > cellWidth)
- size = effectiveMaxSize(QSizeF(cellWidth, -1));
- } else if (size.height() > cellHeight) {
- size = effectiveMaxSize(QSizeF(-1, cellHeight));
- }
- }
- size = size.boundedTo(QSizeF(cellWidth, cellHeight));
- width = size.width();
- height = size.height();
-
- Qt::Alignment align = q_engine->effectiveAlignment(this);
- switch (align & Qt::AlignHorizontal_Mask) {
- case Qt::AlignHCenter:
- x += (cellWidth - width)/2;
- break;
- case Qt::AlignRight:
- x += cellWidth - width;
- break;
- default:
- break;
- }
- switch (align & Qt::AlignVertical_Mask) {
- case Qt::AlignVCenter:
- y += (cellHeight - height)/2;
- break;
- case Qt::AlignBottom:
- y += cellHeight - height;
- break;
- default:
- break;
- }
- return QRectF(x, y, width, height);
- } else {
- qreal descent = vBox.q_minimumDescent;
- qreal ascent = vBox.q_minimumSize - descent;
- return QRectF(x, y + height - rowDescent - ascent, width, ascent + descent);
- }
-}
-
-void QGridLayoutItem::setGeometry(const QRectF &rect)
-{
- q_layoutItem->setGeometry(rect);
-}
-
-void QGridLayoutItem::transpose()
-{
- qSwap(q_firstRows[Hor], q_firstRows[Ver]);
- qSwap(q_rowSpans[Hor], q_rowSpans[Ver]);
- qSwap(q_stretches[Hor], q_stretches[Ver]);
-}
-
-void QGridLayoutItem::insertOrRemoveRows(int row, int delta, Qt::Orientation orientation)
-{
- int oldFirstRow = firstRow(orientation);
- if (oldFirstRow >= row) {
- setFirstRow(oldFirstRow + delta, orientation);
- } else if (lastRow(orientation) >= row) {
- setRowSpan(rowSpan(orientation) + delta, orientation);
- }
-}
-/*!
- \internal
- returns the effective maximumSize, will take the sizepolicy into
- consideration. (i.e. if sizepolicy does not have QSizePolicy::Grow, then
- maxSizeHint will be the preferredSize)
- Note that effectiveSizeHint does not take sizePolicy into consideration,
- (since it only evaluates the hints, as the name implies)
-*/
-QSizeF QGridLayoutItem::effectiveMaxSize(const QSizeF &constraint) const
-{
- QSizeF size = constraint;
- bool vGrow = (sizePolicy(Qt::Vertical) & QSizePolicy::GrowFlag) == QSizePolicy::GrowFlag;
- bool hGrow = (sizePolicy(Qt::Horizontal) & QSizePolicy::GrowFlag) == QSizePolicy::GrowFlag;
- if (!vGrow || !hGrow) {
- QSizeF pref = layoutItem()->effectiveSizeHint(Qt::PreferredSize, constraint);
- if (!vGrow)
- size.setHeight(pref.height());
- if (!hGrow)
- size.setWidth(pref.width());
- }
-
- if (!size.isValid()) {
- QSizeF maxSize = layoutItem()->effectiveSizeHint(Qt::MaximumSize, size);
- if (size.width() == -1)
- size.setWidth(maxSize.width());
- if (size.height() == -1)
- size.setHeight(maxSize.height());
- }
- return size;
-}
-
-#ifdef QT_DEBUG
-void QGridLayoutItem::dump(int indent) const
-{
- qDebug("%*s%p (%d, %d) %d x %d", indent, "", q_layoutItem, firstRow(), firstColumn(),
- rowSpan(), columnSpan());
-
- if (q_stretches[Hor] >= 0)
- qDebug("%*s Horizontal stretch: %d", indent, "", q_stretches[Hor]);
- if (q_stretches[Ver] >= 0)
- qDebug("%*s Vertical stretch: %d", indent, "", q_stretches[Ver]);
- if (q_alignment != 0)
- qDebug("%*s Alignment: %x", indent, "", uint(q_alignment));
- qDebug("%*s Horizontal size policy: %x Vertical size policy: %x",
- indent, "", sizePolicy(Qt::Horizontal), sizePolicy(Qt::Vertical));
-}
-#endif
-
-void QGridLayoutRowInfo::insertOrRemoveRows(int row, int delta)
-{
- count += delta;
-
- insertOrRemoveItems(stretches, row, delta);
- insertOrRemoveItems(spacings, row, delta);
- insertOrRemoveItems(alignments, row, delta);
- insertOrRemoveItems(boxes, row, delta);
-}
-
-#ifdef QT_DEBUG
-void QGridLayoutRowInfo::dump(int indent) const
-{
- qDebug("%*sInfo (count: %d)", indent, "", count);
- for (int i = 0; i < count; ++i) {
- QString message;
-
- if (stretches.value(i).value() >= 0)
- message += QString::fromAscii(" stretch %1").arg(stretches.value(i).value());
- if (spacings.value(i).value() >= 0.0)
- message += QString::fromAscii(" spacing %1").arg(spacings.value(i).value());
- if (alignments.value(i) != 0)
- message += QString::fromAscii(" alignment %1").arg(int(alignments.value(i)), 16);
-
- if (!message.isEmpty() || boxes.value(i) != QGridLayoutBox()) {
- qDebug("%*s Row %d:%s", indent, "", i, qPrintable(message));
- if (boxes.value(i) != QGridLayoutBox())
- boxes.value(i).dump(indent + 1);
- }
- }
-}
-#endif
-
-QGridLayoutEngine::QGridLayoutEngine()
-{
- m_visualDirection = Qt::LeftToRight;
- invalidate();
-}
-
-int QGridLayoutEngine::rowCount(Qt::Orientation orientation) const
-{
- return q_infos[orientation == Qt::Vertical].count;
-}
-
-int QGridLayoutEngine::columnCount(Qt::Orientation orientation) const
-{
- return q_infos[orientation == Qt::Horizontal].count;
-}
-
-int QGridLayoutEngine::itemCount() const
-{
- return q_items.count();
-}
-
-QGridLayoutItem *QGridLayoutEngine::itemAt(int index) const
-{
- Q_ASSERT(index >= 0 && index < itemCount());
- return q_items.at(index);
-}
-
-int QGridLayoutEngine::indexOf(QGraphicsLayoutItem *item) const
-{
- for (int i = 0; i < q_items.size(); ++i) {
- if (item == q_items.at(i)->layoutItem())
- return i;
- }
- return -1;
-}
-
-int QGridLayoutEngine::effectiveFirstRow(Qt::Orientation orientation) const
-{
- ensureEffectiveFirstAndLastRows();
- return q_cachedEffectiveFirstRows[orientation == Qt::Vertical];
-}
-
-int QGridLayoutEngine::effectiveLastRow(Qt::Orientation orientation) const
-{
- ensureEffectiveFirstAndLastRows();
- return q_cachedEffectiveLastRows[orientation == Qt::Vertical];
-}
-
-void QGridLayoutEngine::setSpacing(qreal spacing, Qt::Orientations orientations)
-{
- Q_ASSERT(spacing >= 0.0);
- if (orientations & Qt::Horizontal)
- q_defaultSpacings[Hor].setUserValue(spacing);
- if (orientations & Qt::Vertical)
- q_defaultSpacings[Ver].setUserValue(spacing);
-
- invalidate();
-}
-
-qreal QGridLayoutEngine::spacing(const QLayoutStyleInfo &styleInfo, Qt::Orientation orientation) const
-{
- if (q_defaultSpacings[orientation == Qt::Vertical].isDefault()) {
- QStyle *style = styleInfo.style();
- QStyleOption option;
- option.initFrom(styleInfo.widget());
- qreal defaultSpacing = (qreal)style->pixelMetric(orientation == Qt::Vertical ? QStyle::PM_LayoutVerticalSpacing
- : QStyle::PM_LayoutHorizontalSpacing, &option, styleInfo.widget());
- q_defaultSpacings[orientation == Qt::Vertical].setCachedValue(defaultSpacing);
- }
- return q_defaultSpacings[orientation == Qt::Vertical].value();
-}
-
-void QGridLayoutEngine::setRowSpacing(int row, qreal spacing, Qt::Orientation orientation)
-{
- Q_ASSERT(row >= 0);
-
- QGridLayoutRowInfo &rowInfo = q_infos[orientation == Qt::Vertical];
- if (row >= rowInfo.spacings.count())
- rowInfo.spacings.resize(row + 1);
- if (spacing >= 0)
- rowInfo.spacings[row].setUserValue(spacing);
- else
- rowInfo.spacings[row] = QLayoutParameter<qreal>();
- invalidate();
-}
-
-qreal QGridLayoutEngine::rowSpacing(int row, Qt::Orientation orientation) const
-{
- QLayoutParameter<qreal> spacing = q_infos[orientation == Qt::Vertical].spacings.value(row);
- if (!spacing.isDefault())
- return spacing.value();
- return q_defaultSpacings[orientation == Qt::Vertical].value();
-}
-
-void QGridLayoutEngine::setRowStretchFactor(int row, int stretch, Qt::Orientation orientation)
-{
- Q_ASSERT(row >= 0);
- Q_ASSERT(stretch >= 0);
-
- maybeExpandGrid(row, -1, orientation);
-
- QGridLayoutRowInfo &rowInfo = q_infos[orientation == Qt::Vertical];
- if (row >= rowInfo.stretches.count())
- rowInfo.stretches.resize(row + 1);
- rowInfo.stretches[row].setUserValue(stretch);
-}
-
-int QGridLayoutEngine::rowStretchFactor(int row, Qt::Orientation orientation) const
-{
- QStretchParameter stretch = q_infos[orientation == Qt::Vertical].stretches.value(row);
- if (!stretch.isDefault())
- return stretch.value();
- return 0;
-}
-
-void QGridLayoutEngine::setStretchFactor(QGraphicsLayoutItem *layoutItem, int stretch,
- Qt::Orientation orientation)
-{
- Q_ASSERT(stretch >= 0);
-
- if (QGridLayoutItem *item = findLayoutItem(layoutItem))
- item->setStretchFactor(stretch, orientation);
-}
-
-int QGridLayoutEngine::stretchFactor(QGraphicsLayoutItem *layoutItem, Qt::Orientation orientation) const
-{
- if (QGridLayoutItem *item = findLayoutItem(layoutItem))
- return item->stretchFactor(orientation);
- return 0;
-}
-
-void QGridLayoutEngine::setRowSizeHint(Qt::SizeHint which, int row, qreal size,
- Qt::Orientation orientation)
-{
- Q_ASSERT(row >= 0);
- Q_ASSERT(size >= 0.0);
-
- maybeExpandGrid(row, -1, orientation);
-
- QGridLayoutRowInfo &rowInfo = q_infos[orientation == Qt::Vertical];
- if (row >= rowInfo.boxes.count())
- rowInfo.boxes.resize(row + 1);
- rowInfo.boxes[row].q_sizes(which) = size;
-}
-
-qreal QGridLayoutEngine::rowSizeHint(Qt::SizeHint which, int row, Qt::Orientation orientation) const
-{
- return q_infos[orientation == Qt::Vertical].boxes.value(row).q_sizes(which);
-}
-
-void QGridLayoutEngine::setRowAlignment(int row, Qt::Alignment alignment,
- Qt::Orientation orientation)
-{
- Q_ASSERT(row >= 0);
-
- maybeExpandGrid(row, -1, orientation);
-
- QGridLayoutRowInfo &rowInfo = q_infos[orientation == Qt::Vertical];
- if (row >= rowInfo.alignments.count())
- rowInfo.alignments.resize(row + 1);
- rowInfo.alignments[row] = alignment;
-}
-
-Qt::Alignment QGridLayoutEngine::rowAlignment(int row, Qt::Orientation orientation) const
-{
- Q_ASSERT(row >= 0);
- return q_infos[orientation == Qt::Vertical].alignments.value(row);
-}
-
-void QGridLayoutEngine::setAlignment(QGraphicsLayoutItem *layoutItem, Qt::Alignment alignment)
-{
- if (QGridLayoutItem *item = findLayoutItem(layoutItem))
- item->setAlignment(alignment);
- invalidate();
-}
-
-Qt::Alignment QGridLayoutEngine::alignment(QGraphicsLayoutItem *layoutItem) const
-{
- if (QGridLayoutItem *item = findLayoutItem(layoutItem))
- return item->alignment();
- return 0;
-}
-
-Qt::Alignment QGridLayoutEngine::effectiveAlignment(const QGridLayoutItem *layoutItem) const
-{
- Qt::Alignment align = layoutItem->alignment();
- if (!(align & Qt::AlignVertical_Mask)) {
- // no vertical alignment, respect the row alignment
- int y = layoutItem->firstRow();
- align |= (rowAlignment(y, Qt::Vertical) & Qt::AlignVertical_Mask);
- }
- if (!(align & Qt::AlignHorizontal_Mask)) {
- // no horizontal alignment, respect the column alignment
- int x = layoutItem->firstColumn();
- align |= (rowAlignment(x, Qt::Horizontal) & Qt::AlignHorizontal_Mask);
- }
- return align;
-}
-
-/*!
- \internal
- The \a index is only used by QGraphicsLinearLayout to ensure that itemAt() reflects the order
- of visual arrangement. Strictly speaking it does not have to, but most people expect it to.
- (And if it didn't we would have to add itemArrangedAt(int index) or something..)
- */
-void QGridLayoutEngine::insertItem(QGridLayoutItem *item, int index)
-{
- maybeExpandGrid(item->lastRow(), item->lastColumn());
-
- if (index == -1)
- q_items.append(item);
- else
- q_items.insert(index, item);
-
- for (int i = item->firstRow(); i <= item->lastRow(); ++i) {
- for (int j = item->firstColumn(); j <= item->lastColumn(); ++j) {
- if (itemAt(i, j))
- qWarning("QGridLayoutEngine::addItem: Cell (%d, %d) already taken", i, j);
- setItemAt(i, j, item);
- }
- }
-}
-
-void QGridLayoutEngine::addItem(QGridLayoutItem *item)
-{
- insertItem(item, -1);
-}
-
-void QGridLayoutEngine::removeItem(QGridLayoutItem *item)
-{
- Q_ASSERT(q_items.contains(item));
-
- invalidate();
-
- for (int i = item->firstRow(); i <= item->lastRow(); ++i) {
- for (int j = item->firstColumn(); j <= item->lastColumn(); ++j) {
- if (itemAt(i, j) == item)
- setItemAt(i, j, 0);
- }
- }
-
- q_items.removeAll(item);
-}
-
-QGridLayoutItem *QGridLayoutEngine::findLayoutItem(QGraphicsLayoutItem *layoutItem) const
-{
- for (int i = q_items.count() - 1; i >= 0; --i) {
- QGridLayoutItem *item = q_items.at(i);
- if (item->layoutItem() == layoutItem)
- return item;
- }
- return 0;
-}
-
-QGridLayoutItem *QGridLayoutEngine::itemAt(int row, int column, Qt::Orientation orientation) const
-{
- if (orientation == Qt::Horizontal)
- qSwap(row, column);
- if (uint(row) >= uint(rowCount()) || uint(column) >= uint(columnCount()))
- return 0;
- return q_grid.at((row * internalGridColumnCount()) + column);
-}
-
-void QGridLayoutEngine::invalidate()
-{
- q_cachedEffectiveFirstRows[Hor] = -1;
- q_cachedEffectiveFirstRows[Ver] = -1;
- q_cachedEffectiveLastRows[Hor] = -1;
- q_cachedEffectiveLastRows[Ver] = -1;
- q_cachedDataForStyleInfo.invalidate();
- q_cachedSize = QSizeF();
- q_cachedConstraintOrientation = UnknownConstraint;
-}
-
-static void visualRect(QRectF *geom, Qt::LayoutDirection dir, const QRectF &contentsRect)
-{
- if (dir == Qt::RightToLeft)
- geom->moveRight(contentsRect.right() - (geom->left() - contentsRect.left()));
-}
-
-void QGridLayoutEngine::setGeometries(const QLayoutStyleInfo &styleInfo,
- const QRectF &contentsGeometry)
-{
- if (rowCount() < 1 || columnCount() < 1)
- return;
-
- ensureGeometries(styleInfo, contentsGeometry.size());
-
- for (int i = q_items.count() - 1; i >= 0; --i) {
- QGridLayoutItem *item = q_items.at(i);
-
- qreal x = q_xx[item->firstColumn()];
- qreal y = q_yy[item->firstRow()];
- qreal width = q_widths[item->lastColumn()];
- qreal height = q_heights[item->lastRow()];
-
- if (item->columnSpan() != 1)
- width += q_xx[item->lastColumn()] - x;
- if (item->rowSpan() != 1)
- height += q_yy[item->lastRow()] - y;
-
- QRectF geom = item->geometryWithin(contentsGeometry.x() + x, contentsGeometry.y() + y,
- width, height, q_descents[item->lastRow()]);
- visualRect(&geom, visualDirection(), contentsGeometry);
- item->setGeometry(geom);
- }
-}
-
-// ### candidate for deletion
-QRectF QGridLayoutEngine::cellRect(const QLayoutStyleInfo &styleInfo,
- const QRectF &contentsGeometry, int row, int column, int rowSpan,
- int columnSpan) const
-{
- if (uint(row) >= uint(rowCount()) || uint(column) >= uint(columnCount())
- || rowSpan < 1 || columnSpan < 1)
- return QRectF();
-
- ensureGeometries(styleInfo, contentsGeometry.size());
-
- int lastColumn = qMax(column + columnSpan, columnCount()) - 1;
- int lastRow = qMax(row + rowSpan, rowCount()) - 1;
-
- qreal x = q_xx[column];
- qreal y = q_yy[row];
- qreal width = q_widths[lastColumn];
- qreal height = q_heights[lastRow];
-
- if (columnSpan != 1)
- width += q_xx[lastColumn] - x;
- if (rowSpan != 1)
- height += q_yy[lastRow] - y;
-
- return QRectF(contentsGeometry.x() + x, contentsGeometry.y() + y, width, height);
-}
-
-QSizeF QGridLayoutEngine::sizeHint(const QLayoutStyleInfo &styleInfo, Qt::SizeHint which,
- const QSizeF &constraint) const
-{
- QGridLayoutBox sizehint_totalBoxes[NOrientations];
-
- bool sizeHintCalculated = false;
-
- if (hasDynamicConstraint() && rowCount() > 0 && columnCount() > 0) {
- if (constraintOrientation() == Qt::Vertical) {
- //We have items whose height depends on their width
- if (constraint.width() >= 0) {
- if (q_cachedDataForStyleInfo != styleInfo)
- ensureColumnAndRowData(&q_columnData, &sizehint_totalBoxes[Hor], styleInfo, NULL, NULL, Qt::Horizontal);
- else
- sizehint_totalBoxes[Hor] = q_totalBoxes[Hor];
- QVector<qreal> sizehint_xx;
- QVector<qreal> sizehint_widths;
-
- sizehint_xx.resize(columnCount());
- sizehint_widths.resize(columnCount());
- qreal width = constraint.width();
- //Calculate column widths and positions, and put results in q_xx.data() and q_widths.data() so that we can use this information as
- //constraints to find the row heights
- q_columnData.calculateGeometries(0, columnCount(), width, sizehint_xx.data(), sizehint_widths.data(),
- 0, sizehint_totalBoxes[Hor], q_infos[Hor]);
- ensureColumnAndRowData(&q_rowData, &sizehint_totalBoxes[Ver], styleInfo, sizehint_xx.data(), sizehint_widths.data(), Qt::Vertical);
- sizeHintCalculated = true;
- }
- } else {
- if (constraint.height() >= 0) {
- //We have items whose width depends on their height
- ensureColumnAndRowData(&q_rowData, &sizehint_totalBoxes[Ver], styleInfo, NULL, NULL, Qt::Vertical);
- QVector<qreal> sizehint_yy;
- QVector<qreal> sizehint_heights;
-
- sizehint_yy.resize(rowCount());
- sizehint_heights.resize(rowCount());
- qreal height = constraint.height();
- //Calculate row heights and positions, and put results in q_yy.data() and q_heights.data() so that we can use this information as
- //constraints to find the column widths
- q_rowData.calculateGeometries(0, rowCount(), height, sizehint_yy.data(), sizehint_heights.data(),
- 0, sizehint_totalBoxes[Ver], q_infos[Ver]);
- ensureColumnAndRowData(&q_columnData, &sizehint_totalBoxes[Hor], styleInfo, sizehint_yy.data(), sizehint_heights.data(), Qt::Horizontal);
- sizeHintCalculated = true;
- }
- }
- }
-
- if (!sizeHintCalculated) {
- //No items with height for width, so it doesn't matter which order we do these in
- if (q_cachedDataForStyleInfo != styleInfo) {
- ensureColumnAndRowData(&q_columnData, &sizehint_totalBoxes[Hor], styleInfo, NULL, NULL, Qt::Horizontal);
- ensureColumnAndRowData(&q_rowData, &sizehint_totalBoxes[Ver], styleInfo, NULL, NULL, Qt::Vertical);
- } else {
- sizehint_totalBoxes[Hor] = q_totalBoxes[Hor];
- sizehint_totalBoxes[Ver] = q_totalBoxes[Ver];
- }
- }
-
- switch (which) {
- case Qt::MinimumSize:
- return QSizeF(sizehint_totalBoxes[Hor].q_minimumSize, sizehint_totalBoxes[Ver].q_minimumSize);
- case Qt::PreferredSize:
- return QSizeF(sizehint_totalBoxes[Hor].q_preferredSize, sizehint_totalBoxes[Ver].q_preferredSize);
- case Qt::MaximumSize:
- return QSizeF(sizehint_totalBoxes[Hor].q_maximumSize, sizehint_totalBoxes[Ver].q_maximumSize);
- case Qt::MinimumDescent:
- return QSizeF(-1.0, sizehint_totalBoxes[Hor].q_minimumDescent); // ### doesn't work
- default:
- break;
- }
- return QSizeF();
-}
-
-QSizePolicy::ControlTypes QGridLayoutEngine::controlTypes(LayoutSide side) const
-{
- Qt::Orientation orientation = (side == Top || side == Bottom) ? Qt::Vertical : Qt::Horizontal;
- int row = (side == Top || side == Left) ? effectiveFirstRow(orientation)
- : effectiveLastRow(orientation);
- QSizePolicy::ControlTypes result = 0;
-
- for (int column = columnCount(orientation) - 1; column >= 0; --column) {
- if (QGridLayoutItem *item = itemAt(row, column, orientation))
- result |= item->controlTypes(side);
- }
- return result;
-}
-
-void QGridLayoutEngine::transpose()
-{
- invalidate();
-
- for (int i = q_items.count() - 1; i >= 0; --i)
- q_items.at(i)->transpose();
-
- qSwap(q_defaultSpacings[Hor], q_defaultSpacings[Ver]);
- qSwap(q_infos[Hor], q_infos[Ver]);
-
- regenerateGrid();
-}
-
-void QGridLayoutEngine::setVisualDirection(Qt::LayoutDirection direction)
-{
- m_visualDirection = direction;
-}
-
-Qt::LayoutDirection QGridLayoutEngine::visualDirection() const
-{
- return m_visualDirection;
-}
-
-#ifdef QT_DEBUG
-void QGridLayoutEngine::dump(int indent) const
-{
- qDebug("%*sEngine", indent, "");
-
- qDebug("%*s Items (%d)", indent, "", q_items.count());
- int i;
- for (i = 0; i < q_items.count(); ++i)
- q_items.at(i)->dump(indent + 2);
-
- qDebug("%*s Grid (%d x %d)", indent, "", internalGridRowCount(),
- internalGridColumnCount());
- for (int row = 0; row < internalGridRowCount(); ++row) {
- QString message = QLatin1String("[ ");
- for (int column = 0; column < internalGridColumnCount(); ++column) {
- message += QString::number(q_items.indexOf(itemAt(row, column))).rightJustified(3);
- message += QLatin1Char(' ');
- }
- message += QLatin1Char(']');
- qDebug("%*s %s", indent, "", qPrintable(message));
- }
-
- if (q_defaultSpacings[Hor].value() >= 0.0 || q_defaultSpacings[Ver].value() >= 0.0)
- qDebug("%*s Default spacings: %g %g", indent, "", q_defaultSpacings[Hor].value(),
- q_defaultSpacings[Ver].value());
-
- qDebug("%*s Column and row info", indent, "");
- q_infos[Hor].dump(indent + 2);
- q_infos[Ver].dump(indent + 2);
-
- qDebug("%*s Column and row data", indent, "");
- q_columnData.dump(indent + 2);
- q_rowData.dump(indent + 2);
-
- qDebug("%*s Geometries output", indent, "");
- QVector<qreal> *cellPos = &q_yy;
- for (int pass = 0; pass < 2; ++pass) {
- QString message;
- for (i = 0; i < cellPos->count(); ++i) {
- message += QLatin1String((message.isEmpty() ? "[" : ", "));
- message += QString::number(cellPos->at(i));
- }
- message += QLatin1Char(']');
- qDebug("%*s %s %s", indent, "", (pass == 0 ? "rows:" : "columns:"), qPrintable(message));
- cellPos = &q_xx;
- }
-}
-#endif
-
-void QGridLayoutEngine::maybeExpandGrid(int row, int column, Qt::Orientation orientation)
-{
- invalidate(); // ### move out of here?
-
- if (orientation == Qt::Horizontal)
- qSwap(row, column);
-
- if (row < rowCount() && column < columnCount())
- return;
-
- int oldGridRowCount = internalGridRowCount();
- int oldGridColumnCount = internalGridColumnCount();
-
- q_infos[Ver].count = qMax(row + 1, rowCount());
- q_infos[Hor].count = qMax(column + 1, columnCount());
-
- int newGridRowCount = internalGridRowCount();
- int newGridColumnCount = internalGridColumnCount();
-
- int newGridSize = newGridRowCount * newGridColumnCount;
- if (newGridSize != q_grid.count()) {
- q_grid.resize(newGridSize);
-
- if (newGridColumnCount != oldGridColumnCount) {
- for (int i = oldGridRowCount - 1; i >= 1; --i) {
- for (int j = oldGridColumnCount - 1; j >= 0; --j) {
- int oldIndex = (i * oldGridColumnCount) + j;
- int newIndex = (i * newGridColumnCount) + j;
-
- Q_ASSERT(newIndex > oldIndex);
- q_grid[newIndex] = q_grid[oldIndex];
- q_grid[oldIndex] = 0;
- }
- }
- }
- }
-}
-
-void QGridLayoutEngine::regenerateGrid()
-{
- q_grid.fill(0);
-
- for (int i = q_items.count() - 1; i >= 0; --i) {
- QGridLayoutItem *item = q_items.at(i);
-
- for (int j = item->firstRow(); j <= item->lastRow(); ++j) {
- for (int k = item->firstColumn(); k <= item->lastColumn(); ++k) {
- setItemAt(j, k, item);
- }
- }
- }
-}
-
-void QGridLayoutEngine::setItemAt(int row, int column, QGridLayoutItem *item)
-{
- Q_ASSERT(row >= 0 && row < rowCount());
- Q_ASSERT(column >= 0 && column < columnCount());
- q_grid[(row * internalGridColumnCount()) + column] = item;
-}
-
-void QGridLayoutEngine::insertOrRemoveRows(int row, int delta, Qt::Orientation orientation)
-{
- int oldRowCount = rowCount(orientation);
- Q_ASSERT(uint(row) <= uint(oldRowCount));
-
- invalidate();
-
- // appending rows (or columns) is easy
- if (row == oldRowCount && delta > 0) {
- maybeExpandGrid(oldRowCount + delta - 1, -1, orientation);
- return;
- }
-
- q_infos[orientation == Qt::Vertical].insertOrRemoveRows(row, delta);
-
- for (int i = q_items.count() - 1; i >= 0; --i)
- q_items.at(i)->insertOrRemoveRows(row, delta, orientation);
-
- q_grid.resize(internalGridRowCount() * internalGridColumnCount());
- regenerateGrid();
-}
-
-void QGridLayoutEngine::fillRowData(QGridLayoutRowData *rowData, const QLayoutStyleInfo &styleInfo,
- qreal *colPositions, qreal *colSizes,
- Qt::Orientation orientation) const
-{
- const int ButtonMask = QSizePolicy::ButtonBox | QSizePolicy::PushButton;
- const QGridLayoutRowInfo &rowInfo = q_infos[orientation == Qt::Vertical];
- const QGridLayoutRowInfo &columnInfo = q_infos[orientation == Qt::Horizontal];
- LayoutSide top = (orientation == Qt::Vertical) ? Top : Left;
- LayoutSide bottom = (orientation == Qt::Vertical) ? Bottom : Right;
-
- QStyle *style = styleInfo.style();
- QStyleOption option;
- option.initFrom(styleInfo.widget());
-
- const QLayoutParameter<qreal> &defaultSpacing = q_defaultSpacings[orientation == Qt::Vertical];
- qreal innerSpacing = 0.0;
- if (style)
- innerSpacing = (qreal)style->pixelMetric(orientation == Qt::Vertical ? QStyle::PM_LayoutVerticalSpacing
- : QStyle::PM_LayoutHorizontalSpacing,
- &option, styleInfo.widget());
- if (innerSpacing >= 0.0)
- defaultSpacing.setCachedValue(innerSpacing);
-
- for (int row = 0; row < rowInfo.count; ++row) {
- bool rowIsEmpty = true;
- bool rowIsIdenticalToPrevious = (row > 0);
-
- for (int column = 0; column < columnInfo.count; ++column) {
- QGridLayoutItem *item = itemAt(row, column, orientation);
-
- if (rowIsIdenticalToPrevious && item != itemAt(row - 1, column, orientation))
- rowIsIdenticalToPrevious = false;
-
- if (item)
- rowIsEmpty = false;
- }
-
- if ((rowIsEmpty || rowIsIdenticalToPrevious)
- && rowInfo.spacings.value(row).isDefault()
- && rowInfo.stretches.value(row).isDefault()
- && rowInfo.boxes.value(row) == QGridLayoutBox())
- rowData->ignore.setBit(row, true);
-
- if (rowInfo.spacings.value(row).isUser()) {
- rowData->spacings[row] = rowInfo.spacings.at(row).value();
- } else if (!defaultSpacing.isDefault()) {
- rowData->spacings[row] = defaultSpacing.value();
- }
-
- rowData->stretches[row] = rowInfo.stretches.value(row).value();
- }
-
- struct RowAdHocData {
- int q_row;
- unsigned int q_hasButtons : 8;
- unsigned int q_hasNonButtons : 8;
-
- inline RowAdHocData() : q_row(-1), q_hasButtons(false), q_hasNonButtons(false) {}
- inline void init(int row) {
- this->q_row = row;
- q_hasButtons = false;
- q_hasNonButtons = false;
- }
- inline bool hasOnlyButtons() const { return q_hasButtons && !q_hasNonButtons; }
- inline bool hasOnlyNonButtons() const { return q_hasNonButtons && !q_hasButtons; }
- };
- RowAdHocData lastRowAdHocData;
- RowAdHocData nextToLastRowAdHocData;
- RowAdHocData nextToNextToLastRowAdHocData;
-
- rowData->hasIgnoreFlag = false;
- for (int row = 0; row < rowInfo.count; ++row) {
- if (rowData->ignore.testBit(row))
- continue;
-
- QGridLayoutBox &rowBox = rowData->boxes[row];
- if (option.state & QStyle::State_Window) {
- nextToNextToLastRowAdHocData = nextToLastRowAdHocData;
- nextToLastRowAdHocData = lastRowAdHocData;
- lastRowAdHocData.init(row);
- }
-
- bool userRowStretch = rowInfo.stretches.value(row).isUser();
- int &rowStretch = rowData->stretches[row];
-
- bool hasIgnoreFlag = true;
- for (int column = 0; column < columnInfo.count; ++column) {
- QGridLayoutItem *item = itemAt(row, column, orientation);
- if (item) {
- int itemRow = item->firstRow(orientation);
- int itemColumn = item->firstColumn(orientation);
-
- if (itemRow == row && itemColumn == column) {
- int itemStretch = item->stretchFactor(orientation);
- if (!(item->sizePolicy(orientation) & QSizePolicy::IgnoreFlag))
- hasIgnoreFlag = false;
- int itemRowSpan = item->rowSpan(orientation);
-
- int effectiveRowSpan = 1;
- for (int i = 1; i < itemRowSpan; ++i) {
- if (!rowData->ignore.testBit(i))
- ++effectiveRowSpan;
- }
-
- QGridLayoutBox *box;
- if (effectiveRowSpan == 1) {
- box = &rowBox;
- if (!userRowStretch && itemStretch != 0)
- rowStretch = qMax(rowStretch, itemStretch);
- } else {
- QGridLayoutMultiCellData &multiCell =
- rowData->multiCellMap[qMakePair(row, effectiveRowSpan)];
- box = &multiCell.q_box;
- multiCell.q_stretch = itemStretch;
- }
- // Items with constraints need to be passed the constraint
- if (colSizes && colPositions && item->hasDynamicConstraint() && orientation == item->dynamicConstraintOrientation()) {
- /* Get the width of the item by summing up the widths of the columns that it spans.
- * We need to have already calculated the widths of the columns by calling
- * q_columns->calculateGeometries() before hand and passing the value in the colSizes
- * and colPositions parameters.
- * The variable name is still colSizes even when it actually has the row sizes
- */
- qreal length = colSizes[item->lastColumn(orientation)];
- if (item->columnSpan(orientation) != 1)
- length += colPositions[item->lastColumn(orientation)] - colPositions[item->firstColumn(orientation)];
- box->combine(item->box(orientation, length));
- } else {
- box->combine(item->box(orientation));
- }
-
- if (effectiveRowSpan == 1) {
- QSizePolicy::ControlTypes controls = item->controlTypes(top);
- if (controls & ButtonMask)
- lastRowAdHocData.q_hasButtons = true;
- if (controls & ~ButtonMask)
- lastRowAdHocData.q_hasNonButtons = true;
- }
- }
- }
- }
- if (row < rowInfo.boxes.count()) {
- QGridLayoutBox rowBoxInfo = rowInfo.boxes.at(row);
- rowBoxInfo.normalize();
- rowBox.q_minimumSize = qMax(rowBox.q_minimumSize, rowBoxInfo.q_minimumSize);
- rowBox.q_maximumSize = qMax(rowBox.q_minimumSize,
- (rowBoxInfo.q_maximumSize != FLT_MAX ?
- rowBoxInfo.q_maximumSize : rowBox.q_maximumSize));
- rowBox.q_preferredSize = qBound(rowBox.q_minimumSize,
- qMax(rowBox.q_preferredSize, rowBoxInfo.q_preferredSize),
- rowBox.q_maximumSize);
- }
- if (hasIgnoreFlag)
- rowData->hasIgnoreFlag = true;
- }
-
- /*
- Heuristic: Detect button boxes that don't use QSizePolicy::ButtonBox.
- This is somewhat ad hoc but it usually does the trick.
- */
- bool lastRowIsButtonBox = (lastRowAdHocData.hasOnlyButtons()
- && nextToLastRowAdHocData.hasOnlyNonButtons());
- bool lastTwoRowsIsButtonBox = (lastRowAdHocData.hasOnlyButtons()
- && nextToLastRowAdHocData.hasOnlyButtons()
- && nextToNextToLastRowAdHocData.hasOnlyNonButtons()
- && orientation == Qt::Vertical);
-
- if (defaultSpacing.isDefault()) {
- int prevRow = -1;
- for (int row = 0; row < rowInfo.count; ++row) {
- if (rowData->ignore.testBit(row))
- continue;
-
- if (prevRow != -1 && !rowInfo.spacings.value(prevRow).isUser()) {
- qreal &rowSpacing = rowData->spacings[prevRow];
- for (int column = 0; column < columnInfo.count; ++column) {
- QGridLayoutItem *item1 = itemAt(prevRow, column, orientation);
- QGridLayoutItem *item2 = itemAt(row, column, orientation);
-
- if (item1 && item2 && item1 != item2) {
- QSizePolicy::ControlTypes controls1 = item1->controlTypes(bottom);
- QSizePolicy::ControlTypes controls2 = item2->controlTypes(top);
-
- if (controls2 & QSizePolicy::PushButton) {
- if ((row == nextToLastRowAdHocData.q_row && lastTwoRowsIsButtonBox)
- || (row == lastRowAdHocData.q_row && lastRowIsButtonBox)) {
- controls2 &= ~QSizePolicy::PushButton;
- controls2 |= QSizePolicy::ButtonBox;
- }
- }
-
- qreal spacing = style->combinedLayoutSpacing(controls1, controls2,
- orientation, &option,
- styleInfo.widget());
- if (orientation == Qt::Horizontal) {
- qreal width1 = rowData->boxes.at(prevRow).q_minimumSize;
- qreal width2 = rowData->boxes.at(row).q_minimumSize;
- QRectF rect1 = item1->geometryWithin(0.0, 0.0, width1, FLT_MAX, -1.0);
- QRectF rect2 = item2->geometryWithin(0.0, 0.0, width2, FLT_MAX, -1.0);
- spacing -= (width1 - (rect1.x() + rect1.width())) + rect2.x();
- } else {
- const QGridLayoutBox &box1 = rowData->boxes.at(prevRow);
- const QGridLayoutBox &box2 = rowData->boxes.at(row);
- qreal height1 = box1.q_minimumSize;
- qreal height2 = box2.q_minimumSize;
- qreal rowDescent1 = fixedDescent(box1.q_minimumDescent,
- box1.q_minimumAscent, height1);
- qreal rowDescent2 = fixedDescent(box2.q_minimumDescent,
- box2.q_minimumAscent, height2);
- QRectF rect1 = item1->geometryWithin(0.0, 0.0, FLT_MAX, height1,
- rowDescent1);
- QRectF rect2 = item2->geometryWithin(0.0, 0.0, FLT_MAX, height2,
- rowDescent2);
- spacing -= (height1 - (rect1.y() + rect1.height())) + rect2.y();
- }
- rowSpacing = qMax(spacing, rowSpacing);
- }
- }
- }
- prevRow = row;
- }
- } else if (lastRowIsButtonBox || lastTwoRowsIsButtonBox) {
- /*
- Even for styles that define a uniform spacing, we cheat a
- bit and use the window margin as the spacing. This
- significantly improves the look of dialogs.
- */
- int prevRow = lastRowIsButtonBox ? nextToLastRowAdHocData.q_row
- : nextToNextToLastRowAdHocData.q_row;
- if (!defaultSpacing.isUser() && !rowInfo.spacings.value(prevRow).isUser()) {
- qreal windowMargin = style->pixelMetric(orientation == Qt::Vertical
- ? QStyle::PM_LayoutBottomMargin
- : QStyle::PM_LayoutRightMargin,
- &option, styleInfo.widget());
-
- qreal &rowSpacing = rowData->spacings[prevRow];
- rowSpacing = qMax(windowMargin, rowSpacing);
- }
- }
-}
-
-void QGridLayoutEngine::ensureEffectiveFirstAndLastRows() const
-{
- if (q_cachedEffectiveFirstRows[Hor] == -1 && !q_items.isEmpty()) {
- int rowCount = this->rowCount();
- int columnCount = this->columnCount();
-
- q_cachedEffectiveFirstRows[Ver] = rowCount;
- q_cachedEffectiveFirstRows[Hor] = columnCount;
- q_cachedEffectiveLastRows[Ver] = -1;
- q_cachedEffectiveLastRows[Hor] = -1;
-
- for (int i = q_items.count() - 1; i >= 0; --i) {
- const QGridLayoutItem *item = q_items.at(i);
-
- for (int j = 0; j < NOrientations; ++j) {
- Qt::Orientation orientation = (j == Hor) ? Qt::Horizontal : Qt::Vertical;
- if (item->firstRow(orientation) < q_cachedEffectiveFirstRows[j])
- q_cachedEffectiveFirstRows[j] = item->firstRow(orientation);
- if (item->lastRow(orientation) > q_cachedEffectiveLastRows[j])
- q_cachedEffectiveLastRows[j] = item->lastRow(orientation);
- }
- }
- }
-}
-
-void QGridLayoutEngine::ensureColumnAndRowData(QGridLayoutRowData *rowData, QGridLayoutBox *totalBox,
- const QLayoutStyleInfo &styleInfo,
- qreal *colPositions, qreal *colSizes,
- Qt::Orientation orientation) const
-{
- rowData->reset(rowCount(orientation));
- fillRowData(rowData, styleInfo, colPositions, colSizes, orientation);
- const QGridLayoutRowInfo &rowInfo = q_infos[orientation == Qt::Vertical];
- rowData->distributeMultiCells(rowInfo);
- *totalBox = rowData->totalBox(0, rowCount(orientation));
- //We have items whose width depends on their height
-}
-
-/**
- returns false if the layout has contradicting constraints (i.e. some items with a horizontal
- constraint and other items with a vertical constraint)
- */
-bool QGridLayoutEngine::ensureDynamicConstraint() const
-{
- if (q_cachedConstraintOrientation == UnknownConstraint) {
- for (int i = q_items.count() - 1; i >= 0; --i) {
- QGridLayoutItem *item = q_items.at(i);
- if (item->hasDynamicConstraint()) {
- Qt::Orientation itemConstraintOrientation = item->dynamicConstraintOrientation();
- if (q_cachedConstraintOrientation == UnknownConstraint) {
- q_cachedConstraintOrientation = itemConstraintOrientation;
- } else if (q_cachedConstraintOrientation != itemConstraintOrientation) {
- q_cachedConstraintOrientation = UnfeasibleConstraint;
- qWarning("QGridLayoutEngine: Unfeasible, cannot mix horizontal and"
- " vertical constraint in the same layout");
- return false;
- }
- }
- }
- if (q_cachedConstraintOrientation == UnknownConstraint)
- q_cachedConstraintOrientation = NoConstraint;
- }
- return true;
-}
-
-bool QGridLayoutEngine::hasDynamicConstraint() const
-{
- if (!ensureDynamicConstraint())
- return false;
- return q_cachedConstraintOrientation != NoConstraint;
-}
-
-/*
- * return value is only valid if hasConstraint() returns true
- */
-Qt::Orientation QGridLayoutEngine::constraintOrientation() const
-{
- (void)ensureDynamicConstraint();
- return (Qt::Orientation)q_cachedConstraintOrientation;
-}
-
-void QGridLayoutEngine::ensureGeometries(const QLayoutStyleInfo &styleInfo,
- const QSizeF &size) const
-{
- if (q_cachedDataForStyleInfo == styleInfo && q_cachedSize == size)
- return;
-
- q_cachedDataForStyleInfo = styleInfo;
- q_cachedSize = size;
-
- q_xx.resize(columnCount());
- q_widths.resize(columnCount());
- q_yy.resize(rowCount());
- q_heights.resize(rowCount());
- q_descents.resize(rowCount());
-
- if (constraintOrientation() != Qt::Horizontal) {
- //We might have items whose width depends on their height
- ensureColumnAndRowData(&q_columnData, &q_totalBoxes[Hor], styleInfo, NULL, NULL, Qt::Horizontal);
- //Calculate column widths and positions, and put results in q_xx.data() and q_widths.data() so that we can use this information as
- //constraints to find the row heights
- q_columnData.calculateGeometries(0, columnCount(), size.width(), q_xx.data(), q_widths.data(),
- 0, q_totalBoxes[Hor], q_infos[Hor] );
- ensureColumnAndRowData(&q_rowData, &q_totalBoxes[Ver], styleInfo, q_xx.data(), q_widths.data(), Qt::Vertical);
- //Calculate row heights and positions, and put results in q_yy.data() and q_heights.data()
- q_rowData.calculateGeometries(0, rowCount(), size.height(), q_yy.data(), q_heights.data(),
- q_descents.data(), q_totalBoxes[Ver], q_infos[Ver]);
- } else {
- //We have items whose height depends on their width
- ensureColumnAndRowData(&q_rowData, &q_totalBoxes[Ver], styleInfo, NULL, NULL, Qt::Vertical);
- //Calculate row heights and positions, and put results in q_yy.data() and q_heights.data() so that we can use this information as
- //constraints to find the column widths
- q_rowData.calculateGeometries(0, rowCount(), size.height(), q_yy.data(), q_heights.data(),
- q_descents.data(), q_totalBoxes[Ver], q_infos[Ver]);
- ensureColumnAndRowData(&q_columnData, &q_totalBoxes[Hor], styleInfo, q_yy.data(), q_heights.data(), Qt::Horizontal);
- //Calculate row heights and positions, and put results in q_yy.data() and q_heights.data()
- q_columnData.calculateGeometries(0, columnCount(), size.width(), q_xx.data(), q_widths.data(),
- 0, q_totalBoxes[Hor], q_infos[Hor]);
- }
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_GRAPHICSVIEW
diff --git a/src/gui/graphicsview/qgridlayoutengine_p.h b/src/gui/graphicsview/qgridlayoutengine_p.h
deleted file mode 100644
index c5b35f59e8..0000000000
--- a/src/gui/graphicsview/qgridlayoutengine_p.h
+++ /dev/null
@@ -1,458 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRIDLAYOUTENGINE_P_H
-#define QGRIDLAYOUTENGINE_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the graphics view layout classes. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qalgorithms.h"
-#include "qbitarray.h"
-#include "qlist.h"
-#include "qmap.h"
-#include "qpair.h"
-#include "qvector.h"
-#include "qgraphicslayout_p.h"
-#include <float.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGraphicsLayoutItem;
-class QStyle;
-class QWidget;
-
-// ### deal with Descent in a similar way
-enum {
- MinimumSize = Qt::MinimumSize,
- PreferredSize = Qt::PreferredSize,
- MaximumSize = Qt::MaximumSize,
- NSizes
-};
-
-// do not reorder
-enum {
- Hor,
- Ver,
- NOrientations
-};
-
-// do not reorder
-enum LayoutSide {
- Left,
- Top,
- Right,
- Bottom
-};
-
-enum {
- NoConstraint,
- HorizontalConstraint, // Width depends on the height
- VerticalConstraint, // Height depends on the width
- UnknownConstraint, // need to update cache
- UnfeasibleConstraint // not feasible, it be has some items with Vertical and others with Horizontal constraints
-};
-
-template <typename T>
-class QLayoutParameter
-{
-public:
- enum State { Default, User, Cached };
-
- inline QLayoutParameter() : q_value(T()), q_state(Default) {}
- inline QLayoutParameter(T value, State state = Default) : q_value(value), q_state(state) {}
-
- inline void setUserValue(T value) {
- q_value = value;
- q_state = User;
- }
- inline void setCachedValue(T value) const {
- if (q_state != User) {
- q_value = value;
- q_state = Cached;
- }
- }
- inline T value() const { return q_value; }
- inline T value(T defaultValue) const { return isUser() ? q_value : defaultValue; }
- inline bool isDefault() const { return q_state == Default; }
- inline bool isUser() const { return q_state == User; }
- inline bool isCached() const { return q_state == Cached; }
-
-private:
- mutable T q_value;
- mutable State q_state;
-};
-
-class QStretchParameter : public QLayoutParameter<int>
-{
-public:
- QStretchParameter() : QLayoutParameter<int>(-1) {}
-
-};
-
-class QGridLayoutBox
-{
-public:
- inline QGridLayoutBox()
- : q_minimumSize(0), q_preferredSize(0), q_maximumSize(FLT_MAX),
- q_minimumDescent(-1), q_minimumAscent(-1) {}
-
- void add(const QGridLayoutBox &other, int stretch, qreal spacing);
- void combine(const QGridLayoutBox &other);
- void normalize();
-
-#ifdef QT_DEBUG
- void dump(int indent = 0) const;
-#endif
- // This code could use the union-struct-array trick, but a compiler
- // bug prevents this from working.
- qreal q_minimumSize;
- qreal q_preferredSize;
- qreal q_maximumSize;
- qreal q_minimumDescent;
- qreal q_minimumAscent;
- inline qreal &q_sizes(int which)
- {
- qreal *t;
- switch (which) {
- case Qt::MinimumSize:
- t = &q_minimumSize;
- break;
- case Qt::PreferredSize:
- t = &q_preferredSize;
- break;
- case Qt::MaximumSize:
- t = &q_maximumSize;
- break;
- case Qt::MinimumDescent:
- t = &q_minimumDescent;
- break;
- case (Qt::MinimumDescent + 1):
- t = &q_minimumAscent;
- break;
- default:
- t = 0;
- break;
- }
- return *t;
- }
- inline const qreal &q_sizes(int which) const
- {
- const qreal *t;
- switch (which) {
- case Qt::MinimumSize:
- t = &q_minimumSize;
- break;
- case Qt::PreferredSize:
- t = &q_preferredSize;
- break;
- case Qt::MaximumSize:
- t = &q_maximumSize;
- break;
- case Qt::MinimumDescent:
- t = &q_minimumDescent;
- break;
- case (Qt::MinimumDescent + 1):
- t = &q_minimumAscent;
- break;
- default:
- t = 0;
- break;
- }
- return *t;
- }
-};
-
-bool operator==(const QGridLayoutBox &box1, const QGridLayoutBox &box2);
-inline bool operator!=(const QGridLayoutBox &box1, const QGridLayoutBox &box2)
- { return !operator==(box1, box2); }
-
-class QGridLayoutMultiCellData
-{
-public:
- inline QGridLayoutMultiCellData() : q_stretch(-1) {}
-
- QGridLayoutBox q_box;
- int q_stretch;
-};
-
-typedef QMap<QPair<int, int>, QGridLayoutMultiCellData> MultiCellMap;
-
-class QGridLayoutRowInfo;
-
-class QGridLayoutRowData
-{
-public:
- void reset(int count);
- void distributeMultiCells(const QGridLayoutRowInfo &rowInfo);
- void calculateGeometries(int start, int end, qreal targetSize, qreal *positions, qreal *sizes,
- qreal *descents, const QGridLayoutBox &totalBox,
- const QGridLayoutRowInfo &rowInfo);
- QGridLayoutBox totalBox(int start, int end) const;
- void stealBox(int start, int end, int which, qreal *positions, qreal *sizes);
-
-#ifdef QT_DEBUG
- void dump(int indent = 0) const;
-#endif
-
- QBitArray ignore; // ### rename q_
- QVector<QGridLayoutBox> boxes;
- MultiCellMap multiCellMap;
- QVector<int> stretches;
- QVector<qreal> spacings;
- bool hasIgnoreFlag;
-};
-
-class QGridLayoutEngine;
-
-class QGridLayoutItem
-{
-public:
- QGridLayoutItem(QGridLayoutEngine *engine, QGraphicsLayoutItem *layoutItem, int row, int column,
- int rowSpan = 1, int columnSpan = 1, Qt::Alignment alignment = 0,
- int itemAtIndex = -1);
-
- inline int firstRow() const { return q_firstRows[Ver]; }
- inline int firstColumn() const { return q_firstRows[Hor]; }
- inline int rowSpan() const { return q_rowSpans[Ver]; }
- inline int columnSpan() const { return q_rowSpans[Hor]; }
- inline int lastRow() const { return firstRow() + rowSpan() - 1; }
- inline int lastColumn() const { return firstColumn() + columnSpan() - 1; }
-
- int firstRow(Qt::Orientation orientation) const;
- int firstColumn(Qt::Orientation orientation) const;
- int lastRow(Qt::Orientation orientation) const;
- int lastColumn(Qt::Orientation orientation) const;
- int rowSpan(Qt::Orientation orientation) const;
- int columnSpan(Qt::Orientation orientation) const;
- void setFirstRow(int row, Qt::Orientation orientation = Qt::Vertical);
- void setRowSpan(int rowSpan, Qt::Orientation orientation = Qt::Vertical);
-
- int stretchFactor(Qt::Orientation orientation) const;
- void setStretchFactor(int stretch, Qt::Orientation orientation);
-
- inline Qt::Alignment alignment() const { return q_alignment; }
- inline void setAlignment(Qt::Alignment alignment) { q_alignment = alignment; }
-
- QSizePolicy::Policy sizePolicy(Qt::Orientation orientation) const;
-
- bool hasDynamicConstraint() const;
- Qt::Orientation dynamicConstraintOrientation() const;
-
- QSizePolicy::ControlTypes controlTypes(LayoutSide side) const;
- QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const;
- QGridLayoutBox box(Qt::Orientation orientation, qreal constraint = -1.0) const;
- QRectF geometryWithin(qreal x, qreal y, qreal width, qreal height, qreal rowDescent) const;
-
- QGraphicsLayoutItem *layoutItem() const { return q_layoutItem; }
-
- void setGeometry(const QRectF &rect);
- void transpose();
- void insertOrRemoveRows(int row, int delta, Qt::Orientation orientation = Qt::Vertical);
- QSizeF effectiveMaxSize(const QSizeF &constraint) const;
-
-#ifdef QT_DEBUG
- void dump(int indent = 0) const;
-#endif
-
-private:
- QGridLayoutEngine *q_engine; // ### needed?
- QGraphicsLayoutItem *q_layoutItem;
- int q_firstRows[NOrientations];
- int q_rowSpans[NOrientations];
- int q_stretches[NOrientations];
- Qt::Alignment q_alignment;
-};
-
-class QGridLayoutRowInfo
-{
-public:
- inline QGridLayoutRowInfo() : count(0) {}
-
- void insertOrRemoveRows(int row, int delta);
-
-#ifdef QT_DEBUG
- void dump(int indent = 0) const;
-#endif
-
- int count;
- QVector<QStretchParameter> stretches;
- QVector<QLayoutParameter<qreal> > spacings;
- QVector<Qt::Alignment> alignments;
- QVector<QGridLayoutBox> boxes;
-};
-
-class QGridLayoutEngine
-{
-public:
- QGridLayoutEngine();
- inline ~QGridLayoutEngine() { qDeleteAll(q_items); }
-
- int rowCount(Qt::Orientation orientation) const;
- int columnCount(Qt::Orientation orientation) const;
- inline int rowCount() const { return q_infos[Ver].count; }
- inline int columnCount() const { return q_infos[Hor].count; }
- // returns the number of items inserted, which may be less than (rowCount * columnCount)
- int itemCount() const;
- QGridLayoutItem *itemAt(int index) const;
- int indexOf(QGraphicsLayoutItem *item) const;
-
- int effectiveFirstRow(Qt::Orientation orientation = Qt::Vertical) const;
- int effectiveLastRow(Qt::Orientation orientation = Qt::Vertical) const;
-
- void setSpacing(qreal spacing, Qt::Orientations orientations);
- qreal spacing(const QLayoutStyleInfo &styleInfo, Qt::Orientation orientation) const;
- // ### setSpacingAfterRow(), spacingAfterRow()
- void setRowSpacing(int row, qreal spacing, Qt::Orientation orientation = Qt::Vertical);
- qreal rowSpacing(int row, Qt::Orientation orientation = Qt::Vertical) const;
-
- void setRowStretchFactor(int row, int stretch, Qt::Orientation orientation = Qt::Vertical);
- int rowStretchFactor(int row, Qt::Orientation orientation = Qt::Vertical) const;
-
- void setStretchFactor(QGraphicsLayoutItem *layoutItem, int stretch,
- Qt::Orientation orientation);
- int stretchFactor(QGraphicsLayoutItem *layoutItem, Qt::Orientation orientation) const;
-
- void setRowSizeHint(Qt::SizeHint which, int row, qreal size,
- Qt::Orientation orientation = Qt::Vertical);
- qreal rowSizeHint(Qt::SizeHint which, int row,
- Qt::Orientation orientation = Qt::Vertical) const;
-
- void setRowAlignment(int row, Qt::Alignment alignment, Qt::Orientation orientation);
- Qt::Alignment rowAlignment(int row, Qt::Orientation orientation) const;
-
- void setAlignment(QGraphicsLayoutItem *layoutItem, Qt::Alignment alignment);
- Qt::Alignment alignment(QGraphicsLayoutItem *layoutItem) const;
- Qt::Alignment effectiveAlignment(const QGridLayoutItem *layoutItem) const;
-
-
- void insertItem(QGridLayoutItem *item, int index);
- void addItem(QGridLayoutItem *item);
- void removeItem(QGridLayoutItem *item);
- QGridLayoutItem *findLayoutItem(QGraphicsLayoutItem *layoutItem) const;
- QGridLayoutItem *itemAt(int row, int column, Qt::Orientation orientation = Qt::Vertical) const;
- inline void insertRow(int row, Qt::Orientation orientation = Qt::Vertical)
- { insertOrRemoveRows(row, +1, orientation); }
- inline void removeRows(int row, int count, Qt::Orientation orientation)
- { insertOrRemoveRows(row, -count, orientation); }
-
- void invalidate();
- void setGeometries(const QLayoutStyleInfo &styleInfo, const QRectF &contentsGeometry);
- QRectF cellRect(const QLayoutStyleInfo &styleInfo, const QRectF &contentsGeometry, int row,
- int column, int rowSpan, int columnSpan) const;
- QSizeF sizeHint(const QLayoutStyleInfo &styleInfo, Qt::SizeHint which,
- const QSizeF &constraint) const;
-
- // heightForWidth / widthForHeight support
- QSizeF dynamicallyConstrainedSizeHint(Qt::SizeHint which, const QSizeF &constraint) const;
- bool ensureDynamicConstraint() const;
- bool hasDynamicConstraint() const;
- Qt::Orientation constraintOrientation() const;
-
-
- QSizePolicy::ControlTypes controlTypes(LayoutSide side) const;
- void transpose();
- void setVisualDirection(Qt::LayoutDirection direction);
- Qt::LayoutDirection visualDirection() const;
-#ifdef QT_DEBUG
- void dump(int indent = 0) const;
-#endif
-
-private:
- static int grossRoundUp(int n) { return ((n + 2) | 0x3) - 2; }
-
- void maybeExpandGrid(int row, int column, Qt::Orientation orientation = Qt::Vertical);
- void regenerateGrid();
- inline int internalGridRowCount() const { return grossRoundUp(rowCount()); }
- inline int internalGridColumnCount() const { return grossRoundUp(columnCount()); }
- void setItemAt(int row, int column, QGridLayoutItem *item);
- void insertOrRemoveRows(int row, int delta, Qt::Orientation orientation = Qt::Vertical);
- void fillRowData(QGridLayoutRowData *rowData, const QLayoutStyleInfo &styleInfo,
- qreal *colPositions, qreal *colSizes,
- Qt::Orientation orientation = Qt::Vertical) const;
- void ensureEffectiveFirstAndLastRows() const;
- void ensureColumnAndRowData(QGridLayoutRowData *rowData, QGridLayoutBox *totalBox,
- const QLayoutStyleInfo &styleInfo,
- qreal *colPositions, qreal *colSizes,
- Qt::Orientation orientation) const;
-
- void ensureGeometries(const QLayoutStyleInfo &styleInfo, const QSizeF &size) const;
-
- // User input
- QVector<QGridLayoutItem *> q_grid;
- QList<QGridLayoutItem *> q_items;
- QLayoutParameter<qreal> q_defaultSpacings[NOrientations];
- QGridLayoutRowInfo q_infos[NOrientations];
- Qt::LayoutDirection m_visualDirection;
-
- // Lazily computed from the above user input
- mutable int q_cachedEffectiveFirstRows[NOrientations];
- mutable int q_cachedEffectiveLastRows[NOrientations];
- mutable quint8 q_cachedConstraintOrientation : 3;
-
- // Layout item input
- mutable QLayoutStyleInfo q_cachedDataForStyleInfo;
- mutable QGridLayoutRowData q_columnData;
- mutable QGridLayoutRowData q_rowData;
- mutable QGridLayoutBox q_totalBoxes[NOrientations];
-
- // Output
- mutable QSizeF q_cachedSize;
- mutable QVector<qreal> q_xx;
- mutable QVector<qreal> q_yy;
- mutable QVector<qreal> q_widths;
- mutable QVector<qreal> q_heights;
- mutable QVector<qreal> q_descents;
-
- friend class QGridLayoutItem;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/graphicsview/qsimplex_p.cpp b/src/gui/graphicsview/qsimplex_p.cpp
deleted file mode 100644
index d2d9646b90..0000000000
--- a/src/gui/graphicsview/qsimplex_p.cpp
+++ /dev/null
@@ -1,673 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsimplex_p.h"
-
-#include <QtCore/qset.h>
-#include <QtCore/qdebug.h>
-
-#include <stdlib.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QSimplex
-
- The QSimplex class is a Linear Programming problem solver based on the two-phase
- simplex method.
-
- It takes a set of QSimplexConstraints as its restrictive constraints and an
- additional QSimplexConstraint as its objective function. Then methods to maximize
- and minimize the problem solution are provided.
-
- The two-phase simplex method is based on the following steps:
- First phase:
- 1.a) Modify the original, complex, and possibly not feasible problem, into a new,
- easy to solve problem.
- 1.b) Set as the objective of the new problem, a feasible solution for the original
- complex problem.
- 1.c) Run simplex to optimize the modified problem and check whether a solution for
- the original problem exists.
-
- Second phase:
- 2.a) Go back to the original problem with the feasibl (but not optimal) solution
- found in the first phase.
- 2.b) Set the original objective.
- 3.c) Run simplex to optimize the original problem towards its optimal solution.
-*/
-
-/*!
- \internal
-*/
-QSimplex::QSimplex() : objective(0), rows(0), columns(0), firstArtificial(0), matrix(0)
-{
-}
-
-/*!
- \internal
-*/
-QSimplex::~QSimplex()
-{
- clearDataStructures();
-}
-
-/*!
- \internal
-*/
-void QSimplex::clearDataStructures()
-{
- if (matrix == 0)
- return;
-
- // Matrix
- rows = 0;
- columns = 0;
- firstArtificial = 0;
- free(matrix);
- matrix = 0;
-
- // Constraints
- for (int i = 0; i < constraints.size(); ++i) {
- delete constraints[i]->helper.first;
- delete constraints[i]->artificial;
- delete constraints[i];
- }
- constraints.clear();
-
- // Other
- variables.clear();
- objective = 0;
-}
-
-/*!
- \internal
- Sets the new constraints in the simplex solver and returns whether the problem
- is feasible.
-
- This method sets the new constraints, normalizes them, creates the simplex matrix
- and runs the first simplex phase.
-*/
-bool QSimplex::setConstraints(const QList<QSimplexConstraint *> newConstraints)
-{
- ////////////////////////////
- // Reset to initial state //
- ////////////////////////////
- clearDataStructures();
-
- if (newConstraints.isEmpty())
- return true; // we are ok with no constraints
-
- // Make deep copy of constraints. We need this copy because we may change
- // them in the simplification method.
- for (int i = 0; i < newConstraints.size(); ++i) {
- QSimplexConstraint *c = new QSimplexConstraint;
- c->constant = newConstraints[i]->constant;
- c->ratio = newConstraints[i]->ratio;
- c->variables = newConstraints[i]->variables;
- constraints << c;
- }
-
- // Remove constraints of type Var == K and replace them for their value.
- if (!simplifyConstraints(&constraints)) {
- qWarning() << "QSimplex: No feasible solution!";
- clearDataStructures();
- return false;
- }
-
- ///////////////////////////////////////
- // Prepare variables and constraints //
- ///////////////////////////////////////
-
- // Set Variables direct mapping.
- // "variables" is a list that provides a stable, indexed list of all variables
- // used in this problem.
- QSet<QSimplexVariable *> variablesSet;
- for (int i = 0; i < constraints.size(); ++i)
- variablesSet += \
- QSet<QSimplexVariable *>::fromList(constraints[i]->variables.keys());
- variables = variablesSet.toList();
-
- // Set Variables reverse mapping
- // We also need to be able to find the index for a given variable, to do that
- // we store in each variable its index.
- for (int i = 0; i < variables.size(); ++i) {
- // The variable "0" goes at the column "1", etc...
- variables[i]->index = i + 1;
- }
-
- // Normalize Constraints
- // In this step, we prepare the constraints in two ways:
- // Firstly, we modify all constraints of type "LessOrEqual" or "MoreOrEqual"
- // by the adding slack or surplus variables and making them "Equal" constraints.
- // Secondly, we need every single constraint to have a direct, easy feasible
- // solution. Constraints that have slack variables are already easy to solve,
- // to all the others we add artificial variables.
- //
- // At the end we modify the constraints as follows:
- // - LessOrEqual: SLACK variable is added.
- // - Equal: ARTIFICIAL variable is added.
- // - More or Equal: ARTIFICIAL and SURPLUS variables are added.
- int variableIndex = variables.size();
- QList <QSimplexVariable *> artificialList;
-
- for (int i = 0; i < constraints.size(); ++i) {
- QSimplexVariable *slack;
- QSimplexVariable *surplus;
- QSimplexVariable *artificial;
-
- Q_ASSERT(constraints[i]->helper.first == 0);
- Q_ASSERT(constraints[i]->artificial == 0);
-
- switch(constraints[i]->ratio) {
- case QSimplexConstraint::LessOrEqual:
- slack = new QSimplexVariable;
- slack->index = ++variableIndex;
- constraints[i]->helper.first = slack;
- constraints[i]->helper.second = 1.0;
- break;
- case QSimplexConstraint::MoreOrEqual:
- surplus = new QSimplexVariable;
- surplus->index = ++variableIndex;
- constraints[i]->helper.first = surplus;
- constraints[i]->helper.second = -1.0;
- // fall through
- case QSimplexConstraint::Equal:
- artificial = new QSimplexVariable;
- constraints[i]->artificial = artificial;
- artificialList += constraints[i]->artificial;
- break;
- }
- }
-
- // All original, slack and surplus have already had its index set
- // at this point. We now set the index of the artificial variables
- // as to ensure they are at the end of the variable list and therefore
- // can be easily removed at the end of this method.
- firstArtificial = variableIndex + 1;
- for (int i = 0; i < artificialList.size(); ++i)
- artificialList[i]->index = ++variableIndex;
- artificialList.clear();
-
- /////////////////////////////
- // Fill the Simplex matrix //
- /////////////////////////////
-
- // One for each variable plus the Basic and BFS columns (first and last)
- columns = variableIndex + 2;
- // One for each constraint plus the objective function
- rows = constraints.size() + 1;
-
- matrix = (qreal *)malloc(sizeof(qreal) * columns * rows);
- if (!matrix) {
- qWarning() << "QSimplex: Unable to allocate memory!";
- return false;
- }
- for (int i = columns * rows - 1; i >= 0; --i)
- matrix[i] = 0.0;
-
- // Fill Matrix
- for (int i = 1; i <= constraints.size(); ++i) {
- QSimplexConstraint *c = constraints[i - 1];
-
- if (c->artificial) {
- // Will use artificial basic variable
- setValueAt(i, 0, c->artificial->index);
- setValueAt(i, c->artificial->index, 1.0);
-
- if (c->helper.second != 0.0) {
- // Surplus variable
- setValueAt(i, c->helper.first->index, c->helper.second);
- }
- } else {
- // Slack is used as the basic variable
- Q_ASSERT(c->helper.second == 1.0);
- setValueAt(i, 0, c->helper.first->index);
- setValueAt(i, c->helper.first->index, 1.0);
- }
-
- QHash<QSimplexVariable *, qreal>::const_iterator iter;
- for (iter = c->variables.constBegin();
- iter != c->variables.constEnd();
- ++iter) {
- setValueAt(i, iter.key()->index, iter.value());
- }
-
- setValueAt(i, columns - 1, c->constant);
- }
-
- // Set objective for the first-phase Simplex.
- // Z = -1 * sum_of_artificial_vars
- for (int j = firstArtificial; j < columns - 1; ++j)
- setValueAt(0, j, 1.0);
-
- // Maximize our objective (artificial vars go to zero)
- solveMaxHelper();
-
- // If there is a solution where the sum of all artificial
- // variables is zero, then all of them can be removed and yet
- // we will have a feasible (but not optimal) solution for the
- // original problem.
- // Otherwise, we clean up our structures and report there is
- // no feasible solution.
- if ((valueAt(0, columns - 1) != 0.0) && (qAbs(valueAt(0, columns - 1)) > 0.00001)) {
- qWarning() << "QSimplex: No feasible solution!";
- clearDataStructures();
- return false;
- }
-
- // Remove artificial variables. We already have a feasible
- // solution for the first problem, thus we don't need them
- // anymore.
- clearColumns(firstArtificial, columns - 2);
-
- return true;
-}
-
-/*!
- \internal
-
- Run simplex on the current matrix with the current objective.
-
- This is the iterative method. The matrix lines are combined
- as to modify the variable values towards the best solution possible.
- The method returns when the matrix is in the optimal state.
-*/
-void QSimplex::solveMaxHelper()
-{
- reducedRowEchelon();
- while (iterate()) ;
-}
-
-/*!
- \internal
-*/
-void QSimplex::setObjective(QSimplexConstraint *newObjective)
-{
- objective = newObjective;
-}
-
-/*!
- \internal
-*/
-void QSimplex::clearRow(int rowIndex)
-{
- qreal *item = matrix + rowIndex * columns;
- for (int i = 0; i < columns; ++i)
- item[i] = 0.0;
-}
-
-/*!
- \internal
-*/
-void QSimplex::clearColumns(int first, int last)
-{
- for (int i = 0; i < rows; ++i) {
- qreal *row = matrix + i * columns;
- for (int j = first; j <= last; ++j)
- row[j] = 0.0;
- }
-}
-
-/*!
- \internal
-*/
-void QSimplex::dumpMatrix()
-{
- qDebug("---- Simplex Matrix ----\n");
-
- QString str(QLatin1String(" "));
- for (int j = 0; j < columns; ++j)
- str += QString::fromAscii(" <%1 >").arg(j, 2);
- qDebug("%s", qPrintable(str));
- for (int i = 0; i < rows; ++i) {
- str = QString::fromAscii("Row %1:").arg(i, 2);
-
- qreal *row = matrix + i * columns;
- for (int j = 0; j < columns; ++j)
- str += QString::fromAscii("%1").arg(row[j], 7, 'f', 2);
- qDebug("%s", qPrintable(str));
- }
- qDebug("------------------------\n");
-}
-
-/*!
- \internal
-*/
-void QSimplex::combineRows(int toIndex, int fromIndex, qreal factor)
-{
- if (!factor)
- return;
-
- qreal *from = matrix + fromIndex * columns;
- qreal *to = matrix + toIndex * columns;
-
- for (int j = 1; j < columns; ++j) {
- qreal value = from[j];
-
- // skip to[j] = to[j] + factor*0.0
- if (value == 0.0)
- continue;
-
- to[j] += factor * value;
-
- // ### Avoid Numerical errors
- if (qAbs(to[j]) < 0.0000000001)
- to[j] = 0.0;
- }
-}
-
-/*!
- \internal
-*/
-int QSimplex::findPivotColumn()
-{
- qreal min = 0;
- int minIndex = -1;
-
- for (int j = 0; j < columns-1; ++j) {
- if (valueAt(0, j) < min) {
- min = valueAt(0, j);
- minIndex = j;
- }
- }
-
- return minIndex;
-}
-
-/*!
- \internal
-
- For a given pivot column, find the pivot row. That is, the row with the
- minimum associated "quotient" where:
-
- - quotient is the division of the value in the last column by the value
- in the pivot column.
- - rows with value less or equal to zero are ignored
- - if two rows have the same quotient, lines are chosen based on the
- highest variable index (value in the first column)
-
- The last condition avoids a bug where artificial variables would be
- left behind for the second-phase simplex, and with 'good'
- constraints would be removed before it, what would lead to incorrect
- results.
-*/
-int QSimplex::pivotRowForColumn(int column)
-{
- qreal min = qreal(999999999999.0); // ###
- int minIndex = -1;
-
- for (int i = 1; i < rows; ++i) {
- qreal divisor = valueAt(i, column);
- if (divisor <= 0)
- continue;
-
- qreal quotient = valueAt(i, columns - 1) / divisor;
- if (quotient < min) {
- min = quotient;
- minIndex = i;
- } else if ((quotient == min) && (valueAt(i, 0) > valueAt(minIndex, 0))) {
- minIndex = i;
- }
- }
-
- return minIndex;
-}
-
-/*!
- \internal
-*/
-void QSimplex::reducedRowEchelon()
-{
- for (int i = 1; i < rows; ++i) {
- int factorInObjectiveRow = valueAt(i, 0);
- combineRows(0, i, -1 * valueAt(0, factorInObjectiveRow));
- }
-}
-
-/*!
- \internal
-
- Does one iteration towards a better solution for the problem.
- See 'solveMaxHelper'.
-*/
-bool QSimplex::iterate()
-{
- // Find Pivot column
- int pivotColumn = findPivotColumn();
- if (pivotColumn == -1)
- return false;
-
- // Find Pivot row for column
- int pivotRow = pivotRowForColumn(pivotColumn);
- if (pivotRow == -1) {
- qWarning() << "QSimplex: Unbounded problem!";
- return false;
- }
-
- // Normalize Pivot Row
- qreal pivot = valueAt(pivotRow, pivotColumn);
- if (pivot != 1.0)
- combineRows(pivotRow, pivotRow, (1.0 - pivot) / pivot);
-
- // Update other rows
- for (int row=0; row < rows; ++row) {
- if (row == pivotRow)
- continue;
-
- combineRows(row, pivotRow, -1 * valueAt(row, pivotColumn));
- }
-
- // Update first column
- setValueAt(pivotRow, 0, pivotColumn);
-
- // dumpMatrix();
- // qDebug("------------ end of iteration --------------\n");
- return true;
-}
-
-/*!
- \internal
-
- Both solveMin and solveMax are interfaces to this method.
-
- The enum solverFactor admits 2 values: Minimum (-1) and Maximum (+1).
-
- This method sets the original objective and runs the second phase
- Simplex to obtain the optimal solution for the problem. As the internal
- simplex solver is only able to _maximize_ objectives, we handle the
- minimization case by inverting the original objective and then
- maximizing it.
-*/
-qreal QSimplex::solver(solverFactor factor)
-{
- // Remove old objective
- clearRow(0);
-
- // Set new objective in the first row of the simplex matrix
- qreal resultOffset = 0;
- QHash<QSimplexVariable *, qreal>::const_iterator iter;
- for (iter = objective->variables.constBegin();
- iter != objective->variables.constEnd();
- ++iter) {
-
- // Check if the variable was removed in the simplification process.
- // If so, we save its offset to the objective function and skip adding
- // it to the matrix.
- if (iter.key()->index == -1) {
- resultOffset += iter.value() * iter.key()->result;
- continue;
- }
-
- setValueAt(0, iter.key()->index, -1 * factor * iter.value());
- }
-
- solveMaxHelper();
- collectResults();
-
-#ifdef QT_DEBUG
- for (int i = 0; i < constraints.size(); ++i) {
- Q_ASSERT(constraints[i]->isSatisfied());
- }
-#endif
-
- // Return the value calculated by the simplex plus the value of the
- // fixed variables.
- return (factor * valueAt(0, columns - 1)) + resultOffset;
-}
-
-/*!
- \internal
- Minimize the original objective.
-*/
-qreal QSimplex::solveMin()
-{
- return solver(Minimum);
-}
-
-/*!
- \internal
- Maximize the original objective.
-*/
-qreal QSimplex::solveMax()
-{
- return solver(Maximum);
-}
-
-/*!
- \internal
-
- Reads results from the simplified matrix and saves them in the
- "result" member of each QSimplexVariable.
-*/
-void QSimplex::collectResults()
-{
- // All variables are zero unless overridden below.
-
- // ### Is this really needed? Is there any chance that an
- // important variable remains as non-basic at the end of simplex?
- for (int i = 0; i < variables.size(); ++i)
- variables[i]->result = 0;
-
- // Basic variables
- // Update the variable indicated in the first column with the value
- // in the last column.
- for (int i = 1; i < rows; ++i) {
- int index = valueAt(i, 0) - 1;
- if (index < variables.size())
- variables[index]->result = valueAt(i, columns - 1);
- }
-}
-
-/*!
- \internal
-
- Looks for single-valued variables and remove them from the constraints list.
-*/
-bool QSimplex::simplifyConstraints(QList<QSimplexConstraint *> *constraints)
-{
- QHash<QSimplexVariable *, qreal> results; // List of single-valued variables
- bool modified = true; // Any chance more optimization exists?
-
- while (modified) {
- modified = false;
-
- // For all constraints
- QList<QSimplexConstraint *>::iterator iter = constraints->begin();
- while (iter != constraints->end()) {
- QSimplexConstraint *c = *iter;
- if ((c->ratio == QSimplexConstraint::Equal) && (c->variables.count() == 1)) {
- // Check whether this is a constraint of type Var == K
- // If so, save its value to "results".
- QSimplexVariable *variable = c->variables.constBegin().key();
- qreal result = c->constant / c->variables.value(variable);
-
- results.insert(variable, result);
- variable->result = result;
- variable->index = -1;
- modified = true;
-
- }
-
- // Replace known values among their variables
- QHash<QSimplexVariable *, qreal>::const_iterator r;
- for (r = results.constBegin(); r != results.constEnd(); ++r) {
- if (c->variables.contains(r.key())) {
- c->constant -= r.value() * c->variables.take(r.key());
- modified = true;
- }
- }
-
- // Keep it normalized
- if (c->constant < 0)
- c->invert();
-
- if (c->variables.isEmpty()) {
- // If constraint became empty due to substitution, delete it.
- if (c->isSatisfied() == false)
- // We must ensure that the constraint soon to be deleted would not
- // make the problem unfeasible if left behind. If that's the case,
- // we return false so the simplex solver can properly report that.
- return false;
-
- delete c;
- iter = constraints->erase(iter);
- } else {
- ++iter;
- }
- }
- }
-
- return true;
-}
-
-void QSimplexConstraint::invert()
-{
- constant = -constant;
- ratio = Ratio(2 - ratio);
-
- QHash<QSimplexVariable *, qreal>::iterator iter;
- for (iter = variables.begin(); iter != variables.end(); ++iter) {
- iter.value() = -iter.value();
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/graphicsview/qsimplex_p.h b/src/gui/graphicsview/qsimplex_p.h
deleted file mode 100644
index e6eced311e..0000000000
--- a/src/gui/graphicsview/qsimplex_p.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/****************************************************************************
-**
-** 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 QSIMPLEX_P_H
-#define QSIMPLEX_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qhash.h>
-#include <QtCore/qpair.h>
-
-QT_BEGIN_NAMESPACE
-
-struct QSimplexVariable
-{
- QSimplexVariable() : result(0), index(0) {}
-
- qreal result;
- int index;
-};
-
-
-/*!
- \internal
-
- Representation of a LP constraint like:
-
- (c1 * X1) + (c2 * X2) + ... = K
- or <= K
- or >= K
-
- Where (ci, Xi) are the pairs in "variables" and K the real "constant".
-*/
-struct QSimplexConstraint
-{
- QSimplexConstraint() : constant(0), ratio(Equal), artificial(0) {}
-
- enum Ratio {
- LessOrEqual = 0,
- Equal,
- MoreOrEqual
- };
-
- QHash<QSimplexVariable *, qreal> variables;
- qreal constant;
- Ratio ratio;
-
- QPair<QSimplexVariable *, qreal> helper;
- QSimplexVariable * artificial;
-
- void invert();
-
- bool isSatisfied() {
- qreal leftHandSide(0);
-
- QHash<QSimplexVariable *, qreal>::const_iterator iter;
- for (iter = variables.constBegin(); iter != variables.constEnd(); ++iter) {
- leftHandSide += iter.value() * iter.key()->result;
- }
-
- Q_ASSERT(constant > 0 || qFuzzyCompare(1, 1 + constant));
-
- if ((leftHandSide == constant) || qAbs(leftHandSide - constant) < 0.0000001)
- return true;
-
- switch (ratio) {
- case LessOrEqual:
- return leftHandSide < constant;
- case MoreOrEqual:
- return leftHandSide > constant;
- default:
- return false;
- }
- }
-
-#ifdef QT_DEBUG
- QString toString() {
- QString result;
- result += QString::fromAscii("-- QSimplexConstraint %1 --").arg(quintptr(this), 0, 16);
-
- QHash<QSimplexVariable *, qreal>::const_iterator iter;
- for (iter = variables.constBegin(); iter != variables.constEnd(); ++iter) {
- result += QString::fromAscii(" %1 x %2").arg(iter.value()).arg(quintptr(iter.key()), 0, 16);
- }
-
- switch (ratio) {
- case LessOrEqual:
- result += QString::fromAscii(" (less) <= %1").arg(constant);
- break;
- case MoreOrEqual:
- result += QString::fromAscii(" (more) >= %1").arg(constant);
- break;
- default:
- result += QString::fromAscii(" (eqal) == %1").arg(constant);
- }
-
- return result;
- }
-#endif
-};
-
-class QSimplex
-{
-public:
- QSimplex();
- virtual ~QSimplex();
-
- qreal solveMin();
- qreal solveMax();
-
- bool setConstraints(const QList<QSimplexConstraint *> constraints);
- void setObjective(QSimplexConstraint *objective);
-
- void dumpMatrix();
-
-private:
- // Matrix handling
- qreal valueAt(int row, int column);
- void setValueAt(int row, int column, qreal value);
- void clearRow(int rowIndex);
- void clearColumns(int first, int last);
- void combineRows(int toIndex, int fromIndex, qreal factor);
-
- // Simplex
- bool simplifyConstraints(QList<QSimplexConstraint *> *constraints);
- int findPivotColumn();
- int pivotRowForColumn(int column);
- void reducedRowEchelon();
- bool iterate();
-
- // Helpers
- void clearDataStructures();
- void solveMaxHelper();
- enum solverFactor { Minimum = -1, Maximum = 1 };
- qreal solver(solverFactor factor);
- void collectResults();
-
- QList<QSimplexConstraint *> constraints;
- QList<QSimplexVariable *> variables;
- QSimplexConstraint *objective;
-
- int rows;
- int columns;
- int firstArtificial;
-
- qreal *matrix;
-};
-
-inline qreal QSimplex::valueAt(int rowIndex, int columnIndex)
-{
- return matrix[rowIndex * columns + columnIndex];
-}
-
-inline void QSimplex::setValueAt(int rowIndex, int columnIndex, qreal value)
-{
- matrix[rowIndex * columns + columnIndex] = value;
-}
-
-QT_END_NAMESPACE
-
-#endif // QSIMPLEX_P_H
diff --git a/src/gui/gui.pro b/src/gui/gui.pro
index c146a9b472..f9ae32b6b5 100644
--- a/src/gui/gui.pro
+++ b/src/gui/gui.pro
@@ -6,68 +6,24 @@ CONFIG += module
MODULE_PRI = ../modules/qt_gui.pri
DEFINES += QT_BUILD_GUI_LIB QT_NO_USING_NAMESPACE
-win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x65000000
-irix-cc*:QMAKE_CXXFLAGS += -no_prelink -ptused
-
-!win32:!qpa:!mac:!symbian:CONFIG += x11
unix|win32-g++*:QMAKE_PKGCONFIG_REQUIRES = QtCore
include(../qbase.pri)
-contains(QT_CONFIG, x11sm):CONFIG += x11sm
-
-#platforms
-x11:include(kernel/x11.pri)
-mac:include(kernel/mac.pri)
-win32:include(kernel/win.pri)
-symbian {
- include(kernel/symbian.pri)
- include(s60framework/s60framework.pri)
-}
-
# stuff that goes into new QtGui
include(guikernel/guikernel.pri)
include(image/image.pri)
include(text/text.pri)
include(painting/painting.pri)
include(guiutil/guiutil.pri)
-
-# to be moved into QtGui
-include(to_be_moved/to_be_moved.pri)
-
-#modules
-include(animation/animation.pri)
-include(kernel/kernel.pri)
-include(styles/styles.pri)
-include(widgets/widgets.pri)
-include(dialogs/dialogs.pri)
-include(accessible/accessible.pri)
-include(itemviews/itemviews.pri)
-include(inputmethod/inputmethod.pri)
-include(graphicsview/graphicsview.pri)
-include(util/util.pri)
-include(statemachine/statemachine.pri)
include(math3d/math3d.pri)
-include(effects/effects.pri)
include(egl/egl.pri)
-win32:!wince*: DEFINES += QT_NO_EGL
QMAKE_LIBS += $$QMAKE_LIBS_GUI
-contains(DEFINES,QT_EVAL):include($$QT_SOURCE_TREE/src/corelib/eval.pri)
-
-QMAKE_DYNAMIC_LIST_FILE = $$PWD/QtGui.dynlist
-
DEFINES += Q_INTERNAL_QAPP_SRC
-symbian {
- TARGET.UID3=0x2001B2DD
-
- # ro-section in gui can exceed default allocated space, so move rw-section a little further
- QMAKE_LFLAGS.ARMCC += --rw-base 0x800000
- QMAKE_LFLAGS.GCCE += -Tdata 0x800000
-}
neon:*-g++* {
DEFINES += QT_HAVE_NEON
diff --git a/src/gui/guikernel/qplatformcursor_qpa.cpp b/src/gui/guikernel/qplatformcursor_qpa.cpp
index 6b4f9152ce..f43eca640f 100644
--- a/src/gui/guikernel/qplatformcursor_qpa.cpp
+++ b/src/gui/guikernel/qplatformcursor_qpa.cpp
@@ -40,7 +40,6 @@
****************************************************************************/
#include "qplatformcursor_qpa.h"
-#include <QWidget>
#include <QPainter>
#include <QBitmap>
#include <QGuiApplication>
diff --git a/src/gui/kernel/qt_gui_pch.h b/src/gui/guikernel/qt_gui_pch.h
index 368c12d444..79450219fa 100644
--- a/src/gui/kernel/qt_gui_pch.h
+++ b/src/gui/guikernel/qt_gui_pch.h
@@ -67,18 +67,14 @@
#include <qstringlist.h>
#include <qtextcodec.h>
-#include <qapplication.h>
+#include <qguiapplication.h>
#include <qbitmap.h>
#include <qcursor.h>
-#include <qdesktopwidget.h>
#include <qevent.h>
#include <qimage.h>
-#include <qlayout.h>
#include <qpainter.h>
#include <qpixmap.h>
-#include <qstyle.h>
#include <qtimer.h>
-#include <qwidget.h>
#include <stdlib.h>
diff --git a/src/gui/inputmethod/inputmethod.pri b/src/gui/inputmethod/inputmethod.pri
deleted file mode 100644
index 77ca3bd057..0000000000
--- a/src/gui/inputmethod/inputmethod.pri
+++ /dev/null
@@ -1,27 +0,0 @@
-# Qt inputmethod module
-
-HEADERS +=inputmethod/qinputcontextfactory.h \
- inputmethod/qinputcontextplugin.h \
- inputmethod/qinputcontext_p.h \
- inputmethod/qinputcontext.h
-SOURCES +=inputmethod/qinputcontextfactory.cpp \
- inputmethod/qinputcontextplugin.cpp \
- inputmethod/qinputcontext.cpp
-x11 {
- HEADERS += inputmethod/qximinputcontext_p.h
- SOURCES += inputmethod/qximinputcontext_x11.cpp
-}
-win32 {
- HEADERS += inputmethod/qwininputcontext_p.h
- SOURCES += inputmethod/qwininputcontext_win.cpp
-}
-mac:!qpa {
- HEADERS += inputmethod/qmacinputcontext_p.h
- SOURCES += inputmethod/qmacinputcontext_mac.cpp
-}
-symbian:contains(QT_CONFIG, s60) {
- HEADERS += inputmethod/qcoefepinputcontext_p.h
- SOURCES += inputmethod/qcoefepinputcontext_s60.cpp
- LIBS += -lfepbase -lakninputlanguage
-}
-
diff --git a/src/gui/inputmethod/qcoefepinputcontext_p.h b/src/gui/inputmethod/qcoefepinputcontext_p.h
deleted file mode 100644
index de3577f1a6..0000000000
--- a/src/gui/inputmethod/qcoefepinputcontext_p.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOEFEPINPUTCONTEXT_P_H
-#define QCOEFEPINPUTCONTEXT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QT_NO_IM
-
-#include "qinputcontext.h"
-#include <qhash.h>
-#include <qtimer.h>
-#include <private/qcore_symbian_p.h>
-#include <private/qt_s60_p.h>
-
-#include <fepbase.h>
-#include <aknedsts.h>
-
-QT_BEGIN_NAMESPACE
-
-class Q_AUTOTEST_EXPORT QCoeFepInputContext : public QInputContext,
- public MCoeFepAwareTextEditor,
- public MCoeFepAwareTextEditor_Extension1,
- public MObjectProvider
-{
- Q_OBJECT
-
-public:
- QCoeFepInputContext(QObject *parent = 0);
- ~QCoeFepInputContext();
-
- QString identifierName() { return QLatin1String("coefep"); }
- QString language();
-
- void reset();
- void update();
-
- bool filterEvent(const QEvent *event);
- bool symbianFilterEvent(QWidget *keyWidget, const QSymbianEvent *event);
- void mouseHandler( int x, QMouseEvent *event);
- bool isComposing() const { return !m_preeditString.isEmpty(); }
-
- void setFocusWidget(QWidget * w);
- void widgetDestroyed(QWidget *w);
-
- TCoeInputCapabilities inputCapabilities();
-
- void resetSplitViewWidget(bool keepInputWidget = false);
- void ensureFocusWidgetVisible(QWidget *widget);
-
-protected:
- void timerEvent(QTimerEvent *timerEvent);
-
-private:
- void commitCurrentString(bool cancelFepTransaction);
- void updateHints(bool mustUpdateInputCapabilities);
- void applyHints(Qt::InputMethodHints hints);
- void applyFormat(QList<QInputMethodEvent::Attribute> *attributes);
- void queueInputCapabilitiesChanged();
- bool needsInputPanel();
- void commitTemporaryPreeditString();
- bool isWidgetVisible(QWidget *widget, int offset = 0);
-
-private Q_SLOTS:
- void ensureInputCapabilitiesChanged();
- void translateInputWidget();
-
- // From MCoeFepAwareTextEditor
-public:
- void StartFepInlineEditL(const TDesC& aInitialInlineText, TInt aPositionOfInsertionPointInInlineText,
- TBool aCursorVisibility, const MFormCustomDraw* aCustomDraw,
- MFepInlineTextFormatRetriever& aInlineTextFormatRetriever,
- MFepPointerEventHandlerDuringInlineEdit& aPointerEventHandlerDuringInlineEdit);
- void UpdateFepInlineTextL(const TDesC& aNewInlineText, TInt aPositionOfInsertionPointInInlineText);
- void SetInlineEditingCursorVisibilityL(TBool aCursorVisibility);
- void CancelFepInlineEdit();
- TInt DocumentLengthForFep() const;
- TInt DocumentMaximumLengthForFep() const;
- void SetCursorSelectionForFepL(const TCursorSelection& aCursorSelection);
- void GetCursorSelectionForFep(TCursorSelection& aCursorSelection) const;
- void GetEditorContentForFep(TDes& aEditorContent, TInt aDocumentPosition, TInt aLengthToRetrieve) const;
- void GetFormatForFep(TCharFormat& aFormat, TInt aDocumentPosition) const;
- void GetScreenCoordinatesForFepL(TPoint& aLeftSideOfBaseLine, TInt& aHeight, TInt& aAscent,
- TInt aDocumentPosition) const;
-private:
- void DoCommitFepInlineEditL();
- MCoeFepAwareTextEditor_Extension1* Extension1(TBool& aSetToTrue);
- void ReportAknEdStateEvent(MAknEdStateObserver::EAknEdwinStateEvent aEventType);
-
- // From MCoeFepAwareTextEditor_Extension1
-public:
- void SetStateTransferingOwnershipL(MCoeFepAwareTextEditor_Extension1::CState* aState, TUid aTypeSafetyUid);
- MCoeFepAwareTextEditor_Extension1::CState* State(TUid aTypeSafetyUid);
-
- // From MObjectProvider
-public:
- TTypeUid::Ptr MopSupplyObject(TTypeUid id);
- MObjectProvider *MopNext();
-
-private:
- QSymbianControl *m_parent;
- CAknEdwinState *m_fepState;
- QString m_preeditString;
- Qt::InputMethodHints m_lastImHints;
- TUint m_textCapabilities;
- bool m_inDestruction;
- bool m_pendingInputCapabilitiesChanged;
- int m_cursorVisibility;
- int m_inlinePosition;
- MFepInlineTextFormatRetriever *m_formatRetriever;
- MFepPointerEventHandlerDuringInlineEdit *m_pointerHandler;
- QBasicTimer m_tempPreeditStringTimeout;
- bool m_hasTempPreeditString;
-
- int m_splitViewResizeBy;
- Qt::WindowStates m_splitViewPreviousWindowStates;
- QRectF m_transformation;
-
- friend class tst_QInputContext;
-};
-
-Q_GUI_EXPORT void qt_s60_setPartialScreenInputMode(bool enable);
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_IM
-
-#endif // QCOEFEPINPUTCONTEXT_P_H
diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp
deleted file mode 100644
index 06dc25c708..0000000000
--- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp
+++ /dev/null
@@ -1,1200 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_IM
-
-#include "qcoefepinputcontext_p.h"
-#include <qapplication.h>
-#include <qtextformat.h>
-#include <qgraphicsview.h>
-#include <qgraphicsscene.h>
-#include <qgraphicswidget.h>
-#include <qsymbianevent.h>
-#include <qlayout.h>
-#include <qdesktopwidget.h>
-#include <private/qcore_symbian_p.h>
-
-#include <fepitfr.h>
-#include <hal.h>
-
-#include <limits.h>
-// You only find these enumerations on SDK 5 onwards, so we need to provide our own
-// to remain compatible with older releases. They won't be called by pre-5.0 SDKs.
-
-// MAknEdStateObserver::EAknCursorPositionChanged
-#define QT_EAknCursorPositionChanged MAknEdStateObserver::EAknEdwinStateEvent(6)
-// MAknEdStateObserver::EAknActivatePenInputRequest
-#define QT_EAknActivatePenInputRequest MAknEdStateObserver::EAknEdwinStateEvent(7)
-
-// EAknEditorFlagSelectionVisible is only valid from 3.2 onwards.
-// Sym^3 AVKON FEP manager expects that this flag is used for FEP-aware editors
-// that support text selection.
-#define QT_EAknEditorFlagSelectionVisible 0x100000
-
-// EAknEditorFlagEnablePartialScreen is only valid from Sym^3 onwards.
-#define QT_EAknEditorFlagEnablePartialScreen 0x200000
-
-QT_BEGIN_NAMESPACE
-
-Q_GUI_EXPORT void qt_s60_setPartialScreenInputMode(bool enable)
-{
- S60->partial_keyboard = enable;
-
- QInputContext *ic = 0;
- if (QApplication::focusWidget()) {
- ic = QApplication::focusWidget()->inputContext();
- } else if (qApp && qApp->inputContext()) {
- ic = qApp->inputContext();
- }
- if (ic)
- ic->update();
-}
-
-QCoeFepInputContext::QCoeFepInputContext(QObject *parent)
- : QInputContext(parent),
- m_fepState(q_check_ptr(new CAknEdwinState)), // CBase derived object needs check on new
- m_lastImHints(Qt::ImhNone),
- m_textCapabilities(TCoeInputCapabilities::EAllText),
- m_inDestruction(false),
- m_pendingInputCapabilitiesChanged(false),
- m_cursorVisibility(1),
- m_inlinePosition(0),
- m_formatRetriever(0),
- m_pointerHandler(0),
- m_hasTempPreeditString(false),
- m_splitViewResizeBy(0),
- m_splitViewPreviousWindowStates(Qt::WindowNoState)
-{
- m_fepState->SetObjectProvider(this);
- int defaultFlags = EAknEditorFlagDefault;
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0) {
- if (S60->partial_keyboard) {
- defaultFlags |= QT_EAknEditorFlagEnablePartialScreen;
- }
- defaultFlags |= QT_EAknEditorFlagSelectionVisible;
- }
- m_fepState->SetFlags(defaultFlags);
- m_fepState->SetDefaultInputMode( EAknEditorTextInputMode );
- m_fepState->SetPermittedInputModes( EAknEditorAllInputModes );
- m_fepState->SetDefaultCase( EAknEditorTextCase );
- m_fepState->SetPermittedCases( EAknEditorAllCaseModes );
- m_fepState->SetSpecialCharacterTableResourceId(R_AVKON_SPECIAL_CHARACTER_TABLE_DIALOG);
- m_fepState->SetNumericKeymap(EAknEditorAlphanumericNumberModeKeymap);
-}
-
-QCoeFepInputContext::~QCoeFepInputContext()
-{
- m_inDestruction = true;
-
- // This is to make sure that the FEP manager "forgets" about us,
- // otherwise we may get callbacks even after we're destroyed.
- // The call below is essentially equivalent to InputCapabilitiesChanged(),
- // but is synchronous, rather than asynchronous.
- CCoeEnv::Static()->SyncNotifyFocusObserversOfChangeInFocus();
-
- if (m_fepState)
- delete m_fepState;
-}
-
-void QCoeFepInputContext::reset()
-{
- commitCurrentString(true);
-}
-
-void QCoeFepInputContext::ReportAknEdStateEvent(MAknEdStateObserver::EAknEdwinStateEvent aEventType)
-{
- QT_TRAP_THROWING(m_fepState->ReportAknEdStateEventL(aEventType));
-}
-
-void QCoeFepInputContext::update()
-{
- updateHints(false);
-
- // For pre-5.0 SDKs, we don't do text updates on S60 side.
- if (QSysInfo::s60Version() < QSysInfo::SV_S60_5_0) {
- return;
- }
-
- // Don't be fooled (as I was) by the name of this enumeration.
- // What it really does is tell the virtual keyboard UI that the text has been
- // updated and it should be reflected in the internal display of the VK.
- ReportAknEdStateEvent(QT_EAknCursorPositionChanged);
-}
-
-void QCoeFepInputContext::setFocusWidget(QWidget *w)
-{
- commitCurrentString(true);
-
- QInputContext::setFocusWidget(w);
-
- updateHints(true);
-}
-
-void QCoeFepInputContext::widgetDestroyed(QWidget *w)
-{
- // Make sure that the input capabilities of whatever new widget got focused are queried.
- CCoeControl *ctrl = w->effectiveWinId();
- if (ctrl->IsFocused()) {
- queueInputCapabilitiesChanged();
- }
-}
-
-QString QCoeFepInputContext::language()
-{
- TLanguage lang = m_fepState->LocalLanguage();
- const QByteArray localeName = qt_symbianLocaleName(lang);
- if (!localeName.isEmpty()) {
- return QString::fromLatin1(localeName);
- } else {
- return QString::fromLatin1("C");
- }
-}
-
-bool QCoeFepInputContext::needsInputPanel()
-{
- switch (QSysInfo::s60Version()) {
- case QSysInfo::SV_S60_3_1:
- case QSysInfo::SV_S60_3_2:
- // There are no touch phones for pre-5.0 SDKs.
- return false;
-#ifdef Q_CC_NOKIAX86
- default:
- // For emulator we assume that we need an input panel, since we can't
- // separate between phone types.
- return true;
-#else
- case QSysInfo::SV_S60_5_0: {
- // For SDK == 5.0, we need phone specific detection, since the HAL API
- // is no good on most phones. However, all phones at the time of writing use the
- // input panel, except N97 in landscape mode, but in this mode it refuses to bring
- // up the panel anyway, so we don't have to care.
- return true;
- }
- default:
- // For unknown/newer types, we try to use the HAL API.
- int keyboardEnabled;
- int keyboardType;
- int err[2];
- err[0] = HAL::Get(HAL::EKeyboard, keyboardType);
- err[1] = HAL::Get(HAL::EKeyboardState, keyboardEnabled);
- if (err[0] == KErrNone && err[1] == KErrNone
- && keyboardType != 0 && keyboardEnabled)
- // Means that we have some sort of keyboard.
- return false;
-
- // Fall back to using the input panel.
- return true;
-#endif // !Q_CC_NOKIAX86
- }
-}
-
-bool QCoeFepInputContext::filterEvent(const QEvent *event)
-{
- // The CloseSoftwareInputPanel event is not handled here, because the VK will automatically
- // close when it discovers that the underlying widget does not have input capabilities.
-
- if (!focusWidget())
- return false;
-
- switch (event->type()) {
- case QEvent::MouseButtonPress:
- // Alphanumeric keypad doesn't like it when we click and text is still getting displayed
- // It ignores the mouse event, so we need to commit and send a selection event (which will get triggered
- // after the commit)
- if (!m_preeditString.isEmpty()) {
- commitCurrentString(true);
-
- int pos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt();
-
- QList<QInputMethodEvent::Attribute> selectAttributes;
- selectAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, pos, 0, QVariant());
- QInputMethodEvent selectEvent(QLatin1String(""), selectAttributes);
- sendEvent(selectEvent);
- }
- break;
- case QEvent::KeyPress:
- commitTemporaryPreeditString();
- // fall through intended
- case QEvent::KeyRelease:
- const QKeyEvent *keyEvent = static_cast<const QKeyEvent *>(event);
- //If proxy exists, always use hints from proxy.
- QWidget *proxy = focusWidget()->focusProxy();
- Qt::InputMethodHints currentHints = proxy ? proxy->inputMethodHints() : focusWidget()->inputMethodHints();
-
- switch (keyEvent->key()) {
- case Qt::Key_F20:
- Q_ASSERT(m_lastImHints == currentHints);
- if (m_lastImHints & Qt::ImhHiddenText) {
- // Special case in Symbian. On editors with secret text, F20 is for some reason
- // considered to be a backspace.
- QKeyEvent modifiedEvent(keyEvent->type(), Qt::Key_Backspace, keyEvent->modifiers(),
- keyEvent->text(), keyEvent->isAutoRepeat(), keyEvent->count());
- QApplication::sendEvent(focusWidget(), &modifiedEvent);
- return true;
- }
- break;
- case Qt::Key_Select:
- if (!m_preeditString.isEmpty()) {
- commitCurrentString(true);
- return true;
- }
- break;
- default:
- break;
- }
-
- QString widgetText = focusWidget()->inputMethodQuery(Qt::ImSurroundingText).toString();
- bool validLength;
- int maxLength = focusWidget()->inputMethodQuery(Qt::ImMaximumTextLength).toInt(&validLength);
- if (!keyEvent->text().isEmpty() && validLength
- && widgetText.size() + m_preeditString.size() >= maxLength) {
- // Don't send key events with string content if the widget is "full".
- return true;
- }
-
- if (keyEvent->type() == QEvent::KeyPress
- && currentHints & Qt::ImhHiddenText
- && !keyEvent->text().isEmpty()) {
- // Send some temporary preedit text in order to make text visible for a moment.
- m_preeditString = keyEvent->text();
- QList<QInputMethodEvent::Attribute> attributes;
- QInputMethodEvent imEvent(m_preeditString, attributes);
- sendEvent(imEvent);
- m_tempPreeditStringTimeout.start(1000, this);
- m_hasTempPreeditString = true;
- update();
- return true;
- }
- break;
- }
-
- if (!needsInputPanel())
- return false;
-
- if (event->type() == QEvent::RequestSoftwareInputPanel) {
- // Notify S60 that we want the virtual keyboard to show up.
- QSymbianControl *sControl;
- sControl = focusWidget()->effectiveWinId()->MopGetObject(sControl);
- Q_ASSERT(sControl);
-
- // The FEP UI temporarily steals focus when it shows up the first time, causing
- // all sorts of weird effects on the focused widgets. Since it will immediately give
- // back focus to us, we temporarily disable focus handling until the job's done.
- if (sControl) {
- sControl->setIgnoreFocusChanged(true);
- }
-
- ensureInputCapabilitiesChanged();
- m_fepState->ReportAknEdStateEventL(MAknEdStateObserver::QT_EAknActivatePenInputRequest);
-
- if (sControl) {
- sControl->setIgnoreFocusChanged(false);
- }
- return true;
- }
-
- return false;
-}
-
-bool QCoeFepInputContext::symbianFilterEvent(QWidget *keyWidget, const QSymbianEvent *event)
-{
- Q_UNUSED(keyWidget);
- if (event->type() == QSymbianEvent::CommandEvent)
- // A command basically means the same as a button being pushed. With Qt buttons
- // that would normally result in a reset of the input method due to the focus change.
- // This should also happen for commands.
- reset();
-
- if (event->type() == QSymbianEvent::WindowServerEvent
- && event->windowServerEvent()
- && event->windowServerEvent()->Type() == EEventWindowVisibilityChanged
- && S60->splitViewLastWidget) {
-
- QGraphicsView *gv = qobject_cast<QGraphicsView*>(S60->splitViewLastWidget);
- const bool alwaysResize = (gv && gv->verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff);
-
- if (alwaysResize) {
- TUint visibleFlags = event->windowServerEvent()->VisibilityChanged()->iFlags;
- if (visibleFlags & TWsVisibilityChangedEvent::EPartiallyVisible)
- ensureFocusWidgetVisible(S60->splitViewLastWidget);
- if (visibleFlags & TWsVisibilityChangedEvent::ENotVisible)
- resetSplitViewWidget(true);
- }
- }
-
- return false;
-}
-
-void QCoeFepInputContext::timerEvent(QTimerEvent *timerEvent)
-{
- if (timerEvent->timerId() == m_tempPreeditStringTimeout.timerId())
- commitTemporaryPreeditString();
-}
-
-void QCoeFepInputContext::commitTemporaryPreeditString()
-{
- if (m_tempPreeditStringTimeout.isActive())
- m_tempPreeditStringTimeout.stop();
-
- if (!m_hasTempPreeditString)
- return;
-
- commitCurrentString(false);
-}
-
-void QCoeFepInputContext::mouseHandler( int x, QMouseEvent *event)
-{
- Q_ASSERT(focusWidget());
-
- if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) {
- commitCurrentString(true);
- int pos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt();
-
- QList<QInputMethodEvent::Attribute> attributes;
- attributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, pos + x, 0, QVariant());
- QInputMethodEvent event(QLatin1String(""), attributes);
- sendEvent(event);
- }
-}
-
-TCoeInputCapabilities QCoeFepInputContext::inputCapabilities()
-{
- if (m_inDestruction || !focusWidget()) {
- return TCoeInputCapabilities(TCoeInputCapabilities::ENone, 0, 0);
- }
-
- return TCoeInputCapabilities(m_textCapabilities, this, 0);
-}
-
-void QCoeFepInputContext::resetSplitViewWidget(bool keepInputWidget)
-{
- QGraphicsView *gv = qobject_cast<QGraphicsView*>(S60->splitViewLastWidget);
-
- if (!gv) {
- return;
- }
-
- QSymbianControl *symControl = static_cast<QSymbianControl*>(gv->effectiveWinId());
- symControl->CancelLongTapTimer();
-
- const bool alwaysResize = (gv->verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff);
- QWidget *windowToMove = gv->window();
-
- bool userResize = gv->testAttribute(Qt::WA_Resized);
-
- windowToMove->setUpdatesEnabled(false);
-
- if (!alwaysResize) {
- if (gv->scene()) {
- if (gv->scene()->focusItem()) {
- // Check if the widget contains cursorPositionChanged signal and disconnect from it.
- QByteArray signal = QMetaObject::normalizedSignature(SIGNAL(cursorPositionChanged()));
- int index = gv->scene()->focusItem()->toGraphicsObject()->metaObject()->indexOfSignal(signal.right(signal.length() - 1));
- if (index != -1)
- disconnect(gv->scene()->focusItem()->toGraphicsObject(), SIGNAL(cursorPositionChanged()), this, SLOT(translateInputWidget()));
- }
-
- QGraphicsItem *rootItem = 0;
- foreach (QGraphicsItem *item, gv->scene()->items()) {
- if (!item->parentItem()) {
- rootItem = item;
- break;
- }
- }
- if (rootItem)
- rootItem->resetTransform();
- }
- } else {
- if (m_splitViewResizeBy)
- gv->resize(gv->rect().width(), m_splitViewResizeBy);
- }
- // Resizing might have led to widget losing its original windowstate.
- // Restore previous window state.
-
- if (m_splitViewPreviousWindowStates != windowToMove->windowState())
- windowToMove->setWindowState(m_splitViewPreviousWindowStates);
-
- windowToMove->setUpdatesEnabled(true);
-
- gv->setAttribute(Qt::WA_Resized, userResize); //not a user resize
-
- m_splitViewResizeBy = 0;
- if (!keepInputWidget) {
- m_splitViewPreviousWindowStates = Qt::WindowNoState;
- S60->splitViewLastWidget = 0;
- }
-}
-
-// Checks if a given widget is visible in the splitview rect. The offset
-// parameter can be used to validate if moving widget upwards or downwards
-// by the offset would make a difference for the visibility.
-
-bool QCoeFepInputContext::isWidgetVisible(QWidget *widget, int offset)
-{
- bool visible = false;
- if (widget) {
- QRect splitViewRect = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect());
- QWidget *window = QApplication::activeWindow();
- QGraphicsView *gv = qobject_cast<QGraphicsView*>(widget);
- if (gv && window) {
- if (QGraphicsScene *scene = gv->scene()) {
- if (QGraphicsItem *focusItem = scene->focusItem()) {
- QPoint cursorPos = window->mapToGlobal(focusItem->cursor().pos());
- cursorPos.setY(cursorPos.y() + offset);
- if (splitViewRect.contains(cursorPos)) {
- visible = true;
- }
- }
- }
- }
- }
- return visible;
-}
-
-// Ensure that the input widget is visible in the splitview rect.
-
-void QCoeFepInputContext::ensureFocusWidgetVisible(QWidget *widget)
-{
- // Native side opening and closing its virtual keyboard when it changes the keyboard layout,
- // has an adverse impact on long tap timer. Cancel the timer when splitview opens to avoid this.
- QSymbianControl *symControl = static_cast<QSymbianControl*>(widget->effectiveWinId());
- symControl->CancelLongTapTimer();
-
- // Graphicsviews that have vertical scrollbars should always be resized to the splitview area.
- // Graphicsviews without scrollbars should be translated.
-
- QGraphicsView *gv = qobject_cast<QGraphicsView*>(widget);
- if (!gv)
- return;
-
- const bool alwaysResize = (gv && gv->verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOff);
- const bool moveWithinVisibleArea = (S60->splitViewLastWidget != 0);
-
- QWidget *windowToMove = gv ? gv : symControl->widget();
- if (!windowToMove->isWindow())
- windowToMove = windowToMove->window();
- if (!windowToMove) {
- return;
- }
-
- // When opening the keyboard (not moving within the splitview area), save the original
- // window state. In some cases, ensuring input widget visibility might lead to window
- // states getting changed.
-
- if (!moveWithinVisibleArea) {
- // Check if the widget contains cursorPositionChanged signal and connect to it.
- QByteArray signal = QMetaObject::normalizedSignature(SIGNAL(cursorPositionChanged()));
- if (gv->scene() && gv->scene()->focusItem()) {
- int index = gv->scene()->focusItem()->toGraphicsObject()->metaObject()->indexOfSignal(signal.right(signal.length() - 1));
- if (index != -1)
- connect(gv->scene()->focusItem()->toGraphicsObject(), SIGNAL(cursorPositionChanged()), this, SLOT(translateInputWidget()));
- }
- S60->splitViewLastWidget = widget;
- m_splitViewPreviousWindowStates = windowToMove->windowState();
- }
-
- int windowTop = widget->window()->pos().y();
-
- const bool userResize = widget->testAttribute(Qt::WA_Resized);
-
- QRect splitViewRect = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect());
-
-
- // When resizing a window widget, it will lose its maximized window state.
- // Native applications hide statuspane in splitview state, so lets move to
- // fullscreen mode. This makes available area slightly bigger, which helps usability
- // and greatly reduces event passing in orientation switch cases,
- // as the statuspane size is not changing.
-
- if (alwaysResize)
- windowToMove->setUpdatesEnabled(false);
-
- if (!(windowToMove->windowState() & Qt::WindowFullScreen)) {
- windowToMove->setWindowState(
- (windowToMove->windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen)) | Qt::WindowFullScreen);
- }
-
- if (alwaysResize) {
- if (!moveWithinVisibleArea) {
- m_splitViewResizeBy = widget->height();
- windowTop = widget->geometry().top();
- widget->resize(widget->width(), splitViewRect.height() - windowTop);
- }
-
- if (gv->scene()) {
- const QRectF microFocusRect = gv->scene()->inputMethodQuery(Qt::ImMicroFocus).toRectF();
- gv->ensureVisible(microFocusRect);
- }
- } else {
- translateInputWidget();
- }
-
- if (alwaysResize)
- windowToMove->setUpdatesEnabled(true);
-
- widget->setAttribute(Qt::WA_Resized, userResize); //not a user resize
-}
-
-static QTextCharFormat qt_TCharFormat2QTextCharFormat(const TCharFormat &cFormat, bool validStyleColor)
-{
- QTextCharFormat qFormat;
-
- if (validStyleColor) {
- QBrush foreground(QColor(cFormat.iFontPresentation.iTextColor.Internal()));
- qFormat.setForeground(foreground);
- }
-
- qFormat.setFontStrikeOut(cFormat.iFontPresentation.iStrikethrough == EStrikethroughOn);
- qFormat.setFontUnderline(cFormat.iFontPresentation.iUnderline == EUnderlineOn);
-
- return qFormat;
-}
-
-void QCoeFepInputContext::updateHints(bool mustUpdateInputCapabilities)
-{
- QWidget *w = focusWidget();
- if (w) {
- QWidget *proxy = w->focusProxy();
- Qt::InputMethodHints hints = proxy ? proxy->inputMethodHints() : w->inputMethodHints();
-
- // Since splitview support works like an input method hint, yet it is private flag,
- // we need to update its state separately.
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0) {
- TInt currentFlags = m_fepState->Flags();
- if (S60->partial_keyboard)
- currentFlags |= QT_EAknEditorFlagEnablePartialScreen;
- else
- currentFlags &= ~QT_EAknEditorFlagEnablePartialScreen;
- if (currentFlags != m_fepState->Flags())
- m_fepState->SetFlags(currentFlags);
- }
-
- if (hints != m_lastImHints) {
- m_lastImHints = hints;
- applyHints(hints);
- } else if (!mustUpdateInputCapabilities) {
- // Optimization. Return immediately if there was no change.
- return;
- }
- }
- queueInputCapabilitiesChanged();
-}
-
-void QCoeFepInputContext::applyHints(Qt::InputMethodHints hints)
-{
- using namespace Qt;
-
- commitTemporaryPreeditString();
-
- const bool anynumbermodes = hints & (ImhDigitsOnly | ImhFormattedNumbersOnly | ImhDialableCharactersOnly);
- const bool anytextmodes = hints & (ImhUppercaseOnly | ImhLowercaseOnly | ImhEmailCharactersOnly | ImhUrlCharactersOnly);
- const bool numbersOnly = anynumbermodes && !anytextmodes;
- const bool noOnlys = !(hints & ImhExclusiveInputMask);
- // if alphanumeric input, or if multiple incompatible number modes are selected;
- // then make all symbols available in numeric mode too.
- const bool needsCharMap= !numbersOnly || ((hints & ImhFormattedNumbersOnly) && (hints & ImhDialableCharactersOnly));
- TInt flags;
- Qt::InputMethodHints oldHints = hints;
-
- // Some sanity checking. Make sure that only one preference is set.
- InputMethodHints prefs = ImhPreferNumbers | ImhPreferUppercase | ImhPreferLowercase;
- prefs &= hints;
- if (prefs != ImhPreferNumbers && prefs != ImhPreferUppercase && prefs != ImhPreferLowercase) {
- hints &= ~prefs;
- }
- if (!noOnlys) {
- // Make sure that the preference is within the permitted set.
- if (hints & ImhPreferNumbers && !anynumbermodes) {
- hints &= ~ImhPreferNumbers;
- } else if (hints & ImhPreferUppercase && !(hints & ImhUppercaseOnly)) {
- hints &= ~ImhPreferUppercase;
- } else if (hints & ImhPreferLowercase && !(hints & ImhLowercaseOnly)) {
- hints &= ~ImhPreferLowercase;
- }
- // If there is no preference, set it to something within the permitted set.
- if (!(hints & ImhPreferNumbers || hints & ImhPreferUppercase || hints & ImhPreferLowercase)) {
- if (hints & ImhLowercaseOnly) {
- hints |= ImhPreferLowercase;
- } else if (hints & ImhUppercaseOnly) {
- hints |= ImhPreferUppercase;
- } else if (numbersOnly) {
- hints |= ImhPreferNumbers;
- }
- }
- }
-
- if (hints & ImhPreferNumbers) {
- m_fepState->SetDefaultInputMode(EAknEditorNumericInputMode);
- m_fepState->SetCurrentInputMode(EAknEditorNumericInputMode);
- } else {
- m_fepState->SetDefaultInputMode(EAknEditorTextInputMode);
- m_fepState->SetCurrentInputMode(EAknEditorTextInputMode);
- }
- flags = 0;
- if (noOnlys || (anynumbermodes && anytextmodes)) {
- flags = EAknEditorAllInputModes;
- }
- else if (anynumbermodes) {
- flags |= EAknEditorNumericInputMode;
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0
- && ((hints & ImhFormattedNumbersOnly) || (hints & ImhDialableCharactersOnly))) {
- //workaround - the * key does not launch the symbols menu, making it impossible to use these modes unless text mode is enabled.
- flags |= EAknEditorTextInputMode;
- }
- }
- else if (anytextmodes) {
- flags |= EAknEditorTextInputMode;
- }
- else {
- flags = EAknEditorAllInputModes;
- }
- m_fepState->SetPermittedInputModes(flags);
- ReportAknEdStateEvent(MAknEdStateObserver::EAknEdwinStateInputModeUpdate);
-
- if (hints & ImhPreferLowercase) {
- m_fepState->SetDefaultCase(EAknEditorLowerCase);
- m_fepState->SetCurrentCase(EAknEditorLowerCase);
- } else if (hints & ImhPreferUppercase) {
- m_fepState->SetDefaultCase(EAknEditorUpperCase);
- m_fepState->SetCurrentCase(EAknEditorUpperCase);
- } else if (hints & ImhNoAutoUppercase) {
- m_fepState->SetDefaultCase(EAknEditorLowerCase);
- m_fepState->SetCurrentCase(EAknEditorLowerCase);
- } else {
- m_fepState->SetDefaultCase(EAknEditorTextCase);
- m_fepState->SetCurrentCase(EAknEditorTextCase);
- }
- flags = 0;
- if (hints & ImhUppercaseOnly) {
- flags |= EAknEditorUpperCase;
- }
- if (hints & ImhLowercaseOnly) {
- flags |= EAknEditorLowerCase;
- }
- if (flags == 0) {
- flags = EAknEditorAllCaseModes;
- if (hints & ImhNoAutoUppercase) {
- flags &= ~EAknEditorTextCase;
- }
- }
- m_fepState->SetPermittedCases(flags);
- ReportAknEdStateEvent(MAknEdStateObserver::EAknEdwinStateCaseModeUpdate);
-
- flags = 0;
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0) {
- if (S60->partial_keyboard)
- flags |= QT_EAknEditorFlagEnablePartialScreen;
- flags |= QT_EAknEditorFlagSelectionVisible;
- }
- if (hints & ImhUppercaseOnly && !(hints & ImhLowercaseOnly)
- || hints & ImhLowercaseOnly && !(hints & ImhUppercaseOnly)) {
- flags |= EAknEditorFlagFixedCase;
- }
- // Using T9 and hidden text together may actually crash the FEP, so check for hidden text too.
- if (hints & ImhNoPredictiveText || hints & ImhHiddenText) {
- flags |= EAknEditorFlagNoT9;
- }
- if (needsCharMap)
- flags |= EAknEditorFlagUseSCTNumericCharmap;
- m_fepState->SetFlags(flags);
- ReportAknEdStateEvent(MAknEdStateObserver::EAknEdwinStateFlagsUpdate);
-
- if (hints & ImhDialableCharactersOnly) {
- // This is first, because if (ImhDialableCharactersOnly | ImhFormattedNumbersOnly)
- // is specified, this one is more natural (# key enters a #)
- flags = EAknEditorStandardNumberModeKeymap;
- } else if (hints & ImhFormattedNumbersOnly) {
- // # key enters decimal point
- flags = EAknEditorCalculatorNumberModeKeymap;
- } else if (hints & ImhDigitsOnly) {
- // This is last, because it is most restrictive (# key is inactive)
- flags = EAknEditorPlainNumberModeKeymap;
- } else {
- flags = EAknEditorStandardNumberModeKeymap;
- }
- m_fepState->SetNumericKeymap(static_cast<TAknEditorNumericKeymap>(flags));
-
- if (hints & ImhUrlCharactersOnly) {
- // URL characters is everything except space, so a superset of the other restrictions
- m_fepState->SetSpecialCharacterTableResourceId(R_AVKON_URL_SPECIAL_CHARACTER_TABLE_DIALOG);
- } else if (hints & ImhEmailCharactersOnly) {
- m_fepState->SetSpecialCharacterTableResourceId(R_AVKON_EMAIL_ADDR_SPECIAL_CHARACTER_TABLE_DIALOG);
- } else if (needsCharMap) {
- m_fepState->SetSpecialCharacterTableResourceId(R_AVKON_SPECIAL_CHARACTER_TABLE_DIALOG);
- } else if ((hints & ImhFormattedNumbersOnly) || (hints & ImhDialableCharactersOnly)) {
- m_fepState->SetSpecialCharacterTableResourceId(R_AVKON_SPECIAL_CHARACTER_TABLE_DIALOG);
- } else {
- m_fepState->SetSpecialCharacterTableResourceId(0);
- }
-
- if (hints & ImhHiddenText) {
- m_textCapabilities = TCoeInputCapabilities::EAllText | TCoeInputCapabilities::ESecretText;
- } else {
- m_textCapabilities = TCoeInputCapabilities::EAllText;
- }
-}
-
-void QCoeFepInputContext::applyFormat(QList<QInputMethodEvent::Attribute> *attributes)
-{
- TCharFormat cFormat;
- QColor styleTextColor;
- if (QWidget *focused = focusWidget()) {
- QGraphicsView *gv = qobject_cast<QGraphicsView*>(focused);
- if (!gv) // could be either the QGV or its viewport that has focus
- gv = qobject_cast<QGraphicsView*>(focused->parentWidget());
- if (gv) {
- if (QGraphicsScene *scene = gv->scene()) {
- if (QGraphicsItem *focusItem = scene->focusItem()) {
- if (focusItem->isWidget()) {
- styleTextColor = static_cast<QGraphicsWidget*>(focusItem)->palette().text().color();
- }
- }
- }
- } else {
- styleTextColor = focused->palette().text().color();
- }
- } else {
- styleTextColor = QApplication::palette("QLineEdit").text().color();
- }
-
- if (styleTextColor.isValid()) {
- const TLogicalRgb fontColor(TRgb(styleTextColor.red(), styleTextColor.green(), styleTextColor.blue(), styleTextColor.alpha()));
- cFormat.iFontPresentation.iTextColor = fontColor;
- }
-
- TInt numChars = 0;
- TInt charPos = 0;
- int oldSize = attributes->size();
- while (m_formatRetriever) {
- m_formatRetriever->GetFormatOfFepInlineText(cFormat, numChars, charPos);
- if (numChars <= 0) {
- // This shouldn't happen according to S60 docs, but apparently does sometimes.
- break;
- }
- attributes->append(QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- charPos,
- numChars,
- QVariant(qt_TCharFormat2QTextCharFormat(cFormat, styleTextColor.isValid()))));
- charPos += numChars;
- if (charPos >= m_preeditString.size()) {
- break;
- }
- }
-
- if (attributes->size() == oldSize) {
- // S60 didn't provide any format, so let's give our own instead.
- attributes->append(QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- 0,
- m_preeditString.size(),
- standardFormat(PreeditFormat)));
- }
-}
-
-void QCoeFepInputContext::queueInputCapabilitiesChanged()
-{
- if (m_pendingInputCapabilitiesChanged)
- return;
-
- // Call ensureInputCapabilitiesChanged asynchronously. This is done to improve performance
- // by not updating input capabilities too often. The reason we don't call the Symbian
- // asynchronous version of InputCapabilitiesChanged is because we need to ensure that it
- // is synchronous in some specific cases. Those will call ensureInputCapabilitesChanged.
- QMetaObject::invokeMethod(this, "ensureInputCapabilitiesChanged", Qt::QueuedConnection);
- m_pendingInputCapabilitiesChanged = true;
-}
-
-void QCoeFepInputContext::ensureInputCapabilitiesChanged()
-{
- if (!m_pendingInputCapabilitiesChanged)
- return;
-
- // The call below is essentially equivalent to InputCapabilitiesChanged(),
- // but is synchronous, rather than asynchronous.
- CCoeEnv::Static()->SyncNotifyFocusObserversOfChangeInFocus();
- m_pendingInputCapabilitiesChanged = false;
-}
-
-void QCoeFepInputContext::translateInputWidget()
-{
- QGraphicsView *gv = qobject_cast<QGraphicsView *>(S60->splitViewLastWidget);
- QRect splitViewRect = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect());
-
- QRectF cursor = gv->scene()->inputMethodQuery(Qt::ImMicroFocus).toRectF();
- QPolygon cursorP = gv->mapFromScene(cursor);
- QRectF vkbRect = QRectF(splitViewRect.bottomLeft(), qApp->desktop()->rect().bottomRight());
- if (cursor.isEmpty() || vkbRect.isEmpty())
- return;
-
- // Fetch root item (i.e. graphicsitem with no parent)
- QGraphicsItem *rootItem = 0;
- foreach (QGraphicsItem *item, gv->scene()->items()) {
- if (!item->parentItem()) {
- rootItem = item;
- break;
- }
- }
- if (!rootItem)
- return;
-
- m_transformation = (rootItem->transform().isTranslating()) ? QRectF(0,0, gv->width(), rootItem->transform().dy()) : QRectF();
-
- // Do nothing if the cursor is visible in the splitview area.
- if (splitViewRect.contains(cursorP.boundingRect()))
- return;
-
- // New Y position should be ideally at the center of the splitview area.
- // If that would expose unpainted canvas, limit the tranformation to the visible scene bottom.
-
- const qreal maxY = gv->sceneRect().bottom() - splitViewRect.bottom() + m_transformation.height();
- qreal dy = -(qMin(maxY, (cursor.bottom() - vkbRect.top() / 2)));
-
- // Do not allow transform above screen top.
- if (m_transformation.height() + dy > 0)
- return;
-
- rootItem->setTransform(QTransform::fromTranslate(0, dy), true);
-}
-
-void QCoeFepInputContext::StartFepInlineEditL(const TDesC& aInitialInlineText,
- TInt aPositionOfInsertionPointInInlineText, TBool aCursorVisibility, const MFormCustomDraw* /*aCustomDraw*/,
- MFepInlineTextFormatRetriever& aInlineTextFormatRetriever,
- MFepPointerEventHandlerDuringInlineEdit& aPointerEventHandlerDuringInlineEdit)
-{
- QWidget *w = focusWidget();
- if (!w)
- return;
-
- commitTemporaryPreeditString();
-
- QList<QInputMethodEvent::Attribute> attributes;
-
- m_cursorVisibility = aCursorVisibility ? 1 : 0;
- m_inlinePosition = aPositionOfInsertionPointInInlineText;
- m_preeditString = qt_TDesC2QString(aInitialInlineText);
-
- m_formatRetriever = &aInlineTextFormatRetriever;
- m_pointerHandler = &aPointerEventHandlerDuringInlineEdit;
-
- // With T9 aInitialInlineText is typically empty when StartFepInlineEditL is called,
- // but FEP requires that selected text is always removed at StartFepInlineEditL.
- // Let's remove the selected text if aInitialInlineText is empty and there is selected text
- if (m_preeditString.isEmpty()) {
- int anchor = w->inputMethodQuery(Qt::ImAnchorPosition).toInt();
- int cursorPos = w->inputMethodQuery(Qt::ImCursorPosition).toInt();
- int replacementLength = qAbs(cursorPos-anchor);
- if (replacementLength > 0) {
- int replacementStart = cursorPos < anchor ? 0 : -replacementLength;
- QList<QInputMethodEvent::Attribute> clearSelectionAttributes;
- QInputMethodEvent clearSelectionEvent(QLatin1String(""), clearSelectionAttributes);
- clearSelectionEvent.setCommitString(QLatin1String(""), replacementStart, replacementLength);
- sendEvent(clearSelectionEvent);
- }
- }
-
- applyFormat(&attributes);
-
- attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor,
- m_inlinePosition,
- m_cursorVisibility,
- QVariant()));
- QInputMethodEvent event(m_preeditString, attributes);
- sendEvent(event);
-}
-
-void QCoeFepInputContext::UpdateFepInlineTextL(const TDesC& aNewInlineText,
- TInt aPositionOfInsertionPointInInlineText)
-{
- QWidget *w = focusWidget();
- if (!w)
- return;
-
- commitTemporaryPreeditString();
-
- m_inlinePosition = aPositionOfInsertionPointInInlineText;
-
- QList<QInputMethodEvent::Attribute> attributes;
- applyFormat(&attributes);
- attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor,
- m_inlinePosition,
- m_cursorVisibility,
- QVariant()));
- QString newPreeditString = qt_TDesC2QString(aNewInlineText);
- QInputMethodEvent event(newPreeditString, attributes);
- if (newPreeditString.isEmpty() && m_preeditString.isEmpty()) {
- // In Symbian world this means "erase last character".
- event.setCommitString(QLatin1String(""), -1, 1);
- }
- m_preeditString = newPreeditString;
- sendEvent(event);
-}
-
-void QCoeFepInputContext::SetInlineEditingCursorVisibilityL(TBool aCursorVisibility)
-{
- QWidget *w = focusWidget();
- if (!w)
- return;
-
- m_cursorVisibility = aCursorVisibility ? 1 : 0;
-
- QList<QInputMethodEvent::Attribute> attributes;
- attributes.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor,
- m_inlinePosition,
- m_cursorVisibility,
- QVariant()));
- QInputMethodEvent event(m_preeditString, attributes);
- sendEvent(event);
-}
-
-void QCoeFepInputContext::CancelFepInlineEdit()
-{
- // We are not supposed to ever have a tempPreeditString and a real preedit string
- // from S60 at the same time, so it should be safe to rely on this test to determine
- // whether we should honor S60's request to clear the text or not.
- if (m_hasTempPreeditString)
- return;
-
- QList<QInputMethodEvent::Attribute> attributes;
- QInputMethodEvent event(QLatin1String(""), attributes);
- event.setCommitString(QLatin1String(""), 0, 0);
- m_preeditString.clear();
- m_inlinePosition = 0;
- sendEvent(event);
-}
-
-TInt QCoeFepInputContext::DocumentLengthForFep() const
-{
- QWidget *w = focusWidget();
- if (!w)
- return 0;
-
- QVariant variant = w->inputMethodQuery(Qt::ImSurroundingText);
- return variant.value<QString>().size() + m_preeditString.size();
-}
-
-TInt QCoeFepInputContext::DocumentMaximumLengthForFep() const
-{
- QWidget *w = focusWidget();
- if (!w)
- return 0;
-
- QVariant variant = w->inputMethodQuery(Qt::ImMaximumTextLength);
- int size;
- if (variant.isValid()) {
- size = variant.toInt();
- } else {
- size = INT_MAX; // Sensible default for S60.
- }
- return size;
-}
-
-void QCoeFepInputContext::SetCursorSelectionForFepL(const TCursorSelection& aCursorSelection)
-{
- QWidget *w = focusWidget();
- if (!w)
- return;
-
- commitTemporaryPreeditString();
-
- int pos = aCursorSelection.iAnchorPos;
- int length = aCursorSelection.iCursorPos - pos;
-
- QList<QInputMethodEvent::Attribute> attributes;
- attributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, pos, length, QVariant());
- QInputMethodEvent event(m_preeditString, attributes);
- sendEvent(event);
-}
-
-void QCoeFepInputContext::GetCursorSelectionForFep(TCursorSelection& aCursorSelection) const
-{
- QWidget *w = focusWidget();
- if (!w) {
- aCursorSelection.SetSelection(0,0);
- return;
- }
-
- int cursor = w->inputMethodQuery(Qt::ImCursorPosition).toInt() + m_preeditString.size();
- int anchor = w->inputMethodQuery(Qt::ImAnchorPosition).toInt() + m_preeditString.size();
- QString text = w->inputMethodQuery(Qt::ImSurroundingText).value<QString>();
- int combinedSize = text.size() + m_preeditString.size();
- if (combinedSize < anchor || combinedSize < cursor) {
- // ### TODO! FIXME! QTBUG-5050
- // This is a hack to prevent crashing in 4.6 with QLineEdits that use input masks.
- // The root problem is that cursor position is relative to displayed text instead of the
- // actual text we get.
- //
- // To properly fix this we would need to know the displayText of QLineEdits instead
- // of just the text, which on itself should be a trivial change. The difficulties start
- // when we need to commit the changes back to the QLineEdit, which would have to be somehow
- // able to handle displayText, too.
- //
- // Until properly fixed, the cursor and anchor positions will not reflect correct positions
- // for masked QLineEdits, unless all the masked positions are filled in order so that
- // cursor position relative to the displayed text matches position relative to actual text.
- aCursorSelection.iAnchorPos = combinedSize;
- aCursorSelection.iCursorPos = combinedSize;
- } else {
- aCursorSelection.iAnchorPos = anchor;
- aCursorSelection.iCursorPos = cursor;
- }
-}
-
-void QCoeFepInputContext::GetEditorContentForFep(TDes& aEditorContent, TInt aDocumentPosition,
- TInt aLengthToRetrieve) const
-{
- QWidget *w = focusWidget();
- if (!w) {
- aEditorContent.FillZ(aLengthToRetrieve);
- return;
- }
-
- QString text = w->inputMethodQuery(Qt::ImSurroundingText).value<QString>();
- // FEP expects the preedit string to be part of the editor content, so let's mix it in.
- int cursor = w->inputMethodQuery(Qt::ImCursorPosition).toInt();
- text.insert(cursor, m_preeditString);
- aEditorContent.Copy(qt_QString2TPtrC(text.mid(aDocumentPosition, aLengthToRetrieve)));
-}
-
-void QCoeFepInputContext::GetFormatForFep(TCharFormat& aFormat, TInt /* aDocumentPosition */) const
-{
- QWidget *w = focusWidget();
- if (!w) {
- aFormat = TCharFormat();
- return;
- }
-
- QFont font = w->inputMethodQuery(Qt::ImFont).value<QFont>();
- QFontMetrics metrics(font);
- //QString name = font.rawName();
- QString name = font.defaultFamily(); // TODO! FIXME! Should be the above.
- QHBufC hBufC(name);
- aFormat = TCharFormat(hBufC->Des(), metrics.height());
-}
-
-void QCoeFepInputContext::GetScreenCoordinatesForFepL(TPoint& aLeftSideOfBaseLine, TInt& aHeight,
- TInt& aAscent, TInt /* aDocumentPosition */) const
-{
- QWidget *w = focusWidget();
- if (!w) {
- aLeftSideOfBaseLine = TPoint(0,0);
- aHeight = 0;
- aAscent = 0;
- return;
- }
-
- QRect rect = w->inputMethodQuery(Qt::ImMicroFocus).value<QRect>();
- aLeftSideOfBaseLine.iX = rect.left();
- aLeftSideOfBaseLine.iY = rect.bottom();
-
- QFont font = w->inputMethodQuery(Qt::ImFont).value<QFont>();
- QFontMetrics metrics(font);
- aHeight = metrics.height();
- aAscent = metrics.ascent();
-}
-
-void QCoeFepInputContext::DoCommitFepInlineEditL()
-{
- commitCurrentString(false);
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0)
- ReportAknEdStateEvent(QT_EAknCursorPositionChanged);
-
-}
-
-void QCoeFepInputContext::commitCurrentString(bool cancelFepTransaction)
-{
- QList<QInputMethodEvent::Attribute> attributes;
- QInputMethodEvent event(QLatin1String(""), attributes);
- event.setCommitString(m_preeditString, 0, 0);
- m_preeditString.clear();
- m_inlinePosition = 0;
- sendEvent(event);
-
- m_hasTempPreeditString = false;
-
- if (cancelFepTransaction) {
- CCoeFep* fep = CCoeEnv::Static()->Fep();
- if (fep)
- fep->CancelTransaction();
- }
-}
-
-MCoeFepAwareTextEditor_Extension1* QCoeFepInputContext::Extension1(TBool& aSetToTrue)
-{
- aSetToTrue = ETrue;
- return this;
-}
-
-void QCoeFepInputContext::SetStateTransferingOwnershipL(MCoeFepAwareTextEditor_Extension1::CState* aState,
- TUid /*aTypeSafetyUid*/)
-{
- // Note: The S60 docs are wrong! See the State() function.
- if (m_fepState)
- delete m_fepState;
- m_fepState = static_cast<CAknEdwinState *>(aState);
-}
-
-MCoeFepAwareTextEditor_Extension1::CState* QCoeFepInputContext::State(TUid /*aTypeSafetyUid*/)
-{
- // Note: The S60 docs are horribly wrong when describing the
- // SetStateTransferingOwnershipL function and this function. They say that the former
- // sets a CState object identified by the TUid, and the latter retrieves it.
- // In reality, the CState is expected to always be a CAknEdwinState (even if it was not
- // previously set), and the TUid is ignored. All in all, there is a single CAknEdwinState
- // per QCoeFepInputContext, which should be deleted if the SetStateTransferingOwnershipL
- // function is used to set a new one.
- return m_fepState;
-}
-
-TTypeUid::Ptr QCoeFepInputContext::MopSupplyObject(TTypeUid /*id*/)
-{
- return TTypeUid::Null();
-}
-
-MObjectProvider *QCoeFepInputContext::MopNext()
-{
- QWidget *w = focusWidget();
- if (w)
- return w->effectiveWinId();
- return 0;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_IM
diff --git a/src/gui/inputmethod/qinputcontext.cpp b/src/gui/inputmethod/qinputcontext.cpp
deleted file mode 100644
index f083e51981..0000000000
--- a/src/gui/inputmethod/qinputcontext.cpp
+++ /dev/null
@@ -1,500 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Implementation of QInputContext class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-//#define QT_NO_IM_PREEDIT_RELOCATION
-
-#include "qinputcontext.h"
-#include "qinputcontext_p.h"
-
-#ifndef QT_NO_IM
-
-#include "qplatformdefs.h"
-
-#include "qapplication.h"
-#include "qmenu.h"
-#include "qtextformat.h"
-#include "qpalette.h"
-
-#include <stdlib.h>
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QInputContext
- \brief The QInputContext class abstracts the input method dependent data and composing state.
-
- \ingroup i18n
-
- An input method is responsible for inputting complex text that cannot
- be inputted via simple keymap. It converts a sequence of input
- events (typically key events) into a text string through the input
- method specific converting process. The class of the processes are
- widely ranging from simple finite state machine to complex text
- translator that pools a whole paragraph of a text with text
- editing capability to perform grammar and semantic analysis.
-
- To abstract such different input method specific intermediate
- information, Qt offers the QInputContext as base class. The
- concept is well known as 'input context' in the input method
- domain. An input context is created for a text widget in response
- to a demand. It is ensured that an input context is prepared for
- an input method before input to a text widget.
-
- Multiple input contexts that belong to a single input method
- may concurrently coexist. Suppose multi-window text editor. Each
- text widget of window A and B holds different QInputContext
- instance which contains different state information such as
- partially composed text.
-
- \section1 Groups of Functions
-
- \table
- \header \o Context \o Functions
-
- \row \o Receiving information \o
- x11FilterEvent(),
- filterEvent(),
- mouseHandler()
-
- \row \o Sending back composed text \o
- sendEvent()
-
- \row \o State change notification \o
- setFocusWidget(),
- reset()
-
- \row \o Context information \o
- identifierName(),
- language(),
- font(),
- isComposing()
-
- \endtable
-
- \section1 Licensing Information
-
- \legalese
- Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-
- This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
- license. You may use this file under your Qt license. Following
- description is copied from their original file headers. Contact
- immodule-qt@freedesktop.org if any conditions of this licensing are
- not clear to you.
- \endlegalese
-
- \sa QInputContextPlugin, QInputContextFactory, QApplication::setInputContext()
-*/
-
-/*!
- Constructs an input context with the given \a parent.
-*/
-QInputContext::QInputContext(QObject* parent)
- : QObject(*new QInputContextPrivate, parent)
-{
-}
-
-
-/*!
- Destroys the input context.
-*/
-QInputContext::~QInputContext()
-{
-}
-
-/*!
- Returns the widget that has an input focus for this input
- context.
-
- The return value may differ from holderWidget() if the input
- context is shared between several text widgets.
-
- \warning To ensure platform independence and support flexible
- configuration of widgets, ordinary input methods should not call
- this function directly.
-
- \sa setFocusWidget()
-*/
-QWidget *QInputContext::focusWidget() const
-{
- Q_D(const QInputContext);
- return d->focusWidget;
-}
-
-
-/*!
- Sets the \a widget that has an input focus for this input context.
-
- \warning Ordinary input methods must not call this function
- directly.
-
- \sa focusWidget()
-*/
-void QInputContext::setFocusWidget(QWidget *widget)
-{
- Q_ASSERT(!widget || widget->testAttribute(Qt::WA_InputMethodEnabled));
- Q_D(QInputContext);
- d->focusWidget = widget;
-}
-
-/*!
- \fn bool QInputContext::isComposing() const
-
- This function indicates whether InputMethodStart event had been
- sent to the current focus widget. It is ensured that an input
- context can send InputMethodCompose or InputMethodEnd event safely
- if this function returned true.
-
- The state is automatically being tracked through sendEvent().
-
- \sa sendEvent()
-*/
-
-/*!
- This function can be reimplemented in a subclass to filter input
- events.
-
- Return true if the \a event has been consumed. Otherwise, the
- unfiltered \a event will be forwarded to widgets as ordinary
- way. Although the input events have accept() and ignore()
- methods, leave it untouched.
-
- \a event is currently restricted to events of these types:
-
- \list
- \i CloseSoftwareInputPanel
- \i KeyPress
- \i KeyRelease
- \i MouseButtonDblClick
- \i MouseButtonPress
- \i MouseButtonRelease
- \i MouseMove
- \i RequestSoftwareInputPanel
- \endlist
-
- But some input method related events such as QWheelEvent or
- QTabletEvent may be added in future.
-
- The filtering opportunity is always given to the input context as
- soon as possible. It has to be taken place before any other key
- event consumers such as eventfilters and accelerators because some
- input methods require quite various key combination and
- sequences. It often conflicts with accelerators and so on, so we
- must give the input context the filtering opportunity first to
- ensure all input methods work properly regardless of application
- design.
-
- Ordinary input methods require discrete key events to work
- properly, so Qt's key compression is always disabled for any input
- contexts.
-
- \sa QKeyEvent, x11FilterEvent()
-*/
-bool QInputContext::filterEvent(const QEvent * /*event*/)
-{
- return false;
-}
-
-/*!
- Sends an input method event specified by \a event to the current focus
- widget. Implementations of QInputContext should call this method to
- send the generated input method events and not
- QApplication::sendEvent(), as the events might have to get dispatched
- to a different application on some platforms.
-
- Some complex input methods route the handling to several child
- contexts (e.g. to enable language switching). To account for this,
- QInputContext will check if the parent object is a QInputContext. If
- yes, it will call the parents sendEvent() implementation instead of
- sending the event directly.
-
- \sa QInputMethodEvent
-*/
-void QInputContext::sendEvent(const QInputMethodEvent &event)
-{
- // route events over input context parents to make chaining possible.
- QInputContext *p = qobject_cast<QInputContext *>(parent());
- if (p) {
- p->sendEvent(event);
- return;
- }
-
- QWidget *focus = focusWidget();
- if (!focus)
- return;
-
- QInputMethodEvent e(event);
- QApplication::sendEvent(focus, &e);
-}
-
-
-/*!
- This function can be reimplemented in a subclass to handle mouse
- press, release, double-click, and move events within the preedit
- text. You can use the function to implement mouse-oriented user
- interface such as text selection or popup menu for candidate
- selection.
-
- The \a x parameter is the offset within the string that was sent
- with the InputMethodCompose event. The alteration boundary of \a
- x is ensured as character boundary of preedit string accurately.
-
- The \a event parameter is the event that was sent to the editor
- widget. The event type is QEvent::MouseButtonPress,
- QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick or
- QEvent::MouseMove. The event's button and state indicate
- the kind of operation that was performed.
-*/
-void QInputContext::mouseHandler(int /*x*/, QMouseEvent *event)
-{
- // Default behavior for simple ephemeral input contexts. Some
- // complex input contexts should not be reset here.
- if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick)
- reset();
-}
-
-
-/*!
- Returns the font of the current input widget
-*/
-QFont QInputContext::font() const
-{
- Q_D(const QInputContext);
- if (!d->focusWidget)
- return QApplication::font();
-
- return qvariant_cast<QFont>(d->focusWidget->inputMethodQuery(Qt::ImFont));
-}
-
-/*!
- This virtual function is called when a state in the focus widget
- has changed. QInputContext can then use
- QWidget::inputMethodQuery() to query the new state of the widget.
-*/
-void QInputContext::update()
-{
-}
-
-/*!
- This virtual function is called when the specified \a widget is
- destroyed. The \a widget is a widget on which this input context
- is installed.
-*/
-void QInputContext::widgetDestroyed(QWidget *widget)
-{
- Q_D(QInputContext);
- if (widget == d->focusWidget)
- setFocusWidget(0);
-}
-
-/*!
- \fn void QInputContext::reset()
-
- This function can be reimplemented in a subclass to reset the
- state of the input method.
-
- This function is called by several widgets to reset input
- state. For example, a text widget call this function before
- inserting a text to make widget ready to accept a text.
-
- Default implementation is sufficient for simple input method. You
- can override this function to reset external input method engines
- in complex input method. In the case, call QInputContext::reset()
- to ensure proper termination of inputting.
-
- In a reimplementation of reset(), you must not send any
- QInputMethodEvent containing preedit text. You can only commit
- string and attributes; otherwise, you risk breaking input state
- consistency.
-*/
-
-
-/*!
- \fn QString QInputContext::identifierName()
-
- This function must be implemented in any subclasses to return the
- identifier name of the input method.
-
- Return value is the name to identify and specify input methods for
- the input method switching mechanism and so on. The name has to be
- consistent with QInputContextPlugin::keys(). The name has to
- consist of ASCII characters only.
-
- There are two different names with different responsibility in the
- input method domain. This function returns one of them. Another
- name is called 'display name' that stands for the name for
- endusers appeared in a menu and so on.
-
- \sa QInputContextPlugin::keys(), QInputContextPlugin::displayName()
-*/
-
-
-/*!
- \fn QString QInputContext::language()
-
- This function must be implemented in any subclasses to return a
- language code (e.g. "zh_CN", "zh_TW", "zh_HK", "ja", "ko", ...)
- of the input context. If the input context can handle multiple
- languages, return the currently used one. The name has to be
- consistent with QInputContextPlugin::language().
-
- This information will be used by language tagging feature in
- QInputMethodEvent. It is required to distinguish unified han characters
- correctly. It enables proper font and character code
- handling. Suppose CJK-awared multilingual web browser
- (that automatically modifies fonts in CJK-mixed text) and XML editor
- (that automatically inserts lang attr).
-*/
-
-
-/*!
- This is a preliminary interface for Qt 4.
-*/
-QList<QAction *> QInputContext::actions()
-{
- return QList<QAction *>();
-}
-
-/*!
- \enum QInputContext::StandardFormat
-
- \value PreeditFormat The preedit text.
- \value SelectionFormat The selection text.
-
- \sa standardFormat()
-*/
-
-/*!
- Returns a QTextFormat object that specifies the format for
- component \a s.
-*/
-QTextFormat QInputContext::standardFormat(StandardFormat s) const
-{
- QWidget *focus = focusWidget();
- const QPalette &pal = focus ? focus->palette() : QApplication::palette();
-
- QTextCharFormat fmt;
- QColor bg;
- switch (s) {
- case QInputContext::PreeditFormat: {
- fmt.setUnderlineStyle(QTextCharFormat::DashUnderline);
- break;
- }
- case QInputContext::SelectionFormat: {
- bg = pal.text().color();
- fmt.setBackground(QBrush(bg));
- fmt.setForeground(pal.background());
- break;
- }
- }
- return fmt;
-}
-
-#ifdef Q_WS_X11
-/*!
- This function may be overridden only if input method is depending
- on X11 and you need raw XEvent. Otherwise, this function must not.
-
- This function is designed to filter raw key events for XIM, but
- other input methods may use this to implement some special
- features such as distinguishing Shift_L and Shift_R.
-
- Return true if the \a event has been consumed. Otherwise, the
- unfiltered \a event will be translated into QEvent and forwarded
- to filterEvent(). Filtering at both x11FilterEvent() and
- filterEvent() in single input method is allowed.
-
- \a keywidget is a client widget into which a text is inputted. \a
- event is inputted XEvent.
-
- \sa filterEvent()
-*/
-bool QInputContext::x11FilterEvent(QWidget * /*keywidget*/, XEvent * /*event*/)
-{
- return false;
-}
-#endif // Q_WS_X11
-
-#ifdef Q_OS_SYMBIAN
-/*!
- \since 4.6
-
- This function may be overridden only if input method is depending
- on Symbian and you need raw Symbian events. Otherwise, this function must not.
-
- This function is designed to filter raw key events on Symbian, but
- other input methods may use this to implement some special
- features.
-
- Return true if the \a event has been consumed. Otherwise, the
- unfiltered \a event will be translated into QEvent and forwarded
- to filterEvent(). Filtering at both symbianFilterEvent() and
- filterEvent() in single input method is allowed.
-
- \a keywidget is a client widget into which a text is inputted. \a
- event is inputted QSymbianEvent.
-
- \sa filterEvent()
-*/
-bool QInputContext::symbianFilterEvent(QWidget * /*keywidget*/, const QSymbianEvent * /*event*/)
-{
- return false;
-}
-#endif // Q_OS_SYMBIAN
-
-QT_END_NAMESPACE
-
-#endif //Q_NO_IM
diff --git a/src/gui/inputmethod/qinputcontext.h b/src/gui/inputmethod/qinputcontext.h
deleted file mode 100644
index 089e6cdb9a..0000000000
--- a/src/gui/inputmethod/qinputcontext.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Definition of QInputContext class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#ifndef QINPUTCONTEXT_H
-#define QINPUTCONTEXT_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qglobal.h>
-#include <QtGui/qevent.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qlist.h>
-#include <QtGui/qaction.h>
-
-#ifndef QT_NO_IM
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QWidget;
-class QFont;
-class QPopupMenu;
-class QInputContextPrivate;
-#ifdef Q_OS_SYMBIAN
-class QSymbianEvent;
-#endif
-
-class Q_GUI_EXPORT QInputContext : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QInputContext)
-public:
- explicit QInputContext(QObject* parent = 0);
- virtual ~QInputContext();
-
- virtual QString identifierName() = 0;
- virtual QString language() = 0;
-
- virtual void reset() = 0;
- virtual void update();
-
- virtual void mouseHandler( int x, QMouseEvent *event);
- virtual QFont font() const;
- virtual bool isComposing() const = 0;
-
- QWidget *focusWidget() const;
- virtual void setFocusWidget( QWidget *w );
-
- virtual void widgetDestroyed(QWidget *w);
-
- virtual QList<QAction *> actions();
-
-#if defined(Q_WS_X11)
- virtual bool x11FilterEvent( QWidget *keywidget, XEvent *event );
-#endif // Q_WS_X11
-#if defined(Q_OS_SYMBIAN)
- virtual bool symbianFilterEvent( QWidget *keywidget, const QSymbianEvent *event );
-#endif // Q_OS_SYMBIAN
- virtual bool filterEvent( const QEvent *event );
-
- void sendEvent(const QInputMethodEvent &event);
-
- enum StandardFormat {
- PreeditFormat,
- SelectionFormat
- };
- QTextFormat standardFormat(StandardFormat s) const;
-private:
- friend class QWidget;
- friend class QWidgetPrivate;
- friend class QInputContextFactory;
- friend class QApplication;
-private: // Disabled copy constructor and operator=
- QInputContext( const QInputContext & );
- QInputContext &operator=( const QInputContext & );
-
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //Q_NO_IM
-
-#endif // QINPUTCONTEXT_H
diff --git a/src/gui/inputmethod/qinputcontext_p.h b/src/gui/inputmethod/qinputcontext_p.h
deleted file mode 100644
index be4c141d05..0000000000
--- a/src/gui/inputmethod/qinputcontext_p.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-/****************************************************************************
-**
-** Implementation of QInputContext class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#ifndef QINPUTCONTEXT_P_H
-#define QINPUTCONTEXT_P_H
-
-#include "private/qobject_p.h"
-#include "qwidget.h"
-#include "qinputcontext.h"
-
-#ifndef QT_NO_IM
-
-QT_BEGIN_NAMESPACE
-
-class QInputContextPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QInputContext)
-public:
- QInputContextPrivate()
- : focusWidget(0)
- {}
-
- QWidget *focusWidget;
-};
-
-QT_END_NAMESPACE
-
-#endif
-
-#endif
-
diff --git a/src/gui/inputmethod/qinputcontextfactory.cpp b/src/gui/inputmethod/qinputcontextfactory.cpp
deleted file mode 100644
index 636e9d5c52..0000000000
--- a/src/gui/inputmethod/qinputcontextfactory.cpp
+++ /dev/null
@@ -1,354 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Implementation of QInputContextFactory class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#include "qinputcontextfactory.h"
-
-#ifndef QT_NO_IM
-
-#include "qcoreapplication.h"
-#include "qinputcontext.h"
-#include "qinputcontextplugin.h"
-
-#ifdef Q_WS_X11
-#include "private/qt_x11_p.h"
-#include "qximinputcontext_p.h"
-#endif
-#ifdef Q_WS_WIN
-#include "qwininputcontext_p.h"
-#endif
-#ifdef Q_WS_MAC
-#include "qmacinputcontext_p.h"
-#endif
-#ifdef Q_WS_S60
-#include "qcoefepinputcontext_p.h"
-#include "AknInputLanguageInfo.h"
-#endif
-
-#include "private/qfactoryloader_p.h"
-#include "qmutex.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_LIBRARY
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QInputContextFactoryInterface_iid, QLatin1String("/inputmethods")))
-#endif
-
-/*!
- \class QInputContextFactory
- \brief The QInputContextFactory class creates QInputContext objects.
-
-
- The input context factory creates a QInputContext object for a
- given key with QInputContextFactory::create().
-
- The input contexts are either built-in or dynamically loaded from
- an input context plugin (see QInputContextPlugin).
-
- keys() returns a list of valid keys. The
- keys are the names used, for example, to identify and specify
- input methods for the input method switching mechanism. The names
- have to be consistent with QInputContext::identifierName(), and
- may only contain ASCII characters.
-
- A key can be used to retrieve the associated input context's
- supported languages using languages(). You
- can retrieve the input context's description using
- description() and finally you can get a user
- friendly internationalized name of the QInputContext object
- specified by the key using displayName().
-
- \legalese
- Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-
- This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
- license. You may use this file under your Qt license. Following
- description is copied from their original file headers. Contact
- immodule-qt@freedesktop.org if any conditions of this licensing are
- not clear to you.
- \endlegalese
-
- \sa QInputContext, QInputContextPlugin
-*/
-
-/*!
- Creates and returns a QInputContext object for the input context
- specified by \a key with the given \a parent. Keys are case
- sensitive.
-
- \sa keys()
-*/
-QInputContext *QInputContextFactory::create( const QString& key, QObject *parent )
-{
- QInputContext *result = 0;
-#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
- if (key == QLatin1String("xim")) {
- result = new QXIMInputContext;
- }
-#endif
-#if defined(Q_WS_WIN)
- if (key == QLatin1String("win")) {
- result = new QWinInputContext;
- }
-#endif
-#if defined(Q_WS_MAC)
- if (key == QLatin1String("mac")) {
- result = new QMacInputContext;
- }
-#endif
-#if defined(Q_WS_S60)
- if (key == QLatin1String("coefep")) {
- result = new QCoeFepInputContext;
- }
-#endif
-#ifdef QT_NO_LIBRARY
- Q_UNUSED(key);
-#else
- if (QInputContextFactoryInterface *factory =
- qobject_cast<QInputContextFactoryInterface*>(loader()->instance(key))) {
- result = factory->create(key);
- }
-#endif
- if (result)
- result->setParent(parent);
- return result;
-}
-
-
-/*!
- Returns the list of keys this factory can create input contexts
- for.
-
- The keys are the names used, for example, to identify and specify
- input methods for the input method switching mechanism. The names
- have to be consistent with QInputContext::identifierName(), and
- may only contain ASCII characters.
-
- \sa create(), displayName(), QInputContext::identifierName()
-*/
-QStringList QInputContextFactory::keys()
-{
- QStringList result;
-#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
- result << QLatin1String("xim");
-#endif
-#if defined(Q_WS_WIN) && !defined(QT_NO_XIM)
- result << QLatin1String("win");
-#endif
-#if defined(Q_WS_MAC)
- result << QLatin1String("mac");
-#endif
-#if defined(Q_WS_S60)
- result << QLatin1String("coefep");
-#endif
-#ifndef QT_NO_LIBRARY
- result += loader()->keys();
-#endif // QT_NO_LIBRARY
- return result;
-}
-
-#if defined(Q_WS_S60)
-/*!
- \internal
-
- This function contains pure Symbian exception handling code for
- getting S60 language list.
- Returned object ownership is transferred to caller.
-*/
-static CAknInputLanguageList* s60LangListL()
-{
- CAknInputLanguageInfo *langInfo = AknInputLanguageInfoFactory::CreateInputLanguageInfoL();
- CleanupStack::PushL(langInfo);
- // In rare phone there is more than 7 languages installed -> use 7 as an array granularity
- CAknInputLanguageList *langList = new (ELeave) CAknInputLanguageList(7);
- CleanupStack::PushL(langList);
- langInfo->AppendAvailableLanguagesL(langList);
- CleanupStack::Pop(langList);
- CleanupStack::PopAndDestroy(langInfo);
- return langList;
-}
-
-/*!
- \internal
-
- This function utility function return S60 language list.
- Returned object ownership is transferred to caller.
-*/
-static CAknInputLanguageList* s60LangList()
-{
- CAknInputLanguageList *langList = NULL;
- TRAP_IGNORE(langList = s60LangListL());
- q_check_ptr(langList);
- return langList;
-}
-#endif
-
-/*!
- Returns the languages supported by the QInputContext object
- specified by \a key.
-
- The languages are expressed as language code (e.g. "zh_CN",
- "zh_TW", "zh_HK", "ja", "ko", ...). An input context that supports
- multiple languages can return all supported languages as a
- QStringList. The name has to be consistent with
- QInputContext::language().
-
- This information may be used to optimize a user interface.
-
- \sa keys(), QInputContext::language(), QLocale
-*/
-QStringList QInputContextFactory::languages( const QString &key )
-{
- QStringList result;
-#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
- if (key == QLatin1String("xim"))
- return QStringList(QString());
-#endif
-#if defined(Q_WS_WIN)
- if (key == QLatin1String("win"))
- return QStringList(QString());
-#endif
-#if defined(Q_WS_MAC)
- if (key == QLatin1String("mac"))
- return QStringList(QString());
-#endif
-#if defined(Q_WS_S60)
- if (key == QLatin1String("coefep"))
- {
- CAknInputLanguageList *langList = s60LangList();
- int count = langList->Count();
- for (int i = 0; i < count; ++i)
- {
- result.append(QString(qt_symbianLocaleName(langList->At(i)->LanguageCode())));
- }
- delete langList;
- }
-#endif
-#if defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
- Q_UNUSED(key);
-#else
- if (QInputContextFactoryInterface *factory =
- qobject_cast<QInputContextFactoryInterface*>(loader()->instance(key)))
- result = factory->languages(key);
-#endif // QT_NO_LIBRARY
- return result;
-}
-
-/*!
- Returns a user friendly internationalized name of the
- QInputContext object specified by \a key. You can, for example,
- use this name in a menu.
-
- \sa keys(), QInputContext::identifierName()
-*/
-QString QInputContextFactory::displayName( const QString &key )
-{
- QString result;
-#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
- if (key == QLatin1String("xim"))
- return QInputContext::tr( "XIM" );
-#endif
-#ifdef Q_WS_S60
- if (key == QLatin1String("coefep"))
- return QInputContext::tr( "FEP" );
-#endif
-#if defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
- Q_UNUSED(key);
-#else
- if (QInputContextFactoryInterface *factory =
- qobject_cast<QInputContextFactoryInterface*>(loader()->instance(key)))
- return factory->displayName(key);
-#endif // QT_NO_LIBRARY
- return QString();
-}
-
-/*!
- Returns an internationalized brief description of the QInputContext
- object specified by \a key. You can, for example, use this
- description in a user interface.
-
- \sa keys(), displayName()
-*/
-QString QInputContextFactory::description( const QString &key )
-{
-#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
- if (key == QLatin1String("xim"))
- return QInputContext::tr( "XIM input method" );
-#endif
-#if defined(Q_WS_WIN) && !defined(QT_NO_XIM)
- if (key == QLatin1String("win"))
- return QInputContext::tr( "Windows input method" );
-#endif
-#if defined(Q_WS_MAC)
- if (key == QLatin1String("mac"))
- return QInputContext::tr( "Mac OS X input method" );
-#endif
-#if defined(Q_WS_S60)
- if (key == QLatin1String("coefep"))
- return QInputContext::tr( "S60 FEP input method" );
-#endif
-#if defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
- Q_UNUSED(key);
-#else
- if (QInputContextFactoryInterface *factory =
- qobject_cast<QInputContextFactoryInterface*>(loader()->instance(key)))
- return factory->description(key);
-#endif // QT_NO_LIBRARY
- return QString();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_IM
diff --git a/src/gui/inputmethod/qinputcontextfactory.h b/src/gui/inputmethod/qinputcontextfactory.h
deleted file mode 100644
index 2382857ae1..0000000000
--- a/src/gui/inputmethod/qinputcontextfactory.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Definition of QInputContextFactory class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#ifndef QINPUTCONTEXTFACTORY_H
-#define QINPUTCONTEXTFACTORY_H
-
-#include <QtCore/qstringlist.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_IM
-
-class QInputContext;
-class QWidget;
-
-class Q_GUI_EXPORT QInputContextFactory
-{
-public:
- static QStringList keys();
- static QInputContext *create( const QString &key, QObject *parent ); // should be a toplevel widget
- static QStringList languages( const QString &key );
- static QString displayName( const QString &key );
- static QString description( const QString &key );
-};
-
-#endif // QT_NO_IM
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QINPUTCONTEXTFACTORY_H
diff --git a/src/gui/inputmethod/qinputcontextplugin.cpp b/src/gui/inputmethod/qinputcontextplugin.cpp
deleted file mode 100644
index a83359324a..0000000000
--- a/src/gui/inputmethod/qinputcontextplugin.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Implementation of QInputContext class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#include "qinputcontextplugin.h"
-
-#ifndef QT_NO_IM
-#ifndef QT_NO_LIBRARY
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QInputContextPlugin
- \brief The QInputContextPlugin class provides an abstract base for custom QInputContext plugins.
-
- \reentrant
- \ingroup plugins
-
- The input context plugin is a simple plugin interface that makes it
- easy to create custom input contexts that can be loaded dynamically
- into applications.
-
- To create an input context plugin you subclass this base class,
- reimplement the pure virtual functions keys(), create(),
- languages(), displayName(), and description(), and export the
- class with the Q_EXPORT_PLUGIN2() macro.
-
- \legalese
- Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-
- This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
- license. You may use this file under your Qt license. Following
- description is copied from their original file headers. Contact
- immodule-qt@freedesktop.org if any conditions of this licensing are
- not clear to you.
- \endlegalese
-
- \sa QInputContext, {How to Create Qt Plugins}
-*/
-
-/*!
- \fn QStringList QInputContextPlugin::keys() const
-
- Returns the list of QInputContext keys this plugin provides.
-
- These keys are usually the class names of the custom input context
- that are implemented in the plugin. The names are used, for
- example, to identify and specify input methods for the input
- method switching mechanism. They have to be consistent with
- QInputContext::identifierName(), and may only contain ASCII
- characters.
-
- \sa create(), displayName(), QInputContext::identifierName()
-*/
-
-/*!
- \fn QInputContext* QInputContextPlugin::create( const QString& key )
-
- Creates and returns a QInputContext object for the input context
- key \a key. The input context key is usually the class name of
- the required input method.
-
- \sa keys()
-*/
-
-/*!
- \fn QStringList QInputContextPlugin::languages(const QString &key)
-
- Returns the languages supported by the QInputContext object
- specified by \a key.
-
- The languages are expressed as language code (e.g. "zh_CN",
- "zh_TW", "zh_HK", "ja", "ko", ...). An input context that supports
- multiple languages can return all supported languages as
- QStringList. The name has to be consistent with
- QInputContext::language().
-
- This information may be used to optimize user interface.
-
- \sa keys(), QInputContext::language(), QLocale
-*/
-
-/*!
- \fn QString QInputContextPlugin::displayName(const QString &key)
-
- Returns a user friendly internationalized name of the
- QInputContext object specified by \a key. You can, for example,
- use this name in a menu.
-
- \sa keys(), QInputContext::identifierName()
-*/
-
-/*!
- \fn QString QInputContextPlugin::description(const QString &key)
-
- Returns an internationalized brief description of the QInputContext
- object specified by \a key. You can, for example, use this
- description in a user interface.
-
- \sa keys(), displayName()
-*/
-
-
-/*!
- Constructs a input context plugin with the given \a parent. This
- is invoked automatically by the Q_EXPORT_PLUGIN2() macro.
-*/
-QInputContextPlugin::QInputContextPlugin(QObject *parent)
- :QObject(parent)
-{
-}
-
-/*!
- Destroys the input context plugin.
-
- You never have to call this explicitly. Qt destroys a plugin
- automatically when it's no longer used.
-*/
-QInputContextPlugin::~QInputContextPlugin()
-{
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_LIBRARY
-
-#endif // QT_NO_IM
diff --git a/src/gui/inputmethod/qinputcontextplugin.h b/src/gui/inputmethod/qinputcontextplugin.h
deleted file mode 100644
index 3038298792..0000000000
--- a/src/gui/inputmethod/qinputcontextplugin.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Definition of QInputContextPlugin class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#ifndef QINPUTCONTEXTPLUGIN_H
-#define QINPUTCONTEXTPLUGIN_H
-
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-#include <QtCore/qstringlist.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_IM)
-
-class QInputContext;
-class QInputContextPluginPrivate;
-
-struct Q_GUI_EXPORT QInputContextFactoryInterface : public QFactoryInterface
-{
- virtual QInputContext *create( const QString &key ) = 0;
- virtual QStringList languages( const QString &key ) = 0;
- virtual QString displayName( const QString &key ) = 0;
- virtual QString description( const QString &key ) = 0;
-};
-
-#define QInputContextFactoryInterface_iid "com.trolltech.Qt.QInputContextFactoryInterface"
-Q_DECLARE_INTERFACE(QInputContextFactoryInterface, QInputContextFactoryInterface_iid)
-
-class Q_GUI_EXPORT QInputContextPlugin : public QObject, public QInputContextFactoryInterface
-{
- Q_OBJECT
- Q_INTERFACES(QInputContextFactoryInterface:QFactoryInterface)
-public:
- explicit QInputContextPlugin(QObject *parent = 0);
- ~QInputContextPlugin();
-
- virtual QStringList keys() const = 0;
- virtual QInputContext *create( const QString &key ) = 0;
- virtual QStringList languages( const QString &key ) = 0;
- virtual QString displayName( const QString &key ) = 0;
- virtual QString description( const QString &key ) = 0;
-};
-
-#endif // QT_NO_IM
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QINPUTCONTEXTPLUGIN_H
diff --git a/src/gui/inputmethod/qmacinputcontext_mac.cpp b/src/gui/inputmethod/qmacinputcontext_mac.cpp
deleted file mode 100644
index a1ba39c1d6..0000000000
--- a/src/gui/inputmethod/qmacinputcontext_mac.cpp
+++ /dev/null
@@ -1,378 +0,0 @@
-/****************************************************************************
-**
-** 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 <qvarlengtharray.h>
-#include <qwidget.h>
-#include <private/qmacinputcontext_p.h>
-#include "qtextformat.h"
-#include <qdebug.h>
-#include <private/qapplication_p.h>
-#include <private/qkeymapper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
-# define typeRefCon typeSInt32
-# define typeByteCount typeSInt32
-#endif
-
-QMacInputContext::QMacInputContext(QObject *parent)
- : QInputContext(parent), composing(false), recursionGuard(false), textDocument(0),
- keydownEvent(0)
-{
-// createTextDocument();
-}
-
-QMacInputContext::~QMacInputContext()
-{
-#ifndef QT_MAC_USE_COCOA
- if(textDocument)
- DeleteTSMDocument(textDocument);
-#endif
-}
-
-void
-QMacInputContext::createTextDocument()
-{
-#ifndef QT_MAC_USE_COCOA
- if(!textDocument) {
- InterfaceTypeList itl = { kUnicodeDocument };
- NewTSMDocument(1, itl, &textDocument, SRefCon(this));
- }
-#endif
-}
-
-
-QString QMacInputContext::language()
-{
- return QString();
-}
-
-
-void QMacInputContext::mouseHandler(int pos, QMouseEvent *e)
-{
-#ifndef QT_MAC_USE_COCOA
- if(e->type() != QEvent::MouseButtonPress)
- return;
-
- if (!composing)
- return;
- if (pos < 0 || pos > currentText.length())
- reset();
- // ##### handle mouse position
-#else
- Q_UNUSED(pos);
- Q_UNUSED(e);
-#endif
-}
-
-#if !defined QT_MAC_USE_COCOA
-
-static QTextFormat qt_mac_compose_format()
-{
- QTextCharFormat ret;
- ret.setFontUnderline(true);
- return ret;
-}
-
-void QMacInputContext::reset()
-{
- if (recursionGuard)
- return;
- if (!currentText.isEmpty()){
- QInputMethodEvent e;
- e.setCommitString(currentText);
- qt_sendSpontaneousEvent(focusWidget(), &e);
- currentText = QString();
- }
- recursionGuard = true;
- createTextDocument();
- composing = false;
- ActivateTSMDocument(textDocument);
- FixTSMDocument(textDocument);
- recursionGuard = false;
-}
-
-bool QMacInputContext::isComposing() const
-{
- return composing;
-}
-#endif
-
-void QMacInputContext::setFocusWidget(QWidget *w)
-{
- createTextDocument();
-#ifndef QT_MAC_USE_COCOA
- if(w)
- ActivateTSMDocument(textDocument);
- else
- DeactivateTSMDocument(textDocument);
-#endif
- QInputContext::setFocusWidget(w);
-}
-
-
-#ifndef QT_MAC_USE_COCOA
-static EventTypeSpec input_events[] = {
- { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent },
- { kEventClassTextInput, kEventTextInputOffsetToPos },
- { kEventClassTextInput, kEventTextInputUpdateActiveInputArea }
-};
-static EventHandlerUPP input_proc_handlerUPP = 0;
-static EventHandlerRef input_proc_handler = 0;
-#endif
-
-void
-QMacInputContext::initialize()
-{
-#ifndef QT_MAC_USE_COCOA
- if(!input_proc_handler) {
- input_proc_handlerUPP = NewEventHandlerUPP(QMacInputContext::globalEventProcessor);
- InstallEventHandler(GetApplicationEventTarget(), input_proc_handlerUPP,
- GetEventTypeCount(input_events), input_events,
- 0, &input_proc_handler);
- }
-#endif
-}
-
-void
-QMacInputContext::cleanup()
-{
-#ifndef QT_MAC_USE_COCOA
- if(input_proc_handler) {
- RemoveEventHandler(input_proc_handler);
- input_proc_handler = 0;
- }
- if(input_proc_handlerUPP) {
- DisposeEventHandlerUPP(input_proc_handlerUPP);
- input_proc_handlerUPP = 0;
- }
-#endif
-}
-
-void QMacInputContext::setLastKeydownEvent(EventRef event)
-{
- EventRef tmpEvent = keydownEvent;
- keydownEvent = event;
- if (keydownEvent)
- RetainEvent(keydownEvent);
- if (tmpEvent)
- ReleaseEvent(tmpEvent);
-}
-
-OSStatus
-QMacInputContext::globalEventProcessor(EventHandlerCallRef, EventRef event, void *)
-{
-#ifndef QT_MAC_USE_COCOA
- QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-
- SRefCon refcon = 0;
- GetEventParameter(event, kEventParamTextInputSendRefCon, typeRefCon, 0,
- sizeof(refcon), 0, &refcon);
- QMacInputContext *context = reinterpret_cast<QMacInputContext*>(refcon);
-
- bool handled_event=true;
- UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
- switch(eclass) {
- case kEventClassTextInput: {
- handled_event = false;
- QWidget *widget = QApplicationPrivate::focus_widget;
- bool canCompose = widget && (!context || widget->inputContext() == context)
- && !(widget->inputMethodHints() & Qt::ImhDigitsOnly
- || widget->inputMethodHints() & Qt::ImhFormattedNumbersOnly
- || widget->inputMethodHints() & Qt::ImhHiddenText);
- if(!canCompose) {
- handled_event = false;
- } else if(ekind == kEventTextInputOffsetToPos) {
- if(!widget->testAttribute(Qt::WA_InputMethodEnabled)) {
- handled_event = false;
- break;
- }
-
- QRect mr(widget->inputMethodQuery(Qt::ImMicroFocus).toRect());
- QPoint mp(widget->mapToGlobal(QPoint(mr.topLeft())));
- Point pt;
- pt.h = mp.x();
- pt.v = mp.y() + mr.height();
- SetEventParameter(event, kEventParamTextInputReplyPoint, typeQDPoint,
- sizeof(pt), &pt);
- handled_event = true;
- } else if(ekind == kEventTextInputUpdateActiveInputArea) {
- if(!widget->testAttribute(Qt::WA_InputMethodEnabled)) {
- handled_event = false;
- break;
- }
-
- if (context->recursionGuard)
- break;
-
- ByteCount unilen = 0;
- GetEventParameter(event, kEventParamTextInputSendText, typeUnicodeText,
- 0, 0, &unilen, 0);
- UniChar *unicode = (UniChar*)NewPtr(unilen);
- GetEventParameter(event, kEventParamTextInputSendText, typeUnicodeText,
- 0, unilen, 0, unicode);
- QString text((QChar*)unicode, unilen / sizeof(UniChar));
- DisposePtr((char*)unicode);
-
- ByteCount fixed_length = 0;
- GetEventParameter(event, kEventParamTextInputSendFixLen, typeByteCount, 0,
- sizeof(fixed_length), 0, &fixed_length);
- if(fixed_length == ULONG_MAX || fixed_length == unilen) {
- QInputMethodEvent e;
- e.setCommitString(text);
- context->currentText = QString();
- qt_sendSpontaneousEvent(context->focusWidget(), &e);
- handled_event = true;
- context->reset();
- } else {
- ByteCount rngSize = 0;
- OSStatus err = GetEventParameter(event, kEventParamTextInputSendHiliteRng, typeTextRangeArray, 0,
- 0, &rngSize, 0);
- QVarLengthArray<TextRangeArray> highlight(rngSize);
- if (noErr == err) {
- err = GetEventParameter(event, kEventParamTextInputSendHiliteRng, typeTextRangeArray, 0,
- rngSize, &rngSize, highlight.data());
- }
- context->composing = true;
- if(fixed_length > 0) {
- const int qFixedLength = fixed_length / sizeof(UniChar);
- QList<QInputMethodEvent::Attribute> attrs;
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- qFixedLength, text.length()-qFixedLength,
- qt_mac_compose_format());
- QInputMethodEvent e(text, attrs);
- context->currentText = text;
- e.setCommitString(text.left(qFixedLength), 0, qFixedLength);
- qt_sendSpontaneousEvent(widget, &e);
- handled_event = true;
- } else {
- /* Apple's enums that they have removed from Tiger :(
- enum {
- kCaretPosition = 1,
- kRawText = 2,
- kSelectedRawText = 3,
- kConvertedText = 4,
- kSelectedConvertedText = 5,
- kBlockFillText = 6,
- kOutlineText = 7,
- kSelectedText = 8
- };
- */
-#ifndef kConvertedText
-#define kConvertedText 4
-#endif
-#ifndef kCaretPosition
-#define kCaretPosition 1
-#endif
- QList<QInputMethodEvent::Attribute> attrs;
- if (!highlight.isEmpty()) {
- TextRangeArray *data = highlight.data();
- for (int i = 0; i < data->fNumOfRanges; ++i) {
- int start = data->fRange[i].fStart / sizeof(UniChar);
- int len = (data->fRange[i].fEnd - data->fRange[i].fStart) / sizeof(UniChar);
- if (data->fRange[i].fHiliteStyle == kCaretPosition) {
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, start, 0, QVariant());
- continue;
- }
- QTextCharFormat format;
- format.setFontUnderline(true);
- if (data->fRange[i].fHiliteStyle == kConvertedText)
- format.setUnderlineColor(Qt::gray);
- else
- format.setUnderlineColor(Qt::black);
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, start, len, format);
- }
- } else {
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- 0, text.length(), qt_mac_compose_format());
- }
- context->currentText = text;
- QInputMethodEvent e(text, attrs);
- qt_sendSpontaneousEvent(widget, &e);
- handled_event = true;
- }
- }
-#if 0
- if(!context->composing)
- handled_event = false;
-#endif
-
- extern bool qt_mac_eat_unicode_key; //qapplication_mac.cpp
- qt_mac_eat_unicode_key = handled_event;
- } else if(ekind == kEventTextInputUnicodeForKeyEvent) {
- EventRef key_ev = 0;
- GetEventParameter(event, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0,
- sizeof(key_ev), 0, &key_ev);
- QString text;
- ByteCount unilen = 0;
- if(GetEventParameter(key_ev, kEventParamKeyUnicodes, typeUnicodeText, 0, 0, &unilen, 0) == noErr) {
- UniChar *unicode = (UniChar*)NewPtr(unilen);
- GetEventParameter(key_ev, kEventParamKeyUnicodes, typeUnicodeText, 0, unilen, 0, unicode);
- text = QString((QChar*)unicode, unilen / sizeof(UniChar));
- DisposePtr((char*)unicode);
- }
- unsigned char chr = 0;
- GetEventParameter(key_ev, kEventParamKeyMacCharCodes, typeChar, 0, sizeof(chr), 0, &chr);
- if(!chr || chr >= 128 || (text.length() > 0 && (text.length() > 1 || text.at(0) != QLatin1Char(chr))))
- handled_event = !widget->testAttribute(Qt::WA_InputMethodEnabled);
- QMacInputContext *context = qobject_cast<QMacInputContext*>(qApp->inputContext());
- if (context && context->lastKeydownEvent()) {
- qt_keymapper_private()->translateKeyEvent(widget, 0, context->lastKeydownEvent(),
- 0, false);
- context->setLastKeydownEvent(0);
- }
- }
- break; }
- default:
- break;
- }
- if(!handled_event) //let the event go through
- return eventNotHandledErr;
-#else
- Q_UNUSED(event);
-#endif
- return noErr; //we eat the event
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/inputmethod/qmacinputcontext_p.h b/src/gui/inputmethod/qmacinputcontext_p.h
deleted file mode 100644
index c4575a3c60..0000000000
--- a/src/gui/inputmethod/qmacinputcontext_p.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** 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 QMACINPUTCONTEXT_P_H
-#define QMACINPUTCONTEXT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qinputcontext.h"
-#include "private/qt_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class Q_GUI_EXPORT QMacInputContext : public QInputContext
-{
- Q_OBJECT
- //Q_DECLARE_PRIVATE(QMacInputContext)
- void createTextDocument();
-public:
- explicit QMacInputContext(QObject* parent = 0);
- virtual ~QMacInputContext();
-
- virtual void setFocusWidget(QWidget *w);
- virtual QString identifierName() { return QLatin1String("mac"); }
- virtual QString language();
-
- virtual void reset();
-
- virtual bool isComposing() const;
-
- static OSStatus globalEventProcessor(EventHandlerCallRef, EventRef, void *);
- static void initialize();
- static void cleanup();
-
- EventRef lastKeydownEvent() { return keydownEvent; }
- void setLastKeydownEvent(EventRef);
-
-protected:
- void mouseHandler(int pos, QMouseEvent *);
-private:
- bool composing;
- bool recursionGuard;
- TSMDocumentID textDocument;
- QString currentText;
- EventRef keydownEvent;
-};
-
-QT_END_NAMESPACE
-
-#endif // QMACINPUTCONTEXT_P_H
diff --git a/src/gui/inputmethod/qwininputcontext_p.h b/src/gui/inputmethod/qwininputcontext_p.h
deleted file mode 100644
index dc87000b6c..0000000000
--- a/src/gui/inputmethod/qwininputcontext_p.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** 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 QWININPUTCONTEXT_P_H
-#define QWININPUTCONTEXT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of qinputcontext.cpp. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qinputcontext.h"
-#include "QtCore/qt_windows.h"
-
-#if !defined(IMR_RECONVERTSTRING)
-typedef struct tagRECONVERTSTRING {
- DWORD dwSize;
- DWORD dwVersion;
- DWORD dwStrLen;
- DWORD dwStrOffset;
- DWORD dwCompStrLen;
- DWORD dwCompStrOffset;
- DWORD dwTargetStrLen;
- DWORD dwTargetStrOffset;
-} RECONVERTSTRING, *PRECONVERTSTRING;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QWinInputContext : public QInputContext
-{
- Q_OBJECT
-public:
- explicit QWinInputContext(QObject* parent = 0);
- virtual ~QWinInputContext();
-
- virtual QString identifierName() { return QLatin1String("win"); }
- virtual QString language();
-
- virtual void reset();
- virtual void update();
-
- virtual void mouseHandler(int x, QMouseEvent *event);
- virtual bool isComposing() const;
-
- virtual void setFocusWidget(QWidget *w);
-
- bool startComposition();
- bool endComposition();
- bool composition(LPARAM lparam);
- int reconvertString(RECONVERTSTRING *reconv);
-
- static void TranslateMessage(const MSG *msg);
- static LRESULT DefWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
-
- static void updateImeStatus(QWidget *w, bool hasFocus);
- static void enablePopupChild(QWidget *w, bool e);
- static void enable(QWidget *w, bool e);
-
-private:
- void init();
- bool recursionGuard;
-};
-
-QT_END_NAMESPACE
-
-#endif // QWININPUTCONTEXT_P_H
diff --git a/src/gui/inputmethod/qwininputcontext_win.cpp b/src/gui/inputmethod/qwininputcontext_win.cpp
deleted file mode 100644
index 4289cf4191..0000000000
--- a/src/gui/inputmethod/qwininputcontext_win.cpp
+++ /dev/null
@@ -1,847 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwininputcontext_p.h"
-#include "qinputcontext_p.h"
-
-#include "qfont.h"
-#include "qwidget.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qtextformat.h"
-#include "qtextboundaryfinder.h"
-
-//#define Q_IME_DEBUG
-
-#ifdef Q_IME_DEBUG
-#include "qdebug.h"
-#endif
-
-#if defined(Q_WS_WINCE)
-extern void qt_wince_show_SIP(bool show); // defined in qguifunctions_wince.cpp
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-
-DEFINE_GUID(IID_IActiveIMMApp,
-0x08c0e040, 0x62d1, 0x11d1, 0x93, 0x26, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e);
-
-
-
-DEFINE_GUID(CLSID_CActiveIMM,
-0x4955DD33, 0xB159, 0x11d0, 0x8F, 0xCF, 0x0, 0xAA, 0x00, 0x6B, 0xCC, 0x59);
-
-
-
-DEFINE_GUID(IID_IActiveIMMMessagePumpOwner,
-0xb5cf2cfa, 0x8aeb, 0x11d1, 0x93, 0x64, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e);
-
-
-
-interface IEnumRegisterWordW;
-interface IEnumInputContext;
-
-
-bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-
-#define IFMETHOD HRESULT STDMETHODCALLTYPE
-
-interface IActiveIMMApp : public IUnknown
-{
-public:
- virtual IFMETHOD AssociateContext(HWND hWnd, HIMC hIME, HIMC __RPC_FAR *phPrev) = 0;
- virtual IFMETHOD dummy_ConfigureIMEA() = 0;
- virtual IFMETHOD ConfigureIMEW(HKL hKL, HWND hWnd, DWORD dwMode, REGISTERWORDW __RPC_FAR *pData) = 0;
- virtual IFMETHOD CreateContext(HIMC __RPC_FAR *phIMC) = 0;
- virtual IFMETHOD DestroyContext(HIMC hIME) = 0;
- virtual IFMETHOD dummy_EnumRegisterWordA() = 0;
- virtual IFMETHOD EnumRegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister, LPVOID pData,
- IEnumRegisterWordW __RPC_FAR *__RPC_FAR *pEnum) = 0;
- virtual IFMETHOD dummy_EscapeA() = 0;
- virtual IFMETHOD EscapeW(HKL hKL, HIMC hIMC, UINT uEscape, LPVOID pData, LRESULT __RPC_FAR *plResult) = 0;
- virtual IFMETHOD dummy_GetCandidateListA() = 0;
- virtual IFMETHOD GetCandidateListW(HIMC hIMC, DWORD dwIndex, UINT uBufLen, CANDIDATELIST __RPC_FAR *pCandList,
- UINT __RPC_FAR *puCopied) = 0;
- virtual IFMETHOD dummy_GetCandidateListCountA() = 0;
- virtual IFMETHOD GetCandidateListCountW(HIMC hIMC, DWORD __RPC_FAR *pdwListSize, DWORD __RPC_FAR *pdwBufLen) = 0;
- virtual IFMETHOD GetCandidateWindow(HIMC hIMC, DWORD dwIndex, CANDIDATEFORM __RPC_FAR *pCandidate) = 0;
- virtual IFMETHOD dummy_GetCompositionFontA() = 0;
- virtual IFMETHOD GetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0;
- virtual IFMETHOD dummy_GetCompositionStringA() = 0;
- virtual IFMETHOD GetCompositionStringW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LONG __RPC_FAR *plCopied, LPVOID pBuf) = 0;
- virtual IFMETHOD GetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0;
- virtual IFMETHOD GetContext(HWND hWnd, HIMC __RPC_FAR *phIMC) = 0;
- virtual IFMETHOD dummy_GetConversionListA() = 0;
- virtual IFMETHOD GetConversionListW(HKL hKL, HIMC hIMC, LPWSTR pSrc, UINT uBufLen, UINT uFlag,
- CANDIDATELIST __RPC_FAR *pDst, UINT __RPC_FAR *puCopied) = 0;
- virtual IFMETHOD GetConversionStatus(HIMC hIMC, DWORD __RPC_FAR *pfdwConversion, DWORD __RPC_FAR *pfdwSentence) = 0;
- virtual IFMETHOD GetDefaultIMEWnd(HWND hWnd, HWND __RPC_FAR *phDefWnd) = 0;
- virtual IFMETHOD dummy_GetDescriptionA() = 0;
- virtual IFMETHOD GetDescriptionW(HKL hKL, UINT uBufLen, LPWSTR szDescription, UINT __RPC_FAR *puCopied) = 0;
- virtual IFMETHOD dummy_GetGuideLineA() = 0;
- virtual IFMETHOD GetGuideLineW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LPWSTR pBuf, DWORD __RPC_FAR *pdwResult) = 0;
- virtual IFMETHOD dummy_GetIMEFileNameA() = 0;
- virtual IFMETHOD GetIMEFileNameW(HKL hKL, UINT uBufLen, LPWSTR szFileName, UINT __RPC_FAR *puCopied) = 0;
- virtual IFMETHOD GetOpenStatus(HIMC hIMC) = 0;
- virtual IFMETHOD GetProperty(HKL hKL, DWORD fdwIndex, DWORD __RPC_FAR *pdwProperty) = 0;
- virtual IFMETHOD dummy_GetRegisterWordStyleA() = 0;
- virtual IFMETHOD GetRegisterWordStyleW(HKL hKL, UINT nItem, STYLEBUFW __RPC_FAR *pStyleBuf, UINT __RPC_FAR *puCopied) = 0;
- virtual IFMETHOD GetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0;
- virtual IFMETHOD GetVirtualKey(HWND hWnd, UINT __RPC_FAR *puVirtualKey) = 0;
- virtual IFMETHOD dummy_InstallIMEA() = 0;
- virtual IFMETHOD InstallIMEW(LPWSTR szIMEFileName, LPWSTR szLayoutText, HKL __RPC_FAR *phKL) = 0;
- virtual IFMETHOD IsIME(HKL hKL) = 0;
- virtual IFMETHOD dummy_IsUIMessageA() = 0;
- virtual IFMETHOD IsUIMessageW(HWND hWndIME, UINT msg, WPARAM wParam, LPARAM lParam) = 0;
- virtual IFMETHOD NotifyIME(HIMC hIMC, DWORD dwAction, DWORD dwIndex, DWORD dwValue) = 0;
- virtual IFMETHOD dummy_RegisterWordA() = 0;
- virtual IFMETHOD RegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister) = 0;
- virtual IFMETHOD ReleaseContext(HWND hWnd, HIMC hIMC) = 0;
- virtual IFMETHOD SetCandidateWindow(HIMC hIMC, CANDIDATEFORM __RPC_FAR *pCandidate) = 0;
- virtual IFMETHOD SetCompositionFontA(HIMC hIMC, LOGFONTA __RPC_FAR *plf) = 0;
- virtual IFMETHOD SetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0;
- virtual IFMETHOD dummy_SetCompositionStringA() = 0;
- virtual IFMETHOD SetCompositionStringW(HIMC hIMC, DWORD dwIndex, LPVOID pComp, DWORD dwCompLen,
- LPVOID pRead, DWORD dwReadLen) = 0;
- virtual IFMETHOD SetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0;
- virtual IFMETHOD SetConversionStatus(HIMC hIMC, DWORD fdwConversion, DWORD fdwSentence) = 0;
- virtual IFMETHOD SetOpenStatus(HIMC hIMC, BOOL fOpen) = 0;
- virtual IFMETHOD SetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0;
- virtual IFMETHOD SimulateHotKey(HWND hWnd, DWORD dwHotKeyID) = 0;
- virtual IFMETHOD dummy_UnregisterWordA() = 0;
- virtual IFMETHOD UnregisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szUnregister) = 0;
- virtual IFMETHOD Activate(BOOL fRestoreLayout) = 0;
- virtual IFMETHOD Deactivate(void) = 0;
- virtual IFMETHOD OnDefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, LRESULT __RPC_FAR *plResult) = 0;
- virtual IFMETHOD FilterClientWindows(ATOM __RPC_FAR *aaClassList, UINT uSize) = 0;
- virtual IFMETHOD dummy_GetCodePageA() = 0;
- virtual IFMETHOD GetLangId(HKL hKL, LANGID __RPC_FAR *plid) = 0;
- virtual IFMETHOD AssociateContextEx(HWND hWnd, HIMC hIMC, DWORD dwFlags) = 0;
- virtual IFMETHOD DisableIME(DWORD idThread) = 0;
- virtual IFMETHOD dummy_GetImeMenuItemsA() = 0;
- virtual IFMETHOD GetImeMenuItemsW(HIMC hIMC, DWORD dwFlags, DWORD dwType, /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeParentMenu,
- /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeMenu, DWORD dwSize, DWORD __RPC_FAR *pdwResult) = 0;
- virtual IFMETHOD EnumInputContext(DWORD idThread, IEnumInputContext __RPC_FAR *__RPC_FAR *ppEnum) = 0;
-};
-
-interface IActiveIMMMessagePumpOwner : public IUnknown
-{
-public:
- virtual IFMETHOD Start(void) = 0;
- virtual IFMETHOD End(void) = 0;
- virtual IFMETHOD OnTranslateMessage(const MSG __RPC_FAR *pMsg) = 0;
- virtual IFMETHOD Pause(DWORD __RPC_FAR *pdwCookie) = 0;
- virtual IFMETHOD Resume(DWORD dwCookie) = 0;
-};
-
-
-static IActiveIMMApp *aimm = 0;
-static IActiveIMMMessagePumpOwner *aimmpump = 0;
-static QString *imeComposition = 0;
-static int imePosition = -1;
-bool qt_use_rtl_extensions = false;
-static bool haveCaret = false;
-
-#ifndef LGRPID_INSTALLED
-#define LGRPID_INSTALLED 0x00000001 // installed language group ids
-#define LGRPID_SUPPORTED 0x00000002 // supported language group ids
-#endif
-
-#ifndef LGRPID_ARABIC
-#define LGRPID_WESTERN_EUROPE 0x0001 // Western Europe & U.S.
-#define LGRPID_CENTRAL_EUROPE 0x0002 // Central Europe
-#define LGRPID_BALTIC 0x0003 // Baltic
-#define LGRPID_GREEK 0x0004 // Greek
-#define LGRPID_CYRILLIC 0x0005 // Cyrillic
-#define LGRPID_TURKISH 0x0006 // Turkish
-#define LGRPID_JAPANESE 0x0007 // Japanese
-#define LGRPID_KOREAN 0x0008 // Korean
-#define LGRPID_TRADITIONAL_CHINESE 0x0009 // Traditional Chinese
-#define LGRPID_SIMPLIFIED_CHINESE 0x000a // Simplified Chinese
-#define LGRPID_THAI 0x000b // Thai
-#define LGRPID_HEBREW 0x000c // Hebrew
-#define LGRPID_ARABIC 0x000d // Arabic
-#define LGRPID_VIETNAMESE 0x000e // Vietnamese
-#define LGRPID_INDIC 0x000f // Indic
-#define LGRPID_GEORGIAN 0x0010 // Georgian
-#define LGRPID_ARMENIAN 0x0011 // Armenian
-#endif
-
-static DWORD WM_MSIME_MOUSE = 0;
-
-QWinInputContext::QWinInputContext(QObject *parent)
- : QInputContext(parent), recursionGuard(false)
-{
-#ifndef Q_WS_WINCE
- QSysInfo::WinVersion ver = QSysInfo::windowsVersion();
- if (ver & QSysInfo::WV_NT_based && ver >= QSysInfo::WV_VISTA) {
- // Since the IsValidLanguageGroup/IsValidLocale functions always return true on
- // Vista, check the Keyboard Layouts for enabling RTL.
- UINT nLayouts = GetKeyboardLayoutList(0, 0);
- if (nLayouts) {
- HKL *lpList = new HKL[nLayouts];
- GetKeyboardLayoutList(nLayouts, lpList);
- for (int i = 0; i<(int)nLayouts; i++) {
- WORD plangid = PRIMARYLANGID((quintptr)lpList[i]);
- if (plangid == LANG_ARABIC
- || plangid == LANG_HEBREW
- || plangid == LANG_FARSI
-#ifdef LANG_SYRIAC
- || plangid == LANG_SYRIAC
-#endif
- ) {
- qt_use_rtl_extensions = true;
- break;
- }
- }
- delete []lpList;
- }
- } else {
- // figure out whether a RTL language is installed
- qt_use_rtl_extensions = IsValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED)
- || IsValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED)
- || IsValidLocale(MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
- || IsValidLocale(MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
-#ifdef LANG_SYRIAC
- || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
-#endif
- || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED);
- }
-#else
- qt_use_rtl_extensions = false;
-#endif
-
- WM_MSIME_MOUSE = RegisterWindowMessage(L"MSIMEMouseOperation");
-}
-
-QWinInputContext::~QWinInputContext()
-{
- // release active input method if we have one
- if (aimm) {
- aimmpump->End();
- aimmpump->Release();
- aimm->Deactivate();
- aimm->Release();
- aimm = 0;
- aimmpump = 0;
- }
- delete imeComposition;
- imeComposition = 0;
-}
-
-static HWND getDefaultIMEWnd(HWND wnd)
-{
- HWND ime_wnd;
- if(aimm)
- aimm->GetDefaultIMEWnd(wnd, &ime_wnd);
- else
- ime_wnd = ImmGetDefaultIMEWnd(wnd);
- return ime_wnd;
-}
-
-static HIMC getContext(HWND wnd)
-{
- HIMC imc;
- if (aimm)
- aimm->GetContext(wnd, &imc);
- else
- imc = ImmGetContext(wnd);
-
- return imc;
-}
-
-static void releaseContext(HWND wnd, HIMC imc)
-{
- if (aimm)
- aimm->ReleaseContext(wnd, imc);
- else
- ImmReleaseContext(wnd, imc);
-}
-
-static void notifyIME(HIMC imc, DWORD dwAction, DWORD dwIndex, DWORD dwValue)
-{
- if (!imc)
- return;
- if (aimm)
- aimm->NotifyIME(imc, dwAction, dwIndex, dwValue);
- else
- ImmNotifyIME(imc, dwAction, dwIndex, dwValue);
-}
-
-static LONG getCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpbuf, DWORD dBufLen)
-{
- LONG len = 0;
- if (aimm)
- aimm->GetCompositionStringW(himc, dwIndex, dBufLen, &len, lpbuf);
- else
- len = ImmGetCompositionString(himc, dwIndex, lpbuf, dBufLen);
- return len;
-}
-
-static int getCursorPosition(HIMC himc)
-{
- return getCompositionString(himc, GCS_CURSORPOS, 0, 0);
-}
-
-static QString getString(HIMC himc, DWORD dwindex, int *selStart = 0, int *selLength = 0)
-{
- const int bufferSize = 256;
- wchar_t buffer[bufferSize];
- int len = getCompositionString(himc, dwindex, buffer, bufferSize * sizeof(wchar_t));
-
- if (selStart) {
- char attrbuffer[bufferSize];
- int attrlen = getCompositionString(himc, GCS_COMPATTR, attrbuffer, bufferSize);
- *selStart = attrlen+1;
- *selLength = -1;
- for (int i = 0; i < attrlen; i++) {
- if (attrbuffer[i] & ATTR_TARGET_CONVERTED) {
- *selStart = qMin(*selStart, i);
- *selLength = qMax(*selLength, i);
- }
- }
- *selLength = qMax(0, *selLength - *selStart + 1);
- }
-
- if (len <= 0)
- return QString();
-
- return QString((QChar*)buffer, len / sizeof(QChar));
-}
-
-void QWinInputContext::TranslateMessage(const MSG *msg)
-{
- if (!aimmpump || aimmpump->OnTranslateMessage(msg) != S_OK)
- ::TranslateMessage(msg);
-}
-
-LRESULT QWinInputContext::DefWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
-{
- LRESULT retval;
- if (!aimm || aimm->OnDefWindowProc(hwnd, msg, wParam, lParam, &retval) != S_OK)
- {
- retval = ::DefWindowProc(hwnd, msg, wParam, lParam);
- }
- return retval;
-}
-
-
-void QWinInputContext::update()
-{
- QWidget *w = focusWidget();
- if(!w)
- return;
-
- Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
- HIMC imc = getContext(w->effectiveWinId());
-
- if (!imc)
- return;
-
- QFont f = qvariant_cast<QFont>(w->inputMethodQuery(Qt::ImFont));
- HFONT hf;
- hf = f.handle();
-
- LOGFONT lf;
- if (GetObject(hf, sizeof(lf), &lf)) {
- if (aimm)
- aimm->SetCompositionFontW(imc, &lf);
- else
- ImmSetCompositionFont(imc, &lf);
- }
-
- QRect r = w->inputMethodQuery(Qt::ImMicroFocus).toRect();
-
- // The ime window positions are based on the WinId with active focus.
- QWidget *imeWnd = QWidget::find(::GetFocus());
- if (imeWnd && !aimm) {
- QPoint pt (r.topLeft());
- pt = w->mapToGlobal(pt);
- pt = imeWnd->mapFromGlobal(pt);
- r.moveTo(pt);
- }
-
- COMPOSITIONFORM cf;
- // ### need X-like inputStyle config settings
- cf.dwStyle = CFS_FORCE_POSITION;
- cf.ptCurrentPos.x = r.x();
- cf.ptCurrentPos.y = r.y();
-
- CANDIDATEFORM candf;
- candf.dwIndex = 0;
- candf.dwStyle = CFS_EXCLUDE;
- candf.ptCurrentPos.x = r.x();
- candf.ptCurrentPos.y = r.y() + r.height();
- candf.rcArea.left = r.x();
- candf.rcArea.top = r.y();
- candf.rcArea.right = r.x() + r.width();
- candf.rcArea.bottom = r.y() + r.height();
-
- if(haveCaret)
- SetCaretPos(r.x(), r.y());
-
- if (aimm) {
- aimm->SetCompositionWindow(imc, &cf);
- aimm->SetCandidateWindow(imc, &candf);
- } else {
- ImmSetCompositionWindow(imc, &cf);
- ImmSetCandidateWindow(imc, &candf);
- }
-
- releaseContext(w->effectiveWinId(), imc);
-}
-
-
-bool QWinInputContext::endComposition()
-{
- QWidget *fw = focusWidget();
-#ifdef Q_IME_DEBUG
- qDebug("endComposition! fw = %s", fw ? fw->className() : "(null)");
-#endif
- bool result = true;
- if(imePosition == -1 || recursionGuard)
- return result;
-
- // Googles Pinyin Input Method likes to call endComposition again
- // when we call notifyIME with CPS_CANCEL, so protect ourselves
- // against that.
- recursionGuard = true;
-
- if (fw) {
- Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
- HIMC imc = getContext(fw->effectiveWinId());
- notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
- releaseContext(fw->effectiveWinId(), imc);
- if(haveCaret) {
- DestroyCaret();
- haveCaret = false;
- }
- }
-
- if (!fw)
- fw = QApplication::focusWidget();
-
- if (fw) {
- QInputMethodEvent e;
- result = qt_sendSpontaneousEvent(fw, &e);
- }
-
- if (imeComposition)
- imeComposition->clear();
- imePosition = -1;
-
- recursionGuard = false;
-
- return result;
-}
-
-void QWinInputContext::reset()
-{
- QWidget *fw = focusWidget();
-
-#ifdef Q_IME_DEBUG
- qDebug("sending accept to focus widget %s", fw ? fw->className() : "(null)");
-#endif
-
- if (fw && imePosition != -1) {
- QInputMethodEvent e;
- if (imeComposition)
- e.setCommitString(*imeComposition);
- imePosition = -1;
- qt_sendSpontaneousEvent(fw, &e);
- }
-
- if (imeComposition)
- imeComposition->clear();
- imePosition = -1;
-
- if (fw) {
- Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
- HIMC imc = getContext(fw->effectiveWinId());
- notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
- releaseContext(fw->effectiveWinId(), imc);
- }
-
-}
-
-
-bool QWinInputContext::startComposition()
-{
-#ifdef Q_IME_DEBUG
- qDebug("startComposition");
-#endif
-
- if (!imeComposition)
- imeComposition = new QString();
-
- QWidget *fw = focusWidget();
- if (fw) {
- Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
- imePosition = 0;
- haveCaret = CreateCaret(fw->effectiveWinId(), 0, 1, 1);
- HideCaret(fw->effectiveWinId());
- update();
- }
- return fw != 0;
-}
-
-enum StandardFormat {
- PreeditFormat,
- SelectionFormat
-};
-
-bool QWinInputContext::composition(LPARAM lParam)
-{
-#ifdef Q_IME_DEBUG
- QString str;
- if (lParam & GCS_RESULTSTR)
- str += "RESULTSTR ";
- if (lParam & GCS_COMPSTR)
- str += "COMPSTR ";
- if (lParam & GCS_COMPATTR)
- str += "COMPATTR ";
- if (lParam & GCS_CURSORPOS)
- str += "CURSORPOS ";
- if (lParam & GCS_COMPCLAUSE)
- str += "COMPCLAUSE ";
- if (lParam & CS_INSERTCHAR)
- str += "INSERTCHAR ";
- if (lParam & CS_NOMOVECARET)
- str += "NOMOVECARET ";
- qDebug("composition, lParam=(%x) %s imePosition=%d", lParam, str.latin1(), imePosition);
-#endif
-
- bool result = true;
-
- if(!lParam)
- // bogus event
- return true;
-
- QWidget *fw = QApplication::focusWidget();
- if (fw) {
- Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
- HIMC imc = getContext(fw->effectiveWinId());
- QInputMethodEvent e;
- if (lParam & (GCS_COMPSTR | GCS_COMPATTR | GCS_CURSORPOS)) {
- if (imePosition == -1)
- // need to send a start event
- startComposition();
-
- // some intermediate composition result
- int selStart, selLength;
- *imeComposition = getString(imc, GCS_COMPSTR, &selStart, &selLength);
- imePosition = getCursorPosition(imc);
- if (lParam & CS_INSERTCHAR && lParam & CS_NOMOVECARET) {
- // make korean work correctly. Hope this is correct for all IMEs
- selStart = 0;
- selLength = imeComposition->length();
- }
- if(selLength == 0)
- selStart = 0;
-
- QList<QInputMethodEvent::Attribute> attrs;
- if (selStart > 0)
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, selStart,
- standardFormat(PreeditFormat));
- if (selLength)
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart, selLength,
- standardFormat(SelectionFormat));
- if (selStart + selLength < imeComposition->length())
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart + selLength,
- imeComposition->length() - selStart - selLength,
- standardFormat(PreeditFormat));
- if(imePosition >= 0)
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, imePosition, selLength ? 0 : 1, QVariant());
-
- e = QInputMethodEvent(*imeComposition, attrs);
- }
- if (lParam & GCS_RESULTSTR) {
- if(imePosition == -1)
- startComposition();
- // a fixed result, return the converted string
- *imeComposition = getString(imc, GCS_RESULTSTR);
- imePosition = -1;
- e.setCommitString(*imeComposition);
- imeComposition->clear();
- }
- result = qt_sendSpontaneousEvent(fw, &e);
- update();
- releaseContext(fw->effectiveWinId(), imc);
- }
-#ifdef Q_IME_DEBUG
- qDebug("imecomposition: cursor pos at %d, str=%x", imePosition, str[0].unicode());
-#endif
- return result;
-}
-
-static HIMC defaultContext = 0;
-
-// checks whether widget is a popup
-inline bool isPopup(QWidget *w)
-{
- if (w && (w->windowFlags() & Qt::Popup) == Qt::Popup)
- return true;
- else
- return false;
-}
-// checks whether widget is in a popup
-inline bool isInPopup(QWidget *w)
-{
- if (w && (isPopup(w) || isPopup(w->window())))
- return true;
- else
- return false;
-}
-
-// find the parent widget, which is a non popup toplevel
-// this is valid only if the widget is/in a popup
-inline QWidget *findParentforPopup(QWidget *w)
-{
- QWidget *e = QWidget::find(w->effectiveWinId());
- // check if this or its parent is a popup
- while (isInPopup(e)) {
- e = e->window()->parentWidget();
- if (!e)
- break;
- e = QWidget::find(e->effectiveWinId());
- }
- if (e)
- return e->window();
- else
- return 0;
-}
-
-// enables or disables the ime
-inline void enableIme(QWidget *w, bool value)
-{
- if (value) {
- // enable ime
- if (defaultContext)
- ImmAssociateContext(w->effectiveWinId(), defaultContext);
-#ifdef Q_WS_WINCE
- if (qApp->autoSipEnabled())
- qt_wince_show_SIP(true);
-#endif
- } else {
- // disable ime
- HIMC oldimc = ImmAssociateContext(w->effectiveWinId(), 0);
- if (!defaultContext)
- defaultContext = oldimc;
-#ifdef Q_WS_WINCE
- if (qApp->autoSipEnabled())
- qt_wince_show_SIP(false);
-#endif
- }
-}
-
-
-void QWinInputContext::updateImeStatus(QWidget *w, bool hasFocus)
-{
- if (!w)
- return;
- // It's always the proxy that carries the hints.
- QWidget *focusProxyWidget = w->focusProxy();
- if (!focusProxyWidget)
- focusProxyWidget = w;
- bool e = w->testAttribute(Qt::WA_InputMethodEnabled) && w->isEnabled()
- && !(focusProxyWidget->inputMethodHints() & (Qt::ImhExclusiveInputMask | Qt::ImhHiddenText));
- bool hasIme = e && hasFocus;
-#ifdef Q_IME_DEBUG
- qDebug("%s HasFocus = %d hasIme = %d e = %d ", w->className(), hasFocus, hasIme, e);
-#endif
- if (hasFocus || e) {
- if (isInPopup(w))
- QWinInputContext::enablePopupChild(w, hasIme);
- else
- QWinInputContext::enable(w, hasIme);
- }
-}
-
-void QWinInputContext::enablePopupChild(QWidget *w, bool e)
-{
- if (aimm) {
- enable(w, e);
- return;
- }
-
- if (!w || !isInPopup(w))
- return;
-#ifdef Q_IME_DEBUG
- qDebug("enablePopupChild: w=%s, enable = %s", w ? w->className() : "(null)" , e ? "true" : "false");
-#endif
- QWidget *parent = findParentforPopup(w);
- if (parent) {
- // update ime status of the normal toplevel parent of the popup
- enableIme(parent, e);
- }
- QWidget *toplevel = w->window();
- if (toplevel) {
- // update ime status of the toplevel popup
- enableIme(toplevel, e);
- }
-}
-
-void QWinInputContext::enable(QWidget *w, bool e)
-{
- if(w) {
-#ifdef Q_IME_DEBUG
- qDebug("enable: w=%s, enable = %s", w ? w->className() : "(null)" , e ? "true" : "false");
-#endif
- if (!w->testAttribute(Qt::WA_WState_Created))
- return;
- if(aimm) {
- HIMC oldimc;
- if (!e) {
- aimm->AssociateContext(w->effectiveWinId(), 0, &oldimc);
- if (!defaultContext)
- defaultContext = oldimc;
- } else if (defaultContext) {
- aimm->AssociateContext(w->effectiveWinId(), defaultContext, &oldimc);
- }
- } else {
- // update ime status on the widget
- QWidget *p = QWidget::find(w->effectiveWinId());
- if (p)
- enableIme(p, e);
- }
- }
-}
-
-void QWinInputContext::setFocusWidget(QWidget *w)
-{
- QWidget *oldFocus = focusWidget();
- if (oldFocus == w)
- return;
- if (w) {
- QWinInputContext::updateImeStatus(w, true);
- } else {
- if (oldFocus)
- QWinInputContext::updateImeStatus(oldFocus , false);
- }
- QInputContext::setFocusWidget(w);
- update();
-}
-
-bool QWinInputContext::isComposing() const
-{
- return imeComposition && !imeComposition->isEmpty();
-}
-
-void QWinInputContext::mouseHandler(int pos, QMouseEvent *e)
-{
- if(e->type() != QEvent::MouseButtonPress)
- return;
-
- if (pos < 0 || pos > imeComposition->length())
- reset();
-
- // Probably should pass the correct button, but it seems to work fine like this.
- DWORD button = MK_LBUTTON;
-
- QWidget *fw = focusWidget();
- if (fw) {
- Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
- HIMC himc = getContext(fw->effectiveWinId());
- HWND ime_wnd = getDefaultIMEWnd(fw->effectiveWinId());
- SendMessage(ime_wnd, WM_MSIME_MOUSE, MAKELONG(MAKEWORD(button, pos == 0 ? 2 : 1), pos), (LPARAM)himc);
- releaseContext(fw->effectiveWinId(), himc);
- }
- //qDebug("mouseHandler: got value %d pos=%d", ret,pos);
-}
-
-QString QWinInputContext::language()
-{
- return QString();
-}
-
-int QWinInputContext::reconvertString(RECONVERTSTRING *reconv)
-{
- QWidget *w = focusWidget();
- if(!w)
- return -1;
-
- Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
- QString surroundingText = qvariant_cast<QString>(w->inputMethodQuery(Qt::ImSurroundingText));
- int memSize = sizeof(RECONVERTSTRING)+(surroundingText.length()+1)*sizeof(ushort);
- // If memory is not allocated, return the required size.
- if (!reconv) {
- if (surroundingText.isEmpty())
- return -1;
- else
- return memSize;
- }
- int pos = qvariant_cast<int>(w->inputMethodQuery(Qt::ImCursorPosition));
- // find the word in the surrounding text.
- QTextBoundaryFinder bounds(QTextBoundaryFinder::Word, surroundingText);
- bounds.setPosition(pos);
- if (bounds.isAtBoundary()) {
- if (QTextBoundaryFinder::EndWord == bounds.boundaryReasons())
- bounds.toPreviousBoundary();
- } else {
- bounds.toPreviousBoundary();
- }
- int startPos = bounds.position();
- bounds.toNextBoundary();
- int endPos = bounds.position();
- // select the text, this will be overwritten by following ime events.
- QList<QInputMethodEvent::Attribute> attrs;
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, startPos, endPos-startPos, QVariant());
- QInputMethodEvent e(QString(), attrs);
- qt_sendSpontaneousEvent(w, &e);
-
- reconv->dwSize = memSize;
- reconv->dwVersion = 0;
-
- reconv->dwStrLen = surroundingText.length();
- reconv->dwStrOffset = sizeof(RECONVERTSTRING);
- reconv->dwCompStrLen = endPos-startPos;
- reconv->dwCompStrOffset = startPos*sizeof(ushort);
- reconv->dwTargetStrLen = reconv->dwCompStrLen;
- reconv->dwTargetStrOffset = reconv->dwCompStrOffset;
- memcpy((char*)(reconv+1), surroundingText.utf16(), surroundingText.length()*sizeof(ushort));
- return memSize;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/inputmethod/qximinputcontext_p.h b/src/gui/inputmethod/qximinputcontext_p.h
deleted file mode 100644
index 13c389cce6..0000000000
--- a/src/gui/inputmethod/qximinputcontext_p.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Definition of QXIMInputContext class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#ifndef QXIMINPUTCONTEXT_P_H
-#define QXIMINPUTCONTEXT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#if !defined(Q_NO_IM)
-
-#include "QtCore/qglobal.h"
-#include "QtGui/qinputcontext.h"
-#include "QtGui/qfont.h"
-#include "QtCore/qhash.h"
-#ifdef Q_WS_X11
-#include "QtCore/qlist.h"
-#include "QtCore/qbitarray.h"
-#include "QtGui/qwindowdefs.h"
-#include "private/qt_x11_p.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QKeyEvent;
-class QWidget;
-class QFont;
-class QString;
-
-class QXIMInputContext : public QInputContext
-{
- Q_OBJECT
-public:
- struct ICData {
- XIC ic;
- XFontSet fontset;
- QWidget *widget;
- QString text;
- QBitArray selectedChars;
- bool composing;
- bool preeditEmpty;
- void clear();
- };
-
- QXIMInputContext();
- ~QXIMInputContext();
-
- QString identifierName();
- QString language();
-
- void reset();
-
- void mouseHandler( int x, QMouseEvent *event);
- bool isComposing() const;
-
- void setFocusWidget( QWidget *w );
- void widgetDestroyed(QWidget *w);
-
- void create_xim();
- void close_xim();
-
- void update();
-
- ICData *icData() const;
-protected:
- bool x11FilterEvent( QWidget *keywidget, XEvent *event );
-
-private:
- static XIMStyle xim_style;
-
- QString _language;
- XIM xim;
- QHash<WId, ICData *> ximData;
-
- ICData *createICData(QWidget *w);
-};
-
-QT_END_NAMESPACE
-
-#endif // Q_NO_IM
-
-#endif // QXIMINPUTCONTEXT_P_H
diff --git a/src/gui/inputmethod/qximinputcontext_x11.cpp b/src/gui/inputmethod/qximinputcontext_x11.cpp
deleted file mode 100644
index 155796828e..0000000000
--- a/src/gui/inputmethod/qximinputcontext_x11.cpp
+++ /dev/null
@@ -1,885 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Implementation of QXIMInputContext class
-**
-** Copyright (C) 2003-2004 immodule for Qt Project. All rights reserved.
-**
-** This file is written to contribute to Nokia Corporation and/or its subsidiary(-ies) under their own
-** license. You may use this file under your Qt license. Following
-** description is copied from their original file headers. Contact
-** immodule-qt@freedesktop.org if any conditions of this licensing are
-** not clear to you.
-**
-****************************************************************************/
-
-#include "qplatformdefs.h"
-#include "qdebug.h"
-#include "qximinputcontext_p.h"
-
-#if !defined(QT_NO_IM)
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(QT_NO_XIM)
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qplatformdefs.h"
-
-#include "qapplication.h"
-#include "qwidget.h"
-#include "qstring.h"
-#include "qlist.h"
-#include "qtextcodec.h"
-#include "qevent.h"
-#include "qtextformat.h"
-
-#include "qx11info_x11.h"
-
-#include <stdlib.h>
-#include <limits.h>
-QT_END_INCLUDE_NAMESPACE
-
-// #define QT_XIM_DEBUG
-#ifdef QT_XIM_DEBUG
-#define XIM_DEBUG qDebug
-#else
-#define XIM_DEBUG if (0) qDebug
-#endif
-
-// from qapplication_x11.cpp
-// #### move to X11 struct
-extern XIMStyle qt_xim_preferred_style;
-extern char *qt_ximServer;
-extern int qt_ximComposingKeycode;
-extern QTextCodec * qt_input_mapper;
-
-XIMStyle QXIMInputContext::xim_style = 0;
-// moved from qapplication_x11.cpp
-static const XIMStyle xim_default_style = XIMPreeditCallbacks | XIMStatusNothing;
-
-
-extern "C" {
-#ifdef USE_X11R6_XIM
- static void xim_create_callback(XIM /*im*/,
- XPointer client_data,
- XPointer /*call_data*/)
- {
- QXIMInputContext *qic = reinterpret_cast<QXIMInputContext *>(client_data);
- // qDebug("xim_create_callback");
- qic->create_xim();
- }
-
- static void xim_destroy_callback(XIM /*im*/,
- XPointer client_data,
- XPointer /*call_data*/)
- {
- QXIMInputContext *qic = reinterpret_cast<QXIMInputContext *>(client_data);
- // qDebug("xim_destroy_callback");
- qic->close_xim();
- XRegisterIMInstantiateCallback(X11->display, 0, 0, 0,
- (XIMProc) xim_create_callback, reinterpret_cast<char *>(qic));
- }
-#endif // USE_X11R6_XIM
-
- static int xic_start_callback(XIC, XPointer client_data, XPointer) {
- QXIMInputContext *qic = (QXIMInputContext *) client_data;
- if (!qic) {
- XIM_DEBUG("xic_start_callback: no qic");
- return 0;
- }
- QXIMInputContext::ICData *data = qic->icData();
- if (!data) {
- XIM_DEBUG("xic_start_callback: no ic data");
- return 0;
- }
- XIM_DEBUG("xic_start_callback");
-
- data->clear();
- data->composing = true;
-
- return 0;
- }
-
- static int xic_draw_callback(XIC, XPointer client_data, XPointer call_data) {
- QXIMInputContext *qic = (QXIMInputContext *) client_data;
- if (!qic) {
- XIM_DEBUG("xic_draw_callback: no qic");
- return 0;
- }
- QXIMInputContext::ICData *data = qic->icData();
- if (!data) {
- XIM_DEBUG("xic_draw_callback: no ic data");
- return 0;
- }
- XIM_DEBUG("xic_draw_callback");
-
-
- if(!data->composing) {
- data->clear();
- data->composing = true;
- }
-
- XIMPreeditDrawCallbackStruct *drawstruct = (XIMPreeditDrawCallbackStruct *) call_data;
- XIMText *text = (XIMText *) drawstruct->text;
- int cursor = drawstruct->caret, sellen = 0, selstart = 0;
-
- if (!drawstruct->caret && !drawstruct->chg_first && !drawstruct->chg_length && !text) {
- if(data->text.isEmpty()) {
- XIM_DEBUG("compose emptied");
- // if the composition string has been emptied, we need
- // to send an InputMethodEnd event
- QInputMethodEvent e;
- qic->sendEvent(e);
- data->clear();
-
- // if the commit string has coming after here, InputMethodStart
- // will be sent dynamically
- }
- return 0;
- }
-
- if (text) {
- char *str = 0;
- if (text->encoding_is_wchar) {
- int l = wcstombs(NULL, text->string.wide_char, text->length);
- if (l != -1) {
- str = new char[l + 1];
- wcstombs(str, text->string.wide_char, l);
- str[l] = 0;
- }
- } else
- str = text->string.multi_byte;
-
- if (!str)
- return 0;
-
- QString s = QString::fromLocal8Bit(str);
-
- if (text->encoding_is_wchar)
- delete [] str;
-
- if (drawstruct->chg_length < 0)
- data->text.replace(drawstruct->chg_first, INT_MAX, s);
- else
- data->text.replace(drawstruct->chg_first, drawstruct->chg_length, s);
-
- if (data->selectedChars.size() < data->text.length()) {
- // expand the selectedChars array if the compose string is longer
- int from = data->selectedChars.size();
- data->selectedChars.resize(data->text.length());
- for (int x = from; x < data->selectedChars.size(); ++x)
- data->selectedChars.clearBit(x);
- }
-
- // determine if the changed chars are selected based on text->feedback
- for (int x = 0; x < text->length; ++x)
- data->selectedChars.setBit(x + drawstruct->chg_first,
- (text->feedback ? (text->feedback[x] & XIMReverse) : 0));
-
- // figure out where the selection starts, and how long it is
- bool started = false;
- for (int x = 0; x < qMin(data->selectedChars.size(), data->text.length()); ++x) {
- if (started) {
- if (data->selectedChars.testBit(x)) ++sellen;
- else break;
- } else {
- if (data->selectedChars.testBit(x)) {
- selstart = x;
- started = true;
- sellen = 1;
- }
- }
- }
- } else {
- if (drawstruct->chg_length == 0)
- drawstruct->chg_length = -1;
-
- data->text.remove(drawstruct->chg_first, drawstruct->chg_length);
- bool qt_compose_emptied = data->text.isEmpty();
- if (qt_compose_emptied) {
- XIM_DEBUG("compose emptied 2 text=%s", data->text.toUtf8().constData());
- // if the composition string has been emptied, we need
- // to send an InputMethodEnd event
- QInputMethodEvent e;
- qic->sendEvent(e);
- data->clear();
- // if the commit string has coming after here, InputMethodStart
- // will be sent dynamically
- return 0;
- }
- }
-
- XIM_DEBUG("sending compose: '%s', cursor=%d, sellen=%d",
- data->text.toUtf8().constData(), cursor, sellen);
- QList<QInputMethodEvent::Attribute> attrs;
- if (selstart > 0)
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, selstart,
- qic->standardFormat(QInputContext::PreeditFormat));
- if (sellen)
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selstart, sellen,
- qic->standardFormat(QInputContext::SelectionFormat));
- if (selstart + sellen < data->text.length())
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- selstart + sellen, data->text.length() - selstart - sellen,
- qic->standardFormat(QInputContext::PreeditFormat));
- attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, cursor, sellen ? 0 : 1, QVariant());
- QInputMethodEvent e(data->text, attrs);
- data->preeditEmpty = data->text.isEmpty();
- qic->sendEvent(e);
-
- return 0;
- }
-
- static int xic_done_callback(XIC, XPointer client_data, XPointer) {
- QXIMInputContext *qic = (QXIMInputContext *) client_data;
- if (!qic)
- return 0;
-
- XIM_DEBUG("xic_done_callback");
- // Don't send InputMethodEnd here. QXIMInputContext::x11FilterEvent()
- // handles InputMethodEnd with commit string.
- return 0;
- }
-}
-
-void QXIMInputContext::ICData::clear()
-{
- text = QString();
- selectedChars.clear();
- composing = false;
- preeditEmpty = true;
-}
-
-QXIMInputContext::ICData *QXIMInputContext::icData() const
-{
- if (QWidget *w = focusWidget())
- return ximData.value(w->effectiveWinId());
- return 0;
-}
-/* The cache here is needed, as X11 leaks a few kb for every
- XFreeFontSet call, so we avoid creating and deletion of fontsets as
- much as possible
-*/
-static XFontSet fontsetCache[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
-static int fontsetRefCount = 0;
-
-static const char * const fontsetnames[] = {
- "-*-fixed-medium-r-*-*-16-*,-*-*-medium-r-*-*-16-*",
- "-*-fixed-medium-i-*-*-16-*,-*-*-medium-i-*-*-16-*",
- "-*-fixed-bold-r-*-*-16-*,-*-*-bold-r-*-*-16-*",
- "-*-fixed-bold-i-*-*-16-*,-*-*-bold-i-*-*-16-*",
- "-*-fixed-medium-r-*-*-24-*,-*-*-medium-r-*-*-24-*",
- "-*-fixed-medium-i-*-*-24-*,-*-*-medium-i-*-*-24-*",
- "-*-fixed-bold-r-*-*-24-*,-*-*-bold-r-*-*-24-*",
- "-*-fixed-bold-i-*-*-24-*,-*-*-bold-i-*-*-24-*"
-};
-
-static XFontSet getFontSet(const QFont &f)
-{
- int i = 0;
- if (f.italic())
- i |= 1;
- if (f.bold())
- i |= 2;
-
- if (f.pointSize() > 20)
- i += 4;
-
- if (!fontsetCache[i]) {
- Display* dpy = X11->display;
- int missCount;
- char** missList;
- fontsetCache[i] = XCreateFontSet(dpy, fontsetnames[i], &missList, &missCount, 0);
- if(missCount > 0)
- XFreeStringList(missList);
- if (!fontsetCache[i]) {
- fontsetCache[i] = XCreateFontSet(dpy, "-*-fixed-*-*-*-*-16-*", &missList, &missCount, 0);
- if(missCount > 0)
- XFreeStringList(missList);
- if (!fontsetCache[i])
- fontsetCache[i] = (XFontSet)-1;
- }
- }
- return (fontsetCache[i] == (XFontSet)-1) ? 0 : fontsetCache[i];
-}
-
-extern bool qt_use_rtl_extensions; // from qapplication_x11.cpp
-#ifndef QT_NO_XKB
-extern QLocale q_getKeyboardLocale(const QByteArray &layoutName, const QByteArray &variantName);
-#endif
-
-QXIMInputContext::QXIMInputContext()
-{
- if (!qt_xim_preferred_style) // no configured input style, use the default
- qt_xim_preferred_style = xim_default_style;
-
- xim = 0;
- QByteArray ximServerName(qt_ximServer);
- if (qt_ximServer)
- ximServerName.prepend("@im=");
- else
- ximServerName = "";
-
- if (!XSupportsLocale())
-#ifndef QT_NO_DEBUG
- qWarning("Qt: Locale not supported on X server")
-#endif
- ;
-#ifdef USE_X11R6_XIM
- else if (XSetLocaleModifiers (ximServerName.constData()) == 0)
- qWarning("Qt: Cannot set locale modifiers: %s", ximServerName.constData());
- else
- XRegisterIMInstantiateCallback(X11->display, 0, 0, 0,
- (XIMProc) xim_create_callback, reinterpret_cast<char *>(this));
-#else // !USE_X11R6_XIM
- else if (XSetLocaleModifiers ("") == 0)
- qWarning("Qt: Cannot set locale modifiers");
- else
- QXIMInputContext::create_xim();
-#endif // USE_X11R6_XIM
-
-#ifndef QT_NO_XKB
- if (X11->use_xkb) {
- QByteArray layoutName;
- QByteArray variantName;
-
- Atom type = XNone;
- int format = 0;
- ulong nitems = 0;
- ulong bytesAfter = 0;
- uchar *data = 0;
- if (XGetWindowProperty(X11->display, RootWindow(X11->display, 0), ATOM(_XKB_RULES_NAMES), 0, 1024,
- false, XA_STRING, &type, &format, &nitems, &bytesAfter, &data) == Success
- && type == XA_STRING && format == 8 && nitems > 2) {
-
- char *names[5] = { 0, 0, 0, 0, 0 };
- char *p = reinterpret_cast<char *>(data), *end = p + nitems;
- int i = 0;
- do {
- names[i++] = p;
- p += qstrlen(p) + 1;
- } while (p < end);
-
- QList<QByteArray> layoutNames = QByteArray::fromRawData(names[2], qstrlen(names[2])).split(',');
- QList<QByteArray> variantNames = QByteArray::fromRawData(names[3], qstrlen(names[3])).split(',');
- for (int i = 0; i < qMin(layoutNames.count(), variantNames.count()); ++i ) {
- QByteArray variantName = variantNames.at(i);
- const int dashPos = variantName.indexOf("-");
- if (dashPos >= 0)
- variantName.truncate(dashPos);
- QLocale keyboardInputLocale = q_getKeyboardLocale(layoutNames.at(i), variantName);
- if (keyboardInputLocale.textDirection() == Qt::RightToLeft)
- qt_use_rtl_extensions = true;
- }
- }
-
- if (data)
- XFree(data);
- }
-#endif // QT_NO_XKB
-
-}
-
-
-/*!\internal
- Creates the application input method.
-*/
-void QXIMInputContext::create_xim()
-{
- ++fontsetRefCount;
-#ifndef QT_NO_XIM
- xim = XOpenIM(X11->display, 0, 0, 0);
- if (xim) {
-
-#ifdef USE_X11R6_XIM
- XIMCallback destroy;
- destroy.callback = (XIMProc) xim_destroy_callback;
- destroy.client_data = XPointer(this);
- if (XSetIMValues(xim, XNDestroyCallback, &destroy, (char *) 0) != 0)
- qWarning("Xlib doesn't support destroy callback");
-#endif // USE_X11R6_XIM
-
- XIMStyles *styles = 0;
- XGetIMValues(xim, XNQueryInputStyle, &styles, (char *) 0, (char *) 0);
- if (styles) {
- int i;
- for (i = 0; !xim_style && i < styles->count_styles; i++) {
- if (styles->supported_styles[i] == qt_xim_preferred_style) {
- xim_style = qt_xim_preferred_style;
- break;
- }
- }
- // if the preferred input style couldn't be found, look for
- // Nothing
- for (i = 0; !xim_style && i < styles->count_styles; i++) {
- if (styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) {
- xim_style = XIMPreeditNothing | XIMStatusNothing;
- break;
- }
- }
- // ... and failing that, None.
- for (i = 0; !xim_style && i < styles->count_styles; i++) {
- if (styles->supported_styles[i] == (XIMPreeditNone |
- XIMStatusNone)) {
- xim_style = XIMPreeditNone | XIMStatusNone;
- break;
- }
- }
-
- // qDebug("QApplication: using im style %lx", xim_style);
- XFree((char *)styles);
- }
-
- if (xim_style) {
-
-#ifdef USE_X11R6_XIM
- XUnregisterIMInstantiateCallback(X11->display, 0, 0, 0,
- (XIMProc) xim_create_callback, reinterpret_cast<char *>(this));
-#endif // USE_X11R6_XIM
-
- if (QWidget *focusWidget = QApplication::focusWidget()) {
- // reinitialize input context after the input method
- // server (like SCIM) has been launched without
- // requiring the user to manually switch focus.
- if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled)
- && focusWidget->testAttribute(Qt::WA_WState_Created)
- && focusWidget->isEnabled())
- setFocusWidget(focusWidget);
- }
- // following code fragment is not required for immodule
- // version of XIM
-#if 0
- QWidgetList list = qApp->topLevelWidgets();
- for (int i = 0; i < list.size(); ++i) {
- QWidget *w = list.at(i);
- w->d->createTLSysExtra();
- }
-#endif
- } else {
- // Give up
- qWarning("No supported input style found."
- " See InputMethod documentation.");
- close_xim();
- }
- }
-#endif // QT_NO_XIM
-}
-
-/*!\internal
- Closes the application input method.
-*/
-void QXIMInputContext::close_xim()
-{
- for(QHash<WId, ICData *>::const_iterator i = ximData.constBegin(),
- e = ximData.constEnd(); i != e; ++i) {
- ICData *data = i.value();
- if (data->ic)
- XDestroyIC(data->ic);
- delete data;
- }
- ximData.clear();
-
- if ( --fontsetRefCount == 0 ) {
- Display *dpy = X11->display;
- for ( int i = 0; i < 8; i++ ) {
- if ( fontsetCache[i] && fontsetCache[i] != (XFontSet)-1 ) {
- XFreeFontSet(dpy, fontsetCache[i]);
- fontsetCache[i] = 0;
- }
- }
- }
-
- setFocusWidget(0);
- xim = 0;
-}
-
-
-
-QXIMInputContext::~QXIMInputContext()
-{
- XIM old_xim = xim; // close_xim clears xim pointer.
- close_xim();
- if (old_xim)
- XCloseIM(old_xim);
-}
-
-
-QString QXIMInputContext::identifierName()
-{
- // the name should be "xim" rather than "XIM" to be consistent
- // with corresponding immodule of GTK+
- return QLatin1String("xim");
-}
-
-
-QString QXIMInputContext::language()
-{
- QString language;
- if (xim) {
- QByteArray locale(XLocaleOfIM(xim));
-
- if (locale.startsWith("zh")) {
- // Chinese language should be formed as "zh_CN", "zh_TW", "zh_HK"
- language = QLatin1String(locale.left(5));
- } else {
- // other languages should be two-letter ISO 639 language code
- language = QLatin1String(locale.left(2));
- }
- }
- return language;
-}
-
-void QXIMInputContext::reset()
-{
- QWidget *w = focusWidget();
- if (!w)
- return;
-
- ICData *data = ximData.value(w->effectiveWinId());
- if (!data)
- return;
-
- if (data->ic) {
- char *mb = XmbResetIC(data->ic);
- QInputMethodEvent e;
- if (mb) {
- e.setCommitString(QString::fromLocal8Bit(mb));
- XFree(mb);
- data->preeditEmpty = false; // force sending an event
- }
- if (!data->preeditEmpty) {
- sendEvent(e);
- update();
- }
- }
- data->clear();
-}
-
-void QXIMInputContext::widgetDestroyed(QWidget *w)
-{
- QInputContext::widgetDestroyed(w);
- ICData *data = ximData.take(w->effectiveWinId());
- if (!data)
- return;
-
- data->clear();
- if (data->ic)
- XDestroyIC(data->ic);
- delete data;
-}
-
-void QXIMInputContext::mouseHandler(int pos, QMouseEvent *e)
-{
- if(e->type() != QEvent::MouseButtonPress)
- return;
-
- XIM_DEBUG("QXIMInputContext::mouseHandler pos=%d", pos);
- if (QWidget *w = focusWidget()) {
- ICData *data = ximData.value(w->effectiveWinId());
- if (!data)
- return;
- if (pos < 0 || pos > data->text.length())
- reset();
- // ##### handle mouse position
- }
-}
-
-bool QXIMInputContext::isComposing() const
-{
- QWidget *w = focusWidget();
- if (!w)
- return false;
-
- ICData *data = ximData.value(w->effectiveWinId());
- if (!data)
- return false;
- return data->composing;
-}
-
-void QXIMInputContext::setFocusWidget(QWidget *w)
-{
- if (!xim)
- return;
- QWidget *oldFocus = focusWidget();
- if (oldFocus == w)
- return;
-
- if (language() != QLatin1String("ja"))
- reset();
-
- if (oldFocus) {
- ICData *data = ximData.value(oldFocus->effectiveWinId());
- if (data && data->ic)
- XUnsetICFocus(data->ic);
- }
-
- QInputContext::setFocusWidget(w);
-
- if (!w || w->inputMethodHints() & (Qt::ImhExclusiveInputMask | Qt::ImhHiddenText))
- return;
-
- ICData *data = ximData.value(w->effectiveWinId());
- if (!data)
- data = createICData(w);
-
- if (data->ic)
- XSetICFocus(data->ic);
-
- update();
-}
-
-
-bool QXIMInputContext::x11FilterEvent(QWidget *keywidget, XEvent *event)
-{
- int xkey_keycode = event->xkey.keycode;
- if (!keywidget->testAttribute(Qt::WA_WState_Created))
- return false;
- if (XFilterEvent(event, keywidget->effectiveWinId())) {
- qt_ximComposingKeycode = xkey_keycode; // ### not documented in xlib
-
- update();
-
- return true;
- }
- if (event->type != XKeyPress || event->xkey.keycode != 0)
- return false;
-
- QWidget *w = focusWidget();
- if (keywidget != w)
- return false;
- ICData *data = ximData.value(w->effectiveWinId());
- if (!data)
- return false;
-
- // input method has sent us a commit string
- QByteArray string;
- string.resize(513);
- KeySym key; // unused
- Status status; // unused
- QString text;
- int count = XmbLookupString(data->ic, &event->xkey, string.data(), string.size(),
- &key, &status);
-
- if (status == XBufferOverflow) {
- string.resize(count + 1);
- count = XmbLookupString(data->ic, &event->xkey, string.data(), string.size(),
- &key, &status);
- }
- if (count > 0) {
- // XmbLookupString() gave us some text, convert it to unicode
- text = qt_input_mapper->toUnicode(string.constData() , count);
- if (text.isEmpty()) {
- // codec couldn't convert to unicode? this can happen when running in the
- // C locale (or with no LANG set). try converting from latin-1
- text = QString::fromLatin1(string.constData(), count);
- }
- }
-
-#if 0
- if (!(xim_style & XIMPreeditCallbacks) || !isComposing()) {
- // ############### send a regular key event here!
- ;
- }
-#endif
-
- QInputMethodEvent e;
- e.setCommitString(text);
- sendEvent(e);
- data->clear();
-
- update();
-
- return true;
-}
-
-
-QXIMInputContext::ICData *QXIMInputContext::createICData(QWidget *w)
-{
- ICData *data = new ICData;
- data->widget = w;
- data->preeditEmpty = true;
-
- XVaNestedList preedit_attr = 0;
- XIMCallback startcallback, drawcallback, donecallback;
-
- QFont font = w->font();
- data->fontset = getFontSet(font);
-
- if (xim_style & XIMPreeditArea) {
- XRectangle rect;
- rect.x = 0;
- rect.y = 0;
- rect.width = w->width();
- rect.height = w->height();
-
- preedit_attr = XVaCreateNestedList(0,
- XNArea, &rect,
- XNFontSet, data->fontset,
- (char *) 0);
- } else if (xim_style & XIMPreeditPosition) {
- XPoint spot;
- spot.x = 1;
- spot.y = 1;
-
- preedit_attr = XVaCreateNestedList(0,
- XNSpotLocation, &spot,
- XNFontSet, data->fontset,
- (char *) 0);
- } else if (xim_style & XIMPreeditCallbacks) {
- startcallback.client_data = (XPointer) this;
- startcallback.callback = (XIMProc) xic_start_callback;
- drawcallback.client_data = (XPointer) this;
- drawcallback.callback = (XIMProc)xic_draw_callback;
- donecallback.client_data = (XPointer) this;
- donecallback.callback = (XIMProc) xic_done_callback;
-
- preedit_attr = XVaCreateNestedList(0,
- XNPreeditStartCallback, &startcallback,
- XNPreeditDrawCallback, &drawcallback,
- XNPreeditDoneCallback, &donecallback,
- (char *) 0);
- }
-
- if (preedit_attr) {
- data->ic = XCreateIC(xim,
- XNInputStyle, xim_style,
- XNClientWindow, w->effectiveWinId(),
- XNPreeditAttributes, preedit_attr,
- (char *) 0);
- XFree(preedit_attr);
- } else {
- data->ic = XCreateIC(xim,
- XNInputStyle, xim_style,
- XNClientWindow, w->effectiveWinId(),
- (char *) 0);
- }
-
- if (data->ic) {
- // when resetting the input context, preserve the input state
- (void) XSetICValues(data->ic, XNResetState, XIMPreserveState, (char *) 0);
- } else {
- qWarning("Failed to create XIC");
- }
-
- ximData[w->effectiveWinId()] = data;
- return data;
-}
-
-void QXIMInputContext::update()
-{
- QWidget *w = focusWidget();
- if (!w)
- return;
-
- ICData *data = ximData.value(w->effectiveWinId());
- if (!data || !data->ic)
- return;
-
- QRect r = w->inputMethodQuery(Qt::ImMicroFocus).toRect();
- QPoint p;
- if (w->nativeParentWidget())
- p = w->mapTo(w->nativeParentWidget(), QPoint((r.left() + r.right() + 1)/2, r.bottom()));
- else
- p = QPoint((r.left() + r.right() + 1)/2, r.bottom());
- XPoint spot;
- spot.x = p.x();
- spot.y = p.y();
-
- r = w->rect();
- XRectangle area;
- area.x = r.x();
- area.y = r.y();
- area.width = r.width();
- area.height = r.height();
-
- XFontSet fontset = getFontSet(qvariant_cast<QFont>(w->inputMethodQuery(Qt::ImFont)));
- if (data->fontset == fontset)
- fontset = 0;
- else
- data->fontset = fontset;
-
- XVaNestedList preedit_attr;
- if (fontset)
- preedit_attr = XVaCreateNestedList(0,
- XNSpotLocation, &spot,
- XNArea, &area,
- XNFontSet, fontset,
- (char *) 0);
- else
- preedit_attr = XVaCreateNestedList(0,
- XNSpotLocation, &spot,
- XNArea, &area,
- (char *) 0);
-
- XSetICValues(data->ic, XNPreeditAttributes, preedit_attr, (char *) 0);
- XFree(preedit_attr);
-}
-
-
-#else
-/*
- When QT_NO_XIM is defined, we provide a dummy implementation for
- this class. The reason for this is that the header file is moc'ed
- regardless of QT_NO_XIM. The best would be to remove the file
- completely from the pri file is QT_NO_XIM was defined, or for moc
- to understand this preprocessor directive. Since the header does
- not declare this class when QT_NO_XIM is defined, this is dead
- code.
-*/
-bool QXIMInputContext::isComposing() const { return false; }
-QString QXIMInputContext::identifierName() { return QString(); }
-void QXIMInputContext::mouseHandler(int, QMouseEvent *) {}
-void QXIMInputContext::setFocusWidget(QWidget *) {}
-void QXIMInputContext::reset() {}
-void QXIMInputContext::update() {}
-QXIMInputContext::~QXIMInputContext() {}
-void QXIMInputContext::widgetDestroyed(QWidget *) {}
-QString QXIMInputContext::language() { return QString(); }
-bool QXIMInputContext::x11FilterEvent(QWidget *, XEvent *) { return true; }
-
-#endif //QT_NO_XIM
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_IM
diff --git a/src/gui/itemviews/itemviews.pri b/src/gui/itemviews/itemviews.pri
deleted file mode 100644
index bbc1e983ba..0000000000
--- a/src/gui/itemviews/itemviews.pri
+++ /dev/null
@@ -1,70 +0,0 @@
-# Qt gui library, itemviews
-
-HEADERS += \
- itemviews/qabstractitemview.h \
- itemviews/qabstractitemview_p.h \
- itemviews/qheaderview.h \
- itemviews/qlistview.h \
- itemviews/qlistview_p.h \
- itemviews/qbsptree_p.h \
- itemviews/qtableview.h \
- itemviews/qtableview_p.h \
- itemviews/qtreeview.h \
- itemviews/qtreeview_p.h \
- itemviews/qabstractitemdelegate.h \
- itemviews/qitemdelegate.h \
- itemviews/qitemselectionmodel.h \
- itemviews/qitemselectionmodel_p.h \
- itemviews/qdirmodel.h \
- itemviews/qlistwidget.h \
- itemviews/qlistwidget_p.h \
- itemviews/qtablewidget.h \
- itemviews/qtablewidget_p.h \
- itemviews/qtreewidget.h \
- itemviews/qtreewidget_p.h \
- itemviews/qwidgetitemdata_p.h \
- itemviews/qproxymodel.h \
- itemviews/qproxymodel_p.h \
- itemviews/qabstractproxymodel.h \
- itemviews/qabstractproxymodel_p.h \
- itemviews/qsortfilterproxymodel.h \
- itemviews/qitemeditorfactory.h \
- itemviews/qitemeditorfactory_p.h \
- itemviews/qstandarditemmodel.h \
- itemviews/qstandarditemmodel_p.h \
- itemviews/qstringlistmodel.h \
- itemviews/qtreewidgetitemiterator.h \
- itemviews/qdatawidgetmapper.h \
- itemviews/qfileiconprovider.h \
- itemviews/qcolumnviewgrip_p.h \
- itemviews/qcolumnview.h \
- itemviews/qcolumnview_p.h \
- itemviews/qstyleditemdelegate.h
-
-SOURCES += \
- itemviews/qabstractitemview.cpp \
- itemviews/qheaderview.cpp \
- itemviews/qlistview.cpp \
- itemviews/qbsptree.cpp \
- itemviews/qtableview.cpp \
- itemviews/qtreeview.cpp \
- itemviews/qabstractitemdelegate.cpp \
- itemviews/qitemdelegate.cpp \
- itemviews/qitemselectionmodel.cpp \
- itemviews/qdirmodel.cpp \
- itemviews/qlistwidget.cpp \
- itemviews/qtablewidget.cpp \
- itemviews/qtreewidget.cpp \
- itemviews/qproxymodel.cpp \
- itemviews/qabstractproxymodel.cpp \
- itemviews/qsortfilterproxymodel.cpp \
- itemviews/qitemeditorfactory.cpp \
- itemviews/qstandarditemmodel.cpp \
- itemviews/qstringlistmodel.cpp \
- itemviews/qtreewidgetitemiterator.cpp \
- itemviews/qdatawidgetmapper.cpp \
- itemviews/qfileiconprovider.cpp \
- itemviews/qcolumnview.cpp \
- itemviews/qcolumnviewgrip.cpp \
- itemviews/qstyleditemdelegate.cpp
-
diff --git a/src/gui/itemviews/qabstractitemdelegate.cpp b/src/gui/itemviews/qabstractitemdelegate.cpp
deleted file mode 100644
index 478c4747ef..0000000000
--- a/src/gui/itemviews/qabstractitemdelegate.cpp
+++ /dev/null
@@ -1,393 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractitemdelegate.h"
-
-#ifndef QT_NO_ITEMVIEWS
-#include <qabstractitemmodel.h>
-#include <qabstractitemview.h>
-#include <qfontmetrics.h>
-#include <qwhatsthis.h>
-#include <qtooltip.h>
-#include <qevent.h>
-#include <qstring.h>
-#include <qdebug.h>
-#include <private/qtextengine_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAbstractItemDelegate
-
- \brief The QAbstractItemDelegate class is used to display and edit
- data items from a model.
-
- \ingroup model-view
-
-
- A QAbstractItemDelegate provides the interface and common functionality
- for delegates in the model/view architecture. Delegates display
- individual items in views, and handle the editing of model data.
-
- The QAbstractItemDelegate class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- To render an item in a custom way, you must implement paint() and
- sizeHint(). The QItemDelegate class provides default implementations for
- these functions; if you do not need custom rendering, subclass that
- class instead.
-
- We give an example of drawing a progress bar in items; in our case
- for a package management program.
-
- \image widgetdelegate.png
-
- We create the \c WidgetDelegate class, which inherits from
- QStyledItemDelegate. We do the drawing in the paint() function:
-
- \snippet doc/src/snippets/widgetdelegate.cpp 0
-
- Notice that we use a QStyleOptionProgressBar and initialize its
- members. We can then use the current QStyle to draw it.
-
- To provide custom editing, there are two approaches that can be
- used. The first approach is to create an editor widget and display
- it directly on top of the item. To do this you must reimplement
- createEditor() to provide an editor widget, setEditorData() to populate
- the editor with the data from the model, and setModelData() so that the
- delegate can update the model with data from the editor.
-
- The second approach is to handle user events directly by reimplementing
- editorEvent().
-
- \sa {model-view-programming}{Model/View Programming}, QItemDelegate,
- {Pixelator Example}, QStyledItemDelegate, QStyle
-*/
-
-/*!
- \enum QAbstractItemDelegate::EndEditHint
-
- This enum describes the different hints that the delegate can give to the
- model and view components to make editing data in a model a comfortable
- experience for the user.
-
- \value NoHint There is no recommended action to be performed.
-
- These hints let the delegate influence the behavior of the view:
-
- \value EditNextItem The view should use the delegate to open an
- editor on the next item in the view.
- \value EditPreviousItem The view should use the delegate to open an
- editor on the previous item in the view.
-
- Note that custom views may interpret the concepts of next and previous
- differently.
-
- The following hints are most useful when models are used that cache
- data, such as those that manipulate data locally in order to increase
- performance or conserve network bandwidth.
-
- \value SubmitModelCache If the model caches data, it should write out
- cached data to the underlying data store.
- \value RevertModelCache If the model caches data, it should discard
- cached data and replace it with data from the
- underlying data store.
-
- Although models and views should respond to these hints in appropriate
- ways, custom components may ignore any or all of them if they are not
- relevant.
-*/
-
-/*!
- \fn void QAbstractItemDelegate::commitData(QWidget *editor)
-
- This signal must be emitted when the \a editor widget has completed
- editing the data, and wants to write it back into the model.
-*/
-
-/*!
- \fn void QAbstractItemDelegate::closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
-
- This signal is emitted when the user has finished editing an item using
- the specified \a editor.
-
- The \a hint provides a way for the delegate to influence how the model and
- view behave after editing is completed. It indicates to these components
- what action should be performed next to provide a comfortable editing
- experience for the user. For example, if \c EditNextItem is specified,
- the view should use a delegate to open an editor on the next item in the
- model.
-
- \sa EndEditHint
-*/
-
-/*!
- \fn void QAbstractItemDelegate::sizeHintChanged(const QModelIndex &index)
- \since 4.4
-
- This signal must be emitted when the sizeHint() of \a index changed.
-
- Views automatically connect to this signal and relayout items as necessary.
-*/
-
-
-/*!
- Creates a new abstract item delegate with the given \a parent.
-*/
-QAbstractItemDelegate::QAbstractItemDelegate(QObject *parent)
- : QObject(parent)
-{
-
-}
-
-/*!
- \internal
-
- Creates a new abstract item delegate with the given \a parent.
-*/
-QAbstractItemDelegate::QAbstractItemDelegate(QObjectPrivate &dd, QObject *parent)
- : QObject(dd, parent)
-{
-
-}
-
-/*!
- Destroys the abstract item delegate.
-*/
-QAbstractItemDelegate::~QAbstractItemDelegate()
-{
-
-}
-
-/*!
- \fn void QAbstractItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const = 0;
-
- This pure abstract function must be reimplemented if you want to
- provide custom rendering. Use the \a painter and style \a option to
- render the item specified by the item \a index.
-
- If you reimplement this you must also reimplement sizeHint().
-*/
-
-/*!
- \fn QSize QAbstractItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const = 0
-
- This pure abstract function must be reimplemented if you want to
- provide custom rendering. The options are specified by \a option
- and the model item by \a index.
-
- If you reimplement this you must also reimplement paint().
-*/
-
-/*!
- Returns the editor to be used for editing the data item with the
- given \a index. Note that the index contains information about the
- model being used. The editor's parent widget is specified by \a parent,
- and the item options by \a option.
-
- The base implementation returns 0. If you want custom editing you
- will need to reimplement this function.
-
- The returned editor widget should have Qt::StrongFocus;
- otherwise, \l{QMouseEvent}s received by the widget will propagate
- to the view. The view's background will shine through unless the
- editor paints its own background (e.g., with
- \l{QWidget::}{setAutoFillBackground()}).
-
- \sa setModelData() setEditorData()
-*/
-QWidget *QAbstractItemDelegate::createEditor(QWidget *,
- const QStyleOptionViewItem &,
- const QModelIndex &) const
-{
- return 0;
-}
-
-/*!
- Sets the contents of the given \a editor to the data for the item
- at the given \a index. Note that the index contains information
- about the model being used.
-
- The base implementation does nothing. If you want custom editing
- you will need to reimplement this function.
-
- \sa setModelData()
-*/
-void QAbstractItemDelegate::setEditorData(QWidget *,
- const QModelIndex &) const
-{
- // do nothing
-}
-
-/*!
- Sets the data for the item at the given \a index in the \a model
- to the contents of the given \a editor.
-
- The base implementation does nothing. If you want custom editing
- you will need to reimplement this function.
-
- \sa setEditorData()
-*/
-void QAbstractItemDelegate::setModelData(QWidget *,
- QAbstractItemModel *,
- const QModelIndex &) const
-{
- // do nothing
-}
-
-/*!
- Updates the geometry of the \a editor for the item with the given
- \a index, according to the rectangle specified in the \a option.
- If the item has an internal layout, the editor will be laid out
- accordingly. Note that the index contains information about the
- model being used.
-
- The base implementation does nothing. If you want custom editing
- you must reimplement this function.
-*/
-void QAbstractItemDelegate::updateEditorGeometry(QWidget *,
- const QStyleOptionViewItem &,
- const QModelIndex &) const
-{
- // do nothing
-}
-
-/*!
- When editing of an item starts, this function is called with the
- \a event that triggered the editing, the \a model, the \a index of
- the item, and the \a option used for rendering the item.
-
- Mouse events are sent to editorEvent() even if they don't start
- editing of the item. This can, for instance, be useful if you wish
- to open a context menu when the right mouse button is pressed on
- an item.
-
- The base implementation returns false (indicating that it has not
- handled the event).
-*/
-bool QAbstractItemDelegate::editorEvent(QEvent *,
- QAbstractItemModel *,
- const QStyleOptionViewItem &,
- const QModelIndex &)
-{
- // do nothing
- return false;
-}
-
-/*!
- \obsolete
-
- Use QFontMetrics::elidedText() instead.
-
- \oldcode
- QFontMetrics fm = ...
- QString str = QAbstractItemDelegate::elidedText(fm, width, mode, text);
- \newcode
- QFontMetrics fm = ...
- QString str = fm.elidedText(text, mode, width);
- \endcode
-*/
-
-QString QAbstractItemDelegate::elidedText(const QFontMetrics &fontMetrics, int width,
- Qt::TextElideMode mode, const QString &text)
-{
- return fontMetrics.elidedText(text, mode, width);
-}
-
-/*!
- \since 4.3
- Whenever a help event occurs, this function is called with the \a event
- \a view \a option and the \a index that corresponds to the item where the
- event occurs.
-
- Returns true if the delegate can handle the event; otherwise returns false.
- A return value of true indicates that the data obtained using the index had
- the required role.
-
- For QEvent::ToolTip and QEvent::WhatsThis events that were handled successfully,
- the relevant popup may be shown depending on the user's system configuration.
-
- \sa QHelpEvent
-*/
-// ### Qt 5: Make this a virtual non-slot function
-bool QAbstractItemDelegate::helpEvent(QHelpEvent *event,
- QAbstractItemView *view,
- const QStyleOptionViewItem &option,
- const QModelIndex &index)
-{
- Q_UNUSED(option);
-
- if (!event || !view)
- return false;
- switch (event->type()) {
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTip: {
- QHelpEvent *he = static_cast<QHelpEvent*>(event);
- QVariant tooltip = index.data(Qt::ToolTipRole);
- if (tooltip.canConvert<QString>()) {
- QToolTip::showText(he->globalPos(), tooltip.toString(), view);
- return true;
- }
- break;}
-#endif
-#ifndef QT_NO_WHATSTHIS
- case QEvent::QueryWhatsThis: {
- if (index.data(Qt::WhatsThisRole).isValid())
- return true;
- break; }
- case QEvent::WhatsThis: {
- QHelpEvent *he = static_cast<QHelpEvent*>(event);
- QVariant whatsthis = index.data(Qt::WhatsThisRole);
- if (whatsthis.canConvert<QString>()) {
- QWhatsThis::showText(he->globalPos(), whatsthis.toString(), view);
- return true;
- }
- break ; }
-#endif
- default:
- break;
- }
- return false;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ITEMVIEWS
diff --git a/src/gui/itemviews/qabstractitemdelegate.h b/src/gui/itemviews/qabstractitemdelegate.h
deleted file mode 100644
index 6789317137..0000000000
--- a/src/gui/itemviews/qabstractitemdelegate.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTITEMDELEGATE_H
-#define QABSTRACTITEMDELEGATE_H
-
-#include <QtCore/qobject.h>
-#include <QtGui/qstyleoption.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class QPainter;
-class QModelIndex;
-class QAbstractItemModel;
-class QAbstractItemView;
-class QHelpEvent;
-
-class Q_GUI_EXPORT QAbstractItemDelegate : public QObject
-{
- Q_OBJECT
-
-public:
-
- enum EndEditHint {
- NoHint,
- EditNextItem,
- EditPreviousItem,
- SubmitModelCache,
- RevertModelCache
- };
-
- explicit QAbstractItemDelegate(QObject *parent = 0);
- virtual ~QAbstractItemDelegate();
-
- // painting
- virtual void paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const = 0;
-
- virtual QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const = 0;
-
- // editing
- virtual QWidget *createEditor(QWidget *parent,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- virtual void setEditorData(QWidget *editor, const QModelIndex &index) const;
-
- virtual void setModelData(QWidget *editor,
- QAbstractItemModel *model,
- const QModelIndex &index) const;
-
- virtual void updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- // for non-widget editors
- virtual bool editorEvent(QEvent *event,
- QAbstractItemModel *model,
- const QStyleOptionViewItem &option,
- const QModelIndex &index);
-
- static QString elidedText(const QFontMetrics &fontMetrics, int width,
- Qt::TextElideMode mode, const QString &text);
-
-public Q_SLOTS:
- bool helpEvent(QHelpEvent *event,
- QAbstractItemView *view,
- const QStyleOptionViewItem &option,
- const QModelIndex &index);
-
-Q_SIGNALS:
- void commitData(QWidget *editor);
- void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint = NoHint);
- void sizeHintChanged(const QModelIndex &);
-
-protected:
- QAbstractItemDelegate(QObjectPrivate &, QObject *parent = 0);
-private:
- Q_DISABLE_COPY(QAbstractItemDelegate)
-};
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTITEMDELEGATE_H
diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp
deleted file mode 100644
index d6714968b5..0000000000
--- a/src/gui/itemviews/qabstractitemview.cpp
+++ /dev/null
@@ -1,4241 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractitemview.h"
-
-#ifndef QT_NO_ITEMVIEWS
-#include <qpointer.h>
-#include <qapplication.h>
-#include <qclipboard.h>
-#include <qpainter.h>
-#include <qstyle.h>
-#include <qdrag.h>
-#include <qevent.h>
-#include <qscrollbar.h>
-#include <qwhatsthis.h>
-#include <qtooltip.h>
-#include <qdatetime.h>
-#include <qlineedit.h>
-#include <qspinbox.h>
-#include <qstyleditemdelegate.h>
-#include <private/qabstractitemview_p.h>
-#include <private/qabstractitemmodel_p.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qaccessible.h>
-#endif
-#include <private/qsoftkeymanager_p.h>
-#ifndef QT_NO_GESTURE
-# include <qscroller.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QAbstractItemViewPrivate::QAbstractItemViewPrivate()
- : model(QAbstractItemModelPrivate::staticEmptyModel()),
- itemDelegate(0),
- selectionModel(0),
- ctrlDragSelectionFlag(QItemSelectionModel::NoUpdate),
- noSelectionOnMousePress(false),
- selectionMode(QAbstractItemView::ExtendedSelection),
- selectionBehavior(QAbstractItemView::SelectItems),
- currentlyCommittingEditor(0),
- pressedModifiers(Qt::NoModifier),
- pressedPosition(QPoint(-1, -1)),
- pressedAlreadySelected(false),
- viewportEnteredNeeded(false),
- state(QAbstractItemView::NoState),
- stateBeforeAnimation(QAbstractItemView::NoState),
- editTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed),
- lastTrigger(QAbstractItemView::NoEditTriggers),
- tabKeyNavigation(false),
-#ifndef QT_NO_DRAGANDDROP
- showDropIndicator(true),
- dragEnabled(false),
- dragDropMode(QAbstractItemView::NoDragDrop),
- overwrite(false),
- dropIndicatorPosition(QAbstractItemView::OnItem),
- defaultDropAction(Qt::IgnoreAction),
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- doneSoftKey(0),
-#endif
- autoScroll(true),
- autoScrollMargin(16),
- autoScrollCount(0),
- shouldScrollToCurrentOnShow(false),
- shouldClearStatusTip(false),
- alternatingColors(false),
- textElideMode(Qt::ElideRight),
- verticalScrollMode(QAbstractItemView::ScrollPerItem),
- horizontalScrollMode(QAbstractItemView::ScrollPerItem),
- currentIndexSet(false),
- wrapItemText(false),
- delayedPendingLayout(true),
- moveCursorUpdatedView(false)
-{
- keyboardInputTime.invalidate();
-}
-
-QAbstractItemViewPrivate::~QAbstractItemViewPrivate()
-{
-}
-
-void QAbstractItemViewPrivate::init()
-{
- Q_Q(QAbstractItemView);
- q->setItemDelegate(new QStyledItemDelegate(q));
-
- vbar->setRange(0, 0);
- hbar->setRange(0, 0);
-
- QObject::connect(vbar, SIGNAL(actionTriggered(int)),
- q, SLOT(verticalScrollbarAction(int)));
- QObject::connect(hbar, SIGNAL(actionTriggered(int)),
- q, SLOT(horizontalScrollbarAction(int)));
- QObject::connect(vbar, SIGNAL(valueChanged(int)),
- q, SLOT(verticalScrollbarValueChanged(int)));
- QObject::connect(hbar, SIGNAL(valueChanged(int)),
- q, SLOT(horizontalScrollbarValueChanged(int)));
-
- viewport->setBackgroundRole(QPalette::Base);
-
- q->setAttribute(Qt::WA_InputMethodEnabled);
-
-#ifdef QT_SOFTKEYS_ENABLED
- doneSoftKey = QSoftKeyManager::createKeyedAction(QSoftKeyManager::DoneSoftKey, Qt::Key_Back, q);
-#endif
-}
-
-void QAbstractItemViewPrivate::setHoverIndex(const QPersistentModelIndex &index)
-{
- Q_Q(QAbstractItemView);
- if (hover == index)
- return;
-
- if (selectionBehavior != QAbstractItemView::SelectRows) {
- q->update(hover); //update the old one
- q->update(index); //update the new one
- } else {
- QRect oldHoverRect = q->visualRect(hover);
- QRect newHoverRect = q->visualRect(index);
- viewport->update(QRect(0, newHoverRect.y(), viewport->width(), newHoverRect.height()));
- viewport->update(QRect(0, oldHoverRect.y(), viewport->width(), oldHoverRect.height()));
- }
- hover = index;
-}
-
-void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index)
-{
- //we take a persistent model index because the model might change by emitting signals
- Q_Q(QAbstractItemView);
- setHoverIndex(index);
- if (viewportEnteredNeeded || enteredIndex != index) {
- viewportEnteredNeeded = false;
-
- if (index.isValid()) {
- emit q->entered(index);
-#ifndef QT_NO_STATUSTIP
- QString statustip = model->data(index, Qt::StatusTipRole).toString();
- if (parent && (shouldClearStatusTip || !statustip.isEmpty())) {
- QStatusTipEvent tip(statustip);
- QApplication::sendEvent(parent, &tip);
- shouldClearStatusTip = !statustip.isEmpty();
- }
-#endif
- } else {
-#ifndef QT_NO_STATUSTIP
- if (parent && shouldClearStatusTip) {
- QString emptyString;
- QStatusTipEvent tip( emptyString );
- QApplication::sendEvent(parent, &tip);
- }
-#endif
- emit q->viewportEntered();
- }
- enteredIndex = index;
- }
-}
-
-#ifndef QT_NO_GESTURES
-
-// stores and restores the selection and current item when flicking
-void QAbstractItemViewPrivate::_q_scrollerStateChanged()
-{
- Q_Q(QAbstractItemView);
-
- if (QScroller *scroller = QScroller::scroller(viewport)) {
- switch (scroller->state()) {
- case QScroller::Pressed:
- // store the current selection in case we start scrolling
- if (q->selectionModel()) {
- oldSelection = q->selectionModel()->selection();
- oldCurrent = q->selectionModel()->currentIndex();
- }
- break;
-
- case QScroller::Dragging:
- // restore the old selection if we really start scrolling
- if (q->selectionModel()) {
- q->selectionModel()->select(oldSelection, QItemSelectionModel::ClearAndSelect);
- q->selectionModel()->setCurrentIndex(oldCurrent, QItemSelectionModel::NoUpdate);
- }
- // fall through
-
- default:
- oldSelection = QItemSelection();
- oldCurrent = QModelIndex();
- break;
- }
- }
-}
-
-#endif // QT_NO_GESTURES
-
-/*!
- \class QAbstractItemView
-
- \brief The QAbstractItemView class provides the basic functionality for
- item view classes.
-
- \ingroup model-view
-
-
- QAbstractItemView class is the base class for every standard view
- that uses a QAbstractItemModel. QAbstractItemView is an abstract
- class and cannot itself be instantiated. It provides a standard
- interface for interoperating with models through the signals and
- slots mechanism, enabling subclasses to be kept up-to-date with
- changes to their models. This class provides standard support for
- keyboard and mouse navigation, viewport scrolling, item editing,
- and selections. The keyboard navigation implements this
- functionality:
-
- \table
- \header
- \o Keys
- \o Functionality
- \row
- \o Arrow keys
- \o Changes the current item and selects it.
- \row
- \o Ctrl+Arrow keys
- \o Changes the current item but does not select it.
- \row
- \o Shift+Arrow keys
- \o Changes the current item and selects it. The previously
- selected item(s) is not deselected.
- \row
- \o Ctr+Space
- \o Toggles selection of the current item.
- \row
- \o Tab/Backtab
- \o Changes the current item to the next/previous item.
- \row
- \o Home/End
- \o Selects the first/last item in the model.
- \row
- \o Page up/Page down
- \o Scrolls the rows shown up/down by the number of
- visible rows in the view.
- \row
- \o Ctrl+A
- \o Selects all items in the model.
- \endtable
-
- Note that the above table assumes that the
- \l{selectionMode}{selection mode} allows the operations. For
- instance, you cannot select items if the selection mode is
- QAbstractItemView::NoSelection.
-
- The QAbstractItemView class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- The view classes that inherit QAbstractItemView only need
- to implement their own view-specific functionality, such as
- drawing items, returning the geometry of items, finding items,
- etc.
-
- QAbstractItemView provides common slots such as edit() and
- setCurrentIndex(). Many protected slots are also provided, including
- dataChanged(), rowsInserted(), rowsAboutToBeRemoved(), selectionChanged(),
- and currentChanged().
-
- The root item is returned by rootIndex(), and the current item by
- currentIndex(). To make sure that an item is visible use
- scrollTo().
-
- Some of QAbstractItemView's functions are concerned with
- scrolling, for example setHorizontalScrollMode() and
- setVerticalScrollMode(). To set the range of the scroll bars, you
- can, for example, reimplement the view's resizeEvent() function:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp 0
-
- Note that the range is not updated until the widget is shown.
-
- Several other functions are concerned with selection control; for
- example setSelectionMode(), and setSelectionBehavior(). This class
- provides a default selection model to work with
- (selectionModel()), but this can be replaced by using
- setSelectionModel() with an instance of QItemSelectionModel.
-
- For complete control over the display and editing of items you can
- specify a delegate with setItemDelegate().
-
- QAbstractItemView provides a lot of protected functions. Some are
- concerned with editing, for example, edit(), and commitData(),
- whilst others are keyboard and mouse event handlers.
-
- \note If you inherit QAbstractItemView and intend to update the contents
- of the viewport, you should use viewport->update() instead of
- \l{QWidget::update()}{update()} as all painting operations take place on the
- viewport.
-
- \sa {View Classes}, {Model/View Programming}, QAbstractItemModel, {Chart Example}
-*/
-
-/*!
- \enum QAbstractItemView::SelectionMode
-
- This enum indicates how the view responds to user selections:
-
- \value SingleSelection When the user selects an item, any already-selected
- item becomes unselected, and the user cannot unselect the selected item by
- clicking on it.
-
- \value ContiguousSelection When the user selects an item in the usual way,
- the selection is cleared and the new item selected. However, if the user
- presses the Shift key while clicking on an item, all items between the
- current item and the clicked item are selected or unselected, depending on
- the state of the clicked item.
-
- \value ExtendedSelection When the user selects an item in the usual way,
- the selection is cleared and the new item selected. However, if the user
- presses the Ctrl key when clicking on an item, the clicked item gets
- toggled and all other items are left untouched. If the user presses the
- Shift key while clicking on an item, all items between the current item
- and the clicked item are selected or unselected, depending on the state of
- the clicked item. Multiple items can be selected by dragging the mouse over
- them.
-
- \value MultiSelection When the user selects an item in the usual way, the
- selection status of that item is toggled and the other items are left
- alone. Multiple items can be toggled by dragging the mouse over them.
-
- \value NoSelection Items cannot be selected.
-
- The most commonly used modes are SingleSelection and ExtendedSelection.
-*/
-
-/*!
- \enum QAbstractItemView::SelectionBehavior
-
- \value SelectItems Selecting single items.
- \value SelectRows Selecting only rows.
- \value SelectColumns Selecting only columns.
-*/
-
-/*!
- \enum QAbstractItemView::ScrollHint
-
- \value EnsureVisible Scroll to ensure that the item is visible.
- \value PositionAtTop Scroll to position the item at the top of the
- viewport.
- \value PositionAtBottom Scroll to position the item at the bottom of the
- viewport.
- \value PositionAtCenter Scroll to position the item at the center of the
- viewport.
-*/
-
-
-/*!
- \enum QAbstractItemView::EditTrigger
-
- This enum describes actions which will initiate item editing.
-
- \value NoEditTriggers No editing possible.
- \value CurrentChanged Editing start whenever current item changes.
- \value DoubleClicked Editing starts when an item is double clicked.
- \value SelectedClicked Editing starts when clicking on an already selected
- item.
- \value EditKeyPressed Editing starts when the platform edit key has been
- pressed over an item.
- \value AnyKeyPressed Editing starts when any key is pressed over an item.
- \value AllEditTriggers Editing starts for all above actions.
-*/
-
-/*!
- \enum QAbstractItemView::CursorAction
-
- This enum describes the different ways to navigate between items,
- \sa moveCursor()
-
- \value MoveUp Move to the item above the current item.
- \value MoveDown Move to the item below the current item.
- \value MoveLeft Move to the item left of the current item.
- \value MoveRight Move to the item right of the current item.
- \value MoveHome Move to the top-left corner item.
- \value MoveEnd Move to the bottom-right corner item.
- \value MovePageUp Move one page up above the current item.
- \value MovePageDown Move one page down below the current item.
- \value MoveNext Move to the item after the current item.
- \value MovePrevious Move to the item before the current item.
-*/
-
-/*!
- \enum QAbstractItemView::State
-
- Describes the different states the view can be in. This is usually
- only interesting when reimplementing your own view.
-
- \value NoState The is the default state.
- \value DraggingState The user is dragging items.
- \value DragSelectingState The user is selecting items.
- \value EditingState The user is editing an item in a widget editor.
- \value ExpandingState The user is opening a branch of items.
- \value CollapsingState The user is closing a branch of items.
- \value AnimatingState The item view is performing an animation.
-*/
-
-/*!
- \since 4.2
- \enum QAbstractItemView::ScrollMode
-
- \value ScrollPerItem The view will scroll the contents one item at a time.
- \value ScrollPerPixel The view will scroll the contents one pixel at a time.
-*/
-
-/*!
- \fn QRect QAbstractItemView::visualRect(const QModelIndex &index) const = 0
- Returns the rectangle on the viewport occupied by the item at \a index.
-
- If your item is displayed in several areas then visualRect should return
- the primary area that contains index and not the complete area that index
- might encompasses, touch or cause drawing.
-
- In the base class this is a pure virtual function.
-
- \sa indexAt(), visualRegionForSelection()
-*/
-
-/*!
- \fn void QAbstractItemView::scrollTo(const QModelIndex &index, ScrollHint hint) = 0
-
- Scrolls the view if necessary to ensure that the item at \a index
- is visible. The view will try to position the item according to the given \a hint.
-
- In the base class this is a pure virtual function.
-*/
-
-/*!
- \fn QModelIndex QAbstractItemView::indexAt(const QPoint &point) const = 0
-
- Returns the model index of the item at the viewport coordinates \a point.
-
- In the base class this is a pure virtual function.
-
- \sa visualRect()
-*/
-
-/*!
- \fn void QAbstractItemView::activated(const QModelIndex &index)
-
- This signal is emitted when the item specified by \a index is
- activated by the user. How to activate items depends on the
- platform; e.g., by single- or double-clicking the item, or by
- pressing the Return or Enter key when the item is current.
-
- \sa clicked(), doubleClicked(), entered(), pressed()
-*/
-
-/*!
- \fn void QAbstractItemView::entered(const QModelIndex &index)
-
- This signal is emitted when the mouse cursor enters the item
- specified by \a index.
- Mouse tracking needs to be enabled for this feature to work.
-
- \sa viewportEntered(), activated(), clicked(), doubleClicked(), pressed()
-*/
-
-/*!
- \fn void QAbstractItemView::viewportEntered()
-
- This signal is emitted when the mouse cursor enters the viewport.
- Mouse tracking needs to be enabled for this feature to work.
-
- \sa entered()
-*/
-
-/*!
- \fn void QAbstractItemView::pressed(const QModelIndex &index)
-
- This signal is emitted when a mouse button is pressed. The item
- the mouse was pressed on is specified by \a index. The signal is
- only emitted when the index is valid.
-
- Use the QApplication::mouseButtons() function to get the state
- of the mouse buttons.
-
- \sa activated(), clicked(), doubleClicked(), entered()
-*/
-
-/*!
- \fn void QAbstractItemView::clicked(const QModelIndex &index)
-
- This signal is emitted when a mouse button is clicked. The item
- the mouse was clicked on is specified by \a index. The signal is
- only emitted when the index is valid.
-
- \sa activated(), doubleClicked(), entered(), pressed()
-*/
-
-/*!
- \fn void QAbstractItemView::doubleClicked(const QModelIndex &index)
-
- This signal is emitted when a mouse button is double-clicked. The
- item the mouse was double-clicked on is specified by \a index.
- The signal is only emitted when the index is valid.
-
- \sa clicked(), activated()
-*/
-
-/*!
- \fn QModelIndex QAbstractItemView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) = 0
-
- Returns a QModelIndex object pointing to the next object in the view,
- based on the given \a cursorAction and keyboard modifiers specified
- by \a modifiers.
-
- In the base class this is a pure virtual function.
-*/
-
-/*!
- \fn int QAbstractItemView::horizontalOffset() const = 0
-
- Returns the horizontal offset of the view.
-
- In the base class this is a pure virtual function.
-
- \sa verticalOffset()
-*/
-
-/*!
- \fn int QAbstractItemView::verticalOffset() const = 0
-
- Returns the vertical offset of the view.
-
- In the base class this is a pure virtual function.
-
- \sa horizontalOffset()
-*/
-
-/*!
- \fn bool QAbstractItemView::isIndexHidden(const QModelIndex &index) const
-
- Returns true if the item referred to by the given \a index is hidden in the view,
- otherwise returns false.
-
- Hiding is a view specific feature. For example in TableView a column can be marked
- as hidden or a row in the TreeView.
-
- In the base class this is a pure virtual function.
-*/
-
-/*!
- \fn void QAbstractItemView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags)
-
- Applies the selection \a flags to the items in or touched by the
- rectangle, \a rect.
-
- When implementing your own itemview setSelection should call
- selectionModel()->select(selection, flags) where selection
- is either an empty QModelIndex or a QItemSelection that contains
- all items that are contained in \a rect.
-
- \sa selectionCommand(), selectedIndexes()
-*/
-
-/*!
- \fn QRegion QAbstractItemView::visualRegionForSelection(const QItemSelection &selection) const = 0
-
- Returns the region from the viewport of the items in the given
- \a selection.
-
- In the base class this is a pure virtual function.
-
- \sa visualRect(), selectedIndexes()
-*/
-
-/*!
- \fn void QAbstractItemView::update()
- \internal
-*/
-
-/*!
- Constructs an abstract item view with the given \a parent.
-*/
-QAbstractItemView::QAbstractItemView(QWidget *parent)
- : QAbstractScrollArea(*(new QAbstractItemViewPrivate), parent)
-{
- d_func()->init();
-}
-
-/*!
- \internal
-*/
-QAbstractItemView::QAbstractItemView(QAbstractItemViewPrivate &dd, QWidget *parent)
- : QAbstractScrollArea(dd, parent)
-{
- d_func()->init();
-}
-
-/*!
- Destroys the view.
-*/
-QAbstractItemView::~QAbstractItemView()
-{
- Q_D(QAbstractItemView);
- // stop these timers here before ~QObject
- d->delayedReset.stop();
- d->updateTimer.stop();
- d->delayedEditing.stop();
- d->delayedAutoScroll.stop();
- d->autoScrollTimer.stop();
- d->delayedLayout.stop();
- d->fetchMoreTimer.stop();
-}
-
-/*!
- Sets the \a model for the view to present.
-
- This function will create and set a new selection model, replacing any
- model that was previously set with setSelectionModel(). However, the old
- selection model will not be deleted as it may be shared between several
- views. We recommend that you delete the old selection model if it is no
- longer required. This is done with the following code:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp 2
-
- If both the old model and the old selection model do not have parents, or
- if their parents are long-lived objects, it may be preferable to call their
- deleteLater() functions to explicitly delete them.
-
- The view \e{does not} take ownership of the model unless it is the model's
- parent object because the model may be shared between many different views.
-
- \sa selectionModel(), setSelectionModel()
-*/
-void QAbstractItemView::setModel(QAbstractItemModel *model)
-{
- Q_D(QAbstractItemView);
- if (model == d->model)
- return;
- if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex)));
- disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(_q_headerDataChanged()));
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(rowsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_columnsInserted(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(modelReset()), this, SLOT(reset()));
- disconnect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
- }
- d->model = (model ? model : QAbstractItemModelPrivate::staticEmptyModel());
-
- // These asserts do basic sanity checking of the model
- Q_ASSERT_X(d->model->index(0,0) == d->model->index(0,0),
- "QAbstractItemView::setModel",
- "A model should return the exact same index "
- "(including its internal id/pointer) when asked for it twice in a row.");
- Q_ASSERT_X(!d->model->index(0,0).parent().isValid(),
- "QAbstractItemView::setModel",
- "The parent of a top level index should be invalid");
-
- if (d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- connect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- connect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(dataChanged(QModelIndex,QModelIndex)));
- connect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(_q_headerDataChanged()));
- connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(rowsInserted(QModelIndex,int,int)));
- connect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_columnsRemoved(QModelIndex,int,int)));
- connect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_columnsInserted(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(modelReset()), this, SLOT(reset()));
- connect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged()));
- }
-
- QItemSelectionModel *selection_model = new QItemSelectionModel(d->model, this);
- connect(d->model, SIGNAL(destroyed()), selection_model, SLOT(deleteLater()));
- setSelectionModel(selection_model);
-
- reset(); // kill editors, set new root and do layout
-}
-
-/*!
- Returns the model that this view is presenting.
-*/
-QAbstractItemModel *QAbstractItemView::model() const
-{
- Q_D(const QAbstractItemView);
- return (d->model == QAbstractItemModelPrivate::staticEmptyModel() ? 0 : d->model);
-}
-
-/*!
- Sets the current selection model to the given \a selectionModel.
-
- Note that, if you call setModel() after this function, the given \a selectionModel
- will be replaced by one created by the view.
-
- \note It is up to the application to delete the old selection model if it is no
- longer needed; i.e., if it is not being used by other views. This will happen
- automatically when its parent object is deleted. However, if it does not have a
- parent, or if the parent is a long-lived object, it may be preferable to call its
- deleteLater() function to explicitly delete it.
-
- \sa selectionModel(), setModel(), clearSelection()
-*/
-void QAbstractItemView::setSelectionModel(QItemSelectionModel *selectionModel)
-{
- // ### if the given model is null, we should use the original selection model
- Q_ASSERT(selectionModel);
- Q_D(QAbstractItemView);
-
- if (selectionModel->model() != d->model) {
- qWarning("QAbstractItemView::setSelectionModel() failed: "
- "Trying to set a selection model, which works on "
- "a different model than the view.");
- return;
- }
-
- if (d->selectionModel) {
- disconnect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
- disconnect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(currentChanged(QModelIndex,QModelIndex)));
- }
-
- d->selectionModel = selectionModel;
-
- if (d->selectionModel) {
- connect(d->selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
- connect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(currentChanged(QModelIndex,QModelIndex)));
- }
-}
-
-/*!
- Returns the current selection model.
-
- \sa setSelectionModel(), selectedIndexes()
-*/
-QItemSelectionModel* QAbstractItemView::selectionModel() const
-{
- Q_D(const QAbstractItemView);
- return d->selectionModel;
-}
-
-/*!
- Sets the item delegate for this view and its model to \a delegate.
- This is useful if you want complete control over the editing and
- display of items.
-
- Any existing delegate will be removed, but not deleted. QAbstractItemView
- does not take ownership of \a delegate.
-
- \warning You should not share the same instance of a delegate between views.
- Doing so can cause incorrect or unintuitive editing behavior since each
- view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
- signal, and attempt to access, modify or close an editor that has already been closed.
-
- \sa itemDelegate()
-*/
-void QAbstractItemView::setItemDelegate(QAbstractItemDelegate *delegate)
-{
- Q_D(QAbstractItemView);
- if (delegate == d->itemDelegate)
- return;
-
- if (d->itemDelegate) {
- if (d->delegateRefCount(d->itemDelegate) == 1) {
- disconnect(d->itemDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- disconnect(d->itemDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- disconnect(d->itemDelegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(doItemsLayout()));
- }
- }
-
- if (delegate) {
- if (d->delegateRefCount(delegate) == 0) {
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- qRegisterMetaType<QModelIndex>("QModelIndex");
- connect(delegate, SIGNAL(sizeHintChanged(QModelIndex)), this, SLOT(doItemsLayout()), Qt::QueuedConnection);
- }
- }
- d->itemDelegate = delegate;
- viewport()->update();
-}
-
-/*!
- Returns the item delegate used by this view and model. This is
- either one set with setItemDelegate(), or the default one.
-
- \sa setItemDelegate()
-*/
-QAbstractItemDelegate *QAbstractItemView::itemDelegate() const
-{
- return d_func()->itemDelegate;
-}
-
-/*!
- \reimp
-*/
-QVariant QAbstractItemView::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- const QModelIndex current = currentIndex();
- if (!current.isValid() || query != Qt::ImMicroFocus)
- return QAbstractScrollArea::inputMethodQuery(query);
- return visualRect(current);
-}
-
-/*!
- \since 4.2
-
- Sets the given item \a delegate used by this view and model for the given
- \a row. All items on \a row will be drawn and managed by \a delegate
- instead of using the default delegate (i.e., itemDelegate()).
-
- Any existing row delegate for \a row will be removed, but not
- deleted. QAbstractItemView does not take ownership of \a delegate.
-
- \note If a delegate has been assigned to both a row and a column, the row
- delegate (i.e., this delegate) will take precedence and manage the
- intersecting cell index.
-
- \warning You should not share the same instance of a delegate between views.
- Doing so can cause incorrect or unintuitive editing behavior since each
- view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
- signal, and attempt to access, modify or close an editor that has already been closed.
-
- \sa itemDelegateForRow(), setItemDelegateForColumn(), itemDelegate()
-*/
-void QAbstractItemView::setItemDelegateForRow(int row, QAbstractItemDelegate *delegate)
-{
- Q_D(QAbstractItemView);
- if (QAbstractItemDelegate *rowDelegate = d->rowDelegates.value(row, 0)) {
- if (d->delegateRefCount(rowDelegate) == 1) {
- disconnect(rowDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- disconnect(rowDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- }
- d->rowDelegates.remove(row);
- }
- if (delegate) {
- if (d->delegateRefCount(delegate) == 0) {
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- }
- d->rowDelegates.insert(row, delegate);
- }
- viewport()->update();
-}
-
-/*!
- \since 4.2
-
- Returns the item delegate used by this view and model for the given \a row,
- or 0 if no delegate has been assigned. You can call itemDelegate() to get a
- pointer to the current delegate for a given index.
-
- \sa setItemDelegateForRow(), itemDelegateForColumn(), setItemDelegate()
-*/
-QAbstractItemDelegate *QAbstractItemView::itemDelegateForRow(int row) const
-{
- Q_D(const QAbstractItemView);
- return d->rowDelegates.value(row, 0);
-}
-
-/*!
- \since 4.2
-
- Sets the given item \a delegate used by this view and model for the given
- \a column. All items on \a column will be drawn and managed by \a delegate
- instead of using the default delegate (i.e., itemDelegate()).
-
- Any existing column delegate for \a column will be removed, but not
- deleted. QAbstractItemView does not take ownership of \a delegate.
-
- \note If a delegate has been assigned to both a row and a column, the row
- delegate will take precedence and manage the intersecting cell index.
-
- \warning You should not share the same instance of a delegate between views.
- Doing so can cause incorrect or unintuitive editing behavior since each
- view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
- signal, and attempt to access, modify or close an editor that has already been closed.
-
- \sa itemDelegateForColumn(), setItemDelegateForRow(), itemDelegate()
-*/
-void QAbstractItemView::setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate)
-{
- Q_D(QAbstractItemView);
- if (QAbstractItemDelegate *columnDelegate = d->columnDelegates.value(column, 0)) {
- if (d->delegateRefCount(columnDelegate) == 1) {
- disconnect(columnDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- disconnect(columnDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- }
- d->columnDelegates.remove(column);
- }
- if (delegate) {
- if (d->delegateRefCount(delegate) == 0) {
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- connect(delegate, SIGNAL(commitData(QWidget*)), this, SLOT(commitData(QWidget*)));
- }
- d->columnDelegates.insert(column, delegate);
- }
- viewport()->update();
-}
-
-/*!
- \since 4.2
-
- Returns the item delegate used by this view and model for the given \a
- column. You can call itemDelegate() to get a pointer to the current delegate
- for a given index.
-
- \sa setItemDelegateForColumn(), itemDelegateForRow(), itemDelegate()
-*/
-QAbstractItemDelegate *QAbstractItemView::itemDelegateForColumn(int column) const
-{
- Q_D(const QAbstractItemView);
- return d->columnDelegates.value(column, 0);
-}
-
-/*!
- Returns the item delegate used by this view and model for
- the given \a index.
-*/
-QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) const
-{
- Q_D(const QAbstractItemView);
- return d->delegateForIndex(index);
-}
-
-/*!
- \property QAbstractItemView::selectionMode
- \brief which selection mode the view operates in
-
- This property controls whether the user can select one or many items
- and, in many-item selections, whether the selection must be a
- continuous range of items.
-
- \sa SelectionMode SelectionBehavior
-*/
-void QAbstractItemView::setSelectionMode(SelectionMode mode)
-{
- Q_D(QAbstractItemView);
- d->selectionMode = mode;
-}
-
-QAbstractItemView::SelectionMode QAbstractItemView::selectionMode() const
-{
- Q_D(const QAbstractItemView);
- return d->selectionMode;
-}
-
-/*!
- \property QAbstractItemView::selectionBehavior
- \brief which selection behavior the view uses
-
- This property holds whether selections are done
- in terms of single items, rows or columns.
-
- \sa SelectionMode SelectionBehavior
-*/
-
-void QAbstractItemView::setSelectionBehavior(QAbstractItemView::SelectionBehavior behavior)
-{
- Q_D(QAbstractItemView);
- d->selectionBehavior = behavior;
-}
-
-QAbstractItemView::SelectionBehavior QAbstractItemView::selectionBehavior() const
-{
- Q_D(const QAbstractItemView);
- return d->selectionBehavior;
-}
-
-/*!
- Sets the current item to be the item at \a index.
-
- Unless the current selection mode is
- \l{QAbstractItemView::}{NoSelection}, the item is also be selected.
- Note that this function also updates the starting position for any
- new selections the user performs.
-
- To set an item as the current item without selecting it, call
-
- \c{selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);}
-
- \sa currentIndex(), currentChanged(), selectionMode
-*/
-void QAbstractItemView::setCurrentIndex(const QModelIndex &index)
-{
- Q_D(QAbstractItemView);
- if (d->selectionModel && (!index.isValid() || d->isIndexEnabled(index))) {
- QItemSelectionModel::SelectionFlags command = selectionCommand(index, 0);
- d->selectionModel->setCurrentIndex(index, command);
- d->currentIndexSet = true;
- if ((command & QItemSelectionModel::Current) == 0)
- d->pressedPosition = visualRect(currentIndex()).center() + d->offset();
- }
-}
-
-/*!
- Returns the model index of the current item.
-
- \sa setCurrentIndex()
-*/
-QModelIndex QAbstractItemView::currentIndex() const
-{
- Q_D(const QAbstractItemView);
- return d->selectionModel ? d->selectionModel->currentIndex() : QModelIndex();
-}
-
-
-/*!
- Reset the internal state of the view.
-
- \warning This function will reset open editors, scroll bar positions,
- selections, etc. Existing changes will not be committed. If you would like
- to save your changes when resetting the view, you can reimplement this
- function, commit your changes, and then call the superclass'
- implementation.
-*/
-void QAbstractItemView::reset()
-{
- Q_D(QAbstractItemView);
- d->delayedReset.stop(); //make sure we stop the timer
- foreach (const QEditorInfo &info, d->indexEditorHash) {
- if (info.widget)
- d->releaseEditor(info.widget.data());
- }
- d->editorIndexHash.clear();
- d->indexEditorHash.clear();
- d->persistent.clear();
- d->currentIndexSet = false;
- setState(NoState);
- setRootIndex(QModelIndex());
- if (d->selectionModel)
- d->selectionModel->reset();
-}
-
-/*!
- Sets the root item to the item at the given \a index.
-
- \sa rootIndex()
-*/
-void QAbstractItemView::setRootIndex(const QModelIndex &index)
-{
- Q_D(QAbstractItemView);
- if (index.isValid() && index.model() != d->model) {
- qWarning("QAbstractItemView::setRootIndex failed : index must be from the currently set model");
- return;
- }
- d->root = index;
- d->doDelayedItemsLayout();
-}
-
-/*!
- Returns the model index of the model's root item. The root item is
- the parent item to the view's toplevel items. The root can be invalid.
-
- \sa setRootIndex()
-*/
-QModelIndex QAbstractItemView::rootIndex() const
-{
- return QModelIndex(d_func()->root);
-}
-
-/*!
- Selects all items in the view.
- This function will use the selection behavior
- set on the view when selecting.
-
- \sa setSelection(), selectedIndexes(), clearSelection()
-*/
-void QAbstractItemView::selectAll()
-{
- Q_D(QAbstractItemView);
- SelectionMode mode = d->selectionMode;
- if (mode == MultiSelection || mode == ExtendedSelection)
- d->selectAll(QItemSelectionModel::ClearAndSelect
- |d->selectionBehaviorFlags());
- else if (mode != SingleSelection)
- d->selectAll(selectionCommand(d->model->index(0, 0, d->root)));
-}
-
-/*!
- Starts editing the item corresponding to the given \a index if it is
- editable.
-
- Note that this function does not change the current index. Since the current
- index defines the next and previous items to edit, users may find that
- keyboard navigation does not work as expected. To provide consistent navigation
- behavior, call setCurrentIndex() before this function with the same model
- index.
-
- \sa QModelIndex::flags()
-*/
-void QAbstractItemView::edit(const QModelIndex &index)
-{
- Q_D(QAbstractItemView);
- if (!d->isIndexValid(index))
- qWarning("edit: index was invalid");
- if (!edit(index, AllEditTriggers, 0))
- qWarning("edit: editing failed");
-}
-
-/*!
- Deselects all selected items. The current index will not be changed.
-
- \sa setSelection(), selectAll()
-*/
-void QAbstractItemView::clearSelection()
-{
- Q_D(QAbstractItemView);
- if (d->selectionModel)
- d->selectionModel->clearSelection();
-}
-
-/*!
- \internal
-
- This function is intended to lay out the items in the view.
- The default implementation just calls updateGeometries() and updates the viewport.
-*/
-void QAbstractItemView::doItemsLayout()
-{
- Q_D(QAbstractItemView);
- d->interruptDelayedItemsLayout();
- updateGeometries();
- d->viewport->update();
-}
-
-/*!
- \property QAbstractItemView::editTriggers
- \brief which actions will initiate item editing
-
- This property is a selection of flags defined by
- \l{EditTrigger}, combined using the OR
- operator. The view will only initiate the editing of an item if the
- action performed is set in this property.
-*/
-void QAbstractItemView::setEditTriggers(EditTriggers actions)
-{
- Q_D(QAbstractItemView);
- d->editTriggers = actions;
-}
-
-QAbstractItemView::EditTriggers QAbstractItemView::editTriggers() const
-{
- Q_D(const QAbstractItemView);
- return d->editTriggers;
-}
-
-/*!
- \since 4.2
- \property QAbstractItemView::verticalScrollMode
- \brief how the view scrolls its contents in the vertical direction
-
- This property controls how the view scroll its contents vertically.
- Scrolling can be done either per pixel or per item.
-*/
-
-void QAbstractItemView::setVerticalScrollMode(ScrollMode mode)
-{
- Q_D(QAbstractItemView);
- if (mode == d->verticalScrollMode)
- return;
- QModelIndex topLeft = indexAt(QPoint(0, 0));
- d->verticalScrollMode = mode;
- updateGeometries(); // update the scroll bars
- scrollTo(topLeft, QAbstractItemView::PositionAtTop);
-}
-
-QAbstractItemView::ScrollMode QAbstractItemView::verticalScrollMode() const
-{
- Q_D(const QAbstractItemView);
- return d->verticalScrollMode;
-}
-
-/*!
- \since 4.2
- \property QAbstractItemView::horizontalScrollMode
- \brief how the view scrolls its contents in the horizontal direction
-
- This property controls how the view scroll its contents horizontally.
- Scrolling can be done either per pixel or per item.
-*/
-
-void QAbstractItemView::setHorizontalScrollMode(ScrollMode mode)
-{
- Q_D(QAbstractItemView);
- d->horizontalScrollMode = mode;
- updateGeometries(); // update the scroll bars
-}
-
-QAbstractItemView::ScrollMode QAbstractItemView::horizontalScrollMode() const
-{
- Q_D(const QAbstractItemView);
- return d->horizontalScrollMode;
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- \since 4.2
- \property QAbstractItemView::dragDropOverwriteMode
- \brief the view's drag and drop behavior
-
- If its value is \c true, the selected data will overwrite the
- existing item data when dropped, while moving the data will clear
- the item. If its value is \c false, the selected data will be
- inserted as a new item when the data is dropped. When the data is
- moved, the item is removed as well.
-
- The default value is \c false, as in the QListView and QTreeView
- subclasses. In the QTableView subclass, on the other hand, the
- property has been set to \c true.
-
- Note: This is not intended to prevent overwriting of items.
- The model's implementation of flags() should do that by not
- returning Qt::ItemIsDropEnabled.
-
- \sa dragDropMode
-*/
-void QAbstractItemView::setDragDropOverwriteMode(bool overwrite)
-{
- Q_D(QAbstractItemView);
- d->overwrite = overwrite;
-}
-
-bool QAbstractItemView::dragDropOverwriteMode() const
-{
- Q_D(const QAbstractItemView);
- return d->overwrite;
-}
-#endif
-
-/*!
- \property QAbstractItemView::autoScroll
- \brief whether autoscrolling in drag move events is enabled
-
- If this property is set to true (the default), the
- QAbstractItemView automatically scrolls the contents of the view
- if the user drags within 16 pixels of the viewport edge. If the current
- item changes, then the view will scroll automatically to ensure that the
- current item is fully visible.
-
- This property only works if the viewport accepts drops. Autoscroll is
- switched off by setting this property to false.
-*/
-
-void QAbstractItemView::setAutoScroll(bool enable)
-{
- Q_D(QAbstractItemView);
- d->autoScroll = enable;
-}
-
-bool QAbstractItemView::hasAutoScroll() const
-{
- Q_D(const QAbstractItemView);
- return d->autoScroll;
-}
-
-/*!
- \since 4.4
- \property QAbstractItemView::autoScrollMargin
- \brief the size of the area when auto scrolling is triggered
-
- This property controls the size of the area at the edge of the viewport that
- triggers autoscrolling. The default value is 16 pixels.
-*/
-void QAbstractItemView::setAutoScrollMargin(int margin)
-{
- Q_D(QAbstractItemView);
- d->autoScrollMargin = margin;
-}
-
-int QAbstractItemView::autoScrollMargin() const
-{
- Q_D(const QAbstractItemView);
- return d->autoScrollMargin;
-}
-
-/*!
- \property QAbstractItemView::tabKeyNavigation
- \brief whether item navigation with tab and backtab is enabled.
-*/
-
-void QAbstractItemView::setTabKeyNavigation(bool enable)
-{
- Q_D(QAbstractItemView);
- d->tabKeyNavigation = enable;
-}
-
-bool QAbstractItemView::tabKeyNavigation() const
-{
- Q_D(const QAbstractItemView);
- return d->tabKeyNavigation;
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- \property QAbstractItemView::showDropIndicator
- \brief whether the drop indicator is shown when dragging items and dropping.
-
- \sa dragEnabled DragDropMode dragDropOverwriteMode acceptDrops
-*/
-
-void QAbstractItemView::setDropIndicatorShown(bool enable)
-{
- Q_D(QAbstractItemView);
- d->showDropIndicator = enable;
-}
-
-bool QAbstractItemView::showDropIndicator() const
-{
- Q_D(const QAbstractItemView);
- return d->showDropIndicator;
-}
-
-/*!
- \property QAbstractItemView::dragEnabled
- \brief whether the view supports dragging of its own items
-
- \sa showDropIndicator DragDropMode dragDropOverwriteMode acceptDrops
-*/
-
-void QAbstractItemView::setDragEnabled(bool enable)
-{
- Q_D(QAbstractItemView);
- d->dragEnabled = enable;
-}
-
-bool QAbstractItemView::dragEnabled() const
-{
- Q_D(const QAbstractItemView);
- return d->dragEnabled;
-}
-
-/*!
- \since 4.2
- \enum QAbstractItemView::DragDropMode
-
- Describes the various drag and drop events the view can act upon.
- By default the view does not support dragging or dropping (\c
- NoDragDrop).
-
- \value NoDragDrop Does not support dragging or dropping.
- \value DragOnly The view supports dragging of its own items
- \value DropOnly The view accepts drops
- \value DragDrop The view supports both dragging and dropping
- \value InternalMove The view accepts move (\bold{not copy}) operations only
- from itself.
-
- Note that the model used needs to provide support for drag and drop operations.
-
- \sa setDragDropMode() {Using drag and drop with item views}
-*/
-
-/*!
- \property QAbstractItemView::dragDropMode
- \brief the drag and drop event the view will act upon
-
- \since 4.2
- \sa showDropIndicator dragDropOverwriteMode
-*/
-void QAbstractItemView::setDragDropMode(DragDropMode behavior)
-{
- Q_D(QAbstractItemView);
- d->dragDropMode = behavior;
- setDragEnabled(behavior == DragOnly || behavior == DragDrop || behavior == InternalMove);
- setAcceptDrops(behavior == DropOnly || behavior == DragDrop || behavior == InternalMove);
-}
-
-QAbstractItemView::DragDropMode QAbstractItemView::dragDropMode() const
-{
- Q_D(const QAbstractItemView);
- DragDropMode setBehavior = d->dragDropMode;
- if (!dragEnabled() && !acceptDrops())
- return NoDragDrop;
-
- if (dragEnabled() && !acceptDrops())
- return DragOnly;
-
- if (!dragEnabled() && acceptDrops())
- return DropOnly;
-
- if (dragEnabled() && acceptDrops()) {
- if (setBehavior == InternalMove)
- return setBehavior;
- else
- return DragDrop;
- }
-
- return NoDragDrop;
-}
-
-/*!
- \property QAbstractItemView::defaultDropAction
- \brief the drop action that will be used by default in QAbstractItemView::drag()
-
- If the property is not set, the drop action is CopyAction when the supported
- actions support CopyAction.
-
- \since 4.6
- \sa showDropIndicator dragDropOverwriteMode
-*/
-void QAbstractItemView::setDefaultDropAction(Qt::DropAction dropAction)
-{
- Q_D(QAbstractItemView);
- d->defaultDropAction = dropAction;
-}
-
-Qt::DropAction QAbstractItemView::defaultDropAction() const
-{
- Q_D(const QAbstractItemView);
- return d->defaultDropAction;
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- \property QAbstractItemView::alternatingRowColors
- \brief whether to draw the background using alternating colors
-
- If this property is true, the item background will be drawn using
- QPalette::Base and QPalette::AlternateBase; otherwise the background
- will be drawn using the QPalette::Base color.
-
- By default, this property is false.
-*/
-void QAbstractItemView::setAlternatingRowColors(bool enable)
-{
- Q_D(QAbstractItemView);
- d->alternatingColors = enable;
- if (isVisible())
- d->viewport->update();
-}
-
-bool QAbstractItemView::alternatingRowColors() const
-{
- Q_D(const QAbstractItemView);
- return d->alternatingColors;
-}
-
-/*!
- \property QAbstractItemView::iconSize
- \brief the size of items' icons
-
- Setting this property when the view is visible will cause the
- items to be laid out again.
-*/
-void QAbstractItemView::setIconSize(const QSize &size)
-{
- Q_D(QAbstractItemView);
- if (size == d->iconSize)
- return;
- d->iconSize = size;
- d->doDelayedItemsLayout();
-}
-
-QSize QAbstractItemView::iconSize() const
-{
- Q_D(const QAbstractItemView);
- return d->iconSize;
-}
-
-/*!
- \property QAbstractItemView::textElideMode
-
- \brief the position of the "..." in elided text.
-
- The default value for all item views is Qt::ElideRight.
-*/
-void QAbstractItemView::setTextElideMode(Qt::TextElideMode mode)
-{
- Q_D(QAbstractItemView);
- d->textElideMode = mode;
-}
-
-Qt::TextElideMode QAbstractItemView::textElideMode() const
-{
- return d_func()->textElideMode;
-}
-
-/*!
- \reimp
-*/
-bool QAbstractItemView::focusNextPrevChild(bool next)
-{
- Q_D(QAbstractItemView);
- if (d->tabKeyNavigation && isEnabled() && d->viewport->isEnabled()) {
- QKeyEvent event(QEvent::KeyPress, next ? Qt::Key_Tab : Qt::Key_Backtab, Qt::NoModifier);
- keyPressEvent(&event);
- if (event.isAccepted())
- return true;
- }
- return QAbstractScrollArea::focusNextPrevChild(next);
-}
-
-/*!
- \reimp
-*/
-bool QAbstractItemView::event(QEvent *event)
-{
- Q_D(QAbstractItemView);
- switch (event->type()) {
- case QEvent::Paint:
- //we call this here because the scrollbars' visibility might be altered
- //so this can't be done in the paintEvent method
- d->executePostedLayout(); //make sure we set the layout properly
- break;
- case QEvent::Show:
- d->executePostedLayout(); //make sure we set the layout properly
- if (d->shouldScrollToCurrentOnShow) {
- d->shouldScrollToCurrentOnShow = false;
- const QModelIndex current = currentIndex();
- if (current.isValid() && (d->state == QAbstractItemView::EditingState || d->autoScroll))
- scrollTo(current);
- }
- break;
- case QEvent::LocaleChange:
- viewport()->update();
- break;
- case QEvent::LayoutDirectionChange:
- case QEvent::ApplicationLayoutDirectionChange:
- updateGeometries();
- break;
- case QEvent::StyleChange:
- doItemsLayout();
- break;
- case QEvent::FocusOut:
- d->checkPersistentEditorFocus();
- break;
- case QEvent::FontChange:
- d->doDelayedItemsLayout(); // the size of the items will change
- break;
-#ifdef QT_SOFTKEYS_ENABLED
- case QEvent::LanguageChange:
- d->doneSoftKey->setText(QSoftKeyManager::standardSoftKeyText(QSoftKeyManager::DoneSoftKey));
- break;
-#endif
- default:
- break;
- }
- return QAbstractScrollArea::event(event);
-}
-
-/*!
- \fn bool QAbstractItemView::viewportEvent(QEvent *event)
-
- This function is used to handle tool tips, and What's
- This? mode, if the given \a event is a QEvent::ToolTip,or a
- QEvent::WhatsThis. It passes all other
- events on to its base class viewportEvent() handler.
-*/
-bool QAbstractItemView::viewportEvent(QEvent *event)
-{
- Q_D(QAbstractItemView);
- switch (event->type()) {
- case QEvent::HoverMove:
- case QEvent::HoverEnter:
- d->setHoverIndex(indexAt(static_cast<QHoverEvent*>(event)->pos()));
- break;
- case QEvent::HoverLeave:
- d->setHoverIndex(QModelIndex());
- break;
- case QEvent::Enter:
- d->viewportEnteredNeeded = true;
- break;
- case QEvent::Leave:
- #ifndef QT_NO_STATUSTIP
- if (d->shouldClearStatusTip && d->parent) {
- QString empty;
- QStatusTipEvent tip(empty);
- QApplication::sendEvent(d->parent, &tip);
- d->shouldClearStatusTip = false;
- }
- #endif
- d->enteredIndex = QModelIndex();
- break;
- case QEvent::ToolTip:
- case QEvent::QueryWhatsThis:
- case QEvent::WhatsThis: {
- QHelpEvent *he = static_cast<QHelpEvent*>(event);
- const QModelIndex index = indexAt(he->pos());
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- option.rect = visualRect(index);
- option.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
- bool retval = false;
- // ### Qt 5: make this a normal function call to a virtual function
- QMetaObject::invokeMethod(d->delegateForIndex(index), "helpEvent",
- Q_RETURN_ARG(bool, retval),
- Q_ARG(QHelpEvent *, he),
- Q_ARG(QAbstractItemView *, this),
- Q_ARG(QStyleOptionViewItem, option),
- Q_ARG(QModelIndex, index));
- return retval;
- }
- case QEvent::FontChange:
- d->doDelayedItemsLayout(); // the size of the items will change
- break;
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- d->viewport->update();
- break;
- case QEvent::ScrollPrepare:
- executeDelayedItemsLayout();
-#ifndef QT_NO_GESTURES
- connect(QScroller::scroller(d->viewport), SIGNAL(stateChanged(QScroller::State)), this, SLOT(_q_scrollerStateChanged()), Qt::UniqueConnection);
-#endif
- break;
-
- default:
- break;
- }
- return QAbstractScrollArea::viewportEvent(event);
-}
-
-/*!
- This function is called with the given \a event when a mouse button is pressed
- while the cursor is inside the widget. If a valid item is pressed on it is made
- into the current item. This function emits the pressed() signal.
-*/
-void QAbstractItemView::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QAbstractItemView);
- d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling
- QPoint pos = event->pos();
- QPersistentModelIndex index = indexAt(pos);
-
- if (!d->selectionModel
- || (d->state == EditingState && d->hasEditor(index)))
- return;
-
- d->pressedAlreadySelected = d->selectionModel->isSelected(index);
- d->pressedIndex = index;
- d->pressedModifiers = event->modifiers();
- QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
- d->noSelectionOnMousePress = command == QItemSelectionModel::NoUpdate || !index.isValid();
- QPoint offset = d->offset();
- if ((command & QItemSelectionModel::Current) == 0)
- d->pressedPosition = pos + offset;
- else if (!indexAt(d->pressedPosition - offset).isValid())
- d->pressedPosition = visualRect(currentIndex()).center() + offset;
-
- if (edit(index, NoEditTriggers, event))
- return;
-
- if (index.isValid() && d->isIndexEnabled(index)) {
- // we disable scrollTo for mouse press so the item doesn't change position
- // when the user is interacting with it (ie. clicking on it)
- bool autoScroll = d->autoScroll;
- d->autoScroll = false;
- d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- d->autoScroll = autoScroll;
- QRect rect(d->pressedPosition - offset, pos);
- if (command.testFlag(QItemSelectionModel::Toggle)) {
- command &= ~QItemSelectionModel::Toggle;
- d->ctrlDragSelectionFlag = d->selectionModel->isSelected(index) ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
- command |= d->ctrlDragSelectionFlag;
- }
- setSelection(rect, command);
-
- // signal handlers may change the model
- emit pressed(index);
- if (d->autoScroll) {
- //we delay the autoscrolling to filter out double click event
- //100 is to be sure that there won't be a double-click misinterpreted as a 2 single clicks
- d->delayedAutoScroll.start(QApplication::doubleClickInterval()+100, this);
- }
-
- } else {
- // Forces a finalize() even if mouse is pressed, but not on a item
- d->selectionModel->select(QModelIndex(), QItemSelectionModel::Select);
- }
-}
-
-/*!
- This function is called with the given \a event when a mouse move event is
- sent to the widget. If a selection is in progress and new items are moved
- over the selection is extended; if a drag is in progress it is continued.
-*/
-void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QAbstractItemView);
- QPoint topLeft;
- QPoint bottomRight = event->pos();
-
- if (state() == ExpandingState || state() == CollapsingState)
- return;
-
-#ifndef QT_NO_DRAGANDDROP
- if (state() == DraggingState) {
- topLeft = d->pressedPosition - d->offset();
- if ((topLeft - bottomRight).manhattanLength() > QApplication::startDragDistance()) {
- d->pressedIndex = QModelIndex();
- startDrag(d->model->supportedDragActions());
- setState(NoState); // the startDrag will return when the dnd operation is done
- stopAutoScroll();
- }
- return;
- }
-#endif // QT_NO_DRAGANDDROP
-
- QPersistentModelIndex index = indexAt(bottomRight);
- QModelIndex buddy = d->model->buddy(d->pressedIndex);
- if ((state() == EditingState && d->hasEditor(buddy))
- || edit(index, NoEditTriggers, event))
- return;
-
- if (d->selectionMode != SingleSelection)
- topLeft = d->pressedPosition - d->offset();
- else
- topLeft = bottomRight;
-
- d->checkMouseMove(index);
-
-#ifndef QT_NO_DRAGANDDROP
- if (d->pressedIndex.isValid()
- && d->dragEnabled
- && (state() != DragSelectingState)
- && (event->buttons() != Qt::NoButton)
- && !d->selectedDraggableIndexes().isEmpty()) {
- setState(DraggingState);
- return;
- }
-#endif
-
- if ((event->buttons() & Qt::LeftButton) && d->selectionAllowed(index) && d->selectionModel) {
- setState(DragSelectingState);
- QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
- if (d->ctrlDragSelectionFlag != QItemSelectionModel::NoUpdate && command.testFlag(QItemSelectionModel::Toggle)) {
- command &= ~QItemSelectionModel::Toggle;
- command |= d->ctrlDragSelectionFlag;
- }
-
- // Do the normalize ourselves, since QRect::normalized() is flawed
- QRect selectionRect = QRect(topLeft, bottomRight);
- setSelection(selectionRect, command);
-
- // set at the end because it might scroll the view
- if (index.isValid()
- && (index != d->selectionModel->currentIndex())
- && d->isIndexEnabled(index))
- d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- }
-}
-
-/*!
- This function is called with the given \a event when a mouse button is released,
- after a mouse press event on the widget. If a user presses the mouse inside your
- widget and then drags the mouse to another location before releasing the mouse button,
- your widget receives the release event. The function will emit the clicked() signal if an
- item was being pressed.
-*/
-void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QAbstractItemView);
-
- QPoint pos = event->pos();
- QPersistentModelIndex index = indexAt(pos);
-
- if (state() == EditingState) {
- if (d->isIndexValid(index)
- && d->isIndexEnabled(index)
- && d->sendDelegateEvent(index, event))
- update(index);
- return;
- }
-
- bool click = (index == d->pressedIndex && index.isValid());
- bool selectedClicked = click && (event->button() & Qt::LeftButton) && d->pressedAlreadySelected;
- EditTrigger trigger = (selectedClicked ? SelectedClicked : NoEditTriggers);
- bool edited = edit(index, trigger, event);
-
- d->ctrlDragSelectionFlag = QItemSelectionModel::NoUpdate;
-
- if (d->selectionModel && d->noSelectionOnMousePress) {
- d->noSelectionOnMousePress = false;
- d->selectionModel->select(index, selectionCommand(index, event));
- }
-
- setState(NoState);
-
- if (click) {
- emit clicked(index);
- if (edited)
- return;
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- if (d->pressedAlreadySelected)
- option.state |= QStyle::State_Selected;
- if (style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, &option, this))
- emit activated(index);
- }
-}
-
-/*!
- This function is called with the given \a event when a mouse button is
- double clicked inside the widget. If the double-click is on a valid item it
- emits the doubleClicked() signal and calls edit() on the item.
-*/
-void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QAbstractItemView);
-
- QModelIndex index = indexAt(event->pos());
- if (!index.isValid()
- || !d->isIndexEnabled(index)
- || (d->pressedIndex != index)) {
- QMouseEvent me(QEvent::MouseButtonPress,
- event->pos(), event->button(),
- event->buttons(), event->modifiers());
- mousePressEvent(&me);
- return;
- }
- // signal handlers may change the model
- QPersistentModelIndex persistent = index;
- emit doubleClicked(persistent);
- if ((event->button() & Qt::LeftButton) && !edit(persistent, DoubleClicked, event)
- && !style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, this))
- emit activated(persistent);
-}
-
-#ifndef QT_NO_DRAGANDDROP
-
-/*!
- This function is called with the given \a event when a drag and drop operation enters
- the widget. If the drag is over a valid dropping place (e.g. over an item that
- accepts drops), the event is accepted; otherwise it is ignored.
-
- \sa dropEvent() startDrag()
-*/
-void QAbstractItemView::dragEnterEvent(QDragEnterEvent *event)
-{
- if (dragDropMode() == InternalMove
- && (event->source() != this|| !(event->possibleActions() & Qt::MoveAction)))
- return;
-
- if (d_func()->canDecode(event)) {
- event->accept();
- setState(DraggingState);
- } else {
- event->ignore();
- }
-}
-
-/*!
- This function is called continuously with the given \a event during a drag and
- drop operation over the widget. It can cause the view to scroll if, for example,
- the user drags a selection to view's right or bottom edge. In this case, the
- event will be accepted; otherwise it will be ignored.
-
- \sa dropEvent() startDrag()
-*/
-void QAbstractItemView::dragMoveEvent(QDragMoveEvent *event)
-{
- Q_D(QAbstractItemView);
- if (dragDropMode() == InternalMove
- && (event->source() != this || !(event->possibleActions() & Qt::MoveAction)))
- return;
-
- // ignore by default
- event->ignore();
-
- QModelIndex index = indexAt(event->pos());
- d->hover = index;
- if (!d->droppingOnItself(event, index)
- && d->canDecode(event)) {
-
- if (index.isValid() && d->showDropIndicator) {
- QRect rect = visualRect(index);
- d->dropIndicatorPosition = d->position(event->pos(), rect, index);
- switch (d->dropIndicatorPosition) {
- case AboveItem:
- if (d->isIndexDropEnabled(index.parent())) {
- d->dropIndicatorRect = QRect(rect.left(), rect.top(), rect.width(), 0);
- event->accept();
- } else {
- d->dropIndicatorRect = QRect();
- }
- break;
- case BelowItem:
- if (d->isIndexDropEnabled(index.parent())) {
- d->dropIndicatorRect = QRect(rect.left(), rect.bottom(), rect.width(), 0);
- event->accept();
- } else {
- d->dropIndicatorRect = QRect();
- }
- break;
- case OnItem:
- if (d->isIndexDropEnabled(index)) {
- d->dropIndicatorRect = rect;
- event->accept();
- } else {
- d->dropIndicatorRect = QRect();
- }
- break;
- case OnViewport:
- d->dropIndicatorRect = QRect();
- if (d->isIndexDropEnabled(rootIndex())) {
- event->accept(); // allow dropping in empty areas
- }
- break;
- }
- } else {
- d->dropIndicatorRect = QRect();
- d->dropIndicatorPosition = OnViewport;
- if (d->isIndexDropEnabled(rootIndex())) {
- event->accept(); // allow dropping in empty areas
- }
- }
- d->viewport->update();
- } // can decode
-
- if (d->shouldAutoScroll(event->pos()))
- startAutoScroll();
-}
-
-/*!
- \internal
- Return true if this is a move from ourself and \a index is a child of the selection that
- is being moved.
- */
-bool QAbstractItemViewPrivate::droppingOnItself(QDropEvent *event, const QModelIndex &index)
-{
- Q_Q(QAbstractItemView);
- Qt::DropAction dropAction = event->dropAction();
- if (q->dragDropMode() == QAbstractItemView::InternalMove)
- dropAction = Qt::MoveAction;
- if (event->source() == q
- && event->possibleActions() & Qt::MoveAction
- && dropAction == Qt::MoveAction) {
- QModelIndexList selectedIndexes = q->selectedIndexes();
- QModelIndex child = index;
- while (child.isValid() && child != root) {
- if (selectedIndexes.contains(child))
- return true;
- child = child.parent();
- }
- }
- return false;
-}
-
-/*!
- \fn void QAbstractItemView::dragLeaveEvent(QDragLeaveEvent *event)
-
- This function is called when the item being dragged leaves the view.
- The \a event describes the state of the drag and drop operation.
-*/
-void QAbstractItemView::dragLeaveEvent(QDragLeaveEvent *)
-{
- Q_D(QAbstractItemView);
- stopAutoScroll();
- setState(NoState);
- d->hover = QModelIndex();
- d->viewport->update();
-}
-
-/*!
- This function is called with the given \a event when a drop event occurs over
- the widget. If the model accepts the even position the drop event is accepted;
- otherwise it is ignored.
-
- \sa startDrag()
-*/
-void QAbstractItemView::dropEvent(QDropEvent *event)
-{
- Q_D(QAbstractItemView);
- if (dragDropMode() == InternalMove) {
- if (event->source() != this || !(event->possibleActions() & Qt::MoveAction))
- return;
- }
-
- QModelIndex index;
- int col = -1;
- int row = -1;
- if (d->dropOn(event, &row, &col, &index)) {
- if (d->model->dropMimeData(event->mimeData(),
- dragDropMode() == InternalMove ? Qt::MoveAction : event->dropAction(), row, col, index)) {
- if (dragDropMode() == InternalMove)
- event->setDropAction(Qt::MoveAction);
- event->accept();
- }
- }
- stopAutoScroll();
- setState(NoState);
- d->viewport->update();
-}
-
-/*!
- If the event hasn't already been accepted, determines the index to drop on.
-
- if (row == -1 && col == -1)
- // append to this drop index
- else
- // place at row, col in drop index
-
- If it returns true a drop can be done, and dropRow, dropCol and dropIndex reflects the position of the drop.
- \internal
- */
-bool QAbstractItemViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QModelIndex *dropIndex)
-{
- Q_Q(QAbstractItemView);
- if (event->isAccepted())
- return false;
-
- QModelIndex index;
- // rootIndex() (i.e. the viewport) might be a valid index
- if (viewport->rect().contains(event->pos())) {
- index = q->indexAt(event->pos());
- if (!index.isValid() || !q->visualRect(index).contains(event->pos()))
- index = root;
- }
-
- // If we are allowed to do the drop
- if (model->supportedDropActions() & event->dropAction()) {
- int row = -1;
- int col = -1;
- if (index != root) {
- dropIndicatorPosition = position(event->pos(), q->visualRect(index), index);
- switch (dropIndicatorPosition) {
- case QAbstractItemView::AboveItem:
- row = index.row();
- col = index.column();
- index = index.parent();
- break;
- case QAbstractItemView::BelowItem:
- row = index.row() + 1;
- col = index.column();
- index = index.parent();
- break;
- case QAbstractItemView::OnItem:
- case QAbstractItemView::OnViewport:
- break;
- }
- } else {
- dropIndicatorPosition = QAbstractItemView::OnViewport;
- }
- *dropIndex = index;
- *dropRow = row;
- *dropCol = col;
- if (!droppingOnItself(event, index))
- return true;
- }
- return false;
-}
-
-QAbstractItemView::DropIndicatorPosition
-QAbstractItemViewPrivate::position(const QPoint &pos, const QRect &rect, const QModelIndex &index) const
-{
- QAbstractItemView::DropIndicatorPosition r = QAbstractItemView::OnViewport;
- if (!overwrite) {
- const int margin = 2;
- if (pos.y() - rect.top() < margin) {
- r = QAbstractItemView::AboveItem;
- } else if (rect.bottom() - pos.y() < margin) {
- r = QAbstractItemView::BelowItem;
- } else if (rect.contains(pos, true)) {
- r = QAbstractItemView::OnItem;
- }
- } else {
- QRect touchingRect = rect;
- touchingRect.adjust(-1, -1, 1, 1);
- if (touchingRect.contains(pos, false)) {
- r = QAbstractItemView::OnItem;
- }
- }
-
- if (r == QAbstractItemView::OnItem && (!(model->flags(index) & Qt::ItemIsDropEnabled)))
- r = pos.y() < rect.center().y() ? QAbstractItemView::AboveItem : QAbstractItemView::BelowItem;
-
- return r;
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- This function is called with the given \a event when the widget obtains the focus.
- By default, the event is ignored.
-
- \sa setFocus(), focusOutEvent()
-*/
-void QAbstractItemView::focusInEvent(QFocusEvent *event)
-{
- Q_D(QAbstractItemView);
- QAbstractScrollArea::focusInEvent(event);
-
- const QItemSelectionModel* model = selectionModel();
- const bool currentIndexValid = currentIndex().isValid();
-
- if (model
- && !d->currentIndexSet
- && !currentIndexValid) {
- bool autoScroll = d->autoScroll;
- d->autoScroll = false;
- QModelIndex index = moveCursor(MoveNext, Qt::NoModifier); // first visible index
- if (index.isValid() && d->isIndexEnabled(index) && event->reason() != Qt::MouseFocusReason)
- selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- d->autoScroll = autoScroll;
- }
-
- if (model && currentIndexValid) {
- if (currentIndex().flags() != Qt::ItemIsEditable)
- setAttribute(Qt::WA_InputMethodEnabled, false);
- else
- setAttribute(Qt::WA_InputMethodEnabled);
- }
-
- if (!currentIndexValid)
- setAttribute(Qt::WA_InputMethodEnabled, false);
-
- d->viewport->update();
-}
-
-/*!
- This function is called with the given \a event when the widget
- looses the focus. By default, the event is ignored.
-
- \sa clearFocus(), focusInEvent()
-*/
-void QAbstractItemView::focusOutEvent(QFocusEvent *event)
-{
- Q_D(QAbstractItemView);
- QAbstractScrollArea::focusOutEvent(event);
- d->viewport->update();
-
-#ifdef QT_SOFTKEYS_ENABLED
- if(!hasEditFocus())
- removeAction(d->doneSoftKey);
-#endif
-}
-
-/*!
- This function is called with the given \a event when a key event is sent to
- the widget. The default implementation handles basic cursor movement, e.g. Up,
- Down, Left, Right, Home, PageUp, and PageDown; the activated() signal is
- emitted if the current index is valid and the activation key is pressed
- (e.g. Enter or Return, depending on the platform).
- This function is where editing is initiated by key press, e.g. if F2 is
- pressed.
-
- \sa edit(), moveCursor(), keyboardSearch(), tabKeyNavigation
-*/
-void QAbstractItemView::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QAbstractItemView);
- d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling
-
-#ifdef QT_KEYPAD_NAVIGATION
- switch (event->key()) {
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus()) {
- setEditFocus(true);
-#ifdef QT_SOFTKEYS_ENABLED
- // If we can't keypad navigate to any direction, there is no sense to add
- // "Done" softkey, since it basically does nothing when there is
- // only one widget in screen
- if(QWidgetPrivate::canKeypadNavigate(Qt::Horizontal)
- || QWidgetPrivate::canKeypadNavigate(Qt::Vertical))
- addAction(d->doneSoftKey);
-#endif
- return;
- }
- }
- break;
- case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
-#ifdef QT_SOFTKEYS_ENABLED
- removeAction(d->doneSoftKey);
-#endif
- setEditFocus(false);
- } else {
- event->ignore();
- }
- return;
- case Qt::Key_Down:
- case Qt::Key_Up:
- // Let's ignore vertical navigation events, only if there is no other widget
- // what can take the focus in vertical direction. This means widget can handle navigation events
- // even the widget don't have edit focus, and there is no other widget in requested direction.
- if(QApplication::keypadNavigationEnabled() && !hasEditFocus()
- && QWidgetPrivate::canKeypadNavigate(Qt::Vertical)) {
- event->ignore();
- return;
- }
- break;
- case Qt::Key_Left:
- case Qt::Key_Right:
- // Similar logic as in up and down events
- if(QApplication::keypadNavigationEnabled() && !hasEditFocus()
- && (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal) || QWidgetPrivate::inTabWidget(this))) {
- event->ignore();
- return;
- }
- break;
- default:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- event->ignore();
- return;
- }
- }
-#endif
-
-#if !defined(QT_NO_CLIPBOARD) && !defined(QT_NO_SHORTCUT)
- if (event == QKeySequence::Copy) {
- QVariant variant;
- if (d->model)
- variant = d->model->data(currentIndex(), Qt::DisplayRole);
- if (variant.type() == QVariant::String)
- QApplication::clipboard()->setText(variant.toString());
- event->accept();
- }
-#endif
-
- QPersistentModelIndex newCurrent;
- d->moveCursorUpdatedView = false;
- switch (event->key()) {
- case Qt::Key_Down:
- newCurrent = moveCursor(MoveDown, event->modifiers());
- break;
- case Qt::Key_Up:
- newCurrent = moveCursor(MoveUp, event->modifiers());
- break;
- case Qt::Key_Left:
- newCurrent = moveCursor(MoveLeft, event->modifiers());
- break;
- case Qt::Key_Right:
- newCurrent = moveCursor(MoveRight, event->modifiers());
- break;
- case Qt::Key_Home:
- newCurrent = moveCursor(MoveHome, event->modifiers());
- break;
- case Qt::Key_End:
- newCurrent = moveCursor(MoveEnd, event->modifiers());
- break;
- case Qt::Key_PageUp:
- newCurrent = moveCursor(MovePageUp, event->modifiers());
- break;
- case Qt::Key_PageDown:
- newCurrent = moveCursor(MovePageDown, event->modifiers());
- break;
- case Qt::Key_Tab:
- if (d->tabKeyNavigation)
- newCurrent = moveCursor(MoveNext, event->modifiers());
- break;
- case Qt::Key_Backtab:
- if (d->tabKeyNavigation)
- newCurrent = moveCursor(MovePrevious, event->modifiers());
- break;
- }
-
- QPersistentModelIndex oldCurrent = currentIndex();
- if (newCurrent != oldCurrent && newCurrent.isValid() && d->isIndexEnabled(newCurrent)) {
- if (!hasFocus() && QApplication::focusWidget() == indexWidget(oldCurrent))
- setFocus();
- QItemSelectionModel::SelectionFlags command = selectionCommand(newCurrent, event);
- if (command != QItemSelectionModel::NoUpdate
- || style()->styleHint(QStyle::SH_ItemView_MovementWithoutUpdatingSelection, 0, this)) {
- // note that we don't check if the new current index is enabled because moveCursor() makes sure it is
- if (command & QItemSelectionModel::Current) {
- d->selectionModel->setCurrentIndex(newCurrent, QItemSelectionModel::NoUpdate);
- if (!indexAt(d->pressedPosition - d->offset()).isValid())
- d->pressedPosition = visualRect(oldCurrent).center() + d->offset();
- QRect rect(d->pressedPosition - d->offset(), visualRect(newCurrent).center());
- setSelection(rect, command);
- } else {
- d->selectionModel->setCurrentIndex(newCurrent, command);
- d->pressedPosition = visualRect(newCurrent).center() + d->offset();
- if (newCurrent.isValid()) {
- // We copy the same behaviour as for mousePressEvent().
- QRect rect(d->pressedPosition - d->offset(), QSize(1, 1));
- setSelection(rect, command);
- }
- }
- event->accept();
- return;
- }
- }
-
- switch (event->key()) {
- // ignored keys
- case Qt::Key_Down:
- case Qt::Key_Up:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical)) {
- event->accept(); // don't change focus
- break;
- }
-#endif
- case Qt::Key_Left:
- case Qt::Key_Right:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
- && (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal)
- || (QWidgetPrivate::inTabWidget(this) && d->model->columnCount(d->root) > 1))) {
- event->accept(); // don't change focus
- break;
- }
-#endif // QT_KEYPAD_NAVIGATION
- case Qt::Key_Home:
- case Qt::Key_End:
- case Qt::Key_PageUp:
- case Qt::Key_PageDown:
- case Qt::Key_Escape:
- case Qt::Key_Shift:
- case Qt::Key_Control:
- case Qt::Key_Delete:
- case Qt::Key_Backspace:
- event->ignore();
- break;
- case Qt::Key_Space:
- case Qt::Key_Select:
- if (!edit(currentIndex(), AnyKeyPressed, event) && d->selectionModel)
- d->selectionModel->select(currentIndex(), selectionCommand(currentIndex(), event));
-#ifdef QT_KEYPAD_NAVIGATION
- if ( event->key()==Qt::Key_Select ) {
- // Also do Key_Enter action.
- if (currentIndex().isValid()) {
- if (state() != EditingState)
- emit activated(currentIndex());
- } else {
- event->ignore();
- }
- }
-#endif
- break;
-#ifdef Q_WS_MAC
- case Qt::Key_Enter:
- case Qt::Key_Return:
- // Propagate the enter if you couldn't edit the item and there are no
- // current editors (if there are editors, the event was most likely propagated from it).
- if (!edit(currentIndex(), EditKeyPressed, event) && d->editorIndexHash.isEmpty())
- event->ignore();
- break;
-#else
- case Qt::Key_F2:
- if (!edit(currentIndex(), EditKeyPressed, event))
- event->ignore();
- break;
- case Qt::Key_Enter:
- case Qt::Key_Return:
- // ### we can't open the editor on enter, becuse
- // some widgets will forward the enter event back
- // to the viewport, starting an endless loop
- if (state() != EditingState || hasFocus()) {
- if (currentIndex().isValid())
- emit activated(currentIndex());
- event->ignore();
- }
- break;
-#endif
- case Qt::Key_A:
- if (event->modifiers() & Qt::ControlModifier) {
- selectAll();
- break;
- }
- default: {
-#ifdef Q_WS_MAC
- if (event->key() == Qt::Key_O && event->modifiers() & Qt::ControlModifier && currentIndex().isValid()) {
- emit activated(currentIndex());
- break;
- }
-#endif
- bool modified = (event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier));
- if (!event->text().isEmpty() && !modified && !edit(currentIndex(), AnyKeyPressed, event)) {
- keyboardSearch(event->text());
- event->accept();
- } else {
- event->ignore();
- }
- break; }
- }
- if (d->moveCursorUpdatedView)
- event->accept();
-}
-
-/*!
- This function is called with the given \a event when a resize event is sent to
- the widget.
-
- \sa QWidget::resizeEvent()
-*/
-void QAbstractItemView::resizeEvent(QResizeEvent *event)
-{
- QAbstractScrollArea::resizeEvent(event);
- updateGeometries();
-}
-
-/*!
- This function is called with the given \a event when a timer event is sent
- to the widget.
-
- \sa QObject::timerEvent()
-*/
-void QAbstractItemView::timerEvent(QTimerEvent *event)
-{
- Q_D(QAbstractItemView);
- if (event->timerId() == d->fetchMoreTimer.timerId())
- d->fetchMore();
- else if (event->timerId() == d->delayedReset.timerId())
- reset();
- else if (event->timerId() == d->autoScrollTimer.timerId())
- doAutoScroll();
- else if (event->timerId() == d->updateTimer.timerId())
- d->updateDirtyRegion();
- else if (event->timerId() == d->delayedEditing.timerId()) {
- d->delayedEditing.stop();
- edit(currentIndex());
- } else if (event->timerId() == d->delayedLayout.timerId()) {
- d->delayedLayout.stop();
- if (isVisible()) {
- d->interruptDelayedItemsLayout();
- doItemsLayout();
- const QModelIndex current = currentIndex();
- if (current.isValid() && d->state == QAbstractItemView::EditingState)
- scrollTo(current);
- }
- } else if (event->timerId() == d->delayedAutoScroll.timerId()) {
- d->delayedAutoScroll.stop();
- //end of the timer: if the current item is still the same as the one when the mouse press occurred
- //we only get here if there was no double click
- if (d->pressedIndex.isValid() && d->pressedIndex == currentIndex())
- scrollTo(d->pressedIndex);
- }
-}
-
-/*!
- \reimp
-*/
-void QAbstractItemView::inputMethodEvent(QInputMethodEvent *event)
-{
- if (event->commitString().isEmpty() && event->preeditString().isEmpty()) {
- event->ignore();
- return;
- }
- if (!edit(currentIndex(), AnyKeyPressed, event)) {
- if (!event->commitString().isEmpty())
- keyboardSearch(event->commitString());
- event->ignore();
- }
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- \enum QAbstractItemView::DropIndicatorPosition
-
- This enum indicates the position of the drop indicator in
- relation to the index at the current mouse position:
-
- \value OnItem The item will be dropped on the index.
-
- \value AboveItem The item will be dropped above the index.
-
- \value BelowItem The item will be dropped below the index.
-
- \value OnViewport The item will be dropped onto a region of the viewport with
- no items. The way each view handles items dropped onto the viewport depends on
- the behavior of the underlying model in use.
-*/
-
-
-/*!
- \since 4.1
-
- Returns the position of the drop indicator in relation to the closest item.
-*/
-QAbstractItemView::DropIndicatorPosition QAbstractItemView::dropIndicatorPosition() const
-{
- Q_D(const QAbstractItemView);
- return d->dropIndicatorPosition;
-}
-#endif
-
-/*!
- This convenience function returns a list of all selected and
- non-hidden item indexes in the view. The list contains no
- duplicates, and is not sorted.
-
- \sa QItemSelectionModel::selectedIndexes()
-*/
-QModelIndexList QAbstractItemView::selectedIndexes() const
-{
- Q_D(const QAbstractItemView);
- QModelIndexList indexes;
- if (d->selectionModel) {
- indexes = d->selectionModel->selectedIndexes();
- QList<QModelIndex>::iterator it = indexes.begin();
- while (it != indexes.end())
- if (isIndexHidden(*it))
- it = indexes.erase(it);
- else
- ++it;
- }
- return indexes;
-}
-
-/*!
- Starts editing the item at \a index, creating an editor if
- necessary, and returns true if the view's \l{State} is now
- EditingState; otherwise returns false.
-
- The action that caused the editing process is described by
- \a trigger, and the associated event is specified by \a event.
-
- Editing can be forced by specifying the \a trigger to be
- QAbstractItemView::AllEditTriggers.
-
- \sa closeEditor()
-*/
-bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEvent *event)
-{
- Q_D(QAbstractItemView);
-
- if (!d->isIndexValid(index))
- return false;
-
- if (QWidget *w = (d->persistent.isEmpty() ? static_cast<QWidget*>(0) : d->editorForIndex(index).widget.data())) {
- if (w->focusPolicy() == Qt::NoFocus)
- return false;
- w->setFocus();
- return true;
- }
-
- if (trigger == DoubleClicked) {
- d->delayedEditing.stop();
- d->delayedAutoScroll.stop();
- } else if (trigger == CurrentChanged) {
- d->delayedEditing.stop();
- }
-
- if (d->sendDelegateEvent(index, event)) {
- update(index);
- return true;
- }
-
- // save the previous trigger before updating
- EditTriggers lastTrigger = d->lastTrigger;
- d->lastTrigger = trigger;
-
- if (!d->shouldEdit(trigger, d->model->buddy(index)))
- return false;
-
- if (d->delayedEditing.isActive())
- return false;
-
- // we will receive a mouseButtonReleaseEvent after a
- // mouseDoubleClickEvent, so we need to check the previous trigger
- if (lastTrigger == DoubleClicked && trigger == SelectedClicked)
- return false;
-
- // we may get a double click event later
- if (trigger == SelectedClicked)
- d->delayedEditing.start(QApplication::doubleClickInterval(), this);
- else
- d->openEditor(index, d->shouldForwardEvent(trigger, event) ? event : 0);
-
- return true;
-}
-
-/*!
- \internal
- Updates the data shown in the open editor widgets in the view.
-*/
-void QAbstractItemView::updateEditorData()
-{
- Q_D(QAbstractItemView);
- d->updateEditorData(QModelIndex(), QModelIndex());
-}
-
-/*!
- \internal
- Updates the geometry of the open editor widgets in the view.
-*/
-void QAbstractItemView::updateEditorGeometries()
-{
- Q_D(QAbstractItemView);
- if(d->editorIndexHash.isEmpty())
- return;
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- QEditorIndexHash::iterator it = d->editorIndexHash.begin();
- QWidgetList editorsToRelease;
- QWidgetList editorsToHide;
- while (it != d->editorIndexHash.end()) {
- QModelIndex index = it.value();
- QWidget *editor = it.key();
- if (index.isValid() && editor) {
- option.rect = visualRect(index);
- if (option.rect.isValid()) {
- editor->show();
- QAbstractItemDelegate *delegate = d->delegateForIndex(index);
- if (delegate)
- delegate->updateEditorGeometry(editor, option, index);
- } else {
- editorsToHide << editor;
- }
- ++it;
- } else {
- d->indexEditorHash.remove(it.value());
- it = d->editorIndexHash.erase(it);
- editorsToRelease << editor;
- }
- }
-
- //we hide and release the editor outside of the loop because it might change the focus and try
- //to change the editors hashes.
- for (int i = 0; i < editorsToHide.count(); ++i) {
- editorsToHide.at(i)->hide();
- }
- for (int i = 0; i < editorsToRelease.count(); ++i) {
- d->releaseEditor(editorsToRelease.at(i));
- }
-}
-
-/*!
- \since 4.4
-
- Updates the geometry of the child widgets of the view.
-*/
-void QAbstractItemView::updateGeometries()
-{
- updateEditorGeometries();
- d_func()->fetchMoreTimer.start(0, this); //fetch more later
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::verticalScrollbarValueChanged(int value)
-{
- Q_D(QAbstractItemView);
- if (verticalScrollBar()->maximum() == value && d->model->canFetchMore(d->root))
- d->model->fetchMore(d->root);
- QPoint posInVp = viewport()->mapFromGlobal(QCursor::pos());
- if (viewport()->rect().contains(posInVp))
- d->checkMouseMove(posInVp);
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::horizontalScrollbarValueChanged(int value)
-{
- Q_D(QAbstractItemView);
- if (horizontalScrollBar()->maximum() == value && d->model->canFetchMore(d->root))
- d->model->fetchMore(d->root);
- QPoint posInVp = viewport()->mapFromGlobal(QCursor::pos());
- if (viewport()->rect().contains(posInVp))
- d->checkMouseMove(posInVp);
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::verticalScrollbarAction(int)
-{
- //do nothing
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::horizontalScrollbarAction(int)
-{
- //do nothing
-}
-
-/*!
- Closes the given \a editor, and releases it. The \a hint is
- used to specify how the view should respond to the end of the editing
- operation. For example, the hint may indicate that the next item in
- the view should be opened for editing.
-
- \sa edit(), commitData()
-*/
-
-void QAbstractItemView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
-{
- Q_D(QAbstractItemView);
-
- // Close the editor
- if (editor) {
- bool isPersistent = d->persistent.contains(editor);
- bool hadFocus = editor->hasFocus();
- QModelIndex index = d->indexForEditor(editor);
- if (!index.isValid())
- return; // the editor was not registered
-
- if (!isPersistent) {
- setState(NoState);
- QModelIndex index = d->indexForEditor(editor);
- editor->removeEventFilter(d->delegateForIndex(index));
- d->removeEditor(editor);
- }
- if (hadFocus)
- setFocus(); // this will send a focusLost event to the editor
- else
- d->checkPersistentEditorFocus();
-
- QPointer<QWidget> ed = editor;
- QApplication::sendPostedEvents(editor, 0);
- editor = ed;
-
- if (!isPersistent && editor)
- d->releaseEditor(editor);
- }
-
- // The EndEditHint part
- QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::ClearAndSelect
- | d->selectionBehaviorFlags();
- switch (hint) {
- case QAbstractItemDelegate::EditNextItem: {
- QModelIndex index = moveCursor(MoveNext, Qt::NoModifier);
- if (index.isValid()) {
- QPersistentModelIndex persistent(index);
- d->selectionModel->setCurrentIndex(persistent, flags);
- // currentChanged signal would have already started editing
- if (index.flags() & Qt::ItemIsEditable
- && (!(editTriggers() & QAbstractItemView::CurrentChanged)))
- edit(persistent);
- } break; }
- case QAbstractItemDelegate::EditPreviousItem: {
- QModelIndex index = moveCursor(MovePrevious, Qt::NoModifier);
- if (index.isValid()) {
- QPersistentModelIndex persistent(index);
- d->selectionModel->setCurrentIndex(persistent, flags);
- // currentChanged signal would have already started editing
- if (index.flags() & Qt::ItemIsEditable
- && (!(editTriggers() & QAbstractItemView::CurrentChanged)))
- edit(persistent);
- } break; }
- case QAbstractItemDelegate::SubmitModelCache:
- d->model->submit();
- break;
- case QAbstractItemDelegate::RevertModelCache:
- d->model->revert();
- break;
- default:
- break;
- }
-}
-
-/*!
- Commit the data in the \a editor to the model.
-
- \sa closeEditor()
-*/
-void QAbstractItemView::commitData(QWidget *editor)
-{
- Q_D(QAbstractItemView);
- if (!editor || !d->itemDelegate || d->currentlyCommittingEditor)
- return;
- QModelIndex index = d->indexForEditor(editor);
- if (!index.isValid())
- return;
- d->currentlyCommittingEditor = editor;
- QAbstractItemDelegate *delegate = d->delegateForIndex(index);
- editor->removeEventFilter(delegate);
- delegate->setModelData(editor, d->model, index);
- editor->installEventFilter(delegate);
- d->currentlyCommittingEditor = 0;
-}
-
-/*!
- This function is called when the given \a editor has been destroyed.
-
- \sa closeEditor()
-*/
-void QAbstractItemView::editorDestroyed(QObject *editor)
-{
- Q_D(QAbstractItemView);
- QWidget *w = qobject_cast<QWidget*>(editor);
- d->removeEditor(w);
- d->persistent.remove(w);
- if (state() == EditingState)
- setState(NoState);
-}
-
-/*!
- \obsolete
- Sets the horizontal scroll bar's steps per item to \a steps.
-
- This is the number of steps used by the horizontal scroll bar to
- represent the width of an item.
-
- Note that if the view has a horizontal header, the item steps
- will be ignored and the header section size will be used instead.
-
- \sa horizontalStepsPerItem() setVerticalStepsPerItem()
-*/
-void QAbstractItemView::setHorizontalStepsPerItem(int steps)
-{
- Q_UNUSED(steps);
- // do nothing
-}
-
-/*!
- \obsolete
- Returns the horizontal scroll bar's steps per item.
-
- \sa setHorizontalStepsPerItem() verticalStepsPerItem()
-*/
-int QAbstractItemView::horizontalStepsPerItem() const
-{
- return 1;
-}
-
-/*!
- \obsolete
- Sets the vertical scroll bar's steps per item to \a steps.
-
- This is the number of steps used by the vertical scroll bar to
- represent the height of an item.
-
- Note that if the view has a vertical header, the item steps
- will be ignored and the header section size will be used instead.
-
- \sa verticalStepsPerItem() setHorizontalStepsPerItem()
-*/
-void QAbstractItemView::setVerticalStepsPerItem(int steps)
-{
- Q_UNUSED(steps);
- // do nothing
-}
-
-/*!
- \obsolete
- Returns the vertical scroll bar's steps per item.
-
- \sa setVerticalStepsPerItem() horizontalStepsPerItem()
-*/
-int QAbstractItemView::verticalStepsPerItem() const
-{
- return 1;
-}
-
-/*!
- Moves to and selects the item best matching the string \a search.
- If no item is found nothing happens.
-
- In the default implementation, the search is reset if \a search is empty, or
- the time interval since the last search has exceeded
- QApplication::keyboardInputInterval().
-*/
-void QAbstractItemView::keyboardSearch(const QString &search)
-{
- Q_D(QAbstractItemView);
- if (!d->model->rowCount(d->root) || !d->model->columnCount(d->root))
- return;
-
- QModelIndex start = currentIndex().isValid() ? currentIndex()
- : d->model->index(0, 0, d->root);
- bool skipRow = false;
- bool keyboardTimeWasValid = d->keyboardInputTime.isValid();
- qint64 keyboardInputTimeElapsed = d->keyboardInputTime.restart();
- if (search.isEmpty() || !keyboardTimeWasValid
- || keyboardInputTimeElapsed > QApplication::keyboardInputInterval()) {
- d->keyboardInput = search;
- skipRow = currentIndex().isValid(); //if it is not valid we should really start at QModelIndex(0,0)
- } else {
- d->keyboardInput += search;
- }
-
- // special case for searches with same key like 'aaaaa'
- bool sameKey = false;
- if (d->keyboardInput.length() > 1) {
- int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1));
- sameKey = (c == d->keyboardInput.length());
- if (sameKey)
- skipRow = true;
- }
-
- // skip if we are searching for the same key or a new search started
- if (skipRow) {
- QModelIndex parent = start.parent();
- int newRow = (start.row() < d->model->rowCount(parent) - 1) ? start.row() + 1 : 0;
- start = d->model->index(newRow, start.column(), parent);
- }
-
- // search from start with wraparound
- const QString searchString = sameKey ? QString(d->keyboardInput.at(0)) : d->keyboardInput;
- QModelIndex current = start;
- QModelIndexList match;
- QModelIndex firstMatch;
- QModelIndex startMatch;
- QModelIndexList previous;
- do {
- match = d->model->match(current, Qt::DisplayRole, searchString);
- if (match == previous)
- break;
- firstMatch = match.value(0);
- previous = match;
- if (firstMatch.isValid()) {
- if (d->isIndexEnabled(firstMatch)) {
- setCurrentIndex(firstMatch);
- break;
- }
- int row = firstMatch.row() + 1;
- if (row >= d->model->rowCount(firstMatch.parent()))
- row = 0;
- current = firstMatch.sibling(row, firstMatch.column());
-
- //avoid infinite loop if all the matching items are disabled.
- if (!startMatch.isValid())
- startMatch = firstMatch;
- else if (startMatch == firstMatch)
- break;
- }
- } while (current != start && firstMatch.isValid());
-}
-
-/*!
- Returns the size hint for the item with the specified \a index or
- an invalid size for invalid indexes.
-
- \sa sizeHintForRow(), sizeHintForColumn()
-*/
-QSize QAbstractItemView::sizeHintForIndex(const QModelIndex &index) const
-{
- Q_D(const QAbstractItemView);
- if (!d->isIndexValid(index) || !d->itemDelegate)
- return QSize();
- return d->delegateForIndex(index)->sizeHint(d->viewOptionsV4(), index);
-}
-
-/*!
- Returns the height size hint for the specified \a row or -1 if
- there is no model.
-
- The returned height is calculated using the size hints of the
- given \a row's items, i.e. the returned value is the maximum
- height among the items. Note that to control the height of a row,
- you must reimplement the QAbstractItemDelegate::sizeHint()
- function.
-
- This function is used in views with a vertical header to find the
- size hint for a header section based on the contents of the given
- \a row.
-
- \sa sizeHintForColumn()
-*/
-int QAbstractItemView::sizeHintForRow(int row) const
-{
- Q_D(const QAbstractItemView);
-
- if (row < 0 || row >= d->model->rowCount(d->root))
- return -1;
-
- ensurePolished();
-
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- int height = 0;
- int colCount = d->model->columnCount(d->root);
- QModelIndex index;
- for (int c = 0; c < colCount; ++c) {
- index = d->model->index(row, c, d->root);
- if (QWidget *editor = d->editorForIndex(index).widget.data())
- height = qMax(height, editor->height());
- int hint = d->delegateForIndex(index)->sizeHint(option, index).height();
- height = qMax(height, hint);
- }
- return height;
-}
-
-/*!
- Returns the width size hint for the specified \a column or -1 if there is no model.
-
- This function is used in views with a horizontal header to find the size hint for
- a header section based on the contents of the given \a column.
-
- \sa sizeHintForRow()
-*/
-int QAbstractItemView::sizeHintForColumn(int column) const
-{
- Q_D(const QAbstractItemView);
-
- if (column < 0 || column >= d->model->columnCount(d->root))
- return -1;
-
- ensurePolished();
-
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- int width = 0;
- int rows = d->model->rowCount(d->root);
- QModelIndex index;
- for (int r = 0; r < rows; ++r) {
- index = d->model->index(r, column, d->root);
- if (QWidget *editor = d->editorForIndex(index).widget.data())
- width = qMax(width, editor->sizeHint().width());
- int hint = d->delegateForIndex(index)->sizeHint(option, index).width();
- width = qMax(width, hint);
- }
- return width;
-}
-
-/*!
- Opens a persistent editor on the item at the given \a index.
- If no editor exists, the delegate will create a new editor.
-
- \sa closePersistentEditor()
-*/
-void QAbstractItemView::openPersistentEditor(const QModelIndex &index)
-{
- Q_D(QAbstractItemView);
- QStyleOptionViewItemV4 options = d->viewOptionsV4();
- options.rect = visualRect(index);
- options.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
-
- QWidget *editor = d->editor(index, options);
- if (editor) {
- editor->show();
- d->persistent.insert(editor);
- }
-}
-
-/*!
- Closes the persistent editor for the item at the given \a index.
-
- \sa openPersistentEditor()
-*/
-void QAbstractItemView::closePersistentEditor(const QModelIndex &index)
-{
- Q_D(QAbstractItemView);
- if (QWidget *editor = d->editorForIndex(index).widget.data()) {
- if (index == selectionModel()->currentIndex())
- closeEditor(editor, QAbstractItemDelegate::RevertModelCache);
- d->persistent.remove(editor);
- d->removeEditor(editor);
- d->releaseEditor(editor);
- }
-}
-
-/*!
- \since 4.1
-
- Sets the given \a widget on the item at the given \a index, passing the
- ownership of the widget to the viewport.
-
- If \a index is invalid (e.g., if you pass the root index), this function
- will do nothing.
-
- The given \a widget's \l{QWidget}{autoFillBackground} property must be set
- to true, otherwise the widget's background will be transparent, showing
- both the model data and the item at the given \a index.
-
- If index widget A is replaced with index widget B, index widget A will be
- deleted. For example, in the code snippet below, the QLineEdit object will
- be deleted.
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp 1
-
- This function should only be used to display static content within the
- visible area corresponding to an item of data. If you want to display
- custom dynamic content or implement a custom editor widget, subclass
- QItemDelegate instead.
-
- \sa {Delegate Classes}
-*/
-void QAbstractItemView::setIndexWidget(const QModelIndex &index, QWidget *widget)
-{
- Q_D(QAbstractItemView);
- if (!d->isIndexValid(index))
- return;
- if (QWidget *oldWidget = indexWidget(index)) {
- d->persistent.remove(oldWidget);
- d->removeEditor(oldWidget);
- oldWidget->deleteLater();
- }
- if (widget) {
- widget->setParent(viewport());
- d->persistent.insert(widget);
- d->addEditor(index, widget, true);
- widget->show();
- dataChanged(index, index); // update the geometry
- if (!d->delayedPendingLayout)
- widget->setGeometry(visualRect(index));
- }
-}
-
-/*!
- \since 4.1
-
- Returns the widget for the item at the given \a index.
-*/
-QWidget* QAbstractItemView::indexWidget(const QModelIndex &index) const
-{
- Q_D(const QAbstractItemView);
- if (d->isIndexValid(index))
- if (QWidget *editor = d->editorForIndex(index).widget.data())
- return editor;
-
- return 0;
-}
-
-/*!
- \since 4.1
-
- Scrolls the view to the top.
-
- \sa scrollTo(), scrollToBottom()
-*/
-void QAbstractItemView::scrollToTop()
-{
- verticalScrollBar()->setValue(verticalScrollBar()->minimum());
-}
-
-/*!
- \since 4.1
-
- Scrolls the view to the bottom.
-
- \sa scrollTo(), scrollToTop()
-*/
-void QAbstractItemView::scrollToBottom()
-{
- Q_D(QAbstractItemView);
- if (d->delayedPendingLayout) {
- d->executePostedLayout();
- updateGeometries();
- }
- verticalScrollBar()->setValue(verticalScrollBar()->maximum());
-}
-
-/*!
- \since 4.3
-
- Updates the area occupied by the given \a index.
-
-*/
-void QAbstractItemView::update(const QModelIndex &index)
-{
- Q_D(QAbstractItemView);
- if (index.isValid()) {
- const QRect rect = visualRect(index);
- //this test is important for peformance reason
- //For example in dataChanged we simply update all the cells without checking
- //it can be a major bottleneck to update rects that aren't even part of the viewport
- if (d->viewport->rect().intersects(rect))
- d->viewport->update(rect);
- }
-}
-
-/*!
- This slot is called when items are changed in the model. The
- changed items are those from \a topLeft to \a bottomRight
- inclusive. If just one item is changed \a topLeft == \a
- bottomRight.
-*/
-void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- // Single item changed
- Q_D(QAbstractItemView);
- if (topLeft == bottomRight && topLeft.isValid()) {
- const QEditorInfo &editorInfo = d->editorForIndex(topLeft);
- //we don't update the edit data if it is static
- if (!editorInfo.isStatic && editorInfo.widget) {
- QAbstractItemDelegate *delegate = d->delegateForIndex(topLeft);
- if (delegate) {
- delegate->setEditorData(editorInfo.widget.data(), topLeft);
- }
- }
- if (isVisible() && !d->delayedPendingLayout) {
- // otherwise the items will be update later anyway
- update(topLeft);
- }
- return;
- }
- d->updateEditorData(topLeft, bottomRight);
- if (!isVisible() || d->delayedPendingLayout)
- return; // no need to update
- d->viewport->update();
-}
-
-/*!
- This slot is called when rows are inserted. The new rows are those
- under the given \a parent from \a start to \a end inclusive. The
- base class implementation calls fetchMore() on the model to check
- for more data.
-
- \sa rowsAboutToBeRemoved()
-*/
-void QAbstractItemView::rowsInserted(const QModelIndex &, int, int)
-{
- if (!isVisible())
- d_func()->fetchMoreTimer.start(0, this); //fetch more later
- else
- updateEditorGeometries();
-}
-
-/*!
- This slot is called when rows are about to be removed. The deleted rows are
- those under the given \a parent from \a start to \a end inclusive.
-
- \sa rowsInserted()
-*/
-void QAbstractItemView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
-{
- Q_D(QAbstractItemView);
-
- setState(CollapsingState);
-
- // Ensure one selected item in single selection mode.
- QModelIndex current = currentIndex();
- if (d->selectionMode == SingleSelection
- && current.isValid()
- && current.row() >= start
- && current.row() <= end
- && current.parent() == parent) {
- int totalToRemove = end - start + 1;
- if (d->model->rowCount(parent) <= totalToRemove) { // no more children
- QModelIndex index = parent;
- while (index != d->root && !d->isIndexEnabled(index))
- index = index.parent();
- if (index != d->root)
- setCurrentIndex(index);
- } else {
- int row = end + 1;
- QModelIndex next;
- do { // find the next visible and enabled item
- next = d->model->index(row++, current.column(), current.parent());
- } while (next.isValid() && (isIndexHidden(next) || !d->isIndexEnabled(next)));
- if (row > d->model->rowCount(parent)) {
- row = start - 1;
- do { // find the previous visible and enabled item
- next = d->model->index(row--, current.column(), current.parent());
- } while (next.isValid() && (isIndexHidden(next) || !d->isIndexEnabled(next)));
- }
- setCurrentIndex(next);
- }
- }
-
- // Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
- QEditorIndexHash::iterator i = d->editorIndexHash.begin();
- while (i != d->editorIndexHash.end()) {
- const QModelIndex index = i.value();
- if (index.row() >= start && index.row() <= end && d->model->parent(index) == parent) {
- QWidget *editor = i.key();
- QEditorInfo info = d->indexEditorHash.take(index);
- i = d->editorIndexHash.erase(i);
- if (info.widget)
- d->releaseEditor(editor);
- } else {
- ++i;
- }
- }
-}
-
-/*!
- \internal
-
- This slot is called when rows have been removed. The deleted
- rows are those under the given \a parent from \a start to \a end
- inclusive.
-*/
-void QAbstractItemViewPrivate::_q_rowsRemoved(const QModelIndex &, int, int)
-{
- Q_Q(QAbstractItemView);
- if (q->isVisible())
- q->updateEditorGeometries();
- q->setState(QAbstractItemView::NoState);
-}
-
-/*!
- \internal
-
- This slot is called when columns are about to be removed. The deleted
- columns are those under the given \a parent from \a start to \a end
- inclusive.
-*/
-void QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
-{
- Q_Q(QAbstractItemView);
-
- q->setState(QAbstractItemView::CollapsingState);
-
- // Ensure one selected item in single selection mode.
- QModelIndex current = q->currentIndex();
- if (current.isValid()
- && selectionMode == QAbstractItemView::SingleSelection
- && current.column() >= start
- && current.column() <= end) {
- int totalToRemove = end - start + 1;
- if (model->columnCount(parent) < totalToRemove) { // no more columns
- QModelIndex index = parent;
- while (index.isValid() && !isIndexEnabled(index))
- index = index.parent();
- if (index.isValid())
- q->setCurrentIndex(index);
- } else {
- int column = end;
- QModelIndex next;
- do { // find the next visible and enabled item
- next = model->index(current.row(), column++, current.parent());
- } while (next.isValid() && (q->isIndexHidden(next) || !isIndexEnabled(next)));
- q->setCurrentIndex(next);
- }
- }
-
- // Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
- QEditorIndexHash::iterator it = editorIndexHash.begin();
- while (it != editorIndexHash.end()) {
- QModelIndex index = it.value();
- if (index.column() <= start && index.column() >= end && model->parent(index) == parent) {
- QWidget *editor = it.key();
- QEditorInfo info = indexEditorHash.take(it.value());
- it = editorIndexHash.erase(it);
- if (info.widget)
- releaseEditor(editor);
- } else {
- ++it;
- }
- }
-
-}
-
-/*!
- \internal
-
- This slot is called when columns have been removed. The deleted
- rows are those under the given \a parent from \a start to \a end
- inclusive.
-*/
-void QAbstractItemViewPrivate::_q_columnsRemoved(const QModelIndex &, int, int)
-{
- Q_Q(QAbstractItemView);
- if (q->isVisible())
- q->updateEditorGeometries();
- q->setState(QAbstractItemView::NoState);
-}
-
-/*!
- \internal
-
- This slot is called when rows have been inserted.
-*/
-void QAbstractItemViewPrivate::_q_columnsInserted(const QModelIndex &, int, int)
-{
- Q_Q(QAbstractItemView);
- if (q->isVisible())
- q->updateEditorGeometries();
-}
-
-
-
-/*!
- \internal
-*/
-void QAbstractItemViewPrivate::_q_modelDestroyed()
-{
- model = QAbstractItemModelPrivate::staticEmptyModel();
- doDelayedReset();
-}
-
-/*!
- \internal
-
- This slot is called when the layout is changed.
-*/
-void QAbstractItemViewPrivate::_q_layoutChanged()
-{
- doDelayedItemsLayout();
-}
-
-/*!
- This slot is called when the selection is changed. The previous
- selection (which may be empty), is specified by \a deselected, and the
- new selection by \a selected.
-
- \sa setSelection()
-*/
-void QAbstractItemView::selectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected)
-{
- Q_D(QAbstractItemView);
- if (isVisible() && updatesEnabled()) {
- d->viewport->update(visualRegionForSelection(deselected) | visualRegionForSelection(selected));
- }
-}
-
-/*!
- This slot is called when a new item becomes the current item.
- The previous current item is specified by the \a previous index, and the new
- item by the \a current index.
-
- If you want to know about changes to items see the
- dataChanged() signal.
-*/
-void QAbstractItemView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
-{
- Q_D(QAbstractItemView);
- Q_ASSERT(d->model);
-
- if (previous.isValid()) {
- QModelIndex buddy = d->model->buddy(previous);
- QWidget *editor = d->editorForIndex(buddy).widget.data();
- if (editor && !d->persistent.contains(editor)) {
- commitData(editor);
- if (current.row() != previous.row())
- closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
- else
- closeEditor(editor, QAbstractItemDelegate::NoHint);
- }
- if (isVisible()) {
- update(previous);
- }
- }
-
- if (current.isValid() && !d->autoScrollTimer.isActive()) {
- if (isVisible()) {
- if (d->autoScroll)
- scrollTo(current);
- update(current);
- edit(current, CurrentChanged, 0);
- if (current.row() == (d->model->rowCount(d->root) - 1))
- d->fetchMore();
- } else {
- d->shouldScrollToCurrentOnShow = d->autoScroll;
- }
- }
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- Starts a drag by calling drag->exec() using the given \a supportedActions.
-*/
-void QAbstractItemView::startDrag(Qt::DropActions supportedActions)
-{
- Q_D(QAbstractItemView);
- QModelIndexList indexes = d->selectedDraggableIndexes();
- if (indexes.count() > 0) {
- QMimeData *data = d->model->mimeData(indexes);
- if (!data)
- return;
- QRect rect;
- QPixmap pixmap = d->renderToPixmap(indexes, &rect);
- rect.adjust(horizontalOffset(), verticalOffset(), 0, 0);
- QDrag *drag = new QDrag(this);
- drag->setPixmap(pixmap);
- drag->setMimeData(data);
- drag->setHotSpot(d->pressedPosition - rect.topLeft());
- Qt::DropAction defaultDropAction = Qt::IgnoreAction;
- if (d->defaultDropAction != Qt::IgnoreAction && (supportedActions & d->defaultDropAction))
- defaultDropAction = d->defaultDropAction;
- else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove)
- defaultDropAction = Qt::CopyAction;
- if (drag->exec(supportedActions, defaultDropAction) == Qt::MoveAction)
- d->clearOrRemove();
- }
-}
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- Returns a QStyleOptionViewItem structure populated with the view's
- palette, font, state, alignments etc.
-*/
-QStyleOptionViewItem QAbstractItemView::viewOptions() const
-{
- Q_D(const QAbstractItemView);
- QStyleOptionViewItem option;
- option.init(this);
- option.state &= ~QStyle::State_MouseOver;
- option.font = font();
-
-#ifndef Q_WS_MAC
- // On mac the focus appearance follows window activation
- // not widget activation
- if (!hasFocus())
- option.state &= ~QStyle::State_Active;
-#endif
-
- option.state &= ~QStyle::State_HasFocus;
- if (d->iconSize.isValid()) {
- option.decorationSize = d->iconSize;
- } else {
- int pm = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this);
- option.decorationSize = QSize(pm, pm);
- }
- option.decorationPosition = QStyleOptionViewItem::Left;
- option.decorationAlignment = Qt::AlignCenter;
- option.displayAlignment = Qt::AlignLeft|Qt::AlignVCenter;
- option.textElideMode = d->textElideMode;
- option.rect = QRect();
- option.showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, 0, this);
- return option;
-}
-
-QStyleOptionViewItemV4 QAbstractItemViewPrivate::viewOptionsV4() const
-{
- Q_Q(const QAbstractItemView);
- QStyleOptionViewItemV4 option = q->viewOptions();
- if (wrapItemText)
- option.features = QStyleOptionViewItemV2::WrapText;
- option.locale = q->locale();
- option.locale.setNumberOptions(QLocale::OmitGroupSeparator);
- option.widget = q;
- return option;
-}
-
-/*!
- Returns the item view's state.
-
- \sa setState()
-*/
-QAbstractItemView::State QAbstractItemView::state() const
-{
- Q_D(const QAbstractItemView);
- return d->state;
-}
-
-/*!
- Sets the item view's state to the given \a state.
-
- \sa state()
-*/
-void QAbstractItemView::setState(State state)
-{
- Q_D(QAbstractItemView);
- d->state = state;
-}
-
-/*!
- Schedules a layout of the items in the view to be executed when the
- event processing starts.
-
- Even if scheduleDelayedItemsLayout() is called multiple times before
- events are processed, the view will only do the layout once.
-
- \sa executeDelayedItemsLayout()
-*/
-void QAbstractItemView::scheduleDelayedItemsLayout()
-{
- Q_D(QAbstractItemView);
- d->doDelayedItemsLayout();
-}
-
-/*!
- Executes the scheduled layouts without waiting for the event processing
- to begin.
-
- \sa scheduleDelayedItemsLayout()
-*/
-void QAbstractItemView::executeDelayedItemsLayout()
-{
- Q_D(QAbstractItemView);
- d->executePostedLayout();
-}
-
-/*!
- \since 4.1
-
- Marks the given \a region as dirty and schedules it to be updated.
- You only need to call this function if you are implementing
- your own view subclass.
-
- \sa scrollDirtyRegion(), dirtyRegionOffset()
-*/
-
-void QAbstractItemView::setDirtyRegion(const QRegion &region)
-{
- Q_D(QAbstractItemView);
- d->setDirtyRegion(region);
-}
-
-/*!
- Prepares the view for scrolling by (\a{dx},\a{dy}) pixels by moving the dirty regions in the
- opposite direction. You only need to call this function if you are implementing a scrolling
- viewport in your view subclass.
-
- If you implement scrollContentsBy() in a subclass of QAbstractItemView, call this function
- before you call QWidget::scroll() on the viewport. Alternatively, just call update().
-
- \sa scrollContentsBy(), dirtyRegionOffset(), setDirtyRegion()
-*/
-void QAbstractItemView::scrollDirtyRegion(int dx, int dy)
-{
- Q_D(QAbstractItemView);
- d->scrollDirtyRegion(dx, dy);
-}
-
-/*!
- Returns the offset of the dirty regions in the view.
-
- If you use scrollDirtyRegion() and implement a paintEvent() in a subclass of
- QAbstractItemView, you should translate the area given by the paint event with
- the offset returned from this function.
-
- \sa scrollDirtyRegion(), setDirtyRegion()
-*/
-QPoint QAbstractItemView::dirtyRegionOffset() const
-{
- Q_D(const QAbstractItemView);
- return d->scrollDelayOffset;
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::startAutoScroll()
-{
- d_func()->startAutoScroll();
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::stopAutoScroll()
-{
- d_func()->stopAutoScroll();
-}
-
-/*!
- \internal
-*/
-void QAbstractItemView::doAutoScroll()
-{
- // find how much we should scroll with
- Q_D(QAbstractItemView);
- int verticalStep = verticalScrollBar()->pageStep();
- int horizontalStep = horizontalScrollBar()->pageStep();
- if (d->autoScrollCount < qMax(verticalStep, horizontalStep))
- ++d->autoScrollCount;
-
- int margin = d->autoScrollMargin;
- int verticalValue = verticalScrollBar()->value();
- int horizontalValue = horizontalScrollBar()->value();
-
- QPoint pos = d->viewport->mapFromGlobal(QCursor::pos());
- QRect area = static_cast<QAbstractItemView*>(d->viewport)->d_func()->clipRect(); // access QWidget private by bending C++ rules
-
- // do the scrolling if we are in the scroll margins
- if (pos.y() - area.top() < margin)
- verticalScrollBar()->setValue(verticalValue - d->autoScrollCount);
- else if (area.bottom() - pos.y() < margin)
- verticalScrollBar()->setValue(verticalValue + d->autoScrollCount);
- if (pos.x() - area.left() < margin)
- horizontalScrollBar()->setValue(horizontalValue - d->autoScrollCount);
- else if (area.right() - pos.x() < margin)
- horizontalScrollBar()->setValue(horizontalValue + d->autoScrollCount);
- // if nothing changed, stop scrolling
- bool verticalUnchanged = (verticalValue == verticalScrollBar()->value());
- bool horizontalUnchanged = (horizontalValue == horizontalScrollBar()->value());
- if (verticalUnchanged && horizontalUnchanged) {
- stopAutoScroll();
- } else {
-#ifndef QT_NO_DRAGANDDROP
- d->dropIndicatorRect = QRect();
- d->dropIndicatorPosition = QAbstractItemView::OnViewport;
-#endif
- d->viewport->update();
- }
-}
-
-/*!
- Returns the SelectionFlags to be used when updating a selection with
- to include the \a index specified. The \a event is a user input event,
- such as a mouse or keyboard event.
-
- Reimplement this function to define your own selection behavior.
-
- \sa setSelection()
-*/
-QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QModelIndex &index,
- const QEvent *event) const
-{
- Q_D(const QAbstractItemView);
- switch (d->selectionMode) {
- case NoSelection: // Never update selection model
- return QItemSelectionModel::NoUpdate;
- case SingleSelection: // ClearAndSelect on valid index otherwise NoUpdate
- if (event && event->type() == QEvent::MouseButtonRelease)
- return QItemSelectionModel::NoUpdate;
- return QItemSelectionModel::ClearAndSelect|d->selectionBehaviorFlags();
- case MultiSelection:
- return d->multiSelectionCommand(index, event);
- case ExtendedSelection:
- return d->extendedSelectionCommand(index, event);
- case ContiguousSelection:
- return d->contiguousSelectionCommand(index, event);
- }
- return QItemSelectionModel::NoUpdate;
-}
-
-QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionCommand(
- const QModelIndex &index, const QEvent *event) const
-{
- Q_UNUSED(index);
-
- if (event) {
- switch (event->type()) {
- case QEvent::KeyPress:
- if (static_cast<const QKeyEvent*>(event)->key() == Qt::Key_Space
- || static_cast<const QKeyEvent*>(event)->key() == Qt::Key_Select)
- return QItemSelectionModel::Toggle|selectionBehaviorFlags();
- break;
- case QEvent::MouseButtonPress:
- if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton)
- return QItemSelectionModel::Toggle|selectionBehaviorFlags(); // toggle
- break;
- case QEvent::MouseButtonRelease:
- if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton)
- return QItemSelectionModel::NoUpdate|selectionBehaviorFlags(); // finalize
- break;
- case QEvent::MouseMove:
- if (static_cast<const QMouseEvent*>(event)->buttons() & Qt::LeftButton)
- return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags(); // toggle drag select
- default:
- break;
- }
- return QItemSelectionModel::NoUpdate;
- }
-
- return QItemSelectionModel::Toggle|selectionBehaviorFlags();
-}
-
-QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionCommand(
- const QModelIndex &index, const QEvent *event) const
-{
- Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
- if (event) {
- switch (event->type()) {
- case QEvent::MouseMove: {
- // Toggle on MouseMove
- modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
- if (modifiers & Qt::ControlModifier)
- return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags();
- break;
- }
- case QEvent::MouseButtonPress: {
- modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
- const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
- const bool rightButtonPressed = button & Qt::RightButton;
- const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
- const bool controlKeyPressed = modifiers & Qt::ControlModifier;
- const bool indexIsSelected = selectionModel->isSelected(index);
- if ((shiftKeyPressed || controlKeyPressed) && rightButtonPressed)
- return QItemSelectionModel::NoUpdate;
- if (!shiftKeyPressed && !controlKeyPressed && indexIsSelected)
- return QItemSelectionModel::NoUpdate;
- if (!index.isValid() && !rightButtonPressed && !shiftKeyPressed && !controlKeyPressed)
- return QItemSelectionModel::Clear;
- if (!index.isValid())
- return QItemSelectionModel::NoUpdate;
- break;
- }
- case QEvent::MouseButtonRelease: {
- // ClearAndSelect on MouseButtonRelease if MouseButtonPress on selected item or empty area
- modifiers = static_cast<const QMouseEvent*>(event)->modifiers();
- const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
- const bool rightButtonPressed = button & Qt::RightButton;
- const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
- const bool controlKeyPressed = modifiers & Qt::ControlModifier;
- if (((index == pressedIndex && selectionModel->isSelected(index))
- || !index.isValid()) && state != QAbstractItemView::DragSelectingState
- && !shiftKeyPressed && !controlKeyPressed && (!rightButtonPressed || !index.isValid()))
- return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
- return QItemSelectionModel::NoUpdate;
- }
- case QEvent::KeyPress: {
- // NoUpdate on Key movement and Ctrl
- modifiers = static_cast<const QKeyEvent*>(event)->modifiers();
- switch (static_cast<const QKeyEvent*>(event)->key()) {
- case Qt::Key_Backtab:
- modifiers = modifiers & ~Qt::ShiftModifier; // special case for backtab
- case Qt::Key_Down:
- case Qt::Key_Up:
- case Qt::Key_Left:
- case Qt::Key_Right:
- case Qt::Key_Home:
- case Qt::Key_End:
- case Qt::Key_PageUp:
- case Qt::Key_PageDown:
- case Qt::Key_Tab:
- if (modifiers & Qt::ControlModifier
-#ifdef QT_KEYPAD_NAVIGATION
- // Preserve historical tab order navigation behavior
- || QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
-#endif
- )
- return QItemSelectionModel::NoUpdate;
- break;
- case Qt::Key_Select:
- return QItemSelectionModel::Toggle|selectionBehaviorFlags();
- case Qt::Key_Space:// Toggle on Ctrl-Qt::Key_Space, Select on Space
- if (modifiers & Qt::ControlModifier)
- return QItemSelectionModel::Toggle|selectionBehaviorFlags();
- return QItemSelectionModel::Select|selectionBehaviorFlags();
- default:
- break;
- }
- }
- default:
- break;
- }
- }
-
- if (modifiers & Qt::ShiftModifier)
- return QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
- if (modifiers & Qt::ControlModifier)
- return QItemSelectionModel::Toggle|selectionBehaviorFlags();
- if (state == QAbstractItemView::DragSelectingState) {
- //when drag-selecting we need to clear any previous selection and select the current one
- return QItemSelectionModel::Clear|QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
- }
-
- return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
-}
-
-QItemSelectionModel::SelectionFlags
-QAbstractItemViewPrivate::contiguousSelectionCommand(const QModelIndex &index,
- const QEvent *event) const
-{
- QItemSelectionModel::SelectionFlags flags = extendedSelectionCommand(index, event);
- const int Mask = QItemSelectionModel::Clear | QItemSelectionModel::Select
- | QItemSelectionModel::Deselect | QItemSelectionModel::Toggle
- | QItemSelectionModel::Current;
-
- switch (flags & Mask) {
- case QItemSelectionModel::Clear:
- case QItemSelectionModel::ClearAndSelect:
- case QItemSelectionModel::SelectCurrent:
- return flags;
- case QItemSelectionModel::NoUpdate:
- if (event &&
- (event->type() == QEvent::MouseButtonPress
- || event->type() == QEvent::MouseButtonRelease))
- return flags;
- return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
- default:
- return QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
- }
-}
-
-void QAbstractItemViewPrivate::fetchMore()
-{
- fetchMoreTimer.stop();
- if (!model->canFetchMore(root))
- return;
- int last = model->rowCount(root) - 1;
- if (last < 0) {
- model->fetchMore(root);
- return;
- }
-
- QModelIndex index = model->index(last, 0, root);
- QRect rect = q_func()->visualRect(index);
- if (viewport->rect().intersects(rect))
- model->fetchMore(root);
-}
-
-bool QAbstractItemViewPrivate::shouldEdit(QAbstractItemView::EditTrigger trigger,
- const QModelIndex &index) const
-{
- if (!index.isValid())
- return false;
- Qt::ItemFlags flags = model->flags(index);
- if (((flags & Qt::ItemIsEditable) == 0) || ((flags & Qt::ItemIsEnabled) == 0))
- return false;
- if (state == QAbstractItemView::EditingState)
- return false;
- if (hasEditor(index))
- return false;
- if (trigger == QAbstractItemView::AllEditTriggers) // force editing
- return true;
- if ((trigger & editTriggers) == QAbstractItemView::SelectedClicked
- && !selectionModel->isSelected(index))
- return false;
- return (trigger & editTriggers);
-}
-
-bool QAbstractItemViewPrivate::shouldForwardEvent(QAbstractItemView::EditTrigger trigger,
- const QEvent *event) const
-{
- if (!event || (trigger & editTriggers) != QAbstractItemView::AnyKeyPressed)
- return false;
-
- switch (event->type()) {
- case QEvent::KeyPress:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseMove:
- return true;
- default:
- break;
- };
-
- return false;
-}
-
-bool QAbstractItemViewPrivate::shouldAutoScroll(const QPoint &pos) const
-{
- if (!autoScroll)
- return false;
- QRect area = static_cast<QAbstractItemView*>(viewport)->d_func()->clipRect(); // access QWidget private by bending C++ rules
- return (pos.y() - area.top() < autoScrollMargin)
- || (area.bottom() - pos.y() < autoScrollMargin)
- || (pos.x() - area.left() < autoScrollMargin)
- || (area.right() - pos.x() < autoScrollMargin);
-}
-
-void QAbstractItemViewPrivate::doDelayedItemsLayout(int delay)
-{
- if (!delayedPendingLayout) {
- delayedPendingLayout = true;
- delayedLayout.start(delay, q_func());
- }
-}
-
-void QAbstractItemViewPrivate::interruptDelayedItemsLayout() const
-{
- delayedLayout.stop();
- delayedPendingLayout = false;
-}
-
-
-
-QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
- const QStyleOptionViewItem &options)
-{
- Q_Q(QAbstractItemView);
- QWidget *w = editorForIndex(index).widget.data();
- if (!w) {
- QAbstractItemDelegate *delegate = delegateForIndex(index);
- if (!delegate)
- return 0;
- w = delegate->createEditor(viewport, options, index);
- if (w) {
- w->installEventFilter(delegate);
- QObject::connect(w, SIGNAL(destroyed(QObject*)), q, SLOT(editorDestroyed(QObject*)));
- delegate->updateEditorGeometry(w, options, index);
- delegate->setEditorData(w, index);
- addEditor(index, w, false);
- if (w->parent() == viewport)
- QWidget::setTabOrder(q, w);
-
- // Special cases for some editors containing QLineEdit
- QWidget *focusWidget = w;
- while (QWidget *fp = focusWidget->focusProxy())
- focusWidget = fp;
-#ifndef QT_NO_LINEEDIT
- if (QLineEdit *le = qobject_cast<QLineEdit*>(focusWidget))
- le->selectAll();
-#endif
-#ifndef QT_NO_SPINBOX
- if (QSpinBox *sb = qobject_cast<QSpinBox*>(focusWidget))
- sb->selectAll();
- else if (QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox*>(focusWidget))
- dsb->selectAll();
-#endif
- }
- }
-
- return w;
-}
-
-void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QModelIndex &br)
-{
- // we are counting on having relatively few editors
- const bool checkIndexes = tl.isValid() && br.isValid();
- const QModelIndex parent = tl.parent();
- QIndexEditorHash::const_iterator it = indexEditorHash.constBegin();
- for (; it != indexEditorHash.constEnd(); ++it) {
- QWidget *editor = it.value().widget.data();
- const QModelIndex index = it.key();
- if (it.value().isStatic || !editor || !index.isValid() ||
- (checkIndexes
- && (index.row() < tl.row() || index.row() > br.row()
- || index.column() < tl.column() || index.column() > br.column()
- || index.parent() != parent)))
- continue;
-
- QAbstractItemDelegate *delegate = delegateForIndex(index);
- if (delegate) {
- delegate->setEditorData(editor, index);
- }
- }
-}
-
-/*!
- \internal
-
- In DND if something has been moved then this is called.
- Typically this means you should "remove" the selected item or row,
- but the behavior is view dependant (table just clears the selected indexes for example).
-
- Either remove the selected rows or clear them
-*/
-void QAbstractItemViewPrivate::clearOrRemove()
-{
-#ifndef QT_NO_DRAGANDDROP
- const QItemSelection selection = selectionModel->selection();
- QList<QItemSelectionRange>::const_iterator it = selection.constBegin();
-
- if (!overwrite) {
- for (; it != selection.constEnd(); ++it) {
- QModelIndex parent = (*it).parent();
- if ((*it).left() != 0)
- continue;
- if ((*it).right() != (model->columnCount(parent) - 1))
- continue;
- int count = (*it).bottom() - (*it).top() + 1;
- model->removeRows((*it).top(), count, parent);
- }
- } else {
- // we can't remove the rows so reset the items (i.e. the view is like a table)
- QModelIndexList list = selection.indexes();
- for (int i=0; i < list.size(); ++i) {
- QModelIndex index = list.at(i);
- QMap<int, QVariant> roles = model->itemData(index);
- for (QMap<int, QVariant>::Iterator it = roles.begin(); it != roles.end(); ++it)
- it.value() = QVariant();
- model->setItemData(index, roles);
- }
- }
-#endif
-}
-
-/*!
- \internal
-
- When persistent aeditor gets/loses focus, we need to check
- and setcorrectly the current index.
-*/
-void QAbstractItemViewPrivate::checkPersistentEditorFocus()
-{
- Q_Q(QAbstractItemView);
- if (QWidget *widget = QApplication::focusWidget()) {
- if (persistent.contains(widget)) {
- //a persistent editor has gained the focus
- QModelIndex index = indexForEditor(widget);
- if (selectionModel->currentIndex() != index)
- q->setCurrentIndex(index);
- }
- }
-}
-
-
-const QEditorInfo & QAbstractItemViewPrivate::editorForIndex(const QModelIndex &index) const
-{
- static QEditorInfo nullInfo;
-
- QIndexEditorHash::const_iterator it = indexEditorHash.find(index);
- if (it == indexEditorHash.end())
- return nullInfo;
-
- return it.value();
-}
-
-QModelIndex QAbstractItemViewPrivate::indexForEditor(QWidget *editor) const
-{
- QEditorIndexHash::const_iterator it = editorIndexHash.find(editor);
- if (it == editorIndexHash.end())
- return QModelIndex();
-
- return it.value();
-}
-
-void QAbstractItemViewPrivate::removeEditor(QWidget *editor)
-{
- QEditorIndexHash::iterator it = editorIndexHash.find(editor);
- if (it != editorIndexHash.end())
- {
- indexEditorHash.remove(it.value());
- editorIndexHash.erase(it);
- }
-}
-
-void QAbstractItemViewPrivate::addEditor(const QModelIndex &index, QWidget *editor, bool isStatic)
-{
- editorIndexHash.insert(editor, index);
- indexEditorHash.insert(index, QEditorInfo(editor, isStatic));
-}
-
-bool QAbstractItemViewPrivate::sendDelegateEvent(const QModelIndex &index, QEvent *event) const
-{
- Q_Q(const QAbstractItemView);
- QModelIndex buddy = model->buddy(index);
- QStyleOptionViewItemV4 options = viewOptionsV4();
- options.rect = q->visualRect(buddy);
- options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
- QAbstractItemDelegate *delegate = delegateForIndex(index);
- return (event && delegate && delegate->editorEvent(event, model, options, buddy));
-}
-
-bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *event)
-{
- Q_Q(QAbstractItemView);
-
- QModelIndex buddy = model->buddy(index);
- QStyleOptionViewItemV4 options = viewOptionsV4();
- options.rect = q->visualRect(buddy);
- options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
-
- QWidget *w = editor(buddy, options);
- if (!w)
- return false;
-
- q->setState(QAbstractItemView::EditingState);
- w->show();
- w->setFocus();
-
- if (event)
- QApplication::sendEvent(w->focusProxy() ? w->focusProxy() : w, event);
-
- return true;
-}
-
-/*
- \internal
-
- returns the pair QRect/QModelIndex that should be painted on the viewports's rect
-*/
-
-QItemViewPaintPairs QAbstractItemViewPrivate::draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const
-{
- Q_ASSERT(r);
- Q_Q(const QAbstractItemView);
- QRect &rect = *r;
- const QRect viewportRect = viewport->rect();
- QItemViewPaintPairs ret;
- for (int i = 0; i < indexes.count(); ++i) {
- const QModelIndex &index = indexes.at(i);
- const QRect current = q->visualRect(index);
- if (current.intersects(viewportRect)) {
- ret += qMakePair(current, index);
- rect |= current;
- }
- }
- rect &= viewportRect;
- return ret;
-}
-
-QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes, QRect *r) const
-{
- Q_ASSERT(r);
- QItemViewPaintPairs paintPairs = draggablePaintPairs(indexes, r);
- if (paintPairs.isEmpty())
- return QPixmap();
- QPixmap pixmap(r->size());
- pixmap.fill(Qt::transparent);
- QPainter painter(&pixmap);
- QStyleOptionViewItemV4 option = viewOptionsV4();
- option.state |= QStyle::State_Selected;
- for (int j = 0; j < paintPairs.count(); ++j) {
- option.rect = paintPairs.at(j).first.translated(-r->topLeft());
- const QModelIndex &current = paintPairs.at(j).second;
- delegateForIndex(current)->paint(&painter, option, current);
- }
- return pixmap;
-}
-
-void QAbstractItemViewPrivate::selectAll(QItemSelectionModel::SelectionFlags command)
-{
- if (!selectionModel)
- return;
-
- QItemSelection selection;
- QModelIndex tl = model->index(0, 0, root);
- QModelIndex br = model->index(model->rowCount(root) - 1,
- model->columnCount(root) - 1,
- root);
- selection.append(QItemSelectionRange(tl, br));
- selectionModel->select(selection, command);
-}
-
-QModelIndexList QAbstractItemViewPrivate::selectedDraggableIndexes() const
-{
- Q_Q(const QAbstractItemView);
- QModelIndexList indexes = q->selectedIndexes();
- for(int i = indexes.count() - 1 ; i >= 0; --i) {
- if (!isIndexDragEnabled(indexes.at(i)))
- indexes.removeAt(i);
- }
- return indexes;
-}
-
-
-QT_END_NAMESPACE
-
-#include "moc_qabstractitemview.cpp"
-
-#endif // QT_NO_ITEMVIEWS
diff --git a/src/gui/itemviews/qabstractitemview.h b/src/gui/itemviews/qabstractitemview.h
deleted file mode 100644
index f11f209010..0000000000
--- a/src/gui/itemviews/qabstractitemview.h
+++ /dev/null
@@ -1,380 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTITEMVIEW_H
-#define QABSTRACTITEMVIEW_H
-
-#include <QtGui/qabstractscrollarea.h>
-#include <QtCore/qabstractitemmodel.h>
-#include <QtGui/qitemselectionmodel.h>
-#include <QtGui/qabstractitemdelegate.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class QMenu;
-class QDrag;
-class QEvent;
-class QAbstractItemViewPrivate;
-
-class Q_GUI_EXPORT QAbstractItemView : public QAbstractScrollArea
-{
- Q_OBJECT
- Q_ENUMS(SelectionMode SelectionBehavior ScrollHint ScrollMode DragDropMode)
- Q_FLAGS(EditTriggers)
- Q_PROPERTY(bool autoScroll READ hasAutoScroll WRITE setAutoScroll)
- Q_PROPERTY(int autoScrollMargin READ autoScrollMargin WRITE setAutoScrollMargin)
- Q_PROPERTY(EditTriggers editTriggers READ editTriggers WRITE setEditTriggers)
- Q_PROPERTY(bool tabKeyNavigation READ tabKeyNavigation WRITE setTabKeyNavigation)
-#ifndef QT_NO_DRAGANDDROP
- Q_PROPERTY(bool showDropIndicator READ showDropIndicator WRITE setDropIndicatorShown)
- Q_PROPERTY(bool dragEnabled READ dragEnabled WRITE setDragEnabled)
- Q_PROPERTY(bool dragDropOverwriteMode READ dragDropOverwriteMode WRITE setDragDropOverwriteMode)
- Q_PROPERTY(DragDropMode dragDropMode READ dragDropMode WRITE setDragDropMode)
- Q_PROPERTY(Qt::DropAction defaultDropAction READ defaultDropAction WRITE setDefaultDropAction)
-#endif
- Q_PROPERTY(bool alternatingRowColors READ alternatingRowColors WRITE setAlternatingRowColors)
- Q_PROPERTY(SelectionMode selectionMode READ selectionMode WRITE setSelectionMode)
- Q_PROPERTY(SelectionBehavior selectionBehavior READ selectionBehavior WRITE setSelectionBehavior)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
- Q_PROPERTY(Qt::TextElideMode textElideMode READ textElideMode WRITE setTextElideMode)
- Q_PROPERTY(ScrollMode verticalScrollMode READ verticalScrollMode WRITE setVerticalScrollMode)
- Q_PROPERTY(ScrollMode horizontalScrollMode READ horizontalScrollMode WRITE setHorizontalScrollMode)
-
-public:
- enum SelectionMode {
- NoSelection,
- SingleSelection,
- MultiSelection,
- ExtendedSelection,
- ContiguousSelection
- };
-
- enum SelectionBehavior {
- SelectItems,
- SelectRows,
- SelectColumns
- };
-
- enum ScrollHint {
- EnsureVisible,
- PositionAtTop,
- PositionAtBottom,
- PositionAtCenter
- };
-
- enum EditTrigger {
- NoEditTriggers = 0,
- CurrentChanged = 1,
- DoubleClicked = 2,
- SelectedClicked = 4,
- EditKeyPressed = 8,
- AnyKeyPressed = 16,
- AllEditTriggers = 31
- };
-
- Q_DECLARE_FLAGS(EditTriggers, EditTrigger)
-
- enum ScrollMode {
- ScrollPerItem,
- ScrollPerPixel
- };
-
- explicit QAbstractItemView(QWidget *parent = 0);
- ~QAbstractItemView();
-
- virtual void setModel(QAbstractItemModel *model);
- QAbstractItemModel *model() const;
-
- virtual void setSelectionModel(QItemSelectionModel *selectionModel);
- QItemSelectionModel *selectionModel() const;
-
- void setItemDelegate(QAbstractItemDelegate *delegate);
- QAbstractItemDelegate *itemDelegate() const;
-
- void setSelectionMode(QAbstractItemView::SelectionMode mode);
- QAbstractItemView::SelectionMode selectionMode() const;
-
- void setSelectionBehavior(QAbstractItemView::SelectionBehavior behavior);
- QAbstractItemView::SelectionBehavior selectionBehavior() const;
-
- QModelIndex currentIndex() const;
- QModelIndex rootIndex() const;
-
- void setEditTriggers(EditTriggers triggers);
- EditTriggers editTriggers() const;
-
- void setVerticalScrollMode(ScrollMode mode);
- ScrollMode verticalScrollMode() const;
-
- void setHorizontalScrollMode(ScrollMode mode);
- ScrollMode horizontalScrollMode() const;
-
- void setAutoScroll(bool enable);
- bool hasAutoScroll() const;
-
- void setAutoScrollMargin(int margin);
- int autoScrollMargin() const;
-
- void setTabKeyNavigation(bool enable);
- bool tabKeyNavigation() const;
-
-#ifndef QT_NO_DRAGANDDROP
- void setDropIndicatorShown(bool enable);
- bool showDropIndicator() const;
-
- void setDragEnabled(bool enable);
- bool dragEnabled() const;
-
- void setDragDropOverwriteMode(bool overwrite);
- bool dragDropOverwriteMode() const;
-
- enum DragDropMode {
- NoDragDrop,
- DragOnly,
- DropOnly,
- DragDrop,
- InternalMove
- };
-
- void setDragDropMode(DragDropMode behavior);
- DragDropMode dragDropMode() const;
-
- void setDefaultDropAction(Qt::DropAction dropAction);
- Qt::DropAction defaultDropAction() const;
-#endif
-
- void setAlternatingRowColors(bool enable);
- bool alternatingRowColors() const;
-
- void setIconSize(const QSize &size);
- QSize iconSize() const;
-
- void setTextElideMode(Qt::TextElideMode mode);
- Qt::TextElideMode textElideMode() const;
-
- virtual void keyboardSearch(const QString &search);
-
- virtual QRect visualRect(const QModelIndex &index) const = 0;
- virtual void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible) = 0;
- virtual QModelIndex indexAt(const QPoint &point) const = 0;
-
- QSize sizeHintForIndex(const QModelIndex &index) const;
- virtual int sizeHintForRow(int row) const;
- virtual int sizeHintForColumn(int column) const;
-
- void openPersistentEditor(const QModelIndex &index);
- void closePersistentEditor(const QModelIndex &index);
-
- void setIndexWidget(const QModelIndex &index, QWidget *widget);
- QWidget *indexWidget(const QModelIndex &index) const;
-
- void setItemDelegateForRow(int row, QAbstractItemDelegate *delegate);
- QAbstractItemDelegate *itemDelegateForRow(int row) const;
-
- void setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate);
- QAbstractItemDelegate *itemDelegateForColumn(int column) const;
-
- QAbstractItemDelegate *itemDelegate(const QModelIndex &index) const;
-
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
-
-#ifdef Q_NO_USING_KEYWORD
- inline void update() { QAbstractScrollArea::update(); }
-#else
- using QAbstractScrollArea::update;
-#endif
-
-public Q_SLOTS:
- virtual void reset();
- virtual void setRootIndex(const QModelIndex &index);
- virtual void doItemsLayout();
- virtual void selectAll();
- void edit(const QModelIndex &index);
- void clearSelection();
- void setCurrentIndex(const QModelIndex &index);
- void scrollToTop();
- void scrollToBottom();
- void update(const QModelIndex &index);
-
-protected Q_SLOTS:
- virtual void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- virtual void rowsInserted(const QModelIndex &parent, int start, int end);
- virtual void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
- virtual void currentChanged(const QModelIndex &current, const QModelIndex &previous);
- virtual void updateEditorData();
- virtual void updateEditorGeometries();
- virtual void updateGeometries();
- virtual void verticalScrollbarAction(int action);
- virtual void horizontalScrollbarAction(int action);
- virtual void verticalScrollbarValueChanged(int value);
- virtual void horizontalScrollbarValueChanged(int value);
- virtual void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint);
- virtual void commitData(QWidget *editor);
- virtual void editorDestroyed(QObject *editor);
-
-Q_SIGNALS:
- void pressed(const QModelIndex &index);
- void clicked(const QModelIndex &index);
- void doubleClicked(const QModelIndex &index);
-
- void activated(const QModelIndex &index);
- void entered(const QModelIndex &index);
- void viewportEntered();
-
-protected:
- QAbstractItemView(QAbstractItemViewPrivate &, QWidget *parent = 0);
-
- void setHorizontalStepsPerItem(int steps);
- int horizontalStepsPerItem() const;
- void setVerticalStepsPerItem(int steps);
- int verticalStepsPerItem() const;
-
- enum CursorAction { MoveUp, MoveDown, MoveLeft, MoveRight,
- MoveHome, MoveEnd, MovePageUp, MovePageDown,
- MoveNext, MovePrevious };
- virtual QModelIndex moveCursor(CursorAction cursorAction,
- Qt::KeyboardModifiers modifiers) = 0;
-
- virtual int horizontalOffset() const = 0;
- virtual int verticalOffset() const = 0;
-
- virtual bool isIndexHidden(const QModelIndex &index) const = 0;
-
- virtual void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) = 0;
- virtual QRegion visualRegionForSelection(const QItemSelection &selection) const = 0;
- virtual QModelIndexList selectedIndexes() const;
-
- virtual bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event);
-
- virtual QItemSelectionModel::SelectionFlags selectionCommand(const QModelIndex &index,
- const QEvent *event = 0) const;
-
-#ifndef QT_NO_DRAGANDDROP
- virtual void startDrag(Qt::DropActions supportedActions);
-#endif
-
- virtual QStyleOptionViewItem viewOptions() const;
-
- enum State {
- NoState,
- DraggingState,
- DragSelectingState,
- EditingState,
- ExpandingState,
- CollapsingState,
- AnimatingState
- };
-
- State state() const;
- void setState(State state);
-
- void scheduleDelayedItemsLayout();
- void executeDelayedItemsLayout();
-
- void setDirtyRegion(const QRegion &region);
- void scrollDirtyRegion(int dx, int dy);
- QPoint dirtyRegionOffset() const;
-
- void startAutoScroll();
- void stopAutoScroll();
- void doAutoScroll();
-
- bool focusNextPrevChild(bool next);
- bool event(QEvent *event);
- bool viewportEvent(QEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QDragEnterEvent *event);
- void dragMoveEvent(QDragMoveEvent *event);
- void dragLeaveEvent(QDragLeaveEvent *event);
- void dropEvent(QDropEvent *event);
-#endif
- void focusInEvent(QFocusEvent *event);
- void focusOutEvent(QFocusEvent *event);
- void keyPressEvent(QKeyEvent *event);
- void resizeEvent(QResizeEvent *event);
- void timerEvent(QTimerEvent *event);
- void inputMethodEvent(QInputMethodEvent *event);
-
-#ifndef QT_NO_DRAGANDDROP
- enum DropIndicatorPosition { OnItem, AboveItem, BelowItem, OnViewport };
- DropIndicatorPosition dropIndicatorPosition() const;
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QAbstractItemView)
- Q_DISABLE_COPY(QAbstractItemView)
- Q_PRIVATE_SLOT(d_func(), void _q_columnsAboutToBeRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_columnsRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_columnsInserted(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed())
- Q_PRIVATE_SLOT(d_func(), void _q_layoutChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_headerDataChanged())
-#ifndef QT_NO_GESTURES
- Q_PRIVATE_SLOT(d_func(), void _q_scrollerStateChanged())
-#endif
-
- friend class QTreeViewPrivate; // needed to compile with MSVC
- friend class QAccessibleItemRow;
- friend class QListModeViewBase;
- friend class QListViewPrivate; // needed to compile for Symbian emulator
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QAbstractItemView::EditTriggers)
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTITEMVIEW_H
diff --git a/src/gui/itemviews/qabstractitemview_p.h b/src/gui/itemviews/qabstractitemview_p.h
deleted file mode 100644
index 6041e5e177..0000000000
--- a/src/gui/itemviews/qabstractitemview_p.h
+++ /dev/null
@@ -1,457 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTITEMVIEW_P_H
-#define QABSTRACTITEMVIEW_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qabstractscrollarea_p.h"
-#include "private/qabstractitemmodel_p.h"
-#include "QtGui/qapplication.h"
-#include "QtGui/qevent.h"
-#include "QtGui/qmime.h"
-#include "QtGui/qpainter.h"
-#include "QtCore/qpair.h"
-#include "QtGui/qregion.h"
-#include "QtCore/qdebug.h"
-#include "QtGui/qpainter.h"
-#include "QtCore/qbasictimer.h"
-#include "QtCore/qelapsedtimer.h"
-
-#ifndef QT_NO_ITEMVIEWS
-
-QT_BEGIN_NAMESPACE
-
-struct QEditorInfo {
- QEditorInfo(QWidget *e, bool s): widget(QWeakPointer<QWidget>(e)), isStatic(s) {}
- QEditorInfo(): isStatic(false) {}
-
- QWeakPointer<QWidget> widget;
- bool isStatic;
-};
-
-// Fast associativity between Persistent editors and indices.
-typedef QHash<QWidget *, QPersistentModelIndex> QEditorIndexHash;
-typedef QHash<QPersistentModelIndex, QEditorInfo> QIndexEditorHash;
-
-typedef QPair<QRect, QModelIndex> QItemViewPaintPair;
-typedef QList<QItemViewPaintPair> QItemViewPaintPairs;
-
-class QEmptyModel : public QAbstractItemModel
-{
-public:
- explicit QEmptyModel(QObject *parent = 0) : QAbstractItemModel(parent) {}
- QModelIndex index(int, int, const QModelIndex &) const { return QModelIndex(); }
- QModelIndex parent(const QModelIndex &) const { return QModelIndex(); }
- int rowCount(const QModelIndex &) const { return 0; }
- int columnCount(const QModelIndex &) const { return 0; }
- bool hasChildren(const QModelIndex &) const { return false; }
- QVariant data(const QModelIndex &, int) const { return QVariant(); }
-};
-
-class Q_AUTOTEST_EXPORT QAbstractItemViewPrivate : public QAbstractScrollAreaPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractItemView)
-
-public:
- QAbstractItemViewPrivate();
- virtual ~QAbstractItemViewPrivate();
-
- void init();
-
- virtual void _q_rowsRemoved(const QModelIndex &parent, int start, int end);
- virtual void _q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- virtual void _q_columnsRemoved(const QModelIndex &parent, int start, int end);
- virtual void _q_columnsInserted(const QModelIndex &parent, int start, int end);
- virtual void _q_modelDestroyed();
- virtual void _q_layoutChanged();
- void _q_headerDataChanged() { doDelayedItemsLayout(); }
- void _q_scrollerStateChanged();
-
- void fetchMore();
-
- bool shouldEdit(QAbstractItemView::EditTrigger trigger, const QModelIndex &index) const;
- bool shouldForwardEvent(QAbstractItemView::EditTrigger trigger, const QEvent *event) const;
- bool shouldAutoScroll(const QPoint &pos) const;
- void doDelayedItemsLayout(int delay = 0);
- void interruptDelayedItemsLayout() const;
-
- void startAutoScroll()
- { // ### it would be nice to make this into a style hint one day
- int scrollInterval = (verticalScrollMode == QAbstractItemView::ScrollPerItem) ? 150 : 50;
- autoScrollTimer.start(scrollInterval, q_func());
- autoScrollCount = 0;
- }
- void stopAutoScroll() { autoScrollTimer.stop(); autoScrollCount = 0;}
-
-#ifndef QT_NO_DRAGANDDROP
- virtual bool dropOn(QDropEvent *event, int *row, int *col, QModelIndex *index);
-#endif
- bool droppingOnItself(QDropEvent *event, const QModelIndex &index);
-
- QWidget *editor(const QModelIndex &index, const QStyleOptionViewItem &options);
- bool sendDelegateEvent(const QModelIndex &index, QEvent *event) const;
- bool openEditor(const QModelIndex &index, QEvent *event);
- void updateEditorData(const QModelIndex &topLeft, const QModelIndex &bottomRight);
-
- QItemSelectionModel::SelectionFlags multiSelectionCommand(const QModelIndex &index,
- const QEvent *event) const;
- QItemSelectionModel::SelectionFlags extendedSelectionCommand(const QModelIndex &index,
- const QEvent *event) const;
- QItemSelectionModel::SelectionFlags contiguousSelectionCommand(const QModelIndex &index,
- const QEvent *event) const;
- virtual void selectAll(QItemSelectionModel::SelectionFlags command);
-
- void setHoverIndex(const QPersistentModelIndex &index);
-
- void checkMouseMove(const QPersistentModelIndex &index);
- inline void checkMouseMove(const QPoint &pos) { checkMouseMove(q_func()->indexAt(pos)); }
-
- inline QItemSelectionModel::SelectionFlags selectionBehaviorFlags() const
- {
- switch (selectionBehavior) {
- case QAbstractItemView::SelectRows: return QItemSelectionModel::Rows;
- case QAbstractItemView::SelectColumns: return QItemSelectionModel::Columns;
- case QAbstractItemView::SelectItems: default: return QItemSelectionModel::NoUpdate;
- }
- }
-
-#ifndef QT_NO_DRAGANDDROP
- virtual QAbstractItemView::DropIndicatorPosition position(const QPoint &pos, const QRect &rect, const QModelIndex &idx) const;
-
- inline bool canDecode(QDropEvent *e) const {
- QStringList modelTypes = model->mimeTypes();
- const QMimeData *mime = e->mimeData();
- for (int i = 0; i < modelTypes.count(); ++i)
- if (mime->hasFormat(modelTypes.at(i))
- && (e->dropAction() & model->supportedDropActions()))
- return true;
- return false;
- }
-
- inline void paintDropIndicator(QPainter *painter)
- {
- if (showDropIndicator && state == QAbstractItemView::DraggingState
-#ifndef QT_NO_CURSOR
- && viewport->cursor().shape() != Qt::ForbiddenCursor
-#endif
- ) {
- QStyleOption opt;
- opt.init(q_func());
- opt.rect = dropIndicatorRect;
- q_func()->style()->drawPrimitive(QStyle::PE_IndicatorItemViewItemDrop, &opt, painter, q_func());
- }
- }
-
-#endif
- virtual QItemViewPaintPairs draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const;
-
- inline void releaseEditor(QWidget *editor) const {
- if (editor) {
- QObject::disconnect(editor, SIGNAL(destroyed(QObject*)),
- q_func(), SLOT(editorDestroyed(QObject*)));
- editor->removeEventFilter(itemDelegate);
- editor->hide();
- editor->deleteLater();
- }
- }
-
- inline void executePostedLayout() const {
- if (delayedPendingLayout && state != QAbstractItemView::CollapsingState) {
- interruptDelayedItemsLayout();
- const_cast<QAbstractItemView*>(q_func())->doItemsLayout();
- }
- }
-
- inline void setDirtyRegion(const QRegion &visualRegion) {
- updateRegion += visualRegion;
- if (!updateTimer.isActive())
- updateTimer.start(0, q_func());
- }
-
- inline void scrollDirtyRegion(int dx, int dy) {
- scrollDelayOffset = QPoint(-dx, -dy);
- updateDirtyRegion();
- scrollDelayOffset = QPoint(0, 0);
- }
-
- inline void scrollContentsBy(int dx, int dy) {
- scrollDirtyRegion(dx, dy);
- viewport->scroll(dx, dy);
- }
-
- void updateDirtyRegion() {
- updateTimer.stop();
- viewport->update(updateRegion);
- updateRegion = QRegion();
- }
-
- void clearOrRemove();
- void checkPersistentEditorFocus();
-
- QPixmap renderToPixmap(const QModelIndexList &indexes, QRect *r) const;
-
- inline QPoint offset() const {
- const Q_Q(QAbstractItemView);
- return QPoint(q->isRightToLeft() ? -q->horizontalOffset()
- : q->horizontalOffset(), q->verticalOffset());
- }
-
- const QEditorInfo &editorForIndex(const QModelIndex &index) const;
- inline bool hasEditor(const QModelIndex &index) const {
- return indexEditorHash.find(index) != indexEditorHash.constEnd();
- }
-
- QModelIndex indexForEditor(QWidget *editor) const;
- void addEditor(const QModelIndex &index, QWidget *editor, bool isStatic);
- void removeEditor(QWidget *editor);
-
- inline bool isAnimating() const {
- return state == QAbstractItemView::AnimatingState;
- }
-
- inline QAbstractItemDelegate *delegateForIndex(const QModelIndex &index) const {
- QAbstractItemDelegate *del;
- if ((del = rowDelegates.value(index.row(), 0))) return del;
- if ((del = columnDelegates.value(index.column(), 0))) return del;
- return itemDelegate;
- }
-
- inline bool isIndexValid(const QModelIndex &index) const {
- return (index.row() >= 0) && (index.column() >= 0) && (index.model() == model);
- }
- inline bool isIndexSelectable(const QModelIndex &index) const {
- return (model->flags(index) & Qt::ItemIsSelectable);
- }
- inline bool isIndexEnabled(const QModelIndex &index) const {
- return (model->flags(index) & Qt::ItemIsEnabled);
- }
- inline bool isIndexDropEnabled(const QModelIndex &index) const {
- return (model->flags(index) & Qt::ItemIsDropEnabled);
- }
- inline bool isIndexDragEnabled(const QModelIndex &index) const {
- return (model->flags(index) & Qt::ItemIsDragEnabled);
- }
-
- virtual bool selectionAllowed(const QModelIndex &index) const {
- // in some views we want to go ahead with selections, even if the index is invalid
- return isIndexValid(index) && isIndexSelectable(index);
- }
-
- // reimplemented from QAbstractScrollAreaPrivate
- virtual QPoint contentsOffset() const {
- Q_Q(const QAbstractItemView);
- return QPoint(q->horizontalOffset(), q->verticalOffset());
- }
-
- /**
- * For now, assume that we have few editors, if we need a more efficient implementation
- * we should add a QMap<QAbstractItemDelegate*, int> member.
- */
- int delegateRefCount(const QAbstractItemDelegate *delegate) const
- {
- int ref = 0;
- if (itemDelegate == delegate)
- ++ref;
-
- for (int maps = 0; maps < 2; ++maps) {
- const QMap<int, QPointer<QAbstractItemDelegate> > *delegates = maps ? &columnDelegates : &rowDelegates;
- for (QMap<int, QPointer<QAbstractItemDelegate> >::const_iterator it = delegates->begin();
- it != delegates->end(); ++it) {
- if (it.value() == delegate) {
- ++ref;
- // optimization, we are only interested in the ref count values 0, 1 or >=2
- if (ref >= 2) {
- return ref;
- }
- }
- }
- }
- return ref;
- }
-
- /**
- * return true if the index is registered as a QPersistentModelIndex
- */
- inline bool isPersistent(const QModelIndex &index) const
- {
- return static_cast<QAbstractItemModelPrivate *>(model->d_ptr.data())->persistent.indexes.contains(index);
- }
-
- QModelIndexList selectedDraggableIndexes() const;
-
- QStyleOptionViewItemV4 viewOptionsV4() const;
-
- void doDelayedReset()
- {
- //we delay the reset of the timer because some views (QTableView)
- //with headers can't handle the fact that the model has been destroyed
- //all _q_modelDestroyed slots must have been called
- if (!delayedReset.isActive())
- delayedReset.start(0, q_func());
- }
-
- QAbstractItemModel *model;
- QPointer<QAbstractItemDelegate> itemDelegate;
- QMap<int, QPointer<QAbstractItemDelegate> > rowDelegates;
- QMap<int, QPointer<QAbstractItemDelegate> > columnDelegates;
- QPointer<QItemSelectionModel> selectionModel;
- QItemSelectionModel::SelectionFlag ctrlDragSelectionFlag;
- bool noSelectionOnMousePress;
-
- QAbstractItemView::SelectionMode selectionMode;
- QAbstractItemView::SelectionBehavior selectionBehavior;
-
- QEditorIndexHash editorIndexHash;
- QIndexEditorHash indexEditorHash;
- QSet<QWidget*> persistent;
- QWidget *currentlyCommittingEditor;
-
- QPersistentModelIndex enteredIndex;
- QPersistentModelIndex pressedIndex;
- Qt::KeyboardModifiers pressedModifiers;
- QPoint pressedPosition;
- bool pressedAlreadySelected;
-
- //forces the next mouseMoveEvent to send the viewportEntered signal
- //if the mouse is over the viewport and not over an item
- bool viewportEnteredNeeded;
-
- QAbstractItemView::State state;
- QAbstractItemView::State stateBeforeAnimation;
- QAbstractItemView::EditTriggers editTriggers;
- QAbstractItemView::EditTrigger lastTrigger;
-
- QPersistentModelIndex root;
- QPersistentModelIndex hover;
-
- bool tabKeyNavigation;
-
-#ifndef QT_NO_DRAGANDDROP
- bool showDropIndicator;
- QRect dropIndicatorRect;
- bool dragEnabled;
- QAbstractItemView::DragDropMode dragDropMode;
- bool overwrite;
- QAbstractItemView::DropIndicatorPosition dropIndicatorPosition;
- Qt::DropAction defaultDropAction;
-#endif
-
-#ifdef QT_SOFTKEYS_ENABLED
- QAction *doneSoftKey;
-#endif
-
- QString keyboardInput;
- QElapsedTimer keyboardInputTime;
-
- bool autoScroll;
- QBasicTimer autoScrollTimer;
- int autoScrollMargin;
- int autoScrollCount;
- bool shouldScrollToCurrentOnShow; //used to know if we should scroll to current on show event
- bool shouldClearStatusTip; //if there is a statustip currently shown that need to be cleared when leaving.
-
- bool alternatingColors;
-
- QSize iconSize;
- Qt::TextElideMode textElideMode;
-
- QRegion updateRegion; // used for the internal update system
- QPoint scrollDelayOffset;
-
- QBasicTimer updateTimer;
- QBasicTimer delayedEditing;
- QBasicTimer delayedAutoScroll; //used when an item is clicked
- QBasicTimer delayedReset;
-
- QAbstractItemView::ScrollMode verticalScrollMode;
- QAbstractItemView::ScrollMode horizontalScrollMode;
-
-#ifndef QT_NO_GESTURES
- // the selection before the last mouse down. In case we have to restore it for scrolling
- QItemSelection oldSelection;
- QModelIndex oldCurrent;
-#endif
-
- bool currentIndexSet;
-
- bool wrapItemText;
- mutable bool delayedPendingLayout;
- bool moveCursorUpdatedView;
-
-private:
- mutable QBasicTimer delayedLayout;
- mutable QBasicTimer fetchMoreTimer;
-};
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qvector.h>
-QT_END_INCLUDE_NAMESPACE
-
-template <typename T>
-inline int qBinarySearch(const QVector<T> &vec, const T &item, int start, int end)
-{
- int i = (start + end + 1) >> 1;
- while (end - start > 0) {
- if (vec.at(i) > item)
- end = i - 1;
- else
- start = i;
- i = (start + end + 1) >> 1;
- }
- return i;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ITEMVIEWS
-
-#endif // QABSTRACTITEMVIEW_P_H
diff --git a/src/gui/itemviews/qabstractproxymodel.cpp b/src/gui/itemviews/qabstractproxymodel.cpp
deleted file mode 100644
index 34ca7dff50..0000000000
--- a/src/gui/itemviews/qabstractproxymodel.cpp
+++ /dev/null
@@ -1,409 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractproxymodel.h"
-
-#ifndef QT_NO_PROXYMODEL
-
-#include "qitemselectionmodel.h"
-#include <private/qabstractproxymodel_p.h>
-#include <QtCore/QSize>
-#include <QtCore/QStringList>
-
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \since 4.1
- \class QAbstractProxyModel
- \brief The QAbstractProxyModel class provides a base class for proxy item
- models that can do sorting, filtering or other data processing tasks.
- \ingroup model-view
-
- This class defines the standard interface that proxy models must use to be
- able to interoperate correctly with other model/view components. It is not
- supposed to be instantiated directly.
-
- All standard proxy models are derived from the QAbstractProxyModel class.
- If you need to create a new proxy model class, it is usually better to
- subclass an existing class that provides the closest behavior to the one
- you want to provide.
-
- Proxy models that filter or sort items of data from a source model should
- be created by using or subclassing QSortFilterProxyModel.
-
- To subclass QAbstractProxyModel, you need to implement mapFromSource() and
- mapToSource(). The mapSelectionFromSource() and mapSelectionToSource()
- functions only need to be reimplemented if you need a behavior different
- from the default behavior.
-
- \note If the source model is deleted or no source model is specified, the
- proxy model operates on a empty placeholder model.
-
- \sa QSortFilterProxyModel, QAbstractItemModel, {Model/View Programming}
-*/
-
-//detects the deletion of the source model
-void QAbstractProxyModelPrivate::_q_sourceModelDestroyed()
-{
- model = QAbstractItemModelPrivate::staticEmptyModel();
-}
-
-/*!
- Constructs a proxy model with the given \a parent.
-*/
-
-QAbstractProxyModel::QAbstractProxyModel(QObject *parent)
- :QAbstractItemModel(*new QAbstractProxyModelPrivate, parent)
-{
- setSourceModel(QAbstractItemModelPrivate::staticEmptyModel());
-}
-
-/*!
- \internal
-*/
-
-QAbstractProxyModel::QAbstractProxyModel(QAbstractProxyModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- setSourceModel(QAbstractItemModelPrivate::staticEmptyModel());
-}
-
-/*!
- Destroys the proxy model.
-*/
-QAbstractProxyModel::~QAbstractProxyModel()
-{
-
-}
-
-/*!
- Sets the given \a sourceModel to be processed by the proxy model.
-*/
-void QAbstractProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
-{
- Q_D(QAbstractProxyModel);
- if (d->model) {
- disconnect(d->model, SIGNAL(destroyed()), this, SLOT(_q_sourceModelDestroyed()));
- disconnect(d->model, SIGNAL(modelReset()), this, SLOT(resetInternalData()));
- }
-
- if (sourceModel) {
- d->model = sourceModel;
- connect(d->model, SIGNAL(destroyed()), this, SLOT(_q_sourceModelDestroyed()));
- connect(d->model, SIGNAL(modelReset()), this, SLOT(resetInternalData()));
- } else {
- d->model = QAbstractItemModelPrivate::staticEmptyModel();
- }
- d->roleNames = d->model->roleNames();
-}
-
-/*!
- Returns the model that contains the data that is available through the proxy model.
-*/
-QAbstractItemModel *QAbstractProxyModel::sourceModel() const
-{
- Q_D(const QAbstractProxyModel);
- if (d->model == QAbstractItemModelPrivate::staticEmptyModel())
- return 0;
- return d->model;
-}
-
-/*!
- \reimp
- */
-bool QAbstractProxyModel::submit()
-{
- Q_D(QAbstractProxyModel);
- return d->model->submit();
-}
-
-/*!
- \reimp
- */
-void QAbstractProxyModel::revert()
-{
- Q_D(QAbstractProxyModel);
- d->model->revert();
-}
-
-
-/*!
- \fn QModelIndex QAbstractProxyModel::mapToSource(const QModelIndex &proxyIndex) const
-
- Reimplement this function to return the model index in the source model that
- corresponds to the \a proxyIndex in the proxy model.
-
- \sa mapFromSource()
-*/
-
-/*!
- \fn QModelIndex QAbstractProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
-
- Reimplement this function to return the model index in the proxy model that
- corresponds to the \a sourceIndex from the source model.
-
- \sa mapToSource()
-*/
-
-/*!
- Returns a source selection mapped from the specified \a proxySelection.
-
- Reimplement this method to map proxy selections to source selections.
- */
-QItemSelection QAbstractProxyModel::mapSelectionToSource(const QItemSelection &proxySelection) const
-{
- QModelIndexList proxyIndexes = proxySelection.indexes();
- QItemSelection sourceSelection;
- for (int i = 0; i < proxyIndexes.size(); ++i) {
- const QModelIndex proxyIdx = mapToSource(proxyIndexes.at(i));
- if (!proxyIdx.isValid())
- continue;
- sourceSelection << QItemSelectionRange(proxyIdx);
- }
- return sourceSelection;
-}
-
-/*!
- Returns a proxy selection mapped from the specified \a sourceSelection.
-
- Reimplement this method to map source selections to proxy selections.
-*/
-QItemSelection QAbstractProxyModel::mapSelectionFromSource(const QItemSelection &sourceSelection) const
-{
- QModelIndexList sourceIndexes = sourceSelection.indexes();
- QItemSelection proxySelection;
- for (int i = 0; i < sourceIndexes.size(); ++i) {
- const QModelIndex srcIdx = mapFromSource(sourceIndexes.at(i));
- if (!srcIdx.isValid())
- continue;
- proxySelection << QItemSelectionRange(srcIdx);
- }
- return proxySelection;
-}
-
-/*!
- \reimp
- */
-QVariant QAbstractProxyModel::data(const QModelIndex &proxyIndex, int role) const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->data(mapToSource(proxyIndex), role);
-}
-
-/*!
- \reimp
- */
-QVariant QAbstractProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- Q_D(const QAbstractProxyModel);
- int sourceSection;
- if (orientation == Qt::Horizontal) {
- const QModelIndex proxyIndex = index(0, section);
- sourceSection = mapToSource(proxyIndex).column();
- } else {
- const QModelIndex proxyIndex = index(section, 0);
- sourceSection = mapToSource(proxyIndex).row();
- }
- return d->model->headerData(sourceSection, orientation, role);
-}
-
-/*!
- \reimp
- */
-QMap<int, QVariant> QAbstractProxyModel::itemData(const QModelIndex &proxyIndex) const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->itemData(mapToSource(proxyIndex));
-}
-
-/*!
- \reimp
- */
-Qt::ItemFlags QAbstractProxyModel::flags(const QModelIndex &index) const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->flags(mapToSource(index));
-}
-
-/*!
- \reimp
- */
-bool QAbstractProxyModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- Q_D(QAbstractProxyModel);
- return d->model->setData(mapToSource(index), value, role);
-}
-
-/*!
- \reimp
- */
-bool QAbstractProxyModel::setItemData(const QModelIndex &index, const QMap< int, QVariant >& roles)
-{
- Q_D(QAbstractProxyModel);
- return d->model->setItemData(mapToSource(index), roles);
-}
-
-/*!
- \reimp
- */
-bool QAbstractProxyModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
-{
- Q_D(QAbstractProxyModel);
- int sourceSection;
- if (orientation == Qt::Horizontal) {
- const QModelIndex proxyIndex = index(0, section);
- sourceSection = mapToSource(proxyIndex).column();
- } else {
- const QModelIndex proxyIndex = index(section, 0);
- sourceSection = mapToSource(proxyIndex).row();
- }
- return d->model->setHeaderData(sourceSection, orientation, value, role);
-}
-
-/*!
- \reimp
- */
-QModelIndex QAbstractProxyModel::buddy(const QModelIndex &index) const
-{
- Q_D(const QAbstractProxyModel);
- return mapFromSource(d->model->buddy(mapToSource(index)));
-}
-
-/*!
- \reimp
- */
-bool QAbstractProxyModel::canFetchMore(const QModelIndex &parent) const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->canFetchMore(mapToSource(parent));
-}
-
-/*!
- \reimp
- */
-void QAbstractProxyModel::fetchMore(const QModelIndex &parent)
-{
- Q_D(QAbstractProxyModel);
- d->model->fetchMore(mapToSource(parent));
-}
-
-/*!
- \reimp
- */
-void QAbstractProxyModel::sort(int column, Qt::SortOrder order)
-{
- Q_D(QAbstractProxyModel);
- d->model->sort(column, order);
-}
-
-/*!
- \reimp
- */
-QSize QAbstractProxyModel::span(const QModelIndex &index) const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->span(mapToSource(index));
-}
-
-/*!
- \reimp
- */
-bool QAbstractProxyModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->hasChildren(mapToSource(parent));
-}
-
-/*!
- \reimp
- */
-QMimeData* QAbstractProxyModel::mimeData(const QModelIndexList &indexes) const
-{
- Q_D(const QAbstractProxyModel);
- QModelIndexList list;
- foreach(const QModelIndex &index, indexes)
- list << mapToSource(index);
- return d->model->mimeData(list);
-}
-
-/*!
- \reimp
- */
-QStringList QAbstractProxyModel::mimeTypes() const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->mimeTypes();
-}
-
-/*!
- \reimp
- */
-Qt::DropActions QAbstractProxyModel::supportedDropActions() const
-{
- Q_D(const QAbstractProxyModel);
- return d->model->supportedDropActions();
-}
-
-/*
- \since 4.8
-
- This slot is called just after the internal data of a model is cleared
- while it is being reset.
-
- This slot is provided the convenience of subclasses of concrete proxy
- models, such as subclasses of QSortFilterProxyModel which maintain extra
- data.
-
- \snippet doc/src/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp 10
-
- \sa modelAboutToBeReset(), modelReset()
-*/
-void QAbstractProxyModel::resetInternalData()
-{
-
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qabstractproxymodel.cpp"
-
-#endif // QT_NO_PROXYMODEL
diff --git a/src/gui/itemviews/qabstractproxymodel.h b/src/gui/itemviews/qabstractproxymodel.h
deleted file mode 100644
index 6e485aec12..0000000000
--- a/src/gui/itemviews/qabstractproxymodel.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTPROXYMODEL_H
-#define QABSTRACTPROXYMODEL_H
-
-#include <QtCore/qabstractitemmodel.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PROXYMODEL
-
-class QAbstractProxyModelPrivate;
-class QItemSelection;
-
-class Q_GUI_EXPORT QAbstractProxyModel : public QAbstractItemModel
-{
- Q_OBJECT
-
-public:
- QAbstractProxyModel(QObject *parent = 0);
- ~QAbstractProxyModel();
-
- virtual void setSourceModel(QAbstractItemModel *sourceModel);
- QAbstractItemModel *sourceModel() const;
-
- virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const = 0;
- virtual QModelIndex mapFromSource(const QModelIndex &sourceIndex) const = 0;
-
- virtual QItemSelection mapSelectionToSource(const QItemSelection &selection) const;
- virtual QItemSelection mapSelectionFromSource(const QItemSelection &selection) const;
-
- bool submit();
- void revert();
-
- QVariant data(const QModelIndex &proxyIndex, int role = Qt::DisplayRole) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- QMap<int, QVariant> itemData(const QModelIndex &index) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
- bool setItemData(const QModelIndex& index, const QMap<int, QVariant> &roles);
- bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole);
-
- QModelIndex buddy(const QModelIndex &index) const;
- bool canFetchMore(const QModelIndex &parent) const;
- void fetchMore(const QModelIndex &parent);
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
- QSize span(const QModelIndex &index) const;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
-
- QMimeData* mimeData(const QModelIndexList &indexes) const;
- QStringList mimeTypes() const;
- Qt::DropActions supportedDropActions() const;
-
-protected Q_SLOTS:
- void resetInternalData();
-
-protected:
- QAbstractProxyModel(QAbstractProxyModelPrivate &, QObject *parent);
-
-private:
- Q_DECLARE_PRIVATE(QAbstractProxyModel)
- Q_DISABLE_COPY(QAbstractProxyModel)
- Q_PRIVATE_SLOT(d_func(), void _q_sourceModelDestroyed())
-};
-
-#endif // QT_NO_PROXYMODEL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTPROXYMODEL_H
diff --git a/src/gui/itemviews/qabstractproxymodel_p.h b/src/gui/itemviews/qabstractproxymodel_p.h
deleted file mode 100644
index 3e6e35a29f..0000000000
--- a/src/gui/itemviews/qabstractproxymodel_p.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTPROXYMODEL_P_H
-#define QABSTRACTPROXYMODEL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of QAbstractItemModel*. This header file may change from version
-// to version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include "private/qabstractitemmodel_p.h"
-
-#ifndef QT_NO_PROXYMODEL
-
-QT_BEGIN_NAMESPACE
-
-class QAbstractProxyModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractProxyModel)
-public:
- QAbstractProxyModelPrivate() : QAbstractItemModelPrivate(), model(0) {}
- QAbstractItemModel *model;
- virtual void _q_sourceModelDestroyed();
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PROXYMODEL
-
-#endif // QABSTRACTPROXYMODEL_P_H
diff --git a/src/gui/itemviews/qbsptree.cpp b/src/gui/itemviews/qbsptree.cpp
deleted file mode 100644
index ffe3ae8a10..0000000000
--- a/src/gui/itemviews/qbsptree.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbsptree_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QBspTree::QBspTree() : depth(6), visited(0) {}
-
-void QBspTree::create(int n, int d)
-{
- // simple heuristics to find the best tree depth
- if (d == -1) {
- int c;
- for (c = 0; n; ++c)
- n = n / 10;
- depth = c << 1;
- } else {
- depth = d;
- }
- depth = qMax(depth, uint(1));
-
- nodes.resize((1 << depth) - 1); // resize to number of nodes
- leaves.resize(1 << depth); // resize to number of leaves
-}
-
-void QBspTree::destroy()
-{
- leaves.clear();
- nodes.clear();
-}
-
-void QBspTree::climbTree(const QRect &rect, callback *function, QBspTreeData data)
-{
- if (nodes.isEmpty())
- return;
- ++visited;
- climbTree(rect, function, data, 0);
-}
-
-void QBspTree::climbTree(const QRect &area, callback *function, QBspTreeData data, int index)
-{
- if (index >= nodes.count()) { // the index points to a leaf
- Q_ASSERT(!nodes.isEmpty());
- function(leaf(index - nodes.count()), area, visited, data);
- return;
- }
-
- Node::Type t = (Node::Type) nodes.at(index).type;
-
- int pos = nodes.at(index).pos;
- int idx = firstChildIndex(index);
- if (t == Node::VerticalPlane) {
- if (area.left() < pos)
- climbTree(area, function, data, idx); // back
- if (area.right() >= pos)
- climbTree(area, function, data, idx + 1); // front
- } else {
- if (area.top() < pos)
- climbTree(area, function, data, idx); // back
- if (area.bottom() >= pos)
- climbTree(area, function, data, idx + 1); // front
- }
-}
-
-void QBspTree::init(const QRect &area, int depth, NodeType type, int index)
-{
- Node::Type t = Node::None; // t should never have this value
- if (type == Node::Both) // if both planes are specified, use 2d bsp
- t = (depth & 1) ? Node::HorizontalPlane : Node::VerticalPlane;
- else
- t = type;
- QPoint center = area.center();
- nodes[index].pos = (t == Node::VerticalPlane ? center.x() : center.y());
- nodes[index].type = t;
-
- QRect front = area;
- QRect back = area;
-
- if (t == Node::VerticalPlane) {
- front.setLeft(center.x());
- back.setRight(center.x() - 1); // front includes the center
- } else { // t == Node::HorizontalPlane
- front.setTop(center.y());
- back.setBottom(center.y() - 1);
- }
-
- int idx = firstChildIndex(index);
- if (--depth) {
- init(back, depth, type, idx);
- init(front, depth, type, idx + 1);
- }
-}
-
-void QBspTree::insert(QVector<int> &leaf, const QRect &, uint, QBspTreeData data)
-{
- leaf.append(data.i);
-}
-
-void QBspTree::remove(QVector<int> &leaf, const QRect &, uint, QBspTreeData data)
-{
- int i = leaf.indexOf(data.i);
- if (i != -1)
- leaf.remove(i);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/itemviews/qbsptree_p.h b/src/gui/itemviews/qbsptree_p.h
deleted file mode 100644
index f5b559a6d9..0000000000
--- a/src/gui/itemviews/qbsptree_p.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** 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 QBSPTREE_P_H
-#define QBSPTREE_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 <qvector.h>
-#include <qrect.h>
-
-QT_BEGIN_NAMESPACE
-
-class QBspTree
-{
-public:
-
- struct Node
- {
- enum Type { None = 0, VerticalPlane = 1, HorizontalPlane = 2, Both = 3 };
- inline Node() : pos(0), type(None) {}
- int pos;
- Type type;
- };
- typedef Node::Type NodeType;
-
- struct Data
- {
- Data(void *p) : ptr(p) {}
- Data(int n) : i(n) {}
- union {
- void *ptr;
- int i;
- };
- };
- typedef QBspTree::Data QBspTreeData;
- typedef void callback(QVector<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
-
- QBspTree();
-
- void create(int n, int d = -1);
- void destroy();
-
- inline void init(const QRect &area, NodeType type) { init(area, depth, type, 0); }
-
- void climbTree(const QRect &rect, callback *function, QBspTreeData data);
-
- inline int leafCount() const { return leaves.count(); }
- inline QVector<int> &leaf(int i) { return leaves[i]; }
- inline void insertLeaf(const QRect &r, int i) { climbTree(r, &insert, i, 0); }
- inline void removeLeaf(const QRect &r, int i) { climbTree(r, &remove, i, 0); }
-
-protected:
- void init(const QRect &area, int depth, NodeType type, int index);
- void climbTree(const QRect &rect, callback *function, QBspTreeData data, int index);
-
- inline int parentIndex(int i) const { return (i & 1) ? ((i - 1) / 2) : ((i - 2) / 2); }
- inline int firstChildIndex(int i) const { return ((i * 2) + 1); }
-
- static void insert(QVector<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
- static void remove(QVector<int> &leaf, const QRect &area, uint visited, QBspTreeData data);
-
-private:
- uint depth;
- mutable uint visited;
- QVector<Node> nodes;
- mutable QVector< QVector<int> > leaves; // the leaves are just indices into the items
-};
-
-QT_END_NAMESPACE
-
-#endif // QBSPTREE_P_H
diff --git a/src/gui/itemviews/qcolumnview.cpp b/src/gui/itemviews/qcolumnview.cpp
deleted file mode 100644
index a44ecc7779..0000000000
--- a/src/gui/itemviews/qcolumnview.cpp
+++ /dev/null
@@ -1,1168 +0,0 @@
-/****************************************************************************
-**
-** 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>
-
-#ifndef QT_NO_COLUMNVIEW
-
-#include "qcolumnview.h"
-#include "qcolumnview_p.h"
-#include "qcolumnviewgrip_p.h"
-
-#include <qlistview.h>
-#include <qabstractitemdelegate.h>
-#include <qscrollbar.h>
-#include <qpainter.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-#define ANIMATION_DURATION_MSEC 150
-
-/*!
- \since 4.3
- \class QColumnView
- \brief The QColumnView class provides a model/view implementation of a column view.
- \ingroup model-view
- \ingroup advanced
-
-
- QColumnView displays a model in a number of QListViews, one for each
- hierarchy in the tree. This is sometimes referred to as a cascading list.
-
- The QColumnView class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- QColumnView implements the interfaces defined by the
- QAbstractItemView class to allow it to display data provided by
- models derived from the QAbstractItemModel class.
-
- \image qcolumnview.png
-
- \sa \link model-view-programming.html Model/View Programming\endlink
-*/
-
-/*!
- Constructs a column view with a \a parent to represent a model's
- data. Use setModel() to set the model.
-
- \sa QAbstractItemModel
-*/
-QColumnView::QColumnView(QWidget * parent)
-: QAbstractItemView(*new QColumnViewPrivate, parent)
-{
- Q_D(QColumnView);
- d->initialize();
-}
-
-/*!
- \internal
-*/
-QColumnView::QColumnView(QColumnViewPrivate & dd, QWidget * parent)
-: QAbstractItemView(dd, parent)
-{
- Q_D(QColumnView);
- d->initialize();
-}
-
-void QColumnViewPrivate::initialize()
-{
- Q_Q(QColumnView);
- q->setTextElideMode(Qt::ElideMiddle);
-#ifndef QT_NO_ANIMATION
- QObject::connect(&currentAnimation, SIGNAL(finished()), q, SLOT(_q_changeCurrentColumn()));
- currentAnimation.setDuration(ANIMATION_DURATION_MSEC);
- currentAnimation.setTargetObject(hbar);
- currentAnimation.setPropertyName("value");
- currentAnimation.setEasingCurve(QEasingCurve::InOutQuad);
-#endif //QT_NO_ANIMATION
- delete itemDelegate;
- q->setItemDelegate(new QColumnViewDelegate(q));
-}
-
-/*!
- Destroys the column view.
-*/
-QColumnView::~QColumnView()
-{
-}
-
-/*!
- \property QColumnView::resizeGripsVisible
- \brief the way to specify if the list views gets resize grips or not
-
- By default, \c visible is set to true
-
- \sa setRootIndex()
-*/
-void QColumnView::setResizeGripsVisible(bool visible)
-{
- Q_D(QColumnView);
- if (d->showResizeGrips == visible)
- return;
- d->showResizeGrips = visible;
- for (int i = 0; i < d->columns.count(); ++i) {
- QAbstractItemView *view = d->columns[i];
- if (visible) {
- QColumnViewGrip *grip = new QColumnViewGrip(view);
- view->setCornerWidget(grip);
- connect(grip, SIGNAL(gripMoved(int)), this, SLOT(_q_gripMoved(int)));
- } else {
- QWidget *widget = view->cornerWidget();
- view->setCornerWidget(0);
- widget->deleteLater();
- }
- }
-}
-
-bool QColumnView::resizeGripsVisible() const
-{
- Q_D(const QColumnView);
- return d->showResizeGrips;
-}
-
-/*!
- \reimp
-*/
-void QColumnView::setModel(QAbstractItemModel *model)
-{
- Q_D(QColumnView);
- if (model == d->model)
- return;
- d->closeColumns();
- QAbstractItemView::setModel(model);
-}
-
-/*!
- \reimp
-*/
-void QColumnView::setRootIndex(const QModelIndex &index)
-{
- Q_D(QColumnView);
- if (!model())
- return;
-
- d->closeColumns();
- Q_ASSERT(d->columns.count() == 0);
-
- QAbstractItemView *view = d->createColumn(index, true);
- if (view->selectionModel())
- view->selectionModel()->deleteLater();
- if (view->model())
- view->setSelectionModel(selectionModel());
-
- QAbstractItemView::setRootIndex(index);
- d->updateScrollbars();
-}
-
-/*!
- \reimp
-*/
-bool QColumnView::isIndexHidden(const QModelIndex &index) const
-{
- Q_UNUSED(index);
- return false;
-}
-
-/*!
- \reimp
-*/
-QModelIndex QColumnView::indexAt(const QPoint &point) const
-{
- Q_D(const QColumnView);
- for (int i = 0; i < d->columns.size(); ++i) {
- QPoint topLeft = d->columns.at(i)->frameGeometry().topLeft();
- QPoint adjustedPoint(point.x() - topLeft.x(), point.y() - topLeft.y());
- QModelIndex index = d->columns.at(i)->indexAt(adjustedPoint);
- if (index.isValid())
- return index;
- }
- return QModelIndex();
-}
-
-/*!
- \reimp
-*/
-QRect QColumnView::visualRect(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QRect();
-
- Q_D(const QColumnView);
- for (int i = 0; i < d->columns.size(); ++i) {
- QRect rect = d->columns.at(i)->visualRect(index);
- if (!rect.isNull()) {
- rect.translate(d->columns.at(i)->frameGeometry().topLeft());
- return rect;
- }
- }
- return QRect();
-}
-
-/*!
- \reimp
- */
-void QColumnView::scrollContentsBy(int dx, int dy)
-{
- Q_D(QColumnView);
- if (d->columns.isEmpty() || dx == 0)
- return;
-
- dx = isRightToLeft() ? -dx : dx;
- for (int i = 0; i < d->columns.count(); ++i)
- d->columns.at(i)->move(d->columns.at(i)->x() + dx, 0);
- d->offset += dx;
- QAbstractItemView::scrollContentsBy(dx, dy);
-}
-
-/*!
- \reimp
-*/
-void QColumnView::scrollTo(const QModelIndex &index, ScrollHint hint)
-{
- Q_D(QColumnView);
- Q_UNUSED(hint);
- if (!index.isValid() || d->columns.isEmpty())
- return;
-
-#ifndef QT_NO_ANIMATION
- if (d->currentAnimation.state() == QPropertyAnimation::Running)
- return;
-
- d->currentAnimation.stop();
-#endif //QT_NO_ANIMATION
-
- // Fill up what is needed to get to index
- d->closeColumns(index, true);
-
- QModelIndex indexParent = index.parent();
- // Find the left edge of the column that contains index
- int currentColumn = 0;
- int leftEdge = 0;
- while (currentColumn < d->columns.size()) {
- if (indexParent == d->columns.at(currentColumn)->rootIndex())
- break;
- leftEdge += d->columns.at(currentColumn)->width();
- ++currentColumn;
- }
-
- // Don't let us scroll above the root index
- if (currentColumn == d->columns.size())
- return;
-
- int indexColumn = currentColumn;
- // Find the width of what we want to show (i.e. the right edge)
- int visibleWidth = d->columns.at(currentColumn)->width();
- // We want to always try to show two columns
- if (currentColumn + 1 < d->columns.size()) {
- ++currentColumn;
- visibleWidth += d->columns.at(currentColumn)->width();
- }
-
- int rightEdge = leftEdge + visibleWidth;
- if (isRightToLeft()) {
- leftEdge = viewport()->width() - leftEdge;
- rightEdge = leftEdge - visibleWidth;
- qSwap(rightEdge, leftEdge);
- }
-
- // If it is already visible don't animate
- if (leftEdge > -horizontalOffset()
- && rightEdge <= ( -horizontalOffset() + viewport()->size().width())) {
- d->columns.at(indexColumn)->scrollTo(index);
- d->_q_changeCurrentColumn();
- return;
- }
-
- int newScrollbarValue = 0;
- if (isRightToLeft()) {
- if (leftEdge < 0) {
- // scroll to the right
- newScrollbarValue = viewport()->size().width() - leftEdge;
- } else {
- // scroll to the left
- newScrollbarValue = rightEdge + horizontalOffset();
- }
- } else {
- if (leftEdge > -horizontalOffset()) {
- // scroll to the right
- newScrollbarValue = rightEdge - viewport()->size().width();
- } else {
- // scroll to the left
- newScrollbarValue = leftEdge;
- }
- }
-
-#ifndef QT_NO_ANIMATION
- d->currentAnimation.setEndValue(newScrollbarValue);
- d->currentAnimation.start();
-#else
- horizontalScrollBar()->setValue(newScrollbarValue);
-#endif //QT_NO_ANIMATION
-}
-
-/*!
- \reimp
- Move left should go to the parent index
- Move right should go to the child index or down if there is no child
-*/
-QModelIndex QColumnView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
-{
- // the child views which have focus get to deal with this first and if
- // they don't accept it then it comes up this view and we only grip left/right
- Q_UNUSED(modifiers);
- if (!model())
- return QModelIndex();
-
- QModelIndex current = currentIndex();
- if (isRightToLeft()) {
- if (cursorAction == MoveLeft)
- cursorAction = MoveRight;
- else if (cursorAction == MoveRight)
- cursorAction = MoveLeft;
- }
- switch (cursorAction) {
- case MoveLeft:
- if (current.parent().isValid() && current.parent() != rootIndex())
- return (current.parent());
- else
- return current;
- break;
-
- case MoveRight:
- if (model()->hasChildren(current))
- return model()->index(0, 0, current);
- else
- return current.sibling(current.row() + 1, current.column());
- break;
-
- default:
- break;
- }
-
- return QModelIndex();
-}
-
-/*!
- \reimp
-*/
-void QColumnView::resizeEvent(QResizeEvent *event)
-{
- Q_D(QColumnView);
- d->doLayout();
- d->updateScrollbars();
- if (!isRightToLeft()) {
- int diff = event->oldSize().width() - event->size().width();
- if (diff < 0 && horizontalScrollBar()->isVisible()
- && horizontalScrollBar()->value() == horizontalScrollBar()->maximum()) {
- horizontalScrollBar()->setMaximum(horizontalScrollBar()->maximum() + diff);
- }
- }
- QAbstractItemView::resizeEvent(event);
-}
-
-/*!
- \internal
-*/
-void QColumnViewPrivate::updateScrollbars()
-{
- Q_Q(QColumnView);
-#ifndef QT_NO_ANIMATION
- if (currentAnimation.state() == QPropertyAnimation::Running)
- return;
-#endif //QT_NO_ANIMATION
-
- // find the total horizontal length of the laid out columns
- int horizontalLength = 0;
- if (!columns.isEmpty()) {
- horizontalLength = (columns.last()->x() + columns.last()->width()) - columns.first()->x();
- if (horizontalLength <= 0) // reverse mode
- horizontalLength = (columns.first()->x() + columns.first()->width()) - columns.last()->x();
- }
-
- QSize viewportSize = viewport->size();
- if (horizontalLength < viewportSize.width() && hbar->value() == 0) {
- hbar->setRange(0, 0);
- } else {
- int visibleLength = qMin(horizontalLength + q->horizontalOffset(), viewportSize.width());
- int hiddenLength = horizontalLength - visibleLength;
- if (hiddenLength != hbar->maximum())
- hbar->setRange(0, hiddenLength);
- }
- if (!columns.isEmpty()) {
- int pageStepSize = columns.at(0)->width();
- if (pageStepSize != hbar->pageStep())
- hbar->setPageStep(pageStepSize);
- }
- bool visible = (hbar->maximum() > 0);
- if (visible != hbar->isVisible())
- hbar->setVisible(visible);
-}
-
-/*!
- \reimp
-*/
-int QColumnView::horizontalOffset() const
-{
- Q_D(const QColumnView);
- return d->offset;
-}
-
-/*!
- \reimp
-*/
-int QColumnView::verticalOffset() const
-{
- return 0;
-}
-
-/*!
- \reimp
-*/
-QRegion QColumnView::visualRegionForSelection(const QItemSelection &selection) const
-{
- int ranges = selection.count();
-
- if (ranges == 0)
- return QRect();
-
- // Note that we use the top and bottom functions of the selection range
- // since the data is stored in rows.
- int firstRow = selection.at(0).top();
- int lastRow = selection.at(0).top();
- for (int i = 0; i < ranges; ++i) {
- firstRow = qMin(firstRow, selection.at(i).top());
- lastRow = qMax(lastRow, selection.at(i).bottom());
- }
-
- QModelIndex firstIdx = model()->index(qMin(firstRow, lastRow), 0, rootIndex());
- QModelIndex lastIdx = model()->index(qMax(firstRow, lastRow), 0, rootIndex());
-
- if (firstIdx == lastIdx)
- return visualRect(firstIdx);
-
- QRegion firstRegion = visualRect(firstIdx);
- QRegion lastRegion = visualRect(lastIdx);
- return firstRegion.unite(lastRegion);
-}
-
-/*!
- \reimp
-*/
-void QColumnView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
-{
- Q_UNUSED(rect);
- Q_UNUSED(command);
-}
-
-/*!
- \reimp
-*/
-void QColumnView::setSelectionModel(QItemSelectionModel *newSelectionModel)
-{
- Q_D(const QColumnView);
- for (int i = 0; i < d->columns.size(); ++i) {
- if (d->columns.at(i)->selectionModel() == selectionModel()) {
- d->columns.at(i)->setSelectionModel(newSelectionModel);
- break;
- }
- }
- QAbstractItemView::setSelectionModel(newSelectionModel);
-}
-
-/*!
- \reimp
-*/
-QSize QColumnView::sizeHint() const
-{
- Q_D(const QColumnView);
- QSize sizeHint;
- for (int i = 0; i < d->columns.size(); ++i) {
- sizeHint += d->columns.at(i)->sizeHint();
- }
- return sizeHint.expandedTo(QAbstractItemView::sizeHint());
-}
-
-/*!
- \internal
- Move all widgets from the corner grip and to the right
- */
-void QColumnViewPrivate::_q_gripMoved(int offset)
-{
- Q_Q(QColumnView);
-
- QObject *grip = q->sender();
- Q_ASSERT(grip);
-
- if (q->isRightToLeft())
- offset = -1 * offset;
-
- bool found = false;
- for (int i = 0; i < columns.size(); ++i) {
- if (!found && columns.at(i)->cornerWidget() == grip) {
- found = true;
- columnSizes[i] = columns.at(i)->width();
- if (q->isRightToLeft())
- columns.at(i)->move(columns.at(i)->x() + offset, 0);
- continue;
- }
- if (!found)
- continue;
-
- int currentX = columns.at(i)->x();
- columns.at(i)->move(currentX + offset, 0);
- }
-
- updateScrollbars();
-}
-
-/*!
- \internal
-
- Find where the current columns intersect parent's columns
-
- Delete any extra columns and insert any needed columns.
- */
-void QColumnViewPrivate::closeColumns(const QModelIndex &parent, bool build)
-{
- if (columns.isEmpty())
- return;
-
- bool clearAll = !parent.isValid();
- bool passThroughRoot = false;
-
- QList<QModelIndex> dirsToAppend;
-
- // Find the last column that matches the parent's tree
- int currentColumn = -1;
- QModelIndex parentIndex = parent;
- while (currentColumn == -1 && parentIndex.isValid()) {
- if (columns.isEmpty())
- break;
- parentIndex = parentIndex.parent();
- if (root == parentIndex)
- passThroughRoot = true;
- if (!parentIndex.isValid())
- break;
- for (int i = columns.size() - 1; i >= 0; --i) {
- if (columns.at(i)->rootIndex() == parentIndex) {
- currentColumn = i;
- break;
- }
- }
- if (currentColumn == -1)
- dirsToAppend.append(parentIndex);
- }
-
- // Someone wants to go to an index that can be reached without changing
- // the root index, don't allow them
- if (!clearAll && !passThroughRoot && currentColumn == -1)
- return;
-
- if (currentColumn == -1 && parent.isValid())
- currentColumn = 0;
-
- // Optimization so we don't go deleting and then creating the same thing
- bool alreadyExists = false;
- if (build && columns.size() > currentColumn + 1) {
- bool viewingParent = (columns.at(currentColumn + 1)->rootIndex() == parent);
- bool viewingChild = (!model->hasChildren(parent)
- && !columns.at(currentColumn + 1)->rootIndex().isValid());
- if (viewingParent || viewingChild) {
- currentColumn++;
- alreadyExists = true;
- }
- }
-
- // Delete columns that don't match our path
- for (int i = columns.size() - 1; i > currentColumn; --i) {
- QAbstractItemView* notShownAnymore = columns.at(i);
- columns.removeAt(i);
- notShownAnymore->setVisible(false);
- if (notShownAnymore != previewColumn)
- notShownAnymore->deleteLater();
- }
-
- if (columns.isEmpty()) {
- offset = 0;
- updateScrollbars();
- }
-
- // Now fill in missing columns
- while (!dirsToAppend.isEmpty()) {
- QAbstractItemView *newView = createColumn(dirsToAppend.takeLast(), true);
- if (!dirsToAppend.isEmpty())
- newView->setCurrentIndex(dirsToAppend.last());
- }
-
- if (build && !alreadyExists)
- createColumn(parent, false);
-}
-
-void QColumnViewPrivate::_q_clicked(const QModelIndex &index)
-{
- Q_Q(QColumnView);
- QModelIndex parent = index.parent();
- QAbstractItemView *columnClicked = 0;
- for (int column = 0; column < columns.count(); ++column) {
- if (columns.at(column)->rootIndex() == parent) {
- columnClicked = columns[column];
- break;
- }
- }
- if (q->selectionModel() && columnClicked) {
- QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Current;
- if (columnClicked->selectionModel()->isSelected(index))
- flags |= QItemSelectionModel::Select;
- q->selectionModel()->setCurrentIndex(index, flags);
- }
-}
-
-/*!
- \internal
- Create a new column for \a index. A grip is attached if requested and it is shown
- if requested.
-
- Return the new view
-
- \sa createColumn() setPreviewWidget()
- \sa doLayout()
-*/
-QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bool show)
-{
- Q_Q(QColumnView);
- QAbstractItemView *view = 0;
- if (model->hasChildren(index)) {
- view = q->createColumn(index);
- q->connect(view, SIGNAL(clicked(QModelIndex)),
- q, SLOT(_q_clicked(QModelIndex)));
- } else {
- if (!previewColumn)
- setPreviewWidget(new QWidget(q));
- view = previewColumn;
- view->setMinimumWidth(qMax(view->minimumWidth(), previewWidget->minimumWidth()));
- }
-
- q->connect(view, SIGNAL(activated(QModelIndex)),
- q, SIGNAL(activated(QModelIndex)));
- q->connect(view, SIGNAL(clicked(QModelIndex)),
- q, SIGNAL(clicked(QModelIndex)));
- q->connect(view, SIGNAL(doubleClicked(QModelIndex)),
- q, SIGNAL(doubleClicked(QModelIndex)));
- q->connect(view, SIGNAL(entered(QModelIndex)),
- q, SIGNAL(entered(QModelIndex)));
- q->connect(view, SIGNAL(pressed(QModelIndex)),
- q, SIGNAL(pressed(QModelIndex)));
-
- view->setFocusPolicy(Qt::NoFocus);
- view->setParent(viewport);
- Q_ASSERT(view);
-
- // Setup corner grip
- if (showResizeGrips) {
- QColumnViewGrip *grip = new QColumnViewGrip(view);
- view->setCornerWidget(grip);
- q->connect(grip, SIGNAL(gripMoved(int)), q, SLOT(_q_gripMoved(int)));
- }
-
- if (columnSizes.count() > columns.count()) {
- view->setGeometry(0, 0, columnSizes.at(columns.count()), viewport->height());
- } else {
- int initialWidth = view->sizeHint().width();
- if (q->isRightToLeft())
- view->setGeometry(viewport->width() - initialWidth, 0, initialWidth, viewport->height());
- else
- view->setGeometry(0, 0, initialWidth, viewport->height());
- columnSizes.resize(qMax(columnSizes.count(), columns.count() + 1));
- columnSizes[columns.count()] = initialWidth;
- }
- if (!columns.isEmpty() && columns.last()->isHidden())
- columns.last()->setVisible(true);
-
- columns.append(view);
- doLayout();
- updateScrollbars();
- if (show && view->isHidden())
- view->setVisible(true);
- return view;
-}
-
-/*!
- \fn void QColumnView::updatePreviewWidget(const QModelIndex &index)
-
- This signal is emitted when the preview widget should be updated to
- provide rich information about \a index
-
- \sa previewWidget()
- */
-
-/*!
- To use a custom widget for the final column when you select
- an item overload this function and return a widget.
- \a index is the root index that will be assigned to the view.
-
- Return the new view. QColumnView will automatically take ownership of the widget.
-
- \sa setPreviewWidget()
- */
-QAbstractItemView *QColumnView::createColumn(const QModelIndex &index)
-{
- QListView *view = new QListView(viewport());
-
- initializeColumn(view);
-
- view->setRootIndex(index);
- if (model()->canFetchMore(index))
- model()->fetchMore(index);
-
- return view;
-}
-
-/*!
- Copies the behavior and options of the column view and applies them to
- the \a column such as the iconSize(), textElideMode() and
- alternatingRowColors(). This can be useful when reimplementing
- createColumn().
-
- \since 4.4
- \sa createColumn()
- */
-void QColumnView::initializeColumn(QAbstractItemView *column) const
-{
- Q_D(const QColumnView);
-
- column->setFrameShape(QFrame::NoFrame);
- column->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- column->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
- column->setMinimumWidth(100);
- column->setAttribute(Qt::WA_MacShowFocusRect, false);
-
-#ifndef QT_NO_DRAGANDDROP
- column->setDragDropMode(dragDropMode());
- column->setDragDropOverwriteMode(dragDropOverwriteMode());
- column->setDropIndicatorShown(showDropIndicator());
-#endif
- column->setAlternatingRowColors(alternatingRowColors());
- column->setAutoScroll(hasAutoScroll());
- column->setEditTriggers(editTriggers());
- column->setHorizontalScrollMode(horizontalScrollMode());
- column->setIconSize(iconSize());
- column->setSelectionBehavior(selectionBehavior());
- column->setSelectionMode(selectionMode());
- column->setTabKeyNavigation(tabKeyNavigation());
- column->setTextElideMode(textElideMode());
- column->setVerticalScrollMode(verticalScrollMode());
-
- column->setModel(model());
-
- // Copy the custom delegate per row
- QMapIterator<int, QPointer<QAbstractItemDelegate> > i(d->rowDelegates);
- while (i.hasNext()) {
- i.next();
- column->setItemDelegateForRow(i.key(), i.value());
- }
-
- // set the delegate to be the columnview delegate
- QAbstractItemDelegate *delegate = column->itemDelegate();
- column->setItemDelegate(d->itemDelegate);
- delete delegate;
-}
-
-/*!
- Returns the preview widget, or 0 if there is none.
-
- \sa setPreviewWidget(), updatePreviewWidget()
-*/
-QWidget *QColumnView::previewWidget() const
-{
- Q_D(const QColumnView);
- return d->previewWidget;
-}
-
-/*!
- Sets the preview \a widget.
-
- The \a widget becomes a child of the column view, and will be
- destroyed when the column area is deleted or when a new widget is
- set.
-
- \sa previewWidget(), updatePreviewWidget()
-*/
-void QColumnView::setPreviewWidget(QWidget *widget)
-{
- Q_D(QColumnView);
- d->setPreviewWidget(widget);
-}
-
-/*!
- \internal
-*/
-void QColumnViewPrivate::setPreviewWidget(QWidget *widget)
-{
- Q_Q(QColumnView);
- if (previewColumn) {
- if (!columns.isEmpty() && columns.last() == previewColumn)
- columns.removeLast();
- previewColumn->deleteLater();
- }
- QColumnViewPreviewColumn *column = new QColumnViewPreviewColumn(q);
- column->setPreviewWidget(widget);
- previewColumn = column;
- previewColumn->hide();
- previewColumn->setFrameShape(QFrame::NoFrame);
- previewColumn->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
- previewColumn->setSelectionMode(QAbstractItemView::NoSelection);
- previewColumn->setMinimumWidth(qMax(previewColumn->verticalScrollBar()->width(),
- previewColumn->minimumWidth()));
- previewWidget = widget;
- previewWidget->setParent(previewColumn->viewport());
-}
-
-/*!
- Sets the column widths to the values given in the \a list. Extra values in the list are
- kept and used when the columns are created.
-
- If list contains too few values, only width of the rest of the columns will not be modified.
-
- \sa columnWidths(), createColumn()
-*/
-void QColumnView::setColumnWidths(const QList<int> &list)
-{
- Q_D(QColumnView);
- int i = 0;
- for (; (i < list.count() && i < d->columns.count()); ++i) {
- d->columns.at(i)->resize(list.at(i), d->columns.at(i)->height());
- d->columnSizes[i] = list.at(i);
- }
- for (; i < list.count(); ++i)
- d->columnSizes.append(list.at(i));
-}
-
-/*!
- Returns a list of the width of all the columns in this view.
-
- \sa setColumnWidths()
-*/
-QList<int> QColumnView::columnWidths() const
-{
- Q_D(const QColumnView);
- QList<int> list;
- for (int i = 0; i < d->columns.count(); ++i)
- list.append(d->columnSizes.at(i));
- return list;
-}
-
-/*!
- \reimp
-*/
-void QColumnView::rowsInserted(const QModelIndex &parent, int start, int end)
-{
- QAbstractItemView::rowsInserted(parent, start, end);
- d_func()->checkColumnCreation(parent);
-}
-
-/*!
- \reimp
-*/
-void QColumnView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
-{
- Q_D(QColumnView);
- if (!current.isValid()) {
- QAbstractItemView::currentChanged(current, previous);
- return;
- }
-
- QModelIndex currentParent = current.parent();
- // optimize for just moving up/down in a list where the child view doesn't change
- if (currentParent == previous.parent()
- && model()->hasChildren(current) && model()->hasChildren(previous)) {
- for (int i = 0; i < d->columns.size(); ++i) {
- if (currentParent == d->columns.at(i)->rootIndex()) {
- if (d->columns.size() > i + 1) {
- QAbstractItemView::currentChanged(current, previous);
- return;
- }
- break;
- }
- }
- }
-
- // Scrolling to the right we need to have an empty spot
- bool found = false;
- if (currentParent == previous) {
- for (int i = 0; i < d->columns.size(); ++i) {
- if (currentParent == d->columns.at(i)->rootIndex()) {
- found = true;
- if (d->columns.size() < i + 2) {
- d->createColumn(current, false);
- }
- break;
- }
- }
- }
- if (!found)
- d->closeColumns(current, true);
-
- if (!model()->hasChildren(current))
- emit updatePreviewWidget(current);
-
- QAbstractItemView::currentChanged(current, previous);
-}
-
-/*
- We have change the current column and need to update focus and selection models
- on the new current column.
-*/
-void QColumnViewPrivate::_q_changeCurrentColumn()
-{
- Q_Q(QColumnView);
- if (columns.isEmpty())
- return;
-
- QModelIndex current = q->currentIndex();
- if (!current.isValid())
- return;
-
- // We might have scrolled far to the left so we need to close all of the children
- closeColumns(current, true);
-
- // Set up the "current" column with focus
- int currentColumn = qMax(0, columns.size() - 2);
- QAbstractItemView *parentColumn = columns.at(currentColumn);
- if (q->hasFocus())
- parentColumn->setFocus(Qt::OtherFocusReason);
- q->setFocusProxy(parentColumn);
-
- // find the column that is our current selection model and give it a new one.
- for (int i = 0; i < columns.size(); ++i) {
- if (columns.at(i)->selectionModel() == q->selectionModel()) {
- QItemSelectionModel *replacementSelectionModel =
- new QItemSelectionModel(parentColumn->model());
- replacementSelectionModel->setCurrentIndex(
- q->selectionModel()->currentIndex(), QItemSelectionModel::Current);
- replacementSelectionModel->select(
- q->selectionModel()->selection(), QItemSelectionModel::Select);
- QAbstractItemView *view = columns.at(i);
- view->setSelectionModel(replacementSelectionModel);
- view->setFocusPolicy(Qt::NoFocus);
- if (columns.size() > i + 1)
- view->setCurrentIndex(columns.at(i+1)->rootIndex());
- break;
- }
- }
- parentColumn->selectionModel()->deleteLater();
- parentColumn->setFocusPolicy(Qt::StrongFocus);
- parentColumn->setSelectionModel(q->selectionModel());
- // We want the parent selection to stay highlighted (but dimmed depending upon the color theme)
- if (currentColumn > 0) {
- parentColumn = columns.at(currentColumn - 1);
- if (parentColumn->currentIndex() != current.parent())
- parentColumn->setCurrentIndex(current.parent());
- }
-
- if (columns.last()->isHidden()) {
- columns.last()->setVisible(true);
- }
- if (columns.last()->selectionModel())
- columns.last()->selectionModel()->clear();
- updateScrollbars();
-}
-
-/*!
- \reimp
-*/
-void QColumnView::selectAll()
-{
- if (!model() || !selectionModel())
- return;
-
- QModelIndexList indexList = selectionModel()->selectedIndexes();
- QModelIndex parent = rootIndex();
- QItemSelection selection;
- if (indexList.count() >= 1)
- parent = indexList.at(0).parent();
- if (indexList.count() == 1) {
- parent = indexList.at(0);
- if (!model()->hasChildren(parent))
- parent = parent.parent();
- else
- selection.append(QItemSelectionRange(parent, parent));
- }
-
- QModelIndex tl = model()->index(0, 0, parent);
- QModelIndex br = model()->index(model()->rowCount(parent) - 1,
- model()->columnCount(parent) - 1,
- parent);
- selection.append(QItemSelectionRange(tl, br));
- selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect);
-}
-
-/*
- * private object implementation
- */
-QColumnViewPrivate::QColumnViewPrivate()
-: QAbstractItemViewPrivate()
-,showResizeGrips(true)
-,offset(0)
-,previewWidget(0)
-,previewColumn(0)
-{
-}
-
-QColumnViewPrivate::~QColumnViewPrivate()
-{
-}
-
-/*!
- \internal
-
- */
-void QColumnViewPrivate::_q_columnsInserted(const QModelIndex &parent, int start, int end)
-{
- QAbstractItemViewPrivate::_q_columnsInserted(parent, start, end);
- checkColumnCreation(parent);
-}
-
-/*!
- \internal
-
- Makes sure we create a corresponding column as a result of changing the model.
-
- */
-void QColumnViewPrivate::checkColumnCreation(const QModelIndex &parent)
-{
- if (parent == q_func()->currentIndex() && model->hasChildren(parent)) {
- //the parent has children and is the current
- //let's try to find out if there is already a mapping that is good
- for (int i = 0; i < columns.count(); ++i) {
- QAbstractItemView *view = columns.at(i);
- if (view->rootIndex() == parent) {
- if (view == previewColumn) {
- //let's recreate the parent
- closeColumns(parent, false);
- createColumn(parent, true /*show*/);
- }
- break;
- }
- }
- }
-}
-
-/*!
- \internal
- Place all of the columns where they belong inside of the viewport, resize as necessary.
-*/
-void QColumnViewPrivate::doLayout()
-{
- Q_Q(QColumnView);
- if (!model || columns.isEmpty())
- return;
-
- int viewportHeight = viewport->height();
- int x = columns.at(0)->x();
-
- if (q->isRightToLeft()) {
- x = viewport->width() + q->horizontalOffset();
- for (int i = 0; i < columns.size(); ++i) {
- QAbstractItemView *view = columns.at(i);
- x -= view->width();
- if (x != view->x() || viewportHeight != view->height())
- view->setGeometry(x, 0, view->width(), viewportHeight);
- }
- } else {
- for (int i = 0; i < columns.size(); ++i) {
- QAbstractItemView *view = columns.at(i);
- int currentColumnWidth = view->width();
- if (x != view->x() || viewportHeight != view->height())
- view->setGeometry(x, 0, currentColumnWidth, viewportHeight);
- x += currentColumnWidth;
- }
- }
-}
-
-/*!
- \internal
-
- Draws a delegate with a > if an object has children.
-
- \sa {Model/View Programming}, QItemDelegate
-*/
-void QColumnViewDelegate::paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- drawBackground(painter, option, index );
-
- bool reverse = (option.direction == Qt::RightToLeft);
- int width = ((option.rect.height() * 2) / 3);
- // Modify the options to give us room to add an arrow
- QStyleOptionViewItemV4 opt = option;
- if (reverse)
- opt.rect.adjust(width,0,0,0);
- else
- opt.rect.adjust(0,0,-width,0);
-
- if (!(index.model()->flags(index) & Qt::ItemIsEnabled)) {
- opt.showDecorationSelected = true;
- opt.state |= QStyle::State_Selected;
- }
-
- QItemDelegate::paint(painter, opt, index);
-
- if (reverse)
- opt.rect = QRect(option.rect.x(), option.rect.y(), width, option.rect.height());
- else
- opt.rect = QRect(option.rect.x() + option.rect.width() - width, option.rect.y(),
- width, option.rect.height());
-
- // Draw >
- if (index.model()->hasChildren(index)) {
- const QWidget *view = opt.widget;
- QStyle *style = view ? view->style() : QApplication::style();
- style->drawPrimitive(QStyle::PE_IndicatorColumnViewArrow, &opt, painter, view);
- }
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qcolumnview.cpp"
-
-#endif // QT_NO_COLUMNVIEW
diff --git a/src/gui/itemviews/qcolumnview.h b/src/gui/itemviews/qcolumnview.h
deleted file mode 100644
index a3f74b89d5..0000000000
--- a/src/gui/itemviews/qcolumnview.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOLUMNVIEW_H
-#define QCOLUMNVIEW_H
-
-#include <QtGui/qabstractitemview.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_COLUMNVIEW
-
-class QColumnViewPrivate;
-
-class Q_GUI_EXPORT QColumnView : public QAbstractItemView {
-
-Q_OBJECT
- Q_PROPERTY(bool resizeGripsVisible READ resizeGripsVisible WRITE setResizeGripsVisible)
-
-Q_SIGNALS:
- void updatePreviewWidget(const QModelIndex &index);
-
-public:
- explicit QColumnView(QWidget *parent = 0);
- ~QColumnView();
-
- // QAbstractItemView overloads
- QModelIndex indexAt(const QPoint &point) const;
- void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible);
- QSize sizeHint() const;
- QRect visualRect(const QModelIndex &index) const;
- void setModel(QAbstractItemModel *model);
- void setSelectionModel(QItemSelectionModel * selectionModel);
- void setRootIndex(const QModelIndex &index);
- void selectAll();
-
- // QColumnView functions
- void setResizeGripsVisible(bool visible);
- bool resizeGripsVisible() const;
-
- QWidget *previewWidget() const;
- void setPreviewWidget(QWidget *widget);
-
- void setColumnWidths(const QList<int> &list);
- QList<int> columnWidths() const;
-
-protected:
- QColumnView(QColumnViewPrivate &dd, QWidget *parent = 0);
-
- // QAbstractItemView overloads
- bool isIndexHidden(const QModelIndex &index) const;
- QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
- void resizeEvent(QResizeEvent *event);
- void setSelection(const QRect & rect, QItemSelectionModel::SelectionFlags command);
- QRegion visualRegionForSelection(const QItemSelection &selection) const;
- int horizontalOffset() const;
- int verticalOffset() const;
- void rowsInserted(const QModelIndex &parent, int start, int end);
- void currentChanged(const QModelIndex &current, const QModelIndex &previous);
-
- // QColumnView functions
- void scrollContentsBy(int dx, int dy);
- virtual QAbstractItemView* createColumn(const QModelIndex &rootIndex);
- void initializeColumn(QAbstractItemView *column) const;
-
-private:
- Q_DECLARE_PRIVATE(QColumnView)
- Q_DISABLE_COPY(QColumnView)
- Q_PRIVATE_SLOT(d_func(), void _q_gripMoved(int))
- Q_PRIVATE_SLOT(d_func(), void _q_changeCurrentColumn())
- Q_PRIVATE_SLOT(d_func(), void _q_clicked(const QModelIndex &))
-};
-
-#endif // QT_NO_COLUMNVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOLUMNVIEW_H
-
diff --git a/src/gui/itemviews/qcolumnview_p.h b/src/gui/itemviews/qcolumnview_p.h
deleted file mode 100644
index c42c236445..0000000000
--- a/src/gui/itemviews/qcolumnview_p.h
+++ /dev/null
@@ -1,189 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOLUMNVIEW_P_H
-#define QCOLUMNVIEW_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 "qcolumnview.h"
-
-#ifndef QT_NO_QCOLUMNVIEW
-
-#include <private/qabstractitemview_p.h>
-
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qpropertyanimation.h>
-#include <QtGui/qabstractitemdelegate.h>
-#include <QtGui/qabstractitemview.h>
-#include <QtGui/qitemdelegate.h>
-#include <qlistview.h>
-#include <qevent.h>
-#include <qscrollbar.h>
-
-QT_BEGIN_NAMESPACE
-
-class QColumnViewPreviewColumn : public QAbstractItemView {
-
-public:
- QColumnViewPreviewColumn(QWidget *parent) : QAbstractItemView(parent), previewWidget(0) {
- }
-
- void setPreviewWidget(QWidget *widget) {
- previewWidget = widget;
- setMinimumWidth(previewWidget->minimumWidth());
- }
-
- void resizeEvent(QResizeEvent * event){
- if (!previewWidget)
- return;
- previewWidget->resize(
- qMax(previewWidget->minimumWidth(), event->size().width()),
- previewWidget->height());
- QSize p = viewport()->size();
- QSize v = previewWidget->size();
- horizontalScrollBar()->setRange(0, v.width() - p.width());
- horizontalScrollBar()->setPageStep(p.width());
- verticalScrollBar()->setRange(0, v.height() - p.height());
- verticalScrollBar()->setPageStep(p.height());
-
- QAbstractScrollArea::resizeEvent(event);
- }
-
- QRect visualRect(const QModelIndex &) const
- {
- return QRect();
- }
- void scrollTo(const QModelIndex &, ScrollHint)
- {
- }
- QModelIndex indexAt(const QPoint &) const
- {
- return QModelIndex();
- }
- QModelIndex moveCursor(CursorAction, Qt::KeyboardModifiers)
- {
- return QModelIndex();
- }
- int horizontalOffset () const {
- return 0;
- }
- int verticalOffset () const {
- return 0;
- }
- QRegion visualRegionForSelection(const QItemSelection &) const
- {
- return QRegion();
- }
- bool isIndexHidden(const QModelIndex &) const
- {
- return false;
- }
- void setSelection(const QRect &, QItemSelectionModel::SelectionFlags)
- {
- }
-private:
- QWidget *previewWidget;
-};
-
-class Q_AUTOTEST_EXPORT QColumnViewPrivate : public QAbstractItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QColumnView)
-
-public:
- QColumnViewPrivate();
- ~QColumnViewPrivate();
- void initialize();
-
- QAbstractItemView *createColumn(const QModelIndex &index, bool show);
-
- void updateScrollbars();
- void closeColumns(const QModelIndex &parent = QModelIndex(), bool build = false);
- void doLayout();
- void setPreviewWidget(QWidget *widget);
- void checkColumnCreation(const QModelIndex &parent);
-
-
- void _q_gripMoved(int offset);
- void _q_changeCurrentColumn();
- void _q_clicked(const QModelIndex &index);
- void _q_columnsInserted(const QModelIndex &parent, int start, int end);
-
- QList<QAbstractItemView*> columns;
- QVector<int> columnSizes; // used during init and corner moving
- bool showResizeGrips;
- int offset;
-#ifndef QT_NO_ANIMATION
- QPropertyAnimation currentAnimation;
-#endif
- QWidget *previewWidget;
- QAbstractItemView *previewColumn;
-};
-
-/*!
- * This is a delegate that will paint the triangle
- */
-class QColumnViewDelegate : public QItemDelegate
-{
-
-public:
- explicit QColumnViewDelegate(QObject *parent = 0) : QItemDelegate(parent) {}
- ~QColumnViewDelegate() {}
-
- void paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-};
-#endif // QT_NO_QCOLUMNVIEW
-
-
-QT_END_NAMESPACE
-#endif //QCOLUMNVIEW_P_H
-
diff --git a/src/gui/itemviews/qcolumnviewgrip.cpp b/src/gui/itemviews/qcolumnviewgrip.cpp
deleted file mode 100644
index 5cd448cc35..0000000000
--- a/src/gui/itemviews/qcolumnviewgrip.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_QCOLUMNVIEW
-
-#include "qcolumnviewgrip_p.h"
-#include <qstyleoption.h>
-#include <qpainter.h>
-#include <qbrush.h>
-#include <qevent.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-/*
- \internal
- class QColumnViewGrip
-
- QColumnViewGrip is created to go inside QAbstractScrollArea's corner.
- When the mouse it moved it will resize the scroll area and emit's a signal.
- */
-
-/*
- \internal
- \fn void QColumnViewGrip::gripMoved()
- Signal that is emitted when the grip moves the parent widget.
- */
-
-/*!
- Creates a new QColumnViewGrip with the given \a parent to view a model.
- Use setModel() to set the model.
-*/
-QColumnViewGrip::QColumnViewGrip(QWidget *parent)
-: QWidget(*new QColumnViewGripPrivate, parent, 0)
-{
-#ifndef QT_NO_CURSOR
- setCursor(Qt::SplitHCursor);
-#endif
-}
-
-/*!
- \internal
-*/
-QColumnViewGrip::QColumnViewGrip(QColumnViewGripPrivate & dd, QWidget *parent, Qt::WFlags f)
-: QWidget(dd, parent, f)
-{
-}
-
-/*!
- Destroys the view.
-*/
-QColumnViewGrip::~QColumnViewGrip()
-{
-}
-
-/*!
- Attempt to resize the parent object by \a offset
- returns the amount of offset that it was actually able to resized
-*/
-int QColumnViewGrip::moveGrip(int offset)
-{
- QWidget *parentWidget = (QWidget*)parent();
-
- // first resize the parent
- int oldWidth = parentWidget->width();
- int newWidth = oldWidth;
- if (isRightToLeft())
- newWidth -= offset;
- else
- newWidth += offset;
- newWidth = qMax(parentWidget->minimumWidth(), newWidth);
- parentWidget->resize(newWidth, parentWidget->height());
-
- // Then have the view move the widget
- int realOffset = parentWidget->width() - oldWidth;
- int oldX = parentWidget->x();
- if (realOffset != 0)
- emit gripMoved(realOffset);
- if (isRightToLeft())
- realOffset = -1 * (oldX - parentWidget->x());
- return realOffset;
-}
-
-/*!
- \reimp
-*/
-void QColumnViewGrip::paintEvent(QPaintEvent *event)
-{
- QPainter painter(this);
- QStyleOption opt;
- opt.initFrom(this);
- style()->drawControl(QStyle::CE_ColumnViewGrip, &opt, &painter, this);
- event->accept();
-}
-
-/*!
- \reimp
- Resize the parent window to the sizeHint
-*/
-void QColumnViewGrip::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_UNUSED(event);
- QWidget *parentWidget = (QWidget*)parent();
- int offset = parentWidget->sizeHint().width() - parentWidget->width();
- if (isRightToLeft())
- offset *= -1;
- moveGrip(offset);
- event->accept();
-}
-
-/*!
- \reimp
- Begin watching for mouse movements
-*/
-void QColumnViewGrip::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QColumnViewGrip);
- d->originalXLocation = event->globalX();
- event->accept();
-}
-
-/*!
- \reimp
- Calculate the movement of the grip and moveGrip() and emit gripMoved
-*/
-void QColumnViewGrip::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QColumnViewGrip);
- int offset = event->globalX() - d->originalXLocation;
- d->originalXLocation = moveGrip(offset) + d->originalXLocation;
- event->accept();
-}
-
-/*!
- \reimp
- Stop watching for mouse movements
-*/
-void QColumnViewGrip::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QColumnViewGrip);
- d->originalXLocation = -1;
- event->accept();
-}
-
-/*
- * private object implementation
- */
-QColumnViewGripPrivate::QColumnViewGripPrivate()
-: QWidgetPrivate(),
-originalXLocation(-1)
-{
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_QCOLUMNVIEW
diff --git a/src/gui/itemviews/qcolumnviewgrip_p.h b/src/gui/itemviews/qcolumnviewgrip_p.h
deleted file mode 100644
index a621f953ea..0000000000
--- a/src/gui/itemviews/qcolumnviewgrip_p.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOLUMNVIEWGRIP_P_H
-#define QCOLUMNVIEWGRIP_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 <private/qwidget_p.h>
-
-#ifndef QT_NO_QCOLUMNVIEW
-
-QT_BEGIN_NAMESPACE
-
-class QColumnViewGripPrivate;
-
-class Q_AUTOTEST_EXPORT QColumnViewGrip : public QWidget {
-
-Q_OBJECT
-
-Q_SIGNALS:
- void gripMoved(int offset);
-
-public:
- explicit QColumnViewGrip(QWidget *parent = 0);
- ~QColumnViewGrip();
- int moveGrip(int offset);
-
-protected:
- QColumnViewGrip(QColumnViewGripPrivate &, QWidget *parent = 0, Qt::WFlags f = 0);
- void paintEvent(QPaintEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mousePressEvent(QMouseEvent *event);
-
-private:
- Q_DECLARE_PRIVATE(QColumnViewGrip)
- Q_DISABLE_COPY(QColumnViewGrip)
-};
-
-class QColumnViewGripPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QColumnViewGrip)
-
-public:
- QColumnViewGripPrivate();
- ~QColumnViewGripPrivate() {}
-
- int originalXLocation;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_QCOLUMNVIEW
-
-#endif //QCOLUMNVIEWGRIP_P_H
diff --git a/src/gui/itemviews/qdatawidgetmapper.cpp b/src/gui/itemviews/qdatawidgetmapper.cpp
deleted file mode 100644
index 745ef5af91..0000000000
--- a/src/gui/itemviews/qdatawidgetmapper.cpp
+++ /dev/null
@@ -1,849 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdatawidgetmapper.h"
-
-#ifndef QT_NO_DATAWIDGETMAPPER
-
-#include "qabstractitemmodel.h"
-#include "qitemdelegate.h"
-#include "qmetaobject.h"
-#include "qwidget.h"
-#include "private/qobject_p.h"
-#include "private/qabstractitemmodel_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QDataWidgetMapperPrivate: public QObjectPrivate
-{
-public:
- Q_DECLARE_PUBLIC(QDataWidgetMapper)
-
- QDataWidgetMapperPrivate()
- : model(QAbstractItemModelPrivate::staticEmptyModel()), delegate(0),
- orientation(Qt::Horizontal), submitPolicy(QDataWidgetMapper::AutoSubmit)
- {
- }
-
- QAbstractItemModel *model;
- QAbstractItemDelegate *delegate;
- Qt::Orientation orientation;
- QDataWidgetMapper::SubmitPolicy submitPolicy;
- QPersistentModelIndex rootIndex;
- QPersistentModelIndex currentTopLeft;
-
- inline int itemCount()
- {
- return orientation == Qt::Horizontal
- ? model->rowCount(rootIndex)
- : model->columnCount(rootIndex);
- }
-
- inline int currentIdx() const
- {
- return orientation == Qt::Horizontal ? currentTopLeft.row() : currentTopLeft.column();
- }
-
- inline QModelIndex indexAt(int itemPos)
- {
- return orientation == Qt::Horizontal
- ? model->index(currentIdx(), itemPos, rootIndex)
- : model->index(itemPos, currentIdx(), rootIndex);
- }
-
- inline void flipEventFilters(QAbstractItemDelegate *oldDelegate,
- QAbstractItemDelegate *newDelegate)
- {
- for (int i = 0; i < widgetMap.count(); ++i) {
- QWidget *w = widgetMap.at(i).widget;
- if (!w)
- continue;
- w->removeEventFilter(oldDelegate);
- w->installEventFilter(newDelegate);
- }
- }
-
- void populate();
-
- // private slots
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void _q_commitData(QWidget *);
- void _q_closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint);
- void _q_modelDestroyed();
-
- struct WidgetMapper
- {
- inline WidgetMapper(QWidget *w = 0, int c = 0, const QModelIndex &i = QModelIndex())
- : widget(w), section(c), currentIndex(i) {}
- inline WidgetMapper(QWidget *w, int c, const QModelIndex &i, const QByteArray &p)
- : widget(w), section(c), currentIndex(i), property(p) {}
-
- QPointer<QWidget> widget;
- int section;
- QPersistentModelIndex currentIndex;
- QByteArray property;
- };
-
- void populate(WidgetMapper &m);
- int findWidget(QWidget *w) const;
-
- bool commit(const WidgetMapper &m);
-
- QList<WidgetMapper> widgetMap;
-};
-
-int QDataWidgetMapperPrivate::findWidget(QWidget *w) const
-{
- for (int i = 0; i < widgetMap.count(); ++i) {
- if (widgetMap.at(i).widget == w)
- return i;
- }
- return -1;
-}
-
-bool QDataWidgetMapperPrivate::commit(const WidgetMapper &m)
-{
- if (m.widget.isNull())
- return true; // just ignore
-
- if (!m.currentIndex.isValid())
- return false;
-
- // Create copy to avoid passing the widget mappers data
- QModelIndex idx = m.currentIndex;
- if (m.property.isEmpty())
- delegate->setModelData(m.widget, model, idx);
- else
- model->setData(idx, m.widget->property(m.property), Qt::EditRole);
-
- return true;
-}
-
-void QDataWidgetMapperPrivate::populate(WidgetMapper &m)
-{
- if (m.widget.isNull())
- return;
-
- m.currentIndex = indexAt(m.section);
- if (m.property.isEmpty())
- delegate->setEditorData(m.widget, m.currentIndex);
- else
- m.widget->setProperty(m.property, m.currentIndex.data(Qt::EditRole));
-}
-
-void QDataWidgetMapperPrivate::populate()
-{
- for (int i = 0; i < widgetMap.count(); ++i)
- populate(widgetMap[i]);
-}
-
-static bool qContainsIndex(const QModelIndex &idx, const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
-{
- return idx.row() >= topLeft.row() && idx.row() <= bottomRight.row()
- && idx.column() >= topLeft.column() && idx.column() <= bottomRight.column();
-}
-
-void QDataWidgetMapperPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- if (topLeft.parent() != rootIndex)
- return; // not in our hierarchy
-
- for (int i = 0; i < widgetMap.count(); ++i) {
- WidgetMapper &m = widgetMap[i];
- if (qContainsIndex(m.currentIndex, topLeft, bottomRight))
- populate(m);
- }
-}
-
-void QDataWidgetMapperPrivate::_q_commitData(QWidget *w)
-{
- if (submitPolicy == QDataWidgetMapper::ManualSubmit)
- return;
-
- int idx = findWidget(w);
- if (idx == -1)
- return; // not our widget
-
- commit(widgetMap.at(idx));
-}
-
-class QFocusHelper: public QWidget
-{
-public:
- bool focusNextPrevChild(bool next)
- {
- return QWidget::focusNextPrevChild(next);
- }
-
- static inline void focusNextPrevChild(QWidget *w, bool next)
- {
- static_cast<QFocusHelper *>(w)->focusNextPrevChild(next);
- }
-};
-
-void QDataWidgetMapperPrivate::_q_closeEditor(QWidget *w, QAbstractItemDelegate::EndEditHint hint)
-{
- int idx = findWidget(w);
- if (idx == -1)
- return; // not our widget
-
- switch (hint) {
- case QAbstractItemDelegate::RevertModelCache: {
- populate(widgetMap[idx]);
- break; }
- case QAbstractItemDelegate::EditNextItem:
- QFocusHelper::focusNextPrevChild(w, true);
- break;
- case QAbstractItemDelegate::EditPreviousItem:
- QFocusHelper::focusNextPrevChild(w, false);
- break;
- case QAbstractItemDelegate::SubmitModelCache:
- case QAbstractItemDelegate::NoHint:
- // nothing
- break;
- }
-}
-
-void QDataWidgetMapperPrivate::_q_modelDestroyed()
-{
- Q_Q(QDataWidgetMapper);
-
- model = 0;
- q->setModel(QAbstractItemModelPrivate::staticEmptyModel());
-}
-
-/*!
- \class QDataWidgetMapper
- \brief The QDataWidgetMapper class provides mapping between a section
- of a data model to widgets.
- \since 4.2
- \ingroup model-view
- \ingroup advanced
-
- QDataWidgetMapper can be used to create data-aware widgets by mapping
- them to sections of an item model. A section is a column of a model
- if the orientation is horizontal (the default), otherwise a row.
-
- Every time the current index changes, each widget is updated with data
- from the model via the property specified when its mapping was made.
- If the user edits the contents of a widget, the changes are read using
- the same property and written back to the model.
- By default, each widget's \l{Q_PROPERTY()}{user property} is used to
- transfer data between the model and the widget. Since Qt 4.3, an
- additional addMapping() function enables a named property to be used
- instead of the default user property.
-
- It is possible to set an item delegate to support custom widgets. By default,
- a QItemDelegate is used to synchronize the model with the widgets.
-
- Let us assume that we have an item model named \c{model} with the following contents:
-
- \table
- \row \o 1 \o Qt Norway \o Oslo
- \row \o 2 \o Qt Australia \o Brisbane
- \row \o 3 \o Qt USA \o Palo Alto
- \row \o 4 \o Qt China \o Beijing
- \row \o 5 \o Qt Germany \o Berlin
- \endtable
-
- The following code will map the columns of the model to widgets called \c mySpinBox,
- \c myLineEdit and \c{myCountryChooser}:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp 0
-
- After the call to toFirst(), \c mySpinBox displays the value \c{1}, \c myLineEdit
- displays \c {Nokia Corporation and/or its subsidiary(-ies)} and \c myCountryChooser displays \c{Oslo}. The
- navigational functions toFirst(), toNext(), toPrevious(), toLast() and setCurrentIndex()
- can be used to navigate in the model and update the widgets with contents from
- the model.
-
- The setRootIndex() function enables a particular item in a model to be
- specified as the root index - children of this item will be mapped to
- the relevant widgets in the user interface.
-
- QDataWidgetMapper supports two submit policies, \c AutoSubmit and \c{ManualSubmit}.
- \c AutoSubmit will update the model as soon as the current widget loses focus,
- \c ManualSubmit will not update the model unless submit() is called. \c ManualSubmit
- is useful when displaying a dialog that lets the user cancel all modifications.
- Also, other views that display the model won't update until the user finishes
- all their modifications and submits.
-
- Note that QDataWidgetMapper keeps track of external modifications. If the contents
- of the model are updated in another module of the application, the widgets are
- updated as well.
-
- \sa QAbstractItemModel, QAbstractItemDelegate
- */
-
-/*! \enum QDataWidgetMapper::SubmitPolicy
-
- This enum describes the possible submit policies a QDataWidgetMapper
- supports.
-
- \value AutoSubmit Whenever a widget loses focus, the widget's current
- value is set to the item model.
- \value ManualSubmit The model is not updated until submit() is called.
- */
-
-/*!
- \fn void QDataWidgetMapper::currentIndexChanged(int index)
-
- This signal is emitted after the current index has changed and
- all widgets were populated with new data. \a index is the new
- current index.
-
- \sa currentIndex(), setCurrentIndex()
- */
-
-/*!
- Constructs a new QDataWidgetMapper with parent object \a parent.
- By default, the orientation is horizontal and the submit policy
- is \c{AutoSubmit}.
-
- \sa setOrientation(), setSubmitPolicy()
- */
-QDataWidgetMapper::QDataWidgetMapper(QObject *parent)
- : QObject(*new QDataWidgetMapperPrivate, parent)
-{
- setItemDelegate(new QItemDelegate(this));
-}
-
-/*!
- Destroys the object.
- */
-QDataWidgetMapper::~QDataWidgetMapper()
-{
-}
-
-/*!
- Sets the current model to \a model. If another model was set,
- all mappings to that old model are cleared.
-
- \sa model()
- */
-void QDataWidgetMapper::setModel(QAbstractItemModel *model)
-{
- Q_D(QDataWidgetMapper);
-
- if (d->model == model)
- return;
-
- if (d->model) {
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this,
- SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- disconnect(d->model, SIGNAL(destroyed()), this,
- SLOT(_q_modelDestroyed()));
- }
- clearMapping();
- d->rootIndex = QModelIndex();
- d->currentTopLeft = QModelIndex();
-
- d->model = model;
-
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(destroyed()), SLOT(_q_modelDestroyed()));
-}
-
-/*!
- Returns the current model.
-
- \sa setModel()
- */
-QAbstractItemModel *QDataWidgetMapper::model() const
-{
- Q_D(const QDataWidgetMapper);
- return d->model == QAbstractItemModelPrivate::staticEmptyModel()
- ? static_cast<QAbstractItemModel *>(0)
- : d->model;
-}
-
-/*!
- Sets the item delegate to \a delegate. The delegate will be used to write
- data from the model into the widget and from the widget to the model,
- using QAbstractItemDelegate::setEditorData() and QAbstractItemDelegate::setModelData().
-
- The delegate also decides when to apply data and when to change the editor,
- using QAbstractItemDelegate::commitData() and QAbstractItemDelegate::closeEditor().
-
- \warning You should not share the same instance of a delegate between widget mappers
- or views. Doing so can cause incorrect or unintuitive editing behavior since each
- view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
- signal, and attempt to access, modify or close an editor that has already been closed.
- */
-void QDataWidgetMapper::setItemDelegate(QAbstractItemDelegate *delegate)
-{
- Q_D(QDataWidgetMapper);
- QAbstractItemDelegate *oldDelegate = d->delegate;
- if (oldDelegate) {
- disconnect(oldDelegate, SIGNAL(commitData(QWidget*)), this, SLOT(_q_commitData(QWidget*)));
- disconnect(oldDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- this, SLOT(_q_closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- }
-
- d->delegate = delegate;
-
- if (delegate) {
- connect(delegate, SIGNAL(commitData(QWidget*)), SLOT(_q_commitData(QWidget*)));
- connect(delegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
- SLOT(_q_closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));
- }
-
- d->flipEventFilters(oldDelegate, delegate);
-}
-
-/*!
- Returns the current item delegate.
- */
-QAbstractItemDelegate *QDataWidgetMapper::itemDelegate() const
-{
- Q_D(const QDataWidgetMapper);
- return d->delegate;
-}
-
-/*!
- Sets the root item to \a index. This can be used to display
- a branch of a tree. Pass an invalid model index to display
- the top-most branch.
-
- \sa rootIndex()
- */
-void QDataWidgetMapper::setRootIndex(const QModelIndex &index)
-{
- Q_D(QDataWidgetMapper);
- d->rootIndex = index;
-}
-
-/*!
- Returns the current root index.
-
- \sa setRootIndex()
-*/
-QModelIndex QDataWidgetMapper::rootIndex() const
-{
- Q_D(const QDataWidgetMapper);
- return QModelIndex(d->rootIndex);
-}
-
-/*!
- Adds a mapping between a \a widget and a \a section from the model.
- The \a section is a column in the model if the orientation is
- horizontal (the default), otherwise a row.
-
- For the following example, we assume a model \c myModel that
- has two columns: the first one contains the names of people in a
- group, and the second column contains their ages. The first column
- is mapped to the QLineEdit \c nameLineEdit, and the second is
- mapped to the QSpinBox \c{ageSpinBox}:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp 1
-
- \bold{Notes:}
- \list
- \o If the \a widget is already mapped to a section, the
- old mapping will be replaced by the new one.
- \o Only one-to-one mappings between sections and widgets are allowed.
- It is not possible to map a single section to multiple widgets, or to
- map a single widget to multiple sections.
- \endlist
-
- \sa removeMapping(), mappedSection(), clearMapping()
- */
-void QDataWidgetMapper::addMapping(QWidget *widget, int section)
-{
- Q_D(QDataWidgetMapper);
-
- removeMapping(widget);
- d->widgetMap.append(QDataWidgetMapperPrivate::WidgetMapper(widget, section, d->indexAt(section)));
- widget->installEventFilter(d->delegate);
-}
-
-/*!
- \since 4.3
-
- Essentially the same as addMapping(), but adds the possibility to specify
- the property to use specifying \a propertyName.
-
- \sa addMapping()
-*/
-
-void QDataWidgetMapper::addMapping(QWidget *widget, int section, const QByteArray &propertyName)
-{
- Q_D(QDataWidgetMapper);
-
- removeMapping(widget);
- d->widgetMap.append(QDataWidgetMapperPrivate::WidgetMapper(widget, section, d->indexAt(section), propertyName));
- widget->installEventFilter(d->delegate);
-}
-
-/*!
- Removes the mapping for the given \a widget.
-
- \sa addMapping(), clearMapping()
- */
-void QDataWidgetMapper::removeMapping(QWidget *widget)
-{
- Q_D(QDataWidgetMapper);
-
- int idx = d->findWidget(widget);
- if (idx == -1)
- return;
-
- d->widgetMap.removeAt(idx);
- widget->removeEventFilter(d->delegate);
-}
-
-/*!
- Returns the section the \a widget is mapped to or -1
- if the widget is not mapped.
-
- \sa addMapping(), removeMapping()
- */
-int QDataWidgetMapper::mappedSection(QWidget *widget) const
-{
- Q_D(const QDataWidgetMapper);
-
- int idx = d->findWidget(widget);
- if (idx == -1)
- return -1;
-
- return d->widgetMap.at(idx).section;
-}
-
-/*!
- \since 4.3
- Returns the name of the property that is used when mapping
- data to the given \a widget.
-
- \sa mappedSection(), addMapping(), removeMapping()
-*/
-
-QByteArray QDataWidgetMapper::mappedPropertyName(QWidget *widget) const
-{
- Q_D(const QDataWidgetMapper);
-
- int idx = d->findWidget(widget);
- if (idx == -1)
- return QByteArray();
- const QDataWidgetMapperPrivate::WidgetMapper &m = d->widgetMap.at(idx);
- if (m.property.isEmpty())
- return m.widget->metaObject()->userProperty().name();
- else
- return m.property;
-}
-
-/*!
- Returns the widget that is mapped at \a section, or
- 0 if no widget is mapped at that section.
-
- \sa addMapping(), removeMapping()
- */
-QWidget *QDataWidgetMapper::mappedWidgetAt(int section) const
-{
- Q_D(const QDataWidgetMapper);
-
- for (int i = 0; i < d->widgetMap.count(); ++i) {
- if (d->widgetMap.at(i).section == section)
- return d->widgetMap.at(i).widget;
- }
-
- return 0;
-}
-
-/*!
- Repopulates all widgets with the current data of the model.
- All unsubmitted changes will be lost.
-
- \sa submit(), setSubmitPolicy()
- */
-void QDataWidgetMapper::revert()
-{
- Q_D(QDataWidgetMapper);
-
- d->populate();
-}
-
-/*!
- Submits all changes from the mapped widgets to the model.
-
- For every mapped section, the item delegate reads the current
- value from the widget and sets it in the model. Finally, the
- model's \l {QAbstractItemModel::}{submit()} method is invoked.
-
- Returns true if all the values were submitted, otherwise false.
-
- Note: For database models, QSqlQueryModel::lastError() can be
- used to retrieve the last error.
-
- \sa revert(), setSubmitPolicy()
- */
-bool QDataWidgetMapper::submit()
-{
- Q_D(QDataWidgetMapper);
-
- for (int i = 0; i < d->widgetMap.count(); ++i) {
- const QDataWidgetMapperPrivate::WidgetMapper &m = d->widgetMap.at(i);
- if (!d->commit(m))
- return false;
- }
-
- return d->model->submit();
-}
-
-/*!
- Populates the widgets with data from the first row of the model
- if the orientation is horizontal (the default), otherwise
- with data from the first column.
-
- This is equivalent to calling \c setCurrentIndex(0).
-
- \sa toLast(), setCurrentIndex()
- */
-void QDataWidgetMapper::toFirst()
-{
- setCurrentIndex(0);
-}
-
-/*!
- Populates the widgets with data from the last row of the model
- if the orientation is horizontal (the default), otherwise
- with data from the last column.
-
- Calls setCurrentIndex() internally.
-
- \sa toFirst(), setCurrentIndex()
- */
-void QDataWidgetMapper::toLast()
-{
- Q_D(QDataWidgetMapper);
- setCurrentIndex(d->itemCount() - 1);
-}
-
-
-/*!
- Populates the widgets with data from the next row of the model
- if the orientation is horizontal (the default), otherwise
- with data from the next column.
-
- Calls setCurrentIndex() internally. Does nothing if there is
- no next row in the model.
-
- \sa toPrevious(), setCurrentIndex()
- */
-void QDataWidgetMapper::toNext()
-{
- Q_D(QDataWidgetMapper);
- setCurrentIndex(d->currentIdx() + 1);
-}
-
-/*!
- Populates the widgets with data from the previous row of the model
- if the orientation is horizontal (the default), otherwise
- with data from the previous column.
-
- Calls setCurrentIndex() internally. Does nothing if there is
- no previous row in the model.
-
- \sa toNext(), setCurrentIndex()
- */
-void QDataWidgetMapper::toPrevious()
-{
- Q_D(QDataWidgetMapper);
- setCurrentIndex(d->currentIdx() - 1);
-}
-
-/*!
- \property QDataWidgetMapper::currentIndex
- \brief the current row or column
-
- The widgets are populated with with data from the row at \a index
- if the orientation is horizontal (the default), otherwise with
- data from the column at \a index.
-
- \sa setCurrentModelIndex(), toFirst(), toNext(), toPrevious(), toLast()
-*/
-void QDataWidgetMapper::setCurrentIndex(int index)
-{
- Q_D(QDataWidgetMapper);
-
- if (index < 0 || index >= d->itemCount())
- return;
- d->currentTopLeft = d->orientation == Qt::Horizontal
- ? d->model->index(index, 0, d->rootIndex)
- : d->model->index(0, index, d->rootIndex);
- d->populate();
-
- emit currentIndexChanged(index);
-}
-
-int QDataWidgetMapper::currentIndex() const
-{
- Q_D(const QDataWidgetMapper);
- return d->currentIdx();
-}
-
-/*!
- Sets the current index to the row of the \a index if the
- orientation is horizontal (the default), otherwise to the
- column of the \a index.
-
- Calls setCurrentIndex() internally. This convenience slot can be
- connected to the signal \l
- {QItemSelectionModel::}{currentRowChanged()} or \l
- {QItemSelectionModel::}{currentColumnChanged()} of another view's
- \l {QItemSelectionModel}{selection model}.
-
- The following example illustrates how to update all widgets
- with new data whenever the selection of a QTableView named
- \c myTableView changes:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp 2
-
- \sa currentIndex()
-*/
-void QDataWidgetMapper::setCurrentModelIndex(const QModelIndex &index)
-{
- Q_D(QDataWidgetMapper);
-
- if (!index.isValid()
- || index.model() != d->model
- || index.parent() != d->rootIndex)
- return;
-
- setCurrentIndex(d->orientation == Qt::Horizontal ? index.row() : index.column());
-}
-
-/*!
- Clears all mappings.
-
- \sa addMapping(), removeMapping()
- */
-void QDataWidgetMapper::clearMapping()
-{
- Q_D(QDataWidgetMapper);
-
- while (!d->widgetMap.isEmpty()) {
- QWidget *w = d->widgetMap.takeLast().widget;
- if (w)
- w->removeEventFilter(d->delegate);
- }
-}
-
-/*!
- \property QDataWidgetMapper::orientation
- \brief the orientation of the model
-
- If the orientation is Qt::Horizontal (the default), a widget is
- mapped to a column of a data model. The widget will be populated
- with the model's data from its mapped column and the row that
- currentIndex() points at.
-
- Use Qt::Horizontal for tabular data that looks like this:
-
- \table
- \row \o 1 \o Qt Norway \o Oslo
- \row \o 2 \o Qt Australia \o Brisbane
- \row \o 3 \o Qt USA \o Silicon Valley
- \row \o 4 \o Qt China \o Beijing
- \row \o 5 \o Qt Germany \o Berlin
- \endtable
-
- If the orientation is set to Qt::Vertical, a widget is mapped to
- a row. Calling setCurrentIndex() will change the current column.
- The widget will be populates with the model's data from its
- mapped row and the column that currentIndex() points at.
-
- Use Qt::Vertical for tabular data that looks like this:
-
- \table
- \row \o 1 \o 2 \o 3 \o 4 \o 5
- \row \o Qt Norway \o Qt Australia \o Qt USA \o Qt China \o Qt Germany
- \row \o Oslo \o Brisbane \o Silicon Valley \o Beijing \i Berlin
- \endtable
-
- Changing the orientation clears all existing mappings.
-*/
-void QDataWidgetMapper::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QDataWidgetMapper);
-
- if (d->orientation == orientation)
- return;
-
- clearMapping();
- d->orientation = orientation;
-}
-
-Qt::Orientation QDataWidgetMapper::orientation() const
-{
- Q_D(const QDataWidgetMapper);
- return d->orientation;
-}
-
-/*!
- \property QDataWidgetMapper::submitPolicy
- \brief the current submit policy
-
- Changing the current submit policy will revert all widgets
- to the current data from the model.
-*/
-void QDataWidgetMapper::setSubmitPolicy(SubmitPolicy policy)
-{
- Q_D(QDataWidgetMapper);
- if (policy == d->submitPolicy)
- return;
-
- revert();
- d->submitPolicy = policy;
-}
-
-QDataWidgetMapper::SubmitPolicy QDataWidgetMapper::submitPolicy() const
-{
- Q_D(const QDataWidgetMapper);
- return d->submitPolicy;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qdatawidgetmapper.cpp"
-
-#endif // QT_NO_DATAWIDGETMAPPER
diff --git a/src/gui/itemviews/qdatawidgetmapper.h b/src/gui/itemviews/qdatawidgetmapper.h
deleted file mode 100644
index 9485cb08a8..0000000000
--- a/src/gui/itemviews/qdatawidgetmapper.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** 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 QDATAWIDGETMAPPER_H
-#define QDATAWIDGETMAPPER_H
-
-#include "QtCore/qobject.h"
-
-#ifndef QT_NO_DATAWIDGETMAPPER
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QAbstractItemDelegate;
-class QAbstractItemModel;
-class QModelIndex;
-class QDataWidgetMapperPrivate;
-
-class Q_GUI_EXPORT QDataWidgetMapper: public QObject
-{
- Q_OBJECT
-
- Q_ENUMS(SubmitPolicy)
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
- Q_PROPERTY(SubmitPolicy submitPolicy READ submitPolicy WRITE setSubmitPolicy)
-
-public:
- QDataWidgetMapper(QObject *parent = 0);
- ~QDataWidgetMapper();
-
- void setModel(QAbstractItemModel *model);
- QAbstractItemModel *model() const;
-
- void setItemDelegate(QAbstractItemDelegate *delegate);
- QAbstractItemDelegate *itemDelegate() const;
-
- void setRootIndex(const QModelIndex &index);
- QModelIndex rootIndex() const;
-
- void setOrientation(Qt::Orientation aOrientation);
- Qt::Orientation orientation() const;
-
- enum SubmitPolicy { AutoSubmit, ManualSubmit };
- void setSubmitPolicy(SubmitPolicy policy);
- SubmitPolicy submitPolicy() const;
-
- void addMapping(QWidget *widget, int section);
- void addMapping(QWidget *widget, int section, const QByteArray &propertyName);
- void removeMapping(QWidget *widget);
- int mappedSection(QWidget *widget) const;
- QByteArray mappedPropertyName(QWidget *widget) const;
- QWidget *mappedWidgetAt(int section) const;
- void clearMapping();
-
- int currentIndex() const;
-
-public Q_SLOTS:
- void revert();
- bool submit();
-
- void toFirst();
- void toLast();
- void toNext();
- void toPrevious();
- virtual void setCurrentIndex(int index);
- void setCurrentModelIndex(const QModelIndex &index);
-
-Q_SIGNALS:
- void currentIndexChanged(int index);
-
-private:
- Q_DECLARE_PRIVATE(QDataWidgetMapper)
- Q_DISABLE_COPY(QDataWidgetMapper)
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &, const QModelIndex &))
- Q_PRIVATE_SLOT(d_func(), void _q_commitData(QWidget *))
- Q_PRIVATE_SLOT(d_func(), void _q_closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint))
- Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed())
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_DATAWIDGETMAPPER
-#endif
-
diff --git a/src/gui/itemviews/qdirmodel.cpp b/src/gui/itemviews/qdirmodel.cpp
deleted file mode 100644
index 203ac69c12..0000000000
--- a/src/gui/itemviews/qdirmodel.cpp
+++ /dev/null
@@ -1,1406 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdirmodel.h"
-
-#ifndef QT_NO_DIRMODEL
-#include <qstack.h>
-#include <qfile.h>
-#include <qfilesystemmodel.h>
-#include <qurl.h>
-#include <qmime.h>
-#include <qpair.h>
-#include <qvector.h>
-#include <qobject.h>
-#include <qdatetime.h>
-#include <qlocale.h>
-#include <qstyle.h>
-#include <qapplication.h>
-#include <private/qabstractitemmodel_p.h>
-#include <qdebug.h>
-
-/*!
- \enum QDirModel::Roles
- \value FileIconRole
- \value FilePathRole
- \value FileNameRole
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QDirModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QDirModel)
-
-public:
- struct QDirNode
- {
- QDirNode() : parent(0), populated(false), stat(false) {}
- ~QDirNode() { children.clear(); }
- QDirNode *parent;
- QFileInfo info;
- QIcon icon; // cache the icon
- mutable QVector<QDirNode> children;
- mutable bool populated; // have we read the children
- mutable bool stat;
- };
-
- QDirModelPrivate()
- : resolveSymlinks(true),
- readOnly(true),
- lazyChildCount(false),
- allowAppendChild(true),
- iconProvider(&defaultProvider),
- shouldStat(true) // ### This is set to false by QFileDialog
- { }
-
- void init();
- QDirNode *node(int row, QDirNode *parent) const;
- QVector<QDirNode> children(QDirNode *parent, bool stat) const;
-
- void _q_refresh();
-
- void savePersistentIndexes();
- void restorePersistentIndexes();
-
- QFileInfoList entryInfoList(const QString &path) const;
- QStringList entryList(const QString &path) const;
-
- QString name(const QModelIndex &index) const;
- QString size(const QModelIndex &index) const;
- QString type(const QModelIndex &index) const;
- QString time(const QModelIndex &index) const;
-
- void appendChild(QDirModelPrivate::QDirNode *parent, const QString &path) const;
- static QFileInfo resolvedInfo(QFileInfo info);
-
- inline QDirNode *node(const QModelIndex &index) const;
- inline void populate(QDirNode *parent) const;
- inline void clear(QDirNode *parent) const;
-
- void invalidate();
-
- mutable QDirNode root;
- bool resolveSymlinks;
- bool readOnly;
- bool lazyChildCount;
- bool allowAppendChild;
-
- QDir::Filters filters;
- QDir::SortFlags sort;
- QStringList nameFilters;
-
- QFileIconProvider *iconProvider;
- QFileIconProvider defaultProvider;
-
- struct SavedPersistent {
- QString path;
- int column;
- QPersistentModelIndexData *data;
- QPersistentModelIndex index;
- };
- QList<SavedPersistent> savedPersistent;
- QPersistentModelIndex toBeRefreshed;
-
- bool shouldStat; // use the "carefull not to stat directories" mode
-};
-
-void qt_setDirModelShouldNotStat(QDirModelPrivate *modelPrivate)
-{
- modelPrivate->shouldStat = false;
-}
-
-QDirModelPrivate::QDirNode *QDirModelPrivate::node(const QModelIndex &index) const
-{
- QDirModelPrivate::QDirNode *n =
- static_cast<QDirModelPrivate::QDirNode*>(index.internalPointer());
- Q_ASSERT(n);
- return n;
-}
-
-void QDirModelPrivate::populate(QDirNode *parent) const
-{
- Q_ASSERT(parent);
- parent->children = children(parent, parent->stat);
- parent->populated = true;
-}
-
-void QDirModelPrivate::clear(QDirNode *parent) const
-{
- Q_ASSERT(parent);
- parent->children.clear();
- parent->populated = false;
-}
-
-void QDirModelPrivate::invalidate()
-{
- QStack<const QDirNode*> nodes;
- nodes.push(&root);
- while (!nodes.empty()) {
- const QDirNode *current = nodes.pop();
- current->stat = false;
- const QVector<QDirNode> children = current->children;
- for (int i = 0; i < children.count(); ++i)
- nodes.push(&children.at(i));
- }
-}
-
-/*!
- \class QDirModel
- \obsolete
- \brief The QDirModel class provides a data model for the local filesystem.
-
- \ingroup model-view
-
- The usage of QDirModel is not recommended anymore. The
- QFileSystemModel class is a more performant alternative.
-
- This class provides access to the local filesystem, providing functions
- for renaming and removing files and directories, and for creating new
- directories. In the simplest case, it can be used with a suitable display
- widget as part of a browser or filer.
-
- QDirModel keeps a cache with file information. The cache needs to be
- updated with refresh().
-
- QDirModel can be accessed using the standard interface provided by
- QAbstractItemModel, but it also provides some convenience functions
- that are specific to a directory model. The fileInfo() and isDir()
- functions provide information about the underlying files and directories
- related to items in the model.
-
- Directories can be created and removed using mkdir(), rmdir(), and the
- model will be automatically updated to take the changes into account.
-
- \note QDirModel requires an instance of a GUI application.
-
- \sa nameFilters(), setFilter(), filter(), QListView, QTreeView, QFileSystemModel,
- {Dir View Example}, {Model Classes}
-*/
-
-/*!
- Constructs a new directory model with the given \a parent.
- Only those files matching the \a nameFilters and the
- \a filters are included in the model. The sort order is given by the
- \a sort flags.
-*/
-
-QDirModel::QDirModel(const QStringList &nameFilters,
- QDir::Filters filters,
- QDir::SortFlags sort,
- QObject *parent)
- : QAbstractItemModel(*new QDirModelPrivate, parent)
-{
- Q_D(QDirModel);
- // we always start with QDir::drives()
- d->nameFilters = nameFilters.isEmpty() ? QStringList(QLatin1String("*")) : nameFilters;
- d->filters = filters;
- d->sort = sort;
- d->root.parent = 0;
- d->root.info = QFileInfo();
- d->clear(&d->root);
-}
-
-/*!
- Constructs a directory model with the given \a parent.
-*/
-
-QDirModel::QDirModel(QObject *parent)
- : QAbstractItemModel(*new QDirModelPrivate, parent)
-{
- Q_D(QDirModel);
- d->init();
-}
-
-/*!
- \internal
-*/
-QDirModel::QDirModel(QDirModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- Q_D(QDirModel);
- d->init();
-}
-
-/*!
- Destroys this directory model.
-*/
-
-QDirModel::~QDirModel()
-{
-
-}
-
-/*!
- Returns the model item index for the item in the \a parent with the
- given \a row and \a column.
-
-*/
-
-QModelIndex QDirModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QDirModel);
- // note that rowCount does lazy population
- if (column < 0 || column >= columnCount(parent) || row < 0 || parent.column() > 0)
- return QModelIndex();
- // make sure the list of children is up to date
- QDirModelPrivate::QDirNode *p = (d->indexValid(parent) ? d->node(parent) : &d->root);
- Q_ASSERT(p);
- if (!p->populated)
- d->populate(p); // populate without stat'ing
- if (row >= p->children.count())
- return QModelIndex();
- // now get the internal pointer for the index
- QDirModelPrivate::QDirNode *n = d->node(row, d->indexValid(parent) ? p : 0);
- Q_ASSERT(n);
-
- return createIndex(row, column, n);
-}
-
-/*!
- Return the parent of the given \a child model item.
-*/
-
-QModelIndex QDirModel::parent(const QModelIndex &child) const
-{
- Q_D(const QDirModel);
-
- if (!d->indexValid(child))
- return QModelIndex();
- QDirModelPrivate::QDirNode *node = d->node(child);
- QDirModelPrivate::QDirNode *par = (node ? node->parent : 0);
- if (par == 0) // parent is the root node
- return QModelIndex();
-
- // get the parent's row
- const QVector<QDirModelPrivate::QDirNode> children =
- par->parent ? par->parent->children : d->root.children;
- Q_ASSERT(children.count() > 0);
- int row = (par - &(children.at(0)));
- Q_ASSERT(row >= 0);
-
- return createIndex(row, 0, par);
-}
-
-/*!
- Returns the number of rows in the \a parent model item.
-
-*/
-
-int QDirModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QDirModel);
- if (parent.column() > 0)
- return 0;
-
- if (!parent.isValid()) {
- if (!d->root.populated) // lazy population
- d->populate(&d->root);
- return d->root.children.count();
- }
- if (parent.model() != this)
- return 0;
- QDirModelPrivate::QDirNode *p = d->node(parent);
- if (p->info.isDir() && !p->populated) // lazy population
- d->populate(p);
- return p->children.count();
-}
-
-/*!
- Returns the number of columns in the \a parent model item.
-
-*/
-
-int QDirModel::columnCount(const QModelIndex &parent) const
-{
- if (parent.column() > 0)
- return 0;
- return 4;
-}
-
-/*!
- Returns the data for the model item \a index with the given \a role.
-*/
-QVariant QDirModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QDirModel);
- if (!d->indexValid(index))
- return QVariant();
-
- if (role == Qt::DisplayRole || role == Qt::EditRole) {
- switch (index.column()) {
- case 0: return d->name(index);
- case 1: return d->size(index);
- case 2: return d->type(index);
- case 3: return d->time(index);
- default:
- qWarning("data: invalid display value column %d", index.column());
- return QVariant();
- }
- }
-
- if (index.column() == 0) {
- if (role == FileIconRole)
- return fileIcon(index);
- if (role == FilePathRole)
- return filePath(index);
- if (role == FileNameRole)
- return fileName(index);
- }
-
- if (index.column() == 1 && Qt::TextAlignmentRole == role) {
- return Qt::AlignRight;
- }
- return QVariant();
-}
-
-/*!
- Sets the data for the model item \a index with the given \a role to
- the data referenced by the \a value. Returns true if successful;
- otherwise returns false.
-
- \sa Qt::ItemDataRole
-*/
-
-bool QDirModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- Q_D(QDirModel);
- if (!d->indexValid(index) || index.column() != 0
- || (flags(index) & Qt::ItemIsEditable) == 0 || role != Qt::EditRole)
- return false;
-
- QDirModelPrivate::QDirNode *node = d->node(index);
- QDir dir = node->info.dir();
- QString name = value.toString();
- if (dir.rename(node->info.fileName(), name)) {
- node->info = QFileInfo(dir, name);
- QModelIndex sibling = index.sibling(index.row(), 3);
- emit dataChanged(index, sibling);
-
- d->toBeRefreshed = index.parent();
- QMetaObject::invokeMethod(this, "_q_refresh", Qt::QueuedConnection);
-
- return true;
- }
-
- return false;
-}
-
-/*!
- Returns the data stored under the given \a role for the specified \a section
- of the header with the given \a orientation.
-*/
-
-QVariant QDirModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Horizontal) {
- if (role != Qt::DisplayRole)
- return QVariant();
- switch (section) {
- case 0: return tr("Name");
- case 1: return tr("Size");
- case 2: return
-#ifdef Q_OS_MAC
- tr("Kind", "Match OS X Finder");
-#else
- tr("Type", "All other platforms");
-#endif
- // Windows - Type
- // OS X - Kind
- // Konqueror - File Type
- // Nautilus - Type
- case 3: return tr("Date Modified");
- default: return QVariant();
- }
- }
- return QAbstractItemModel::headerData(section, orientation, role);
-}
-
-/*!
- Returns true if the \a parent model item has children; otherwise
- returns false.
-*/
-
-bool QDirModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QDirModel);
- if (parent.column() > 0)
- return false;
-
- if (!parent.isValid()) // the invalid index is the "My Computer" item
- return true; // the drives
- QDirModelPrivate::QDirNode *p = d->node(parent);
- Q_ASSERT(p);
-
- if (d->lazyChildCount) // optimization that only checks for children if the node has been populated
- return p->info.isDir();
- return p->info.isDir() && rowCount(parent) > 0;
-}
-
-/*!
- Returns the item flags for the given \a index in the model.
-
- \sa Qt::ItemFlags
-*/
-Qt::ItemFlags QDirModel::flags(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (!d->indexValid(index))
- return flags;
- flags |= Qt::ItemIsDragEnabled;
- if (d->readOnly)
- return flags;
- QDirModelPrivate::QDirNode *node = d->node(index);
- if ((index.column() == 0) && node->info.isWritable()) {
- flags |= Qt::ItemIsEditable;
- if (fileInfo(index).isDir()) // is directory and is editable
- flags |= Qt::ItemIsDropEnabled;
- }
- return flags;
-}
-
-/*!
- Sort the model items in the \a column using the \a order given.
- The order is a value defined in \l Qt::SortOrder.
-*/
-
-void QDirModel::sort(int column, Qt::SortOrder order)
-{
- QDir::SortFlags sort = QDir::DirsFirst | QDir::IgnoreCase;
- if (order == Qt::DescendingOrder)
- sort |= QDir::Reversed;
-
- switch (column) {
- case 0:
- sort |= QDir::Name;
- break;
- case 1:
- sort |= QDir::Size;
- break;
- case 2:
- sort |= QDir::Type;
- break;
- case 3:
- sort |= QDir::Time;
- break;
- default:
- break;
- }
-
- setSorting(sort);
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of items
- in the model.
-*/
-
-QStringList QDirModel::mimeTypes() const
-{
- return QStringList(QLatin1String("text/uri-list"));
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a indexes. The format used to describe the items corresponding to the
- indexes is obtained from the mimeTypes() function.
-
- If the list of indexes is empty, 0 is returned rather than a serialized
- empty list.
-*/
-
-QMimeData *QDirModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QUrl> urls;
- QList<QModelIndex>::const_iterator it = indexes.begin();
- for (; it != indexes.end(); ++it)
- if ((*it).column() == 0)
- urls << QUrl::fromLocalFile(filePath(*it));
- QMimeData *data = new QMimeData();
- data->setUrls(urls);
- return data;
-}
-
-/*!
- Handles the \a data supplied by a drag and drop operation that ended with
- the given \a action over the row in the model specified by the \a row and
- \a column and by the \a parent index.
-
- \sa supportedDropActions()
-*/
-
-bool QDirModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int /* row */, int /* column */, const QModelIndex &parent)
-{
- Q_D(QDirModel);
- if (!d->indexValid(parent) || isReadOnly())
- return false;
-
- bool success = true;
- QString to = filePath(parent) + QDir::separator();
- QModelIndex _parent = parent;
-
- QList<QUrl> urls = data->urls();
- QList<QUrl>::const_iterator it = urls.constBegin();
-
- switch (action) {
- case Qt::CopyAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::copy(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::LinkAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- success = QFile::link(path, to + QFileInfo(path).fileName()) && success;
- }
- break;
- case Qt::MoveAction:
- for (; it != urls.constEnd(); ++it) {
- QString path = (*it).toLocalFile();
- if (QFile::copy(path, to + QFileInfo(path).fileName())
- && QFile::remove(path)) {
- QModelIndex idx=index(QFileInfo(path).path());
- if (idx.isValid()) {
- refresh(idx);
- //the previous call to refresh may invalidate the _parent. so recreate a new QModelIndex
- _parent = index(to);
- }
- } else {
- success = false;
- }
- }
- break;
- default:
- return false;
- }
-
- if (success)
- refresh(_parent);
-
- return success;
-}
-
-/*!
- Returns the drop actions supported by this model.
-
- \sa Qt::DropActions
-*/
-
-Qt::DropActions QDirModel::supportedDropActions() const
-{
- return Qt::CopyAction | Qt::MoveAction; // FIXME: LinkAction is not supported yet
-}
-
-/*!
- Sets the \a provider of file icons for the directory model.
-
-*/
-
-void QDirModel::setIconProvider(QFileIconProvider *provider)
-{
- Q_D(QDirModel);
- d->iconProvider = provider;
-}
-
-/*!
- Returns the file icon provider for this directory model.
-*/
-
-QFileIconProvider *QDirModel::iconProvider() const
-{
- Q_D(const QDirModel);
- return d->iconProvider;
-}
-
-/*!
- Sets the name \a filters for the directory model.
-*/
-
-void QDirModel::setNameFilters(const QStringList &filters)
-{
- Q_D(QDirModel);
- d->nameFilters = filters;
- emit layoutAboutToBeChanged();
- if (d->shouldStat)
- refresh(QModelIndex());
- else
- d->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Returns a list of filters applied to the names in the model.
-*/
-
-QStringList QDirModel::nameFilters() const
-{
- Q_D(const QDirModel);
- return d->nameFilters;
-}
-
-/*!
- Sets the directory model's filter to that specified by \a filters.
-
- Note that the filter you set should always include the QDir::AllDirs enum value,
- otherwise QDirModel won't be able to read the directory structure.
-
- \sa QDir::Filters
-*/
-
-void QDirModel::setFilter(QDir::Filters filters)
-{
- Q_D(QDirModel);
- d->filters = filters;
- emit layoutAboutToBeChanged();
- if (d->shouldStat)
- refresh(QModelIndex());
- else
- d->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Returns the filter specification for the directory model.
-
- \sa QDir::Filters
-*/
-
-QDir::Filters QDirModel::filter() const
-{
- Q_D(const QDirModel);
- return d->filters;
-}
-
-/*!
- Sets the directory model's sorting order to that specified by \a sort.
-
- \sa QDir::SortFlags
-*/
-
-void QDirModel::setSorting(QDir::SortFlags sort)
-{
- Q_D(QDirModel);
- d->sort = sort;
- emit layoutAboutToBeChanged();
- if (d->shouldStat)
- refresh(QModelIndex());
- else
- d->invalidate();
- emit layoutChanged();
-}
-
-/*!
- Returns the sorting method used for the directory model.
-
- \sa QDir::SortFlags */
-
-QDir::SortFlags QDirModel::sorting() const
-{
- Q_D(const QDirModel);
- return d->sort;
-}
-
-/*!
- \property QDirModel::resolveSymlinks
- \brief Whether the directory model should resolve symbolic links
-
- This is only relevant on operating systems that support symbolic
- links.
-*/
-void QDirModel::setResolveSymlinks(bool enable)
-{
- Q_D(QDirModel);
- d->resolveSymlinks = enable;
-}
-
-bool QDirModel::resolveSymlinks() const
-{
- Q_D(const QDirModel);
- return d->resolveSymlinks;
-}
-
-/*!
- \property QDirModel::readOnly
- \brief Whether the directory model allows writing to the file system
-
- If this property is set to false, the directory model will allow renaming, copying
- and deleting of files and directories.
-
- This property is true by default
-*/
-
-void QDirModel::setReadOnly(bool enable)
-{
- Q_D(QDirModel);
- d->readOnly = enable;
-}
-
-bool QDirModel::isReadOnly() const
-{
- Q_D(const QDirModel);
- return d->readOnly;
-}
-
-/*!
- \property QDirModel::lazyChildCount
- \brief Whether the directory model optimizes the hasChildren function
- to only check if the item is a directory.
-
- If this property is set to false, the directory model will make sure that a directory
- actually containes any files before reporting that it has children.
- Otherwise the directory model will report that an item has children if the item
- is a directory.
-
- This property is false by default
-*/
-
-void QDirModel::setLazyChildCount(bool enable)
-{
- Q_D(QDirModel);
- d->lazyChildCount = enable;
-}
-
-bool QDirModel::lazyChildCount() const
-{
- Q_D(const QDirModel);
- return d->lazyChildCount;
-}
-
-/*!
- QDirModel caches file information. This function updates the
- cache. The \a parent parameter is the directory from which the
- model is updated; the default value will update the model from
- root directory of the file system (the entire model).
-*/
-
-void QDirModel::refresh(const QModelIndex &parent)
-{
- Q_D(QDirModel);
-
- QDirModelPrivate::QDirNode *n = d->indexValid(parent) ? d->node(parent) : &(d->root);
-
- int rows = n->children.count();
- if (rows == 0) {
- emit layoutAboutToBeChanged();
- n->stat = true; // make sure that next time we read all the info
- n->populated = false;
- emit layoutChanged();
- return;
- }
-
- emit layoutAboutToBeChanged();
- d->savePersistentIndexes();
- d->rowsAboutToBeRemoved(parent, 0, rows - 1);
- n->stat = true; // make sure that next time we read all the info
- d->clear(n);
- d->rowsRemoved(parent, 0, rows - 1);
- d->restorePersistentIndexes();
- emit layoutChanged();
-}
-
-/*!
- \overload
-
- Returns the model item index for the given \a path.
-*/
-
-QModelIndex QDirModel::index(const QString &path, int column) const
-{
- Q_D(const QDirModel);
-
- if (path.isEmpty() || path == QCoreApplication::translate("QFileDialog", "My Computer"))
- return QModelIndex();
-
- QString absolutePath = QDir(path).absolutePath();
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- absolutePath = absolutePath.toLower();
-#endif
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- // On Windows, "filename......." and "filename" are equivalent
- if (absolutePath.endsWith(QLatin1Char('.'))) {
- int i;
- for (i = absolutePath.count() - 1; i >= 0; --i) {
- if (absolutePath.at(i) != QLatin1Char('.'))
- break;
- }
- absolutePath = absolutePath.left(i+1);
- }
-#endif
-
- QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
- if ((pathElements.isEmpty() || !QFileInfo(path).exists())
-#if !defined(Q_OS_WIN) || defined(Q_OS_WINCE)
- && path != QLatin1String("/")
-#endif
- )
- return QModelIndex();
-
- QModelIndex idx; // start with "My Computer"
- if (!d->root.populated) // make sure the root is populated
- d->populate(&d->root);
-
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (absolutePath.startsWith(QLatin1String("//"))) { // UNC path
- QString host = pathElements.first();
- int r = 0;
- for (; r < d->root.children.count(); ++r)
- if (d->root.children.at(r).info.fileName() == host)
- break;
- bool childAppended = false;
- if (r >= d->root.children.count() && d->allowAppendChild) {
- d->appendChild(&d->root, QLatin1String("//") + host);
- childAppended = true;
- }
- idx = index(r, 0, QModelIndex());
- pathElements.pop_front();
- if (childAppended)
- emit const_cast<QDirModel*>(this)->layoutChanged();
- } else
-#endif
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- if (pathElements.at(0).endsWith(QLatin1Char(':'))) {
- pathElements[0] += QLatin1Char('/');
- }
-#else
- // add the "/" item, since it is a valid path element on unix
- pathElements.prepend(QLatin1String("/"));
-#endif
-
- for (int i = 0; i < pathElements.count(); ++i) {
- Q_ASSERT(!pathElements.at(i).isEmpty());
- QString element = pathElements.at(i);
- QDirModelPrivate::QDirNode *parent = (idx.isValid() ? d->node(idx) : &d->root);
-
- Q_ASSERT(parent);
- if (!parent->populated)
- d->populate(parent);
-
- // search for the element in the child nodes first
- int row = -1;
- for (int j = parent->children.count() - 1; j >= 0; --j) {
- const QFileInfo& fi = parent->children.at(j).info;
- QString childFileName;
- childFileName = idx.isValid() ? fi.fileName() : fi.absoluteFilePath();
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- childFileName = childFileName.toLower();
-#endif
- if (childFileName == element) {
- if (i == pathElements.count() - 1)
- parent->children[j].stat = true;
- row = j;
- break;
- }
- }
-
- // we couldn't find the path element, we create a new node since we _know_ that the path is valid
- if (row == -1) {
-#if defined(Q_OS_WINCE)
- QString newPath;
- if (parent->info.isRoot())
- newPath = parent->info.absoluteFilePath() + element;
- else
- newPath = parent->info.absoluteFilePath() + QLatin1Char('/') + element;
-#else
- QString newPath = parent->info.absoluteFilePath() + QLatin1Char('/') + element;
-#endif
- if (!d->allowAppendChild || !QFileInfo(newPath).isDir())
- return QModelIndex();
- d->appendChild(parent, newPath);
- row = parent->children.count() - 1;
- if (i == pathElements.count() - 1) // always stat children of the last element
- parent->children[row].stat = true;
- emit const_cast<QDirModel*>(this)->layoutChanged();
- }
-
- Q_ASSERT(row >= 0);
- idx = createIndex(row, 0, static_cast<void*>(&parent->children[row]));
- Q_ASSERT(idx.isValid());
- }
-
- if (column != 0)
- return idx.sibling(idx.row(), column);
- return idx;
-}
-
-/*!
- Returns true if the model item \a index represents a directory;
- otherwise returns false.
-*/
-
-bool QDirModel::isDir(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- Q_ASSERT(d->indexValid(index));
- QDirModelPrivate::QDirNode *node = d->node(index);
- return node->info.isDir();
-}
-
-/*!
- Create a directory with the \a name in the \a parent model item.
-*/
-
-QModelIndex QDirModel::mkdir(const QModelIndex &parent, const QString &name)
-{
- Q_D(QDirModel);
- if (!d->indexValid(parent) || isReadOnly())
- return QModelIndex();
-
- QDirModelPrivate::QDirNode *p = d->node(parent);
- QString path = p->info.absoluteFilePath();
- // For the indexOf() method to work, the new directory has to be a direct child of
- // the parent directory.
-
- QDir newDir(name);
- QDir dir(path);
- if (newDir.isRelative())
- newDir = QDir(path + QLatin1Char('/') + name);
- QString childName = newDir.dirName(); // Get the singular name of the directory
- newDir.cdUp();
-
- if (newDir.absolutePath() != dir.absolutePath() || !dir.mkdir(name))
- return QModelIndex(); // nothing happened
-
- refresh(parent);
-
- QStringList entryList = d->entryList(path);
- int r = entryList.indexOf(childName);
- QModelIndex i = index(r, 0, parent); // return an invalid index
-
- return i;
-}
-
-/*!
- Removes the directory corresponding to the model item \a index in the
- directory model and \bold{deletes the corresponding directory from the
- file system}, returning true if successful. If the directory cannot be
- removed, false is returned.
-
- \warning This function deletes directories from the file system; it does
- \bold{not} move them to a location where they can be recovered.
-
- \sa remove()
-*/
-
-bool QDirModel::rmdir(const QModelIndex &index)
-{
- Q_D(QDirModel);
- if (!d->indexValid(index) || isReadOnly())
- return false;
-
- QDirModelPrivate::QDirNode *n = d_func()->node(index);
- if (!n->info.isDir()) {
- qWarning("rmdir: the node is not a directory");
- return false;
- }
-
- QModelIndex par = parent(index);
- QDirModelPrivate::QDirNode *p = d_func()->node(par);
- QDir dir = p->info.dir(); // parent dir
- QString path = n->info.absoluteFilePath();
- if (!dir.rmdir(path))
- return false;
-
- refresh(par);
-
- return true;
-}
-
-/*!
- Removes the model item \a index from the directory model and \bold{deletes the
- corresponding file from the file system}, returning true if successful. If the
- item cannot be removed, false is returned.
-
- \warning This function deletes files from the file system; it does \bold{not}
- move them to a location where they can be recovered.
-
- \sa rmdir()
-*/
-
-bool QDirModel::remove(const QModelIndex &index)
-{
- Q_D(QDirModel);
- if (!d->indexValid(index) || isReadOnly())
- return false;
-
- QDirModelPrivate::QDirNode *n = d_func()->node(index);
- if (n->info.isDir())
- return false;
-
- QModelIndex par = parent(index);
- QDirModelPrivate::QDirNode *p = d_func()->node(par);
- QDir dir = p->info.dir(); // parent dir
- QString path = n->info.absoluteFilePath();
- if (!dir.remove(path))
- return false;
-
- refresh(par);
-
- return true;
-}
-
-/*!
- Returns the path of the item stored in the model under the
- \a index given.
-
-*/
-
-QString QDirModel::filePath(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- if (d->indexValid(index)) {
- QFileInfo fi = fileInfo(index);
- if (d->resolveSymlinks && fi.isSymLink())
- fi = d->resolvedInfo(fi);
- return QDir::cleanPath(fi.absoluteFilePath());
- }
- return QString(); // root path
-}
-
-/*!
- Returns the name of the item stored in the model under the
- \a index given.
-
-*/
-
-QString QDirModel::fileName(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- if (!d->indexValid(index))
- return QString();
- QFileInfo info = fileInfo(index);
- if (info.isRoot())
- return info.absoluteFilePath();
- if (d->resolveSymlinks && info.isSymLink())
- info = d->resolvedInfo(info);
- return info.fileName();
-}
-
-/*!
- Returns the icons for the item stored in the model under the given
- \a index.
-*/
-
-QIcon QDirModel::fileIcon(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- if (!d->indexValid(index))
- return d->iconProvider->icon(QFileIconProvider::Computer);
- QDirModelPrivate::QDirNode *node = d->node(index);
- if (node->icon.isNull())
- node->icon = d->iconProvider->icon(node->info);
- return node->icon;
-}
-
-/*!
- Returns the file information for the specified model \a index.
-
- \bold{Note:} If the model index represents a symbolic link in the
- underlying filing system, the file information returned will contain
- information about the symbolic link itself, regardless of whether
- resolveSymlinks is enabled or not.
-
- \sa QFileInfo::symLinkTarget()
-*/
-
-QFileInfo QDirModel::fileInfo(const QModelIndex &index) const
-{
- Q_D(const QDirModel);
- Q_ASSERT(d->indexValid(index));
-
- QDirModelPrivate::QDirNode *node = d->node(index);
- return node->info;
-}
-
-/*!
- \fn QObject *QDirModel::parent() const
- \internal
-*/
-
-/*
- The root node is never seen outside the model.
-*/
-
-void QDirModelPrivate::init()
-{
- Q_Q(QDirModel);
- filters = QDir::AllEntries | QDir::NoDotAndDotDot;
- sort = QDir::Name;
- nameFilters << QLatin1String("*");
- root.parent = 0;
- root.info = QFileInfo();
- clear(&root);
- QHash<int, QByteArray> roles = q->roleNames();
- roles.insertMulti(QDirModel::FileIconRole, "fileIcon"); // == Qt::decoration
- roles.insert(QDirModel::FilePathRole, "filePath");
- roles.insert(QDirModel::FileNameRole, "fileName");
- q->setRoleNames(roles);
-}
-
-QDirModelPrivate::QDirNode *QDirModelPrivate::node(int row, QDirNode *parent) const
-{
- if (row < 0)
- return 0;
-
- bool isDir = !parent || parent->info.isDir();
- QDirNode *p = (parent ? parent : &root);
- if (isDir && !p->populated)
- populate(p); // will also resolve symlinks
-
- if (row >= p->children.count()) {
- qWarning("node: the row does not exist");
- return 0;
- }
-
- return const_cast<QDirNode*>(&p->children.at(row));
-}
-
-QVector<QDirModelPrivate::QDirNode> QDirModelPrivate::children(QDirNode *parent, bool stat) const
-{
- Q_ASSERT(parent);
- QFileInfoList infoList;
- if (parent == &root) {
- parent = 0;
- infoList = QDir::drives();
- } else if (parent->info.isDir()) {
- //resolve directory links only if requested.
- if (parent->info.isSymLink() && resolveSymlinks) {
- QString link = parent->info.symLinkTarget();
- if (link.size() > 1 && link.at(link.size() - 1) == QDir::separator())
- link.chop(1);
- if (stat)
- infoList = entryInfoList(link);
- else
- infoList = QDir(link).entryInfoList(nameFilters, QDir::AllEntries | QDir::System);
- } else {
- if (stat)
- infoList = entryInfoList(parent->info.absoluteFilePath());
- else
- infoList = QDir(parent->info.absoluteFilePath()).entryInfoList(nameFilters, QDir::AllEntries | QDir::System);
- }
- }
-
- QVector<QDirNode> nodes(infoList.count());
- for (int i = 0; i < infoList.count(); ++i) {
- QDirNode &node = nodes[i];
- node.parent = parent;
- node.info = infoList.at(i);
- node.populated = false;
- node.stat = shouldStat;
- }
-
- return nodes;
-}
-
-void QDirModelPrivate::_q_refresh()
-{
- Q_Q(QDirModel);
- q->refresh(toBeRefreshed);
- toBeRefreshed = QModelIndex();
-}
-
-void QDirModelPrivate::savePersistentIndexes()
-{
- Q_Q(QDirModel);
- savedPersistent.clear();
- foreach (QPersistentModelIndexData *data, persistent.indexes) {
- SavedPersistent saved;
- QModelIndex index = data->index;
- saved.path = q->filePath(index);
- saved.column = index.column();
- saved.data = data;
- saved.index = index;
- savedPersistent.append(saved);
- }
-}
-
-void QDirModelPrivate::restorePersistentIndexes()
-{
- Q_Q(QDirModel);
- bool allow = allowAppendChild;
- allowAppendChild = false;
- for (int i = 0; i < savedPersistent.count(); ++i) {
- QPersistentModelIndexData *data = savedPersistent.at(i).data;
- QString path = savedPersistent.at(i).path;
- int column = savedPersistent.at(i).column;
- QModelIndex idx = q->index(path, column);
- if (idx != data->index || data->model == 0) {
- //data->model may be equal to 0 if the model is getting destroyed
- persistent.indexes.remove(data->index);
- data->index = idx;
- data->model = q;
- if (idx.isValid())
- persistent.indexes.insert(idx, data);
- }
- }
- savedPersistent.clear();
- allowAppendChild = allow;
-}
-
-QFileInfoList QDirModelPrivate::entryInfoList(const QString &path) const
-{
- const QDir dir(path);
- return dir.entryInfoList(nameFilters, filters, sort);
-}
-
-QStringList QDirModelPrivate::entryList(const QString &path) const
-{
- const QDir dir(path);
- return dir.entryList(nameFilters, filters, sort);
-}
-
-QString QDirModelPrivate::name(const QModelIndex &index) const
-{
- const QDirNode *n = node(index);
- const QFileInfo info = n->info;
- if (info.isRoot()) {
- QString name = info.absoluteFilePath();
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (name.startsWith(QLatin1Char('/'))) // UNC host
- return info.fileName();
-#endif
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- if (name.endsWith(QLatin1Char('/')))
- name.chop(1);
-#endif
- return name;
- }
- return info.fileName();
-}
-
-QString QDirModelPrivate::size(const QModelIndex &index) const
-{
- const QDirNode *n = node(index);
- if (n->info.isDir()) {
-#ifdef Q_OS_MAC
- return QLatin1String("--");
-#else
- return QLatin1String("");
-#endif
- // Windows - ""
- // OS X - "--"
- // Konqueror - "4 KB"
- // Nautilus - "9 items" (the number of children)
- }
-
- // According to the Si standard KB is 1000 bytes, KiB is 1024
- // but on windows sizes are calulated by dividing by 1024 so we do what they do.
- const quint64 kb = 1024;
- const quint64 mb = 1024 * kb;
- const quint64 gb = 1024 * mb;
- const quint64 tb = 1024 * gb;
- quint64 bytes = n->info.size();
- if (bytes >= tb)
- return QFileSystemModel::tr("%1 TB").arg(QLocale().toString(qreal(bytes) / tb, 'f', 3));
- if (bytes >= gb)
- return QFileSystemModel::tr("%1 GB").arg(QLocale().toString(qreal(bytes) / gb, 'f', 2));
- if (bytes >= mb)
- return QFileSystemModel::tr("%1 MB").arg(QLocale().toString(qreal(bytes) / mb, 'f', 1));
- if (bytes >= kb)
- return QFileSystemModel::tr("%1 KB").arg(QLocale().toString(bytes / kb));
- return QFileSystemModel::tr("%1 byte(s)").arg(QLocale().toString(bytes));
-}
-
-QString QDirModelPrivate::type(const QModelIndex &index) const
-{
- return iconProvider->type(node(index)->info);
-}
-
-QString QDirModelPrivate::time(const QModelIndex &index) const
-{
-#ifndef QT_NO_DATESTRING
- return node(index)->info.lastModified().toString(Qt::LocalDate);
-#else
- Q_UNUSED(index);
- return QString();
-#endif
-}
-
-void QDirModelPrivate::appendChild(QDirModelPrivate::QDirNode *parent, const QString &path) const
-{
- QDirModelPrivate::QDirNode node;
- node.populated = false;
- node.stat = shouldStat;
- node.parent = (parent == &root ? 0 : parent);
- node.info = QFileInfo(path);
- node.info.setCaching(true);
-
- // The following append(node) may reallocate the vector, thus
- // we need to update the pointers to the childnodes parent.
- QDirModelPrivate *that = const_cast<QDirModelPrivate *>(this);
- that->savePersistentIndexes();
- parent->children.append(node);
- for (int i = 0; i < parent->children.count(); ++i) {
- QDirNode *childNode = &parent->children[i];
- for (int j = 0; j < childNode->children.count(); ++j)
- childNode->children[j].parent = childNode;
- }
- that->restorePersistentIndexes();
-}
-
-QFileInfo QDirModelPrivate::resolvedInfo(QFileInfo info)
-{
-#ifdef Q_OS_WIN
- // On windows, we cannot create a shortcut to a shortcut.
- return QFileInfo(info.symLinkTarget());
-#else
- QStringList paths;
- do {
- QFileInfo link(info.symLinkTarget());
- if (link.isRelative())
- info.setFile(info.absolutePath(), link.filePath());
- else
- info = link;
- if (paths.contains(info.absoluteFilePath()))
- return QFileInfo();
- paths.append(info.absoluteFilePath());
- } while (info.isSymLink());
- return info;
-#endif
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qdirmodel.cpp"
-
-#endif // QT_NO_DIRMODEL
diff --git a/src/gui/itemviews/qdirmodel.h b/src/gui/itemviews/qdirmodel.h
deleted file mode 100644
index 2b1cd9d81b..0000000000
--- a/src/gui/itemviews/qdirmodel.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/****************************************************************************
-**
-** 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 QDIRMODEL_H
-#define QDIRMODEL_H
-
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qdir.h>
-#include <QtGui/qfileiconprovider.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_DIRMODEL
-
-class QDirModelPrivate;
-
-class Q_GUI_EXPORT QDirModel : public QAbstractItemModel
-{
- Q_OBJECT
- Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(bool lazyChildCount READ lazyChildCount WRITE setLazyChildCount)
-
-public:
- enum Roles {
- FileIconRole = Qt::DecorationRole,
- FilePathRole = Qt::UserRole + 1,
- FileNameRole
- };
-
- QDirModel(const QStringList &nameFilters, QDir::Filters filters,
- QDir::SortFlags sort, QObject *parent = 0);
- explicit QDirModel(QObject *parent = 0);
- ~QDirModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex &child) const;
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
-
- bool hasChildren(const QModelIndex &index = QModelIndex()) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
- Qt::DropActions supportedDropActions() const;
-
- // QDirModel specific API
-
- void setIconProvider(QFileIconProvider *provider);
- QFileIconProvider *iconProvider() const;
-
- void setNameFilters(const QStringList &filters);
- QStringList nameFilters() const;
-
- void setFilter(QDir::Filters filters);
- QDir::Filters filter() const;
-
- void setSorting(QDir::SortFlags sort);
- QDir::SortFlags sorting() const;
-
- void setResolveSymlinks(bool enable);
- bool resolveSymlinks() const;
-
- void setReadOnly(bool enable);
- bool isReadOnly() const;
-
- void setLazyChildCount(bool enable);
- bool lazyChildCount() const;
-
- QModelIndex index(const QString &path, int column = 0) const;
-
- bool isDir(const QModelIndex &index) const;
- QModelIndex mkdir(const QModelIndex &parent, const QString &name);
- bool rmdir(const QModelIndex &index);
- bool remove(const QModelIndex &index);
-
- QString filePath(const QModelIndex &index) const;
- QString fileName(const QModelIndex &index) const;
- QIcon fileIcon(const QModelIndex &index) const;
- QFileInfo fileInfo(const QModelIndex &index) const;
-
-#ifdef Q_NO_USING_KEYWORD
- inline QObject *parent() const { return QObject::parent(); }
-#else
- using QObject::parent;
-#endif
-
-public Q_SLOTS:
- void refresh(const QModelIndex &parent = QModelIndex());
-
-protected:
- QDirModel(QDirModelPrivate &, QObject *parent = 0);
- friend class QFileDialogPrivate;
-
-private:
- Q_DECLARE_PRIVATE(QDirModel)
- Q_DISABLE_COPY(QDirModel)
- Q_PRIVATE_SLOT(d_func(), void _q_refresh())
-};
-
-#endif // QT_NO_DIRMODEL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDIRMODEL_H
diff --git a/src/gui/itemviews/qfileiconprovider.cpp b/src/gui/itemviews/qfileiconprovider.cpp
deleted file mode 100644
index ae93054cf3..0000000000
--- a/src/gui/itemviews/qfileiconprovider.cpp
+++ /dev/null
@@ -1,509 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfileiconprovider.h"
-
-#ifndef QT_NO_FILEICONPROVIDER
-#include <qstyle.h>
-#include <qapplication.h>
-#include <qdir.h>
-#include <qpixmapcache.h>
-#if defined(Q_WS_WIN)
-# define _WIN32_IE 0x0500
-# include <qt_windows.h>
-# include <commctrl.h>
-# include <objbase.h>
-#elif defined(Q_WS_MAC)
-# include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#include <private/qfunctions_p.h>
-#include <private/qguiplatformplugin_p.h>
-
-#if defined(Q_WS_X11) && !defined(Q_NO_STYLE_GTK)
-# include <private/qgtkstyle_p.h>
-# include <private/qt_x11_p.h>
-#endif
-
-#ifndef SHGFI_ADDOVERLAYS
-# define SHGFI_ADDOVERLAYS 0x000000020
-# define SHGFI_OVERLAYINDEX 0x000000040
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QFileIconProvider
-
- \brief The QFileIconProvider class provides file icons for the QDirModel and the QFileSystemModel classes.
-*/
-
-/*!
- \enum QFileIconProvider::IconType
- \value Computer
- \value Desktop
- \value Trashcan
- \value Network
- \value Drive
- \value Folder
- \value File
-*/
-
-class QFileIconProviderPrivate
-{
- Q_DECLARE_PUBLIC(QFileIconProvider)
-
-public:
- QFileIconProviderPrivate();
- QIcon getIcon(QStyle::StandardPixmap name) const;
-#ifdef Q_WS_WIN
- QIcon getWinIcon(const QFileInfo &fi) const;
-#elif defined(Q_WS_MAC)
- QIcon getMacIcon(const QFileInfo &fi) const;
-#endif
- QFileIconProvider *q_ptr;
- const QString homePath;
-
-private:
- mutable QIcon file;
- mutable QIcon fileLink;
- mutable QIcon directory;
- mutable QIcon directoryLink;
- mutable QIcon harddisk;
- mutable QIcon floppy;
- mutable QIcon cdrom;
- mutable QIcon ram;
- mutable QIcon network;
- mutable QIcon computer;
- mutable QIcon desktop;
- mutable QIcon trashcan;
- mutable QIcon generic;
- mutable QIcon home;
-};
-
-QFileIconProviderPrivate::QFileIconProviderPrivate() :
- homePath(QDir::home().absolutePath())
-{
-}
-
-QIcon QFileIconProviderPrivate::getIcon(QStyle::StandardPixmap name) const
-{
- switch (name) {
- case QStyle::SP_FileIcon:
- if (file.isNull())
- file = QApplication::style()->standardIcon(name);
- return file;
- case QStyle::SP_FileLinkIcon:
- if (fileLink.isNull())
- fileLink = QApplication::style()->standardIcon(name);
- return fileLink;
- case QStyle::SP_DirIcon:
- if (directory.isNull())
- directory = QApplication::style()->standardIcon(name);
- return directory;
- case QStyle::SP_DirLinkIcon:
- if (directoryLink.isNull())
- directoryLink = QApplication::style()->standardIcon(name);
- return directoryLink;
- case QStyle::SP_DriveHDIcon:
- if (harddisk.isNull())
- harddisk = QApplication::style()->standardIcon(name);
- return harddisk;
- case QStyle::SP_DriveFDIcon:
- if (floppy.isNull())
- floppy = QApplication::style()->standardIcon(name);
- return floppy;
- case QStyle::SP_DriveCDIcon:
- if (cdrom.isNull())
- cdrom = QApplication::style()->standardIcon(name);
- return cdrom;
- case QStyle::SP_DriveNetIcon:
- if (network.isNull())
- network = QApplication::style()->standardIcon(name);
- return network;
- case QStyle::SP_ComputerIcon:
- if (computer.isNull())
- computer = QApplication::style()->standardIcon(name);
- return computer;
- case QStyle::SP_DesktopIcon:
- if (desktop.isNull())
- desktop = QApplication::style()->standardIcon(name);
- return desktop;
- case QStyle::SP_TrashIcon:
- if (trashcan.isNull())
- trashcan = QApplication::style()->standardIcon(name);
- return trashcan;
- case QStyle::SP_DirHomeIcon:
- if (home.isNull())
- home = QApplication::style()->standardIcon(name);
- return home;
- default:
- return QIcon();
- }
- return QIcon();
-}
-
-/*!
- Constructs a file icon provider.
-*/
-
-QFileIconProvider::QFileIconProvider()
- : d_ptr(new QFileIconProviderPrivate)
-{
-}
-
-/*!
- Destroys the file icon provider.
-
-*/
-
-QFileIconProvider::~QFileIconProvider()
-{
-}
-
-/*!
- Returns an icon set for the given \a type.
-*/
-
-QIcon QFileIconProvider::icon(IconType type) const
-{
- Q_D(const QFileIconProvider);
- switch (type) {
- case Computer:
- return d->getIcon(QStyle::SP_ComputerIcon);
- case Desktop:
- return d->getIcon(QStyle::SP_DesktopIcon);
- case Trashcan:
- return d->getIcon(QStyle::SP_TrashIcon);
- case Network:
- return d->getIcon(QStyle::SP_DriveNetIcon);
- case Drive:
- return d->getIcon(QStyle::SP_DriveHDIcon);
- case Folder:
- return d->getIcon(QStyle::SP_DirIcon);
- case File:
- return d->getIcon(QStyle::SP_FileIcon);
- default:
- break;
- };
- return QIcon();
-}
-
-#ifdef Q_WS_WIN
-QIcon QFileIconProviderPrivate::getWinIcon(const QFileInfo &fileInfo) const
-{
- QIcon retIcon;
- const QString fileExtension = QLatin1Char('.') + fileInfo.suffix().toUpper();
-
- QString key;
- if (fileInfo.isFile() && !fileInfo.isExecutable() && !fileInfo.isSymLink() && fileExtension != QLatin1String(".ICO"))
- key = QLatin1String("qt_") + fileExtension;
-
- QPixmap pixmap;
- if (!key.isEmpty()) {
- QPixmapCache::find(key, pixmap);
- }
-
- if (!pixmap.isNull()) {
- retIcon.addPixmap(pixmap);
- if (QPixmapCache::find(key + QLatin1Char('l'), pixmap))
- retIcon.addPixmap(pixmap);
- return retIcon;
- }
-
- /* We don't use the variable, but by storing it statically, we
- * ensure CoInitialize is only called once. */
- static HRESULT comInit = CoInitialize(NULL);
- Q_UNUSED(comInit);
-
- SHFILEINFO info;
- unsigned long val = 0;
-
- //Get the small icon
-#ifndef Q_OS_WINCE
- val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info,
- sizeof(SHFILEINFO), SHGFI_ICON|SHGFI_SMALLICON|SHGFI_SYSICONINDEX|SHGFI_ADDOVERLAYS|SHGFI_OVERLAYINDEX);
-#else
- val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info,
- sizeof(SHFILEINFO), SHGFI_SMALLICON|SHGFI_SYSICONINDEX);
-#endif
-
- // Even if GetFileInfo returns a valid result, hIcon can be empty in some cases
- if (val && info.hIcon) {
- if (fileInfo.isDir() && !fileInfo.isRoot()) {
- //using the unique icon index provided by windows save us from duplicate keys
- key = QString::fromLatin1("qt_dir_%1").arg(info.iIcon);
- QPixmapCache::find(key, pixmap);
- if (!pixmap.isNull()) {
- retIcon.addPixmap(pixmap);
- if (QPixmapCache::find(key + QLatin1Char('l'), pixmap))
- retIcon.addPixmap(pixmap);
- DestroyIcon(info.hIcon);
- return retIcon;
- }
- }
- if (pixmap.isNull()) {
-#ifndef Q_OS_WINCE
- pixmap = QPixmap::fromWinHICON(info.hIcon);
-#else
- pixmap = QPixmap::fromWinHICON(ImageList_GetIcon((HIMAGELIST) val, info.iIcon, ILD_NORMAL));
-#endif
- if (!pixmap.isNull()) {
- retIcon.addPixmap(pixmap);
- if (!key.isEmpty())
- QPixmapCache::insert(key, pixmap);
- }
- else {
- qWarning("QFileIconProviderPrivate::getWinIcon() no small icon found");
- }
- }
- DestroyIcon(info.hIcon);
- }
-
- //Get the big icon
-#ifndef Q_OS_WINCE
- val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info,
- sizeof(SHFILEINFO), SHGFI_ICON|SHGFI_LARGEICON|SHGFI_SYSICONINDEX|SHGFI_ADDOVERLAYS|SHGFI_OVERLAYINDEX);
-#else
- val = SHGetFileInfo((const wchar_t *)QDir::toNativeSeparators(fileInfo.filePath()).utf16(), 0, &info,
- sizeof(SHFILEINFO), SHGFI_LARGEICON|SHGFI_SYSICONINDEX);
-#endif
- if (val && info.hIcon) {
- if (fileInfo.isDir() && !fileInfo.isRoot()) {
- //using the unique icon index provided by windows save us from duplicate keys
- key = QString::fromLatin1("qt_dir_%1").arg(info.iIcon);
- }
-#ifndef Q_OS_WINCE
- pixmap = QPixmap::fromWinHICON(info.hIcon);
-#else
- pixmap = QPixmap::fromWinHICON(ImageList_GetIcon((HIMAGELIST) val, info.iIcon, ILD_NORMAL));
-#endif
- if (!pixmap.isNull()) {
- retIcon.addPixmap(pixmap);
- if (!key.isEmpty())
- QPixmapCache::insert(key + QLatin1Char('l'), pixmap);
- }
- else {
- qWarning("QFileIconProviderPrivate::getWinIcon() no large icon found");
- }
- DestroyIcon(info.hIcon);
- }
- return retIcon;
-}
-
-#elif defined(Q_WS_MAC)
-QIcon QFileIconProviderPrivate::getMacIcon(const QFileInfo &fi) const
-{
- QIcon retIcon;
- QString fileExtension = fi.suffix().toUpper();
- fileExtension.prepend(QLatin1String("."));
-
- const QString keyBase = QLatin1String("qt_") + fileExtension;
-
- QPixmap pixmap;
- if (fi.isFile() && !fi.isExecutable() && !fi.isSymLink()) {
- QPixmapCache::find(keyBase + QLatin1String("16"), pixmap);
- }
-
- if (!pixmap.isNull()) {
- retIcon.addPixmap(pixmap);
- if (QPixmapCache::find(keyBase + QLatin1String("32"), pixmap)) {
- retIcon.addPixmap(pixmap);
- if (QPixmapCache::find(keyBase + QLatin1String("64"), pixmap)) {
- retIcon.addPixmap(pixmap);
- if (QPixmapCache::find(keyBase + QLatin1String("128"), pixmap)) {
- retIcon.addPixmap(pixmap);
- return retIcon;
- }
- }
- }
- }
-
-
- FSRef macRef;
- OSStatus status = FSPathMakeRef(reinterpret_cast<const UInt8*>(fi.canonicalFilePath().toUtf8().constData()),
- &macRef, 0);
- if (status != noErr)
- return retIcon;
- FSCatalogInfo info;
- HFSUniStr255 macName;
- status = FSGetCatalogInfo(&macRef, kIconServicesCatalogInfoMask, &info, &macName, 0, 0);
- if (status != noErr)
- return retIcon;
- IconRef iconRef;
- SInt16 iconLabel;
- status = GetIconRefFromFileInfo(&macRef, macName.length, macName.unicode,
- kIconServicesCatalogInfoMask, &info, kIconServicesNormalUsageFlag,
- &iconRef, &iconLabel);
- if (status != noErr)
- return retIcon;
- qt_mac_constructQIconFromIconRef(iconRef, 0, &retIcon);
- ReleaseIconRef(iconRef);
-
- pixmap = retIcon.pixmap(16);
- QPixmapCache::insert(keyBase + QLatin1String("16"), pixmap);
- pixmap = retIcon.pixmap(32);
- QPixmapCache::insert(keyBase + QLatin1String("32"), pixmap);
- pixmap = retIcon.pixmap(64);
- QPixmapCache::insert(keyBase + QLatin1String("64"), pixmap);
- pixmap = retIcon.pixmap(128);
- QPixmapCache::insert(keyBase + QLatin1String("128"), pixmap);
-
- return retIcon;
-}
-#endif
-
-
-/*!
- Returns an icon for the file described by \a info.
-*/
-
-QIcon QFileIconProvider::icon(const QFileInfo &info) const
-{
- Q_D(const QFileIconProvider);
-
- QIcon platformIcon = qt_guiPlatformPlugin()->fileSystemIcon(info);
- if (!platformIcon.isNull())
- return platformIcon;
-
-#if defined(Q_WS_X11) && !defined(QT_NO_STYLE_GTK)
- if (X11->desktopEnvironment == DE_GNOME) {
- QIcon gtkIcon = QGtkStylePrivate::getFilesystemIcon(info);
- if (!gtkIcon.isNull())
- return gtkIcon;
- }
-#endif
-
-#ifdef Q_WS_MAC
- QIcon retIcon = d->getMacIcon(info);
- if (!retIcon.isNull())
- return retIcon;
-#elif defined Q_WS_WIN
- QIcon icon = d->getWinIcon(info);
- if (!icon.isNull())
- return icon;
-#endif
- if (info.isRoot())
-#if defined (Q_WS_WIN) && !defined(Q_WS_WINCE)
- {
- UINT type = GetDriveType((wchar_t *)info.absoluteFilePath().utf16());
-
- switch (type) {
- case DRIVE_REMOVABLE:
- return d->getIcon(QStyle::SP_DriveFDIcon);
- case DRIVE_FIXED:
- return d->getIcon(QStyle::SP_DriveHDIcon);
- case DRIVE_REMOTE:
- return d->getIcon(QStyle::SP_DriveNetIcon);
- case DRIVE_CDROM:
- return d->getIcon(QStyle::SP_DriveCDIcon);
- case DRIVE_RAMDISK:
- case DRIVE_UNKNOWN:
- case DRIVE_NO_ROOT_DIR:
- default:
- return d->getIcon(QStyle::SP_DriveHDIcon);
- }
- }
-#else
- return d->getIcon(QStyle::SP_DriveHDIcon);
-#endif
- if (info.isFile()) {
- if (info.isSymLink())
- return d->getIcon(QStyle::SP_FileLinkIcon);
- else
- return d->getIcon(QStyle::SP_FileIcon);
- }
- if (info.isDir()) {
- if (info.isSymLink()) {
- return d->getIcon(QStyle::SP_DirLinkIcon);
- } else {
- if (info.absoluteFilePath() == d->homePath) {
- return d->getIcon(QStyle::SP_DirHomeIcon);
- } else {
- return d->getIcon(QStyle::SP_DirIcon);
- }
- }
- }
- return QIcon();
-}
-
-/*!
- Returns the type of the file described by \a info.
-*/
-
-QString QFileIconProvider::type(const QFileInfo &info) const
-{
- if (info.isRoot())
- return QApplication::translate("QFileDialog", "Drive");
- if (info.isFile()) {
- if (!info.suffix().isEmpty())
- return info.suffix() + QLatin1Char(' ') + QApplication::translate("QFileDialog", "File");
- return QApplication::translate("QFileDialog", "File");
- }
-
- if (info.isDir())
-#ifdef Q_WS_WIN
- return QApplication::translate("QFileDialog", "File Folder", "Match Windows Explorer");
-#else
- return QApplication::translate("QFileDialog", "Folder", "All other platforms");
-#endif
- // Windows - "File Folder"
- // OS X - "Folder"
- // Konqueror - "Folder"
- // Nautilus - "folder"
-
- if (info.isSymLink())
-#ifdef Q_OS_MAC
- return QApplication::translate("QFileDialog", "Alias", "Mac OS X Finder");
-#else
- return QApplication::translate("QFileDialog", "Shortcut", "All other platforms");
-#endif
- // OS X - "Alias"
- // Windows - "Shortcut"
- // Konqueror - "Folder" or "TXT File" i.e. what it is pointing to
- // Nautilus - "link to folder" or "link to object file", same as Konqueror
-
- return QApplication::translate("QFileDialog", "Unknown");
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/itemviews/qfileiconprovider.h b/src/gui/itemviews/qfileiconprovider.h
deleted file mode 100644
index 5a70f80062..0000000000
--- a/src/gui/itemviews/qfileiconprovider.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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 QFILEICONPROVIDER_H
-#define QFILEICONPROVIDER_H
-
-#include <QtCore/qfileinfo.h>
-#include <QtCore/qscopedpointer.h>
-#include <QtGui/qicon.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_FILEICONPROVIDER
-
-class QFileIconProviderPrivate;
-
-class Q_GUI_EXPORT QFileIconProvider
-{
-public:
- QFileIconProvider();
- virtual ~QFileIconProvider();
- enum IconType { Computer, Desktop, Trashcan, Network, Drive, Folder, File };
- virtual QIcon icon(IconType type) const;
- virtual QIcon icon(const QFileInfo &info) const;
- virtual QString type(const QFileInfo &info) const;
-
-private:
- Q_DECLARE_PRIVATE(QFileIconProvider)
- QScopedPointer<QFileIconProviderPrivate> d_ptr;
- Q_DISABLE_COPY(QFileIconProvider)
-};
-
-#endif // QT_NO_FILEICONPROVIDER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QFILEICONPROVIDER_H
-
diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp
deleted file mode 100644
index 471c199bc2..0000000000
--- a/src/gui/itemviews/qheaderview.cpp
+++ /dev/null
@@ -1,3615 +0,0 @@
-/****************************************************************************
-**
-** 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 "qheaderview.h"
-
-#ifndef QT_NO_ITEMVIEWS
-#include <qbitarray.h>
-#include <qbrush.h>
-#include <qdebug.h>
-#include <qevent.h>
-#include <qpainter.h>
-#include <qscrollbar.h>
-#include <qtooltip.h>
-#include <qwhatsthis.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qvector.h>
-#include <qapplication.h>
-#include <qvarlengtharray.h>
-#include <qabstractitemdelegate.h>
-#include <qvariant.h>
-#include <private/qheaderview_p.h>
-#include <private/qabstractitemmodel_p.h>
-
-#ifndef QT_NO_DATASTREAM
-#include <qdatastream.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_DATASTREAM
-QDataStream &operator<<(QDataStream &out, const QHeaderViewPrivate::SectionSpan &span)
-{
- span.write(out);
- return out;
-}
-
-QDataStream &operator>>(QDataStream &in, QHeaderViewPrivate::SectionSpan &span)
-{
- span.read(in);
- return in;
-}
-#endif // QT_NO_DATASTREAM
-
-
-/*!
- \class QHeaderView
-
- \brief The QHeaderView class provides a header row or header column for
- item views.
-
- \ingroup model-view
-
-
- A QHeaderView displays the headers used in item views such as the
- QTableView and QTreeView classes. It takes the place of Qt3's \c QHeader
- class previously used for the same purpose, but uses the Qt's model/view
- architecture for consistency with the item view classes.
-
- The QHeaderView class is one of the \l{Model/View Classes} and is part of
- Qt's \l{Model/View Programming}{model/view framework}.
-
- The header gets the data for each section from the model using the
- QAbstractItemModel::headerData() function. You can set the data by using
- QAbstractItemModel::setHeaderData().
-
- Each header has an orientation() and a number of sections, given by the
- count() function. A section refers to a part of the header - either a row
- or a column, depending on the orientation.
-
- Sections can be moved and resized using moveSection() and resizeSection();
- they can also be hidden and shown with hideSection() and showSection().
-
- Each section of a header is described by a section ID, specified by its
- section(), and can be located at a particular visualIndex() in the header.
- A section can have a sort indicator set with setSortIndicator(); this
- indicates whether the items in the associated item view will be sorted in
- the order given by the section.
-
- For a horizontal header the section is equivalent to a column in the model,
- and for a vertical header the section is equivalent to a row in the model.
-
- \section1 Moving Header Sections
-
- A header can be fixed in place, or made movable with setMovable(). It can
- be made clickable with setClickable(), and has resizing behavior in
- accordance with setResizeMode().
-
- \note Double-clicking on a header to resize a section only applies for
- visible rows.
-
- A header will emit sectionMoved() if the user moves a section,
- sectionResized() if the user resizes a section, and sectionClicked() as
- well as sectionHandleDoubleClicked() in response to mouse clicks. A header
- will also emit sectionCountChanged() and sectionAutoResize().
-
- You can identify a section using the logicalIndex() and logicalIndexAt()
- functions, or by its index position, using the visualIndex() and
- visualIndexAt() functions. The visual index will change if a section is
- moved, but the logical index will not change.
-
- \section1 Appearance
-
- QTableWidget and QTableView create default headers. If you want
- the headers to be visible, you can use \l{QFrame::}{setVisible()}.
-
- Not all \l{Qt::}{ItemDataRole}s will have an effect on a
- QHeaderView. If you need to draw other roles, you can subclass
- QHeaderView and reimplement \l{QHeaderView::}{paintEvent()}.
- QHeaderView respects the following item data roles:
- \l{Qt::}{TextAlignmentRole}, \l{Qt::}{DisplayRole},
- \l{Qt::}{FontRole}, \l{Qt::}{DecorationRole},
- \l{Qt::}{ForegroundRole}, and \l{Qt::}{BackgroundRole}.
-
- \note Each header renders the data for each section itself, and does not
- rely on a delegate. As a result, calling a header's setItemDelegate()
- function will have no effect.
-
- \sa {Model/View Programming}, QListView, QTableView, QTreeView
-*/
-
-/*!
- \enum QHeaderView::ResizeMode
-
- The resize mode specifies the behavior of the header sections. It can be
- set on the entire header view or on individual sections using
- setResizeMode().
-
- \value Interactive The user can resize the section. The section can also be
- resized programmatically using resizeSection(). The section size
- defaults to \l defaultSectionSize. (See also
- \l cascadingSectionResizes.)
-
- \value Fixed The user cannot resize the section. The section can only be
- resized programmatically using resizeSection(). The section size
- defaults to \l defaultSectionSize.
-
- \value Stretch QHeaderView will automatically resize the section to fill
- the available space. The size cannot be changed by the user or
- programmatically.
-
- \value ResizeToContents QHeaderView will automatically resize the section
- to its optimal size based on the contents of the entire column or
- row. The size cannot be changed by the user or programmatically.
- (This value was introduced in 4.2)
-
- The following values are obsolete:
- \value Custom Use Fixed instead.
-
- \sa setResizeMode() stretchLastSection minimumSectionSize
-*/
-
-/*!
- \fn void QHeaderView::sectionMoved(int logicalIndex, int oldVisualIndex,
- int newVisualIndex)
-
- This signal is emitted when a section is moved. The section's logical index
- is specified by \a logicalIndex, the old index by \a oldVisualIndex, and
- the new index position by \a newVisualIndex.
-
- \sa moveSection()
-*/
-
-/*!
- \fn void QHeaderView::sectionResized(int logicalIndex, int oldSize,
- int newSize)
-
- This signal is emitted when a section is resized. The section's logical
- number is specified by \a logicalIndex, the old size by \a oldSize, and the
- new size by \a newSize.
-
- \sa resizeSection()
-*/
-
-/*!
- \fn void QHeaderView::sectionPressed(int logicalIndex)
-
- This signal is emitted when a section is pressed. The section's logical
- index is specified by \a logicalIndex.
-
- \sa setClickable()
-*/
-
-/*!
- \fn void QHeaderView::sectionClicked(int logicalIndex)
-
- This signal is emitted when a section is clicked. The section's logical
- index is specified by \a logicalIndex.
-
- Note that the sectionPressed signal will also be emitted.
-
- \sa setClickable(), sectionPressed()
-*/
-
-/*!
- \fn void QHeaderView::sectionEntered(int logicalIndex)
- \since 4.3
-
- This signal is emitted when the cursor moves over the section and the left
- mouse button is pressed. The section's logical index is specified by
- \a logicalIndex.
-
- \sa setClickable(), sectionPressed()
-*/
-
-/*!
- \fn void QHeaderView::sectionDoubleClicked(int logicalIndex)
-
- This signal is emitted when a section is double-clicked. The section's
- logical index is specified by \a logicalIndex.
-
- \sa setClickable()
-*/
-
-/*!
- \fn void QHeaderView::sectionCountChanged(int oldCount, int newCount)
-
- This signal is emitted when the number of sections changes, i.e., when
- sections are added or deleted. The original count is specified by
- \a oldCount, and the new count by \a newCount.
-
- \sa count(), length(), headerDataChanged()
-*/
-
-/*!
- \fn void QHeaderView::sectionHandleDoubleClicked(int logicalIndex)
-
- This signal is emitted when a section is double-clicked. The section's
- logical index is specified by \a logicalIndex.
-
- \sa setClickable()
-*/
-
-/*!
- \fn void QHeaderView::sortIndicatorChanged(int logicalIndex,
- Qt::SortOrder order)
- \since 4.3
-
- This signal is emitted when the section containing the sort indicator or
- the order indicated is changed. The section's logical index is specified
- by \a logicalIndex and the sort order is specified by \a order.
-
- \sa setSortIndicator()
-*/
-
-/*!
- \fn void QHeaderView::sectionAutoResize(int logicalIndex,
- QHeaderView::ResizeMode mode)
-
- This signal is emitted when a section is automatically resized. The
- section's logical index is specified by \a logicalIndex, and the resize
- mode by \a mode.
-
- \sa setResizeMode(), stretchLastSection()
-*/
-// ### Qt 5: change to sectionAutoResized()
-
-/*!
- \fn void QHeaderView::geometriesChanged()
- \since 4.2
-
- This signal is emitted when the header's geometries have changed.
-*/
-
-/*!
- \property QHeaderView::highlightSections
- \brief whether the sections containing selected items are highlighted
-
- By default, this property is false.
-*/
-
-/*!
- Creates a new generic header with the given \a orientation and \a parent.
-*/
-QHeaderView::QHeaderView(Qt::Orientation orientation, QWidget *parent)
- : QAbstractItemView(*new QHeaderViewPrivate, parent)
-{
- Q_D(QHeaderView);
- d->setDefaultValues(orientation);
- initialize();
-}
-
-/*!
- \internal
-*/
-QHeaderView::QHeaderView(QHeaderViewPrivate &dd,
- Qt::Orientation orientation, QWidget *parent)
- : QAbstractItemView(dd, parent)
-{
- Q_D(QHeaderView);
- d->setDefaultValues(orientation);
- initialize();
-}
-
-/*!
- Destroys the header.
-*/
-
-QHeaderView::~QHeaderView()
-{
-}
-
-/*!
- \internal
-*/
-void QHeaderView::initialize()
-{
- Q_D(QHeaderView);
- setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- setFrameStyle(NoFrame);
- setFocusPolicy(Qt::NoFocus);
- d->viewport->setMouseTracking(true);
- d->viewport->setBackgroundRole(QPalette::Button);
- d->textElideMode = Qt::ElideNone;
- delete d->itemDelegate;
-}
-
-/*!
- \reimp
-*/
-void QHeaderView::setModel(QAbstractItemModel *model)
-{
- if (model == this->model())
- return;
- Q_D(QHeaderView);
- if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- if (d->orientation == Qt::Horizontal) {
- QObject::disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- } else {
- QObject::disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- }
- QObject::disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(headerDataChanged(Qt::Orientation,int,int)));
- QObject::disconnect(d->model, SIGNAL(layoutAboutToBeChanged()),
- this, SLOT(_q_layoutAboutToBeChanged()));
- }
-
- if (model && model != QAbstractItemModelPrivate::staticEmptyModel()) {
- if (d->orientation == Qt::Horizontal) {
- QObject::connect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- } else {
- QObject::connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(sectionsInserted(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(sectionsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sectionsRemoved(QModelIndex,int,int)));
- }
- QObject::connect(model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(headerDataChanged(Qt::Orientation,int,int)));
- QObject::connect(model, SIGNAL(layoutAboutToBeChanged()),
- this, SLOT(_q_layoutAboutToBeChanged()));
- }
-
- d->state = QHeaderViewPrivate::NoClear;
- QAbstractItemView::setModel(model);
- d->state = QHeaderViewPrivate::NoState;
-
- // Users want to set sizes and modes before the widget is shown.
- // Thus, we have to initialize when the model is set,
- // and not lazily like we do in the other views.
- initializeSections();
-}
-
-/*!
- Returns the orientation of the header.
-
- \sa Qt::Orientation
-*/
-
-Qt::Orientation QHeaderView::orientation() const
-{
- Q_D(const QHeaderView);
- return d->orientation;
-}
-
-/*!
- Returns the offset of the header: this is the header's left-most (or
- top-most for vertical headers) visible pixel.
-
- \sa setOffset()
-*/
-
-int QHeaderView::offset() const
-{
- Q_D(const QHeaderView);
- return d->offset;
-}
-
-/*!
- \fn void QHeaderView::setOffset(int offset)
-
- Sets the header's offset to \a offset.
-
- \sa offset(), length()
-*/
-
-void QHeaderView::setOffset(int newOffset)
-{
- Q_D(QHeaderView);
- if (d->offset == (int)newOffset)
- return;
- int ndelta = d->offset - newOffset;
- d->offset = newOffset;
- if (d->orientation == Qt::Horizontal)
- d->viewport->scroll(isRightToLeft() ? -ndelta : ndelta, 0);
- else
- d->viewport->scroll(0, ndelta);
- if (d->state == QHeaderViewPrivate::ResizeSection) {
- QPoint cursorPos = QCursor::pos();
- if (d->orientation == Qt::Horizontal)
- QCursor::setPos(cursorPos.x() + ndelta, cursorPos.y());
- else
- QCursor::setPos(cursorPos.x(), cursorPos.y() + ndelta);
- d->firstPos += ndelta;
- d->lastPos += ndelta;
- }
-}
-
-/*!
- \since 4.2
- Sets the offset to the start of the section at the given \a visualIndex.
-
- \sa setOffset(), sectionPosition()
-*/
-void QHeaderView::setOffsetToSectionPosition(int visualIndex)
-{
- Q_D(QHeaderView);
- if (visualIndex > -1 && visualIndex < d->sectionCount) {
- int position = d->headerSectionPosition(d->adjustedVisualIndex(visualIndex));
- setOffset(position);
- }
-}
-
-/*!
- \since 4.2
- Sets the offset to make the last section visible.
-
- \sa setOffset(), sectionPosition(), setOffsetToSectionPosition()
-*/
-void QHeaderView::setOffsetToLastSection()
-{
- Q_D(const QHeaderView);
- int size = (d->orientation == Qt::Horizontal ? viewport()->width() : viewport()->height());
- int position = length() - size;
- setOffset(position);
-}
-
-/*!
- Returns the length along the orientation of the header.
-
- \sa sizeHint(), setResizeMode(), offset()
-*/
-
-int QHeaderView::length() const
-{
- Q_D(const QHeaderView);
- //Q_ASSERT(d->headerLength() == d->length);
- return d->length;
-}
-
-/*!
- Returns a suitable size hint for this header.
-
- \sa sectionSizeHint()
-*/
-
-QSize QHeaderView::sizeHint() const
-{
- Q_D(const QHeaderView);
- if (d->cachedSizeHint.isValid())
- return d->cachedSizeHint;
- d->cachedSizeHint = QSize(0, 0); //reinitialize the cached size hint
- const int sectionCount = count();
-
- // get size hint for the first n sections
- int i = 0;
- for (int checked = 0; checked < 100 && i < sectionCount; ++i) {
- if (isSectionHidden(i))
- continue;
- checked++;
- QSize hint = sectionSizeFromContents(i);
- d->cachedSizeHint = d->cachedSizeHint.expandedTo(hint);
- }
- // get size hint for the last n sections
- i = qMax(i, sectionCount - 100 );
- for (int j = sectionCount - 1, checked = 0; j >= i && checked < 100; --j) {
- if (isSectionHidden(j))
- continue;
- checked++;
- QSize hint = sectionSizeFromContents(j);
- d->cachedSizeHint = d->cachedSizeHint.expandedTo(hint);
- }
- return d->cachedSizeHint;
-}
-
-/*!
- Returns a suitable size hint for the section specified by \a logicalIndex.
-
- \sa sizeHint(), defaultSectionSize(), minimumSectionSize(),
- Qt::SizeHintRole
-*/
-
-int QHeaderView::sectionSizeHint(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- if (isSectionHidden(logicalIndex))
- return 0;
- if (logicalIndex < 0 || logicalIndex >= count())
- return -1;
- QSize size;
- QVariant value = d->model->headerData(logicalIndex, d->orientation, Qt::SizeHintRole);
- if (value.isValid())
- size = qvariant_cast<QSize>(value);
- else
- size = sectionSizeFromContents(logicalIndex);
- int hint = d->orientation == Qt::Horizontal ? size.width() : size.height();
- return qMax(minimumSectionSize(), hint);
-}
-
-/*!
- Returns the visual index of the section that covers the given \a position
- in the viewport.
-
- \sa logicalIndexAt()
-*/
-
-int QHeaderView::visualIndexAt(int position) const
-{
- Q_D(const QHeaderView);
- int vposition = position;
- d->executePostedLayout();
- d->executePostedResize();
- const int count = d->sectionCount;
- if (count < 1)
- return -1;
-
- if (d->reverse())
- vposition = d->viewport->width() - vposition;
- vposition += d->offset;
-
- if (vposition > d->length)
- return -1;
- int visual = d->headerVisualIndexAt(vposition);
- if (visual < 0)
- return -1;
-
- while (d->isVisualIndexHidden(visual)){
- ++visual;
- if (visual >= count)
- return -1;
- }
- return visual;
-}
-
-/*!
- Returns the section that covers the given \a position in the viewport.
-
- \sa visualIndexAt(), isSectionHidden()
-*/
-
-int QHeaderView::logicalIndexAt(int position) const
-{
- const int visual = visualIndexAt(position);
- if (visual > -1)
- return logicalIndex(visual);
- return -1;
-}
-
-/*!
- Returns the width (or height for vertical headers) of the given
- \a logicalIndex.
-
- \sa length(), setResizeMode(), defaultSectionSize()
-*/
-
-int QHeaderView::sectionSize(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- if (isSectionHidden(logicalIndex))
- return 0;
- if (logicalIndex < 0 || logicalIndex >= count())
- return 0;
- int visual = visualIndex(logicalIndex);
- if (visual == -1)
- return 0;
- d->executePostedResize();
- return d->headerSectionSize(visual);
-}
-
-/*!
-
- Returns the section position of the given \a logicalIndex, or -1
- if the section is hidden. The position is measured in pixels from
- the first visible item's top-left corner to the top-left corner of
- the item with \a logicalIndex. The measurement is along the x-axis
- for horizontal headers and along the y-axis for vertical headers.
-
- \sa sectionViewportPosition()
-*/
-
-int QHeaderView::sectionPosition(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- int visual = visualIndex(logicalIndex);
- // in some cases users may change the selections
- // before we have a chance to do the layout
- if (visual == -1)
- return -1;
- d->executePostedResize();
- return d->headerSectionPosition(visual);
-}
-
-/*!
- Returns the section viewport position of the given \a logicalIndex.
-
- If the section is hidden, the return value is undefined.
-
- \sa sectionPosition(), isSectionHidden()
-*/
-
-int QHeaderView::sectionViewportPosition(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- if (logicalIndex >= count())
- return -1;
- int position = sectionPosition(logicalIndex);
- if (position < 0)
- return position; // the section was hidden
- int offsetPosition = position - d->offset;
- if (d->reverse())
- return d->viewport->width() - (offsetPosition + sectionSize(logicalIndex));
- return offsetPosition;
-}
-
-/*!
- \fn int QHeaderView::logicalIndexAt(int x, int y) const
-
- Returns the logical index of the section at the given coordinate. If the
- header is horizontal \a x will be used, otherwise \a y will be used to
- find the logical index.
-*/
-
-/*!
- \fn int QHeaderView::logicalIndexAt(const QPoint &pos) const
-
- Returns the logical index of the section at the position given in \a pos.
- If the header is horizontal the x-coordinate will be used, otherwise the
- y-coordinate will be used to find the logical index.
-
- \sa sectionPosition()
-*/
-
-/*!
- Moves the section at visual index \a from to occupy visual index \a to.
-
- \sa sectionsMoved()
-*/
-
-void QHeaderView::moveSection(int from, int to)
-{
- Q_D(QHeaderView);
-
- d->executePostedLayout();
- if (from < 0 || from >= d->sectionCount || to < 0 || to >= d->sectionCount)
- return;
-
- if (from == to) {
- int logical = logicalIndex(from);
- Q_ASSERT(logical != -1);
- updateSection(logical);
- return;
- }
-
- if (stretchLastSection() && to == d->lastVisibleVisualIndex())
- d->lastSectionSize = sectionSize(from);
-
- //int oldHeaderLength = length(); // ### for debugging; remove later
- d->initializeIndexMapping();
-
- QBitArray sectionHidden = d->sectionHidden;
- int *visualIndices = d->visualIndices.data();
- int *logicalIndices = d->logicalIndices.data();
- int logical = logicalIndices[from];
- int visual = from;
-
- int affected_count = qAbs(to - from) + 1;
- QVarLengthArray<int> sizes(affected_count);
- QVarLengthArray<ResizeMode> modes(affected_count);
-
- // move sections and indices
- if (to > from) {
- sizes[to - from] = d->headerSectionSize(from);
- modes[to - from] = d->headerSectionResizeMode(from);
- while (visual < to) {
- sizes[visual - from] = d->headerSectionSize(visual + 1);
- modes[visual - from] = d->headerSectionResizeMode(visual + 1);
- if (!sectionHidden.isEmpty())
- sectionHidden.setBit(visual, sectionHidden.testBit(visual + 1));
- visualIndices[logicalIndices[visual + 1]] = visual;
- logicalIndices[visual] = logicalIndices[visual + 1];
- ++visual;
- }
- } else {
- sizes[0] = d->headerSectionSize(from);
- modes[0] = d->headerSectionResizeMode(from);
- while (visual > to) {
- sizes[visual - to] = d->headerSectionSize(visual - 1);
- modes[visual - to] = d->headerSectionResizeMode(visual - 1);
- if (!sectionHidden.isEmpty())
- sectionHidden.setBit(visual, sectionHidden.testBit(visual - 1));
- visualIndices[logicalIndices[visual - 1]] = visual;
- logicalIndices[visual] = logicalIndices[visual - 1];
- --visual;
- }
- }
- if (!sectionHidden.isEmpty()) {
- sectionHidden.setBit(to, d->sectionHidden.testBit(from));
- d->sectionHidden = sectionHidden;
- }
- visualIndices[logical] = to;
- logicalIndices[to] = logical;
-
- //Q_ASSERT(oldHeaderLength == length());
- // move sizes
- // ### check for spans of section sizes here
- if (to > from) {
- for (visual = from; visual <= to; ++visual) {
- int size = sizes[visual - from];
- ResizeMode mode = modes[visual - from];
- d->createSectionSpan(visual, visual, size, mode);
- }
- } else {
- for (visual = to; visual <= from; ++visual) {
- int size = sizes[visual - to];
- ResizeMode mode = modes[visual - to];
- d->createSectionSpan(visual, visual, size, mode);
- }
- }
- //Q_ASSERT(d->headerLength() == length());
- //Q_ASSERT(oldHeaderLength == length());
- //Q_ASSERT(d->logicalIndices.count() == d->sectionCount);
-
- if (d->hasAutoResizeSections())
- d->doDelayedResizeSections();
- d->viewport->update();
-
- emit sectionMoved(logical, from, to);
-}
-
-/*!
- \since 4.2
- Swaps the section at visual index \a first with the section at visual
- index \a second.
-
- \sa moveSection()
-*/
-void QHeaderView::swapSections(int first, int second)
-{
- Q_D(QHeaderView);
-
- if (first == second)
- return;
- d->executePostedLayout();
- if (first < 0 || first >= d->sectionCount || second < 0 || second >= d->sectionCount)
- return;
-
- int firstSize = d->headerSectionSize(first);
- ResizeMode firstMode = d->headerSectionResizeMode(first);
- int firstLogical = d->logicalIndex(first);
-
- int secondSize = d->headerSectionSize(second);
- ResizeMode secondMode = d->headerSectionResizeMode(second);
- int secondLogical = d->logicalIndex(second);
-
- d->createSectionSpan(second, second, firstSize, firstMode);
- d->createSectionSpan(first, first, secondSize, secondMode);
-
- d->initializeIndexMapping();
-
- d->visualIndices[firstLogical] = second;
- d->logicalIndices[second] = firstLogical;
-
- d->visualIndices[secondLogical] = first;
- d->logicalIndices[first] = secondLogical;
-
- if (!d->sectionHidden.isEmpty()) {
- bool firstHidden = d->sectionHidden.testBit(first);
- bool secondHidden = d->sectionHidden.testBit(second);
- d->sectionHidden.setBit(first, secondHidden);
- d->sectionHidden.setBit(second, firstHidden);
- }
-
- d->viewport->update();
- emit sectionMoved(firstLogical, first, second);
- emit sectionMoved(secondLogical, second, first);
-}
-
-/*!
- \fn void QHeaderView::resizeSection(int logicalIndex, int size)
-
- Resizes the section specified by \a logicalIndex to \a size measured in
- pixels.
-
- \sa sectionResized(), resizeMode(), sectionSize()
-*/
-
-void QHeaderView::resizeSection(int logical, int size)
-{
- Q_D(QHeaderView);
- if (logical < 0 || logical >= count())
- return;
-
- if (isSectionHidden(logical)) {
- d->hiddenSectionSize.insert(logical, size);
- return;
- }
-
- int visual = visualIndex(logical);
- if (visual == -1)
- return;
-
- int oldSize = d->headerSectionSize(visual);
- if (oldSize == size)
- return;
-
- d->executePostedLayout();
- d->invalidateCachedSizeHint();
-
- if (stretchLastSection() && visual == d->lastVisibleVisualIndex())
- d->lastSectionSize = size;
-
- if (size != oldSize)
- d->createSectionSpan(visual, visual, size, d->headerSectionResizeMode(visual));
-
- int w = d->viewport->width();
- int h = d->viewport->height();
- int pos = sectionViewportPosition(logical);
- QRect r;
- if (d->orientation == Qt::Horizontal)
- if (isRightToLeft())
- r.setRect(0, 0, pos + size, h);
- else
- r.setRect(pos, 0, w - pos, h);
- else
- r.setRect(0, pos, w, h - pos);
-
- if (d->hasAutoResizeSections()) {
- d->doDelayedResizeSections();
- r = d->viewport->rect();
- }
- d->viewport->update(r.normalized());
- emit sectionResized(logical, oldSize, size);
-}
-
-/*!
- Resizes the sections according to the given \a mode, ignoring the current
- resize mode.
-
- \sa resizeMode(), sectionResized()
-*/
-
-void QHeaderView::resizeSections(QHeaderView::ResizeMode mode)
-{
- Q_D(QHeaderView);
- d->resizeSections(mode, true);
-}
-
-/*!
- \fn void QHeaderView::hideSection(int logicalIndex)
- Hides the section specified by \a logicalIndex.
-
- \sa showSection(), isSectionHidden(), hiddenSectionCount(),
- setSectionHidden()
-*/
-
-/*!
- \fn void QHeaderView::showSection(int logicalIndex)
- Shows the section specified by \a logicalIndex.
-
- \sa hideSection(), isSectionHidden(), hiddenSectionCount(),
- setSectionHidden()
-*/
-
-/*!
- Returns true if the section specified by \a logicalIndex is explicitly
- hidden from the user; otherwise returns false.
-
- \sa hideSection(), showSection(), setSectionHidden(), hiddenSectionCount()
-*/
-
-bool QHeaderView::isSectionHidden(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- d->executePostedLayout();
- if (logicalIndex >= d->sectionHidden.count() || logicalIndex < 0 || logicalIndex >= d->sectionCount)
- return false;
- int visual = visualIndex(logicalIndex);
- Q_ASSERT(visual != -1);
- return d->sectionHidden.testBit(visual);
-}
-
-/*!
- \since 4.1
-
- Returns the number of sections in the header that has been hidden.
-
- \sa setSectionHidden(), isSectionHidden()
-*/
-int QHeaderView::hiddenSectionCount() const
-{
- Q_D(const QHeaderView);
- return d->hiddenSectionSize.count();
-}
-
-/*!
- If \a hide is true the section specified by \a logicalIndex is hidden;
- otherwise the section is shown.
-
- \sa isSectionHidden(), hiddenSectionCount()
-*/
-
-void QHeaderView::setSectionHidden(int logicalIndex, bool hide)
-{
- Q_D(QHeaderView);
- if (logicalIndex < 0 || logicalIndex >= count())
- return;
-
- d->executePostedLayout();
- int visual = visualIndex(logicalIndex);
- Q_ASSERT(visual != -1);
- if (hide == d->isVisualIndexHidden(visual))
- return;
- if (hide) {
- int size = d->headerSectionSize(visual);
- if (!d->hasAutoResizeSections())
- resizeSection(logicalIndex, 0);
- d->hiddenSectionSize.insert(logicalIndex, size);
- if (d->sectionHidden.count() < count())
- d->sectionHidden.resize(count());
- d->sectionHidden.setBit(visual, true);
- if (d->hasAutoResizeSections())
- d->doDelayedResizeSections();
- } else {
- int size = d->hiddenSectionSize.value(logicalIndex, d->defaultSectionSize);
- d->hiddenSectionSize.remove(logicalIndex);
- if (d->hiddenSectionSize.isEmpty()) {
- d->sectionHidden.clear();
- } else {
- Q_ASSERT(visual <= d->sectionHidden.count());
- d->sectionHidden.setBit(visual, false);
- }
- resizeSection(logicalIndex, size);
- }
-}
-
-/*!
- Returns the number of sections in the header.
-
- \sa sectionCountChanged(), length()
-*/
-
-int QHeaderView::count() const
-{
- Q_D(const QHeaderView);
- //Q_ASSERT(d->sectionCount == d->headerSectionCount());
- // ### this may affect the lazy layout
- d->executePostedLayout();
- return d->sectionCount;
-}
-
-/*!
- Returns the visual index position of the section specified by the given
- \a logicalIndex, or -1 otherwise.
-
- Hidden sections still have valid visual indexes.
-
- \sa logicalIndex()
-*/
-
-int QHeaderView::visualIndex(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- if (logicalIndex < 0)
- return -1;
- d->executePostedLayout();
- if (d->visualIndices.isEmpty()) { // nothing has been moved, so we have no mapping
- if (logicalIndex < d->sectionCount)
- return logicalIndex;
- } else if (logicalIndex < d->visualIndices.count()) {
- int visual = d->visualIndices.at(logicalIndex);
- Q_ASSERT(visual < d->sectionCount);
- return visual;
- }
- return -1;
-}
-
-/*!
- Returns the logicalIndex for the section at the given \a visualIndex
- position, or -1 if visualIndex < 0 or visualIndex >= QHeaderView::count().
-
- Note that the visualIndex is not affected by hidden sections.
-
- \sa visualIndex(), sectionPosition()
-*/
-
-int QHeaderView::logicalIndex(int visualIndex) const
-{
- Q_D(const QHeaderView);
- if (visualIndex < 0 || visualIndex >= d->sectionCount)
- return -1;
- return d->logicalIndex(visualIndex);
-}
-
-/*!
- If \a movable is true, the header may be moved by the user; otherwise it
- is fixed in place.
-
- \sa isMovable(), sectionMoved()
-*/
-
-// ### Qt 5: change to setSectionsMovable()
-void QHeaderView::setMovable(bool movable)
-{
- Q_D(QHeaderView);
- d->movableSections = movable;
-}
-
-/*!
- Returns true if the header can be moved by the user; otherwise returns
- false.
-
- \sa setMovable()
-*/
-
-// ### Qt 5: change to sectionsMovable()
-bool QHeaderView::isMovable() const
-{
- Q_D(const QHeaderView);
- return d->movableSections;
-}
-
-/*!
- If \a clickable is true, the header will respond to single clicks.
-
- \sa isClickable(), sectionClicked(), sectionPressed(),
- setSortIndicatorShown()
-*/
-
-// ### Qt 5: change to setSectionsClickable()
-void QHeaderView::setClickable(bool clickable)
-{
- Q_D(QHeaderView);
- d->clickableSections = clickable;
-}
-
-/*!
- Returns true if the header is clickable; otherwise returns false. A
- clickable header could be set up to allow the user to change the
- representation of the data in the view related to the header.
-
- \sa setClickable()
-*/
-
-// ### Qt 5: change to sectionsClickable()
-bool QHeaderView::isClickable() const
-{
- Q_D(const QHeaderView);
- return d->clickableSections;
-}
-
-void QHeaderView::setHighlightSections(bool highlight)
-{
- Q_D(QHeaderView);
- d->highlightSelected = highlight;
-}
-
-bool QHeaderView::highlightSections() const
-{
- Q_D(const QHeaderView);
- return d->highlightSelected;
-}
-
-/*!
- Sets the constraints on how the header can be resized to those described
- by the given \a mode.
-
- \sa resizeMode(), length(), sectionResized(), sectionAutoResize()
-*/
-
-void QHeaderView::setResizeMode(ResizeMode mode)
-{
- Q_D(QHeaderView);
- initializeSections();
- d->stretchSections = (mode == Stretch ? count() : 0);
- d->contentsSections = (mode == ResizeToContents ? count() : 0);
- d->setGlobalHeaderResizeMode(mode);
- if (d->hasAutoResizeSections())
- d->doDelayedResizeSections(); // section sizes may change as a result of the new mode
-}
-
-/*!
- \overload
-
- Sets the constraints on how the section specified by \a logicalIndex in
- the header can be resized to those described by the given \a mode. The logical
- index should exist at the time this function is called.
-
- \note This setting will be ignored for the last section if the stretchLastSection
- property is set to true. This is the default for the horizontal headers provided
- by QTreeView.
-
- \sa setStretchLastSection()
-*/
-
-// ### Qt 5: change to setSectionResizeMode()
-void QHeaderView::setResizeMode(int logicalIndex, ResizeMode mode)
-{
- Q_D(QHeaderView);
- int visual = visualIndex(logicalIndex);
- Q_ASSERT(visual != -1);
-
- ResizeMode old = d->headerSectionResizeMode(visual);
- d->setHeaderSectionResizeMode(visual, mode);
-
- if (mode == Stretch && old != Stretch)
- ++d->stretchSections;
- else if (mode == ResizeToContents && old != ResizeToContents)
- ++d->contentsSections;
- else if (mode != Stretch && old == Stretch)
- --d->stretchSections;
- else if (mode != ResizeToContents && old == ResizeToContents)
- --d->contentsSections;
-
- if (d->hasAutoResizeSections() && d->state == QHeaderViewPrivate::NoState)
- d->doDelayedResizeSections(); // section sizes may change as a result of the new mode
-}
-
-/*!
- Returns the resize mode that applies to the section specified by the given
- \a logicalIndex.
-
- \sa setResizeMode()
-*/
-
-QHeaderView::ResizeMode QHeaderView::resizeMode(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- int visual = visualIndex(logicalIndex);
- if (visual == -1)
- return Fixed; //the default value
- return d->headerSectionResizeMode(visual);
-}
-
-/*!
- \since 4.1
-
- Returns the number of sections that are set to resize mode stretch. In
- views, this can be used to see if the headerview needs to resize the
- sections when the view's geometry changes.
-
- \sa stretchLastSection, resizeMode()
-*/
-
-int QHeaderView::stretchSectionCount() const
-{
- Q_D(const QHeaderView);
- return d->stretchSections;
-}
-
-/*!
- \property QHeaderView::showSortIndicator
- \brief whether the sort indicator is shown
-
- By default, this property is false.
-
- \sa setClickable()
-*/
-
-void QHeaderView::setSortIndicatorShown(bool show)
-{
- Q_D(QHeaderView);
- if (d->sortIndicatorShown == show)
- return;
-
- d->sortIndicatorShown = show;
-
- if (sortIndicatorSection() < 0 || sortIndicatorSection() > count())
- return;
-
- if (d->headerSectionResizeMode(sortIndicatorSection()) == ResizeToContents)
- resizeSections();
-
- d->viewport->update();
-}
-
-bool QHeaderView::isSortIndicatorShown() const
-{
- Q_D(const QHeaderView);
- return d->sortIndicatorShown;
-}
-
-/*!
- Sets the sort indicator for the section specified by the given
- \a logicalIndex in the direction specified by \a order, and removes the
- sort indicator from any other section that was showing it.
-
- \a logicalIndex may be -1, in which case no sort indicator will be shown
- and the model will return to its natural, unsorted order. Note that not
- all models support this and may even crash in this case.
-
- \sa sortIndicatorSection() sortIndicatorOrder()
-*/
-
-void QHeaderView::setSortIndicator(int logicalIndex, Qt::SortOrder order)
-{
- Q_D(QHeaderView);
-
- // This is so that people can set the position of the sort indicator before the fill the model
- int old = d->sortIndicatorSection;
- d->sortIndicatorSection = logicalIndex;
- d->sortIndicatorOrder = order;
-
- if (logicalIndex >= d->sectionCount) {
- emit sortIndicatorChanged(logicalIndex, order);
- return; // nothing to do
- }
-
- if (old != logicalIndex
- && ((logicalIndex >= 0 && resizeMode(logicalIndex) == ResizeToContents)
- || old >= d->sectionCount || (old >= 0 && resizeMode(old) == ResizeToContents))) {
- resizeSections();
- d->viewport->update();
- } else {
- if (old >= 0 && old != logicalIndex)
- updateSection(old);
- if (logicalIndex >= 0)
- updateSection(logicalIndex);
- }
-
- emit sortIndicatorChanged(logicalIndex, order);
-}
-
-/*!
- Returns the logical index of the section that has a sort indicator.
- By default this is section 0.
-
- \sa setSortIndicator() sortIndicatorOrder() setSortIndicatorShown()
-*/
-
-int QHeaderView::sortIndicatorSection() const
-{
- Q_D(const QHeaderView);
- return d->sortIndicatorSection;
-}
-
-/*!
- Returns the order for the sort indicator. If no section has a sort
- indicator the return value of this function is undefined.
-
- \sa setSortIndicator() sortIndicatorSection()
-*/
-
-Qt::SortOrder QHeaderView::sortIndicatorOrder() const
-{
- Q_D(const QHeaderView);
- return d->sortIndicatorOrder;
-}
-
-/*!
- \property QHeaderView::stretchLastSection
- \brief whether the last visible section in the header takes up all the
- available space
-
- The default value is false.
-
- \note The horizontal headers provided by QTreeView are configured with this
- property set to true, ensuring that the view does not waste any of the
- space assigned to it for its header. If this value is set to true, this
- property will override the resize mode set on the last section in the
- header.
-
- \sa setResizeMode()
-*/
-bool QHeaderView::stretchLastSection() const
-{
- Q_D(const QHeaderView);
- return d->stretchLastSection;
-}
-
-void QHeaderView::setStretchLastSection(bool stretch)
-{
- Q_D(QHeaderView);
- d->stretchLastSection = stretch;
- if (d->state != QHeaderViewPrivate::NoState)
- return;
- if (stretch)
- resizeSections();
- else if (count())
- resizeSection(count() - 1, d->defaultSectionSize);
-}
-
-/*!
- \since 4.2
- \property QHeaderView::cascadingSectionResizes
- \brief whether interactive resizing will be cascaded to the following
- sections once the section being resized by the user has reached its
- minimum size
-
- This property only affects sections that have \l Interactive as their
- resize mode.
-
- The default value is false.
-
- \sa setResizeMode()
-*/
-bool QHeaderView::cascadingSectionResizes() const
-{
- Q_D(const QHeaderView);
- return d->cascadingResizing;
-}
-
-void QHeaderView::setCascadingSectionResizes(bool enable)
-{
- Q_D(QHeaderView);
- d->cascadingResizing = enable;
-}
-
-/*!
- \property QHeaderView::defaultSectionSize
- \brief the default size of the header sections before resizing.
-
- This property only affects sections that have \l Interactive or \l Fixed
- as their resize mode.
-
- \sa setResizeMode() minimumSectionSize
-*/
-int QHeaderView::defaultSectionSize() const
-{
- Q_D(const QHeaderView);
- return d->defaultSectionSize;
-}
-
-void QHeaderView::setDefaultSectionSize(int size)
-{
- Q_D(QHeaderView);
- d->setDefaultSectionSize(size);
-}
-
-/*!
- \since 4.2
- \property QHeaderView::minimumSectionSize
- \brief the minimum size of the header sections.
-
- The minimum section size is the smallest section size allowed. If the
- minimum section size is set to -1, QHeaderView will use the maximum of
- the \l{QApplication::globalStrut()}{global strut} or the
- \l{fontMetrics()}{font metrics} size.
-
- This property is honored by all \l{ResizeMode}{resize modes}.
-
- \sa setResizeMode() defaultSectionSize
-*/
-int QHeaderView::minimumSectionSize() const
-{
- Q_D(const QHeaderView);
- if (d->minimumSectionSize == -1) {
- QSize strut = QApplication::globalStrut();
- int margin = style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);
- if (d->orientation == Qt::Horizontal)
- return qMax(strut.width(), (fontMetrics().maxWidth() + margin));
- return qMax(strut.height(), (fontMetrics().height() + margin));
- }
- return d->minimumSectionSize;
-}
-
-void QHeaderView::setMinimumSectionSize(int size)
-{
- Q_D(QHeaderView);
- d->minimumSectionSize = size;
-}
-
-/*!
- \since 4.1
- \property QHeaderView::defaultAlignment
- \brief the default alignment of the text in each header section
-*/
-
-Qt::Alignment QHeaderView::defaultAlignment() const
-{
- Q_D(const QHeaderView);
- return d->defaultAlignment;
-}
-
-void QHeaderView::setDefaultAlignment(Qt::Alignment alignment)
-{
- Q_D(QHeaderView);
- if (d->defaultAlignment == alignment)
- return;
-
- d->defaultAlignment = alignment;
- d->viewport->update();
-}
-
-/*!
- \internal
-*/
-void QHeaderView::doItemsLayout()
-{
- initializeSections();
- QAbstractItemView::doItemsLayout();
-}
-
-/*!
- Returns true if sections in the header has been moved; otherwise returns
- false;
-
- \sa moveSection()
-*/
-bool QHeaderView::sectionsMoved() const
-{
- Q_D(const QHeaderView);
- return !d->visualIndices.isEmpty();
-}
-
-/*!
- \since 4.1
-
- Returns true if sections in the header has been hidden; otherwise returns
- false;
-
- \sa setSectionHidden()
-*/
-bool QHeaderView::sectionsHidden() const
-{
- Q_D(const QHeaderView);
- return !d->hiddenSectionSize.isEmpty();
-}
-
-#ifndef QT_NO_DATASTREAM
-/*!
- \since 4.3
-
- Saves the current state of this header view.
-
- To restore the saved state, pass the return value to restoreState().
-
- \sa restoreState()
-*/
-QByteArray QHeaderView::saveState() const
-{
- Q_D(const QHeaderView);
- QByteArray data;
- QDataStream stream(&data, QIODevice::WriteOnly);
- stream << QHeaderViewPrivate::VersionMarker;
- stream << 0; // current version is 0
- d->write(stream);
- return data;
-}
-
-/*!
- \since 4.3
- Restores the \a state of this header view.
- This function returns \c true if the state was restored; otherwise returns
- false.
-
- \sa saveState()
-*/
-bool QHeaderView::restoreState(const QByteArray &state)
-{
- Q_D(QHeaderView);
- if (state.isEmpty())
- return false;
- QByteArray data = state;
- QDataStream stream(&data, QIODevice::ReadOnly);
- int marker;
- int ver;
- stream >> marker;
- stream >> ver;
- if (stream.status() != QDataStream::Ok
- || marker != QHeaderViewPrivate::VersionMarker
- || ver != 0) // current version is 0
- return false;
-
- if (d->read(stream)) {
- emit sortIndicatorChanged(d->sortIndicatorSection, d->sortIndicatorOrder );
- d->viewport->update();
- return true;
- }
- return false;
-}
-#endif // QT_NO_DATASTREAM
-
-/*!
- \reimp
-*/
-void QHeaderView::reset()
-{
- QAbstractItemView::reset();
- // it would be correct to call clear, but some apps rely
- // on the header keeping the sections, even after calling reset
- //d->clear();
- initializeSections();
-}
-
-/*!
- Updates the changed header sections with the given \a orientation, from
- \a logicalFirst to \a logicalLast inclusive.
-*/
-void QHeaderView::headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast)
-{
- Q_D(QHeaderView);
- if (d->orientation != orientation)
- return;
-
- if (logicalFirst < 0 || logicalLast < 0 || logicalFirst >= count() || logicalLast >= count())
- return;
-
- d->invalidateCachedSizeHint();
-
- int firstVisualIndex = INT_MAX, lastVisualIndex = -1;
-
- for (int section = logicalFirst; section <= logicalLast; ++section) {
- const int visual = visualIndex(section);
- firstVisualIndex = qMin(firstVisualIndex, visual);
- lastVisualIndex = qMax(lastVisualIndex, visual);
- }
-
- d->executePostedResize();
- const int first = d->headerSectionPosition(firstVisualIndex),
- last = d->headerSectionPosition(lastVisualIndex)
- + d->headerSectionSize(lastVisualIndex);
-
- if (orientation == Qt::Horizontal) {
- d->viewport->update(first, 0, last - first, d->viewport->height());
- } else {
- d->viewport->update(0, first, d->viewport->width(), last - first);
- }
-}
-
-/*!
- \internal
- \since 4.2
-
- Updates the section specified by the given \a logicalIndex.
-*/
-
-void QHeaderView::updateSection(int logicalIndex)
-{
- Q_D(QHeaderView);
- if (d->orientation == Qt::Horizontal)
- d->viewport->update(QRect(sectionViewportPosition(logicalIndex),
- 0, sectionSize(logicalIndex), d->viewport->height()));
- else
- d->viewport->update(QRect(0, sectionViewportPosition(logicalIndex),
- d->viewport->width(), sectionSize(logicalIndex)));
-}
-
-/*!
- Resizes the sections according to their size hints. Normally, you do not
- have to call this function.
-*/
-
-void QHeaderView::resizeSections()
-{
- Q_D(QHeaderView);
- if (d->hasAutoResizeSections())
- d->resizeSections(Interactive, false); // no global resize mode
-}
-
-/*!
- This slot is called when sections are inserted into the \a parent.
- \a logicalFirst and \a logicalLast indices signify where the new sections
- were inserted.
-
- If only one section is inserted, \a logicalFirst and \a logicalLast will
- be the same.
-*/
-
-void QHeaderView::sectionsInserted(const QModelIndex &parent,
- int logicalFirst, int logicalLast)
-{
- Q_D(QHeaderView);
- if (parent != d->root)
- return; // we only handle changes in the top level
- int oldCount = d->sectionCount;
-
- d->invalidateCachedSizeHint();
-
- // add the new sections
- int insertAt = 0;
- for (int spanStart = 0; insertAt < d->sectionSpans.count() && spanStart < logicalFirst; ++insertAt)
- spanStart += d->sectionSpans.at(insertAt).count;
-
- int insertCount = logicalLast - logicalFirst + 1;
- d->sectionCount += insertCount;
-
- if (d->sectionSpans.isEmpty() || insertAt >= d->sectionSpans.count()) {
- int insertLength = d->defaultSectionSize * insertCount;
- d->length += insertLength;
- QHeaderViewPrivate::SectionSpan span(insertLength, insertCount, d->globalResizeMode);
- d->sectionSpans.append(span);
- } else if ((d->sectionSpans.at(insertAt).sectionSize() == d->defaultSectionSize)
- && d->sectionSpans.at(insertAt).resizeMode == d->globalResizeMode) {
- // add the new sections to an existing span
- int insertLength = d->sectionSpans.at(insertAt).sectionSize() * insertCount;
- d->length += insertLength;
- d->sectionSpans[insertAt].size += insertLength;
- d->sectionSpans[insertAt].count += insertCount;
- } else {
- // separate them out into their own span
- int insertLength = d->defaultSectionSize * insertCount;
- d->length += insertLength;
- QHeaderViewPrivate::SectionSpan span(insertLength, insertCount, d->globalResizeMode);
- d->sectionSpans.insert(insertAt, span);
- }
-
- // update sorting column
- if (d->sortIndicatorSection >= logicalFirst)
- d->sortIndicatorSection += insertCount;
-
- // update resize mode section counts
- if (d->globalResizeMode == Stretch)
- d->stretchSections = d->sectionCount;
- else if (d->globalResizeMode == ResizeToContents)
- d->contentsSections = d->sectionCount;
-
- // clear selection cache
- d->sectionSelected.clear();
-
- // update mapping
- if (!d->visualIndices.isEmpty() && !d->logicalIndices.isEmpty()) {
- Q_ASSERT(d->visualIndices.count() == d->logicalIndices.count());
- int mappingCount = d->visualIndices.count();
- for (int i = 0; i < mappingCount; ++i) {
- if (d->visualIndices.at(i) >= logicalFirst)
- d->visualIndices[i] += insertCount;
- if (d->logicalIndices.at(i) >= logicalFirst)
- d->logicalIndices[i] += insertCount;
- }
- for (int j = logicalFirst; j <= logicalLast; ++j) {
- d->visualIndices.insert(j, j);
- d->logicalIndices.insert(j, j);
- }
- }
-
- // insert sections into sectionsHidden
- if (!d->sectionHidden.isEmpty()) {
- QBitArray sectionHidden(d->sectionHidden);
- sectionHidden.resize(sectionHidden.count() + insertCount);
- sectionHidden.fill(false, logicalFirst, logicalLast + 1);
- for (int j = logicalLast + 1; j < sectionHidden.count(); ++j)
- //here we simply copy the old sectionHidden
- sectionHidden.setBit(j, d->sectionHidden.testBit(j - insertCount));
- d->sectionHidden = sectionHidden;
- }
-
- // insert sections into hiddenSectionSize
- QHash<int, int> newHiddenSectionSize; // from logical index to section size
- for (int i = 0; i < logicalFirst; ++i)
- if (isSectionHidden(i))
- newHiddenSectionSize[i] = d->hiddenSectionSize[i];
- for (int j = logicalLast + 1; j < d->sectionCount; ++j)
- if (isSectionHidden(j))
- newHiddenSectionSize[j] = d->hiddenSectionSize[j - insertCount];
- d->hiddenSectionSize = newHiddenSectionSize;
-
- d->doDelayedResizeSections();
- emit sectionCountChanged(oldCount, count());
-
- // if the new sections were not updated by resizing, we need to update now
- if (!d->hasAutoResizeSections())
- d->viewport->update();
-}
-
-/*!
- This slot is called when sections are removed from the \a parent.
- \a logicalFirst and \a logicalLast signify where the sections were removed.
-
- If only one section is removed, \a logicalFirst and \a logicalLast will
- be the same.
-*/
-
-void QHeaderView::sectionsAboutToBeRemoved(const QModelIndex &parent,
- int logicalFirst, int logicalLast)
-{
- Q_UNUSED(parent);
- Q_UNUSED(logicalFirst);
- Q_UNUSED(logicalLast);
-}
-
-void QHeaderViewPrivate::updateHiddenSections(int logicalFirst, int logicalLast)
-{
- Q_Q(QHeaderView);
- const int changeCount = logicalLast - logicalFirst + 1;
-
- // remove sections from hiddenSectionSize
- QHash<int, int> newHiddenSectionSize; // from logical index to section size
- for (int i = 0; i < logicalFirst; ++i)
- if (q->isSectionHidden(i))
- newHiddenSectionSize[i] = hiddenSectionSize[i];
- for (int j = logicalLast + 1; j < sectionCount; ++j)
- if (q->isSectionHidden(j))
- newHiddenSectionSize[j - changeCount] = hiddenSectionSize[j];
- hiddenSectionSize = newHiddenSectionSize;
-
- // remove sections from sectionsHidden
- if (!sectionHidden.isEmpty()) {
- const int newsize = qMin(sectionCount - changeCount, sectionHidden.size());
- QBitArray newSectionHidden(newsize);
- for (int j = 0, k = 0; j < sectionHidden.size(); ++j) {
- const int logical = logicalIndex(j);
- if (logical < logicalFirst || logical > logicalLast) {
- newSectionHidden[k++] = sectionHidden[j];
- }
- }
- sectionHidden = newSectionHidden;
- }
-}
-
-void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent,
- int logicalFirst, int logicalLast)
-{
- Q_Q(QHeaderView);
- if (parent != root)
- return; // we only handle changes in the top level
- if (qMin(logicalFirst, logicalLast) < 0
- || qMax(logicalLast, logicalFirst) >= sectionCount)
- return;
- int oldCount = q->count();
- int changeCount = logicalLast - logicalFirst + 1;
-
- updateHiddenSections(logicalFirst, logicalLast);
-
- if (visualIndices.isEmpty() && logicalIndices.isEmpty()) {
- //Q_ASSERT(headerSectionCount() == sectionCount);
- removeSectionsFromSpans(logicalFirst, logicalLast);
- } else {
- for (int l = logicalLast; l >= logicalFirst; --l) {
- int visual = visualIndices.at(l);
- for (int v = 0; v < sectionCount; ++v) {
- if (v >= logicalIndices.count())
- continue; // the section doesn't exist
- if (v > visual) {
- int logical = logicalIndices.at(v);
- --(visualIndices[logical]);
- }
- if (logicalIndex(v) > l) // no need to move the positions before l
- --(logicalIndices[v]);
- }
- logicalIndices.remove(visual);
- visualIndices.remove(l);
- //Q_ASSERT(headerSectionCount() == sectionCount);
- removeSectionsFromSpans(visual, visual);
- }
- // ### handle sectionSelection, sectionHidden
- }
- sectionCount -= changeCount;
-
- // update sorting column
- if (sortIndicatorSection >= logicalFirst) {
- if (sortIndicatorSection <= logicalLast)
- sortIndicatorSection = -1;
- else
- sortIndicatorSection -= changeCount;
- }
-
- // if we only have the last section (the "end" position) left, the header is empty
- if (sectionCount <= 0)
- clear();
- invalidateCachedSizeHint();
- emit q->sectionCountChanged(oldCount, q->count());
- viewport->update();
-}
-
-void QHeaderViewPrivate::_q_layoutAboutToBeChanged()
-{
- //if there is no row/column we can't have mapping for columns
- //because no QModelIndex in the model would be valid
- // ### this is far from being bullet-proof and we would need a real system to
- // ### map columns or rows persistently
- if ((orientation == Qt::Horizontal && model->rowCount(root) == 0)
- || model->columnCount(root) == 0)
- return;
-
- for (int i = 0; i < sectionHidden.count(); ++i)
- if (sectionHidden.testBit(i)) // ### note that we are using column or row 0
- persistentHiddenSections.append(orientation == Qt::Horizontal
- ? model->index(0, logicalIndex(i), root)
- : model->index(logicalIndex(i), 0, root));
-}
-
-void QHeaderViewPrivate::_q_layoutChanged()
-{
- Q_Q(QHeaderView);
- viewport->update();
- if (persistentHiddenSections.isEmpty() || modelIsEmpty()) {
- if (modelSectionCount() != sectionCount)
- q->initializeSections();
- persistentHiddenSections.clear();
- return;
- }
-
- QBitArray oldSectionHidden = sectionHidden;
- bool sectionCountChanged = false;
-
- for (int i = 0; i < persistentHiddenSections.count(); ++i) {
- QModelIndex index = persistentHiddenSections.at(i);
- if (index.isValid()) {
- const int logical = (orientation == Qt::Horizontal
- ? index.column()
- : index.row());
- q->setSectionHidden(logical, true);
- oldSectionHidden.setBit(logical, false);
- } else if (!sectionCountChanged && (modelSectionCount() != sectionCount)) {
- sectionCountChanged = true;
- break;
- }
- }
- persistentHiddenSections.clear();
-
- for (int i = 0; i < oldSectionHidden.count(); ++i) {
- if (oldSectionHidden.testBit(i))
- q->setSectionHidden(i, false);
- }
-
- // the number of sections changed; we need to reread the state of the model
- if (sectionCountChanged)
- q->initializeSections();
-}
-
-/*!
- \internal
-*/
-
-void QHeaderView::initializeSections()
-{
- Q_D(QHeaderView);
- const int oldCount = d->sectionCount;
- const int newCount = d->modelSectionCount();
- if (newCount <= 0) {
- d->clear();
- emit sectionCountChanged(oldCount, 0);
- } else if (newCount != oldCount) {
- const int min = qBound(0, oldCount, newCount - 1);
- initializeSections(min, newCount - 1);
- if (stretchLastSection()) // we've already gotten the size hint
- d->lastSectionSize = sectionSize(logicalIndex(d->sectionCount - 1));
-
- //make sure we update the hidden sections
- if (newCount < oldCount)
- d->updateHiddenSections(0, newCount-1);
- }
-}
-
-/*!
- \internal
-*/
-
-void QHeaderView::initializeSections(int start, int end)
-{
- Q_D(QHeaderView);
-
- Q_ASSERT(start >= 0);
- Q_ASSERT(end >= 0);
-
- d->invalidateCachedSizeHint();
-
- if (end + 1 < d->sectionCount) {
- int newCount = end + 1;
- d->removeSectionsFromSpans(newCount, d->sectionCount);
- if (!d->hiddenSectionSize.isEmpty()) {
- if (d->sectionCount - newCount > d->hiddenSectionSize.count()) {
- for (int i = end + 1; i < d->sectionCount; ++i)
- d->hiddenSectionSize.remove(i);
- } else {
- QHash<int, int>::iterator it = d->hiddenSectionSize.begin();
- while (it != d->hiddenSectionSize.end()) {
- if (it.key() > end)
- it = d->hiddenSectionSize.erase(it);
- else
- ++it;
- }
- }
- }
- }
-
- int oldCount = d->sectionCount;
- d->sectionCount = end + 1;
-
- if (!d->logicalIndices.isEmpty()) {
- if (oldCount <= d->sectionCount) {
- d->logicalIndices.resize(d->sectionCount);
- d->visualIndices.resize(d->sectionCount);
- for (int i = oldCount; i < d->sectionCount; ++i) {
- d->logicalIndices[i] = i;
- d->visualIndices[i] = i;
- }
- } else {
- int j = 0;
- for (int i = 0; i < oldCount; ++i) {
- int v = d->logicalIndices.at(i);
- if (v < d->sectionCount) {
- d->logicalIndices[j] = v;
- d->visualIndices[v] = j;
- j++;
- }
- }
- d->logicalIndices.resize(d->sectionCount);
- d->visualIndices.resize(d->sectionCount);
- }
- }
-
- if (d->globalResizeMode == Stretch)
- d->stretchSections = d->sectionCount;
- else if (d->globalResizeMode == ResizeToContents)
- d->contentsSections = d->sectionCount;
- if (!d->sectionHidden.isEmpty())
- d->sectionHidden.resize(d->sectionCount);
-
- if (d->sectionCount > oldCount)
- d->createSectionSpan(start, end, (end - start + 1) * d->defaultSectionSize, d->globalResizeMode);
- //Q_ASSERT(d->headerLength() == d->length);
-
- if (d->sectionCount != oldCount)
- emit sectionCountChanged(oldCount, d->sectionCount);
- d->viewport->update();
-}
-
-/*!
- \reimp
-*/
-
-void QHeaderView::currentChanged(const QModelIndex &current, const QModelIndex &old)
-{
- Q_D(QHeaderView);
-
- if (d->orientation == Qt::Horizontal && current.column() != old.column()) {
- if (old.isValid() && old.parent() == d->root)
- d->viewport->update(QRect(sectionViewportPosition(old.column()), 0,
- sectionSize(old.column()), d->viewport->height()));
- if (current.isValid() && current.parent() == d->root)
- d->viewport->update(QRect(sectionViewportPosition(current.column()), 0,
- sectionSize(current.column()), d->viewport->height()));
- } else if (d->orientation == Qt::Vertical && current.row() != old.row()) {
- if (old.isValid() && old.parent() == d->root)
- d->viewport->update(QRect(0, sectionViewportPosition(old.row()),
- d->viewport->width(), sectionSize(old.row())));
- if (current.isValid() && current.parent() == d->root)
- d->viewport->update(QRect(0, sectionViewportPosition(current.row()),
- d->viewport->width(), sectionSize(current.row())));
- }
-}
-
-
-/*!
- \reimp
-*/
-
-bool QHeaderView::event(QEvent *e)
-{
- Q_D(QHeaderView);
- switch (e->type()) {
- case QEvent::HoverEnter: {
- QHoverEvent *he = static_cast<QHoverEvent*>(e);
- d->hover = logicalIndexAt(he->pos());
- if (d->hover != -1)
- updateSection(d->hover);
- break; }
- case QEvent::Leave:
- case QEvent::HoverLeave: {
- if (d->hover != -1)
- updateSection(d->hover);
- d->hover = -1;
- break; }
- case QEvent::HoverMove: {
- QHoverEvent *he = static_cast<QHoverEvent*>(e);
- int oldHover = d->hover;
- d->hover = logicalIndexAt(he->pos());
- if (d->hover != oldHover) {
- if (oldHover != -1)
- updateSection(oldHover);
- if (d->hover != -1)
- updateSection(d->hover);
- }
- break; }
- case QEvent::Timer: {
- QTimerEvent *te = static_cast<QTimerEvent*>(e);
- if (te->timerId() == d->delayedResize.timerId()) {
- d->delayedResize.stop();
- resizeSections();
- }
- break; }
- default:
- break;
- }
- return QAbstractItemView::event(e);
-}
-
-/*!
- \reimp
-*/
-
-void QHeaderView::paintEvent(QPaintEvent *e)
-{
- Q_D(QHeaderView);
-
- if (count() == 0)
- return;
-
- QPainter painter(d->viewport);
- const QPoint offset = d->scrollDelayOffset;
- QRect translatedEventRect = e->rect();
- translatedEventRect.translate(offset);
-
- int start = -1;
- int end = -1;
- if (d->orientation == Qt::Horizontal) {
- start = visualIndexAt(translatedEventRect.left());
- end = visualIndexAt(translatedEventRect.right());
- } else {
- start = visualIndexAt(translatedEventRect.top());
- end = visualIndexAt(translatedEventRect.bottom());
- }
-
- if (d->reverse()) {
- start = (start == -1 ? count() - 1 : start);
- end = (end == -1 ? 0 : end);
- } else {
- start = (start == -1 ? 0 : start);
- end = (end == -1 ? count() - 1 : end);
- }
-
- int tmp = start;
- start = qMin(start, end);
- end = qMax(tmp, end);
-
- d->prepareSectionSelected(); // clear and resize the bit array
-
- QRect currentSectionRect;
- int logical;
- const int width = d->viewport->width();
- const int height = d->viewport->height();
- for (int i = start; i <= end; ++i) {
- if (d->isVisualIndexHidden(i))
- continue;
- painter.save();
- logical = logicalIndex(i);
- if (d->orientation == Qt::Horizontal) {
- currentSectionRect.setRect(sectionViewportPosition(logical), 0, sectionSize(logical), height);
- } else {
- currentSectionRect.setRect(0, sectionViewportPosition(logical), width, sectionSize(logical));
- }
- currentSectionRect.translate(offset);
-
- QVariant variant = d->model->headerData(logical, d->orientation,
- Qt::FontRole);
- if (variant.isValid() && variant.canConvert<QFont>()) {
- QFont sectionFont = qvariant_cast<QFont>(variant);
- painter.setFont(sectionFont);
- }
- paintSection(&painter, currentSectionRect, logical);
- painter.restore();
- }
-
- QStyleOption opt;
- opt.init(this);
- // Paint the area beyond where there are indexes
- if (d->reverse()) {
- opt.state |= QStyle::State_Horizontal;
- if (currentSectionRect.left() > translatedEventRect.left()) {
- opt.rect = QRect(translatedEventRect.left(), 0,
- currentSectionRect.left() - translatedEventRect.left(), height);
- style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
- }
- } else if (currentSectionRect.right() < translatedEventRect.right()) {
- // paint to the right
- opt.state |= QStyle::State_Horizontal;
- opt.rect = QRect(currentSectionRect.right() + 1, 0,
- translatedEventRect.right() - currentSectionRect.right(), height);
- style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
- } else if (currentSectionRect.bottom() < translatedEventRect.bottom()) {
- // paint the bottom section
- opt.state &= ~QStyle::State_Horizontal;
- opt.rect = QRect(0, currentSectionRect.bottom() + 1,
- width, height - currentSectionRect.bottom() - 1);
- style()->drawControl(QStyle::CE_HeaderEmptyArea, &opt, &painter, this);
- }
-
-#if 0
- // ### visualize section spans
- for (int a = 0, i = 0; i < d->sectionSpans.count(); ++i) {
- QColor color((i & 4 ? 255 : 0), (i & 2 ? 255 : 0), (i & 1 ? 255 : 0));
- if (d->orientation == Qt::Horizontal)
- painter.fillRect(a - d->offset, 0, d->sectionSpans.at(i).size, 4, color);
- else
- painter.fillRect(0, a - d->offset, 4, d->sectionSpans.at(i).size, color);
- a += d->sectionSpans.at(i).size;
- }
-
-#endif
-}
-
-/*!
- \reimp
-*/
-
-void QHeaderView::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QHeaderView);
- if (d->state != QHeaderViewPrivate::NoState || e->button() != Qt::LeftButton)
- return;
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
- int handle = d->sectionHandleAt(pos);
- d->originalSize = -1; // clear the stored original size
- if (handle == -1) {
- d->pressed = logicalIndexAt(pos);
- if (d->clickableSections)
- emit sectionPressed(d->pressed);
- if (d->movableSections) {
- d->section = d->target = d->pressed;
- if (d->section == -1)
- return;
- d->state = QHeaderViewPrivate::MoveSection;
- d->setupSectionIndicator(d->section, pos);
- } else if (d->clickableSections && d->pressed != -1) {
- updateSection(d->pressed);
- d->state = QHeaderViewPrivate::SelectSections;
- }
- } else if (resizeMode(handle) == Interactive) {
- d->originalSize = sectionSize(handle);
- d->state = QHeaderViewPrivate::ResizeSection;
- d->section = handle;
- }
-
- d->firstPos = pos;
- d->lastPos = pos;
-
- d->clearCascadingSections();
-}
-
-/*!
- \reimp
-*/
-
-void QHeaderView::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
- if (pos < 0)
- return;
- if (e->buttons() == Qt::NoButton) {
- d->state = QHeaderViewPrivate::NoState;
- d->pressed = -1;
- }
- switch (d->state) {
- case QHeaderViewPrivate::ResizeSection: {
- Q_ASSERT(d->originalSize != -1);
- if (d->cascadingResizing) {
- int delta = d->reverse() ? d->lastPos - pos : pos - d->lastPos;
- int visual = visualIndex(d->section);
- d->cascadingResize(visual, d->headerSectionSize(visual) + delta);
- } else {
- int delta = d->reverse() ? d->firstPos - pos : pos - d->firstPos;
- resizeSection(d->section, qMax(d->originalSize + delta, minimumSectionSize()));
- }
- d->lastPos = pos;
- return;
- }
- case QHeaderViewPrivate::MoveSection: {
- if (qAbs(pos - d->firstPos) >= QApplication::startDragDistance()
- || !d->sectionIndicator->isHidden()) {
- int visual = visualIndexAt(pos);
- if (visual == -1)
- return;
- int posThreshold = d->headerSectionPosition(visual) + d->headerSectionSize(visual) / 2;
- int moving = visualIndex(d->section);
- if (visual < moving) {
- if (pos < posThreshold)
- d->target = d->logicalIndex(visual);
- else
- d->target = d->logicalIndex(visual + 1);
- } else if (visual > moving) {
- if (pos > posThreshold)
- d->target = d->logicalIndex(visual);
- else
- d->target = d->logicalIndex(visual - 1);
- } else {
- d->target = d->section;
- }
- d->updateSectionIndicator(d->section, pos);
- }
- return;
- }
- case QHeaderViewPrivate::SelectSections: {
- int logical = logicalIndexAt(pos);
- if (logical == d->pressed)
- return; // nothing to do
- else if (d->pressed != -1)
- updateSection(d->pressed);
- d->pressed = logical;
- if (d->clickableSections && logical != -1) {
- emit sectionEntered(d->pressed);
- updateSection(d->pressed);
- }
- return;
- }
- case QHeaderViewPrivate::NoState: {
-#ifndef QT_NO_CURSOR
- int handle = d->sectionHandleAt(pos);
- bool hasCursor = testAttribute(Qt::WA_SetCursor);
- if (handle != -1 && (resizeMode(handle) == Interactive)) {
- if (!hasCursor)
- setCursor(d->orientation == Qt::Horizontal ? Qt::SplitHCursor : Qt::SplitVCursor);
- } else if (hasCursor) {
- unsetCursor();
- }
-#endif
- return;
- }
- default:
- break;
- }
-}
-
-/*!
- \reimp
-*/
-
-void QHeaderView::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
- switch (d->state) {
- case QHeaderViewPrivate::MoveSection:
- if (!d->sectionIndicator->isHidden()) { // moving
- int from = visualIndex(d->section);
- Q_ASSERT(from != -1);
- int to = visualIndex(d->target);
- Q_ASSERT(to != -1);
- moveSection(from, to);
- d->section = d->target = -1;
- d->updateSectionIndicator(d->section, pos);
- break;
- } // not moving
- case QHeaderViewPrivate::SelectSections:
- if (!d->clickableSections) {
- int section = logicalIndexAt(pos);
- updateSection(section);
- }
- // fall through
- case QHeaderViewPrivate::NoState:
- if (d->clickableSections) {
- int section = logicalIndexAt(pos);
- if (section != -1 && section == d->pressed) {
- d->flipSortIndicator(section);
- emit sectionClicked(section);
- }
- if (d->pressed != -1)
- updateSection(d->pressed);
- }
- break;
- case QHeaderViewPrivate::ResizeSection:
- d->originalSize = -1;
- d->clearCascadingSections();
- break;
- default:
- break;
- }
- d->state = QHeaderViewPrivate::NoState;
- d->pressed = -1;
-}
-
-/*!
- \reimp
-*/
-
-void QHeaderView::mouseDoubleClickEvent(QMouseEvent *e)
-{
- Q_D(QHeaderView);
- int pos = d->orientation == Qt::Horizontal ? e->x() : e->y();
- int handle = d->sectionHandleAt(pos);
- if (handle > -1 && resizeMode(handle) == Interactive) {
- emit sectionHandleDoubleClicked(handle);
-#ifndef QT_NO_CURSOR
- Qt::CursorShape splitCursor = (d->orientation == Qt::Horizontal)
- ? Qt::SplitHCursor : Qt::SplitVCursor;
- if (cursor().shape() == splitCursor) {
- // signal handlers may have changed the section size
- handle = d->sectionHandleAt(pos);
- if (!(handle > -1 && resizeMode(handle) == Interactive))
- setCursor(Qt::ArrowCursor);
- }
-#endif
- } else {
- emit sectionDoubleClicked(logicalIndexAt(e->pos()));
- }
-}
-
-/*!
- \reimp
-*/
-
-bool QHeaderView::viewportEvent(QEvent *e)
-{
- Q_D(QHeaderView);
- switch (e->type()) {
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTip: {
- QHelpEvent *he = static_cast<QHelpEvent*>(e);
- int logical = logicalIndexAt(he->pos());
- if (logical != -1) {
- QVariant variant = d->model->headerData(logical, d->orientation, Qt::ToolTipRole);
- if (variant.isValid()) {
- QToolTip::showText(he->globalPos(), variant.toString(), this);
- return true;
- }
- }
- break; }
-#endif
-#ifndef QT_NO_WHATSTHIS
- case QEvent::QueryWhatsThis: {
- QHelpEvent *he = static_cast<QHelpEvent*>(e);
- int logical = logicalIndexAt(he->pos());
- if (logical != -1
- && d->model->headerData(logical, d->orientation, Qt::WhatsThisRole).isValid())
- return true;
- break; }
- case QEvent::WhatsThis: {
- QHelpEvent *he = static_cast<QHelpEvent*>(e);
- int logical = logicalIndexAt(he->pos());
- if (logical != -1) {
- QVariant whatsthis = d->model->headerData(logical, d->orientation,
- Qt::WhatsThisRole);
- if (whatsthis.isValid()) {
- QWhatsThis::showText(he->globalPos(), whatsthis.toString(), this);
- return true;
- }
- }
- break; }
-#endif // QT_NO_WHATSTHIS
-#ifndef QT_NO_STATUSTIP
- case QEvent::StatusTip: {
- QHelpEvent *he = static_cast<QHelpEvent*>(e);
- int logical = logicalIndexAt(he->pos());
- if (logical != -1) {
- QString statustip = d->model->headerData(logical, d->orientation,
- Qt::StatusTipRole).toString();
- if (!statustip.isEmpty())
- setStatusTip(statustip);
- }
- return true; }
-#endif // QT_NO_STATUSTIP
- case QEvent::Hide:
- case QEvent::Show:
- case QEvent::FontChange:
- case QEvent::StyleChange:
- d->invalidateCachedSizeHint();
- resizeSections();
- emit geometriesChanged();
- break;
- case QEvent::ContextMenu: {
- d->state = QHeaderViewPrivate::NoState;
- d->pressed = d->section = d->target = -1;
- d->updateSectionIndicator(d->section, -1);
- break; }
- case QEvent::Wheel: {
- QAbstractScrollArea *asa = qobject_cast<QAbstractScrollArea *>(parentWidget());
- if (asa)
- return QApplication::sendEvent(asa->viewport(), e);
- break; }
- default:
- break;
- }
- return QAbstractItemView::viewportEvent(e);
-}
-
-/*!
- Paints the section specified by the given \a logicalIndex, using the given
- \a painter and \a rect.
-
- Normally, you do not have to call this function.
-*/
-
-void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
-{
- Q_D(const QHeaderView);
- if (!rect.isValid())
- return;
- // get the state of the section
- QStyleOptionHeader opt;
- initStyleOption(&opt);
- QStyle::State state = QStyle::State_None;
- if (isEnabled())
- state |= QStyle::State_Enabled;
- if (window()->isActiveWindow())
- state |= QStyle::State_Active;
- if (d->clickableSections) {
- if (logicalIndex == d->hover)
- state |= QStyle::State_MouseOver;
- if (logicalIndex == d->pressed)
- state |= QStyle::State_Sunken;
- else if (d->highlightSelected) {
- if (d->sectionIntersectsSelection(logicalIndex))
- state |= QStyle::State_On;
- if (d->isSectionSelected(logicalIndex))
- state |= QStyle::State_Sunken;
- }
-
- }
- if (isSortIndicatorShown() && sortIndicatorSection() == logicalIndex)
- opt.sortIndicator = (sortIndicatorOrder() == Qt::AscendingOrder)
- ? QStyleOptionHeader::SortDown : QStyleOptionHeader::SortUp;
-
- // setup the style options structure
- QVariant textAlignment = d->model->headerData(logicalIndex, d->orientation,
- Qt::TextAlignmentRole);
- opt.rect = rect;
- opt.section = logicalIndex;
- opt.state |= state;
- opt.textAlignment = Qt::Alignment(textAlignment.isValid()
- ? Qt::Alignment(textAlignment.toInt())
- : d->defaultAlignment);
-
- opt.iconAlignment = Qt::AlignVCenter;
- opt.text = d->model->headerData(logicalIndex, d->orientation,
- Qt::DisplayRole).toString();
- if (d->textElideMode != Qt::ElideNone)
- opt.text = opt.fontMetrics.elidedText(opt.text, d->textElideMode , rect.width() - 4);
-
- QVariant variant = d->model->headerData(logicalIndex, d->orientation,
- Qt::DecorationRole);
- opt.icon = qvariant_cast<QIcon>(variant);
- if (opt.icon.isNull())
- opt.icon = qvariant_cast<QPixmap>(variant);
- QVariant foregroundBrush = d->model->headerData(logicalIndex, d->orientation,
- Qt::ForegroundRole);
- if (foregroundBrush.canConvert<QBrush>())
- opt.palette.setBrush(QPalette::ButtonText, qvariant_cast<QBrush>(foregroundBrush));
-
- QPointF oldBO = painter->brushOrigin();
- QVariant backgroundBrush = d->model->headerData(logicalIndex, d->orientation,
- Qt::BackgroundRole);
- if (backgroundBrush.canConvert<QBrush>()) {
- opt.palette.setBrush(QPalette::Button, qvariant_cast<QBrush>(backgroundBrush));
- opt.palette.setBrush(QPalette::Window, qvariant_cast<QBrush>(backgroundBrush));
- painter->setBrushOrigin(opt.rect.topLeft());
- }
-
- // the section position
- int visual = visualIndex(logicalIndex);
- Q_ASSERT(visual != -1);
- if (count() == 1)
- opt.position = QStyleOptionHeader::OnlyOneSection;
- else if (visual == 0)
- opt.position = QStyleOptionHeader::Beginning;
- else if (visual == count() - 1)
- opt.position = QStyleOptionHeader::End;
- else
- opt.position = QStyleOptionHeader::Middle;
- opt.orientation = d->orientation;
- // the selected position
- bool previousSelected = d->isSectionSelected(this->logicalIndex(visual - 1));
- bool nextSelected = d->isSectionSelected(this->logicalIndex(visual + 1));
- if (previousSelected && nextSelected)
- opt.selectedPosition = QStyleOptionHeader::NextAndPreviousAreSelected;
- else if (previousSelected)
- opt.selectedPosition = QStyleOptionHeader::PreviousIsSelected;
- else if (nextSelected)
- opt.selectedPosition = QStyleOptionHeader::NextIsSelected;
- else
- opt.selectedPosition = QStyleOptionHeader::NotAdjacent;
- // draw the section
- style()->drawControl(QStyle::CE_Header, &opt, painter, this);
-
- painter->setBrushOrigin(oldBO);
-}
-
-/*!
- Returns the size of the contents of the section specified by the given
- \a logicalIndex.
-
- \sa defaultSectionSize()
-*/
-
-QSize QHeaderView::sectionSizeFromContents(int logicalIndex) const
-{
- Q_D(const QHeaderView);
- Q_ASSERT(logicalIndex >= 0);
-
- ensurePolished();
-
- // use SizeHintRole
- QVariant variant = d->model->headerData(logicalIndex, d->orientation, Qt::SizeHintRole);
- if (variant.isValid())
- return qvariant_cast<QSize>(variant);
-
- // otherwise use the contents
- QStyleOptionHeader opt;
- initStyleOption(&opt);
- opt.section = logicalIndex;
- QVariant var = d->model->headerData(logicalIndex, d->orientation,
- Qt::FontRole);
- QFont fnt;
- if (var.isValid() && var.canConvert<QFont>())
- fnt = qvariant_cast<QFont>(var);
- else
- fnt = font();
- fnt.setBold(true);
- opt.fontMetrics = QFontMetrics(fnt);
- opt.text = d->model->headerData(logicalIndex, d->orientation,
- Qt::DisplayRole).toString();
- variant = d->model->headerData(logicalIndex, d->orientation, Qt::DecorationRole);
- opt.icon = qvariant_cast<QIcon>(variant);
- if (opt.icon.isNull())
- opt.icon = qvariant_cast<QPixmap>(variant);
- QSize size = style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), this);
- if (isSortIndicatorShown()) {
- int margin = style()->pixelMetric(QStyle::PM_HeaderMargin, &opt, this);
- if (d->orientation == Qt::Horizontal)
- size.rwidth() += size.height() + margin;
- else
- size.rheight() += size.width() + margin;
- }
- return size;
-}
-
-/*!
- Returns the horizontal offset of the header. This is 0 for vertical
- headers.
-
- \sa offset()
-*/
-
-int QHeaderView::horizontalOffset() const
-{
- Q_D(const QHeaderView);
- if (d->orientation == Qt::Horizontal)
- return d->offset;
- return 0;
-}
-
-/*!
- Returns the vertical offset of the header. This is 0 for horizontal
- headers.
-
- \sa offset()
-*/
-
-int QHeaderView::verticalOffset() const
-{
- Q_D(const QHeaderView);
- if (d->orientation == Qt::Vertical)
- return d->offset;
- return 0;
-}
-
-/*!
- \reimp
- \internal
-*/
-
-void QHeaderView::updateGeometries()
-{
- Q_D(QHeaderView);
- d->layoutChildren();
- if (d->hasAutoResizeSections())
- d->doDelayedResizeSections();
-}
-
-/*!
- \reimp
- \internal
-*/
-
-void QHeaderView::scrollContentsBy(int dx, int dy)
-{
- Q_D(QHeaderView);
- d->scrollDirtyRegion(dx, dy);
-}
-
-/*!
- \reimp
- \internal
-*/
-void QHeaderView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- Q_D(QHeaderView);
- d->invalidateCachedSizeHint();
- if (d->hasAutoResizeSections()) {
- bool resizeRequired = d->globalResizeMode == ResizeToContents;
- int first = orientation() == Qt::Horizontal ? topLeft.column() : topLeft.row();
- int last = orientation() == Qt::Horizontal ? bottomRight.column() : bottomRight.row();
- for (int i = first; i <= last && !resizeRequired; ++i)
- resizeRequired = (resizeMode(i) == ResizeToContents);
- if (resizeRequired)
- d->doDelayedResizeSections();
- }
-}
-
-/*!
- \reimp
- \internal
-
- Empty implementation because the header doesn't show QModelIndex items.
-*/
-void QHeaderView::rowsInserted(const QModelIndex &, int, int)
-{
- // do nothing
-}
-
-/*!
- \reimp
- \internal
-
- Empty implementation because the header doesn't show QModelIndex items.
-*/
-
-QRect QHeaderView::visualRect(const QModelIndex &) const
-{
- return QRect();
-}
-
-/*!
- \reimp
- \internal
-
- Empty implementation because the header doesn't show QModelIndex items.
-*/
-
-void QHeaderView::scrollTo(const QModelIndex &, ScrollHint)
-{
- // do nothing - the header only displays sections
-}
-
-/*!
- \reimp
- \internal
-
- Empty implementation because the header doesn't show QModelIndex items.
-*/
-
-QModelIndex QHeaderView::indexAt(const QPoint &) const
-{
- return QModelIndex();
-}
-
-/*!
- \reimp
- \internal
-
- Empty implementation because the header doesn't show QModelIndex items.
-*/
-
-bool QHeaderView::isIndexHidden(const QModelIndex &) const
-{
- return true; // the header view has no items, just sections
-}
-
-/*!
- \reimp
- \internal
-
- Empty implementation because the header doesn't show QModelIndex items.
-*/
-
-QModelIndex QHeaderView::moveCursor(CursorAction, Qt::KeyboardModifiers)
-{
- return QModelIndex();
-}
-
-/*!
- \reimp
-
- Selects the items in the given \a rect according to the specified
- \a flags.
-
- The base class implementation does nothing.
-*/
-
-void QHeaderView::setSelection(const QRect&, QItemSelectionModel::SelectionFlags)
-{
- // do nothing
-}
-
-/*!
- \internal
-*/
-
-QRegion QHeaderView::visualRegionForSelection(const QItemSelection &selection) const
-{
- Q_D(const QHeaderView);
- const int max = d->modelSectionCount();
- if (d->orientation == Qt::Horizontal) {
- int left = max;
- int right = 0;
- int rangeLeft, rangeRight;
-
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange r = selection.at(i);
- if (r.parent().isValid() || !r.isValid())
- continue; // we only know about toplevel items and we don't want invalid ranges
- // FIXME an item inside the range may be the leftmost or rightmost
- rangeLeft = visualIndex(r.left());
- if (rangeLeft == -1) // in some cases users may change the selections
- continue; // before we have a chance to do the layout
- rangeRight = visualIndex(r.right());
- if (rangeRight == -1) // in some cases users may change the selections
- continue; // before we have a chance to do the layout
- if (rangeLeft < left)
- left = rangeLeft;
- if (rangeRight > right)
- right = rangeRight;
- }
-
- int logicalLeft = logicalIndex(left);
- int logicalRight = logicalIndex(right);
-
- if (logicalLeft < 0 || logicalLeft >= count() ||
- logicalRight < 0 || logicalRight >= count())
- return QRegion();
-
- int leftPos = sectionViewportPosition(logicalLeft);
- int rightPos = sectionViewportPosition(logicalRight);
- rightPos += sectionSize(logicalRight);
- return QRect(leftPos, 0, rightPos - leftPos, height());
- }
- // orientation() == Qt::Vertical
- int top = max;
- int bottom = 0;
- int rangeTop, rangeBottom;
-
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange r = selection.at(i);
- if (r.parent().isValid() || !r.isValid())
- continue; // we only know about toplevel items
- // FIXME an item inside the range may be the leftmost or rightmost
- rangeTop = visualIndex(r.top());
- if (rangeTop == -1) // in some cases users may change the selections
- continue; // before we have a chance to do the layout
- rangeBottom = visualIndex(r.bottom());
- if (rangeBottom == -1) // in some cases users may change the selections
- continue; // before we have a chance to do the layout
- if (rangeTop < top)
- top = rangeTop;
- if (rangeBottom > bottom)
- bottom = rangeBottom;
- }
-
- int logicalTop = logicalIndex(top);
- int logicalBottom = logicalIndex(bottom);
-
- if (logicalTop == -1 || logicalBottom == -1)
- return QRect();
-
- int topPos = sectionViewportPosition(logicalTop);
- int bottomPos = sectionViewportPosition(logicalBottom) + sectionSize(logicalBottom);
-
- return QRect(0, topPos, width(), bottomPos - topPos);
-}
-
-
-// private implementation
-
-int QHeaderViewPrivate::sectionHandleAt(int position)
-{
- Q_Q(QHeaderView);
- int visual = q->visualIndexAt(position);
- if (visual == -1)
- return -1;
- int log = logicalIndex(visual);
- int pos = q->sectionViewportPosition(log);
- int grip = q->style()->pixelMetric(QStyle::PM_HeaderGripMargin, 0, q);
-
- bool atLeft = position < pos + grip;
- bool atRight = (position > pos + q->sectionSize(log) - grip);
- if (reverse())
- qSwap(atLeft, atRight);
-
- if (atLeft) {
- //grip at the beginning of the section
- while(visual > -1) {
- int logical = q->logicalIndex(--visual);
- if (!q->isSectionHidden(logical))
- return logical;
- }
- } else if (atRight) {
- //grip at the end of the section
- return log;
- }
- return -1;
-}
-
-void QHeaderViewPrivate::setupSectionIndicator(int section, int position)
-{
- Q_Q(QHeaderView);
- if (!sectionIndicator) {
- sectionIndicator = new QLabel(viewport);
- }
-
- int w, h;
- int p = q->sectionViewportPosition(section);
- if (orientation == Qt::Horizontal) {
- w = q->sectionSize(section);
- h = viewport->height();
- } else {
- w = viewport->width();
- h = q->sectionSize(section);
- }
- sectionIndicator->resize(w, h);
-
- QPixmap pm(w, h);
- pm.fill(QColor(0, 0, 0, 45));
- QRect rect(0, 0, w, h);
-
- QPainter painter(&pm);
- painter.setOpacity(0.75);
- q->paintSection(&painter, rect, section);
- painter.end();
-
- sectionIndicator->setPixmap(pm);
- sectionIndicatorOffset = position - qMax(p, 0);
-}
-
-void QHeaderViewPrivate::updateSectionIndicator(int section, int position)
-{
- if (!sectionIndicator)
- return;
-
- if (section == -1 || target == -1) {
- sectionIndicator->hide();
- return;
- }
-
- if (orientation == Qt::Horizontal)
- sectionIndicator->move(position - sectionIndicatorOffset, 0);
- else
- sectionIndicator->move(0, position - sectionIndicatorOffset);
-
- sectionIndicator->show();
-}
-
-/*!
- Initialize \a option with the values from this QHeaderView. This method is
- useful for subclasses when they need a QStyleOptionHeader, but do not want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QHeaderView::initStyleOption(QStyleOptionHeader *option) const
-{
- Q_D(const QHeaderView);
- option->initFrom(this);
- option->state = QStyle::State_None | QStyle::State_Raised;
- option->orientation = d->orientation;
- if (d->orientation == Qt::Horizontal)
- option->state |= QStyle::State_Horizontal;
- if (isEnabled())
- option->state |= QStyle::State_Enabled;
- option->section = 0;
-}
-
-bool QHeaderViewPrivate::isSectionSelected(int section) const
-{
- int i = section * 2;
- if (i < 0 || i >= sectionSelected.count())
- return false;
- if (sectionSelected.testBit(i)) // if the value was cached
- return sectionSelected.testBit(i + 1);
- bool s = false;
- if (orientation == Qt::Horizontal)
- s = isColumnSelected(section);
- else
- s = isRowSelected(section);
- sectionSelected.setBit(i + 1, s); // selection state
- sectionSelected.setBit(i, true); // cache state
- return s;
-}
-
-/*!
- \internal
- Returns the last visible (ie. not hidden) visual index
-*/
-int QHeaderViewPrivate::lastVisibleVisualIndex() const
-{
- Q_Q(const QHeaderView);
- for (int visual = q->count()-1; visual >= 0; --visual) {
- if (!q->isSectionHidden(q->logicalIndex(visual)))
- return visual;
- }
-
- //default value if no section is actually visible
- return -1;
-}
-
-/*!
- \internal
- Go through and resize all of the sections applying stretchLastSection,
- manualy stretches, sizes, and useGlobalMode.
-
- The different resize modes are:
- Interactive - the user decides the size
- Stretch - take up whatever space is left
- Fixed - the size is set programmatically outside the header
- ResizeToContentes - the size is set based on the contents of the row or column in the parent view
-
- The resize mode will not affect the last section if stretchLastSection is true.
-*/
-void QHeaderViewPrivate::resizeSections(QHeaderView::ResizeMode globalMode, bool useGlobalMode)
-{
- Q_Q(QHeaderView);
- //stop the timer in case it is delayed
- delayedResize.stop();
-
- executePostedLayout();
- if (sectionCount == 0)
- return;
-
- if (resizeRecursionBlock)
- return;
- resizeRecursionBlock = true;
-
- invalidateCachedSizeHint();
-
- const int lastVisibleSection = lastVisibleVisualIndex();
-
- // find stretchLastSection if we have it
- int stretchSection = -1;
- if (stretchLastSection && !useGlobalMode)
- stretchSection = lastVisibleVisualIndex();
-
- // count up the number of strected sections and how much space left for them
- int lengthToStrech = (orientation == Qt::Horizontal ? viewport->width() : viewport->height());
- int numberOfStretchedSections = 0;
- QList<int> section_sizes;
- for (int i = 0; i < sectionCount; ++i) {
- if (isVisualIndexHidden(i))
- continue;
-
- QHeaderView::ResizeMode resizeMode;
- if (useGlobalMode && (i != stretchSection))
- resizeMode = globalMode;
- else
- resizeMode = (i == stretchSection ? QHeaderView::Stretch : headerSectionResizeMode(i));
-
- if (resizeMode == QHeaderView::Stretch) {
- ++numberOfStretchedSections;
- section_sizes.append(headerSectionSize(i));
- continue;
- }
-
- // because it isn't stretch, determine its width and remove that from lengthToStrech
- int sectionSize = 0;
- if (resizeMode == QHeaderView::Interactive || resizeMode == QHeaderView::Fixed) {
- sectionSize = headerSectionSize(i);
- } else { // resizeMode == QHeaderView::ResizeToContents
- int logicalIndex = q->logicalIndex(i);
- sectionSize = qMax(viewSectionSizeHint(logicalIndex),
- q->sectionSizeHint(logicalIndex));
- }
- section_sizes.append(sectionSize);
- lengthToStrech -= sectionSize;
- }
-
- // calculate the new length for all of the stretched sections
- int stretchSectionLength = -1;
- int pixelReminder = 0;
- if (numberOfStretchedSections > 0 && lengthToStrech > 0) { // we have room to stretch in
- int hintLengthForEveryStretchedSection = lengthToStrech / numberOfStretchedSections;
- stretchSectionLength = qMax(hintLengthForEveryStretchedSection, q->minimumSectionSize());
- pixelReminder = lengthToStrech % numberOfStretchedSections;
- }
-
- int spanStartSection = 0;
- int previousSectionLength = 0;
-
- QHeaderView::ResizeMode previousSectionResizeMode = QHeaderView::Interactive;
-
- // resize each section along the total length
- for (int i = 0; i < sectionCount; ++i) {
- int oldSectionLength = headerSectionSize(i);
- int newSectionLength = -1;
- QHeaderView::ResizeMode newSectionResizeMode = headerSectionResizeMode(i);
-
- if (isVisualIndexHidden(i)) {
- newSectionLength = 0;
- } else {
- QHeaderView::ResizeMode resizeMode;
- if (useGlobalMode)
- resizeMode = globalMode;
- else
- resizeMode = (i == stretchSection
- ? QHeaderView::Stretch
- : newSectionResizeMode);
- if (resizeMode == QHeaderView::Stretch && stretchSectionLength != -1) {
- if (i == lastVisibleSection)
- newSectionLength = qMax(stretchSectionLength, lastSectionSize);
- else
- newSectionLength = stretchSectionLength;
- if (pixelReminder > 0) {
- newSectionLength += 1;
- --pixelReminder;
- }
- section_sizes.removeFirst();
- } else {
- newSectionLength = section_sizes.front();
- section_sizes.removeFirst();
- }
- }
-
- //Q_ASSERT(newSectionLength > 0);
- if ((previousSectionResizeMode != newSectionResizeMode
- || previousSectionLength != newSectionLength) && i > 0) {
- int spanLength = (i - spanStartSection) * previousSectionLength;
- createSectionSpan(spanStartSection, i - 1, spanLength, previousSectionResizeMode);
- //Q_ASSERT(headerLength() == length);
- spanStartSection = i;
- }
-
- if (newSectionLength != oldSectionLength)
- emit q->sectionResized(logicalIndex(i), oldSectionLength, newSectionLength);
-
- previousSectionLength = newSectionLength;
- previousSectionResizeMode = newSectionResizeMode;
- }
-
- createSectionSpan(spanStartSection, sectionCount - 1,
- (sectionCount - spanStartSection) * previousSectionLength,
- previousSectionResizeMode);
- //Q_ASSERT(headerLength() == length);
- resizeRecursionBlock = false;
- viewport->update();
-}
-
-void QHeaderViewPrivate::createSectionSpan(int start, int end, int size, QHeaderView::ResizeMode mode)
-{
- // ### the code for merging spans does not merge at all opertuneties
- // ### what if the number of sections is reduced ?
-
- SectionSpan span(size, (end - start) + 1, mode);
- int start_section = 0;
-#ifndef QT_NO_DEBUG
- int initial_section_count = headerSectionCount(); // ### debug code
-#endif
-
- QList<int> spansToRemove;
- for (int i = 0; i < sectionSpans.count(); ++i) {
- int end_section = start_section + sectionSpans.at(i).count - 1;
- int section_count = sectionSpans.at(i).count;
- if (start <= start_section && end > end_section) {
- // the existing span is entirely coveded by the new span
- spansToRemove.append(i);
- } else if (start < start_section && end >= end_section) {
- // the existing span is entirely coveded by the new span
- spansToRemove.append(i);
- } else if (start == start_section && end == end_section) {
- // the new span is covered by an existin span
- length -= sectionSpans.at(i).size;
- length += size;
- sectionSpans[i].size = size;
- sectionSpans[i].resizeMode = mode;
- // ### check if we can merge the section with any of its neighbours
- removeSpans(spansToRemove);
- Q_ASSERT(initial_section_count == headerSectionCount());
- return;
- } else if (start > start_section && end < end_section) {
- if (sectionSpans.at(i).sectionSize() == span.sectionSize()
- && sectionSpans.at(i).resizeMode == span.resizeMode) {
- Q_ASSERT(initial_section_count == headerSectionCount());
- return;
- }
- // the new span is in the middle of the old span, so we have to split it
- length -= sectionSpans.at(i).size;
- int section_size = sectionSpans.at(i).sectionSize();
-#ifndef QT_NO_DEBUG
- int span_count = sectionSpans.at(i).count;
-#endif
- QHeaderView::ResizeMode span_mode = sectionSpans.at(i).resizeMode;
- // first span
- int first_span_count = start - start_section;
- int first_span_size = section_size * first_span_count;
- sectionSpans[i].count = first_span_count;
- sectionSpans[i].size = first_span_size;
- sectionSpans[i].resizeMode = span_mode;
- length += first_span_size;
- // middle span (the new span)
-#ifndef QT_NO_DEBUG
- int mid_span_count = span.count;
-#endif
- int mid_span_size = span.size;
- sectionSpans.insert(i + 1, span);
- length += mid_span_size;
- // last span
- int last_span_count = end_section - end;
- int last_span_size = section_size * last_span_count;
- sectionSpans.insert(i + 2, SectionSpan(last_span_size, last_span_count, span_mode));
- length += last_span_size;
- Q_ASSERT(span_count == first_span_count + mid_span_count + last_span_count);
- removeSpans(spansToRemove);
- Q_ASSERT(initial_section_count == headerSectionCount());
- return;
- } else if (start > start_section && start <= end_section && end >= end_section) {
- // the new span covers the last part of the existing span
- length -= sectionSpans.at(i).size;
- int removed_count = (end_section - start + 1);
- int span_count = sectionSpans.at(i).count - removed_count;
- int section_size = sectionSpans.at(i).sectionSize();
- int span_size = section_size * span_count;
- sectionSpans[i].count = span_count;
- sectionSpans[i].size = span_size;
- length += span_size;
- if (end == end_section) {
- sectionSpans.insert(i + 1, span); // insert after
- length += span.size;
- removeSpans(spansToRemove);
- Q_ASSERT(initial_section_count == headerSectionCount());
- return;
- }
- } else if (end < end_section && end >= start_section && start <= start_section) {
- // the new span covers the first part of the existing span
- length -= sectionSpans.at(i).size;
- int removed_count = (end - start_section + 1);
- int section_size = sectionSpans.at(i).sectionSize();
- int span_count = sectionSpans.at(i).count - removed_count;
- int span_size = section_size * span_count;
- sectionSpans[i].count = span_count;
- sectionSpans[i].size = span_size;
- length += span_size;
- sectionSpans.insert(i, span); // insert before
- length += span.size;
- removeSpans(spansToRemove);
- Q_ASSERT(initial_section_count == headerSectionCount());
- return;
- }
- start_section += section_count;
- }
-
- // ### adding and removing _ sections_ in addition to spans
- // ### add some more checks here
-
- if (spansToRemove.isEmpty()) {
- if (!sectionSpans.isEmpty()
- && sectionSpans.last().sectionSize() == span.sectionSize()
- && sectionSpans.last().resizeMode == span.resizeMode) {
- length += span.size;
- int last = sectionSpans.count() - 1;
- sectionSpans[last].count += span.count;
- sectionSpans[last].size += span.size;
- sectionSpans[last].resizeMode = span.resizeMode;
- } else {
- length += span.size;
- sectionSpans.append(span);
- }
- } else {
- removeSpans(spansToRemove);
- length += span.size;
- sectionSpans.insert(spansToRemove.first(), span);
- //Q_ASSERT(initial_section_count == headerSectionCount());
- }
-}
-
-void QHeaderViewPrivate::removeSectionsFromSpans(int start, int end)
-{
- // remove sections
- int start_section = 0;
- QList<int> spansToRemove;
- for (int i = 0; i < sectionSpans.count(); ++i) {
- int end_section = start_section + sectionSpans.at(i).count - 1;
- int section_size = sectionSpans.at(i).sectionSize();
- int section_count = sectionSpans.at(i).count;
- if (start <= start_section && end >= end_section) {
- // the change covers the entire span
- spansToRemove.append(i);
- if (end == end_section)
- break;
- } else if (start > start_section && end < end_section) {
- // all the removed sections are inside the span
- int change = (end - start + 1);
- sectionSpans[i].count -= change;
- sectionSpans[i].size = section_size * sectionSpans.at(i).count;
- length -= (change * section_size);
- break;
- } else if (start >= start_section && start <= end_section) {
- // the some of the removed sections are inside the span,at the end
- int change = qMin(end_section - start + 1, end - start + 1);
- sectionSpans[i].count -= change;
- sectionSpans[i].size = section_size * sectionSpans.at(i).count;
- start += change;
- length -= (change * section_size);
- // the change affects several spans
- } else if (end >= start_section && end <= end_section) {
- // the some of the removed sections are inside the span, at the beginning
- int change = qMin((end - start_section + 1), end - start + 1);
- sectionSpans[i].count -= change;
- sectionSpans[i].size = section_size * sectionSpans.at(i).count;
- length -= (change * section_size);
- break;
- }
- start_section += section_count;
- }
-
- for (int i = spansToRemove.count() - 1; i >= 0; --i) {
- int s = spansToRemove.at(i);
- length -= sectionSpans.at(s).size;
- sectionSpans.remove(s);
- // ### merge remaining spans
- }
-}
-
-void QHeaderViewPrivate::clear()
-{
- if (state != NoClear) {
- length = 0;
- sectionCount = 0;
- visualIndices.clear();
- logicalIndices.clear();
- sectionSelected.clear();
- sectionHidden.clear();
- hiddenSectionSize.clear();
- sectionSpans.clear();
- }
-}
-
-void QHeaderViewPrivate::flipSortIndicator(int section)
-{
- Q_Q(QHeaderView);
- Qt::SortOrder sortOrder;
- if (sortIndicatorSection == section) {
- sortOrder = (sortIndicatorOrder == Qt::DescendingOrder) ? Qt::AscendingOrder : Qt::DescendingOrder;
- } else {
- const QVariant value = model->headerData(section, orientation, Qt::InitialSortOrderRole);
- if (value.canConvert(QVariant::Int))
- sortOrder = static_cast<Qt::SortOrder>(value.toInt());
- else
- sortOrder = Qt::AscendingOrder;
- }
- q->setSortIndicator(section, sortOrder);
-}
-
-void QHeaderViewPrivate::cascadingResize(int visual, int newSize)
-{
- Q_Q(QHeaderView);
- const int minimumSize = q->minimumSectionSize();
- const int oldSize = headerSectionSize(visual);
- int delta = newSize - oldSize;
-
- if (delta > 0) { // larger
- bool sectionResized = false;
-
- // restore old section sizes
- for (int i = firstCascadingSection; i < visual; ++i) {
- if (cascadingSectionSize.contains(i)) {
- int currentSectionSize = headerSectionSize(i);
- int originalSectionSize = cascadingSectionSize.value(i);
- if (currentSectionSize < originalSectionSize) {
- int newSectionSize = currentSectionSize + delta;
- resizeSectionSpan(i, currentSectionSize, newSectionSize);
- if (newSectionSize >= originalSectionSize && false)
- cascadingSectionSize.remove(i); // the section is now restored
- sectionResized = true;
- break;
- }
- }
-
- }
-
- // resize the section
- if (!sectionResized) {
- newSize = qMax(newSize, minimumSize);
- if (oldSize != newSize)
- resizeSectionSpan(visual, oldSize, newSize);
- }
-
- // cascade the section size change
- for (int i = visual + 1; i < sectionCount; ++i) {
- if (!sectionIsCascadable(i))
- continue;
- int currentSectionSize = headerSectionSize(i);
- if (currentSectionSize <= minimumSize)
- continue;
- int newSectionSize = qMax(currentSectionSize - delta, minimumSize);
- //qDebug() << "### cascading to" << i << newSectionSize - currentSectionSize << delta;
- resizeSectionSpan(i, currentSectionSize, newSectionSize);
- saveCascadingSectionSize(i, currentSectionSize);
- delta = delta - (currentSectionSize - newSectionSize);
- //qDebug() << "new delta" << delta;
- //if (newSectionSize != minimumSize)
- if (delta <= 0)
- break;
- }
- } else { // smaller
- bool sectionResized = false;
-
- // restore old section sizes
- for (int i = lastCascadingSection; i > visual; --i) {
- if (!cascadingSectionSize.contains(i))
- continue;
- int currentSectionSize = headerSectionSize(i);
- int originalSectionSize = cascadingSectionSize.value(i);
- if (currentSectionSize >= originalSectionSize)
- continue;
- int newSectionSize = currentSectionSize - delta;
- resizeSectionSpan(i, currentSectionSize, newSectionSize);
- if (newSectionSize >= originalSectionSize && false) {
- //qDebug() << "section" << i << "restored to" << originalSectionSize;
- cascadingSectionSize.remove(i); // the section is now restored
- }
- sectionResized = true;
- break;
- }
-
- // resize the section
- resizeSectionSpan(visual, oldSize, qMax(newSize, minimumSize));
-
- // cascade the section size change
- if (delta < 0 && newSize < minimumSize) {
- for (int i = visual - 1; i >= 0; --i) {
- if (!sectionIsCascadable(i))
- continue;
- int sectionSize = headerSectionSize(i);
- if (sectionSize <= minimumSize)
- continue;
- resizeSectionSpan(i, sectionSize, qMax(sectionSize + delta, minimumSize));
- saveCascadingSectionSize(i, sectionSize);
- break;
- }
- }
-
- // let the next section get the space from the resized section
- if (!sectionResized) {
- for (int i = visual + 1; i < sectionCount; ++i) {
- if (!sectionIsCascadable(i))
- continue;
- int currentSectionSize = headerSectionSize(i);
- int newSectionSize = qMax(currentSectionSize - delta, minimumSize);
- resizeSectionSpan(i, currentSectionSize, newSectionSize);
- break;
- }
- }
- }
-
- if (hasAutoResizeSections())
- doDelayedResizeSections();
-
- viewport->update();
-}
-
-void QHeaderViewPrivate::setDefaultSectionSize(int size)
-{
- Q_Q(QHeaderView);
- defaultSectionSize = size;
- int currentVisualIndex = 0;
- for (int i = 0; i < sectionSpans.count(); ++i) {
- QHeaderViewPrivate::SectionSpan &span = sectionSpans[i];
- if (span.size > 0) {
- //we resize it if it is not hidden (ie size > 0)
- const int newSize = span.count * size;
- if (newSize != span.size) {
- length += newSize - span.size; //the whole length is changed
- const int oldSectionSize = span.sectionSize();
- span.size = span.count * size;
- for (int i = currentVisualIndex; i < currentVisualIndex + span.count; ++i) {
- emit q->sectionResized(logicalIndex(i), oldSectionSize, size);
- }
- }
- }
- currentVisualIndex += span.count;
- }
-}
-
-void QHeaderViewPrivate::resizeSectionSpan(int visualIndex, int oldSize, int newSize)
-{
- Q_Q(QHeaderView);
- QHeaderView::ResizeMode mode = headerSectionResizeMode(visualIndex);
- createSectionSpan(visualIndex, visualIndex, newSize, mode);
- emit q->sectionResized(logicalIndex(visualIndex), oldSize, newSize);
-}
-
-int QHeaderViewPrivate::headerSectionSize(int visual) const
-{
- // ### stupid iteration
- int section_start = 0;
- const int sectionSpansCount = sectionSpans.count();
- for (int i = 0; i < sectionSpansCount; ++i) {
- const QHeaderViewPrivate::SectionSpan &currentSection = sectionSpans.at(i);
- int section_end = section_start + currentSection.count - 1;
- if (visual >= section_start && visual <= section_end)
- return currentSection.sectionSize();
- section_start = section_end + 1;
- }
- return -1;
-}
-
-int QHeaderViewPrivate::headerSectionPosition(int visual) const
-{
- // ### stupid iteration
- int section_start = 0;
- int span_position = 0;
- const int sectionSpansCount = sectionSpans.count();
- for (int i = 0; i < sectionSpansCount; ++i) {
- const QHeaderViewPrivate::SectionSpan &currentSection = sectionSpans.at(i);
- int section_end = section_start + currentSection.count - 1;
- if (visual >= section_start && visual <= section_end)
- return span_position + (visual - section_start) * currentSection.sectionSize();
- section_start = section_end + 1;
- span_position += currentSection.size;
- }
- return -1;
-}
-
-int QHeaderViewPrivate::headerVisualIndexAt(int position) const
-{
- // ### stupid iteration
- int span_start_section = 0;
- int span_position = 0;
- const int sectionSpansCount = sectionSpans.count();
- for (int i = 0; i < sectionSpansCount; ++i) {
- const QHeaderViewPrivate::SectionSpan &currentSection = sectionSpans.at(i);
- int next_span_start_section = span_start_section + currentSection.count;
- int next_span_position = span_position + currentSection.size;
- if (position == span_position)
- return span_start_section; // spans with no size
- if (position > span_position && position < next_span_position) {
- int position_in_span = position - span_position;
- return span_start_section + (position_in_span / currentSection.sectionSize());
- }
- span_start_section = next_span_start_section;
- span_position = next_span_position;
- }
- return -1;
-}
-
-void QHeaderViewPrivate::setHeaderSectionResizeMode(int visual, QHeaderView::ResizeMode mode)
-{
- int size = headerSectionSize(visual);
- createSectionSpan(visual, visual, size, mode);
-}
-
-QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual) const
-{
- int span = sectionSpanIndex(visual);
- if (span == -1)
- return globalResizeMode;
- return sectionSpans.at(span).resizeMode;
-}
-
-void QHeaderViewPrivate::setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode)
-{
- globalResizeMode = mode;
- for (int i = 0; i < sectionSpans.count(); ++i)
- sectionSpans[i].resizeMode = mode;
-}
-
-int QHeaderViewPrivate::viewSectionSizeHint(int logical) const
-{
- if (QAbstractItemView *view = qobject_cast<QAbstractItemView*>(parent)) {
- return (orientation == Qt::Horizontal
- ? view->sizeHintForColumn(logical)
- : view->sizeHintForRow(logical));
- }
- return 0;
-}
-
-int QHeaderViewPrivate::adjustedVisualIndex(int visualIndex) const
-{
- if (hiddenSectionSize.count() > 0) {
- int adjustedVisualIndex = visualIndex;
- int currentVisualIndex = 0;
- for (int i = 0; i < sectionSpans.count(); ++i) {
- if (sectionSpans.at(i).size == 0)
- adjustedVisualIndex += sectionSpans.at(i).count;
- else
- currentVisualIndex += sectionSpans.at(i).count;
- if (currentVisualIndex >= visualIndex)
- break;
- }
- visualIndex = adjustedVisualIndex;
- }
- return visualIndex;
-}
-
-#ifndef QT_NO_DATASTREAM
-void QHeaderViewPrivate::write(QDataStream &out) const
-{
- out << int(orientation);
- out << int(sortIndicatorOrder);
- out << sortIndicatorSection;
- out << sortIndicatorShown;
-
- out << visualIndices;
- out << logicalIndices;
-
- out << sectionHidden;
- out << hiddenSectionSize;
-
- out << length;
- out << sectionCount;
- out << movableSections;
- out << clickableSections;
- out << highlightSelected;
- out << stretchLastSection;
- out << cascadingResizing;
- out << stretchSections;
- out << contentsSections;
- out << defaultSectionSize;
- out << minimumSectionSize;
-
- out << int(defaultAlignment);
- out << int(globalResizeMode);
-
- out << sectionSpans;
-}
-
-bool QHeaderViewPrivate::read(QDataStream &in)
-{
- int orient, order, align, global;
- in >> orient;
- orientation = (Qt::Orientation)orient;
-
- in >> order;
- sortIndicatorOrder = (Qt::SortOrder)order;
-
- in >> sortIndicatorSection;
- in >> sortIndicatorShown;
-
- in >> visualIndices;
- in >> logicalIndices;
-
- in >> sectionHidden;
- in >> hiddenSectionSize;
-
- in >> length;
- in >> sectionCount;
- in >> movableSections;
- in >> clickableSections;
- in >> highlightSelected;
- in >> stretchLastSection;
- in >> cascadingResizing;
- in >> stretchSections;
- in >> contentsSections;
- in >> defaultSectionSize;
- in >> minimumSectionSize;
-
- in >> align;
- defaultAlignment = Qt::Alignment(align);
-
- in >> global;
- globalResizeMode = (QHeaderView::ResizeMode)global;
-
- in >> sectionSpans;
-
- return true;
-}
-
-#endif // QT_NO_DATASTREAM
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ITEMVIEWS
-
-#include "moc_qheaderview.cpp"
diff --git a/src/gui/itemviews/qheaderview.h b/src/gui/itemviews/qheaderview.h
deleted file mode 100644
index bd0b7666b0..0000000000
--- a/src/gui/itemviews/qheaderview.h
+++ /dev/null
@@ -1,250 +0,0 @@
-/****************************************************************************
-**
-** 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 QHEADERVIEW_H
-#define QHEADERVIEW_H
-
-#include <QtGui/qabstractitemview.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class QHeaderViewPrivate;
-class QStyleOptionHeader;
-
-class Q_GUI_EXPORT QHeaderView : public QAbstractItemView
-{
- Q_OBJECT
- Q_PROPERTY(bool showSortIndicator READ isSortIndicatorShown WRITE setSortIndicatorShown)
- Q_PROPERTY(bool highlightSections READ highlightSections WRITE setHighlightSections)
- Q_PROPERTY(bool stretchLastSection READ stretchLastSection WRITE setStretchLastSection)
- Q_PROPERTY(bool cascadingSectionResizes READ cascadingSectionResizes WRITE setCascadingSectionResizes)
- Q_PROPERTY(int defaultSectionSize READ defaultSectionSize WRITE setDefaultSectionSize)
- Q_PROPERTY(int minimumSectionSize READ minimumSectionSize WRITE setMinimumSectionSize)
- Q_PROPERTY(Qt::Alignment defaultAlignment READ defaultAlignment WRITE setDefaultAlignment)
- Q_ENUMS(ResizeMode)
-
-public:
-
- enum ResizeMode
- {
- Interactive,
- Stretch,
- Fixed,
- ResizeToContents,
- Custom = Fixed
- };
-
- explicit QHeaderView(Qt::Orientation orientation, QWidget *parent = 0);
- virtual ~QHeaderView();
-
- void setModel(QAbstractItemModel *model);
-
- Qt::Orientation orientation() const;
- int offset() const;
- int length() const;
- QSize sizeHint() const;
- int sectionSizeHint(int logicalIndex) const;
-
- int visualIndexAt(int position) const;
- int logicalIndexAt(int position) const;
-
- inline int logicalIndexAt(int x, int y) const;
- inline int logicalIndexAt(const QPoint &pos) const;
-
- int sectionSize(int logicalIndex) const;
- int sectionPosition(int logicalIndex) const;
- int sectionViewportPosition(int logicalIndex) const;
-
- void moveSection(int from, int to);
- void swapSections(int first, int second);
- void resizeSection(int logicalIndex, int size);
- void resizeSections(QHeaderView::ResizeMode mode);
-
- bool isSectionHidden(int logicalIndex) const;
- void setSectionHidden(int logicalIndex, bool hide);
- int hiddenSectionCount() const;
-
- inline void hideSection(int logicalIndex);
- inline void showSection(int logicalIndex);
-
- int count() const;
- int visualIndex(int logicalIndex) const;
- int logicalIndex(int visualIndex) const;
-
- void setMovable(bool movable);
- bool isMovable() const;
-
- void setClickable(bool clickable);
- bool isClickable() const;
-
- void setHighlightSections(bool highlight);
- bool highlightSections() const;
-
- void setResizeMode(ResizeMode mode);
- void setResizeMode(int logicalIndex, ResizeMode mode);
- ResizeMode resizeMode(int logicalIndex) const;
- int stretchSectionCount() const;
-
- void setSortIndicatorShown(bool show);
- bool isSortIndicatorShown() const;
-
- void setSortIndicator(int logicalIndex, Qt::SortOrder order);
- int sortIndicatorSection() const;
- Qt::SortOrder sortIndicatorOrder() const;
-
- bool stretchLastSection() const;
- void setStretchLastSection(bool stretch);
-
- bool cascadingSectionResizes() const;
- void setCascadingSectionResizes(bool enable);
-
- int defaultSectionSize() const;
- void setDefaultSectionSize(int size);
-
- int minimumSectionSize() const;
- void setMinimumSectionSize(int size);
-
- Qt::Alignment defaultAlignment() const;
- void setDefaultAlignment(Qt::Alignment alignment);
-
- void doItemsLayout();
- bool sectionsMoved() const;
- bool sectionsHidden() const;
-
-#ifndef QT_NO_DATASTREAM
- QByteArray saveState() const;
- bool restoreState(const QByteArray &state);
-#endif
-
- void reset();
-
-public Q_SLOTS:
- void setOffset(int offset);
- void setOffsetToSectionPosition(int visualIndex);
- void setOffsetToLastSection();
- void headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast);
-
-Q_SIGNALS:
- void sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex);
- void sectionResized(int logicalIndex, int oldSize, int newSize);
- void sectionPressed(int logicalIndex);
- void sectionClicked(int logicalIndex);
- void sectionEntered(int logicalIndex);
- void sectionDoubleClicked(int logicalIndex);
- void sectionCountChanged(int oldCount, int newCount);
- void sectionHandleDoubleClicked(int logicalIndex);
- void sectionAutoResize(int logicalIndex, QHeaderView::ResizeMode mode);
- void geometriesChanged();
- void sortIndicatorChanged(int logicalIndex, Qt::SortOrder order);
-
-protected Q_SLOTS:
- void updateSection(int logicalIndex);
- void resizeSections();
- void sectionsInserted(const QModelIndex &parent, int logicalFirst, int logicalLast);
- void sectionsAboutToBeRemoved(const QModelIndex &parent, int logicalFirst, int logicalLast);
-
-protected:
- QHeaderView(QHeaderViewPrivate &dd, Qt::Orientation orientation, QWidget *parent = 0);
- void initialize();
-
- void initializeSections();
- void initializeSections(int start, int end);
- void currentChanged(const QModelIndex &current, const QModelIndex &old);
-
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *e);
- void mousePressEvent(QMouseEvent *e);
- void mouseMoveEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
- void mouseDoubleClickEvent(QMouseEvent *e);
- bool viewportEvent(QEvent *e);
-
- virtual void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
- virtual QSize sectionSizeFromContents(int logicalIndex) const;
-
- int horizontalOffset() const;
- int verticalOffset() const;
- void updateGeometries();
- void scrollContentsBy(int dx, int dy);
-
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void rowsInserted(const QModelIndex &parent, int start, int end);
-
- QRect visualRect(const QModelIndex &index) const;
- void scrollTo(const QModelIndex &index, ScrollHint hint);
-
- QModelIndex indexAt(const QPoint &p) const;
- bool isIndexHidden(const QModelIndex &index) const;
-
- QModelIndex moveCursor(CursorAction, Qt::KeyboardModifiers);
- void setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags flags);
- QRegion visualRegionForSelection(const QItemSelection &selection) const;
- void initStyleOption(QStyleOptionHeader *option) const;
-
-private:
- Q_PRIVATE_SLOT(d_func(), void _q_sectionsRemoved(const QModelIndex &parent, int logicalFirst, int logicalLast))
- Q_PRIVATE_SLOT(d_func(), void _q_layoutAboutToBeChanged())
- Q_DECLARE_PRIVATE(QHeaderView)
- Q_DISABLE_COPY(QHeaderView)
-};
-
-inline int QHeaderView::logicalIndexAt(int ax, int ay) const
-{ return orientation() == Qt::Horizontal ? logicalIndexAt(ax) : logicalIndexAt(ay); }
-inline int QHeaderView::logicalIndexAt(const QPoint &apos) const
-{ return logicalIndexAt(apos.x(), apos.y()); }
-inline void QHeaderView::hideSection(int alogicalIndex)
-{ setSectionHidden(alogicalIndex, true); }
-inline void QHeaderView::showSection(int alogicalIndex)
-{ setSectionHidden(alogicalIndex, false); }
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QHEADERVIEW_H
diff --git a/src/gui/itemviews/qheaderview_p.h b/src/gui/itemviews/qheaderview_p.h
deleted file mode 100644
index f4b7ff7df0..0000000000
--- a/src/gui/itemviews/qheaderview_p.h
+++ /dev/null
@@ -1,366 +0,0 @@
-/****************************************************************************
-**
-** 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 QHEADERVIEW_P_H
-#define QHEADERVIEW_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qabstractitemview_p.h"
-
-#ifndef QT_NO_ITEMVIEWS
-
-#include "QtCore/qbitarray.h"
-#include "QtGui/qapplication.h"
-#include "QtGui/qlabel.h"
-
-QT_BEGIN_NAMESPACE
-
-class QHeaderViewPrivate: public QAbstractItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QHeaderView)
-
-public:
- enum StateVersion { VersionMarker = 0xff };
-
- QHeaderViewPrivate()
- : state(NoState),
- offset(0),
- sortIndicatorOrder(Qt::DescendingOrder),
- sortIndicatorSection(0),
- sortIndicatorShown(false),
- lastPos(-1),
- firstPos(-1),
- originalSize(-1),
- section(-1),
- target(-1),
- pressed(-1),
- hover(-1),
- length(0),
- sectionCount(0),
- movableSections(false),
- clickableSections(false),
- highlightSelected(false),
- stretchLastSection(false),
- cascadingResizing(false),
- resizeRecursionBlock(false),
- stretchSections(0),
- contentsSections(0),
- minimumSectionSize(-1),
- lastSectionSize(0),
- sectionIndicatorOffset(0),
- sectionIndicator(0),
- globalResizeMode(QHeaderView::Interactive)
- {}
-
-
- int lastVisibleVisualIndex() const;
- int sectionHandleAt(int position);
- void setupSectionIndicator(int section, int position);
- void updateSectionIndicator(int section, int position);
- void updateHiddenSections(int logicalFirst, int logicalLast);
- void resizeSections(QHeaderView::ResizeMode globalMode, bool useGlobalMode = false);
- void _q_sectionsRemoved(const QModelIndex &,int,int);
- void _q_layoutAboutToBeChanged();
- void _q_layoutChanged();
-
- bool isSectionSelected(int section) const;
-
- inline bool rowIntersectsSelection(int row) const {
- return (selectionModel ? selectionModel->rowIntersectsSelection(row, root) : false);
- }
-
- inline bool columnIntersectsSelection(int column) const {
- return (selectionModel ? selectionModel->columnIntersectsSelection(column, root) : false);
- }
-
- inline bool sectionIntersectsSelection(int logical) const {
- return (orientation == Qt::Horizontal ? columnIntersectsSelection(logical) : rowIntersectsSelection(logical));
- }
-
- inline bool isRowSelected(int row) const {
- return (selectionModel ? selectionModel->isRowSelected(row, root) : false);
- }
-
- inline bool isColumnSelected(int column) const {
- return (selectionModel ? selectionModel->isColumnSelected(column, root) : false);
- }
-
- inline void prepareSectionSelected() {
- if (!selectionModel || !selectionModel->hasSelection())
- sectionSelected.clear();
- else if (sectionSelected.count() != sectionCount * 2)
- sectionSelected.fill(false, sectionCount * 2);
- else sectionSelected.fill(false);
- }
-
- inline bool reverse() const {
- return orientation == Qt::Horizontal && q_func()->isRightToLeft();
- }
-
- inline int logicalIndex(int visualIndex) const {
- return logicalIndices.isEmpty() ? visualIndex : logicalIndices.at(visualIndex);
- }
-
- inline int visualIndex(int logicalIndex) const {
- return visualIndices.isEmpty() ? logicalIndex : visualIndices.at(logicalIndex);
- }
-
- inline void setDefaultValues(Qt::Orientation o) {
- orientation = o;
- defaultSectionSize = (o == Qt::Horizontal ? 100
- : qMax(q_func()->minimumSectionSize(), 30));
- defaultAlignment = (o == Qt::Horizontal
- ? Qt::Alignment(Qt::AlignCenter)
- : Qt::AlignLeft|Qt::AlignVCenter);
- }
-
- inline bool isVisualIndexHidden(int visual) const {
- return !sectionHidden.isEmpty() && sectionHidden.at(visual);
- }
-
- inline void setVisualIndexHidden(int visual, bool hidden) {
- if (!sectionHidden.isEmpty()) sectionHidden.setBit(visual, hidden);
- }
-
- inline bool hasAutoResizeSections() const {
- return stretchSections || stretchLastSection || contentsSections;
- }
-
- QStyleOptionHeader getStyleOption() const;
-
- inline void invalidateCachedSizeHint() const {
- cachedSizeHint = QSize();
- }
-
- inline void initializeIndexMapping() const {
- if (visualIndices.count() != sectionCount
- || logicalIndices.count() != sectionCount) {
- visualIndices.resize(sectionCount);
- logicalIndices.resize(sectionCount);
- for (int s = 0; s < sectionCount; ++s) {
- visualIndices[s] = s;
- logicalIndices[s] = s;
- }
- }
- }
-
- inline void clearCascadingSections() {
- firstCascadingSection = sectionCount;
- lastCascadingSection = 0;
- cascadingSectionSize.clear();
- }
-
- inline void saveCascadingSectionSize(int visual, int size) {
- if (!cascadingSectionSize.contains(visual)) {
- cascadingSectionSize.insert(visual, size);
- firstCascadingSection = qMin(firstCascadingSection, visual);
- lastCascadingSection = qMax(lastCascadingSection, visual);
- }
- }
-
- inline bool sectionIsCascadable(int visual) const {
- return headerSectionResizeMode(visual) == QHeaderView::Interactive;
- }
-
- inline int modelSectionCount() const {
- return (orientation == Qt::Horizontal
- ? model->columnCount(root)
- : model->rowCount(root));
- }
-
- inline bool modelIsEmpty() const {
- return (model->rowCount(root) == 0 || model->columnCount(root) == 0);
- }
-
- inline void doDelayedResizeSections() {
- if (!delayedResize.isActive())
- delayedResize.start(0, q_func());
- }
-
- inline void executePostedResize() const {
- if (delayedResize.isActive() && state == NoState) {
- const_cast<QHeaderView*>(q_func())->resizeSections();
- }
- }
-
- void clear();
- void flipSortIndicator(int section);
- void cascadingResize(int visual, int newSize);
-
- enum State { NoState, ResizeSection, MoveSection, SelectSections, NoClear } state;
-
- int offset;
- Qt::Orientation orientation;
- Qt::SortOrder sortIndicatorOrder;
- int sortIndicatorSection;
- bool sortIndicatorShown;
-
- mutable QVector<int> visualIndices; // visualIndex = visualIndices.at(logicalIndex)
- mutable QVector<int> logicalIndices; // logicalIndex = row or column in the model
- mutable QBitArray sectionSelected; // from logical index to bit
- mutable QBitArray sectionHidden; // from visual index to bit
- mutable QHash<int, int> hiddenSectionSize; // from logical index to section size
- mutable QHash<int, int> cascadingSectionSize; // from visual index to section size
- mutable QSize cachedSizeHint;
- mutable QBasicTimer delayedResize;
-
- int firstCascadingSection;
- int lastCascadingSection;
-
- int lastPos;
- int firstPos;
- int originalSize;
- int section; // used for resizing and moving sections
- int target;
- int pressed;
- int hover;
-
- int length;
- int sectionCount;
- bool movableSections;
- bool clickableSections;
- bool highlightSelected;
- bool stretchLastSection;
- bool cascadingResizing;
- bool resizeRecursionBlock;
- int stretchSections;
- int contentsSections;
- int defaultSectionSize;
- int minimumSectionSize;
- int lastSectionSize; // $$$
- int sectionIndicatorOffset;
- Qt::Alignment defaultAlignment;
- QLabel *sectionIndicator;
- QHeaderView::ResizeMode globalResizeMode;
- QList<QPersistentModelIndex> persistentHiddenSections;
-
- // header section spans
-
- struct SectionSpan {
- int size;
- int count;
- QHeaderView::ResizeMode resizeMode;
- inline SectionSpan() : size(0), count(0), resizeMode(QHeaderView::Interactive) {}
- inline SectionSpan(int length, int sections, QHeaderView::ResizeMode mode)
- : size(length), count(sections), resizeMode(mode) {}
- inline int sectionSize() const { return (count > 0 ? size / count : 0); }
-#ifndef QT_NO_DATASTREAM
- inline void write(QDataStream &out) const
- { out << size; out << count; out << (int)resizeMode; }
- inline void read(QDataStream &in)
- { in >> size; in >> count; int m; in >> m; resizeMode = (QHeaderView::ResizeMode)m; }
-#endif
- };
-
- QVector<SectionSpan> sectionSpans;
-
- void createSectionSpan(int start, int end, int size, QHeaderView::ResizeMode mode);
- void removeSectionsFromSpans(int start, int end);
- void resizeSectionSpan(int visualIndex, int oldSize, int newSize);
- void setDefaultSectionSize(int size);
-
- inline int headerSectionCount() const { // for debugging
- int count = 0;
- for (int i = 0; i < sectionSpans.count(); ++i)
- count += sectionSpans.at(i).count;
- return count;
- }
-
- inline int headerLength() const { // for debugging
- int len = 0;
- for (int i = 0; i < sectionSpans.count(); ++i)
- len += sectionSpans.at(i).size;
- return len;
- }
-
- inline void removeSpans(const QList<int> &spans) {
- for (int i = spans.count() - 1; i >= 0; --i) {
- length -= sectionSpans.at(spans.at(i)).size;
- sectionSpans.remove(spans.at(i));
- }
- }
-
- inline int sectionSpanIndex(int visual) const {
- int section_start = 0;
- for (int i = 0; i < sectionSpans.count(); ++i) {
- int section_end = section_start + sectionSpans.at(i).count - 1;
- if (visual >= section_start && visual <= section_end)
- return i;
- section_start = section_end + 1;
- }
- return -1;
- }
-
- int headerSectionSize(int visual) const;
- int headerSectionPosition(int visual) const;
- int headerVisualIndexAt(int position) const;
-
- // resize mode
- void setHeaderSectionResizeMode(int visual, QHeaderView::ResizeMode mode);
- QHeaderView::ResizeMode headerSectionResizeMode(int visual) const;
- void setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode);
-
- // other
- int viewSectionSizeHint(int logical) const;
- int adjustedVisualIndex(int visualIndex) const;
-
-#ifndef QT_NO_DATASTREAM
- void write(QDataStream &out) const;
- bool read(QDataStream &in);
-#endif
-
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ITEMVIEWS
-
-#endif // QHEADERVIEW_P_H
diff --git a/src/gui/itemviews/qitemdelegate.cpp b/src/gui/itemviews/qitemdelegate.cpp
deleted file mode 100644
index f211438dcd..0000000000
--- a/src/gui/itemviews/qitemdelegate.cpp
+++ /dev/null
@@ -1,1341 +0,0 @@
-/****************************************************************************
-**
-** 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 "qitemdelegate.h"
-
-#ifndef QT_NO_ITEMVIEWS
-#include <qabstractitemmodel.h>
-#include <qapplication.h>
-#include <qbrush.h>
-#include <qlineedit.h>
-#include <qtextedit.h>
-#include <qplaintextedit.h>
-#include <qpainter.h>
-#include <qpalette.h>
-#include <qpoint.h>
-#include <qrect.h>
-#include <qsize.h>
-#include <qstyle.h>
-#include <qdatetime.h>
-#include <qstyleoption.h>
-#include <qevent.h>
-#include <qpixmap.h>
-#include <qbitmap.h>
-#include <qpixmapcache.h>
-#include <qitemeditorfactory.h>
-#include <qmetaobject.h>
-#include <qtextlayout.h>
-#include <private/qobject_p.h>
-#include <private/qdnd_p.h>
-#include <private/qtextengine_p.h>
-#include <qdebug.h>
-#include <qlocale.h>
-#include <qdialog.h>
-#include <qmath.h>
-
-#include <limits.h>
-
-#ifndef DBL_DIG
-# define DBL_DIG 10
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QItemDelegatePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QItemDelegate)
-
-public:
- QItemDelegatePrivate() : f(0), clipPainting(true) {}
-
- inline const QItemEditorFactory *editorFactory() const
- { return f ? f : QItemEditorFactory::defaultFactory(); }
-
- inline QIcon::Mode iconMode(QStyle::State state) const
- {
- if (!(state & QStyle::State_Enabled)) return QIcon::Disabled;
- if (state & QStyle::State_Selected) return QIcon::Selected;
- return QIcon::Normal;
- }
-
- inline QIcon::State iconState(QStyle::State state) const
- { return state & QStyle::State_Open ? QIcon::On : QIcon::Off; }
-
- inline static QString replaceNewLine(QString text)
- {
- const QChar nl = QLatin1Char('\n');
- for (int i = 0; i < text.count(); ++i)
- if (text.at(i) == nl)
- text[i] = QChar::LineSeparator;
- return text;
- }
-
- static QString valueToText(const QVariant &value, const QStyleOptionViewItemV4 &option);
-
- void _q_commitDataAndCloseEditor(QWidget *editor);
-
- QItemEditorFactory *f;
- bool clipPainting;
-
- QRect textLayoutBounds(const QStyleOptionViewItemV2 &options) const;
- QSizeF doTextLayout(int lineWidth) const;
- mutable QTextLayout textLayout;
- mutable QTextOption textOption;
-
- const QWidget *widget(const QStyleOptionViewItem &option) const
- {
- if (const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3 *>(&option))
- return v3->widget;
-
- return 0;
- }
-
- // ### temporary hack until we have QStandardItemDelegate
- mutable struct Icon {
- QIcon icon;
- QIcon::Mode mode;
- QIcon::State state;
- } tmp;
-};
-
-void QItemDelegatePrivate::_q_commitDataAndCloseEditor(QWidget *editor)
-{
- Q_Q(QItemDelegate);
- emit q->commitData(editor);
- emit q->closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
-}
-
-QRect QItemDelegatePrivate::textLayoutBounds(const QStyleOptionViewItemV2 &option) const
-{
- QRect rect = option.rect;
- const bool wrapText = option.features & QStyleOptionViewItemV2::WrapText;
- switch (option.decorationPosition) {
- case QStyleOptionViewItem::Left:
- case QStyleOptionViewItem::Right:
- rect.setWidth(wrapText && rect.isValid() ? rect.width() : (QFIXED_MAX));
- break;
- case QStyleOptionViewItem::Top:
- case QStyleOptionViewItem::Bottom:
- rect.setWidth(wrapText ? option.decorationSize.width() : (QFIXED_MAX));
- break;
- }
-
- return rect;
-}
-
-QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
-{
- qreal height = 0;
- qreal widthUsed = 0;
- textLayout.beginLayout();
- while (true) {
- QTextLine line = textLayout.createLine();
- if (!line.isValid())
- break;
- line.setLineWidth(lineWidth);
- line.setPosition(QPointF(0, height));
- height += line.height();
- widthUsed = qMax(widthUsed, line.naturalTextWidth());
- }
- textLayout.endLayout();
- return QSizeF(widthUsed, height);
-}
-
-/*!
- \class QItemDelegate
-
- \brief The QItemDelegate class provides display and editing facilities for
- data items from a model.
-
- \ingroup model-view
-
-
- QItemDelegate can be used to provide custom display features and editor
- widgets for item views based on QAbstractItemView subclasses. Using a
- delegate for this purpose allows the display and editing mechanisms to be
- customized and developed independently from the model and view.
-
- The QItemDelegate class is one of the \l{Model/View Classes} and
- is part of Qt's \l{Model/View Programming}{model/view framework}.
- Note that QStyledItemDelegate has taken over the job of drawing
- Qt's item views. We recommend the use of QStyledItemDelegate when
- creating new delegates.
-
- When displaying items from a custom model in a standard view, it is
- often sufficient to simply ensure that the model returns appropriate
- data for each of the \l{Qt::ItemDataRole}{roles} that determine the
- appearance of items in views. The default delegate used by Qt's
- standard views uses this role information to display items in most
- of the common forms expected by users. However, it is sometimes
- necessary to have even more control over the appearance of items than
- the default delegate can provide.
-
- This class provides default implementations of the functions for
- painting item data in a view and editing data from item models.
- Default implementations of the paint() and sizeHint() virtual
- functions, defined in QAbstractItemDelegate, are provided to
- ensure that the delegate implements the correct basic behavior
- expected by views. You can reimplement these functions in
- subclasses to customize the appearance of items.
-
- When editing data in an item view, QItemDelegate provides an
- editor widget, which is a widget that is placed on top of the view
- while editing takes place. Editors are created with a
- QItemEditorFactory; a default static instance provided by
- QItemEditorFactory is installed on all item delegates. You can set
- a custom factory using setItemEditorFactory() or set a new default
- factory with QItemEditorFactory::setDefaultFactory(). It is the
- data stored in the item model with the Qt::EditRole that is edited.
-
- Only the standard editing functions for widget-based delegates are
- reimplemented here:
-
- \list
- \o createEditor() returns the widget used to change data from the model
- and can be reimplemented to customize editing behavior.
- \o setEditorData() provides the widget with data to manipulate.
- \o updateEditorGeometry() ensures that the editor is displayed correctly
- with respect to the item view.
- \o setModelData() returns updated data to the model.
- \endlist
-
- The closeEditor() signal indicates that the user has completed editing the data,
- and that the editor widget can be destroyed.
-
- \section1 Standard Roles and Data Types
-
- The default delegate used by the standard views supplied with Qt
- associates each standard role (defined by Qt::ItemDataRole) with certain
- data types. Models that return data in these types can influence the
- appearance of the delegate as described in the following table.
-
- \table
- \header \o Role \o Accepted Types
- \omit
- \row \o \l Qt::AccessibleDescriptionRole \o QString
- \row \o \l Qt::AccessibleTextRole \o QString
- \endomit
- \row \o \l Qt::BackgroundRole \o QBrush
- \row \o \l Qt::BackgroundColorRole \o QColor (obsolete; use Qt::BackgroundRole instead)
- \row \o \l Qt::CheckStateRole \o Qt::CheckState
- \row \o \l Qt::DecorationRole \o QIcon, QPixmap and QColor
- \row \o \l Qt::DisplayRole \o QString and types with a string representation
- \row \o \l Qt::EditRole \o See QItemEditorFactory for details
- \row \o \l Qt::FontRole \o QFont
- \row \o \l Qt::SizeHintRole \o QSize
- \omit
- \row \o \l Qt::StatusTipRole \o
- \endomit
- \row \o \l Qt::TextAlignmentRole \o Qt::Alignment
- \row \o \l Qt::ForegroundRole \o QBrush
- \row \o \l Qt::TextColorRole \o QColor (obsolete; use Qt::ForegroundRole instead)
- \omit
- \row \o \l Qt::ToolTipRole
- \row \o \l Qt::WhatsThisRole
- \endomit
- \endtable
-
- If the default delegate does not allow the level of customization that
- you need, either for display purposes or for editing data, it is possible to
- subclass QItemDelegate to implement the desired behavior.
-
- \section1 Subclassing
-
- When subclassing QItemDelegate to create a delegate that displays items
- using a custom renderer, it is important to ensure that the delegate can
- render items suitably for all the required states; e.g. selected,
- disabled, checked. The documentation for the paint() function contains
- some hints to show how this can be achieved.
-
- You can provide custom editors by using a QItemEditorFactory. The
- \l{Color Editor Factory Example} shows how a custom editor can be
- made available to delegates with the default item editor
- factory. This way, there is no need to subclass QItemDelegate. An
- alternative is to reimplement createEditor(), setEditorData(),
- setModelData(), and updateEditorGeometry(). This process is
- described in the \l{Spin Box Delegate Example}.
-
- \section1 QStyledItemDelegate vs. QItemDelegate
-
- Since Qt 4.4, there are two delegate classes: QItemDelegate and
- QStyledItemDelegate. However, the default delegate is QStyledItemDelegate.
- These two classes are independent alternatives to painting and providing
- editors for items in views. The difference between them is that
- QStyledItemDelegate uses the current style to paint its items. We therefore
- recommend using QStyledItemDelegate as the base class when implementing
- custom delegates or when working with Qt style sheets. The code required
- for either class should be equal unless the custom delegate needs to use
- the style for drawing.
-
- \sa {Delegate Classes}, QStyledItemDelegate, QAbstractItemDelegate,
- {Spin Box Delegate Example}, {Settings Editor Example},
- {Icons Example}
-*/
-
-/*!
- Constructs an item delegate with the given \a parent.
-*/
-
-QItemDelegate::QItemDelegate(QObject *parent)
- : QAbstractItemDelegate(*new QItemDelegatePrivate(), parent)
-{
-
-}
-
-/*!
- Destroys the item delegate.
-*/
-
-QItemDelegate::~QItemDelegate()
-{
-}
-
-/*!
- \property QItemDelegate::clipping
- \brief if the delegate should clip the paint events
- \since 4.2
-
- This property will set the paint clip to the size of the item.
- The default value is on. It is useful for cases such
- as when images are larger than the size of the item.
-*/
-
-bool QItemDelegate::hasClipping() const
-{
- Q_D(const QItemDelegate);
- return d->clipPainting;
-}
-
-void QItemDelegate::setClipping(bool clip)
-{
- Q_D(QItemDelegate);
- d->clipPainting = clip;
-}
-
-QString QItemDelegatePrivate::valueToText(const QVariant &value, const QStyleOptionViewItemV4 &option)
-{
- QString text;
- switch (value.userType()) {
- case QMetaType::Float:
- text = option.locale.toString(value.toFloat(), 'g');
- break;
- case QVariant::Double:
- text = option.locale.toString(value.toDouble(), 'g', DBL_DIG);
- break;
- case QVariant::Int:
- case QVariant::LongLong:
- text = option.locale.toString(value.toLongLong());
- break;
- case QVariant::UInt:
- case QVariant::ULongLong:
- text = option.locale.toString(value.toULongLong());
- break;
- case QVariant::Date:
- text = option.locale.toString(value.toDate(), QLocale::ShortFormat);
- break;
- case QVariant::Time:
- text = option.locale.toString(value.toTime(), QLocale::ShortFormat);
- break;
- case QVariant::DateTime:
- text = option.locale.toString(value.toDateTime().date(), QLocale::ShortFormat);
- text += QLatin1Char(' ');
- text += option.locale.toString(value.toDateTime().time(), QLocale::ShortFormat);
- break;
- default:
- text = replaceNewLine(value.toString());
- break;
- }
- return text;
-}
-
-/*!
- Renders the delegate using the given \a painter and style \a option for
- the item specified by \a index.
-
- When reimplementing this function in a subclass, you should update the area
- held by the option's \l{QStyleOption::rect}{rect} variable, using the
- option's \l{QStyleOption::state}{state} variable to determine the state of
- the item to be displayed, and adjust the way it is painted accordingly.
-
- For example, a selected item may need to be displayed differently to
- unselected items, as shown in the following code:
-
- \snippet examples/itemviews/pixelator/pixeldelegate.cpp 2
- \dots
-
- After painting, you should ensure that the painter is returned to its
- the state it was supplied in when this function was called. For example,
- it may be useful to call QPainter::save() before painting and
- QPainter::restore() afterwards.
-
- \sa QStyle::State
-*/
-void QItemDelegate::paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- Q_D(const QItemDelegate);
- Q_ASSERT(index.isValid());
-
- QStyleOptionViewItemV4 opt = setOptions(index, option);
-
- const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(&option);
- opt.features = v2 ? v2->features
- : QStyleOptionViewItemV2::ViewItemFeatures(QStyleOptionViewItemV2::None);
- const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3 *>(&option);
- opt.locale = v3 ? v3->locale : QLocale();
- opt.widget = v3 ? v3->widget : 0;
-
- // prepare
- painter->save();
- if (d->clipPainting)
- painter->setClipRect(opt.rect);
-
- // get the data and the rectangles
-
- QVariant value;
-
- QPixmap pixmap;
- QRect decorationRect;
- value = index.data(Qt::DecorationRole);
- if (value.isValid()) {
- // ### we need the pixmap to call the virtual function
- pixmap = decoration(opt, value);
- if (value.type() == QVariant::Icon) {
- d->tmp.icon = qvariant_cast<QIcon>(value);
- d->tmp.mode = d->iconMode(option.state);
- d->tmp.state = d->iconState(option.state);
- const QSize size = d->tmp.icon.actualSize(option.decorationSize,
- d->tmp.mode, d->tmp.state);
- decorationRect = QRect(QPoint(0, 0), size);
- } else {
- d->tmp.icon = QIcon();
- decorationRect = QRect(QPoint(0, 0), pixmap.size());
- }
- } else {
- d->tmp.icon = QIcon();
- decorationRect = QRect();
- }
-
- QString text;
- QRect displayRect;
- value = index.data(Qt::DisplayRole);
- if (value.isValid() && !value.isNull()) {
- text = QItemDelegatePrivate::valueToText(value, opt);
- displayRect = textRectangle(painter, d->textLayoutBounds(opt), opt.font, text);
- }
-
- QRect checkRect;
- Qt::CheckState checkState = Qt::Unchecked;
- value = index.data(Qt::CheckStateRole);
- if (value.isValid()) {
- checkState = static_cast<Qt::CheckState>(value.toInt());
- checkRect = check(opt, opt.rect, value);
- }
-
- // do the layout
-
- doLayout(opt, &checkRect, &decorationRect, &displayRect, false);
-
- // draw the item
-
- drawBackground(painter, opt, index);
- drawCheck(painter, opt, checkRect, checkState);
- drawDecoration(painter, opt, decorationRect, pixmap);
- drawDisplay(painter, opt, displayRect, text);
- drawFocus(painter, opt, displayRect);
-
- // done
- painter->restore();
-}
-
-/*!
- Returns the size needed by the delegate to display the item
- specified by \a index, taking into account the style information
- provided by \a option.
-
- When reimplementing this function, note that in case of text
- items, QItemDelegate adds a margin (i.e. 2 *
- QStyle::PM_FocusFrameHMargin) to the length of the text.
-*/
-
-QSize QItemDelegate::sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- QVariant value = index.data(Qt::SizeHintRole);
- if (value.isValid())
- return qvariant_cast<QSize>(value);
- QRect decorationRect = rect(option, index, Qt::DecorationRole);
- QRect displayRect = rect(option, index, Qt::DisplayRole);
- QRect checkRect = rect(option, index, Qt::CheckStateRole);
-
- doLayout(option, &checkRect, &decorationRect, &displayRect, true);
-
- return (decorationRect|displayRect|checkRect).size();
-}
-
-/*!
- Returns the widget used to edit the item specified by \a index
- for editing. The \a parent widget and style \a option are used to
- control how the editor widget appears.
-
- \sa QAbstractItemDelegate::createEditor()
-*/
-
-QWidget *QItemDelegate::createEditor(QWidget *parent,
- const QStyleOptionViewItem &,
- const QModelIndex &index) const
-{
- Q_D(const QItemDelegate);
- if (!index.isValid())
- return 0;
- QVariant::Type t = static_cast<QVariant::Type>(index.data(Qt::EditRole).userType());
- const QItemEditorFactory *factory = d->f;
- if (factory == 0)
- factory = QItemEditorFactory::defaultFactory();
- return factory->createEditor(t, parent);
-}
-
-/*!
- Sets the data to be displayed and edited by the \a editor from the
- data model item specified by the model \a index.
-
- The default implementation stores the data in the \a editor
- widget's \l {Qt's Property System} {user property}.
-
- \sa QMetaProperty::isUser()
-*/
-
-void QItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
-{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
- Q_D(const QItemDelegate);
- QVariant v = index.data(Qt::EditRole);
- QByteArray n = editor->metaObject()->userProperty().name();
-
- // ### Qt 5: remove
- // A work-around for missing "USER true" in qdatetimeedit.h for
- // QTimeEdit's time property and QDateEdit's date property.
- // It only triggers if the default user property "dateTime" is
- // reported for QTimeEdit and QDateEdit.
- if (n == "dateTime") {
- if (editor->inherits("QTimeEdit"))
- n = "time";
- else if (editor->inherits("QDateEdit"))
- n = "date";
- }
-
- // ### Qt 5: give QComboBox a USER property
- if (n.isEmpty() && editor->inherits("QComboBox"))
- n = d->editorFactory()->valuePropertyName(static_cast<QVariant::Type>(v.userType()));
- if (!n.isEmpty()) {
- if (!v.isValid())
- v = QVariant(editor->property(n).userType(), (const void *)0);
- editor->setProperty(n, v);
- }
-#endif
-}
-
-/*!
- Gets data from the \a editor widget and stores it in the specified
- \a model at the item \a index.
-
- The default implementation gets the value to be stored in the data
- model from the \a editor widget's \l {Qt's Property System} {user
- property}.
-
- \sa QMetaProperty::isUser()
-*/
-
-void QItemDelegate::setModelData(QWidget *editor,
- QAbstractItemModel *model,
- const QModelIndex &index) const
-{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(model);
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
- Q_D(const QItemDelegate);
- Q_ASSERT(model);
- Q_ASSERT(editor);
- QByteArray n = editor->metaObject()->userProperty().name();
- if (n.isEmpty())
- n = d->editorFactory()->valuePropertyName(
- static_cast<QVariant::Type>(model->data(index, Qt::EditRole).userType()));
- if (!n.isEmpty())
- model->setData(index, editor->property(n), Qt::EditRole);
-#endif
-}
-
-/*!
- Updates the \a editor for the item specified by \a index
- according to the style \a option given.
-*/
-
-void QItemDelegate::updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- if (!editor)
- return;
- Q_ASSERT(index.isValid());
- QPixmap pixmap = decoration(option, index.data(Qt::DecorationRole));
- QString text = QItemDelegatePrivate::replaceNewLine(index.data(Qt::DisplayRole).toString());
- QRect pixmapRect = QRect(QPoint(0, 0), option.decorationSize).intersected(pixmap.rect());
- QRect textRect = textRectangle(0, option.rect, option.font, text);
- QRect checkRect = check(option, textRect, index.data(Qt::CheckStateRole));
- QStyleOptionViewItem opt = option;
- opt.showDecorationSelected = true; // let the editor take up all available space
- doLayout(opt, &checkRect, &pixmapRect, &textRect, false);
- editor->setGeometry(textRect);
-}
-
-/*!
- Returns the editor factory used by the item delegate.
- If no editor factory is set, the function will return null.
-
- \sa setItemEditorFactory()
-*/
-QItemEditorFactory *QItemDelegate::itemEditorFactory() const
-{
- Q_D(const QItemDelegate);
- return d->f;
-}
-
-/*!
- Sets the editor factory to be used by the item delegate to be the \a factory
- specified. If no editor factory is set, the item delegate will use the
- default editor factory.
-
- \sa itemEditorFactory()
-*/
-void QItemDelegate::setItemEditorFactory(QItemEditorFactory *factory)
-{
- Q_D(QItemDelegate);
- d->f = factory;
-}
-
-/*!
- Renders the item view \a text within the rectangle specified by \a rect
- using the given \a painter and style \a option.
-*/
-
-void QItemDelegate::drawDisplay(QPainter *painter, const QStyleOptionViewItem &option,
- const QRect &rect, const QString &text) const
-{
- Q_D(const QItemDelegate);
-
- QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
- cg = QPalette::Inactive;
- if (option.state & QStyle::State_Selected) {
- painter->fillRect(rect, option.palette.brush(cg, QPalette::Highlight));
- painter->setPen(option.palette.color(cg, QPalette::HighlightedText));
- } else {
- painter->setPen(option.palette.color(cg, QPalette::Text));
- }
-
- if (text.isEmpty())
- return;
-
- if (option.state & QStyle::State_Editing) {
- painter->save();
- painter->setPen(option.palette.color(cg, QPalette::Text));
- painter->drawRect(rect.adjusted(0, 0, -1, -1));
- painter->restore();
- }
-
- const QStyleOptionViewItemV4 opt = option;
-
- const QWidget *widget = d->widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
- const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1;
- QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding
- const bool wrapText = opt.features & QStyleOptionViewItemV2::WrapText;
- d->textOption.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap);
- d->textOption.setTextDirection(option.direction);
- d->textOption.setAlignment(QStyle::visualAlignment(option.direction, option.displayAlignment));
- d->textLayout.setTextOption(d->textOption);
- d->textLayout.setFont(option.font);
- d->textLayout.setText(QItemDelegatePrivate::replaceNewLine(text));
-
- QSizeF textLayoutSize = d->doTextLayout(textRect.width());
-
- if (textRect.width() < textLayoutSize.width()
- || textRect.height() < textLayoutSize.height()) {
- QString elided;
- int start = 0;
- int end = text.indexOf(QChar::LineSeparator, start);
- if (end == -1) {
- elided += option.fontMetrics.elidedText(text, option.textElideMode, textRect.width());
- } else {
- while (end != -1) {
- elided += option.fontMetrics.elidedText(text.mid(start, end - start),
- option.textElideMode, textRect.width());
- elided += QChar::LineSeparator;
- start = end + 1;
- end = text.indexOf(QChar::LineSeparator, start);
- }
- //let's add the last line (after the last QChar::LineSeparator)
- elided += option.fontMetrics.elidedText(text.mid(start),
- option.textElideMode, textRect.width());
- }
- d->textLayout.setText(elided);
- textLayoutSize = d->doTextLayout(textRect.width());
- }
-
- const QSize layoutSize(textRect.width(), int(textLayoutSize.height()));
- const QRect layoutRect = QStyle::alignedRect(option.direction, option.displayAlignment,
- layoutSize, textRect);
- // if we still overflow even after eliding the text, enable clipping
- if (!hasClipping() && (textRect.width() < textLayoutSize.width()
- || textRect.height() < textLayoutSize.height())) {
- painter->save();
- painter->setClipRect(layoutRect);
- d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect);
- painter->restore();
- } else {
- d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect);
- }
-}
-
-/*!
- Renders the decoration \a pixmap within the rectangle specified by
- \a rect using the given \a painter and style \a option.
-*/
-void QItemDelegate::drawDecoration(QPainter *painter, const QStyleOptionViewItem &option,
- const QRect &rect, const QPixmap &pixmap) const
-{
- Q_D(const QItemDelegate);
- // if we have an icon, we ignore the pixmap
- if (!d->tmp.icon.isNull()) {
- d->tmp.icon.paint(painter, rect, option.decorationAlignment,
- d->tmp.mode, d->tmp.state);
- return;
- }
-
- if (pixmap.isNull() || !rect.isValid())
- return;
- QPoint p = QStyle::alignedRect(option.direction, option.decorationAlignment,
- pixmap.size(), rect).topLeft();
- if (option.state & QStyle::State_Selected) {
- QPixmap *pm = selected(pixmap, option.palette, option.state & QStyle::State_Enabled);
- painter->drawPixmap(p, *pm);
- } else {
- painter->drawPixmap(p, pixmap);
- }
-}
-
-/*!
- Renders the region within the rectangle specified by \a rect, indicating
- that it has the focus, using the given \a painter and style \a option.
-*/
-
-void QItemDelegate::drawFocus(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QRect &rect) const
-{
- Q_D(const QItemDelegate);
- if ((option.state & QStyle::State_HasFocus) == 0 || !rect.isValid())
- return;
- QStyleOptionFocusRect o;
- o.QStyleOption::operator=(option);
- o.rect = rect;
- o.state |= QStyle::State_KeyboardFocusChange;
- o.state |= QStyle::State_Item;
- QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled)
- ? QPalette::Normal : QPalette::Disabled;
- o.backgroundColor = option.palette.color(cg, (option.state & QStyle::State_Selected)
- ? QPalette::Highlight : QPalette::Window);
- const QWidget *widget = d->widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
- style->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, widget);
-}
-
-/*!
- Renders a check indicator within the rectangle specified by \a
- rect, using the given \a painter and style \a option, using the
- given \a state.
-*/
-
-void QItemDelegate::drawCheck(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QRect &rect, Qt::CheckState state) const
-{
- Q_D(const QItemDelegate);
- if (!rect.isValid())
- return;
-
- QStyleOptionViewItem opt(option);
- opt.rect = rect;
- opt.state = opt.state & ~QStyle::State_HasFocus;
-
- switch (state) {
- case Qt::Unchecked:
- opt.state |= QStyle::State_Off;
- break;
- case Qt::PartiallyChecked:
- opt.state |= QStyle::State_NoChange;
- break;
- case Qt::Checked:
- opt.state |= QStyle::State_On;
- break;
- }
-
- const QWidget *widget = d->widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
- style->drawPrimitive(QStyle::PE_IndicatorViewItemCheck, &opt, painter, widget);
-}
-
-/*!
- \since 4.2
-
- Renders the item background for the given \a index,
- using the given \a painter and style \a option.
-*/
-
-void QItemDelegate::drawBackground(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- if (option.showDecorationSelected && (option.state & QStyle::State_Selected)) {
- QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
- } else {
- QVariant value = index.data(Qt::BackgroundRole);
- if (value.canConvert<QBrush>()) {
- QPointF oldBO = painter->brushOrigin();
- painter->setBrushOrigin(option.rect.topLeft());
- painter->fillRect(option.rect, qvariant_cast<QBrush>(value));
- painter->setBrushOrigin(oldBO);
- }
- }
-}
-
-
-/*!
- \internal
-
- Code duplicated in QCommonStylePrivate::viewItemLayout
-*/
-
-void QItemDelegate::doLayout(const QStyleOptionViewItem &option,
- QRect *checkRect, QRect *pixmapRect, QRect *textRect,
- bool hint) const
-{
- Q_ASSERT(checkRect && pixmapRect && textRect);
- Q_D(const QItemDelegate);
- const QWidget *widget = d->widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
- const bool hasCheck = checkRect->isValid();
- const bool hasPixmap = pixmapRect->isValid();
- const bool hasText = textRect->isValid();
- const int textMargin = hasText ? style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1 : 0;
- const int pixmapMargin = hasPixmap ? style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1 : 0;
- const int checkMargin = hasCheck ? style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1 : 0;
- int x = option.rect.left();
- int y = option.rect.top();
- int w, h;
-
- textRect->adjust(-textMargin, 0, textMargin, 0); // add width padding
- if (textRect->height() == 0 && (!hasPixmap || !hint)) {
- //if there is no text, we still want to have a decent height for the item sizeHint and the editor size
- textRect->setHeight(option.fontMetrics.height());
- }
-
- QSize pm(0, 0);
- if (hasPixmap) {
- pm = pixmapRect->size();
- pm.rwidth() += 2 * pixmapMargin;
- }
- if (hint) {
- h = qMax(checkRect->height(), qMax(textRect->height(), pm.height()));
- if (option.decorationPosition == QStyleOptionViewItem::Left
- || option.decorationPosition == QStyleOptionViewItem::Right) {
- w = textRect->width() + pm.width();
- } else {
- w = qMax(textRect->width(), pm.width());
- }
- } else {
- w = option.rect.width();
- h = option.rect.height();
- }
-
- int cw = 0;
- QRect check;
- if (hasCheck) {
- cw = checkRect->width() + 2 * checkMargin;
- if (hint) w += cw;
- if (option.direction == Qt::RightToLeft) {
- check.setRect(x + w - cw, y, cw, h);
- } else {
- check.setRect(x + checkMargin, y, cw, h);
- }
- }
-
- // at this point w should be the *total* width
-
- QRect display;
- QRect decoration;
- switch (option.decorationPosition) {
- case QStyleOptionViewItem::Top: {
- if (hasPixmap)
- pm.setHeight(pm.height() + pixmapMargin); // add space
- h = hint ? textRect->height() : h - pm.height();
-
- if (option.direction == Qt::RightToLeft) {
- decoration.setRect(x, y, w - cw, pm.height());
- display.setRect(x, y + pm.height(), w - cw, h);
- } else {
- decoration.setRect(x + cw, y, w - cw, pm.height());
- display.setRect(x + cw, y + pm.height(), w - cw, h);
- }
- break; }
- case QStyleOptionViewItem::Bottom: {
- if (hasText)
- textRect->setHeight(textRect->height() + textMargin); // add space
- h = hint ? textRect->height() + pm.height() : h;
-
- if (option.direction == Qt::RightToLeft) {
- display.setRect(x, y, w - cw, textRect->height());
- decoration.setRect(x, y + textRect->height(), w - cw, h - textRect->height());
- } else {
- display.setRect(x + cw, y, w - cw, textRect->height());
- decoration.setRect(x + cw, y + textRect->height(), w - cw, h - textRect->height());
- }
- break; }
- case QStyleOptionViewItem::Left: {
- if (option.direction == Qt::LeftToRight) {
- decoration.setRect(x + cw, y, pm.width(), h);
- display.setRect(decoration.right() + 1, y, w - pm.width() - cw, h);
- } else {
- display.setRect(x, y, w - pm.width() - cw, h);
- decoration.setRect(display.right() + 1, y, pm.width(), h);
- }
- break; }
- case QStyleOptionViewItem::Right: {
- if (option.direction == Qt::LeftToRight) {
- display.setRect(x + cw, y, w - pm.width() - cw, h);
- decoration.setRect(display.right() + 1, y, pm.width(), h);
- } else {
- decoration.setRect(x, y, pm.width(), h);
- display.setRect(decoration.right() + 1, y, w - pm.width() - cw, h);
- }
- break; }
- default:
- qWarning("doLayout: decoration position is invalid");
- decoration = *pixmapRect;
- break;
- }
-
- if (!hint) { // we only need to do the internal layout if we are going to paint
- *checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
- checkRect->size(), check);
- *pixmapRect = QStyle::alignedRect(option.direction, option.decorationAlignment,
- pixmapRect->size(), decoration);
- // the text takes up all available space, unless the decoration is not shown as selected
- if (option.showDecorationSelected)
- *textRect = display;
- else
- *textRect = QStyle::alignedRect(option.direction, option.displayAlignment,
- textRect->size().boundedTo(display.size()), display);
- } else {
- *checkRect = check;
- *pixmapRect = decoration;
- *textRect = display;
- }
-}
-
-/*!
- \internal
-
- Returns the pixmap used to decorate the root of the item view.
- The style \a option controls the appearance of the root; the \a variant
- refers to the data associated with an item.
-*/
-
-QPixmap QItemDelegate::decoration(const QStyleOptionViewItem &option, const QVariant &variant) const
-{
- Q_D(const QItemDelegate);
- switch (variant.type()) {
- case QVariant::Icon: {
- QIcon::Mode mode = d->iconMode(option.state);
- QIcon::State state = d->iconState(option.state);
- return qvariant_cast<QIcon>(variant).pixmap(option.decorationSize, mode, state); }
- case QVariant::Color: {
- static QPixmap pixmap(option.decorationSize);
- pixmap.fill(qvariant_cast<QColor>(variant));
- return pixmap; }
- default:
- break;
- }
-
- return qvariant_cast<QPixmap>(variant);
-}
-
-// hacky but faster version of "QString::sprintf("%d-%d", i, enabled)"
-static QString qPixmapSerial(quint64 i, bool enabled)
-{
- ushort arr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '-', ushort('0' + enabled) };
- ushort *ptr = &arr[16];
-
- while (i > 0) {
- // hey - it's our internal representation, so use the ascii character after '9'
- // instead of 'a' for hex
- *(--ptr) = '0' + i % 16;
- i >>= 4;
- }
-
- return QString((const QChar *)ptr, int(&arr[sizeof(arr) / sizeof(ushort)] - ptr));
-}
-
-/*!
- \internal
- Returns the selected version of the given \a pixmap using the given \a palette.
- The \a enabled argument decides whether the normal or disabled highlight color of
- the palette is used.
-*/
-QPixmap *QItemDelegate::selected(const QPixmap &pixmap, const QPalette &palette, bool enabled) const
-{
- QString key = qPixmapSerial(qt_pixmap_id(pixmap), enabled);
- QPixmap *pm = QPixmapCache::find(key);
- if (!pm) {
- QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied);
-
- QColor color = palette.color(enabled ? QPalette::Normal : QPalette::Disabled,
- QPalette::Highlight);
- color.setAlphaF((qreal)0.3);
-
- QPainter painter(&img);
- painter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
- painter.fillRect(0, 0, img.width(), img.height(), color);
- painter.end();
-
- QPixmap selected = QPixmap(QPixmap::fromImage(img));
- int n = (img.byteCount() >> 10) + 1;
- if (QPixmapCache::cacheLimit() < n)
- QPixmapCache::setCacheLimit(n);
-
- QPixmapCache::insert(key, selected);
- pm = QPixmapCache::find(key);
- }
- return pm;
-}
-
-/*!
- \internal
-*/
-
-QRect QItemDelegate::rect(const QStyleOptionViewItem &option,
- const QModelIndex &index, int role) const
-{
- Q_D(const QItemDelegate);
- QVariant value = index.data(role);
- if (role == Qt::CheckStateRole)
- return check(option, option.rect, value);
- if (value.isValid() && !value.isNull()) {
- switch (value.type()) {
- case QVariant::Invalid:
- break;
- case QVariant::Pixmap:
- return QRect(QPoint(0, 0), qvariant_cast<QPixmap>(value).size());
- case QVariant::Image:
- return QRect(QPoint(0, 0), qvariant_cast<QImage>(value).size());
- case QVariant::Icon: {
- QIcon::Mode mode = d->iconMode(option.state);
- QIcon::State state = d->iconState(option.state);
- QIcon icon = qvariant_cast<QIcon>(value);
- QSize size = icon.actualSize(option.decorationSize, mode, state);
- return QRect(QPoint(0, 0), size); }
- case QVariant::Color:
- return QRect(QPoint(0, 0), option.decorationSize);
- case QVariant::String:
- default: {
- QString text = QItemDelegatePrivate::valueToText(value, option);
- value = index.data(Qt::FontRole);
- QFont fnt = qvariant_cast<QFont>(value).resolve(option.font);
- return textRectangle(0, d->textLayoutBounds(option), fnt, text); }
- }
- }
- return QRect();
-}
-
-/*!
- \internal
-
- Note that on Mac, if /usr/include/AssertMacros.h is included prior
- to QItemDelegate, and the application is building in debug mode, the
- check(assertion) will conflict with QItemDelegate::check.
-
- To avoid this problem, add
-
- #ifdef check
- #undef check
- #endif
-
- after including AssertMacros.h
-*/
-QRect QItemDelegate::check(const QStyleOptionViewItem &option,
- const QRect &bounding, const QVariant &value) const
-{
- if (value.isValid()) {
- Q_D(const QItemDelegate);
- QStyleOptionButton opt;
- opt.QStyleOption::operator=(option);
- opt.rect = bounding;
- const QWidget *widget = d->widget(option); // cast
- QStyle *style = widget ? widget->style() : QApplication::style();
- return style->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt, widget);
- }
- return QRect();
-}
-
-/*!
- \internal
-*/
-QRect QItemDelegate::textRectangle(QPainter * /*painter*/, const QRect &rect,
- const QFont &font, const QString &text) const
-{
- Q_D(const QItemDelegate);
- d->textOption.setWrapMode(QTextOption::WordWrap);
- d->textLayout.setTextOption(d->textOption);
- d->textLayout.setFont(font);
- d->textLayout.setText(QItemDelegatePrivate::replaceNewLine(text));
- QSizeF fpSize = d->doTextLayout(rect.width());
- const QSize size = QSize(qCeil(fpSize.width()), qCeil(fpSize.height()));
- // ###: textRectangle should take style option as argument
- const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
- return QRect(0, 0, size.width() + 2 * textMargin, size.height());
-}
-
-/*!
- \fn bool QItemDelegate::eventFilter(QObject *editor, QEvent *event)
-
- Returns true if the given \a editor is a valid QWidget and the
- given \a event is handled; otherwise returns false. The following
- key press events are handled by default:
-
- \list
- \o \gui Tab
- \o \gui Backtab
- \o \gui Enter
- \o \gui Return
- \o \gui Esc
- \endlist
-
- In the case of \gui Tab, \gui Backtab, \gui Enter and \gui Return
- key press events, the \a editor's data is comitted to the model
- and the editor is closed. If the \a event is a \gui Tab key press
- the view will open an editor on the next item in the
- view. Likewise, if the \a event is a \gui Backtab key press the
- view will open an editor on the \e previous item in the view.
-
- If the event is a \gui Esc key press event, the \a editor is
- closed \e without committing its data.
-
- \sa commitData(), closeEditor()
-*/
-
-bool QItemDelegate::eventFilter(QObject *object, QEvent *event)
-{
- QWidget *editor = qobject_cast<QWidget*>(object);
- if (!editor)
- return false;
- if (event->type() == QEvent::KeyPress) {
- switch (static_cast<QKeyEvent *>(event)->key()) {
- case Qt::Key_Tab:
- emit commitData(editor);
- emit closeEditor(editor, QAbstractItemDelegate::EditNextItem);
- return true;
- case Qt::Key_Backtab:
- emit commitData(editor);
- emit closeEditor(editor, QAbstractItemDelegate::EditPreviousItem);
- return true;
- case Qt::Key_Enter:
- case Qt::Key_Return:
-#ifndef QT_NO_TEXTEDIT
- if (qobject_cast<QTextEdit *>(editor) || qobject_cast<QPlainTextEdit *>(editor))
- return false; // don't filter enter key events for QTextEdit
- // We want the editor to be able to process the key press
- // before committing the data (e.g. so it can do
- // validation/fixup of the input).
-#endif // QT_NO_TEXTEDIT
-#ifndef QT_NO_LINEEDIT
- if (QLineEdit *e = qobject_cast<QLineEdit*>(editor))
- if (!e->hasAcceptableInput())
- return false;
-#endif // QT_NO_LINEEDIT
- QMetaObject::invokeMethod(this, "_q_commitDataAndCloseEditor",
- Qt::QueuedConnection, Q_ARG(QWidget*, editor));
- return false;
- case Qt::Key_Escape:
- // don't commit data
- emit closeEditor(editor, QAbstractItemDelegate::RevertModelCache);
- break;
- default:
- return false;
- }
- if (editor->parentWidget())
- editor->parentWidget()->setFocus();
- return true;
- } else if (event->type() == QEvent::FocusOut || (event->type() == QEvent::Hide && editor->isWindow())) {
- //the Hide event will take care of he editors that are in fact complete dialogs
- if (!editor->isActiveWindow() || (QApplication::focusWidget() != editor)) {
- QWidget *w = QApplication::focusWidget();
- while (w) { // don't worry about focus changes internally in the editor
- if (w == editor)
- return false;
- w = w->parentWidget();
- }
-#ifndef QT_NO_DRAGANDDROP
- // The window may lose focus during an drag operation.
- // i.e when dragging involves the taskbar on Windows.
- if (QDragManager::self() && QDragManager::self()->object != 0)
- return false;
-#endif
-
- emit commitData(editor);
- emit closeEditor(editor, NoHint);
- }
- } else if (event->type() == QEvent::ShortcutOverride) {
- if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
- event->accept();
- return true;
- }
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-
-bool QItemDelegate::editorEvent(QEvent *event,
- QAbstractItemModel *model,
- const QStyleOptionViewItem &option,
- const QModelIndex &index)
-{
- Q_ASSERT(event);
- Q_ASSERT(model);
-
- // make sure that the item is checkable
- Qt::ItemFlags flags = model->flags(index);
- if (!(flags & Qt::ItemIsUserCheckable) || !(option.state & QStyle::State_Enabled)
- || !(flags & Qt::ItemIsEnabled))
- return false;
-
- // make sure that we have a check state
- QVariant value = index.data(Qt::CheckStateRole);
- if (!value.isValid())
- return false;
-
- // make sure that we have the right event type
- if ((event->type() == QEvent::MouseButtonRelease)
- || (event->type() == QEvent::MouseButtonDblClick)
- || (event->type() == QEvent::MouseButtonPress)) {
- QRect checkRect = check(option, option.rect, Qt::Checked);
- QRect emptyRect;
- doLayout(option, &checkRect, &emptyRect, &emptyRect, false);
- QMouseEvent *me = static_cast<QMouseEvent*>(event);
- if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
- return false;
-
- // eat the double click events inside the check rect
- if ((event->type() == QEvent::MouseButtonPress)
- || (event->type() == QEvent::MouseButtonDblClick))
- return true;
-
- } else if (event->type() == QEvent::KeyPress) {
- if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space
- && static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
- return false;
- } else {
- return false;
- }
-
- Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
- ? Qt::Unchecked : Qt::Checked);
- return model->setData(index, state, Qt::CheckStateRole);
-}
-
-/*!
- \internal
-*/
-
-QStyleOptionViewItem QItemDelegate::setOptions(const QModelIndex &index,
- const QStyleOptionViewItem &option) const
-{
- QStyleOptionViewItem opt = option;
-
- // set font
- QVariant value = index.data(Qt::FontRole);
- if (value.isValid()){
- opt.font = qvariant_cast<QFont>(value).resolve(opt.font);
- opt.fontMetrics = QFontMetrics(opt.font);
- }
-
- // set text alignment
- value = index.data(Qt::TextAlignmentRole);
- if (value.isValid())
- opt.displayAlignment = Qt::Alignment(value.toInt());
-
- // set foreground brush
- value = index.data(Qt::ForegroundRole);
- if (value.canConvert<QBrush>())
- opt.palette.setBrush(QPalette::Text, qvariant_cast<QBrush>(value));
-
- return opt;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qitemdelegate.cpp"
-
-#endif // QT_NO_ITEMVIEWS
diff --git a/src/gui/itemviews/qitemdelegate.h b/src/gui/itemviews/qitemdelegate.h
deleted file mode 100644
index 2df3d1c1c1..0000000000
--- a/src/gui/itemviews/qitemdelegate.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** 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 QITEMDELEGATE_H
-#define QITEMDELEGATE_H
-
-#include <QtGui/qabstractitemdelegate.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qpixmap.h>
-#include <QtCore/qvariant.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class QItemDelegatePrivate;
-class QItemEditorFactory;
-
-class Q_GUI_EXPORT QItemDelegate : public QAbstractItemDelegate
-{
- Q_OBJECT
- Q_PROPERTY(bool clipping READ hasClipping WRITE setClipping)
-
-public:
- explicit QItemDelegate(QObject *parent = 0);
- ~QItemDelegate();
-
- bool hasClipping() const;
- void setClipping(bool clip);
-
- // painting
- void paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
- QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- // editing
- QWidget *createEditor(QWidget *parent,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- void setEditorData(QWidget *editor, const QModelIndex &index) const;
- void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
-
- void updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- // editor factory
- QItemEditorFactory *itemEditorFactory() const;
- void setItemEditorFactory(QItemEditorFactory *factory);
-
-protected:
- virtual void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option,
- const QRect &rect, const QString &text) const;
- virtual void drawDecoration(QPainter *painter, const QStyleOptionViewItem &option,
- const QRect &rect, const QPixmap &pixmap) const;
- virtual void drawFocus(QPainter *painter, const QStyleOptionViewItem &option,
- const QRect &rect) const;
- virtual void drawCheck(QPainter *painter, const QStyleOptionViewItem &option,
- const QRect &rect, Qt::CheckState state) const;
- void drawBackground(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- void doLayout(const QStyleOptionViewItem &option,
- QRect *checkRect, QRect *iconRect, QRect *textRect, bool hint) const;
-
- QRect rect(const QStyleOptionViewItem &option, const QModelIndex &index, int role) const;
-
- bool eventFilter(QObject *object, QEvent *event);
- bool editorEvent(QEvent *event, QAbstractItemModel *model,
- const QStyleOptionViewItem &option, const QModelIndex &index);
-
- QStyleOptionViewItem setOptions(const QModelIndex &index,
- const QStyleOptionViewItem &option) const;
-
- QPixmap decoration(const QStyleOptionViewItem &option, const QVariant &variant) const;
- QPixmap *selected(const QPixmap &pixmap, const QPalette &palette, bool enabled) const;
-
- QRect check(const QStyleOptionViewItem &option, const QRect &bounding,
- const QVariant &variant) const;
- QRect textRectangle(QPainter *painter, const QRect &rect,
- const QFont &font, const QString &text) const;
-
-private:
- Q_DECLARE_PRIVATE(QItemDelegate)
- Q_DISABLE_COPY(QItemDelegate)
-
- Q_PRIVATE_SLOT(d_func(), void _q_commitDataAndCloseEditor(QWidget*))
-};
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QITEMDELEGATE_H
diff --git a/src/gui/itemviews/qitemeditorfactory.cpp b/src/gui/itemviews/qitemeditorfactory.cpp
deleted file mode 100644
index 92c78cb6f1..0000000000
--- a/src/gui/itemviews/qitemeditorfactory.cpp
+++ /dev/null
@@ -1,578 +0,0 @@
-/****************************************************************************
-**
-** 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 "qitemeditorfactory.h"
-#include "qitemeditorfactory_p.h"
-
-#ifndef QT_NO_ITEMVIEWS
-
-#include <qcombobox.h>
-#include <qdatetimeedit.h>
-#include <qlabel.h>
-#include <qlineedit.h>
-#include <qspinbox.h>
-#include <limits.h>
-#include <float.h>
-#include <qapplication.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-
-#ifndef QT_NO_COMBOBOX
-
-class QBooleanComboBox : public QComboBox
-{
- Q_OBJECT
- Q_PROPERTY(bool value READ value WRITE setValue USER true)
-
-public:
- QBooleanComboBox(QWidget *parent);
- void setValue(bool);
- bool value() const;
-};
-
-#endif // QT_NO_COMBOBOX
-
-/*!
- \class QItemEditorFactory
- \brief The QItemEditorFactory class provides widgets for editing item data
- in views and delegates.
- \since 4.2
- \ingroup model-view
-
- When editing data in an item view, editors are created and
- displayed by a delegate. QItemDelegate, which is the delegate by
- default installed on Qt's item views, uses a QItemEditorFactory to
- create editors for it. A default unique instance provided by
- QItemEditorFactory is used by all item delegates. If you set a
- new default factory with setDefaultFactory(), the new factory will
- be used by existing and new delegates.
-
- A factory keeps a collection of QItemEditorCreatorBase
- instances, which are specialized editors that produce editors
- for one particular QVariant data type (All Qt models store
- their data in \l{QVariant}s).
-
- \section1 Standard Editing Widgets
-
- The standard factory implementation provides editors for a variety of data
- types. These are created whenever a delegate needs to provide an editor for
- data supplied by a model. The following table shows the relationship between
- types and the standard editors provided.
-
- \table
- \header \o Type \o Editor Widget
- \row \o bool \o QComboBox
- \row \o double \o QDoubleSpinBox
- \row \o int \o{1,2} QSpinBox
- \row \o unsigned int
- \row \o QDate \o QDateEdit
- \row \o QDateTime \o QDateTimeEdit
- \row \o QPixmap \o QLabel
- \row \o QString \o QLineEdit
- \row \o QTime \o QTimeEdit
- \endtable
-
- Additional editors can be registered with the registerEditor() function.
-
- \sa QItemDelegate, {Model/View Programming}, {Color Editor Factory Example}
-*/
-
-/*!
- \fn QItemEditorFactory::QItemEditorFactory()
-
- Constructs a new item editor factory.
-*/
-
-/*!
- Creates an editor widget with the given \a parent for the specified \a type of data,
- and returns it as a QWidget.
-
- \sa registerEditor()
-*/
-QWidget *QItemEditorFactory::createEditor(QVariant::Type type, QWidget *parent) const
-{
- QItemEditorCreatorBase *creator = creatorMap.value(type, 0);
- if (!creator) {
- const QItemEditorFactory *dfactory = defaultFactory();
- return dfactory == this ? 0 : dfactory->createEditor(type, parent);
- }
- return creator->createWidget(parent);
-}
-
-/*!
- Returns the property name used to access data for the given \a type of data.
-*/
-QByteArray QItemEditorFactory::valuePropertyName(QVariant::Type type) const
-{
- QItemEditorCreatorBase *creator = creatorMap.value(type, 0);
- if (!creator) {
- const QItemEditorFactory *dfactory = defaultFactory();
- return dfactory == this ? QByteArray() : dfactory->valuePropertyName(type);
- }
- return creator->valuePropertyName();
-}
-
-/*!
- Destroys the item editor factory.
-*/
-QItemEditorFactory::~QItemEditorFactory()
-{
- //we make sure we delete all the QItemEditorCreatorBase
- //this has to be done only once, hence the QSet
- QSet<QItemEditorCreatorBase*> set = creatorMap.values().toSet();
- qDeleteAll(set);
-}
-
-/*!
- Registers an item editor creator specified by \a creator for the given \a type of data.
-
- \bold{Note:} The factory takes ownership of the item editor creator and will destroy
- it if a new creator for the same type is registered later.
-
- \sa createEditor()
-*/
-void QItemEditorFactory::registerEditor(QVariant::Type type, QItemEditorCreatorBase *creator)
-{
- QHash<QVariant::Type, QItemEditorCreatorBase *>::iterator it = creatorMap.find(type);
- if (it != creatorMap.end()) {
- QItemEditorCreatorBase *oldCreator = it.value();
- Q_ASSERT(oldCreator);
- creatorMap.erase(it);
- if (!creatorMap.values().contains(oldCreator))
- delete oldCreator; // if it is no more in use we can delete it
- }
-
- creatorMap[type] = creator;
-}
-
-class QDefaultItemEditorFactory : public QItemEditorFactory
-{
-public:
- inline QDefaultItemEditorFactory() {}
- QWidget *createEditor(QVariant::Type type, QWidget *parent) const;
- QByteArray valuePropertyName(QVariant::Type) const;
-};
-
-QWidget *QDefaultItemEditorFactory::createEditor(QVariant::Type type, QWidget *parent) const
-{
- switch (type) {
-#ifndef QT_NO_COMBOBOX
- case QVariant::Bool: {
- QBooleanComboBox *cb = new QBooleanComboBox(parent);
- cb->setFrame(false);
- return cb; }
-#endif
-#ifndef QT_NO_SPINBOX
- case QVariant::UInt: {
- QSpinBox *sb = new QSpinBox(parent);
- sb->setFrame(false);
- sb->setMaximum(INT_MAX);
- return sb; }
- case QVariant::Int: {
- QSpinBox *sb = new QSpinBox(parent);
- sb->setFrame(false);
- sb->setMinimum(INT_MIN);
- sb->setMaximum(INT_MAX);
- return sb; }
-#endif
-#ifndef QT_NO_DATETIMEEDIT
- case QVariant::Date: {
- QDateTimeEdit *ed = new QDateEdit(parent);
- ed->setFrame(false);
- return ed; }
- case QVariant::Time: {
- QDateTimeEdit *ed = new QTimeEdit(parent);
- ed->setFrame(false);
- return ed; }
- case QVariant::DateTime: {
- QDateTimeEdit *ed = new QDateTimeEdit(parent);
- ed->setFrame(false);
- return ed; }
-#endif
- case QVariant::Pixmap:
- return new QLabel(parent);
-#ifndef QT_NO_SPINBOX
- case QVariant::Double: {
- QDoubleSpinBox *sb = new QDoubleSpinBox(parent);
- sb->setFrame(false);
- sb->setMinimum(-DBL_MAX);
- sb->setMaximum(DBL_MAX);
- return sb; }
-#endif
-#ifndef QT_NO_LINEEDIT
- case QVariant::String:
- default: {
- // the default editor is a lineedit
- QExpandingLineEdit *le = new QExpandingLineEdit(parent);
- le->setFrame(le->style()->styleHint(QStyle::SH_ItemView_DrawDelegateFrame, 0, le));
- if (!le->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, 0, le))
- le->setWidgetOwnsGeometry(true);
- return le; }
-#else
- default:
- break;
-#endif
- }
- return 0;
-}
-
-QByteArray QDefaultItemEditorFactory::valuePropertyName(QVariant::Type type) const
-{
- switch (type) {
-#ifndef QT_NO_COMBOBOX
- case QVariant::Bool:
- return "currentIndex";
-#endif
-#ifndef QT_NO_SPINBOX
- case QVariant::UInt:
- case QVariant::Int:
- case QVariant::Double:
- return "value";
-#endif
-#ifndef QT_NO_DATETIMEEDIT
- case QVariant::Date:
- return "date";
- case QVariant::Time:
- return "time";
- case QVariant::DateTime:
- return "dateTime";
-#endif
- case QVariant::String:
- default:
- // the default editor is a lineedit
- return "text";
- }
-}
-
-static QItemEditorFactory *q_default_factory = 0;
-struct QDefaultFactoryCleaner
-{
- inline QDefaultFactoryCleaner() {}
- ~QDefaultFactoryCleaner() { delete q_default_factory; q_default_factory = 0; }
-};
-
-/*!
- Returns the default item editor factory.
-
- \sa setDefaultFactory()
-*/
-const QItemEditorFactory *QItemEditorFactory::defaultFactory()
-{
- static const QDefaultItemEditorFactory factory;
- if (q_default_factory)
- return q_default_factory;
- return &factory;
-}
-
-/*!
- Sets the default item editor factory to the given \a factory.
- Both new and existing delegates will use the new factory.
-
- \sa defaultFactory()
-*/
-void QItemEditorFactory::setDefaultFactory(QItemEditorFactory *factory)
-{
- static const QDefaultFactoryCleaner cleaner;
- delete q_default_factory;
- q_default_factory = factory;
-}
-
-/*!
- \class QItemEditorCreatorBase
- \brief The QItemEditorCreatorBase class provides an abstract base class that
- must be subclassed when implementing new item editor creators.
- \since 4.2
- \ingroup model-view
-
- QItemEditorCreatorBase objects are specialized widget factories that
- provide editor widgets for one particular QVariant data type. They
- are used by QItemEditorFactory to create editors for
- \l{QItemDelegate}s. Creator bases must be registered with
- QItemEditorFactory::registerEditor().
-
- An editor should provide a user property for the data it edits.
- QItemDelagates can then access the property using Qt's
- \l{Meta-Object System}{meta-object system} to set and retrieve the
- editing data. A property is set as the user property with the USER
- keyword:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp 0
-
- If the editor does not provide a user property, it must return the
- name of the property from valuePropertyName(); delegates will then
- use the name to access the property. If a user property exists,
- item delegates will not call valuePropertyName().
-
- QStandardItemEditorCreator is a convenience template class that can be used
- to register widgets without the need to subclass QItemEditorCreatorBase.
-
- \sa QStandardItemEditorCreator, QItemEditorFactory,
- {Model/View Programming}, {Color Editor Factory Example}
-*/
-
-/*!
- \fn QItemEditorCreatorBase::~QItemEditorCreatorBase()
-
- Destroys the editor creator object.
-*/
-
-/*!
- \fn QWidget *QItemEditorCreatorBase::createWidget(QWidget *parent) const
-
- Returns an editor widget with the given \a parent.
-
- When implementing this function in subclasses of this class, you must
- construct and return new editor widgets with the parent widget specified.
-*/
-
-/*!
- \fn QByteArray QItemEditorCreatorBase::valuePropertyName() const
-
- Returns the name of the property used to get and set values in the creator's
- editor widgets.
-
- When implementing this function in subclasses, you must ensure that the
- editor widget's property specified by this function can accept the type
- the creator is registered for. For example, a creator which constructs
- QCheckBox widgets to edit boolean values would return the
- \l{QCheckBox::checkable}{checkable} property name from this function,
- and must be registered in the item editor factory for the QVariant::Bool
- type.
-
- Note: Since Qt 4.2 the item delegates query the user property of widgets,
- and only call this function if the widget has no user property. You can
- override this behavior by reimplementing QAbstractItemDelegate::setModelData()
- and QAbstractItemDelegate::setEditorData().
-
- \sa QMetaObject::userProperty(), QItemEditorFactory::registerEditor()
-*/
-
-/*!
- \class QItemEditorCreator
- \brief The QItemEditorCreator class makes it possible to create
- item editor creator bases without subclassing
- QItemEditorCreatorBase.
-
- \since 4.2
- \ingroup model-view
-
- QItemEditorCreator is a convenience template class. It uses
- the template class to create editors for QItemEditorFactory.
- This way, it is not necessary to subclass
- QItemEditorCreatorBase.
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp 1
-
- The constructor takes the name of the property that contains the
- editing data. QItemDelegate can then access the property by name
- when it sets and retrieves editing data. Only use this class if
- your editor does not define a user property (using the USER
- keyword in the Q_PROPERTY macro). If the widget has a user
- property, you should use QStandardItemEditorCreator instead.
-
- \sa QItemEditorCreatorBase, QStandardItemEditorCreator,
- QItemEditorFactory, {Color Editor Factory Example}
-*/
-
-/*!
- \fn QItemEditorCreator::QItemEditorCreator(const QByteArray &valuePropertyName)
-
- Constructs an editor creator object using \a valuePropertyName
- as the name of the property to be used for editing. The
- property name is used by QItemDelegate when setting and
- getting editor data.
-
- Note that the \a valuePropertyName is only used if the editor
- widget does not have a user property defined.
-*/
-
-/*!
- \fn QWidget *QItemEditorCreator::createWidget(QWidget *parent) const
- \reimp
-*/
-
-/*!
- \fn QByteArray QItemEditorCreator::valuePropertyName() const
- \reimp
-*/
-
-/*!
- \class QStandardItemEditorCreator
-
- \brief The QStandardItemEditorCreator class provides the
- possibility to register widgets without having to subclass
- QItemEditorCreatorBase.
-
- \since 4.2
- \ingroup model-view
-
- This convenience template class makes it possible to register widgets without
- having to subclass QItemEditorCreatorBase.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp 2
-
- Setting the \c editorFactory created above in an item delegate via
- QItemDelegate::setItemEditorFactory() makes sure that all values of type
- QVariant::DateTime will be edited in \c{MyFancyDateTimeEdit}.
-
- The editor must provide a user property that will contain the
- editing data. The property is used by \l{QItemDelegate}s to set
- and retrieve the data (using Qt's \l{Meta-Object
- System}{meta-object system}). You set the user property with
- the USER keyword:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp 3
-
- \sa QItemEditorCreatorBase, QItemEditorCreator,
- QItemEditorFactory, QItemDelegate, {Color Editor Factory Example}
-*/
-
-/*!
- \fn QStandardItemEditorCreator::QStandardItemEditorCreator()
-
- Constructs an editor creator object.
-*/
-
-/*!
- \fn QWidget *QStandardItemEditorCreator::createWidget(QWidget *parent) const
- \reimp
-*/
-
-/*!
- \fn QByteArray QStandardItemEditorCreator::valuePropertyName() const
- \reimp
-*/
-
-#ifndef QT_NO_LINEEDIT
-
-QExpandingLineEdit::QExpandingLineEdit(QWidget *parent)
- : QLineEdit(parent), originalWidth(-1), widgetOwnsGeometry(false)
-{
- connect(this, SIGNAL(textChanged(QString)), this, SLOT(resizeToContents()));
- updateMinimumWidth();
-}
-
-void QExpandingLineEdit::changeEvent(QEvent *e)
-{
- switch (e->type())
- {
- case QEvent::FontChange:
- case QEvent::StyleChange:
- case QEvent::ContentsRectChange:
- updateMinimumWidth();
- break;
- default:
- break;
- }
-
- QLineEdit::changeEvent(e);
-}
-
-void QExpandingLineEdit::updateMinimumWidth()
-{
- int left, right;
- getTextMargins(&left, 0, &right, 0);
- int width = left + right + 4 /*horizontalMargin in qlineedit.cpp*/;
- getContentsMargins(&left, 0, &right, 0);
- width += left + right;
-
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
-
- int minWidth = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(width, 0).
- expandedTo(QApplication::globalStrut()), this).width();
- setMinimumWidth(minWidth);
-}
-
-void QExpandingLineEdit::resizeToContents()
-{
- int oldWidth = width();
- if (originalWidth == -1)
- originalWidth = oldWidth;
- if (QWidget *parent = parentWidget()) {
- QPoint position = pos();
- int hintWidth = minimumWidth() + fontMetrics().width(displayText());
- int parentWidth = parent->width();
- int maxWidth = isRightToLeft() ? position.x() + oldWidth : parentWidth - position.x();
- int newWidth = qBound(originalWidth, hintWidth, maxWidth);
- if (widgetOwnsGeometry)
- setMaximumWidth(newWidth);
- if (isRightToLeft())
- move(position.x() - newWidth + oldWidth, position.y());
- resize(newWidth, height());
- }
-}
-
-#endif // QT_NO_LINEEDIT
-
-#ifndef QT_NO_COMBOBOX
-
-QBooleanComboBox::QBooleanComboBox(QWidget *parent)
- : QComboBox(parent)
-{
- addItem(QComboBox::tr("False"));
- addItem(QComboBox::tr("True"));
-}
-
-void QBooleanComboBox::setValue(bool value)
-{
- setCurrentIndex(value ? 1 : 0);
-}
-
-bool QBooleanComboBox::value() const
-{
- return (currentIndex() == 1);
-}
-
-#endif // QT_NO_COMBOBOX
-
-QT_END_NAMESPACE
-
-#if !defined(QT_NO_LINEEDIT) || !defined(QT_NO_COMBOBOX)
-#include "qitemeditorfactory.moc"
-#endif
-
-#endif // QT_NO_ITEMVIEWS
diff --git a/src/gui/itemviews/qitemeditorfactory.h b/src/gui/itemviews/qitemeditorfactory.h
deleted file mode 100644
index 28e145460f..0000000000
--- a/src/gui/itemviews/qitemeditorfactory.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/****************************************************************************
-**
-** 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 QITEMEDITORFACTORY_H
-#define QITEMEDITORFACTORY_H
-
-#include <QtCore/qmetaobject.h>
-#include <QtCore/qbytearray.h>
-#include <QtCore/qhash.h>
-#include <QtCore/qvariant.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class QWidget;
-
-class Q_GUI_EXPORT QItemEditorCreatorBase
-{
-public:
- virtual ~QItemEditorCreatorBase() {}
-
- virtual QWidget *createWidget(QWidget *parent) const = 0;
- virtual QByteArray valuePropertyName() const = 0;
-};
-
-template <class T>
-class QItemEditorCreator : public QItemEditorCreatorBase
-{
-public:
- inline QItemEditorCreator(const QByteArray &valuePropertyName);
- inline QWidget *createWidget(QWidget *parent) const { return new T(parent); }
- inline QByteArray valuePropertyName() const { return propertyName; }
-
-private:
- QByteArray propertyName;
-};
-
-template <class T>
-class QStandardItemEditorCreator: public QItemEditorCreatorBase
-{
-public:
- inline QStandardItemEditorCreator()
- : propertyName(T::staticMetaObject.userProperty().name())
- {}
- inline QWidget *createWidget(QWidget *parent) const { return new T(parent); }
- inline QByteArray valuePropertyName() const { return propertyName; }
-
-private:
- QByteArray propertyName;
-};
-
-
-template <class T>
-Q_INLINE_TEMPLATE QItemEditorCreator<T>::QItemEditorCreator(const QByteArray &avaluePropertyName)
- : propertyName(avaluePropertyName) {}
-
-class Q_GUI_EXPORT QItemEditorFactory
-{
-public:
- inline QItemEditorFactory() {}
- virtual ~QItemEditorFactory();
-
- virtual QWidget *createEditor(QVariant::Type type, QWidget *parent) const;
- virtual QByteArray valuePropertyName(QVariant::Type type) const;
-
- void registerEditor(QVariant::Type type, QItemEditorCreatorBase *creator);
-
- static const QItemEditorFactory *defaultFactory();
- static void setDefaultFactory(QItemEditorFactory *factory);
-
-private:
- QHash<QVariant::Type, QItemEditorCreatorBase *> creatorMap;
-};
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QITEMEDITORFACTORY_H
diff --git a/src/gui/itemviews/qitemeditorfactory_p.h b/src/gui/itemviews/qitemeditorfactory_p.h
deleted file mode 100644
index 87b39c7a12..0000000000
--- a/src/gui/itemviews/qitemeditorfactory_p.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** 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 QITEMEDITORFACTORY_P_H
-#define QITEMEDITORFACTORY_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-
-
-#include <qlineedit.h>
-
-#ifndef QT_NO_ITEMVIEWS
-
-#ifndef QT_NO_LINEEDIT
-
-QT_BEGIN_NAMESPACE
-
-
-class QExpandingLineEdit : public QLineEdit
-{
- Q_OBJECT
-
-public:
- QExpandingLineEdit(QWidget *parent);
-
- void setWidgetOwnsGeometry(bool value)
- {
- widgetOwnsGeometry = value;
- }
-
-protected:
- void changeEvent(QEvent *e);
-
-public Q_SLOTS:
- void resizeToContents();
-
-private:
- void updateMinimumWidth();
-
- int originalWidth;
- bool widgetOwnsGeometry;
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_LINEEDIT
-
-#endif //QT_NO_ITEMVIEWS
-
-#endif //QITEMEDITORFACTORY_P_H
diff --git a/src/gui/itemviews/qitemselectionmodel.cpp b/src/gui/itemviews/qitemselectionmodel.cpp
deleted file mode 100644
index 27a4a402e2..0000000000
--- a/src/gui/itemviews/qitemselectionmodel.cpp
+++ /dev/null
@@ -1,1625 +0,0 @@
-/****************************************************************************
-**
-** 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 "qitemselectionmodel.h"
-#include <private/qitemselectionmodel_p.h>
-#include <qdebug.h>
-
-#ifndef QT_NO_ITEMVIEWS
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QItemSelectionRange
-
- \brief The QItemSelectionRange class manages information about a
- range of selected items in a model.
-
- \ingroup model-view
-
- A QItemSelectionRange contains information about a range of
- selected items in a model. A range of items is a contiguous array
- of model items, extending to cover a number of adjacent rows and
- columns with a common parent item; this can be visualized as a
- two-dimensional block of cells in a table. A selection range has a
- top(), left() a bottom(), right() and a parent().
-
- The QItemSelectionRange class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- The model items contained in the selection range can be obtained
- using the indexes() function. Use QItemSelectionModel::selectedIndexes()
- to get a list of all selected items for a view.
-
- You can determine whether a given model item lies within a
- particular range by using the contains() function. Ranges can also
- be compared using the overloaded operators for equality and
- inequality, and the intersects() function allows you to determine
- whether two ranges overlap.
-
- \sa {Model/View Programming}, QAbstractItemModel, QItemSelection,
- QItemSelectionModel
-*/
-
-/*!
- \fn QItemSelectionRange::QItemSelectionRange()
-
- Constructs an empty selection range.
-*/
-
-/*!
- \fn QItemSelectionRange::QItemSelectionRange(const QItemSelectionRange &other)
-
- Copy constructor. Constructs a new selection range with the same contents
- as the \a other range given.
-
-*/
-
-/*!
- \fn QItemSelectionRange::QItemSelectionRange(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-
- Constructs a new selection range containing only the index specified
- by the \a topLeft and the index \a bottomRight.
-
-*/
-
-/*!
- \fn QItemSelectionRange::QItemSelectionRange(const QModelIndex &index)
-
- Constructs a new selection range containing only the model item specified
- by the model index \a index.
-*/
-
-/*!
- \fn int QItemSelectionRange::top() const
-
- Returns the row index corresponding to the uppermost selected row in the
- selection range.
-
-*/
-
-/*!
- \fn int QItemSelectionRange::left() const
-
- Returns the column index corresponding to the leftmost selected column in the
- selection range.
-*/
-
-/*!
- \fn int QItemSelectionRange::bottom() const
-
- Returns the row index corresponding to the lowermost selected row in the
- selection range.
-
-*/
-
-/*!
- \fn int QItemSelectionRange::right() const
-
- Returns the column index corresponding to the rightmost selected column in
- the selection range.
-
-*/
-
-/*!
- \fn int QItemSelectionRange::width() const
-
- Returns the number of selected columns in the selection range.
-
-*/
-
-/*!
- \fn int QItemSelectionRange::height() const
-
- Returns the number of selected rows in the selection range.
-
-*/
-
-/*!
- \fn const QAbstractItemModel *QItemSelectionRange::model() const
-
- Returns the model that the items in the selection range belong to.
-*/
-
-/*!
- \fn QModelIndex QItemSelectionRange::topLeft() const
-
- Returns the index for the item located at the top-left corner of
- the selection range.
-
- \sa top(), left(), bottomRight()
-*/
-
-/*!
- \fn QModelIndex QItemSelectionRange::bottomRight() const
-
- Returns the index for the item located at the bottom-right corner
- of the selection range.
-
- \sa bottom(), right(), topLeft()
-*/
-
-/*!
- \fn QModelIndex QItemSelectionRange::parent() const
-
- Returns the parent model item index of the items in the selection range.
-
-*/
-
-/*!
- \fn bool QItemSelectionRange::contains(const QModelIndex &index) const
-
- Returns true if the model item specified by the \a index lies within the
- range of selected items; otherwise returns false.
-*/
-
-/*!
- \fn bool QItemSelectionRange::contains(int row, int column,
- const QModelIndex &parentIndex) const
- \overload
-
- Returns true if the model item specified by (\a row, \a column)
- and with \a parentIndex as the parent item lies within the range
- of selected items; otherwise returns false.
-*/
-
-/*!
- \fn bool QItemSelectionRange::intersects(const QItemSelectionRange &other) const
-
- Returns true if this selection range intersects (overlaps with) the \a other
- range given; otherwise returns false.
-
-*/
-bool QItemSelectionRange::intersects(const QItemSelectionRange &other) const
-{
- return (isValid() && other.isValid()
- && parent() == other.parent()
- && model() == other.model()
- && ((top() <= other.top() && bottom() >= other.top())
- || (top() >= other.top() && top() <= other.bottom()))
- && ((left() <= other.left() && right() >= other.left())
- || (left() >= other.left() && left() <= other.right())));
-}
-
-/*!
- \fn QItemSelectionRange QItemSelectionRange::intersect(const QItemSelectionRange &other) const
- \obsolete
-
- Use intersected(\a other) instead.
-*/
-
-/*!
- \fn QItemSelectionRange QItemSelectionRange::intersected(const QItemSelectionRange &other) const
- \since 4.2
-
- Returns a new selection range containing only the items that are found in
- both the selection range and the \a other selection range.
-*/
-
-QItemSelectionRange QItemSelectionRange::intersect(const QItemSelectionRange &other) const
-{
- if (model() == other.model() && parent() == other.parent()) {
- QModelIndex topLeft = model()->index(qMax(top(), other.top()),
- qMax(left(), other.left()),
- other.parent());
- QModelIndex bottomRight = model()->index(qMin(bottom(), other.bottom()),
- qMin(right(), other.right()),
- other.parent());
- return QItemSelectionRange(topLeft, bottomRight);
- }
- return QItemSelectionRange();
-}
-
-/*!
- \fn bool QItemSelectionRange::operator==(const QItemSelectionRange &other) const
-
- Returns true if the selection range is exactly the same as the \a other
- range given; otherwise returns false.
-
-*/
-
-/*!
- \fn bool QItemSelectionRange::operator!=(const QItemSelectionRange &other) const
-
- Returns true if the selection range differs from the \a other range given;
- otherwise returns false.
-
-*/
-
-/*!
- \fn bool QItemSelectionRange::isValid() const
-
- Returns true if the selection range is valid; otherwise returns false.
-
-*/
-
-/*
- \internal
-
- utility function for getting the indexes from a range
- it avoid concatenating list and works on one
- */
-
-static void indexesFromRange(const QItemSelectionRange &range, QModelIndexList &result)
-{
- if (range.isValid() && range.model()) {
- for (int column = range.left(); column <= range.right(); ++column) {
- for (int row = range.top(); row <= range.bottom(); ++row) {
- QModelIndex index = range.model()->index(row, column, range.parent());
- Qt::ItemFlags flags = range.model()->flags(index);
- if ((flags & Qt::ItemIsSelectable) && (flags & Qt::ItemIsEnabled))
- result.append(index);
- }
- }
- }
-}
-
-/*!
- Returns true if the selection range contains no selectable item
- \since 4.7
-*/
-
-bool QItemSelectionRange::isEmpty() const
-{
- if (!isValid() || !model())
- return true;
-
- for (int column = left(); column <= right(); ++column) {
- for (int row = top(); row <= bottom(); ++row) {
- QModelIndex index = model()->index(row, column, parent());
- Qt::ItemFlags flags = model()->flags(index);
- if ((flags & Qt::ItemIsSelectable) && (flags & Qt::ItemIsEnabled))
- return false;
- }
- }
- return true;
-}
-
-/*!
- Returns the list of model index items stored in the selection.
-*/
-
-QModelIndexList QItemSelectionRange::indexes() const
-{
- QModelIndexList result;
- indexesFromRange(*this, result);
- return result;
-}
-
-/*!
- \class QItemSelection
-
- \brief The QItemSelection class manages information about selected items in a model.
-
- \ingroup model-view
-
- A QItemSelection describes the items in a model that have been
- selected by the user. A QItemSelection is basically a list of
- selection ranges, see QItemSelectionRange. It provides functions for
- creating and manipulating selections, and selecting a range of items
- from a model.
-
- The QItemSelection class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- An item selection can be constructed and initialized to contain a
- range of items from an existing model. The following example constructs
- a selection that contains a range of items from the given \c model,
- beginning at the \c topLeft, and ending at the \c bottomRight.
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp 0
-
- An empty item selection can be constructed, and later populated as
- required. So, if the model is going to be unavailable when we construct
- the item selection, we can rewrite the above code in the following way:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp 1
-
- QItemSelection saves memory, and avoids unnecessary work, by working with
- selection ranges rather than recording the model item index for each
- item in the selection. Generally, an instance of this class will contain
- a list of non-overlapping selection ranges.
-
- Use merge() to merge one item selection into another without making
- overlapping ranges. Use split() to split one selection range into
- smaller ranges based on a another selection range.
-
- \sa {Model/View Programming}, QItemSelectionModel
-*/
-
-/*!
- \fn QItemSelection::QItemSelection()
-
- Constructs an empty selection.
-*/
-
-/*!
- Constructs an item selection that extends from the top-left model item,
- specified by the \a topLeft index, to the bottom-right item, specified
- by \a bottomRight.
-*/
-QItemSelection::QItemSelection(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- select(topLeft, bottomRight);
-}
-
-/*!
- Adds the items in the range that extends from the top-left model
- item, specified by the \a topLeft index, to the bottom-right item,
- specified by \a bottomRight to the list.
-
- \note \a topLeft and \a bottomRight must have the same parent.
-*/
-void QItemSelection::select(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- if (!topLeft.isValid() || !bottomRight.isValid())
- return;
-
- if ((topLeft.model() != bottomRight.model())
- || topLeft.parent() != bottomRight.parent()) {
- qWarning("Can't select indexes from different model or with different parents");
- return;
- }
- if (topLeft.row() > bottomRight.row() || topLeft.column() > bottomRight.column()) {
- int top = qMin(topLeft.row(), bottomRight.row());
- int bottom = qMax(topLeft.row(), bottomRight.row());
- int left = qMin(topLeft.column(), bottomRight.column());
- int right = qMax(topLeft.column(), bottomRight.column());
- QModelIndex tl = topLeft.sibling(top, left);
- QModelIndex br = bottomRight.sibling(bottom, right);
- append(QItemSelectionRange(tl, br));
- return;
- }
- append(QItemSelectionRange(topLeft, bottomRight));
-}
-
-/*!
- Returns true if the selection contains the given \a index; otherwise
- returns false.
-*/
-
-bool QItemSelection::contains(const QModelIndex &index) const
-{
- if (index.flags() & Qt::ItemIsSelectable) {
- QList<QItemSelectionRange>::const_iterator it = begin();
- for (; it != end(); ++it)
- if ((*it).contains(index))
- return true;
- }
- return false;
-}
-
-/*!
- Returns a list of model indexes that correspond to the selected items.
-*/
-
-QModelIndexList QItemSelection::indexes() const
-{
- QModelIndexList result;
- QList<QItemSelectionRange>::const_iterator it = begin();
- for (; it != end(); ++it)
- indexesFromRange(*it, result);
- return result;
-}
-
-/*!
- Merges the \a other selection with this QItemSelection using the
- \a command given. This method guarantees that no ranges are overlapping.
-
- Note that only QItemSelectionModel::Select,
- QItemSelectionModel::Deselect, and QItemSelectionModel::Toggle are
- supported.
-
- \sa split()
-*/
-void QItemSelection::merge(const QItemSelection &other, QItemSelectionModel::SelectionFlags command)
-{
- if (other.isEmpty() ||
- !(command & QItemSelectionModel::Select ||
- command & QItemSelectionModel::Deselect ||
- command & QItemSelectionModel::Toggle))
- return;
-
- QItemSelection newSelection = other;
- // Collect intersections
- QItemSelection intersections;
- QItemSelection::iterator it = newSelection.begin();
- while (it != newSelection.end()) {
- if (!(*it).isValid()) {
- it = newSelection.erase(it);
- continue;
- }
- for (int t = 0; t < count(); ++t) {
- if ((*it).intersects(at(t)))
- intersections.append(at(t).intersected(*it));
- }
- ++it;
- }
-
- // Split the old (and new) ranges using the intersections
- for (int i = 0; i < intersections.count(); ++i) { // for each intersection
- for (int t = 0; t < count();) { // splitt each old range
- if (at(t).intersects(intersections.at(i))) {
- split(at(t), intersections.at(i), this);
- removeAt(t);
- } else {
- ++t;
- }
- }
- // only split newSelection if Toggle is specified
- for (int n = 0; (command & QItemSelectionModel::Toggle) && n < newSelection.count();) {
- if (newSelection.at(n).intersects(intersections.at(i))) {
- split(newSelection.at(n), intersections.at(i), &newSelection);
- newSelection.removeAt(n);
- } else {
- ++n;
- }
- }
- }
- // do not add newSelection for Deselect
- if (!(command & QItemSelectionModel::Deselect))
- operator+=(newSelection);
-}
-
-/*!
- Splits the selection \a range using the selection \a other range.
- Removes all items in \a other from \a range and puts the result in \a result.
- This can be compared with the semantics of the \e subtract operation of a set.
- \sa merge()
-*/
-
-void QItemSelection::split(const QItemSelectionRange &range,
- const QItemSelectionRange &other, QItemSelection *result)
-{
- if (range.parent() != other.parent() || range.model() != other.model())
- return;
-
- QModelIndex parent = other.parent();
- int top = range.top();
- int left = range.left();
- int bottom = range.bottom();
- int right = range.right();
- int other_top = other.top();
- int other_left = other.left();
- int other_bottom = other.bottom();
- int other_right = other.right();
- const QAbstractItemModel *model = range.model();
- Q_ASSERT(model);
- if (other_top > top) {
- QModelIndex tl = model->index(top, left, parent);
- QModelIndex br = model->index(other_top - 1, right, parent);
- result->append(QItemSelectionRange(tl, br));
- top = other_top;
- }
- if (other_bottom < bottom) {
- QModelIndex tl = model->index(other_bottom + 1, left, parent);
- QModelIndex br = model->index(bottom, right, parent);
- result->append(QItemSelectionRange(tl, br));
- bottom = other_bottom;
- }
- if (other_left > left) {
- QModelIndex tl = model->index(top, left, parent);
- QModelIndex br = model->index(bottom, other_left - 1, parent);
- result->append(QItemSelectionRange(tl, br));
- left = other_left;
- }
- if (other_right < right) {
- QModelIndex tl = model->index(top, other_right + 1, parent);
- QModelIndex br = model->index(bottom, right, parent);
- result->append(QItemSelectionRange(tl, br));
- right = other_right;
- }
-}
-
-
-void QItemSelectionModelPrivate::initModel(QAbstractItemModel *model)
-{
- this->model = model;
- if (model) {
- Q_Q(QItemSelectionModel);
- QObject::connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- q, SLOT(_q_rowsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- q, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- q, SLOT(_q_rowsAboutToBeInserted(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- q, SLOT(_q_columnsAboutToBeInserted(QModelIndex,int,int)));
- QObject::connect(model, SIGNAL(layoutAboutToBeChanged()),
- q, SLOT(_q_layoutAboutToBeChanged()));
- QObject::connect(model, SIGNAL(layoutChanged()),
- q, SLOT(_q_layoutChanged()));
- }
-}
-
-/*!
- \internal
-
- returns a QItemSelection where all ranges have been expanded to:
- Rows: left: 0 and right: columnCount()-1
- Columns: top: 0 and bottom: rowCount()-1
-*/
-
-QItemSelection QItemSelectionModelPrivate::expandSelection(const QItemSelection &selection,
- QItemSelectionModel::SelectionFlags command) const
-{
- if (selection.isEmpty() && !((command & QItemSelectionModel::Rows) ||
- (command & QItemSelectionModel::Columns)))
- return selection;
-
- QItemSelection expanded;
- if (command & QItemSelectionModel::Rows) {
- for (int i = 0; i < selection.count(); ++i) {
- QModelIndex parent = selection.at(i).parent();
- int colCount = model->columnCount(parent);
- QModelIndex tl = model->index(selection.at(i).top(), 0, parent);
- QModelIndex br = model->index(selection.at(i).bottom(), colCount - 1, parent);
- //we need to merge because the same row could have already been inserted
- expanded.merge(QItemSelection(tl, br), QItemSelectionModel::Select);
- }
- }
- if (command & QItemSelectionModel::Columns) {
- for (int i = 0; i < selection.count(); ++i) {
- QModelIndex parent = selection.at(i).parent();
- int rowCount = model->rowCount(parent);
- QModelIndex tl = model->index(0, selection.at(i).left(), parent);
- QModelIndex br = model->index(rowCount - 1, selection.at(i).right(), parent);
- //we need to merge because the same column could have already been inserted
- expanded.merge(QItemSelection(tl, br), QItemSelectionModel::Select);
- }
- }
- return expanded;
-}
-
-/*!
- \internal
-*/
-void QItemSelectionModelPrivate::_q_rowsAboutToBeRemoved(const QModelIndex &parent,
- int start, int end)
-{
- Q_Q(QItemSelectionModel);
- finalize();
-
- // update current index
- if (currentIndex.isValid() && parent == currentIndex.parent()
- && currentIndex.row() >= start && currentIndex.row() <= end) {
- QModelIndex old = currentIndex;
- if (start > 0) // there are rows left above the change
- currentIndex = model->index(start - 1, old.column(), parent);
- else if (model && end < model->rowCount(parent) - 1) // there are rows left below the change
- currentIndex = model->index(end + 1, old.column(), parent);
- else // there are no rows left in the table
- currentIndex = QModelIndex();
- emit q->currentChanged(currentIndex, old);
- emit q->currentRowChanged(currentIndex, old);
- if (currentIndex.column() != old.column())
- emit q->currentColumnChanged(currentIndex, old);
- }
-
- QItemSelection deselected;
- QItemSelection newParts;
- QItemSelection::iterator it = ranges.begin();
- while (it != ranges.end()) {
- if (it->topLeft().parent() != parent) { // Check parents until reaching root or contained in range
- QModelIndex itParent = it->topLeft().parent();
- while (itParent.isValid() && itParent.parent() != parent)
- itParent = itParent.parent();
-
- if (itParent.isValid() && start <= itParent.row() && itParent.row() <= end) {
- deselected.append(*it);
- it = ranges.erase(it);
- } else {
- ++it;
- }
- } else if (start <= it->bottom() && it->bottom() <= end // Full inclusion
- && start <= it->top() && it->top() <= end) {
- deselected.append(*it);
- it = ranges.erase(it);
- } else if (start <= it->top() && it->top() <= end) { // Top intersection
- deselected.append(QItemSelectionRange(it->topLeft(), model->index(end, it->left(), it->parent())));
- *it = QItemSelectionRange(model->index(end + 1, it->left(), it->parent()), it->bottomRight());
- ++it;
- } else if (start <= it->bottom() && it->bottom() <= end) { // Bottom intersection
- deselected.append(QItemSelectionRange(model->index(start, it->right(), it->parent()), it->bottomRight()));
- *it = QItemSelectionRange(it->topLeft(), model->index(start - 1, it->right(), it->parent()));
- ++it;
- } else if (it->top() < start && end < it->bottom()) { // Middle intersection
- // If the parent contains (1, 2, 3, 4, 5, 6, 7, 8) and [3, 4, 5, 6] is selected,
- // and [4, 5] is removed, we need to split [3, 4, 5, 6] into [3], [4, 5] and [6].
- // [4, 5] is appended to deselected, and [3] and [6] remain part of the selection
- // in ranges.
- const QItemSelectionRange removedRange(model->index(start, it->right(), it->parent()),
- model->index(end, it->left(), it->parent()));
- deselected.append(removedRange);
- QItemSelection::split(*it, removedRange, &newParts);
- it = ranges.erase(it);
- } else
- ++it;
- }
- ranges.append(newParts);
-
- if (!deselected.isEmpty())
- emit q->selectionChanged(QItemSelection(), deselected);
-}
-
-/*!
- \internal
-*/
-void QItemSelectionModelPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent,
- int start, int end)
-{
- Q_Q(QItemSelectionModel);
-
- // update current index
- if (currentIndex.isValid() && parent == currentIndex.parent()
- && currentIndex.column() >= start && currentIndex.column() <= end) {
- QModelIndex old = currentIndex;
- if (start > 0) // there are columns to the left of the change
- currentIndex = model->index(old.row(), start - 1, parent);
- else if (model && end < model->columnCount() - 1) // there are columns to the right of the change
- currentIndex = model->index(old.row(), end + 1, parent);
- else // there are no columns left in the table
- currentIndex = QModelIndex();
- emit q->currentChanged(currentIndex, old);
- if (currentIndex.row() != old.row())
- emit q->currentRowChanged(currentIndex, old);
- emit q->currentColumnChanged(currentIndex, old);
- }
-
- // update selections
- QModelIndex tl = model->index(0, start, parent);
- QModelIndex br = model->index(model->rowCount(parent) - 1, end, parent);
- q->select(QItemSelection(tl, br), QItemSelectionModel::Deselect);
- finalize();
-}
-
-/*!
- \internal
-
- Split selection ranges if columns are about to be inserted in the middle.
-*/
-void QItemSelectionModelPrivate::_q_columnsAboutToBeInserted(const QModelIndex &parent,
- int start, int end)
-{
- Q_UNUSED(end);
- finalize();
- QList<QItemSelectionRange> split;
- QList<QItemSelectionRange>::iterator it = ranges.begin();
- for (; it != ranges.end(); ) {
- if ((*it).isValid() && (*it).parent() == parent
- && (*it).left() < start && (*it).right() >= start) {
- QModelIndex bottomMiddle = model->index((*it).bottom(), start - 1, (*it).parent());
- QItemSelectionRange left((*it).topLeft(), bottomMiddle);
- QModelIndex topMiddle = model->index((*it).top(), start, (*it).parent());
- QItemSelectionRange right(topMiddle, (*it).bottomRight());
- it = ranges.erase(it);
- split.append(left);
- split.append(right);
- } else {
- ++it;
- }
- }
- ranges += split;
-}
-
-/*!
- \internal
-
- Split selection ranges if rows are about to be inserted in the middle.
-*/
-void QItemSelectionModelPrivate::_q_rowsAboutToBeInserted(const QModelIndex &parent,
- int start, int end)
-{
- Q_UNUSED(end);
- finalize();
- QList<QItemSelectionRange> split;
- QList<QItemSelectionRange>::iterator it = ranges.begin();
- for (; it != ranges.end(); ) {
- if ((*it).isValid() && (*it).parent() == parent
- && (*it).top() < start && (*it).bottom() >= start) {
- QModelIndex middleRight = model->index(start - 1, (*it).right(), (*it).parent());
- QItemSelectionRange top((*it).topLeft(), middleRight);
- QModelIndex middleLeft = model->index(start, (*it).left(), (*it).parent());
- QItemSelectionRange bottom(middleLeft, (*it).bottomRight());
- it = ranges.erase(it);
- split.append(top);
- split.append(bottom);
- } else {
- ++it;
- }
- }
- ranges += split;
-}
-
-/*!
- \internal
-
- Split selection into individual (persistent) indexes. This is done in
- preparation for the layoutChanged() signal, where the indexes can be
- merged again.
-*/
-void QItemSelectionModelPrivate::_q_layoutAboutToBeChanged()
-{
- savedPersistentIndexes.clear();
- savedPersistentCurrentIndexes.clear();
-
- // optimization for when all indexes are selected
- // (only if there is lots of items (1000) because this is not entirely correct)
- if (ranges.isEmpty() && currentSelection.count() == 1) {
- QItemSelectionRange range = currentSelection.first();
- QModelIndex parent = range.parent();
- tableRowCount = model->rowCount(parent);
- tableColCount = model->columnCount(parent);
- if (tableRowCount * tableColCount > 1000
- && range.top() == 0
- && range.left() == 0
- && range.bottom() == tableRowCount - 1
- && range.right() == tableColCount - 1) {
- tableSelected = true;
- tableParent = parent;
- return;
- }
- }
- tableSelected = false;
-
- QModelIndexList indexes = ranges.indexes();
- QModelIndexList::const_iterator it;
- for (it = indexes.constBegin(); it != indexes.constEnd(); ++it)
- savedPersistentIndexes.append(QPersistentModelIndex(*it));
- indexes = currentSelection.indexes();
- for (it = indexes.constBegin(); it != indexes.constEnd(); ++it)
- savedPersistentCurrentIndexes.append(QPersistentModelIndex(*it));
-}
-
-/*!
- \internal
-
- Merges \a indexes into an item selection made up of ranges.
- Assumes that the indexes are sorted.
-*/
-static QItemSelection mergeIndexes(const QList<QPersistentModelIndex> &indexes)
-{
- QItemSelection colSpans;
- // merge columns
- int i = 0;
- while (i < indexes.count()) {
- QModelIndex tl = indexes.at(i);
- QModelIndex br = tl;
- while (++i < indexes.count()) {
- QModelIndex next = indexes.at(i);
- if ((next.parent() == br.parent())
- && (next.row() == br.row())
- && (next.column() == br.column() + 1))
- br = next;
- else
- break;
- }
- colSpans.append(QItemSelectionRange(tl, br));
- }
- // merge rows
- QItemSelection rowSpans;
- i = 0;
- while (i < colSpans.count()) {
- QModelIndex tl = colSpans.at(i).topLeft();
- QModelIndex br = colSpans.at(i).bottomRight();
- QModelIndex prevTl = tl;
- while (++i < colSpans.count()) {
- QModelIndex nextTl = colSpans.at(i).topLeft();
- QModelIndex nextBr = colSpans.at(i).bottomRight();
-
- if (nextTl.parent() != tl.parent())
- break; // we can't merge selection ranges from different parents
-
- if ((nextTl.column() == prevTl.column()) && (nextBr.column() == br.column())
- && (nextTl.row() == prevTl.row() + 1) && (nextBr.row() == br.row() + 1)) {
- br = nextBr;
- prevTl = nextTl;
- } else {
- break;
- }
- }
- rowSpans.append(QItemSelectionRange(tl, br));
- }
- return rowSpans;
-}
-
-/*!
- \internal
-
- Merge the selected indexes into selection ranges again.
-*/
-void QItemSelectionModelPrivate::_q_layoutChanged()
-{
- // special case for when all indexes are selected
- if (tableSelected && tableColCount == model->columnCount(tableParent)
- && tableRowCount == model->rowCount(tableParent)) {
- ranges.clear();
- currentSelection.clear();
- int bottom = tableRowCount - 1;
- int right = tableColCount - 1;
- QModelIndex tl = model->index(0, 0, tableParent);
- QModelIndex br = model->index(bottom, right, tableParent);
- currentSelection << QItemSelectionRange(tl, br);
- tableParent = QModelIndex();
- tableSelected = false;
- return;
- }
-
- if (savedPersistentCurrentIndexes.isEmpty() && savedPersistentIndexes.isEmpty()) {
- // either the selection was actually empty, or we
- // didn't get the layoutAboutToBeChanged() signal
- return;
- }
- // clear the "old" selection
- ranges.clear();
- currentSelection.clear();
-
- // sort the "new" selection, as preparation for merging
- qStableSort(savedPersistentIndexes.begin(), savedPersistentIndexes.end());
- qStableSort(savedPersistentCurrentIndexes.begin(), savedPersistentCurrentIndexes.end());
-
- // update the selection by merging the individual indexes
- ranges = mergeIndexes(savedPersistentIndexes);
- currentSelection = mergeIndexes(savedPersistentCurrentIndexes);
-
- // release the persistent indexes
- savedPersistentIndexes.clear();
- savedPersistentCurrentIndexes.clear();
-}
-
-/*!
- \class QItemSelectionModel
-
- \brief The QItemSelectionModel class keeps track of a view's selected items.
-
- \ingroup model-view
-
- A QItemSelectionModel keeps track of the selected items in a view, or
- in several views onto the same model. It also keeps track of the
- currently selected item in a view.
-
- The QItemSelectionModel class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- The selected items are stored using ranges. Whenever you want to
- modify the selected items use select() and provide either a
- QItemSelection, or a QModelIndex and a QItemSelectionModel::SelectionFlag.
-
- The QItemSelectionModel takes a two layer approach to selection
- management, dealing with both selected items that have been committed
- and items that are part of the current selection. The current
- selected items are part of the current interactive selection (for
- example with rubber-band selection or keyboard-shift selections).
-
- To update the currently selected items, use the bitwise OR of
- QItemSelectionModel::Current and any of the other SelectionFlags.
- If you omit the QItemSelectionModel::Current command, a new current
- selection will be created, and the previous one added to the whole
- selection. All functions operate on both layers; for example,
- selectedItems() will return items from both layers.
-
- \sa {Model/View Programming}, QAbstractItemModel, {Chart Example}
-*/
-
-/*!
- Constructs a selection model that operates on the specified item \a model.
-*/
-QItemSelectionModel::QItemSelectionModel(QAbstractItemModel *model)
- : QObject(*new QItemSelectionModelPrivate, model)
-{
- d_func()->initModel(model);
-}
-
-/*!
- Constructs a selection model that operates on the specified item \a model with \a parent.
-*/
-QItemSelectionModel::QItemSelectionModel(QAbstractItemModel *model, QObject *parent)
- : QObject(*new QItemSelectionModelPrivate, parent)
-{
- d_func()->initModel(model);
-}
-
-/*!
- \internal
-*/
-QItemSelectionModel::QItemSelectionModel(QItemSelectionModelPrivate &dd, QAbstractItemModel *model)
- : QObject(dd, model)
-{
- dd.initModel(model);
-}
-
-/*!
- Destroys the selection model.
-*/
-QItemSelectionModel::~QItemSelectionModel()
-{
-}
-
-/*!
- Selects the model item \a index using the specified \a command, and emits
- selectionChanged().
-
- \sa QItemSelectionModel::SelectionFlags
-*/
-void QItemSelectionModel::select(const QModelIndex &index, QItemSelectionModel::SelectionFlags command)
-{
- QItemSelection selection(index, index);
- select(selection, command);
-}
-
-/*!
- \fn void QItemSelectionModel::currentChanged(const QModelIndex &current, const QModelIndex &previous)
-
- This signal is emitted whenever the current item changes. The \a previous
- model item index is replaced by the \a current index as the selection's
- current item.
-
- Note that this signal will not be emitted when the item model is reset.
-
- \sa currentIndex() setCurrentIndex() selectionChanged()
-*/
-
-/*!
- \fn void QItemSelectionModel::currentColumnChanged(const QModelIndex &current, const QModelIndex &previous)
-
- This signal is emitted if the \a current item changes and its column is
- different to the column of the \a previous current item.
-
- Note that this signal will not be emitted when the item model is reset.
-
- \sa currentChanged() currentRowChanged() currentIndex() setCurrentIndex()
-*/
-
-/*!
- \fn void QItemSelectionModel::currentRowChanged(const QModelIndex &current, const QModelIndex &previous)
-
- This signal is emitted if the \a current item changes and its row is
- different to the row of the \a previous current item.
-
- Note that this signal will not be emitted when the item model is reset.
-
- \sa currentChanged() currentColumnChanged() currentIndex() setCurrentIndex()
-*/
-
-/*!
- \fn void QItemSelectionModel::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
-
- This signal is emitted whenever the selection changes. The change in the
- selection is represented as an item selection of \a deselected items and
- an item selection of \a selected items.
-
- Note the that the current index changes independently from the selection.
- Also note that this signal will not be emitted when the item model is reset.
-
- \sa select() currentChanged()
-*/
-
-/*!
- \enum QItemSelectionModel::SelectionFlag
-
- This enum describes the way the selection model will be updated.
-
- \value NoUpdate No selection will be made.
- \value Clear The complete selection will be cleared.
- \value Select All specified indexes will be selected.
- \value Deselect All specified indexes will be deselected.
- \value Toggle All specified indexes will be selected or
- deselected depending on their current state.
- \value Current The current selection will be updated.
- \value Rows All indexes will be expanded to span rows.
- \value Columns All indexes will be expanded to span columns.
- \value SelectCurrent A combination of Select and Current, provided for
- convenience.
- \value ToggleCurrent A combination of Toggle and Current, provided for
- convenience.
- \value ClearAndSelect A combination of Clear and Select, provided for
- convenience.
-*/
-
-/*!
- Selects the item \a selection using the specified \a command, and emits
- selectionChanged().
-
- \sa QItemSelectionModel::SelectionFlag
-*/
-void QItemSelectionModel::select(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QItemSelectionModel);
- if (command == NoUpdate)
- return;
-
- // store old selection
- QItemSelection sel = selection;
- // If d->ranges is non-empty when the source model is reset the persistent indexes
- // it contains will be invalid. We can't clear them in a modelReset slot because that might already
- // be too late if another model observer is connected to the same modelReset slot and is invoked first
- // it might call select() on this selection model before any such QItemSelectionModelPrivate::_q_modelReset() slot
- // is invoked, so it would not be cleared yet. We clear it invalid ranges in it here.
- QItemSelection::iterator it = d->ranges.begin();
- while (it != d->ranges.end()) {
- if (!it->isValid())
- it = d->ranges.erase(it);
- else
- ++it;
- }
-
- QItemSelection old = d->ranges;
- old.merge(d->currentSelection, d->currentCommand);
-
- // expand selection according to SelectionBehavior
- if (command & Rows || command & Columns)
- sel = d->expandSelection(sel, command);
-
- // clear ranges and currentSelection
- if (command & Clear) {
- d->ranges.clear();
- d->currentSelection.clear();
- }
-
- // merge and clear currentSelection if Current was not set (ie. start new currentSelection)
- if (!(command & Current))
- d->finalize();
-
- // update currentSelection
- if (command & Toggle || command & Select || command & Deselect) {
- d->currentCommand = command;
- d->currentSelection = sel;
- }
-
- // generate new selection, compare with old and emit selectionChanged()
- QItemSelection newSelection = d->ranges;
- newSelection.merge(d->currentSelection, d->currentCommand);
- emitSelectionChanged(newSelection, old);
-}
-
-/*!
- Clears the selection model. Emits selectionChanged() and currentChanged().
-*/
-void QItemSelectionModel::clear()
-{
- Q_D(QItemSelectionModel);
- clearSelection();
- QModelIndex previous = d->currentIndex;
- d->currentIndex = QModelIndex();
- if (previous.isValid()) {
- emit currentChanged(d->currentIndex, previous);
- emit currentRowChanged(d->currentIndex, previous);
- emit currentColumnChanged(d->currentIndex, previous);
- }
-}
-
-/*!
- Clears the selection model. Does not emit any signals.
-*/
-void QItemSelectionModel::reset()
-{
- bool block = blockSignals(true);
- clear();
- blockSignals(block);
-}
-
-/*!
- \since 4.2
- Clears the selection in the selection model. Emits selectionChanged().
-*/
-void QItemSelectionModel::clearSelection()
-{
- Q_D(QItemSelectionModel);
- if (d->ranges.count() == 0 && d->currentSelection.count() == 0)
- return;
- QItemSelection selection = d->ranges;
- selection.merge(d->currentSelection, d->currentCommand);
- d->ranges.clear();
- d->currentSelection.clear();
- emit selectionChanged(QItemSelection(), selection);
-}
-
-
-/*!
- Sets the model item \a index to be the current item, and emits
- currentChanged(). The current item is used for keyboard navigation and
- focus indication; it is independent of any selected items, although a
- selected item can also be the current item.
-
- Depending on the specified \a command, the \a index can also become part
- of the current selection.
- \sa select()
-*/
-void QItemSelectionModel::setCurrentIndex(const QModelIndex &index, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QItemSelectionModel);
- if (index == d->currentIndex) {
- if (command != NoUpdate)
- select(index, command); // select item
- return;
- }
- QPersistentModelIndex previous = d->currentIndex;
- d->currentIndex = index; // set current before emitting selection changed below
- if (command != NoUpdate)
- select(d->currentIndex, command); // select item
- emit currentChanged(d->currentIndex, previous);
- if (d->currentIndex.row() != previous.row() ||
- d->currentIndex.parent() != previous.parent())
- emit currentRowChanged(d->currentIndex, previous);
- if (d->currentIndex.column() != previous.column() ||
- d->currentIndex.parent() != previous.parent())
- emit currentColumnChanged(d->currentIndex, previous);
-}
-
-/*!
- Returns the model item index for the current item, or an invalid index
- if there is no current item.
-*/
-QModelIndex QItemSelectionModel::currentIndex() const
-{
- return static_cast<QModelIndex>(d_func()->currentIndex);
-}
-
-/*!
- Returns true if the given model item \a index is selected.
-*/
-bool QItemSelectionModel::isSelected(const QModelIndex &index) const
-{
- Q_D(const QItemSelectionModel);
- if (d->model != index.model() || !index.isValid())
- return false;
-
- bool selected = false;
- // search model ranges
- QList<QItemSelectionRange>::const_iterator it = d->ranges.begin();
- for (; it != d->ranges.end(); ++it) {
- if ((*it).isValid() && (*it).contains(index)) {
- selected = true;
- break;
- }
- }
-
- // check currentSelection
- if (d->currentSelection.count()) {
- if ((d->currentCommand & Deselect) && selected)
- selected = !d->currentSelection.contains(index);
- else if (d->currentCommand & Toggle)
- selected ^= d->currentSelection.contains(index);
- else if ((d->currentCommand & Select) && !selected)
- selected = d->currentSelection.contains(index);
- }
-
- if (selected) {
- Qt::ItemFlags flags = d->model->flags(index);
- return (flags & Qt::ItemIsSelectable);
- }
-
- return false;
-}
-
-/*!
- Returns true if all items are selected in the \a row with the given
- \a parent.
-
- Note that this function is usually faster than calling isSelected()
- on all items in the same row and that unselectable items are
- ignored.
-*/
-bool QItemSelectionModel::isRowSelected(int row, const QModelIndex &parent) const
-{
- Q_D(const QItemSelectionModel);
- if (parent.isValid() && d->model != parent.model())
- return false;
-
- // return false if row exist in currentSelection (Deselect)
- if (d->currentCommand & Deselect && d->currentSelection.count()) {
- for (int i=0; i<d->currentSelection.count(); ++i) {
- if (d->currentSelection.at(i).parent() == parent &&
- row >= d->currentSelection.at(i).top() &&
- row <= d->currentSelection.at(i).bottom())
- return false;
- }
- }
- // return false if ranges in both currentSelection and ranges
- // intersect and have the same row contained
- if (d->currentCommand & Toggle && d->currentSelection.count()) {
- for (int i=0; i<d->currentSelection.count(); ++i)
- if (d->currentSelection.at(i).top() <= row &&
- d->currentSelection.at(i).bottom() >= row)
- for (int j=0; j<d->ranges.count(); ++j)
- if (d->ranges.at(j).top() <= row && d->ranges.at(j).bottom() >= row
- && d->currentSelection.at(i).intersected(d->ranges.at(j)).isValid())
- return false;
- }
- // add ranges and currentSelection and check through them all
- QList<QItemSelectionRange>::const_iterator it;
- QList<QItemSelectionRange> joined = d->ranges;
- if (d->currentSelection.count())
- joined += d->currentSelection;
- int colCount = d->model->columnCount(parent);
- for (int column = 0; column < colCount; ++column) {
- for (it = joined.constBegin(); it != joined.constEnd(); ++it) {
- if ((*it).contains(row, column, parent)) {
- bool selectable = false;
- for (int i = column; !selectable && i <= (*it).right(); ++i) {
- Qt::ItemFlags flags = d->model->index(row, i, parent).flags();
- selectable = flags & Qt::ItemIsSelectable;
- }
- if (selectable){
- column = qMax(column, (*it).right());
- break;
- }
- }
- }
- if (it == joined.constEnd())
- return false;
- }
- return colCount > 0; // no columns means no selected items
-}
-
-/*!
- Returns true if all items are selected in the \a column with the given
- \a parent.
-
- Note that this function is usually faster than calling isSelected()
- on all items in the same column and that unselectable items are
- ignored.
-*/
-bool QItemSelectionModel::isColumnSelected(int column, const QModelIndex &parent) const
-{
- Q_D(const QItemSelectionModel);
- if (parent.isValid() && d->model != parent.model())
- return false;
-
- // return false if column exist in currentSelection (Deselect)
- if (d->currentCommand & Deselect && d->currentSelection.count()) {
- for (int i = 0; i < d->currentSelection.count(); ++i) {
- if (d->currentSelection.at(i).parent() == parent &&
- column >= d->currentSelection.at(i).left() &&
- column <= d->currentSelection.at(i).right())
- return false;
- }
- }
- // return false if ranges in both currentSelection and the selection model
- // intersect and have the same column contained
- if (d->currentCommand & Toggle && d->currentSelection.count()) {
- for (int i = 0; i < d->currentSelection.count(); ++i) {
- if (d->currentSelection.at(i).left() <= column &&
- d->currentSelection.at(i).right() >= column) {
- for (int j = 0; j < d->ranges.count(); ++j) {
- if (d->ranges.at(j).left() <= column && d->ranges.at(j).right() >= column
- && d->currentSelection.at(i).intersected(d->ranges.at(j)).isValid()) {
- return false;
- }
- }
- }
- }
- }
- // add ranges and currentSelection and check through them all
- QList<QItemSelectionRange>::const_iterator it;
- QList<QItemSelectionRange> joined = d->ranges;
- if (d->currentSelection.count())
- joined += d->currentSelection;
- int rowCount = d->model->rowCount(parent);
- for (int row = 0; row < rowCount; ++row) {
- for (it = joined.constBegin(); it != joined.constEnd(); ++it) {
- if ((*it).contains(row, column, parent)) {
- Qt::ItemFlags flags = d->model->index(row, column, parent).flags();
- if ((flags & Qt::ItemIsSelectable) && (flags & Qt::ItemIsEnabled)) {
- row = qMax(row, (*it).bottom());
- break;
- }
- }
- }
- if (it == joined.constEnd())
- return false;
- }
- return rowCount > 0; // no rows means no selected items
-}
-
-/*!
- Returns true if there are any items selected in the \a row with the given
- \a parent.
-*/
-bool QItemSelectionModel::rowIntersectsSelection(int row, const QModelIndex &parent) const
-{
- Q_D(const QItemSelectionModel);
- if (parent.isValid() && d->model != parent.model())
- return false;
-
- QItemSelection sel = d->ranges;
- sel.merge(d->currentSelection, d->currentCommand);
- for (int i = 0; i < sel.count(); ++i) {
- int top = sel.at(i).top();
- int bottom = sel.at(i).bottom();
- int left = sel.at(i).left();
- int right = sel.at(i).right();
- if (top <= row && bottom >= row) {
- for (int j = left; j <= right; j++) {
- const Qt::ItemFlags flags = d->model->index(row, j, parent).flags();
- if ((flags & Qt::ItemIsSelectable) && (flags & Qt::ItemIsEnabled))
- return true;
- }
- }
- }
-
- return false;
-}
-
-/*!
- Returns true if there are any items selected in the \a column with the given
- \a parent.
-*/
-bool QItemSelectionModel::columnIntersectsSelection(int column, const QModelIndex &parent) const
-{
- Q_D(const QItemSelectionModel);
- if (parent.isValid() && d->model != parent.model())
- return false;
-
- QItemSelection sel = d->ranges;
- sel.merge(d->currentSelection, d->currentCommand);
- for (int i = 0; i < sel.count(); ++i) {
- int left = sel.at(i).left();
- int right = sel.at(i).right();
- int top = sel.at(i).top();
- int bottom = sel.at(i).bottom();
- if (left <= column && right >= column) {
- for (int j = top; j <= bottom; j++) {
- const Qt::ItemFlags flags = d->model->index(j, column, parent).flags();
- if ((flags & Qt::ItemIsSelectable) && (flags & Qt::ItemIsEnabled))
- return true;
- }
- }
- }
-
- return false;
-}
-
-/*!
- \since 4.2
-
- Returns true if the selection model contains any selection ranges;
- otherwise returns false.
-*/
-bool QItemSelectionModel::hasSelection() const
-{
- Q_D(const QItemSelectionModel);
- if (d->currentCommand & (Toggle | Deselect)) {
- QItemSelection sel = d->ranges;
- sel.merge(d->currentSelection, d->currentCommand);
- return !sel.isEmpty();
- } else {
- return !(d->ranges.isEmpty() && d->currentSelection.isEmpty());
- }
-}
-
-/*!
- Returns a list of all selected model item indexes. The list contains no
- duplicates, and is not sorted.
-*/
-QModelIndexList QItemSelectionModel::selectedIndexes() const
-{
- Q_D(const QItemSelectionModel);
- QItemSelection selected = d->ranges;
- selected.merge(d->currentSelection, d->currentCommand);
- return selected.indexes();
-}
-
-/*!
- \since 4.2
- Returns the indexes in the given \a column for the rows where all columns are selected.
-
- \sa selectedIndexes(), selectedColumns()
-*/
-
-QModelIndexList QItemSelectionModel::selectedRows(int column) const
-{
- QModelIndexList indexes;
- //the QSet contains pairs of parent modelIndex
- //and row number
- QSet< QPair<QModelIndex, int> > rowsSeen;
-
- const QItemSelection ranges = selection();
- for (int i = 0; i < ranges.count(); ++i) {
- const QItemSelectionRange &range = ranges.at(i);
- QModelIndex parent = range.parent();
- for (int row = range.top(); row <= range.bottom(); row++) {
- QPair<QModelIndex, int> rowDef = qMakePair(parent, row);
- if (!rowsSeen.contains(rowDef)) {
- rowsSeen << rowDef;
- if (isRowSelected(row, parent)) {
- indexes.append(model()->index(row, column, parent));
- }
- }
- }
- }
-
- return indexes;
-}
-
-/*!
- \since 4.2
- Returns the indexes in the given \a row for columns where all rows are selected.
-
- \sa selectedIndexes(), selectedRows()
-*/
-
-QModelIndexList QItemSelectionModel::selectedColumns(int row) const
-{
- QModelIndexList indexes;
- //the QSet contains pairs of parent modelIndex
- //and column number
- QSet< QPair<QModelIndex, int> > columnsSeen;
-
- const QItemSelection ranges = selection();
- for (int i = 0; i < ranges.count(); ++i) {
- const QItemSelectionRange &range = ranges.at(i);
- QModelIndex parent = range.parent();
- for (int column = range.left(); column <= range.right(); column++) {
- QPair<QModelIndex, int> columnDef = qMakePair(parent, column);
- if (!columnsSeen.contains(columnDef)) {
- columnsSeen << columnDef;
- if (isColumnSelected(column, parent)) {
- indexes.append(model()->index(row, column, parent));
- }
- }
- }
- }
-
- return indexes;
-}
-
-/*!
- Returns the selection ranges stored in the selection model.
-*/
-const QItemSelection QItemSelectionModel::selection() const
-{
- Q_D(const QItemSelectionModel);
- QItemSelection selected = d->ranges;
- selected.merge(d->currentSelection, d->currentCommand);
- int i = 0;
- // make sure we have no invalid ranges
- // ### should probably be handled more generic somewhere else
- while (i<selected.count()) {
- if (selected.at(i).isValid())
- ++i;
- else
- (selected.removeAt(i));
- }
- return selected;
-}
-
-/*!
- Returns the item model operated on by the selection model.
-*/
-const QAbstractItemModel *QItemSelectionModel::model() const
-{
- return d_func()->model;
-}
-
-/*!
- Compares the two selections \a newSelection and \a oldSelection
- and emits selectionChanged() with the deselected and selected items.
-*/
-void QItemSelectionModel::emitSelectionChanged(const QItemSelection &newSelection,
- const QItemSelection &oldSelection)
-{
- // if both selections are empty or equal we return
- if ((oldSelection.isEmpty() && newSelection.isEmpty()) ||
- oldSelection == newSelection)
- return;
-
- // if either selection is empty we do not need to compare
- if (oldSelection.isEmpty() || newSelection.isEmpty()) {
- emit selectionChanged(newSelection, oldSelection);
- return;
- }
-
- QItemSelection deselected = oldSelection;
- QItemSelection selected = newSelection;
-
- // remove equal ranges
- bool advance;
- for (int o = 0; o < deselected.count(); ++o) {
- advance = true;
- for (int s = 0; s < selected.count() && o < deselected.count();) {
- if (deselected.at(o) == selected.at(s)) {
- deselected.removeAt(o);
- selected.removeAt(s);
- advance = false;
- } else {
- ++s;
- }
- }
- if (advance)
- ++o;
- }
-
- // find intersections
- QItemSelection intersections;
- for (int o = 0; o < deselected.count(); ++o) {
- for (int s = 0; s < selected.count(); ++s) {
- if (deselected.at(o).intersects(selected.at(s)))
- intersections.append(deselected.at(o).intersected(selected.at(s)));
- }
- }
-
- // compare remaining ranges with intersections and split them to find deselected and selected
- for (int i = 0; i < intersections.count(); ++i) {
- // split deselected
- for (int o = 0; o < deselected.count();) {
- if (deselected.at(o).intersects(intersections.at(i))) {
- QItemSelection::split(deselected.at(o), intersections.at(i), &deselected);
- deselected.removeAt(o);
- } else {
- ++o;
- }
- }
- // split selected
- for (int s = 0; s < selected.count();) {
- if (selected.at(s).intersects(intersections.at(i))) {
- QItemSelection::split(selected.at(s), intersections.at(i), &selected);
- selected.removeAt(s);
- } else {
- ++s;
- }
- }
- }
-
- if (!selected.isEmpty() || !deselected.isEmpty())
- emit selectionChanged(selected, deselected);
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug dbg, const QItemSelectionRange &range)
-{
-#ifndef Q_BROKEN_DEBUG_STREAM
- dbg.nospace() << "QItemSelectionRange(" << range.topLeft()
- << ',' << range.bottomRight() << ')';
- return dbg.space();
-#else
- qWarning("This compiler doesn't support streaming QItemSelectionRange to QDebug");
- return dbg;
- Q_UNUSED(range);
-#endif
-}
-#endif
-
-QT_END_NAMESPACE
-
-#include "moc_qitemselectionmodel.cpp"
-
-#endif // QT_NO_ITEMVIEWS
diff --git a/src/gui/itemviews/qitemselectionmodel.h b/src/gui/itemviews/qitemselectionmodel.h
deleted file mode 100644
index 12b875b8ab..0000000000
--- a/src/gui/itemviews/qitemselectionmodel.h
+++ /dev/null
@@ -1,255 +0,0 @@
-/****************************************************************************
-**
-** 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 QITEMSELECTIONMODEL_H
-#define QITEMSELECTIONMODEL_H
-
-#include <QtCore/qset.h>
-#include <QtCore/qvector.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qabstractitemmodel.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class Q_GUI_EXPORT QItemSelectionRange
-{
-
-public:
- inline QItemSelectionRange() {}
- inline QItemSelectionRange(const QItemSelectionRange &other)
- : tl(other.tl), br(other.br) {}
- inline QItemSelectionRange(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- explicit inline QItemSelectionRange(const QModelIndex &index)
- { tl = index; br = tl; }
-
- inline int top() const { return tl.row(); }
- inline int left() const { return tl.column(); }
- inline int bottom() const { return br.row(); }
- inline int right() const { return br.column(); }
- inline int width() const { return br.column() - tl.column() + 1; }
- inline int height() const { return br.row() - tl.row() + 1; }
-
- inline QModelIndex topLeft() const { return QModelIndex(tl); }
- inline QModelIndex bottomRight() const { return QModelIndex(br); }
- inline QModelIndex parent() const { return tl.parent(); }
- inline const QAbstractItemModel *model() const { return tl.model(); }
-
- inline bool contains(const QModelIndex &index) const
- {
- return (parent() == index.parent()
- && tl.row() <= index.row() && tl.column() <= index.column()
- && br.row() >= index.row() && br.column() >= index.column());
- }
-
- inline bool contains(int row, int column, const QModelIndex &parentIndex) const
- {
- return (parent() == parentIndex
- && tl.row() <= row && tl.column() <= column
- && br.row() >= row && br.column() >= column);
- }
-
- bool intersects(const QItemSelectionRange &other) const;
- QItemSelectionRange intersect(const QItemSelectionRange &other) const; // ### Qt 5: make QT4_SUPPORT
- inline QItemSelectionRange intersected(const QItemSelectionRange &other) const
- { return intersect(other); }
-
- inline bool operator==(const QItemSelectionRange &other) const
- { return (tl == other.tl && br == other.br); }
- inline bool operator!=(const QItemSelectionRange &other) const
- { return !operator==(other); }
- inline bool operator<(const QItemSelectionRange &other) const
- {
- // Comparing parents will compare the models, but if two equivalent ranges
- // in two different models have invalid parents, they would appear the same
- if (other.tl.model() == tl.model()) {
- // parent has to be calculated, so we only do so once.
- const QModelIndex topLeftParent = tl.parent();
- const QModelIndex otherTopLeftParent = other.tl.parent();
- if (topLeftParent == otherTopLeftParent) {
- if (other.tl.row() == tl.row()) {
- if (other.tl.column() == tl.column()) {
- if (other.br.row() == br.row()) {
- return br.column() < other.br.column();
- }
- return br.row() < other.br.row();
- }
- return tl.column() < other.tl.column();
- }
- return tl.row() < other.tl.row();
- }
- return topLeftParent < otherTopLeftParent;
- }
- return tl.model() < other.tl.model();
- }
-
- inline bool isValid() const
- {
- return (tl.isValid() && br.isValid() && tl.parent() == br.parent()
- && top() <= bottom() && left() <= right());
- }
-
- bool isEmpty() const;
-
- QModelIndexList indexes() const;
-
-private:
- QPersistentModelIndex tl, br;
-};
-Q_DECLARE_TYPEINFO(QItemSelectionRange, Q_MOVABLE_TYPE);
-
-inline QItemSelectionRange::QItemSelectionRange(const QModelIndex &atopLeft,
- const QModelIndex &abottomRight)
-{ tl = atopLeft; br = abottomRight; }
-
-class QItemSelection;
-class QItemSelectionModelPrivate;
-
-class Q_GUI_EXPORT QItemSelectionModel : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QItemSelectionModel)
- Q_FLAGS(SelectionFlags)
-
-public:
-
- enum SelectionFlag {
- NoUpdate = 0x0000,
- Clear = 0x0001,
- Select = 0x0002,
- Deselect = 0x0004,
- Toggle = 0x0008,
- Current = 0x0010,
- Rows = 0x0020,
- Columns = 0x0040,
- SelectCurrent = Select | Current,
- ToggleCurrent = Toggle | Current,
- ClearAndSelect = Clear | Select
- };
-
- Q_DECLARE_FLAGS(SelectionFlags, SelectionFlag)
-
- explicit QItemSelectionModel(QAbstractItemModel *model);
- explicit QItemSelectionModel(QAbstractItemModel *model, QObject *parent);
- virtual ~QItemSelectionModel();
-
- QModelIndex currentIndex() const;
-
- bool isSelected(const QModelIndex &index) const;
- bool isRowSelected(int row, const QModelIndex &parent) const;
- bool isColumnSelected(int column, const QModelIndex &parent) const;
-
- bool rowIntersectsSelection(int row, const QModelIndex &parent) const;
- bool columnIntersectsSelection(int column, const QModelIndex &parent) const;
-
- bool hasSelection() const;
-
- QModelIndexList selectedIndexes() const;
- QModelIndexList selectedRows(int column = 0) const;
- QModelIndexList selectedColumns(int row = 0) const;
- const QItemSelection selection() const;
-
- const QAbstractItemModel *model() const;
-
-public Q_SLOTS:
- void setCurrentIndex(const QModelIndex &index, QItemSelectionModel::SelectionFlags command);
- virtual void select(const QModelIndex &index, QItemSelectionModel::SelectionFlags command);
- virtual void select(const QItemSelection &selection, QItemSelectionModel::SelectionFlags command);
- virtual void clear();
- virtual void reset();
-
- void clearSelection();
-
-Q_SIGNALS:
- void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
- void currentChanged(const QModelIndex &current, const QModelIndex &previous);
- void currentRowChanged(const QModelIndex &current, const QModelIndex &previous);
- void currentColumnChanged(const QModelIndex &current, const QModelIndex &previous);
-
-protected:
- QItemSelectionModel(QItemSelectionModelPrivate &dd, QAbstractItemModel *model);
- void emitSelectionChanged(const QItemSelection &newSelection, const QItemSelection &oldSelection);
-
-private:
- Q_DISABLE_COPY(QItemSelectionModel)
- Q_PRIVATE_SLOT(d_func(), void _q_columnsAboutToBeRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsAboutToBeRemoved(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_columnsAboutToBeInserted(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsAboutToBeInserted(const QModelIndex&, int, int))
- Q_PRIVATE_SLOT(d_func(), void _q_layoutAboutToBeChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_layoutChanged())
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QItemSelectionModel::SelectionFlags)
-
-// dummy implentation of qHash() necessary for instantiating QList<QItemSelectionRange>::toSet() with MSVC
-inline uint qHash(const QItemSelectionRange &) { return 0; }
-
-class Q_GUI_EXPORT QItemSelection : public QList<QItemSelectionRange>
-{
-public:
- QItemSelection() {}
- QItemSelection(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void select(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- bool contains(const QModelIndex &index) const;
- QModelIndexList indexes() const;
- void merge(const QItemSelection &other, QItemSelectionModel::SelectionFlags command);
- static void split(const QItemSelectionRange &range,
- const QItemSelectionRange &other,
- QItemSelection *result);
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_GUI_EXPORT QDebug operator<<(QDebug, const QItemSelectionRange &);
-#endif
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QITEMSELECTIONMODEL_H
diff --git a/src/gui/itemviews/qitemselectionmodel_p.h b/src/gui/itemviews/qitemselectionmodel_p.h
deleted file mode 100644
index 1574864477..0000000000
--- a/src/gui/itemviews/qitemselectionmodel_p.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** 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 QITEMSELECTIONMODEL_P_H
-#define QITEMSELECTIONMODEL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qobject_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_ITEMVIEWS
-class QItemSelectionModelPrivate: public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QItemSelectionModel)
-public:
- QItemSelectionModelPrivate()
- : model(0),
- currentCommand(QItemSelectionModel::NoUpdate),
- tableSelected(false), tableColCount(0), tableRowCount(0) {}
-
- QItemSelection expandSelection(const QItemSelection &selection,
- QItemSelectionModel::SelectionFlags command) const;
-
- void initModel(QAbstractItemModel *model);
-
- void _q_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- void _q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- void _q_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
- void _q_columnsAboutToBeInserted(const QModelIndex &parent, int start, int end);
- void _q_layoutAboutToBeChanged();
- void _q_layoutChanged();
-
- inline void remove(QList<QItemSelectionRange> &r)
- {
- QList<QItemSelectionRange>::const_iterator it = r.constBegin();
- for (; it != r.constEnd(); ++it)
- ranges.removeAll(*it);
- }
-
- inline void finalize()
- {
- ranges.merge(currentSelection, currentCommand);
- if (!currentSelection.isEmpty()) // ### perhaps this should be in QList
- currentSelection.clear();
- }
-
- QPointer<QAbstractItemModel> model;
- QItemSelection ranges;
- QItemSelection currentSelection;
- QPersistentModelIndex currentIndex;
- QItemSelectionModel::SelectionFlags currentCommand;
- QList<QPersistentModelIndex> savedPersistentIndexes;
- QList<QPersistentModelIndex> savedPersistentCurrentIndexes;
- // optimization when all indexes are selected
- bool tableSelected;
- QPersistentModelIndex tableParent;
- int tableColCount, tableRowCount;
-};
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-#endif // QITEMSELECTIONMODEL_P_H
diff --git a/src/gui/itemviews/qlistview.cpp b/src/gui/itemviews/qlistview.cpp
deleted file mode 100644
index 26478ffe97..0000000000
--- a/src/gui/itemviews/qlistview.cpp
+++ /dev/null
@@ -1,3213 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlistview.h"
-
-#ifndef QT_NO_LISTVIEW
-#include <qabstractitemdelegate.h>
-#include <qapplication.h>
-#include <qpainter.h>
-#include <qbitmap.h>
-#include <qdrag.h>
-#include <qvector.h>
-#include <qstyle.h>
-#include <qevent.h>
-#include <qscrollbar.h>
-#include <qrubberband.h>
-#include <private/qlistview_p.h>
-#include <qdebug.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qaccessible.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QListView
-
- \brief The QListView class provides a list or icon view onto a model.
-
- \ingroup model-view
- \ingroup advanced
-
-
- A QListView presents items stored in a model, either as a simple
- non-hierarchical list, or as a collection of icons. This class is used
- to provide lists and icon views that were previously provided by the
- \c QListBox and \c QIconView classes, but using the more flexible
- approach provided by Qt's model/view architecture.
-
- The QListView class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- This view does not display horizontal or vertical headers; to display
- a list of items with a horizontal header, use QTreeView instead.
-
- QListView implements the interfaces defined by the
- QAbstractItemView class to allow it to display data provided by
- models derived from the QAbstractItemModel class.
-
- Items in a list view can be displayed using one of two view modes:
- In \l ListMode, the items are displayed in the form of a simple list;
- in \l IconMode, the list view takes the form of an \e{icon view} in
- which the items are displayed with icons like files in a file manager.
- By default, the list view is in \l ListMode. To change the view mode,
- use the setViewMode() function, and to determine the current view mode,
- use viewMode().
-
- Items in these views are laid out in the direction specified by the
- flow() of the list view. The items may be fixed in place, or allowed
- to move, depending on the view's movement() state.
-
- If the items in the model cannot be completely laid out in the
- direction of flow, they can be wrapped at the boundary of the view
- widget; this depends on isWrapping(). This property is useful when the
- items are being represented by an icon view.
-
- The resizeMode() and layoutMode() govern how and when the items are
- laid out. Items are spaced according to their spacing(), and can exist
- within a notional grid of size specified by gridSize(). The items can
- be rendered as large or small icons depending on their iconSize().
-
- \table 100%
- \row \o \inlineimage windowsxp-listview.png Screenshot of a Windows XP style list view
- \o \inlineimage macintosh-listview.png Screenshot of a Macintosh style table view
- \o \inlineimage plastique-listview.png Screenshot of a Plastique style table view
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} list view.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} list view.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} list view.
- \endtable
-
- \section1 Improving Performance
-
- It is possible to give the view hints about the data it is handling in order
- to improve its performance when displaying large numbers of items. One approach
- that can be taken for views that are intended to display items with equal sizes
- is to set the \l uniformItemSizes property to true.
-
- \sa {View Classes}, QTreeView, QTableView, QListWidget
-*/
-
-/*!
- \enum QListView::ViewMode
-
- \value ListMode The items are laid out using TopToBottom flow, with Small size and Static movement
- \value IconMode The items are laid out using LeftToRight flow, with Large size and Free movement
-*/
-
-/*!
- \enum QListView::Movement
-
- \value Static The items cannot be moved by the user.
- \value Free The items can be moved freely by the user.
- \value Snap The items snap to the specified grid when moved; see
- setGridSize().
-*/
-
-/*!
- \enum QListView::Flow
-
- \value LeftToRight The items are laid out in the view from the left
- to the right.
- \value TopToBottom The items are laid out in the view from the top
- to the bottom.
-*/
-
-/*!
- \enum QListView::ResizeMode
-
- \value Fixed The items will only be laid out the first time the view is shown.
- \value Adjust The items will be laid out every time the view is resized.
-*/
-
-/*!
- \enum QListView::LayoutMode
-
- \value SinglePass The items are laid out all at once.
- \value Batched The items are laid out in batches of \l batchSize items.
- \sa batchSize
-*/
-
-/*!
- \since 4.2
- \fn void QListView::indexesMoved(const QModelIndexList &indexes)
-
- This signal is emitted when the specified \a indexes are moved in the view.
-*/
-
-/*!
- Creates a new QListView with the given \a parent to view a model.
- Use setModel() to set the model.
-*/
-QListView::QListView(QWidget *parent)
- : QAbstractItemView(*new QListViewPrivate, parent)
-{
- setViewMode(ListMode);
- setSelectionMode(SingleSelection);
- setAttribute(Qt::WA_MacShowFocusRect);
- Q_D(QListView); // We rely on a qobject_cast for PM_DefaultFrameWidth to change
- d->updateStyledFrameWidths(); // hence we have to force an update now that the object has been constructed
-}
-
-/*!
- \internal
-*/
-QListView::QListView(QListViewPrivate &dd, QWidget *parent)
- : QAbstractItemView(dd, parent)
-{
- setViewMode(ListMode);
- setSelectionMode(SingleSelection);
- setAttribute(Qt::WA_MacShowFocusRect);
- Q_D(QListView); // We rely on a qobject_cast for PM_DefaultFrameWidth to change
- d->updateStyledFrameWidths(); // hence we have to force an update now that the object has been constructed
-}
-
-/*!
- Destroys the view.
-*/
-QListView::~QListView()
-{
-}
-
-/*!
- \property QListView::movement
- \brief whether the items can be moved freely, are snapped to a
- grid, or cannot be moved at all.
-
- This property determines how the user can move the items in the
- view. \l Static means that the items can't be moved the user. \l
- Free means that the user can drag and drop the items to any
- position in the view. \l Snap means that the user can drag and
- drop the items, but only to the positions in a notional grid
- signified by the gridSize property.
-
- Setting this property when the view is visible will cause the
- items to be laid out again.
-
- By default, this property is set to \l Static.
-
- \sa gridSize, resizeMode, viewMode
-*/
-void QListView::setMovement(Movement movement)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::Movement);
- d->movement = movement;
-
-#ifndef QT_NO_DRAGANDDROP
- bool movable = (movement != Static);
- setDragEnabled(movable);
- d->viewport->setAcceptDrops(movable);
-#endif
- d->doDelayedItemsLayout();
-}
-
-QListView::Movement QListView::movement() const
-{
- Q_D(const QListView);
- return d->movement;
-}
-
-/*!
- \property QListView::flow
- \brief which direction the items layout should flow.
-
- If this property is \l LeftToRight, the items will be laid out left
- to right. If the \l isWrapping property is true, the layout will wrap
- when it reaches the right side of the visible area. If this
- property is \l TopToBottom, the items will be laid out from the top
- of the visible area, wrapping when it reaches the bottom.
-
- Setting this property when the view is visible will cause the
- items to be laid out again.
-
- By default, this property is set to \l TopToBottom.
-
- \sa viewMode
-*/
-void QListView::setFlow(Flow flow)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::Flow);
- d->flow = flow;
- d->doDelayedItemsLayout();
-}
-
-QListView::Flow QListView::flow() const
-{
- Q_D(const QListView);
- return d->flow;
-}
-
-/*!
- \property QListView::isWrapping
- \brief whether the items layout should wrap.
-
- This property holds whether the layout should wrap when there is
- no more space in the visible area. The point at which the layout wraps
- depends on the \l flow property.
-
- Setting this property when the view is visible will cause the
- items to be laid out again.
-
- By default, this property is false.
-
- \sa viewMode
-*/
-void QListView::setWrapping(bool enable)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::Wrap);
- d->setWrapping(enable);
- d->doDelayedItemsLayout();
-}
-
-bool QListView::isWrapping() const
-{
- Q_D(const QListView);
- return d->isWrapping();
-}
-
-/*!
- \property QListView::resizeMode
- \brief whether the items are laid out again when the view is resized.
-
- If this property is \l Adjust, the items will be laid out again
- when the view is resized. If the value is \l Fixed, the items will
- not be laid out when the view is resized.
-
- By default, this property is set to \l Fixed.
-
- \sa movement, gridSize, viewMode
-*/
-void QListView::setResizeMode(ResizeMode mode)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::ResizeMode);
- d->resizeMode = mode;
-}
-
-QListView::ResizeMode QListView::resizeMode() const
-{
- Q_D(const QListView);
- return d->resizeMode;
-}
-
-/*!
- \property QListView::layoutMode
- \brief determines whether the layout of items should happen immediately or be delayed.
-
- This property holds the layout mode for the items. When the mode
- is \l SinglePass (the default), the items are laid out all in one go.
- When the mode is \l Batched, the items are laid out in batches of \l batchSize
- items, while processing events. This makes it possible to
- instantly view and interact with the visible items while the rest
- are being laid out.
-
- \sa viewMode
-*/
-void QListView::setLayoutMode(LayoutMode mode)
-{
- Q_D(QListView);
- d->layoutMode = mode;
-}
-
-QListView::LayoutMode QListView::layoutMode() const
-{
- Q_D(const QListView);
- return d->layoutMode;
-}
-
-/*!
- \property QListView::spacing
- \brief the space around the items in the layout
-
- This property is the size of the empty space that is padded around
- an item in the layout.
-
- Setting this property when the view is visible will cause the
- items to be laid out again.
-
- By default, this property contains a value of 0.
-
- \sa viewMode
-*/
-// ### Qt5: Use same semantic as layouts (spacing is the size of space
-// *between* items)
-void QListView::setSpacing(int space)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::Spacing);
- d->setSpacing(space);
- d->doDelayedItemsLayout();
-}
-
-int QListView::spacing() const
-{
- Q_D(const QListView);
- return d->spacing();
-}
-
-/*!
- \property QListView::batchSize
- \brief the number of items laid out in each batch if \l layoutMode is
- set to \l Batched
-
- The default value is 100.
-
- \since 4.2
-*/
-
-void QListView::setBatchSize(int batchSize)
-{
- Q_D(QListView);
- if (batchSize <= 0) {
- qWarning("Invalid batchSize (%d)", batchSize);
- return;
- }
- d->batchSize = batchSize;
-}
-
-int QListView::batchSize() const
-{
- Q_D(const QListView);
- return d->batchSize;
-}
-
-/*!
- \property QListView::gridSize
- \brief the size of the layout grid
-
- This property is the size of the grid in which the items are laid
- out. The default is an empty size which means that there is no
- grid and the layout is not done in a grid. Setting this property
- to a non-empty size switches on the grid layout. (When a grid
- layout is in force the \l spacing property is ignored.)
-
- Setting this property when the view is visible will cause the
- items to be laid out again.
-
- \sa viewMode
-*/
-void QListView::setGridSize(const QSize &size)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::GridSize);
- d->setGridSize(size);
- d->doDelayedItemsLayout();
-}
-
-QSize QListView::gridSize() const
-{
- Q_D(const QListView);
- return d->gridSize();
-}
-
-/*!
- \property QListView::viewMode
- \brief the view mode of the QListView.
-
- This property will change the other unset properties to conform
- with the set view mode. QListView-specific properties that have already been set
- will not be changed, unless clearPropertyFlags() has been called.
-
- Setting the view mode will enable or disable drag and drop based on the
- selected movement. For ListMode, the default movement is \l Static
- (drag and drop disabled); for IconMode, the default movement is
- \l Free (drag and drop enabled).
-
- \sa isWrapping, spacing, gridSize, flow, movement, resizeMode
-*/
-void QListView::setViewMode(ViewMode mode)
-{
- Q_D(QListView);
- if (d->commonListView && d->viewMode == mode)
- return;
- d->viewMode = mode;
-
- delete d->commonListView;
- if (mode == ListMode) {
- d->commonListView = new QListModeViewBase(this, d);
- if (!(d->modeProperties & QListViewPrivate::Wrap))
- d->setWrapping(false);
- if (!(d->modeProperties & QListViewPrivate::Spacing))
- d->setSpacing(0);
- if (!(d->modeProperties & QListViewPrivate::GridSize))
- d->setGridSize(QSize());
- if (!(d->modeProperties & QListViewPrivate::Flow))
- d->flow = TopToBottom;
- if (!(d->modeProperties & QListViewPrivate::Movement))
- d->movement = Static;
- if (!(d->modeProperties & QListViewPrivate::ResizeMode))
- d->resizeMode = Fixed;
- if (!(d->modeProperties & QListViewPrivate::SelectionRectVisible))
- d->showElasticBand = false;
- } else {
- d->commonListView = new QIconModeViewBase(this, d);
- if (!(d->modeProperties & QListViewPrivate::Wrap))
- d->setWrapping(true);
- if (!(d->modeProperties & QListViewPrivate::Spacing))
- d->setSpacing(0);
- if (!(d->modeProperties & QListViewPrivate::GridSize))
- d->setGridSize(QSize());
- if (!(d->modeProperties & QListViewPrivate::Flow))
- d->flow = LeftToRight;
- if (!(d->modeProperties & QListViewPrivate::Movement))
- d->movement = Free;
- if (!(d->modeProperties & QListViewPrivate::ResizeMode))
- d->resizeMode = Fixed;
- if (!(d->modeProperties & QListViewPrivate::SelectionRectVisible))
- d->showElasticBand = true;
- }
-
-#ifndef QT_NO_DRAGANDDROP
- bool movable = (d->movement != Static);
- setDragEnabled(movable);
- setAcceptDrops(movable);
-#endif
- d->clear();
- d->doDelayedItemsLayout();
-}
-
-QListView::ViewMode QListView::viewMode() const
-{
- Q_D(const QListView);
- return d->viewMode;
-}
-
-/*!
- Clears the QListView-specific property flags. See \l{viewMode}.
-
- Properties inherited from QAbstractItemView are not covered by the
- property flags. Specifically, \l{QAbstractItemView::dragEnabled}
- {dragEnabled} and \l{QAbstractItemView::acceptDrops}
- {acceptsDrops} are computed by QListView when calling
- setMovement() or setViewMode().
-*/
-void QListView::clearPropertyFlags()
-{
- Q_D(QListView);
- d->modeProperties = 0;
-}
-
-/*!
- Returns true if the \a row is hidden; otherwise returns false.
-*/
-bool QListView::isRowHidden(int row) const
-{
- Q_D(const QListView);
- return d->isHidden(row);
-}
-
-/*!
- If \a hide is true, the given \a row will be hidden; otherwise
- the \a row will be shown.
-*/
-void QListView::setRowHidden(int row, bool hide)
-{
- Q_D(QListView);
- const bool hidden = d->isHidden(row);
- if (hide && !hidden)
- d->commonListView->appendHiddenRow(row);
- else if (!hide && hidden)
- d->commonListView->removeHiddenRow(row);
- d->doDelayedItemsLayout();
- d->viewport->update();
-}
-
-/*!
- \reimp
-*/
-QRect QListView::visualRect(const QModelIndex &index) const
-{
- Q_D(const QListView);
- return d->mapToViewport(rectForIndex(index));
-}
-
-/*!
- \reimp
-*/
-void QListView::scrollTo(const QModelIndex &index, ScrollHint hint)
-{
- Q_D(QListView);
-
- if (index.parent() != d->root || index.column() != d->column)
- return;
-
- const QRect rect = visualRect(index);
- if (hint == EnsureVisible && d->viewport->rect().contains(rect)) {
- d->viewport->update(rect);
- return;
- }
-
- if (d->flow == QListView::TopToBottom || d->isWrapping()) // vertical
- verticalScrollBar()->setValue(d->verticalScrollToValue(index, rect, hint));
-
- if (d->flow == QListView::LeftToRight || d->isWrapping()) // horizontal
- horizontalScrollBar()->setValue(d->horizontalScrollToValue(index, rect, hint));
-}
-
-int QListViewPrivate::horizontalScrollToValue(const QModelIndex &index, const QRect &rect,
- QListView::ScrollHint hint) const
-{
- Q_Q(const QListView);
- const QRect area = viewport->rect();
- const bool leftOf = q->isRightToLeft()
- ? (rect.left() < area.left()) && (rect.right() < area.right())
- : rect.left() < area.left();
- const bool rightOf = q->isRightToLeft()
- ? rect.right() > area.right()
- : (rect.right() > area.right()) && (rect.left() > area.left());
- return commonListView->horizontalScrollToValue(q->visualIndex(index), hint, leftOf, rightOf, area, rect);
-}
-
-int QListViewPrivate::verticalScrollToValue(const QModelIndex &index, const QRect &rect,
- QListView::ScrollHint hint) const
-{
- Q_Q(const QListView);
- const QRect area = viewport->rect();
- const bool above = (hint == QListView::EnsureVisible && rect.top() < area.top());
- const bool below = (hint == QListView::EnsureVisible && rect.bottom() > area.bottom());
- return commonListView->verticalScrollToValue(q->visualIndex(index), hint, above, below, area, rect);
-}
-
-void QListViewPrivate::selectAll(QItemSelectionModel::SelectionFlags command)
-{
- if (!selectionModel)
- return;
-
- QItemSelection selection;
- QModelIndex topLeft;
- int row = 0;
- const int colCount = model->columnCount(root);
- for(; row < model->rowCount(root); ++row) {
- if (isHidden(row)) {
- //it might be the end of a selection range
- if (topLeft.isValid()) {
- QModelIndex bottomRight = model->index(row - 1, colCount - 1, root);
- selection.append(QItemSelectionRange(topLeft, bottomRight));
- topLeft = QModelIndex();
- }
- continue;
- }
-
- if (!topLeft.isValid()) //start of a new selection range
- topLeft = model->index(row, 0, root);
- }
-
- if (topLeft.isValid()) {
- //last selected range
- QModelIndex bottomRight = model->index(row - 1, colCount - 1, root);
- selection.append(QItemSelectionRange(topLeft, bottomRight));
- }
-
- if (!selection.isEmpty())
- selectionModel->select(selection, command);
-}
-
-/*!
- \reimp
-
- We have a QListView way of knowing what elements are on the viewport
- through the intersectingSet function
-*/
-QItemViewPaintPairs QListViewPrivate::draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const
-{
- Q_ASSERT(r);
- Q_Q(const QListView);
- QRect &rect = *r;
- const QRect viewportRect = viewport->rect();
- QItemViewPaintPairs ret;
- const QSet<QModelIndex> visibleIndexes = intersectingSet(viewportRect).toList().toSet();
- for (int i = 0; i < indexes.count(); ++i) {
- const QModelIndex &index = indexes.at(i);
- if (visibleIndexes.contains(index)) {
- const QRect current = q->visualRect(index);
- ret += qMakePair(current, index);
- rect |= current;
- }
- }
- rect &= viewportRect;
- return ret;
-}
-
-/*!
- \internal
-*/
-void QListView::reset()
-{
- Q_D(QListView);
- d->clear();
- d->hiddenRows.clear();
- QAbstractItemView::reset();
-}
-
-/*!
- \internal
-*/
-void QListView::setRootIndex(const QModelIndex &index)
-{
- Q_D(QListView);
- d->column = qBound(0, d->column, d->model->columnCount(index) - 1);
- QAbstractItemView::setRootIndex(index);
- // sometimes we get an update before reset() is called
- d->clear();
- d->hiddenRows.clear();
-}
-
-/*!
- \internal
-
- Scroll the view contents by \a dx and \a dy.
-*/
-
-void QListView::scrollContentsBy(int dx, int dy)
-{
- Q_D(QListView);
- d->delayedAutoScroll.stop(); // auto scroll was canceled by the user scrolling
- d->commonListView->scrollContentsBy(dx, dy, d->state == QListView::DragSelectingState);
-}
-
-/*!
- \internal
-
- Resize the internal contents to \a width and \a height and set the
- scroll bar ranges accordingly.
-*/
-void QListView::resizeContents(int width, int height)
-{
- Q_D(QListView);
- d->setContentsSize(width, height);
-}
-
-/*!
- \internal
-*/
-QSize QListView::contentsSize() const
-{
- Q_D(const QListView);
- return d->contentsSize();
-}
-
-/*!
- \reimp
-*/
-void QListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- d_func()->commonListView->dataChanged(topLeft, bottomRight);
- QAbstractItemView::dataChanged(topLeft, bottomRight);
-}
-
-/*!
- \reimp
-*/
-void QListView::rowsInserted(const QModelIndex &parent, int start, int end)
-{
- Q_D(QListView);
- // ### be smarter about inserted items
- d->clear();
- d->doDelayedItemsLayout();
- QAbstractItemView::rowsInserted(parent, start, end);
-}
-
-/*!
- \reimp
-*/
-void QListView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
-{
- Q_D(QListView);
- // if the parent is above d->root in the tree, nothing will happen
- QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
- if (parent == d->root) {
- QSet<QPersistentModelIndex>::iterator it = d->hiddenRows.begin();
- while (it != d->hiddenRows.end()) {
- int hiddenRow = it->row();
- if (hiddenRow >= start && hiddenRow <= end) {
- it = d->hiddenRows.erase(it);
- } else {
- ++it;
- }
- }
- }
- d->clear();
- d->doDelayedItemsLayout();
-}
-
-/*!
- \reimp
-*/
-void QListView::mouseMoveEvent(QMouseEvent *e)
-{
- if (!isVisible())
- return;
- Q_D(QListView);
- QAbstractItemView::mouseMoveEvent(e);
- if (state() == DragSelectingState
- && d->showElasticBand
- && d->selectionMode != SingleSelection
- && d->selectionMode != NoSelection) {
- QRect rect(d->pressedPosition, e->pos() + QPoint(horizontalOffset(), verticalOffset()));
- rect = rect.normalized();
- d->viewport->update(d->mapToViewport(rect.united(d->elasticBand)));
- d->elasticBand = rect;
- }
-}
-
-/*!
- \reimp
-*/
-void QListView::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QListView);
- QAbstractItemView::mouseReleaseEvent(e);
- // #### move this implementation into a dynamic class
- if (d->showElasticBand && d->elasticBand.isValid()) {
- d->viewport->update(d->mapToViewport(d->elasticBand));
- d->elasticBand = QRect();
- }
-}
-
-/*!
- \reimp
-*/
-void QListView::timerEvent(QTimerEvent *e)
-{
- Q_D(QListView);
- if (e->timerId() == d->batchLayoutTimer.timerId()) {
- if (d->doItemsLayout(d->batchSize)) { // layout is done
- d->batchLayoutTimer.stop();
- updateGeometries();
- d->viewport->update();
- }
- }
- QAbstractItemView::timerEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QListView::resizeEvent(QResizeEvent *e)
-{
- Q_D(QListView);
- if (d->delayedPendingLayout)
- return;
-
- QSize delta = e->size() - e->oldSize();
-
- if (delta.isNull())
- return;
-
- bool listWrap = (d->viewMode == ListMode) && d->wrapItemText;
- bool flowDimensionChanged = (d->flow == LeftToRight && delta.width() != 0)
- || (d->flow == TopToBottom && delta.height() != 0);
-
- // We post a delayed relayout in the following cases :
- // - we're wrapping
- // - the state is NoState, we're adjusting and the size has changed in the flowing direction
- if (listWrap
- || (state() == NoState && d->resizeMode == Adjust && flowDimensionChanged)) {
- d->doDelayedItemsLayout(100); // wait 1/10 sec before starting the layout
- } else {
- QAbstractItemView::resizeEvent(e);
- }
-}
-
-#ifndef QT_NO_DRAGANDDROP
-
-/*!
- \reimp
-*/
-void QListView::dragMoveEvent(QDragMoveEvent *e)
-{
- Q_D(QListView);
- if (!d->commonListView->filterDragMoveEvent(e)) {
- if (viewMode() == QListView::ListMode && flow() == QListView::LeftToRight)
- static_cast<QListModeViewBase *>(d->commonListView)->dragMoveEvent(e);
- else
- QAbstractItemView::dragMoveEvent(e);
- }
-}
-
-
-/*!
- \reimp
-*/
-void QListView::dragLeaveEvent(QDragLeaveEvent *e)
-{
- if (!d_func()->commonListView->filterDragLeaveEvent(e))
- QAbstractItemView::dragLeaveEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QListView::dropEvent(QDropEvent *e)
-{
- if (!d_func()->commonListView->filterDropEvent(e))
- QAbstractItemView::dropEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QListView::startDrag(Qt::DropActions supportedActions)
-{
- if (!d_func()->commonListView->filterStartDrag(supportedActions))
- QAbstractItemView::startDrag(supportedActions);
-}
-
-/*!
- \internal
-
- Called whenever items from the view is dropped on the viewport.
- The \a event provides additional information.
-*/
-void QListView::internalDrop(QDropEvent *event)
-{
- // ### Qt5: remove that function
- Q_UNUSED(event);
-}
-
-/*!
- \internal
-
- Called whenever the user starts dragging items and the items are movable,
- enabling internal dragging and dropping of items.
-*/
-void QListView::internalDrag(Qt::DropActions supportedActions)
-{
- // ### Qt5: remove that function
- Q_UNUSED(supportedActions);
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- \reimp
-*/
-QStyleOptionViewItem QListView::viewOptions() const
-{
- Q_D(const QListView);
- QStyleOptionViewItem option = QAbstractItemView::viewOptions();
- if (!d->iconSize.isValid()) { // otherwise it was already set in abstractitemview
- int pm = (d->viewMode == ListMode
- ? style()->pixelMetric(QStyle::PM_ListViewIconSize, 0, this)
- : style()->pixelMetric(QStyle::PM_IconViewIconSize, 0, this));
- option.decorationSize = QSize(pm, pm);
- }
- if (d->viewMode == IconMode) {
- option.showDecorationSelected = false;
- option.decorationPosition = QStyleOptionViewItem::Top;
- option.displayAlignment = Qt::AlignCenter;
- } else {
- option.decorationPosition = QStyleOptionViewItem::Left;
- }
- return option;
-}
-
-
-/*!
- \reimp
-*/
-void QListView::paintEvent(QPaintEvent *e)
-{
- Q_D(QListView);
- if (!d->itemDelegate)
- return;
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- QPainter painter(d->viewport);
-
- const QVector<QModelIndex> toBeRendered = d->intersectingSet(e->rect().translated(horizontalOffset(), verticalOffset()), false);
-
- const QModelIndex current = currentIndex();
- const QModelIndex hover = d->hover;
- const QAbstractItemModel *itemModel = d->model;
- const QItemSelectionModel *selections = d->selectionModel;
- const bool focus = (hasFocus() || d->viewport->hasFocus()) && current.isValid();
- const bool alternate = d->alternatingColors;
- const QStyle::State state = option.state;
- const QAbstractItemView::State viewState = this->state();
- const bool enabled = (state & QStyle::State_Enabled) != 0;
-
- bool alternateBase = false;
- int previousRow = -2; // trigger the alternateBase adjustment on first pass
-
- int maxSize = (flow() == TopToBottom)
- ? qMax(viewport()->size().width(), d->contentsSize().width()) - 2 * d->spacing()
- : qMax(viewport()->size().height(), d->contentsSize().height()) - 2 * d->spacing();
-
- QVector<QModelIndex>::const_iterator end = toBeRendered.constEnd();
- for (QVector<QModelIndex>::const_iterator it = toBeRendered.constBegin(); it != end; ++it) {
- Q_ASSERT((*it).isValid());
- option.rect = visualRect(*it);
-
- if (flow() == TopToBottom)
- option.rect.setWidth(qMin(maxSize, option.rect.width()));
- else
- option.rect.setHeight(qMin(maxSize, option.rect.height()));
-
- option.state = state;
- if (selections && selections->isSelected(*it))
- option.state |= QStyle::State_Selected;
- if (enabled) {
- QPalette::ColorGroup cg;
- if ((itemModel->flags(*it) & Qt::ItemIsEnabled) == 0) {
- option.state &= ~QStyle::State_Enabled;
- cg = QPalette::Disabled;
- } else {
- cg = QPalette::Normal;
- }
- option.palette.setCurrentColorGroup(cg);
- }
- if (focus && current == *it) {
- option.state |= QStyle::State_HasFocus;
- if (viewState == EditingState)
- option.state |= QStyle::State_Editing;
- }
- if (*it == hover)
- option.state |= QStyle::State_MouseOver;
- else
- option.state &= ~QStyle::State_MouseOver;
-
- if (alternate) {
- int row = (*it).row();
- if (row != previousRow + 1) {
- // adjust alternateBase according to rows in the "gap"
- if (!d->hiddenRows.isEmpty()) {
- for (int r = qMax(previousRow + 1, 0); r < row; ++r) {
- if (!d->isHidden(r))
- alternateBase = !alternateBase;
- }
- } else {
- alternateBase = (row & 1) != 0;
- }
- }
- if (alternateBase) {
- option.features |= QStyleOptionViewItemV2::Alternate;
- } else {
- option.features &= ~QStyleOptionViewItemV2::Alternate;
- }
-
- // draw background of the item (only alternate row). rest of the background
- // is provided by the delegate
- QStyle::State oldState = option.state;
- option.state &= ~QStyle::State_Selected;
- style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &option, &painter, this);
- option.state = oldState;
-
- alternateBase = !alternateBase;
- previousRow = row;
- }
-
- d->delegateForIndex(*it)->paint(&painter, option, *it);
- }
-
-#ifndef QT_NO_DRAGANDDROP
- d->commonListView->paintDragDrop(&painter);
-#endif
-
-#ifndef QT_NO_RUBBERBAND
- // #### move this implementation into a dynamic class
- if (d->showElasticBand && d->elasticBand.isValid()) {
- QStyleOptionRubberBand opt;
- opt.initFrom(this);
- opt.shape = QRubberBand::Rectangle;
- opt.opaque = false;
- opt.rect = d->mapToViewport(d->elasticBand, false).intersected(
- d->viewport->rect().adjusted(-16, -16, 16, 16));
- painter.save();
- style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
- painter.restore();
- }
-#endif
-}
-
-/*!
- \reimp
-*/
-QModelIndex QListView::indexAt(const QPoint &p) const
-{
- Q_D(const QListView);
- QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1);
- const QVector<QModelIndex> intersectVector = d->intersectingSet(rect);
- QModelIndex index = intersectVector.count() > 0
- ? intersectVector.last() : QModelIndex();
- if (index.isValid() && visualRect(index).contains(p))
- return index;
- return QModelIndex();
-}
-
-/*!
- \reimp
-*/
-int QListView::horizontalOffset() const
-{
- return d_func()->commonListView->horizontalOffset();
-}
-
-/*!
- \reimp
-*/
-int QListView::verticalOffset() const
-{
- return d_func()->commonListView->verticalOffset();
-}
-
-/*!
- \reimp
-*/
-QModelIndex QListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
-{
- Q_D(QListView);
- Q_UNUSED(modifiers);
-
- QModelIndex current = currentIndex();
- if (!current.isValid()) {
- int rowCount = d->model->rowCount(d->root);
- if (!rowCount)
- return QModelIndex();
- int row = 0;
- while (row < rowCount && d->isHiddenOrDisabled(row))
- ++row;
- if (row >= rowCount)
- return QModelIndex();
- return d->model->index(row, d->column, d->root);
- }
-
- const QRect initialRect = rectForIndex(current);
- QRect rect = initialRect;
- if (rect.isEmpty()) {
- return d->model->index(0, d->column, d->root);
- }
- if (d->gridSize().isValid()) rect.setSize(d->gridSize());
-
- QSize contents = d->contentsSize();
- QVector<QModelIndex> intersectVector;
-
- switch (cursorAction) {
- case MoveLeft:
- while (intersectVector.isEmpty()) {
- rect.translate(-rect.width(), 0);
- if (rect.right() <= 0)
- return current;
- if (rect.left() < 0)
- rect.setLeft(0);
- intersectVector = d->intersectingSet(rect);
- d->removeCurrentAndDisabled(&intersectVector, current);
- }
- return d->closestIndex(initialRect, intersectVector);
- case MoveRight:
- while (intersectVector.isEmpty()) {
- rect.translate(rect.width(), 0);
- if (rect.left() >= contents.width())
- return current;
- if (rect.right() > contents.width())
- rect.setRight(contents.width());
- intersectVector = d->intersectingSet(rect);
- d->removeCurrentAndDisabled(&intersectVector, current);
- }
- return d->closestIndex(initialRect, intersectVector);
- case MovePageUp:
- // move current by (visibileRowCount - 1) items.
- // rect.translate(0, -rect.height()); will happen in the switch fallthrough for MoveUp.
- rect.moveTop(rect.top() - d->viewport->height() + 2 * rect.height());
- if (rect.top() < rect.height())
- rect.moveTop(rect.height());
- case MovePrevious:
- case MoveUp:
- while (intersectVector.isEmpty()) {
- rect.translate(0, -rect.height());
- if (rect.bottom() <= 0) {
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- int row = d->batchStartRow() - 1;
- while (row >= 0 && d->isHiddenOrDisabled(row))
- --row;
- if (row >= 0)
- return d->model->index(row, d->column, d->root);
- }
-#endif
- return current;
- }
- if (rect.top() < 0)
- rect.setTop(0);
- intersectVector = d->intersectingSet(rect);
- d->removeCurrentAndDisabled(&intersectVector, current);
- }
- return d->closestIndex(initialRect, intersectVector);
- case MovePageDown:
- // move current by (visibileRowCount - 1) items.
- // rect.translate(0, rect.height()); will happen in the switch fallthrough for MoveDown.
- rect.moveTop(rect.top() + d->viewport->height() - 2 * rect.height());
- if (rect.bottom() > contents.height() - rect.height())
- rect.moveBottom(contents.height() - rect.height());
- case MoveNext:
- case MoveDown:
- while (intersectVector.isEmpty()) {
- rect.translate(0, rect.height());
- if (rect.top() >= contents.height()) {
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- int rowCount = d->model->rowCount(d->root);
- int row = 0;
- while (row < rowCount && d->isHiddenOrDisabled(row))
- ++row;
- if (row < rowCount)
- return d->model->index(row, d->column, d->root);
- }
-#endif
- return current;
- }
- if (rect.bottom() > contents.height())
- rect.setBottom(contents.height());
- intersectVector = d->intersectingSet(rect);
- d->removeCurrentAndDisabled(&intersectVector, current);
- }
- return d->closestIndex(initialRect, intersectVector);
- case MoveHome:
- return d->model->index(0, d->column, d->root);
- case MoveEnd:
- return d->model->index(d->batchStartRow() - 1, d->column, d->root);}
-
- return current;
-}
-
-/*!
- Returns the rectangle of the item at position \a index in the
- model. The rectangle is in contents coordinates.
-
- \sa visualRect()
-*/
-QRect QListView::rectForIndex(const QModelIndex &index) const
-{
- return d_func()->rectForIndex(index);
-}
-
-/*!
- \since 4.1
-
- Sets the contents position of the item at \a index in the model to the given
- \a position.
- If the list view's movement mode is Static or its view mode is ListView,
- this function will have no effect.
-*/
-void QListView::setPositionForIndex(const QPoint &position, const QModelIndex &index)
-{
- Q_D(QListView);
- if (d->movement == Static
- || !d->isIndexValid(index)
- || index.parent() != d->root
- || index.column() != d->column)
- return;
-
- d->executePostedLayout();
- d->commonListView->setPositionForIndex(position, index);
-}
-
-/*!
- \reimp
-*/
-void QListView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QListView);
- if (!d->selectionModel)
- return;
-
- // if we are wrapping, we can only selecte inside the contents rectangle
- int w = qMax(d->contentsSize().width(), d->viewport->width());
- int h = qMax(d->contentsSize().height(), d->viewport->height());
- if (d->wrap && !QRect(0, 0, w, h).intersects(rect))
- return;
-
- QItemSelection selection;
-
- if (rect.width() == 1 && rect.height() == 1) {
- const QVector<QModelIndex> intersectVector = d->intersectingSet(rect.translated(horizontalOffset(), verticalOffset()));
- QModelIndex tl;
- if (!intersectVector.isEmpty())
- tl = intersectVector.last(); // special case for mouse press; only select the top item
- if (tl.isValid() && d->isIndexEnabled(tl))
- selection.select(tl, tl);
- } else {
- if (state() == DragSelectingState) { // visual selection mode (rubberband selection)
- selection = d->selection(rect.translated(horizontalOffset(), verticalOffset()));
- } else { // logical selection mode (key and mouse click selection)
- QModelIndex tl, br;
- // get the first item
- const QRect topLeft(rect.left() + horizontalOffset(), rect.top() + verticalOffset(), 1, 1);
- QVector<QModelIndex> intersectVector = d->intersectingSet(topLeft);
- if (!intersectVector.isEmpty())
- tl = intersectVector.last();
- // get the last item
- const QRect bottomRight(rect.right() + horizontalOffset(), rect.bottom() + verticalOffset(), 1, 1);
- intersectVector = d->intersectingSet(bottomRight);
- if (!intersectVector.isEmpty())
- br = intersectVector.last();
-
- // get the ranges
- if (tl.isValid() && br.isValid()
- && d->isIndexEnabled(tl)
- && d->isIndexEnabled(br)) {
- QRect first = rectForIndex(tl);
- QRect last = rectForIndex(br);
- QRect middle;
- if (d->flow == LeftToRight) {
- QRect &top = first;
- QRect &bottom = last;
- // if bottom is above top, swap them
- if (top.center().y() > bottom.center().y()) {
- QRect tmp = top;
- top = bottom;
- bottom = tmp;
- }
- // if the rect are on differnet lines, expand
- if (top.top() != bottom.top()) {
- // top rectangle
- if (isRightToLeft())
- top.setLeft(0);
- else
- top.setRight(contentsSize().width());
- // bottom rectangle
- if (isRightToLeft())
- bottom.setRight(contentsSize().width());
- else
- bottom.setLeft(0);
- } else if (top.left() > bottom.right()) {
- if (isRightToLeft())
- bottom.setLeft(top.right());
- else
- bottom.setRight(top.left());
- } else {
- if (isRightToLeft())
- top.setLeft(bottom.right());
- else
- top.setRight(bottom.left());
- }
- // middle rectangle
- if (top.bottom() < bottom.top()) {
- if (gridSize().isValid() && !gridSize().isNull())
- middle.setTop(top.top() + gridSize().height());
- else
- middle.setTop(top.bottom() + 1);
- middle.setLeft(qMin(top.left(), bottom.left()));
- middle.setBottom(bottom.top() - 1);
- middle.setRight(qMax(top.right(), bottom.right()));
- }
- } else { // TopToBottom
- QRect &left = first;
- QRect &right = last;
- if (left.center().x() > right.center().x())
- qSwap(left, right);
-
- int ch = contentsSize().height();
- if (left.left() != right.left()) {
- // left rectangle
- if (isRightToLeft())
- left.setTop(0);
- else
- left.setBottom(ch);
-
- // top rectangle
- if (isRightToLeft())
- right.setBottom(ch);
- else
- right.setTop(0);
- // only set middle if the
- middle.setTop(0);
- middle.setBottom(ch);
- if (gridSize().isValid() && !gridSize().isNull())
- middle.setLeft(left.left() + gridSize().width());
- else
- middle.setLeft(left.right() + 1);
- middle.setRight(right.left() - 1);
- } else if (left.bottom() < right.top()) {
- left.setBottom(right.top() - 1);
- } else {
- right.setBottom(left.top() - 1);
- }
- }
-
- // do the selections
- QItemSelection topSelection = d->selection(first);
- QItemSelection middleSelection = d->selection(middle);
- QItemSelection bottomSelection = d->selection(last);
- // merge
- selection.merge(topSelection, QItemSelectionModel::Select);
- selection.merge(middleSelection, QItemSelectionModel::Select);
- selection.merge(bottomSelection, QItemSelectionModel::Select);
- }
- }
- }
-
- d->selectionModel->select(selection, command);
-}
-
-/*!
- \reimp
-
- Since 4.7, the returned region only contains rectangles intersecting
- (or included in) the viewport.
-*/
-QRegion QListView::visualRegionForSelection(const QItemSelection &selection) const
-{
- Q_D(const QListView);
- // ### NOTE: this is a potential bottleneck in non-static mode
- int c = d->column;
- QRegion selectionRegion;
- const QRect &viewportRect = d->viewport->rect();
- for (int i = 0; i < selection.count(); ++i) {
- if (!selection.at(i).isValid())
- continue;
- QModelIndex parent = selection.at(i).topLeft().parent();
- //we only display the children of the root in a listview
- //we're not interested in the other model indexes
- if (parent != d->root)
- continue;
- int t = selection.at(i).topLeft().row();
- int b = selection.at(i).bottomRight().row();
- if (d->viewMode == IconMode || d->isWrapping()) { // in non-static mode, we have to go through all selected items
- for (int r = t; r <= b; ++r) {
- const QRect &rect = visualRect(d->model->index(r, c, parent));
- if (viewportRect.intersects(rect))
- selectionRegion += rect;
- }
- } else { // in static mode, we can optimize a bit
- while (t <= b && d->isHidden(t)) ++t;
- while (b >= t && d->isHidden(b)) --b;
- const QModelIndex top = d->model->index(t, c, parent);
- const QModelIndex bottom = d->model->index(b, c, parent);
- QRect rect(visualRect(top).topLeft(),
- visualRect(bottom).bottomRight());
- if (viewportRect.intersects(rect))
- selectionRegion += rect;
- }
- }
-
- return selectionRegion;
-}
-
-/*!
- \reimp
-*/
-QModelIndexList QListView::selectedIndexes() const
-{
- Q_D(const QListView);
- if (!d->selectionModel)
- return QModelIndexList();
-
- QModelIndexList viewSelected = d->selectionModel->selectedIndexes();
- for (int i = 0; i < viewSelected.count(); ++i) {
- const QModelIndex &index = viewSelected.at(i);
- if (!isIndexHidden(index) && index.parent() == d->root && index.column() == d->column)
- ++i;
- else
- viewSelected.removeAt(i);
- }
- return viewSelected;
-}
-
-/*!
- \internal
-
- Layout the items according to the flow and wrapping properties.
-*/
-void QListView::doItemsLayout()
-{
- Q_D(QListView);
- // showing the scroll bars will trigger a resize event,
- // so we set the state to expanding to avoid
- // triggering another layout
- QAbstractItemView::State oldState = state();
- setState(ExpandingState);
- if (d->model->columnCount(d->root) > 0) { // no columns means no contents
- d->resetBatchStartRow();
- if (layoutMode() == SinglePass)
- d->doItemsLayout(d->model->rowCount(d->root)); // layout everything
- else if (!d->batchLayoutTimer.isActive()) {
- if (!d->doItemsLayout(d->batchSize)) // layout is done
- d->batchLayoutTimer.start(0, this); // do a new batch as fast as possible
- }
- }
- QAbstractItemView::doItemsLayout();
- setState(oldState); // restoring the oldState
-}
-
-/*!
- \reimp
-*/
-void QListView::updateGeometries()
-{
- Q_D(QListView);
- if (d->model->rowCount(d->root) <= 0 || d->model->columnCount(d->root) <= 0) {
- horizontalScrollBar()->setRange(0, 0);
- verticalScrollBar()->setRange(0, 0);
- } else {
- QModelIndex index = d->model->index(0, d->column, d->root);
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- QSize step = d->itemSize(option, index);
- d->commonListView->updateHorizontalScrollBar(step);
- d->commonListView->updateVerticalScrollBar(step);
- }
-
- QAbstractItemView::updateGeometries();
-
- // if the scroll bars are turned off, we resize the contents to the viewport
- if (d->movement == Static && !d->isWrapping()) {
- const QSize maxSize = maximumViewportSize();
- if (d->flow == TopToBottom) {
- if (horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) {
- d->setContentsSize(maxSize.width(), contentsSize().height());
- horizontalScrollBar()->setRange(0, 0); // we see all the contents anyway
- }
- } else { // LeftToRight
- if (verticalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) {
- d->setContentsSize(contentsSize().width(), maxSize.height());
- verticalScrollBar()->setRange(0, 0); // we see all the contents anyway
- }
- }
- }
-
-}
-
-/*!
- \reimp
-*/
-bool QListView::isIndexHidden(const QModelIndex &index) const
-{
- Q_D(const QListView);
- return (d->isHidden(index.row())
- && (index.parent() == d->root)
- && index.column() == d->column);
-}
-
-/*!
- \property QListView::modelColumn
- \brief the column in the model that is visible
-
- By default, this property contains 0, indicating that the first
- column in the model will be shown.
-*/
-void QListView::setModelColumn(int column)
-{
- Q_D(QListView);
- if (column < 0 || column >= d->model->columnCount(d->root))
- return;
- d->column = column;
- d->doDelayedItemsLayout();
-}
-
-int QListView::modelColumn() const
-{
- Q_D(const QListView);
- return d->column;
-}
-
-/*!
- \property QListView::uniformItemSizes
- \brief whether all items in the listview have the same size
- \since 4.1
-
- This property should only be set to true if it is guaranteed that all items
- in the view have the same size. This enables the view to do some
- optimizations for performance purposes.
-
- By default, this property is false.
-*/
-void QListView::setUniformItemSizes(bool enable)
-{
- Q_D(QListView);
- d->uniformItemSizes = enable;
-}
-
-bool QListView::uniformItemSizes() const
-{
- Q_D(const QListView);
- return d->uniformItemSizes;
-}
-
-/*!
- \property QListView::wordWrap
- \brief the item text word-wrapping policy
- \since 4.2
-
- If this property is true then the item text is wrapped where
- necessary at word-breaks; otherwise it is not wrapped at all.
- This property is false by default.
-
- Please note that even if wrapping is enabled, the cell will not be
- expanded to make room for the text. It will print ellipsis for
- text that cannot be shown, according to the view's
- \l{QAbstractItemView::}{textElideMode}.
-*/
-void QListView::setWordWrap(bool on)
-{
- Q_D(QListView);
- if (d->wrapItemText == on)
- return;
- d->wrapItemText = on;
- d->doDelayedItemsLayout();
-}
-
-bool QListView::wordWrap() const
-{
- Q_D(const QListView);
- return d->wrapItemText;
-}
-
-/*!
- \property QListView::selectionRectVisible
- \brief if the selection rectangle should be visible
- \since 4.3
-
- If this property is true then the selection rectangle is visible;
- otherwise it will be hidden.
-
- \note The selection rectangle will only be visible if the selection mode
- is in a mode where more than one item can be selected; i.e., it will not
- draw a selection rectangle if the selection mode is
- QAbstractItemView::SingleSelection.
-
- By default, this property is false.
-*/
-void QListView::setSelectionRectVisible(bool show)
-{
- Q_D(QListView);
- d->modeProperties |= uint(QListViewPrivate::SelectionRectVisible);
- d->setSelectionRectVisible(show);
-}
-
-bool QListView::isSelectionRectVisible() const
-{
- Q_D(const QListView);
- return d->isSelectionRectVisible();
-}
-
-/*!
- \reimp
-*/
-bool QListView::event(QEvent *e)
-{
- return QAbstractItemView::event(e);
-}
-
-/*
- * private object implementation
- */
-
-QListViewPrivate::QListViewPrivate()
- : QAbstractItemViewPrivate(),
- commonListView(0),
- wrap(false),
- space(0),
- flow(QListView::TopToBottom),
- movement(QListView::Static),
- resizeMode(QListView::Fixed),
- layoutMode(QListView::SinglePass),
- viewMode(QListView::ListMode),
- modeProperties(0),
- column(0),
- uniformItemSizes(false),
- batchSize(100),
- showElasticBand(false)
-{
-}
-
-QListViewPrivate::~QListViewPrivate()
-{
- delete commonListView;
-}
-
-void QListViewPrivate::clear()
-{
- // initialization of data structs
- cachedItemSize = QSize();
- commonListView->clear();
-}
-
-void QListViewPrivate::prepareItemsLayout()
-{
- Q_Q(QListView);
- clear();
-
- //take the size as if there were scrollbar in order to prevent scrollbar to blink
- layoutBounds = QRect(QPoint(), q->maximumViewportSize());
-
- int frameAroundContents = 0;
- if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents))
- frameAroundContents = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2;
-
- // maximumViewportSize() already takes scrollbar into account if policy is
- // Qt::ScrollBarAlwaysOn but scrollbar extent must be deduced if policy
- // is Qt::ScrollBarAsNeeded
- int verticalMargin = vbarpolicy==Qt::ScrollBarAsNeeded
- ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, vbar) + frameAroundContents
- : 0;
- int horizontalMargin = hbarpolicy==Qt::ScrollBarAsNeeded
- ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, hbar) + frameAroundContents
- : 0;
-
- layoutBounds.adjust(0, 0, -verticalMargin, -horizontalMargin);
-
- int rowCount = model->columnCount(root) <= 0 ? 0 : model->rowCount(root);
- commonListView->setRowCount(rowCount);
-}
-
-/*!
- \internal
-*/
-bool QListViewPrivate::doItemsLayout(int delta)
-{
- int max = model->rowCount(root) - 1;
- int first = batchStartRow();
- int last = qMin(first + delta - 1, max);
-
- if (first == 0) {
- layoutChildren(); // make sure the viewport has the right size
- prepareItemsLayout();
- }
-
- if (max < 0 || last < first) {
- return true; // nothing to do
- }
-
- QListViewLayoutInfo info;
- info.bounds = layoutBounds;
- info.grid = gridSize();
- info.spacing = (info.grid.isValid() ? 0 : spacing());
- info.first = first;
- info.last = last;
- info.wrap = isWrapping();
- info.flow = flow;
- info.max = max;
-
- return commonListView->doBatchedItemLayout(info, max);
-}
-
-QListViewItem QListViewPrivate::indexToListViewItem(const QModelIndex &index) const
-{
- if (!index.isValid() || isHidden(index.row()))
- return QListViewItem();
-
- return commonListView->indexToListViewItem(index);
-}
-
-QRect QListViewPrivate::mapToViewport(const QRect &rect, bool extend) const
-{
- Q_Q(const QListView);
- if (!rect.isValid())
- return rect;
-
- QRect result = extend ? commonListView->mapToViewport(rect) : rect;
- int dx = -q->horizontalOffset();
- int dy = -q->verticalOffset();
- return result.adjusted(dx, dy, dx, dy);
-}
-
-QModelIndex QListViewPrivate::closestIndex(const QRect &target,
- const QVector<QModelIndex> &candidates) const
-{
- int distance = 0;
- int shortest = INT_MAX;
- QModelIndex closest;
- QVector<QModelIndex>::const_iterator it = candidates.begin();
-
- for (; it != candidates.end(); ++it) {
- if (!(*it).isValid())
- continue;
-
- const QRect indexRect = indexToListViewItem(*it).rect();
-
- //if the center x (or y) position of an item is included in the rect of the other item,
- //we define the distance between them as the difference in x (or y) of their respective center.
- // Otherwise, we use the nahattan length between the 2 items
- if ((target.center().x() >= indexRect.x() && target.center().x() < indexRect.right())
- || (indexRect.center().x() >= target.x() && indexRect.center().x() < target.right())) {
- //one item's center is at the vertical of the other
- distance = qAbs(indexRect.center().y() - target.center().y());
- } else if ((target.center().y() >= indexRect.y() && target.center().y() < indexRect.bottom())
- || (indexRect.center().y() >= target.y() && indexRect.center().y() < target.bottom())) {
- //one item's center is at the vertical of the other
- distance = qAbs(indexRect.center().x() - target.center().x());
- } else {
- distance = (indexRect.center() - target.center()).manhattanLength();
- }
- if (distance < shortest) {
- shortest = distance;
- closest = *it;
- }
- }
- return closest;
-}
-
-QSize QListViewPrivate::itemSize(const QStyleOptionViewItem &option, const QModelIndex &index) const
-{
- if (!uniformItemSizes) {
- const QAbstractItemDelegate *delegate = delegateForIndex(index);
- return delegate ? delegate->sizeHint(option, index) : QSize();
- }
- if (!cachedItemSize.isValid()) { // the last item is probaly the largest, so we use its size
- int row = model->rowCount(root) - 1;
- QModelIndex sample = model->index(row, column, root);
- const QAbstractItemDelegate *delegate = delegateForIndex(sample);
- cachedItemSize = delegate ? delegate->sizeHint(option, sample) : QSize();
- }
- return cachedItemSize;
-}
-
-QItemSelection QListViewPrivate::selection(const QRect &rect) const
-{
- QItemSelection selection;
- QModelIndex tl, br;
- const QVector<QModelIndex> intersectVector = intersectingSet(rect);
- QVector<QModelIndex>::const_iterator it = intersectVector.begin();
- for (; it != intersectVector.end(); ++it) {
- if (!tl.isValid() && !br.isValid()) {
- tl = br = *it;
- } else if ((*it).row() == (tl.row() - 1)) {
- tl = *it; // expand current range
- } else if ((*it).row() == (br.row() + 1)) {
- br = (*it); // expand current range
- } else {
- selection.select(tl, br); // select current range
- tl = br = *it; // start new range
- }
- }
-
- if (tl.isValid() && br.isValid())
- selection.select(tl, br);
- else if (tl.isValid())
- selection.select(tl, tl);
- else if (br.isValid())
- selection.select(br, br);
-
- return selection;
-}
-
-#ifndef QT_NO_DRAGANDDROP
-QAbstractItemView::DropIndicatorPosition QListViewPrivate::position(const QPoint &pos, const QRect &rect, const QModelIndex &idx) const
-{
- if (viewMode == QListView::ListMode && flow == QListView::LeftToRight)
- return static_cast<QListModeViewBase *>(commonListView)->position(pos, rect, idx);
- else
- return QAbstractItemViewPrivate::position(pos, rect, idx);
-}
-
-bool QListViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QModelIndex *dropIndex)
-{
- if (viewMode == QListView::ListMode && flow == QListView::LeftToRight)
- return static_cast<QListModeViewBase *>(commonListView)->dropOn(event, dropRow, dropCol, dropIndex);
- else
- return QAbstractItemViewPrivate::dropOn(event, dropRow, dropCol, dropIndex);
-}
-#endif
-
-/*
- * Common ListView Implementation
-*/
-
-void QCommonListViewBase::appendHiddenRow(int row)
-{
- dd->hiddenRows.insert(dd->model->index(row, 0, qq->rootIndex()));
-}
-
-void QCommonListViewBase::removeHiddenRow(int row)
-{
- dd->hiddenRows.remove(dd->model->index(row, 0, qq->rootIndex()));
-}
-
-void QCommonListViewBase::updateHorizontalScrollBar(const QSize &step)
-{
- horizontalScrollBar()->setSingleStep(step.width() + spacing());
- horizontalScrollBar()->setPageStep(viewport()->width());
- horizontalScrollBar()->setRange(0, contentsSize.width() - viewport()->width());
-}
-
-void QCommonListViewBase::updateVerticalScrollBar(const QSize &step)
-{
- verticalScrollBar()->setSingleStep(step.height() + spacing());
- verticalScrollBar()->setPageStep(viewport()->height());
- verticalScrollBar()->setRange(0, contentsSize.height() - viewport()->height());
-}
-
-void QCommonListViewBase::scrollContentsBy(int dx, int dy, bool /*scrollElasticBand*/)
-{
- dd->scrollContentsBy(isRightToLeft() ? -dx : dx, dy);
-}
-
-int QCommonListViewBase::verticalScrollToValue(int /*index*/, QListView::ScrollHint hint,
- bool above, bool below, const QRect &area, const QRect &rect) const
-{
- int verticalValue = verticalScrollBar()->value();
- QRect adjusted = rect.adjusted(-spacing(), -spacing(), spacing(), spacing());
- if (hint == QListView::PositionAtTop || above)
- verticalValue += adjusted.top();
- else if (hint == QListView::PositionAtBottom || below)
- verticalValue += qMin(adjusted.top(), adjusted.bottom() - area.height() + 1);
- else if (hint == QListView::PositionAtCenter)
- verticalValue += adjusted.top() - ((area.height() - adjusted.height()) / 2);
- return verticalValue;
-}
-
-int QCommonListViewBase::horizontalOffset() const
-{
- return (isRightToLeft() ? horizontalScrollBar()->maximum() - horizontalScrollBar()->value() : horizontalScrollBar()->value());
-}
-
-int QCommonListViewBase::horizontalScrollToValue(const int /*index*/, QListView::ScrollHint hint,
- bool leftOf, bool rightOf, const QRect &area, const QRect &rect) const
-{
- int horizontalValue = horizontalScrollBar()->value();
- if (isRightToLeft()) {
- if (hint == QListView::PositionAtCenter) {
- horizontalValue += ((area.width() - rect.width()) / 2) - rect.left();
- } else {
- if (leftOf)
- horizontalValue -= rect.left();
- else if (rightOf)
- horizontalValue += qMin(rect.left(), area.width() - rect.right());
- }
- } else {
- if (hint == QListView::PositionAtCenter) {
- horizontalValue += rect.left() - ((area.width()- rect.width()) / 2);
- } else {
- if (leftOf)
- horizontalValue += rect.left();
- else if (rightOf)
- horizontalValue += qMin(rect.left(), rect.right() - area.width());
- }
- }
- return horizontalValue;
-}
-
-/*
- * ListMode ListView Implementation
-*/
-
-#ifndef QT_NO_DRAGANDDROP
-void QListModeViewBase::paintDragDrop(QPainter *painter)
-{
- // FIXME: Until the we can provide a proper drop indicator
- // in IconMode, it makes no sense to show it
- dd->paintDropIndicator(painter);
-}
-
-QAbstractItemView::DropIndicatorPosition QListModeViewBase::position(const QPoint &pos, const QRect &rect, const QModelIndex &index) const
-{
- QAbstractItemView::DropIndicatorPosition r = QAbstractItemView::OnViewport;
- if (!dd->overwrite) {
- const int margin = 2;
- if (pos.x() - rect.left() < margin) {
- r = QAbstractItemView::AboveItem; // Visually, on the left
- } else if (rect.right() - pos.x() < margin) {
- r = QAbstractItemView::BelowItem; // Visually, on the right
- } else if (rect.contains(pos, true)) {
- r = QAbstractItemView::OnItem;
- }
- } else {
- QRect touchingRect = rect;
- touchingRect.adjust(-1, -1, 1, 1);
- if (touchingRect.contains(pos, false)) {
- r = QAbstractItemView::OnItem;
- }
- }
-
- if (r == QAbstractItemView::OnItem && (!(dd->model->flags(index) & Qt::ItemIsDropEnabled)))
- r = pos.x() < rect.center().x() ? QAbstractItemView::AboveItem : QAbstractItemView::BelowItem;
-
- return r;
-}
-
-void QListModeViewBase::dragMoveEvent(QDragMoveEvent *event)
-{
- if (qq->dragDropMode() == QAbstractItemView::InternalMove
- && (event->source() != qq || !(event->possibleActions() & Qt::MoveAction)))
- return;
-
- // ignore by default
- event->ignore();
-
- // can't use indexAt, doesn't account for spacing.
- QPoint p = event->pos();
- QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1);
- rect.adjust(-dd->spacing(), -dd->spacing(), dd->spacing(), dd->spacing());
- const QVector<QModelIndex> intersectVector = dd->intersectingSet(rect);
- QModelIndex index = intersectVector.count() > 0
- ? intersectVector.last() : QModelIndex();
- dd->hover = index;
- if (!dd->droppingOnItself(event, index)
- && dd->canDecode(event)) {
-
- if (index.isValid() && dd->showDropIndicator) {
- QRect rect = qq->visualRect(index);
- dd->dropIndicatorPosition = position(event->pos(), rect, index);
- // if spacing, should try to draw between items, not just next to item.
- switch (dd->dropIndicatorPosition) {
- case QAbstractItemView::AboveItem:
- if (dd->isIndexDropEnabled(index.parent())) {
- dd->dropIndicatorRect = QRect(rect.left()-dd->spacing(), rect.top(), 0, rect.height());
- event->accept();
- } else {
- dd->dropIndicatorRect = QRect();
- }
- break;
- case QAbstractItemView::BelowItem:
- if (dd->isIndexDropEnabled(index.parent())) {
- dd->dropIndicatorRect = QRect(rect.right()+dd->spacing(), rect.top(), 0, rect.height());
- event->accept();
- } else {
- dd->dropIndicatorRect = QRect();
- }
- break;
- case QAbstractItemView::OnItem:
- if (dd->isIndexDropEnabled(index)) {
- dd->dropIndicatorRect = rect;
- event->accept();
- } else {
- dd->dropIndicatorRect = QRect();
- }
- break;
- case QAbstractItemView::OnViewport:
- dd->dropIndicatorRect = QRect();
- if (dd->isIndexDropEnabled(qq->rootIndex())) {
- event->accept(); // allow dropping in empty areas
- }
- break;
- }
- } else {
- dd->dropIndicatorRect = QRect();
- dd->dropIndicatorPosition = QAbstractItemView::OnViewport;
- if (dd->isIndexDropEnabled(qq->rootIndex())) {
- event->accept(); // allow dropping in empty areas
- }
- }
- dd->viewport->update();
- } // can decode
-
- if (dd->shouldAutoScroll(event->pos()))
- qq->startAutoScroll();
-}
-
-/*!
- If the event hasn't already been accepted, determines the index to drop on.
-
- if (row == -1 && col == -1)
- // append to this drop index
- else
- // place at row, col in drop index
-
- If it returns true a drop can be done, and dropRow, dropCol and dropIndex reflects the position of the drop.
- \internal
- */
-bool QListModeViewBase::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QModelIndex *dropIndex)
-{
- if (event->isAccepted())
- return false;
-
- QModelIndex index;
- if (dd->viewport->rect().contains(event->pos())) {
- // can't use indexAt, doesn't account for spacing.
- QPoint p = event->pos();
- QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1);
- rect.adjust(-dd->spacing(), -dd->spacing(), dd->spacing(), dd->spacing());
- const QVector<QModelIndex> intersectVector = dd->intersectingSet(rect);
- index = intersectVector.count() > 0
- ? intersectVector.last() : QModelIndex();
- if (!index.isValid())
- index = dd->root;
- }
-
- // If we are allowed to do the drop
- if (dd->model->supportedDropActions() & event->dropAction()) {
- int row = -1;
- int col = -1;
- if (index != dd->root) {
- dd->dropIndicatorPosition = position(event->pos(), qq->visualRect(index), index);
- switch (dd->dropIndicatorPosition) {
- case QAbstractItemView::AboveItem:
- row = index.row();
- col = index.column();
- index = index.parent();
- break;
- case QAbstractItemView::BelowItem:
- row = index.row() + 1;
- col = index.column();
- index = index.parent();
- break;
- case QAbstractItemView::OnItem:
- case QAbstractItemView::OnViewport:
- break;
- }
- } else {
- dd->dropIndicatorPosition = QAbstractItemView::OnViewport;
- }
- *dropIndex = index;
- *dropRow = row;
- *dropCol = col;
- if (!dd->droppingOnItself(event, index))
- return true;
- }
- return false;
-}
-
-#endif //QT_NO_DRAGANDDROP
-
-void QListModeViewBase::updateVerticalScrollBar(const QSize &step)
-{
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem
- && ((flow() == QListView::TopToBottom && !isWrapping())
- || (flow() == QListView::LeftToRight && isWrapping()))) {
- const int steps = (flow() == QListView::TopToBottom ? scrollValueMap : segmentPositions).count() - 1;
- if (steps > 0) {
- const int pageSteps = perItemScrollingPageSteps(viewport()->height(), contentsSize.height(), isWrapping());
- verticalScrollBar()->setSingleStep(1);
- verticalScrollBar()->setPageStep(pageSteps);
- verticalScrollBar()->setRange(0, steps - pageSteps);
- } else {
- verticalScrollBar()->setRange(0, 0);
- }
- // } else if (vertical && d->isWrapping() && d->movement == Static) {
- // ### wrapped scrolling in flow direction
- } else {
- QCommonListViewBase::updateVerticalScrollBar(step);
- }
-}
-
-void QListModeViewBase::updateHorizontalScrollBar(const QSize &step)
-{
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem
- && ((flow() == QListView::TopToBottom && isWrapping())
- || (flow() == QListView::LeftToRight && !isWrapping()))) {
- int steps = (flow() == QListView::TopToBottom ? segmentPositions : scrollValueMap).count() - 1;
- if (steps > 0) {
- const int pageSteps = perItemScrollingPageSteps(viewport()->width(), contentsSize.width(), isWrapping());
- horizontalScrollBar()->setSingleStep(1);
- horizontalScrollBar()->setPageStep(pageSteps);
- horizontalScrollBar()->setRange(0, steps - pageSteps);
- } else {
- horizontalScrollBar()->setRange(0, 0);
- }
- } else {
- QCommonListViewBase::updateHorizontalScrollBar(step);
- }
-}
-
-int QListModeViewBase::verticalScrollToValue(int index, QListView::ScrollHint hint,
- bool above, bool below, const QRect &area, const QRect &rect) const
-{
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int value;
- if (scrollValueMap.isEmpty())
- value = 0;
- else
- value = qBound(0, scrollValueMap.at(verticalScrollBar()->value()), flowPositions.count() - 1);
- if (above)
- hint = QListView::PositionAtTop;
- else if (below)
- hint = QListView::PositionAtBottom;
- if (hint == QListView::EnsureVisible)
- return value;
-
- return perItemScrollToValue(index, value, area.height(), hint, Qt::Vertical, isWrapping(), rect.height());
- }
-
- return QCommonListViewBase::verticalScrollToValue(index, hint, above, below, area, rect);
-}
-
-int QListModeViewBase::horizontalOffset() const
-{
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
- if (isWrapping()) {
- if (flow() == QListView::TopToBottom && !segmentPositions.isEmpty()) {
- const int max = segmentPositions.count() - 1;
- int currentValue = qBound(0, horizontalScrollBar()->value(), max);
- int position = segmentPositions.at(currentValue);
- int maximumValue = qBound(0, horizontalScrollBar()->maximum(), max);
- int maximum = segmentPositions.at(maximumValue);
- return (isRightToLeft() ? maximum - position : position);
- }
- } else if (flow() == QListView::LeftToRight && !flowPositions.isEmpty()) {
- int position = flowPositions.at(scrollValueMap.at(horizontalScrollBar()->value()));
- int maximum = flowPositions.at(scrollValueMap.at(horizontalScrollBar()->maximum()));
- return (isRightToLeft() ? maximum - position : position);
- }
- }
- return QCommonListViewBase::horizontalOffset();
-}
-
-int QListModeViewBase::verticalOffset() const
-{
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- if (isWrapping()) {
- if (flow() == QListView::LeftToRight && !segmentPositions.isEmpty()) {
- int value = verticalScrollBar()->value();
- if (value >= segmentPositions.count())
- return 0;
- return segmentPositions.at(value) - spacing();
- }
- } else if (flow() == QListView::TopToBottom && !flowPositions.isEmpty()) {
- int value = verticalScrollBar()->value();
- if (value > scrollValueMap.count())
- return 0;
- return flowPositions.at(scrollValueMap.at(value)) - spacing();
- }
- }
- return QCommonListViewBase::verticalOffset();
-}
-
-int QListModeViewBase::horizontalScrollToValue(int index, QListView::ScrollHint hint,
- bool leftOf, bool rightOf, const QRect &area, const QRect &rect) const
-{
- if (horizontalScrollMode() != QAbstractItemView::ScrollPerItem)
- return QCommonListViewBase::horizontalScrollToValue(index, hint, leftOf, rightOf, area, rect);
-
- int value;
- if (scrollValueMap.isEmpty())
- value = 0;
- else
- value = qBound(0, scrollValueMap.at(horizontalScrollBar()->value()), flowPositions.count() - 1);
- if (leftOf)
- hint = QListView::PositionAtTop;
- else if (rightOf)
- hint = QListView::PositionAtBottom;
- if (hint == QListView::EnsureVisible)
- return value;
-
- return perItemScrollToValue(index, value, area.width(), hint, Qt::Horizontal, isWrapping(), rect.width());
-}
-
-void QListModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand)
-{
- // ### reorder this logic
- const int verticalValue = verticalScrollBar()->value();
- const int horizontalValue = horizontalScrollBar()->value();
- const bool vertical = (verticalScrollMode() == QAbstractItemView::ScrollPerItem);
- const bool horizontal = (horizontalScrollMode() == QAbstractItemView::ScrollPerItem);
-
- if (isWrapping()) {
- if (segmentPositions.isEmpty())
- return;
- const int max = segmentPositions.count() - 1;
- if (horizontal && flow() == QListView::TopToBottom && dx != 0) {
- int currentValue = qBound(0, horizontalValue, max);
- int previousValue = qBound(0, currentValue + dx, max);
- int currentCoordinate = segmentPositions.at(currentValue) - spacing();
- int previousCoordinate = segmentPositions.at(previousValue) - spacing();
- dx = previousCoordinate - currentCoordinate;
- } else if (vertical && flow() == QListView::LeftToRight && dy != 0) {
- int currentValue = qBound(0, verticalValue, max);
- int previousValue = qBound(0, currentValue + dy, max);
- int currentCoordinate = segmentPositions.at(currentValue) - spacing();
- int previousCoordinate = segmentPositions.at(previousValue) - spacing();
- dy = previousCoordinate - currentCoordinate;
- }
- } else {
- if (flowPositions.isEmpty())
- return;
- const int max = scrollValueMap.count() - 1;
- if (vertical && flow() == QListView::TopToBottom && dy != 0) {
- int currentValue = qBound(0, verticalValue, max);
- int previousValue = qBound(0, currentValue + dy, max);
- int currentCoordinate = flowPositions.at(scrollValueMap.at(currentValue));
- int previousCoordinate = flowPositions.at(scrollValueMap.at(previousValue));
- dy = previousCoordinate - currentCoordinate;
- } else if (horizontal && flow() == QListView::LeftToRight && dx != 0) {
- int currentValue = qBound(0, horizontalValue, max);
- int previousValue = qBound(0, currentValue + dx, max);
- int currentCoordinate = flowPositions.at(scrollValueMap.at(currentValue));
- int previousCoordinate = flowPositions.at(scrollValueMap.at(previousValue));
- dx = previousCoordinate - currentCoordinate;
- }
- }
- QCommonListViewBase::scrollContentsBy(dx, dy, scrollElasticBand);
-}
-
-bool QListModeViewBase::doBatchedItemLayout(const QListViewLayoutInfo &info, int max)
-{
- doStaticLayout(info);
- if (batchStartRow > max) { // stop items layout
- flowPositions.resize(flowPositions.count());
- segmentPositions.resize(segmentPositions.count());
- segmentStartRows.resize(segmentStartRows.count());
- return true; // done
- }
- return false; // not done
-}
-
-QListViewItem QListModeViewBase::indexToListViewItem(const QModelIndex &index) const
-{
- if (flowPositions.isEmpty()
- || segmentPositions.isEmpty()
- || index.row() >= flowPositions.count())
- return QListViewItem();
-
- const int segment = qBinarySearch<int>(segmentStartRows, index.row(),
- 0, segmentStartRows.count() - 1);
-
-
- QStyleOptionViewItemV4 options = viewOptions();
- options.rect.setSize(contentsSize);
- QSize size = (uniformItemSizes() && cachedItemSize().isValid())
- ? cachedItemSize() : itemSize(options, index);
-
- QPoint pos;
- if (flow() == QListView::LeftToRight) {
- pos.setX(flowPositions.at(index.row()));
- pos.setY(segmentPositions.at(segment));
- } else { // TopToBottom
- pos.setY(flowPositions.at(index.row()));
- pos.setX(segmentPositions.at(segment));
- if (isWrapping()) { // make the items as wide as the segment
- int right = (segment + 1 >= segmentPositions.count()
- ? contentsSize.width()
- : segmentPositions.at(segment + 1));
- size.setWidth(right - pos.x());
- } else { // make the items as wide as the viewport
- size.setWidth(qMax(size.width(), viewport()->width()));
- }
- }
-
- return QListViewItem(QRect(pos, size), index.row());
-}
-
-QPoint QListModeViewBase::initStaticLayout(const QListViewLayoutInfo &info)
-{
- int x, y;
- if (info.first == 0) {
- flowPositions.clear();
- segmentPositions.clear();
- segmentStartRows.clear();
- segmentExtents.clear();
- scrollValueMap.clear();
- x = info.bounds.left() + info.spacing;
- y = info.bounds.top() + info.spacing;
- segmentPositions.append(info.flow == QListView::LeftToRight ? y : x);
- segmentStartRows.append(0);
- } else if (info.wrap) {
- if (info.flow == QListView::LeftToRight) {
- x = batchSavedPosition;
- y = segmentPositions.last();
- } else { // flow == QListView::TopToBottom
- x = segmentPositions.last();
- y = batchSavedPosition;
- }
- } else { // not first and not wrap
- if (info.flow == QListView::LeftToRight) {
- x = batchSavedPosition;
- y = info.bounds.top() + info.spacing;
- } else { // flow == QListView::TopToBottom
- x = info.bounds.left() + info.spacing;
- y = batchSavedPosition;
- }
- }
- return QPoint(x, y);
-}
-
-/*!
- \internal
-*/
-void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info)
-{
- const bool useItemSize = !info.grid.isValid();
- const QPoint topLeft = initStaticLayout(info);
- QStyleOptionViewItemV4 option = viewOptions();
- option.rect = info.bounds;
- option.rect.adjust(info.spacing, info.spacing, -info.spacing, -info.spacing);
-
- // The static layout data structures are as follows:
- // One vector contains the coordinate in the direction of layout flow.
- // Another vector contains the coordinates of the segments.
- // A third vector contains the index (model row) of the first item
- // of each segment.
-
- int segStartPosition;
- int segEndPosition;
- int deltaFlowPosition;
- int deltaSegPosition;
- int deltaSegHint;
- int flowPosition;
- int segPosition;
-
- if (info.flow == QListView::LeftToRight) {
- segStartPosition = info.bounds.left();
- segEndPosition = info.bounds.width();
- flowPosition = topLeft.x();
- segPosition = topLeft.y();
- deltaFlowPosition = info.grid.width(); // dx
- deltaSegPosition = useItemSize ? batchSavedDeltaSeg : info.grid.height(); // dy
- deltaSegHint = info.grid.height();
- } else { // flow == QListView::TopToBottom
- segStartPosition = info.bounds.top();
- segEndPosition = info.bounds.height();
- flowPosition = topLeft.y();
- segPosition = topLeft.x();
- deltaFlowPosition = info.grid.height(); // dy
- deltaSegPosition = useItemSize ? batchSavedDeltaSeg : info.grid.width(); // dx
- deltaSegHint = info.grid.width();
- }
-
- for (int row = info.first; row <= info.last; ++row) {
- if (isHidden(row)) { // ###
- flowPositions.append(flowPosition);
- } else {
- // if we are not using a grid, we need to find the deltas
- if (useItemSize) {
- QSize hint = itemSize(option, modelIndex(row));
- if (info.flow == QListView::LeftToRight) {
- deltaFlowPosition = hint.width() + info.spacing;
- deltaSegHint = hint.height() + info.spacing;
- } else { // TopToBottom
- deltaFlowPosition = hint.height() + info.spacing;
- deltaSegHint = hint.width() + info.spacing;
- }
- }
- // create new segment
- if (info.wrap && (flowPosition + deltaFlowPosition >= segEndPosition)) {
- segmentExtents.append(flowPosition);
- flowPosition = info.spacing + segStartPosition;
- segPosition += deltaSegPosition;
- if (info.wrap)
- segPosition += info.spacing;
- segmentPositions.append(segPosition);
- segmentStartRows.append(row);
- deltaSegPosition = 0;
- }
- // save the flow position of this item
- scrollValueMap.append(flowPositions.count());
- flowPositions.append(flowPosition);
- // prepare for the next item
- deltaSegPosition = qMax(deltaSegHint, deltaSegPosition);
- flowPosition += info.spacing + deltaFlowPosition;
- }
- }
- // used when laying out next batch
- batchSavedPosition = flowPosition;
- batchSavedDeltaSeg = deltaSegPosition;
- batchStartRow = info.last + 1;
- if (info.last == info.max)
- flowPosition -= info.spacing; // remove extra spacing
- // set the contents size
- QRect rect = info.bounds;
- if (info.flow == QListView::LeftToRight) {
- rect.setRight(segmentPositions.count() == 1 ? flowPosition : info.bounds.right());
- rect.setBottom(segPosition + deltaSegPosition);
- } else { // TopToBottom
- rect.setRight(segPosition + deltaSegPosition);
- rect.setBottom(segmentPositions.count() == 1 ? flowPosition : info.bounds.bottom());
- }
- contentsSize = QSize(rect.right(), rect.bottom());
- // if it is the last batch, save the end of the segments
- if (info.last == info.max) {
- segmentExtents.append(flowPosition);
- scrollValueMap.append(flowPositions.count());
- flowPositions.append(flowPosition);
- segmentPositions.append(info.wrap ? segPosition + deltaSegPosition : INT_MAX);
- }
- // if the new items are visble, update the viewport
- QRect changedRect(topLeft, rect.bottomRight());
- if (clipRect().intersects(changedRect))
- viewport()->update();
-}
-
-/*!
- \internal
- Finds the set of items intersecting with \a area.
- In this function, itemsize is counted from topleft to the start of the next item.
-*/
-QVector<QModelIndex> QListModeViewBase::intersectingSet(const QRect &area) const
-{
- QVector<QModelIndex> ret;
- int segStartPosition;
- int segEndPosition;
- int flowStartPosition;
- int flowEndPosition;
- if (flow() == QListView::LeftToRight) {
- segStartPosition = area.top();
- segEndPosition = area.bottom();
- flowStartPosition = area.left();
- flowEndPosition = area.right();
- } else {
- segStartPosition = area.left();
- segEndPosition = area.right();
- flowStartPosition = area.top();
- flowEndPosition = area.bottom();
- }
- if (segmentPositions.count() < 2 || flowPositions.isEmpty())
- return ret;
- // the last segment position is actually the edge of the last segment
- const int segLast = segmentPositions.count() - 2;
- int seg = qBinarySearch<int>(segmentPositions, segStartPosition, 0, segLast + 1);
- for (; seg <= segLast && segmentPositions.at(seg) <= segEndPosition; ++seg) {
- int first = segmentStartRows.at(seg);
- int last = (seg < segLast ? segmentStartRows.at(seg + 1) : batchStartRow) - 1;
- if (segmentExtents.at(seg) < flowStartPosition)
- continue;
- int row = qBinarySearch<int>(flowPositions, flowStartPosition, first, last);
- for (; row <= last && flowPositions.at(row) <= flowEndPosition; ++row) {
- if (isHidden(row))
- continue;
- QModelIndex index = modelIndex(row);
- if (index.isValid())
- ret += index;
-#if 0 // for debugging
- else
- qWarning("intersectingSet: row %d was invalid", row);
-#endif
- }
- }
- return ret;
-}
-
-void QListModeViewBase::dataChanged(const QModelIndex &, const QModelIndex &)
-{
- dd->doDelayedItemsLayout();
-}
-
-
-QRect QListModeViewBase::mapToViewport(const QRect &rect) const
-{
- if (isWrapping())
- return rect;
- // If the listview is in "listbox-mode", the items are as wide as the view.
- // But we don't shrink the items.
- QRect result = rect;
- if (flow() == QListView::TopToBottom) {
- result.setLeft(spacing());
- result.setWidth(qMax(rect.width(), qMax(contentsSize.width(), viewport()->width()) - 2 * spacing()));
- } else { // LeftToRight
- result.setTop(spacing());
- result.setHeight(qMax(rect.height(), qMax(contentsSize.height(), viewport()->height()) - 2 * spacing()));
- }
- return result;
-}
-
-int QListModeViewBase::perItemScrollingPageSteps(int length, int bounds, bool wrap) const
-{
- QVector<int> positions;
- if (wrap)
- positions = segmentPositions;
- else if (!flowPositions.isEmpty()) {
- positions.reserve(scrollValueMap.size());
- foreach (int itemShown, scrollValueMap)
- positions.append(flowPositions.at(itemShown));
- }
- if (positions.isEmpty() || bounds <= length)
- return positions.count();
- if (uniformItemSizes()) {
- for (int i = 1; i < positions.count(); ++i)
- if (positions.at(i) > 0)
- return length / positions.at(i);
- return 0; // all items had height 0
- }
- int pageSteps = 0;
- int steps = positions.count() - 1;
- int max = qMax(length, bounds);
- int min = qMin(length, bounds);
- int pos = min - (max - positions.last());
-
- while (pos >= 0 && steps > 0) {
- pos -= (positions.at(steps) - positions.at(steps - 1));
- if (pos >= 0) //this item should be visible
- ++pageSteps;
- --steps;
- }
-
- // at this point we know that positions has at least one entry
- return qMax(pageSteps, 1);
-}
-
-int QListModeViewBase::perItemScrollToValue(int index, int scrollValue, int viewportSize,
- QAbstractItemView::ScrollHint hint,
- Qt::Orientation orientation, bool wrap, int itemExtent) const
-{
- if (index < 0)
- return scrollValue;
- if (!wrap) {
- int topIndex = index;
- const int bottomIndex = topIndex;
- const int bottomCoordinate = flowPositions.at(index);
-
- while (topIndex > 0 &&
- (bottomCoordinate - flowPositions.at(topIndex-1) + itemExtent) <= (viewportSize)) {
- topIndex--;
- }
-
- const int itemCount = bottomIndex - topIndex + 1;
- switch (hint) {
- case QAbstractItemView::PositionAtTop:
- return index;
- case QAbstractItemView::PositionAtBottom:
- return index - itemCount + 1;
- case QAbstractItemView::PositionAtCenter:
- return index - (itemCount / 2);
- default:
- break;
- }
- } else { // wrapping
- Qt::Orientation flowOrientation = (flow() == QListView::LeftToRight
- ? Qt::Horizontal : Qt::Vertical);
- if (flowOrientation == orientation) { // scrolling in the "flow" direction
- // ### wrapped scrolling in the flow direction
- return flowPositions.at(index); // ### always pixel based for now
- } else if (!segmentStartRows.isEmpty()) { // we are scrolling in the "segment" direction
- int segment = qBinarySearch<int>(segmentStartRows, index, 0, segmentStartRows.count() - 1);
- int leftSegment = segment;
- const int rightSegment = leftSegment;
- const int bottomCoordinate = segmentPositions.at(segment);
-
- while (leftSegment > scrollValue &&
- (bottomCoordinate - segmentPositions.at(leftSegment-1) + itemExtent) <= (viewportSize)) {
- leftSegment--;
- }
-
- const int segmentCount = rightSegment - leftSegment + 1;
- switch (hint) {
- case QAbstractItemView::PositionAtTop:
- return segment;
- case QAbstractItemView::PositionAtBottom:
- return segment - segmentCount + 1;
- case QAbstractItemView::PositionAtCenter:
- return segment - (segmentCount / 2);
- default:
- break;
- }
- }
- }
- return scrollValue;
-}
-
-void QListModeViewBase::clear()
-{
- flowPositions.clear();
- segmentPositions.clear();
- segmentStartRows.clear();
- segmentExtents.clear();
- batchSavedPosition = 0;
- batchStartRow = 0;
- batchSavedDeltaSeg = 0;
-}
-
-/*
- * IconMode ListView Implementation
-*/
-
-void QIconModeViewBase::setPositionForIndex(const QPoint &position, const QModelIndex &index)
-{
- if (index.row() >= items.count())
- return;
- const QSize oldContents = contentsSize;
- qq->update(index); // update old position
- moveItem(index.row(), position);
- qq->update(index); // update new position
-
- if (contentsSize != oldContents)
- dd->viewUpdateGeometries(); // update the scroll bars
-}
-
-void QIconModeViewBase::appendHiddenRow(int row)
-{
- if (row >= 0 && row < items.count()) //remove item
- tree.removeLeaf(items.at(row).rect(), row);
- QCommonListViewBase::appendHiddenRow(row);
-}
-
-void QIconModeViewBase::removeHiddenRow(int row)
-{
- QCommonListViewBase::removeHiddenRow(row);
- if (row >= 0 && row < items.count()) //insert item
- tree.insertLeaf(items.at(row).rect(), row);
-}
-
-#ifndef QT_NO_DRAGANDDROP
-void QIconModeViewBase::paintDragDrop(QPainter *painter)
-{
- if (!draggedItems.isEmpty() && viewport()->rect().contains(draggedItemsPos)) {
- //we need to draw the items that arre dragged
- painter->translate(draggedItemsDelta());
- QStyleOptionViewItemV4 option = viewOptions();
- option.state &= ~QStyle::State_MouseOver;
- QVector<QModelIndex>::const_iterator it = draggedItems.begin();
- QListViewItem item = indexToListViewItem(*it);
- for (; it != draggedItems.end(); ++it) {
- item = indexToListViewItem(*it);
- option.rect = viewItemRect(item);
- delegate(*it)->paint(painter, option, *it);
- }
- }
-}
-
-bool QIconModeViewBase::filterStartDrag(Qt::DropActions supportedActions)
-{
- // This function does the same thing as in QAbstractItemView::startDrag(),
- // plus adding viewitems to the draggedItems list.
- // We need these items to draw the drag items
- QModelIndexList indexes = dd->selectionModel->selectedIndexes();
- if (indexes.count() > 0 ) {
- if (viewport()->acceptDrops()) {
- QModelIndexList::ConstIterator it = indexes.constBegin();
- for (; it != indexes.constEnd(); ++it)
- if (dd->model->flags(*it) & Qt::ItemIsDragEnabled
- && (*it).column() == dd->column)
- draggedItems.push_back(*it);
- }
- QDrag *drag = new QDrag(qq);
- drag->setMimeData(dd->model->mimeData(indexes));
- Qt::DropAction action = drag->exec(supportedActions, Qt::CopyAction);
- draggedItems.clear();
- if (action == Qt::MoveAction)
- dd->clearOrRemove();
- }
- return true;
-}
-
-bool QIconModeViewBase::filterDropEvent(QDropEvent *e)
-{
- if (e->source() != qq)
- return false;
-
- const QSize contents = contentsSize;
- QPoint offset(horizontalOffset(), verticalOffset());
- QPoint end = e->pos() + offset;
- if (qq->acceptDrops()) {
- const Qt::ItemFlags dropableFlags = Qt::ItemIsDropEnabled|Qt::ItemIsEnabled;
- const QVector<QModelIndex> &dropIndices = intersectingSet(QRect(end, QSize(1, 1)));
- foreach (const QModelIndex &index, dropIndices)
- if ((index.flags() & dropableFlags) == dropableFlags)
- return false;
- }
- QPoint start = dd->pressedPosition;
- QPoint delta = (dd->movement == QListView::Snap ? snapToGrid(end) - snapToGrid(start) : end - start);
- QList<QModelIndex> indexes = dd->selectionModel->selectedIndexes();
- for (int i = 0; i < indexes.count(); ++i) {
- QModelIndex index = indexes.at(i);
- QRect rect = dd->rectForIndex(index);
- viewport()->update(dd->mapToViewport(rect, false));
- QPoint dest = rect.topLeft() + delta;
- if (qq->isRightToLeft())
- dest.setX(dd->flipX(dest.x()) - rect.width());
- moveItem(index.row(), dest);
- qq->update(index);
- }
- dd->stopAutoScroll();
- draggedItems.clear();
- dd->emitIndexesMoved(indexes);
- e->accept(); // we have handled the event
- // if the size has not grown, we need to check if it has shrinked
- if (contentsSize != contents) {
- if ((contentsSize.width() <= contents.width()
- || contentsSize.height() <= contents.height())) {
- updateContentsSize();
- }
- dd->viewUpdateGeometries();
- }
- return true;
-}
-
-bool QIconModeViewBase::filterDragLeaveEvent(QDragLeaveEvent *e)
-{
- viewport()->update(draggedItemsRect()); // erase the area
- draggedItemsPos = QPoint(-1, -1); // don't draw the dragged items
- return QCommonListViewBase::filterDragLeaveEvent(e);
-}
-
-bool QIconModeViewBase::filterDragMoveEvent(QDragMoveEvent *e)
-{
- if (e->source() != qq || !dd->canDecode(e))
- return false;
-
- // ignore by default
- e->ignore();
- // get old dragged items rect
- QRect itemsRect = this->itemsRect(draggedItems);
- viewport()->update(itemsRect.translated(draggedItemsDelta()));
- // update position
- draggedItemsPos = e->pos();
- // get new items rect
- viewport()->update(itemsRect.translated(draggedItemsDelta()));
- // set the item under the cursor to current
- QModelIndex index;
- if (movement() == QListView::Snap) {
- QRect rect(snapToGrid(e->pos() + offset()), gridSize());
- const QVector<QModelIndex> intersectVector = intersectingSet(rect);
- index = intersectVector.count() > 0 ? intersectVector.last() : QModelIndex();
- } else {
- index = qq->indexAt(e->pos());
- }
- // check if we allow drops here
- if (draggedItems.contains(index))
- e->accept(); // allow changing item position
- else if (dd->model->flags(index) & Qt::ItemIsDropEnabled)
- e->accept(); // allow dropping on dropenabled items
- else if (!index.isValid())
- e->accept(); // allow dropping in empty areas
-
- // the event was treated. do autoscrolling
- if (dd->shouldAutoScroll(e->pos()))
- dd->startAutoScroll();
- return true;
-}
-#endif // QT_NO_DRAGANDDROP
-
-void QIconModeViewBase::setRowCount(int rowCount)
-{
- tree.create(qMax(rowCount - hiddenCount(), 0));
-}
-
-void QIconModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand)
-{
- if (scrollElasticBand)
- dd->scrollElasticBandBy(isRightToLeft() ? -dx : dx, dy);
-
- QCommonListViewBase::scrollContentsBy(dx, dy, scrollElasticBand);
- if (!draggedItems.isEmpty())
- viewport()->update(draggedItemsRect().translated(dx, dy));
-}
-
-void QIconModeViewBase::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- if (column() >= topLeft.column() && column() <= bottomRight.column()) {
- QStyleOptionViewItemV4 option = viewOptions();
- int bottom = qMin(items.count(), bottomRight.row() + 1);
- for (int row = topLeft.row(); row < bottom; ++row)
- items[row].resize(itemSize(option, modelIndex(row)));
- }
-}
-
-bool QIconModeViewBase::doBatchedItemLayout(const QListViewLayoutInfo &info, int max)
-{
- if (info.last >= items.count()) {
- //first we create the items
- QStyleOptionViewItemV4 option = viewOptions();
- for (int row = items.count(); row <= info.last; ++row) {
- QSize size = itemSize(option, modelIndex(row));
- QListViewItem item(QRect(0, 0, size.width(), size.height()), row); // default pos
- items.append(item);
- }
- doDynamicLayout(info);
- }
- return (batchStartRow > max); // done
-}
-
-QListViewItem QIconModeViewBase::indexToListViewItem(const QModelIndex &index) const
-{
- if (index.isValid() && index.row() < items.count())
- return items.at(index.row());
- return QListViewItem();
-}
-
-void QIconModeViewBase::initBspTree(const QSize &contents)
-{
- // remove all items from the tree
- int leafCount = tree.leafCount();
- for (int l = 0; l < leafCount; ++l)
- tree.leaf(l).clear();
- // we have to get the bounding rect of the items before we can initialize the tree
- QBspTree::Node::Type type = QBspTree::Node::Both; // 2D
- // simple heuristics to get better bsp
- if (contents.height() / contents.width() >= 3)
- type = QBspTree::Node::HorizontalPlane;
- else if (contents.width() / contents.height() >= 3)
- type = QBspTree::Node::VerticalPlane;
- // build tree for the bounding rect (not just the contents rect)
- tree.init(QRect(0, 0, contents.width(), contents.height()), type);
-}
-
-QPoint QIconModeViewBase::initDynamicLayout(const QListViewLayoutInfo &info)
-{
- int x, y;
- if (info.first == 0) {
- x = info.bounds.x() + info.spacing;
- y = info.bounds.y() + info.spacing;
- items.reserve(rowCount() - hiddenCount());
- } else {
- int idx = info.first - 1;
- while (idx > 0 && !items.at(idx).isValid())
- --idx;
- const QListViewItem &item = items.at(idx);
- x = item.x;
- y = item.y;
- if (info.flow == QListView::LeftToRight)
- x += (info.grid.isValid() ? info.grid.width() : item.w) + info.spacing;
- else
- y += (info.grid.isValid() ? info.grid.height() : item.h) + info.spacing;
- }
- return QPoint(x, y);
-}
-
-/*!
- \internal
-*/
-void QIconModeViewBase::doDynamicLayout(const QListViewLayoutInfo &info)
-{
- const bool useItemSize = !info.grid.isValid();
- const QPoint topLeft = initDynamicLayout(info);
-
- int segStartPosition;
- int segEndPosition;
- int deltaFlowPosition;
- int deltaSegPosition;
- int deltaSegHint;
- int flowPosition;
- int segPosition;
-
- if (info.flow == QListView::LeftToRight) {
- segStartPosition = info.bounds.left() + info.spacing;
- segEndPosition = info.bounds.right();
- deltaFlowPosition = info.grid.width(); // dx
- deltaSegPosition = (useItemSize ? batchSavedDeltaSeg : info.grid.height()); // dy
- deltaSegHint = info.grid.height();
- flowPosition = topLeft.x();
- segPosition = topLeft.y();
- } else { // flow == QListView::TopToBottom
- segStartPosition = info.bounds.top() + info.spacing;
- segEndPosition = info.bounds.bottom();
- deltaFlowPosition = info.grid.height(); // dy
- deltaSegPosition = (useItemSize ? batchSavedDeltaSeg : info.grid.width()); // dx
- deltaSegHint = info.grid.width();
- flowPosition = topLeft.y();
- segPosition = topLeft.x();
- }
-
- if (moved.count() != items.count())
- moved.resize(items.count());
-
- QRect rect(QPoint(), topLeft);
- QListViewItem *item = 0;
- for (int row = info.first; row <= info.last; ++row) {
- item = &items[row];
- if (isHidden(row)) {
- item->invalidate();
- } else {
- // if we are not using a grid, we need to find the deltas
- if (useItemSize) {
- if (info.flow == QListView::LeftToRight)
- deltaFlowPosition = item->w + info.spacing;
- else
- deltaFlowPosition = item->h + info.spacing;
- } else {
- item->w = qMin<int>(info.grid.width(), item->w);
- item->h = qMin<int>(info.grid.height(), item->h);
- }
-
- // create new segment
- if (info.wrap
- && flowPosition + deltaFlowPosition > segEndPosition
- && flowPosition > segStartPosition) {
- flowPosition = segStartPosition;
- segPosition += deltaSegPosition;
- if (useItemSize)
- deltaSegPosition = 0;
- }
- // We must delay calculation of the seg adjustment, as this item
- // may have caused a wrap to occur
- if (useItemSize) {
- if (info.flow == QListView::LeftToRight)
- deltaSegHint = item->h + info.spacing;
- else
- deltaSegHint = item->w + info.spacing;
- deltaSegPosition = qMax(deltaSegPosition, deltaSegHint);
- }
-
- // set the position of the item
- // ### idealy we should have some sort of alignment hint for the item
- // ### (normally that would be a point between the icon and the text)
- if (!moved.testBit(row)) {
- if (info.flow == QListView::LeftToRight) {
- if (useItemSize) {
- item->x = flowPosition;
- item->y = segPosition;
- } else { // use grid
- item->x = flowPosition + ((deltaFlowPosition - item->w) / 2);
- item->y = segPosition;
- }
- } else { // TopToBottom
- if (useItemSize) {
- item->y = flowPosition;
- item->x = segPosition;
- } else { // use grid
- item->y = flowPosition + ((deltaFlowPosition - item->h) / 2);
- item->x = segPosition;
- }
- }
- }
-
- // let the contents contain the new item
- if (useItemSize)
- rect |= item->rect();
- else if (info.flow == QListView::LeftToRight)
- rect |= QRect(flowPosition, segPosition, deltaFlowPosition, deltaSegPosition);
- else // flow == TopToBottom
- rect |= QRect(segPosition, flowPosition, deltaSegPosition, deltaFlowPosition);
-
- // prepare for next item
- flowPosition += deltaFlowPosition; // current position + item width + gap
- }
- }
- batchSavedDeltaSeg = deltaSegPosition;
- batchStartRow = info.last + 1;
- bool done = (info.last >= rowCount() - 1);
- // resize the content area
- if (done || !info.bounds.contains(item->rect())) {
- contentsSize = rect.size();
- if (info.flow == QListView::LeftToRight)
- contentsSize.rheight() += info.spacing;
- else
- contentsSize.rwidth() += info.spacing;
- }
- if (rect.size().isEmpty())
- return;
- // resize tree
- int insertFrom = info.first;
- if (done || info.first == 0) {
- initBspTree(rect.size());
- insertFrom = 0;
- }
- // insert items in tree
- for (int row = insertFrom; row <= info.last; ++row)
- tree.insertLeaf(items.at(row).rect(), row);
- // if the new items are visble, update the viewport
- QRect changedRect(topLeft, rect.bottomRight());
- if (clipRect().intersects(changedRect))
- viewport()->update();
-}
-
-QVector<QModelIndex> QIconModeViewBase::intersectingSet(const QRect &area) const
-{
- QIconModeViewBase *that = const_cast<QIconModeViewBase*>(this);
- QBspTree::Data data(static_cast<void*>(that));
- QVector<QModelIndex> res;
- that->interSectingVector = &res;
- that->tree.climbTree(area, &QIconModeViewBase::addLeaf, data);
- that->interSectingVector = 0;
- return res;
-}
-
-QRect QIconModeViewBase::itemsRect(const QVector<QModelIndex> &indexes) const
-{
- QVector<QModelIndex>::const_iterator it = indexes.begin();
- QListViewItem item = indexToListViewItem(*it);
- QRect rect(item.x, item.y, item.w, item.h);
- for (; it != indexes.end(); ++it) {
- item = indexToListViewItem(*it);
- rect |= viewItemRect(item);
- }
- return rect;
-}
-
-int QIconModeViewBase::itemIndex(const QListViewItem &item) const
-{
- if (!item.isValid())
- return -1;
- int i = item.indexHint;
- if (i < items.count()) {
- if (items.at(i) == item)
- return i;
- } else {
- i = items.count() - 1;
- }
-
- int j = i;
- int c = items.count();
- bool a = true;
- bool b = true;
-
- while (a || b) {
- if (a) {
- if (items.at(i) == item) {
- items.at(i).indexHint = i;
- return i;
- }
- a = ++i < c;
- }
- if (b) {
- if (items.at(j) == item) {
- items.at(j).indexHint = j;
- return j;
- }
- b = --j > -1;
- }
- }
- return -1;
-}
-
-void QIconModeViewBase::addLeaf(QVector<int> &leaf, const QRect &area,
- uint visited, QBspTree::Data data)
-{
- QListViewItem *vi;
- QIconModeViewBase *_this = static_cast<QIconModeViewBase *>(data.ptr);
- for (int i = 0; i < leaf.count(); ++i) {
- int idx = leaf.at(i);
- if (idx < 0 || idx >= _this->items.count())
- continue;
- vi = &_this->items[idx];
- Q_ASSERT(vi);
- if (vi->isValid() && vi->rect().intersects(area) && vi->visited != visited) {
- QModelIndex index = _this->dd->listViewItemToIndex(*vi);
- Q_ASSERT(index.isValid());
- _this->interSectingVector->append(index);
- vi->visited = visited;
- }
- }
-}
-
-void QIconModeViewBase::moveItem(int index, const QPoint &dest)
-{
- // does not impact on the bintree itself or the contents rect
- QListViewItem *item = &items[index];
- QRect rect = item->rect();
-
- // move the item without removing it from the tree
- tree.removeLeaf(rect, index);
- item->move(dest);
- tree.insertLeaf(QRect(dest, rect.size()), index);
-
- // resize the contents area
- contentsSize = (QRect(QPoint(0, 0), contentsSize)|QRect(dest, rect.size())).size();
-
- // mark the item as moved
- if (moved.count() != items.count())
- moved.resize(items.count());
- moved.setBit(index, true);
-}
-
-QPoint QIconModeViewBase::snapToGrid(const QPoint &pos) const
-{
- int x = pos.x() - (pos.x() % gridSize().width());
- int y = pos.y() - (pos.y() % gridSize().height());
- return QPoint(x, y);
-}
-
-QPoint QIconModeViewBase::draggedItemsDelta() const
-{
- if (movement() == QListView::Snap) {
- QPoint snapdelta = QPoint((offset().x() % gridSize().width()),
- (offset().y() % gridSize().height()));
- return snapToGrid(draggedItemsPos + snapdelta) - snapToGrid(pressedPosition()) - snapdelta;
- }
- return draggedItemsPos - pressedPosition();
-}
-
-QRect QIconModeViewBase::draggedItemsRect() const
-{
- QRect rect = itemsRect(draggedItems);
- rect.translate(draggedItemsDelta());
- return rect;
-}
-
-void QListViewPrivate::scrollElasticBandBy(int dx, int dy)
-{
- if (dx > 0) // right
- elasticBand.moveRight(elasticBand.right() + dx);
- else if (dx < 0) // left
- elasticBand.moveLeft(elasticBand.left() - dx);
- if (dy > 0) // down
- elasticBand.moveBottom(elasticBand.bottom() + dy);
- else if (dy < 0) // up
- elasticBand.moveTop(elasticBand.top() - dy);
-}
-
-void QIconModeViewBase::clear()
-{
- tree.destroy();
- items.clear();
- moved.clear();
- batchStartRow = 0;
- batchSavedDeltaSeg = 0;
-}
-
-void QIconModeViewBase::updateContentsSize()
-{
- QRect bounding;
- for (int i = 0; i < items.count(); ++i)
- bounding |= items.at(i).rect();
- contentsSize = bounding.size();
-}
-
-/*!
- \reimp
-*/
-void QListView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
-{
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- if (current.isValid()) {
- int entry = visualIndex(current) + 1;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::Focus);
- }
- }
-#endif
- QAbstractItemView::currentChanged(current, previous);
-}
-
-/*!
- \reimp
-*/
-void QListView::selectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected)
-{
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- // ### does not work properly for selection ranges.
- QModelIndex sel = selected.indexes().value(0);
- if (sel.isValid()) {
- int entry = visualIndex(sel) + 1;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::Selection);
- }
- QModelIndex desel = deselected.indexes().value(0);
- if (desel.isValid()) {
- int entry = visualIndex(desel) + 1;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::SelectionRemove);
- }
- }
-#endif
- QAbstractItemView::selectionChanged(selected, deselected);
-}
-
-int QListView::visualIndex(const QModelIndex &index) const
-{
- Q_D(const QListView);
- d->executePostedLayout();
- QListViewItem itm = d->indexToListViewItem(index);
- return d->commonListView->itemIndex(itm);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_LISTVIEW
diff --git a/src/gui/itemviews/qlistview.h b/src/gui/itemviews/qlistview.h
deleted file mode 100644
index 3d6dd421f7..0000000000
--- a/src/gui/itemviews/qlistview.h
+++ /dev/null
@@ -1,203 +0,0 @@
-/****************************************************************************
-**
-** 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 QLISTVIEW_H
-#define QLISTVIEW_H
-
-#include <QtGui/qabstractitemview.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_LISTVIEW
-
-class QListViewPrivate;
-
-class Q_GUI_EXPORT QListView : public QAbstractItemView
-{
- Q_OBJECT
- Q_ENUMS(Movement Flow ResizeMode LayoutMode ViewMode)
- Q_PROPERTY(Movement movement READ movement WRITE setMovement)
- Q_PROPERTY(Flow flow READ flow WRITE setFlow)
- Q_PROPERTY(bool isWrapping READ isWrapping WRITE setWrapping)
- Q_PROPERTY(ResizeMode resizeMode READ resizeMode WRITE setResizeMode)
- Q_PROPERTY(LayoutMode layoutMode READ layoutMode WRITE setLayoutMode)
- Q_PROPERTY(int spacing READ spacing WRITE setSpacing)
- Q_PROPERTY(QSize gridSize READ gridSize WRITE setGridSize)
- Q_PROPERTY(ViewMode viewMode READ viewMode WRITE setViewMode)
- Q_PROPERTY(int modelColumn READ modelColumn WRITE setModelColumn)
- Q_PROPERTY(bool uniformItemSizes READ uniformItemSizes WRITE setUniformItemSizes)
- Q_PROPERTY(int batchSize READ batchSize WRITE setBatchSize)
- Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap)
- Q_PROPERTY(bool selectionRectVisible READ isSelectionRectVisible WRITE setSelectionRectVisible)
-
-public:
- enum Movement { Static, Free, Snap };
- enum Flow { LeftToRight, TopToBottom };
- enum ResizeMode { Fixed, Adjust };
- enum LayoutMode { SinglePass, Batched };
- enum ViewMode { ListMode, IconMode };
-
- explicit QListView(QWidget *parent = 0);
- ~QListView();
-
- void setMovement(Movement movement);
- Movement movement() const;
-
- void setFlow(Flow flow);
- Flow flow() const;
-
- void setWrapping(bool enable);
- bool isWrapping() const;
-
- void setResizeMode(ResizeMode mode);
- ResizeMode resizeMode() const;
-
- void setLayoutMode(LayoutMode mode);
- LayoutMode layoutMode() const;
-
- void setSpacing(int space);
- int spacing() const;
-
- void setBatchSize(int batchSize);
- int batchSize() const;
-
- void setGridSize(const QSize &size);
- QSize gridSize() const;
-
- void setViewMode(ViewMode mode);
- ViewMode viewMode() const;
-
- void clearPropertyFlags();
-
- bool isRowHidden(int row) const;
- void setRowHidden(int row, bool hide);
-
- void setModelColumn(int column);
- int modelColumn() const;
-
- void setUniformItemSizes(bool enable);
- bool uniformItemSizes() const;
-
- void setWordWrap(bool on);
- bool wordWrap() const;
-
- void setSelectionRectVisible(bool show);
- bool isSelectionRectVisible() const;
-
- QRect visualRect(const QModelIndex &index) const;
- void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible);
- QModelIndex indexAt(const QPoint &p) const;
-
- void doItemsLayout();
- void reset();
- void setRootIndex(const QModelIndex &index);
-
-Q_SIGNALS:
- void indexesMoved(const QModelIndexList &indexes);
-
-protected:
- QListView(QListViewPrivate &, QWidget *parent = 0);
-
- bool event(QEvent *e);
-
- void scrollContentsBy(int dx, int dy);
-
- void resizeContents(int width, int height);
- QSize contentsSize() const;
-
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void rowsInserted(const QModelIndex &parent, int start, int end);
- void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
-
- void mouseMoveEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
-
- void timerEvent(QTimerEvent *e);
- void resizeEvent(QResizeEvent *e);
-#ifndef QT_NO_DRAGANDDROP
- void dragMoveEvent(QDragMoveEvent *e);
- void dragLeaveEvent(QDragLeaveEvent *e);
- void dropEvent(QDropEvent *e);
- void startDrag(Qt::DropActions supportedActions);
-
- void internalDrop(QDropEvent *e);
- void internalDrag(Qt::DropActions supportedActions);
-#endif // QT_NO_DRAGANDDROP
-
- QStyleOptionViewItem viewOptions() const;
- void paintEvent(QPaintEvent *e);
-
- int horizontalOffset() const;
- int verticalOffset() const;
- QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
- QRect rectForIndex(const QModelIndex &index) const;
- void setPositionForIndex(const QPoint &position, const QModelIndex &index);
-
- void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command);
- QRegion visualRegionForSelection(const QItemSelection &selection) const;
- QModelIndexList selectedIndexes() const;
-
- void updateGeometries();
-
- bool isIndexHidden(const QModelIndex &index) const;
-
- void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
- void currentChanged(const QModelIndex &current, const QModelIndex &previous);
-
-private:
- friend class QAccessibleItemView;
- int visualIndex(const QModelIndex &index) const;
-
- Q_DECLARE_PRIVATE(QListView)
- Q_DISABLE_COPY(QListView)
-};
-
-#endif // QT_NO_LISTVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLISTVIEW_H
diff --git a/src/gui/itemviews/qlistview_p.h b/src/gui/itemviews/qlistview_p.h
deleted file mode 100644
index 84aaaca2de..0000000000
--- a/src/gui/itemviews/qlistview_p.h
+++ /dev/null
@@ -1,492 +0,0 @@
-/****************************************************************************
-**
-** 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 QLISTVIEW_P_H
-#define QLISTVIEW_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 "private/qabstractitemview_p.h"
-#include "qrubberband.h"
-#include "qbitarray.h"
-#include "qbsptree_p.h"
-#include <limits.h>
-#include <qscrollbar.h>
-
-#ifndef QT_NO_LISTVIEW
-
-QT_BEGIN_NAMESPACE
-
-class QListViewItem
-{
- friend class QListViewPrivate;
- friend class QListModeViewBase;
- friend class QIconModeViewBase;
-public:
- inline QListViewItem()
- : x(-1), y(-1), w(0), h(0), indexHint(-1), visited(0xffff) {}
- inline QListViewItem(const QListViewItem &other)
- : x(other.x), y(other.y), w(other.w), h(other.h),
- indexHint(other.indexHint), visited(other.visited) {}
- inline QListViewItem(QRect r, int i)
- : x(r.x()), y(r.y()), w(qMin(r.width(), SHRT_MAX)), h(qMin(r.height(), SHRT_MAX)),
- indexHint(i), visited(0xffff) {}
- inline bool operator==(const QListViewItem &other) const {
- return (x == other.x && y == other.y && w == other.w && h == other.h &&
- indexHint == other.indexHint); }
- inline bool operator!=(const QListViewItem &other) const
- { return !(*this == other); }
- inline bool isValid() const
- { return rect().isValid() && (indexHint > -1); }
- inline void invalidate()
- { x = -1; y = -1; w = 0; h = 0; }
- inline void resize(const QSize &size)
- { w = qMin(size.width(), SHRT_MAX); h = qMin(size.height(), SHRT_MAX); }
- inline void move(const QPoint &position)
- { x = position.x(); y = position.y(); }
- inline int width() const { return w; }
- inline int height() const { return h; }
-private:
- inline QRect rect() const
- { return QRect(x, y, w, h); }
- int x, y;
- short w, h;
- mutable int indexHint;
- uint visited;
-};
-
-struct QListViewLayoutInfo
-{
- QRect bounds;
- QSize grid;
- int spacing;
- int first;
- int last;
- bool wrap;
- QListView::Flow flow;
- int max;
-};
-
-class QListView;
-class QListViewPrivate;
-
-class QCommonListViewBase
-{
-public:
- inline QCommonListViewBase(QListView *q, QListViewPrivate *d) : dd(d), qq(q), batchStartRow(0), batchSavedDeltaSeg(0) {}
- virtual ~QCommonListViewBase() {}
-
- //common interface
- virtual int itemIndex(const QListViewItem &item) const = 0;
- virtual QListViewItem indexToListViewItem(const QModelIndex &index) const = 0;
- virtual bool doBatchedItemLayout(const QListViewLayoutInfo &info, int max) = 0;
- virtual void clear() = 0;
- virtual void setRowCount(int) = 0;
- virtual QVector<QModelIndex> intersectingSet(const QRect &area) const = 0;
- virtual void dataChanged(const QModelIndex &, const QModelIndex &) = 0;
-
- virtual int horizontalScrollToValue(int index, QListView::ScrollHint hint,
- bool leftOf, bool rightOf, const QRect &area, const QRect &rect) const;
- virtual int verticalScrollToValue(int index, QListView::ScrollHint hint,
- bool above, bool below, const QRect &area, const QRect &rect) const;
- virtual void scrollContentsBy(int dx, int dy, bool scrollElasticBand);
- virtual QRect mapToViewport(const QRect &rect) const {return rect;}
- virtual int horizontalOffset() const;
- virtual int verticalOffset() const { return verticalScrollBar()->value(); }
- virtual void updateHorizontalScrollBar(const QSize &step);
- virtual void updateVerticalScrollBar(const QSize &step);
- virtual void appendHiddenRow(int row);
- virtual void removeHiddenRow(int row);
- virtual void setPositionForIndex(const QPoint &, const QModelIndex &) { }
-
-#ifndef QT_NO_DRAGANDDROP
- virtual void paintDragDrop(QPainter *painter) = 0;
- virtual bool filterDragMoveEvent(QDragMoveEvent *) { return false; }
- virtual bool filterDragLeaveEvent(QDragLeaveEvent *) { return false; }
- virtual bool filterDropEvent(QDropEvent *) { return false; }
- virtual bool filterStartDrag(Qt::DropActions) { return false; }
-#endif
-
-
- //other inline members
- inline int spacing() const;
- inline bool isWrapping() const;
- inline QSize gridSize() const;
- inline QListView::Flow flow() const;
- inline QListView::Movement movement() const;
-
- inline QPoint offset() const;
- inline QPoint pressedPosition() const;
- inline bool uniformItemSizes() const;
- inline int column() const;
-
- inline QScrollBar *verticalScrollBar() const;
- inline QScrollBar *horizontalScrollBar() const;
- inline QListView::ScrollMode verticalScrollMode() const;
- inline QListView::ScrollMode horizontalScrollMode() const;
-
- inline QModelIndex modelIndex(int row) const;
- inline int rowCount() const;
-
- inline QStyleOptionViewItemV4 viewOptions() const;
- inline QWidget *viewport() const;
- inline QRect clipRect() const;
-
- inline QSize cachedItemSize() const;
- inline QRect viewItemRect(const QListViewItem &item) const;
- inline QSize itemSize(const QStyleOptionViewItemV2 &opt, const QModelIndex &idx) const;
- inline QAbstractItemDelegate *delegate(const QModelIndex &idx) const;
-
- inline bool isHidden(int row) const;
- inline int hiddenCount() const;
-
- inline bool isRightToLeft() const;
-
- QListViewPrivate *dd;
- QListView *qq;
- QSize contentsSize;
- int batchStartRow;
- int batchSavedDeltaSeg;
-};
-
-class QListModeViewBase : public QCommonListViewBase
-{
-public:
- QListModeViewBase(QListView *q, QListViewPrivate *d) : QCommonListViewBase(q, d) {}
-
- QVector<int> flowPositions;
- QVector<int> segmentPositions;
- QVector<int> segmentStartRows;
- QVector<int> segmentExtents;
- QVector<int> scrollValueMap;
-
- // used when laying out in batches
- int batchSavedPosition;
-
- //reimplementations
- int itemIndex(const QListViewItem &item) const { return item.indexHint; }
- QListViewItem indexToListViewItem(const QModelIndex &index) const;
- bool doBatchedItemLayout(const QListViewLayoutInfo &info, int max);
- void clear();
- void setRowCount(int rowCount) { flowPositions.resize(rowCount); }
- QVector<QModelIndex> intersectingSet(const QRect &area) const;
- void dataChanged(const QModelIndex &, const QModelIndex &);
-
- int horizontalScrollToValue(int index, QListView::ScrollHint hint,
- bool leftOf, bool rightOf,const QRect &area, const QRect &rect) const;
- int verticalScrollToValue(int index, QListView::ScrollHint hint,
- bool above, bool below, const QRect &area, const QRect &rect) const;
- void scrollContentsBy(int dx, int dy, bool scrollElasticBand);
- QRect mapToViewport(const QRect &rect) const;
- int horizontalOffset() const;
- int verticalOffset() const;
- void updateHorizontalScrollBar(const QSize &step);
- void updateVerticalScrollBar(const QSize &step);
-
-#ifndef QT_NO_DRAGANDDROP
- void paintDragDrop(QPainter *painter);
-
- // The next two methods are to be used on LefToRight flow only.
- // WARNING: Plenty of duplicated code from QAbstractItemView{,Private}.
- QAbstractItemView::DropIndicatorPosition position(const QPoint &pos, const QRect &rect, const QModelIndex &idx) const;
- void dragMoveEvent(QDragMoveEvent *e);
- bool dropOn(QDropEvent *event, int *row, int *col, QModelIndex *index);
-#endif
-
-private:
- QPoint initStaticLayout(const QListViewLayoutInfo &info);
- void doStaticLayout(const QListViewLayoutInfo &info);
- int perItemScrollToValue(int index, int value, int height,
- QAbstractItemView::ScrollHint hint,
- Qt::Orientation orientation, bool wrap, int extent) const;
- int perItemScrollingPageSteps(int length, int bounds, bool wrap) const;
-};
-
-class QIconModeViewBase : public QCommonListViewBase
-{
-public:
- QIconModeViewBase(QListView *q, QListViewPrivate *d) : QCommonListViewBase(q, d), interSectingVector(0) {}
-
- QBspTree tree;
- QVector<QListViewItem> items;
- QBitArray moved;
-
- QVector<QModelIndex> draggedItems; // indices to the tree.itemVector
- mutable QPoint draggedItemsPos;
-
- // used when laying out in batches
- QVector<QModelIndex> *interSectingVector; //used from within intersectingSet
-
- //reimplementations
- int itemIndex(const QListViewItem &item) const;
- QListViewItem indexToListViewItem(const QModelIndex &index) const;
- bool doBatchedItemLayout(const QListViewLayoutInfo &info, int max);
- void clear();
- void setRowCount(int rowCount);
- QVector<QModelIndex> intersectingSet(const QRect &area) const;
-
- void scrollContentsBy(int dx, int dy, bool scrollElasticBand);
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void appendHiddenRow(int row);
- void removeHiddenRow(int row);
- void setPositionForIndex(const QPoint &position, const QModelIndex &index);
-
-#ifndef QT_NO_DRAGANDDROP
- void paintDragDrop(QPainter *painter);
- bool filterDragMoveEvent(QDragMoveEvent *);
- bool filterDragLeaveEvent(QDragLeaveEvent *);
- bool filterDropEvent(QDropEvent *e);
- bool filterStartDrag(Qt::DropActions);
-#endif
-
-private:
- void initBspTree(const QSize &contents);
- QPoint initDynamicLayout(const QListViewLayoutInfo &info);
- void doDynamicLayout(const QListViewLayoutInfo &info);
- static void addLeaf(QVector<int> &leaf, const QRect &area,
- uint visited, QBspTree::Data data);
- QRect itemsRect(const QVector<QModelIndex> &indexes) const;
- QRect draggedItemsRect() const;
- QPoint snapToGrid(const QPoint &pos) const;
- void updateContentsSize();
- QPoint draggedItemsDelta() const;
- void drawItems(QPainter *painter, const QVector<QModelIndex> &indexes) const;
- void moveItem(int index, const QPoint &dest);
-
-};
-
-class QListViewPrivate: public QAbstractItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QListView)
-public:
- QListViewPrivate();
- ~QListViewPrivate();
-
- void clear();
- void prepareItemsLayout();
-
- bool doItemsLayout(int num);
-
- inline QVector<QModelIndex> intersectingSet(const QRect &area, bool doLayout = true) const {
- if (doLayout) executePostedLayout();
- QRect a = (q_func()->isRightToLeft() ? flipX(area.normalized()) : area.normalized());
- return commonListView->intersectingSet(a);
- }
-
- inline void resetBatchStartRow() { commonListView->batchStartRow = 0; }
- inline int batchStartRow() const { return commonListView->batchStartRow; }
- inline QSize contentsSize() const { return commonListView->contentsSize; }
- inline void setContentsSize(int w, int h) { commonListView->contentsSize = QSize(w, h); }
-
- inline int flipX(int x) const
- { return qMax(viewport->width(), contentsSize().width()) - x; }
- inline QPoint flipX(const QPoint &p) const
- { return QPoint(flipX(p.x()), p.y()); }
- inline QRect flipX(const QRect &r) const
- { return QRect(flipX(r.x()) - r.width(), r.y(), r.width(), r.height()); }
- inline QRect viewItemRect(const QListViewItem &item) const
- { if (q_func()->isRightToLeft()) return flipX(item.rect()); return item.rect(); }
-
- QListViewItem indexToListViewItem(const QModelIndex &index) const;
- inline QModelIndex listViewItemToIndex(const QListViewItem &item) const
- { return model->index(commonListView->itemIndex(item), column, root); }
-
- QRect rectForIndex(const QModelIndex &index) const
- {
- if (!isIndexValid(index) || index.parent() != root || index.column() != column || isHidden(index.row()))
- return QRect();
- executePostedLayout();
- return viewItemRect(indexToListViewItem(index));
- }
-
- void viewUpdateGeometries() { q_func()->updateGeometries(); }
-
-
- QRect mapToViewport(const QRect &rect, bool extend = true) const;
-
- QModelIndex closestIndex(const QRect &target, const QVector<QModelIndex> &candidates) const;
- QSize itemSize(const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
- bool selectionAllowed(const QModelIndex &index) const
- { if (viewMode == QListView::ListMode && !showElasticBand) return index.isValid(); return true; }
-
- int horizontalScrollToValue(const QModelIndex &index, const QRect &rect, QListView::ScrollHint hint) const;
- int verticalScrollToValue(const QModelIndex &index, const QRect &rect, QListView::ScrollHint hint) const;
-
- QItemSelection selection(const QRect &rect) const;
- void selectAll(QItemSelectionModel::SelectionFlags command);
-
-#ifndef QT_NO_DRAGANDDROP
- virtual QAbstractItemView::DropIndicatorPosition position(const QPoint &pos, const QRect &rect, const QModelIndex &idx) const;
- bool dropOn(QDropEvent *event, int *row, int *col, QModelIndex *index);
-#endif
-
- inline void setGridSize(const QSize &size) { grid = size; }
- inline QSize gridSize() const { return grid; }
- inline void setWrapping(bool b) { wrap = b; }
- inline bool isWrapping() const { return wrap; }
- inline void setSpacing(int s) { space = s; }
- inline int spacing() const { return space; }
- inline void setSelectionRectVisible(bool visible) { showElasticBand = visible; }
- inline bool isSelectionRectVisible() const { return showElasticBand; }
-
- inline QModelIndex modelIndex(int row) const { return model->index(row, column, root); }
- inline bool isHidden(int row) const {
- QModelIndex idx = model->index(row, 0, root);
- return isPersistent(idx) && hiddenRows.contains(idx);
- }
- inline bool isHiddenOrDisabled(int row) const { return isHidden(row) || !isIndexEnabled(modelIndex(row)); }
-
- inline void removeCurrentAndDisabled(QVector<QModelIndex> *indexes, const QModelIndex &current) const {
- QVector<QModelIndex>::iterator it = indexes->begin();
- while (it != indexes->end()) {
- if (!isIndexEnabled(*it) || (*it) == current)
- indexes->erase(it);
- else
- ++it;
- }
- }
-
- void scrollElasticBandBy(int dx, int dy);
-
- QItemViewPaintPairs draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const;
-
- void emitIndexesMoved(const QModelIndexList &indexes) { emit q_func()->indexesMoved(indexes); }
-
-
- QCommonListViewBase *commonListView;
-
- // ### FIXME: see if we can move the members into the dynamic/static classes
-
- bool wrap;
- int space;
- QSize grid;
-
- QListView::Flow flow;
- QListView::Movement movement;
- QListView::ResizeMode resizeMode;
- QListView::LayoutMode layoutMode;
- QListView::ViewMode viewMode;
-
- // the properties controlling the
- // icon- or list-view modes
- enum ModeProperties {
- Wrap = 1,
- Spacing = 2,
- GridSize = 4,
- Flow = 8,
- Movement = 16,
- ResizeMode = 32,
- SelectionRectVisible = 64
- };
-
- uint modeProperties : 8;
-
- QRect layoutBounds;
-
- // timers
- QBasicTimer batchLayoutTimer;
-
- // used for hidden items
- QSet<QPersistentModelIndex> hiddenRows;
-
- int column;
- bool uniformItemSizes;
- mutable QSize cachedItemSize;
- int batchSize;
-
- QRect elasticBand;
- bool showElasticBand;
-};
-
-// inline implementations
-
-inline int QCommonListViewBase::spacing() const { return dd->spacing(); }
-inline bool QCommonListViewBase::isWrapping() const { return dd->isWrapping(); }
-inline QSize QCommonListViewBase::gridSize() const { return dd->gridSize(); }
-inline QListView::Flow QCommonListViewBase::flow() const { return dd->flow; }
-inline QListView::Movement QCommonListViewBase::movement() const { return dd->movement; }
-
-inline QPoint QCommonListViewBase::offset() const { return dd->offset(); }
-inline QPoint QCommonListViewBase::pressedPosition() const { return dd->pressedPosition; }
-inline bool QCommonListViewBase::uniformItemSizes() const { return dd->uniformItemSizes; }
-inline int QCommonListViewBase::column() const { return dd->column; }
-
-inline QScrollBar *QCommonListViewBase::verticalScrollBar() const { return qq->verticalScrollBar(); }
-inline QScrollBar *QCommonListViewBase::horizontalScrollBar() const { return qq->horizontalScrollBar(); }
-inline QListView::ScrollMode QCommonListViewBase::verticalScrollMode() const { return qq->verticalScrollMode(); }
-inline QListView::ScrollMode QCommonListViewBase::horizontalScrollMode() const { return qq->horizontalScrollMode(); }
-
-inline QModelIndex QCommonListViewBase::modelIndex(int row) const
- { return dd->model->index(row, dd->column, dd->root); }
-inline int QCommonListViewBase::rowCount() const { return dd->model->rowCount(dd->root); }
-
-inline QStyleOptionViewItemV4 QCommonListViewBase::viewOptions() const { return dd->viewOptionsV4(); }
-inline QWidget *QCommonListViewBase::viewport() const { return dd->viewport; }
-inline QRect QCommonListViewBase::clipRect() const { return dd->clipRect(); }
-
-inline QSize QCommonListViewBase::cachedItemSize() const { return dd->cachedItemSize; }
-inline QRect QCommonListViewBase::viewItemRect(const QListViewItem &item) const { return dd->viewItemRect(item); }
-inline QSize QCommonListViewBase::itemSize(const QStyleOptionViewItemV2 &opt, const QModelIndex &idx) const
- { return dd->itemSize(opt, idx); }
-
-inline QAbstractItemDelegate *QCommonListViewBase::delegate(const QModelIndex &idx) const
- { return dd->delegateForIndex(idx); }
-
-inline bool QCommonListViewBase::isHidden(int row) const { return dd->isHidden(row); }
-inline int QCommonListViewBase::hiddenCount() const { return dd->hiddenRows.count(); }
-
-inline bool QCommonListViewBase::isRightToLeft() const { return qq->isRightToLeft(); }
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_LISTVIEW
-
-#endif // QLISTVIEW_P_H
diff --git a/src/gui/itemviews/qlistwidget.cpp b/src/gui/itemviews/qlistwidget.cpp
deleted file mode 100644
index 61a935fdc9..0000000000
--- a/src/gui/itemviews/qlistwidget.cpp
+++ /dev/null
@@ -1,1914 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlistwidget.h"
-
-#ifndef QT_NO_LISTWIDGET
-#include <qitemdelegate.h>
-#include <private/qlistview_p.h>
-#include <private/qwidgetitemdata_p.h>
-#include <private/qlistwidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// workaround for VC++ 6.0 linker bug (?)
-typedef bool(*LessThan)(const QPair<QListWidgetItem*,int>&,const QPair<QListWidgetItem*,int>&);
-
-class QListWidgetMimeData : public QMimeData
-{
- Q_OBJECT
-public:
- QList<QListWidgetItem*> items;
-};
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qlistwidget.moc"
-QT_END_INCLUDE_NAMESPACE
-
-QListModel::QListModel(QListWidget *parent)
- : QAbstractListModel(parent)
-{
-}
-
-QListModel::~QListModel()
-{
- clear();
-}
-
-void QListModel::clear()
-{
- for (int i = 0; i < items.count(); ++i) {
- if (items.at(i)) {
- items.at(i)->d->theid = -1;
- items.at(i)->view = 0;
- delete items.at(i);
- }
- }
- items.clear();
- reset();
-}
-
-QListWidgetItem *QListModel::at(int row) const
-{
- return items.value(row);
-}
-
-void QListModel::remove(QListWidgetItem *item)
-{
- if (!item)
- return;
- int row = items.indexOf(item); // ### use index(item) - it's faster
- Q_ASSERT(row != -1);
- beginRemoveRows(QModelIndex(), row, row);
- items.at(row)->d->theid = -1;
- items.at(row)->view = 0;
- items.removeAt(row);
- endRemoveRows();
-}
-
-void QListModel::insert(int row, QListWidgetItem *item)
-{
- if (!item)
- return;
-
- item->view = qobject_cast<QListWidget*>(QObject::parent());
- if (item->view && item->view->isSortingEnabled()) {
- // sorted insertion
- QList<QListWidgetItem*>::iterator it;
- it = sortedInsertionIterator(items.begin(), items.end(),
- item->view->sortOrder(), item);
- row = qMax(it - items.begin(), 0);
- } else {
- if (row < 0)
- row = 0;
- else if (row > items.count())
- row = items.count();
- }
- beginInsertRows(QModelIndex(), row, row);
- items.insert(row, item);
- item->d->theid = row;
- endInsertRows();
-}
-
-void QListModel::insert(int row, const QStringList &labels)
-{
- const int count = labels.count();
- if (count <= 0)
- return;
- QListWidget *view = qobject_cast<QListWidget*>(QObject::parent());
- if (view && view->isSortingEnabled()) {
- // sorted insertion
- for (int i = 0; i < count; ++i) {
- QListWidgetItem *item = new QListWidgetItem(labels.at(i));
- insert(row, item);
- }
- } else {
- if (row < 0)
- row = 0;
- else if (row > items.count())
- row = items.count();
- beginInsertRows(QModelIndex(), row, row + count - 1);
- for (int i = 0; i < count; ++i) {
- QListWidgetItem *item = new QListWidgetItem(labels.at(i));
- item->d->theid = row;
- item->view = qobject_cast<QListWidget*>(QObject::parent());
- items.insert(row++, item);
- }
- endInsertRows();
- }
-}
-
-QListWidgetItem *QListModel::take(int row)
-{
- if (row < 0 || row >= items.count())
- return 0;
-
- beginRemoveRows(QModelIndex(), row, row);
- items.at(row)->d->theid = -1;
- items.at(row)->view = 0;
- QListWidgetItem *item = items.takeAt(row);
- endRemoveRows();
- return item;
-}
-
-void QListModel::move(int srcRow, int dstRow)
-{
- if (srcRow == dstRow
- || srcRow < 0 || srcRow >= items.count()
- || dstRow < 0 || dstRow > items.count())
- return;
-
- if (!beginMoveRows(QModelIndex(), srcRow, srcRow, QModelIndex(), dstRow))
- return;
- if (srcRow < dstRow)
- --dstRow;
- items.move(srcRow, dstRow);
- endMoveRows();
-}
-
-int QListModel::rowCount(const QModelIndex &parent) const
-{
- return parent.isValid() ? 0 : items.count();
-}
-
-QModelIndex QListModel::index(QListWidgetItem *item) const
-{
- if (!item || !item->view || static_cast<const QListModel *>(item->view->model()) != this
- || items.isEmpty())
- return QModelIndex();
- int row;
- const int theid = item->d->theid;
- if (theid >= 0 && theid < items.count() && items.at(theid) == item) {
- row = theid;
- } else { // we need to search for the item
- row = items.lastIndexOf(item); // lastIndexOf is an optimization in favor of indexOf
- if (row == -1) // not found
- return QModelIndex();
- item->d->theid = row;
- }
- return createIndex(row, 0, item);
-}
-
-QModelIndex QListModel::index(int row, int column, const QModelIndex &parent) const
-{
- if (hasIndex(row, column, parent))
- return createIndex(row, column, items.at(row));
- return QModelIndex();
-}
-
-QVariant QListModel::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid() || index.row() >= items.count())
- return QVariant();
- return items.at(index.row())->data(role);
-}
-
-bool QListModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (!index.isValid() || index.row() >= items.count())
- return false;
- items.at(index.row())->setData(role, value);
- return true;
-}
-
-QMap<int, QVariant> QListModel::itemData(const QModelIndex &index) const
-{
- QMap<int, QVariant> roles;
- if (!index.isValid() || index.row() >= items.count())
- return roles;
- QListWidgetItem *itm = items.at(index.row());
- for (int i = 0; i < itm->d->values.count(); ++i) {
- roles.insert(itm->d->values.at(i).role,
- itm->d->values.at(i).value);
- }
- return roles;
-}
-
-bool QListModel::insertRows(int row, int count, const QModelIndex &parent)
-{
- if (count < 1 || row < 0 || row > rowCount() || parent.isValid())
- return false;
-
- beginInsertRows(QModelIndex(), row, row + count - 1);
- QListWidget *view = qobject_cast<QListWidget*>(QObject::parent());
- QListWidgetItem *itm = 0;
-
- for (int r = row; r < row + count; ++r) {
- itm = new QListWidgetItem;
- itm->view = view;
- itm->d->theid = r;
- items.insert(r, itm);
- }
-
- endInsertRows();
- return true;
-}
-
-bool QListModel::removeRows(int row, int count, const QModelIndex &parent)
-{
- if (count < 1 || row < 0 || (row + count) > rowCount() || parent.isValid())
- return false;
-
- beginRemoveRows(QModelIndex(), row, row + count - 1);
- QListWidgetItem *itm = 0;
- for (int r = row; r < row + count; ++r) {
- itm = items.takeAt(row);
- itm->view = 0;
- itm->d->theid = -1;
- delete itm;
- }
- endRemoveRows();
- return true;
-}
-
-Qt::ItemFlags QListModel::flags(const QModelIndex &index) const
-{
- if (!index.isValid() || index.row() >= items.count() || index.model() != this)
- return Qt::ItemIsDropEnabled; // we allow drops outside the items
- return items.at(index.row())->flags();
-}
-
-void QListModel::sort(int column, Qt::SortOrder order)
-{
- if (column != 0)
- return;
-
- emit layoutAboutToBeChanged();
-
- QVector < QPair<QListWidgetItem*,int> > sorting(items.count());
- for (int i = 0; i < items.count(); ++i) {
- QListWidgetItem *item = items.at(i);
- sorting[i].first = item;
- sorting[i].second = i;
- }
-
- LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- qSort(sorting.begin(), sorting.end(), compare);
- QModelIndexList fromIndexes;
- QModelIndexList toIndexes;
- for (int r = 0; r < sorting.count(); ++r) {
- QListWidgetItem *item = sorting.at(r).first;
- toIndexes.append(createIndex(r, 0, item));
- fromIndexes.append(createIndex(sorting.at(r).second, 0, sorting.at(r).first));
- items[r] = sorting.at(r).first;
- }
- changePersistentIndexList(fromIndexes, toIndexes);
-
- emit layoutChanged();
-}
-
-/**
- * This function assumes that all items in the model except the items that are between
- * (inclusive) start and end are sorted.
- * With these assumptions, this function can ensure that the model is sorted in a
- * much more efficient way than doing a naive 'sort everything'.
- * (provided that the range is relatively small compared to the total number of items)
- */
-void QListModel::ensureSorted(int column, Qt::SortOrder order, int start, int end)
-{
- if (column != 0)
- return;
-
- int count = end - start + 1;
- QVector < QPair<QListWidgetItem*,int> > sorting(count);
- for (int i = 0; i < count; ++i) {
- sorting[i].first = items.at(start + i);
- sorting[i].second = start + i;
- }
-
- LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- qSort(sorting.begin(), sorting.end(), compare);
-
- QModelIndexList oldPersistentIndexes = persistentIndexList();
- QModelIndexList newPersistentIndexes = oldPersistentIndexes;
- QList<QListWidgetItem*> tmp = items;
- QList<QListWidgetItem*>::iterator lit = tmp.begin();
- bool changed = false;
- for (int i = 0; i < count; ++i) {
- int oldRow = sorting.at(i).second;
- QListWidgetItem *item = tmp.takeAt(oldRow);
- lit = sortedInsertionIterator(lit, tmp.end(), order, item);
- int newRow = qMax(lit - tmp.begin(), 0);
- lit = tmp.insert(lit, item);
- if (newRow != oldRow) {
- changed = true;
- for (int j = i + 1; j < count; ++j) {
- int otherRow = sorting.at(j).second;
- if (oldRow < otherRow && newRow >= otherRow)
- --sorting[j].second;
- else if (oldRow > otherRow && newRow <= otherRow)
- ++sorting[j].second;
- }
- for (int k = 0; k < newPersistentIndexes.count(); ++k) {
- QModelIndex pi = newPersistentIndexes.at(k);
- int oldPersistentRow = pi.row();
- int newPersistentRow = oldPersistentRow;
- if (oldPersistentRow == oldRow)
- newPersistentRow = newRow;
- else if (oldRow < oldPersistentRow && newRow >= oldPersistentRow)
- newPersistentRow = oldPersistentRow - 1;
- else if (oldRow > oldPersistentRow && newRow <= oldPersistentRow)
- newPersistentRow = oldPersistentRow + 1;
- if (newPersistentRow != oldPersistentRow)
- newPersistentIndexes[k] = createIndex(newPersistentRow,
- pi.column(), pi.internalPointer());
- }
- }
- }
-
- if (changed) {
- emit layoutAboutToBeChanged();
- items = tmp;
- changePersistentIndexList(oldPersistentIndexes, newPersistentIndexes);
- emit layoutChanged();
- }
-}
-
-bool QListModel::itemLessThan(const QPair<QListWidgetItem*,int> &left,
- const QPair<QListWidgetItem*,int> &right)
-{
- return (*left.first) < (*right.first);
-}
-
-bool QListModel::itemGreaterThan(const QPair<QListWidgetItem*,int> &left,
- const QPair<QListWidgetItem*,int> &right)
-{
- return (*right.first) < (*left.first);
-}
-
-QList<QListWidgetItem*>::iterator QListModel::sortedInsertionIterator(
- const QList<QListWidgetItem*>::iterator &begin,
- const QList<QListWidgetItem*>::iterator &end,
- Qt::SortOrder order, QListWidgetItem *item)
-{
- if (order == Qt::AscendingOrder)
- return qLowerBound(begin, end, item, QListModelLessThan());
- return qLowerBound(begin, end, item, QListModelGreaterThan());
-}
-
-void QListModel::itemChanged(QListWidgetItem *item)
-{
- QModelIndex idx = index(item);
- emit dataChanged(idx, idx);
-}
-
-QStringList QListModel::mimeTypes() const
-{
- const QListWidget *view = qobject_cast<const QListWidget*>(QObject::parent());
- return view->mimeTypes();
-}
-
-QMimeData *QListModel::internalMimeData() const
-{
- return QAbstractItemModel::mimeData(cachedIndexes);
-}
-
-QMimeData *QListModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QListWidgetItem*> itemlist;
- for (int i = 0; i < indexes.count(); ++i)
- itemlist << at(indexes.at(i).row());
- const QListWidget *view = qobject_cast<const QListWidget*>(QObject::parent());
-
- cachedIndexes = indexes;
- QMimeData *mimeData = view->mimeData(itemlist);
- cachedIndexes.clear();
- return mimeData;
-}
-
-#ifndef QT_NO_DRAGANDDROP
-bool QListModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &index)
-{
- Q_UNUSED(column);
- QListWidget *view = qobject_cast<QListWidget*>(QObject::parent());
- if (index.isValid())
- row = index.row();
- else if (row == -1)
- row = items.count();
-
- return view->dropMimeData(row, data, action);
-}
-
-Qt::DropActions QListModel::supportedDropActions() const
-{
- const QListWidget *view = qobject_cast<const QListWidget*>(QObject::parent());
- return view->supportedDropActions();
-}
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- \class QListWidgetItem
- \brief The QListWidgetItem class provides an item for use with the
- QListWidget item view class.
-
- \ingroup model-view
-
- A QListWidgetItem represents a single item in a QListWidget. Each item can
- hold several pieces of information, and will display them appropriately.
-
- The item view convenience classes use a classic item-based interface rather
- than a pure model/view approach. For a more flexible list view widget,
- consider using the QListView class with a standard model.
-
- List items can be inserted automatically into a list, when they are
- constructed, by specifying the list widget:
-
- \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 2
-
- Alternatively, list items can also be created without a parent widget, and
- later inserted into a list using QListWidget::insertItem().
-
- List items are typically used to display text() and an icon(). These are
- set with the setText() and setIcon() functions. The appearance of the text
- can be customized with setFont(), setForeground(), and setBackground().
- Text in list items can be aligned using the setTextAlignment() function.
- Tooltips, status tips and "What's This?" help can be added to list items
- with setToolTip(), setStatusTip(), and setWhatsThis().
-
- By default, items are enabled, selectable, checkable, and can be the source
- of drag and drop operations.
-
- Each item's flags can be changed by calling setFlags() with the appropriate
- value (see Qt::ItemFlags). Checkable items can be checked, unchecked and
- partially checked with the setCheckState() function. The corresponding
- checkState() function indicates the item's current check state.
-
- The isHidden() function can be used to determine whether the item is
- hidden. To hide an item, use setHidden().
-
-
- \section1 Subclassing
-
- When subclassing QListWidgetItem to provide custom items, it is possible to
- define new types for them enabling them to be distinguished from standard
- items. For subclasses that require this feature, ensure that you call the
- base class constructor with a new type value equal to or greater than
- \l UserType, within \e your constructor.
-
- \sa QListWidget, {Model/View Programming}, QTreeWidgetItem, QTableWidgetItem
-*/
-
-/*!
- \enum QListWidgetItem::ItemType
-
- This enum describes the types that are used to describe list widget items.
-
- \value Type The default type for list widget items.
- \value UserType The minimum value for custom types. Values below UserType are
- reserved by Qt.
-
- You can define new user types in QListWidgetItem subclasses to ensure that
- custom items are treated specially.
-
- \sa type()
-*/
-
-/*!
- \fn int QListWidgetItem::type() const
-
- Returns the type passed to the QListWidgetItem constructor.
-*/
-
-/*!
- \fn QListWidget *QListWidgetItem::listWidget() const
-
- Returns the list widget containing the item.
-*/
-
-/*!
- \fn void QListWidgetItem::setSelected(bool select)
- \since 4.2
-
- Sets the selected state of the item to \a select.
-
- \sa isSelected()
-*/
-
-/*!
- \fn bool QListWidgetItem::isSelected() const
- \since 4.2
-
- Returns true if the item is selected; otherwise returns false.
-
- \sa setSelected()
-*/
-
-/*!
- \fn void QListWidgetItem::setHidden(bool hide)
- \since 4.2
-
- Hides the item if \a hide is true; otherwise shows the item.
-
- \sa isHidden()
-*/
-
-/*!
- \fn bool QListWidgetItem::isHidden() const
- \since 4.2
-
- Returns true if the item is hidden; otherwise returns false.
-
- \sa setHidden()
-*/
-
-/*!
- \fn QListWidgetItem::QListWidgetItem(QListWidget *parent, int type)
-
- Constructs an empty list widget item of the specified \a type with the
- given \a parent. If \a parent is not specified, the item will need to be
- inserted into a list widget with QListWidget::insertItem().
-
- This constructor inserts the item into the model of the parent that is
- passed to the constructor. If the model is sorted then the behavior of the
- insert is undetermined since the model will call the \c '<' operator method
- on the item which, at this point, is not yet constructed. To avoid the
- undetermined behavior, we recommend not to specify the parent and use
- QListWidget::insertItem() instead.
-
- \sa type()
-*/
-QListWidgetItem::QListWidgetItem(QListWidget *view, int type)
- : rtti(type), view(view), d(new QListWidgetItemPrivate(this)),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled)
-{
- if (QListModel *model = (view ? qobject_cast<QListModel*>(view->model()) : 0))
- model->insert(model->rowCount(), this);
-}
-
-/*!
- \fn QListWidgetItem::QListWidgetItem(const QString &text, QListWidget *parent, int type)
-
- Constructs an empty list widget item of the specified \a type with the
- given \a text and \a parent. If the parent is not specified, the item will
- need to be inserted into a list widget with QListWidget::insertItem().
-
- This constructor inserts the item into the model of the parent that is
- passed to the constructor. If the model is sorted then the behavior of the
- insert is undetermined since the model will call the \c '<' operator method
- on the item which, at this point, is not yet constructed. To avoid the
- undetermined behavior, we recommend not to specify the parent and use
- QListWidget::insertItem() instead.
-
- \sa type()
-*/
-QListWidgetItem::QListWidgetItem(const QString &text, QListWidget *view, int type)
- : rtti(type), view(0), d(new QListWidgetItemPrivate(this)),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled)
-{
- setData(Qt::DisplayRole, text);
- this->view = view;
- if (QListModel *model = (view ? qobject_cast<QListModel*>(view->model()) : 0))
- model->insert(model->rowCount(), this);
-}
-
-/*!
- \fn QListWidgetItem::QListWidgetItem(const QIcon &icon, const QString &text, QListWidget *parent, int type)
-
- Constructs an empty list widget item of the specified \a type with the
- given \a icon, \a text and \a parent. If the parent is not specified, the
- item will need to be inserted into a list widget with
- QListWidget::insertItem().
-
- This constructor inserts the item into the model of the parent that is
- passed to the constructor. If the model is sorted then the behavior of the
- insert is undetermined since the model will call the \c '<' operator method
- on the item which, at this point, is not yet constructed. To avoid the
- undetermined behavior, we recommend not to specify the parent and use
- QListWidget::insertItem() instead.
-
- \sa type()
-*/
-QListWidgetItem::QListWidgetItem(const QIcon &icon,const QString &text,
- QListWidget *view, int type)
- : rtti(type), view(0), d(new QListWidgetItemPrivate(this)),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled)
-{
- setData(Qt::DisplayRole, text);
- setData(Qt::DecorationRole, icon);
- this->view = view;
- if (QListModel *model = (view ? qobject_cast<QListModel*>(view->model()) : 0))
- model->insert(model->rowCount(), this);
-}
-
-/*!
- Destroys the list item.
-*/
-QListWidgetItem::~QListWidgetItem()
-{
- if (QListModel *model = (view ? qobject_cast<QListModel*>(view->model()) : 0))
- model->remove(this);
- delete d;
-}
-
-/*!
- Creates an exact copy of the item.
-*/
-QListWidgetItem *QListWidgetItem::clone() const
-{
- return new QListWidgetItem(*this);
-}
-
-/*!
- Sets the data for a given \a role to the given \a value. Reimplement this
- function if you need extra roles or special behavior for certain roles.
-
- \sa Qt::ItemDataRole, data()
-*/
-void QListWidgetItem::setData(int role, const QVariant &value)
-{
- bool found = false;
- role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < d->values.count(); ++i) {
- if (d->values.at(i).role == role) {
- if (d->values.at(i).value == value)
- return;
- d->values[i].value = value;
- found = true;
- break;
- }
- }
- if (!found)
- d->values.append(QWidgetItemData(role, value));
- if (QListModel *model = (view ? qobject_cast<QListModel*>(view->model()) : 0))
- model->itemChanged(this);
-}
-
-/*!
- Returns the item's data for a given \a role. Reimplement this function if
- you need extra roles or special behavior for certain roles.
-
- \sa Qt::ItemDataRole, setData()
-*/
-QVariant QListWidgetItem::data(int role) const
-{
- role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < d->values.count(); ++i)
- if (d->values.at(i).role == role)
- return d->values.at(i).value;
- return QVariant();
-}
-
-/*!
- Returns true if this item's text is less then \a other item's text;
- otherwise returns false.
-*/
-bool QListWidgetItem::operator<(const QListWidgetItem &other) const
-{
- const QVariant v1 = data(Qt::DisplayRole), v2 = other.data(Qt::DisplayRole);
- return QAbstractItemModelPrivate::variantLessThan(v1, v2);
-}
-
-#ifndef QT_NO_DATASTREAM
-
-/*!
- Reads the item from stream \a in.
-
- \sa write()
-*/
-void QListWidgetItem::read(QDataStream &in)
-{
- in >> d->values;
-}
-
-/*!
- Writes the item to stream \a out.
-
- \sa read()
-*/
-void QListWidgetItem::write(QDataStream &out) const
-{
- out << d->values;
-}
-#endif // QT_NO_DATASTREAM
-
-/*!
- \since 4.1
-
- Constructs a copy of \a other. Note that type() and listWidget() are not
- copied.
-
- This function is useful when reimplementing clone().
-
- \sa data(), flags()
-*/
-QListWidgetItem::QListWidgetItem(const QListWidgetItem &other)
- : rtti(Type), view(0),
- d(new QListWidgetItemPrivate(this)),
- itemFlags(other.itemFlags)
-{
- d->values = other.d->values;
-}
-
-/*!
- Assigns \a other's data and flags to this item. Note that type() and
- listWidget() are not copied.
-
- This function is useful when reimplementing clone().
-
- \sa data(), flags()
-*/
-QListWidgetItem &QListWidgetItem::operator=(const QListWidgetItem &other)
-{
- d->values = other.d->values;
- itemFlags = other.itemFlags;
- return *this;
-}
-
-#ifndef QT_NO_DATASTREAM
-
-/*!
- \relates QListWidgetItem
-
- Writes the list widget item \a item to stream \a out.
-
- This operator uses QListWidgetItem::write().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator<<(QDataStream &out, const QListWidgetItem &item)
-{
- item.write(out);
- return out;
-}
-
-/*!
- \relates QListWidgetItem
-
- Reads a list widget item from stream \a in into \a item.
-
- This operator uses QListWidgetItem::read().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator>>(QDataStream &in, QListWidgetItem &item)
-{
- item.read(in);
- return in;
-}
-
-#endif // QT_NO_DATASTREAM
-
-/*!
- \fn Qt::ItemFlags QListWidgetItem::flags() const
-
- Returns the item flags for this item (see \l{Qt::ItemFlags}).
-*/
-
-/*!
- \fn QString QListWidgetItem::text() const
-
- Returns the list item's text.
-
- \sa setText()
-*/
-
-/*!
- \fn QIcon QListWidgetItem::icon() const
-
- Returns the list item's icon.
-
- \sa setIcon(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn QString QListWidgetItem::statusTip() const
-
- Returns the list item's status tip.
-
- \sa setStatusTip()
-*/
-
-/*!
- \fn QString QListWidgetItem::toolTip() const
-
- Returns the list item's tooltip.
-
- \sa setToolTip() statusTip() whatsThis()
-*/
-
-/*!
- \fn QString QListWidgetItem::whatsThis() const
-
- Returns the list item's "What's This?" help text.
-
- \sa setWhatsThis() statusTip() toolTip()
-*/
-
-/*!
- \fn QFont QListWidgetItem::font() const
-
- Returns the font used to display this list item's text.
-*/
-
-/*!
- \fn int QListWidgetItem::textAlignment() const
-
- Returns the text alignment for the list item.
-
- \sa Qt::AlignmentFlag
-*/
-
-/*!
- \fn QColor QListWidgetItem::backgroundColor() const
- \obsolete
-
- This function is deprecated. Use background() instead.
-*/
-
-/*!
- \fn QBrush QListWidgetItem::background() const
- \since 4.2
-
- Returns the brush used to display the list item's background.
-
- \sa setBackground() foreground()
-*/
-
-/*!
- \fn QColor QListWidgetItem::textColor() const
- \obsolete
-
- Returns the color used to display the list item's text.
-
- This function is deprecated. Use foreground() instead.
-*/
-
-/*!
- \fn QBrush QListWidgetItem::foreground() const
- \since 4.2
-
- Returns the brush used to display the list item's foreground (e.g. text).
-
- \sa setForeground() background()
-*/
-
-/*!
- \fn Qt::CheckState QListWidgetItem::checkState() const
-
- Returns the checked state of the list item (see \l{Qt::CheckState}).
-
- \sa flags()
-*/
-
-/*!
- \fn QSize QListWidgetItem::sizeHint() const
- \since 4.1
-
- Returns the size hint set for the list item.
-*/
-
-/*!
- \fn void QListWidgetItem::setSizeHint(const QSize &size)
- \since 4.1
-
- Sets the size hint for the list item to be \a size. If no size hint is set,
- the item delegate will compute the size hint based on the item data.
-*/
-
-/*!
- \fn void QListWidgetItem::setFlags(Qt::ItemFlags flags)
-
- Sets the item flags for the list item to \a flags.
-
- \sa Qt::ItemFlags
-*/
-void QListWidgetItem::setFlags(Qt::ItemFlags aflags) {
- itemFlags = aflags;
- if (QListModel *model = (view ? qobject_cast<QListModel*>(view->model()) : 0))
- model->itemChanged(this);
-}
-
-
-/*!
- \fn void QListWidgetItem::setText(const QString &text)
-
- Sets the text for the list widget item's to the given \a text.
-
- \sa text()
-*/
-
-/*!
- \fn void QListWidgetItem::setIcon(const QIcon &icon)
-
- Sets the icon for the list item to the given \a icon.
-
- \sa icon(), text(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn void QListWidgetItem::setStatusTip(const QString &statusTip)
-
- Sets the status tip for the list item to the text specified by
- \a statusTip. QListWidget mouseTracking needs to be enabled for this
- feature to work.
-
- \sa statusTip(), setToolTip(), setWhatsThis(), QWidget::setMouseTracking()
-*/
-
-/*!
- \fn void QListWidgetItem::setToolTip(const QString &toolTip)
-
- Sets the tooltip for the list item to the text specified by \a toolTip.
-
- \sa toolTip(), setStatusTip(), setWhatsThis()
-*/
-
-/*!
- \fn void QListWidgetItem::setWhatsThis(const QString &whatsThis)
-
- Sets the "What's This?" help for the list item to the text specified by
- \a whatsThis.
-
- \sa whatsThis(), setStatusTip(), setToolTip()
-*/
-
-/*!
- \fn void QListWidgetItem::setFont(const QFont &font)
-
- Sets the font used when painting the item to the given \a font.
-*/
-
-/*!
- \fn void QListWidgetItem::setTextAlignment(int alignment)
-
- Sets the list item's text alignment to \a alignment.
-
- \sa Qt::AlignmentFlag
-*/
-
-/*!
- \fn void QListWidgetItem::setBackgroundColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setBackground() instead.
-*/
-
-/*!
- \fn void QListWidgetItem::setBackground(const QBrush &brush)
- \since 4.2
-
- Sets the background brush of the list item to the given \a brush.
-
- \sa background() setForeground()
-*/
-
-/*!
- \fn void QListWidgetItem::setTextColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setForeground() instead.
-*/
-
-/*!
- \fn void QListWidgetItem::setForeground(const QBrush &brush)
- \since 4.2
-
- Sets the foreground brush of the list item to the given \a brush.
-
- \sa foreground() setBackground()
-*/
-
-/*!
- \fn void QListWidgetItem::setCheckState(Qt::CheckState state)
-
- Sets the check state of the list item to \a state.
-
- \sa checkState()
-*/
-
-void QListWidgetPrivate::setup()
-{
- Q_Q(QListWidget);
- q->QListView::setModel(new QListModel(q));
- // view signals
- QObject::connect(q, SIGNAL(pressed(QModelIndex)), q, SLOT(_q_emitItemPressed(QModelIndex)));
- QObject::connect(q, SIGNAL(clicked(QModelIndex)), q, SLOT(_q_emitItemClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(doubleClicked(QModelIndex)),
- q, SLOT(_q_emitItemDoubleClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(activated(QModelIndex)),
- q, SLOT(_q_emitItemActivated(QModelIndex)));
- QObject::connect(q, SIGNAL(entered(QModelIndex)), q, SLOT(_q_emitItemEntered(QModelIndex)));
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitItemChanged(QModelIndex)));
- QObject::connect(q->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- QObject::connect(q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- q, SIGNAL(itemSelectionChanged()));
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort()));
-}
-
-void QListWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
-{
- Q_Q(QListWidget);
- emit q->itemPressed(listModel()->at(index.row()));
-}
-
-void QListWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
-{
- Q_Q(QListWidget);
- emit q->itemClicked(listModel()->at(index.row()));
-}
-
-void QListWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
-{
- Q_Q(QListWidget);
- emit q->itemDoubleClicked(listModel()->at(index.row()));
-}
-
-void QListWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
-{
- Q_Q(QListWidget);
- emit q->itemActivated(listModel()->at(index.row()));
-}
-
-void QListWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
-{
- Q_Q(QListWidget);
- emit q->itemEntered(listModel()->at(index.row()));
-}
-
-void QListWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
-{
- Q_Q(QListWidget);
- emit q->itemChanged(listModel()->at(index.row()));
-}
-
-void QListWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
- const QModelIndex &previous)
-{
- Q_Q(QListWidget);
- QPersistentModelIndex persistentCurrent = current;
- QListWidgetItem *currentItem = listModel()->at(persistentCurrent.row());
- emit q->currentItemChanged(currentItem, listModel()->at(previous.row()));
-
- //persistentCurrent is invalid if something changed the model in response
- //to the currentItemChanged signal emission and the item was removed
- if (!persistentCurrent.isValid()) {
- currentItem = 0;
- }
-
- emit q->currentTextChanged(currentItem ? currentItem->text() : QString());
- emit q->currentRowChanged(persistentCurrent.row());
-}
-
-void QListWidgetPrivate::_q_sort()
-{
- if (sortingEnabled)
- model->sort(0, sortOrder);
-}
-
-void QListWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
-{
- if (sortingEnabled && topLeft.isValid() && bottomRight.isValid())
- listModel()->ensureSorted(topLeft.column(), sortOrder,
- topLeft.row(), bottomRight.row());
-}
-
-/*!
- \class QListWidget
- \brief The QListWidget class provides an item-based list widget.
-
- \ingroup model-view
-
-
- QListWidget is a convenience class that provides a list view similar to the
- one supplied by QListView, but with a classic item-based interface for
- adding and removing items. QListWidget uses an internal model to manage
- each QListWidgetItem in the list.
-
- For a more flexible list view widget, use the QListView class with a
- standard model.
-
- List widgets are constructed in the same way as other widgets:
-
- \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 0
-
- The selectionMode() of a list widget determines how many of the items in
- the list can be selected at the same time, and whether complex selections
- of items can be created. This can be set with the setSelectionMode()
- function.
-
- There are two ways to add items to the list: they can be constructed with
- the list widget as their parent widget, or they can be constructed with no
- parent widget and added to the list later. If a list widget already exists
- when the items are constructed, the first method is easier to use:
-
- \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 1
-
- If you need to insert a new item into the list at a particular position, it
- is more required to construct the item without a parent widget and use the
- insertItem() function to place it within the list. The list widget will
- take ownership of the item.
-
- \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 6
- \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 7
-
- For multiple items, insertItems() can be used instead. The number of items
- in the list is found with the count() function. To remove items from the
- list, use takeItem().
-
- The current item in the list can be found with currentItem(), and changed
- with setCurrentItem(). The user can also change the current item by
- navigating with the keyboard or clicking on a different item. When the
- current item changes, the currentItemChanged() signal is emitted with the
- new current item and the item that was previously current.
-
- \table 100%
- \row \o \inlineimage windowsxp-listview.png Screenshot of a Windows XP style list widget
- \o \inlineimage macintosh-listview.png Screenshot of a Macintosh style table widget
- \o \inlineimage plastique-listview.png Screenshot of a Plastique style table widget
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} list widget.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} list widget.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} list widget.
- \endtable
-
- \sa QListWidgetItem, QListView, QTreeView, {Model/View Programming},
- {Config Dialog Example}
-*/
-
-/*!
- \fn void QListWidget::addItem(QListWidgetItem *item)
-
- Inserts the \a item at the end of the list widget.
-
- \warning A QListWidgetItem can only be added to a QListWidget once. Adding
- the same QListWidgetItem multiple times to a QListWidget will result in
- undefined behavior.
-
- \sa insertItem()
-*/
-
-/*!
- \fn void QListWidget::addItem(const QString &label)
-
- Inserts an item with the text \a label at the end of the list widget.
-*/
-
-/*!
- \fn void QListWidget::addItems(const QStringList &labels)
-
- Inserts items with the text \a labels at the end of the list widget.
-
- \sa insertItems()
-*/
-
-/*!
- \fn void QListWidget::itemPressed(QListWidgetItem *item)
-
- This signal is emitted with the specified \a item when a mouse button is
- pressed on an item in the widget.
-
- \sa itemClicked(), itemDoubleClicked()
-*/
-
-/*!
- \fn void QListWidget::itemClicked(QListWidgetItem *item)
-
- This signal is emitted with the specified \a item when a mouse button is
- clicked on an item in the widget.
-
- \sa itemPressed(), itemDoubleClicked()
-*/
-
-/*!
- \fn void QListWidget::itemDoubleClicked(QListWidgetItem *item)
-
- This signal is emitted with the specified \a item when a mouse button is
- double clicked on an item in the widget.
-
- \sa itemClicked(), itemPressed()
-*/
-
-/*!
- \fn void QListWidget::itemActivated(QListWidgetItem *item)
-
- This signal is emitted when the \a item is activated. The \a item is
- activated when the user clicks or double clicks on it, depending on the
- system configuration. It is also activated when the user presses the
- activation key (on Windows and X11 this is the \gui Return key, on Mac OS
- X it is \key{Ctrl+0}).
-*/
-
-/*!
- \fn void QListWidget::itemEntered(QListWidgetItem *item)
-
- This signal is emitted when the mouse cursor enters an item. The \a item is
- the item entered. This signal is only emitted when mouseTracking is turned
- on, or when a mouse button is pressed while moving into an item.
-
- \sa QWidget::setMouseTracking()
-*/
-
-/*!
- \fn void QListWidget::itemChanged(QListWidgetItem *item)
-
- This signal is emitted whenever the data of \a item has changed.
-*/
-
-/*!
- \fn void QListWidget::currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
-
- This signal is emitted whenever the current item changes.
-
- \a previous is the item that previously had the focus; \a current is the
- new current item.
-*/
-
-/*!
- \fn void QListWidget::currentTextChanged(const QString &currentText)
-
- This signal is emitted whenever the current item changes.
-
- \a currentText is the text data in the current item. If there is no current
- item, the \a currentText is invalid.
-*/
-
-/*!
- \fn void QListWidget::currentRowChanged(int currentRow)
-
- This signal is emitted whenever the current item changes.
-
- \a currentRow is the row of the current item. If there is no current item,
- the \a currentRow is -1.
-*/
-
-/*!
- \fn void QListWidget::itemSelectionChanged()
-
- This signal is emitted whenever the selection changes.
-
- \sa selectedItems(), QListWidgetItem::isSelected(), currentItemChanged()
-*/
-
-/*!
- \since 4.3
-
- \fn void QListWidget::removeItemWidget(QListWidgetItem *item)
-
- Removes the widget set on the given \a item.
-*/
-
-/*!
- Constructs an empty QListWidget with the given \a parent.
-*/
-
-QListWidget::QListWidget(QWidget *parent)
- : QListView(*new QListWidgetPrivate(), parent)
-{
- Q_D(QListWidget);
- d->setup();
-}
-
-/*!
- Destroys the list widget and all its items.
-*/
-
-QListWidget::~QListWidget()
-{
-}
-
-/*!
- Returns the item that occupies the given \a row in the list if one has been
- set; otherwise returns 0.
-
- \sa row()
-*/
-
-QListWidgetItem *QListWidget::item(int row) const
-{
- Q_D(const QListWidget);
- if (row < 0 || row >= d->model->rowCount())
- return 0;
- return d->listModel()->at(row);
-}
-
-/*!
- Returns the row containing the given \a item.
-
- \sa item()
-*/
-
-int QListWidget::row(const QListWidgetItem *item) const
-{
- Q_D(const QListWidget);
- return d->listModel()->index(const_cast<QListWidgetItem*>(item)).row();
-}
-
-
-/*!
- Inserts the \a item at the position in the list given by \a row.
-
- \sa addItem()
-*/
-
-void QListWidget::insertItem(int row, QListWidgetItem *item)
-{
- Q_D(QListWidget);
- if (item && !item->view)
- d->listModel()->insert(row, item);
-}
-
-/*!
- Inserts an item with the text \a label in the list widget at the position
- given by \a row.
-
- \sa addItem()
-*/
-
-void QListWidget::insertItem(int row, const QString &label)
-{
- Q_D(QListWidget);
- d->listModel()->insert(row, new QListWidgetItem(label));
-}
-
-/*!
- Inserts items from the list of \a labels into the list, starting at the
- given \a row.
-
- \sa insertItem(), addItem()
-*/
-
-void QListWidget::insertItems(int row, const QStringList &labels)
-{
- Q_D(QListWidget);
- d->listModel()->insert(row, labels);
-}
-
-/*!
- Removes and returns the item from the given \a row in the list widget;
- otherwise returns 0.
-
- Items removed from a list widget will not be managed by Qt, and will need
- to be deleted manually.
-
- \sa insertItem(), addItem()
-*/
-
-QListWidgetItem *QListWidget::takeItem(int row)
-{
- Q_D(QListWidget);
- if (row < 0 || row >= d->model->rowCount())
- return 0;
- return d->listModel()->take(row);
-}
-
-/*!
- \property QListWidget::count
- \brief the number of items in the list including any hidden items.
-*/
-
-int QListWidget::count() const
-{
- Q_D(const QListWidget);
- return d->model->rowCount();
-}
-
-/*!
- Returns the current item.
-*/
-QListWidgetItem *QListWidget::currentItem() const
-{
- Q_D(const QListWidget);
- return d->listModel()->at(currentIndex().row());
-}
-
-
-/*!
- Sets the current item to \a item.
-
- Unless the selection mode is \l{QAbstractItemView::}{NoSelection},
- the item is also be selected.
-*/
-void QListWidget::setCurrentItem(QListWidgetItem *item)
-{
- setCurrentRow(row(item));
-}
-
-/*!
- \since 4.4
- Set the current item to \a item, using the given \a command.
-*/
-void QListWidget::setCurrentItem(QListWidgetItem *item, QItemSelectionModel::SelectionFlags command)
-{
- setCurrentRow(row(item), command);
-}
-
-/*!
- \property QListWidget::currentRow
- \brief the row of the current item.
-
- Depending on the current selection mode, the row may also be selected.
-*/
-
-int QListWidget::currentRow() const
-{
- return currentIndex().row();
-}
-
-void QListWidget::setCurrentRow(int row)
-{
- Q_D(QListWidget);
- QModelIndex index = d->listModel()->index(row);
- if (d->selectionMode == SingleSelection)
- selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
- else if (d->selectionMode == NoSelection)
- selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- else
- selectionModel()->setCurrentIndex(index, QItemSelectionModel::SelectCurrent);
-}
-
-/*!
- \since 4.4
-
- Sets the current row to be the given \a row, using the given \a command,
-*/
-void QListWidget::setCurrentRow(int row, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QListWidget);
- d->selectionModel->setCurrentIndex(d->listModel()->index(row), command);
-}
-
-/*!
- Returns a pointer to the item at the coordinates \a p. The coordinates
- are relative to the list widget's \l{QAbstractScrollArea::}{viewport()}.
-
-*/
-QListWidgetItem *QListWidget::itemAt(const QPoint &p) const
-{
- Q_D(const QListWidget);
- return d->listModel()->at(indexAt(p).row());
-
-}
-
-/*!
- \fn QListWidgetItem *QListWidget::itemAt(int x, int y) const
- \overload
-
- Returns a pointer to the item at the coordinates (\a x, \a y).
- The coordinates are relative to the list widget's
- \l{QAbstractScrollArea::}{viewport()}.
-
-*/
-
-
-/*!
- Returns the rectangle on the viewport occupied by the item at \a item.
-*/
-QRect QListWidget::visualItemRect(const QListWidgetItem *item) const
-{
- Q_D(const QListWidget);
- QModelIndex index = d->listModel()->index(const_cast<QListWidgetItem*>(item));
- return visualRect(index);
-}
-
-/*!
- Sorts all the items in the list widget according to the specified \a order.
-*/
-void QListWidget::sortItems(Qt::SortOrder order)
-{
- Q_D(QListWidget);
- d->sortOrder = order;
- d->listModel()->sort(0, order);
-}
-
-/*!
- \since 4.2
- \property QListWidget::sortingEnabled
- \brief whether sorting is enabled
-
- If this property is true, sorting is enabled for the list; if the property
- is false, sorting is not enabled.
-
- The default value is false.
-*/
-void QListWidget::setSortingEnabled(bool enable)
-{
- Q_D(QListWidget);
- d->sortingEnabled = enable;
-}
-
-bool QListWidget::isSortingEnabled() const
-{
- Q_D(const QListWidget);
- return d->sortingEnabled;
-}
-
-/*!
- \internal
-*/
-Qt::SortOrder QListWidget::sortOrder() const
-{
- Q_D(const QListWidget);
- return d->sortOrder;
-}
-
-/*!
- Starts editing the \a item if it is editable.
-*/
-
-void QListWidget::editItem(QListWidgetItem *item)
-{
- Q_D(QListWidget);
- edit(d->listModel()->index(item));
-}
-
-/*!
- Opens an editor for the given \a item. The editor remains open after
- editing.
-
- \sa closePersistentEditor()
-*/
-void QListWidget::openPersistentEditor(QListWidgetItem *item)
-{
- Q_D(QListWidget);
- QModelIndex index = d->listModel()->index(item);
- QAbstractItemView::openPersistentEditor(index);
-}
-
-/*!
- Closes the persistent editor for the given \a item.
-
- \sa openPersistentEditor()
-*/
-void QListWidget::closePersistentEditor(QListWidgetItem *item)
-{
- Q_D(QListWidget);
- QModelIndex index = d->listModel()->index(item);
- QAbstractItemView::closePersistentEditor(index);
-}
-
-/*!
- \since 4.1
-
- Returns the widget displayed in the given \a item.
-*/
-QWidget *QListWidget::itemWidget(QListWidgetItem *item) const
-{
- Q_D(const QListWidget);
- QModelIndex index = d->listModel()->index(item);
- return QAbstractItemView::indexWidget(index);
-}
-
-/*!
- \since 4.1
-
- Sets the \a widget to be displayed in the give \a item.
-
- This function should only be used to display static content in the place of
- a list widget item. If you want to display custom dynamic content or
- implement a custom editor widget, use QListView and subclass QItemDelegate
- instead.
-
- \sa {Delegate Classes}
-*/
-void QListWidget::setItemWidget(QListWidgetItem *item, QWidget *widget)
-{
- Q_D(QListWidget);
- QModelIndex index = d->listModel()->index(item);
- QAbstractItemView::setIndexWidget(index, widget);
-}
-
-/*!
- Returns true if \a item is selected; otherwise returns false.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::isSelected() instead.
-*/
-bool QListWidget::isItemSelected(const QListWidgetItem *item) const
-{
- Q_D(const QListWidget);
- QModelIndex index = d->listModel()->index(const_cast<QListWidgetItem*>(item));
- return selectionModel()->isSelected(index);
-}
-
-/*!
- Selects or deselects the given \a item depending on whether \a select is
- true of false.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::setSelected() instead.
-*/
-void QListWidget::setItemSelected(const QListWidgetItem *item, bool select)
-{
- Q_D(QListWidget);
- QModelIndex index = d->listModel()->index(const_cast<QListWidgetItem*>(item));
-
- if (d->selectionMode == SingleSelection) {
- selectionModel()->select(index, select
- ? QItemSelectionModel::ClearAndSelect
- : QItemSelectionModel::Deselect);
- } else if (d->selectionMode != NoSelection) {
- selectionModel()->select(index, select
- ? QItemSelectionModel::Select
- : QItemSelectionModel::Deselect);
- }
-
-}
-
-/*!
- Returns a list of all selected items in the list widget.
-*/
-
-QList<QListWidgetItem*> QListWidget::selectedItems() const
-{
- Q_D(const QListWidget);
- QModelIndexList indexes = selectionModel()->selectedIndexes();
- QList<QListWidgetItem*> items;
- for (int i = 0; i < indexes.count(); ++i)
- items.append(d->listModel()->at(indexes.at(i).row()));
- return items;
-}
-
-/*!
- Finds items with the text that matches the string \a text using the given
- \a flags.
-*/
-
-QList<QListWidgetItem*> QListWidget::findItems(const QString &text, Qt::MatchFlags flags) const
-{
- Q_D(const QListWidget);
- QModelIndexList indexes = d->listModel()->match(model()->index(0, 0, QModelIndex()),
- Qt::DisplayRole, text, -1, flags);
- QList<QListWidgetItem*> items;
- for (int i = 0; i < indexes.size(); ++i)
- items.append(d->listModel()->at(indexes.at(i).row()));
- return items;
-}
-
-/*!
- Returns true if the \a item is explicitly hidden; otherwise returns false.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::isHidden() instead.
-*/
-bool QListWidget::isItemHidden(const QListWidgetItem *item) const
-{
- return isRowHidden(row(item));
-}
-
-/*!
- If \a hide is true, the \a item will be hidden; otherwise it will be shown.
-
- \obsolete
-
- This function is deprecated. Use QListWidgetItem::setHidden() instead.
-*/
-void QListWidget::setItemHidden(const QListWidgetItem *item, bool hide)
-{
- setRowHidden(row(item), hide);
-}
-
-/*!
- Scrolls the view if necessary to ensure that the \a item is visible.
-
- \a hint specifies where the \a item should be located after the operation.
-*/
-
-void QListWidget::scrollToItem(const QListWidgetItem *item, QAbstractItemView::ScrollHint hint)
-{
- Q_D(QListWidget);
- QModelIndex index = d->listModel()->index(const_cast<QListWidgetItem*>(item));
- QListView::scrollTo(index, hint);
-}
-
-/*!
- Removes all items and selections in the view.
-
- \warning All items will be permanently deleted.
-*/
-void QListWidget::clear()
-{
- Q_D(QListWidget);
- selectionModel()->clear();
- d->listModel()->clear();
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of
- listwidget items.
-
- \sa mimeData()
-*/
-QStringList QListWidget::mimeTypes() const
-{
- return d_func()->listModel()->QAbstractListModel::mimeTypes();
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a items. The format used to describe the items is obtained from the
- mimeTypes() function.
-
- If the list of items is empty, 0 is returned instead of a serialized empty
- list.
-*/
-QMimeData *QListWidget::mimeData(const QList<QListWidgetItem*>) const
-{
- return d_func()->listModel()->internalMimeData();
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- Handles \a data supplied by an external drag and drop operation that ended
- with the given \a action in the given \a index. Returns true if \a data and
- \a action can be handled by the model; otherwise returns false.
-
- \sa supportedDropActions()
-*/
-bool QListWidget::dropMimeData(int index, const QMimeData *data, Qt::DropAction action)
-{
- QModelIndex idx;
- int row = index;
- int column = 0;
- if (dropIndicatorPosition() == QAbstractItemView::OnItem) {
- // QAbstractListModel::dropMimeData will overwrite on the index if row == -1 and column == -1
- idx = model()->index(row, column);
- row = -1;
- column = -1;
- }
- return d_func()->listModel()->QAbstractListModel::dropMimeData(data, action , row, column, idx);
-}
-
-/*! \reimp */
-void QListWidget::dropEvent(QDropEvent *event) {
- Q_D(QListWidget);
- if (event->source() == this && d->movement != Static) {
- QListView::dropEvent(event);
- return;
- }
-
- if (event->source() == this && (event->dropAction() == Qt::MoveAction ||
- dragDropMode() == QAbstractItemView::InternalMove)) {
- QModelIndex topIndex;
- int col = -1;
- int row = -1;
- if (d->dropOn(event, &row, &col, &topIndex)) {
- QList<QModelIndex> selIndexes = selectedIndexes();
- QList<QPersistentModelIndex> persIndexes;
- for (int i = 0; i < selIndexes.count(); i++)
- persIndexes.append(selIndexes.at(i));
-
- if (persIndexes.contains(topIndex))
- return;
- qSort(persIndexes); // The dropped items will remain in the same visual order.
-
- QPersistentModelIndex dropRow = model()->index(row, col, topIndex);
-
- int r = row == -1 ? count() : (dropRow.row() >= 0 ? dropRow.row() : row);
- for (int i = 0; i < persIndexes.count(); ++i) {
- const QPersistentModelIndex &pIndex = persIndexes.at(i);
- d->listModel()->move(pIndex.row(), r);
- r = pIndex.row() + 1; // Dropped items are inserted contiguously and in the right order.
- }
-
- event->accept();
- // Don't want QAbstractItemView to delete it because it was "moved" we already did it
- event->setDropAction(Qt::CopyAction);
- }
- }
-
- QListView::dropEvent(event);
-}
-
-/*!
- Returns the drop actions supported by this view.
-
- \sa Qt::DropActions
-*/
-Qt::DropActions QListWidget::supportedDropActions() const
-{
- Q_D(const QListWidget);
- return d->listModel()->QAbstractListModel::supportedDropActions() | Qt::MoveAction;
-}
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- Returns a list of pointers to the items contained in the \a data object. If
- the object was not created by a QListWidget in the same process, the list
- is empty.
-*/
-QList<QListWidgetItem*> QListWidget::items(const QMimeData *data) const
-{
- const QListWidgetMimeData *lwd = qobject_cast<const QListWidgetMimeData*>(data);
- if (lwd)
- return lwd->items;
- return QList<QListWidgetItem*>();
-}
-
-/*!
- Returns the QModelIndex assocated with the given \a item.
-*/
-
-QModelIndex QListWidget::indexFromItem(QListWidgetItem *item) const
-{
- Q_D(const QListWidget);
- return d->listModel()->index(item);
-}
-
-/*!
- Returns a pointer to the QListWidgetItem assocated with the given \a index.
-*/
-
-QListWidgetItem *QListWidget::itemFromIndex(const QModelIndex &index) const
-{
- Q_D(const QListWidget);
- if (d->isIndexValid(index))
- return d->listModel()->at(index.row());
- return 0;
-}
-
-/*!
- \internal
-*/
-void QListWidget::setModel(QAbstractItemModel * /*model*/)
-{
- Q_ASSERT(!"QListWidget::setModel() - Changing the model of the QListWidget is not allowed.");
-}
-
-/*!
- \reimp
-*/
-bool QListWidget::event(QEvent *e)
-{
- return QListView::event(e);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qlistwidget.cpp"
-
-#endif // QT_NO_LISTWIDGET
diff --git a/src/gui/itemviews/qlistwidget.h b/src/gui/itemviews/qlistwidget.h
deleted file mode 100644
index ff6616dfac..0000000000
--- a/src/gui/itemviews/qlistwidget.h
+++ /dev/null
@@ -1,335 +0,0 @@
-/****************************************************************************
-**
-** 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 QLISTWIDGET_H
-#define QLISTWIDGET_H
-
-#include <QtGui/qlistview.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
-#include <QtGui/qitemselectionmodel.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_LISTWIDGET
-
-class QListWidget;
-class QListModel;
-class QWidgetItemData;
-class QListWidgetItemPrivate;
-
-class Q_GUI_EXPORT QListWidgetItem
-{
- friend class QListModel;
- friend class QListWidget;
-public:
- enum ItemType { Type = 0, UserType = 1000 };
- explicit QListWidgetItem(QListWidget *view = 0, int type = Type);
- explicit QListWidgetItem(const QString &text, QListWidget *view = 0, int type = Type);
- explicit QListWidgetItem(const QIcon &icon, const QString &text,
- QListWidget *view = 0, int type = Type);
- QListWidgetItem(const QListWidgetItem &other);
- virtual ~QListWidgetItem();
-
- virtual QListWidgetItem *clone() const;
-
- inline QListWidget *listWidget() const { return view; }
-
- inline void setSelected(bool select);
- inline bool isSelected() const;
-
- inline void setHidden(bool hide);
- inline bool isHidden() const;
-
- inline Qt::ItemFlags flags() const { return itemFlags; }
- void setFlags(Qt::ItemFlags flags);
-
- inline QString text() const
- { return data(Qt::DisplayRole).toString(); }
- inline void setText(const QString &text);
-
- inline QIcon icon() const
- { return qvariant_cast<QIcon>(data(Qt::DecorationRole)); }
- inline void setIcon(const QIcon &icon);
-
- inline QString statusTip() const
- { return data(Qt::StatusTipRole).toString(); }
- inline void setStatusTip(const QString &statusTip);
-
-#ifndef QT_NO_TOOLTIP
- inline QString toolTip() const
- { return data(Qt::ToolTipRole).toString(); }
- inline void setToolTip(const QString &toolTip);
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- inline QString whatsThis() const
- { return data(Qt::WhatsThisRole).toString(); }
- inline void setWhatsThis(const QString &whatsThis);
-#endif
-
- inline QFont font() const
- { return qvariant_cast<QFont>(data(Qt::FontRole)); }
- inline void setFont(const QFont &font);
-
- inline int textAlignment() const
- { return data(Qt::TextAlignmentRole).toInt(); }
- inline void setTextAlignment(int alignment)
- { setData(Qt::TextAlignmentRole, alignment); }
-
- inline QColor backgroundColor() const
- { return qvariant_cast<QColor>(data(Qt::BackgroundColorRole)); }
- virtual void setBackgroundColor(const QColor &color)
- { setData(Qt::BackgroundColorRole, color); }
-
- inline QBrush background() const
- { return qvariant_cast<QBrush>(data(Qt::BackgroundRole)); }
- inline void setBackground(const QBrush &brush)
- { setData(Qt::BackgroundRole, brush); }
-
- inline QColor textColor() const
- { return qvariant_cast<QColor>(data(Qt::TextColorRole)); }
- inline void setTextColor(const QColor &color)
- { setData(Qt::TextColorRole, color); }
-
- inline QBrush foreground() const
- { return qvariant_cast<QBrush>(data(Qt::ForegroundRole)); }
- inline void setForeground(const QBrush &brush)
- { setData(Qt::ForegroundRole, brush); }
-
- inline Qt::CheckState checkState() const
- { return static_cast<Qt::CheckState>(data(Qt::CheckStateRole).toInt()); }
- inline void setCheckState(Qt::CheckState state)
- { setData(Qt::CheckStateRole, static_cast<int>(state)); }
-
- inline QSize sizeHint() const
- { return qvariant_cast<QSize>(data(Qt::SizeHintRole)); }
- inline void setSizeHint(const QSize &size)
- { setData(Qt::SizeHintRole, size); }
-
- virtual QVariant data(int role) const;
- virtual void setData(int role, const QVariant &value);
-
- virtual bool operator<(const QListWidgetItem &other) const;
-
-#ifndef QT_NO_DATASTREAM
- virtual void read(QDataStream &in);
- virtual void write(QDataStream &out) const;
-#endif
- QListWidgetItem &operator=(const QListWidgetItem &other);
-
- inline int type() const { return rtti; }
-
-private:
- int rtti;
- QVector<void *> dummy;
- QListWidget *view;
- QListWidgetItemPrivate *d;
- Qt::ItemFlags itemFlags;
-};
-
-inline void QListWidgetItem::setText(const QString &atext)
-{ setData(Qt::DisplayRole, atext); }
-
-inline void QListWidgetItem::setIcon(const QIcon &aicon)
-{ setData(Qt::DecorationRole, aicon); }
-
-inline void QListWidgetItem::setStatusTip(const QString &astatusTip)
-{ setData(Qt::StatusTipRole, astatusTip); }
-
-#ifndef QT_NO_TOOLTIP
-inline void QListWidgetItem::setToolTip(const QString &atoolTip)
-{ setData(Qt::ToolTipRole, atoolTip); }
-#endif
-
-#ifndef QT_NO_WHATSTHIS
-inline void QListWidgetItem::setWhatsThis(const QString &awhatsThis)
-{ setData(Qt::WhatsThisRole, awhatsThis); }
-#endif
-
-inline void QListWidgetItem::setFont(const QFont &afont)
-{ setData(Qt::FontRole, afont); }
-
-#ifndef QT_NO_DATASTREAM
-Q_GUI_EXPORT QDataStream &operator<<(QDataStream &out, const QListWidgetItem &item);
-Q_GUI_EXPORT QDataStream &operator>>(QDataStream &in, QListWidgetItem &item);
-#endif
-
-class QListWidgetPrivate;
-
-class Q_GUI_EXPORT QListWidget : public QListView
-{
- Q_OBJECT
- Q_PROPERTY(int count READ count)
- Q_PROPERTY(int currentRow READ currentRow WRITE setCurrentRow NOTIFY currentRowChanged USER true)
- Q_PROPERTY(bool sortingEnabled READ isSortingEnabled WRITE setSortingEnabled)
-
- friend class QListWidgetItem;
- friend class QListModel;
-public:
- explicit QListWidget(QWidget *parent = 0);
- ~QListWidget();
-
- QListWidgetItem *item(int row) const;
- int row(const QListWidgetItem *item) const;
- void insertItem(int row, QListWidgetItem *item);
- void insertItem(int row, const QString &label);
- void insertItems(int row, const QStringList &labels);
- inline void addItem(const QString &label) { insertItem(count(), label); }
- inline void addItem(QListWidgetItem *item);
- inline void addItems(const QStringList &labels) { insertItems(count(), labels); }
- QListWidgetItem *takeItem(int row);
- int count() const;
-
- QListWidgetItem *currentItem() const;
- void setCurrentItem(QListWidgetItem *item);
- void setCurrentItem(QListWidgetItem *item, QItemSelectionModel::SelectionFlags command);
-
- int currentRow() const;
- void setCurrentRow(int row);
- void setCurrentRow(int row, QItemSelectionModel::SelectionFlags command);
-
- QListWidgetItem *itemAt(const QPoint &p) const;
- inline QListWidgetItem *itemAt(int x, int y) const;
- QRect visualItemRect(const QListWidgetItem *item) const;
-
- void sortItems(Qt::SortOrder order = Qt::AscendingOrder);
- void setSortingEnabled(bool enable);
- bool isSortingEnabled() const;
-
- void editItem(QListWidgetItem *item);
- void openPersistentEditor(QListWidgetItem *item);
- void closePersistentEditor(QListWidgetItem *item);
-
- QWidget *itemWidget(QListWidgetItem *item) const;
- void setItemWidget(QListWidgetItem *item, QWidget *widget);
- inline void removeItemWidget(QListWidgetItem *item);
-
- bool isItemSelected(const QListWidgetItem *item) const;
- void setItemSelected(const QListWidgetItem *item, bool select);
- QList<QListWidgetItem*> selectedItems() const;
- QList<QListWidgetItem*> findItems(const QString &text, Qt::MatchFlags flags) const;
-
- bool isItemHidden(const QListWidgetItem *item) const;
- void setItemHidden(const QListWidgetItem *item, bool hide);
- void dropEvent(QDropEvent *event);
-
-public Q_SLOTS:
- void scrollToItem(const QListWidgetItem *item, QAbstractItemView::ScrollHint hint = EnsureVisible);
- void clear();
-
-Q_SIGNALS:
- void itemPressed(QListWidgetItem *item);
- void itemClicked(QListWidgetItem *item);
- void itemDoubleClicked(QListWidgetItem *item);
- void itemActivated(QListWidgetItem *item);
- void itemEntered(QListWidgetItem *item);
- void itemChanged(QListWidgetItem *item);
-
- void currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous);
- void currentTextChanged(const QString &currentText);
- void currentRowChanged(int currentRow);
-
- void itemSelectionChanged();
-
-protected:
- bool event(QEvent *e);
- virtual QStringList mimeTypes() const;
- virtual QMimeData *mimeData(const QList<QListWidgetItem*> items) const;
-#ifndef QT_NO_DRAGANDDROP
- virtual bool dropMimeData(int index, const QMimeData *data, Qt::DropAction action);
- virtual Qt::DropActions supportedDropActions() const;
-#endif
- QList<QListWidgetItem*> items(const QMimeData *data) const;
-
- QModelIndex indexFromItem(QListWidgetItem *item) const;
- QListWidgetItem *itemFromIndex(const QModelIndex &index) const;
-
-private:
- void setModel(QAbstractItemModel *model);
- Qt::SortOrder sortOrder() const;
-
- Q_DECLARE_PRIVATE(QListWidget)
- Q_DISABLE_COPY(QListWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current))
- Q_PRIVATE_SLOT(d_func(), void _q_sort())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight))
-};
-
-inline void QListWidget::removeItemWidget(QListWidgetItem *aItem)
-{ setItemWidget(aItem, 0); }
-
-inline void QListWidget::addItem(QListWidgetItem *aitem)
-{ insertItem(count(), aitem); }
-
-inline QListWidgetItem *QListWidget::itemAt(int ax, int ay) const
-{ return itemAt(QPoint(ax, ay)); }
-
-inline void QListWidgetItem::setSelected(bool aselect)
-{ if (view) view->setItemSelected(this, aselect); }
-
-inline bool QListWidgetItem::isSelected() const
-{ return (view ? view->isItemSelected(this) : false); }
-
-inline void QListWidgetItem::setHidden(bool ahide)
-{ if (view) view->setItemHidden(this, ahide); }
-
-inline bool QListWidgetItem::isHidden() const
-{ return (view ? view->isItemHidden(this) : false); }
-
-#endif // QT_NO_LISTWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLISTWIDGET_H
diff --git a/src/gui/itemviews/qlistwidget_p.h b/src/gui/itemviews/qlistwidget_p.h
deleted file mode 100644
index 0614b66799..0000000000
--- a/src/gui/itemviews/qlistwidget_p.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/****************************************************************************
-**
-** 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 QLISTWIDGET_P_H
-#define QLISTWIDGET_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. This header file may change
-// from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qabstractitemmodel.h>
-#include <QtGui/qabstractitemview.h>
-#include <QtGui/qlistwidget.h>
-#include <qitemdelegate.h>
-#include <private/qlistview_p.h>
-#include <private/qwidgetitemdata_p.h>
-
-#ifndef QT_NO_LISTWIDGET
-
-QT_BEGIN_NAMESPACE
-
-class QListModelLessThan
-{
-public:
- inline bool operator()(QListWidgetItem *i1, QListWidgetItem *i2) const
- { return *i1 < *i2; }
-};
-
-class QListModelGreaterThan
-{
-public:
- inline bool operator()(QListWidgetItem *i1, QListWidgetItem *i2) const
- { return *i2 < *i1; }
-};
-
-class Q_AUTOTEST_EXPORT QListModel : public QAbstractListModel
-{
- Q_OBJECT
-public:
- QListModel(QListWidget *parent);
- ~QListModel();
-
- void clear();
- QListWidgetItem *at(int row) const;
- void insert(int row, QListWidgetItem *item);
- void insert(int row, const QStringList &items);
- void remove(QListWidgetItem *item);
- QListWidgetItem *take(int row);
- void move(int srcRow, int dstRow);
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
-
- QModelIndex index(QListWidgetItem *item) const;
- QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role);
-
- QMap<int, QVariant> itemData(const QModelIndex &index) const;
-
- bool insertRows(int row, int count = 1, const QModelIndex &parent = QModelIndex());
- bool removeRows(int row, int count = 1, const QModelIndex &parent = QModelIndex());
-
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- void sort(int column, Qt::SortOrder order);
- void ensureSorted(int column, Qt::SortOrder order, int start, int end);
- static bool itemLessThan(const QPair<QListWidgetItem*,int> &left,
- const QPair<QListWidgetItem*,int> &right);
- static bool itemGreaterThan(const QPair<QListWidgetItem*,int> &left,
- const QPair<QListWidgetItem*,int> &right);
- static QList<QListWidgetItem*>::iterator sortedInsertionIterator(
- const QList<QListWidgetItem*>::iterator &begin,
- const QList<QListWidgetItem*>::iterator &end,
- Qt::SortOrder order, QListWidgetItem *item);
-
- void itemChanged(QListWidgetItem *item);
-
- // dnd
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
-#ifndef QT_NO_DRAGANDDROP
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
- Qt::DropActions supportedDropActions() const;
-#endif
-
- QMimeData *internalMimeData() const;
-private:
- QList<QListWidgetItem*> items;
-
- // A cache must be mutable if get-functions should have const modifiers
- mutable QModelIndexList cachedIndexes;
-};
-
-
-
-class QListWidgetPrivate : public QListViewPrivate
-{
- Q_DECLARE_PUBLIC(QListWidget)
-public:
- QListWidgetPrivate() : QListViewPrivate(), sortOrder(Qt::AscendingOrder), sortingEnabled(false) {}
- inline QListModel *listModel() const { return qobject_cast<QListModel*>(model); }
- void setup();
- void _q_emitItemPressed(const QModelIndex &index);
- void _q_emitItemClicked(const QModelIndex &index);
- void _q_emitItemDoubleClicked(const QModelIndex &index);
- void _q_emitItemActivated(const QModelIndex &index);
- void _q_emitItemEntered(const QModelIndex &index);
- void _q_emitItemChanged(const QModelIndex &index);
- void _q_emitCurrentItemChanged(const QModelIndex &current, const QModelIndex &previous);
- void _q_sort();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- Qt::SortOrder sortOrder;
- bool sortingEnabled;
-};
-
-class QListWidgetItemPrivate
-{
-public:
- QListWidgetItemPrivate(QListWidgetItem *item) : q(item), theid(-1) {}
- QListWidgetItem *q;
- QVector<QWidgetItemData> values;
- int theid;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_LISTWIDGET
-
-#endif // QLISTWIDGET_P_H
diff --git a/src/gui/itemviews/qproxymodel.cpp b/src/gui/itemviews/qproxymodel.cpp
deleted file mode 100644
index 9a232a6a74..0000000000
--- a/src/gui/itemviews/qproxymodel.cpp
+++ /dev/null
@@ -1,547 +0,0 @@
-/****************************************************************************
-**
-** 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 "qproxymodel.h"
-
-#ifndef QT_NO_PROXYMODEL
-#include <private/qproxymodel_p.h>
-#include <qsize.h>
-#include <qstringlist.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QProxyModel
- \obsolete
- \brief The QProxyModel class provides support for processing data
- passed between another model and a view.
-
- \ingroup model-view
-
- If you want to do filtering and sorting, see QSortFilterProxyModel.
-
- Proxy models provide a standard model interface that can be used to
- manipulate the data retrieved through an underlying model. They can be used to
- perform operations such as sorting and filtering on the data obtained without
- changing the contents of the model.
-
- Just as with subclasses of QAbstractItemView, QProxyModel provides the setModel()
- function that is used to specify the model to be acted on by the proxy.
- Views can be connected to either the underlying model or the proxy model with
- \l QAbstractItemView::setModel().
-
- Since views rely on the information provided in model indexes to identify
- items of data from models, and to position these items in some visual
- representation, proxy models must create their own model indexes instead of
- supplying model indexes from their underlying models.
-
- \sa \link model-view-programming.html Model/View Programming\endlink QAbstractItemModel
-
-*/
-
-/*!
- Constructs a proxy model with the given \a parent.
-*/
-
-QProxyModel::QProxyModel(QObject *parent)
- : QAbstractItemModel(*new QProxyModelPrivate, parent)
-{
- Q_D(QProxyModel);
- setModel(&d->empty);
-}
-
-/*!
- \internal
-*/
-QProxyModel::QProxyModel(QProxyModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- Q_D(QProxyModel);
- setModel(&d->empty);
-}
-
-/*!
- Destroys the proxy model.
-*/
-QProxyModel::~QProxyModel()
-{
-}
-
-/*!
- Sets the given \a model to be processed by the proxy model.
-*/
-void QProxyModel::setModel(QAbstractItemModel *model)
-{
- Q_D(QProxyModel);
- if (d->model && d->model != &d->empty)
- disconnectFromModel(d->model);
- if (model) {
- d->model = model;
- connectToModel(model);
- } else {
- d->model = &d->empty;
- }
-}
-
-/*!
- Returns the model that contains the data that is available through the
- proxy model.
-*/
-QAbstractItemModel *QProxyModel::model() const
-{
- Q_D(const QProxyModel);
- return d->model;
-}
-
-/*!
- Returns the model index with the given \a row, \a column, and \a parent.
-
- \sa QAbstractItemModel::index()
-*/
-QModelIndex QProxyModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QProxyModel);
- return setProxyModel(d->model->index(row, column, setSourceModel(parent)));
-}
-
-/*!
- Returns the model index that corresponds to the parent of the given \a child
- index.
-*/
-QModelIndex QProxyModel::parent(const QModelIndex &child) const
-{
- Q_D(const QProxyModel);
- return setProxyModel(d->model->parent(setSourceModel(child)));
-}
-
-/*!
- Returns the number of rows for the given \a parent.
-
- \sa QAbstractItemModel::rowCount()
-*/
-int QProxyModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QProxyModel);
- return d->model->rowCount(setSourceModel(parent));
-}
-
-/*!
- Returns the number of columns for the given \a parent.
-
- \sa QAbstractItemModel::columnCount()
-*/
-int QProxyModel::columnCount(const QModelIndex &parent) const
-{
- Q_D(const QProxyModel);
- return d->model->columnCount(setSourceModel(parent));
-}
-
-/*!
- Returns true if the item corresponding to the \a parent index has child
- items; otherwise returns false.
-
- \sa QAbstractItemModel::hasChildren()
-*/
-bool QProxyModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QProxyModel);
- return d->model->hasChildren(setSourceModel(parent));
-}
-
-/*!
- Returns the data stored in the item with the given \a index under the
- specified \a role.
-*/
-QVariant QProxyModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QProxyModel);
- return d->model->data(setSourceModel(index), role);
-}
-
-/*!
- Sets the \a role data for the item at \a index to \a value.
- Returns true if successful; otherwise returns false.
-
- The base class implementation returns false. This function and
- data() must be reimplemented for editable models.
-
- \sa data() itemData() QAbstractItemModel::setData()
-*/
-bool QProxyModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- Q_D(const QProxyModel);
- return d->model->setData(setSourceModel(index), value, role);
-}
-
-/*!
- Returns the data stored in the \a section of the header with specified
- \a orientation under the given \a role.
-*/
-QVariant QProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- Q_D(const QProxyModel);
- return d->model->headerData(section, orientation, role);
-}
-
-/*!
- Sets the \a role data in the \a section of the header with the specified
- \a orientation to the \a value given.
-
- \sa QAbstractItemModel::setHeaderData()
-*/
-bool QProxyModel::setHeaderData(int section, Qt::Orientation orientation,
- const QVariant &value, int role)
-{
- Q_D(const QProxyModel);
- return d->model->setHeaderData(section, orientation, value, role);
-}
-
-/*!
- Returns a list of MIME types that are supported by the model.
-*/
-QStringList QProxyModel::mimeTypes() const
-{
- Q_D(const QProxyModel);
- return d->model->mimeTypes();
-}
-
-/*!
- Returns MIME data for the specified \a indexes in the model.
-*/
-QMimeData *QProxyModel::mimeData(const QModelIndexList &indexes) const
-{
- Q_D(const QProxyModel);
- QModelIndexList lst;
- for (int i = 0; i < indexes.count(); ++i)
- lst.append(setSourceModel(indexes.at(i)));
- return d->model->mimeData(lst);
-}
-
-/*!
- Returns true if the model accepts the \a data dropped onto an attached
- view for the specified \a action; otherwise returns false.
-
- The \a parent, \a row, and \a column details can be used to control
- which MIME types are acceptable to different parts of a model when
- received via the drag and drop system.
-*/
-bool QProxyModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- Q_D(const QProxyModel);
- return d->model->dropMimeData(data, action, row, column, setSourceModel(parent));
-}
-
-/*!
- Returns the drop actions that are supported by the model; this is
- a combination of the individual actions defined in \l Qt::DropActions.
-
- The selection of drop actions provided by the model will influence the
- behavior of the component that started the drag and drop operation.
-
- \sa \link dnd.html Drag and Drop\endlink
-*/
-Qt::DropActions QProxyModel::supportedDropActions() const
-{
- Q_D(const QProxyModel);
- return d->model->supportedDropActions();
-}
-
-/*!
- Inserts \a count rows into the model, creating new items as children of
- the given \a parent. The new rows are inserted before the \a row
- specified. If the \a parent item has no children, a single column is
- created to contain the required number of rows.
-
- Returns true if the rows were successfully inserted; otherwise
- returns false.
-
- \sa QAbstractItemModel::insertRows()*/
-bool QProxyModel::insertRows(int row, int count, const QModelIndex &parent)
-{
- Q_D(const QProxyModel);
- return d->model->insertRows(row, count, setSourceModel(parent));
-}
-
-/*!
- Inserts \a count columns into the model, creating new items as children of
- the given \a parent. The new columns are inserted before the \a column
- specified. If the \a parent item has no children, a single row is created
- to contain the required number of columns.
-
- Returns true if the columns were successfully inserted; otherwise
- returns false.
-
- \sa QAbstractItemModel::insertColumns()
-*/
-bool QProxyModel::insertColumns(int column, int count, const QModelIndex &parent)
-{
- Q_D(const QProxyModel);
- return d->model->insertColumns(column, count, setSourceModel(parent));
-}
-
-/*!
- Fetches more child items of the given \a parent. This function is used by views
- to tell the model that they can display more data than the model has provided.
-
- \sa QAbstractItemModel::fetchMore()
-*/
-void QProxyModel::fetchMore(const QModelIndex &parent)
-{
- Q_D(const QProxyModel);
- d->model->fetchMore(parent);
-}
-
-/*!
- Returns the item flags for the given \a index.
-*/
-Qt::ItemFlags QProxyModel::flags(const QModelIndex &index) const
-{
- Q_D(const QProxyModel);
- return d->model->flags(setSourceModel(index));
-}
-
-/*!
- Sorts the child items in the specified \a column according to the sort
- order defined by \a order.
-
- \sa QAbstractItemModel::sort()
-*/
-void QProxyModel::sort(int column, Qt::SortOrder order)
-{
- Q_D(QProxyModel);
- d->model->sort(column, order);
-}
-
-/*!
- Returns a list of model indexes that each contain the given \a value for
- the \a role specified. The search begins at the \a start index and is
- performed according to the specified \a flags. The search continues until
- the number of matching data items equals \a hits, the last row is reached,
- or the search reaches \a start again, depending on whether \c MatchWrap is
- specified in \a flags.
-
- \sa QAbstractItemModel::match()
-*/
-QModelIndexList QProxyModel::match(const QModelIndex &start,
- int role, const QVariant &value,
- int hits, Qt::MatchFlags flags) const
-{
- Q_D(const QProxyModel);
- return d->model->match(start, role, value, hits, flags);
-}
-
-/*!
- Returns the size of the item that corresponds to the specified \a index.
-*/
-QSize QProxyModel::span(const QModelIndex &index) const
-{
- Q_D(const QProxyModel);
- return d->model->span(setSourceModel(index));
-}
-
-/*!
- */
-bool QProxyModel::submit()
-{
- Q_D(QProxyModel);
- return d->model->submit();
-}
-
-/*!
- */
-void QProxyModel::revert()
-{
- Q_D(QProxyModel);
- d->model->revert();
-}
-
-/*!
- \internal
- Change the model pointer in the given \a source_index to point to the proxy model.
- */
-QModelIndex QProxyModel::setProxyModel(const QModelIndex &source_index) const
-{
- QModelIndex proxy_index = source_index;
- if (proxy_index.isValid())
- proxy_index.m = this;
- return proxy_index;
-}
-
-/*!
- \internal
- Change the model pointer in the given \a proxy_index to point to the source model.
- */
-QModelIndex QProxyModel::setSourceModel(const QModelIndex &proxy_index) const
-{
- Q_D(const QProxyModel);
- QModelIndex source_index = proxy_index;
- source_index.m = d->model;
- return source_index;
-}
-
-/*!
- \internal
- Connect to all the signals emitted by given \a model.
-*/
-void QProxyModel::connectToModel(const QAbstractItemModel *model) const
-{
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SIGNAL(headerDataChanged(Qt::Orientation,int,int))); // signal to signal
- connect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(modelReset()), this, SIGNAL(modelReset())); // signal to signal
- connect(model, SIGNAL(layoutAboutToBeChanged()), this, SIGNAL(layoutAboutToBeChanged())); // signal to signal
- connect(model, SIGNAL(layoutChanged()), this, SIGNAL(layoutChanged())); // signal to signal
-}
-
-/*!
- \internal
- Disconnect from all the signals emitted by the given \a model.
- */
-void QProxyModel::disconnectFromModel(const QAbstractItemModel *model) const
-{
- disconnect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
- disconnect(model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SIGNAL(headerDataChanged(Qt::Orientation,int,int))); // signal to signal
- disconnect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeInserted(QModelIndex,int,int)));
- disconnect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(rowsInserted(QModelIndex,int,int)));
- disconnect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
- disconnect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsRemoved(QModelIndex,int,int)));
- disconnect(model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeInserted(QModelIndex,int,int)));
- disconnect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsInserted(QModelIndex,int,int)));
- disconnect(model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeRemoved(QModelIndex,int,int)));
- disconnect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsRemoved(QModelIndex,int,int)));
- disconnect(model, SIGNAL(modelReset()), this, SIGNAL(modelReset())); // signal to signal
- disconnect(model, SIGNAL(layoutAboutToBeChanged()), this, SIGNAL(layoutAboutToBeChanged())); // signal to signal
- disconnect(model, SIGNAL(layoutChanged()), this, SIGNAL(layoutChanged())); // signal to signal
-}
-
-/*!
- \fn QObject *QProxyModel::parent() const
- \internal
-*/
-
-void QProxyModelPrivate::_q_sourceDataChanged(const QModelIndex &tl,const QModelIndex &br)
-{
- Q_Q(QProxyModel);
- emit q->dataChanged(q->setProxyModel(tl), q->setProxyModel(br));
-}
-
-void QProxyModelPrivate::_q_sourceRowsAboutToBeInserted(const QModelIndex &parent, int first ,int last)
-{
- Q_Q(QProxyModel);
- q->beginInsertRows(q->setProxyModel(parent), first, last);
-}
-
-void QProxyModelPrivate::_q_sourceRowsInserted(const QModelIndex &, int, int)
-{
- Q_Q(QProxyModel);
- q->endInsertRows();
-}
-
-void QProxyModelPrivate::_q_sourceRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
-{
- Q_Q(QProxyModel);
- q->beginRemoveRows(q->setProxyModel(parent), first, last);
-}
-
-void QProxyModelPrivate::_q_sourceRowsRemoved(const QModelIndex &, int, int)
-{
- Q_Q(QProxyModel);
- q->endRemoveRows();
-}
-
-void QProxyModelPrivate::_q_sourceColumnsAboutToBeInserted(const QModelIndex &parent, int first, int last)
-{
- Q_Q(QProxyModel);
- q->beginInsertColumns(q->setProxyModel(parent), first, last);
-}
-
-void QProxyModelPrivate::_q_sourceColumnsInserted(const QModelIndex &, int, int)
-{
- Q_Q(QProxyModel);
- q->endInsertColumns();
-}
-
-void QProxyModelPrivate::_q_sourceColumnsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
-{
- Q_Q(QProxyModel);
- q->beginRemoveColumns(q->setProxyModel(parent), first, last);
-}
-
-
-void QProxyModelPrivate::_q_sourceColumnsRemoved(const QModelIndex &, int, int)
-{
- Q_Q(QProxyModel);
- q->endRemoveColumns();
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qproxymodel.cpp"
-
-#endif // QT_NO_PROXYMODEL
diff --git a/src/gui/itemviews/qproxymodel.h b/src/gui/itemviews/qproxymodel.h
deleted file mode 100644
index eeca4b266b..0000000000
--- a/src/gui/itemviews/qproxymodel.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** 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 QPROXYMODEL_H
-#define QPROXYMODEL_H
-
-#include <QtCore/qabstractitemmodel.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PROXYMODEL
-
-class QProxyModelPrivate;
-
-class Q_GUI_EXPORT QProxyModel : public QAbstractItemModel
-{
- Q_OBJECT
-
-public:
- explicit QProxyModel(QObject *parent = 0);
- ~QProxyModel();
-
- virtual void setModel(QAbstractItemModel *model);
- QAbstractItemModel *model() const;
-
- // implementing model interface
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex &child) const;
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
- bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value,
- int role = Qt::EditRole);
-
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
- Qt::DropActions supportedDropActions() const;
-
- bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
- bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex());
-
- void fetchMore(const QModelIndex &parent);
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- QModelIndexList match(const QModelIndex &start, int role, const QVariant &value,
- int hits = 1, Qt::MatchFlags flags =
- Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const;
-
- QSize span(const QModelIndex &index) const;
-
- bool submit();
- void revert();
-
-#ifdef Q_NO_USING_KEYWORD
- inline QObject *parent() const { return QObject::parent(); }
-#else
- using QObject::parent;
-#endif
-
-protected:
- QProxyModel(QProxyModelPrivate &, QObject *parent = 0);
-
- QModelIndex setProxyModel(const QModelIndex &source_index) const;
- QModelIndex setSourceModel(const QModelIndex &proxy_index) const;
-
- void connectToModel(const QAbstractItemModel *model) const;
- void disconnectFromModel(const QAbstractItemModel *model) const;
-
-private:
- Q_DECLARE_PRIVATE(QProxyModel)
- Q_DISABLE_COPY(QProxyModel)
-
- Q_PRIVATE_SLOT(d_func(), void _q_sourceDataChanged(const QModelIndex&,const QModelIndex&))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeInserted(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsInserted(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeRemoved(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsRemoved(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeInserted(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsInserted(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeRemoved(const QModelIndex&,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsRemoved(const QModelIndex&,int,int))
-};
-
-#endif // QT_NO_PROXYMODEL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPROXYMODEL_H
diff --git a/src/gui/itemviews/qproxymodel_p.h b/src/gui/itemviews/qproxymodel_p.h
deleted file mode 100644
index ef4bcbada2..0000000000
--- a/src/gui/itemviews/qproxymodel_p.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************************
-**
-** 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 QPROXYMODEL_P_H
-#define QPROXYMODEL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of QAbstractItemModel*. This header file may change from version
-// to version without notice, or even be removed.
-//
-// We mean it.
-//
-//
-
-#include "QtCore/qabstractitemmodel.h"
-#include "private/qabstractitemmodel_p.h"
-
-#ifndef QT_NO_PROXYMODEL
-
-QT_BEGIN_NAMESPACE
-
-class QEmptyModel : public QAbstractItemModel
-{
-public:
- explicit QEmptyModel(QObject *parent = 0) : QAbstractItemModel(parent) {}
- QModelIndex index(int, int, const QModelIndex &) const { return QModelIndex(); }
- QModelIndex parent(const QModelIndex &) const { return QModelIndex(); }
- int rowCount(const QModelIndex &) const { return 0; }
- int columnCount(const QModelIndex &) const { return 0; }
- bool hasChildren(const QModelIndex &) const { return false; }
- QVariant data(const QModelIndex &, int) const { return QVariant(); }
-};
-
-class QProxyModelPrivate : private QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QProxyModel)
-
-public:
- void _q_sourceDataChanged(const QModelIndex &tl,const QModelIndex &br);
- void _q_sourceRowsAboutToBeInserted(const QModelIndex &parent, int first ,int last);
- void _q_sourceRowsInserted(const QModelIndex &parent, int first ,int last);
- void _q_sourceRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last);
- void _q_sourceRowsRemoved(const QModelIndex &parent, int first, int last);
- void _q_sourceColumnsAboutToBeInserted(const QModelIndex &parent, int first, int last);
- void _q_sourceColumnsInserted(const QModelIndex &parent, int first, int last);
- void _q_sourceColumnsAboutToBeRemoved(const QModelIndex &parent, int first, int last);
- void _q_sourceColumnsRemoved(const QModelIndex &parent, int first, int last);
-
- QProxyModelPrivate() : QAbstractItemModelPrivate(), model(0) {}
- QAbstractItemModel *model;
- QEmptyModel empty;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PROXYMODEL
-
-#endif // QPROXYMODEL_P_H
diff --git a/src/gui/itemviews/qsortfilterproxymodel.cpp b/src/gui/itemviews/qsortfilterproxymodel.cpp
deleted file mode 100644
index eb56f56ed4..0000000000
--- a/src/gui/itemviews/qsortfilterproxymodel.cpp
+++ /dev/null
@@ -1,2542 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsortfilterproxymodel.h"
-
-#ifndef QT_NO_SORTFILTERPROXYMODEL
-
-#include "qitemselectionmodel.h"
-#include <qsize.h>
-#include <qdebug.h>
-#include <qdatetime.h>
-#include <qpair.h>
-#include <qstringlist.h>
-#include <private/qabstractitemmodel_p.h>
-#include <private/qabstractproxymodel_p.h>
-
-QT_BEGIN_NAMESPACE
-
-typedef QList<QPair<QModelIndex, QPersistentModelIndex> > QModelIndexPairList;
-
-static inline QSet<int> qVectorToSet(const QVector<int> &vector)
-{
- QSet<int> set;
- set.reserve(vector.size());
- for(int i=0; i < vector.size(); ++i)
- set << vector.at(i);
- return set;
-}
-
-class QSortFilterProxyModelLessThan
-{
-public:
- inline QSortFilterProxyModelLessThan(int column, const QModelIndex &parent,
- const QAbstractItemModel *source,
- const QSortFilterProxyModel *proxy)
- : sort_column(column), source_parent(parent), source_model(source), proxy_model(proxy) {}
-
- inline bool operator()(int r1, int r2) const
- {
- QModelIndex i1 = source_model->index(r1, sort_column, source_parent);
- QModelIndex i2 = source_model->index(r2, sort_column, source_parent);
- return proxy_model->lessThan(i1, i2);
- }
-
-private:
- int sort_column;
- QModelIndex source_parent;
- const QAbstractItemModel *source_model;
- const QSortFilterProxyModel *proxy_model;
-};
-
-class QSortFilterProxyModelGreaterThan
-{
-public:
- inline QSortFilterProxyModelGreaterThan(int column, const QModelIndex &parent,
- const QAbstractItemModel *source,
- const QSortFilterProxyModel *proxy)
- : sort_column(column), source_parent(parent),
- source_model(source), proxy_model(proxy) {}
-
- inline bool operator()(int r1, int r2) const
- {
- QModelIndex i1 = source_model->index(r1, sort_column, source_parent);
- QModelIndex i2 = source_model->index(r2, sort_column, source_parent);
- return proxy_model->lessThan(i2, i1);
- }
-
-private:
- int sort_column;
- QModelIndex source_parent;
- const QAbstractItemModel *source_model;
- const QSortFilterProxyModel *proxy_model;
-};
-
-
-//this struct is used to store what are the rows that are removed
-//between a call to rowsAboutToBeRemoved and rowsRemoved
-//it avoids readding rows to the mapping that are currently being removed
-struct QRowsRemoval
-{
- QRowsRemoval(const QModelIndex &parent_source, int start, int end) : parent_source(parent_source), start(start), end(end)
- {
- }
-
- QRowsRemoval() : start(-1), end(-1)
- {
- }
-
- bool contains(QModelIndex parent, int row)
- {
- do {
- if (parent == parent_source)
- return row >= start && row <= end;
- row = parent.row();
- parent = parent.parent();
- } while (row >= 0);
- return false;
- }
-private:
- QModelIndex parent_source;
- int start;
- int end;
-};
-
-class QSortFilterProxyModelPrivate : public QAbstractProxyModelPrivate
-{
- Q_DECLARE_PUBLIC(QSortFilterProxyModel)
-
-public:
- struct Mapping {
- QVector<int> source_rows;
- QVector<int> source_columns;
- QVector<int> proxy_rows;
- QVector<int> proxy_columns;
- QVector<QModelIndex> mapped_children;
- QHash<QModelIndex, Mapping *>::const_iterator map_iter;
- };
-
- mutable QHash<QModelIndex, Mapping*> source_index_mapping;
-
- int source_sort_column;
- int proxy_sort_column;
- Qt::SortOrder sort_order;
- Qt::CaseSensitivity sort_casesensitivity;
- int sort_role;
- bool sort_localeaware;
-
- int filter_column;
- QRegExp filter_regexp;
- int filter_role;
-
- bool dynamic_sortfilter;
- QRowsRemoval itemsBeingRemoved;
-
- QModelIndexPairList saved_persistent_indexes;
-
- QHash<QModelIndex, Mapping *>::const_iterator create_mapping(
- const QModelIndex &source_parent) const;
- QModelIndex proxy_to_source(const QModelIndex &proxyIndex) const;
- QModelIndex source_to_proxy(const QModelIndex &sourceIndex) const;
- bool can_create_mapping(const QModelIndex &source_parent) const;
-
- void remove_from_mapping(const QModelIndex &source_parent);
-
- inline QHash<QModelIndex, Mapping *>::const_iterator index_to_iterator(
- const QModelIndex &proxy_index) const
- {
- Q_ASSERT(proxy_index.isValid());
- Q_ASSERT(proxy_index.model() == q_func());
- const void *p = proxy_index.internalPointer();
- Q_ASSERT(p);
- QHash<QModelIndex, Mapping *>::const_iterator it =
- static_cast<const Mapping*>(p)->map_iter;
- Q_ASSERT(it != source_index_mapping.constEnd());
- Q_ASSERT(it.value());
- return it;
- }
-
- inline QModelIndex create_index(int row, int column,
- QHash<QModelIndex, Mapping*>::const_iterator it) const
- {
- return q_func()->createIndex(row, column, *it);
- }
-
- void _q_sourceDataChanged(const QModelIndex &source_top_left,
- const QModelIndex &source_bottom_right);
- void _q_sourceHeaderDataChanged(Qt::Orientation orientation, int start, int end);
-
- void _q_sourceAboutToBeReset();
- void _q_sourceReset();
-
- void _q_sourceLayoutAboutToBeChanged();
- void _q_sourceLayoutChanged();
-
- void _q_sourceRowsAboutToBeInserted(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceRowsInserted(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceRowsAboutToBeRemoved(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceRowsRemoved(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceColumnsAboutToBeInserted(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceColumnsInserted(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceColumnsAboutToBeRemoved(const QModelIndex &source_parent,
- int start, int end);
- void _q_sourceColumnsRemoved(const QModelIndex &source_parent,
- int start, int end);
-
- void _q_clearMapping();
-
- void sort();
- bool update_source_sort_column();
- void sort_source_rows(QVector<int> &source_rows,
- const QModelIndex &source_parent) const;
- QVector<QPair<int, QVector<int > > > proxy_intervals_for_source_items_to_add(
- const QVector<int> &proxy_to_source, const QVector<int> &source_items,
- const QModelIndex &source_parent, Qt::Orientation orient) const;
- QVector<QPair<int, int > > proxy_intervals_for_source_items(
- const QVector<int> &source_to_proxy, const QVector<int> &source_items) const;
- void insert_source_items(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- const QVector<int> &source_items, const QModelIndex &source_parent,
- Qt::Orientation orient, bool emit_signal = true);
- void remove_source_items(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- const QVector<int> &source_items, const QModelIndex &source_parent,
- Qt::Orientation orient, bool emit_signal = true);
- void remove_proxy_interval(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- int proxy_start, int proxy_end, const QModelIndex &proxy_parent,
- Qt::Orientation orient, bool emit_signal = true);
- void build_source_to_proxy_mapping(
- const QVector<int> &proxy_to_source, QVector<int> &source_to_proxy) const;
- void source_items_inserted(const QModelIndex &source_parent,
- int start, int end, Qt::Orientation orient);
- void source_items_about_to_be_removed(const QModelIndex &source_parent,
- int start, int end, Qt::Orientation orient);
- void source_items_removed(const QModelIndex &source_parent,
- int start, int end, Qt::Orientation orient);
- void proxy_item_range(
- const QVector<int> &source_to_proxy, const QVector<int> &source_items,
- int &proxy_low, int &proxy_high) const;
-
- QModelIndexPairList store_persistent_indexes();
- void update_persistent_indexes(const QModelIndexPairList &source_indexes);
-
- void filter_changed(const QModelIndex &source_parent = QModelIndex());
- QSet<int> handle_filter_changed(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- const QModelIndex &source_parent, Qt::Orientation orient);
-
- void updateChildrenMapping(const QModelIndex &source_parent, Mapping *parent_mapping,
- Qt::Orientation orient, int start, int end, int delta_item_count, bool remove);
-
- virtual void _q_sourceModelDestroyed();
-};
-
-typedef QHash<QModelIndex, QSortFilterProxyModelPrivate::Mapping *> IndexMap;
-
-void QSortFilterProxyModelPrivate::_q_sourceModelDestroyed()
-{
- QAbstractProxyModelPrivate::_q_sourceModelDestroyed();
- _q_clearMapping();
-}
-
-void QSortFilterProxyModelPrivate::remove_from_mapping(const QModelIndex &source_parent)
-{
- if (Mapping *m = source_index_mapping.take(source_parent)) {
- for (int i = 0; i < m->mapped_children.size(); ++i)
- remove_from_mapping(m->mapped_children.at(i));
- delete m;
- }
-}
-
-void QSortFilterProxyModelPrivate::_q_clearMapping()
-{
- // store the persistent indexes
- QModelIndexPairList source_indexes = store_persistent_indexes();
-
- qDeleteAll(source_index_mapping);
- source_index_mapping.clear();
- if (dynamic_sortfilter && update_source_sort_column()) {
- //update_source_sort_column might have created wrong mapping so we have to clear it again
- qDeleteAll(source_index_mapping);
- source_index_mapping.clear();
- }
-
- // update the persistent indexes
- update_persistent_indexes(source_indexes);
-}
-
-IndexMap::const_iterator QSortFilterProxyModelPrivate::create_mapping(
- const QModelIndex &source_parent) const
-{
- Q_Q(const QSortFilterProxyModel);
-
- IndexMap::const_iterator it = source_index_mapping.constFind(source_parent);
- if (it != source_index_mapping.constEnd()) // was mapped already
- return it;
-
- Mapping *m = new Mapping;
-
- int source_rows = model->rowCount(source_parent);
- m->source_rows.reserve(source_rows);
- for (int i = 0; i < source_rows; ++i) {
- if (q->filterAcceptsRow(i, source_parent))
- m->source_rows.append(i);
- }
- int source_cols = model->columnCount(source_parent);
- m->source_columns.reserve(source_cols);
- for (int i = 0; i < source_cols; ++i) {
- if (q->filterAcceptsColumn(i, source_parent))
- m->source_columns.append(i);
- }
-
- sort_source_rows(m->source_rows, source_parent);
- m->proxy_rows.resize(source_rows);
- build_source_to_proxy_mapping(m->source_rows, m->proxy_rows);
- m->proxy_columns.resize(source_cols);
- build_source_to_proxy_mapping(m->source_columns, m->proxy_columns);
-
- it = IndexMap::const_iterator(source_index_mapping.insert(source_parent, m));
- m->map_iter = it;
-
- if (source_parent.isValid()) {
- QModelIndex source_grand_parent = source_parent.parent();
- IndexMap::const_iterator it2 = create_mapping(source_grand_parent);
- Q_ASSERT(it2 != source_index_mapping.constEnd());
- it2.value()->mapped_children.append(source_parent);
- }
-
- Q_ASSERT(it != source_index_mapping.constEnd());
- Q_ASSERT(it.value());
-
- return it;
-}
-
-QModelIndex QSortFilterProxyModelPrivate::proxy_to_source(const QModelIndex &proxy_index) const
-{
- if (!proxy_index.isValid())
- return QModelIndex(); // for now; we may want to be able to set a root index later
- if (proxy_index.model() != q_func()) {
- qWarning() << "QSortFilterProxyModel: index from wrong model passed to mapToSource";
- Q_ASSERT(!"QSortFilterProxyModel: index from wrong model passed to mapToSource");
- return QModelIndex();
- }
- IndexMap::const_iterator it = index_to_iterator(proxy_index);
- Mapping *m = it.value();
- if ((proxy_index.row() >= m->source_rows.size()) || (proxy_index.column() >= m->source_columns.size()))
- return QModelIndex();
- int source_row = m->source_rows.at(proxy_index.row());
- int source_col = m->source_columns.at(proxy_index.column());
- return model->index(source_row, source_col, it.key());
-}
-
-QModelIndex QSortFilterProxyModelPrivate::source_to_proxy(const QModelIndex &source_index) const
-{
- if (!source_index.isValid())
- return QModelIndex(); // for now; we may want to be able to set a root index later
- if (source_index.model() != model) {
- qWarning() << "QSortFilterProxyModel: index from wrong model passed to mapFromSource";
- Q_ASSERT(!"QSortFilterProxyModel: index from wrong model passed to mapFromSource");
- return QModelIndex();
- }
- QModelIndex source_parent = source_index.parent();
- IndexMap::const_iterator it = create_mapping(source_parent);
- Mapping *m = it.value();
- if ((source_index.row() >= m->proxy_rows.size()) || (source_index.column() >= m->proxy_columns.size()))
- return QModelIndex();
- int proxy_row = m->proxy_rows.at(source_index.row());
- int proxy_column = m->proxy_columns.at(source_index.column());
- if (proxy_row == -1 || proxy_column == -1)
- return QModelIndex();
- return create_index(proxy_row, proxy_column, it);
-}
-
-bool QSortFilterProxyModelPrivate::can_create_mapping(const QModelIndex &source_parent) const
-{
- if (source_parent.isValid()) {
- QModelIndex source_grand_parent = source_parent.parent();
- IndexMap::const_iterator it = source_index_mapping.constFind(source_grand_parent);
- if (it == source_index_mapping.constEnd()) {
- // Don't care, since we don't have mapping for the grand parent
- return false;
- }
- Mapping *gm = it.value();
- if (gm->proxy_rows.at(source_parent.row()) == -1 ||
- gm->proxy_columns.at(source_parent.column()) == -1) {
- // Don't care, since parent is filtered
- return false;
- }
- }
- return true;
-}
-
-/*!
- \internal
-
- Sorts the existing mappings.
-*/
-void QSortFilterProxyModelPrivate::sort()
-{
- Q_Q(QSortFilterProxyModel);
- emit q->layoutAboutToBeChanged();
- QModelIndexPairList source_indexes = store_persistent_indexes();
- IndexMap::const_iterator it = source_index_mapping.constBegin();
- for (; it != source_index_mapping.constEnd(); ++it) {
- QModelIndex source_parent = it.key();
- Mapping *m = it.value();
- sort_source_rows(m->source_rows, source_parent);
- build_source_to_proxy_mapping(m->source_rows, m->proxy_rows);
- }
- update_persistent_indexes(source_indexes);
- emit q->layoutChanged();
-}
-
-/*!
- \internal
-
- update the source_sort_column according to the proxy_sort_column
- return true if the column was changed
-*/
-bool QSortFilterProxyModelPrivate::update_source_sort_column()
-{
- Q_Q(QSortFilterProxyModel);
- QModelIndex proxy_index = q->index(0, proxy_sort_column, QModelIndex());
- int old_source_sort_colum = source_sort_column;
- source_sort_column = q->mapToSource(proxy_index).column();
- return old_source_sort_colum != source_sort_column;
-}
-
-
-/*!
- \internal
-
- Sorts the given \a source_rows according to current sort column and order.
-*/
-void QSortFilterProxyModelPrivate::sort_source_rows(
- QVector<int> &source_rows, const QModelIndex &source_parent) const
-{
- Q_Q(const QSortFilterProxyModel);
- if (source_sort_column >= 0) {
- if (sort_order == Qt::AscendingOrder) {
- QSortFilterProxyModelLessThan lt(source_sort_column, source_parent, model, q);
- qStableSort(source_rows.begin(), source_rows.end(), lt);
- } else {
- QSortFilterProxyModelGreaterThan gt(source_sort_column, source_parent, model, q);
- qStableSort(source_rows.begin(), source_rows.end(), gt);
- }
- } else { // restore the source model order
- qStableSort(source_rows.begin(), source_rows.end());
- }
-}
-
-/*!
- \internal
-
- Given source-to-proxy mapping \a source_to_proxy and the set of
- source items \a source_items (which are part of that mapping),
- determines the corresponding proxy item intervals that should
- be removed from the proxy model.
-
- The result is a vector of pairs, where each pair represents a
- (start, end) tuple, sorted in ascending order.
-*/
-QVector<QPair<int, int > > QSortFilterProxyModelPrivate::proxy_intervals_for_source_items(
- const QVector<int> &source_to_proxy, const QVector<int> &source_items) const
-{
- QVector<QPair<int, int> > proxy_intervals;
- if (source_items.isEmpty())
- return proxy_intervals;
-
- int source_items_index = 0;
- while (source_items_index < source_items.size()) {
- int first_proxy_item = source_to_proxy.at(source_items.at(source_items_index));
- Q_ASSERT(first_proxy_item != -1);
- int last_proxy_item = first_proxy_item;
- ++source_items_index;
- // Find end of interval
- while ((source_items_index < source_items.size())
- && (source_to_proxy.at(source_items.at(source_items_index)) == last_proxy_item + 1)) {
- ++last_proxy_item;
- ++source_items_index;
- }
- // Add interval to result
- proxy_intervals.append(QPair<int, int>(first_proxy_item, last_proxy_item));
- }
- qStableSort(proxy_intervals.begin(), proxy_intervals.end());
- return proxy_intervals;
-}
-
-/*!
- \internal
-
- Given source-to-proxy mapping \a src_to_proxy and proxy-to-source mapping
- \a proxy_to_source, removes \a source_items from this proxy model.
- The corresponding proxy items are removed in intervals, so that the proper
- rows/columnsRemoved(start, end) signals will be generated.
-*/
-void QSortFilterProxyModelPrivate::remove_source_items(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- const QVector<int> &source_items, const QModelIndex &source_parent,
- Qt::Orientation orient, bool emit_signal)
-{
- Q_Q(QSortFilterProxyModel);
- QModelIndex proxy_parent = q->mapFromSource(source_parent);
- if (!proxy_parent.isValid() && source_parent.isValid())
- return; // nothing to do (already removed)
-
- QVector<QPair<int, int> > proxy_intervals;
- proxy_intervals = proxy_intervals_for_source_items(source_to_proxy, source_items);
-
- for (int i = proxy_intervals.size()-1; i >= 0; --i) {
- QPair<int, int> interval = proxy_intervals.at(i);
- int proxy_start = interval.first;
- int proxy_end = interval.second;
- remove_proxy_interval(source_to_proxy, proxy_to_source, proxy_start, proxy_end,
- proxy_parent, orient, emit_signal);
- }
-}
-
-/*!
- \internal
-
- Given source-to-proxy mapping \a source_to_proxy and proxy-to-source mapping
- \a proxy_to_source, removes items from \a proxy_start to \a proxy_end
- (inclusive) from this proxy model.
-*/
-void QSortFilterProxyModelPrivate::remove_proxy_interval(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, int proxy_start, int proxy_end,
- const QModelIndex &proxy_parent, Qt::Orientation orient, bool emit_signal)
-{
- Q_Q(QSortFilterProxyModel);
- if (emit_signal) {
- if (orient == Qt::Vertical)
- q->beginRemoveRows(proxy_parent, proxy_start, proxy_end);
- else
- q->beginRemoveColumns(proxy_parent, proxy_start, proxy_end);
- }
-
- // Remove items from proxy-to-source mapping
- proxy_to_source.remove(proxy_start, proxy_end - proxy_start + 1);
-
- build_source_to_proxy_mapping(proxy_to_source, source_to_proxy);
-
- if (emit_signal) {
- if (orient == Qt::Vertical)
- q->endRemoveRows();
- else
- q->endRemoveColumns();
- }
-}
-
-/*!
- \internal
-
- Given proxy-to-source mapping \a proxy_to_source and a set of
- unmapped source items \a source_items, determines the proxy item
- intervals at which the subsets of source items should be inserted
- (but does not actually add them to the mapping).
-
- The result is a vector of pairs, each pair representing a tuple (start,
- items), where items is a vector containing the (sorted) source items that
- should be inserted at that proxy model location.
-*/
-QVector<QPair<int, QVector<int > > > QSortFilterProxyModelPrivate::proxy_intervals_for_source_items_to_add(
- const QVector<int> &proxy_to_source, const QVector<int> &source_items,
- const QModelIndex &source_parent, Qt::Orientation orient) const
-{
- Q_Q(const QSortFilterProxyModel);
- QVector<QPair<int, QVector<int> > > proxy_intervals;
- if (source_items.isEmpty())
- return proxy_intervals;
-
- int proxy_low = 0;
- int proxy_item = 0;
- int source_items_index = 0;
- QVector<int> source_items_in_interval;
- bool compare = (orient == Qt::Vertical && source_sort_column >= 0 && dynamic_sortfilter);
- while (source_items_index < source_items.size()) {
- source_items_in_interval.clear();
- int first_new_source_item = source_items.at(source_items_index);
- source_items_in_interval.append(first_new_source_item);
- ++source_items_index;
-
- // Find proxy item at which insertion should be started
- int proxy_high = proxy_to_source.size() - 1;
- QModelIndex i1 = compare ? model->index(first_new_source_item, source_sort_column, source_parent) : QModelIndex();
- while (proxy_low <= proxy_high) {
- proxy_item = (proxy_low + proxy_high) / 2;
- if (compare) {
- QModelIndex i2 = model->index(proxy_to_source.at(proxy_item), source_sort_column, source_parent);
- if ((sort_order == Qt::AscendingOrder) ? q->lessThan(i1, i2) : q->lessThan(i2, i1))
- proxy_high = proxy_item - 1;
- else
- proxy_low = proxy_item + 1;
- } else {
- if (first_new_source_item < proxy_to_source.at(proxy_item))
- proxy_high = proxy_item - 1;
- else
- proxy_low = proxy_item + 1;
- }
- }
- proxy_item = proxy_low;
-
- // Find the sequence of new source items that should be inserted here
- if (proxy_item >= proxy_to_source.size()) {
- for ( ; source_items_index < source_items.size(); ++source_items_index)
- source_items_in_interval.append(source_items.at(source_items_index));
- } else {
- i1 = compare ? model->index(proxy_to_source.at(proxy_item), source_sort_column, source_parent) : QModelIndex();
- for ( ; source_items_index < source_items.size(); ++source_items_index) {
- int new_source_item = source_items.at(source_items_index);
- if (compare) {
- QModelIndex i2 = model->index(new_source_item, source_sort_column, source_parent);
- if ((sort_order == Qt::AscendingOrder) ? q->lessThan(i1, i2) : q->lessThan(i2, i1))
- break;
- } else {
- if (proxy_to_source.at(proxy_item) < new_source_item)
- break;
- }
- source_items_in_interval.append(new_source_item);
- }
- }
-
- // Add interval to result
- proxy_intervals.append(QPair<int, QVector<int> >(proxy_item, source_items_in_interval));
- }
- return proxy_intervals;
-}
-
-/*!
- \internal
-
- Given source-to-proxy mapping \a source_to_proxy and proxy-to-source mapping
- \a proxy_to_source, inserts the given \a source_items into this proxy model.
- The source items are inserted in intervals (based on some sorted order), so
- that the proper rows/columnsInserted(start, end) signals will be generated.
-*/
-void QSortFilterProxyModelPrivate::insert_source_items(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- const QVector<int> &source_items, const QModelIndex &source_parent,
- Qt::Orientation orient, bool emit_signal)
-{
- Q_Q(QSortFilterProxyModel);
- QModelIndex proxy_parent = q->mapFromSource(source_parent);
- if (!proxy_parent.isValid() && source_parent.isValid())
- return; // nothing to do (source_parent is not mapped)
-
- QVector<QPair<int, QVector<int> > > proxy_intervals;
- proxy_intervals = proxy_intervals_for_source_items_to_add(
- proxy_to_source, source_items, source_parent, orient);
-
- for (int i = proxy_intervals.size()-1; i >= 0; --i) {
- QPair<int, QVector<int> > interval = proxy_intervals.at(i);
- int proxy_start = interval.first;
- QVector<int> source_items = interval.second;
- int proxy_end = proxy_start + source_items.size() - 1;
-
- if (emit_signal) {
- if (orient == Qt::Vertical)
- q->beginInsertRows(proxy_parent, proxy_start, proxy_end);
- else
- q->beginInsertColumns(proxy_parent, proxy_start, proxy_end);
- }
-
- for (int i = 0; i < source_items.size(); ++i)
- proxy_to_source.insert(proxy_start + i, source_items.at(i));
-
- build_source_to_proxy_mapping(proxy_to_source, source_to_proxy);
-
- if (emit_signal) {
- if (orient == Qt::Vertical)
- q->endInsertRows();
- else
- q->endInsertColumns();
- }
- }
-}
-
-/*!
- \internal
-
- Handles source model items insertion (columnsInserted(), rowsInserted()).
- Determines
- 1) which of the inserted items to also insert into proxy model (filtering),
- 2) where to insert the items into the proxy model (sorting),
- then inserts those items.
- The items are inserted into the proxy model in intervals (based on
- sorted order), so that the proper rows/columnsInserted(start, end)
- signals will be generated.
-*/
-void QSortFilterProxyModelPrivate::source_items_inserted(
- const QModelIndex &source_parent, int start, int end, Qt::Orientation orient)
-{
- Q_Q(QSortFilterProxyModel);
- if ((start < 0) || (end < 0))
- return;
- IndexMap::const_iterator it = source_index_mapping.constFind(source_parent);
- if (it == source_index_mapping.constEnd()) {
- if (!can_create_mapping(source_parent))
- return;
- it = create_mapping(source_parent);
- Mapping *m = it.value();
- QModelIndex proxy_parent = q->mapFromSource(source_parent);
- if (m->source_rows.count() > 0) {
- q->beginInsertRows(proxy_parent, 0, m->source_rows.count() - 1);
- q->endInsertRows();
- }
- if (m->source_columns.count() > 0) {
- q->beginInsertColumns(proxy_parent, 0, m->source_columns.count() - 1);
- q->endInsertColumns();
- }
- return;
- }
-
- Mapping *m = it.value();
- QVector<int> &source_to_proxy = (orient == Qt::Vertical) ? m->proxy_rows : m->proxy_columns;
- QVector<int> &proxy_to_source = (orient == Qt::Vertical) ? m->source_rows : m->source_columns;
-
- int delta_item_count = end - start + 1;
- int old_item_count = source_to_proxy.size();
-
- updateChildrenMapping(source_parent, m, orient, start, end, delta_item_count, false);
-
- // Expand source-to-proxy mapping to account for new items
- if (start < 0 || start > source_to_proxy.size()) {
- qWarning("QSortFilterProxyModel: invalid inserted rows reported by source model");
- remove_from_mapping(source_parent);
- return;
- }
- source_to_proxy.insert(start, delta_item_count, -1);
-
- if (start < old_item_count) {
- // Adjust existing "stale" indexes in proxy-to-source mapping
- int proxy_count = proxy_to_source.size();
- for (int proxy_item = 0; proxy_item < proxy_count; ++proxy_item) {
- int source_item = proxy_to_source.at(proxy_item);
- if (source_item >= start)
- proxy_to_source.replace(proxy_item, source_item + delta_item_count);
- }
- build_source_to_proxy_mapping(proxy_to_source, source_to_proxy);
- }
-
- // Figure out which items to add to mapping based on filter
- QVector<int> source_items;
- for (int i = start; i <= end; ++i) {
- if ((orient == Qt::Vertical)
- ? q->filterAcceptsRow(i, source_parent)
- : q->filterAcceptsColumn(i, source_parent)) {
- source_items.append(i);
- }
- }
-
- if (model->rowCount(source_parent) == delta_item_count) {
- // Items were inserted where there were none before.
- // If it was new rows make sure to create mappings for columns so that a
- // valid mapping can be retrieved later and vice-versa.
-
- QVector<int> &orthogonal_proxy_to_source = (orient == Qt::Horizontal) ? m->source_rows : m->source_columns;
- QVector<int> &orthogonal_source_to_proxy = (orient == Qt::Horizontal) ? m->proxy_rows : m->proxy_columns;
-
- if (orthogonal_source_to_proxy.isEmpty()) {
- const int ortho_end = (orient == Qt::Horizontal) ? model->rowCount(source_parent) : model->columnCount(source_parent);
-
- orthogonal_source_to_proxy.resize(ortho_end);
-
- for (int ortho_item = 0; ortho_item < ortho_end; ++ortho_item) {
- if ((orient == Qt::Horizontal) ? q->filterAcceptsRow(ortho_item, source_parent)
- : q->filterAcceptsColumn(ortho_item, source_parent)) {
- orthogonal_proxy_to_source.append(ortho_item);
- }
- }
- if (orient == Qt::Horizontal) {
- // We're reacting to columnsInserted, but we've just inserted new rows. Sort them.
- sort_source_rows(orthogonal_proxy_to_source, source_parent);
- }
- build_source_to_proxy_mapping(orthogonal_proxy_to_source, orthogonal_source_to_proxy);
- }
- }
-
- // Sort and insert the items
- if (orient == Qt::Vertical) // Only sort rows
- sort_source_rows(source_items, source_parent);
- insert_source_items(source_to_proxy, proxy_to_source, source_items, source_parent, orient);
-}
-
-/*!
- \internal
-
- Handles source model items removal
- (columnsAboutToBeRemoved(), rowsAboutToBeRemoved()).
-*/
-void QSortFilterProxyModelPrivate::source_items_about_to_be_removed(
- const QModelIndex &source_parent, int start, int end, Qt::Orientation orient)
-{
- if ((start < 0) || (end < 0))
- return;
- IndexMap::const_iterator it = source_index_mapping.constFind(source_parent);
- if (it == source_index_mapping.constEnd()) {
- // Don't care, since we don't have mapping for this index
- return;
- }
-
- Mapping *m = it.value();
- QVector<int> &source_to_proxy = (orient == Qt::Vertical) ? m->proxy_rows : m->proxy_columns;
- QVector<int> &proxy_to_source = (orient == Qt::Vertical) ? m->source_rows : m->source_columns;
-
- // figure out which items to remove
- QVector<int> source_items_to_remove;
- int proxy_count = proxy_to_source.size();
- for (int proxy_item = 0; proxy_item < proxy_count; ++proxy_item) {
- int source_item = proxy_to_source.at(proxy_item);
- if ((source_item >= start) && (source_item <= end))
- source_items_to_remove.append(source_item);
- }
-
- remove_source_items(source_to_proxy, proxy_to_source, source_items_to_remove,
- source_parent, orient);
-}
-
-/*!
- \internal
-
- Handles source model items removal (columnsRemoved(), rowsRemoved()).
-*/
-void QSortFilterProxyModelPrivate::source_items_removed(
- const QModelIndex &source_parent, int start, int end, Qt::Orientation orient)
-{
- if ((start < 0) || (end < 0))
- return;
- IndexMap::const_iterator it = source_index_mapping.constFind(source_parent);
- if (it == source_index_mapping.constEnd()) {
- // Don't care, since we don't have mapping for this index
- return;
- }
-
- Mapping *m = it.value();
- QVector<int> &source_to_proxy = (orient == Qt::Vertical) ? m->proxy_rows : m->proxy_columns;
- QVector<int> &proxy_to_source = (orient == Qt::Vertical) ? m->source_rows : m->source_columns;
-
- if (end >= source_to_proxy.size())
- end = source_to_proxy.size() - 1;
-
- // Shrink the source-to-proxy mapping to reflect the new item count
- int delta_item_count = end - start + 1;
- source_to_proxy.remove(start, delta_item_count);
-
- int proxy_count = proxy_to_source.size();
- if (proxy_count > source_to_proxy.size()) {
- // mapping is in an inconsistent state -- redo the whole mapping
- qWarning("QSortFilterProxyModel: inconsistent changes reported by source model");
- remove_from_mapping(source_parent);
- Q_Q(QSortFilterProxyModel);
- q->reset();
- return;
- }
-
- // Adjust "stale" indexes in proxy-to-source mapping
- for (int proxy_item = 0; proxy_item < proxy_count; ++proxy_item) {
- int source_item = proxy_to_source.at(proxy_item);
- if (source_item >= start) {
- Q_ASSERT(source_item - delta_item_count >= 0);
- proxy_to_source.replace(proxy_item, source_item - delta_item_count);
- }
- }
- build_source_to_proxy_mapping(proxy_to_source, source_to_proxy);
-
- updateChildrenMapping(source_parent, m, orient, start, end, delta_item_count, true);
-
-}
-
-
-/*!
- \internal
- updates the mapping of the children when inserting or removing items
-*/
-void QSortFilterProxyModelPrivate::updateChildrenMapping(const QModelIndex &source_parent, Mapping *parent_mapping,
- Qt::Orientation orient, int start, int end, int delta_item_count, bool remove)
-{
- // see if any mapped children should be (re)moved
- QVector<QPair<QModelIndex, Mapping*> > moved_source_index_mappings;
- QVector<QModelIndex>::iterator it2 = parent_mapping->mapped_children.begin();
- for ( ; it2 != parent_mapping->mapped_children.end();) {
- const QModelIndex source_child_index = *it2;
- const int pos = (orient == Qt::Vertical)
- ? source_child_index.row()
- : source_child_index.column();
- if (pos < start) {
- // not affected
- ++it2;
- } else if (remove && pos <= end) {
- // in the removed interval
- it2 = parent_mapping->mapped_children.erase(it2);
- remove_from_mapping(source_child_index);
- } else {
- // below the removed items -- recompute the index
- QModelIndex new_index;
- const int newpos = remove ? pos - delta_item_count : pos + delta_item_count;
- if (orient == Qt::Vertical) {
- new_index = model->index(newpos,
- source_child_index.column(),
- source_parent);
- } else {
- new_index = model->index(source_child_index.row(),
- newpos,
- source_parent);
- }
- *it2 = new_index;
- ++it2;
-
- // update mapping
- Mapping *cm = source_index_mapping.take(source_child_index);
- Q_ASSERT(cm);
- // we do not reinsert right away, because the new index might be identical with another, old index
- moved_source_index_mappings.append(QPair<QModelIndex, Mapping*>(new_index, cm));
- }
- }
-
- // reinsert moved, mapped indexes
- QVector<QPair<QModelIndex, Mapping*> >::iterator it = moved_source_index_mappings.begin();
- for (; it != moved_source_index_mappings.end(); ++it) {
-#ifdef QT_STRICT_ITERATORS
- source_index_mapping.insert((*it).first, (*it).second);
- (*it).second->map_iter = source_index_mapping.constFind((*it).first);
-#else
- (*it).second->map_iter = source_index_mapping.insert((*it).first, (*it).second);
-#endif
- }
-}
-
-/*!
- \internal
-*/
-void QSortFilterProxyModelPrivate::proxy_item_range(
- const QVector<int> &source_to_proxy, const QVector<int> &source_items,
- int &proxy_low, int &proxy_high) const
-{
- proxy_low = INT_MAX;
- proxy_high = INT_MIN;
- for (int i = 0; i < source_items.count(); ++i) {
- int proxy_item = source_to_proxy.at(source_items.at(i));
- Q_ASSERT(proxy_item != -1);
- if (proxy_item < proxy_low)
- proxy_low = proxy_item;
- if (proxy_item > proxy_high)
- proxy_high = proxy_item;
- }
-}
-
-/*!
- \internal
-*/
-void QSortFilterProxyModelPrivate::build_source_to_proxy_mapping(
- const QVector<int> &proxy_to_source, QVector<int> &source_to_proxy) const
-{
- source_to_proxy.fill(-1);
- int proxy_count = proxy_to_source.size();
- for (int i = 0; i < proxy_count; ++i)
- source_to_proxy[proxy_to_source.at(i)] = i;
-}
-
-/*!
- \internal
-
- Maps the persistent proxy indexes to source indexes and
- returns the list of source indexes.
-*/
-QModelIndexPairList QSortFilterProxyModelPrivate::store_persistent_indexes()
-{
- Q_Q(QSortFilterProxyModel);
- QModelIndexPairList source_indexes;
- foreach (QPersistentModelIndexData *data, persistent.indexes) {
- QModelIndex proxy_index = data->index;
- QModelIndex source_index = q->mapToSource(proxy_index);
- source_indexes.append(qMakePair(proxy_index, QPersistentModelIndex(source_index)));
- }
- return source_indexes;
-}
-
-/*!
- \internal
-
- Maps \a source_indexes to proxy indexes and stores those
- as persistent indexes.
-*/
-void QSortFilterProxyModelPrivate::update_persistent_indexes(
- const QModelIndexPairList &source_indexes)
-{
- Q_Q(QSortFilterProxyModel);
- QModelIndexList from, to;
- for (int i = 0; i < source_indexes.count(); ++i) {
- QModelIndex source_index = source_indexes.at(i).second;
- QModelIndex old_proxy_index = source_indexes.at(i).first;
- create_mapping(source_index.parent());
- QModelIndex proxy_index = q->mapFromSource(source_index);
- from << old_proxy_index;
- to << proxy_index;
- }
- q->changePersistentIndexList(from, to);
-}
-
-
-/*!
- \internal
-
- Updates the proxy model (adds/removes rows) based on the
- new filter.
-*/
-void QSortFilterProxyModelPrivate::filter_changed(const QModelIndex &source_parent)
-{
- IndexMap::const_iterator it = source_index_mapping.constFind(source_parent);
- if (it == source_index_mapping.constEnd())
- return;
- Mapping *m = it.value();
- QSet<int> rows_removed = handle_filter_changed(m->proxy_rows, m->source_rows, source_parent, Qt::Vertical);
- QSet<int> columns_removed = handle_filter_changed(m->proxy_columns, m->source_columns, source_parent, Qt::Horizontal);
- QVector<QModelIndex>::iterator it2 = m->mapped_children.end();
- while (it2 != m->mapped_children.begin()) {
- --it2;
- const QModelIndex source_child_index = *it2;
- if (rows_removed.contains(source_child_index.row()) || columns_removed.contains(source_child_index.column())) {
- it2 = m->mapped_children.erase(it2);
- remove_from_mapping(source_child_index);
- } else {
- filter_changed(source_child_index);
- }
- }
-}
-
-/*!
- \internal
- returns the removed items indexes
-*/
-QSet<int> QSortFilterProxyModelPrivate::handle_filter_changed(
- QVector<int> &source_to_proxy, QVector<int> &proxy_to_source,
- const QModelIndex &source_parent, Qt::Orientation orient)
-{
- Q_Q(QSortFilterProxyModel);
- // Figure out which mapped items to remove
- QVector<int> source_items_remove;
- for (int i = 0; i < proxy_to_source.count(); ++i) {
- const int source_item = proxy_to_source.at(i);
- if ((orient == Qt::Vertical)
- ? !q->filterAcceptsRow(source_item, source_parent)
- : !q->filterAcceptsColumn(source_item, source_parent)) {
- // This source item does not satisfy the filter, so it must be removed
- source_items_remove.append(source_item);
- }
- }
- // Figure out which non-mapped items to insert
- QVector<int> source_items_insert;
- int source_count = source_to_proxy.size();
- for (int source_item = 0; source_item < source_count; ++source_item) {
- if (source_to_proxy.at(source_item) == -1) {
- if ((orient == Qt::Vertical)
- ? q->filterAcceptsRow(source_item, source_parent)
- : q->filterAcceptsColumn(source_item, source_parent)) {
- // This source item satisfies the filter, so it must be added
- source_items_insert.append(source_item);
- }
- }
- }
- if (!source_items_remove.isEmpty() || !source_items_insert.isEmpty()) {
- // Do item removal and insertion
- remove_source_items(source_to_proxy, proxy_to_source,
- source_items_remove, source_parent, orient);
- if (orient == Qt::Vertical)
- sort_source_rows(source_items_insert, source_parent);
- insert_source_items(source_to_proxy, proxy_to_source,
- source_items_insert, source_parent, orient);
- }
- return qVectorToSet(source_items_remove);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceDataChanged(const QModelIndex &source_top_left,
- const QModelIndex &source_bottom_right)
-{
- Q_Q(QSortFilterProxyModel);
- if (!source_top_left.isValid() || !source_bottom_right.isValid())
- return;
- QModelIndex source_parent = source_top_left.parent();
- IndexMap::const_iterator it = source_index_mapping.find(source_parent);
- if (it == source_index_mapping.constEnd()) {
- // Don't care, since we don't have mapping for this index
- return;
- }
- Mapping *m = it.value();
-
- // Figure out how the source changes affect us
- QVector<int> source_rows_remove;
- QVector<int> source_rows_insert;
- QVector<int> source_rows_change;
- QVector<int> source_rows_resort;
- int end = qMin(source_bottom_right.row(), m->proxy_rows.count() - 1);
- for (int source_row = source_top_left.row(); source_row <= end; ++source_row) {
- if (dynamic_sortfilter) {
- if (m->proxy_rows.at(source_row) != -1) {
- if (!q->filterAcceptsRow(source_row, source_parent)) {
- // This source row no longer satisfies the filter, so it must be removed
- source_rows_remove.append(source_row);
- } else if (source_sort_column >= source_top_left.column() && source_sort_column <= source_bottom_right.column()) {
- // This source row has changed in a way that may affect sorted order
- source_rows_resort.append(source_row);
- } else {
- // This row has simply changed, without affecting filtering nor sorting
- source_rows_change.append(source_row);
- }
- } else {
- if (!itemsBeingRemoved.contains(source_parent, source_row) && q->filterAcceptsRow(source_row, source_parent)) {
- // This source row now satisfies the filter, so it must be added
- source_rows_insert.append(source_row);
- }
- }
- } else {
- if (m->proxy_rows.at(source_row) != -1)
- source_rows_change.append(source_row);
- }
- }
-
- if (!source_rows_remove.isEmpty()) {
- remove_source_items(m->proxy_rows, m->source_rows,
- source_rows_remove, source_parent, Qt::Vertical);
- QSet<int> source_rows_remove_set = qVectorToSet(source_rows_remove);
- QVector<QModelIndex>::iterator it = m->mapped_children.end();
- while (it != m->mapped_children.begin()) {
- --it;
- const QModelIndex source_child_index = *it;
- if (source_rows_remove_set.contains(source_child_index.row())) {
- it = m->mapped_children.erase(it);
- remove_from_mapping(source_child_index);
- }
- }
- }
-
- if (!source_rows_resort.isEmpty()) {
- // Re-sort the rows
- emit q->layoutAboutToBeChanged();
- QModelIndexPairList source_indexes = store_persistent_indexes();
- remove_source_items(m->proxy_rows, m->source_rows, source_rows_resort,
- source_parent, Qt::Vertical, false);
- sort_source_rows(source_rows_resort, source_parent);
- insert_source_items(m->proxy_rows, m->source_rows, source_rows_resort,
- source_parent, Qt::Vertical, false);
- update_persistent_indexes(source_indexes);
- emit q->layoutChanged();
- // Make sure we also emit dataChanged for the rows
- source_rows_change += source_rows_resort;
- }
-
- if (!source_rows_change.isEmpty()) {
- // Find the proxy row range
- int proxy_start_row;
- int proxy_end_row;
- proxy_item_range(m->proxy_rows, source_rows_change,
- proxy_start_row, proxy_end_row);
- // ### Find the proxy column range also
- if (proxy_end_row >= 0) {
- // the row was accepted, but some columns might still be filtered out
- int source_left_column = source_top_left.column();
- while (source_left_column < source_bottom_right.column()
- && m->proxy_columns.at(source_left_column) == -1)
- ++source_left_column;
- const QModelIndex proxy_top_left = create_index(
- proxy_start_row, m->proxy_columns.at(source_left_column), it);
- int source_right_column = source_bottom_right.column();
- while (source_right_column > source_top_left.column()
- && m->proxy_columns.at(source_right_column) == -1)
- --source_right_column;
- const QModelIndex proxy_bottom_right = create_index(
- proxy_end_row, m->proxy_columns.at(source_right_column), it);
- emit q->dataChanged(proxy_top_left, proxy_bottom_right);
- }
- }
-
- if (!source_rows_insert.isEmpty()) {
- sort_source_rows(source_rows_insert, source_parent);
- insert_source_items(m->proxy_rows, m->source_rows,
- source_rows_insert, source_parent, Qt::Vertical);
- }
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceHeaderDataChanged(Qt::Orientation orientation,
- int start, int end)
-{
- Q_Q(QSortFilterProxyModel);
- Mapping *m = create_mapping(QModelIndex()).value();
- int proxy_start = (orientation == Qt::Vertical
- ? m->proxy_rows.at(start)
- : m->proxy_columns.at(start));
- int proxy_end = (orientation == Qt::Vertical
- ? m->proxy_rows.at(end)
- : m->proxy_columns.at(end));
- emit q->headerDataChanged(orientation, proxy_start, proxy_end);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceAboutToBeReset()
-{
- Q_Q(QSortFilterProxyModel);
- q->beginResetModel();
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceReset()
-{
- Q_Q(QSortFilterProxyModel);
- invalidatePersistentIndexes();
- _q_clearMapping();
- // All internal structures are deleted in clear()
- q->endResetModel();
- update_source_sort_column();
- if (dynamic_sortfilter)
- sort();
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceLayoutAboutToBeChanged()
-{
- Q_Q(QSortFilterProxyModel);
- saved_persistent_indexes.clear();
- emit q->layoutAboutToBeChanged();
- if (persistent.indexes.isEmpty())
- return;
-
- saved_persistent_indexes = store_persistent_indexes();
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceLayoutChanged()
-{
- Q_Q(QSortFilterProxyModel);
-
- qDeleteAll(source_index_mapping);
- source_index_mapping.clear();
-
- update_persistent_indexes(saved_persistent_indexes);
- saved_persistent_indexes.clear();
-
- if (dynamic_sortfilter && update_source_sort_column()) {
- //update_source_sort_column might have created wrong mapping so we have to clear it again
- qDeleteAll(source_index_mapping);
- source_index_mapping.clear();
- }
-
- emit q->layoutChanged();
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceRowsAboutToBeInserted(
- const QModelIndex &source_parent, int start, int end)
-{
- Q_UNUSED(start);
- Q_UNUSED(end);
- //Force the creation of a mapping now, even if its empty.
- //We need it because the proxy can be acessed at the moment it emits rowsAboutToBeInserted in insert_source_items
- if (can_create_mapping(source_parent))
- create_mapping(source_parent);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceRowsInserted(
- const QModelIndex &source_parent, int start, int end)
-{
- source_items_inserted(source_parent, start, end, Qt::Vertical);
- if (update_source_sort_column() && dynamic_sortfilter) //previous call to update_source_sort_column may fail if the model has no column.
- sort(); // now it should succeed so we need to make sure to sort again
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceRowsAboutToBeRemoved(
- const QModelIndex &source_parent, int start, int end)
-{
- itemsBeingRemoved = QRowsRemoval(source_parent, start, end);
- source_items_about_to_be_removed(source_parent, start, end,
- Qt::Vertical);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceRowsRemoved(
- const QModelIndex &source_parent, int start, int end)
-{
- itemsBeingRemoved = QRowsRemoval();
- source_items_removed(source_parent, start, end, Qt::Vertical);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceColumnsAboutToBeInserted(
- const QModelIndex &source_parent, int start, int end)
-{
- Q_UNUSED(start);
- Q_UNUSED(end);
- //Force the creation of a mapping now, even if its empty.
- //We need it because the proxy can be acessed at the moment it emits columnsAboutToBeInserted in insert_source_items
- if (can_create_mapping(source_parent))
- create_mapping(source_parent);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceColumnsInserted(
- const QModelIndex &source_parent, int start, int end)
-{
- Q_Q(const QSortFilterProxyModel);
- source_items_inserted(source_parent, start, end, Qt::Horizontal);
-
- if (source_parent.isValid())
- return; //we sort according to the root column only
- if (source_sort_column == -1) {
- //we update the source_sort_column depending on the proxy_sort_column
- if (update_source_sort_column() && dynamic_sortfilter)
- sort();
- } else {
- if (start <= source_sort_column)
- source_sort_column += end - start + 1;
-
- proxy_sort_column = q->mapFromSource(model->index(0,source_sort_column, source_parent)).column();
- }
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceColumnsAboutToBeRemoved(
- const QModelIndex &source_parent, int start, int end)
-{
- source_items_about_to_be_removed(source_parent, start, end,
- Qt::Horizontal);
-}
-
-void QSortFilterProxyModelPrivate::_q_sourceColumnsRemoved(
- const QModelIndex &source_parent, int start, int end)
-{
- Q_Q(const QSortFilterProxyModel);
- source_items_removed(source_parent, start, end, Qt::Horizontal);
-
- if (source_parent.isValid())
- return; //we sort according to the root column only
- if (start <= source_sort_column) {
- if (end < source_sort_column)
- source_sort_column -= end - start + 1;
- else
- source_sort_column = -1;
- }
-
- proxy_sort_column = q->mapFromSource(model->index(0,source_sort_column, source_parent)).column();
-}
-
-/*!
- \since 4.1
- \class QSortFilterProxyModel
- \brief The QSortFilterProxyModel class provides support for sorting and
- filtering data passed between another model and a view.
-
- \ingroup model-view
-
- QSortFilterProxyModel can be used for sorting items, filtering out items,
- or both. The model transforms the structure of a source model by mapping
- the model indexes it supplies to new indexes, corresponding to different
- locations, for views to use. This approach allows a given source model to
- be restructured as far as views are concerned without requiring any
- transformations on the underlying data, and without duplicating the data in
- memory.
-
- Let's assume that we want to sort and filter the items provided by a custom
- model. The code to set up the model and the view, \e without sorting and
- filtering, would look like this:
-
- \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 1
-
- To add sorting and filtering support to \c MyItemModel, we need to create
- a QSortFilterProxyModel, call setSourceModel() with the \c MyItemModel as
- argument, and install the QSortFilterProxyModel on the view:
-
- \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 0
- \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 2
-
- At this point, neither sorting nor filtering is enabled; the original data
- is displayed in the view. Any changes made through the
- QSortFilterProxyModel are applied to the original model.
-
- The QSortFilterProxyModel acts as a wrapper for the original model. If you
- need to convert source \l{QModelIndex}es to sorted/filtered model indexes
- or vice versa, use mapToSource(), mapFromSource(), mapSelectionToSource(),
- and mapSelectionFromSource().
-
- \note By default, the model does not dynamically re-sort and re-filter data
- whenever the original model changes. This behavior can be changed by
- setting the \l{QSortFilterProxyModel::dynamicSortFilter}{dynamicSortFilter}
- property.
-
- The \l{itemviews/basicsortfiltermodel}{Basic Sort/Filter Model} and
- \l{itemviews/customsortfiltermodel}{Custom Sort/Filter Model} examples
- illustrate how to use QSortFilterProxyModel to perform basic sorting and
- filtering and how to subclass it to implement custom behavior.
-
- \section1 Sorting
-
- QTableView and QTreeView have a
- \l{QTreeView::sortingEnabled}{sortingEnabled} property that controls
- whether the user can sort the view by clicking the view's horizontal
- header. For example:
-
- \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 3
-
- When this feature is on (the default is off), clicking on a header section
- sorts the items according to that column. By clicking repeatedly, the user
- can alternate between ascending and descending order.
-
- \image qsortfilterproxymodel-sorting.png A sorted QTreeView
-
- Behind the scene, the view calls the sort() virtual function on the model
- to reorder the data in the model. To make your data sortable, you can
- either implement sort() in your model, or use a QSortFilterProxyModel to
- wrap your model -- QSortFilterProxyModel provides a generic sort()
- reimplementation that operates on the sortRole() (Qt::DisplayRole by
- default) of the items and that understands several data types, including
- \c int, QString, and QDateTime. For hierarchical models, sorting is applied
- recursively to all child items. String comparisons are case sensitive by
- default; this can be changed by setting the \l{QSortFilterProxyModel::}
- {sortCaseSensitivity} property.
-
- Custom sorting behavior is achieved by subclassing
- QSortFilterProxyModel and reimplementing lessThan(), which is
- used to compare items. For example:
-
- \snippet examples/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp 5
-
- (This code snippet comes from the
- \l{itemviews/customsortfiltermodel}{Custom Sort/Filter Model}
- example.)
-
- An alternative approach to sorting is to disable sorting on the view and to
- impose a certain order to the user. This is done by explicitly calling
- sort() with the desired column and order as arguments on the
- QSortFilterProxyModel (or on the original model if it implements sort()).
- For example:
-
- \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 4
-
- QSortFilterProxyModel can be sorted by column -1, in which case it returns
- to the sort order of the underlying source model.
-
- \section1 Filtering
-
- In addition to sorting, QSortFilterProxyModel can be used to hide items
- that do not match a certain filter. The filter is specified using a QRegExp
- object and is applied to the filterRole() (Qt::DisplayRole by default) of
- each item, for a given column. The QRegExp object can be used to match a
- regular expression, a wildcard pattern, or a fixed string. For example:
-
- \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 5
-
- For hierarchical models, the filter is applied recursively to all children.
- If a parent item doesn't match the filter, none of its children will be
- shown.
-
- A common use case is to let the user specify the filter regexp, wildcard
- pattern, or fixed string in a QLineEdit and to connect the
- \l{QLineEdit::textChanged()}{textChanged()} signal to setFilterRegExp(),
- setFilterWildcard(), or setFilterFixedString() to reapply the filter.
-
- Custom filtering behavior can be achieved by reimplementing the
- filterAcceptsRow() and filterAcceptsColumn() functions. For
- example (from the \l{itemviews/customsortfiltermodel}
- {Custom Sort/Filter Model} example), the following implementation ignores
- the \l{QSortFilterProxyModel::filterKeyColumn}{filterKeyColumn} property
- and performs filtering on columns 0, 1, and 2:
-
- \snippet examples/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp 3
-
- (This code snippet comes from the
- \l{itemviews/customsortfiltermodel}{Custom Sort/Filter Model}
- example.)
-
- If you are working with large amounts of filtering and have to invoke
- invalidateFilter() repeatedly, using reset() may be more efficient,
- depending on the implementation of your model. However, reset() returns the
- proxy model to its original state, losing selection information, and will
- cause the proxy model to be repopulated.
-
- \section1 Subclassing
-
- Since QAbstractProxyModel and its subclasses are derived from
- QAbstractItemModel, much of the same advice about subclassing normal models
- also applies to proxy models. In addition, it is worth noting that many of
- the default implementations of functions in this class are written so that
- they call the equivalent functions in the relevant source model. This
- simple proxying mechanism may need to be overridden for source models with
- more complex behavior; for example, if the source model provides a custom
- hasChildren() implementation, you should also provide one in the proxy
- model.
-
- \note Some general guidelines for subclassing models are available in the
- \l{Model Subclassing Reference}.
-
- \sa QAbstractProxyModel, QAbstractItemModel, {Model/View Programming},
- {Basic Sort/Filter Model Example}, {Custom Sort/Filter Model Example}
-*/
-
-/*!
- Constructs a sorting filter model with the given \a parent.
-*/
-
-QSortFilterProxyModel::QSortFilterProxyModel(QObject *parent)
- : QAbstractProxyModel(*new QSortFilterProxyModelPrivate, parent)
-{
- Q_D(QSortFilterProxyModel);
- d->proxy_sort_column = d->source_sort_column = -1;
- d->sort_order = Qt::AscendingOrder;
- d->sort_casesensitivity = Qt::CaseSensitive;
- d->sort_role = Qt::DisplayRole;
- d->sort_localeaware = false;
- d->filter_column = 0;
- d->filter_role = Qt::DisplayRole;
- d->dynamic_sortfilter = false;
- connect(this, SIGNAL(modelReset()), this, SLOT(_q_clearMapping()));
-}
-
-/*!
- Destroys this sorting filter model.
-*/
-QSortFilterProxyModel::~QSortFilterProxyModel()
-{
- Q_D(QSortFilterProxyModel);
- qDeleteAll(d->source_index_mapping);
- d->source_index_mapping.clear();
-}
-
-/*!
- \reimp
-*/
-void QSortFilterProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
-{
- Q_D(QSortFilterProxyModel);
-
- beginResetModel();
-
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
-
- disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(_q_sourceHeaderDataChanged(Qt::Orientation,int,int)));
-
- disconnect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeInserted(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsInserted(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeInserted(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsInserted(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsRemoved(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeRemoved(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsRemoved(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(layoutAboutToBeChanged()),
- this, SLOT(_q_sourceLayoutAboutToBeChanged()));
-
- disconnect(d->model, SIGNAL(layoutChanged()),
- this, SLOT(_q_sourceLayoutChanged()));
-
- disconnect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_sourceAboutToBeReset()));
- disconnect(d->model, SIGNAL(modelReset()), this, SLOT(_q_sourceReset()));
-
- QAbstractProxyModel::setSourceModel(sourceModel);
-
- connect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
-
- connect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- this, SLOT(_q_sourceHeaderDataChanged(Qt::Orientation,int,int)));
-
- connect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeInserted(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsInserted(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeInserted(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsInserted(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceRowsRemoved(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsAboutToBeRemoved(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sourceColumnsRemoved(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(layoutAboutToBeChanged()),
- this, SLOT(_q_sourceLayoutAboutToBeChanged()));
-
- connect(d->model, SIGNAL(layoutChanged()),
- this, SLOT(_q_sourceLayoutChanged()));
-
- connect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_sourceAboutToBeReset()));
- connect(d->model, SIGNAL(modelReset()), this, SLOT(_q_sourceReset()));
-
- d->_q_clearMapping();
- endResetModel();
- if (d->update_source_sort_column() && d->dynamic_sortfilter)
- d->sort();
-}
-
-/*!
- \reimp
-*/
-QModelIndex QSortFilterProxyModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QSortFilterProxyModel);
- if (row < 0 || column < 0)
- return QModelIndex();
-
- QModelIndex source_parent = mapToSource(parent); // parent is already mapped at this point
- IndexMap::const_iterator it = d->create_mapping(source_parent); // but make sure that the children are mapped
- if (it.value()->source_rows.count() <= row || it.value()->source_columns.count() <= column)
- return QModelIndex();
-
- return d->create_index(row, column, it);
-}
-
-/*!
- \reimp
-*/
-QModelIndex QSortFilterProxyModel::parent(const QModelIndex &child) const
-{
- Q_D(const QSortFilterProxyModel);
- if (!d->indexValid(child))
- return QModelIndex();
- IndexMap::const_iterator it = d->index_to_iterator(child);
- Q_ASSERT(it != d->source_index_mapping.constEnd());
- QModelIndex source_parent = it.key();
- QModelIndex proxy_parent = mapFromSource(source_parent);
- return proxy_parent;
-}
-
-/*!
- \reimp
-*/
-int QSortFilterProxyModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return 0;
- IndexMap::const_iterator it = d->create_mapping(source_parent);
- return it.value()->source_rows.count();
-}
-
-/*!
- \reimp
-*/
-int QSortFilterProxyModel::columnCount(const QModelIndex &parent) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return 0;
- IndexMap::const_iterator it = d->create_mapping(source_parent);
- return it.value()->source_columns.count();
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return false;
- if (!d->model->hasChildren(source_parent))
- return false;
-
- if (d->model->canFetchMore(source_parent))
- return true; //we assume we might have children that can be fetched
-
- QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value();
- return m->source_rows.count() != 0 && m->source_columns.count() != 0;
-}
-
-/*!
- \reimp
-*/
-QVariant QSortFilterProxyModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_index = mapToSource(index);
- if (index.isValid() && !source_index.isValid())
- return QVariant();
- return d->model->data(source_index, role);
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- Q_D(QSortFilterProxyModel);
- QModelIndex source_index = mapToSource(index);
- if (index.isValid() && !source_index.isValid())
- return false;
- return d->model->setData(source_index, value, role);
-}
-
-/*!
- \reimp
-*/
-QVariant QSortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- Q_D(const QSortFilterProxyModel);
- IndexMap::const_iterator it = d->create_mapping(QModelIndex());
- if (it.value()->source_rows.count() * it.value()->source_columns.count() > 0)
- return QAbstractProxyModel::headerData(section, orientation, role);
- int source_section;
- if (orientation == Qt::Vertical) {
- if (section < 0 || section >= it.value()->source_rows.count())
- return QVariant();
- source_section = it.value()->source_rows.at(section);
- } else {
- if (section < 0 || section >= it.value()->source_columns.count())
- return QVariant();
- source_section = it.value()->source_columns.at(section);
- }
- return d->model->headerData(source_section, orientation, role);
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::setHeaderData(int section, Qt::Orientation orientation,
- const QVariant &value, int role)
-{
- Q_D(QSortFilterProxyModel);
- IndexMap::const_iterator it = d->create_mapping(QModelIndex());
- if (it.value()->source_rows.count() * it.value()->source_columns.count() > 0)
- return QAbstractProxyModel::setHeaderData(section, orientation, value, role);
- int source_section;
- if (orientation == Qt::Vertical) {
- if (section < 0 || section >= it.value()->source_rows.count())
- return false;
- source_section = it.value()->source_rows.at(section);
- } else {
- if (section < 0 || section >= it.value()->source_columns.count())
- return false;
- source_section = it.value()->source_columns.at(section);
- }
- return d->model->setHeaderData(source_section, orientation, value, role);
-}
-
-/*!
- \reimp
-*/
-QMimeData *QSortFilterProxyModel::mimeData(const QModelIndexList &indexes) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndexList source_indexes;
- for (int i = 0; i < indexes.count(); ++i)
- source_indexes << mapToSource(indexes.at(i));
- return d->model->mimeData(source_indexes);
-}
-
-/*!
- \reimp
-*/
-QStringList QSortFilterProxyModel::mimeTypes() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->model->mimeTypes();
-}
-
-/*!
- \reimp
-*/
-Qt::DropActions QSortFilterProxyModel::supportedDropActions() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->model->supportedDropActions();
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- Q_D(QSortFilterProxyModel);
- if ((row == -1) && (column == -1))
- return d->model->dropMimeData(data, action, -1, -1, mapToSource(parent));
- int source_destination_row = -1;
- int source_destination_column = -1;
- QModelIndex source_parent;
- if (row == rowCount(parent)) {
- source_parent = mapToSource(parent);
- source_destination_row = d->model->rowCount(source_parent);
- } else {
- QModelIndex proxy_index = index(row, column, parent);
- QModelIndex source_index = mapToSource(proxy_index);
- source_destination_row = source_index.row();
- source_destination_column = source_index.column();
- source_parent = source_index.parent();
- }
- return d->model->dropMimeData(data, action, source_destination_row,
- source_destination_column, source_parent);
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::insertRows(int row, int count, const QModelIndex &parent)
-{
- Q_D(QSortFilterProxyModel);
- if (row < 0 || count <= 0)
- return false;
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return false;
- QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value();
- if (row > m->source_rows.count())
- return false;
- int source_row = (row >= m->source_rows.count()
- ? m->source_rows.count()
- : m->source_rows.at(row));
- return d->model->insertRows(source_row, count, source_parent);
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::insertColumns(int column, int count, const QModelIndex &parent)
-{
- Q_D(QSortFilterProxyModel);
- if (column < 0|| count <= 0)
- return false;
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return false;
- QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value();
- if (column > m->source_columns.count())
- return false;
- int source_column = (column >= m->source_columns.count()
- ? m->source_columns.count()
- : m->source_columns.at(column));
- return d->model->insertColumns(source_column, count, source_parent);
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::removeRows(int row, int count, const QModelIndex &parent)
-{
- Q_D(QSortFilterProxyModel);
- if (row < 0 || count <= 0)
- return false;
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return false;
- QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value();
- if (row + count > m->source_rows.count())
- return false;
- if ((count == 1)
- || ((d->source_sort_column < 0) && (m->proxy_rows.count() == m->source_rows.count()))) {
- int source_row = m->source_rows.at(row);
- return d->model->removeRows(source_row, count, source_parent);
- }
- // remove corresponding source intervals
- // ### if this proves to be slow, we can switch to single-row removal
- QVector<int> rows;
- for (int i = row; i < row + count; ++i)
- rows.append(m->source_rows.at(i));
- qSort(rows.begin(), rows.end());
-
- int pos = rows.count() - 1;
- bool ok = true;
- while (pos >= 0) {
- const int source_end = rows.at(pos--);
- int source_start = source_end;
- while ((pos >= 0) && (rows.at(pos) == (source_start - 1))) {
- --source_start;
- --pos;
- }
- ok = ok && d->model->removeRows(source_start, source_end - source_start + 1,
- source_parent);
- }
- return ok;
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::removeColumns(int column, int count, const QModelIndex &parent)
-{
- Q_D(QSortFilterProxyModel);
- if (column < 0 || count <= 0)
- return false;
- QModelIndex source_parent = mapToSource(parent);
- if (parent.isValid() && !source_parent.isValid())
- return false;
- QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value();
- if (column + count > m->source_columns.count())
- return false;
- if ((count == 1) || (m->proxy_columns.count() == m->source_columns.count())) {
- int source_column = m->source_columns.at(column);
- return d->model->removeColumns(source_column, count, source_parent);
- }
- // remove corresponding source intervals
- QVector<int> columns;
- for (int i = column; i < column + count; ++i)
- columns.append(m->source_columns.at(i));
-
- int pos = columns.count() - 1;
- bool ok = true;
- while (pos >= 0) {
- const int source_end = columns.at(pos--);
- int source_start = source_end;
- while ((pos >= 0) && (columns.at(pos) == (source_start - 1))) {
- --source_start;
- --pos;
- }
- ok = ok && d->model->removeColumns(source_start, source_end - source_start + 1,
- source_parent);
- }
- return ok;
-}
-
-/*!
- \reimp
-*/
-void QSortFilterProxyModel::fetchMore(const QModelIndex &parent)
-{
- Q_D(QSortFilterProxyModel);
- QModelIndex source_parent;
- if (d->indexValid(parent))
- source_parent = mapToSource(parent);
- d->model->fetchMore(source_parent);
-}
-
-/*!
- \reimp
-*/
-bool QSortFilterProxyModel::canFetchMore(const QModelIndex &parent) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_parent;
- if (d->indexValid(parent))
- source_parent = mapToSource(parent);
- return d->model->canFetchMore(source_parent);
-}
-
-/*!
- \reimp
-*/
-Qt::ItemFlags QSortFilterProxyModel::flags(const QModelIndex &index) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_index;
- if (d->indexValid(index))
- source_index = mapToSource(index);
- return d->model->flags(source_index);
-}
-
-/*!
- \reimp
-*/
-QModelIndex QSortFilterProxyModel::buddy(const QModelIndex &index) const
-{
- Q_D(const QSortFilterProxyModel);
- if (!d->indexValid(index))
- return QModelIndex();
- QModelIndex source_index = mapToSource(index);
- QModelIndex source_buddy = d->model->buddy(source_index);
- if (source_index == source_buddy)
- return index;
- return mapFromSource(source_buddy);
-}
-
-/*!
- \reimp
-*/
-QModelIndexList QSortFilterProxyModel::match(const QModelIndex &start, int role,
- const QVariant &value, int hits,
- Qt::MatchFlags flags) const
-{
- return QAbstractProxyModel::match(start, role, value, hits, flags);
-}
-
-/*!
- \reimp
-*/
-QSize QSortFilterProxyModel::span(const QModelIndex &index) const
-{
- Q_D(const QSortFilterProxyModel);
- QModelIndex source_index = mapToSource(index);
- if (index.isValid() && !source_index.isValid())
- return QSize();
- return d->model->span(source_index);
-}
-
-/*!
- \reimp
-*/
-void QSortFilterProxyModel::sort(int column, Qt::SortOrder order)
-{
- Q_D(QSortFilterProxyModel);
- if (d->dynamic_sortfilter && d->proxy_sort_column == column && d->sort_order == order)
- return;
- d->sort_order = order;
- d->proxy_sort_column = column;
- d->update_source_sort_column();
- d->sort();
-}
-
-/*!
- \since 4.5
- \brief the column currently used for sorting
-
- This returns the most recently used sort column.
-*/
-int QSortFilterProxyModel::sortColumn() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->proxy_sort_column;
-}
-
-/*!
- \since 4.5
- \brief the order currently used for sorting
-
- This returns the most recently used sort order.
-*/
-Qt::SortOrder QSortFilterProxyModel::sortOrder() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->sort_order;
-}
-
-/*!
- \property QSortFilterProxyModel::filterRegExp
- \brief the QRegExp used to filter the contents of the source model
-
- Setting this property overwrites the current
- \l{QSortFilterProxyModel::filterCaseSensitivity}{filterCaseSensitivity}.
- By default, the QRegExp is an empty string matching all contents.
-
- If no QRegExp or an empty string is set, everything in the source model
- will be accepted.
-
- \sa filterCaseSensitivity, setFilterWildcard(), setFilterFixedString()
-*/
-QRegExp QSortFilterProxyModel::filterRegExp() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->filter_regexp;
-}
-
-void QSortFilterProxyModel::setFilterRegExp(const QRegExp &regExp)
-{
- Q_D(QSortFilterProxyModel);
- d->filter_regexp = regExp;
- d->filter_changed();
-}
-
-/*!
- \property QSortFilterProxyModel::filterKeyColumn
- \brief the column where the key used to filter the contents of the
- source model is read from.
-
- The default value is 0. If the value is -1, the keys will be read
- from all columns.
-*/
-int QSortFilterProxyModel::filterKeyColumn() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->filter_column;
-}
-
-void QSortFilterProxyModel::setFilterKeyColumn(int column)
-{
- Q_D(QSortFilterProxyModel);
- d->filter_column = column;
- d->filter_changed();
-}
-
-/*!
- \property QSortFilterProxyModel::filterCaseSensitivity
-
- \brief the case sensitivity of the QRegExp pattern used to filter the
- contents of the source model
-
- By default, the filter is case sensitive.
-
- \sa filterRegExp, sortCaseSensitivity
-*/
-Qt::CaseSensitivity QSortFilterProxyModel::filterCaseSensitivity() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->filter_regexp.caseSensitivity();
-}
-
-void QSortFilterProxyModel::setFilterCaseSensitivity(Qt::CaseSensitivity cs)
-{
- Q_D(QSortFilterProxyModel);
- if (cs == d->filter_regexp.caseSensitivity())
- return;
- d->filter_regexp.setCaseSensitivity(cs);
- d->filter_changed();
-}
-
-/*!
- \since 4.2
- \property QSortFilterProxyModel::sortCaseSensitivity
- \brief the case sensitivity setting used for comparing strings when sorting
-
- By default, sorting is case sensitive.
-
- \sa filterCaseSensitivity, lessThan()
-*/
-Qt::CaseSensitivity QSortFilterProxyModel::sortCaseSensitivity() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->sort_casesensitivity;
-}
-
-void QSortFilterProxyModel::setSortCaseSensitivity(Qt::CaseSensitivity cs)
-{
- Q_D(QSortFilterProxyModel);
- if (d->sort_casesensitivity == cs)
- return;
-
- d->sort_casesensitivity = cs;
- d->sort();
-}
-
-/*!
- \since 4.3
- \property QSortFilterProxyModel::isSortLocaleAware
- \brief the local aware setting used for comparing strings when sorting
-
- By default, sorting is not local aware.
-
- \sa sortCaseSensitivity, lessThan()
-*/
-bool QSortFilterProxyModel::isSortLocaleAware() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->sort_localeaware;
-}
-
-void QSortFilterProxyModel::setSortLocaleAware(bool on)
-{
- Q_D(QSortFilterProxyModel);
- if (d->sort_localeaware == on)
- return;
-
- d->sort_localeaware = on;
- d->sort();
-}
-
-/*!
- \overload
-
- Sets the regular expression used to filter the contents
- of the source model to \a pattern.
-
- \sa setFilterCaseSensitivity(), setFilterWildcard(), setFilterFixedString(), filterRegExp()
-*/
-void QSortFilterProxyModel::setFilterRegExp(const QString &pattern)
-{
- Q_D(QSortFilterProxyModel);
- d->filter_regexp.setPatternSyntax(QRegExp::RegExp);
- d->filter_regexp.setPattern(pattern);
- d->filter_changed();
-}
-
-/*!
- Sets the wildcard expression used to filter the contents
- of the source model to the given \a pattern.
-
- \sa setFilterCaseSensitivity(), setFilterRegExp(), setFilterFixedString(), filterRegExp()
-*/
-void QSortFilterProxyModel::setFilterWildcard(const QString &pattern)
-{
- Q_D(QSortFilterProxyModel);
- d->filter_regexp.setPatternSyntax(QRegExp::Wildcard);
- d->filter_regexp.setPattern(pattern);
- d->filter_changed();
-}
-
-/*!
- Sets the fixed string used to filter the contents
- of the source model to the given \a pattern.
-
- \sa setFilterCaseSensitivity(), setFilterRegExp(), setFilterWildcard(), filterRegExp()
-*/
-void QSortFilterProxyModel::setFilterFixedString(const QString &pattern)
-{
- Q_D(QSortFilterProxyModel);
- d->filter_regexp.setPatternSyntax(QRegExp::FixedString);
- d->filter_regexp.setPattern(pattern);
- d->filter_changed();
-}
-
-/*!
- \since 4.2
- \property QSortFilterProxyModel::dynamicSortFilter
- \brief whether the proxy model is dynamically sorted and filtered
- whenever the contents of the source model change
-
- Note that you should not update the source model through the proxy
- model when dynamicSortFilter is true. For instance, if you set the
- proxy model on a QComboBox, then using functions that update the
- model, e.g., \l{QComboBox::}{addItem()}, will not work as
- expected. An alternative is to set dynamicSortFilter to false and
- call \l{QSortFilterProxyModel::}{sort()} after adding items to the
- QComboBox.
-
- The default value is false.
-*/
-bool QSortFilterProxyModel::dynamicSortFilter() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->dynamic_sortfilter;
-}
-
-void QSortFilterProxyModel::setDynamicSortFilter(bool enable)
-{
- Q_D(QSortFilterProxyModel);
- d->dynamic_sortfilter = enable;
- if (enable)
- d->sort();
-}
-
-/*!
- \since 4.2
- \property QSortFilterProxyModel::sortRole
- \brief the item role that is used to query the source model's data when sorting items
-
- The default value is Qt::DisplayRole.
-
- \sa lessThan()
-*/
-int QSortFilterProxyModel::sortRole() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->sort_role;
-}
-
-void QSortFilterProxyModel::setSortRole(int role)
-{
- Q_D(QSortFilterProxyModel);
- if (d->sort_role == role)
- return;
- d->sort_role = role;
- d->sort();
-}
-
-/*!
- \since 4.2
- \property QSortFilterProxyModel::filterRole
- \brief the item role that is used to query the source model's data when filtering items
-
- The default value is Qt::DisplayRole.
-
- \sa filterAcceptsRow()
-*/
-int QSortFilterProxyModel::filterRole() const
-{
- Q_D(const QSortFilterProxyModel);
- return d->filter_role;
-}
-
-void QSortFilterProxyModel::setFilterRole(int role)
-{
- Q_D(QSortFilterProxyModel);
- if (d->filter_role == role)
- return;
- d->filter_role = role;
- d->filter_changed();
-}
-
-/*!
- \obsolete
-
- This function is obsolete. Use invalidate() instead.
-*/
-void QSortFilterProxyModel::clear()
-{
- Q_D(QSortFilterProxyModel);
- emit layoutAboutToBeChanged();
- d->_q_clearMapping();
- emit layoutChanged();
-}
-
-/*!
- \since 4.3
-
- Invalidates the current sorting and filtering.
-
- \sa invalidateFilter()
-*/
-void QSortFilterProxyModel::invalidate()
-{
- Q_D(QSortFilterProxyModel);
- emit layoutAboutToBeChanged();
- d->_q_clearMapping();
- emit layoutChanged();
-}
-
-/*!
- \obsolete
-
- This function is obsolete. Use invalidateFilter() instead.
-*/
-void QSortFilterProxyModel::filterChanged()
-{
- Q_D(QSortFilterProxyModel);
- d->filter_changed();
-}
-
-/*!
- \since 4.3
-
- Invalidates the current filtering.
-
- This function should be called if you are implementing custom filtering
- (e.g. filterAcceptsRow()), and your filter parameters have changed.
-
- \sa invalidate()
-*/
-void QSortFilterProxyModel::invalidateFilter()
-{
- Q_D(QSortFilterProxyModel);
- d->filter_changed();
-}
-
-/*!
- Returns true if the value of the item referred to by the given
- index \a left is less than the value of the item referred to by
- the given index \a right, otherwise returns false.
-
- This function is used as the < operator when sorting, and handles
- the following QVariant types:
-
- \list
- \o QVariant::Int
- \o QVariant::UInt
- \o QVariant::LongLong
- \o QVariant::ULongLong
- \o QVariant::Double
- \o QVariant::Char
- \o QVariant::Date
- \o QVariant::Time
- \o QVariant::DateTime
- \o QVariant::String
- \endlist
-
- Any other type will be converted to a QString using
- QVariant::toString().
-
- Comparison of \l{QString}s is case sensitive by default; this can
- be changed using the \l {QSortFilterProxyModel::sortCaseSensitivity}
- {sortCaseSensitivity} property.
-
- By default, the Qt::DisplayRole associated with the
- \l{QModelIndex}es is used for comparisons. This can be changed by
- setting the \l {QSortFilterProxyModel::sortRole} {sortRole} property.
-
- \note The indices passed in correspond to the source model.
-
- \sa sortRole, sortCaseSensitivity, dynamicSortFilter
-*/
-bool QSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
-{
- Q_D(const QSortFilterProxyModel);
- QVariant l = (left.model() ? left.model()->data(left, d->sort_role) : QVariant());
- QVariant r = (right.model() ? right.model()->data(right, d->sort_role) : QVariant());
- switch (l.userType()) {
- case QVariant::Invalid:
- return (r.type() != QVariant::Invalid);
- case QVariant::Int:
- return l.toInt() < r.toInt();
- case QVariant::UInt:
- return l.toUInt() < r.toUInt();
- case QVariant::LongLong:
- return l.toLongLong() < r.toLongLong();
- case QVariant::ULongLong:
- return l.toULongLong() < r.toULongLong();
- case QMetaType::Float:
- return l.toFloat() < r.toFloat();
- case QVariant::Double:
- return l.toDouble() < r.toDouble();
- case QVariant::Char:
- return l.toChar() < r.toChar();
- case QVariant::Date:
- return l.toDate() < r.toDate();
- case QVariant::Time:
- return l.toTime() < r.toTime();
- case QVariant::DateTime:
- return l.toDateTime() < r.toDateTime();
- case QVariant::String:
- default:
- if (d->sort_localeaware)
- return l.toString().localeAwareCompare(r.toString()) < 0;
- else
- return l.toString().compare(r.toString(), d->sort_casesensitivity) < 0;
- }
- return false;
-}
-
-/*!
- Returns true if the item in the row indicated by the given \a source_row
- and \a source_parent should be included in the model; otherwise returns
- false.
-
- The default implementation returns true if the value held by the relevant item
- matches the filter string, wildcard string or regular expression.
-
- \note By default, the Qt::DisplayRole is used to determine if the row
- should be accepted or not. This can be changed by setting the
- \l{QSortFilterProxyModel::filterRole}{filterRole} property.
-
- \sa filterAcceptsColumn(), setFilterFixedString(), setFilterRegExp(), setFilterWildcard()
-*/
-bool QSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
-{
- Q_D(const QSortFilterProxyModel);
- if (d->filter_regexp.isEmpty())
- return true;
- if (d->filter_column == -1) {
- int column_count = d->model->columnCount(source_parent);
- for (int column = 0; column < column_count; ++column) {
- QModelIndex source_index = d->model->index(source_row, column, source_parent);
- QString key = d->model->data(source_index, d->filter_role).toString();
- if (key.contains(d->filter_regexp))
- return true;
- }
- return false;
- }
- QModelIndex source_index = d->model->index(source_row, d->filter_column, source_parent);
- if (!source_index.isValid()) // the column may not exist
- return true;
- QString key = d->model->data(source_index, d->filter_role).toString();
- return key.contains(d->filter_regexp);
-}
-
-/*!
- Returns true if the item in the column indicated by the given \a source_column
- and \a source_parent should be included in the model; otherwise returns false.
-
- The default implementation returns true if the value held by the relevant item
- matches the filter string, wildcard string or regular expression.
-
- \note By default, the Qt::DisplayRole is used to determine if the row
- should be accepted or not. This can be changed by setting the \l
- filterRole property.
-
- \sa filterAcceptsRow(), setFilterFixedString(), setFilterRegExp(), setFilterWildcard()
-*/
-bool QSortFilterProxyModel::filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const
-{
- Q_UNUSED(source_column);
- Q_UNUSED(source_parent);
- return true;
-}
-
-/*!
- Returns the source model index corresponding to the given \a
- proxyIndex from the sorting filter model.
-
- \sa mapFromSource()
-*/
-QModelIndex QSortFilterProxyModel::mapToSource(const QModelIndex &proxyIndex) const
-{
- Q_D(const QSortFilterProxyModel);
- return d->proxy_to_source(proxyIndex);
-}
-
-/*!
- Returns the model index in the QSortFilterProxyModel given the \a
- sourceIndex from the source model.
-
- \sa mapToSource()
-*/
-QModelIndex QSortFilterProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
-{
- Q_D(const QSortFilterProxyModel);
- return d->source_to_proxy(sourceIndex);
-}
-
-/*!
- \reimp
-*/
-QItemSelection QSortFilterProxyModel::mapSelectionToSource(const QItemSelection &proxySelection) const
-{
- return QAbstractProxyModel::mapSelectionToSource(proxySelection);
-}
-
-/*!
- \reimp
-*/
-QItemSelection QSortFilterProxyModel::mapSelectionFromSource(const QItemSelection &sourceSelection) const
-{
- return QAbstractProxyModel::mapSelectionFromSource(sourceSelection);
-}
-
-/*!
- \fn QObject *QSortFilterProxyModel::parent() const
- \internal
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qsortfilterproxymodel.cpp"
-
-#endif // QT_NO_SORTFILTERPROXYMODEL
diff --git a/src/gui/itemviews/qsortfilterproxymodel.h b/src/gui/itemviews/qsortfilterproxymodel.h
deleted file mode 100644
index afeaa6936d..0000000000
--- a/src/gui/itemviews/qsortfilterproxymodel.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/****************************************************************************
-**
-** 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 QSORTFILTERPROXYMODEL_H
-#define QSORTFILTERPROXYMODEL_H
-
-#include <QtGui/qabstractproxymodel.h>
-
-#ifndef QT_NO_SORTFILTERPROXYMODEL
-
-#include <QtCore/qregexp.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QSortFilterProxyModelPrivate;
-class QSortFilterProxyModelLessThan;
-class QSortFilterProxyModelGreaterThan;
-
-class Q_GUI_EXPORT QSortFilterProxyModel : public QAbstractProxyModel
-{
- friend class QSortFilterProxyModelLessThan;
- friend class QSortFilterProxyModelGreaterThan;
-
- Q_OBJECT
- Q_PROPERTY(QRegExp filterRegExp READ filterRegExp WRITE setFilterRegExp)
- Q_PROPERTY(int filterKeyColumn READ filterKeyColumn WRITE setFilterKeyColumn)
- Q_PROPERTY(bool dynamicSortFilter READ dynamicSortFilter WRITE setDynamicSortFilter)
- Q_PROPERTY(Qt::CaseSensitivity filterCaseSensitivity READ filterCaseSensitivity WRITE setFilterCaseSensitivity)
- Q_PROPERTY(Qt::CaseSensitivity sortCaseSensitivity READ sortCaseSensitivity WRITE setSortCaseSensitivity)
- Q_PROPERTY(bool isSortLocaleAware READ isSortLocaleAware WRITE setSortLocaleAware)
- Q_PROPERTY(int sortRole READ sortRole WRITE setSortRole)
- Q_PROPERTY(int filterRole READ filterRole WRITE setFilterRole)
-
-public:
- QSortFilterProxyModel(QObject *parent = 0);
- ~QSortFilterProxyModel();
-
- void setSourceModel(QAbstractItemModel *sourceModel);
-
- QModelIndex mapToSource(const QModelIndex &proxyIndex) const;
- QModelIndex mapFromSource(const QModelIndex &sourceIndex) const;
-
- QItemSelection mapSelectionToSource(const QItemSelection &proxySelection) const;
- QItemSelection mapSelectionFromSource(const QItemSelection &sourceSelection) const;
-
- QRegExp filterRegExp() const;
- void setFilterRegExp(const QRegExp &regExp);
-
- int filterKeyColumn() const;
- void setFilterKeyColumn(int column);
-
- Qt::CaseSensitivity filterCaseSensitivity() const;
- void setFilterCaseSensitivity(Qt::CaseSensitivity cs);
-
- Qt::CaseSensitivity sortCaseSensitivity() const;
- void setSortCaseSensitivity(Qt::CaseSensitivity cs);
-
- bool isSortLocaleAware() const;
- void setSortLocaleAware(bool on);
-
- int sortColumn() const;
- Qt::SortOrder sortOrder() const;
-
- bool dynamicSortFilter() const;
- void setDynamicSortFilter(bool enable);
-
- int sortRole() const;
- void setSortRole(int role);
-
- int filterRole() const;
- void setFilterRole(int role);
-
-public Q_SLOTS:
- void setFilterRegExp(const QString &pattern);
- void setFilterWildcard(const QString &pattern);
- void setFilterFixedString(const QString &pattern);
- void clear();
- void invalidate();
-
-protected:
- virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
- virtual bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const;
- virtual bool lessThan(const QModelIndex &left, const QModelIndex &right) const;
-
- void filterChanged();
- void invalidateFilter();
-
-public:
-#ifdef Q_NO_USING_KEYWORD
- inline QObject *parent() const { return QObject::parent(); }
-#else
- using QObject::parent;
-#endif
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex &child) const;
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
- bool setHeaderData(int section, Qt::Orientation orientation,
- const QVariant &value, int role = Qt::EditRole);
-
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
-
- bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
- bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex());
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
- bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex());
-
- void fetchMore(const QModelIndex &parent);
- bool canFetchMore(const QModelIndex &parent) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- QModelIndex buddy(const QModelIndex &index) const;
- QModelIndexList match(const QModelIndex &start, int role,
- const QVariant &value, int hits = 1,
- Qt::MatchFlags flags =
- Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const;
- QSize span(const QModelIndex &index) const;
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- QStringList mimeTypes() const;
- Qt::DropActions supportedDropActions() const;
-private:
- Q_DECLARE_PRIVATE(QSortFilterProxyModel)
- Q_DISABLE_COPY(QSortFilterProxyModel)
-
- Q_PRIVATE_SLOT(d_func(), void _q_sourceDataChanged(const QModelIndex &source_top_left, const QModelIndex &source_bottom_right))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceHeaderDataChanged(Qt::Orientation orientation, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceAboutToBeReset())
- Q_PRIVATE_SLOT(d_func(), void _q_sourceReset())
- Q_PRIVATE_SLOT(d_func(), void _q_sourceLayoutAboutToBeChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_sourceLayoutChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeInserted(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsInserted(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeRemoved(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsRemoved(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeInserted(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsInserted(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeRemoved(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsRemoved(const QModelIndex &source_parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_clearMapping())
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_SORTFILTERPROXYMODEL
-
-#endif // QSORTFILTERPROXYMODEL_H
diff --git a/src/gui/itemviews/qstandarditemmodel.cpp b/src/gui/itemviews/qstandarditemmodel.cpp
deleted file mode 100644
index 711f5f8a40..0000000000
--- a/src/gui/itemviews/qstandarditemmodel.cpp
+++ /dev/null
@@ -1,3115 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstandarditemmodel.h"
-
-#ifndef QT_NO_STANDARDITEMMODEL
-
-#include <QtCore/qdatetime.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qmap.h>
-#include <QtCore/qpair.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
-#include <QtCore/qstringlist.h>
-#include <QtCore/qbitarray.h>
-#include <QtCore/qmimedata.h>
-
-#include <private/qstandarditemmodel_p.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-class QStandardItemModelLessThan
-{
-public:
- inline QStandardItemModelLessThan()
- { }
-
- inline bool operator()(const QPair<QStandardItem*, int> &l,
- const QPair<QStandardItem*, int> &r) const
- {
- return *(l.first) < *(r.first);
- }
-};
-
-class QStandardItemModelGreaterThan
-{
-public:
- inline QStandardItemModelGreaterThan()
- { }
-
- inline bool operator()(const QPair<QStandardItem*, int> &l,
- const QPair<QStandardItem*, int> &r) const
- {
- return *(r.first) < *(l.first);
- }
-};
-
-/*!
- \internal
-*/
-QStandardItemPrivate::~QStandardItemPrivate()
-{
- QVector<QStandardItem*>::const_iterator it;
- for (it = children.constBegin(); it != children.constEnd(); ++it) {
- QStandardItem *child = *it;
- if (child)
- child->d_func()->setModel(0);
- delete child;
- }
- children.clear();
- if (parent && model)
- parent->d_func()->childDeleted(q_func());
-}
-
-/*!
- \internal
-*/
-QPair<int, int> QStandardItemPrivate::position() const
-{
- if (QStandardItem *par = parent) {
- int idx = par->d_func()->childIndex(q_func());
- if (idx == -1)
- return QPair<int, int>(-1, -1);
- return QPair<int, int>(idx / par->columnCount(), idx % par->columnCount());
- }
- // ### support header items?
- return QPair<int, int>(-1, -1);
-}
-
-/*!
- \internal
-*/
-void QStandardItemPrivate::setChild(int row, int column, QStandardItem *item,
- bool emitChanged)
-{
- Q_Q(QStandardItem);
- if (item == q) {
- qWarning("QStandardItem::setChild: Can't make an item a child of itself %p",
- item);
- return;
- }
- if ((row < 0) || (column < 0))
- return;
- if (rows <= row)
- q->setRowCount(row + 1);
- if (columns <= column)
- q->setColumnCount(column + 1);
- int index = childIndex(row, column);
- Q_ASSERT(index != -1);
- QStandardItem *oldItem = children.at(index);
- if (item == oldItem)
- return;
- if (item) {
- if (item->d_func()->parent == 0) {
- item->d_func()->setParentAndModel(q, model);
- } else {
- qWarning("QStandardItem::setChild: Ignoring duplicate insertion of item %p",
- item);
- return;
- }
- }
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
- children.replace(index, item);
- if (emitChanged && model)
- model->d_func()->itemChanged(item);
-}
-
-
-/*!
- \internal
-*/
-void QStandardItemPrivate::changeFlags(bool enable, Qt::ItemFlags f)
-{
- Q_Q(QStandardItem);
- Qt::ItemFlags flags = q->flags();
- if (enable)
- flags |= f;
- else
- flags &= ~f;
- q->setFlags(flags);
-}
-
-/*!
- \internal
-*/
-void QStandardItemPrivate::childDeleted(QStandardItem *child)
-{
- int index = childIndex(child);
- Q_ASSERT(index != -1);
- children.replace(index, 0);
-}
-
-/*!
- \internal
-*/
-void QStandardItemPrivate::setItemData(const QMap<int, QVariant> &roles)
-{
- Q_Q(QStandardItem);
-
- //let's build the vector of new values
- QVector<QWidgetItemData> newValues;
- QMap<int, QVariant>::const_iterator it;
- for (it = roles.begin(); it != roles.end(); ++it) {
- QVariant value = it.value();
- if (value.isValid()) {
- int role = it.key();
- role = (role == Qt::EditRole) ? Qt::DisplayRole : role;
- QWidgetItemData wid(role,it.value());
- newValues.append(wid);
- }
- }
-
- if (values!=newValues) {
- values=newValues;
- if (model)
- model->d_func()->itemChanged(q);
- }
-}
-
-/*!
- \internal
-*/
-const QMap<int, QVariant> QStandardItemPrivate::itemData() const
-{
- QMap<int, QVariant> result;
- QVector<QWidgetItemData>::const_iterator it;
- for (it = values.begin(); it != values.end(); ++it)
- result.insert((*it).role, (*it).value);
- return result;
-}
-
-/*!
- \internal
-*/
-void QStandardItemPrivate::sortChildren(int column, Qt::SortOrder order)
-{
- Q_Q(QStandardItem);
- if (column >= columnCount())
- return;
-
- QVector<QPair<QStandardItem*, int> > sortable;
- QVector<int> unsortable;
-
- sortable.reserve(rowCount());
- unsortable.reserve(rowCount());
-
- for (int row = 0; row < rowCount(); ++row) {
- QStandardItem *itm = q->child(row, column);
- if (itm)
- sortable.append(QPair<QStandardItem*,int>(itm, row));
- else
- unsortable.append(row);
- }
-
- if (order == Qt::AscendingOrder) {
- QStandardItemModelLessThan lt;
- qStableSort(sortable.begin(), sortable.end(), lt);
- } else {
- QStandardItemModelGreaterThan gt;
- qStableSort(sortable.begin(), sortable.end(), gt);
- }
-
- QModelIndexList changedPersistentIndexesFrom, changedPersistentIndexesTo;
- QVector<QStandardItem*> sorted_children(children.count());
- for (int i = 0; i < rowCount(); ++i) {
- int r = (i < sortable.count()
- ? sortable.at(i).second
- : unsortable.at(i - sortable.count()));
- for (int c = 0; c < columnCount(); ++c) {
- QStandardItem *itm = q->child(r, c);
- sorted_children[childIndex(i, c)] = itm;
- if (model) {
- QModelIndex from = model->createIndex(r, c, q);
- if (model->d_func()->persistent.indexes.contains(from)) {
- QModelIndex to = model->createIndex(i, c, q);
- changedPersistentIndexesFrom.append(from);
- changedPersistentIndexesTo.append(to);
- }
- }
- }
- }
-
- children = sorted_children;
-
- if (model) {
- model->changePersistentIndexList(changedPersistentIndexesFrom, changedPersistentIndexesTo);
- }
-
- QVector<QStandardItem*>::iterator it;
- for (it = children.begin(); it != children.end(); ++it) {
- if (*it)
- (*it)->d_func()->sortChildren(column, order);
- }
-}
-
-/*!
- \internal
- set the model of this item and all its children
- */
-void QStandardItemPrivate::setModel(QStandardItemModel *mod)
-{
- if (children.isEmpty()) {
- if (model)
- model->d_func()->invalidatePersistentIndex(model->indexFromItem(q_ptr));
- model = mod;
- } else {
- QStack<QStandardItem*> stack;
- stack.push(q_ptr);
- while (!stack.isEmpty()) {
- QStandardItem *itm = stack.pop();
- if (itm->d_func()->model) {
- itm->d_func()->model->d_func()->invalidatePersistentIndex(itm->d_func()->model->indexFromItem(itm));
- }
- itm->d_func()->model = mod;
- const QVector<QStandardItem*> &childList = itm->d_func()->children;
- for (int i = 0; i < childList.count(); ++i) {
- QStandardItem *chi = childList.at(i);
- if (chi)
- stack.push(chi);
- }
- }
- }
-}
-
-/*!
- \internal
-*/
-QStandardItemModelPrivate::QStandardItemModelPrivate()
- : root(new QStandardItem),
- itemPrototype(0),
- sortRole(Qt::DisplayRole)
-{
- root->setFlags(Qt::ItemIsDropEnabled);
-}
-
-/*!
- \internal
-*/
-QStandardItemModelPrivate::~QStandardItemModelPrivate()
-{
- delete itemPrototype;
- qDeleteAll(columnHeaderItems);
- qDeleteAll(rowHeaderItems);
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::init()
-{
- Q_Q(QStandardItemModel);
- QObject::connect(q, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitItemChanged(QModelIndex,QModelIndex)));
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::_q_emitItemChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
-{
- Q_Q(QStandardItemModel);
- QModelIndex parent = topLeft.parent();
- for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
- for (int column = topLeft.column(); column <= bottomRight.column(); ++column) {
- QModelIndex index = q->index(row, column, parent);
- if (QStandardItem *item = itemFromIndex(index))
- emit q->itemChanged(item);
- }
- }
-}
-
-/*!
- \internal
-*/
-bool QStandardItemPrivate::insertRows(int row, const QList<QStandardItem*> &items)
-{
- Q_Q(QStandardItem);
- if ((row < 0) || (row > rowCount()))
- return false;
- int count = items.count();
- if (model)
- model->d_func()->rowsAboutToBeInserted(q, row, row + count - 1);
- if (rowCount() == 0) {
- if (columnCount() == 0)
- q->setColumnCount(1);
- children.resize(columnCount() * count);
- rows = count;
- } else {
- rows += count;
- int index = childIndex(row, 0);
- if (index != -1)
- children.insert(index, columnCount() * count, 0);
- }
- for (int i = 0; i < items.count(); ++i) {
- QStandardItem *item = items.at(i);
- item->d_func()->model = model;
- item->d_func()->parent = q;
- int index = childIndex(i + row, 0);
- children.replace(index, item);
- }
- if (model)
- model->d_func()->rowsInserted(q, row, count);
- return true;
-}
-
-bool QStandardItemPrivate::insertRows(int row, int count, const QList<QStandardItem*> &items)
-{
- Q_Q(QStandardItem);
- if ((count < 1) || (row < 0) || (row > rowCount()))
- return false;
- if (model)
- model->d_func()->rowsAboutToBeInserted(q, row, row + count - 1);
- if (rowCount() == 0) {
- children.resize(columnCount() * count);
- rows = count;
- } else {
- rows += count;
- int index = childIndex(row, 0);
- if (index != -1)
- children.insert(index, columnCount() * count, 0);
- }
- if (!items.isEmpty()) {
- int index = childIndex(row, 0);
- int limit = qMin(items.count(), columnCount() * count);
- for (int i = 0; i < limit; ++i) {
- QStandardItem *item = items.at(i);
- if (item) {
- if (item->d_func()->parent == 0) {
- item->d_func()->setParentAndModel(q, model);
- } else {
- qWarning("QStandardItem::insertRows: Ignoring duplicate insertion of item %p",
- item);
- item = 0;
- }
- }
- children.replace(index, item);
- ++index;
- }
- }
- if (model)
- model->d_func()->rowsInserted(q, row, count);
- return true;
-}
-
-/*!
- \internal
-*/
-bool QStandardItemPrivate::insertColumns(int column, int count, const QList<QStandardItem*> &items)
-{
- Q_Q(QStandardItem);
- if ((count < 1) || (column < 0) || (column > columnCount()))
- return false;
- if (model)
- model->d_func()->columnsAboutToBeInserted(q, column, column + count - 1);
- if (columnCount() == 0) {
- children.resize(rowCount() * count);
- columns = count;
- } else {
- columns += count;
- int index = childIndex(0, column);
- for (int row = 0; row < rowCount(); ++row) {
- children.insert(index, count, 0);
- index += columnCount();
- }
- }
- if (!items.isEmpty()) {
- int limit = qMin(items.count(), rowCount() * count);
- for (int i = 0; i < limit; ++i) {
- QStandardItem *item = items.at(i);
- if (item) {
- if (item->d_func()->parent == 0) {
- item->d_func()->setParentAndModel(q, model);
- } else {
- qWarning("QStandardItem::insertColumns: Ignoring duplicate insertion of item %p",
- item);
- item = 0;
- }
- }
- int r = i / count;
- int c = column + (i % count);
- int index = childIndex(r, c);
- children.replace(index, item);
- }
- }
- if (model)
- model->d_func()->columnsInserted(q, column, count);
- return true;
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::itemChanged(QStandardItem *item)
-{
- Q_Q(QStandardItemModel);
- if (item->d_func()->parent == 0) {
- // Header item
- int idx = columnHeaderItems.indexOf(item);
- if (idx != -1) {
- emit q->headerDataChanged(Qt::Horizontal, idx, idx);
- } else {
- idx = rowHeaderItems.indexOf(item);
- if (idx != -1)
- emit q->headerDataChanged(Qt::Vertical, idx, idx);
- }
- } else {
- // Normal item
- QModelIndex index = q->indexFromItem(item);
- emit q->dataChanged(index, index);
- }
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::rowsAboutToBeInserted(QStandardItem *parent,
- int start, int end)
-{
- Q_Q(QStandardItemModel);
- QModelIndex index = q->indexFromItem(parent);
- q->beginInsertRows(index, start, end);
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::columnsAboutToBeInserted(QStandardItem *parent,
- int start, int end)
-{
- Q_Q(QStandardItemModel);
- QModelIndex index = q->indexFromItem(parent);
- q->beginInsertColumns(index, start, end);
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::rowsAboutToBeRemoved(QStandardItem *parent,
- int start, int end)
-{
- Q_Q(QStandardItemModel);
- QModelIndex index = q->indexFromItem(parent);
- q->beginRemoveRows(index, start, end);
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::columnsAboutToBeRemoved(QStandardItem *parent,
- int start, int end)
-{
- Q_Q(QStandardItemModel);
- QModelIndex index = q->indexFromItem(parent);
- q->beginRemoveColumns(index, start, end);
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::rowsInserted(QStandardItem *parent,
- int row, int count)
-{
- Q_Q(QStandardItemModel);
- if (parent == root.data())
- rowHeaderItems.insert(row, count, 0);
- q->endInsertRows();
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::columnsInserted(QStandardItem *parent,
- int column, int count)
-{
- Q_Q(QStandardItemModel);
- if (parent == root.data())
- columnHeaderItems.insert(column, count, 0);
- q->endInsertColumns();
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::rowsRemoved(QStandardItem *parent,
- int row, int count)
-{
- Q_Q(QStandardItemModel);
- if (parent == root.data()) {
- for (int i = row; i < row + count; ++i) {
- QStandardItem *oldItem = rowHeaderItems.at(i);
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
- }
- rowHeaderItems.remove(row, count);
- }
- q->endRemoveRows();
-}
-
-/*!
- \internal
-*/
-void QStandardItemModelPrivate::columnsRemoved(QStandardItem *parent,
- int column, int count)
-{
- Q_Q(QStandardItemModel);
- if (parent == root.data()) {
- for (int i = column; i < column + count; ++i) {
- QStandardItem *oldItem = columnHeaderItems.at(i);
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
- }
- columnHeaderItems.remove(column, count);
- }
- q->endRemoveColumns();
-}
-
-/*!
- \class QStandardItem
- \brief The QStandardItem class provides an item for use with the
- QStandardItemModel class.
- \since 4.2
- \ingroup model-view
-
- Items usually contain text, icons, or checkboxes.
-
- Each item can have its own background brush which is set with the
- setBackground() function. The current background brush can be found with
- background(). The text label for each item can be rendered with its own
- font and brush. These are specified with the setFont() and setForeground()
- functions, and read with font() and foreground().
-
- By default, items are enabled, editable, selectable, checkable, and can be
- used both as the source of a drag and drop operation and as a drop target.
- Each item's flags can be changed by calling setFlags(). Checkable items
- can be checked and unchecked with the setCheckState() function. The
- corresponding checkState() function indicates whether the item is
- currently checked.
-
- You can store application-specific data in an item by calling setData().
-
- Each item can have a two-dimensional table of child items. This makes it
- possible to build hierarchies of items. The typical hierarchy is the tree,
- in which case the child table is a table with a single column (a list).
-
- The dimensions of the child table can be set with setRowCount() and
- setColumnCount(). Items can be positioned in the child table with
- setChild(). Get a pointer to a child item with child(). New rows and
- columns of children can also be inserted with insertRow() and
- insertColumn(), or appended with appendRow() and appendColumn(). When
- using the append and insert functions, the dimensions of the child table
- will grow as needed.
-
- An existing row of children can be removed with removeRow() or takeRow();
- correspondingly, a column can be removed with removeColumn() or
- takeColumn().
-
- An item's children can be sorted by calling sortChildren().
-
- \section1 Subclassing
-
- When subclassing QStandardItem to provide custom items, it is possible to
- define new types for them so that they can be distinguished from the base
- class. The type() function should be reimplemented to return a new type
- value equal to or greater than \l UserType.
-
- Reimplement data() and setData() if you want to perform custom handling of
- data queries and/or control how an item's data is represented.
-
- Reimplement clone() if you want QStandardItemModel to be able to create
- instances of your custom item class on demand (see
- QStandardItemModel::setItemPrototype()).
-
- Reimplement read() and write() if you want to control how items are
- represented in their serialized form.
-
- Reimplement \l{operator<()} if you want to control the semantics of item
- comparison. \l{operator<()} determines the sorted order when sorting items
- with sortChildren() or with QStandardItemModel::sort().
-
- \sa QStandardItemModel, {Item View Convenience Classes}, {Model/View Programming}
-*/
-
-/*!
- \enum QStandardItem::ItemType
-
- This enum describes the types that are used to describe standard items.
-
- \value Type The default type for standard items.
- \value UserType The minimum value for custom types. Values below UserType are
- reserved by Qt.
-
- You can define new user types in QStandardItem subclasses to ensure that
- custom items are treated specially; for example, when items are sorted.
-
- \sa type()
-*/
-
-/*!
- Constructs an item.
-*/
-QStandardItem::QStandardItem()
- : d_ptr(new QStandardItemPrivate)
-{
- Q_D(QStandardItem);
- d->q_ptr = this;
-}
-
-/*!
- Constructs an item with the given \a text.
-*/
-QStandardItem::QStandardItem(const QString &text)
- : d_ptr(new QStandardItemPrivate)
-{
- Q_D(QStandardItem);
- d->q_ptr = this;
- setText(text);
-}
-
-/*!
- Constructs an item with the given \a icon and \a text.
-*/
-QStandardItem::QStandardItem(const QIcon &icon, const QString &text)
- : d_ptr(new QStandardItemPrivate)
-{
- Q_D(QStandardItem);
- d->q_ptr = this;
- setIcon(icon);
- setText(text);
-}
-
-/*!
- Constructs an item with \a rows rows and \a columns columns of child items.
-*/
-QStandardItem::QStandardItem(int rows, int columns)
- : d_ptr(new QStandardItemPrivate)
-{
- Q_D(QStandardItem);
- d->q_ptr = this;
- setRowCount(rows);
- setColumnCount(columns);
-}
-
-/*!
- \internal
-*/
-QStandardItem::QStandardItem(QStandardItemPrivate &dd)
- : d_ptr(&dd)
-{
- Q_D(QStandardItem);
- d->q_ptr = this;
-}
-
-/*!
- Constructs a copy of \a other. Note that model() is
- not copied.
-
- This function is useful when reimplementing clone().
-*/
-QStandardItem::QStandardItem(const QStandardItem &other)
- : d_ptr(new QStandardItemPrivate)
-{
- Q_D(QStandardItem);
- d->q_ptr = this;
- operator=(other);
-}
-
-/*!
- Assigns \a other's data and flags to this item. Note that
- type() and model() are not copied.
-
- This function is useful when reimplementing clone().
-*/
-QStandardItem &QStandardItem::operator=(const QStandardItem &other)
-{
- Q_D(QStandardItem);
- d->values = other.d_func()->values;
- return *this;
-}
-
-/*!
- Destructs the item.
- This causes the item's children to be destructed as well.
-*/
-QStandardItem::~QStandardItem()
-{
-}
-
-/*!
- Returns the item's parent item, or 0 if the item has no parent.
-
- \sa child()
-*/
-QStandardItem *QStandardItem::parent() const
-{
- Q_D(const QStandardItem);
- if (!d->model || (d->model->d_func()->root.data() != d->parent))
- return d->parent;
- return 0;
-}
-
-/*!
- Sets the item's data for the given \a role to the specified \a value.
-
- If you subclass QStandardItem and reimplement this function, your
- reimplementation should call emitDataChanged() if you do not call
- the base implementation of setData(). This will ensure that e.g.
- views using the model are notified of the changes.
-
- \note The default implementation treats Qt::EditRole and Qt::DisplayRole
- as referring to the same data.
-
- \sa Qt::ItemDataRole, data(), setFlags()
-*/
-void QStandardItem::setData(const QVariant &value, int role)
-{
- Q_D(QStandardItem);
- role = (role == Qt::EditRole) ? Qt::DisplayRole : role;
- QVector<QWidgetItemData>::iterator it;
- for (it = d->values.begin(); it != d->values.end(); ++it) {
- if ((*it).role == role) {
- if (value.isValid()) {
- if ((*it).value.type() == value.type() && (*it).value == value)
- return;
- (*it).value = value;
- } else {
- d->values.erase(it);
- }
- if (d->model)
- d->model->d_func()->itemChanged(this);
- return;
- }
- }
- d->values.append(QWidgetItemData(role, value));
- if (d->model)
- d->model->d_func()->itemChanged(this);
-}
-
-/*!
- Returns the item's data for the given \a role, or an invalid
- QVariant if there is no data for the role.
-
- \note The default implementation treats Qt::EditRole and Qt::DisplayRole
- as referring to the same data.
-*/
-QVariant QStandardItem::data(int role) const
-{
- Q_D(const QStandardItem);
- role = (role == Qt::EditRole) ? Qt::DisplayRole : role;
- QVector<QWidgetItemData>::const_iterator it;
- for (it = d->values.begin(); it != d->values.end(); ++it) {
- if ((*it).role == role)
- return (*it).value;
- }
- return QVariant();
-}
-
-/*!
- \since 4.4
-
- Causes the model associated with this item to emit a
- \l{QAbstractItemModel::dataChanged()}{dataChanged}() signal for this
- item.
-
- You normally only need to call this function if you have subclassed
- QStandardItem and reimplemented data() and/or setData().
-
- \sa setData()
-*/
-void QStandardItem::emitDataChanged()
-{
- Q_D(QStandardItem);
- if (d->model)
- d->model->d_func()->itemChanged(this);
-}
-
-/*!
- Sets the item flags for the item to \a flags.
-
- The item flags determine how the user can interact with the item.
- This is often used to disable an item.
-
- \sa flags(), setData()
-*/
-void QStandardItem::setFlags(Qt::ItemFlags flags)
-{
- setData((int)flags, Qt::UserRole - 1);
-}
-
-/*!
- Returns the item flags for the item.
-
- The item flags determine how the user can interact with the item.
-
- By default, items are enabled, editable, selectable, checkable, and can be
- used both as the source of a drag and drop operation and as a drop target.
-
- \sa setFlags()
-*/
-Qt::ItemFlags QStandardItem::flags() const
-{
- QVariant v = data(Qt::UserRole - 1);
- if (!v.isValid())
- return (Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsEditable
- |Qt::ItemIsDragEnabled|Qt::ItemIsDropEnabled);
- return Qt::ItemFlags(v.toInt());
-}
-
-/*!
- \fn QString QStandardItem::text() const
-
- Returns the item's text. This is the text that's presented to the user
- in a view.
-
- \sa setText()
-*/
-
-/*!
- \fn void QStandardItem::setText(const QString &text)
-
- Sets the item's text to the \a text specified.
-
- \sa text(), setFont(), setForeground()
-*/
-
-/*!
- \fn QIcon QStandardItem::icon() const
-
- Returns the item's icon.
-
- \sa setIcon(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn void QStandardItem::setIcon(const QIcon &icon)
-
- Sets the item's icon to the \a icon specified.
-*/
-
-/*!
- \fn QString QStandardItem::statusTip() const
-
- Returns the item's status tip.
-
- \sa setStatusTip(), toolTip(), whatsThis()
-*/
-
-/*!
- \fn void QStandardItem::setStatusTip(const QString &statusTip)
-
- Sets the item's status tip to the string specified by \a statusTip.
-
- \sa statusTip(), setToolTip(), setWhatsThis()
-*/
-
-/*!
- \fn QString QStandardItem::toolTip() const
-
- Returns the item's tooltip.
-
- \sa setToolTip(), statusTip(), whatsThis()
-*/
-
-/*!
- \fn void QStandardItem::setToolTip(const QString &toolTip)
-
- Sets the item's tooltip to the string specified by \a toolTip.
-
- \sa toolTip(), setStatusTip(), setWhatsThis()
-*/
-
-/*!
- \fn QString QStandardItem::whatsThis() const
-
- Returns the item's "What's This?" help.
-
- \sa setWhatsThis(), toolTip(), statusTip()
-*/
-
-/*!
- \fn void QStandardItem::setWhatsThis(const QString &whatsThis)
-
- Sets the item's "What's This?" help to the string specified by \a whatsThis.
-
- \sa whatsThis(), setStatusTip(), setToolTip()
-*/
-
-/*!
- \fn QFont QStandardItem::font() const
-
- Returns the font used to render the item's text.
-
- \sa setFont()
-*/
-
-/*!
- \fn void QStandardItem::setFont(const QFont &font)
-
- Sets the font used to display the item's text to the given \a font.
-
- \sa font() setText() setForeground()
-*/
-
-/*!
- \fn QBrush QStandardItem::background() const
-
- Returns the brush used to render the item's background.
-
- \sa foreground() setBackground()
-*/
-
-/*!
- \fn void QStandardItem::setBackground(const QBrush &brush)
-
- Sets the item's background brush to the specified \a brush.
-
- \sa background() setForeground()
-*/
-
-/*!
- \fn QBrush QStandardItem::foreground() const
-
- Returns the brush used to render the item's foreground (e.g. text).
-
- \sa setForeground() background()
-*/
-
-/*!
- \fn void QStandardItem::setForeground(const QBrush &brush)
-
- Sets the brush used to display the item's foreground (e.g. text) to the
- given \a brush.
-
- \sa foreground() setBackground() setFont()
-*/
-
-/*!
- \fn int QStandardItem::textAlignment() const
-
- Returns the text alignment for the item's text.
-*/
-
-/*!
- \fn void QStandardItem::setTextAlignment(Qt::Alignment alignment)
-
- Sets the text alignment for the item's text to the \a alignment
- specified.
-
- \sa textAlignment()
-*/
-
-/*!
- \fn QSize QStandardItem::sizeHint() const
-
- Returns the size hint set for the item, or an invalid QSize if no
- size hint has been set.
-
- If no size hint has been set, the item delegate will compute the
- size hint based on the item data.
-
- \sa setSizeHint()
-*/
-
-/*!
- \fn void QStandardItem::setSizeHint(const QSize &size)
-
- Sets the size hint for the item to be \a size.
- If no size hint is set, the item delegate will compute the
- size hint based on the item data.
-
- \sa sizeHint()
-*/
-
-/*!
- \fn Qt::CheckState QStandardItem::checkState() const
-
- Returns the checked state of the item.
-
- \sa setCheckState(), isCheckable()
-*/
-
-/*!
- \fn void QStandardItem::setCheckState(Qt::CheckState state)
-
- Sets the check state of the item to be \a state.
-
- \sa checkState(), setCheckable()
-*/
-
-/*!
- \fn QString QStandardItem::accessibleText() const
-
- Returns the item's accessible text.
-
- The accessible text is used by assistive technologies (i.e. for users who
- cannot use conventional means of interaction).
-
- \sa setAccessibleText(), accessibleDescription()
-*/
-
-/*!
- \fn void QStandardItem::setAccessibleText(const QString &accessibleText)
-
- Sets the item's accessible text to the string specified by \a accessibleText.
-
- The accessible text is used by assistive technologies (i.e. for users who
- cannot use conventional means of interaction).
-
- \sa accessibleText(), setAccessibleDescription()
-*/
-
-/*!
- \fn QString QStandardItem::accessibleDescription() const
-
- Returns the item's accessible description.
-
- The accessible description is used by assistive technologies (i.e. for
- users who cannot use conventional means of interaction).
-
- \sa setAccessibleDescription(), accessibleText()
-*/
-
-/*!
- \fn void QStandardItem::setAccessibleDescription(const QString &accessibleDescription)
-
- Sets the item's accessible description to the string specified by \a
- accessibleDescription.
-
- The accessible description is used by assistive technologies (i.e. for
- users who cannot use conventional means of interaction).
-
- \sa accessibleDescription(), setAccessibleText()
-*/
-
-/*!
- Sets whether the item is enabled. If \a enabled is true, the item is enabled,
- meaning that the user can interact with the item; if \a enabled is false, the
- user cannot interact with the item.
-
- This flag takes precedence over the other item flags; e.g. if an item is not
- enabled, it cannot be selected by the user, even if the Qt::ItemIsSelectable
- flag has been set.
-
- \sa isEnabled(), Qt::ItemIsEnabled, setFlags()
-*/
-void QStandardItem::setEnabled(bool enabled)
-{
- Q_D(QStandardItem);
- d->changeFlags(enabled, Qt::ItemIsEnabled);
-}
-
-/*!
- \fn bool QStandardItem::isEnabled() const
-
- Returns whether the item is enabled.
-
- When an item is enabled, the user can interact with it. The possible
- types of interaction are specified by the other item flags, such as
- isEditable() and isSelectable().
-
- The default value is true.
-
- \sa setEnabled(), flags()
-*/
-
-/*!
- Sets whether the item is editable. If \a editable is true, the item can be
- edited by the user; otherwise, the user cannot edit the item.
-
- How the user can edit items in a view is determined by the view's edit
- triggers; see QAbstractItemView::editTriggers.
-
- \sa isEditable(), setFlags()
-*/
-void QStandardItem::setEditable(bool editable)
-{
- Q_D(QStandardItem);
- d->changeFlags(editable, Qt::ItemIsEditable);
-}
-
-/*!
- \fn bool QStandardItem::isEditable() const
-
- Returns whether the item can be edited by the user.
-
- When an item is editable (and enabled), the user can edit the item by
- invoking one of the view's edit triggers; see
- QAbstractItemView::editTriggers.
-
- The default value is true.
-
- \sa setEditable(), flags()
-*/
-
-/*!
- Sets whether the item is selectable. If \a selectable is true, the item
- can be selected by the user; otherwise, the user cannot select the item.
-
- You can control the selection behavior and mode by manipulating their
- view properties; see QAbstractItemView::selectionMode and
- QAbstractItemView::selectionBehavior.
-
- \sa isSelectable(), setFlags()
-*/
-void QStandardItem::setSelectable(bool selectable)
-{
- Q_D(QStandardItem);
- d->changeFlags(selectable, Qt::ItemIsSelectable);
-}
-
-/*!
- \fn bool QStandardItem::isSelectable() const
-
- Returns whether the item is selectable by the user.
-
- The default value is true.
-
- \sa setSelectable(), flags()
-*/
-
-/*!
- Sets whether the item is user-checkable. If \a checkable is true, the
- item can be checked by the user; otherwise, the user cannot check
- the item.
-
- The item delegate will render a checkable item with a check box next to the
- item's text.
-
- \sa isCheckable(), setCheckState(), setTristate()
-*/
-void QStandardItem::setCheckable(bool checkable)
-{
- Q_D(QStandardItem);
- if (checkable && !isCheckable()) {
- // make sure there's data for the checkstate role
- if (!data(Qt::CheckStateRole).isValid())
- setData(Qt::Unchecked, Qt::CheckStateRole);
- }
- d->changeFlags(checkable, Qt::ItemIsUserCheckable);
-}
-
-/*!
- \fn bool QStandardItem::isCheckable() const
-
- Returns whether the item is user-checkable.
-
- The default value is false.
-
- \sa setCheckable(), checkState(), isTristate()
-*/
-
-/*!
- Sets whether the item is tristate. If \a tristate is true, the
- item is checkable with three separate states; otherwise, the item
- is checkable with two states. (Note that this also requires that
- the item is checkable; see isCheckable().)
-
- \sa isTristate(), setCheckable(), setCheckState()
-*/
-void QStandardItem::setTristate(bool tristate)
-{
- Q_D(QStandardItem);
- d->changeFlags(tristate, Qt::ItemIsTristate);
-}
-
-/*!
- \fn bool QStandardItem::isTristate() const
-
- Returns whether the item is tristate; that is, if it's checkable with three
- separate states.
-
- The default value is false.
-
- \sa setTristate(), isCheckable(), checkState()
-*/
-
-#ifndef QT_NO_DRAGANDDROP
-
-/*!
- Sets whether the item is drag enabled. If \a dragEnabled is true, the item
- can be dragged by the user; otherwise, the user cannot drag the item.
-
- Note that you also need to ensure that item dragging is enabled in the view;
- see QAbstractItemView::dragEnabled.
-
- \sa isDragEnabled(), setDropEnabled(), setFlags()
-*/
-void QStandardItem::setDragEnabled(bool dragEnabled)
-{
- Q_D(QStandardItem);
- d->changeFlags(dragEnabled, Qt::ItemIsDragEnabled);
-}
-
-/*!
- \fn bool QStandardItem::isDragEnabled() const
-
- Returns whether the item is drag enabled. An item that is drag enabled can
- be dragged by the user.
-
- The default value is true.
-
- Note that item dragging must be enabled in the view for dragging to work;
- see QAbstractItemView::dragEnabled.
-
- \sa setDragEnabled(), isDropEnabled(), flags()
-*/
-
-/*!
- Sets whether the item is drop enabled. If \a dropEnabled is true, the item
- can be used as a drop target; otherwise, it cannot.
-
- Note that you also need to ensure that drops are enabled in the view; see
- QWidget::acceptDrops(); and that the model supports the desired drop actions;
- see QAbstractItemModel::supportedDropActions().
-
- \sa isDropEnabled(), setDragEnabled(), setFlags()
-*/
-void QStandardItem::setDropEnabled(bool dropEnabled)
-{
- Q_D(QStandardItem);
- d->changeFlags(dropEnabled, Qt::ItemIsDropEnabled);
-}
-
-/*!
- \fn bool QStandardItem::isDropEnabled() const
-
- Returns whether the item is drop enabled. When an item is drop enabled, it
- can be used as a drop target.
-
- The default value is true.
-
- \sa setDropEnabled(), isDragEnabled(), flags()
-*/
-
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- Returns the row where the item is located in its parent's child table, or
- -1 if the item has no parent.
-
- \sa column(), parent()
-*/
-int QStandardItem::row() const
-{
- Q_D(const QStandardItem);
- QPair<int, int> pos = d->position();
- return pos.first;
-}
-
-/*!
- Returns the column where the item is located in its parent's child table,
- or -1 if the item has no parent.
-
- \sa row(), parent()
-*/
-int QStandardItem::column() const
-{
- Q_D(const QStandardItem);
- QPair<int, int> pos = d->position();
- return pos.second;
-}
-
-/*!
- Returns the QModelIndex associated with this item.
-
- When you need to invoke item functionality in a QModelIndex-based API (e.g.
- QAbstractItemView), you can call this function to obtain an index that
- corresponds to the item's location in the model.
-
- If the item is not associated with a model, an invalid QModelIndex is
- returned.
-
- \sa model(), QStandardItemModel::itemFromIndex()
-*/
-QModelIndex QStandardItem::index() const
-{
- Q_D(const QStandardItem);
- return d->model ? d->model->indexFromItem(this) : QModelIndex();
-}
-
-/*!
- Returns the QStandardItemModel that this item belongs to.
-
- If the item is not a child of another item that belongs to the model, this
- function returns 0.
-
- \sa index()
-*/
-QStandardItemModel *QStandardItem::model() const
-{
- Q_D(const QStandardItem);
- return d->model;
-}
-
-/*!
- Sets the number of child item rows to \a rows. If this is less than
- rowCount(), the data in the unwanted rows is discarded.
-
- \sa rowCount(), setColumnCount()
-*/
-void QStandardItem::setRowCount(int rows)
-{
- int rc = rowCount();
- if (rc == rows)
- return;
- if (rc < rows)
- insertRows(qMax(rc, 0), rows - rc);
- else
- removeRows(qMax(rows, 0), rc - rows);
-}
-
-/*!
- Returns the number of child item rows that the item has.
-
- \sa setRowCount(), columnCount()
-*/
-int QStandardItem::rowCount() const
-{
- Q_D(const QStandardItem);
- return d->rowCount();
-}
-
-/*!
- Sets the number of child item columns to \a columns. If this is less than
- columnCount(), the data in the unwanted columns is discarded.
-
- \sa columnCount(), setRowCount()
-*/
-void QStandardItem::setColumnCount(int columns)
-{
- int cc = columnCount();
- if (cc == columns)
- return;
- if (cc < columns)
- insertColumns(qMax(cc, 0), columns - cc);
- else
- removeColumns(qMax(columns, 0), cc - columns);
-}
-
-/*!
- Returns the number of child item columns that the item has.
-
- \sa setColumnCount(), rowCount()
-*/
-int QStandardItem::columnCount() const
-{
- Q_D(const QStandardItem);
- return d->columnCount();
-}
-
-/*!
- Inserts a row at \a row containing \a items. If necessary, the column
- count is increased to the size of \a items.
-
- \sa insertRows(), insertColumn()
-*/
-void QStandardItem::insertRow(int row, const QList<QStandardItem*> &items)
-{
- Q_D(QStandardItem);
- if (row < 0)
- return;
- if (columnCount() < items.count())
- setColumnCount(items.count());
- d->insertRows(row, 1, items);
-}
-
-/*!
- Inserts \a items at \a row. The column count wont be changed.
-
- \sa insertRow(), insertColumn()
-*/
-void QStandardItem::insertRows(int row, const QList<QStandardItem*> &items)
-{
- Q_D(QStandardItem);
- if (row < 0)
- return;
- d->insertRows(row, items);
-}
-
-/*!
- Inserts a column at \a column containing \a items. If necessary,
- the row count is increased to the size of \a items.
-
- \sa insertColumns(), insertRow()
-*/
-void QStandardItem::insertColumn(int column, const QList<QStandardItem*> &items)
-{
- Q_D(QStandardItem);
- if (column < 0)
- return;
- if (rowCount() < items.count())
- setRowCount(items.count());
- d->insertColumns(column, 1, items);
-}
-
-/*!
- Inserts \a count rows of child items at row \a row.
-
- \sa insertRow(), insertColumns()
-*/
-void QStandardItem::insertRows(int row, int count)
-{
- Q_D(QStandardItem);
- if (rowCount() < row) {
- count += row - rowCount();
- row = rowCount();
- }
- d->insertRows(row, count, QList<QStandardItem*>());
-}
-
-/*!
- Inserts \a count columns of child items at column \a column.
-
- \sa insertColumn(), insertRows()
-*/
-void QStandardItem::insertColumns(int column, int count)
-{
- Q_D(QStandardItem);
- if (columnCount() < column) {
- count += column - columnCount();
- column = columnCount();
- }
- d->insertColumns(column, count, QList<QStandardItem*>());
-}
-
-/*!
- \fn void QStandardItem::appendRow(const QList<QStandardItem*> &items)
-
- Appends a row containing \a items. If necessary, the column count is
- increased to the size of \a items.
-
- \sa insertRow()
-*/
-
-/*!
- \fn void QStandardItem::appendRows(const QList<QStandardItem*> &items)
-
- Appends rows containing \a items. The column count will not change.
-
- \sa insertRow()
-*/
-
-/*!
- \fn void QStandardItem::appendColumn(const QList<QStandardItem*> &items)
-
- Appends a column containing \a items. If necessary, the row count is
- increased to the size of \a items.
-
- \sa insertColumn()
-*/
-
-/*!
- \fn bool QStandardItemModel::insertRow(int row, const QModelIndex &parent)
-
- Inserts a single row before the given \a row in the child items of the
- \a parent specified. Returns true if the row is inserted; otherwise
- returns false.
-
- \sa insertRows(), insertColumn(), removeRow()
-*/
-
-/*!
- \fn bool QStandardItemModel::insertColumn(int column, const QModelIndex &parent)
-
- Inserts a single column before the given \a column in the child items of
- the \a parent specified. Returns true if the column is inserted; otherwise
- returns false.
-
- \sa insertColumns(), insertRow(), removeColumn()
-*/
-
-/*!
- \fn QStandardItem::insertRow(int row, QStandardItem *item)
- \overload
-
- Inserts a row at \a row containing \a item.
-
- When building a list or a tree that has only one column, this function
- provides a convenient way to insert a single new item.
-*/
-
-/*!
- \fn QStandardItem::appendRow(QStandardItem *item)
- \overload
-
- Appends a row containing \a item.
-
- When building a list or a tree that has only one column, this function
- provides a convenient way to append a single new item.
-*/
-
-/*!
- Removes the given \a row. The items that were in the row are deleted.
-
- \sa takeRow(), removeRows(), removeColumn()
-*/
-void QStandardItem::removeRow(int row)
-{
- removeRows(row, 1);
-}
-
-/*!
- Removes the given \a column. The items that were in the
- column are deleted.
-
- \sa takeColumn(), removeColumns(), removeRow()
-*/
-void QStandardItem::removeColumn(int column)
-{
- removeColumns(column, 1);
-}
-
-/*!
- Removes \a count rows at row \a row. The items that were in those rows are
- deleted.
-
- \sa removeRow(), removeColumn()
-*/
-void QStandardItem::removeRows(int row, int count)
-{
- Q_D(QStandardItem);
- if ((count < 1) || (row < 0) || ((row + count) > rowCount()))
- return;
- if (d->model)
- d->model->d_func()->rowsAboutToBeRemoved(this, row, row + count - 1);
- int i = d->childIndex(row, 0);
- int n = count * d->columnCount();
- for (int j = i; j < n+i; ++j) {
- QStandardItem *oldItem = d->children.at(j);
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
- }
- d->children.remove(qMax(i, 0), n);
- d->rows -= count;
- if (d->model)
- d->model->d_func()->rowsRemoved(this, row, count);
-}
-
-/*!
- Removes \a count columns at column \a column. The items that were in those
- columns are deleted.
-
- \sa removeColumn(), removeRows()
-*/
-void QStandardItem::removeColumns(int column, int count)
-{
- Q_D(QStandardItem);
- if ((count < 1) || (column < 0) || ((column + count) > columnCount()))
- return;
- if (d->model)
- d->model->d_func()->columnsAboutToBeRemoved(this, column, column + count - 1);
- for (int row = d->rowCount() - 1; row >= 0; --row) {
- int i = d->childIndex(row, column);
- for (int j=i; j<i+count; ++j) {
- QStandardItem *oldItem = d->children.at(j);
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
- }
- d->children.remove(i, count);
- }
- d->columns -= count;
- if (d->model)
- d->model->d_func()->columnsRemoved(this, column, count);
-}
-
-/*!
- Returns true if this item has any children; otherwise returns false.
-
- \sa rowCount(), columnCount(), child()
-*/
-bool QStandardItem::hasChildren() const
-{
- return (rowCount() > 0) && (columnCount() > 0);
-}
-
-/*!
- Sets the child item at (\a row, \a column) to \a item. This item (the parent
- item) takes ownership of \a item. If necessary, the row count and column
- count are increased to fit the item.
-
- \sa child()
-*/
-void QStandardItem::setChild(int row, int column, QStandardItem *item)
-{
- Q_D(QStandardItem);
- d->setChild(row, column, item, true);
-}
-
-/*!
- \fn QStandardItem::setChild(int row, QStandardItem *item)
- \overload
-
- Sets the child at \a row to \a item.
-*/
-
-/*!
- Returns the child item at (\a row, \a column) if one has been set; otherwise
- returns 0.
-
- \sa setChild(), takeChild(), parent()
-*/
-QStandardItem *QStandardItem::child(int row, int column) const
-{
- Q_D(const QStandardItem);
- int index = d->childIndex(row, column);
- if (index == -1)
- return 0;
- return d->children.at(index);
-}
-
-/*!
- Removes the child item at (\a row, \a column) without deleting it, and returns
- a pointer to the item. If there was no child at the given location, then
- this function returns 0.
-
- Note that this function, unlike takeRow() and takeColumn(), does not affect
- the dimensions of the child table.
-
- \sa child(), takeRow(), takeColumn()
-*/
-QStandardItem *QStandardItem::takeChild(int row, int column)
-{
- Q_D(QStandardItem);
- QStandardItem *item = 0;
- int index = d->childIndex(row, column);
- if (index != -1) {
- item = d->children.at(index);
- if (item)
- item->d_func()->setParentAndModel(0, 0);
- d->children.replace(index, 0);
- }
- return item;
-}
-
-/*!
- Removes \a row without deleting the row items, and returns a list of
- pointers to the removed items. For items in the row that have not been
- set, the corresponding pointers in the list will be 0.
-
- \sa removeRow(), insertRow(), takeColumn()
-*/
-QList<QStandardItem*> QStandardItem::takeRow(int row)
-{
- Q_D(QStandardItem);
- if ((row < 0) || (row >= rowCount()))
- return QList<QStandardItem*>();
- if (d->model)
- d->model->d_func()->rowsAboutToBeRemoved(this, row, row);
- QList<QStandardItem*> items;
- int index = d->childIndex(row, 0); // Will return -1 if there are no columns
- if (index != -1) {
- int col_count = d->columnCount();
- for (int column = 0; column < col_count; ++column) {
- QStandardItem *ch = d->children.at(index + column);
- if (ch)
- ch->d_func()->setParentAndModel(0, 0);
- items.append(ch);
- }
- d->children.remove(index, col_count);
- }
- d->rows--;
- if (d->model)
- d->model->d_func()->rowsRemoved(this, row, 1);
- return items;
-}
-
-/*!
- Removes \a column without deleting the column items, and returns a list of
- pointers to the removed items. For items in the column that have not been
- set, the corresponding pointers in the list will be 0.
-
- \sa removeColumn(), insertColumn(), takeRow()
-*/
-QList<QStandardItem*> QStandardItem::takeColumn(int column)
-{
- Q_D(QStandardItem);
- if ((column < 0) || (column >= columnCount()))
- return QList<QStandardItem*>();
- if (d->model)
- d->model->d_func()->columnsAboutToBeRemoved(this, column, column);
- QList<QStandardItem*> items;
-
- for (int row = d->rowCount() - 1; row >= 0; --row) {
- int index = d->childIndex(row, column);
- QStandardItem *ch = d->children.at(index);
- if (ch)
- ch->d_func()->setParentAndModel(0, 0);
- d->children.remove(index);
- items.prepend(ch);
- }
- d->columns--;
- if (d->model)
- d->model->d_func()->columnsRemoved(this, column, 1);
- return items;
-}
-
-/*!
- Returns true if this item is less than \a other; otherwise returns false.
-
- The default implementation uses the data for the item's sort role (see
- QStandardItemModel::sortRole) to perform the comparison if the item
- belongs to a model; otherwise, the data for the item's Qt::DisplayRole
- (text()) is used to perform the comparison.
-
- sortChildren() and QStandardItemModel::sort() use this function when
- sorting items. If you want custom sorting, you can subclass QStandardItem
- and reimplement this function.
-*/
-bool QStandardItem::operator<(const QStandardItem &other) const
-{
- const int role = model() ? model()->sortRole() : Qt::DisplayRole;
- const QVariant l = data(role), r = other.data(role);
- // this code is copied from QSortFilterProxyModel::lessThan()
- switch (l.userType()) {
- case QVariant::Invalid:
- return (r.type() == QVariant::Invalid);
- case QVariant::Int:
- return l.toInt() < r.toInt();
- case QVariant::UInt:
- return l.toUInt() < r.toUInt();
- case QVariant::LongLong:
- return l.toLongLong() < r.toLongLong();
- case QVariant::ULongLong:
- return l.toULongLong() < r.toULongLong();
- case QMetaType::Float:
- return l.toFloat() < r.toFloat();
- case QVariant::Double:
- return l.toDouble() < r.toDouble();
- case QVariant::Char:
- return l.toChar() < r.toChar();
- case QVariant::Date:
- return l.toDate() < r.toDate();
- case QVariant::Time:
- return l.toTime() < r.toTime();
- case QVariant::DateTime:
- return l.toDateTime() < r.toDateTime();
- case QVariant::String:
- default:
- return l.toString().compare(r.toString()) < 0;
- }
-}
-
-/*!
- Sorts the children of the item using the given \a order, by the values in
- the given \a column.
-
- \note This function is recursive, therefore it sorts the children of the
- item, its grandchildren, etc.
-
- \sa {operator<()}
-*/
-void QStandardItem::sortChildren(int column, Qt::SortOrder order)
-{
- Q_D(QStandardItem);
- if ((column < 0) || (rowCount() == 0))
- return;
- if (d->model)
- emit d->model->layoutAboutToBeChanged();
- d->sortChildren(column, order);
- if (d->model)
- emit d->model->layoutChanged();
-}
-
-/*!
- Returns a copy of this item. The item's children are not copied.
-
- When subclassing QStandardItem, you can reimplement this function
- to provide QStandardItemModel with a factory that it can use to
- create new items on demand.
-
- \sa QStandardItemModel::setItemPrototype(), operator=()
-*/
-QStandardItem *QStandardItem::clone() const
-{
- return new QStandardItem(*this);
-}
-
-/*!
- Returns the type of this item. The type is used to distinguish custom
- items from the base class. When subclassing QStandardItem, you should
- reimplement this function and return a new value greater than or equal
- to \l UserType.
-
- \sa QStandardItem::Type
-*/
-int QStandardItem::type() const
-{
- return Type;
-}
-
-#ifndef QT_NO_DATASTREAM
-
-/*!
- Reads the item from stream \a in. Only the data and flags of the item are
- read, not the child items.
-
- \sa write()
-*/
-void QStandardItem::read(QDataStream &in)
-{
- Q_D(QStandardItem);
- in >> d->values;
- qint32 flags;
- in >> flags;
- setFlags(Qt::ItemFlags(flags));
-}
-
-/*!
- Writes the item to stream \a out. Only the data and flags of the item
- are written, not the child items.
-
- \sa read()
-*/
-void QStandardItem::write(QDataStream &out) const
-{
- Q_D(const QStandardItem);
- out << d->values;
- out << flags();
-}
-
-/*!
- \relates QStandardItem
- \since 4.2
-
- Reads a QStandardItem from stream \a in into \a item.
-
- This operator uses QStandardItem::read().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator>>(QDataStream &in, QStandardItem &item)
-{
- item.read(in);
- return in;
-}
-
-/*!
- \relates QStandardItem
- \since 4.2
-
- Writes the QStandardItem \a item to stream \a out.
-
- This operator uses QStandardItem::write().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator<<(QDataStream &out, const QStandardItem &item)
-{
- item.write(out);
- return out;
-}
-
-#endif // QT_NO_DATASTREAM
-
-/*!
- \class QStandardItemModel
- \brief The QStandardItemModel class provides a generic model for storing custom data.
- \ingroup model-view
-
- QStandardItemModel can be used as a repository for standard Qt
- data types. It is one of the \l {Model/View Classes} and is part
- of Qt's \l {Model/View Programming}{model/view} framework.
-
- QStandardItemModel provides a classic item-based approach to working with
- the model. The items in a QStandardItemModel are provided by
- QStandardItem.
-
- QStandardItemModel implements the QAbstractItemModel interface, which
- means that the model can be used to provide data in any view that supports
- that interface (such as QListView, QTableView and QTreeView, and your own
- custom views). For performance and flexibility, you may want to subclass
- QAbstractItemModel to provide support for different kinds of data
- repositories. For example, the QDirModel provides a model interface to the
- underlying file system.
-
- When you want a list or tree, you typically create an empty
- QStandardItemModel and use appendRow() to add items to the model, and
- item() to access an item. If your model represents a table, you typically
- pass the dimensions of the table to the QStandardItemModel constructor and
- use setItem() to position items into the table. You can also use setRowCount()
- and setColumnCount() to alter the dimensions of the model. To insert items,
- use insertRow() or insertColumn(), and to remove items, use removeRow() or
- removeColumn().
-
- You can set the header labels of your model with setHorizontalHeaderLabels()
- and setVerticalHeaderLabels().
-
- You can search for items in the model with findItems(), and sort the model by
- calling sort().
-
- Call clear() to remove all items from the model.
-
- An example usage of QStandardItemModel to create a table:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp 0
-
- An example usage of QStandardItemModel to create a tree:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp 1
-
- After setting the model on a view, you typically want to react to user
- actions, such as an item being clicked. Since a QAbstractItemView provides
- QModelIndex-based signals and functions, you need a way to obtain the
- QStandardItem that corresponds to a given QModelIndex, and vice
- versa. itemFromIndex() and indexFromItem() provide this mapping. Typical
- usage of itemFromIndex() includes obtaining the item at the current index
- in a view, and obtaining the item that corresponds to an index carried by
- a QAbstractItemView signal, such as QAbstractItemView::clicked(). First
- you connect the view's signal to a slot in your class:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp 2
-
- When you receive the signal, you call itemFromIndex() on the given model
- index to get a pointer to the item:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp 3
-
- Conversely, you must obtain the QModelIndex of an item when you want to
- invoke a model/view function that takes an index as argument. You can
- obtain the index either by using the model's indexFromItem() function, or,
- equivalently, by calling QStandardItem::index():
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp 4
-
- You are, of course, not required to use the item-based approach; you could
- instead rely entirely on the QAbstractItemModel interface when working with
- the model, or use a combination of the two as appropriate.
-
- \sa QStandardItem, {Model/View Programming}, QAbstractItemModel,
- {itemviews/simpletreemodel}{Simple Tree Model example},
- {Item View Convenience Classes}
-*/
-
-/*!
- \fn void QStandardItemModel::itemChanged(QStandardItem *item)
- \since 4.2
-
- This signal is emitted whenever the data of \a item has changed.
-*/
-
-/*!
- Constructs a new item model with the given \a parent.
-*/
-QStandardItemModel::QStandardItemModel(QObject *parent)
- : QAbstractItemModel(*new QStandardItemModelPrivate, parent)
-{
- Q_D(QStandardItemModel);
- d->init();
- d->root->d_func()->setModel(this);
-}
-
-/*!
- Constructs a new item model that initially has \a rows rows and \a columns
- columns, and that has the given \a parent.
-*/
-QStandardItemModel::QStandardItemModel(int rows, int columns, QObject *parent)
- : QAbstractItemModel(*new QStandardItemModelPrivate, parent)
-{
- Q_D(QStandardItemModel);
- d->init();
- d->root->insertColumns(0, columns);
- d->columnHeaderItems.insert(0, columns, 0);
- d->root->insertRows(0, rows);
- d->rowHeaderItems.insert(0, rows, 0);
- d->root->d_func()->setModel(this);
-}
-
-/*!
- \internal
-*/
-QStandardItemModel::QStandardItemModel(QStandardItemModelPrivate &dd, QObject *parent)
- : QAbstractItemModel(dd, parent)
-{
- Q_D(QStandardItemModel);
- d->init();
-}
-
-/*!
- Destructs the model. The model destroys all its items.
-*/
-QStandardItemModel::~QStandardItemModel()
-{
-}
-
-/*!
- Removes all items (including header items) from the model and sets the
- number of rows and columns to zero.
-
- \sa removeColumns(), removeRows()
-*/
-void QStandardItemModel::clear()
-{
- Q_D(QStandardItemModel);
- d->root.reset(new QStandardItem);
- d->root->d_func()->setModel(this);
- qDeleteAll(d->columnHeaderItems);
- d->columnHeaderItems.clear();
- qDeleteAll(d->rowHeaderItems);
- d->rowHeaderItems.clear();
- reset();
-}
-
-/*!
- \since 4.2
-
- Returns a pointer to the QStandardItem associated with the given \a index.
-
- Calling this function is typically the initial step when processing
- QModelIndex-based signals from a view, such as
- QAbstractItemView::activated(). In your slot, you call itemFromIndex(),
- with the QModelIndex carried by the signal as argument, to obtain a
- pointer to the corresponding QStandardItem.
-
- Note that this function will lazily create an item for the index (using
- itemPrototype()), and set it in the parent item's child table, if no item
- already exists at that index.
-
- If \a index is an invalid index, this function returns 0.
-
- \sa indexFromItem()
-*/
-QStandardItem *QStandardItemModel::itemFromIndex(const QModelIndex &index) const
-{
- Q_D(const QStandardItemModel);
- if ((index.row() < 0) || (index.column() < 0) || (index.model() != this))
- return 0;
- QStandardItem *parent = static_cast<QStandardItem*>(index.internalPointer());
- if (parent == 0)
- return 0;
- QStandardItem *item = parent->child(index.row(), index.column());
- // lazy part
- if (item == 0) {
- item = d->createItem();
- parent->d_func()->setChild(index.row(), index.column(), item);
- }
- return item;
-}
-
-/*!
- \since 4.2
-
- Returns the QModelIndex associated with the given \a item.
-
- Use this function when you want to perform an operation that requires the
- QModelIndex of the item, such as
- QAbstractItemView::scrollTo(). QStandardItem::index() is provided as
- convenience; it is equivalent to calling this function.
-
- \sa itemFromIndex(), QStandardItem::index()
-*/
-QModelIndex QStandardItemModel::indexFromItem(const QStandardItem *item) const
-{
- if (item && item->d_func()->parent) {
- QPair<int, int> pos = item->d_func()->position();
- return createIndex(pos.first, pos.second, item->d_func()->parent);
- }
- return QModelIndex();
-}
-
-/*!
- \since 4.2
-
- Sets the number of rows in this model to \a rows. If
- this is less than rowCount(), the data in the unwanted rows
- is discarded.
-
- \sa setColumnCount()
-*/
-void QStandardItemModel::setRowCount(int rows)
-{
- Q_D(QStandardItemModel);
- d->root->setRowCount(rows);
-}
-
-/*!
- \since 4.2
-
- Sets the number of columns in this model to \a columns. If
- this is less than columnCount(), the data in the unwanted columns
- is discarded.
-
- \sa setRowCount()
-*/
-void QStandardItemModel::setColumnCount(int columns)
-{
- Q_D(QStandardItemModel);
- d->root->setColumnCount(columns);
-}
-
-/*!
- \since 4.2
-
- Sets the item for the given \a row and \a column to \a item. The model
- takes ownership of the item. If necessary, the row count and column count
- are increased to fit the item. The previous item at the given location (if
- there was one) is deleted.
-
- \sa item()
-*/
-void QStandardItemModel::setItem(int row, int column, QStandardItem *item)
-{
- Q_D(QStandardItemModel);
- d->root->d_func()->setChild(row, column, item, true);
-}
-
-/*!
- \fn QStandardItemModel::setItem(int row, QStandardItem *item)
- \overload
-*/
-
-/*!
- \since 4.2
-
- Returns the item for the given \a row and \a column if one has been set;
- otherwise returns 0.
-
- \sa setItem(), takeItem(), itemFromIndex()
-*/
-QStandardItem *QStandardItemModel::item(int row, int column) const
-{
- Q_D(const QStandardItemModel);
- return d->root->child(row, column);
-}
-
-/*!
- \since 4.2
-
- Returns the model's invisible root item.
-
- The invisible root item provides access to the model's top-level items
- through the QStandardItem API, making it possible to write functions that
- can treat top-level items and their children in a uniform way; for
- example, recursive functions involving a tree model.
-
- \note Calling \l{QAbstractItemModel::index()}{index()} on the QStandardItem object
- retrieved from this function is not valid.
-*/
-QStandardItem *QStandardItemModel::invisibleRootItem() const
-{
- Q_D(const QStandardItemModel);
- return d->root.data();
-}
-
-/*!
- \since 4.2
-
- Sets the horizontal header item for \a column to \a item. The model takes
- ownership of the item. If necessary, the column count is increased to fit
- the item. The previous header item (if there was one) is deleted.
-
- \sa horizontalHeaderItem(), setHorizontalHeaderLabels(),
- setVerticalHeaderItem()
-*/
-void QStandardItemModel::setHorizontalHeaderItem(int column, QStandardItem *item)
-{
- Q_D(QStandardItemModel);
- if (column < 0)
- return;
- if (columnCount() <= column)
- setColumnCount(column + 1);
-
- QStandardItem *oldItem = d->columnHeaderItems.at(column);
- if (item == oldItem)
- return;
-
- if (item) {
- if (item->model() == 0) {
- item->d_func()->setModel(this);
- } else {
- qWarning("QStandardItem::setHorizontalHeaderItem: Ignoring duplicate insertion of item %p",
- item);
- return;
- }
- }
-
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
-
- d->columnHeaderItems.replace(column, item);
- emit headerDataChanged(Qt::Horizontal, column, column);
-}
-
-/*!
- \since 4.2
-
- Returns the horizontal header item for \a column if one has been set;
- otherwise returns 0.
-
- \sa setHorizontalHeaderItem(), verticalHeaderItem()
-*/
-QStandardItem *QStandardItemModel::horizontalHeaderItem(int column) const
-{
- Q_D(const QStandardItemModel);
- if ((column < 0) || (column >= columnCount()))
- return 0;
- return d->columnHeaderItems.at(column);
-}
-
-/*!
- \since 4.2
-
- Sets the vertical header item for \a row to \a item. The model takes
- ownership of the item. If necessary, the row count is increased to fit the
- item. The previous header item (if there was one) is deleted.
-
- \sa verticalHeaderItem(), setVerticalHeaderLabels(),
- setHorizontalHeaderItem()
-*/
-void QStandardItemModel::setVerticalHeaderItem(int row, QStandardItem *item)
-{
- Q_D(QStandardItemModel);
- if (row < 0)
- return;
- if (rowCount() <= row)
- setRowCount(row + 1);
-
- QStandardItem *oldItem = d->rowHeaderItems.at(row);
- if (item == oldItem)
- return;
-
- if (item) {
- if (item->model() == 0) {
- item->d_func()->setModel(this);
- } else {
- qWarning("QStandardItem::setVerticalHeaderItem: Ignoring duplicate insertion of item %p",
- item);
- return;
- }
- }
-
- if (oldItem)
- oldItem->d_func()->setModel(0);
- delete oldItem;
-
- d->rowHeaderItems.replace(row, item);
- emit headerDataChanged(Qt::Vertical, row, row);
-}
-
-/*!
- \since 4.2
-
- Returns the vertical header item for row \a row if one has been set;
- otherwise returns 0.
-
- \sa setVerticalHeaderItem(), horizontalHeaderItem()
-*/
-QStandardItem *QStandardItemModel::verticalHeaderItem(int row) const
-{
- Q_D(const QStandardItemModel);
- if ((row < 0) || (row >= rowCount()))
- return 0;
- return d->rowHeaderItems.at(row);
-}
-
-/*!
- \since 4.2
-
- Sets the horizontal header labels using \a labels. If necessary, the
- column count is increased to the size of \a labels.
-
- \sa setHorizontalHeaderItem()
-*/
-void QStandardItemModel::setHorizontalHeaderLabels(const QStringList &labels)
-{
- Q_D(QStandardItemModel);
- if (columnCount() < labels.count())
- setColumnCount(labels.count());
- for (int i = 0; i < labels.count(); ++i) {
- QStandardItem *item = horizontalHeaderItem(i);
- if (!item) {
- item = d->createItem();
- setHorizontalHeaderItem(i, item);
- }
- item->setText(labels.at(i));
- }
-}
-
-/*!
- \since 4.2
-
- Sets the vertical header labels using \a labels. If necessary, the row
- count is increased to the size of \a labels.
-
- \sa setVerticalHeaderItem()
-*/
-void QStandardItemModel::setVerticalHeaderLabels(const QStringList &labels)
-{
- Q_D(QStandardItemModel);
- if (rowCount() < labels.count())
- setRowCount(labels.count());
- for (int i = 0; i < labels.count(); ++i) {
- QStandardItem *item = verticalHeaderItem(i);
- if (!item) {
- item = d->createItem();
- setVerticalHeaderItem(i, item);
- }
- item->setText(labels.at(i));
- }
-}
-
-/*!
- \since 4.2
-
- Sets the item prototype for the model to the specified \a item. The model
- takes ownership of the prototype.
-
- The item prototype acts as a QStandardItem factory, by relying on the
- QStandardItem::clone() function. To provide your own prototype, subclass
- QStandardItem, reimplement QStandardItem::clone() and set the prototype to
- be an instance of your custom class. Whenever QStandardItemModel needs to
- create an item on demand (for instance, when a view or item delegate calls
- setData())), the new items will be instances of your custom class.
-
- \sa itemPrototype(), QStandardItem::clone()
-*/
-void QStandardItemModel::setItemPrototype(const QStandardItem *item)
-{
- Q_D(QStandardItemModel);
- if (d->itemPrototype != item) {
- delete d->itemPrototype;
- d->itemPrototype = item;
- }
-}
-
-/*!
- \since 4.2
-
- Returns the item prototype used by the model. The model uses the item
- prototype as an item factory when it needs to construct new items on
- demand (for instance, when a view or item delegate calls setData()).
-
- \sa setItemPrototype()
-*/
-const QStandardItem *QStandardItemModel::itemPrototype() const
-{
- Q_D(const QStandardItemModel);
- return d->itemPrototype;
-}
-
-/*!
- \since 4.2
-
- Returns a list of items that match the given \a text, using the given \a
- flags, in the given \a column.
-*/
-QList<QStandardItem*> QStandardItemModel::findItems(const QString &text,
- Qt::MatchFlags flags, int column) const
-{
- QModelIndexList indexes = match(index(0, column, QModelIndex()),
- Qt::DisplayRole, text, -1, flags);
- QList<QStandardItem*> items;
- for (int i = 0; i < indexes.size(); ++i)
- items.append(itemFromIndex(indexes.at(i)));
- return items;
-}
-
-/*!
- \since 4.2
-
- Appends a row containing \a items. If necessary, the column count is
- increased to the size of \a items.
-
- \sa insertRow(), appendColumn()
-*/
-void QStandardItemModel::appendRow(const QList<QStandardItem*> &items)
-{
- invisibleRootItem()->appendRow(items);
-}
-
-/*!
- \since 4.2
-
- Appends a column containing \a items. If necessary, the row count is
- increased to the size of \a items.
-
- \sa insertColumn(), appendRow()
-*/
-void QStandardItemModel::appendColumn(const QList<QStandardItem*> &items)
-{
- invisibleRootItem()->appendColumn(items);
-}
-
-/*!
- \since 4.2
- \fn QStandardItemModel::appendRow(QStandardItem *item)
- \overload
-
- When building a list or a tree that has only one column, this function
- provides a convenient way to append a single new \a item.
-*/
-
-/*!
- \since 4.2
-
- Inserts a row at \a row containing \a items. If necessary, the column
- count is increased to the size of \a items.
-
- \sa takeRow(), appendRow(), insertColumn()
-*/
-void QStandardItemModel::insertRow(int row, const QList<QStandardItem*> &items)
-{
- invisibleRootItem()->insertRow(row, items);
-}
-
-/*!
- \since 4.2
-
- \fn void QStandardItemModel::insertRow(int row, QStandardItem *item)
- \overload
-
- Inserts a row at \a row containing \a item.
-
- When building a list or a tree that has only one column, this function
- provides a convenient way to append a single new item.
-*/
-
-/*!
- \since 4.2
-
- Inserts a column at \a column containing \a items. If necessary, the row
- count is increased to the size of \a items.
-
- \sa takeColumn(), appendColumn(), insertRow()
-*/
-void QStandardItemModel::insertColumn(int column, const QList<QStandardItem*> &items)
-{
- invisibleRootItem()->insertColumn(column, items);
-}
-
-/*!
- \since 4.2
-
- Removes the item at (\a row, \a column) without deleting it. The model
- releases ownership of the item.
-
- \sa item(), takeRow(), takeColumn()
-*/
-QStandardItem *QStandardItemModel::takeItem(int row, int column)
-{
- Q_D(QStandardItemModel);
- return d->root->takeChild(row, column);
-}
-
-/*!
- \since 4.2
-
- Removes the given \a row without deleting the row items, and returns a
- list of pointers to the removed items. The model releases ownership of the
- items. For items in the row that have not been set, the corresponding
- pointers in the list will be 0.
-
- \sa takeColumn()
-*/
-QList<QStandardItem*> QStandardItemModel::takeRow(int row)
-{
- Q_D(QStandardItemModel);
- return d->root->takeRow(row);
-}
-
-/*!
- \since 4.2
-
- Removes the given \a column without deleting the column items, and returns
- a list of pointers to the removed items. The model releases ownership of
- the items. For items in the column that have not been set, the
- corresponding pointers in the list will be 0.
-
- \sa takeRow()
-*/
-QList<QStandardItem*> QStandardItemModel::takeColumn(int column)
-{
- Q_D(QStandardItemModel);
- return d->root->takeColumn(column);
-}
-
-/*!
- \since 4.2
-
- Removes the horizontal header item at \a column from the header without
- deleting it, and returns a pointer to the item. The model releases
- ownership of the item.
-
- \sa horizontalHeaderItem(), takeVerticalHeaderItem()
-*/
-QStandardItem *QStandardItemModel::takeHorizontalHeaderItem(int column)
-{
- Q_D(QStandardItemModel);
- if ((column < 0) || (column >= columnCount()))
- return 0;
- QStandardItem *headerItem = d->columnHeaderItems.at(column);
- if (headerItem) {
- headerItem->d_func()->setParentAndModel(0, 0);
- d->columnHeaderItems.replace(column, 0);
- }
- return headerItem;
-}
-
-/*!
- \since 4.2
-
- Removes the vertical header item at \a row from the header without
- deleting it, and returns a pointer to the item. The model releases
- ownership of the item.
-
- \sa verticalHeaderItem(), takeHorizontalHeaderItem()
-*/
-QStandardItem *QStandardItemModel::takeVerticalHeaderItem(int row)
-{
- Q_D(QStandardItemModel);
- if ((row < 0) || (row >= rowCount()))
- return 0;
- QStandardItem *headerItem = d->rowHeaderItems.at(row);
- if (headerItem) {
- headerItem->d_func()->setParentAndModel(0, 0);
- d->rowHeaderItems.replace(row, 0);
- }
- return headerItem;
-}
-
-/*!
- \since 4.2
- \property QStandardItemModel::sortRole
- \brief the item role that is used to query the model's data when sorting items
-
- The default value is Qt::DisplayRole.
-
- \sa sort(), QStandardItem::sortChildren()
-*/
-int QStandardItemModel::sortRole() const
-{
- Q_D(const QStandardItemModel);
- return d->sortRole;
-}
-
-void QStandardItemModel::setSortRole(int role)
-{
- Q_D(QStandardItemModel);
- d->sortRole = role;
-}
-
-/*!
- \reimp
-*/
-int QStandardItemModel::columnCount(const QModelIndex &parent) const
-{
- Q_D(const QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(parent);
- return item ? item->columnCount() : 0;
-}
-
-/*!
- \reimp
-*/
-QVariant QStandardItemModel::data(const QModelIndex &index, int role) const
-{
- Q_D(const QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(index);
- return item ? item->data(role) : QVariant();
-}
-
-/*!
- \reimp
-*/
-Qt::ItemFlags QStandardItemModel::flags(const QModelIndex &index) const
-{
- Q_D(const QStandardItemModel);
- if (!d->indexValid(index))
- return d->root->flags();
- QStandardItem *item = d->itemFromIndex(index);
- if (item)
- return item->flags();
- return Qt::ItemIsSelectable
- |Qt::ItemIsEnabled
- |Qt::ItemIsEditable
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled;
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(parent);
- return item ? item->hasChildren() : false;
-}
-
-/*!
- \reimp
-*/
-QVariant QStandardItemModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- Q_D(const QStandardItemModel);
- if ((section < 0)
- || ((orientation == Qt::Horizontal) && (section >= columnCount()))
- || ((orientation == Qt::Vertical) && (section >= rowCount()))) {
- return QVariant();
- }
- QStandardItem *headerItem = 0;
- if (orientation == Qt::Horizontal)
- headerItem = d->columnHeaderItems.at(section);
- else if (orientation == Qt::Vertical)
- headerItem = d->rowHeaderItems.at(section);
- return headerItem ? headerItem->data(role)
- : QAbstractItemModel::headerData(section, orientation, role);
-}
-
-/*!
- \reimp
-
- QStandardItemModel supports both copy and move.
-*/
-Qt::DropActions QStandardItemModel::supportedDropActions () const
-{
- return Qt::CopyAction | Qt::MoveAction;
-}
-
-/*!
- \reimp
-*/
-QModelIndex QStandardItemModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_D(const QStandardItemModel);
- QStandardItem *parentItem = d->itemFromIndex(parent);
- if ((parentItem == 0)
- || (row < 0)
- || (column < 0)
- || (row >= parentItem->rowCount())
- || (column >= parentItem->columnCount())) {
- return QModelIndex();
- }
- return createIndex(row, column, parentItem);
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::insertColumns(int column, int count, const QModelIndex &parent)
-{
- Q_D(QStandardItemModel);
- QStandardItem *item = parent.isValid() ? itemFromIndex(parent) : d->root.data();
- if (item == 0)
- return false;
- return item->d_func()->insertColumns(column, count, QList<QStandardItem*>());
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::insertRows(int row, int count, const QModelIndex &parent)
-{
- Q_D(QStandardItemModel);
- QStandardItem *item = parent.isValid() ? itemFromIndex(parent) : d->root.data();
- if (item == 0)
- return false;
- return item->d_func()->insertRows(row, count, QList<QStandardItem*>());
-}
-
-/*!
- \reimp
-*/
-QMap<int, QVariant> QStandardItemModel::itemData(const QModelIndex &index) const
-{
- Q_D(const QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(index);
- return item ? item->d_func()->itemData() : QMap<int, QVariant>();
-}
-
-/*!
- \reimp
-*/
-QModelIndex QStandardItemModel::parent(const QModelIndex &child) const
-{
- Q_D(const QStandardItemModel);
- if (!d->indexValid(child))
- return QModelIndex();
- QStandardItem *parentItem = static_cast<QStandardItem*>(child.internalPointer());
- return indexFromItem(parentItem);
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::removeColumns(int column, int count, const QModelIndex &parent)
-{
- Q_D(QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(parent);
- if ((item == 0) || (count < 1) || (column < 0) || ((column + count) > item->columnCount()))
- return false;
- item->removeColumns(column, count);
- return true;
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::removeRows(int row, int count, const QModelIndex &parent)
-{
- Q_D(QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(parent);
- if ((item == 0) || (count < 1) || (row < 0) || ((row + count) > item->rowCount()))
- return false;
- item->removeRows(row, count);
- return true;
-}
-
-/*!
- \reimp
-*/
-int QStandardItemModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QStandardItemModel);
- QStandardItem *item = d->itemFromIndex(parent);
- return item ? item->rowCount() : 0;
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (!index.isValid())
- return false;
- QStandardItem *item = itemFromIndex(index);
- if (item == 0)
- return false;
- item->setData(value, role);
- return true;
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
-{
- Q_D(QStandardItemModel);
- if ((section < 0)
- || ((orientation == Qt::Horizontal) && (section >= columnCount()))
- || ((orientation == Qt::Vertical) && (section >= rowCount()))) {
- return false;
- }
- QStandardItem *headerItem = 0;
- if (orientation == Qt::Horizontal) {
- headerItem = d->columnHeaderItems.at(section);
- if (headerItem == 0) {
- headerItem = d->createItem();
- headerItem->d_func()->setModel(this);
- d->columnHeaderItems.replace(section, headerItem);
- }
- } else if (orientation == Qt::Vertical) {
- headerItem = d->rowHeaderItems.at(section);
- if (headerItem == 0) {
- headerItem = d->createItem();
- headerItem->d_func()->setModel(this);
- d->rowHeaderItems.replace(section, headerItem);
- }
- }
- if (headerItem) {
- headerItem->setData(value, role);
- return true;
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)
-{
- QStandardItem *item = itemFromIndex(index);
- if (item == 0)
- return false;
- item->d_func()->setItemData(roles);
- return true;
-}
-
-/*!
- \reimp
-*/
-void QStandardItemModel::sort(int column, Qt::SortOrder order)
-{
- Q_D(QStandardItemModel);
- d->root->sortChildren(column, order);
-}
-
-/*!
- \fn QObject *QStandardItemModel::parent() const
- \internal
-*/
-
-
-/*!
- \reimp
-*/
-QStringList QStandardItemModel::mimeTypes() const
-{
- return QAbstractItemModel::mimeTypes() << QLatin1String("application/x-qstandarditemmodeldatalist");
-}
-
-/*!
- \reimp
-*/
-QMimeData *QStandardItemModel::mimeData(const QModelIndexList &indexes) const
-{
- QMimeData *data = QAbstractItemModel::mimeData(indexes);
- if(!data)
- return 0;
-
- QString format = QLatin1String("application/x-qstandarditemmodeldatalist");
- if (!mimeTypes().contains(format))
- return data;
- QByteArray encoded;
- QDataStream stream(&encoded, QIODevice::WriteOnly);
-
- QSet<QStandardItem*> itemsSet;
- QStack<QStandardItem*> stack;
- itemsSet.reserve(indexes.count());
- stack.reserve(indexes.count());
- for (int i = 0; i < indexes.count(); ++i) {
- QStandardItem *item = itemFromIndex(indexes.at(i));
- itemsSet << item;
- stack.push(item);
- }
-
- //remove duplicates childrens
- {
- QSet<QStandardItem *> seen;
- while (!stack.isEmpty()) {
- QStandardItem *itm = stack.pop();
- if (seen.contains(itm))
- continue;
- seen.insert(itm);
-
- const QVector<QStandardItem*> &childList = itm->d_func()->children;
- for (int i = 0; i < childList.count(); ++i) {
- QStandardItem *chi = childList.at(i);
- if (chi) {
- QSet<QStandardItem *>::iterator it = itemsSet.find(chi);
- if (it != itemsSet.end()) {
- itemsSet.erase(it);
- }
- stack.push(chi);
- }
- }
- }
- }
-
- stack.reserve(itemsSet.count());
- foreach (QStandardItem *item, itemsSet) {
- stack.push(item);
- }
-
- //stream everything recursively
- while (!stack.isEmpty()) {
- QStandardItem *item = stack.pop();
- if(itemsSet.contains(item)) { //if the item is selection 'top-level', strem its position
- stream << item->row() << item->column();
- }
- if(item) {
- stream << *item << item->columnCount() << item->d_ptr->children.count();
- stack += item->d_ptr->children;
- } else {
- QStandardItem dummy;
- stream << dummy << 0 << 0;
- }
- }
-
- data->setData(format, encoded);
- return data;
-}
-
-
-/* \internal
- Used by QStandardItemModel::dropMimeData
- stream out an item and his children
- */
-void QStandardItemModelPrivate::decodeDataRecursive(QDataStream &stream, QStandardItem *item)
-{
- int colCount, childCount;
- stream >> *item;
- stream >> colCount >> childCount;
- item->setColumnCount(colCount);
-
- int childPos = childCount;
-
- while(childPos > 0) {
- childPos--;
- QStandardItem *child = createItem();
- decodeDataRecursive(stream, child);
- item->setChild( childPos / colCount, childPos % colCount, child);
- }
-}
-
-
-/*!
- \reimp
-*/
-bool QStandardItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- Q_D(QStandardItemModel);
- // check if the action is supported
- if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
- return false;
- // check if the format is supported
- QString format = QLatin1String("application/x-qstandarditemmodeldatalist");
- if (!data->hasFormat(format))
- return QAbstractItemModel::dropMimeData(data, action, row, column, parent);
-
- if (row > rowCount(parent))
- row = rowCount(parent);
- if (row == -1)
- row = rowCount(parent);
- if (column == -1)
- column = 0;
-
- // decode and insert
- QByteArray encoded = data->data(format);
- QDataStream stream(&encoded, QIODevice::ReadOnly);
-
-
- //code based on QAbstractItemModel::decodeData
- // adapted to work with QStandardItem
- int top = INT_MAX;
- int left = INT_MAX;
- int bottom = 0;
- int right = 0;
- QVector<int> rows, columns;
- QVector<QStandardItem *> items;
-
- while (!stream.atEnd()) {
- int r, c;
- QStandardItem *item = d->createItem();
- stream >> r >> c;
- d->decodeDataRecursive(stream, item);
-
- rows.append(r);
- columns.append(c);
- items.append(item);
- top = qMin(r, top);
- left = qMin(c, left);
- bottom = qMax(r, bottom);
- right = qMax(c, right);
- }
-
- // insert the dragged items into the table, use a bit array to avoid overwriting items,
- // since items from different tables can have the same row and column
- int dragRowCount = 0;
- int dragColumnCount = right - left + 1;
-
- // Compute the number of continuous rows upon insertion and modify the rows to match
- QVector<int> rowsToInsert(bottom + 1);
- for (int i = 0; i < rows.count(); ++i)
- rowsToInsert[rows.at(i)] = 1;
- for (int i = 0; i < rowsToInsert.count(); ++i) {
- if (rowsToInsert[i] == 1){
- rowsToInsert[i] = dragRowCount;
- ++dragRowCount;
- }
- }
- for (int i = 0; i < rows.count(); ++i)
- rows[i] = top + rowsToInsert[rows[i]];
-
- QBitArray isWrittenTo(dragRowCount * dragColumnCount);
-
- // make space in the table for the dropped data
- int colCount = columnCount(parent);
- if (colCount < dragColumnCount + column) {
- insertColumns(colCount, dragColumnCount + column - colCount, parent);
- colCount = columnCount(parent);
- }
- insertRows(row, dragRowCount, parent);
-
- row = qMax(0, row);
- column = qMax(0, column);
-
- QStandardItem *parentItem = itemFromIndex (parent);
- if (!parentItem)
- parentItem = invisibleRootItem();
-
- QVector<QPersistentModelIndex> newIndexes(items.size());
- // set the data in the table
- for (int j = 0; j < items.size(); ++j) {
- int relativeRow = rows.at(j) - top;
- int relativeColumn = columns.at(j) - left;
- int destinationRow = relativeRow + row;
- int destinationColumn = relativeColumn + column;
- int flat = (relativeRow * dragColumnCount) + relativeColumn;
- // if the item was already written to, or we just can't fit it in the table, create a new row
- if (destinationColumn >= colCount || isWrittenTo.testBit(flat)) {
- destinationColumn = qBound(column, destinationColumn, colCount - 1);
- destinationRow = row + dragRowCount;
- insertRows(row + dragRowCount, 1, parent);
- flat = (dragRowCount * dragColumnCount) + relativeColumn;
- isWrittenTo.resize(++dragRowCount * dragColumnCount);
- }
- if (!isWrittenTo.testBit(flat)) {
- newIndexes[j] = index(destinationRow, destinationColumn, parentItem->index());
- isWrittenTo.setBit(flat);
- }
- }
-
- for(int k = 0; k < newIndexes.size(); k++) {
- if (newIndexes.at(k).isValid()) {
- parentItem->setChild(newIndexes.at(k).row(), newIndexes.at(k).column(), items.at(k));
- } else {
- delete items.at(k);
- }
- }
-
- return true;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qstandarditemmodel.cpp"
-
-#endif // QT_NO_STANDARDITEMMODEL
diff --git a/src/gui/itemviews/qstandarditemmodel.h b/src/gui/itemviews/qstandarditemmodel.h
deleted file mode 100644
index 6cc0270dad..0000000000
--- a/src/gui/itemviews/qstandarditemmodel.h
+++ /dev/null
@@ -1,456 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTANDARDITEMMODEL_H
-#define QSTANDARDITEMMODEL_H
-
-#include <QtCore/qabstractitemmodel.h>
-#include <QtGui/qbrush.h>
-#include <QtGui/qfont.h>
-#include <QtGui/qicon.h>
-#ifndef QT_NO_DATASTREAM
-#include <QtCore/qdatastream.h>
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_STANDARDITEMMODEL
-
-template <class T> class QList;
-
-class QStandardItemModel;
-
-class QStandardItemPrivate;
-class Q_GUI_EXPORT QStandardItem
-{
-public:
- QStandardItem();
- QStandardItem(const QString &text);
- QStandardItem(const QIcon &icon, const QString &text);
- explicit QStandardItem(int rows, int columns = 1);
- virtual ~QStandardItem();
-
- virtual QVariant data(int role = Qt::UserRole + 1) const;
- virtual void setData(const QVariant &value, int role = Qt::UserRole + 1);
-
- inline QString text() const {
- return qvariant_cast<QString>(data(Qt::DisplayRole));
- }
- inline void setText(const QString &text);
-
- inline QIcon icon() const {
- return qvariant_cast<QIcon>(data(Qt::DecorationRole));
- }
- inline void setIcon(const QIcon &icon);
-
-#ifndef QT_NO_TOOLTIP
- inline QString toolTip() const {
- return qvariant_cast<QString>(data(Qt::ToolTipRole));
- }
- inline void setToolTip(const QString &toolTip);
-#endif
-
-#ifndef QT_NO_STATUSTIP
- inline QString statusTip() const {
- return qvariant_cast<QString>(data(Qt::StatusTipRole));
- }
- inline void setStatusTip(const QString &statusTip);
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- inline QString whatsThis() const {
- return qvariant_cast<QString>(data(Qt::WhatsThisRole));
- }
- inline void setWhatsThis(const QString &whatsThis);
-#endif
-
- inline QSize sizeHint() const {
- return qvariant_cast<QSize>(data(Qt::SizeHintRole));
- }
- inline void setSizeHint(const QSize &sizeHint);
-
- inline QFont font() const {
- return qvariant_cast<QFont>(data(Qt::FontRole));
- }
- inline void setFont(const QFont &font);
-
- inline Qt::Alignment textAlignment() const {
- return Qt::Alignment(qvariant_cast<int>(data(Qt::TextAlignmentRole)));
- }
- inline void setTextAlignment(Qt::Alignment textAlignment);
-
- inline QBrush background() const {
- return qvariant_cast<QBrush>(data(Qt::BackgroundRole));
- }
- inline void setBackground(const QBrush &brush);
-
- inline QBrush foreground() const {
- return qvariant_cast<QBrush>(data(Qt::ForegroundRole));
- }
- inline void setForeground(const QBrush &brush);
-
- inline Qt::CheckState checkState() const {
- return Qt::CheckState(qvariant_cast<int>(data(Qt::CheckStateRole)));
- }
- inline void setCheckState(Qt::CheckState checkState);
-
- inline QString accessibleText() const {
- return qvariant_cast<QString>(data(Qt::AccessibleTextRole));
- }
- inline void setAccessibleText(const QString &accessibleText);
-
- inline QString accessibleDescription() const {
- return qvariant_cast<QString>(data(Qt::AccessibleDescriptionRole));
- }
- inline void setAccessibleDescription(const QString &accessibleDescription);
-
- Qt::ItemFlags flags() const;
- void setFlags(Qt::ItemFlags flags);
-
- inline bool isEnabled() const {
- return (flags() & Qt::ItemIsEnabled) != 0;
- }
- void setEnabled(bool enabled);
-
- inline bool isEditable() const {
- return (flags() & Qt::ItemIsEditable) != 0;
- }
- void setEditable(bool editable);
-
- inline bool isSelectable() const {
- return (flags() & Qt::ItemIsSelectable) != 0;
- }
- void setSelectable(bool selectable);
-
- inline bool isCheckable() const {
- return (flags() & Qt::ItemIsUserCheckable) != 0;
- }
- void setCheckable(bool checkable);
-
- inline bool isTristate() const {
- return (flags() & Qt::ItemIsTristate) != 0;
- }
- void setTristate(bool tristate);
-
-#ifndef QT_NO_DRAGANDDROP
- inline bool isDragEnabled() const {
- return (flags() & Qt::ItemIsDragEnabled) != 0;
- }
- void setDragEnabled(bool dragEnabled);
-
- inline bool isDropEnabled() const {
- return (flags() & Qt::ItemIsDropEnabled) != 0;
- }
- void setDropEnabled(bool dropEnabled);
-#endif // QT_NO_DRAGANDDROP
-
- QStandardItem *parent() const;
- int row() const;
- int column() const;
- QModelIndex index() const;
- QStandardItemModel *model() const;
-
- int rowCount() const;
- void setRowCount(int rows);
- int columnCount() const;
- void setColumnCount(int columns);
-
- bool hasChildren() const;
- QStandardItem *child(int row, int column = 0) const;
- void setChild(int row, int column, QStandardItem *item);
- inline void setChild(int row, QStandardItem *item);
-
- void insertRow(int row, const QList<QStandardItem*> &items);
- void insertColumn(int column, const QList<QStandardItem*> &items);
- void insertRows(int row, const QList<QStandardItem*> &items);
- void insertRows(int row, int count);
- void insertColumns(int column, int count);
-
- void removeRow(int row);
- void removeColumn(int column);
- void removeRows(int row, int count);
- void removeColumns(int column, int count);
-
- inline void appendRow(const QList<QStandardItem*> &items);
- inline void appendRows(const QList<QStandardItem*> &items);
- inline void appendColumn(const QList<QStandardItem*> &items);
- inline void insertRow(int row, QStandardItem *item);
- inline void appendRow(QStandardItem *item);
-
- QStandardItem *takeChild(int row, int column = 0);
- QList<QStandardItem*> takeRow(int row);
- QList<QStandardItem*> takeColumn(int column);
-
- void sortChildren(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- virtual QStandardItem *clone() const;
-
- enum ItemType { Type = 0, UserType = 1000 };
- virtual int type() const;
-
-#ifndef QT_NO_DATASTREAM
- virtual void read(QDataStream &in);
- virtual void write(QDataStream &out) const;
-#endif
- virtual bool operator<(const QStandardItem &other) const;
-
-protected:
- QStandardItem(const QStandardItem &other);
- QStandardItem(QStandardItemPrivate &dd);
- QStandardItem &operator=(const QStandardItem &other);
- QScopedPointer<QStandardItemPrivate> d_ptr;
-
- void emitDataChanged();
-
-private:
- Q_DECLARE_PRIVATE(QStandardItem)
- friend class QStandardItemModelPrivate;
- friend class QStandardItemModel;
-};
-
-inline void QStandardItem::setText(const QString &atext)
-{ setData(atext, Qt::DisplayRole); }
-
-inline void QStandardItem::setIcon(const QIcon &aicon)
-{ setData(aicon, Qt::DecorationRole); }
-
-#ifndef QT_NO_TOOLTIP
-inline void QStandardItem::setToolTip(const QString &atoolTip)
-{ setData(atoolTip, Qt::ToolTipRole); }
-#endif
-
-#ifndef QT_NO_STATUSTIP
-inline void QStandardItem::setStatusTip(const QString &astatusTip)
-{ setData(astatusTip, Qt::StatusTipRole); }
-#endif
-
-#ifndef QT_NO_WHATSTHIS
-inline void QStandardItem::setWhatsThis(const QString &awhatsThis)
-{ setData(awhatsThis, Qt::WhatsThisRole); }
-#endif
-
-inline void QStandardItem::setSizeHint(const QSize &asizeHint)
-{ setData(asizeHint, Qt::SizeHintRole); }
-
-inline void QStandardItem::setFont(const QFont &afont)
-{ setData(afont, Qt::FontRole); }
-
-inline void QStandardItem::setTextAlignment(Qt::Alignment atextAlignment)
-{ setData(int(atextAlignment), Qt::TextAlignmentRole); }
-
-inline void QStandardItem::setBackground(const QBrush &abrush)
-{ setData(abrush, Qt::BackgroundRole); }
-
-inline void QStandardItem::setForeground(const QBrush &abrush)
-{ setData(abrush, Qt::ForegroundRole); }
-
-inline void QStandardItem::setCheckState(Qt::CheckState acheckState)
-{ setData(acheckState, Qt::CheckStateRole); }
-
-inline void QStandardItem::setAccessibleText(const QString &aaccessibleText)
-{ setData(aaccessibleText, Qt::AccessibleTextRole); }
-
-inline void QStandardItem::setAccessibleDescription(const QString &aaccessibleDescription)
-{ setData(aaccessibleDescription, Qt::AccessibleDescriptionRole); }
-
-inline void QStandardItem::setChild(int arow, QStandardItem *aitem)
-{ setChild(arow, 0, aitem); }
-
-inline void QStandardItem::appendRow(const QList<QStandardItem*> &aitems)
-{ insertRow(rowCount(), aitems); }
-
-inline void QStandardItem::appendRows(const QList<QStandardItem*> &aitems)
-{ insertRows(rowCount(), aitems); }
-
-inline void QStandardItem::appendColumn(const QList<QStandardItem*> &aitems)
-{ insertColumn(columnCount(), aitems); }
-
-inline void QStandardItem::insertRow(int arow, QStandardItem *aitem)
-{ insertRow(arow, QList<QStandardItem*>() << aitem); }
-
-inline void QStandardItem::appendRow(QStandardItem *aitem)
-{ insertRow(rowCount(), aitem); }
-
-class QStandardItemModelPrivate;
-
-class Q_GUI_EXPORT QStandardItemModel : public QAbstractItemModel
-{
- Q_OBJECT
- Q_PROPERTY(int sortRole READ sortRole WRITE setSortRole)
-
-public:
- explicit QStandardItemModel(QObject *parent = 0);
- QStandardItemModel(int rows, int columns, QObject *parent = 0);
- ~QStandardItemModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex &child) const;
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
-
- QVariant headerData(int section, Qt::Orientation orientation,
- int role = Qt::DisplayRole) const;
- bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value,
- int role = Qt::EditRole);
-
- bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
- bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex());
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
- bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex());
-
- Qt::ItemFlags flags(const QModelIndex &index) const;
- Qt::DropActions supportedDropActions() const;
-
- QMap<int, QVariant> itemData(const QModelIndex &index) const;
- bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles);
-
- void clear();
-
-#ifdef Q_NO_USING_KEYWORD
- inline QObject *parent() const { return QObject::parent(); }
-#else
- using QObject::parent;
-#endif
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- QStandardItem *itemFromIndex(const QModelIndex &index) const;
- QModelIndex indexFromItem(const QStandardItem *item) const;
-
- QStandardItem *item(int row, int column = 0) const;
- void setItem(int row, int column, QStandardItem *item);
- inline void setItem(int row, QStandardItem *item);
- QStandardItem *invisibleRootItem() const;
-
- QStandardItem *horizontalHeaderItem(int column) const;
- void setHorizontalHeaderItem(int column, QStandardItem *item);
- QStandardItem *verticalHeaderItem(int row) const;
- void setVerticalHeaderItem(int row, QStandardItem *item);
-
- void setHorizontalHeaderLabels(const QStringList &labels);
- void setVerticalHeaderLabels(const QStringList &labels);
-
- void setRowCount(int rows);
- void setColumnCount(int columns);
-
- void appendRow(const QList<QStandardItem*> &items);
- void appendColumn(const QList<QStandardItem*> &items);
- inline void appendRow(QStandardItem *item);
-
- void insertRow(int row, const QList<QStandardItem*> &items);
- void insertColumn(int column, const QList<QStandardItem*> &items);
- inline void insertRow(int row, QStandardItem *item);
-
- inline bool insertRow(int row, const QModelIndex &parent = QModelIndex());
- inline bool insertColumn(int column, const QModelIndex &parent = QModelIndex());
-
- QStandardItem *takeItem(int row, int column = 0);
- QList<QStandardItem*> takeRow(int row);
- QList<QStandardItem*> takeColumn(int column);
-
- QStandardItem *takeHorizontalHeaderItem(int column);
- QStandardItem *takeVerticalHeaderItem(int row);
-
- const QStandardItem *itemPrototype() const;
- void setItemPrototype(const QStandardItem *item);
-
- QList<QStandardItem*> findItems(const QString &text,
- Qt::MatchFlags flags = Qt::MatchExactly,
- int column = 0) const;
-
- int sortRole() const;
- void setSortRole(int role);
-
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
-
-Q_SIGNALS:
- void itemChanged(QStandardItem *item);
-
-protected:
- QStandardItemModel(QStandardItemModelPrivate &dd, QObject *parent = 0);
-
-private:
- friend class QStandardItemPrivate;
- friend class QStandardItem;
- Q_DISABLE_COPY(QStandardItemModel)
- Q_DECLARE_PRIVATE(QStandardItemModel)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight))
-};
-
-inline void QStandardItemModel::setItem(int arow, QStandardItem *aitem)
-{ setItem(arow, 0, aitem); }
-
-inline void QStandardItemModel::appendRow(QStandardItem *aitem)
-{ appendRow(QList<QStandardItem*>() << aitem); }
-
-inline void QStandardItemModel::insertRow(int arow, QStandardItem *aitem)
-{ insertRow(arow, QList<QStandardItem*>() << aitem); }
-
-inline bool QStandardItemModel::insertRow(int arow, const QModelIndex &aparent)
-{ return QAbstractItemModel::insertRow(arow, aparent); }
-inline bool QStandardItemModel::insertColumn(int acolumn, const QModelIndex &aparent)
-{ return QAbstractItemModel::insertColumn(acolumn, aparent); }
-
-#ifndef QT_NO_DATASTREAM
-Q_GUI_EXPORT QDataStream &operator>>(QDataStream &in, QStandardItem &item);
-Q_GUI_EXPORT QDataStream &operator<<(QDataStream &out, const QStandardItem &item);
-#endif
-
-#endif // QT_NO_STANDARDITEMMODEL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //QSTANDARDITEMMODEL_H
diff --git a/src/gui/itemviews/qstandarditemmodel_p.h b/src/gui/itemviews/qstandarditemmodel_p.h
deleted file mode 100644
index bc053398a3..0000000000
--- a/src/gui/itemviews/qstandarditemmodel_p.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTANDARDITEMMODEL_P_H
-#define QSTANDARDITEMMODEL_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 "private/qabstractitemmodel_p.h"
-
-#ifndef QT_NO_STANDARDITEMMODEL
-
-#include <private/qwidgetitemdata_p.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qpair.h>
-#include <QtCore/qstack.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
-
-QT_BEGIN_NAMESPACE
-
-class QStandardItemPrivate
-{
- Q_DECLARE_PUBLIC(QStandardItem)
-public:
- inline QStandardItemPrivate()
- : model(0),
- parent(0),
- rows(0),
- columns(0),
- q_ptr(0),
- lastIndexOf(2)
- { }
- virtual ~QStandardItemPrivate();
-
- inline int childIndex(int row, int column) const {
- if ((row < 0) || (column < 0)
- || (row >= rowCount()) || (column >= columnCount())) {
- return -1;
- }
- return (row * columnCount()) + column;
- }
- inline int childIndex(const QStandardItem *child) {
- int start = qMax(0, lastIndexOf -2);
- lastIndexOf = children.indexOf(const_cast<QStandardItem*>(child), start);
- if (lastIndexOf == -1 && start != 0)
- lastIndexOf = children.lastIndexOf(const_cast<QStandardItem*>(child), start);
- return lastIndexOf;
- }
- QPair<int, int> position() const;
- void setChild(int row, int column, QStandardItem *item,
- bool emitChanged = false);
- inline int rowCount() const {
- return rows;
- }
- inline int columnCount() const {
- return columns;
- }
- void childDeleted(QStandardItem *child);
-
- void setModel(QStandardItemModel *mod);
-
- inline void setParentAndModel(
- QStandardItem *par,
- QStandardItemModel *mod) {
- setModel(mod);
- parent = par;
- }
-
- void changeFlags(bool enable, Qt::ItemFlags f);
- void setItemData(const QMap<int, QVariant> &roles);
- const QMap<int, QVariant> itemData() const;
-
- bool insertRows(int row, int count, const QList<QStandardItem*> &items);
- bool insertRows(int row, const QList<QStandardItem*> &items);
- bool insertColumns(int column, int count, const QList<QStandardItem*> &items);
-
- void sortChildren(int column, Qt::SortOrder order);
-
- QStandardItemModel *model;
- QStandardItem *parent;
- QVector<QWidgetItemData> values;
- QVector<QStandardItem*> children;
- int rows;
- int columns;
-
- QStandardItem *q_ptr;
-
- int lastIndexOf;
-};
-
-class QStandardItemModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QStandardItemModel)
-
-public:
- QStandardItemModelPrivate();
- virtual ~QStandardItemModelPrivate();
-
- void init();
-
- inline QStandardItem *createItem() const {
- return itemPrototype ? itemPrototype->clone() : new QStandardItem;
- }
-
- inline QStandardItem *itemFromIndex(const QModelIndex &index) const {
- Q_Q(const QStandardItemModel);
- if (!index.isValid())
- return root.data();
- if (index.model() != q)
- return 0;
- QStandardItem *parent = static_cast<QStandardItem*>(index.internalPointer());
- if (parent == 0)
- return 0;
- return parent->child(index.row(), index.column());
- }
-
- void sort(QStandardItem *parent, int column, Qt::SortOrder order);
- void itemChanged(QStandardItem *item);
- void rowsAboutToBeInserted(QStandardItem *parent, int start, int end);
- void columnsAboutToBeInserted(QStandardItem *parent, int start, int end);
- void rowsAboutToBeRemoved(QStandardItem *parent, int start, int end);
- void columnsAboutToBeRemoved(QStandardItem *parent, int start, int end);
- void rowsInserted(QStandardItem *parent, int row, int count);
- void columnsInserted(QStandardItem *parent, int column, int count);
- void rowsRemoved(QStandardItem *parent, int row, int count);
- void columnsRemoved(QStandardItem *parent, int column, int count);
-
- void _q_emitItemChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight);
-
- void decodeDataRecursive(QDataStream &stream, QStandardItem *item);
-
- QVector<QStandardItem*> columnHeaderItems;
- QVector<QStandardItem*> rowHeaderItems;
- QScopedPointer<QStandardItem> root;
- const QStandardItem *itemPrototype;
- int sortRole;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STANDARDITEMMODEL
-
-#endif // QSTANDARDITEMMODEL_P_H
diff --git a/src/gui/itemviews/qstringlistmodel.cpp b/src/gui/itemviews/qstringlistmodel.cpp
deleted file mode 100644
index d2e4c2204e..0000000000
--- a/src/gui/itemviews/qstringlistmodel.cpp
+++ /dev/null
@@ -1,308 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*
- A simple model that uses a QStringList as its data source.
-*/
-
-#include "qstringlistmodel.h"
-
-#ifndef QT_NO_STRINGLISTMODEL
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QStringListModel
- \brief The QStringListModel class provides a model that supplies strings to views.
-
- \ingroup model-view
-
-
- QStringListModel is an editable model that can be used for simple
- cases where you need to display a number of strings in a view
- widget, such as a QListView or a QComboBox.
-
- The model provides all the standard functions of an editable
- model, representing the data in the string list as a model with
- one column and a number of rows equal to the number of items in
- the list.
-
- Model indexes corresponding to items are obtained with the
- \l{QAbstractListModel::index()}{index()} function, and item flags
- are obtained with flags(). Item data is read with the data()
- function and written with setData(). The number of rows (and
- number of items in the string list) can be found with the
- rowCount() function.
-
- The model can be constructed with an existing string list, or
- strings can be set later with the setStringList() convenience
- function. Strings can also be inserted in the usual way with the
- insertRows() function, and removed with removeRows(). The contents
- of the string list can be retrieved with the stringList()
- convenience function.
-
- An example usage of QStringListModel:
-
- \snippet doc/src/snippets/qstringlistmodel/main.cpp 0
-
- \sa QAbstractListModel, QAbstractItemModel, {Model Classes}
-*/
-
-/*!
- Constructs a string list model with the given \a parent.
-*/
-
-QStringListModel::QStringListModel(QObject *parent)
- : QAbstractListModel(parent)
-{
-}
-
-/*!
- Constructs a string list model containing the specified \a strings
- with the given \a parent.
-*/
-
-QStringListModel::QStringListModel(const QStringList &strings, QObject *parent)
- : QAbstractListModel(parent), lst(strings)
-{
-}
-
-/*!
- Returns the number of rows in the model. This value corresponds to the
- number of items in the model's internal string list.
-
- The optional \a parent argument is in most models used to specify
- the parent of the rows to be counted. Because this is a list if a
- valid parent is specified, the result will always be 0.
-
- \sa insertRows(), removeRows(), QAbstractItemModel::rowCount()
-*/
-
-int QStringListModel::rowCount(const QModelIndex &parent) const
-{
- if (parent.isValid())
- return 0;
-
- return lst.count();
-}
-
-/*!
- Returns data for the specified \a role, from the item with the
- given \a index.
-
- If the view requests an invalid index, an invalid variant is returned.
-
- \sa setData()
-*/
-
-QVariant QStringListModel::data(const QModelIndex &index, int role) const
-{
- if (index.row() < 0 || index.row() >= lst.size())
- return QVariant();
-
- if (role == Qt::DisplayRole || role == Qt::EditRole)
- return lst.at(index.row());
-
- return QVariant();
-}
-
-/*!
- Returns the flags for the item with the given \a index.
-
- Valid items are enabled, selectable, editable, drag enabled and drop enabled.
-
- \sa QAbstractItemModel::flags()
-*/
-
-Qt::ItemFlags QStringListModel::flags(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QAbstractItemModel::flags(index) | Qt::ItemIsDropEnabled;
-
- return QAbstractItemModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
-}
-
-/*!
- Sets the data for the specified \a role in the item with the given
- \a index in the model, to the provided \a value.
-
- The dataChanged() signal is emitted if the item is changed.
-
- \sa Qt::ItemDataRole, data()
-*/
-
-bool QStringListModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (index.row() >= 0 && index.row() < lst.size()
- && (role == Qt::EditRole || role == Qt::DisplayRole)) {
- lst.replace(index.row(), value.toString());
- emit dataChanged(index, index);
- return true;
- }
- return false;
-}
-
-/*!
- Inserts \a count rows into the model, beginning at the given \a row.
-
- The \a parent index of the rows is optional and is only used for
- consistency with QAbstractItemModel. By default, a null index is
- specified, indicating that the rows are inserted in the top level of
- the model.
-
- \sa QAbstractItemModel::insertRows()
-*/
-
-bool QStringListModel::insertRows(int row, int count, const QModelIndex &parent)
-{
- if (count < 1 || row < 0 || row > rowCount(parent))
- return false;
-
- beginInsertRows(QModelIndex(), row, row + count - 1);
-
- for (int r = 0; r < count; ++r)
- lst.insert(row, QString());
-
- endInsertRows();
-
- return true;
-}
-
-/*!
- Removes \a count rows from the model, beginning at the given \a row.
-
- The \a parent index of the rows is optional and is only used for
- consistency with QAbstractItemModel. By default, a null index is
- specified, indicating that the rows are removed in the top level of
- the model.
-
- \sa QAbstractItemModel::removeRows()
-*/
-
-bool QStringListModel::removeRows(int row, int count, const QModelIndex &parent)
-{
- if (count <= 0 || row < 0 || (row + count) > rowCount(parent))
- return false;
-
- beginRemoveRows(QModelIndex(), row, row + count - 1);
-
- for (int r = 0; r < count; ++r)
- lst.removeAt(row);
-
- endRemoveRows();
-
- return true;
-}
-
-static bool ascendingLessThan(const QPair<QString, int> &s1, const QPair<QString, int> &s2)
-{
- return s1.first < s2.first;
-}
-
-static bool decendingLessThan(const QPair<QString, int> &s1, const QPair<QString, int> &s2)
-{
- return s1.first > s2.first;
-}
-
-/*!
- \reimp
-*/
-void QStringListModel::sort(int, Qt::SortOrder order)
-{
- emit layoutAboutToBeChanged();
-
- QList<QPair<QString, int> > list;
- for (int i = 0; i < lst.count(); ++i)
- list.append(QPair<QString, int>(lst.at(i), i));
-
- if (order == Qt::AscendingOrder)
- qSort(list.begin(), list.end(), ascendingLessThan);
- else
- qSort(list.begin(), list.end(), decendingLessThan);
-
- lst.clear();
- QVector<int> forwarding(list.count());
- for (int i = 0; i < list.count(); ++i) {
- lst.append(list.at(i).first);
- forwarding[list.at(i).second] = i;
- }
-
- QModelIndexList oldList = persistentIndexList();
- QModelIndexList newList;
- for (int i = 0; i < oldList.count(); ++i)
- newList.append(index(forwarding.at(oldList.at(i).row()), 0));
- changePersistentIndexList(oldList, newList);
-
- emit layoutChanged();
-}
-
-/*!
- Returns the string list used by the model to store data.
-*/
-QStringList QStringListModel::stringList() const
-{
- return lst;
-}
-
-/*!
- Sets the model's internal string list to \a strings. The model will
- notify any attached views that its underlying data has changed.
-
- \sa dataChanged()
-*/
-void QStringListModel::setStringList(const QStringList &strings)
-{
- emit beginResetModel();
- lst = strings;
- emit endResetModel();
-}
-
-/*!
- \reimp
-*/
-Qt::DropActions QStringListModel::supportedDropActions() const
-{
- return QAbstractItemModel::supportedDropActions() | Qt::MoveAction;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STRINGLISTMODEL
diff --git a/src/gui/itemviews/qstringlistmodel.h b/src/gui/itemviews/qstringlistmodel.h
deleted file mode 100644
index b9b284cfc5..0000000000
--- a/src/gui/itemviews/qstringlistmodel.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTRINGLISTMODEL_H
-#define QSTRINGLISTMODEL_H
-
-#include <QtCore/qstringlist.h>
-#include <QtGui/qabstractitemview.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_STRINGLISTMODEL
-
-class Q_GUI_EXPORT QStringListModel : public QAbstractListModel
-{
- Q_OBJECT
-public:
- explicit QStringListModel(QObject *parent = 0);
- QStringListModel(const QStringList &strings, QObject *parent = 0);
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
-
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
-
- void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
-
- QStringList stringList() const;
- void setStringList(const QStringList &strings);
-
- Qt::DropActions supportedDropActions() const;
-
-private:
- Q_DISABLE_COPY(QStringListModel)
- QStringList lst;
-};
-
-#endif // QT_NO_STRINGLISTMODEL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTRINGLISTMODEL_H
diff --git a/src/gui/itemviews/qstyleditemdelegate.cpp b/src/gui/itemviews/qstyleditemdelegate.cpp
deleted file mode 100644
index 4989c05c69..0000000000
--- a/src/gui/itemviews/qstyleditemdelegate.cpp
+++ /dev/null
@@ -1,765 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstyleditemdelegate.h"
-
-#ifndef QT_NO_ITEMVIEWS
-#include <qabstractitemmodel.h>
-#include <qapplication.h>
-#include <qbrush.h>
-#include <qlineedit.h>
-#include <qtextedit.h>
-#include <qplaintextedit.h>
-#include <qpainter.h>
-#include <qpalette.h>
-#include <qpoint.h>
-#include <qrect.h>
-#include <qsize.h>
-#include <qstyle.h>
-#include <qdatetime.h>
-#include <qstyleoption.h>
-#include <qevent.h>
-#include <qpixmap.h>
-#include <qbitmap.h>
-#include <qpixmapcache.h>
-#include <qitemeditorfactory.h>
-#include <private/qitemeditorfactory_p.h>
-#include <qmetaobject.h>
-#include <qtextlayout.h>
-#include <private/qobject_p.h>
-#include <private/qdnd_p.h>
-#include <private/qtextengine_p.h>
-#include <private/qlayoutengine_p.h>
-#include <qdebug.h>
-#include <qlocale.h>
-#include <qdialog.h>
-#include <qtableview.h>
-
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-class QStyledItemDelegatePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QStyledItemDelegate)
-
-public:
- QStyledItemDelegatePrivate() : factory(0) { }
-
- static const QWidget *widget(const QStyleOptionViewItem &option)
- {
- if (const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3 *>(&option))
- return v3->widget;
- return 0;
- }
-
- const QItemEditorFactory *editorFactory() const
- {
- return factory ? factory : QItemEditorFactory::defaultFactory();
- }
-
- void _q_commitDataAndCloseEditor(QWidget *editor)
- {
- Q_Q(QStyledItemDelegate);
- emit q->commitData(editor);
- emit q->closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
- }
- QItemEditorFactory *factory;
-};
-
-/*!
- \class QStyledItemDelegate
-
- \brief The QStyledItemDelegate class provides display and editing facilities for
- data items from a model.
-
- \ingroup model-view
-
- \since 4.4
-
- When displaying data from models in Qt item views, e.g., a
- QTableView, the individual items are drawn by a delegate. Also,
- when an item is edited, it provides an editor widget, which is
- placed on top of the item view while editing takes place.
- QStyledItemDelegate is the default delegate for all Qt item
- views, and is installed upon them when they are created.
-
- The QStyledItemDelegate class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view
- framework}. The delegate allows the display and editing of items
- to be developed independently from the model and view.
-
- The data of items in models are assigned an
- \l{Qt::}{ItemDataRole}; each item can store a QVariant for each
- role. QStyledItemDelegate implements display and editing for the
- most common datatypes expected by users, including booleans,
- integers, and strings.
-
- The data will be drawn differently depending on which role they
- have in the model. The following table describes the roles and the
- data types the delegate can handle for each of them. It is often
- sufficient to ensure that the model returns appropriate data for
- each of the roles to determine the appearance of items in views.
-
- \table
- \header \o Role \o Accepted Types
- \omit
- \row \o \l Qt::AccessibleDescriptionRole \o QString
- \row \o \l Qt::AccessibleTextRole \o QString
- \endomit
- \row \o \l Qt::BackgroundRole \o QBrush
- \row \o \l Qt::BackgroundColorRole \o QColor (obsolete; use Qt::BackgroundRole instead)
- \row \o \l Qt::CheckStateRole \o Qt::CheckState
- \row \o \l Qt::DecorationRole \o QIcon, QPixmap, QImage and QColor
- \row \o \l Qt::DisplayRole \o QString and types with a string representation
- \row \o \l Qt::EditRole \o See QItemEditorFactory for details
- \row \o \l Qt::FontRole \o QFont
- \row \o \l Qt::SizeHintRole \o QSize
- \omit
- \row \o \l Qt::StatusTipRole \o
- \endomit
- \row \o \l Qt::TextAlignmentRole \o Qt::Alignment
- \row \o \l Qt::ForegroundRole \o QBrush
- \row \o \l Qt::TextColorRole \o QColor (obsolete; use Qt::ForegroundRole instead)
- \omit
- \row \o \l Qt::ToolTipRole
- \row \o \l Qt::WhatsThisRole
- \endomit
- \endtable
-
- Editors are created with a QItemEditorFactory; a default static
- instance provided by QItemEditorFactory is installed on all item
- delegates. You can set a custom factory using
- setItemEditorFactory() or set a new default factory with
- QItemEditorFactory::setDefaultFactory(). It is the data stored in
- the item model with the \l{Qt::}{EditRole} that is edited. See the
- QItemEditorFactory class for a more high-level introduction to
- item editor factories. The \l{Color Editor Factory Example}{Color
- Editor Factory} example shows how to create custom editors with a
- factory.
-
- \section1 Subclassing QStyledItemDelegate
-
- If the delegate does not support painting of the data types you
- need or you want to customize the drawing of items, you need to
- subclass QStyledItemDelegate, and reimplement paint() and possibly
- sizeHint(). The paint() function is called individually for each
- item, and with sizeHint(), you can specify the hint for each
- of them.
-
- When reimplementing paint(), one would typically handle the
- datatypes one would like to draw and use the superclass
- implementation for other types.
-
- The painting of check box indicators are performed by the current
- style. The style also specifies the size and the bounding
- rectangles in which to draw the data for the different data roles.
- The bounding rectangle of the item itself is also calculated by
- the style. When drawing already supported datatypes, it is
- therefore a good idea to ask the style for these bounding
- rectangles. The QStyle class description describes this in
- more detail.
-
- If you wish to change any of the bounding rectangles calculated by
- the style or the painting of check box indicators, you can
- subclass QStyle. Note, however, that the size of the items can
- also be affected by reimplementing sizeHint().
-
- It is possible for a custom delegate to provide editors
- without the use of an editor item factory. In this case, the
- following virtual functions must be reimplemented:
-
- \list
- \o createEditor() returns the widget used to change data from the model
- and can be reimplemented to customize editing behavior.
- \o setEditorData() provides the widget with data to manipulate.
- \o updateEditorGeometry() ensures that the editor is displayed correctly
- with respect to the item view.
- \o setModelData() returns updated data to the model.
- \endlist
-
- The \l{Star Delegate Example}{Star Delegate} example creates
- editors by reimplementing these methods.
-
- \section1 QStyledItemDelegate vs. QItemDelegate
-
- Since Qt 4.4, there are two delegate classes: QItemDelegate and
- QStyledItemDelegate. However, the default delegate is QStyledItemDelegate.
- These two classes are independent alternatives to painting and providing
- editors for items in views. The difference between them is that
- QStyledItemDelegate uses the current style to paint its items. We therefore
- recommend using QStyledItemDelegate as the base class when implementing
- custom delegates or when working with Qt style sheets. The code required
- for either class should be equal unless the custom delegate needs to use
- the style for drawing.
-
- If you wish to customize the painting of item views, you should
- implement a custom style. Please see the QStyle class
- documentation for details.
-
- \sa {Delegate Classes}, QItemDelegate, QAbstractItemDelegate, QStyle,
- {Spin Box Delegate Example}, {Star Delegate Example}, {Color
- Editor Factory Example}
-*/
-
-
-/*!
- Constructs an item delegate with the given \a parent.
-*/
-QStyledItemDelegate::QStyledItemDelegate(QObject *parent)
- : QAbstractItemDelegate(*new QStyledItemDelegatePrivate(), parent)
-{
-}
-
-/*!
- Destroys the item delegate.
-*/
-QStyledItemDelegate::~QStyledItemDelegate()
-{
-}
-
-/*!
- This function returns the string that the delegate will use to display the
- Qt::DisplayRole of the model in \a locale. \a value is the value of the Qt::DisplayRole
- provided by the model.
-
- The default implementation uses the QLocale::toString to convert \a value into
- a QString.
-
- This function is not called for empty model indices, i.e., indices for which
- the model returns an invalid QVariant.
-
- \sa QAbstractItemModel::data()
-*/
-QString QStyledItemDelegate::displayText(const QVariant &value, const QLocale& locale) const
-{
- QString text;
- switch (value.userType()) {
- case QMetaType::Float:
- case QVariant::Double:
- text = locale.toString(value.toReal());
- break;
- case QVariant::Int:
- case QVariant::LongLong:
- text = locale.toString(value.toLongLong());
- break;
- case QVariant::UInt:
- case QVariant::ULongLong:
- text = locale.toString(value.toULongLong());
- break;
- case QVariant::Date:
- text = locale.toString(value.toDate(), QLocale::ShortFormat);
- break;
- case QVariant::Time:
- text = locale.toString(value.toTime(), QLocale::ShortFormat);
- break;
- case QVariant::DateTime:
- text = locale.toString(value.toDateTime().date(), QLocale::ShortFormat);
- text += QLatin1Char(' ');
- text += locale.toString(value.toDateTime().time(), QLocale::ShortFormat);
- break;
- default:
- // convert new lines into line separators
- text = value.toString();
- for (int i = 0; i < text.count(); ++i) {
- if (text.at(i) == QLatin1Char('\n'))
- text[i] = QChar::LineSeparator;
- }
- break;
- }
- return text;
-}
-
-/*!
- Initialize \a option with the values using the index \a index. This method
- is useful for subclasses when they need a QStyleOptionViewItem, but don't want
- to fill in all the information themselves. This function will check the version
- of the QStyleOptionViewItem and fill in the additional values for a
- QStyleOptionViewItemV2, QStyleOptionViewItemV3 and QStyleOptionViewItemV4.
-
- \sa QStyleOption::initFrom()
-*/
-void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
- const QModelIndex &index) const
-{
- QVariant value = index.data(Qt::FontRole);
- if (value.isValid() && !value.isNull()) {
- option->font = qvariant_cast<QFont>(value).resolve(option->font);
- option->fontMetrics = QFontMetrics(option->font);
- }
-
- value = index.data(Qt::TextAlignmentRole);
- if (value.isValid() && !value.isNull())
- option->displayAlignment = Qt::Alignment(value.toInt());
-
- value = index.data(Qt::ForegroundRole);
- if (value.canConvert<QBrush>())
- option->palette.setBrush(QPalette::Text, qvariant_cast<QBrush>(value));
-
- if (QStyleOptionViewItemV4 *v4 = qstyleoption_cast<QStyleOptionViewItemV4 *>(option)) {
- v4->index = index;
- QVariant value = index.data(Qt::CheckStateRole);
- if (value.isValid() && !value.isNull()) {
- v4->features |= QStyleOptionViewItemV2::HasCheckIndicator;
- v4->checkState = static_cast<Qt::CheckState>(value.toInt());
- }
-
- value = index.data(Qt::DecorationRole);
- if (value.isValid() && !value.isNull()) {
- v4->features |= QStyleOptionViewItemV2::HasDecoration;
- switch (value.type()) {
- case QVariant::Icon: {
- v4->icon = qvariant_cast<QIcon>(value);
- QIcon::Mode mode;
- if (!(option->state & QStyle::State_Enabled))
- mode = QIcon::Disabled;
- else if (option->state & QStyle::State_Selected)
- mode = QIcon::Selected;
- else
- mode = QIcon::Normal;
- QIcon::State state = option->state & QStyle::State_Open ? QIcon::On : QIcon::Off;
- v4->decorationSize = v4->icon.actualSize(option->decorationSize, mode, state);
- break;
- }
- case QVariant::Color: {
- QPixmap pixmap(option->decorationSize);
- pixmap.fill(qvariant_cast<QColor>(value));
- v4->icon = QIcon(pixmap);
- break;
- }
- case QVariant::Image: {
- QImage image = qvariant_cast<QImage>(value);
- v4->icon = QIcon(QPixmap::fromImage(image));
- v4->decorationSize = image.size();
- break;
- }
- case QVariant::Pixmap: {
- QPixmap pixmap = qvariant_cast<QPixmap>(value);
- v4->icon = QIcon(pixmap);
- v4->decorationSize = pixmap.size();
- break;
- }
- default:
- break;
- }
- }
-
- value = index.data(Qt::DisplayRole);
- if (value.isValid() && !value.isNull()) {
- v4->features |= QStyleOptionViewItemV2::HasDisplay;
- v4->text = displayText(value, v4->locale);
- }
-
- v4->backgroundBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole));
- }
-}
-
-/*!
- Renders the delegate using the given \a painter and style \a option for
- the item specified by \a index.
-
- This function paints the item using the view's QStyle.
-
- When reimplementing paint in a subclass. Use the initStyleOption()
- to set up the \a option in the same way as the
- QStyledItemDelegate; the option will always be an instance of
- QStyleOptionViewItemV4. Please see its class description for
- information on its contents.
-
- Whenever possible, use the \a option while painting.
- Especially its \l{QStyleOption::}{rect} variable to decide
- where to draw and its \l{QStyleOption::}{state} to determine
- if it is enabled or selected.
-
- After painting, you should ensure that the painter is returned to
- its the state it was supplied in when this function was called.
- For example, it may be useful to call QPainter::save() before
- painting and QPainter::restore() afterwards.
-
- \sa QItemDelegate::paint(), QStyle::drawControl(), QStyle::CE_ItemViewItem
-*/
-void QStyledItemDelegate::paint(QPainter *painter,
- const QStyleOptionViewItem &option, const QModelIndex &index) const
-{
- Q_ASSERT(index.isValid());
-
- QStyleOptionViewItemV4 opt = option;
- initStyleOption(&opt, index);
-
- const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
- style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
-}
-
-/*!
- Returns the size needed by the delegate to display the item
- specified by \a index, taking into account the style information
- provided by \a option.
-
- This function uses the view's QStyle to determine the size of the
- item.
-
- \sa QStyle::sizeFromContents(), QStyle::CT_ItemViewItem
-*/
-QSize QStyledItemDelegate::sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- QVariant value = index.data(Qt::SizeHintRole);
- if (value.isValid())
- return qvariant_cast<QSize>(value);
-
- QStyleOptionViewItemV4 opt = option;
- initStyleOption(&opt, index);
- const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
- return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), widget);
-}
-
-/*!
- Returns the widget used to edit the item specified by \a index
- for editing. The \a parent widget and style \a option are used to
- control how the editor widget appears.
-
- \sa QAbstractItemDelegate::createEditor()
-*/
-QWidget *QStyledItemDelegate::createEditor(QWidget *parent,
- const QStyleOptionViewItem &,
- const QModelIndex &index) const
-{
- Q_D(const QStyledItemDelegate);
- if (!index.isValid())
- return 0;
- QVariant::Type t = static_cast<QVariant::Type>(index.data(Qt::EditRole).userType());
- return d->editorFactory()->createEditor(t, parent);
-}
-
-/*!
- Sets the data to be displayed and edited by the \a editor from the
- data model item specified by the model \a index.
-
- The default implementation stores the data in the \a editor
- widget's \l {Qt's Property System} {user property}.
-
- \sa QMetaProperty::isUser()
-*/
-void QStyledItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
-{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
- Q_D(const QStyledItemDelegate);
- QVariant v = index.data(Qt::EditRole);
- QByteArray n = editor->metaObject()->userProperty().name();
-
- // ### Qt 5: remove
- // A work-around for missing "USER true" in qdatetimeedit.h for
- // QTimeEdit's time property and QDateEdit's date property.
- // It only triggers if the default user property "dateTime" is
- // reported for QTimeEdit and QDateEdit.
- if (n == "dateTime") {
- if (editor->inherits("QTimeEdit"))
- n = "time";
- else if (editor->inherits("QDateEdit"))
- n = "date";
- }
-
- // ### Qt 5: give QComboBox a USER property
- if (n.isEmpty() && editor->inherits("QComboBox"))
- n = d->editorFactory()->valuePropertyName(static_cast<QVariant::Type>(v.userType()));
- if (!n.isEmpty()) {
- if (!v.isValid())
- v = QVariant(editor->property(n).userType(), (const void *)0);
- editor->setProperty(n, v);
- }
-#endif
-}
-
-/*!
- Gets data from the \a editor widget and stores it in the specified
- \a model at the item \a index.
-
- The default implementation gets the value to be stored in the data
- model from the \a editor widget's \l {Qt's Property System} {user
- property}.
-
- \sa QMetaProperty::isUser()
-*/
-void QStyledItemDelegate::setModelData(QWidget *editor,
- QAbstractItemModel *model,
- const QModelIndex &index) const
-{
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(model);
- Q_UNUSED(editor);
- Q_UNUSED(index);
-#else
- Q_D(const QStyledItemDelegate);
- Q_ASSERT(model);
- Q_ASSERT(editor);
- QByteArray n = editor->metaObject()->userProperty().name();
- if (n.isEmpty())
- n = d->editorFactory()->valuePropertyName(
- static_cast<QVariant::Type>(model->data(index, Qt::EditRole).userType()));
- if (!n.isEmpty())
- model->setData(index, editor->property(n), Qt::EditRole);
-#endif
-}
-
-/*!
- Updates the \a editor for the item specified by \a index
- according to the style \a option given.
-*/
-void QStyledItemDelegate::updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- if (!editor)
- return;
- Q_ASSERT(index.isValid());
- const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
-
- QStyleOptionViewItemV4 opt = option;
- initStyleOption(&opt, index);
- // let the editor take up all available space
- //if the editor is not a QLineEdit
- //or it is in a QTableView
-#if !defined(QT_NO_TABLEVIEW) && !defined(QT_NO_LINEEDIT)
- if (qobject_cast<QExpandingLineEdit*>(editor) && !qobject_cast<const QTableView*>(widget))
- opt.showDecorationSelected = editor->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, 0, editor);
- else
-#endif
- opt.showDecorationSelected = true;
-
- QStyle *style = widget ? widget->style() : QApplication::style();
- QRect geom = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);
- if ( editor->layoutDirection() == Qt::RightToLeft) {
- const int delta = qSmartMinSize(editor).width() - geom.width();
- if (delta > 0) {
- //we need to widen the geometry
- geom.adjust(-delta, 0, 0, 0);
- }
- }
-
- editor->setGeometry(geom);
-}
-
-/*!
- Returns the editor factory used by the item delegate.
- If no editor factory is set, the function will return null.
-
- \sa setItemEditorFactory()
-*/
-QItemEditorFactory *QStyledItemDelegate::itemEditorFactory() const
-{
- Q_D(const QStyledItemDelegate);
- return d->factory;
-}
-
-/*!
- Sets the editor factory to be used by the item delegate to be the \a factory
- specified. If no editor factory is set, the item delegate will use the
- default editor factory.
-
- \sa itemEditorFactory()
-*/
-void QStyledItemDelegate::setItemEditorFactory(QItemEditorFactory *factory)
-{
- Q_D(QStyledItemDelegate);
- d->factory = factory;
-}
-
-
-/*!
- \fn bool QStyledItemDelegate::eventFilter(QObject *editor, QEvent *event)
-
- Returns true if the given \a editor is a valid QWidget and the
- given \a event is handled; otherwise returns false. The following
- key press events are handled by default:
-
- \list
- \o \gui Tab
- \o \gui Backtab
- \o \gui Enter
- \o \gui Return
- \o \gui Esc
- \endlist
-
- In the case of \gui Tab, \gui Backtab, \gui Enter and \gui Return
- key press events, the \a editor's data is comitted to the model
- and the editor is closed. If the \a event is a \gui Tab key press
- the view will open an editor on the next item in the
- view. Likewise, if the \a event is a \gui Backtab key press the
- view will open an editor on the \e previous item in the view.
-
- If the event is a \gui Esc key press event, the \a editor is
- closed \e without committing its data.
-
- \sa commitData(), closeEditor()
-*/
-bool QStyledItemDelegate::eventFilter(QObject *object, QEvent *event)
-{
- QWidget *editor = qobject_cast<QWidget*>(object);
- if (!editor)
- return false;
- if (event->type() == QEvent::KeyPress) {
- switch (static_cast<QKeyEvent *>(event)->key()) {
- case Qt::Key_Tab:
- emit commitData(editor);
- emit closeEditor(editor, QAbstractItemDelegate::EditNextItem);
- return true;
- case Qt::Key_Backtab:
- emit commitData(editor);
- emit closeEditor(editor, QAbstractItemDelegate::EditPreviousItem);
- return true;
- case Qt::Key_Enter:
- case Qt::Key_Return:
-#ifndef QT_NO_TEXTEDIT
- if (qobject_cast<QTextEdit *>(editor) || qobject_cast<QPlainTextEdit *>(editor))
- return false; // don't filter enter key events for QTextEdit
- // We want the editor to be able to process the key press
- // before committing the data (e.g. so it can do
- // validation/fixup of the input).
-#endif // QT_NO_TEXTEDIT
-#ifndef QT_NO_LINEEDIT
- if (QLineEdit *e = qobject_cast<QLineEdit*>(editor))
- if (!e->hasAcceptableInput())
- return false;
-#endif // QT_NO_LINEEDIT
- QMetaObject::invokeMethod(this, "_q_commitDataAndCloseEditor",
- Qt::QueuedConnection, Q_ARG(QWidget*, editor));
- return false;
- case Qt::Key_Escape:
- // don't commit data
- emit closeEditor(editor, QAbstractItemDelegate::RevertModelCache);
- break;
- default:
- return false;
- }
- if (editor->parentWidget())
- editor->parentWidget()->setFocus();
- return true;
- } else if (event->type() == QEvent::FocusOut || (event->type() == QEvent::Hide && editor->isWindow())) {
- //the Hide event will take care of he editors that are in fact complete dialogs
- if (!editor->isActiveWindow() || (QApplication::focusWidget() != editor)) {
- QWidget *w = QApplication::focusWidget();
- while (w) { // don't worry about focus changes internally in the editor
- if (w == editor)
- return false;
- w = w->parentWidget();
- }
-#ifndef QT_NO_DRAGANDDROP
- // The window may lose focus during an drag operation.
- // i.e when dragging involves the taskbar on Windows.
- if (QDragManager::self() && QDragManager::self()->object != 0)
- return false;
-#endif
-
- emit commitData(editor);
- emit closeEditor(editor, NoHint);
- }
- } else if (event->type() == QEvent::ShortcutOverride) {
- if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
- event->accept();
- return true;
- }
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-bool QStyledItemDelegate::editorEvent(QEvent *event,
- QAbstractItemModel *model,
- const QStyleOptionViewItem &option,
- const QModelIndex &index)
-{
- Q_ASSERT(event);
- Q_ASSERT(model);
-
- // make sure that the item is checkable
- Qt::ItemFlags flags = model->flags(index);
- if (!(flags & Qt::ItemIsUserCheckable) || !(option.state & QStyle::State_Enabled)
- || !(flags & Qt::ItemIsEnabled))
- return false;
-
- // make sure that we have a check state
- QVariant value = index.data(Qt::CheckStateRole);
- if (!value.isValid())
- return false;
-
- const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
- QStyle *style = widget ? widget->style() : QApplication::style();
-
- // make sure that we have the right event type
- if ((event->type() == QEvent::MouseButtonRelease)
- || (event->type() == QEvent::MouseButtonDblClick)
- || (event->type() == QEvent::MouseButtonPress)) {
- QStyleOptionViewItemV4 viewOpt(option);
- initStyleOption(&viewOpt, index);
- QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, widget);
- QMouseEvent *me = static_cast<QMouseEvent*>(event);
- if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
- return false;
-
- if ((event->type() == QEvent::MouseButtonPress)
- || (event->type() == QEvent::MouseButtonDblClick))
- return true;
-
- } else if (event->type() == QEvent::KeyPress) {
- if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space
- && static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
- return false;
- } else {
- return false;
- }
-
- Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
- ? Qt::Unchecked : Qt::Checked);
- return model->setData(index, state, Qt::CheckStateRole);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qstyleditemdelegate.cpp"
-
-#endif // QT_NO_ITEMVIEWS
diff --git a/src/gui/itemviews/qstyleditemdelegate.h b/src/gui/itemviews/qstyleditemdelegate.h
deleted file mode 100644
index 1c8299b07c..0000000000
--- a/src/gui/itemviews/qstyleditemdelegate.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLEDITEMDELEGATE_H
-#define QSTYLEDITEMDELEGATE_H
-
-#include <QtGui/qabstractitemdelegate.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qpixmap.h>
-#include <QtCore/qvariant.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ITEMVIEWS
-
-class QStyledItemDelegatePrivate;
-class QItemEditorFactory;
-
-class Q_GUI_EXPORT QStyledItemDelegate : public QAbstractItemDelegate
-{
- Q_OBJECT
-
-public:
- explicit QStyledItemDelegate(QObject *parent = 0);
- ~QStyledItemDelegate();
-
- // painting
- void paint(QPainter *painter,
- const QStyleOptionViewItem &option, const QModelIndex &index) const;
- QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- // editing
- QWidget *createEditor(QWidget *parent,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- void setEditorData(QWidget *editor, const QModelIndex &index) const;
- void setModelData(QWidget *editor,
- QAbstractItemModel *model,
- const QModelIndex &index) const;
-
- void updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- // editor factory
- QItemEditorFactory *itemEditorFactory() const;
- void setItemEditorFactory(QItemEditorFactory *factory);
-
- virtual QString displayText(const QVariant &value, const QLocale &locale) const;
-
-protected:
- virtual void initStyleOption(QStyleOptionViewItem *option,
- const QModelIndex &index) const;
-
- bool eventFilter(QObject *object, QEvent *event);
- bool editorEvent(QEvent *event, QAbstractItemModel *model,
- const QStyleOptionViewItem &option, const QModelIndex &index);
-
-private:
- Q_DECLARE_PRIVATE(QStyledItemDelegate)
- Q_DISABLE_COPY(QStyledItemDelegate)
-
- Q_PRIVATE_SLOT(d_func(), void _q_commitDataAndCloseEditor(QWidget*))
-};
-
-#endif // QT_NO_ITEMVIEWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTYLEDITEMDELEGATE_H
diff --git a/src/gui/itemviews/qtableview.cpp b/src/gui/itemviews/qtableview.cpp
deleted file mode 100644
index e494ee5564..0000000000
--- a/src/gui/itemviews/qtableview.cpp
+++ /dev/null
@@ -1,3198 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtableview.h"
-
-#ifndef QT_NO_TABLEVIEW
-#include <qheaderview.h>
-#include <qitemdelegate.h>
-#include <qapplication.h>
-#include <qpainter.h>
-#include <qstyle.h>
-#include <qsize.h>
-#include <qevent.h>
-#include <qbitarray.h>
-#include <qscrollbar.h>
-#include <qabstractbutton.h>
-#include <private/qtableview_p.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qaccessible.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/** \internal
- Add a span to the collection. the collection takes the ownership.
- */
-void QSpanCollection::addSpan(QSpanCollection::Span *span)
-{
- spans.append(span);
- Index::iterator it_y = index.lowerBound(-span->top());
- if (it_y == index.end() || it_y.key() != -span->top()) {
- //there is no spans that starts with the row in the index, so create a sublist for it.
- SubIndex sub_index;
- if (it_y != index.end()) {
- //the previouslist is the list of spans that sarts _before_ the row of the span.
- // and which may intersect this row.
- const SubIndex previousList = it_y.value();
- foreach(Span *s, previousList) {
- //If a subspans intersect the row, we need to split it into subspans
- if(s->bottom() >= span->top())
- sub_index.insert(-s->left(), s);
- }
- }
- it_y = index.insert(-span->top(), sub_index);
- //we will insert span to *it_y in the later loop
- }
-
- //insert the span as supspan in all the lists that intesects the span
- while(-it_y.key() <= span->bottom()) {
- (*it_y).insert(-span->left(), span);
- if(it_y == index.begin())
- break;
- --it_y;
- }
-}
-
-
-/** \internal
-* Has to be called after the height and width of a span is changed.
-*
-* old_height is the height before the change
-*
-* if the size of the span is now 0x0 the span will be deleted.
-*/
-void QSpanCollection::updateSpan(QSpanCollection::Span *span, int old_height)
-{
- if (old_height < span->height()) {
- //add the span as subspan in all the lists that intersect the new covered columns
- Index::iterator it_y = index.lowerBound(-(span->top() + old_height - 1));
- Q_ASSERT(it_y != index.end()); //it_y must exist since the span is in the list
- while (-it_y.key() <= span->bottom()) {
- (*it_y).insert(-span->left(), span);
- if(it_y == index.begin())
- break;
- --it_y;
- }
- } else if (old_height > span->height()) {
- //remove the span from all the subspans lists that intersect the columns not covered anymore
- Index::iterator it_y = index.lowerBound(-qMax(span->bottom(), span->top())); //qMax useful if height is 0
- Q_ASSERT(it_y != index.end()); //it_y must exist since the span is in the list
- while (-it_y.key() <= span->top() + old_height -1) {
- if (-it_y.key() > span->bottom()) {
- int removed = (*it_y).remove(-span->left());
- Q_ASSERT(removed == 1); Q_UNUSED(removed);
- if (it_y->isEmpty()) {
- it_y = index.erase(it_y);
- }
- }
- if(it_y == index.begin())
- break;
- --it_y;
- }
- }
-
- if (span->width() == 0 && span->height() == 0) {
- spans.removeOne(span);
- delete span;
- }
-}
-
-/** \internal
- * \return a spans that spans over cell x,y (column,row) or 0 if there is none.
- */
-QSpanCollection::Span *QSpanCollection::spanAt(int x, int y) const
-{
- Index::const_iterator it_y = index.lowerBound(-y);
- if (it_y == index.end())
- return 0;
- SubIndex::const_iterator it_x = (*it_y).lowerBound(-x);
- if (it_x == (*it_y).end())
- return 0;
- Span *span = *it_x;
- if (span->right() >= x && span->bottom() >= y)
- return span;
- return 0;
-}
-
-
-/** \internal
-* remove and deletes all spans inside the collection
-*/
-void QSpanCollection::clear()
-{
- qDeleteAll(spans);
- index.clear();
- spans.clear();
-}
-
-/** \internal
- * return a list to all the spans that spans over cells in the given rectangle
- */
-QList<QSpanCollection::Span *> QSpanCollection::spansInRect(int x, int y, int w, int h) const
-{
- QSet<Span *> list;
- Index::const_iterator it_y = index.lowerBound(-y);
- if(it_y == index.end())
- --it_y;
- while(-it_y.key() <= y + h) {
- SubIndex::const_iterator it_x = (*it_y).lowerBound(-x);
- if (it_x == (*it_y).end())
- --it_x;
- while(-it_x.key() <= x + w) {
- Span *s = *it_x;
- if (s->bottom() >= y && s->right() >= x)
- list << s;
- if (it_x == (*it_y).begin())
- break;
- --it_x;
- }
- if(it_y == index.begin())
- break;
- --it_y;
- }
- return list.toList();
-}
-
-#undef DEBUG_SPAN_UPDATE
-
-#ifdef DEBUG_SPAN_UPDATE
-QDebug operator<<(QDebug str, const QSpanCollection::Span &span)
-{
- str << "(" << span.top() << "," << span.left() << "," << span.bottom() << "," << span.right() << ")";
- return str;
-}
-#endif
-
-/** \internal
-* Updates the span collection after row insertion.
-*/
-void QSpanCollection::updateInsertedRows(int start, int end)
-{
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << Q_FUNC_INFO;
- qDebug() << start << end;
- qDebug() << index;
-#endif
- if (spans.isEmpty())
- return;
-
- int delta = end - start + 1;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("Before");
-#endif
- for (SpanList::iterator it = spans.begin(); it != spans.end(); ++it) {
- Span *span = *it;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << span << *span;
-#endif
- if (span->m_bottom < start)
- continue;
- if (span->m_top >= start)
- span->m_top += delta;
- span->m_bottom += delta;
- }
-
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
-#endif
-
- for (Index::iterator it_y = index.begin(); it_y != index.end(); ) {
- int y = -it_y.key();
- if (y < start) {
- ++it_y;
- continue;
- }
-
- index.insert(-y - delta, it_y.value());
- it_y = index.erase(it_y);
- }
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << index;
-#endif
-}
-
-/** \internal
-* Updates the span collection after column insertion.
-*/
-void QSpanCollection::updateInsertedColumns(int start, int end)
-{
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << Q_FUNC_INFO;
- qDebug() << start << end;
- qDebug() << index;
-#endif
- if (spans.isEmpty())
- return;
-
- int delta = end - start + 1;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("Before");
-#endif
- for (SpanList::iterator it = spans.begin(); it != spans.end(); ++it) {
- Span *span = *it;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << span << *span;
-#endif
- if (span->m_right < start)
- continue;
- if (span->m_left >= start)
- span->m_left += delta;
- span->m_right += delta;
- }
-
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
-#endif
-
- for (Index::iterator it_y = index.begin(); it_y != index.end(); ++it_y) {
- SubIndex &subindex = it_y.value();
- for (SubIndex::iterator it = subindex.begin(); it != subindex.end(); ) {
- int x = -it.key();
- if (x < start) {
- ++it;
- continue;
- }
- subindex.insert(-x - delta, it.value());
- it = subindex.erase(it);
- }
- }
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << index;
-#endif
-}
-
-/** \internal
-* Cleans a subindex from to be deleted spans. The update argument is used
-* to move the spans inside the subindex, in case their anchor changed.
-* \return true if no span in this subindex starts at y, and should thus be deleted.
-*/
-bool QSpanCollection::cleanSpanSubIndex(QSpanCollection::SubIndex &subindex, int y, bool update)
-{
- if (subindex.isEmpty())
- return true;
-
- bool should_be_deleted = true;
- SubIndex::iterator it = subindex.end();
- do {
- --it;
- int x = -it.key();
- Span *span = it.value();
- if (span->will_be_deleted) {
- it = subindex.erase(it);
- continue;
- }
- if (update && span->m_left != x) {
- subindex.insert(-span->m_left, span);
- it = subindex.erase(it);
- }
- if (should_be_deleted && span->m_top == y)
- should_be_deleted = false;
- } while (it != subindex.begin());
-
- return should_be_deleted;
-}
-
-/** \internal
-* Updates the span collection after row removal.
-*/
-void QSpanCollection::updateRemovedRows(int start, int end)
-{
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << Q_FUNC_INFO;
- qDebug() << start << end;
- qDebug() << index;
-#endif
- if (spans.isEmpty())
- return;
-
- SpanList spansToBeDeleted;
- int delta = end - start + 1;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("Before");
-#endif
- for (SpanList::iterator it = spans.begin(); it != spans.end(); ) {
- Span *span = *it;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << span << *span;
-#endif
- if (span->m_bottom < start) {
- ++it;
- continue;
- }
- if (span->m_top < start) {
- if (span->m_bottom <= end)
- span->m_bottom = start - 1;
- else
- span->m_bottom -= delta;
- } else {
- if (span->m_bottom > end) {
- if (span->m_top <= end)
- span->m_top = start;
- else
- span->m_top -= delta;
- span->m_bottom -= delta;
- } else {
- span->will_be_deleted = true;
- }
- }
- if (span->m_top == span->m_bottom && span->m_left == span->m_right)
- span->will_be_deleted = true;
- if (span->will_be_deleted) {
- spansToBeDeleted.append(span);
- it = spans.erase(it);
- } else {
- ++it;
- }
- }
-
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
-#endif
- if (spans.isEmpty()) {
- qDeleteAll(spansToBeDeleted);
- index.clear();
- return;
- }
-
- Index::iterator it_y = index.end();
- do {
- --it_y;
- int y = -it_y.key();
- SubIndex &subindex = it_y.value();
- if (y < start) {
- if (cleanSpanSubIndex(subindex, y))
- it_y = index.erase(it_y);
- } else if (y >= start && y <= end) {
- bool span_at_start = false;
- SubIndex spansToBeMoved;
- for (SubIndex::iterator it = subindex.begin(); it != subindex.end(); ++it) {
- Span *span = it.value();
- if (span->will_be_deleted)
- continue;
- if (!span_at_start && span->m_top == start)
- span_at_start = true;
- spansToBeMoved.insert(it.key(), span);
- }
-
- if (y == start && span_at_start)
- subindex.clear();
- else
- it_y = index.erase(it_y);
-
- if (span_at_start) {
- Index::iterator it_start;
- if (y == start)
- it_start = it_y;
- else {
- it_start = index.find(-start);
- if (it_start == index.end())
- it_start = index.insert(-start, SubIndex());
- }
- SubIndex &start_subindex = it_start.value();
- for (SubIndex::iterator it = spansToBeMoved.begin(); it != spansToBeMoved.end(); ++it)
- start_subindex.insert(it.key(), it.value());
- }
- } else {
- if (y == end + 1) {
- Index::iterator it_top = index.find(-y + delta);
- if (it_top == index.end())
- it_top = index.insert(-y + delta, SubIndex());
- for (SubIndex::iterator it = subindex.begin(); it != subindex.end(); ) {
- Span *span = it.value();
- if (!span->will_be_deleted)
- it_top.value().insert(it.key(), span);
- ++it;
- }
- } else {
- index.insert(-y + delta, subindex);
- }
- it_y = index.erase(it_y);
- }
- } while (it_y != index.begin());
-
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << index;
- qDebug("Deleted");
- foreach (QSpanCollection::Span *span, spansToBeDeleted)
- qDebug() << span << *span;
-#endif
- qDeleteAll(spansToBeDeleted);
-}
-
-/** \internal
-* Updates the span collection after column removal.
-*/
-void QSpanCollection::updateRemovedColumns(int start, int end)
-{
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << Q_FUNC_INFO;
- qDebug() << start << end;
- qDebug() << index;
-#endif
- if (spans.isEmpty())
- return;
-
- SpanList toBeDeleted;
- int delta = end - start + 1;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("Before");
-#endif
- for (SpanList::iterator it = spans.begin(); it != spans.end(); ) {
- Span *span = *it;
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << span << *span;
-#endif
- if (span->m_right < start) {
- ++it;
- continue;
- }
- if (span->m_left < start) {
- if (span->m_right <= end)
- span->m_right = start - 1;
- else
- span->m_right -= delta;
- } else {
- if (span->m_right > end) {
- if (span->m_left <= end)
- span->m_left = start;
- else
- span->m_left -= delta;
- span->m_right -= delta;
- } else {
- span->will_be_deleted = true;
- }
- }
- if (span->m_top == span->m_bottom && span->m_left == span->m_right)
- span->will_be_deleted = true;
- if (span->will_be_deleted) {
- toBeDeleted.append(span);
- it = spans.erase(it);
- } else {
- ++it;
- }
- }
-
-#ifdef DEBUG_SPAN_UPDATE
- qDebug("After");
- foreach (QSpanCollection::Span *span, spans)
- qDebug() << span << *span;
-#endif
- if (spans.isEmpty()) {
- qDeleteAll(toBeDeleted);
- index.clear();
- return;
- }
-
- for (Index::iterator it_y = index.begin(); it_y != index.end(); ) {
- int y = -it_y.key();
- if (cleanSpanSubIndex(it_y.value(), y, true))
- it_y = index.erase(it_y);
- else
- ++it_y;
- }
-
-#ifdef DEBUG_SPAN_UPDATE
- qDebug() << index;
- qDebug("Deleted");
- foreach (QSpanCollection::Span *span, toBeDeleted)
- qDebug() << span << *span;
-#endif
- qDeleteAll(toBeDeleted);
-}
-
-#ifdef QT_BUILD_INTERNAL
-/*!
- \internal
- Checks whether the span index structure is self-consistent, and consistent with the spans list.
-*/
-bool QSpanCollection::checkConsistency() const
-{
- for (Index::const_iterator it_y = index.begin(); it_y != index.end(); ++it_y) {
- int y = -it_y.key();
- const SubIndex &subIndex = it_y.value();
- for (SubIndex::const_iterator it = subIndex.begin(); it != subIndex.end(); ++it) {
- int x = -it.key();
- Span *span = it.value();
- if (!spans.contains(span) || span->left() != x
- || y < span->top() || y > span->bottom())
- return false;
- }
- }
-
- foreach (const Span *span, spans) {
- if (span->width() < 1 || span->height() < 1
- || (span->width() == 1 && span->height() == 1))
- return false;
- for (int y = span->top(); y <= span->bottom(); ++y) {
- Index::const_iterator it_y = index.find(-y);
- if (it_y == index.end()) {
- if (y == span->top())
- return false;
- else
- continue;
- }
- const SubIndex &subIndex = it_y.value();
- SubIndex::const_iterator it = subIndex.find(-span->left());
- if (it == subIndex.end() || it.value() != span)
- return false;
- }
- }
- return true;
-}
-#endif
-
-class QTableCornerButton : public QAbstractButton
-{
- Q_OBJECT
-public:
- QTableCornerButton(QWidget *parent) : QAbstractButton(parent) {}
- void paintEvent(QPaintEvent*) {
- QStyleOptionHeader opt;
- opt.init(this);
- QStyle::State state = QStyle::State_None;
- if (isEnabled())
- state |= QStyle::State_Enabled;
- if (isActiveWindow())
- state |= QStyle::State_Active;
- if (isDown())
- state |= QStyle::State_Sunken;
- opt.state = state;
- opt.rect = rect();
- opt.position = QStyleOptionHeader::OnlyOneSection;
- QPainter painter(this);
- style()->drawControl(QStyle::CE_Header, &opt, &painter, this);
- }
-};
-
-void QTableViewPrivate::init()
-{
- Q_Q(QTableView);
-
- q->setEditTriggers(editTriggers|QAbstractItemView::AnyKeyPressed);
-
- QHeaderView *vertical = new QHeaderView(Qt::Vertical, q);
- vertical->setClickable(true);
- vertical->setHighlightSections(true);
- q->setVerticalHeader(vertical);
-
- QHeaderView *horizontal = new QHeaderView(Qt::Horizontal, q);
- horizontal->setClickable(true);
- horizontal->setHighlightSections(true);
- q->setHorizontalHeader(horizontal);
-
- tabKeyNavigation = true;
-
- cornerWidget = new QTableCornerButton(q);
- cornerWidget->setFocusPolicy(Qt::NoFocus);
- QObject::connect(cornerWidget, SIGNAL(clicked()), q, SLOT(selectAll()));
-}
-
-/*!
- \internal
- Trims away indices that are hidden in the treeview due to hidden horizontal or vertical sections.
-*/
-void QTableViewPrivate::trimHiddenSelections(QItemSelectionRange *range) const
-{
- Q_ASSERT(range && range->isValid());
-
- int top = range->top();
- int left = range->left();
- int bottom = range->bottom();
- int right = range->right();
-
- while (bottom >= top && verticalHeader->isSectionHidden(bottom))
- --bottom;
- while (right >= left && horizontalHeader->isSectionHidden(right))
- --right;
-
- if (top > bottom || left > right) { // everything is hidden
- *range = QItemSelectionRange();
- return;
- }
-
- while (verticalHeader->isSectionHidden(top) && top <= bottom)
- ++top;
- while (horizontalHeader->isSectionHidden(left) && left <= right)
- ++left;
-
- if (top > bottom || left > right) { // everything is hidden
- *range = QItemSelectionRange();
- return;
- }
-
- QModelIndex bottomRight = model->index(bottom, right, range->parent());
- QModelIndex topLeft = model->index(top, left, range->parent());
- *range = QItemSelectionRange(topLeft, bottomRight);
-}
-
-/*!
- \internal
- Sets the span for the cell at (\a row, \a column).
-*/
-void QTableViewPrivate::setSpan(int row, int column, int rowSpan, int columnSpan)
-{
- if (row < 0 || column < 0 || rowSpan <= 0 || columnSpan <= 0) {
- qWarning() << "QTableView::setSpan: invalid span given: (" << row << ',' << column << ',' << rowSpan << ',' << columnSpan << ')';
- return;
- }
- QSpanCollection::Span *sp = spans.spanAt(column, row);
- if (sp) {
- if (sp->top() != row || sp->left() != column) {
- qWarning() << "QTableView::setSpan: span cannot overlap";
- return;
- }
- if (rowSpan == 1 && columnSpan == 1) {
- rowSpan = columnSpan = 0;
- }
- const int old_height = sp->height();
- sp->m_bottom = row + rowSpan - 1;
- sp->m_right = column + columnSpan - 1;
- spans.updateSpan(sp, old_height);
- return;
- } else if (rowSpan == 1 && columnSpan == 1) {
- qWarning() << "QTableView::setSpan: single cell span won't be added";
- return;
- }
- sp = new QSpanCollection::Span(row, column, rowSpan, columnSpan);
- spans.addSpan(sp);
-}
-
-/*!
- \internal
- Gets the span information for the cell at (\a row, \a column).
-*/
-QSpanCollection::Span QTableViewPrivate::span(int row, int column) const
-{
- QSpanCollection::Span *sp = spans.spanAt(column, row);
- if (sp)
- return *sp;
-
- return QSpanCollection::Span(row, column, 1, 1);
-}
-
-/*!
- \internal
- Returns the logical index of the last section that's part of the span.
-*/
-int QTableViewPrivate::sectionSpanEndLogical(const QHeaderView *header, int logical, int span) const
-{
- int visual = header->visualIndex(logical);
- for (int i = 1; i < span; ) {
- if (++visual >= header->count())
- break;
- logical = header->logicalIndex(visual);
- ++i;
- }
- return logical;
-}
-
-/*!
- \internal
- Returns the size of the span starting at logical index \a logical
- and spanning \a span sections.
-*/
-int QTableViewPrivate::sectionSpanSize(const QHeaderView *header, int logical, int span) const
-{
- int endLogical = sectionSpanEndLogical(header, logical, span);
- return header->sectionPosition(endLogical)
- - header->sectionPosition(logical)
- + header->sectionSize(endLogical);
-}
-
-/*!
- \internal
- Returns true if the section at logical index \a logical is part of the span
- starting at logical index \a spanLogical and spanning \a span sections;
- otherwise, returns false.
-*/
-bool QTableViewPrivate::spanContainsSection(const QHeaderView *header, int logical, int spanLogical, int span) const
-{
- if (logical == spanLogical)
- return true; // it's the start of the span
- int visual = header->visualIndex(spanLogical);
- for (int i = 1; i < span; ) {
- if (++visual >= header->count())
- break;
- spanLogical = header->logicalIndex(visual);
- if (logical == spanLogical)
- return true;
- ++i;
- }
- return false;
-}
-
-/*!
- \internal
- Returns the visual rect for the given \a span.
-*/
-QRect QTableViewPrivate::visualSpanRect(const QSpanCollection::Span &span) const
-{
- Q_Q(const QTableView);
- // vertical
- int row = span.top();
- int rowp = verticalHeader->sectionViewportPosition(row);
- int rowh = rowSpanHeight(row, span.height());
- // horizontal
- int column = span.left();
- int colw = columnSpanWidth(column, span.width());
- if (q->isRightToLeft())
- column = span.right();
- int colp = horizontalHeader->sectionViewportPosition(column);
-
- const int i = showGrid ? 1 : 0;
- if (q->isRightToLeft())
- return QRect(colp + i, rowp, colw - i, rowh - i);
- return QRect(colp, rowp, colw - i, rowh - i);
-}
-
-/*!
- \internal
- Draws the spanning cells within rect \a area, and clips them off as
- preparation for the main drawing loop.
- \a drawn is a QBitArray of visualRowCountxvisualCoulumnCount which say if particular cell has been drawn
-*/
-void QTableViewPrivate::drawAndClipSpans(const QRegion &area, QPainter *painter,
- const QStyleOptionViewItemV4 &option, QBitArray *drawn,
- int firstVisualRow, int lastVisualRow, int firstVisualColumn, int lastVisualColumn)
-{
- bool alternateBase = false;
- QRegion region = viewport->rect();
-
- QList<QSpanCollection::Span *> visibleSpans;
- bool sectionMoved = verticalHeader->sectionsMoved() || horizontalHeader->sectionsMoved();
-
- if (!sectionMoved) {
- visibleSpans = spans.spansInRect(logicalColumn(firstVisualColumn), logicalRow(firstVisualRow),
- lastVisualColumn - firstVisualColumn + 1, lastVisualRow - firstVisualRow + 1);
- } else {
- QSet<QSpanCollection::Span *> set;
- for(int x = firstVisualColumn; x <= lastVisualColumn; x++)
- for(int y = firstVisualRow; y <= lastVisualRow; y++)
- set.insert(spans.spanAt(x,y));
- set.remove(0);
- visibleSpans = set.toList();
- }
-
- foreach (QSpanCollection::Span *span, visibleSpans) {
- int row = span->top();
- int col = span->left();
- QModelIndex index = model->index(row, col, root);
- if (!index.isValid())
- continue;
- QRect rect = visualSpanRect(*span);
- rect.translate(scrollDelayOffset);
- if (!area.intersects(rect))
- continue;
- QStyleOptionViewItemV4 opt = option;
- opt.rect = rect;
- alternateBase = alternatingColors && (span->top() & 1);
- if (alternateBase)
- opt.features |= QStyleOptionViewItemV2::Alternate;
- else
- opt.features &= ~QStyleOptionViewItemV2::Alternate;
- drawCell(painter, opt, index);
- region -= rect;
- for (int r = span->top(); r <= span->bottom(); ++r) {
- const int vr = visualRow(r);
- if (vr < firstVisualRow || vr > lastVisualRow)
- continue;
- for (int c = span->left(); c <= span->right(); ++c) {
- const int vc = visualColumn(c);
- if (vc < firstVisualColumn || vc > lastVisualColumn)
- continue;
- drawn->setBit((vr - firstVisualRow) * (lastVisualColumn - firstVisualColumn + 1)
- + vc - firstVisualColumn);
- }
- }
-
- }
- painter->setClipRegion(region);
-}
-
-/*!
- \internal
- Updates spans after row insertion.
-*/
-void QTableViewPrivate::_q_updateSpanInsertedRows(const QModelIndex &parent, int start, int end)
-{
- Q_UNUSED(parent)
- spans.updateInsertedRows(start, end);
-}
-
-/*!
- \internal
- Updates spans after column insertion.
-*/
-void QTableViewPrivate::_q_updateSpanInsertedColumns(const QModelIndex &parent, int start, int end)
-{
- Q_UNUSED(parent)
- spans.updateInsertedColumns(start, end);
-}
-
-/*!
- \internal
- Updates spans after row removal.
-*/
-void QTableViewPrivate::_q_updateSpanRemovedRows(const QModelIndex &parent, int start, int end)
-{
- Q_UNUSED(parent)
- spans.updateRemovedRows(start, end);
-}
-
-/*!
- \internal
- Updates spans after column removal.
-*/
-void QTableViewPrivate::_q_updateSpanRemovedColumns(const QModelIndex &parent, int start, int end)
-{
- Q_UNUSED(parent)
- spans.updateRemovedColumns(start, end);
-}
-
-/*!
- \internal
- Draws a table cell.
-*/
-void QTableViewPrivate::drawCell(QPainter *painter, const QStyleOptionViewItemV4 &option, const QModelIndex &index)
-{
- Q_Q(QTableView);
- QStyleOptionViewItemV4 opt = option;
-
- if (selectionModel && selectionModel->isSelected(index))
- opt.state |= QStyle::State_Selected;
- if (index == hover)
- opt.state |= QStyle::State_MouseOver;
- if (option.state & QStyle::State_Enabled) {
- QPalette::ColorGroup cg;
- if ((model->flags(index) & Qt::ItemIsEnabled) == 0) {
- opt.state &= ~QStyle::State_Enabled;
- cg = QPalette::Disabled;
- } else {
- cg = QPalette::Normal;
- }
- opt.palette.setCurrentColorGroup(cg);
- }
-
- if (index == q->currentIndex()) {
- const bool focus = (q->hasFocus() || viewport->hasFocus()) && q->currentIndex().isValid();
- if (focus)
- opt.state |= QStyle::State_HasFocus;
- }
-
- q->style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, q);
-
- q->itemDelegate(index)->paint(painter, opt, index);
-}
-
-/*!
- \class QTableView
-
- \brief The QTableView class provides a default model/view
- implementation of a table view.
-
- \ingroup model-view
- \ingroup advanced
-
-
- A QTableView implements a table view that displays items from a
- model. This class is used to provide standard tables that were
- previously provided by the QTable class, but using the more
- flexible approach provided by Qt's model/view architecture.
-
- The QTableView class is one of the \l{Model/View Classes}
- and is part of Qt's \l{Model/View Programming}{model/view framework}.
-
- QTableView implements the interfaces defined by the
- QAbstractItemView class to allow it to display data provided by
- models derived from the QAbstractItemModel class.
-
- \section1 Navigation
-
- You can navigate the cells in the table by clicking on a cell with the
- mouse, or by using the arrow keys. Because QTableView enables
- \l{QAbstractItemView::tabKeyNavigation}{tabKeyNavigation} by default, you
- can also hit Tab and Backtab to move from cell to cell.
-
- \section1 Visual Appearance
-
- The table has a vertical header that can be obtained using the
- verticalHeader() function, and a horizontal header that is available
- through the horizontalHeader() function. The height of each row in the
- table can be found by using rowHeight(); similarly, the width of
- columns can be found using columnWidth(). Since both of these are plain
- widgets, you can hide either of them using their hide() functions.
-
- Rows and columns can be hidden and shown with hideRow(), hideColumn(),
- showRow(), and showColumn(). They can be selected with selectRow()
- and selectColumn(). The table will show a grid depending on the
- \l showGrid property.
-
- The items shown in a table view, like those in the other item views, are
- rendered and edited using standard \l{QItemDelegate}{delegates}. However,
- for some tasks it is sometimes useful to be able to insert widgets in a
- table instead. Widgets are set for particular indexes with the
- \l{QAbstractItemView::}{setIndexWidget()} function, and
- later retrieved with \l{QAbstractItemView::}{indexWidget()}.
-
- \table
- \row \o \inlineimage qtableview-resized.png
- \o By default, the cells in a table do not expand to fill the available space.
-
- You can make the cells fill the available space by stretching the last
- header section. Access the relevant header using horizontalHeader()
- or verticalHeader() and set the header's \l{QHeaderView::}{stretchLastSection}
- property.
-
- To distribute the available space according to the space requirement of
- each column or row, call the view's resizeColumnsToContents() or
- resizeRowsToContents() functions.
- \endtable
-
- \section1 Coordinate Systems
-
- For some specialized forms of tables it is useful to be able to
- convert between row and column indexes and widget coordinates.
- The rowAt() function provides the y-coordinate within the view of the
- specified row; the row index can be used to obtain a corresponding
- y-coordinate with rowViewportPosition(). The columnAt() and
- columnViewportPosition() functions provide the equivalent conversion
- operations between x-coordinates and column indexes.
-
- \section1 Styles
-
- QTableView is styled appropriately for each platform. The following images show
- how it looks on three different platforms. Go to the \l{Qt Widget Gallery} to see
- its appearance in other styles.
-
- \table 100%
- \row \o \inlineimage windowsxp-tableview.png Screenshot of a Windows XP style table view
- \o \inlineimage macintosh-tableview.png Screenshot of a Macintosh style table view
- \o \inlineimage plastique-tableview.png Screenshot of a Plastique style table view
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} table view.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} table view.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} table view.
- \endtable
-
- \sa QTableWidget, {View Classes}, QAbstractItemModel, QAbstractItemView,
- {Chart Example}, {Pixelator Example}, {Table Model Example}
-*/
-
-/*!
- Constructs a table view with a \a parent to represent the data.
-
- \sa QAbstractItemModel
-*/
-
-QTableView::QTableView(QWidget *parent)
- : QAbstractItemView(*new QTableViewPrivate, parent)
-{
- Q_D(QTableView);
- d->init();
-}
-
-/*!
- \internal
-*/
-QTableView::QTableView(QTableViewPrivate &dd, QWidget *parent)
- : QAbstractItemView(dd, parent)
-{
- Q_D(QTableView);
- d->init();
-}
-
-/*!
- Destroys the table view.
-*/
-QTableView::~QTableView()
-{
-}
-
-/*!
- \reimp
-*/
-void QTableView::setModel(QAbstractItemModel *model)
-{
- Q_D(QTableView);
- if (model == d->model)
- return;
- //let's disconnect from the old model
- if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedRows(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedColumns(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedRows(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedColumns(QModelIndex,int,int)));
- }
- if (model) { //and connect to the new one
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedRows(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanInsertedColumns(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedRows(QModelIndex,int,int)));
- connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateSpanRemovedColumns(QModelIndex,int,int)));
- }
- d->verticalHeader->setModel(model);
- d->horizontalHeader->setModel(model);
- QAbstractItemView::setModel(model);
-}
-
-/*!
- \reimp
-*/
-void QTableView::setRootIndex(const QModelIndex &index)
-{
- Q_D(QTableView);
- if (index == d->root) {
- viewport()->update();
- return;
- }
- d->verticalHeader->setRootIndex(index);
- d->horizontalHeader->setRootIndex(index);
- QAbstractItemView::setRootIndex(index);
-}
-
-/*!
- \reimp
-*/
-void QTableView::setSelectionModel(QItemSelectionModel *selectionModel)
-{
- Q_D(QTableView);
- Q_ASSERT(selectionModel);
- d->verticalHeader->setSelectionModel(selectionModel);
- d->horizontalHeader->setSelectionModel(selectionModel);
- QAbstractItemView::setSelectionModel(selectionModel);
-}
-
-/*!
- Returns the table view's horizontal header.
-
- \sa setHorizontalHeader(), verticalHeader(), QAbstractItemModel::headerData()
-*/
-QHeaderView *QTableView::horizontalHeader() const
-{
- Q_D(const QTableView);
- return d->horizontalHeader;
-}
-
-/*!
- Returns the table view's vertical header.
-
- \sa setVerticalHeader(), horizontalHeader(), QAbstractItemModel::headerData()
-*/
-QHeaderView *QTableView::verticalHeader() const
-{
- Q_D(const QTableView);
- return d->verticalHeader;
-}
-
-/*!
- Sets the widget to use for the horizontal header to \a header.
-
- \sa horizontalHeader() setVerticalHeader()
-*/
-void QTableView::setHorizontalHeader(QHeaderView *header)
-{
- Q_D(QTableView);
-
- if (!header || header == d->horizontalHeader)
- return;
- if (d->horizontalHeader && d->horizontalHeader->parent() == this)
- delete d->horizontalHeader;
- d->horizontalHeader = header;
- d->horizontalHeader->setParent(this);
- if (!d->horizontalHeader->model()) {
- d->horizontalHeader->setModel(d->model);
- if (d->selectionModel)
- d->horizontalHeader->setSelectionModel(d->selectionModel);
- }
-
- connect(d->horizontalHeader,SIGNAL(sectionResized(int,int,int)),
- this, SLOT(columnResized(int,int,int)));
- connect(d->horizontalHeader, SIGNAL(sectionMoved(int,int,int)),
- this, SLOT(columnMoved(int,int,int)));
- connect(d->horizontalHeader, SIGNAL(sectionCountChanged(int,int)),
- this, SLOT(columnCountChanged(int,int)));
- connect(d->horizontalHeader, SIGNAL(sectionPressed(int)), this, SLOT(selectColumn(int)));
- connect(d->horizontalHeader, SIGNAL(sectionEntered(int)), this, SLOT(_q_selectColumn(int)));
- connect(d->horizontalHeader, SIGNAL(sectionHandleDoubleClicked(int)),
- this, SLOT(resizeColumnToContents(int)));
- connect(d->horizontalHeader, SIGNAL(geometriesChanged()), this, SLOT(updateGeometries()));
-
- //update the sorting enabled states on the new header
- setSortingEnabled(d->sortingEnabled);
-}
-
-/*!
- Sets the widget to use for the vertical header to \a header.
-
- \sa verticalHeader() setHorizontalHeader()
-*/
-void QTableView::setVerticalHeader(QHeaderView *header)
-{
- Q_D(QTableView);
-
- if (!header || header == d->verticalHeader)
- return;
- if (d->verticalHeader && d->verticalHeader->parent() == this)
- delete d->verticalHeader;
- d->verticalHeader = header;
- d->verticalHeader->setParent(this);
- if (!d->verticalHeader->model()) {
- d->verticalHeader->setModel(d->model);
- if (d->selectionModel)
- d->verticalHeader->setSelectionModel(d->selectionModel);
- }
-
- connect(d->verticalHeader, SIGNAL(sectionResized(int,int,int)),
- this, SLOT(rowResized(int,int,int)));
- connect(d->verticalHeader, SIGNAL(sectionMoved(int,int,int)),
- this, SLOT(rowMoved(int,int,int)));
- connect(d->verticalHeader, SIGNAL(sectionCountChanged(int,int)),
- this, SLOT(rowCountChanged(int,int)));
- connect(d->verticalHeader, SIGNAL(sectionPressed(int)), this, SLOT(selectRow(int)));
- connect(d->verticalHeader, SIGNAL(sectionEntered(int)), this, SLOT(_q_selectRow(int)));
- connect(d->verticalHeader, SIGNAL(sectionHandleDoubleClicked(int)),
- this, SLOT(resizeRowToContents(int)));
- connect(d->verticalHeader, SIGNAL(geometriesChanged()), this, SLOT(updateGeometries()));
-}
-
-/*!
- \internal
-
- Scroll the contents of the table view by (\a dx, \a dy).
-*/
-void QTableView::scrollContentsBy(int dx, int dy)
-{
- Q_D(QTableView);
-
- d->delayedAutoScroll.stop(); // auto scroll was canceled by the user scrolling
-
- dx = isRightToLeft() ? -dx : dx;
- if (dx) {
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int oldOffset = d->horizontalHeader->offset();
- if (horizontalScrollBar()->value() == horizontalScrollBar()->maximum())
- d->horizontalHeader->setOffsetToLastSection();
- else
- d->horizontalHeader->setOffsetToSectionPosition(horizontalScrollBar()->value());
- int newOffset = d->horizontalHeader->offset();
- dx = isRightToLeft() ? newOffset - oldOffset : oldOffset - newOffset;
- } else {
- d->horizontalHeader->setOffset(horizontalScrollBar()->value());
- }
- }
- if (dy) {
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int oldOffset = d->verticalHeader->offset();
- if (verticalScrollBar()->value() == verticalScrollBar()->maximum())
- d->verticalHeader->setOffsetToLastSection();
- else
- d->verticalHeader->setOffsetToSectionPosition(verticalScrollBar()->value());
- int newOffset = d->verticalHeader->offset();
- dy = oldOffset - newOffset;
- } else {
- d->verticalHeader->setOffset(verticalScrollBar()->value());
- }
- }
- d->scrollContentsBy(dx, dy);
-
- if (d->showGrid) {
- //we need to update the first line of the previous top item in the view
- //because it has the grid drawn if the header is invisible.
- //It is strictly related to what's done at then end of the paintEvent
- if (dy > 0 && d->horizontalHeader->isHidden() && d->verticalScrollMode == ScrollPerItem) {
- d->viewport->update(0, dy, d->viewport->width(), dy);
- }
- if (dx > 0 && d->verticalHeader->isHidden() && d->horizontalScrollMode == ScrollPerItem) {
- d->viewport->update(dx, 0, dx, d->viewport->height());
- }
- }
-}
-
-/*!
- \reimp
-*/
-QStyleOptionViewItem QTableView::viewOptions() const
-{
- QStyleOptionViewItem option = QAbstractItemView::viewOptions();
- option.showDecorationSelected = true;
- return option;
-}
-
-/*!
- Paints the table on receipt of the given paint event \a event.
-*/
-void QTableView::paintEvent(QPaintEvent *event)
-{
- Q_D(QTableView);
- // setup temp variables for the painting
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- const QPoint offset = d->scrollDelayOffset;
- const bool showGrid = d->showGrid;
- const int gridSize = showGrid ? 1 : 0;
- const int gridHint = style()->styleHint(QStyle::SH_Table_GridLineColor, &option, this);
- const QColor gridColor = static_cast<QRgb>(gridHint);
- const QPen gridPen = QPen(gridColor, 0, d->gridStyle);
- const QHeaderView *verticalHeader = d->verticalHeader;
- const QHeaderView *horizontalHeader = d->horizontalHeader;
- const QStyle::State state = option.state;
- const bool alternate = d->alternatingColors;
- const bool rightToLeft = isRightToLeft();
-
- QPainter painter(d->viewport);
-
- // if there's nothing to do, clear the area and return
- if (horizontalHeader->count() == 0 || verticalHeader->count() == 0 || !d->itemDelegate)
- return;
-
- uint x = horizontalHeader->length() - horizontalHeader->offset() - (rightToLeft ? 0 : 1);
- uint y = verticalHeader->length() - verticalHeader->offset() - 1;
-
- const QRegion region = event->region().translated(offset);
- const QVector<QRect> rects = region.rects();
-
- //firstVisualRow is the visual index of the first visible row. lastVisualRow is the visual index of the last visible Row.
- //same goes for ...VisualColumn
- int firstVisualRow = qMax(verticalHeader->visualIndexAt(0),0);
- int lastVisualRow = verticalHeader->visualIndexAt(verticalHeader->viewport()->height());
- if (lastVisualRow == -1)
- lastVisualRow = d->model->rowCount(d->root) - 1;
-
- int firstVisualColumn = horizontalHeader->visualIndexAt(0);
- int lastVisualColumn = horizontalHeader->visualIndexAt(horizontalHeader->viewport()->width());
- if (rightToLeft)
- qSwap(firstVisualColumn, lastVisualColumn);
- if (firstVisualColumn == -1)
- firstVisualColumn = 0;
- if (lastVisualColumn == -1)
- lastVisualColumn = horizontalHeader->count() - 1;
-
- QBitArray drawn((lastVisualRow - firstVisualRow + 1) * (lastVisualColumn - firstVisualColumn + 1));
-
- if (d->hasSpans()) {
- d->drawAndClipSpans(region, &painter, option, &drawn,
- firstVisualRow, lastVisualRow, firstVisualColumn, lastVisualColumn);
- }
-
- for (int i = 0; i < rects.size(); ++i) {
- QRect dirtyArea = rects.at(i);
- dirtyArea.setBottom(qMin(dirtyArea.bottom(), int(y)));
- if (rightToLeft) {
- dirtyArea.setLeft(qMax(dirtyArea.left(), d->viewport->width() - int(x)));
- } else {
- dirtyArea.setRight(qMin(dirtyArea.right(), int(x)));
- }
-
- // get the horizontal start and end visual sections
- int left = horizontalHeader->visualIndexAt(dirtyArea.left());
- int right = horizontalHeader->visualIndexAt(dirtyArea.right());
- if (rightToLeft)
- qSwap(left, right);
- if (left == -1) left = 0;
- if (right == -1) right = horizontalHeader->count() - 1;
-
- // get the vertical start and end visual sections and if alternate color
- int bottom = verticalHeader->visualIndexAt(dirtyArea.bottom());
- if (bottom == -1) bottom = verticalHeader->count() - 1;
- int top = 0;
- bool alternateBase = false;
- if (alternate && verticalHeader->sectionsHidden()) {
- uint verticalOffset = verticalHeader->offset();
- int row = verticalHeader->logicalIndex(top);
- for (int y = 0;
- ((uint)(y += verticalHeader->sectionSize(top)) <= verticalOffset) && (top < bottom);
- ++top) {
- row = verticalHeader->logicalIndex(top);
- if (alternate && !verticalHeader->isSectionHidden(row))
- alternateBase = !alternateBase;
- }
- } else {
- top = verticalHeader->visualIndexAt(dirtyArea.top());
- alternateBase = (top & 1) && alternate;
- }
- if (top == -1 || top > bottom)
- continue;
-
- // Paint each row item
- for (int visualRowIndex = top; visualRowIndex <= bottom; ++visualRowIndex) {
- int row = verticalHeader->logicalIndex(visualRowIndex);
- if (verticalHeader->isSectionHidden(row))
- continue;
- int rowY = rowViewportPosition(row);
- rowY += offset.y();
- int rowh = rowHeight(row) - gridSize;
-
- // Paint each column item
- for (int visualColumnIndex = left; visualColumnIndex <= right; ++visualColumnIndex) {
- int currentBit = (visualRowIndex - firstVisualRow) * (lastVisualColumn - firstVisualColumn + 1)
- + visualColumnIndex - firstVisualColumn;
-
- if (currentBit < 0 || currentBit >= drawn.size() || drawn.testBit(currentBit))
- continue;
- drawn.setBit(currentBit);
-
- int col = horizontalHeader->logicalIndex(visualColumnIndex);
- if (horizontalHeader->isSectionHidden(col))
- continue;
- int colp = columnViewportPosition(col);
- colp += offset.x();
- int colw = columnWidth(col) - gridSize;
-
- const QModelIndex index = d->model->index(row, col, d->root);
- if (index.isValid()) {
- option.rect = QRect(colp + (showGrid && rightToLeft ? 1 : 0), rowY, colw, rowh);
- if (alternate) {
- if (alternateBase)
- option.features |= QStyleOptionViewItemV2::Alternate;
- else
- option.features &= ~QStyleOptionViewItemV2::Alternate;
- }
- d->drawCell(&painter, option, index);
- }
- }
- alternateBase = !alternateBase && alternate;
- }
-
- if (showGrid) {
- // Find the bottom right (the last rows/columns might be hidden)
- while (verticalHeader->isSectionHidden(verticalHeader->logicalIndex(bottom))) --bottom;
- QPen old = painter.pen();
- painter.setPen(gridPen);
- // Paint each row
- for (int visualIndex = top; visualIndex <= bottom; ++visualIndex) {
- int row = verticalHeader->logicalIndex(visualIndex);
- if (verticalHeader->isSectionHidden(row))
- continue;
- int rowY = rowViewportPosition(row);
- rowY += offset.y();
- int rowh = rowHeight(row) - gridSize;
- painter.drawLine(dirtyArea.left(), rowY + rowh, dirtyArea.right(), rowY + rowh);
- }
-
- // Paint each column
- for (int h = left; h <= right; ++h) {
- int col = horizontalHeader->logicalIndex(h);
- if (horizontalHeader->isSectionHidden(col))
- continue;
- int colp = columnViewportPosition(col);
- colp += offset.x();
- if (!rightToLeft)
- colp += columnWidth(col) - gridSize;
- painter.drawLine(colp, dirtyArea.top(), colp, dirtyArea.bottom());
- }
-
- //draw the top & left grid lines if the headers are not visible.
- //We do update this line when subsequent scroll happen (see scrollContentsBy)
- if (horizontalHeader->isHidden() && verticalScrollMode() == ScrollPerItem)
- painter.drawLine(dirtyArea.left(), 0, dirtyArea.right(), 0);
- if (verticalHeader->isHidden() && horizontalScrollMode() == ScrollPerItem)
- painter.drawLine(0, dirtyArea.top(), 0, dirtyArea.bottom());
- painter.setPen(old);
- }
- }
-
-#ifndef QT_NO_DRAGANDDROP
- // Paint the dropIndicator
- d->paintDropIndicator(&painter);
-#endif
-}
-
-/*!
- Returns the index position of the model item corresponding to the
- table item at position \a pos in contents coordinates.
-*/
-QModelIndex QTableView::indexAt(const QPoint &pos) const
-{
- Q_D(const QTableView);
- d->executePostedLayout();
- int r = rowAt(pos.y());
- int c = columnAt(pos.x());
- if (r >= 0 && c >= 0) {
- if (d->hasSpans()) {
- QSpanCollection::Span span = d->span(r, c);
- r = span.top();
- c = span.left();
- }
- return d->model->index(r, c, d->root);
- }
- return QModelIndex();
-}
-
-/*!
- Returns the horizontal offset of the items in the table view.
-
- Note that the table view uses the horizontal header section
- positions to determine the positions of columns in the view.
-
- \sa verticalOffset()
-*/
-int QTableView::horizontalOffset() const
-{
- Q_D(const QTableView);
- return d->horizontalHeader->offset();
-}
-
-/*!
- Returns the vertical offset of the items in the table view.
-
- Note that the table view uses the vertical header section
- positions to determine the positions of rows in the view.
-
- \sa horizontalOffset()
-*/
-int QTableView::verticalOffset() const
-{
- Q_D(const QTableView);
- return d->verticalHeader->offset();
-}
-
-/*!
- \fn QModelIndex QTableView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
-
- Moves the cursor in accordance with the given \a cursorAction, using the
- information provided by the \a modifiers.
-
- \sa QAbstractItemView::CursorAction
-*/
-QModelIndex QTableView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
-{
- Q_D(QTableView);
- Q_UNUSED(modifiers);
-
- int bottom = d->model->rowCount(d->root) - 1;
- // make sure that bottom is the bottommost *visible* row
- while (bottom >= 0 && isRowHidden(d->logicalRow(bottom)))
- --bottom;
-
- int right = d->model->columnCount(d->root) - 1;
-
- while (right >= 0 && isColumnHidden(d->logicalColumn(right)))
- --right;
-
- if (bottom == -1 || right == -1)
- return QModelIndex(); // model is empty
-
- QModelIndex current = currentIndex();
-
- if (!current.isValid()) {
- int row = 0;
- int column = 0;
- while (column < right && isColumnHidden(d->logicalColumn(column)))
- ++column;
- while (isRowHidden(d->logicalRow(row)) && row < bottom)
- ++row;
- d->visualCursor = QPoint(column, row);
- return d->model->index(d->logicalRow(row), d->logicalColumn(column), d->root);
- }
-
- // Update visual cursor if current index has changed.
- QPoint visualCurrent(d->visualColumn(current.column()), d->visualRow(current.row()));
- if (visualCurrent != d->visualCursor) {
- if (d->hasSpans()) {
- QSpanCollection::Span span = d->span(current.row(), current.column());
- if (span.top() > d->visualCursor.y() || d->visualCursor.y() > span.bottom()
- || span.left() > d->visualCursor.x() || d->visualCursor.x() > span.right())
- d->visualCursor = visualCurrent;
- } else {
- d->visualCursor = visualCurrent;
- }
- }
-
- int visualRow = d->visualCursor.y();
- if (visualRow > bottom)
- visualRow = bottom;
- Q_ASSERT(visualRow != -1);
- int visualColumn = d->visualCursor.x();
- if (visualColumn > right)
- visualColumn = right;
- Q_ASSERT(visualColumn != -1);
-
- if (isRightToLeft()) {
- if (cursorAction == MoveLeft)
- cursorAction = MoveRight;
- else if (cursorAction == MoveRight)
- cursorAction = MoveLeft;
- }
-
- switch (cursorAction) {
- case MoveUp: {
- int originalRow = visualRow;
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && visualRow == 0)
- visualRow = d->visualRow(model()->rowCount() - 1) + 1;
- // FIXME? visualRow = bottom + 1;
-#endif
- int r = d->logicalRow(visualRow);
- int c = d->logicalColumn(visualColumn);
- if (r != -1 && d->hasSpans()) {
- QSpanCollection::Span span = d->span(r, c);
- if (span.width() > 1 || span.height() > 1)
- visualRow = d->visualRow(span.top());
- }
- while (visualRow >= 0) {
- --visualRow;
- r = d->logicalRow(visualRow);
- c = d->logicalColumn(visualColumn);
- if (r == -1 || (!isRowHidden(r) && d->isCellEnabled(r, c)))
- break;
- }
- if (visualRow < 0)
- visualRow = originalRow;
- break;
- }
- case MoveDown: {
- int originalRow = visualRow;
- if (d->hasSpans()) {
- QSpanCollection::Span span = d->span(current.row(), current.column());
- visualRow = d->visualRow(d->rowSpanEndLogical(span.top(), span.height()));
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && visualRow >= bottom)
- visualRow = -1;
-#endif
- int r = d->logicalRow(visualRow);
- int c = d->logicalColumn(visualColumn);
- if (r != -1 && d->hasSpans()) {
- QSpanCollection::Span span = d->span(r, c);
- if (span.width() > 1 || span.height() > 1)
- visualRow = d->visualRow(d->rowSpanEndLogical(span.top(), span.height()));
- }
- while (visualRow <= bottom) {
- ++visualRow;
- r = d->logicalRow(visualRow);
- c = d->logicalColumn(visualColumn);
- if (r == -1 || (!isRowHidden(r) && d->isCellEnabled(r, c)))
- break;
- }
- if (visualRow > bottom)
- visualRow = originalRow;
- break;
- }
- case MovePrevious:
- case MoveLeft: {
- int originalRow = visualRow;
- int originalColumn = visualColumn;
- bool firstTime = true;
- bool looped = false;
- bool wrapped = false;
- do {
- int r = d->logicalRow(visualRow);
- int c = d->logicalColumn(visualColumn);
- if (firstTime && c != -1 && d->hasSpans()) {
- firstTime = false;
- QSpanCollection::Span span = d->span(r, c);
- if (span.width() > 1 || span.height() > 1)
- visualColumn = d->visualColumn(span.left());
- }
- while (visualColumn >= 0) {
- --visualColumn;
- r = d->logicalRow(visualRow);
- c = d->logicalColumn(visualColumn);
- if (r == -1 || c == -1 || (!isRowHidden(r) && !isColumnHidden(c) && d->isCellEnabled(r, c)))
- break;
- if (wrapped && (originalRow < visualRow || (originalRow == visualRow && originalColumn <= visualColumn))) {
- looped = true;
- break;
- }
- }
- if (cursorAction == MoveLeft || visualColumn >= 0)
- break;
- visualColumn = right + 1;
- if (visualRow == 0) {
- wrapped = true;
- visualRow = bottom;
- } else {
- --visualRow;
- }
- } while (!looped);
- if (visualColumn < 0)
- visualColumn = originalColumn;
- break;
- }
- case MoveNext:
- case MoveRight: {
- int originalRow = visualRow;
- int originalColumn = visualColumn;
- bool firstTime = true;
- bool looped = false;
- bool wrapped = false;
- do {
- int r = d->logicalRow(visualRow);
- int c = d->logicalColumn(visualColumn);
- if (firstTime && c != -1 && d->hasSpans()) {
- firstTime = false;
- QSpanCollection::Span span = d->span(r, c);
- if (span.width() > 1 || span.height() > 1)
- visualColumn = d->visualColumn(d->columnSpanEndLogical(span.left(), span.width()));
- }
- while (visualColumn <= right) {
- ++visualColumn;
- r = d->logicalRow(visualRow);
- c = d->logicalColumn(visualColumn);
- if (r == -1 || c == -1 || (!isRowHidden(r) && !isColumnHidden(c) && d->isCellEnabled(r, c)))
- break;
- if (wrapped && (originalRow > visualRow || (originalRow == visualRow && originalColumn >= visualColumn))) {
- looped = true;
- break;
- }
- }
- if (cursorAction == MoveRight || visualColumn <= right)
- break;
- visualColumn = -1;
- if (visualRow == bottom) {
- wrapped = true;
- visualRow = 0;
- } else {
- ++visualRow;
- }
- } while (!looped);
- if (visualColumn > right)
- visualColumn = originalColumn;
- break;
- }
- case MoveHome:
- visualColumn = 0;
- while (visualColumn < right && d->isVisualColumnHiddenOrDisabled(visualRow, visualColumn))
- ++visualColumn;
- if (modifiers & Qt::ControlModifier) {
- visualRow = 0;
- while (visualRow < bottom && d->isVisualRowHiddenOrDisabled(visualRow, visualColumn))
- ++visualRow;
- }
- break;
- case MoveEnd:
- visualColumn = right;
- if (modifiers & Qt::ControlModifier)
- visualRow = bottom;
- break;
- case MovePageUp: {
- int newRow = rowAt(visualRect(current).top() - d->viewport->height());
- if (newRow == -1)
- newRow = d->logicalRow(0);
- return d->model->index(newRow, current.column(), d->root);
- }
- case MovePageDown: {
- int newRow = rowAt(visualRect(current).bottom() + d->viewport->height());
- if (newRow == -1)
- newRow = d->logicalRow(bottom);
- return d->model->index(newRow, current.column(), d->root);
- }}
-
- d->visualCursor = QPoint(visualColumn, visualRow);
- int logicalRow = d->logicalRow(visualRow);
- int logicalColumn = d->logicalColumn(visualColumn);
- if (!d->model->hasIndex(logicalRow, logicalColumn, d->root))
- return QModelIndex();
-
- QModelIndex result = d->model->index(logicalRow, logicalColumn, d->root);
- if (!d->isRowHidden(logicalRow) && !d->isColumnHidden(logicalColumn) && d->isIndexEnabled(result))
- return result;
-
- return QModelIndex();
-}
-
-/*!
- \fn void QTableView::setSelection(const QRect &rect,
- QItemSelectionModel::SelectionFlags flags)
-
- Selects the items within the given \a rect and in accordance with
- the specified selection \a flags.
-*/
-void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QTableView);
- QModelIndex tl = indexAt(QPoint(isRightToLeft() ? qMax(rect.left(), rect.right())
- : qMin(rect.left(), rect.right()), qMin(rect.top(), rect.bottom())));
- QModelIndex br = indexAt(QPoint(isRightToLeft() ? qMin(rect.left(), rect.right()) :
- qMax(rect.left(), rect.right()), qMax(rect.top(), rect.bottom())));
- if (!d->selectionModel || !tl.isValid() || !br.isValid() || !d->isIndexEnabled(tl) || !d->isIndexEnabled(br))
- return;
-
- bool verticalMoved = verticalHeader()->sectionsMoved();
- bool horizontalMoved = horizontalHeader()->sectionsMoved();
-
- QItemSelection selection;
-
- if (d->hasSpans()) {
- bool expanded;
- int top = qMin(d->visualRow(tl.row()), d->visualRow(br.row()));
- int left = qMin(d->visualColumn(tl.column()), d->visualColumn(br.column()));
- int bottom = qMax(d->visualRow(tl.row()), d->visualRow(br.row()));
- int right = qMax(d->visualColumn(tl.column()), d->visualColumn(br.column()));
- do {
- expanded = false;
- foreach (QSpanCollection::Span *it, d->spans.spans) {
- const QSpanCollection::Span &span = *it;
- int t = d->visualRow(span.top());
- int l = d->visualColumn(span.left());
- int b = d->visualRow(d->rowSpanEndLogical(span.top(), span.height()));
- int r = d->visualColumn(d->columnSpanEndLogical(span.left(), span.width()));
- if ((t > bottom) || (l > right) || (top > b) || (left > r))
- continue; // no intersect
- if (t < top) {
- top = t;
- expanded = true;
- }
- if (l < left) {
- left = l;
- expanded = true;
- }
- if (b > bottom) {
- bottom = b;
- expanded = true;
- }
- if (r > right) {
- right = r;
- expanded = true;
- }
- if (expanded)
- break;
- }
- } while (expanded);
- for (int horizontal = left; horizontal <= right; ++horizontal) {
- int column = d->logicalColumn(horizontal);
- for (int vertical = top; vertical <= bottom; ++vertical) {
- int row = d->logicalRow(vertical);
- QModelIndex index = d->model->index(row, column, d->root);
- selection.append(QItemSelectionRange(index));
- }
- }
- } else if (verticalMoved && horizontalMoved) {
- int top = d->visualRow(tl.row());
- int left = d->visualColumn(tl.column());
- int bottom = d->visualRow(br.row());
- int right = d->visualColumn(br.column());
- for (int horizontal = left; horizontal <= right; ++horizontal) {
- int column = d->logicalColumn(horizontal);
- for (int vertical = top; vertical <= bottom; ++vertical) {
- int row = d->logicalRow(vertical);
- QModelIndex index = d->model->index(row, column, d->root);
- selection.append(QItemSelectionRange(index));
- }
- }
- } else if (horizontalMoved) {
- int left = d->visualColumn(tl.column());
- int right = d->visualColumn(br.column());
- for (int visual = left; visual <= right; ++visual) {
- int column = d->logicalColumn(visual);
- QModelIndex topLeft = d->model->index(tl.row(), column, d->root);
- QModelIndex bottomRight = d->model->index(br.row(), column, d->root);
- selection.append(QItemSelectionRange(topLeft, bottomRight));
- }
- } else if (verticalMoved) {
- int top = d->visualRow(tl.row());
- int bottom = d->visualRow(br.row());
- for (int visual = top; visual <= bottom; ++visual) {
- int row = d->logicalRow(visual);
- QModelIndex topLeft = d->model->index(row, tl.column(), d->root);
- QModelIndex bottomRight = d->model->index(row, br.column(), d->root);
- selection.append(QItemSelectionRange(topLeft, bottomRight));
- }
- } else { // nothing moved
- QItemSelectionRange range(tl, br);
- if (!range.isEmpty())
- selection.append(range);
- }
-
- d->selectionModel->select(selection, command);
-}
-
-/*!
- \internal
-
- Returns the rectangle from the viewport of the items in the given
- \a selection.
-
- Since 4.7, the returned region only contains rectangles intersecting
- (or included in) the viewport.
-*/
-QRegion QTableView::visualRegionForSelection(const QItemSelection &selection) const
-{
- Q_D(const QTableView);
-
- if (selection.isEmpty())
- return QRegion();
-
- QRegion selectionRegion;
- const QRect &viewportRect = d->viewport->rect();
- bool verticalMoved = verticalHeader()->sectionsMoved();
- bool horizontalMoved = horizontalHeader()->sectionsMoved();
-
- if ((verticalMoved && horizontalMoved) || (d->hasSpans() && (verticalMoved || horizontalMoved))) {
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange range = selection.at(i);
- if (range.parent() != d->root || !range.isValid())
- continue;
- for (int r = range.top(); r <= range.bottom(); ++r)
- for (int c = range.left(); c <= range.right(); ++c) {
- const QRect &rangeRect = visualRect(d->model->index(r, c, d->root));
- if (viewportRect.intersects(rangeRect))
- selectionRegion += rangeRect;
- }
- }
- } else if (horizontalMoved) {
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange range = selection.at(i);
- if (range.parent() != d->root || !range.isValid())
- continue;
- int top = rowViewportPosition(range.top());
- int bottom = rowViewportPosition(range.bottom()) + rowHeight(range.bottom());
- if (top > bottom)
- qSwap<int>(top, bottom);
- int height = bottom - top;
- for (int c = range.left(); c <= range.right(); ++c) {
- const QRect rangeRect(columnViewportPosition(c), top, columnWidth(c), height);
- if (viewportRect.intersects(rangeRect))
- selectionRegion += rangeRect;
- }
- }
- } else if (verticalMoved) {
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange range = selection.at(i);
- if (range.parent() != d->root || !range.isValid())
- continue;
- int left = columnViewportPosition(range.left());
- int right = columnViewportPosition(range.right()) + columnWidth(range.right());
- if (left > right)
- qSwap<int>(left, right);
- int width = right - left;
- for (int r = range.top(); r <= range.bottom(); ++r) {
- const QRect rangeRect(left, rowViewportPosition(r), width, rowHeight(r));
- if (viewportRect.intersects(rangeRect))
- selectionRegion += rangeRect;
- }
- }
- } else { // nothing moved
- const int gridAdjust = showGrid() ? 1 : 0;
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange range = selection.at(i);
- if (range.parent() != d->root || !range.isValid())
- continue;
- d->trimHiddenSelections(&range);
-
- const int rtop = rowViewportPosition(range.top());
- const int rbottom = rowViewportPosition(range.bottom()) + rowHeight(range.bottom());
- int rleft;
- int rright;
- if (isLeftToRight()) {
- rleft = columnViewportPosition(range.left());
- rright = columnViewportPosition(range.right()) + columnWidth(range.right());
- } else {
- rleft = columnViewportPosition(range.right());
- rright = columnViewportPosition(range.left()) + columnWidth(range.left());
- }
- const QRect rangeRect(QPoint(rleft, rtop), QPoint(rright - 1 - gridAdjust, rbottom - 1 - gridAdjust));
- if (viewportRect.intersects(rangeRect))
- selectionRegion += rangeRect;
- if (d->hasSpans()) {
- foreach (QSpanCollection::Span *s,
- d->spans.spansInRect(range.left(), range.top(), range.width(), range.height())) {
- if (range.contains(s->top(), s->left(), range.parent())) {
- const QRect &visualSpanRect = d->visualSpanRect(*s);
- if (viewportRect.intersects(visualSpanRect))
- selectionRegion += visualSpanRect;
- }
- }
- }
- }
- }
-
- return selectionRegion;
-}
-
-
-/*!
- \reimp
-*/
-QModelIndexList QTableView::selectedIndexes() const
-{
- Q_D(const QTableView);
- QModelIndexList viewSelected;
- QModelIndexList modelSelected;
- if (d->selectionModel)
- modelSelected = d->selectionModel->selectedIndexes();
- for (int i = 0; i < modelSelected.count(); ++i) {
- QModelIndex index = modelSelected.at(i);
- if (!isIndexHidden(index) && index.parent() == d->root)
- viewSelected.append(index);
- }
- return viewSelected;
-}
-
-
-/*!
- This slot is called whenever rows are added or deleted. The
- previous number of rows is specified by \a oldCount, and the new
- number of rows is specified by \a newCount.
-*/
-void QTableView::rowCountChanged(int /*oldCount*/, int /*newCount*/ )
-{
- Q_D(QTableView);
- d->doDelayedItemsLayout();
-}
-
-/*!
- This slot is called whenever columns are added or deleted. The
- previous number of columns is specified by \a oldCount, and the new
- number of columns is specified by \a newCount.
-*/
-void QTableView::columnCountChanged(int, int)
-{
- Q_D(QTableView);
- updateGeometries();
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem)
- d->horizontalHeader->setOffsetToSectionPosition(horizontalScrollBar()->value());
- else
- d->horizontalHeader->setOffset(horizontalScrollBar()->value());
- d->viewport->update();
-}
-
-/*!
- \reimp
-*/
-void QTableView::updateGeometries()
-{
- Q_D(QTableView);
- if (d->geometryRecursionBlock)
- return;
- d->geometryRecursionBlock = true;
-
- int width = 0;
- if (!d->verticalHeader->isHidden()) {
- width = qMax(d->verticalHeader->minimumWidth(), d->verticalHeader->sizeHint().width());
- width = qMin(width, d->verticalHeader->maximumWidth());
- }
- int height = 0;
- if (!d->horizontalHeader->isHidden()) {
- height = qMax(d->horizontalHeader->minimumHeight(), d->horizontalHeader->sizeHint().height());
- height = qMin(height, d->horizontalHeader->maximumHeight());
- }
- bool reverse = isRightToLeft();
- if (reverse)
- setViewportMargins(0, height, width, 0);
- else
- setViewportMargins(width, height, 0, 0);
-
- // update headers
-
- QRect vg = d->viewport->geometry();
-
- int verticalLeft = reverse ? vg.right() + 1 : (vg.left() - width);
- d->verticalHeader->setGeometry(verticalLeft, vg.top(), width, vg.height());
- if (d->verticalHeader->isHidden())
- QMetaObject::invokeMethod(d->verticalHeader, "updateGeometries");
-
- int horizontalTop = vg.top() - height;
- d->horizontalHeader->setGeometry(vg.left(), horizontalTop, vg.width(), height);
- if (d->horizontalHeader->isHidden())
- QMetaObject::invokeMethod(d->horizontalHeader, "updateGeometries");
-
- // update cornerWidget
- if (d->horizontalHeader->isHidden() || d->verticalHeader->isHidden()) {
- d->cornerWidget->setHidden(true);
- } else {
- d->cornerWidget->setHidden(false);
- d->cornerWidget->setGeometry(verticalLeft, horizontalTop, width, height);
- }
-
- // update scroll bars
-
- // ### move this block into the if
- QSize vsize = d->viewport->size();
- QSize max = maximumViewportSize();
- uint horizontalLength = d->horizontalHeader->length();
- uint verticalLength = d->verticalHeader->length();
- if ((uint)max.width() >= horizontalLength && (uint)max.height() >= verticalLength)
- vsize = max;
-
- // horizontal scroll bar
- const int columnCount = d->horizontalHeader->count();
- const int viewportWidth = vsize.width();
- int columnsInViewport = 0;
- for (int width = 0, column = columnCount - 1; column >= 0; --column) {
- int logical = d->horizontalHeader->logicalIndex(column);
- if (!d->horizontalHeader->isSectionHidden(logical)) {
- width += d->horizontalHeader->sectionSize(logical);
- if (width > viewportWidth)
- break;
- ++columnsInViewport;
- }
- }
- columnsInViewport = qMax(columnsInViewport, 1); //there must be always at least 1 column
-
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
- const int visibleColumns = columnCount - d->horizontalHeader->hiddenSectionCount();
- horizontalScrollBar()->setRange(0, visibleColumns - columnsInViewport);
- horizontalScrollBar()->setPageStep(columnsInViewport);
- if (columnsInViewport >= visibleColumns)
- d->horizontalHeader->setOffset(0);
- horizontalScrollBar()->setSingleStep(1);
- } else { // ScrollPerPixel
- horizontalScrollBar()->setPageStep(vsize.width());
- horizontalScrollBar()->setRange(0, horizontalLength - vsize.width());
- horizontalScrollBar()->setSingleStep(qMax(vsize.width() / (columnsInViewport + 1), 2));
- }
-
- // vertical scroll bar
- const int rowCount = d->verticalHeader->count();
- const int viewportHeight = vsize.height();
- int rowsInViewport = 0;
- for (int height = 0, row = rowCount - 1; row >= 0; --row) {
- int logical = d->verticalHeader->logicalIndex(row);
- if (!d->verticalHeader->isSectionHidden(logical)) {
- height += d->verticalHeader->sectionSize(logical);
- if (height > viewportHeight)
- break;
- ++rowsInViewport;
- }
- }
- rowsInViewport = qMax(rowsInViewport, 1); //there must be always at least 1 row
-
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- const int visibleRows = rowCount - d->verticalHeader->hiddenSectionCount();
- verticalScrollBar()->setRange(0, visibleRows - rowsInViewport);
- verticalScrollBar()->setPageStep(rowsInViewport);
- if (rowsInViewport >= visibleRows)
- d->verticalHeader->setOffset(0);
- verticalScrollBar()->setSingleStep(1);
- } else { // ScrollPerPixel
- verticalScrollBar()->setPageStep(vsize.height());
- verticalScrollBar()->setRange(0, verticalLength - vsize.height());
- verticalScrollBar()->setSingleStep(qMax(vsize.height() / (rowsInViewport + 1), 2));
- }
-
- d->geometryRecursionBlock = false;
- QAbstractItemView::updateGeometries();
-}
-
-/*!
- Returns the size hint for the given \a row's height or -1 if there
- is no model.
-
- If you need to set the height of a given row to a fixed value, call
- QHeaderView::resizeSection() on the table's vertical header.
-
- If you reimplement this function in a subclass, note that the value you
- return is only used when resizeRowToContents() is called. In that case,
- if a larger row height is required by either the vertical header or
- the item delegate, that width will be used instead.
-
- \sa QWidget::sizeHint, verticalHeader()
-*/
-int QTableView::sizeHintForRow(int row) const
-{
- Q_D(const QTableView);
-
- if (!model())
- return -1;
-
- ensurePolished();
-
- int left = qMax(0, d->horizontalHeader->visualIndexAt(0));
- int right = d->horizontalHeader->visualIndexAt(d->viewport->width());
- if (right == -1) // the table don't have enough columns to fill the viewport
- right = d->model->columnCount(d->root) - 1;
-
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
-
- int hint = 0;
- QModelIndex index;
- for (int column = left; column <= right; ++column) {
- int logicalColumn = d->horizontalHeader->logicalIndex(column);
- if (d->horizontalHeader->isSectionHidden(logicalColumn))
- continue;
- index = d->model->index(row, logicalColumn, d->root);
- if (d->wrapItemText) {// for wrapping boundaries
- option.rect.setY(rowViewportPosition(index.row()));
- option.rect.setHeight(rowHeight(index.row()));
- option.rect.setX(columnViewportPosition(index.column()));
- option.rect.setWidth(columnWidth(index.column()));
- }
-
- QWidget *editor = d->editorForIndex(index).widget.data();
- if (editor && d->persistent.contains(editor)) {
- hint = qMax(hint, editor->sizeHint().height());
- int min = editor->minimumSize().height();
- int max = editor->maximumSize().height();
- hint = qBound(min, hint, max);
- }
-
- hint = qMax(hint, itemDelegate(index)->sizeHint(option, index).height());
- }
-
- return d->showGrid ? hint + 1 : hint;
-}
-
-/*!
- Returns the size hint for the given \a column's width or -1 if
- there is no model.
-
- If you need to set the width of a given column to a fixed value, call
- QHeaderView::resizeSection() on the table's horizontal header.
-
- If you reimplement this function in a subclass, note that the value you
- return will be used when resizeColumnToContents() or
- QHeaderView::resizeSections() is called. If a larger column width is
- required by either the horizontal header or the item delegate, the larger
- width will be used instead.
-
- \sa QWidget::sizeHint, horizontalHeader()
-*/
-int QTableView::sizeHintForColumn(int column) const
-{
- Q_D(const QTableView);
-
- if (!model())
- return -1;
-
- ensurePolished();
-
- int top = qMax(0, d->verticalHeader->visualIndexAt(0));
- int bottom = d->verticalHeader->visualIndexAt(d->viewport->height());
- if (!isVisible() || bottom == -1) // the table don't have enough rows to fill the viewport
- bottom = d->model->rowCount(d->root) - 1;
-
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
-
- int hint = 0;
- QModelIndex index;
- for (int row = top; row <= bottom; ++row) {
- int logicalRow = d->verticalHeader->logicalIndex(row);
- if (d->verticalHeader->isSectionHidden(logicalRow))
- continue;
- index = d->model->index(logicalRow, column, d->root);
-
- QWidget *editor = d->editorForIndex(index).widget.data();
- if (editor && d->persistent.contains(editor)) {
- hint = qMax(hint, editor->sizeHint().width());
- int min = editor->minimumSize().width();
- int max = editor->maximumSize().width();
- hint = qBound(min, hint, max);
- }
-
- hint = qMax(hint, itemDelegate(index)->sizeHint(option, index).width());
- }
-
- return d->showGrid ? hint + 1 : hint;
-}
-
-/*!
- Returns the y-coordinate in contents coordinates of the given \a
- row.
-*/
-int QTableView::rowViewportPosition(int row) const
-{
- Q_D(const QTableView);
- return d->verticalHeader->sectionViewportPosition(row);
-}
-
-/*!
- Returns the row in which the given y-coordinate, \a y, in contents
- coordinates is located.
-
- \note This function returns -1 if the given coordinate is not valid
- (has no row).
-
- \sa columnAt()
-*/
-int QTableView::rowAt(int y) const
-{
- Q_D(const QTableView);
- return d->verticalHeader->logicalIndexAt(y);
-}
-
-/*!
- \since 4.1
-
- Sets the height of the given \a row to be \a height.
-*/
-void QTableView::setRowHeight(int row, int height)
-{
- Q_D(const QTableView);
- d->verticalHeader->resizeSection(row, height);
-}
-
-/*!
- Returns the height of the given \a row.
-
- \sa resizeRowToContents(), columnWidth()
-*/
-int QTableView::rowHeight(int row) const
-{
- Q_D(const QTableView);
- return d->verticalHeader->sectionSize(row);
-}
-
-/*!
- Returns the x-coordinate in contents coordinates of the given \a
- column.
-*/
-int QTableView::columnViewportPosition(int column) const
-{
- Q_D(const QTableView);
- return d->horizontalHeader->sectionViewportPosition(column);
-}
-
-/*!
- Returns the column in which the given x-coordinate, \a x, in contents
- coordinates is located.
-
- \note This function returns -1 if the given coordinate is not valid
- (has no column).
-
- \sa rowAt()
-*/
-int QTableView::columnAt(int x) const
-{
- Q_D(const QTableView);
- return d->horizontalHeader->logicalIndexAt(x);
-}
-
-/*!
- \since 4.1
-
- Sets the width of the given \a column to be \a width.
-*/
-void QTableView::setColumnWidth(int column, int width)
-{
- Q_D(const QTableView);
- d->horizontalHeader->resizeSection(column, width);
-}
-
-/*!
- Returns the width of the given \a column.
-
- \sa resizeColumnToContents(), rowHeight()
-*/
-int QTableView::columnWidth(int column) const
-{
- Q_D(const QTableView);
- return d->horizontalHeader->sectionSize(column);
-}
-
-/*!
- Returns true if the given \a row is hidden; otherwise returns false.
-
- \sa isColumnHidden()
-*/
-bool QTableView::isRowHidden(int row) const
-{
- Q_D(const QTableView);
- return d->verticalHeader->isSectionHidden(row);
-}
-
-/*!
- If \a hide is true \a row will be hidden, otherwise it will be shown.
-
- \sa setColumnHidden()
-*/
-void QTableView::setRowHidden(int row, bool hide)
-{
- Q_D(QTableView);
- if (row < 0 || row >= d->verticalHeader->count())
- return;
- d->verticalHeader->setSectionHidden(row, hide);
-}
-
-/*!
- Returns true if the given \a column is hidden; otherwise returns false.
-
- \sa isRowHidden()
-*/
-bool QTableView::isColumnHidden(int column) const
-{
- Q_D(const QTableView);
- return d->horizontalHeader->isSectionHidden(column);
-}
-
-/*!
- If \a hide is true the given \a column will be hidden; otherwise it
- will be shown.
-
- \sa setRowHidden()
-*/
-void QTableView::setColumnHidden(int column, bool hide)
-{
- Q_D(QTableView);
- if (column < 0 || column >= d->horizontalHeader->count())
- return;
- d->horizontalHeader->setSectionHidden(column, hide);
-}
-
-/*!
- \since 4.2
- \property QTableView::sortingEnabled
- \brief whether sorting is enabled
-
- If this property is true, sorting is enabled for the table. If
- this property is false, sorting is not enabled. The default value
- is false.
-
- \note. Setting the property to true with setSortingEnabled()
- immediately triggers a call to sortByColumn() with the current
- sort section and order.
-
- \sa sortByColumn()
-*/
-
-/*!
- If \a enabled true enables sorting for the table and immediately
- trigger a call to sortByColumn() with the current sort section and
- order
- */
-void QTableView::setSortingEnabled(bool enable)
-{
- Q_D(QTableView);
- d->sortingEnabled = enable;
- horizontalHeader()->setSortIndicatorShown(enable);
- if (enable) {
- disconnect(d->horizontalHeader, SIGNAL(sectionEntered(int)),
- this, SLOT(_q_selectColumn(int)));
- disconnect(horizontalHeader(), SIGNAL(sectionPressed(int)),
- this, SLOT(selectColumn(int)));
- connect(horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(sortByColumn(int)), Qt::UniqueConnection);
- sortByColumn(horizontalHeader()->sortIndicatorSection(),
- horizontalHeader()->sortIndicatorOrder());
- } else {
- connect(d->horizontalHeader, SIGNAL(sectionEntered(int)),
- this, SLOT(_q_selectColumn(int)), Qt::UniqueConnection);
- connect(horizontalHeader(), SIGNAL(sectionPressed(int)),
- this, SLOT(selectColumn(int)), Qt::UniqueConnection);
- disconnect(horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(sortByColumn(int)));
- }
-}
-
-bool QTableView::isSortingEnabled() const
-{
- Q_D(const QTableView);
- return d->sortingEnabled;
-}
-
-/*!
- \property QTableView::showGrid
- \brief whether the grid is shown
-
- If this property is true a grid is drawn for the table; if the
- property is false, no grid is drawn. The default value is true.
-*/
-bool QTableView::showGrid() const
-{
- Q_D(const QTableView);
- return d->showGrid;
-}
-
-void QTableView::setShowGrid(bool show)
-{
- Q_D(QTableView);
- if (d->showGrid != show) {
- d->showGrid = show;
- d->viewport->update();
- }
-}
-
-/*!
- \property QTableView::gridStyle
- \brief the pen style used to draw the grid.
-
- This property holds the style used when drawing the grid (see \l{showGrid}).
-*/
-Qt::PenStyle QTableView::gridStyle() const
-{
- Q_D(const QTableView);
- return d->gridStyle;
-}
-
-void QTableView::setGridStyle(Qt::PenStyle style)
-{
- Q_D(QTableView);
- if (d->gridStyle != style) {
- d->gridStyle = style;
- d->viewport->update();
- }
-}
-
-/*!
- \property QTableView::wordWrap
- \brief the item text word-wrapping policy
- \since 4.3
-
- If this property is true then the item text is wrapped where
- necessary at word-breaks; otherwise it is not wrapped at all.
- This property is true by default.
-
- Note that even of wrapping is enabled, the cell will not be
- expanded to fit all text. Ellipsis will be inserted according to
- the current \l{QAbstractItemView::}{textElideMode}.
-
-*/
-void QTableView::setWordWrap(bool on)
-{
- Q_D(QTableView);
- if (d->wrapItemText == on)
- return;
- d->wrapItemText = on;
- QMetaObject::invokeMethod(d->verticalHeader, "resizeSections");
- QMetaObject::invokeMethod(d->horizontalHeader, "resizeSections");
-}
-
-bool QTableView::wordWrap() const
-{
- Q_D(const QTableView);
- return d->wrapItemText;
-}
-
-/*!
- \property QTableView::cornerButtonEnabled
- \brief whether the button in the top-left corner is enabled
- \since 4.3
-
- If this property is true then button in the top-left corner
- of the table view is enabled. Clicking on this button will
- select all the cells in the table view.
-
- This property is true by default.
-*/
-void QTableView::setCornerButtonEnabled(bool enable)
-{
- Q_D(QTableView);
- d->cornerWidget->setEnabled(enable);
-}
-
-bool QTableView::isCornerButtonEnabled() const
-{
- Q_D(const QTableView);
- return d->cornerWidget->isEnabled();
-}
-
-/*!
- \internal
-
- Returns the rectangle on the viewport occupied by the given \a
- index.
- If the index is hidden in the view it will return a null QRect.
-*/
-QRect QTableView::visualRect(const QModelIndex &index) const
-{
- Q_D(const QTableView);
- if (!d->isIndexValid(index) || index.parent() != d->root
- || (!d->hasSpans() && isIndexHidden(index)))
- return QRect();
-
- d->executePostedLayout();
-
- if (d->hasSpans()) {
- QSpanCollection::Span span = d->span(index.row(), index.column());
- return d->visualSpanRect(span);
- }
-
- int rowp = rowViewportPosition(index.row());
- int rowh = rowHeight(index.row());
- int colp = columnViewportPosition(index.column());
- int colw = columnWidth(index.column());
-
- const int i = showGrid() ? 1 : 0;
- return QRect(colp, rowp, colw - i, rowh - i);
-}
-
-/*!
- \internal
-
- Makes sure that the given \a item is visible in the table view,
- scrolling if necessary.
-*/
-void QTableView::scrollTo(const QModelIndex &index, ScrollHint hint)
-{
- Q_D(QTableView);
-
- // check if we really need to do anything
- if (!d->isIndexValid(index)
- || (d->model->parent(index) != d->root)
- || isRowHidden(index.row()) || isColumnHidden(index.column()))
- return;
-
- QSpanCollection::Span span;
- if (d->hasSpans())
- span = d->span(index.row(), index.column());
-
- // Adjust horizontal position
-
- int viewportWidth = d->viewport->width();
- int horizontalOffset = d->horizontalHeader->offset();
- int horizontalPosition = d->horizontalHeader->sectionPosition(index.column());
- int horizontalIndex = d->horizontalHeader->visualIndex(index.column());
- int cellWidth = d->hasSpans()
- ? d->columnSpanWidth(index.column(), span.width())
- : d->horizontalHeader->sectionSize(index.column());
-
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
-
- bool positionAtLeft = (horizontalPosition - horizontalOffset < 0);
- bool positionAtRight = (horizontalPosition - horizontalOffset + cellWidth > viewportWidth);
-
- if (hint == PositionAtCenter || positionAtRight) {
- int w = (hint == PositionAtCenter ? viewportWidth / 2 : viewportWidth);
- int x = cellWidth;
- while (horizontalIndex > 0) {
- x += columnWidth(d->horizontalHeader->logicalIndex(horizontalIndex-1));
- if (x > w)
- break;
- --horizontalIndex;
- }
- }
-
- if (positionAtRight || hint == PositionAtCenter || positionAtLeft) {
- int hiddenSections = 0;
- if (d->horizontalHeader->sectionsHidden()) {
- for (int s = horizontalIndex - 1; s >= 0; --s) {
- int column = d->horizontalHeader->logicalIndex(s);
- if (d->horizontalHeader->isSectionHidden(column))
- ++hiddenSections;
- }
- }
- horizontalScrollBar()->setValue(horizontalIndex - hiddenSections);
- }
-
- } else { // ScrollPerPixel
- if (hint == PositionAtCenter) {
- horizontalScrollBar()->setValue(horizontalPosition - ((viewportWidth - cellWidth) / 2));
- } else {
- if (horizontalPosition - horizontalOffset < 0 || cellWidth > viewportWidth)
- horizontalScrollBar()->setValue(horizontalPosition);
- else if (horizontalPosition - horizontalOffset + cellWidth > viewportWidth)
- horizontalScrollBar()->setValue(horizontalPosition - viewportWidth + cellWidth);
- }
- }
-
- // Adjust vertical position
-
- int viewportHeight = d->viewport->height();
- int verticalOffset = d->verticalHeader->offset();
- int verticalPosition = d->verticalHeader->sectionPosition(index.row());
- int verticalIndex = d->verticalHeader->visualIndex(index.row());
- int cellHeight = d->hasSpans()
- ? d->rowSpanHeight(index.row(), span.height())
- : d->verticalHeader->sectionSize(index.row());
-
- if (verticalPosition - verticalOffset < 0 || cellHeight > viewportHeight) {
- if (hint == EnsureVisible)
- hint = PositionAtTop;
- } else if (verticalPosition - verticalOffset + cellHeight > viewportHeight) {
- if (hint == EnsureVisible)
- hint = PositionAtBottom;
- }
-
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
-
- if (hint == PositionAtBottom || hint == PositionAtCenter) {
- int h = (hint == PositionAtCenter ? viewportHeight / 2 : viewportHeight);
- int y = cellHeight;
- while (verticalIndex > 0) {
- int row = d->verticalHeader->logicalIndex(verticalIndex - 1);
- y += d->verticalHeader->sectionSize(row);
- if (y > h)
- break;
- --verticalIndex;
- }
- }
-
- if (hint == PositionAtBottom || hint == PositionAtCenter || hint == PositionAtTop) {
- int hiddenSections = 0;
- if (d->verticalHeader->sectionsHidden()) {
- for (int s = verticalIndex - 1; s >= 0; --s) {
- int row = d->verticalHeader->logicalIndex(s);
- if (d->verticalHeader->isSectionHidden(row))
- ++hiddenSections;
- }
- }
- verticalScrollBar()->setValue(verticalIndex - hiddenSections);
- }
-
- } else { // ScrollPerPixel
- if (hint == PositionAtTop) {
- verticalScrollBar()->setValue(verticalPosition);
- } else if (hint == PositionAtBottom) {
- verticalScrollBar()->setValue(verticalPosition - viewportHeight + cellHeight);
- } else if (hint == PositionAtCenter) {
- verticalScrollBar()->setValue(verticalPosition - ((viewportHeight - cellHeight) / 2));
- }
- }
-
- update(index);
-}
-
-/*!
- This slot is called to change the height of the given \a row. The
- old height is specified by \a oldHeight, and the new height by \a
- newHeight.
-
- \sa columnResized()
-*/
-void QTableView::rowResized(int row, int, int)
-{
- Q_D(QTableView);
- d->rowsToUpdate.append(row);
- if (d->rowResizeTimerID == 0)
- d->rowResizeTimerID = startTimer(0);
-}
-
-/*!
- This slot is called to change the width of the given \a column.
- The old width is specified by \a oldWidth, and the new width by \a
- newWidth.
-
- \sa rowResized()
-*/
-void QTableView::columnResized(int column, int, int)
-{
- Q_D(QTableView);
- d->columnsToUpdate.append(column);
- if (d->columnResizeTimerID == 0)
- d->columnResizeTimerID = startTimer(0);
-}
-
-/*!
- \reimp
- */
-void QTableView::timerEvent(QTimerEvent *event)
-{
- Q_D(QTableView);
-
- if (event->timerId() == d->columnResizeTimerID) {
- updateGeometries();
- killTimer(d->columnResizeTimerID);
- d->columnResizeTimerID = 0;
-
- QRect rect;
- int viewportHeight = d->viewport->height();
- int viewportWidth = d->viewport->width();
- if (d->hasSpans()) {
- rect = QRect(0, 0, viewportWidth, viewportHeight);
- } else {
- for (int i = d->columnsToUpdate.size()-1; i >= 0; --i) {
- int column = d->columnsToUpdate.at(i);
- int x = columnViewportPosition(column);
- if (isRightToLeft())
- rect |= QRect(0, 0, x + columnWidth(column), viewportHeight);
- else
- rect |= QRect(x, 0, viewportWidth - x, viewportHeight);
- }
- }
-
- d->viewport->update(rect.normalized());
- d->columnsToUpdate.clear();
- }
-
- if (event->timerId() == d->rowResizeTimerID) {
- updateGeometries();
- killTimer(d->rowResizeTimerID);
- d->rowResizeTimerID = 0;
-
- int viewportHeight = d->viewport->height();
- int viewportWidth = d->viewport->width();
- int top;
- if (d->hasSpans()) {
- top = 0;
- } else {
- top = viewportHeight;
- for (int i = d->rowsToUpdate.size()-1; i >= 0; --i) {
- int y = rowViewportPosition(d->rowsToUpdate.at(i));
- top = qMin(top, y);
- }
- }
-
- d->viewport->update(QRect(0, top, viewportWidth, viewportHeight - top));
- d->rowsToUpdate.clear();
- }
-
- QAbstractItemView::timerEvent(event);
-}
-
-/*!
- This slot is called to change the index of the given \a row in the
- table view. The old index is specified by \a oldIndex, and the new
- index by \a newIndex.
-
- \sa columnMoved()
-*/
-void QTableView::rowMoved(int, int oldIndex, int newIndex)
-{
- Q_D(QTableView);
-
- updateGeometries();
- int logicalOldIndex = d->verticalHeader->logicalIndex(oldIndex);
- int logicalNewIndex = d->verticalHeader->logicalIndex(newIndex);
- if (d->hasSpans()) {
- d->viewport->update();
- } else {
- int oldTop = rowViewportPosition(logicalOldIndex);
- int newTop = rowViewportPosition(logicalNewIndex);
- int oldBottom = oldTop + rowHeight(logicalOldIndex);
- int newBottom = newTop + rowHeight(logicalNewIndex);
- int top = qMin(oldTop, newTop);
- int bottom = qMax(oldBottom, newBottom);
- int height = bottom - top;
- d->viewport->update(0, top, d->viewport->width(), height);
- }
-}
-
-/*!
- This slot is called to change the index of the given \a column in
- the table view. The old index is specified by \a oldIndex, and
- the new index by \a newIndex.
-
- \sa rowMoved()
-*/
-void QTableView::columnMoved(int, int oldIndex, int newIndex)
-{
- Q_D(QTableView);
-
- updateGeometries();
- int logicalOldIndex = d->horizontalHeader->logicalIndex(oldIndex);
- int logicalNewIndex = d->horizontalHeader->logicalIndex(newIndex);
- if (d->hasSpans()) {
- d->viewport->update();
- } else {
- int oldLeft = columnViewportPosition(logicalOldIndex);
- int newLeft = columnViewportPosition(logicalNewIndex);
- int oldRight = oldLeft + columnWidth(logicalOldIndex);
- int newRight = newLeft + columnWidth(logicalNewIndex);
- int left = qMin(oldLeft, newLeft);
- int right = qMax(oldRight, newRight);
- int width = right - left;
- d->viewport->update(left, 0, width, d->viewport->height());
- }
-}
-
-/*!
- Selects the given \a row in the table view if the current
- SelectionMode and SelectionBehavior allows rows to be selected.
-
- \sa selectColumn()
-*/
-void QTableView::selectRow(int row)
-{
- Q_D(QTableView);
- d->selectRow(row, true);
-}
-
-/*!
- Selects the given \a column in the table view if the current
- SelectionMode and SelectionBehavior allows columns to be selected.
-
- \sa selectRow()
-*/
-void QTableView::selectColumn(int column)
-{
- Q_D(QTableView);
- d->selectColumn(column, true);
-}
-
-/*!
- Hide the given \a row.
-
- \sa showRow() hideColumn()
-*/
-void QTableView::hideRow(int row)
-{
- Q_D(QTableView);
- d->verticalHeader->hideSection(row);
-}
-
-/*!
- Hide the given \a column.
-
- \sa showColumn() hideRow()
-*/
-void QTableView::hideColumn(int column)
-{
- Q_D(QTableView);
- d->horizontalHeader->hideSection(column);
-}
-
-/*!
- Show the given \a row.
-
- \sa hideRow() showColumn()
-*/
-void QTableView::showRow(int row)
-{
- Q_D(QTableView);
- d->verticalHeader->showSection(row);
-}
-
-/*!
- Show the given \a column.
-
- \sa hideColumn() showRow()
-*/
-void QTableView::showColumn(int column)
-{
- Q_D(QTableView);
- d->horizontalHeader->showSection(column);
-}
-
-/*!
- Resizes the given \a row based on the size hints of the delegate
- used to render each item in the row.
-*/
-void QTableView::resizeRowToContents(int row)
-{
- Q_D(QTableView);
- int content = sizeHintForRow(row);
- int header = d->verticalHeader->sectionSizeHint(row);
- d->verticalHeader->resizeSection(row, qMax(content, header));
-}
-
-/*!
- Resizes all rows based on the size hints of the delegate
- used to render each item in the rows.
-*/
-void QTableView::resizeRowsToContents()
-{
- Q_D(QTableView);
- d->verticalHeader->resizeSections(QHeaderView::ResizeToContents);
-}
-
-/*!
- Resizes the given \a column based on the size hints of the delegate
- used to render each item in the column.
-
- \note Only visible columns will be resized. Reimplement sizeHintForColumn()
- to resize hidden columns as well.
-*/
-void QTableView::resizeColumnToContents(int column)
-{
- Q_D(QTableView);
- int content = sizeHintForColumn(column);
- int header = d->horizontalHeader->sectionSizeHint(column);
- d->horizontalHeader->resizeSection(column, qMax(content, header));
-}
-
-/*!
- Resizes all columns based on the size hints of the delegate
- used to render each item in the columns.
-*/
-void QTableView::resizeColumnsToContents()
-{
- Q_D(QTableView);
- d->horizontalHeader->resizeSections(QHeaderView::ResizeToContents);
-}
-
-/*!
- \obsolete
- \overload
-
- Sorts the model by the values in the given \a column.
-*/
-void QTableView::sortByColumn(int column)
-{
- Q_D(QTableView);
- if (column == -1)
- return;
- d->model->sort(column, d->horizontalHeader->sortIndicatorOrder());
-}
-
-/*!
- \since 4.2
-
- Sorts the model by the values in the given \a column in the given \a order.
-
- \sa sortingEnabled
- */
-void QTableView::sortByColumn(int column, Qt::SortOrder order)
-{
- Q_D(QTableView);
- d->horizontalHeader->setSortIndicator(column, order);
- sortByColumn(column);
-}
-
-/*!
- \internal
-*/
-void QTableView::verticalScrollbarAction(int action)
-{
- QAbstractItemView::verticalScrollbarAction(action);
-}
-
-/*!
- \internal
-*/
-void QTableView::horizontalScrollbarAction(int action)
-{
- QAbstractItemView::horizontalScrollbarAction(action);
-}
-
-/*!
- \reimp
-*/
-bool QTableView::isIndexHidden(const QModelIndex &index) const
-{
- Q_D(const QTableView);
- Q_ASSERT(d->isIndexValid(index));
- if (isRowHidden(index.row()) || isColumnHidden(index.column()))
- return true;
- if (d->hasSpans()) {
- QSpanCollection::Span span = d->span(index.row(), index.column());
- return !((span.top() == index.row()) && (span.left() == index.column()));
- }
- return false;
-}
-
-/*!
- \fn void QTableView::setSpan(int row, int column, int rowSpanCount, int columnSpanCount)
- \since 4.2
-
- Sets the span of the table element at (\a row, \a column) to the number of
- rows and columns specified by (\a rowSpanCount, \a columnSpanCount).
-
- \sa rowSpan(), columnSpan()
-*/
-void QTableView::setSpan(int row, int column, int rowSpan, int columnSpan)
-{
- Q_D(QTableView);
- if (row < 0 || column < 0 || rowSpan < 0 || columnSpan < 0)
- return;
- d->setSpan(row, column, rowSpan, columnSpan);
- d->viewport->update();
-}
-
-/*!
- \since 4.2
-
- Returns the row span of the table element at (\a row, \a column).
- The default is 1.
-
- \sa setSpan(), columnSpan()
-*/
-int QTableView::rowSpan(int row, int column) const
-{
- Q_D(const QTableView);
- return d->rowSpan(row, column);
-}
-
-/*!
- \since 4.2
-
- Returns the column span of the table element at (\a row, \a
- column). The default is 1.
-
- \sa setSpan(), rowSpan()
-*/
-int QTableView::columnSpan(int row, int column) const
-{
- Q_D(const QTableView);
- return d->columnSpan(row, column);
-}
-
-/*!
- \since 4.4
-
- Removes all row and column spans in the table view.
-
- \sa setSpan()
-*/
-
-void QTableView::clearSpans()
-{
- Q_D(QTableView);
- d->spans.clear();
- d->viewport->update();
-}
-
-void QTableViewPrivate::_q_selectRow(int row)
-{
- selectRow(row, false);
-}
-
-void QTableViewPrivate::_q_selectColumn(int column)
-{
- selectColumn(column, false);
-}
-
-void QTableViewPrivate::selectRow(int row, bool anchor)
-{
- Q_Q(QTableView);
-
- if (q->selectionBehavior() == QTableView::SelectColumns
- || (q->selectionMode() == QTableView::SingleSelection
- && q->selectionBehavior() == QTableView::SelectItems))
- return;
-
- if (row >= 0 && row < model->rowCount(root)) {
- int column = horizontalHeader->logicalIndexAt(q->isRightToLeft() ? viewport->width() : 0);
- QModelIndex index = model->index(row, column, root);
- QItemSelectionModel::SelectionFlags command = q->selectionCommand(index);
- selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- if ((anchor && !(command & QItemSelectionModel::Current))
- || (q->selectionMode() == QTableView::SingleSelection))
- rowSectionAnchor = row;
-
- if (q->selectionMode() != QTableView::SingleSelection
- && command.testFlag(QItemSelectionModel::Toggle)) {
- if (anchor)
- ctrlDragSelectionFlag = verticalHeader->selectionModel()->selectedRows().contains(index)
- ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
- command &= ~QItemSelectionModel::Toggle;
- command |= ctrlDragSelectionFlag;
- if (!anchor)
- command |= QItemSelectionModel::Current;
- }
-
- QModelIndex tl = model->index(qMin(rowSectionAnchor, row), 0, root);
- QModelIndex br = model->index(qMax(rowSectionAnchor, row), model->columnCount(root) - 1, root);
- if (verticalHeader->sectionsMoved() && tl.row() != br.row())
- q->setSelection(q->visualRect(tl)|q->visualRect(br), command);
- else
- selectionModel->select(QItemSelection(tl, br), command);
- }
-}
-
-void QTableViewPrivate::selectColumn(int column, bool anchor)
-{
- Q_Q(QTableView);
-
- if (q->selectionBehavior() == QTableView::SelectRows
- || (q->selectionMode() == QTableView::SingleSelection
- && q->selectionBehavior() == QTableView::SelectItems))
- return;
-
- if (column >= 0 && column < model->columnCount(root)) {
- int row = verticalHeader->logicalIndexAt(0);
- QModelIndex index = model->index(row, column, root);
- QItemSelectionModel::SelectionFlags command = q->selectionCommand(index);
- selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- if ((anchor && !(command & QItemSelectionModel::Current))
- || (q->selectionMode() == QTableView::SingleSelection))
- columnSectionAnchor = column;
-
- if (q->selectionMode() != QTableView::SingleSelection
- && command.testFlag(QItemSelectionModel::Toggle)) {
- if (anchor)
- ctrlDragSelectionFlag = horizontalHeader->selectionModel()->selectedColumns().contains(index)
- ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
- command &= ~QItemSelectionModel::Toggle;
- command |= ctrlDragSelectionFlag;
- if (!anchor)
- command |= QItemSelectionModel::Current;
- }
-
- QModelIndex tl = model->index(0, qMin(columnSectionAnchor, column), root);
- QModelIndex br = model->index(model->rowCount(root) - 1,
- qMax(columnSectionAnchor, column), root);
- if (horizontalHeader->sectionsMoved() && tl.column() != br.column())
- q->setSelection(q->visualRect(tl)|q->visualRect(br), command);
- else
- selectionModel->select(QItemSelection(tl, br), command);
- }
-}
-
-/*!
- \reimp
- */
-void QTableView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
-{
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- if (current.isValid()) {
- int entry = visualIndex(current) + 1;
- if (horizontalHeader())
- ++entry;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::Focus);
- }
- }
-#endif
- QAbstractItemView::currentChanged(current, previous);
-}
-
-/*!
- \reimp
- */
-void QTableView::selectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected)
-{
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- // ### does not work properly for selection ranges.
- QModelIndex sel = selected.indexes().value(0);
- if (sel.isValid()) {
- int entry = visualIndex(sel);
- if (horizontalHeader())
- ++entry;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::Selection);
- }
- QModelIndex desel = deselected.indexes().value(0);
- if (desel.isValid()) {
- int entry = visualIndex(sel);
- if (horizontalHeader())
- ++entry;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::SelectionRemove);
- }
- }
-#endif
- QAbstractItemView::selectionChanged(selected, deselected);
-}
-
-int QTableView::visualIndex(const QModelIndex &index) const
-{
- return index.row();
-}
-
-QT_END_NAMESPACE
-
-#include "qtableview.moc"
-
-#include "moc_qtableview.cpp"
-
-#endif // QT_NO_TABLEVIEW
diff --git a/src/gui/itemviews/qtableview.h b/src/gui/itemviews/qtableview.h
deleted file mode 100644
index d4be0868c0..0000000000
--- a/src/gui/itemviews/qtableview.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABLEVIEW_H
-#define QTABLEVIEW_H
-
-#include <QtGui/qabstractitemview.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TABLEVIEW
-
-class QHeaderView;
-class QTableViewPrivate;
-
-class Q_GUI_EXPORT QTableView : public QAbstractItemView
-{
- Q_OBJECT
- Q_PROPERTY(bool showGrid READ showGrid WRITE setShowGrid)
- Q_PROPERTY(Qt::PenStyle gridStyle READ gridStyle WRITE setGridStyle)
- Q_PROPERTY(bool sortingEnabled READ isSortingEnabled WRITE setSortingEnabled)
- Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap)
- Q_PROPERTY(bool cornerButtonEnabled READ isCornerButtonEnabled WRITE setCornerButtonEnabled)
-
-public:
- explicit QTableView(QWidget *parent = 0);
- ~QTableView();
-
- void setModel(QAbstractItemModel *model);
- void setRootIndex(const QModelIndex &index);
- void setSelectionModel(QItemSelectionModel *selectionModel);
-
- QHeaderView *horizontalHeader() const;
- QHeaderView *verticalHeader() const;
- void setHorizontalHeader(QHeaderView *header);
- void setVerticalHeader(QHeaderView *header);
-
- int rowViewportPosition(int row) const;
- int rowAt(int y) const;
-
- void setRowHeight(int row, int height);
- int rowHeight(int row) const;
-
- int columnViewportPosition(int column) const;
- int columnAt(int x) const;
-
- void setColumnWidth(int column, int width);
- int columnWidth(int column) const;
-
- bool isRowHidden(int row) const;
- void setRowHidden(int row, bool hide);
-
- bool isColumnHidden(int column) const;
- void setColumnHidden(int column, bool hide);
-
- void setSortingEnabled(bool enable);
- bool isSortingEnabled() const;
-
- bool showGrid() const;
-
- Qt::PenStyle gridStyle() const;
- void setGridStyle(Qt::PenStyle style);
-
- void setWordWrap(bool on);
- bool wordWrap() const;
-
- void setCornerButtonEnabled(bool enable);
- bool isCornerButtonEnabled() const;
-
- QRect visualRect(const QModelIndex &index) const;
- void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible);
- QModelIndex indexAt(const QPoint &p) const;
-
- void setSpan(int row, int column, int rowSpan, int columnSpan);
- int rowSpan(int row, int column) const;
- int columnSpan(int row, int column) const;
- void clearSpans();
-
- void sortByColumn(int column, Qt::SortOrder order);
-
-public Q_SLOTS:
- void selectRow(int row);
- void selectColumn(int column);
- void hideRow(int row);
- void hideColumn(int column);
- void showRow(int row);
- void showColumn(int column);
- void resizeRowToContents(int row);
- void resizeRowsToContents();
- void resizeColumnToContents(int column);
- void resizeColumnsToContents();
- void sortByColumn(int column);
- void setShowGrid(bool show);
-
-protected Q_SLOTS:
- void rowMoved(int row, int oldIndex, int newIndex);
- void columnMoved(int column, int oldIndex, int newIndex);
- void rowResized(int row, int oldHeight, int newHeight);
- void columnResized(int column, int oldWidth, int newWidth);
- void rowCountChanged(int oldCount, int newCount);
- void columnCountChanged(int oldCount, int newCount);
-
-protected:
- QTableView(QTableViewPrivate &, QWidget *parent);
- void scrollContentsBy(int dx, int dy);
-
- QStyleOptionViewItem viewOptions() const;
- void paintEvent(QPaintEvent *e);
-
- void timerEvent(QTimerEvent *event);
-
- int horizontalOffset() const;
- int verticalOffset() const;
- QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
-
- void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command);
- QRegion visualRegionForSelection(const QItemSelection &selection) const;
- QModelIndexList selectedIndexes() const;
-
- void updateGeometries();
-
- int sizeHintForRow(int row) const;
- int sizeHintForColumn(int column) const;
-
- void verticalScrollbarAction(int action);
- void horizontalScrollbarAction(int action);
-
- bool isIndexHidden(const QModelIndex &index) const;
-
- void selectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected);
- void currentChanged(const QModelIndex &current,
- const QModelIndex &previous);
-
-private:
- friend class QAccessibleItemView;
- int visualIndex(const QModelIndex &index) const;
-
- Q_DECLARE_PRIVATE(QTableView)
- Q_DISABLE_COPY(QTableView)
- Q_PRIVATE_SLOT(d_func(), void _q_selectRow(int))
- Q_PRIVATE_SLOT(d_func(), void _q_selectColumn(int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanInsertedRows(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanInsertedColumns(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanRemovedRows(QModelIndex,int,int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateSpanRemovedColumns(QModelIndex,int,int))
-};
-
-#endif // QT_NO_TABLEVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTABLEVIEW_H
diff --git a/src/gui/itemviews/qtableview_p.h b/src/gui/itemviews/qtableview_p.h
deleted file mode 100644
index e3d2a8f4a6..0000000000
--- a/src/gui/itemviews/qtableview_p.h
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABLEVIEW_P_H
-#define QTABLEVIEW_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/QList>
-#include <QtCore/QLinkedList>
-#include <QtCore/QMap>
-#include <QtCore/QSet>
-#include <QtCore/QDebug>
-#include "private/qabstractitemview_p.h"
-
-#ifndef QT_NO_TABLEVIEW
-
-QT_BEGIN_NAMESPACE
-
-/** \internal
-*
-* This is a list of span with a binary index to look up quickly a span at a certain index.
-*
-* The index is a map of map.
-* spans are mentaly divided into sub spans so that the start of any subspans doesn't overlap
-* with any other subspans. There is no real representation of the subspans.
-* The key of the first map is the row where the subspan starts, the value of the first map is
-* a list (map) of all subspans that starts at the same row. It is indexed with its row
-*/
-class Q_AUTOTEST_EXPORT QSpanCollection
-{
-public:
- struct Span
- {
- int m_top;
- int m_left;
- int m_bottom;
- int m_right;
- bool will_be_deleted;
- Span()
- : m_top(-1), m_left(-1), m_bottom(-1), m_right(-1), will_be_deleted(false) { }
- Span(int row, int column, int rowCount, int columnCount)
- : m_top(row), m_left(column), m_bottom(row+rowCount-1), m_right(column+columnCount-1), will_be_deleted(false) { }
- inline int top() const { return m_top; }
- inline int left() const { return m_left; }
- inline int bottom() const { return m_bottom; }
- inline int right() const { return m_right; }
- inline int height() const { return m_bottom - m_top + 1; }
- inline int width() const { return m_right - m_left + 1; }
- };
-
- ~QSpanCollection()
- {
- qDeleteAll(spans);
- }
-
- void addSpan(Span *span);
- void updateSpan(Span *span, int old_height);
- Span *spanAt(int x, int y) const;
- void clear();
- QList<Span *> spansInRect(int x, int y, int w, int h) const;
-
- void updateInsertedRows(int start, int end);
- void updateInsertedColumns(int start, int end);
- void updateRemovedRows(int start, int end);
- void updateRemovedColumns(int start, int end);
-
-#ifdef QT_BUILD_INTERNAL
- bool checkConsistency() const;
-#endif
-
- typedef QLinkedList<Span *> SpanList;
- SpanList spans; //lists of all spans
-private:
- //the indexes are negative so the QMap::lowerBound do what i need.
- typedef QMap<int, Span *> SubIndex;
- typedef QMap<int, SubIndex> Index;
- Index index;
-
- bool cleanSpanSubIndex(SubIndex &subindex, int end, bool update = false);
-};
-
-Q_DECLARE_TYPEINFO ( QSpanCollection::Span, Q_MOVABLE_TYPE);
-
-
-class QTableViewPrivate : public QAbstractItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QTableView)
-public:
- QTableViewPrivate()
- : showGrid(true), gridStyle(Qt::SolidLine),
- rowSectionAnchor(-1), columnSectionAnchor(-1),
- columnResizeTimerID(0), rowResizeTimerID(0),
- horizontalHeader(0), verticalHeader(0),
- sortingEnabled(false), geometryRecursionBlock(false),
- visualCursor(QPoint())
- {
- wrapItemText = true;
-#ifndef QT_NO_DRAGANDDROP
- overwrite = true;
-#endif
- }
- void init();
- void trimHiddenSelections(QItemSelectionRange *range) const;
-
- inline bool isHidden(int row, int col) const {
- return verticalHeader->isSectionHidden(row)
- || horizontalHeader->isSectionHidden(col);
- }
- inline int visualRow(int logicalRow) const {
- return verticalHeader->visualIndex(logicalRow);
- }
- inline int visualColumn(int logicalCol) const {
- return horizontalHeader->visualIndex(logicalCol);
- }
- inline int logicalRow(int visualRow) const {
- return verticalHeader->logicalIndex(visualRow);
- }
- inline int logicalColumn(int visualCol) const {
- return horizontalHeader->logicalIndex(visualCol);
- }
-
- int sectionSpanEndLogical(const QHeaderView *header, int logical, int span) const;
- int sectionSpanSize(const QHeaderView *header, int logical, int span) const;
- bool spanContainsSection(const QHeaderView *header, int logical, int spanLogical, int span) const;
- void drawAndClipSpans(const QRegion &area, QPainter *painter,
- const QStyleOptionViewItemV4 &option, QBitArray *drawn,
- int firstVisualRow, int lastVisualRow, int firstVisualColumn, int lastVisualColumn);
- void drawCell(QPainter *painter, const QStyleOptionViewItemV4 &option, const QModelIndex &index);
-
- bool showGrid;
- Qt::PenStyle gridStyle;
- int rowSectionAnchor;
- int columnSectionAnchor;
- int columnResizeTimerID;
- int rowResizeTimerID;
- QList<int> columnsToUpdate;
- QList<int> rowsToUpdate;
- QHeaderView *horizontalHeader;
- QHeaderView *verticalHeader;
- QWidget *cornerWidget;
- bool sortingEnabled;
- bool geometryRecursionBlock;
- QPoint visualCursor; // (Row,column) cell coordinates to track through span navigation.
-
- QSpanCollection spans;
-
- void setSpan(int row, int column, int rowSpan, int columnSpan);
- QSpanCollection::Span span(int row, int column) const;
- inline int rowSpan(int row, int column) const {
- return span(row, column).height();
- }
- inline int columnSpan(int row, int column) const {
- return span(row, column).width();
- }
- inline bool hasSpans() const {
- return !spans.spans.isEmpty();
- }
- inline int rowSpanHeight(int row, int span) const {
- return sectionSpanSize(verticalHeader, row, span);
- }
- inline int columnSpanWidth(int column, int span) const {
- return sectionSpanSize(horizontalHeader, column, span);
- }
- inline int rowSpanEndLogical(int row, int span) const {
- return sectionSpanEndLogical(verticalHeader, row, span);
- }
- inline int columnSpanEndLogical(int column, int span) const {
- return sectionSpanEndLogical(horizontalHeader, column, span);
- }
-
- inline bool isRowHidden(int row) const {
- return verticalHeader->isSectionHidden(row);
- }
- inline bool isColumnHidden(int column) const {
- return horizontalHeader->isSectionHidden(column);
- }
- inline bool isCellEnabled(int row, int column) const {
- return isIndexEnabled(model->index(row, column, root));
- }
- inline bool isVisualRowHiddenOrDisabled(int row, int column) const {
- int r = logicalRow(row);
- int c = logicalColumn(column);
- return isRowHidden(r) || !isCellEnabled(r, c);
- }
- inline bool isVisualColumnHiddenOrDisabled(int row, int column) const {
- int r = logicalRow(row);
- int c = logicalColumn(column);
- return isColumnHidden(c) || !isCellEnabled(r, c);
- }
-
- QRect visualSpanRect(const QSpanCollection::Span &span) const;
-
- void _q_selectRow(int row);
- void _q_selectColumn(int column);
-
- void selectRow(int row, bool anchor);
- void selectColumn(int column, bool anchor);
-
- void _q_updateSpanInsertedRows(const QModelIndex &parent, int start, int end);
- void _q_updateSpanInsertedColumns(const QModelIndex &parent, int start, int end);
- void _q_updateSpanRemovedRows(const QModelIndex &parent, int start, int end);
- void _q_updateSpanRemovedColumns(const QModelIndex &parent, int start, int end);
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TABLEVIEW
-
-#endif // QTABLEVIEW_P_H
diff --git a/src/gui/itemviews/qtablewidget.cpp b/src/gui/itemviews/qtablewidget.cpp
deleted file mode 100644
index 3c5d22379a..0000000000
--- a/src/gui/itemviews/qtablewidget.cpp
+++ /dev/null
@@ -1,2685 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtablewidget.h"
-
-#ifndef QT_NO_TABLEWIDGET
-#include <qitemdelegate.h>
-#include <qpainter.h>
-#include <private/qtablewidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QTableModel::QTableModel(int rows, int columns, QTableWidget *parent)
- : QAbstractTableModel(parent),
- prototype(0),
- tableItems(rows * columns, 0),
- verticalHeaderItems(rows, 0),
- horizontalHeaderItems(columns, 0)
-{}
-
-QTableModel::~QTableModel()
-{
- clear();
- delete prototype;
-}
-
-bool QTableModel::insertRows(int row, int count, const QModelIndex &)
-{
- if (count < 1 || row < 0 || row > verticalHeaderItems.count())
- return false;
-
- beginInsertRows(QModelIndex(), row, row + count - 1);
- int rc = verticalHeaderItems.count();
- int cc = horizontalHeaderItems.count();
- verticalHeaderItems.insert(row, count, 0);
- if (rc == 0)
- tableItems.resize(cc * count);
- else
- tableItems.insert(tableIndex(row, 0), cc * count, 0);
- endInsertRows();
- return true;
-}
-
-bool QTableModel::insertColumns(int column, int count, const QModelIndex &)
-{
- if (count < 1 || column < 0 || column > horizontalHeaderItems.count())
- return false;
-
- beginInsertColumns(QModelIndex(), column, column + count - 1);
- int rc = verticalHeaderItems.count();
- int cc = horizontalHeaderItems.count();
- horizontalHeaderItems.insert(column, count, 0);
- if (cc == 0)
- tableItems.resize(rc * count);
- else
- for (int row = 0; row < rc; ++row)
- tableItems.insert(tableIndex(row, column), count, 0);
- endInsertColumns();
- return true;
-}
-
-bool QTableModel::removeRows(int row, int count, const QModelIndex &)
-{
- if (count < 1 || row < 0 || row + count > verticalHeaderItems.count())
- return false;
-
- beginRemoveRows(QModelIndex(), row, row + count - 1);
- int i = tableIndex(row, 0);
- int n = count * columnCount();
- QTableWidgetItem *oldItem = 0;
- for (int j = i; j < n + i; ++j) {
- oldItem = tableItems.at(j);
- if (oldItem)
- oldItem->view = 0;
- delete oldItem;
- }
- tableItems.remove(qMax(i, 0), n);
- for (int v = row; v < row + count; ++v) {
- oldItem = verticalHeaderItems.at(v);
- if (oldItem)
- oldItem->view = 0;
- delete oldItem;
- }
- verticalHeaderItems.remove(row, count);
- endRemoveRows();
- return true;
-}
-
-bool QTableModel::removeColumns(int column, int count, const QModelIndex &)
-{
- if (count < 1 || column < 0 || column + count > horizontalHeaderItems.count())
- return false;
-
- beginRemoveColumns(QModelIndex(), column, column + count - 1);
- QTableWidgetItem *oldItem = 0;
- for (int row = rowCount() - 1; row >= 0; --row) {
- int i = tableIndex(row, column);
- for (int j = i; j < i + count; ++j) {
- oldItem = tableItems.at(j);
- if (oldItem)
- oldItem->view = 0;
- delete oldItem;
- }
- tableItems.remove(i, count);
- }
- for (int h=column; h<column+count; ++h) {
- oldItem = horizontalHeaderItems.at(h);
- if (oldItem)
- oldItem->view = 0;
- delete oldItem;
- }
- horizontalHeaderItems.remove(column, count);
- endRemoveColumns();
- return true;
-}
-
-void QTableModel::setItem(int row, int column, QTableWidgetItem *item)
-{
- int i = tableIndex(row, column);
- if (i < 0 || i >= tableItems.count())
- return;
- QTableWidgetItem *oldItem = tableItems.at(i);
- if (item == oldItem)
- return;
-
- // remove old
- if (oldItem)
- oldItem->view = 0;
- delete tableItems.at(i);
-
- QTableWidget *view = qobject_cast<QTableWidget*>(QObject::parent());
-
- // set new
- if (item)
- item->d->id = i;
- tableItems[i] = item;
-
- if (view && view->isSortingEnabled()
- && view->horizontalHeader()->sortIndicatorSection() == column) {
- // sorted insertion
- Qt::SortOrder order = view->horizontalHeader()->sortIndicatorOrder();
- QVector<QTableWidgetItem*> colItems = columnItems(column);
- if (row < colItems.count())
- colItems.remove(row);
- int sortedRow;
- if (item == 0) {
- // move to after all non-0 (sortable) items
- sortedRow = colItems.count();
- } else {
- QVector<QTableWidgetItem*>::iterator it;
- it = sortedInsertionIterator(colItems.begin(), colItems.end(), order, item);
- sortedRow = qMax((int)(it - colItems.begin()), 0);
- }
- if (sortedRow != row) {
- emit layoutAboutToBeChanged();
- // move the items @ row to sortedRow
- int cc = columnCount();
- QVector<QTableWidgetItem*> rowItems(cc);
- for (int j = 0; j < cc; ++j)
- rowItems[j] = tableItems.at(tableIndex(row, j));
- tableItems.remove(tableIndex(row, 0), cc);
- tableItems.insert(tableIndex(sortedRow, 0), cc, 0);
- for (int j = 0; j < cc; ++j)
- tableItems[tableIndex(sortedRow, j)] = rowItems.at(j);
- QTableWidgetItem *header = verticalHeaderItems.at(row);
- verticalHeaderItems.remove(row);
- verticalHeaderItems.insert(sortedRow, header);
- // update persistent indexes
- QModelIndexList oldPersistentIndexes = persistentIndexList();
- QModelIndexList newPersistentIndexes = oldPersistentIndexes;
- updateRowIndexes(newPersistentIndexes, row, sortedRow);
- changePersistentIndexList(oldPersistentIndexes,
- newPersistentIndexes);
-
- emit layoutChanged();
- return;
- }
- }
- QModelIndex idx = QAbstractTableModel::index(row, column);
- emit dataChanged(idx, idx);
-}
-
-QTableWidgetItem *QTableModel::takeItem(int row, int column)
-{
- long i = tableIndex(row, column);
- QTableWidgetItem *itm = tableItems.value(i);
- if (itm) {
- itm->view = 0;
- itm->d->id = -1;
- tableItems[i] = 0;
- QModelIndex ind = index(itm);
- emit dataChanged(ind, ind);
- }
- return itm;
-}
-
-QTableWidgetItem *QTableModel::item(int row, int column) const
-{
- return tableItems.value(tableIndex(row, column));
-}
-
-QTableWidgetItem *QTableModel::item(const QModelIndex &index) const
-{
- if (!isValid(index))
- return 0;
- return tableItems.at(tableIndex(index.row(), index.column()));
-}
-
-void QTableModel::removeItem(QTableWidgetItem *item)
-{
- int i = tableItems.indexOf(item);
- if (i != -1) {
- tableItems[i] = 0;
- QModelIndex idx = index(item);
- emit dataChanged(idx, idx);
- return;
- }
-
- i = verticalHeaderItems.indexOf(item);
-
- if (i != -1) {
- verticalHeaderItems[i] = 0;
- emit headerDataChanged(Qt::Vertical, i, i);
- return;
- }
- i = horizontalHeaderItems.indexOf(item);
- if (i != -1) {
- horizontalHeaderItems[i] = 0;
- emit headerDataChanged(Qt::Horizontal, i, i);
- return;
- }
-}
-
-void QTableModel::setHorizontalHeaderItem(int section, QTableWidgetItem *item)
-{
- if (section < 0 || section >= horizontalHeaderItems.count())
- return;
- QTableWidgetItem *oldItem = horizontalHeaderItems.at(section);
- if (item == oldItem)
- return;
-
- if (oldItem)
- oldItem->view = 0;
- delete oldItem;
-
- QTableWidget *view = qobject_cast<QTableWidget*>(QObject::parent());
-
- if (item) {
- item->view = view;
- item->itemFlags = Qt::ItemFlags(int(item->itemFlags)|ItemIsHeaderItem);
- }
- horizontalHeaderItems[section] = item;
- emit headerDataChanged(Qt::Horizontal, section, section);
-}
-
-void QTableModel::setVerticalHeaderItem(int section, QTableWidgetItem *item)
-{
- if (section < 0 || section >= verticalHeaderItems.count())
- return;
- QTableWidgetItem *oldItem = verticalHeaderItems.at(section);
- if (item == oldItem)
- return;
-
- if (oldItem)
- oldItem->view = 0;
- delete oldItem;
-
- QTableWidget *view = qobject_cast<QTableWidget*>(QObject::parent());
-
- if (item) {
- item->view = view;
- item->itemFlags = Qt::ItemFlags(int(item->itemFlags)|ItemIsHeaderItem);
- }
- verticalHeaderItems[section] = item;
- emit headerDataChanged(Qt::Vertical, section, section);
-}
-
-QTableWidgetItem *QTableModel::takeHorizontalHeaderItem(int section)
-{
- if (section < 0 || section >= horizontalHeaderItems.count())
- return 0;
- QTableWidgetItem *itm = horizontalHeaderItems.at(section);
- if (itm) {
- itm->view = 0;
- itm->itemFlags &= ~ItemIsHeaderItem;
- horizontalHeaderItems[section] = 0;
- }
- return itm;
-}
-
-QTableWidgetItem *QTableModel::takeVerticalHeaderItem(int section)
-{
- if (section < 0 || section >= verticalHeaderItems.count())
- return 0;
- QTableWidgetItem *itm = verticalHeaderItems.at(section);
- if (itm) {
- itm->view = 0;
- itm->itemFlags &= ~ItemIsHeaderItem;
- verticalHeaderItems[section] = 0;
- }
- return itm;
-}
-
-QTableWidgetItem *QTableModel::horizontalHeaderItem(int section)
-{
- return horizontalHeaderItems.value(section);
-}
-
-QTableWidgetItem *QTableModel::verticalHeaderItem(int section)
-{
- return verticalHeaderItems.value(section);
-}
-
-QModelIndex QTableModel::index(const QTableWidgetItem *item) const
-{
- if (!item)
- return QModelIndex();
- int i = -1;
- const int id = item->d->id;
- if (id >= 0 && id < tableItems.count() && tableItems.at(id) == item) {
- i = id;
- } else { // we need to search for the item
- i = tableItems.indexOf(const_cast<QTableWidgetItem*>(item));
- if (i == -1) // not found
- return QModelIndex();
- }
- int row = i / columnCount();
- int col = i % columnCount();
- return QAbstractTableModel::index(row, col);
-}
-
-void QTableModel::setRowCount(int rows)
-{
- int rc = verticalHeaderItems.count();
- if (rows < 0 || rc == rows)
- return;
- if (rc < rows)
- insertRows(qMax(rc, 0), rows - rc);
- else
- removeRows(qMax(rows, 0), rc - rows);
-}
-
-void QTableModel::setColumnCount(int columns)
-{
- int cc = horizontalHeaderItems.count();
- if (columns < 0 || cc == columns)
- return;
- if (cc < columns)
- insertColumns(qMax(cc, 0), columns - cc);
- else
- removeColumns(qMax(columns, 0), cc - columns);
-}
-
-int QTableModel::rowCount(const QModelIndex &parent) const
-{
- return parent.isValid() ? 0 : verticalHeaderItems.count();
-}
-
-int QTableModel::columnCount(const QModelIndex &parent) const
-{
- return parent.isValid() ? 0 : horizontalHeaderItems.count();
-}
-
-QVariant QTableModel::data(const QModelIndex &index, int role) const
-{
- QTableWidgetItem *itm = item(index);
- if (itm)
- return itm->data(role);
- return QVariant();
-}
-
-bool QTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (!index.isValid())
- return false;
-
- QTableWidgetItem *itm = item(index);
- if (itm) {
- itm->setData(role, value);
- return true;
- }
-
- // don't create dummy table items for empty values
- if (!value.isValid())
- return false;
-
- QTableWidget *view = qobject_cast<QTableWidget*>(QObject::parent());
- if (!view)
- return false;
-
- itm = createItem();
- itm->setData(role, value);
- view->setItem(index.row(), index.column(), itm);
- return true;
-}
-
-QMap<int, QVariant> QTableModel::itemData(const QModelIndex &index) const
-{
- QMap<int, QVariant> roles;
- QTableWidgetItem *itm = item(index);
- if (itm) {
- for (int i = 0; i < itm->values.count(); ++i) {
- roles.insert(itm->values.at(i).role,
- itm->values.at(i).value);
- }
- }
- return roles;
-}
-
-// reimplemented to ensure that only one dataChanged() signal is emitted
-bool QTableModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles)
-{
- if (!index.isValid())
- return false;
-
- QTableWidget *view = qobject_cast<QTableWidget*>(QObject::parent());
- QTableWidgetItem *itm = item(index);
- if (itm) {
- itm->view = 0; // prohibits item from calling itemChanged()
- bool changed = false;
- for (QMap<int, QVariant>::ConstIterator it = roles.constBegin(); it != roles.constEnd(); ++it) {
- if (itm->data(it.key()) != it.value()) {
- itm->setData(it.key(), it.value());
- changed = true;
- }
- }
- itm->view = view;
- if (changed)
- itemChanged(itm);
- return true;
- }
-
- if (!view)
- return false;
-
- itm = createItem();
- for (QMap<int, QVariant>::ConstIterator it = roles.constBegin(); it != roles.constEnd(); ++it)
- itm->setData(it.key(), it.value());
- view->setItem(index.row(), index.column(), itm);
- return true;
-}
-
-Qt::ItemFlags QTableModel::flags(const QModelIndex &index) const
-{
- if (!index.isValid())
- return Qt::ItemIsDropEnabled;
- if (QTableWidgetItem *itm = item(index))
- return itm->flags();
- return (Qt::ItemIsEditable
- |Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled);
-}
-
-void QTableModel::sort(int column, Qt::SortOrder order)
-{
- QVector<QPair<QTableWidgetItem*, int> > sortable;
- QVector<int> unsortable;
-
- sortable.reserve(rowCount());
- unsortable.reserve(rowCount());
-
- for (int row = 0; row < rowCount(); ++row) {
- if (QTableWidgetItem *itm = item(row, column))
- sortable.append(QPair<QTableWidgetItem*,int>(itm, row));
- else
- unsortable.append(row);
- }
-
- LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- qStableSort(sortable.begin(), sortable.end(), compare);
-
- QVector<QTableWidgetItem*> sorted_table(tableItems.count());
- QModelIndexList from;
- QModelIndexList to;
- for (int i = 0; i < rowCount(); ++i) {
- int r = (i < sortable.count()
- ? sortable.at(i).second
- : unsortable.at(i - sortable.count()));
- for (int c = 0; c < columnCount(); ++c) {
- sorted_table[tableIndex(i, c)] = item(r, c);
- from.append(createIndex(r, c, 0));
- to.append(createIndex(i, c, 0));
- }
- }
-
- emit layoutAboutToBeChanged();
-
- tableItems = sorted_table;
- changePersistentIndexList(from, to); // ### slow
-
- emit layoutChanged();
-}
-
-/*
- \internal
-
- Ensures that rows in the interval [start, end] are
- sorted according to the contents of column \a column
- and the given sort \a order.
-*/
-void QTableModel::ensureSorted(int column, Qt::SortOrder order,
- int start, int end)
-{
- int count = end - start + 1;
- QVector < QPair<QTableWidgetItem*,int> > sorting;
- sorting.reserve(count);
- for (int row = start; row <= end; ++row) {
- QTableWidgetItem *itm = item(row, column);
- if (itm == 0) {
- // no more sortable items (all 0-items are
- // at the end of the table when it is sorted)
- break;
- }
- sorting.append(QPair<QTableWidgetItem*,int>(itm, row));
- }
-
- LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- qStableSort(sorting.begin(), sorting.end(), compare);
-
- QModelIndexList oldPersistentIndexes = persistentIndexList();
- QModelIndexList newPersistentIndexes = oldPersistentIndexes;
- QVector<QTableWidgetItem*> newTable = tableItems;
- QVector<QTableWidgetItem*> newVertical = verticalHeaderItems;
- QVector<QTableWidgetItem*> colItems = columnItems(column);
- QVector<QTableWidgetItem*>::iterator vit = colItems.begin();
- bool changed = false;
- for (int i = 0; i < sorting.count(); ++i) {
- int oldRow = sorting.at(i).second;
- QTableWidgetItem *item = colItems.at(oldRow);
- colItems.remove(oldRow);
- vit = sortedInsertionIterator(vit, colItems.end(), order, item);
- int newRow = qMax((int)(vit - colItems.begin()), 0);
- if ((newRow < oldRow) && !(*item < *colItems.at(oldRow - 1)) && !(*colItems.at(oldRow - 1) < *item))
- newRow = oldRow;
- vit = colItems.insert(vit, item);
- if (newRow != oldRow) {
- changed = true;
- // move the items @ oldRow to newRow
- int cc = columnCount();
- QVector<QTableWidgetItem*> rowItems(cc);
- for (int j = 0; j < cc; ++j)
- rowItems[j] = newTable.at(tableIndex(oldRow, j));
- newTable.remove(tableIndex(oldRow, 0), cc);
- newTable.insert(tableIndex(newRow, 0), cc, 0);
- for (int j = 0; j < cc; ++j)
- newTable[tableIndex(newRow, j)] = rowItems.at(j);
- QTableWidgetItem *header = newVertical.at(oldRow);
- newVertical.remove(oldRow);
- newVertical.insert(newRow, header);
- // update persistent indexes
- updateRowIndexes(newPersistentIndexes, oldRow, newRow);
- // the index of the remaining rows may have changed
- for (int j = i + 1; j < sorting.count(); ++j) {
- int otherRow = sorting.at(j).second;
- if (oldRow < otherRow && newRow >= otherRow)
- --sorting[j].second;
- else if (oldRow > otherRow && newRow <= otherRow)
- ++sorting[j].second;
- }
- }
- }
-
- if (changed) {
- emit layoutAboutToBeChanged();
- tableItems = newTable;
- verticalHeaderItems = newVertical;
- changePersistentIndexList(oldPersistentIndexes,
- newPersistentIndexes);
- emit layoutChanged();
- }
-}
-
-/*
- \internal
-
- Returns the non-0 items in column \a column.
-*/
-QVector<QTableWidgetItem*> QTableModel::columnItems(int column) const
-{
- QVector<QTableWidgetItem*> items;
- int rc = rowCount();
- items.reserve(rc);
- for (int row = 0; row < rc; ++row) {
- QTableWidgetItem *itm = item(row, column);
- if (itm == 0) {
- // no more sortable items (all 0-items are
- // at the end of the table when it is sorted)
- break;
- }
- items.append(itm);
- }
- return items;
-}
-
-/*
- \internal
-
- Adjusts the row of each index in \a indexes if necessary, given
- that a row of items has been moved from row \a movedFrom to row
- \a movedTo.
-*/
-void QTableModel::updateRowIndexes(QModelIndexList &indexes,
- int movedFromRow, int movedToRow)
-{
- QModelIndexList::iterator it;
- for (it = indexes.begin(); it != indexes.end(); ++it) {
- int oldRow = (*it).row();
- int newRow = oldRow;
- if (oldRow == movedFromRow)
- newRow = movedToRow;
- else if (movedFromRow < oldRow && movedToRow >= oldRow)
- newRow = oldRow - 1;
- else if (movedFromRow > oldRow && movedToRow <= oldRow)
- newRow = oldRow + 1;
- if (newRow != oldRow)
- *it = index(newRow, (*it).column(), (*it).parent());
- }
-}
-
-/*
- \internal
-
- Returns an iterator to the item where \a item should be
- inserted in the interval (\a begin, \a end) according to
- the given sort \a order.
-*/
-QVector<QTableWidgetItem*>::iterator QTableModel::sortedInsertionIterator(
- const QVector<QTableWidgetItem*>::iterator &begin,
- const QVector<QTableWidgetItem*>::iterator &end,
- Qt::SortOrder order, QTableWidgetItem *item)
-{
- if (order == Qt::AscendingOrder)
- return qLowerBound(begin, end, item, QTableModelLessThan());
- return qLowerBound(begin, end, item, QTableModelGreaterThan());
-}
-
-bool QTableModel::itemLessThan(const QPair<QTableWidgetItem*,int> &left,
- const QPair<QTableWidgetItem*,int> &right)
-{
- return *(left.first) < *(right.first);
-}
-
-bool QTableModel::itemGreaterThan(const QPair<QTableWidgetItem*,int> &left,
- const QPair<QTableWidgetItem*,int> &right)
-{
- return (*(right.first) < *(left .first));
-}
-
-QVariant QTableModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (section < 0)
- return QVariant();
-
- QTableWidgetItem *itm = 0;
- if (orientation == Qt::Horizontal && section < horizontalHeaderItems.count())
- itm = horizontalHeaderItems.at(section);
- else if (orientation == Qt::Vertical && section < verticalHeaderItems.count())
- itm = verticalHeaderItems.at(section);
- else
- return QVariant(); // section is out of bounds
-
- if (itm)
- return itm->data(role);
- if (role == Qt::DisplayRole)
- return section + 1;
- return QVariant();
-}
-
-bool QTableModel::setHeaderData(int section, Qt::Orientation orientation,
- const QVariant &value, int role)
-{
- if (section < 0 ||
- (orientation == Qt::Horizontal && horizontalHeaderItems.size() <= section) ||
- (orientation == Qt::Vertical && verticalHeaderItems.size() <= section))
- return false;
-
- QTableWidgetItem *itm = 0;
- if (orientation == Qt::Horizontal)
- itm = horizontalHeaderItems.at(section);
- else
- itm = verticalHeaderItems.at(section);
- if (itm) {
- itm->setData(role, value);
- return true;
- }
- return false;
-}
-
-bool QTableModel::isValid(const QModelIndex &index) const
-{
- return (index.isValid()
- && index.row() < verticalHeaderItems.count()
- && index.column() < horizontalHeaderItems.count());
-}
-
-void QTableModel::clear()
-{
- for (int j = 0; j < verticalHeaderItems.count(); ++j) {
- if (verticalHeaderItems.at(j)) {
- verticalHeaderItems.at(j)->view = 0;
- delete verticalHeaderItems.at(j);
- verticalHeaderItems[j] = 0;
- }
- }
- for (int k = 0; k < horizontalHeaderItems.count(); ++k) {
- if (horizontalHeaderItems.at(k)) {
- horizontalHeaderItems.at(k)->view = 0;
- delete horizontalHeaderItems.at(k);
- horizontalHeaderItems[k] = 0;
- }
- }
- clearContents();
-}
-
-void QTableModel::clearContents()
-{
- for (int i = 0; i < tableItems.count(); ++i) {
- if (tableItems.at(i)) {
- tableItems.at(i)->view = 0;
- delete tableItems.at(i);
- tableItems[i] = 0;
- }
- }
- reset();
-}
-
-void QTableModel::itemChanged(QTableWidgetItem *item)
-{
- if (!item)
- return;
- if (item->flags() & ItemIsHeaderItem) {
- int row = verticalHeaderItems.indexOf(item);
- if (row >= 0) {
- emit headerDataChanged(Qt::Vertical, row, row);
- } else {
- int column = horizontalHeaderItems.indexOf(item);
- if (column >= 0)
- emit headerDataChanged(Qt::Horizontal, column, column);
- }
- } else {
- QModelIndex idx = index(item);
- if (idx.isValid())
- emit dataChanged(idx, idx);
- }
-}
-
-QTableWidgetItem* QTableModel::createItem() const
-{
- return prototype ? prototype->clone() : new QTableWidgetItem;
-}
-
-const QTableWidgetItem *QTableModel::itemPrototype() const
-{
- return prototype;
-}
-
-void QTableModel::setItemPrototype(const QTableWidgetItem *item)
-{
- if (prototype != item) {
- delete prototype;
- prototype = item;
- }
-}
-
-QStringList QTableModel::mimeTypes() const
-{
- const QTableWidget *view = qobject_cast<const QTableWidget*>(QObject::parent());
- return (view ? view->mimeTypes() : QStringList());
-}
-
-QMimeData *QTableModel::internalMimeData() const
-{
- return QAbstractTableModel::mimeData(cachedIndexes);
-}
-
-QMimeData *QTableModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QTableWidgetItem*> items;
- for (int i = 0; i < indexes.count(); ++i)
- items << item(indexes.at(i));
- const QTableWidget *view = qobject_cast<const QTableWidget*>(QObject::parent());
-
- // cachedIndexes is a little hack to avoid copying from QModelIndexList to
- // QList<QTreeWidgetItem*> and back again in the view
- cachedIndexes = indexes;
- QMimeData *mimeData = (view ? view->mimeData(items) : 0);
- cachedIndexes.clear();
- return mimeData;
-}
-
-bool QTableModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row , int column, const QModelIndex &index)
-{
- if (index.isValid()) {
- row = index.row();
- column = index.column();
- }else if (row == -1 || column == -1) { // The user dropped outside the table.
- row = rowCount();
- column = 0;
- }
-
- QTableWidget *view = qobject_cast<QTableWidget*>(QObject::parent());
- return (view ? view->dropMimeData(row, column, data, action) : false);
-}
-
-Qt::DropActions QTableModel::supportedDropActions() const
-{
- const QTableWidget *view = qobject_cast<const QTableWidget*>(QObject::parent());
- return (view ? view->supportedDropActions() : Qt::DropActions(Qt::IgnoreAction));
-}
-
-/*!
- \class QTableWidgetSelectionRange
-
- \brief The QTableWidgetSelectionRange class provides a way to interact with
- selection in a model without using model indexes and a selection model.
-
- \ingroup model-view
-
- The QTableWidgetSelectionRange class stores the top left and bottom
- right rows and columns of a selection range in a table. The
- selections in the table may consist of several selection ranges.
-
- \note If the item within the selection range is marked as not selectable,
- e.g., \c{itemFlags() & Qt::ItemIsSelectable == 0} then it will not appear
- in the selection range.
-
- \sa QTableWidget
-*/
-
-/*!
- Constructs an table selection range, i.e. a range
- whose rowCount() and columnCount() are 0.
-*/
-QTableWidgetSelectionRange::QTableWidgetSelectionRange()
- : top(-1), left(-1), bottom(-2), right(-2)
-{
-}
-
-/*!
- Constructs the table selection range from the given \a top, \a
- left, \a bottom and \a right table rows and columns.
-
- \sa topRow(), leftColumn(), bottomRow(), rightColumn()
-*/
-QTableWidgetSelectionRange::QTableWidgetSelectionRange(int top, int left, int bottom, int right)
- : top(top), left(left), bottom(bottom), right(right)
-{
-}
-
-/*!
- Constructs a the table selection range by copying the given \a
- other table selection range.
-*/
-QTableWidgetSelectionRange::QTableWidgetSelectionRange(const QTableWidgetSelectionRange &other)
- : top(other.top), left(other.left), bottom(other.bottom), right(other.right)
-{
-}
-
-/*!
- Destroys the table selection range.
-*/
-QTableWidgetSelectionRange::~QTableWidgetSelectionRange()
-{
-}
-
-/*!
- \fn int QTableWidgetSelectionRange::topRow() const
-
- Returns the top row of the range.
-
- \sa bottomRow(), leftColumn(), rowCount()
-*/
-
-/*!
- \fn int QTableWidgetSelectionRange::bottomRow() const
-
- Returns the bottom row of the range.
-
- \sa topRow(), rightColumn(), rowCount()
-*/
-
-/*!
- \fn int QTableWidgetSelectionRange::leftColumn() const
-
- Returns the left column of the range.
-
- \sa rightColumn(), topRow(), columnCount()
-*/
-
-/*!
- \fn int QTableWidgetSelectionRange::rightColumn() const
-
- Returns the right column of the range.
-
- \sa leftColumn(), bottomRow(), columnCount()
-*/
-
-/*!
- \since 4.1
- \fn int QTableWidgetSelectionRange::rowCount() const
-
- Returns the number of rows in the range.
-
- This is equivalent to bottomRow() - topRow() + 1.
-
- \sa columnCount(), topRow(), bottomRow()
-*/
-
-/*!
- \since 4.1
- \fn int QTableWidgetSelectionRange::columnCount() const
-
- Returns the number of columns in the range.
-
- This is equivalent to rightColumn() - leftColumn() + 1.
-
- \sa rowCount(), leftColumn(), rightColumn()
-*/
-
-/*!
- \class QTableWidgetItem
- \brief The QTableWidgetItem class provides an item for use with the
- QTableWidget class.
-
- \ingroup model-view
-
- Table items are used to hold pieces of information for table widgets.
- Items usually contain text, icons, or checkboxes
-
- The QTableWidgetItem class is a convenience class that replaces the
- \c QTableItem class in Qt 3. It provides an item for use with
- the QTableWidget class.
-
- Top-level items are constructed without a parent then inserted at the
- position specified by a pair of row and column numbers:
-
- \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 3
-
- Each item can have its own background brush which is set with
- the setBackground() function. The current background brush can be
- found with background().
- The text label for each item can be rendered with its own font and brush.
- These are specified with the setFont() and setForeground() functions,
- and read with font() and foreground().
-
- By default, items are enabled, editable, selectable, checkable, and can be
- used both as the source of a drag and drop operation and as a drop target.
- Each item's flags can be changed by calling setFlags() with the appropriate
- value (see \l{Qt::ItemFlags}). Checkable items can be checked and unchecked
- with the setCheckState() function. The corresponding checkState() function
- indicates whether the item is currently checked.
-
- \section1 Subclassing
-
- When subclassing QTableWidgetItem to provide custom items, it is possible to
- define new types for them so that they can be distinguished from standard
- items. The constructors for subclasses that require this feature need to
- call the base class constructor with a new type value equal to or greater
- than \l UserType.
-
- \sa QTableWidget, {Model/View Programming}, QListWidgetItem, QTreeWidgetItem
-*/
-
-/*!
- \fn int QTableWidgetItem::row() const
- \since 4.2
-
- Returns the row of the item in the table.
- If the item is not in a table, this function will return -1.
-
- \sa column()
-*/
-
-/*!
- \fn int QTableWidgetItem::column() const
- \since 4.2
-
- Returns the column of the item in the table.
- If the item is not in a table, this function will return -1.
-
- \sa row()
-*/
-
-/*!
- \fn void QTableWidgetItem::setSelected(bool select)
- \since 4.2
-
- Sets the selected state of the item to \a select.
-
- \sa isSelected()
-*/
-
-/*!
- \fn bool QTableWidgetItem::isSelected() const
- \since 4.2
-
- Returns true if the item is selected, otherwise returns false.
-
- \sa setSelected()
-*/
-
-/*!
- \fn QSize QTableWidgetItem::sizeHint() const
- \since 4.1
-
- Returns the size hint set for the table item.
-*/
-
-/*!
- \fn void QTableWidgetItem::setSizeHint(const QSize &size)
- \since 4.1
-
- Sets the size hint for the table item to be \a size.
- If no size hint is set, the item delegate will compute the
- size hint based on the item data.
-*/
-
-/*!
- \fn Qt::CheckState QTableWidgetItem::checkState() const
-
- Returns the checked state of the table item.
-
- \sa flags()
-*/
-
-/*!
- \fn void QTableWidgetItem::setCheckState(Qt::CheckState state)
-
- Sets the check state of the table item to be \a state.
-*/
-
-/*!
- \fn QTableWidget *QTableWidgetItem::tableWidget() const
-
- Returns the table widget that contains the item.
-*/
-
-/*!
- \fn Qt::ItemFlags QTableWidgetItem::flags() const
-
- Returns the flags used to describe the item. These determine whether
- the item can be checked, edited, and selected.
-
- \sa setFlags()
-*/
-
-/*!
- \fn void QTableWidgetItem::setFlags(Qt::ItemFlags flags)
-
- Sets the flags for the item to the given \a flags. These determine whether
- the item can be selected or modified.
-
- \sa flags()
-*/
-void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
-{
- itemFlags = aflags;
- if (QTableModel *model = (view ? qobject_cast<QTableModel*>(view->model()) : 0))
- model->itemChanged(this);
-}
-
-
-/*!
- \fn QString QTableWidgetItem::text() const
-
- Returns the item's text.
-
- \sa setText()
-*/
-
-/*!
- \fn void QTableWidgetItem::setText(const QString &text)
-
- Sets the item's text to the \a text specified.
-
- \sa text() setFont() setForeground()
-*/
-
-/*!
- \fn QIcon QTableWidgetItem::icon() const
-
- Returns the item's icon.
-
- \sa setIcon(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn void QTableWidgetItem::setIcon(const QIcon &icon)
-
- Sets the item's icon to the \a icon specified.
-
- \sa icon(), setText(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn QString QTableWidgetItem::statusTip() const
-
- Returns the item's status tip.
-
- \sa setStatusTip()
-*/
-
-/*!
- \fn void QTableWidgetItem::setStatusTip(const QString &statusTip)
-
- Sets the status tip for the table item to the text specified by
- \a statusTip. QTableWidget mouse tracking needs to be enabled for this
- feature to work.
-
- \sa statusTip() setToolTip() setWhatsThis()
-*/
-
-/*!
- \fn QString QTableWidgetItem::toolTip() const
-
- Returns the item's tooltip.
-
- \sa setToolTip()
-*/
-
-/*!
- \fn void QTableWidgetItem::setToolTip(const QString &toolTip)
-
- Sets the item's tooltip to the string specified by \a toolTip.
-
- \sa toolTip() setStatusTip() setWhatsThis()
-*/
-
-/*!
- \fn QString QTableWidgetItem::whatsThis() const
-
- Returns the item's "What's This?" help.
-
- \sa setWhatsThis()
-*/
-
-/*!
- \fn void QTableWidgetItem::setWhatsThis(const QString &whatsThis)
-
- Sets the item's "What's This?" help to the string specified by \a whatsThis.
-
- \sa whatsThis() setStatusTip() setToolTip()
-*/
-
-/*!
- \fn QFont QTableWidgetItem::font() const
-
- Returns the font used to render the item's text.
-
- \sa setFont()
-*/
-
-/*!
- \fn void QTableWidgetItem::setFont(const QFont &font)
-
- Sets the font used to display the item's text to the given \a font.
-
- \sa font() setText() setForeground()
-*/
-
-/*!
- \fn QColor QTableWidgetItem::backgroundColor() const
- \obsolete
-
- This function is deprecated. Use background() instead.
-*/
-
-/*!
- \fn void QTableWidgetItem::setBackgroundColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setBackground() instead.
-*/
-
-/*!
- \fn QBrush QTableWidgetItem::background() const
- \since 4.2
-
- Returns the brush used to render the item's background.
-
- \sa foreground()
-*/
-
-/*!
- \fn void QTableWidgetItem::setBackground(const QBrush &brush)
- \since 4.2
-
- Sets the item's background brush to the specified \a brush.
-
- \sa setForeground()
-*/
-
-/*!
- \fn QColor QTableWidgetItem::textColor() const
- \obsolete
-
- This function is deprecated. Use foreground() instead.
-*/
-
-/*!
- \fn void QTableWidgetItem::setTextColor(const QColor &color)
- \obsolete
-
- This function is deprecated. Use setForeground() instead.
-*/
-
-/*!
- \fn QBrush QTableWidgetItem::foreground() const
- \since 4.2
-
- Returns the brush used to render the item's foreground (e.g. text).
-
- \sa background()
-*/
-
-/*!
- \fn void QTableWidgetItem::setForeground(const QBrush &brush)
- \since 4.2
-
- Sets the item's foreground brush to the specified \a brush.
-
- \sa setBackground()
-*/
-
-/*!
- \fn int QTableWidgetItem::textAlignment() const
-
- Returns the text alignment for the item's text.
-
- \sa Qt::Alignment
-*/
-
-/*!
- \fn void QTableWidgetItem::setTextAlignment(int alignment)
-
- Sets the text alignment for the item's text to the \a alignment
- specified.
-
- \sa Qt::Alignment
-*/
-
-/*!
- Constructs a table item of the specified \a type that does not belong
- to any table.
-
- \sa type()
-*/
-QTableWidgetItem::QTableWidgetItem(int type)
- : rtti(type), view(0), d(new QTableWidgetItemPrivate(this)),
- itemFlags(Qt::ItemIsEditable
- |Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
-}
-
-/*!
- Constructs a table item with the given \a text.
-
- \sa type()
-*/
-QTableWidgetItem::QTableWidgetItem(const QString &text, int type)
- : rtti(type), view(0), d(new QTableWidgetItemPrivate(this)),
- itemFlags(Qt::ItemIsEditable
- |Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- setData(Qt::DisplayRole, text);
-}
-
-/*!
- Constructs a table item with the given \a icon and \a text.
-
- \sa type()
-*/
-QTableWidgetItem::QTableWidgetItem(const QIcon &icon, const QString &text, int type)
- : rtti(type), view(0), d(new QTableWidgetItemPrivate(this)),
- itemFlags(Qt::ItemIsEditable
- |Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- setData(Qt::DecorationRole, icon);
- setData(Qt::DisplayRole, text);
-}
-
-/*!
- Destroys the table item.
-*/
-QTableWidgetItem::~QTableWidgetItem()
-{
- if (QTableModel *model = (view ? qobject_cast<QTableModel*>(view->model()) : 0))
- model->removeItem(this);
- view = 0;
- delete d;
-}
-
-/*!
- Creates a copy of the item.
-*/
-QTableWidgetItem *QTableWidgetItem::clone() const
-{
- return new QTableWidgetItem(*this);
-}
-
-/*!
- Sets the item's data for the given \a role to the specified \a value.
-
- \sa Qt::ItemDataRole, data()
-*/
-void QTableWidgetItem::setData(int role, const QVariant &value)
-{
- bool found = false;
- role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < values.count(); ++i) {
- if (values.at(i).role == role) {
- if (values[i].value == value)
- return;
-
- values[i].value = value;
- found = true;
- break;
- }
- }
- if (!found)
- values.append(QWidgetItemData(role, value));
- if (QTableModel *model = (view ? qobject_cast<QTableModel*>(view->model()) : 0))
- model->itemChanged(this);
-}
-
-/*!
- Returns the item's data for the given \a role.
-*/
-QVariant QTableWidgetItem::data(int role) const
-{
- role = (role == Qt::EditRole ? Qt::DisplayRole : role);
- for (int i = 0; i < values.count(); ++i)
- if (values.at(i).role == role)
- return values.at(i).value;
- return QVariant();
-}
-
-/*!
- Returns true if the item is less than the \a other item; otherwise returns
- false.
-*/
-bool QTableWidgetItem::operator<(const QTableWidgetItem &other) const
-{
- const QVariant v1 = data(Qt::DisplayRole), v2 = other.data(Qt::DisplayRole);
- return QAbstractItemModelPrivate::variantLessThan(v1, v2);
-}
-
-#ifndef QT_NO_DATASTREAM
-
-/*!
- Reads the item from stream \a in.
-
- \sa write()
-*/
-void QTableWidgetItem::read(QDataStream &in)
-{
- in >> values;
-}
-
-/*!
- Writes the item to stream \a out.
-
- \sa read()
-*/
-void QTableWidgetItem::write(QDataStream &out) const
-{
- out << values;
-}
-
-/*!
- \relates QTableWidgetItem
-
- Reads a table widget item from stream \a in into \a item.
-
- This operator uses QTableWidgetItem::read().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator>>(QDataStream &in, QTableWidgetItem &item)
-{
- item.read(in);
- return in;
-}
-
-/*!
- \relates QTableWidgetItem
-
- Writes the table widget item \a item to stream \a out.
-
- This operator uses QTableWidgetItem::write().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator<<(QDataStream &out, const QTableWidgetItem &item)
-{
- item.write(out);
- return out;
-}
-
-#endif // QT_NO_DATASTREAM
-
-/*!
- \since 4.1
-
- Constructs a copy of \a other. Note that type() and tableWidget()
- are not copied.
-
- This function is useful when reimplementing clone().
-
- \sa data(), flags()
-*/
-QTableWidgetItem::QTableWidgetItem(const QTableWidgetItem &other)
- : rtti(Type), values(other.values), view(0),
- d(new QTableWidgetItemPrivate(this)),
- itemFlags(other.itemFlags)
-{
-}
-
-/*!
- Assigns \a other's data and flags to this item. Note that type()
- and tableWidget() are not copied.
-
- This function is useful when reimplementing clone().
-
- \sa data(), flags()
-*/
-QTableWidgetItem &QTableWidgetItem::operator=(const QTableWidgetItem &other)
-{
- values = other.values;
- itemFlags = other.itemFlags;
- return *this;
-}
-
-/*!
- \class QTableWidget
- \brief The QTableWidget class provides an item-based table view with a default model.
-
- \ingroup model-view
-
-
- Table widgets provide standard table display facilities for applications.
- The items in a QTableWidget are provided by QTableWidgetItem.
-
- If you want a table that uses your own data model you should
- use QTableView rather than this class.
-
- Table widgets can be constructed with the required numbers of rows and
- columns:
-
- \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 0
-
- Alternatively, tables can be constructed without a given size and resized
- later:
-
- \snippet doc/src/snippets/qtablewidget-resizing/mainwindow.cpp 0
- \snippet doc/src/snippets/qtablewidget-resizing/mainwindow.cpp 1
-
- Items are created ouside the table (with no parent widget) and inserted
- into the table with setItem():
-
- \snippet doc/src/snippets/qtablewidget-resizing/mainwindow.cpp 2
-
- If you want to enable sorting in your table widget, do so after you
- have populated it with items, otherwise sorting may interfere with
- the insertion order (see setItem() for details).
-
- Tables can be given both horizontal and vertical headers. The simplest way
- to create the headers is to supply a list of strings to the
- setHorizontalHeaderLabels() and setVerticalHeaderLabels() functions. These
- will provide simple textual headers for the table's columns and rows.
- More sophisticated headers can be created from existing table items
- that are usually constructed outside the table. For example, we can
- construct a table item with an icon and aligned text, and use it as the
- header for a particular column:
-
- \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 2
-
- The number of rows in the table can be found with rowCount(), and the
- number of columns with columnCount(). The table can be cleared with the
- clear() function.
-
- \table 100%
- \row \o \inlineimage windowsxp-tableview.png Screenshot of a Windows XP style table widget
- \o \inlineimage macintosh-tableview.png Screenshot of a Macintosh style table widget
- \o \inlineimage plastique-tableview.png Screenshot of a Plastique style table widget
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} table widget.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} table widget.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} table widget.
- \endtable
-
- \sa QTableWidgetItem, QTableView, {Model/View Programming}
-*/
-
-/*!
- \property QTableWidget::rowCount
- \brief the number of rows in the table
-
- By default, for a table constructed without row and column counts,
- this property contains a value of 0.
-*/
-
-/*!
- \property QTableWidget::columnCount
- \brief the number of columns in the table
-
- By default, for a table constructed without row and column counts,
- this property contains a value of 0.
-*/
-
-void QTableWidgetPrivate::setup()
-{
- Q_Q(QTableWidget);
- // view signals
- QObject::connect(q, SIGNAL(pressed(QModelIndex)), q, SLOT(_q_emitItemPressed(QModelIndex)));
- QObject::connect(q, SIGNAL(clicked(QModelIndex)), q, SLOT(_q_emitItemClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(doubleClicked(QModelIndex)),
- q, SLOT(_q_emitItemDoubleClicked(QModelIndex)));
- QObject::connect(q, SIGNAL(activated(QModelIndex)), q, SLOT(_q_emitItemActivated(QModelIndex)));
- QObject::connect(q, SIGNAL(entered(QModelIndex)), q, SLOT(_q_emitItemEntered(QModelIndex)));
- // model signals
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitItemChanged(QModelIndex)));
- // selection signals
- QObject::connect(q->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- QObject::connect(q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- q, SIGNAL(itemSelectionChanged()));
- // sorting
- QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort()));
-}
-
-void QTableWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
-{
- Q_Q(QTableWidget);
- if (QTableWidgetItem *item = tableModel()->item(index))
- emit q->itemPressed(item);
- emit q->cellPressed(index.row(), index.column());
-}
-
-void QTableWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
-{
- Q_Q(QTableWidget);
- if (QTableWidgetItem *item = tableModel()->item(index))
- emit q->itemClicked(item);
- emit q->cellClicked(index.row(), index.column());
-}
-
-void QTableWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
-{
- Q_Q(QTableWidget);
- if (QTableWidgetItem *item = tableModel()->item(index))
- emit q->itemDoubleClicked(item);
- emit q->cellDoubleClicked(index.row(), index.column());
-}
-
-void QTableWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
-{
- Q_Q(QTableWidget);
- if (QTableWidgetItem *item = tableModel()->item(index))
- emit q->itemActivated(item);
- emit q->cellActivated(index.row(), index.column());
-}
-
-void QTableWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
-{
- Q_Q(QTableWidget);
- if (QTableWidgetItem *item = tableModel()->item(index))
- emit q->itemEntered(item);
- emit q->cellEntered(index.row(), index.column());
-}
-
-void QTableWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
-{
- Q_Q(QTableWidget);
- if (QTableWidgetItem *item = tableModel()->item(index))
- emit q->itemChanged(item);
- emit q->cellChanged(index.row(), index.column());
-}
-
-void QTableWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
- const QModelIndex &previous)
-{
- Q_Q(QTableWidget);
- QTableWidgetItem *currentItem = tableModel()->item(current);
- QTableWidgetItem *previousItem = tableModel()->item(previous);
- if (currentItem || previousItem)
- emit q->currentItemChanged(currentItem, previousItem);
- emit q->currentCellChanged(current.row(), current.column(), previous.row(), previous.column());
-}
-
-void QTableWidgetPrivate::_q_sort()
-{
- if (sortingEnabled) {
- int column = horizontalHeader->sortIndicatorSection();
- Qt::SortOrder order = horizontalHeader->sortIndicatorOrder();
- model->sort(column, order);
- }
-}
-
-void QTableWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
-{
- if (sortingEnabled && topLeft.isValid() && bottomRight.isValid()) {
- int column = horizontalHeader->sortIndicatorSection();
- if (column >= topLeft.column() && column <= bottomRight.column()) {
- Qt::SortOrder order = horizontalHeader->sortIndicatorOrder();
- tableModel()->ensureSorted(column, order, topLeft.row(), bottomRight.row());
- }
- }
-}
-
-/*!
- \fn void QTableWidget::itemPressed(QTableWidgetItem *item)
-
- This signal is emitted whenever an item in the table is pressed.
- The \a item specified is the item that was pressed.
-*/
-
-/*!
- \fn void QTableWidget::itemClicked(QTableWidgetItem *item)
-
- This signal is emitted whenever an item in the table is clicked.
- The \a item specified is the item that was clicked.
-*/
-
-/*!
- \fn void QTableWidget::itemDoubleClicked(QTableWidgetItem *item)
-
- This signal is emitted whenever an item in the table is double
- clicked. The \a item specified is the item that was double clicked.
-*/
-
-/*!
- \fn void QTableWidget::itemActivated(QTableWidgetItem *item)
-
- This signal is emitted when the specified \a item has been activated
-*/
-
-/*!
- \fn void QTableWidget::itemEntered(QTableWidgetItem *item)
-
- This signal is emitted when the mouse cursor enters an item. The
- \a item is the item entered.
-
- This signal is only emitted when mouseTracking is turned on, or when a
- mouse button is pressed while moving into an item.
-*/
-
-/*!
- \fn void QTableWidget::itemChanged(QTableWidgetItem *item)
-
- This signal is emitted whenever the data of \a item has changed.
-*/
-
-/*!
- \fn void QTableWidget::currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous)
-
- This signal is emitted whenever the current item changes. The \a
- previous item is the item that previously had the focus, \a
- current is the new current item.
-*/
-
-/*!
- \fn void QTableWidget::itemSelectionChanged()
-
- This signal is emitted whenever the selection changes.
-
- \sa selectedItems() QTableWidgetItem::isSelected()
-*/
-
-
-/*!
- \since 4.1
- \fn void QTableWidget::cellPressed(int row, int column)
-
- This signal is emitted whenever a cell in the table is pressed.
- The \a row and \a column specified is the cell that was pressed.
-*/
-
-/*!
- \since 4.1
- \fn void QTableWidget::cellClicked(int row, int column)
-
- This signal is emitted whenever a cell in the table is clicked.
- The \a row and \a column specified is the cell that was clicked.
-*/
-
-/*!
- \since 4.1
- \fn void QTableWidget::cellDoubleClicked(int row, int column)
-
- This signal is emitted whenever a cell in the table is double
- clicked. The \a row and \a column specified is the cell that was
- double clicked.
-*/
-
-/*!
- \since 4.1
- \fn void QTableWidget::cellActivated(int row, int column)
-
- This signal is emitted when the cell specified by \a row and \a column
- has been activated
-*/
-
-/*!
- \since 4.1
- \fn void QTableWidget::cellEntered(int row, int column)
-
- This signal is emitted when the mouse cursor enters a cell. The
- cell is specified by \a row and \a column.
-
- This signal is only emitted when mouseTracking is turned on, or when a
- mouse button is pressed while moving into an item.
-*/
-
-/*!
- \since 4.1
- \fn void QTableWidget::cellChanged(int row, int column)
-
- This signal is emitted whenever the data of the item in the cell
- specified by \a row and \a column has changed.
-*/
-
-/*!
- \since 4.1
- \fn void QTableWidget::currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
-
- This signal is emitted whenever the current cell changes. The cell
- specified by \a previousRow and \a previousColumn is the cell that
- previously had the focus, the cell specified by \a currentRow and \a
- currentColumn is the new current cell.
-*/
-
-/*!
- \since 4.3
- \fn void QTableWidget::removeCellWidget(int row, int column)
-
- Removes the widget set on the cell indicated by \a row and \a column.
-*/
-
-/*!
- \fn QTableWidgetItem *QTableWidget::itemAt(int ax, int ay) const
-
- Returns the item at the position equivalent to QPoint(\a{ax}, \a{ay}) in
- the table widget's coordinate system, or returns 0 if the specified point
- is not covered by an item in the table widget.
-
- \sa item()
-*/
-
-/*!
- \enum QTableWidgetItem::ItemType
-
- This enum describes the types that are used to describe table widget items.
-
- \value Type The default type for table widget items.
- \value UserType The minimum value for custom types. Values below UserType are
- reserved by Qt.
-
- You can define new user types in QTableWidgetItem subclasses to ensure that
- custom items are treated specially.
-
- \sa type()
-*/
-
-/*!
- \fn int QTableWidgetItem::type() const
-
- Returns the type passed to the QTableWidgetItem constructor.
-*/
-
-/*!
- Creates a new table view with the given \a parent.
-*/
-QTableWidget::QTableWidget(QWidget *parent)
- : QTableView(*new QTableWidgetPrivate, parent)
-{
- Q_D(QTableWidget);
- QTableView::setModel(new QTableModel(0, 0, this));
- d->setup();
-}
-
-/*!
- Creates a new table view with the given \a rows and \a columns, and with the given \a parent.
-*/
-QTableWidget::QTableWidget(int rows, int columns, QWidget *parent)
- : QTableView(*new QTableWidgetPrivate, parent)
-{
- Q_D(QTableWidget);
- QTableView::setModel(new QTableModel(rows, columns, this));
- d->setup();
-}
-
-/*!
- Destroys this QTableWidget.
-*/
-QTableWidget::~QTableWidget()
-{
-}
-
-/*!
- Sets the number of rows in this table's model to \a rows. If
- this is less than rowCount(), the data in the unwanted rows
- is discarded.
-
- \sa setColumnCount()
-*/
-void QTableWidget::setRowCount(int rows)
-{
- Q_D(QTableWidget);
- d->tableModel()->setRowCount(rows);
-}
-
-/*!
- Returns the number of rows.
-*/
-
-int QTableWidget::rowCount() const
-{
- Q_D(const QTableWidget);
- return d->model->rowCount();
-}
-
-/*!
- Sets the number of columns in this table's model to \a columns. If
- this is less than columnCount(), the data in the unwanted columns
- is discarded.
-
- \sa setRowCount()
-*/
-void QTableWidget::setColumnCount(int columns)
-{
- Q_D(QTableWidget);
- d->tableModel()->setColumnCount(columns);
-}
-
-/*!
- Returns the number of columns.
-*/
-
-int QTableWidget::columnCount() const
-{
- Q_D(const QTableWidget);
- return d->model->columnCount();
-}
-
-/*!
- Returns the row for the \a item.
-*/
-int QTableWidget::row(const QTableWidgetItem *item) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->index(item).row();
-}
-
-/*!
- Returns the column for the \a item.
-*/
-int QTableWidget::column(const QTableWidgetItem *item) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->index(item).column();
-}
-
-
-/*!
- Returns the item for the given \a row and \a column if one has been set; otherwise
- returns 0.
-
- \sa setItem()
-*/
-QTableWidgetItem *QTableWidget::item(int row, int column) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->item(row, column);
-}
-
-/*!
- Sets the item for the given \a row and \a column to \a item.
-
- The table takes ownership of the item.
-
- Note that if sorting is enabled (see
- \l{QTableView::sortingEnabled} {sortingEnabled}) and \a column is
- the current sort column, the \a row will be moved to the sorted
- position determined by \a item.
-
- If you want to set several items of a particular row (say, by
- calling setItem() in a loop), you may want to turn off sorting
- before doing so, and turn it back on afterwards; this will allow
- you to use the same \a row argument for all items in the same row
- (i.e. setItem() will not move the row).
-
- \sa item() takeItem()
-*/
-void QTableWidget::setItem(int row, int column, QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- if (item) {
- if (item->view != 0) {
- qWarning("QTableWidget: cannot insert an item that is already owned by another QTableWidget");
- } else {
- item->view = this;
- d->tableModel()->setItem(row, column, item);
- }
- } else {
- delete takeItem(row, column);
- }
-}
-
-/*!
- Removes the item at \a row and \a column from the table without deleting it.
-*/
-QTableWidgetItem *QTableWidget::takeItem(int row, int column)
-{
- Q_D(QTableWidget);
- QTableWidgetItem *item = d->tableModel()->takeItem(row, column);
- if (item)
- item->view = 0;
- return item;
-}
-
-/*!
- Returns the vertical header item for row \a row.
-*/
-QTableWidgetItem *QTableWidget::verticalHeaderItem(int row) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->verticalHeaderItem(row);
-}
-
-/*!
- Sets the vertical header item for row \a row to \a item.
-*/
-void QTableWidget::setVerticalHeaderItem(int row, QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- if (item) {
- item->view = this;
- d->tableModel()->setVerticalHeaderItem(row, item);
- } else {
- delete takeVerticalHeaderItem(row);
- }
-}
-
-/*!
- \since 4.1
- Removes the vertical header item at \a row from the header without deleting it.
-*/
-QTableWidgetItem *QTableWidget::takeVerticalHeaderItem(int row)
-{
- Q_D(QTableWidget);
- QTableWidgetItem *itm = d->tableModel()->takeVerticalHeaderItem(row);
- if (itm)
- itm->view = 0;
- return itm;
-}
-
-/*!
- Returns the horizontal header item for column, \a column, if one has been
- set; otherwise returns 0.
-*/
-QTableWidgetItem *QTableWidget::horizontalHeaderItem(int column) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->horizontalHeaderItem(column);
-}
-
-/*!
- Sets the horizontal header item for column \a column to \a item.
-*/
-void QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- if (item) {
- item->view = this;
- d->tableModel()->setHorizontalHeaderItem(column, item);
- } else {
- delete takeHorizontalHeaderItem(column);
- }
-}
-
-/*!
- \since 4.1
- Removes the horizontal header item at \a column from the header without deleting it.
-*/
-QTableWidgetItem *QTableWidget::takeHorizontalHeaderItem(int column)
-{
- Q_D(QTableWidget);
- QTableWidgetItem *itm = d->tableModel()->takeHorizontalHeaderItem(column);
- if (itm)
- itm->view = 0;
- return itm;
-}
-
-/*!
- Sets the vertical header labels using \a labels.
-*/
-void QTableWidget::setVerticalHeaderLabels(const QStringList &labels)
-{
- Q_D(QTableWidget);
- QTableModel *model = d->tableModel();
- QTableWidgetItem *item = 0;
- for (int i = 0; i < model->rowCount() && i < labels.count(); ++i) {
- item = model->verticalHeaderItem(i);
- if (!item) {
- item = model->createItem();
- setVerticalHeaderItem(i, item);
- }
- item->setText(labels.at(i));
- }
-}
-
-/*!
- Sets the horizontal header labels using \a labels.
-*/
-void QTableWidget::setHorizontalHeaderLabels(const QStringList &labels)
-{
- Q_D(QTableWidget);
- QTableModel *model = d->tableModel();
- QTableWidgetItem *item = 0;
- for (int i = 0; i < model->columnCount() && i < labels.count(); ++i) {
- item = model->horizontalHeaderItem(i);
- if (!item) {
- item = model->createItem();
- setHorizontalHeaderItem(i, item);
- }
- item->setText(labels.at(i));
- }
-}
-
-/*!
- Returns the row of the current item.
-
- \sa currentColumn(), setCurrentCell()
-*/
-int QTableWidget::currentRow() const
-{
- return currentIndex().row();
-}
-
-/*!
- Returns the column of the current item.
-
- \sa currentRow(), setCurrentCell()
-*/
-int QTableWidget::currentColumn() const
-{
- return currentIndex().column();
-}
-
-/*!
- Returns the current item.
-
- \sa setCurrentItem()
-*/
-QTableWidgetItem *QTableWidget::currentItem() const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->item(currentIndex());
-}
-
-/*!
- Sets the current item to \a item.
-
- Unless the selection mode is \l{QAbstractItemView::}{NoSelection},
- the item is also be selected.
-
- \sa currentItem(), setCurrentCell()
-*/
-void QTableWidget::setCurrentItem(QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- setCurrentIndex(d->tableModel()->index(item));
-}
-
-/*!
- \since 4.4
-
- Sets the current item to be \a item, using the given \a command.
-
- \sa currentItem(), setCurrentCell()
-*/
-void QTableWidget::setCurrentItem(QTableWidgetItem *item, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QTableWidget);
- d->selectionModel->setCurrentIndex(d->tableModel()->index(item), command);
-}
-
-/*!
- \since 4.1
-
- Sets the current cell to be the cell at position (\a row, \a
- column).
-
- Depending on the current \l{QAbstractItemView::SelectionMode}{selection mode},
- the cell may also be selected.
-
- \sa setCurrentItem(), currentRow(), currentColumn()
-*/
-void QTableWidget::setCurrentCell(int row, int column)
-{
- setCurrentIndex(model()->index(row, column, QModelIndex()));
-}
-
-/*!
- \since 4.4
-
- Sets the current cell to be the cell at position (\a row, \a
- column), using the given \a command.
-
- \sa setCurrentItem(), currentRow(), currentColumn()
-*/
-void QTableWidget::setCurrentCell(int row, int column, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QTableWidget);
- d->selectionModel->setCurrentIndex(model()->index(row, column, QModelIndex()), command);
-}
-
-/*!
- Sorts all the rows in the table widget based on \a column and \a order.
-*/
-void QTableWidget::sortItems(int column, Qt::SortOrder order)
-{
- Q_D(QTableWidget);
- d->model->sort(column, order);
- horizontalHeader()->setSortIndicator(column, order);
-}
-
-/*!
- \internal
-*/
-void QTableWidget::setSortingEnabled(bool enable)
-{
- QTableView::setSortingEnabled(enable);
-}
-
-/*!
- \internal
-*/
-bool QTableWidget::isSortingEnabled() const
-{
- return QTableView::isSortingEnabled();
-}
-
-/*!
- Starts editing the \a item if it is editable.
-*/
-
-void QTableWidget::editItem(QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- if (!item)
- return;
- edit(d->tableModel()->index(item));
-}
-
-/*!
- Opens an editor for the give \a item. The editor remains open after editing.
-
- \sa closePersistentEditor()
-*/
-void QTableWidget::openPersistentEditor(QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- if (!item)
- return;
- QModelIndex index = d->tableModel()->index(item);
- QAbstractItemView::openPersistentEditor(index);
-}
-
-/*!
- Closes the persistent editor for \a item.
-
- \sa openPersistentEditor()
-*/
-void QTableWidget::closePersistentEditor(QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- if (!item)
- return;
- QModelIndex index = d->tableModel()->index(item);
- QAbstractItemView::closePersistentEditor(index);
-}
-
-/*!
- \since 4.1
-
- Returns the widget displayed in the cell in the given \a row and \a column.
-
- \note The table takes ownership of the widget.
-
- \sa setCellWidget()
-*/
-QWidget *QTableWidget::cellWidget(int row, int column) const
-{
- QModelIndex index = model()->index(row, column, QModelIndex());
- return QAbstractItemView::indexWidget(index);
-}
-
-/*!
- \since 4.1
-
- Sets the given \a widget to be displayed in the cell in the given \a row
- and \a column, passing the ownership of the widget to the table.
-
- If cell widget A is replaced with cell widget B, cell widget A will be
- deleted. For example, in the code snippet below, the QLineEdit object will
- be deleted.
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qtablewidget.cpp 0
-
- \sa cellWidget()
-*/
-void QTableWidget::setCellWidget(int row, int column, QWidget *widget)
-{
- QModelIndex index = model()->index(row, column, QModelIndex());
- QAbstractItemView::setIndexWidget(index, widget);
-}
-
-/*!
- Returns true if the \a item is selected, otherwise returns false.
-
- \obsolete
-
- This function is deprecated. Use \l{QTableWidgetItem::isSelected()} instead.
-*/
-
-bool QTableWidget::isItemSelected(const QTableWidgetItem *item) const
-{
- Q_D(const QTableWidget);
- QModelIndex index = d->tableModel()->index(item);
- return selectionModel()->isSelected(index);
-}
-
-/*!
- Selects or deselects \a item depending on \a select.
-
- \obsolete
-
- This function is deprecated. Use \l{QTableWidgetItem::setSelected()} instead.
-*/
-void QTableWidget::setItemSelected(const QTableWidgetItem *item, bool select)
-{
- Q_D(QTableWidget);
- QModelIndex index = d->tableModel()->index(item);
- selectionModel()->select(index, select ? QItemSelectionModel::Select : QItemSelectionModel::Deselect);
-}
-
-/*!
- Selects or deselects the \a range depending on \a select.
-*/
-void QTableWidget::setRangeSelected(const QTableWidgetSelectionRange &range, bool select)
-{
- if (!model()->hasIndex(range.topRow(), range.leftColumn(), rootIndex()) ||
- !model()->hasIndex(range.bottomRow(), range.rightColumn(), rootIndex()))
- return;
-
- QModelIndex topLeft = model()->index(range.topRow(), range.leftColumn(), rootIndex());
- QModelIndex bottomRight = model()->index(range.bottomRow(), range.rightColumn(), rootIndex());
-
- selectionModel()->select(QItemSelection(topLeft, bottomRight),
- select ? QItemSelectionModel::Select : QItemSelectionModel::Deselect);
-}
-
-/*!
- Returns a list of all selected ranges.
-
- \sa QTableWidgetSelectionRange
-*/
-
-QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges() const
-{
- const QList<QItemSelectionRange> ranges = selectionModel()->selection();
- QList<QTableWidgetSelectionRange> result;
- for (int i = 0; i < ranges.count(); ++i)
- result.append(QTableWidgetSelectionRange(ranges.at(i).top(),
- ranges.at(i).left(),
- ranges.at(i).bottom(),
- ranges.at(i).right()));
- return result;
-}
-
-/*!
- Returns a list of all selected items.
-
- This function returns a list of pointers to the contents of the
- selected cells. Use the selectedIndexes() function to retrieve the
- complete selection \e including empty cells.
-
- \sa selectedIndexes()
-*/
-
-QList<QTableWidgetItem*> QTableWidget::selectedItems()
-{
- Q_D(QTableWidget);
- QModelIndexList indexes = selectionModel()->selectedIndexes();
- QList<QTableWidgetItem*> items;
- for (int i = 0; i < indexes.count(); ++i) {
- QModelIndex index = indexes.at(i);
- if (isIndexHidden(index))
- continue;
- QTableWidgetItem *item = d->tableModel()->item(index);
- if (item)
- items.append(item);
- }
- return items;
-}
-
-/*!
- Finds items that matches the \a text using the given \a flags.
-*/
-
-QList<QTableWidgetItem*> QTableWidget::findItems(const QString &text, Qt::MatchFlags flags) const
-{
- Q_D(const QTableWidget);
- QModelIndexList indexes;
- for (int column = 0; column < columnCount(); ++column)
- indexes += d->model->match(model()->index(0, column, QModelIndex()),
- Qt::DisplayRole, text, -1, flags);
- QList<QTableWidgetItem*> items;
- for (int i = 0; i < indexes.size(); ++i)
- items.append(d->tableModel()->item(indexes.at(i)));
- return items;
-}
-
-/*!
- Returns the visual row of the given \a logicalRow.
-*/
-
-int QTableWidget::visualRow(int logicalRow) const
-{
- return verticalHeader()->visualIndex(logicalRow);
-}
-
-/*!
- Returns the visual column of the given \a logicalColumn.
-*/
-
-int QTableWidget::visualColumn(int logicalColumn) const
-{
- return horizontalHeader()->visualIndex(logicalColumn);
-}
-
-/*!
- \fn QTableWidgetItem *QTableWidget::itemAt(const QPoint &point) const
-
- Returns a pointer to the item at the given \a point, or returns 0 if
- \a point is not covered by an item in the table widget.
-
- \sa item()
-*/
-
-QTableWidgetItem *QTableWidget::itemAt(const QPoint &p) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->item(indexAt(p));
-}
-
-/*!
- Returns the rectangle on the viewport occupied by the item at \a item.
-*/
-QRect QTableWidget::visualItemRect(const QTableWidgetItem *item) const
-{
- Q_D(const QTableWidget);
- if (!item)
- return QRect();
- QModelIndex index = d->tableModel()->index(const_cast<QTableWidgetItem*>(item));
- Q_ASSERT(index.isValid());
- return visualRect(index);
-}
-
-/*!
- Scrolls the view if necessary to ensure that the \a item is visible.
- The \a hint parameter specifies more precisely where the
- \a item should be located after the operation.
-*/
-
-void QTableWidget::scrollToItem(const QTableWidgetItem *item, QAbstractItemView::ScrollHint hint)
-{
- Q_D(QTableWidget);
- if (!item)
- return;
- QModelIndex index = d->tableModel()->index(const_cast<QTableWidgetItem*>(item));
- Q_ASSERT(index.isValid());
- QTableView::scrollTo(index, hint);
-}
-
-/*!
- Returns the item prototype used by the table.
-
- \sa setItemPrototype()
-*/
-const QTableWidgetItem *QTableWidget::itemPrototype() const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->itemPrototype();
-}
-
-/*!
- Sets the item prototype for the table to the specified \a item.
-
- The table widget will use the item prototype clone function when it needs
- to create a new table item. For example when the user is editing
- in an empty cell. This is useful when you have a QTableWidgetItem
- subclass and want to make sure that QTableWidget creates instances of
- your subclass.
-
- The table takes ownership of the prototype.
-
- \sa itemPrototype()
-*/
-void QTableWidget::setItemPrototype(const QTableWidgetItem *item)
-{
- Q_D(QTableWidget);
- d->tableModel()->setItemPrototype(item);
-}
-
-/*!
- Inserts an empty row into the table at \a row.
-*/
-void QTableWidget::insertRow(int row)
-{
- Q_D(QTableWidget);
- d->tableModel()->insertRows(row);
-}
-
-/*!
- Inserts an empty column into the table at \a column.
-*/
-void QTableWidget::insertColumn(int column)
-{
- Q_D(QTableWidget);
- d->tableModel()->insertColumns(column);
-}
-
-/*!
- Removes the row \a row and all its items from the table.
-*/
-void QTableWidget::removeRow(int row)
-{
- Q_D(QTableWidget);
- d->tableModel()->removeRows(row);
-}
-
-/*!
- Removes the column \a column and all its items from the table.
-*/
-void QTableWidget::removeColumn(int column)
-{
- Q_D(QTableWidget);
- d->tableModel()->removeColumns(column);
-}
-
-/*!
- Removes all items in the view.
- This will also remove all selections.
- The table dimensions stay the same.
-*/
-
-void QTableWidget::clear()
-{
- Q_D(QTableWidget);
- selectionModel()->clear();
- d->tableModel()->clear();
-}
-
-/*!
- \since 4.2
-
- Removes all items not in the headers from the view.
- This will also remove all selections.
- The table dimensions stay the same.
-*/
-void QTableWidget::clearContents()
-{
- Q_D(QTableWidget);
- selectionModel()->clear();
- d->tableModel()->clearContents();
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of
- tablewidget items.
-
- \sa mimeData()
-*/
-QStringList QTableWidget::mimeTypes() const
-{
- return d_func()->tableModel()->QAbstractTableModel::mimeTypes();
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a items. The format used to describe the items is obtained from the
- mimeTypes() function.
-
- If the list of items is empty, 0 is returned rather than a serialized
- empty list.
-*/
-QMimeData *QTableWidget::mimeData(const QList<QTableWidgetItem*>) const
-{
- return d_func()->tableModel()->internalMimeData();
-}
-
-/*!
- Handles the \a data supplied by a drag and drop operation that ended with
- the given \a action in the given \a row and \a column.
- Returns true if the data and action can be handled by the model;
- otherwise returns false.
-
- \sa supportedDropActions()
-*/
-bool QTableWidget::dropMimeData(int row, int column, const QMimeData *data, Qt::DropAction action)
-{
- QModelIndex idx;
-#ifndef QT_NO_DRAGANDDROP
- if (dropIndicatorPosition() == QAbstractItemView::OnItem) {
- // QAbstractTableModel::dropMimeData will overwrite on the index if row == -1 and column == -1
- idx = model()->index(row, column);
- row = -1;
- column = -1;
- }
-#endif
- return d_func()->tableModel()->QAbstractTableModel::dropMimeData(data, action , row, column, idx);
-}
-
-/*!
- Returns the drop actions supported by this view.
-
- \sa Qt::DropActions
-*/
-Qt::DropActions QTableWidget::supportedDropActions() const
-{
- return d_func()->tableModel()->QAbstractTableModel::supportedDropActions() | Qt::MoveAction;
-}
-
-/*!
- Returns a list of pointers to the items contained in the \a data object.
- If the object was not created by a QTreeWidget in the same process, the list
- is empty.
-
-*/
-QList<QTableWidgetItem*> QTableWidget::items(const QMimeData *data) const
-{
- const QTableWidgetMimeData *twd = qobject_cast<const QTableWidgetMimeData*>(data);
- if (twd)
- return twd->items;
- return QList<QTableWidgetItem*>();
-}
-
-/*!
- Returns the QModelIndex assocated with the given \a item.
-*/
-
-QModelIndex QTableWidget::indexFromItem(QTableWidgetItem *item) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->index(item);
-}
-
-/*!
- Returns a pointer to the QTableWidgetItem assocated with the given \a index.
-*/
-
-QTableWidgetItem *QTableWidget::itemFromIndex(const QModelIndex &index) const
-{
- Q_D(const QTableWidget);
- return d->tableModel()->item(index);
-}
-
-/*!
- \internal
-*/
-void QTableWidget::setModel(QAbstractItemModel * /*model*/)
-{
- Q_ASSERT(!"QTableWidget::setModel() - Changing the model of the QTableWidget is not allowed.");
-}
-
-/*! \reimp */
-bool QTableWidget::event(QEvent *e)
-{
- return QTableView::event(e);
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*! \reimp */
-void QTableWidget::dropEvent(QDropEvent *event) {
- Q_D(QTableWidget);
- if (event->source() == this && (event->dropAction() == Qt::MoveAction ||
- dragDropMode() == QAbstractItemView::InternalMove)) {
- QModelIndex topIndex;
- int col = -1;
- int row = -1;
- if (d->dropOn(event, &row, &col, &topIndex)) {
- QModelIndexList indexes = selectedIndexes();
- int top = INT_MAX;
- int left = INT_MAX;
- for (int i = 0; i < indexes.count(); ++i) {
- top = qMin(indexes.at(i).row(), top);
- left = qMin(indexes.at(i).column(), left);
- }
-
- QList<QTableWidgetItem *> taken;
- for (int i = 0; i < indexes.count(); ++i)
- taken.append(takeItem(indexes.at(i).row(), indexes.at(i).column()));
-
- for (int i = 0; i < indexes.count(); ++i) {
- QModelIndex index = indexes.at(i);
- int r = index.row() - top + topIndex.row();
- int c = index.column() - left + topIndex.column();
- setItem(r, c, taken.takeFirst());
- }
-
- event->accept();
- // Don't want QAbstractItemView to delete it because it was "moved" we already did it
- event->setDropAction(Qt::CopyAction);
- }
- }
-
- QTableView::dropEvent(event);
-}
-#endif
-
-QT_END_NAMESPACE
-
-#include "moc_qtablewidget.cpp"
-
-#endif // QT_NO_TABLEWIDGET
diff --git a/src/gui/itemviews/qtablewidget.h b/src/gui/itemviews/qtablewidget.h
deleted file mode 100644
index 35e3b29628..0000000000
--- a/src/gui/itemviews/qtablewidget.h
+++ /dev/null
@@ -1,377 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABLEWIDGET_H
-#define QTABLEWIDGET_H
-
-#include <QtGui/qtableview.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
-//#include <QtGui/qitemselectionmodel.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TABLEWIDGET
-
-class Q_GUI_EXPORT QTableWidgetSelectionRange
-{
-public:
- QTableWidgetSelectionRange();
- QTableWidgetSelectionRange(int top, int left, int bottom, int right);
- QTableWidgetSelectionRange(const QTableWidgetSelectionRange &other);
- ~QTableWidgetSelectionRange();
-
- inline int topRow() const { return top; }
- inline int bottomRow() const { return bottom; }
- inline int leftColumn() const { return left; }
- inline int rightColumn() const { return right; }
- inline int rowCount() const { return bottom - top + 1; }
- inline int columnCount() const { return right - left + 1; }
-
-private:
- int top, left, bottom, right;
-};
-
-class QTableWidget;
-class QTableModel;
-class QWidgetItemData;
-class QTableWidgetItemPrivate;
-
-class Q_GUI_EXPORT QTableWidgetItem
-{
- friend class QTableWidget;
- friend class QTableModel;
-public:
- enum ItemType { Type = 0, UserType = 1000 };
- QTableWidgetItem(int type = Type);
- explicit QTableWidgetItem(const QString &text, int type = Type);
- explicit QTableWidgetItem(const QIcon &icon, const QString &text, int type = Type);
- QTableWidgetItem(const QTableWidgetItem &other);
- virtual ~QTableWidgetItem();
-
- virtual QTableWidgetItem *clone() const;
-
- inline QTableWidget *tableWidget() const { return view; }
-
- inline int row() const;
- inline int column() const;
-
- inline void setSelected(bool select);
- inline bool isSelected() const;
-
- inline Qt::ItemFlags flags() const { return itemFlags; }
- void setFlags(Qt::ItemFlags flags);
-
- inline QString text() const
- { return data(Qt::DisplayRole).toString(); }
- inline void setText(const QString &text);
-
- inline QIcon icon() const
- { return qvariant_cast<QIcon>(data(Qt::DecorationRole)); }
- inline void setIcon(const QIcon &icon);
-
- inline QString statusTip() const
- { return data(Qt::StatusTipRole).toString(); }
- inline void setStatusTip(const QString &statusTip);
-
-#ifndef QT_NO_TOOLTIP
- inline QString toolTip() const
- { return data(Qt::ToolTipRole).toString(); }
- inline void setToolTip(const QString &toolTip);
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- inline QString whatsThis() const
- { return data(Qt::WhatsThisRole).toString(); }
- inline void setWhatsThis(const QString &whatsThis);
-#endif
-
- inline QFont font() const
- { return qvariant_cast<QFont>(data(Qt::FontRole)); }
- inline void setFont(const QFont &font);
-
- inline int textAlignment() const
- { return data(Qt::TextAlignmentRole).toInt(); }
- inline void setTextAlignment(int alignment)
- { setData(Qt::TextAlignmentRole, alignment); }
-
- inline QColor backgroundColor() const
- { return qvariant_cast<QColor>(data(Qt::BackgroundColorRole)); }
- inline void setBackgroundColor(const QColor &color)
- { setData(Qt::BackgroundColorRole, color); }
-
- inline QBrush background() const
- { return qvariant_cast<QBrush>(data(Qt::BackgroundRole)); }
- inline void setBackground(const QBrush &brush)
- { setData(Qt::BackgroundRole, brush); }
-
- inline QColor textColor() const
- { return qvariant_cast<QColor>(data(Qt::TextColorRole)); }
- inline void setTextColor(const QColor &color)
- { setData(Qt::TextColorRole, color); }
-
- inline QBrush foreground() const
- { return qvariant_cast<QBrush>(data(Qt::ForegroundRole)); }
- inline void setForeground(const QBrush &brush)
- { setData(Qt::ForegroundRole, brush); }
-
- inline Qt::CheckState checkState() const
- { return static_cast<Qt::CheckState>(data(Qt::CheckStateRole).toInt()); }
- inline void setCheckState(Qt::CheckState state)
- { setData(Qt::CheckStateRole, state); }
-
- inline QSize sizeHint() const
- { return qvariant_cast<QSize>(data(Qt::SizeHintRole)); }
- inline void setSizeHint(const QSize &size)
- { setData(Qt::SizeHintRole, size); }
-
- virtual QVariant data(int role) const;
- virtual void setData(int role, const QVariant &value);
-
- virtual bool operator<(const QTableWidgetItem &other) const;
-
-#ifndef QT_NO_DATASTREAM
- virtual void read(QDataStream &in);
- virtual void write(QDataStream &out) const;
-#endif
- QTableWidgetItem &operator=(const QTableWidgetItem &other);
-
- inline int type() const { return rtti; }
-
-private:
- int rtti;
- QVector<QWidgetItemData> values;
- QTableWidget *view;
- QTableWidgetItemPrivate *d;
- Qt::ItemFlags itemFlags;
-};
-
-inline void QTableWidgetItem::setText(const QString &atext)
-{ setData(Qt::DisplayRole, atext); }
-
-inline void QTableWidgetItem::setIcon(const QIcon &aicon)
-{ setData(Qt::DecorationRole, aicon); }
-
-inline void QTableWidgetItem::setStatusTip(const QString &astatusTip)
-{ setData(Qt::StatusTipRole, astatusTip); }
-
-#ifndef QT_NO_TOOLTIP
-inline void QTableWidgetItem::setToolTip(const QString &atoolTip)
-{ setData(Qt::ToolTipRole, atoolTip); }
-#endif
-
-#ifndef QT_NO_WHATSTHIS
-inline void QTableWidgetItem::setWhatsThis(const QString &awhatsThis)
-{ setData(Qt::WhatsThisRole, awhatsThis); }
-#endif
-
-inline void QTableWidgetItem::setFont(const QFont &afont)
-{ setData(Qt::FontRole, afont); }
-
-#ifndef QT_NO_DATASTREAM
-Q_GUI_EXPORT QDataStream &operator>>(QDataStream &in, QTableWidgetItem &item);
-Q_GUI_EXPORT QDataStream &operator<<(QDataStream &out, const QTableWidgetItem &item);
-#endif
-
-class QTableWidgetPrivate;
-
-class Q_GUI_EXPORT QTableWidget : public QTableView
-{
- Q_OBJECT
- Q_PROPERTY(int rowCount READ rowCount WRITE setRowCount)
- Q_PROPERTY(int columnCount READ columnCount WRITE setColumnCount)
-
- friend class QTableModel;
-public:
- explicit QTableWidget(QWidget *parent = 0);
- QTableWidget(int rows, int columns, QWidget *parent = 0);
- ~QTableWidget();
-
- void setRowCount(int rows);
- int rowCount() const;
-
- void setColumnCount(int columns);
- int columnCount() const;
-
- int row(const QTableWidgetItem *item) const;
- int column(const QTableWidgetItem *item) const;
-
- QTableWidgetItem *item(int row, int column) const;
- void setItem(int row, int column, QTableWidgetItem *item);
- QTableWidgetItem *takeItem(int row, int column);
-
- QTableWidgetItem *verticalHeaderItem(int row) const;
- void setVerticalHeaderItem(int row, QTableWidgetItem *item);
- QTableWidgetItem *takeVerticalHeaderItem(int row);
-
- QTableWidgetItem *horizontalHeaderItem(int column) const;
- void setHorizontalHeaderItem(int column, QTableWidgetItem *item);
- QTableWidgetItem *takeHorizontalHeaderItem(int column);
- void setVerticalHeaderLabels(const QStringList &labels);
- void setHorizontalHeaderLabels(const QStringList &labels);
-
- int currentRow() const;
- int currentColumn() const;
- QTableWidgetItem *currentItem() const;
- void setCurrentItem(QTableWidgetItem *item);
- void setCurrentItem(QTableWidgetItem *item, QItemSelectionModel::SelectionFlags command);
- void setCurrentCell(int row, int column);
- void setCurrentCell(int row, int column, QItemSelectionModel::SelectionFlags command);
-
- void sortItems(int column, Qt::SortOrder order = Qt::AscendingOrder);
- void setSortingEnabled(bool enable);
- bool isSortingEnabled() const;
-
- void editItem(QTableWidgetItem *item);
- void openPersistentEditor(QTableWidgetItem *item);
- void closePersistentEditor(QTableWidgetItem *item);
-
- QWidget *cellWidget(int row, int column) const;
- void setCellWidget(int row, int column, QWidget *widget);
- inline void removeCellWidget(int row, int column);
-
- bool isItemSelected(const QTableWidgetItem *item) const;
- void setItemSelected(const QTableWidgetItem *item, bool select);
- void setRangeSelected(const QTableWidgetSelectionRange &range, bool select);
-
- QList<QTableWidgetSelectionRange> selectedRanges() const;
- QList<QTableWidgetItem*> selectedItems();
- QList<QTableWidgetItem*> findItems(const QString &text, Qt::MatchFlags flags) const;
-
- int visualRow(int logicalRow) const;
- int visualColumn(int logicalColumn) const;
-
- QTableWidgetItem *itemAt(const QPoint &p) const;
- inline QTableWidgetItem *itemAt(int x, int y) const;
- QRect visualItemRect(const QTableWidgetItem *item) const;
-
- const QTableWidgetItem *itemPrototype() const;
- void setItemPrototype(const QTableWidgetItem *item);
-
-public Q_SLOTS:
- void scrollToItem(const QTableWidgetItem *item, QAbstractItemView::ScrollHint hint = EnsureVisible);
- void insertRow(int row);
- void insertColumn(int column);
- void removeRow(int row);
- void removeColumn(int column);
- void clear();
- void clearContents();
-
-Q_SIGNALS:
- void itemPressed(QTableWidgetItem *item);
- void itemClicked(QTableWidgetItem *item);
- void itemDoubleClicked(QTableWidgetItem *item);
-
- void itemActivated(QTableWidgetItem *item);
- void itemEntered(QTableWidgetItem *item);
- void itemChanged(QTableWidgetItem *item);
-
- void currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous);
- void itemSelectionChanged();
-
- void cellPressed(int row, int column);
- void cellClicked(int row, int column);
- void cellDoubleClicked(int row, int column);
-
- void cellActivated(int row, int column);
- void cellEntered(int row, int column);
- void cellChanged(int row, int column);
-
- void currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);
-
-protected:
- bool event(QEvent *e);
- virtual QStringList mimeTypes() const;
- virtual QMimeData *mimeData(const QList<QTableWidgetItem*> items) const;
- virtual bool dropMimeData(int row, int column, const QMimeData *data, Qt::DropAction action);
- virtual Qt::DropActions supportedDropActions() const;
- QList<QTableWidgetItem*> items(const QMimeData *data) const;
-
- QModelIndex indexFromItem(QTableWidgetItem *item) const;
- QTableWidgetItem *itemFromIndex(const QModelIndex &index) const;
- void dropEvent(QDropEvent *event);
-
-private:
- void setModel(QAbstractItemModel *model);
-
- Q_DECLARE_PRIVATE(QTableWidget)
- Q_DISABLE_COPY(QTableWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current))
- Q_PRIVATE_SLOT(d_func(), void _q_sort())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight))
-};
-
-inline void QTableWidget::removeCellWidget(int arow, int acolumn)
-{ setCellWidget(arow, acolumn, 0); }
-
-inline QTableWidgetItem *QTableWidget::itemAt(int ax, int ay) const
-{ return itemAt(QPoint(ax, ay)); }
-
-inline int QTableWidgetItem::row() const
-{ return (view ? view->row(this) : -1); }
-
-inline int QTableWidgetItem::column() const
-{ return (view ? view->column(this) : -1); }
-
-inline void QTableWidgetItem::setSelected(bool aselect)
-{ if (view) view->setItemSelected(this, aselect); }
-
-inline bool QTableWidgetItem::isSelected() const
-{ return (view ? view->isItemSelected(this) : false); }
-
-#endif // QT_NO_TABLEWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTABLEWIDGET_H
diff --git a/src/gui/itemviews/qtablewidget_p.h b/src/gui/itemviews/qtablewidget_p.h
deleted file mode 100644
index e0b06cb89c..0000000000
--- a/src/gui/itemviews/qtablewidget_p.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABLEWIDGET_P_H
-#define QTABLEWIDGET_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. This header file may change
-// from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qheaderview.h>
-#include <qtablewidget.h>
-#include <qabstractitemmodel.h>
-#include <private/qabstractitemmodel_p.h>
-#include <private/qtableview_p.h>
-#include <private/qwidgetitemdata_p.h>
-
-#ifndef QT_NO_TABLEWIDGET
-
-QT_BEGIN_NAMESPACE
-
-// workaround for VC++ 6.0 linker bug
-typedef bool(*LessThan)(const QPair<QTableWidgetItem*,int>&,const QPair<QTableWidgetItem*,int>&);
-
-class QTableWidgetMimeData : public QMimeData
-{
- Q_OBJECT
-public:
- QList<QTableWidgetItem*> items;
-};
-
-class QTableModelLessThan
-{
-public:
- inline bool operator()(QTableWidgetItem *i1, QTableWidgetItem *i2) const
- { return (*i1 < *i2); }
-};
-
-class QTableModelGreaterThan
-{
-public:
- inline bool operator()(QTableWidgetItem *i1, QTableWidgetItem *i2) const
- { return (*i2 < *i1); }
-};
-
-class QTableModel : public QAbstractTableModel
-{
- Q_OBJECT
-public:
- enum ItemFlagsExtension {
- ItemIsHeaderItem = 128
- }; // we need this to separate header items from other items
-
- QTableModel(int rows, int columns, QTableWidget *parent);
- ~QTableModel();
-
- bool insertRows(int row, int count = 1, const QModelIndex &parent = QModelIndex());
- bool insertColumns(int column, int count = 1, const QModelIndex &parent = QModelIndex());
-
- bool removeRows(int row, int count = 1, const QModelIndex &parent = QModelIndex());
- bool removeColumns(int column, int count = 1, const QModelIndex &parent = QModelIndex());
-
- void setItem(int row, int column, QTableWidgetItem *item);
- QTableWidgetItem *takeItem(int row, int column);
- QTableWidgetItem *item(int row, int column) const;
- QTableWidgetItem *item(const QModelIndex &index) const;
- void removeItem(QTableWidgetItem *item);
-
- void setHorizontalHeaderItem(int section, QTableWidgetItem *item);
- void setVerticalHeaderItem(int section, QTableWidgetItem *item);
- QTableWidgetItem *takeHorizontalHeaderItem(int section);
- QTableWidgetItem *takeVerticalHeaderItem(int section);
- QTableWidgetItem *horizontalHeaderItem(int section);
- QTableWidgetItem *verticalHeaderItem(int section);
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const
- { return QAbstractTableModel::index(row, column, parent); }
-
- QModelIndex index(const QTableWidgetItem *item) const;
-
- void setRowCount(int rows);
- void setColumnCount(int columns);
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role);
- bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles);
-
- QMap<int, QVariant> itemData(const QModelIndex &index) const;
-
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role);
-
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- void sort(int column, Qt::SortOrder order);
- static bool itemLessThan(const QPair<QTableWidgetItem*,int> &left,
- const QPair<QTableWidgetItem*,int> &right);
- static bool itemGreaterThan(const QPair<QTableWidgetItem*,int> &left,
- const QPair<QTableWidgetItem*,int> &right);
-
- void ensureSorted(int column, Qt::SortOrder order, int start, int end);
- QVector<QTableWidgetItem*> columnItems(int column) const;
- void updateRowIndexes(QModelIndexList &indexes, int movedFromRow, int movedToRow);
- static QVector<QTableWidgetItem*>::iterator sortedInsertionIterator(
- const QVector<QTableWidgetItem*>::iterator &begin,
- const QVector<QTableWidgetItem*>::iterator &end,
- Qt::SortOrder order, QTableWidgetItem *item);
-
- bool isValid(const QModelIndex &index) const;
- inline long tableIndex(int row, int column) const
- { return (row * horizontalHeaderItems.count()) + column; }
-
- void clear();
- void clearContents();
- void itemChanged(QTableWidgetItem *item);
-
- QTableWidgetItem *createItem() const;
- const QTableWidgetItem *itemPrototype() const;
- void setItemPrototype(const QTableWidgetItem *item);
-
- // dnd
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
- Qt::DropActions supportedDropActions() const;
-
- QMimeData *internalMimeData() const;
-
-private:
- const QTableWidgetItem *prototype;
- QVector<QTableWidgetItem*> tableItems;
- QVector<QTableWidgetItem*> verticalHeaderItems;
- QVector<QTableWidgetItem*> horizontalHeaderItems;
-
- // A cache must be mutable if get-functions should have const modifiers
- mutable QModelIndexList cachedIndexes;
-};
-
-class QTableWidgetPrivate : public QTableViewPrivate
-{
- Q_DECLARE_PUBLIC(QTableWidget)
-public:
- QTableWidgetPrivate() : QTableViewPrivate() {}
- inline QTableModel *tableModel() const { return qobject_cast<QTableModel*>(model); }
- void setup();
-
- // view signals
- void _q_emitItemPressed(const QModelIndex &index);
- void _q_emitItemClicked(const QModelIndex &index);
- void _q_emitItemDoubleClicked(const QModelIndex &index);
- void _q_emitItemActivated(const QModelIndex &index);
- void _q_emitItemEntered(const QModelIndex &index);
- // model signals
- void _q_emitItemChanged(const QModelIndex &index);
- // selection signals
- void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current);
- // sorting
- void _q_sort();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
-};
-
-class QTableWidgetItemPrivate
-{
-public:
- QTableWidgetItemPrivate(QTableWidgetItem *item) : q(item), id(-1) {}
- QTableWidgetItem *q;
- int id;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TABLEWIDGET
-
-#endif // QTABLEWIDGET_P_H
diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp
deleted file mode 100644
index 21c9d3b31a..0000000000
--- a/src/gui/itemviews/qtreeview.cpp
+++ /dev/null
@@ -1,3755 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtreeview.h"
-
-#ifndef QT_NO_TREEVIEW
-#include <qheaderview.h>
-#include <qitemdelegate.h>
-#include <qapplication.h>
-#include <qscrollbar.h>
-#include <qpainter.h>
-#include <qstack.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qevent.h>
-#include <qpen.h>
-#include <qdebug.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qaccessible.h>
-#endif
-
-#include <private/qtreeview_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QTreeView
- \brief The QTreeView class provides a default model/view implementation of a tree view.
-
- \ingroup model-view
- \ingroup advanced
-
-
- A QTreeView implements a tree representation of items from a
- model. This class is used to provide standard hierarchical lists that
- were previously provided by the \c QListView class, but using the more
- flexible approach provided by Qt's model/view architecture.
-
- The QTreeView class is one of the \l{Model/View Classes} and is part of
- Qt's \l{Model/View Programming}{model/view framework}.
-
- QTreeView implements the interfaces defined by the
- QAbstractItemView class to allow it to display data provided by
- models derived from the QAbstractItemModel class.
-
- It is simple to construct a tree view displaying data from a
- model. In the following example, the contents of a directory are
- supplied by a QDirModel and displayed as a tree:
-
- \snippet doc/src/snippets/shareddirmodel/main.cpp 3
- \snippet doc/src/snippets/shareddirmodel/main.cpp 6
-
- The model/view architecture ensures that the contents of the tree view
- are updated as the model changes.
-
- Items that have children can be in an expanded (children are
- visible) or collapsed (children are hidden) state. When this state
- changes a collapsed() or expanded() signal is emitted with the
- model index of the relevant item.
-
- The amount of indentation used to indicate levels of hierarchy is
- controlled by the \l indentation property.
-
- Headers in tree views are constructed using the QHeaderView class and can
- be hidden using \c{header()->hide()}. Note that each header is configured
- with its \l{QHeaderView::}{stretchLastSection} property set to true,
- ensuring that the view does not waste any of the space assigned to it for
- its header. If this value is set to true, this property will override the
- resize mode set on the last section in the header.
-
-
- \section1 Key Bindings
-
- QTreeView supports a set of key bindings that enable the user to
- navigate in the view and interact with the contents of items:
-
- \table
- \header \o Key \o Action
- \row \o Up \o Moves the cursor to the item in the same column on
- the previous row. If the parent of the current item has no more rows to
- navigate to, the cursor moves to the relevant item in the last row
- of the sibling that precedes the parent.
- \row \o Down \o Moves the cursor to the item in the same column on
- the next row. If the parent of the current item has no more rows to
- navigate to, the cursor moves to the relevant item in the first row
- of the sibling that follows the parent.
- \row \o Left \o Hides the children of the current item (if present)
- by collapsing a branch.
- \row \o Minus \o Same as LeftArrow.
- \row \o Right \o Reveals the children of the current item (if present)
- by expanding a branch.
- \row \o Plus \o Same as RightArrow.
- \row \o Asterisk \o Expands all children of the current item (if present).
- \row \o PageUp \o Moves the cursor up one page.
- \row \o PageDown \o Moves the cursor down one page.
- \row \o Home \o Moves the cursor to an item in the same column of the first
- row of the first top-level item in the model.
- \row \o End \o Moves the cursor to an item in the same column of the last
- row of the last top-level item in the model.
- \row \o F2 \o In editable models, this opens the current item for editing.
- The Escape key can be used to cancel the editing process and revert
- any changes to the data displayed.
- \endtable
-
- \omit
- Describe the expanding/collapsing concept if not covered elsewhere.
- \endomit
-
- \table 100%
- \row \o \inlineimage windowsxp-treeview.png Screenshot of a Windows XP style tree view
- \o \inlineimage macintosh-treeview.png Screenshot of a Macintosh style tree view
- \o \inlineimage plastique-treeview.png Screenshot of a Plastique style tree view
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} tree view.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} tree view.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} tree view.
- \endtable
-
- \section1 Improving Performance
-
- It is possible to give the view hints about the data it is handling in order
- to improve its performance when displaying large numbers of items. One approach
- that can be taken for views that are intended to display items with equal heights
- is to set the \l uniformRowHeights property to true.
-
- \sa QListView, QTreeWidget, {View Classes}, QAbstractItemModel, QAbstractItemView,
- {Dir View Example}
-*/
-
-
-/*!
- \fn void QTreeView::expanded(const QModelIndex &index)
-
- This signal is emitted when the item specified by \a index is expanded.
-*/
-
-
-/*!
- \fn void QTreeView::collapsed(const QModelIndex &index)
-
- This signal is emitted when the item specified by \a index is collapsed.
-*/
-
-/*!
- Constructs a tree view with a \a parent to represent a model's
- data. Use setModel() to set the model.
-
- \sa QAbstractItemModel
-*/
-QTreeView::QTreeView(QWidget *parent)
- : QAbstractItemView(*new QTreeViewPrivate, parent)
-{
- Q_D(QTreeView);
- d->initialize();
-}
-
-/*!
- \internal
-*/
-QTreeView::QTreeView(QTreeViewPrivate &dd, QWidget *parent)
- : QAbstractItemView(dd, parent)
-{
- Q_D(QTreeView);
- d->initialize();
-}
-
-/*!
- Destroys the tree view.
-*/
-QTreeView::~QTreeView()
-{
-}
-
-/*!
- \reimp
-*/
-void QTreeView::setModel(QAbstractItemModel *model)
-{
- Q_D(QTreeView);
- if (model == d->model)
- return;
- if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(rowsRemoved(QModelIndex,int,int)));
-
- disconnect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_modelAboutToBeReset()));
- }
-
- if (d->selectionModel) { // support row editing
- disconnect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_modelAboutToBeReset()));
- }
- d->viewItems.clear();
- d->expandedIndexes.clear();
- d->hiddenIndexes.clear();
- d->header->setModel(model);
- QAbstractItemView::setModel(model);
-
- // QAbstractItemView connects to a private slot
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- // do header layout after the tree
- disconnect(d->model, SIGNAL(layoutChanged()),
- d->header, SLOT(_q_layoutChanged()));
- // QTreeView has a public slot for this
- connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(rowsRemoved(QModelIndex,int,int)));
-
- connect(d->model, SIGNAL(modelAboutToBeReset()), SLOT(_q_modelAboutToBeReset()));
-
- if (d->sortingEnabled)
- d->_q_sortIndicatorChanged(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
-}
-
-/*!
- \reimp
-*/
-void QTreeView::setRootIndex(const QModelIndex &index)
-{
- Q_D(QTreeView);
- d->header->setRootIndex(index);
- QAbstractItemView::setRootIndex(index);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::setSelectionModel(QItemSelectionModel *selectionModel)
-{
- Q_D(QTreeView);
- Q_ASSERT(selectionModel);
- if (d->selectionModel) {
- // support row editing
- disconnect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
- }
-
- d->header->setSelectionModel(selectionModel);
- QAbstractItemView::setSelectionModel(selectionModel);
-
- if (d->selectionModel) {
- // support row editing
- connect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- d->model, SLOT(submit()));
- }
-}
-
-/*!
- Returns the header for the tree view.
-
- \sa QAbstractItemModel::headerData()
-*/
-QHeaderView *QTreeView::header() const
-{
- Q_D(const QTreeView);
- return d->header;
-}
-
-/*!
- Sets the header for the tree view, to the given \a header.
-
- The view takes ownership over the given \a header and deletes it
- when a new header is set.
-
- \sa QAbstractItemModel::headerData()
-*/
-void QTreeView::setHeader(QHeaderView *header)
-{
- Q_D(QTreeView);
- if (header == d->header || !header)
- return;
- if (d->header && d->header->parent() == this)
- delete d->header;
- d->header = header;
- d->header->setParent(this);
-
- if (!d->header->model()) {
- d->header->setModel(d->model);
- if (d->selectionModel)
- d->header->setSelectionModel(d->selectionModel);
- }
-
- connect(d->header, SIGNAL(sectionResized(int,int,int)),
- this, SLOT(columnResized(int,int,int)));
- connect(d->header, SIGNAL(sectionMoved(int,int,int)),
- this, SLOT(columnMoved()));
- connect(d->header, SIGNAL(sectionCountChanged(int,int)),
- this, SLOT(columnCountChanged(int,int)));
- connect(d->header, SIGNAL(sectionHandleDoubleClicked(int)),
- this, SLOT(resizeColumnToContents(int)));
- connect(d->header, SIGNAL(geometriesChanged()),
- this, SLOT(updateGeometries()));
-
- setSortingEnabled(d->sortingEnabled);
-}
-
-/*!
- \property QTreeView::autoExpandDelay
- \brief The delay time before items in a tree are opened during a drag and drop operation.
- \since 4.3
-
- This property holds the amount of time in milliseconds that the user must wait over
- a node before that node will automatically open or close. If the time is
- set to less then 0 then it will not be activated.
-
- By default, this property has a value of -1, meaning that auto-expansion is disabled.
-*/
-int QTreeView::autoExpandDelay() const
-{
- Q_D(const QTreeView);
- return d->autoExpandDelay;
-}
-
-void QTreeView::setAutoExpandDelay(int delay)
-{
- Q_D(QTreeView);
- d->autoExpandDelay = delay;
-}
-
-/*!
- \property QTreeView::indentation
- \brief indentation of the items in the tree view.
-
- This property holds the indentation measured in pixels of the items for each
- level in the tree view. For top-level items, the indentation specifies the
- horizontal distance from the viewport edge to the items in the first column;
- for child items, it specifies their indentation from their parent items.
-
- By default, this property has a value of 20.
-*/
-int QTreeView::indentation() const
-{
- Q_D(const QTreeView);
- return d->indent;
-}
-
-void QTreeView::setIndentation(int i)
-{
- Q_D(QTreeView);
- if (i != d->indent) {
- d->indent = i;
- d->viewport->update();
- }
-}
-
-/*!
- \property QTreeView::rootIsDecorated
- \brief whether to show controls for expanding and collapsing top-level items
-
- Items with children are typically shown with controls to expand and collapse
- them, allowing their children to be shown or hidden. If this property is
- false, these controls are not shown for top-level items. This can be used to
- make a single level tree structure appear like a simple list of items.
-
- By default, this property is true.
-*/
-bool QTreeView::rootIsDecorated() const
-{
- Q_D(const QTreeView);
- return d->rootDecoration;
-}
-
-void QTreeView::setRootIsDecorated(bool show)
-{
- Q_D(QTreeView);
- if (show != d->rootDecoration) {
- d->rootDecoration = show;
- d->viewport->update();
- }
-}
-
-/*!
- \property QTreeView::uniformRowHeights
- \brief whether all items in the treeview have the same height
-
- This property should only be set to true if it is guaranteed that all items
- in the view has the same height. This enables the view to do some
- optimizations.
-
- The height is obtained from the first item in the view. It is updated
- when the data changes on that item.
-
- By default, this property is false.
-*/
-bool QTreeView::uniformRowHeights() const
-{
- Q_D(const QTreeView);
- return d->uniformRowHeights;
-}
-
-void QTreeView::setUniformRowHeights(bool uniform)
-{
- Q_D(QTreeView);
- d->uniformRowHeights = uniform;
-}
-
-/*!
- \property QTreeView::itemsExpandable
- \brief whether the items are expandable by the user.
-
- This property holds whether the user can expand and collapse items
- interactively.
-
- By default, this property is true.
-
-*/
-bool QTreeView::itemsExpandable() const
-{
- Q_D(const QTreeView);
- return d->itemsExpandable;
-}
-
-void QTreeView::setItemsExpandable(bool enable)
-{
- Q_D(QTreeView);
- d->itemsExpandable = enable;
-}
-
-/*!
- \property QTreeView::expandsOnDoubleClick
- \since 4.4
- \brief whether the items can be expanded by double-clicking.
-
- This property holds whether the user can expand and collapse items
- by double-clicking. The default value is true.
-
- \sa itemsExpandable
-*/
-bool QTreeView::expandsOnDoubleClick() const
-{
- Q_D(const QTreeView);
- return d->expandsOnDoubleClick;
-}
-
-void QTreeView::setExpandsOnDoubleClick(bool enable)
-{
- Q_D(QTreeView);
- d->expandsOnDoubleClick = enable;
-}
-
-/*!
- Returns the horizontal position of the \a column in the viewport.
-*/
-int QTreeView::columnViewportPosition(int column) const
-{
- Q_D(const QTreeView);
- return d->header->sectionViewportPosition(column);
-}
-
-/*!
- Returns the width of the \a column.
-
- \sa resizeColumnToContents(), setColumnWidth()
-*/
-int QTreeView::columnWidth(int column) const
-{
- Q_D(const QTreeView);
- return d->header->sectionSize(column);
-}
-
-/*!
- \since 4.2
-
- Sets the width of the given \a column to the \a width specified.
-
- \sa columnWidth(), resizeColumnToContents()
-*/
-void QTreeView::setColumnWidth(int column, int width)
-{
- Q_D(QTreeView);
- d->header->resizeSection(column, width);
-}
-
-/*!
- Returns the column in the tree view whose header covers the \a x
- coordinate given.
-*/
-int QTreeView::columnAt(int x) const
-{
- Q_D(const QTreeView);
- return d->header->logicalIndexAt(x);
-}
-
-/*!
- Returns true if the \a column is hidden; otherwise returns false.
-
- \sa hideColumn(), isRowHidden()
-*/
-bool QTreeView::isColumnHidden(int column) const
-{
- Q_D(const QTreeView);
- return d->header->isSectionHidden(column);
-}
-
-/*!
- If \a hide is true the \a column is hidden, otherwise the \a column is shown.
-
- \sa hideColumn(), setRowHidden()
-*/
-void QTreeView::setColumnHidden(int column, bool hide)
-{
- Q_D(QTreeView);
- if (column < 0 || column >= d->header->count())
- return;
- d->header->setSectionHidden(column, hide);
-}
-
-/*!
- \property QTreeView::headerHidden
- \brief whether the header is shown or not.
- \since 4.4
-
- If this property is true, the header is not shown otherwise it is.
- The default value is false.
-
- \sa header()
-*/
-bool QTreeView::isHeaderHidden() const
-{
- Q_D(const QTreeView);
- return d->header->isHidden();
-}
-
-void QTreeView::setHeaderHidden(bool hide)
-{
- Q_D(QTreeView);
- d->header->setHidden(hide);
-}
-
-/*!
- Returns true if the item in the given \a row of the \a parent is hidden;
- otherwise returns false.
-
- \sa setRowHidden(), isColumnHidden()
-*/
-bool QTreeView::isRowHidden(int row, const QModelIndex &parent) const
-{
- Q_D(const QTreeView);
- if (!d->model)
- return false;
- return d->isRowHidden(d->model->index(row, 0, parent));
-}
-
-/*!
- If \a hide is true the \a row with the given \a parent is hidden, otherwise the \a row is shown.
-
- \sa isRowHidden(), setColumnHidden()
-*/
-void QTreeView::setRowHidden(int row, const QModelIndex &parent, bool hide)
-{
- Q_D(QTreeView);
- if (!d->model)
- return;
- QModelIndex index = d->model->index(row, 0, parent);
- if (!index.isValid())
- return;
-
- if (hide) {
- d->hiddenIndexes.insert(index);
- } else if(d->isPersistent(index)) { //if the index is not persistent, it cannot be in the set
- d->hiddenIndexes.remove(index);
- }
-
- d->doDelayedItemsLayout();
-}
-
-/*!
- \since 4.3
-
- Returns true if the item in first column in the given \a row
- of the \a parent is spanning all the columns; otherwise returns false.
-
- \sa setFirstColumnSpanned()
-*/
-bool QTreeView::isFirstColumnSpanned(int row, const QModelIndex &parent) const
-{
- Q_D(const QTreeView);
- if (d->spanningIndexes.isEmpty() || !d->model)
- return false;
- QModelIndex index = d->model->index(row, 0, parent);
- for (int i = 0; i < d->spanningIndexes.count(); ++i)
- if (d->spanningIndexes.at(i) == index)
- return true;
- return false;
-}
-
-/*!
- \since 4.3
-
- If \a span is true the item in the first column in the \a row
- with the given \a parent is set to span all columns, otherwise all items
- on the \a row are shown.
-
- \sa isFirstColumnSpanned()
-*/
-void QTreeView::setFirstColumnSpanned(int row, const QModelIndex &parent, bool span)
-{
- Q_D(QTreeView);
- if (!d->model)
- return;
- QModelIndex index = d->model->index(row, 0, parent);
- if (!index.isValid())
- return;
-
- if (span) {
- QPersistentModelIndex persistent(index);
- if (!d->spanningIndexes.contains(persistent))
- d->spanningIndexes.append(persistent);
- } else {
- QPersistentModelIndex persistent(index);
- int i = d->spanningIndexes.indexOf(persistent);
- if (i >= 0)
- d->spanningIndexes.remove(i);
- }
-
- d->executePostedLayout();
- int i = d->viewIndex(index);
- if (i >= 0)
- d->viewItems[i].spanning = span;
-
- d->viewport->update();
-}
-
-/*!
- \reimp
-*/
-void QTreeView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- Q_D(QTreeView);
-
- // if we are going to do a complete relayout anyway, there is no need to update
- if (d->delayedPendingLayout)
- return;
-
- // refresh the height cache here; we don't really lose anything by getting the size hint,
- // since QAbstractItemView::dataChanged() will get the visualRect for the items anyway
-
- bool sizeChanged = false;
- int topViewIndex = d->viewIndex(topLeft);
- if (topViewIndex == 0) {
- int newDefaultItemHeight = indexRowSizeHint(topLeft);
- sizeChanged = d->defaultItemHeight != newDefaultItemHeight;
- d->defaultItemHeight = newDefaultItemHeight;
- }
-
- if (topViewIndex != -1) {
- if (topLeft.row() == bottomRight.row()) {
- int oldHeight = d->itemHeight(topViewIndex);
- d->invalidateHeightCache(topViewIndex);
- sizeChanged |= (oldHeight != d->itemHeight(topViewIndex));
- if (topLeft.column() == 0)
- d->viewItems[topViewIndex].hasChildren = d->hasVisibleChildren(topLeft);
- } else {
- int bottomViewIndex = d->viewIndex(bottomRight);
- for (int i = topViewIndex; i <= bottomViewIndex; ++i) {
- int oldHeight = d->itemHeight(i);
- d->invalidateHeightCache(i);
- sizeChanged |= (oldHeight != d->itemHeight(i));
- if (topLeft.column() == 0)
- d->viewItems[i].hasChildren = d->hasVisibleChildren(d->viewItems.at(i).index);
- }
- }
- }
-
- if (sizeChanged) {
- d->updateScrollBars();
- d->viewport->update();
- }
- QAbstractItemView::dataChanged(topLeft, bottomRight);
-}
-
-/*!
- Hides the \a column given.
-
- \note This function should only be called after the model has been
- initialized, as the view needs to know the number of columns in order to
- hide \a column.
-
- \sa showColumn(), setColumnHidden()
-*/
-void QTreeView::hideColumn(int column)
-{
- Q_D(QTreeView);
- d->header->hideSection(column);
-}
-
-/*!
- Shows the given \a column in the tree view.
-
- \sa hideColumn(), setColumnHidden()
-*/
-void QTreeView::showColumn(int column)
-{
- Q_D(QTreeView);
- d->header->showSection(column);
-}
-
-/*!
- \fn void QTreeView::expand(const QModelIndex &index)
-
- Expands the model item specified by the \a index.
-
- \sa expanded()
-*/
-void QTreeView::expand(const QModelIndex &index)
-{
- Q_D(QTreeView);
- if (!d->isIndexValid(index))
- return;
- if (d->delayedPendingLayout) {
- //A complete relayout is going to be performed, just store the expanded index, no need to layout.
- if (d->storeExpanded(index))
- emit expanded(index);
- return;
- }
-
- int i = d->viewIndex(index);
- if (i != -1) { // is visible
- d->expand(i, true);
- if (!d->isAnimating()) {
- updateGeometries();
- d->viewport->update();
- }
- } else if (d->storeExpanded(index)) {
- emit expanded(index);
- }
-}
-
-/*!
- \fn void QTreeView::collapse(const QModelIndex &index)
-
- Collapses the model item specified by the \a index.
-
- \sa collapsed()
-*/
-void QTreeView::collapse(const QModelIndex &index)
-{
- Q_D(QTreeView);
- if (!d->isIndexValid(index))
- return;
- //if the current item is now invisible, the autoscroll will expand the tree to see it, so disable the autoscroll
- d->delayedAutoScroll.stop();
-
- if (d->delayedPendingLayout) {
- //A complete relayout is going to be performed, just un-store the expanded index, no need to layout.
- if (d->isPersistent(index) && d->expandedIndexes.remove(index))
- emit collapsed(index);
- return;
- }
- int i = d->viewIndex(index);
- if (i != -1) { // is visible
- d->collapse(i, true);
- if (!d->isAnimating()) {
- updateGeometries();
- viewport()->update();
- }
- } else {
- if (d->isPersistent(index) && d->expandedIndexes.remove(index))
- emit collapsed(index);
- }
-}
-
-/*!
- \fn bool QTreeView::isExpanded(const QModelIndex &index) const
-
- Returns true if the model item \a index is expanded; otherwise returns
- false.
-
- \sa expand(), expanded(), setExpanded()
-*/
-bool QTreeView::isExpanded(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- return d->isIndexExpanded(index);
-}
-
-/*!
- Sets the item referred to by \a index to either collapse or expanded,
- depending on the value of \a expanded.
-
- \sa expanded(), expand(), isExpanded()
-*/
-void QTreeView::setExpanded(const QModelIndex &index, bool expanded)
-{
- if (expanded)
- this->expand(index);
- else
- this->collapse(index);
-}
-
-/*!
- \since 4.2
- \property QTreeView::sortingEnabled
- \brief whether sorting is enabled
-
- If this property is true, sorting is enabled for the tree; if the property
- is false, sorting is not enabled. The default value is false.
-
- \note In order to avoid performance issues, it is recommended that
- sorting is enabled \e after inserting the items into the tree.
- Alternatively, you could also insert the items into a list before inserting
- the items into the tree.
-
- \sa sortByColumn()
-*/
-
-void QTreeView::setSortingEnabled(bool enable)
-{
- Q_D(QTreeView);
- header()->setSortIndicatorShown(enable);
- header()->setClickable(enable);
- if (enable) {
- //sortByColumn has to be called before we connect or set the sortingEnabled flag
- // because otherwise it will not call sort on the model.
- sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
- connect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(_q_sortIndicatorChanged(int,Qt::SortOrder)), Qt::UniqueConnection);
- } else {
- disconnect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
- this, SLOT(_q_sortIndicatorChanged(int,Qt::SortOrder)));
- }
- d->sortingEnabled = enable;
-}
-
-bool QTreeView::isSortingEnabled() const
-{
- Q_D(const QTreeView);
- return d->sortingEnabled;
-}
-
-/*!
- \since 4.2
- \property QTreeView::animated
- \brief whether animations are enabled
-
- If this property is true the treeview will animate expandsion
- and collasping of branches. If this property is false, the treeview
- will expand or collapse branches immediately without showing
- the animation.
-
- By default, this property is false.
-*/
-
-void QTreeView::setAnimated(bool animate)
-{
- Q_D(QTreeView);
- d->animationsEnabled = animate;
-}
-
-bool QTreeView::isAnimated() const
-{
- Q_D(const QTreeView);
- return d->animationsEnabled;
-}
-
-/*!
- \since 4.2
- \property QTreeView::allColumnsShowFocus
- \brief whether items should show keyboard focus using all columns
-
- If this property is true all columns will show focus, otherwise only
- one column will show focus.
-
- The default is false.
-*/
-
-void QTreeView::setAllColumnsShowFocus(bool enable)
-{
- Q_D(QTreeView);
- if (d->allColumnsShowFocus == enable)
- return;
- d->allColumnsShowFocus = enable;
- d->viewport->update();
-}
-
-bool QTreeView::allColumnsShowFocus() const
-{
- Q_D(const QTreeView);
- return d->allColumnsShowFocus;
-}
-
-/*!
- \property QTreeView::wordWrap
- \brief the item text word-wrapping policy
- \since 4.3
-
- If this property is true then the item text is wrapped where
- necessary at word-breaks; otherwise it is not wrapped at all.
- This property is false by default.
-
- Note that even if wrapping is enabled, the cell will not be
- expanded to fit all text. Ellipsis will be inserted according to
- the current \l{QAbstractItemView::}{textElideMode}.
-*/
-void QTreeView::setWordWrap(bool on)
-{
- Q_D(QTreeView);
- if (d->wrapItemText == on)
- return;
- d->wrapItemText = on;
- d->doDelayedItemsLayout();
-}
-
-bool QTreeView::wordWrap() const
-{
- Q_D(const QTreeView);
- return d->wrapItemText;
-}
-
-
-/*!
- \reimp
- */
-void QTreeView::keyboardSearch(const QString &search)
-{
- Q_D(QTreeView);
- if (!d->model->rowCount(d->root) || !d->model->columnCount(d->root))
- return;
-
- QModelIndex start;
- if (currentIndex().isValid())
- start = currentIndex();
- else
- start = d->model->index(0, 0, d->root);
-
- bool skipRow = false;
- bool keyboardTimeWasValid = d->keyboardInputTime.isValid();
- qint64 keyboardInputTimeElapsed = d->keyboardInputTime.restart();
- if (search.isEmpty() || !keyboardTimeWasValid
- || keyboardInputTimeElapsed > QApplication::keyboardInputInterval()) {
- d->keyboardInput = search;
- skipRow = currentIndex().isValid(); //if it is not valid we should really start at QModelIndex(0,0)
- } else {
- d->keyboardInput += search;
- }
-
- // special case for searches with same key like 'aaaaa'
- bool sameKey = false;
- if (d->keyboardInput.length() > 1) {
- int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1));
- sameKey = (c == d->keyboardInput.length());
- if (sameKey)
- skipRow = true;
- }
-
- // skip if we are searching for the same key or a new search started
- if (skipRow) {
- if (indexBelow(start).isValid())
- start = indexBelow(start);
- else
- start = d->model->index(0, start.column(), d->root);
- }
-
- d->executePostedLayout();
- int startIndex = d->viewIndex(start);
- if (startIndex <= -1)
- return;
-
- int previousLevel = -1;
- int bestAbove = -1;
- int bestBelow = -1;
- QString searchString = sameKey ? QString(d->keyboardInput.at(0)) : d->keyboardInput;
- for (int i = 0; i < d->viewItems.count(); ++i) {
- if ((int)d->viewItems.at(i).level > previousLevel) {
- QModelIndex searchFrom = d->viewItems.at(i).index;
- if (searchFrom.parent() == start.parent())
- searchFrom = start;
- QModelIndexList match = d->model->match(searchFrom, Qt::DisplayRole, searchString);
- if (match.count()) {
- int hitIndex = d->viewIndex(match.at(0));
- if (hitIndex >= 0 && hitIndex < startIndex)
- bestAbove = bestAbove == -1 ? hitIndex : qMin(hitIndex, bestAbove);
- else if (hitIndex >= startIndex)
- bestBelow = bestBelow == -1 ? hitIndex : qMin(hitIndex, bestBelow);
- }
- }
- previousLevel = d->viewItems.at(i).level;
- }
-
- QModelIndex index;
- if (bestBelow > -1)
- index = d->viewItems.at(bestBelow).index;
- else if (bestAbove > -1)
- index = d->viewItems.at(bestAbove).index;
-
- if (index.isValid()) {
- QItemSelectionModel::SelectionFlags flags = (d->selectionMode == SingleSelection
- ? QItemSelectionModel::SelectionFlags(
- QItemSelectionModel::ClearAndSelect
- |d->selectionBehaviorFlags())
- : QItemSelectionModel::SelectionFlags(
- QItemSelectionModel::NoUpdate));
- selectionModel()->setCurrentIndex(index, flags);
- }
-}
-
-/*!
- Returns the rectangle on the viewport occupied by the item at \a index.
- If the index is not visible or explicitly hidden, the returned rectangle is invalid.
-*/
-QRect QTreeView::visualRect(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
-
- if (!d->isIndexValid(index) || isIndexHidden(index))
- return QRect();
-
- d->executePostedLayout();
-
- int vi = d->viewIndex(index);
- if (vi < 0)
- return QRect();
-
- bool spanning = d->viewItems.at(vi).spanning;
-
- // if we have a spanning item, make the selection stretch from left to right
- int x = (spanning ? 0 : columnViewportPosition(index.column()));
- int w = (spanning ? d->header->length() : columnWidth(index.column()));
- // handle indentation
- if (index.column() == 0) {
- int i = d->indentationForItem(vi);
- w -= i;
- if (!isRightToLeft())
- x += i;
- }
-
- int y = d->coordinateForItem(vi);
- int h = d->itemHeight(vi);
-
- return QRect(x, y, w, h);
-}
-
-/*!
- Scroll the contents of the tree view until the given model item
- \a index is visible. The \a hint parameter specifies more
- precisely where the item should be located after the
- operation.
- If any of the parents of the model item are collapsed, they will
- be expanded to ensure that the model item is visible.
-*/
-void QTreeView::scrollTo(const QModelIndex &index, ScrollHint hint)
-{
- Q_D(QTreeView);
-
- if (!d->isIndexValid(index))
- return;
-
- d->executePostedLayout();
- d->updateScrollBars();
-
- // Expand all parents if the parent(s) of the node are not expanded.
- QModelIndex parent = index.parent();
- while (parent.isValid() && state() == NoState && d->itemsExpandable) {
- if (!isExpanded(parent))
- expand(parent);
- parent = d->model->parent(parent);
- }
-
- int item = d->viewIndex(index);
- if (item < 0)
- return;
-
- QRect area = d->viewport->rect();
-
- // vertical
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int top = verticalScrollBar()->value();
- int bottom = top + verticalScrollBar()->pageStep();
- if (hint == EnsureVisible && item >= top && item < bottom) {
- // nothing to do
- } else if (hint == PositionAtTop || (hint == EnsureVisible && item < top)) {
- verticalScrollBar()->setValue(item);
- } else { // PositionAtBottom or PositionAtCenter
- const int currentItemHeight = d->itemHeight(item);
- int y = (hint == PositionAtCenter
- //we center on the current item with a preference to the top item (ie. -1)
- ? area.height() / 2 + currentItemHeight - 1
- //otherwise we simply take the whole space
- : area.height());
- if (y > currentItemHeight) {
- while (item >= 0) {
- y -= d->itemHeight(item);
- if (y < 0) { //there is no more space left
- item++;
- break;
- }
- item--;
- }
- }
- verticalScrollBar()->setValue(item);
- }
- } else { // ScrollPerPixel
- QRect rect(columnViewportPosition(index.column()),
- d->coordinateForItem(item), // ### slow for items outside the view
- columnWidth(index.column()),
- d->itemHeight(item));
-
- if (rect.isEmpty()) {
- // nothing to do
- } else if (hint == EnsureVisible && area.contains(rect)) {
- d->viewport->update(rect);
- // nothing to do
- } else {
- bool above = (hint == EnsureVisible
- && (rect.top() < area.top()
- || area.height() < rect.height()));
- bool below = (hint == EnsureVisible
- && rect.bottom() > area.bottom()
- && rect.height() < area.height());
-
- int verticalValue = verticalScrollBar()->value();
- if (hint == PositionAtTop || above)
- verticalValue += rect.top();
- else if (hint == PositionAtBottom || below)
- verticalValue += rect.bottom() - area.height();
- else if (hint == PositionAtCenter)
- verticalValue += rect.top() - ((area.height() - rect.height()) / 2);
- verticalScrollBar()->setValue(verticalValue);
- }
- }
- // horizontal
- int viewportWidth = d->viewport->width();
- int horizontalOffset = d->header->offset();
- int horizontalPosition = d->header->sectionPosition(index.column());
- int cellWidth = d->header->sectionSize(index.column());
-
- if (hint == PositionAtCenter) {
- horizontalScrollBar()->setValue(horizontalPosition - ((viewportWidth - cellWidth) / 2));
- } else {
- if (horizontalPosition - horizontalOffset < 0 || cellWidth > viewportWidth)
- horizontalScrollBar()->setValue(horizontalPosition);
- else if (horizontalPosition - horizontalOffset + cellWidth > viewportWidth)
- horizontalScrollBar()->setValue(horizontalPosition - viewportWidth + cellWidth);
- }
-}
-
-/*!
- \reimp
-*/
-void QTreeView::timerEvent(QTimerEvent *event)
-{
- Q_D(QTreeView);
- if (event->timerId() == d->columnResizeTimerID) {
- updateGeometries();
- killTimer(d->columnResizeTimerID);
- d->columnResizeTimerID = 0;
- QRect rect;
- int viewportHeight = d->viewport->height();
- int viewportWidth = d->viewport->width();
- for (int i = d->columnsToUpdate.size() - 1; i >= 0; --i) {
- int column = d->columnsToUpdate.at(i);
- int x = columnViewportPosition(column);
- if (isRightToLeft())
- rect |= QRect(0, 0, x + columnWidth(column), viewportHeight);
- else
- rect |= QRect(x, 0, viewportWidth - x, viewportHeight);
- }
- d->viewport->update(rect.normalized());
- d->columnsToUpdate.clear();
- } else if (event->timerId() == d->openTimer.timerId()) {
- QPoint pos = d->viewport->mapFromGlobal(QCursor::pos());
- if (state() == QAbstractItemView::DraggingState
- && d->viewport->rect().contains(pos)) {
- QModelIndex index = indexAt(pos);
- setExpanded(index, !isExpanded(index));
- }
- d->openTimer.stop();
- }
-
- QAbstractItemView::timerEvent(event);
-}
-
-/*!
- \reimp
-*/
-#ifndef QT_NO_DRAGANDDROP
-void QTreeView::dragMoveEvent(QDragMoveEvent *event)
-{
- Q_D(QTreeView);
- if (d->autoExpandDelay >= 0)
- d->openTimer.start(d->autoExpandDelay, this);
- QAbstractItemView::dragMoveEvent(event);
-}
-#endif
-
-/*!
- \reimp
-*/
-bool QTreeView::viewportEvent(QEvent *event)
-{
- Q_D(QTreeView);
- switch (event->type()) {
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove: {
- QHoverEvent *he = static_cast<QHoverEvent*>(event);
- int oldBranch = d->hoverBranch;
- d->hoverBranch = d->itemDecorationAt(he->pos());
- if (oldBranch != d->hoverBranch) {
- //we need to paint the whole items (including the decoration) so that when the user
- //moves the mouse over those elements they are updated
- if (oldBranch >= 0) {
- int y = d->coordinateForItem(oldBranch);
- int h = d->itemHeight(oldBranch);
- viewport()->update(QRect(0, y, viewport()->width(), h));
- }
- if (d->hoverBranch >= 0) {
- int y = d->coordinateForItem(d->hoverBranch);
- int h = d->itemHeight(d->hoverBranch);
- viewport()->update(QRect(0, y, viewport()->width(), h));
- }
- }
- break; }
- default:
- break;
- }
- return QAbstractItemView::viewportEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::paintEvent(QPaintEvent *event)
-{
- Q_D(QTreeView);
- d->executePostedLayout();
- QPainter painter(viewport());
-#ifndef QT_NO_ANIMATION
- if (d->isAnimating()) {
- drawTree(&painter, event->region() - d->animatedOperation.rect());
- d->drawAnimatedOperation(&painter);
- } else
-#endif //QT_NO_ANIMATION
- {
- drawTree(&painter, event->region());
-#ifndef QT_NO_DRAGANDDROP
- d->paintDropIndicator(&painter);
-#endif
- }
-}
-
-void QTreeViewPrivate::paintAlternatingRowColors(QPainter *painter, QStyleOptionViewItemV4 *option, int y, int bottom) const
-{
- Q_Q(const QTreeView);
- if (!alternatingColors || !q->style()->styleHint(QStyle::SH_ItemView_PaintAlternatingRowColorsForEmptyArea, option, q))
- return;
- int rowHeight = defaultItemHeight;
- if (rowHeight <= 0) {
- rowHeight = itemDelegate->sizeHint(*option, QModelIndex()).height();
- if (rowHeight <= 0)
- return;
- }
- while (y <= bottom) {
- option->rect.setRect(0, y, viewport->width(), rowHeight);
- if (current & 1) {
- option->features |= QStyleOptionViewItemV2::Alternate;
- } else {
- option->features &= ~QStyleOptionViewItemV2::Alternate;
- }
- ++current;
- q->style()->drawPrimitive(QStyle::PE_PanelItemViewRow, option, painter, q);
- y += rowHeight;
- }
-}
-
-bool QTreeViewPrivate::expandOrCollapseItemAtPos(const QPoint &pos)
-{
- Q_Q(QTreeView);
- // we want to handle mousePress in EditingState (persistent editors)
- if ((state != QAbstractItemView::NoState
- && state != QAbstractItemView::EditingState)
- || !viewport->rect().contains(pos))
- return true;
-
- int i = itemDecorationAt(pos);
- if ((i != -1) && itemsExpandable && hasVisibleChildren(viewItems.at(i).index)) {
- if (viewItems.at(i).expanded)
- collapse(i, true);
- else
- expand(i, true);
- if (!isAnimating()) {
- q->updateGeometries();
- viewport->update();
- }
- return true;
- }
- return false;
-}
-
-void QTreeViewPrivate::_q_modelDestroyed()
-{
- //we need to clear that list because it contais QModelIndex to
- //the model currently being destroyed
- viewItems.clear();
- QAbstractItemViewPrivate::_q_modelDestroyed();
-}
-
-/*!
- \reimp
-
- We have a QTreeView way of knowing what elements are on the viewport
-*/
-QItemViewPaintPairs QTreeViewPrivate::draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const
-{
- Q_ASSERT(r);
- return QAbstractItemViewPrivate::draggablePaintPairs(indexes, r);
- Q_Q(const QTreeView);
- QRect &rect = *r;
- const QRect viewportRect = viewport->rect();
- int itemOffset = 0;
- int row = firstVisibleItem(&itemOffset);
- QPair<int, int> startEnd = startAndEndColumns(viewportRect);
- QVector<int> columns;
- for (int i = startEnd.first; i <= startEnd.second; ++i) {
- int logical = header->logicalIndex(i);
- if (!header->isSectionHidden(logical))
- columns += logical;
- }
- QSet<QModelIndex> visibleIndexes;
- for (; itemOffset < viewportRect.bottom() && row < viewItems.count(); ++row) {
- const QModelIndex &index = viewItems.at(row).index;
- for (int colIndex = 0; colIndex < columns.count(); ++colIndex)
- visibleIndexes += index.sibling(index.row(), columns.at(colIndex));
- itemOffset += itemHeight(row);
- }
-
- //now that we have the visible indexes, we can try to find those which are selected
- QItemViewPaintPairs ret;
- for (int i = 0; i < indexes.count(); ++i) {
- const QModelIndex &index = indexes.at(i);
- if (visibleIndexes.contains(index)) {
- const QRect current = q->visualRect(index);
- ret += qMakePair(current, index);
- rect |= current;
- }
- }
- rect &= viewportRect;
- return ret;
-}
-
-
-/*!
- \since 4.2
- Draws the part of the tree intersecting the given \a region using the specified
- \a painter.
-
- \sa paintEvent()
-*/
-void QTreeView::drawTree(QPainter *painter, const QRegion &region) const
-{
- Q_D(const QTreeView);
- const QVector<QTreeViewItem> viewItems = d->viewItems;
-
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- const QStyle::State state = option.state;
- d->current = 0;
-
- if (viewItems.count() == 0 || d->header->count() == 0 || !d->itemDelegate) {
- d->paintAlternatingRowColors(painter, &option, 0, region.boundingRect().bottom()+1);
- return;
- }
-
- int firstVisibleItemOffset = 0;
- const int firstVisibleItem = d->firstVisibleItem(&firstVisibleItemOffset);
- if (firstVisibleItem < 0) {
- d->paintAlternatingRowColors(painter, &option, 0, region.boundingRect().bottom()+1);
- return;
- }
-
- const int viewportWidth = d->viewport->width();
-
- QVector<QRect> rects = region.rects();
- QVector<int> drawn;
- bool multipleRects = (rects.size() > 1);
- for (int a = 0; a < rects.size(); ++a) {
- const QRect area = (multipleRects
- ? QRect(0, rects.at(a).y(), viewportWidth, rects.at(a).height())
- : rects.at(a));
- d->leftAndRight = d->startAndEndColumns(area);
-
- int i = firstVisibleItem; // the first item at the top of the viewport
- int y = firstVisibleItemOffset; // we may only see part of the first item
-
- // start at the top of the viewport and iterate down to the update area
- for (; i < viewItems.count(); ++i) {
- const int itemHeight = d->itemHeight(i);
- if (y + itemHeight > area.top())
- break;
- y += itemHeight;
- }
-
- // paint the visible rows
- for (; i < viewItems.count() && y <= area.bottom(); ++i) {
- const int itemHeight = d->itemHeight(i);
- option.rect.setRect(0, y, viewportWidth, itemHeight);
- option.state = state | (viewItems.at(i).expanded ? QStyle::State_Open : QStyle::State_None)
- | (viewItems.at(i).hasChildren ? QStyle::State_Children : QStyle::State_None)
- | (viewItems.at(i).hasMoreSiblings ? QStyle::State_Sibling : QStyle::State_None);
- d->current = i;
- d->spanning = viewItems.at(i).spanning;
- if (!multipleRects || !drawn.contains(i)) {
- drawRow(painter, option, viewItems.at(i).index);
- if (multipleRects) // even if the rect only intersects the item,
- drawn.append(i); // the entire item will be painted
- }
- y += itemHeight;
- }
-
- if (y <= area.bottom()) {
- d->current = i;
- d->paintAlternatingRowColors(painter, &option, y, area.bottom());
- }
- }
-}
-
-/// ### move to QObject :)
-static inline bool ancestorOf(QObject *widget, QObject *other)
-{
- for (QObject *parent = other; parent != 0; parent = parent->parent()) {
- if (parent == widget)
- return true;
- }
- return false;
-}
-
-/*!
- Draws the row in the tree view that contains the model item \a index,
- using the \a painter given. The \a option control how the item is
- displayed.
-
- \sa setAlternatingRowColors()
-*/
-void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- QStyleOptionViewItemV4 opt = option;
- const QPoint offset = d->scrollDelayOffset;
- const int y = option.rect.y() + offset.y();
- const QModelIndex parent = index.parent();
- const QHeaderView *header = d->header;
- const QModelIndex current = currentIndex();
- const QModelIndex hover = d->hover;
- const bool reverse = isRightToLeft();
- const QStyle::State state = opt.state;
- const bool spanning = d->spanning;
- const int left = (spanning ? header->visualIndex(0) : d->leftAndRight.first);
- const int right = (spanning ? header->visualIndex(0) : d->leftAndRight.second);
- const bool alternate = d->alternatingColors;
- const bool enabled = (state & QStyle::State_Enabled) != 0;
- const bool allColumnsShowFocus = d->allColumnsShowFocus;
-
-
- // when the row contains an index widget which has focus,
- // we want to paint the entire row as active
- bool indexWidgetHasFocus = false;
- if ((current.row() == index.row()) && !d->editorIndexHash.isEmpty()) {
- const int r = index.row();
- QWidget *fw = QApplication::focusWidget();
- for (int c = 0; c < header->count(); ++c) {
- QModelIndex idx = d->model->index(r, c, parent);
- if (QWidget *editor = indexWidget(idx)) {
- if (ancestorOf(editor, fw)) {
- indexWidgetHasFocus = true;
- break;
- }
- }
- }
- }
-
- const bool widgetHasFocus = hasFocus();
- bool currentRowHasFocus = false;
- if (allColumnsShowFocus && widgetHasFocus && current.isValid()) {
- // check if the focus index is before or after the visible columns
- const int r = index.row();
- for (int c = 0; c < left && !currentRowHasFocus; ++c) {
- QModelIndex idx = d->model->index(r, c, parent);
- currentRowHasFocus = (idx == current);
- }
- QModelIndex parent = d->model->parent(index);
- for (int c = right; c < header->count() && !currentRowHasFocus; ++c) {
- currentRowHasFocus = (d->model->index(r, c, parent) == current);
- }
- }
-
- // ### special case: treeviews with multiple columns draw
- // the selections differently than with only one column
- opt.showDecorationSelected = (d->selectionBehavior & SelectRows)
- || option.showDecorationSelected;
-
- int width, height = option.rect.height();
- int position;
- QModelIndex modelIndex;
- int columnCount = header->count();
- const bool hoverRow = selectionBehavior() == QAbstractItemView::SelectRows
- && index.parent() == hover.parent()
- && index.row() == hover.row();
-
- /* 'left' and 'right' are the left-most and right-most visible visual indices.
- Compute the first visible logical indices before and after the left and right.
- We will use these values to determine the QStyleOptionViewItemV4::viewItemPosition. */
- int logicalIndexBeforeLeft = -1, logicalIndexAfterRight = -1;
- for (int visualIndex = left - 1; visualIndex >= 0; --visualIndex) {
- int logicalIndex = header->logicalIndex(visualIndex);
- if (!header->isSectionHidden(logicalIndex)) {
- logicalIndexBeforeLeft = logicalIndex;
- break;
- }
- }
- QVector<int> logicalIndices; // vector of currently visibly logical indices
- for (int visualIndex = left; visualIndex < columnCount; ++visualIndex) {
- int logicalIndex = header->logicalIndex(visualIndex);
- if (!header->isSectionHidden(logicalIndex)) {
- if (visualIndex > right) {
- logicalIndexAfterRight = logicalIndex;
- break;
- }
- logicalIndices.append(logicalIndex);
- }
- }
-
- for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices.count(); ++currentLogicalSection) {
- int headerSection = logicalIndices.at(currentLogicalSection);
- position = columnViewportPosition(headerSection) + offset.x();
- width = header->sectionSize(headerSection);
-
- if (spanning) {
- int lastSection = header->logicalIndex(header->count() - 1);
- if (!reverse) {
- width = columnViewportPosition(lastSection) + header->sectionSize(lastSection) - position;
- } else {
- width += position - columnViewportPosition(lastSection);
- position = columnViewportPosition(lastSection);
- }
- }
-
- modelIndex = d->model->index(index.row(), headerSection, parent);
- if (!modelIndex.isValid())
- continue;
- opt.state = state;
-
- // determine the viewItemPosition depending on the position of column 0
- int nextLogicalSection = currentLogicalSection + 1 >= logicalIndices.count()
- ? logicalIndexAfterRight
- : logicalIndices.at(currentLogicalSection + 1);
- int prevLogicalSection = currentLogicalSection - 1 < 0
- ? logicalIndexBeforeLeft
- : logicalIndices.at(currentLogicalSection - 1);
- if (columnCount == 1 || (nextLogicalSection == 0 && prevLogicalSection == -1)
- || (headerSection == 0 && nextLogicalSection == -1) || spanning)
- opt.viewItemPosition = QStyleOptionViewItemV4::OnlyOne;
- else if (headerSection == 0 || (nextLogicalSection != 0 && prevLogicalSection == -1))
- opt.viewItemPosition = QStyleOptionViewItemV4::Beginning;
- else if (nextLogicalSection == 0 || nextLogicalSection == -1)
- opt.viewItemPosition = QStyleOptionViewItemV4::End;
- else
- opt.viewItemPosition = QStyleOptionViewItemV4::Middle;
-
- // fake activeness when row editor has focus
- if (indexWidgetHasFocus)
- opt.state |= QStyle::State_Active;
-
- if (d->selectionModel->isSelected(modelIndex))
- opt.state |= QStyle::State_Selected;
- if (widgetHasFocus && (current == modelIndex)) {
- if (allColumnsShowFocus)
- currentRowHasFocus = true;
- else
- opt.state |= QStyle::State_HasFocus;
- }
- if ((hoverRow || modelIndex == hover)
- && (option.showDecorationSelected || (d->hoverBranch == -1)))
- opt.state |= QStyle::State_MouseOver;
- else
- opt.state &= ~QStyle::State_MouseOver;
-
- if (enabled) {
- QPalette::ColorGroup cg;
- if ((d->model->flags(modelIndex) & Qt::ItemIsEnabled) == 0) {
- opt.state &= ~QStyle::State_Enabled;
- cg = QPalette::Disabled;
- } else if (opt.state & QStyle::State_Active) {
- cg = QPalette::Active;
- } else {
- cg = QPalette::Inactive;
- }
- opt.palette.setCurrentColorGroup(cg);
- }
-
- if (alternate) {
- if (d->current & 1) {
- opt.features |= QStyleOptionViewItemV2::Alternate;
- } else {
- opt.features &= ~QStyleOptionViewItemV2::Alternate;
- }
- }
-
- /* Prior to Qt 4.3, the background of the branch (in selected state and
- alternate row color was provided by the view. For backward compatibility,
- this is now delegated to the style using PE_PanelViewItemRow which
- does the appropriate fill */
- if (headerSection == 0) {
- const int i = d->indentationForItem(d->current);
- QRect branches(reverse ? position + width - i : position, y, i, height);
- const bool setClipRect = branches.width() > width;
- if (setClipRect) {
- painter->save();
- painter->setClipRect(QRect(position, y, width, height));
- }
- // draw background for the branch (selection + alternate row)
- opt.rect = branches;
- style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this);
-
- // draw background of the item (only alternate row). rest of the background
- // is provided by the delegate
- QStyle::State oldState = opt.state;
- opt.state &= ~QStyle::State_Selected;
- opt.rect.setRect(reverse ? position : i + position, y, width - i, height);
- style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this);
- opt.state = oldState;
-
- drawBranches(painter, branches, index);
- if (setClipRect)
- painter->restore();
- } else {
- QStyle::State oldState = opt.state;
- opt.state &= ~QStyle::State_Selected;
- opt.rect.setRect(position, y, width, height);
- style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this);
- opt.state = oldState;
- }
-
- d->delegateForIndex(modelIndex)->paint(painter, opt, modelIndex);
- }
-
- if (currentRowHasFocus) {
- QStyleOptionFocusRect o;
- o.QStyleOption::operator=(option);
- o.state |= QStyle::State_KeyboardFocusChange;
- QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled)
- ? QPalette::Normal : QPalette::Disabled;
- o.backgroundColor = option.palette.color(cg, d->selectionModel->isSelected(index)
- ? QPalette::Highlight : QPalette::Background);
- int x = 0;
- if (!option.showDecorationSelected)
- x = header->sectionPosition(0) + d->indentationForItem(d->current);
- QRect focusRect(x - header->offset(), y, header->length() - x, height);
- o.rect = style()->visualRect(layoutDirection(), d->viewport->rect(), focusRect);
- style()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter);
- // if we show focus on all columns and the first section is moved,
- // we have to split the focus rect into two rects
- if (allColumnsShowFocus && !option.showDecorationSelected
- && header->sectionsMoved() && (header->visualIndex(0) != 0)) {
- QRect sectionRect(0, y, header->sectionPosition(0), height);
- o.rect = style()->visualRect(layoutDirection(), d->viewport->rect(), sectionRect);
- style()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter);
- }
- }
-}
-
-/*!
- Draws the branches in the tree view on the same row as the model item
- \a index, using the \a painter given. The branches are drawn in the
- rectangle specified by \a rect.
-*/
-void QTreeView::drawBranches(QPainter *painter, const QRect &rect,
- const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- const bool reverse = isRightToLeft();
- const int indent = d->indent;
- const int outer = d->rootDecoration ? 0 : 1;
- const int item = d->current;
- const QTreeViewItem &viewItem = d->viewItems.at(item);
- int level = viewItem.level;
- QRect primitive(reverse ? rect.left() : rect.right() + 1, rect.top(), indent, rect.height());
-
- QModelIndex parent = index.parent();
- QModelIndex current = parent;
- QModelIndex ancestor = current.parent();
-
- QStyleOptionViewItemV2 opt = viewOptions();
- QStyle::State extraFlags = QStyle::State_None;
- if (isEnabled())
- extraFlags |= QStyle::State_Enabled;
- if (window()->isActiveWindow())
- extraFlags |= QStyle::State_Active;
- QPoint oldBO = painter->brushOrigin();
- if (verticalScrollMode() == QAbstractItemView::ScrollPerPixel)
- painter->setBrushOrigin(QPoint(0, verticalOffset()));
-
- if (d->alternatingColors) {
- if (d->current & 1) {
- opt.features |= QStyleOptionViewItemV2::Alternate;
- } else {
- opt.features &= ~QStyleOptionViewItemV2::Alternate;
- }
- }
-
- // When hovering over a row, pass State_Hover for painting the branch
- // indicators if it has the decoration (aka branch) selected.
- bool hoverRow = selectionBehavior() == QAbstractItemView::SelectRows
- && opt.showDecorationSelected
- && index.parent() == d->hover.parent()
- && index.row() == d->hover.row();
-
- if (d->selectionModel->isSelected(index))
- extraFlags |= QStyle::State_Selected;
-
- if (level >= outer) {
- // start with the innermost branch
- primitive.moveLeft(reverse ? primitive.left() : primitive.left() - indent);
- opt.rect = primitive;
-
- const bool expanded = viewItem.expanded;
- const bool children = viewItem.hasChildren;
- bool moreSiblings = viewItem.hasMoreSiblings;
-
- opt.state = QStyle::State_Item | extraFlags
- | (moreSiblings ? QStyle::State_Sibling : QStyle::State_None)
- | (children ? QStyle::State_Children : QStyle::State_None)
- | (expanded ? QStyle::State_Open : QStyle::State_None);
- if (hoverRow || item == d->hoverBranch)
- opt.state |= QStyle::State_MouseOver;
- else
- opt.state &= ~QStyle::State_MouseOver;
- style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, painter, this);
- }
- // then go out level by level
- for (--level; level >= outer; --level) { // we have already drawn the innermost branch
- primitive.moveLeft(reverse ? primitive.left() + indent : primitive.left() - indent);
- opt.rect = primitive;
- opt.state = extraFlags;
- bool moreSiblings = false;
- if (d->hiddenIndexes.isEmpty()) {
- moreSiblings = (d->model->rowCount(ancestor) - 1 > current.row());
- } else {
- int successor = item + viewItem.total + 1;
- while (successor < d->viewItems.size()
- && d->viewItems.at(successor).level >= uint(level)) {
- const QTreeViewItem &successorItem = d->viewItems.at(successor);
- if (successorItem.level == uint(level)) {
- moreSiblings = true;
- break;
- }
- successor += successorItem.total + 1;
- }
- }
- if (moreSiblings)
- opt.state |= QStyle::State_Sibling;
- if (hoverRow || item == d->hoverBranch)
- opt.state |= QStyle::State_MouseOver;
- else
- opt.state &= ~QStyle::State_MouseOver;
- style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, painter, this);
- current = ancestor;
- ancestor = current.parent();
- }
- painter->setBrushOrigin(oldBO);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QTreeView);
- bool handled = false;
- if (style()->styleHint(QStyle::SH_Q3ListViewExpand_SelectMouseType, 0, this) == QEvent::MouseButtonPress)
- handled = d->expandOrCollapseItemAtPos(event->pos());
- if (!handled && d->itemDecorationAt(event->pos()) == -1)
- QAbstractItemView::mousePressEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QTreeView);
- if (d->itemDecorationAt(event->pos()) == -1) {
- QAbstractItemView::mouseReleaseEvent(event);
- } else {
- if (state() == QAbstractItemView::DragSelectingState)
- setState(QAbstractItemView::NoState);
- if (style()->styleHint(QStyle::SH_Q3ListViewExpand_SelectMouseType, 0, this) == QEvent::MouseButtonRelease)
- d->expandOrCollapseItemAtPos(event->pos());
- }
-}
-
-/*!
- \reimp
-*/
-void QTreeView::mouseDoubleClickEvent(QMouseEvent *event)
-{
- Q_D(QTreeView);
- if (state() != NoState || !d->viewport->rect().contains(event->pos()))
- return;
-
- int i = d->itemDecorationAt(event->pos());
- if (i == -1) {
- i = d->itemAtCoordinate(event->y());
- if (i == -1)
- return; // user clicked outside the items
-
- const QPersistentModelIndex firstColumnIndex = d->viewItems.at(i).index;
- const QPersistentModelIndex persistent = indexAt(event->pos());
-
- if (d->pressedIndex != persistent) {
- mousePressEvent(event);
- return;
- }
-
- // signal handlers may change the model
- emit doubleClicked(persistent);
-
- if (!persistent.isValid())
- return;
-
- if (edit(persistent, DoubleClicked, event) || state() != NoState)
- return; // the double click triggered editing
-
- if (!style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, this))
- emit activated(persistent);
-
- d->executePostedLayout(); // we need to make sure viewItems is updated
- if (d->itemsExpandable
- && d->expandsOnDoubleClick
- && d->hasVisibleChildren(persistent)) {
- if (!((i < d->viewItems.count()) && (d->viewItems.at(i).index == firstColumnIndex))) {
- // find the new index of the item
- for (i = 0; i < d->viewItems.count(); ++i) {
- if (d->viewItems.at(i).index == firstColumnIndex)
- break;
- }
- if (i == d->viewItems.count())
- return;
- }
- if (d->viewItems.at(i).expanded)
- d->collapse(i, true);
- else
- d->expand(i, true);
- updateGeometries();
- viewport()->update();
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QTreeView::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QTreeView);
- if (d->itemDecorationAt(event->pos()) == -1) // ### what about expanding/collapsing state ?
- QAbstractItemView::mouseMoveEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QTreeView);
- QModelIndex current = currentIndex();
- //this is the management of the expansion
- if (d->isIndexValid(current) && d->model && d->itemsExpandable) {
- switch (event->key()) {
- case Qt::Key_Asterisk: {
- QStack<QModelIndex> parents;
- parents.push(current);
- while (!parents.isEmpty()) {
- QModelIndex parent = parents.pop();
- for (int row = 0; row < d->model->rowCount(parent); ++row) {
- QModelIndex child = d->model->index(row, 0, parent);
- if (!d->isIndexValid(child))
- break;
- parents.push(child);
- expand(child);
- }
- }
- expand(current);
- break; }
- case Qt::Key_Plus:
- expand(current);
- break;
- case Qt::Key_Minus:
- collapse(current);
- break;
- }
- }
-
- QAbstractItemView::keyPressEvent(event);
-}
-
-/*!
- \reimp
-*/
-QModelIndex QTreeView::indexAt(const QPoint &point) const
-{
- Q_D(const QTreeView);
- d->executePostedLayout();
-
- int visualIndex = d->itemAtCoordinate(point.y());
- QModelIndex idx = d->modelIndex(visualIndex);
- if (!idx.isValid())
- return QModelIndex();
-
- if (d->viewItems.at(visualIndex).spanning)
- return idx;
-
- int column = d->columnAt(point.x());
- if (column == idx.column())
- return idx;
- if (column < 0)
- return QModelIndex();
- return idx.sibling(idx.row(), column);
-}
-
-/*!
- Returns the model index of the item above \a index.
-*/
-QModelIndex QTreeView::indexAbove(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- if (!d->isIndexValid(index))
- return QModelIndex();
- d->executePostedLayout();
- int i = d->viewIndex(index);
- if (--i < 0)
- return QModelIndex();
- return d->viewItems.at(i).index;
-}
-
-/*!
- Returns the model index of the item below \a index.
-*/
-QModelIndex QTreeView::indexBelow(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- if (!d->isIndexValid(index))
- return QModelIndex();
- d->executePostedLayout();
- int i = d->viewIndex(index);
- if (++i >= d->viewItems.count())
- return QModelIndex();
- return d->viewItems.at(i).index;
-}
-
-/*!
- \internal
-
- Lays out the items in the tree view.
-*/
-void QTreeView::doItemsLayout()
-{
- Q_D(QTreeView);
- if (d->hasRemovedItems) {
- //clean the QSet that may contains old (and this invalid) indexes
- d->hasRemovedItems = false;
- QSet<QPersistentModelIndex>::iterator it = d->expandedIndexes.begin();
- while (it != d->expandedIndexes.constEnd()) {
- if (!it->isValid())
- it = d->expandedIndexes.erase(it);
- else
- ++it;
- }
- it = d->hiddenIndexes.begin();
- while (it != d->hiddenIndexes.constEnd()) {
- if (!it->isValid())
- it = d->hiddenIndexes.erase(it);
- else
- ++it;
- }
- }
- d->viewItems.clear(); // prepare for new layout
- QModelIndex parent = d->root;
- if (d->model->hasChildren(parent)) {
- d->layout(-1);
- }
- QAbstractItemView::doItemsLayout();
- d->header->doItemsLayout();
-}
-
-/*!
- \reimp
-*/
-void QTreeView::reset()
-{
- Q_D(QTreeView);
- d->expandedIndexes.clear();
- d->hiddenIndexes.clear();
- d->spanningIndexes.clear();
- d->viewItems.clear();
- QAbstractItemView::reset();
-}
-
-/*!
- Returns the horizontal offset of the items in the treeview.
-
- Note that the tree view uses the horizontal header section
- positions to determine the positions of columns in the view.
-
- \sa verticalOffset()
-*/
-int QTreeView::horizontalOffset() const
-{
- Q_D(const QTreeView);
- return d->header->offset();
-}
-
-/*!
- Returns the vertical offset of the items in the tree view.
-
- \sa horizontalOffset()
-*/
-int QTreeView::verticalOffset() const
-{
- Q_D(const QTreeView);
- if (d->verticalScrollMode == QAbstractItemView::ScrollPerItem) {
- if (d->uniformRowHeights)
- return verticalScrollBar()->value() * d->defaultItemHeight;
- // If we are scrolling per item and have non-uniform row heights,
- // finding the vertical offset in pixels is going to be relatively slow.
- // ### find a faster way to do this
- d->executePostedLayout();
- int offset = 0;
- for (int i = 0; i < d->viewItems.count(); ++i) {
- if (i == verticalScrollBar()->value())
- return offset;
- offset += d->itemHeight(i);
- }
- return 0;
- }
- // scroll per pixel
- return verticalScrollBar()->value();
-}
-
-/*!
- Move the cursor in the way described by \a cursorAction, using the
- information provided by the button \a modifiers.
-*/
-QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
-{
- Q_D(QTreeView);
- Q_UNUSED(modifiers);
-
- d->executePostedLayout();
-
- QModelIndex current = currentIndex();
- if (!current.isValid()) {
- int i = d->below(-1);
- int c = 0;
- while (c < d->header->count() && d->header->isSectionHidden(c))
- ++c;
- if (i < d->viewItems.count() && c < d->header->count()) {
- return d->modelIndex(i, c);
- }
- return QModelIndex();
- }
- int vi = -1;
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- // Selection behavior is slightly different on the Mac.
- if (d->selectionMode == QAbstractItemView::ExtendedSelection
- && d->selectionModel
- && d->selectionModel->hasSelection()) {
-
- const bool moveUpDown = (cursorAction == MoveUp || cursorAction == MoveDown);
- const bool moveNextPrev = (cursorAction == MoveNext || cursorAction == MovePrevious);
- const bool contiguousSelection = moveUpDown && (modifiers & Qt::ShiftModifier);
-
- // Use the outermost index in the selection as the current index
- if (!contiguousSelection && (moveUpDown || moveNextPrev)) {
-
- // Find outermost index.
- const bool useTopIndex = (cursorAction == MoveUp || cursorAction == MovePrevious);
- int index = useTopIndex ? INT_MAX : INT_MIN;
- const QItemSelection selection = d->selectionModel->selection();
- for (int i = 0; i < selection.count(); ++i) {
- const QItemSelectionRange &range = selection.at(i);
- int candidate = d->viewIndex(useTopIndex ? range.topLeft() : range.bottomRight());
- if (candidate >= 0)
- index = useTopIndex ? qMin(index, candidate) : qMax(index, candidate);
- }
-
- if (index >= 0 && index < INT_MAX)
- vi = index;
- }
- }
-#endif
- if (vi < 0)
- vi = qMax(0, d->viewIndex(current));
-
- if (isRightToLeft()) {
- if (cursorAction == MoveRight)
- cursorAction = MoveLeft;
- else if (cursorAction == MoveLeft)
- cursorAction = MoveRight;
- }
- switch (cursorAction) {
- case MoveNext:
- case MoveDown:
-#ifdef QT_KEYPAD_NAVIGATION
- if (vi == d->viewItems.count()-1 && QApplication::keypadNavigationEnabled())
- return d->model->index(0, current.column(), d->root);
-#endif
- return d->modelIndex(d->below(vi), current.column());
- case MovePrevious:
- case MoveUp:
-#ifdef QT_KEYPAD_NAVIGATION
- if (vi == 0 && QApplication::keypadNavigationEnabled())
- return d->modelIndex(d->viewItems.count() - 1, current.column());
-#endif
- return d->modelIndex(d->above(vi), current.column());
- case MoveLeft: {
- QScrollBar *sb = horizontalScrollBar();
- if (vi < d->viewItems.count() && d->viewItems.at(vi).expanded && d->itemsExpandable && sb->value() == sb->minimum()) {
- d->collapse(vi, true);
- d->moveCursorUpdatedView = true;
- } else {
- bool descend = style()->styleHint(QStyle::SH_ItemView_ArrowKeysNavigateIntoChildren, 0, this);
- if (descend) {
- QModelIndex par = current.parent();
- if (par.isValid() && par != rootIndex())
- return par;
- else
- descend = false;
- }
- if (!descend) {
- if (d->selectionBehavior == SelectItems || d->selectionBehavior == SelectColumns) {
- int visualColumn = d->header->visualIndex(current.column()) - 1;
- while (visualColumn >= 0 && isColumnHidden(d->header->logicalIndex(visualColumn)))
- visualColumn--;
- int newColumn = d->header->logicalIndex(visualColumn);
- QModelIndex next = current.sibling(current.row(), newColumn);
- if (next.isValid())
- return next;
- }
-
- int oldValue = sb->value();
- sb->setValue(sb->value() - sb->singleStep());
- if (oldValue != sb->value())
- d->moveCursorUpdatedView = true;
- }
-
- }
- updateGeometries();
- viewport()->update();
- break;
- }
- case MoveRight:
- if (vi < d->viewItems.count() && !d->viewItems.at(vi).expanded && d->itemsExpandable
- && d->hasVisibleChildren(d->viewItems.at(vi).index)) {
- d->expand(vi, true);
- d->moveCursorUpdatedView = true;
- } else {
- bool descend = style()->styleHint(QStyle::SH_ItemView_ArrowKeysNavigateIntoChildren, 0, this);
- if (descend) {
- QModelIndex idx = d->modelIndex(d->below(vi));
- if (idx.parent() == current)
- return idx;
- else
- descend = false;
- }
- if (!descend) {
- if (d->selectionBehavior == SelectItems || d->selectionBehavior == SelectColumns) {
- int visualColumn = d->header->visualIndex(current.column()) + 1;
- while (visualColumn < d->model->columnCount(current.parent()) && isColumnHidden(d->header->logicalIndex(visualColumn)))
- visualColumn++;
-
- QModelIndex next = current.sibling(current.row(), visualColumn);
- if (next.isValid())
- return next;
- }
-
- //last restort: we change the scrollbar value
- QScrollBar *sb = horizontalScrollBar();
- int oldValue = sb->value();
- sb->setValue(sb->value() + sb->singleStep());
- if (oldValue != sb->value())
- d->moveCursorUpdatedView = true;
- }
- }
- updateGeometries();
- viewport()->update();
- break;
- case MovePageUp:
- return d->modelIndex(d->pageUp(vi), current.column());
- case MovePageDown:
- return d->modelIndex(d->pageDown(vi), current.column());
- case MoveHome:
- return d->model->index(0, current.column(), d->root);
- case MoveEnd:
- return d->modelIndex(d->viewItems.count() - 1, current.column());
- }
- return current;
-}
-
-/*!
- Applies the selection \a command to the items in or touched by the
- rectangle, \a rect.
-
- \sa selectionCommand()
-*/
-void QTreeView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QTreeView);
- if (!selectionModel() || rect.isNull())
- return;
-
- d->executePostedLayout();
- QPoint tl(isRightToLeft() ? qMax(rect.left(), rect.right())
- : qMin(rect.left(), rect.right()), qMin(rect.top(), rect.bottom()));
- QPoint br(isRightToLeft() ? qMin(rect.left(), rect.right()) :
- qMax(rect.left(), rect.right()), qMax(rect.top(), rect.bottom()));
- QModelIndex topLeft = indexAt(tl);
- QModelIndex bottomRight = indexAt(br);
- if (!topLeft.isValid() && !bottomRight.isValid()) {
- if (command & QItemSelectionModel::Clear)
- selectionModel()->clear();
- return;
- }
- if (!topLeft.isValid() && !d->viewItems.isEmpty())
- topLeft = d->viewItems.first().index;
- if (!bottomRight.isValid() && !d->viewItems.isEmpty()) {
- const int column = d->header->logicalIndex(d->header->count() - 1);
- const QModelIndex index = d->viewItems.last().index;
- bottomRight = index.sibling(index.row(), column);
- }
-
- if (!d->isIndexEnabled(topLeft) || !d->isIndexEnabled(bottomRight))
- return;
-
- d->select(topLeft, bottomRight, command);
-}
-
-/*!
- Returns the rectangle from the viewport of the items in the given
- \a selection.
-
- Since 4.7, the returned region only contains rectangles intersecting
- (or included in) the viewport.
-*/
-QRegion QTreeView::visualRegionForSelection(const QItemSelection &selection) const
-{
- Q_D(const QTreeView);
- if (selection.isEmpty())
- return QRegion();
-
- QRegion selectionRegion;
- const QRect &viewportRect = d->viewport->rect();
- for (int i = 0; i < selection.count(); ++i) {
- QItemSelectionRange range = selection.at(i);
- if (!range.isValid())
- continue;
- QModelIndex parent = range.parent();
- QModelIndex leftIndex = range.topLeft();
- int columnCount = d->model->columnCount(parent);
- while (leftIndex.isValid() && isIndexHidden(leftIndex)) {
- if (leftIndex.column() + 1 < columnCount)
- leftIndex = d->model->index(leftIndex.row(), leftIndex.column() + 1, parent);
- else
- leftIndex = QModelIndex();
- }
- if (!leftIndex.isValid())
- continue;
- const QRect leftRect = visualRect(leftIndex);
- int top = leftRect.top();
- QModelIndex rightIndex = range.bottomRight();
- while (rightIndex.isValid() && isIndexHidden(rightIndex)) {
- if (rightIndex.column() - 1 >= 0)
- rightIndex = d->model->index(rightIndex.row(), rightIndex.column() - 1, parent);
- else
- rightIndex = QModelIndex();
- }
- if (!rightIndex.isValid())
- continue;
- const QRect rightRect = visualRect(rightIndex);
- int bottom = rightRect.bottom();
- if (top > bottom)
- qSwap<int>(top, bottom);
- int height = bottom - top + 1;
- if (d->header->sectionsMoved()) {
- for (int c = range.left(); c <= range.right(); ++c) {
- const QRect rangeRect(columnViewportPosition(c), top, columnWidth(c), height);
- if (viewportRect.intersects(rangeRect))
- selectionRegion += rangeRect;
- }
- } else {
- QRect combined = leftRect|rightRect;
- combined.setX(columnViewportPosition(isRightToLeft() ? range.right() : range.left()));
- if (viewportRect.intersects(combined))
- selectionRegion += combined;
- }
- }
- return selectionRegion;
-}
-
-/*!
- \reimp
-*/
-QModelIndexList QTreeView::selectedIndexes() const
-{
- QModelIndexList viewSelected;
- QModelIndexList modelSelected;
- if (selectionModel())
- modelSelected = selectionModel()->selectedIndexes();
- for (int i = 0; i < modelSelected.count(); ++i) {
- // check that neither the parents nor the index is hidden before we add
- QModelIndex index = modelSelected.at(i);
- while (index.isValid() && !isIndexHidden(index))
- index = index.parent();
- if (index.isValid())
- continue;
- viewSelected.append(modelSelected.at(i));
- }
- return viewSelected;
-}
-
-/*!
- Scrolls the contents of the tree view by (\a dx, \a dy).
-*/
-void QTreeView::scrollContentsBy(int dx, int dy)
-{
- Q_D(QTreeView);
-
- d->delayedAutoScroll.stop(); // auto scroll was canceled by the user scrolling
-
- dx = isRightToLeft() ? -dx : dx;
- if (dx) {
- if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int oldOffset = d->header->offset();
- if (horizontalScrollBar()->value() == horizontalScrollBar()->maximum())
- d->header->setOffsetToLastSection();
- else
- d->header->setOffsetToSectionPosition(horizontalScrollBar()->value());
- int newOffset = d->header->offset();
- dx = isRightToLeft() ? newOffset - oldOffset : oldOffset - newOffset;
- } else {
- d->header->setOffset(horizontalScrollBar()->value());
- }
- }
-
- const int itemHeight = d->defaultItemHeight <= 0 ? sizeHintForRow(0) : d->defaultItemHeight;
- if (d->viewItems.isEmpty() || itemHeight == 0)
- return;
-
- // guestimate the number of items in the viewport
- int viewCount = d->viewport->height() / itemHeight;
- int maxDeltaY = qMin(d->viewItems.count(), viewCount);
- // no need to do a lot of work if we are going to redraw the whole thing anyway
- if (qAbs(dy) > qAbs(maxDeltaY) && d->editorIndexHash.isEmpty()) {
- verticalScrollBar()->update();
- d->viewport->update();
- return;
- }
-
- if (dy && verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int currentScrollbarValue = verticalScrollBar()->value();
- int previousScrollbarValue = currentScrollbarValue + dy; // -(-dy)
- int currentViewIndex = currentScrollbarValue; // the first visible item
- int previousViewIndex = previousScrollbarValue;
- const QVector<QTreeViewItem> viewItems = d->viewItems;
- dy = 0;
- if (previousViewIndex < currentViewIndex) { // scrolling down
- for (int i = previousViewIndex; i < currentViewIndex; ++i) {
- if (i < d->viewItems.count())
- dy -= d->itemHeight(i);
- }
- } else if (previousViewIndex > currentViewIndex) { // scrolling up
- for (int i = previousViewIndex - 1; i >= currentViewIndex; --i) {
- if (i < d->viewItems.count())
- dy += d->itemHeight(i);
- }
- }
- }
-
- d->scrollContentsBy(dx, dy);
-}
-
-/*!
- This slot is called whenever a column has been moved.
-*/
-void QTreeView::columnMoved()
-{
- Q_D(QTreeView);
- updateEditorGeometries();
- d->viewport->update();
-}
-
-/*!
- \internal
-*/
-void QTreeView::reexpand()
-{
- // do nothing
-}
-
-/*!
- Informs the view that the rows from the \a start row to the \a end row
- inclusive have been inserted into the \a parent model item.
-*/
-void QTreeView::rowsInserted(const QModelIndex &parent, int start, int end)
-{
- Q_D(QTreeView);
- // if we are going to do a complete relayout anyway, there is no need to update
- if (d->delayedPendingLayout) {
- QAbstractItemView::rowsInserted(parent, start, end);
- return;
- }
-
- //don't add a hierarchy on a column != 0
- if (parent.column() != 0 && parent.isValid()) {
- QAbstractItemView::rowsInserted(parent, start, end);
- return;
- }
-
- const int parentRowCount = d->model->rowCount(parent);
- const int delta = end - start + 1;
- if (parent != d->root && !d->isIndexExpanded(parent) && parentRowCount > delta) {
- QAbstractItemView::rowsInserted(parent, start, end);
- return;
- }
-
- const int parentItem = d->viewIndex(parent);
- if (((parentItem != -1) && d->viewItems.at(parentItem).expanded)
- || (parent == d->root)) {
- d->doDelayedItemsLayout();
- } else if (parentItem != -1 && (d->model->rowCount(parent) == end - start + 1)) {
- // the parent just went from 0 children to more. update to re-paint the decoration
- d->viewItems[parentItem].hasChildren = true;
- viewport()->update();
- }
- QAbstractItemView::rowsInserted(parent, start, end);
-}
-
-/*!
- Informs the view that the rows from the \a start row to the \a end row
- inclusive are about to removed from the given \a parent model item.
-*/
-void QTreeView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
-{
- Q_D(QTreeView);
- QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
- d->viewItems.clear();
-}
-
-/*!
- \since 4.1
-
- Informs the view that the rows from the \a start row to the \a end row
- inclusive have been removed from the given \a parent model item.
-*/
-void QTreeView::rowsRemoved(const QModelIndex &parent, int start, int end)
-{
- Q_D(QTreeView);
- d->viewItems.clear();
- d->doDelayedItemsLayout();
- d->hasRemovedItems = true;
- d->_q_rowsRemoved(parent, start, end);
-}
-
-/*!
- Informs the tree view that the number of columns in the tree view has
- changed from \a oldCount to \a newCount.
-*/
-void QTreeView::columnCountChanged(int oldCount, int newCount)
-{
- Q_D(QTreeView);
- if (oldCount == 0 && newCount > 0) {
- //if the first column has just been added we need to relayout.
- d->doDelayedItemsLayout();
- }
-
- if (isVisible())
- updateGeometries();
- viewport()->update();
-}
-
-/*!
- Resizes the \a column given to the size of its contents.
-
- \sa columnWidth(), setColumnWidth()
-*/
-void QTreeView::resizeColumnToContents(int column)
-{
- Q_D(QTreeView);
- d->executePostedLayout();
- if (column < 0 || column >= d->header->count())
- return;
- int contents = sizeHintForColumn(column);
- int header = d->header->isHidden() ? 0 : d->header->sectionSizeHint(column);
- d->header->resizeSection(column, qMax(contents, header));
-}
-
-/*!
- \obsolete
- \overload
-
- Sorts the model by the values in the given \a column.
-*/
-void QTreeView::sortByColumn(int column)
-{
- Q_D(QTreeView);
- sortByColumn(column, d->header->sortIndicatorOrder());
-}
-
-/*!
- \since 4.2
-
- Sets the model up for sorting by the values in the given \a column and \a order.
-
- \a column may be -1, in which case no sort indicator will be shown
- and the model will return to its natural, unsorted order. Note that not
- all models support this and may even crash in this case.
-
- \sa sortingEnabled
-*/
-void QTreeView::sortByColumn(int column, Qt::SortOrder order)
-{
- Q_D(QTreeView);
-
- //If sorting is enabled will emit a signal connected to _q_sortIndicatorChanged, which then actually sorts
- d->header->setSortIndicator(column, order);
- //If sorting is not enabled, force to sort now.
- if (!d->sortingEnabled)
- d->model->sort(column, order);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::selectAll()
-{
- Q_D(QTreeView);
- if (!selectionModel())
- return;
- SelectionMode mode = d->selectionMode;
- d->executePostedLayout(); //make sure we lay out the items
- if (mode != SingleSelection && !d->viewItems.isEmpty()) {
- const QModelIndex &idx = d->viewItems.last().index;
- QModelIndex lastItemIndex = idx.sibling(idx.row(), d->model->columnCount(idx.parent()) - 1);
- d->select(d->viewItems.first().index, lastItemIndex,
- QItemSelectionModel::ClearAndSelect
- |QItemSelectionModel::Rows);
- }
-}
-
-/*!
- \since 4.2
- Expands all expandable items.
-
- Warning: if the model contains a large number of items,
- this function will take some time to execute.
-
- \sa collapseAll() expand() collapse() setExpanded()
-*/
-void QTreeView::expandAll()
-{
- Q_D(QTreeView);
- d->viewItems.clear();
- d->interruptDelayedItemsLayout();
- d->layout(-1, true);
- updateGeometries();
- d->viewport->update();
-}
-
-/*!
- \since 4.2
-
- Collapses all expanded items.
-
- \sa expandAll() expand() collapse() setExpanded()
-*/
-void QTreeView::collapseAll()
-{
- Q_D(QTreeView);
- d->expandedIndexes.clear();
- doItemsLayout();
-}
-
-/*!
- \since 4.3
- Expands all expandable items to the given \a depth.
-
- \sa expandAll() collapseAll() expand() collapse() setExpanded()
-*/
-void QTreeView::expandToDepth(int depth)
-{
- Q_D(QTreeView);
- d->viewItems.clear();
- d->expandedIndexes.clear();
- d->interruptDelayedItemsLayout();
- d->layout(-1);
- for (int i = 0; i < d->viewItems.count(); ++i) {
- if (d->viewItems.at(i).level <= (uint)depth) {
- d->viewItems[i].expanded = true;
- d->layout(i);
- d->storeExpanded(d->viewItems.at(i).index);
- }
- }
- updateGeometries();
- d->viewport->update();
-}
-
-/*!
- This function is called whenever \a{column}'s size is changed in
- the header. \a oldSize and \a newSize give the previous size and
- the new size in pixels.
-
- \sa setColumnWidth()
-*/
-void QTreeView::columnResized(int column, int /* oldSize */, int /* newSize */)
-{
- Q_D(QTreeView);
- d->columnsToUpdate.append(column);
- if (d->columnResizeTimerID == 0)
- d->columnResizeTimerID = startTimer(0);
-}
-
-/*!
- \reimp
-*/
-void QTreeView::updateGeometries()
-{
- Q_D(QTreeView);
- if (d->header) {
- if (d->geometryRecursionBlock)
- return;
- d->geometryRecursionBlock = true;
- QSize hint = d->header->isHidden() ? QSize(0, 0) : d->header->sizeHint();
- setViewportMargins(0, hint.height(), 0, 0);
- QRect vg = d->viewport->geometry();
- QRect geometryRect(vg.left(), vg.top() - hint.height(), vg.width(), hint.height());
- d->header->setGeometry(geometryRect);
- //d->header->setOffset(horizontalScrollBar()->value()); // ### bug ???
- QMetaObject::invokeMethod(d->header, "updateGeometries");
- d->updateScrollBars();
- d->geometryRecursionBlock = false;
- }
- QAbstractItemView::updateGeometries();
-}
-
-/*!
- Returns the size hint for the \a column's width or -1 if there is no
- model.
-
- If you need to set the width of a given column to a fixed value, call
- QHeaderView::resizeSection() on the view's header.
-
- If you reimplement this function in a subclass, note that the value you
- return is only used when resizeColumnToContents() is called. In that case,
- if a larger column width is required by either the view's header or
- the item delegate, that width will be used instead.
-
- \sa QWidget::sizeHint, header()
-*/
-int QTreeView::sizeHintForColumn(int column) const
-{
- Q_D(const QTreeView);
- d->executePostedLayout();
- if (d->viewItems.isEmpty())
- return -1;
- ensurePolished();
- int w = 0;
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- const QVector<QTreeViewItem> viewItems = d->viewItems;
-
- int start = 0;
- int end = viewItems.count();
- if(end > 1000) { //if we have too many item this function would be too slow.
- //we get a good approximation by only iterate over 1000 items.
- start = qMax(0, d->firstVisibleItem() - 100);
- end = qMin(end, start + 900);
- }
-
- for (int i = start; i < end; ++i) {
- if (viewItems.at(i).spanning)
- continue; // we have no good size hint
- QModelIndex index = viewItems.at(i).index;
- index = index.sibling(index.row(), column);
- QWidget *editor = d->editorForIndex(index).widget.data();
- if (editor && d->persistent.contains(editor)) {
- w = qMax(w, editor->sizeHint().width());
- int min = editor->minimumSize().width();
- int max = editor->maximumSize().width();
- w = qBound(min, w, max);
- }
- int hint = d->delegateForIndex(index)->sizeHint(option, index).width();
- w = qMax(w, hint + (column == 0 ? d->indentationForItem(i) : 0));
- }
- return w;
-}
-
-/*!
- Returns the size hint for the row indicated by \a index.
-
- \sa sizeHintForColumn(), uniformRowHeights()
-*/
-int QTreeView::indexRowSizeHint(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- if (!d->isIndexValid(index) || !d->itemDelegate)
- return 0;
-
- int start = -1;
- int end = -1;
- int indexRow = index.row();
- int count = d->header->count();
- bool emptyHeader = (count == 0);
- QModelIndex parent = index.parent();
-
- if (count && isVisible()) {
- // If the sections have moved, we end up checking too many or too few
- start = d->header->visualIndexAt(0);
- } else {
- // If the header has not been laid out yet, we use the model directly
- count = d->model->columnCount(parent);
- }
-
- if (isRightToLeft()) {
- start = (start == -1 ? count - 1 : start);
- end = 0;
- } else {
- start = (start == -1 ? 0 : start);
- end = count - 1;
- }
-
- if (end < start)
- qSwap(end, start);
-
- int height = -1;
- QStyleOptionViewItemV4 option = d->viewOptionsV4();
- // ### If we want word wrapping in the items,
- // ### we need to go through all the columns
- // ### and set the width of the column
-
- // Hack to speed up the function
- option.rect.setWidth(-1);
-
- for (int column = start; column <= end; ++column) {
- int logicalColumn = emptyHeader ? column : d->header->logicalIndex(column);
- if (d->header->isSectionHidden(logicalColumn))
- continue;
- QModelIndex idx = d->model->index(indexRow, logicalColumn, parent);
- if (idx.isValid()) {
- QWidget *editor = d->editorForIndex(idx).widget.data();
- if (editor && d->persistent.contains(editor)) {
- height = qMax(height, editor->sizeHint().height());
- int min = editor->minimumSize().height();
- int max = editor->maximumSize().height();
- height = qBound(min, height, max);
- }
- int hint = d->delegateForIndex(idx)->sizeHint(option, idx).height();
- height = qMax(height, hint);
- }
- }
-
- return height;
-}
-
-/*!
- \since 4.3
- Returns the height of the row indicated by the given \a index.
- \sa indexRowSizeHint()
-*/
-int QTreeView::rowHeight(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- d->executePostedLayout();
- int i = d->viewIndex(index);
- if (i == -1)
- return 0;
- return d->itemHeight(i);
-}
-
-/*!
- \internal
-*/
-void QTreeView::horizontalScrollbarAction(int action)
-{
- QAbstractItemView::horizontalScrollbarAction(action);
-}
-
-/*!
- \reimp
-*/
-bool QTreeView::isIndexHidden(const QModelIndex &index) const
-{
- return (isColumnHidden(index.column()) || isRowHidden(index.row(), index.parent()));
-}
-
-/*
- private implementation
-*/
-void QTreeViewPrivate::initialize()
-{
- Q_Q(QTreeView);
- updateStyledFrameWidths();
- q->setSelectionBehavior(QAbstractItemView::SelectRows);
- q->setSelectionMode(QAbstractItemView::SingleSelection);
- q->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
- q->setAttribute(Qt::WA_MacShowFocusRect);
-
- QHeaderView *header = new QHeaderView(Qt::Horizontal, q);
- header->setMovable(true);
- header->setStretchLastSection(true);
- header->setDefaultAlignment(Qt::AlignLeft|Qt::AlignVCenter);
- q->setHeader(header);
-#ifndef QT_NO_ANIMATION
- QObject::connect(&animatedOperation, SIGNAL(finished()), q, SLOT(_q_endAnimatedOperation()));
-#endif //QT_NO_ANIMATION
-}
-
-void QTreeViewPrivate::expand(int item, bool emitSignal)
-{
- Q_Q(QTreeView);
-
- if (item == -1 || viewItems.at(item).expanded)
- return;
-
-#ifndef QT_NO_ANIMATION
- if (emitSignal && animationsEnabled)
- prepareAnimatedOperation(item, QVariantAnimation::Forward);
-#endif //QT_NO_ANIMATION
- stateBeforeAnimation = state;
- q->setState(QAbstractItemView::ExpandingState);
- const QModelIndex index = viewItems.at(item).index;
- storeExpanded(index);
- viewItems[item].expanded = true;
- layout(item);
- q->setState(stateBeforeAnimation);
-
- if (model->canFetchMore(index))
- model->fetchMore(index);
- if (emitSignal) {
- emit q->expanded(index);
-#ifndef QT_NO_ANIMATION
- if (animationsEnabled)
- beginAnimatedOperation();
-#endif //QT_NO_ANIMATION
- }
-}
-
-void QTreeViewPrivate::insertViewItems(int pos, int count, const QTreeViewItem &viewItem)
-{
- viewItems.insert(pos, count, viewItem);
- QTreeViewItem *items = viewItems.data();
- for (int i = pos + count; i < viewItems.count(); i++)
- if (items[i].parentItem >= pos)
- items[i].parentItem += count;
-}
-
-void QTreeViewPrivate::removeViewItems(int pos, int count)
-{
- viewItems.remove(pos, count);
- QTreeViewItem *items = viewItems.data();
- for (int i = pos; i < viewItems.count(); i++)
- if (items[i].parentItem >= pos)
- items[i].parentItem -= count;
-}
-
-#if 0
-bool QTreeViewPrivate::checkViewItems() const
-{
- for (int i = 0; i < viewItems.count(); ++i) {
- const QTreeViewItem &vi = viewItems.at(i);
- if (vi.parentItem == -1) {
- Q_ASSERT(!vi.index.parent().isValid() || vi.index.parent() == root);
- } else {
- Q_ASSERT(vi.index.parent() == viewItems.at(vi.parentItem).index);
- }
- }
- return true;
-}
-#endif
-
-void QTreeViewPrivate::collapse(int item, bool emitSignal)
-{
- Q_Q(QTreeView);
-
- if (item == -1 || expandedIndexes.isEmpty())
- return;
-
- //if the current item is now invisible, the autoscroll will expand the tree to see it, so disable the autoscroll
- delayedAutoScroll.stop();
-
- int total = viewItems.at(item).total;
- const QModelIndex &modelIndex = viewItems.at(item).index;
- if (!isPersistent(modelIndex))
- return; // if the index is not persistent, no chances it is expanded
- QSet<QPersistentModelIndex>::iterator it = expandedIndexes.find(modelIndex);
- if (it == expandedIndexes.end() || viewItems.at(item).expanded == false)
- return; // nothing to do
-
-#ifndef QT_NO_ANIMATION
- if (emitSignal && animationsEnabled)
- prepareAnimatedOperation(item, QVariantAnimation::Backward);
-#endif //QT_NO_ANIMATION
-
- stateBeforeAnimation = state;
- q->setState(QAbstractItemView::CollapsingState);
- expandedIndexes.erase(it);
- viewItems[item].expanded = false;
- int index = item;
- while (index > -1) {
- viewItems[index].total -= total;
- index = viewItems[index].parentItem;
- }
- removeViewItems(item + 1, total); // collapse
- q->setState(stateBeforeAnimation);
-
- if (emitSignal) {
- emit q->collapsed(modelIndex);
-#ifndef QT_NO_ANIMATION
- if (animationsEnabled)
- beginAnimatedOperation();
-#endif //QT_NO_ANIMATION
- }
-}
-
-#ifndef QT_NO_ANIMATION
-void QTreeViewPrivate::prepareAnimatedOperation(int item, QVariantAnimation::Direction direction)
-{
- animatedOperation.item = item;
- animatedOperation.viewport = viewport;
- animatedOperation.setDirection(direction);
-
- int top = coordinateForItem(item) + itemHeight(item);
- QRect rect = viewport->rect();
- rect.setTop(top);
- if (direction == QVariantAnimation::Backward) {
- const int limit = rect.height() * 2;
- int h = 0;
- int c = item + viewItems.at(item).total + 1;
- for (int i = item + 1; i < c && h < limit; ++i)
- h += itemHeight(i);
- rect.setHeight(h);
- animatedOperation.setEndValue(top + h);
- }
- animatedOperation.setStartValue(top);
- animatedOperation.before = renderTreeToPixmapForAnimation(rect);
-}
-
-void QTreeViewPrivate::beginAnimatedOperation()
-{
- Q_Q(QTreeView);
-
- QRect rect = viewport->rect();
- rect.setTop(animatedOperation.top());
- if (animatedOperation.direction() == QVariantAnimation::Forward) {
- const int limit = rect.height() * 2;
- int h = 0;
- int c = animatedOperation.item + viewItems.at(animatedOperation.item).total + 1;
- for (int i = animatedOperation.item + 1; i < c && h < limit; ++i)
- h += itemHeight(i);
- rect.setHeight(h);
- animatedOperation.setEndValue(animatedOperation.top() + h);
- }
-
- if (!rect.isEmpty()) {
- animatedOperation.after = renderTreeToPixmapForAnimation(rect);
-
- q->setState(QAbstractItemView::AnimatingState);
- animatedOperation.start(); //let's start the animation
- }
-}
-
-void QTreeViewPrivate::drawAnimatedOperation(QPainter *painter) const
-{
- const int start = animatedOperation.startValue().toInt(),
- end = animatedOperation.endValue().toInt(),
- current = animatedOperation.currentValue().toInt();
- bool collapsing = animatedOperation.direction() == QVariantAnimation::Backward;
- const QPixmap top = collapsing ? animatedOperation.before : animatedOperation.after;
- painter->drawPixmap(0, start, top, 0, end - current - 1, top.width(), top.height());
- const QPixmap bottom = collapsing ? animatedOperation.after : animatedOperation.before;
- painter->drawPixmap(0, current, bottom);
-}
-
-QPixmap QTreeViewPrivate::renderTreeToPixmapForAnimation(const QRect &rect) const
-{
- Q_Q(const QTreeView);
- QPixmap pixmap(rect.size());
- if (rect.size().isEmpty())
- return pixmap;
- pixmap.fill(Qt::transparent); //the base might not be opaque, and we don't want uninitialized pixels.
- QPainter painter(&pixmap);
- painter.fillRect(QRect(QPoint(0,0), rect.size()), q->palette().base());
- painter.translate(0, -rect.top());
- q->drawTree(&painter, QRegion(rect));
- painter.end();
-
- //and now let's render the editors the editors
- QStyleOptionViewItemV4 option = viewOptionsV4();
- for (QEditorIndexHash::const_iterator it = editorIndexHash.constBegin(); it != editorIndexHash.constEnd(); ++it) {
- QWidget *editor = it.key();
- const QModelIndex &index = it.value();
- option.rect = q->visualRect(index);
- if (option.rect.isValid()) {
-
- if (QAbstractItemDelegate *delegate = delegateForIndex(index))
- delegate->updateEditorGeometry(editor, option, index);
-
- const QPoint pos = editor->pos();
- if (rect.contains(pos)) {
- editor->render(&pixmap, pos - rect.topLeft());
- //the animation uses pixmap to display the treeview's content
- //the editor is rendered on this pixmap and thus can (should) be hidden
- editor->hide();
- }
- }
- }
-
-
- return pixmap;
-}
-
-void QTreeViewPrivate::_q_endAnimatedOperation()
-{
- Q_Q(QTreeView);
- q->setState(stateBeforeAnimation);
- q->updateGeometries();
- viewport->update();
-}
-#endif //QT_NO_ANIMATION
-
-void QTreeViewPrivate::_q_modelAboutToBeReset()
-{
- viewItems.clear();
-}
-
-void QTreeViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
-{
- if (start <= 0 && 0 <= end)
- viewItems.clear();
- QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(parent, start, end);
-}
-
-void QTreeViewPrivate::_q_columnsRemoved(const QModelIndex &parent, int start, int end)
-{
- if (start <= 0 && 0 <= end)
- doDelayedItemsLayout();
- QAbstractItemViewPrivate::_q_columnsRemoved(parent, start, end);
-}
-
-/** \internal
- creates and initialize the viewItem structure of the children of the element \i
-
- set \a recursiveExpanding if the function has to expand all the children (called from expandAll)
- \a afterIsUninitialized is when we recurse from layout(-1), it means all the items after 'i' are
- not yet initialized and need not to be moved
- */
-void QTreeViewPrivate::layout(int i, bool recursiveExpanding, bool afterIsUninitialized)
-{
- Q_Q(QTreeView);
- QModelIndex current;
- QModelIndex parent = (i < 0) ? (QModelIndex)root : modelIndex(i);
-
- if (i>=0 && !parent.isValid()) {
- //modelIndex() should never return something invalid for the real items.
- //This can happen if columncount has been set to 0.
- //To avoid infinite loop we stop here.
- return;
- }
-
- int count = 0;
- if (model->hasChildren(parent)) {
- if (model->canFetchMore(parent))
- model->fetchMore(parent);
- count = model->rowCount(parent);
- }
-
- bool expanding = true;
- if (i == -1) {
- if (uniformRowHeights) {
- QModelIndex index = model->index(0, 0, parent);
- defaultItemHeight = q->indexRowSizeHint(index);
- }
- viewItems.resize(count);
- afterIsUninitialized = true;
- } else if (viewItems[i].total != (uint)count) {
- if (!afterIsUninitialized)
- insertViewItems(i + 1, count, QTreeViewItem()); // expand
- else if (count > 0)
- viewItems.resize(viewItems.count() + count);
- } else {
- expanding = false;
- }
-
- int first = i + 1;
- int level = (i >= 0 ? viewItems.at(i).level + 1 : 0);
- int hidden = 0;
- int last = 0;
- int children = 0;
- QTreeViewItem *item = 0;
- for (int j = first; j < first + count; ++j) {
- current = model->index(j - first, 0, parent);
- if (isRowHidden(current)) {
- ++hidden;
- last = j - hidden + children;
- } else {
- last = j - hidden + children;
- if (item)
- item->hasMoreSiblings = true;
- item = &viewItems[last];
- item->index = current;
- item->parentItem = i;
- item->level = level;
- item->height = 0;
- item->spanning = q->isFirstColumnSpanned(current.row(), parent);
- item->expanded = false;
- item->total = 0;
- item->hasMoreSiblings = false;
- if (recursiveExpanding || isIndexExpanded(current)) {
- if (recursiveExpanding)
- expandedIndexes.insert(current);
- item->expanded = true;
- layout(last, recursiveExpanding, afterIsUninitialized);
- item = &viewItems[last];
- children += item->total;
- item->hasChildren = item->total > 0;
- last = j - hidden + children;
- } else {
- item->hasChildren = hasVisibleChildren(current);
- }
- }
- }
-
- // remove hidden items
- if (hidden > 0) {
- if (!afterIsUninitialized)
- removeViewItems(last + 1, hidden);
- else
- viewItems.resize(viewItems.size() - hidden);
- }
-
- if (!expanding)
- return; // nothing changed
-
- while (i > -1) {
- viewItems[i].total += count - hidden;
- i = viewItems[i].parentItem;
- }
-}
-
-int QTreeViewPrivate::pageUp(int i) const
-{
- int index = itemAtCoordinate(coordinateForItem(i) - viewport->height());
- while (isItemHiddenOrDisabled(index))
- index--;
- return index == -1 ? 0 : index;
-}
-
-int QTreeViewPrivate::pageDown(int i) const
-{
- int index = itemAtCoordinate(coordinateForItem(i) + viewport->height());
- while (isItemHiddenOrDisabled(index))
- index++;
- return index == -1 ? viewItems.count() - 1 : index;
-}
-
-int QTreeViewPrivate::indentationForItem(int item) const
-{
- if (item < 0 || item >= viewItems.count())
- return 0;
- int level = viewItems.at(item).level;
- if (rootDecoration)
- ++level;
- return level * indent;
-}
-
-int QTreeViewPrivate::itemHeight(int item) const
-{
- if (uniformRowHeights)
- return defaultItemHeight;
- if (viewItems.isEmpty())
- return 0;
- const QModelIndex &index = viewItems.at(item).index;
- if (!index.isValid())
- return 0;
- int height = viewItems.at(item).height;
- if (height <= 0) {
- height = q_func()->indexRowSizeHint(index);
- viewItems[item].height = height;
- }
- return qMax(height, 0);
-}
-
-
-/*!
- \internal
- Returns the viewport y coordinate for \a item.
-*/
-int QTreeViewPrivate::coordinateForItem(int item) const
-{
- if (verticalScrollMode == QAbstractItemView::ScrollPerPixel) {
- if (uniformRowHeights)
- return (item * defaultItemHeight) - vbar->value();
- // ### optimize (spans or caching)
- int y = 0;
- for (int i = 0; i < viewItems.count(); ++i) {
- if (i == item)
- return y - vbar->value();
- y += itemHeight(i);
- }
- } else { // ScrollPerItem
- int topViewItemIndex = vbar->value();
- if (uniformRowHeights)
- return defaultItemHeight * (item - topViewItemIndex);
- if (item >= topViewItemIndex) {
- // search in the visible area first and continue down
- // ### slow if the item is not visible
- int viewItemCoordinate = 0;
- int viewItemIndex = topViewItemIndex;
- while (viewItemIndex < viewItems.count()) {
- if (viewItemIndex == item)
- return viewItemCoordinate;
- viewItemCoordinate += itemHeight(viewItemIndex);
- ++viewItemIndex;
- }
- // below the last item in the view
- Q_ASSERT(false);
- return viewItemCoordinate;
- } else {
- // search the area above the viewport (used for editor widgets)
- int viewItemCoordinate = 0;
- for (int viewItemIndex = topViewItemIndex; viewItemIndex > 0; --viewItemIndex) {
- if (viewItemIndex == item)
- return viewItemCoordinate;
- viewItemCoordinate -= itemHeight(viewItemIndex - 1);
- }
- return viewItemCoordinate;
- }
- }
- return 0;
-}
-
-/*!
- \internal
- Returns the index of the view item at the
- given viewport \a coordinate.
-
- \sa modelIndex()
-*/
-int QTreeViewPrivate::itemAtCoordinate(int coordinate) const
-{
- const int itemCount = viewItems.count();
- if (itemCount == 0)
- return -1;
- if (uniformRowHeights && defaultItemHeight <= 0)
- return -1;
- if (verticalScrollMode == QAbstractItemView::ScrollPerPixel) {
- if (uniformRowHeights) {
- const int viewItemIndex = (coordinate + vbar->value()) / defaultItemHeight;
- return ((viewItemIndex >= itemCount || viewItemIndex < 0) ? -1 : viewItemIndex);
- }
- // ### optimize
- int viewItemCoordinate = 0;
- const int contentsCoordinate = coordinate + vbar->value();
- for (int viewItemIndex = 0; viewItemIndex < viewItems.count(); ++viewItemIndex) {
- viewItemCoordinate += itemHeight(viewItemIndex);
- if (viewItemCoordinate >= contentsCoordinate)
- return (viewItemIndex >= itemCount ? -1 : viewItemIndex);
- }
- } else { // ScrollPerItem
- int topViewItemIndex = vbar->value();
- if (uniformRowHeights) {
- if (coordinate < 0)
- coordinate -= defaultItemHeight - 1;
- const int viewItemIndex = topViewItemIndex + (coordinate / defaultItemHeight);
- return ((viewItemIndex >= itemCount || viewItemIndex < 0) ? -1 : viewItemIndex);
- }
- if (coordinate >= 0) {
- // the coordinate is in or below the viewport
- int viewItemCoordinate = 0;
- for (int viewItemIndex = topViewItemIndex; viewItemIndex < viewItems.count(); ++viewItemIndex) {
- viewItemCoordinate += itemHeight(viewItemIndex);
- if (viewItemCoordinate > coordinate)
- return (viewItemIndex >= itemCount ? -1 : viewItemIndex);
- }
- } else {
- // the coordinate is above the viewport
- int viewItemCoordinate = 0;
- for (int viewItemIndex = topViewItemIndex; viewItemIndex >= 0; --viewItemIndex) {
- if (viewItemCoordinate <= coordinate)
- return (viewItemIndex >= itemCount ? -1 : viewItemIndex);
- viewItemCoordinate -= itemHeight(viewItemIndex);
- }
- }
- }
- return -1;
-}
-
-int QTreeViewPrivate::viewIndex(const QModelIndex &_index) const
-{
- if (!_index.isValid() || viewItems.isEmpty())
- return -1;
-
- const int totalCount = viewItems.count();
- const QModelIndex index = _index.sibling(_index.row(), 0);
- const int row = index.row();
- const qint64 internalId = index.internalId();
-
- // We start nearest to the lastViewedItem
- int localCount = qMin(lastViewedItem - 1, totalCount - lastViewedItem);
- for (int i = 0; i < localCount; ++i) {
- const QModelIndex &idx1 = viewItems.at(lastViewedItem + i).index;
- if (idx1.row() == row && idx1.internalId() == internalId) {
- lastViewedItem = lastViewedItem + i;
- return lastViewedItem;
- }
- const QModelIndex &idx2 = viewItems.at(lastViewedItem - i - 1).index;
- if (idx2.row() == row && idx2.internalId() == internalId) {
- lastViewedItem = lastViewedItem - i - 1;
- return lastViewedItem;
- }
- }
-
- for (int j = qMax(0, lastViewedItem + localCount); j < totalCount; ++j) {
- const QModelIndex &idx = viewItems.at(j).index;
- if (idx.row() == row && idx.internalId() == internalId) {
- lastViewedItem = j;
- return j;
- }
- }
- for (int j = qMin(totalCount, lastViewedItem - localCount) - 1; j >= 0; --j) {
- const QModelIndex &idx = viewItems.at(j).index;
- if (idx.row() == row && idx.internalId() == internalId) {
- lastViewedItem = j;
- return j;
- }
- }
-
- // nothing found
- return -1;
-}
-
-QModelIndex QTreeViewPrivate::modelIndex(int i, int column) const
-{
- if (i < 0 || i >= viewItems.count())
- return QModelIndex();
-
- QModelIndex ret = viewItems.at(i).index;
- if (column)
- ret = ret.sibling(ret.row(), column);
- return ret;
-}
-
-int QTreeViewPrivate::firstVisibleItem(int *offset) const
-{
- const int value = vbar->value();
- if (verticalScrollMode == QAbstractItemView::ScrollPerItem) {
- if (offset)
- *offset = 0;
- return (value < 0 || value >= viewItems.count()) ? -1 : value;
- }
- // ScrollMode == ScrollPerPixel
- if (uniformRowHeights) {
- if (!defaultItemHeight)
- return -1;
-
- if (offset)
- *offset = -(value % defaultItemHeight);
- return value / defaultItemHeight;
- }
- int y = 0; // ### optimize (use spans ?)
- for (int i = 0; i < viewItems.count(); ++i) {
- y += itemHeight(i); // the height value is cached
- if (y > value) {
- if (offset)
- *offset = y - value - itemHeight(i);
- return i;
- }
- }
- return -1;
-}
-
-int QTreeViewPrivate::columnAt(int x) const
-{
- return header->logicalIndexAt(x);
-}
-
-void QTreeViewPrivate::updateScrollBars()
-{
- Q_Q(QTreeView);
- QSize viewportSize = viewport->size();
- if (!viewportSize.isValid())
- viewportSize = QSize(0, 0);
-
- if (viewItems.isEmpty()) {
- q->doItemsLayout();
- }
-
- int itemsInViewport = 0;
- if (uniformRowHeights) {
- if (defaultItemHeight <= 0)
- itemsInViewport = viewItems.count();
- else
- itemsInViewport = viewportSize.height() / defaultItemHeight;
- } else {
- const int itemsCount = viewItems.count();
- const int viewportHeight = viewportSize.height();
- for (int height = 0, item = itemsCount - 1; item >= 0; --item) {
- height += itemHeight(item);
- if (height > viewportHeight)
- break;
- ++itemsInViewport;
- }
- }
- if (verticalScrollMode == QAbstractItemView::ScrollPerItem) {
- if (!viewItems.isEmpty())
- itemsInViewport = qMax(1, itemsInViewport);
- vbar->setRange(0, viewItems.count() - itemsInViewport);
- vbar->setPageStep(itemsInViewport);
- vbar->setSingleStep(1);
- } else { // scroll per pixel
- int contentsHeight = 0;
- if (uniformRowHeights) {
- contentsHeight = defaultItemHeight * viewItems.count();
- } else { // ### optimize (spans or caching)
- for (int i = 0; i < viewItems.count(); ++i)
- contentsHeight += itemHeight(i);
- }
- vbar->setRange(0, contentsHeight - viewportSize.height());
- vbar->setPageStep(viewportSize.height());
- vbar->setSingleStep(qMax(viewportSize.height() / (itemsInViewport + 1), 2));
- }
-
- const int columnCount = header->count();
- const int viewportWidth = viewportSize.width();
- int columnsInViewport = 0;
- for (int width = 0, column = columnCount - 1; column >= 0; --column) {
- int logical = header->logicalIndex(column);
- width += header->sectionSize(logical);
- if (width > viewportWidth)
- break;
- ++columnsInViewport;
- }
- if (columnCount > 0)
- columnsInViewport = qMax(1, columnsInViewport);
- if (horizontalScrollMode == QAbstractItemView::ScrollPerItem) {
- hbar->setRange(0, columnCount - columnsInViewport);
- hbar->setPageStep(columnsInViewport);
- hbar->setSingleStep(1);
- } else { // scroll per pixel
- const int horizontalLength = header->length();
- const QSize maxSize = q->maximumViewportSize();
- if (maxSize.width() >= horizontalLength && vbar->maximum() <= 0)
- viewportSize = maxSize;
- hbar->setPageStep(viewportSize.width());
- hbar->setRange(0, qMax(horizontalLength - viewportSize.width(), 0));
- hbar->setSingleStep(qMax(viewportSize.width() / (columnsInViewport + 1), 2));
- }
-}
-
-int QTreeViewPrivate::itemDecorationAt(const QPoint &pos) const
-{
- executePostedLayout();
- int x = pos.x();
- int column = header->logicalIndexAt(x);
- if (column != 0)
- return -1; // no logical index at x
-
- int viewItemIndex = itemAtCoordinate(pos.y());
- QRect returning = itemDecorationRect(modelIndex(viewItemIndex));
- if (!returning.contains(pos))
- return -1;
-
- return viewItemIndex;
-}
-
-QRect QTreeViewPrivate::itemDecorationRect(const QModelIndex &index) const
-{
- Q_Q(const QTreeView);
- if (!rootDecoration && index.parent() == root)
- return QRect(); // no decoration at root
-
- int viewItemIndex = viewIndex(index);
- if (viewItemIndex < 0 || !hasVisibleChildren(viewItems.at(viewItemIndex).index))
- return QRect();
-
- int itemIndentation = indentationForItem(viewItemIndex);
- int position = header->sectionViewportPosition(0);
- int size = header->sectionSize(0);
-
- QRect rect;
- if (q->isRightToLeft())
- rect = QRect(position + size - itemIndentation, coordinateForItem(viewItemIndex),
- indent, itemHeight(viewItemIndex));
- else
- rect = QRect(position + itemIndentation - indent, coordinateForItem(viewItemIndex),
- indent, itemHeight(viewItemIndex));
- QStyleOption opt;
- opt.initFrom(q);
- opt.rect = rect;
- return q->style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &opt, q);
-}
-
-QList<QPair<int, int> > QTreeViewPrivate::columnRanges(const QModelIndex &topIndex,
- const QModelIndex &bottomIndex) const
-{
- const int topVisual = header->visualIndex(topIndex.column()),
- bottomVisual = header->visualIndex(bottomIndex.column());
-
- const int start = qMin(topVisual, bottomVisual);
- const int end = qMax(topVisual, bottomVisual);
-
- QList<int> logicalIndexes;
-
- //we iterate over the visual indexes to get the logical indexes
- for (int c = start; c <= end; c++) {
- const int logical = header->logicalIndex(c);
- if (!header->isSectionHidden(logical)) {
- logicalIndexes << logical;
- }
- }
- //let's sort the list
- qSort(logicalIndexes.begin(), logicalIndexes.end());
-
- QList<QPair<int, int> > ret;
- QPair<int, int> current;
- current.first = -2; // -1 is not enough because -1+1 = 0
- current.second = -2;
- for(int i = 0; i < logicalIndexes.count(); ++i) {
- const int logicalColumn = logicalIndexes.at(i);
- if (current.second + 1 != logicalColumn) {
- if (current.first != -2) {
- //let's save the current one
- ret += current;
- }
- //let's start a new one
- current.first = current.second = logicalColumn;
- } else {
- current.second++;
- }
- }
-
- //let's get the last range
- if (current.first != -2) {
- ret += current;
- }
-
- return ret;
-}
-
-void QTreeViewPrivate::select(const QModelIndex &topIndex, const QModelIndex &bottomIndex,
- QItemSelectionModel::SelectionFlags command)
-{
- Q_Q(QTreeView);
- QItemSelection selection;
- const int top = viewIndex(topIndex),
- bottom = viewIndex(bottomIndex);
-
- const QList< QPair<int, int> > colRanges = columnRanges(topIndex, bottomIndex);
- QList< QPair<int, int> >::const_iterator it;
- for (it = colRanges.begin(); it != colRanges.end(); ++it) {
- const int left = (*it).first,
- right = (*it).second;
-
- QModelIndex previous;
- QItemSelectionRange currentRange;
- QStack<QItemSelectionRange> rangeStack;
- for (int i = top; i <= bottom; ++i) {
- QModelIndex index = modelIndex(i);
- QModelIndex parent = index.parent();
- QModelIndex previousParent = previous.parent();
- if (previous.isValid() && parent == previousParent) {
- // same parent
- if (qAbs(previous.row() - index.row()) > 1) {
- //a hole (hidden index inside a range) has been detected
- if (currentRange.isValid()) {
- selection.append(currentRange);
- }
- //let's start a new range
- currentRange = QItemSelectionRange(index.sibling(index.row(), left), index.sibling(index.row(), right));
- } else {
- QModelIndex tl = model->index(currentRange.top(), currentRange.left(),
- currentRange.parent());
- currentRange = QItemSelectionRange(tl, index.sibling(index.row(), right));
- }
- } else if (previous.isValid() && parent == model->index(previous.row(), 0, previousParent)) {
- // item is child of previous
- rangeStack.push(currentRange);
- currentRange = QItemSelectionRange(index.sibling(index.row(), left), index.sibling(index.row(), right));
- } else {
- if (currentRange.isValid())
- selection.append(currentRange);
- if (rangeStack.isEmpty()) {
- currentRange = QItemSelectionRange(index.sibling(index.row(), left), index.sibling(index.row(), right));
- } else {
- currentRange = rangeStack.pop();
- index = currentRange.bottomRight(); //let's resume the range
- --i; //we process again the current item
- }
- }
- previous = index;
- }
- if (currentRange.isValid())
- selection.append(currentRange);
- for (int i = 0; i < rangeStack.count(); ++i)
- selection.append(rangeStack.at(i));
- }
- q->selectionModel()->select(selection, command);
-}
-
-QPair<int,int> QTreeViewPrivate::startAndEndColumns(const QRect &rect) const
-{
- Q_Q(const QTreeView);
- int start = header->visualIndexAt(rect.left());
- int end = header->visualIndexAt(rect.right());
- if (q->isRightToLeft()) {
- start = (start == -1 ? header->count() - 1 : start);
- end = (end == -1 ? 0 : end);
- } else {
- start = (start == -1 ? 0 : start);
- end = (end == -1 ? header->count() - 1 : end);
- }
- return qMakePair<int,int>(qMin(start, end), qMax(start, end));
-}
-
-bool QTreeViewPrivate::hasVisibleChildren(const QModelIndex& parent) const
-{
- Q_Q(const QTreeView);
- if (model->hasChildren(parent)) {
- if (hiddenIndexes.isEmpty())
- return true;
- if (q->isIndexHidden(parent))
- return false;
- int rowCount = model->rowCount(parent);
- for (int i = 0; i < rowCount; ++i) {
- if (!q->isRowHidden(i, parent))
- return true;
- }
- if (rowCount == 0)
- return true;
- }
- return false;
-}
-
-void QTreeViewPrivate::_q_sortIndicatorChanged(int column, Qt::SortOrder order)
-{
- model->sort(column, order);
-}
-
-/*!
- \reimp
- */
-void QTreeView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
-{
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- int entry = visualIndex(current) + 1;
- if (header())
- ++entry;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::Focus);
- }
-#endif
- QAbstractItemView::currentChanged(current, previous);
-
- if (allColumnsShowFocus()) {
- if (previous.isValid()) {
- QRect previousRect = visualRect(previous);
- previousRect.setX(0);
- previousRect.setWidth(viewport()->width());
- viewport()->update(previousRect);
- }
- if (current.isValid()) {
- QRect currentRect = visualRect(current);
- currentRect.setX(0);
- currentRect.setWidth(viewport()->width());
- viewport()->update(currentRect);
- }
- }
-}
-
-/*!
- \reimp
- */
-void QTreeView::selectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected)
-{
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- // ### does not work properly for selection ranges.
- QModelIndex sel = selected.indexes().value(0);
- if (sel.isValid()) {
- int entry = visualIndex(sel) + 1;
- if (header())
- ++entry;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::Selection);
- }
- QModelIndex desel = deselected.indexes().value(0);
- if (desel.isValid()) {
- int entry = visualIndex(desel) + 1;
- if (header())
- ++entry;
- QAccessible::updateAccessibility(viewport(), entry, QAccessible::SelectionRemove);
- }
- }
-#endif
- QAbstractItemView::selectionChanged(selected, deselected);
-}
-
-int QTreeView::visualIndex(const QModelIndex &index) const
-{
- Q_D(const QTreeView);
- d->executePostedLayout();
- return d->viewIndex(index);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtreeview.cpp"
-
-#endif // QT_NO_TREEVIEW
diff --git a/src/gui/itemviews/qtreeview.h b/src/gui/itemviews/qtreeview.h
deleted file mode 100644
index 49b8419389..0000000000
--- a/src/gui/itemviews/qtreeview.h
+++ /dev/null
@@ -1,239 +0,0 @@
-/****************************************************************************
-**
-** 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 QTREEVIEW_H
-#define QTREEVIEW_H
-
-#include <QtGui/qabstractitemview.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TREEVIEW
-
-class QTreeViewPrivate;
-class QHeaderView;
-
-class Q_GUI_EXPORT QTreeView : public QAbstractItemView
-{
- Q_OBJECT
- Q_PROPERTY(int autoExpandDelay READ autoExpandDelay WRITE setAutoExpandDelay)
- Q_PROPERTY(int indentation READ indentation WRITE setIndentation)
- Q_PROPERTY(bool rootIsDecorated READ rootIsDecorated WRITE setRootIsDecorated)
- Q_PROPERTY(bool uniformRowHeights READ uniformRowHeights WRITE setUniformRowHeights)
- Q_PROPERTY(bool itemsExpandable READ itemsExpandable WRITE setItemsExpandable)
- Q_PROPERTY(bool sortingEnabled READ isSortingEnabled WRITE setSortingEnabled)
- Q_PROPERTY(bool animated READ isAnimated WRITE setAnimated)
- Q_PROPERTY(bool allColumnsShowFocus READ allColumnsShowFocus WRITE setAllColumnsShowFocus)
- Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap)
- Q_PROPERTY(bool headerHidden READ isHeaderHidden WRITE setHeaderHidden)
- Q_PROPERTY(bool expandsOnDoubleClick READ expandsOnDoubleClick WRITE setExpandsOnDoubleClick)
-
-public:
- explicit QTreeView(QWidget *parent = 0);
- ~QTreeView();
-
- void setModel(QAbstractItemModel *model);
- void setRootIndex(const QModelIndex &index);
- void setSelectionModel(QItemSelectionModel *selectionModel);
-
- QHeaderView *header() const;
- void setHeader(QHeaderView *header);
-
- int autoExpandDelay() const;
- void setAutoExpandDelay(int delay);
-
- int indentation() const;
- void setIndentation(int i);
-
- bool rootIsDecorated() const;
- void setRootIsDecorated(bool show);
-
- bool uniformRowHeights() const;
- void setUniformRowHeights(bool uniform);
-
- bool itemsExpandable() const;
- void setItemsExpandable(bool enable);
-
- bool expandsOnDoubleClick() const;
- void setExpandsOnDoubleClick(bool enable);
-
- int columnViewportPosition(int column) const;
- int columnWidth(int column) const;
- void setColumnWidth(int column, int width);
- int columnAt(int x) const;
-
- bool isColumnHidden(int column) const;
- void setColumnHidden(int column, bool hide);
-
- bool isHeaderHidden() const;
- void setHeaderHidden(bool hide);
-
- bool isRowHidden(int row, const QModelIndex &parent) const;
- void setRowHidden(int row, const QModelIndex &parent, bool hide);
-
- bool isFirstColumnSpanned(int row, const QModelIndex &parent) const;
- void setFirstColumnSpanned(int row, const QModelIndex &parent, bool span);
-
- bool isExpanded(const QModelIndex &index) const;
- void setExpanded(const QModelIndex &index, bool expand);
-
- void setSortingEnabled(bool enable);
- bool isSortingEnabled() const;
-
- void setAnimated(bool enable);
- bool isAnimated() const;
-
- void setAllColumnsShowFocus(bool enable);
- bool allColumnsShowFocus() const;
-
- void setWordWrap(bool on);
- bool wordWrap() const;
-
- void keyboardSearch(const QString &search);
-
- QRect visualRect(const QModelIndex &index) const;
- void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible);
- QModelIndex indexAt(const QPoint &p) const;
- QModelIndex indexAbove(const QModelIndex &index) const;
- QModelIndex indexBelow(const QModelIndex &index) const;
-
- void doItemsLayout();
- void reset();
-
- void sortByColumn(int column, Qt::SortOrder order);
-
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void selectAll();
-
-Q_SIGNALS:
- void expanded(const QModelIndex &index);
- void collapsed(const QModelIndex &index);
-
-public Q_SLOTS:
- void hideColumn(int column);
- void showColumn(int column);
- void expand(const QModelIndex &index);
- void collapse(const QModelIndex &index);
- void resizeColumnToContents(int column);
- void sortByColumn(int column);
- void expandAll();
- void collapseAll();
- void expandToDepth(int depth);
-
-protected Q_SLOTS:
- void columnResized(int column, int oldSize, int newSize);
- void columnCountChanged(int oldCount, int newCount);
- void columnMoved();
- void reexpand();
- void rowsRemoved(const QModelIndex &parent, int first, int last);
-
-protected:
- QTreeView(QTreeViewPrivate &dd, QWidget *parent = 0);
- void scrollContentsBy(int dx, int dy);
- void rowsInserted(const QModelIndex &parent, int start, int end);
- void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
-
- QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
- int horizontalOffset() const;
- int verticalOffset() const;
-
- void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command);
- QRegion visualRegionForSelection(const QItemSelection &selection) const;
- QModelIndexList selectedIndexes() const;
-
- void timerEvent(QTimerEvent *event);
- void paintEvent(QPaintEvent *event);
-
- void drawTree(QPainter *painter, const QRegion &region) const;
- virtual void drawRow(QPainter *painter,
- const QStyleOptionViewItem &options,
- const QModelIndex &index) const;
- virtual void drawBranches(QPainter *painter,
- const QRect &rect,
- const QModelIndex &index) const;
-
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void keyPressEvent(QKeyEvent *event);
-#ifndef QT_NO_DRAGANDDROP
- void dragMoveEvent(QDragMoveEvent *event);
-#endif
- bool viewportEvent(QEvent *event);
-
- void updateGeometries();
-
- int sizeHintForColumn(int column) const;
- int indexRowSizeHint(const QModelIndex &index) const;
- int rowHeight(const QModelIndex &index) const;
-
- void horizontalScrollbarAction(int action);
-
- bool isIndexHidden(const QModelIndex &index) const;
- void selectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected);
- void currentChanged(const QModelIndex &current, const QModelIndex &previous);
-
-private:
- friend class QAccessibleItemView;
- int visualIndex(const QModelIndex &index) const;
-
- Q_DECLARE_PRIVATE(QTreeView)
- Q_DISABLE_COPY(QTreeView)
-#ifndef QT_NO_ANIMATION
- Q_PRIVATE_SLOT(d_func(), void _q_endAnimatedOperation())
-#endif //QT_NO_ANIMATION
- Q_PRIVATE_SLOT(d_func(), void _q_modelAboutToBeReset())
- Q_PRIVATE_SLOT(d_func(), void _q_sortIndicatorChanged(int column, Qt::SortOrder order))
-};
-
-#endif // QT_NO_TREEVIEW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTREEVIEW_H
diff --git a/src/gui/itemviews/qtreeview_p.h b/src/gui/itemviews/qtreeview_p.h
deleted file mode 100644
index 9a923c5972..0000000000
--- a/src/gui/itemviews/qtreeview_p.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/****************************************************************************
-**
-** 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 QTREEVIEW_P_H
-#define QTREEVIEW_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qabstractitemview_p.h"
-#include <QtCore/qvariantanimation.h>
-#include <QtCore/qabstractitemmodel.h>
-
-#ifndef QT_NO_TREEVIEW
-
-QT_BEGIN_NAMESPACE
-
-struct QTreeViewItem
-{
- QTreeViewItem() : parentItem(-1), expanded(false), spanning(false), hasChildren(false),
- hasMoreSiblings(false), total(0), level(0), height(0) {}
- QModelIndex index; // we remove items whenever the indexes are invalidated
- int parentItem; // parent item index in viewItems
- uint expanded : 1;
- uint spanning : 1;
- uint hasChildren : 1; // if the item has visible children (even if collapsed)
- uint hasMoreSiblings : 1;
- uint total : 28; // total number of children visible
- uint level : 16; // indentation
- int height : 16; // row height
-};
-
-Q_DECLARE_TYPEINFO(QTreeViewItem, Q_MOVABLE_TYPE);
-
-class QTreeViewPrivate : public QAbstractItemViewPrivate
-{
- Q_DECLARE_PUBLIC(QTreeView)
-public:
-
- QTreeViewPrivate()
- : QAbstractItemViewPrivate(),
- header(0), indent(20), lastViewedItem(0), defaultItemHeight(-1),
- uniformRowHeights(false), rootDecoration(true),
- itemsExpandable(true), sortingEnabled(false),
- expandsOnDoubleClick(true),
- allColumnsShowFocus(false), current(0), spanning(false),
- animationsEnabled(false), columnResizeTimerID(0),
- autoExpandDelay(-1), hoverBranch(-1), geometryRecursionBlock(false), hasRemovedItems(false) {}
-
- ~QTreeViewPrivate() {}
- void initialize();
-
- QItemViewPaintPairs draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const;
-
-#ifndef QT_NO_ANIMATION
- struct AnimatedOperation : public QVariantAnimation
- {
- int item;
- QPixmap before;
- QPixmap after;
- QWidget *viewport;
- AnimatedOperation() : item(0) { setEasingCurve(QEasingCurve::InOutQuad); }
- int top() const { return startValue().toInt(); }
- QRect rect() const { QRect rect = viewport->rect(); rect.moveTop(top()); return rect; }
- void updateCurrentValue(const QVariant &) { viewport->update(rect()); }
- void updateState(State state, State) { if (state == Stopped) before = after = QPixmap(); }
- } animatedOperation;
- void prepareAnimatedOperation(int item, QVariantAnimation::Direction d);
- void beginAnimatedOperation();
- void drawAnimatedOperation(QPainter *painter) const;
- QPixmap renderTreeToPixmapForAnimation(const QRect &rect) const;
- void _q_endAnimatedOperation();
-#endif //QT_NO_ANIMATION
-
- void expand(int item, bool emitSignal);
- void collapse(int item, bool emitSignal);
-
- void _q_columnsAboutToBeRemoved(const QModelIndex &, int, int);
- void _q_columnsRemoved(const QModelIndex &, int, int);
- void _q_modelAboutToBeReset();
- void _q_sortIndicatorChanged(int column, Qt::SortOrder order);
- void _q_modelDestroyed();
-
- void layout(int item, bool recusiveExpanding = false, bool afterIsUninitialized = false);
-
- int pageUp(int item) const;
- int pageDown(int item) const;
-
- int itemHeight(int item) const;
- int indentationForItem(int item) const;
- int coordinateForItem(int item) const;
- int itemAtCoordinate(int coordinate) const;
-
- int viewIndex(const QModelIndex &index) const;
- QModelIndex modelIndex(int i, int column = 0) const;
-
- void insertViewItems(int pos, int count, const QTreeViewItem &viewItem);
- void removeViewItems(int pos, int count);
-#if 0
- bool checkViewItems() const;
-#endif
-
- int firstVisibleItem(int *offset = 0) const;
- int columnAt(int x) const;
- bool hasVisibleChildren( const QModelIndex& parent) const;
-
- bool expandOrCollapseItemAtPos(const QPoint &pos);
-
- void updateScrollBars();
-
- int itemDecorationAt(const QPoint &pos) const;
- QRect itemDecorationRect(const QModelIndex &index) const;
-
-
- QList<QPair<int, int> > columnRanges(const QModelIndex &topIndex, const QModelIndex &bottomIndex) const;
- void select(const QModelIndex &start, const QModelIndex &stop, QItemSelectionModel::SelectionFlags command);
-
- QPair<int,int> startAndEndColumns(const QRect &rect) const;
-
- void updateChildCount(const int parentItem, const int delta);
-
- void paintAlternatingRowColors(QPainter *painter, QStyleOptionViewItemV4 *option, int y, int bottom) const;
-
- QHeaderView *header;
- int indent;
-
- mutable QVector<QTreeViewItem> viewItems;
- mutable int lastViewedItem;
- int defaultItemHeight; // this is just a number; contentsHeight() / numItems
- bool uniformRowHeights; // used when all rows have the same height
- bool rootDecoration;
- bool itemsExpandable;
- bool sortingEnabled;
- bool expandsOnDoubleClick;
- bool allColumnsShowFocus;
-
- // used for drawing
- mutable QPair<int,int> leftAndRight;
- mutable int current;
- mutable bool spanning;
-
- // used when expanding and collapsing items
- QSet<QPersistentModelIndex> expandedIndexes;
- bool animationsEnabled;
-
- inline bool storeExpanded(const QPersistentModelIndex &idx) {
- if (expandedIndexes.contains(idx))
- return false;
- expandedIndexes.insert(idx);
- return true;
- }
-
- inline bool isIndexExpanded(const QModelIndex &idx) const {
- //We first check if the idx is a QPersistentModelIndex, because creating QPersistentModelIndex is slow
- return isPersistent(idx) && expandedIndexes.contains(idx);
- }
-
- // used when hiding and showing items
- QSet<QPersistentModelIndex> hiddenIndexes;
-
- inline bool isRowHidden(const QModelIndex &idx) const {
- //We first check if the idx is a QPersistentModelIndex, because creating QPersistentModelIndex is slow
- return isPersistent(idx) && hiddenIndexes.contains(idx);
- }
-
- inline bool isItemHiddenOrDisabled(int i) const {
- if (i < 0 || i >= viewItems.count())
- return false;
- const QModelIndex index = viewItems.at(i).index;
- return isRowHidden(index) || !isIndexEnabled(index);
- }
-
- inline int above(int item) const
- { int i = item; while (isItemHiddenOrDisabled(--item)){} return item < 0 ? i : item; }
- inline int below(int item) const
- { int i = item; while (isItemHiddenOrDisabled(++item)){} return item >= viewItems.count() ? i : item; }
- inline void invalidateHeightCache(int item) const
- { viewItems[item].height = 0; }
-
- // used for spanning rows
- QVector<QPersistentModelIndex> spanningIndexes;
-
- // used for updating resized columns
- int columnResizeTimerID;
- QList<int> columnsToUpdate;
-
- // used for the automatic opening of nodes during DND
- int autoExpandDelay;
- QBasicTimer openTimer;
-
- // used for drawing hilighted expand/collapse indicators
- int hoverBranch;
-
- // used for blocking recursion when calling setViewportMargins from updateGeometries
- bool geometryRecursionBlock;
-
- // If we should clean the set
- bool hasRemovedItems;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TREEVIEW
-
-#endif // QTREEVIEW_P_H
diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp
deleted file mode 100644
index 2ea9a4316b..0000000000
--- a/src/gui/itemviews/qtreewidget.cpp
+++ /dev/null
@@ -1,3460 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtreewidget.h"
-
-#ifndef QT_NO_TREEWIDGET
-#include <qheaderview.h>
-#include <qpainter.h>
-#include <qitemdelegate.h>
-#include <qstack.h>
-#include <qdebug.h>
-#include <private/qtreewidget_p.h>
-#include <private/qwidgetitemdata_p.h>
-#include <private/qtreewidgetitemiterator_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// workaround for VC++ 6.0 linker bug (?)
-typedef bool(*LessThan)(const QPair<QTreeWidgetItem*,int>&,const QPair<QTreeWidgetItem*,int>&);
-
-class QTreeModelLessThan
-{
-public:
- inline bool operator()(QTreeWidgetItem *i1, QTreeWidgetItem *i2) const
- { return *i1 < *i2; }
-};
-
-class QTreeModelGreaterThan
-{
-public:
- inline bool operator()(QTreeWidgetItem *i1, QTreeWidgetItem *i2) const
- { return *i2 < *i1; }
-};
-
-/*
- \class QTreeModel
- \brief The QTreeModel class manages the items stored in a tree view.
-
- \ingroup model-view
-
-*/
-
-/*!
- \enum QTreeWidgetItem::ChildIndicatorPolicy
- \since 4.3
-
- \value ShowIndicator The controls for expanding and collapsing will be shown for this item even if there are no children.
- \value DontShowIndicator The controls for expanding and collapsing will never be shown even if there are children. If the node is forced open the user will not be able to expand or collapse the item.
- \value DontShowIndicatorWhenChildless The controls for expanding and collapsing will be shown if the item contains children.
-*/
-
-/*!
- \fn void QTreeWidgetItem::setDisabled(bool disabled)
- \since 4.3
-
- Disables the item if \a disabled is true; otherwise enables the item.
-
- \sa setFlags()
-*/
-
-/*!
- \fn bool QTreeWidgetItem::isDisabled() const
- \since 4.3
-
- Returns true if the item is disabled; otherwise returns false.
-
- \sa setFlags()
-*/
-
-/*!
- \internal
-
- Constructs a tree model with a \a parent object and the given
- number of \a columns.
-*/
-
-QTreeModel::QTreeModel(int columns, QTreeWidget *parent)
- : QAbstractItemModel(parent), rootItem(new QTreeWidgetItem),
- headerItem(new QTreeWidgetItem), skipPendingSort(false)
-{
- rootItem->view = parent;
- rootItem->itemFlags = Qt::ItemIsDropEnabled;
- headerItem->view = parent;
- setColumnCount(columns);
-}
-
-/*!
- \internal
-
-*/
-
-QTreeModel::QTreeModel(QTreeModelPrivate &dd, QTreeWidget *parent)
- : QAbstractItemModel(dd, parent), rootItem(new QTreeWidgetItem),
- headerItem(new QTreeWidgetItem), skipPendingSort(false)
-{
- rootItem->view = parent;
- rootItem->itemFlags = Qt::ItemIsDropEnabled;
- headerItem->view = parent;
-}
-
-/*!
- \internal
-
- Destroys this tree model.
-*/
-
-QTreeModel::~QTreeModel()
-{
- clear();
- delete headerItem;
- rootItem->view = 0;
- delete rootItem;
-}
-
-/*!
- \internal
-
- Removes all items in the model.
-*/
-
-void QTreeModel::clear()
-{
- SkipSorting skipSorting(this);
- for (int i = 0; i < rootItem->childCount(); ++i) {
- QTreeWidgetItem *item = rootItem->children.at(i);
- item->par = 0;
- item->view = 0;
- delete item;
- }
- rootItem->children.clear();
- sortPendingTimer.stop();
- reset();
-}
-
-/*!
- \internal
-
- Sets the number of \a columns in the tree model.
-*/
-
-void QTreeModel::setColumnCount(int columns)
-{
- SkipSorting skipSorting(this);
- if (columns < 0)
- return;
- if (!headerItem) {
- headerItem = new QTreeWidgetItem();
- headerItem->view = view();
- }
- int count = columnCount();
- if (count == columns)
- return;
-
- if (columns < count) {
- beginRemoveColumns(QModelIndex(), columns, count - 1);
- headerItem->values.resize(columns);
- endRemoveColumns();
- } else {
- beginInsertColumns(QModelIndex(), count, columns - 1);
- headerItem->values.resize(columns);
- for (int i = count; i < columns; ++i) {// insert data without emitting the dataChanged signal
- headerItem->values[i].append(QWidgetItemData(Qt::DisplayRole, QString::number(i + 1)));
- headerItem->d->display.append(QString::number(i + 1));
- }
- endInsertColumns();
- }
-}
-
-/*!
- \internal
-
- Returns the tree view item corresponding to the \a index given.
-
- \sa QModelIndex
-*/
-
-QTreeWidgetItem *QTreeModel::item(const QModelIndex &index) const
-{
- if (!index.isValid())
- return 0;
- return static_cast<QTreeWidgetItem*>(index.internalPointer());
-}
-
-/*!
- \internal
-
- Returns the model index that refers to the
- tree view \a item and \a column.
-*/
-
-QModelIndex QTreeModel::index(const QTreeWidgetItem *item, int column) const
-{
- executePendingSort();
-
- if (!item || (item == rootItem))
- return QModelIndex();
- const QTreeWidgetItem *par = item->parent();
- QTreeWidgetItem *itm = const_cast<QTreeWidgetItem*>(item);
- if (!par)
- par = rootItem;
- int row;
- int guess = item->d->rowGuess;
- if (guess >= 0
- && par->children.count() > guess
- && par->children.at(guess) == itm) {
- row = guess;
- } else {
- row = par->children.lastIndexOf(itm);
- itm->d->rowGuess = row;
- }
- return createIndex(row, column, itm);
-}
-
-/*!
- \internal
- \reimp
-
- Returns the model index with the given \a row,
- \a column and \a parent.
-*/
-
-QModelIndex QTreeModel::index(int row, int column, const QModelIndex &parent) const
-{
- executePendingSort();
-
- int c = columnCount(parent);
- if (row < 0 || column < 0 || column >= c)
- return QModelIndex();
-
- QTreeWidgetItem *parentItem = parent.isValid() ? item(parent) : rootItem;
- if (parentItem && row < parentItem->childCount()) {
- QTreeWidgetItem *itm = parentItem->child(row);
- if (itm)
- return createIndex(row, column, itm);
- return QModelIndex();
- }
-
- return QModelIndex();
-}
-
-/*!
- \internal
- \reimp
-
- Returns the parent model index of the index given as
- the \a child.
-*/
-
-QModelIndex QTreeModel::parent(const QModelIndex &child) const
-{
- SkipSorting skipSorting(this); //The reason we don't sort here is that this might be called from a valid QPersistentModelIndex
- //We don't want it to become suddenly invalid
-
- if (!child.isValid())
- return QModelIndex();
- QTreeWidgetItem *itm = static_cast<QTreeWidgetItem *>(child.internalPointer());
- if (!itm || itm == rootItem)
- return QModelIndex();
- QTreeWidgetItem *parent = itm->parent();
- return index(parent, 0);
-}
-
-/*!
- \internal
- \reimp
-
- Returns the number of rows in the \a parent model index.
-*/
-
-int QTreeModel::rowCount(const QModelIndex &parent) const
-{
- if (!parent.isValid())
- return rootItem->childCount();
-
- QTreeWidgetItem *parentItem = item(parent);
- if (parentItem)
- return parentItem->childCount();
- return 0;
-}
-
-/*!
- \internal
- \reimp
-
- Returns the number of columns in the item referred to by
- the given \a index.
-*/
-
-int QTreeModel::columnCount(const QModelIndex &index) const
-{
- Q_UNUSED(index);
- if (!headerItem)
- return 0;
- return headerItem->columnCount();
-}
-
-bool QTreeModel::hasChildren(const QModelIndex &parent) const
-{
- if (!parent.isValid())
- return (rootItem->childCount() > 0);
-
- QTreeWidgetItem *itm = item(parent);
- if (!itm)
- return false;
- switch (itm->d->policy) {
- case QTreeWidgetItem::ShowIndicator:
- return true;
- case QTreeWidgetItem::DontShowIndicator:
- return false;
- case QTreeWidgetItem::DontShowIndicatorWhenChildless:
- return (itm->childCount() > 0);
- }
- return false;
-}
-
-/*!
- \internal
- \reimp
-
- Returns the data corresponding to the given model \a index
- and \a role.
-*/
-
-QVariant QTreeModel::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid())
- return QVariant();
- QTreeWidgetItem *itm = item(index);
- if (itm)
- return itm->data(index.column(), role);
- return QVariant();
-}
-
-/*!
- \internal
- \reimp
-
- Sets the data for the item specified by the \a index and \a role
- to that referred to by the \a value.
-
- Returns true if successful; otherwise returns false.
-*/
-
-bool QTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (!index.isValid())
- return false;
- QTreeWidgetItem *itm = item(index);
- if (itm) {
- itm->setData(index.column(), role, value);
- return true;
- }
- return false;
-}
-
-QMap<int, QVariant> QTreeModel::itemData(const QModelIndex &index) const
-{
- QMap<int, QVariant> roles;
- QTreeWidgetItem *itm = item(index);
- if (itm) {
- int column = index.column();
- if (column < itm->values.count()) {
- for (int i = 0; i < itm->values.at(column).count(); ++i) {
- roles.insert(itm->values.at(column).at(i).role,
- itm->values.at(column).at(i).value);
- }
- }
-
- // the two special cases
- QVariant displayValue = itm->data(column, Qt::DisplayRole);
- if (displayValue.isValid())
- roles.insert(Qt::DisplayRole, displayValue);
-
- QVariant checkValue = itm->data(column, Qt::CheckStateRole);
- if (checkValue.isValid())
- roles.insert(Qt::CheckStateRole, checkValue);
- }
- return roles;
-}
-
-/*!
- \internal
- \reimp
-*/
-bool QTreeModel::insertRows(int row, int count, const QModelIndex &parent)
-{
- SkipSorting skipSorting(this);
- if (count < 1 || row < 0 || row > rowCount(parent) || parent.column() > 0)
- return false;
-
- beginInsertRows(parent, row, row + count - 1);
- QTreeWidgetItem *par = item(parent);
- while (count > 0) {
- QTreeWidgetItem *item = new QTreeWidgetItem();
- item->view = view();
- item->par = par;
- if (par)
- par->children.insert(row++, item);
- else
- rootItem->children.insert(row++, item);
- --count;
- }
- endInsertRows();
- return true;
-}
-
-/*!
- \internal
- \reimp
-*/
-bool QTreeModel::insertColumns(int column, int count, const QModelIndex &parent)
-{
- SkipSorting skipSorting(this);
- if (count < 1 || column < 0 || column > columnCount(parent) || parent.column() > 0 || !headerItem)
- return false;
-
- beginInsertColumns(parent, column, column + count - 1);
-
- int oldCount = columnCount(parent);
- column = qBound(0, column, oldCount);
- headerItem->values.resize(oldCount + count);
- for (int i = oldCount; i < oldCount + count; ++i) {
- headerItem->values[i].append(QWidgetItemData(Qt::DisplayRole, QString::number(i + 1)));
- headerItem->d->display.append(QString::number(i + 1));
- }
-
- QStack<QTreeWidgetItem*> itemstack;
- itemstack.push(0);
- while (!itemstack.isEmpty()) {
- QTreeWidgetItem *par = itemstack.pop();
- QList<QTreeWidgetItem*> children = par ? par->children : rootItem->children;
- for (int row = 0; row < children.count(); ++row) {
- QTreeWidgetItem *child = children.at(row);
- if (child->children.count())
- itemstack.push(child);
- child->values.insert(column, count, QVector<QWidgetItemData>());
- }
- }
-
- endInsertColumns();
- return true;
-}
-
-/*!
- \internal
- \reimp
-*/
-bool QTreeModel::removeRows(int row, int count, const QModelIndex &parent) {
- if (count < 1 || row < 0 || (row + count) > rowCount(parent))
- return false;
-
- beginRemoveRows(parent, row, row + count - 1);
-
- bool blockSignal = signalsBlocked();
- blockSignals(true);
-
- QTreeWidgetItem *itm = item(parent);
- for (int i = row + count - 1; i >= row; --i) {
- QTreeWidgetItem *child = itm ? itm->takeChild(i) : rootItem->children.takeAt(i);
- Q_ASSERT(child);
- child->view = 0;
- delete child;
- child = 0;
- }
- blockSignals(blockSignal);
-
- endRemoveRows();
- return true;
-}
-
-/*!
- \internal
- \reimp
-
- Returns the header data corresponding to the given header \a section,
- \a orientation and data \a role.
-*/
-
-QVariant QTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (orientation != Qt::Horizontal)
- return QVariant();
-
- if (headerItem)
- return headerItem->data(section, role);
- if (role == Qt::DisplayRole)
- return QString::number(section + 1);
- return QVariant();
-}
-
-/*!
- \internal
- \reimp
-
- Sets the header data for the item specified by the header \a section,
- \a orientation and data \a role to the given \a value.
-
- Returns true if successful; otherwise returns false.
-*/
-
-bool QTreeModel::setHeaderData(int section, Qt::Orientation orientation,
- const QVariant &value, int role)
-{
- if (section < 0 || orientation != Qt::Horizontal || !headerItem || section >= columnCount())
- return false;
-
- headerItem->setData(section, role, value);
- return true;
-}
-
-/*!
- \reimp
-
- Returns the flags for the item referred to the given \a index.
-
-*/
-
-Qt::ItemFlags QTreeModel::flags(const QModelIndex &index) const
-{
- if (!index.isValid())
- return rootItem->flags();
- QTreeWidgetItem *itm = item(index);
- Q_ASSERT(itm);
- return itm->flags();
-}
-
-/*!
- \internal
-
- Sorts the entire tree in the model in the given \a order,
- by the values in the given \a column.
-*/
-
-void QTreeModel::sort(int column, Qt::SortOrder order)
-{
- SkipSorting skipSorting(this);
- sortPendingTimer.stop();
-
- if (column < 0 || column >= columnCount())
- return;
-
- //layoutAboutToBeChanged and layoutChanged will be called by sortChildren
- rootItem->sortChildren(column, order, true);
-}
-
-/*!
- \internal
-*/
-void QTreeModel::ensureSorted(int column, Qt::SortOrder order,
- int start, int end, const QModelIndex &parent)
-{
- if (isChanging())
- return;
-
- sortPendingTimer.stop();
-
- if (column < 0 || column >= columnCount())
- return;
-
- SkipSorting skipSorting(this);
-
- QTreeWidgetItem *itm = item(parent);
- if (!itm)
- itm = rootItem;
- QList<QTreeWidgetItem*> lst = itm->children;
-
- int count = end - start + 1;
- QVector < QPair<QTreeWidgetItem*,int> > sorting(count);
- for (int i = 0; i < count; ++i) {
- sorting[i].first = lst.at(start + i);
- sorting[i].second = start + i;
- }
-
- LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- qStableSort(sorting.begin(), sorting.end(), compare);
-
- QModelIndexList oldPersistentIndexes;
- QModelIndexList newPersistentIndexes;
- QList<QTreeWidgetItem*>::iterator lit = lst.begin();
- bool changed = false;
-
- for (int i = 0; i < count; ++i) {
- int oldRow = sorting.at(i).second;
- QTreeWidgetItem *item = lst.takeAt(oldRow);
- lit = sortedInsertionIterator(lit, lst.end(), order, item);
- int newRow = qMax(lit - lst.begin(), 0);
-
- if ((newRow < oldRow) && !(*item < *lst.at(oldRow - 1)) && !(*lst.at(oldRow - 1) < *item ))
- newRow = oldRow;
-
- lit = lst.insert(lit, item);
- if (newRow != oldRow) {
- // we are going to change the persistent indexes, so we need to prepare
- if (!changed) { // this will only happen once
- changed = true;
- emit layoutAboutToBeChanged(); // the selection model needs to know
- oldPersistentIndexes = persistentIndexList();
- newPersistentIndexes = oldPersistentIndexes;
- }
- for (int j = i + 1; j < count; ++j) {
- int otherRow = sorting.at(j).second;
- if (oldRow < otherRow && newRow >= otherRow)
- --sorting[j].second;
- else if (oldRow > otherRow && newRow <= otherRow)
- ++sorting[j].second;
- }
- for (int k = 0; k < newPersistentIndexes.count(); ++k) {
- QModelIndex pi = newPersistentIndexes.at(k);
- if (pi.parent() != parent)
- continue;
- int oldPersistentRow = pi.row();
- int newPersistentRow = oldPersistentRow;
- if (oldPersistentRow == oldRow)
- newPersistentRow = newRow;
- else if (oldRow < oldPersistentRow && newRow >= oldPersistentRow)
- newPersistentRow = oldPersistentRow - 1;
- else if (oldRow > oldPersistentRow && newRow <= oldPersistentRow)
- newPersistentRow = oldPersistentRow + 1;
- if (newPersistentRow != oldPersistentRow)
- newPersistentIndexes[k] = createIndex(newPersistentRow,
- pi.column(), pi.internalPointer());
- }
- }
- }
-
- if (changed) {
- itm->children = lst;
- changePersistentIndexList(oldPersistentIndexes, newPersistentIndexes);
- emit layoutChanged();
- }
-}
-
-/*!
- \internal
-
- Returns true if the value of the \a left item is
- less than the value of the \a right item.
-
- Used by the sorting functions.
-*/
-
-bool QTreeModel::itemLessThan(const QPair<QTreeWidgetItem*,int> &left,
- const QPair<QTreeWidgetItem*,int> &right)
-{
- return *(left.first) < *(right.first);
-}
-
-/*!
- \internal
-
- Returns true if the value of the \a left item is
- greater than the value of the \a right item.
-
- Used by the sorting functions.
-*/
-
-bool QTreeModel::itemGreaterThan(const QPair<QTreeWidgetItem*,int> &left,
- const QPair<QTreeWidgetItem*,int> &right)
-{
- return *(right.first) < *(left.first);
-}
-
-/*!
- \internal
-*/
-QList<QTreeWidgetItem*>::iterator QTreeModel::sortedInsertionIterator(
- const QList<QTreeWidgetItem*>::iterator &begin,
- const QList<QTreeWidgetItem*>::iterator &end,
- Qt::SortOrder order, QTreeWidgetItem *item)
-{
- if (order == Qt::AscendingOrder)
- return qLowerBound(begin, end, item, QTreeModelLessThan());
- return qLowerBound(begin, end, item, QTreeModelGreaterThan());
-}
-
-QStringList QTreeModel::mimeTypes() const
-{
- return view()->mimeTypes();
-}
-
-QMimeData *QTreeModel::internalMimeData() const
-{
- return QAbstractItemModel::mimeData(cachedIndexes);
-}
-
-QMimeData *QTreeModel::mimeData(const QModelIndexList &indexes) const
-{
- QList<QTreeWidgetItem*> items;
- for (int i = 0; i < indexes.count(); ++i) {
- if (indexes.at(i).column() == 0) // only one item per row
- items << item(indexes.at(i));
- }
-
- // cachedIndexes is a little hack to avoid copying from QModelIndexList to
- // QList<QTreeWidgetItem*> and back again in the view
- cachedIndexes = indexes;
- QMimeData *mimeData = view()->mimeData(items);
- cachedIndexes.clear();
- return mimeData;
-}
-
-bool QTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent)
-{
- if (row == -1 && column == -1)
- row = rowCount(parent); // append
- return view()->dropMimeData(item(parent), row, data, action);
-}
-
-Qt::DropActions QTreeModel::supportedDropActions() const
-{
- return view()->supportedDropActions();
-}
-
-void QTreeModel::itemChanged(QTreeWidgetItem *item)
-{
- SkipSorting skipSorting(this); //this is kind of wrong, but not doing this would kill performence
- QModelIndex left = index(item, 0);
- QModelIndex right = index(item, item->columnCount() - 1);
- emit dataChanged(left, right);
-}
-
-bool QTreeModel::isChanging() const
-{
- Q_D(const QTreeModel);
- return !d->changes.isEmpty();
-}
-
-/*!
- \internal
- Emits the dataChanged() signal for the given \a item.
- if column is -1 then all columns have changed
-*/
-
-void QTreeModel::emitDataChanged(QTreeWidgetItem *item, int column)
-{
- if (signalsBlocked())
- return;
-
- if (headerItem == item && column < item->columnCount()) {
- if (column == -1)
- emit headerDataChanged(Qt::Horizontal, 0, columnCount() - 1);
- else
- emit headerDataChanged(Qt::Horizontal, column, column);
- return;
- }
-
- SkipSorting skipSorting(this); //This is a little bit wrong, but not doing it would kill performence
-
- QModelIndex bottomRight, topLeft;
- if (column == -1) {
- topLeft = index(item, 0);
- bottomRight = createIndex(topLeft.row(), columnCount() - 1, item);
- } else {
- topLeft = index(item, column);
- bottomRight = topLeft;
- }
- emit dataChanged(topLeft, bottomRight);
-}
-
-void QTreeModel::beginInsertItems(QTreeWidgetItem *parent, int row, int count)
-{
- QModelIndex par = index(parent, 0);
- beginInsertRows(par, row, row + count - 1);
-}
-
-void QTreeModel::endInsertItems()
-{
- endInsertRows();
-}
-
-void QTreeModel::beginRemoveItems(QTreeWidgetItem *parent, int row, int count)
-{
- Q_ASSERT(row >= 0);
- Q_ASSERT(count > 0);
- beginRemoveRows(index(parent, 0), row, row + count - 1);
- if (!parent)
- parent = rootItem;
- // now update the iterators
- for (int i = 0; i < iterators.count(); ++i) {
- for (int j = 0; j < count; j++) {
- QTreeWidgetItem *c = parent->child(row + j);
- iterators[i]->d_func()->ensureValidIterator(c);
- }
- }
-}
-
-void QTreeModel::endRemoveItems()
-{
- endRemoveRows();
-}
-
-void QTreeModel::sortItems(QList<QTreeWidgetItem*> *items, int column, Qt::SortOrder order)
-{
- // see QTreeViewItem::operator<
- Q_UNUSED(column);
- if (isChanging())
- return;
-
- // store the original order of indexes
- QVector< QPair<QTreeWidgetItem*,int> > sorting(items->count());
- for (int i = 0; i < sorting.count(); ++i) {
- sorting[i].first = items->at(i);
- sorting[i].second = i;
- }
-
- // do the sorting
- LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
- qStableSort(sorting.begin(), sorting.end(), compare);
-
- QModelIndexList fromList;
- QModelIndexList toList;
- int colCount = columnCount();
- for (int r = 0; r < sorting.count(); ++r) {
- int oldRow = sorting.at(r).second;
- if (oldRow == r)
- continue;
- QTreeWidgetItem *item = sorting.at(r).first;
- items->replace(r, item);
- for (int c = 0; c < colCount; ++c) {
- QModelIndex from = createIndex(oldRow, c, item);
- if (static_cast<QAbstractItemModelPrivate *>(d_ptr.data())->persistent.indexes.contains(from)) {
- QModelIndex to = createIndex(r, c, item);
- fromList << from;
- toList << to;
- }
- }
- }
- changePersistentIndexList(fromList, toList);
-}
-
-void QTreeModel::timerEvent(QTimerEvent *ev)
-{
- if (ev->timerId() == sortPendingTimer.timerId()) {
- executePendingSort();
- } else {
- QAbstractItemModel::timerEvent(ev);
- }
-}
-
-/*!
- \class QTreeWidgetItem
-
- \brief The QTreeWidgetItem class provides an item for use with the
- QTreeWidget convenience class.
-
- \ingroup model-view
-
- Tree widget items are used to hold rows of information for tree widgets.
- Rows usually contain several columns of data, each of which can contain
- a text label and an icon.
-
- The QTreeWidgetItem class is a convenience class that replaces the
- QListViewItem class in Qt 3. It provides an item for use with
- the QTreeWidget class.
-
- Items are usually constructed with a parent that is either a QTreeWidget
- (for top-level items) or a QTreeWidgetItem (for items on lower levels of
- the tree). For example, the following code constructs a top-level item
- to represent cities of the world, and adds a entry for Oslo as a child
- item:
-
- \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 3
-
- Items can be added in a particular order by specifying the item they
- follow when they are constructed:
-
- \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 5
-
- Each column in an item can have its own background brush which is set with
- the setBackground() function. The current background brush can be
- found with background().
- The text label for each column can be rendered with its own font and brush.
- These are specified with the setFont() and setForeground() functions,
- and read with font() and foreground().
-
- The main difference between top-level items and those in lower levels of
- the tree is that a top-level item has no parent(). This information
- can be used to tell the difference between items, and is useful to know
- when inserting and removing items from the tree.
- Children of an item can be removed with takeChild() and inserted at a
- given index in the list of children with the insertChild() function.
-
- By default, items are enabled, selectable, checkable, and can be the source
- of a drag and drop operation.
- Each item's flags can be changed by calling setFlags() with the appropriate
- value (see \l{Qt::ItemFlags}). Checkable items can be checked and unchecked
- with the setCheckState() function. The corresponding checkState() function
- indicates whether the item is currently checked.
-
- \section1 Subclassing
-
- When subclassing QTreeWidgetItem to provide custom items, it is possible to
- define new types for them so that they can be distinguished from standard
- items. The constructors for subclasses that require this feature need to
- call the base class constructor with a new type value equal to or greater
- than \l UserType.
-
- \sa QTreeWidget, QTreeWidgetItemIterator, {Model/View Programming},
- QListWidgetItem, QTableWidgetItem
-*/
-
-/*!
- \enum QTreeWidgetItem::ItemType
-
- This enum describes the types that are used to describe tree widget items.
-
- \value Type The default type for tree widget items.
- \value UserType The minimum value for custom types. Values below UserType are
- reserved by Qt.
-
- You can define new user types in QTreeWidgetItem subclasses to ensure that
- custom items are treated specially; for example, when items are sorted.
-
- \sa type()
-*/
-
-/*!
- \fn int QTreeWidgetItem::type() const
-
- Returns the type passed to the QTreeWidgetItem constructor.
-*/
-
-/*!
- \fn void QTreeWidgetItem::sortChildren(int column, Qt::SortOrder order)
- \since 4.2
-
- Sorts the children of the item using the given \a order,
- by the values in the given \a column.
-
- \note This function does nothing if the item is not associated with a
- QTreeWidget.
-*/
-
-/*!
- \fn QTreeWidget *QTreeWidgetItem::treeWidget() const
-
- Returns the tree widget that contains the item.
-*/
-
-/*!
- \fn void QTreeWidgetItem::setSelected(bool select)
- \since 4.2
-
- Sets the selected state of the item to \a select.
-
- \sa isSelected()
-
-*/
-
-/*!
- \fn bool QTreeWidgetItem::isSelected() const
- \since 4.2
-
- Returns true if the item is selected, otherwise returns false.
-
- \sa setSelected()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setHidden(bool hide)
- \since 4.2
-
- Hides the item if \a hide is true, otherwise shows the item.
-
- \sa isHidden()
-*/
-
-/*!
- \fn bool QTreeWidgetItem::isHidden() const
- \since 4.2
-
- Returns true if the item is hidden, otherwise returns false.
-
- \sa setHidden()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setExpanded(bool expand)
- \since 4.2
-
- Expands the item if \a expand is true, otherwise collapses the item.
- \warning The QTreeWidgetItem must be added to the QTreeWidget before calling this function.
-
- \sa isExpanded()
-*/
-
-/*!
- \fn bool QTreeWidgetItem::isExpanded() const
- \since 4.2
-
- Returns true if the item is expanded, otherwise returns false.
-
- \sa setExpanded()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setFirstColumnSpanned(bool span)
- \since 4.3
-
- Sets the first section to span all columns if \a span is true;
- otherwise all item sections are shown.
-
- \sa isFirstColumnSpanned()
-*/
-
-/*!
- \fn bool QTreeWidgetItem::isFirstColumnSpanned() const
- \since 4.3
-
- Returns true if the item is spanning all the columns in a row; otherwise returns false.
-
- \sa setFirstColumnSpanned()
-*/
-
-/*!
- \fn QString QTreeWidgetItem::text(int column) const
-
- Returns the text in the specified \a column.
-
- \sa setText()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setText(int column, const QString &text)
-
- Sets the text to be displayed in the given \a column to the given \a text.
-
- \sa text() setFont() setForeground()
-*/
-
-/*!
- \fn QIcon QTreeWidgetItem::icon(int column) const
-
- Returns the icon that is displayed in the specified \a column.
-
- \sa setIcon(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn void QTreeWidgetItem::setIcon(int column, const QIcon &icon)
-
- Sets the icon to be displayed in the given \a column to \a icon.
-
- \sa icon(), setText(), {QAbstractItemView::iconSize}{iconSize}
-*/
-
-/*!
- \fn QString QTreeWidgetItem::statusTip(int column) const
-
- Returns the status tip for the contents of the given \a column.
-
- \sa setStatusTip()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setStatusTip(int column, const QString &statusTip)
-
- Sets the status tip for the given \a column to the given \a statusTip.
- QTreeWidget mouse tracking needs to be enabled for this feature to work.
-
- \sa statusTip() setToolTip() setWhatsThis()
-*/
-
-/*!
- \fn QString QTreeWidgetItem::toolTip(int column) const
-
- Returns the tool tip for the given \a column.
-
- \sa setToolTip()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setToolTip(int column, const QString &toolTip)
-
- Sets the tooltip for the given \a column to \a toolTip.
-
- \sa toolTip() setStatusTip() setWhatsThis()
-*/
-
-/*!
- \fn QString QTreeWidgetItem::whatsThis(int column) const
-
- Returns the "What's This?" help for the contents of the given \a column.
-
- \sa setWhatsThis()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setWhatsThis(int column, const QString &whatsThis)
-
- Sets the "What's This?" help for the given \a column to \a whatsThis.
-
- \sa whatsThis() setStatusTip() setToolTip()
-*/
-
-/*!
- \fn QFont QTreeWidgetItem::font(int column) const
-
- Returns the font used to render the text in the specified \a column.
-
- \sa setFont()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setFont(int column, const QFont &font)
-
- Sets the font used to display the text in the given \a column to the given
- \a font.
-
- \sa font() setText() setForeground()
-*/
-
-/*!
- \fn QColor QTreeWidgetItem::backgroundColor(int column) const
- \obsolete
-
- This function is deprecated. Use background() instead.
-*/
-
-/*!
- \fn void QTreeWidgetItem::setBackgroundColor(int column, const QColor &color)
- \obsolete
-
- This function is deprecated. Use setBackground() instead.
-*/
-
-/*!
- \fn QBrush QTreeWidgetItem::background(int column) const
- \since 4.2
-
- Returns the brush used to render the background of the specified \a column.
-
- \sa foreground()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setBackground(int column, const QBrush &brush)
- \since 4.2
-
- Sets the background brush of the label in the given \a column to the
- specified \a brush.
-
- \sa setForeground()
-*/
-
-/*!
- \fn QColor QTreeWidgetItem::textColor(int column) const
- \obsolete
-
- This function is deprecated. Use foreground() instead.
-*/
-
-/*!
- \fn void QTreeWidgetItem::setTextColor(int column, const QColor &color)
- \obsolete
-
- This function is deprecated. Use setForeground() instead.
-*/
-
-/*!
- \fn QBrush QTreeWidgetItem::foreground(int column) const
- \since 4.2
-
- Returns the brush used to render the foreground (e.g. text) of the
- specified \a column.
-
- \sa background()
-*/
-
-/*!
- \fn void QTreeWidgetItem::setForeground(int column, const QBrush &brush)
- \since 4.2
-
- Sets the foreground brush of the label in the given \a column to the
- specified \a brush.
-
- \sa setBackground()
-*/
-
-/*!
- \fn Qt::CheckState QTreeWidgetItem::checkState(int column) const
-
- Returns the check state of the label in the given \a column.
-
- \sa Qt::CheckState
-*/
-
-/*!
- \fn void QTreeWidgetItem::setCheckState(int column, Qt::CheckState state)
-
- Sets the item in the given \a column check state to be \a state.
-
- \sa checkState()
-*/
-
-/*!
- \fn QSize QTreeWidgetItem::sizeHint(int column) const
- \since 4.1
-
- Returns the size hint set for the tree item in the given
- \a column (see \l{QSize}).
-*/
-
-/*!
- \fn void QTreeWidgetItem::setSizeHint(int column, const QSize &size)
- \since 4.1
-
- Sets the size hint for the tree item in the given \a column to be \a size.
- If no size hint is set, the item delegate will compute the size hint based
- on the item data.
-*/
-
-/*!
- \fn QTreeWidgetItem *QTreeWidgetItem::parent() const
-
- Returns the item's parent.
-
- \sa child()
-*/
-
-/*!
- \fn QTreeWidgetItem *QTreeWidgetItem::child(int index) const
-
- Returns the item at the given \a index in the list of the item's children.
-
- \sa parent()
-*/
-
-/*!
- \fn int QTreeWidgetItem::childCount() const
-
- Returns the number of child items.
-*/
-
-/*!
- \fn int QTreeWidgetItem::columnCount() const
-
- Returns the number of columns in the item.
-*/
-
-/*!
- \fn int QTreeWidgetItem::textAlignment(int column) const
-
- Returns the text alignment for the label in the given \a column
- (see \l{Qt::AlignmentFlag}).
-*/
-
-/*!
- \fn void QTreeWidgetItem::setTextAlignment(int column, int alignment)
-
- Sets the text alignment for the label in the given \a column to
- the \a alignment specified (see \l{Qt::AlignmentFlag}).
-*/
-
-/*!
- \fn int QTreeWidgetItem::indexOfChild(QTreeWidgetItem *child) const
-
- Returns the index of the given \a child in the item's list of children.
-*/
-
-/*!
- Constructs a tree widget item of the specified \a type. The item
- must be inserted into a tree widget.
-
- \sa type()
-*/
-QTreeWidgetItem::QTreeWidgetItem(int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
-}
-
-
-/*!
- Constructs a tree widget item of the specified \a type. The item
- must be inserted into a tree widget.
- The given list of \a strings will be set as the item text for each
- column in the item.
-
- \sa type()
-*/
-QTreeWidgetItem::QTreeWidgetItem(const QStringList &strings, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- for (int i = 0; i < strings.count(); ++i)
- setText(i, strings.at(i));
-}
-
-/*!
- \fn QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *parent, int type)
-
- Constructs a tree widget item of the specified \a type and appends it
- to the items in the given \a parent.
-
- \sa type()
-*/
-
-QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *view, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- if (view && view->model()) {
- QTreeModel *model = qobject_cast<QTreeModel*>(view->model());
- model->rootItem->addChild(this);
- values.reserve(model->headerItem->columnCount());
- }
-}
-
-/*!
- \fn QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *parent, const QStringList &strings, int type)
-
- Constructs a tree widget item of the specified \a type and appends it
- to the items in the given \a parent. The given list of \a strings will be set as
- the item text for each column in the item.
-
- \sa type()
-*/
-
-QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *view, const QStringList &strings, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- for (int i = 0; i < strings.count(); ++i)
- setText(i, strings.at(i));
- if (view && view->model()) {
- QTreeModel *model = qobject_cast<QTreeModel*>(view->model());
- model->rootItem->addChild(this);
- values.reserve(model->headerItem->columnCount());
- }
-}
-
-/*!
- \fn QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *parent, QTreeWidgetItem *preceding, int type)
-
- Constructs a tree widget item of the specified \a type and inserts it into
- the given \a parent after the \a preceding item.
-
- \sa type()
-*/
-QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *view, QTreeWidgetItem *after, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- if (view) {
- QTreeModel *model = qobject_cast<QTreeModel*>(view->model());
- if (model) {
- int i = model->rootItem->children.indexOf(after) + 1;
- model->rootItem->insertChild(i, this);
- values.reserve(model->headerItem->columnCount());
- }
- }
-}
-
-/*!
- Constructs a tree widget item and append it to the given \a parent.
-
- \sa type()
-*/
-QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- if (parent)
- parent->addChild(this);
-}
-
-/*!
- Constructs a tree widget item and append it to the given \a parent.
- The given list of \a strings will be set as the item text for each column in the item.
-
- \sa type()
-*/
-QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- for (int i = 0; i < strings.count(); ++i)
- setText(i, strings.at(i));
- if (parent)
- parent->addChild(this);
-}
-
-/*!
- \fn QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, QTreeWidgetItem *preceding, int type)
-
- Constructs a tree widget item of the specified \a type that is inserted
- into the \a parent after the \a preceding child item.
-
- \sa type()
-*/
-QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, QTreeWidgetItem *after, int type)
- : rtti(type), view(0), d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(Qt::ItemIsSelectable
- |Qt::ItemIsUserCheckable
- |Qt::ItemIsEnabled
- |Qt::ItemIsDragEnabled
- |Qt::ItemIsDropEnabled)
-{
- if (parent) {
- int i = parent->children.indexOf(after) + 1;
- parent->insertChild(i, this);
- }
-}
-
-/*!
- Destroys this tree widget item.
-
- The item will be removed from \l{QTreeWidget}s to which it has
- been added. This makes it safe to delete an item at any time.
-
-*/
-
-QTreeWidgetItem::~QTreeWidgetItem()
-{
- QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0);
- bool wasSkipSort = false;
- if (model) {
- wasSkipSort = model->skipPendingSort;
- model->skipPendingSort = true;
- }
- if (par) {
- int i = par->children.indexOf(this);
- if (i >= 0) {
- if (model) model->beginRemoveItems(par, i, 1);
- // users _could_ do changes when connected to rowsAboutToBeRemoved,
- // so we check again to make sure 'i' is valid
- if (!par->children.isEmpty() && par->children.at(i) == this)
- par->children.takeAt(i);
- if (model) model->endRemoveItems();
- }
- } else if (model) {
- if (this == model->headerItem) {
- model->headerItem = 0;
- } else {
- int i = model->rootItem->children.indexOf(this);
- if (i >= 0) {
- model->beginRemoveItems(0, i, 1);
- // users _could_ do changes when connected to rowsAboutToBeRemoved,
- // so we check again to make sure 'i' is valid
- if (!model->rootItem->children.isEmpty() && model->rootItem->children.at(i) == this)
- model->rootItem->children.takeAt(i);
- model->endRemoveItems();
- }
- }
- }
- // at this point the persistent indexes for the children should also be invalidated
- // since we invalidated the parent
- for (int i = 0; i < children.count(); ++i) {
- QTreeWidgetItem *child = children.at(i);
- // make sure the child does not try to remove itself from our children list
- child->par = 0;
- // make sure the child does not try to remove itself from the top level list
- child->view = 0;
- delete child;
- }
-
- children.clear();
- delete d;
- if (model) {
- model->skipPendingSort = wasSkipSort;
- }
-}
-
-/*!
- Creates a deep copy of the item and of its children.
-*/
-QTreeWidgetItem *QTreeWidgetItem::clone() const
-{
- QTreeWidgetItem *copy = 0;
-
- QStack<const QTreeWidgetItem*> stack;
- QStack<QTreeWidgetItem*> parentStack;
- stack.push(this);
- parentStack.push(0);
-
- QTreeWidgetItem *root = 0;
- const QTreeWidgetItem *item = 0;
- QTreeWidgetItem *parent = 0;
- while (!stack.isEmpty()) {
- // get current item, and copied parent
- item = stack.pop();
- parent = parentStack.pop();
-
- // copy item
- copy = new QTreeWidgetItem(*item);
- if (!root)
- root = copy;
-
- // set parent and add to parents children list
- if (parent) {
- copy->par = parent;
- parent->children.insert(0, copy);
- }
-
- for (int i = 0; i < item->childCount(); ++i) {
- stack.push(item->child(i));
- parentStack.push(copy);
- }
- }
- return root;
-}
-
-/*!
- Sets the item indicator \a policy. This policy decides when the
- tree branch expand/collapse indicator is shown.
- The default value is ShowForChildren.
-
- \sa childIndicatorPolicy()
-*/
-void QTreeWidgetItem::setChildIndicatorPolicy(QTreeWidgetItem::ChildIndicatorPolicy policy)
-{
- if (d->policy == policy)
- return;
- d->policy = policy;
-
- if (!view)
- return;
-
- view->scheduleDelayedItemsLayout();
-}
-
-/*!
- Returns the item indicator policy. This policy decides when the
- tree branch expand/collapse indicator is shown.
-
- \sa setChildIndicatorPolicy()
-*/
-QTreeWidgetItem::ChildIndicatorPolicy QTreeWidgetItem::childIndicatorPolicy() const
-{
- return d->policy;
-}
-
-/*!
- \fn void QTreeWidgetItem::setFlags(Qt::ItemFlags flags)
-
- Sets the flags for the item to the given \a flags. These determine whether
- the item can be selected or modified. This is often used to disable an item.
-
- \sa flags()
-*/
-void QTreeWidgetItem::setFlags(Qt::ItemFlags flags)
-{
- const bool enable = (flags & Qt::ItemIsEnabled);
- const bool changedState = bool(itemFlags & Qt::ItemIsEnabled) != enable;
- const bool changedExplicit = d->disabled != !enable;
-
- d->disabled = !enable;
-
- if (enable && par && !(par->itemFlags & Qt::ItemIsEnabled)) // inherit from parent
- itemFlags = flags & ~Qt::ItemIsEnabled;
- else // this item is explicitly disabled or has no parent
- itemFlags = flags;
-
- if (changedState && changedExplicit) { // if the propagate the change to the children
- QStack<QTreeWidgetItem*> parents;
- parents.push(this);
- while (!parents.isEmpty()) {
- QTreeWidgetItem *parent = parents.pop();
- for (int i = 0; i < parent->children.count(); ++i) {
- QTreeWidgetItem *child = parent->children.at(i);
- if (!child->d->disabled) { // if not explicitly disabled
- parents.push(child);
- if (enable)
- child->itemFlags = child->itemFlags | Qt::ItemIsEnabled;
- else
- child->itemFlags = child->itemFlags & ~Qt::ItemIsEnabled;
- child->itemChanged(); // ### we may want to optimize this
- }
- }
- }
- }
- itemChanged();
-}
-
-void QTreeWidgetItemPrivate::propagateDisabled(QTreeWidgetItem *item)
-{
- Q_ASSERT(item);
- const bool enable = item->par ? (item->par->itemFlags.testFlag(Qt::ItemIsEnabled)) : true;
-
- QStack<QTreeWidgetItem*> parents;
- parents.push(item);
- while (!parents.isEmpty()) {
- QTreeWidgetItem *parent = parents.pop();
- if (!parent->d->disabled) { // if not explicitly disabled
- Qt::ItemFlags oldFlags = parent->itemFlags;
- if (enable)
- parent->itemFlags = parent->itemFlags | Qt::ItemIsEnabled;
- else
- parent->itemFlags = parent->itemFlags & ~Qt::ItemIsEnabled;
- if (parent->itemFlags != oldFlags)
- parent->itemChanged();
- }
-
- for (int i = 0; i < parent->children.count(); ++i) {
- QTreeWidgetItem *child = parent->children.at(i);
- parents.push(child);
- }
- }
-}
-/*!
- \fn Qt::ItemFlags QTreeWidgetItem::flags() const
-
- Returns the flags used to describe the item. These determine whether
- the item can be checked, edited, and selected.
-
- The default value for flags is
- Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled.
- If the item was constructed with a parent, flags will in addition contain Qt::ItemIsDropEnabled.
-
- \sa setFlags()
-*/
-Qt::ItemFlags QTreeWidgetItem::flags() const
-{
- return itemFlags;
-}
-
-/*!
- Sets the value for the item's \a column and \a role to the given
- \a value.
-
- The \a role describes the type of data specified by \a value, and is defined by
- the Qt::ItemDataRole enum.
-*/
-void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
-{
- if (column < 0)
- return;
-
- QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0);
- switch (role) {
- case Qt::EditRole:
- case Qt::DisplayRole: {
- if (values.count() <= column) {
- if (model && this == model->headerItem)
- model->setColumnCount(column + 1);
- else
- values.resize(column + 1);
- }
- if (d->display.count() <= column) {
- for (int i = d->display.count() - 1; i < column - 1; ++i)
- d->display.append(QVariant());
- d->display.append(value);
- } else if (d->display[column] != value) {
- d->display[column] = value;
- } else {
- return; // value is unchanged
- }
- } break;
- case Qt::CheckStateRole:
- if (itemFlags & Qt::ItemIsTristate) {
- for (int i = 0; i < children.count(); ++i) {
- QTreeWidgetItem *child = children.at(i);
- if (child->data(column, role).isValid()) {// has a CheckState
- Qt::ItemFlags f = itemFlags; // a little hack to avoid multiple dataChanged signals
- itemFlags &= ~Qt::ItemIsTristate;
- child->setData(column, role, value);
- itemFlags = f;
- }
- }
- }
- // Don't break, but fall through
- default:
- if (column < values.count()) {
- bool found = false;
- QVector<QWidgetItemData> column_values = values.at(column);
- for (int i = 0; i < column_values.count(); ++i) {
- if (column_values.at(i).role == role) {
- if (column_values.at(i).value == value)
- return; // value is unchanged
- values[column][i].value = value;
- found = true;
- break;
- }
- }
- if (!found)
- values[column].append(QWidgetItemData(role, value));
- } else {
- if (model && this == model->headerItem)
- model->setColumnCount(column + 1);
- else
- values.resize(column + 1);
- values[column].append(QWidgetItemData(role, value));
- }
- }
-
- if (model) {
- model->emitDataChanged(this, column);
- if (role == Qt::CheckStateRole) {
- QTreeWidgetItem *p;
- for (p = par; p && (p->itemFlags & Qt::ItemIsTristate); p = p->par)
- model->emitDataChanged(p, column);
- }
- }
-}
-
-/*!
- Returns the value for the item's \a column and \a role.
-*/
-QVariant QTreeWidgetItem::data(int column, int role) const
-{
- switch (role) {
- case Qt::EditRole:
- case Qt::DisplayRole:
- if (column >= 0 && column < d->display.count())
- return d->display.at(column);
- break;
- case Qt::CheckStateRole:
- // special case for check state in tristate
- if (children.count() && (itemFlags & Qt::ItemIsTristate))
- return childrenCheckState(column);
- // fallthrough intended
- default:
- if (column >= 0 && column < values.size()) {
- const QVector<QWidgetItemData> &column_values = values.at(column);
- for (int i = 0; i < column_values.count(); ++i)
- if (column_values.at(i).role == role)
- return column_values.at(i).value;
- }
- }
- return QVariant();
-}
-
-/*!
- Returns true if the text in the item is less than the text in the
- \a other item, otherwise returns false.
-*/
-
-bool QTreeWidgetItem::operator<(const QTreeWidgetItem &other) const
-{
- int column = view ? view->sortColumn() : 0;
- const QVariant v1 = data(column, Qt::DisplayRole);
- const QVariant v2 = other.data(column, Qt::DisplayRole);
- return QAbstractItemModelPrivate::variantLessThan(v1, v2);
-}
-
-#ifndef QT_NO_DATASTREAM
-
-/*!
- Reads the item from stream \a in. This only reads data into a single item.
-
- \sa write()
-*/
-void QTreeWidgetItem::read(QDataStream &in)
-{
- // convert from streams written before we introduced display (4.2.0)
- if (in.version() < QDataStream::Qt_4_2) {
- d->display.clear();
- in >> values;
- // move the display value over to the display string list
- for (int column = 0; column < values.count(); ++column) {
- d->display << QVariant();
- for (int i = 0; i < values.at(column).count(); ++i) {
- if (values.at(column).at(i).role == Qt::DisplayRole) {
- d->display[column] = values.at(column).at(i).value;
- values[column].remove(i--);
- }
- }
- }
- } else {
- in >> values >> d->display;
- }
-}
-
-/*!
- Writes the item to stream \a out. This only writes data from one single item.
-
- \sa read()
-*/
-void QTreeWidgetItem::write(QDataStream &out) const
-{
- out << values << d->display;
-}
-#endif // QT_NO_DATASTREAM
-
-/*!
- \since 4.1
-
- Constructs a copy of \a other. Note that type() and treeWidget()
- are not copied.
-
- This function is useful when reimplementing clone().
-
- \sa data(), flags()
-*/
-QTreeWidgetItem::QTreeWidgetItem(const QTreeWidgetItem &other)
- : rtti(Type), values(other.values), view(0),
- d(new QTreeWidgetItemPrivate(this)), par(0),
- itemFlags(other.itemFlags)
-{
- d->display = other.d->display;
-}
-
-/*!
- Assigns \a other's data and flags to this item. Note that type()
- and treeWidget() are not copied.
-
- This function is useful when reimplementing clone().
-
- \sa data(), flags()
-*/
-QTreeWidgetItem &QTreeWidgetItem::operator=(const QTreeWidgetItem &other)
-{
- values = other.values;
- d->display = other.d->display;
- d->policy = other.d->policy;
- itemFlags = other.itemFlags;
- return *this;
-}
-
-/*!
- Appends the \a child item to the list of children.
-
- \sa insertChild() takeChild()
-*/
-void QTreeWidgetItem::addChild(QTreeWidgetItem *child)
-{
- if (child) {
- insertChild(children.count(), child);
- child->d->rowGuess = children.count() - 1;
- }
-}
-
-/*!
- Inserts the \a child item at \a index in the list of children.
-
- If the child has already been inserted somewhere else it wont be inserted again.
-*/
-void QTreeWidgetItem::insertChild(int index, QTreeWidgetItem *child)
-{
- if (index < 0 || index > children.count() || child == 0 || child->view != 0 || child->par != 0)
- return;
-
- if (QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0)) {
- const bool wasSkipSort = model->skipPendingSort;
- model->skipPendingSort = true;
- if (model->rootItem == this)
- child->par = 0;
- else
- child->par = this;
- if (view->isSortingEnabled()) {
- // do a delayed sort instead
- if (!model->sortPendingTimer.isActive())
- model->sortPendingTimer.start(0, model);
- }
- model->beginInsertItems(this, index, 1);
- int cols = model->columnCount();
- QStack<QTreeWidgetItem*> stack;
- stack.push(child);
- while (!stack.isEmpty()) {
- QTreeWidgetItem *i = stack.pop();
- i->view = view;
- i->values.reserve(cols);
- for (int c = 0; c < i->children.count(); ++c)
- stack.push(i->children.at(c));
- }
- children.insert(index, child);
- model->endInsertItems();
- model->skipPendingSort = wasSkipSort;
- } else {
- child->par = this;
- children.insert(index, child);
- }
- if (child->par)
- d->propagateDisabled(child);
-}
-
-/*!
- Removes the given item indicated by \a child.
- The removed item will not be deleted.
-*/
-void QTreeWidgetItem::removeChild(QTreeWidgetItem *child)
-{
- (void)takeChild(children.indexOf(child));
-}
-
-/*!
- Removes the item at \a index and returns it, otherwise return 0.
-*/
-QTreeWidgetItem *QTreeWidgetItem::takeChild(int index)
-{
- // we move this outside the check of the index to allow executing
- // pending sorts from inline functions, using this function (hack)
- QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0);
- if (model) {
- // This will trigger a layoutChanged signal, thus we might want to optimize
- // this function by not emitting the rowsRemoved signal etc to the view.
- // On the other hand we also need to make sure that the selectionmodel
- // is updated in case we take an item that is selected.
- model->skipPendingSort = false;
- model->executePendingSort();
- }
- if (index >= 0 && index < children.count()) {
- if (model) model->beginRemoveItems(this, index, 1);
- QTreeWidgetItem *item = children.takeAt(index);
- item->par = 0;
- QStack<QTreeWidgetItem*> stack;
- stack.push(item);
- while (!stack.isEmpty()) {
- QTreeWidgetItem *i = stack.pop();
- i->view = 0;
- for (int c = 0; c < i->children.count(); ++c)
- stack.push(i->children.at(c));
- }
- d->propagateDisabled(item);
- if (model) model->endRemoveRows();
- return item;
- }
- return 0;
-}
-
-/*!
- \since 4.1
-
- Appends the given list of \a children to the item.
-
- \sa insertChildren() takeChildren()
-*/
-void QTreeWidgetItem::addChildren(const QList<QTreeWidgetItem*> &children)
-{
- insertChildren(this->children.count(), children);
-}
-
-/*!
- \since 4.1
-
- Inserts the given list of \a children into the list of the item children at \a index .
-
- Children that have already been inserted somewhere else wont be inserted.
-*/
-void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &children)
-{
- if (view && view->isSortingEnabled()) {
- for (int n = 0; n < children.count(); ++n)
- insertChild(index, children.at(n));
- return;
- }
- QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0);
- QStack<QTreeWidgetItem*> stack;
- QList<QTreeWidgetItem*> itemsToInsert;
- for (int n = 0; n < children.count(); ++n) {
- QTreeWidgetItem *child = children.at(n);
- if (child->view || child->par)
- continue;
- itemsToInsert.append(child);
- if (view && model) {
- if (child->childCount() == 0)
- child->view = view;
- else
- stack.push(child);
- }
- if (model && (model->rootItem == this))
- child->par = 0;
- else
- child->par = this;
- }
- if (!itemsToInsert.isEmpty()) {
- while (!stack.isEmpty()) {
- QTreeWidgetItem *i = stack.pop();
- i->view = view;
- for (int c = 0; c < i->children.count(); ++c)
- stack.push(i->children.at(c));
- }
- if (model) model->beginInsertItems(this, index, itemsToInsert.count());
- for (int n = 0; n < itemsToInsert.count(); ++n) {
- QTreeWidgetItem *child = itemsToInsert.at(n);
- this->children.insert(index + n, child);
- if (child->par)
- d->propagateDisabled(child);
- }
- if (model) model->endInsertItems();
- }
-}
-
-/*!
- \since 4.1
-
- Removes the list of children and returns it, otherwise returns an empty list.
-*/
-QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren()
-{
- QList<QTreeWidgetItem*> removed;
- if (children.count() > 0) {
- QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0);
- if (model) {
- // This will trigger a layoutChanged signal, thus we might want to optimize
- // this function by not emitting the rowsRemoved signal etc to the view.
- // On the other hand we also need to make sure that the selectionmodel
- // is updated in case we take an item that is selected.
- model->executePendingSort();
- }
- if (model) model->beginRemoveItems(this, 0, children.count());
- for (int n = 0; n < children.count(); ++n) {
- QTreeWidgetItem *item = children.at(n);
- item->par = 0;
- QStack<QTreeWidgetItem*> stack;
- stack.push(item);
- while (!stack.isEmpty()) {
- QTreeWidgetItem *i = stack.pop();
- i->view = 0;
- for (int c = 0; c < i->children.count(); ++c)
- stack.push(i->children.at(c));
- }
- d->propagateDisabled(item);
- }
- removed = children;
- children.clear(); // detach
- if (model) model->endRemoveItems();
- }
- return removed;
-}
-
-
-void QTreeWidgetItemPrivate::sortChildren(int column, Qt::SortOrder order, bool climb)
-{
- QTreeModel *model = (q->view ? qobject_cast<QTreeModel*>(q->view->model()) : 0);
- if (!model)
- return;
- model->sortItems(&q->children, column, order);
- if (climb) {
- QList<QTreeWidgetItem*>::iterator it = q->children.begin();
- for (; it != q->children.end(); ++it) {
- //here we call the private object's method to avoid emitting
- //the layoutAboutToBeChanged and layoutChanged signals
- (*it)->d->sortChildren(column, order, climb);
- }
- }
-}
-
-/*!
- \internal
-
- Sorts the children by the value in the given \a column, in the \a order
- specified. If \a climb is true, the items below each of the children will
- also be sorted.
-*/
-void QTreeWidgetItem::sortChildren(int column, Qt::SortOrder order, bool climb)
-{
- QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0);
- if (!model)
- return;
- if (model->isChanging())
- return;
- int oldSortColumn = view->d_func()->explicitSortColumn;
- view->d_func()->explicitSortColumn = column;
- emit model->layoutAboutToBeChanged();
- d->sortChildren(column, order, climb);
- emit model->layoutChanged();
- view->d_func()->explicitSortColumn = oldSortColumn;
-}
-
-/*!
- \internal
-
- Calculates the checked state of the item based on the checked state
- of its children. E.g. if all children checked => this item is also
- checked; if some children checked => this item is partially checked;
- if no children checked => this item is unchecked.
-*/
-QVariant QTreeWidgetItem::childrenCheckState(int column) const
-{
- if (column < 0)
- return QVariant();
- bool checkedChildren = false;
- bool uncheckedChildren = false;
- for (int i = 0; i < children.count(); ++i) {
- QVariant value = children.at(i)->data(column, Qt::CheckStateRole);
- if (!value.isValid())
- return QVariant();
-
- switch (static_cast<Qt::CheckState>(value.toInt()))
- {
- case Qt::Unchecked:
- uncheckedChildren = true;
- break;
- case Qt::Checked:
- checkedChildren = true;
- break;
- case Qt::PartiallyChecked:
- default:
- return Qt::PartiallyChecked;
- }
- }
-
- if (uncheckedChildren && checkedChildren)
- return Qt::PartiallyChecked;
- if (uncheckedChildren)
- return Qt::Unchecked;
- else if (checkedChildren)
- return Qt::Checked;
- else
- return QVariant(); // value was not defined
-}
-
-/*!
- \since 4.5
-
- Causes the model associated with this item to emit a
- \l{QAbstractItemModel::dataChanged()}{dataChanged}() signal for this
- item.
-
- You normally only need to call this function if you have subclassed
- QTreeWidgetItem and reimplemented data() and/or setData().
-
- \sa setData()
-*/
-void QTreeWidgetItem::emitDataChanged()
-{
- itemChanged();
-}
-
-/*!
- \internal
-*/
-void QTreeWidgetItem::itemChanged()
-{
- if (QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0))
- model->itemChanged(this);
-}
-
-/*!
- \internal
-*/
-void QTreeWidgetItem::executePendingSort() const
-{
- if (QTreeModel *model = (view ? qobject_cast<QTreeModel*>(view->model()) : 0))
- model->executePendingSort();
-}
-
-
-#ifndef QT_NO_DATASTREAM
-/*!
- \relates QTreeWidgetItem
-
- Writes the tree widget item \a item to stream \a out.
-
- This operator uses QTreeWidgetItem::write().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator<<(QDataStream &out, const QTreeWidgetItem &item)
-{
- item.write(out);
- return out;
-}
-
-/*!
- \relates QTreeWidgetItem
-
- Reads a tree widget item from stream \a in into \a item.
-
- This operator uses QTreeWidgetItem::read().
-
- \sa {Serializing Qt Data Types}
-*/
-QDataStream &operator>>(QDataStream &in, QTreeWidgetItem &item)
-{
- item.read(in);
- return in;
-}
-#endif // QT_NO_DATASTREAM
-
-
-void QTreeWidgetPrivate::_q_emitItemPressed(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemPressed(item(index), index.column());
-}
-
-void QTreeWidgetPrivate::_q_emitItemClicked(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemClicked(item(index), index.column());
-}
-
-void QTreeWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemDoubleClicked(item(index), index.column());
-}
-
-void QTreeWidgetPrivate::_q_emitItemActivated(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemActivated(item(index), index.column());
-}
-
-void QTreeWidgetPrivate::_q_emitItemEntered(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemEntered(item(index), index.column());
-}
-
-void QTreeWidgetPrivate::_q_emitItemChanged(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- QTreeWidgetItem *indexItem = item(index);
- if (indexItem)
- emit q->itemChanged(indexItem, index.column());
-}
-
-void QTreeWidgetPrivate::_q_emitItemExpanded(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemExpanded(item(index));
-}
-
-void QTreeWidgetPrivate::_q_emitItemCollapsed(const QModelIndex &index)
-{
- Q_Q(QTreeWidget);
- emit q->itemCollapsed(item(index));
-}
-
-void QTreeWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex &current,
- const QModelIndex &previous)
-{
- Q_Q(QTreeWidget);
- QTreeWidgetItem *currentItem = item(current);
- QTreeWidgetItem *previousItem = item(previous);
- emit q->currentItemChanged(currentItem, previousItem);
-}
-
-void QTreeWidgetPrivate::_q_sort()
-{
- if (sortingEnabled) {
- int column = header->sortIndicatorSection();
- Qt::SortOrder order = header->sortIndicatorOrder();
- treeModel()->sort(column, order);
- }
-}
-
-void QTreeWidgetPrivate::_q_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
-{
- Q_Q(QTreeWidget);
- QModelIndexList indices = selected.indexes();
- int i;
- QTreeModel *m = treeModel();
- for (i = 0; i < indices.count(); ++i) {
- QTreeWidgetItem *item = m->item(indices.at(i));
- item->d->selected = true;
- }
-
- indices = deselected.indexes();
- for (i = 0; i < indices.count(); ++i) {
- QTreeWidgetItem *item = m->item(indices.at(i));
- item->d->selected = false;
- }
-
- emit q->itemSelectionChanged();
-}
-
-void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft,
- const QModelIndex &bottomRight)
-{
- if (sortingEnabled && topLeft.isValid() && bottomRight.isValid()
- && !treeModel()->sortPendingTimer.isActive()) {
- int column = header->sortIndicatorSection();
- if (column >= topLeft.column() && column <= bottomRight.column()) {
- Qt::SortOrder order = header->sortIndicatorOrder();
- treeModel()->ensureSorted(column, order, topLeft.row(),
- bottomRight.row(), topLeft.parent());
- }
- }
-}
-
-/*!
- \class QTreeWidget
-
- \brief The QTreeWidget class provides a tree view that uses a predefined
- tree model.
-
- \ingroup model-view
-
-
- The QTreeWidget class is a convenience class that provides a standard
- tree widget with a classic item-based interface similar to that used by
- the QListView class in Qt 3.
- This class is based on Qt's Model/View architecture and uses a default
- model to hold items, each of which is a QTreeWidgetItem.
-
- Developers who do not need the flexibility of the Model/View framework
- can use this class to create simple hierarchical lists very easily. A more
- flexible approach involves combining a QTreeView with a standard item model.
- This allows the storage of data to be separated from its representation.
-
- In its simplest form, a tree widget can be constructed in the following way:
-
- \snippet doc/src/snippets/code/src_gui_itemviews_qtreewidget.cpp 0
-
- Before items can be added to the tree widget, the number of columns must
- be set with setColumnCount(). This allows each item to have one or more
- labels or other decorations. The number of columns in use can be found
- with the columnCount() function.
-
- The tree can have a header that contains a section for each column in
- the widget. It is easiest to set up the labels for each section by
- supplying a list of strings with setHeaderLabels(), but a custom header
- can be constructed with a QTreeWidgetItem and inserted into the tree
- with the setHeaderItem() function.
-
- The items in the tree can be sorted by column according to a predefined
- sort order. If sorting is enabled, the user can sort the items by clicking
- on a column header. Sorting can be enabled or disabled by calling
- \l{QTreeView::setSortingEnabled()}{setSortingEnabled()}. The
- \l{QTreeView::isSortingEnabled()}{isSortingEnabled()} function indicates
- whether sorting is enabled.
-
- \table 100%
- \row \o \inlineimage windowsxp-treeview.png Screenshot of a Windows XP style tree widget
- \o \inlineimage macintosh-treeview.png Screenshot of a Macintosh style tree widget
- \o \inlineimage plastique-treeview.png Screenshot of a Plastique style tree widget
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} tree widget.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} tree widget.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} tree widget.
- \endtable
-
- \sa QTreeWidgetItem, QTreeWidgetItemIterator, QTreeView,
- {Model/View Programming}, {Settings Editor Example}
-*/
-
-/*!
- \property QTreeWidget::columnCount
- \brief the number of columns displayed in the tree widget
-
- By default, this property has a value of 1.
-*/
-
-/*!
- \fn void QTreeWidget::itemActivated(QTreeWidgetItem *item, int column)
-
- This signal is emitted when the user activates an item by single-
- or double-clicking (depending on the platform, i.e. on the
- QStyle::SH_ItemView_ActivateItemOnSingleClick style hint) or
- pressing a special key (e.g., \key Enter).
-
- The specified \a item is the item that was clicked, or 0 if no
- item was clicked. The \a column is the item's column that was
- clicked, or -1 if no item was clicked.
-*/
-
-/*!
- \fn void QTreeWidget::itemPressed(QTreeWidgetItem *item, int column)
-
- This signal is emitted when the user presses a mouse button inside
- the widget.
-
- The specified \a item is the item that was clicked, or 0 if no
- item was clicked. The \a column is the item's column that was
- clicked, or -1 if no item was clicked.
-*/
-
-/*!
- \fn void QTreeWidget::itemClicked(QTreeWidgetItem *item, int column)
-
- This signal is emitted when the user clicks inside the widget.
-
- The specified \a item is the item that was clicked. The \a column is the
- item's column that was clicked. If no item was clicked, no signal will be
- emitted.
-*/
-
-/*!
- \fn void QTreeWidget::itemDoubleClicked(QTreeWidgetItem *item, int column)
-
- This signal is emitted when the user double clicks inside the
- widget.
-
- The specified \a item is the item that was clicked, or 0 if no
- item was clicked. The \a column is the item's column that was
- clicked. If no item was double clicked, no signal will be emitted.
-*/
-
-/*!
- \fn void QTreeWidget::itemExpanded(QTreeWidgetItem *item)
-
- This signal is emitted when the specified \a item is expanded so that
- all of its children are displayed.
-
- \note This signal will not be emitted if an item changes its state when
- expandAll() is invoked.
-
- \sa QTreeWidgetItem::isExpanded(), itemCollapsed(), expandItem()
-*/
-
-/*!
- \fn void QTreeWidget::itemCollapsed(QTreeWidgetItem *item)
-
- This signal is emitted when the specified \a item is collapsed so that
- none of its children are displayed.
-
- \note This signal will not be emitted if an item changes its state when
- collapseAll() is invoked.
-
- \sa QTreeWidgetItem::isExpanded(), itemExpanded(), collapseItem()
-*/
-
-/*!
- \fn void QTreeWidget::currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
-
- This signal is emitted when the current item changes. The current
- item is specified by \a current, and this replaces the \a previous
- current item.
-
- \sa setCurrentItem()
-*/
-
-/*!
- \fn void QTreeWidget::itemSelectionChanged()
-
- This signal is emitted when the selection changes in the tree widget.
- The current selection can be found with selectedItems().
-*/
-
-/*!
- \fn void QTreeWidget::itemEntered(QTreeWidgetItem *item, int column)
-
- This signal is emitted when the mouse cursor enters an \a item over the
- specified \a column.
- QTreeWidget mouse tracking needs to be enabled for this feature to work.
-*/
-
-/*!
- \fn void QTreeWidget::itemChanged(QTreeWidgetItem *item, int column)
-
- This signal is emitted when the contents of the \a column in the specified
- \a item changes.
-*/
-
-/*!
- \since 4.3
-
- \fn void QTreeWidget::removeItemWidget(QTreeWidgetItem *item, int column)
-
- Removes the widget set in the given \a item in the given \a column.
-*/
-
-/*!
- Constructs a tree widget with the given \a parent.
-*/
-QTreeWidget::QTreeWidget(QWidget *parent)
- : QTreeView(*new QTreeWidgetPrivate(), parent)
-{
- QTreeView::setModel(new QTreeModel(1, this));
- connect(this, SIGNAL(pressed(QModelIndex)),
- SLOT(_q_emitItemPressed(QModelIndex)));
- connect(this, SIGNAL(clicked(QModelIndex)),
- SLOT(_q_emitItemClicked(QModelIndex)));
- connect(this, SIGNAL(doubleClicked(QModelIndex)),
- SLOT(_q_emitItemDoubleClicked(QModelIndex)));
- connect(this, SIGNAL(activated(QModelIndex)),
- SLOT(_q_emitItemActivated(QModelIndex)));
- connect(this, SIGNAL(entered(QModelIndex)),
- SLOT(_q_emitItemEntered(QModelIndex)));
- connect(this, SIGNAL(expanded(QModelIndex)),
- SLOT(_q_emitItemExpanded(QModelIndex)));
- connect(this, SIGNAL(collapsed(QModelIndex)),
- SLOT(_q_emitItemCollapsed(QModelIndex)));
- connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex)));
- connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitItemChanged(QModelIndex)));
- connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- connect(model(), SIGNAL(columnsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_sort()));
- connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(_q_selectionChanged(QItemSelection,QItemSelection)));
- header()->setClickable(false);
-}
-
-/*!
- Destroys the tree widget and all its items.
-*/
-
-QTreeWidget::~QTreeWidget()
-{
-}
-
-/*
- Retuns the number of header columns in the view.
-
- \sa sortColumn(), currentColumn(), topLevelItemCount()
-*/
-
-int QTreeWidget::columnCount() const
-{
- Q_D(const QTreeWidget);
- return d->model->columnCount();
-}
-
-/*
- Sets the number of header \a columns in the tree widget.
-*/
-
-void QTreeWidget::setColumnCount(int columns)
-{
- Q_D(QTreeWidget);
- if (columns < 0)
- return;
- d->treeModel()->setColumnCount(columns);
-}
-
-/*!
- \since 4.2
-
- Returns the tree widget's invisible root item.
-
- The invisible root item provides access to the tree widget's top-level items
- through the QTreeWidgetItem API, making it possible to write functions that
- can treat top-level items and their children in a uniform way; for example,
- recursive functions.
-*/
-
-QTreeWidgetItem *QTreeWidget::invisibleRootItem() const
-{
- Q_D(const QTreeWidget);
- return d->treeModel()->rootItem;
-}
-
-/*!
- Returns the top level item at the given \a index, or 0 if the item does
- not exist.
-
- \sa topLevelItemCount(), insertTopLevelItem()
-*/
-
-QTreeWidgetItem *QTreeWidget::topLevelItem(int index) const
-{
- Q_D(const QTreeWidget);
- return d->treeModel()->rootItem->child(index);
-}
-
-/*!
- \property QTreeWidget::topLevelItemCount
- \brief the number of top-level items
-
- By default, this property has a value of 0.
-
- \sa columnCount(), currentItem()
-*/
-
-int QTreeWidget::topLevelItemCount() const
-{
- Q_D(const QTreeWidget);
- return d->treeModel()->rootItem->childCount();
-}
-
-/*!
- Inserts the \a item at \a index in the top level in the view.
-
- If the item has already been inserted somewhere else it wont be inserted.
-
- \sa addTopLevelItem(), columnCount()
-*/
-
-void QTreeWidget::insertTopLevelItem(int index, QTreeWidgetItem *item)
-{
- Q_D(QTreeWidget);
- d->treeModel()->rootItem->insertChild(index, item);
-}
-
-/*!
- \since 4.1
-
- Appends the \a item as a top-level item in the widget.
-
- \sa insertTopLevelItem()
-*/
-void QTreeWidget::addTopLevelItem(QTreeWidgetItem *item)
-{
- insertTopLevelItem(topLevelItemCount(), item);
-}
-
-/*!
- Removes the top-level item at the given \a index in the tree and
- returns it, otherwise returns 0;
-
- \sa insertTopLevelItem(), topLevelItem(), topLevelItemCount()
-*/
-
-QTreeWidgetItem *QTreeWidget::takeTopLevelItem(int index)
-{
- Q_D(QTreeWidget);
- return d->treeModel()->rootItem->takeChild(index);
-}
-
-/*!
- \internal
-*/
-int QTreeWidget::indexOfTopLevelItem(QTreeWidgetItem *item)
-{
- Q_D(QTreeWidget);
- d->treeModel()->executePendingSort();
- return d->treeModel()->rootItem->children.indexOf(item);
-}
-
-/*!
- Returns the index of the given top-level \a item, or -1 if the item
- cannot be found.
-
- \sa sortItems(), topLevelItemCount()
- */
-int QTreeWidget::indexOfTopLevelItem(QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- d->treeModel()->executePendingSort();
- return d->treeModel()->rootItem->children.indexOf(item);
-}
-
-/*!
- \since 4.1
-
- Inserts the list of \a items at \a index in the top level in the view.
-
- Items that have already been inserted somewhere else wont be inserted.
-
- \sa addTopLevelItems()
-*/
-void QTreeWidget::insertTopLevelItems(int index, const QList<QTreeWidgetItem*> &items)
-{
- Q_D(QTreeWidget);
- d->treeModel()->rootItem->insertChildren(index, items);
-}
-
-/*!
- Appends the list of \a items as a top-level items in the widget.
-
- \sa insertTopLevelItems()
-*/
-void QTreeWidget::addTopLevelItems(const QList<QTreeWidgetItem*> &items)
-{
- insertTopLevelItems(topLevelItemCount(), items);
-}
-
-/*!
- Returns the item used for the tree widget's header.
-
- \sa setHeaderItem()
-*/
-
-QTreeWidgetItem *QTreeWidget::headerItem() const
-{
- Q_D(const QTreeWidget);
- return d->treeModel()->headerItem;
-}
-
-/*!
- Sets the header \a item for the tree widget. The label for each column in
- the header is supplied by the corresponding label in the item.
-
- The tree widget takes ownership of the item.
-
- \sa headerItem(), setHeaderLabels()
-*/
-
-void QTreeWidget::setHeaderItem(QTreeWidgetItem *item)
-{
- Q_D(QTreeWidget);
- if (!item)
- return;
- item->view = this;
-
- int oldCount = columnCount();
- if (oldCount < item->columnCount())
- d->treeModel()->beginInsertColumns(QModelIndex(), oldCount, item->columnCount());
- else
- d->treeModel()->beginRemoveColumns(QModelIndex(), item->columnCount(), oldCount);
- delete d->treeModel()->headerItem;
- d->treeModel()->headerItem = item;
- if (oldCount < item->columnCount())
- d->treeModel()->endInsertColumns();
- else
- d->treeModel()->endRemoveColumns();
- d->treeModel()->headerDataChanged(Qt::Horizontal, 0, oldCount);
-}
-
-
-/*!
- Adds a column in the header for each item in the \a labels list, and sets
- the label for each column.
-
- Note that setHeaderLabels() won't remove existing columns.
-
- \sa setHeaderItem(), setHeaderLabel()
-*/
-void QTreeWidget::setHeaderLabels(const QStringList &labels)
-{
- Q_D(QTreeWidget);
- if (columnCount() < labels.count())
- setColumnCount(labels.count());
- QTreeWidgetItem *item = d->treeModel()->headerItem;
- for (int i = 0; i < labels.count(); ++i)
- item->setText(i, labels.at(i));
-}
-
-/*!
- \fn void QTreeWidget::setHeaderLabel(const QString &label)
- \since 4.2
-
- Same as setHeaderLabels(QStringList(\a label)).
-*/
-
-/*!
- Returns the current item in the tree widget.
-
- \sa setCurrentItem(), currentItemChanged()
-*/
-QTreeWidgetItem *QTreeWidget::currentItem() const
-{
- Q_D(const QTreeWidget);
- return d->item(currentIndex());
-}
-
-/*!
- \since 4.1
- Returns the current column in the tree widget.
-
- \sa setCurrentItem(), columnCount()
-*/
-int QTreeWidget::currentColumn() const
-{
- return currentIndex().column();
-}
-
-/*!
- Sets the current \a item in the tree widget.
-
- Unless the selection mode is \l{QAbstractItemView::}{NoSelection},
- the item is also be selected.
-
- \sa currentItem(), currentItemChanged()
-*/
-void QTreeWidget::setCurrentItem(QTreeWidgetItem *item)
-{
- setCurrentItem(item, 0);
-}
-
-/*!
- \since 4.1
- Sets the current \a item in the tree widget and the current column to \a column.
-
- \sa currentItem()
-*/
-void QTreeWidget::setCurrentItem(QTreeWidgetItem *item, int column)
-{
- Q_D(QTreeWidget);
- setCurrentIndex(d->index(item, column));
-}
-
-/*!
- \since 4.4
- Sets the current \a item in the tree widget and the current column to \a column,
- using the given \a command.
-
- \sa currentItem()
-*/
-void QTreeWidget::setCurrentItem(QTreeWidgetItem *item, int column,
- QItemSelectionModel::SelectionFlags command)
-{
- Q_D(QTreeWidget);
- d->selectionModel->setCurrentIndex(d->index(item, column), command);
-}
-
-
-/*!
- Returns a pointer to the item at the coordinates \a p. The coordinates
- are relative to the tree widget's \l{QAbstractScrollArea::}{viewport()}.
-
- \sa visualItemRect()
-*/
-QTreeWidgetItem *QTreeWidget::itemAt(const QPoint &p) const
-{
- Q_D(const QTreeWidget);
- return d->item(indexAt(p));
-}
-
-/*!
- \fn QTreeWidgetItem *QTreeWidget::itemAt(int x, int y) const
- \overload
-
- Returns a pointer to the item at the coordinates (\a x, \a y). The coordinates
- are relative to the tree widget's \l{QAbstractScrollArea::}{viewport()}.
-*/
-
-/*!
- Returns the rectangle on the viewport occupied by the item at \a item.
-
- \sa itemAt()
-*/
-QRect QTreeWidget::visualItemRect(const QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- //the visual rect for an item is across all columns. So we need to determine
- //what is the first and last column and get their visual index rects
- QModelIndex base = d->index(item);
- const int firstVisiblesection = header()->logicalIndexAt(- header()->offset());
- const int lastVisibleSection = header()->logicalIndexAt(header()->length() - header()->offset() - 1);
- QModelIndex first = base.sibling(base.row(), header()->logicalIndex(firstVisiblesection));
- QModelIndex last = base.sibling(base.row(), header()->logicalIndex(lastVisibleSection));
- return visualRect(first) | visualRect(last);
-}
-
-/*!
- \since 4.1
-
- Returns the column used to sort the contents of the widget.
-
- \sa sortItems()
-*/
-int QTreeWidget::sortColumn() const
-{
- Q_D(const QTreeWidget);
- return (d->explicitSortColumn != -1
- ? d->explicitSortColumn
- : header()->sortIndicatorSection());
-}
-
-/*!
- Sorts the items in the widget in the specified \a order by the values in
- the given \a column.
-
- \sa sortColumn()
-*/
-
-void QTreeWidget::sortItems(int column, Qt::SortOrder order)
-{
- Q_D(QTreeWidget);
- header()->setSortIndicator(column, order);
- d->model->sort(column, order);
-}
-
-/*!
- \internal
-
- ### Qt 5: remove
-*/
-void QTreeWidget::setSortingEnabled(bool enable)
-{
- QTreeView::setSortingEnabled(enable);
-}
-
-/*!
- \internal
-
- ### Qt 5: remove
-*/
-bool QTreeWidget::isSortingEnabled() const
-{
- return QTreeView::isSortingEnabled();
-}
-
-/*!
- Starts editing the \a item in the given \a column if it is editable.
-*/
-
-void QTreeWidget::editItem(QTreeWidgetItem *item, int column)
-{
- Q_D(QTreeWidget);
- edit(d->index(item, column));
-}
-
-/*!
- Opens a persistent editor for the \a item in the given \a column.
-
- \sa closePersistentEditor()
-*/
-
-void QTreeWidget::openPersistentEditor(QTreeWidgetItem *item, int column)
-{
- Q_D(QTreeWidget);
- QAbstractItemView::openPersistentEditor(d->index(item, column));
-}
-
-/*!
- Closes the persistent editor for the \a item in the given \a column.
-
- This function has no effect if no persistent editor is open for this
- combination of item and column.
-
- \sa openPersistentEditor()
-*/
-
-void QTreeWidget::closePersistentEditor(QTreeWidgetItem *item, int column)
-{
- Q_D(QTreeWidget);
- QAbstractItemView::closePersistentEditor(d->index(item, column));
-}
-
-/*!
- \since 4.1
-
- Returns the widget displayed in the cell specified by \a item and the given \a column.
-
- \note The tree takes ownership of the widget.
-
-*/
-QWidget *QTreeWidget::itemWidget(QTreeWidgetItem *item, int column) const
-{
- Q_D(const QTreeWidget);
- return QAbstractItemView::indexWidget(d->index(item, column));
-}
-
-/*!
- \since 4.1
-
- Sets the given \a widget to be displayed in the cell specified by the given
- \a item and \a column.
-
- The given \a widget's \l {QWidget::}{autoFillBackground} property must be
- set to true, otherwise the widget's background will be transparent, showing
- both the model data and the tree widget item.
-
- This function should only be used to display static content in the place of
- a tree widget item. If you want to display custom dynamic content or
- implement a custom editor widget, use QTreeView and subclass QItemDelegate
- instead.
-
- This function cannot be called before the item hierarchy has been set up,
- i.e., the QTreeWidgetItem that will hold \a widget must have been added to
- the view before \a widget is set.
-
- \note The tree takes ownership of the widget.
-
- \sa {Delegate Classes}
-*/
-void QTreeWidget::setItemWidget(QTreeWidgetItem *item, int column, QWidget *widget)
-{
- Q_D(QTreeWidget);
- QAbstractItemView::setIndexWidget(d->index(item, column), widget);
-}
-
-/*!
- Returns true if the \a item is selected; otherwise returns false.
-
- \sa itemSelectionChanged()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isSelected()} instead.
-*/
-bool QTreeWidget::isItemSelected(const QTreeWidgetItem *item) const
-{
- if (!item)
- return false;
- return item->d->selected;
-}
-
-/*!
- If \a select is true, the given \a item is selected; otherwise it is
- deselected.
-
- \sa itemSelectionChanged()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setSelected()} instead.
-*/
-void QTreeWidget::setItemSelected(const QTreeWidgetItem *item, bool select)
-{
- Q_D(QTreeWidget);
-
- if (!item)
- return;
-
- selectionModel()->select(d->index(item), (select ? QItemSelectionModel::Select
- : QItemSelectionModel::Deselect)
- |QItemSelectionModel::Rows);
- item->d->selected = select;
-}
-
-/*!
- Returns a list of all selected non-hidden items.
-
- \sa itemSelectionChanged()
-*/
-QList<QTreeWidgetItem*> QTreeWidget::selectedItems() const
-{
- Q_D(const QTreeWidget);
- QModelIndexList indexes = selectionModel()->selectedIndexes();
- QList<QTreeWidgetItem*> items;
- items.reserve(indexes.count());
- QSet<QTreeWidgetItem *> seen;
- seen.reserve(indexes.count());
- for (int i = 0; i < indexes.count(); ++i) {
- QTreeWidgetItem *item = d->item(indexes.at(i));
- if (isItemHidden(item) || seen.contains(item))
- continue;
- seen.insert(item);
- items.append(item);
- }
- return items;
-}
-
-/*!
- Returns a list of items that match the given \a text, using the given \a flags, in the given \a column.
-*/
-QList<QTreeWidgetItem*> QTreeWidget::findItems(const QString &text, Qt::MatchFlags flags, int column) const
-{
- Q_D(const QTreeWidget);
- QModelIndexList indexes = d->model->match(model()->index(0, column, QModelIndex()),
- Qt::DisplayRole, text, -1, flags);
- QList<QTreeWidgetItem*> items;
- for (int i = 0; i < indexes.size(); ++i)
- items.append(d->item(indexes.at(i)));
- return items;
-}
-
-/*!
- Returns true if the \a item is explicitly hidden, otherwise returns false.
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isHidden()} instead.
-*/
-bool QTreeWidget::isItemHidden(const QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- if (item == d->treeModel()->headerItem)
- return header()->isHidden();
- if (d->hiddenIndexes.isEmpty())
- return false;
- QTreeModel::SkipSorting skipSorting(d->treeModel());
- return d->isRowHidden(d->index(item));
-}
-
-/*!
- Hides the given \a item if \a hide is true; otherwise shows the item.
-
- \sa itemChanged()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setHidden()} instead.
-*/
-void QTreeWidget::setItemHidden(const QTreeWidgetItem *item, bool hide)
-{
- Q_D(QTreeWidget);
- if (item == d->treeModel()->headerItem) {
- header()->setHidden(hide);
- } else {
- const QModelIndex index = d->index(item);
- setRowHidden(index.row(), index.parent(), hide);
- }
-}
-
-/*!
- Returns true if the given \a item is open; otherwise returns false.
-
- \sa itemExpanded()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::isExpanded()} instead.
-*/
-bool QTreeWidget::isItemExpanded(const QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- QTreeModel::SkipSorting skipSorting(d->treeModel());
- return isExpanded(d->index(item));
-}
-
-/*!
- Sets the item referred to by \a item to either closed or opened,
- depending on the value of \a expand.
-
- \sa expandItem(), collapseItem(), itemExpanded()
-
- \obsolete
-
- This function is deprecated. Use \l{QTreeWidgetItem::setExpanded()} instead.
-*/
-void QTreeWidget::setItemExpanded(const QTreeWidgetItem *item, bool expand)
-{
- Q_D(QTreeWidget);
- QTreeModel::SkipSorting skipSorting(d->treeModel());
- setExpanded(d->index(item), expand);
-}
-
-/*!
- \since 4.3
-
- Returns true if the given \a item is set to show only one section over all columns;
- otherwise returns false.
-
- \sa setFirstItemColumnSpanned()
-*/
-bool QTreeWidget::isFirstItemColumnSpanned(const QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- if (item == d->treeModel()->headerItem)
- return false; // We can't set the header items to spanning
- const QModelIndex index = d->index(item);
- return isFirstColumnSpanned(index.row(), index.parent());
-}
-
-/*!
- \since 4.3
-
- Sets the given \a item to only show one section for all columns if \a span is true;
- otherwise the item will show one section per column.
-
- \sa isFirstItemColumnSpanned()
-*/
-void QTreeWidget::setFirstItemColumnSpanned(const QTreeWidgetItem *item, bool span)
-{
- Q_D(QTreeWidget);
- if (item == d->treeModel()->headerItem)
- return; // We can't set header items to spanning
- const QModelIndex index = d->index(item);
- setFirstColumnSpanned(index.row(), index.parent(), span);
-}
-
-/*!
- \since 4.3
-
- Returns the item above the given \a item.
-*/
-QTreeWidgetItem *QTreeWidget::itemAbove(const QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- if (item == d->treeModel()->headerItem)
- return 0;
- const QModelIndex index = d->index(item);
- const QModelIndex above = indexAbove(index);
- return d->item(above);
-}
-
-/*!
- \since 4.3
-
- Returns the item visually below the given \a item.
-*/
-QTreeWidgetItem *QTreeWidget::itemBelow(const QTreeWidgetItem *item) const
-{
- Q_D(const QTreeWidget);
- if (item == d->treeModel()->headerItem)
- return 0;
- const QModelIndex index = d->index(item);
- const QModelIndex below = indexBelow(index);
- return d->item(below);
-}
-
-/*!
- \reimp
- */
-void QTreeWidget::setSelectionModel(QItemSelectionModel *selectionModel)
-{
- Q_D(QTreeWidget);
- QTreeView::setSelectionModel(selectionModel);
- QItemSelection newSelection = selectionModel->selection();
- if (!newSelection.isEmpty())
- d->_q_selectionChanged(newSelection, QItemSelection());
-}
-
-/*!
- Ensures that the \a item is visible, scrolling the view if necessary using
- the specified \a hint.
-
- \sa currentItem(), itemAt(), topLevelItem()
-*/
-void QTreeWidget::scrollToItem(const QTreeWidgetItem *item, QAbstractItemView::ScrollHint hint)
-{
- Q_D(QTreeWidget);
- QTreeView::scrollTo(d->index(item), hint);
-}
-
-/*!
- Expands the \a item. This causes the tree containing the item's children
- to be expanded.
-
- \sa collapseItem(), currentItem(), itemAt(), topLevelItem(), itemExpanded()
-*/
-void QTreeWidget::expandItem(const QTreeWidgetItem *item)
-{
- Q_D(QTreeWidget);
- QTreeModel::SkipSorting skipSorting(d->treeModel());
- expand(d->index(item));
-}
-
-/*!
- Closes the \a item. This causes the tree containing the item's children
- to be collapsed.
-
- \sa expandItem(), currentItem(), itemAt(), topLevelItem()
-*/
-void QTreeWidget::collapseItem(const QTreeWidgetItem *item)
-{
- Q_D(QTreeWidget);
- QTreeModel::SkipSorting skipSorting(d->treeModel());
- collapse(d->index(item));
-}
-
-/*!
- Clears the tree widget by removing all of its items and selections.
-
- \bold{Note:} Since each item is removed from the tree widget before being
- deleted, the return value of QTreeWidgetItem::treeWidget() will be invalid
- when called from an item's destructor.
-
- \sa takeTopLevelItem(), topLevelItemCount(), columnCount()
-*/
-void QTreeWidget::clear()
-{
- Q_D(QTreeWidget);
- selectionModel()->clear();
- d->treeModel()->clear();
-}
-
-/*!
- Returns a list of MIME types that can be used to describe a list of
- treewidget items.
-
- \sa mimeData()
-*/
-QStringList QTreeWidget::mimeTypes() const
-{
- return model()->QAbstractItemModel::mimeTypes();
-}
-
-/*!
- Returns an object that contains a serialized description of the specified
- \a items. The format used to describe the items is obtained from the
- mimeTypes() function.
-
- If the list of items is empty, 0 is returned rather than a serialized
- empty list.
-*/
-QMimeData *QTreeWidget::mimeData(const QList<QTreeWidgetItem*> items) const
-{
- Q_D(const QTreeWidget);
- if (d->treeModel()->cachedIndexes.isEmpty()) {
- QList<QModelIndex> indexes;
- for (int i = 0; i < items.count(); ++i) {
- QTreeWidgetItem *item = items.at(i);
- for (int c = 0; c < item->values.count(); ++c) {
- indexes << indexFromItem(item, c);
- }
- }
- return d->model->QAbstractItemModel::mimeData(indexes);
- }
- return d->treeModel()->internalMimeData();
-}
-
-/*!
- Handles the \a data supplied by a drag and drop operation that ended with
- the given \a action in the \a index in the given \a parent item.
-
- The default implementation returns true if the drop was
- successfully handled by decoding the mime data and inserting it
- into the model; otherwise it returns false.
-
- \sa supportedDropActions()
-*/
-bool QTreeWidget::dropMimeData(QTreeWidgetItem *parent, int index,
- const QMimeData *data, Qt::DropAction action)
-{
- QModelIndex idx;
- if (parent) idx = indexFromItem(parent);
- return model()->QAbstractItemModel::dropMimeData(data, action , index, 0, idx);
-}
-
-/*!
- Returns the drop actions supported by this view.
-
- \sa Qt::DropActions
-*/
-Qt::DropActions QTreeWidget::supportedDropActions() const
-{
- return model()->QAbstractItemModel::supportedDropActions() | Qt::MoveAction;
-}
-
-/*!
- \obsolete
- Returns an empty list
-
- \sa mimeData()
-*/
-QList<QTreeWidgetItem*> QTreeWidget::items(const QMimeData *data) const
-{
- Q_UNUSED(data);
- return QList<QTreeWidgetItem*>();
-}
-
-/*!
- Returns the QModelIndex assocated with the given \a item in the given \a column.
-
- \sa itemFromIndex(), topLevelItem()
-*/
-QModelIndex QTreeWidget::indexFromItem(QTreeWidgetItem *item, int column) const
-{
- Q_D(const QTreeWidget);
- return d->index(item, column);
-}
-
-/*!
- Returns a pointer to the QTreeWidgetItem assocated with the given \a index.
-
- \sa indexFromItem()
-*/
-QTreeWidgetItem *QTreeWidget::itemFromIndex(const QModelIndex &index) const
-{
- Q_D(const QTreeWidget);
- return d->item(index);
-}
-
-#ifndef QT_NO_DRAGANDDROP
-/*! \reimp */
-void QTreeWidget::dropEvent(QDropEvent *event) {
- Q_D(QTreeWidget);
- if (event->source() == this && (event->dropAction() == Qt::MoveAction ||
- dragDropMode() == QAbstractItemView::InternalMove)) {
- QModelIndex topIndex;
- int col = -1;
- int row = -1;
- if (d->dropOn(event, &row, &col, &topIndex)) {
- QList<QModelIndex> idxs = selectedIndexes();
- QList<QPersistentModelIndex> indexes;
- for (int i = 0; i < idxs.count(); i++)
- indexes.append(idxs.at(i));
-
- if (indexes.contains(topIndex))
- return;
-
- // When removing items the drop location could shift
- QPersistentModelIndex dropRow = model()->index(row, col, topIndex);
-
- // Remove the items
- QList<QTreeWidgetItem *> taken;
- for (int i = indexes.count() - 1; i >= 0; --i) {
- QTreeWidgetItem *parent = itemFromIndex(indexes.at(i));
- if (!parent || !parent->parent()) {
- taken.append(takeTopLevelItem(indexes.at(i).row()));
- } else {
- taken.append(parent->parent()->takeChild(indexes.at(i).row()));
- }
- }
-
- // insert them back in at their new positions
- for (int i = 0; i < indexes.count(); ++i) {
- // Either at a specific point or appended
- if (row == -1) {
- if (topIndex.isValid()) {
- QTreeWidgetItem *parent = itemFromIndex(topIndex);
- parent->insertChild(parent->childCount(), taken.takeFirst());
- } else {
- insertTopLevelItem(topLevelItemCount(), taken.takeFirst());
- }
- } else {
- int r = dropRow.row() >= 0 ? dropRow.row() : row;
- if (topIndex.isValid()) {
- QTreeWidgetItem *parent = itemFromIndex(topIndex);
- parent->insertChild(qMin(r, parent->childCount()), taken.takeFirst());
- } else {
- insertTopLevelItem(qMin(r, topLevelItemCount()), taken.takeFirst());
- }
- }
- }
-
- event->accept();
- // Don't want QAbstractItemView to delete it because it was "moved" we already did it
- event->setDropAction(Qt::CopyAction);
- }
- }
-
- QTreeView::dropEvent(event);
-}
-#endif
-
-/*!
- \reimp
-*/
-
-void QTreeWidget::setModel(QAbstractItemModel * /*model*/)
-{
- Q_ASSERT(!"QTreeWidget::setModel() - Changing the model of the QTreeWidget is not allowed.");
-}
-
-/*!
- \reimp
-*/
-bool QTreeWidget::event(QEvent *e)
-{
- Q_D(QTreeWidget);
- if (e->type() == QEvent::Polish)
- d->treeModel()->executePendingSort();
- return QTreeView::event(e);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtreewidget.cpp"
-
-#endif // QT_NO_TREEWIDGET
diff --git a/src/gui/itemviews/qtreewidget.h b/src/gui/itemviews/qtreewidget.h
deleted file mode 100644
index 59532dd594..0000000000
--- a/src/gui/itemviews/qtreewidget.h
+++ /dev/null
@@ -1,432 +0,0 @@
-/****************************************************************************
-**
-** 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 QTREEWIDGET_H
-#define QTREEWIDGET_H
-
-#include <QtGui/qtreeview.h>
-#include <QtGui/qtreewidgetitemiterator.h>
-#include <QtCore/qvariant.h>
-#include <QtCore/qvector.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TREEWIDGET
-
-class QTreeWidget;
-class QTreeModel;
-class QWidgetItemData;
-class QTreeWidgetItemPrivate;
-
-class Q_GUI_EXPORT QTreeWidgetItem
-{
- friend class QTreeModel;
- friend class QTreeWidget;
- friend class QTreeWidgetPrivate;
- friend class QTreeWidgetItemIterator;
- friend class QTreeWidgetItemPrivate;
-public:
- enum ItemType { Type = 0, UserType = 1000 };
- explicit QTreeWidgetItem(int type = Type);
- QTreeWidgetItem(const QStringList &strings, int type = Type);
- explicit QTreeWidgetItem(QTreeWidget *view, int type = Type);
- QTreeWidgetItem(QTreeWidget *view, const QStringList &strings, int type = Type);
- QTreeWidgetItem(QTreeWidget *view, QTreeWidgetItem *after, int type = Type);
- explicit QTreeWidgetItem(QTreeWidgetItem *parent, int type = Type);
- QTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings, int type = Type);
- QTreeWidgetItem(QTreeWidgetItem *parent, QTreeWidgetItem *after, int type = Type);
- QTreeWidgetItem(const QTreeWidgetItem &other);
- virtual ~QTreeWidgetItem();
-
- virtual QTreeWidgetItem *clone() const;
-
- inline QTreeWidget *treeWidget() const { return view; }
-
- inline void setSelected(bool select);
- inline bool isSelected() const;
-
- inline void setHidden(bool hide);
- inline bool isHidden() const;
-
- inline void setExpanded(bool expand);
- inline bool isExpanded() const;
-
- inline void setFirstColumnSpanned(bool span);
- inline bool isFirstColumnSpanned() const;
-
- inline void setDisabled(bool disabled);
- inline bool isDisabled() const;
-
- enum ChildIndicatorPolicy { ShowIndicator, DontShowIndicator, DontShowIndicatorWhenChildless };
- void setChildIndicatorPolicy(QTreeWidgetItem::ChildIndicatorPolicy policy);
- QTreeWidgetItem::ChildIndicatorPolicy childIndicatorPolicy() const;
-
- Qt::ItemFlags flags() const;
- void setFlags(Qt::ItemFlags flags);
-
- inline QString text(int column) const
- { return data(column, Qt::DisplayRole).toString(); }
- inline void setText(int column, const QString &text);
-
- inline QIcon icon(int column) const
- { return qvariant_cast<QIcon>(data(column, Qt::DecorationRole)); }
- inline void setIcon(int column, const QIcon &icon);
-
- inline QString statusTip(int column) const
- { return data(column, Qt::StatusTipRole).toString(); }
- inline void setStatusTip(int column, const QString &statusTip);
-
-#ifndef QT_NO_TOOLTIP
- inline QString toolTip(int column) const
- { return data(column, Qt::ToolTipRole).toString(); }
- inline void setToolTip(int column, const QString &toolTip);
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- inline QString whatsThis(int column) const
- { return data(column, Qt::WhatsThisRole).toString(); }
- inline void setWhatsThis(int column, const QString &whatsThis);
-#endif
-
- inline QFont font(int column) const
- { return qvariant_cast<QFont>(data(column, Qt::FontRole)); }
- inline void setFont(int column, const QFont &font);
-
- inline int textAlignment(int column) const
- { return data(column, Qt::TextAlignmentRole).toInt(); }
- inline void setTextAlignment(int column, int alignment)
- { setData(column, Qt::TextAlignmentRole, alignment); }
-
- inline QColor backgroundColor(int column) const
- { return qvariant_cast<QColor>(data(column, Qt::BackgroundColorRole)); }
- inline void setBackgroundColor(int column, const QColor &color)
- { setData(column, Qt::BackgroundColorRole, color); }
-
- inline QBrush background(int column) const
- { return qvariant_cast<QBrush>(data(column, Qt::BackgroundRole)); }
- inline void setBackground(int column, const QBrush &brush)
- { setData(column, Qt::BackgroundRole, brush); }
-
- inline QColor textColor(int column) const
- { return qvariant_cast<QColor>(data(column, Qt::TextColorRole)); }
- inline void setTextColor(int column, const QColor &color)
- { setData(column, Qt::TextColorRole, color); }
-
- inline QBrush foreground(int column) const
- { return qvariant_cast<QBrush>(data(column, Qt::ForegroundRole)); }
- inline void setForeground(int column, const QBrush &brush)
- { setData(column, Qt::ForegroundRole, brush); }
-
- inline Qt::CheckState checkState(int column) const
- { return static_cast<Qt::CheckState>(data(column, Qt::CheckStateRole).toInt()); }
- inline void setCheckState(int column, Qt::CheckState state)
- { setData(column, Qt::CheckStateRole, state); }
-
- inline QSize sizeHint(int column) const
- { return qvariant_cast<QSize>(data(column, Qt::SizeHintRole)); }
- inline void setSizeHint(int column, const QSize &size)
- { setData(column, Qt::SizeHintRole, size); }
-
- virtual QVariant data(int column, int role) const;
- virtual void setData(int column, int role, const QVariant &value);
-
- virtual bool operator<(const QTreeWidgetItem &other) const;
-
-#ifndef QT_NO_DATASTREAM
- virtual void read(QDataStream &in);
- virtual void write(QDataStream &out) const;
-#endif
- QTreeWidgetItem &operator=(const QTreeWidgetItem &other);
-
- inline QTreeWidgetItem *parent() const { return par; }
- inline QTreeWidgetItem *child(int index) const {
- if (index < 0 || index >= children.size())
- return 0;
- executePendingSort();
- return children.at(index);
- }
- inline int childCount() const { return children.count(); }
- inline int columnCount() const { return values.count(); }
- inline int indexOfChild(QTreeWidgetItem *child) const;
-
- void addChild(QTreeWidgetItem *child);
- void insertChild(int index, QTreeWidgetItem *child);
- void removeChild(QTreeWidgetItem *child);
- QTreeWidgetItem *takeChild(int index);
-
- void addChildren(const QList<QTreeWidgetItem*> &children);
- void insertChildren(int index, const QList<QTreeWidgetItem*> &children);
- QList<QTreeWidgetItem*> takeChildren();
-
- inline int type() const { return rtti; }
- inline void sortChildren(int column, Qt::SortOrder order)
- { sortChildren(column, order, false); }
-
-protected:
- void emitDataChanged();
-
-private:
- void sortChildren(int column, Qt::SortOrder order, bool climb);
- QVariant childrenCheckState(int column) const;
- void itemChanged();
- void executePendingSort() const;
-
- int rtti;
- // One item has a vector of column entries. Each column has a vector of (role, value) pairs.
- QVector< QVector<QWidgetItemData> > values;
- QTreeWidget *view;
- QTreeWidgetItemPrivate *d;
- QTreeWidgetItem *par;
- QList<QTreeWidgetItem*> children;
- Qt::ItemFlags itemFlags;
-};
-
-inline void QTreeWidgetItem::setText(int column, const QString &atext)
-{ setData(column, Qt::DisplayRole, atext); }
-
-inline void QTreeWidgetItem::setIcon(int column, const QIcon &aicon)
-{ setData(column, Qt::DecorationRole, aicon); }
-
-#ifndef QT_NO_STATUSTIP
-inline void QTreeWidgetItem::setStatusTip(int column, const QString &astatusTip)
-{ setData(column, Qt::StatusTipRole, astatusTip); }
-#endif
-
-#ifndef QT_NO_TOOLTIP
-inline void QTreeWidgetItem::setToolTip(int column, const QString &atoolTip)
-{ setData(column, Qt::ToolTipRole, atoolTip); }
-#endif
-
-#ifndef QT_NO_WHATSTHIS
-inline void QTreeWidgetItem::setWhatsThis(int column, const QString &awhatsThis)
-{ setData(column, Qt::WhatsThisRole, awhatsThis); }
-#endif
-
-inline void QTreeWidgetItem::setFont(int column, const QFont &afont)
-{ setData(column, Qt::FontRole, afont); }
-
-inline int QTreeWidgetItem::indexOfChild(QTreeWidgetItem *achild) const
-{ executePendingSort(); return children.indexOf(achild); }
-
-#ifndef QT_NO_DATASTREAM
-Q_GUI_EXPORT QDataStream &operator<<(QDataStream &out, const QTreeWidgetItem &item);
-Q_GUI_EXPORT QDataStream &operator>>(QDataStream &in, QTreeWidgetItem &item);
-#endif
-
-class QTreeWidgetPrivate;
-
-class Q_GUI_EXPORT QTreeWidget : public QTreeView
-{
- Q_OBJECT
- Q_PROPERTY(int columnCount READ columnCount WRITE setColumnCount)
- Q_PROPERTY(int topLevelItemCount READ topLevelItemCount)
-
- friend class QTreeModel;
- friend class QTreeWidgetItem;
-public:
- explicit QTreeWidget(QWidget *parent = 0);
- ~QTreeWidget();
-
- int columnCount() const;
- void setColumnCount(int columns);
-
- QTreeWidgetItem *invisibleRootItem() const;
- QTreeWidgetItem *topLevelItem(int index) const;
- int topLevelItemCount() const;
- void insertTopLevelItem(int index, QTreeWidgetItem *item);
- void addTopLevelItem(QTreeWidgetItem *item);
- QTreeWidgetItem *takeTopLevelItem(int index);
- int indexOfTopLevelItem(QTreeWidgetItem *item); // ### Qt 5: remove me
- int indexOfTopLevelItem(QTreeWidgetItem *item) const;
-
- void insertTopLevelItems(int index, const QList<QTreeWidgetItem*> &items);
- void addTopLevelItems(const QList<QTreeWidgetItem*> &items);
-
- QTreeWidgetItem *headerItem() const;
- void setHeaderItem(QTreeWidgetItem *item);
- void setHeaderLabels(const QStringList &labels);
- inline void setHeaderLabel(const QString &label);
-
- QTreeWidgetItem *currentItem() const;
- int currentColumn() const;
- void setCurrentItem(QTreeWidgetItem *item);
- void setCurrentItem(QTreeWidgetItem *item, int column);
- void setCurrentItem(QTreeWidgetItem *item, int column, QItemSelectionModel::SelectionFlags command);
-
- QTreeWidgetItem *itemAt(const QPoint &p) const;
- inline QTreeWidgetItem *itemAt(int x, int y) const;
- QRect visualItemRect(const QTreeWidgetItem *item) const;
-
- int sortColumn() const;
- void sortItems(int column, Qt::SortOrder order);
- void setSortingEnabled(bool enable);
- bool isSortingEnabled() const;
-
- void editItem(QTreeWidgetItem *item, int column = 0);
- void openPersistentEditor(QTreeWidgetItem *item, int column = 0);
- void closePersistentEditor(QTreeWidgetItem *item, int column = 0);
-
- QWidget *itemWidget(QTreeWidgetItem *item, int column) const;
- void setItemWidget(QTreeWidgetItem *item, int column, QWidget *widget);
- inline void removeItemWidget(QTreeWidgetItem *item, int column);
-
- bool isItemSelected(const QTreeWidgetItem *item) const;
- void setItemSelected(const QTreeWidgetItem *item, bool select);
- QList<QTreeWidgetItem*> selectedItems() const;
- QList<QTreeWidgetItem*> findItems(const QString &text, Qt::MatchFlags flags,
- int column = 0) const;
-
- bool isItemHidden(const QTreeWidgetItem *item) const;
- void setItemHidden(const QTreeWidgetItem *item, bool hide);
-
- bool isItemExpanded(const QTreeWidgetItem *item) const;
- void setItemExpanded(const QTreeWidgetItem *item, bool expand);
-
- bool isFirstItemColumnSpanned(const QTreeWidgetItem *item) const;
- void setFirstItemColumnSpanned(const QTreeWidgetItem *item, bool span);
-
- QTreeWidgetItem *itemAbove(const QTreeWidgetItem *item) const;
- QTreeWidgetItem *itemBelow(const QTreeWidgetItem *item) const;
-
- void setSelectionModel(QItemSelectionModel *selectionModel);
-
-public Q_SLOTS:
- void scrollToItem(const QTreeWidgetItem *item,
- QAbstractItemView::ScrollHint hint = EnsureVisible);
- void expandItem(const QTreeWidgetItem *item);
- void collapseItem(const QTreeWidgetItem *item);
- void clear();
-
-Q_SIGNALS:
- void itemPressed(QTreeWidgetItem *item, int column);
- void itemClicked(QTreeWidgetItem *item, int column);
- void itemDoubleClicked(QTreeWidgetItem *item, int column);
- void itemActivated(QTreeWidgetItem *item, int column);
- void itemEntered(QTreeWidgetItem *item, int column);
- void itemChanged(QTreeWidgetItem *item, int column);
- void itemExpanded(QTreeWidgetItem *item);
- void itemCollapsed(QTreeWidgetItem *item);
- void currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous);
- void itemSelectionChanged();
-
-protected:
- bool event(QEvent *e);
- virtual QStringList mimeTypes() const;
- virtual QMimeData *mimeData(const QList<QTreeWidgetItem*> items) const;
- virtual bool dropMimeData(QTreeWidgetItem *parent, int index,
- const QMimeData *data, Qt::DropAction action);
- virtual Qt::DropActions supportedDropActions() const;
- QList<QTreeWidgetItem*> items(const QMimeData *data) const;
-
- QModelIndex indexFromItem(QTreeWidgetItem *item, int column = 0) const;
- QTreeWidgetItem *itemFromIndex(const QModelIndex &index) const;
- void dropEvent(QDropEvent *event);
-
-private:
- void setModel(QAbstractItemModel *model);
-
- Q_DECLARE_PRIVATE(QTreeWidget)
- Q_DISABLE_COPY(QTreeWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemExpanded(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitItemCollapsed(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &current))
- Q_PRIVATE_SLOT(d_func(), void _q_sort())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight))
- Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected))
-};
-
-inline void QTreeWidget::removeItemWidget(QTreeWidgetItem *item, int column)
-{ setItemWidget(item, column, 0); }
-
-inline QTreeWidgetItem *QTreeWidget::itemAt(int ax, int ay) const
-{ return itemAt(QPoint(ax, ay)); }
-
-inline void QTreeWidget::setHeaderLabel(const QString &alabel)
-{ setHeaderLabels(QStringList(alabel)); }
-
-inline void QTreeWidgetItem::setSelected(bool aselect)
-{ if (view) view->setItemSelected(this, aselect); }
-
-inline bool QTreeWidgetItem::isSelected() const
-{ return (view ? view->isItemSelected(this) : false); }
-
-inline void QTreeWidgetItem::setHidden(bool ahide)
-{ if (view) view->setItemHidden(this, ahide); }
-
-inline bool QTreeWidgetItem::isHidden() const
-{ return (view ? view->isItemHidden(this) : false); }
-
-inline void QTreeWidgetItem::setExpanded(bool aexpand)
-{ if (view) view->setItemExpanded(this, aexpand); }
-
-inline bool QTreeWidgetItem::isExpanded() const
-{ return (view ? view->isItemExpanded(this) : false); }
-
-inline void QTreeWidgetItem::setFirstColumnSpanned(bool aspan)
-{ if (view) view->setFirstItemColumnSpanned(this, aspan); }
-
-inline bool QTreeWidgetItem::isFirstColumnSpanned() const
-{ return (view ? view->isFirstItemColumnSpanned(this) : false); }
-
-inline void QTreeWidgetItem::setDisabled(bool disabled)
-{ setFlags(disabled ? (flags() & ~Qt::ItemIsEnabled) : flags() | Qt::ItemIsEnabled); }
-
-inline bool QTreeWidgetItem::isDisabled() const
-{ return !(flags() & Qt::ItemIsEnabled); }
-
-#endif // QT_NO_TREEWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTREEWIDGET_H
diff --git a/src/gui/itemviews/qtreewidget_p.h b/src/gui/itemviews/qtreewidget_p.h
deleted file mode 100644
index 7395e6a5db..0000000000
--- a/src/gui/itemviews/qtreewidget_p.h
+++ /dev/null
@@ -1,248 +0,0 @@
-/****************************************************************************
-**
-** 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 QTREEWIDGET_P_H
-#define QTREEWIDGET_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. This header file may change
-// from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qabstractitemmodel.h>
-#include <private/qabstractitemmodel_p.h>
-#include <QtCore/qpair.h>
-#include <QtCore/qbasictimer.h>
-#include <QtGui/qtreewidget.h>
-#include <private/qtreeview_p.h>
-#include <QtGui/qheaderview.h>
-
-#ifndef QT_NO_TREEWIDGET
-
-QT_BEGIN_NAMESPACE
-
-class QTreeWidgetItem;
-class QTreeWidgetItemIterator;
-class QTreeModelPrivate;
-
-class QTreeModel : public QAbstractItemModel
-{
- Q_OBJECT
- friend class QTreeWidget;
- friend class QTreeWidgetPrivate;
- friend class QTreeWidgetItem;
- friend class QTreeWidgetItemPrivate;
- friend class QTreeWidgetItemIterator;
- friend class QTreeWidgetItemIteratorPrivate;
-
-public:
- explicit QTreeModel(int columns = 0, QTreeWidget *parent = 0);
- ~QTreeModel();
-
- inline QTreeWidget *view() const
- { return qobject_cast<QTreeWidget*>(QObject::parent()); }
-
- void clear();
- void setColumnCount(int columns);
-
- QTreeWidgetItem *item(const QModelIndex &index) const;
- void itemChanged(QTreeWidgetItem *item);
-
- QModelIndex index(const QTreeWidgetItem *item, int column) const;
- QModelIndex index(int row, int column, const QModelIndex &parent) const;
- QModelIndex parent(const QModelIndex &child) const;
- int rowCount(const QModelIndex &parent) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
- bool hasChildren(const QModelIndex &parent) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role);
-
- QMap<int, QVariant> itemData(const QModelIndex &index) const;
-
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value,
- int role);
-
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- void sort(int column, Qt::SortOrder order);
- void ensureSorted(int column, Qt::SortOrder order,
- int start, int end, const QModelIndex &parent);
- static bool itemLessThan(const QPair<QTreeWidgetItem*,int> &left,
- const QPair<QTreeWidgetItem*,int> &right);
- static bool itemGreaterThan(const QPair<QTreeWidgetItem*,int> &left,
- const QPair<QTreeWidgetItem*,int> &right);
- static QList<QTreeWidgetItem*>::iterator sortedInsertionIterator(
- const QList<QTreeWidgetItem*>::iterator &begin,
- const QList<QTreeWidgetItem*>::iterator &end,
- Qt::SortOrder order, QTreeWidgetItem *item);
-
- bool insertRows(int row, int count, const QModelIndex &);
- bool insertColumns(int column, int count, const QModelIndex &);
-
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
-
- // dnd
- QStringList mimeTypes() const;
- QMimeData *mimeData(const QModelIndexList &indexes) const;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action,
- int row, int column, const QModelIndex &parent);
- Qt::DropActions supportedDropActions() const;
-
- QMimeData *internalMimeData() const;
-
- inline QModelIndex createIndexFromItem(int row, int col, QTreeWidgetItem *item) const
- { return createIndex(row, col, item); }
-
-protected:
- QTreeModel(QTreeModelPrivate &, QTreeWidget *parent = 0);
- void emitDataChanged(QTreeWidgetItem *item, int column);
- void beginInsertItems(QTreeWidgetItem *parent, int row, int count);
- void endInsertItems();
- void beginRemoveItems(QTreeWidgetItem *parent, int row, int count);
- void endRemoveItems();
- void sortItems(QList<QTreeWidgetItem*> *items, int column, Qt::SortOrder order);
- void timerEvent(QTimerEvent *);
-
-private:
- QTreeWidgetItem *rootItem;
- QTreeWidgetItem *headerItem;
-
- mutable QModelIndexList cachedIndexes;
- QList<QTreeWidgetItemIterator*> iterators;
-
- mutable QBasicTimer sortPendingTimer;
- mutable bool skipPendingSort; //while doing internal operation we don't care about sorting
- bool inline executePendingSort() const;
-
- bool isChanging() const;
-
-private:
- Q_DECLARE_PRIVATE(QTreeModel)
-public:
- struct SkipSorting
- {
- const QTreeModel * const model;
- const bool previous;
- SkipSorting(const QTreeModel *m) : model(m), previous(model->skipPendingSort)
- { model->skipPendingSort = true; }
- ~SkipSorting() { model->skipPendingSort = previous; }
- };
- friend struct SkipSorting;
-};
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "private/qabstractitemmodel_p.h"
-QT_END_INCLUDE_NAMESPACE
-
-class QTreeModelPrivate : public QAbstractItemModelPrivate
-{
- Q_DECLARE_PUBLIC(QTreeModel)
-};
-
-class QTreeWidgetItemPrivate
-{
-public:
- QTreeWidgetItemPrivate(QTreeWidgetItem *item)
- : q(item), disabled(false), selected(false), rowGuess(-1), policy(QTreeWidgetItem::DontShowIndicatorWhenChildless) {}
- void propagateDisabled(QTreeWidgetItem *item);
- void sortChildren(int column, Qt::SortOrder order, bool climb);
- QTreeWidgetItem *q;
- QVariantList display;
- uint disabled : 1;
- uint selected : 1;
- int rowGuess;
- QTreeWidgetItem::ChildIndicatorPolicy policy;
-};
-
-
-inline bool QTreeModel::executePendingSort() const
-{
- if (!skipPendingSort && sortPendingTimer.isActive() && !isChanging()) {
- sortPendingTimer.stop();
- int column = view()->header()->sortIndicatorSection();
- Qt::SortOrder order = view()->header()->sortIndicatorOrder();
- QTreeModel *that = const_cast<QTreeModel*>(this);
- that->sort(column, order);
- return true;
- }
- return false;
-}
-
-class QTreeWidgetPrivate : public QTreeViewPrivate
-{
- friend class QTreeModel;
- Q_DECLARE_PUBLIC(QTreeWidget)
-public:
- QTreeWidgetPrivate() : QTreeViewPrivate(), explicitSortColumn(-1) {}
- inline QTreeModel *treeModel() const { return qobject_cast<QTreeModel*>(model); }
- inline QModelIndex index(const QTreeWidgetItem *item, int column = 0) const
- { return treeModel()->index(item, column); }
- inline QTreeWidgetItem *item(const QModelIndex &index) const
- { return treeModel()->item(index); }
- void _q_emitItemPressed(const QModelIndex &index);
- void _q_emitItemClicked(const QModelIndex &index);
- void _q_emitItemDoubleClicked(const QModelIndex &index);
- void _q_emitItemActivated(const QModelIndex &index);
- void _q_emitItemEntered(const QModelIndex &index);
- void _q_emitItemChanged(const QModelIndex &index);
- void _q_emitItemExpanded(const QModelIndex &index);
- void _q_emitItemCollapsed(const QModelIndex &index);
- void _q_emitCurrentItemChanged(const QModelIndex &previous, const QModelIndex &index);
- void _q_sort();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void _q_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
-
- // used by QTreeWidgetItem::sortChildren to make sure the column argument is used
- int explicitSortColumn;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TREEWIDGET
-
-#endif // QTREEWIDGET_P_H
diff --git a/src/gui/itemviews/qtreewidgetitemiterator.cpp b/src/gui/itemviews/qtreewidgetitemiterator.cpp
deleted file mode 100644
index fa0115ed27..0000000000
--- a/src/gui/itemviews/qtreewidgetitemiterator.cpp
+++ /dev/null
@@ -1,458 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qtreewidgetitemiterator_p.h>
-#include "qtreewidget.h"
-#include "qtreewidget_p.h"
-#include "qwidgetitemdata_p.h"
-
-#ifndef QT_NO_TREEWIDGET
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QTreeWidgetItemIterator
- \ingroup model-view
- \brief The QTreeWidgetItemIterator class provides a way to iterate over the
- items in a QTreeWidget instance.
-
- The iterator will walk the items in a pre-order traversal order, thus visiting the
- parent node \e before it continues to the child nodes.
-
- For example, the following code examples each item in a tree, checking the
- text in the first column against a user-specified search string:
-
- \snippet doc/src/snippets/qtreewidgetitemiterator-using/mainwindow.cpp 0
-
- It is also possible to filter out certain types of node by passing certain
- \l{IteratorFlag}{flags} to the constructor of QTreeWidgetItemIterator.
-
- \sa QTreeWidget, {Model/View Programming}, QTreeWidgetItem
-*/
-
-/*!
- Constructs an iterator for the same QTreeWidget as \a it. The
- current iterator item is set to point on the current item of \a it.
-*/
-
-QTreeWidgetItemIterator::QTreeWidgetItemIterator(const QTreeWidgetItemIterator &it)
- : d_ptr(new QTreeWidgetItemIteratorPrivate(*(it.d_ptr))),
- current(it.current), flags(it.flags)
-{
- Q_D(QTreeWidgetItemIterator);
- Q_ASSERT(d->m_model);
- d->m_model->iterators.append(this);
-}
-
-/*!
- Constructs an iterator for the given \a widget that uses the specified \a flags
- to determine which items are found during iteration.
- The iterator is set to point to the first top-level item contained in the widget,
- or the next matching item if the top-level item doesn't match the flags.
-
- \sa QTreeWidgetItemIterator::IteratorFlag
-*/
-
-QTreeWidgetItemIterator::QTreeWidgetItemIterator(QTreeWidget *widget, IteratorFlags flags)
-: current(0), flags(flags)
-{
- Q_ASSERT(widget);
- QTreeModel *model = qobject_cast<QTreeModel*>(widget->model());
- Q_ASSERT(model);
- d_ptr.reset(new QTreeWidgetItemIteratorPrivate(this, model));
- model->iterators.append(this);
- if (!model->rootItem->children.isEmpty()) current = model->rootItem->children.first();
- if (current && !matchesFlags(current))
- ++(*this);
-}
-
-/*!
- Constructs an iterator for the given \a item that uses the specified \a flags
- to determine which items are found during iteration.
- The iterator is set to point to \a item, or the next matching item if \a item
- doesn't match the flags.
-
- \sa QTreeWidgetItemIterator::IteratorFlag
-*/
-
-QTreeWidgetItemIterator::QTreeWidgetItemIterator(QTreeWidgetItem *item, IteratorFlags flags)
- : d_ptr(new QTreeWidgetItemIteratorPrivate(
- this, qobject_cast<QTreeModel*>(item->view->model()))),
- current(item), flags(flags)
-{
- Q_D(QTreeWidgetItemIterator);
- Q_ASSERT(item);
- QTreeModel *model = qobject_cast<QTreeModel*>(item->view->model());
- Q_ASSERT(model);
- model->iterators.append(this);
-
- // Initialize m_currentIndex and m_parentIndex as it would be if we had traversed from
- // the beginning.
- QTreeWidgetItem *parent = item;
- parent = parent->parent();
- QList<QTreeWidgetItem *> children = parent ? parent->children : d->m_model->rootItem->children;
- d->m_currentIndex = children.indexOf(item);
-
- while (parent) {
- QTreeWidgetItem *itm = parent;
- parent = parent->parent();
- QList<QTreeWidgetItem *> children = parent ? parent->children : d->m_model->rootItem->children;
- int index = children.indexOf(itm);
- d->m_parentIndex.prepend(index);
- }
-
- if (current && !matchesFlags(current))
- ++(*this);
-}
-
-/*!
- Destroys the iterator.
-*/
-
-QTreeWidgetItemIterator::~QTreeWidgetItemIterator()
-{
- d_func()->m_model->iterators.removeAll(this);
-}
-
-/*!
- Assignment. Makes a copy of \a it and returns a reference to its
- iterator.
-*/
-
-QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator=(const QTreeWidgetItemIterator &it)
-{
- Q_D(QTreeWidgetItemIterator);
- if (d_func()->m_model != it.d_func()->m_model) {
- d_func()->m_model->iterators.removeAll(this);
- it.d_func()->m_model->iterators.append(this);
- }
- current = it.current;
- flags = it.flags;
- d->operator=(*it.d_func());
- return *this;
-}
-
-/*!
- The prefix ++ operator (++it) advances the iterator to the next matching item
- and returns a reference to the resulting iterator.
- Sets the current pointer to 0 if the current item is the last matching item.
-*/
-
-QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator++()
-{
- if (current)
- do {
- current = d_func()->next(current);
- } while (current && !matchesFlags(current));
- return *this;
-}
-
-/*!
- The prefix -- operator (--it) advances the iterator to the previous matching item
- and returns a reference to the resulting iterator.
- Sets the current pointer to 0 if the current item is the first matching item.
-*/
-
-QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator--()
-{
- if (current)
- do {
- current = d_func()->previous(current);
- } while (current && !matchesFlags(current));
- return *this;
-}
-
-/*!
- \internal
-*/
-bool QTreeWidgetItemIterator::matchesFlags(const QTreeWidgetItem *item) const
-{
- if (!item)
- return false;
-
- if (flags == All)
- return true;
-
- {
- Qt::ItemFlags itemFlags = item->flags();
- if ((flags & Selectable) && !(itemFlags & Qt::ItemIsSelectable))
- return false;
- if ((flags & NotSelectable) && (itemFlags & Qt::ItemIsSelectable))
- return false;
- if ((flags & DragEnabled) && !(itemFlags & Qt::ItemIsDragEnabled))
- return false;
- if ((flags & DragDisabled) && (itemFlags & Qt::ItemIsDragEnabled))
- return false;
- if ((flags & DropEnabled) && !(itemFlags & Qt::ItemIsDropEnabled))
- return false;
- if ((flags & DropDisabled) && (itemFlags & Qt::ItemIsDropEnabled))
- return false;
- if ((flags & Enabled) && !(itemFlags & Qt::ItemIsEnabled))
- return false;
- if ((flags & Disabled) && (itemFlags & Qt::ItemIsEnabled))
- return false;
- if ((flags & Editable) && !(itemFlags & Qt::ItemIsEditable))
- return false;
- if ((flags & NotEditable) && (itemFlags & Qt::ItemIsEditable))
- return false;
- }
-
- if (flags & (Checked|NotChecked)) {
- // ### We only test the check state for column 0
- Qt::CheckState check = item->checkState(0);
- // PartiallyChecked matches as Checked.
- if ((flags & Checked) && (check == Qt::Unchecked))
- return false;
- if ((flags & NotChecked) && (check != Qt::Unchecked))
- return false;
- }
-
- if ((flags & HasChildren) && !item->childCount())
- return false;
- if ((flags & NoChildren) && item->childCount())
- return false;
-
- if ((flags & Hidden) && !item->isHidden())
- return false;
- if ((flags & NotHidden) && item->isHidden())
- return false;
-
- if ((flags & Selected) && !item->isSelected())
- return false;
- if ((flags & Unselected) && item->isSelected())
- return false;
-
- return true;
-}
-
-/*
- * Implementation of QTreeWidgetItemIteratorPrivate
- */
-QTreeWidgetItem* QTreeWidgetItemIteratorPrivate::nextSibling(const QTreeWidgetItem* item) const
-{
- Q_ASSERT(item);
- QTreeWidgetItem *next = 0;
- if (QTreeWidgetItem *par = item->parent()) {
- int i = par->indexOfChild(const_cast<QTreeWidgetItem*>(item));
- next = par->child(i + 1);
- } else {
- QTreeWidget *tw = item->treeWidget();
- int i = tw->indexOfTopLevelItem(const_cast<QTreeWidgetItem*>(item));
- next = tw->topLevelItem(i + 1);
- }
- return next;
-}
-
-QTreeWidgetItem *QTreeWidgetItemIteratorPrivate::next(const QTreeWidgetItem *current)
-{
- if (!current) return 0;
-
- QTreeWidgetItem *next = 0;
- if (current->childCount()) {
- // walk the child
- m_parentIndex.push(m_currentIndex);
- m_currentIndex = 0;
- next = current->child(0);
- } else {
- // walk the sibling
- QTreeWidgetItem *parent = current->parent();
- next = parent ? parent->child(m_currentIndex + 1)
- : m_model->rootItem->child(m_currentIndex + 1);
- while (!next && parent) {
- // if we had no sibling walk up the parent and try the sibling of that
- parent = parent->parent();
- m_currentIndex = m_parentIndex.pop();
- next = parent ? parent->child(m_currentIndex + 1)
- : m_model->rootItem->child(m_currentIndex + 1);
- }
- if (next) ++(m_currentIndex);
- }
- return next;
-}
-
-QTreeWidgetItem *QTreeWidgetItemIteratorPrivate::previous(const QTreeWidgetItem *current)
-{
- if (!current) return 0;
-
- QTreeWidgetItem *prev = 0;
- // walk the previous sibling
- QTreeWidgetItem *parent = current->parent();
- prev = parent ? parent->child(m_currentIndex - 1)
- : m_model->rootItem->child(m_currentIndex - 1);
- if (prev) {
- // Yes, we had a previous sibling but we need go down to the last leafnode.
- --m_currentIndex;
- while (prev && prev->childCount()) {
- m_parentIndex.push(m_currentIndex);
- m_currentIndex = prev->childCount() - 1;
- prev = prev->child(m_currentIndex);
- }
- } else if (parent) {
- m_currentIndex = m_parentIndex.pop();
- prev = parent;
- }
- return prev;
-}
-
-void QTreeWidgetItemIteratorPrivate::ensureValidIterator(const QTreeWidgetItem *itemToBeRemoved)
-{
- Q_Q(QTreeWidgetItemIterator);
- Q_ASSERT(itemToBeRemoved);
-
- if (!q->current) return;
- QTreeWidgetItem *nextItem = q->current;
-
- // Do not walk to the ancestor to find the other item if they have the same parent.
- if (nextItem->parent() != itemToBeRemoved->parent()) {
- while (nextItem->parent() && nextItem != itemToBeRemoved) {
- nextItem = nextItem->parent();
- }
- }
- // If the item to be removed is an ancestor of the current iterator item,
- // we need to adjust the iterator.
- if (nextItem == itemToBeRemoved) {
- QTreeWidgetItem *parent = nextItem;
- nextItem = 0;
- while (parent && !nextItem) {
- nextItem = nextSibling(parent);
- parent = parent->parent();
- }
- if (nextItem) {
- // Ooooh... Set the iterator to the next valid item
- *q = QTreeWidgetItemIterator(nextItem, q->flags);
- if (!(q->matchesFlags(nextItem))) ++(*q);
- } else {
- // set it to null.
- q->current = 0;
- m_parentIndex.clear();
- return;
- }
- }
- if (nextItem->parent() == itemToBeRemoved->parent()) {
- // They have the same parent, i.e. we have to adjust the m_currentIndex member of the iterator
- // if the deleted item is to the left of the nextItem.
-
- QTreeWidgetItem *par = itemToBeRemoved->parent(); // We know they both have the same parent.
- QTreeWidget *tw = itemToBeRemoved->treeWidget(); // ..and widget
- int indexOfItemToBeRemoved = par ? par->indexOfChild(const_cast<QTreeWidgetItem *>(itemToBeRemoved))
- : tw->indexOfTopLevelItem(const_cast<QTreeWidgetItem *>(itemToBeRemoved));
- int indexOfNextItem = par ? par->indexOfChild(nextItem) : tw->indexOfTopLevelItem(nextItem);
-
- if (indexOfItemToBeRemoved <= indexOfNextItem) {
- // A sibling to the left of us was deleted, adjust the m_currentIndex member of the iterator.
- // Note that the m_currentIndex will be wrong until the item is actually removed!
- m_currentIndex--;
- }
- }
-}
-
-/*!
- \fn const QTreeWidgetItemIterator QTreeWidgetItemIterator::operator++(int)
-
- The postfix ++ operator (it++) advances the iterator to the next matching item
- and returns an iterator to the previously current item.
-*/
-
-/*!
- \fn QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator+=(int n)
-
- Makes the iterator go forward by \a n matching items. (If n is negative, the
- iterator goes backward.)
-
- If the current item is beyond the last item, the current item pointer is
- set to 0. Returns the resulting iterator.
-*/
-
-/*!
- \fn const QTreeWidgetItemIterator QTreeWidgetItemIterator::operator--(int)
-
- The postfix -- operator (it--) makes the preceding matching item current and returns an iterator to the previously current item.
-*/
-
-/*!
- \fn QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator-=(int n)
-
- Makes the iterator go backward by \a n matching items. (If n is negative, the
- iterator goes forward.)
-
- If the current item is ahead of the last item, the current item pointer is
- set to 0. Returns the resulting iterator.
-*/
-
-/*!
- \fn QTreeWidgetItem *QTreeWidgetItemIterator::operator*() const
-
- Dereference operator. Returns a pointer to the current item.
-*/
-
-
-/*!
- \enum QTreeWidgetItemIterator::IteratorFlag
-
- These flags can be passed to a QTreeWidgetItemIterator constructor
- (OR-ed together if more than one is used), so that the iterator
- will only iterate over items that match the given flags.
-
- \value All
- \value Hidden
- \value NotHidden
- \value Selected
- \value Unselected
- \value Selectable
- \value NotSelectable
- \value DragEnabled
- \value DragDisabled
- \value DropEnabled
- \value DropDisabled
- \value HasChildren
- \value NoChildren
- \value Checked
- \value NotChecked
- \value Enabled
- \value Disabled
- \value Editable
- \value NotEditable
- \value UserFlag
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TREEWIDGET
diff --git a/src/gui/itemviews/qtreewidgetitemiterator.h b/src/gui/itemviews/qtreewidgetitemiterator.h
deleted file mode 100644
index 680bac4f51..0000000000
--- a/src/gui/itemviews/qtreewidgetitemiterator.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/****************************************************************************
-**
-** 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 QTREEWIDGETITEMITERATOR_H
-#define QTREEWIDGETITEMITERATOR_H
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qscopedpointer.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TREEWIDGET
-
-class QTreeWidget;
-class QTreeWidgetItem;
-class QTreeModel;
-
-class QTreeWidgetItemIteratorPrivate;
-class Q_GUI_EXPORT QTreeWidgetItemIterator
-{
- friend class QTreeModel;
-
-public:
- enum IteratorFlag {
- All = 0x00000000,
- Hidden = 0x00000001,
- NotHidden = 0x00000002,
- Selected = 0x00000004,
- Unselected = 0x00000008,
- Selectable = 0x00000010,
- NotSelectable = 0x00000020,
- DragEnabled = 0x00000040,
- DragDisabled = 0x00000080,
- DropEnabled = 0x00000100,
- DropDisabled = 0x00000200,
- HasChildren = 0x00000400,
- NoChildren = 0x00000800,
- Checked = 0x00001000,
- NotChecked = 0x00002000,
- Enabled = 0x00004000,
- Disabled = 0x00008000,
- Editable = 0x00010000,
- NotEditable = 0x00020000,
- UserFlag = 0x01000000 // The first flag that can be used by the user.
- };
- Q_DECLARE_FLAGS(IteratorFlags, IteratorFlag)
-
- QTreeWidgetItemIterator(const QTreeWidgetItemIterator &it);
- explicit QTreeWidgetItemIterator(QTreeWidget *widget, IteratorFlags flags = All);
- explicit QTreeWidgetItemIterator(QTreeWidgetItem *item, IteratorFlags flags = All);
- ~QTreeWidgetItemIterator();
-
- QTreeWidgetItemIterator &operator=(const QTreeWidgetItemIterator &it);
-
- QTreeWidgetItemIterator &operator++();
- inline const QTreeWidgetItemIterator operator++(int);
- inline QTreeWidgetItemIterator &operator+=(int n);
-
- QTreeWidgetItemIterator &operator--();
- inline const QTreeWidgetItemIterator operator--(int);
- inline QTreeWidgetItemIterator &operator-=(int n);
-
- inline QTreeWidgetItem *operator*() const;
-
-private:
- bool matchesFlags(const QTreeWidgetItem *item) const;
- QScopedPointer<QTreeWidgetItemIteratorPrivate> d_ptr;
- QTreeWidgetItem *current;
- IteratorFlags flags;
- Q_DECLARE_PRIVATE(QTreeWidgetItemIterator)
-};
-
-inline const QTreeWidgetItemIterator QTreeWidgetItemIterator::operator++(int)
-{
- QTreeWidgetItemIterator it = *this;
- ++(*this);
- return it;
-}
-
-inline const QTreeWidgetItemIterator QTreeWidgetItemIterator::operator--(int)
-{
- QTreeWidgetItemIterator it = *this;
- --(*this);
- return it;
-}
-
-inline QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator+=(int n)
-{
- if (n < 0)
- return (*this) -= (-n);
- while (current && n--)
- ++(*this);
- return *this;
-}
-
-inline QTreeWidgetItemIterator &QTreeWidgetItemIterator::operator-=(int n)
-{
- if (n < 0)
- return (*this) += (-n);
- while (current && n--)
- --(*this);
- return *this;
-}
-
-inline QTreeWidgetItem *QTreeWidgetItemIterator::operator*() const
-{
- return current;
-}
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QTreeWidgetItemIterator::IteratorFlags)
-
-
-QT_END_NAMESPACE
-#endif // QT_NO_TREEWIDGET
-QT_END_HEADER
-
-#endif // QTREEWIDGETITEMITERATOR_H
diff --git a/src/gui/itemviews/qtreewidgetitemiterator_p.h b/src/gui/itemviews/qtreewidgetitemiterator_p.h
deleted file mode 100644
index 69876eb646..0000000000
--- a/src/gui/itemviews/qtreewidgetitemiterator_p.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** 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 QTREEWIDGETITEMITERATOR_P_H
-#define QTREEWIDGETITEMITERATOR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qstack.h>
-
-#ifndef QT_NO_TREEWIDGET
-#include "qtreewidgetitemiterator.h"
-
-QT_BEGIN_NAMESPACE
-
-class QTreeModel;
-class QTreeWidgetItem;
-
-class QTreeWidgetItemIteratorPrivate {
- Q_DECLARE_PUBLIC(QTreeWidgetItemIterator)
-public:
- QTreeWidgetItemIteratorPrivate(QTreeWidgetItemIterator *q, QTreeModel *model)
- : m_currentIndex(0), m_model(model), q_ptr(q)
- {
-
- }
-
- QTreeWidgetItemIteratorPrivate(const QTreeWidgetItemIteratorPrivate& other)
- : m_currentIndex(other.m_currentIndex), m_model(other.m_model),
- m_parentIndex(other.m_parentIndex), q_ptr(other.q_ptr)
- {
-
- }
-
- QTreeWidgetItemIteratorPrivate &operator=(const QTreeWidgetItemIteratorPrivate& other)
- {
- m_currentIndex = other.m_currentIndex;
- m_parentIndex = other.m_parentIndex;
- m_model = other.m_model;
- return (*this);
- }
-
- ~QTreeWidgetItemIteratorPrivate()
- {
- }
-
- QTreeWidgetItem* nextSibling(const QTreeWidgetItem* item) const;
- void ensureValidIterator(const QTreeWidgetItem *itemToBeRemoved);
-
- QTreeWidgetItem *next(const QTreeWidgetItem *current);
- QTreeWidgetItem *previous(const QTreeWidgetItem *current);
-private:
- int m_currentIndex;
- QTreeModel *m_model; // This iterator class should not have ownership of the model.
- QStack<int> m_parentIndex;
- QTreeWidgetItemIterator *q_ptr;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TREEWIDGET
-
-#endif //QTREEWIDGETITEMITERATOR_P_H
diff --git a/src/gui/itemviews/qwidgetitemdata_p.h b/src/gui/itemviews/qwidgetitemdata_p.h
deleted file mode 100644
index a7068b7559..0000000000
--- a/src/gui/itemviews/qwidgetitemdata_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGETITEMDATA_P_H
-#define QWIDGETITEMDATA_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_NAMESPACE
-
-class QWidgetItemData
-{
-public:
- inline QWidgetItemData() : role(-1) {}
- inline QWidgetItemData(int r, QVariant v) : role(r), value(v) {}
- int role;
- QVariant value;
- inline bool operator==(const QWidgetItemData &other) { return role == other.role && value == other.value; }
-};
-
-#ifndef QT_NO_DATASTREAM
-
-inline QDataStream &operator>>(QDataStream &in, QWidgetItemData &data)
-{
- in >> data.role;
- in >> data.value;
- return in;
-}
-
-inline QDataStream &operator<<(QDataStream &out, const QWidgetItemData &data)
-{
- out << data.role;
- out << data.value;
- return out;
-}
-
-#endif // QT_NO_DATASTREAM
-
-QT_END_NAMESPACE
-
-#endif // QWIDGETITEMDATA_P_H
diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri
deleted file mode 100644
index d085bff146..0000000000
--- a/src/gui/kernel/kernel.pri
+++ /dev/null
@@ -1,246 +0,0 @@
-# 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/qbackingstore_p.h \
- kernel/qboxlayout.h \
- kernel/qdesktopwidget.h \
- kernel/qformlayout.h \
- kernel/qgridlayout.h \
- kernel/qicon.h \
- kernel/qicon_p.h \
- kernel/qiconloader_p.h \
- kernel/qiconengine.h \
- kernel/qiconengineplugin.h \
- kernel/qlayout.h \
- kernel/qlayout_p.h \
- kernel/qlayoutengine_p.h \
- kernel/qlayoutitem.h \
- kernel/qsizepolicy.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/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/qbackingstore.cpp \
- kernel/qboxlayout.cpp \
- kernel/qformlayout.cpp \
- kernel/qgridlayout.cpp \
- kernel/qicon.cpp \
- kernel/qiconloader.cpp \
- kernel/qiconengine.cpp \
- kernel/qiconengineplugin.cpp \
- kernel/qlayout.cpp \
- kernel/qlayoutengine.cpp \
- kernel/qlayoutitem.cpp \
- kernel/qstackedlayout.cpp \
- kernel/qtooltip.cpp \
- kernel/qwhatsthis.cpp \
- kernel/qwidget.cpp \
- kernel/qwidgetaction.cpp \
- kernel/qgesture.cpp \
- kernel/qstandardgestures.cpp \
- kernel/qgesturerecognizer.cpp \
- kernel/qgesturemanager.cpp \
- kernel/qsoftkeymanager.cpp \
- kernel/qdesktopwidget.cpp \
- kernel/qguiplatformplugin.cpp \
- kernel/qwidgetsvariant.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
-}
-
-!qpa {
- HEADERS += \
- kernel/qsound.h \
- kernel/qsound_p.h
-
- SOURCES += \
- kernel/qsound.cpp
-}
-
-qpa {
- HEADERS += \
- kernel/qdesktopwidget_qpa_p.h \
- kernel/qwidgetwindow_qpa_p.h \
-
- SOURCES += \
- kernel/qapplication_qpa.cpp \
- kernel/qdesktopwidget_qpa.cpp \
- kernel/qwidget_qpa.cpp \
- kernel/qwidgetwindow_qpa.cpp \
-}
-
-!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
deleted file mode 100644
index df457dd166..0000000000
--- a/src/gui/kernel/mac.pri
+++ /dev/null
@@ -1,4 +0,0 @@
-!x11:!qpa:mac {
- LIBS_PRIVATE += -framework Carbon -lz
- *-mwerks:INCLUDEPATH += compat
-}
diff --git a/src/gui/kernel/qaction.cpp b/src/gui/kernel/qaction.cpp
deleted file mode 100644
index 69e9889e08..0000000000
--- a/src/gui/kernel/qaction.cpp
+++ /dev/null
@@ -1,1520 +0,0 @@
-/****************************************************************************
-**
-** 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
deleted file mode 100644
index 856fd92f10..0000000000
--- a/src/gui/kernel/qaction.h
+++ /dev/null
@@ -1,264 +0,0 @@
-/****************************************************************************
-**
-** 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
deleted file mode 100644
index f3154f90c1..0000000000
--- a/src/gui/kernel/qaction_p.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** 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
deleted file mode 100644
index 95ea8afab7..0000000000
--- a/src/gui/kernel/qactiongroup.cpp
+++ /dev/null
@@ -1,422 +0,0 @@
-/****************************************************************************
-**
-** 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
deleted file mode 100644
index 88f4fe8eac..0000000000
--- a/src/gui/kernel/qactiongroup.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** 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
deleted file mode 100644
index 2044cf78ce..0000000000
--- a/src/gui/kernel/qapplication.cpp
+++ /dev/null
@@ -1,5687 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qdnd_p.h"
-#include "qcolormap.h"
-#include "qdebug.h"
-#include "private/qstylesheetstyle_p.h"
-#include "private/qstyle_p.h"
-#include "qmessagebox.h"
-#include <QtGui/qgraphicsproxywidget.h>
-
-#include "qinputcontext.h"
-#include "private/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 "private/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)
- : QApplicationPrivateBase(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::sys_pal = 0; // default system palette
-QPalette *QApplicationPrivate::set_pal = 0; // default palette set by programmer
-
-#ifndef Q_WS_QPA
-Q_GLOBAL_STATIC(QMutex, applicationFontMutex)
-QFont *QApplicationPrivate::app_font = 0; // default application font
-#endif
-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
-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;
-
-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
-#if !defined(Q_WS_QPA) && !defined(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, "-widgetcount") == 0) {
- widgetCount = true;
- } else if (qstrcmp(arg, "-testability") == 0) {
- load_testability = true;
- } 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 -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)
- : QApplicationBase(*new QApplicationPrivate(argc, argv, GuiClient, 0x040000))
-{ Q_D(QApplication); d->construct(); }
-
-QApplication::QApplication(int &argc, char **argv, int _internal)
- : QApplicationBase(*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 )
- : QApplicationBase(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, 0x040000))
-{ Q_D(QApplication); d->construct(); }
-
-QApplication::QApplication(int &argc, char **argv, bool GUIenabled , int _internal)
- : QApplicationBase(*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)
- : QApplicationBase(*new QApplicationPrivate(argc, argv, type, 0x040000))
-{ Q_D(QApplication); d->construct(); }
-
-QApplication::QApplication(int &argc, char **argv, Type type , int _internal)
- : QApplicationBase(*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();
-
- // 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)
- : QApplicationBase(*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)
- : QApplicationBase(*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)
- : QApplicationBase(*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)
- : QApplicationBase(*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 (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);
-
-#if !defined(Q_WS_QPA) && !defined(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();
-
-#if !defined(Q_WS_QPA)
- d->eventDispatcher->closingDown();
- d->eventDispatcher = 0;
-#endif
- 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;
-
-#if !defined(Q_WS_QPA) && !defined(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();
-
-#ifndef Q_WS_QPA
- {
- QMutexLocker locker(applicationFontMutex());
- delete QApplicationPrivate::app_font;
- QApplicationPrivate::app_font = 0;
- }
-#endif
-
- 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;
-
-#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;
- 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 QApplicationBase::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;
-}
-
-/*!
- 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;
-}
-
-
-/*!
- \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()
-{
-#ifndef Q_WS_QPA
- QMutexLocker locker(applicationFontMutex());
- if (!QApplicationPrivate::app_font)
- QApplicationPrivate::app_font = new QFont(QLatin1String("Helvetica"));
- return *QApplicationPrivate::app_font;
-#else
- return QGuiApplication::font();
-#endif
-}
-
-/*!
- \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) {
-#ifndef Q_WS_QPA
- QMutexLocker locker(applicationFontMutex());
- if (!QApplicationPrivate::app_font)
- QApplicationPrivate::app_font = new QFont(font);
- else
- *QApplicationPrivate::app_font = font;
-#else
- QGuiApplication::setFont(font);
-#endif
- 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
-*/
-
-
-#ifndef QT_NO_TRANSLATION
-#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
- }
-#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 QApplicationBase::event(e);
-
- if(e->type() == QEvent::LanguageChange) {
-#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));
- }
- }
-
-}
-#if !defined(Q_WS_X11)
-
-// The doc and X implementation of this function is in qapplication_x11.cpp
-
-void QApplication::syncX() {} // do nothing
-
-#endif
-
-void QApplicationPrivate::notifyLayoutDirectionChange()
-{
- Q_Q(QApplication);
- QWidgetList list = q->topLevelWidgets();
- for (int i = 0; i < list.size(); ++i) {
- QWidget *w = list.at(i);
- QEvent ev(QEvent::ApplicationLayoutDirectionChange);
- q->sendEvent(w, &ev);
- }
-}
-
-
-/*!
- \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;
-
-#if 0
- 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;
- }
- }
-#endif
- 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;
-}
-
-#if !defined(Q_WS_QPA) && !defined(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 // Q_WS_QPA && 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.
-*/
-
-
-/*!
- \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 QGuiApplicationPrivate::visualAlignment(layoutDirection(), align);
-}
-#endif
-
-/*!
- 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 QApplicationBase::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
-
-bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
-{
- return QApplicationBase::sendSpontaneousEvent(receiver, event);
-}
-
-
-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
-
-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
deleted file mode 100644
index 3a5f02f144..0000000000
--- a/src/gui/kernel/qapplication.h
+++ /dev/null
@@ -1,422 +0,0 @@
-/****************************************************************************
-**
-** 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
-#ifdef Q_WS_QPA
-# include <QtGui/qguiapplication.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()))
-
-#ifdef Q_WS_QPA
-#define QApplicationBase QGuiApplication
-#else
-#define QApplicationBase QCoreApplication
-#endif
-
-class Q_GUI_EXPORT QApplication : public QApplicationBase
-{
- Q_OBJECT
- 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);
- // ### Qt4 compatibility, remove?
- static inline void setGraphicsSystem(const QString &) {}
-
- using QGuiApplication::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();
-#if !defined(Q_WS_QPA) && !defined(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 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 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);
-#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 QWidgetWindow;
- 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;
-
-#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_p.h b/src/gui/kernel/qapplication_p.h
deleted file mode 100644
index a089a6ba40..0000000000
--- a/src/gui/kernel/qapplication_p.h
+++ /dev/null
@@ -1,626 +0,0 @@
-/****************************************************************************
-**
-** 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_OS_SYMBIAN
-#include <w32std.h>
-#endif
-#ifdef Q_WS_QPA
-#include <QWindowSystemInterface>
-#include "private/qwindowsysteminterface_qpa_p.h"
-#include "QtGui/qplatformintegration_qpa.h"
-#include "QtGui/private/qguiapplication_p.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QClipboard;
-class QGraphicsScene;
-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();
-
-#ifdef Q_WS_QPA
-#define QApplicationPrivateBase QGuiApplicationPrivate
-#else
-#define QApplicationPrivateBase QCoreApplicationPrivate
-#endif
-
-class Q_GUI_EXPORT QApplicationPrivate : public QApplicationPrivateBase
-{
- Q_DECLARE_PUBLIC(QApplication)
-public:
- QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags);
- ~QApplicationPrivate();
-
- virtual void notifyLayoutDirectionChange();
-
-#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();
-
-
- 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
-
- 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_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 *sys_pal;
- static QPalette *set_pal;
-
-private:
-#ifndef Q_WS_QPA
- static QFont *app_font; // private for a reason! Always use QApplication::font() instead!
-#endif
-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_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
-
- 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);
-#else
- extern void qt_qpa_set_cursor(QWidget * w, bool force);
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QAPPLICATION_P_H
diff --git a/src/gui/kernel/qapplication_qpa.cpp b/src/gui/kernel/qapplication_qpa.cpp
deleted file mode 100644
index f3e033c787..0000000000
--- a/src/gui/kernel/qapplication_qpa.cpp
+++ /dev/null
@@ -1,431 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qeventdispatcher_glib_qpa_p.h"
-#endif
-#include "private/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 "private/qplatformintegrationfactory_qpa_p.h"
-#include <qdesktopwidget.h>
-
-#include <qinputcontext.h>
-#include <QPlatformCursor>
-#include <qdebug.h>
-#include <QWindowSystemInterface>
-#include "private/qwindowsysteminterface_qpa_p.h"
-#include <QPlatformIntegration>
-
-#include "qdesktopwidget_qpa_p.h"
-#include "qwidgetwindow_qpa_p.h"
-
-QT_BEGIN_NAMESPACE
-
-static QString appName;
-static QString appFont;
-
-QString QApplicationPrivate::appName() const
-{
- return QT_PREPEND_NAMESPACE(appName);
-}
-
-void QApplicationPrivate::createEventDispatcher()
-{
- QGuiApplicationPrivate::createEventDispatcher();
-}
-
-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 *)
-{
-#if 0
- if (!qt_modal_stack)
- qt_modal_stack = new QWidgetList;
- qt_modal_stack->insert(0, widget);
- app_do_modal = true;
-#endif
-}
-
-void QApplicationPrivate::leaveModal_sys(QWidget *)
-{
-#if 0
- 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;
-#endif
-}
-
-bool QApplicationPrivate::modalState()
-{
- return false;
-#if 0
- return app_do_modal;
-#endif
-}
-
-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;
- }
-}
-
-QWidget *QApplication::topLevelAt(const QPoint &pos)
-{
- QPlatformIntegration *pi = QGuiApplicationPrivate::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()) {
- QWidgetWindow *w = qobject_cast<QWidgetWindow *>((*screen)->topLevelAt(pos));
- return w ? w->widget() : 0;
- }
-
- while (screen != end) {
- if ((*screen)->geometry().contains(pos)) {
- QWidgetWindow *w = qobject_cast<QWidgetWindow *>((*screen)->topLevelAt(pos));
- return w ? w->widget() : 0;
- }
- ++screen;
- }
- return 0;
-}
-
-void QApplication::beep()
-{
-}
-
-void QApplication::alert(QWidget *, int)
-{
-}
-
-QPlatformNativeInterface *QApplication::platformNativeInterface()
-{
- QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
- return pi->nativeInterface();
-}
-
-#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 *, int type)
-{
- Q_UNUSED(type);
-
- qApp->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
- QColormap::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()
-{
- QPixmapCache::clear();
-#ifndef QT_NO_CURSOR
- QCursorData::cleanup();
-#endif
- 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
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qbackingstore.cpp b/src/gui/kernel/qbackingstore.cpp
deleted file mode 100644
index 1ee66f09cc..0000000000
--- a/src/gui/kernel/qbackingstore.cpp
+++ /dev/null
@@ -1,1665 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbackingstore_p.h"
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qdebug.h>
-#include <QtCore/qvarlengtharray.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qapplication.h>
-#include <QtGui/qpaintengine.h>
-#include <QtGui/qgraphicsproxywidget.h>
-
-#include <private/qwidget_p.h>
-#include <private/qapplication_p.h>
-#include <private/qpaintengine_raster_p.h>
-#include <private/qgraphicseffect_p.h>
-
-#ifdef Q_WS_QWS
-#include <QtGui/qwsmanager_qws.h>
-#include <private/qwsmanager_p.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern QRegion qt_dirtyRegion(QWidget *);
-
-/*
- A version of QRect::intersects() that does not normalize the rects.
-*/
-static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
-{
- return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right())
- && qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
-}
-
-/**
- * Flushes the contents of the \a windowSurface into the screen area of \a widget.
- * \a tlwOffset is the position of the top level widget relative to the window surface.
- * \a region is the region to be updated in \a widget coordinates.
- */
-static inline void qt_flush(QWidget *widget, const QRegion &region, QWindowSurface *windowSurface,
- QWidget *tlw, const QPoint &tlwOffset)
-{
- Q_ASSERT(widget);
- Q_ASSERT(!region.isEmpty());
- Q_ASSERT(windowSurface);
- Q_ASSERT(tlw);
-
-#if !defined(QT_NO_PAINT_DEBUG) && !defined(Q_WS_QWS)
- // QWS does flush update in QWindowSurface::flush (because it needs to lock the surface etc).
- static int flushUpdate = qgetenv("QT_FLUSH_UPDATE").toInt();
- if (flushUpdate > 0)
- QWidgetBackingStore::showYellowThing(widget, region, flushUpdate * 10, false);
-#endif
-
- //The performance hit by doing this should be negligible. However, be aware that
- //using this FPS when you have > 1 windowsurface can give you inaccurate FPS
- static bool fpsDebug = qgetenv("QT_DEBUG_FPS").toInt();
- if (fpsDebug) {
- static QTime time = QTime::currentTime();
- static int frames = 0;
-
- frames++;
-
- if(time.elapsed() > 5000) {
- double fps = double(frames * 1000) /time.restart();
- fprintf(stderr,"FPS: %.1f\n",fps);
- frames = 0;
- }
- }
- if (widget != tlw)
- windowSurface->flush(widget->windowHandle(), region, tlwOffset + widget->mapTo(tlw, QPoint()));
- else
- windowSurface->flush(widget->windowHandle(), region, tlwOffset);
-}
-
-#ifndef QT_NO_PAINT_DEBUG
-#ifdef Q_WS_WIN
-static void showYellowThing_win(QWidget *widget, const QRegion &region, int msec)
-{
- HBRUSH brush;
- static int i = 0;
- switch (i) {
- case 0:
- brush = CreateSolidBrush(RGB(255, 255, 0));
- break;
- case 1:
- brush = CreateSolidBrush(RGB(255, 200, 55));
- break;
- case 2:
- brush = CreateSolidBrush(RGB(200, 255, 55));
- break;
- case 3:
- brush = CreateSolidBrush(RGB(200, 200, 0));
- break;
- }
- i = (i + 1) & 3;
-
- HDC hdc = widget->getDC();
-
- const QVector<QRect> &rects = region.rects();
- foreach (QRect rect, rects) {
- RECT winRect;
- SetRect(&winRect, rect.left(), rect.top(), rect.right(), rect.bottom());
- FillRect(hdc, &winRect, brush);
- }
-
- widget->releaseDC(hdc);
- ::Sleep(msec);
-}
-#endif
-
-void QWidgetBackingStore::showYellowThing(QWidget *widget, const QRegion &toBePainted, int msec, bool unclipped)
-{
-#ifdef Q_WS_QWS
- Q_UNUSED(widget);
- Q_UNUSED(unclipped);
- static QWSYellowSurface surface(true);
- surface.setDelay(msec);
- surface.flush(widget, toBePainted, QPoint());
-#else
- QRegion paintRegion = toBePainted;
- QRect widgetRect = widget->rect();
-
- if (!widget->internalWinId()) {
- QWidget *nativeParent = widget->nativeParentWidget();
- const QPoint offset = widget->mapTo(nativeParent, QPoint(0, 0));
- paintRegion.translate(offset);
- widgetRect.translate(offset);
- widget = nativeParent;
- }
-
-#ifdef Q_WS_WIN
- Q_UNUSED(unclipped);
- showYellowThing_win(widget, paintRegion, msec);
-#else
- //flags to fool painter
- bool paintUnclipped = widget->testAttribute(Qt::WA_PaintUnclipped);
- if (unclipped && !widget->d_func()->paintOnScreen())
- widget->setAttribute(Qt::WA_PaintUnclipped);
-
- const bool setFlag = !widget->testAttribute(Qt::WA_WState_InPaintEvent);
- if (setFlag)
- widget->setAttribute(Qt::WA_WState_InPaintEvent);
-
- //setup the engine
- QPaintEngine *pe = widget->paintEngine();
- if (pe) {
- pe->setSystemClip(paintRegion);
- {
- QPainter p(widget);
- p.setClipRegion(paintRegion);
- static int i = 0;
- switch (i) {
- case 0:
- p.fillRect(widgetRect, QColor(255,255,0));
- break;
- case 1:
- p.fillRect(widgetRect, QColor(255,200,55));
- break;
- case 2:
- p.fillRect(widgetRect, QColor(200,255,55));
- break;
- case 3:
- p.fillRect(widgetRect, QColor(200,200,0));
- break;
- }
- i = (i+1) & 3;
- p.end();
- }
- }
-
- if (setFlag)
- widget->setAttribute(Qt::WA_WState_InPaintEvent, false);
-
- //restore
- widget->setAttribute(Qt::WA_PaintUnclipped, paintUnclipped);
-
- if (pe)
- pe->setSystemClip(QRegion());
-
- QApplication::syncX();
-
-#if defined(Q_OS_UNIX)
- ::usleep(1000 * msec);
-#endif
-#endif // Q_WS_WIN
-#endif // Q_WS_QWS
-}
-
-bool QWidgetBackingStore::flushPaint(QWidget *widget, const QRegion &rgn)
-{
- if (!widget)
- return false;
-
- int delay = 0;
- if (widget->testAttribute(Qt::WA_WState_InPaintEvent)) {
- static int flushPaintEvent = qgetenv("QT_FLUSH_PAINT_EVENT").toInt();
- if (!flushPaintEvent)
- return false;
- delay = flushPaintEvent;
- } else {
- static int flushPaint = qgetenv("QT_FLUSH_PAINT").toInt();
- if (!flushPaint)
- return false;
- delay = flushPaint;
- }
-
- QWidgetBackingStore::showYellowThing(widget, rgn, delay * 10, true);
- return true;
-}
-
-void QWidgetBackingStore::unflushPaint(QWidget *widget, const QRegion &rgn)
-{
- if (widget->d_func()->paintOnScreen() || rgn.isEmpty())
- return;
-
- QWidget *tlw = widget->window();
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (!tlwExtra)
- return;
-
- const QPoint offset = widget->mapTo(tlw, QPoint());
- qt_flush(widget, rgn, tlwExtra->backingStore->windowSurface, tlw, offset);
-}
-#endif // QT_NO_PAINT_DEBUG
-
-/*
- Moves the whole rect by (dx, dy) in widget's coordinate system.
- Doesn't generate any updates.
-*/
-bool QWidgetBackingStore::bltRect(const QRect &rect, int dx, int dy, QWidget *widget)
-{
- const QPoint pos(tlwOffset + widget->mapTo(tlw, rect.topLeft()));
- const QRect tlwRect(QRect(pos, rect.size()));
- if (fullUpdatePending || dirty.intersects(tlwRect))
- return false; // We don't want to scroll junk.
- return windowSurface->scroll(tlwRect, dx, dy);
-}
-
-void QWidgetBackingStore::releaseBuffer()
-{
- if (windowSurface)
-#if defined(Q_WS_QPA)
- windowSurface->resize(QSize());
-#else
- windowSurface->setGeometry(QRect());
-#endif
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- for (int i = 0; i < subSurfaces.size(); ++i)
- subSurfaces.at(i)->setGeometry(QRect());
-#endif
-}
-
-/*!
- Prepares the window surface to paint a\ toClean region of the \a widget and
- updates the BeginPaintInfo struct accordingly.
-
- The \a toClean region might be clipped by the window surface.
-*/
-void QWidgetBackingStore::beginPaint(QRegion &toClean, QWidget *widget, QWindowSurface *windowSurface,
- BeginPaintInfo *returnInfo, bool toCleanIsInTopLevelCoordinates)
-{
-#ifdef Q_WS_QWS
- QWSWindowSurface *surface = static_cast<QWSWindowSurface *>(windowSurface);
- QWidget *surfaceWidget = surface->window();
-
- if (!surface->isValid()) {
- // this looks strange but it really just releases the surface
- surface->releaseSurface();
- // the old window surface is deleted in setWindowSurface, which is
- // called from QWindowSurface constructor.
- windowSurface = tlw->d_func()->createDefaultWindowSurface();
- surface = static_cast<QWSWindowSurface *>(windowSurface);
- // createDefaultWindowSurface() will set topdata->windowSurface on the
- // widget to zero. However, if this is a sub-surface, it should point
- // to the widget's sub windowSurface, so we set that here:
- if (!surfaceWidget->isWindow())
- surfaceWidget->d_func()->topData()->windowSurface = windowSurface;
- surface->setGeometry(topLevelRect());
- returnInfo->windowSurfaceRecreated = true;
- }
-
- const QRegion toCleanUnclipped(toClean);
-
- if (surfaceWidget->isWindow())
- tlwOffset = surface->painterOffset();
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- else if (toCleanIsInTopLevelCoordinates)
- toClean &= surface->clipRegion().translated(surfaceWidget->mapTo(tlw, QPoint()));
- if (!toCleanIsInTopLevelCoordinates && windowSurface == this->windowSurface)
- toClean &= surface->clipRegion().translated(-widget->mapTo(surfaceWidget, QPoint()));
-#else
- toClean &= surface->clipRegion();
-#endif
-
- if (toClean.isEmpty()) {
- if (surfaceWidget->isWindow()) {
- dirtyFromPreviousSync += toCleanUnclipped;
- hasDirtyFromPreviousSync = true;
- }
-
- returnInfo->nothingToPaint = true;
- // Nothing to repaint. However, we might have newly exposed areas on the
- // screen, so we have to make sure those are flushed.
- flush();
- return;
- }
-
- if (surfaceWidget->isWindow()) {
- if (toCleanUnclipped != toClean) {
- dirtyFromPreviousSync += (toCleanUnclipped - surface->clipRegion());
- hasDirtyFromPreviousSync = true;
- }
- if (hasDirtyFromPreviousSync) {
- dirtyFromPreviousSync -= toClean;
- hasDirtyFromPreviousSync = !dirtyFromPreviousSync.isEmpty();
- }
- }
-
-#endif // Q_WS_QWS
-
- Q_UNUSED(widget);
- Q_UNUSED(toCleanIsInTopLevelCoordinates);
-
- // Always flush repainted areas.
- dirtyOnScreen += toClean;
-
-#if defined(Q_WS_QWS) && !defined(Q_BACKINGSTORE_SUBSURFACES)
- toClean.translate(tlwOffset);
-#endif
-
-#ifdef QT_NO_PAINT_DEBUG
- windowSurface->beginPaint(toClean);
-#else
- returnInfo->wasFlushed = QWidgetBackingStore::flushPaint(tlw, toClean);
- // Avoid deadlock with QT_FLUSH_PAINT: the server will wait for
- // the BackingStore lock, so if we hold that, the server will
- // never release the Communication lock that we are waiting for in
- // sendSynchronousCommand
- if (!returnInfo->wasFlushed)
- windowSurface->beginPaint(toClean);
-#endif
-
- Q_UNUSED(returnInfo);
-}
-
-void QWidgetBackingStore::endPaint(const QRegion &cleaned, QWindowSurface *windowSurface,
- BeginPaintInfo *beginPaintInfo)
-{
-#ifndef QT_NO_PAINT_DEBUG
- if (!beginPaintInfo->wasFlushed)
- windowSurface->endPaint(cleaned);
- else
- QWidgetBackingStore::unflushPaint(tlw, cleaned);
-#else
- Q_UNUSED(beginPaintInfo);
- windowSurface->endPaint(cleaned);
-#endif
-
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- flush(static_cast<QWSWindowSurface *>(windowSurface)->window(), windowSurface);
-#else
- flush();
-#endif
-}
-
-/*!
- Returns the region (in top-level coordinates) that needs repaint and/or flush.
-
- If the widget is non-zero, only the dirty region for the widget is returned
- and the region will be in widget coordinates.
-*/
-QRegion QWidgetBackingStore::dirtyRegion(QWidget *widget) const
-{
- const bool widgetDirty = widget && widget != tlw;
- const QRect tlwRect(topLevelRect());
-#if defined(Q_WS_QPA)
- const QRect surfaceGeometry(tlwRect.topLeft(), windowSurface->size());
-#else
- const QRect surfaceGeometry(windowSurface->geometry());
-#endif
- if (fullUpdatePending || (surfaceGeometry != tlwRect && surfaceGeometry.size() != tlwRect.size())) {
- if (widgetDirty) {
- const QRect dirtyTlwRect = QRect(QPoint(), tlwRect.size());
- const QPoint offset(widget->mapTo(tlw, QPoint()));
- const QRect dirtyWidgetRect(dirtyTlwRect & widget->rect().translated(offset));
- return dirtyWidgetRect.translated(-offset);
- }
- return QRect(QPoint(), tlwRect.size());
- }
-
- // Calculate the region that needs repaint.
- QRegion r(dirty);
- for (int i = 0; i < dirtyWidgets.size(); ++i) {
- QWidget *w = dirtyWidgets.at(i);
- if (widgetDirty && w != widget && !widget->isAncestorOf(w))
- continue;
- r += w->d_func()->dirty.translated(w->mapTo(tlw, QPoint()));
- }
-
- // Append the region that needs flush.
- r += dirtyOnScreen;
-
- if (dirtyOnScreenWidgets) { // Only in use with native child widgets.
- for (int i = 0; i < dirtyOnScreenWidgets->size(); ++i) {
- QWidget *w = dirtyOnScreenWidgets->at(i);
- if (widgetDirty && w != widget && !widget->isAncestorOf(w))
- continue;
- QWidgetPrivate *wd = w->d_func();
- Q_ASSERT(wd->needsFlush);
- r += wd->needsFlush->translated(w->mapTo(tlw, QPoint()));
- }
- }
-
- if (widgetDirty) {
- // Intersect with the widget geometry and translate to its coordinates.
- const QPoint offset(widget->mapTo(tlw, QPoint()));
- r &= widget->rect().translated(offset);
- r.translate(-offset);
- }
- return r;
-}
-
-/*!
- Returns the static content inside the \a parent if non-zero; otherwise the static content
- for the entire backing store is returned. The content will be clipped to \a withinClipRect
- if non-empty.
-*/
-QRegion QWidgetBackingStore::staticContents(QWidget *parent, const QRect &withinClipRect) const
-{
- if (!parent && tlw->testAttribute(Qt::WA_StaticContents)) {
-#if defined(Q_WS_QPA)
- const QSize surfaceGeometry(windowSurface->size());
-#else
- const QRect surfaceGeometry(windowSurface->geometry());
-#endif
- QRect surfaceRect(0, 0, surfaceGeometry.width(), surfaceGeometry.height());
- if (!withinClipRect.isEmpty())
- surfaceRect &= withinClipRect;
- return QRegion(surfaceRect);
- }
-
- QRegion region;
- if (parent && parent->d_func()->children.isEmpty())
- return region;
-
- const bool clipToRect = !withinClipRect.isEmpty();
- const int count = staticWidgets.count();
- for (int i = 0; i < count; ++i) {
- QWidget *w = staticWidgets.at(i);
- QWidgetPrivate *wd = w->d_func();
- if (!wd->isOpaque || !wd->extra || wd->extra->staticContentsSize.isEmpty()
- || !w->isVisible() || (parent && !parent->isAncestorOf(w))) {
- continue;
- }
-
- QRect rect(0, 0, wd->extra->staticContentsSize.width(), wd->extra->staticContentsSize.height());
- const QPoint offset = w->mapTo(parent ? parent : tlw, QPoint());
- if (clipToRect)
- rect &= withinClipRect.translated(-offset);
- if (rect.isEmpty())
- continue;
-
- rect &= wd->clipRect();
- if (rect.isEmpty())
- continue;
-
- QRegion visible(rect);
- wd->clipToEffectiveMask(visible);
- if (visible.isEmpty())
- continue;
- wd->subtractOpaqueSiblings(visible, 0, /*alsoNonOpaque=*/true);
-
- visible.translate(offset);
- region += visible;
- }
-
- return region;
-}
-
-static inline void sendUpdateRequest(QWidget *widget, bool updateImmediately)
-{
- if (!widget)
- return;
-
- if (updateImmediately) {
- QEvent event(QEvent::UpdateRequest);
- QApplication::sendEvent(widget, &event);
- } else {
- QApplication::postEvent(widget, new QEvent(QEvent::UpdateRequest), Qt::LowEventPriority);
- }
-}
-
-/*!
- Marks the region of the widget as dirty (if not already marked as dirty) and
- posts an UpdateRequest event to the top-level widget (if not already posted).
-
- If updateImmediately is true, the event is sent immediately instead of posted.
-
- If invalidateBuffer is true, all widgets intersecting with the region will be dirty.
-
- If the widget paints directly on screen, the event is sent to the widget
- instead of the top-level widget, and invalidateBuffer is completely ignored.
-
- ### Qt 4.6: Merge into a template function (after MSVC isn't supported anymore).
-*/
-void QWidgetBackingStore::markDirty(const QRegion &rgn, QWidget *widget, bool updateImmediately,
- bool invalidateBuffer)
-{
- Q_ASSERT(tlw->d_func()->extra);
- Q_ASSERT(tlw->d_func()->extra->topextra);
- Q_ASSERT(!tlw->d_func()->extra->topextra->inTopLevelResize);
- Q_ASSERT(widget->isVisible() && widget->updatesEnabled());
- Q_ASSERT(widget->window() == tlw);
- Q_ASSERT(!rgn.isEmpty());
-
-#ifndef QT_NO_GRAPHICSEFFECT
- widget->d_func()->invalidateGraphicsEffectsRecursively();
-#endif //QT_NO_GRAPHICSEFFECT
-
- if (widget->d_func()->paintOnScreen()) {
- if (widget->d_func()->dirty.isEmpty()) {
- widget->d_func()->dirty = rgn;
- sendUpdateRequest(widget, updateImmediately);
- return;
- } else if (qt_region_strictContains(widget->d_func()->dirty, widget->rect())) {
- if (updateImmediately)
- sendUpdateRequest(widget, updateImmediately);
- return; // Already dirty.
- }
-
- const bool eventAlreadyPosted = !widget->d_func()->dirty.isEmpty();
- widget->d_func()->dirty += rgn;
- if (!eventAlreadyPosted || updateImmediately)
- sendUpdateRequest(widget, updateImmediately);
- return;
- }
-
- if (fullUpdatePending) {
- if (updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- if (!windowSurface->hasFeature(QWindowSurface::PartialUpdates)) {
- fullUpdatePending = true;
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- const QPoint offset = widget->mapTo(tlw, QPoint());
- const QRect widgetRect = widget->d_func()->effectiveRectFor(widget->rect());
- if (qt_region_strictContains(dirty, widgetRect.translated(offset))) {
- if (updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
- return; // Already dirty.
- }
-
- if (invalidateBuffer) {
- const bool eventAlreadyPosted = !dirty.isEmpty();
-#ifndef QT_NO_GRAPHICSEFFECT
- if (widget->d_func()->graphicsEffect)
- dirty += widget->d_func()->effectiveRectFor(rgn.boundingRect()).translated(offset);
- else
-#endif //QT_NO_GRAPHICSEFFECT
- dirty += rgn.translated(offset);
- if (!eventAlreadyPosted || updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- if (dirtyWidgets.isEmpty()) {
- addDirtyWidget(widget, rgn);
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- if (widget->d_func()->inDirtyList) {
- if (!qt_region_strictContains(widget->d_func()->dirty, widgetRect)) {
-#ifndef QT_NO_GRAPHICSEFFECT
- if (widget->d_func()->graphicsEffect)
- widget->d_func()->dirty += widget->d_func()->effectiveRectFor(rgn.boundingRect());
- else
-#endif //QT_NO_GRAPHICSEFFECT
- widget->d_func()->dirty += rgn;
- }
- } else {
- addDirtyWidget(widget, rgn);
- }
-
- if (updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
-}
-
-/*!
- This function is equivalent to calling markDirty(QRegion(rect), ...), but
- is more efficient as it eliminates QRegion operations/allocations and can
- use the rect more precisely for additional cut-offs.
-
- ### Qt 4.6: Merge into a template function (after MSVC isn't supported anymore).
-*/
-void QWidgetBackingStore::markDirty(const QRect &rect, QWidget *widget, bool updateImmediately,
- bool invalidateBuffer)
-{
- Q_ASSERT(tlw->d_func()->extra);
- Q_ASSERT(tlw->d_func()->extra->topextra);
- Q_ASSERT(!tlw->d_func()->extra->topextra->inTopLevelResize);
- Q_ASSERT(widget->isVisible() && widget->updatesEnabled());
- Q_ASSERT(widget->window() == tlw);
- Q_ASSERT(!rect.isEmpty());
-
-#ifndef QT_NO_GRAPHICSEFFECT
- widget->d_func()->invalidateGraphicsEffectsRecursively();
-#endif //QT_NO_GRAPHICSEFFECT
-
- if (widget->d_func()->paintOnScreen()) {
- if (widget->d_func()->dirty.isEmpty()) {
- widget->d_func()->dirty = QRegion(rect);
- sendUpdateRequest(widget, updateImmediately);
- return;
- } else if (qt_region_strictContains(widget->d_func()->dirty, rect)) {
- if (updateImmediately)
- sendUpdateRequest(widget, updateImmediately);
- return; // Already dirty.
- }
-
- const bool eventAlreadyPosted = !widget->d_func()->dirty.isEmpty();
- widget->d_func()->dirty += rect;
- if (!eventAlreadyPosted || updateImmediately)
- sendUpdateRequest(widget, updateImmediately);
- return;
- }
-
- if (fullUpdatePending) {
- if (updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- if (!windowSurface->hasFeature(QWindowSurface::PartialUpdates)) {
- fullUpdatePending = true;
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- const QRect widgetRect = widget->d_func()->effectiveRectFor(rect);
- const QRect translatedRect(widgetRect.translated(widget->mapTo(tlw, QPoint())));
- if (qt_region_strictContains(dirty, translatedRect)) {
- if (updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
- return; // Already dirty
- }
-
- if (invalidateBuffer) {
- const bool eventAlreadyPosted = !dirty.isEmpty();
- dirty += translatedRect;
- if (!eventAlreadyPosted || updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- if (dirtyWidgets.isEmpty()) {
- addDirtyWidget(widget, rect);
- sendUpdateRequest(tlw, updateImmediately);
- return;
- }
-
- if (widget->d_func()->inDirtyList) {
- if (!qt_region_strictContains(widget->d_func()->dirty, widgetRect))
- widget->d_func()->dirty += widgetRect;
- } else {
- addDirtyWidget(widget, rect);
- }
-
- if (updateImmediately)
- sendUpdateRequest(tlw, updateImmediately);
-}
-
-/*!
- Marks the \a region of the \a widget as dirty on screen. The \a region will be copied from
- the backing store to the \a widget's native parent next time flush() is called.
-
- Paint on screen widgets are ignored.
-*/
-void QWidgetBackingStore::markDirtyOnScreen(const QRegion &region, QWidget *widget, const QPoint &topLevelOffset)
-{
- if (!widget || widget->d_func()->paintOnScreen() || region.isEmpty())
- return;
-
-#if defined(Q_WS_QWS) || defined(Q_WS_MAC)
- if (!widget->testAttribute(Qt::WA_WState_InPaintEvent))
- dirtyOnScreen += region.translated(topLevelOffset);
- return;
-#endif
-
- // Top-level.
- if (widget == tlw) {
- if (!widget->testAttribute(Qt::WA_WState_InPaintEvent))
- dirtyOnScreen += region;
- return;
- }
-
- // Alien widgets.
- if (!widget->internalWinId() && !widget->isWindow()) {
- QWidget *nativeParent = widget->nativeParentWidget(); // Alien widgets with the top-level as the native parent (common case).
- if (nativeParent == tlw) {
- if (!widget->testAttribute(Qt::WA_WState_InPaintEvent))
- dirtyOnScreen += region.translated(topLevelOffset);
- return;
- }
-
- // Alien widgets with native parent != tlw.
- QWidgetPrivate *nativeParentPrivate = nativeParent->d_func();
- if (!nativeParentPrivate->needsFlush)
- nativeParentPrivate->needsFlush = new QRegion;
- const QPoint nativeParentOffset = widget->mapTo(nativeParent, QPoint());
- *nativeParentPrivate->needsFlush += region.translated(nativeParentOffset);
- appendDirtyOnScreenWidget(nativeParent);
- return;
- }
-
- // Native child widgets.
- QWidgetPrivate *widgetPrivate = widget->d_func();
- if (!widgetPrivate->needsFlush)
- widgetPrivate->needsFlush = new QRegion;
- *widgetPrivate->needsFlush += region;
- appendDirtyOnScreenWidget(widget);
-}
-
-void QWidgetBackingStore::removeDirtyWidget(QWidget *w)
-{
- if (!w)
- return;
-
- dirtyWidgetsRemoveAll(w);
- dirtyOnScreenWidgetsRemoveAll(w);
- resetWidget(w);
-
- QWidgetPrivate *wd = w->d_func();
- const int n = wd->children.count();
- for (int i = 0; i < n; ++i) {
- if (QWidget *child = qobject_cast<QWidget*>(wd->children.at(i)))
- removeDirtyWidget(child);
- }
-}
-
-#if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER)
-bool QWidgetBackingStore::hasDirtyWindowDecoration() const
-{
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (tlwExtra && tlwExtra->qwsManager)
- return !tlwExtra->qwsManager->d_func()->dirtyRegions.isEmpty();
- return false;
-}
-
-void QWidgetBackingStore::paintWindowDecoration()
-{
- if (!hasDirtyWindowDecoration())
- return;
-
- QDecoration &decoration = QApplication::qwsDecoration();
- const QRect decorationRect = tlw->rect();
- QRegion decorationRegion = decoration.region(tlw, decorationRect);
-
- QWSManagerPrivate *managerPrivate = tlw->d_func()->topData()->qwsManager->d_func();
- const bool doClipping = !managerPrivate->entireDecorationNeedsRepaint
- && !managerPrivate->dirtyClip.isEmpty();
-
- if (doClipping) {
- decorationRegion &= static_cast<QWSWindowSurface *>(windowSurface)->clipRegion();
- decorationRegion &= managerPrivate->dirtyClip;
- }
-
- if (decorationRegion.isEmpty())
- return;
-
- //### The QWS decorations do not always paint the pixels they promise to paint.
- // This causes painting problems with QWSMemorySurface. Since none of the other
- // window surfaces actually use the region, passing an empty region is a safe
- // workaround.
-
- windowSurface->beginPaint(QRegion());
-
- QPaintEngine *engine = windowSurface->paintDevice()->paintEngine();
- Q_ASSERT(engine);
- const QRegion oldSystemClip(engine->systemClip());
- engine->setSystemClip(decorationRegion.translated(tlwOffset));
-
- QPainter painter(windowSurface->paintDevice());
- painter.setFont(QApplication::font());
- painter.translate(tlwOffset);
-
- const int numDirty = managerPrivate->dirtyRegions.size();
- for (int i = 0; i < numDirty; ++i) {
- const int area = managerPrivate->dirtyRegions.at(i);
-
- QRegion clipRegion = decoration.region(tlw, decorationRect, area);
- if (!clipRegion.isEmpty()) {
- // Decoration styles changes the clip and assumes the old clip is non-empty,
- // so we have to set it, but in theory it shouldn't be required.
- painter.setClipRegion(clipRegion);
- decoration.paint(&painter, tlw, area, managerPrivate->dirtyStates.at(i));
- }
- }
- markDirtyOnScreen(decorationRegion, tlw, QPoint());
-
- painter.end();
- windowSurface->endPaint(decorationRegion);
- managerPrivate->clearDirtyRegions();
- engine->setSystemClip(oldSystemClip);
-}
-#endif
-
-void QWidgetBackingStore::updateLists(QWidget *cur)
-{
- if (!cur)
- return;
-
- QList<QObject*> children = cur->children();
- for (int i = 0; i < children.size(); ++i) {
- QWidget *child = qobject_cast<QWidget*>(children.at(i));
- if (!child)
- continue;
-
- updateLists(child);
- }
-
- if (cur->testAttribute(Qt::WA_StaticContents))
- addStaticWidget(cur);
-
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- QTLWExtra *extra = cur->d_func()->maybeTopData();
- if (extra && extra->windowSurface && cur != tlw)
- subSurfaces.append(extra->windowSurface);
-#endif
-}
-
-QWidgetBackingStore::QWidgetBackingStore(QWidget *topLevel)
- : tlw(topLevel), dirtyOnScreenWidgets(0), hasDirtyFromPreviousSync(false)
- , fullUpdatePending(0)
-{
- windowSurface = tlw->windowSurface();
- if (!windowSurface)
- windowSurface = topLevel->d_func()->createDefaultWindowSurface();
-
- // The QWindowSurface constructor will call QWidget::setWindowSurface(),
- // but automatically created surfaces should not be added to the topdata.
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- Q_ASSERT(topLevel->d_func()->topData()->windowSurface == windowSurface);
-#endif
- topLevel->d_func()->topData()->windowSurface = 0;
-
- // Ensure all existing subsurfaces and static widgets are added to their respective lists.
- updateLists(topLevel);
-}
-
-QWidgetBackingStore::~QWidgetBackingStore()
-{
- for (int c = 0; c < dirtyWidgets.size(); ++c) {
- resetWidget(dirtyWidgets.at(c));
- }
-
- delete windowSurface;
- windowSurface = 0;
- delete dirtyOnScreenWidgets;
- dirtyOnScreenWidgets = 0;
-}
-
-//parent's coordinates; move whole rect; update parent and widget
-//assume the screen blt has already been done, so we don't need to refresh that part
-void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
-{
- Q_Q(QWidget);
- if (!q->isVisible() || (dx == 0 && dy == 0))
- return;
-
- QWidget *tlw = q->window();
- QTLWExtra* x = tlw->d_func()->topData();
- if (x->inTopLevelResize)
- return;
-
- static int accelEnv = -1;
- if (accelEnv == -1) {
- accelEnv = qgetenv("QT_NO_FAST_MOVE").toInt() == 0;
- }
-
- QWidget *pw = q->parentWidget();
- QPoint toplevelOffset = pw->mapTo(tlw, QPoint());
- QWidgetPrivate *pd = pw->d_func();
- QRect clipR(pd->clipRect());
-#ifdef Q_WS_QWS
- QWidgetBackingStore *wbs = x->backingStore.data();
- QWSWindowSurface *surface = static_cast<QWSWindowSurface*>(wbs->windowSurface);
- clipR = clipR.intersected(surface->clipRegion().translated(-toplevelOffset).boundingRect());
-#endif
- const QRect newRect(rect.translated(dx, dy));
- QRect destRect = rect.intersected(clipR);
- if (destRect.isValid())
- destRect = destRect.translated(dx, dy).intersected(clipR);
- const QRect sourceRect(destRect.translated(-dx, -dy));
- const QRect parentRect(rect & clipR);
-
- bool accelerateMove = accelEnv && isOpaque
-#ifndef QT_NO_GRAPHICSVIEW
- // No accelerate move for proxy widgets.
- && !tlw->d_func()->extra->proxyWidget
-#endif
- && !isOverlapped(sourceRect) && !isOverlapped(destRect);
-
- if (!accelerateMove) {
- QRegion parentR(effectiveRectFor(parentRect));
- if (!extra || !extra->hasMask) {
- parentR -= newRect;
- } else {
- // invalidateBuffer() excludes anything outside the mask
- parentR += newRect & clipR;
- }
- pd->invalidateBuffer(parentR);
- invalidateBuffer((newRect & clipR).translated(-data.crect.topLeft()));
- } else {
-
- QWidgetBackingStore *wbs = x->backingStore.data();
- QRegion childExpose(newRect & clipR);
-
- if (sourceRect.isValid() && wbs->bltRect(sourceRect, dx, dy, pw))
- childExpose -= destRect;
-
- if (!pw->updatesEnabled())
- return;
-
- const bool childUpdatesEnabled = q->updatesEnabled();
- if (childUpdatesEnabled && !childExpose.isEmpty()) {
- childExpose.translate(-data.crect.topLeft());
- wbs->markDirty(childExpose, q);
- isMoved = true;
- }
-
- QRegion parentExpose(parentRect);
- parentExpose -= newRect;
- if (extra && extra->hasMask)
- parentExpose += QRegion(newRect) - extra->mask.translated(data.crect.topLeft());
-
- if (!parentExpose.isEmpty()) {
- wbs->markDirty(parentExpose, pw);
- pd->isMoved = true;
- }
-
- if (childUpdatesEnabled) {
- QRegion needsFlush(sourceRect);
- needsFlush += destRect;
- wbs->markDirtyOnScreen(needsFlush, pw, toplevelOffset);
- }
- }
-}
-
-//widget's coordinates; scroll within rect; only update widget
-void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
-{
- Q_Q(QWidget);
- QWidget *tlw = q->window();
- QTLWExtra* x = tlw->d_func()->topData();
- if (x->inTopLevelResize)
- return;
-
- QWidgetBackingStore *wbs = x->backingStore.data();
- if (!wbs)
- return;
-
- static int accelEnv = -1;
- if (accelEnv == -1) {
- accelEnv = qgetenv("QT_NO_FAST_SCROLL").toInt() == 0;
- }
-
- QRect scrollRect = rect & clipRect();
- bool overlapped = false;
- bool accelerateScroll = accelEnv && isOpaque
- && !(overlapped = isOverlapped(scrollRect.translated(data.crect.topLeft())));
-
-#if defined(Q_WS_QWS)
- QWSWindowSurface *surface;
- surface = static_cast<QWSWindowSurface*>(wbs->windowSurface);
-
- if (accelerateScroll && !surface->isBuffered()) {
- const QRegion surfaceClip = surface->clipRegion();
- const QRegion outsideClip = QRegion(rect) - surfaceClip;
- if (!outsideClip.isEmpty()) {
- const QVector<QRect> clipped = (surfaceClip & rect).rects();
- if (clipped.size() < 8) {
- for (int i = 0; i < clipped.size(); ++i)
- this->scrollRect(clipped.at(i), dx, dy);
- return;
- } else {
- accelerateScroll = false;
- }
- }
- }
-#endif // Q_WS_QWS
-
- if (!accelerateScroll) {
- if (overlapped) {
- QRegion region(scrollRect);
- subtractOpaqueSiblings(region);
- invalidateBuffer(region);
- }else {
- invalidateBuffer(scrollRect);
- }
- } else {
- const QPoint toplevelOffset = q->mapTo(tlw, QPoint());
-#ifdef Q_WS_QWS
- QWSWindowSurface *surface = static_cast<QWSWindowSurface*>(wbs->windowSurface);
- const QRegion clip = surface->clipRegion().translated(-toplevelOffset) & scrollRect;
- const QRect clipBoundingRect = clip.boundingRect();
- scrollRect &= clipBoundingRect;
-#endif
- const QRect destRect = scrollRect.translated(dx, dy) & scrollRect;
- const QRect sourceRect = destRect.translated(-dx, -dy);
-
- QRegion childExpose(scrollRect);
- if (sourceRect.isValid()) {
- if (wbs->bltRect(sourceRect, dx, dy, q))
- childExpose -= destRect;
- }
-
- if (inDirtyList) {
- if (rect == q->rect()) {
- dirty.translate(dx, dy);
- } else {
- QRegion dirtyScrollRegion = dirty.intersected(scrollRect);
- if (!dirtyScrollRegion.isEmpty()) {
- dirty -= dirtyScrollRegion;
- dirtyScrollRegion.translate(dx, dy);
- dirty += dirtyScrollRegion;
- }
- }
- }
-
- if (!q->updatesEnabled())
- return;
-
- if (!childExpose.isEmpty()) {
- wbs->markDirty(childExpose, q);
- isScrolled = true;
- }
-
- // Instead of using native scroll-on-screen, we copy from
- // backingstore, giving only one screen update for each
- // scroll, and a solid appearance
- wbs->markDirtyOnScreen(destRect, q, toplevelOffset);
- }
-}
-
-static inline bool discardSyncRequest(QWidget *tlw, QTLWExtra *tlwExtra)
-{
- if (!tlw || !tlwExtra)
- return true;
-
-#ifdef Q_WS_X11
- // Delay the sync until we get an Expose event from X11 (initial show).
- // Qt::WA_Mapped is set to true, but the actual mapping has not yet occurred.
- // However, we must repaint immediately regardless of the state if someone calls repaint().
- if (tlwExtra->waitingForMapNotify && !tlwExtra->inRepaint)
- return true;
-#endif
-
- if (!tlw->testAttribute(Qt::WA_Mapped))
- return true;
-
- if (!tlw->isVisible()
-#ifndef Q_WS_X11
- // If we're minimized on X11, WA_Mapped will be false and we
- // will return in the case above. Some window managers on X11
- // sends us the PropertyNotify to change the minimized state
- // *AFTER* we've received the expose event, which is baaad.
- || tlw->isMinimized()
-#endif
- )
- return true;
-
- return false;
-}
-
-/*!
- Synchronizes the \a exposedRegion of the \a exposedWidget with the backing store.
-
- If there's nothing to repaint, the area is flushed and painting does not occur;
- otherwise the area is marked as dirty on screen and will be flushed right after
- we are done with all painting.
-*/
-void QWidgetBackingStore::sync(QWidget *exposedWidget, const QRegion &exposedRegion)
-{
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (discardSyncRequest(tlw, tlwExtra) || tlwExtra->inTopLevelResize)
- return;
-
- if (!exposedWidget || !exposedWidget->internalWinId() || !exposedWidget->isVisible()
- || !exposedWidget->updatesEnabled() || exposedRegion.isEmpty()) {
- return;
- }
-
- // If there's no preserved contents support we always need
- // to do a full repaint before flushing
- if (!windowSurface->hasFeature(QWindowSurface::PreservedContents))
- fullUpdatePending = true;
-
- // Nothing to repaint.
- if (!isDirty()) {
- qt_flush(exposedWidget, exposedRegion, windowSurface, tlw, tlwOffset);
- return;
- }
-
- if (exposedWidget != tlw)
- markDirtyOnScreen(exposedRegion, exposedWidget, exposedWidget->mapTo(tlw, QPoint()));
- else
- markDirtyOnScreen(exposedRegion, exposedWidget, QPoint());
- sync();
-}
-
-/*!
- Synchronizes the backing store, i.e. dirty areas are repainted and flushed.
-*/
-void QWidgetBackingStore::sync()
-{
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (discardSyncRequest(tlw, tlwExtra)) {
- // If the top-level is minimized, it's not visible on the screen so we can delay the
- // update until it's shown again. In order to do that we must keep the dirty states.
- // These will be cleared when we receive the first expose after showNormal().
- // However, if the widget is not visible (isVisible() returns false), everything will
- // be invalidated once the widget is shown again, so clear all dirty states.
- if (!tlw->isVisible()) {
- dirty = QRegion();
- for (int i = 0; i < dirtyWidgets.size(); ++i)
- resetWidget(dirtyWidgets.at(i));
- dirtyWidgets.clear();
- fullUpdatePending = false;
- }
- return;
- }
-
- const bool updatesDisabled = !tlw->updatesEnabled();
- bool repaintAllWidgets = false;
-
- const bool inTopLevelResize = tlwExtra->inTopLevelResize;
- const QRect tlwRect(topLevelRect());
-#ifdef Q_WS_QPA
- const QRect surfaceGeometry(tlwRect.topLeft(), windowSurface->size());
-#else
- const QRect surfaceGeometry(windowSurface->geometry());
-#endif
- if ((fullUpdatePending || inTopLevelResize || surfaceGeometry.size() != tlwRect.size()) && !updatesDisabled) {
- if (hasStaticContents()) {
- // Repaint existing dirty area and newly visible area.
- const QRect clipRect(0, 0, surfaceGeometry.width(), surfaceGeometry.height());
- const QRegion staticRegion(staticContents(0, clipRect));
- QRegion newVisible(0, 0, tlwRect.width(), tlwRect.height());
- newVisible -= staticRegion;
- dirty += newVisible;
- windowSurface->setStaticContents(staticRegion);
- } else {
- // Repaint everything.
- dirty = QRegion(0, 0, tlwRect.width(), tlwRect.height());
- for (int i = 0; i < dirtyWidgets.size(); ++i)
- resetWidget(dirtyWidgets.at(i));
- dirtyWidgets.clear();
- repaintAllWidgets = true;
- }
- }
-
-#ifdef Q_WS_QPA
- if (inTopLevelResize || surfaceGeometry.size() != tlwRect.size())
- windowSurface->resize(tlwRect.size());
-#else
- if (inTopLevelResize || surfaceGeometry != tlwRect)
- windowSurface->setGeometry(tlwRect);
-#endif
-
- if (updatesDisabled)
- return;
-
- if (hasDirtyFromPreviousSync)
- dirty += dirtyFromPreviousSync;
-
- // Contains everything that needs repaint.
- QRegion toClean(dirty);
-
- // Loop through all update() widgets and remove them from the list before they are
- // painted (in case someone calls update() in paintEvent). If the widget is opaque
- // and does not have transparent overlapping siblings, append it to the
- // opaqueNonOverlappedWidgets list and paint it directly without composition.
- QVarLengthArray<QWidget *, 32> opaqueNonOverlappedWidgets;
- for (int i = 0; i < dirtyWidgets.size(); ++i) {
- QWidget *w = dirtyWidgets.at(i);
- QWidgetPrivate *wd = w->d_func();
- if (wd->data.in_destructor)
- continue;
-
- // Clip with mask() and clipRect().
- wd->dirty &= wd->clipRect();
- wd->clipToEffectiveMask(wd->dirty);
-
- // Subtract opaque siblings and children.
- bool hasDirtySiblingsAbove = false;
- // We know for sure that the widget isn't overlapped if 'isMoved' is true.
- if (!wd->isMoved)
- wd->subtractOpaqueSiblings(wd->dirty, &hasDirtySiblingsAbove);
- // Scrolled and moved widgets must draw all children.
- if (!wd->isScrolled && !wd->isMoved)
- wd->subtractOpaqueChildren(wd->dirty, w->rect());
-
- if (wd->dirty.isEmpty()) {
- resetWidget(w);
- continue;
- }
-
- const QRegion widgetDirty(w != tlw ? wd->dirty.translated(w->mapTo(tlw, QPoint()))
- : wd->dirty);
- toClean += widgetDirty;
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (tlw->d_func()->extra->proxyWidget) {
- resetWidget(w);
- continue;
- }
-#endif
-
- if (!hasDirtySiblingsAbove && wd->isOpaque && !dirty.intersects(widgetDirty.boundingRect())) {
- opaqueNonOverlappedWidgets.append(w);
- } else {
- resetWidget(w);
- dirty += widgetDirty;
- }
- }
- dirtyWidgets.clear();
-
- fullUpdatePending = false;
-
- if (toClean.isEmpty()) {
- // Nothing to repaint. However, we might have newly exposed areas on the
- // screen if this function was called from sync(QWidget *, QRegion)), so
- // we have to make sure those are flushed.
- flush();
- return;
- }
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (tlw->d_func()->extra->proxyWidget) {
- updateStaticContentsSize();
- dirty = QRegion();
- const QVector<QRect> rects(toClean.rects());
- for (int i = 0; i < rects.size(); ++i)
- tlw->d_func()->extra->proxyWidget->update(rects.at(i));
- return;
- }
-#endif
-
-#ifndef Q_BACKINGSTORE_SUBSURFACES
- BeginPaintInfo beginPaintInfo;
- beginPaint(toClean, tlw, windowSurface, &beginPaintInfo);
- if (beginPaintInfo.nothingToPaint) {
- for (int i = 0; i < opaqueNonOverlappedWidgets.size(); ++i)
- resetWidget(opaqueNonOverlappedWidgets[i]);
- dirty = QRegion();
- return;
- }
-#endif
-
- // Must do this before sending any paint events because
- // the size may change in the paint event.
- updateStaticContentsSize();
- const QRegion dirtyCopy(dirty);
- dirty = QRegion();
-
- // Paint opaque non overlapped widgets.
- for (int i = 0; i < opaqueNonOverlappedWidgets.size(); ++i) {
- QWidget *w = opaqueNonOverlappedWidgets[i];
- QWidgetPrivate *wd = w->d_func();
-
- int flags = QWidgetPrivate::DrawRecursive;
- // Scrolled and moved widgets must draw all children.
- if (!wd->isScrolled && !wd->isMoved)
- flags |= QWidgetPrivate::DontDrawOpaqueChildren;
- if (w == tlw)
- flags |= QWidgetPrivate::DrawAsRoot;
-
- QRegion toBePainted(wd->dirty);
- resetWidget(w);
-
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- QWindowSurface *subSurface = w->windowSurface();
- BeginPaintInfo beginPaintInfo;
-
- QPoint off = w->mapTo(tlw, QPoint());
- toBePainted.translate(off);
- beginPaint(toBePainted, w, subSurface, &beginPaintInfo, true);
- toBePainted.translate(-off);
-
- if (beginPaintInfo.nothingToPaint)
- continue;
-
- if (beginPaintInfo.windowSurfaceRecreated) {
- // Eep the window surface has changed. The old one may have been
- // deleted, in which case we will segfault on the call to
- // painterOffset() below. Use the new window surface instead.
- subSurface = w->windowSurface();
- }
-
- QPoint offset(tlwOffset);
- if (subSurface == windowSurface)
- offset += w->mapTo(tlw, QPoint());
- else
- offset = static_cast<QWSWindowSurface*>(subSurface)->painterOffset();
- wd->drawWidget(subSurface->paintDevice(), toBePainted, offset, flags, 0, this);
-
- endPaint(toBePainted, subSurface, &beginPaintInfo);
-#else
- QPoint offset(tlwOffset);
- if (w != tlw)
- offset += w->mapTo(tlw, QPoint());
- wd->drawWidget(windowSurface->paintDevice(), toBePainted, offset, flags, 0, this);
-#endif
- }
-
- // Paint the rest with composition.
-#ifndef Q_BACKINGSTORE_SUBSURFACES
- if (repaintAllWidgets || !dirtyCopy.isEmpty()) {
- const int flags = QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawRecursive;
- tlw->d_func()->drawWidget(windowSurface->paintDevice(), dirtyCopy, tlwOffset, flags, 0, this);
- }
-
- endPaint(toClean, windowSurface, &beginPaintInfo);
-#else
- if (!repaintAllWidgets && dirtyCopy.isEmpty())
- return; // Nothing more to paint.
-
- QList<QWindowSurface *> surfaceList(subSurfaces);
- surfaceList.prepend(windowSurface);
- const QRect dirtyBoundingRect(dirtyCopy.boundingRect());
-
- // Loop through all window surfaces (incl. the top-level surface) and
- // repaint those intersecting with the bounding rect of the dirty region.
- for (int i = 0; i < surfaceList.size(); ++i) {
- QWindowSurface *subSurface = surfaceList.at(i);
- QWidget *w = subSurface->window();
- QWidgetPrivate *wd = w->d_func();
-
- const QRect clipRect = wd->clipRect().translated(w->mapTo(tlw, QPoint()));
- if (!qRectIntersects(dirtyBoundingRect, clipRect))
- continue;
-
- toClean = dirtyCopy;
- BeginPaintInfo beginPaintInfo;
- beginPaint(toClean, w, subSurface, &beginPaintInfo);
- if (beginPaintInfo.nothingToPaint)
- continue;
-
- if (beginPaintInfo.windowSurfaceRecreated) {
- // Eep the window surface has changed. The old one may have been
- // deleted, in which case we will segfault on the call to
- // painterOffset() below. Use the new window surface instead.
- subSurface = w->windowSurface();
- }
-
- int flags = QWidgetPrivate::DrawRecursive;
- if (w == tlw)
- flags |= QWidgetPrivate::DrawAsRoot;
- const QPoint painterOffset = static_cast<QWSWindowSurface*>(subSurface)->painterOffset();
- wd->drawWidget(subSurface->paintDevice(), toClean, painterOffset, flags, 0, this);
-
- endPaint(toClean, subSurface, &beginPaintInfo);
- }
-#endif
-}
-
-/*!
- Flushes the contents of the backing store into the top-level widget.
- If the \a widget is non-zero, the content is flushed to the \a widget.
- If the \a surface is non-zero, the content of the \a surface is flushed.
-*/
-void QWidgetBackingStore::flush(QWidget *widget, QWindowSurface *surface)
-{
-#if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER)
- paintWindowDecoration();
-#endif
-
- if (!dirtyOnScreen.isEmpty()) {
- QWidget *target = widget ? widget : tlw;
- QWindowSurface *source = surface ? surface : windowSurface;
- qt_flush(target, dirtyOnScreen, source, tlw, tlwOffset);
- dirtyOnScreen = QRegion();
- }
-
- if (!dirtyOnScreenWidgets || dirtyOnScreenWidgets->isEmpty())
- return;
-
- for (int i = 0; i < dirtyOnScreenWidgets->size(); ++i) {
- QWidget *w = dirtyOnScreenWidgets->at(i);
- QWidgetPrivate *wd = w->d_func();
- Q_ASSERT(wd->needsFlush);
- qt_flush(w, *wd->needsFlush, windowSurface, tlw, tlwOffset);
- *wd->needsFlush = QRegion();
- }
- dirtyOnScreenWidgets->clear();
-}
-
-static inline bool discardInvalidateBufferRequest(QWidget *widget, QTLWExtra *tlwExtra)
-{
- Q_ASSERT(widget);
- if (QApplication::closingDown())
- return true;
-
- if (!tlwExtra || tlwExtra->inTopLevelResize || !tlwExtra->backingStore)
- return true;
-
- if (!widget->isVisible() || !widget->updatesEnabled())
- return true;
-
- return false;
-}
-
-/*!
- Invalidates the buffer when the widget is resized.
- Static areas are never invalidated unless absolutely needed.
-*/
-void QWidgetPrivate::invalidateBuffer_resizeHelper(const QPoint &oldPos, const QSize &oldSize)
-{
- Q_Q(QWidget);
- Q_ASSERT(!q->isWindow());
- Q_ASSERT(q->parentWidget());
-
- const bool staticContents = q->testAttribute(Qt::WA_StaticContents);
- const bool sizeDecreased = (data.crect.width() < oldSize.width())
- || (data.crect.height() < oldSize.height());
-
- const QPoint offset(data.crect.x() - oldPos.x(), data.crect.y() - oldPos.y());
- const bool parentAreaExposed = !offset.isNull() || sizeDecreased;
- const QRect newWidgetRect(q->rect());
- const QRect oldWidgetRect(0, 0, oldSize.width(), oldSize.height());
-
- if (!staticContents || graphicsEffect) {
- QRegion staticChildren;
- QWidgetBackingStore *bs = 0;
- if (offset.isNull() && (bs = maybeBackingStore()))
- staticChildren = bs->staticContents(q, oldWidgetRect);
- const bool hasStaticChildren = !staticChildren.isEmpty();
-
- if (hasStaticChildren) {
- QRegion dirty(newWidgetRect);
- dirty -= staticChildren;
- invalidateBuffer(dirty);
- } else {
- // Entire widget needs repaint.
- invalidateBuffer(newWidgetRect);
- }
-
- if (!parentAreaExposed)
- return;
-
- // Invalidate newly exposed area of the parent.
- if (!graphicsEffect && extra && extra->hasMask) {
- QRegion parentExpose(extra->mask.translated(oldPos));
- parentExpose &= QRect(oldPos, oldSize);
- if (hasStaticChildren)
- parentExpose -= data.crect; // Offset is unchanged, safe to do this.
- q->parentWidget()->d_func()->invalidateBuffer(parentExpose);
- } else {
- if (hasStaticChildren && !graphicsEffect) {
- QRegion parentExpose(QRect(oldPos, oldSize));
- parentExpose -= data.crect; // Offset is unchanged, safe to do this.
- q->parentWidget()->d_func()->invalidateBuffer(parentExpose);
- } else {
- q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(QRect(oldPos, oldSize)));
- }
- }
- return;
- }
-
- // Move static content to its new position.
- if (!offset.isNull()) {
- if (sizeDecreased) {
- const QSize minSize(qMin(oldSize.width(), data.crect.width()),
- qMin(oldSize.height(), data.crect.height()));
- moveRect(QRect(oldPos, minSize), offset.x(), offset.y());
- } else {
- moveRect(QRect(oldPos, oldSize), offset.x(), offset.y());
- }
- }
-
- // Invalidate newly visible area of the widget.
- if (!sizeDecreased || !oldWidgetRect.contains(newWidgetRect)) {
- QRegion newVisible(newWidgetRect);
- newVisible -= oldWidgetRect;
- invalidateBuffer(newVisible);
- }
-
- if (!parentAreaExposed)
- return;
-
- // Invalidate newly exposed area of the parent.
- const QRect oldRect(oldPos, oldSize);
- if (extra && extra->hasMask) {
- QRegion parentExpose(oldRect);
- parentExpose &= extra->mask.translated(oldPos);
- parentExpose -= (extra->mask.translated(data.crect.topLeft()) & data.crect);
- q->parentWidget()->d_func()->invalidateBuffer(parentExpose);
- } else {
- QRegion parentExpose(oldRect);
- parentExpose -= data.crect;
- q->parentWidget()->d_func()->invalidateBuffer(parentExpose);
- }
-}
-
-/*!
- Invalidates the \a rgn (in widget's coordinates) of the backing store, i.e.
- all widgets intersecting with the region will be repainted when the backing store
- is synced.
-
- ### Qt 4.6: Merge into a template function (after MSVC isn't supported anymore).
-*/
-void QWidgetPrivate::invalidateBuffer(const QRegion &rgn)
-{
- Q_Q(QWidget);
-
- QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- if (discardInvalidateBufferRequest(q, tlwExtra) || rgn.isEmpty())
- return;
-
- QRegion wrgn(rgn);
- wrgn &= clipRect();
- if (!graphicsEffect && extra && extra->hasMask)
- wrgn &= extra->mask;
- if (wrgn.isEmpty())
- return;
-
- tlwExtra->backingStore->markDirty(wrgn, q, false, true);
-}
-
-/*!
- This function is equivalent to calling invalidateBuffer(QRegion(rect), ...), but
- is more efficient as it eliminates QRegion operations/allocations and can
- use the rect more precisely for additional cut-offs.
-
- ### Qt 4.6: Merge into a template function (after MSVC isn't supported anymore).
-*/
-void QWidgetPrivate::invalidateBuffer(const QRect &rect)
-{
- Q_Q(QWidget);
-
- QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- if (discardInvalidateBufferRequest(q, tlwExtra) || rect.isEmpty())
- return;
-
- QRect wRect(rect);
- wRect &= clipRect();
- if (wRect.isEmpty())
- return;
-
- if (graphicsEffect || !extra || !extra->hasMask) {
- tlwExtra->backingStore->markDirty(wRect, q, false, true);
- return;
- }
-
- QRegion wRgn(extra->mask);
- wRgn &= wRect;
- if (wRgn.isEmpty())
- return;
-
- tlwExtra->backingStore->markDirty(wRgn, q, false, true);
-}
-
-void QWidgetPrivate::repaint_sys(const QRegion &rgn)
-{
- if (data.in_destructor)
- return;
-
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_StaticContents)) {
- if (!extra)
- createExtra();
- extra->staticContentsSize = data.crect.size();
- }
-
-#ifdef Q_WS_QPA //Dont even call q->p
- QPaintEngine *engine = 0;
-#else
- QPaintEngine *engine = q->paintEngine();
-#endif
- // QGLWidget does not support partial updates if:
- // 1) The context is double buffered
- // 2) The context is single buffered and auto-fill background is enabled.
- const bool noPartialUpdateSupport = (engine && (engine->type() == QPaintEngine::OpenGL
- || engine->type() == QPaintEngine::OpenGL2))
- && (usesDoubleBufferedGLContext || q->autoFillBackground());
- QRegion toBePainted(noPartialUpdateSupport ? q->rect() : rgn);
-
-#ifdef Q_WS_MAC
- // No difference between update() and repaint() on the Mac.
- update_sys(toBePainted);
- return;
-#endif
-
- toBePainted &= clipRect();
- clipToEffectiveMask(toBePainted);
- if (toBePainted.isEmpty())
- return; // Nothing to repaint.
-
-#ifndef QT_NO_PAINT_DEBUG
- bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
-#endif
-
- drawWidget(q, toBePainted, QPoint(), QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawPaintOnScreen, 0);
-
-#ifndef QT_NO_PAINT_DEBUG
- if (flushed)
- QWidgetBackingStore::unflushPaint(q, toBePainted);
-#endif
-
- if (!q->testAttribute(Qt::WA_PaintOutsidePaintEvent) && q->paintingActive())
- qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qbackingstore_p.h b/src/gui/kernel/qbackingstore_p.h
deleted file mode 100644
index 05f4bfcb6c..0000000000
--- a/src/gui/kernel/qbackingstore_p.h
+++ /dev/null
@@ -1,278 +0,0 @@
-/****************************************************************************
-**
-** 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 QBACKINGSTORE_P_H
-#define QBACKINGSTORE_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QDebug>
-#include <QtGui/qwidget.h>
-#include <private/qwidget_p.h>
-#include <private/qwindowsurface_p.h>
-#ifdef Q_WS_QWS
-#include <private/qwindowsurface_qws_p.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QWindowSurface;
-
-struct BeginPaintInfo {
- inline BeginPaintInfo() : wasFlushed(0), nothingToPaint(0), windowSurfaceRecreated(0) {}
- uint wasFlushed : 1;
- uint nothingToPaint : 1;
- uint windowSurfaceRecreated : 1;
-};
-
-class Q_AUTOTEST_EXPORT QWidgetBackingStore
-{
-public:
- QWidgetBackingStore(QWidget *t);
- ~QWidgetBackingStore();
-
- static void showYellowThing(QWidget *widget, const QRegion &rgn, int msec, bool);
-
- void sync(QWidget *exposedWidget, const QRegion &exposedRegion);
- void sync();
- void flush(QWidget *widget = 0, QWindowSurface *surface = 0);
-
- inline QPoint topLevelOffset() const { return tlwOffset; }
-
- QWindowSurface *surface() const { return windowSurface; }
-
- inline bool isDirty() const
- {
- return !(dirtyWidgets.isEmpty() && dirty.isEmpty() && !hasDirtyFromPreviousSync
- && !fullUpdatePending
-#if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER)
- && !hasDirtyWindowDecoration()
-#endif
- );
- }
-
- // ### Qt 4.6: Merge into a template function (after MSVC isn't supported anymore).
- void markDirty(const QRegion &rgn, QWidget *widget, bool updateImmediately = false,
- bool invalidateBuffer = false);
- void markDirty(const QRect &rect, QWidget *widget, bool updateImmediately = false,
- bool invalidateBuffer = false);
-
-private:
- QWidget *tlw;
- QRegion dirtyOnScreen; // needsFlush
- QRegion dirty; // needsRepaint
- QRegion dirtyFromPreviousSync;
- QVector<QWidget *> dirtyWidgets;
- QVector<QWidget *> *dirtyOnScreenWidgets;
- QList<QWidget *> staticWidgets;
- QWindowSurface *windowSurface;
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- QList<QWindowSurface*> subSurfaces;
-#endif
- uint hasDirtyFromPreviousSync : 1;
- uint fullUpdatePending : 1;
-
- QPoint tlwOffset;
-
- static bool flushPaint(QWidget *widget, const QRegion &rgn);
- static void unflushPaint(QWidget *widget, const QRegion &rgn);
-
- bool bltRect(const QRect &rect, int dx, int dy, QWidget *widget);
- void releaseBuffer();
-
- void beginPaint(QRegion &toClean, QWidget *widget, QWindowSurface *windowSurface,
- BeginPaintInfo *returnInfo, bool toCleanIsInTopLevelCoordinates = true);
- void endPaint(const QRegion &cleaned, QWindowSurface *windowSurface, BeginPaintInfo *beginPaintInfo);
-
- QRegion dirtyRegion(QWidget *widget = 0) const;
- QRegion staticContents(QWidget *widget = 0, const QRect &withinClipRect = QRect()) const;
-
- void markDirtyOnScreen(const QRegion &dirtyOnScreen, QWidget *widget, const QPoint &topLevelOffset);
-
- void removeDirtyWidget(QWidget *w);
-
-#if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER)
- bool hasDirtyWindowDecoration() const;
- void paintWindowDecoration();
-#endif
- void updateLists(QWidget *widget);
-
- inline void addDirtyWidget(QWidget *widget, const QRegion &rgn)
- {
- if (widget && !widget->d_func()->inDirtyList && !widget->data->in_destructor) {
- QWidgetPrivate *widgetPrivate = widget->d_func();
-#ifndef QT_NO_GRAPHICSEFFECT
- if (widgetPrivate->graphicsEffect)
- widgetPrivate->dirty = widgetPrivate->effectiveRectFor(rgn.boundingRect());
- else
-#endif //QT_NO_GRAPHICSEFFECT
- widgetPrivate->dirty = rgn;
- dirtyWidgets.append(widget);
- widgetPrivate->inDirtyList = true;
- }
- }
-
- inline void dirtyWidgetsRemoveAll(QWidget *widget)
- {
- int i = 0;
- while (i < dirtyWidgets.size()) {
- if (dirtyWidgets.at(i) == widget)
- dirtyWidgets.remove(i);
- else
- ++i;
- }
- }
-
- inline void addStaticWidget(QWidget *widget)
- {
- if (!widget)
- return;
-
- Q_ASSERT(widget->testAttribute(Qt::WA_StaticContents));
- if (!staticWidgets.contains(widget))
- staticWidgets.append(widget);
- }
-
- inline void removeStaticWidget(QWidget *widget)
- { staticWidgets.removeAll(widget); }
-
- // Move the reparented widget and all its static children from this backing store
- // to the new backing store if reparented into another top-level / backing store.
- inline void moveStaticWidgets(QWidget *reparented)
- {
- Q_ASSERT(reparented);
- QWidgetBackingStore *newBs = reparented->d_func()->maybeBackingStore();
- if (newBs == this)
- return;
-
- int i = 0;
- while (i < staticWidgets.size()) {
- QWidget *w = staticWidgets.at(i);
- if (reparented == w || reparented->isAncestorOf(w)) {
- staticWidgets.removeAt(i);
- if (newBs)
- newBs->addStaticWidget(w);
- } else {
- ++i;
- }
- }
- }
-
- inline QRect topLevelRect() const
- {
-#ifdef Q_WS_QWS
- return tlw->frameGeometry();
-#else
- return tlw->data->crect;
-#endif
- }
-
- inline void appendDirtyOnScreenWidget(QWidget *widget)
- {
- if (!widget)
- return;
-
- if (!dirtyOnScreenWidgets) {
- dirtyOnScreenWidgets = new QVector<QWidget *>;
- dirtyOnScreenWidgets->append(widget);
- } else if (!dirtyOnScreenWidgets->contains(widget)) {
- dirtyOnScreenWidgets->append(widget);
- }
- }
-
- inline void dirtyOnScreenWidgetsRemoveAll(QWidget *widget)
- {
- if (!widget || !dirtyOnScreenWidgets)
- return;
-
- int i = 0;
- while (i < dirtyOnScreenWidgets->size()) {
- if (dirtyOnScreenWidgets->at(i) == widget)
- dirtyOnScreenWidgets->remove(i);
- else
- ++i;
- }
- }
-
- inline void resetWidget(QWidget *widget)
- {
- if (widget) {
- widget->d_func()->inDirtyList = false;
- widget->d_func()->isScrolled = false;
- widget->d_func()->isMoved = false;
- widget->d_func()->dirty = QRegion();
- }
- }
-
- inline void updateStaticContentsSize()
- {
- for (int i = 0; i < staticWidgets.size(); ++i) {
- QWidgetPrivate *wd = staticWidgets.at(i)->d_func();
- if (!wd->extra)
- wd->createExtra();
- wd->extra->staticContentsSize = wd->data.crect.size();
- }
- }
-
- inline bool hasStaticContents() const
- { return !staticWidgets.isEmpty() && windowSurface->hasFeature(QWindowSurface::StaticContents); }
-
- friend QRegion qt_dirtyRegion(QWidget *);
- friend class QWidgetPrivate;
- friend class QWidget;
- friend class QWSManagerPrivate;
- friend class QETWidget;
- friend class QWindowSurface;
- friend class QWSWindowSurface;
-};
-
-QT_END_NAMESPACE
-
-#endif // QBACKINGSTORE_P_H
diff --git a/src/gui/kernel/qboxlayout.cpp b/src/gui/kernel/qboxlayout.cpp
deleted file mode 100644
index 6946f9bd27..0000000000
--- a/src/gui/kernel/qboxlayout.cpp
+++ /dev/null
@@ -1,1550 +0,0 @@
-/****************************************************************************
-**
-** 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 "qboxlayout.h"
-#include "qapplication.h"
-#include "qwidget.h"
-#include "qlist.h"
-#include "qsizepolicy.h"
-#include "qvector.h"
-
-#include "qlayoutengine_p.h"
-#include "qlayout_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*
- Returns true if the \a widget can be added to the \a layout;
- otherwise returns false.
-*/
-static bool checkWidget(QLayout *layout, QWidget *widget)
-{
- if (!widget) {
- qWarning("QLayout: Cannot add null widget to %s/%s", layout->metaObject()->className(),
- layout->objectName().toLocal8Bit().data());
- return false;
- }
- return true;
-}
-
-struct QBoxLayoutItem
-{
- QBoxLayoutItem(QLayoutItem *it, int stretch_ = 0)
- : item(it), stretch(stretch_), magic(false) { }
- ~QBoxLayoutItem() { delete item; }
-
- int hfw(int w) {
- if (item->hasHeightForWidth()) {
- return item->heightForWidth(w);
- } else {
- return item->sizeHint().height();
- }
- }
- int mhfw(int w) {
- if (item->hasHeightForWidth()) {
- return item->heightForWidth(w);
- } else {
- return item->minimumSize().height();
- }
- }
- int hStretch() {
- if (stretch == 0 && item->widget()) {
- return item->widget()->sizePolicy().horizontalStretch();
- } else {
- return stretch;
- }
- }
- int vStretch() {
- if (stretch == 0 && item->widget()) {
- return item->widget()->sizePolicy().verticalStretch();
- } else {
- return stretch;
- }
- }
-
- QLayoutItem *item;
- int stretch;
- bool magic;
-};
-
-class QBoxLayoutPrivate : public QLayoutPrivate
-{
- Q_DECLARE_PUBLIC(QBoxLayout)
-public:
- QBoxLayoutPrivate() : hfwWidth(-1), dirty(true), spacing(-1) { }
- ~QBoxLayoutPrivate();
-
- void setDirty() {
- geomArray.clear();
- hfwWidth = -1;
- hfwHeight = -1;
- dirty = true;
- }
-
- QList<QBoxLayoutItem *> list;
- QVector<QLayoutStruct> geomArray;
- int hfwWidth;
- int hfwHeight;
- int hfwMinHeight;
- QSize sizeHint;
- QSize minSize;
- QSize maxSize;
- int leftMargin, topMargin, rightMargin, bottomMargin;
- Qt::Orientations expanding;
- uint hasHfw : 1;
- uint dirty : 1;
- QBoxLayout::Direction dir;
- int spacing;
-
- inline void deleteAll() { while (!list.isEmpty()) delete list.takeFirst(); }
-
- void setupGeom();
- void calcHfw(int);
-
- void effectiveMargins(int *left, int *top, int *right, int *bottom) const;
-};
-
-QBoxLayoutPrivate::~QBoxLayoutPrivate()
-{
-}
-
-static inline bool horz(QBoxLayout::Direction dir)
-{
- return dir == QBoxLayout::RightToLeft || dir == QBoxLayout::LeftToRight;
-}
-
-/**
- * The purpose of this function is to make sure that widgets are not laid out outside its layout.
- * E.g. the layoutItemRect margins are only meant to take of the surrounding margins/spacings.
- * However, if the margin is 0, it can easily cover the area of a widget above it.
- */
-void QBoxLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *bottom) const
-{
- int l = leftMargin;
- int t = topMargin;
- int r = rightMargin;
- int b = bottomMargin;
-#ifdef Q_WS_MAC
- Q_Q(const QBoxLayout);
- if (horz(dir)) {
- QBoxLayoutItem *leftBox = 0;
- QBoxLayoutItem *rightBox = 0;
-
- if (left || right) {
- leftBox = list.value(0);
- rightBox = list.value(list.count() - 1);
- if (dir == QBoxLayout::RightToLeft)
- qSwap(leftBox, rightBox);
-
- int leftDelta = 0;
- int rightDelta = 0;
- if (leftBox) {
- QLayoutItem *itm = leftBox->item;
- if (QWidget *w = itm->widget())
- leftDelta = itm->geometry().left() - w->geometry().left();
- }
- if (rightBox) {
- QLayoutItem *itm = rightBox->item;
- if (QWidget *w = itm->widget())
- rightDelta = w->geometry().right() - itm->geometry().right();
- }
- QWidget *w = q->parentWidget();
- Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QApplication::layoutDirection();
- if (layoutDirection == Qt::RightToLeft)
- qSwap(leftDelta, rightDelta);
-
- l = qMax(l, leftDelta);
- r = qMax(r, rightDelta);
- }
-
- int count = top || bottom ? list.count() : 0;
- for (int i = 0; i < count; ++i) {
- QBoxLayoutItem *box = list.at(i);
- QLayoutItem *itm = box->item;
- QWidget *w = itm->widget();
- if (w) {
- QRect lir = itm->geometry();
- QRect wr = w->geometry();
- if (top)
- t = qMax(t, lir.top() - wr.top());
- if (bottom)
- b = qMax(b, wr.bottom() - lir.bottom());
- }
- }
- } else { // vertical layout
- QBoxLayoutItem *topBox = 0;
- QBoxLayoutItem *bottomBox = 0;
-
- if (top || bottom) {
- topBox = list.value(0);
- bottomBox = list.value(list.count() - 1);
- if (dir == QBoxLayout::BottomToTop) {
- qSwap(topBox, bottomBox);
- }
-
- if (top && topBox) {
- QLayoutItem *itm = topBox->item;
- QWidget *w = itm->widget();
- if (w)
- t = qMax(t, itm->geometry().top() - w->geometry().top());
- }
-
- if (bottom && bottomBox) {
- QLayoutItem *itm = bottomBox->item;
- QWidget *w = itm->widget();
- if (w)
- b = qMax(b, w->geometry().bottom() - itm->geometry().bottom());
- }
- }
-
- int count = left || right ? list.count() : 0;
- for (int i = 0; i < count; ++i) {
- QBoxLayoutItem *box = list.at(i);
- QLayoutItem *itm = box->item;
- QWidget *w = itm->widget();
- if (w) {
- QRect lir = itm->geometry();
- QRect wr = w->geometry();
- if (left)
- l = qMax(l, lir.left() - wr.left());
- if (right)
- r = qMax(r, wr.right() - lir.right());
- }
- }
- }
-#endif
- if (left)
- *left = l;
- if (top)
- *top = t;
- if (right)
- *right = r;
- if (bottom)
- *bottom = b;
-}
-
-
-/*
- Initializes the data structure needed by qGeomCalc and
- recalculates max/min and size hint.
-*/
-void QBoxLayoutPrivate::setupGeom()
-{
- if (!dirty)
- return;
-
- Q_Q(QBoxLayout);
- int maxw = horz(dir) ? 0 : QLAYOUTSIZE_MAX;
- int maxh = horz(dir) ? QLAYOUTSIZE_MAX : 0;
- int minw = 0;
- int minh = 0;
- int hintw = 0;
- int hinth = 0;
-
- bool horexp = false;
- bool verexp = false;
-
- hasHfw = false;
-
- int n = list.count();
- geomArray.clear();
- QVector<QLayoutStruct> a(n);
-
- QSizePolicy::ControlTypes controlTypes1;
- QSizePolicy::ControlTypes controlTypes2;
- int fixedSpacing = q->spacing();
- int previousNonEmptyIndex = -1;
-
- QStyle *style = 0;
- if (fixedSpacing < 0) {
- if (QWidget *parentWidget = q->parentWidget())
- style = parentWidget->style();
- }
-
- for (int i = 0; i < n; i++) {
- QBoxLayoutItem *box = list.at(i);
- QSize max = box->item->maximumSize();
- QSize min = box->item->minimumSize();
- QSize hint = box->item->sizeHint();
- Qt::Orientations exp = box->item->expandingDirections();
- bool empty = box->item->isEmpty();
- int spacing = 0;
-
- if (!empty) {
- if (fixedSpacing >= 0) {
- spacing = (previousNonEmptyIndex >= 0) ? fixedSpacing : 0;
-#ifdef Q_WS_MAC
- if (!horz(dir) && previousNonEmptyIndex >= 0) {
- QBoxLayoutItem *sibling = (dir == QBoxLayout::TopToBottom ? box : list.at(previousNonEmptyIndex));
- if (sibling) {
- QWidget *wid = sibling->item->widget();
- if (wid)
- spacing = qMax(spacing, sibling->item->geometry().top() - wid->geometry().top());
- }
- }
-#endif
- } else {
- controlTypes1 = controlTypes2;
- controlTypes2 = box->item->controlTypes();
- if (previousNonEmptyIndex >= 0) {
- QSizePolicy::ControlTypes actual1 = controlTypes1;
- QSizePolicy::ControlTypes actual2 = controlTypes2;
- if (dir == QBoxLayout::RightToLeft || dir == QBoxLayout::BottomToTop)
- qSwap(actual1, actual2);
-
- if (style) {
- spacing = style->combinedLayoutSpacing(actual1, actual2,
- horz(dir) ? Qt::Horizontal : Qt::Vertical,
- 0, q->parentWidget());
- if (spacing < 0)
- spacing = 0;
- }
- }
- }
-
- if (previousNonEmptyIndex >= 0)
- a[previousNonEmptyIndex].spacing = spacing;
- previousNonEmptyIndex = i;
- }
-
- bool ignore = empty && box->item->widget(); // ignore hidden widgets
- bool dummy = true;
- if (horz(dir)) {
- bool expand = (exp & Qt::Horizontal || box->stretch > 0);
- horexp = horexp || expand;
- maxw += spacing + max.width();
- minw += spacing + min.width();
- hintw += spacing + hint.width();
- if (!ignore)
- qMaxExpCalc(maxh, verexp, dummy,
- max.height(), exp & Qt::Vertical, box->item->isEmpty());
- minh = qMax(minh, min.height());
- hinth = qMax(hinth, hint.height());
-
- a[i].sizeHint = hint.width();
- a[i].maximumSize = max.width();
- a[i].minimumSize = min.width();
- a[i].expansive = expand;
- a[i].stretch = box->stretch ? box->stretch : box->hStretch();
- } else {
- bool expand = (exp & Qt::Vertical || box->stretch > 0);
- verexp = verexp || expand;
- maxh += spacing + max.height();
- minh += spacing + min.height();
- hinth += spacing + hint.height();
- if (!ignore)
- qMaxExpCalc(maxw, horexp, dummy,
- max.width(), exp & Qt::Horizontal, box->item->isEmpty());
- minw = qMax(minw, min.width());
- hintw = qMax(hintw, hint.width());
-
- a[i].sizeHint = hint.height();
- a[i].maximumSize = max.height();
- a[i].minimumSize = min.height();
- a[i].expansive = expand;
- a[i].stretch = box->stretch ? box->stretch : box->vStretch();
- }
-
- a[i].empty = empty;
- a[i].spacing = 0; // might be be initialized with a non-zero value in a later iteration
- hasHfw = hasHfw || box->item->hasHeightForWidth();
- }
-
- geomArray = a;
-
- expanding = (Qt::Orientations)
- ((horexp ? Qt::Horizontal : 0)
- | (verexp ? Qt::Vertical : 0));
-
- minSize = QSize(minw, minh);
- maxSize = QSize(maxw, maxh).expandedTo(minSize);
- sizeHint = QSize(hintw, hinth).expandedTo(minSize).boundedTo(maxSize);
-
- q->getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
- int left, top, right, bottom;
- effectiveMargins(&left, &top, &right, &bottom);
- QSize extra(left + right, top + bottom);
-
- minSize += extra;
- maxSize += extra;
- sizeHint += extra;
-
- dirty = false;
-}
-
-/*
- Calculates and stores the preferred height given the width \a w.
-*/
-void QBoxLayoutPrivate::calcHfw(int w)
-{
- QVector<QLayoutStruct> &a = geomArray;
- int n = a.count();
- int h = 0;
- int mh = 0;
-
- Q_ASSERT(n == list.size());
-
- if (horz(dir)) {
- qGeomCalc(a, 0, n, 0, w);
- for (int i = 0; i < n; i++) {
- QBoxLayoutItem *box = list.at(i);
- h = qMax(h, box->hfw(a.at(i).size));
- mh = qMax(mh, box->mhfw(a.at(i).size));
- }
- } else {
- for (int i = 0; i < n; ++i) {
- QBoxLayoutItem *box = list.at(i);
- int spacing = a.at(i).spacing;
- h += box->hfw(w);
- mh += box->mhfw(w);
- h += spacing;
- mh += spacing;
- }
- }
- hfwWidth = w;
- hfwHeight = h;
- hfwMinHeight = mh;
-}
-
-
-/*!
- \class QBoxLayout
-
- \brief The QBoxLayout class lines up child widgets horizontally or
- vertically.
-
- \ingroup geomanagement
-
- QBoxLayout takes the space it gets (from its parent layout or from
- the parentWidget()), divides it up into a row of boxes, and makes
- each managed widget fill one box.
-
- \image qhboxlayout-with-5-children.png Horizontal box layout with five child widgets
-
- If the QBoxLayout's orientation is Qt::Horizontal the boxes are
- placed in a row, with suitable sizes. Each widget (or other box)
- will get at least its minimum size and at most its maximum size.
- Any excess space is shared according to the stretch factors (more
- about that below).
-
- \image qvboxlayout-with-5-children.png Vertical box layout with five child widgets
-
- If the QBoxLayout's orientation is Qt::Vertical, the boxes are
- placed in a column, again with suitable sizes.
-
- The easiest way to create a QBoxLayout is to use one of the
- convenience classes, e.g. QHBoxLayout (for Qt::Horizontal boxes)
- or QVBoxLayout (for Qt::Vertical boxes). You can also use the
- QBoxLayout constructor directly, specifying its direction as
- LeftToRight, RightToLeft, TopToBottom, or BottomToTop.
-
- If the QBoxLayout is not the top-level layout (i.e. it is not
- managing all of the widget's area and children), you must add it
- to its parent layout before you can do anything with it. The
- normal way to add a layout is by calling
- parentLayout-\>addLayout().
-
- Once you have done this, you can add boxes to the QBoxLayout using
- one of four functions:
-
- \list
- \o addWidget() to add a widget to the QBoxLayout and set the
- widget's stretch factor. (The stretch factor is along the row of
- boxes.)
-
- \o addSpacing() to create an empty box; this is one of the
- functions you use to create nice and spacious dialogs. See below
- for ways to set margins.
-
- \o addStretch() to create an empty, stretchable box.
-
- \o addLayout() to add a box containing another QLayout to the row
- and set that layout's stretch factor.
- \endlist
-
- Use insertWidget(), insertSpacing(), insertStretch() or
- insertLayout() to insert a box at a specified position in the
- layout.
-
- QBoxLayout also includes two margin widths:
-
- \list
- \o setContentsMargins() sets the width of the outer border on
- each side of the widget. This is the width of the reserved space
- along each of the QBoxLayout's four sides.
- \o setSpacing() sets the width between neighboring boxes. (You
- can use addSpacing() to get more space at a particular spot.)
- \endlist
-
- The margin default is provided by the style. The default margin
- most Qt styles specify is 9 for child widgets and 11 for windows.
- The spacing defaults to the same as the margin width for a
- top-level layout, or to the same as the parent layout.
-
- To remove a widget from a layout, call removeWidget(). Calling
- QWidget::hide() on a widget also effectively removes the widget
- from the layout until QWidget::show() is called.
-
- You will almost always want to use QVBoxLayout and QHBoxLayout
- rather than QBoxLayout because of their convenient constructors.
-
- \sa QGridLayout, QStackedLayout, {Layout Management}
-*/
-
-/*!
- \enum QBoxLayout::Direction
-
- This type is used to determine the direction of a box layout.
-
- \value LeftToRight Horizontal from left to right.
- \value RightToLeft Horizontal from right to left.
- \value TopToBottom Vertical from top to bottom.
- \value BottomToTop Vertical from bottom to top.
-
- \omitvalue Down
- \omitvalue Up
-*/
-
-/*!
- Constructs a new QBoxLayout with direction \a dir and parent widget \a
- parent.
-
- \sa direction()
-*/
-QBoxLayout::QBoxLayout(Direction dir, QWidget *parent)
- : QLayout(*new QBoxLayoutPrivate, 0, parent)
-{
- Q_D(QBoxLayout);
- d->dir = dir;
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a new QBoxLayout with direction \a dir and main widget \a
- parent. \a parent may not be 0.
-
- The \a margin is the number of pixels between the edge of the
- widget and its managed children. The \a spacing is the default
- number of pixels between neighboring children. If \a spacing is -1
- the value of \a margin is used for \a spacing.
-
- \a name is the internal object name.
-
- \sa direction()
-*/
-QBoxLayout::QBoxLayout(QWidget *parent, Direction dir,
- int margin, int spacing, const char *name)
- : QLayout(*new QBoxLayoutPrivate, 0, parent)
-{
- Q_D(QBoxLayout);
- d->dir = dir;
- setMargin(margin);
- setObjectName(QString::fromAscii(name));
- setSpacing(spacing<0 ? margin : spacing);
-}
-
-/*!
- Constructs a new QBoxLayout called \a name, with direction \a dir,
- and inserts it into \a parentLayout.
-
- The \a spacing is the default number of pixels between neighboring
- children. If \a spacing is -1, the layout will inherit its
- parent's spacing().
-*/
-QBoxLayout::QBoxLayout(QLayout *parentLayout, Direction dir, int spacing,
- const char *name)
- : QLayout(*new QBoxLayoutPrivate, parentLayout, 0)
-{
- Q_D(QBoxLayout);
- d->dir = dir;
- setObjectName(QString::fromAscii(name));
- setSpacing(spacing);
-}
-
-/*!
- Constructs a new QBoxLayout called \a name, with direction \a dir.
-
- If \a spacing is -1, the layout will inherit its parent's
- spacing(); otherwise \a spacing is used.
-
- You must insert this box into another layout.
-*/
-QBoxLayout::QBoxLayout(Direction dir, int spacing, const char *name)
- : QLayout(*new QBoxLayoutPrivate,0, 0)
-{
- Q_D(QBoxLayout);
- d->dir = dir;
- setObjectName(QString::fromAscii(name));
- setSpacing(spacing);
-}
-#endif // QT3_SUPPORT
-
-
-/*!
- Destroys this box layout.
-
- The layout's widgets aren't destroyed.
-*/
-QBoxLayout::~QBoxLayout()
-{
- Q_D(QBoxLayout);
- d->deleteAll(); // must do it before QObject deletes children, so can't be in ~QBoxLayoutPrivate
-}
-
-/*!
- Reimplements QLayout::spacing(). If the spacing property is
- valid, that value is returned. Otherwise, a value for the spacing
- property is computed and returned. Since layout spacing in a widget
- is style dependent, if the parent is a widget, it queries the style
- for the (horizontal or vertical) spacing of the layout. Otherwise,
- the parent is a layout, and it queries the parent layout for the
- spacing().
-
- \sa QLayout::spacing(), setSpacing()
- */
-int QBoxLayout::spacing() const
-{
- Q_D(const QBoxLayout);
- if (d->spacing >=0) {
- return d->spacing;
- } else {
- return qSmartSpacing(this, d->dir == LeftToRight || d->dir == RightToLeft
- ? QStyle::PM_LayoutHorizontalSpacing
- : QStyle::PM_LayoutVerticalSpacing);
- }
-}
-
-/*!
- Reimplements QLayout::setSpacing(). Sets the spacing
- property to \a spacing.
-
- \sa QLayout::setSpacing(), spacing()
- */
-void QBoxLayout::setSpacing(int spacing)
-{
- Q_D(QBoxLayout);
- d->spacing = spacing;
- invalidate();
-}
-
-/*!
- \reimp
-*/
-QSize QBoxLayout::sizeHint() const
-{
- Q_D(const QBoxLayout);
- if (d->dirty)
- const_cast<QBoxLayout*>(this)->d_func()->setupGeom();
- return d->sizeHint;
-}
-
-/*!
- \reimp
-*/
-QSize QBoxLayout::minimumSize() const
-{
- Q_D(const QBoxLayout);
- if (d->dirty)
- const_cast<QBoxLayout*>(this)->d_func()->setupGeom();
- return d->minSize;
-}
-
-/*!
- \reimp
-*/
-QSize QBoxLayout::maximumSize() const
-{
- Q_D(const QBoxLayout);
- if (d->dirty)
- const_cast<QBoxLayout*>(this)->d_func()->setupGeom();
-
- QSize s = d->maxSize.boundedTo(QSize(QLAYOUTSIZE_MAX, QLAYOUTSIZE_MAX));
-
- if (alignment() & Qt::AlignHorizontal_Mask)
- s.setWidth(QLAYOUTSIZE_MAX);
- if (alignment() & Qt::AlignVertical_Mask)
- s.setHeight(QLAYOUTSIZE_MAX);
- return s;
-}
-
-/*!
- \reimp
-*/
-bool QBoxLayout::hasHeightForWidth() const
-{
- Q_D(const QBoxLayout);
- if (d->dirty)
- const_cast<QBoxLayout*>(this)->d_func()->setupGeom();
- return d->hasHfw;
-}
-
-/*!
- \reimp
-*/
-int QBoxLayout::heightForWidth(int w) const
-{
- Q_D(const QBoxLayout);
- if (!hasHeightForWidth())
- return -1;
-
- int left, top, right, bottom;
- d->effectiveMargins(&left, &top, &right, &bottom);
-
- w -= left + right;
- if (w != d->hfwWidth)
- const_cast<QBoxLayout*>(this)->d_func()->calcHfw(w);
-
- return d->hfwHeight + top + bottom;
-}
-
-/*!
- \reimp
-*/
-int QBoxLayout::minimumHeightForWidth(int w) const
-{
- Q_D(const QBoxLayout);
- (void) heightForWidth(w);
- int top, bottom;
- d->effectiveMargins(0, &top, 0, &bottom);
- return d->hasHfw ? (d->hfwMinHeight + top + bottom) : -1;
-}
-
-/*!
- Resets cached information.
-*/
-void QBoxLayout::invalidate()
-{
- Q_D(QBoxLayout);
- d->setDirty();
- QLayout::invalidate();
-}
-
-/*!
- \reimp
-*/
-int QBoxLayout::count() const
-{
- Q_D(const QBoxLayout);
- return d->list.count();
-}
-
-/*!
- \reimp
-*/
-QLayoutItem *QBoxLayout::itemAt(int index) const
-{
- Q_D(const QBoxLayout);
- return index >= 0 && index < d->list.count() ? d->list.at(index)->item : 0;
-}
-
-/*!
- \reimp
-*/
-QLayoutItem *QBoxLayout::takeAt(int index)
-{
- Q_D(QBoxLayout);
- if (index < 0 || index >= d->list.count())
- return 0;
- QBoxLayoutItem *b = d->list.takeAt(index);
- QLayoutItem *item = b->item;
- b->item = 0;
- delete b;
-
- invalidate();
- return item;
-}
-
-
-/*!
- \reimp
-*/
-Qt::Orientations QBoxLayout::expandingDirections() const
-{
- Q_D(const QBoxLayout);
- if (d->dirty)
- const_cast<QBoxLayout*>(this)->d_func()->setupGeom();
- return d->expanding;
-}
-
-/*!
- \reimp
-*/
-void QBoxLayout::setGeometry(const QRect &r)
-{
- Q_D(QBoxLayout);
- if (d->dirty || r != geometry()) {
- QRect oldRect = geometry();
- QLayout::setGeometry(r);
- if (d->dirty)
- d->setupGeom();
- QRect cr = alignment() ? alignmentRect(r) : r;
-
- int left, top, right, bottom;
- d->effectiveMargins(&left, &top, &right, &bottom);
- QRect s(cr.x() + left, cr.y() + top,
- cr.width() - (left + right),
- cr.height() - (top + bottom));
-
- QVector<QLayoutStruct> a = d->geomArray;
- int pos = horz(d->dir) ? s.x() : s.y();
- int space = horz(d->dir) ? s.width() : s.height();
- int n = a.count();
- if (d->hasHfw && !horz(d->dir)) {
- for (int i = 0; i < n; i++) {
- QBoxLayoutItem *box = d->list.at(i);
- if (box->item->hasHeightForWidth()) {
- int width = qBound(box->item->minimumSize().width(), s.width(), box->item->maximumSize().width());
- a[i].sizeHint = a[i].minimumSize =
- box->item->heightForWidth(width);
- }
- }
- }
-
- Direction visualDir = d->dir;
- QWidget *parent = parentWidget();
- if (parent && parent->isRightToLeft()) {
- if (d->dir == LeftToRight)
- visualDir = RightToLeft;
- else if (d->dir == RightToLeft)
- visualDir = LeftToRight;
- }
-
- qGeomCalc(a, 0, n, pos, space);
-
- bool reverse = (horz(visualDir)
- ? ((r.right() > oldRect.right()) != (visualDir == RightToLeft))
- : r.bottom() > oldRect.bottom());
- for (int j = 0; j < n; j++) {
- int i = reverse ? n-j-1 : j;
- QBoxLayoutItem *box = d->list.at(i);
-
- switch (visualDir) {
- case LeftToRight:
- box->item->setGeometry(QRect(a.at(i).pos, s.y(), a.at(i).size, s.height()));
- break;
- case RightToLeft:
- box->item->setGeometry(QRect(s.left() + s.right() - a.at(i).pos - a.at(i).size + 1,
- s.y(), a.at(i).size, s.height()));
- break;
- case TopToBottom:
- box->item->setGeometry(QRect(s.x(), a.at(i).pos, s.width(), a.at(i).size));
- break;
- case BottomToTop:
- box->item->setGeometry(QRect(s.x(),
- s.top() + s.bottom() - a.at(i).pos - a.at(i).size + 1,
- s.width(), a.at(i).size));
- }
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QBoxLayout::addItem(QLayoutItem *item)
-{
- Q_D(QBoxLayout);
- QBoxLayoutItem *it = new QBoxLayoutItem(item);
- d->list.append(it);
- invalidate();
-}
-
-/*!
- Inserts \a item into this box layout at position \a index. If \a
- index is negative, the item is added at the end.
-
- \sa addItem(), insertWidget(), insertLayout(), insertStretch(),
- insertSpacing()
-*/
-void QBoxLayout::insertItem(int index, QLayoutItem *item)
-{
- Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
- QBoxLayoutItem *it = new QBoxLayoutItem(item);
- d->list.insert(index, it);
- invalidate();
-}
-
-/*!
- Inserts a non-stretchable space (a QSpacerItem) at position \a index, with
- size \a size. If \a index is negative the space is added at the end.
-
- The box layout has default margin and spacing. This function adds
- additional space.
-
- \sa addSpacing(), insertItem(), QSpacerItem
-*/
-void QBoxLayout::insertSpacing(int index, int size)
-{
- Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
- QLayoutItem *b;
- if (horz(d->dir))
- b = QLayoutPrivate::createSpacerItem(this, size, 0, QSizePolicy::Fixed, QSizePolicy::Minimum);
- else
- b = QLayoutPrivate::createSpacerItem(this, 0, size, QSizePolicy::Minimum, QSizePolicy::Fixed);
-
- QT_TRY {
- QBoxLayoutItem *it = new QBoxLayoutItem(b);
- it->magic = true;
- d->list.insert(index, it);
-
- } QT_CATCH(...) {
- delete b;
- QT_RETHROW;
- }
- invalidate();
-}
-
-/*!
- Inserts a stretchable space (a QSpacerItem) at position \a
- index, with zero minimum size and stretch factor \a stretch. If \a
- index is negative the space is added at the end.
-
- \sa addStretch(), insertItem(), QSpacerItem
-*/
-void QBoxLayout::insertStretch(int index, int stretch)
-{
- Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
- QLayoutItem *b;
- if (horz(d->dir))
- b = QLayoutPrivate::createSpacerItem(this, 0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
- else
- b = QLayoutPrivate::createSpacerItem(this, 0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
-
- QBoxLayoutItem *it = new QBoxLayoutItem(b, stretch);
- it->magic = true;
- d->list.insert(index, it);
- invalidate();
-}
-
-/*!
- \since 4.4
-
- Inserts \a spacerItem at position \a index, with zero minimum
- size and stretch factor. If \a index is negative the
- space is added at the end.
-
- \sa addSpacerItem(), insertStretch(), insertSpacing()
-*/
-void QBoxLayout::insertSpacerItem(int index, QSpacerItem *spacerItem)
-{
- Q_D(QBoxLayout);
- if (index < 0) // append
- index = d->list.count();
-
- QBoxLayoutItem *it = new QBoxLayoutItem(spacerItem);
- it->magic = true;
- d->list.insert(index, it);
- invalidate();
-}
-
-/*!
- Inserts \a layout at position \a index, with stretch factor \a
- stretch. If \a index is negative, the layout is added at the end.
-
- \a layout becomes a child of the box layout.
-
- \sa addLayout(), insertItem()
-*/
-void QBoxLayout::insertLayout(int index, QLayout *layout, int stretch)
-{
- Q_D(QBoxLayout);
- addChildLayout(layout);
- if (index < 0) // append
- index = d->list.count();
- QBoxLayoutItem *it = new QBoxLayoutItem(layout, stretch);
- d->list.insert(index, it);
- invalidate();
-}
-
-/*!
- Inserts \a widget at position \a index, with stretch factor \a
- stretch and alignment \a alignment. If \a index is negative, the
- widget is added at the end.
-
- The stretch factor applies only in the \l{direction()}{direction}
- of the QBoxLayout, and is relative to the other boxes and widgets
- in this QBoxLayout. Widgets and boxes with higher stretch factors
- grow more.
-
- If the stretch factor is 0 and nothing else in the QBoxLayout has
- a stretch factor greater than zero, the space is distributed
- according to the QWidget:sizePolicy() of each widget that's
- involved.
-
- The alignment is specified by \a alignment. The default alignment
- is 0, which means that the widget fills the entire cell.
-
- \sa addWidget(), insertItem()
-*/
-void QBoxLayout::insertWidget(int index, QWidget *widget, int stretch,
- Qt::Alignment alignment)
-{
- Q_D(QBoxLayout);
- if (!checkWidget(this, widget))
- return;
- addChildWidget(widget);
- if (index < 0) // append
- index = d->list.count();
- QWidgetItem *b = QLayoutPrivate::createWidgetItem(this, widget);
- b->setAlignment(alignment);
-
- QBoxLayoutItem *it;
- QT_TRY{
- it = new QBoxLayoutItem(b, stretch);
- } QT_CATCH(...) {
- delete b;
- QT_RETHROW;
- }
-
- QT_TRY{
- d->list.insert(index, it);
- } QT_CATCH(...) {
- delete it;
- QT_RETHROW;
- }
- invalidate();
-}
-
-/*!
- Adds a non-stretchable space (a QSpacerItem) with size \a size
- to the end of this box layout. QBoxLayout provides default margin
- and spacing. This function adds additional space.
-
- \sa insertSpacing(), addItem(), QSpacerItem
-*/
-void QBoxLayout::addSpacing(int size)
-{
- insertSpacing(-1, size);
-}
-
-/*!
- Adds a stretchable space (a QSpacerItem) with zero minimum
- size and stretch factor \a stretch to the end of this box layout.
-
- \sa insertStretch(), addItem(), QSpacerItem
-*/
-void QBoxLayout::addStretch(int stretch)
-{
- insertStretch(-1, stretch);
-}
-
-/*!
- \since 4.4
-
- Adds \a spacerItem to the end of this box layout.
-
- \sa addSpacing(), addStretch()
-*/
-void QBoxLayout::addSpacerItem(QSpacerItem *spacerItem)
-{
- insertSpacerItem(-1, spacerItem);
-}
-
-/*!
- Adds \a widget to the end of this box layout, with a stretch
- factor of \a stretch and alignment \a alignment.
-
- The stretch factor applies only in the \l{direction()}{direction}
- of the QBoxLayout, and is relative to the other boxes and widgets
- in this QBoxLayout. Widgets and boxes with higher stretch factors
- grow more.
-
- If the stretch factor is 0 and nothing else in the QBoxLayout has
- a stretch factor greater than zero, the space is distributed
- according to the QWidget:sizePolicy() of each widget that's
- involved.
-
- The alignment is specified by \a alignment. The default
- alignment is 0, which means that the widget fills the entire cell.
-
- \sa insertWidget(), addItem(), addLayout(), addStretch(),
- addSpacing(), addStrut()
-*/
-void QBoxLayout::addWidget(QWidget *widget, int stretch, Qt::Alignment alignment)
-{
- insertWidget(-1, widget, stretch, alignment);
-}
-
-/*!
- Adds \a layout to the end of the box, with serial stretch factor
- \a stretch.
-
- \sa insertLayout(), addItem(), addWidget()
-*/
-void QBoxLayout::addLayout(QLayout *layout, int stretch)
-{
- insertLayout(-1, layout, stretch);
-}
-
-/*!
- Limits the perpendicular dimension of the box (e.g. height if the
- box is \l LeftToRight) to a minimum of \a size. Other constraints
- may increase the limit.
-
- \sa addItem()
-*/
-void QBoxLayout::addStrut(int size)
-{
- Q_D(QBoxLayout);
- QLayoutItem *b;
- if (horz(d->dir))
- b = QLayoutPrivate::createSpacerItem(this, 0, size, QSizePolicy::Fixed, QSizePolicy::Minimum);
- else
- b = QLayoutPrivate::createSpacerItem(this, size, 0, QSizePolicy::Minimum, QSizePolicy::Fixed);
-
- QBoxLayoutItem *it = new QBoxLayoutItem(b);
- it->magic = true;
- d->list.append(it);
- invalidate();
-}
-
-/*!
- \fn int QBoxLayout::findWidget(QWidget *widget)
-
- Use indexOf(\a widget) instead.
-*/
-
-/*!
- Sets the stretch factor for \a widget to \a stretch and returns
- true if \a widget is found in this layout (not including child
- layouts); otherwise returns false.
-
- \sa setAlignment()
-*/
-bool QBoxLayout::setStretchFactor(QWidget *widget, int stretch)
-{
- Q_D(QBoxLayout);
- if (!widget)
- return false;
- for (int i = 0; i < d->list.size(); ++i) {
- QBoxLayoutItem *box = d->list.at(i);
- if (box->item->widget() == widget) {
- box->stretch = stretch;
- invalidate();
- return true;
- }
- }
- return false;
-}
-
-/*!
- \overload
-
- Sets the stretch factor for the layout \a layout to \a stretch and
- returns true if \a layout is found in this layout (not including
- child layouts); otherwise returns false.
-*/
-bool QBoxLayout::setStretchFactor(QLayout *layout, int stretch)
-{
- Q_D(QBoxLayout);
- for (int i = 0; i < d->list.size(); ++i) {
- QBoxLayoutItem *box = d->list.at(i);
- if (box->item->layout() == layout) {
- if (box->stretch != stretch) {
- box->stretch = stretch;
- invalidate();
- }
- return true;
- }
- }
- return false;
-}
-
-/*!
- Sets the stretch factor at position \a index. to \a stretch.
-
- \since 4.5
-*/
-
-void QBoxLayout::setStretch(int index, int stretch)
-{
- Q_D(QBoxLayout);
- if (index >= 0 && index < d->list.size()) {
- QBoxLayoutItem *box = d->list.at(index);
- if (box->stretch != stretch) {
- box->stretch = stretch;
- invalidate();
- }
- }
-}
-
-/*!
- Returns the stretch factor at position \a index.
-
- \since 4.5
-*/
-
-int QBoxLayout::stretch(int index) const
-{
- Q_D(const QBoxLayout);
- if (index >= 0 && index < d->list.size())
- return d->list.at(index)->stretch;
- return -1;
-}
-
-/*!
- Sets the direction of this layout to \a direction.
-*/
-void QBoxLayout::setDirection(Direction direction)
-{
- Q_D(QBoxLayout);
- if (d->dir == direction)
- return;
- if (horz(d->dir) != horz(direction)) {
- //swap around the spacers (the "magic" bits)
- //#### a bit yucky, knows too much.
- //#### probably best to add access functions to spacerItem
- //#### or even a QSpacerItem::flip()
- for (int i = 0; i < d->list.size(); ++i) {
- QBoxLayoutItem *box = d->list.at(i);
- if (box->magic) {
- QSpacerItem *sp = box->item->spacerItem();
- if (sp) {
- if (sp->expandingDirections() == Qt::Orientations(0) /*No Direction*/) {
- //spacing or strut
- QSize s = sp->sizeHint();
- sp->changeSize(s.height(), s.width(),
- horz(direction) ? QSizePolicy::Fixed:QSizePolicy::Minimum,
- horz(direction) ? QSizePolicy::Minimum:QSizePolicy::Fixed);
-
- } else {
- //stretch
- if (horz(direction))
- sp->changeSize(0, 0, QSizePolicy::Expanding,
- QSizePolicy::Minimum);
- else
- sp->changeSize(0, 0, QSizePolicy::Minimum,
- QSizePolicy::Expanding);
- }
- }
- }
- }
- }
- d->dir = direction;
- invalidate();
-}
-
-/*!
- \fn QBoxLayout::Direction QBoxLayout::direction() const
-
- Returns the direction of the box. addWidget() and addSpacing()
- work in this direction; the stretch stretches in this direction.
-
- \sa QBoxLayout::Direction addWidget() addSpacing()
-*/
-
-QBoxLayout::Direction QBoxLayout::direction() const
-{
- Q_D(const QBoxLayout);
- return d->dir;
-}
-
-/*!
- \class QHBoxLayout
- \brief The QHBoxLayout class lines up widgets horizontally.
-
- \ingroup geomanagement
-
- This class is used to construct horizontal box layout objects. See
- QBoxLayout for details.
-
- The simplest use of the class is like this:
-
- \snippet doc/src/snippets/layouts/layouts.cpp 0
- \snippet doc/src/snippets/layouts/layouts.cpp 1
- \snippet doc/src/snippets/layouts/layouts.cpp 2
- \codeline
- \snippet doc/src/snippets/layouts/layouts.cpp 3
- \snippet doc/src/snippets/layouts/layouts.cpp 4
- \snippet doc/src/snippets/layouts/layouts.cpp 5
-
- First, we create the widgets we want in the layout. Then, we
- create the QHBoxLayout object and add the widgets into the
- layout. Finally, we call QWidget::setLayout() to install the
- QHBoxLayout object onto the widget. At that point, the widgets in
- the layout are reparented to have \c window as their parent.
-
- \image qhboxlayout-with-5-children.png Horizontal box layout with five child widgets
-
- \sa QVBoxLayout, QGridLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example}
-*/
-
-
-/*!
- Constructs a new top-level horizontal box with
- parent \a parent.
-*/
-QHBoxLayout::QHBoxLayout(QWidget *parent)
- : QBoxLayout(LeftToRight, parent)
-{
-}
-
-/*!
- Constructs a new horizontal box. You must add
- it to another layout.
-*/
-QHBoxLayout::QHBoxLayout()
- : QBoxLayout(LeftToRight)
-{
-}
-
-
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a new top-level horizontal box called \a name, with
- parent \a parent.
-
- The \a margin is the number of pixels between the edge of the
- widget and its managed children. The \a spacing is the default
- number of pixels between neighboring children. If \a spacing is -1
- the value of \a margin is used for \a spacing.
-*/
-QHBoxLayout::QHBoxLayout(QWidget *parent, int margin,
- int spacing, const char *name)
- : QBoxLayout(LeftToRight, parent)
-{
- setMargin(margin);
- setSpacing(spacing<0 ? margin : spacing);
- setObjectName(QString::fromAscii(name));
-}
-
-/*!
- Constructs a new horizontal box called name \a name and adds it to
- \a parentLayout.
-
- The \a spacing is the default number of pixels between neighboring
- children. If \a spacing is -1, this QHBoxLayout will inherit its
- parent's spacing().
-*/
-QHBoxLayout::QHBoxLayout(QLayout *parentLayout, int spacing,
- const char *name)
- : QBoxLayout(LeftToRight)
-{
- setSpacing(spacing);
- setObjectName(QString::fromAscii(name));
- if (parentLayout) {
- setParent(parentLayout);
- parentLayout->addItem(this);
- }
-}
-
-/*!
- Constructs a new horizontal box called name \a name. You must add
- it to another layout.
-
- The \a spacing is the default number of pixels between neighboring
- children. If \a spacing is -1, this QHBoxLayout will inherit its
- parent's spacing().
-*/
-QHBoxLayout::QHBoxLayout(int spacing, const char *name)
- : QBoxLayout(LeftToRight)
-{
- setSpacing(spacing);
- setObjectName(QString::fromAscii(name));
-}
-#endif
-
-
-/*!
- Destroys this box layout.
-
- The layout's widgets aren't destroyed.
-*/
-QHBoxLayout::~QHBoxLayout()
-{
-}
-
-/*!
- \class QVBoxLayout
- \brief The QVBoxLayout class lines up widgets vertically.
-
- \ingroup geomanagement
-
- This class is used to construct vertical box layout objects. See
- QBoxLayout for details.
-
- The simplest use of the class is like this:
-
- \snippet doc/src/snippets/layouts/layouts.cpp 6
- \snippet doc/src/snippets/layouts/layouts.cpp 7
- \snippet doc/src/snippets/layouts/layouts.cpp 8
- \codeline
- \snippet doc/src/snippets/layouts/layouts.cpp 9
- \snippet doc/src/snippets/layouts/layouts.cpp 10
- \snippet doc/src/snippets/layouts/layouts.cpp 11
-
- First, we create the widgets we want in the layout. Then, we
- create the QVBoxLayout object and add the widgets into the
- layout. Finally, we call QWidget::setLayout() to install the
- QVBoxLayout object onto the widget. At that point, the widgets in
- the layout are reparented to have \c window as their parent.
-
- \image qvboxlayout-with-5-children.png Horizontal box layout with five child widgets
-
- \sa QHBoxLayout, QGridLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example}
-*/
-
-/*!
- Constructs a new top-level vertical box with
- parent \a parent.
-*/
-QVBoxLayout::QVBoxLayout(QWidget *parent)
- : QBoxLayout(TopToBottom, parent)
-{
-}
-
-/*!
- Constructs a new vertical box. You must add
- it to another layout.
-
-*/
-QVBoxLayout::QVBoxLayout()
- : QBoxLayout(TopToBottom)
-{
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a new top-level vertical box called \a name, with
- parent \a parent.
-
- The \a margin is the number of pixels between the edge of the
- widget and its managed children. The \a spacing is the default
- number of pixels between neighboring children. If \a spacing is -1
- the value of \a margin is used for \a spacing.
-*/
-QVBoxLayout::QVBoxLayout(QWidget *parent, int margin, int spacing,
- const char *name)
- : QBoxLayout(TopToBottom, parent)
-{
- setMargin(margin);
- setSpacing(spacing<0 ? margin : spacing);
- setObjectName(QString::fromAscii(name));
-}
-
-/*!
- Constructs a new vertical box called name \a name and adds it to
- \a parentLayout.
-
- The \a spacing is the default number of pixels between neighboring
- children. If \a spacing is -1, this QVBoxLayout will inherit its
- parent's spacing().
-*/
-QVBoxLayout::QVBoxLayout(QLayout *parentLayout, int spacing,
- const char *name)
- : QBoxLayout(TopToBottom)
-{
- setSpacing(spacing);
- setObjectName(QString::fromAscii(name));
- if (parentLayout) {
- setParent(parentLayout);
- parentLayout->addItem(this);
- }
-}
-
-/*!
- Constructs a new vertical box called name \a name. You must add
- it to another layout.
-
- The \a spacing is the default number of pixels between neighboring
- children. If \a spacing is -1, this QVBoxLayout will inherit its
- parent's spacing().
-*/
-QVBoxLayout::QVBoxLayout(int spacing, const char *name)
- : QBoxLayout(TopToBottom)
-{
- setSpacing(spacing);
- setObjectName(QString::fromAscii(name));
-}
-
-
-#endif
-
-/*!
- Destroys this box layout.
-
- The layout's widgets aren't destroyed.
-*/
-QVBoxLayout::~QVBoxLayout()
-{
-}
-
-/*!
- \fn QWidget *QLayout::mainWidget() const
-
- Use parentWidget() instead.
-*/
-
-/*!
- \fn void QLayout::remove(QWidget *widget)
-
- Use removeWidget(\a widget) instead.
-*/
-
-/*!
- \fn void QLayout::add(QWidget *widget)
-
- Use addWidget(\a widget) instead.
-*/
-
-/*!
- \fn QLayoutIterator QLayout::iterator()
-
- Use a QLayoutIterator() constructor instead.
-*/
-
-/*!
- \fn int QLayout::defaultBorder() const
-
- Use spacing() instead.
-*/
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qboxlayout.h b/src/gui/kernel/qboxlayout.h
deleted file mode 100644
index 66ce23a9f5..0000000000
--- a/src/gui/kernel/qboxlayout.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/****************************************************************************
-**
-** 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 QBOXLAYOUT_H
-#define QBOXLAYOUT_H
-
-#include <QtGui/qlayout.h>
-#ifdef QT_INCLUDE_COMPAT
-#include <QtGui/qwidget.h>
-#endif
-
-#include <limits.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QBoxLayoutPrivate;
-
-class Q_GUI_EXPORT QBoxLayout : public QLayout
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QBoxLayout)
-public:
- enum Direction { LeftToRight, RightToLeft, TopToBottom, BottomToTop,
- Down = TopToBottom, Up = BottomToTop };
-
- explicit QBoxLayout(Direction, QWidget *parent = 0);
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QBoxLayout(QWidget *parent, Direction, int border = 0, int spacing = -1,
- const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QBoxLayout(QLayout *parentLayout, Direction, int spacing = -1,
- const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QBoxLayout(Direction, int spacing, const char *name = 0);
-#endif
- ~QBoxLayout();
-
- Direction direction() const;
- void setDirection(Direction);
-
- void addSpacing(int size);
- void addStretch(int stretch = 0);
- void addSpacerItem(QSpacerItem *spacerItem);
- void addWidget(QWidget *, int stretch = 0, Qt::Alignment alignment = 0);
- void addLayout(QLayout *layout, int stretch = 0);
- void addStrut(int);
- void addItem(QLayoutItem *);
-
- void insertSpacing(int index, int size);
- void insertStretch(int index, int stretch = 0);
- void insertSpacerItem(int index, QSpacerItem *spacerItem);
- void insertWidget(int index, QWidget *widget, int stretch = 0, Qt::Alignment alignment = 0);
- void insertLayout(int index, QLayout *layout, int stretch = 0);
-
- int spacing() const;
- void setSpacing(int spacing);
-
- bool setStretchFactor(QWidget *w, int stretch);
- bool setStretchFactor(QLayout *l, int stretch);
- void setStretch(int index, int stretch);
- int stretch(int index) const;
-
- QSize sizeHint() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
-
- bool hasHeightForWidth() const;
- int heightForWidth(int) const;
- int minimumHeightForWidth(int) const;
-
- Qt::Orientations expandingDirections() const;
- void invalidate();
- QLayoutItem *itemAt(int) const;
- QLayoutItem *takeAt(int);
- int count() const;
- void setGeometry(const QRect&);
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT int findWidget(QWidget* w) {return indexOf(w);}
-#endif
-protected:
- // ### Qt 5: make public
- void insertItem(int index, QLayoutItem *);
-
-private:
- Q_DISABLE_COPY(QBoxLayout)
-};
-
-class Q_GUI_EXPORT QHBoxLayout : public QBoxLayout
-{
- Q_OBJECT
-public:
- QHBoxLayout();
- explicit QHBoxLayout(QWidget *parent);
- ~QHBoxLayout();
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QHBoxLayout(QWidget *parent, int border,
- int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QHBoxLayout(QLayout *parentLayout,
- int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QHBoxLayout(int spacing, const char *name = 0);
-#endif
-
-private:
- Q_DISABLE_COPY(QHBoxLayout)
-};
-
-class Q_GUI_EXPORT QVBoxLayout : public QBoxLayout
-{
- Q_OBJECT
-public:
- QVBoxLayout();
- explicit QVBoxLayout(QWidget *parent);
- ~QVBoxLayout();
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QVBoxLayout(QWidget *parent, int border,
- int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QVBoxLayout(QLayout *parentLayout,
- int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QVBoxLayout(int spacing, const char *name = 0);
-#endif
-
-private:
- Q_DISABLE_COPY(QVBoxLayout)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QBOXLAYOUT_H
diff --git a/src/gui/kernel/qdesktopwidget.cpp b/src/gui/kernel/qdesktopwidget.cpp
deleted file mode 100644
index 6e1414dc5d..0000000000
--- a/src/gui/kernel/qdesktopwidget.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdesktopwidget.h"
-#include "qwidget_p.h"
-
-QT_BEGIN_NAMESPACE
-
-const QRect QDesktopWidget::screenGeometry(const QWidget *widget) const
-{
- if (!widget) {
- qWarning("QDesktopWidget::screenGeometry(): Attempt "
- "to get the screen geometry of a null widget");
- return QRect();
- }
- QRect rect = QWidgetPrivate::screenGeometry(widget);
- if (rect.isNull())
- return screenGeometry(screenNumber(widget));
- else return rect;
-}
-
-const QRect QDesktopWidget::availableGeometry(const QWidget *widget) const
-{
- if (!widget) {
- qWarning("QDesktopWidget::availableGeometry(): Attempt "
- "to get the available geometry of a null widget");
- return QRect();
- }
- QRect rect = QWidgetPrivate::screenGeometry(widget);
- if (rect.isNull())
- return availableGeometry(screenNumber(widget));
- else
- return rect;
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/gui/kernel/qdesktopwidget.h b/src/gui/kernel/qdesktopwidget.h
deleted file mode 100644
index deb896029a..0000000000
--- a/src/gui/kernel/qdesktopwidget.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** 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 QDESKTOPWIDGET_H
-#define QDESKTOPWIDGET_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QApplication;
-class QDesktopWidgetPrivate;
-
-class Q_GUI_EXPORT QDesktopWidget : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(bool virtualDesktop READ isVirtualDesktop)
- Q_PROPERTY(int screenCount READ screenCount NOTIFY screenCountChanged)
- Q_PROPERTY(int primaryScreen READ primaryScreen)
-public:
- QDesktopWidget();
- ~QDesktopWidget();
-
- bool isVirtualDesktop() const;
-
- int numScreens() const;
- int screenCount() const;
- int primaryScreen() const;
-
- int screenNumber(const QWidget *widget = 0) const;
- int screenNumber(const QPoint &) const;
-
- QWidget *screen(int screen = -1);
-
- const QRect screenGeometry(int screen = -1) const;
- const QRect screenGeometry(const QWidget *widget) const;
- const QRect screenGeometry(const QPoint &point) const
- { return screenGeometry(screenNumber(point)); }
-
- const QRect availableGeometry(int screen = -1) const;
- const QRect availableGeometry(const QWidget *widget) const;
- const QRect availableGeometry(const QPoint &point) const
- { return availableGeometry(screenNumber(point)); }
-
-Q_SIGNALS:
- void resized(int);
- void workAreaResized(int);
- void screenCountChanged(int);
-
-protected:
- void resizeEvent(QResizeEvent *e);
-
-private:
- Q_DISABLE_COPY(QDesktopWidget)
- Q_DECLARE_PRIVATE(QDesktopWidget)
-
- friend class QApplication;
- friend class QApplicationPrivate;
-};
-
-inline int QDesktopWidget::screenCount() const
-{ return numScreens(); }
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDESKTOPWIDGET_H
diff --git a/src/gui/kernel/qdesktopwidget.qdoc b/src/gui/kernel/qdesktopwidget.qdoc
deleted file mode 100644
index a79a098d74..0000000000
--- a/src/gui/kernel/qdesktopwidget.qdoc
+++ /dev/null
@@ -1,269 +0,0 @@
-/****************************************************************************
-**
-** 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 documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** 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 Free Documentation License
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of this
-** file.
-**
-** If you have questions regarding the use of this file, please contact
-** Nokia at qt-info@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \class QDesktopWidget
- \brief The QDesktopWidget class provides access to screen information on multi-head systems.
-
- \ingroup advanced
- \ingroup desktop
-
- Systems with more than one graphics card and monitor can manage the
- physical screen space available either as multiple desktops, or as a
- large virtual desktop.
-
- This class provides information about the user's desktop, such as its
- total size, number of screens, the geometry of each screen, and whether
- they are configured as separate desktops or a single virtual desktop.
-
- Widgets provided by Qt use this class to place tooltips, menus and
- dialog boxes on the correct screen for their parent or application
- widgets. Applications can use this class to obtain information that
- can be used to save window positions, or to place child widgets and
- dialogs on one particular screen.
-
- \section1 Obtaining a Desktop Widget
-
- The QApplication::desktop() function is used to get an instance of
- QDesktopWidget.
-
- The widget's screenGeometry() function provides information about the
- geometry of the available screens with. The number of screens
- available is returned by screenCount, and the screenCountChanged()
- signal is emitted when screens are added or removed.
- The screen number that a particular point or widget is located in
- is returned by screenNumber().
-
- \section1 Screen Geometry
-
- To obtain the dimensions of a particular screen, call the screenGeometry()
- function. On some desktop environments, not all of the screen is
- available for applications to use; for example, an application dock or
- menu bar may take up some space. Use the availableGeometry() function
- to obtain the available area for applications.
-
- QDesktopWidget also inherits the QWidget properties, width() and
- height(), which specify the size of the desktop. However, for
- desktops with multiple screens, the size of the desktop is the union
- of all the screen sizes, so width() and height() should \e not be
- used for computing the size of a widget to be placed on one of the
- screens.
-
- On systems that are configured to use the available screens as a
- single, large virtual desktop, the virtualDesktop property will be
- set to true. In this case, the widget's size is usually the size of
- the bounding rectangle of all the screens.
-
- \section1 Use of the Primary Screen
-
- For an application, the screen where the main widget resides is the
- primary screen. This is stored in the primaryScreen property.
- All windows opened in the context of the application should be
- constrained to the boundaries of the primary screen; for example,
- it would be inconvenient if a dialog box popped up on a different
- screen, or split over two screens.
-
- \image qdesktopwidget.png Managing Multiple Screens
-
- In the illustration above, Application One's primary screen is
- screen 0, and App Two's primary screen is screen 1.
-
- \sa QApplication, QApplication::desktop(), QX11Info::appRootWindow()
-*/
-
-/*!
- \fn QDesktopWidget::QDesktopWidget()
-
- \internal
-
- Creates the desktop widget.
-
- If the system supports a virtual desktop, this widget will have
- the size of the virtual desktop; otherwise this widget will have
- the size of the primary screen.
-
- Instead of using QDesktopWidget directly, use QApplication::desktop().
-*/
-
-/*!
- \fn QDesktopWidget::~QDesktopWidget()
-
- \internal
-
- Destroys the desktop widget and frees any allocated resources.
-*/
-
-/*!
- \fn int QDesktopWidget::numScreens() const
-
- Returns the number of available screens.
-
- \obsolete
-
- This function is deprecated. Use screenCount instead.
-
- \sa primaryScreen
-*/
-
-/*!
- \fn QWidget *QDesktopWidget::screen(int screen)
-
- Returns a widget that represents the screen with index \a screen
- (a value of -1 means the default screen).
-
- If the system uses a virtual desktop, the returned widget will
- have the geometry of the entire virtual desktop; i.e., bounding
- every \a screen.
-
- \sa primaryScreen, screenCount, virtualDesktop
-*/
-
-/*!
- \fn const QRect QDesktopWidget::availableGeometry(int screen) const
-
- Returns the available geometry of the screen with index \a screen. What
- is available will be subrect of screenGeometry() based on what the
- platform decides is available (for example excludes the dock and menu bar
- on Mac OS X, or the task bar on Windows). The default screen is used if
- \a screen is -1.
-
- \sa screenNumber(), screenGeometry()
-*/
-
-/*!
- \fn const QRect QDesktopWidget::availableGeometry(const QWidget *widget) const
- \overload
-
- Returns the available geometry of the screen which contains \a widget.
-
- \sa screenGeometry()
-*/
-
-/*!
- \fn const QRect QDesktopWidget::availableGeometry(const QPoint &p) const
- \overload
-
- Returns the available geometry of the screen which contains \a p.
-
- \sa screenGeometry()
-*/
-
-
-/*!
- \fn const QRect QDesktopWidget::screenGeometry(int screen) const
-
- Returns the geometry of the screen with index \a screen. The default
- screen is used if \a screen is -1.
-
- \sa screenNumber()
-*/
-
-/*!
- \fn const QRect QDesktopWidget::screenGeometry(const QWidget *widget) const
- \overload
-
- Returns the geometry of the screen which contains \a widget.
-*/
-
-/*!
- \fn const QRect QDesktopWidget::screenGeometry(const QPoint &p) const
- \overload
-
- Returns the geometry of the screen which contains \a p.
-*/
-
-
-/*!
- \fn int QDesktopWidget::screenNumber(const QWidget *widget) const
-
- Returns the index of the screen that contains the largest
- part of \a widget, or -1 if the widget not on a screen.
-
- \sa primaryScreen
-*/
-
-/*!
- \fn int QDesktopWidget::screenNumber(const QPoint &point) const
-
- \overload
- Returns the index of the screen that contains the \a point, or the
- screen which is the shortest distance from the \a point.
-
- \sa primaryScreen
-*/
-
-/*!
- \fn void QDesktopWidget::resizeEvent(QResizeEvent *event)
- \reimp
-*/
-
-/*!
- \fn void QDesktopWidget::resized(int screen)
-
- This signal is emitted when the size of \a screen changes.
-*/
-
-/*!
- \fn void QDesktopWidget::workAreaResized(int screen)
-
- This signal is emitted when the work area available on \a screen changes.
-*/
-
-/*!
- \property QDesktopWidget::screenCount
- \brief the number of screens currently available on the system.
-
- \since 4.6
-
- \sa screenCountChanged()
-*/
-
-/*!
- \property QDesktopWidget::primaryScreen
- \brief the index of the screen that is configured to be the primary screen
- on the system.
-*/
-
-/*!
- \property QDesktopWidget::virtualDesktop
-
- \brief if the system manages the available screens in a virtual desktop.
-
- For virtual desktops, screen() will always return the same widget.
- The size of the virtual desktop is the size of this desktop
- widget.
-*/
-
-/*!
- \fn void QDesktopWidget::screenCountChanged(int newCount)
-
- \since 4.6
-
- This signal is emitted when the number of screens changes to \a newCount.
-
- \sa screenCount
-*/
diff --git a/src/gui/kernel/qdesktopwidget_qpa.cpp b/src/gui/kernel/qdesktopwidget_qpa.cpp
deleted file mode 100644
index 7b175dbe95..0000000000
--- a/src/gui/kernel/qdesktopwidget_qpa.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdesktopwidget.h"
-#include "private/qapplication_p.h"
-#include <QWidget>
-#include "private/qwidget_p.h"
-#include "private/qdesktopwidget_qpa_p.h"
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-void QDesktopWidgetPrivate::updateScreenList()
-{
- Q_Q(QDesktopWidget);
- QList<QPlatformScreen *> screenList = QGuiApplicationPrivate::platformIntegration()->screens();
- int targetLength = screenList.length();
- int currentLength = screens.length();
-
- // Add or remove screen widgets as necessary
- if(currentLength > targetLength) {
- QDesktopScreenWidget *screen;
- while (currentLength-- > targetLength) {
- screen = screens.takeLast();
- delete screen;
- }
- }
- else if (currentLength < targetLength) {
- QDesktopScreenWidget *screen;
- while (currentLength < targetLength) {
- screen = new QDesktopScreenWidget(currentLength++);
- screens.append(screen);
- }
- }
-
- QRegion virtualGeometry;
-
- // update the geometry of each screen widget
- for (int i = 0; i < screens.length(); i++) {
- QRect screenGeometry = screenList.at(i)->geometry();
- screens.at(i)->setGeometry(screenGeometry);
- virtualGeometry += screenGeometry;
- }
-
- q->setGeometry(virtualGeometry.boundingRect());
-}
-
-QDesktopWidget::QDesktopWidget()
- : QWidget(*new QDesktopWidgetPrivate, 0, Qt::Desktop)
-{
- Q_D(QDesktopWidget);
- setObjectName(QLatin1String("desktop"));
- d->updateScreenList();
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
- return QGuiApplicationPrivate::platformIntegration()->isVirtualDesktop();
-}
-
-int QDesktopWidget::primaryScreen() const
-{
- return 0;
-}
-
-int QDesktopWidget::numScreens() const
-{
- QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
- return qMax(pi->screens().size(), 1);
-}
-
-QWidget *QDesktopWidget::screen(int screen)
-{
- Q_D(QDesktopWidget);
- if (screen < 0 || screen >= d->screens.length())
- return d->screens.at(0);
- return d->screens.at(screen);
-}
-
-const QRect QDesktopWidget::availableGeometry(int screenNo) const
-{
- QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
- QList<QPlatformScreen *> screens = pi->screens();
- if (screenNo == -1)
- screenNo = 0;
- if (screenNo < 0 || screenNo >= screens.size())
- return QRect();
- else
- return screens[screenNo]->availableGeometry();
-}
-
-const QRect QDesktopWidget::screenGeometry(int screenNo) const
-{
- QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
- QList<QPlatformScreen *> screens = pi->screens();
- if (screenNo == -1)
- screenNo = 0;
- if (screenNo < 0 || screenNo >= screens.size())
- return QRect();
- else
- return screens[screenNo]->geometry();
-}
-
-int QDesktopWidget::screenNumber(const QWidget *w) const
-{
- if (!w)
- return 0;
-
- QRect frame = w->frameGeometry();
- if (!w->isWindow())
- frame.moveTopLeft(w->mapToGlobal(QPoint(0, 0)));
- const QPoint midpoint = (frame.topLeft() + frame.bottomRight()) / 2;
- return screenNumber(midpoint);
-}
-
-int QDesktopWidget::screenNumber(const QPoint &p) const
-{
- QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
- QList<QPlatformScreen *> screens = pi->screens();
-
- for (int i = 0; i < screens.size(); ++i)
- if (screens[i]->geometry().contains(p))
- return i;
-
- return primaryScreen(); //even better would be closest screen
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qdesktopwidget_qpa_p.h b/src/gui/kernel/qdesktopwidget_qpa_p.h
deleted file mode 100644
index d6ed686a3f..0000000000
--- a/src/gui/kernel/qdesktopwidget_qpa_p.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-#ifndef QDESKTOPWIDGET_QPA_P_H
-#define QDESKTOPWIDGET_QPA_P_H
-
-#include "QDesktopWidget"
-#include "private/qwidget_p.h"
-
-class QDesktopScreenWidget : public QWidget {
- Q_OBJECT
-public:
- QDesktopScreenWidget(int screenNumber = -1)
- {
- setWindowFlags(Qt::Desktop);
- setVisible(false);
- QTLWExtra *topData = d_func()->topData();
- topData->screenIndex = screenNumber;
- }
-};
-
-class QDesktopWidgetPrivate : public QWidgetPrivate {
- Q_DECLARE_PUBLIC(QDesktopWidget)
-
-public:
- ~QDesktopWidgetPrivate() {foreach(QDesktopScreenWidget *s, screens) delete s; }
- void updateScreenList();
-
- QList<QDesktopScreenWidget *> screens;
-};
-
-#endif // QDESKTOPWIDGET_QPA_P_H
diff --git a/src/gui/kernel/qformlayout.cpp b/src/gui/kernel/qformlayout.cpp
deleted file mode 100644
index d098c01f0f..0000000000
--- a/src/gui/kernel/qformlayout.cpp
+++ /dev/null
@@ -1,2079 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qdebug.h"
-#include "qformlayout.h"
-#include "qlabel.h"
-#include "qlayout_p.h"
-#include "qlayoutengine_p.h"
-#include "qrect.h"
-#include "qvector.h"
-#include "qwidget.h"
-
-QT_BEGIN_NAMESPACE
-
-namespace {
-// Fixed column matrix, stores items as [i11, i12, i21, i22...],
-// with FORTRAN-style index operator(r, c).
-template <class T, int NumColumns>
-class FixedColumnMatrix {
-public:
- typedef QVector<T> Storage;
-
- FixedColumnMatrix() { }
-
- void clear() { m_storage.clear(); }
-
- const T &operator()(int r, int c) const { return m_storage[r * NumColumns + c]; }
- T &operator()(int r, int c) { return m_storage[r * NumColumns + c]; }
-
- int rowCount() const { return m_storage.size() / NumColumns; }
- void addRow(const T &value);
- void insertRow(int r, const T &value);
- void removeRow(int r);
-
- bool find(const T &value, int *rowPtr, int *colPtr) const ;
- int count(const T &value) const { return m_storage.count(value); }
-
- // Hmmpf.. Some things are faster that way.
- const Storage &storage() const { return m_storage; }
-
- static void storageIndexToPosition(int idx, int *rowPtr, int *colPtr);
-
-private:
- Storage m_storage;
-};
-
-template <class T, int NumColumns>
-void FixedColumnMatrix<T, NumColumns>::addRow(const T &value)
-{
- for (int i = 0; i < NumColumns; ++i)
- m_storage.append(value);
-}
-
-template <class T, int NumColumns>
-void FixedColumnMatrix<T, NumColumns>::insertRow(int r, const T &value)
-{
- Q_TYPENAME Storage::iterator it = m_storage.begin();
- it += r * NumColumns;
- m_storage.insert(it, NumColumns, value);
-}
-
-template <class T, int NumColumns>
-void FixedColumnMatrix<T, NumColumns>::removeRow(int r)
-{
- m_storage.remove(r * NumColumns, NumColumns);
-}
-
-template <class T, int NumColumns>
-bool FixedColumnMatrix<T, NumColumns>::find(const T &value, int *rowPtr, int *colPtr) const
-{
- const int idx = m_storage.indexOf(value);
- if (idx == -1)
- return false;
- storageIndexToPosition(idx, rowPtr, colPtr);
- return true;
-}
-
-template <class T, int NumColumns>
-void FixedColumnMatrix<T, NumColumns>::storageIndexToPosition(int idx, int *rowPtr, int *colPtr)
-{
- *rowPtr = idx / NumColumns;
- *colPtr = idx % NumColumns;
-}
-} // namespace
-
-// special values for unset fields; must not clash with values of FieldGrowthPolicy or
-// RowWrapPolicy
-const uint DefaultFieldGrowthPolicy = 255;
-const uint DefaultRowWrapPolicy = 255;
-
-enum { ColumnCount = 2 };
-
-// -- our data structure for our items
-// This owns the QLayoutItem
-struct QFormLayoutItem
-{
- QFormLayoutItem(QLayoutItem* i) : item(i), fullRow(false), isHfw(false) { }
- ~QFormLayoutItem() { delete item; }
-
- // Wrappers
- QWidget *widget() const { return item->widget(); }
- QLayout *layout() const { return item->layout(); }
-
- bool hasHeightForWidth() const { return item->hasHeightForWidth(); }
- int heightForWidth(int width) const { return item->heightForWidth(width); }
- int minimumHeightForWidth(int width) const { return item->minimumHeightForWidth(width); }
- Qt::Orientations expandingDirections() const { return item->expandingDirections(); }
- QSizePolicy::ControlTypes controlTypes() const { return item->controlTypes(); }
- int vStretch() const { return widget() ? widget()->sizePolicy().verticalStretch() : 0; }
-
- void setGeometry(const QRect& r) { item->setGeometry(r); }
- QRect geometry() const { return item->geometry(); }
-
- // For use with FixedColumnMatrix
- bool operator==(const QFormLayoutItem& other) { return item == other.item; }
-
- QLayoutItem *item;
- bool fullRow;
-
- // set by updateSizes
- bool isHfw;
- QSize minSize;
- QSize sizeHint;
- QSize maxSize;
-
- // also set by updateSizes
- int sbsHSpace; // only used for side by side, for the field item only (not label)
- int vSpace; // This is the spacing to the item in the row above
-
- // set by setupVerticalLayoutData
- bool sideBySide;
- int vLayoutIndex;
-
- // set by setupHorizontalLayoutData
- int layoutPos;
- int layoutWidth;
-};
-
-class QFormLayoutPrivate : public QLayoutPrivate
-{
- Q_DECLARE_PUBLIC(QFormLayout)
-
-public:
- typedef FixedColumnMatrix<QFormLayoutItem *, ColumnCount> ItemMatrix;
-
- QFormLayoutPrivate();
- ~QFormLayoutPrivate() { }
-
- int insertRow(int row);
- void insertRows(int row, int count);
- void setItem(int row, QFormLayout::ItemRole role, QLayoutItem *item);
- void setLayout(int row, QFormLayout::ItemRole role, QLayout *layout);
- void setWidget(int row, QFormLayout::ItemRole role, QWidget *widget);
-
- void arrangeWidgets(const QVector<QLayoutStruct>& layouts, QRect &rect);
-
- void updateSizes();
-
- void setupVerticalLayoutData(int width);
- void setupHorizontalLayoutData(int width);
-
- QStyle* getStyle() const;
-
- inline bool haveHfwCached(int width) const
- {
- return (hfw_width == width) || (width == sh_width && hfw_sh_height >= 0);
- }
-
- void recalcHFW(int w);
- void setupHfwLayoutData();
-
- uint fieldGrowthPolicy : 8;
- uint rowWrapPolicy : 8;
- uint has_hfw : 2;
- uint dirty : 2; // have we laid out yet?
- uint sizesDirty : 2; // have we (not) gathered layout item sizes?
- uint expandVertical : 1; // Do we expand vertically?
- uint expandHorizontal : 1; // Do we expand horizonally?
- Qt::Alignment labelAlignment;
- Qt::Alignment formAlignment;
-
- ItemMatrix m_matrix;
- QList<QFormLayoutItem *> m_things;
-
- int layoutWidth; // the last width that we called setupVerticalLayoutData on (for vLayouts)
-
- int hfw_width; // the last width we calculated HFW for
- int hfw_height; // what that height was
- int hfw_minheight; // what that minheight was
-
- int hfw_sh_height; // the hfw for sh_width
- int hfw_sh_minheight; // the minhfw for sh_width
-
- int min_width; // the width that gets turned into minSize (from updateSizes)
- int sh_width; // the width that gets turned into prefSize (from updateSizes)
- int thresh_width; // the width that we start splitting label/field pairs at (from updateSizes)
- QSize minSize;
- QSize prefSize;
- int formMaxWidth;
- void calcSizeHints();
-
- QVector<QLayoutStruct> vLayouts; // set by setupVerticalLayoutData;
- int vLayoutCount; // Number of rows we calculated in setupVerticalLayoutData
- int maxLabelWidth; // the label width we calculated in setupVerticalLayoutData
-
- QVector<QLayoutStruct> hfwLayouts;
-
- int hSpacing;
- int vSpacing;
-};
-
-QFormLayoutPrivate::QFormLayoutPrivate()
- : fieldGrowthPolicy(DefaultFieldGrowthPolicy),
- rowWrapPolicy(DefaultRowWrapPolicy), has_hfw(false), dirty(true), sizesDirty(true),
- expandVertical(0), expandHorizontal(0), labelAlignment(0), formAlignment(0),
- layoutWidth(-1), hfw_width(-1), hfw_sh_height(-1), min_width(-1),
- sh_width(-1), thresh_width(QLAYOUTSIZE_MAX), hSpacing(-1), vSpacing(-1)
-{
-}
-
-static Qt::Alignment fixedAlignment(Qt::Alignment alignment, Qt::LayoutDirection layoutDirection)
-{
- if (layoutDirection == Qt::RightToLeft && alignment & Qt::AlignAbsolute) {
- // swap left and right, and eliminate absolute flag
- return Qt::Alignment((alignment & ~(Qt::AlignLeft | Qt::AlignRight | Qt::AlignAbsolute))
- | ((alignment & Qt::AlignRight) ? Qt::AlignLeft : 0)
- | ((alignment & Qt::AlignLeft) ? Qt::AlignRight : 0));
- } else {
- return alignment & ~Qt::AlignAbsolute;
- }
-}
-
-static int storageIndexFromLayoutItem(const QFormLayoutPrivate::ItemMatrix &m,
- QFormLayoutItem *item)
-{
- if (item) {
- return m.storage().indexOf(item);
- } else {
- return -1;
- }
-}
-
-static void updateFormLayoutItem(QFormLayoutItem *item, int userVSpacing,
- QFormLayout::FieldGrowthPolicy fieldGrowthPolicy,
- bool fullRow)
-{
- item->minSize = item->item->minimumSize();
- item->sizeHint = item->item->sizeHint();
- item->maxSize = item->item->maximumSize();
-
- if (!fullRow && (fieldGrowthPolicy == QFormLayout::FieldsStayAtSizeHint
- || (fieldGrowthPolicy == QFormLayout::ExpandingFieldsGrow
- && !(item->item->expandingDirections() & Qt::Horizontal))))
- item->maxSize.setWidth(item->sizeHint.width());
-
- item->isHfw = item->item->hasHeightForWidth();
- item->vSpace = userVSpacing;
-}
-
-/*
- Iterate over all the controls and gather their size information
- (min, sizeHint and max). Also work out what the spacing between
- pairs of controls should be, and figure out the min and sizeHint
- widths.
-*/
-void QFormLayoutPrivate::updateSizes()
-{
- Q_Q(QFormLayout);
-
- if (sizesDirty) {
- QFormLayout::RowWrapPolicy wrapPolicy = q->rowWrapPolicy();
- bool wrapAllRows = (wrapPolicy == QFormLayout::WrapAllRows);
- bool dontWrapRows = (wrapPolicy == QFormLayout::DontWrapRows);
- int rr = m_matrix.rowCount();
-
- has_hfw = false;
-
- // If any control can expand, so can this layout
- // Wrapping doesn't affect expansion, though, just the minsize
- bool expandH = false;
- bool expandV = false;
-
- QFormLayoutItem *prevLbl = 0;
- QFormLayoutItem *prevFld = 0;
-
- QWidget *parent = q->parentWidget();
- QStyle *style = parent ? parent->style() : 0;
-
- int userVSpacing = q->verticalSpacing();
- int userHSpacing = wrapAllRows ? 0 : q->horizontalSpacing();
-
- int maxMinLblWidth = 0;
- int maxMinFldWidth = 0; // field with label
- int maxMinIfldWidth = 0; // independent field
-
- int maxShLblWidth = 0;
- int maxShFldWidth = 0;
- int maxShIfldWidth = 0;
-
- for (int i = 0; i < rr; ++i) {
- QFormLayoutItem *label = m_matrix(i, 0);
- QFormLayoutItem *field = m_matrix(i, 1);
-
- // Skip empty rows
- if (!label && !field)
- continue;
-
- if (label) {
- updateFormLayoutItem(label, userVSpacing, q->fieldGrowthPolicy(), false);
- if (label->isHfw)
- has_hfw = true;
- Qt::Orientations o = label->expandingDirections();
-
- if (o & Qt::Vertical)
- expandV = true;
- if (o & Qt::Horizontal)
- expandH = true;
- }
- if (field) {
- updateFormLayoutItem(field, userVSpacing, q->fieldGrowthPolicy(), !label && field->fullRow);
- field->sbsHSpace = (!label && field->fullRow) ? 0 : userHSpacing;
- if (field->isHfw)
- has_hfw = true;
-
- Qt::Orientations o = field->expandingDirections();
-
- if (o & Qt::Vertical)
- expandV = true;
- if (o & Qt::Horizontal)
- expandH = true;
- }
-
- // See if we need to calculate default spacings
- if ((userHSpacing < 0 || userVSpacing < 0) && style) {
- QSizePolicy::ControlTypes lbltypes =
- QSizePolicy::ControlTypes(label ? label->controlTypes() : QSizePolicy::DefaultType);
- QSizePolicy::ControlTypes fldtypes =
- QSizePolicy::ControlTypes(field ? field->controlTypes() : QSizePolicy::DefaultType);
-
- // VSpacing
- if (userVSpacing < 0) {
- if (wrapAllRows) {
- // label spacing is to a previous item
- QFormLayoutItem *lbltop = prevFld ? prevFld : prevLbl;
- // field spacing is to the label (or a previous item)
- QFormLayoutItem *fldtop = label ? label : lbltop;
- QSizePolicy::ControlTypes lbltoptypes =
- QSizePolicy::ControlTypes(lbltop ? lbltop->controlTypes() : QSizePolicy::DefaultType);
- QSizePolicy::ControlTypes fldtoptypes =
- QSizePolicy::ControlTypes(fldtop ? fldtop->controlTypes() : QSizePolicy::DefaultType);
- if (label && lbltop)
- label->vSpace = style->combinedLayoutSpacing(lbltoptypes, lbltypes, Qt::Vertical, 0, parent);
- if (field && fldtop)
- field->vSpace = style->combinedLayoutSpacing(fldtoptypes, fldtypes, Qt::Vertical, 0, parent);
- } else {
- // Side by side.. we have to also consider the spacings to empty cells, which can strangely be more than
- // non empty cells..
- QFormLayoutItem *lbltop = prevLbl ? prevLbl : prevFld;
- QFormLayoutItem *fldtop = prevFld;
- QSizePolicy::ControlTypes lbltoptypes =
- QSizePolicy::ControlTypes(lbltop ? lbltop->controlTypes() : QSizePolicy::DefaultType);
- QSizePolicy::ControlTypes fldtoptypes =
- QSizePolicy::ControlTypes(fldtop ? fldtop->controlTypes() : QSizePolicy::DefaultType);
-
- // To be compatible to QGridLayout, we have to compare solitary labels & fields with both predecessors
- if (label) {
- if (!field) {
- int lblspacing = style->combinedLayoutSpacing(lbltoptypes, lbltypes, Qt::Vertical, 0, parent);
- int fldspacing = style->combinedLayoutSpacing(fldtoptypes, lbltypes, Qt::Vertical, 0, parent);
- label->vSpace = qMax(lblspacing, fldspacing);
- } else
- label->vSpace = style->combinedLayoutSpacing(lbltoptypes, lbltypes, Qt::Vertical, 0, parent);
- }
-
- if (field) {
- // check spacing against both the previous label and field
- if (!label) {
- int lblspacing = style->combinedLayoutSpacing(lbltoptypes, fldtypes, Qt::Vertical, 0, parent);
- int fldspacing = style->combinedLayoutSpacing(fldtoptypes, fldtypes, Qt::Vertical, 0, parent);
- field->vSpace = qMax(lblspacing, fldspacing);
- } else
- field->vSpace = style->combinedLayoutSpacing(fldtoptypes, fldtypes, Qt::Vertical, 0, parent);
- }
- }
- }
-
- // HSpacing
- // hard-coded the left and right control types so that all the rows have the same
- // inter-column spacing (otherwise the right column isn't always left aligned)
- if (userHSpacing < 0 && !wrapAllRows && (label || !field->fullRow) && field)
- field->sbsHSpace = style->combinedLayoutSpacing(QSizePolicy::Label, QSizePolicy::LineEdit, Qt::Horizontal, 0, parent);
- }
-
- // Now update our min/sizehint widths
- // We choose to put the spacing in the field side in sbs, so
- // the right edge of the labels will align, but fields may
- // be a little ragged.. since different controls may have
- // different appearances, a slight raggedness in the left
- // edges of fields can be tolerated.
- // (Note - field->sbsHSpace is 0 for WrapAllRows mode)
- if (label) {
- maxMinLblWidth = qMax(maxMinLblWidth, label->minSize.width());
- maxShLblWidth = qMax(maxShLblWidth, label->sizeHint.width());
- if (field) {
- maxMinFldWidth = qMax(maxMinFldWidth, field->minSize.width() + field->sbsHSpace);
- maxShFldWidth = qMax(maxShFldWidth, field->sizeHint.width() + field->sbsHSpace);
- }
- } else if (field) {
- maxMinIfldWidth = qMax(maxMinIfldWidth, field->minSize.width());
- maxShIfldWidth = qMax(maxShIfldWidth, field->sizeHint.width());
- }
-
- prevLbl = label;
- prevFld = field;
- }
-
- // Now, finally update the min/sizeHint widths
- if (wrapAllRows) {
- sh_width = qMax(maxShLblWidth, qMax(maxShIfldWidth, maxShFldWidth));
- min_width = qMax(maxMinLblWidth, qMax(maxMinIfldWidth, maxMinFldWidth));
- // in two line, we don't care as much about the threshold width
- thresh_width = 0;
- } else if (dontWrapRows) {
- // This is just the max widths glommed together
- sh_width = qMax(maxShLblWidth + maxShFldWidth, maxShIfldWidth);
- min_width = qMax(maxMinLblWidth + maxMinFldWidth, maxMinIfldWidth);
- thresh_width = QWIDGETSIZE_MAX;
- } else {
- // This is just the max widths glommed together
- sh_width = qMax(maxShLblWidth + maxShFldWidth, maxShIfldWidth);
- // min width needs to be the min when everything is wrapped,
- // otherwise we'll never get set with a width that causes wrapping
- min_width = qMax(maxMinLblWidth, qMax(maxMinIfldWidth, maxMinFldWidth));
- // We split a pair at label sh + field min (### for now..)
- thresh_width = maxShLblWidth + maxMinFldWidth;
- }
-
- // Update the expansions
- expandVertical = expandV;
- expandHorizontal = expandH;
- }
- sizesDirty = false;
-}
-
-void QFormLayoutPrivate::recalcHFW(int w)
-{
- setupHfwLayoutData();
-
- int h = 0;
- int mh = 0;
-
- for (int r = 0; r < vLayoutCount; ++r) {
- int spacing = hfwLayouts.at(r).spacing;
- h += hfwLayouts.at(r).sizeHint + spacing;
- mh += hfwLayouts.at(r).minimumSize + spacing;
- }
-
- if (sh_width > 0 && sh_width == w) {
- hfw_sh_height = qMin(QLAYOUTSIZE_MAX, h);
- hfw_sh_minheight = qMin(QLAYOUTSIZE_MAX, mh);
- } else {
- hfw_width = w;
- hfw_height = qMin(QLAYOUTSIZE_MAX, h);
- hfw_minheight = qMin(QLAYOUTSIZE_MAX, mh);
- }
-}
-
-void QFormLayoutPrivate::setupHfwLayoutData()
-{
- // setupVerticalLayoutData must be called before this
- // setupHorizontalLayoutData must also be called before this
- // copies non hfw data into hfw
- // then updates size and min
-
-
- // Note: QGridLayout doesn't call minimumHeightForWidth,
- // but instead uses heightForWidth for both min and sizeHint.
- // For the common case where minimumHeightForWidth just calls
- // heightForWidth, we do the calculation twice, which can be
- // very expensive for word wrapped QLabels/QTextEdits, for example.
- // So we just use heightForWidth as well.
- int i;
- int rr = m_matrix.rowCount();
-
- hfwLayouts.clear();
- hfwLayouts.resize(vLayoutCount);
- for (i = 0; i < vLayoutCount; ++i)
- hfwLayouts[i] = vLayouts.at(i);
-
- for (i = 0; i < rr; ++i) {
- QFormLayoutItem *label = m_matrix(i, 0);
- QFormLayoutItem *field = m_matrix(i, 1);
-
- if (label) {
- if (label->isHfw) {
- // We don't check sideBySide here, since a label is only
- // ever side by side with its field
- int hfw = label->heightForWidth(label->layoutWidth);
- hfwLayouts[label->vLayoutIndex].minimumSize = hfw;
- hfwLayouts[label->vLayoutIndex].sizeHint = hfw;
- } else {
- // Reset these here, so the field can do a qMax below (the previous value may have
- // been the fields non-hfw values, which are often larger than hfw)
- hfwLayouts[label->vLayoutIndex].sizeHint = label->sizeHint.height();
- hfwLayouts[label->vLayoutIndex].minimumSize = label->minSize.height();
- }
- }
-
- if (field) {
- int hfw = field->isHfw ? field->heightForWidth(field->layoutWidth) : 0;
- int h = field->isHfw ? hfw : field->sizeHint.height();
- int mh = field->isHfw ? hfw : field->minSize.height();
-
- if (field->sideBySide) {
- int oh = hfwLayouts.at(field->vLayoutIndex).sizeHint;
- int omh = hfwLayouts.at(field->vLayoutIndex).minimumSize;
-
- hfwLayouts[field->vLayoutIndex].sizeHint = qMax(h, oh);
- hfwLayouts[field->vLayoutIndex].minimumSize = qMax(mh, omh);
- } else {
- hfwLayouts[field->vLayoutIndex].sizeHint = h;
- hfwLayouts[field->vLayoutIndex].minimumSize = mh;
- }
- }
- }
-}
-
-/*
- Given up to four items involved in a vertical spacing calculation
- (two rows * two columns), return the max vertical spacing for the
- row containing item1 (which may also include item2)
- We assume parent and item1 are not null.
-
- If a particular row is split, then the spacings for that row and
- the following row are affected, and this function should be
- called with recalculate = true for both rows (note: only rows with both
- a label and a field can be split).
-
- In particular:
-
- 1) the split label's row vspace needs to be changed to qMax(label/prevLabel, label/prevField)
- [call with item1 = label, item2 = null, prevItem1 & prevItem2 as before]
- 2) the split field's row vspace needs to be changed to the label/field spacing
- [call with item1 = field, item2 = null, prevItem1 = label, prevItem2 = null]
-
- [if the next row has one item, 'item']
- 3a) the following row's vspace needs to be changed to item/field spacing (would
- previously been the qMax(item/label, item/field) spacings)
- [call with item1 = item, item2 = null, prevItem1 = field, prevItem2 = null]
-
- [if the next row has two items, 'label2' and 'field2']
- 3b) the following row's vspace needs to be changed to be qMax(field/label2, field/field2) spacing
- [call with item1 = label2, item2 = field2, prevItem1 = field, prevItem2 = null]
-
- In the (common) non split case, we can just use the precalculated vspace (possibly qMaxed between
- label and field).
-
- If recalculate is true, we expect:
- - parent != null
- - item1 != null
- - item2 can be null
- - prevItem1 can be null
- - if item2 is not null, prevItem2 will be null (e.g. steps 1 or 3 above)
- - if prevItem1 is null, prevItem2 will be null
-*/
-static inline int spacingHelper(QWidget* parent, QStyle *style, int userVSpacing, bool recalculate, QFormLayoutItem* item1, QFormLayoutItem* item2, QFormLayoutItem* prevItem1, QFormLayoutItem *prevItem2)
-{
- int spacing = userVSpacing;
- if (spacing < 0) {
- if (!recalculate) {
- if (item1)
- spacing = item1->vSpace;
- if (item2)
- spacing = qMax(spacing, item2->vSpace);
- } else {
- if (style && prevItem1) {
- QSizePolicy::ControlTypes itemtypes =
- QSizePolicy::ControlTypes(item1 ? item1->controlTypes() : QSizePolicy::DefaultType);
- int spacing2 = 0;
-
- spacing = style->combinedLayoutSpacing(itemtypes, prevItem1->controlTypes(), Qt::Vertical, 0, parent);
-
- // At most of one of item2 and prevItem2 will be nonnull
- if (item2)
- spacing2 = style->combinedLayoutSpacing(item2->controlTypes(), prevItem1->controlTypes(), Qt::Vertical, 0, parent);
- else if (prevItem2)
- spacing2 = style->combinedLayoutSpacing(itemtypes, prevItem2->controlTypes(), Qt::Vertical, 0, parent);
-
- spacing = qMax(spacing, spacing2);
- }
- }
- } else {
- if (prevItem1) {
- QWidget *wid = prevItem1->item->widget();
- if (wid)
- spacing = qMax(spacing, prevItem1->geometry().top() - wid->geometry().top() );
- }
- if (prevItem2) {
- QWidget *wid = prevItem2->item->widget();
- if (wid)
- spacing = qMax(spacing, prevItem2->geometry().top() - wid->geometry().top() );
- }
- }
- return spacing;
-}
-
-static inline void initLayoutStruct(QLayoutStruct& sl, QFormLayoutItem* item)
-{
- sl.init(item->vStretch(), item->minSize.height());
- sl.sizeHint = item->sizeHint.height();
- sl.maximumSize = item->maxSize.height();
- sl.expansive = (item->expandingDirections() & Qt::Vertical);
- sl.empty = false;
-}
-
-void QFormLayoutPrivate::setupVerticalLayoutData(int width)
-{
- Q_Q(QFormLayout);
-
- // Early out if we have no changes that would cause a change in vertical layout
- if ((width == layoutWidth || (width >= thresh_width && layoutWidth >= thresh_width)) && !dirty && !sizesDirty)
- return;
-
- layoutWidth = width;
-
- int rr = m_matrix.rowCount();
- int vidx = 1;
- QFormLayout::RowWrapPolicy rowWrapPolicy = q->rowWrapPolicy();
- bool wrapAllRows = (rowWrapPolicy == QFormLayout::WrapAllRows);
- bool addTopBottomStretch = true;
-
- vLayouts.clear();
- vLayouts.resize((2 * rr) + 2); // a max, some may be unused
-
- QStyle *style = 0;
-
- int userVSpacing = q->verticalSpacing();
-
- if (userVSpacing < 0) {
- if (QWidget *widget = q->parentWidget())
- style = widget->style();
- }
-
- // make sure our sizes are up to date
- updateSizes();
-
- // Grab the widest label width here
- // This might be different from the value computed during
- // sizeHint/minSize, since we don't count label/field pairs that
- // are split.
- maxLabelWidth = 0;
- if (!wrapAllRows) {
- for (int i = 0; i < rr; ++i) {
- const QFormLayoutItem *label = m_matrix(i, 0);
- const QFormLayoutItem *field = m_matrix(i, 1);
- if (label && (label->sizeHint.width() + (field ? field->minSize.width() : 0) <= width))
- maxLabelWidth = qMax(maxLabelWidth, label->sizeHint.width());
- }
- } else {
- maxLabelWidth = width;
- }
-
- QFormLayoutItem *prevItem1 = 0;
- QFormLayoutItem *prevItem2 = 0;
- bool prevRowSplit = false;
-
- for (int i = 0; i < rr; ++i) {
- QFormLayoutItem *label = m_matrix(i, 0);
- QFormLayoutItem *field = m_matrix(i, 1);
-
- // Totally ignore empty rows...
- if (!label && !field)
- continue;
-
- QSize min1;
- QSize min2;
- QSize sh1;
- QSize sh2;
- if (label) {
- min1 = label->minSize;
- sh1 = label->sizeHint;
- }
- if (field) {
- min2 = field->minSize;
- sh2 = field->sizeHint;
- }
-
- // In separate lines, we make a vLayout for everything that isn't null
- // in side by side, we only separate label/field if we're going to wrap it
- bool splitSideBySide = (rowWrapPolicy == QFormLayout::WrapLongRows)
- && ((maxLabelWidth < sh1.width()) || (width < (maxLabelWidth + min2.width())));
-
- if (wrapAllRows || splitSideBySide) {
- if (label) {
- initLayoutStruct(vLayouts[vidx], label);
-
- if (vidx > 1)
- vLayouts[vidx - 1].spacing = spacingHelper(q->parentWidget(), style, userVSpacing, splitSideBySide || prevRowSplit, label, 0, prevItem1, prevItem2);
-
- label->vLayoutIndex = vidx;
- label->sideBySide = false;
-
- prevItem1 = label;
- prevItem2 = 0;
-
- if (vLayouts[vidx].stretch > 0)
- addTopBottomStretch = false;
-
- ++vidx;
- }
-
- if (field) {
- initLayoutStruct(vLayouts[vidx], field);
-
- if (vidx > 1)
- vLayouts[vidx - 1].spacing = spacingHelper(q->parentWidget(), style, userVSpacing, splitSideBySide || prevRowSplit, field, 0, prevItem1, prevItem2);
-
- field->vLayoutIndex = vidx;
- field->sideBySide = false;
-
- prevItem1 = field;
- prevItem2 = 0;
-
- if (vLayouts[vidx].stretch > 0)
- addTopBottomStretch = false;
-
- ++vidx;
- }
-
- prevRowSplit = splitSideBySide;
- } else {
- // we're in side by side mode, and we have enough space to do that
- QSize max1(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
- QSize max2(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
-
- int stretch1 = 0;
- int stretch2 = 0;
- bool expanding = false;
-
- if (label) {
- max1 = label->maxSize;
- if (label->expandingDirections() & Qt::Vertical)
- expanding = true;
-
- label->sideBySide = (field != 0);
- label->vLayoutIndex = vidx;
- stretch1 = label->vStretch();
- }
-
- if (field) {
- max2 = field->maxSize;
- if (field->expandingDirections() & Qt::Vertical)
- expanding = true;
-
- field->sideBySide = (label || !field->fullRow);
- field->vLayoutIndex = vidx;
- stretch2 = field->vStretch();
- }
-
- vLayouts[vidx].init(qMax(stretch1, stretch2), qMax(min1.height(), min2.height()));
- vLayouts[vidx].sizeHint = qMax(sh1.height(), sh2.height());
- vLayouts[vidx].maximumSize = qMin(max1.height(), max2.height());
- vLayouts[vidx].expansive = expanding || (vLayouts[vidx].stretch > 0);
- vLayouts[vidx].empty = false;
-
- if (vLayouts[vidx].stretch > 0)
- addTopBottomStretch = false;
-
- if (vidx > 1)
- vLayouts[vidx - 1].spacing = spacingHelper(q->parentWidget(), style, userVSpacing, prevRowSplit, label, field, prevItem1, prevItem2);
-
- if (label) {
- prevItem1 = label;
- prevItem2 = field;
- } else {
- prevItem1 = field;
- prevItem2 = 0;
- }
-
- prevRowSplit = false;
- ++vidx;
- }
- }
-
- if (addTopBottomStretch) {
- Qt::Alignment formAlignment = q->formAlignment();
-
- if (!(formAlignment & Qt::AlignBottom)) {
- // AlignTop (default if unspecified) or AlignVCenter: We add a stretch at the bottom
- vLayouts[vidx].init(1, 0);
- vLayouts[vidx].expansive = true;
- ++vidx;
- }
-
- if (formAlignment & (Qt::AlignVCenter | Qt::AlignBottom)) {
- // AlignVCenter or AlignBottom: We add a stretch at the top
- vLayouts[0].init(1, 0);
- vLayouts[0].expansive = true;
- } else {
- vLayouts[0].init(0, 0);
- }
- } else {
- vLayouts[0].init(0, 0);
- }
-
- vLayoutCount = vidx;
- dirty = false;
-}
-
-void QFormLayoutPrivate::setupHorizontalLayoutData(int width)
-{
- Q_Q(QFormLayout);
-
- // requires setupVerticalLayoutData to be called first
-
- int fieldMaxWidth = 0;
-
- int rr = m_matrix.rowCount();
- bool wrapAllRows = (q->rowWrapPolicy() == QFormLayout::WrapAllRows);
-
- for (int i = 0; i < rr; ++i) {
- QFormLayoutItem *label = m_matrix(i, 0);
- QFormLayoutItem *field = m_matrix(i, 1);
-
- // Totally ignore empty rows...
- if (!label && !field)
- continue;
-
- if (label) {
- // if there is a field, and we're side by side, we use maxLabelWidth
- // otherwise we just use the sizehint
- label->layoutWidth = (field && label->sideBySide) ? maxLabelWidth : label->sizeHint.width();
- label->layoutPos = 0;
- }
-
- if (field) {
- // This is the default amount allotted to fields in sbs
- int fldwidth = width - maxLabelWidth - field->sbsHSpace;
-
- // If we've split a row, we still decide to align
- // the field with all the other field if it will fit
- // Fields in sbs mode get the remnants of the maxLabelWidth
- if (!field->sideBySide) {
- if (wrapAllRows || (!label && field->fullRow) || field->sizeHint.width() > fldwidth) {
- field->layoutWidth = width;
- field->layoutPos = 0;
- } else {
- field->layoutWidth = fldwidth;
- field->layoutPos = width - fldwidth;
- }
- } else {
- // We're sbs, so we should have a label
- field->layoutWidth = fldwidth;
- field->layoutPos = width - fldwidth;
- }
-
- fieldMaxWidth = qMax(fieldMaxWidth, field->maxSize.width());
- }
- }
-
- formMaxWidth = maxLabelWidth + fieldMaxWidth;
-}
-
-void QFormLayoutPrivate::calcSizeHints()
-{
- Q_Q(QFormLayout);
-
- int leftMargin, topMargin, rightMargin, bottomMargin;
- q->getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
-
- updateSizes();
- setupVerticalLayoutData(QLAYOUTSIZE_MAX);
- // Don't need to call setupHorizontal here
-
- int h = topMargin + bottomMargin;
- int mh = topMargin + bottomMargin;
-
- // The following are set in updateSizes
- int w = sh_width + leftMargin + rightMargin;
- int mw = min_width + leftMargin + rightMargin;
-
- for (int i = 0; i < vLayoutCount; ++i) {
- int spacing = vLayouts.at(i).spacing;
- h += vLayouts.at(i).sizeHint + spacing;
- mh += vLayouts.at(i).minimumSize + spacing;
- }
-
- minSize.rwidth() = qMin(mw, QLAYOUTSIZE_MAX);
- minSize.rheight() = qMin(mh, QLAYOUTSIZE_MAX);
- prefSize.rwidth() = qMin(w, QLAYOUTSIZE_MAX);
- prefSize.rheight() = qMin(h, QLAYOUTSIZE_MAX);
-}
-
-int QFormLayoutPrivate::insertRow(int row)
-{
- int rowCnt = m_matrix.rowCount();
- if (uint(row) > uint(rowCnt))
- row = rowCnt;
-
- insertRows(row, 1);
- return row;
-}
-
-void QFormLayoutPrivate::insertRows(int row, int count)
-{
- while (count > 0) {
- m_matrix.insertRow(row, 0);
- --count;
- }
-}
-
-void QFormLayoutPrivate::setItem(int row, QFormLayout::ItemRole role, QLayoutItem *item)
-{
- const bool fullRow = role == QFormLayout::SpanningRole;
- const int column = role == QFormLayout::SpanningRole ? 1 : static_cast<int>(role);
- if (uint(row) >= uint(m_matrix.rowCount()) || uint(column) > 1U) {
- qWarning("QFormLayoutPrivate::setItem: Invalid cell (%d, %d)", row, column);
- return;
- }
-
- if (!item)
- return;
-
- if (m_matrix(row, column)) {
- qWarning("QFormLayoutPrivate::setItem: Cell (%d, %d) already occupied", row, column);
- return;
- }
-
- QFormLayoutItem *i = new QFormLayoutItem(item);
- i->fullRow = fullRow;
- m_matrix(row, column) = i;
-
- m_things.append(i);
-}
-
-void QFormLayoutPrivate::setLayout(int row, QFormLayout::ItemRole role, QLayout *layout)
-{
- if (layout) {
- Q_Q(QFormLayout);
- q->addChildLayout(layout);
- setItem(row, role, layout);
- }
-}
-
-void QFormLayoutPrivate::setWidget(int row, QFormLayout::ItemRole role, QWidget *widget)
-{
- if (widget) {
- Q_Q(QFormLayout);
- q->addChildWidget(widget);
- setItem(row, role, QLayoutPrivate::createWidgetItem(q, widget));
- }
-}
-
-QStyle* QFormLayoutPrivate::getStyle() const
-{
- Q_Q(const QFormLayout);
-
- // ### cache
- if (QWidget *parentWidget = q->parentWidget())
- return parentWidget->style();
- else
- return QApplication::style();
-}
-
-/*!
- \class QFormLayout
- \since 4.4
- \brief The QFormLayout class manages forms of input widgets and their associated labels.
-
- \ingroup geomanagement
-
-
- QFormLayout is a convenience layout class that lays out its
- children in a two-column form. The left column consists of labels
- and the right column consists of "field" widgets (line editors,
- spin boxes, etc.).
-
- Traditionally, such two-column form layouts were achieved using
- QGridLayout. QFormLayout is a higher-level alternative that
- provides the following advantages:
-
- \list
- \o \bold{Adherence to the different platform's look and feel guidelines.}
-
- For example, the
- \l{Mac OS X Aqua} and KDE guidelines specify that the
- labels should be right-aligned, whereas Windows and GNOME
- applications normally use left-alignment.
-
- \o \bold{Support for wrapping long rows.}
-
- For devices with small displays, QFormLayout can be set to
- \l{WrapLongRows}{wrap long rows}, or even to
- \l{WrapAllRows}{wrap all rows}.
-
- \o \bold{Convenient API for creating label--field pairs.}
-
- The addRow() overload that takes a QString and a QWidget *
- creates a QLabel behind the scenes and automatically set up
- its buddy. We can then write code like this:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qformlayout.cpp 0
-
- Compare this with the following code, written using QGridLayout:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qformlayout.cpp 1
- \endlist
-
- The table below shows the default appearance in different styles.
-
- \table
- \header
- \o QCommonStyle derived styles (except QPlastiqueStyle)
- \o QMacStyle
- \o QPlastiqueStyle
- \o Qt Extended styles
- \row
- \o \inlineimage qformlayout-win.png
- \o \inlineimage qformlayout-mac.png
- \o \inlineimage qformlayout-kde.png
- \o \inlineimage qformlayout-qpe.png
- \row
- \o Traditional style used for Windows, GNOME, and earlier
- versions of KDE. Labels are left aligned, and expanding
- fields grow to fill the available space. (This normally
- corresponds to what we would get using a two-column
- QGridLayout.)
- \o Style based on the
- \l{Mac OS X Aqua} guidelines. Labels are right-aligned,
- the fields don't grow beyond their size hint, and the
- form is horizontally centered.
- \o Recommended style for
- \l{KDE applications}. Similar to MacStyle, except that the form
- is left-aligned and all fields grow to fill the available
- space.
- \o Default style for Qt Extended styles. Labels are right-aligned,
- expanding fields grow to fill the available space, and row
- wrapping is enabled for long lines.
- \endtable
-
- The form styles can be also be overridden individually by calling
- setLabelAlignment(), setFormAlignment(), setFieldGrowthPolicy(),
- and setRowWrapPolicy(). For example, to simulate the form layout
- appearance of QMacStyle on all platforms, but with left-aligned
- labels, you could write:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qformlayout.cpp 2
-
- \sa QGridLayout, QBoxLayout, QStackedLayout
-*/
-
-
-/*!
- \enum QFormLayout::FieldGrowthPolicy
-
- This enum specifies the different policies that can be used to
- control the way in which the form's fields grow.
-
- \value FieldsStayAtSizeHint
- The fields never grow beyond their
- \l{QWidgetItem::sizeHint()}{effective size hint}. This is
- the default for QMacStyle.
-
- \value ExpandingFieldsGrow
- Fields with an horizontal \l{QSizePolicy}{size policy} of
- \l{QSizePolicy::}{Expanding} or
- \l{QSizePolicy::}{MinimumExpanding} will grow to fill the
- available space. The other fields will not grow beyond
- their effective size hint. This is the default policy for
- Plastique.
-
- \value AllNonFixedFieldsGrow
- All fields with a size policy that allows them to grow
- will grow to fill the available space. This is the default
- policy for most styles.
-
- \sa fieldGrowthPolicy
-*/
-
-/*!
- \enum QFormLayout::RowWrapPolicy
-
- This enum specifies the different policies that can be used to
- control the way in which the form's rows wrap.
-
- \value DontWrapRows
- Fields are always laid out next to their label. This is
- the default policy for all styles except Qt Extended styles
- and QS60Style.
-
- \value WrapLongRows
- Labels are given enough horizontal space to fit the widest label,
- and the rest of the space is given to the fields. If the minimum
- size of a field pair is wider than the available space, the field
- is wrapped to the next line. This is the default policy for
- Qt Extended styles and and QS60Style.
-
- \value WrapAllRows
- Fields are always laid out below their label.
-
- \sa rowWrapPolicy
-*/
-
-/*!
- \enum QFormLayout::ItemRole
-
- This enum specifies the types of widgets (or other layout items)
- that may appear in a row.
-
- \value LabelRole A label widget.
- \value FieldRole A field widget.
- \value SpanningRole A widget that spans label and field columns.
-
- \sa itemAt(), getItemPosition()
-*/
-
-/*!
- Constructs a new form layout with the given \a parent widget.
-
- \sa QWidget::setLayout()
-*/
-QFormLayout::QFormLayout(QWidget *parent)
- : QLayout(*new QFormLayoutPrivate, 0, parent)
-{
-}
-
-/*!
- Destroys the form layout.
-*/
-QFormLayout::~QFormLayout()
-{
- Q_D(QFormLayout);
-
- /*
- The clearing and destruction order here is important. We start by clearing
- m_things so that QLayout and the rest of the world know that we don't babysit
- the layout items anymore and don't care if they are destroyed.
- */
- d->m_things.clear();
- qDeleteAll(d->m_matrix.storage());
- d->m_matrix.clear();
-}
-
-/*!
- Adds a new row to the bottom of this form layout, with the given
- \a label and \a field.
-
- \sa insertRow()
-*/
-void QFormLayout::addRow(QWidget *label, QWidget *field)
-{
- insertRow(-1, label, field);
-}
-
-/*!
- \overload
-*/
-void QFormLayout::addRow(QWidget *label, QLayout *field)
-{
- insertRow(-1, label, field);
-}
-
-/*!
- \overload
-
- This overload automatically creates a QLabel behind the scenes
- with \a labelText as its text. The \a field is set as the new
- QLabel's \l{QLabel::setBuddy()}{buddy}.
-*/
-void QFormLayout::addRow(const QString &labelText, QWidget *field)
-{
- insertRow(-1, labelText, field);
-}
-
-/*!
- \overload
-
- This overload automatically creates a QLabel behind the scenes
- with \a labelText as its text.
-*/
-void QFormLayout::addRow(const QString &labelText, QLayout *field)
-{
- insertRow(-1, labelText, field);
-}
-
-/*!
- \overload
-
- Adds the specified \a widget at the end of this form layout. The
- \a widget spans both columns.
-*/
-void QFormLayout::addRow(QWidget *widget)
-{
- insertRow(-1, widget);
-}
-
-/*!
- \overload
-
- Adds the specified \a layout at the end of this form layout. The
- \a layout spans both columns.
-*/
-void QFormLayout::addRow(QLayout *layout)
-{
- insertRow(-1, layout);
-}
-
-/*!
- Inserts a new row at position \a row in this form layout, with
- the given \a label and \a field. If \a row is out of bounds, the
- new row is added at the end.
-
- \sa addRow()
-*/
-void QFormLayout::insertRow(int row, QWidget *label, QWidget *field)
-{
- Q_D(QFormLayout);
-
- row = d->insertRow(row);
- if (label)
- d->setWidget(row, LabelRole, label);
- if (field)
- d->setWidget(row, FieldRole, field);
- invalidate();
-}
-
-/*!
- \overload
-*/
-void QFormLayout::insertRow(int row, QWidget *label, QLayout *field)
-{
- Q_D(QFormLayout);
-
- row = d->insertRow(row);
- if (label)
- d->setWidget(row, LabelRole, label);
- if (field)
- d->setLayout(row, FieldRole, field);
- invalidate();
-}
-
-/*!
- \overload
-
- This overload automatically creates a QLabel behind the scenes
- with \a labelText as its text. The \a field is set as the new
- QLabel's \l{QLabel::setBuddy()}{buddy}.
-*/
-void QFormLayout::insertRow(int row, const QString &labelText, QWidget *field)
-{
- QLabel *label = 0;
- if (!labelText.isEmpty()) {
- label = new QLabel(labelText);
-#ifndef QT_NO_SHORTCUT
- label->setBuddy(field);
-#endif
- }
- insertRow(row, label, field);
-}
-
-/*!
- \overload
-
- This overload automatically creates a QLabel behind the scenes
- with \a labelText as its text.
-*/
-void QFormLayout::insertRow(int row, const QString &labelText, QLayout *field)
-{
- insertRow(row, labelText.isEmpty() ? 0 : new QLabel(labelText), field);
-}
-
-/*!
- \overload
-
- Inserts the specified \a widget at position \a row in this form
- layout. The \a widget spans both columns. If \a row is out of
- bounds, the widget is added at the end.
-*/
-void QFormLayout::insertRow(int row, QWidget *widget)
-{
- Q_D(QFormLayout);
-
- if (!widget) {
- qWarning("QFormLayout: Cannot add null field to %s", qPrintable(objectName()));
- return;
- }
-
- row = d->insertRow(row);
- d->setWidget(row, SpanningRole, widget);
- invalidate();
-}
-
-/*!
- \overload
-
- Inserts the specified \a layout at position \a row in this form
- layout. The \a layout spans both columns. If \a row is out of
- bounds, the widget is added at the end.
-*/
-void QFormLayout::insertRow(int row, QLayout *layout)
-{
- Q_D(QFormLayout);
-
- if (!layout) {
- qWarning("QFormLayout: Cannot add null field to %s", qPrintable(objectName()));
- return;
- }
-
- row = d->insertRow(row);
- d->setLayout(row, SpanningRole, layout);
- invalidate();
-}
-
-/*!
- \reimp
-*/
-void QFormLayout::addItem(QLayoutItem *item)
-{
- Q_D(QFormLayout);
-
- int row = d->insertRow(d->m_matrix.rowCount());
- d->setItem(row, FieldRole, item);
- invalidate();
-}
-
-/*!
- \reimp
-*/
-int QFormLayout::count() const
-{
- Q_D(const QFormLayout);
- return d->m_things.count();
-}
-
-/*!
- \reimp
-*/
-QLayoutItem *QFormLayout::itemAt(int index) const
-{
- Q_D(const QFormLayout);
- if (QFormLayoutItem *formItem = d->m_things.value(index))
- return formItem->item;
- return 0;
-}
-
-/*!
- \reimp
-*/
-QLayoutItem *QFormLayout::takeAt(int index)
-{
- Q_D(QFormLayout);
-
- const int storageIndex = storageIndexFromLayoutItem(d->m_matrix, d->m_things.value(index));
- if (storageIndex == -1) {
- qWarning("QFormLayout::takeAt: Invalid index %d", index);
- return 0;
- }
-
- int row, col;
- QFormLayoutPrivate::ItemMatrix::storageIndexToPosition(storageIndex, &row, &col);
- Q_ASSERT(d->m_matrix(row, col));
-
- QFormLayoutItem *item = d->m_matrix(row, col);
- Q_ASSERT(item);
- d->m_things.removeAt(index);
- d->m_matrix(row, col) = 0;
-
- invalidate();
-
- // grab ownership back from the QFormLayoutItem
- QLayoutItem *i = item->item;
- item->item = 0;
- delete item;
- return i;
-}
-
-/*!
- \reimp
-*/
-Qt::Orientations QFormLayout::expandingDirections() const
-{
- Q_D(const QFormLayout);
- QFormLayoutPrivate *e = const_cast<QFormLayoutPrivate *>(d);
- e->updateSizes();
-
- Qt::Orientations o = 0;
- if (e->expandHorizontal)
- o = Qt::Horizontal;
- if (e->expandVertical)
- o |= Qt::Vertical;
- return o;
-}
-
-/*!
- \reimp
-*/
-bool QFormLayout::hasHeightForWidth() const
-{
- Q_D(const QFormLayout);
- QFormLayoutPrivate *e = const_cast<QFormLayoutPrivate *>(d);
- e->updateSizes();
- return (d->has_hfw || rowWrapPolicy() == WrapLongRows);
-}
-
-/*!
- \reimp
-*/
-int QFormLayout::heightForWidth(int width) const
-{
- Q_D(const QFormLayout);
- if (!hasHeightForWidth())
- return -1;
-
- int leftMargin, topMargin, rightMargin, bottomMargin;
- getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
-
- int targetWidth = width - leftMargin - rightMargin;
-
- if (!d->haveHfwCached(targetWidth)) {
- QFormLayoutPrivate *dat = const_cast<QFormLayoutPrivate *>(d);
- dat->setupVerticalLayoutData(targetWidth);
- dat->setupHorizontalLayoutData(targetWidth);
- dat->recalcHFW(targetWidth);
- }
- if (targetWidth == d->sh_width)
- return d->hfw_sh_height + topMargin + bottomMargin;
- else
- return d->hfw_height + topMargin + bottomMargin;
-}
-
-/*!
- \reimp
-*/
-void QFormLayout::setGeometry(const QRect &rect)
-{
- Q_D(QFormLayout);
- if (d->dirty || rect != geometry()) {
- QRect cr = rect;
- int leftMargin, topMargin, rightMargin, bottomMargin;
- getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
- cr.adjust(+leftMargin, +topMargin, -rightMargin, -bottomMargin);
-
- bool hfw = hasHeightForWidth();
- d->setupVerticalLayoutData(cr.width());
- d->setupHorizontalLayoutData(cr.width());
- if (hfw && (!d->haveHfwCached(cr.width()) || d->hfwLayouts.size() != d->vLayoutCount))
- d->recalcHFW(cr.width());
- if (hfw) {
- qGeomCalc(d->hfwLayouts, 0, d->vLayoutCount, cr.y(), cr.height());
- d->arrangeWidgets(d->hfwLayouts, cr);
- } else {
- qGeomCalc(d->vLayouts, 0, d->vLayoutCount, cr.y(), cr.height());
- d->arrangeWidgets(d->vLayouts, cr);
- }
- QLayout::setGeometry(rect);
- }
-}
-
-/*!
- \reimp
-*/
-QSize QFormLayout::sizeHint() const
-{
- Q_D(const QFormLayout);
- if (!d->prefSize.isValid()) {
- QFormLayoutPrivate *dat = const_cast<QFormLayoutPrivate *>(d);
- dat->calcSizeHints();
- }
- return d->prefSize;
-}
-
-/*!
- \reimp
-*/
-QSize QFormLayout::minimumSize() const
-{
- // ### fix minimumSize if hfw
- Q_D(const QFormLayout);
- if (!d->minSize.isValid()) {
- QFormLayoutPrivate *dat = const_cast<QFormLayoutPrivate *>(d);
- dat->calcSizeHints();
- }
- return d->minSize;
-}
-
-/*!
- \reimp
-*/
-void QFormLayout::invalidate()
-{
- Q_D(QFormLayout);
- d->dirty = true;
- d->sizesDirty = true;
- d->minSize = QSize();
- d->prefSize = QSize();
- d->formMaxWidth = -1;
- d->hfw_width = -1;
- d->sh_width = -1;
- d->layoutWidth = -1;
- d->hfw_sh_height = -1;
- QLayout::invalidate();
-}
-
-/*!
- Returns the number of rows in the form.
-
- \sa QLayout::count()
-*/
-int QFormLayout::rowCount() const
-{
- Q_D(const QFormLayout);
- return d->m_matrix.rowCount();
-}
-
-/*!
- Returns the layout item in the given \a row with the specified \a
- role (column). Returns 0 if there is no such item.
-
- \sa QLayout::itemAt(), setItem()
-*/
-QLayoutItem *QFormLayout::itemAt(int row, ItemRole role) const
-{
- Q_D(const QFormLayout);
- if (uint(row) >= uint(d->m_matrix.rowCount()))
- return 0;
- switch (role) {
- case SpanningRole:
- if (QFormLayoutItem *item = d->m_matrix(row, 1))
- if (item->fullRow)
- return item->item;
- break;
- case LabelRole:
- case FieldRole:
- if (QFormLayoutItem *item = d->m_matrix(row, (role == LabelRole) ? 0 : 1))
- return item->item;
- break;
- }
- return 0;
-}
-
-/*!
- Retrieves the row and role (column) of the item at the specified
- \a index. If \a index is out of bounds, *\a rowPtr is set to -1;
- otherwise the row is stored in *\a rowPtr and the role is stored
- in *\a rolePtr.
-
- \sa itemAt(), count(), getLayoutPosition(), getWidgetPosition()
-*/
-void QFormLayout::getItemPosition(int index, int *rowPtr, ItemRole *rolePtr) const
-{
- Q_D(const QFormLayout);
- int col = -1;
- int row = -1;
-
- const int storageIndex = storageIndexFromLayoutItem(d->m_matrix, d->m_things.value(index));
- if (storageIndex != -1)
- QFormLayoutPrivate::ItemMatrix::storageIndexToPosition(storageIndex, &row, &col);
-
- if (rowPtr)
- *rowPtr = row;
- if (rolePtr && col != -1) {
- const bool spanning = col == 1 && d->m_matrix(row, col)->fullRow;
- if (spanning) {
- *rolePtr = SpanningRole;
- } else {
- *rolePtr = ItemRole(col);
- }
- }
-}
-
-/*!
- Retrieves the row and role (column) of the specified child \a
- layout. If \a layout is not in the form layout, *\a rowPtr is set
- to -1; otherwise the row is stored in *\a rowPtr and the role is stored
- in *\a rolePtr.
-*/
-void QFormLayout::getLayoutPosition(QLayout *layout, int *rowPtr, ItemRole *rolePtr) const
-{
- int n = count();
- int index = 0;
- while (index < n) {
- if (itemAt(index) == layout)
- break;
- ++index;
- }
- getItemPosition(index, rowPtr, rolePtr);
-}
-
-/*!
- Retrieves the row and role (column) of the specified \a widget in
- the layout. If \a widget is not in the layout, *\a rowPtr is set
- to -1; otherwise the row is stored in *\a rowPtr and the role is stored
- in *\a rolePtr.
-
- \sa getItemPosition(), itemAt()
-*/
-void QFormLayout::getWidgetPosition(QWidget *widget, int *rowPtr, ItemRole *rolePtr) const
-{
- getItemPosition(indexOf(widget), rowPtr, rolePtr);
-}
-
-// ### eliminate labelForField()
-
-/*!
- Returns the label associated with the given \a field.
-
- \sa itemAt()
-*/
-QWidget *QFormLayout::labelForField(QWidget *field) const
-{
- Q_D(const QFormLayout);
-
- int row;
- ItemRole role;
-
- getWidgetPosition(field, &row, &role);
-
- if (row != -1 && role == FieldRole) {
- if (QFormLayoutItem *label = d->m_matrix(row, LabelRole))
- return label->widget();
- }
- return 0;
-}
-
-/*!
- \overload
-*/
-QWidget *QFormLayout::labelForField(QLayout *field) const
-{
- Q_D(const QFormLayout);
-
- int row;
- ItemRole role;
-
- getLayoutPosition(field, &row, &role);
-
- if (row != -1 && role == FieldRole) {
- if (QFormLayoutItem *label = d->m_matrix(row, LabelRole))
- return label->widget();
- }
- return 0;
-}
-
-/*!
- \property QFormLayout::fieldGrowthPolicy
- \brief the way in which the form's fields grow
-
- The default value depends on the widget or application style. For
- QMacStyle, the default is FieldsStayAtSizeHint; for QCommonStyle
- derived styles (like Plastique and Windows), the default
- is ExpandingFieldsGrow; for Qt Extended styles, the default is
- AllNonFixedFieldsGrow.
-
- If none of the fields can grow and the form is resized, extra
- space is distributed according to the current
- \l{formAlignment}{form alignment}.
-
- \sa formAlignment, rowWrapPolicy
-*/
-
-void QFormLayout::setFieldGrowthPolicy(FieldGrowthPolicy policy)
-{
- Q_D(QFormLayout);
- if (FieldGrowthPolicy(d->fieldGrowthPolicy) != policy) {
- d->fieldGrowthPolicy = policy;
- invalidate();
- }
-}
-
-QFormLayout::FieldGrowthPolicy QFormLayout::fieldGrowthPolicy() const
-{
- Q_D(const QFormLayout);
- if (d->fieldGrowthPolicy == DefaultFieldGrowthPolicy) {
- return QFormLayout::FieldGrowthPolicy(d->getStyle()->styleHint(QStyle::SH_FormLayoutFieldGrowthPolicy));
- } else {
- return QFormLayout::FieldGrowthPolicy(d->fieldGrowthPolicy);
- }
-}
-
-/*!
- \property QFormLayout::rowWrapPolicy
- \brief the way in which the form's rows wrap
-
- The default value depends on the widget or application style. For
- Qt Extended styles and QS60Style, the default is WrapLongRows;
- for the other styles, the default is DontWrapRows.
-
- If you want to display each label above its associated field
- (instead of next to it), set this property to WrapAllRows.
-
- \sa fieldGrowthPolicy
-*/
-
-void QFormLayout::setRowWrapPolicy(RowWrapPolicy policy)
-{
- Q_D(QFormLayout);
- if (RowWrapPolicy(d->rowWrapPolicy) != policy) {
- d->rowWrapPolicy = policy;
- invalidate();
- }
-}
-
-QFormLayout::RowWrapPolicy QFormLayout::rowWrapPolicy() const
-{
- Q_D(const QFormLayout);
- if (d->rowWrapPolicy == DefaultRowWrapPolicy) {
- return QFormLayout::RowWrapPolicy(d->getStyle()->styleHint(QStyle::SH_FormLayoutWrapPolicy));
- } else {
- return QFormLayout::RowWrapPolicy(d->rowWrapPolicy);
- }
-}
-
-/*!
- \property QFormLayout::labelAlignment
- \brief the horizontal alignment of the labels
-
- The default value depends on the widget or application style. For
- QCommonStyle derived styles, except for QPlastiqueStyle, the
- default is Qt::AlignLeft; for the other styles, the default is
- Qt::AlignRight.
-
- \sa formAlignment
-*/
-
-void QFormLayout::setLabelAlignment(Qt::Alignment alignment)
-{
- Q_D(QFormLayout);
- if (d->labelAlignment != alignment) {
- d->labelAlignment = alignment;
- invalidate();
- }
-}
-
-Qt::Alignment QFormLayout::labelAlignment() const
-{
- Q_D(const QFormLayout);
- if (!d->labelAlignment) {
- return Qt::Alignment(d->getStyle()->styleHint(QStyle::SH_FormLayoutLabelAlignment));
- } else {
- return d->labelAlignment;
- }
-}
-
-/*!
- \property QFormLayout::formAlignment
- \brief the alignment of the form layout's contents within the layout's geometry
-
- The default value depends on the widget or application style. For
- QMacStyle, the default is Qt::AlignHCenter | Qt::AlignTop; for the
- other styles, the default is Qt::AlignLeft | Qt::AlignTop.
-
- \sa labelAlignment, rowWrapPolicy
-*/
-
-void QFormLayout::setFormAlignment(Qt::Alignment alignment)
-{
- Q_D(QFormLayout);
- if (d->formAlignment != alignment) {
- d->formAlignment = alignment;
- invalidate();
- }
-}
-
-Qt::Alignment QFormLayout::formAlignment() const
-{
- Q_D(const QFormLayout);
- if (!d->formAlignment) {
- return Qt::Alignment(d->getStyle()->styleHint(QStyle::SH_FormLayoutFormAlignment));
- } else {
- return d->formAlignment;
- }
-}
-
-/*!
- \property QFormLayout::horizontalSpacing
- \brief the spacing between widgets that are laid out side by side
-
- By default, if no value is explicitly set, the layout's horizontal
- spacing is inherited from the parent layout, or from the style settings
- for the parent widget.
-
- \sa verticalSpacing, QStyle::pixelMetric(), {QStyle::}{PM_LayoutHorizontalSpacing}
-*/
-void QFormLayout::setHorizontalSpacing(int spacing)
-{
- Q_D(QFormLayout);
- if (spacing != d->hSpacing) {
- d->hSpacing = spacing;
- invalidate();
- }
-}
-
-int QFormLayout::horizontalSpacing() const
-{
- Q_D(const QFormLayout);
- if (d->hSpacing >= 0) {
- return d->hSpacing;
- } else {
- return qSmartSpacing(this, QStyle::PM_LayoutHorizontalSpacing);
- }
-}
-
-/*!
- \property QFormLayout::verticalSpacing
- \brief the spacing between widgets that are laid out vertically
-
- By default, if no value is explicitly set, the layout's vertical spacing is
- inherited from the parent layout, or from the style settings for the parent
- widget.
-
- \sa horizontalSpacing, QStyle::pixelMetric(), {QStyle::}{PM_LayoutHorizontalSpacing}
-*/
-void QFormLayout::setVerticalSpacing(int spacing)
-{
- Q_D(QFormLayout);
- if (spacing != d->vSpacing) {
- d->vSpacing = spacing;
- invalidate();
- }
-}
-
-int QFormLayout::verticalSpacing() const
-{
- Q_D(const QFormLayout);
- if (d->vSpacing >= 0) {
- return d->vSpacing;
- } else {
- return qSmartSpacing(this, QStyle::PM_LayoutVerticalSpacing);
- }
-}
-
-/*!
- This function sets both the vertical and horizontal spacing to
- \a spacing.
-
- \sa setVerticalSpacing(), setHorizontalSpacing()
-*/
-void QFormLayout::setSpacing(int spacing)
-{
- Q_D(QFormLayout);
- d->vSpacing = d->hSpacing = spacing;
- invalidate();
-}
-
-/*!
- If the vertical spacing is equal to the horizontal spacing,
- this function returns that value; otherwise it returns -1.
-
- \sa setSpacing(), verticalSpacing(), horizontalSpacing()
-*/
-int QFormLayout::spacing() const
-{
- int hSpacing = horizontalSpacing();
- if (hSpacing == verticalSpacing()) {
- return hSpacing;
- } else {
- return -1;
- }
-}
-
-void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, QRect &rect)
-{
- Q_Q(QFormLayout);
-
- int i;
- const int rr = m_matrix.rowCount();
- QWidget *w = q->parentWidget();
- Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QApplication::layoutDirection();
-
- Qt::Alignment formAlignment = fixedAlignment(q->formAlignment(), layoutDirection);
- int leftOffset = 0;
- int delta = rect.width() - formMaxWidth;
- if (formAlignment & (Qt::AlignHCenter | Qt::AlignRight) && delta > 0) {
- leftOffset = delta;
- if (formAlignment & Qt::AlignHCenter)
- leftOffset >>= 1;
- }
-
- for (i = 0; i < rr; ++i) {
- QFormLayoutItem *label = m_matrix(i, 0);
- QFormLayoutItem *field = m_matrix(i, 1);
-
- if (label) {
- int height = layouts.at(label->vLayoutIndex).size;
- if ((label->expandingDirections() & Qt::Vertical) == 0) {
- /*
- If the field on the right-hand side is tall,
- we want the label to be top-aligned, but not too
- much. So we introduce a 7 / 4 factor so that it
- gets some extra pixels at the top.
- */
- height = qMin(height,
- qMin(label->sizeHint.height() * 7 / 4,
- label->maxSize.height()));
- }
-
- QSize sz(qMin(label->layoutWidth, label->sizeHint.width()), height);
- int x = leftOffset + rect.x() + label->layoutPos;
- if (fixedAlignment(q->labelAlignment(), layoutDirection) & Qt::AlignRight)
- x += label->layoutWidth - sz.width();
- QPoint p(x, layouts.at(label->vLayoutIndex).pos);
- // ### expansion & sizepolicy stuff
-
- label->setGeometry(QStyle::visualRect(layoutDirection, rect, QRect(p, sz)));
- }
-
- if (field) {
- QSize sz(field->layoutWidth, layouts.at(field->vLayoutIndex).size);
- QPoint p(field->layoutPos + leftOffset + rect.x(), layouts.at(field->vLayoutIndex).pos);
-/*
- if ((field->widget() && field->widget()->sizePolicy().horizontalPolicy() & (QSizePolicy::GrowFlag | QSizePolicy::ExpandFlag | QSizePolicy::IgnoreFlag))
- || (field->layout() && sz.width() < field->maxSize.width())) {
- sz.rwidth() = field->layoutWidth;
- }
-*/
- if (field->maxSize.isValid())
- sz = sz.boundedTo(field->maxSize);
-
- field->setGeometry(QStyle::visualRect(layoutDirection, rect, QRect(p, sz)));
- }
- }
-}
-
-/*!
- Sets the widget in the given \a row for the given \a role to \a widget, extending the
- layout with empty rows if necessary.
-
- If the cell is already occupied, the \a widget is not inserted and an error message is
- sent to the console.
-
- \bold{Note:} For most applications, addRow() or insertRow() should be used instead of setWidget().
-
- \sa setLayout()
-*/
-void QFormLayout::setWidget(int row, ItemRole role, QWidget *widget)
-{
- Q_D(QFormLayout);
- int rowCnt = rowCount();
- if (row >= rowCnt)
- d->insertRows(rowCnt, row - rowCnt + 1);
- d->setWidget(row, role, widget);
-}
-
-/*!
- Sets the sub-layout in the given \a row for the given \a role to \a layout, extending the
- form layout with empty rows if necessary.
-
- If the cell is already occupied, the \a layout is not inserted and an error message is
- sent to the console.
-
- \bold{Note:} For most applications, addRow() or insertRow() should be used instead of setLayout().
-
- \sa setWidget()
-*/
-void QFormLayout::setLayout(int row, ItemRole role, QLayout *layout)
-{
- Q_D(QFormLayout);
- int rowCnt = rowCount();
- if (row >= rowCnt)
- d->insertRows(rowCnt, row - rowCnt + 1);
- d->setLayout(row, role, layout);
-}
-
-/*!
- Sets the item in the given \a row for the given \a role to \a item, extending the
- layout with empty rows if necessary.
-
- If the cell is already occupied, the \a item is not inserted and an error message is
- sent to the console.
- The \a item spans both columns.
-
- \warning Do not use this function to add child layouts or child
- widget items. Use setLayout() or setWidget() instead.
-
- \sa setLayout()
-*/
-void QFormLayout::setItem(int row, ItemRole role, QLayoutItem *item)
-{
- Q_D(QFormLayout);
- int rowCnt = rowCount();
- if (row >= rowCnt)
- d->insertRows(rowCnt, row - rowCnt + 1);
- d->setItem(row, role, item);
-}
-
-/*!
- \internal
- */
-
-void QFormLayout::resetFieldGrowthPolicy()
-{
- Q_D(QFormLayout);
- d->fieldGrowthPolicy = DefaultFieldGrowthPolicy;
-}
-
-/*!
- \internal
- */
-
-void QFormLayout::resetRowWrapPolicy()
-{
- Q_D(QFormLayout);
- d->rowWrapPolicy = DefaultRowWrapPolicy;
-}
-
-/*!
- \internal
- */
-
-void QFormLayout::resetFormAlignment()
-{
- Q_D(QFormLayout);
- d->formAlignment = 0;
-}
-
-/*!
- \internal
- */
-
-void QFormLayout::resetLabelAlignment()
-{
- Q_D(QFormLayout);
- d->labelAlignment = 0;
-}
-
-#if 0
-void QFormLayout::dump() const
-{
- Q_D(const QFormLayout);
- for (int i = 0; i < rowCount(); ++i) {
- for (int j = 0; j < 2; ++j) {
- qDebug("m_matrix(%d, %d) = %p", i, j, d->m_matrix(i, j));
- }
- }
- for (int i = 0; i < d->m_things.count(); ++i)
- qDebug("m_things[%d] = %p", i, d->m_things.at(i));
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qformlayout.h b/src/gui/kernel/qformlayout.h
deleted file mode 100644
index f229ac2d83..0000000000
--- a/src/gui/kernel/qformlayout.h
+++ /dev/null
@@ -1,163 +0,0 @@
-/****************************************************************************
-**
-** 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 QFORMLAYOUT_H
-#define QFORMLAYOUT_H
-
-#include <QtGui/QLayout>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QFormLayoutPrivate;
-
-class Q_GUI_EXPORT QFormLayout : public QLayout
-{
- Q_OBJECT
- Q_ENUMS(FormStyle FieldGrowthPolicy RowWrapPolicy ItemRole)
- Q_DECLARE_PRIVATE(QFormLayout)
- Q_PROPERTY(FieldGrowthPolicy fieldGrowthPolicy READ fieldGrowthPolicy WRITE setFieldGrowthPolicy RESET resetFieldGrowthPolicy)
- Q_PROPERTY(RowWrapPolicy rowWrapPolicy READ rowWrapPolicy WRITE setRowWrapPolicy RESET resetRowWrapPolicy)
- Q_PROPERTY(Qt::Alignment labelAlignment READ labelAlignment WRITE setLabelAlignment RESET resetLabelAlignment)
- Q_PROPERTY(Qt::Alignment formAlignment READ formAlignment WRITE setFormAlignment RESET resetFormAlignment)
- Q_PROPERTY(int horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing)
- Q_PROPERTY(int verticalSpacing READ verticalSpacing WRITE setVerticalSpacing)
-
-public:
- enum FieldGrowthPolicy {
- FieldsStayAtSizeHint,
- ExpandingFieldsGrow,
- AllNonFixedFieldsGrow
- };
-
- enum RowWrapPolicy {
- DontWrapRows,
- WrapLongRows,
- WrapAllRows
- };
-
- enum ItemRole {
- LabelRole = 0,
- FieldRole = 1,
- SpanningRole = 2
- };
-
- explicit QFormLayout(QWidget *parent = 0);
- ~QFormLayout();
-
- void setFieldGrowthPolicy(FieldGrowthPolicy policy);
- FieldGrowthPolicy fieldGrowthPolicy() const;
- void setRowWrapPolicy(RowWrapPolicy policy);
- RowWrapPolicy rowWrapPolicy() const;
- void setLabelAlignment(Qt::Alignment alignment);
- Qt::Alignment labelAlignment() const;
- void setFormAlignment(Qt::Alignment alignment);
- Qt::Alignment formAlignment() const;
-
- void setHorizontalSpacing(int spacing);
- int horizontalSpacing() const;
- void setVerticalSpacing(int spacing);
- int verticalSpacing() const;
-
- int spacing() const;
- void setSpacing(int);
-
- void addRow(QWidget *label, QWidget *field);
- void addRow(QWidget *label, QLayout *field);
- void addRow(const QString &labelText, QWidget *field);
- void addRow(const QString &labelText, QLayout *field);
- void addRow(QWidget *widget);
- void addRow(QLayout *layout);
-
- void insertRow(int row, QWidget *label, QWidget *field);
- void insertRow(int row, QWidget *label, QLayout *field);
- void insertRow(int row, const QString &labelText, QWidget *field);
- void insertRow(int row, const QString &labelText, QLayout *field);
- void insertRow(int row, QWidget *widget);
- void insertRow(int row, QLayout *layout);
-
- void setItem(int row, ItemRole role, QLayoutItem *item);
- void setWidget(int row, ItemRole role, QWidget *widget);
- void setLayout(int row, ItemRole role, QLayout *layout);
-
- QLayoutItem *itemAt(int row, ItemRole role) const;
- void getItemPosition(int index, int *rowPtr, ItemRole *rolePtr) const;
- void getWidgetPosition(QWidget *widget, int *rowPtr, ItemRole *rolePtr) const;
- void getLayoutPosition(QLayout *layout, int *rowPtr, ItemRole *rolePtr) const;
- QWidget *labelForField(QWidget *field) const;
- QWidget *labelForField(QLayout *field) const;
-
- // reimplemented from QLayout
- void addItem(QLayoutItem *item);
- QLayoutItem *itemAt(int index) const;
- QLayoutItem *takeAt(int index);
-
- void setGeometry(const QRect &rect);
- QSize minimumSize() const;
- QSize sizeHint() const;
- void invalidate();
-
- bool hasHeightForWidth() const;
- int heightForWidth(int width) const;
- Qt::Orientations expandingDirections() const;
- int count() const;
-
- int rowCount() const;
-
-#if 0
- void dump() const;
-#endif
-
-private:
- void resetFieldGrowthPolicy();
- void resetRowWrapPolicy();
- void resetLabelAlignment();
- void resetFormAlignment();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/kernel/qgesture.cpp b/src/gui/kernel/qgesture.cpp
deleted file mode 100644
index daabe4f436..0000000000
--- a/src/gui/kernel/qgesture.cpp
+++ /dev/null
@@ -1,1118 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgesture.h"
-#include "private/qgesture_p.h"
-#include "private/qstandardgestures_p.h"
-#include "qgraphicsview.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
- /*!
- \class QGesture
- \since 4.6
- \ingroup gestures
-
- \brief The QGesture class represents a gesture, containing properties that
- describe the corresponding user input.
-
- Gesture objects are not constructed directly by developers. They are created by
- the QGestureRecognizer object that is registered with the application; see
- QGestureRecognizer::registerRecognizer().
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \section1 Gesture Properties
-
- The class has a list of properties that can be queried by the user to get
- some gesture-specific arguments. For example, the pinch gesture has a scale
- factor that is exposed as a property.
-
- Developers of custom gesture recognizers can add additional properties in
- order to provide additional information about a gesture. This can be done
- by adding new dynamic properties to a QGesture object, or by subclassing
- the QGesture class (or one of its subclasses).
-
- \section1 Lifecycle of a Gesture Object
-
- A QGesture instance is implicitly created when needed and is owned by Qt.
- Developers should never destroy them or store them for later use as Qt may
- destroy particular instances of them and create new ones to replace them.
-
- The registered gesture recognizer monitors the input events for the target
- object via its \l{QGestureRecognizer::}{recognize()} function, updating the
- properties of the gesture object as required.
-
- The gesture object may be delivered to the target object in a QGestureEvent if
- the corresponding gesture is active or has just been canceled. Each event that
- is delivered contains a list of gesture objects, since support for more than
- one gesture may be enabled for the target object. Due to the way events are
- handled in Qt, gesture events may be filtered by other objects.
-
- \sa QGestureEvent, QGestureRecognizer
-*/
-
-/*!
- Constructs a new gesture object with the given \a parent.
-
- QGesture objects are created by gesture recognizers in the
- QGestureRecognizer::create() function.
-*/
-QGesture::QGesture(QObject *parent)
- : QObject(*new QGesturePrivate, parent)
-{
- d_func()->gestureType = Qt::CustomGesture;
-}
-
-/*!
- \internal
-*/
-QGesture::QGesture(QGesturePrivate &dd, QObject *parent)
- : QObject(dd, parent)
-{
-}
-
-/*!
- Destroys the gesture object.
-*/
-QGesture::~QGesture()
-{
-}
-
-/*!
- \property QGesture::state
- \brief the current state of the gesture
-*/
-
-/*!
- \property QGesture::gestureType
- \brief the type of the gesture
-*/
-
-/*!
- \property QGesture::hotSpot
-
- \brief The point that is used to find the receiver for the gesture event.
-
- The hot-spot is a point in the global coordinate system, use
- QWidget::mapFromGlobal() or QGestureEvent::mapToGraphicsScene() to get a
- local hot-spot.
-
- The hot-spot should be set by the gesture recognizer to allow gesture event
- delivery to a QGraphicsObject.
-*/
-
-/*!
- \property QGesture::hasHotSpot
- \brief whether the gesture has a hot-spot
-*/
-
-Qt::GestureType QGesture::gestureType() const
-{
- return d_func()->gestureType;
-}
-
-Qt::GestureState QGesture::state() const
-{
- return d_func()->state;
-}
-
-QPointF QGesture::hotSpot() const
-{
- return d_func()->hotSpot;
-}
-
-void QGesture::setHotSpot(const QPointF &value)
-{
- Q_D(QGesture);
- d->hotSpot = value;
- d->isHotSpotSet = true;
-}
-
-bool QGesture::hasHotSpot() const
-{
- return d_func()->isHotSpotSet;
-}
-
-void QGesture::unsetHotSpot()
-{
- d_func()->isHotSpotSet = false;
-}
-
-/*!
- \property QGesture::gestureCancelPolicy
- \brief the policy for deciding what happens on accepting a gesture
-
- On accepting one gesture Qt can automatically cancel other gestures
- that belong to other targets. The policy is normally set to not cancel
- any other gestures and can be set to cancel all active gestures in the
- context. For example for all child widgets.
-*/
-
-/*!
- \enum QGesture::GestureCancelPolicy
-
- This enum describes how accepting a gesture can cancel other gestures
- automatically.
-
- \value CancelNone On accepting this gesture no other gestures will be affected.
-
- \value CancelAllInContext On accepting this gesture all gestures that are
- active in the context (respecting the Qt::GestureFlag that were specified
- when subscribed to the gesture) will be cancelled.
-*/
-
-void QGesture::setGestureCancelPolicy(GestureCancelPolicy policy)
-{
- Q_D(QGesture);
- d->gestureCancelPolicy = static_cast<uint>(policy);
-}
-
-QGesture::GestureCancelPolicy QGesture::gestureCancelPolicy() const
-{
- Q_D(const QGesture);
- return static_cast<GestureCancelPolicy>(d->gestureCancelPolicy);
-}
-
-/*!
- \class QPanGesture
- \since 4.6
- \brief The QPanGesture class describes a panning gesture made by the user.
- \ingroup gestures
-
- \image pangesture.png
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \sa QPinchGesture, QSwipeGesture
-*/
-
-/*!
- \property QPanGesture::lastOffset
- \brief the last offset recorded for this gesture
-
- The last offset contains the change in position of the user's input as
- reported in the \l offset property when a previous gesture event was
- delivered for this gesture.
-
- If no previous event was delivered with information about this gesture
- (i.e., this gesture object contains information about the first movement
- in the gesture) then this property contains a zero size.
-*/
-
-/*!
- \property QPanGesture::offset
- \brief the total offset from the first input position to the current input
- position
-
- The offset measures the total change in position of the user's input
- covered by the gesture on the input device.
-*/
-
-/*!
- \property QPanGesture::delta
- \brief the offset from the previous input position to the current input
-
- This is essentially the same as the difference between offset() and
- lastOffset().
-*/
-
-/*!
- \property QPanGesture::acceleration
- \brief the acceleration in the motion of the touch point for this gesture
-*/
-
-/*!
- \property QPanGesture::horizontalVelocity
- \brief the horizontal component of the motion of the touch point for this
- gesture
- \since 4.7.1
- \internal
-
- \sa verticalVelocity, acceleration
-*/
-
-/*!
- \property QPanGesture::verticalVelocity
- \brief the vertical component of the motion of the touch point for this
- gesture
- \since 4.7.1
- \internal
-
- \sa horizontalVelocity, acceleration
-*/
-
-/*!
- \internal
-*/
-QPanGesture::QPanGesture(QObject *parent)
- : QGesture(*new QPanGesturePrivate, parent)
-{
- d_func()->gestureType = Qt::PanGesture;
-}
-
-
-QPointF QPanGesture::lastOffset() const
-{
- return d_func()->lastOffset;
-}
-
-QPointF QPanGesture::offset() const
-{
- return d_func()->offset;
-}
-
-QPointF QPanGesture::delta() const
-{
- Q_D(const QPanGesture);
- return d->offset - d->lastOffset;
-}
-
-qreal QPanGesture::acceleration() const
-{
- return d_func()->acceleration;
-}
-
-void QPanGesture::setLastOffset(const QPointF &value)
-{
- d_func()->lastOffset = value;
-}
-
-void QPanGesture::setOffset(const QPointF &value)
-{
- d_func()->offset = value;
-}
-
-void QPanGesture::setAcceleration(qreal value)
-{
- d_func()->acceleration = value;
-}
-
-/*!
- \class QPinchGesture
- \since 4.6
- \brief The QPinchGesture class describes a pinch gesture made by the user.
- \ingroup touch
- \ingroup gestures
-
- A pinch gesture is a form of touch user input in which the user typically
- touches two points on the input device with a thumb and finger, before moving
- them closer together or further apart to change the scale factor, zoom, or level
- of detail of the user interface.
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \image pinchgesture.png
-
- Instead of repeatedly applying the same pinching gesture, the user may
- continue to touch the input device in one place, and apply a second touch
- to a new point, continuing the gesture. When this occurs, gesture events
- will continue to be delivered to the target object, containing an instance
- of QPinchGesture in the Qt::GestureUpdated state.
-
- \sa QPanGesture, QSwipeGesture
-*/
-
-/*!
- \enum QPinchGesture::ChangeFlag
-
- This enum describes the changes that can occur to the properties of
- the gesture object.
-
- \value ScaleFactorChanged The scale factor held by scaleFactor changed.
- \value RotationAngleChanged The rotation angle held by rotationAngle changed.
- \value CenterPointChanged The center point held by centerPoint changed.
-
- \sa changeFlags, totalChangeFlags
-*/
-
-/*!
- \property QPinchGesture::totalChangeFlags
- \brief the property of the gesture that has change
-
- This property indicates which of the other properties has changed since the
- gesture has started. You can use this information to determine which aspect
- of your user interface needs to be updated.
-
- \sa changeFlags, scaleFactor, rotationAngle, centerPoint
-*/
-
-/*!
- \property QPinchGesture::changeFlags
- \brief the property of the gesture that has changed in the current step
-
- This property indicates which of the other properties has changed since
- the previous gesture event included information about this gesture. You
- can use this information to determine which aspect of your user interface
- needs to be updated.
-
- \sa totalChangeFlags, scaleFactor, rotationAngle, centerPoint
-*/
-
-/*!
- \property QPinchGesture::totalScaleFactor
- \brief the total scale factor
-
- The total scale factor measures the total change in scale factor from the
- original value to the current scale factor.
-
- \sa scaleFactor, lastScaleFactor
-*/
-/*!
- \property QPinchGesture::lastScaleFactor
- \brief the last scale factor recorded for this gesture
-
- The last scale factor contains the scale factor reported in the
- \l scaleFactor property when a previous gesture event included
- information about this gesture.
-
- If no previous event was delivered with information about this gesture
- (i.e., this gesture object contains information about the first movement
- in the gesture) then this property contains zero.
-
- \sa scaleFactor, totalScaleFactor
-*/
-/*!
- \property QPinchGesture::scaleFactor
- \brief the current scale factor
-
- The scale factor measures the scale factor associated with the distance
- between two of the user's inputs on a touch device.
-
- \sa totalScaleFactor, lastScaleFactor
-*/
-
-/*!
- \property QPinchGesture::totalRotationAngle
- \brief the total angle covered by the gesture
-
- This total angle measures the complete angle covered by the gesture. Usually, this
- is equal to the value held by the \l rotationAngle property, except in the case where
- the user performs multiple rotations by removing and repositioning one of the touch
- points, as described above. In this case, the total angle will be the sum of the
- rotation angles for the multiple stages of the gesture.
-
- \sa rotationAngle, lastRotationAngle
-*/
-/*!
- \property QPinchGesture::lastRotationAngle
- \brief the last reported angle covered by the gesture motion
-
- The last rotation angle is the angle as reported in the \l rotationAngle property
- when a previous gesture event was delivered for this gesture.
-
- \sa rotationAngle, totalRotationAngle
-*/
-/*!
- \property QPinchGesture::rotationAngle
- \brief the angle covered by the gesture motion
-
- \sa totalRotationAngle, lastRotationAngle
-*/
-
-/*!
- \property QPinchGesture::startCenterPoint
- \brief the starting position of the center point
-
- \sa centerPoint, lastCenterPoint
-*/
-/*!
- \property QPinchGesture::lastCenterPoint
- \brief the last position of the center point recorded for this gesture
-
- \sa centerPoint, startCenterPoint
-*/
-/*!
- \property QPinchGesture::centerPoint
- \brief the current center point
-
- The center point is the midpoint between the two input points in the gesture.
-
- \sa startCenterPoint, lastCenterPoint
-*/
-
-/*!
- \internal
-*/
-QPinchGesture::QPinchGesture(QObject *parent)
- : QGesture(*new QPinchGesturePrivate, parent)
-{
- d_func()->gestureType = Qt::PinchGesture;
-}
-
-QPinchGesture::ChangeFlags QPinchGesture::totalChangeFlags() const
-{
- return d_func()->totalChangeFlags;
-}
-
-void QPinchGesture::setTotalChangeFlags(QPinchGesture::ChangeFlags value)
-{
- d_func()->totalChangeFlags = value;
-}
-
-QPinchGesture::ChangeFlags QPinchGesture::changeFlags() const
-{
- return d_func()->changeFlags;
-}
-
-void QPinchGesture::setChangeFlags(QPinchGesture::ChangeFlags value)
-{
- d_func()->changeFlags = value;
-}
-
-QPointF QPinchGesture::startCenterPoint() const
-{
- return d_func()->startCenterPoint;
-}
-
-QPointF QPinchGesture::lastCenterPoint() const
-{
- return d_func()->lastCenterPoint;
-}
-
-QPointF QPinchGesture::centerPoint() const
-{
- return d_func()->centerPoint;
-}
-
-void QPinchGesture::setStartCenterPoint(const QPointF &value)
-{
- d_func()->startCenterPoint = value;
-}
-
-void QPinchGesture::setLastCenterPoint(const QPointF &value)
-{
- d_func()->lastCenterPoint = value;
-}
-
-void QPinchGesture::setCenterPoint(const QPointF &value)
-{
- d_func()->centerPoint = value;
-}
-
-
-qreal QPinchGesture::totalScaleFactor() const
-{
- return d_func()->totalScaleFactor;
-}
-
-qreal QPinchGesture::lastScaleFactor() const
-{
- return d_func()->lastScaleFactor;
-}
-
-qreal QPinchGesture::scaleFactor() const
-{
- return d_func()->scaleFactor;
-}
-
-void QPinchGesture::setTotalScaleFactor(qreal value)
-{
- d_func()->totalScaleFactor = value;
-}
-
-void QPinchGesture::setLastScaleFactor(qreal value)
-{
- d_func()->lastScaleFactor = value;
-}
-
-void QPinchGesture::setScaleFactor(qreal value)
-{
- d_func()->scaleFactor = value;
-}
-
-
-qreal QPinchGesture::totalRotationAngle() const
-{
- return d_func()->totalRotationAngle;
-}
-
-qreal QPinchGesture::lastRotationAngle() const
-{
- return d_func()->lastRotationAngle;
-}
-
-qreal QPinchGesture::rotationAngle() const
-{
- return d_func()->rotationAngle;
-}
-
-void QPinchGesture::setTotalRotationAngle(qreal value)
-{
- d_func()->totalRotationAngle = value;
-}
-
-void QPinchGesture::setLastRotationAngle(qreal value)
-{
- d_func()->lastRotationAngle = value;
-}
-
-void QPinchGesture::setRotationAngle(qreal value)
-{
- d_func()->rotationAngle = value;
-}
-
-/*!
- \class QSwipeGesture
- \since 4.6
- \brief The QSwipeGesture class describes a swipe gesture made by the user.
- \ingroup gestures
-
- \image swipegesture.png
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \sa QPanGesture, QPinchGesture
-*/
-
-/*!
- \enum QSwipeGesture::SwipeDirection
-
- This enum describes the possible directions for the gesture's motion
- along the horizontal and vertical axes.
-
- \value NoDirection The gesture had no motion associated with it on a particular axis.
- \value Left The gesture involved a horizontal motion to the left.
- \value Right The gesture involved a horizontal motion to the right.
- \value Up The gesture involved an upward vertical motion.
- \value Down The gesture involved a downward vertical motion.
-*/
-
-/*!
- \property QSwipeGesture::horizontalDirection
- \brief the horizontal direction of the gesture
-
- If the gesture has a horizontal component, the horizontal direction
- is either Left or Right; otherwise, it is NoDirection.
-
- \sa verticalDirection, swipeAngle
-*/
-
-/*!
- \property QSwipeGesture::verticalDirection
- \brief the vertical direction of the gesture
-
- If the gesture has a vertical component, the vertical direction
- is either Up or Down; otherwise, it is NoDirection.
-
- \sa horizontalDirection, swipeAngle
-*/
-
-/*!
- \property QSwipeGesture::swipeAngle
- \brief the angle of the motion associated with the gesture
-
- If the gesture has either a horizontal or vertical component, the
- swipe angle describes the angle between the direction of motion and the
- x-axis as defined using the standard widget
- \l{Coordinate System}{coordinate system}.
-
- \sa horizontalDirection, verticalDirection
-*/
-
-/*!
- \property QSwipeGesture::velocity
- \since 4.7.1
- \internal
-*/
-
-/*!
- \internal
-*/
-QSwipeGesture::QSwipeGesture(QObject *parent)
- : QGesture(*new QSwipeGesturePrivate, parent)
-{
- d_func()->gestureType = Qt::SwipeGesture;
-}
-
-QSwipeGesture::SwipeDirection QSwipeGesture::horizontalDirection() const
-{
- Q_D(const QSwipeGesture);
- if (d->swipeAngle < 0 || d->swipeAngle == 90 || d->swipeAngle == 270)
- return QSwipeGesture::NoDirection;
- else if (d->swipeAngle < 90 || d->swipeAngle > 270)
- return QSwipeGesture::Right;
- else
- return QSwipeGesture::Left;
-}
-
-QSwipeGesture::SwipeDirection QSwipeGesture::verticalDirection() const
-{
- Q_D(const QSwipeGesture);
- if (d->swipeAngle <= 0 || d->swipeAngle == 180)
- return QSwipeGesture::NoDirection;
- else if (d->swipeAngle < 180)
- return QSwipeGesture::Up;
- else
- return QSwipeGesture::Down;
-}
-
-qreal QSwipeGesture::swipeAngle() const
-{
- return d_func()->swipeAngle;
-}
-
-void QSwipeGesture::setSwipeAngle(qreal value)
-{
- d_func()->swipeAngle = value;
-}
-
-/*!
- \class QTapGesture
- \since 4.6
- \brief The QTapGesture class describes a tap gesture made by the user.
- \ingroup gestures
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \sa QPanGesture, QPinchGesture
-*/
-
-/*!
- \property QTapGesture::position
- \brief the position of the tap
-*/
-
-/*!
- \internal
-*/
-QTapGesture::QTapGesture(QObject *parent)
- : QGesture(*new QTapGesturePrivate, parent)
-{
- d_func()->gestureType = Qt::TapGesture;
-}
-
-QPointF QTapGesture::position() const
-{
- return d_func()->position;
-}
-
-void QTapGesture::setPosition(const QPointF &value)
-{
- d_func()->position = value;
-}
-/*!
- \class QTapAndHoldGesture
- \since 4.6
- \brief The QTapAndHoldGesture class describes a tap-and-hold (aka LongTap)
- gesture made by the user.
- \ingroup gestures
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \sa QPanGesture, QPinchGesture
-*/
-
-/*!
- \property QTapAndHoldGesture::position
- \brief the position of the tap
-*/
-
-/*!
- \internal
-*/
-QTapAndHoldGesture::QTapAndHoldGesture(QObject *parent)
- : QGesture(*new QTapAndHoldGesturePrivate, parent)
-{
- d_func()->gestureType = Qt::TapAndHoldGesture;
-}
-
-QPointF QTapAndHoldGesture::position() const
-{
- return d_func()->position;
-}
-
-void QTapAndHoldGesture::setPosition(const QPointF &value)
-{
- d_func()->position = value;
-}
-
-/*!
- Set the timeout, in milliseconds, before the gesture triggers.
-
- The recognizer will detect a touch down and and if \a msecs
- later the touch is still down, it will trigger the QTapAndHoldGesture.
- The default value is 700 milliseconds.
-*/
-// static
-void QTapAndHoldGesture::setTimeout(int msecs)
-{
- QTapAndHoldGesturePrivate::Timeout = msecs;
-}
-
-/*!
- Gets the timeout, in milliseconds, before the gesture triggers.
-
- The recognizer will detect a touch down and and if timeout()
- later the touch is still down, it will trigger the QTapAndHoldGesture.
- The default value is 700 milliseconds.
-*/
-// static
-int QTapAndHoldGesture::timeout()
-{
- return QTapAndHoldGesturePrivate::Timeout;
-}
-
-int QTapAndHoldGesturePrivate::Timeout = 700; // in ms
-
-
-/*!
- \class QGestureEvent
- \since 4.6
- \ingroup events
- \ingroup gestures
-
- \brief The QGestureEvent class provides the description of triggered gestures.
-
- The QGestureEvent class contains a list of gestures, which can be obtained using the
- gestures() function.
-
- The gestures are either active or canceled. A list of those that are currently being
- executed can be obtained using the activeGestures() function. A list of those which
- were previously active and have been canceled can be accessed using the
- canceledGestures() function. A gesture might be canceled if the current window loses
- focus, for example, or because of a timeout, or for other reasons.
-
- If the event handler does not accept the event by calling the generic
- QEvent::accept() function, all individual QGesture object that were not
- accepted and in the Qt::GestureStarted state will be propagated up the
- parent widget chain until a widget accepts them individually, by calling
- QGestureEvent::accept() for each of them, or an event filter consumes the
- event.
-
- \section1 Further Reading
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \sa QGesture, QGestureRecognizer,
- QWidget::grabGesture(), QGraphicsObject::grabGesture()
-*/
-
-/*!
- Creates new QGestureEvent containing a list of \a gestures.
-*/
-QGestureEvent::QGestureEvent(const QList<QGesture *> &gestures)
- : QEvent(QEvent::Gesture)
-{
- d = reinterpret_cast<QEventPrivate *>(new QGestureEventPrivate(gestures));
-}
-
-/*!
- Destroys QGestureEvent.
-*/
-QGestureEvent::~QGestureEvent()
-{
- delete reinterpret_cast<QGestureEventPrivate *>(d);
-}
-
-/*!
- Returns all gestures that are delivered in the event.
-*/
-QList<QGesture *> QGestureEvent::gestures() const
-{
- return d_func()->gestures;
-}
-
-/*!
- Returns a gesture object by \a type.
-*/
-QGesture *QGestureEvent::gesture(Qt::GestureType type) const
-{
- const QGestureEventPrivate *d = d_func();
- for(int i = 0; i < d->gestures.size(); ++i)
- if (d->gestures.at(i)->gestureType() == type)
- return d->gestures.at(i);
- return 0;
-}
-
-/*!
- Returns a list of active (not canceled) gestures.
-*/
-QList<QGesture *> QGestureEvent::activeGestures() const
-{
- QList<QGesture *> gestures;
- foreach (QGesture *gesture, d_func()->gestures) {
- if (gesture->state() != Qt::GestureCanceled)
- gestures.append(gesture);
- }
- return gestures;
-}
-
-/*!
- Returns a list of canceled gestures.
-*/
-QList<QGesture *> QGestureEvent::canceledGestures() const
-{
- QList<QGesture *> gestures;
- foreach (QGesture *gesture, d_func()->gestures) {
- if (gesture->state() == Qt::GestureCanceled)
- gestures.append(gesture);
- }
- return gestures;
-}
-
-/*!
- Sets the accept flag of the given \a gesture object to the specified \a value.
-
- Setting the accept flag indicates that the event receiver wants the \a gesture.
- Unwanted gestures may be propagated to the parent widget.
-
- By default, gestures in events of type QEvent::Gesture are accepted, and
- gestures in QEvent::GestureOverride events are ignored.
-
- For convenience, the accept flag can also be set with
- \l{QGestureEvent::accept()}{accept(gesture)}, and cleared with
- \l{QGestureEvent::ignore()}{ignore(gesture)}.
-*/
-void QGestureEvent::setAccepted(QGesture *gesture, bool value)
-{
- if (gesture)
- setAccepted(gesture->gestureType(), value);
-}
-
-/*!
- Sets the accept flag of the given \a gesture object, the equivalent of calling
- \l{QGestureEvent::setAccepted()}{setAccepted(gesture, true)}.
-
- Setting the accept flag indicates that the event receiver wants the
- gesture. Unwanted gestures may be propagated to the parent widget.
-
- \sa QGestureEvent::ignore()
-*/
-void QGestureEvent::accept(QGesture *gesture)
-{
- if (gesture)
- setAccepted(gesture->gestureType(), true);
-}
-
-/*!
- Clears the accept flag parameter of the given \a gesture object, the equivalent
- of calling \l{QGestureEvent::setAccepted()}{setAccepted(gesture, false)}.
-
- Clearing the accept flag indicates that the event receiver does not
- want the gesture. Unwanted gestures may be propagated to the parent widget.
-
- \sa QGestureEvent::accept()
-*/
-void QGestureEvent::ignore(QGesture *gesture)
-{
- if (gesture)
- setAccepted(gesture->gestureType(), false);
-}
-
-/*!
- Returns true if the \a gesture is accepted; otherwise returns false.
-*/
-bool QGestureEvent::isAccepted(QGesture *gesture) const
-{
- return gesture ? isAccepted(gesture->gestureType()) : false;
-}
-
-/*!
- Sets the accept flag of the given \a gestureType object to the specified
- \a value.
-
- Setting the accept flag indicates that the event receiver wants to receive
- gestures of the specified type, \a gestureType. Unwanted gestures may be
- propagated to the parent widget.
-
- By default, gestures in events of type QEvent::Gesture are accepted, and
- gestures in QEvent::GestureOverride events are ignored.
-
- For convenience, the accept flag can also be set with
- \l{QGestureEvent::accept()}{accept(gestureType)}, and cleared with
- \l{QGestureEvent::ignore()}{ignore(gestureType)}.
-*/
-void QGestureEvent::setAccepted(Qt::GestureType gestureType, bool value)
-{
- setAccepted(false);
- d_func()->accepted[gestureType] = value;
-}
-
-/*!
- Sets the accept flag of the given \a gestureType, the equivalent of calling
- \l{QGestureEvent::setAccepted()}{setAccepted(gestureType, true)}.
-
- Setting the accept flag indicates that the event receiver wants the
- gesture. Unwanted gestures may be propagated to the parent widget.
-
- \sa QGestureEvent::ignore()
-*/
-void QGestureEvent::accept(Qt::GestureType gestureType)
-{
- setAccepted(gestureType, true);
-}
-
-/*!
- Clears the accept flag parameter of the given \a gestureType, the equivalent
- of calling \l{QGestureEvent::setAccepted()}{setAccepted(gesture, false)}.
-
- Clearing the accept flag indicates that the event receiver does not
- want the gesture. Unwanted gestures may be propgated to the parent widget.
-
- \sa QGestureEvent::accept()
-*/
-void QGestureEvent::ignore(Qt::GestureType gestureType)
-{
- setAccepted(gestureType, false);
-}
-
-/*!
- Returns true if the gesture of type \a gestureType is accepted; otherwise
- returns false.
-*/
-bool QGestureEvent::isAccepted(Qt::GestureType gestureType) const
-{
- return d_func()->accepted.value(gestureType, true);
-}
-
-/*!
- \internal
-
- Sets the widget for this event to the \a widget specified.
-*/
-void QGestureEvent::setWidget(QWidget *widget)
-{
- d_func()->widget = widget;
-}
-
-/*!
- Returns the widget on which the event occurred.
-*/
-QWidget *QGestureEvent::widget() const
-{
- return d_func()->widget;
-}
-
-#ifndef QT_NO_GRAPHICSVIEW
-/*!
- Returns the scene-local coordinates if the \a gesturePoint is inside a
- graphics view.
-
- This functional might be useful when the gesture event is delivered to a
- QGraphicsObject to translate a point in screen coordinates to scene-local
- coordinates.
-
- \sa QPointF::isNull().
-*/
-QPointF QGestureEvent::mapToGraphicsScene(const QPointF &gesturePoint) const
-{
- QWidget *w = widget();
- if (w) // we get the viewport as widget, not the graphics view
- w = w->parentWidget();
- QGraphicsView *view = qobject_cast<QGraphicsView*>(w);
- if (view) {
- return view->mapToScene(view->mapFromGlobal(gesturePoint.toPoint()));
- }
- return QPointF();
-}
-#endif //QT_NO_GRAPHICSVIEW
-
-/*!
- \internal
-*/
-QGestureEventPrivate *QGestureEvent::d_func()
-{
- return reinterpret_cast<QGestureEventPrivate *>(d);
-}
-
-/*!
- \internal
-*/
-const QGestureEventPrivate *QGestureEvent::d_func() const
-{
- return reinterpret_cast<const QGestureEventPrivate *>(d);
-}
-
-#ifdef Q_NO_USING_KEYWORD
-/*!
- \fn void QGestureEvent::setAccepted(bool accepted)
-
- Sets or clears the event's internal flag that determines whether it should
- be delivered to other objects.
-
- Calling this function with a value of true for \a accepted indicates that the
- caller has accepted the event and that it should not be propagated further.
- Calling this function with a value of false indicates that the caller has
- ignored the event and that it should be delivered to other objects.
-
- For convenience, the accept flag can also be set with accept(), and cleared
- with ignore().
-
- \sa QEvent::accepted
-*/
-/*!
- \fn bool QGestureEvent::isAccepted() const
-
- Returns true is the event has been accepted; otherwise returns false.
-
- \sa QEvent::accepted
-*/
-/*!
- \fn void QGestureEvent::accept()
-
- Accepts the event, the equivalent of calling setAccepted(true).
-
- \sa QEvent::accept()
-*/
-/*!
- \fn void QGestureEvent::ignore()
-
- Ignores the event, the equivalent of calling setAccepted(false).
-
- \sa QEvent::ignore()
-*/
-#endif
-
-QT_END_NAMESPACE
-
-#include <moc_qgesture.cpp>
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/kernel/qgesture.h b/src/gui/kernel/qgesture.h
deleted file mode 100644
index 78fd2e47f1..0000000000
--- a/src/gui/kernel/qgesture.h
+++ /dev/null
@@ -1,328 +0,0 @@
-/****************************************************************************
-**
-** 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 QGESTURE_H
-#define QGESTURE_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qdatetime.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qmetatype.h>
-#include <QtGui/qevent.h>
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_HEADER
-
-Q_DECLARE_METATYPE(Qt::GestureState)
-Q_DECLARE_METATYPE(Qt::GestureType)
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QGesturePrivate;
-class Q_GUI_EXPORT QGesture : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QGesture)
-
- Q_PROPERTY(Qt::GestureState state READ state)
- Q_PROPERTY(Qt::GestureType gestureType READ gestureType)
- Q_PROPERTY(QGesture::GestureCancelPolicy gestureCancelPolicy READ gestureCancelPolicy WRITE setGestureCancelPolicy)
- Q_PROPERTY(QPointF hotSpot READ hotSpot WRITE setHotSpot RESET unsetHotSpot)
- Q_PROPERTY(bool hasHotSpot READ hasHotSpot)
-
-public:
- explicit QGesture(QObject *parent = 0);
- ~QGesture();
-
- Qt::GestureType gestureType() const;
-
- Qt::GestureState state() const;
-
- QPointF hotSpot() const;
- void setHotSpot(const QPointF &value);
- bool hasHotSpot() const;
- void unsetHotSpot();
-
- enum GestureCancelPolicy {
- CancelNone = 0,
- CancelAllInContext
- };
-
- void setGestureCancelPolicy(GestureCancelPolicy policy);
- GestureCancelPolicy gestureCancelPolicy() const;
-
-protected:
- QGesture(QGesturePrivate &dd, QObject *parent);
-
-private:
- friend class QGestureEvent;
- friend class QGestureRecognizer;
- friend class QGestureManager;
- friend class QGraphicsScenePrivate;
-};
-
-class QPanGesturePrivate;
-class Q_GUI_EXPORT QPanGesture : public QGesture
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPanGesture)
-
- Q_PROPERTY(QPointF lastOffset READ lastOffset WRITE setLastOffset)
- Q_PROPERTY(QPointF offset READ offset WRITE setOffset)
- Q_PROPERTY(QPointF delta READ delta STORED false)
- Q_PROPERTY(qreal acceleration READ acceleration WRITE setAcceleration)
- Q_PRIVATE_PROPERTY(QPanGesture::d_func(), qreal horizontalVelocity READ horizontalVelocity WRITE setHorizontalVelocity)
- Q_PRIVATE_PROPERTY(QPanGesture::d_func(), qreal verticalVelocity READ verticalVelocity WRITE setVerticalVelocity)
-
-public:
- QPanGesture(QObject *parent = 0);
-
- QPointF lastOffset() const;
- QPointF offset() const;
- QPointF delta() const;
- qreal acceleration() const;
-
- void setLastOffset(const QPointF &value);
- void setOffset(const QPointF &value);
- void setAcceleration(qreal value);
-
- friend class QPanGestureRecognizer;
- friend class QWinNativePanGestureRecognizer;
-};
-
-class QPinchGesturePrivate;
-class Q_GUI_EXPORT QPinchGesture : public QGesture
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPinchGesture)
- Q_FLAGS(ChangeFlags ChangeFlag)
-
-public:
- enum ChangeFlag {
- ScaleFactorChanged = 0x1,
- RotationAngleChanged = 0x2,
- CenterPointChanged = 0x4
- };
- Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag)
-
- Q_PROPERTY(ChangeFlags totalChangeFlags READ totalChangeFlags WRITE setTotalChangeFlags)
- Q_PROPERTY(ChangeFlags changeFlags READ changeFlags WRITE setChangeFlags)
-
- Q_PROPERTY(qreal totalScaleFactor READ totalScaleFactor WRITE setTotalScaleFactor)
- Q_PROPERTY(qreal lastScaleFactor READ lastScaleFactor WRITE setLastScaleFactor)
- Q_PROPERTY(qreal scaleFactor READ scaleFactor WRITE setScaleFactor)
-
- Q_PROPERTY(qreal totalRotationAngle READ totalRotationAngle WRITE setTotalRotationAngle)
- Q_PROPERTY(qreal lastRotationAngle READ lastRotationAngle WRITE setLastRotationAngle)
- Q_PROPERTY(qreal rotationAngle READ rotationAngle WRITE setRotationAngle)
-
- Q_PROPERTY(QPointF startCenterPoint READ startCenterPoint WRITE setStartCenterPoint)
- Q_PROPERTY(QPointF lastCenterPoint READ lastCenterPoint WRITE setLastCenterPoint)
- Q_PROPERTY(QPointF centerPoint READ centerPoint WRITE setCenterPoint)
-
-public:
- QPinchGesture(QObject *parent = 0);
-
- ChangeFlags totalChangeFlags() const;
- void setTotalChangeFlags(ChangeFlags value);
-
- ChangeFlags changeFlags() const;
- void setChangeFlags(ChangeFlags value);
-
- QPointF startCenterPoint() const;
- QPointF lastCenterPoint() const;
- QPointF centerPoint() const;
- void setStartCenterPoint(const QPointF &value);
- void setLastCenterPoint(const QPointF &value);
- void setCenterPoint(const QPointF &value);
-
- qreal totalScaleFactor() const;
- qreal lastScaleFactor() const;
- qreal scaleFactor() const;
- void setTotalScaleFactor(qreal value);
- void setLastScaleFactor(qreal value);
- void setScaleFactor(qreal value);
-
- qreal totalRotationAngle() const;
- qreal lastRotationAngle() const;
- qreal rotationAngle() const;
- void setTotalRotationAngle(qreal value);
- void setLastRotationAngle(qreal value);
- void setRotationAngle(qreal value);
-
- friend class QPinchGestureRecognizer;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QPinchGesture::ChangeFlags)
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QPinchGesture::ChangeFlags)
-
-QT_BEGIN_NAMESPACE
-
-class QSwipeGesturePrivate;
-class Q_GUI_EXPORT QSwipeGesture : public QGesture
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QSwipeGesture)
- Q_ENUMS(SwipeDirection)
-
- Q_PROPERTY(SwipeDirection horizontalDirection READ horizontalDirection STORED false)
- Q_PROPERTY(SwipeDirection verticalDirection READ verticalDirection STORED false)
- Q_PROPERTY(qreal swipeAngle READ swipeAngle WRITE setSwipeAngle)
- Q_PRIVATE_PROPERTY(QSwipeGesture::d_func(), qreal velocity READ velocity WRITE setVelocity)
-
-public:
- enum SwipeDirection { NoDirection, Left, Right, Up, Down };
- QSwipeGesture(QObject *parent = 0);
-
- SwipeDirection horizontalDirection() const;
- SwipeDirection verticalDirection() const;
-
- qreal swipeAngle() const;
- void setSwipeAngle(qreal value);
-
- friend class QSwipeGestureRecognizer;
-};
-
-class QTapGesturePrivate;
-class Q_GUI_EXPORT QTapGesture : public QGesture
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QTapGesture)
-
- Q_PROPERTY(QPointF position READ position WRITE setPosition)
-
-public:
- QTapGesture(QObject *parent = 0);
-
- QPointF position() const;
- void setPosition(const QPointF &pos);
-
- friend class QTapGestureRecognizer;
-};
-
-class QTapAndHoldGesturePrivate;
-class Q_GUI_EXPORT QTapAndHoldGesture : public QGesture
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QTapAndHoldGesture)
-
- Q_PROPERTY(QPointF position READ position WRITE setPosition)
-
-public:
- QTapAndHoldGesture(QObject *parent = 0);
-
- QPointF position() const;
- void setPosition(const QPointF &pos);
-
- static void setTimeout(int msecs);
- static int timeout();
-
- friend class QTapAndHoldGestureRecognizer;
-};
-
-class QGesture;
-class QGestureEventPrivate;
-class Q_GUI_EXPORT QGestureEvent : public QEvent
-{
-public:
- QGestureEvent(const QList<QGesture *> &gestures);
- ~QGestureEvent();
-
- QList<QGesture *> gestures() const;
- QGesture *gesture(Qt::GestureType type) const;
-
- QList<QGesture *> activeGestures() const;
- QList<QGesture *> canceledGestures() const;
-
-#ifdef Q_NO_USING_KEYWORD
- inline void setAccepted(bool accepted) { QEvent::setAccepted(accepted); }
- inline bool isAccepted() const { return QEvent::isAccepted(); }
-
- inline void accept() { QEvent::accept(); }
- inline void ignore() { QEvent::ignore(); }
-#else
- using QEvent::setAccepted;
- using QEvent::isAccepted;
- using QEvent::accept;
- using QEvent::ignore;
-#endif
-
- void setAccepted(QGesture *, bool);
- void accept(QGesture *);
- void ignore(QGesture *);
- bool isAccepted(QGesture *) const;
-
- void setAccepted(Qt::GestureType, bool);
- void accept(Qt::GestureType);
- void ignore(Qt::GestureType);
- bool isAccepted(Qt::GestureType) const;
-
- void setWidget(QWidget *widget);
- QWidget *widget() const;
-
-#ifndef QT_NO_GRAPHICSVIEW
- QPointF mapToGraphicsScene(const QPointF &gesturePoint) const;
-#endif
-
-private:
- QGestureEventPrivate *d_func();
- const QGestureEventPrivate *d_func() const;
-
- friend class QApplication;
- friend class QGestureManager;
-};
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QGesture::GestureCancelPolicy)
-QT_END_HEADER
-
-#endif // QT_NO_GESTURES
-
-#endif // QGESTURE_H
diff --git a/src/gui/kernel/qgesture_p.h b/src/gui/kernel/qgesture_p.h
deleted file mode 100644
index 9dd089cc9e..0000000000
--- a/src/gui/kernel/qgesture_p.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/****************************************************************************
-**
-** 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 QGESTURE_P_H
-#define QGESTURE_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 "qrect.h"
-#include "qpoint.h"
-#include "qgesture.h"
-#include "qelapsedtimer.h"
-#include "private/qobject_p.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-class QGesturePrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QGesture)
-
-public:
- QGesturePrivate()
- : gestureType(Qt::CustomGesture), state(Qt::NoGesture),
- isHotSpotSet(false), gestureCancelPolicy(0)
- {
- }
-
- Qt::GestureType gestureType;
- Qt::GestureState state;
- QPointF hotSpot;
- QPointF sceneHotSpot;
- uint isHotSpotSet : 1;
- uint gestureCancelPolicy : 2;
-};
-
-class QPanGesturePrivate : public QGesturePrivate
-{
- Q_DECLARE_PUBLIC(QPanGesture)
-
-public:
- QPanGesturePrivate()
- : acceleration(0), xVelocity(0), yVelocity(0)
- {
- }
-
- qreal horizontalVelocity() const { return xVelocity; }
- void setHorizontalVelocity(qreal value) { xVelocity = value; }
- qreal verticalVelocity() const { return yVelocity; }
- void setVerticalVelocity(qreal value) { yVelocity = value; }
-
- QPointF lastOffset;
- QPointF offset;
- QPoint startPosition;
- qreal acceleration;
- qreal xVelocity;
- qreal yVelocity;
-};
-
-class QPinchGesturePrivate : public QGesturePrivate
-{
- Q_DECLARE_PUBLIC(QPinchGesture)
-
-public:
- QPinchGesturePrivate()
- : totalChangeFlags(0), changeFlags(0),
- totalScaleFactor(1), lastScaleFactor(1), scaleFactor(1),
- totalRotationAngle(0), lastRotationAngle(0), rotationAngle(0),
- isNewSequence(true)
- {
- }
-
- QPinchGesture::ChangeFlags totalChangeFlags;
- QPinchGesture::ChangeFlags changeFlags;
-
- QPointF startCenterPoint;
- QPointF lastCenterPoint;
- QPointF centerPoint;
-
- qreal totalScaleFactor;
- qreal lastScaleFactor;
- qreal scaleFactor;
-
- qreal totalRotationAngle;
- qreal lastRotationAngle;
- qreal rotationAngle;
-
- bool isNewSequence;
- QPointF startPosition[2];
-};
-
-class QSwipeGesturePrivate : public QGesturePrivate
-{
- Q_DECLARE_PUBLIC(QSwipeGesture)
-
-public:
- QSwipeGesturePrivate()
- : horizontalDirection(QSwipeGesture::NoDirection),
- verticalDirection(QSwipeGesture::NoDirection),
- swipeAngle(0),
- started(false), velocityValue(0)
- {
- }
-
- qreal velocity() const { return velocityValue; }
- void setVelocity(qreal value) { velocityValue = value; }
-
- QSwipeGesture::SwipeDirection horizontalDirection;
- QSwipeGesture::SwipeDirection verticalDirection;
- qreal swipeAngle;
-
- QPoint lastPositions[3];
- bool started;
- qreal velocityValue;
- QElapsedTimer time;
-};
-
-class QTapGesturePrivate : public QGesturePrivate
-{
- Q_DECLARE_PUBLIC(QTapGesture)
-
-public:
- QTapGesturePrivate()
- {
- }
-
- QPointF position;
-};
-
-class QTapAndHoldGesturePrivate : public QGesturePrivate
-{
- Q_DECLARE_PUBLIC(QTapAndHoldGesture)
-
-public:
- QTapAndHoldGesturePrivate()
- : timerId(0)
- {
- }
-
- QPointF position;
- int timerId;
- static int Timeout;
-};
-
-#ifndef QT_NO_GESTURES
-class QNativeGestureEvent : public QEvent
-{
-public:
- enum Type {
- None,
- GestureBegin,
- GestureEnd,
- Pan,
- Zoom,
- Rotate,
- Swipe
- };
-
- QNativeGestureEvent()
- : QEvent(QEvent::NativeGesture), gestureType(None), percentage(0)
-#ifdef Q_WS_WIN
- , sequenceId(0), argument(0)
-#endif
- {
- }
-
- Type gestureType;
- float percentage;
- QPoint position;
- float angle;
-#ifdef Q_WS_WIN
- ulong sequenceId;
- quint64 argument;
-#endif
-};
-
-class QGestureEventPrivate
-{
-public:
- inline QGestureEventPrivate(const QList<QGesture *> &list)
- : gestures(list), widget(0)
- {
- }
-
- QList<QGesture *> gestures;
- QWidget *widget;
- QMap<Qt::GestureType, bool> accepted;
- QMap<Qt::GestureType, QWidget *> targetWidgets;
-};
-#endif // QT_NO_GESTURES
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QGESTURE_P_H
diff --git a/src/gui/kernel/qgesturemanager.cpp b/src/gui/kernel/qgesturemanager.cpp
deleted file mode 100644
index 5359fb37e8..0000000000
--- a/src/gui/kernel/qgesturemanager.cpp
+++ /dev/null
@@ -1,721 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qgesturemanager_p.h"
-#include "private/qstandardgestures_p.h"
-#include "private/qwidget_p.h"
-#include "private/qgesture_p.h"
-#include "private/qgraphicsitem_p.h"
-#include "private/qevent_p.h"
-#include "private/qapplication_p.h"
-#include "qgesture.h"
-#include "qevent.h"
-#include "qgraphicsitem.h"
-
-#ifdef Q_WS_MAC
-#include "qmacgesturerecognizer_mac_p.h"
-#endif
-#if defined(Q_OS_WIN) && !defined(QT_NO_NATIVE_GESTURES)
-#include "qwinnativepangesturerecognizer_win_p.h"
-#endif
-
-#include "qdebug.h"
-
-// #define GESTURE_DEBUG
-#ifndef GESTURE_DEBUG
-# define DEBUG if (0) qDebug
-#else
-# define DEBUG qDebug
-#endif
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-QGestureManager::QGestureManager(QObject *parent)
- : QObject(parent), state(NotGesture), m_lastCustomGestureId(Qt::CustomGesture)
-{
- qRegisterMetaType<Qt::GestureState>();
-
-#if defined(Q_WS_MAC)
- registerGestureRecognizer(new QMacSwipeGestureRecognizer);
- registerGestureRecognizer(new QMacPinchGestureRecognizer);
- #if defined(QT_MAC_USE_COCOA)
- registerGestureRecognizer(new QMacPanGestureRecognizer);
- #endif
-#else
- registerGestureRecognizer(new QPanGestureRecognizer);
- registerGestureRecognizer(new QPinchGestureRecognizer);
- registerGestureRecognizer(new QSwipeGestureRecognizer);
- registerGestureRecognizer(new QTapGestureRecognizer);
-#endif
-#if defined(Q_OS_WIN)
- #if !defined(QT_NO_NATIVE_GESTURES)
- if (QApplicationPrivate::HasTouchSupport)
- registerGestureRecognizer(new QWinNativePanGestureRecognizer);
- #endif
-#else
- registerGestureRecognizer(new QTapAndHoldGestureRecognizer);
-#endif
-}
-
-QGestureManager::~QGestureManager()
-{
- qDeleteAll(m_recognizers.values());
- foreach (QGestureRecognizer *recognizer, m_obsoleteGestures.keys()) {
- qDeleteAll(m_obsoleteGestures.value(recognizer));
- delete recognizer;
- }
- m_obsoleteGestures.clear();
-}
-
-Qt::GestureType QGestureManager::registerGestureRecognizer(QGestureRecognizer *recognizer)
-{
- QGesture *dummy = recognizer->create(0);
- if (!dummy) {
- qWarning("QGestureManager::registerGestureRecognizer: "
- "the recognizer fails to create a gesture object, skipping registration.");
- return Qt::GestureType(0);
- }
- Qt::GestureType type = dummy->gestureType();
- if (type == Qt::CustomGesture) {
- // generate a new custom gesture id
- ++m_lastCustomGestureId;
- type = Qt::GestureType(m_lastCustomGestureId);
- }
- m_recognizers.insertMulti(type, recognizer);
- delete dummy;
- return type;
-}
-
-void QGestureManager::unregisterGestureRecognizer(Qt::GestureType type)
-{
- QList<QGestureRecognizer *> list = m_recognizers.values(type);
- while (QGestureRecognizer *recognizer = m_recognizers.take(type)) {
- if (!m_obsoleteGestures.contains(recognizer)) {
- // inserting even an empty QSet will cause the recognizer to be deleted on destruction of the manager
- m_obsoleteGestures.insert(recognizer, QSet<QGesture *>());
- }
- }
- foreach (QGesture *g, m_gestureToRecognizer.keys()) {
- QGestureRecognizer *recognizer = m_gestureToRecognizer.value(g);
- if (list.contains(recognizer)) {
- m_deletedRecognizers.insert(g, recognizer);
- }
- }
-
- QMap<ObjectGesture, QList<QGesture *> >::const_iterator iter = m_objectGestures.begin();
- while (iter != m_objectGestures.end()) {
- ObjectGesture objectGesture = iter.key();
- if (objectGesture.gesture == type) {
- foreach (QGesture *g, iter.value()) {
- if (QGestureRecognizer *recognizer = m_gestureToRecognizer.value(g)) {
- m_gestureToRecognizer.remove(g);
- m_obsoleteGestures[recognizer].insert(g);
- }
- }
- }
- ++iter;
- }
-}
-
-void QGestureManager::cleanupCachedGestures(QObject *target, Qt::GestureType type)
-{
- QMap<ObjectGesture, QList<QGesture *> >::Iterator iter = m_objectGestures.begin();
- while (iter != m_objectGestures.end()) {
- ObjectGesture objectGesture = iter.key();
- if (objectGesture.gesture == type && target == objectGesture.object) {
- QSet<QGesture *> gestures = iter.value().toSet();
- for (QHash<QGestureRecognizer *, QSet<QGesture *> >::iterator
- it = m_obsoleteGestures.begin(), e = m_obsoleteGestures.end(); it != e; ++it) {
- it.value() -= gestures;
- }
- foreach (QGesture *g, gestures) {
- m_deletedRecognizers.remove(g);
- m_gestureToRecognizer.remove(g);
- m_maybeGestures.remove(g);
- m_activeGestures.remove(g);
- m_gestureOwners.remove(g);
- m_gestureTargets.remove(g);
- m_gesturesToDelete.insert(g);
- }
-
- iter = m_objectGestures.erase(iter);
- } else {
- ++iter;
- }
- }
-}
-
-// get or create a QGesture object that will represent the state for a given object, used by the recognizer
-QGesture *QGestureManager::getState(QObject *object, QGestureRecognizer *recognizer, Qt::GestureType type)
-{
- // if the widget is being deleted we should be careful not to
- // create a new state, as it will create QWeakPointer which doesn't work
- // from the destructor.
- if (object->isWidgetType()) {
- if (static_cast<QWidget *>(object)->d_func()->data.in_destructor)
- return 0;
- } else if (QGesture *g = qobject_cast<QGesture *>(object)) {
- return g;
-#ifndef QT_NO_GRAPHICSVIEW
- } else {
- Q_ASSERT(qobject_cast<QGraphicsObject *>(object));
- QGraphicsObject *graphicsObject = static_cast<QGraphicsObject *>(object);
- if (graphicsObject->QGraphicsItem::d_func()->inDestructor)
- return 0;
-#endif
- }
-
- // check if the QGesture for this recognizer has already been created
- foreach (QGesture *state, m_objectGestures.value(QGestureManager::ObjectGesture(object, type))) {
- if (m_gestureToRecognizer.value(state) == recognizer)
- return state;
- }
-
- Q_ASSERT(recognizer);
- QGesture *state = recognizer->create(object);
- if (!state)
- return 0;
- state->setParent(this);
- if (state->gestureType() == Qt::CustomGesture) {
- // if the recognizer didn't fill in the gesture type, then this
- // is a custom gesture with autogenerated id and we fill it.
- state->d_func()->gestureType = type;
-#if defined(GESTURE_DEBUG)
- state->setObjectName(QString::number((int)type));
-#endif
- }
- m_objectGestures[QGestureManager::ObjectGesture(object, type)].append(state);
- m_gestureToRecognizer[state] = recognizer;
- m_gestureOwners[state] = object;
-
- return state;
-}
-
-bool QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,
- Qt::GestureType> &contexts,
- QEvent *event)
-{
- QSet<QGesture *> triggeredGestures;
- QSet<QGesture *> finishedGestures;
- QSet<QGesture *> newMaybeGestures;
- QSet<QGesture *> notGestures;
-
- // TODO: sort contexts by the gesture type and check if one of the contexts
- // is already active.
-
- bool consumeEventHint = false;
-
- // filter the event through recognizers
- typedef QMultiMap<QObject *, Qt::GestureType>::const_iterator ContextIterator;
- ContextIterator contextEnd = contexts.end();
- for (ContextIterator context = contexts.begin(); context != contextEnd; ++context) {
- Qt::GestureType gestureType = context.value();
- QMap<Qt::GestureType, QGestureRecognizer *>::const_iterator
- typeToRecognizerIterator = m_recognizers.lowerBound(gestureType),
- typeToRecognizerEnd = m_recognizers.upperBound(gestureType);
- for (; typeToRecognizerIterator != typeToRecognizerEnd; ++typeToRecognizerIterator) {
- QGestureRecognizer *recognizer = typeToRecognizerIterator.value();
- QObject *target = context.key();
- QGesture *state = getState(target, recognizer, gestureType);
- if (!state)
- continue;
- QGestureRecognizer::Result recognizerResult = recognizer->recognize(state, target, event);
- QGestureRecognizer::Result recognizerState = recognizerResult & QGestureRecognizer::ResultState_Mask;
- QGestureRecognizer::Result resultHint = recognizerResult & QGestureRecognizer::ResultHint_Mask;
- if (recognizerState == QGestureRecognizer::TriggerGesture) {
- DEBUG() << "QGestureManager:Recognizer: gesture triggered: " << state;
- triggeredGestures << state;
- } else if (recognizerState == QGestureRecognizer::FinishGesture) {
- DEBUG() << "QGestureManager:Recognizer: gesture finished: " << state;
- finishedGestures << state;
- } else if (recognizerState == QGestureRecognizer::MayBeGesture) {
- DEBUG() << "QGestureManager:Recognizer: maybe gesture: " << state;
- newMaybeGestures << state;
- } else if (recognizerState == QGestureRecognizer::CancelGesture) {
- DEBUG() << "QGestureManager:Recognizer: not gesture: " << state;
- notGestures << state;
- } else if (recognizerState == QGestureRecognizer::Ignore) {
- DEBUG() << "QGestureManager:Recognizer: ignored the event: " << state;
- } else {
- DEBUG() << "QGestureManager:Recognizer: hm, lets assume the recognizer"
- << "ignored the event: " << state;
- }
- if (resultHint & QGestureRecognizer::ConsumeEventHint) {
- DEBUG() << "QGestureManager: we were asked to consume the event: "
- << state;
- consumeEventHint = true;
- }
- }
- }
- if (triggeredGestures.isEmpty() && finishedGestures.isEmpty()
- && newMaybeGestures.isEmpty() && notGestures.isEmpty())
- return consumeEventHint;
-
- QSet<QGesture *> startedGestures = triggeredGestures - m_activeGestures;
- triggeredGestures &= m_activeGestures;
-
- // check if a running gesture switched back to maybe state
- QSet<QGesture *> activeToMaybeGestures = m_activeGestures & newMaybeGestures;
-
- // check if a maybe gesture switched to canceled - reset it but don't send an event
- QSet<QGesture *> maybeToCanceledGestures = m_maybeGestures & notGestures;
-
- // check if a running gesture switched back to not gesture state,
- // i.e. were canceled
- QSet<QGesture *> canceledGestures = m_activeGestures & notGestures;
-
- // new gestures in maybe state
- m_maybeGestures += newMaybeGestures;
-
- // gestures that were in maybe state
- QSet<QGesture *> notMaybeGestures = (startedGestures | triggeredGestures
- | finishedGestures | canceledGestures
- | notGestures);
- m_maybeGestures -= notMaybeGestures;
-
- Q_ASSERT((startedGestures & finishedGestures).isEmpty());
- Q_ASSERT((startedGestures & newMaybeGestures).isEmpty());
- Q_ASSERT((startedGestures & canceledGestures).isEmpty());
- Q_ASSERT((finishedGestures & newMaybeGestures).isEmpty());
- Q_ASSERT((finishedGestures & canceledGestures).isEmpty());
- Q_ASSERT((canceledGestures & newMaybeGestures).isEmpty());
-
- QSet<QGesture *> notStarted = finishedGestures - m_activeGestures;
- if (!notStarted.isEmpty()) {
- // there are some gestures that claim to be finished, but never started.
- // probably those are "singleshot" gestures so we'll fake the started state.
- foreach (QGesture *gesture, notStarted)
- gesture->d_func()->state = Qt::GestureStarted;
- QSet<QGesture *> undeliveredGestures;
- deliverEvents(notStarted, &undeliveredGestures);
- finishedGestures -= undeliveredGestures;
- }
-
- m_activeGestures += startedGestures;
- // sanity check: all triggered gestures should already be in active gestures list
- Q_ASSERT((m_activeGestures & triggeredGestures).size() == triggeredGestures.size());
- m_activeGestures -= finishedGestures;
- m_activeGestures -= activeToMaybeGestures;
- m_activeGestures -= canceledGestures;
-
- // set the proper gesture state on each gesture
- foreach (QGesture *gesture, startedGestures)
- gesture->d_func()->state = Qt::GestureStarted;
- foreach (QGesture *gesture, triggeredGestures)
- gesture->d_func()->state = Qt::GestureUpdated;
- foreach (QGesture *gesture, finishedGestures)
- gesture->d_func()->state = Qt::GestureFinished;
- foreach (QGesture *gesture, canceledGestures)
- gesture->d_func()->state = Qt::GestureCanceled;
- foreach (QGesture *gesture, activeToMaybeGestures)
- gesture->d_func()->state = Qt::GestureFinished;
-
- if (!m_activeGestures.isEmpty() || !m_maybeGestures.isEmpty() ||
- !startedGestures.isEmpty() || !triggeredGestures.isEmpty() ||
- !finishedGestures.isEmpty() || !canceledGestures.isEmpty()) {
- DEBUG() << "QGestureManager::filterEventThroughContexts:"
- << "\n\tactiveGestures:" << m_activeGestures
- << "\n\tmaybeGestures:" << m_maybeGestures
- << "\n\tstarted:" << startedGestures
- << "\n\ttriggered:" << triggeredGestures
- << "\n\tfinished:" << finishedGestures
- << "\n\tcanceled:" << canceledGestures
- << "\n\tmaybe-canceled:" << maybeToCanceledGestures;
- }
-
- QSet<QGesture *> undeliveredGestures;
- deliverEvents(startedGestures+triggeredGestures+finishedGestures+canceledGestures,
- &undeliveredGestures);
-
- foreach (QGesture *g, startedGestures) {
- if (undeliveredGestures.contains(g))
- continue;
- if (g->gestureCancelPolicy() == QGesture::CancelAllInContext) {
- DEBUG() << "lets try to cancel some";
- // find gestures in context in Qt::GestureStarted or Qt::GestureUpdated state and cancel them
- cancelGesturesForChildren(g);
- }
- }
-
- m_activeGestures -= undeliveredGestures;
-
- // reset gestures that ended
- QSet<QGesture *> endedGestures =
- finishedGestures + canceledGestures + undeliveredGestures + maybeToCanceledGestures;
- foreach (QGesture *gesture, endedGestures) {
- recycle(gesture);
- m_gestureTargets.remove(gesture);
- }
-
- //Clean up the Gestures
- qDeleteAll(m_gesturesToDelete);
- m_gesturesToDelete.clear();
-
- return consumeEventHint;
-}
-
-// Cancel all gestures of children of the widget that original is associated with
-void QGestureManager::cancelGesturesForChildren(QGesture *original)
-{
- Q_ASSERT(original);
- QWidget *originatingWidget = m_gestureTargets.value(original);
- Q_ASSERT(originatingWidget);
-
- // iterate over all active gestures and all maybe gestures
- // for each find the owner
- // if the owner is part of our sub-hierarchy, cancel it.
-
- QSet<QGesture*> cancelledGestures;
- QSet<QGesture*>::Iterator iter = m_activeGestures.begin();
- while (iter != m_activeGestures.end()) {
- QWidget *widget = m_gestureTargets.value(*iter);
- // note that we don't touch the gestures for our originatingWidget
- if (widget != originatingWidget && originatingWidget->isAncestorOf(widget)) {
- DEBUG() << " found a gesture to cancel" << (*iter);
- (*iter)->d_func()->state = Qt::GestureCanceled;
- cancelledGestures << *iter;
- iter = m_activeGestures.erase(iter);
- } else {
- ++iter;
- }
- }
-
- // TODO handle 'maybe' gestures too
-
- // sort them per target widget by cherry picking from almostCanceledGestures and delivering
- QSet<QGesture *> almostCanceledGestures = cancelledGestures;
- while (!almostCanceledGestures.isEmpty()) {
- QWidget *target = 0;
- QSet<QGesture*> gestures;
- iter = almostCanceledGestures.begin();
- // sort per target widget
- while (iter != almostCanceledGestures.end()) {
- QWidget *widget = m_gestureTargets.value(*iter);
- if (target == 0)
- target = widget;
- if (target == widget) {
- gestures << *iter;
- iter = almostCanceledGestures.erase(iter);
- } else {
- ++iter;
- }
- }
- Q_ASSERT(target);
-
- QSet<QGesture*> undeliveredGestures;
- deliverEvents(gestures, &undeliveredGestures);
- }
-
- for (iter = cancelledGestures.begin(); iter != cancelledGestures.end(); ++iter)
- recycle(*iter);
-}
-
-void QGestureManager::cleanupGesturesForRemovedRecognizer(QGesture *gesture)
-{
- QGestureRecognizer *recognizer = m_deletedRecognizers.value(gesture);
- if(!recognizer) //The Gesture is removed while in the even loop, so the recognizers for this gestures was removed
- return;
- m_deletedRecognizers.remove(gesture);
- if (m_deletedRecognizers.keys(recognizer).isEmpty()) {
- // no more active gestures, cleanup!
- qDeleteAll(m_obsoleteGestures.value(recognizer));
- m_obsoleteGestures.remove(recognizer);
- delete recognizer;
- }
-}
-
-// return true if accepted (consumed)
-bool QGestureManager::filterEvent(QWidget *receiver, QEvent *event)
-{
- QMap<Qt::GestureType, int> types;
- QMultiMap<QObject *, Qt::GestureType> contexts;
- QWidget *w = receiver;
- typedef QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator ContextIterator;
- if (!w->d_func()->gestureContext.isEmpty()) {
- for(ContextIterator it = w->d_func()->gestureContext.begin(),
- e = w->d_func()->gestureContext.end(); it != e; ++it) {
- types.insert(it.key(), 0);
- contexts.insertMulti(w, it.key());
- }
- }
- // find all gesture contexts for the widget tree
- w = w->isWindow() ? 0 : w->parentWidget();
- while (w)
- {
- for (ContextIterator it = w->d_func()->gestureContext.begin(),
- e = w->d_func()->gestureContext.end(); it != e; ++it) {
- if (!(it.value() & Qt::DontStartGestureOnChildren)) {
- if (!types.contains(it.key())) {
- types.insert(it.key(), 0);
- contexts.insertMulti(w, it.key());
- }
- }
- }
- if (w->isWindow())
- break;
- w = w->parentWidget();
- }
- return contexts.isEmpty() ? false : filterEventThroughContexts(contexts, event);
-}
-
-#ifndef QT_NO_GRAPHICSVIEW
-bool QGestureManager::filterEvent(QGraphicsObject *receiver, QEvent *event)
-{
- QMap<Qt::GestureType, int> types;
- QMultiMap<QObject *, Qt::GestureType> contexts;
- QGraphicsObject *item = receiver;
- if (!item->QGraphicsItem::d_func()->gestureContext.isEmpty()) {
- typedef QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator ContextIterator;
- for(ContextIterator it = item->QGraphicsItem::d_func()->gestureContext.begin(),
- e = item->QGraphicsItem::d_func()->gestureContext.end(); it != e; ++it) {
- types.insert(it.key(), 0);
- contexts.insertMulti(item, it.key());
- }
- }
- // find all gesture contexts for the graphics object tree
- item = item->parentObject();
- while (item)
- {
- typedef QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator ContextIterator;
- for (ContextIterator it = item->QGraphicsItem::d_func()->gestureContext.begin(),
- e = item->QGraphicsItem::d_func()->gestureContext.end(); it != e; ++it) {
- if (!(it.value() & Qt::DontStartGestureOnChildren)) {
- if (!types.contains(it.key())) {
- types.insert(it.key(), 0);
- contexts.insertMulti(item, it.key());
- }
- }
- }
- item = item->parentObject();
- }
- return contexts.isEmpty() ? false : filterEventThroughContexts(contexts, event);
-}
-#endif
-
-bool QGestureManager::filterEvent(QObject *receiver, QEvent *event)
-{
- if (!m_gestureToRecognizer.contains(static_cast<QGesture *>(receiver)))
- return false;
- QGesture *state = static_cast<QGesture *>(receiver);
- QMultiMap<QObject *, Qt::GestureType> contexts;
- contexts.insert(state, state->gestureType());
- return filterEventThroughContexts(contexts, event);
-}
-
-void QGestureManager::getGestureTargets(const QSet<QGesture*> &gestures,
- QMap<QWidget *, QList<QGesture *> > *conflicts,
- QMap<QWidget *, QList<QGesture *> > *normal)
-{
- typedef QHash<Qt::GestureType, QHash<QWidget *, QGesture *> > GestureByTypes;
- GestureByTypes gestureByTypes;
-
- // sort gestures by types
- foreach (QGesture *gesture, gestures) {
- QWidget *receiver = m_gestureTargets.value(gesture, 0);
- Q_ASSERT(receiver);
- gestureByTypes[gesture->gestureType()].insert(receiver, gesture);
- }
-
- // for each gesture type
- foreach (Qt::GestureType type, gestureByTypes.keys()) {
- QHash<QWidget *, QGesture *> gestures = gestureByTypes.value(type);
- foreach (QWidget *widget, gestures.keys()) {
- QWidget *w = widget->parentWidget();
- while (w) {
- QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator it
- = w->d_func()->gestureContext.find(type);
- if (it != w->d_func()->gestureContext.end()) {
- // i.e. 'w' listens to gesture 'type'
- Qt::GestureFlags flags = it.value();
- if (!(it.value() & Qt::DontStartGestureOnChildren) && w != widget) {
- // conflicting gesture!
- (*conflicts)[widget].append(gestures[widget]);
- break;
- }
- }
- if (w->isWindow()) {
- w = 0;
- break;
- }
- w = w->parentWidget();
- }
- if (!w)
- (*normal)[widget].append(gestures[widget]);
- }
- }
-}
-
-void QGestureManager::deliverEvents(const QSet<QGesture *> &gestures,
- QSet<QGesture *> *undeliveredGestures)
-{
- if (gestures.isEmpty())
- return;
-
- typedef QMap<QWidget *, QList<QGesture *> > GesturesPerWidget;
- GesturesPerWidget conflictedGestures;
- GesturesPerWidget normalStartedGestures;
-
- QSet<QGesture *> startedGestures;
- // first figure out the initial receivers of gestures
- for (QSet<QGesture *>::const_iterator it = gestures.begin(),
- e = gestures.end(); it != e; ++it) {
- QGesture *gesture = *it;
- QWidget *target = m_gestureTargets.value(gesture, 0);
- if (!target) {
- // the gesture has just started and doesn't have a target yet.
- Q_ASSERT(gesture->state() == Qt::GestureStarted);
- if (gesture->hasHotSpot()) {
- // guess the target widget using the hotspot of the gesture
- QPoint pt = gesture->hotSpot().toPoint();
- if (QWidget *topLevel = qApp->topLevelAt(pt)) {
- QWidget *child = topLevel->childAt(topLevel->mapFromGlobal(pt));
- target = child ? child : topLevel;
- }
- } else {
- // or use the context of the gesture
- QObject *context = m_gestureOwners.value(gesture, 0);
- if (context->isWidgetType())
- target = static_cast<QWidget *>(context);
- }
- if (target)
- m_gestureTargets.insert(gesture, target);
- }
-
- Qt::GestureType gestureType = gesture->gestureType();
- Q_ASSERT(gestureType != Qt::CustomGesture);
- Q_UNUSED(gestureType);
-
- if (target) {
- if (gesture->state() == Qt::GestureStarted) {
- startedGestures.insert(gesture);
- } else {
- normalStartedGestures[target].append(gesture);
- }
- } else {
- DEBUG() << "QGestureManager::deliverEvent: could not find the target for gesture"
- << gesture->gestureType();
- qWarning("QGestureManager::deliverEvent: could not find the target for gesture");
- undeliveredGestures->insert(gesture);
- }
- }
-
- getGestureTargets(startedGestures, &conflictedGestures, &normalStartedGestures);
- DEBUG() << "QGestureManager::deliverEvents:"
- << "\nstarted: " << startedGestures
- << "\nconflicted: " << conflictedGestures
- << "\nnormal: " << normalStartedGestures
- << "\n";
-
- // if there are conflicting gestures, send the GestureOverride event
- for (GesturesPerWidget::const_iterator it = conflictedGestures.begin(),
- e = conflictedGestures.end(); it != e; ++it) {
- QWidget *receiver = it.key();
- QList<QGesture *> gestures = it.value();
- DEBUG() << "QGestureManager::deliverEvents: sending GestureOverride to"
- << receiver
- << "gestures:" << gestures;
- QGestureEvent event(gestures);
- event.t = QEvent::GestureOverride;
- // mark event and individual gestures as ignored
- event.ignore();
- foreach(QGesture *g, gestures)
- event.setAccepted(g, false);
-
- QApplication::sendEvent(receiver, &event);
- bool eventAccepted = event.isAccepted();
- foreach(QGesture *gesture, event.gestures()) {
- if (eventAccepted || event.isAccepted(gesture)) {
- QWidget *w = event.d_func()->targetWidgets.value(gesture->gestureType(), 0);
- Q_ASSERT(w);
- DEBUG() << "override event: gesture was accepted:" << gesture << w;
- QList<QGesture *> &gestures = normalStartedGestures[w];
- gestures.append(gesture);
- // override the target
- m_gestureTargets[gesture] = w;
- } else {
- DEBUG() << "override event: gesture wasn't accepted. putting back:" << gesture;
- QList<QGesture *> &gestures = normalStartedGestures[receiver];
- gestures.append(gesture);
- }
- }
- }
-
- // delivering gestures that are not in conflicted state
- for (GesturesPerWidget::const_iterator it = normalStartedGestures.begin(),
- e = normalStartedGestures.end(); it != e; ++it) {
- if (!it.value().isEmpty()) {
- DEBUG() << "QGestureManager::deliverEvents: sending to" << it.key()
- << "gestures:" << it.value();
- QGestureEvent event(it.value());
- QApplication::sendEvent(it.key(), &event);
- bool eventAccepted = event.isAccepted();
- foreach (QGesture *gesture, event.gestures()) {
- if (gesture->state() == Qt::GestureStarted &&
- (eventAccepted || event.isAccepted(gesture))) {
- QWidget *w = event.d_func()->targetWidgets.value(gesture->gestureType(), 0);
- Q_ASSERT(w);
- DEBUG() << "started gesture was delivered and accepted by" << w;
- m_gestureTargets[gesture] = w;
- }
- }
- }
- }
-}
-
-void QGestureManager::recycle(QGesture *gesture)
-{
- QGestureRecognizer *recognizer = m_gestureToRecognizer.value(gesture, 0);
- if (recognizer) {
- gesture->setGestureCancelPolicy(QGesture::CancelNone);
- recognizer->reset(gesture);
- m_activeGestures.remove(gesture);
- } else {
- cleanupGesturesForRemovedRecognizer(gesture);
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#include "moc_qgesturemanager_p.cpp"
diff --git a/src/gui/kernel/qgesturemanager_p.h b/src/gui/kernel/qgesturemanager_p.h
deleted file mode 100644
index b4d9f61ec0..0000000000
--- a/src/gui/kernel/qgesturemanager_p.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/****************************************************************************
-**
-** 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 QGESTUREMANAGER_P_H
-#define QGESTUREMANAGER_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 "qobject.h"
-#include "qbasictimer.h"
-#include "private/qwidget_p.h"
-#include "qgesturerecognizer.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-class QBasicTimer;
-class QGraphicsObject;
-class QGestureManager : public QObject
-{
- Q_OBJECT
-public:
- QGestureManager(QObject *parent);
- ~QGestureManager();
-
- Qt::GestureType registerGestureRecognizer(QGestureRecognizer *recognizer);
- void unregisterGestureRecognizer(Qt::GestureType type);
-
- bool filterEvent(QWidget *receiver, QEvent *event);
- bool filterEvent(QObject *receiver, QEvent *event);
-#ifndef QT_NO_GRAPHICSVIEW
- bool filterEvent(QGraphicsObject *receiver, QEvent *event);
-#endif //QT_NO_GRAPHICSVIEW
-
- static QGestureManager* instance(); // declared in qapplication.cpp
-
- void cleanupCachedGestures(QObject *target, Qt::GestureType type);
-
- void recycle(QGesture *gesture);
-
-protected:
- bool filterEventThroughContexts(const QMultiMap<QObject *, Qt::GestureType> &contexts,
- QEvent *event);
-
-private:
- QMultiMap<Qt::GestureType, QGestureRecognizer *> m_recognizers;
-
- QSet<QGesture *> m_activeGestures;
- QSet<QGesture *> m_maybeGestures;
-
- enum State {
- Gesture,
- NotGesture,
- MaybeGesture // this means timers are up and waiting for some
- // more events, and input events are handled by
- // gesture recognizer explicitly
- } state;
-
- struct ObjectGesture
- {
- QObject* object;
- Qt::GestureType gesture;
-
- ObjectGesture(QObject *o, const Qt::GestureType &g) : object(o), gesture(g) { }
- inline bool operator<(const ObjectGesture &rhs) const
- {
- if (object < rhs.object)
- return true;
- if (object == rhs.object)
- return gesture < rhs.gesture;
- return false;
- }
- };
-
- QMap<ObjectGesture, QList<QGesture *> > m_objectGestures;
- QHash<QGesture *, QGestureRecognizer *> m_gestureToRecognizer;
- QHash<QGesture *, QObject *> m_gestureOwners;
-
- QHash<QGesture *, QWidget *> m_gestureTargets;
-
- int m_lastCustomGestureId;
-
- QHash<QGestureRecognizer *, QSet<QGesture *> > m_obsoleteGestures;
- QHash<QGesture *, QGestureRecognizer *> m_deletedRecognizers;
- QSet<QGesture *> m_gesturesToDelete;
- void cleanupGesturesForRemovedRecognizer(QGesture *gesture);
-
- QGesture *getState(QObject *widget, QGestureRecognizer *recognizer,
- Qt::GestureType gesture);
- void deliverEvents(const QSet<QGesture *> &gestures,
- QSet<QGesture *> *undeliveredGestures);
- void getGestureTargets(const QSet<QGesture*> &gestures,
- QMap<QWidget *, QList<QGesture *> > *conflicts,
- QMap<QWidget *, QList<QGesture *> > *normal);
-
- void cancelGesturesForChildren(QGesture *originatingGesture);
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QGESTUREMANAGER_P_H
diff --git a/src/gui/kernel/qgesturerecognizer.cpp b/src/gui/kernel/qgesturerecognizer.cpp
deleted file mode 100644
index f7a4a189b9..0000000000
--- a/src/gui/kernel/qgesturerecognizer.cpp
+++ /dev/null
@@ -1,240 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgesturerecognizer.h"
-
-#include "private/qgesture_p.h"
-#include "private/qgesturemanager_p.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QGestureRecognizer
- \since 4.6
- \brief The QGestureRecognizer class provides the infrastructure for gesture recognition.
- \ingroup gestures
-
- Gesture recognizers are responsible for creating and managing QGesture objects and
- monitoring input events sent to QWidget and QGraphicsObject subclasses.
- QGestureRecognizer is the base class for implementing custom gestures.
-
- Developers that only need to provide gesture recognition for standard gestures do not
- need to use this class directly. Instances will be created behind the scenes by the
- framework.
-
- For an overview of gesture handling in Qt and information on using gestures
- in your applications, see the \l{Gestures Programming} document.
-
- \section1 Recognizing Gestures
-
- The process of recognizing gestures involves filtering input events sent to specific
- objects, and modifying the associated QGesture objects to include relevant information
- about the user's input.
-
- Gestures are created when the framework calls create() to handle user input
- for a particular instance of a QWidget or QGraphicsObject subclass. A QGesture object
- is created for each widget or item that is configured to use gestures.
-
- Once a QGesture has been created for a target object, the gesture recognizer will
- receive events for it in its recognize() handler function.
-
- When a gesture is canceled, the reset() function is called, giving the recognizer the
- chance to update the appropriate properties in the corresponding QGesture object.
-
- \section1 Supporting New Gestures
-
- To add support for new gestures, you need to derive from QGestureRecognizer to create
- a custom recognizer class, construct an instance of this class, and register it with
- the application by calling QGestureRecognizer::registerRecognizer(). You can also
- subclass QGesture to create a custom gesture class, or rely on dynamic properties
- to express specific details of the gesture you want to handle.
-
- Your custom QGestureRecognizer subclass needs to reimplement the recognize()
- function to handle and filter the incoming input events for QWidget and
- QGraphicsObject subclasses. Although the logic for gesture recognition is
- implemented in this function, you can store persistent information about the
- state of the recognition process in the QGesture object supplied. The
- recognize() function must return a value of QGestureRecognizer::Result that
- indicates the state of recognition for a given gesture and target object.
- This determines whether or not a gesture event will be delivered to a target
- object.
-
- If you choose to represent a gesture by a custom QGesture subclass, you will need to
- reimplement the create() function to construct instances of your gesture class.
- Similarly, you may need to reimplement the reset() function if your custom gesture
- objects need to be specially handled when a gesture is canceled.
-
- \sa QGesture
-*/
-
-/*!
- \enum QGestureRecognizer::ResultFlag
-
- This enum describes the result of the current event filtering step in
- a gesture recognizer state machine.
-
- The result consists of a state value (one of Ignore, MayBeGesture,
- TriggerGesture, FinishGesture, CancelGesture) and an optional hint
- (ConsumeEventHint).
-
- \value Ignore The event does not change the state of the recognizer.
-
- \value MayBeGesture The event changed the internal state of the recognizer,
- but it isn't clear yet if it is a gesture or not. The recognizer needs to
- filter more events to decide. Gesture recognizers in the MayBeGesture state
- may be reset automatically if they take too long to recognize gestures.
-
- \value TriggerGesture The gesture has been triggered and the appropriate
- QGesture object will be delivered to the target as a part of a
- QGestureEvent.
-
- \value FinishGesture The gesture has been finished successfully and the
- appropriate QGesture object will be delivered to the target as a part of a
- QGestureEvent.
-
- \value CancelGesture The event made it clear that it is not a gesture. If
- the gesture recognizer was in GestureTriggered state before, then the
- gesture is canceled and the appropriate QGesture object will be delivered
- to the target as a part of a QGestureEvent.
-
- \value ConsumeEventHint This hint specifies that the gesture framework
- should consume the filtered event and not deliver it to the receiver.
-
- \omitvalue ResultState_Mask
- \omitvalue ResultHint_Mask
-
- \sa QGestureRecognizer::recognize()
-*/
-
-/*!
- Constructs a new gesture recognizer object.
-*/
-QGestureRecognizer::QGestureRecognizer()
-{
-}
-
-/*!
- Destroys the gesture recognizer.
-*/
-QGestureRecognizer::~QGestureRecognizer()
-{
-}
-
-/*!
- This function is called by Qt to create a new QGesture object for the
- given \a target (QWidget or QGraphicsObject).
-
- Reimplement this function to create a custom QGesture-derived gesture
- object if necessary.
-
- The application takes ownership of the created gesture object.
-*/
-QGesture *QGestureRecognizer::create(QObject *target)
-{
- Q_UNUSED(target);
- return new QGesture;
-}
-
-/*!
- This function is called by the framework to reset a given \a gesture.
-
- Reimplement this function to implement additional requirements for custom QGesture
- objects. This may be necessary if you implement a custom QGesture whose properties
- need special handling when the gesture is reset.
-*/
-void QGestureRecognizer::reset(QGesture *gesture)
-{
- if (gesture) {
- QGesturePrivate *d = gesture->d_func();
- d->state = Qt::NoGesture;
- d->hotSpot = QPointF();
- d->sceneHotSpot = QPointF();
- d->isHotSpotSet = false;
- }
-}
-
-/*!
- \fn QGestureRecognizer::recognize(QGesture *gesture, QObject *watched, QEvent *event)
-
- Handles the given \a event for the \a watched object, updating the state of the \a gesture
- object as required, and returns a suitable result for the current recognition step.
-
- This function is called by the framework to allow the recognizer to filter input events
- dispatched to QWidget or QGraphicsObject instances that it is monitoring.
-
- The result reflects how much of the gesture has been recognized. The state of the
- \a gesture object is set depending on the result.
-
- \sa QGestureRecognizer::Result
-*/
-
-/*!
- Registers the given \a recognizer in the gesture framework and returns a gesture ID
- for it.
-
- The application takes ownership of the \a recognizer and returns the gesture type
- ID associated with it. For gesture recognizers which handle custom QGesture
- objects (i.e., those which return Qt::CustomGesture in a QGesture::gestureType()
- function) the return value is a generated gesture ID with the Qt::CustomGesture
- flag set.
-
- \sa unregisterRecognizer(), QGestureRecognizer::create(), QGesture
-*/
-Qt::GestureType QGestureRecognizer::registerRecognizer(QGestureRecognizer *recognizer)
-{
- return QGestureManager::instance()->registerGestureRecognizer(recognizer);
-}
-
-/*!
- Unregisters all gesture recognizers of the specified \a type.
-
- \sa registerRecognizer()
-*/
-void QGestureRecognizer::unregisterRecognizer(Qt::GestureType type)
-{
- QGestureManager::instance()->unregisterGestureRecognizer(type);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/kernel/qgesturerecognizer.h b/src/gui/kernel/qgesturerecognizer.h
deleted file mode 100644
index 80d978d6bb..0000000000
--- a/src/gui/kernel/qgesturerecognizer.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** 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 QGESTURERECOGNIZER_H
-#define QGESTURERECOGNIZER_H
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qnamespace.h>
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QObject;
-class QEvent;
-class QGesture;
-class Q_GUI_EXPORT QGestureRecognizer
-{
-public:
- enum ResultFlag
- {
- Ignore = 0x0001,
-
- MayBeGesture = 0x0002,
- TriggerGesture = 0x0004,
- FinishGesture = 0x0008,
- CancelGesture = 0x0010,
-
- ResultState_Mask = 0x00ff,
-
- ConsumeEventHint = 0x0100,
- // StoreEventHint = 0x0200,
- // ReplayStoredEventsHint = 0x0400,
- // DiscardStoredEventsHint = 0x0800,
-
- ResultHint_Mask = 0xff00
- };
- Q_DECLARE_FLAGS(Result, ResultFlag)
-
- QGestureRecognizer();
- virtual ~QGestureRecognizer();
-
- virtual QGesture *create(QObject *target);
- virtual Result recognize(QGesture *state, QObject *watched,
- QEvent *event) = 0;
- virtual void reset(QGesture *state);
-
- static Qt::GestureType registerRecognizer(QGestureRecognizer *recognizer);
- static void unregisterRecognizer(Qt::GestureType type);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QGestureRecognizer::Result)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_GESTURES
-
-#endif // QGESTURERECOGNIZER_H
diff --git a/src/gui/kernel/qgridlayout.cpp b/src/gui/kernel/qgridlayout.cpp
deleted file mode 100644
index 19d101a0b0..0000000000
--- a/src/gui/kernel/qgridlayout.cpp
+++ /dev/null
@@ -1,1889 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgridlayout.h"
-#include "qapplication.h"
-#include "qwidget.h"
-#include "qlist.h"
-#include "qsizepolicy.h"
-#include "qvector.h"
-#include "qvarlengtharray.h"
-#include "qlayoutengine_p.h"
-#include "qlayout_p.h"
-
-QT_BEGIN_NAMESPACE
-
-struct QGridLayoutSizeTriple
-{
- QSize minS;
- QSize hint;
- QSize maxS;
-};
-
-/*
- Three internal classes related to QGridLayout: (1) QGridBox is a
- QLayoutItem with (row, column) information and (torow, tocolumn) information; (3) QGridLayoutData is
- the internal representation of a QGridLayout.
-*/
-
-class QGridBox
-{
-public:
- QGridBox(QLayoutItem *lit) { item_ = lit; }
-
- QGridBox(const QLayout *l, QWidget *wid) { item_ = QLayoutPrivate::createWidgetItem(l, wid); }
- ~QGridBox() { delete item_; }
-
- QSize sizeHint() const { return item_->sizeHint(); }
- QSize minimumSize() const { return item_->minimumSize(); }
- QSize maximumSize() const { return item_->maximumSize(); }
- Qt::Orientations expandingDirections() const { return item_->expandingDirections(); }
- bool isEmpty() const { return item_->isEmpty(); }
-
- bool hasHeightForWidth() const { return item_->hasHeightForWidth(); }
- int heightForWidth(int w) const { return item_->heightForWidth(w); }
-
- void setAlignment(Qt::Alignment a) { item_->setAlignment(a); }
- void setGeometry(const QRect &r) { item_->setGeometry(r); }
- Qt::Alignment alignment() const { return item_->alignment(); }
- QLayoutItem *item() { return item_; }
- QLayoutItem *takeItem() { QLayoutItem *i = item_; item_ = 0; return i; }
-
- int hStretch() { return item_->widget() ?
- item_->widget()->sizePolicy().horizontalStretch() : 0; }
- int vStretch() { return item_->widget() ?
- item_->widget()->sizePolicy().verticalStretch() : 0; }
-
-private:
- friend class QGridLayoutPrivate;
- friend class QGridLayout;
-
- inline int toRow(int rr) const { return torow >= 0 ? torow : rr - 1; }
- inline int toCol(int cc) const { return tocol >= 0 ? tocol : cc - 1; }
-
- QLayoutItem *item_;
- int row, col;
- int torow, tocol;
-};
-
-class QGridLayoutPrivate : public QLayoutPrivate
-{
- Q_DECLARE_PUBLIC(QGridLayout)
-public:
- QGridLayoutPrivate();
-
- void add(QGridBox*, int row, int col);
- void add(QGridBox*, int row1, int row2, int col1, int col2);
- QSize sizeHint(int hSpacing, int vSpacing) const;
- QSize minimumSize(int hSpacing, int vSpacing) const;
- QSize maximumSize(int hSpacing, int vSpacing) const;
-
- Qt::Orientations expandingDirections(int hSpacing, int vSpacing) const;
-
- void distribute(QRect rect, int hSpacing, int vSpacing);
- inline int numRows() const { return rr; }
- inline int numCols() const { return cc; }
- inline void expand(int rows, int cols)
- { setSize(qMax(rows, rr), qMax(cols, cc)); }
- inline void setRowStretch(int r, int s)
- { expand(r + 1, 0); rStretch[r] = s; setDirty(); }
- inline void setColStretch(int c, int s)
- { expand(0, c + 1); cStretch[c] = s; setDirty(); }
- inline int rowStretch(int r) const { return rStretch.at(r); }
- inline int colStretch(int c) const { return cStretch.at(c); }
- inline void setRowMinimumHeight(int r, int s)
- { expand(r + 1, 0); rMinHeights[r] = s; setDirty(); }
- inline void setColumnMinimumWidth(int c, int s)
- { expand(0, c + 1); cMinWidths[c] = s; setDirty(); }
- inline int rowSpacing(int r) const { return rMinHeights.at(r); }
- inline int colSpacing(int c) const { return cMinWidths.at(c); }
-
- inline void setReversed(bool r, bool c) { hReversed = c; vReversed = r; }
- inline bool horReversed() const { return hReversed; }
- inline bool verReversed() const { return vReversed; }
- inline void setDirty() { needRecalc = true; hfw_width = -1; }
- inline bool isDirty() const { return needRecalc; }
- bool hasHeightForWidth(int hSpacing, int vSpacing);
- int heightForWidth(int width, int hSpacing, int vSpacing);
- int minimumHeightForWidth(int width, int hSpacing, int vSpacing);
-
- inline void getNextPos(int &row, int &col) { row = nextR; col = nextC; }
- inline int count() const { return things.count(); }
- QRect cellRect(int row, int col) const;
-
- inline QLayoutItem *itemAt(int index) const {
- if (index < things.count())
- return things.at(index)->item();
- else
- return 0;
- }
- inline QLayoutItem *takeAt(int index) {
- QLayoutItem *item = 0;
- if (index < things.count()) {
- QGridBox *b = things.takeAt(index);
- if (b) {
- item = b->takeItem();
- delete b;
- }
- }
- return item;
- }
-
- void getItemPosition(int index, int *row, int *column, int *rowSpan, int *columnSpan) {
- if (index < things.count()) {
- QGridBox *b = things.at(index);
- int toRow = b->toRow(rr);
- int toCol = b->toCol(cc);
- *row = b->row;
- *column = b->col;
- *rowSpan = toRow - *row + 1;
- *columnSpan = toCol - *column +1;
- }
- }
- void deleteAll();
-
-private:
- void setNextPosAfter(int r, int c);
- void recalcHFW(int w);
- void addHfwData(QGridBox *box, int width);
- void init();
- QSize findSize(int QLayoutStruct::*, int hSpacing, int vSpacing) const;
- void addData(QGridBox *b, const QGridLayoutSizeTriple &sizes, bool r, bool c);
- void setSize(int rows, int cols);
- void setupSpacings(QVector<QLayoutStruct> &chain, QGridBox *grid[], int fixedSpacing,
- Qt::Orientation orientation);
- void setupLayoutData(int hSpacing, int vSpacing);
- void setupHfwLayoutData();
- void effectiveMargins(int *left, int *top, int *right, int *bottom) const;
-
- int rr;
- int cc;
- QVector<QLayoutStruct> rowData;
- QVector<QLayoutStruct> colData;
- QVector<QLayoutStruct> *hfwData;
- QVector<int> rStretch;
- QVector<int> cStretch;
- QVector<int> rMinHeights;
- QVector<int> cMinWidths;
- QList<QGridBox *> things;
-
- int hfw_width;
- int hfw_height;
- int hfw_minheight;
- int nextR;
- int nextC;
-
- int horizontalSpacing;
- int verticalSpacing;
- int leftMargin;
- int topMargin;
- int rightMargin;
- int bottomMargin;
-
- uint hReversed : 1;
- uint vReversed : 1;
- uint needRecalc : 1;
- uint has_hfw : 1;
- uint addVertical : 1;
-};
-
-void QGridLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *bottom) const
-{
- int l = leftMargin;
- int t = topMargin;
- int r = rightMargin;
- int b = bottomMargin;
-#ifdef Q_WS_MAC
- int leftMost = INT_MAX;
- int topMost = INT_MAX;
- int rightMost = 0;
- int bottomMost = 0;
-
- QWidget *w = 0;
- const int n = things.count();
- for (int i = 0; i < n; ++i) {
- QGridBox *box = things.at(i);
- QLayoutItem *itm = box->item();
- w = itm->widget();
- if (w) {
- bool visualHReversed = hReversed != (w->layoutDirection() == Qt::RightToLeft);
- QRect lir = itm->geometry();
- QRect wr = w->geometry();
- if (box->col <= leftMost) {
- if (box->col < leftMost) {
- // we found an item even closer to the margin, discard.
- leftMost = box->col;
- if (visualHReversed)
- r = rightMargin;
- else
- l = leftMargin;
- }
- if (visualHReversed) {
- r = qMax(r, wr.right() - lir.right());
- } else {
- l = qMax(l, lir.left() - wr.left());
- }
- }
- if (box->row <= topMost) {
- if (box->row < topMost) {
- // we found an item even closer to the margin, discard.
- topMost = box->row;
- if (vReversed)
- b = bottomMargin;
- else
- t = topMargin;
- }
- if (vReversed)
- b = qMax(b, wr.bottom() - lir.bottom());
- else
- t = qMax(t, lir.top() - wr.top());
- }
- if (box->toCol(cc) >= rightMost) {
- if (box->toCol(cc) > rightMost) {
- // we found an item even closer to the margin, discard.
- rightMost = box->toCol(cc);
- if (visualHReversed)
- l = leftMargin;
- else
- r = rightMargin;
- }
- if (visualHReversed) {
- l = qMax(l, lir.left() - wr.left());
- } else {
- r = qMax(r, wr.right() - lir.right());
- }
-
- }
- if (box->toRow(rr) >= bottomMost) {
- if (box->toRow(rr) > bottomMost) {
- // we found an item even closer to the margin, discard.
- bottomMost = box->toRow(rr);
- if (vReversed)
- t = topMargin;
- else
- b = bottomMargin;
- }
- if (vReversed)
- t = qMax(t, lir.top() - wr.top());
- else
- b = qMax(b, wr.bottom() - lir.bottom());
- }
- }
- }
-
-#endif
- if (left)
- *left = l;
- if (top)
- *top = t;
- if (right)
- *right = r;
- if (bottom)
- *bottom = b;
-}
-
-QGridLayoutPrivate::QGridLayoutPrivate()
-{
- addVertical = false;
- setDirty();
- rr = cc = 0;
- nextR = nextC = 0;
- hfwData = 0;
- hReversed = false;
- vReversed = false;
- horizontalSpacing = -1;
- verticalSpacing = -1;
-}
-
-#if 0
-QGridLayoutPrivate::QGridLayoutPrivate(int nRows, int nCols)
- : rowData(0), colData(0)
-{
- init();
- if (nRows < 0) {
- nRows = 1;
- addVertical = false;
- }
- if (nCols < 0) {
- nCols = 1;
- addVertical = true;
- }
- setSize(nRows, nCols);
-}
-#endif
-
-void QGridLayoutPrivate::deleteAll()
-{
- while (!things.isEmpty())
- delete things.takeFirst();
- delete hfwData;
-}
-
-bool QGridLayoutPrivate::hasHeightForWidth(int hSpacing, int vSpacing)
-{
- setupLayoutData(hSpacing, vSpacing);
- return has_hfw;
-}
-
-/*
- Assumes that setupLayoutData() has been called, and that
- qGeomCalc() has filled in colData with appropriate values.
-*/
-void QGridLayoutPrivate::recalcHFW(int w)
-{
- /*
- Go through all children, using colData and heightForWidth()
- and put the results in hfwData.
- */
- if (!hfwData)
- hfwData = new QVector<QLayoutStruct>(rr);
- setupHfwLayoutData();
- QVector<QLayoutStruct> &rData = *hfwData;
-
- int h = 0;
- int mh = 0;
- for (int r = 0; r < rr; r++) {
- int spacing = rData.at(r).spacing;
- h += rData.at(r).sizeHint + spacing;
- mh += rData.at(r).minimumSize + spacing;
- }
-
- hfw_width = w;
- hfw_height = qMin(QLAYOUTSIZE_MAX, h);
- hfw_minheight = qMin(QLAYOUTSIZE_MAX, mh);
-}
-
-int QGridLayoutPrivate::heightForWidth(int w, int hSpacing, int vSpacing)
-{
- setupLayoutData(hSpacing, vSpacing);
- if (!has_hfw)
- return -1;
- int left, top, right, bottom;
- effectiveMargins(&left, &top, &right, &bottom);
-
- int hMargins = left + right;
- if (w - hMargins != hfw_width) {
- qGeomCalc(colData, 0, cc, 0, w - hMargins);
- recalcHFW(w - hMargins);
- }
- return hfw_height + top + bottom;
-}
-
-int QGridLayoutPrivate::minimumHeightForWidth(int w, int hSpacing, int vSpacing)
-{
- (void)heightForWidth(w, hSpacing, vSpacing);
- if (!has_hfw)
- return -1;
- int top, bottom;
- effectiveMargins(0, &top, 0, &bottom);
- return hfw_minheight + top + bottom;
-}
-
-QSize QGridLayoutPrivate::findSize(int QLayoutStruct::*size, int hSpacing, int vSpacing) const
-{
- QGridLayoutPrivate *that = const_cast<QGridLayoutPrivate*>(this);
- that->setupLayoutData(hSpacing, vSpacing);
-
- int w = 0;
- int h = 0;
-
- for (int r = 0; r < rr; r++)
- h += rowData.at(r).*size + rowData.at(r).spacing;
- for (int c = 0; c < cc; c++)
- w += colData.at(c).*size + colData.at(c).spacing;
-
- w = qMin(QLAYOUTSIZE_MAX, w);
- h = qMin(QLAYOUTSIZE_MAX, h);
-
- return QSize(w, h);
-}
-
-Qt::Orientations QGridLayoutPrivate::expandingDirections(int hSpacing, int vSpacing) const
-{
- QGridLayoutPrivate *that = const_cast<QGridLayoutPrivate*>(this);
- that->setupLayoutData(hSpacing, vSpacing);
- Qt::Orientations ret;
-
- for (int r = 0; r < rr; r++) {
- if (rowData.at(r).expansive) {
- ret |= Qt::Vertical;
- break;
- }
- }
- for (int c = 0; c < cc; c++) {
- if (colData.at(c).expansive) {
- ret |= Qt::Horizontal;
- break;
- }
- }
- return ret;
-}
-
-QSize QGridLayoutPrivate::sizeHint(int hSpacing, int vSpacing) const
-{
- return findSize(&QLayoutStruct::sizeHint, hSpacing, vSpacing);
-}
-
-QSize QGridLayoutPrivate::maximumSize(int hSpacing, int vSpacing) const
-{
- return findSize(&QLayoutStruct::maximumSize, hSpacing, vSpacing);
-}
-
-QSize QGridLayoutPrivate::minimumSize(int hSpacing, int vSpacing) const
-{
- return findSize(&QLayoutStruct::minimumSize, hSpacing, vSpacing);
-}
-
-void QGridLayoutPrivate::setSize(int r, int c)
-{
- if ((int)rowData.size() < r) {
- int newR = qMax(r, rr * 2);
- rowData.resize(newR);
- rStretch.resize(newR);
- rMinHeights.resize(newR);
- for (int i = rr; i < newR; i++) {
- rowData[i].init();
- rowData[i].maximumSize = 0;
- rowData[i].pos = 0;
- rowData[i].size = 0;
- rStretch[i] = 0;
- rMinHeights[i] = 0;
- }
- }
- if ((int)colData.size() < c) {
- int newC = qMax(c, cc * 2);
- colData.resize(newC);
- cStretch.resize(newC);
- cMinWidths.resize(newC);
- for (int i = cc; i < newC; i++) {
- colData[i].init();
- colData[i].maximumSize = 0;
- colData[i].pos = 0;
- colData[i].size = 0;
- cStretch[i] = 0;
- cMinWidths[i] = 0;
- }
- }
-
- if (hfwData && (int)hfwData->size() < r) {
- delete hfwData;
- hfwData = 0;
- hfw_width = -1;
- }
- rr = r;
- cc = c;
-}
-
-void QGridLayoutPrivate::setNextPosAfter(int row, int col)
-{
- if (addVertical) {
- if (col > nextC || (col == nextC && row >= nextR)) {
- nextR = row + 1;
- nextC = col;
- if (nextR >= rr) {
- nextR = 0;
- nextC++;
- }
- }
- } else {
- if (row > nextR || (row == nextR && col >= nextC)) {
- nextR = row;
- nextC = col + 1;
- if (nextC >= cc) {
- nextC = 0;
- nextR++;
- }
- }
- }
-}
-
-void QGridLayoutPrivate::add(QGridBox *box, int row, int col)
-{
- expand(row + 1, col + 1);
- box->row = box->torow = row;
- box->col = box->tocol = col;
- things.append(box);
- setDirty();
- setNextPosAfter(row, col);
-}
-
-void QGridLayoutPrivate::add(QGridBox *box, int row1, int row2, int col1, int col2)
-{
- if (row2 >= 0 && row2 < row1)
- qWarning("QGridLayout: Multi-cell fromRow greater than toRow");
- if (col2 >= 0 && col2 < col1)
- qWarning("QGridLayout: Multi-cell fromCol greater than toCol");
- if (row1 == row2 && col1 == col2) {
- add(box, row1, col1);
- return;
- }
- expand(row2 + 1, col2 + 1);
- box->row = row1;
- box->col = col1;
-
- box->torow = row2;
- box->tocol = col2;
-
- things.append(box);
- setDirty();
- if (col2 < 0)
- col2 = cc - 1;
-
- setNextPosAfter(row2, col2);
-}
-
-void QGridLayoutPrivate::addData(QGridBox *box, const QGridLayoutSizeTriple &sizes, bool r, bool c)
-{
- const QWidget *widget = box->item()->widget();
-
- if (box->isEmpty() && widget)
- return;
-
- if (c) {
- QLayoutStruct *data = &colData[box->col];
- if (!cStretch.at(box->col))
- data->stretch = qMax(data->stretch, box->hStretch());
- data->sizeHint = qMax(sizes.hint.width(), data->sizeHint);
- data->minimumSize = qMax(sizes.minS.width(), data->minimumSize);
-
- qMaxExpCalc(data->maximumSize, data->expansive, data->empty, sizes.maxS.width(),
- box->expandingDirections() & Qt::Horizontal, box->isEmpty());
- }
- if (r) {
- QLayoutStruct *data = &rowData[box->row];
- if (!rStretch.at(box->row))
- data->stretch = qMax(data->stretch, box->vStretch());
- data->sizeHint = qMax(sizes.hint.height(), data->sizeHint);
- data->minimumSize = qMax(sizes.minS.height(), data->minimumSize);
-
- qMaxExpCalc(data->maximumSize, data->expansive, data->empty, sizes.maxS.height(),
- box->expandingDirections() & Qt::Vertical, box->isEmpty());
- }
-}
-
-static void initEmptyMultiBox(QVector<QLayoutStruct> &chain, int start, int end)
-{
- for (int i = start; i <= end; i++) {
- QLayoutStruct *data = &chain[i];
- if (data->empty && data->maximumSize == 0) // truly empty box
- data->maximumSize = QWIDGETSIZE_MAX;
- data->empty = false;
- }
-}
-
-static void distributeMultiBox(QVector<QLayoutStruct> &chain, int start, int end, int minSize,
- int sizeHint, QVector<int> &stretchArray, int stretch)
-{
- int i;
- int w = 0;
- int wh = 0;
- int max = 0;
-
- for (i = start; i <= end; i++) {
- QLayoutStruct *data = &chain[i];
- w += data->minimumSize;
- wh += data->sizeHint;
- max += data->maximumSize;
- if (stretchArray.at(i) == 0)
- data->stretch = qMax(data->stretch, stretch);
-
- if (i != end) {
- int spacing = data->spacing;
- w += spacing;
- wh += spacing;
- max += spacing;
- }
- }
-
- if (max < minSize) { // implies w < minSize
- /*
- We must increase the maximum size of at least one of the
- items. qGeomCalc() will put the extra space in between the
- items. We must recover that extra space and put it
- somewhere. It does not really matter where, since the user
- can always specify stretch factors and avoid this code.
- */
- qGeomCalc(chain, start, end - start + 1, 0, minSize);
- int pos = 0;
- for (i = start; i <= end; i++) {
- QLayoutStruct *data = &chain[i];
- int nextPos = (i == end) ? minSize : chain.at(i + 1).pos;
- int realSize = nextPos - pos;
- if (i != end)
- realSize -= data->spacing;
- if (data->minimumSize < realSize)
- data->minimumSize = realSize;
- if (data->maximumSize < data->minimumSize)
- data->maximumSize = data->minimumSize;
- pos = nextPos;
- }
- } else if (w < minSize) {
- qGeomCalc(chain, start, end - start + 1, 0, minSize);
- for (i = start; i <= end; i++) {
- QLayoutStruct *data = &chain[i];
- if (data->minimumSize < data->size)
- data->minimumSize = data->size;
- }
- }
-
- if (wh < sizeHint) {
- qGeomCalc(chain, start, end - start + 1, 0, sizeHint);
- for (i = start; i <= end; i++) {
- QLayoutStruct *data = &chain[i];
- if (data->sizeHint < data->size)
- data->sizeHint = data->size;
- }
- }
-}
-
-static QGridBox *&gridAt(QGridBox *grid[], int r, int c, int cc,
- Qt::Orientation orientation = Qt::Vertical)
-{
- if (orientation == Qt::Horizontal)
- qSwap(r, c);
- return grid[(r * cc) + c];
-}
-
-void QGridLayoutPrivate::setupSpacings(QVector<QLayoutStruct> &chain,
- QGridBox *grid[], int fixedSpacing,
- Qt::Orientation orientation)
-{
- Q_Q(QGridLayout);
- int numRows = rr; // or columns if orientation is horizontal
- int numColumns = cc; // or rows if orientation is horizontal
-
- if (orientation == Qt::Horizontal) {
- qSwap(numRows, numColumns);
- }
-
- QStyle *style = 0;
- if (fixedSpacing < 0) {
- if (QWidget *parentWidget = q->parentWidget())
- style = parentWidget->style();
- }
-
- for (int c = 0; c < numColumns; ++c) {
- QGridBox *previousBox = 0;
- int previousRow = -1; // previous *non-empty* row
-
- for (int r = 0; r < numRows; ++r) {
- if (chain.at(r).empty)
- continue;
-
- QGridBox *box = gridAt(grid, r, c, cc, orientation);
- if (previousRow != -1 && (!box || previousBox != box)) {
- int spacing = fixedSpacing;
- if (spacing < 0) {
- QSizePolicy::ControlTypes controlTypes1 = QSizePolicy::DefaultType;
- QSizePolicy::ControlTypes controlTypes2 = QSizePolicy::DefaultType;
- if (previousBox)
- controlTypes1 = previousBox->item()->controlTypes();
- if (box)
- controlTypes2 = box->item()->controlTypes();
-
- if ((orientation == Qt::Horizontal && hReversed)
- || (orientation == Qt::Vertical && vReversed))
- qSwap(controlTypes1, controlTypes2);
-
- if (style)
- spacing = style->combinedLayoutSpacing(controlTypes1, controlTypes2,
- orientation, 0, q->parentWidget());
- } else {
- if (orientation == Qt::Vertical) {
- QGridBox *sibling = vReversed ? previousBox : box;
- if (sibling) {
- QWidget *wid = sibling->item()->widget();
- if (wid)
- spacing = qMax(spacing, sibling->item()->geometry().top() - wid->geometry().top() );
- }
- }
- }
-
- if (spacing > chain.at(previousRow).spacing)
- chain[previousRow].spacing = spacing;
- }
-
- previousBox = box;
- previousRow = r;
- }
- }
-}
-
-//#define QT_LAYOUT_DISABLE_CACHING
-
-void QGridLayoutPrivate::setupLayoutData(int hSpacing, int vSpacing)
-{
- Q_Q(QGridLayout);
-
-#ifndef QT_LAYOUT_DISABLE_CACHING
- if (!needRecalc)
- return;
-#endif
- has_hfw = false;
- int i;
-
- for (i = 0; i < rr; i++) {
- rowData[i].init(rStretch.at(i), rMinHeights.at(i));
- rowData[i].maximumSize = rStretch.at(i) ? QLAYOUTSIZE_MAX : rMinHeights.at(i);
- }
- for (i = 0; i < cc; i++) {
- colData[i].init(cStretch.at(i), cMinWidths.at(i));
- colData[i].maximumSize = cStretch.at(i) ? QLAYOUTSIZE_MAX : cMinWidths.at(i);
- }
-
- int n = things.size();
- QVarLengthArray<QGridLayoutSizeTriple> sizes(n);
-
- bool has_multi = false;
-
- /*
- Grid of items. We use it to determine which items are
- adjacent to which and compute the spacings correctly.
- */
- QVarLengthArray<QGridBox *> grid(rr * cc);
- qMemSet(grid.data(), 0, rr * cc * sizeof(QGridBox *));
-
- /*
- Initialize 'sizes' and 'grid' data structures, and insert
- non-spanning items to our row and column data structures.
- */
- for (i = 0; i < n; ++i) {
- QGridBox * const box = things.at(i);
- sizes[i].minS = box->minimumSize();
- sizes[i].hint = box->sizeHint();
- sizes[i].maxS = box->maximumSize();
-
- if (box->hasHeightForWidth())
- has_hfw = true;
-
- if (box->row == box->toRow(rr)) {
- addData(box, sizes[i], true, false);
- } else {
- initEmptyMultiBox(rowData, box->row, box->toRow(rr));
- has_multi = true;
- }
-
- if (box->col == box->toCol(cc)) {
- addData(box, sizes[i], false, true);
- } else {
- initEmptyMultiBox(colData, box->col, box->toCol(cc));
- has_multi = true;
- }
-
- for (int r = box->row; r <= box->toRow(rr); ++r) {
- for (int c = box->col; c <= box->toCol(cc); ++c) {
- gridAt(grid.data(), r, c, cc) = box;
- }
- }
- }
-
- setupSpacings(colData, grid.data(), hSpacing, Qt::Horizontal);
- setupSpacings(rowData, grid.data(), vSpacing, Qt::Vertical);
-
- /*
- Insert multicell items to our row and column data structures.
- This must be done after the non-spanning items to obtain a
- better distribution in distributeMultiBox().
- */
- if (has_multi) {
- for (i = 0; i < n; ++i) {
- QGridBox * const box = things.at(i);
-
- if (box->row != box->toRow(rr))
- distributeMultiBox(rowData, box->row, box->toRow(rr), sizes[i].minS.height(),
- sizes[i].hint.height(), rStretch, box->vStretch());
- if (box->col != box->toCol(cc))
- distributeMultiBox(colData, box->col, box->toCol(cc), sizes[i].minS.width(),
- sizes[i].hint.width(), cStretch, box->hStretch());
- }
- }
-
- for (i = 0; i < rr; i++)
- rowData[i].expansive = rowData.at(i).expansive || rowData.at(i).stretch > 0;
- for (i = 0; i < cc; i++)
- colData[i].expansive = colData.at(i).expansive || colData.at(i).stretch > 0;
-
- q->getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
-
- needRecalc = false;
-}
-
-void QGridLayoutPrivate::addHfwData(QGridBox *box, int width)
-{
- QVector<QLayoutStruct> &rData = *hfwData;
- if (box->hasHeightForWidth()) {
- int hint = box->heightForWidth(width);
- rData[box->row].sizeHint = qMax(hint, rData.at(box->row).sizeHint);
- rData[box->row].minimumSize = qMax(hint, rData.at(box->row).minimumSize);
- } else {
- QSize hint = box->sizeHint();
- QSize minS = box->minimumSize();
- rData[box->row].sizeHint = qMax(hint.height(), rData.at(box->row).sizeHint);
- rData[box->row].minimumSize = qMax(minS.height(), rData.at(box->row).minimumSize);
- }
-}
-
-/*
- Similar to setupLayoutData(), but uses heightForWidth(colData)
- instead of sizeHint(). Assumes that setupLayoutData() and
- qGeomCalc(colData) has been called.
-*/
-void QGridLayoutPrivate::setupHfwLayoutData()
-{
- QVector<QLayoutStruct> &rData = *hfwData;
- for (int i = 0; i < rr; i++) {
- rData[i] = rowData.at(i);
- rData[i].minimumSize = rData[i].sizeHint = rMinHeights.at(i);
- }
-
- for (int pass = 0; pass < 2; ++pass) {
- for (int i = 0; i < things.size(); ++i) {
- QGridBox *box = things.at(i);
- int r1 = box->row;
- int c1 = box->col;
- int r2 = box->toRow(rr);
- int c2 = box->toCol(cc);
- int w = colData.at(c2).pos + colData.at(c2).size - colData.at(c1).pos;
-
- if (r1 == r2) {
- if (pass == 0)
- addHfwData(box, w);
- } else {
- if (pass == 0) {
- initEmptyMultiBox(rData, r1, r2);
- } else {
- QSize hint = box->sizeHint();
- QSize min = box->minimumSize();
- if (box->hasHeightForWidth()) {
- int hfwh = box->heightForWidth(w);
- if (hfwh > hint.height())
- hint.setHeight(hfwh);
- if (hfwh > min.height())
- min.setHeight(hfwh);
- }
- distributeMultiBox(rData, r1, r2, min.height(), hint.height(),
- rStretch, box->vStretch());
- }
- }
- }
- }
- for (int i = 0; i < rr; i++)
- rData[i].expansive = rData.at(i).expansive || rData.at(i).stretch > 0;
-}
-
-void QGridLayoutPrivate::distribute(QRect r, int hSpacing, int vSpacing)
-{
- Q_Q(QGridLayout);
- bool visualHReversed = hReversed;
- QWidget *parent = q->parentWidget();
- if (parent && parent->isRightToLeft())
- visualHReversed = !visualHReversed;
-
- setupLayoutData(hSpacing, vSpacing);
-
- int left, top, right, bottom;
- effectiveMargins(&left, &top, &right, &bottom);
- r.adjust(+left, +top, -right, -bottom);
-
- qGeomCalc(colData, 0, cc, r.x(), r.width());
- QVector<QLayoutStruct> *rDataPtr;
- if (has_hfw) {
- recalcHFW(r.width());
- qGeomCalc(*hfwData, 0, rr, r.y(), r.height());
- rDataPtr = hfwData;
- } else {
- qGeomCalc(rowData, 0, rr, r.y(), r.height());
- rDataPtr = &rowData;
- }
- QVector<QLayoutStruct> &rData = *rDataPtr;
- int i;
-
- bool reverse = ((r.bottom() > rect.bottom()) || (r.bottom() == rect.bottom()
- && ((r.right() > rect.right()) != visualHReversed)));
- int n = things.size();
- for (i = 0; i < n; ++i) {
- QGridBox *box = things.at(reverse ? n-i-1 : i);
- int r2 = box->toRow(rr);
- int c2 = box->toCol(cc);
-
- int x = colData.at(box->col).pos;
- int y = rData.at(box->row).pos;
- int x2p = colData.at(c2).pos + colData.at(c2).size; // x2+1
- int y2p = rData.at(r2).pos + rData.at(r2).size; // y2+1
- int w = x2p - x;
- int h = y2p - y;
-
- if (visualHReversed)
- x = r.left() + r.right() - x - w + 1;
- if (vReversed)
- y = r.top() + r.bottom() - y - h + 1;
-
- box->setGeometry(QRect(x, y, w, h));
- }
-}
-
-QRect QGridLayoutPrivate::cellRect(int row, int col) const
-{
- if (row < 0 || row >= rr || col < 0 || col >= cc)
- return QRect();
-
- const QVector<QLayoutStruct> *rDataPtr;
- if (has_hfw && hfwData)
- rDataPtr = hfwData;
- else
- rDataPtr = &rowData;
- return QRect(colData.at(col).pos, rDataPtr->at(row).pos,
- colData.at(col).size, rDataPtr->at(row).size);
-}
-
-/*!
- \class QGridLayout
-
- \brief The QGridLayout class lays out widgets in a grid.
-
- \ingroup geomanagement
-
-
- QGridLayout takes the space made available to it (by its parent
- layout or by the parentWidget()), divides it up into rows and
- columns, and puts each widget it manages into the correct cell.
-
- Columns and rows behave identically; we will discuss columns, but
- there are equivalent functions for rows.
-
- Each column has a minimum width and a stretch factor. The minimum
- width is the greatest of that set using setColumnMinimumWidth() and the
- minimum width of each widget in that column. The stretch factor is
- set using setColumnStretch() and determines how much of the available
- space the column will get over and above its necessary minimum.
-
- Normally, each managed widget or layout is put into a cell of its
- own using addWidget(). It is also possible for a widget to occupy
- multiple cells using the row and column spanning overloads of
- addItem() and addWidget(). If you do this, QGridLayout will guess
- how to distribute the size over the columns/rows (based on the
- stretch factors).
-
- To remove a widget from a layout, call removeWidget(). Calling
- QWidget::hide() on a widget also effectively removes the widget
- from the layout until QWidget::show() is called.
-
- This illustration shows a fragment of a dialog with a five-column,
- three-row grid (the grid is shown overlaid in magenta):
-
- \image gridlayout.png A grid layout
-
- Columns 0, 2 and 4 in this dialog fragment are made up of a
- QLabel, a QLineEdit, and a QListBox. Columns 1 and 3 are
- placeholders made with setColumnMinimumWidth(). Row 0 consists of three
- QLabel objects, row 1 of three QLineEdit objects and row 2 of
- three QListBox objects. We used placeholder columns (1 and 3) to
- get the right amount of space between the columns.
-
- Note that the columns and rows are not equally wide or tall. If
- you want two columns to have the same width, you must set their
- minimum widths and stretch factors to be the same yourself. You do
- this using setColumnMinimumWidth() and setColumnStretch().
-
- If the QGridLayout is not the top-level layout (i.e. does not
- manage all of the widget's area and children), you must add it to
- its parent layout when you create it, but before you do anything
- with it. The normal way to add a layout is by calling
- addLayout() on the parent layout.
-
- Once you have added your layout you can start putting widgets and
- other layouts into the cells of your grid layout using
- addWidget(), addItem(), and addLayout().
-
- QGridLayout also includes two margin widths:
- the \l{getContentsMargins()}{contents margin} and the spacing().
- The contents margin is the width of the reserved space along each
- of the QGridLayout's four sides. The spacing() is the width of the
- automatically allocated spacing between neighboring boxes.
-
- The default contents margin values are provided by the
- \l{QStyle::pixelMetric()}{style}. The default value Qt styles specify
- is 9 for child widgets and 11 for windows. The spacing defaults to the same as
- the margin width for a top-level layout, or to the same as the
- parent layout.
-
- \sa QBoxLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example}
-*/
-
-
-/*!
- Constructs a new QGridLayout with parent widget, \a parent. The
- layout has one row and one column initially, and will expand when
- new items are inserted.
-*/
-QGridLayout::QGridLayout(QWidget *parent)
- : QLayout(*new QGridLayoutPrivate, 0, parent)
-{
- Q_D(QGridLayout);
- d->expand(1, 1);
-}
-
-/*!
- Constructs a new grid layout.
-
- You must insert this grid into another layout. You can insert
- widgets and layouts into this layout at any time, but laying out
- will not be performed before this is inserted into another layout.
-*/
-QGridLayout::QGridLayout()
- : QLayout(*new QGridLayoutPrivate, 0, 0)
-{
- Q_D(QGridLayout);
- d->expand(1, 1);
-}
-
-
-#ifdef QT3_SUPPORT
-/*!
- \obsolete
- Constructs a new QGridLayout with \a nRows rows, \a nCols columns
- and parent widget, \a parent. \a parent may not be 0. The grid
- layout is called \a name.
-
- \a margin is the number of pixels between the edge of the widget
- and its managed children. \a space is the default number of pixels
- between cells. If \a space is -1, the value of \a margin is used.
-*/
-QGridLayout::QGridLayout(QWidget *parent, int nRows, int nCols, int margin,
- int space, const char *name)
- : QLayout(*new QGridLayoutPrivate, 0, parent)
-{
- Q_D(QGridLayout);
- d->expand(nRows, nCols);
- setMargin(margin);
- setSpacing(space < 0 ? margin : space);
- setObjectName(QString::fromAscii(name));
-}
-
-/*!
- \obsolete
-
- Constructs a new grid with \a nRows rows and \a nCols columns. If
- \a spacing is -1, this QGridLayout inherits its parent's
- spacing(); otherwise \a spacing is used. The grid layout is called
- \a name.
-
- You must insert this grid into another layout. You can insert
- widgets and layouts into this layout at any time, but laying out
- will not be performed before this is inserted into another layout.
-*/
-QGridLayout::QGridLayout(QLayout *parentLayout, int nRows, int nCols,
- int spacing, const char *name)
- : QLayout(*new QGridLayoutPrivate, parentLayout, 0)
-{
- Q_D(QGridLayout);
- d->expand(nRows, nCols);
- setSpacing(spacing);
- setObjectName(QString::fromAscii(name));
-}
-
-/*!
- \obsolete
-
- Constructs a new grid with \a nRows rows and \a nCols columns. If
- \a spacing is -1, this QGridLayout inherits its parent's
- spacing(); otherwise \a spacing is used. The grid layout is called
- \a name.
-
- You must insert this grid into another layout. You can insert
- widgets and layouts into this layout at any time, but laying out
- will not be performed before this is inserted into another layout.
-*/
-QGridLayout::QGridLayout(int nRows, int nCols, int spacing, const char *name)
- : QLayout(*new QGridLayoutPrivate, 0, 0)
-{
- Q_D(QGridLayout);
- d->expand(nRows, nCols);
- setSpacing(spacing);
- setObjectName(QString::fromAscii(name));
-}
-#endif
-
-
-/*!
-\internal (mostly)
-
-Sets the positioning mode used by addItem(). If \a orient is
-Qt::Horizontal, this layout is expanded to \a n columns, and items
-will be added columns-first. Otherwise it is expanded to \a n rows and
-items will be added rows-first.
-*/
-
-void QGridLayout::setDefaultPositioning(int n, Qt::Orientation orient)
-{
- Q_D(QGridLayout);
- if (orient == Qt::Horizontal) {
- d->expand(1, n);
- d->addVertical = false;
- } else {
- d->expand(n,1);
- d->addVertical = true;
- }
-}
-
-
-/*!
- Destroys the grid layout. Geometry management is terminated if
- this is a top-level grid.
-
- The layout's widgets aren't destroyed.
-*/
-QGridLayout::~QGridLayout()
-{
- Q_D(QGridLayout);
- d->deleteAll();
-}
-
-/*!
- \property QGridLayout::horizontalSpacing
- \brief the spacing between widgets that are laid out side by side
- \since 4.3
-
- If no value is explicitly set, the layout's horizontal spacing is
- inherited from the parent layout, or from the style settings for
- the parent widget.
-
- \sa verticalSpacing, QStyle::pixelMetric(), {QStyle::}{PM_LayoutHorizontalSpacing}
-*/
-void QGridLayout::setHorizontalSpacing(int spacing)
-{
- Q_D(QGridLayout);
- d->horizontalSpacing = spacing;
- invalidate();
-}
-
-int QGridLayout::horizontalSpacing() const
-{
- Q_D(const QGridLayout);
- if (d->horizontalSpacing >= 0) {
- return d->horizontalSpacing;
- } else {
- return qSmartSpacing(this, QStyle::PM_LayoutHorizontalSpacing);
- }
-}
-
-/*!
- \property QGridLayout::verticalSpacing
- \brief the spacing between widgets that are laid out on top of each other
- \since 4.3
-
- If no value is explicitly set, the layout's vertical spacing is
- inherited from the parent layout, or from the style settings for
- the parent widget.
-
- \sa horizontalSpacing, QStyle::pixelMetric(), {QStyle::}{PM_LayoutHorizontalSpacing}
-*/
-void QGridLayout::setVerticalSpacing(int spacing)
-{
- Q_D(QGridLayout);
- d->verticalSpacing = spacing;
- invalidate();
-}
-
-int QGridLayout::verticalSpacing() const
-{
- Q_D(const QGridLayout);
- if (d->verticalSpacing >= 0) {
- return d->verticalSpacing;
- } else {
- return qSmartSpacing(this, QStyle::PM_LayoutVerticalSpacing);
- }
-}
-
-/*!
- This function sets both the vertical and horizontal spacing to
- \a spacing.
-
- \sa setVerticalSpacing(), setHorizontalSpacing()
-*/
-void QGridLayout::setSpacing(int spacing)
-{
- Q_D(QGridLayout);
- d->horizontalSpacing = d->verticalSpacing = spacing;
- invalidate();
-}
-
-/*!
- If the vertical spacing is equal to the horizontal spacing,
- this function returns that value; otherwise it return -1.
-
- \sa setSpacing(), verticalSpacing(), horizontalSpacing()
-*/
-int QGridLayout::spacing() const
-{
- int hSpacing = horizontalSpacing();
- if (hSpacing == verticalSpacing()) {
- return hSpacing;
- } else {
- return -1;
- }
-}
-
-/*!
- Returns the number of rows in this grid.
-*/
-int QGridLayout::rowCount() const
-{
- Q_D(const QGridLayout);
- return d->numRows();
-}
-
-/*!
- Returns the number of columns in this grid.
-*/
-int QGridLayout::columnCount() const
-{
- Q_D(const QGridLayout);
- return d->numCols();
-}
-
-/*!
- \reimp
-*/
-QSize QGridLayout::sizeHint() const
-{
- Q_D(const QGridLayout);
- QSize result(d->sizeHint(horizontalSpacing(), verticalSpacing()));
- int left, top, right, bottom;
- d->effectiveMargins(&left, &top, &right, &bottom);
- result += QSize(left + right, top + bottom);
- return result;
-}
-
-/*!
- \reimp
-*/
-QSize QGridLayout::minimumSize() const
-{
- Q_D(const QGridLayout);
- QSize result(d->minimumSize(horizontalSpacing(), verticalSpacing()));
- int left, top, right, bottom;
- d->effectiveMargins(&left, &top, &right, &bottom);
- result += QSize(left + right, top + bottom);
- return result;
-}
-
-/*!
- \reimp
-*/
-QSize QGridLayout::maximumSize() const
-{
- Q_D(const QGridLayout);
-
- QSize s = d->maximumSize(horizontalSpacing(), verticalSpacing());
- int left, top, right, bottom;
- d->effectiveMargins(&left, &top, &right, &bottom);
- s += QSize(left + right, top + bottom);
- s = s.boundedTo(QSize(QLAYOUTSIZE_MAX, QLAYOUTSIZE_MAX));
- if (alignment() & Qt::AlignHorizontal_Mask)
- s.setWidth(QLAYOUTSIZE_MAX);
- if (alignment() & Qt::AlignVertical_Mask)
- s.setHeight(QLAYOUTSIZE_MAX);
- return s;
-}
-
-/*!
- \reimp
-*/
-bool QGridLayout::hasHeightForWidth() const
-{
- return ((QGridLayout*)this)->d_func()->hasHeightForWidth(horizontalSpacing(), verticalSpacing());
-}
-
-/*!
- \reimp
-*/
-int QGridLayout::heightForWidth(int w) const
-{
- Q_D(const QGridLayout);
- QGridLayoutPrivate *dat = const_cast<QGridLayoutPrivate *>(d);
- return dat->heightForWidth(w, horizontalSpacing(), verticalSpacing());
-}
-
-/*!
- \reimp
-*/
-int QGridLayout::minimumHeightForWidth(int w) const
-{
- Q_D(const QGridLayout);
- QGridLayoutPrivate *dat = const_cast<QGridLayoutPrivate *>(d);
- return dat->minimumHeightForWidth(w, horizontalSpacing(), verticalSpacing());
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \compat
-
- Searches for widget \a w in this layout (not including child
- layouts). If \a w is found, it sets \c{*}\a{row} and
- \c{*}\a{column} to the row and column that the widget
- occupies and returns true; otherwise returns false.
-
- If the widget spans multiple rows/columns, the top-left cell
- is returned.
-
- Use indexOf() and getItemPosition() instead.
-*/
-bool QGridLayout::findWidget(QWidget* w, int *row, int *column)
-{
- Q_D(QGridLayout);
- int index = indexOf(w);
- if (index < 0)
- return false;
- int dummy1, dummy2;
- d->getItemPosition(index, row, column, &dummy1, &dummy2);
- return true;
-}
-#endif
-/*!
- \reimp
-*/
-int QGridLayout::count() const
-{
- Q_D(const QGridLayout);
- return d->count();
-}
-
-
-/*!
- \reimp
-*/
-QLayoutItem *QGridLayout::itemAt(int index) const
-{
- Q_D(const QGridLayout);
- return d->itemAt(index);
-}
-
-/*!
- \since 4.4
-
- Returns the layout item that occupies cell (\a row, \a column), or 0 if
- the cell is empty.
-
- \sa getItemPosition(), indexOf()
-*/
-QLayoutItem *QGridLayout::itemAtPosition(int row, int column) const
-{
- Q_D(const QGridLayout);
- int n = d->things.count();
- for (int i = 0; i < n; ++i) {
- QGridBox *box = d->things.at(i);
- if (row >= box->row && row <= box->toRow(d->rr)
- && column >= box->col && column <= box->toCol(d->cc)) {
- return box->item();
- }
- }
- return 0;
-}
-
-/*!
- \reimp
-*/
-QLayoutItem *QGridLayout::takeAt(int index)
-{
- Q_D(QGridLayout);
- return d->takeAt(index);
-}
-
-/*!
- Returns the position information of the item with the given \a index.
-
- The variables passed as \a row and \a column are updated with the position of the
- item in the layout, and the \a rowSpan and \a columnSpan variables are updated
- with the vertical and horizontal spans of the item.
-
- \sa itemAtPosition(), itemAt()
-*/
-void QGridLayout::getItemPosition(int index, int *row, int *column, int *rowSpan, int *columnSpan)
-{
- Q_D(QGridLayout);
- d->getItemPosition(index, row, column, rowSpan, columnSpan);
-}
-
-
-/*!
- \reimp
-*/
-void QGridLayout::setGeometry(const QRect &rect)
-{
- Q_D(QGridLayout);
- if (d->isDirty() || rect != geometry()) {
- QRect cr = alignment() ? alignmentRect(rect) : rect;
- d->distribute(cr, horizontalSpacing(), verticalSpacing());
- QLayout::setGeometry(rect);
- }
-}
-
-/*!
- Returns the geometry of the cell with row \a row and column \a column
- in the grid. Returns an invalid rectangle if \a row or \a column is
- outside the grid.
-
- \warning in the current version of Qt this function does not
- return valid results until setGeometry() has been called, i.e.
- after the parentWidget() is visible.
-*/
-QRect QGridLayout::cellRect(int row, int column) const
-{
- Q_D(const QGridLayout);
- return d->cellRect(row, column);
-}
-#ifdef QT3_SUPPORT
-/*!
- \obsolete
- Expands this grid so that it will have \a nRows rows and \a nCols
- columns. Will not shrink the grid. You should not need to call
- this function because QGridLayout expands automatically as new
- items are inserted.
-*/
-void QGridLayout::expand(int nRows, int nCols)
-{
- Q_D(QGridLayout);
- d->expand(nRows, nCols);
-}
-#endif
-
-/*!
- \reimp
-*/
-void QGridLayout::addItem(QLayoutItem *item)
-{
- Q_D(QGridLayout);
- int r, c;
- d->getNextPos(r, c);
- addItem(item, r, c);
-}
-
-/*!
- Adds \a item at position \a row, \a column, spanning \a rowSpan
- rows and \a columnSpan columns, and aligns it according to \a
- alignment. If \a rowSpan and/or \a columnSpan is -1, then the item
- will extend to the bottom and/or right edge, respectively. The
- layout takes ownership of the \a item.
-
- \warning Do not use this function to add child layouts or child
- widget items. Use addLayout() or addWidget() instead.
-*/
-void QGridLayout::addItem(QLayoutItem *item, int row, int column, int rowSpan, int columnSpan, Qt::Alignment alignment)
-{
- Q_D(QGridLayout);
- QGridBox *b = new QGridBox(item);
- b->setAlignment(alignment);
- d->add(b, row, (rowSpan < 0) ? -1 : row + rowSpan - 1, column, (columnSpan < 0) ? -1 : column + columnSpan - 1);
- invalidate();
-}
-
-/*
- Returns true if the widget \a w can be added to the layout \a l;
- otherwise returns false.
-*/
-static bool checkWidget(QLayout *l, QWidget *w)
-{
- if (!w) {
- qWarning("QLayout: Cannot add null widget to %s/%s", l->metaObject()->className(),
- l->objectName().toLocal8Bit().data());
- return false;
- }
- return true;
-}
-
-/*!
- Adds the given \a widget to the cell grid at \a row, \a column. The
- top-left position is (0, 0) by default.
-
- The alignment is specified by \a alignment. The default
- alignment is 0, which means that the widget fills the entire cell.
-
-*/
-void QGridLayout::addWidget(QWidget *widget, int row, int column, Qt::Alignment alignment)
-{
- if (!checkWidget(this, widget))
- return;
- if (row < 0 || column < 0) {
- qWarning("QGridLayout: Cannot add %s/%s to %s/%s at row %d column %d",
- widget->metaObject()->className(), widget->objectName().toLocal8Bit().data(),
- metaObject()->className(), objectName().toLocal8Bit().data(), row, column);
- return;
- }
- addChildWidget(widget);
- QWidgetItem *b = QLayoutPrivate::createWidgetItem(this, widget);
- addItem(b, row, column, 1, 1, alignment);
-}
-
-/*!
- \overload
-
- This version adds the given \a widget to the cell grid, spanning
- multiple rows/columns. The cell will start at \a fromRow, \a
- fromColumn spanning \a rowSpan rows and \a columnSpan columns. The
- \a widget will have the given \a alignment.
-
- If \a rowSpan and/or \a columnSpan is -1, then the widget will
- extend to the bottom and/or right edge, respectively.
-
-*/
-void QGridLayout::addWidget(QWidget *widget, int fromRow, int fromColumn,
- int rowSpan, int columnSpan, Qt::Alignment alignment)
-{
- Q_D(QGridLayout);
- if (!checkWidget(this, widget))
- return;
- int toRow = (rowSpan < 0) ? -1 : fromRow + rowSpan - 1;
- int toColumn = (columnSpan < 0) ? -1 : fromColumn + columnSpan - 1;
- addChildWidget(widget);
- QGridBox *b = new QGridBox(this, widget);
- b->setAlignment(alignment);
- d->add(b, fromRow, toRow, fromColumn, toColumn);
- invalidate();
-}
-
-/*!
- \fn void QGridLayout::addWidget(QWidget *widget)
-
- \overload
- \internal
-*/
-
-/*!
- Places the \a layout at position (\a row, \a column) in the grid. The
- top-left position is (0, 0).
-
- The alignment is specified by \a alignment. The default
- alignment is 0, which means that the widget fills the entire cell.
-
- A non-zero alignment indicates that the layout should not grow to
- fill the available space but should be sized according to
- sizeHint().
-
-
- \a layout becomes a child of the grid layout.
-*/
-void QGridLayout::addLayout(QLayout *layout, int row, int column, Qt::Alignment alignment)
-{
- Q_D(QGridLayout);
- addChildLayout(layout);
- QGridBox *b = new QGridBox(layout);
- b->setAlignment(alignment);
- d->add(b, row, column);
-}
-
-/*!
- \overload
- This version adds the layout \a layout to the cell grid, spanning multiple
- rows/columns. The cell will start at \a row, \a column spanning \a
- rowSpan rows and \a columnSpan columns.
-
- If \a rowSpan and/or \a columnSpan is -1, then the layout will extend to the bottom
- and/or right edge, respectively.
-*/
-void QGridLayout::addLayout(QLayout *layout, int row, int column,
- int rowSpan, int columnSpan, Qt::Alignment alignment)
-{
- Q_D(QGridLayout);
- addChildLayout(layout);
- QGridBox *b = new QGridBox(layout);
- b->setAlignment(alignment);
- d->add(b, row, (rowSpan < 0) ? -1 : row + rowSpan - 1, column, (columnSpan < 0) ? -1 : column + columnSpan - 1);
-}
-
-/*!
- Sets the stretch factor of row \a row to \a stretch. The first row
- is number 0.
-
- The stretch factor is relative to the other rows in this grid.
- Rows with a higher stretch factor take more of the available
- space.
-
- The default stretch factor is 0. If the stretch factor is 0 and no
- other row in this table can grow at all, the row may still grow.
-
- \sa rowStretch(), setRowMinimumHeight(), setColumnStretch()
-*/
-void QGridLayout::setRowStretch(int row, int stretch)
-{
- Q_D(QGridLayout);
- d->setRowStretch(row, stretch);
- invalidate();
-}
-
-/*!
- Returns the stretch factor for row \a row.
-
- \sa setRowStretch()
-*/
-int QGridLayout::rowStretch(int row) const
-{
- Q_D(const QGridLayout);
- return d->rowStretch(row);
-}
-
-/*!
- Returns the stretch factor for column \a column.
-
- \sa setColumnStretch()
-*/
-int QGridLayout::columnStretch(int column) const
-{
- Q_D(const QGridLayout);
- return d->colStretch(column);
-}
-
-/*!
- Sets the stretch factor of column \a column to \a stretch. The first
- column is number 0.
-
- The stretch factor is relative to the other columns in this grid.
- Columns with a higher stretch factor take more of the available
- space.
-
- The default stretch factor is 0. If the stretch factor is 0 and no
- other column in this table can grow at all, the column may still
- grow.
-
- An alternative approach is to add spacing using addItem() with a
- QSpacerItem.
-
- \sa columnStretch(), setRowStretch()
-*/
-void QGridLayout::setColumnStretch(int column, int stretch)
-{
- Q_D(QGridLayout);
- d->setColStretch(column, stretch);
- invalidate();
-}
-
-
-
-/*!
- Sets the minimum height of row \a row to \a minSize pixels.
-
- \sa rowMinimumHeight(), setColumnMinimumWidth()
-*/
-void QGridLayout::setRowMinimumHeight(int row, int minSize)
-{
- Q_D(QGridLayout);
- d->setRowMinimumHeight(row, minSize);
- invalidate();
-}
-
-/*!
- Returns the minimum width set for row \a row.
-
- \sa setRowMinimumHeight()
-*/
-int QGridLayout::rowMinimumHeight(int row) const
-{
- Q_D(const QGridLayout);
- return d->rowSpacing(row);
-}
-
-/*!
- Sets the minimum width of column \a column to \a minSize pixels.
-
- \sa columnMinimumWidth(), setRowMinimumHeight()
-*/
-void QGridLayout::setColumnMinimumWidth(int column, int minSize)
-{
- Q_D(QGridLayout);
- d->setColumnMinimumWidth(column, minSize);
- invalidate();
-}
-
-/*!
- Returns the column spacing for column \a column.
-
- \sa setColumnMinimumWidth()
-*/
-int QGridLayout::columnMinimumWidth(int column) const
-{
- Q_D(const QGridLayout);
- return d->colSpacing(column);
-}
-
-/*!
- \reimp
-*/
-Qt::Orientations QGridLayout::expandingDirections() const
-{
- Q_D(const QGridLayout);
- return d->expandingDirections(horizontalSpacing(), verticalSpacing());
-}
-
-/*!
- Sets the grid's origin corner, i.e. position (0, 0), to \a corner.
-*/
-void QGridLayout::setOriginCorner(Qt::Corner corner)
-{
- Q_D(QGridLayout);
- d->setReversed(corner == Qt::BottomLeftCorner || corner == Qt::BottomRightCorner,
- corner == Qt::TopRightCorner || corner == Qt::BottomRightCorner);
-}
-
-/*!
- Returns the corner that's used for the grid's origin, i.e. for
- position (0, 0).
-*/
-Qt::Corner QGridLayout::originCorner() const
-{
- Q_D(const QGridLayout);
- if (d->horReversed()) {
- return d->verReversed() ? Qt::BottomRightCorner : Qt::TopRightCorner;
- } else {
- return d->verReversed() ? Qt::BottomLeftCorner : Qt::TopLeftCorner;
- }
-}
-
-/*!
- \reimp
-*/
-void QGridLayout::invalidate()
-{
- Q_D(QGridLayout);
- d->setDirty();
- QLayout::invalidate();
-}
-
-/*!
- \fn void QGridLayout::addRowSpacing(int row, int minsize)
-
- Use addItem(new QSpacerItem(0, minsize), row, 0) instead.
-*/
-
-/*!
- \fn void QGridLayout::addColSpacing(int col, int minsize)
-
- Use addItem(new QSpacerItem(minsize, 0), 0, col) instead.
-*/
-
-/*!
- \fn void QGridLayout::addMultiCellWidget(QWidget *widget, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment align = 0)
-
- Use an addWidget() overload that allows you to specify row and
- column spans instead.
-*/
-
-/*!
- \fn void QGridLayout::addMultiCell(QLayoutItem *l, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment align = 0)
-
- Use an addItem() overload that allows you to specify row and
- column spans instead.
-*/
-
-/*!
- \fn void QGridLayout::addMultiCellLayout(QLayout *layout, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment align = 0)
-
- Use an addLayout() overload that allows you to specify row and
- column spans instead.
-*/
-
-/*!
- \fn int QGridLayout::numRows() const
-
- Use rowCount() instead.
-*/
-
-/*!
- \fn int QGridLayout::numCols() const
-
- Use columnCount() instead.
-*/
-
-/*!
- \fn void QGridLayout::setColStretch(int col, int stretch)
-
- Use setColumnStretch() instead.
-*/
-
-/*!
- \fn int QGridLayout::colStretch(int col) const
-
- Use columnStretch() instead.
-*/
-
-/*!
- \fn void QGridLayout::setColSpacing(int col, int minSize)
-
- Use setColumnMinimumWidth() instead.
-*/
-
-/*!
- \fn int QGridLayout::colSpacing(int col) const
-
- Use columnMinimumWidth() instead.
-*/
-
-/*!
- \fn void QGridLayout::setRowSpacing(int row, int minSize)
-
- Use setRowMinimumHeight(\a row, \a minSize) instead.
-*/
-
-/*!
- \fn int QGridLayout::rowSpacing(int row) const
-
- Use rowMinimumHeight(\a row) instead.
-*/
-
-/*!
- \fn QRect QGridLayout::cellGeometry(int row, int column) const
-
- Use cellRect(\a row, \a column) instead.
-*/
-
-/*!
- \fn void QGridLayout::setOrigin(Qt::Corner corner)
-
- Use setOriginCorner(\a corner) instead.
-*/
-
-/*!
- \fn Qt::Corner QGridLayout::origin() const
-
- Use originCorner() instead.
-*/
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qgridlayout.h b/src/gui/kernel/qgridlayout.h
deleted file mode 100644
index 0ac66e8f87..0000000000
--- a/src/gui/kernel/qgridlayout.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** 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 QGRIDLAYOUT_H
-#define QGRIDLAYOUT_H
-
-#include <QtGui/qlayout.h>
-#ifdef QT_INCLUDE_COMPAT
-#include <QtGui/qwidget.h>
-#endif
-
-#include <limits.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QGridLayoutPrivate;
-
-class Q_GUI_EXPORT QGridLayout : public QLayout
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QGridLayout)
- QDOC_PROPERTY(int horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing)
- QDOC_PROPERTY(int verticalSpacing READ verticalSpacing WRITE setVerticalSpacing)
-
-public:
- explicit QGridLayout(QWidget *parent);
- QGridLayout();
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QGridLayout(QWidget *parent, int nRows , int nCols = 1, int border = 0,
- int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QGridLayout(int nRows , int nCols = 1, int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QGridLayout(QLayout *parentLayout, int nRows = 1, int nCols = 1, int spacing = -1,
- const char *name = 0);
-#endif
- ~QGridLayout();
-
- QSize sizeHint() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
-
- void setHorizontalSpacing(int spacing);
- int horizontalSpacing() const;
- void setVerticalSpacing(int spacing);
- int verticalSpacing() const;
- void setSpacing(int spacing);
- int spacing() const;
-
- void setRowStretch(int row, int stretch);
- void setColumnStretch(int column, int stretch);
- int rowStretch(int row) const;
- int columnStretch(int column) const;
-
- void setRowMinimumHeight(int row, int minSize);
- void setColumnMinimumWidth(int column, int minSize);
- int rowMinimumHeight(int row) const;
- int columnMinimumWidth(int column) const;
-
- int columnCount() const;
- int rowCount() const;
-
- QRect cellRect(int row, int column) const;
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT QRect cellGeometry(int row, int column) const {return cellRect(row, column);}
-#endif
-
- bool hasHeightForWidth() const;
- int heightForWidth(int) const;
- int minimumHeightForWidth(int) const;
-
- Qt::Orientations expandingDirections() const;
- void invalidate();
-
- inline void addWidget(QWidget *w) { QLayout::addWidget(w); }
- void addWidget(QWidget *, int row, int column, Qt::Alignment = 0);
- void addWidget(QWidget *, int row, int column, int rowSpan, int columnSpan, Qt::Alignment = 0);
- void addLayout(QLayout *, int row, int column, Qt::Alignment = 0);
- void addLayout(QLayout *, int row, int column, int rowSpan, int columnSpan, Qt::Alignment = 0);
-
- void setOriginCorner(Qt::Corner);
- Qt::Corner originCorner() const;
-
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT void setOrigin(Qt::Corner corner) { setOriginCorner(corner); }
- inline QT3_SUPPORT Qt::Corner origin() const { return originCorner(); }
-#endif
- QLayoutItem *itemAt(int index) const;
- QLayoutItem *itemAtPosition(int row, int column) const;
- QLayoutItem *takeAt(int index);
- int count() const;
- void setGeometry(const QRect&);
-
- void addItem(QLayoutItem *item, int row, int column, int rowSpan = 1, int columnSpan = 1, Qt::Alignment = 0);
-
- void setDefaultPositioning(int n, Qt::Orientation orient);
- void getItemPosition(int idx, int *row, int *column, int *rowSpan, int *columnSpan);
-
-protected:
-#ifdef QT3_SUPPORT
- QT3_SUPPORT bool findWidget(QWidget* w, int *r, int *c);
-#endif
- void addItem(QLayoutItem *);
-
-private:
- Q_DISABLE_COPY(QGridLayout)
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT void expand(int rows, int cols);
- inline QT3_SUPPORT void addRowSpacing(int row, int minsize) { addItem(new QSpacerItem(0,minsize), row, 0); }
- inline QT3_SUPPORT void addColSpacing(int col, int minsize) { addItem(new QSpacerItem(minsize,0), 0, col); }
- inline QT3_SUPPORT void addMultiCellWidget(QWidget *w, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment _align = 0)
- { addWidget(w, fromRow, fromCol, (toRow < 0) ? -1 : toRow - fromRow + 1, (toCol < 0) ? -1 : toCol - fromCol + 1, _align); }
- inline QT3_SUPPORT void addMultiCell(QLayoutItem *l, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment _align = 0)
- { addItem(l, fromRow, fromCol, (toRow < 0) ? -1 : toRow - fromRow + 1, (toCol < 0) ? -1 : toCol - fromCol + 1, _align); }
- inline QT3_SUPPORT void addMultiCellLayout(QLayout *layout, int fromRow, int toRow, int fromCol, int toCol, Qt::Alignment _align = 0)
- { addLayout(layout, fromRow, fromCol, (toRow < 0) ? -1 : toRow - fromRow + 1, (toCol < 0) ? -1 : toCol - fromCol + 1, _align); }
-
- inline QT3_SUPPORT int numRows() const { return rowCount(); }
- inline QT3_SUPPORT int numCols() const { return columnCount(); }
- inline QT3_SUPPORT void setColStretch(int col, int stretch) {setColumnStretch(col, stretch); }
- inline QT3_SUPPORT int colStretch(int col) const {return columnStretch(col); }
- inline QT3_SUPPORT void setColSpacing(int col, int minSize) { setColumnMinimumWidth(col, minSize); }
- inline QT3_SUPPORT int colSpacing(int col) const { return columnMinimumWidth(col); }
- inline QT3_SUPPORT void setRowSpacing(int row, int minSize) {setRowMinimumHeight(row, minSize); }
- inline QT3_SUPPORT int rowSpacing(int row) const {return rowMinimumHeight(row); }
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QGRIDLAYOUT_H
diff --git a/src/gui/kernel/qguieventdispatcher_glib.cpp b/src/gui/kernel/qguieventdispatcher_glib.cpp
deleted file mode 100644
index 3fa10eb7e9..0000000000
--- a/src/gui/kernel/qguieventdispatcher_glib.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/****************************************************************************
-**
-** 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 "qguieventdispatcher_glib_p.h"
-
-#include "qapplication.h"
-#include "qx11info_x11.h"
-
-#include "qt_x11_p.h"
-
-#include <glib.h>
-
-QT_BEGIN_NAMESPACE
-
-struct GX11EventSource
-{
- GSource source;
- GPollFD pollfd;
- QEventLoop::ProcessEventsFlags flags;
- QGuiEventDispatcherGlib *q;
- QGuiEventDispatcherGlibPrivate *d;
-};
-
-class QGuiEventDispatcherGlibPrivate : public QEventDispatcherGlibPrivate
-{
- Q_DECLARE_PUBLIC(QGuiEventDispatcherGlib)
-
-public:
- QGuiEventDispatcherGlibPrivate();
- GX11EventSource *x11EventSource;
- QList<XEvent> queuedUserInputEvents;
-};
-
-static gboolean x11EventSourcePrepare(GSource *s, gint *timeout)
-{
- if (timeout)
- *timeout = -1;
- GX11EventSource *source = reinterpret_cast<GX11EventSource *>(s);
- return (XEventsQueued(X11->display, QueuedAfterFlush)
- || (!(source->flags & QEventLoop::ExcludeUserInputEvents)
- && !source->d->queuedUserInputEvents.isEmpty()));
-}
-
-static gboolean x11EventSourceCheck(GSource *s)
-{
- GX11EventSource *source = reinterpret_cast<GX11EventSource *>(s);
- return (XEventsQueued(X11->display, QueuedAfterFlush)
- || (!(source->flags & QEventLoop::ExcludeUserInputEvents)
- && !source->d->queuedUserInputEvents.isEmpty()));
-}
-
-static gboolean x11EventSourceDispatch(GSource *s, GSourceFunc callback, gpointer user_data)
-{
- GX11EventSource *source = reinterpret_cast<GX11EventSource *>(s);
-
- ulong marker = XNextRequest(X11->display);
- do {
- XEvent event;
- if (!(source->flags & QEventLoop::ExcludeUserInputEvents)
- && !source->d->queuedUserInputEvents.isEmpty()) {
- // process a pending user input event
- event = source->d->queuedUserInputEvents.takeFirst();
- } else if (XEventsQueued(X11->display, QueuedAlready)) {
- // process events from the X server
- XNextEvent(X11->display, &event);
-
- if (source->flags & QEventLoop::ExcludeUserInputEvents) {
- // queue user input events
- switch (event.type) {
- case ButtonPress:
- case ButtonRelease:
- case MotionNotify:
- case XKeyPress:
- case XKeyRelease:
- case EnterNotify:
- case LeaveNotify:
- source->d->queuedUserInputEvents.append(event);
- continue;
-
- case ClientMessage:
- // only keep the wm_take_focus and
- // _qt_scrolldone protocols, queue all other
- // client messages
- if (event.xclient.format == 32) {
- if (event.xclient.message_type == ATOM(WM_PROTOCOLS) &&
- (Atom) event.xclient.data.l[0] == ATOM(WM_TAKE_FOCUS)) {
- break;
- } else if (event.xclient.message_type == ATOM(_QT_SCROLL_DONE)) {
- break;
- }
- }
- source->d->queuedUserInputEvents.append(event);
- continue;
-
- default:
- break;
- }
- }
- } else {
- // no event to process
- break;
- }
-
- // send through event filter
- if (source->q->filterEvent(&event))
- continue;
-
- if (qApp->x11ProcessEvent(&event) == 1)
- return true;
-
- if (event.xany.serial >= marker)
- goto out;
- } while (XEventsQueued(X11->display, QueuedAfterFlush));
-
- out:
-
- source->d->runTimersOnceWithNormalPriority();
-
- if (callback)
- callback(user_data);
- return true;
-}
-
-static GSourceFuncs x11EventSourceFuncs = {
- x11EventSourcePrepare,
- x11EventSourceCheck,
- x11EventSourceDispatch,
- NULL,
- NULL,
- NULL
-};
-
-QGuiEventDispatcherGlibPrivate::QGuiEventDispatcherGlibPrivate()
-{
- x11EventSource = reinterpret_cast<GX11EventSource *>(g_source_new(&x11EventSourceFuncs,
- sizeof(GX11EventSource)));
- g_source_set_can_recurse(&x11EventSource->source, true);
-
- memset(&x11EventSource->pollfd, 0, sizeof(GPollFD));
- x11EventSource->flags = QEventLoop::AllEvents;
- x11EventSource->q = 0;
- x11EventSource->d = 0;
-
- g_source_attach(&x11EventSource->source, mainContext);
-}
-
-QGuiEventDispatcherGlib::QGuiEventDispatcherGlib(QObject *parent)
- : QEventDispatcherGlib(*new QGuiEventDispatcherGlibPrivate, parent)
-{
-}
-
-QGuiEventDispatcherGlib::~QGuiEventDispatcherGlib()
-{
- Q_D(QGuiEventDispatcherGlib);
-
- g_source_remove_poll(&d->x11EventSource->source, &d->x11EventSource->pollfd);
- g_source_destroy(&d->x11EventSource->source);
- d->x11EventSource = 0;
-}
-
-bool QGuiEventDispatcherGlib::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
- Q_D(QGuiEventDispatcherGlib);
- QEventLoop::ProcessEventsFlags saved_flags = d->x11EventSource->flags;
- d->x11EventSource->flags = flags;
- bool returnValue = QEventDispatcherGlib::processEvents(flags);
- d->x11EventSource->flags = saved_flags;
- return returnValue;
-}
-
-void QGuiEventDispatcherGlib::startingUp()
-{
- Q_D(QGuiEventDispatcherGlib);
- d->x11EventSource->pollfd.fd = XConnectionNumber(X11->display);
- d->x11EventSource->pollfd.events = G_IO_IN | G_IO_HUP | G_IO_ERR;
- d->x11EventSource->q = this;
- d->x11EventSource->d = d;
- g_source_add_poll(&d->x11EventSource->source, &d->x11EventSource->pollfd);
-}
-
-void QGuiEventDispatcherGlib::flush()
-{
- XFlush(X11->display);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qguieventdispatcher_glib_p.h b/src/gui/kernel/qguieventdispatcher_glib_p.h
deleted file mode 100644
index d37db93679..0000000000
--- a/src/gui/kernel/qguieventdispatcher_glib_p.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** 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 QGUIEVENTDISPATCHER_GLIB_P_H
-#define QGUIEVENTDISPATCHER_GLIB_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QLibrary class. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/private/qeventdispatcher_glib_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGuiEventDispatcherGlibPrivate;
-
-class QGuiEventDispatcherGlib : public QEventDispatcherGlib
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QGuiEventDispatcherGlib)
-
-public:
- explicit QGuiEventDispatcherGlib(QObject *parent = 0);
- ~QGuiEventDispatcherGlib();
-
- bool processEvents(QEventLoop::ProcessEventsFlags flags);
-
- void startingUp();
- void flush();
-};
-
-QT_END_NAMESPACE
-
-#endif // QGUIEVENTDISPATCHER_GLIB_P_H
diff --git a/src/gui/kernel/qguiplatformplugin.cpp b/src/gui/kernel/qguiplatformplugin.cpp
deleted file mode 100644
index 011b816e77..0000000000
--- a/src/gui/kernel/qguiplatformplugin.cpp
+++ /dev/null
@@ -1,298 +0,0 @@
-/****************************************************************************
-**
-** 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 "qguiplatformplugin_p.h"
-#include <qdebug.h>
-#include <qfile.h>
-#include <qdir.h>
-#include <qsettings.h>
-#include "private/qfactoryloader_p.h"
-#include "qstylefactory.h"
-#include "qapplication.h"
-#include "qplatformdefs.h"
-#include "qicon.h"
-
-#ifdef Q_WS_WINCE
-#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
-
-
-#if defined(Q_WS_X11)
-#include <private/qkde_p.h>
-#include <private/qgtkstyle_p.h>
-#include <private/qt_x11_p.h>
-#endif
-
-
-QT_BEGIN_NAMESPACE
-
-
-/*! \internal
- Return (an construct if necesseray) the Gui Platform plugin.
-
- The plugin key to be loaded is inside the QT_PLATFORM_PLUGIN environment variable.
- If it is not set, it will be the DESKTOP_SESSION on X11.
-
- If no plugin can be loaded, the default one is returned.
- */
-QGuiPlatformPlugin *qt_guiPlatformPlugin()
-{
- static QGuiPlatformPlugin *plugin;
- if (!plugin)
- {
-#ifndef QT_NO_LIBRARY
-
- QString key = QString::fromLocal8Bit(qgetenv("QT_PLATFORM_PLUGIN"));
-#ifdef Q_WS_X11
- if (key.isEmpty()) {
- switch(X11->desktopEnvironment) {
- case DE_KDE:
- key = QString::fromLatin1("kde");
- break;
- default:
- key = QString::fromLocal8Bit(qgetenv("DESKTOP_SESSION"));
- break;
- }
- }
-#endif
-
- if (!key.isEmpty() && QApplication::desktopSettingsAware()) {
- QFactoryLoader loader(QGuiPlatformPluginInterface_iid, QLatin1String("/gui_platform"));
- plugin = qobject_cast<QGuiPlatformPlugin *>(loader.instance(key));
- }
-#endif // QT_NO_LIBRARY
-
- if(!plugin) {
- static QGuiPlatformPlugin def;
- plugin = &def;
- }
- }
- return plugin;
-}
-
-
-/* \class QPlatformPlugin
- QGuiPlatformPlugin can be used to integrate Qt applications in a platform built on top of Qt.
- The application developer should not know or use the plugin, it is only used by Qt internaly.
-
- But full platform that are built on top of Qt may provide a plugin so 3rd party Qt application
- running in the platform are integrated.
- */
-
-/*
- The constructor can be used to install hooks in Qt
- */
-QGuiPlatformPlugin::QGuiPlatformPlugin(QObject *parent) : QObject(parent) {}
-QGuiPlatformPlugin::~QGuiPlatformPlugin() {}
-
-
-/* return the string key to be used by default the application */
-QString QGuiPlatformPlugin::styleName()
-{
-#if defined(Q_WS_WIN) && defined(Q_WS_WINCE)
- if (qt_wince_is_smartphone() || qt_wince_is_pocket_pc())
- return QLatin1String("WindowsMobile");
- else
- return QLatin1String("WindowsCE");
-#elif defined(Q_WS_WIN)
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- return QLatin1String("WindowsVista");
- else if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- return QLatin1String("WindowsXP");
- else
- return QLatin1String("Windows"); // default styles for Windows
-#elif defined(Q_WS_X11) && defined(Q_OS_SOLARIS)
- return QLatin1String("CDE"); // default style for X11 on Solaris
-#elif defined(Q_WS_S60)
- return QLatin1String("S60"); // default style for Symbian with S60
-#elif defined(Q_OS_SYMBIAN)
- return QLatin1String("Windows"); // default style for Symbian without S60
-#elif defined(Q_WS_X11) && defined(Q_OS_IRIX)
- return QLatin1String("SGI"); // default style for X11 on IRIX
-#elif defined(Q_WS_QWS) || defined(Q_WS_QPA)
- return QLatin1String("Plastique"); // default style for X11 and small devices
-#elif defined(Q_WS_MAC)
- return QLatin1String("Macintosh"); // default style for all Mac's
-#elif defined(Q_WS_X11)
- QString stylename;
- switch(X11->desktopEnvironment) {
- case DE_KDE:
- stylename = QKde::kdeStyle();
- break;
- case DE_GNOME: {
- QStringList availableStyles = QStyleFactory::keys();
- // Set QGtkStyle for GNOME if available
- QString gtkStyleKey = QString::fromLatin1("GTK+");
- if (availableStyles.contains(gtkStyleKey)) {
- stylename = gtkStyleKey;
- break;
- }
- if (X11->use_xrender)
- stylename = QLatin1String("cleanlooks");
- else
- stylename = QLatin1String("windows");
- break;
- }
- case DE_CDE:
- stylename = QLatin1String("cde");
- break;
- default:
- // Don't do anything
- break;
- }
- return stylename;
-#endif
-}
-
-/* return an additional default palette (only work on X11) */
-QPalette QGuiPlatformPlugin::palette()
-{
-#ifdef Q_WS_X11
- if (QApplication::desktopSettingsAware() && X11->desktopEnvironment == DE_KDE)
- return QKde::kdePalette();
-#endif
-
- return QPalette();
-}
-
-/* the default icon theme name for QIcon::fromTheme. */
-QString QGuiPlatformPlugin::systemIconThemeName()
-{
- QString result;
-#ifdef Q_WS_X11
- if (X11->desktopEnvironment == DE_GNOME) {
- result = QString::fromLatin1("gnome");
-#ifndef QT_NO_STYLE_GTK
- result = QGtkStylePrivate::getGConfString(QLatin1String("/desktop/gnome/interface/icon_theme"), result);
-#endif
- } else if (X11->desktopEnvironment == DE_KDE) {
- result = X11->desktopVersion >= 4 ? QString::fromLatin1("oxygen") : QString::fromLatin1("crystalsvg");
- QSettings settings(QKde::kdeHome() + QLatin1String("/share/config/kdeglobals"), QSettings::IniFormat);
- settings.beginGroup(QLatin1String("Icons"));
- result = settings.value(QLatin1String("Theme"), result).toString();
- }
-#endif
- return result;
-}
-
-
-QStringList QGuiPlatformPlugin::iconThemeSearchPaths()
-{
- QStringList paths;
-#if defined(Q_WS_X11)
- QString xdgDirString = QFile::decodeName(getenv("XDG_DATA_DIRS"));
- if (xdgDirString.isEmpty())
- xdgDirString = QLatin1String("/usr/local/share/:/usr/share/");
-
- QStringList xdgDirs = xdgDirString.split(QLatin1Char(':'));
-
- for (int i = 0 ; i < xdgDirs.size() ; ++i) {
- QDir dir(xdgDirs[i]);
- if (dir.exists())
- paths.append(dir.path() + QLatin1String("/icons"));
- }
- if (X11->desktopEnvironment == DE_KDE) {
- paths << QLatin1Char(':') + QKde::kdeHome() + QLatin1String("/share/icons");
- QStringList kdeDirs = QFile::decodeName(getenv("KDEDIRS")).split(QLatin1Char(':'));
- for (int i = 0 ; i< kdeDirs.count() ; ++i) {
- QDir dir(QLatin1Char(':') + kdeDirs.at(i) + QLatin1String("/share/icons"));
- if (dir.exists())
- paths.append(dir.path());
- }
- }
-
- // Add home directory first in search path
- QDir homeDir(QDir::homePath() + QLatin1String("/.icons"));
- if (homeDir.exists())
- paths.prepend(homeDir.path());
-#endif
-
-#if defined(Q_WS_WIN)
- paths.append(qApp->applicationDirPath() + QLatin1String("/icons"));
-#elif defined(Q_WS_MAC)
- paths.append(qApp->applicationDirPath() + QLatin1String("/../Resources/icons"));
-#endif
- return paths;
-}
-
-/* backend for QFileIconProvider, null icon means default */
-QIcon QGuiPlatformPlugin::fileSystemIcon(const QFileInfo &)
-{
- return QIcon();
-}
-
-/* Like QStyle::styleHint */
-int QGuiPlatformPlugin::platformHint(PlatformHint hint)
-{
- int ret = 0;
- switch(hint)
- {
- case PH_ToolButtonStyle:
- ret = Qt::ToolButtonIconOnly;
-#ifdef Q_WS_X11
- if (X11->desktopEnvironment == DE_KDE && X11->desktopVersion >= 4
- && QApplication::desktopSettingsAware()) {
- ret = QKde::kdeToolButtonStyle();
- }
-#endif
- break;
- case PH_ToolBarIconSize:
-#ifdef Q_WS_X11
- if (X11->desktopEnvironment == DE_KDE && X11->desktopVersion >= 4
- && QApplication::desktopSettingsAware()) {
- ret = QKde::kdeToolBarIconSize();
- }
-#endif
- //by default keep ret = 0 so QCommonStyle will use the style default
- break;
- default:
- break;
- }
- return ret;
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qguiplatformplugin_p.h b/src/gui/kernel/qguiplatformplugin_p.h
deleted file mode 100644
index 49e2d9294a..0000000000
--- a/src/gui/kernel/qguiplatformplugin_p.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/****************************************************************************
-**
-** 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 QGUIPLATFORM_P_H
-#define QGUIPLATFORM_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-#include <QtGui/qdialog.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStyle;
-class QPalette;
-class QIcon;
-class QFileDialog;
-class QColorDialog;
-class QFileInfo;
-
-struct Q_GUI_EXPORT QGuiPlatformPluginInterface : public QFactoryInterface
-{
-};
-
-#define QGuiPlatformPluginInterface_iid "com.nokia.qt.QGuiPlatformPluginInterface"
-
-Q_DECLARE_INTERFACE(QGuiPlatformPluginInterface, QGuiPlatformPluginInterface_iid)
-
-class Q_GUI_EXPORT QGuiPlatformPlugin : public QObject, public QGuiPlatformPluginInterface
-{
- Q_OBJECT
- Q_INTERFACES(QGuiPlatformPluginInterface:QFactoryInterface)
- public:
- explicit QGuiPlatformPlugin(QObject *parent = 0);
- ~QGuiPlatformPlugin();
-
- virtual QStringList keys() const { return QStringList() << QLatin1String("default"); };
-
- virtual QString styleName();
- virtual QPalette palette();
- virtual QString systemIconThemeName();
- virtual QStringList iconThemeSearchPaths();
- virtual QIcon fileSystemIcon(const QFileInfo &);
-
- enum PlatformHint { PH_ToolButtonStyle, PH_ToolBarIconSize, PH_ItemView_ActivateItemOnSingleClick };
- virtual int platformHint(PlatformHint hint);
-
-
- virtual void fileDialogDelete(QFileDialog *) {}
- virtual bool fileDialogSetVisible(QFileDialog *, bool) { return false; }
- virtual QDialog::DialogCode fileDialogResultCode(QFileDialog *) { return QDialog::Rejected; }
- virtual void fileDialogSetDirectory(QFileDialog *, const QString &) {}
- virtual QString fileDialogDirectory(const QFileDialog *) const { return QString(); }
- virtual void fileDialogSelectFile(QFileDialog *, const QString &) {}
- virtual QStringList fileDialogSelectedFiles(const QFileDialog *) const { return QStringList(); }
- virtual void fileDialogSetFilter(QFileDialog *) {}
- virtual void fileDialogSetNameFilters(QFileDialog *, const QStringList &) {}
- virtual void fileDialogSelectNameFilter(QFileDialog *, const QString &) {}
- virtual QString fileDialogSelectedNameFilter(const QFileDialog *) const { return QString(); }
-
- virtual void colorDialogDelete(QColorDialog *) {}
- virtual bool colorDialogSetVisible(QColorDialog *, bool) { return false; }
- virtual void colorDialogSetCurrentColor(QColorDialog *, const QColor &) {}
-};
-
-//internal
-QGuiPlatformPlugin *qt_guiPlatformPlugin();
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-
-#endif // QGUIPLATFORMPLUGIN_H
diff --git a/src/gui/kernel/qicon.cpp b/src/gui/kernel/qicon.cpp
deleted file mode 100644
index 59687c709d..0000000000
--- a/src/gui/kernel/qicon.cpp
+++ /dev/null
@@ -1,1165 +0,0 @@
-/****************************************************************************
-**
-** 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 "qicon.h"
-#include "qicon_p.h"
-#include "qiconengine.h"
-#include "qiconengineplugin.h"
-#include "private/qfactoryloader_p.h"
-#include "private/qiconloader_p.h"
-#include "qstyleoption.h"
-#include "qpainter.h"
-#include "qfileinfo.h"
-#include "qstyle.h"
-#include "qpixmapcache.h"
-#include "qvariant.h"
-#include "qcache.h"
-#include "qdebug.h"
-#include "private/qguiplatformplugin_p.h"
-#include "qguiapplication.h"
-
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#ifdef Q_WS_X11
-#include "private/qt_x11_p.h"
-#include "private/qkde_p.h"
-#endif
-
-#include "private/qhexstring_p.h"
-
-#ifndef QT_NO_ICON
-QT_BEGIN_NAMESPACE
-
-/*!
- \enum QIcon::Mode
-
- This enum type describes the mode for which a pixmap is intended
- to be used. The currently defined modes are:
-
- \value Normal
- Display the pixmap when the user is
- not interacting with the icon, but the
- functionality represented by the icon is available.
- \value Disabled
- Display the pixmap when the
- functionality represented by the icon is not available.
- \value Active
- Display the pixmap when the
- functionality represented by the icon is available and
- the user is interacting with the icon, for example, moving the
- mouse over it or clicking it.
- \value Selected
- Display the pixmap when the item represented by the icon is
- selected.
-*/
-
-/*!
- \enum QIcon::State
-
- This enum describes the state for which a pixmap is intended to be
- used. The \e state can be:
-
- \value Off Display the pixmap when the widget is in an "off" state
- \value On Display the pixmap when the widget is in an "on" state
-*/
-
-static QBasicAtomicInt serialNumCounter = Q_BASIC_ATOMIC_INITIALIZER(1);
-
-static void qt_cleanup_icon_cache();
-typedef QCache<QString, QIcon> IconCache;
-Q_GLOBAL_STATIC_WITH_INITIALIZER(IconCache, qtIconCache, qAddPostRoutine(qt_cleanup_icon_cache))
-
-static void qt_cleanup_icon_cache()
-{
- qtIconCache()->clear();
-}
-
-QIconPrivate::QIconPrivate()
- : engine(0), ref(1),
- serialNum(serialNumCounter.fetchAndAddRelaxed(1)),
- detach_no(0),
- engine_version(2),
- v1RefCount(0)
-{
-}
-
-QPixmapIconEngine::QPixmapIconEngine()
-{
-}
-
-QPixmapIconEngine::QPixmapIconEngine(const QPixmapIconEngine &other)
- : QIconEngineV2(other), pixmaps(other.pixmaps)
-{
-}
-
-QPixmapIconEngine::~QPixmapIconEngine()
-{
-}
-
-void QPixmapIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state)
-{
- QSize pixmapSize = rect.size();
-#if defined(Q_WS_MAC)
- pixmapSize *= qt_mac_get_scalefactor();
-#endif
- painter->drawPixmap(rect, pixmap(pixmapSize, mode, state));
-}
-
-static inline int area(const QSize &s) { return s.width() * s.height(); }
-
-// returns the smallest of the two that is still larger than or equal to size.
-static QPixmapIconEngineEntry *bestSizeMatch( const QSize &size, QPixmapIconEngineEntry *pa, QPixmapIconEngineEntry *pb)
-{
- int s = area(size);
- if (pa->size == QSize() && pa->pixmap.isNull()) {
- pa->pixmap = QPixmap(pa->fileName);
- pa->size = pa->pixmap.size();
- }
- int a = area(pa->size);
- if (pb->size == QSize() && pb->pixmap.isNull()) {
- pb->pixmap = QPixmap(pb->fileName);
- pb->size = pb->pixmap.size();
- }
- int b = area(pb->size);
- int res = a;
- if (qMin(a,b) >= s)
- res = qMin(a,b);
- else
- res = qMax(a,b);
- if (res == a)
- return pa;
- return pb;
-}
-
-QPixmapIconEngineEntry *QPixmapIconEngine::tryMatch(const QSize &size, QIcon::Mode mode, QIcon::State state)
-{
- QPixmapIconEngineEntry *pe = 0;
- for (int i = 0; i < pixmaps.count(); ++i)
- if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) {
- if (pe)
- pe = bestSizeMatch(size, &pixmaps[i], pe);
- else
- pe = &pixmaps[i];
- }
- return pe;
-}
-
-
-QPixmapIconEngineEntry *QPixmapIconEngine::bestMatch(const QSize &size, QIcon::Mode mode, QIcon::State state, bool sizeOnly)
-{
- QPixmapIconEngineEntry *pe = tryMatch(size, mode, state);
- while (!pe){
- QIcon::State oppositeState = (state == QIcon::On) ? QIcon::Off : QIcon::On;
- if (mode == QIcon::Disabled || mode == QIcon::Selected) {
- QIcon::Mode oppositeMode = (mode == QIcon::Disabled) ? QIcon::Selected : QIcon::Disabled;
- if ((pe = tryMatch(size, QIcon::Normal, state)))
- break;
- if ((pe = tryMatch(size, QIcon::Active, state)))
- break;
- if ((pe = tryMatch(size, mode, oppositeState)))
- break;
- if ((pe = tryMatch(size, QIcon::Normal, oppositeState)))
- break;
- if ((pe = tryMatch(size, QIcon::Active, oppositeState)))
- break;
- if ((pe = tryMatch(size, oppositeMode, state)))
- break;
- if ((pe = tryMatch(size, oppositeMode, oppositeState)))
- break;
- } else {
- QIcon::Mode oppositeMode = (mode == QIcon::Normal) ? QIcon::Active : QIcon::Normal;
- if ((pe = tryMatch(size, oppositeMode, state)))
- break;
- if ((pe = tryMatch(size, mode, oppositeState)))
- break;
- if ((pe = tryMatch(size, oppositeMode, oppositeState)))
- break;
- if ((pe = tryMatch(size, QIcon::Disabled, state)))
- break;
- if ((pe = tryMatch(size, QIcon::Selected, state)))
- break;
- if ((pe = tryMatch(size, QIcon::Disabled, oppositeState)))
- break;
- if ((pe = tryMatch(size, QIcon::Selected, oppositeState)))
- break;
- }
-
- if (!pe)
- return pe;
- }
-
- if (sizeOnly ? (pe->size.isNull() || !pe->size.isValid()) : pe->pixmap.isNull()) {
- pe->pixmap = QPixmap(pe->fileName);
- if (!pe->pixmap.isNull())
- pe->size = pe->pixmap.size();
- }
-
- return pe;
-}
-
-QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
-{
- QPixmap pm;
- QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, false);
- if (pe)
- pm = pe->pixmap;
-
- if (pm.isNull()) {
- int idx = pixmaps.count();
- while (--idx >= 0) {
- if (pe == &pixmaps[idx]) {
- pixmaps.remove(idx);
- break;
- }
- }
- if (pixmaps.isEmpty())
- return pm;
- else
- return pixmap(size, mode, state);
- }
-
- QSize actualSize = pm.size();
- if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
- actualSize.scale(size, Qt::KeepAspectRatio);
-
- // #### Qt5 no idea what this really does, but we need to remove the QApp and style references
-// QString key = QLatin1Literal("qt_")
-// % HexString<quint64>(pm.cacheKey())
-// % HexString<uint>(pe->mode)
-// % HexString<quint64>(QApplication::palette().cacheKey())
-// % HexString<uint>(actualSize.width())
-// % HexString<uint>(actualSize.height());
-
-// if (mode == QIcon::Active) {
-// if (QPixmapCache::find(key % HexString<uint>(mode), pm))
-// return pm; // horray
-// if (QPixmapCache::find(key % HexString<uint>(QIcon::Normal), pm)) {
-// QStyleOption opt(0);
-// opt.palette = QApplication::palette();
-// QPixmap active = QApplication::style()->generatedIconPixmap(QIcon::Active, pm, &opt);
-// if (pm.cacheKey() == active.cacheKey())
-// return pm;
-// }
-// }
-
-// if (!QPixmapCache::find(key % HexString<uint>(mode), pm)) {
- if (pm.size() != actualSize)
- pm = pm.scaled(actualSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
-// if (pe->mode != mode && mode != QIcon::Normal) {
-// QStyleOption opt(0);
-// opt.palette = QApplication::palette();
-// QPixmap generated = QApplication::style()->generatedIconPixmap(mode, pm, &opt);
-// if (!generated.isNull())
-// pm = generated;
-// }
-// QPixmapCache::insert(key % HexString<uint>(mode), pm);
-// }
- return pm;
-}
-
-QSize QPixmapIconEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state)
-{
- QSize actualSize;
- if (QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, true))
- actualSize = pe->size;
-
- if (actualSize.isNull())
- return actualSize;
-
- if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
- actualSize.scale(size, Qt::KeepAspectRatio);
- return actualSize;
-}
-
-void QPixmapIconEngine::addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state)
-{
- if (!pixmap.isNull()) {
- QPixmapIconEngineEntry *pe = tryMatch(pixmap.size(), mode, state);
- if(pe && pe->size == pixmap.size()) {
- pe->pixmap = pixmap;
- pe->fileName.clear();
- } else {
- pixmaps += QPixmapIconEngineEntry(pixmap, mode, state);
- }
- }
-}
-
-void QPixmapIconEngine::addFile(const QString &fileName, const QSize &_size, QIcon::Mode mode, QIcon::State state)
-{
- if (!fileName.isEmpty()) {
- QSize size = _size;
- QPixmap pixmap;
-
- QString abs = fileName;
- if (fileName.at(0) != QLatin1Char(':'))
- abs = QFileInfo(fileName).absoluteFilePath();
-
- for (int i = 0; i < pixmaps.count(); ++i) {
- if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) {
- QPixmapIconEngineEntry *pe = &pixmaps[i];
- if(size == QSize()) {
- pixmap = QPixmap(abs);
- size = pixmap.size();
- }
- if (pe->size == QSize() && pe->pixmap.isNull()) {
- pe->pixmap = QPixmap(pe->fileName);
- pe->size = pe->pixmap.size();
- }
- if(pe->size == size) {
- pe->pixmap = pixmap;
- pe->fileName = abs;
- return;
- }
- }
- }
- QPixmapIconEngineEntry e(abs, size, mode, state);
- e.pixmap = pixmap;
- pixmaps += e;
- }
-}
-
-QString QPixmapIconEngine::key() const
-{
- return QLatin1String("QPixmapIconEngine");
-}
-
-QIconEngineV2 *QPixmapIconEngine::clone() const
-{
- return new QPixmapIconEngine(*this);
-}
-
-bool QPixmapIconEngine::read(QDataStream &in)
-{
- int num_entries;
- QPixmap pm;
- QString fileName;
- QSize sz;
- uint mode;
- uint state;
-
- in >> num_entries;
- for (int i=0; i < num_entries; ++i) {
- if (in.atEnd()) {
- pixmaps.clear();
- return false;
- }
- in >> pm;
- in >> fileName;
- in >> sz;
- in >> mode;
- in >> state;
- if (pm.isNull()) {
- addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
- } else {
- QPixmapIconEngineEntry pe(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
- pe.pixmap = pm;
- pixmaps += pe;
- }
- }
- return true;
-}
-
-bool QPixmapIconEngine::write(QDataStream &out) const
-{
- int num_entries = pixmaps.size();
- out << num_entries;
- for (int i=0; i < num_entries; ++i) {
- if (pixmaps.at(i).pixmap.isNull())
- out << QPixmap(pixmaps.at(i).fileName);
- else
- out << pixmaps.at(i).pixmap;
- out << pixmaps.at(i).fileName;
- out << pixmaps.at(i).size;
- out << (uint) pixmaps.at(i).mode;
- out << (uint) pixmaps.at(i).state;
- }
- return true;
-}
-
-void QPixmapIconEngine::virtual_hook(int id, void *data)
-{
- switch (id) {
- case QIconEngineV2::AvailableSizesHook: {
- QIconEngineV2::AvailableSizesArgument &arg =
- *reinterpret_cast<QIconEngineV2::AvailableSizesArgument*>(data);
- arg.sizes.clear();
- for (int i = 0; i < pixmaps.size(); ++i) {
- QPixmapIconEngineEntry &pe = pixmaps[i];
- if (pe.size == QSize() && pe.pixmap.isNull()) {
- pe.pixmap = QPixmap(pe.fileName);
- pe.size = pe.pixmap.size();
- }
- if (pe.mode == arg.mode && pe.state == arg.state && !pe.size.isEmpty())
- arg.sizes.push_back(pe.size);
- }
- break;
- }
- default:
- QIconEngineV2::virtual_hook(id, data);
- }
-}
-
-#ifndef QT_NO_LIBRARY
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QIconEngineFactoryInterface_iid, QLatin1String("/iconengines"), Qt::CaseInsensitive))
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loaderV2,
- (QIconEngineFactoryInterfaceV2_iid, QLatin1String("/iconengines"), Qt::CaseInsensitive))
-#endif
-
-
-
-/*!
- \class QIcon
-
- \brief The QIcon class provides scalable icons in different modes
- and states.
-
- \ingroup painting
- \ingroup shared
-
-
- A QIcon can generate smaller, larger, active, and disabled pixmaps
- from the set of pixmaps it is given. Such pixmaps are used by Qt
- widgets to show an icon representing a particular action.
-
- The simplest use of QIcon is to create one from a QPixmap file or
- resource, and then use it, allowing Qt to work out all the required
- icon styles and sizes. For example:
-
- \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 0
-
- To undo a QIcon, simply set a null icon in its place:
-
- \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 1
-
- Use the QImageReader::supportedImageFormats() and
- QImageWriter::supportedImageFormats() functions to retrieve a
- complete list of the supported file formats.
-
- When you retrieve a pixmap using pixmap(QSize, Mode, State), and no
- pixmap for this given size, mode and state has been added with
- addFile() or addPixmap(), then QIcon will generate one on the
- fly. This pixmap generation happens in a QIconEngineV2. The default
- engine scales pixmaps down if required, but never up, and it uses
- the current style to calculate a disabled appearance. By using
- custom icon engines, you can customize every aspect of generated
- icons. With QIconEnginePluginV2 it is possible to register different
- icon engines for different file suffixes, making it possible for
- third parties to provide additional icon engines to those included
- with Qt.
-
- \note Since Qt 4.2, an icon engine that supports SVG is included.
-
- \section1 Making Classes that Use QIcon
-
- If you write your own widgets that have an option to set a small
- pixmap, consider allowing a QIcon to be set for that pixmap. The
- Qt class QToolButton is an example of such a widget.
-
- Provide a method to set a QIcon, and when you draw the icon, choose
- whichever pixmap is appropriate for the current state of your widget.
- For example:
- \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 2
-
- You might also make use of the \c Active mode, perhaps making your
- widget \c Active when the mouse is over the widget (see \l
- QWidget::enterEvent()), while the mouse is pressed pending the
- release that will activate the function, or when it is the currently
- selected item. If the widget can be toggled, the "On" mode might be
- used to draw a different icon.
-
- \img icon.png QIcon
-
- \sa {fowler}{GUI Design Handbook: Iconic Label}, {Icons Example}
-*/
-
-
-/*!
- Constructs a null icon.
-*/
-QIcon::QIcon()
- : d(0)
-{
-}
-
-/*!
- Constructs an icon from a \a pixmap.
- */
-QIcon::QIcon(const QPixmap &pixmap)
- :d(0)
-{
- addPixmap(pixmap);
-}
-
-/*!
- Constructs a copy of \a other. This is very fast.
-*/
-QIcon::QIcon(const QIcon &other)
- :d(other.d)
-{
- if (d)
- d->ref.ref();
-}
-
-/*!
- Constructs an icon from the file with the given \a fileName. The
- file will be loaded on demand.
-
- If \a fileName contains a relative path (e.g. the filename only)
- the relevant file must be found relative to the runtime working
- directory.
-
- The file name can be either refer to an actual file on disk or to
- one of the application's embedded resources. See the
- \l{resources.html}{Resource System} overview for details on how to
- embed images and other resource files in the application's
- executable.
-
- Use the QImageReader::supportedImageFormats() and
- QImageWriter::supportedImageFormats() functions to retrieve a
- complete list of the supported file formats.
-*/
-QIcon::QIcon(const QString &fileName)
- : d(0)
-{
- addFile(fileName);
-}
-
-
-/*!
- Creates an icon with a specific icon \a engine. The icon takes
- ownership of the engine.
-*/
-QIcon::QIcon(QIconEngine *engine)
- :d(new QIconPrivate)
-{
- d->engine_version = 1;
- d->engine = engine;
- d->v1RefCount = new QAtomicInt(1);
-}
-
-/*!
- Creates an icon with a specific icon \a engine. The icon takes
- ownership of the engine.
-*/
-QIcon::QIcon(QIconEngineV2 *engine)
- :d(new QIconPrivate)
-{
- d->engine_version = 2;
- d->engine = engine;
-}
-
-/*!
- Destroys the icon.
-*/
-QIcon::~QIcon()
-{
- if (d && !d->ref.deref())
- delete d;
-}
-
-/*!
- Assigns the \a other icon to this icon and returns a reference to
- this icon.
-*/
-QIcon &QIcon::operator=(const QIcon &other)
-{
- if (other.d)
- other.d->ref.ref();
- if (d && !d->ref.deref())
- delete d;
- d = other.d;
- return *this;
-}
-
-/*!
- \fn void QIcon::swap(QIcon &other)
- \since 4.8
-
- Swaps icon \a other with this icon. This operation is very
- fast and never fails.
-*/
-
-/*!
- Returns the icon as a QVariant.
-*/
-QIcon::operator QVariant() const
-{
- return QVariant(QVariant::Icon, this);
-}
-
-/*! \obsolete
-
- Returns a number that identifies the contents of this
- QIcon object. Distinct QIcon objects can have
- the same serial number if they refer to the same contents
- (but they don't have to). Also, the serial number of
- a QIcon object may change during its lifetime.
-
- Use cacheKey() instead.
-
- A null icon always has a serial number of 0.
-
- Serial numbers are mostly useful in conjunction with caching.
-
- \sa QPixmap::serialNumber()
-*/
-
-int QIcon::serialNumber() const
-{
- return d ? d->serialNum : 0;
-}
-
-/*!
- Returns a number that identifies the contents of this QIcon
- object. Distinct QIcon objects can have the same key if
- they refer to the same contents.
- \since 4.3
-
- The cacheKey() will change when the icon is altered via
- addPixmap() or addFile().
-
- Cache keys are mostly useful in conjunction with caching.
-
- \sa QPixmap::cacheKey()
-*/
-qint64 QIcon::cacheKey() const
-{
- if (!d)
- return 0;
- return (((qint64) d->serialNum) << 32) | ((qint64) (d->detach_no));
-}
-
-/*!
- Returns a pixmap with the requested \a size, \a mode, and \a
- state, generating one if necessary. The pixmap might be smaller than
- requested, but never larger.
-
- \sa actualSize(), paint()
-*/
-QPixmap QIcon::pixmap(const QSize &size, Mode mode, State state) const
-{
- if (!d)
- return QPixmap();
- return d->engine->pixmap(size, mode, state);
-}
-
-/*!
- \fn QPixmap QIcon::pixmap(int w, int h, Mode mode = Normal, State state = Off) const
-
- \overload
-
- Returns a pixmap of size QSize(\a w, \a h). The pixmap might be smaller than
- requested, but never larger.
-*/
-
-/*!
- \fn QPixmap QIcon::pixmap(int extent, Mode mode = Normal, State state = Off) const
-
- \overload
-
- Returns a pixmap of size QSize(\a extent, \a extent). The pixmap might be smaller
- than requested, but never larger.
-*/
-
-/*! Returns the actual size of the icon for the requested \a size, \a
- mode, and \a state. The result might be smaller than requested, but
- never larger.
-
- \sa pixmap(), paint()
-*/
-QSize QIcon::actualSize(const QSize &size, Mode mode, State state) const
-{
- if (!d)
- return QSize();
- return d->engine->actualSize(size, mode, state);
-}
-
-
-/*!
- Uses the \a painter to paint the icon with specified \a alignment,
- required \a mode, and \a state into the rectangle \a rect.
-
- \sa actualSize(), pixmap()
-*/
-void QIcon::paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment, Mode mode, State state) const
-{
- if (!d || !painter)
- return;
- QRect alignedRect = QStyle::alignedRect(painter->layoutDirection(), alignment, d->engine->actualSize(rect.size(), mode, state), rect);
- d->engine->paint(painter, alignedRect, mode, state);
-}
-
-/*!
- \fn void QIcon::paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment,
- Mode mode, State state) const
-
- \overload
-
- Paints the icon into the rectangle QRect(\a x, \a y, \a w, \a h).
-*/
-
-/*!
- Returns true if the icon is empty; otherwise returns false.
-
- An icon is empty if it has neither a pixmap nor a filename.
-
- Note: Even a non-null icon might not be able to create valid
- pixmaps, eg. if the file does not exist or cannot be read.
-*/
-bool QIcon::isNull() const
-{
- return !d;
-}
-
-/*!\internal
- */
-bool QIcon::isDetached() const
-{
- return !d || d->ref == 1;
-}
-
-/*! \internal
- */
-void QIcon::detach()
-{
- if (d) {
- if (d->ref != 1) {
- QIconPrivate *x = new QIconPrivate;
- if (d->engine_version > 1) {
- QIconEngineV2 *engine = static_cast<QIconEngineV2 *>(d->engine);
- x->engine = engine->clone();
- } else {
- x->engine = d->engine;
- x->v1RefCount = d->v1RefCount;
- x->v1RefCount->ref();
- }
- x->engine_version = d->engine_version;
- if (!d->ref.deref())
- delete d;
- d = x;
- }
- ++d->detach_no;
- }
-}
-
-/*!
- Adds \a pixmap to the icon, as a specialization for \a mode and
- \a state.
-
- Custom icon engines are free to ignore additionally added
- pixmaps.
-
- \sa addFile()
-*/
-void QIcon::addPixmap(const QPixmap &pixmap, Mode mode, State state)
-{
- if (pixmap.isNull())
- return;
- if (!d) {
- d = new QIconPrivate;
- d->engine = new QPixmapIconEngine;
- } else {
- detach();
- }
- d->engine->addPixmap(pixmap, mode, state);
-}
-
-
-/*! Adds an image from the file with the given \a fileName to the
- icon, as a specialization for \a size, \a mode and \a state. The
- file will be loaded on demand. Note: custom icon engines are free
- to ignore additionally added pixmaps.
-
- If \a fileName contains a relative path (e.g. the filename only)
- the relevant file must be found relative to the runtime working
- directory.
-
- The file name can be either refer to an actual file on disk or to
- one of the application's embedded resources. See the
- \l{resources.html}{Resource System} overview for details on how to
- embed images and other resource files in the application's
- executable.
-
- Use the QImageReader::supportedImageFormats() and
- QImageWriter::supportedImageFormats() functions to retrieve a
- complete list of the supported file formats.
-
- Note: When you add a non-empty filename to a QIcon, the icon becomes
- non-null, even if the file doesn't exist or points to a corrupt file.
-
- \sa addPixmap()
- */
-void QIcon::addFile(const QString &fileName, const QSize &size, Mode mode, State state)
-{
- if (fileName.isEmpty())
- return;
- if (!d) {
-#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
- QFileInfo info(fileName);
- QString suffix = info.suffix();
- if (!suffix.isEmpty()) {
- // first try version 2 engines..
- if (QIconEngineFactoryInterfaceV2 *factory = qobject_cast<QIconEngineFactoryInterfaceV2*>(loaderV2()->instance(suffix))) {
- if (QIconEngine *engine = factory->create(fileName)) {
- d = new QIconPrivate;
- d->engine = engine;
- }
- }
- // ..then fall back and try to load version 1 engines
- if (!d) {
- if (QIconEngineFactoryInterface *factory = qobject_cast<QIconEngineFactoryInterface*>(loader()->instance(suffix))) {
- if (QIconEngine *engine = factory->create(fileName)) {
- d = new QIconPrivate;
- d->engine = engine;
- d->engine_version = 1;
- d->v1RefCount = new QAtomicInt(1);
- }
- }
- }
- }
-#endif
- // ...then fall back to the default engine
- if (!d) {
- d = new QIconPrivate;
- d->engine = new QPixmapIconEngine;
- }
- } else {
- detach();
- }
- d->engine->addFile(fileName, size, mode, state);
-}
-
-/*!
- \since 4.5
-
- Returns a list of available icon sizes for the specified \a mode and
- \a state.
-*/
-QList<QSize> QIcon::availableSizes(Mode mode, State state) const
-{
- if (!d || !d->engine || d->engine_version < 2)
- return QList<QSize>();
- QIconEngineV2 *engine = static_cast<QIconEngineV2*>(d->engine);
- return engine->availableSizes(mode, state);
-}
-
-/*!
- \since 4.7
-
- Returns the name used to create the icon, if available.
-
- Depending on the way the icon was created, it may have an associated
- name. This is the case for icons created with fromTheme() or icons
- using a QIconEngine which supports the QIconEngineV2::IconNameHook.
-
- \sa fromTheme(), QIconEngine
-*/
-QString QIcon::name() const
-{
- if (!d || !d->engine || d->engine_version < 2)
- return QString();
- QIconEngineV2 *engine = static_cast<QIconEngineV2*>(d->engine);
- return engine->iconName();
-}
-
-/*!
- \since 4.6
-
- Sets the search paths for icon themes to \a paths.
- \sa themeSearchPaths(), fromTheme(), setThemeName()
-*/
-void QIcon::setThemeSearchPaths(const QStringList &paths)
-{
- QIconLoader::instance()->setThemeSearchPath(paths);
-}
-
-/*!
- \since 4.6
-
- Returns the search paths for icon themes.
-
- The default value will depend on the platform:
-
- On X11, the search path will use the XDG_DATA_DIRS environment
- variable if available.
-
- By default all platforms will have the resource directory
- \c{:\icons} as a fallback. You can use "rcc -project" to generate a
- resource file from your icon theme.
-
- \sa setThemeSearchPaths(), fromTheme(), setThemeName()
-*/
-QStringList QIcon::themeSearchPaths()
-{
- return QIconLoader::instance()->themeSearchPaths();
-}
-
-/*!
- \since 4.6
-
- Sets the current icon theme to \a name.
-
- The \a name should correspond to a directory name in the
- themeSearchPath() containing an index.theme
- file describing it's contents.
-
- \sa themeSearchPaths(), themeName()
-*/
-void QIcon::setThemeName(const QString &name)
-{
- QIconLoader::instance()->setThemeName(name);
-}
-
-/*!
- \since 4.6
-
- Returns the name of the current icon theme.
-
- On X11, the current icon theme depends on your desktop
- settings. On other platforms it is not set by default.
-
- \sa setThemeName(), themeSearchPaths(), fromTheme(),
- hasThemeIcon()
-*/
-QString QIcon::themeName()
-{
- return QIconLoader::instance()->themeName();
-}
-
-/*!
- \since 4.6
-
- Returns the QIcon corresponding to \a name in the current
- icon theme. If no such icon is found in the current theme
- \a fallback is returned instead.
-
- The latest version of the freedesktop icon specification and naming
- specification can be obtained here:
-
- \list
- \o \l{http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html}
- \o \l{http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html}
- \endlist
-
- To fetch an icon from the current icon theme:
-
- \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 3
-
- Or if you want to provide a guaranteed fallback for platforms that
- do not support theme icons, you can use the second argument:
-
- \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 4
-
- \note By default, only X11 will support themed icons. In order to
- use themed icons on Mac and Windows, you will have to bundle a
- compliant theme in one of your themeSearchPaths() and set the
- appropriate themeName().
-
- \sa themeName(), setThemeName(), themeSearchPaths()
-*/
-QIcon QIcon::fromTheme(const QString &name, const QIcon &fallback)
-{
- QIcon icon;
-
- if (qtIconCache()->contains(name)) {
- icon = *qtIconCache()->object(name);
- } else {
- QIcon *cachedIcon = new QIcon(new QIconLoaderEngine(name));
- qtIconCache()->insert(name, cachedIcon);
- icon = *cachedIcon;
- }
-
- // Note the qapp check is to allow lazy loading of static icons
- // Supporting fallbacks will not work for this case.
- if (qApp && icon.availableSizes().isEmpty())
- return fallback;
-
- return icon;
-}
-
-/*!
- \since 4.6
-
- Returns true if there is an icon available for \a name in the
- current icon theme, otherwise returns false.
-
- \sa themeSearchPaths(), fromTheme(), setThemeName()
-*/
-bool QIcon::hasThemeIcon(const QString &name)
-{
- QIcon icon = fromTheme(name);
-
- return !icon.isNull();
-}
-
-
-/*****************************************************************************
- QIcon stream functions
- *****************************************************************************/
-#if !defined(QT_NO_DATASTREAM)
-/*!
- \fn QDataStream &operator<<(QDataStream &stream, const QIcon &icon)
- \relates QIcon
- \since 4.2
-
- Writes the given \a icon to the given \a stream as a PNG
- image. If the icon contains more than one image, all images will
- be written to the stream. Note that writing the stream to a file
- will not produce a valid image file.
-*/
-
-QDataStream &operator<<(QDataStream &s, const QIcon &icon)
-{
- if (s.version() >= QDataStream::Qt_4_3) {
- if (icon.isNull()) {
- s << QString();
- } else {
- if (icon.d->engine_version > 1) {
- QIconEngineV2 *engine = static_cast<QIconEngineV2 *>(icon.d->engine);
- s << engine->key();
- engine->write(s);
- } else {
- // not really supported
- qWarning("QIcon: Cannot stream QIconEngine. Use QIconEngineV2 instead.");
- }
- }
- } else if (s.version() == QDataStream::Qt_4_2) {
- if (icon.isNull()) {
- s << 0;
- } else {
- QPixmapIconEngine *engine = static_cast<QPixmapIconEngine *>(icon.d->engine);
- int num_entries = engine->pixmaps.size();
- s << num_entries;
- for (int i=0; i < num_entries; ++i) {
- s << engine->pixmaps.at(i).pixmap;
- s << engine->pixmaps.at(i).fileName;
- s << engine->pixmaps.at(i).size;
- s << (uint) engine->pixmaps.at(i).mode;
- s << (uint) engine->pixmaps.at(i).state;
- }
- }
- } else {
- s << QPixmap(icon.pixmap(22,22));
- }
- return s;
-}
-
-/*!
- \fn QDataStream &operator>>(QDataStream &stream, QIcon &icon)
- \relates QIcon
- \since 4.2
-
- Reads an image, or a set of images, from the given \a stream into
- the given \a icon.
-*/
-
-QDataStream &operator>>(QDataStream &s, QIcon &icon)
-{
- if (s.version() >= QDataStream::Qt_4_3) {
- icon = QIcon();
- QString key;
- s >> key;
- if (key == QLatin1String("QPixmapIconEngine")) {
- icon.d = new QIconPrivate;
- QIconEngineV2 *engine = new QPixmapIconEngine;
- icon.d->engine = engine;
- engine->read(s);
- } else if (key == QLatin1String("QIconLoaderEngine")) {
- icon.d = new QIconPrivate;
- QIconEngineV2 *engine = new QIconLoaderEngine();
- icon.d->engine = engine;
- engine->read(s);
-#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
- } else if (QIconEngineFactoryInterfaceV2 *factory = qobject_cast<QIconEngineFactoryInterfaceV2*>(loaderV2()->instance(key))) {
- if (QIconEngineV2 *engine= factory->create()) {
- icon.d = new QIconPrivate;
- icon.d->engine = engine;
- engine->read(s);
- }
-#endif
- }
- } else if (s.version() == QDataStream::Qt_4_2) {
- icon = QIcon();
- int num_entries;
- QPixmap pm;
- QString fileName;
- QSize sz;
- uint mode;
- uint state;
-
- s >> num_entries;
- for (int i=0; i < num_entries; ++i) {
- s >> pm;
- s >> fileName;
- s >> sz;
- s >> mode;
- s >> state;
- if (pm.isNull())
- icon.addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
- else
- icon.addPixmap(pm, QIcon::Mode(mode), QIcon::State(state));
- }
- } else {
- QPixmap pm;
- s >> pm;
- icon.addPixmap(pm);
- }
- return s;
-}
-
-#endif //QT_NO_DATASTREAM
-
-/*!
- \fn DataPtr &QIcon::data_ptr()
- \internal
-*/
-
-/*!
- \typedef QIcon::DataPtr
- \internal
-*/
-
-QT_END_NAMESPACE
-#endif //QT_NO_ICON
diff --git a/src/gui/kernel/qicon.h b/src/gui/kernel/qicon.h
deleted file mode 100644
index 4e3960925e..0000000000
--- a/src/gui/kernel/qicon.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** 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 QICON_H
-#define QICON_H
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qsize.h>
-#include <QtCore/qlist.h>
-#include <QtGui/qpixmap.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QIconPrivate;
-class QIconEngine;
-class QIconEngineV2;
-
-class Q_GUI_EXPORT QIcon
-{
-public:
- enum Mode { Normal, Disabled, Active, Selected };
- enum State { On, Off };
-
- QIcon();
- QIcon(const QPixmap &pixmap);
- QIcon(const QIcon &other);
- explicit QIcon(const QString &fileName); // file or resource name
- explicit QIcon(QIconEngine *engine);
- explicit QIcon(QIconEngineV2 *engine);
- ~QIcon();
- QIcon &operator=(const QIcon &other);
-#ifdef Q_COMPILER_RVALUE_REFS
- inline QIcon &operator=(QIcon &&other)
- { qSwap(d, other.d); return *this; }
-#endif
- inline void swap(QIcon &other) { qSwap(d, other.d); }
-
- operator QVariant() const;
-
- QPixmap pixmap(const QSize &size, Mode mode = Normal, State state = Off) const;
- inline QPixmap pixmap(int w, int h, Mode mode = Normal, State state = Off) const
- { return pixmap(QSize(w, h), mode, state); }
- inline QPixmap pixmap(int extent, Mode mode = Normal, State state = Off) const
- { return pixmap(QSize(extent, extent), mode, state); }
-
- QSize actualSize(const QSize &size, Mode mode = Normal, State state = Off) const;
-
- QString name() const;
-
- void paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment = Qt::AlignCenter, Mode mode = Normal, State state = Off) const;
- inline void paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment = Qt::AlignCenter, Mode mode = Normal, State state = Off) const
- { paint(painter, QRect(x, y, w, h), alignment, mode, state); }
-
- bool isNull() const;
- bool isDetached() const;
- void detach();
-
- int serialNumber() const;
- qint64 cacheKey() const;
-
- void addPixmap(const QPixmap &pixmap, Mode mode = Normal, State state = Off);
- void addFile(const QString &fileName, const QSize &size = QSize(), Mode mode = Normal, State state = Off);
-
- QList<QSize> availableSizes(Mode mode = Normal, State state = Off) const;
-
- static QIcon fromTheme(const QString &name, const QIcon &fallback = QIcon());
- static bool hasThemeIcon(const QString &name);
-
- static QStringList themeSearchPaths();
- static void setThemeSearchPaths(const QStringList &searchpath);
-
- static QString themeName();
- static void setThemeName(const QString &path);
-
- Q_DUMMY_COMPARISON_OPERATOR(QIcon)
-
-private:
- QIconPrivate *d;
-#if !defined(QT_NO_DATASTREAM)
- friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QIcon &);
- friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QIcon &);
-#endif
-
-public:
- typedef QIconPrivate * DataPtr;
- inline DataPtr &data_ptr() { return d; }
-};
-
-Q_DECLARE_SHARED(QIcon)
-Q_DECLARE_TYPEINFO(QIcon, Q_MOVABLE_TYPE);
-
-#if !defined(QT_NO_DATASTREAM)
-Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QIcon &);
-Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QIcon &);
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QICON_H
diff --git a/src/gui/kernel/qicon_p.h b/src/gui/kernel/qicon_p.h
deleted file mode 100644
index 0bf7e65cc1..0000000000
--- a/src/gui/kernel/qicon_p.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/****************************************************************************
-**
-** 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 QICON_P_H
-#define QICON_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qsize.h>
-#include <QtCore/qlist.h>
-#include <QtGui/qpixmap.h>
-#include <QtGui/qicon.h>
-#include <QtGui/qiconengine.h>
-
-#ifndef QT_NO_ICON
-QT_BEGIN_NAMESPACE
-
-class QIconPrivate
-{
-public:
- QIconPrivate();
-
- ~QIconPrivate() {
- if (engine_version == 1) {
- if (!v1RefCount->deref()) {
- delete engine;
- delete v1RefCount;
- }
- } else if (engine_version == 2) {
- delete engine;
- }
- }
-
- QIconEngine *engine;
-
- QAtomicInt ref;
- int serialNum;
- int detach_no;
- int engine_version;
-
- QAtomicInt *v1RefCount;
-};
-
-
-struct QPixmapIconEngineEntry
-{
- QPixmapIconEngineEntry():mode(QIcon::Normal), state(QIcon::Off){}
- QPixmapIconEngineEntry(const QPixmap &pm, QIcon::Mode m = QIcon::Normal, QIcon::State s = QIcon::Off)
- :pixmap(pm), size(pm.size()), mode(m), state(s){}
- QPixmapIconEngineEntry(const QString &file, const QSize &sz = QSize(), QIcon::Mode m = QIcon::Normal, QIcon::State s = QIcon::Off)
- :fileName(file), size(sz), mode(m), state(s){}
- QPixmap pixmap;
- QString fileName;
- QSize size;
- QIcon::Mode mode;
- QIcon::State state;
- bool isNull() const {return (fileName.isEmpty() && pixmap.isNull()); }
-};
-
-
-
-class QPixmapIconEngine : public QIconEngineV2 {
-public:
- QPixmapIconEngine();
- QPixmapIconEngine(const QPixmapIconEngine &);
- ~QPixmapIconEngine();
- void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state);
- QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state);
- QPixmapIconEngineEntry *bestMatch(const QSize &size, QIcon::Mode mode, QIcon::State state, bool sizeOnly);
- QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state);
- void addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state);
- void addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state);
-
- // v2 functions
- QString key() const;
- QIconEngineV2 *clone() const;
- bool read(QDataStream &in);
- bool write(QDataStream &out) const;
- void virtual_hook(int id, void *data);
-
-private:
- QPixmapIconEngineEntry *tryMatch(const QSize &size, QIcon::Mode mode, QIcon::State state);
- QVector<QPixmapIconEngineEntry> pixmaps;
-
- friend QDataStream &operator<<(QDataStream &s, const QIcon &icon);
- friend class QIconThemeEngine;
-};
-
-QT_END_NAMESPACE
-#endif //QT_NO_ICON
-#endif // QICON_P_H
diff --git a/src/gui/kernel/qiconengine.cpp b/src/gui/kernel/qiconengine.cpp
deleted file mode 100644
index 6168a83940..0000000000
--- a/src/gui/kernel/qiconengine.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-/****************************************************************************
-**
-** 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 "qiconengine.h"
-#include "qpainter.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QIconEngine
-
- \brief The QIconEngine class provides an abstract base class for QIcon renderers.
-
- \ingroup painting
-
- \bold {Use QIconEngineV2 instead.}
-
- An icon engine provides the rendering functions for a QIcon. Each icon has a
- corresponding icon engine that is responsible for drawing the icon with a
- requested size, mode and state.
-
- The icon is rendered by the paint() function, and the icon can additionally be
- obtained as a pixmap with the pixmap() function (the default implementation
- simply uses paint() to achieve this). The addPixmap() function can be used to
- add new pixmaps to the icon engine, and is used by QIcon to add specialized
- custom pixmaps.
-
- The paint(), pixmap(), and addPixmap() functions are all virtual, and can
- therefore be reimplemented in subclasses of QIconEngine.
-
- \sa QIconEngineV2, QIconEnginePlugin
-
-*/
-
-/*!
- \fn virtual void QIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) = 0;
-
- Uses the given \a painter to paint the icon with the required \a mode and
- \a state into the rectangle \a rect.
-*/
-
-/*! Returns the actual size of the icon the engine provides for the
- requested \a size, \a mode and \a state. The default implementation
- returns the given \a size.
- */
-QSize QIconEngine::actualSize(const QSize &size, QIcon::Mode /*mode*/, QIcon::State /*state*/)
-{
- return size;
-}
-
-
-/*!
- Destroys the icon engine.
- */
-QIconEngine::~QIconEngine()
-{
-}
-
-
-/*!
- Returns the icon as a pixmap with the required \a size, \a mode,
- and \a state. The default implementation creates a new pixmap and
- calls paint() to fill it.
-*/
-QPixmap QIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
-{
- QPixmap pm(size);
- {
- QPainter p(&pm);
- paint(&p, QRect(QPoint(0,0),size), mode, state);
- }
- return pm;
-}
-
-/*!
- Called by QIcon::addPixmap(). Adds a specialized \a pixmap for the given
- \a mode and \a state. The default pixmap-based engine stores any supplied
- pixmaps, and it uses them instead of scaled pixmaps if the size of a pixmap
- matches the size of icon requested. Custom icon engines that implement
- scalable vector formats are free to ignores any extra pixmaps.
- */
-void QIconEngine::addPixmap(const QPixmap &/*pixmap*/, QIcon::Mode /*mode*/, QIcon::State /*state*/)
-{
-}
-
-
-/*! Called by QIcon::addFile(). Adds a specialized pixmap from the
- file with the given \a fileName, \a size, \a mode and \a state. The
- default pixmap-based engine stores any supplied file names, and it
- loads the pixmaps on demand instead of using scaled pixmaps if the
- size of a pixmap matches the size of icon requested. Custom icon
- engines that implement scalable vector formats are free to ignores
- any extra files.
- */
-void QIconEngine::addFile(const QString &/*fileName*/, const QSize &/*size*/, QIcon::Mode /*mode*/, QIcon::State /*state*/)
-{
-}
-
-
-
-// version 2 functions
-
-
-/*!
- \class QIconEngineV2
-
- \brief The QIconEngineV2 class provides an abstract base class for QIcon renderers.
-
- \ingroup painting
- \since 4.3
-
- An icon engine renders \l{QIcon}s. With icon engines, you can
- customize icons. Qt provides a default engine that makes icons
- adhere to the current style by scaling the icons and providing a
- disabled appearance.
-
- An engine is installed on an icon either through a QIcon
- constructor or through a QIconEnginePluginV2. The plugins are used
- by Qt if a specific engine is not given when the icon is created.
- See the QIconEngineV2 class description to learn how to create
- icon engine plugins.
-
- An icon engine provides the rendering functions for a QIcon. Each
- icon has a corresponding icon engine that is responsible for drawing
- the icon with a requested size, mode and state.
-
- QIconEngineV2 extends the API of QIconEngine to allow streaming of
- the icon engine contents, and should be used instead of QIconEngine
- for implementing new icon engines.
-
- \sa QIconEnginePluginV2
-
-*/
-
-/*!
- \enum QIconEngineV2::IconEngineHook
- \since 4.5
-
- These enum values are used for virtual_hook() to allow additional
- queries to icon engine without breaking binary compatibility.
-
- \value AvailableSizesHook Allows to query the sizes of the
- contained pixmaps for pixmap-based engines. The \a data argument
- of the virtual_hook() function is a AvailableSizesArgument pointer
- that should be filled with icon sizes. Engines that work in terms
- of a scalable, vectorial format normally return an empty list.
-
- \value IconNameHook Allows to query the name used to create the
- icon, for example when instantiating an icon using
- QIcon::fromTheme().
-
- \sa virtual_hook()
- */
-
-/*!
- \class QIconEngineV2::AvailableSizesArgument
- \since 4.5
-
- This struct represents arguments to virtual_hook() function when
- \a id parameter is QIconEngineV2::AvailableSizesHook.
-
- \sa virtual_hook(), QIconEngineV2::IconEngineHook
- */
-
-/*!
- \variable QIconEngineV2::AvailableSizesArgument::mode
- \brief the requested mode of an image.
-
- \sa QIcon::Mode
-*/
-
-/*!
- \variable QIconEngineV2::AvailableSizesArgument::state
- \brief the requested state of an image.
-
- \sa QIcon::State
-*/
-
-/*!
- \variable QIconEngineV2::AvailableSizesArgument::sizes
-
- \brief image sizes that are available with specified \a mode and
- \a state. This is an output parameter and is filled after call to
- virtual_hook(). Engines that work in terms of a scalable,
- vectorial format normally return an empty list.
-*/
-
-
-/*!
- Returns a key that identifies this icon engine.
- */
-QString QIconEngineV2::key() const
-{
- return QString();
-}
-
-/*!
- Returns a clone of this icon engine.
- */
-QIconEngineV2 *QIconEngineV2::clone() const
-{
- return 0;
-}
-
-/*!
- Reads icon engine contents from the QDataStream \a in. Returns
- true if the contents were read; otherwise returns false.
-
- QIconEngineV2's default implementation always return false.
- */
-bool QIconEngineV2::read(QDataStream &)
-{
- return false;
-}
-
-/*!
- Writes the contents of this engine to the QDataStream \a out.
- Returns true if the contents were written; otherwise returns false.
-
- QIconEngineV2's default implementation always return false.
- */
-bool QIconEngineV2::write(QDataStream &) const
-{
- return false;
-}
-
-/*!
- \since 4.5
-
- Additional method to allow extending QIconEngineV2 without
- adding new virtual methods (and without breaking binary compatibility).
- The actual action and format of \a data depends on \a id argument
- which is in fact a constant from IconEngineHook enum.
-
- \sa IconEngineHook
-*/
-void QIconEngineV2::virtual_hook(int id, void *data)
-{
- switch (id) {
- case QIconEngineV2::AvailableSizesHook: {
- QIconEngineV2::AvailableSizesArgument &arg =
- *reinterpret_cast<QIconEngineV2::AvailableSizesArgument*>(data);
- arg.sizes.clear();
- break;
- }
- default:
- break;
- }
-}
-
-/*!
- \since 4.5
-
- Returns sizes of all images that are contained in the engine for the
- specific \a mode and \a state.
-
- \note This is a helper method and the actual work is done by
- virtual_hook() method, hence this method depends on icon engine support
- and may not work with all icon engines.
- */
-QList<QSize> QIconEngineV2::availableSizes(QIcon::Mode mode, QIcon::State state)
-{
- AvailableSizesArgument arg;
- arg.mode = mode;
- arg.state = state;
- virtual_hook(QIconEngineV2::AvailableSizesHook, reinterpret_cast<void*>(&arg));
- return arg.sizes;
-}
-
-/*!
- \since 4.7
-
- Returns the name used to create the engine, if available.
-
- \note This is a helper method and the actual work is done by
- virtual_hook() method, hence this method depends on icon engine support
- and may not work with all icon engines.
- */
-QString QIconEngineV2::iconName()
-{
- QString name;
- virtual_hook(QIconEngineV2::IconNameHook, reinterpret_cast<void*>(&name));
- return name;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qiconengine.h b/src/gui/kernel/qiconengine.h
deleted file mode 100644
index 12caea8a20..0000000000
--- a/src/gui/kernel/qiconengine.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** 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 QICONENGINE_H
-#define QICONENGINE_H
-
-#include <QtCore/qglobal.h>
-#include <QtCore/qlist.h>
-#include <QtGui/qicon.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QIconEngine
-{
-public:
- virtual ~QIconEngine();
- virtual void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) = 0;
- virtual QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state);
- virtual QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state);
-
- virtual void addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state);
- virtual void addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state);
-
-#if 0
- virtual int frameCount(QIcon::Mode fromMode, QIcon::State fromState, QIcon::Mode toMode, QIcon::State toState);
- virtual void paintFrame(QPainter *painter, const QRect &rect, int frameNumber, QIcon::Mode fromMode, QIcon::State fromState, QIcon::Mode toMode, QIcon::State toState);
-#endif
-};
-
-// ### Qt 5: move the below into QIconEngine
-class Q_GUI_EXPORT QIconEngineV2 : public QIconEngine
-{
-public:
- virtual QString key() const;
- virtual QIconEngineV2 *clone() const;
- virtual bool read(QDataStream &in);
- virtual bool write(QDataStream &out) const;
- virtual void virtual_hook(int id, void *data);
-
-public:
- enum IconEngineHook { AvailableSizesHook = 1, IconNameHook };
-
- struct AvailableSizesArgument
- {
- QIcon::Mode mode;
- QIcon::State state;
- QList<QSize> sizes;
- };
-
- // ### Qt 5: make this function const and virtual.
- QList<QSize> availableSizes(QIcon::Mode mode = QIcon::Normal,
- QIcon::State state = QIcon::Off);
-
- // ### Qt 5: make this function const and virtual.
- QString iconName();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QICONENGINE_H
diff --git a/src/gui/kernel/qiconengineplugin.cpp b/src/gui/kernel/qiconengineplugin.cpp
deleted file mode 100644
index 7c8c3a3c1a..0000000000
--- a/src/gui/kernel/qiconengineplugin.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/****************************************************************************
-**
-** 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 "qiconengineplugin.h"
-#include "qiconengine.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QIconEnginePlugin
- \brief The QIconEnginePlugin class provides an abstract base for custom QIconEngine plugins.
-
- \ingroup plugins
-
- \bold {Use QIconEnginePluginV2 instead.}
-
- The icon engine plugin is a simple plugin interface that makes it easy to
- create custom icon engines that can be loaded dynamically into applications
- through QIcon. QIcon uses the file or resource name's suffix to determine
- what icon engine to use.
-
- Writing a icon engine plugin is achieved by subclassing this base class,
- reimplementing the pure virtual functions keys() and create(), and
- exporting the class with the Q_EXPORT_PLUGIN2() macro.
-
- \sa {How to Create Qt Plugins}
-*/
-
-/*!
- \fn QStringList QIconEnginePlugin::keys() const
-
- Returns a list of icon engine keys that this plugin supports. The keys correspond
- to the suffix of the file or resource name used when the plugin was created.
- Keys are case insensitive.
-
- \sa create()
-*/
-
-/*!
- \fn QIconEngine* QIconEnginePlugin::create(const QString& filename)
-
- Creates and returns a QIconEngine object for the icon with the given
- \a filename.
-
- \sa keys()
-*/
-
-/*!
- Constructs a icon engine plugin with the given \a parent. This is invoked
- automatically by the Q_EXPORT_PLUGIN2() macro.
-*/
-QIconEnginePlugin::QIconEnginePlugin(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*!
- Destroys the icon engine plugin.
-
- You never have to call this explicitly. Qt destroys a plugin
- automatically when it is no longer used.
-*/
-QIconEnginePlugin::~QIconEnginePlugin()
-{
-}
-
-// version 2
-
-/*!
- \class QIconEnginePluginV2
- \brief The QIconEnginePluginV2 class provides an abstract base for custom QIconEngineV2 plugins.
-
- \ingroup plugins
- \since 4.3
-
- Icon engine plugins produces \l{QIconEngine}s for \l{QIcon}s; an
- icon engine is used to render the icon. The keys that identifies
- the engines the plugin can create are suffixes of
- icon filenames; they are returned by keys(). The create() function
- receives the icon filename to return an engine for; it should
- return 0 if it cannot produce an engine for the file.
-
- Writing an icon engine plugin is achieved by inheriting
- QIconEnginePluginV2, reimplementing keys() and create(), and
- adding the Q_EXPORT_PLUGIN2() macro.
-
- You should ensure that you do not duplicate keys. Qt will query
- the plugins for icon engines in the order in which the plugins are
- found during plugin search (see the plugins \l{How to Create Qt
- Plugins}{overview document}).
-
- \sa {How to Create Qt Plugins}
-*/
-
-/*!
- \fn QStringList QIconEnginePluginV2::keys() const
-
- Returns a list of icon engine keys that this plugin supports. The keys correspond
- to the suffix of the file or resource name used when the plugin was created.
- Keys are case insensitive.
-
- \sa create()
-*/
-
-/*!
- \fn QIconEngineV2* QIconEnginePluginV2::create(const QString& filename = QString())
-
- Creates and returns a QIconEngine object for the icon with the given
- \a filename.
-
- \sa keys()
-*/
-
-/*!
- Constructs a icon engine plugin with the given \a parent. This is invoked
- automatically by the Q_EXPORT_PLUGIN2() macro.
-*/
-QIconEnginePluginV2::QIconEnginePluginV2(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*!
- Destroys the icon engine plugin.
-
- You never have to call this explicitly. Qt destroys a plugin
- automatically when it is no longer used.
-*/
-QIconEnginePluginV2::~QIconEnginePluginV2()
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qiconengineplugin.h b/src/gui/kernel/qiconengineplugin.h
deleted file mode 100644
index e892a38f7b..0000000000
--- a/src/gui/kernel/qiconengineplugin.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** 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 QICONENGINEPLUGIN_H
-#define QICONENGINEPLUGIN_H
-
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QIconEngine;
-class QIconEngineV2;
-
-struct Q_GUI_EXPORT QIconEngineFactoryInterface : public QFactoryInterface
-{
- virtual QIconEngine *create(const QString &filename) = 0;
-};
-
-#define QIconEngineFactoryInterface_iid \
- "com.trolltech.Qt.QIconEngineFactoryInterface"
-Q_DECLARE_INTERFACE(QIconEngineFactoryInterface, QIconEngineFactoryInterface_iid)
-
-class Q_GUI_EXPORT QIconEnginePlugin : public QObject, public QIconEngineFactoryInterface
-{
- Q_OBJECT
- Q_INTERFACES(QIconEngineFactoryInterface:QFactoryInterface)
-public:
- QIconEnginePlugin(QObject *parent = 0);
- ~QIconEnginePlugin();
-
- virtual QStringList keys() const = 0;
- virtual QIconEngine *create(const QString &filename) = 0;
-};
-
-// ### Qt 5: remove version 2
-struct Q_GUI_EXPORT QIconEngineFactoryInterfaceV2 : public QFactoryInterface
-{
- virtual QIconEngineV2 *create(const QString &filename = QString()) = 0;
-};
-
-#define QIconEngineFactoryInterfaceV2_iid \
- "com.trolltech.Qt.QIconEngineFactoryInterfaceV2"
-Q_DECLARE_INTERFACE(QIconEngineFactoryInterfaceV2, QIconEngineFactoryInterfaceV2_iid)
-
-class Q_GUI_EXPORT QIconEnginePluginV2 : public QObject, public QIconEngineFactoryInterfaceV2
-{
- Q_OBJECT
- Q_INTERFACES(QIconEngineFactoryInterfaceV2:QFactoryInterface)
-public:
- QIconEnginePluginV2(QObject *parent = 0);
- ~QIconEnginePluginV2();
-
- virtual QStringList keys() const = 0;
- virtual QIconEngineV2 *create(const QString &filename = QString()) = 0;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QICONENGINEPLUGIN_H
diff --git a/src/gui/kernel/qiconloader.cpp b/src/gui/kernel/qiconloader.cpp
deleted file mode 100644
index 19be636e9c..0000000000
--- a/src/gui/kernel/qiconloader.cpp
+++ /dev/null
@@ -1,573 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_ICON
-#include <private/qiconloader_p.h>
-
-#include <private/qguiapplication_p.h>
-#include <private/qicon_p.h>
-#include <private/qguiplatformplugin_p.h>
-
-#include <QtGui/QIconEnginePlugin>
-#include <QtGui/QPixmapCache>
-#include <QtGui/QIconEngine>
-#include <QtGui/QStyleOption>
-#include <QtCore/QList>
-#include <QtCore/QHash>
-#include <QtCore/QDir>
-#include <QtCore/QSettings>
-#include <QtGui/QPainter>
-
-#ifdef Q_WS_MAC
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#ifdef Q_WS_X11
-#include <private/qt_x11_p.h>
-#endif
-
-#include <private/qhexstring_p.h>
-
-QT_BEGIN_NAMESPACE
-
-Q_GLOBAL_STATIC(QIconLoader, iconLoaderInstance)
-
-/* Theme to use in last resort, if the theme does not have the icon, neither the parents */
-static QString fallbackTheme()
-{
-#ifdef Q_WS_X11
- if (X11->desktopEnvironment == DE_GNOME) {
- return QLatin1String("gnome");
- } else if (X11->desktopEnvironment == DE_KDE) {
- return X11->desktopVersion >= 4
- ? QString::fromLatin1("oxygen")
- : QString::fromLatin1("crystalsvg");
- } else {
- return QLatin1String("hicolor");
- }
-#endif
- return QString();
-}
-
-QIconLoader::QIconLoader() :
- m_themeKey(1), m_supportsSvg(false), m_initialized(false)
-{
-}
-
-// We lazily initialize the loader to make static icons
-// work. Though we do not officially support this.
-void QIconLoader::ensureInitialized()
-{
- if (!m_initialized) {
- m_initialized = true;
-
- Q_ASSERT(qApp);
-
- m_systemTheme = qt_guiPlatformPlugin()->systemIconThemeName();
- if (m_systemTheme.isEmpty())
- m_systemTheme = fallbackTheme();
-#ifndef QT_NO_LIBRARY
- QFactoryLoader iconFactoryLoader(QIconEngineFactoryInterfaceV2_iid,
- QLatin1String("/iconengines"),
- Qt::CaseInsensitive);
- if (iconFactoryLoader.keys().contains(QLatin1String("svg")))
- m_supportsSvg = true;
-#endif //QT_NO_LIBRARY
- }
-}
-
-QIconLoader *QIconLoader::instance()
-{
- return iconLoaderInstance();
-}
-
-// Queries the system theme and invalidates existing
-// icons if the theme has changed.
-void QIconLoader::updateSystemTheme()
-{
- // Only change if this is not explicitly set by the user
- if (m_userTheme.isEmpty()) {
- QString theme = qt_guiPlatformPlugin()->systemIconThemeName();
- if (theme.isEmpty())
- theme = fallbackTheme();
- if (theme != m_systemTheme) {
- m_systemTheme = theme;
- invalidateKey();
- }
- }
-}
-
-void QIconLoader::setThemeName(const QString &themeName)
-{
- m_userTheme = themeName;
- invalidateKey();
-}
-
-void QIconLoader::setThemeSearchPath(const QStringList &searchPaths)
-{
- m_iconDirs = searchPaths;
- themeList.clear();
- invalidateKey();
-}
-
-QStringList QIconLoader::themeSearchPaths() const
-{
- if (m_iconDirs.isEmpty()) {
- m_iconDirs = qt_guiPlatformPlugin()->iconThemeSearchPaths();
- // Always add resource directory as search path
- m_iconDirs.append(QLatin1String(":/icons"));
- }
- return m_iconDirs;
-}
-
-QIconTheme::QIconTheme(const QString &themeName)
- : m_valid(false)
-{
- QFile themeIndex;
-
- QList <QIconDirInfo> keyList;
- QStringList iconDirs = QIcon::themeSearchPaths();
- for ( int i = 0 ; i < iconDirs.size() ; ++i) {
- QDir iconDir(iconDirs[i]);
- QString themeDir = iconDir.path() + QLatin1Char('/') + themeName;
- themeIndex.setFileName(themeDir + QLatin1String("/index.theme"));
- if (themeIndex.exists()) {
- m_contentDir = themeDir;
- m_valid = true;
- break;
- }
- }
-#ifndef QT_NO_SETTINGS
- if (themeIndex.exists()) {
- const QSettings indexReader(themeIndex.fileName(), QSettings::IniFormat);
- QStringListIterator keyIterator(indexReader.allKeys());
- while (keyIterator.hasNext()) {
-
- const QString key = keyIterator.next();
- if (key.endsWith(QLatin1String("/Size"))) {
- // Note the QSettings ini-format does not accept
- // slashes in key names, hence we have to cheat
- if (int size = indexReader.value(key).toInt()) {
- QString directoryKey = key.left(key.size() - 5);
- QIconDirInfo dirInfo(directoryKey);
- dirInfo.size = size;
- QString type = indexReader.value(directoryKey +
- QLatin1String("/Type")
- ).toString();
-
- if (type == QLatin1String("Fixed"))
- dirInfo.type = QIconDirInfo::Fixed;
- else if (type == QLatin1String("Scalable"))
- dirInfo.type = QIconDirInfo::Scalable;
- else
- dirInfo.type = QIconDirInfo::Threshold;
-
- dirInfo.threshold = indexReader.value(directoryKey +
- QLatin1String("/Threshold"),
- 2).toInt();
-
- dirInfo.minSize = indexReader.value(directoryKey +
- QLatin1String("/MinSize"),
- size).toInt();
-
- dirInfo.maxSize = indexReader.value(directoryKey +
- QLatin1String("/MaxSize"),
- size).toInt();
- m_keyList.append(dirInfo);
- }
- }
- }
-
- // Parent themes provide fallbacks for missing icons
- m_parents = indexReader.value(
- QLatin1String("Icon Theme/Inherits")).toStringList();
-
- // Ensure a default platform fallback for all themes
- if (m_parents.isEmpty())
- m_parents.append(fallbackTheme());
-
- // Ensure that all themes fall back to hicolor
- if (!m_parents.contains(QLatin1String("hicolor")))
- m_parents.append(QLatin1String("hicolor"));
- }
-#endif //QT_NO_SETTINGS
-}
-
-QThemeIconEntries QIconLoader::findIconHelper(const QString &themeName,
- const QString &iconName,
- QStringList &visited) const
-{
- QThemeIconEntries entries;
- Q_ASSERT(!themeName.isEmpty());
-
- QPixmap pixmap;
-
- // Used to protect against potential recursions
- visited << themeName;
-
- QIconTheme theme = themeList.value(themeName);
- if (!theme.isValid()) {
- theme = QIconTheme(themeName);
- if (!theme.isValid())
- theme = QIconTheme(fallbackTheme());
-
- themeList.insert(themeName, theme);
- }
-
- QString contentDir = theme.contentDir() + QLatin1Char('/');
- QList<QIconDirInfo> subDirs = theme.keyList();
-
- const QString svgext(QLatin1String(".svg"));
- const QString pngext(QLatin1String(".png"));
-
- // Add all relevant files
- for (int i = 0; i < subDirs.size() ; ++i) {
- const QIconDirInfo &dirInfo = subDirs.at(i);
- QString subdir = dirInfo.path;
- QDir currentDir(contentDir + subdir);
- if (currentDir.exists(iconName + pngext)) {
- PixmapEntry *iconEntry = new PixmapEntry;
- iconEntry->dir = dirInfo;
- iconEntry->filename = currentDir.filePath(iconName + pngext);
- // Notice we ensure that pixmap entries always come before
- // scalable to preserve search order afterwards
- entries.prepend(iconEntry);
- } else if (m_supportsSvg &&
- currentDir.exists(iconName + svgext)) {
- ScalableEntry *iconEntry = new ScalableEntry;
- iconEntry->dir = dirInfo;
- iconEntry->filename = currentDir.filePath(iconName + svgext);
- entries.append(iconEntry);
- }
- }
-
- if (entries.isEmpty()) {
- const QStringList parents = theme.parents();
- // Search recursively through inherited themes
- for (int i = 0 ; i < parents.size() ; ++i) {
-
- const QString parentTheme = parents.at(i).trimmed();
-
- if (!visited.contains(parentTheme)) // guard against recursion
- entries = findIconHelper(parentTheme, iconName, visited);
-
- if (!entries.isEmpty()) // success
- break;
- }
- }
- return entries;
-}
-
-QThemeIconEntries QIconLoader::loadIcon(const QString &name) const
-{
- if (!themeName().isEmpty()) {
- QStringList visited;
- return findIconHelper(themeName(), name, visited);
- }
-
- return QThemeIconEntries();
-}
-
-
-// -------- Icon Loader Engine -------- //
-
-
-QIconLoaderEngine::QIconLoaderEngine(const QString& iconName)
- : m_iconName(iconName), m_key(0)
-{
-}
-
-QIconLoaderEngine::~QIconLoaderEngine()
-{
- while (!m_entries.isEmpty())
- delete m_entries.takeLast();
- Q_ASSERT(m_entries.size() == 0);
-}
-
-QIconLoaderEngine::QIconLoaderEngine(const QIconLoaderEngine &other)
- : QIconEngineV2(other),
- m_iconName(other.m_iconName),
- m_key(0)
-{
-}
-
-QIconEngineV2 *QIconLoaderEngine::clone() const
-{
- return new QIconLoaderEngine(*this);
-}
-
-bool QIconLoaderEngine::read(QDataStream &in) {
- in >> m_iconName;
- return true;
-}
-
-bool QIconLoaderEngine::write(QDataStream &out) const
-{
- out << m_iconName;
- return true;
-}
-
-bool QIconLoaderEngine::hasIcon() const
-{
- return !(m_entries.isEmpty());
-}
-
-// Lazily load the icon
-void QIconLoaderEngine::ensureLoaded()
-{
-
- iconLoaderInstance()->ensureInitialized();
-
- if (!(iconLoaderInstance()->themeKey() == m_key)) {
-
- while (!m_entries.isEmpty())
- delete m_entries.takeLast();
-
- Q_ASSERT(m_entries.size() == 0);
- m_entries = iconLoaderInstance()->loadIcon(m_iconName);
- m_key = iconLoaderInstance()->themeKey();
- }
-}
-
-void QIconLoaderEngine::paint(QPainter *painter, const QRect &rect,
- QIcon::Mode mode, QIcon::State state)
-{
- QSize pixmapSize = rect.size();
-#if defined(Q_WS_MAC)
- pixmapSize *= qt_mac_get_scalefactor();
-#endif
- painter->drawPixmap(rect, pixmap(pixmapSize, mode, state));
-}
-
-/*
- * This algorithm is defined by the freedesktop spec:
- * http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html
- */
-static bool directoryMatchesSize(const QIconDirInfo &dir, int iconsize)
-{
- if (dir.type == QIconDirInfo::Fixed) {
- return dir.size == iconsize;
-
- } else if (dir.type == QIconDirInfo::Scalable) {
- return dir.size <= dir.maxSize &&
- iconsize >= dir.minSize;
-
- } else if (dir.type == QIconDirInfo::Threshold) {
- return iconsize >= dir.size - dir.threshold &&
- iconsize <= dir.size + dir.threshold;
- }
-
- Q_ASSERT(1); // Not a valid value
- return false;
-}
-
-/*
- * This algorithm is defined by the freedesktop spec:
- * http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html
- */
-static int directorySizeDistance(const QIconDirInfo &dir, int iconsize)
-{
- if (dir.type == QIconDirInfo::Fixed) {
- return qAbs(dir.size - iconsize);
-
- } else if (dir.type == QIconDirInfo::Scalable) {
- if (iconsize < dir.minSize)
- return dir.minSize - iconsize;
- else if (iconsize > dir.maxSize)
- return iconsize - dir.maxSize;
- else
- return 0;
-
- } else if (dir.type == QIconDirInfo::Threshold) {
- if (iconsize < dir.size - dir.threshold)
- return dir.minSize - iconsize;
- else if (iconsize > dir.size + dir.threshold)
- return iconsize - dir.maxSize;
- else return 0;
- }
-
- Q_ASSERT(1); // Not a valid value
- return INT_MAX;
-}
-
-QIconLoaderEngineEntry *QIconLoaderEngine::entryForSize(const QSize &size)
-{
- int iconsize = qMin(size.width(), size.height());
-
- // Note that m_entries are sorted so that png-files
- // come first
-
- // Search for exact matches first
- for (int i = 0; i < m_entries.count(); ++i) {
- QIconLoaderEngineEntry *entry = m_entries.at(i);
- if (directoryMatchesSize(entry->dir, iconsize)) {
- return entry;
- }
- }
-
- // Find the minimum distance icon
- int minimalSize = INT_MAX;
- QIconLoaderEngineEntry *closestMatch = 0;
- for (int i = 0; i < m_entries.count(); ++i) {
- QIconLoaderEngineEntry *entry = m_entries.at(i);
- int distance = directorySizeDistance(entry->dir, iconsize);
- if (distance < minimalSize) {
- minimalSize = distance;
- closestMatch = entry;
- }
- }
- return closestMatch;
-}
-
-/*
- * Returns the actual icon size. For scalable svg's this is equivalent
- * to the requested size. Otherwise the closest match is returned but
- * we can never return a bigger size than the requested size.
- *
- */
-QSize QIconLoaderEngine::actualSize(const QSize &size, QIcon::Mode mode,
- QIcon::State state)
-{
- ensureLoaded();
-
- QIconLoaderEngineEntry *entry = entryForSize(size);
- if (entry) {
- const QIconDirInfo &dir = entry->dir;
- if (dir.type == QIconDirInfo::Scalable)
- return size;
- else {
- int result = qMin<int>(dir.size, qMin(size.width(), size.height()));
- return QSize(result, result);
- }
- }
- return QIconEngineV2::actualSize(size, mode, state);
-}
-
-QPixmap PixmapEntry::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
-{
- Q_UNUSED(state);
-
- // Ensure that basePixmap is lazily initialized before generating the
- // key, otherwise the cache key is not unique
- if (basePixmap.isNull())
- basePixmap.load(filename);
-
-#if 0 // ### Qt5
- int actualSize = qMin(size.width(), size.height());
- QString key = QLatin1Literal("$qt_theme_")
- % HexString<qint64>(basePixmap.cacheKey())
- % HexString<int>(mode)
- % HexString<qint64>(qApp->palette().cacheKey())
- % HexString<int>(actualSize);
-
- QPixmap cachedPixmap;
- if (QPixmapCache::find(key, &cachedPixmap)) {
- return cachedPixmap;
- } else {
- QStyleOption opt(0);
- opt.palette = qApp->palette();
- cachedPixmap = qApp->style()->generatedIconPixmap(mode, basePixmap, &opt);
- QPixmapCache::insert(key, cachedPixmap);
- }
- return cachedPixmap;
-#else
- return basePixmap;
-#endif
-}
-
-QPixmap ScalableEntry::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
-{
- if (svgIcon.isNull())
- svgIcon = QIcon(filename);
-
- // Simply reuse svg icon engine
- return svgIcon.pixmap(size, mode, state);
-}
-
-QPixmap QIconLoaderEngine::pixmap(const QSize &size, QIcon::Mode mode,
- QIcon::State state)
-{
- ensureLoaded();
-
- QIconLoaderEngineEntry *entry = entryForSize(size);
- if (entry)
- return entry->pixmap(size, mode, state);
-
- return QPixmap();
-}
-
-QString QIconLoaderEngine::key() const
-{
- return QLatin1String("QIconLoaderEngine");
-}
-
-void QIconLoaderEngine::virtual_hook(int id, void *data)
-{
- ensureLoaded();
-
- switch (id) {
- case QIconEngineV2::AvailableSizesHook:
- {
- QIconEngineV2::AvailableSizesArgument &arg
- = *reinterpret_cast<QIconEngineV2::AvailableSizesArgument*>(data);
- const QList<QIconDirInfo> directoryKey = iconLoaderInstance()->theme().keyList();
- arg.sizes.clear();
-
- // Gets all sizes from the DirectoryInfo entries
- for (int i = 0 ; i < m_entries.size() ; ++i) {
- int size = m_entries.at(i)->dir.size;
- arg.sizes.append(QSize(size, size));
- }
- }
- break;
- case QIconEngineV2::IconNameHook:
- {
- QString &name = *reinterpret_cast<QString*>(data);
- name = m_iconName;
- }
- break;
- default:
- QIconEngineV2::virtual_hook(id, data);
- }
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_ICON
diff --git a/src/gui/kernel/qiconloader_p.h b/src/gui/kernel/qiconloader_p.h
deleted file mode 100644
index 00a3976b40..0000000000
--- a/src/gui/kernel/qiconloader_p.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/****************************************************************************
-**
-** 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 QDESKTOPICON_P_H
-#define QDESKTOPICON_P_H
-
-#ifndef QT_NO_ICON
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/QIcon>
-#include <QtGui/QIconEngine>
-#include <QtGui/QPixmapCache>
-#include <private/qicon_p.h>
-#include <private/qfactoryloader_p.h>
-#include <QtCore/QHash>
-
-QT_BEGIN_NAMESPACE
-
-class QIconLoader;
-
-struct QIconDirInfo
-{
- enum Type { Fixed, Scalable, Threshold };
- QIconDirInfo(const QString &_path = QString()) :
- path(_path),
- size(0),
- maxSize(0),
- minSize(0),
- threshold(0),
- type(Threshold) {}
- QString path;
- short size;
- short maxSize;
- short minSize;
- short threshold;
- Type type : 4;
-};
-
-class QIconLoaderEngineEntry
- {
-public:
- virtual ~QIconLoaderEngineEntry() {}
- virtual QPixmap pixmap(const QSize &size,
- QIcon::Mode mode,
- QIcon::State state) = 0;
- QString filename;
- QIconDirInfo dir;
- static int count;
-};
-
-struct ScalableEntry : public QIconLoaderEngineEntry
-{
- QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state);
- QIcon svgIcon;
-};
-
-struct PixmapEntry : public QIconLoaderEngineEntry
-{
- QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state);
- QPixmap basePixmap;
-};
-
-typedef QList<QIconLoaderEngineEntry*> QThemeIconEntries;
-
-class QIconLoaderEngine : public QIconEngineV2
-{
-public:
- QIconLoaderEngine(const QString& iconName = QString());
- ~QIconLoaderEngine();
-
- void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state);
- QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state);
- QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state);
- QIconEngineV2 *clone() const;
- bool read(QDataStream &in);
- bool write(QDataStream &out) const;
-
-private:
- QString key() const;
- bool hasIcon() const;
- void ensureLoaded();
- void virtual_hook(int id, void *data);
- QIconLoaderEngineEntry *entryForSize(const QSize &size);
- QIconLoaderEngine(const QIconLoaderEngine &other);
- QThemeIconEntries m_entries;
- QString m_iconName;
- uint m_key;
-
- friend class QIconLoader;
-};
-
-class QIconTheme
-{
-public:
- QIconTheme(const QString &name);
- QIconTheme() : m_valid(false) {}
- QStringList parents() { return m_parents; }
- QList <QIconDirInfo> keyList() { return m_keyList; }
- QString contentDir() { return m_contentDir; }
- bool isValid() { return m_valid; }
-
-private:
- QString m_contentDir;
- QList <QIconDirInfo> m_keyList;
- QStringList m_parents;
- bool m_valid;
-};
-
-class QIconLoader : public QObject
-{
-public:
- QIconLoader();
- QThemeIconEntries loadIcon(const QString &iconName) const;
- uint themeKey() const { return m_themeKey; }
-
- QString themeName() const { return m_userTheme.isEmpty() ? m_systemTheme : m_userTheme; }
- void setThemeName(const QString &themeName);
- QIconTheme theme() { return themeList.value(themeName()); }
- void setThemeSearchPath(const QStringList &searchPaths);
- QStringList themeSearchPaths() const;
- QIconDirInfo dirInfo(int dirindex);
- static QIconLoader *instance();
- void updateSystemTheme();
- void invalidateKey() { m_themeKey++; }
- void ensureInitialized();
-
-private:
- QThemeIconEntries findIconHelper(const QString &themeName,
- const QString &iconName,
- QStringList &visited) const;
- uint m_themeKey;
- bool m_supportsSvg;
- bool m_initialized;
-
- mutable QString m_userTheme;
- mutable QString m_systemTheme;
- mutable QStringList m_iconDirs;
- mutable QHash <QString, QIconTheme> themeList;
-};
-
-QT_END_NAMESPACE
-
-#endif // QDESKTOPICON_P_H
-
-#endif //QT_NO_ICON
diff --git a/src/gui/kernel/qlayout.cpp b/src/gui/kernel/qlayout.cpp
deleted file mode 100644
index e014ec855f..0000000000
--- a/src/gui/kernel/qlayout.cpp
+++ /dev/null
@@ -1,1632 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlayout.h"
-
-#include "qapplication.h"
-#include "qlayoutengine_p.h"
-#include "qmenubar.h"
-#include "qtoolbar.h"
-#include "qsizegrip.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qvariant.h"
-#include "qwidget_p.h"
-#include "qlayout_p.h"
-#include "qformlayout.h"
-
-QT_BEGIN_NAMESPACE
-
-static int menuBarHeightForWidth(QWidget *menubar, int w)
-{
- if (menubar && !menubar->isHidden() && !menubar->isWindow()) {
- int result = menubar->heightForWidth(qMax(w, menubar->minimumWidth()));
- if (result != -1)
- return result;
- result = menubar->sizeHint()
- .expandedTo(menubar->minimumSize())
- .expandedTo(menubar->minimumSizeHint())
- .boundedTo(menubar->maximumSize()).height();
- if (result != -1)
- return result;
- }
- return 0;
-}
-
-/*!
- \class QLayout
- \brief The QLayout class is the base class of geometry managers.
-
- \ingroup geomanagement
-
- This is an abstract base class inherited by the concrete classes
- QBoxLayout, QGridLayout, QFormLayout, and QStackedLayout.
-
- For users of QLayout subclasses or of QMainWindow there is seldom
- any need to use the basic functions provided by QLayout, such as
- setSizeConstraint() or setMenuBar(). See \l{Layout Management}
- for more information.
-
- To make your own layout manager, implement the functions
- addItem(), sizeHint(), setGeometry(), itemAt() and takeAt(). You
- should also implement minimumSize() to ensure your layout isn't
- resized to zero size if there is too little space. To support
- children whose heights depend on their widths, implement
- hasHeightForWidth() and heightForWidth(). See the
- \l{layouts/borderlayout}{Border Layout} and
- \l{layouts/flowlayout}{Flow Layout} examples for
- more information about implementing custom layout managers.
-
- Geometry management stops when the layout manager is deleted.
-
- \sa QLayoutItem, {Layout Management}, {Basic Layouts Example},
- {Border Layout Example}, {Flow Layout Example}
-*/
-
-
-/*!
- Constructs a new top-level QLayout, with parent \a parent.
- \a parent may not be 0.
-
- There can be only one top-level layout for a widget. It is
- returned by QWidget::layout().
-*/
-QLayout::QLayout(QWidget *parent)
- : QObject(*new QLayoutPrivate, parent)
-{
- if (!parent)
- return;
- parent->setLayout(this);
-}
-
-/*!
- Constructs a new child QLayout.
-
- This layout has to be inserted into another layout before geometry
- management will work.
-*/
-QLayout::QLayout()
- : QObject(*new QLayoutPrivate, 0)
-{
-}
-
-
-/*! \internal
- */
-QLayout::QLayout(QLayoutPrivate &dd, QLayout *lay, QWidget *w)
- : QObject(dd, lay ? static_cast<QObject*>(lay) : static_cast<QObject*>(w))
-{
- Q_D(QLayout);
- if (lay) {
- lay->addItem(this);
- } else if (w) {
- if (w->layout()) {
- qWarning("QLayout: Attempting to add QLayout \"%s\" to %s \"%s\", which"
- " already has a layout",
- qPrintable(QObject::objectName()), w->metaObject()->className(),
- w->objectName().toLocal8Bit().data());
- setParent(0);
- } else {
- d->topLevel = true;
- w->d_func()->layout = this;
- QT_TRY {
- invalidate();
- } QT_CATCH(...) {
- w->d_func()->layout = 0;
- QT_RETHROW;
- }
- }
- }
-}
-
-QLayoutPrivate::QLayoutPrivate()
- : QObjectPrivate(), insideSpacing(-1), userLeftMargin(-1), userTopMargin(-1), userRightMargin(-1),
- userBottomMargin(-1), topLevel(false), enabled(true), activated(true), autoNewChild(false),
- constraint(QLayout::SetDefaultConstraint), menubar(0)
-{
-}
-
-void QLayoutPrivate::getMargin(int *result, int userMargin, QStyle::PixelMetric pm) const
-{
- if (!result)
- return;
-
- Q_Q(const QLayout);
- if (userMargin >= 0) {
- *result = userMargin;
- } else if (!topLevel) {
- *result = 0;
- } else if (QWidget *pw = q->parentWidget()) {
- *result = pw->style()->pixelMetric(pm, 0, pw);
- } else {
- *result = 0;
- }
-}
-
-// Static item factory functions that allow for hooking things in Designer
-
-QLayoutPrivate::QWidgetItemFactoryMethod QLayoutPrivate::widgetItemFactoryMethod = 0;
-QLayoutPrivate::QSpacerItemFactoryMethod QLayoutPrivate::spacerItemFactoryMethod = 0;
-
-QWidgetItem *QLayoutPrivate::createWidgetItem(const QLayout *layout, QWidget *widget)
-{
- if (widgetItemFactoryMethod)
- if (QWidgetItem *wi = (*widgetItemFactoryMethod)(layout, widget))
- return wi;
- return new QWidgetItemV2(widget);
-}
-
-QSpacerItem *QLayoutPrivate::createSpacerItem(const QLayout *layout, int w, int h, QSizePolicy::Policy hPolicy, QSizePolicy::Policy vPolicy)
-{
- if (spacerItemFactoryMethod)
- if (QSpacerItem *si = (*spacerItemFactoryMethod)(layout, w, h, hPolicy, vPolicy))
- return si;
- return new QSpacerItem(w, h, hPolicy, vPolicy);
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a new top-level QLayout called \a name, with parent
- widget \a parent. \a parent may not be 0.
-
- The \a margin is the number of pixels between the edge of the
- widget and the managed children. The \a spacing sets the value of
- spacing(), which gives the spacing between the managed widgets. If
- \a spacing is -1 (the default), spacing is set to the value of \a
- margin.
-
- There can be only one top-level layout for a widget. It is
- returned by QWidget::layout()
-
- \sa QWidget::setLayout()
-*/
-QLayout::QLayout(QWidget *parent, int margin, int spacing, const char *name)
- : QObject(*new QLayoutPrivate,parent)
-{
- Q_D(QLayout);
- setObjectName(QString::fromAscii(name));
- setMargin(margin);
- if (spacing < 0)
- d->insideSpacing = margin;
- else
- d->insideSpacing = spacing;
- if (parent) {
- if (parent->layout()) {
- qWarning("QLayout \"%s\" added to %s \"%s\", which already has a layout",
- QObject::objectName().toLocal8Bit().data(), parent->metaObject()->className(),
- parent->objectName().toLocal8Bit().data());
- parent->layout()->setParent(0);
- } else {
- d->topLevel = true;
- parent->d_func()->layout = this;
- QT_TRY {
- invalidate();
- } QT_CATCH(...) {
- parent->d_func()->layout = 0;
- QT_RETHROW;
- }
- }
- }
-}
-
-/*!
- Constructs a new child QLayout called \a name, and places it
- inside \a parentLayout by using the default placement defined by
- addItem().
-
- If \a spacing is -1, this QLayout inherits \a parentLayout's
- spacing(), otherwise the value of \a spacing is used.
-*/
-QLayout::QLayout(QLayout *parentLayout, int spacing, const char *name)
- : QObject(*new QLayoutPrivate,parentLayout)
-
-{
- Q_D(QLayout);
- setObjectName(QString::fromAscii(name));
- d->insideSpacing = spacing;
- parentLayout->addItem(this);
-}
-
-/*!
- Constructs a new child QLayout called \a name. If \a spacing is
- -1, this QLayout inherits its parent's spacing(); otherwise the
- value of \a spacing is used.
-
- This layout has to be inserted into another layout before geometry
- management will work.
-*/
-QLayout::QLayout(int spacing, const char *name)
- : QObject(*new QLayoutPrivate, 0)
-{
- Q_D(QLayout);
- setObjectName(QString::fromAscii(name));
- d->insideSpacing = spacing;
-}
-
-/*!
- Automatically adding widgets is deprecated. Use addWidget() or
- addLayout() instead.
-*/
-void QLayout::setAutoAdd(bool a) { Q_D(QLayout); d->autoNewChild = a; }
-
-/*!
- Automatically adding widgets is deprecated. Use addWidget() or
- addLayout() instead.
-*/
-bool QLayout::autoAdd() const { Q_D(const QLayout); return d->autoNewChild; }
-#endif
-
-
-/*!
- \fn void QLayout::addItem(QLayoutItem *item)
-
- Implemented in subclasses to add an \a item. How it is added is
- specific to each subclass.
-
- This function is not usually called in application code. To add a widget
- to a layout, use the addWidget() function; to add a child layout, use the
- addLayout() function provided by the relevant QLayout subclass.
-
- \bold{Note:} The ownership of \a item is transferred to the layout, and it's
- the layout's responsibility to delete it.
-
- \sa addWidget(), QBoxLayout::addLayout(), QGridLayout::addLayout()
-*/
-
-/*!
- Adds widget \a w to this layout in a manner specific to the
- layout. This function uses addItem().
-*/
-void QLayout::addWidget(QWidget *w)
-{
- addChildWidget(w);
- addItem(QLayoutPrivate::createWidgetItem(this, w));
-}
-
-
-
-/*!
- Sets the alignment for widget \a w to \a alignment and returns
- true if \a w is found in this layout (not including child
- layouts); otherwise returns false.
-*/
-bool QLayout::setAlignment(QWidget *w, Qt::Alignment alignment)
-{
- int i = 0;
- QLayoutItem *item = itemAt(i);
- while (item) {
- if (item->widget() == w) {
- item->setAlignment(alignment);
- invalidate();
- return true;
- }
- ++i;
- item = itemAt(i);
- }
- return false;
-}
-
-/*!
- \overload
-
- Sets the alignment for the layout \a l to \a alignment and
- returns true if \a l is found in this layout (not including child
- layouts); otherwise returns false.
-*/
-bool QLayout::setAlignment(QLayout *l, Qt::Alignment alignment)
-{
- int i = 0;
- QLayoutItem *item = itemAt(i);
- while (item) {
- if (item->layout() == l) {
- item->setAlignment(alignment);
- invalidate();
- return true;
- }
- ++i;
- item = itemAt(i);
- }
- return false;
-}
-
-/*!
- \fn void QLayout::setAlignment(Qt::Alignment alignment)
-
- Sets the alignment of this item to \a alignment.
-
- \sa QLayoutItem::setAlignment()
-*/
-
-/*!
- \fn bool QLayout::isTopLevel() const
-
- Returns true if this layout is a top-level layout, i.e. not a
- child of another layout; otherwise returns false.
-*/
-
-/*!
- \property QLayout::margin
- \brief the width of the outside border of the layout
- \obsolete
-
- Use setContentsMargins() and getContentsMargins() instead.
-
- \sa contentsRect(), spacing
-*/
-
-/*!
- \obsolete
-*/
-int QLayout::margin() const
-{
- int left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- if (left == top && top == right && right == bottom) {
- return left;
- } else {
- return -1;
- }
-}
-
-/*!
- \property QLayout::spacing
- \brief the spacing between widgets inside the layout
-
- If no value is explicitly set, the layout's spacing is inherited
- from the parent layout, or from the style settings for the parent
- widget.
-
- For QGridLayout and QFormLayout, it is possible to set different horizontal and
- vertical spacings using \l{QGridLayout::}{setHorizontalSpacing()}
- and \l{QGridLayout::}{setVerticalSpacing()}. In that case,
- spacing() returns -1.
-
- \sa contentsRect(), getContentsMargins(), QStyle::layoutSpacing(),
- QStyle::pixelMetric()
-*/
-
-int QLayout::spacing() const
-{
- if (const QBoxLayout* boxlayout = qobject_cast<const QBoxLayout*>(this)) {
- return boxlayout->spacing();
- } else if (const QGridLayout* gridlayout = qobject_cast<const QGridLayout*>(this)) {
- return gridlayout->spacing();
- } else if (const QFormLayout* formlayout = qobject_cast<const QFormLayout*>(this)) {
- return formlayout->spacing();
- } else {
- Q_D(const QLayout);
- if (d->insideSpacing >=0) {
- return d->insideSpacing;
- } else {
- // arbitrarily prefer horizontal spacing to vertical spacing
- return qSmartSpacing(this, QStyle::PM_LayoutHorizontalSpacing);
- }
- }
-}
-
-/*!
- \obsolete
-*/
-void QLayout::setMargin(int margin)
-{
- setContentsMargins(margin, margin, margin, margin);
-}
-
-void QLayout::setSpacing(int spacing)
-{
- if (QBoxLayout* boxlayout = qobject_cast<QBoxLayout*>(this)) {
- boxlayout->setSpacing(spacing);
- } else if (QGridLayout* gridlayout = qobject_cast<QGridLayout*>(this)) {
- gridlayout->setSpacing(spacing);
- } else if (QFormLayout* formlayout = qobject_cast<QFormLayout*>(this)) {
- formlayout->setSpacing(spacing);
- } else {
- Q_D(QLayout);
- d->insideSpacing = spacing;
- invalidate();
- }
-}
-
-/*!
- \since 4.3
-
- Sets the \a left, \a top, \a right, and \a bottom margins to use
- around the layout.
-
- By default, QLayout uses the values provided by the style. On
- most platforms, the margin is 11 pixels in all directions.
-
- \sa getContentsMargins(), QStyle::pixelMetric(),
- {QStyle::}{PM_LayoutLeftMargin},
- {QStyle::}{PM_LayoutTopMargin},
- {QStyle::}{PM_LayoutRightMargin},
- {QStyle::}{PM_LayoutBottomMargin}
-*/
-void QLayout::setContentsMargins(int left, int top, int right, int bottom)
-{
- Q_D(QLayout);
-
- if (d->userLeftMargin == left && d->userTopMargin == top &&
- d->userRightMargin == right && d->userBottomMargin == bottom)
- return;
-
- d->userLeftMargin = left;
- d->userTopMargin = top;
- d->userRightMargin = right;
- d->userBottomMargin = bottom;
- invalidate();
-}
-
-/*!
- \since 4.6
-
- Sets the \a margins to use around the layout.
-
- By default, QLayout uses the values provided by the style. On
- most platforms, the margin is 11 pixels in all directions.
-
- \sa contentsMargins()
-*/
-void QLayout::setContentsMargins(const QMargins &margins)
-{
- setContentsMargins(margins.left(), margins.top(), margins.right(), margins.bottom());
-}
-
-/*!
- \since 4.3
-
- Extracts the left, top, right, and bottom margins used around the
- layout, and assigns them to *\a left, *\a top, *\a right, and *\a
- bottom (unless they are null pointers).
-
- By default, QLayout uses the values provided by the style. On
- most platforms, the margin is 11 pixels in all directions.
-
- \sa setContentsMargins(), QStyle::pixelMetric(),
- {QStyle::}{PM_LayoutLeftMargin},
- {QStyle::}{PM_LayoutTopMargin},
- {QStyle::}{PM_LayoutRightMargin},
- {QStyle::}{PM_LayoutBottomMargin}
-*/
-void QLayout::getContentsMargins(int *left, int *top, int *right, int *bottom) const
-{
- Q_D(const QLayout);
- d->getMargin(left, d->userLeftMargin, QStyle::PM_LayoutLeftMargin);
- d->getMargin(top, d->userTopMargin, QStyle::PM_LayoutTopMargin);
- d->getMargin(right, d->userRightMargin, QStyle::PM_LayoutRightMargin);
- d->getMargin(bottom, d->userBottomMargin, QStyle::PM_LayoutBottomMargin);
-}
-
-/*!
- \since 4.6
-
- Returns the margins used around the layout.
-
- By default, QLayout uses the values provided by the style. On
- most platforms, the margin is 11 pixels in all directions.
-
- \sa setContentsMargins()
-*/
-QMargins QLayout::contentsMargins() const
-{
- int left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- return QMargins(left, top, right, bottom);
-}
-
-/*!
- \since 4.3
-
- Returns the layout's geometry() rectangle, but taking into account the
- contents margins.
-
- \sa setContentsMargins(), getContentsMargins()
-*/
-QRect QLayout::contentsRect() const
-{
- Q_D(const QLayout);
- int left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- return d->rect.adjusted(+left, +top, -right, -bottom);
-}
-
-#ifdef QT3_SUPPORT
-bool QLayout::isTopLevel() const
-{
- Q_D(const QLayout);
- return d->topLevel;
-}
-#endif
-
-/*!
- Returns the parent widget of this layout, or 0 if this layout is
- not installed on any widget.
-
- If the layout is a sub-layout, this function returns the parent
- widget of the parent layout.
-
- \sa parent()
-*/
-QWidget *QLayout::parentWidget() const
-{
- Q_D(const QLayout);
- if (!d->topLevel) {
- if (parent()) {
- QLayout *parentLayout = qobject_cast<QLayout*>(parent());
- if (!parentLayout) {
- qWarning("QLayout::parentWidget: A layout can only have another layout as a parent.");
- return 0;
- }
- return parentLayout->parentWidget();
- } else {
- return 0;
- }
- } else {
- Q_ASSERT(parent() && parent()->isWidgetType());
- return static_cast<QWidget *>(parent());
- }
-}
-
-/*!
- \reimp
-*/
-bool QLayout::isEmpty() const
-{
- int i = 0;
- QLayoutItem *item = itemAt(i);
- while (item) {
- if (!item->isEmpty())
- return false;
- ++i;
- item = itemAt(i);
- }
- return true;
-}
-
-/*!
- \reimp
-*/
-void QLayout::setGeometry(const QRect &r)
-{
- Q_D(QLayout);
- d->rect = r;
-}
-
-/*!
- \reimp
-*/
-QRect QLayout::geometry() const
-{
- Q_D(const QLayout);
- return d->rect;
-}
-
-/*!
- \reimp
-*/
-void QLayout::invalidate()
-{
- Q_D(QLayout);
- d->rect = QRect();
- update();
-}
-
-static bool removeWidgetRecursively(QLayoutItem *li, QWidget *w)
-{
- QLayout *lay = li->layout();
- if (!lay)
- return false;
- int i = 0;
- QLayoutItem *child;
- while ((child = lay->itemAt(i))) {
- if (child->widget() == w) {
- delete lay->takeAt(i);
- lay->invalidate();
- return true;
- } else if (removeWidgetRecursively(child, w)) {
- return true;
- } else {
- ++i;
- }
- }
- return false;
-}
-
-
-void QLayoutPrivate::doResize(const QSize &r)
-{
- Q_Q(QLayout);
- int mbh = menuBarHeightForWidth(menubar, r.width());
- QWidget *mw = q->parentWidget();
- QRect rect = mw->testAttribute(Qt::WA_LayoutOnEntireRect) ? mw->rect() : mw->contentsRect();
- rect.setTop(rect.top() + mbh);
- q->setGeometry(rect);
-#ifndef QT_NO_MENUBAR
- if (menubar)
- menubar->setGeometry(0,0,r.width(), mbh);
-#endif
-}
-
-
-/*!
- \internal
- Performs child widget layout when the parent widget is
- resized. Also handles removal of widgets. \a e is the
- event
-*/
-void QLayout::widgetEvent(QEvent *e)
-{
- Q_D(QLayout);
- if (!d->enabled)
- return;
-
- switch (e->type()) {
- case QEvent::Resize:
- if (d->activated) {
- QResizeEvent *r = (QResizeEvent *)e;
- d->doResize(r->size());
- } else {
- activate();
- }
- break;
- case QEvent::ChildRemoved:
- {
- QChildEvent *c = (QChildEvent *)e;
- if (c->child()->isWidgetType()) {
- QWidget *w = (QWidget *)c->child();
-#ifndef QT_NO_MENUBAR
- if (w == d->menubar)
- d->menubar = 0;
-#endif
- removeWidgetRecursively(this, w);
- }
- }
- break;
-#ifdef QT3_SUPPORT
- case QEvent::ChildInserted:
- if (d->topLevel && d->autoNewChild) {
- QChildEvent *c = (QChildEvent *)e;
- if (c->child()->isWidgetType()) {
- QWidget *w = (QWidget *)c->child();
- if (!w->isWindow()) {
-#if !defined(QT_NO_MENUBAR) && !defined(QT_NO_TOOLBAR)
- if (qobject_cast<QMenuBar*>(w) && !qobject_cast<QToolBar*>(w->parentWidget())) {
- d->menubar = (QMenuBar *)w;
- invalidate();
- } else
-#endif
-#ifndef QT_NO_SIZEGRIP
- if (qobject_cast<QSizeGrip*>(w) ) {
- //SizeGrip is handled by the dialog itself.
- } else
-#endif
- addItem(QLayoutPrivate::createWidgetItem(this, w));
- }
- }
- }
- break;
- case QEvent::LayoutHint:
- d->activated = false;
- // fall through
-#endif
- case QEvent::LayoutRequest:
- if (static_cast<QWidget *>(parent())->isVisible())
- activate();
- break;
- default:
- break;
- }
-}
-
-/*!
- \reimp
-*/
-void QLayout::childEvent(QChildEvent *e)
-{
- Q_D(QLayout);
- if (!d->enabled)
- return;
-
- if (e->type() == QEvent::ChildRemoved) {
- QChildEvent *c = (QChildEvent*)e;
- int i = 0;
-
- QLayoutItem *item;
- while ((item = itemAt(i))) {
- if (item == static_cast<QLayout*>(c->child())) {
- takeAt(i);
- invalidate();
- break;
- } else {
- ++i;
- }
- }
- }
-}
-
-/*!
- \internal
- Also takes contentsMargins and menu bar into account.
-*/
-int QLayout::totalHeightForWidth(int w) const
-{
- Q_D(const QLayout);
- int side=0, top=0;
- if (d->topLevel) {
- QWidget *parent = parentWidget();
- parent->ensurePolished();
- QWidgetPrivate *wd = parent->d_func();
- side += wd->leftmargin + wd->rightmargin;
- top += wd->topmargin + wd->bottommargin;
- }
- int h = heightForWidth(w - side) + top;
-#ifndef QT_NO_MENUBAR
- h += menuBarHeightForWidth(d->menubar, w);
-#endif
- return h;
-}
-
-/*!
- \internal
- Also takes contentsMargins and menu bar into account.
-*/
-QSize QLayout::totalMinimumSize() const
-{
- Q_D(const QLayout);
- int side=0, top=0;
- if (d->topLevel) {
- QWidget *pw = parentWidget();
- pw->ensurePolished();
- QWidgetPrivate *wd = pw->d_func();
- side += wd->leftmargin + wd->rightmargin;
- top += wd->topmargin + wd->bottommargin;
- }
-
- QSize s = minimumSize();
-#ifndef QT_NO_MENUBAR
- top += menuBarHeightForWidth(d->menubar, s.width() + side);
-#endif
- return s + QSize(side, top);
-}
-
-/*!
- \internal
- Also takes contentsMargins and menu bar into account.
-*/
-QSize QLayout::totalSizeHint() const
-{
- Q_D(const QLayout);
- int side=0, top=0;
- if (d->topLevel) {
- QWidget *pw = parentWidget();
- pw->ensurePolished();
- QWidgetPrivate *wd = pw->d_func();
- side += wd->leftmargin + wd->rightmargin;
- top += wd->topmargin + wd->bottommargin;
- }
-
- QSize s = sizeHint();
- if (hasHeightForWidth())
- s.setHeight(heightForWidth(s.width() + side));
-#ifndef QT_NO_MENUBAR
- top += menuBarHeightForWidth(d->menubar, s.width());
-#endif
- return s + QSize(side, top);
-}
-
-/*!
- \internal
- Also takes contentsMargins and menu bar into account.
-*/
-QSize QLayout::totalMaximumSize() const
-{
- Q_D(const QLayout);
- int side=0, top=0;
- if (d->topLevel) {
- QWidget *pw = parentWidget();
- pw->ensurePolished();
- QWidgetPrivate *wd = pw->d_func();
- side += wd->leftmargin + wd->rightmargin;
- top += wd->topmargin + wd->bottommargin;
- }
-
- QSize s = maximumSize();
-#ifndef QT_NO_MENUBAR
- top += menuBarHeightForWidth(d->menubar, s.width());
-#endif
-
- if (d->topLevel)
- s = QSize(qMin(s.width() + side, QLAYOUTSIZE_MAX),
- qMin(s.height() + top, QLAYOUTSIZE_MAX));
- return s;
-}
-
-/*!
- \internal
- Destroys the layout, deleting all child layouts.
- Geometry management stops when a top-level layout is deleted.
-
- The layout classes will probably be fatally confused if you delete
- a sublayout.
-*/
-QLayout::~QLayout()
-{
- Q_D(QLayout);
- /*
- This function may be called during the QObject destructor,
- when the parent no longer is a QWidget.
- */
- if (d->topLevel && parent() && parent()->isWidgetType() &&
- ((QWidget*)parent())->layout() == this)
- ((QWidget*)parent())->d_func()->layout = 0;
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Removes and deletes all items in this layout.
-*/
-void QLayout::deleteAllItems()
-{
- QLayoutItem *l;
- while ((l = takeAt(0)))
- delete l;
-}
-#endif
-
-/*!
- This function is called from \c addLayout() or \c insertLayout() functions in
- subclasses to add layout \a l as a sub-layout.
-
- The only scenario in which you need to call it directly is if you
- implement a custom layout that supports nested layouts.
-
- \sa QBoxLayout::addLayout(), QBoxLayout::insertLayout(), QGridLayout::addLayout()
-*/
-void QLayout::addChildLayout(QLayout *l)
-{
- if (l->parent()) {
- qWarning("QLayout::addChildLayout: layout \"%s\" already has a parent",
- l->objectName().toLocal8Bit().data());
- return;
- }
- l->setParent(this);
-
- if (QWidget *mw = parentWidget()) {
- l->d_func()->reparentChildWidgets(mw);
- }
-
-}
-
-#ifdef QT_DEBUG
-static bool layoutDebug()
-{
- static int checked_env = -1;
- if(checked_env == -1)
- checked_env = !!qgetenv("QT_LAYOUT_DEBUG").toInt();
-
- return checked_env;
-}
-#endif
-
-void QLayoutPrivate::reparentChildWidgets(QWidget *mw)
-{
- Q_Q(QLayout);
- int n = q->count();
-
-#ifndef QT_NO_MENUBAR
- if (menubar && menubar->parentWidget() != mw) {
- menubar->setParent(mw);
- }
-#endif
- bool mwVisible = mw && mw->isVisible();
- for (int i = 0; i < n; ++i) {
- QLayoutItem *item = q->itemAt(i);
- if (QWidget *w = item->widget()) {
- QWidget *pw = w->parentWidget();
-#ifdef QT_DEBUG
- if (pw && pw != mw && layoutDebug()) {
- qWarning("QLayout::addChildLayout: widget %s \"%s\" in wrong parent; moved to correct parent",
- w->metaObject()->className(), w->objectName().toLocal8Bit().data());
- }
-#endif
- bool needShow = mwVisible && !(w->isHidden() && w->testAttribute(Qt::WA_WState_ExplicitShowHide));
- if (pw != mw)
- w->setParent(mw);
- if (needShow)
- QMetaObject::invokeMethod(w, "_q_showIfNotHidden", Qt::QueuedConnection); //show later
- } else if (QLayout *l = item->layout()) {
- l->d_func()->reparentChildWidgets(mw);
- }
- }
-}
-
-/*!
- This function is called from \c addWidget() functions in
- subclasses to add \a w as a managed widget of a layout.
-
- If \a w is already managed by a layout, this function will give a warning
- and remove \a w from that layout. This function must therefore be
- called before adding \a w to the layout's data structure.
-*/
-void QLayout::addChildWidget(QWidget *w)
-{
- QWidget *mw = parentWidget();
- QWidget *pw = w->parentWidget();
-
- //Qt::WA_LaidOut is never reset. It only means that the widget at some point has
- //been in a layout.
- if (pw && w->testAttribute(Qt::WA_LaidOut)) {
- QLayout *l = pw->layout();
- if (l && removeWidgetRecursively(l, w)) {
-#ifdef QT_DEBUG
- if (layoutDebug())
- qWarning("QLayout::addChildWidget: %s \"%s\" is already in a layout; moved to new layout",
- w->metaObject()->className(), w->objectName().toLocal8Bit().data());
-#endif
- }
- }
- if (pw && mw && pw != mw) {
-#ifdef QT_DEBUG
- if (layoutDebug())
- qWarning("QLayout::addChildWidget: %s \"%s\" in wrong parent; moved to correct parent",
- w->metaObject()->className(), w->objectName().toLocal8Bit().data());
-#endif
- pw = 0;
- }
- bool needShow = mw && mw->isVisible() && !(w->isHidden() && w->testAttribute(Qt::WA_WState_ExplicitShowHide));
- if (!pw && mw)
- w->setParent(mw);
- w->setAttribute(Qt::WA_LaidOut);
- if (needShow)
- QMetaObject::invokeMethod(w, "_q_showIfNotHidden", Qt::QueuedConnection); //show later
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \compat
-
- Sets this layout's parent widget to a fixed size with width \a w
- and height \a h, stopping the user from resizing it, and also
- prevents the layout from resizing it, even if the layout's size
- hint should change. Does nothing if this is not a top-level
- layout (i.e., if parent()->isWidgetType()).
-
- As a special case, if both \a w and \a h are 0, then the layout's
- current sizeHint() is used.
-
- Use \c setResizeMode(Fixed) to stop the widget from being resized
- by the user, while still allowing the layout to resize it when
- the sizeHint() changes.
-
- Use \c setResizeMode(FreeResize) to allow the user to resize the
- widget, while preventing the layout from resizing it.
-
-*/
-void QLayout::freeze(int w, int h)
-{
- Q_D(QLayout);
- if (!d->topLevel)
- return;
- if (w <= 0 || h <= 0) {
- QSize s = totalSizeHint();
- w = s.width();
- h = s.height();
- }
- setSizeConstraint(SetNoConstraint); // layout will not change min/max size
- QWidget *parent = parentWidget();
- if (parent)
- parent->setFixedSize(w, h);
-}
-
-#endif
-
-
-
-
-
-
-
-/*!
- Tells the geometry manager to place the menu bar \a widget at the
- top of parentWidget(), outside QWidget::contentsMargins(). All
- child widgets are placed below the bottom edge of the menu bar.
-*/
-void QLayout::setMenuBar(QWidget *widget)
-{
- Q_D(QLayout);
-
-#ifdef Q_OS_WINCE_WM
- if (widget && widget->size().height() > 0)
-#else
- if (widget)
-#endif
- addChildWidget(widget);
- d->menubar = widget;
-}
-
-/*!
- Returns the menu bar set for this layout, or 0 if no menu bar is
- set.
-*/
-
-QWidget *QLayout::menuBar() const
-{
- Q_D(const QLayout);
- return d->menubar;
-}
-
-
-/*!
- Returns the minimum size of this layout. This is the smallest
- size that the layout can have while still respecting the
- specifications.
-
- The returned value doesn't include the space required by
- QWidget::setContentsMargins() or menuBar().
-
- The default implementation allows unlimited resizing.
-*/
-QSize QLayout::minimumSize() const
-{
- return QSize(0, 0);
-}
-
-/*!
- Returns the maximum size of this layout. This is the largest size
- that the layout can have while still respecting the
- specifications.
-
- The returned value doesn't include the space required by
- QWidget::setContentsMargins() or menuBar().
-
- The default implementation allows unlimited resizing.
-*/
-QSize QLayout::maximumSize() const
-{
- return QSize(QLAYOUTSIZE_MAX, QLAYOUTSIZE_MAX);
-}
-
-/*!
- Returns whether this layout can make use of more space than
- sizeHint(). A value of Qt::Vertical or Qt::Horizontal means that
- it wants to grow in only one dimension, whereas Qt::Vertical |
- Qt::Horizontal means that it wants to grow in both dimensions.
-
- The default implementation returns Qt::Horizontal | Qt::Vertical.
- Subclasses reimplement it to return a meaningful value based on
- their child widgets's \l{QSizePolicy}{size policies}.
-
- \sa sizeHint()
-*/
-Qt::Orientations QLayout::expandingDirections() const
-{
- return Qt::Horizontal | Qt::Vertical;
-}
-
-void QLayout::activateRecursiveHelper(QLayoutItem *item)
-{
- item->invalidate();
- QLayout *layout = item->layout();
- if (layout) {
- QLayoutItem *child;
- int i=0;
- while ((child = layout->itemAt(i++)))
- activateRecursiveHelper(child);
- layout->d_func()->activated = true;
- }
-}
-
-/*!
- Updates the layout for parentWidget().
-
- You should generally not need to call this because it is
- automatically called at the most appropriate times.
-
- \sa activate(), invalidate()
-*/
-
-void QLayout::update()
-{
- QLayout *layout = this;
- while (layout && layout->d_func()->activated) {
- layout->d_func()->activated = false;
- if (layout->d_func()->topLevel) {
- Q_ASSERT(layout->parent()->isWidgetType());
- QWidget *mw = static_cast<QWidget*>(layout->parent());
- QApplication::postEvent(mw, new QEvent(QEvent::LayoutRequest));
- break;
- }
- layout = static_cast<QLayout*>(layout->parent());
- }
-}
-
-/*!
- Redoes the layout for parentWidget() if necessary.
-
- You should generally not need to call this because it is
- automatically called at the most appropriate times. It returns
- true if the layout was redone.
-
- \sa update(), QWidget::updateGeometry()
-*/
-bool QLayout::activate()
-{
- Q_D(QLayout);
- if (!d->enabled || !parent())
- return false;
- if (!d->topLevel)
- return static_cast<QLayout*>(parent())->activate();
- if (d->activated)
- return false;
- QWidget *mw = static_cast<QWidget*>(parent());
- if (mw == 0) {
- qWarning("QLayout::activate: %s \"%s\" does not have a main widget",
- QObject::metaObject()->className(), QObject::objectName().toLocal8Bit().data());
- return false;
- }
- activateRecursiveHelper(this);
-
- QWidgetPrivate *md = mw->d_func();
- uint explMin = md->extra ? md->extra->explicitMinSize : 0;
- uint explMax = md->extra ? md->extra->explicitMaxSize : 0;
-
- switch (d->constraint) {
- case SetFixedSize:
- // will trigger resize
- mw->setFixedSize(totalSizeHint());
- break;
- case SetMinimumSize:
- mw->setMinimumSize(totalMinimumSize());
- break;
- case SetMaximumSize:
- mw->setMaximumSize(totalMaximumSize());
- break;
- case SetMinAndMaxSize:
- mw->setMinimumSize(totalMinimumSize());
- mw->setMaximumSize(totalMaximumSize());
- break;
- case SetDefaultConstraint: {
- bool widthSet = explMin & Qt::Horizontal;
- bool heightSet = explMin & Qt::Vertical;
- if (mw->isWindow()) {
- QSize ms = totalMinimumSize();
- if (widthSet)
- ms.setWidth(mw->minimumSize().width());
- if (heightSet)
- ms.setHeight(mw->minimumSize().height());
- if ((!heightSet || !widthSet) && hasHeightForWidth()) {
- int h = minimumHeightForWidth(ms.width());
- if (h > ms.height()) {
- if (!heightSet)
- ms.setHeight(0);
- if (!widthSet)
- ms.setWidth(0);
- }
- }
- mw->setMinimumSize(ms);
- } else if (!widthSet || !heightSet) {
- QSize ms = mw->minimumSize();
- if (!widthSet)
- ms.setWidth(0);
- if (!heightSet)
- ms.setHeight(0);
- mw->setMinimumSize(ms);
- }
- break;
- }
- case SetNoConstraint:
- break;
- }
-
- d->doResize(mw->size());
-
- if (md->extra) {
- md->extra->explicitMinSize = explMin;
- md->extra->explicitMaxSize = explMax;
- }
- // ideally only if sizeHint() or sizePolicy() has changed
- mw->updateGeometry();
- return true;
-}
-
-/*!
- \fn QLayoutItem *QLayout::itemAt(int index) const
-
- Must be implemented in subclasses to return the layout item at \a
- index. If there is no such item, the function must return 0.
- Items are numbered consecutively from 0. If an item is deleted, other items will be renumbered.
-
- This function can be used to iterate over a layout. The following
- code will draw a rectangle for each layout item in the layout structure of the widget.
-
- \snippet doc/src/snippets/code/src_gui_kernel_qlayout.cpp 0
-
- \sa count(), takeAt()
-*/
-
-/*!
- \fn QLayoutItem *QLayout::takeAt(int index)
-
- Must be implemented in subclasses to remove the layout item at \a
- index from the layout, and return the item. If there is no such
- item, the function must do nothing and return 0. Items are numbered
- consecutively from 0. If an item is removed, other items will be
- renumbered.
-
- The following code fragment shows a safe way to remove all items
- from a layout:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qlayout.cpp 1
-
- \sa itemAt(), count()
-*/
-
-/*!
- \fn int *QLayout::count() const
-
- Must be implemented in subclasses to return the number of items
- in the layout.
-
- \sa itemAt()
-*/
-
-/*!
- Searches for widget \a widget in this layout (not including child
- layouts).
-
- Returns the index of \a widget, or -1 if \a widget is not found.
-
- The default implementation iterates over all items using itemAt()
-*/
-int QLayout::indexOf(QWidget *widget) const
-{
- int i = 0;
- QLayoutItem *item = itemAt(i);
- while (item) {
- if (item->widget() == widget)
- return i;
- ++i;
- item = itemAt(i);
- }
- return -1;
-}
-
-/*!
- \enum QLayout::SizeConstraint
-
- The possible values are:
-
- \value SetDefaultConstraint The main widget's minimum size is set
- to minimumSize(), unless the widget already has
- a minimum size.
-
- \value SetFixedSize The main widget's size is set to sizeHint(); it
- cannot be resized at all.
- \value SetMinimumSize The main widget's minimum size is set to
- minimumSize(); it cannot be smaller.
-
- \value SetMaximumSize The main widget's maximum size is set to
- maximumSize(); it cannot be larger.
-
- \value SetMinAndMaxSize The main widget's minimum size is set to
- minimumSize() and its maximum size is set to
- maximumSize().
-
- \value SetNoConstraint The widget is not constrained.
-
- \omitvalue Auto
- \omitvalue FreeResize
- \omitvalue Minimum
- \omitvalue Fixed
-
- \sa setSizeConstraint()
-*/
-
-/*!
- \property QLayout::sizeConstraint
- \brief the resize mode of the layout
-
- The default mode is \l {QLayout::SetDefaultConstraint}
- {SetDefaultConstraint}.
-*/
-void QLayout::setSizeConstraint(SizeConstraint constraint)
-{
- Q_D(QLayout);
- if (constraint == d->constraint)
- return;
-
- d->constraint = constraint;
- invalidate();
-}
-
-QLayout::SizeConstraint QLayout::sizeConstraint() const
-{
- Q_D(const QLayout);
- return d->constraint;
-}
-
-/*!
- Returns the rectangle that should be covered when the geometry of
- this layout is set to \a r, provided that this layout supports
- setAlignment().
-
- The result is derived from sizeHint() and expanding(). It is never
- larger than \a r.
-*/
-QRect QLayout::alignmentRect(const QRect &r) const
-{
- QSize s = sizeHint();
- Qt::Alignment a = alignment();
-
- /*
- This is a hack to obtain the real maximum size, not
- QSize(QLAYOUTSIZE_MAX, QLAYOUTSIZE_MAX), the value consistently
- returned by QLayoutItems that have an alignment.
- */
- QLayout *that = const_cast<QLayout *>(this);
- that->setAlignment(0);
- QSize ms = that->maximumSize();
- that->setAlignment(a);
-
- if ((expandingDirections() & Qt::Horizontal) ||
- !(a & Qt::AlignHorizontal_Mask)) {
- s.setWidth(qMin(r.width(), ms.width()));
- }
- if ((expandingDirections() & Qt::Vertical) ||
- !(a & Qt::AlignVertical_Mask)) {
- s.setHeight(qMin(r.height(), ms.height()));
- } else if (hasHeightForWidth()) {
- int hfw = heightForWidth(s.width());
- if (hfw < s.height())
- s.setHeight(qMin(hfw, ms.height()));
- }
-
- s = s.boundedTo(r.size());
- int x = r.x();
- int y = r.y();
-
- if (a & Qt::AlignBottom)
- y += (r.height() - s.height());
- else if (!(a & Qt::AlignTop))
- y += (r.height() - s.height()) / 2;
-
- QWidget *parent = parentWidget();
- a = QStyle::visualAlignment(parent ? parent->layoutDirection() : QApplication::layoutDirection(), a);
- if (a & Qt::AlignRight)
- x += (r.width() - s.width());
- else if (!(a & Qt::AlignLeft))
- x += (r.width() - s.width()) / 2;
-
- return QRect(x, y, s.width(), s.height());
-}
-
-/*!
- Removes the widget \a widget from the layout. After this call, it
- is the caller's responsibility to give the widget a reasonable
- geometry or to put the widget back into a layout.
-
- \bold{Note:} The ownership of \a widget remains the same as
- when it was added.
-
- \sa removeItem(), QWidget::setGeometry(), addWidget()
-*/
-void QLayout::removeWidget(QWidget *widget)
-{
- int i = 0;
- QLayoutItem *child;
- while ((child = itemAt(i))) {
- if (child->widget() == widget) {
- delete takeAt(i);
- invalidate();
- } else {
- ++i;
- }
- }
-}
-
-/*!
- Removes the layout item \a item from the layout. It is the
- caller's responsibility to delete the item.
-
- Notice that \a item can be a layout (since QLayout inherits
- QLayoutItem).
-
- \sa removeWidget(), addItem()
-*/
-void QLayout::removeItem(QLayoutItem *item)
-{
- int i = 0;
- QLayoutItem *child;
- while ((child = itemAt(i))) {
- if (child == item) {
- takeAt(i);
- invalidate();
- } else {
- ++i;
- }
- }
-}
-
-/*!
- Enables this layout if \a enable is true, otherwise disables it.
-
- An enabled layout adjusts dynamically to changes; a disabled
- layout acts as if it did not exist.
-
- By default all layouts are enabled.
-
- \sa isEnabled()
-*/
-void QLayout::setEnabled(bool enable)
-{
- Q_D(QLayout);
- d->enabled = enable;
-}
-
-/*!
- Returns true if the layout is enabled; otherwise returns false.
-
- \sa setEnabled()
-*/
-bool QLayout::isEnabled() const
-{
- Q_D(const QLayout);
- return d->enabled;
-}
-
-/*!
- Returns a size that satisfies all size constraints on \a widget,
- including heightForWidth() and that is as close as possible to \a
- size.
-*/
-
-QSize QLayout::closestAcceptableSize(const QWidget *widget, const QSize &size)
-{
- QSize result = size.boundedTo(qSmartMaxSize(widget));
- result = result.expandedTo(qSmartMinSize(widget));
- QLayout *l = widget->layout();
- if (l && l->hasHeightForWidth() && result.height() < l->minimumHeightForWidth(result.width()) ) {
- QSize current = widget->size();
- int currentHfw = l->minimumHeightForWidth(current.width());
- int newHfw = l->minimumHeightForWidth(result.width());
- if (current.height() < currentHfw || currentHfw == newHfw) {
- //handle the constant hfw case and the vertical-only case, as well as the
- // current-size-is-not-correct case
- result.setHeight(newHfw);
- } else {
- // binary search; assume hfw is decreasing ###
-
- int maxw = qMax(widget->width(),result.width());
- int maxh = qMax(widget->height(), result.height());
- int minw = qMin(widget->width(),result.width());
- int minh = qMin(widget->height(), result.height());
-
- int minhfw = l->minimumHeightForWidth(minw);
- int maxhfw = l->minimumHeightForWidth(maxw);
- while (minw < maxw) {
- if (minhfw > maxh) { //assume decreasing
- minw = maxw - (maxw-minw)/2;
- minhfw = l->minimumHeightForWidth(minw);
- } else if (maxhfw < minh ) { //assume decreasing
- maxw = minw + (maxw-minw)/2;
- maxhfw = l->minimumHeightForWidth(maxw);
- } else {
- break;
- }
- }
- result = result.expandedTo(QSize(minw, minhfw));
- }
- }
- return result;
-}
-
-/*!
- \fn void QLayout::setResizeMode(SizeConstraint constraint)
-
- Use setSizeConstraint(\a constraint) instead.
-*/
-
-/*!
- \fn QLayout::SizeConstraint QLayout::resizeMode() const
-
- Use sizeConstraint() instead.
-*/
-
-void QSizePolicy::setControlType(ControlType type)
-{
- /*
- The control type is a flag type, with values 0x1, 0x2, 0x4, 0x8, 0x10,
- etc. In memory, we pack it onto the available bits (CTSize) in
- setControlType(), and unpack it here.
-
- Example:
-
- 0x00000001 maps to 0x00000000
- 0x00000002 maps to 0x00000200
- 0x00000004 maps to 0x00000400
- 0x00000008 maps to 0x00000600
- etc.
- */
-
- int i = 0;
- while (true) {
- if (type & (0x1 << i)) {
- data = (data & ~CTMask) | (i << CTShift);
- return;
- }
- ++i;
- }
-}
-
-QSizePolicy::ControlType QSizePolicy::controlType() const
-{
- return QSizePolicy::ControlType(0x1 << ((data & CTMask) >> CTShift));
-}
-
-#ifndef QT_NO_DATASTREAM
-/*!
- \relates QSizePolicy
- \since 4.2
-
- Writes the size \a policy to the data stream \a stream.
-
- \sa \link datastreamformat.html Format of the QDataStream operators \endlink
-*/
-QDataStream &operator<<(QDataStream &stream, const QSizePolicy &policy)
-{
- return stream << policy.data;
-}
-
-/*!
- \relates QSizePolicy
- \since 4.2
-
- Reads the size \a policy from the data stream \a stream.
-
- \sa \link datastreamformat.html Format of the QDataStream operators \endlink
-*/
-QDataStream &operator>>(QDataStream &stream, QSizePolicy &policy)
-{
- return stream >> policy.data;
-}
-#endif // QT_NO_DATASTREAM
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qlayout.h b/src/gui/kernel/qlayout.h
deleted file mode 100644
index 5333150072..0000000000
--- a/src/gui/kernel/qlayout.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/****************************************************************************
-**
-** 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 QLAYOUT_H
-#define QLAYOUT_H
-
-#include <QtCore/qobject.h>
-#include <QtGui/qlayoutitem.h>
-#include <QtGui/qsizepolicy.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qmargins.h>
-
-#include <limits.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QLayout;
-class QSize;
-
-#ifdef QT3_SUPPORT
-class Q_GUI_EXPORT QLayoutIterator
-{
-public:
- inline QT3_SUPPORT_CONSTRUCTOR QLayoutIterator(QLayout *i) : layout(i), index(0) {}
- inline QLayoutIterator(const QLayoutIterator &i)
- : layout(i.layout), index(i.index) {}
- inline QLayoutIterator &operator=(const QLayoutIterator &i) {
- layout = i.layout;
- index = i.index;
- return *this;
- }
- inline QT3_SUPPORT QLayoutItem *operator++();
- inline QT3_SUPPORT QLayoutItem *current();
- inline QT3_SUPPORT QLayoutItem *takeCurrent();
- inline QT3_SUPPORT void deleteCurrent();
-
-private:
- // hack to avoid deprecated warning
- friend class QLayout;
- inline QLayoutIterator(QLayout *i, bool) : layout(i), index(0) {}
- QLayout *layout;
- int index;
-};
-#endif
-
-class QLayoutPrivate;
-
-class Q_GUI_EXPORT QLayout : public QObject, public QLayoutItem
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QLayout)
-
- Q_ENUMS(SizeConstraint)
- Q_PROPERTY(int margin READ margin WRITE setMargin)
- Q_PROPERTY(int spacing READ spacing WRITE setSpacing)
- Q_PROPERTY(SizeConstraint sizeConstraint READ sizeConstraint WRITE setSizeConstraint)
-public:
- enum SizeConstraint {
- SetDefaultConstraint,
- SetNoConstraint,
- SetMinimumSize,
- SetFixedSize,
- SetMaximumSize,
- SetMinAndMaxSize
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- , Auto = SetDefaultConstraint,
- FreeResize = SetNoConstraint,
- Minimum = SetMinimumSize,
- Fixed = SetFixedSize
-#endif
- };
-
- QLayout(QWidget *parent);
- QLayout();
- ~QLayout();
-
- int margin() const;
- int spacing() const;
-
- void setMargin(int);
- void setSpacing(int);
-
- void setContentsMargins(int left, int top, int right, int bottom);
- void setContentsMargins(const QMargins &margins);
- void getContentsMargins(int *left, int *top, int *right, int *bottom) const;
- QMargins contentsMargins() const;
- QRect contentsRect() const;
-
- bool setAlignment(QWidget *w, Qt::Alignment alignment);
- bool setAlignment(QLayout *l, Qt::Alignment alignment);
-#ifdef Q_NO_USING_KEYWORD
- inline void setAlignment(Qt::Alignment alignment) { QLayoutItem::setAlignment(alignment); }
-#else
- using QLayoutItem::setAlignment;
-#endif
-
- void setSizeConstraint(SizeConstraint);
- SizeConstraint sizeConstraint() const;
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT void setResizeMode(SizeConstraint s) {setSizeConstraint(s);}
- inline QT3_SUPPORT SizeConstraint resizeMode() const {return sizeConstraint();}
-#endif
- void setMenuBar(QWidget *w);
- QWidget *menuBar() const;
-
- QWidget *parentWidget() const;
-
- void invalidate();
- QRect geometry() const;
- bool activate();
- void update();
-
- void addWidget(QWidget *w);
- virtual void addItem(QLayoutItem *) = 0;
-
- void removeWidget(QWidget *w);
- void removeItem(QLayoutItem *);
-
- Qt::Orientations expandingDirections() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
- virtual void setGeometry(const QRect&);
- virtual QLayoutItem *itemAt(int index) const = 0;
- virtual QLayoutItem *takeAt(int index) = 0;
- virtual int indexOf(QWidget *) const;
- virtual int count() const = 0;
- bool isEmpty() const;
-
- int totalHeightForWidth(int w) const;
- QSize totalMinimumSize() const;
- QSize totalMaximumSize() const;
- QSize totalSizeHint() const;
- QLayout *layout();
-
- void setEnabled(bool);
- bool isEnabled() const;
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT void freeze(int w=0, int h=0);
- QT3_SUPPORT bool isTopLevel() const;
-#endif
-
- static QSize closestAcceptableSize(const QWidget *w, const QSize &s);
-
-protected:
- void widgetEvent(QEvent *);
- void childEvent(QChildEvent *e);
- void addChildLayout(QLayout *l);
- void addChildWidget(QWidget *w);
-#ifdef QT3_SUPPORT
- QT3_SUPPORT void deleteAllItems();
-#endif
-
- QRect alignmentRect(const QRect&) const;
-protected:
- QLayout(QLayoutPrivate &d, QLayout*, QWidget*);
-
-private:
- Q_DISABLE_COPY(QLayout)
-
- static void activateRecursiveHelper(QLayoutItem *item);
-
- friend class QApplicationPrivate;
- friend class QWidget;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QLayout(QWidget *parent, int margin, int spacing = -1,
- const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QLayout(QLayout *parentLayout, int spacing = -1, const char *name = 0);
- QT3_SUPPORT_CONSTRUCTOR QLayout(int spacing, const char *name = 0);
- inline QT3_SUPPORT QWidget *mainWidget() const { return parentWidget(); }
- inline QT3_SUPPORT void remove(QWidget *w) { removeWidget(w); }
- inline QT3_SUPPORT void add(QWidget *w) { addWidget(w); }
-
- QT3_SUPPORT void setAutoAdd(bool a);
- QT3_SUPPORT bool autoAdd() const;
- inline QT3_SUPPORT QLayoutIterator iterator() { return QLayoutIterator(this,true); }
-
- inline QT3_SUPPORT int defaultBorder() const { return spacing(); }
-#endif
-};
-
-#ifdef QT3_SUPPORT
-inline QLayoutItem *QLayoutIterator::operator++() { return layout->itemAt(++index); }
-inline QLayoutItem *QLayoutIterator::current() { return layout->itemAt(index); }
-inline QLayoutItem *QLayoutIterator::takeCurrent() { return layout->takeAt(index); }
-inline void QLayoutIterator::deleteCurrent() { delete layout->takeAt(index); }
-#endif
-
-//### support old includes
-#if 1 //def QT3_SUPPORT
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <QtGui/qboxlayout.h>
-#include <QtGui/qgridlayout.h>
-QT_END_INCLUDE_NAMESPACE
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLAYOUT_H
diff --git a/src/gui/kernel/qlayout_p.h b/src/gui/kernel/qlayout_p.h
deleted file mode 100644
index 342333954c..0000000000
--- a/src/gui/kernel/qlayout_p.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/****************************************************************************
-**
-** 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 QLAYOUT_P_H
-#define QLAYOUT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of qlayout*.cpp, and qabstractlayout.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qobject_p.h"
-#include "qstyle.h"
-#include "qsizepolicy.h"
-
-QT_BEGIN_NAMESPACE
-
-class QWidgetItem;
-class QSpacerItem;
-
-class Q_GUI_EXPORT QLayoutPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QLayout)
-
-public:
- typedef QWidgetItem * (*QWidgetItemFactoryMethod)(const QLayout *layout, QWidget *widget);
- typedef QSpacerItem * (*QSpacerItemFactoryMethod)(const QLayout *layout, int w, int h, QSizePolicy::Policy hPolicy, QSizePolicy::Policy);
-
- QLayoutPrivate();
-
- void getMargin(int *result, int userMargin, QStyle::PixelMetric pm) const;
- void doResize(const QSize &);
- void reparentChildWidgets(QWidget *mw);
-
- static QWidgetItem *createWidgetItem(const QLayout *layout, QWidget *widget);
- static QSpacerItem *createSpacerItem(const QLayout *layout, int w, int h, QSizePolicy::Policy hPolicy = QSizePolicy::Minimum, QSizePolicy::Policy vPolicy = QSizePolicy::Minimum);
-
- static QWidgetItemFactoryMethod widgetItemFactoryMethod;
- static QSpacerItemFactoryMethod spacerItemFactoryMethod;
-
- int insideSpacing;
- int userLeftMargin;
- int userTopMargin;
- int userRightMargin;
- int userBottomMargin;
- uint topLevel : 1;
- uint enabled : 1;
- uint activated : 1;
- uint autoNewChild : 1;
- QLayout::SizeConstraint constraint;
- QRect rect;
- QWidget *menubar;
-};
-
-QT_END_NAMESPACE
-
-#endif // QLAYOUT_P_H
diff --git a/src/gui/kernel/qlayoutengine.cpp b/src/gui/kernel/qlayoutengine.cpp
deleted file mode 100644
index fdabd8ae1f..0000000000
--- a/src/gui/kernel/qlayoutengine.cpp
+++ /dev/null
@@ -1,436 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlayout.h"
-#include "private/qlayoutengine_p.h"
-
-#include "qvector.h"
-#include "qwidget.h"
-
-#include <qlist.h>
-#include <qalgorithms.h>
-
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-//#define QLAYOUT_EXTRA_DEBUG
-
-typedef qint64 Fixed64;
-static inline Fixed64 toFixed(int i) { return (Fixed64)i * 256; }
-static inline int fRound(Fixed64 i) {
- return (i % 256 < 128) ? i / 256 : 1 + i / 256;
-}
-
-/*
- This is the main workhorse of the QGridLayout. It portions out
- available space to the chain's children.
-
- The calculation is done in fixed point: "fixed" variables are
- scaled by a factor of 256.
-
- If the layout runs "backwards" (i.e. RightToLeft or Up) the layout
- is computed mirror-reversed, and it's the caller's responsibility
- do reverse the values before use.
-
- chain contains input and output parameters describing the geometry.
- count is the count of items in the chain; pos and space give the
- interval (relative to parentWidget topLeft).
-*/
-void qGeomCalc(QVector<QLayoutStruct> &chain, int start, int count,
- int pos, int space, int spacer)
-{
- int cHint = 0;
- int cMin = 0;
- int cMax = 0;
- int sumStretch = 0;
- int sumSpacing = 0;
-
- bool wannaGrow = false; // anyone who really wants to grow?
- // bool canShrink = false; // anyone who could be persuaded to shrink?
-
- bool allEmptyNonstretch = true;
- int pendingSpacing = -1;
- int spacerCount = 0;
- int i;
-
- for (i = start; i < start + count; i++) {
- QLayoutStruct *data = &chain[i];
-
- data->done = false;
- cHint += data->smartSizeHint();
- cMin += data->minimumSize;
- cMax += data->maximumSize;
- sumStretch += data->stretch;
- if (!data->empty) {
- /*
- Using pendingSpacing, we ensure that the spacing for the last
- (non-empty) item is ignored.
- */
- if (pendingSpacing >= 0) {
- sumSpacing += pendingSpacing;
- ++spacerCount;
- }
- pendingSpacing = data->effectiveSpacer(spacer);
- }
- wannaGrow = wannaGrow || data->expansive || data->stretch > 0;
- allEmptyNonstretch = allEmptyNonstretch && !wannaGrow && data->empty;
- }
-
- int extraspace = 0;
-
- if (space < cMin + sumSpacing) {
- /*
- Less space than minimumSize; take from the biggest first
- */
-
- int minSize = cMin + sumSpacing;
-
- // shrink the spacers proportionally
- if (spacer >= 0) {
- spacer = minSize > 0 ? spacer * space / minSize : 0;
- sumSpacing = spacer * spacerCount;
- }
-
- QList<int> list;
-
- for (i = start; i < start + count; i++)
- list << chain.at(i).minimumSize;
-
- qSort(list);
-
- int space_left = space - sumSpacing;
-
- int sum = 0;
- int idx = 0;
- int space_used=0;
- int current = 0;
- while (idx < count && space_used < space_left) {
- current = list.at(idx);
- space_used = sum + current * (count - idx);
- sum += current;
- ++idx;
- }
- --idx;
- int deficit = space_used - space_left;
-
- int items = count - idx;
- /*
- * If we truncate all items to "current", we would get "deficit" too many pixels. Therefore, we have to remove
- * deficit/items from each item bigger than maxval. The actual value to remove is deficitPerItem + remainder/items
- * "rest" is the accumulated error from using integer arithmetic.
- */
- int deficitPerItem = deficit/items;
- int remainder = deficit % items;
- int maxval = current - deficitPerItem;
-
- int rest = 0;
- for (i = start; i < start + count; i++) {
- int maxv = maxval;
- rest += remainder;
- if (rest >= items) {
- maxv--;
- rest-=items;
- }
- QLayoutStruct *data = &chain[i];
- data->size = qMin(data->minimumSize, maxv);
- data->done = true;
- }
- } else if (space < cHint + sumSpacing) {
- /*
- Less space than smartSizeHint(), but more than minimumSize.
- Currently take space equally from each, as in Qt 2.x.
- Commented-out lines will give more space to stretchier
- items.
- */
- int n = count;
- int space_left = space - sumSpacing;
- int overdraft = cHint - space_left;
-
- // first give to the fixed ones:
- for (i = start; i < start + count; i++) {
- QLayoutStruct *data = &chain[i];
- if (!data->done
- && data->minimumSize >= data->smartSizeHint()) {
- data->size = data->smartSizeHint();
- data->done = true;
- space_left -= data->smartSizeHint();
- // sumStretch -= data->stretch;
- n--;
- }
- }
- bool finished = n == 0;
- while (!finished) {
- finished = true;
- Fixed64 fp_over = toFixed(overdraft);
- Fixed64 fp_w = 0;
-
- for (i = start; i < start+count; i++) {
- QLayoutStruct *data = &chain[i];
- if (data->done)
- continue;
- // if (sumStretch <= 0)
- fp_w += fp_over / n;
- // else
- // fp_w += (fp_over * data->stretch) / sumStretch;
- int w = fRound(fp_w);
- data->size = data->smartSizeHint() - w;
- fp_w -= toFixed(w); // give the difference to the next
- if (data->size < data->minimumSize) {
- data->done = true;
- data->size = data->minimumSize;
- finished = false;
- overdraft -= data->smartSizeHint() - data->minimumSize;
- // sumStretch -= data->stretch;
- n--;
- break;
- }
- }
- }
- } else { // extra space
- int n = count;
- int space_left = space - sumSpacing;
- // first give to the fixed ones, and handle non-expansiveness
- for (i = start; i < start + count; i++) {
- QLayoutStruct *data = &chain[i];
- if (!data->done
- && (data->maximumSize <= data->smartSizeHint()
- || (wannaGrow && !data->expansive && data->stretch == 0)
- || (!allEmptyNonstretch && data->empty &&
- !data->expansive && data->stretch == 0))) {
- data->size = data->smartSizeHint();
- data->done = true;
- space_left -= data->size;
- sumStretch -= data->stretch;
- n--;
- }
- }
- extraspace = space_left;
-
- /*
- Do a trial distribution and calculate how much it is off.
- If there are more deficit pixels than surplus pixels, give
- the minimum size items what they need, and repeat.
- Otherwise give to the maximum size items, and repeat.
-
- Paul Olav Tvete has a wonderful mathematical proof of the
- correctness of this principle, but unfortunately this
- comment is too small to contain it.
- */
- int surplus, deficit;
- do {
- surplus = deficit = 0;
- Fixed64 fp_space = toFixed(space_left);
- Fixed64 fp_w = 0;
- for (i = start; i < start + count; i++) {
- QLayoutStruct *data = &chain[i];
- if (data->done)
- continue;
- extraspace = 0;
- if (sumStretch <= 0)
- fp_w += fp_space / n;
- else
- fp_w += (fp_space * data->stretch) / sumStretch;
- int w = fRound(fp_w);
- data->size = w;
- fp_w -= toFixed(w); // give the difference to the next
- if (w < data->smartSizeHint()) {
- deficit += data->smartSizeHint() - w;
- } else if (w > data->maximumSize) {
- surplus += w - data->maximumSize;
- }
- }
- if (deficit > 0 && surplus <= deficit) {
- // give to the ones that have too little
- for (i = start; i < start+count; i++) {
- QLayoutStruct *data = &chain[i];
- if (!data->done && data->size < data->smartSizeHint()) {
- data->size = data->smartSizeHint();
- data->done = true;
- space_left -= data->smartSizeHint();
- sumStretch -= data->stretch;
- n--;
- }
- }
- }
- if (surplus > 0 && surplus >= deficit) {
- // take from the ones that have too much
- for (i = start; i < start + count; i++) {
- QLayoutStruct *data = &chain[i];
- if (!data->done && data->size > data->maximumSize) {
- data->size = data->maximumSize;
- data->done = true;
- space_left -= data->maximumSize;
- sumStretch -= data->stretch;
- n--;
- }
- }
- }
- } while (n > 0 && surplus != deficit);
- if (n == 0)
- extraspace = space_left;
- }
-
- /*
- As a last resort, we distribute the unwanted space equally
- among the spacers (counting the start and end of the chain). We
- could, but don't, attempt a sub-pixel allocation of the extra
- space.
- */
- int extra = extraspace / (spacerCount + 2);
- int p = pos + extra;
- for (i = start; i < start+count; i++) {
- QLayoutStruct *data = &chain[i];
- data->pos = p;
- p += data->size;
- if (!data->empty)
- p += data->effectiveSpacer(spacer) + extra;
- }
-
-#ifdef QLAYOUT_EXTRA_DEBUG
- qDebug() << "qGeomCalc" << "start" << start << "count" << count << "pos" << pos
- << "space" << space << "spacer" << spacer;
- for (i = start; i < start + count; ++i) {
- qDebug() << i << ':' << chain[i].minimumSize << chain[i].smartSizeHint()
- << chain[i].maximumSize << "stretch" << chain[i].stretch
- << "empty" << chain[i].empty << "expansive" << chain[i].expansive
- << "spacing" << chain[i].spacing;
- qDebug() << "result pos" << chain[i].pos << "size" << chain[i].size;
- }
-#endif
-}
-
-Q_GUI_EXPORT QSize qSmartMinSize(const QSize &sizeHint, const QSize &minSizeHint,
- const QSize &minSize, const QSize &maxSize,
- const QSizePolicy &sizePolicy)
-{
- QSize s(0, 0);
-
- if (sizePolicy.horizontalPolicy() != QSizePolicy::Ignored) {
- if (sizePolicy.horizontalPolicy() & QSizePolicy::ShrinkFlag)
- s.setWidth(minSizeHint.width());
- else
- s.setWidth(qMax(sizeHint.width(), minSizeHint.width()));
- }
-
- if (sizePolicy.verticalPolicy() != QSizePolicy::Ignored) {
- if (sizePolicy.verticalPolicy() & QSizePolicy::ShrinkFlag) {
- s.setHeight(minSizeHint.height());
- } else {
- s.setHeight(qMax(sizeHint.height(), minSizeHint.height()));
- }
- }
-
- s = s.boundedTo(maxSize);
- if (minSize.width() > 0)
- s.setWidth(minSize.width());
- if (minSize.height() > 0)
- s.setHeight(minSize.height());
-
- return s.expandedTo(QSize(0,0));
-}
-
-Q_GUI_EXPORT QSize qSmartMinSize(const QWidgetItem *i)
-{
- QWidget *w = ((QWidgetItem *)i)->widget();
- return qSmartMinSize(w->sizeHint(), w->minimumSizeHint(),
- w->minimumSize(), w->maximumSize(),
- w->sizePolicy());
-}
-
-Q_GUI_EXPORT QSize qSmartMinSize(const QWidget *w)
-{
- return qSmartMinSize(w->sizeHint(), w->minimumSizeHint(),
- w->minimumSize(), w->maximumSize(),
- w->sizePolicy());
-}
-
-Q_GUI_EXPORT QSize qSmartMaxSize(const QSize &sizeHint,
- const QSize &minSize, const QSize &maxSize,
- const QSizePolicy &sizePolicy, Qt::Alignment align)
-{
- if (align & Qt::AlignHorizontal_Mask && align & Qt::AlignVertical_Mask)
- return QSize(QLAYOUTSIZE_MAX, QLAYOUTSIZE_MAX);
- QSize s = maxSize;
- QSize hint = sizeHint.expandedTo(minSize);
- if (s.width() == QWIDGETSIZE_MAX && !(align & Qt::AlignHorizontal_Mask))
- if (!(sizePolicy.horizontalPolicy() & QSizePolicy::GrowFlag))
- s.setWidth(hint.width());
-
- if (s.height() == QWIDGETSIZE_MAX && !(align & Qt::AlignVertical_Mask))
- if (!(sizePolicy.verticalPolicy() & QSizePolicy::GrowFlag))
- s.setHeight(hint.height());
-
- if (align & Qt::AlignHorizontal_Mask)
- s.setWidth(QLAYOUTSIZE_MAX);
- if (align & Qt::AlignVertical_Mask)
- s.setHeight(QLAYOUTSIZE_MAX);
- return s;
-}
-
-Q_GUI_EXPORT QSize qSmartMaxSize(const QWidgetItem *i, Qt::Alignment align)
-{
- QWidget *w = ((QWidgetItem*)i)->widget();
-
- return qSmartMaxSize(w->sizeHint().expandedTo(w->minimumSizeHint()), w->minimumSize(), w->maximumSize(),
- w->sizePolicy(), align);
-}
-
-Q_GUI_EXPORT QSize qSmartMaxSize(const QWidget *w, Qt::Alignment align)
-{
- return qSmartMaxSize(w->sizeHint().expandedTo(w->minimumSizeHint()), w->minimumSize(), w->maximumSize(),
- w->sizePolicy(), align);
-}
-
-Q_GUI_EXPORT int qSmartSpacing(const QLayout *layout, QStyle::PixelMetric pm)
-{
- QObject *parent = layout->parent();
- if (!parent) {
- return -1;
- } else if (parent->isWidgetType()) {
- QWidget *pw = static_cast<QWidget *>(parent);
- return pw->style()->pixelMetric(pm, 0, pw);
- } else {
- return static_cast<QLayout *>(parent)->spacing();
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qlayoutengine_p.h b/src/gui/kernel/qlayoutengine_p.h
deleted file mode 100644
index da07f3bab1..0000000000
--- a/src/gui/kernel/qlayoutengine_p.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** 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 QLAYOUTENGINE_P_H
-#define QLAYOUTENGINE_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qlayoutitem.h"
-#include "QtGui/qstyle.h"
-
-QT_BEGIN_NAMESPACE
-
-template <typename T> class QVector;
-
-struct QLayoutStruct
-{
- inline void init(int stretchFactor = 0, int minSize = 0) {
- stretch = stretchFactor;
- minimumSize = sizeHint = minSize;
- maximumSize = QLAYOUTSIZE_MAX;
- expansive = false;
- empty = true;
- spacing = 0;
- }
-
- int smartSizeHint() {
- return (stretch > 0) ? minimumSize : sizeHint;
- }
- int effectiveSpacer(int uniformSpacer) const {
- Q_ASSERT(uniformSpacer >= 0 || spacing >= 0);
- return (uniformSpacer >= 0) ? uniformSpacer : spacing;
- }
-
- // parameters
- int stretch;
- int sizeHint;
- int maximumSize;
- int minimumSize;
- bool expansive;
- bool empty;
- int spacing;
-
- // temporary storage
- bool done;
-
- // result
- int pos;
- int size;
-};
-
-
-Q_GUI_EXPORT void qGeomCalc(QVector<QLayoutStruct> &chain, int start, int count,
- int pos, int space, int spacer = -1);
-Q_GUI_EXPORT QSize qSmartMinSize(const QSize &sizeHint, const QSize &minSizeHint,
- const QSize &minSize, const QSize &maxSize,
- const QSizePolicy &sizePolicy);
-Q_GUI_EXPORT QSize qSmartMinSize(const QWidgetItem *i);
-Q_GUI_EXPORT QSize qSmartMinSize(const QWidget *w);
-Q_GUI_EXPORT QSize qSmartMaxSize(const QSize &sizeHint,
- const QSize &minSize, const QSize &maxSize,
- const QSizePolicy &sizePolicy, Qt::Alignment align = 0);
-Q_GUI_EXPORT QSize qSmartMaxSize(const QWidgetItem *i, Qt::Alignment align = 0);
-Q_GUI_EXPORT QSize qSmartMaxSize(const QWidget *w, Qt::Alignment align = 0);
-
-Q_GUI_EXPORT int qSmartSpacing(const QLayout *layout, QStyle::PixelMetric pm);
-
-/*
- Modify total maximum (max), total expansion (exp), and total empty
- when adding boxmax/boxexp.
-
- Expansive boxes win over non-expansive boxes.
- Non-empty boxes win over empty boxes.
-*/
-static inline void qMaxExpCalc(int & max, bool &exp, bool &empty,
- int boxmax, bool boxexp, bool boxempty)
-{
- if (exp) {
- if (boxexp)
- max = qMax(max, boxmax);
- } else {
- if (boxexp || (empty && (!boxempty || max == 0)))
- max = boxmax;
- else if (empty == boxempty)
- max = qMin(max, boxmax);
- }
- exp = exp || boxexp;
- empty = empty && boxempty;
-}
-
-QT_END_NAMESPACE
-
-#endif // QLAYOUTENGINE_P_H
diff --git a/src/gui/kernel/qlayoutitem.cpp b/src/gui/kernel/qlayoutitem.cpp
deleted file mode 100644
index aeb96e9ef5..0000000000
--- a/src/gui/kernel/qlayoutitem.cpp
+++ /dev/null
@@ -1,834 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlayout.h"
-
-#include "qapplication.h"
-#include "qlayoutengine_p.h"
-#include "qmenubar.h"
-#include "qtoolbar.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qvariant.h"
-#include "qwidget_p.h"
-
-QT_BEGIN_NAMESPACE
-
-inline static QRect fromLayoutItemRect(QWidgetPrivate *priv, const QRect &rect)
-{
- return rect.adjusted(priv->leftLayoutItemMargin, priv->topLayoutItemMargin,
- -priv->rightLayoutItemMargin, -priv->bottomLayoutItemMargin);
-}
-
-inline static QSize fromLayoutItemSize(QWidgetPrivate *priv, const QSize &size)
-{
- return fromLayoutItemRect(priv, QRect(QPoint(0, 0), size)).size();
-}
-
-inline static QRect toLayoutItemRect(QWidgetPrivate *priv, const QRect &rect)
-{
- return rect.adjusted(-priv->leftLayoutItemMargin, -priv->topLayoutItemMargin,
- priv->rightLayoutItemMargin, priv->bottomLayoutItemMargin);
-}
-
-inline static QSize toLayoutItemSize(QWidgetPrivate *priv, const QSize &size)
-{
- return toLayoutItemRect(priv, QRect(QPoint(0, 0), size)).size();
-}
-
-/*!
- Returns a QVariant storing this QSizePolicy.
-*/
-QSizePolicy::operator QVariant() const
-{
- return QVariant(QVariant::SizePolicy, this);
-}
-
-/*!
- \class QLayoutItem
- \brief The QLayoutItem class provides an abstract item that a
- QLayout manipulates.
-
- \ingroup geomanagement
-
- This is used by custom layouts.
-
- Pure virtual functions are provided to return information about
- the layout, including, sizeHint(), minimumSize(), maximumSize()
- and expanding().
-
- The layout's geometry can be set and retrieved with setGeometry()
- and geometry(), and its alignment with setAlignment() and
- alignment().
-
- isEmpty() returns whether the layout item is empty. If the
- concrete item is a QWidget, it can be retrieved using widget().
- Similarly for layout() and spacerItem().
-
- Some layouts have width and height interdependencies. These can
- be expressed using hasHeightForWidth(), heightForWidth(), and
- minimumHeightForWidth(). For more explanation see the \e{Qt
- Quarterly} article
- \l{http://qt.nokia.com/doc/qq/qq04-height-for-width.html}{Trading
- Height for Width}.
-
- \sa QLayout
-*/
-
-/*!
- \class QSpacerItem
- \ingroup geomanagement
- \brief The QSpacerItem class provides blank space in a layout.
-
- Normally, you don't need to use this class directly. Qt's
- built-in layout managers provide the following functions for
- manipulating empty space in layouts:
-
- \table
- \header \o Class
- \o Functions
- \row \o QHBoxLayout
- \o \l{QBoxLayout::addSpacing()}{addSpacing()},
- \l{QBoxLayout::addStretch()}{addStretch()},
- \l{QBoxLayout::insertSpacing()}{insertSpacing()},
- \l{QBoxLayout::insertStretch()}{insertStretch()}
- \row \o QGridLayout
- \o \l{QGridLayout::setRowMinimumHeight()}{setRowMinimumHeight()},
- \l{QGridLayout::setRowStretch()}{setRowStretch()},
- \l{QGridLayout::setColumnMinimumWidth()}{setColumnMinimumWidth()},
- \l{QGridLayout::setColumnStretch()}{setColumnStretch()}
- \endtable
-
- \sa QLayout, QWidgetItem, QLayoutItem::spacerItem()
-*/
-
-/*!
- \class QWidgetItem
- \ingroup geomanagement
- \brief The QWidgetItem class is a layout item that represents a widget.
-
- Normally, you don't need to use this class directly. Qt's
- built-in layout managers provide the following functions for
- manipulating widgets in layouts:
-
- \table
- \header \o Class
- \o Functions
- \row \o QBoxLayout
- \o \l{QBoxLayout::addWidget()}{addWidget()},
- \l{QBoxLayout::insertWidget()}{insertWidget()},
- \l{QBoxLayout::setStretchFactor()}{setStretchFactor()}
- \row \o QGridLayout
- \o \l{QGridLayout::addWidget()}{addWidget()}
- \row \o QStackedLayout
- \o \l{QStackedLayout::addWidget()}{addWidget()},
- \l{QStackedLayout::insertWidget()}{insertWidget()},
- \l{QStackedLayout::currentWidget()}{currentWidget()},
- \l{QStackedLayout::setCurrentWidget()}{setCurrentWidget()},
- \l{QStackedLayout::widget()}{widget()}
- \endtable
-
- \sa QLayout, QSpacerItem, QLayoutItem::widget()
-*/
-
-/*!
- \fn QLayoutItem::QLayoutItem(Qt::Alignment alignment)
-
- Constructs a layout item with an \a alignment.
- Not all subclasses support alignment.
-*/
-
-/*!
- \fn Qt::Alignment QLayoutItem::alignment() const
-
- Returns the alignment of this item.
-*/
-
-/*!
- Sets the alignment of this item to \a alignment.
-
- \bold{Note:} Item alignment is only supported by QLayoutItem subclasses
- where it would have a visual effect. Except for QSpacerItem, which provides
- blank space for layouts, all public Qt classes that inherit QLayoutItem
- support item alignment.
-*/
-void QLayoutItem::setAlignment(Qt::Alignment alignment)
-{
- align = alignment;
-}
-
-/*!
- \fn QSize QLayoutItem::maximumSize() const
-
- Implemented in subclasses to return the maximum size of this item.
-*/
-
-/*!
- \fn QSize QLayoutItem::minimumSize() const
-
- Implemented in subclasses to return the minimum size of this item.
-*/
-
-/*!
- \fn QSize QLayoutItem::sizeHint() const
-
- Implemented in subclasses to return the preferred size of this item.
-*/
-
-/*!
- \fn Qt::Orientations QLayoutItem::expandingDirections() const
-
- Returns whether this layout item can make use of more space than
- sizeHint(). A value of Qt::Vertical or Qt::Horizontal means that
- it wants to grow in only one dimension, whereas Qt::Vertical |
- Qt::Horizontal means that it wants to grow in both dimensions.
-*/
-
-/*!
- \fn void QLayoutItem::setGeometry(const QRect &r)
-
- Implemented in subclasses to set this item's geometry to \a r.
-
- \sa geometry()
-*/
-
-/*!
- \fn QRect QLayoutItem::geometry() const
-
- Returns the rectangle covered by this layout item.
-
- \sa setGeometry()
-*/
-
-/*!
- \fn virtual bool QLayoutItem::isEmpty() const
-
- Implemented in subclasses to return whether this item is empty,
- i.e. whether it contains any widgets.
-*/
-
-/*!
- \fn QSpacerItem::QSpacerItem(int w, int h, QSizePolicy::Policy hPolicy, QSizePolicy::Policy vPolicy)
-
- Constructs a spacer item with preferred width \a w, preferred
- height \a h, horizontal size policy \a hPolicy and vertical size
- policy \a vPolicy.
-
- The default values provide a gap that is able to stretch if
- nothing else wants the space.
-*/
-
-/*!
- Changes this spacer item to have preferred width \a w, preferred
- height \a h, horizontal size policy \a hPolicy and vertical size
- policy \a vPolicy.
-
- The default values provide a gap that is able to stretch if
- nothing else wants the space.
-
- Note that if changeSize() is called after the spacer item has been added
- to a layout, it is necessary to invalidate the layout in order for the
- spacer item's new size to take effect.
-
- \sa QSpacerItem::invalidate()
-*/
-void QSpacerItem::changeSize(int w, int h, QSizePolicy::Policy hPolicy,
- QSizePolicy::Policy vPolicy)
-{
- width = w;
- height = h;
- sizeP = QSizePolicy(hPolicy, vPolicy);
-}
-
-/*!
- \fn QWidgetItem::QWidgetItem(QWidget *widget)
-
- Creates an item containing the given \a widget.
-*/
-
-/*!
- Destroys the QLayoutItem.
-*/
-QLayoutItem::~QLayoutItem()
-{
-}
-
-/*!
- Invalidates any cached information in this layout item.
-*/
-void QLayoutItem::invalidate()
-{
-}
-
-/*!
- If this item is a QLayout, it is returned as a QLayout; otherwise
- 0 is returned. This function provides type-safe casting.
-*/
-QLayout * QLayoutItem::layout()
-{
- return 0;
-}
-
-/*!
- If this item is a QSpacerItem, it is returned as a QSpacerItem;
- otherwise 0 is returned. This function provides type-safe casting.
-*/
-QSpacerItem * QLayoutItem::spacerItem()
-{
- return 0;
-}
-
-/*!
- \reimp
-*/
-QLayout * QLayout::layout()
-{
- return this;
-}
-
-/*!
- Returns a pointer to this object.
-*/
-QSpacerItem * QSpacerItem::spacerItem()
-{
- return this;
-}
-
-/*!
- If this item is a QWidget, it is returned as a QWidget; otherwise
- 0 is returned. This function provides type-safe casting.
-*/
-QWidget * QLayoutItem::widget()
-{
- return 0;
-}
-
-/*!
- Returns the widget managed by this item.
-*/
-QWidget *QWidgetItem::widget()
-{
- return wid;
-}
-
-/*!
- Returns true if this layout's preferred height depends on its
- width; otherwise returns false. The default implementation returns
- false.
-
- Reimplement this function in layout managers that support height
- for width.
-
- \sa heightForWidth(), QWidget::heightForWidth()
-*/
-bool QLayoutItem::hasHeightForWidth() const
-{
- return false;
-}
-
-/*!
- Returns the minimum height this widget needs for the given width,
- \a w. The default implementation simply returns heightForWidth(\a
- w).
-*/
-int QLayoutItem::minimumHeightForWidth(int w) const
-{
- return heightForWidth(w);
-}
-
-
-/*!
- Returns the preferred height for this layout item, given the width
- \a w.
-
- The default implementation returns -1, indicating that the
- preferred height is independent of the width of the item. Using
- the function hasHeightForWidth() will typically be much faster
- than calling this function and testing for -1.
-
- Reimplement this function in layout managers that support height
- for width. A typical implementation will look like this:
- \snippet doc/src/snippets/code/src_gui_kernel_qlayoutitem.cpp 0
-
- Caching is strongly recommended; without it layout will take
- exponential time.
-
- \sa hasHeightForWidth()
-*/
-int QLayoutItem::heightForWidth(int /* w */) const
-{
- return -1;
-}
-
-/*!
- Returns the control type(s) for the layout item. For a
- QWidgetItem, the control type comes from the widget's size
- policy; for a QLayoutItem, the control types is derived from the
- layout's contents.
-
- \sa QSizePolicy::controlType()
-*/
-QSizePolicy::ControlTypes QLayoutItem::controlTypes() const
-{
- // ### Qt 5: This function should probably be virtual instead
- if (const QWidget *widget = const_cast<QLayoutItem*>(this)->widget()) {
- return widget->sizePolicy().controlType();
- } else if (const QLayout *layout = const_cast<QLayoutItem*>(this)->layout()) {
- if (layout->count() == 0)
- return QSizePolicy::DefaultType;
- QSizePolicy::ControlTypes types;
- for (int i = layout->count() - 1; i >= 0; --i)
- types |= layout->itemAt(i)->controlTypes();
- return types;
- }
- return QSizePolicy::DefaultType;
-}
-
-/*!
- \reimp
-*/
-void QSpacerItem::setGeometry(const QRect &r)
-{
- rect = r;
-}
-
-/*!
- \reimp
-*/
-void QWidgetItem::setGeometry(const QRect &rect)
-{
- if (isEmpty())
- return;
-
- QRect r = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? fromLayoutItemRect(wid->d_func(), rect)
- : rect;
- const QSize widgetRectSurplus = r.size() - rect.size();
-
- /*
- For historical reasons, this code is done using widget rect
- coordinates, not layout item rect coordinates. However,
- QWidgetItem's sizeHint(), maximumSize(), and heightForWidth()
- all work in terms of layout item rect coordinates, so we have to
- add or subtract widgetRectSurplus here and there. The code could
- be much simpler if we did everything using layout item rect
- coordinates and did the conversion right before the call to
- QWidget::setGeometry().
- */
-
- QSize s = r.size().boundedTo(maximumSize() + widgetRectSurplus);
- int x = r.x();
- int y = r.y();
- if (align & (Qt::AlignHorizontal_Mask | Qt::AlignVertical_Mask)) {
- QSize pref(sizeHint());
- QSizePolicy sp = wid->sizePolicy();
- if (sp.horizontalPolicy() == QSizePolicy::Ignored)
- pref.setWidth(wid->sizeHint().expandedTo(wid->minimumSize()).width());
- if (sp.verticalPolicy() == QSizePolicy::Ignored)
- pref.setHeight(wid->sizeHint().expandedTo(wid->minimumSize()).height());
- pref += widgetRectSurplus;
- if (align & Qt::AlignHorizontal_Mask)
- s.setWidth(qMin(s.width(), pref.width()));
- if (align & Qt::AlignVertical_Mask) {
- if (hasHeightForWidth())
- s.setHeight(qMin(s.height(),
- heightForWidth(s.width() - widgetRectSurplus.width())
- + widgetRectSurplus.height()));
- else
- s.setHeight(qMin(s.height(), pref.height()));
- }
- }
- Qt::Alignment alignHoriz = QStyle::visualAlignment(wid->layoutDirection(), align);
- if (alignHoriz & Qt::AlignRight)
- x = x + (r.width() - s.width());
- else if (!(alignHoriz & Qt::AlignLeft))
- x = x + (r.width() - s.width()) / 2;
-
- if (align & Qt::AlignBottom)
- y = y + (r.height() - s.height());
- else if (!(align & Qt::AlignTop))
- y = y + (r.height() - s.height()) / 2;
-
- wid->setGeometry(x, y, s.width(), s.height());
-}
-
-/*!
- \reimp
-*/
-QRect QSpacerItem::geometry() const
-{
- return rect;
-}
-
-/*!
- \reimp
-*/
-QRect QWidgetItem::geometry() const
-{
- return !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? toLayoutItemRect(wid->d_func(), wid->geometry())
- : wid->geometry();
-}
-
-
-/*!
- \reimp
-*/
-bool QWidgetItem::hasHeightForWidth() const
-{
- if (isEmpty())
- return false;
- return wid->d_func()->hasHeightForWidth();
-}
-
-/*!
- \reimp
-*/
-int QWidgetItem::heightForWidth(int w) const
-{
- if (isEmpty())
- return -1;
-
- w = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? fromLayoutItemSize(wid->d_func(), QSize(w, 0)).width()
- : w;
-
- int hfw;
- if (wid->layout())
- hfw = wid->layout()->totalHeightForWidth(w);
- else
- hfw = wid->heightForWidth(w);
-
- if (hfw > wid->maximumHeight())
- hfw = wid->maximumHeight();
- if (hfw < wid->minimumHeight())
- hfw = wid->minimumHeight();
-
- hfw = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? toLayoutItemSize(wid->d_func(), QSize(0, hfw)).height()
- : hfw;
-
- if (hfw < 0)
- hfw = 0;
- return hfw;
-}
-
-/*!
- \reimp
-*/
-Qt::Orientations QSpacerItem::expandingDirections() const
-{
- return sizeP.expandingDirections();
-}
-
-/*!
- \reimp
-*/
-Qt::Orientations QWidgetItem::expandingDirections() const
-{
- if (isEmpty())
- return Qt::Orientations(0);
-
- Qt::Orientations e = wid->sizePolicy().expandingDirections();
- /*
- ### Qt 4.0:
- If the layout is expanding, we make the widget expanding, even if
- its own size policy isn't expanding. This behavior should be
- reconsidered.
- */
- if (wid->layout()) {
- if (wid->sizePolicy().horizontalPolicy() & QSizePolicy::GrowFlag
- && (wid->layout()->expandingDirections() & Qt::Horizontal))
- e |= Qt::Horizontal;
- if (wid->sizePolicy().verticalPolicy() & QSizePolicy::GrowFlag
- && (wid->layout()->expandingDirections() & Qt::Vertical))
- e |= Qt::Vertical;
- }
-
- if (align & Qt::AlignHorizontal_Mask)
- e &= ~Qt::Horizontal;
- if (align & Qt::AlignVertical_Mask)
- e &= ~Qt::Vertical;
- return e;
-}
-
-/*!
- \reimp
-*/
-QSize QSpacerItem::minimumSize() const
-{
- return QSize(sizeP.horizontalPolicy() & QSizePolicy::ShrinkFlag ? 0 : width,
- sizeP.verticalPolicy() & QSizePolicy::ShrinkFlag ? 0 : height);
-}
-
-/*!
- \reimp
-*/
-QSize QWidgetItem::minimumSize() const
-{
- if (isEmpty())
- return QSize(0, 0);
- return !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? toLayoutItemSize(wid->d_func(), qSmartMinSize(this))
- : qSmartMinSize(this);
-}
-
-/*!
- \reimp
-*/
-QSize QSpacerItem::maximumSize() const
-{
- return QSize(sizeP.horizontalPolicy() & QSizePolicy::GrowFlag ? QLAYOUTSIZE_MAX : width,
- sizeP.verticalPolicy() & QSizePolicy::GrowFlag ? QLAYOUTSIZE_MAX : height);
-}
-
-/*!
- \reimp
-*/
-QSize QWidgetItem::maximumSize() const
-{
- if (isEmpty()) {
- return QSize(0, 0);
- } else {
- return !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? toLayoutItemSize(wid->d_func(), qSmartMaxSize(this, align))
- : qSmartMaxSize(this, align);
- }
-}
-
-/*!
- \reimp
-*/
-QSize QSpacerItem::sizeHint() const
-{
- return QSize(width, height);
-}
-
-/*!
- \reimp
-*/
-QSize QWidgetItem::sizeHint() const
-{
- QSize s(0, 0);
- if (!isEmpty()) {
- s = wid->sizeHint().expandedTo(wid->minimumSizeHint());
- s = s.boundedTo(wid->maximumSize())
- .expandedTo(wid->minimumSize());
- s = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect)
- ? toLayoutItemSize(wid->d_func(), s)
- : s;
-
- if (wid->sizePolicy().horizontalPolicy() == QSizePolicy::Ignored)
- s.setWidth(0);
- if (wid->sizePolicy().verticalPolicy() == QSizePolicy::Ignored)
- s.setHeight(0);
- }
- return s;
-}
-
-/*!
- Returns true.
-*/
-bool QSpacerItem::isEmpty() const
-{
- return true;
-}
-
-/*!
- Returns true if the widget is hidden; otherwise returns false.
-
- \sa QWidget::isHidden()
-*/
-bool QWidgetItem::isEmpty() const
-{
- return wid->isHidden() || wid->isWindow();
-}
-
-/*!
- \class QWidgetItemV2
- \internal
-*/
-
-inline bool QWidgetItemV2::useSizeCache() const
-{
- return wid->d_func()->widgetItem == this;
-}
-
-void QWidgetItemV2::updateCacheIfNecessary() const
-{
- if (q_cachedMinimumSize.width() != Dirty)
- return;
-
- const QSize sizeHint(wid->sizeHint());
- const QSize minimumSizeHint(wid->minimumSizeHint());
- const QSize minimumSize(wid->minimumSize());
- const QSize maximumSize(wid->maximumSize());
- const QSizePolicy sizePolicy(wid->sizePolicy());
- const QSize expandedSizeHint(sizeHint.expandedTo(minimumSizeHint));
-
- const QSize smartMinSize(qSmartMinSize(sizeHint, minimumSizeHint, minimumSize, maximumSize, sizePolicy));
- const QSize smartMaxSize(qSmartMaxSize(expandedSizeHint, minimumSize, maximumSize, sizePolicy, align));
-
- const bool useLayoutItemRect = !wid->testAttribute(Qt::WA_LayoutUsesWidgetRect);
-
- q_cachedMinimumSize = useLayoutItemRect
- ? toLayoutItemSize(wid->d_func(), smartMinSize)
- : smartMinSize;
-
- q_cachedSizeHint = expandedSizeHint;
- q_cachedSizeHint = q_cachedSizeHint.boundedTo(maximumSize)
- .expandedTo(minimumSize);
- q_cachedSizeHint = useLayoutItemRect
- ? toLayoutItemSize(wid->d_func(), q_cachedSizeHint)
- : q_cachedSizeHint;
-
- if (wid->sizePolicy().horizontalPolicy() == QSizePolicy::Ignored)
- q_cachedSizeHint.setWidth(0);
- if (wid->sizePolicy().verticalPolicy() == QSizePolicy::Ignored)
- q_cachedSizeHint.setHeight(0);
-
- q_cachedMaximumSize = useLayoutItemRect
- ? toLayoutItemSize(wid->d_func(), smartMaxSize)
- : smartMaxSize;
-}
-
-QWidgetItemV2::QWidgetItemV2(QWidget *widget)
- : QWidgetItem(widget),
- q_cachedMinimumSize(Dirty, Dirty),
- q_cachedSizeHint(Dirty, Dirty),
- q_cachedMaximumSize(Dirty, Dirty),
- q_firstCachedHfw(0),
- q_hfwCacheSize(0),
- d(0)
-{
- QWidgetPrivate *wd = wid->d_func();
- if (!wd->widgetItem)
- wd->widgetItem = this;
-}
-
-QWidgetItemV2::~QWidgetItemV2()
-{
- if (wid) {
- QWidgetPrivate *wd = wid->d_func();
- if (wd->widgetItem == this)
- wd->widgetItem = 0;
- }
-}
-
-QSize QWidgetItemV2::sizeHint() const
-{
- if (isEmpty())
- return QSize(0, 0);
-
- if (useSizeCache()) {
- updateCacheIfNecessary();
- return q_cachedSizeHint;
- } else {
- return QWidgetItem::sizeHint();
- }
-}
-
-QSize QWidgetItemV2::minimumSize() const
-{
- if (isEmpty())
- return QSize(0, 0);
-
- if (useSizeCache()) {
- updateCacheIfNecessary();
- return q_cachedMinimumSize;
- } else {
- return QWidgetItem::minimumSize();
- }
-}
-
-QSize QWidgetItemV2::maximumSize() const
-{
- if (isEmpty())
- return QSize(0, 0);
-
- if (useSizeCache()) {
- updateCacheIfNecessary();
- return q_cachedMaximumSize;
- } else {
- return QWidgetItem::maximumSize();
- }
-}
-
-/*
- The height-for-width cache is organized as a circular buffer. The entries
-
- q_hfwCachedHfws[q_firstCachedHfw],
- ...,
- q_hfwCachedHfws[(q_firstCachedHfw + q_hfwCacheSize - 1) % HfwCacheMaxSize]
-
- contain the last cached values. When the cache is full, the first entry to
- be erased is the entry before q_hfwCachedHfws[q_firstCachedHfw]. When
- values are looked up, we try to move q_firstCachedHfw to point to that new
- entry (unless the cache is not full, in which case it would leave the cache
- in a broken state), so that the most recently used entry is also the last
- to be erased.
-*/
-
-int QWidgetItemV2::heightForWidth(int width) const
-{
- if (isEmpty())
- return -1;
-
- for (int i = 0; i < q_hfwCacheSize; ++i) {
- int offset = q_firstCachedHfw + i;
- const QSize &size = q_cachedHfws[offset % HfwCacheMaxSize];
- if (size.width() == width) {
- if (q_hfwCacheSize == HfwCacheMaxSize)
- q_firstCachedHfw = offset;
- return size.height();
- }
- }
-
- if (q_hfwCacheSize < HfwCacheMaxSize)
- ++q_hfwCacheSize;
- q_firstCachedHfw = (q_firstCachedHfw + HfwCacheMaxSize - 1) % HfwCacheMaxSize;
-
- int height = QWidgetItem::heightForWidth(width);
- q_cachedHfws[q_firstCachedHfw] = QSize(width, height);
- return height;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qlayoutitem.h b/src/gui/kernel/qlayoutitem.h
deleted file mode 100644
index a75011f3ff..0000000000
--- a/src/gui/kernel/qlayoutitem.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/****************************************************************************
-**
-** 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 QLAYOUTITEM_H
-#define QLAYOUTITEM_H
-
-#include <QtGui/qsizepolicy.h>
-#include <QtCore/qrect.h>
-
-#include <limits.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-static const int QLAYOUTSIZE_MAX = INT_MAX/256/16;
-
-class QLayout;
-class QLayoutItem;
-class QSpacerItem;
-class QWidget;
-class QSize;
-
-class Q_GUI_EXPORT QLayoutItem
-{
-public:
- inline explicit QLayoutItem(Qt::Alignment alignment = 0);
- virtual ~QLayoutItem();
- virtual QSize sizeHint() const = 0;
- virtual QSize minimumSize() const = 0;
- virtual QSize maximumSize() const = 0;
- virtual Qt::Orientations expandingDirections() const = 0;
- virtual void setGeometry(const QRect&) = 0;
- virtual QRect geometry() const = 0;
- virtual bool isEmpty() const = 0;
- virtual bool hasHeightForWidth() const;
- virtual int heightForWidth(int) const;
- virtual int minimumHeightForWidth(int) const;
- virtual void invalidate();
-
- virtual QWidget *widget();
- virtual QLayout *layout();
- virtual QSpacerItem *spacerItem();
-
- Qt::Alignment alignment() const { return align; }
- void setAlignment(Qt::Alignment a);
- QSizePolicy::ControlTypes controlTypes() const;
-
-protected:
- Qt::Alignment align;
-};
-
-inline QLayoutItem::QLayoutItem(Qt::Alignment aalignment)
- : align(aalignment) { }
-
-class Q_GUI_EXPORT QSpacerItem : public QLayoutItem
-{
-public:
- QSpacerItem(int w, int h,
- QSizePolicy::Policy hData = QSizePolicy::Minimum,
- QSizePolicy::Policy vData = QSizePolicy::Minimum)
- : width(w), height(h), sizeP(hData, vData) { }
- void changeSize(int w, int h,
- QSizePolicy::Policy hData = QSizePolicy::Minimum,
- QSizePolicy::Policy vData = QSizePolicy::Minimum);
- QSize sizeHint() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
- Qt::Orientations expandingDirections() const;
- bool isEmpty() const;
- void setGeometry(const QRect&);
- QRect geometry() const;
- QSpacerItem *spacerItem();
-
-private:
- int width;
- int height;
- QSizePolicy sizeP;
- QRect rect;
-};
-
-class Q_GUI_EXPORT QWidgetItem : public QLayoutItem
-{
- Q_DISABLE_COPY(QWidgetItem)
-
-public:
- explicit QWidgetItem(QWidget *w) : wid(w) { }
- QSize sizeHint() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
- Qt::Orientations expandingDirections() const;
- bool isEmpty() const;
- void setGeometry(const QRect&);
- QRect geometry() const;
- virtual QWidget *widget();
-
- bool hasHeightForWidth() const;
- int heightForWidth(int) const;
-
-protected:
- QWidget *wid;
-};
-
-class Q_GUI_EXPORT QWidgetItemV2 : public QWidgetItem
-{
-public:
- explicit QWidgetItemV2(QWidget *widget);
- ~QWidgetItemV2();
-
- QSize sizeHint() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
- int heightForWidth(int width) const;
-
-private:
- enum { Dirty = -123, HfwCacheMaxSize = 3 };
-
- inline bool useSizeCache() const;
- void updateCacheIfNecessary() const;
- inline void invalidateSizeCache() {
- q_cachedMinimumSize.setWidth(Dirty);
- q_hfwCacheSize = 0;
- }
-
- mutable QSize q_cachedMinimumSize;
- mutable QSize q_cachedSizeHint;
- mutable QSize q_cachedMaximumSize;
- mutable QSize q_cachedHfws[HfwCacheMaxSize];
- mutable short q_firstCachedHfw;
- mutable short q_hfwCacheSize;
- void *d;
-
- friend class QWidgetPrivate;
-
- Q_DISABLE_COPY(QWidgetItemV2)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLAYOUTITEM_H
diff --git a/src/gui/kernel/qsizepolicy.h b/src/gui/kernel/qsizepolicy.h
deleted file mode 100644
index c0a8cc1f18..0000000000
--- a/src/gui/kernel/qsizepolicy.h
+++ /dev/null
@@ -1,244 +0,0 @@
-/****************************************************************************
-**
-** 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 QSIZEPOLICY_H
-#define QSIZEPOLICY_H
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QVariant;
-
-class Q_GUI_EXPORT QSizePolicy
-{
- Q_GADGET
- Q_ENUMS(Policy)
-
-private:
- enum SizePolicyMasks {
- HSize = 4,
- HMask = 0x0f,
- VMask = HMask << HSize,
- CTShift = 9,
- CTSize = 5,
- CTMask = ((0x1 << CTSize) - 1) << CTShift,
- WFHShift = CTShift + CTSize,
- UnusedShift = WFHShift + 1,
- UnusedSize = 1
- };
-
-public:
- enum PolicyFlag {
- GrowFlag = 1,
- ExpandFlag = 2,
- ShrinkFlag = 4,
- IgnoreFlag = 8
- };
-
- enum Policy {
- Fixed = 0,
- Minimum = GrowFlag,
- Maximum = ShrinkFlag,
- Preferred = GrowFlag | ShrinkFlag,
- MinimumExpanding = GrowFlag | ExpandFlag,
- Expanding = GrowFlag | ShrinkFlag | ExpandFlag,
- Ignored = ShrinkFlag | GrowFlag | IgnoreFlag
- };
-
- enum ControlType {
- DefaultType = 0x00000001,
- ButtonBox = 0x00000002,
- CheckBox = 0x00000004,
- ComboBox = 0x00000008,
- Frame = 0x00000010,
- GroupBox = 0x00000020,
- Label = 0x00000040,
- Line = 0x00000080,
- LineEdit = 0x00000100,
- PushButton = 0x00000200,
- RadioButton = 0x00000400,
- Slider = 0x00000800,
- SpinBox = 0x00001000,
- TabWidget = 0x00002000,
- ToolButton = 0x00004000
- };
- Q_DECLARE_FLAGS(ControlTypes, ControlType)
-
- QSizePolicy() : data(0) { }
-
- // ### Qt 5: merge these two constructors (with type == DefaultType)
- QSizePolicy(Policy horizontal, Policy vertical)
- : data(horizontal | (vertical << HSize)) { }
- QSizePolicy(Policy horizontal, Policy vertical, ControlType type)
- : data(horizontal | (vertical << HSize)) { setControlType(type); }
-
- Policy horizontalPolicy() const { return static_cast<Policy>(data & HMask); }
- Policy verticalPolicy() const { return static_cast<Policy>((data & VMask) >> HSize); }
- ControlType controlType() const;
-
- void setHorizontalPolicy(Policy d) { data = (data & ~HMask) | d; }
- void setVerticalPolicy(Policy d) { data = (data & ~(HMask << HSize)) | (d << HSize); }
- void setControlType(ControlType type);
-
- Qt::Orientations expandingDirections() const {
- Qt::Orientations result;
- if (verticalPolicy() & ExpandFlag)
- result |= Qt::Vertical;
- if (horizontalPolicy() & ExpandFlag)
- result |= Qt::Horizontal;
- return result;
- }
-
- void setHeightForWidth(bool b) { data = b ? (data | (1 << 2*HSize)) : (data & ~(1 << 2*HSize)); }
- bool hasHeightForWidth() const { return data & (1 << 2*HSize); }
- void setWidthForHeight(bool b) { data = b ? (data | (1 << (WFHShift))) : (data & ~(1 << (WFHShift))); }
- bool hasWidthForHeight() const { return data & (1 << (WFHShift)); }
-
- bool operator==(const QSizePolicy& s) const { return data == s.data; }
- bool operator!=(const QSizePolicy& s) const { return data != s.data; }
- operator QVariant() const; // implemented in qabstractlayout.cpp
-
- int horizontalStretch() const { return data >> 24; }
- int verticalStretch() const { return (data >> 16) & 0xff; }
- void setHorizontalStretch(uchar stretchFactor) { data = (data&0x00ffffff) | (uint(stretchFactor)<<24); }
- void setVerticalStretch(uchar stretchFactor) { data = (data&0xff00ffff) | (uint(stretchFactor)<<16); }
-
- void transpose();
-
-#ifdef QT3_SUPPORT
- typedef Policy SizeType;
-#ifndef qdoc
- typedef Qt::Orientations ExpandData;
- enum {
- NoDirection = 0,
- Horizontally = 1,
- Vertically = 2,
- BothDirections = Horizontally | Vertically
- };
-#else
- enum ExpandData {
- NoDirection = 0x0,
- Horizontally = 0x1,
- Vertically = 0x2,
- BothDirections = 0x3
- };
-#endif // qdoc
-
- inline QT3_SUPPORT bool mayShrinkHorizontally() const
- { return horizontalPolicy() & ShrinkFlag; }
- inline QT3_SUPPORT bool mayShrinkVertically() const { return verticalPolicy() & ShrinkFlag; }
- inline QT3_SUPPORT bool mayGrowHorizontally() const { return horizontalPolicy() & GrowFlag; }
- inline QT3_SUPPORT bool mayGrowVertically() const { return verticalPolicy() & GrowFlag; }
- inline QT3_SUPPORT Qt::Orientations expanding() const { return expandingDirections(); }
-
- QT3_SUPPORT_CONSTRUCTOR QSizePolicy(Policy hor, Policy ver, bool hfw)
- : data(hor | (ver<<HSize) | (hfw ? (1U<<2*HSize) : 0)) { }
-
- QT3_SUPPORT_CONSTRUCTOR QSizePolicy(Policy hor, Policy ver, uchar hors, uchar vers, bool hfw = false)
- : data(hor | (ver<<HSize) | (hfw ? (1U<<2*HSize) : 0)) {
- setHorizontalStretch(hors);
- setVerticalStretch(vers);
- }
-
- inline QT3_SUPPORT Policy horData() const { return static_cast<Policy>(data & HMask); }
- inline QT3_SUPPORT Policy verData() const { return static_cast<Policy>((data & VMask) >> HSize); }
- inline QT3_SUPPORT void setHorData(Policy d) { setHorizontalPolicy(d); }
- inline QT3_SUPPORT void setVerData(Policy d) { setVerticalPolicy(d); }
-
- inline QT3_SUPPORT uint horStretch() const { return horizontalStretch(); }
- inline QT3_SUPPORT uint verStretch() const { return verticalStretch(); }
- inline QT3_SUPPORT void setHorStretch(uchar sf) { setHorizontalStretch(sf); }
- inline QT3_SUPPORT void setVerStretch(uchar sf) { setVerticalStretch(sf); }
-#endif
-
-private:
-#ifndef QT_NO_DATASTREAM
- friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QSizePolicy &);
- friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QSizePolicy &);
-#endif
- QSizePolicy(int i) : data(i) { }
-
- quint32 data;
-/* Qt5: Use bit flags instead, keep it here for improved readability for now.
- We can maybe change it for Qt4, but we'd have to be careful, since the behaviour
- is implementation defined. It usually varies between little- and big-endian compilers, but
- it might also not vary.
- quint32 horzPolicy : 4;
- quint32 vertPolicy : 4;
- quint32 hfw : 1;
- quint32 ctype : 5;
- quint32 wfh : 1;
- quint32 padding : 1; // we cannot use the highest bit
- quint32 verStretch : 8;
- quint32 horStretch : 8;
-*/
-
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QSizePolicy::ControlTypes)
-
-#ifndef QT_NO_DATASTREAM
-// implemented in qlayout.cpp
-Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QSizePolicy &);
-Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QSizePolicy &);
-#endif
-
-inline void QSizePolicy::transpose() {
- Policy hData = horizontalPolicy();
- Policy vData = verticalPolicy();
- uchar hStretch = uchar(horizontalStretch());
- uchar vStretch = uchar(verticalStretch());
- setHorizontalPolicy(vData);
- setVerticalPolicy(hData);
- setHorizontalStretch(vStretch);
- setVerticalStretch(hStretch);
-}
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSIZEPOLICY_H
diff --git a/src/gui/kernel/qsizepolicy.qdoc b/src/gui/kernel/qsizepolicy.qdoc
deleted file mode 100644
index 80e9f20f74..0000000000
--- a/src/gui/kernel/qsizepolicy.qdoc
+++ /dev/null
@@ -1,529 +0,0 @@
-/****************************************************************************
-**
-** 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 documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** 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 Free Documentation License
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of this
-** file.
-**
-** If you have questions regarding the use of this file, please contact
-** Nokia at qt-info@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \class QSizePolicy
- \brief The QSizePolicy class is a layout attribute describing horizontal
- and vertical resizing policy.
-
- \ingroup geomanagement
-
- The size policy of a widget is an expression of its willingness to
- be resized in various ways, and affects how the widget is treated
- by the \l{Layout Management}{layout engine}. Each widget returns a
- QSizePolicy that describes the horizontal and vertical resizing
- policy it prefers when being laid out. You can change this for
- a specific widget by changing its QWidget::sizePolicy property.
-
- QSizePolicy contains two independent QSizePolicy::Policy values
- and two stretch factors; one describes the widgets's horizontal
- size policy, and the other describes its vertical size policy. It
- also contains a flag to indicate whether the height and width of
- its preferred size are related.
-
- The horizontal and vertical policies can be set in the
- constructor, and altered using the setHorizontalPolicy() and
- setVerticalPolicy() functions. The stretch factors can be set
- using the setHorizontalStretch() and setVerticalStretch()
- functions. The flag indicating whether the widget's
- \l{QWidget::sizeHint()}{sizeHint()} is width-dependent (such as a
- menu bar or a word-wrapping label) can be set using the
- setHeightForWidth() function.
-
- The current size policies and stretch factors be retrieved using
- the horizontalPolicy(), verticalPolicy(), horizontalStretch() and
- verticalStretch() functions. Alternatively, use the transpose()
- function to swap the horizontal and vertical policies and
- stretches. The hasHeightForWidth() function returns the current
- status of the flag indicating the size hint dependencies.
-
- Use the expandingDirections() function to determine whether the
- associated widget can make use of more space than its
- \l{QWidget::sizeHint()}{sizeHint()} function indicates, as well as
- find out in which directions it can expand.
-
- Finally, the QSizePolicy class provides operators comparing this
- size policy to a given policy, as well as a QVariant operator
- storing this QSizePolicy as a QVariant object.
-
- \sa QSize, QWidget::sizeHint(), QWidget::sizePolicy,
- QLayoutItem::sizeHint()
-*/
-
-/*!
- \enum QSizePolicy::PolicyFlag
-
- These flags are combined together to form the various \l{Policy}
- values:
-
- \value GrowFlag The widget can grow beyond its size hint if necessary.
- \value ExpandFlag The widget should get as much space as possible.
- \value ShrinkFlag The widget can shrink below its size hint if necessary.
- \value IgnoreFlag The widget's size hint is ignored. The widget will get
- as much space as possible.
-
- \sa Policy
-*/
-
-/*!
- \enum QSizePolicy::Policy
-
- This enum describes the various per-dimension sizing types used
- when constructing a QSizePolicy.
-
- \value Fixed The QWidget::sizeHint() is the only acceptable
- alternative, so the widget can never grow or shrink (e.g. the
- vertical direction of a push button).
-
- \value Minimum The sizeHint() is minimal, and sufficient. The
- widget can be expanded, but there is no advantage to it being
- larger (e.g. the horizontal direction of a push button).
- It cannot be smaller than the size provided by sizeHint().
-
- \value Maximum The sizeHint() is a maximum. The widget can be
- shrunk any amount without detriment if other widgets need the
- space (e.g. a separator line).
- It cannot be larger than the size provided by sizeHint().
-
- \value Preferred The sizeHint() is best, but the widget can be
- shrunk and still be useful. The widget can be expanded, but there
- is no advantage to it being larger than sizeHint() (the default
- QWidget policy).
-
- \value Expanding The sizeHint() is a sensible size, but the
- widget can be shrunk and still be useful. The widget can make use
- of extra space, so it should get as much space as possible (e.g.
- the horizontal direction of a horizontal slider).
-
- \value MinimumExpanding The sizeHint() is minimal, and sufficient.
- The widget can make use of extra space, so it should get as much
- space as possible (e.g. the horizontal direction of a horizontal
- slider).
-
- \value Ignored The sizeHint() is ignored. The widget will get as
- much space as possible.
-
- \sa PolicyFlag, setHorizontalPolicy(), setVerticalPolicy()
-*/
-
-/*!
- \fn QSizePolicy::QSizePolicy()
-
- Constructs a QSizePolicy object with \l Fixed as its horizontal
- and vertical policies.
-
- The policies can be altered using the setHorizontalPolicy() and
- setVerticalPolicy() functions. Use the setHeightForWidth()
- function if the preferred height of the widget is dependent on the
- width of the widget (for example, a QLabel with line wrapping).
-
- \sa setHorizontalStretch(), setVerticalStretch()
-*/
-
-/*!
- \fn QSizePolicy::QSizePolicy(Policy horizontal, Policy vertical)
-
- Constructs a QSizePolicy object with the given \a horizontal and
- \a vertical policies, and DefaultType as the control type.
-
- Use setHeightForWidth() if the preferred height of the widget is
- dependent on the width of the widget (for example, a QLabel with
- line wrapping).
-
- \sa setHorizontalStretch(), setVerticalStretch()
-*/
-
-/*!
- \fn QSizePolicy::QSizePolicy(Policy horizontal, Policy vertical, ControlType type)
- \since 4.3
-
- Constructs a QSizePolicy object with the given \a horizontal and
- \a vertical policies, and the specified control \a type.
-
- Use setHeightForWidth() if the preferred height of the widget is
- dependent on the width of the widget (for example, a QLabel with
- line wrapping).
-
- \sa setHorizontalStretch(), setVerticalStretch(), controlType()
-*/
-
-/*!
- \fn QSizePolicy::Policy QSizePolicy::horizontalPolicy() const
-
- Returns the horizontal component of the size policy.
-
- \sa setHorizontalPolicy(), verticalPolicy(), horizontalStretch()
-*/
-
-/*!
- \fn QSizePolicy::Policy QSizePolicy::verticalPolicy() const
-
- Returns the vertical component of the size policy.
-
- \sa setVerticalPolicy(), horizontalPolicy(), verticalStretch()
-*/
-
-/*!
- \fn void QSizePolicy::setHorizontalPolicy(Policy policy)
-
- Sets the horizontal component to the given \a policy.
-
- \sa horizontalPolicy(), setVerticalPolicy(), setHorizontalStretch()
-*/
-
-/*!
- \fn void QSizePolicy::setVerticalPolicy(Policy policy)
-
- Sets the vertical component to the given \a policy.
-
- \sa verticalPolicy(), setHorizontalPolicy(), setVerticalStretch()
-*/
-
-/*!
- \fn Qt::Orientations QSizePolicy::expandingDirections() const
-
- Returns whether a widget can make use of more space than the
- QWidget::sizeHint() function indicates.
-
- A value of Qt::Horizontal or Qt::Vertical means that the widget
- can grow horizontally or vertically (i.e., the horizontal or
- vertical policy is \l Expanding or \l MinimumExpanding), whereas
- Qt::Horizontal | Qt::Vertical means that it can grow in both
- dimensions.
-
- \sa horizontalPolicy(), verticalPolicy()
-*/
-
-/*!
- \fn ControlType QSizePolicy::controlType() const
- \since 4.3
-
- Returns the control type associated with the widget for which
- this size policy applies.
-*/
-
-/*!
- \fn void QSizePolicy::setControlType(ControlType type)
- \since 4.3
-
- Sets the control type associated with the widget for which this
- size policy applies to \a type.
-
- The control type specifies the type of the widget for which this
- size policy applies. It is used by some styles, notably
- QMacStyle, to insert proper spacing between widgets. For example,
- the Mac OS X Aqua guidelines specify that push buttons should be
- separated by 12 pixels, whereas vertically stacked radio buttons
- only require 6 pixels.
-
- \sa QStyle::layoutSpacing()
-*/
-
-/*!
- \fn void QSizePolicy::setHeightForWidth(bool dependent)
-
- Sets the flag determining whether the widget's preferred height
- depends on its width, to \a dependent.
-
- \sa hasHeightForWidth(), setWidthForHeight()
-*/
-
-/*!
- \fn bool QSizePolicy::hasHeightForWidth() const
-
- Returns true if the widget's preferred height depends on its
- width; otherwise returns false.
-
- \sa setHeightForWidth()
-*/
-
-/*!
- \fn void QSizePolicy::setWidthForHeight(bool dependent)
-
- Sets the flag determining whether the widget's width
- depends on its height, to \a dependent.
-
- This is only supported for QGraphicsLayout's subclasses.
- It is not possible to have a layout with both height-for-width
- and width-for-height constraints at the same time.
-
- \sa hasWidthForHeight(), setHeightForWidth()
-*/
-
-/*!
- \fn bool QSizePolicy::hasWidthForHeight() const
-
- Returns true if the widget's width depends on its
- height; otherwise returns false.
-
- \sa setWidthForHeight()
-*/
-
-/*!
- \fn bool QSizePolicy::operator==(const QSizePolicy &other) const
-
- Returns true if this policy is equal to \a other; otherwise
- returns false.
-
- \sa operator!=()
-*/
-
-/*!
- \fn bool QSizePolicy::operator!=(const QSizePolicy &other) const
-
- Returns true if this policy is different from \a other; otherwise
- returns false.
-
- \sa operator==()
-*/
-
-/*!
- \fn int QSizePolicy::horizontalStretch() const
-
- Returns the horizontal stretch factor of the size policy.
-
- \sa setHorizontalStretch(), verticalStretch(), horizontalPolicy()
-*/
-
-/*!
- \fn int QSizePolicy::verticalStretch() const
-
- Returns the vertical stretch factor of the size policy.
-
- \sa setVerticalStretch(), horizontalStretch(), verticalPolicy()
-*/
-
-/*!
- \fn void QSizePolicy::setHorizontalStretch(uchar stretchFactor)
-
- Sets the horizontal stretch factor of the size policy to the given \a
- stretchFactor.
-
- \sa horizontalStretch(), setVerticalStretch(), setHorizontalPolicy()
-*/
-
-/*!
- \fn void QSizePolicy::setVerticalStretch(uchar stretchFactor)
-
- Sets the vertical stretch factor of the size policy to the given
- \a stretchFactor.
-
- \sa verticalStretch(), setHorizontalStretch(), setVerticalPolicy()
-*/
-
-/*!
- \fn void QSizePolicy::transpose()
-
- Swaps the horizontal and vertical policies and stretches.
-*/
-
-/*!
- \enum QSizePolicy::ControlType
- \since 4.3
-
- This enum specifies the different types of widgets in terms of
- layout interaction:
-
- \value DefaultType The default type, when none is specified.
- \value ButtonBox A QDialogButtonBox instance.
- \value CheckBox A QCheckBox instance.
- \value ComboBox A QComboBox instance.
- \value Frame A QFrame instance.
- \value GroupBox A QGroupBox instance.
- \value Label A QLabel instance.
- \value Line A QFrame instance with QFrame::HLine or QFrame::VLine.
- \value LineEdit A QLineEdit instance.
- \value PushButton A QPushButton instance.
- \value RadioButton A QRadioButton instance.
- \value Slider A QAbstractSlider instance.
- \value SpinBox A QAbstractSpinBox instance.
- \value TabWidget A QTabWidget instance.
- \value ToolButton A QToolButton instance.
-
- \sa setControlType(), controlType()
-*/
-
-#ifdef QT3_SUPPORT
-/*!
- \typedef QSizePolicy::SizeType
- \compat
-
- Use the QSizePolicy::Policy enum instead.
-*/
-
-/*!
- \enum QSizePolicy::ExpandData
- \compat
-
- Use the Qt::Orientations enum instead.
-
- \value NoDirection Use 0 instead.
- \value Horizontally Use Qt::Horizontal instead.
- \value Vertically Use Qt::Vertical instead.
- \value BothDirections Use Qt::Horizontal | Qt::Vertical instead.
-*/
-
-/*!
- \fn bool QSizePolicy::mayShrinkHorizontally() const
-
- Use the horizontalPolicy() function combined with the
- QSizePolicy::PolicyFlag enum instead.
-
- \oldcode
- bool policy = mayShrinkHorizontally();
- \newcode
- bool policy = horizontalPolicy() & QSizePolicy::ShrinkFlag;
- \endcode
-*/
-
-/*!
- \fn bool QSizePolicy::mayShrinkVertically() const
-
- Use the verticalPolicy() function combined with the
- QSizePolicy::PolicyFlag enum instead.
-
- \oldcode
- bool policy = mayShrinkVertically();
- \newcode
- bool policy = verticalPolicy() & QSizePolicy::ShrinkFlag;
- \endcode
-*/
-
-/*!
- \fn bool QSizePolicy::mayGrowHorizontally() const
-
- Use the horizontalPolicy() function combined with the
- QSizePolicy::PolicyFlag enum instead.
-
- \oldcode
- bool policy = mayGrowHorizontally();
- \newcode
- bool policy = horizontalPolicy() & QSizePolicy::GrowFlag;
- \endcode
-*/
-
-/*!
- \fn bool QSizePolicy::mayGrowVertically() const
-
- Use the verticalPolicy() function combined with the
- QSizePolicy::PolicyFlag enum instead.
-
- \oldcode
- bool policy = mayGrowVertically();
- \newcode
- bool policy = verticalPolicy() & QSizePolicy::GrowFlag;
- \endcode
-*/
-
-/*!
- \fn Qt::QSizePolicy::Orientations QSizePolicy::expanding() const
-
- Use expandingDirections() instead.
-*/
-
-/*!
- \fn QSizePolicy::QSizePolicy(Policy horizontal, Policy vertical, bool dependent)
-
- Use the QSizePolicy() constructor and the setHeightForWidth()
- function instead.
-
- \oldcode
- QSizePolicy *policy = new QSizePolicy(horizontal, vertical, dependent);
- \newcode
- QSizePolicy *policy = new QSizePolicy(horizontal, vertical);
- policy->setHeightForWidth(dependent);
- \endcode
-*/
-
-/*!
- \fn QSizePolicy::QSizePolicy(Policy horizontal, Policy vertical, uchar horizontalStretch,
- uchar verticalStretch, bool dependent)
-
- Use the QSizePolicy() constructor and call the
- setHorizontalStretch(), setVerticalStretch(), and
- setHeightForWidth() functions instead.
-
- \oldcode
- QSizePolicy *policy = new QSizePolicy(horizontal, vertical,
- horizontalStretch, verticalStretch,
- dependent);
- \newcode
- QSizePolicy *policy = new QSizePolicy(horizontal, vertical);
- policy->setHorizontalStretch(horizontalStretch);
- policy->setVerticalStretch(verticalStretch);
- policy->setHeightForWidth(dependent);
- \endcode
-*/
-
-/*!
- \fn QSizePolicy::Policy QSizePolicy::horData() const
-
- Use horizontalPolicy() instead.
-*/
-
-/*!
- \fn QSizePolicy::Policy QSizePolicy::verData() const
-
- Use verticalPolicy() instead.
-*/
-
-/*!
- \fn void QSizePolicy::setHorData(Policy policy)
-
- Use setHorizontalPolicy() instead.
-*/
-
-/*!
- \fn void QSizePolicy::setVerData(Policy policy)
-
- Use setVerticalPolicy() instead.
-*/
-
-/*!
- \fn uint QSizePolicy::horStretch() const
-
- Use horizontalStretch() instead.
-*/
-
-/*!
- \fn uint QSizePolicy::verStretch() const
-
- Use verticalStretch() instead.
-*/
-
-/*!
- \fn void QSizePolicy::setHorStretch(uchar stretch)
-
- Use setHorizontalStretch() instead.
-*/
-
-/*!
- \fn void QSizePolicy::setVerStretch(uchar stretch)
-
- Use setVerticalStretch() instead.
-*/
-#endif
diff --git a/src/gui/kernel/qsoftkeymanager.cpp b/src/gui/kernel/qsoftkeymanager.cpp
deleted file mode 100644
index 204efe9ee9..0000000000
--- a/src/gui/kernel/qsoftkeymanager.cpp
+++ /dev/null
@@ -1,319 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qevent.h"
-#include "qbitmap.h"
-#include "private/qsoftkeymanager_p.h"
-#include "private/qaction_p.h"
-#include "private/qsoftkeymanager_common_p.h"
-
-#ifdef Q_WS_S60
-#include "private/qsoftkeymanager_s60_p.h"
-#endif
-
-#ifdef SYMBIAN_VERSION_SYMBIAN3
-#include "private/qt_s60_p.h"
-#endif
-
-#ifndef QT_NO_SOFTKEYMANAGER
-QT_BEGIN_NAMESPACE
-
-QSoftKeyManager *QSoftKeyManagerPrivate::self = 0;
-
-QString QSoftKeyManager::standardSoftKeyText(StandardSoftKey standardKey)
-{
- QString softKeyText;
- switch (standardKey) {
- case OkSoftKey:
- softKeyText = QSoftKeyManager::tr("Ok");
- break;
- case SelectSoftKey:
- softKeyText = QSoftKeyManager::tr("Select");
- break;
- case DoneSoftKey:
- softKeyText = QSoftKeyManager::tr("Done");
- break;
- case MenuSoftKey:
- softKeyText = QSoftKeyManager::tr("Options");
- break;
- case CancelSoftKey:
- softKeyText = QSoftKeyManager::tr("Cancel");
- break;
- default:
- break;
- };
-
- return softKeyText;
-}
-
-QSoftKeyManager *QSoftKeyManager::instance()
-{
- if (!QSoftKeyManagerPrivate::self)
- QSoftKeyManagerPrivate::self = new QSoftKeyManager;
-
- return QSoftKeyManagerPrivate::self;
-}
-
-QSoftKeyManager::QSoftKeyManager() :
-#ifdef Q_WS_S60
- QObject(*(new QSoftKeyManagerPrivateS60), 0)
-#else
- QObject(*(new QSoftKeyManagerPrivate), 0)
-#endif
-{
-}
-
-QAction *QSoftKeyManager::createAction(StandardSoftKey standardKey, QWidget *actionWidget)
-{
- QAction *action = new QAction(standardSoftKeyText(standardKey), actionWidget);
-#ifdef SYMBIAN_VERSION_SYMBIAN3
- int key = 0;
- switch (standardKey) {
- case OkSoftKey:
- key = EAknSoftkeyOk;
- break;
- case SelectSoftKey:
- key = EAknSoftkeySelect;
- break;
- case DoneSoftKey:
- key = EAknSoftkeyDone;
- break;
- case MenuSoftKey:
- key = EAknSoftkeyOptions;
- break;
- case CancelSoftKey:
- key = EAknSoftkeyCancel;
- break;
- default:
- break;
- };
- if (key != 0)
- QSoftKeyManager::instance()->d_func()->softKeyCommandActions.insert(action, key);
-#endif
- QAction::SoftKeyRole softKeyRole = QAction::NoSoftKey;
- switch (standardKey) {
- case MenuSoftKey: // FALL-THROUGH
- QActionPrivate::get(action)->menuActionSoftkeys = true;
- case OkSoftKey:
- case SelectSoftKey:
- case DoneSoftKey:
- softKeyRole = QAction::PositiveSoftKey;
- break;
- case CancelSoftKey:
- softKeyRole = QAction::NegativeSoftKey;
- break;
- }
- action->setSoftKeyRole(softKeyRole);
- action->setVisible(false);
- setForceEnabledInSoftkeys(action);
- return action;
-}
-
-/*! \internal
-
- Creates a QAction and registers the 'triggered' signal to send the given key event to
- \a actionWidget as a convenience.
-
-*/
-QAction *QSoftKeyManager::createKeyedAction(StandardSoftKey standardKey, Qt::Key key, QWidget *actionWidget)
-{
-#ifndef QT_NO_ACTION
- QScopedPointer<QAction> action(createAction(standardKey, actionWidget));
-
- connect(action.data(), SIGNAL(triggered()), QSoftKeyManager::instance(), SLOT(sendKeyEvent()));
- connect(action.data(), SIGNAL(destroyed(QObject*)), QSoftKeyManager::instance(), SLOT(cleanupHash(QObject*)));
- QSoftKeyManager::instance()->d_func()->keyedActions.insert(action.data(), key);
- return action.take();
-#endif //QT_NO_ACTION
-}
-
-void QSoftKeyManager::cleanupHash(QObject *obj)
-{
- Q_D(QSoftKeyManager);
- QAction *action = qobject_cast<QAction*>(obj);
- d->keyedActions.remove(action);
-#ifdef SYMBIAN_VERSION_SYMBIAN3
- d->softKeyCommandActions.remove(action);
-#endif
-}
-
-void QSoftKeyManager::sendKeyEvent()
-{
- Q_D(QSoftKeyManager);
- QAction *action = qobject_cast<QAction*>(sender());
-
- if (!action)
- return;
-
- Qt::Key keyToSend = d->keyedActions.value(action, Qt::Key_unknown);
-
- if (keyToSend != Qt::Key_unknown)
- QApplication::postEvent(action->parentWidget(),
- new QKeyEvent(QEvent::KeyPress, keyToSend, Qt::NoModifier));
-}
-
-void QSoftKeyManager::updateSoftKeys()
-{
- QSoftKeyManager::instance()->d_func()->pendingUpdate = true;
- QEvent *event = new QEvent(QEvent::UpdateSoftKeys);
- QApplication::postEvent(QSoftKeyManager::instance(), event);
-}
-
-bool QSoftKeyManager::appendSoftkeys(const QWidget &source, int level)
-{
- Q_D(QSoftKeyManager);
- bool ret = false;
- foreach(QAction *action, source.actions()) {
- if (action->softKeyRole() != QAction::NoSoftKey
- && (action->isVisible() || isForceEnabledInSofkeys(action))) {
- d->requestedSoftKeyActions.insert(level, action);
- ret = true;
- }
- }
- return ret;
-}
-
-
-static bool isChildOf(const QWidget *c, const QWidget *p)
-{
- while (c) {
- if (c == p)
- return true;
- c = c->parentWidget();
- }
- return false;
-}
-
-QWidget *QSoftKeyManager::softkeySource(QWidget *previousSource, bool& recursiveMerging)
-{
- Q_D(QSoftKeyManager);
- QWidget *source = NULL;
- if (!previousSource) {
- // Initial source is primarily focuswidget and secondarily activeWindow
- QWidget *focus = QApplication::focusWidget();
- QWidget *popup = QApplication::activePopupWidget();
- if (popup) {
- if (isChildOf(focus, popup))
- source = focus;
- else
- source = popup;
- }
- if (!source) {
- QWidget *modal = QApplication::activeModalWidget();
- if (modal) {
- if (isChildOf(focus, modal))
- source = focus;
- else
- source = modal;
- }
- }
- if (!source) {
- source = focus;
- if (!source)
- source = QApplication::activeWindow();
- }
- } else {
- // Softkey merging is based on four criterias
- // 1. Implicit merging is used whenever focus widget does not specify any softkeys
- bool implicitMerging = d->requestedSoftKeyActions.isEmpty();
- // 2. Explicit merging with parent is used whenever WA_MergeSoftkeys widget attribute is set
- bool explicitMerging = previousSource->testAttribute(Qt::WA_MergeSoftkeys);
- // 3. Explicit merging with all parents
- recursiveMerging |= previousSource->testAttribute(Qt::WA_MergeSoftkeysRecursively);
- // 4. Implicit and explicit merging always stops at window boundary
- bool merging = (implicitMerging || explicitMerging || recursiveMerging) && !previousSource->isWindow();
-
- source = merging ? previousSource->parentWidget() : NULL;
- }
- return source;
-}
-
-bool QSoftKeyManager::handleUpdateSoftKeys()
-{
- Q_D(QSoftKeyManager);
- int level = 0;
- d->requestedSoftKeyActions.clear();
- bool recursiveMerging = false;
- QWidget *source = softkeySource(NULL, recursiveMerging);
- d->initialSoftKeySource = source;
- while (source) {
- if (appendSoftkeys(*source, level))
- ++level;
- source = softkeySource(source, recursiveMerging);
- }
-
- d->updateSoftKeys_sys();
- d->pendingUpdate = false;
- return true;
-}
-
-void QSoftKeyManager::setForceEnabledInSoftkeys(QAction *action)
-{
- QActionPrivate::get(action)->forceEnabledInSoftkeys = true;
-}
-
-bool QSoftKeyManager::isForceEnabledInSofkeys(QAction *action)
-{
- return QActionPrivate::get(action)->forceEnabledInSoftkeys;
-}
-
-bool QSoftKeyManager::event(QEvent *e)
-{
-#ifndef QT_NO_ACTION
- if (e->type() == QEvent::UpdateSoftKeys)
- return handleUpdateSoftKeys();
-#endif //QT_NO_ACTION
- return false;
-}
-
-#ifdef Q_WS_S60
-bool QSoftKeyManager::handleCommand(int command)
-{
- if (QSoftKeyManager::instance()->d_func()->pendingUpdate)
- (void)QSoftKeyManager::instance()->handleUpdateSoftKeys();
-
- return static_cast<QSoftKeyManagerPrivateS60*>(QSoftKeyManager::instance()->d_func())->handleCommand(command);
-}
-#endif
-
-QT_END_NAMESPACE
-#endif //QT_NO_SOFTKEYMANAGER
diff --git a/src/gui/kernel/qsoftkeymanager_common_p.h b/src/gui/kernel/qsoftkeymanager_common_p.h
deleted file mode 100644
index 02ae697eef..0000000000
--- a/src/gui/kernel/qsoftkeymanager_common_p.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** 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 QSOFTKEYMANAGER_COMMON_P_H
-#define QSOFTKEYMANAGER_COMMON_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_HEADER
-
-#ifndef QT_NO_SOFTKEYMANAGER
-
-QT_BEGIN_NAMESPACE
-
-class QSoftKeyManagerPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QSoftKeyManager)
-
-public:
- virtual void updateSoftKeys_sys() {};
-
-protected:
- static QSoftKeyManager *self;
- QHash<QAction*, Qt::Key> keyedActions;
- QMultiHash<int, QAction*> requestedSoftKeyActions;
- QWidget *initialSoftKeySource;
- bool pendingUpdate;
-#ifdef SYMBIAN_VERSION_SYMBIAN3
- QHash<QAction*, int> softKeyCommandActions;
-#endif
-};
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_SOFTKEYMANAGER
-
-QT_END_HEADER
-
-#endif // QSOFTKEYMANAGER_COMMON_P_H
diff --git a/src/gui/kernel/qsoftkeymanager_p.h b/src/gui/kernel/qsoftkeymanager_p.h
deleted file mode 100644
index 78999a97bd..0000000000
--- a/src/gui/kernel/qsoftkeymanager_p.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** 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 QSOFTKEYMANAGER_P_H
-#define QSOFTKEYMANAGER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qobject.h>
-#include "QtGui/qaction.h"
-
-QT_BEGIN_HEADER
-
-#ifndef QT_NO_SOFTKEYMANAGER
-QT_BEGIN_NAMESPACE
-
-class QSoftKeyManagerPrivate;
-
-class Q_AUTOTEST_EXPORT QSoftKeyManager : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QSoftKeyManager)
-
-public:
-
- enum StandardSoftKey {
- OkSoftKey,
- SelectSoftKey,
- DoneSoftKey,
- MenuSoftKey,
- CancelSoftKey
- };
-
- static void updateSoftKeys();
-#ifdef Q_WS_S60
- static bool handleCommand(int);
-#endif
-
- static QAction *createAction(StandardSoftKey standardKey, QWidget *actionWidget);
- static QAction *createKeyedAction(StandardSoftKey standardKey, Qt::Key key, QWidget *actionWidget);
- static QString standardSoftKeyText(StandardSoftKey standardKey);
- static void setForceEnabledInSoftkeys(QAction *action);
- static bool isForceEnabledInSofkeys(QAction *action);
-
-protected:
- bool event(QEvent *e);
-
-private:
- QSoftKeyManager();
- static QSoftKeyManager *instance();
- bool appendSoftkeys(const QWidget &source, int level);
- QWidget *softkeySource(QWidget *previousSource, bool& recursiveMerging);
- bool handleUpdateSoftKeys();
-
-private Q_SLOTS:
- void cleanupHash(QObject* obj);
- void sendKeyEvent();
-
-private:
- Q_DISABLE_COPY(QSoftKeyManager)
-};
-
-QT_END_NAMESPACE
-#endif //QT_NO_SOFTKEYMANAGER
-
-QT_END_HEADER
-
-#endif //QSOFTKEYMANAGER_P_H
diff --git a/src/gui/kernel/qsound.cpp b/src/gui/kernel/qsound.cpp
deleted file mode 100644
index 55a98758c3..0000000000
--- a/src/gui/kernel/qsound.cpp
+++ /dev/null
@@ -1,367 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsound.h"
-
-#ifndef QT_NO_SOUND
-
-#include "qlist.h"
-#include <private/qobject_p.h>
-#include "qsound_p.h"
-
-QT_BEGIN_NAMESPACE
-
-static QList<QAuServer*> *servers=0;
-
-QAuServer::QAuServer(QObject* parent)
- : QObject(parent)
-{
- if (!servers)
- servers = new QList<QAuServer*>;
- servers->prepend(this);
-}
-
-QAuServer::~QAuServer()
-{
- servers->removeAll(this);
- if (servers->count() == 0) {
- delete servers;
- servers = 0;
- }
-}
-
-void QAuServer::play(const QString& filename)
-{
- QSound s(filename);
- play(&s);
-}
-
-extern QAuServer* qt_new_audio_server();
-
-static QAuServer& server()
-{
- if (!servers) qt_new_audio_server();
- return *servers->first();
-}
-
-class QSoundPrivate : public QObjectPrivate
-{
-public:
- QSoundPrivate(const QString& fname)
- : filename(fname), bucket(0), looprem(0), looptotal(1)
- {
- }
-
- ~QSoundPrivate()
- {
- delete bucket;
- }
-
- QString filename;
- QAuBucket* bucket;
- int looprem;
- int looptotal;
-};
-
-/*!
- \class QSound
- \brief The QSound class provides access to the platform audio facilities.
-
- \ingroup multimedia
-
-
- Qt provides the most commonly required audio operation in GUI
- applications: asynchronously playing a sound file. This is most
- easily accomplished using the static play() function:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qsound.cpp 0
-
- Alternatively, create a QSound object from the sound file first
- and then call the play() slot:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qsound.cpp 1
-
- Once created a QSound object can be queried for its fileName() and
- total number of loops() (i.e. the number of times the sound will
- play). The number of repetitions can be altered using the
- setLoops() function. While playing the sound, the loopsRemaining()
- function returns the remaining number of repetitions. Use the
- isFinished() function to determine whether the sound has finished
- playing.
-
- Sounds played using a QSound object may use more memory than the
- static play() function, but it may also play more immediately
- (depending on the underlying platform audio facilities). Use the
- static isAvailable() function to determine whether sound
- facilities exist on the platform. Which facilities that are
- actually used varies:
-
- \table
- \header \o Platform \o Audio Facility
- \row
- \o Microsoft Windows
- \o The underlying multimedia system is used; only WAVE format sound files
- are supported.
- \row
- \o X11
- \o The \l{ftp://ftp.x.org/contrib/audio/nas/}{Network Audio System}
- is used if available, otherwise all operations work silently. NAS
- supports WAVE and AU files.
- \row
- \o Mac OS X
- \o NSSound is used. All formats that NSSound supports, including QuickTime formats,
- are supported by Qt for Mac OS X.
- \row
- \o Qt for Embedded Linux
- \o A built-in mixing sound server is used, accessing \c /dev/dsp
- directly. Only the WAVE format is supported.
- \row
- \o Symbian
- \o CMdaAudioPlayerUtility is used. All formats that Symbian OS or devices support
- are supported also by Qt.
- \endtable
-
- Note that QSound does not support \l{resources.html}{resources}.
- This might be fixed in a future Qt version.
-*/
-
-/*!
- Plays the sound stored in the file specified by the given \a filename.
-
- \sa stop(), loopsRemaining(), isFinished()
-*/
-void QSound::play(const QString& filename)
-{
- server().play(filename);
-}
-
-/*!
- Constructs a QSound object from the file specified by the given \a
- filename and with the given \a parent.
-
- This may use more memory than the static play() function, but it
- may also play more immediately (depending on the underlying
- platform audio facilities).
-
- \sa play()
-*/
-QSound::QSound(const QString& filename, QObject* parent)
- : QObject(*new QSoundPrivate(filename), parent)
-{
- server().init(this);
-}
-
-/*!
- Destroys this sound object. If the sound is not finished playing,
- the stop() function is called before the sound object is
- destructed.
-
- \sa stop(), isFinished()
-*/
-QSound::~QSound()
-{
- if (!isFinished())
- stop();
-}
-
-/*!
- Returns true if the sound has finished playing; otherwise returns false.
-
- \warning On Windows this function always returns true for unlooped sounds.
-*/
-bool QSound::isFinished() const
-{
- Q_D(const QSound);
- return d->looprem == 0;
-}
-
-/*!
- \overload
-
- Starts playing the sound specified by this QSound object.
-
- The function returns immediately. Depending on the platform audio
- facilities, other sounds may stop or be mixed with the new
- sound. The sound can be played again at any time, possibly mixing
- or replacing previous plays of the sound.
-
- \sa fileName()
-*/
-void QSound::play()
-{
- Q_D(QSound);
- d->looprem = d->looptotal;
- server().play(this);
-}
-
-/*!
- Returns the number of times the sound will play.
-
- \sa loopsRemaining(), setLoops()
-*/
-int QSound::loops() const
-{
- Q_D(const QSound);
- return d->looptotal;
-}
-
-/*!
- Returns the remaining number of times the sound will loop (this
- value decreases each time the sound is played).
-
- \sa loops(), isFinished()
-*/
-int QSound::loopsRemaining() const
-{
- Q_D(const QSound);
- return d->looprem;
-}
-
-/*!
- \fn void QSound::setLoops(int number)
-
- Sets the sound to repeat the given \a number of times when it is
- played.
-
- Note that passing the value -1 will cause the sound to loop
- indefinitely.
-
- \sa loops()
-*/
-void QSound::setLoops(int n)
-{
- Q_D(QSound);
- d->looptotal = n;
-}
-
-/*!
- Returns the filename associated with this QSound object.
-
- \sa QSound()
-*/
-QString QSound::fileName() const
-{
- Q_D(const QSound);
- return d->filename;
-}
-
-/*!
- Stops the sound playing.
-
- Note that on Windows the current loop will finish if a sound is
- played in a loop.
-
- \sa play()
-*/
-void QSound::stop()
-{
- Q_D(QSound);
- server().stop(this);
- d->looprem = 0;
-}
-
-
-/*!
- Returns true if sound facilities exist on the platform; otherwise
- returns false.
-
- If no sound is available, all QSound operations work silently and
- quickly. An application may choose either to notify the user if
- sound is crucial to the application or to operate silently without
- bothering the user.
-
- Note: On Windows this always returns true because some sound card
- drivers do not implement a way to find out whether it is available
- or not.
-*/
-bool QSound::isAvailable()
-{
- return server().okay();
-}
-
-/*!
- Sets the internal bucket record of sound \a s to \a b, deleting
- any previous setting.
-*/
-void QAuServer::setBucket(QSound* s, QAuBucket* b)
-{
- delete s->d_func()->bucket;
- s->d_func()->bucket = b;
-}
-
-/*!
- Returns the internal bucket record of sound \a s.
-*/
-QAuBucket* QAuServer::bucket(QSound* s)
-{
- return s->d_func()->bucket;
-}
-
-/*!
- Decrements the QSound::loopRemaining() value for sound \a s,
- returning the result.
-*/
-int QAuServer::decLoop(QSound* s)
-{
- if (s->d_func()->looprem > 0)
- --s->d_func()->looprem;
- return s->d_func()->looprem;
-}
-
-/*!
- Initializes the sound. The default implementation does nothing.
-*/
-void QAuServer::init(QSound*)
-{
-}
-
-QAuBucket::~QAuBucket()
-{
-}
-/*!
- \fn bool QSound::available()
-
- Use the isAvailable() function instead.
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SOUND
diff --git a/src/gui/kernel/qsound.h b/src/gui/kernel/qsound.h
deleted file mode 100644
index a0d058011a..0000000000
--- a/src/gui/kernel/qsound.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/****************************************************************************
-**
-** 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 QSOUND_H
-#define QSOUND_H
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SOUND
-
-class QSoundPrivate;
-
-class Q_GUI_EXPORT QSound : public QObject
-{
- Q_OBJECT
-
-public:
- static bool isAvailable();
- static void play(const QString& filename);
-
- explicit QSound(const QString& filename, QObject* parent = 0);
- ~QSound();
-
- int loops() const;
- int loopsRemaining() const;
- void setLoops(int);
- QString fileName() const;
-
- bool isFinished() const;
-
-public Q_SLOTS:
- void play();
- void stop();
-
-private:
- Q_DECLARE_PRIVATE(QSound)
- friend class QAuServer;
-};
-
-#endif // QT_NO_SOUND
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSOUND_H
diff --git a/src/gui/kernel/qsound_p.h b/src/gui/kernel/qsound_p.h
deleted file mode 100644
index dfdbfff063..0000000000
--- a/src/gui/kernel/qsound_p.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************************
-**
-** 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 QSOUND_P_H
-#define QSOUND_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 "QtCore/qobject.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_SOUND
-
-class QSound;
-/*
- QAuServer is an INTERNAL class. If you wish to provide support for
- additional audio servers, you can make a subclass of QAuServer to do
- so, HOWEVER, your class may need to be re-engineered to some degree
- with each new Qt release, including minor releases.
-
- QAuBucket is whatever you want.
-*/
-
-class QAuBucket {
-public:
- virtual ~QAuBucket();
-};
-
-class QAuServer : public QObject {
- Q_OBJECT
-
-public:
- explicit QAuServer(QObject* parent);
- ~QAuServer();
-
- virtual void init(QSound*);
- virtual void play(const QString& filename);
- virtual void play(QSound*)=0;
- virtual void stop(QSound*)=0;
- virtual bool okay()=0;
-
-protected:
- void setBucket(QSound*, QAuBucket*);
- QAuBucket* bucket(QSound*);
- int decLoop(QSound*);
-};
-
-#endif // QT_NO_SOUND
-
-QT_END_NAMESPACE
-
-#endif // QSOUND_P_H
diff --git a/src/gui/kernel/qstackedlayout.cpp b/src/gui/kernel/qstackedlayout.cpp
deleted file mode 100644
index c5ce238958..0000000000
--- a/src/gui/kernel/qstackedlayout.cpp
+++ /dev/null
@@ -1,543 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstackedlayout.h"
-#include "qlayout_p.h"
-
-#include <qlist.h>
-#include <qwidget.h>
-#include "private/qlayoutengine_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QStackedLayoutPrivate : public QLayoutPrivate
-{
- Q_DECLARE_PUBLIC(QStackedLayout)
-public:
- QStackedLayoutPrivate() : index(-1), stackingMode(QStackedLayout::StackOne) {}
- QList<QLayoutItem *> list;
- int index;
- QStackedLayout::StackingMode stackingMode;
-};
-
-/*!
- \class QStackedLayout
-
- \brief The QStackedLayout class provides a stack of widgets where
- only one widget is visible at a time.
-
- \ingroup geomanagement
-
- QStackedLayout can be used to create a user interface similar to
- the one provided by QTabWidget. There is also a convenience
- QStackedWidget class built on top of QStackedLayout.
-
- A QStackedLayout can be populated with a number of child widgets
- ("pages"). For example:
-
- \snippet doc/src/snippets/qstackedlayout/main.cpp 0
- \codeline
- \snippet doc/src/snippets/qstackedlayout/main.cpp 2
- \snippet doc/src/snippets/qstackedlayout/main.cpp 3
-
- QStackedLayout provides no intrinsic means for the user to switch
- page. This is typically done through a QComboBox or a QListWidget
- that stores the titles of the QStackedLayout's pages. For
- example:
-
- \snippet doc/src/snippets/qstackedlayout/main.cpp 1
-
- When populating a layout, the widgets are added to an internal
- list. The indexOf() function returns the index of a widget in that
- list. The widgets can either be added to the end of the list using
- the addWidget() function, or inserted at a given index using the
- insertWidget() function. The removeWidget() function removes the
- widget at the given index from the layout. The number of widgets
- contained in the layout, can be obtained using the count()
- function.
-
- The widget() function returns the widget at a given index
- position. The index of the widget that is shown on screen is given
- by currentIndex() and can be changed using setCurrentIndex(). In a
- similar manner, the currently shown widget can be retrieved using
- the currentWidget() function, and altered using the
- setCurrentWidget() function.
-
- Whenever the current widget in the layout changes or a widget is
- removed from the layout, the currentChanged() and widgetRemoved()
- signals are emitted respectively.
-
- \sa QStackedWidget, QTabWidget
-*/
-
-/*!
- \fn void QStackedLayout::currentChanged(int index)
-
- This signal is emitted whenever the current widget in the layout
- changes. The \a index specifies the index of the new current
- widget, or -1 if there isn't a new one (for example, if there
- are no widgets in the QStackedLayout)
-
- \sa currentWidget(), setCurrentWidget()
-*/
-
-/*!
- \fn void QStackedLayout::widgetRemoved(int index)
-
- This signal is emitted whenever a widget is removed from the
- layout. The widget's \a index is passed as parameter.
-
- \sa removeWidget()
-*/
-
-/*!
- \fn QWidget *QStackedLayout::widget()
- \internal
-*/
-
-/*!
- Constructs a QStackedLayout with no parent.
-
- This QStackedLayout must be installed on a widget later on to
- become effective.
-
- \sa addWidget(), insertWidget()
-*/
-QStackedLayout::QStackedLayout()
- : QLayout(*new QStackedLayoutPrivate, 0, 0)
-{
-}
-
-/*!
- Constructs a new QStackedLayout with the given \a parent.
-
- This layout will install itself on the \a parent widget and
- manage the geometry of its children.
-*/
-QStackedLayout::QStackedLayout(QWidget *parent)
- : QLayout(*new QStackedLayoutPrivate, 0, parent)
-{
-}
-
-/*!
- Constructs a new QStackedLayout and inserts it into
- the given \a parentLayout.
-*/
-QStackedLayout::QStackedLayout(QLayout *parentLayout)
- : QLayout(*new QStackedLayoutPrivate, parentLayout, 0)
-{
-}
-
-/*!
- Destroys this QStackedLayout. Note that the layout's widgets are
- \e not destroyed.
-*/
-QStackedLayout::~QStackedLayout()
-{
- Q_D(QStackedLayout);
- qDeleteAll(d->list);
-}
-
-/*!
- Adds the given \a widget to the end of this layout and returns the
- index position of the \a widget.
-
- If the QStackedLayout is empty before this function is called,
- the given \a widget becomes the current widget.
-
- \sa insertWidget(), removeWidget(), setCurrentWidget()
-*/
-int QStackedLayout::addWidget(QWidget *widget)
-{
- Q_D(QStackedLayout);
- return insertWidget(d->list.count(), widget);
-}
-
-/*!
- Inserts the given \a widget at the given \a index in this
- QStackedLayout. If \a index is out of range, the widget is
- appended (in which case it is the actual index of the \a widget
- that is returned).
-
- If the QStackedLayout is empty before this function is called, the
- given \a widget becomes the current widget.
-
- Inserting a new widget at an index less than or equal to the current index
- will increment the current index, but keep the current widget.
-
- \sa addWidget(), removeWidget(), setCurrentWidget()
-*/
-int QStackedLayout::insertWidget(int index, QWidget *widget)
-{
- Q_D(QStackedLayout);
- addChildWidget(widget);
- index = qMin(index, d->list.count());
- if (index < 0)
- index = d->list.count();
- QWidgetItem *wi = QLayoutPrivate::createWidgetItem(this, widget);
- d->list.insert(index, wi);
- invalidate();
- if (d->index < 0) {
- setCurrentIndex(index);
- } else {
- if (index <= d->index)
- ++d->index;
- if (d->stackingMode == StackOne)
- widget->hide();
- widget->lower();
- }
- return index;
-}
-
-/*!
- \reimp
-*/
-QLayoutItem *QStackedLayout::itemAt(int index) const
-{
- Q_D(const QStackedLayout);
- return d->list.value(index);
-}
-
-// Code that enables proper handling of the case that takeAt() is
-// called somewhere inside QObject destructor (can't call hide()
-// on the object then)
-
-class QtFriendlyLayoutWidget : public QWidget
-{
-public:
- inline bool wasDeleted() const { return d_ptr->wasDeleted; }
-};
-
-static bool qt_wasDeleted(const QWidget *w) { return static_cast<const QtFriendlyLayoutWidget*>(w)->wasDeleted(); }
-
-
-/*!
- \reimp
-*/
-QLayoutItem *QStackedLayout::takeAt(int index)
-{
- Q_D(QStackedLayout);
- if (index <0 || index >= d->list.size())
- return 0;
- QLayoutItem *item = d->list.takeAt(index);
- if (index == d->index) {
- d->index = -1;
- if ( d->list.count() > 0 ) {
- int newIndex = (index == d->list.count()) ? index-1 : index;
- setCurrentIndex(newIndex);
- } else {
- emit currentChanged(-1);
- }
- } else if (index < d->index) {
- --d->index;
- }
- emit widgetRemoved(index);
- if (item->widget() && !qt_wasDeleted(item->widget()))
- item->widget()->hide();
- return item;
-}
-
-/*!
- \property QStackedLayout::currentIndex
- \brief the index position of the widget that is visible
-
- The current index is -1 if there is no current widget.
-
- \sa currentWidget(), indexOf()
-*/
-void QStackedLayout::setCurrentIndex(int index)
-{
- Q_D(QStackedLayout);
- QWidget *prev = currentWidget();
- QWidget *next = widget(index);
- if (!next || next == prev)
- return;
-
- bool reenableUpdates = false;
- QWidget *parent = parentWidget();
-
- if (parent && parent->updatesEnabled()) {
- reenableUpdates = true;
- parent->setUpdatesEnabled(false);
- }
-
- QWidget *fw = parent ? parent->window()->focusWidget() : 0;
- if (prev) {
- prev->clearFocus();
- if (d->stackingMode == StackOne)
- prev->hide();
- }
-
- d->index = index;
- next->raise();
- next->show();
-
- // try to move focus onto the incoming widget if focus
- // was somewhere on the outgoing widget.
-
- if (parent) {
- if (fw && (prev && prev->isAncestorOf(fw))) { // focus was on old page
- // look for the best focus widget we can find
- if (QWidget *nfw = next->focusWidget())
- nfw->setFocus();
- else {
- // second best: first child widget in the focus chain
- QWidget *i = fw;
- while ((i = i->nextInFocusChain()) != fw) {
- if (((i->focusPolicy() & Qt::TabFocus) == Qt::TabFocus)
- && !i->focusProxy() && i->isVisibleTo(next) && i->isEnabled()
- && next->isAncestorOf(i)) {
- i->setFocus();
- break;
- }
- }
- // third best: incoming widget
- if (i == fw )
- next->setFocus();
- }
- }
- }
- if (reenableUpdates)
- parent->setUpdatesEnabled(true);
- emit currentChanged(index);
-}
-
-int QStackedLayout::currentIndex() const
-{
- Q_D(const QStackedLayout);
- return d->index;
-}
-
-
-/*!
- \fn void QStackedLayout::setCurrentWidget(QWidget *widget)
-
- Sets the current widget to be the specified \a widget. The new
- current widget must already be contained in this stacked layout.
-
- \sa setCurrentIndex(), currentWidget()
- */
-void QStackedLayout::setCurrentWidget(QWidget *widget)
-{
- int index = indexOf(widget);
- if (index == -1) {
- qWarning("QStackedLayout::setCurrentWidget: Widget %p not contained in stack", widget);
- return;
- }
- setCurrentIndex(index);
-}
-
-
-/*!
- Returns the current widget, or 0 if there are no widgets in this
- layout.
-
- \sa currentIndex(), setCurrentWidget()
-*/
-QWidget *QStackedLayout::currentWidget() const
-{
- Q_D(const QStackedLayout);
- return d->index >= 0 ? d->list.at(d->index)->widget() : 0;
-}
-
-/*!
- Returns the widget at the given \a index, or 0 if there is no
- widget at the given position.
-
- \sa currentWidget(), indexOf()
-*/
-QWidget *QStackedLayout::widget(int index) const
-{
- Q_D(const QStackedLayout);
- if (index < 0 || index >= d->list.size())
- return 0;
- return d->list.at(index)->widget();
-}
-
-/*!
- \property QStackedLayout::count
- \brief the number of widgets contained in the layout
-
- \sa currentIndex(), widget()
-*/
-int QStackedLayout::count() const
-{
- Q_D(const QStackedLayout);
- return d->list.size();
-}
-
-
-/*!
- \reimp
-*/
-void QStackedLayout::addItem(QLayoutItem *item)
-{
- QWidget *widget = item->widget();
- if (widget) {
- addWidget(widget);
- delete item;
- } else {
- qWarning("QStackedLayout::addItem: Only widgets can be added");
- }
-}
-
-/*!
- \reimp
-*/
-QSize QStackedLayout::sizeHint() const
-{
- Q_D(const QStackedLayout);
- QSize s(0, 0);
- int n = d->list.count();
-
- for (int i = 0; i < n; ++i)
- if (QWidget *widget = d->list.at(i)->widget()) {
- QSize ws(widget->sizeHint());
- if (widget->sizePolicy().horizontalPolicy() == QSizePolicy::Ignored)
- ws.setWidth(0);
- if (widget->sizePolicy().verticalPolicy() == QSizePolicy::Ignored)
- ws.setHeight(0);
- s = s.expandedTo(ws);
- }
- return s;
-}
-
-/*!
- \reimp
-*/
-QSize QStackedLayout::minimumSize() const
-{
- Q_D(const QStackedLayout);
- QSize s(0, 0);
- int n = d->list.count();
-
- for (int i = 0; i < n; ++i)
- if (QWidget *widget = d->list.at(i)->widget())
- s = s.expandedTo(qSmartMinSize(widget));
- return s;
-}
-
-/*!
- \reimp
-*/
-void QStackedLayout::setGeometry(const QRect &rect)
-{
- Q_D(QStackedLayout);
- switch (d->stackingMode) {
- case StackOne:
- if (QWidget *widget = currentWidget())
- widget->setGeometry(rect);
- break;
- case StackAll:
- if (const int n = d->list.count())
- for (int i = 0; i < n; ++i)
- if (QWidget *widget = d->list.at(i)->widget())
- widget->setGeometry(rect);
- break;
- }
-}
-
-/*!
- \enum QStackedLayout::StackingMode
- \since 4.4
-
- This enum specifies how the layout handles its child widgets
- regarding their visibility.
-
- \value StackOne
- Only the current widget is visible. This is the default.
-
- \value StackAll
- All widgets are visible. The current widget is merely raised.
-*/
-
-
-/*!
- \property QStackedLayout::stackingMode
- \brief determines the way visibility of child widgets are handled.
- \since 4.4
-
- The default value is StackOne. Setting the property to StackAll
- allows you to make use of the layout for overlay widgets
- that do additional drawing on top of other widgets, for example,
- graphical editors.
-*/
-
-QStackedLayout::StackingMode QStackedLayout::stackingMode() const
-{
- Q_D(const QStackedLayout);
- return d->stackingMode;
-}
-
-void QStackedLayout::setStackingMode(StackingMode stackingMode)
-{
- Q_D(QStackedLayout);
- if (d->stackingMode == stackingMode)
- return;
- d->stackingMode = stackingMode;
-
- const int n = d->list.count();
- if (n == 0)
- return;
-
- switch (d->stackingMode) {
- case StackOne:
- if (const int idx = currentIndex())
- for (int i = 0; i < n; ++i)
- if (QWidget *widget = d->list.at(i)->widget())
- widget->setVisible(i == idx);
- break;
- case StackAll: { // Turn overlay on: Make sure all widgets are the same size
- QRect geometry;
- if (const QWidget *widget = currentWidget())
- geometry = widget->geometry();
- for (int i = 0; i < n; ++i)
- if (QWidget *widget = d->list.at(i)->widget()) {
- if (!geometry.isNull())
- widget->setGeometry(geometry);
- widget->setVisible(true);
- }
- }
- break;
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qstackedlayout.h b/src/gui/kernel/qstackedlayout.h
deleted file mode 100644
index 49b80c6445..0000000000
--- a/src/gui/kernel/qstackedlayout.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTACKEDLAYOUT_H
-#define QSTACKEDLAYOUT_H
-
-#include <QtGui/qlayout.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStackedLayoutPrivate;
-
-class Q_GUI_EXPORT QStackedLayout : public QLayout
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QStackedLayout)
- Q_ENUMS(StackingMode)
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)
- Q_PROPERTY(StackingMode stackingMode READ stackingMode WRITE setStackingMode)
- QDOC_PROPERTY(int count READ count)
-
-public:
- enum StackingMode {
- StackOne,
- StackAll
- };
-
- QStackedLayout();
- explicit QStackedLayout(QWidget *parent);
- explicit QStackedLayout(QLayout *parentLayout);
- ~QStackedLayout();
-
- int addWidget(QWidget *w);
- int insertWidget(int index, QWidget *w);
-
- QWidget *currentWidget() const;
- int currentIndex() const;
-#ifdef Q_NO_USING_KEYWORD
- inline QWidget *widget() { return QLayout::widget(); }
-#else
- using QLayout::widget;
-#endif
- QWidget *widget(int) const;
- int count() const;
-
- StackingMode stackingMode() const;
- void setStackingMode(StackingMode stackingMode);
-
- // abstract virtual functions:
- void addItem(QLayoutItem *item);
- QSize sizeHint() const;
- QSize minimumSize() const;
- QLayoutItem *itemAt(int) const;
- QLayoutItem *takeAt(int);
- void setGeometry(const QRect &rect);
-
-Q_SIGNALS:
- void widgetRemoved(int index);
- void currentChanged(int index);
-
-public Q_SLOTS:
- void setCurrentIndex(int index);
- void setCurrentWidget(QWidget *w);
-
-private:
- Q_DISABLE_COPY(QStackedLayout)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTACKEDLAYOUT_H
diff --git a/src/gui/kernel/qstandardgestures.cpp b/src/gui/kernel/qstandardgestures.cpp
deleted file mode 100644
index 6338ef7afb..0000000000
--- a/src/gui/kernel/qstandardgestures.cpp
+++ /dev/null
@@ -1,595 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstandardgestures_p.h"
-#include "qgesture.h"
-#include "qgesture_p.h"
-#include "qevent.h"
-#include "qwidget.h"
-#include "qabstractscrollarea.h"
-#include <qgraphicssceneevent.h>
-#include "qdebug.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-QPanGestureRecognizer::QPanGestureRecognizer()
-{
-}
-
-QGesture *QPanGestureRecognizer::create(QObject *target)
-{
- if (target && target->isWidgetType()) {
-#if defined(Q_OS_WIN) && !defined(QT_NO_NATIVE_GESTURES)
- // for scroll areas on Windows we want to use native gestures instead
- if (!qobject_cast<QAbstractScrollArea *>(target->parent()))
- static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
-#else
- static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
-#endif
- }
- return new QPanGesture;
-}
-
-QGestureRecognizer::Result QPanGestureRecognizer::recognize(QGesture *state,
- QObject *,
- QEvent *event)
-{
- QPanGesture *q = static_cast<QPanGesture *>(state);
- QPanGesturePrivate *d = q->d_func();
-
- const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
-
- QGestureRecognizer::Result result;
- switch (event->type()) {
- case QEvent::TouchBegin: {
- result = QGestureRecognizer::MayBeGesture;
- QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
- d->lastOffset = d->offset = QPointF();
- break;
- }
- case QEvent::TouchEnd: {
- if (q->state() != Qt::NoGesture) {
- if (ev->touchPoints().size() == 2) {
- QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
- QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
- d->lastOffset = d->offset;
- d->offset =
- QPointF(p1.pos().x() - p1.startPos().x() + p2.pos().x() - p2.startPos().x(),
- p1.pos().y() - p1.startPos().y() + p2.pos().y() - p2.startPos().y()) / 2;
- }
- result = QGestureRecognizer::FinishGesture;
- } else {
- result = QGestureRecognizer::CancelGesture;
- }
- break;
- }
- case QEvent::TouchUpdate: {
- if (ev->touchPoints().size() >= 2) {
- QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
- QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
- d->lastOffset = d->offset;
- d->offset =
- QPointF(p1.pos().x() - p1.startPos().x() + p2.pos().x() - p2.startPos().x(),
- p1.pos().y() - p1.startPos().y() + p2.pos().y() - p2.startPos().y()) / 2;
- if (d->offset.x() > 10 || d->offset.y() > 10 ||
- d->offset.x() < -10 || d->offset.y() < -10) {
- q->setHotSpot(p1.startScreenPos());
- result = QGestureRecognizer::TriggerGesture;
- } else {
- result = QGestureRecognizer::MayBeGesture;
- }
- }
- break;
- }
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- result = QGestureRecognizer::Ignore;
- break;
- default:
- result = QGestureRecognizer::Ignore;
- break;
- }
- return result;
-}
-
-void QPanGestureRecognizer::reset(QGesture *state)
-{
- QPanGesture *pan = static_cast<QPanGesture*>(state);
- QPanGesturePrivate *d = pan->d_func();
-
- d->lastOffset = d->offset = QPointF();
- d->acceleration = 0;
-
- QGestureRecognizer::reset(state);
-}
-
-
-//
-// QPinchGestureRecognizer
-//
-
-QPinchGestureRecognizer::QPinchGestureRecognizer()
-{
-}
-
-QGesture *QPinchGestureRecognizer::create(QObject *target)
-{
- if (target && target->isWidgetType()) {
- static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
- }
- return new QPinchGesture;
-}
-
-QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
- QObject *,
- QEvent *event)
-{
- QPinchGesture *q = static_cast<QPinchGesture *>(state);
- QPinchGesturePrivate *d = q->d_func();
-
- const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
-
- QGestureRecognizer::Result result;
-
- switch (event->type()) {
- case QEvent::TouchBegin: {
- result = QGestureRecognizer::MayBeGesture;
- break;
- }
- case QEvent::TouchEnd: {
- if (q->state() != Qt::NoGesture) {
- result = QGestureRecognizer::FinishGesture;
- } else {
- result = QGestureRecognizer::CancelGesture;
- }
- break;
- }
- case QEvent::TouchUpdate: {
- d->changeFlags = 0;
- if (ev->touchPoints().size() == 2) {
- QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
- QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
-
- d->hotSpot = p1.screenPos();
- d->isHotSpotSet = true;
-
- QPointF centerPoint = (p1.screenPos() + p2.screenPos()) / 2.0;
- if (d->isNewSequence) {
- d->startPosition[0] = p1.screenPos();
- d->startPosition[1] = p2.screenPos();
- d->lastCenterPoint = centerPoint;
- } else {
- d->lastCenterPoint = d->centerPoint;
- }
- d->centerPoint = centerPoint;
-
- d->changeFlags |= QPinchGesture::CenterPointChanged;
-
- if (d->isNewSequence) {
- d->scaleFactor = 1.0;
- d->lastScaleFactor = 1.0;
- } else {
- d->lastScaleFactor = d->scaleFactor;
- QLineF line(p1.screenPos(), p2.screenPos());
- QLineF lastLine(p1.lastScreenPos(), p2.lastScreenPos());
- d->scaleFactor = line.length() / lastLine.length();
- }
- d->totalScaleFactor = d->totalScaleFactor * d->scaleFactor;
- d->changeFlags |= QPinchGesture::ScaleFactorChanged;
-
- qreal angle = QLineF(p1.screenPos(), p2.screenPos()).angle();
- if (angle > 180)
- angle -= 360;
- qreal startAngle = QLineF(p1.startScreenPos(), p2.startScreenPos()).angle();
- if (startAngle > 180)
- startAngle -= 360;
- const qreal rotationAngle = startAngle - angle;
- if (d->isNewSequence)
- d->lastRotationAngle = 0.0;
- else
- d->lastRotationAngle = d->rotationAngle;
- d->rotationAngle = rotationAngle;
- d->totalRotationAngle += d->rotationAngle - d->lastRotationAngle;
- d->changeFlags |= QPinchGesture::RotationAngleChanged;
-
- d->totalChangeFlags |= d->changeFlags;
- d->isNewSequence = false;
- result = QGestureRecognizer::TriggerGesture;
- } else {
- d->isNewSequence = true;
- if (q->state() == Qt::NoGesture)
- result = QGestureRecognizer::Ignore;
- else
- result = QGestureRecognizer::FinishGesture;
- }
- break;
- }
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- result = QGestureRecognizer::Ignore;
- break;
- default:
- result = QGestureRecognizer::Ignore;
- break;
- }
- return result;
-}
-
-void QPinchGestureRecognizer::reset(QGesture *state)
-{
- QPinchGesture *pinch = static_cast<QPinchGesture *>(state);
- QPinchGesturePrivate *d = pinch->d_func();
-
- d->totalChangeFlags = d->changeFlags = 0;
-
- d->startCenterPoint = d->lastCenterPoint = d->centerPoint = QPointF();
- d->totalScaleFactor = d->lastScaleFactor = d->scaleFactor = 1;
- d->totalRotationAngle = d->lastRotationAngle = d->rotationAngle = 0;
-
- d->isNewSequence = true;
- d->startPosition[0] = d->startPosition[1] = QPointF();
-
- QGestureRecognizer::reset(state);
-}
-
-//
-// QSwipeGestureRecognizer
-//
-
-QSwipeGestureRecognizer::QSwipeGestureRecognizer()
-{
-}
-
-QGesture *QSwipeGestureRecognizer::create(QObject *target)
-{
- if (target && target->isWidgetType()) {
- static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
- }
- return new QSwipeGesture;
-}
-
-QGestureRecognizer::Result QSwipeGestureRecognizer::recognize(QGesture *state,
- QObject *,
- QEvent *event)
-{
- QSwipeGesture *q = static_cast<QSwipeGesture *>(state);
- QSwipeGesturePrivate *d = q->d_func();
-
- const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
-
- QGestureRecognizer::Result result;
-
- switch (event->type()) {
- case QEvent::TouchBegin: {
- d->velocityValue = 1;
- d->time.start();
- d->started = true;
- result = QGestureRecognizer::MayBeGesture;
- break;
- }
- case QEvent::TouchEnd: {
- if (q->state() != Qt::NoGesture) {
- result = QGestureRecognizer::FinishGesture;
- } else {
- result = QGestureRecognizer::CancelGesture;
- }
- break;
- }
- case QEvent::TouchUpdate: {
- if (!d->started)
- result = QGestureRecognizer::CancelGesture;
- else if (ev->touchPoints().size() == 3) {
- QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
- QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
- QTouchEvent::TouchPoint p3 = ev->touchPoints().at(2);
-
- if (d->lastPositions[0].isNull()) {
- d->lastPositions[0] = p1.startScreenPos().toPoint();
- d->lastPositions[1] = p2.startScreenPos().toPoint();
- d->lastPositions[2] = p3.startScreenPos().toPoint();
- }
- d->hotSpot = p1.screenPos();
- d->isHotSpotSet = true;
-
- int xDistance = (p1.screenPos().x() - d->lastPositions[0].x() +
- p2.screenPos().x() - d->lastPositions[1].x() +
- p3.screenPos().x() - d->lastPositions[2].x()) / 3;
- int yDistance = (p1.screenPos().y() - d->lastPositions[0].y() +
- p2.screenPos().y() - d->lastPositions[1].y() +
- p3.screenPos().y() - d->lastPositions[2].y()) / 3;
-
- const int distance = xDistance >= yDistance ? xDistance : yDistance;
- int elapsedTime = d->time.restart();
- if (!elapsedTime)
- elapsedTime = 1;
- d->velocityValue = 0.9 * d->velocityValue + distance / elapsedTime;
- d->swipeAngle = QLineF(p1.startScreenPos(), p1.screenPos()).angle();
-
- static const int MoveThreshold = 50;
- if (xDistance > MoveThreshold || yDistance > MoveThreshold) {
- // measure the distance to check if the direction changed
- d->lastPositions[0] = p1.screenPos().toPoint();
- d->lastPositions[1] = p2.screenPos().toPoint();
- d->lastPositions[2] = p3.screenPos().toPoint();
- QSwipeGesture::SwipeDirection horizontal =
- xDistance > 0 ? QSwipeGesture::Right : QSwipeGesture::Left;
- QSwipeGesture::SwipeDirection vertical =
- yDistance > 0 ? QSwipeGesture::Down : QSwipeGesture::Up;
- if (d->verticalDirection == QSwipeGesture::NoDirection)
- d->verticalDirection = vertical;
- if (d->horizontalDirection == QSwipeGesture::NoDirection)
- d->horizontalDirection = horizontal;
- if (d->verticalDirection != vertical || d->horizontalDirection != horizontal) {
- // the user has changed the direction!
- result = QGestureRecognizer::CancelGesture;
- }
- result = QGestureRecognizer::TriggerGesture;
- } else {
- if (q->state() != Qt::NoGesture)
- result = QGestureRecognizer::TriggerGesture;
- else
- result = QGestureRecognizer::MayBeGesture;
- }
- } else if (ev->touchPoints().size() > 3) {
- result = QGestureRecognizer::CancelGesture;
- } else { // less than 3 touch points
- if (d->started && (ev->touchPointStates() & Qt::TouchPointPressed))
- result = QGestureRecognizer::CancelGesture;
- else if (d->started)
- result = QGestureRecognizer::Ignore;
- else
- result = QGestureRecognizer::MayBeGesture;
- }
- break;
- }
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- result = QGestureRecognizer::Ignore;
- break;
- default:
- result = QGestureRecognizer::Ignore;
- break;
- }
- return result;
-}
-
-void QSwipeGestureRecognizer::reset(QGesture *state)
-{
- QSwipeGesture *q = static_cast<QSwipeGesture *>(state);
- QSwipeGesturePrivate *d = q->d_func();
-
- d->verticalDirection = d->horizontalDirection = QSwipeGesture::NoDirection;
- d->swipeAngle = 0;
-
- d->lastPositions[0] = d->lastPositions[1] = d->lastPositions[2] = QPoint();
- d->started = false;
- d->velocityValue = 0;
- d->time.invalidate();
-
- QGestureRecognizer::reset(state);
-}
-
-//
-// QTapGestureRecognizer
-//
-
-QTapGestureRecognizer::QTapGestureRecognizer()
-{
-}
-
-QGesture *QTapGestureRecognizer::create(QObject *target)
-{
- if (target && target->isWidgetType()) {
- static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
- }
- return new QTapGesture;
-}
-
-QGestureRecognizer::Result QTapGestureRecognizer::recognize(QGesture *state,
- QObject *,
- QEvent *event)
-{
- QTapGesture *q = static_cast<QTapGesture *>(state);
- QTapGesturePrivate *d = q->d_func();
-
- const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
-
- QGestureRecognizer::Result result = QGestureRecognizer::CancelGesture;
-
- switch (event->type()) {
- case QEvent::TouchBegin: {
- d->position = ev->touchPoints().at(0).pos();
- q->setHotSpot(ev->touchPoints().at(0).screenPos());
- result = QGestureRecognizer::TriggerGesture;
- break;
- }
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd: {
- if (q->state() != Qt::NoGesture && ev->touchPoints().size() == 1) {
- QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
- QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
- enum { TapRadius = 40 };
- if (delta.manhattanLength() <= TapRadius) {
- if (event->type() == QEvent::TouchEnd)
- result = QGestureRecognizer::FinishGesture;
- else
- result = QGestureRecognizer::TriggerGesture;
- }
- }
- break;
- }
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- case QEvent::MouseButtonRelease:
- result = QGestureRecognizer::Ignore;
- break;
- default:
- result = QGestureRecognizer::Ignore;
- break;
- }
- return result;
-}
-
-void QTapGestureRecognizer::reset(QGesture *state)
-{
- QTapGesture *q = static_cast<QTapGesture *>(state);
- QTapGesturePrivate *d = q->d_func();
-
- d->position = QPointF();
-
- QGestureRecognizer::reset(state);
-}
-
-//
-// QTapAndHoldGestureRecognizer
-//
-
-QTapAndHoldGestureRecognizer::QTapAndHoldGestureRecognizer()
-{
-}
-
-QGesture *QTapAndHoldGestureRecognizer::create(QObject *target)
-{
- if (target && target->isWidgetType()) {
- static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
- }
- return new QTapAndHoldGesture;
-}
-
-QGestureRecognizer::Result
-QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
- QEvent *event)
-{
- QTapAndHoldGesture *q = static_cast<QTapAndHoldGesture *>(state);
- QTapAndHoldGesturePrivate *d = q->d_func();
-
- if (object == state && event->type() == QEvent::Timer) {
- q->killTimer(d->timerId);
- d->timerId = 0;
- return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
- }
-
- const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
- const QMouseEvent *me = static_cast<const QMouseEvent *>(event);
-#ifndef QT_NO_GRAPHICSVIEW
- const QGraphicsSceneMouseEvent *gsme = static_cast<const QGraphicsSceneMouseEvent *>(event);
-#endif
-
- enum { TapRadius = 40 };
-
- switch (event->type()) {
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMousePress:
- d->position = gsme->screenPos();
- q->setHotSpot(d->position);
- if (d->timerId)
- q->killTimer(d->timerId);
- d->timerId = q->startTimer(QTapAndHoldGesturePrivate::Timeout);
- return QGestureRecognizer::MayBeGesture; // we don't show a sign of life until the timeout
-#endif
- case QEvent::MouseButtonPress:
- d->position = me->globalPos();
- q->setHotSpot(d->position);
- if (d->timerId)
- q->killTimer(d->timerId);
- d->timerId = q->startTimer(QTapAndHoldGesturePrivate::Timeout);
- return QGestureRecognizer::MayBeGesture; // we don't show a sign of life until the timeout
- case QEvent::TouchBegin:
- d->position = ev->touchPoints().at(0).startScreenPos();
- q->setHotSpot(d->position);
- if (d->timerId)
- q->killTimer(d->timerId);
- d->timerId = q->startTimer(QTapAndHoldGesturePrivate::Timeout);
- return QGestureRecognizer::MayBeGesture; // we don't show a sign of life until the timeout
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseRelease:
-#endif
- case QEvent::MouseButtonRelease:
- case QEvent::TouchEnd:
- return QGestureRecognizer::CancelGesture; // get out of the MayBeGesture state
- case QEvent::TouchUpdate:
- if (d->timerId && ev->touchPoints().size() == 1) {
- QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
- QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
- if (delta.manhattanLength() <= TapRadius)
- return QGestureRecognizer::MayBeGesture;
- }
- return QGestureRecognizer::CancelGesture;
- case QEvent::MouseMove: {
- QPoint delta = me->globalPos() - d->position.toPoint();
- if (d->timerId && delta.manhattanLength() <= TapRadius)
- return QGestureRecognizer::MayBeGesture;
- return QGestureRecognizer::CancelGesture;
- }
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseMove: {
- QPoint delta = gsme->screenPos() - d->position.toPoint();
- if (d->timerId && delta.manhattanLength() <= TapRadius)
- return QGestureRecognizer::MayBeGesture;
- return QGestureRecognizer::CancelGesture;
- }
-#endif
- default:
- return QGestureRecognizer::Ignore;
- }
-}
-
-void QTapAndHoldGestureRecognizer::reset(QGesture *state)
-{
- QTapAndHoldGesture *q = static_cast<QTapAndHoldGesture *>(state);
- QTapAndHoldGesturePrivate *d = q->d_func();
-
- d->position = QPointF();
- if (d->timerId)
- q->killTimer(d->timerId);
- d->timerId = 0;
-
- QGestureRecognizer::reset(state);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/kernel/qstandardgestures_p.h b/src/gui/kernel/qstandardgestures_p.h
deleted file mode 100644
index b3c5002565..0000000000
--- a/src/gui/kernel/qstandardgestures_p.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTANDARDGESTURES_P_H
-#define QSTANDARDGESTURES_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 "qgesturerecognizer.h"
-#include "private/qgesture_p.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-class QPanGestureRecognizer : public QGestureRecognizer
-{
-public:
- QPanGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-};
-
-class QPinchGestureRecognizer : public QGestureRecognizer
-{
-public:
- QPinchGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-};
-
-class QSwipeGestureRecognizer : public QGestureRecognizer
-{
-public:
- QSwipeGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-};
-
-class QTapGestureRecognizer : public QGestureRecognizer
-{
-public:
- QTapGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-};
-
-class QTapAndHoldGestureRecognizer : public QGestureRecognizer
-{
-public:
- QTapAndHoldGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QSTANDARDGESTURES_P_H
diff --git a/src/gui/kernel/qtooltip.cpp b/src/gui/kernel/qtooltip.cpp
deleted file mode 100644
index 4311df58a6..0000000000
--- a/src/gui/kernel/qtooltip.cpp
+++ /dev/null
@@ -1,623 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-#ifdef Q_WS_MAC
-# include <private/qcore_mac_p.h>
-#endif
-
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <qevent.h>
-#include <qhash.h>
-#include <qlabel.h>
-#include <qpointer.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qstylepainter.h>
-#include <qtimer.h>
-#include <qtooltip.h>
-#include <private/qeffects_p.h>
-#include <qtextdocument.h>
-#include <qdebug.h>
-#include <private/qstylesheetstyle_p.h>
-#ifndef QT_NO_TOOLTIP
-
-#ifdef Q_WS_MAC
-# include <private/qcore_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QToolTip
-
- \brief The QToolTip class provides tool tips (balloon help) for any
- widget.
-
- \ingroup helpsystem
-
-
- The tip is a short piece of text reminding the user of the
- widget's function. It is drawn immediately below the given
- position in a distinctive black-on-yellow color combination. The
- tip can be any \l{QTextEdit}{rich text} formatted string.
-
- Rich text displayed in a tool tip is implicitly word-wrapped unless
- specified differently with \c{<p style='white-space:pre'>}.
-
- The simplest and most common way to set a widget's tool tip is by
- calling its QWidget::setToolTip() function.
-
- It is also possible to show different tool tips for different
- regions of a widget, by using a QHelpEvent of type
- QEvent::ToolTip. Intercept the help event in your widget's \l
- {QWidget::}{event()} function and call QToolTip::showText() with
- the text you want to display. The \l{widgets/tooltips}{Tooltips}
- example illustrates this technique.
-
- If you are calling QToolTip::hideText(), or QToolTip::showText()
- with an empty string, as a result of a \l{QEvent::}{ToolTip}-event you
- should also call \l{QEvent::}{ignore()} on the event, to signal
- that you don't want to start any tooltip specific modes.
-
- Note that, if you want to show tooltips in an item view, the
- model/view architecture provides functionality to set an item's
- tool tip; e.g., the QTableWidgetItem::setToolTip() function.
- However, if you want to provide custom tool tips in an item view,
- you must intercept the help event in the
- QAbstractItemView::viewportEvent() function and handle it yourself.
-
- The default tool tip color and font can be customized with
- setPalette() and setFont(). When a tooltip is currently on
- display, isVisible() returns true and text() the currently visible
- text.
-
- \note Tool tips use the inactive color group of QPalette, because tool
- tips are not active windows.
-
- \sa QWidget::toolTip, QAction::toolTip, {Tool Tips Example}
-*/
-
-class QTipLabel : public QLabel
-{
- Q_OBJECT
-public:
- QTipLabel(const QString &text, QWidget *w);
- ~QTipLabel();
- static QTipLabel *instance;
-
- bool eventFilter(QObject *, QEvent *);
-
- QBasicTimer hideTimer, expireTimer;
-
- bool fadingOut;
-
- void reuseTip(const QString &text);
- void hideTip();
- void hideTipImmediately();
- void setTipRect(QWidget *w, const QRect &r);
- void restartExpireTimer();
- bool tipChanged(const QPoint &pos, const QString &text, QObject *o);
- void placeTip(const QPoint &pos, QWidget *w);
-
- static int getTipScreen(const QPoint &pos, QWidget *w);
-protected:
- void timerEvent(QTimerEvent *e);
- void paintEvent(QPaintEvent *e);
- void mouseMoveEvent(QMouseEvent *e);
- void resizeEvent(QResizeEvent *e);
-
-#ifndef QT_NO_STYLE_STYLESHEET
-public slots:
- /** \internal
- Cleanup the _q_stylesheet_parent propery.
- */
- void styleSheetParentDestroyed() {
- setProperty("_q_stylesheet_parent", QVariant());
- styleSheetParent = 0;
- }
-
-private:
- QWidget *styleSheetParent;
-#endif
-
-private:
- QWidget *widget;
- QRect rect;
-};
-
-QTipLabel *QTipLabel::instance = 0;
-
-QTipLabel::QTipLabel(const QString &text, QWidget *w)
-#ifndef QT_NO_STYLE_STYLESHEET
- : QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget), styleSheetParent(0), widget(0)
-#else
- : QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget), widget(0)
-#endif
-{
- delete instance;
- instance = this;
- setForegroundRole(QPalette::ToolTipText);
- setBackgroundRole(QPalette::ToolTipBase);
- setPalette(QToolTip::palette());
- ensurePolished();
- setMargin(1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, this));
- setFrameStyle(QFrame::NoFrame);
- setAlignment(Qt::AlignLeft);
- setIndent(1);
- qApp->installEventFilter(this);
- setWindowOpacity(style()->styleHint(QStyle::SH_ToolTipLabel_Opacity, 0, this) / 255.0);
- setMouseTracking(true);
- fadingOut = false;
- reuseTip(text);
-}
-
-void QTipLabel::restartExpireTimer()
-{
- int time = 10000 + 40 * qMax(0, text().length()-100);
- expireTimer.start(time, this);
- hideTimer.stop();
-}
-
-void QTipLabel::reuseTip(const QString &text)
-{
-#ifndef QT_NO_STYLE_STYLESHEET
- if (styleSheetParent){
- disconnect(styleSheetParent, SIGNAL(destroyed()),
- QTipLabel::instance, SLOT(styleSheetParentDestroyed()));
- styleSheetParent = 0;
- }
-#endif
-
- setWordWrap(Qt::mightBeRichText(text));
- setText(text);
- QFontMetrics fm(font());
- QSize extra(1, 0);
- // Make it look good with the default ToolTip font on Mac, which has a small descent.
- if (fm.descent() == 2 && fm.ascent() >= 11)
- ++extra.rheight();
- resize(sizeHint() + extra);
- restartExpireTimer();
-}
-
-void QTipLabel::paintEvent(QPaintEvent *ev)
-{
- QStylePainter p(this);
- QStyleOptionFrame opt;
- opt.init(this);
- p.drawPrimitive(QStyle::PE_PanelTipLabel, opt);
- p.end();
-
- QLabel::paintEvent(ev);
-}
-
-void QTipLabel::resizeEvent(QResizeEvent *e)
-{
- QStyleHintReturnMask frameMask;
- QStyleOption option;
- option.init(this);
- if (style()->styleHint(QStyle::SH_ToolTip_Mask, &option, this, &frameMask))
- setMask(frameMask.region);
-
- QLabel::resizeEvent(e);
-}
-
-void QTipLabel::mouseMoveEvent(QMouseEvent *e)
-{
- if (rect.isNull())
- return;
- QPoint pos = e->globalPos();
- if (widget)
- pos = widget->mapFromGlobal(pos);
- if (!rect.contains(pos))
- hideTip();
- QLabel::mouseMoveEvent(e);
-}
-
-QTipLabel::~QTipLabel()
-{
- instance = 0;
-}
-
-void QTipLabel::hideTip()
-{
- if (!hideTimer.isActive())
- hideTimer.start(300, this);
-}
-
-void QTipLabel::hideTipImmediately()
-{
- close(); // to trigger QEvent::Close which stops the animation
- deleteLater();
-}
-
-void QTipLabel::setTipRect(QWidget *w, const QRect &r)
-{
- if (!rect.isNull() && !w)
- qWarning("QToolTip::setTipRect: Cannot pass null widget if rect is set");
- else{
- widget = w;
- rect = r;
- }
-}
-
-void QTipLabel::timerEvent(QTimerEvent *e)
-{
- if (e->timerId() == hideTimer.timerId()
- || e->timerId() == expireTimer.timerId()){
- hideTimer.stop();
- expireTimer.stop();
-#if defined(Q_WS_MAC) && !defined(QT_NO_EFFECTS)
- if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip)){
- // Fade out tip on mac (makes it invisible).
- // The tip will not be deleted until a new tip is shown.
-
- // DRSWAT - Cocoa
- macWindowFade(qt_mac_window_for(this));
- QTipLabel::instance->fadingOut = true; // will never be false again.
- }
- else
- hideTipImmediately();
-#else
- hideTipImmediately();
-#endif
- }
-}
-
-bool QTipLabel::eventFilter(QObject *o, QEvent *e)
-{
- switch (e->type()) {
-#ifdef Q_WS_MAC
- case QEvent::KeyPress:
- case QEvent::KeyRelease: {
- int key = static_cast<QKeyEvent *>(e)->key();
- Qt::KeyboardModifiers mody = static_cast<QKeyEvent *>(e)->modifiers();
- if (!(mody & Qt::KeyboardModifierMask)
- && key != Qt::Key_Shift && key != Qt::Key_Control
- && key != Qt::Key_Alt && key != Qt::Key_Meta)
- hideTip();
- break;
- }
-#endif
- case QEvent::Leave:
- hideTip();
- break;
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- case QEvent::Wheel:
- hideTipImmediately();
- break;
-
- case QEvent::MouseMove:
- if (o == widget && !rect.isNull() && !rect.contains(static_cast<QMouseEvent*>(e)->pos()))
- hideTip();
- default:
- break;
- }
- return false;
-}
-
-int QTipLabel::getTipScreen(const QPoint &pos, QWidget *w)
-{
- if (QApplication::desktop()->isVirtualDesktop())
- return QApplication::desktop()->screenNumber(pos);
- else
- return QApplication::desktop()->screenNumber(w);
-}
-
-void QTipLabel::placeTip(const QPoint &pos, QWidget *w)
-{
-#ifndef QT_NO_STYLE_STYLESHEET
- if (testAttribute(Qt::WA_StyleSheet) || (w && qobject_cast<QStyleSheetStyle *>(w->style()))) {
- //the stylesheet need to know the real parent
- QTipLabel::instance->setProperty("_q_stylesheet_parent", QVariant::fromValue(w));
- //we force the style to be the QStyleSheetStyle, and force to clear the cache as well.
- QTipLabel::instance->setStyleSheet(QLatin1String("/* */"));
-
- // Set up for cleaning up this later...
- QTipLabel::instance->styleSheetParent = w;
- if (w) {
- connect(w, SIGNAL(destroyed()),
- QTipLabel::instance, SLOT(styleSheetParentDestroyed()));
- }
- }
-#endif //QT_NO_STYLE_STYLESHEET
-
-
-#ifdef Q_WS_MAC
- // When in full screen mode, there is no Dock nor Menu so we can use
- // the whole screen for displaying the tooltip. However when not in
- // full screen mode we need to save space for the dock, so we use
- // availableGeometry instead.
- extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
- QRect screen;
- if(qt_mac_app_fullscreen)
- screen = QApplication::desktop()->screenGeometry(getTipScreen(pos, w));
- else
- screen = QApplication::desktop()->availableGeometry(getTipScreen(pos, w));
-#else
- QRect screen = QApplication::desktop()->screenGeometry(getTipScreen(pos, w));
-#endif
-
- QPoint p = pos;
- p += QPoint(2,
-#ifdef Q_WS_WIN
- 21
-#else
- 16
-#endif
- );
- if (p.x() + this->width() > screen.x() + screen.width())
- p.rx() -= 4 + this->width();
- if (p.y() + this->height() > screen.y() + screen.height())
- p.ry() -= 24 + this->height();
- if (p.y() < screen.y())
- p.setY(screen.y());
- if (p.x() + this->width() > screen.x() + screen.width())
- p.setX(screen.x() + screen.width() - this->width());
- if (p.x() < screen.x())
- p.setX(screen.x());
- if (p.y() + this->height() > screen.y() + screen.height())
- p.setY(screen.y() + screen.height() - this->height());
- this->move(p);
-}
-
-bool QTipLabel::tipChanged(const QPoint &pos, const QString &text, QObject *o)
-{
- if (QTipLabel::instance->text() != text)
- return true;
-
- if (o != widget)
- return true;
-
- if (!rect.isNull())
- return !rect.contains(pos);
- else
- return false;
-}
-
-/*!
- Shows \a text as a tool tip, with the global position \a pos as
- the point of interest. The tool tip will be shown with a platform
- specific offset from this point of interest.
-
- If you specify a non-empty rect the tip will be hidden as soon
- as you move your cursor out of this area.
-
- The \a rect is in the coordinates of the widget you specify with
- \a w. If the \a rect is not empty you must specify a widget.
- Otherwise this argument can be 0 but it is used to determine the
- appropriate screen on multi-head systems.
-
- If \a text is empty the tool tip is hidden. If the text is the
- same as the currently shown tooltip, the tip will \e not move.
- You can force moving by first hiding the tip with an empty text,
- and then showing the new tip at the new position.
-*/
-
-void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect)
-{
- if (QTipLabel::instance && QTipLabel::instance->isVisible()){ // a tip does already exist
- if (text.isEmpty()){ // empty text means hide current tip
- QTipLabel::instance->hideTip();
- return;
- }
- else if (!QTipLabel::instance->fadingOut){
- // If the tip has changed, reuse the one
- // that is showing (removes flickering)
- QPoint localPos = pos;
- if (w)
- localPos = w->mapFromGlobal(pos);
- if (QTipLabel::instance->tipChanged(localPos, text, w)){
- QTipLabel::instance->reuseTip(text);
- QTipLabel::instance->setTipRect(w, rect);
- QTipLabel::instance->placeTip(pos, w);
- }
- return;
- }
- }
-
- if (!text.isEmpty()){ // no tip can be reused, create new tip:
-#ifndef Q_WS_WIN
- new QTipLabel(text, w); // sets QTipLabel::instance to itself
-#else
- // On windows, we can't use the widget as parent otherwise the window will be
- // raised when the tooltip will be shown
- new QTipLabel(text, QApplication::desktop()->screen(QTipLabel::getTipScreen(pos, w)));
-#endif
- QTipLabel::instance->setTipRect(w, rect);
- QTipLabel::instance->placeTip(pos, w);
- QTipLabel::instance->setObjectName(QLatin1String("qtooltip_label"));
-
-
-#if !defined(QT_NO_EFFECTS) && !defined(Q_WS_MAC)
- if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
- qFadeEffect(QTipLabel::instance);
- else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))
- qScrollEffect(QTipLabel::instance);
- else
- QTipLabel::instance->show();
-#else
- QTipLabel::instance->show();
-#endif
- }
-}
-
-/*!
- \overload
-
- This is analogous to calling QToolTip::showText(\a pos, \a text, \a w, QRect())
-*/
-
-void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w)
-{
- QToolTip::showText(pos, text, w, QRect());
-}
-
-
-/*!
- \fn void QToolTip::hideText()
- \since 4.2
-
- Hides the tool tip. This is the same as calling showText() with an
- empty string.
-
- \sa showText()
-*/
-
-
-/*!
- \since 4.4
-
- Returns true if this tooltip is currently shown.
-
- \sa showText()
- */
-bool QToolTip::isVisible()
-{
- return (QTipLabel::instance != 0 && QTipLabel::instance->isVisible());
-}
-
-/*!
- \since 4.4
-
- Returns the tooltip text, if a tooltip is visible, or an
- empty string if a tooltip is not visible.
- */
-QString QToolTip::text()
-{
- if (QTipLabel::instance)
- return QTipLabel::instance->text();
- return QString();
-}
-
-
-Q_GLOBAL_STATIC(QPalette, tooltip_palette)
-
-/*!
- Returns the palette used to render tooltips.
-
- \note Tool tips use the inactive color group of QPalette, because tool
- tips are not active windows.
-*/
-QPalette QToolTip::palette()
-{
- return *tooltip_palette();
-}
-
-/*!
- \since 4.2
-
- Returns the font used to render tooltips.
-*/
-QFont QToolTip::font()
-{
- return QApplication::font("QTipLabel");
-}
-
-/*!
- \since 4.2
-
- Sets the \a palette used to render tooltips.
-
- \note Tool tips use the inactive color group of QPalette, because tool
- tips are not active windows.
-*/
-void QToolTip::setPalette(const QPalette &palette)
-{
- *tooltip_palette() = palette;
- if (QTipLabel::instance)
- QTipLabel::instance->setPalette(palette);
-}
-
-/*!
- \since 4.2
-
- Sets the \a font used to render tooltips.
-*/
-void QToolTip::setFont(const QFont &font)
-{
- QApplication::setFont(font, "QTipLabel");
-}
-
-
-/*!
- \fn void QToolTip::add(QWidget *widget, const QString &text)
-
- Use QWidget::setToolTip() instead.
-
- \oldcode
- tip->add(widget, text);
- \newcode
- widget->setToolTip(text);
- \endcode
-*/
-
-/*!
- \fn void QToolTip::add(QWidget *widget, const QRect &rect, const QString &text)
-
- Intercept the QEvent::ToolTip events in your widget's
- QWidget::event() function and call QToolTip::showText() with the
- text you want to display. The \l{widgets/tooltips}{Tooltips}
- example illustrates this technique.
-*/
-
-/*!
- \fn void QToolTip::remove(QWidget *widget)
-
- Use QWidget::setToolTip() instead.
-
- \oldcode
- tip->remove(widget);
- \newcode
- widget->setToolTip("");
- \endcode
-*/
-
-QT_END_NAMESPACE
-
-#include "qtooltip.moc"
-#endif // QT_NO_TOOLTIP
diff --git a/src/gui/kernel/qtooltip.h b/src/gui/kernel/qtooltip.h
deleted file mode 100644
index 4195f1cb3e..0000000000
--- a/src/gui/kernel/qtooltip.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** 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 QTOOLTIP_H
-#define QTOOLTIP_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TOOLTIP
-
-class Q_GUI_EXPORT QToolTip
-{
- QToolTip();
-public:
- static void showText(const QPoint &pos, const QString &text, QWidget *w = 0);
- static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect);
- static inline void hideText() { showText(QPoint(), QString()); }
-
- static bool isVisible();
- static QString text();
-
- static QPalette palette();
- static void setPalette(const QPalette &);
- static QFont font();
- static void setFont(const QFont &);
-#ifdef QT3_SUPPORT
- static inline QT3_SUPPORT void add(QWidget *w, const QString &s) { w->setToolTip(s); }
- static inline QT3_SUPPORT void add(QWidget *w, const QRect &, const QString &s)
- { w->setToolTip(s); }
- static inline QT3_SUPPORT void remove(QWidget *w) { w->setToolTip(QString()); }
-#endif
-};
-
-#endif // QT_NO_TOOLTIP
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTOOLTIP_H
diff --git a/src/gui/kernel/qwhatsthis.cpp b/src/gui/kernel/qwhatsthis.cpp
deleted file mode 100644
index 5e47ffa56b..0000000000
--- a/src/gui/kernel/qwhatsthis.cpp
+++ /dev/null
@@ -1,777 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwhatsthis.h"
-#ifndef QT_NO_WHATSTHIS
-#include "qpointer.h"
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qpixmap.h"
-#include "qpainter.h"
-#include "qtimer.h"
-#include "qhash.h"
-#include "qaction.h"
-#include "qcursor.h"
-#include "qbitmap.h"
-#include "qtextdocument.h"
-#include "../text/qtextdocumentlayout_p.h"
-#include "qtoolbutton.h"
-#include "qdebug.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#if defined(Q_WS_WIN)
-#include "qt_windows.h"
-#ifndef SPI_GETDROPSHADOW
-#define SPI_GETDROPSHADOW 0x1024
-#endif
-#endif
-#if defined(Q_WS_X11)
-#include "qx11info_x11.h"
-#include <qwidget.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QWhatsThis
- \brief The QWhatsThis class provides a simple description of any
- widget, i.e. answering the question "What's This?".
-
- \ingroup helpsystem
-
-
- "What's This?" help is part of an application's online help
- system, and provides users with information about the
- functionality and usage of a particular widget. "What's This?"
- help texts are typically longer and more detailed than \link
- QToolTip tooltips\endlink, but generally provide less information
- than that supplied by separate help windows.
-
- QWhatsThis provides a single window with an explanatory text that
- pops up when the user asks "What's This?". The default way for
- users to ask the question is to move the focus to the relevant
- widget and press Shift+F1. The help text appears immediately; it
- goes away as soon as the user does something else.
- (Note that if there is a shortcut for Shift+F1, this mechanism
- will not work.) Some dialogs provide a "?" button that users can
- click to enter "What's This?" mode; they then click the relevant
- widget to pop up the "What's This?" window. It is also possible to
- provide a a menu option or toolbar button to switch into "What's
- This?" mode.
-
- To add "What's This?" text to a widget or an action, you simply
- call QWidget::setWhatsThis() or QAction::setWhatsThis().
-
- The text can be either rich text or plain text. If you specify a
- rich text formatted string, it will be rendered using the default
- stylesheet, making it possible to embed images in the displayed
- text. To be as fast as possible, the default stylesheet uses a
- simple method to determine whether the text can be rendered as
- plain text. See Qt::mightBeRichText() for details.
-
- \snippet doc/src/snippets/whatsthis/whatsthis.cpp 0
-
- An alternative way to enter "What's This?" mode is to call
- createAction(), and add the returned QAction to either a menu or
- a tool bar. By invoking this context help action (in the picture
- below, the button with the arrow and question mark icon) the user
- switches into "What's This?" mode. If they now click on a widget
- the appropriate help text is shown. The mode is left when help is
- given or when the user presses Esc.
-
- \img whatsthis.png
-
- You can enter "What's This?" mode programmatically with
- enterWhatsThisMode(), check the mode with inWhatsThisMode(), and
- return to normal mode with leaveWhatsThisMode().
-
- If you want to control the "What's This?" behavior of a widget
- manually see Qt::WA_CustomWhatsThis.
-
- It is also possible to show different help texts for different
- regions of a widget, by using a QHelpEvent of type
- QEvent::WhatsThis. Intercept the help event in your widget's
- QWidget::event() function and call QWhatsThis::showText() with the
- text you want to display for the position specified in
- QHelpEvent::pos(). If the text is rich text and the user clicks
- on a link, the widget also receives a QWhatsThisClickedEvent with
- the link's reference as QWhatsThisClickedEvent::href(). If a
- QWhatsThisClickedEvent is handled (i.e. QWidget::event() returns
- true), the help window remains visible. Call
- QWhatsThis::hideText() to hide it explicitly.
-
- \sa QToolTip
-*/
-
-Q_CORE_EXPORT void qDeleteInEventHandler(QObject *o);
-
-class QWhatsThat : public QWidget
-{
- Q_OBJECT
-
-public:
- QWhatsThat(const QString& txt, QWidget* parent, QWidget *showTextFor);
- ~QWhatsThat() ;
-
- static QWhatsThat *instance;
-
-protected:
- void showEvent(QShowEvent *e);
- void mousePressEvent(QMouseEvent*);
- void mouseReleaseEvent(QMouseEvent*);
- void mouseMoveEvent(QMouseEvent*);
- void keyPressEvent(QKeyEvent*);
- void paintEvent(QPaintEvent*);
-
-private:
- QPointer<QWidget>widget;
- bool pressed;
- QString text;
- QTextDocument* doc;
- QString anchor;
- QPixmap background;
-};
-
-QWhatsThat *QWhatsThat::instance = 0;
-
-// shadowWidth not const, for XP drop-shadow-fu turns it to 0
-static int shadowWidth = 6; // also used as '5' and '6' and even '8' below
-static const int vMargin = 8;
-static const int hMargin = 12;
-
-QWhatsThat::QWhatsThat(const QString& txt, QWidget* parent, QWidget *showTextFor)
- : QWidget(parent, Qt::Popup),
- widget(showTextFor), pressed(false), text(txt)
-{
- delete instance;
- instance = this;
- setAttribute(Qt::WA_DeleteOnClose, true);
- setAttribute(Qt::WA_NoSystemBackground, true);
- if (parent)
- setPalette(parent->palette());
- setMouseTracking(true);
- setFocusPolicy(Qt::StrongFocus);
-#ifndef QT_NO_CURSOR
- setCursor(Qt::ArrowCursor);
-#endif
- QRect r;
- doc = 0;
- ensurePolished(); // Ensures style sheet font before size calc
- if (Qt::mightBeRichText(text)) {
- doc = new QTextDocument();
- doc->setUndoRedoEnabled(false);
- doc->setDefaultFont(QApplication::font(this));
-#ifdef QT_NO_TEXTHTMLPARSER
- doc->setPlainText(text);
-#else
- doc->setHtml(text);
-#endif
- doc->setUndoRedoEnabled(false);
- doc->adjustSize();
- r.setTop(0);
- r.setLeft(0);
- r.setSize(doc->size().toSize());
- }
- else
- {
- int sw = QApplication::desktop()->width() / 3;
- if (sw < 200)
- sw = 200;
- else if (sw > 300)
- sw = 300;
-
- r = fontMetrics().boundingRect(0, 0, sw, 1000,
- Qt::AlignLeft + Qt::AlignTop
- + Qt::TextWordWrap + Qt::TextExpandTabs,
- text);
- }
-#if defined(Q_WS_WIN)
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- {
- BOOL shadow;
- SystemParametersInfo(SPI_GETDROPSHADOW, 0, &shadow, 0);
- shadowWidth = shadow ? 0 : 6;
- }
-#endif
- resize(r.width() + 2*hMargin + shadowWidth, r.height() + 2*vMargin + shadowWidth);
-}
-
-QWhatsThat::~QWhatsThat()
-{
- instance = 0;
- if (doc)
- delete doc;
-}
-
-void QWhatsThat::showEvent(QShowEvent *)
-{
- background = QPixmap::grabWindow(QApplication::desktop()->internalWinId(),
- x(), y(), width(), height());
-}
-
-void QWhatsThat::mousePressEvent(QMouseEvent* e)
-{
- pressed = true;
- if (e->button() == Qt::LeftButton && rect().contains(e->pos())) {
- if (doc)
- anchor = doc->documentLayout()->anchorAt(e->pos() - QPoint(hMargin, vMargin));
- return;
- }
- close();
-}
-
-void QWhatsThat::mouseReleaseEvent(QMouseEvent* e)
-{
- if (!pressed)
- return;
- if (widget && e->button() == Qt::LeftButton && doc && rect().contains(e->pos())) {
- QString a = doc->documentLayout()->anchorAt(e->pos() - QPoint(hMargin, vMargin));
- QString href;
- if (anchor == a)
- href = a;
- anchor.clear();
- if (!href.isEmpty()) {
- QWhatsThisClickedEvent e(href);
- if (QApplication::sendEvent(widget, &e))
- return;
- }
- }
- close();
-}
-
-void QWhatsThat::mouseMoveEvent(QMouseEvent* e)
-{
-#ifdef QT_NO_CURSOR
- Q_UNUSED(e);
-#else
- if (!doc)
- return;
- QString a = doc->documentLayout()->anchorAt(e->pos() - QPoint(hMargin, vMargin));
- if (!a.isEmpty())
- setCursor(Qt::PointingHandCursor);
- else
- setCursor(Qt::ArrowCursor);
-#endif
-}
-
-void QWhatsThat::keyPressEvent(QKeyEvent*)
-{
- close();
-}
-
-void QWhatsThat::paintEvent(QPaintEvent*)
-{
- bool drawShadow = true;
-#if defined(Q_WS_WIN)
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- {
- BOOL shadow;
- SystemParametersInfo(SPI_GETDROPSHADOW, 0, &shadow, 0);
- drawShadow = !shadow;
- }
-#elif defined(Q_WS_MAC) || defined(Q_WS_QWS)
- drawShadow = false; // never draw it on OS X or QWS, as we get it for free
-#endif
-
- QRect r = rect();
- r.adjust(0, 0, -1, -1);
- if (drawShadow)
- r.adjust(0, 0, -shadowWidth, -shadowWidth);
- QPainter p(this);
- p.drawPixmap(0, 0, background);
- p.setPen(QPen(palette().toolTipText(), 0));
- p.setBrush(palette().toolTipBase());
- p.drawRect(r);
- int w = r.width();
- int h = r.height();
- p.setPen(palette().brush(QPalette::Dark).color());
- p.drawRect(1, 1, w-2, h-2);
- if (drawShadow) {
- p.setPen(palette().shadow().color());
- p.drawPoint(w + 5, 6);
- p.drawLine(w + 3, 6, w + 5, 8);
- p.drawLine(w + 1, 6, w + 5, 10);
- int i;
- for(i=7; i < h; i += 2)
- p.drawLine(w, i, w + 5, i + 5);
- for(i = w - i + h; i > 6; i -= 2)
- p.drawLine(i, h, i + 5, h + 5);
- for(; i > 0 ; i -= 2)
- p.drawLine(6, h + 6 - i, i + 5, h + 5);
- }
- r.adjust(0, 0, 1, 1);
- p.setPen(palette().toolTipText().color());
- r.adjust(hMargin, vMargin, -hMargin, -vMargin);
-
- if (doc) {
- p.translate(r.x(), r.y());
- QRect rect = r;
- rect.translate(-r.x(), -r.y());
- p.setClipRect(rect);
- QAbstractTextDocumentLayout::PaintContext context;
- context.palette.setBrush(QPalette::Text, context.palette.toolTipText());
- doc->documentLayout()->draw(&p, context);
- }
- else
- {
- p.drawText(r, Qt::AlignLeft + Qt::AlignTop + Qt::TextWordWrap + Qt::TextExpandTabs, text);
- }
-}
-
-static const char * const button_image[] = {
-"16 16 3 1",
-" c None",
-"o c #000000",
-"a c #000080",
-"o aaaaa ",
-"oo aaa aaa ",
-"ooo aaa aaa",
-"oooo aa aa",
-"ooooo aa aa",
-"oooooo a aaa",
-"ooooooo aaa ",
-"oooooooo aaa ",
-"ooooooooo aaa ",
-"ooooo aaa ",
-"oo ooo ",
-"o ooo aaa ",
-" ooo aaa ",
-" ooo ",
-" ooo ",
-" ooo "};
-
-class QWhatsThisPrivate : public QObject
-{
- public:
- QWhatsThisPrivate();
- ~QWhatsThisPrivate();
- static QWhatsThisPrivate *instance;
- bool eventFilter(QObject *, QEvent *);
- QPointer<QAction> action;
-#ifdef QT3_SUPPORT
- QPointer<QToolButton> button;
-#endif
- static void say(QWidget *, const QString &, int x = 0, int y = 0);
- static void notifyToplevels(QEvent *e);
- bool leaveOnMouseRelease;
-};
-
-void QWhatsThisPrivate::notifyToplevels(QEvent *e)
-{
- QWidgetList toplevels = QApplication::topLevelWidgets();
- for (int i = 0; i < toplevels.count(); ++i) {
- register QWidget *w = toplevels.at(i);
- QApplication::sendEvent(w, e);
- }
-}
-
-QWhatsThisPrivate *QWhatsThisPrivate::instance = 0;
-
-QWhatsThisPrivate::QWhatsThisPrivate()
- : leaveOnMouseRelease(false)
-{
- instance = this;
- qApp->installEventFilter(this);
-
- QPoint pos = QCursor::pos();
- if (QWidget *w = QApplication::widgetAt(pos)) {
- QHelpEvent e(QEvent::QueryWhatsThis, w->mapFromGlobal(pos), pos);
- bool sentEvent = QApplication::sendEvent(w, &e);
-#ifdef QT_NO_CURSOR
- Q_UNUSED(sentEvent);
-#else
- QApplication::setOverrideCursor((!sentEvent || !e.isAccepted())?
- Qt::ForbiddenCursor:Qt::WhatsThisCursor);
- } else {
- QApplication::setOverrideCursor(Qt::WhatsThisCursor);
-#endif
- }
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::ContextHelpStart);
-#endif
-}
-
-QWhatsThisPrivate::~QWhatsThisPrivate()
-{
- if (action)
- action->setChecked(false);
-#ifdef QT3_SUPPORT
- if (button)
- button->setChecked(false);
-#endif
-#ifndef QT_NO_CURSOR
- QApplication::restoreOverrideCursor();
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::ContextHelpEnd);
-#endif
- instance = 0;
-}
-
-bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
-{
- if (!o->isWidgetType())
- return false;
- QWidget * w = static_cast<QWidget *>(o);
- bool customWhatsThis = w->testAttribute(Qt::WA_CustomWhatsThis);
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- {
- QMouseEvent *me = static_cast<QMouseEvent*>(e);
- if (me->button() == Qt::RightButton || customWhatsThis)
- return false;
- QHelpEvent e(QEvent::WhatsThis, me->pos(), me->globalPos());
- if (!QApplication::sendEvent(w, &e) || !e.isAccepted())
- leaveOnMouseRelease = true;
-
- } break;
-
- case QEvent::MouseMove:
- {
- QMouseEvent *me = static_cast<QMouseEvent*>(e);
- QHelpEvent e(QEvent::QueryWhatsThis, me->pos(), me->globalPos());
- bool sentEvent = QApplication::sendEvent(w, &e);
-#ifdef QT_NO_CURSOR
- Q_UNUSED(sentEvent);
-#else
- QApplication::changeOverrideCursor((!sentEvent || !e.isAccepted())?
- Qt::ForbiddenCursor:Qt::WhatsThisCursor);
-#endif
- }
- // fall through
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- if (leaveOnMouseRelease && e->type() == QEvent::MouseButtonRelease)
- QWhatsThis::leaveWhatsThisMode();
- if (static_cast<QMouseEvent*>(e)->button() == Qt::RightButton || customWhatsThis)
- return false; // ignore RMB release
- break;
- case QEvent::KeyPress:
- {
- QKeyEvent* kev = (QKeyEvent*)e;
-
- if (kev->key() == Qt::Key_Escape) {
- QWhatsThis::leaveWhatsThisMode();
- return true;
- } else if (customWhatsThis) {
- return false;
- } else if (kev->key() == Qt::Key_Menu ||
- (kev->key() == Qt::Key_F10 &&
- kev->modifiers() == Qt::ShiftModifier)) {
- // we don't react to these keys, they are used for context menus
- return false;
- } else if (kev->key() != Qt::Key_Shift && kev->key() != Qt::Key_Alt // not a modifier key
- && kev->key() != Qt::Key_Control && kev->key() != Qt::Key_Meta) {
- QWhatsThis::leaveWhatsThisMode();
- }
- } break;
- default:
- return false;
- }
- return true;
-}
-
-class QWhatsThisAction: public QAction
-{
- Q_OBJECT
-
-public:
- explicit QWhatsThisAction(QObject* parent = 0);
-
-private slots:
- void actionTriggered();
-};
-
-QWhatsThisAction::QWhatsThisAction(QObject *parent) : QAction(tr("What's This?"), parent)
-{
-#ifndef QT_NO_IMAGEFORMAT_XPM
- QPixmap p((const char**)button_image);
- setIcon(p);
-#endif
- setCheckable(true);
- connect(this, SIGNAL(triggered()), this, SLOT(actionTriggered()));
-#ifndef QT_NO_SHORTCUT
- setShortcut(Qt::ShiftModifier + Qt::Key_F1);
-#endif
-}
-
-void QWhatsThisAction::actionTriggered()
-{
- if (isChecked()) {
- QWhatsThis::enterWhatsThisMode();
- QWhatsThisPrivate::instance->action = this;
- }
-}
-
-QWhatsThis::QWhatsThis()
-{
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \obsolete
-
- Sets the What's This text \a s for the widget \a w.
-
- Use QWidget::setWhatsThis() or QAction::setWhatsThis() instead.
-*/
-void QWhatsThis::add(QWidget *w, const QString &s)
-{
- w->setWhatsThis(s);
-}
-
-/*!
- \obsolete
-
- Remove's the What's This text for the widget \a w.
-
- Use QWidget::setWhatsThis() or QAction::setWhatsThis() instead.
-*/
-void QWhatsThis::remove(QWidget *w)
-{
- w->setWhatsThis(QString());
-}
-
-class QWhatsThisButton : public QToolButton
-{
- Q_OBJECT
-public:
- QWhatsThisButton(QWidget *p) : QToolButton(p) {
- setCheckable(true);
- QPixmap pix( const_cast<const char**>(button_image) );
- setIcon( pix );
- QObject::connect(this, SIGNAL(toggled(bool)), this, SLOT(whatToggled(bool)));
- setAutoRaise(true);
- setFocusPolicy(Qt::NoFocus);
- }
-
-public slots:
- void whatToggled(bool b) {
- if (b) {
- QWhatsThis::enterWhatsThisMode();
- QWhatsThisPrivate::instance->button = this;
- }
- }
-};
-
-/*!
- Returns a new "What's This?" QToolButton with the given \a
- parent. To do this now, create your own QToolButton and a
- QWhatsThis object and call the QWhatsThis object's showText()
- function when the QToolButton is invoked.
-
- Use createAction() instead.
-*/
-QToolButton * QWhatsThis::whatsThisButton(QWidget * parent)
-{
- return new QWhatsThisButton(parent);
-}
-#endif
-
-/*!
- This function switches the user interface into "What's This?"
- mode. The user interface can be switched back into normal mode by
- the user (e.g. by them clicking or pressing Esc), or
- programmatically by calling leaveWhatsThisMode().
-
- When entering "What's This?" mode, a QEvent of type
- Qt::EnterWhatsThisMode is sent to all toplevel widgets.
-
- \sa inWhatsThisMode() leaveWhatsThisMode()
-*/
-void QWhatsThis::enterWhatsThisMode()
-{
- if (QWhatsThisPrivate::instance)
- return;
- (void) new QWhatsThisPrivate;
- QEvent e(QEvent::EnterWhatsThisMode);
- QWhatsThisPrivate::notifyToplevels(&e);
- }
-
-/*!
- Returns true if the user interface is in "What's This?" mode;
- otherwise returns false.
-
- \sa enterWhatsThisMode()
-*/
-bool QWhatsThis::inWhatsThisMode()
-{
- return (QWhatsThisPrivate::instance != 0);
-}
-
-/*!
- If the user interface is in "What's This?" mode, this function
- switches back to normal mode; otherwise it does nothing.
-
- When leaving "What's This?" mode, a QEvent of type
- Qt::LeaveWhatsThisMode is sent to all toplevel widgets.
-
- \sa enterWhatsThisMode() inWhatsThisMode()
-*/
-void QWhatsThis::leaveWhatsThisMode()
-{
- delete QWhatsThisPrivate::instance;
- QEvent e(QEvent::LeaveWhatsThisMode);
- QWhatsThisPrivate::notifyToplevels(&e);
-}
-
-void QWhatsThisPrivate::say(QWidget * widget, const QString &text, int x, int y)
-{
- if (text.size() == 0)
- return;
- // make a fresh widget, and set it up
- QWhatsThat *whatsThat = new QWhatsThat(
- text,
-#if defined(Q_WS_X11) && !defined(QT_NO_CURSOR)
- QApplication::desktop()->screen(widget ? widget->x11Info().screen() : QCursor::x11Screen()),
-#else
- 0,
-#endif
- widget
- );
-
-
- // okay, now to find a suitable location
-
- int scr = (widget ?
- QApplication::desktop()->screenNumber(widget) :
-#if defined(Q_WS_X11) && !defined(QT_NO_CURSOR)
- QCursor::x11Screen()
-#else
- QApplication::desktop()->screenNumber(QPoint(x,y))
-#endif // Q_WS_X11
- );
- QRect screen = QApplication::desktop()->screenGeometry(scr);
-
- int w = whatsThat->width();
- int h = whatsThat->height();
- int sx = screen.x();
- int sy = screen.y();
-
- // first try locating the widget immediately above/below,
- // with nice alignment if possible.
- QPoint pos;
- if (widget)
- pos = widget->mapToGlobal(QPoint(0,0));
-
- if (widget && w > widget->width() + 16)
- x = pos.x() + widget->width()/2 - w/2;
- else
- x = x - w/2;
-
- // squeeze it in if that would result in part of what's this
- // being only partially visible
- if (x + w + shadowWidth > sx+screen.width())
- x = (widget? (qMin(screen.width(),
- pos.x() + widget->width())
- ) : screen.width())
- - w;
-
- if (x < sx)
- x = sx;
-
- if (widget && h > widget->height() + 16) {
- y = pos.y() + widget->height() + 2; // below, two pixels spacing
- // what's this is above or below, wherever there's most space
- if (y + h + 10 > sy+screen.height())
- y = pos.y() + 2 - shadowWidth - h; // above, overlap
- }
- y = y + 2;
-
- // squeeze it in if that would result in part of what's this
- // being only partially visible
- if (y + h + shadowWidth > sy+screen.height())
- y = (widget ? (qMin(screen.height(),
- pos.y() + widget->height())
- ) : screen.height())
- - h;
- if (y < sy)
- y = sy;
-
- whatsThat->move(x, y);
- whatsThat->show();
- whatsThat->grabKeyboard();
-}
-
-/*!
- Shows \a text as a "What's This?" window, at global position \a
- pos. The optional widget argument, \a w, is used to determine the
- appropriate screen on multi-head systems.
-
- \sa hideText()
-*/
-void QWhatsThis::showText(const QPoint &pos, const QString &text, QWidget *w)
-{
- leaveWhatsThisMode();
- QWhatsThisPrivate::say(w, text, pos.x(), pos.y());
-}
-
-/*!
- If a "What's This?" window is showing, this destroys it.
-
- \sa showText()
-*/
-void QWhatsThis::hideText()
-{
- qDeleteInEventHandler(QWhatsThat::instance);
-}
-
-/*!
- Returns a ready-made QAction, used to invoke "What's This?" context
- help, with the given \a parent.
-
- The returned QAction provides a convenient way to let users enter
- "What's This?" mode.
-*/
-QAction *QWhatsThis::createAction(QObject *parent)
-{
- return new QWhatsThisAction(parent);
-}
-
-QT_END_NAMESPACE
-
-#include "qwhatsthis.moc"
-
-#endif // QT_NO_WHATSTHIS
diff --git a/src/gui/kernel/qwhatsthis.h b/src/gui/kernel/qwhatsthis.h
deleted file mode 100644
index c2e396d0d0..0000000000
--- a/src/gui/kernel/qwhatsthis.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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 QWHATSTHIS_H
-#define QWHATSTHIS_H
-
-#include <QtCore/qobject.h>
-#include <QtGui/qcursor.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_WHATSTHIS
-
-class QAction;
-#ifdef QT3_SUPPORT
-class QToolButton;
-#endif
-
-class Q_GUI_EXPORT QWhatsThis
-{
- QWhatsThis();
-
-public:
- static void enterWhatsThisMode();
- static bool inWhatsThisMode();
- static void leaveWhatsThisMode();
-
- static void showText(const QPoint &pos, const QString &text, QWidget *w = 0);
- static void hideText();
-
- static QAction *createAction(QObject *parent = 0);
-
-#ifdef QT3_SUPPORT
- static QT3_SUPPORT void add(QWidget *w, const QString &s);
- static QT3_SUPPORT void remove(QWidget *);
- static QT3_SUPPORT QToolButton *whatsThisButton(QWidget *parent);
-#endif
-};
-
-#endif // QT_NO_WHATSTHIS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWHATSTHIS_H
diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp
deleted file mode 100644
index b6e6a56f4a..0000000000
--- a/src/gui/kernel/qwidget.cpp
+++ /dev/null
@@ -1,12677 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qapplication_p.h"
-#include "qbrush.h"
-#include "qcursor.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qhash.h"
-#include "qlayout.h"
-#include "qmenu.h"
-#include "qmetaobject.h"
-#include "qpixmap.h"
-#include "qpointer.h"
-#include "qstack.h"
-#include "qstyle.h"
-#include "qstylefactory.h"
-#include "qvariant.h"
-#include "qwidget.h"
-#include "qstyleoption.h"
-#ifndef QT_NO_ACCESSIBILITY
-# include "qaccessible.h"
-#endif
-#if defined(Q_WS_WIN)
-# include "qt_windows.h"
-#endif
-#ifdef Q_WS_MAC
-# include "qt_mac_p.h"
-# include "qt_cocoa_helpers_mac_p.h"
-# include "qmainwindow.h"
-# include "qtoolbar.h"
-# include <private/qmainwindowlayout_p.h>
-#endif
-#if defined(Q_WS_QWS)
-# include "qwsdisplay_qws.h"
-# include "qwsmanager_qws.h"
-# include "qpaintengine.h" // for PorterDuff
-# include "private/qwindowsurface_qws_p.h"
-#endif
-#if defined(Q_WS_QPA)
-#include "qplatformwindow_qpa.h"
-#include "private/qwidgetwindow_qpa_p.h"
-#endif
-#include "qpainter.h"
-#include "qtooltip.h"
-#include "qwhatsthis.h"
-#include "qdebug.h"
-#include "private/qstylesheetstyle_p.h"
-#include "private/qstyle_p.h"
-#include "private/qinputcontext_p.h"
-#include "qfileinfo.h"
-#include "private/qsoftkeymanager_p.h"
-
-#if defined (Q_WS_WIN)
-# include <private/qwininputcontext_p.h>
-#endif
-
-#if defined(Q_WS_X11)
-# include <private/qpaintengine_x11_p.h>
-# include "qx11info_x11.h"
-#endif
-
-#include <private/qgraphicseffect_p.h>
-#include <private/qwindowsurface_p.h>
-#include <private/qbackingstore_p.h>
-#ifdef Q_WS_MAC
-# include <private/qpaintengine_mac_p.h>
-#endif
-#include <private/qpaintengine_raster_p.h>
-
-#if defined(Q_OS_SYMBIAN)
-#include "private/qt_s60_p.h"
-#endif
-
-#include "qwidget_p.h"
-#include "qaction_p.h"
-#include "qlayout_p.h"
-#include "QtGui/qgraphicsproxywidget.h"
-#include "QtGui/qgraphicsscene.h"
-#include "private/qgraphicsproxywidget_p.h"
-#include "QtGui/qabstractscrollarea.h"
-#include "private/qabstractscrollarea_p.h"
-#include "private/qevent_p.h"
-
-#include "private/qgesturemanager_p.h"
-
-#ifdef QT_KEYPAD_NAVIGATION
-#include "qtabwidget.h" // Needed in inTabWidget()
-#endif // QT_KEYPAD_NAVIGATION
-
-#ifdef Q_WS_S60
-#include <aknappui.h>
-#endif
-
-// widget/widget data creation count
-//#define QWIDGET_EXTRA_DEBUG
-//#define ALIEN_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(Q_WS_QWS)
-static bool qt_enable_backingstore = true;
-#endif
-#ifdef Q_WS_X11
-// for compatibility with Qt 4.0
-Q_GUI_EXPORT void qt_x11_set_global_double_buffer(bool enable)
-{
- qt_enable_backingstore = enable;
-}
-#endif
-
-#if defined(QT_MAC_USE_COCOA)
-bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
-#endif
-
-static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
-{
- return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
- qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
-}
-
-static inline bool hasBackingStoreSupport()
-{
- return true;
-}
-
-#ifdef Q_WS_MAC
-# define QT_NO_PAINT_DEBUG
-#endif
-
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
-extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
-
-/*!
- \internal
- \class QWidgetBackingStoreTracker
- \brief Class which allows tracking of which widgets are using a given backing store
-
- QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
- which maintains a list of the QWidgets which are currently using the backing
- store. This list is modified via the registerWidget and unregisterWidget functions.
- */
-
-QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
- : m_ptr(0)
-{
-
-}
-
-QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
-{
- delete m_ptr;
-}
-
-/*!
- \internal
- Destroy the contained QWidgetBackingStore, if not null, and clear the list of
- widgets using the backing store, then create a new QWidgetBackingStore, providing
- the QWidget.
- */
-void QWidgetBackingStoreTracker::create(QWidget *widget)
-{
- destroy();
- m_ptr = new QWidgetBackingStore(widget);
-}
-
-/*!
- \internal
- Destroy the contained QWidgetBackingStore, if not null, and clear the list of
- widgets using the backing store.
- */
-void QWidgetBackingStoreTracker::destroy()
-{
- delete m_ptr;
- m_ptr = 0;
- m_widgets.clear();
-}
-
-/*!
- \internal
- Add the widget to the list of widgets currently using the backing store.
- If the widget was already in the list, this function is a no-op.
- */
-void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
-{
- Q_ASSERT(m_ptr);
- Q_ASSERT(w->internalWinId());
- Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
- m_widgets.insert(w);
-}
-
-/*!
- \internal
- Remove the widget from the list of widgets currently using the backing store.
- If the widget was in the list, and removing it causes the list to be empty,
- the backing store is deleted.
- If the widget was not in the list, this function is a no-op.
- */
-void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
-{
- if (m_widgets.remove(w) && m_widgets.isEmpty()) {
- delete m_ptr;
- m_ptr = 0;
- }
-}
-
-/*!
- \internal
- Recursively remove widget and all of its descendents.
- */
-void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
-{
- unregisterWidget(widget);
- foreach (QObject *child, widget->children())
- if (QWidget *childWidget = qobject_cast<QWidget *>(child))
- unregisterWidgetSubtree(childWidget);
-}
-
-QWidgetPrivate::QWidgetPrivate(int version)
- : QObjectPrivate(version)
- , extra(0)
- , focus_next(0)
- , focus_prev(0)
- , focus_child(0)
- , layout(0)
- , needsFlush(0)
- , redirectDev(0)
- , widgetItem(0)
- , extraPaintEngine(0)
- , polished(0)
- , graphicsEffect(0)
-#if !defined(QT_NO_IM)
- , imHints(Qt::ImhNone)
-#endif
- , inheritedFontResolveMask(0)
- , inheritedPaletteResolveMask(0)
- , leftmargin(0)
- , topmargin(0)
- , rightmargin(0)
- , bottommargin(0)
- , leftLayoutItemMargin(0)
- , topLayoutItemMargin(0)
- , rightLayoutItemMargin(0)
- , bottomLayoutItemMargin(0)
- , hd(0)
- , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
- , fg_role(QPalette::NoRole)
- , bg_role(QPalette::NoRole)
- , dirtyOpaqueChildren(1)
- , isOpaque(0)
- , inDirtyList(0)
- , isScrolled(0)
- , isMoved(0)
- , isGLWidget(0)
- , usesDoubleBufferedGLContext(0)
-#ifndef QT_NO_IM
- , inheritsInputMethodHints(0)
-#endif
-#if defined(Q_WS_X11)
- , picture(0)
-#elif defined(Q_WS_WIN)
- , noPaintOnScreen(0)
- #ifndef QT_NO_GESTURES
- , nativeGesturePanEnabled(0)
- #endif
-#elif defined(Q_WS_MAC)
- , needWindowChange(0)
- , window_event(0)
- , qd_hd(0)
-#elif defined(Q_OS_SYMBIAN)
- , symbianScreenNumber(0)
- , fixNativeOrientationCalled(false)
-#endif
-{
- if (!qApp) {
- qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
- return;
- }
-
- if (version != QObjectPrivateVersion)
- qFatal("Cannot mix incompatible Qt libraries");
-
- isWidget = true;
- memset(high_attributes, 0, sizeof(high_attributes));
-#if QT_MAC_USE_COCOA
- drawRectOriginalAdded = false;
- originalDrawMethod = true;
- changeMethods = false;
- isInUnifiedToolbar = false;
- unifiedSurface = 0;
- toolbar_ancestor = 0;
- flushRequested = false;
- touchEventsEnabled = false;
-#endif // QT_MAC_USE_COCOA
-#ifdef QWIDGET_EXTRA_DEBUG
- static int count = 0;
- qDebug() << "widgets" << ++count;
-#endif
-}
-
-
-QWidgetPrivate::~QWidgetPrivate()
-{
- if (widgetItem)
- widgetItem->wid = 0;
-
- if (extra)
- deleteExtra();
-
-#ifndef QT_NO_GRAPHICSEFFECT
- delete graphicsEffect;
-#endif //QT_NO_GRAPHICSEFFECT
-}
-
-class QDummyWindowSurface : public QWindowSurface
-{
-public:
- QDummyWindowSurface(QWindow *window) : QWindowSurface(window) {}
- QPaintDevice *paintDevice() { return static_cast<QWidgetWindow *>(window())->widget(); }
- void flush(QWindow *, const QRegion &, const QPoint &) {}
-};
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface()
-{
- Q_Q(QWidget);
-
- QWindowSurface *surface;
-#ifndef QT_NO_PROPERTIES
- if (q->property("_q_DummyWindowSurface").toBool()) {
- surface = new QDummyWindowSurface(q->windowHandle());
- } else
-#endif
- {
- QWindow *win = topData()->window;
- surface = QGuiApplicationPrivate::platformIntegration()->createWindowSurface(win, win->winId());
- }
-
- return surface;
-}
-
-/*!
- \internal
-*/
-void QWidgetPrivate::scrollChildren(int dx, int dy)
-{
- Q_Q(QWidget);
- if (q->children().size() > 0) { // scroll children
- QPoint pd(dx, dy);
- QObjectList childObjects = q->children();
- for (int i = 0; i < childObjects.size(); ++i) { // move all children
- QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
- if (w && !w->isWindow()) {
- QPoint oldp = w->pos();
- QRect r(w->pos() + pd, w->size());
- w->data->crect = r;
-#ifndef Q_WS_QWS
- if (w->testAttribute(Qt::WA_WState_Created))
- w->d_func()->setWSGeometry();
-#endif
- w->d_func()->setDirtyOpaqueRegion();
- QMoveEvent e(r.topLeft(), oldp);
- QApplication::sendEvent(w, &e);
- }
- }
- }
-}
-
-QInputContext *QWidgetPrivate::assignedInputContext() const
-{
-#ifndef QT_NO_IM
- const QWidget *widget = q_func();
- while (widget) {
- if (QInputContext *qic = widget->d_func()->ic)
- return qic;
- widget = widget->parentWidget();
- }
-#endif
- return 0;
-}
-
-QInputContext *QWidgetPrivate::inputContext() const
-{
-#ifndef QT_NO_IM
- if (QInputContext *qic = assignedInputContext())
- return qic;
- return qApp->inputContext();
-#else
- return 0;
-#endif
-}
-
-/*!
- This function returns the QInputContext for this widget. By
- default the input context is inherited from the widgets
- parent. For toplevels it is inherited from QApplication.
-
- You can override this and set a special input context for this
- widget by using the setInputContext() method.
-
- \sa setInputContext()
-*/
-QInputContext *QWidget::inputContext()
-{
- Q_D(QWidget);
- if (!testAttribute(Qt::WA_InputMethodEnabled))
- return 0;
-
- return d->inputContext();
-}
-
-/*!
- This function sets the input context \a context
- on this widget.
-
- Qt takes ownership of the given input \a context.
-
- \sa inputContext()
-*/
-void QWidget::setInputContext(QInputContext *context)
-{
- Q_D(QWidget);
- if (!testAttribute(Qt::WA_InputMethodEnabled))
- return;
-#ifndef QT_NO_IM
- if (context == d->ic)
- return;
- if (d->ic)
- delete d->ic;
- d->ic = context;
- if (d->ic)
- d->ic->setParent(this);
-#endif
-}
-
-
-/*!
- \obsolete
-
- This function can be called on the widget that currently has focus
- to reset the input method operating on it.
-
- This function is providing for convenience, instead you should use
- \l{QInputContext::}{reset()} on the input context that was
- returned by inputContext().
-
- \sa QInputContext, inputContext(), QInputContext::reset()
-*/
-void QWidget::resetInputContext()
-{
- if (!hasFocus())
- return;
-#ifndef QT_NO_IM
- QInputContext *qic = this->inputContext();
- if(qic)
- qic->reset();
-#endif // QT_NO_IM
-}
-
-#ifdef QT_KEYPAD_NAVIGATION
-QPointer<QWidget> QWidgetPrivate::editingWidget;
-
-/*!
- Returns true if this widget currently has edit focus; otherwise false.
-
- This feature is only available in Qt for Embedded Linux.
-
- \sa setEditFocus(), QApplication::keypadNavigationEnabled()
-*/
-bool QWidget::hasEditFocus() const
-{
- const QWidget* w = this;
- while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
- w = w->d_func()->extra->focus_proxy;
- return QWidgetPrivate::editingWidget == w;
-}
-
-/*!
- \fn void QWidget::setEditFocus(bool enable)
-
- If \a enable is true, make this widget have edit focus, in which
- case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
- normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
- change focus.
-
- This feature is only available in Qt for Embedded Linux and Qt
- for Symbian.
-
- \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
-*/
-void QWidget::setEditFocus(bool on)
-{
- QWidget *f = this;
- while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
- f = f->d_func()->extra->focus_proxy;
-
- if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
- QWidgetPrivate::editingWidget->setEditFocus(false);
-
- if (on && !f->hasFocus())
- f->setFocus();
-
- if ((!on && !QWidgetPrivate::editingWidget)
- || (on && QWidgetPrivate::editingWidget == f)) {
- return;
- }
-
- if (!on && QWidgetPrivate::editingWidget == f) {
- QWidgetPrivate::editingWidget = 0;
- QEvent event(QEvent::LeaveEditFocus);
- QApplication::sendEvent(f, &event);
- QApplication::sendEvent(f->style(), &event);
- } else if (on) {
- QWidgetPrivate::editingWidget = f;
- QEvent event(QEvent::EnterEditFocus);
- QApplication::sendEvent(f, &event);
- QApplication::sendEvent(f->style(), &event);
- }
-}
-#endif
-
-/*!
- \property QWidget::autoFillBackground
- \brief whether the widget background is filled automatically
- \since 4.1
-
- If enabled, this property will cause Qt to fill the background of the
- widget before invoking the paint event. The color used is defined by the
- QPalette::Window color role from the widget's \l{QPalette}{palette}.
-
- In addition, Windows are always filled with QPalette::Window, unless the
- WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
-
- This property cannot be turned off (i.e., set to false) if a widget's
- parent has a static gradient for its background.
-
- \warning Use this property with caution in conjunction with
- \l{Qt Style Sheets}. When a widget has a style sheet with a valid
- background or a border-image, this property is automatically disabled.
-
- By default, this property is false.
-
- \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
- {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
-*/
-bool QWidget::autoFillBackground() const
-{
- Q_D(const QWidget);
- return d->extra && d->extra->autoFillBackground;
-}
-
-void QWidget::setAutoFillBackground(bool enabled)
-{
- Q_D(QWidget);
- if (!d->extra)
- d->createExtra();
- if (d->extra->autoFillBackground == enabled)
- return;
-
- d->extra->autoFillBackground = enabled;
- d->updateIsOpaque();
- update();
- d->updateIsOpaque();
-}
-
-/*!
- \class QWidget
- \brief The QWidget class is the base class of all user interface objects.
-
- \ingroup basicwidgets
-
- The widget is the atom of the user interface: it receives mouse, keyboard
- and other events from the window system, and paints a representation of
- itself on the screen. Every widget is rectangular, and they are sorted in a
- Z-order. A widget is clipped by its parent and by the widgets in front of
- it.
-
- A widget that is not embedded in a parent widget is called a window.
- Usually, windows have a frame and a title bar, although it is also possible
- to create windows without such decoration using suitable
- \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
- subclasses of QDialog are the most common window types.
-
- Every widget's constructor accepts one or two standard arguments:
-
- \list 1
- \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
- (the default), the new widget will be a window. If not, it will be
- a child of \e parent, and be constrained by \e parent's geometry
- (unless you specify Qt::Window as window flag).
- \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
- the default is suitable for almost all widgets, but to get, for
- example, a window without a window system frame, you must use
- special flags.
- \endlist
-
- QWidget has many member functions, but some of them have little direct
- functionality; for example, QWidget has a font property, but never uses
- this itself. There are many subclasses which provide real functionality,
- such as QLabel, QPushButton, QListWidget, and QTabWidget.
-
-
- \section1 Top-Level and Child Widgets
-
- A widget without a parent widget is always an independent window (top-level
- widget). For these widgets, setWindowTitle() and setWindowIcon() set the
- title bar and icon respectively.
-
- Non-window widgets are child widgets, displayed within their parent
- widgets. Most widgets in Qt are mainly useful as child widgets. For
- example, it is possible to display a button as a top-level window, but most
- people prefer to put their buttons inside other widgets, such as QDialog.
-
- \image parent-child-widgets.png A parent widget containing various child widgets.
-
- The diagram above shows a QGroupBox widget being used to hold various child
- widgets in a layout provided by QGridLayout. The QLabel child widgets have
- been outlined to indicate their full sizes.
-
- If you want to use a QWidget to hold child widgets you will usually want to
- add a layout to the parent QWidget. See \l{Layout Management} for more
- information.
-
-
- \section1 Composite Widgets
-
- When a widget is used as a container to group a number of child widgets, it
- is known as a composite widget. These can be created by constructing a
- widget with the required visual properties - a QFrame, for example - and
- adding child widgets to it, usually managed by a layout. The above diagram
- shows such a composite widget that was created using \l{Qt Designer}.
-
- Composite widgets can also be created by subclassing a standard widget,
- such as QWidget or QFrame, and adding the necessary layout and child
- widgets in the constructor of the subclass. Many of the \l{Qt Examples}
- {examples provided with Qt} use this approach, and it is also covered in
- the Qt \l{Tutorials}.
-
-
- \section1 Custom Widgets and Painting
-
- Since QWidget is a subclass of QPaintDevice, subclasses can be used to
- display custom content that is composed using a series of painting
- operations with an instance of the QPainter class. This approach contrasts
- with the canvas-style approach used by the \l{Graphics View}
- {Graphics View Framework} where items are added to a scene by the
- application and are rendered by the framework itself.
-
- Each widget performs all painting operations from within its paintEvent()
- function. This is called whenever the widget needs to be redrawn, either
- as a result of some external change or when requested by the application.
-
- The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
- can handle paint events.
-
-
- \section1 Size Hints and Size Policies
-
- When implementing a new widget, it is almost always useful to reimplement
- sizeHint() to provide a reasonable default size for the widget and to set
- the correct size policy with setSizePolicy().
-
- By default, composite widgets which do not provide a size hint will be
- sized according to the space requirements of their child widgets.
-
- The size policy lets you supply good default behavior for the layout
- management system, so that other widgets can contain and manage yours
- easily. The default size policy indicates that the size hint represents
- the preferred size of the widget, and this is often good enough for many
- widgets.
-
- \note The size of top-level widgets are constrained to 2/3 of the desktop's
- height and width. You can resize() the widget manually if these bounds are
- inadequate.
-
-
- \section1 Events
-
- Widgets respond to events that are typically caused by user actions. Qt
- delivers events to widgets by calling specific event handler functions with
- instances of QEvent subclasses containing information about each event.
-
- If your widget only contains child widgets, you probably do not need to
- implement any event handlers. If you want to detect a mouse click in a
- child widget call the child's underMouse() function inside the widget's
- mousePressEvent().
-
- The \l{widgets/scribble}{Scribble example} implements a wider set of
- events to handle mouse movement, button presses, and window resizing.
-
- You will need to supply the behavior and content for your own widgets, but
- here is a brief overview of the events that are relevant to QWidget,
- starting with the most common ones:
-
- \list
- \i paintEvent() is called whenever the widget needs to be repainted.
- Every widget displaying custom content must implement it. Painting
- using a QPainter can only take place in a paintEvent() or a
- function called by a paintEvent().
- \i resizeEvent() is called when the widget has been resized.
- \i mousePressEvent() is called when a mouse button is pressed while
- the mouse cursor is inside the widget, or when the widget has
- grabbed the mouse using grabMouse(). Pressing the mouse without
- releasing it is effectively the same as calling grabMouse().
- \i mouseReleaseEvent() is called when a mouse button is released. A
- widget receives mouse release events when it has received the
- corresponding mouse press event. This means that if the user
- presses the mouse inside \e your widget, then drags the mouse
- somewhere else before releasing the mouse button, \e your widget
- receives the release event. There is one exception: if a popup menu
- appears while the mouse button is held down, this popup immediately
- steals the mouse events.
- \i mouseDoubleClickEvent() is called when the user double-clicks in
- the widget. If the user double-clicks, the widget receives a mouse
- press event, a mouse release event and finally this event instead
- of a second mouse press event. (Some mouse move events may also be
- received if the mouse is not held steady during this operation.) It
- is \e{not possible} to distinguish a click from a double-click
- until the second click arrives. (This is one reason why most GUI
- books recommend that double-clicks be an extension of
- single-clicks, rather than trigger a different action.)
- \endlist
-
- Widgets that accept keyboard input need to reimplement a few more event
- handlers:
-
- \list
- \i keyPressEvent() is called whenever a key is pressed, and again when
- a key has been held down long enough for it to auto-repeat. The
- \key Tab and \key Shift+Tab keys are only passed to the widget if
- they are not used by the focus-change mechanisms. To force those
- keys to be processed by your widget, you must reimplement
- QWidget::event().
- \i focusInEvent() is called when the widget gains keyboard focus
- (assuming you have called setFocusPolicy()). Well-behaved widgets
- indicate that they own the keyboard focus in a clear but discreet
- way.
- \i focusOutEvent() is called when the widget loses keyboard focus.
- \endlist
-
- You may be required to also reimplement some of the less common event
- handlers:
-
- \list
- \i mouseMoveEvent() is called whenever the mouse moves while a mouse
- button is held down. This can be useful during drag and drop
- operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
- you get mouse move events even when no buttons are held down.
- (See also the \l{Drag and Drop} guide.)
- \i keyReleaseEvent() is called whenever a key is released and while it
- is held down (if the key is auto-repeating). In that case, the
- widget will receive a pair of key release and key press event for
- every repeat. The \key Tab and \key Shift+Tab keys are only passed
- to the widget if they are not used by the focus-change mechanisms.
- To force those keys to be processed by your widget, you must
- reimplement QWidget::event().
- \i wheelEvent() is called whenever the user turns the mouse wheel
- while the widget has the focus.
- \i enterEvent() is called when the mouse enters the widget's screen
- space. (This excludes screen space owned by any of the widget's
- children.)
- \i leaveEvent() is called when the mouse leaves the widget's screen
- space. If the mouse enters a child widget it will not cause a
- leaveEvent().
- \i moveEvent() is called when the widget has been moved relative to
- its parent.
- \i closeEvent() is called when the user closes the widget (or when
- close() is called).
- \endlist
-
- There are also some rather obscure events described in the documentation
- for QEvent::Type. To handle these events, you need to reimplement event()
- directly.
-
- The default implementation of event() handles \key Tab and \key Shift+Tab
- (to move the keyboard focus), and passes on most of the other events to
- one of the more specialized handlers above.
-
- Events and the mechanism used to deliver them are covered in
- \l{The Event System}.
-
- \section1 Groups of Functions and Properties
-
- \table
- \header \i Context \i Functions and Properties
-
- \row \i Window functions \i
- show(),
- hide(),
- raise(),
- lower(),
- close().
-
- \row \i Top-level windows \i
- \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
- \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
- \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
- showNormal().
-
- \row \i Window contents \i
- update(),
- repaint(),
- scroll().
-
- \row \i Geometry \i
- \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
- \l sizePolicy, sizeHint(), minimumSizeHint(),
- updateGeometry(), layout(),
- \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
- adjustSize(),
- mapFromGlobal(), mapToGlobal(),
- mapFromParent(), mapToParent(),
- \l maximumSize, \l minimumSize, \l sizeIncrement,
- \l baseSize, setFixedSize()
-
- \row \i Mode \i
- \l visible, isVisibleTo(),
- \l enabled, isEnabledTo(),
- \l modal,
- isWindow(),
- \l mouseTracking,
- \l updatesEnabled,
- visibleRegion().
-
- \row \i Look and feel \i
- style(),
- setStyle(),
- \l styleSheet,
- \l cursor,
- \l font,
- \l palette,
- backgroundRole(), setBackgroundRole(),
- fontInfo(), fontMetrics().
-
- \row \i Keyboard focus functions \i
- \l focus, \l focusPolicy,
- setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
- focusNextChild(), focusPreviousChild().
-
- \row \i Mouse and keyboard grabbing \i
- grabMouse(), releaseMouse(),
- grabKeyboard(), releaseKeyboard(),
- mouseGrabber(), keyboardGrabber().
-
- \row \i Event handlers \i
- event(),
- mousePressEvent(),
- mouseReleaseEvent(),
- mouseDoubleClickEvent(),
- mouseMoveEvent(),
- keyPressEvent(),
- keyReleaseEvent(),
- focusInEvent(),
- focusOutEvent(),
- wheelEvent(),
- enterEvent(),
- leaveEvent(),
- paintEvent(),
- moveEvent(),
- resizeEvent(),
- closeEvent(),
- dragEnterEvent(),
- dragMoveEvent(),
- dragLeaveEvent(),
- dropEvent(),
- childEvent(),
- showEvent(),
- hideEvent(),
- customEvent().
- changeEvent(),
-
- \row \i System functions \i
- parentWidget(), window(), setParent(), winId(),
- find(), metric().
-
- \row \i Interactive help \i
- setToolTip(), setWhatsThis()
-
- \endtable
-
-
- \section1 Widget Style Sheets
-
- In addition to the standard widget styles for each platform, widgets can
- also be styled according to rules specified in a \l{styleSheet}
- {style sheet}. This feature enables you to customize the appearance of
- specific widgets to provide visual cues to users about their purpose. For
- example, a button could be styled in a particular way to indicate that it
- performs a destructive action.
-
- The use of widget style sheets is described in more detail in the
- \l{Qt Style Sheets} document.
-
-
- \section1 Transparency and Double Buffering
-
- Since Qt 4.0, QWidget automatically double-buffers its painting, so there
- is no need to write double-buffering code in paintEvent() to avoid
- flicker.
-
- Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
- deprecated. Instead, the contents of parent widgets are propagated by
- default to each of their children as long as Qt::WA_PaintOnScreen is not
- set. Custom widgets can be written to take advantage of this feature by
- updating irregular regions (to create non-rectangular child widgets), or
- painting with colors that have less than full alpha component. The
- following diagram shows how attributes and properties of a custom widget
- can be fine-tuned to achieve different effects.
-
- \image propagation-custom.png
-
- In the above diagram, a semi-transparent rectangular child widget with an
- area removed is constructed and added to a parent widget (a QLabel showing
- a pixmap). Then, different properties and widget attributes are set to
- achieve different effects:
-
- \list
- \i The left widget has no additional properties or widget attributes
- set. This default state suits most custom widgets using
- transparency, are irregularly-shaped, or do not paint over their
- entire area with an opaque brush.
- \i The center widget has the \l autoFillBackground property set. This
- property is used with custom widgets that rely on the widget to
- supply a default background, and do not paint over their entire
- area with an opaque brush.
- \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
- set. This indicates that the widget will paint over its entire area
- with opaque colors. The widget's area will initially be
- \e{uninitialized}, represented in the diagram with a red diagonal
- grid pattern that shines through the overpainted area. The
- Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
- paint their own specialized contents quickly and do not need a
- default filled background.
- \endlist
-
- To rapidly update custom widgets with simple background colors, such as
- real-time plotting or graphing widgets, it is better to define a suitable
- background color (using setBackgroundRole() with the
- QPalette::Window role), set the \l autoFillBackground property, and only
- implement the necessary drawing functionality in the widget's paintEvent().
-
- To rapidly update custom widgets that constantly paint over their entire
- areas with opaque content, e.g., video streaming widgets, it is better to
- set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
- associated with repainting the widget's background.
-
- If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
- the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
- attribute takes precedence. Depending on your requirements, you should
- choose either one of them.
-
- Since Qt 4.1, the contents of parent widgets are also propagated to
- standard Qt widgets. This can lead to some unexpected results if the
- parent widget is decorated in a non-standard way, as shown in the diagram
- below.
-
- \image propagation-standard.png
-
- The scope for customizing the painting behavior of standard Qt widgets,
- without resorting to subclassing, is slightly less than that possible for
- custom widgets. Usually, the desired appearance of a standard widget can be
- achieved by setting its \l autoFillBackground property.
-
-
- \section1 Creating Translucent Windows
-
- Since Qt 4.5, it has been possible to create windows with translucent regions
- on window systems that support compositing.
-
- To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
- attribute with setAttribute() and ensure that its background is painted with
- non-opaque colors in the regions you want to be partially transparent.
-
- Platform notes:
-
- \list
- \o X11: This feature relies on the use of an X server that supports ARGB visuals
- and a compositing window manager.
- \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
- for the translucency to work.
- \endlist
-
-
- \section1 Native Widgets vs Alien Widgets
-
- Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
- system. They do not have a native window handle associated with them. This
- feature significantly speeds up widget painting, resizing, and removes flicker.
-
- Should you require the old behavior with native windows, you can choose
- one of the following options:
-
- \list 1
- \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
- \i Set the Qt::AA_NativeWindows attribute on your application. All
- widgets will be native widgets.
- \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
- and all of its ancestors will become native (unless
- Qt::WA_DontCreateNativeAncestors is set).
- \i Call QWidget::winId to enforce a native window (this implies 3).
- \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window
- (this implies 3).
- \endlist
-
- \sa QEvent, QPainter, QGridLayout, QBoxLayout
-
- \section1 Softkeys
-
- Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
- other visual representation on the screen that is generally located next to its
- physical counterpart. They are most often found on mobile phone platforms. In
- modern touch based user interfaces it is also possible to have softkeys that do
- not correspond to any physical keys. Softkeys differ from other onscreen labels
- in that they are contextual.
-
- In Qt, contextual softkeys are added to a widget by calling addAction() and
- passing a \c QAction with a softkey role set on it. When the widget
- containing the softkey actions has focus, its softkeys should appear in
- the user interface. Softkeys are discovered by traversing the widget
- hierarchy so it is possible to define a single set of softkeys that are
- present at all times by calling addAction() for a given top level widget.
-
- On some platforms, this concept overlaps with \c QMenuBar such that if no
- other softkeys are found and the top level widget is a QMainWindow containing
- a QMenuBar, the menubar actions may appear on one of the softkeys.
-
- Note: Currently softkeys are only supported on the Symbian Platform.
-
- \sa addAction(), QAction, QMenuBar
-
-*/
-
-QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
-QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
-
-
-/*****************************************************************************
- QWidget utility functions
- *****************************************************************************/
-
-QRegion qt_dirtyRegion(QWidget *widget)
-{
- if (!widget)
- return QRegion();
-
- QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
- if (!bs)
- return QRegion();
-
- return bs->dirtyRegion(widget);
-}
-
-/*****************************************************************************
- QWidget member functions
- *****************************************************************************/
-
-/*
- Widget state flags:
- \list
- \i Qt::WA_WState_Created The widget has a valid winId().
- \i Qt::WA_WState_Visible The widget is currently visible.
- \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
- become visible unless you call show() on it. Qt::WA_WState_Hidden
- implies !Qt::WA_WState_Visible.
- \i Qt::WA_WState_CompressKeys Compress keyboard events.
- \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
- \i Qt::WA_WState_InPaintEvent Currently processing a paint event.
- \i Qt::WA_WState_Reparented The widget has been reparented.
- \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
- \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
- \endlist
-*/
-
-struct QWidgetExceptionCleaner
-{
- /* this cleans up when the constructor throws an exception */
- static inline void cleanup(QWidget *that, QWidgetPrivate *d)
- {
-#ifdef QT_NO_EXCEPTIONS
- Q_UNUSED(that);
- Q_UNUSED(d);
-#else
- QWidgetPrivate::allWidgets->remove(that);
- if (d->focus_next != that) {
- if (d->focus_next)
- d->focus_next->d_func()->focus_prev = d->focus_prev;
- if (d->focus_prev)
- d->focus_prev->d_func()->focus_next = d->focus_next;
- }
-#endif
- }
-};
-
-/*!
- Constructs a widget which is a child of \a parent, with widget
- flags set to \a f.
-
- If \a parent is 0, the new widget becomes a window. If
- \a parent is another widget, this widget becomes a child window
- inside \a parent. The new widget is deleted when its \a parent is
- deleted.
-
- The widget flags argument, \a f, is normally 0, but it can be set
- to customize the frame of a window (i.e. \a
- parent must be 0). To customize the frame, use a value composed
- from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
-
- If you add a child widget to an already visible widget you must
- explicitly show the child to make it visible.
-
- Note that the X11 version of Qt may not be able to deliver all
- combinations of style flags on all systems. This is because on
- X11, Qt can only ask the window manager, and the window manager
- can override the application's settings. On Windows, Qt can set
- whatever flags you want.
-
- \sa windowFlags
-*/
-QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
- : QObject(*new QWidgetPrivate, 0), QPaintDevice()
-{
- QT_TRY {
- d_func()->init(parent, f);
- } QT_CATCH(...) {
- QWidgetExceptionCleaner::cleanup(this, d_func());
- QT_RETHROW;
- }
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \overload
- \obsolete
- */
-QWidget::QWidget(QWidget *parent, const char *name, Qt::WindowFlags f)
- : QObject(*new QWidgetPrivate, 0), QPaintDevice()
-{
- QT_TRY {
- d_func()->init(parent , f);
- setObjectName(QString::fromAscii(name));
- } QT_CATCH(...) {
- QWidgetExceptionCleaner::cleanup(this, d_func());
- QT_RETHROW;
- }
-}
-#endif
-
-/*! \internal
-*/
-QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
- : QObject(dd, 0), QPaintDevice()
-{
- Q_D(QWidget);
- QT_TRY {
- d->init(parent, f);
- } QT_CATCH(...) {
- QWidgetExceptionCleaner::cleanup(this, d_func());
- QT_RETHROW;
- }
-}
-
-/*!
- \internal
-*/
-int QWidget::devType() const
-{
- return QInternal::Widget;
-}
-
-
-//### w is a "this" ptr, passed as a param because QWorkspace needs special logic
-void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
-{
- bool customize = (flags & (Qt::CustomizeWindowHint
- | Qt::FramelessWindowHint
- | Qt::WindowTitleHint
- | Qt::WindowSystemMenuHint
- | Qt::WindowMinimizeButtonHint
- | Qt::WindowMaximizeButtonHint
- | Qt::WindowCloseButtonHint
- | Qt::WindowContextHelpButtonHint));
-
- uint type = (flags & Qt::WindowType_Mask);
-
- if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
- type = Qt::Window;
- flags |= Qt::Window;
- }
-
- if (flags & Qt::CustomizeWindowHint) {
- // modify window flags to make them consistent.
- // Only enable this on non-Mac platforms. Since the old way of doing this would
- // interpret WindowSystemMenuHint as a close button and we can't change that behavior
- // we can't just add this in.
-#ifndef Q_WS_MAC
- if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
- flags |= Qt::WindowSystemMenuHint;
-#else
- if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
- | Qt::WindowSystemMenuHint)) {
-#endif
- flags |= Qt::WindowTitleHint;
- flags &= ~Qt::FramelessWindowHint;
- }
- } else if (customize && !(flags & Qt::FramelessWindowHint)) {
- // if any of the window hints that affect the titlebar are set
- // and the window is supposed to have frame, we add a titlebar
- // and system menu by default.
- flags |= Qt::WindowSystemMenuHint;
- flags |= Qt::WindowTitleHint;
- }
- if (customize)
- ; // don't modify window flags if the user explicitly set them.
- else if (type == Qt::Dialog || type == Qt::Sheet)
-#ifndef Q_WS_WINCE
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
-#else
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
-#endif
- else if (type == Qt::Tool)
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
- else
- flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
-
-
-}
-
-void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
-{
- Q_Q(QWidget);
- if (QApplication::type() == QApplication::Tty)
- qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
-
- Q_ASSERT(allWidgets);
- if (allWidgets)
- allWidgets->insert(q);
-
- QWidget *desktopWidget = 0;
- if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
- desktopWidget = parentWidget;
- parentWidget = 0;
- }
-
- q->data = &data;
-
-#ifndef QT_NO_THREAD
- if (!parent) {
- Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
- "Widgets must be created in the GUI thread.");
- }
-#endif
-
-#if defined(Q_WS_X11)
- if (desktopWidget) {
- // make sure the widget is created on the same screen as the
- // programmer specified desktop widget
- xinfo = desktopWidget->d_func()->xinfo;
- }
-#elif defined(Q_OS_SYMBIAN)
- if (desktopWidget) {
- symbianScreenNumber = qt_widget_private(desktopWidget)->symbianScreenNumber;
- }
-#elif defined(Q_WS_QPA)
- if (desktopWidget) {
- int screen = desktopWidget->d_func()->topData()->screenIndex;
- QPlatformIntegration *platform = QGuiApplicationPrivate::platformIntegration();
- platform->moveToScreen(q->windowHandle(), screen);
- }
-#else
- Q_UNUSED(desktopWidget);
-#endif
-
- data.fstrut_dirty = true;
-
- data.winid = 0;
- data.widget_attributes = 0;
- data.window_flags = f;
- data.window_state = 0;
- data.focus_policy = 0;
- data.context_menu_policy = Qt::DefaultContextMenu;
- data.window_modality = Qt::NonModal;
-
- data.sizehint_forced = 0;
- data.is_closing = 0;
- data.in_show = 0;
- data.in_set_window_state = 0;
- data.in_destructor = false;
-
- // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
- if (f & Qt::MSWindowsOwnDC)
- q->setAttribute(Qt::WA_NativeWindow);
-
-//#ifdef Q_WS_MAC
-// q->setAttribute(Qt::WA_NativeWindow);
-//#endif
-
- q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
- adjustQuitOnCloseAttribute();
-
- q->setAttribute(Qt::WA_WState_Hidden);
-
- //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
-#ifdef Q_OS_SYMBIAN
- if (isGLWidget) {
- // Don't waste GPU mem for unnecessary large egl surface until resized by application
- data.crect = QRect(0,0,1,1);
- } else {
- data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,360,640);
- }
-#else
- data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
-#endif
-
- focus_next = focus_prev = q;
-
- if ((f & Qt::WindowType_Mask) == Qt::Desktop)
- q->create();
- else if (parentWidget)
- q->setParent(parentWidget, data.window_flags);
- else {
- adjustFlags(data.window_flags, q);
- resolveLayoutDirection();
- // opaque system background?
- const QBrush &background = q->palette().brush(QPalette::Window);
- setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
- }
- data.fnt = QFont(data.fnt, q);
-#if defined(Q_WS_X11)
- data.fnt.x11SetScreen(xinfo.screen());
-#endif // Q_WS_X11
-
- q->setAttribute(Qt::WA_PendingMoveEvent);
- q->setAttribute(Qt::WA_PendingResizeEvent);
-
- if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
- QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
-
- if (QApplicationPrivate::app_compile_version < 0x040200
- || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
- q->create();
-
-
- QEvent e(QEvent::Create);
- QApplication::sendEvent(q, &e);
- QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
-
- extraPaintEngine = 0;
-
-#ifdef QT_MAC_USE_COCOA
- // If we add a child to the unified toolbar, we have to redirect the painting.
- if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
- if (parentWidget->d_func()->unifiedSurface) {
- QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
- parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
- }
- }
-#endif // QT_MAC_USE_COCOA
-}
-
-
-
-void QWidgetPrivate::createRecursively()
-{
- Q_Q(QWidget);
- q->create(0, true, true);
- for (int i = 0; i < children.size(); ++i) {
- QWidget *child = qobject_cast<QWidget *>(children.at(i));
- if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
- child->d_func()->createRecursively();
- }
-}
-
-
-
-
-/*!
- Creates a new widget window if \a window is 0, otherwise sets the
- widget's window to \a window.
-
- Initializes the window (sets the geometry etc.) if \a
- initializeWindow is true. If \a initializeWindow is false, no
- initialization is performed. This parameter only makes sense if \a
- window is a valid window.
-
- Destroys the old window if \a destroyOldWindow is true. If \a
- destroyOldWindow is false, you are responsible for destroying the
- window yourself (using platform native code).
-
- The QWidget constructor calls create(0,true,true) to create a
- window for this widget.
-*/
-
-void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
-{
- Q_D(QWidget);
- if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
- return;
-
- if (d->data.in_destructor)
- return;
-
- Qt::WindowType type = windowType();
- Qt::WindowFlags &flags = data->window_flags;
-
- if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
- type = Qt::Window;
- flags |= Qt::Window;
- }
-
-#ifndef Q_WS_QPA
- if (QWidget *parent = parentWidget()) {
- if (type & Qt::Window) {
- if (!parent->testAttribute(Qt::WA_WState_Created))
- parent->createWinId();
- } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
- && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
- // We're about to create a native child widget that doesn't have a native parent;
- // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
- // attribute is set.
- d->createWinId(window);
- // Nothing more to do.
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- Q_ASSERT(internalWinId());
- return;
- }
- }
-#endif //Q_WS_QPA
-
-#ifdef QT3_SUPPORT
- if (flags & Qt::WStaticContents)
- setAttribute(Qt::WA_StaticContents);
- if (flags & Qt::WDestructiveClose)
- setAttribute(Qt::WA_DeleteOnClose);
- if (flags & Qt::WShowModal)
- setWindowModality(Qt::ApplicationModal);
- if (flags & Qt::WMouseNoMask)
- setAttribute(Qt::WA_MouseNoMask);
- if (flags & Qt::WGroupLeader)
- setAttribute(Qt::WA_GroupLeader);
- if (flags & Qt::WNoMousePropagation)
- setAttribute(Qt::WA_NoMousePropagation);
-#endif
-
- static int paintOnScreenEnv = -1;
- if (paintOnScreenEnv == -1)
- paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
- if (paintOnScreenEnv == 1)
- setAttribute(Qt::WA_PaintOnScreen);
-
- if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
- setAttribute(Qt::WA_NativeWindow);
-
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
- << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
-#endif
-
-#if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
- // Unregister the dropsite (if already registered) before we
- // re-create the widget with a native window.
- if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
- && d->extra && d->extra->dropTarget) {
- d->registerDropSite(false);
- }
-#endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
-
- d->updateIsOpaque();
-
- setAttribute(Qt::WA_WState_Created); // set created flag
- d->create_sys(window, initializeWindow, destroyOldWindow);
-
- // a real toplevel window needs a backing store
- if (isWindow() && windowType() != Qt::Desktop) {
- d->topData()->backingStore.destroy();
- if (hasBackingStoreSupport())
- d->topData()->backingStore.create(this);
- }
-
- d->setModal_sys();
-
- if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
- setAttribute(Qt::WA_DropSiteRegistered, true);
-
-#ifdef QT_EVAL
- extern void qt_eval_init_widget(QWidget *w);
- qt_eval_init_widget(this);
-#endif
-
- // need to force the resting of the icon after changing parents
- if (testAttribute(Qt::WA_SetWindowIcon))
- d->setWindowIcon_sys(true);
- if (isWindow() && !d->topData()->iconText.isEmpty())
- d->setWindowIconText_helper(d->topData()->iconText);
- if (isWindow() && !d->topData()->caption.isEmpty())
- d->setWindowTitle_helper(d->topData()->caption);
- if (windowType() != Qt::Desktop) {
- d->updateSystemBackground();
-
- if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
- d->setWindowIcon_sys();
- }
-}
-
-/*!
- Destroys the widget.
-
- All this widget's children are deleted first. The application
- exits if this widget is the main widget.
-*/
-
-QWidget::~QWidget()
-{
- Q_D(QWidget);
- d->data.in_destructor = true;
-
-#if defined (QT_CHECK_STATE)
- if (paintingActive())
- qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
-#endif
-
-#ifndef QT_NO_GESTURES
- foreach (Qt::GestureType type, d->gestureContext.keys())
- ungrabGesture(type);
-#endif
-
- // force acceptDrops false before winId is destroyed.
- d->registerDropSite(false);
-
-#ifndef QT_NO_ACTION
- // remove all actions from this widget
- for (int i = 0; i < d->actions.size(); ++i) {
- QActionPrivate *apriv = d->actions.at(i)->d_func();
- apriv->widgets.removeAll(this);
- }
- d->actions.clear();
-#endif
-
-#ifndef QT_NO_SHORTCUT
- // Remove all shortcuts grabbed by this
- // widget, unless application is closing
- if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
- qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
-#endif
-
- // delete layout while we still are a valid widget
- delete d->layout;
- // Remove myself from focus list
-
- Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
- Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
-
- if (d->focus_next != this) {
- d->focus_next->d_func()->focus_prev = d->focus_prev;
- d->focus_prev->d_func()->focus_next = d->focus_next;
- d->focus_next = d->focus_prev = 0;
- }
-
-#ifdef QT3_SUPPORT
- if (QApplicationPrivate::main_widget == this) { // reset main widget
- QApplicationPrivate::main_widget = 0;
- QApplication::quit();
- }
-#endif
-
- QT_TRY {
- clearFocus();
- } QT_CATCH(...) {
- // swallow this problem because we are in a destructor
- }
-
- d->setDirtyOpaqueRegion();
-
- if (isWindow() && isVisible() && internalWinId()) {
- QT_TRY {
- d->close_helper(QWidgetPrivate::CloseNoEvent);
- } QT_CATCH(...) {
- // if we're out of memory, at least hide the window.
- QT_TRY {
- hide();
- } QT_CATCH(...) {
- // and if that also doesn't work, then give up
- }
- }
- }
-
-#if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
- else if (!internalWinId() && isVisible()) {
- qApp->d_func()->sendSyntheticEnterLeave(this);
- }
-#elif defined(Q_WS_QWS) || defined(Q_WS_QPA)
- else if (isVisible()) {
- qApp->d_func()->sendSyntheticEnterLeave(this);
- }
-#endif
-
-#ifdef Q_OS_SYMBIAN
- if (d->extra && d->extra->topextra && d->extra->topextra->backingStore) {
- // Okay, we are about to destroy the top-level window that owns
- // the backing store. Make sure we delete the backing store right away
- // before the window handle is invalid. This is important because
- // the backing store will delete its window surface, which may or may
- // not have a reference to this widget that will be used later to
- // notify the window it no longer has a surface.
- d->extra->topextra->backingStore.destroy();
- }
-#endif
- if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
- bs->removeDirtyWidget(this);
- if (testAttribute(Qt::WA_StaticContents))
- bs->removeStaticWidget(this);
- }
-
- delete d->needsFlush;
- d->needsFlush = 0;
-
- // set all QPointers for this object to zero
- if (d->hasGuards)
- QObjectPrivate::clearGuards(this);
-
- if (d->declarativeData) {
- QAbstractDeclarativeData::destroyed(d->declarativeData, this);
- d->declarativeData = 0; // don't activate again in ~QObject
- }
-
-#ifdef QT_MAC_USE_COCOA
- // QCocoaView holds a pointer back to this widget. Clear it now
- // to make sure it's not followed later on. The lifetime of the
- // QCocoaView might exceed the lifetime of this widget in cases
- // where Cocoa itself holds references to it.
- extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
- qt_mac_clearCocoaViewQWidgetPointers(this);
-#endif
-
- if (!d->children.isEmpty())
- d->deleteChildren();
-
- QApplication::removePostedEvents(this);
-
- QT_TRY {
- destroy(); // platform-dependent cleanup
- } QT_CATCH(...) {
- // if this fails we can't do anything about it but at least we are not allowed to throw.
- }
- --QWidgetPrivate::instanceCounter;
-
- if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
- QWidgetPrivate::allWidgets->remove(this);
-
- QT_TRY {
- QEvent e(QEvent::Destroy);
- QCoreApplication::sendEvent(this, &e);
- } QT_CATCH(const std::exception&) {
- // if this fails we can't do anything about it but at least we are not allowed to throw.
- }
-}
-
-int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
-int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
-
-void QWidgetPrivate::setWinId(WId id) // set widget identifier
-{
- Q_Q(QWidget);
- // the user might create a widget with Qt::Desktop window
- // attribute (or create another QDesktopWidget instance), which
- // will have the same windowid (the root window id) as the
- // qt_desktopWidget. We should not add the second desktop widget
- // to the mapper.
- bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
- if (mapper && data.winid && !userDesktopWidget) {
- mapper->remove(data.winid);
- }
-
- const WId oldWinId = data.winid;
-
- data.winid = id;
-#if defined(Q_WS_X11)
- hd = id; // X11: hd == ident
-#endif
- if (mapper && id && !userDesktopWidget) {
- mapper->insert(data.winid, q);
- }
-
- if(oldWinId != id) {
- QEvent e(QEvent::WinIdChange);
- QCoreApplication::sendEvent(q, &e);
- }
-}
-
-void QWidgetPrivate::createTLExtra()
-{
- if (!extra)
- createExtra();
- if (!extra->topextra) {
- QTLWExtra* x = extra->topextra = new QTLWExtra;
- x->icon = 0;
- x->iconPixmap = 0;
- x->windowSurface = 0;
- x->sharedPainter = 0;
- x->incw = x->inch = 0;
- x->basew = x->baseh = 0;
- x->frameStrut.setCoords(0, 0, 0, 0);
- x->normalGeometry = QRect(0,0,-1,-1);
- x->savedFlags = 0;
- x->opacity = 255;
- x->posFromMove = false;
- x->sizeAdjusted = false;
- x->inTopLevelResize = false;
- x->inRepaint = false;
- x->embedded = 0;
-#ifdef Q_WS_MAC
-#ifdef QT_MAC_USE_COCOA
- x->wasMaximized = false;
-#endif // QT_MAC_USE_COCOA
-#endif // Q_WS_MAC
- createTLSysExtra();
-#ifdef QWIDGET_EXTRA_DEBUG
- static int count = 0;
- qDebug() << "tlextra" << ++count;
-#endif
- }
-}
-
-/*!
- \internal
- Creates the widget extra data.
-*/
-
-void QWidgetPrivate::createExtra()
-{
- if (!extra) { // if not exists
- extra = new QWExtra;
- extra->glContext = 0;
- extra->topextra = 0;
-#ifndef QT_NO_GRAPHICSVIEW
- extra->proxyWidget = 0;
-#endif
-#ifndef QT_NO_CURSOR
- extra->curs = 0;
-#endif
- extra->minw = 0;
- extra->minh = 0;
- extra->maxw = QWIDGETSIZE_MAX;
- extra->maxh = QWIDGETSIZE_MAX;
- extra->customDpiX = 0;
- extra->customDpiY = 0;
- extra->explicitMinSize = 0;
- extra->explicitMaxSize = 0;
- extra->autoFillBackground = 0;
- extra->nativeChildrenForced = 0;
- extra->inRenderWithPainter = 0;
- extra->hasMask = 0;
- createSysExtra();
-#ifdef QWIDGET_EXTRA_DEBUG
- static int count = 0;
- qDebug() << "extra" << ++count;
-#endif
- }
-}
-
-
-/*!
- \internal
- Deletes the widget extra data.
-*/
-
-void QWidgetPrivate::deleteExtra()
-{
- if (extra) { // if exists
-#ifndef QT_NO_CURSOR
- delete extra->curs;
-#endif
- deleteSysExtra();
-#ifndef QT_NO_STYLE_STYLESHEET
- // dereference the stylesheet style
- if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
- proxy->deref();
-#endif
- if (extra->topextra) {
- deleteTLSysExtra();
- extra->topextra->backingStore.destroy();
- delete extra->topextra->icon;
- delete extra->topextra->iconPixmap;
-#if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER)
- delete extra->topextra->qwsManager;
-#endif
- delete extra->topextra->windowSurface;
- delete extra->topextra;
- }
- delete extra;
- // extra->xic destroyed in QWidget::destroy()
- extra = 0;
- }
-}
-
-/*
- Returns true if there are widgets above this which overlap with
- \a rect, which is in parent's coordinate system (same as crect).
-*/
-
-bool QWidgetPrivate::isOverlapped(const QRect &rect) const
-{
- Q_Q(const QWidget);
-
- const QWidget *w = q;
- QRect r = rect;
- while (w) {
- if (w->isWindow())
- return false;
- QWidgetPrivate *pd = w->parentWidget()->d_func();
- bool above = false;
- for (int i = 0; i < pd->children.size(); ++i) {
- QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
- if (!sibling || !sibling->isVisible() || sibling->isWindow())
- continue;
- if (!above) {
- above = (sibling == w);
- continue;
- }
-
- if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
- const QWExtra *siblingExtra = sibling->d_func()->extra;
- if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
- && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
- continue;
- }
- return true;
- }
- }
- w = w->parentWidget();
- r.translate(pd->data.crect.topLeft());
- }
- return false;
-}
-
-void QWidgetPrivate::syncBackingStore()
-{
- if (paintOnScreen()) {
- repaint_sys(dirty);
- dirty = QRegion();
- } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
- bs->sync();
- }
-}
-
-void QWidgetPrivate::syncBackingStore(const QRegion &region)
-{
- if (paintOnScreen())
- repaint_sys(region);
- else if (QWidgetBackingStore *bs = maybeBackingStore()) {
- bs->sync(q_func(), region);
- }
-}
-
-void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
-{
- Q_Q(QWidget);
-
- if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
- return; // nothing we can do
-
- if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
- return; // nothing to do
-
- q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
- if (enable)
- q->update();
-
- Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(children.at(i));
- if (w && !w->isWindow() && !w->testAttribute(attribute))
- w->d_func()->setUpdatesEnabled_helper(enable);
- }
-}
-
-/*!
- \internal
-
- Propagate this widget's palette to all children, except style sheet
- widgets, and windows that don't enable window propagation (palettes don't
- normally propagate to windows).
-*/
-void QWidgetPrivate::propagatePaletteChange()
-{
- Q_Q(QWidget);
- // Propagate a new inherited mask to all children.
-#ifndef QT_NO_GRAPHICSVIEW
- if (!q->parentWidget() && extra && extra->proxyWidget) {
- QGraphicsProxyWidget *p = extra->proxyWidget;
- inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
- } else
-#endif //QT_NO_GRAPHICSVIEW
- if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
- inheritedPaletteResolveMask = 0;
- }
- int mask = data.pal.resolve() | inheritedPaletteResolveMask;
-
- QEvent pc(QEvent::PaletteChange);
- QApplication::sendEvent(q, &pc);
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget*>(children.at(i));
- if (w && !w->testAttribute(Qt::WA_StyleSheet)
- && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
- QWidgetPrivate *wd = w->d_func();
- wd->inheritedPaletteResolveMask = mask;
- wd->resolvePalette();
- }
- }
-#if defined(QT3_SUPPORT)
- q->paletteChange(q->palette()); // compatibility
-#endif
-}
-
-/*
- Returns the widget's clipping rectangle.
-*/
-QRect QWidgetPrivate::clipRect() const
-{
- Q_Q(const QWidget);
- const QWidget * w = q;
- if (!w->isVisible())
- return QRect();
- QRect r = effectiveRectFor(q->rect());
- int ox = 0;
- int oy = 0;
- while (w
- && w->isVisible()
- && !w->isWindow()
- && w->parentWidget()) {
- ox -= w->x();
- oy -= w->y();
- w = w->parentWidget();
- r &= QRect(ox, oy, w->width(), w->height());
- }
- return r;
-}
-
-/*
- Returns the widget's clipping region (without siblings).
-*/
-QRegion QWidgetPrivate::clipRegion() const
-{
- Q_Q(const QWidget);
- if (!q->isVisible())
- return QRegion();
- QRegion r(q->rect());
- const QWidget * w = q;
- const QWidget *ignoreUpTo;
- int ox = 0;
- int oy = 0;
- while (w
- && w->isVisible()
- && !w->isWindow()
- && w->parentWidget()) {
- ox -= w->x();
- oy -= w->y();
- ignoreUpTo = w;
- w = w->parentWidget();
- r &= QRegion(ox, oy, w->width(), w->height());
-
- int i = 0;
- while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
- ;
- for ( ; i < w->d_func()->children.size(); ++i) {
- if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
- if(sibling->isVisible() && !sibling->isWindow()) {
- QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
- sibling->width(), sibling->height());
- if (qRectIntersects(siblingRect, q->rect()))
- r -= QRegion(siblingRect);
- }
- }
- }
- }
- return r;
-}
-
-#ifndef QT_NO_GRAPHICSEFFECT
-void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
-{
- Q_Q(QWidget);
- QWidget *w = q;
- do {
- if (w->graphicsEffect()) {
- QWidgetEffectSourcePrivate *sourced =
- static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
- if (!sourced->updateDueToGraphicsEffect)
- w->graphicsEffect()->source()->d_func()->invalidateCache();
- }
- w = w->parentWidget();
- } while (w);
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-void QWidgetPrivate::setDirtyOpaqueRegion()
-{
- Q_Q(QWidget);
-
- dirtyOpaqueChildren = true;
-
-#ifndef QT_NO_GRAPHICSEFFECT
- invalidateGraphicsEffectsRecursively();
-#endif //QT_NO_GRAPHICSEFFECT
-
- if (q->isWindow())
- return;
-
- QWidget *parent = q->parentWidget();
- if (!parent)
- return;
-
- // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
- QWidgetPrivate *pd = parent->d_func();
- if (!pd->dirtyOpaqueChildren)
- pd->setDirtyOpaqueRegion();
-}
-
-const QRegion &QWidgetPrivate::getOpaqueChildren() const
-{
- if (!dirtyOpaqueChildren)
- return opaqueChildren;
-
- QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
- that->opaqueChildren = QRegion();
-
- for (int i = 0; i < children.size(); ++i) {
- QWidget *child = qobject_cast<QWidget *>(children.at(i));
- if (!child || !child->isVisible() || child->isWindow())
- continue;
-
- const QPoint offset = child->geometry().topLeft();
- QWidgetPrivate *childd = child->d_func();
- QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
- if (childd->extra && childd->extra->hasMask)
- r &= childd->extra->mask;
- if (r.isEmpty())
- continue;
- r.translate(offset);
- that->opaqueChildren += r;
- }
-
- that->opaqueChildren &= q_func()->rect();
- that->dirtyOpaqueChildren = false;
-
- return that->opaqueChildren;
-}
-
-void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
-{
- if (children.isEmpty() || clipRect.isEmpty())
- return;
-
- const QRegion &r = getOpaqueChildren();
- if (!r.isEmpty())
- source -= (r & clipRect);
-}
-
-//subtract any relatives that are higher up than me --- this is too expensive !!!
-void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
- bool alsoNonOpaque) const
-{
- Q_Q(const QWidget);
- static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
- if (disableSubtractOpaqueSiblings || q->isWindow())
- return;
-
-#ifdef QT_MAC_USE_COCOA
- if (q->d_func()->isInUnifiedToolbar)
- return;
-#endif // QT_MAC_USE_COCOA
-
- QRect clipBoundingRect;
- bool dirtyClipBoundingRect = true;
-
- QRegion parentClip;
- bool dirtyParentClip = true;
-
- QPoint parentOffset = data.crect.topLeft();
-
- const QWidget *w = q;
-
- while (w) {
- if (w->isWindow())
- break;
- QWidgetPrivate *pd = w->parentWidget()->d_func();
- const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
- const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
- for (int i = myIndex + 1; i < pd->children.size(); ++i) {
- QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
- if (!sibling || !sibling->isVisible() || sibling->isWindow())
- continue;
-
- const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
- if (!qRectIntersects(siblingGeometry, widgetGeometry))
- continue;
-
- if (dirtyClipBoundingRect) {
- clipBoundingRect = sourceRegion.boundingRect();
- dirtyClipBoundingRect = false;
- }
-
- if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
- continue;
-
- if (dirtyParentClip) {
- parentClip = sourceRegion.translated(parentOffset);
- dirtyParentClip = false;
- }
-
- const QPoint siblingPos(sibling->data->crect.topLeft());
- const QRect siblingClipRect(sibling->d_func()->clipRect());
- QRegion siblingDirty(parentClip);
- siblingDirty &= (siblingClipRect.translated(siblingPos));
- const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
- && !sibling->d_func()->graphicsEffect;
- if (hasMask)
- siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
- if (siblingDirty.isEmpty())
- continue;
-
- if (sibling->d_func()->isOpaque || alsoNonOpaque) {
- if (hasMask) {
- siblingDirty.translate(-parentOffset);
- sourceRegion -= siblingDirty;
- } else {
- sourceRegion -= siblingGeometry.translated(-parentOffset);
- }
- } else {
- if (hasDirtySiblingsAbove)
- *hasDirtySiblingsAbove = true;
- if (sibling->d_func()->children.isEmpty())
- continue;
- QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
- opaqueSiblingChildren.translate(-parentOffset + siblingPos);
- sourceRegion -= opaqueSiblingChildren;
- }
- if (sourceRegion.isEmpty())
- return;
-
- dirtyClipBoundingRect = true;
- dirtyParentClip = true;
- }
-
- w = w->parentWidget();
- parentOffset += pd->data.crect.topLeft();
- dirtyParentClip = true;
- }
-}
-
-void QWidgetPrivate::clipToEffectiveMask(QRegion &region) const
-{
- Q_Q(const QWidget);
-
- const QWidget *w = q;
- QPoint offset;
-
-#ifndef QT_NO_GRAPHICSEFFECT
- if (graphicsEffect) {
- w = q->parentWidget();
- offset -= data.crect.topLeft();
- }
-#endif //QT_NO_GRAPHICSEFFECT
-
- while (w) {
- const QWidgetPrivate *wd = w->d_func();
- if (wd->extra && wd->extra->hasMask)
- region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
- if (w->isWindow())
- return;
- offset -= wd->data.crect.topLeft();
- w = w->parentWidget();
- }
-}
-
-bool QWidgetPrivate::paintOnScreen() const
-{
-#if defined(Q_WS_QWS)
- return false;
-#elif defined(QT_NO_BACKINGSTORE)
- return true;
-#else
- Q_Q(const QWidget);
- if (q->testAttribute(Qt::WA_PaintOnScreen)
- || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
- return true;
- }
-
- return !qt_enable_backingstore;
-#endif
-}
-
-void QWidgetPrivate::updateIsOpaque()
-{
- // hw: todo: only needed if opacity actually changed
- setDirtyOpaqueRegion();
-
-#ifndef QT_NO_GRAPHICSEFFECT
- if (graphicsEffect) {
- // ### We should probably add QGraphicsEffect::isOpaque at some point.
- setOpaque(false);
- return;
- }
-#endif //QT_NO_GRAPHICSEFFECT
-
- Q_Q(QWidget);
-#ifdef Q_WS_X11
- if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
- setOpaque(false);
- return;
- }
-#endif
-
-#ifdef Q_WS_S60
- if (q->windowType() == Qt::Dialog && q->testAttribute(Qt::WA_TranslucentBackground)
- && S60->avkonComponentsSupportTransparency) {
- setOpaque(false);
- return;
- }
-#endif
-
- if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
- setOpaque(true);
- return;
- }
-
- const QPalette &pal = q->palette();
-
- if (q->autoFillBackground()) {
- const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
- if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
- setOpaque(true);
- return;
- }
- }
-
- if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
- const QBrush &windowBrush = q->palette().brush(QPalette::Window);
- if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
- setOpaque(true);
- return;
- }
- }
- setOpaque(false);
-}
-
-void QWidgetPrivate::setOpaque(bool opaque)
-{
- if (isOpaque == opaque)
- return;
- isOpaque = opaque;
-#ifdef Q_WS_MAC
- macUpdateIsOpaque();
-#endif
-#ifdef Q_WS_X11
- x11UpdateIsOpaque();
-#endif
-#ifdef Q_WS_WIN
- winUpdateIsOpaque();
-#endif
-#ifdef Q_OS_SYMBIAN
- s60UpdateIsOpaque();
-#endif
-}
-
-void QWidgetPrivate::updateIsTranslucent()
-{
-#ifdef Q_WS_MAC
- macUpdateIsOpaque();
-#endif
-#ifdef Q_WS_X11
- x11UpdateIsOpaque();
-#endif
-#ifdef Q_WS_WIN
- winUpdateIsOpaque();
-#endif
-#ifdef Q_OS_SYMBIAN
- s60UpdateIsOpaque();
-#endif
-}
-
-static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
-{
- Q_ASSERT(painter);
-
- if (brush.style() == Qt::TexturePattern) {
-#ifdef Q_WS_MAC
- // Optimize pattern filling on mac by using HITheme directly
- // when filling with the standard widget background.
- // Defined in qmacstyle_mac.cpp
- extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
- qt_mac_fill_background(painter, rgn, brush);
-#else
-#if !defined(QT_NO_STYLE_S60)
- // Defined in qs60style.cpp
- extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
- if (!qt_s60_fill_background(painter, rgn, brush))
-#endif // !defined(QT_NO_STYLE_S60)
- {
- const QRect rect(rgn.boundingRect());
- painter->setClipRegion(rgn);
- painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
- }
-#endif // Q_WS_MAC
-
- } else if (brush.gradient()
- && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
- painter->save();
- painter->setClipRegion(rgn);
- painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
- painter->restore();
- } else {
- const QVector<QRect> &rects = rgn.rects();
- for (int i = 0; i < rects.size(); ++i)
- painter->fillRect(rects.at(i), brush);
- }
-}
-
-void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
-{
- Q_Q(const QWidget);
-
-#ifndef QT_NO_SCROLLAREA
- bool resetBrushOrigin = false;
- QPointF oldBrushOrigin;
- //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
- QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
- if (scrollArea && scrollArea->viewport() == q) {
- QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
- QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
- oldBrushOrigin = painter->brushOrigin();
- resetBrushOrigin = true;
- painter->setBrushOrigin(-priv->contentsOffset());
-
- }
-#endif // QT_NO_SCROLLAREA
-
- const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
-
- if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
- const QBrush bg = q->palette().brush(QPalette::Window);
-#ifdef Q_WS_QWS
- if (!(flags & DontSetCompositionMode) && painter->paintEngine()->hasFeature(QPaintEngine::PorterDuff))
- painter->setCompositionMode(QPainter::CompositionMode_Source); //copy alpha straight in
-#endif
- fillRegion(painter, rgn, bg);
- }
-
- if (q->autoFillBackground())
- fillRegion(painter, rgn, autoFillBrush);
-
- if (q->testAttribute(Qt::WA_StyledBackground)) {
- painter->setClipRegion(rgn);
- QStyleOption opt;
- opt.initFrom(q);
- q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
- }
-
-#ifndef QT_NO_SCROLLAREA
- if (resetBrushOrigin)
- painter->setBrushOrigin(oldBrushOrigin);
-#endif // QT_NO_SCROLLAREA
-}
-
-/*
- \internal
- This function is called when a widget is hidden or destroyed.
- It resets some application global pointers that should only refer active,
- visible widgets.
-*/
-
-#ifdef Q_WS_MAC
- extern QPointer<QWidget> qt_button_down;
-#else
- extern QWidget *qt_button_down;
-#endif
-
-void QWidgetPrivate::deactivateWidgetCleanup()
-{
- Q_Q(QWidget);
- // If this was the active application window, reset it
- if (QApplication::activeWindow() == q)
- QApplication::setActiveWindow(0);
- // If the is the active mouse press widget, reset it
- if (q == qt_button_down)
- qt_button_down = 0;
-}
-
-
-/*!
- Returns a pointer to the widget with window identifer/handle \a
- id.
-
- The window identifier type depends on the underlying window
- system, see \c qwindowdefs.h for the actual definition. If there
- is no widget with this identifier, 0 is returned.
-*/
-
-QWidget *QWidget::find(WId id)
-{
- return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
-}
-
-
-
-/*!
- \fn WId QWidget::internalWinId() const
- \internal
- Returns the window system identifier of the widget, or 0 if the widget is not created yet.
-
-*/
-
-/*!
- \fn WId QWidget::winId() const
-
- Returns the window system identifier of the widget.
-
- Portable in principle, but if you use it you are probably about to
- do something non-portable. Be careful.
-
- If a widget is non-native (alien) and winId() is invoked on it, that widget
- will be provided a native handle.
-
- On Mac OS X, the type returned depends on which framework Qt was linked
- against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
- is using Cocoa, {WId} is a pointer to an NSView.
-
- This value may change at run-time. An event with type QEvent::WinIdChange
- will be sent to the widget following a change in window system identifier.
-
- \sa find()
-*/
-WId QWidget::winId() const
-{
- if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidget::winId: creating native window for" << this;
-#endif
- QWidget *that = const_cast<QWidget*>(this);
-#ifndef Q_WS_QPA
- that->setAttribute(Qt::WA_NativeWindow);
-#endif
- that->d_func()->createWinId();
- return that->data->winid;
- }
- return data->winid;
-}
-
-
-void QWidgetPrivate::createWinId(WId winid)
-{
- Q_Q(QWidget);
-
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
-#endif
- const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
- if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
-#ifndef Q_WS_QPA
- if (!q->isWindow()) {
- QWidget *parent = q->parentWidget();
- QWidgetPrivate *pd = parent->d_func();
- if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
- parent->setAttribute(Qt::WA_NativeWindow);
- if (!parent->internalWinId()) {
- pd->createWinId();
- }
-
- for (int i = 0; i < pd->children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
- if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
- || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
- if (w!=q) {
- w->create();
- } else {
- w->create(winid);
- // if the window has already been created, we
- // need to raise it to its proper stacking position
- if (winid)
- w->raise();
- }
- }
- }
- } else {
- q->create();
- }
-#else
- Q_UNUSED(winid);
- q->create();
-#endif //Q_WS_QPA
-
- }
-}
-
-
-/*!
-\internal
-Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
-
-*/
-
-void QWidget::createWinId()
-{
- Q_D(QWidget);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidget::createWinId" << this;
-#endif
-// qWarning("QWidget::createWinId is obsolete, please fix your code.");
- d->createWinId();
-}
-
-/*!
- \since 4.4
-
- Returns the effective window system identifier of the widget, i.e. the
- native parent's window system identifier.
-
- If the widget is native, this function returns the native widget ID.
- Otherwise, the window ID of the first native parent widget, i.e., the
- top-level widget that contains this widget, is returned.
-
- \note We recommend that you do not store this value as it is likely to
- change at run-time.
-
- \sa nativeParentWidget()
-*/
-WId QWidget::effectiveWinId() const
-{
- WId id = internalWinId();
- if (id || !testAttribute(Qt::WA_WState_Created))
- return id;
- QWidget *realParent = nativeParentWidget();
- Q_ASSERT(realParent);
- Q_ASSERT(realParent->internalWinId());
- return realParent->internalWinId();
-}
-
-#ifndef QT_NO_STYLE_STYLESHEET
-
-/*!
- \property QWidget::styleSheet
- \brief the widget's style sheet
- \since 4.2
-
- The style sheet contains a textual description of customizations to the
- widget's style, as described in the \l{Qt Style Sheets} document.
-
- Since Qt 4.5, Qt style sheets fully supports Mac OS X.
-
- \warning Qt style sheets are currently not supported for custom QStyle
- subclasses. We plan to address this in some future release.
-
- \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
-*/
-QString QWidget::styleSheet() const
-{
- Q_D(const QWidget);
- if (!d->extra)
- return QString();
- return d->extra->styleSheet;
-}
-
-void QWidget::setStyleSheet(const QString& styleSheet)
-{
- Q_D(QWidget);
- d->createExtra();
-
- QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
- d->extra->styleSheet = styleSheet;
- if (styleSheet.isEmpty()) { // stylesheet removed
- if (!proxy)
- return;
-
- d->inheritStyle();
- return;
- }
-
- if (proxy) { // style sheet update
- proxy->repolish(this);
- return;
- }
-
- if (testAttribute(Qt::WA_SetStyle)) {
- d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
- } else {
- d->setStyle_helper(new QStyleSheetStyle(0), true);
- }
-}
-
-#endif // QT_NO_STYLE_STYLESHEET
-
-/*!
- \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
-*/
-
-QStyle *QWidget::style() const
-{
- Q_D(const QWidget);
-
- if (d->extra && d->extra->style)
- return d->extra->style;
- return QApplication::style();
-}
-
-/*!
- Sets the widget's GUI style to \a style. The ownership of the style
- object is not transferred.
-
- If no style is set, the widget uses the application's style,
- QApplication::style() instead.
-
- Setting a widget's style has no effect on existing or future child
- widgets.
-
- \warning This function is particularly useful for demonstration
- purposes, where you want to show Qt's styling capabilities. Real
- applications should avoid it and use one consistent GUI style
- instead.
-
- \warning Qt style sheets are currently not supported for custom QStyle
- subclasses. We plan to address this in some future release.
-
- \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
-*/
-
-void QWidget::setStyle(QStyle *style)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_SetStyle, style != 0);
- d->createExtra();
-#ifndef QT_NO_STYLE_STYLESHEET
- if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
- //if for some reason someone try to set a QStyleSheetStyle, ref it
- //(this may happen for exemple in QButtonDialogBox which propagates its style)
- proxy->ref();
- d->setStyle_helper(style, false);
- } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
- // if we have an application stylesheet or have a proxy already, propagate
- d->setStyle_helper(new QStyleSheetStyle(style), true);
- } else
-#endif
- d->setStyle_helper(style, false);
-}
-
-void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
-#ifdef Q_WS_MAC
- metalHack
-#endif
- )
-{
- Q_Q(QWidget);
- QStyle *oldStyle = q->style();
-#ifndef QT_NO_STYLE_STYLESHEET
- QWeakPointer<QStyle> origStyle;
-#endif
-
-#ifdef Q_WS_MAC
- // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
- // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
- // set when changing that attribute and passes the widget's CURRENT style.
- // therefore no need to do a reassignment.
- if (!metalHack)
-#endif
- {
- createExtra();
-
-#ifndef QT_NO_STYLE_STYLESHEET
- origStyle = extra->style.data();
-#endif
- extra->style = newStyle;
- }
-
- // repolish
- if (q->windowType() != Qt::Desktop) {
- if (polished) {
- oldStyle->unpolish(q);
-#ifdef Q_WS_MAC
- if (metalHack)
- macUpdateMetalAttribute();
-#endif
- q->style()->polish(q);
-#ifdef Q_WS_MAC
- } else if (metalHack) {
- macUpdateMetalAttribute();
-#endif
- }
- }
-
- if (propagate) {
- for (int i = 0; i < children.size(); ++i) {
- QWidget *c = qobject_cast<QWidget*>(children.at(i));
- if (c)
- c->d_func()->inheritStyle();
- }
- }
-
-#ifndef QT_NO_STYLE_STYLESHEET
- if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
- if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
- cssStyle->clearWidgetFont(q);
- }
- }
-#endif
-
- QEvent e(QEvent::StyleChange);
- QApplication::sendEvent(q, &e);
-#ifdef QT3_SUPPORT
- q->styleChange(*oldStyle);
-#endif
-
-#ifndef QT_NO_STYLE_STYLESHEET
- // dereference the old stylesheet style
- if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
- proxy->deref();
-#endif
-}
-
-// Inherits style from the current parent and propagates it as necessary
-void QWidgetPrivate::inheritStyle()
-{
-#ifndef QT_NO_STYLE_STYLESHEET
- Q_Q(QWidget);
-
- QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
-
- if (!q->styleSheet().isEmpty()) {
- Q_ASSERT(proxy);
- proxy->repolish(q);
- return;
- }
-
- QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
- QWidget *parent = q->parentWidget();
- QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
- // If we have stylesheet on app or parent has stylesheet style, we need
- // to be running a proxy
- if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
- QStyle *newStyle = parentStyle;
- if (q->testAttribute(Qt::WA_SetStyle))
- newStyle = new QStyleSheetStyle(origStyle);
- else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
- newProxy->ref();
-
- setStyle_helper(newStyle, true);
- return;
- }
-
- // So, we have no stylesheet on parent/app and we have an empty stylesheet
- // we just need our original style back
- if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
- return;
-
- // We could have inherited the proxy from our parent (which has a custom style)
- // In such a case we need to start following the application style (i.e revert
- // the propagation behavior of QStyleSheetStyle)
- if (!q->testAttribute(Qt::WA_SetStyle))
- origStyle = 0;
-
- setStyle_helper(origStyle, true);
-#endif // QT_NO_STYLE_STYLESHEET
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \overload
-
- Sets the widget's GUI style to \a style using the QStyleFactory.
-*/
-QStyle* QWidget::setStyle(const QString &style)
-{
- QStyle *s = QStyleFactory::create(style);
- setStyle(s);
- return s;
-}
-#endif
-
-/*!
- \fn bool QWidget::isWindow() const
-
- Returns true if the widget is an independent window, otherwise
- returns false.
-
- A window is a widget that isn't visually the child of any other
- widget and that usually has a frame and a
- \l{QWidget::setWindowTitle()}{window title}.
-
- A window can have a \l{QWidget::parentWidget()}{parent widget}.
- It will then be grouped with its parent and deleted when the
- parent is deleted, minimized when the parent is minimized etc. If
- supported by the window manager, it will also have a common
- taskbar entry with its parent.
-
- QDialog and QMainWindow widgets are by default windows, even if a
- parent widget is specified in the constructor. This behavior is
- specified by the Qt::Window flag.
-
- \sa window(), isModal(), parentWidget()
-*/
-
-/*!
- \property QWidget::modal
- \brief whether the widget is a modal widget
-
- This property only makes sense for windows. A modal widget
- prevents widgets in all other windows from getting any input.
-
- By default, this property is false.
-
- \sa isWindow(), windowModality, QDialog
-*/
-
-/*!
- \property QWidget::windowModality
- \brief which windows are blocked by the modal widget
- \since 4.1
-
- This property only makes sense for windows. A modal widget
- prevents widgets in other windows from getting input. The value of
- this property controls which windows are blocked when the widget
- is visible. Changing this property while the window is visible has
- no effect; you must hide() the widget first, then show() it again.
-
- By default, this property is Qt::NonModal.
-
- \sa isWindow(), QWidget::modal, QDialog
-*/
-
-Qt::WindowModality QWidget::windowModality() const
-{
- return static_cast<Qt::WindowModality>(data->window_modality);
-}
-
-void QWidget::setWindowModality(Qt::WindowModality windowModality)
-{
- data->window_modality = windowModality;
- // setModal_sys() will be called by setAttribute()
- setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
- setAttribute(Qt::WA_SetWindowModality, true);
-}
-
-/*!
- \fn bool QWidget::underMouse() const
-
- Returns true if the widget is under the mouse cursor; otherwise
- returns false.
-
- This value is not updated properly during drag and drop
- operations.
-
- \sa enterEvent(), leaveEvent()
-*/
-
-/*!
- \property QWidget::minimized
- \brief whether this widget is minimized (iconified)
-
- This property is only relevant for windows.
-
- By default, this property is false.
-
- \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
-*/
-bool QWidget::isMinimized() const
-{ return data->window_state & Qt::WindowMinimized; }
-
-/*!
- Shows the widget minimized, as an icon.
-
- Calling this function only affects \l{isWindow()}{windows}.
-
- \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
- isMinimized()
-*/
-void QWidget::showMinimized()
-{
- bool isMin = isMinimized();
- if (isMin && isVisible())
- return;
-
- ensurePolished();
-#ifdef QT3_SUPPORT
- if (parent())
- QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
-#endif
-
- if (!isMin)
- setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
- show();
-}
-
-/*!
- \property QWidget::maximized
- \brief whether this widget is maximized
-
- This property is only relevant for windows.
-
- \note Due to limitations on some window systems, this does not always
- report the expected results (e.g., if the user on X11 maximizes the
- window via the window manager, Qt has no way of distinguishing this
- from any other resize). This is expected to improve as window manager
- protocols evolve.
-
- By default, this property is false.
-
- \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
-*/
-bool QWidget::isMaximized() const
-{ return data->window_state & Qt::WindowMaximized; }
-
-
-
-/*!
- Returns the current window state. The window state is a OR'ed
- combination of Qt::WindowState: Qt::WindowMinimized,
- Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
-
- \sa Qt::WindowState setWindowState()
- */
-Qt::WindowStates QWidget::windowState() const
-{
- return Qt::WindowStates(data->window_state);
-}
-
-/*!\internal
-
- The function sets the window state on child widgets similar to
- setWindowState(). The difference is that the window state changed
- event has the isOverride() flag set. It exists mainly to keep
- Q3Workspace working.
- */
-void QWidget::overrideWindowState(Qt::WindowStates newstate)
-{
- QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
- data->window_state = newstate;
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- \fn void QWidget::setWindowState(Qt::WindowStates windowState)
-
- Sets the window state to \a windowState. The window state is a OR'ed
- combination of Qt::WindowState: Qt::WindowMinimized,
- Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
-
- If the window is not visible (i.e. isVisible() returns false), the
- window state will take effect when show() is called. For visible
- windows, the change is immediate. For example, to toggle between
- full-screen and normal mode, use the following code:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
-
- In order to restore and activate a minimized window (while
- preserving its maximized and/or full-screen state), use the following:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
-
- Calling this function will hide the widget. You must call show() to make
- the widget visible again.
-
- \note On some window systems Qt::WindowActive is not immediate, and may be
- ignored in certain cases.
-
- When the window state changes, the widget receives a changeEvent()
- of type QEvent::WindowStateChange.
-
- \sa Qt::WindowState windowState()
-*/
-
-/*!
- \property QWidget::fullScreen
- \brief whether the widget is shown in full screen mode
-
- A widget in full screen mode occupies the whole screen area and does not
- display window decorations, such as a title bar.
-
- By default, this property is false.
-
- \sa windowState(), minimized, maximized
-*/
-bool QWidget::isFullScreen() const
-{ return data->window_state & Qt::WindowFullScreen; }
-
-/*!
- Shows the widget in full-screen mode.
-
- Calling this function only affects \l{isWindow()}{windows}.
-
- To return from full-screen mode, call showNormal().
-
- Full-screen mode works fine under Windows, but has certain
- problems under X. These problems are due to limitations of the
- ICCCM protocol that specifies the communication between X11
- clients and the window manager. ICCCM simply does not understand
- the concept of non-decorated full-screen windows. Therefore, the
- best we can do is to request a borderless window and place and
- resize it to fill the entire screen. Depending on the window
- manager, this may or may not work. The borderless window is
- requested using MOTIF hints, which are at least partially
- supported by virtually all modern window managers.
-
- An alternative would be to bypass the window manager entirely and
- create a window with the Qt::X11BypassWindowManagerHint flag. This
- has other severe problems though, like totally broken keyboard focus
- and very strange effects on desktop changes or when the user raises
- other windows.
-
- X11 window managers that follow modern post-ICCCM specifications
- support full-screen mode properly.
-
- \sa showNormal(), showMaximized(), show(), hide(), isVisible()
-*/
-void QWidget::showFullScreen()
-{
-#ifdef Q_WS_MAC
- // If the unified toolbar is enabled, we have to disable it before going fullscreen.
- QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
- if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
- mainWindow->setUnifiedTitleAndToolBarOnMac(false);
- QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
- mainLayout->activateUnifiedToolbarAfterFullScreen = true;
- }
-#endif // Q_WS_MAC
- ensurePolished();
-#ifdef QT3_SUPPORT
- if (parent())
- QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
-#endif
-
- setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
- | Qt::WindowFullScreen);
- show();
- activateWindow();
-}
-
-/*!
- Shows the widget maximized.
-
- Calling this function only affects \l{isWindow()}{windows}.
-
- On X11, this function may not work properly with certain window
- managers. See the \l{Window Geometry} documentation for an explanation.
-
- \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
-*/
-void QWidget::showMaximized()
-{
- ensurePolished();
-#ifdef QT3_SUPPORT
- if (parent())
- QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
-#endif
-
- setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
- | Qt::WindowMaximized);
-#ifdef Q_WS_MAC
- // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
- QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
- if (mainWindow)
- {
- QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
- if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
- mainWindow->setUnifiedTitleAndToolBarOnMac(true);
- mainLayout->activateUnifiedToolbarAfterFullScreen = false;
- }
- }
-#endif // Q_WS_MAC
- show();
-}
-
-/*!
- Restores the widget after it has been maximized or minimized.
-
- Calling this function only affects \l{isWindow()}{windows}.
-
- \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
-*/
-void QWidget::showNormal()
-{
- ensurePolished();
-#ifdef QT3_SUPPORT
- if (parent())
- QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
-#endif
-
- setWindowState(windowState() & ~(Qt::WindowMinimized
- | Qt::WindowMaximized
- | Qt::WindowFullScreen));
-#ifdef Q_WS_MAC
- // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
- QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
- if (mainWindow)
- {
- QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
- if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
- mainWindow->setUnifiedTitleAndToolBarOnMac(true);
- mainLayout->activateUnifiedToolbarAfterFullScreen = false;
- }
- }
-#endif // Q_WS_MAC
- show();
-}
-
-/*!
- Returns true if this widget would become enabled if \a ancestor is
- enabled; otherwise returns false.
-
-
-
- This is the case if neither the widget itself nor every parent up
- to but excluding \a ancestor has been explicitly disabled.
-
- isEnabledTo(0) is equivalent to isEnabled().
-
- \sa setEnabled() enabled
-*/
-
-bool QWidget::isEnabledTo(QWidget* ancestor) const
-{
- const QWidget * w = this;
- while (!w->testAttribute(Qt::WA_ForceDisabled)
- && !w->isWindow()
- && w->parentWidget()
- && w->parentWidget() != ancestor)
- w = w->parentWidget();
- return !w->testAttribute(Qt::WA_ForceDisabled);
-}
-
-#ifndef QT_NO_ACTION
-/*!
- Appends the action \a action to this widget's list of actions.
-
- All QWidgets have a list of \l{QAction}s, however they can be
- represented graphically in many different ways. The default use of
- the QAction list (as returned by actions()) is to create a context
- QMenu.
-
- A QWidget should only have one of each action and adding an action
- it already has will not cause the same action to be in the widget twice.
-
- The ownership of \a action is not transferred to this QWidget.
-
- \sa removeAction(), insertAction(), actions(), QMenu
-*/
-void QWidget::addAction(QAction *action)
-{
- insertAction(0, action);
-}
-
-/*!
- Appends the actions \a actions to this widget's list of actions.
-
- \sa removeAction(), QMenu, addAction()
-*/
-void QWidget::addActions(QList<QAction*> actions)
-{
- for(int i = 0; i < actions.count(); i++)
- insertAction(0, actions.at(i));
-}
-
-/*!
- Inserts the action \a action to this widget's list of actions,
- before the action \a before. It appends the action if \a before is 0 or
- \a before is not a valid action for this widget.
-
- A QWidget should only have one of each action.
-
- \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
-*/
-void QWidget::insertAction(QAction *before, QAction *action)
-{
- if(!action) {
- qWarning("QWidget::insertAction: Attempt to insert null action");
- return;
- }
-
- Q_D(QWidget);
- if(d->actions.contains(action))
- removeAction(action);
-
- int pos = d->actions.indexOf(before);
- if (pos < 0) {
- before = 0;
- pos = d->actions.size();
- }
- d->actions.insert(pos, action);
-
- QActionPrivate *apriv = action->d_func();
- apriv->widgets.append(this);
-
- QActionEvent e(QEvent::ActionAdded, action, before);
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- Inserts the actions \a actions to this widget's list of actions,
- before the action \a before. It appends the action if \a before is 0 or
- \a before is not a valid action for this widget.
-
- A QWidget can have at most one of each action.
-
- \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
-*/
-void QWidget::insertActions(QAction *before, QList<QAction*> actions)
-{
- for(int i = 0; i < actions.count(); ++i)
- insertAction(before, actions.at(i));
-}
-
-/*!
- Removes the action \a action from this widget's list of actions.
- \sa insertAction(), actions(), insertAction()
-*/
-void QWidget::removeAction(QAction *action)
-{
- if (!action)
- return;
-
- Q_D(QWidget);
-
- QActionPrivate *apriv = action->d_func();
- apriv->widgets.removeAll(this);
-
- if (d->actions.removeAll(action)) {
- QActionEvent e(QEvent::ActionRemoved, action);
- QApplication::sendEvent(this, &e);
- }
-}
-
-/*!
- Returns the (possibly empty) list of this widget's actions.
-
- \sa contextMenuPolicy, insertAction(), removeAction()
-*/
-QList<QAction*> QWidget::actions() const
-{
- Q_D(const QWidget);
- return d->actions;
-}
-#endif // QT_NO_ACTION
-
-/*!
- \fn bool QWidget::isEnabledToTLW() const
- \obsolete
-
- This function is deprecated. It is equivalent to isEnabled()
-*/
-
-/*!
- \property QWidget::enabled
- \brief whether the widget is enabled
-
- An enabled widget handles keyboard and mouse events; a disabled
- widget does not.
-
- Some widgets display themselves differently when they are
- disabled. For example a button might draw its label grayed out. If
- your widget needs to know when it becomes enabled or disabled, you
- can use the changeEvent() with type QEvent::EnabledChange.
-
- Disabling a widget implicitly disables all its children. Enabling
- respectively enables all child widgets unless they have been
- explicitly disabled.
-
- By default, this property is true.
-
- \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
-*/
-void QWidget::setEnabled(bool enable)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_ForceDisabled, !enable);
- d->setEnabled_helper(enable);
-}
-
-void QWidgetPrivate::setEnabled_helper(bool enable)
-{
- Q_Q(QWidget);
-
- if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
- return; // nothing we can do
-
- if (enable != q->testAttribute(Qt::WA_Disabled))
- return; // nothing to do
-
- q->setAttribute(Qt::WA_Disabled, !enable);
- updateSystemBackground();
-
- if (!enable && q->window()->focusWidget() == q) {
- bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
- if (!parentIsEnabled || !q->focusNextChild())
- q->clearFocus();
- }
-
- Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(children.at(i));
- if (w && !w->testAttribute(attribute))
- w->d_func()->setEnabled_helper(enable);
- }
-#if defined(Q_WS_X11)
- if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
- // enforce the windows behavior of clearing the cursor on
- // disabled widgets
- qt_x11_enforce_cursor(q);
- }
-#endif
-#if defined(Q_WS_MAC)
- setEnabled_helper_sys(enable);
-#endif
-#ifndef QT_NO_IM
- if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
- QWidget *focusWidget = effectiveFocusWidget();
- QInputContext *qic = focusWidget->d_func()->inputContext();
- if (enable) {
- if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
- qic->setFocusWidget(focusWidget);
- } else {
- qic->reset();
- qic->setFocusWidget(0);
- }
- }
-#endif //QT_NO_IM
- QEvent e(QEvent::EnabledChange);
- QApplication::sendEvent(q, &e);
-#ifdef QT3_SUPPORT
- q->enabledChange(!enable); // compatibility
-#endif
-}
-
-/*!
- \property QWidget::acceptDrops
- \brief whether drop events are enabled for this widget
-
- Setting this property to true announces to the system that this
- widget \e may be able to accept drop events.
-
- If the widget is the desktop (windowType() == Qt::Desktop), this may
- fail if another application is using the desktop; you can call
- acceptDrops() to test if this occurs.
-
- \warning Do not modify this property in a drag and drop event handler.
-
- By default, this property is false.
-
- \sa {Drag and Drop}
-*/
-bool QWidget::acceptDrops() const
-{
- return testAttribute(Qt::WA_AcceptDrops);
-}
-
-void QWidget::setAcceptDrops(bool on)
-{
- setAttribute(Qt::WA_AcceptDrops, on);
-
-}
-
-/*!
- \fn void QWidget::enabledChange(bool)
-
- \internal
- \obsolete
-*/
-
-/*!
- \fn void QWidget::paletteChange(const QPalette &)
-
- \internal
- \obsolete
-*/
-
-/*!
- \fn void QWidget::fontChange(const QFont &)
-
- \internal
- \obsolete
-*/
-
-/*!
- \fn void QWidget::windowActivationChange(bool)
-
- \internal
- \obsolete
-*/
-
-/*!
- \fn void QWidget::languageChange()
-
- \obsolete
-*/
-
-/*!
- \fn void QWidget::styleChange(QStyle& style)
-
- \internal
- \obsolete
-*/
-
-/*!
- Disables widget input events if \a disable is true; otherwise
- enables input events.
-
- See the \l enabled documentation for more information.
-
- \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
-*/
-void QWidget::setDisabled(bool disable)
-{
- setEnabled(!disable);
-}
-
-/*!
- \property QWidget::frameGeometry
- \brief geometry of the widget relative to its parent including any
- window frame
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-
- \sa geometry() x() y() pos()
-*/
-QRect QWidget::frameGeometry() const
-{
- Q_D(const QWidget);
- if (isWindow() && ! (windowType() == Qt::Popup)) {
- QRect fs = d->frameStrut();
- return QRect(data->crect.x() - fs.left(),
- data->crect.y() - fs.top(),
- data->crect.width() + fs.left() + fs.right(),
- data->crect.height() + fs.top() + fs.bottom());
- }
- return data->crect;
-}
-
-/*!
- \property QWidget::x
-
- \brief the x coordinate of the widget relative to its parent including
- any window frame
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- By default, this property has a value of 0.
-
- \sa frameGeometry, y, pos
-*/
-int QWidget::x() const
-{
- Q_D(const QWidget);
- if (isWindow() && ! (windowType() == Qt::Popup))
- return data->crect.x() - d->frameStrut().left();
- return data->crect.x();
-}
-
-/*!
- \property QWidget::y
- \brief the y coordinate of the widget relative to its parent and
- including any window frame
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- By default, this property has a value of 0.
-
- \sa frameGeometry, x, pos
-*/
-int QWidget::y() const
-{
- Q_D(const QWidget);
- if (isWindow() && ! (windowType() == Qt::Popup))
- return data->crect.y() - d->frameStrut().top();
- return data->crect.y();
-}
-
-/*!
- \property QWidget::pos
- \brief the position of the widget within its parent widget
-
- If the widget is a window, the position is that of the widget on
- the desktop, including its frame.
-
- When changing the position, the widget, if visible, receives a
- move event (moveEvent()) immediately. If the widget is not
- currently visible, it is guaranteed to receive an event before it
- is shown.
-
- By default, this property contains a position that refers to the
- origin.
-
- \warning Calling move() or setGeometry() inside moveEvent() can
- lead to infinite recursion.
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- \sa frameGeometry, size x(), y()
-*/
-QPoint QWidget::pos() const
-{
- Q_D(const QWidget);
- if (isWindow() && ! (windowType() == Qt::Popup)) {
- QRect fs = d->frameStrut();
- return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
- }
- return data->crect.topLeft();
-}
-
-/*!
- \property QWidget::geometry
- \brief the geometry of the widget relative to its parent and
- excluding the window frame
-
- When changing the geometry, the widget, if visible, receives a
- move event (moveEvent()) and/or a resize event (resizeEvent())
- immediately. If the widget is not currently visible, it is
- guaranteed to receive appropriate events before it is shown.
-
- The size component is adjusted if it lies outside the range
- defined by minimumSize() and maximumSize().
-
- \warning Calling setGeometry() inside resizeEvent() or moveEvent()
- can lead to infinite recursion.
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-
- \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
- resizeEvent(), minimumSize(), maximumSize()
-*/
-
-/*!
- \property QWidget::normalGeometry
-
- \brief the geometry of the widget as it will appear when shown as
- a normal (not maximized or full screen) top-level widget
-
- For child widgets this property always holds an empty rectangle.
-
- By default, this property contains an empty rectangle.
-
- \sa QWidget::windowState(), QWidget::geometry
-*/
-
-/*!
- \property QWidget::size
- \brief the size of the widget excluding any window frame
-
- If the widget is visible when it is being resized, it receives a resize event
- (resizeEvent()) immediately. If the widget is not currently
- visible, it is guaranteed to receive an event before it is shown.
-
- The size is adjusted if it lies outside the range defined by
- minimumSize() and maximumSize().
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-
- \warning Calling resize() or setGeometry() inside resizeEvent() can
- lead to infinite recursion.
-
- \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
- appear on screen. This also applies to windows.
-
- \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
-*/
-
-/*!
- \property QWidget::width
- \brief the width of the widget excluding any window frame
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- \note Do not use this function to find the width of a screen on
- a \l{QDesktopWidget}{multiple screen desktop}. Read
- \l{QDesktopWidget#Screen Geometry}{this note} for details.
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-
- \sa geometry, height, size
-*/
-
-/*!
- \property QWidget::height
- \brief the height of the widget excluding any window frame
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- \note Do not use this function to find the height of a screen
- on a \l{QDesktopWidget}{multiple screen desktop}. Read
- \l{QDesktopWidget#Screen Geometry}{this note} for details.
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-
- \sa geometry, width, size
-*/
-
-/*!
- \property QWidget::rect
- \brief the internal geometry of the widget excluding any window
- frame
-
- The rect property equals QRect(0, 0, width(), height()).
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-
- \sa size
-*/
-
-
-QRect QWidget::normalGeometry() const
-{
- Q_D(const QWidget);
- if (!d->extra || !d->extra->topextra)
- return QRect();
-
- if (!isMaximized() && !isFullScreen())
- return geometry();
-
- return d->topData()->normalGeometry;
-}
-
-
-/*!
- \property QWidget::childrenRect
- \brief the bounding rectangle of the widget's children
-
- Hidden children are excluded.
-
- By default, for a widget with no children, this property contains a
- rectangle with zero width and height located at the origin.
-
- \sa childrenRegion() geometry()
-*/
-
-QRect QWidget::childrenRect() const
-{
- Q_D(const QWidget);
- QRect r(0, 0, 0, 0);
- for (int i = 0; i < d->children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
- if (w && !w->isWindow() && !w->isHidden())
- r |= w->geometry();
- }
- return r;
-}
-
-/*!
- \property QWidget::childrenRegion
- \brief the combined region occupied by the widget's children
-
- Hidden children are excluded.
-
- By default, for a widget with no children, this property contains an
- empty region.
-
- \sa childrenRect() geometry() mask()
-*/
-
-QRegion QWidget::childrenRegion() const
-{
- Q_D(const QWidget);
- QRegion r;
- for (int i = 0; i < d->children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
- if (w && !w->isWindow() && !w->isHidden()) {
- QRegion mask = w->mask();
- if (mask.isEmpty())
- r |= w->geometry();
- else
- r |= mask.translated(w->pos());
- }
- }
- return r;
-}
-
-
-/*!
- \property QWidget::minimumSize
- \brief the widget's minimum size
-
- The widget cannot be resized to a smaller size than the minimum
- widget size. The widget's size is forced to the minimum size if
- the current size is smaller.
-
- The minimum size set by this function will override the minimum size
- defined by QLayout. In order to unset the minimum size, use a
- value of \c{QSize(0, 0)}.
-
- By default, this property contains a size with zero width and height.
-
- \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
-*/
-
-QSize QWidget::minimumSize() const
-{
- Q_D(const QWidget);
- return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
-}
-
-/*!
- \property QWidget::maximumSize
- \brief the widget's maximum size in pixels
-
- The widget cannot be resized to a larger size than the maximum
- widget size.
-
- By default, this property contains a size in which both width and height
- have values of 16777215.
-
- \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
- of widgets.
-
- \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
-*/
-
-QSize QWidget::maximumSize() const
-{
- Q_D(const QWidget);
- return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
- : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
-}
-
-
-/*!
- \property QWidget::minimumWidth
- \brief the widget's minimum width in pixels
-
- This property corresponds to the width held by the \l minimumSize property.
-
- By default, this property has a value of 0.
-
- \sa minimumSize, minimumHeight
-*/
-
-/*!
- \property QWidget::minimumHeight
- \brief the widget's minimum height in pixels
-
- This property corresponds to the height held by the \l minimumSize property.
-
- By default, this property has a value of 0.
-
- \sa minimumSize, minimumWidth
-*/
-
-/*!
- \property QWidget::maximumWidth
- \brief the widget's maximum width in pixels
-
- This property corresponds to the width held by the \l maximumSize property.
-
- By default, this property contains a value of 16777215.
-
- \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
- of widgets.
-
- \sa maximumSize, maximumHeight
-*/
-
-/*!
- \property QWidget::maximumHeight
- \brief the widget's maximum height in pixels
-
- This property corresponds to the height held by the \l maximumSize property.
-
- By default, this property contains a value of 16777215.
-
- \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
- of widgets.
-
- \sa maximumSize, maximumWidth
-*/
-
-/*!
- \property QWidget::sizeIncrement
- \brief the size increment of the widget
-
- When the user resizes the window, the size will move in steps of
- sizeIncrement().width() pixels horizontally and
- sizeIncrement.height() pixels vertically, with baseSize() as the
- basis. Preferred widget sizes are for non-negative integers \e i
- and \e j:
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
-
- Note that while you can set the size increment for all widgets, it
- only affects windows.
-
- By default, this property contains a size with zero width and height.
-
- \warning The size increment has no effect under Windows, and may
- be disregarded by the window manager on X11.
-
- \sa size, minimumSize, maximumSize
-*/
-QSize QWidget::sizeIncrement() const
-{
- Q_D(const QWidget);
- return (d->extra && d->extra->topextra)
- ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
- : QSize(0, 0);
-}
-
-/*!
- \property QWidget::baseSize
- \brief the base size of the widget
-
- The base size is used to calculate a proper widget size if the
- widget defines sizeIncrement().
-
- By default, for a newly-created widget, this property contains a size with
- zero width and height.
-
- \sa setSizeIncrement()
-*/
-
-QSize QWidget::baseSize() const
-{
- Q_D(const QWidget);
- return (d->extra != 0 && d->extra->topextra != 0)
- ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
- : QSize(0, 0);
-}
-
-bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
-{
- Q_Q(QWidget);
-
-#ifdef Q_WS_QWS
- if (q->isWindow()) {
- const QRect maxWindowRect = QApplication::desktop()->availableGeometry(QApplication::desktop()->screenNumber(q));
- if (!maxWindowRect.isEmpty()) {
- // ### This is really just a work-around. Layout shouldn't be
- // asking for minimum sizes bigger than the screen.
- if (minw > maxWindowRect.width())
- minw = maxWindowRect.width();
- if (minh > maxWindowRect.height())
- minh = maxWindowRect.height();
- }
- }
-#endif
- int mw = minw, mh = minh;
- if (mw == QWIDGETSIZE_MAX)
- mw = 0;
- if (mh == QWIDGETSIZE_MAX)
- mh = 0;
- if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
- qWarning("QWidget::setMinimumSize: (%s/%s) "
- "The largest allowed size is (%d,%d)",
- q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
- QWIDGETSIZE_MAX);
- minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
- minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
- }
- if (minw < 0 || minh < 0) {
- qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
- "are not possible",
- q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
- minw = mw = qMax(minw, 0);
- minh = mh = qMax(minh, 0);
- }
- createExtra();
- if (extra->minw == mw && extra->minh == mh)
- return false;
- extra->minw = mw;
- extra->minh = mh;
- extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
- return true;
-}
-
-/*!
- \overload
-
- This function corresponds to setMinimumSize(QSize(minw, minh)).
- Sets the minimum width to \a minw and the minimum height to \a
- minh.
-*/
-
-void QWidget::setMinimumSize(int minw, int minh)
-{
- Q_D(QWidget);
- if (!d->setMinimumSize_helper(minw, minh))
- return;
-
- if (isWindow())
- d->setConstraints_sys();
- if (minw > width() || minh > height()) {
- bool resized = testAttribute(Qt::WA_Resized);
- bool maximized = isMaximized();
- resize(qMax(minw,width()), qMax(minh,height()));
- setAttribute(Qt::WA_Resized, resized); //not a user resize
- if (maximized)
- data->window_state = data->window_state | Qt::WindowMaximized;
- }
-#ifndef QT_NO_GRAPHICSVIEW
- if (d->extra) {
- if (d->extra->proxyWidget)
- d->extra->proxyWidget->setMinimumSize(minw, minh);
- }
-#endif
- d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
-}
-
-bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
-{
- Q_Q(QWidget);
- if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
- qWarning("QWidget::setMaximumSize: (%s/%s) "
- "The largest allowed size is (%d,%d)",
- q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
- QWIDGETSIZE_MAX);
- maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
- maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
- }
- if (maxw < 0 || maxh < 0) {
- qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
- "are not possible",
- q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
- maxw = qMax(maxw, 0);
- maxh = qMax(maxh, 0);
- }
- createExtra();
- if (extra->maxw == maxw && extra->maxh == maxh)
- return false;
- extra->maxw = maxw;
- extra->maxh = maxh;
- extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
- (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
- return true;
-}
-
-/*!
- \overload
-
- This function corresponds to setMaximumSize(QSize(\a maxw, \a
- maxh)). Sets the maximum width to \a maxw and the maximum height
- to \a maxh.
-*/
-void QWidget::setMaximumSize(int maxw, int maxh)
-{
- Q_D(QWidget);
- if (!d->setMaximumSize_helper(maxw, maxh))
- return;
-
- if (isWindow())
- d->setConstraints_sys();
- if (maxw < width() || maxh < height()) {
- bool resized = testAttribute(Qt::WA_Resized);
- resize(qMin(maxw,width()), qMin(maxh,height()));
- setAttribute(Qt::WA_Resized, resized); //not a user resize
- }
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (d->extra) {
- if (d->extra->proxyWidget)
- d->extra->proxyWidget->setMaximumSize(maxw, maxh);
- }
-#endif
-
- d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
-}
-
-/*!
- \overload
-
- Sets the x (width) size increment to \a w and the y (height) size
- increment to \a h.
-*/
-void QWidget::setSizeIncrement(int w, int h)
-{
- Q_D(QWidget);
- d->createTLExtra();
- QTLWExtra* x = d->topData();
- if (x->incw == w && x->inch == h)
- return;
- x->incw = w;
- x->inch = h;
- if (isWindow())
- d->setConstraints_sys();
-}
-
-/*!
- \overload
-
- This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
- the widgets base size to width \a basew and height \a baseh.
-*/
-void QWidget::setBaseSize(int basew, int baseh)
-{
- Q_D(QWidget);
- d->createTLExtra();
- QTLWExtra* x = d->topData();
- if (x->basew == basew && x->baseh == baseh)
- return;
- x->basew = basew;
- x->baseh = baseh;
- if (isWindow())
- d->setConstraints_sys();
-}
-
-/*!
- Sets both the minimum and maximum sizes of the widget to \a s,
- thereby preventing it from ever growing or shrinking.
-
- This will override the default size constraints set by QLayout.
-
- To remove constraints, set the size to QWIDGETSIZE_MAX.
-
- Alternatively, if you want the widget to have a
- fixed size based on its contents, you can call
- QLayout::setSizeConstraint(QLayout::SetFixedSize);
-
- \sa maximumSize, minimumSize
-*/
-
-void QWidget::setFixedSize(const QSize & s)
-{
- setFixedSize(s.width(), s.height());
-}
-
-
-/*!
- \fn void QWidget::setFixedSize(int w, int h)
- \overload
-
- Sets the width of the widget to \a w and the height to \a h.
-*/
-
-void QWidget::setFixedSize(int w, int h)
-{
- Q_D(QWidget);
-#ifdef Q_WS_QWS
- // temporary fix for 4.3.x.
- // Should move the embedded spesific contraints in setMinimumSize_helper into QLayout
- int tmpW = w;
- int tmpH = h;
- bool minSizeSet = d->setMinimumSize_helper(tmpW, tmpH);
-#else
- bool minSizeSet = d->setMinimumSize_helper(w, h);
-#endif
- bool maxSizeSet = d->setMaximumSize_helper(w, h);
- if (!minSizeSet && !maxSizeSet)
- return;
-
- if (isWindow())
- d->setConstraints_sys();
- else
- d->updateGeometry_helper(true);
-
- if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
- resize(w, h);
-}
-
-void QWidget::setMinimumWidth(int w)
-{
- Q_D(QWidget);
- d->createExtra();
- uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
- setMinimumSize(w, minimumSize().height());
- d->extra->explicitMinSize = expl;
-}
-
-void QWidget::setMinimumHeight(int h)
-{
- Q_D(QWidget);
- d->createExtra();
- uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
- setMinimumSize(minimumSize().width(), h);
- d->extra->explicitMinSize = expl;
-}
-
-void QWidget::setMaximumWidth(int w)
-{
- Q_D(QWidget);
- d->createExtra();
- uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
- setMaximumSize(w, maximumSize().height());
- d->extra->explicitMaxSize = expl;
-}
-
-void QWidget::setMaximumHeight(int h)
-{
- Q_D(QWidget);
- d->createExtra();
- uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
- setMaximumSize(maximumSize().width(), h);
- d->extra->explicitMaxSize = expl;
-}
-
-/*!
- Sets both the minimum and maximum width of the widget to \a w
- without changing the heights. Provided for convenience.
-
- \sa sizeHint() minimumSize() maximumSize() setFixedSize()
-*/
-
-void QWidget::setFixedWidth(int w)
-{
- Q_D(QWidget);
- d->createExtra();
- uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
- uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
- setMinimumSize(w, minimumSize().height());
- setMaximumSize(w, maximumSize().height());
- d->extra->explicitMinSize = explMin;
- d->extra->explicitMaxSize = explMax;
-}
-
-
-/*!
- Sets both the minimum and maximum heights of the widget to \a h
- without changing the widths. Provided for convenience.
-
- \sa sizeHint() minimumSize() maximumSize() setFixedSize()
-*/
-
-void QWidget::setFixedHeight(int h)
-{
- Q_D(QWidget);
- d->createExtra();
- uint explMin = d->extra->explicitMinSize | Qt::Vertical;
- uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
- setMinimumSize(minimumSize().width(), h);
- setMaximumSize(maximumSize().width(), h);
- d->extra->explicitMinSize = explMin;
- d->extra->explicitMaxSize = explMax;
-}
-
-
-/*!
- Translates the widget coordinate \a pos to the coordinate system
- of \a parent. The \a parent must not be 0 and must be a parent
- of the calling widget.
-
- \sa mapFrom() mapToParent() mapToGlobal() underMouse()
-*/
-
-QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
-{
- QPoint p = pos;
- if (parent) {
- const QWidget * w = this;
- while (w != parent) {
- Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
- "parent must be in parent hierarchy");
- p = w->mapToParent(p);
- w = w->parentWidget();
- }
- }
- return p;
-}
-
-
-/*!
- Translates the widget coordinate \a pos from the coordinate system
- of \a parent to this widget's coordinate system. The \a parent
- must not be 0 and must be a parent of the calling widget.
-
- \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
-*/
-
-QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
-{
- QPoint p(pos);
- if (parent) {
- const QWidget * w = this;
- while (w != parent) {
- Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
- "parent must be in parent hierarchy");
-
- p = w->mapFromParent(p);
- w = w->parentWidget();
- }
- }
- return p;
-}
-
-
-/*!
- Translates the widget coordinate \a pos to a coordinate in the
- parent widget.
-
- Same as mapToGlobal() if the widget has no parent.
-
- \sa mapFromParent() mapTo() mapToGlobal() underMouse()
-*/
-
-QPoint QWidget::mapToParent(const QPoint &pos) const
-{
- return pos + data->crect.topLeft();
-}
-
-/*!
- Translates the parent widget coordinate \a pos to widget
- coordinates.
-
- Same as mapFromGlobal() if the widget has no parent.
-
- \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
-*/
-
-QPoint QWidget::mapFromParent(const QPoint &pos) const
-{
- return pos - data->crect.topLeft();
-}
-
-
-/*!
- Returns the window for this widget, i.e. the next ancestor widget
- that has (or could have) a window-system frame.
-
- If the widget is a window, the widget itself is returned.
-
- Typical usage is changing the window title:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
-
- \sa isWindow()
-*/
-
-QWidget *QWidget::window() const
-{
- QWidget *w = (QWidget *)this;
- QWidget *p = w->parentWidget();
- while (!w->isWindow() && p) {
- w = p;
- p = p->parentWidget();
- }
- return w;
-}
-
-/*!
- \since 4.4
-
- Returns the native parent for this widget, i.e. the next ancestor widget
- that has a system identifier, or 0 if it does not have any native parent.
-
- \sa effectiveWinId()
-*/
-QWidget *QWidget::nativeParentWidget() const
-{
- QWidget *parent = parentWidget();
- while (parent && !parent->internalWinId())
- parent = parent->parentWidget();
- return parent;
-}
-
-/*! \fn QWidget *QWidget::topLevelWidget() const
- \obsolete
-
- Use window() instead.
-*/
-
-#ifdef QT3_SUPPORT
-/*!
- Returns the color role used for painting the widget's background.
-
- Use QPalette(backgroundRole(()) instead.
-*/
-Qt::BackgroundMode QWidget::backgroundMode() const
-{
- if (testAttribute(Qt::WA_NoSystemBackground))
- return Qt::NoBackground;
- switch(backgroundRole()) {
- case QPalette::WindowText:
- return Qt::PaletteForeground;
- case QPalette::Button:
- return Qt::PaletteButton;
- case QPalette::Light:
- return Qt::PaletteLight;
- case QPalette::Midlight:
- return Qt::PaletteMidlight;
- case QPalette::Dark:
- return Qt::PaletteDark;
- case QPalette::Mid:
- return Qt::PaletteMid;
- case QPalette::Text:
- return Qt::PaletteText;
- case QPalette::BrightText:
- return Qt::PaletteBrightText;
- case QPalette::Base:
- return Qt::PaletteBase;
- case QPalette::Window:
- return Qt::PaletteBackground;
- case QPalette::Shadow:
- return Qt::PaletteShadow;
- case QPalette::Highlight:
- return Qt::PaletteHighlight;
- case QPalette::HighlightedText:
- return Qt::PaletteHighlightedText;
- case QPalette::ButtonText:
- return Qt::PaletteButtonText;
- case QPalette::Link:
- return Qt::PaletteLink;
- case QPalette::LinkVisited:
- return Qt::PaletteLinkVisited;
- default:
- break;
- }
- return Qt::NoBackground;
-}
-
-/*!
- \fn void QWidget::setBackgroundMode(Qt::BackgroundMode
- widgetBackground, Qt::BackgroundMode paletteBackground)
-
- Sets the color role used for painting the widget's background to
- background mode \a widgetBackground. The \a paletteBackground mode
- parameter is ignored.
-*/
-void QWidget::setBackgroundMode(Qt::BackgroundMode m, Qt::BackgroundMode)
-{
- Q_D(QWidget);
- if(m == Qt::NoBackground) {
- setAttribute(Qt::WA_NoSystemBackground, true);
- return;
- }
- setAttribute(Qt::WA_NoSystemBackground, false);
- d->fg_role = QPalette::NoRole;
- QPalette::ColorRole role = d->bg_role;
- switch(m) {
- case Qt::FixedColor:
- case Qt::FixedPixmap:
- break;
- case Qt::PaletteForeground:
- role = QPalette::WindowText;
- break;
- case Qt::PaletteButton:
- role = QPalette::Button;
- break;
- case Qt::PaletteLight:
- role = QPalette::Light;
- break;
- case Qt::PaletteMidlight:
- role = QPalette::Midlight;
- break;
- case Qt::PaletteDark:
- role = QPalette::Dark;
- break;
- case Qt::PaletteMid:
- role = QPalette::Mid;
- break;
- case Qt::PaletteText:
- role = QPalette::Text;
- break;
- case Qt::PaletteBrightText:
- role = QPalette::BrightText;
- break;
- case Qt::PaletteBase:
- role = QPalette::Base;
- break;
- case Qt::PaletteBackground:
- role = QPalette::Window;
- break;
- case Qt::PaletteShadow:
- role = QPalette::Shadow;
- break;
- case Qt::PaletteHighlight:
- role = QPalette::Highlight;
- break;
- case Qt::PaletteHighlightedText:
- role = QPalette::HighlightedText;
- break;
- case Qt::PaletteButtonText:
- role = QPalette::ButtonText;
- break;
- case Qt::PaletteLink:
- role = QPalette::Link;
- break;
- case Qt::PaletteLinkVisited:
- role = QPalette::LinkVisited;
- break;
- case Qt::X11ParentRelative:
- d->fg_role = role = QPalette::NoRole;
- default:
- break;
- }
- setBackgroundRole(role);
-}
-
-/*!
- The widget mapper is no longer part of the public API.
-*/
-QT3_SUPPORT QWidgetMapper *QWidget::wmapper() { return QWidgetPrivate::mapper; }
-
-#endif
-
-
-/*!
- Returns the background role of the widget.
-
- The background role defines the brush from the widget's \l palette that
- is used to render the background.
-
- If no explicit background role is set, the widget inherts its parent
- widget's background role.
-
- \sa setBackgroundRole(), foregroundRole()
- */
-QPalette::ColorRole QWidget::backgroundRole() const
-{
-
- const QWidget *w = this;
- do {
- QPalette::ColorRole role = w->d_func()->bg_role;
- if (role != QPalette::NoRole)
- return role;
- if (w->isWindow() || w->windowType() == Qt::SubWindow)
- break;
- w = w->parentWidget();
- } while (w);
- return QPalette::Window;
-}
-
-/*!
- Sets the background role of the widget to \a role.
-
- The background role defines the brush from the widget's \l palette that
- is used to render the background.
-
- If \a role is QPalette::NoRole, then the widget inherits its
- parent's background role.
-
- Note that styles are free to choose any color from the palette.
- You can modify the palette or set a style sheet if you don't
- achieve the result you want with setBackgroundRole().
-
- \sa backgroundRole(), foregroundRole()
- */
-
-void QWidget::setBackgroundRole(QPalette::ColorRole role)
-{
- Q_D(QWidget);
- d->bg_role = role;
- d->updateSystemBackground();
- d->propagatePaletteChange();
- d->updateIsOpaque();
-}
-
-/*!
- Returns the foreground role.
-
- The foreground role defines the color from the widget's \l palette that
- is used to draw the foreground.
-
- If no explicit foreground role is set, the function returns a role
- that contrasts with the background role.
-
- \sa setForegroundRole(), backgroundRole()
- */
-QPalette::ColorRole QWidget::foregroundRole() const
-{
- Q_D(const QWidget);
- QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
- if (rl != QPalette::NoRole)
- return rl;
- QPalette::ColorRole role = QPalette::WindowText;
- switch (backgroundRole()) {
- case QPalette::Button:
- role = QPalette::ButtonText;
- break;
- case QPalette::Base:
- role = QPalette::Text;
- break;
- case QPalette::Dark:
- case QPalette::Shadow:
- role = QPalette::Light;
- break;
- case QPalette::Highlight:
- role = QPalette::HighlightedText;
- break;
- case QPalette::ToolTipBase:
- role = QPalette::ToolTipText;
- break;
- default:
- ;
- }
- return role;
-}
-
-/*!
- Sets the foreground role of the widget to \a role.
-
- The foreground role defines the color from the widget's \l palette that
- is used to draw the foreground.
-
- If \a role is QPalette::NoRole, the widget uses a foreground role
- that contrasts with the background role.
-
- Note that styles are free to choose any color from the palette.
- You can modify the palette or set a style sheet if you don't
- achieve the result you want with setForegroundRole().
-
- \sa foregroundRole(), backgroundRole()
- */
-void QWidget::setForegroundRole(QPalette::ColorRole role)
-{
- Q_D(QWidget);
- d->fg_role = role;
- d->updateSystemBackground();
- d->propagatePaletteChange();
-}
-
-/*!
- \property QWidget::palette
- \brief the widget's palette
-
- This property describes the widget's palette. The palette is used by the
- widget's style when rendering standard components, and is available as a
- means to ensure that custom widgets can maintain consistency with the
- native platform's look and feel. It's common that different platforms, or
- different styles, have different palettes.
-
- When you assign a new palette to a widget, the color roles from this
- palette are combined with the widget's default palette to form the
- widget's final palette. The palette entry for the widget's background role
- is used to fill the widget's background (see QWidget::autoFillBackground),
- and the foreground role initializes QPainter's pen.
-
- The default depends on the system environment. QApplication maintains a
- system/theme palette which serves as a default for all widgets. There may
- also be special palette defaults for certain types of widgets (e.g., on
- Windows XP and Vista, all classes that derive from QMenuBar have a special
- default palette). You can also define default palettes for widgets
- yourself by passing a custom palette and the name of a widget to
- QApplication::setPalette(). Finally, the style always has the option of
- polishing the palette as it's assigned (see QStyle::polish()).
-
- QWidget propagates explicit palette roles from parent to child. If you
- assign a brush or color to a specific role on a palette and assign that
- palette to a widget, that role will propagate to all the widget's
- children, overriding any system defaults for that role. Note that palettes
- by default don't propagate to windows (see isWindow()) unless the
- Qt::WA_WindowPropagation attribute is enabled.
-
- QWidget's palette propagation is similar to its font propagation.
-
- The current style, which is used to render the content of all standard Qt
- widgets, is free to choose colors and brushes from the widget palette, or
- in some cases, to ignore the palette (partially, or completely). In
- particular, certain styles like GTK style, Mac style, Windows XP, and
- Vista style, depend on third party APIs to render the content of widgets,
- and these styles typically do not follow the palette. Because of this,
- assigning roles to a widget's palette is not guaranteed to change the
- appearance of the widget. Instead, you may choose to apply a \l
- styleSheet. You can refer to our Knowledge Base article
- \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
- information.
-
- \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".
-
- \sa QApplication::palette(), QWidget::font()
-*/
-const QPalette &QWidget::palette() const
-{
- if (!isEnabled()) {
- data->pal.setCurrentColorGroup(QPalette::Disabled);
- } else if ((!isVisible() || isActiveWindow())
-#if defined(Q_OS_WIN) && !defined(Q_WS_WINCE)
- && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
-#endif
- ) {
- data->pal.setCurrentColorGroup(QPalette::Active);
- } else {
-#ifdef Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
- if (qt_mac_can_clickThrough(this))
- data->pal.setCurrentColorGroup(QPalette::Active);
- else
-#endif
- data->pal.setCurrentColorGroup(QPalette::Inactive);
- }
- return data->pal;
-}
-
-void QWidget::setPalette(const QPalette &palette)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
-
- // Determine which palette is inherited from this widget's ancestors and
- // QApplication::palette, resolve this against \a palette (attributes from
- // the inherited palette are copied over this widget's palette). Then
- // propagate this palette to this widget's children.
- QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
- QPalette resolvedPalette = palette.resolve(naturalPalette);
- d->setPalette_helper(resolvedPalette);
-}
-
-/*!
- \internal
-
- Returns the palette that the widget \a w inherits from its ancestors and
- QApplication::palette. \a inheritedMask is the combination of the widget's
- ancestors palette request masks (i.e., which attributes from the parent
- widget's palette are implicitly imposed on this widget by the user). Note
- that this font does not take into account the palette set on \a w itself.
-*/
-QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
-{
- Q_Q(const QWidget);
- QPalette naturalPalette = QApplication::palette(q);
- if (!q->testAttribute(Qt::WA_StyleSheet)
- && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
-#ifndef QT_NO_GRAPHICSVIEW
- || (extra && extra->proxyWidget)
-#endif //QT_NO_GRAPHICSVIEW
- )) {
- if (QWidget *p = q->parentWidget()) {
- if (!p->testAttribute(Qt::WA_StyleSheet)) {
- if (!naturalPalette.isCopyOf(QApplication::palette())) {
- QPalette inheritedPalette = p->palette();
- inheritedPalette.resolve(inheritedMask);
- naturalPalette = inheritedPalette.resolve(naturalPalette);
- } else {
- naturalPalette = p->palette();
- }
- }
- }
-#ifndef QT_NO_GRAPHICSVIEW
- else if (extra && extra->proxyWidget) {
- QPalette inheritedPalette = extra->proxyWidget->palette();
- inheritedPalette.resolve(inheritedMask);
- naturalPalette = inheritedPalette.resolve(naturalPalette);
- }
-#endif //QT_NO_GRAPHICSVIEW
- }
- naturalPalette.resolve(0);
- return naturalPalette;
-}
-/*!
- \internal
-
- Determine which palette is inherited from this widget's ancestors and
- QApplication::palette, resolve this against this widget's palette
- (attributes from the inherited palette are copied over this widget's
- palette). Then propagate this palette to this widget's children.
-*/
-void QWidgetPrivate::resolvePalette()
-{
- QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
- QPalette resolvedPalette = data.pal.resolve(naturalPalette);
- setPalette_helper(resolvedPalette);
-}
-
-void QWidgetPrivate::setPalette_helper(const QPalette &palette)
-{
- Q_Q(QWidget);
- if (data.pal == palette && data.pal.resolve() == palette.resolve())
- return;
- data.pal = palette;
- updateSystemBackground();
- propagatePaletteChange();
- updateIsOpaque();
- q->update();
- updateIsOpaque();
-}
-
-/*!
- \property QWidget::font
- \brief the font currently set for the widget
-
- This property describes the widget's requested font. The font is used by
- the widget's style when rendering standard components, and is available as
- a means to ensure that custom widgets can maintain consistency with the
- native platform's look and feel. It's common that different platforms, or
- different styles, define different fonts for an application.
-
- When you assign a new font to a widget, the properties from this font are
- combined with the widget's default font to form the widget's final
- font. You can call fontInfo() to get a copy of the widget's final
- font. The final font is also used to initialize QPainter's font.
-
- The default depends on the system environment. QApplication maintains a
- system/theme font which serves as a default for all widgets. There may
- also be special font defaults for certain types of widgets. You can also
- define default fonts for widgets yourself by passing a custom font and the
- name of a widget to QApplication::setFont(). Finally, the font is matched
- against Qt's font database to find the best match.
-
- QWidget propagates explicit font properties from parent to child. If you
- change a specific property on a font and assign that font to a widget,
- that property will propagate to all the widget's children, overriding any
- system defaults for that property. Note that fonts by default don't
- propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
- attribute is enabled.
-
- QWidget's font propagation is similar to its palette propagation.
-
- The current style, which is used to render the content of all standard Qt
- widgets, is free to choose to use the widget font, or in some cases, to
- ignore it (partially, or completely). In particular, certain styles like
- GTK style, Mac style, Windows XP, and Vista style, apply special
- modifications to the widget font to match the platform's native look and
- feel. Because of this, assigning properties to a widget's font is not
- guaranteed to change the appearance of the widget. Instead, you may choose
- to apply a \l styleSheet.
-
- \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
- style sheets will take precedence if the settings conflict.
-
- \sa fontInfo(), fontMetrics()
-*/
-
-void QWidget::setFont(const QFont &font)
-{
- Q_D(QWidget);
-
-#ifndef QT_NO_STYLE_STYLESHEET
- const QStyleSheetStyle* style;
- if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
- style->saveWidgetFont(this, font);
- }
-#endif
-
- setAttribute(Qt::WA_SetFont, font.resolve() != 0);
-
- // Determine which font is inherited from this widget's ancestors and
- // QApplication::font, resolve this against \a font (attributes from the
- // inherited font are copied over). Then propagate this font to this
- // widget's children.
- QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
- QFont resolvedFont = font.resolve(naturalFont);
- d->setFont_helper(resolvedFont);
-}
-
-/*
- \internal
-
- Returns the font that the widget \a w inherits from its ancestors and
- QApplication::font. \a inheritedMask is the combination of the widget's
- ancestors font request masks (i.e., which attributes from the parent
- widget's font are implicitly imposed on this widget by the user). Note
- that this font does not take into account the font set on \a w itself.
-
- ### Stylesheet has a different font propagation mechanism. When a stylesheet
- is applied, fonts are not propagated anymore
-*/
-QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
-{
- Q_Q(const QWidget);
- QFont naturalFont = QApplication::font(q);
- if (!q->testAttribute(Qt::WA_StyleSheet)
- && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
-#ifndef QT_NO_GRAPHICSVIEW
- || (extra && extra->proxyWidget)
-#endif //QT_NO_GRAPHICSVIEW
- )) {
- if (QWidget *p = q->parentWidget()) {
- if (!p->testAttribute(Qt::WA_StyleSheet)) {
- if (!naturalFont.isCopyOf(QApplication::font())) {
- QFont inheritedFont = p->font();
- inheritedFont.resolve(inheritedMask);
- naturalFont = inheritedFont.resolve(naturalFont);
- } else {
- naturalFont = p->font();
- }
- }
- }
-#ifndef QT_NO_GRAPHICSVIEW
- else if (extra && extra->proxyWidget) {
- QFont inheritedFont = extra->proxyWidget->font();
- inheritedFont.resolve(inheritedMask);
- naturalFont = inheritedFont.resolve(naturalFont);
- }
-#endif //QT_NO_GRAPHICSVIEW
- }
- naturalFont.resolve(0);
- return naturalFont;
-}
-
-/*!
- \internal
-
- Determine which font is implicitly imposed on this widget by its ancestors
- and QApplication::font, resolve this against its own font (attributes from
- the implicit font are copied over). Then propagate this font to this
- widget's children.
-*/
-void QWidgetPrivate::resolveFont()
-{
- QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
- QFont resolvedFont = data.fnt.resolve(naturalFont);
- setFont_helper(resolvedFont);
-}
-
-/*!
- \internal
-
- Assign \a font to this widget, and propagate it to all children, except
- style sheet widgets (handled differently) and windows that don't enable
- window propagation. \a implicitMask is the union of all ancestor widgets'
- font request masks, and determines which attributes from this widget's
- font should propagate.
-*/
-void QWidgetPrivate::updateFont(const QFont &font)
-{
- Q_Q(QWidget);
-#ifndef QT_NO_STYLE_STYLESHEET
- const QStyleSheetStyle* cssStyle;
- cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
-#endif
-
-#ifdef QT3_SUPPORT
- QFont old = data.fnt;
-#endif
- data.fnt = QFont(font, q);
-#if defined(Q_WS_X11)
- // make sure the font set on this widget is associated with the correct screen
- data.fnt.x11SetScreen(xinfo.screen());
-#endif
- // Combine new mask with natural mask and propagate to children.
-#ifndef QT_NO_GRAPHICSVIEW
- if (!q->parentWidget() && extra && extra->proxyWidget) {
- QGraphicsProxyWidget *p = extra->proxyWidget;
- inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
- } else
-#endif //QT_NO_GRAPHICSVIEW
- if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
- inheritedFontResolveMask = 0;
- }
- uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
-
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget*>(children.at(i));
- if (w) {
- if (0) {
-#ifndef QT_NO_STYLE_STYLESHEET
- } else if (w->testAttribute(Qt::WA_StyleSheet)) {
- // Style sheets follow a different font propagation scheme.
- if (cssStyle)
- cssStyle->updateStyleSheetFont(w);
-#endif
- } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
- // Propagate font changes.
- QWidgetPrivate *wd = w->d_func();
- wd->inheritedFontResolveMask = newMask;
- wd->resolveFont();
- }
- }
- }
-
-#ifndef QT_NO_STYLE_STYLESHEET
- if (cssStyle) {
- cssStyle->updateStyleSheetFont(q);
- }
-#endif
-
- QEvent e(QEvent::FontChange);
- QApplication::sendEvent(q, &e);
-#ifdef QT3_SUPPORT
- q->fontChange(old);
-#endif
-}
-
-void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
-{
- Q_Q(QWidget);
-
- if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
- return;
- q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
- if (!children.isEmpty()) {
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget*>(children.at(i));
- if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
- w->d_func()->setLayoutDirection_helper(direction);
- }
- }
- QEvent e(QEvent::LayoutDirectionChange);
- QApplication::sendEvent(q, &e);
-}
-
-void QWidgetPrivate::resolveLayoutDirection()
-{
- Q_Q(const QWidget);
- if (!q->testAttribute(Qt::WA_SetLayoutDirection))
- setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
-}
-
-/*!
- \property QWidget::layoutDirection
-
- \brief the layout direction for this widget
-
- By default, this property is set to Qt::LeftToRight.
-
- When the layout direction is set on a widget, it will propagate to
- the widget's children, but not to a child that is a window and not
- to a child for which setLayoutDirection() has been explicitly
- called. Also, child widgets added \e after setLayoutDirection()
- has been called for the parent do not inherit the parent's layout
- direction.
-
- This method no longer affects text layout direction since Qt 4.7.
-
- \sa QApplication::layoutDirection
-*/
-void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
-{
- Q_D(QWidget);
-
- if (direction == Qt::LayoutDirectionAuto) {
- unsetLayoutDirection();
- return;
- }
-
- setAttribute(Qt::WA_SetLayoutDirection);
- d->setLayoutDirection_helper(direction);
-}
-
-Qt::LayoutDirection QWidget::layoutDirection() const
-{
- return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
-}
-
-void QWidget::unsetLayoutDirection()
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_SetLayoutDirection, false);
- d->resolveLayoutDirection();
-}
-
-/*!
- \fn QFontMetrics QWidget::fontMetrics() const
-
- Returns the font metrics for the widget's current font.
- Equivalent to QFontMetrics(widget->font()).
-
- \sa font(), fontInfo(), setFont()
-*/
-
-/*!
- \fn QFontInfo QWidget::fontInfo() const
-
- Returns the font info for the widget's current font.
- Equivalent to QFontInto(widget->font()).
-
- \sa font(), fontMetrics(), setFont()
-*/
-
-
-/*!
- \property QWidget::cursor
- \brief the cursor shape for this widget
-
- The mouse cursor will assume this shape when it's over this
- widget. See the \link Qt::CursorShape list of predefined cursor
- objects\endlink for a range of useful shapes.
-
- An editor widget might use an I-beam cursor:
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
-
- If no cursor has been set, or after a call to unsetCursor(), the
- parent's cursor is used.
-
- By default, this property contains a cursor with the Qt::ArrowCursor
- shape.
-
- Some underlying window implementations will reset the cursor if it
- leaves a widget even if the mouse is grabbed. If you want to have
- a cursor set for all widgets, even when outside the window, consider
- QApplication::setOverrideCursor().
-
- \sa QApplication::setOverrideCursor()
-*/
-
-#ifndef QT_NO_CURSOR
-QCursor QWidget::cursor() const
-{
- Q_D(const QWidget);
- if (testAttribute(Qt::WA_SetCursor))
- return (d->extra && d->extra->curs)
- ? *d->extra->curs
- : QCursor(Qt::ArrowCursor);
- if (isWindow() || !parentWidget())
- return QCursor(Qt::ArrowCursor);
- return parentWidget()->cursor();
-}
-
-void QWidget::setCursor(const QCursor &cursor)
-{
- Q_D(QWidget);
-// On Mac we must set the cursor even if it is the ArrowCursor.
-#if !defined(Q_WS_MAC) && !defined(Q_WS_QWS)
- if (cursor.shape() != Qt::ArrowCursor
- || (d->extra && d->extra->curs))
-#endif
- {
- d->createExtra();
- QCursor *newCursor = new QCursor(cursor);
- delete d->extra->curs;
- d->extra->curs = newCursor;
- }
- setAttribute(Qt::WA_SetCursor);
- d->setCursor_sys(cursor);
-
- QEvent event(QEvent::CursorChange);
- QApplication::sendEvent(this, &event);
-}
-
-void QWidget::unsetCursor()
-{
- Q_D(QWidget);
- if (d->extra) {
- delete d->extra->curs;
- d->extra->curs = 0;
- }
- if (!isWindow())
- setAttribute(Qt::WA_SetCursor, false);
- d->unsetCursor_sys();
-
- QEvent event(QEvent::CursorChange);
- QApplication::sendEvent(this, &event);
-}
-
-#endif
-
-/*!
- \enum QWidget::RenderFlag
-
- This enum describes how to render the widget when calling QWidget::render().
-
- \value DrawWindowBackground If you enable this option, the widget's background
- is rendered into the target even if autoFillBackground is not set. By default,
- this option is enabled.
-
- \value DrawChildren If you enable this option, the widget's children
- are rendered recursively into the target. By default, this option is enabled.
-
- \value IgnoreMask If you enable this option, the widget's QWidget::mask()
- is ignored when rendering into the target. By default, this option is disabled.
-
- \since 4.3
-*/
-
-/*!
- \since 4.3
-
- Renders the \a sourceRegion of this widget into the \a target
- using \a renderFlags to determine how to render. Rendering
- starts at \a targetOffset in the \a target. For example:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
-
- If \a sourceRegion is a null region, this function will use QWidget::rect() as
- the region, i.e. the entire widget.
-
- Ensure that you call QPainter::end() for the \a target device's
- active painter (if any) before rendering. For example:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
-
- \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
- or QGLWidget::renderPixmap() instead.
-*/
-void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
- const QRegion &sourceRegion, RenderFlags renderFlags)
-{
- d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
-}
-
-/*!
- \overload
-
- Renders the widget into the \a painter's QPainter::device().
-
- Transformations and settings applied to the \a painter will be used
- when rendering.
-
- \note The \a painter must be active. On Mac OS X the widget will be
- rendered into a QPixmap and then drawn by the \a painter.
-
- \sa QPainter::device()
-*/
-void QWidget::render(QPainter *painter, const QPoint &targetOffset,
- const QRegion &sourceRegion, RenderFlags renderFlags)
-{
- if (!painter) {
- qWarning("QWidget::render: Null pointer to painter");
- return;
- }
-
- if (!painter->isActive()) {
- qWarning("QWidget::render: Cannot render with an inactive painter");
- return;
- }
-
- const qreal opacity = painter->opacity();
- if (qFuzzyIsNull(opacity))
- return; // Fully transparent.
-
- Q_D(QWidget);
- const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
- const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
- : sourceRegion;
- if (toBePainted.isEmpty())
- return;
-
- if (!d->extra)
- d->createExtra();
- d->extra->inRenderWithPainter = true;
-
-#ifdef Q_WS_MAC
- d->render_helper(painter, targetOffset, toBePainted, renderFlags);
-#else
- QPaintEngine *engine = painter->paintEngine();
- Q_ASSERT(engine);
- QPaintEnginePrivate *enginePriv = engine->d_func();
- Q_ASSERT(enginePriv);
- QPaintDevice *target = engine->paintDevice();
- Q_ASSERT(target);
-
- // Render via a pixmap when dealing with non-opaque painters or printers.
- if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
- d->render_helper(painter, targetOffset, toBePainted, renderFlags);
- d->extra->inRenderWithPainter = false;
- return;
- }
-
- // Set new shared painter.
- QPainter *oldPainter = d->sharedPainter();
- d->setSharedPainter(painter);
-
- // Save current system clip, viewport and transform,
- const QTransform oldTransform = enginePriv->systemTransform;
- const QRegion oldSystemClip = enginePriv->systemClip;
- const QRegion oldSystemViewport = enginePriv->systemViewport;
-
- // This ensures that all painting triggered by render() is clipped to the current engine clip.
- if (painter->hasClipping()) {
- const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
- enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
- } else {
- enginePriv->setSystemViewport(oldSystemClip);
- }
-
- render(target, targetOffset, toBePainted, renderFlags);
-
- // Restore system clip, viewport and transform.
- enginePriv->systemClip = oldSystemClip;
- enginePriv->setSystemViewport(oldSystemViewport);
- enginePriv->setSystemTransform(oldTransform);
-
- // Restore shared painter.
- d->setSharedPainter(oldPainter);
-#endif
-
- d->extra->inRenderWithPainter = false;
-}
-
-/*!
- \brief The graphicsEffect function returns a pointer to the
- widget's graphics effect.
-
- If the widget has no graphics effect, 0 is returned.
-
- \since 4.6
-
- \sa setGraphicsEffect()
-*/
-#ifndef QT_NO_GRAPHICSEFFECT
-QGraphicsEffect *QWidget::graphicsEffect() const
-{
- Q_D(const QWidget);
- return d->graphicsEffect;
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-/*!
-
- \brief The setGraphicsEffect function is for setting the widget's graphics effect.
-
- Sets \a effect as the widget's effect. If there already is an effect installed
- on this widget, QWidget will delete the existing effect before installing
- the new \a effect.
-
- If \a effect is the installed on a different widget, setGraphicsEffect() will remove
- the effect from the widget and install it on this widget.
-
- QWidget takes ownership of \a effect.
-
- \note This function will apply the effect on itself and all its children.
-
- \since 4.6
-
- \sa graphicsEffect()
-*/
-#ifndef QT_NO_GRAPHICSEFFECT
-void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
-{
- Q_D(QWidget);
- if (d->graphicsEffect == effect)
- return;
-
- if (d->graphicsEffect) {
- d->invalidateBuffer(rect());
- delete d->graphicsEffect;
- d->graphicsEffect = 0;
- }
-
- if (effect) {
- // Set new effect.
- QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
- QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
- d->graphicsEffect = effect;
- effect->d_func()->setGraphicsEffectSource(source);
- update();
- }
-
- d->updateIsOpaque();
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-bool QWidgetPrivate::isAboutToShow() const
-{
- if (data.in_show)
- return true;
-
- Q_Q(const QWidget);
- if (q->isHidden())
- return false;
-
- // The widget will be shown if any of its ancestors are about to show.
- QWidget *parent = q->parentWidget();
- return parent ? parent->d_func()->isAboutToShow() : false;
-}
-
-QRegion QWidgetPrivate::prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags)
-{
- Q_Q(QWidget);
- const bool isVisible = q->isVisible();
-
- // Make sure the widget is laid out correctly.
- if (!isVisible && !isAboutToShow()) {
- QWidget *topLevel = q->window();
- (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
- topLevel->ensurePolished();
-
- // Invalidate the layout of hidden ancestors (incl. myself) and pretend
- // they're not explicitly hidden.
- QWidget *widget = q;
- QWidgetList hiddenWidgets;
- while (widget) {
- if (widget->isHidden()) {
- widget->setAttribute(Qt::WA_WState_Hidden, false);
- hiddenWidgets.append(widget);
- if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
- widget->d_func()->updateGeometry_helper(true);
- }
- widget = widget->parentWidget();
- }
-
- // Activate top-level layout.
- if (topLevel->d_func()->layout)
- topLevel->d_func()->layout->activate();
-
- // Adjust size if necessary.
- QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
- if (topLevelExtra && !topLevelExtra->sizeAdjusted
- && !topLevel->testAttribute(Qt::WA_Resized)) {
- topLevel->adjustSize();
- topLevel->setAttribute(Qt::WA_Resized, false);
- }
-
- // Activate child layouts.
- topLevel->d_func()->activateChildLayoutsRecursively();
-
- // We're not cheating with WA_WState_Hidden anymore.
- for (int i = 0; i < hiddenWidgets.size(); ++i) {
- QWidget *widget = hiddenWidgets.at(i);
- widget->setAttribute(Qt::WA_WState_Hidden);
- if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
- widget->parentWidget()->d_func()->layout->invalidate();
- }
- } else if (isVisible) {
- q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
- }
-
- // Calculate the region to be painted.
- QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
- if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
- toBePainted &= extra->mask;
- return toBePainted;
-}
-
-void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
- QWidget::RenderFlags renderFlags)
-{
- Q_ASSERT(painter);
- Q_ASSERT(!toBePainted.isEmpty());
-
- Q_Q(QWidget);
-#ifndef Q_WS_MAC
- const QTransform originalTransform = painter->worldTransform();
- const bool useDeviceCoordinates = originalTransform.isScaling();
- if (!useDeviceCoordinates) {
-#endif
- // Render via a pixmap.
- const QRect rect = toBePainted.boundingRect();
- const QSize size = rect.size();
- if (size.isNull())
- return;
-
- QPixmap pixmap(size);
- if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
- pixmap.fill(Qt::transparent);
- q->render(&pixmap, QPoint(), toBePainted, renderFlags);
-
- const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
- painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
-
- painter->drawPixmap(targetOffset, pixmap);
-
- if (restore)
- painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
-
-#ifndef Q_WS_MAC
- } else {
- // Render via a pixmap in device coordinates (to avoid pixmap scaling).
- QTransform transform = originalTransform;
- transform.translate(targetOffset.x(), targetOffset.y());
-
- QPaintDevice *device = painter->device();
- Q_ASSERT(device);
-
- // Calculate device rect.
- const QRectF rect(toBePainted.boundingRect());
- QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
- deviceRect &= QRect(0, 0, device->width(), device->height());
-
- QPixmap pixmap(deviceRect.size());
- pixmap.fill(Qt::transparent);
-
- // Create a pixmap device coordinate painter.
- QPainter pixmapPainter(&pixmap);
- pixmapPainter.setRenderHints(painter->renderHints());
- transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
- pixmapPainter.setTransform(transform);
-
- q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
- pixmapPainter.end();
-
- // And then draw the pixmap.
- painter->setTransform(QTransform());
- painter->drawPixmap(deviceRect.topLeft(), pixmap);
- painter->setTransform(originalTransform);
- }
-#endif
-}
-
-void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
- QPainter *sharedPainter, QWidgetBackingStore *backingStore)
-{
- if (rgn.isEmpty())
- return;
-
-#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
- if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
- dirtyOnWidget = QRegion();
-
- // We disable the rendering of QToolBar in the backingStore if
- // it's supposed to be in the unified toolbar on Mac OS X.
- if (backingStore && isInUnifiedToolbar)
- return;
-#endif // Q_WS_MAC && QT_MAC_USE_COCOA
-
-
- Q_Q(QWidget);
-#ifndef QT_NO_GRAPHICSEFFECT
- if (graphicsEffect && graphicsEffect->isEnabled()) {
- QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
- QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
- (source->d_func());
- if (!sourced->context) {
- QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
- sourced->context = &context;
- if (!sharedPainter) {
- QPaintEngine *paintEngine = pdev->paintEngine();
- paintEngine->d_func()->systemClip = rgn.translated(offset);
- QPainter p(pdev);
- p.translate(offset);
- context.painter = &p;
- graphicsEffect->draw(&p);
- paintEngine->d_func()->systemClip = QRegion();
- } else {
- context.painter = sharedPainter;
- if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
- sourced->invalidateCache();
- sourced->lastEffectTransform = sharedPainter->worldTransform();
- }
- sharedPainter->save();
- sharedPainter->translate(offset);
- graphicsEffect->draw(sharedPainter);
- sharedPainter->restore();
- }
- sourced->context = 0;
- return;
- }
- }
-#endif //QT_NO_GRAFFICSEFFECT
-
- const bool asRoot = flags & DrawAsRoot;
- const bool alsoOnScreen = flags & DrawPaintOnScreen;
- const bool recursive = flags & DrawRecursive;
- const bool alsoInvisible = flags & DrawInvisible;
-
- Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
-
- QRegion toBePainted(rgn);
- if (asRoot && !alsoInvisible)
- toBePainted &= clipRect(); //(rgn & visibleRegion());
- if (!(flags & DontSubtractOpaqueChildren))
- subtractOpaqueChildren(toBePainted, q->rect());
-
- if (!toBePainted.isEmpty()) {
- bool onScreen = paintOnScreen();
- if (!onScreen || alsoOnScreen) {
- //update the "in paint event" flag
- if (q->testAttribute(Qt::WA_WState_InPaintEvent))
- qWarning("QWidget::repaint: Recursive repaint detected");
- q->setAttribute(Qt::WA_WState_InPaintEvent);
-
- //clip away the new area
-#ifndef QT_NO_PAINT_DEBUG
- bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
-#endif
- QPaintEngine *paintEngine = pdev->paintEngine();
- if (paintEngine) {
- setRedirected(pdev, -offset);
-
-#ifdef Q_WS_MAC
- // (Alien support) Special case for Mac when redirecting: If the paint device
- // is of the Widget type we need to set WA_WState_InPaintEvent since painting
- // outside the paint event is not supported on QWidgets. The attributeis
- // restored further down.
- if (pdev->devType() == QInternal::Widget)
- static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
-
-#endif
- if (sharedPainter)
- paintEngine->d_func()->systemClip = toBePainted;
- else
- paintEngine->d_func()->systemRect = q->data->crect;
-
- //paint the background
- if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
- && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
- QPainter p(q);
- paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
- }
-
- if (!sharedPainter)
- paintEngine->d_func()->systemClip = toBePainted.translated(offset);
-
- if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
- QPainter p(q);
- QColor tint = q->palette().window().color();
- tint.setAlphaF(qreal(.6));
- p.fillRect(toBePainted.boundingRect(), tint);
- }
- }
-
-#if 0
- qDebug() << "painting" << q << "opaque ==" << isOpaque();
- qDebug() << "clipping to" << toBePainted << "location == " << offset
- << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
-#endif
-
- //actually send the paint event
- QPaintEvent e(toBePainted);
- QCoreApplication::sendSpontaneousEvent(q, &e);
-#if !defined(Q_WS_QWS) && !defined(Q_WS_QPA)
- if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
- backingStore->markDirtyOnScreen(toBePainted, q, offset);
-#endif
-
- //restore
- if (paintEngine) {
-#ifdef Q_WS_MAC
- if (pdev->devType() == QInternal::Widget)
- static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
-#endif
- restoreRedirected();
- if (!sharedPainter)
- paintEngine->d_func()->systemRect = QRect();
- else
- paintEngine->d_func()->currentClipDevice = 0;
- paintEngine->d_func()->systemClip = QRegion();
- }
- q->setAttribute(Qt::WA_WState_InPaintEvent, false);
- if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
- qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
-
- if (paintEngine && paintEngine->autoDestruct()) {
- delete paintEngine;
- }
-
-#ifndef QT_NO_PAINT_DEBUG
- if (flushed)
- QWidgetBackingStore::unflushPaint(q, toBePainted);
-#endif
- } else if (q->isWindow()) {
- QPaintEngine *engine = pdev->paintEngine();
- if (engine) {
- QPainter p(pdev);
- p.setClipRegion(toBePainted);
- const QBrush bg = q->palette().brush(QPalette::Window);
- if (bg.style() == Qt::TexturePattern)
- p.drawTiledPixmap(q->rect(), bg.texture());
- else
- p.fillRect(q->rect(), bg);
-
- if (engine->autoDestruct())
- delete engine;
- }
- }
- }
-
- if (recursive && !children.isEmpty()) {
- paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- , q->windowSurface()
-#endif
- , sharedPainter, backingStore);
- }
-}
-
-void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
- const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
- bool readyToRender)
-{
- if (!target) {
- qWarning("QWidget::render: null pointer to paint device");
- return;
- }
-
- const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
- QRegion paintRegion = !inRenderWithPainter && !readyToRender
- ? prepareToRender(sourceRegion, renderFlags)
- : sourceRegion;
- if (paintRegion.isEmpty())
- return;
-
-#ifndef Q_WS_MAC
- QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
-
- // Use the target's shared painter if set (typically set when doing
- // "other->render(widget);" in the widget's paintEvent.
- if (target->devType() == QInternal::Widget) {
- QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
- if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
- QPainter *targetPainter = targetPrivate->sharedPainter();
- if (targetPainter && targetPainter->isActive())
- setSharedPainter(targetPainter);
- }
- }
-#endif
-
- // Use the target's redirected device if set and adjust offset and paint
- // region accordingly. This is typically the case when people call render
- // from the paintEvent.
- QPoint offset = targetOffset;
- offset -= paintRegion.boundingRect().topLeft();
- QPoint redirectionOffset;
- QPaintDevice *redirected = 0;
-
- if (target->devType() == QInternal::Widget)
- redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
- if (!redirected)
- redirected = QPainter::redirected(target, &redirectionOffset);
-
- if (redirected) {
- target = redirected;
- offset -= redirectionOffset;
- }
-
- if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
- if (QPaintEngine *targetEngine = target->paintEngine()) {
- const QRegion targetSystemClip = targetEngine->systemClip();
- if (!targetSystemClip.isEmpty())
- paintRegion &= targetSystemClip.translated(-offset);
- }
- }
-
- // Set backingstore flags.
- int flags = DrawPaintOnScreen | DrawInvisible;
- if (renderFlags & QWidget::DrawWindowBackground)
- flags |= DrawAsRoot;
-
- if (renderFlags & QWidget::DrawChildren)
- flags |= DrawRecursive;
- else
- flags |= DontSubtractOpaqueChildren;
-
-#ifdef Q_WS_QWS
- flags |= DontSetCompositionMode;
-#endif
-
- if (target->devType() == QInternal::Printer) {
- QPainter p(target);
- render_helper(&p, targetOffset, paintRegion, renderFlags);
- return;
- }
-
-#ifndef Q_WS_MAC
- // Render via backingstore.
- drawWidget(target, paintRegion, offset, flags, sharedPainter());
-
- // Restore shared painter.
- if (oldSharedPainter)
- setSharedPainter(oldSharedPainter);
-#else
- // Render via backingstore (no shared painter).
- drawWidget(target, paintRegion, offset, flags, 0);
-#endif
-}
-
-void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
- const QPoint &offset, int flags
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- , const QWindowSurface *currentSurface
-#endif
- , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
-{
- QWidget *w = 0;
- QRect boundingRect;
- bool dirtyBoundingRect = true;
- const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
- const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
-
- do {
- QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
- if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
- && !(excludeNativeChildren && x->internalWinId())) {
- if (dirtyBoundingRect) {
- boundingRect = rgn.boundingRect();
- dirtyBoundingRect = false;
- }
-
- if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- if (x->windowSurface() == currentSurface)
-#endif
- {
- w = x;
- break;
- }
- }
- }
- --index;
- } while (index >= 0);
-
- if (!w)
- return;
-
- QWidgetPrivate *wd = w->d_func();
- const QPoint widgetPos(w->data->crect.topLeft());
- const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
- if (index > 0) {
- QRegion wr(rgn);
- if (wd->isOpaque)
- wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
- paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- , currentSurface
-#endif
- , sharedPainter, backingStore);
- }
-
- if (w->updatesEnabled()
-#ifndef QT_NO_GRAPHICSVIEW
- && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
-#endif //QT_NO_GRAPHICSVIEW
- ) {
- QRegion wRegion(rgn);
- wRegion &= wd->effectiveRectFor(w->data->crect);
- wRegion.translate(-widgetPos);
- if (hasMask)
- wRegion &= wd->extra->mask;
- wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
- }
-}
-
-#ifndef QT_NO_GRAPHICSEFFECT
-QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
-{
- if (system != Qt::DeviceCoordinates)
- return m_widget->rect();
-
- if (!context) {
- // Device coordinates without context not yet supported.
- qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
- return QRectF();
- }
-
- return context->painter->worldTransform().mapRect(m_widget->rect());
-}
-
-void QWidgetEffectSourcePrivate::draw(QPainter *painter)
-{
- if (!context || context->painter != painter) {
- m_widget->render(painter);
- return;
- }
-
- // The region saved in the context is neither clipped to the rect
- // nor the mask, so we have to clip it here before calling drawWidget.
- QRegion toBePainted = context->rgn;
- toBePainted &= m_widget->rect();
- QWidgetPrivate *wd = qt_widget_private(m_widget);
- if (wd->extra && wd->extra->hasMask)
- toBePainted &= wd->extra->mask;
-
- wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
- context->sharedPainter, context->backingStore);
-}
-
-QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
- QGraphicsEffect::PixmapPadMode mode) const
-{
- const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
- if (!context && deviceCoordinates) {
- // Device coordinates without context not yet supported.
- qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
- return QPixmap();
- }
-
- QPoint pixmapOffset;
- QRectF sourceRect = m_widget->rect();
-
- if (deviceCoordinates) {
- const QTransform &painterTransform = context->painter->worldTransform();
- sourceRect = painterTransform.mapRect(sourceRect);
- pixmapOffset = painterTransform.map(pixmapOffset);
- }
-
- QRect effectRect;
-
- if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
- effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
- else if (mode == QGraphicsEffect::PadToTransparentBorder)
- effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
- else
- effectRect = sourceRect.toAlignedRect();
-
- if (offset)
- *offset = effectRect.topLeft();
-
- pixmapOffset -= effectRect.topLeft();
-
- QPixmap pixmap(effectRect.size());
- pixmap.fill(Qt::transparent);
- m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
- return pixmap;
-}
-#endif //QT_NO_GRAPHICSEFFECT
-
-#ifndef QT_NO_GRAPHICSVIEW
-/*!
- \internal
-
- Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
- widget and its ancestors. The search starts at \a origin (inclusive).
- If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
- widget was found.
-*/
-QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
-{
- if (origin) {
- QWExtra *extra = origin->d_func()->extra;
- if (extra && extra->proxyWidget)
- return extra->proxyWidget;
- return nearestGraphicsProxyWidget(origin->parentWidget());
- }
- return 0;
-}
-#endif
-
-/*!
- \property QWidget::locale
- \brief the widget's locale
- \since 4.3
-
- As long as no special locale has been set, this is either
- the parent's locale or (if this widget is a top level widget),
- the default locale.
-
- If the widget displays dates or numbers, these should be formatted
- using the widget's locale.
-
- \sa QLocale QLocale::setDefault()
-*/
-
-void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
-{
- Q_Q(QWidget);
- if (locale == loc && !forceUpdate)
- return;
-
- locale = loc;
-
- if (!children.isEmpty()) {
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget*>(children.at(i));
- if (!w)
- continue;
- if (w->testAttribute(Qt::WA_SetLocale))
- continue;
- if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
- continue;
- w->d_func()->setLocale_helper(loc, forceUpdate);
- }
- }
- QEvent e(QEvent::LocaleChange);
- QApplication::sendEvent(q, &e);
-}
-
-void QWidget::setLocale(const QLocale &locale)
-{
- Q_D(QWidget);
-
- setAttribute(Qt::WA_SetLocale);
- d->setLocale_helper(locale);
-}
-
-QLocale QWidget::locale() const
-{
- Q_D(const QWidget);
-
- return d->locale;
-}
-
-void QWidgetPrivate::resolveLocale()
-{
- Q_Q(const QWidget);
-
- if (!q->testAttribute(Qt::WA_SetLocale)) {
- setLocale_helper(q->isWindow()
- ? QLocale()
- : q->parentWidget()->locale());
- }
-}
-
-void QWidget::unsetLocale()
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_SetLocale, false);
- d->resolveLocale();
-}
-
-static QString constructWindowTitleFromFilePath(const QString &filePath)
-{
- QFileInfo fi(filePath);
- QString windowTitle = fi.fileName() + QLatin1String("[*]");
-#ifndef Q_WS_MAC
- QString appName = QApplication::applicationName();
- if (!appName.isEmpty())
- windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
-#endif
- return windowTitle;
-}
-
-/*!
- \property QWidget::windowTitle
- \brief the window title (caption)
-
- This property only makes sense for top-level widgets, such as
- windows and dialogs. If no caption has been set, the title is based of the
- \l windowFilePath. If neither of these is set, then the title is
- an empty string.
-
- If you use the \l windowModified mechanism, the window title must
- contain a "[*]" placeholder, which indicates where the '*' should
- appear. Normally, it should appear right after the file name
- (e.g., "document1.txt[*] - Text Editor"). If the \l
- windowModified property is false (the default), the placeholder
- is simply removed.
-
- \sa windowIcon, windowIconText, windowModified, windowFilePath
-*/
-QString QWidget::windowTitle() const
-{
- Q_D(const QWidget);
- if (d->extra && d->extra->topextra) {
- if (!d->extra->topextra->caption.isEmpty())
- return d->extra->topextra->caption;
- if (!d->extra->topextra->filePath.isEmpty())
- return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
- }
- return QString();
-}
-
-/*!
- Returns a modified window title with the [*] place holder
- replaced according to the rules described in QWidget::setWindowTitle
-
- This function assumes that "[*]" can be quoted by another
- "[*]", so it will replace two place holders by one and
- a single last one by either "*" or nothing depending on
- the modified flag.
-
- \internal
-*/
-QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
-{
- Q_ASSERT(widget);
-
-#ifdef QT_EVAL
- extern QString qt_eval_adapt_window_title(const QString &title);
- QString cap = qt_eval_adapt_window_title(title);
-#else
- QString cap = title;
-#endif
-
- if (cap.isEmpty())
- return cap;
-
- QLatin1String placeHolder("[*]");
- int placeHolderLength = 3; // QLatin1String doesn't have length()
-
- int index = cap.indexOf(placeHolder);
-
- // here the magic begins
- while (index != -1) {
- index += placeHolderLength;
- int count = 1;
- while (cap.indexOf(placeHolder, index) == index) {
- ++count;
- index += placeHolderLength;
- }
-
- if (count%2) { // odd number of [*] -> replace last one
- int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
- if (widget->isWindowModified()
- && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
- cap.replace(lastIndex, 3, QWidget::tr("*"));
- else
- cap.remove(lastIndex, 3);
- }
-
- index = cap.indexOf(placeHolder, index);
- }
-
- cap.replace(QLatin1String("[*][*]"), placeHolder);
-
- return cap;
-}
-
-void QWidgetPrivate::setWindowTitle_helper(const QString &title)
-{
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_WState_Created))
- setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
-}
-
-void QWidgetPrivate::setWindowIconText_helper(const QString &title)
-{
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_WState_Created))
- setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
-}
-
-void QWidget::setWindowIconText(const QString &iconText)
-{
- if (QWidget::windowIconText() == iconText)
- return;
-
- Q_D(QWidget);
- d->topData()->iconText = iconText;
- d->setWindowIconText_helper(iconText);
-
- QEvent e(QEvent::IconTextChange);
- QApplication::sendEvent(this, &e);
-}
-
-void QWidget::setWindowTitle(const QString &title)
-{
- if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
- return;
-
- Q_D(QWidget);
- d->topData()->caption = title;
- d->setWindowTitle_helper(title);
-
- QEvent e(QEvent::WindowTitleChange);
- QApplication::sendEvent(this, &e);
-}
-
-
-/*!
- \property QWidget::windowIcon
- \brief the widget's icon
-
- This property only makes sense for windows. If no icon
- has been set, windowIcon() returns the application icon
- (QApplication::windowIcon()).
-
- \sa windowIconText, windowTitle
-*/
-QIcon QWidget::windowIcon() const
-{
- const QWidget *w = this;
- while (w) {
- const QWidgetPrivate *d = w->d_func();
- if (d->extra && d->extra->topextra && d->extra->topextra->icon)
- return *d->extra->topextra->icon;
- w = w->parentWidget();
- }
- return QApplication::windowIcon();
-}
-
-void QWidgetPrivate::setWindowIcon_helper()
-{
- QEvent e(QEvent::WindowIconChange);
- QApplication::sendEvent(q_func(), &e);
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(children.at(i));
- if (w && !w->isWindow())
- QApplication::sendEvent(w, &e);
- }
-}
-
-void QWidget::setWindowIcon(const QIcon &icon)
-{
- Q_D(QWidget);
-
- setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
- d->createTLExtra();
-
- if (!d->extra->topextra->icon)
- d->extra->topextra->icon = new QIcon();
- *d->extra->topextra->icon = icon;
-
- delete d->extra->topextra->iconPixmap;
- d->extra->topextra->iconPixmap = 0;
-
- d->setWindowIcon_sys();
- d->setWindowIcon_helper();
-}
-
-
-/*!
- \property QWidget::windowIconText
- \brief the widget's icon text
-
- This property only makes sense for windows. If no icon
- text has been set, this functions returns an empty string.
-
- \sa windowIcon, windowTitle
-*/
-
-QString QWidget::windowIconText() const
-{
- Q_D(const QWidget);
- return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
-}
-
-/*!
- \property QWidget::windowFilePath
- \since 4.4
- \brief the file path associated with a widget
-
- This property only makes sense for windows. It associates a file path with
- a window. If you set the file path, but have not set the window title, Qt
- sets the window title to contain a string created using the following
- components.
-
- On Mac OS X:
-
- \list
- \o The file name of the specified path, obtained using QFileInfo::fileName().
- \endlist
-
- On Windows and X11:
-
- \list
- \o The file name of the specified path, obtained using QFileInfo::fileName().
- \o An optional \c{*} character, if the \l windowModified property is set.
- \o The \c{0x2014} unicode character, padded either side by spaces.
- \o The application name, obtained from the application's
- \l{QCoreApplication::}{applicationName} property.
- \endlist
-
- If the window title is set at any point, then the window title takes precedence and
- will be shown instead of the file path string.
-
- Additionally, on Mac OS X, this has an added benefit that it sets the
- \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
- for the window, assuming that the file path exists.
-
- If no file path is set, this property contains an empty string.
-
- By default, this property contains an empty string.
-
- \sa windowTitle, windowIcon
-*/
-
-QString QWidget::windowFilePath() const
-{
- Q_D(const QWidget);
- return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
-}
-
-void QWidget::setWindowFilePath(const QString &filePath)
-{
- if (filePath == windowFilePath())
- return;
-
- Q_D(QWidget);
-
- d->createTLExtra();
- d->extra->topextra->filePath = filePath;
- d->setWindowFilePath_helper(filePath);
-}
-
-void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
-{
- if (extra->topextra && extra->topextra->caption.isEmpty()) {
-#ifdef Q_WS_MAC
- setWindowTitle_helper(QFileInfo(filePath).fileName());
-#else
- Q_Q(QWidget);
- Q_UNUSED(filePath);
- setWindowTitle_helper(q->windowTitle());
-#endif
- }
-#ifdef Q_WS_MAC
- setWindowFilePath_sys(filePath);
-#endif
-}
-
-/*!
- Returns the window's role, or an empty string.
-
- \sa windowIcon, windowTitle
-*/
-
-QString QWidget::windowRole() const
-{
- Q_D(const QWidget);
- return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
-}
-
-/*!
- Sets the window's role to \a role. This only makes sense for
- windows on X11.
-*/
-void QWidget::setWindowRole(const QString &role)
-{
-#if defined(Q_WS_X11)
- Q_D(QWidget);
- d->topData()->role = role;
- d->setWindowRole();
-#else
- Q_UNUSED(role)
-#endif
-}
-
-/*!
- \property QWidget::mouseTracking
- \brief whether mouse tracking is enabled for the widget
-
- If mouse tracking is disabled (the default), the widget only
- receives mouse move events when at least one mouse button is
- pressed while the mouse is being moved.
-
- If mouse tracking is enabled, the widget receives mouse move
- events even if no buttons are pressed.
-
- \sa mouseMoveEvent()
-*/
-
-
-/*!
- Sets the widget's focus proxy to widget \a w. If \a w is 0, the
- function resets this widget to have no focus proxy.
-
- Some widgets can "have focus", but create a child widget, such as
- QLineEdit, to actually handle the focus. In this case, the widget
- can set the line edit to be its focus proxy.
-
- setFocusProxy() sets the widget which will actually get focus when
- "this widget" gets it. If there is a focus proxy, setFocus() and
- hasFocus() operate on the focus proxy.
-
- \sa focusProxy()
-*/
-
-void QWidget::setFocusProxy(QWidget * w)
-{
- Q_D(QWidget);
- if (!w && !d->extra)
- return;
-
- for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
- if (fp == this) {
- qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
- return;
- }
- }
-
- d->createExtra();
- d->extra->focus_proxy = w;
-}
-
-
-/*!
- Returns the focus proxy, or 0 if there is no focus proxy.
-
- \sa setFocusProxy()
-*/
-
-QWidget * QWidget::focusProxy() const
-{
- Q_D(const QWidget);
- return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
-}
-
-
-/*!
- \property QWidget::focus
- \brief whether this widget (or its focus proxy) has the keyboard
- input focus
-
- By default, this property is false.
-
- \note Obtaining the value of this property for a widget is effectively equivalent
- to checking whether QApplication::focusWidget() refers to the widget.
-
- \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
-*/
-bool QWidget::hasFocus() const
-{
- const QWidget* w = this;
- while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
- w = w->d_func()->extra->focus_proxy;
- if (QWidget *window = w->window()) {
-#ifndef QT_NO_GRAPHICSVIEW
- QWExtra *e = window->d_func()->extra;
- if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
- return true;
-#endif
- }
- return (QApplication::focusWidget() == w);
-}
-
-/*!
- Gives the keyboard input focus to this widget (or its focus
- proxy) if this widget or one of its parents is the \link
- isActiveWindow() active window\endlink. The \a reason argument will
- be passed into any focus event sent from this function, it is used
- to give an explanation of what caused the widget to get focus.
- If the window is not active, the widget will be given the focus when
- the window becomes active.
-
- First, a focus out event is sent to the focus widget (if any) to
- tell it that it is about to lose the focus. Then a focus in event
- is sent to this widget to tell it that it just received the focus.
- (Nothing happens if the focus in and focus out widgets are the
- same.)
-
- \note On embedded platforms, setFocus() will not cause an input panel
- to be opened by the input method. If you want this to happen, you
- have to send a QEvent::RequestSoftwareInputPanel event to the
- widget yourself.
-
- setFocus() gives focus to a widget regardless of its focus policy,
- but does not clear any keyboard grab (see grabKeyboard()).
-
- Be aware that if the widget is hidden, it will not accept focus
- until it is shown.
-
- \warning If you call setFocus() in a function which may itself be
- called from focusOutEvent() or focusInEvent(), you may get an
- infinite recursion.
-
- \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
- setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
- grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
-*/
-
-void QWidget::setFocus(Qt::FocusReason reason)
-{
- if (!isEnabled())
- return;
-
- QWidget *f = this;
- while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
- f = f->d_func()->extra->focus_proxy;
-
- if (QApplication::focusWidget() == f
-#if defined(Q_WS_WIN)
- && GetFocus() == f->internalWinId()
-#endif
- )
- return;
-
-#ifndef QT_NO_GRAPHICSVIEW
- QWidget *previousProxyFocus = 0;
- if (QWExtra *topData = window()->d_func()->extra) {
- if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
- previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
- if (previousProxyFocus && previousProxyFocus->focusProxy())
- previousProxyFocus = previousProxyFocus->focusProxy();
- if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
- return;
- }
- }
-#endif
-
- QWidget *w = f;
- if (isHidden()) {
- while (w && w->isHidden()) {
- w->d_func()->focus_child = f;
- w = w->isWindow() ? 0 : w->parentWidget();
- }
- } else {
- while (w) {
- w->d_func()->focus_child = f;
- w = w->isWindow() ? 0 : w->parentWidget();
- }
- }
-
-#ifndef QT_NO_GRAPHICSVIEW
- // Update proxy state
- if (QWExtra *topData = window()->d_func()->extra) {
- if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
- topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
- topData->proxyWidget->setFocus(reason);
- topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
- }
- }
-#endif
-
- if (f->isActiveWindow()) {
- QApplicationPrivate::setFocusWidget(f, reason);
-#ifndef QT_NO_ACCESSIBILITY
-# ifdef Q_OS_WIN
- // The negation of the condition in setFocus_sys
- if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
- //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
-# endif
- QAccessible::updateAccessibility(f, 0, QAccessible::Focus);
-#endif
-#ifndef QT_NO_GRAPHICSVIEW
- if (QWExtra *topData = window()->d_func()->extra) {
- if (topData->proxyWidget) {
- if (previousProxyFocus && previousProxyFocus != f) {
- // Send event to self
- QFocusEvent event(QEvent::FocusOut, reason);
- QPointer<QWidget> that = previousProxyFocus;
- QApplication::sendEvent(previousProxyFocus, &event);
- if (that)
- QApplication::sendEvent(that->style(), &event);
- }
- if (!isHidden()) {
-#ifndef QT_NO_GRAPHICSVIEW
- // Update proxy state
- if (QWExtra *topData = window()->d_func()->extra)
- if (topData->proxyWidget && topData->proxyWidget->hasFocus())
- topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
-#endif
- // Send event to self
- QFocusEvent event(QEvent::FocusIn, reason);
- QPointer<QWidget> that = f;
- QApplication::sendEvent(f, &event);
- if (that)
- QApplication::sendEvent(that->style(), &event);
- }
- }
- }
-#endif
- }
-}
-
-/*!
- \fn void QWidget::setFocus()
- \overload
-
- Gives the keyboard input focus to this widget (or its focus
- proxy) if this widget or one of its parents is the
- \l{isActiveWindow()}{active window}.
-*/
-
-/*!
- Takes keyboard input focus from the widget.
-
- If the widget has active focus, a \link focusOutEvent() focus out
- event\endlink is sent to this widget to tell it that it is about
- to lose the focus.
-
- This widget must enable focus setting in order to get the keyboard
- input focus, i.e. it must call setFocusPolicy().
-
- \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
- setFocusPolicy(), QApplication::focusWidget()
-*/
-
-void QWidget::clearFocus()
-{
- QWidget *w = this;
- while (w) {
- if (w->d_func()->focus_child == this)
- w->d_func()->focus_child = 0;
- w = w->parentWidget();
- }
-#ifndef QT_NO_GRAPHICSVIEW
- QWExtra *topData = d_func()->extra;
- if (topData && topData->proxyWidget)
- topData->proxyWidget->clearFocus();
-#endif
-
- if (hasFocus()) {
- // Update proxy state
- QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
-#if defined(Q_WS_WIN)
- if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
- SetFocus(0);
- else
-#endif
- {
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::Focus);
-#endif
- }
- }
-}
-
-
-/*!
- \fn bool QWidget::focusNextChild()
-
- Finds a new widget to give the keyboard focus to, as appropriate
- for \key Tab, and returns true if it can find a new widget, or
- false if it can't.
-
- \sa focusPreviousChild()
-*/
-
-/*!
- \fn bool QWidget::focusPreviousChild()
-
- Finds a new widget to give the keyboard focus to, as appropriate
- for \key Shift+Tab, and returns true if it can find a new widget,
- or false if it can't.
-
- \sa focusNextChild()
-*/
-
-/*!
- Finds a new widget to give the keyboard focus to, as appropriate
- for Tab and Shift+Tab, and returns true if it can find a new
- widget, or false if it can't.
-
- If \a next is true, this function searches forward, if \a next
- is false, it searches backward.
-
- Sometimes, you will want to reimplement this function. For
- example, a web browser might reimplement it to move its "current
- active link" forward or backward, and call
- focusNextPrevChild() only when it reaches the last or
- first link on the "page".
-
- Child widgets call focusNextPrevChild() on their parent widgets,
- but only the window that contains the child widgets decides where
- to redirect focus. By reimplementing this function for an object,
- you thus gain control of focus traversal for all child widgets.
-
- \sa focusNextChild(), focusPreviousChild()
-*/
-
-bool QWidget::focusNextPrevChild(bool next)
-{
- Q_D(QWidget);
- QWidget* p = parentWidget();
- bool isSubWindow = (windowType() == Qt::SubWindow);
- if (!isWindow() && !isSubWindow && p)
- return p->focusNextPrevChild(next);
-#ifndef QT_NO_GRAPHICSVIEW
- if (d->extra && d->extra->proxyWidget)
- return d->extra->proxyWidget->focusNextPrevChild(next);
-#endif
- QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
- if (!w) return false;
-
- w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
- return true;
-}
-
-/*!
- Returns the last child of this widget that setFocus had been
- called on. For top level widgets this is the widget that will get
- focus in case this window gets activated
-
- This is not the same as QApplication::focusWidget(), which returns
- the focus widget in the currently active window.
-*/
-
-QWidget *QWidget::focusWidget() const
-{
- return const_cast<QWidget *>(d_func()->focus_child);
-}
-
-/*!
- Returns the next widget in this widget's focus chain.
-
- \sa previousInFocusChain()
-*/
-QWidget *QWidget::nextInFocusChain() const
-{
- return const_cast<QWidget *>(d_func()->focus_next);
-}
-
-/*!
- \brief The previousInFocusChain function returns the previous
- widget in this widget's focus chain.
-
- \sa nextInFocusChain()
-
- \since 4.6
-*/
-QWidget *QWidget::previousInFocusChain() const
-{
- return const_cast<QWidget *>(d_func()->focus_prev);
-}
-
-/*!
- \property QWidget::isActiveWindow
- \brief whether this widget's window is the active window
-
- The active window is the window that contains the widget that has
- keyboard focus (The window may still have focus if it has no
- widgets or none of its widgets accepts keyboard focus).
-
- When popup windows are visible, this property is true for both the
- active window \e and for the popup.
-
- By default, this property is false.
-
- \sa activateWindow(), QApplication::activeWindow()
-*/
-bool QWidget::isActiveWindow() const
-{
- QWidget *tlw = window();
- if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
- return true;
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (QWExtra *tlwExtra = tlw->d_func()->extra) {
- if (isVisible() && tlwExtra->proxyWidget)
- return tlwExtra->proxyWidget->isActiveWindow();
- }
-#endif
-
-#ifdef Q_WS_MAC
- extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
- if(qt_mac_is_macdrawer(tlw) &&
- tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
- return true;
-
- extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
- if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
- return true;
-#endif
- if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
- if(tlw->windowType() == Qt::Tool &&
- !tlw->isModal() &&
- (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
- return true;
- QWidget *w = QApplication::activeWindow();
- while(w && tlw->windowType() == Qt::Tool &&
- !w->isModal() && w->parentWidget()) {
- w = w->parentWidget()->window();
- if(w == tlw)
- return true;
- }
- }
-#if defined(Q_WS_WIN32)
- HWND active = GetActiveWindow();
- if (!tlw->testAttribute(Qt::WA_WState_Created))
- return false;
- return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
-#else
- return false;
-#endif
-}
-
-/*!
- Puts the \a second widget after the \a first widget in the focus order.
-
- Note that since the tab order of the \a second widget is changed, you
- should order a chain like this:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
-
- \e not like this:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
-
- If \a first or \a second has a focus proxy, setTabOrder()
- correctly substitutes the proxy.
-
- \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
-*/
-void QWidget::setTabOrder(QWidget* first, QWidget *second)
-{
- if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
- return;
-
- if (first->window() != second->window()) {
- qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
- return;
- }
-
- QWidget *fp = first->focusProxy();
- if (fp) {
- // If first is redirected, set first to the last child of first
- // that can take keyboard focus so that second is inserted after
- // that last child, and the focus order within first is (more
- // likely to be) preserved.
- QList<QWidget *> l = first->findChildren<QWidget *>();
- for (int i = l.size()-1; i >= 0; --i) {
- QWidget * next = l.at(i);
- if (next->window() == fp->window()) {
- fp = next;
- if (fp->focusPolicy() != Qt::NoFocus)
- break;
- }
- }
- first = fp;
- }
-
- if (fp == second)
- return;
-
- if (QWidget *sp = second->focusProxy())
- second = sp;
-
-// QWidget *fp = first->d_func()->focus_prev;
- QWidget *fn = first->d_func()->focus_next;
-
- if (fn == second || first == second)
- return;
-
- QWidget *sp = second->d_func()->focus_prev;
- QWidget *sn = second->d_func()->focus_next;
-
- fn->d_func()->focus_prev = second;
- first->d_func()->focus_next = second;
-
- second->d_func()->focus_next = fn;
- second->d_func()->focus_prev = first;
-
- sp->d_func()->focus_next = sn;
- sn->d_func()->focus_prev = sp;
-
-
- Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
- Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
-
- Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
- Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
-}
-
-/*!\internal
-
- Moves the relevant subwidgets of this widget from the \a oldtlw's
- tab chain to that of the new parent, if there's anything to move and
- we're really moving
-
- This function is called from QWidget::reparent() *after* the widget
- has been reparented.
-
- \sa reparent()
-*/
-
-void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
-{
- Q_Q(QWidget);
- if (oldtlw == q->window())
- return; // nothing to do
-
- if(focus_child)
- focus_child->clearFocus();
-
- // separate the focus chain into new (children of myself) and old (the rest)
- QWidget *firstOld = 0;
- //QWidget *firstNew = q; //invariant
- QWidget *o = 0; // last in the old list
- QWidget *n = q; // last in the new list
-
- bool prevWasNew = true;
- QWidget *w = focus_next;
-
- //Note: for efficiency, we do not maintain the list invariant inside the loop
- //we append items to the relevant list, and we optimize by not changing pointers
- //when subsequent items are going into the same list.
- while (w != q) {
- bool currentIsNew = q->isAncestorOf(w);
- if (currentIsNew) {
- if (!prevWasNew) {
- //prev was old -- append to new list
- n->d_func()->focus_next = w;
- w->d_func()->focus_prev = n;
- }
- n = w;
- } else {
- if (prevWasNew) {
- //prev was new -- append to old list, if there is one
- if (o) {
- o->d_func()->focus_next = w;
- w->d_func()->focus_prev = o;
- } else {
- // "create" the old list
- firstOld = w;
- }
- }
- o = w;
- }
- w = w->d_func()->focus_next;
- prevWasNew = currentIsNew;
- }
-
- //repair the old list:
- if (firstOld) {
- o->d_func()->focus_next = firstOld;
- firstOld->d_func()->focus_prev = o;
- }
-
- if (!q->isWindow()) {
- QWidget *topLevel = q->window();
- //insert new chain into toplevel's chain
-
- QWidget *prev = topLevel->d_func()->focus_prev;
-
- topLevel->d_func()->focus_prev = n;
- prev->d_func()->focus_next = q;
-
- focus_prev = prev;
- n->d_func()->focus_next = topLevel;
- } else {
- //repair the new list
- n->d_func()->focus_next = q;
- focus_prev = n;
- }
-
-}
-
-/*!\internal
-
- Measures the shortest distance from a point to a rect.
-
- This function is called from QDesktopwidget::screen(QPoint) to find the
- closest screen for a point.
- In directional KeypadNavigation, it is called to find the closest
- widget to the current focus widget center.
-*/
-int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
-{
- int dx = 0;
- int dy = 0;
- if (p.x() < r.left())
- dx = r.left() - p.x();
- else if (p.x() > r.right())
- dx = p.x() - r.right();
- if (p.y() < r.top())
- dy = r.top() - p.y();
- else if (p.y() > r.bottom())
- dy = p.y() - r.bottom();
- return dx + dy;
-}
-
-/*!
- \property QWidget::frameSize
- \brief the size of the widget including any window frame
-
- By default, this property contains a value that depends on the user's
- platform and screen geometry.
-*/
-QSize QWidget::frameSize() const
-{
- Q_D(const QWidget);
- if (isWindow() && !(windowType() == Qt::Popup)) {
- QRect fs = d->frameStrut();
- return QSize(data->crect.width() + fs.left() + fs.right(),
- data->crect.height() + fs.top() + fs.bottom());
- }
- return data->crect.size();
-}
-
-/*! \fn void QWidget::move(int x, int y)
-
- \overload
-
- This corresponds to move(QPoint(\a x, \a y)).
-*/
-
-void QWidget::move(const QPoint &p)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_Moved);
- if (isWindow())
- d->topData()->posFromMove = true;
- if (testAttribute(Qt::WA_WState_Created)) {
- d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
- p.y() + geometry().y() - QWidget::y(),
- width(), height(), true);
- d->setDirtyOpaqueRegion();
- } else {
- data->crect.moveTopLeft(p); // no frame yet
- setAttribute(Qt::WA_PendingMoveEvent);
- }
-}
-
-/*! \fn void QWidget::resize(int w, int h)
- \overload
-
- This corresponds to resize(QSize(\a w, \a h)).
-*/
-
-void QWidget::resize(const QSize &s)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_Resized);
- if (testAttribute(Qt::WA_WState_Created)) {
- d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
- d->setDirtyOpaqueRegion();
- } else {
- data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
- setAttribute(Qt::WA_PendingResizeEvent);
- }
-}
-
-void QWidget::setGeometry(const QRect &r)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_Resized);
- setAttribute(Qt::WA_Moved);
- if (isWindow())
- d->topData()->posFromMove = false;
- if (testAttribute(Qt::WA_WState_Created)) {
- d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
- d->setDirtyOpaqueRegion();
- } else {
- data->crect.setTopLeft(r.topLeft());
- data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
- setAttribute(Qt::WA_PendingMoveEvent);
- setAttribute(Qt::WA_PendingResizeEvent);
- }
-}
-
-/*!
- \since 4.2
- Saves the current geometry and state for top-level widgets.
-
- To save the geometry when the window closes, you can
- implement a close event like this:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- Use QMainWindow::saveState() to save the geometry and the state of
- toolbars and dock widgets.
-
- \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
-*/
-QByteArray QWidget::saveGeometry() const
-{
-#ifdef QT_MAC_USE_COCOA
- // We check if the window was maximized during this invocation. If so, we need to record the
- // starting position as 0,0.
- Q_D(const QWidget);
- QRect newFramePosition = frameGeometry();
- QRect newNormalPosition = normalGeometry();
- if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
- // Change the starting position
- newFramePosition.moveTo(0, 0);
- newNormalPosition.moveTo(0, 0);
- }
-#endif // QT_MAC_USE_COCOA
- QByteArray array;
- QDataStream stream(&array, QIODevice::WriteOnly);
- stream.setVersion(QDataStream::Qt_4_0);
- const quint32 magicNumber = 0x1D9D0CB;
- quint16 majorVersion = 1;
- quint16 minorVersion = 0;
- stream << magicNumber
- << majorVersion
- << minorVersion
-#ifdef QT_MAC_USE_COCOA
- << newFramePosition
- << newNormalPosition
-#else
- << frameGeometry()
- << normalGeometry()
-#endif // QT_MAC_USE_COCOA
- << qint32(QApplication::desktop()->screenNumber(this))
- << quint8(windowState() & Qt::WindowMaximized)
- << quint8(windowState() & Qt::WindowFullScreen);
- return array;
-}
-
-/*!
- \since 4.2
-
- Restores the geometry and state top-level widgets stored in the
- byte array \a geometry. Returns true on success; otherwise
- returns false.
-
- If the restored geometry is off-screen, it will be modified to be
- inside the available screen geometry.
-
- To restore geometry saved using QSettings, you can use code like
- this:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
-
- See the \l{Window Geometry} documentation for an overview of geometry
- issues with windows.
-
- Use QMainWindow::restoreState() to restore the geometry and the
- state of toolbars and dock widgets.
-
- \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
-*/
-bool QWidget::restoreGeometry(const QByteArray &geometry)
-{
- if (geometry.size() < 4)
- return false;
- QDataStream stream(geometry);
- stream.setVersion(QDataStream::Qt_4_0);
-
- const quint32 magicNumber = 0x1D9D0CB;
- quint32 storedMagicNumber;
- stream >> storedMagicNumber;
- if (storedMagicNumber != magicNumber)
- return false;
-
- const quint16 currentMajorVersion = 1;
- quint16 majorVersion = 0;
- quint16 minorVersion = 0;
-
- stream >> majorVersion >> minorVersion;
-
- if (majorVersion != currentMajorVersion)
- return false;
- // (Allow all minor versions.)
-
- QRect restoredFrameGeometry;
- QRect restoredNormalGeometry;
- qint32 restoredScreenNumber;
- quint8 maximized;
- quint8 fullScreen;
-
- stream >> restoredFrameGeometry
- >> restoredNormalGeometry
- >> restoredScreenNumber
- >> maximized
- >> fullScreen;
-
- const int frameHeight = 20;
- if (!restoredFrameGeometry.isValid())
- restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
-
- if (!restoredNormalGeometry.isValid())
- restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
- if (!restoredNormalGeometry.isValid()) {
- // use the widget's adjustedSize if the sizeHint() doesn't help
- restoredNormalGeometry.setSize(restoredNormalGeometry
- .size()
- .expandedTo(d_func()->adjustedSize()));
- }
-
- const QDesktopWidget * const desktop = QApplication::desktop();
- if (restoredScreenNumber >= desktop->numScreens())
- restoredScreenNumber = desktop->primaryScreen();
-
- const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
-
- // Modify the restored geometry if we are about to restore to coordinates
- // that would make the window "lost". This happens if:
- // - The restored geometry is completely oustside the available geometry
- // - The title bar is outside the available geometry.
- // - (Mac only) The window is higher than the available geometry. It must
- // be possible to bring the size grip on screen by moving the window.
-#ifdef Q_WS_MAC
- restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
- restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
-#endif
-
- if (!restoredFrameGeometry.intersects(availableGeometry)) {
- restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
- restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
- restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
- }
- restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
-
- if (!restoredNormalGeometry.intersects(availableGeometry)) {
- restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
- restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
- restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
- }
- restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
-
- if (maximized || fullScreen) {
- // set geomerty before setting the window state to make
- // sure the window is maximized to the right screen.
- // Skip on windows: the window is restored into a broken
- // half-maximized state.
-#ifndef Q_WS_WIN
- setGeometry(restoredNormalGeometry);
-#endif
- Qt::WindowStates ws = windowState();
- if (maximized)
- ws |= Qt::WindowMaximized;
- if (fullScreen)
- ws |= Qt::WindowFullScreen;
- setWindowState(ws);
- d_func()->topData()->normalGeometry = restoredNormalGeometry;
- } else {
- QPoint offset;
-#ifdef Q_WS_X11
- if (isFullScreen())
- offset = d_func()->topData()->fullScreenOffset;
-#endif
- setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
- move(restoredFrameGeometry.topLeft() + offset);
- resize(restoredNormalGeometry.size());
- }
- return true;
-}
-
-/*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
- \overload
-
- This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
-*/
-
-/*!
- Sets the margins around the contents of the widget to have the sizes
- \a left, \a top, \a right, and \a bottom. The margins are used by
- the layout system, and may be used by subclasses to specify the area
- to draw in (e.g. excluding the frame).
-
- Changing the margins will trigger a resizeEvent().
-
- \sa contentsRect(), getContentsMargins()
-*/
-void QWidget::setContentsMargins(int left, int top, int right, int bottom)
-{
- Q_D(QWidget);
- if (left == d->leftmargin && top == d->topmargin
- && right == d->rightmargin && bottom == d->bottommargin)
- return;
- d->leftmargin = left;
- d->topmargin = top;
- d->rightmargin = right;
- d->bottommargin = bottom;
-
- if (QLayout *l=d->layout)
- l->update(); //force activate; will do updateGeometry
- else
- updateGeometry();
-
- // ### Qt 5: compat, remove
- if (isVisible()) {
- update();
- QResizeEvent e(data->crect.size(), data->crect.size());
- QApplication::sendEvent(this, &e);
- } else {
- setAttribute(Qt::WA_PendingResizeEvent, true);
- }
-
- QEvent e(QEvent::ContentsRectChange);
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- \overload
- \since 4.6
-
- \brief The setContentsMargins function sets the margins around the
- widget's contents.
-
- Sets the margins around the contents of the widget to have the
- sizes determined by \a margins. The margins are
- used by the layout system, and may be used by subclasses to
- specify the area to draw in (e.g. excluding the frame).
-
- Changing the margins will trigger a resizeEvent().
-
- \sa contentsRect(), getContentsMargins()
-*/
-void QWidget::setContentsMargins(const QMargins &margins)
-{
- setContentsMargins(margins.left(), margins.top(),
- margins.right(), margins.bottom());
-}
-
-/*!
- Returns the widget's contents margins for \a left, \a top, \a
- right, and \a bottom.
-
- \sa setContentsMargins(), contentsRect()
- */
-void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
-{
- Q_D(const QWidget);
- if (left)
- *left = d->leftmargin;
- if (top)
- *top = d->topmargin;
- if (right)
- *right = d->rightmargin;
- if (bottom)
- *bottom = d->bottommargin;
-}
-
-/*!
- \since 4.6
-
- \brief The contentsMargins function returns the widget's contents margins.
-
- \sa getContentsMargins(), setContentsMargins(), contentsRect()
- */
-QMargins QWidget::contentsMargins() const
-{
- Q_D(const QWidget);
- return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
-}
-
-
-/*!
- Returns the area inside the widget's margins.
-
- \sa setContentsMargins(), getContentsMargins()
-*/
-QRect QWidget::contentsRect() const
-{
- Q_D(const QWidget);
- return QRect(QPoint(d->leftmargin, d->topmargin),
- QPoint(data->crect.width() - 1 - d->rightmargin,
- data->crect.height() - 1 - d->bottommargin));
-
-}
-
-
-
-/*!
- \fn void QWidget::customContextMenuRequested(const QPoint &pos)
-
- This signal is emitted when the widget's \l contextMenuPolicy is
- Qt::CustomContextMenu, and the user has requested a context menu on
- the widget. The position \a pos is the position of the context menu
- event that the widget receives. Normally this is in widget
- coordinates. The exception to this rule is QAbstractScrollArea and
- its subclasses that map the context menu event to coordinates of the
- \link QAbstractScrollArea::viewport() viewport() \endlink .
-
-
- \sa mapToGlobal() QMenu contextMenuPolicy
-*/
-
-
-/*!
- \property QWidget::contextMenuPolicy
- \brief how the widget shows a context menu
-
- The default value of this property is Qt::DefaultContextMenu,
- which means the contextMenuEvent() handler is called. Other values
- are Qt::NoContextMenu, Qt::PreventContextMenu,
- Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
- Qt::CustomContextMenu, the signal customContextMenuRequested() is
- emitted.
-
- \sa contextMenuEvent(), customContextMenuRequested(), actions()
-*/
-
-Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
-{
- return (Qt::ContextMenuPolicy)data->context_menu_policy;
-}
-
-void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
-{
- data->context_menu_policy = (uint) policy;
-}
-
-/*!
- \property QWidget::focusPolicy
- \brief the way the widget accepts keyboard focus
-
- The policy is Qt::TabFocus if the widget accepts keyboard
- focus by tabbing, Qt::ClickFocus if the widget accepts
- focus by clicking, Qt::StrongFocus if it accepts both, and
- Qt::NoFocus (the default) if it does not accept focus at
- all.
-
- You must enable keyboard focus for a widget if it processes
- keyboard events. This is normally done from the widget's
- constructor. For instance, the QLineEdit constructor calls
- setFocusPolicy(Qt::StrongFocus).
-
- If the widget has a focus proxy, then the focus policy will
- be propagated to it.
-
- \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
-*/
-
-
-Qt::FocusPolicy QWidget::focusPolicy() const
-{
- return (Qt::FocusPolicy)data->focus_policy;
-}
-
-void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
-{
- data->focus_policy = (uint) policy;
- Q_D(QWidget);
- if (d->extra && d->extra->focus_proxy)
- d->extra->focus_proxy->setFocusPolicy(policy);
-}
-
-/*!
- \property QWidget::updatesEnabled
- \brief whether updates are enabled
-
- An updates enabled widget receives paint events and has a system
- background; a disabled widget does not. This also implies that
- calling update() and repaint() has no effect if updates are
- disabled.
-
- By default, this property is true.
-
- setUpdatesEnabled() is normally used to disable updates for a
- short period of time, for instance to avoid screen flicker during
- large changes. In Qt, widgets normally do not generate screen
- flicker, but on X11 the server might erase regions on the screen
- when widgets get hidden before they can be replaced by other
- widgets. Disabling updates solves this.
-
- Example:
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
-
- Disabling a widget implicitly disables all its children. Enabling a widget
- enables all child widgets \e except top-level widgets or those that
- have been explicitly disabled. Re-enabling updates implicitly calls
- update() on the widget.
-
- \sa paintEvent()
-*/
-void QWidget::setUpdatesEnabled(bool enable)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
- d->setUpdatesEnabled_helper(enable);
-}
-
-/*! \fn void QWidget::show()
-
- Shows the widget and its child widgets. This function is
- equivalent to setVisible(true).
-
- \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
- showNormal(), isVisible()
-*/
-
-
-/*! \internal
-
- Makes the widget visible in the isVisible() meaning of the word.
- It is only called for toplevels or widgets with visible parents.
- */
-void QWidgetPrivate::show_recursive()
-{
- Q_Q(QWidget);
- // polish if necessary
-
- if (!q->testAttribute(Qt::WA_WState_Created))
- createRecursively();
- q->ensurePolished();
-
-#ifdef QT3_SUPPORT
- if(sendChildEvents)
- QApplication::sendPostedEvents(q, QEvent::ChildInserted);
-#endif
- if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
- q->parentWidget()->d_func()->layout->activate();
- // activate our layout before we and our children become visible
- if (layout)
- layout->activate();
-
- show_helper();
-}
-
-void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
-{
- Q_Q(QWidget);
-
- disableUpdates = disableUpdates && q->updatesEnabled();
- if (disableUpdates)
- q->setAttribute(Qt::WA_UpdatesDisabled);
-
- if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
- QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
- QApplication::sendEvent(q, &e);
- q->setAttribute(Qt::WA_PendingMoveEvent, false);
- }
-
- if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
- QResizeEvent e(data.crect.size(), QSize());
- QApplication::sendEvent(q, &e);
- q->setAttribute(Qt::WA_PendingResizeEvent, false);
- }
-
- if (disableUpdates)
- q->setAttribute(Qt::WA_UpdatesDisabled, false);
-
- if (!recursive)
- return;
-
- for (int i = 0; i < children.size(); ++i) {
- if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
- child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
- }
-}
-
-void QWidgetPrivate::activateChildLayoutsRecursively()
-{
- sendPendingMoveAndResizeEvents(false, true);
-
- for (int i = 0; i < children.size(); ++i) {
- QWidget *child = qobject_cast<QWidget *>(children.at(i));
- if (!child || child->isHidden() || child->isWindow())
- continue;
-
- child->ensurePolished();
-
- // Activate child's layout
- QWidgetPrivate *childPrivate = child->d_func();
- if (childPrivate->layout)
- childPrivate->layout->activate();
-
- // Pretend we're visible.
- const bool wasVisible = child->isVisible();
- if (!wasVisible)
- child->setAttribute(Qt::WA_WState_Visible);
-
- // Do the same for all my children.
- childPrivate->activateChildLayoutsRecursively();
-
- // We're not cheating anymore.
- if (!wasVisible)
- child->setAttribute(Qt::WA_WState_Visible, false);
- }
-}
-
-void QWidgetPrivate::show_helper()
-{
- Q_Q(QWidget);
- data.in_show = true; // qws optimization
- // make sure we receive pending move and resize events
- sendPendingMoveAndResizeEvents();
-
- // become visible before showing all children
- q->setAttribute(Qt::WA_WState_Visible);
-
- // finally show all children recursively
- showChildren(false);
-
-#ifdef QT3_SUPPORT
- if (q->parentWidget() && sendChildEvents)
- QApplication::sendPostedEvents(q->parentWidget(),
- QEvent::ChildInserted);
-#endif
-
-
- // popup handling: new popups and tools need to be raised, and
- // existing popups must be closed. Also propagate the current
- // windows's KeyboardFocusChange status.
- if (q->isWindow()) {
- if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
- q->raise();
- if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
- q->setAttribute(Qt::WA_KeyboardFocusChange);
- } else {
- while (QApplication::activePopupWidget()) {
- if (!QApplication::activePopupWidget()->close())
- break;
- }
- }
- }
-
- // Automatic embedding of child windows of widgets already embedded into
- // QGraphicsProxyWidget when they are shown the first time.
- bool isEmbedded = false;
-#ifndef QT_NO_GRAPHICSVIEW
- if (q->isWindow()) {
- isEmbedded = q->graphicsProxyWidget() ? true : false;
- if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
- QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
- if (ancestorProxy) {
- isEmbedded = true;
- ancestorProxy->d_func()->embedSubWindow(q);
- }
- }
- }
-#else
- Q_UNUSED(isEmbedded);
-#endif
-
- // On Windows, show the popup now so that our own focus handling
- // stores the correct old focus widget even if it's stolen in the
- // showevent
-#if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
- if (!isEmbedded && q->windowType() == Qt::Popup)
- qApp->d_func()->openPopup(q);
-#endif
-
- // send the show event before showing the window
- QShowEvent showEvent;
- QApplication::sendEvent(q, &showEvent);
-
- if (!isEmbedded && q->isModal() && q->isWindow())
- // QApplicationPrivate::enterModal *before* show, otherwise the initial
- // stacking might be wrong
- QApplicationPrivate::enterModal(q);
-
-
- show_sys();
-
-#if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
- if (!isEmbedded && q->windowType() == Qt::Popup)
- qApp->d_func()->openPopup(q);
-#endif
-
-#ifndef QT_NO_ACCESSIBILITY
- if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator.
- QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow);
-#endif
-
- if (QApplicationPrivate::hidden_focus_widget == q) {
- QApplicationPrivate::hidden_focus_widget = 0;
- q->setFocus(Qt::OtherFocusReason);
- }
-
- // Process events when showing a Qt::SplashScreen widget before the event loop
- // is spinnning; otherwise it might not show up on particular platforms.
- // This makes QSplashScreen behave the same on all platforms.
- if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
- QApplication::processEvents();
-
- data.in_show = false; // reset qws optimization
-}
-
-/*! \fn void QWidget::hide()
-
- Hides the widget. This function is equivalent to
- setVisible(false).
-
-
- \note If you are working with QDialog or its subclasses and you invoke
- the show() function after this function, the dialog will be displayed in
- its original position.
-
- \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
-*/
-
-/*!\internal
- */
-void QWidgetPrivate::hide_helper()
-{
- Q_Q(QWidget);
-
- bool isEmbedded = false;
-#if !defined QT_NO_GRAPHICSVIEW
- isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
-#else
- Q_UNUSED(isEmbedded);
-#endif
-
- if (!isEmbedded && (q->windowType() == Qt::Popup))
- qApp->d_func()->closePopup(q);
-
- // Move test modal here. Otherwise, a modal dialog could get
- // destroyed and we lose all access to its parent because we haven't
- // left modality. (Eg. modal Progress Dialog)
- if (!isEmbedded && q->isModal() && q->isWindow())
- QApplicationPrivate::leaveModal(q);
-
-#if defined(Q_WS_WIN)
- if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
- && !q->parentWidget()->isHidden() && q->isActiveWindow())
- q->parentWidget()->activateWindow(); // Activate parent
-#endif
-
- q->setAttribute(Qt::WA_Mapped, false);
- hide_sys();
-
- bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
-
- if (wasVisible) {
- q->setAttribute(Qt::WA_WState_Visible, false);
-
- }
-
- QHideEvent hideEvent;
- QApplication::sendEvent(q, &hideEvent);
- hideChildren(false);
-
- // next bit tries to move the focus if the focus widget is now
- // hidden.
- if (wasVisible) {
-#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
- qApp->d_func()->sendSyntheticEnterLeave(q);
-#endif
-
- QWidget *fw = QApplication::focusWidget();
- while (fw && !fw->isWindow()) {
- if (fw == q) {
- q->focusNextPrevChild(true);
- break;
- }
- fw = fw->parentWidget();
- }
- }
-
- if (QWidgetBackingStore *bs = maybeBackingStore())
- bs->removeDirtyWidget(q);
-
-#ifndef QT_NO_ACCESSIBILITY
- if (wasVisible)
- QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide);
-#endif
-}
-
-/*!
- \fn bool QWidget::isHidden() const
-
- Returns true if the widget is hidden, otherwise returns false.
-
- A hidden widget will only become visible when show() is called on
- it. It will not be automatically shown when the parent is shown.
-
- To check visibility, use !isVisible() instead (notice the exclamation mark).
-
- isHidden() implies !isVisible(), but a widget can be not visible
- and not hidden at the same time. This is the case for widgets that are children of
- widgets that are not visible.
-
-
- Widgets are hidden if:
- \list
- \o they were created as independent windows,
- \o they were created as children of visible widgets,
- \o hide() or setVisible(false) was called.
- \endlist
-*/
-
-
-void QWidget::setVisible(bool visible)
-{
- if (visible) { // show
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
- return;
-
- Q_D(QWidget);
-
- // Designer uses a trick to make grabWidget work without showing
- if (!isWindow() && parentWidget() && parentWidget()->isVisible()
- && !parentWidget()->testAttribute(Qt::WA_WState_Created))
- parentWidget()->window()->d_func()->createRecursively();
-
- //we have to at least create toplevels before applyX11SpecificCommandLineArguments
- //but not children of non-visible parents
- QWidget *pw = parentWidget();
- if (!testAttribute(Qt::WA_WState_Created)
- && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
- create();
- }
-
-#if defined(Q_WS_X11)
- if (windowType() == Qt::Window)
- QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
-#elif defined(Q_WS_QWS)
- if (windowType() == Qt::Window)
- QApplicationPrivate::applyQWSSpecificCommandLineArguments(this);
-#endif
-
- bool wasResized = testAttribute(Qt::WA_Resized);
- Qt::WindowStates initialWindowState = windowState();
-
- // polish if necessary
- ensurePolished();
-
- // remember that show was called explicitly
- setAttribute(Qt::WA_WState_ExplicitShowHide);
- // whether we need to inform the parent widget immediately
- bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
- // we are no longer hidden
- setAttribute(Qt::WA_WState_Hidden, false);
-
- if (needUpdateGeometry)
- d->updateGeometry_helper(true);
-
-#ifdef QT3_SUPPORT
- QApplication::sendPostedEvents(this, QEvent::ChildInserted);
-#endif
- // activate our layout before we and our children become visible
- if (d->layout)
- d->layout->activate();
-
- if (!isWindow()) {
- QWidget *parent = parentWidget();
- while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
- parent->d_func()->layout->activate();
- if (parent->isWindow())
- break;
- parent = parent->parentWidget();
- }
- if (parent)
- parent->d_func()->setDirtyOpaqueRegion();
- }
-
- // adjust size if necessary
- if (!wasResized
- && (isWindow() || !parentWidget()->d_func()->layout)) {
- if (isWindow()) {
- adjustSize();
- if (windowState() != initialWindowState)
- setWindowState(initialWindowState);
- } else {
- adjustSize();
- }
- setAttribute(Qt::WA_Resized, false);
- }
-
- setAttribute(Qt::WA_KeyboardFocusChange, false);
-
- if (isWindow() || parentWidget()->isVisible()) {
- // remove posted quit events when showing a new window
- QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
-
- d->show_helper();
-
-#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
- qApp->d_func()->sendSyntheticEnterLeave(this);
-#endif
- }
-
- QEvent showToParentEvent(QEvent::ShowToParent);
- QApplication::sendEvent(this, &showToParentEvent);
- } else { // hide
- if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
- return;
-#if defined(Q_WS_WIN)
- // reset WS_DISABLED style in a Blocked window
- if(isWindow() && testAttribute(Qt::WA_WState_Created)
- && QApplicationPrivate::isBlockedByModal(this))
- {
- LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
- dwStyle &= ~WS_DISABLED;
- SetWindowLong(winId(), GWL_STYLE, dwStyle);
- }
-#endif
- if (QApplicationPrivate::hidden_focus_widget == this)
- QApplicationPrivate::hidden_focus_widget = 0;
-
- Q_D(QWidget);
-
- // hw: The test on getOpaqueRegion() needs to be more intelligent
- // currently it doesn't work if the widget is hidden (the region will
- // be clipped). The real check should be testing the cached region
- // (and dirty flag) directly.
- if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
- parentWidget()->d_func()->setDirtyOpaqueRegion();
-
- setAttribute(Qt::WA_WState_Hidden);
- setAttribute(Qt::WA_WState_ExplicitShowHide);
- if (testAttribute(Qt::WA_WState_Created))
- d->hide_helper();
-
- // invalidate layout similar to updateGeometry()
- if (!isWindow() && parentWidget()) {
- if (parentWidget()->d_func()->layout)
- parentWidget()->d_func()->layout->invalidate();
- else if (parentWidget()->isVisible())
- QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
- }
-
- QEvent hideToParentEvent(QEvent::HideToParent);
- QApplication::sendEvent(this, &hideToParentEvent);
- }
-}
-
-/*!\fn void QWidget::setHidden(bool hidden)
-
- Convenience function, equivalent to setVisible(!\a hidden).
-*/
-
-/*!\fn void QWidget::setShown(bool shown)
-
- Use setVisible(\a shown) instead.
-*/
-
-
-void QWidgetPrivate::_q_showIfNotHidden()
-{
- Q_Q(QWidget);
- if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
- q->setVisible(true);
-}
-
-void QWidgetPrivate::showChildren(bool spontaneous)
-{
- QList<QObject*> childList = children;
- for (int i = 0; i < childList.size(); ++i) {
- QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
- if (!widget
- || widget->isWindow()
- || widget->testAttribute(Qt::WA_WState_Hidden))
- continue;
- if (spontaneous) {
- widget->setAttribute(Qt::WA_Mapped);
- widget->d_func()->showChildren(true);
- QShowEvent e;
- QApplication::sendSpontaneousEvent(widget, &e);
- } else {
- if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
- widget->d_func()->show_recursive();
- else
- widget->show();
- }
- }
-}
-
-void QWidgetPrivate::hideChildren(bool spontaneous)
-{
- QList<QObject*> childList = children;
- for (int i = 0; i < childList.size(); ++i) {
- QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
- if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
- continue;
-#ifdef QT_MAC_USE_COCOA
- // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
- // When hiding a widget we need to make sure that no mouse_down events are active, because
- // the mouse_up event will never be received by a hidden widget or one of its descendants.
- // The solution is simple, before going through with this we check if there are any mouse_down events in
- // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
- // then we continue.
- // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
- // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
- // mouse release event. There are two ways to interpret this:
- // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
- // might be waiting for a release event that will never arrive.
- // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
- // supposed to trigger because it is not visible.
- if(widget == qt_button_down)
- qt_button_down = 0;
-#endif // QT_MAC_USE_COCOA
- if (spontaneous)
- widget->setAttribute(Qt::WA_Mapped, false);
- else
- widget->setAttribute(Qt::WA_WState_Visible, false);
- widget->d_func()->hideChildren(spontaneous);
- QHideEvent e;
- if (spontaneous) {
- QApplication::sendSpontaneousEvent(widget, &e);
- } else {
- QApplication::sendEvent(widget, &e);
- if (widget->internalWinId()
- && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
- // hide_sys() on an ancestor won't have any affect on this
- // widget, so it needs an explicit hide_sys() of its own
- widget->d_func()->hide_sys();
- }
- }
-#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
- qApp->d_func()->sendSyntheticEnterLeave(widget);
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- if (!spontaneous)
- QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide);
-#endif
- }
-}
-
-bool QWidgetPrivate::close_helper(CloseMode mode)
-{
- if (data.is_closing)
- return true;
-
- Q_Q(QWidget);
- data.is_closing = 1;
-
- QPointer<QWidget> that = q;
- QPointer<QWidget> parentWidget = q->parentWidget();
-
-#ifdef QT3_SUPPORT
- bool isMain = (QApplicationPrivate::main_widget == q);
-#endif
- bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
- if (mode != CloseNoEvent) {
- QCloseEvent e;
- if (mode == CloseWithSpontaneousEvent)
- QApplication::sendSpontaneousEvent(q, &e);
- else
- QApplication::sendEvent(q, &e);
- if (!that.isNull() && !e.isAccepted()) {
- data.is_closing = 0;
- return false;
- }
- }
-
- if (!that.isNull() && !q->isHidden())
- q->hide();
-
-#ifdef QT3_SUPPORT
- if (isMain)
- QApplication::quit();
-#endif
- // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
- quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
-
- if (quitOnClose) {
- /* if there is no non-withdrawn primary window left (except
- the ones without QuitOnClose), we emit the lastWindowClosed
- signal */
- QWidgetList list = QApplication::topLevelWidgets();
- bool lastWindowClosed = true;
- for (int i = 0; i < list.size(); ++i) {
- QWidget *w = list.at(i);
- if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
- continue;
- lastWindowClosed = false;
- break;
- }
- if (lastWindowClosed)
- QApplicationPrivate::emitLastWindowClosed();
- }
-
- if (!that.isNull()) {
- data.is_closing = 0;
- if (q->testAttribute(Qt::WA_DeleteOnClose)) {
- q->setAttribute(Qt::WA_DeleteOnClose, false);
- q->deleteLater();
- }
- }
- return true;
-}
-
-
-/*!
- Closes this widget. Returns true if the widget was closed;
- otherwise returns false.
-
- First it sends the widget a QCloseEvent. The widget is \link
- hide() hidden\endlink if it \link QCloseEvent::accept()
- accepts\endlink the close event. If it \link QCloseEvent::ignore()
- ignores\endlink the event, nothing happens. The default
- implementation of QWidget::closeEvent() accepts the close event.
-
- If the widget has the Qt::WA_DeleteOnClose flag, the widget
- is also deleted. A close events is delivered to the widget no
- matter if the widget is visible or not.
-
- The \l QApplication::lastWindowClosed() signal is emitted 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 transient windows such as
- splash screens, tool windows, and popup menus.
-
-*/
-
-bool QWidget::close()
-{
- return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
-}
-
-/*!
- \property QWidget::visible
- \brief whether the widget is visible
-
- Calling setVisible(true) or show() sets the widget to visible
- status if all its parent widgets up to the window are visible. If
- an ancestor is not visible, the widget won't become visible until
- all its ancestors are shown. If its size or position has changed,
- Qt guarantees that a widget gets move and resize events just
- before it is shown. If the widget has not been resized yet, Qt
- will adjust the widget's size to a useful default using
- adjustSize().
-
- Calling setVisible(false) or hide() hides a widget explicitly. An
- explicitly hidden widget will never become visible, even if all
- its ancestors become visible, unless you show it.
-
- A widget receives show and hide events when its visibility status
- changes. Between a hide and a show event, there is no need to
- waste CPU cycles preparing or displaying information to the user.
- A video application, for example, might simply stop generating new
- frames.
-
- A widget that happens to be obscured by other windows on the
- screen is considered to be visible. The same applies to iconified
- windows and windows that exist on another virtual
- desktop (on platforms that support this concept). A widget
- receives spontaneous show and hide events when its mapping status
- is changed by the window system, e.g. a spontaneous hide event
- when the user minimizes the window, and a spontaneous show event
- when the window is restored again.
-
- You almost never have to reimplement the setVisible() function. If
- you need to change some settings before a widget is shown, use
- showEvent() instead. If you need to do some delayed initialization
- use the Polish event delivered to the event() function.
-
- \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
- showEvent(), hideEvent()
-*/
-
-
-/*!
- Returns true if this widget would become visible if \a ancestor is
- shown; otherwise returns false.
-
- The true case occurs if neither the widget itself nor any parent
- up to but excluding \a ancestor has been explicitly hidden.
-
- This function will still return true if the widget is obscured by
- other windows on the screen, but could be physically visible if it
- or they were to be moved.
-
- isVisibleTo(0) is identical to isVisible().
-
- \sa show() hide() isVisible()
-*/
-
-bool QWidget::isVisibleTo(QWidget* ancestor) const
-{
- if (!ancestor)
- return isVisible();
- const QWidget * w = this;
- while (!w->isHidden()
- && !w->isWindow()
- && w->parentWidget()
- && w->parentWidget() != ancestor)
- w = w->parentWidget();
- return !w->isHidden();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use visibleRegion() instead.
-*/
-QRect QWidget::visibleRect() const
-{
- return d_func()->clipRect();
-}
-#endif
-
-/*!
- Returns the unobscured region where paint events can occur.
-
- For visible widgets, this is an approximation of the area not
- covered by other widgets; otherwise, this is an empty region.
-
- The repaint() function calls this function if necessary, so in
- general you do not need to call it.
-
-*/
-QRegion QWidget::visibleRegion() const
-{
- Q_D(const QWidget);
-
- QRect clipRect = d->clipRect();
- if (clipRect.isEmpty())
- return QRegion();
- QRegion r(clipRect);
- d->subtractOpaqueChildren(r, clipRect);
- d->subtractOpaqueSiblings(r);
-#ifdef Q_WS_QWS
- const QWSWindowSurface *surface = static_cast<const QWSWindowSurface*>(windowSurface());
- if (surface) {
- const QPoint offset = mapTo(surface->window(), QPoint());
- r &= surface->clipRegion().translated(-offset);
- }
-#endif
- return r;
-}
-
-
-QSize QWidgetPrivate::adjustedSize() const
-{
- Q_Q(const QWidget);
-
- QSize s = q->sizeHint();
-
- if (q->isWindow()) {
- Qt::Orientations exp;
- if (layout) {
- if (layout->hasHeightForWidth())
- s.setHeight(layout->totalHeightForWidth(s.width()));
- exp = layout->expandingDirections();
- } else
- {
- if (q->sizePolicy().hasHeightForWidth())
- s.setHeight(q->heightForWidth(s.width()));
- exp = q->sizePolicy().expandingDirections();
- }
- if (exp & Qt::Horizontal)
- s.setWidth(qMax(s.width(), 200));
- if (exp & Qt::Vertical)
- s.setHeight(qMax(s.height(), 100));
-#if defined(Q_WS_X11)
- QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
-#else // all others
- QRect screen = QApplication::desktop()->screenGeometry(q->pos());
-#endif
-#if defined (Q_WS_WINCE) || defined (Q_OS_SYMBIAN)
- s.setWidth(qMin(s.width(), screen.width()));
- s.setHeight(qMin(s.height(), screen.height()));
-#else
- s.setWidth(qMin(s.width(), screen.width()*2/3));
- s.setHeight(qMin(s.height(), screen.height()*2/3));
-#endif
- if (QTLWExtra *extra = maybeTopData())
- extra->sizeAdjusted = true;
- }
-
- if (!s.isValid()) {
- QRect r = q->childrenRect(); // get children rectangle
- if (r.isNull())
- return s;
- s = r.size() + QSize(2 * r.x(), 2 * r.y());
- }
-
- return s;
-}
-
-/*!
- Adjusts the size of the widget to fit its contents.
-
- This function uses sizeHint() if it is valid, i.e., the size hint's width
- and height are \>= 0. Otherwise, it sets the size to the children
- rectangle that covers all child widgets (the union of all child widget
- rectangles).
-
- For windows, the screen size is also taken into account. If the sizeHint()
- is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
- {expanding}, the window will be at least (200, 100). The maximum size of
- a window is 2/3 of the screen's width and height.
-
- \sa sizeHint(), childrenRect()
-*/
-
-void QWidget::adjustSize()
-{
- Q_D(QWidget);
- ensurePolished();
- QSize s = d->adjustedSize();
-
- if (d->layout)
- d->layout->activate();
-
- if (s.isValid())
- resize(s);
-}
-
-
-/*!
- \property QWidget::sizeHint
- \brief the recommended size for the widget
-
- If the value of this property is an invalid size, no size is
- recommended.
-
- The default implementation of sizeHint() returns an invalid size
- if there is no layout for this widget, and returns the layout's
- preferred size otherwise.
-
- \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
- setMinimumSize(), updateGeometry()
-*/
-
-QSize QWidget::sizeHint() const
-{
- Q_D(const QWidget);
- if (d->layout)
- return d->layout->totalSizeHint();
- return QSize(-1, -1);
-}
-
-/*!
- \property QWidget::minimumSizeHint
- \brief the recommended minimum size for the widget
-
- If the value of this property is an invalid size, no minimum size
- is recommended.
-
- The default implementation of minimumSizeHint() returns an invalid
- size if there is no layout for this widget, and returns the
- layout's minimum size otherwise. Most built-in widgets reimplement
- minimumSizeHint().
-
- \l QLayout will never resize a widget to a size smaller than the
- minimum size hint unless minimumSize() is set or the size policy is
- set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
- size hint will be ignored.
-
- \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
-*/
-QSize QWidget::minimumSizeHint() const
-{
- Q_D(const QWidget);
- if (d->layout)
- return d->layout->totalMinimumSize();
- return QSize(-1, -1);
-}
-
-
-/*!
- \fn QWidget *QWidget::parentWidget() const
-
- Returns the parent of this widget, or 0 if it does not have any
- parent widget.
-*/
-
-
-/*!
- Returns true if this widget is a parent, (or grandparent and so on
- to any level), of the given \a child, and both widgets are within
- the same window; otherwise returns false.
-*/
-
-bool QWidget::isAncestorOf(const QWidget *child) const
-{
- while (child) {
- if (child == this)
- return true;
- if (child->isWindow())
- return false;
- child = child->parentWidget();
- }
- return false;
-}
-
-#if defined(Q_WS_WIN)
-inline void setDisabledStyle(QWidget *w, bool setStyle)
-{
- // set/reset WS_DISABLED style.
- if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
- LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
- LONG newStyle = dwStyle;
- if (setStyle)
- newStyle |= WS_DISABLED;
- else
- newStyle &= ~WS_DISABLED;
- if (newStyle != dwStyle) {
- SetWindowLong(w->winId(), GWL_STYLE, newStyle);
- // we might need to repaint in some situations (eg. menu)
- w->repaint();
- }
- }
-}
-#endif
-
-/*****************************************************************************
- QWidget event handling
- *****************************************************************************/
-
-/*!
- This is the main event handler; it handles event \a event. You can
- reimplement this function in a subclass, but we recommend using
- one of the specialized event handlers instead.
-
- Key press and release events are treated differently from other
- events. event() checks for Tab and Shift+Tab and tries to move the
- focus appropriately. If there is no widget to move the focus to
- (or the key press is not Tab or Shift+Tab), event() calls
- keyPressEvent().
-
- Mouse and tablet event handling is also slightly special: only
- when the widget is \l enabled, event() will call the specialized
- handlers such as mousePressEvent(); otherwise it will discard the
- event.
-
- This function returns true if the event was recognized, otherwise
- it returns false. If the recognized event was accepted (see \l
- QEvent::accepted), any further processing such as event
- propagation to the parent widget stops.
-
- \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
- keyPressEvent(), keyReleaseEvent(), leaveEvent(),
- mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
- mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
- QObject::event(), QObject::timerEvent()
-*/
-
-bool QWidget::event(QEvent *event)
-{
- Q_D(QWidget);
-
- // ignore mouse events when disabled
- if (!isEnabled()) {
- switch(event->type()) {
- case QEvent::TabletPress:
- case QEvent::TabletRelease:
- case QEvent::TabletMove:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- case QEvent::ContextMenu:
-#ifndef QT_NO_WHEELEVENT
- case QEvent::Wheel:
-#endif
- return false;
- default:
- break;
- }
- }
- switch (event->type()) {
- case QEvent::MouseMove:
- mouseMoveEvent((QMouseEvent*)event);
- break;
-
- case QEvent::MouseButtonPress:
- // Don't reset input context here. Whether reset or not is
- // a responsibility of input method. reset() will be
- // called by mouseHandler() of input method if necessary
- // via mousePressEvent() of text widgets.
-#if 0
- resetInputContext();
-#endif
- mousePressEvent((QMouseEvent*)event);
- break;
-
- case QEvent::MouseButtonRelease:
- mouseReleaseEvent((QMouseEvent*)event);
- break;
-
- case QEvent::MouseButtonDblClick:
- mouseDoubleClickEvent((QMouseEvent*)event);
- break;
-#ifndef QT_NO_WHEELEVENT
- case QEvent::Wheel:
- wheelEvent((QWheelEvent*)event);
- break;
-#endif
-#ifndef QT_NO_TABLETEVENT
- case QEvent::TabletMove:
- case QEvent::TabletPress:
- case QEvent::TabletRelease:
- tabletEvent((QTabletEvent*)event);
- break;
-#endif
-#ifdef QT3_SUPPORT
- case QEvent::Accel:
- event->ignore();
- return false;
-#endif
- case QEvent::KeyPress: {
- QKeyEvent *k = (QKeyEvent *)event;
- bool res = false;
- if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
- if (k->key() == Qt::Key_Backtab
- || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
- res = focusNextPrevChild(false);
- else if (k->key() == Qt::Key_Tab)
- res = focusNextPrevChild(true);
- if (res)
- break;
- }
- keyPressEvent(k);
-#ifdef QT_KEYPAD_NAVIGATION
- if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
- && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
- if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
- if (k->key() == Qt::Key_Up)
- res = focusNextPrevChild(false);
- else if (k->key() == Qt::Key_Down)
- res = focusNextPrevChild(true);
- } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
- if (k->key() == Qt::Key_Up)
- res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
- else if (k->key() == Qt::Key_Right)
- res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
- else if (k->key() == Qt::Key_Down)
- res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
- else if (k->key() == Qt::Key_Left)
- res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
- }
- if (res) {
- k->accept();
- break;
- }
- }
-#endif
-#ifndef QT_NO_WHATSTHIS
- if (!k->isAccepted()
- && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
- && d->whatsThis.size()) {
- QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImMicroFocus).toRect().center()), d->whatsThis, this);
- k->accept();
- }
-#endif
- }
- break;
-
- case QEvent::KeyRelease:
- keyReleaseEvent((QKeyEvent*)event);
- // fall through
- case QEvent::ShortcutOverride:
- break;
-
- case QEvent::InputMethod:
- inputMethodEvent((QInputMethodEvent *) event);
- break;
-
- case QEvent::PolishRequest:
- ensurePolished();
- break;
-
- case QEvent::Polish: {
- style()->polish(this);
- setAttribute(Qt::WA_WState_Polished);
- if (!QApplication::font(this).isCopyOf(QApplication::font()))
- d->resolveFont();
- if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
- d->resolvePalette();
-#ifdef QT3_SUPPORT
- if(d->sendChildEvents)
- QApplication::sendPostedEvents(this, QEvent::ChildInserted);
-#endif
- }
- break;
-
- case QEvent::ApplicationWindowIconChange:
- if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
- d->setWindowIcon_sys();
- d->setWindowIcon_helper();
- }
- break;
- case QEvent::FocusIn:
-#ifdef QT_SOFTKEYS_ENABLED
- QSoftKeyManager::updateSoftKeys();
-#endif
- focusInEvent((QFocusEvent*)event);
- break;
-
- case QEvent::FocusOut:
- focusOutEvent((QFocusEvent*)event);
- break;
-
- case QEvent::Enter:
-#ifndef QT_NO_STATUSTIP
- if (d->statusTip.size()) {
- QStatusTipEvent tip(d->statusTip);
- QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
- }
-#endif
- enterEvent(event);
- break;
-
- case QEvent::Leave:
-#ifndef QT_NO_STATUSTIP
- if (d->statusTip.size()) {
- QString empty;
- QStatusTipEvent tip(empty);
- QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
- }
-#endif
- leaveEvent(event);
- break;
-
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- update();
- break;
-
- case QEvent::Paint:
- // At this point the event has to be delivered, regardless
- // whether the widget isVisible() or not because it
- // already went through the filters
- paintEvent((QPaintEvent*)event);
- break;
-
- case QEvent::Move:
- moveEvent((QMoveEvent*)event);
- break;
-
- case QEvent::Resize:
- resizeEvent((QResizeEvent*)event);
- break;
-
- case QEvent::Close:
- closeEvent((QCloseEvent *)event);
- break;
-
-#ifndef QT_NO_CONTEXTMENU
- case QEvent::ContextMenu:
- switch (data->context_menu_policy) {
- case Qt::PreventContextMenu:
- break;
- case Qt::DefaultContextMenu:
- contextMenuEvent(static_cast<QContextMenuEvent *>(event));
- break;
- case Qt::CustomContextMenu:
- emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
- break;
-#ifndef QT_NO_MENU
- case Qt::ActionsContextMenu:
- if (d->actions.count()) {
- QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
- 0, this);
- break;
- }
- // fall through
-#endif
- default:
- event->ignore();
- break;
- }
- break;
-#endif // QT_NO_CONTEXTMENU
-
-#ifndef QT_NO_DRAGANDDROP
- case QEvent::Drop:
- dropEvent((QDropEvent*) event);
- break;
-
- case QEvent::DragEnter:
- dragEnterEvent((QDragEnterEvent*) event);
- break;
-
- case QEvent::DragMove:
- dragMoveEvent((QDragMoveEvent*) event);
- break;
-
- case QEvent::DragLeave:
- dragLeaveEvent((QDragLeaveEvent*) event);
- break;
-#endif
-
- case QEvent::Show:
- showEvent((QShowEvent*) event);
- break;
-
- case QEvent::Hide:
- hideEvent((QHideEvent*) event);
- break;
-
- case QEvent::ShowWindowRequest:
- if (!isHidden())
- d->show_sys();
- break;
-
- case QEvent::ApplicationFontChange:
- d->resolveFont();
- break;
- case QEvent::ApplicationPaletteChange:
- if (!(windowType() == Qt::Desktop))
- d->resolvePalette();
- break;
-
- case QEvent::ToolBarChange:
- case QEvent::ActivationChange:
- case QEvent::EnabledChange:
- case QEvent::FontChange:
- case QEvent::StyleChange:
- case QEvent::PaletteChange:
- case QEvent::WindowTitleChange:
- case QEvent::IconTextChange:
- case QEvent::ModifiedChange:
- case QEvent::MouseTrackingChange:
- case QEvent::ParentChange:
- case QEvent::WindowStateChange:
- case QEvent::LocaleChange:
- case QEvent::MacSizeChange:
- case QEvent::ContentsRectChange:
- changeEvent(event);
- break;
-
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate: {
-#ifdef QT3_SUPPORT
- windowActivationChange(event->type() != QEvent::WindowActivate);
-#endif
- if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
- update();
- QList<QObject*> childList = d->children;
- for (int i = 0; i < childList.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(childList.at(i));
- if (w && w->isVisible() && !w->isWindow())
- QApplication::sendEvent(w, event);
- }
-
-#ifdef QT_SOFTKEYS_ENABLED
- if (isWindow())
- QSoftKeyManager::updateSoftKeys();
-#endif
-
- break; }
-
- case QEvent::LanguageChange:
-#ifdef QT3_SUPPORT
- languageChange();
-#endif
- changeEvent(event);
- {
- QList<QObject*> childList = d->children;
- for (int i = 0; i < childList.size(); ++i) {
- QObject *o = childList.at(i);
- if (o)
- QApplication::sendEvent(o, event);
- }
- }
- update();
- break;
-
- case QEvent::ApplicationLayoutDirectionChange:
- d->resolveLayoutDirection();
- break;
-
- case QEvent::LayoutDirectionChange:
- if (d->layout)
- d->layout->invalidate();
- update();
- changeEvent(event);
- break;
- case QEvent::UpdateRequest:
- d->syncBackingStore();
- break;
- case QEvent::UpdateLater:
- update(static_cast<QUpdateLaterEvent*>(event)->region());
- break;
-
- case QEvent::WindowBlocked:
- case QEvent::WindowUnblocked:
- {
- QList<QObject*> childList = d->children;
- for (int i = 0; i < childList.size(); ++i) {
- QObject *o = childList.at(i);
- if (o && o != QApplication::activeModalWidget()) {
- if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
- // do not forward the event to child windows,
- // QApplication does this for us
- continue;
- }
- QApplication::sendEvent(o, event);
- }
- }
-#if defined(Q_WS_WIN)
- setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
-#endif
- }
- break;
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTip:
- if (!d->toolTip.isEmpty())
- QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
- else
- event->ignore();
- break;
-#endif
-#ifndef QT_NO_WHATSTHIS
- case QEvent::WhatsThis:
- if (d->whatsThis.size())
- QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
- else
- event->ignore();
- break;
- case QEvent::QueryWhatsThis:
- if (d->whatsThis.isEmpty())
- event->ignore();
- break;
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- case QEvent::AccessibilityDescription:
- case QEvent::AccessibilityHelp: {
- QAccessibleEvent *ev = static_cast<QAccessibleEvent *>(event);
- if (ev->child())
- return false;
- switch (ev->type()) {
-#ifndef QT_NO_TOOLTIP
- case QEvent::AccessibilityDescription:
- ev->setValue(d->toolTip);
- break;
-#endif
-#ifndef QT_NO_WHATSTHIS
- case QEvent::AccessibilityHelp:
- ev->setValue(d->whatsThis);
- break;
-#endif
- default:
- return false;
- }
- break; }
-#endif
- case QEvent::EmbeddingControl:
- d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
- data->fstrut_dirty = false;
-#if defined(Q_WS_WIN) || defined(Q_WS_X11)
- d->topData()->embedded = 1;
-#endif
- break;
-#ifndef QT_NO_ACTION
- case QEvent::ActionAdded:
- case QEvent::ActionRemoved:
- case QEvent::ActionChanged:
-#ifdef QT_SOFTKEYS_ENABLED
- QSoftKeyManager::updateSoftKeys();
-#endif
- actionEvent((QActionEvent*)event);
- break;
-#endif
-
- case QEvent::KeyboardLayoutChange:
- {
- changeEvent(event);
-
- // inform children of the change
- QList<QObject*> childList = d->children;
- for (int i = 0; i < childList.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(childList.at(i));
- if (w && w->isVisible() && !w->isWindow())
- QApplication::sendEvent(w, event);
- }
- break;
- }
-#ifdef Q_WS_MAC
- case QEvent::MacGLWindowChange:
- d->needWindowChange = false;
- break;
-#endif
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- {
-#ifndef Q_WS_MAC
- QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
- const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first();
- if (touchPoint.isPrimary() || touchEvent->deviceType() == QTouchEvent::TouchPad)
- break;
-
- // fake a mouse event!
- QEvent::Type eventType = QEvent::None;
- switch (touchEvent->type()) {
- case QEvent::TouchBegin:
- eventType = QEvent::MouseButtonPress;
- break;
- case QEvent::TouchUpdate:
- eventType = QEvent::MouseMove;
- break;
- case QEvent::TouchEnd:
- eventType = QEvent::MouseButtonRelease;
- break;
- default:
- Q_ASSERT(!true);
- break;
- }
- if (eventType == QEvent::None)
- break;
-
- QMouseEvent mouseEvent(eventType,
- touchPoint.pos().toPoint(),
- touchPoint.screenPos().toPoint(),
- Qt::LeftButton,
- Qt::LeftButton,
- touchEvent->modifiers());
- (void) QApplication::sendEvent(this, &mouseEvent);
-#endif // Q_WS_MAC
- break;
- }
-#ifndef QT_NO_GESTURES
- case QEvent::Gesture:
- event->ignore();
- break;
-#endif
-#ifndef QT_NO_PROPERTIES
- case QEvent::DynamicPropertyChange: {
- const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
- if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
- uint value = property(propName.constData()).toUInt();
- if (!d->extra)
- d->createExtra();
- const char axis = propName.at(12);
- if (axis == 'X')
- d->extra->customDpiX = value;
- else if (axis == 'Y')
- d->extra->customDpiY = value;
- d->updateFont(d->data.fnt);
- }
- // fall through
- }
-#endif
- default:
- return QObject::event(event);
- }
- return true;
-}
-
-/*!
- This event handler can be reimplemented to handle state changes.
-
- The state being changed in this event can be retrieved through the \a event
- supplied.
-
- Change events include: QEvent::ToolBarChange,
- QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
- QEvent::StyleChange, QEvent::PaletteChange,
- QEvent::WindowTitleChange, QEvent::IconTextChange,
- QEvent::ModifiedChange, QEvent::MouseTrackingChange,
- QEvent::ParentChange, QEvent::WindowStateChange,
- QEvent::LanguageChange, QEvent::LocaleChange,
- QEvent::LayoutDirectionChange.
-
-*/
-void QWidget::changeEvent(QEvent * event)
-{
- switch(event->type()) {
- case QEvent::EnabledChange:
- update();
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
-#endif
- break;
-
- case QEvent::FontChange:
- case QEvent::StyleChange: {
- Q_D(QWidget);
- update();
- updateGeometry();
- if (d->layout)
- d->layout->invalidate();
-#ifdef Q_WS_QWS
- if (isWindow())
- d->data.fstrut_dirty = true;
-#endif
- break;
- }
-
- case QEvent::PaletteChange:
- update();
- break;
-
-#ifdef Q_WS_MAC
- case QEvent::MacSizeChange:
- updateGeometry();
- break;
- case QEvent::ToolTipChange:
- case QEvent::MouseTrackingChange:
- qt_mac_update_mouseTracking(this);
- break;
-#endif
-
- default:
- break;
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive mouse move events for the widget.
-
- If mouse tracking is switched off, mouse move events only occur if
- a mouse button is pressed while the mouse is being moved. If mouse
- tracking is switched on, mouse move events occur even if no mouse
- button is pressed.
-
- QMouseEvent::pos() reports the position of the mouse cursor,
- relative to this widget. For press and release events, the
- position is usually the same as the position of the last mouse
- move event, but it might be different if the user's hand shakes.
- This is a feature of the underlying window system, not Qt.
-
- If you want to show a tooltip immediately, while the mouse is
- moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
- and show them as a tooltip), you must first enable mouse tracking
- as described above. Then, to ensure that the tooltip is updated
- immediately, you must call QToolTip::showText() instead of
- setToolTip() in your implementation of mouseMoveEvent().
-
- \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
- mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
-*/
-
-void QWidget::mouseMoveEvent(QMouseEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive mouse press events for the widget.
-
- If you create new widgets in the mousePressEvent() the
- mouseReleaseEvent() may not end up where you expect, depending on
- the underlying window system (or X11 window manager), the widgets'
- location and maybe more.
-
- The default implementation implements the closing of popup widgets
- when you click outside the window. For other widget types it does
- nothing.
-
- \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
- mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
-*/
-
-void QWidget::mousePressEvent(QMouseEvent *event)
-{
- event->ignore();
- if ((windowType() == Qt::Popup)) {
- event->accept();
- QWidget* w;
- while ((w = QApplication::activePopupWidget()) && w != this){
- w->close();
- if (QApplication::activePopupWidget() == w) // widget does not want to disappear
- w->hide(); // hide at least
- }
- if (!rect().contains(event->pos())){
- close();
- }
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive mouse release events for the widget.
-
- \sa mousePressEvent(), mouseDoubleClickEvent(),
- mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
-*/
-
-void QWidget::mouseReleaseEvent(QMouseEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive mouse double click events for the widget.
-
- The default implementation generates a normal mouse press event.
-
- \note The widget will also receive mouse press and mouse release
- events in addition to the double click event. It is up to the
- developer to ensure that the application interprets these events
- correctly.
-
- \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
- event(), QMouseEvent
-*/
-
-void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
-{
- mousePressEvent(event); // try mouse press event
-}
-
-#ifndef QT_NO_WHEELEVENT
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive wheel events for the widget.
-
- If you reimplement this handler, it is very important that you
- \link QWheelEvent ignore()\endlink the event if you do not handle
- it, so that the widget's parent can interpret it.
-
- The default implementation ignores the event.
-
- \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
- QWheelEvent
-*/
-
-void QWidget::wheelEvent(QWheelEvent *event)
-{
- event->ignore();
-}
-#endif // QT_NO_WHEELEVENT
-
-#ifndef QT_NO_TABLETEVENT
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive tablet events for the widget.
-
- If you reimplement this handler, it is very important that you
- \link QTabletEvent ignore()\endlink the event if you do not handle
- it, so that the widget's parent can interpret it.
-
- The default implementation ignores the event.
-
- \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
- QTabletEvent
-*/
-
-void QWidget::tabletEvent(QTabletEvent *event)
-{
- event->ignore();
-}
-#endif // QT_NO_TABLETEVENT
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive key press events for the widget.
-
- A widget must call setFocusPolicy() to accept focus initially and
- have focus in order to receive a key press event.
-
- If you reimplement this handler, it is very important that you
- call the base class implementation if you do not act upon the key.
-
- The default implementation closes popup widgets if the user
- presses Esc. Otherwise the event is ignored, so that the widget's
- parent can interpret it.
-
- Note that QKeyEvent starts with isAccepted() == true, so you do not
- need to call QKeyEvent::accept() - just do not call the base class
- implementation if you act upon the key.
-
- \sa keyReleaseEvent(), setFocusPolicy(),
- focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
-*/
-
-void QWidget::keyPressEvent(QKeyEvent *event)
-{
- if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
- event->accept();
- close();
- } else {
- event->ignore();
- }
-}
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive key release events for the widget.
-
- A widget must \link setFocusPolicy() accept focus\endlink
- initially and \link hasFocus() have focus\endlink in order to
- receive a key release event.
-
- If you reimplement this handler, it is very important that you
- call the base class implementation if you do not act upon the key.
-
- The default implementation ignores the event, so that the widget's
- parent can interpret it.
-
- Note that QKeyEvent starts with isAccepted() == true, so you do not
- need to call QKeyEvent::accept() - just do not call the base class
- implementation if you act upon the key.
-
- \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
- focusInEvent(), focusOutEvent(), event(), QKeyEvent
-*/
-
-void QWidget::keyReleaseEvent(QKeyEvent *event)
-{
- event->ignore();
-}
-
-/*!
- \fn void QWidget::focusInEvent(QFocusEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- keyboard focus events (focus received) for the widget. The event
- is passed in the \a event parameter
-
- A widget normally must setFocusPolicy() to something other than
- Qt::NoFocus in order to receive focus events. (Note that the
- application programmer can call setFocus() on any widget, even
- those that do not normally accept focus.)
-
- The default implementation updates the widget (except for windows
- that do not specify a focusPolicy()).
-
- \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
- keyReleaseEvent(), event(), QFocusEvent
-*/
-
-void QWidget::focusInEvent(QFocusEvent *)
-{
- if (focusPolicy() != Qt::NoFocus || !isWindow()) {
- update();
- }
-}
-
-/*!
- \fn void QWidget::focusOutEvent(QFocusEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- keyboard focus events (focus lost) for the widget. The events is
- passed in the \a event parameter.
-
- A widget normally must setFocusPolicy() to something other than
- Qt::NoFocus in order to receive focus events. (Note that the
- application programmer can call setFocus() on any widget, even
- those that do not normally accept focus.)
-
- The default implementation updates the widget (except for windows
- that do not specify a focusPolicy()).
-
- \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
- keyReleaseEvent(), event(), QFocusEvent
-*/
-
-void QWidget::focusOutEvent(QFocusEvent *)
-{
- if (focusPolicy() != Qt::NoFocus || !isWindow())
- update();
-}
-
-/*!
- \fn void QWidget::enterEvent(QEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- widget enter events which are passed in the \a event parameter.
-
- An event is sent to the widget when the mouse cursor enters the
- widget.
-
- \sa leaveEvent(), mouseMoveEvent(), event()
-*/
-
-void QWidget::enterEvent(QEvent *)
-{
-}
-
-/*!
- \fn void QWidget::leaveEvent(QEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- widget leave events which are passed in the \a event parameter.
-
- A leave event is sent to the widget when the mouse cursor leaves
- the widget.
-
- \sa enterEvent(), mouseMoveEvent(), event()
-*/
-
-void QWidget::leaveEvent(QEvent *)
-{
-}
-
-/*!
- \fn void QWidget::paintEvent(QPaintEvent *event)
-
- This event handler can be reimplemented in a subclass to receive paint
- events passed in \a event.
-
- A paint event is a request to repaint all or part of a widget. It can
- happen for one of the following reasons:
-
- \list
- \o repaint() or update() was invoked,
- \o the widget was obscured and has now been uncovered, or
- \o many other reasons.
- \endlist
-
- Many widgets can simply repaint their entire surface when asked to, but
- some slow widgets need to optimize by painting only the requested region:
- QPaintEvent::region(). This speed optimization does not change the result,
- as painting is clipped to that region during event processing. QListView
- and QTableView do this, for example.
-
- Qt also tries to speed up painting by merging multiple paint events into
- one. When update() is called several times or the window system sends
- several paint events, Qt merges these events into one event with a larger
- region (see QRegion::united()). The repaint() function does not permit this
- optimization, so we suggest using update() whenever possible.
-
- When the paint event occurs, the update region has normally been erased, so
- you are painting on the widget's background.
-
- The background can be set using setBackgroundRole() and setPalette().
-
- Since Qt 4.0, QWidget automatically double-buffers its painting, so there
- is no need to write double-buffering code in paintEvent() to avoid flicker.
-
- \bold{Note for the X11 platform}: It is possible to toggle global double
- buffering by calling \c qt_x11_set_global_double_buffer(). For example,
-
- \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
-
- \note Generally, you should refrain from calling update() or repaint()
- \bold{inside} a paintEvent(). For example, calling update() or repaint() on
- children inside a paintevent() results in undefined behavior; the child may
- or may not get a paint event.
-
- \warning If you are using a custom paint engine without Qt's backingstore,
- Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
- never be called; the backingstore will be used instead.
-
- \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
- {Analog Clock Example}
-*/
-
-void QWidget::paintEvent(QPaintEvent *)
-{
-}
-
-
-/*!
- \fn void QWidget::moveEvent(QMoveEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- widget move events which are passed in the \a event parameter.
- When the widget receives this event, it is already at the new
- position.
-
- The old position is accessible through QMoveEvent::oldPos().
-
- \sa resizeEvent(), event(), move(), QMoveEvent
-*/
-
-void QWidget::moveEvent(QMoveEvent *)
-{
-}
-
-
-/*!
- This event handler can be reimplemented in a subclass to receive
- widget resize events which are passed in the \a event parameter.
- When resizeEvent() is called, the widget already has its new
- geometry. The old size is accessible through
- QResizeEvent::oldSize().
-
- The widget will be erased and receive a paint event immediately
- after processing the resize event. No drawing need be (or should
- be) done inside this handler.
-
-
- \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
- {Scribble Example}
-*/
-
-void QWidget::resizeEvent(QResizeEvent * /* event */)
-{
-}
-
-#ifndef QT_NO_ACTION
-/*!
- \fn void QWidget::actionEvent(QActionEvent *event)
-
- This event handler is called with the given \a event whenever the
- widget's actions are changed.
-
- \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
-*/
-void QWidget::actionEvent(QActionEvent *)
-{
-
-}
-#endif
-
-/*!
- This event handler is called with the given \a event when Qt receives a window
- close request for a top-level widget from the window system.
-
- By default, the event is accepted and the widget is closed. You can reimplement
- this function to change the way the widget responds to window close requests.
- For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
- on all events.
-
- Main window applications typically use reimplementations of this function to check
- whether the user's work has been saved and ask for permission before closing.
- For example, the \l{Application Example} uses a helper function to determine whether
- or not to close the window:
-
- \snippet mainwindows/application/mainwindow.cpp 3
- \snippet mainwindows/application/mainwindow.cpp 4
-
- \sa event(), hide(), close(), QCloseEvent, {Application Example}
-*/
-
-void QWidget::closeEvent(QCloseEvent *event)
-{
- event->accept();
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive widget context menu events.
-
- The handler is called when the widget's \l contextMenuPolicy is
- Qt::DefaultContextMenu.
-
- The default implementation ignores the context event.
- See the \l QContextMenuEvent documentation for more details.
-
- \sa event(), QContextMenuEvent customContextMenuRequested()
-*/
-
-void QWidget::contextMenuEvent(QContextMenuEvent *event)
-{
- event->ignore();
-}
-#endif // QT_NO_CONTEXTMENU
-
-
-/*!
- This event handler, for event \a event, can be reimplemented in a
- subclass to receive Input Method composition events. This handler
- is called when the state of the input method changes.
-
- Note that when creating custom text editing widgets, the
- Qt::WA_InputMethodEnabled window attribute must be set explicitly
- (using the setAttribute() function) in order to receive input
- method events.
-
- The default implementation calls event->ignore(), which rejects the
- Input Method event. See the \l QInputMethodEvent documentation for more
- details.
-
- \sa event(), QInputMethodEvent
-*/
-void QWidget::inputMethodEvent(QInputMethodEvent *event)
-{
- event->ignore();
-}
-
-/*!
- This method is only relevant for input widgets. It is used by the
- input method to query a set of properties of the widget to be
- able to support complex input method operations as support for
- surrounding text and reconversions.
-
- \a query specifies which property is queried.
-
- \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints
-*/
-QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- switch(query) {
- case Qt::ImMicroFocus:
- return QRect(width()/2, 0, 1, height());
- case Qt::ImFont:
- return font();
- case Qt::ImAnchorPosition:
- // Fallback.
- return inputMethodQuery(Qt::ImCursorPosition);
- default:
- return QVariant();
- }
-}
-
-/*!
- \property QWidget::inputMethodHints
- \brief What input method specific hints the widget has.
-
- This is only relevant for input widgets. It is used by
- the input method to retrieve hints as to how the input method
- should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
- is set, the input method may change its visual components to reflect
- that only numbers can be entered.
-
- \note The flags are only hints, so the particular input method
- implementation is free to ignore them. If you want to be
- sure that a certain type of characters are entered,
- you should also set a QValidator on the widget.
-
- The default value is Qt::ImhNone.
-
- \since 4.6
-
- \sa inputMethodQuery(), QInputContext
-*/
-Qt::InputMethodHints QWidget::inputMethodHints() const
-{
-#ifndef QT_NO_IM
- const QWidgetPrivate *priv = d_func();
- while (priv->inheritsInputMethodHints) {
- priv = priv->q_func()->parentWidget()->d_func();
- Q_ASSERT(priv);
- }
- return priv->imHints;
-#else //QT_NO_IM
- return 0;
-#endif //QT_NO_IM
-}
-
-void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
-{
-#ifndef QT_NO_IM
- Q_D(QWidget);
- d->imHints = hints;
- // Optimization to update input context only it has already been created.
- if (d->ic || qApp->d_func()->inputContext) {
- QInputContext *ic = inputContext();
- if (ic)
- ic->update();
- }
-#endif //QT_NO_IM
-}
-
-
-#ifndef QT_NO_DRAGANDDROP
-
-/*!
- \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
-
- This event handler is called when a drag is in progress and the
- mouse enters this widget. The event is passed in the \a event parameter.
-
- If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
- move events}.
-
- See the \link dnd.html Drag-and-drop documentation\endlink for an
- overview of how to provide drag-and-drop in your application.
-
- \sa QDrag, QDragEnterEvent
-*/
-void QWidget::dragEnterEvent(QDragEnterEvent *)
-{
-}
-
-/*!
- \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
-
- This event handler is called if a drag is in progress, and when
- any of the following conditions occur: the cursor enters this widget,
- the cursor moves within this widget, or a modifier key is pressed on
- the keyboard while this widget has the focus. The event is passed
- in the \a event parameter.
-
- See the \link dnd.html Drag-and-drop documentation\endlink for an
- overview of how to provide drag-and-drop in your application.
-
- \sa QDrag, QDragMoveEvent
-*/
-void QWidget::dragMoveEvent(QDragMoveEvent *)
-{
-}
-
-/*!
- \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
-
- This event handler is called when a drag is in progress and the
- mouse leaves this widget. The event is passed in the \a event
- parameter.
-
- See the \link dnd.html Drag-and-drop documentation\endlink for an
- overview of how to provide drag-and-drop in your application.
-
- \sa QDrag, QDragLeaveEvent
-*/
-void QWidget::dragLeaveEvent(QDragLeaveEvent *)
-{
-}
-
-/*!
- \fn void QWidget::dropEvent(QDropEvent *event)
-
- This event handler is called when the drag is dropped on this
- widget. The event is passed in the \a event parameter.
-
- See the \link dnd.html Drag-and-drop documentation\endlink for an
- overview of how to provide drag-and-drop in your application.
-
- \sa QDrag, QDropEvent
-*/
-void QWidget::dropEvent(QDropEvent *)
-{
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*!
- \fn void QWidget::showEvent(QShowEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- widget show events which are passed in the \a event parameter.
-
- Non-spontaneous show events are sent to widgets immediately
- before they are shown. The spontaneous show events of windows are
- delivered afterwards.
-
- Note: A widget receives spontaneous show and hide events when its
- mapping status is changed by the window system, e.g. a spontaneous
- hide event when the user minimizes the window, and a spontaneous
- show event when the window is restored again. After receiving a
- spontaneous hide event, a widget is still considered visible in
- the sense of isVisible().
-
- \sa visible, event(), QShowEvent
-*/
-void QWidget::showEvent(QShowEvent *)
-{
-}
-
-/*!
- \fn void QWidget::hideEvent(QHideEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- widget hide events. The event is passed in the \a event parameter.
-
- Hide events are sent to widgets immediately after they have been
- hidden.
-
- Note: A widget receives spontaneous show and hide events when its
- mapping status is changed by the window system, e.g. a spontaneous
- hide event when the user minimizes the window, and a spontaneous
- show event when the window is restored again. After receiving a
- spontaneous hide event, a widget is still considered visible in
- the sense of isVisible().
-
- \sa visible, event(), QHideEvent
-*/
-void QWidget::hideEvent(QHideEvent *)
-{
-}
-
-/*
- \fn QWidget::x11Event(MSG *)
-
- This special event handler can be reimplemented in a subclass to receive
- native X11 events.
-
- In your reimplementation of this function, if you want to stop Qt from
- handling the event, return true. If you return false, this native event
- is passed back to Qt, which translates it into a Qt event and sends it to
- the widget.
-
- \note Events are only delivered to this event handler if the widget is
- native.
-
- \warning This function is not portable.
-
- \sa QApplication::x11EventFilter(), QWidget::winId()
-*/
-
-
-#if defined(Q_WS_MAC)
-
-/*!
- \fn bool QWidget::macEvent(EventHandlerCallRef caller, EventRef event)
-
- This special event handler can be reimplemented in a subclass to
- receive native Macintosh events.
-
- The parameters are a bit different depending if Qt is build against Carbon
- or Cocoa. In Carbon, \a caller and \a event are the corresponding
- EventHandlerCallRef and EventRef that correspond to the Carbon event
- handlers that are installed. In Cocoa, \a caller is always 0 and the
- EventRef is the EventRef generated from the NSEvent.
-
- In your reimplementation of this function, if you want to stop the
- event being handled by Qt, return true. If you return false, this
- native event is passed back to Qt, which translates the event into
- a Qt event and sends it to the widget.
-
- \warning This function is not portable.
-
- \warning This function was not called inside of Qt until Qt 4.4.
- If you need compatibility with earlier versions of Qt, consider QApplication::macEventFilter() instead.
-
- \sa QApplication::macEventFilter()
-*/
-
-bool QWidget::macEvent(EventHandlerCallRef, EventRef)
-{
- return false;
-}
-
-#endif
-#if defined(Q_WS_WIN)
-
-/*!
- This special event handler can be reimplemented in a subclass to
- receive native Windows events which are passed in the \a message
- parameter.
-
- In your reimplementation of this function, if you want to stop the
- event being handled by Qt, return true and set \a result to the value
- that the window procedure should return. If you return false, this
- native event is passed back to Qt, which translates the event into
- a Qt event and sends it to the widget.
-
- \warning This function is not portable.
-
- \sa QApplication::winEventFilter()
-*/
-bool QWidget::winEvent(MSG *message, long *result)
-{
- Q_UNUSED(message);
- Q_UNUSED(result);
- return false;
-}
-
-#endif
-#if defined(Q_WS_X11)
-
-/*!
- \fn bool QWidget::x11Event(XEvent *event)
-
- This special event handler can be reimplemented in a subclass to receive
- native X11 events passed in the \a event parameter.
-
- In your reimplementation of this function, if you want to stop Qt from
- handling the event, return true. If you return false, this native event
- is passed back to Qt, which translates it into a Qt event and sends it to
- the widget.
-
- \note Events are only delivered to this event handler if the widget is
- native.
-
- \warning This function is not portable.
-
- \sa QApplication::x11EventFilter(), QWidget::winId()
-*/
-bool QWidget::x11Event(XEvent *)
-{
- return false;
-}
-
-#endif
-#if defined(Q_WS_QWS)
-
-/*!
- \fn bool QWidget::qwsEvent(QWSEvent *event)
-
- This special event handler can be reimplemented in a subclass to
- receive native Qt for Embedded Linux events which are passed in the
- \a event parameter.
-
- In your reimplementation of this function, if you want to stop the
- event being handled by Qt, return true. If you return false, this
- native event is passed back to Qt, which translates the event into
- a Qt event and sends it to the widget.
-
- \warning This function is not portable.
-
- \sa QApplication::qwsEventFilter()
-*/
-bool QWidget::qwsEvent(QWSEvent *)
-{
- return false;
-}
-
-#endif
-
-
-/*!
- Ensures that the widget has been polished by QStyle (i.e., has a
- proper font and palette).
-
- QWidget calls this function after it has been fully constructed
- but before it is shown the very first time. You can call this
- function if you want to ensure that the widget is polished before
- doing an operation, e.g., the correct font size might be needed in
- the widget's sizeHint() reimplementation. Note that this function
- \e is called from the default implementation of sizeHint().
-
- Polishing is useful for final initialization that must happen after
- all constructors (from base classes as well as from subclasses)
- have been called.
-
- If you need to change some settings when a widget is polished,
- reimplement event() and handle the QEvent::Polish event type.
-
- \bold{Note:} The function is declared const so that it can be called from
- other const functions (e.g., sizeHint()).
-
- \sa event()
-*/
-void QWidget::ensurePolished() const
-{
- Q_D(const QWidget);
-
- const QMetaObject *m = metaObject();
- if (m == d->polished)
- return;
- d->polished = m;
-
- QEvent e(QEvent::Polish);
- QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
-
- // polish children after 'this'
- QList<QObject*> children = d->children;
- for (int i = 0; i < children.size(); ++i) {
- QObject *o = children.at(i);
- if(!o->isWidgetType())
- continue;
- if (QWidget *w = qobject_cast<QWidget *>(o))
- w->ensurePolished();
- }
-
- if (d->parent && d->sendChildEvents) {
- QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
- QCoreApplication::sendEvent(d->parent, &e);
- }
-}
-
-/*!
- Returns the mask currently set on a widget. If no mask is set the
- return value will be an empty region.
-
- \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
-*/
-QRegion QWidget::mask() const
-{
- Q_D(const QWidget);
- return d->extra ? d->extra->mask : QRegion();
-}
-
-/*!
- Returns the layout manager that is installed on this widget, or 0
- if no layout manager is installed.
-
- The layout manager sets the geometry of the widget's children
- that have been added to the layout.
-
- \sa setLayout(), sizePolicy(), {Layout Management}
-*/
-QLayout *QWidget::layout() const
-{
- return d_func()->layout;
-}
-
-
-/*!
- \fn void QWidget::setLayout(QLayout *layout)
-
- Sets the layout manager for this widget to \a layout.
-
- If there already is a layout manager installed on this widget,
- QWidget won't let you install another. You must first delete the
- existing layout manager (returned by layout()) before you can
- call setLayout() with the new layout.
-
- If \a layout is the layout manger on a different widget, setLayout()
- will reparent the layout and make it the layout manager for this widget.
-
- Example:
-
- \snippet examples/uitools/textfinder/textfinder.cpp 3b
-
- An alternative to calling this function is to pass this widget to
- the layout's constructor.
-
- The QWidget will take ownership of \a layout.
-
- \sa layout(), {Layout Management}
-*/
-
-void QWidget::setLayout(QLayout *l)
-{
- if (!l) {
- qWarning("QWidget::setLayout: Cannot set layout to 0");
- return;
- }
- if (layout()) {
- if (layout() != l)
- qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
- " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
- objectName().toLocal8Bit().data());
- return;
- }
-
- QObject *oldParent = l->parent();
- if (oldParent && oldParent != this) {
- if (oldParent->isWidgetType()) {
- // Steal the layout off a widget parent. Takes effect when
- // morphing laid-out container widgets in Designer.
- QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
- oldParentWidget->takeLayout();
- } else {
- qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
- l->objectName().toLocal8Bit().data(), metaObject()->className(),
- objectName().toLocal8Bit().data());
- return;
- }
- }
-
- Q_D(QWidget);
- l->d_func()->topLevel = true;
- d->layout = l;
- if (oldParent != this) {
- l->setParent(this);
- l->d_func()->reparentChildWidgets(this);
- l->invalidate();
- }
-
- if (isWindow() && d->maybeTopData())
- d->topData()->sizeAdjusted = false;
-}
-
-/*!
- \fn QLayout *QWidget::takeLayout()
-
- Remove the layout from the widget.
- \since 4.5
-*/
-
-QLayout *QWidget::takeLayout()
-{
- Q_D(QWidget);
- QLayout *l = layout();
- if (!l)
- return 0;
- d->layout = 0;
- l->setParent(0);
- return l;
-}
-
-/*!
- \property QWidget::sizePolicy
- \brief the default layout behavior of the widget
-
- If there is a QLayout that manages this widget's children, the
- size policy specified by that layout is used. If there is no such
- QLayout, the result of this function is used.
-
- The default policy is Preferred/Preferred, which means that the
- widget can be freely resized, but prefers to be the size
- sizeHint() returns. Button-like widgets set the size policy to
- specify that they may stretch horizontally, but are fixed
- vertically. The same applies to lineedit controls (such as
- QLineEdit, QSpinBox or an editable QComboBox) and other
- horizontally orientated widgets (such as QProgressBar).
- QToolButton's are normally square, so they allow growth in both
- directions. Widgets that support different directions (such as
- QSlider, QScrollBar or QHeader) specify stretching in the
- respective direction only. Widgets that can provide scroll bars
- (usually subclasses of QScrollArea) tend to specify that they can
- use additional space, and that they can make do with less than
- sizeHint().
-
- \sa sizeHint() QLayout QSizePolicy updateGeometry()
-*/
-QSizePolicy QWidget::sizePolicy() const
-{
- Q_D(const QWidget);
- return d->size_policy;
-}
-
-void QWidget::setSizePolicy(QSizePolicy policy)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_WState_OwnSizePolicy);
- if (policy == d->size_policy)
- return;
- d->size_policy = policy;
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (QWExtra *extra = d->extra) {
- if (extra->proxyWidget)
- extra->proxyWidget->setSizePolicy(policy);
- }
-#endif
-
- updateGeometry();
-
- if (isWindow() && d->maybeTopData())
- d->topData()->sizeAdjusted = false;
-}
-
-/*!
- \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
- \overload
-
- Sets the size policy of the widget to \a horizontal and \a
- vertical, with standard stretch and no height-for-width.
-
- \sa QSizePolicy::QSizePolicy()
-*/
-
-/*!
- Returns the preferred height for this widget, given the width \a w.
-
- If this widget has a layout, the default implementation returns
- the layout's preferred height. if there is no layout, the default
- implementation returns -1 indicating that the preferred height
- does not depend on the width.
-*/
-
-int QWidget::heightForWidth(int w) const
-{
- if (layout() && layout()->hasHeightForWidth())
- return layout()->totalHeightForWidth(w);
- return -1;
-}
-
-
-/*!
- \internal
-
- *virtual private*
-
- This is a bit hackish, but ideally we would have created a virtual function
- in the public API (however, too late...) so that subclasses could reimplement
- their own function.
- Instead we add a virtual function to QWidgetPrivate.
- ### Qt5: move to public class and make virtual
-*/
-bool QWidgetPrivate::hasHeightForWidth() const
-{
- return layout ? layout->hasHeightForWidth() : size_policy.hasHeightForWidth();
-}
-
-/*!
- \fn QWidget *QWidget::childAt(int x, int y) const
-
- Returns the visible child widget at the position (\a{x}, \a{y})
- in the widget's coordinate system. If there is no visible child
- widget at the specified position, the function returns 0.
-*/
-
-/*!
- \overload
-
- Returns the visible child widget at point \a p in the widget's own
- coordinate system.
-*/
-
-QWidget *QWidget::childAt(const QPoint &p) const
-{
- return d_func()->childAt_helper(p, false);
-}
-
-QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
-{
- if (children.isEmpty())
- return 0;
-
-#ifdef Q_WS_MAC
- Q_Q(const QWidget);
- // Unified tool bars on the Mac require special handling since they live outside
- // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
- bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
- && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
- if (includeFrame)
- return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
-#endif
-
- if (!pointInsideRectAndMask(p))
- return 0;
- return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
-}
-
-QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
-{
-#ifndef Q_WS_MAC
- Q_UNUSED(includeFrame);
-#endif
- for (int i = children.size() - 1; i >= 0; --i) {
- QWidget *child = qobject_cast<QWidget *>(children.at(i));
- if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
- || (ignoreChildrenInDestructor && child->data->in_destructor)) {
- continue;
- }
-
- // Map the point 'p' from parent coordinates to child coordinates.
- QPoint childPoint = p;
-#ifdef Q_WS_MAC
- // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
- // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
- // QWidget::mapFromParent won't do the trick.
- if (includeFrame && qobject_cast<QToolBar *>(child))
- childPoint = qt_mac_nativeMapFromParent(child, p);
- else
-#endif
- childPoint -= child->data->crect.topLeft();
-
- // Check if the point hits the child.
- if (!child->d_func()->pointInsideRectAndMask(childPoint))
- continue;
-
- // Do the same for the child's descendants.
- if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
- return w;
-
- // We have found our target; namely the child at position 'p'.
- return child;
- }
- return 0;
-}
-
-void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
-{
- Q_Q(QWidget);
- if (widgetItem)
- widgetItem->invalidateSizeCache();
- QWidget *parent;
- if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
- if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
- if (parent->d_func()->layout)
- parent->d_func()->layout->invalidate();
- else if (parent->isVisible())
- QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
- }
- }
-}
-
-/*!
- Notifies the layout system that this widget has changed and may
- need to change geometry.
-
- Call this function if the sizeHint() or sizePolicy() have changed.
-
- For explicitly hidden widgets, updateGeometry() is a no-op. The
- layout system will be notified as soon as the widget is shown.
-*/
-
-void QWidget::updateGeometry()
-{
- Q_D(QWidget);
- d->updateGeometry_helper(false);
-}
-
-/*! \property QWidget::windowFlags
-
- Window flags are a combination of a type (e.g. Qt::Dialog) and
- zero or more hints to the window system (e.g.
- Qt::FramelessWindowHint).
-
- If the widget had type Qt::Widget or Qt::SubWindow and becomes a
- window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
- 0) on the desktop. If the widget is a window and becomes a
- Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
- relative to its parent widget.
-
- \note This function calls setParent() when changing the flags for
- a window, causing the widget to be hidden. You must call show() to make
- the widget visible again..
-
- \sa windowType(), {Window Flags Example}
-*/
-void QWidget::setWindowFlags(Qt::WindowFlags flags)
-{
- if (data->window_flags == flags)
- return;
-
- Q_D(QWidget);
-
- if ((data->window_flags | flags) & Qt::Window) {
- // the old type was a window and/or the new type is a window
- QPoint oldPos = pos();
- bool visible = isVisible();
- setParent(parentWidget(), flags);
-
- // if both types are windows or neither of them are, we restore
- // the old position
- if (!((data->window_flags ^ flags) & Qt::Window)
- && (visible || testAttribute(Qt::WA_Moved))) {
- move(oldPos);
- }
- // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
- d->adjustQuitOnCloseAttribute();
- } else {
- data->window_flags = flags;
- }
-}
-
-/*!
- Sets the window flags for the widget to \a flags,
- \e without telling the window system.
-
- \warning Do not call this function unless you really know what
- you're doing.
-
- \sa setWindowFlags()
-*/
-void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
-{
- data->window_flags = flags;
-}
-
-/*!
- \fn Qt::WindowType QWidget::windowType() const
-
- Returns the window type of this widget. This is identical to
- windowFlags() & Qt::WindowType_Mask.
-
- \sa windowFlags
-*/
-
-/*!
- Sets the parent of the widget to \a parent, and resets the window
- flags. The widget is moved to position (0, 0) in its new parent.
-
- If the new parent widget is in a different window, the
- reparented widget and its children are appended to the end of the
- \l{setFocusPolicy()}{tab chain} of the new parent
- widget, in the same internal order as before. If one of the moved
- widgets had keyboard focus, setParent() calls clearFocus() for that
- widget.
-
- If the new parent widget is in the same window as the
- old parent, setting the parent doesn't change the tab order or
- keyboard focus.
-
- If the "new" parent widget is the old parent widget, this function
- does nothing.
-
- \note The widget becomes invisible as part of changing its parent,
- even if it was previously visible. You must call show() to make the
- widget visible again.
-
- \warning It is very unlikely that you will ever need this
- function. If you have a widget that changes its content
- dynamically, it is far easier to use \l QStackedWidget.
-
- \sa setWindowFlags()
-*/
-void QWidget::setParent(QWidget *parent)
-{
- if (parent == parentWidget())
- return;
- setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
-}
-
-/*!
- \overload
-
- This function also takes widget flags, \a f as an argument.
-*/
-
-void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
-{
- Q_D(QWidget);
- bool resized = testAttribute(Qt::WA_Resized);
- bool wasCreated = testAttribute(Qt::WA_WState_Created);
- QWidget *oldtlw = window();
-
- QWidget *desktopWidget = 0;
- if (parent && parent->windowType() == Qt::Desktop)
- desktopWidget = parent;
- bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
-
-#if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
- if (newParent && parent && !desktopWidget) {
- if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
-#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
- // On Mac, toolbars inside the unified title bar will never overlap with
- // siblings in the content view. So we skip enforce native siblings in that case
- && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
-#endif // Q_WS_MAC && QT_MAC_USE_COCOA
- )
- parent->d_func()->enforceNativeChildren();
- else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
- setAttribute(Qt::WA_NativeWindow);
- }
-#endif
-
- if (wasCreated) {
- if (!testAttribute(Qt::WA_WState_Hidden)) {
- hide();
- setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- }
- if (newParent) {
- QEvent e(QEvent::ParentAboutToChange);
- QApplication::sendEvent(this, &e);
- }
- }
- if (newParent && isAncestorOf(focusWidget()))
- focusWidget()->clearFocus();
-
- QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
- QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStore : 0;
-
- d->setParent_sys(parent, f);
-
- QTLWExtra *topExtra = window()->d_func()->maybeTopData();
- QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStore : 0;
- if (oldBsTracker && oldBsTracker != bsTracker)
- oldBsTracker->unregisterWidgetSubtree(this);
-
- if (desktopWidget)
- parent = 0;
-
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- QTLWExtra *extra = d->maybeTopData();
- QWindowSurface *windowSurface = (extra ? extra->windowSurface : 0);
- if (newParent && windowSurface) {
- QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore();
- if (oldBs)
- oldBs->subSurfaces.removeAll(windowSurface);
-
- if (parent) {
- QWidgetBackingStore *newBs = parent->d_func()->maybeBackingStore();
- if (newBs)
- newBs->subSurfaces.append(windowSurface);
- }
- }
-#endif
-
- if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
- if (newParent)
- oldBs->removeDirtyWidget(this);
- // Move the widget and all its static children from
- // the old backing store to the new one.
- oldBs->moveStaticWidgets(this);
- }
-
- if ((QApplicationPrivate::app_compile_version < 0x040200
- || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
- && !testAttribute(Qt::WA_WState_Created))
- create();
-
- d->reparentFocusWidgets(oldtlw);
- setAttribute(Qt::WA_Resized, resized);
- if (!testAttribute(Qt::WA_StyleSheet)
- && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
- d->resolveFont();
- d->resolvePalette();
- }
- d->resolveLayoutDirection();
- d->resolveLocale();
-
- // Note: GL widgets under WGL or EGL will always need a ParentChange
- // event to handle recreation/rebinding of the GL context, hence the
- // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
- // platforms).
- if (newParent
-#if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
- || (f & Qt::MSWindowsOwnDC)
-#endif
- ) {
- // propagate enabled updates enabled state to non-windows
- if (!isWindow()) {
- if (!testAttribute(Qt::WA_ForceDisabled))
- d->setEnabled_helper(parent ? parent->isEnabled() : true);
- if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
- d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
- }
- d->inheritStyle();
-
- // send and post remaining QObject events
- if (parent && d->sendChildEvents) {
- QChildEvent e(QEvent::ChildAdded, this);
- QApplication::sendEvent(parent, &e);
-#ifdef QT3_SUPPORT
- if (parent->d_func()->pendingChildInsertedEvents.isEmpty()) {
- QApplication::postEvent(parent,
- new QEvent(QEvent::ChildInsertedRequest),
- Qt::HighEventPriority);
- }
- parent->d_func()->pendingChildInsertedEvents.append(this);
-#endif
- }
-
-//### already hidden above ---> must probably do something smart on the mac
-// #ifdef Q_WS_MAC
-// extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
-// if(!qt_mac_is_macdrawer(q)) //special case
-// q->setAttribute(Qt::WA_WState_Hidden);
-// #else
-// q->setAttribute(Qt::WA_WState_Hidden);
-//#endif
-
- if (parent && d->sendChildEvents && d->polished) {
- QChildEvent e(QEvent::ChildPolished, this);
- QCoreApplication::sendEvent(parent, &e);
- }
-
- QEvent e(QEvent::ParentChange);
- QApplication::sendEvent(this, &e);
- }
-
- if (!wasCreated) {
- if (isWindow() || parentWidget()->isVisible())
- setAttribute(Qt::WA_WState_Hidden, true);
- else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
- setAttribute(Qt::WA_WState_Hidden, false);
- }
-
- d->updateIsOpaque();
-
-#ifndef QT_NO_GRAPHICSVIEW
- // Embed the widget into a proxy if the parent is embedded.
- // ### Doesn't handle reparenting out of an embedded widget.
- if (oldtlw->graphicsProxyWidget()) {
- if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
- ancestorProxy->d_func()->unembedSubWindow(this);
- }
- if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
- if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
- ancestorProxy->d_func()->embedSubWindow(this);
- }
-#endif
-}
-
-/*!
- Scrolls the widget including its children \a dx pixels to the
- right and \a dy downward. Both \a dx and \a dy may be negative.
-
- After scrolling, the widgets will receive paint events for
- the areas that need to be repainted. For widgets that Qt knows to
- be opaque, this is only the newly exposed parts.
- For example, if an opaque widget is scrolled 8 pixels to the left,
- only an 8-pixel wide stripe at the right edge needs updating.
-
- Since widgets propagate the contents of their parents by default,
- you need to set the \l autoFillBackground property, or use
- setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
- a widget opaque.
-
- For widgets that use contents propagation, a scroll will cause an
- update of the entire scroll area.
-
- \sa {Transparency and Double Buffering}
-*/
-
-void QWidget::scroll(int dx, int dy)
-{
- if ((!updatesEnabled() && children().size() == 0) || !isVisible())
- return;
- if (dx == 0 && dy == 0)
- return;
- Q_D(QWidget);
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
- // Graphics View maintains its own dirty region as a list of rects;
- // until we can connect item updates directly to the view, we must
- // separately add a translated dirty region.
- if (!d->dirty.isEmpty()) {
- foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
- proxy->update(rect);
- }
- proxy->scroll(dx, dy, proxy->subWidgetRect(this));
- return;
- }
-#endif
- d->setDirtyOpaqueRegion();
- d->scroll_sys(dx, dy);
-}
-
-/*!
- \overload
-
- This version only scrolls \a r and does not move the children of
- the widget.
-
- If \a r is empty or invalid, the result is undefined.
-
- \sa QScrollArea
-*/
-void QWidget::scroll(int dx, int dy, const QRect &r)
-{
-
- if ((!updatesEnabled() && children().size() == 0) || !isVisible())
- return;
- if (dx == 0 && dy == 0)
- return;
- Q_D(QWidget);
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
- // Graphics View maintains its own dirty region as a list of rects;
- // until we can connect item updates directly to the view, we must
- // separately add a translated dirty region.
- if (!d->dirty.isEmpty()) {
- foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
- proxy->update(rect);
- }
- proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
- return;
- }
-#endif
- d->scroll_sys(dx, dy, r);
-}
-
-/*!
- Repaints the widget directly by calling paintEvent() immediately,
- unless updates are disabled or the widget is hidden.
-
- We suggest only using repaint() if you need an immediate repaint,
- for example during animation. In almost all circumstances update()
- is better, as it permits Qt to optimize for speed and minimize
- flicker.
-
- \warning If you call repaint() in a function which may itself be
- called from paintEvent(), you may get infinite recursion. The
- update() function never causes recursion.
-
- \sa update(), paintEvent(), setUpdatesEnabled()
-*/
-
-void QWidget::repaint()
-{
- repaint(rect());
-}
-
-/*! \overload
-
- This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
- the widget.
-
- If \a w is negative, it is replaced with \c{width() - x}, and if
- \a h is negative, it is replaced width \c{height() - y}.
-*/
-void QWidget::repaint(int x, int y, int w, int h)
-{
- if (x > data->crect.width() || y > data->crect.height())
- return;
-
- if (w < 0)
- w = data->crect.width() - x;
- if (h < 0)
- h = data->crect.height() - y;
-
- repaint(QRect(x, y, w, h));
-}
-
-/*! \overload
-
- This version repaints a rectangle \a rect inside the widget.
-*/
-void QWidget::repaint(const QRect &rect)
-{
- Q_D(QWidget);
-
- if (testAttribute(Qt::WA_WState_ConfigPending)) {
- update(rect);
- return;
- }
-
- if (!isVisible() || !updatesEnabled() || rect.isEmpty())
- return;
-
- if (hasBackingStoreSupport()) {
-#ifdef QT_MAC_USE_COCOA
- if (qt_widget_private(this)->isInUnifiedToolbar) {
- qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
- return;
- }
-#endif // QT_MAC_USE_COCOA
- QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
- tlwExtra->inRepaint = true;
- tlwExtra->backingStore->markDirty(rect, this, true);
- tlwExtra->inRepaint = false;
- }
- } else {
- d->repaint_sys(rect);
- }
-}
-
-/*!
- \overload
-
- This version repaints a region \a rgn inside the widget.
-*/
-void QWidget::repaint(const QRegion &rgn)
-{
- Q_D(QWidget);
-
- if (testAttribute(Qt::WA_WState_ConfigPending)) {
- update(rgn);
- return;
- }
-
- if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
- return;
-
- if (hasBackingStoreSupport()) {
-#ifdef QT_MAC_USE_COCOA
- if (qt_widget_private(this)->isInUnifiedToolbar) {
- qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
- return;
- }
-#endif // QT_MAC_USE_COCOA
- QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
- tlwExtra->inRepaint = true;
- tlwExtra->backingStore->markDirty(rgn, this, true);
- tlwExtra->inRepaint = false;
- }
- } else {
- d->repaint_sys(rgn);
- }
-}
-
-/*!
- Updates the widget unless updates are disabled or the widget is
- hidden.
-
- This function does not cause an immediate repaint; instead it
- schedules a paint event for processing when Qt returns to the main
- event loop. This permits Qt to optimize for more speed and less
- flicker than a call to repaint() does.
-
- Calling update() several times normally results in just one
- paintEvent() call.
-
- Qt normally erases the widget's area before the paintEvent() call.
- If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
- responsible for painting all its pixels with an opaque color.
-
- \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
-*/
-void QWidget::update()
-{
- update(rect());
-}
-
-/*! \fn void QWidget::update(int x, int y, int w, int h)
- \overload
-
- This version updates a rectangle (\a x, \a y, \a w, \a h) inside
- the widget.
-*/
-
-/*!
- \overload
-
- This version updates a rectangle \a rect inside the widget.
-*/
-void QWidget::update(const QRect &rect)
-{
- if (!isVisible() || !updatesEnabled() || rect.isEmpty())
- return;
-
- if (testAttribute(Qt::WA_WState_InPaintEvent)) {
- QApplication::postEvent(this, new QUpdateLaterEvent(rect));
- return;
- }
-
- if (hasBackingStoreSupport()) {
-#ifdef QT_MAC_USE_COCOA
- if (qt_widget_private(this)->isInUnifiedToolbar) {
- qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
- return;
- }
-#endif // QT_MAC_USE_COCOA
- QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
- tlwExtra->backingStore->markDirty(rect, this);
- } else {
- d_func()->repaint_sys(rect);
- }
-}
-
-/*!
- \overload
-
- This version repaints a region \a rgn inside the widget.
-*/
-void QWidget::update(const QRegion &rgn)
-{
- if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
- return;
-
- if (testAttribute(Qt::WA_WState_InPaintEvent)) {
- QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
- return;
- }
-
- if (hasBackingStoreSupport()) {
-#ifdef QT_MAC_USE_COCOA
- if (qt_widget_private(this)->isInUnifiedToolbar) {
- qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
- return;
- }
-#endif // QT_MAC_USE_COCOA
- QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
- if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
- tlwExtra->backingStore->markDirty(rgn, this);
- } else {
- d_func()->repaint_sys(rgn);
- }
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Clear the rectangle at point (\a x, \a y) of width \a w and height
- \a h.
-
- \warning This is best done in a paintEvent().
-*/
-void QWidget::erase_helper(int x, int y, int w, int h)
-{
- if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible))
- return;
- if (w < 0)
- w = data->crect.width() - x;
- if (h < 0)
- h = data->crect.height() - y;
- if (w != 0 && h != 0) {
- QPainter p(this);
- p.eraseRect(QRect(x, y, w, h));
- }
-}
-
-/*!
- \overload
-
- Clear the given region, \a rgn.
-
- Drawing may only take place in a QPaintEvent. Overload
- paintEvent() to do your erasing and call update() to schedule a
- replaint whenever necessary. See also QPainter.
-*/
-void QWidget::erase(const QRegion& rgn)
-{
- if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible))
- return;
-
- QPainter p(this);
- p.setClipRegion(rgn);
- p.eraseRect(rgn.boundingRect());
-}
-
-void QWidget::drawText_helper(int x, int y, const QString &str)
-{
- if(!testAttribute(Qt::WA_WState_Visible))
- return;
- QPainter paint(this);
- paint.drawText(x, y, str);
-}
-
-
-/*!
- Closes the widget.
-
- Use the no-argument overload instead.
-*/
-bool QWidget::close(bool alsoDelete)
-{
- QPointer<QWidget> that = this;
- bool accepted = close();
- if (alsoDelete && accepted && that)
- deleteLater();
- return accepted;
-}
-
-void QWidget::setIcon(const QPixmap &i)
-{
- setWindowIcon(i);
-}
-
-/*!
- Return's the widget's icon.
-
- Use windowIcon() instead.
-*/
-const QPixmap *QWidget::icon() const
-{
- Q_D(const QWidget);
- return (d->extra && d->extra->topextra) ? d->extra->topextra->iconPixmap : 0;
-}
-
-#endif // QT3_SUPPORT
-
- /*!
- \internal
-
- This just sets the corresponding attribute bit to 1 or 0
- */
-static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
- QWidgetPrivate *d)
-{
- if (attribute < int(8*sizeof(uint))) {
- if (on)
- data->widget_attributes |= (1<<attribute);
- else
- data->widget_attributes &= ~(1<<attribute);
- } else {
- const int x = attribute - 8*sizeof(uint);
- const int int_off = x / (8*sizeof(uint));
- if (on)
- d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
- else
- d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
- }
-}
-
-/*!
- Sets the attribute \a attribute on this widget if \a on is true;
- otherwise clears the attribute.
-
- \sa testAttribute()
-*/
-void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
-{
- if (testAttribute(attribute) == on)
- return;
-
- Q_D(QWidget);
- Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
- "QWidget::setAttribute(WidgetAttribute, bool)",
- "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
-#ifdef Q_WS_WIN
- // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
- if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
- // see qwidget_win.cpp, ::paintEngine for details
- paintEngine();
- if (d->noPaintOnScreen)
- return;
- }
-#endif
-
- setAttribute_internal(attribute, on, data, d);
-
- switch (attribute) {
-
-#ifndef QT_NO_DRAGANDDROP
- case Qt::WA_AcceptDrops: {
- if (on && !testAttribute(Qt::WA_DropSiteRegistered))
- setAttribute(Qt::WA_DropSiteRegistered, true);
- else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
- setAttribute(Qt::WA_DropSiteRegistered, false);
- QEvent e(QEvent::AcceptDropsChange);
- QApplication::sendEvent(this, &e);
- break;
- }
- case Qt::WA_DropSiteRegistered: {
- d->registerDropSite(on);
- for (int i = 0; i < d->children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
- if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
- w->setAttribute(Qt::WA_DropSiteRegistered, on);
- }
- break;
- }
-#endif
-
- case Qt::WA_NoChildEventsForParent:
- d->sendChildEvents = !on;
- break;
- case Qt::WA_NoChildEventsFromChildren:
- d->receiveChildEvents = !on;
- break;
- case Qt::WA_MacBrushedMetal:
-#ifdef Q_WS_MAC
- d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
- // fall through since changing the metal attribute affects the opaque size grip.
- case Qt::WA_MacOpaqueSizeGrip:
- d->macUpdateOpaqueSizeGrip();
- break;
- case Qt::WA_MacShowFocusRect:
- if (hasFocus()) {
- clearFocus();
- setFocus();
- }
- break;
- case Qt::WA_Hover:
- qt_mac_update_mouseTracking(this);
- break;
-#endif
- case Qt::WA_MacAlwaysShowToolWindow:
-#ifdef Q_WS_MAC
- d->macUpdateHideOnSuspend();
-#endif
- break;
- case Qt::WA_MacNormalSize:
- case Qt::WA_MacSmallSize:
- case Qt::WA_MacMiniSize:
-#ifdef Q_WS_MAC
- {
- // We can only have one of these set at a time
- const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
- Qt::WA_MacMiniSize };
- for (int i = 0; i < 3; ++i) {
- if (MacSizes[i] != attribute)
- setAttribute_internal(MacSizes[i], false, data, d);
- }
- d->macUpdateSizeAttribute();
- }
-#endif
- break;
- case Qt::WA_ShowModal:
- if (!on) {
- if (isVisible())
- QApplicationPrivate::leaveModal(this);
- // reset modality type to Modeless when clearing WA_ShowModal
- data->window_modality = Qt::NonModal;
- } else if (data->window_modality == Qt::NonModal) {
- // determine the modality type if it hasn't been set prior
- // to setting WA_ShowModal. set the default to WindowModal
- // if we are the child of a group leader; otherwise use
- // ApplicationModal.
- QWidget *w = parentWidget();
- if (w)
- w = w->window();
- while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
- w = w->parentWidget();
- if (w)
- w = w->window();
- }
- data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
- ? Qt::WindowModal
- : Qt::ApplicationModal;
- // Some window managers does not allow us to enter modal after the
- // window is showing. Therefore, to be consistent, we cannot call
- // QApplicationPrivate::enterModal(this) here. The window must be
- // hidden before changing modality.
- }
- if (testAttribute(Qt::WA_WState_Created)) {
- // don't call setModal_sys() before create_sys()
- d->setModal_sys();
- }
- break;
- case Qt::WA_MouseTracking: {
- QEvent e(QEvent::MouseTrackingChange);
- QApplication::sendEvent(this, &e);
- break; }
- case Qt::WA_NativeWindow: {
-#if defined(Q_WS_QPA)
- d->createTLExtra();
-#endif
-#ifndef QT_NO_IM
- QWidget *focusWidget = d->effectiveFocusWidget();
- QInputContext *ic = 0;
- if (on && !internalWinId() && hasFocus()
- && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
- ic = focusWidget->d_func()->inputContext();
- if (ic) {
- ic->reset();
- ic->setFocusWidget(0);
- }
- }
- if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
-#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
- // On Mac, toolbars inside the unified title bar will never overlap with
- // siblings in the content view. So we skip enforce native siblings in that case
- && !d->isInUnifiedToolbar && parentWidget()->isWindow()
-#endif // Q_WS_MAC && QT_MAC_USE_COCOA
- )
- parentWidget()->d_func()->enforceNativeChildren();
- if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
- d->createWinId();
- if (ic && isEnabled() && focusWidget->isEnabled()
- && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
- ic->setFocusWidget(focusWidget);
- }
-#endif //QT_NO_IM
- break;
- }
- case Qt::WA_PaintOnScreen:
- d->updateIsOpaque();
-#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
- // Recreate the widget if it's already created as an alien widget and
- // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
- // So must their children.
- if (on) {
- setAttribute(Qt::WA_NativeWindow);
- d->enforceNativeChildren();
- }
-#endif
- // fall through
- case Qt::WA_OpaquePaintEvent:
- d->updateIsOpaque();
- break;
- case Qt::WA_NoSystemBackground:
- d->updateIsOpaque();
- // fall through...
- case Qt::WA_UpdatesDisabled:
- d->updateSystemBackground();
- break;
- case Qt::WA_TransparentForMouseEvents:
-#ifdef Q_WS_MAC
- d->macUpdateIgnoreMouseEvents();
-#endif
- break;
- case Qt::WA_InputMethodEnabled: {
-#ifndef QT_NO_IM
- QWidget *focusWidget = d->effectiveFocusWidget();
- QInputContext *ic = focusWidget->d_func()->assignedInputContext();
- if (!ic && (!on || hasFocus()))
- ic = focusWidget->d_func()->inputContext();
- if (ic) {
- if (on && hasFocus() && ic->focusWidget() != focusWidget && isEnabled()
- && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
- ic->setFocusWidget(focusWidget);
- } else if (!on && ic->focusWidget() == focusWidget) {
- ic->reset();
- ic->setFocusWidget(0);
- }
- }
-#endif //QT_NO_IM
- break;
- }
- case Qt::WA_WindowPropagation:
- d->resolvePalette();
- d->resolveFont();
- d->resolveLocale();
- break;
-#ifdef Q_WS_X11
- case Qt::WA_NoX11EventCompression:
- if (!d->extra)
- d->createExtra();
- d->extra->compress_events = on;
- break;
- case Qt::WA_X11OpenGLOverlay:
- d->updateIsOpaque();
- break;
- case Qt::WA_X11DoNotAcceptFocus:
- if (testAttribute(Qt::WA_WState_Created))
- d->updateX11AcceptFocus();
- break;
-#endif
- case Qt::WA_DontShowOnScreen: {
- if (on && isVisible()) {
- // Make sure we keep the current state and only hide the widget
- // from the desktop. show_sys will only update platform specific
- // attributes at this point.
- d->hide_sys();
-#ifdef Q_WS_QWS
- // Release the region for this window from qws if the widget has
- // been shown before the attribute was set.
- if (QWSWindowSurface *surface = static_cast<QWSWindowSurface *>(windowSurface())) {
- QWidget::qwsDisplay()->requestRegion(surface->winId(), surface->key(),
- surface->permanentState(), QRegion());
- }
-#endif
- d->show_sys();
- }
- break;
- }
-
-#ifdef Q_WS_X11
- case Qt::WA_X11NetWmWindowTypeDesktop:
- case Qt::WA_X11NetWmWindowTypeDock:
- case Qt::WA_X11NetWmWindowTypeToolBar:
- case Qt::WA_X11NetWmWindowTypeMenu:
- case Qt::WA_X11NetWmWindowTypeUtility:
- case Qt::WA_X11NetWmWindowTypeSplash:
- case Qt::WA_X11NetWmWindowTypeDialog:
- case Qt::WA_X11NetWmWindowTypeDropDownMenu:
- case Qt::WA_X11NetWmWindowTypePopupMenu:
- case Qt::WA_X11NetWmWindowTypeToolTip:
- case Qt::WA_X11NetWmWindowTypeNotification:
- case Qt::WA_X11NetWmWindowTypeCombo:
- case Qt::WA_X11NetWmWindowTypeDND:
- if (testAttribute(Qt::WA_WState_Created))
- d->setNetWmWindowTypes();
- break;
-#endif
-
- case Qt::WA_StaticContents:
- if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
- if (on)
- bs->addStaticWidget(this);
- else
- bs->removeStaticWidget(this);
- }
- break;
- case Qt::WA_TranslucentBackground:
- if (on) {
- setAttribute(Qt::WA_NoSystemBackground);
- d->updateIsTranslucent();
- }
-
- break;
- case Qt::WA_AcceptTouchEvents:
-#if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
- if (on)
- d->registerTouchWindow();
-#endif
- break;
- case Qt::WA_LockPortraitOrientation:
- case Qt::WA_LockLandscapeOrientation:
- case Qt::WA_AutoOrientation: {
- const Qt::WidgetAttribute orientations[3] = {
- Qt::WA_LockPortraitOrientation,
- Qt::WA_LockLandscapeOrientation,
- Qt::WA_AutoOrientation
- };
-
- if (on) {
- // We can only have one of these set at a time
- for (int i = 0; i < 3; ++i) {
- if (orientations[i] != attribute)
- setAttribute_internal(orientations[i], false, data, d);
- }
- }
-
-#ifdef Q_WS_S60
- CAknAppUiBase* appUi = static_cast<CAknAppUiBase*>(CEikonEnv::Static()->EikAppUi());
- const CAknAppUiBase::TAppUiOrientation s60orientations[] = {
- CAknAppUiBase::EAppUiOrientationPortrait,
- CAknAppUiBase::EAppUiOrientationLandscape,
- CAknAppUiBase::EAppUiOrientationAutomatic
- };
- CAknAppUiBase::TAppUiOrientation s60orientation = CAknAppUiBase::EAppUiOrientationUnspecified;
- for (int i = 0; i < 3; ++i) {
- if (testAttribute(orientations[i])) {
- s60orientation = s60orientations[i];
- break;
- }
- }
- QT_TRAP_THROWING(appUi->SetOrientationL(s60orientation));
- S60->orientationSet = true;
- QSymbianControl *window = static_cast<QSymbianControl *>(internalWinId());
- if (window)
- window->ensureFixNativeOrientation();
-#endif
- break;
- }
- default:
- break;
- }
-}
-
-/*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
-
- Returns true if attribute \a attribute is set on this widget;
- otherwise returns false.
-
- \sa setAttribute()
- */
-bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
-{
- Q_D(const QWidget);
- const int x = attribute - 8*sizeof(uint);
- const int int_off = x / (8*sizeof(uint));
- return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
-}
-
-/*!
- \property QWidget::windowOpacity
-
- \brief The level of opacity for the window.
-
- The valid range of opacity is from 1.0 (completely opaque) to
- 0.0 (completely transparent).
-
- By default the value of this property is 1.0.
-
- This feature is available on Embedded Linux, Mac OS X, Windows,
- and X11 platforms that support the Composite extension.
-
- This feature is not available on Windows CE.
-
- Note that under X11 you need to have a composite manager running,
- and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
- supported by the window manager you are using.
-
- \warning Changing this property from opaque to transparent might issue a
- paint event that needs to be processed before the window is displayed
- correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
- that semi-transparent windows update and resize significantly slower than
- opaque windows.
-
- \sa setMask()
-*/
-qreal QWidget::windowOpacity() const
-{
- Q_D(const QWidget);
- return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
-}
-
-void QWidget::setWindowOpacity(qreal opacity)
-{
- Q_D(QWidget);
- if (!isWindow())
- return;
-
- opacity = qBound(qreal(0.0), opacity, qreal(1.0));
- QTLWExtra *extra = d->topData();
- extra->opacity = uint(opacity * 255);
- setAttribute(Qt::WA_WState_WindowOpacitySet);
-
-#ifndef Q_WS_QWS
- if (!testAttribute(Qt::WA_WState_Created))
- return;
-#endif
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
- // Avoid invalidating the cache if set.
- if (proxy->cacheMode() == QGraphicsItem::NoCache)
- proxy->update();
- else if (QGraphicsScene *scene = proxy->scene())
- scene->update(proxy->sceneBoundingRect());
- return;
- }
-#endif
-
- d->setWindowOpacity_sys(opacity);
-}
-
-/*!
- \property QWidget::windowModified
- \brief whether the document shown in the window has unsaved changes
-
- A modified window is a window whose content has changed but has
- not been saved to disk. This flag will have different effects
- varied by the platform. On Mac OS X the close button will have a
- modified look; on other platforms, the window title will have an
- '*' (asterisk).
-
- The window title must contain a "[*]" placeholder, which
- indicates where the '*' should appear. Normally, it should appear
- right after the file name (e.g., "document1.txt[*] - Text
- Editor"). If the window isn't modified, the placeholder is simply
- removed.
-
- Note that if a widget is set as modified, all its ancestors will
- also be set as modified. However, if you call \c
- {setWindowModified(false)} on a widget, this will not propagate to
- its parent because other children of the parent might have been
- modified.
-
- \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
-*/
-bool QWidget::isWindowModified() const
-{
- return testAttribute(Qt::WA_WindowModified);
-}
-
-void QWidget::setWindowModified(bool mod)
-{
- Q_D(QWidget);
- setAttribute(Qt::WA_WindowModified, mod);
-
-#ifndef Q_WS_MAC
- if (!windowTitle().contains(QLatin1String("[*]")) && mod)
- qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
-#endif
- d->setWindowTitle_helper(windowTitle());
- d->setWindowIconText_helper(windowIconText());
-#ifdef Q_WS_MAC
- d->setWindowModified_sys(mod);
-#endif
-
- QEvent e(QEvent::ModifiedChange);
- QApplication::sendEvent(this, &e);
-}
-
-#ifndef QT_NO_TOOLTIP
-/*!
- \property QWidget::toolTip
-
- \brief the widget's tooltip
-
- Note that by default tooltips are only shown for widgets that are
- children of the active window. You can change this behavior by
- setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
- not on the widget with the tooltip.
-
- If you want to control a tooltip's behavior, you can intercept the
- event() function and catch the QEvent::ToolTip event (e.g., if you
- want to customize the area for which the tooltip should be shown).
-
- By default, this property contains an empty string.
-
- \sa QToolTip statusTip whatsThis
-*/
-void QWidget::setToolTip(const QString &s)
-{
- Q_D(QWidget);
- d->toolTip = s;
-
- QEvent event(QEvent::ToolTipChange);
- QApplication::sendEvent(this, &event);
-}
-
-QString QWidget::toolTip() const
-{
- Q_D(const QWidget);
- return d->toolTip;
-}
-#endif // QT_NO_TOOLTIP
-
-
-#ifndef QT_NO_STATUSTIP
-/*!
- \property QWidget::statusTip
- \brief the widget's status tip
-
- By default, this property contains an empty string.
-
- \sa toolTip whatsThis
-*/
-void QWidget::setStatusTip(const QString &s)
-{
- Q_D(QWidget);
- d->statusTip = s;
-}
-
-QString QWidget::statusTip() const
-{
- Q_D(const QWidget);
- return d->statusTip;
-}
-#endif // QT_NO_STATUSTIP
-
-#ifndef QT_NO_WHATSTHIS
-/*!
- \property QWidget::whatsThis
-
- \brief the widget's What's This help text.
-
- By default, this property contains an empty string.
-
- \sa QWhatsThis QWidget::toolTip QWidget::statusTip
-*/
-void QWidget::setWhatsThis(const QString &s)
-{
- Q_D(QWidget);
- d->whatsThis = s;
-}
-
-QString QWidget::whatsThis() const
-{
- Q_D(const QWidget);
- return d->whatsThis;
-}
-#endif // QT_NO_WHATSTHIS
-
-#ifndef QT_NO_ACCESSIBILITY
-/*!
- \property QWidget::accessibleName
-
- \brief the widget's name as seen by assistive technologies
-
- This property is used by accessible clients to identify, find, or announce
- the widget for accessible clients.
-
- By default, this property contains an empty string.
-
- \sa QAccessibleInterface::text()
-*/
-void QWidget::setAccessibleName(const QString &name)
-{
- Q_D(QWidget);
- d->accessibleName = name;
-}
-
-QString QWidget::accessibleName() const
-{
- Q_D(const QWidget);
- return d->accessibleName;
-}
-
-/*!
- \property QWidget::accessibleDescription
-
- \brief the widget's description as seen by assistive technologies
-
- By default, this property contains an empty string.
-
- \sa QAccessibleInterface::text()
-*/
-void QWidget::setAccessibleDescription(const QString &description)
-{
- Q_D(QWidget);
- d->accessibleDescription = description;
-}
-
-QString QWidget::accessibleDescription() const
-{
- Q_D(const QWidget);
- return d->accessibleDescription;
-}
-#endif // QT_NO_ACCESSIBILITY
-
-#ifndef QT_NO_SHORTCUT
-/*!
- Adds a shortcut to Qt's shortcut system that watches for the given
- \a key sequence in the given \a context. If the \a context is
- Qt::ApplicationShortcut, the shortcut applies to the application as a
- whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
- or to the window itself, Qt::WindowShortcut.
-
- If the same \a key sequence has been grabbed by several widgets,
- when the \a key sequence occurs a QEvent::Shortcut event is sent
- to all the widgets to which it applies in a non-deterministic
- order, but with the ``ambiguous'' flag set to true.
-
- \warning You should not normally need to use this function;
- instead create \l{QAction}s with the shortcut key sequences you
- require (if you also want equivalent menu options and toolbar
- buttons), or create \l{QShortcut}s if you just need key sequences.
- Both QAction and QShortcut handle all the event filtering for you,
- and provide signals which are triggered when the user triggers the
- key sequence, so are much easier to use than this low-level
- function.
-
- \sa releaseShortcut() setShortcutEnabled()
-*/
-int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
-{
- Q_ASSERT(qApp);
- if (key.isEmpty())
- return 0;
- setAttribute(Qt::WA_GrabbedShortcut);
- return qApp->d_func()->shortcutMap.addShortcut(this, key, context);
-}
-
-/*!
- Removes the shortcut with the given \a id from Qt's shortcut
- system. The widget will no longer receive QEvent::Shortcut events
- for the shortcut's key sequence (unless it has other shortcuts
- with the same key sequence).
-
- \warning You should not normally need to use this function since
- Qt's shortcut system removes shortcuts automatically when their
- parent widget is destroyed. It is best to use QAction or
- QShortcut to handle shortcuts, since they are easier to use than
- this low-level function. Note also that this is an expensive
- operation.
-
- \sa grabShortcut() setShortcutEnabled()
-*/
-void QWidget::releaseShortcut(int id)
-{
- Q_ASSERT(qApp);
- if (id)
- qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
-}
-
-/*!
- If \a enable is true, the shortcut with the given \a id is
- enabled; otherwise the shortcut is disabled.
-
- \warning You should not normally need to use this function since
- Qt's shortcut system enables/disables shortcuts automatically as
- widgets become hidden/visible and gain or lose focus. It is best
- to use QAction or QShortcut to handle shortcuts, since they are
- easier to use than this low-level function.
-
- \sa grabShortcut() releaseShortcut()
-*/
-void QWidget::setShortcutEnabled(int id, bool enable)
-{
- Q_ASSERT(qApp);
- if (id)
- qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
-}
-
-/*!
- \since 4.2
-
- If \a enable is true, auto repeat of the shortcut with the
- given \a id is enabled; otherwise it is disabled.
-
- \sa grabShortcut() releaseShortcut()
-*/
-void QWidget::setShortcutAutoRepeat(int id, bool enable)
-{
- Q_ASSERT(qApp);
- if (id)
- qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
-}
-#endif // QT_NO_SHORTCUT
-/*!
- Updates the widget's micro focus.
-
- \sa QInputContext
-*/
-void QWidget::updateMicroFocus()
-{
-#if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN))
- Q_D(QWidget);
- // and optimization to update input context only it has already been created.
- if (d->assignedInputContext() || qApp->d_func()->inputContext) {
- QInputContext *ic = inputContext();
- if (ic)
- ic->update();
- }
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- // ##### is this correct
- QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
-#endif
-}
-
-
-#if defined (Q_WS_WIN)
-/*!
- Returns the window system handle of the widget, for low-level
- access. Using this function is not portable.
-
- An HDC acquired with getDC() has to be released with releaseDC().
-
- \warning Using this function is not portable.
-*/
-HDC QWidget::getDC() const
-{
- Q_D(const QWidget);
- if (d->hd)
- return (HDC) d->hd;
- return GetDC(winId());
-}
-
-/*!
- Releases the HDC \a hdc acquired by a previous call to getDC().
-
- \warning Using this function is not portable.
-*/
-void QWidget::releaseDC(HDC hdc) const
-{
- Q_D(const QWidget);
- // If its the widgets own dc, it will be released elsewhere. If
- // its a different HDC we release it and issue a warning if it
- // fails.
- if (hdc != d->hd && !ReleaseDC(winId(), hdc))
- qErrnoWarning("QWidget::releaseDC(): failed to release HDC");
-}
-#else
-/*!
- Returns the window system handle of the widget, for low-level
- access. Using this function is not portable.
-
- The HANDLE type varies with platform; see \c qwindowdefs.h for
- details.
-*/
-Qt::HANDLE QWidget::handle() const
-{
- Q_D(const QWidget);
- if (!internalWinId() && testAttribute(Qt::WA_WState_Created))
- (void)winId(); // enforce native window
- return d->hd;
-}
-#endif
-
-
-/*!
- Raises this widget to the top of the parent widget's stack.
-
- After this call the widget will be visually in front of any
- overlapping sibling widgets.
-
- \note When using activateWindow(), you can call this function to
- ensure that the window is stacked on top.
-
- \sa lower(), stackUnder()
-*/
-
-void QWidget::raise()
-{
- Q_D(QWidget);
- if (!isWindow()) {
- QWidget *p = parentWidget();
- const int parentChildCount = p->d_func()->children.size();
- if (parentChildCount < 2)
- return;
- const int from = p->d_func()->children.indexOf(this);
- Q_ASSERT(from >= 0);
- // Do nothing if the widget is already in correct stacking order _and_ created.
- if (from != parentChildCount -1)
- p->d_func()->children.move(from, parentChildCount - 1);
- if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
- create();
- else if (from == parentChildCount - 1)
- return;
-
- QRegion region(rect());
- d->subtractOpaqueSiblings(region);
- d->invalidateBuffer(region);
- }
- if (testAttribute(Qt::WA_WState_Created))
- d->raise_sys();
-
- QEvent e(QEvent::ZOrderChange);
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- Lowers the widget to the bottom of the parent widget's stack.
-
- After this call the widget will be visually behind (and therefore
- obscured by) any overlapping sibling widgets.
-
- \sa raise(), stackUnder()
-*/
-
-void QWidget::lower()
-{
- Q_D(QWidget);
- if (!isWindow()) {
- QWidget *p = parentWidget();
- const int parentChildCount = p->d_func()->children.size();
- if (parentChildCount < 2)
- return;
- const int from = p->d_func()->children.indexOf(this);
- Q_ASSERT(from >= 0);
- // Do nothing if the widget is already in correct stacking order _and_ created.
- if (from != 0)
- p->d_func()->children.move(from, 0);
- if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
- create();
- else if (from == 0)
- return;
- }
- if (testAttribute(Qt::WA_WState_Created))
- d->lower_sys();
-
- QEvent e(QEvent::ZOrderChange);
- QApplication::sendEvent(this, &e);
-}
-
-
-/*!
- Places the widget under \a w in the parent widget's stack.
-
- To make this work, the widget itself and \a w must be siblings.
-
- \sa raise(), lower()
-*/
-void QWidget::stackUnder(QWidget* w)
-{
- Q_D(QWidget);
- QWidget *p = parentWidget();
- if (!w || isWindow() || p != w->parentWidget() || this == w)
- return;
- if (p) {
- int from = p->d_func()->children.indexOf(this);
- int to = p->d_func()->children.indexOf(w);
- Q_ASSERT(from >= 0);
- Q_ASSERT(to >= 0);
- if (from < to)
- --to;
- // Do nothing if the widget is already in correct stacking order _and_ created.
- if (from != to)
- p->d_func()->children.move(from, to);
- if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
- create();
- else if (from == to)
- return;
- }
- if (testAttribute(Qt::WA_WState_Created))
- d->stackUnder_sys(w);
-
- QEvent e(QEvent::ZOrderChange);
- QApplication::sendEvent(this, &e);
-}
-
-void QWidget::styleChange(QStyle&) { }
-void QWidget::enabledChange(bool) { } // compat
-void QWidget::paletteChange(const QPalette &) { } // compat
-void QWidget::fontChange(const QFont &) { } // compat
-void QWidget::windowActivationChange(bool) { } // compat
-void QWidget::languageChange() { } // compat
-
-
-/*!
- \enum QWidget::BackgroundOrigin
-
- \compat
-
- \value WidgetOrigin
- \value ParentOrigin
- \value WindowOrigin
- \value AncestorOrigin
-
-*/
-
-/*!
- \fn bool QWidget::isVisibleToTLW() const
-
- Use isVisible() instead.
-*/
-
-/*!
- \fn void QWidget::iconify()
-
- Use showMinimized() instead.
-*/
-
-/*!
- \fn void QWidget::constPolish() const
-
- Use ensurePolished() instead.
-*/
-
-/*!
- \fn void QWidget::reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt)
-
- Use setParent() to change the parent or the widget's widget flags;
- use move() to move the widget, and use show() to show the widget.
-*/
-
-/*!
- \fn void QWidget::reparent(QWidget *parent, const QPoint &p, bool showIt)
-
- Use setParent() to change the parent; use move() to move the
- widget, and use show() to show the widget.
-*/
-
-/*!
- \fn void QWidget::recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt)
-
- Use setParent() to change the parent or the widget's widget flags;
- use move() to move the widget, and use show() to show the widget.
-*/
-
-/*!
- \fn bool QWidget::hasMouse() const
-
- Use testAttribute(Qt::WA_UnderMouse) instead.
-*/
-
-/*!
- \fn bool QWidget::ownCursor() const
-
- Use testAttribute(Qt::WA_SetCursor) instead.
-*/
-
-/*!
- \fn bool QWidget::ownFont() const
-
- Use testAttribute(Qt::WA_SetFont) instead.
-*/
-
-/*!
- \fn void QWidget::unsetFont()
-
- Use setFont(QFont()) instead.
-*/
-
-/*!
- \fn bool QWidget::ownPalette() const
-
- Use testAttribute(Qt::WA_SetPalette) instead.
-*/
-
-/*!
- \fn void QWidget::unsetPalette()
-
- Use setPalette(QPalette()) instead.
-*/
-
-/*!
- \fn void QWidget::setEraseColor(const QColor &color)
-
- Use the palette instead.
-
- \oldcode
- widget->setEraseColor(color);
- \newcode
- QPalette palette;
- palette.setColor(widget->backgroundRole(), color);
- widget->setPalette(palette);
- \endcode
-*/
-
-/*!
- \fn void QWidget::setErasePixmap(const QPixmap &pixmap)
-
- Use the palette instead.
-
- \oldcode
- widget->setErasePixmap(pixmap);
- \newcode
- QPalette palette;
- palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
- widget->setPalette(palette);
- \endcode
-*/
-
-/*!
- \fn void QWidget::setPaletteForegroundColor(const QColor &color)
-
- Use the palette directly.
-
- \oldcode
- widget->setPaletteForegroundColor(color);
- \newcode
- QPalette palette;
- palette.setColor(widget->foregroundRole(), color);
- widget->setPalette(palette);
- \endcode
-*/
-
-/*!
- \fn void QWidget::setPaletteBackgroundColor(const QColor &color)
-
- Use the palette directly.
-
- \oldcode
- widget->setPaletteBackgroundColor(color);
- \newcode
- QPalette palette;
- palette.setColor(widget->backgroundRole(), color);
- widget->setPalette(palette);
- \endcode
-*/
-
-/*!
- \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap)
-
- Use the palette directly.
-
- \oldcode
- widget->setPaletteBackgroundPixmap(pixmap);
- \newcode
- QPalette palette;
- palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
- widget->setPalette(palette);
- \endcode
-*/
-
-/*!
- \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap)
-
- Use the palette instead.
-
- \oldcode
- widget->setBackgroundPixmap(pixmap);
- \newcode
- QPalette palette;
- palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
- widget->setPalette(palette);
- \endcode
-*/
-
-/*!
- \fn void QWidget::setBackgroundColor(const QColor &color)
-
- Use the palette instead.
-
- \oldcode
- widget->setBackgroundColor(color);
- \newcode
- QPalette palette;
- palette.setColor(widget->backgroundRole(), color);
- widget->setPalette(palette);
- \endcode
-*/
-
-
-/*!
- \fn QWidget *QWidget::parentWidget(bool sameWindow) const
-
- Use the no-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::setKeyCompression(bool b)
-
- Use setAttribute(Qt::WA_KeyCompression, b) instead.
-*/
-
-/*!
- \fn void QWidget::setFont(const QFont &f, bool b)
-
- Use the single-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::setPalette(const QPalette &p, bool b)
-
- Use the single-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::setBackgroundOrigin(BackgroundOrigin background)
-
- \obsolete
-*/
-
-/*!
- \fn BackgroundOrigin QWidget::backgroundOrigin() const
-
- \obsolete
-
- Always returns \c WindowOrigin.
-*/
-
-/*!
- \fn QPoint QWidget::backgroundOffset() const
-
- \obsolete
-
- Always returns QPoint().
-*/
-
-/*!
- \fn void QWidget::repaint(bool b)
-
- The boolean parameter \a b is ignored. Use the no-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::repaint(int x, int y, int w, int h, bool b)
-
- The boolean parameter \a b is ignored. Use the four-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::repaint(const QRect &r, bool b)
-
- The boolean parameter \a b is ignored. Use the single rect-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::repaint(const QRegion &rgn, bool b)
-
- The boolean parameter \a b is ignored. Use the single region-argument overload instead.
-*/
-
-/*!
- \fn void QWidget::erase()
-
- Drawing may only take place in a QPaintEvent. Overload
- paintEvent() to do your erasing and call update() to schedule a
- replaint whenever necessary. See also QPainter.
-*/
-
-/*!
- \fn void QWidget::erase(int x, int y, int w, int h)
-
- Drawing may only take place in a QPaintEvent. Overload
- paintEvent() to do your erasing and call update() to schedule a
- replaint whenever necessary. See also QPainter.
-*/
-
-/*!
- \fn void QWidget::erase(const QRect &rect)
-
- Drawing may only take place in a QPaintEvent. Overload
- paintEvent() to do your erasing and call update() to schedule a
- replaint whenever necessary. See also QPainter.
-*/
-
-/*!
- \fn void QWidget::drawText(const QPoint &p, const QString &s)
-
- Drawing may only take place in a QPaintEvent. Overload
- paintEvent() to do your drawing and call update() to schedule a
- replaint whenever necessary. See also QPainter.
-*/
-
-/*!
- \fn void QWidget::drawText(int x, int y, const QString &s)
-
- Drawing may only take place in a QPaintEvent. Overload
- paintEvent() to do your drawing and call update() to schedule a
- replaint whenever necessary. See also QPainter.
-*/
-
-/*!
- \fn QWidget *QWidget::childAt(const QPoint &p, bool includeThis) const
-
- Use the single point argument overload instead.
-*/
-
-/*!
- \fn void QWidget::setCaption(const QString &c)
-
- Use setWindowTitle() instead.
-*/
-
-/*!
- \fn void QWidget::setIcon(const QPixmap &i)
-
- Use setWindowIcon() instead.
-*/
-
-/*!
- \fn void QWidget::setIconText(const QString &it)
-
- Use setWindowIconText() instead.
-*/
-
-/*!
- \fn QString QWidget::caption() const
-
- Use windowTitle() instead.
-*/
-
-/*!
- \fn QString QWidget::iconText() const
-
- Use windowIconText() instead.
-*/
-
-/*!
- \fn bool QWidget::isTopLevel() const
- \obsolete
-
- Use isWindow() instead.
-*/
-
-/*!
- \fn bool QWidget::isRightToLeft() const
- \internal
-*/
-
-/*!
- \fn bool QWidget::isLeftToRight() const
- \internal
-*/
-
-/*!
- \fn void QWidget::setInputMethodEnabled(bool enabled)
-
- Use setAttribute(Qt::WA_InputMethodEnabled, \a enabled) instead.
-*/
-
-/*!
- \fn bool QWidget::isInputMethodEnabled() const
-
- Use testAttribute(Qt::WA_InputMethodEnabled) instead.
-*/
-
-/*!
- \fn void QWidget::setActiveWindow()
-
- Use activateWindow() instead.
-*/
-
-/*!
- \fn bool QWidget::isShown() const
-
- Use !isHidden() instead (notice the exclamation mark), or use isVisible() to check whether the widget is visible.
-*/
-
-/*!
- \fn bool QWidget::isDialog() const
-
- Use windowType() == Qt::Dialog instead.
-*/
-
-/*!
- \fn bool QWidget::isPopup() const
-
- Use windowType() == Qt::Popup instead.
-*/
-
-/*!
- \fn bool QWidget::isDesktop() const
-
- Use windowType() == Qt::Desktop instead.
-*/
-
-/*!
- \fn void QWidget::polish()
-
- Use ensurePolished() instead.
-*/
-
-/*!
- \fn QWidget *QWidget::childAt(int x, int y, bool includeThis) const
-
- Use the childAt() overload that doesn't have an \a includeThis parameter.
-
- \oldcode
- return widget->childAt(x, y, true);
- \newcode
- QWidget *child = widget->childAt(x, y, true);
- if (child)
- return child;
- if (widget->rect().contains(x, y))
- return widget;
- \endcode
-*/
-
-/*!
- \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
- \compat
-
- Use the \l sizePolicy property and heightForWidth() function instead.
-*/
-
-/*!
- \fn bool QWidget::isUpdatesEnabled() const
- \compat
-
- Use the \l updatesEnabled property instead.
-*/
-
-/*!
- \macro QWIDGETSIZE_MAX
- \relates QWidget
-
- Defines the maximum size for a QWidget object.
-
- The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
- QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
-
- \sa QWidget::setMaximumSize()
-*/
-
-/*!
- \fn QWidget::setupUi(QWidget *widget)
-
- Sets up the user interface for the specified \a widget.
-
- \note This function is available with widgets that derive from user
- interface descriptions created using \l{uic}.
-
- \sa {Using a Designer UI File in Your Application}
-*/
-
-QRect QWidgetPrivate::frameStrut() const
-{
- Q_Q(const QWidget);
- if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
- // x2 = x1 + w - 1, so w/h = 1
- return QRect(0, 0, 1, 1);
- }
-
- if (data.fstrut_dirty
-#ifndef Q_WS_WIN
- // ### Fix properly for 4.3
- && q->isVisible()
-#endif
- && q->testAttribute(Qt::WA_WState_Created))
- const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
-
- return maybeTopData() ? maybeTopData()->frameStrut : QRect();
-}
-
-#ifdef QT_KEYPAD_NAVIGATION
-/*!
- \internal
-
- Changes the focus from the current focusWidget to a widget in
- the \a direction.
-
- Returns true, if there was a widget in that direction
-*/
-bool QWidgetPrivate::navigateToDirection(Direction direction)
-{
- QWidget *targetWidget = widgetInNavigationDirection(direction);
- if (targetWidget)
- targetWidget->setFocus();
- return (targetWidget != 0);
-}
-
-/*!
- \internal
-
- Searches for a widget that is positioned in the \a direction, starting
- from the current focusWidget.
-
- Returns the pointer to a found widget or 0, if there was no widget in
- that direction.
-*/
-QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
-{
- const QWidget *sourceWidget = QApplication::focusWidget();
- if (!sourceWidget)
- return 0;
- const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
- const int sourceX =
- (direction == DirectionNorth || direction == DirectionSouth) ?
- (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
- :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
- const int sourceY =
- (direction == DirectionEast || direction == DirectionWest) ?
- (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
- :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
- const QPoint sourcePoint(sourceX, sourceY);
- const QPoint sourceCenter = sourceRect.center();
- const QWidget *sourceWindow = sourceWidget->window();
-
- QWidget *targetWidget = 0;
- int shortestDistance = INT_MAX;
- foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
-
- const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
-
- // For focus proxies, the child widget handling the focus can have keypad navigation focus,
- // but the owner of the proxy cannot.
- // Additionally, empty widgets should be ignored.
- if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
- continue;
-
- // Only navigate to a target widget that...
- if ( targetCandidate != sourceWidget
- // ...takes the focus,
- && targetCandidate->focusPolicy() & Qt::TabFocus
- // ...is above if DirectionNorth,
- && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
- // ...is on the right if DirectionEast,
- && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
- // ...is below if DirectionSouth,
- && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
- // ...is on the left if DirectionWest,
- && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
- // ...is enabled,
- && targetCandidate->isEnabled()
- // ...is visible,
- && targetCandidate->isVisible()
- // ...is in the same window,
- && targetCandidate->window() == sourceWindow) {
- const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
- if (targetCandidateDistance < shortestDistance) {
- shortestDistance = targetCandidateDistance;
- targetWidget = targetCandidate;
- }
- }
- }
- return targetWidget;
-}
-
-/*!
- \internal
-
- Tells us if it there is currently a reachable widget by keypad navigation in
- a certain \a orientation.
- If no navigation is possible, occurring key events in that \a orientation may
- be used to interact with the value in the focused widget, even though it
- currently has not the editFocus.
-
- \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
-*/
-bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
-{
- return orientation == Qt::Horizontal?
- (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
- || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
- :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
- || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
-}
-/*!
- \internal
-
- Checks, if the \a widget is inside a QTabWidget. If is is inside
- one, left/right key events will be used to switch between tabs in keypad
- navigation. If there is no QTabWidget, the horizontal key events can be used
-to
- interact with the value in the focused widget, even though it currently has
- not the editFocus.
-
- \sa QWidget::hasEditFocus()
-*/
-bool QWidgetPrivate::inTabWidget(QWidget *widget)
-{
- for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
- if (qobject_cast<const QTabWidget*>(tabWidget))
- return true;
- return false;
-}
-#endif
-
-/*!
- \preliminary
- \since 4.2
- \obsolete
-
- Sets the window surface to be the \a surface specified.
- The QWidget takes will ownership of the \a surface.
- widget itself is deleted.
-*/
-void QWidget::setWindowSurface(QWindowSurface *surface)
-{
- // ### createWinId() ??
-
-#ifndef Q_BACKINGSTORE_SUBSURFACES
- if (!isTopLevel())
- return;
-#endif
-
- Q_D(QWidget);
-
- QTLWExtra *topData = d->topData();
- if (topData->windowSurface == surface)
- return;
-
- QWindowSurface *oldSurface = topData->windowSurface;
- delete topData->windowSurface;
- topData->windowSurface = surface;
-
- QWidgetBackingStore *bs = d->maybeBackingStore();
- if (!bs)
- return;
-
- if (isTopLevel()) {
- if (bs->windowSurface != oldSurface && bs->windowSurface != surface)
- delete bs->windowSurface;
- bs->windowSurface = surface;
- }
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- else {
- bs->subSurfaces.append(surface);
- }
- bs->subSurfaces.removeOne(oldSurface);
-#endif
-}
-
-/*!
- \preliminary
- \since 4.2
-
- Returns the QWindowSurface this widget will be drawn into.
-*/
-QWindowSurface *QWidget::windowSurface() const
-{
- Q_D(const QWidget);
- QTLWExtra *extra = d->maybeTopData();
- if (extra && extra->windowSurface)
- return extra->windowSurface;
-
- QWidgetBackingStore *bs = d->maybeBackingStore();
-
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- if (bs && bs->subSurfaces.isEmpty())
- return bs->windowSurface;
-
- if (!isTopLevel()) {
- const QWidget *w = parentWidget();
- while (w) {
- QTLWExtra *extra = w->d_func()->maybeTopData();
- if (extra && extra->windowSurface)
- return extra->windowSurface;
- if (w->isTopLevel())
- break;
- w = w->parentWidget();
- }
- }
-#endif // Q_BACKINGSTORE_SUBSURFACES
-
- return bs ? bs->windowSurface : 0;
-}
-
-void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
-{
- if (left)
- *left = (int)leftLayoutItemMargin;
- if (top)
- *top = (int)topLayoutItemMargin;
- if (right)
- *right = (int)rightLayoutItemMargin;
- if (bottom)
- *bottom = (int)bottomLayoutItemMargin;
-}
-
-void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
-{
- if (leftLayoutItemMargin == left
- && topLayoutItemMargin == top
- && rightLayoutItemMargin == right
- && bottomLayoutItemMargin == bottom)
- return;
-
- Q_Q(QWidget);
- leftLayoutItemMargin = (signed char)left;
- topLayoutItemMargin = (signed char)top;
- rightLayoutItemMargin = (signed char)right;
- bottomLayoutItemMargin = (signed char)bottom;
- q->updateGeometry();
-}
-
-void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
-{
- Q_Q(QWidget);
- QStyleOption myOpt;
- if (!opt) {
- myOpt.initFrom(q);
- myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
- opt = &myOpt;
- }
-
- QRect liRect = q->style()->subElementRect(element, opt, q);
- if (liRect.isValid()) {
- leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
- topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
- rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
- bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
- } else {
- leftLayoutItemMargin = 0;
- topLayoutItemMargin = 0;
- rightLayoutItemMargin = 0;
- bottomLayoutItemMargin = 0;
- }
-}
-// resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
-void QWidgetPrivate::adjustQuitOnCloseAttribute()
-{
- Q_Q(QWidget);
-
- if (!q->parentWidget()) {
- Qt::WindowType type = q->windowType();
- if (type == Qt::Widget || type == Qt::SubWindow)
- type = Qt::Window;
- if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
- q->setAttribute(Qt::WA_QuitOnClose, false);
- }
-}
-
-
-
-Q_GUI_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
-{
- return widget->data;
-}
-
-Q_GUI_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
-{
- return widget->d_func();
-}
-
-
-#ifndef QT_NO_GRAPHICSVIEW
-/*!
- \since 4.5
-
- Returns the proxy widget for the corresponding embedded widget in a graphics
- view; otherwise returns 0.
-
- \sa QGraphicsProxyWidget::createProxyForChildWidget(),
- QGraphicsScene::addWidget()
- */
-QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
-{
- Q_D(const QWidget);
- if (d->extra) {
- return d->extra->proxyWidget;
- }
- return 0;
-}
-#endif
-
-
-/*!
- \typedef QWidgetList
- \relates QWidget
-
- Synonym for QList<QWidget *>.
-*/
-
-#ifndef QT_NO_GESTURES
-/*!
- Subscribes the widget to a given \a gesture with specific \a flags.
-
- \sa ungrabGesture(), QGestureEvent
- \since 4.6
-*/
-void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
-{
- Q_D(QWidget);
- d->gestureContext.insert(gesture, flags);
- (void)QGestureManager::instance(); // create a gesture manager
-}
-
-/*!
- Unsubscribes the widget from a given \a gesture type
-
- \sa grabGesture(), QGestureEvent
- \since 4.6
-*/
-void QWidget::ungrabGesture(Qt::GestureType gesture)
-{
- Q_D(QWidget);
- if (d->gestureContext.remove(gesture)) {
- if (QGestureManager *manager = QGestureManager::instance())
- manager->cleanupCachedGestures(this, gesture);
- }
-}
-#endif // QT_NO_GESTURES
-
-/*!
- \typedef WId
- \relates QWidget
-
- Platform dependent window identifier.
-*/
-
-/*!
- \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-
- Frees up window system resources. Destroys the widget window if \a
- destroyWindow is true.
-
- destroy() calls itself recursively for all the child widgets,
- passing \a destroySubWindows for the \a destroyWindow parameter.
- To have more control over destruction of subwidgets, destroy
- subwidgets selectively first.
-
- This function is usually called from the QWidget destructor.
-*/
-
-/*!
- \fn QPaintEngine *QWidget::paintEngine() const
-
- Returns the widget's paint engine.
-
- Note that this function should not be called explicitly by the
- user, since it's meant for reimplementation purposes only. The
- function is called by Qt internally, and the default
- implementation may not always return a valid pointer.
-*/
-
-/*!
- \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
-
- Translates the widget coordinate \a pos to global screen
- coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
- the global coordinates of the top-left pixel of the widget.
-
- \sa mapFromGlobal() mapTo() mapToParent()
-*/
-
-/*!
- \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-
- Translates the global screen coordinate \a pos to widget
- coordinates.
-
- \sa mapToGlobal() mapFrom() mapFromParent()
-*/
-
-/*!
- \fn void QWidget::grabMouse()
-
- Grabs the mouse input.
-
- This widget receives all mouse events until releaseMouse() is
- called; other widgets get no mouse events at all. Keyboard
- events are not affected. Use grabKeyboard() if you want to grab
- that.
-
- \warning Bugs in mouse-grabbing applications very often lock the
- terminal. Use this function with extreme caution, and consider
- using the \c -nograb command line option while debugging.
-
- It is almost never necessary to grab the mouse when using Qt, as
- Qt grabs and releases it sensibly. In particular, Qt grabs the
- mouse when a mouse button is pressed and keeps it until the last
- button is released.
-
- \note Only visible widgets can grab mouse input. If isVisible()
- returns false for a widget, that widget cannot call grabMouse().
-
- \note \bold{(Mac OS X developers)} For \e Cocoa, calling
- grabMouse() on a widget only works when the mouse is inside the
- frame of that widget. For \e Carbon, it works outside the widget's
- frame as well, like for Windows and X11.
-
- \sa releaseMouse() grabKeyboard() releaseKeyboard()
-*/
-
-/*!
- \fn void QWidget::grabMouse(const QCursor &cursor)
- \overload grabMouse()
-
- Grabs the mouse input and changes the cursor shape.
-
- The cursor will assume shape \a cursor (for as long as the mouse
- focus is grabbed) and this widget will be the only one to receive
- mouse events until releaseMouse() is called().
-
- \warning Grabbing the mouse might lock the terminal.
-
- \note \bold{(Mac OS X developers)} See the note in QWidget::grabMouse().
-
- \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
-*/
-
-/*!
- \fn void QWidget::releaseMouse()
-
- Releases the mouse grab.
-
- \sa grabMouse(), grabKeyboard(), releaseKeyboard()
-*/
-
-/*!
- \fn void QWidget::grabKeyboard()
-
- Grabs the keyboard input.
-
- This widget receives all keyboard events until releaseKeyboard()
- is called; other widgets get no keyboard events at all. Mouse
- events are not affected. Use grabMouse() if you want to grab that.
-
- The focus widget is not affected, except that it doesn't receive
- any keyboard events. setFocus() moves the focus as usual, but the
- new focus widget receives keyboard events only after
- releaseKeyboard() is called.
-
- If a different widget is currently grabbing keyboard input, that
- widget's grab is released first.
-
- \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
-*/
-
-/*!
- \fn void QWidget::releaseKeyboard()
-
- Releases the keyboard grab.
-
- \sa grabKeyboard(), grabMouse(), releaseMouse()
-*/
-
-/*!
- \fn QWidget *QWidget::mouseGrabber()
-
- Returns the widget that is currently grabbing the mouse input.
-
- If no widget in this application is currently grabbing the mouse,
- 0 is returned.
-
- \sa grabMouse(), keyboardGrabber()
-*/
-
-/*!
- \fn QWidget *QWidget::keyboardGrabber()
-
- Returns the widget that is currently grabbing the keyboard input.
-
- If no widget in this application is currently grabbing the
- keyboard, 0 is returned.
-
- \sa grabMouse(), mouseGrabber()
-*/
-
-/*!
- \fn void QWidget::activateWindow()
-
- Sets the top-level widget containing this widget to be the active
- window.
-
- An active window is a visible top-level window that has the
- keyboard input focus.
-
- This function performs the same operation as clicking the mouse on
- the title bar of a top-level window. On X11, the result depends on
- the Window Manager. If you want to ensure that the window is
- stacked on top as well you should also call raise(). Note that the
- window must be visible, otherwise activateWindow() has no effect.
-
- On Windows, if you are calling this when the application is not
- currently the active one then it will not make it the active
- window. It will change the color of the taskbar entry to indicate
- that the window has changed in some way. This is because Microsoft
- does not allow an application to interrupt what the user is currently
- doing in another application.
-
- \sa isActiveWindow(), window(), show()
-*/
-
-/*!
- \fn int QWidget::metric(PaintDeviceMetric m) const
-
- Internal implementation of the virtual QPaintDevice::metric()
- function.
-
- \a m is the metric to get.
-*/
-
-void QWidget::init(QPainter *painter) const
-{
- const QPalette &pal = palette();
- painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
- painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
- QFont f(font(), const_cast<QWidget *>(this));
- painter->d_func()->state->deviceFont = f;
- painter->d_func()->state->font = f;
-}
-
-QPaintDevice *QWidget::redirected(QPoint *offset) const
-{
- return d_func()->redirected(offset);
-}
-
-QPainter *QWidget::sharedPainter() const
-{
- // Someone sent a paint event directly to the widget
- if (!d_func()->redirectDev)
- return 0;
-
- QPainter *sp = d_func()->sharedPainter();
- if (!sp || !sp->isActive())
- return 0;
-
- if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
- return 0;
-
- return sp;
-}
-
-/*!
- \fn void QWidget::setMask(const QRegion &region)
- \overload
-
- Causes only the parts of the widget which overlap \a region to be
- visible. If the region includes pixels outside the rect() of the
- widget, window system controls in that area may or may not be
- visible, depending on the platform.
-
- Note that this effect can be slow if the region is particularly
- complex.
-
- \sa windowOpacity
-*/
-void QWidget::setMask(const QRegion &newMask)
-{
- Q_D(QWidget);
-
- d->createExtra();
- if (newMask == d->extra->mask)
- return;
-
-#ifndef QT_NO_BACKINGSTORE
- const QRegion oldMask(d->extra->mask);
-#endif
-
- d->extra->mask = newMask;
- d->extra->hasMask = !newMask.isEmpty();
-
-#ifndef QT_MAC_USE_COCOA
- if (!testAttribute(Qt::WA_WState_Created))
- return;
-#endif
-
- d->setMask_sys(newMask);
-
-#ifndef QT_NO_BACKINGSTORE
- if (!isVisible())
- return;
-
- if (!d->extra->hasMask) {
- // Mask was cleared; update newly exposed area.
- QRegion expose(rect());
- expose -= oldMask;
- if (!expose.isEmpty()) {
- d->setDirtyOpaqueRegion();
- update(expose);
- }
- return;
- }
-
- if (!isWindow()) {
- // Update newly exposed area on the parent widget.
- QRegion parentExpose(rect());
- parentExpose -= newMask;
- if (!parentExpose.isEmpty()) {
- d->setDirtyOpaqueRegion();
- parentExpose.translate(data->crect.topLeft());
- parentWidget()->update(parentExpose);
- }
-
- // Update newly exposed area on this widget
- if (!oldMask.isEmpty())
- update(newMask - oldMask);
- }
-#endif
-}
-
-/*!
- \fn void QWidget::setMask(const QBitmap &bitmap)
-
- Causes only the pixels of the widget for which \a bitmap has a
- corresponding 1 bit to be visible. If the region includes pixels
- outside the rect() of the widget, window system controls in that
- area may or may not be visible, depending on the platform.
-
- Note that this effect can be slow if the region is particularly
- complex.
-
- The following code shows how an image with an alpha channel can be
- used to generate a mask for a widget:
-
- \snippet doc/src/snippets/widget-mask/main.cpp 0
-
- The label shown by this code is masked using the image it contains,
- giving the appearance that an irregularly-shaped image is being drawn
- directly onto the screen.
-
- Masked widgets receive mouse events only on their visible
- portions.
-
- \sa clearMask(), windowOpacity(), {Shaped Clock Example}
-*/
-void QWidget::setMask(const QBitmap &bitmap)
-{
- setMask(QRegion(bitmap));
-}
-
-/*!
- \fn void QWidget::clearMask()
-
- Removes any mask set by setMask().
-
- \sa setMask()
-*/
-void QWidget::clearMask()
-{
- setMask(QRegion());
-}
-
-/*! \fn const QX11Info &QWidget::x11Info() const
- Returns information about the configuration of the X display used to display
- the widget.
-
- \warning This function is only available on X11.
-*/
-
-/*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
- Returns the X11 Picture handle of the widget for XRender
- support. Use of this function is not portable. This function will
- return 0 if XRender support is not compiled into Qt, if the
- XRender extension is not supported on the X11 display, or if the
- handle could not be created.
-*/
-
-#ifdef Q_OS_SYMBIAN
-void QWidgetPrivate::_q_delayedDestroy(WId winId)
-{
- delete winId;
-}
-#endif
-
-#if QT_MAC_USE_COCOA
-void QWidgetPrivate::syncUnifiedMode() {
- // The whole purpose of this method is to keep the unifiedToolbar in sync.
- // That means making sure we either exchange the drawing methods or we let
- // the toolbar know that it does not require to draw the baseline.
- Q_Q(QWidget);
- // This function makes sense only if this is a top level
- if(!q->isWindow())
- return;
- OSWindowRef window = qt_mac_window_for(q);
- if(changeMethods) {
- // Ok, we are in documentMode.
- if(originalDrawMethod)
- qt_mac_replaceDrawRect(window, this);
- } else {
- if(!originalDrawMethod)
- qt_mac_replaceDrawRectOriginal(window, this);
- }
-}
-
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
-
-#include "moc_qwidget.cpp"
-
diff --git a/src/gui/kernel/qwidget.h b/src/gui/kernel/qwidget.h
deleted file mode 100644
index d14e8652be..0000000000
--- a/src/gui/kernel/qwidget.h
+++ /dev/null
@@ -1,1091 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGET_H
-#define QWIDGET_H
-
-#include <QtGui/qwindowdefs.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qmargins.h>
-#include <QtGui/qpaintdevice.h>
-#include <QtGui/qpalette.h>
-#include <QtGui/qfont.h>
-#include <QtGui/qfontmetrics.h>
-#include <QtGui/qfontinfo.h>
-#include <QtGui/qsizepolicy.h>
-#include <QtGui/qregion.h>
-#include <QtGui/qbrush.h>
-#include <QtGui/qcursor.h>
-#include <QtGui/qkeysequence.h>
-
-#ifdef Q_WS_QPA //should this go somewhere else?
-#include <QtGui/qwindow.h>
-#include <QtGui/qwindowformat_qpa.h>
-#endif
-
-#ifdef QT_INCLUDE_COMPAT
-#include <QtGui/qevent.h>
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QLayout;
-class QWSRegionManager;
-class QStyle;
-class QAction;
-class QVariant;
-
-class QActionEvent;
-class QMouseEvent;
-class QWheelEvent;
-class QHoverEvent;
-class QKeyEvent;
-class QFocusEvent;
-class QPaintEvent;
-class QMoveEvent;
-class QResizeEvent;
-class QCloseEvent;
-class QContextMenuEvent;
-class QInputMethodEvent;
-class QTabletEvent;
-class QDragEnterEvent;
-class QDragMoveEvent;
-class QDragLeaveEvent;
-class QDropEvent;
-class QShowEvent;
-class QHideEvent;
-class QInputContext;
-class QIcon;
-class QWindowSurface;
-class QPlatformWindow;
-class QLocale;
-class QGraphicsProxyWidget;
-class QGraphicsEffect;
-class QRasterWindowSurface;
-class QUnifiedToolbarSurface;
-#if defined(Q_WS_X11)
-class QX11Info;
-#endif
-
-class QWidgetData
-{
-public:
- WId winid;
- uint widget_attributes;
- Qt::WindowFlags window_flags;
- uint window_state : 4;
- uint focus_policy : 4;
- uint sizehint_forced :1;
- uint is_closing :1;
- uint in_show : 1;
- uint in_set_window_state : 1;
- mutable uint fstrut_dirty : 1;
- uint context_menu_policy : 3;
- uint window_modality : 2;
- uint in_destructor : 1;
- uint unused : 13;
- QRect crect;
- mutable QPalette pal;
- QFont fnt;
-#if defined(Q_WS_QWS)
-// QRegion req_region; // Requested region
-// mutable QRegion paintable_region; // Paintable region
-// mutable bool paintable_region_dirty;// needs to be recalculated
-// mutable QRegion alloc_region; // Allocated region
-// mutable bool alloc_region_dirty; // needs to be recalculated
-// mutable int overlapping_children; // Handle overlapping children
-
- int alloc_region_index;
-// int alloc_region_revision;
-#endif
- QRect wrect;
-};
-
-class QWidgetPrivate;
-
-class Q_GUI_EXPORT QWidget : public QObject, public QPaintDevice
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QWidget)
-
- Q_PROPERTY(bool modal READ isModal)
- Q_PROPERTY(Qt::WindowModality windowModality READ windowModality WRITE setWindowModality)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
- Q_PROPERTY(QRect geometry READ geometry WRITE setGeometry)
- Q_PROPERTY(QRect frameGeometry READ frameGeometry)
- Q_PROPERTY(QRect normalGeometry READ normalGeometry)
- Q_PROPERTY(int x READ x)
- Q_PROPERTY(int y READ y)
- Q_PROPERTY(QPoint pos READ pos WRITE move DESIGNABLE false STORED false)
- Q_PROPERTY(QSize frameSize READ frameSize)
- Q_PROPERTY(QSize size READ size WRITE resize DESIGNABLE false STORED false)
- Q_PROPERTY(int width READ width)
- Q_PROPERTY(int height READ height)
- Q_PROPERTY(QRect rect READ rect)
- Q_PROPERTY(QRect childrenRect READ childrenRect)
- Q_PROPERTY(QRegion childrenRegion READ childrenRegion)
- Q_PROPERTY(QSizePolicy sizePolicy READ sizePolicy WRITE setSizePolicy)
- Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize)
- Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize)
- Q_PROPERTY(int minimumWidth READ minimumWidth WRITE setMinimumWidth STORED false DESIGNABLE false)
- Q_PROPERTY(int minimumHeight READ minimumHeight WRITE setMinimumHeight STORED false DESIGNABLE false)
- Q_PROPERTY(int maximumWidth READ maximumWidth WRITE setMaximumWidth STORED false DESIGNABLE false)
- Q_PROPERTY(int maximumHeight READ maximumHeight WRITE setMaximumHeight STORED false DESIGNABLE false)
- Q_PROPERTY(QSize sizeIncrement READ sizeIncrement WRITE setSizeIncrement)
- Q_PROPERTY(QSize baseSize READ baseSize WRITE setBaseSize)
- Q_PROPERTY(QPalette palette READ palette WRITE setPalette)
- Q_PROPERTY(QFont font READ font WRITE setFont)
-#ifndef QT_NO_CURSOR
- Q_PROPERTY(QCursor cursor READ cursor WRITE setCursor RESET unsetCursor)
-#endif
- Q_PROPERTY(bool mouseTracking READ hasMouseTracking WRITE setMouseTracking)
- Q_PROPERTY(bool isActiveWindow READ isActiveWindow)
- Q_PROPERTY(Qt::FocusPolicy focusPolicy READ focusPolicy WRITE setFocusPolicy)
- Q_PROPERTY(bool focus READ hasFocus)
- Q_PROPERTY(Qt::ContextMenuPolicy contextMenuPolicy READ contextMenuPolicy WRITE setContextMenuPolicy)
- Q_PROPERTY(bool updatesEnabled READ updatesEnabled WRITE setUpdatesEnabled DESIGNABLE false)
- Q_PROPERTY(bool visible READ isVisible WRITE setVisible DESIGNABLE false)
- Q_PROPERTY(bool minimized READ isMinimized)
- Q_PROPERTY(bool maximized READ isMaximized)
- Q_PROPERTY(bool fullScreen READ isFullScreen)
- Q_PROPERTY(QSize sizeHint READ sizeHint)
- Q_PROPERTY(QSize minimumSizeHint READ minimumSizeHint)
- Q_PROPERTY(bool acceptDrops READ acceptDrops WRITE setAcceptDrops)
- Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle DESIGNABLE isWindow)
- Q_PROPERTY(QIcon windowIcon READ windowIcon WRITE setWindowIcon DESIGNABLE isWindow)
- Q_PROPERTY(QString windowIconText READ windowIconText WRITE setWindowIconText DESIGNABLE isWindow)
- Q_PROPERTY(double windowOpacity READ windowOpacity WRITE setWindowOpacity DESIGNABLE isWindow)
- Q_PROPERTY(bool windowModified READ isWindowModified WRITE setWindowModified DESIGNABLE isWindow)
-#ifndef QT_NO_TOOLTIP
- Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip)
-#endif
-#ifndef QT_NO_STATUSTIP
- Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip)
-#endif
-#ifndef QT_NO_WHATSTHIS
- Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis)
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- Q_PROPERTY(QString accessibleName READ accessibleName WRITE setAccessibleName)
- Q_PROPERTY(QString accessibleDescription READ accessibleDescription WRITE setAccessibleDescription)
-#endif
- Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection RESET unsetLayoutDirection)
- QDOC_PROPERTY(Qt::WindowFlags windowFlags READ windowFlags WRITE setWindowFlags)
- Q_PROPERTY(bool autoFillBackground READ autoFillBackground WRITE setAutoFillBackground)
-#ifndef QT_NO_STYLE_STYLESHEET
- Q_PROPERTY(QString styleSheet READ styleSheet WRITE setStyleSheet)
-#endif
- Q_PROPERTY(QLocale locale READ locale WRITE setLocale RESET unsetLocale)
- Q_PROPERTY(QString windowFilePath READ windowFilePath WRITE setWindowFilePath DESIGNABLE isWindow)
- Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ inputMethodHints WRITE setInputMethodHints)
-
-public:
- enum RenderFlag {
- DrawWindowBackground = 0x1,
- DrawChildren = 0x2,
- IgnoreMask = 0x4
- };
- Q_DECLARE_FLAGS(RenderFlags, RenderFlag)
-
- explicit QWidget(QWidget* parent = 0, Qt::WindowFlags f = 0);
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QWidget(QWidget* parent, const char *name, Qt::WindowFlags f = 0);
-#endif
- ~QWidget();
-
- int devType() const;
-
- WId winId() const;
- void createWinId(); // internal, going away
- inline WId internalWinId() const { return data->winid; }
- WId effectiveWinId() const;
-
- // GUI style setting
- QStyle *style() const;
- void setStyle(QStyle *);
- // Widget types and states
-
- bool isTopLevel() const;
- bool isWindow() const;
-
- bool isModal() const;
- Qt::WindowModality windowModality() const;
- void setWindowModality(Qt::WindowModality windowModality);
-
- bool isEnabled() const;
- bool isEnabledTo(QWidget*) const;
- bool isEnabledToTLW() const;
-
-public Q_SLOTS:
- void setEnabled(bool);
- void setDisabled(bool);
- void setWindowModified(bool);
-
- // Widget coordinates
-
-public:
- QRect frameGeometry() const;
- const QRect &geometry() const;
- QRect normalGeometry() const;
-
- int x() const;
- int y() const;
- QPoint pos() const;
- QSize frameSize() const;
- QSize size() const;
- inline int width() const;
- inline int height() const;
- inline QRect rect() const;
- QRect childrenRect() const;
- QRegion childrenRegion() const;
-
- QSize minimumSize() const;
- QSize maximumSize() const;
- int minimumWidth() const;
- int minimumHeight() const;
- int maximumWidth() const;
- int maximumHeight() const;
- void setMinimumSize(const QSize &);
- void setMinimumSize(int minw, int minh);
- void setMaximumSize(const QSize &);
- void setMaximumSize(int maxw, int maxh);
- void setMinimumWidth(int minw);
- void setMinimumHeight(int minh);
- void setMaximumWidth(int maxw);
- void setMaximumHeight(int maxh);
-
-#ifdef Q_QDOC
- void setupUi(QWidget *widget);
-#endif
-
- QSize sizeIncrement() const;
- void setSizeIncrement(const QSize &);
- void setSizeIncrement(int w, int h);
- QSize baseSize() const;
- void setBaseSize(const QSize &);
- void setBaseSize(int basew, int baseh);
-
- void setFixedSize(const QSize &);
- void setFixedSize(int w, int h);
- void setFixedWidth(int w);
- void setFixedHeight(int h);
-
- // Widget coordinate mapping
-
- QPoint mapToGlobal(const QPoint &) const;
- QPoint mapFromGlobal(const QPoint &) const;
- QPoint mapToParent(const QPoint &) const;
- QPoint mapFromParent(const QPoint &) const;
- QPoint mapTo(QWidget *, const QPoint &) const;
- QPoint mapFrom(QWidget *, const QPoint &) const;
-
- QWidget *window() const;
- QWidget *nativeParentWidget() const;
- inline QWidget *topLevelWidget() const { return window(); }
-
- // Widget appearance functions
- const QPalette &palette() const;
- void setPalette(const QPalette &);
-
- void setBackgroundRole(QPalette::ColorRole);
- QPalette::ColorRole backgroundRole() const;
-
- void setForegroundRole(QPalette::ColorRole);
- QPalette::ColorRole foregroundRole() const;
-
- const QFont &font() const;
- void setFont(const QFont &);
- QFontMetrics fontMetrics() const;
- QFontInfo fontInfo() const;
-
-#ifndef QT_NO_CURSOR
- QCursor cursor() const;
- void setCursor(const QCursor &);
- void unsetCursor();
-#endif
-
- void setMouseTracking(bool enable);
- bool hasMouseTracking() const;
- bool underMouse() const;
-
- void setMask(const QBitmap &);
- void setMask(const QRegion &);
- QRegion mask() const;
- void clearMask();
-
- void render(QPaintDevice *target, const QPoint &targetOffset = QPoint(),
- const QRegion &sourceRegion = QRegion(),
- RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren));
-
- void render(QPainter *painter, const QPoint &targetOffset = QPoint(),
- const QRegion &sourceRegion = QRegion(),
- RenderFlags renderFlags = RenderFlags(DrawWindowBackground | DrawChildren));
-
-#ifndef QT_NO_GRAPHICSEFFECT
- QGraphicsEffect *graphicsEffect() const;
- void setGraphicsEffect(QGraphicsEffect *effect);
-#endif //QT_NO_GRAPHICSEFFECT
-
-#ifndef QT_NO_GESTURES
- void grabGesture(Qt::GestureType type, Qt::GestureFlags flags = Qt::GestureFlags());
- void ungrabGesture(Qt::GestureType type);
-#endif
-
-public Q_SLOTS:
- void setWindowTitle(const QString &);
-#ifndef QT_NO_STYLE_STYLESHEET
- void setStyleSheet(const QString& styleSheet);
-#endif
-public:
-#ifndef QT_NO_STYLE_STYLESHEET
- QString styleSheet() const;
-#endif
- QString windowTitle() const;
- void setWindowIcon(const QIcon &icon);
- QIcon windowIcon() const;
- void setWindowIconText(const QString &);
- QString windowIconText() const;
- void setWindowRole(const QString &);
- QString windowRole() const;
- void setWindowFilePath(const QString &filePath);
- QString windowFilePath() const;
-
- void setWindowOpacity(qreal level);
- qreal windowOpacity() const;
-
- bool isWindowModified() const;
-#ifndef QT_NO_TOOLTIP
- void setToolTip(const QString &);
- QString toolTip() const;
-#endif
-#ifndef QT_NO_STATUSTIP
- void setStatusTip(const QString &);
- QString statusTip() const;
-#endif
-#ifndef QT_NO_WHATSTHIS
- void setWhatsThis(const QString &);
- QString whatsThis() const;
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- QString accessibleName() const;
- void setAccessibleName(const QString &name);
- QString accessibleDescription() const;
- void setAccessibleDescription(const QString &description);
-#endif
-
- void setLayoutDirection(Qt::LayoutDirection direction);
- Qt::LayoutDirection layoutDirection() const;
- void unsetLayoutDirection();
-
- void setLocale(const QLocale &locale);
- QLocale locale() const;
- void unsetLocale();
-
- inline bool isRightToLeft() const { return layoutDirection() == Qt::RightToLeft; }
- inline bool isLeftToRight() const { return layoutDirection() == Qt::LeftToRight; }
-
-public Q_SLOTS:
- inline void setFocus() { setFocus(Qt::OtherFocusReason); }
-
-public:
- bool isActiveWindow() const;
- void activateWindow();
- void clearFocus();
-
- void setFocus(Qt::FocusReason reason);
- Qt::FocusPolicy focusPolicy() const;
- void setFocusPolicy(Qt::FocusPolicy policy);
- bool hasFocus() const;
- static void setTabOrder(QWidget *, QWidget *);
- void setFocusProxy(QWidget *);
- QWidget *focusProxy() const;
- Qt::ContextMenuPolicy contextMenuPolicy() const;
- void setContextMenuPolicy(Qt::ContextMenuPolicy policy);
-
- // Grab functions
- void grabMouse();
-#ifndef QT_NO_CURSOR
- void grabMouse(const QCursor &);
-#endif
- void releaseMouse();
- void grabKeyboard();
- void releaseKeyboard();
-#ifndef QT_NO_SHORTCUT
- int grabShortcut(const QKeySequence &key, Qt::ShortcutContext context = Qt::WindowShortcut);
- void releaseShortcut(int id);
- void setShortcutEnabled(int id, bool enable = true);
- void setShortcutAutoRepeat(int id, bool enable = true);
-#endif
- static QWidget *mouseGrabber();
- static QWidget *keyboardGrabber();
-
- // Update/refresh functions
- inline bool updatesEnabled() const;
- void setUpdatesEnabled(bool enable);
-
-#if 0 //def Q_WS_QWS
- void repaintUnclipped(const QRegion &, bool erase = true);
-#endif
-
-#ifndef QT_NO_GRAPHICSVIEW
- QGraphicsProxyWidget *graphicsProxyWidget() const;
-#endif
-
-public Q_SLOTS:
- void update();
- void repaint();
-
-public:
- inline void update(int x, int y, int w, int h);
- void update(const QRect&);
- void update(const QRegion&);
-
- void repaint(int x, int y, int w, int h);
- void repaint(const QRect &);
- void repaint(const QRegion &);
-
-public Q_SLOTS:
- // Widget management functions
-
- virtual void setVisible(bool visible);
- inline void setHidden(bool hidden) { setVisible(!hidden); }
-#ifndef Q_WS_WINCE
- inline void show() { setVisible(true); }
-#else
- void show();
-#endif
- inline void hide() { setVisible(false); }
- inline QT_MOC_COMPAT void setShown(bool shown) { setVisible(shown); }
-
- void showMinimized();
- void showMaximized();
- void showFullScreen();
- void showNormal();
-
- bool close();
- void raise();
- void lower();
-
-public:
- void stackUnder(QWidget*);
- void move(int x, int y);
- void move(const QPoint &);
- void resize(int w, int h);
- void resize(const QSize &);
- inline void setGeometry(int x, int y, int w, int h);
- void setGeometry(const QRect &);
- QByteArray saveGeometry() const;
- bool restoreGeometry(const QByteArray &geometry);
- void adjustSize();
- bool isVisible() const;
- bool isVisibleTo(QWidget*) const;
- // ### Qt 5: bool isVisibleTo(_const_ QWidget *) const
- inline bool isHidden() const;
-
- bool isMinimized() const;
- bool isMaximized() const;
- bool isFullScreen() const;
-
- Qt::WindowStates windowState() const;
- void setWindowState(Qt::WindowStates state);
- void overrideWindowState(Qt::WindowStates state);
-
- virtual QSize sizeHint() const;
- virtual QSize minimumSizeHint() const;
-
- QSizePolicy sizePolicy() const;
- void setSizePolicy(QSizePolicy);
- inline void setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical);
- virtual int heightForWidth(int) const;
-
- QRegion visibleRegion() const;
-
- void setContentsMargins(int left, int top, int right, int bottom);
- void setContentsMargins(const QMargins &margins);
- void getContentsMargins(int *left, int *top, int *right, int *bottom) const;
- QMargins contentsMargins() const;
-
- QRect contentsRect() const;
-
-public:
- QLayout *layout() const;
- void setLayout(QLayout *);
- void updateGeometry();
-
- void setParent(QWidget *parent);
- void setParent(QWidget *parent, Qt::WindowFlags f);
-
- void scroll(int dx, int dy);
- void scroll(int dx, int dy, const QRect&);
-
- // Misc. functions
-
- QWidget *focusWidget() const;
- QWidget *nextInFocusChain() const;
- QWidget *previousInFocusChain() const;
-
- // drag and drop
- bool acceptDrops() const;
- void setAcceptDrops(bool on);
-
-#ifndef QT_NO_ACTION
- //actions
- void addAction(QAction *action);
- void addActions(QList<QAction*> actions);
- void insertAction(QAction *before, QAction *action);
- void insertActions(QAction *before, QList<QAction*> actions);
- void removeAction(QAction *action);
- QList<QAction*> actions() const;
-#endif
-
- QWidget *parentWidget() const;
-
- void setWindowFlags(Qt::WindowFlags type);
- inline Qt::WindowFlags windowFlags() const;
- void overrideWindowFlags(Qt::WindowFlags type);
-
- inline Qt::WindowType windowType() const;
-
- static QWidget *find(WId);
-#ifdef QT3_SUPPORT
- static QT3_SUPPORT QWidgetMapper *wmapper();
-#endif
- inline QWidget *childAt(int x, int y) const;
- QWidget *childAt(const QPoint &p) const;
-
-#if defined(Q_WS_X11)
- const QX11Info &x11Info() const;
- Qt::HANDLE x11PictureHandle() const;
-#endif
-
-#if defined(Q_WS_MAC)
- Qt::HANDLE macQDHandle() const;
- Qt::HANDLE macCGHandle() const;
-#endif
-
-#if defined(Q_WS_WIN)
- HDC getDC() const;
- void releaseDC(HDC) const;
-#else
- Qt::HANDLE handle() const;
-#endif
-
- void setAttribute(Qt::WidgetAttribute, bool on = true);
- inline bool testAttribute(Qt::WidgetAttribute) const;
-
- QPaintEngine *paintEngine() const;
-
- void ensurePolished() const;
-
- QInputContext *inputContext();
- void setInputContext(QInputContext *);
-
- bool isAncestorOf(const QWidget *child) const;
-
-#ifdef QT_KEYPAD_NAVIGATION
- bool hasEditFocus() const;
- void setEditFocus(bool on);
-#endif
-
- bool autoFillBackground() const;
- void setAutoFillBackground(bool enabled);
-
- void setWindowSurface(QWindowSurface *surface);
- QWindowSurface *windowSurface() const;
-
-#if defined(Q_WS_QPA)
- void setWindowHandle(QWindow *window);
- QWindow *windowHandle() const;
-
- friend class QDesktopScreenWidget;
-#endif
-
-Q_SIGNALS:
- void customContextMenuRequested(const QPoint &pos);
-
-protected:
- // Event handlers
- bool event(QEvent *);
- virtual void mousePressEvent(QMouseEvent *);
- virtual void mouseReleaseEvent(QMouseEvent *);
- virtual void mouseDoubleClickEvent(QMouseEvent *);
- virtual void mouseMoveEvent(QMouseEvent *);
-#ifndef QT_NO_WHEELEVENT
- virtual void wheelEvent(QWheelEvent *);
-#endif
- virtual void keyPressEvent(QKeyEvent *);
- virtual void keyReleaseEvent(QKeyEvent *);
- virtual void focusInEvent(QFocusEvent *);
- virtual void focusOutEvent(QFocusEvent *);
- virtual void enterEvent(QEvent *);
- virtual void leaveEvent(QEvent *);
- virtual void paintEvent(QPaintEvent *);
- virtual void moveEvent(QMoveEvent *);
- virtual void resizeEvent(QResizeEvent *);
- virtual void closeEvent(QCloseEvent *);
-#ifndef QT_NO_CONTEXTMENU
- virtual void contextMenuEvent(QContextMenuEvent *);
-#endif
-#ifndef QT_NO_TABLETEVENT
- virtual void tabletEvent(QTabletEvent *);
-#endif
-#ifndef QT_NO_ACTION
- virtual void actionEvent(QActionEvent *);
-#endif
-
-#ifndef QT_NO_DRAGANDDROP
- virtual void dragEnterEvent(QDragEnterEvent *);
- virtual void dragMoveEvent(QDragMoveEvent *);
- virtual void dragLeaveEvent(QDragLeaveEvent *);
- virtual void dropEvent(QDropEvent *);
-#endif
-
- virtual void showEvent(QShowEvent *);
- virtual void hideEvent(QHideEvent *);
-
-#if defined(Q_WS_MAC)
- virtual bool macEvent(EventHandlerCallRef, EventRef);
-#endif
-#if defined(Q_WS_WIN)
- virtual bool winEvent(MSG *message, long *result);
-#endif
-#if defined(Q_WS_X11)
- virtual bool x11Event(XEvent *);
-#endif
-#if defined(Q_WS_QWS)
- virtual bool qwsEvent(QWSEvent *);
-#endif
-
- // Misc. protected functions
- virtual void changeEvent(QEvent *);
-
- int metric(PaintDeviceMetric) const;
- void init(QPainter *painter) const;
- QPaintDevice *redirected(QPoint *offset) const;
- QPainter *sharedPainter() const;
-
- virtual void inputMethodEvent(QInputMethodEvent *);
-public:
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery) const;
-
- Qt::InputMethodHints inputMethodHints() const;
- void setInputMethodHints(Qt::InputMethodHints hints);
-
-protected:
- void resetInputContext();
-protected Q_SLOTS:
- void updateMicroFocus();
-protected:
-
- void create(WId = 0, bool initializeWindow = true,
- bool destroyOldWindow = true);
- void destroy(bool destroyWindow = true,
- bool destroySubWindows = true);
-
- virtual bool focusNextPrevChild(bool next);
- inline bool focusNextChild() { return focusNextPrevChild(true); }
- inline bool focusPreviousChild() { return focusNextPrevChild(false); }
-
-protected:
- QWidget(QWidgetPrivate &d, QWidget* parent, Qt::WindowFlags f);
-private:
-
- bool testAttribute_helper(Qt::WidgetAttribute) const;
-
- QLayout *takeLayout();
-
- friend class QBackingStoreDevice;
- friend class QWidgetBackingStore;
- friend class QApplication;
- friend class QApplicationPrivate;
- friend class QGuiApplication;
- friend class QGuiApplicationPrivate;
- friend class QBaseApplication;
- friend class QPainter;
- friend class QPainterPrivate;
- friend class QPixmap; // for QPixmap::fill()
- friend class QFontMetrics;
- friend class QFontInfo;
- friend class QETWidget;
- friend class QLayout;
- friend class QWidgetItem;
- friend class QWidgetItemV2;
- friend class QGLContext;
- friend class QGLWidget;
- friend class QGLWindowSurface;
- friend class QX11PaintEngine;
- friend class QWin32PaintEngine;
- friend class QShortcutPrivate;
- friend class QShortcutMap;
- friend class QWindowSurface;
- friend class QGraphicsProxyWidget;
- friend class QGraphicsProxyWidgetPrivate;
- friend class QStyleSheetStyle;
- friend struct QWidgetExceptionCleaner;
- friend class QWidgetWindow;
-#ifndef QT_NO_GESTURES
- friend class QGestureManager;
- friend class QWinNativePanGestureRecognizer;
-#endif // QT_NO_GESTURES
- friend class QWidgetEffectSourcePrivate;
-
-#ifdef Q_WS_MAC
- friend class QCoreGraphicsPaintEnginePrivate;
- friend QPoint qt_mac_posInWindow(const QWidget *w);
- friend OSWindowRef qt_mac_window_for(const QWidget *w);
- friend bool qt_mac_is_metal(const QWidget *w);
- friend OSViewRef qt_mac_nativeview_for(const QWidget *w);
- friend void qt_event_request_window_change(QWidget *widget);
- friend bool qt_mac_sendMacEventToWidget(QWidget *widget, EventRef ref);
- friend class QRasterWindowSurface;
- friend class QUnifiedToolbarSurface;
-#endif
-#ifdef Q_WS_QWS
- friend class QWSBackingStore;
- friend class QWSManager;
- friend class QWSManagerPrivate;
- friend class QDecoration;
- friend class QWSWindowSurface;
- friend class QScreen;
- friend class QVNCScreen;
- friend bool isWidgetOpaque(const QWidget *);
- friend class QGLWidgetPrivate;
-#endif
-#ifdef Q_OS_SYMBIAN
- friend class QSymbianControl;
- friend class QS60WindowSurface;
-#endif
-#ifdef Q_WS_X11
- friend void qt_net_update_user_time(QWidget *tlw, unsigned long timestamp);
- friend void qt_net_remove_user_time(QWidget *tlw);
- friend void qt_set_winid_on_widget(QWidget*, Qt::HANDLE);
-#endif
-
- friend Q_GUI_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget);
- friend Q_GUI_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget);
-
-private:
- Q_DISABLE_COPY(QWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_showIfNotHidden())
-#ifdef Q_OS_SYMBIAN
- Q_PRIVATE_SLOT(d_func(), void _q_delayedDestroy(WId winId))
-#endif
-
- QWidgetData *data;
-
-#ifdef QT3_SUPPORT
-public:
- inline QT3_SUPPORT bool isUpdatesEnabled() const { return updatesEnabled(); }
- QT3_SUPPORT QStyle *setStyle(const QString&);
- inline QT3_SUPPORT bool isVisibleToTLW() const;
- QT3_SUPPORT QRect visibleRect() const;
- inline QT3_SUPPORT void iconify() { showMinimized(); }
- inline QT3_SUPPORT void constPolish() const { ensurePolished(); }
- inline QT3_SUPPORT void polish() { ensurePolished(); }
- inline QT3_SUPPORT void reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt=false)
- { setParent(parent, f); setGeometry(p.x(),p.y(),width(),height()); if (showIt) show(); }
- inline QT3_SUPPORT void reparent(QWidget *parent, const QPoint &p, bool showIt=false)
- { setParent(parent, windowFlags() & ~Qt::WindowType_Mask); setGeometry(p.x(),p.y(),width(),height()); if (showIt) show(); }
- inline QT3_SUPPORT void recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt=false)
- { setParent(parent, f); setGeometry(p.x(),p.y(),width(),height()); if (showIt) show(); }
- inline QT3_SUPPORT void setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
- { QSizePolicy sp(hor, ver); sp.setHeightForWidth(hfw); setSizePolicy(sp);}
- inline QT3_SUPPORT bool hasMouse() const { return testAttribute(Qt::WA_UnderMouse); }
-#ifndef QT_NO_CURSOR
- inline QT3_SUPPORT bool ownCursor() const { return testAttribute(Qt::WA_SetCursor); }
-#endif
- inline QT3_SUPPORT bool ownFont() const { return testAttribute(Qt::WA_SetFont); }
- inline QT3_SUPPORT void unsetFont() { setFont(QFont()); }
- inline QT3_SUPPORT bool ownPalette() const { return testAttribute(Qt::WA_SetPalette); }
- inline QT3_SUPPORT void unsetPalette() { setPalette(QPalette()); }
- Qt::BackgroundMode QT3_SUPPORT backgroundMode() const;
- void QT3_SUPPORT setBackgroundMode(Qt::BackgroundMode, Qt::BackgroundMode = Qt::PaletteBackground);
- const QT3_SUPPORT QColor &eraseColor() const;
- void QT3_SUPPORT setEraseColor(const QColor &);
- const QT3_SUPPORT QColor &foregroundColor() const;
- const QT3_SUPPORT QPixmap *erasePixmap() const;
- void QT3_SUPPORT setErasePixmap(const QPixmap &);
- const QT3_SUPPORT QColor &paletteForegroundColor() const;
- void QT3_SUPPORT setPaletteForegroundColor(const QColor &);
- const QT3_SUPPORT QColor &paletteBackgroundColor() const;
- void QT3_SUPPORT setPaletteBackgroundColor(const QColor &);
- const QT3_SUPPORT QPixmap *paletteBackgroundPixmap() const;
- void QT3_SUPPORT setPaletteBackgroundPixmap(const QPixmap &);
- const QT3_SUPPORT QBrush& backgroundBrush() const;
- const QT3_SUPPORT QColor &backgroundColor() const;
- const QT3_SUPPORT QPixmap *backgroundPixmap() const;
- void QT3_SUPPORT setBackgroundPixmap(const QPixmap &);
- QT3_SUPPORT void setBackgroundColor(const QColor &);
- QT3_SUPPORT QWidget *parentWidget(bool sameWindow) const;
- inline QT3_SUPPORT void setKeyCompression(bool b) { setAttribute(Qt::WA_KeyCompression, b); }
- inline QT3_SUPPORT void setFont(const QFont &f, bool) { setFont(f); }
- inline QT3_SUPPORT void setPalette(const QPalette &p, bool) { setPalette(p); }
- enum BackgroundOrigin { WidgetOrigin, ParentOrigin, WindowOrigin, AncestorOrigin };
- inline QT3_SUPPORT void setBackgroundOrigin(BackgroundOrigin) {}
- inline QT3_SUPPORT BackgroundOrigin backgroundOrigin() const { return WindowOrigin; }
- inline QT3_SUPPORT QPoint backgroundOffset() const { return QPoint(); }
- inline QT3_SUPPORT void repaint(bool) { repaint(); }
- inline QT3_SUPPORT void repaint(int x, int y, int w, int h, bool) { repaint(x,y,w,h); }
- inline QT3_SUPPORT void repaint(const QRect &r, bool) { repaint(r); }
- inline QT3_SUPPORT void repaint(const QRegion &rgn, bool) { repaint(rgn); }
- QT3_SUPPORT void erase();
- inline QT3_SUPPORT void erase(int x, int y, int w, int h) { erase_helper(x, y, w, h); }
- QT3_SUPPORT void erase(const QRect &);
- QT3_SUPPORT void erase(const QRegion &);
- QT3_SUPPORT void drawText(const QPoint &p, const QString &s)
- { drawText_helper(p.x(), p.y(), s); }
- inline QT3_SUPPORT void drawText(int x, int y, const QString &s)
- { drawText_helper(x, y, s); }
- QT3_SUPPORT bool close(bool);
- inline QT3_SUPPORT QWidget *childAt(int x, int y, bool includeThis) const
- {
- QWidget *w = childAt(x, y);
- return w ? w : ((includeThis && rect().contains(x,y))?const_cast<QWidget*>(this):0);
- }
- inline QT3_SUPPORT QWidget *childAt(const QPoint &p, bool includeThis) const
- {
- QWidget *w = childAt(p);
- return w ? w : ((includeThis && rect().contains(p))?const_cast<QWidget*>(this):0);
- }
- inline QT3_SUPPORT void setCaption(const QString &c) { setWindowTitle(c); }
- QT3_SUPPORT void setIcon(const QPixmap &i);
- inline QT3_SUPPORT void setIconText(const QString &it) { setWindowIconText(it); }
- inline QT3_SUPPORT QString caption() const { return windowTitle(); }
- QT3_SUPPORT const QPixmap *icon() const;
- inline QT3_SUPPORT QString iconText() const { return windowIconText(); }
- inline QT3_SUPPORT void setInputMethodEnabled(bool b) { setAttribute(Qt::WA_InputMethodEnabled, b); }
- inline QT3_SUPPORT bool isInputMethodEnabled() const { return testAttribute(Qt::WA_InputMethodEnabled); }
- inline QT3_SUPPORT void setActiveWindow() { activateWindow(); }
- inline QT3_SUPPORT bool isShown() const { return !isHidden(); }
- inline QT3_SUPPORT bool isDialog() const { return windowType() == Qt::Dialog; }
- inline QT3_SUPPORT bool isPopup() const { return windowType() == Qt::Popup; }
- inline QT3_SUPPORT bool isDesktop() const { return windowType() == Qt::Desktop; }
-
-
-private:
- void drawText_helper(int x, int y, const QString &);
- void erase_helper(int x, int y, int w, int h);
-#endif // QT3_SUPPORT
-
-protected:
- virtual void styleChange(QStyle&); // compat
- virtual void enabledChange(bool); // compat
- virtual void paletteChange(const QPalette &); // compat
- virtual void fontChange(const QFont &); // compat
- virtual void windowActivationChange(bool); // compat
- virtual void languageChange(); // compat
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QWidget::RenderFlags)
-
-template <> inline QWidget *qobject_cast<QWidget*>(QObject *o)
-{
- if (!o || !o->isWidgetType()) return 0;
- return static_cast<QWidget*>(o);
-}
-template <> inline const QWidget *qobject_cast<const QWidget*>(const QObject *o)
-{
- if (!o || !o->isWidgetType()) return 0;
- return static_cast<const QWidget*>(o);
-}
-
-inline QWidget *QWidget::childAt(int ax, int ay) const
-{ return childAt(QPoint(ax, ay)); }
-
-inline Qt::WindowType QWidget::windowType() const
-{ return static_cast<Qt::WindowType>(int(data->window_flags & Qt::WindowType_Mask)); }
-inline Qt::WindowFlags QWidget::windowFlags() const
-{ return data->window_flags; }
-
-inline bool QWidget::isTopLevel() const
-{ return (windowType() & Qt::Window); }
-
-inline bool QWidget::isWindow() const
-{ return (windowType() & Qt::Window); }
-
-inline bool QWidget::isEnabled() const
-{ return !testAttribute(Qt::WA_Disabled); }
-
-inline bool QWidget::isModal() const
-{ return data->window_modality != Qt::NonModal; }
-
-inline bool QWidget::isEnabledToTLW() const
-{ return isEnabled(); }
-
-inline int QWidget::minimumWidth() const
-{ return minimumSize().width(); }
-
-inline int QWidget::minimumHeight() const
-{ return minimumSize().height(); }
-
-inline int QWidget::maximumWidth() const
-{ return maximumSize().width(); }
-
-inline int QWidget::maximumHeight() const
-{ return maximumSize().height(); }
-
-inline void QWidget::setMinimumSize(const QSize &s)
-{ setMinimumSize(s.width(),s.height()); }
-
-inline void QWidget::setMaximumSize(const QSize &s)
-{ setMaximumSize(s.width(),s.height()); }
-
-inline void QWidget::setSizeIncrement(const QSize &s)
-{ setSizeIncrement(s.width(),s.height()); }
-
-inline void QWidget::setBaseSize(const QSize &s)
-{ setBaseSize(s.width(),s.height()); }
-
-inline const QFont &QWidget::font() const
-{ return data->fnt; }
-
-inline QFontMetrics QWidget::fontMetrics() const
-{ return QFontMetrics(data->fnt); }
-
-inline QFontInfo QWidget::fontInfo() const
-{ return QFontInfo(data->fnt); }
-
-inline void QWidget::setMouseTracking(bool enable)
-{ setAttribute(Qt::WA_MouseTracking, enable); }
-
-inline bool QWidget::hasMouseTracking() const
-{ return testAttribute(Qt::WA_MouseTracking); }
-
-inline bool QWidget::underMouse() const
-{ return testAttribute(Qt::WA_UnderMouse); }
-
-inline bool QWidget::updatesEnabled() const
-{ return !testAttribute(Qt::WA_UpdatesDisabled); }
-
-inline void QWidget::update(int ax, int ay, int aw, int ah)
-{ update(QRect(ax, ay, aw, ah)); }
-
-inline bool QWidget::isVisible() const
-{ return testAttribute(Qt::WA_WState_Visible); }
-
-inline bool QWidget::isHidden() const
-{ return testAttribute(Qt::WA_WState_Hidden); }
-
-inline void QWidget::move(int ax, int ay)
-{ move(QPoint(ax, ay)); }
-
-inline void QWidget::resize(int w, int h)
-{ resize(QSize(w, h)); }
-
-inline void QWidget::setGeometry(int ax, int ay, int aw, int ah)
-{ setGeometry(QRect(ax, ay, aw, ah)); }
-
-inline QRect QWidget::rect() const
-{ return QRect(0,0,data->crect.width(),data->crect.height()); }
-
-inline const QRect &QWidget::geometry() const
-{ return data->crect; }
-
-inline QSize QWidget::size() const
-{ return data->crect.size(); }
-
-inline int QWidget::width() const
-{ return data->crect.width(); }
-
-inline int QWidget::height() const
-{ return data->crect.height(); }
-
-inline QWidget *QWidget::parentWidget() const
-{ return static_cast<QWidget *>(QObject::parent()); }
-
-inline void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver)
-{ setSizePolicy(QSizePolicy(hor, ver)); }
-
-inline bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
-{
- if (attribute < int(8*sizeof(uint)))
- return data->widget_attributes & (1<<attribute);
- return testAttribute_helper(attribute);
-}
-
-#ifdef QT3_SUPPORT
-inline bool QWidget::isVisibleToTLW() const
-{ return isVisible(); }
-inline QWidget *QWidget::parentWidget(bool sameWindow) const
-{
- if (sameWindow && isWindow())
- return 0;
- return static_cast<QWidget *>(QObject::parent());
-}
-inline void QWidget::setPaletteForegroundColor(const QColor &c)
-{ QPalette p = palette(); p.setColor(foregroundRole(), c); setPalette(p); }
-inline const QBrush& QWidget::backgroundBrush() const { return palette().brush(backgroundRole()); }
-inline void QWidget::setBackgroundPixmap(const QPixmap &pm)
-{ QPalette p = palette(); p.setBrush(backgroundRole(), QBrush(pm)); setPalette(p); }
-inline const QPixmap *QWidget::backgroundPixmap() const { return 0; }
-inline void QWidget::setBackgroundColor(const QColor &c)
-{ QPalette p = palette(); p.setColor(backgroundRole(), c); setPalette(p); }
-inline const QColor & QWidget::backgroundColor() const { return palette().color(backgroundRole()); }
-inline const QColor &QWidget::foregroundColor() const { return palette().color(foregroundRole());}
-inline const QColor &QWidget::eraseColor() const { return palette().color(backgroundRole()); }
-inline void QWidget::setEraseColor(const QColor &c)
-{ QPalette p = palette(); p.setColor(backgroundRole(), c); setPalette(p); }
-inline const QPixmap *QWidget::erasePixmap() const { return 0; }
-inline void QWidget::setErasePixmap(const QPixmap &pm)
-{ QPalette p = palette(); p.setBrush(backgroundRole(), QBrush(pm)); setPalette(p); }
-inline const QColor &QWidget::paletteForegroundColor() const { return palette().color(foregroundRole());}
-inline const QColor &QWidget::paletteBackgroundColor() const { return palette().color(backgroundRole()); }
-inline void QWidget::setPaletteBackgroundColor(const QColor &c)
-{ QPalette p = palette(); p.setColor(backgroundRole(), c); setPalette(p); }
-inline const QPixmap *QWidget::paletteBackgroundPixmap() const
-{ return 0; }
-inline void QWidget::setPaletteBackgroundPixmap(const QPixmap &pm)
-{ QPalette p = palette(); p.setBrush(backgroundRole(), QBrush(pm)); setPalette(p); }
-inline QT3_SUPPORT void QWidget::erase() { erase_helper(0, 0, data->crect.width(), data->crect.height()); }
-inline QT3_SUPPORT void QWidget::erase(const QRect &r) { erase_helper(r.x(), r.y(), r.width(), r.height()); }
-#endif
-
-#define QWIDGETSIZE_MAX ((1<<24)-1)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWIDGET_H
diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h
deleted file mode 100644
index 7826cab795..0000000000
--- a/src/gui/kernel/qwidget_p.h
+++ /dev/null
@@ -1,1034 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGET_P_H
-#define QWIDGET_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qwidget.h"
-#include "private/qobject_p.h"
-#include "QtCore/qrect.h"
-#include "QtCore/qlocale.h"
-#include "QtCore/qset.h"
-#include "QtGui/qregion.h"
-#include "QtGui/qsizepolicy.h"
-#include "QtGui/qstyle.h"
-#include "QtGui/qapplication.h"
-#include <private/qgraphicseffect_p.h>
-#include "QtGui/qgraphicsproxywidget.h"
-#include "QtGui/qgraphicsscene.h"
-#include "QtGui/qgraphicsview.h"
-#include <private/qgesture_p.h>
-
-#ifdef Q_WS_WIN
-#include "QtCore/qt_windows.h"
-#include <private/qdnd_p.h>
-#endif // Q_WS_WIN
-
-#ifdef Q_WS_X11
-#include "QtGui/qx11info_x11.h"
-#endif
-
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#endif
-
-#if defined(Q_WS_QWS)
-#include "QtGui/qinputcontext.h"
-#include "QtGui/qscreen_qws.h"
-#endif
-
-#if defined(Q_OS_SYMBIAN)
-class RDrawableWindow;
-class CCoeControl;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// Extra QWidget data
-// - to minimize memory usage for members that are seldom used.
-// - top-level widgets have extra extra data to reduce cost further
-#if defined(Q_WS_QWS)
-class QWSManager;
-#endif
-#if defined(Q_WS_MAC)
-class QCoreGraphicsPaintEnginePrivate;
-#endif
-#if defined(Q_WS_QPA)
-class QWidgetWindow;
-#endif
-class QPaintEngine;
-class QPixmap;
-class QWidgetBackingStore;
-class QGraphicsProxyWidget;
-class QWidgetItemV2;
-
-class QStyle;
-
-class QUnifiedToolbarSurface;
-
-class Q_AUTOTEST_EXPORT QWidgetBackingStoreTracker
-{
-
-public:
- QWidgetBackingStoreTracker();
- ~QWidgetBackingStoreTracker();
-
- void create(QWidget *tlw);
- void destroy();
-
- void registerWidget(QWidget *w);
- void unregisterWidget(QWidget *w);
- void unregisterWidgetSubtree(QWidget *w);
-
- inline QWidgetBackingStore* data()
- {
- return m_ptr;
- }
-
- inline QWidgetBackingStore* operator->()
- {
- return m_ptr;
- }
-
- inline QWidgetBackingStore& operator*()
- {
- return *m_ptr;
- }
-
- inline operator bool() const
- {
- return (0 != m_ptr);
- }
-
-private:
- Q_DISABLE_COPY(QWidgetBackingStoreTracker)
-
-private:
- QWidgetBackingStore* m_ptr;
- QSet<QWidget *> m_widgets;
-};
-
-struct QTLWExtra {
- // *************************** Cross-platform variables *****************************
-
- // Regular pointers (keep them together to avoid gaps on 64 bits architectures).
- QIcon *icon; // widget icon
- QPixmap *iconPixmap;
- QWidgetBackingStoreTracker backingStore;
- QWindowSurface *windowSurface;
- QPainter *sharedPainter;
-
- // Implicit pointers (shared_null).
- QString caption; // widget caption
- QString iconText; // widget icon text
- QString role; // widget role
- QString filePath; // widget file path
-
- // Other variables.
- short incw, inch; // size increments
- short basew, baseh; // base sizes
- // frame strut, don't use these directly, use QWidgetPrivate::frameStrut() instead.
- QRect frameStrut;
- QRect normalGeometry; // used by showMin/maximized/FullScreen
- Qt::WindowFlags savedFlags; // Save widget flags while showing fullscreen
-
- // *************************** Cross-platform bit fields ****************************
- uint opacity : 8;
- uint posFromMove : 1;
- uint sizeAdjusted : 1;
- uint inTopLevelResize : 1;
- uint inRepaint : 1;
- uint embedded : 1;
-
- // *************************** Platform specific values (bit fields first) **********
-#if defined(Q_WS_X11) // <----------------------------------------------------------- X11
- uint spont_unmapped: 1; // window was spontaneously unmapped
- uint dnd : 1; // DND properties installed
- uint validWMState : 1; // is WM_STATE valid?
- uint waitingForMapNotify : 1; // show() has been called, haven't got the MapNotify yet
- WId parentWinId; // parent window Id (valid after reparenting)
- WId userTimeWindow; // window id that contains user-time timestamp when WM supports a _NET_WM_USER_TIME_WINDOW atom
- QPoint fullScreenOffset;
-#ifndef QT_NO_XSYNC
- WId syncUpdateCounter;
- ulong syncRequestTimestamp;
- qint32 newCounterValueHi;
- quint32 newCounterValueLo;
-#endif
-#elif defined(Q_WS_WIN) // <--------------------------------------------------------- WIN
- uint hotkeyRegistered: 1; // Hot key from the STARTUPINFO has been registered.
- HICON winIconBig; // internal big Windows icon
- HICON winIconSmall; // internal small Windows icon
-#elif defined(Q_WS_MAC) // <--------------------------------------------------------- MAC
- uint resizer : 4;
- uint isSetGeometry : 1;
- uint isMove : 1;
- quint32 wattr;
- quint32 wclass;
- WindowGroupRef group;
- IconRef windowIcon; // the current window icon, if set with setWindowIcon_sys.
- quint32 savedWindowAttributesFromMaximized; // Saved attributes from when the calling updateMaximizeButton_sys()
-#ifdef QT_MAC_USE_COCOA
- // This value is just to make sure we maximize and restore to the right location, yet we allow apps to be maximized and
- // manually resized.
- // The name is misleading, since this is set when maximizing the window. It is a hint to saveGeometry(..) to record the
- // starting position as 0,0 instead of the normal starting position.
- bool wasMaximized;
-#endif // QT_MAC_USE_COCOA
-
-#elif defined(Q_WS_QWS) // <--------------------------------------------------------- QWS
-#ifndef QT_NO_QWS_MANAGER
- QWSManager *qwsManager;
-#endif
-#elif defined(Q_OS_SYMBIAN)
- uint inExpose : 1; // Prevents drawing recursion
- uint nativeWindowTransparencyEnabled : 1; // Tracks native window transparency
-#elif defined(Q_WS_QPA)
- QWidgetWindow *window;
- quint32 screenIndex; // index in qplatformscreenlist
-#endif
-};
-
-struct QWExtra {
- // *************************** Cross-platform variables *****************************
-
- // Regular pointers (keep them together to avoid gaps on 64 bits architectures).
- void *glContext; // if the widget is hijacked by QGLWindowSurface
- QTLWExtra *topextra; // only useful for TLWs
-#ifndef QT_NO_GRAPHICSVIEW
- QGraphicsProxyWidget *proxyWidget; // if the widget is embedded
-#endif
-#ifndef QT_NO_CURSOR
- QCursor *curs;
-#endif
- QPointer<QStyle> style;
- QPointer<QWidget> focus_proxy;
-
- // Implicit pointers (shared_empty/shared_null).
- QRegion mask; // widget mask
- QString styleSheet;
-
- // Other variables.
- qint32 minw;
- qint32 minh; // minimum size
- qint32 maxw;
- qint32 maxh; // maximum size
- quint16 customDpiX;
- quint16 customDpiY;
- QSize staticContentsSize;
-
- // *************************** Cross-platform bit fields ****************************
- uint explicitMinSize : 2;
- uint explicitMaxSize : 2;
- uint autoFillBackground : 1;
- uint nativeChildrenForced : 1;
- uint inRenderWithPainter : 1;
- uint hasMask : 1;
-
- // *************************** Platform specific values (bit fields first) **********
-#if defined(Q_WS_WIN) // <----------------------------------------------------------- WIN
-#ifndef QT_NO_DRAGANDDROP
- QOleDropTarget *dropTarget; // drop target
- QList<QPointer<QWidget> > oleDropWidgets;
-#endif
-#elif defined(Q_WS_X11) // <--------------------------------------------------------- X11
- uint compress_events : 1;
- WId xDndProxy; // XDND forwarding to embedded windows
-#elif defined(Q_WS_MAC) // <------------------------------------------------------ MAC
-#ifdef QT_MAC_USE_COCOA
- // Cocoa Mask stuff
- QImage maskBits;
- CGImageRef imageMask;
-#endif
-#elif defined(Q_OS_SYMBIAN) // <----------------------------------------------------- Symbian
- uint activated : 1; // RWindowBase::Activated has been called
-
- /**
- * If this bit is set, each native widget receives the signals from the
- * Symbian control immediately before and immediately after draw ops are
- * sent to the window server for this control:
- * void beginNativePaintEvent(const QRect &paintRect);
- * void endNativePaintEvent(const QRect &paintRect);
- */
- uint receiveNativePaintEvents : 1;
-
- /**
- * Defines the behaviour of QSymbianControl::Draw.
- */
- enum NativePaintMode {
- /**
- * Normal drawing mode: blits the required region of the backing store
- * via WSERV.
- */
- Blit,
-
- /**
- * Disable drawing for this widget.
- */
- Disable,
-
- /**
- * Paint zeros into the WSERV framebuffer, using BitGDI APIs. For windows
- * with an EColor16MU display mode, zero is written only into the R, G and B
- * channels of the pixel.
- */
- ZeroFill,
-
- /**
- * Blit backing store, propagating alpha channel into the framebuffer.
- */
- BlitWriteAlpha,
-
- Default = Blit
- };
-
- NativePaintMode nativePaintMode;
-
-#endif
-};
-
-/*!
- \internal
-
- Returns true if \a p or any of its parents enable the
- Qt::BypassGraphicsProxyWidget window flag. Used in QWidget::show() and
- QWidget::setParent() to determine whether it's necessary to embed the
- widget into a QGraphicsProxyWidget or not.
-*/
-static inline bool bypassGraphicsProxyWidget(const QWidget *p)
-{
- while (p) {
- if (p->windowFlags() & Qt::BypassGraphicsProxyWidget)
- return true;
- p = p->parentWidget();
- }
- return false;
-}
-
-class Q_GUI_EXPORT QWidgetPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QWidget)
-
-public:
- // *************************** Cross-platform ***************************************
- enum DrawWidgetFlags {
- DrawAsRoot = 0x01,
- DrawPaintOnScreen = 0x02,
- DrawRecursive = 0x04,
- DrawInvisible = 0x08,
- DontSubtractOpaqueChildren = 0x10,
- DontSetCompositionMode = 0x20,
- DontDrawOpaqueChildren = 0x40,
- DontDrawNativeChildren = 0x80
- };
-
- enum CloseMode {
- CloseNoEvent,
- CloseWithEvent,
- CloseWithSpontaneousEvent
- };
-
- enum Direction {
- DirectionNorth = 0x01,
- DirectionEast = 0x10,
- DirectionSouth = 0x02,
- DirectionWest = 0x20
- };
-
- // Functions.
- explicit QWidgetPrivate(int version = QObjectPrivateVersion);
- ~QWidgetPrivate();
-
- QWExtra *extraData() const;
- QTLWExtra *topData() const;
- QTLWExtra *maybeTopData() const;
- QPainter *sharedPainter() const;
- void setSharedPainter(QPainter *painter);
- QWidgetBackingStore *maybeBackingStore() const;
- void init(QWidget *desktopWidget, Qt::WindowFlags f);
- void create_sys(WId window, bool initializeWindow, bool destroyOldWindow);
- void createRecursively();
- void createWinId(WId id = 0);
-
- void createTLExtra();
- void createExtra();
- void deleteExtra();
- void createSysExtra();
- void deleteSysExtra();
- void createTLSysExtra();
- void deleteTLSysExtra();
- void updateSystemBackground();
- void propagatePaletteChange();
-
- void setPalette_helper(const QPalette &);
- void resolvePalette();
- QPalette naturalWidgetPalette(uint inheritedMask) const;
-
- void setMask_sys(const QRegion &);
-#ifdef Q_OS_SYMBIAN
- void setSoftKeys_sys(const QList<QAction*> &softkeys);
- void activateSymbianWindow(WId wid = 0);
- void _q_delayedDestroy(WId winId);
-#endif
-
- void raise_sys();
- void lower_sys();
- void stackUnder_sys(QWidget *);
-
- void setFocus_sys();
-
- void updateFont(const QFont &);
- inline void setFont_helper(const QFont &font) {
- if (data.fnt == font && data.fnt.resolve() == font.resolve())
- return;
- updateFont(font);
- }
- void resolveFont();
- QFont naturalWidgetFont(uint inheritedMask) const;
-
- void setLayoutDirection_helper(Qt::LayoutDirection);
- void resolveLayoutDirection();
-
- void setLocale_helper(const QLocale &l, bool forceUpdate = false);
- void resolveLocale();
-
- void setStyle_helper(QStyle *newStyle, bool propagate, bool metalHack = false);
- void inheritStyle();
-
- void setUpdatesEnabled_helper(bool );
-
- void paintBackground(QPainter *, const QRegion &, int flags = DrawAsRoot) const;
- bool isAboutToShow() const;
- QRegion prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags);
- void render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &sourceRegion,
- QWidget::RenderFlags renderFlags);
- void render(QPaintDevice *target, const QPoint &targetOffset, const QRegion &sourceRegion,
- QWidget::RenderFlags renderFlags, bool readyToRender);
- void drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
- QPainter *sharedPainter = 0, QWidgetBackingStore *backingStore = 0);
-
-
- void paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& children, int index,
- const QRegion &rgn, const QPoint &offset, int flags
-#ifdef Q_BACKINGSTORE_SUBSURFACES
- , const QWindowSurface *currentSurface
-#endif
- , QPainter *sharedPainter, QWidgetBackingStore *backingStore);
-
-
- QPainter *beginSharedPainter();
- bool endSharedPainter();
-#ifndef QT_NO_GRAPHICSVIEW
- static QGraphicsProxyWidget * nearestGraphicsProxyWidget(const QWidget *origin);
-#endif
- QWindowSurface *createDefaultWindowSurface();
- QWindowSurface *createDefaultWindowSurface_sys();
- void repaint_sys(const QRegion &rgn);
-
- QRect clipRect() const;
- QRegion clipRegion() const;
- void subtractOpaqueChildren(QRegion &rgn, const QRect &clipRect) const;
- void subtractOpaqueSiblings(QRegion &source, bool *hasDirtySiblingsAbove = 0,
- bool alsoNonOpaque = false) const;
- void clipToEffectiveMask(QRegion &region) const;
- void updateIsOpaque();
- void setOpaque(bool opaque);
- void updateIsTranslucent();
- bool paintOnScreen() const;
-#ifndef QT_NO_GRAPHICSEFFECT
- void invalidateGraphicsEffectsRecursively();
-#endif //QT_NO_GRAPHICSEFFECT
-
- const QRegion &getOpaqueChildren() const;
- void setDirtyOpaqueRegion();
-
- bool close_helper(CloseMode mode);
-
- void setWindowIcon_helper();
- void setWindowIcon_sys(bool forceReset = false);
- void setWindowOpacity_sys(qreal opacity);
- void adjustQuitOnCloseAttribute();
-
- void scrollChildren(int dx, int dy);
- void moveRect(const QRect &, int dx, int dy);
- void scrollRect(const QRect &, int dx, int dy);
- void invalidateBuffer_resizeHelper(const QPoint &oldPos, const QSize &oldSize);
- // ### Qt 4.6: Merge into a template function (after MSVC isn't supported anymore).
- void invalidateBuffer(const QRegion &);
- void invalidateBuffer(const QRect &);
- bool isOverlapped(const QRect&) const;
- void syncBackingStore();
- void syncBackingStore(const QRegion &region);
-
- void reparentFocusWidgets(QWidget *oldtlw);
-
- static int pointToRect(const QPoint &p, const QRect &r);
-
- void setWinId(WId);
- void showChildren(bool spontaneous);
- void hideChildren(bool spontaneous);
- void setParent_sys(QWidget *parent, Qt::WindowFlags);
- void scroll_sys(int dx, int dy);
- void scroll_sys(int dx, int dy, const QRect &r);
- void deactivateWidgetCleanup();
- void setGeometry_sys(int, int, int, int, bool);
- void sendPendingMoveAndResizeEvents(bool recursive = false, bool disableUpdates = false);
- void activateChildLayoutsRecursively();
- void show_recursive();
- void show_helper();
- void show_sys();
- void hide_sys();
- void hide_helper();
- void _q_showIfNotHidden();
-
- void setEnabled_helper(bool);
- void registerDropSite(bool);
- static void adjustFlags(Qt::WindowFlags &flags, QWidget *w = 0);
-
- void updateFrameStrut();
- QRect frameStrut() const;
-
-#ifdef QT_KEYPAD_NAVIGATION
- static bool navigateToDirection(Direction direction);
- static QWidget *widgetInNavigationDirection(Direction direction);
- static bool canKeypadNavigate(Qt::Orientation orientation);
- static bool inTabWidget(QWidget *widget);
-#endif
-
- void setWindowIconText_sys(const QString &cap);
- void setWindowIconText_helper(const QString &cap);
- void setWindowTitle_sys(const QString &cap);
-
-#ifndef QT_NO_CURSOR
- void setCursor_sys(const QCursor &cursor);
- void unsetCursor_sys();
-#endif
-
- void setWindowTitle_helper(const QString &cap);
- void setWindowFilePath_helper(const QString &filePath);
-
- bool setMinimumSize_helper(int &minw, int &minh);
- bool setMaximumSize_helper(int &maxw, int &maxh);
- virtual bool hasHeightForWidth() const;
- void setConstraints_sys();
- bool pointInsideRectAndMask(const QPoint &) const;
- QWidget *childAt_helper(const QPoint &, bool) const;
- QWidget *childAtRecursiveHelper(const QPoint &p, bool, bool includeFrame = false) const;
- void updateGeometry_helper(bool forceUpdate);
-
- void getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const;
- void setLayoutItemMargins(int left, int top, int right, int bottom);
- void setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt = 0);
-
- // aboutToDestroy() is called just before the contents of
- // QWidget::destroy() is executed. It's used to signal QWidget
- // sub-classes that their internals are about to be released.
- virtual void aboutToDestroy() {}
-
- QInputContext *assignedInputContext() const;
- QInputContext *inputContext() const;
- inline QWidget *effectiveFocusWidget() {
- QWidget *w = q_func();
- while (w->focusProxy())
- w = w->focusProxy();
- return w;
- }
-
- void setModal_sys();
-
- // This is an helper function that return the available geometry for
- // a widget and takes care is this one is in QGraphicsView.
- // If the widget is not embed in a scene then the geometry available is
- // null, we let QDesktopWidget decide for us.
- static QRect screenGeometry(const QWidget *widget)
- {
- QRect screen;
-#ifndef QT_NO_GRAPHICSVIEW
- QGraphicsProxyWidget *ancestorProxy = widget->d_func()->nearestGraphicsProxyWidget(widget);
- //It's embedded if it has an ancestor
- if (ancestorProxy) {
- if (!bypassGraphicsProxyWidget(widget) && ancestorProxy->scene() != 0) {
- // One view, let be smart and return the viewport rect then the popup is aligned
- if (ancestorProxy->scene()->views().size() == 1) {
- QGraphicsView *view = ancestorProxy->scene()->views().at(0);
- screen = view->mapToScene(view->viewport()->rect()).boundingRect().toRect();
- } else {
- screen = ancestorProxy->scene()->sceneRect().toRect();
- }
- }
- }
-#endif
- return screen;
- }
-
- inline void setRedirected(QPaintDevice *replacement, const QPoint &offset)
- {
- Q_ASSERT(q_func()->testAttribute(Qt::WA_WState_InPaintEvent));
- redirectDev = replacement;
- redirectOffset = offset;
- }
-
- inline QPaintDevice *redirected(QPoint *offset) const
- {
- if (offset)
- *offset = redirectDev ? redirectOffset : QPoint();
- return redirectDev;
- }
-
- inline void restoreRedirected()
- { redirectDev = 0; }
-
- inline void enforceNativeChildren()
- {
- if (!extra)
- createExtra();
-
- if (extra->nativeChildrenForced)
- return;
- extra->nativeChildrenForced = 1;
-
- for (int i = 0; i < children.size(); ++i) {
- if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
- child->setAttribute(Qt::WA_NativeWindow);
- }
- }
-
- inline bool nativeChildrenForced() const
- {
- return extra ? extra->nativeChildrenForced : false;
- }
-
- inline QRect effectiveRectFor(const QRect &rect) const
- {
-#ifndef QT_NO_GRAPHICSEFFECT
- if (graphicsEffect && graphicsEffect->isEnabled())
- return graphicsEffect->boundingRectFor(rect).toAlignedRect();
-#endif //QT_NO_GRAPHICSEFFECT
- return rect;
- }
-
- QSize adjustedSize() const;
-
- inline void handleSoftwareInputPanel(Qt::MouseButton button, bool clickCausedFocus)
- {
- Q_Q(QWidget);
- if (button == Qt::LeftButton && qApp->autoSipEnabled()) {
- QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel(
- q->style()->styleHint(QStyle::SH_RequestSoftwareInputPanel));
- if (!clickCausedFocus || behavior == QStyle::RSIP_OnMouseClick) {
- QEvent event(QEvent::RequestSoftwareInputPanel);
- QApplication::sendEvent(q, &event);
- }
- }
- }
-
-#ifndef Q_WS_QWS // Almost cross-platform :-)
- void setWSGeometry(bool dontShow=false, const QRect &oldRect = QRect());
-
- inline QPoint mapToWS(const QPoint &p) const
- { return p - data.wrect.topLeft(); }
-
- inline QPoint mapFromWS(const QPoint &p) const
- { return p + data.wrect.topLeft(); }
-
- inline QRect mapToWS(const QRect &r) const
- { QRect rr(r); rr.translate(-data.wrect.topLeft()); return rr; }
-
- inline QRect mapFromWS(const QRect &r) const
- { QRect rr(r); rr.translate(data.wrect.topLeft()); return rr; }
-#endif
-
- // Variables.
- // Regular pointers (keep them together to avoid gaps on 64 bit architectures).
- QWExtra *extra;
- QWidget *focus_next;
- QWidget *focus_prev;
- QWidget *focus_child;
- QLayout *layout;
- QRegion *needsFlush;
- QPaintDevice *redirectDev;
- QWidgetItemV2 *widgetItem;
- QPaintEngine *extraPaintEngine;
- mutable const QMetaObject *polished;
- QGraphicsEffect *graphicsEffect;
- // All widgets are added into the allWidgets set. Once
- // they receive a window id they are also added to the mapper.
- // This should just ensure that all widgets are deleted by QApplication
- static QWidgetMapper *mapper;
- static QWidgetSet *allWidgets;
-#if !defined(QT_NO_IM)
- QPointer<QInputContext> ic;
- Qt::InputMethodHints imHints;
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- static QPointer<QWidget> editingWidget;
-#endif
-
- // Implicit pointers (shared_null/shared_empty).
- QRegion opaqueChildren;
- QRegion dirty;
-#ifndef QT_NO_TOOLTIP
- QString toolTip;
-#endif
-#ifndef QT_NO_STATUSTIP
- QString statusTip;
-#endif
-#ifndef QT_NO_WHATSTHIS
- QString whatsThis;
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- QString accessibleName;
- QString accessibleDescription;
-#endif
-
- // Other variables.
- uint inheritedFontResolveMask;
- uint inheritedPaletteResolveMask;
- short leftmargin;
- short topmargin;
- short rightmargin;
- short bottommargin;
- signed char leftLayoutItemMargin;
- signed char topLayoutItemMargin;
- signed char rightLayoutItemMargin;
- signed char bottomLayoutItemMargin;
- static int instanceCounter; // Current number of widget instances
- static int maxInstances; // Maximum number of widget instances
- Qt::HANDLE hd;
- QWidgetData data;
- QSizePolicy size_policy;
- QLocale locale;
- QPoint redirectOffset;
-#ifndef QT_NO_ACTION
- QList<QAction*> actions;
-#endif
-#ifndef QT_NO_GESTURES
- QMap<Qt::GestureType, Qt::GestureFlags> gestureContext;
-#endif
-
- // Bit fields.
- uint high_attributes[4]; // the low ones are in QWidget::widget_attributes
- QPalette::ColorRole fg_role : 8;
- QPalette::ColorRole bg_role : 8;
- uint dirtyOpaqueChildren : 1;
- uint isOpaque : 1;
- uint inDirtyList : 1;
- uint isScrolled : 1;
- uint isMoved : 1;
- uint isGLWidget : 1;
- uint usesDoubleBufferedGLContext : 1;
-#ifndef QT_NO_IM
- uint inheritsInputMethodHints : 1;
-#endif
-
- // *************************** Platform specific ************************************
-#if defined(Q_WS_X11) // <----------------------------------------------------------- X11
- QX11Info xinfo;
- Qt::HANDLE picture;
- static QWidget *mouseGrabber;
- static QWidget *keyboardGrabber;
-
- void setWindowRole();
- void sendStartupMessage(const char *message) const;
- void setNetWmWindowTypes();
- void x11UpdateIsOpaque();
- bool isBackgroundInherited() const;
- void updateX11AcceptFocus();
- QPoint mapToGlobal(const QPoint &pos) const;
- QPoint mapFromGlobal(const QPoint &pos) const;
-#elif defined(Q_WS_WIN) // <--------------------------------------------------------- WIN
- uint noPaintOnScreen : 1; // see qwidget_win.cpp ::paintEngine()
-#ifndef QT_NO_GESTURES
- uint nativeGesturePanEnabled : 1;
-#endif
- bool shouldShowMaximizeButton();
- void winUpdateIsOpaque();
- void reparentChildren();
-#ifndef QT_NO_DRAGANDDROP
- QOleDropTarget *registerOleDnd(QWidget *widget);
- void unregisterOleDnd(QWidget *widget, QOleDropTarget *target);
-#endif
- void grabMouseWhileInWindow();
- void registerTouchWindow();
- void winSetupGestures();
-#elif defined(Q_WS_MAC) // <--------------------------------------------------------- MAC
- // This is new stuff
- uint needWindowChange : 1;
-
- // Each wiget keeps a list of all its child and grandchild OpenGL widgets.
- // This list is used to update the gl context whenever a parent and a granparent
- // moves, and also to check for intersections with gl widgets within the window
- // when a widget moves.
- struct GlWidgetInfo
- {
- GlWidgetInfo(QWidget *widget) : widget(widget), lastUpdateWidget(0) { }
- bool operator==(const GlWidgetInfo &other) const { return (widget == other.widget); }
- QWidget * widget;
- QWidget * lastUpdateWidget;
- };
-
- // dirtyOnWidget contains the areas in the widget that needs to be repained,
- // in the same way as dirtyOnScreen does for the window. Areas are added in
- // dirtyWidget_sys and cleared in the paint event. In scroll_sys we then use
- // this information repaint invalid areas when widgets are scrolled.
- QRegion dirtyOnWidget;
- EventHandlerRef window_event;
- QList<GlWidgetInfo> glWidgets;
-
- //these are here just for code compat (HIViews)
- Qt::HANDLE qd_hd;
-
- void macUpdateSizeAttribute();
- void macUpdateHideOnSuspend();
- void macUpdateOpaqueSizeGrip();
- void macUpdateIgnoreMouseEvents();
- void macUpdateMetalAttribute();
- void macUpdateIsOpaque();
- void macSetNeedsDisplay(QRegion region);
- void setEnabled_helper_sys(bool enable);
- bool isRealWindow() const;
- void adjustWithinMaxAndMinSize(int &w, int &h);
- void applyMaxAndMinSizeOnWindow();
- void update_sys(const QRect &rect);
- void update_sys(const QRegion &rgn);
- void setGeometry_sys_helper(int, int, int, int, bool);
- void setWindowModified_sys(bool b);
- void updateMaximizeButton_sys();
- void setWindowFilePath_sys(const QString &filePath);
- void createWindow_sys();
- void recreateMacWindow();
-#ifndef QT_MAC_USE_COCOA
- void initWindowPtr();
- void finishCreateWindow_sys_Carbon(OSWindowRef windowRef);
-#else
- void setSubWindowStacking(bool set);
- void setWindowLevel();
- void finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ windowRef);
- void syncCocoaMask();
- void finishCocoaMaskSetup();
- void syncUnifiedMode();
- // Did we add the drawRectOriginal method?
- bool drawRectOriginalAdded;
- // Is the original drawRect method available?
- bool originalDrawMethod;
- // Do we need to change the methods?
- bool changeMethods;
-
- // Unified toolbar variables
- bool isInUnifiedToolbar;
- QUnifiedToolbarSurface *unifiedSurface;
- QPoint toolbar_offset;
- QWidget *toolbar_ancestor;
- bool flushRequested;
- bool touchEventsEnabled;
-#endif // QT_MAC_USE_COCOA
- void determineWindowClass();
- void transferChildren();
- bool qt_mac_dnd_event(uint, DragRef);
- void toggleDrawers(bool);
- //mac event functions
- static bool qt_create_root_win();
- static void qt_clean_root_win();
- static bool qt_mac_update_sizer(QWidget *, int up = 0);
- static OSStatus qt_window_event(EventHandlerCallRef er, EventRef event, void *);
- static OSStatus qt_widget_event(EventHandlerCallRef er, EventRef event, void *);
- static bool qt_widget_rgn(QWidget *, short, RgnHandle, bool);
- void registerTouchWindow(bool enable = true);
-#elif defined(Q_WS_QWS) // <--------------------------------------------------------- QWS
- void setMaxWindowState_helper();
- void setFullScreenSize_helper();
- void moveSurface(QWindowSurface *surface, const QPoint &offset);
- QRegion localRequestedRegion() const;
- QRegion localAllocatedRegion() const;
-
- friend class QWSManager;
- friend class QWSManagerPrivate;
- friend class QDecoration;
-#ifndef QT_NO_CURSOR
- void updateCursor() const;
-#endif
- QScreen* getScreen() const;
-#elif defined(Q_WS_QPA) // <--------------------------------------------------------- QPA
- void setMaxWindowState_helper();
- void setFullScreenSize_helper();
-#ifndef QT_NO_CURSOR
- void updateCursor() const;
-#endif
-#elif defined(Q_OS_SYMBIAN) // <--------------------------------------------------------- SYMBIAN
- static QWidget *mouseGrabber;
- static QWidget *keyboardGrabber;
- int symbianScreenNumber; // only valid for desktop widget and top-levels
- bool fixNativeOrientationCalled;
- void s60UpdateIsOpaque();
- void reparentChildren();
- void registerTouchWindow();
-#endif
-
-};
-
-struct QWidgetPaintContext
-{
- inline QWidgetPaintContext(QPaintDevice *d, const QRegion &r, const QPoint &o, int f,
- QPainter *p, QWidgetBackingStore *b)
- : pdev(d), rgn(r), offset(o), flags(f), sharedPainter(p), backingStore(b), painter(0) {}
-
- QPaintDevice *pdev;
- QRegion rgn;
- QPoint offset;
- int flags;
- QPainter *sharedPainter;
- QWidgetBackingStore *backingStore;
- QPainter *painter;
-};
-
-#ifndef QT_NO_GRAPHICSEFFECT
-class QWidgetEffectSourcePrivate : public QGraphicsEffectSourcePrivate
-{
-public:
- QWidgetEffectSourcePrivate(QWidget *widget)
- : QGraphicsEffectSourcePrivate(), m_widget(widget), context(0), updateDueToGraphicsEffect(false)
- {}
-
- inline void detach()
- { m_widget->d_func()->graphicsEffect = 0; }
-
- inline const QGraphicsItem *graphicsItem() const
- { return 0; }
-
- inline const QWidget *widget() const
- { return m_widget; }
-
- inline void update()
- {
- updateDueToGraphicsEffect = true;
- m_widget->update();
- updateDueToGraphicsEffect = false;
- }
-
- inline bool isPixmap() const
- { return false; }
-
- inline void effectBoundingRectChanged()
- {
- // ### This function should take a rect parameter; then we can avoid
- // updating too much on the parent widget.
- if (QWidget *parent = m_widget->parentWidget())
- parent->update();
- else
- update();
- }
-
- inline const QStyleOption *styleOption() const
- { return 0; }
-
- inline QRect deviceRect() const
- { return m_widget->window()->rect(); }
-
- QRectF boundingRect(Qt::CoordinateSystem system) const;
- void draw(QPainter *p);
- QPixmap pixmap(Qt::CoordinateSystem system, QPoint *offset,
- QGraphicsEffect::PixmapPadMode mode) const;
-
- QWidget *m_widget;
- QWidgetPaintContext *context;
- QTransform lastEffectTransform;
- bool updateDueToGraphicsEffect;
-};
-#endif //QT_NO_GRAPHICSEFFECT
-
-inline QWExtra *QWidgetPrivate::extraData() const
-{
- return extra;
-}
-
-inline QTLWExtra *QWidgetPrivate::topData() const
-{
- const_cast<QWidgetPrivate *>(this)->createTLExtra();
- return extra->topextra;
-}
-
-inline QTLWExtra *QWidgetPrivate::maybeTopData() const
-{
- return extra ? extra->topextra : 0;
-}
-
-inline QPainter *QWidgetPrivate::sharedPainter() const
-{
- Q_Q(const QWidget);
- QTLWExtra *x = q->window()->d_func()->maybeTopData();
- return x ? x->sharedPainter : 0;
-}
-
-inline void QWidgetPrivate::setSharedPainter(QPainter *painter)
-{
- Q_Q(QWidget);
- QTLWExtra *x = q->window()->d_func()->topData();
- x->sharedPainter = painter;
-}
-
-inline bool QWidgetPrivate::pointInsideRectAndMask(const QPoint &p) const
-{
- Q_Q(const QWidget);
- return q->rect().contains(p) && (!extra || !extra->hasMask || q->testAttribute(Qt::WA_MouseNoMask)
- || extra->mask.contains(p));
-}
-
-inline QWidgetBackingStore *QWidgetPrivate::maybeBackingStore() const
-{
- Q_Q(const QWidget);
- QTLWExtra *x = q->window()->d_func()->maybeTopData();
- return x ? x->backingStore.data() : 0;
-}
-
-QT_END_NAMESPACE
-
-#endif // QWIDGET_P_H
diff --git a/src/gui/kernel/qwidget_qpa.cpp b/src/gui/kernel/qwidget_qpa.cpp
deleted file mode 100644
index d239e6d652..0000000000
--- a/src/gui/kernel/qwidget_qpa.cpp
+++ /dev/null
@@ -1,824 +0,0 @@
-/****************************************************************************
-**
-** 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 "QtGui/qwidget.h"
-#include "QtGui/qevent.h"
-#include "QtGui/qapplication.h"
-#include "QtGui/private/qbackingstore_p.h"
-#include "QtGui/private/qwidget_p.h"
-#include "QtGui/private/qwidgetwindow_qpa_p.h"
-#include "QtGui/private/qapplication_p.h"
-#include "QtGui/qdesktopwidget.h"
-#include "QtGui/qplatformwindow_qpa.h"
-#include "QtGui/qplatformglcontext_qpa.h"
-
-#include <QtGui/QPlatformCursor>
-
-QT_BEGIN_NAMESPACE
-
-void q_createNativeChildrenAndSetParent(QWindow *parentWindow, const QWidget *parentWidget)
-{
- QObjectList children = parentWidget->children();
- for (int i = 0; i < children.size(); i++) {
- if (children.at(i)->isWidgetType()) {
- const QWidget *childWidget = qobject_cast<const QWidget *>(children.at(i));
- if (childWidget) { // should not be necessary
- if (childWidget->testAttribute(Qt::WA_NativeWindow)) {
- if (!childWidget->windowHandle())
- childWidget->winId();
- if (childWidget->windowHandle())
- childWidget->windowHandle()->setParent(parentWindow);
- } else {
- q_createNativeChildrenAndSetParent(parentWindow,childWidget);
- }
- }
- }
- }
-
-}
-
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
-{
- Q_Q(QWidget);
-
- Q_UNUSED(window);
- Q_UNUSED(initializeWindow);
- Q_UNUSED(destroyOldWindow);
-
- Qt::WindowFlags flags = data.window_flags;
-
- if ((!q->testAttribute(Qt::WA_NativeWindow) && !q->isWindow()) || q->windowType() == Qt::Desktop )
- return; // we only care about real toplevels
-
- QWindowSurface *surface = q->windowSurface();
-
- QWindow *win = topData()->window;
-
- if (!q->isWindow()) {
- if (QWidget *nativeParent = q->nativeParentWidget()) {
- if (nativeParent->windowHandle())
- win->setParent(nativeParent->windowHandle());
- }
- }
-
- win->setWindowFlags(data.window_flags);
- win->setGeometry(q->geometry());
- win->create();
-
- data.window_flags = win->windowFlags();
-
- if (!surface ) {
- if (win) {
- surface = QGuiApplicationPrivate::platformIntegration()->createWindowSurface(win, win->winId());
- q->setWindowSurface(surface);
- } else {
- q->setAttribute(Qt::WA_PaintOnScreen,true);
- }
- }
-
- setWinId(win->winId());
-
-// first check children. and create them if necessary
-// q_createNativeChildrenAndSetParent(q->windowHandle(),q);
-
- QGuiApplicationPrivate::platformIntegration()->moveToScreen(win, topData()->screenIndex);
-// qDebug() << "create_sys" << q << q->internalWinId();
-}
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
- Q_D(QWidget);
-
- if ((windowType() == Qt::Popup))
- qApp->d_func()->closePopup(this);
-
- //### we don't have proper focus event handling yet
- if (this == QApplicationPrivate::active_window)
- QApplication::setActiveWindow(0);
-
- if (windowType() != Qt::Desktop) {
- if (destroySubWindows) {
- QObjectList childList(children());
- for (int i = 0; i < childList.size(); i++) {
- QWidget *widget = qobject_cast<QWidget *>(childList.at(i));
- if (widget && widget->testAttribute(Qt::WA_NativeWindow)) {
- if (widget->windowHandle()) {
- widget->destroy();
- }
- }
- }
- }
- if (destroyWindow) {
- d->deleteTLSysExtra();
- } else {
- if (parentWidget() && parentWidget()->testAttribute(Qt::WA_WState_Created)) {
- d->hide_sys();
- }
- }
- }
-}
-
-void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
-{
- Q_Q(QWidget);
-
- Qt::WindowFlags oldFlags = data.window_flags;
-
- int targetScreen = -1;
- // Handle a request to move the widget to a particular screen
- if (newparent && newparent->windowType() == Qt::Desktop) {
- // make sure the widget is created on the same screen as the
- // programmer specified desktop widget
-
- // get the desktop's screen number
- targetScreen = newparent->window()->d_func()->topData()->screenIndex;
- newparent = 0;
- }
-
- if (parent != newparent) {
- QObjectPrivate::setParent_helper(newparent); //### why does this have to be done in the _sys function???
- if (q->windowHandle() && newparent) {
- QWidget * parentWithWindow = newparent->windowHandle()? newparent : newparent->nativeParentWidget();
- if (parentWithWindow && parentWithWindow->windowHandle()) {
- q->windowHandle()->setParent(parentWithWindow->windowHandle());
- }
- }
-
- }
-
- if (!newparent) {
- f |= Qt::Window;
- if (targetScreen == -1) {
- if (parent)
- targetScreen = q->parentWidget()->window()->d_func()->topData()->screenIndex;
- }
- }
-
- bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
-
- // Reparenting toplevel to child
- if (!(f&Qt::Window) && (oldFlags&Qt::Window) && !q->testAttribute(Qt::WA_NativeWindow)) {
- //qDebug() << "setParent_sys() change from toplevel";
- q->destroy();
- }
-
- data.window_flags = f;
- q->setAttribute(Qt::WA_WState_Created, false);
- q->setAttribute(Qt::WA_WState_Visible, false);
- q->setAttribute(Qt::WA_WState_Hidden, false);
-
- if (q->isWindow() || (!newparent || newparent->isVisible()) || explicitlyHidden)
- q->setAttribute(Qt::WA_WState_Hidden);
- q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
- // move the window to the selected screen
- if (!newparent && targetScreen != -1) {
- if (maybeTopData())
- maybeTopData()->screenIndex = targetScreen;
- // only if it is already created
- if (q->testAttribute(Qt::WA_WState_Created)) {
- QPlatformIntegration *platform = QGuiApplicationPrivate::platformIntegration();
- platform->moveToScreen(q->windowHandle(), targetScreen);
- }
- }
-}
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
- int x=pos.x(), y=pos.y();
- const QWidget* w = this;
- while (w) {
- x += w->data->crect.x();
- y += w->data->crect.y();
- w = w->isWindow() ? 0 : w->parentWidget();
- }
- return QPoint(x, y);
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
- int x=pos.x(), y=pos.y();
- const QWidget* w = this;
- while (w) {
- x -= w->data->crect.x();
- y -= w->data->crect.y();
- w = w->isWindow() ? 0 : w->parentWidget();
- }
- return QPoint(x, y);
-}
-
-void QWidgetPrivate::updateSystemBackground() {}
-
-#ifndef QT_NO_CURSOR
-void QWidgetPrivate::setCursor_sys(const QCursor &cursor)
-{
- Q_UNUSED(cursor);
- Q_Q(QWidget);
- if (q->isVisible())
- qt_qpa_set_cursor(q, false);
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
- Q_Q(QWidget);
- if (q->isVisible())
- qt_qpa_set_cursor(q, false);
-}
-
-void QWidgetPrivate::updateCursor() const
-{
- // XXX
-}
-
-#endif //QT_NO_CURSOR
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
- Q_Q(QWidget);
- if (!q->isWindow())
- return;
-
- if (QWindow *window = q->windowHandle())
- window->setWindowTitle(caption);
-
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool /*forceReset*/)
-{
-}
-
-void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
-{
- Q_UNUSED(iconText);
-}
-
-QWidget *qt_pressGrab = 0;
-QWidget *qt_mouseGrb = 0;
-static QWidget *keyboardGrb = 0;
-
-void QWidget::grabMouse()
-{
- if (qt_mouseGrb)
- qt_mouseGrb->releaseMouse();
-
- // XXX
- //qwsDisplay()->grabMouse(this,true);
-
- qt_mouseGrb = this;
- qt_pressGrab = 0;
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
- Q_UNUSED(cursor);
-
- if (qt_mouseGrb)
- qt_mouseGrb->releaseMouse();
-
- // XXX
- //qwsDisplay()->grabMouse(this,true);
- //qwsDisplay()->selectCursor(this, cursor.handle());
- qt_mouseGrb = this;
- qt_pressGrab = 0;
-}
-#endif
-
-void QWidget::releaseMouse()
-{
- if (qt_mouseGrb == this) {
- // XXX
- //qwsDisplay()->grabMouse(this,false);
- qt_mouseGrb = 0;
- }
-}
-
-void QWidget::grabKeyboard()
-{
- if (keyboardGrb)
- keyboardGrb->releaseKeyboard();
- // XXX
- //qwsDisplay()->grabKeyboard(this, true);
- keyboardGrb = this;
-}
-
-void QWidget::releaseKeyboard()
-{
- if (keyboardGrb == this) {
- // XXX
- //qwsDisplay()->grabKeyboard(this, false);
- keyboardGrb = 0;
- }
-}
-
-QWidget *QWidget::mouseGrabber()
-{
- if (qt_mouseGrb)
- return qt_mouseGrb;
- return qt_pressGrab;
-}
-
-QWidget *QWidget::keyboardGrabber()
-{
- return keyboardGrb;
-}
-
-void QWidget::activateWindow()
-{
- if (windowHandle())
- windowHandle()->requestActivateWindow();
-}
-
-void QWidgetPrivate::show_sys()
-{
- Q_Q(QWidget);
- q->setAttribute(Qt::WA_Mapped);
- if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
- invalidateBuffer(q->rect());
- return;
- }
-
- QApplication::postEvent(q, new QUpdateLaterEvent(q->rect()));
-
- if (!q->isWindow() && !q->testAttribute(Qt::WA_NativeWindow))
- return;
-
- QWindow *window = q->windowHandle();
- if (window) {
- QRect geomRect = q->geometry();
- if (!q->isWindow()) {
- QPoint topLeftOfWindow = q->mapTo(q->nativeParentWidget(),QPoint());
- geomRect.moveTopLeft(topLeftOfWindow);
- }
- const QRect windowRect = window->geometry();
- if (windowRect != geomRect) {
- window->setGeometry(geomRect);
- }
- if (QWindowSurface *surface = q->windowSurface()) {
- if (windowRect.size() != geomRect.size()) {
- surface->resize(geomRect.size());
- }
- }
- if (window)
- window->setVisible(true);
- }
-}
-
-
-void QWidgetPrivate::hide_sys()
-{
- Q_Q(QWidget);
- q->setAttribute(Qt::WA_Mapped, false);
- if (!q->isWindow()) {
- QWidget *p = q->parentWidget();
- if (p &&p->isVisible()) {
- invalidateBuffer(q->rect());
- }
- return;
- }
- if (QWindow *window = q->windowHandle()) {
- window->setVisible(false);
- }
-
- //### we don't yet have proper focus event handling
- if (q == QApplicationPrivate::active_window)
- QApplication::setActiveWindow(0);
-
-}
-
-void QWidgetPrivate::setMaxWindowState_helper()
-{
- setFullScreenSize_helper(); //### decoration size
-}
-
-void QWidgetPrivate::setFullScreenSize_helper()
-{
- Q_Q(QWidget);
-
- const uint old_state = data.in_set_window_state;
- data.in_set_window_state = 1;
-
- const QRect screen = qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(q));
- q->move(screen.topLeft());
- q->resize(screen.size());
-
- data.in_set_window_state = old_state;
-}
-
-static Qt::WindowStates effectiveState(Qt::WindowStates state)
- {
- if (state & Qt::WindowMinimized)
- return Qt::WindowMinimized;
- else if (state & Qt::WindowFullScreen)
- return Qt::WindowFullScreen;
- else if (state & Qt::WindowMaximized)
- return Qt::WindowMaximized;
- return Qt::WindowNoState;
- }
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
- Q_D(QWidget);
- Qt::WindowStates oldstate = windowState();
- if (oldstate == newstate)
- return;
- if (isWindow() && !testAttribute(Qt::WA_WState_Created))
- create();
-
- data->window_state = newstate;
- data->in_set_window_state = 1;
- bool needShow = false;
- Qt::WindowStates newEffectiveState = effectiveState(newstate);
- Qt::WindowStates oldEffectiveState = effectiveState(oldstate);
- if (isWindow() && newEffectiveState != oldEffectiveState) {
- d->createTLExtra();
- if (oldEffectiveState == Qt::WindowNoState) { //normal
- d->topData()->normalGeometry = geometry();
- } else if (oldEffectiveState == Qt::WindowFullScreen) {
- setParent(0, d->topData()->savedFlags);
- needShow = true;
- } else if (oldEffectiveState == Qt::WindowMinimized) {
- needShow = true;
- }
-
- if (newEffectiveState == Qt::WindowMinimized) {
- //### not ideal...
- hide();
- needShow = false;
- } else if (newEffectiveState == Qt::WindowFullScreen) {
- d->topData()->savedFlags = windowFlags();
- setParent(0, Qt::FramelessWindowHint | (windowFlags() & Qt::WindowStaysOnTopHint));
- d->setFullScreenSize_helper();
- raise();
- needShow = true;
- } else if (newEffectiveState == Qt::WindowMaximized) {
- createWinId();
- d->setMaxWindowState_helper();
- } else { //normal
- QRect r = d->topData()->normalGeometry;
- if (r.width() >= 0) {
- d->topData()->normalGeometry = QRect(0,0,-1,-1);
- setGeometry(r);
- }
- }
- }
- data->in_set_window_state = 0;
-
- if (needShow)
- show();
-
- if (newstate & Qt::WindowActive)
- activateWindow();
-
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
-}
-
-void QWidgetPrivate::setFocus_sys()
-{
-
-}
-
-void QWidgetPrivate::raise_sys()
-{
- Q_Q(QWidget);
- if (q->isWindow()) {
- q->windowHandle()->raise();
- }
-}
-
-void QWidgetPrivate::lower_sys()
-{
- Q_Q(QWidget);
- if (q->isWindow()) {
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- q->windowHandle()->lower();
- } else if (QWidget *p = q->parentWidget()) {
- setDirtyOpaqueRegion();
- p->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
- }
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget*)
-{
- Q_Q(QWidget);
- if (QWidget *p = q->parentWidget()) {
- setDirtyOpaqueRegion();
- p->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
- }
-}
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
- Q_Q(QWidget);
- if (extra) { // any size restrictions?
- w = qMin(w,extra->maxw);
- h = qMin(h,extra->maxh);
- w = qMax(w,extra->minw);
- h = qMax(h,extra->minh);
- }
-
- QPoint oldp = q->geometry().topLeft();
- QSize olds = q->size();
- QRect r(x, y, w, h);
-
- bool isResize = olds != r.size();
- isMove = oldp != r.topLeft(); //### why do we have isMove as a parameter?
-
-
- // We only care about stuff that changes the geometry, or may
- // cause the window manager to change its state
- if (r.size() == olds && oldp == r.topLeft())
- return;
-
- if (!data.in_set_window_state) {
- q->data->window_state &= ~Qt::WindowMaximized;
- q->data->window_state &= ~Qt::WindowFullScreen;
- if (q->isWindow())
- topData()->normalGeometry = QRect(0, 0, -1, -1);
- }
-
- QPoint oldPos = q->pos();
- data.crect = r;
-
- if (q->isVisible()) {
- if (q->windowHandle()) {
- if (q->isWindow()) {
- q->windowHandle()->setGeometry(q->geometry());
- } else {
- QPoint posInNativeParent = q->mapTo(q->nativeParentWidget(),QPoint());
- q->windowHandle()->setGeometry(QRect(posInNativeParent,r.size()));
- }
- const QWidgetBackingStore *bs = maybeBackingStore();
- if (bs->windowSurface) {
- if (isResize)
- bs->windowSurface->resize(r.size());
- }
- } else {
- if (isMove && !isResize)
- moveRect(QRect(oldPos, olds), x - oldPos.x(), y - oldPos.y());
- else
- invalidateBuffer_resizeHelper(oldPos, olds);
- }
-
- if (isMove) {
- QMoveEvent e(q->pos(), oldPos);
- QApplication::sendEvent(q, &e);
- }
- if (isResize) {
- QResizeEvent e(r.size(), olds);
- QApplication::sendEvent(q, &e);
- if (q->windowHandle())
- q->update();
- }
- } else { // not visible
- if (isMove && q->pos() != oldPos)
- q->setAttribute(Qt::WA_PendingMoveEvent, true);
- if (isResize)
- q->setAttribute(Qt::WA_PendingResizeEvent, true);
- }
-
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
- Q_Q(QWidget);
- scrollChildren(dx, dy);
- scrollRect(q->rect(), dx, dy);
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
-{
- scrollRect(r, dx, dy);
-}
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
- Q_D(const QWidget);
-
- QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(windowHandle());
- if (!screen) {
- if (m == PdmDpiX || m == PdmDpiY)
- return 72;
- return QPaintDevice::metric(m);
- }
- int val;
- if (m == PdmWidth) {
- val = data->crect.width();
- } else if (m == PdmWidthMM) {
- val = data->crect.width() * screen->physicalSize().width() / screen->geometry().width();
- } else if (m == PdmHeight) {
- val = data->crect.height();
- } else if (m == PdmHeightMM) {
- val = data->crect.height() * screen->physicalSize().height() / screen->geometry().height();
- } else if (m == PdmDepth) {
- return screen->depth();
- } else if (m == PdmDpiX || m == PdmPhysicalDpiX) {
- if (d->extra && d->extra->customDpiX)
- return d->extra->customDpiX;
- else if (d->parent)
- return static_cast<QWidget *>(d->parent)->metric(m);
- return qRound(screen->geometry().width() / double(screen->physicalSize().width() / 25.4));
- } else if (m == PdmDpiY || m == PdmPhysicalDpiY) {
- if (d->extra && d->extra->customDpiY)
- return d->extra->customDpiY;
- else if (d->parent)
- return static_cast<QWidget *>(d->parent)->metric(m);
- return qRound(screen->geometry().height() / double(screen->physicalSize().height() / 25.4));
- } else {
- val = QPaintDevice::metric(m);// XXX
- }
- return val;
-}
-
-/*!
- \preliminary
-
- Returns the QPlatformWindow this widget will be drawn into.
-*/
-QWindow *QWidget::windowHandle() const
-{
- Q_D(const QWidget);
- QTLWExtra *extra = d->maybeTopData();
- if (extra && extra->window)
- return extra->window;
-
- return 0;
-}
-
-void QWidgetPrivate::createSysExtra()
-{
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
-
-}
-
-void QWidgetPrivate::createTLSysExtra()
-{
- Q_Q(QWidget);
- extra->topextra->screenIndex = 0;
- extra->topextra->window = new QWidgetWindow(q);
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
- if (extra && extra->topextra) {
- //the toplevel might have a context with a "qglcontext associated with it. We need to
- //delete the qglcontext before we delete the qplatformglcontext.
- //One unfortunate thing about this is that we potentially create a glContext just to
- //delete it straight afterwards.
- if (extra->topextra->window) {
- extra->topextra->window->destroy();
- }
- setWinId(0);
- //hmmm. should we delete window..
- delete extra->topextra->window;
- extra->topextra->window = 0;
- }
-}
-
-void QWidgetPrivate::registerDropSite(bool on)
-{
- Q_UNUSED(on);
-}
-
-void QWidgetPrivate::setMask_sys(const QRegion &region)
-{
- Q_UNUSED(region);
- // XXX
-}
-
-void QWidgetPrivate::updateFrameStrut()
-{
- // XXX
-}
-
-void QWidgetPrivate::setWindowOpacity_sys(qreal level)
-{
- Q_Q(QWidget);
- q->windowHandle()->setOpacity(level);
-}
-
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect)
-{
- Q_UNUSED(dontShow);
- Q_UNUSED(oldRect);
- // XXX
-}
-
-QPaintEngine *QWidget::paintEngine() const
-{
- qWarning("QWidget::paintEngine: Should no longer be called");
- return 0; //##### @@@
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
- //This function should not be called.
- Q_ASSERT(false);
- return 0;
-}
-
-void QWidgetPrivate::setModal_sys()
-{
-}
-
-#ifndef QT_NO_CURSOR
-void qt_qpa_set_cursor(QWidget * w, bool force)
-{
- static QCursor arrowCursor(Qt::ArrowCursor);
- static QPointer<QWidget> lastUnderMouse = 0;
-
- QCursor * override = QApplication::overrideCursor();
-
- if (override && w != 0)
- return;
-
- QWidget *cursorWidget;
- QCursor cursorCursor;
-
- do {
- if (w == 0) {
- if (override) {
- cursorCursor = *override;
- cursorWidget = QApplication::topLevelAt(QCursor::pos());
- break;
- }
- w = QApplication::widgetAt(QCursor::pos());
- if (w == 0) // clear the override cursor while over empty space
- w = QApplication::desktop();
- } else if (force) {
- lastUnderMouse = w;
- } else if (w->testAttribute(Qt::WA_WState_Created) && lastUnderMouse
- && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
- w = lastUnderMouse;
- }
- if (w == QApplication::desktop() && !override) {
- cursorCursor = arrowCursor;
- cursorWidget = w;
- break;
- }
-
- QWidget * curWin = QApplication::activeWindow();
- if (!curWin && w && w->internalWinId())
- return;
- QWidget* cW = w && !w->internalWinId() ? w : curWin;
-
- if (!cW || cW->window() != w->window() ||
- !cW->isVisible() || !cW->underMouse() || override)
- return;
-
- cursorCursor = w->cursor();
- cursorWidget = w;
- } while (0);
- foreach (QWeakPointer<QPlatformCursor> cursor, QPlatformCursorPrivate::getInstances())
- if (cursor)
- cursor.data()->changeCursor(&cursorCursor, cursorWidget->windowHandle());
-}
-#endif //QT_NO_CURSOR
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qwidgetaction.cpp b/src/gui/kernel/qwidgetaction.cpp
deleted file mode 100644
index 29586da34b..0000000000
--- a/src/gui/kernel/qwidgetaction.cpp
+++ /dev/null
@@ -1,287 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwidgetaction.h"
-#include "qdebug.h"
-
-#ifndef QT_NO_ACTION
-#include "qwidgetaction_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QWidgetAction
- \since 4.2
- \brief The QWidgetAction class extends QAction by an interface
- for inserting custom widgets into action based containers, such
- as toolbars.
-
- \ingroup mainwindow-classes
-
- Most actions in an application are represented as items in menus or
- buttons in toolbars. However sometimes more complex widgets are
- necessary. For example a zoom action in a word processor may be
- realized using a QComboBox in a QToolBar, presenting a range
- of different zoom levels. QToolBar provides QToolBar::insertWidget()
- as convenience function for inserting a single widget.
- However if you want to implement an action that uses custom
- widgets for visualization in multiple containers then you have to
- subclass QWidgetAction.
-
- If a QWidgetAction is added for example to a QToolBar then
- QWidgetAction::createWidget() is called. Reimplementations of that
- function should create a new custom widget with the specified parent.
-
- If the action is removed from a container widget then
- QWidgetAction::deleteWidget() is called with the previously created custom
- widget as argument. The default implementation hides the widget and deletes
- it using QObject::deleteLater().
-
- If you have only one single custom widget then you can set it as default
- widget using setDefaultWidget(). That widget will then be used if the
- action is added to a QToolBar, or in general to an action container that
- supports QWidgetAction. If a QWidgetAction with only a default widget is
- added to two toolbars at the same time then the default widget is shown
- only in the first toolbar the action was added to. QWidgetAction takes
- over ownership of the default widget.
-
- Note that it is up to the widget to activate the action, for example by
- reimplementing mouse event handlers and calling QAction::trigger().
-
- \bold {Mac OS X}: If you add a widget to a menu in the application's menu
- bar on Mac OS X, the widget will be added and it will function but with some
- limitations:
- \list 1
- \o The widget is reparented away from the QMenu to the native menu
- view. If you show the menu in some other place (e.g. as a popup menu),
- the widget will not be there.
- \o Focus/Keyboard handling of the widget is not possible.
- \o Due to Apple's design, mouse tracking on the widget currently does
- not work.
- \o Connecting the triggered() signal to a slot that opens a modal
- dialog will cause a crash in Mac OS X 10.4 (known bug acknowledged
- by Apple), a workaround is to use a QueuedConnection instead of a
- DirectConnection.
- \endlist
-
- \sa QAction, QActionGroup, QWidget
-*/
-
-/*!
- Constructs an action with \a parent.
-*/
-QWidgetAction::QWidgetAction(QObject *parent)
- : QAction(*(new QWidgetActionPrivate), parent)
-{
-}
-
-/*!
- Destroys the object and frees allocated resources.
-*/
-QWidgetAction::~QWidgetAction()
-{
- Q_D(QWidgetAction);
- for (int i = 0; i < d->createdWidgets.count(); ++i)
- disconnect(d->createdWidgets.at(i), SIGNAL(destroyed(QObject*)),
- this, SLOT(_q_widgetDestroyed(QObject*)));
- QList<QWidget *> widgetsToDelete = d->createdWidgets;
- d->createdWidgets.clear();
- qDeleteAll(widgetsToDelete);
- delete d->defaultWidget;
-}
-
-/*!
- Sets \a widget to be the default widget. The ownership is
- transferred to QWidgetAction. Unless createWidget() is
- reimplemented by a subclass to return a new widget the default
- widget is used when a container widget requests a widget through
- requestWidget().
-*/
-void QWidgetAction::setDefaultWidget(QWidget *widget)
-{
- Q_D(QWidgetAction);
- if (widget == d->defaultWidget || d->defaultWidgetInUse)
- return;
- delete d->defaultWidget;
- d->defaultWidget = widget;
- if (!widget)
- return;
-
- setVisible(!(widget->isHidden() && widget->testAttribute(Qt::WA_WState_ExplicitShowHide)));
- d->defaultWidget->hide();
- d->defaultWidget->setParent(0);
- d->defaultWidgetInUse = false;
- if (!isEnabled())
- d->defaultWidget->setEnabled(false);
-}
-
-/*!
- Returns the default widget.
-*/
-QWidget *QWidgetAction::defaultWidget() const
-{
- Q_D(const QWidgetAction);
- return d->defaultWidget;
-}
-
-/*!
- Returns a widget that represents the action, with the given \a
- parent.
-
- Container widgets that support actions can call this function to
- request a widget as visual representation of the action.
-
- \sa releaseWidget(), createWidget(), defaultWidget()
-*/
-QWidget *QWidgetAction::requestWidget(QWidget *parent)
-{
- Q_D(QWidgetAction);
-
- QWidget *w = createWidget(parent);
- if (!w) {
- if (d->defaultWidgetInUse || !d->defaultWidget)
- return 0;
- d->defaultWidget->setParent(parent);
- d->defaultWidgetInUse = true;
- return d->defaultWidget;
- }
-
- connect(w, SIGNAL(destroyed(QObject*)),
- this, SLOT(_q_widgetDestroyed(QObject*)));
- d->createdWidgets.append(w);
- return w;
-}
-
-/*!
- Releases the specified \a widget.
-
- Container widgets that support actions call this function when a widget
- action is removed.
-
- \sa requestWidget(), deleteWidget(), defaultWidget()
-*/
-void QWidgetAction::releaseWidget(QWidget *widget)
-{
- Q_D(QWidgetAction);
-
- if (widget == d->defaultWidget) {
- d->defaultWidget->hide();
- d->defaultWidget->setParent(0);
- d->defaultWidgetInUse = false;
- return;
- }
-
- if (!d->createdWidgets.contains(widget))
- return;
-
- disconnect(widget, SIGNAL(destroyed(QObject*)),
- this, SLOT(_q_widgetDestroyed(QObject*)));
- d->createdWidgets.removeAll(widget);
- deleteWidget(widget);
-}
-
-/*!
- \reimp
-*/
-bool QWidgetAction::event(QEvent *event)
-{
- Q_D(QWidgetAction);
- if (event->type() == QEvent::ActionChanged) {
- if (d->defaultWidget)
- d->defaultWidget->setEnabled(isEnabled());
- for (int i = 0; i < d->createdWidgets.count(); ++i)
- d->createdWidgets.at(i)->setEnabled(isEnabled());
- }
- return QAction::event(event);
-}
-
-/*!
- \reimp
- */
-bool QWidgetAction::eventFilter(QObject *obj, QEvent *event)
-{
- return QAction::eventFilter(obj,event);
-}
-
-/*!
- This function is called whenever the action is added to a container widget
- that supports custom widgets. If you don't want a custom widget to be
- used as representation of the action in the specified \a parent widget then
- 0 should be returned.
-
- \sa deleteWidget()
-*/
-QWidget *QWidgetAction::createWidget(QWidget *parent)
-{
- Q_UNUSED(parent)
- return 0;
-}
-
-/*!
- This function is called whenever the action is removed from a
- container widget that displays the action using a custom \a
- widget previously created using createWidget(). The default
- implementation hides the \a widget and schedules it for deletion
- using QObject::deleteLater().
-
- \sa createWidget()
-*/
-void QWidgetAction::deleteWidget(QWidget *widget)
-{
- widget->hide();
- widget->deleteLater();
-}
-
-/*!
- Returns the list of widgets that have been using createWidget() and
- are currently in use by widgets the action has been added to.
-*/
-QList<QWidget *> QWidgetAction::createdWidgets() const
-{
- Q_D(const QWidgetAction);
- return d->createdWidgets;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qwidgetaction.cpp"
-
-#endif // QT_NO_ACTION
diff --git a/src/gui/kernel/qwidgetaction.h b/src/gui/kernel/qwidgetaction.h
deleted file mode 100644
index a32b5d60dd..0000000000
--- a/src/gui/kernel/qwidgetaction.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGETACTION_H
-#define QWIDGETACTION_H
-
-#include <QtGui/qaction.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_ACTION
-
-class QWidgetActionPrivate;
-
-class Q_GUI_EXPORT QWidgetAction : public QAction
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QWidgetAction)
-
-public:
- explicit QWidgetAction(QObject *parent);
- virtual ~QWidgetAction();
-
- void setDefaultWidget(QWidget *w);
- QWidget *defaultWidget() const;
-
- QWidget *requestWidget(QWidget *parent);
- void releaseWidget(QWidget *widget);
-
-protected:
- virtual bool event(QEvent *);
- virtual bool eventFilter(QObject *, QEvent *);
- virtual QWidget *createWidget(QWidget *parent);
- virtual void deleteWidget(QWidget *widget);
- QList<QWidget *> createdWidgets() const;
-
-private:
- Q_DISABLE_COPY(QWidgetAction)
- Q_PRIVATE_SLOT(d_func(), void _q_widgetDestroyed(QObject *))
- friend class QToolBar;
-};
-
-#endif // QT_NO_ACTION
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWIDGETACTION_H
diff --git a/src/gui/kernel/qwidgetaction_p.h b/src/gui/kernel/qwidgetaction_p.h
deleted file mode 100644
index e4f59a04d2..0000000000
--- a/src/gui/kernel/qwidgetaction_p.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGETACTION_P_H
-#define QWIDGETACTION_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qaction_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QWidgetActionPrivate : public QActionPrivate
-{
- Q_DECLARE_PUBLIC(QWidgetAction)
-public:
- inline QWidgetActionPrivate() : defaultWidgetInUse(false), autoCreated(false) {}
- QPointer<QWidget> defaultWidget;
- QList<QWidget *> createdWidgets;
- uint defaultWidgetInUse : 1;
- uint autoCreated : 1; // created by QToolBar::addWidget and the like
-
- inline void _q_widgetDestroyed(QObject *o) {
- createdWidgets.removeAll(static_cast<QWidget *>(o));
- }
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/kernel/qwidgetwindow_qpa.cpp b/src/gui/kernel/qwidgetwindow_qpa.cpp
deleted file mode 100644
index d1ef77d48c..0000000000
--- a/src/gui/kernel/qwidgetwindow_qpa.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwidgetwindow_qpa_p.h"
-
-#include "private/qwidget_p.h"
-#include "private/qapplication_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QWidget *qt_button_down = 0; // widget got last button-down
-
-QWidgetWindow::QWidgetWindow(QWidget *widget)
- : m_widget(widget)
-{
-}
-
-bool QWidgetWindow::event(QEvent *event)
-{
- switch (event->type()) {
- case QEvent::Close:
- handleCloseEvent(static_cast<QCloseEvent *>(event));
- return true;
-
- case QEvent::Enter:
- case QEvent::Leave:
- handleEnterLeaveEvent(event);
- return true;
-
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- handleKeyEvent(static_cast<QKeyEvent *>(event));
- return true;
-
- case QEvent::MouseMove:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- handleMouseEvent(static_cast<QMouseEvent *>(event));
- return true;
-
- case QEvent::Move:
- handleMoveEvent(static_cast<QMoveEvent *>(event));
- return true;
-
- case QEvent::Resize:
- handleResizeEvent(static_cast<QResizeEvent *>(event));
- return true;
-
- case QEvent::Wheel:
- handleWheelEvent(static_cast<QWheelEvent *>(event));
- return true;
-
- default:
- break;
- }
-
- return m_widget->event(event) || QWindow::event(event);
-}
-
-QPointer<QWidget> qt_last_mouse_receiver = 0;
-
-void QWidgetWindow::handleEnterLeaveEvent(QEvent *event)
-{
- if (event->type() == QEvent::Leave) {
- QApplicationPrivate::dispatchEnterLeave(0, m_widget);
- qt_last_mouse_receiver = 0;
- } else {
- QApplicationPrivate::dispatchEnterLeave(m_widget, 0);
- qt_last_mouse_receiver = m_widget;
- }
-}
-
-void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
-{
- // which child should have it?
- QWidget *widget = m_implicit_mouse_grabber ? m_implicit_mouse_grabber.data() : m_widget->childAt(event->pos());
-
- if (qApp->d_func()->inPopupMode()) {
- widget = qApp->activePopupWidget();
- m_implicit_mouse_grabber.clear();
- }
-
- if (!widget)
- widget = m_widget;
-
- if (event->type() == QEvent::MouseButtonPress && !m_implicit_mouse_grabber)
- m_implicit_mouse_grabber = widget;
-
- if (event->buttons() == Qt::NoButton)
- m_implicit_mouse_grabber.clear();
-
- QPoint mapped = widget->mapFrom(m_widget, event->pos());
-
- if (widget != qt_last_mouse_receiver) {
- QApplicationPrivate::dispatchEnterLeave(widget, qt_last_mouse_receiver);
- qt_last_mouse_receiver = widget;
- }
-
- QMouseEvent translated(event->type(), mapped, event->globalPos(), event->button(), event->buttons(), event->modifiers());
- QGuiApplication::sendSpontaneousEvent(widget, &translated);
-
- if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::RightButton) {
- QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
- QGuiApplication::sendSpontaneousEvent(widget, &e);
- }
-}
-
-void QWidgetWindow::handleKeyEvent(QKeyEvent *event)
-{
- QWidget *widget = m_widget->focusWidget();
-
- if (!widget)
- widget = m_widget;
-
- QGuiApplication::sendSpontaneousEvent(widget, event);
-}
-
-void QWidgetWindow::handleMoveEvent(QMoveEvent *event)
-{
- m_widget->data->crect = geometry();
- QGuiApplication::sendSpontaneousEvent(m_widget, event);
-}
-
-void QWidgetWindow::handleResizeEvent(QResizeEvent *event)
-{
- m_widget->data->crect = geometry();
- QGuiApplication::sendSpontaneousEvent(m_widget, event);
-}
-
-void QWidgetWindow::handleCloseEvent(QCloseEvent *)
-{
- m_widget->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-}
-
-void QWidgetWindow::handleWheelEvent(QWheelEvent *event)
-{
- // which child should have it?
- QWidget *widget = m_widget->childAt(event->pos());
-
- if (!widget)
- widget = m_widget;
-
- QPoint mapped = widget->mapFrom(m_widget, event->pos());
-
- QWheelEvent translated(mapped, event->globalPos(), event->delta(), event->buttons(), event->modifiers(), event->orientation());
- QGuiApplication::sendSpontaneousEvent(widget, &translated);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qwidgetwindow_qpa_p.h b/src/gui/kernel/qwidgetwindow_qpa_p.h
deleted file mode 100644
index 9eb1e4f60e..0000000000
--- a/src/gui/kernel/qwidgetwindow_qpa_p.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGETWINDOW_QPA_P_H
-#define QWIDGETWINDOW_QPA_P_H
-
-#include <QtGui/qwindow.h>
-
-#include <QtCore/private/qobject_p.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QWidgetWindow : public QWindow
-{
- Q_OBJECT
-public:
- QWidgetWindow(QWidget *widget);
-
- QWidget *widget() const { return m_widget; }
-
-protected:
- bool event(QEvent *);
-
- void handleCloseEvent(QCloseEvent *);
- void handleEnterLeaveEvent(QEvent *);
- void handleKeyEvent(QKeyEvent *);
- void handleMouseEvent(QMouseEvent *);
- void handleMoveEvent(QMoveEvent *);
- void handleResizeEvent(QResizeEvent *);
- void handleWheelEvent(QWheelEvent *);
-
-private:
- QWidget *m_widget;
- QWeakPointer<QWidget> m_implicit_mouse_grabber;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWIDGETWINDOW_QPA_P_H
diff --git a/src/gui/kernel/symbian.pri b/src/gui/kernel/symbian.pri
deleted file mode 100644
index 69422dd02e..0000000000
--- a/src/gui/kernel/symbian.pri
+++ /dev/null
@@ -1,7 +0,0 @@
-symbian {
- contains(QT_CONFIG, s60): LIBS+= $$QMAKE_LIBS_S60
- RESOURCES += symbian/symbianresources.qrc
-
- HEADERS += symbian/qsymbianevent.h
- SOURCES += symbian/qsymbianevent.cpp
-}
diff --git a/src/gui/kernel/win.pri b/src/gui/kernel/win.pri
deleted file mode 100644
index 5ecf4dd94a..0000000000
--- a/src/gui/kernel/win.pri
+++ /dev/null
@@ -1,4 +0,0 @@
-# Qt/Windows only configuration file
-# --------------------------------------------------------------------
-
- INCLUDEPATH += ../3rdparty/wintab
diff --git a/src/gui/kernel/x11.pri b/src/gui/kernel/x11.pri
deleted file mode 100644
index 82de1b68af..0000000000
--- a/src/gui/kernel/x11.pri
+++ /dev/null
@@ -1,4 +0,0 @@
-x11 {
- contains(QT_CONFIG, nas): LIBS_PRIVATE += -laudio -lXt
-}
-
diff --git a/src/gui/mac/images/copyarrowcursor.png b/src/gui/mac/images/copyarrowcursor.png
deleted file mode 100644
index 13dfca95bc..0000000000
--- a/src/gui/mac/images/copyarrowcursor.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/mac/images/forbiddencursor.png b/src/gui/mac/images/forbiddencursor.png
deleted file mode 100644
index a9f21b4a5e..0000000000
--- a/src/gui/mac/images/forbiddencursor.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/mac/images/leopard-unified-toolbar-on.png b/src/gui/mac/images/leopard-unified-toolbar-on.png
deleted file mode 100644
index 6716597046..0000000000
--- a/src/gui/mac/images/leopard-unified-toolbar-on.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/mac/images/pluscursor.png b/src/gui/mac/images/pluscursor.png
deleted file mode 100644
index c583c088c9..0000000000
--- a/src/gui/mac/images/pluscursor.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/mac/images/spincursor.png b/src/gui/mac/images/spincursor.png
deleted file mode 100644
index ca44ab50fd..0000000000
--- a/src/gui/mac/images/spincursor.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/mac/images/waitcursor.png b/src/gui/mac/images/waitcursor.png
deleted file mode 100644
index a9abe61320..0000000000
--- a/src/gui/mac/images/waitcursor.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/mac/macresources.qrc b/src/gui/mac/macresources.qrc
deleted file mode 100644
index 9696002205..0000000000
--- a/src/gui/mac/macresources.qrc
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/mac/cursors">
-<file>images/copyarrowcursor.png</file>
-<file>images/forbiddencursor.png</file>
-<file>images/spincursor.png</file>
-<file>images/waitcursor.png</file>
-<file>images/pluscursor.png</file>
-</qresource>
-<qresource prefix="/trolltech/mac/style">
-<file>images/leopard-unified-toolbar-on.png</file>
-</qresource>
-</RCC>
diff --git a/src/gui/mac/qt_menu.nib/classes.nib b/src/gui/mac/qt_menu.nib/classes.nib
deleted file mode 100644
index 0031e0e4e5..0000000000
--- a/src/gui/mac/qt_menu.nib/classes.nib
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>IBClasses</key>
- <array>
- <dict>
- <key>ACTIONS</key>
- <dict>
- <key>hide</key>
- <string>id</string>
- <key>hideOtherApplications</key>
- <string>id</string>
- <key>orderFrontStandardAboutPanel</key>
- <string>id</string>
- <key>qtDispatcherToQAction</key>
- <string>id</string>
- <key>terminate</key>
- <string>id</string>
- <key>unhideAllApplications</key>
- <string>id</string>
- </dict>
- <key>CLASS</key>
- <string>QCocoaMenuLoader</string>
- <key>LANGUAGE</key>
- <string>ObjC</string>
- <key>OUTLETS</key>
- <dict>
- <key>aboutItem</key>
- <string>NSMenuItem</string>
- <key>aboutQtItem</key>
- <string>NSMenuItem</string>
- <key>appMenu</key>
- <string>NSMenu</string>
- <key>hideItem</key>
- <string>NSMenuItem</string>
- <key>preferencesItem</key>
- <string>NSMenuItem</string>
- <key>quitItem</key>
- <string>NSMenuItem</string>
- <key>theMenu</key>
- <string>NSMenu</string>
- </dict>
- <key>SUPERCLASS</key>
- <string>NSResponder</string>
- </dict>
- <dict>
- <key>CLASS</key>
- <string>FirstResponder</string>
- <key>LANGUAGE</key>
- <string>ObjC</string>
- <key>SUPERCLASS</key>
- <string>NSObject</string>
- </dict>
- </array>
- <key>IBVersion</key>
- <string>1</string>
-</dict>
-</plist>
diff --git a/src/gui/mac/qt_menu.nib/info.nib b/src/gui/mac/qt_menu.nib/info.nib
deleted file mode 100644
index 02e5cca562..0000000000
--- a/src/gui/mac/qt_menu.nib/info.nib
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>IBFramework Version</key>
- <string>672</string>
- <key>IBOldestOS</key>
- <integer>5</integer>
- <key>IBOpenObjects</key>
- <array>
- <integer>57</integer>
- </array>
- <key>IBSystem Version</key>
- <string>9L31a</string>
- <key>targetFramework</key>
- <string>IBCocoaFramework</string>
-</dict>
-</plist>
diff --git a/src/gui/mac/qt_menu.nib/keyedobjects.nib b/src/gui/mac/qt_menu.nib/keyedobjects.nib
deleted file mode 100644
index 3edb0ed2eb..0000000000
--- a/src/gui/mac/qt_menu.nib/keyedobjects.nib
+++ /dev/null
Binary files differ
diff --git a/src/gui/painting/qpaintdevice_qpa.cpp b/src/gui/painting/qpaintdevice_qpa.cpp
index 44e169c14e..9d731db4be 100644
--- a/src/gui/painting/qpaintdevice_qpa.cpp
+++ b/src/gui/painting/qpaintdevice_qpa.cpp
@@ -42,7 +42,7 @@
#include "qpaintdevice.h"
#include "qpainter.h"
#include "qbitmap.h"
-#include "qapplication.h"
+#include "qguiapplication.h"
QT_BEGIN_NAMESPACE
diff --git a/src/gui/platforms/mac/qapplication_mac.mm b/src/gui/platforms/mac/qapplication_mac.mm
deleted file mode 100644
index f607a72e92..0000000000
--- a/src/gui/platforms/mac/qapplication_mac.mm
+++ /dev/null
@@ -1,3134 +0,0 @@
-/****************************************************************************
-**
-** 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/platforms/mac/qclipboard_mac.cpp b/src/gui/platforms/mac/qclipboard_mac.cpp
deleted file mode 100644
index 4a8bc56e41..0000000000
--- a/src/gui/platforms/mac/qclipboard_mac.cpp
+++ /dev/null
@@ -1,634 +0,0 @@
-/****************************************************************************
-**
-** 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 "qclipboard.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qdatetime.h"
-#include "qdebug.h"
-#include "qapplication_p.h"
-#include <private/qt_mac_p.h>
-#include "qevent.h"
-#include "qurl.h"
-#include <stdlib.h>
-#include <string.h>
-#include "qt_cocoa_helpers_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
- QClipboard debug facilities
- *****************************************************************************/
-//#define DEBUG_PASTEBOARD
-
-#ifndef QT_NO_CLIPBOARD
-
-/*****************************************************************************
- QClipboard member functions for mac.
- *****************************************************************************/
-
-static QMacPasteboard *qt_mac_pasteboards[2] = {0, 0};
-
-static inline QMacPasteboard *qt_mac_pasteboard(QClipboard::Mode mode)
-{
- Q_ASSERT(mode == QClipboard::Clipboard || mode == QClipboard::FindBuffer);
- if (mode == QClipboard::Clipboard)
- return qt_mac_pasteboards[0];
- else
- return qt_mac_pasteboards[1];
-}
-
-static void qt_mac_cleanupPasteboard() {
- delete qt_mac_pasteboards[0];
- delete qt_mac_pasteboards[1];
- qt_mac_pasteboards[0] = 0;
- qt_mac_pasteboards[1] = 0;
-}
-
-static bool qt_mac_updateScrap(QClipboard::Mode mode)
-{
- if(!qt_mac_pasteboards[0]) {
- qt_mac_pasteboards[0] = new QMacPasteboard(kPasteboardClipboard, QMacPasteboardMime::MIME_CLIP);
- qt_mac_pasteboards[1] = new QMacPasteboard(kPasteboardFind, QMacPasteboardMime::MIME_CLIP);
- qAddPostRoutine(qt_mac_cleanupPasteboard);
- return true;
- }
- return qt_mac_pasteboard(mode)->sync();
-}
-
-void QClipboard::clear(Mode mode)
-{
- if (!supportsMode(mode))
- return;
- qt_mac_updateScrap(mode);
- qt_mac_pasteboard(mode)->clear();
- setMimeData(0, mode);
-}
-
-void QClipboard::ownerDestroyed()
-{
-}
-
-
-void QClipboard::connectNotify(const char *signal)
-{
- Q_UNUSED(signal);
-}
-
-bool QClipboard::event(QEvent *e)
-{
- if(e->type() != QEvent::Clipboard)
- return QObject::event(e);
-
- if (qt_mac_updateScrap(QClipboard::Clipboard)) {
- emitChanged(QClipboard::Clipboard);
- }
-
- if (qt_mac_updateScrap(QClipboard::FindBuffer)) {
- emitChanged(QClipboard::FindBuffer);
- }
-
- return QObject::event(e);
-}
-
-const QMimeData *QClipboard::mimeData(Mode mode) const
-{
- if (!supportsMode(mode))
- return 0;
- qt_mac_updateScrap(mode);
- return qt_mac_pasteboard(mode)->mimeData();
-}
-
-void QClipboard::setMimeData(QMimeData *src, Mode mode)
-{
- if (!supportsMode(mode))
- return;
- qt_mac_updateScrap(mode);
- qt_mac_pasteboard(mode)->setMimeData(src);
- emitChanged(mode);
-}
-
-bool QClipboard::supportsMode(Mode mode) const
-{
- return (mode == Clipboard || mode == FindBuffer);
-}
-
-bool QClipboard::ownsMode(Mode mode) const
-{
- Q_UNUSED(mode);
- return false;
-}
-
-#endif // QT_NO_CLIPBOARD
-
-/*****************************************************************************
- QMacPasteboard code
-*****************************************************************************/
-
-QMacPasteboard::QMacPasteboard(PasteboardRef p, uchar mt)
-{
- mac_mime_source = false;
- mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
- paste = p;
- CFRetain(paste);
-}
-
-QMacPasteboard::QMacPasteboard(uchar mt)
-{
- mac_mime_source = false;
- mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
- paste = 0;
- OSStatus err = PasteboardCreate(0, &paste);
- if(err == noErr) {
- PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
- } else {
- qDebug("PasteBoard: Error creating pasteboard: [%d]", (int)err);
- }
-}
-
-QMacPasteboard::QMacPasteboard(CFStringRef name, uchar mt)
-{
- mac_mime_source = false;
- mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
- paste = 0;
- OSStatus err = PasteboardCreate(name, &paste);
- if(err == noErr) {
- PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
- } else {
- qDebug("PasteBoard: Error creating pasteboard: %s [%d]", QCFString::toQString(name).toLatin1().constData(), (int)err);
- }
-}
-
-QMacPasteboard::~QMacPasteboard()
-{
- // commit all promises for paste after exit close
- for (int i = 0; i < promises.count(); ++i) {
- const Promise &promise = promises.at(i);
- QCFString flavor = QCFString(promise.convertor->flavorFor(promise.mime));
- promiseKeeper(paste, (PasteboardItemID)promise.itemId, flavor, this);
- }
-
- if(paste)
- CFRelease(paste);
-}
-
-PasteboardRef
-QMacPasteboard::pasteBoard() const
-{
- return paste;
-}
-
-OSStatus QMacPasteboard::promiseKeeper(PasteboardRef paste, PasteboardItemID id, CFStringRef flavor, void *_qpaste)
-{
- QMacPasteboard *qpaste = (QMacPasteboard*)_qpaste;
- const long promise_id = (long)id;
-
- // Find the kept promise
- const QString flavorAsQString = QCFString::toQString(flavor);
- QMacPasteboard::Promise promise;
- for (int i = 0; i < qpaste->promises.size(); i++){
- QMacPasteboard::Promise tmp = qpaste->promises[i];
- if (tmp.itemId == promise_id && tmp.convertor->canConvert(tmp.mime, flavorAsQString)){
- promise = tmp;
- break;
- }
- }
-
- if (!promise.itemId && flavorAsQString == QLatin1String("com.trolltech.qt.MimeTypeName")) {
- // we have promised this data, but wont be able to convert, so return null data.
- // This helps in making the application/x-qt-mime-type-name hidden from normal use.
- QByteArray ba;
- QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
- PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
- return noErr;
- }
-
- if (!promise.itemId) {
- // There was no promise that could deliver data for the
- // given id and flavor. This should not happend.
- qDebug("Pasteboard: %d: Request for %ld, %s, but no promise found!", __LINE__, promise_id, qPrintable(flavorAsQString));
- return cantGetFlavorErr;
- }
-
-#ifdef DEBUG_PASTEBOARD
- qDebug("PasteBoard: Calling in promise for %s[%ld] [%s] (%s) [%d]", qPrintable(promise.mime), promise_id,
- qPrintable(flavorAsQString), qPrintable(promise.convertor->convertorName()), promise.offset);
-#endif
-
- QList<QByteArray> md = promise.convertor->convertFromMime(promise.mime, promise.data, flavorAsQString);
- if (md.size() <= promise.offset)
- return cantGetFlavorErr;
- const QByteArray &ba = md[promise.offset];
- QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
- PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
- return noErr;
-}
-
-bool
-QMacPasteboard::hasOSType(int c_flavor) const
-{
- if (!paste)
- return false;
-
- sync();
-
- ItemCount cnt = 0;
- if(PasteboardGetItemCount(paste, &cnt) || !cnt)
- return false;
-
-#ifdef DEBUG_PASTEBOARD
- qDebug("PasteBoard: hasOSType [%c%c%c%c]", (c_flavor>>24)&0xFF, (c_flavor>>16)&0xFF,
- (c_flavor>>8)&0xFF, (c_flavor>>0)&0xFF);
-#endif
- for(uint index = 1; index <= cnt; ++index) {
-
- PasteboardItemID id;
- if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
- return false;
-
- QCFType<CFArrayRef> types;
- if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
- return false;
-
- const int type_count = CFArrayGetCount(types);
- for(int i = 0; i < type_count; ++i) {
- CFStringRef flavor = (CFStringRef)CFArrayGetValueAtIndex(types, i);
- const int os_flavor = UTGetOSTypeFromString(UTTypeCopyPreferredTagWithClass(flavor, kUTTagClassOSType));
- if(os_flavor == c_flavor) {
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - Found!");
-#endif
- return true;
- }
- }
- }
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - NotFound!");
-#endif
- return false;
-}
-
-bool
-QMacPasteboard::hasFlavor(QString c_flavor) const
-{
- if (!paste)
- return false;
-
- sync();
-
- ItemCount cnt = 0;
- if(PasteboardGetItemCount(paste, &cnt) || !cnt)
- return false;
-
-#ifdef DEBUG_PASTEBOARD
- qDebug("PasteBoard: hasFlavor [%s]", qPrintable(c_flavor));
-#endif
- for(uint index = 1; index <= cnt; ++index) {
-
- PasteboardItemID id;
- if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
- return false;
-
- PasteboardFlavorFlags flags;
- if(PasteboardGetItemFlavorFlags(paste, id, QCFString(c_flavor), &flags) == noErr) {
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - Found!");
-#endif
- return true;
- }
- }
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - NotFound!");
-#endif
- return false;
-}
-
-class QMacPasteboardMimeSource : public QMimeData {
- const QMacPasteboard *paste;
-public:
- QMacPasteboardMimeSource(const QMacPasteboard *p) : QMimeData(), paste(p) { }
- ~QMacPasteboardMimeSource() { }
- virtual QStringList formats() const { return paste->formats(); }
- virtual QVariant retrieveData(const QString &format, QVariant::Type type) const { return paste->retrieveData(format, type); }
-};
-
-QMimeData
-*QMacPasteboard::mimeData() const
-{
- if(!mime) {
- mac_mime_source = true;
- mime = new QMacPasteboardMimeSource(this);
-
- }
- return mime;
-}
-
-class QMacMimeData : public QMimeData
-{
-public:
- QVariant variantData(const QString &mime) { return retrieveData(mime, QVariant::Invalid); }
-private:
- QMacMimeData();
-};
-
-void
-QMacPasteboard::setMimeData(QMimeData *mime_src)
-{
- if (!paste)
- return;
-
- if (mime == mime_src || (!mime_src && mime && mac_mime_source))
- return;
- mac_mime_source = false;
- delete mime;
- mime = mime_src;
-
- QList<QMacPasteboardMime*> availableConverters = QMacPasteboardMime::all(mime_type);
- if (mime != 0) {
- clear_helper();
- QStringList formats = mime_src->formats();
-
-#ifdef QT_MAC_USE_COCOA
- // QMimeData sub classes reimplementing the formats() might not expose the
- // temporary "application/x-qt-mime-type-name" mimetype. So check the existence
- // of this mime type while doing drag and drop.
- QString dummyMimeType(QLatin1String("application/x-qt-mime-type-name"));
- if (!formats.contains(dummyMimeType)) {
- QByteArray dummyType = mime_src->data(dummyMimeType);
- if (!dummyType.isEmpty()) {
- formats.append(dummyMimeType);
- }
- }
-#endif
- for(int f = 0; f < formats.size(); ++f) {
- QString mimeType = formats.at(f);
- for (QList<QMacPasteboardMime *>::Iterator it = availableConverters.begin(); it != availableConverters.end(); ++it) {
- QMacPasteboardMime *c = (*it);
- QString flavor(c->flavorFor(mimeType));
- if(!flavor.isEmpty()) {
- QVariant mimeData = static_cast<QMacMimeData*>(mime_src)->variantData(mimeType);
-#if 0
- //### Grrr, why didn't I put in a virtual int QMacPasteboardMime::count()? --Sam
- const int numItems = c->convertFromMime(mimeType, mimeData, flavor).size();
-#else
- int numItems = 1; //this is a hack but it is much faster than allowing conversion above
- if(c->convertorName() == QLatin1String("FileURL"))
- numItems = mime_src->urls().count();
-#endif
- for(int item = 0; item < numItems; ++item) {
- const int itemID = item+1; //id starts at 1
- promises.append(QMacPasteboard::Promise(itemID, c, mimeType, mimeData, item));
- PasteboardPutItemFlavor(paste, (PasteboardItemID)itemID, QCFString(flavor), 0, kPasteboardFlavorNoFlags);
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - adding %d %s [%s] <%s> [%d]",
- itemID, qPrintable(mimeType), qPrintable(flavor), qPrintable(c->convertorName()), item);
-#endif
- }
- }
- }
- }
- }
-}
-
-QStringList
-QMacPasteboard::formats() const
-{
- if (!paste)
- return QStringList();
-
- sync();
-
- QStringList ret;
- ItemCount cnt = 0;
- if(PasteboardGetItemCount(paste, &cnt) || !cnt)
- return ret;
-
-#ifdef DEBUG_PASTEBOARD
- qDebug("PasteBoard: Formats [%d]", (int)cnt);
-#endif
- for(uint index = 1; index <= cnt; ++index) {
-
- PasteboardItemID id;
- if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
- continue;
-
- QCFType<CFArrayRef> types;
- if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
- continue;
-
- const int type_count = CFArrayGetCount(types);
- for(int i = 0; i < type_count; ++i) {
- const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
-#ifdef DEBUG_PASTEBOARD
- qDebug(" -%s", qPrintable(QString(flavor)));
-#endif
- QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
- if(!mimeType.isEmpty() && !ret.contains(mimeType)) {
-#ifdef DEBUG_PASTEBOARD
- qDebug(" -<%d> %s [%s]", ret.size(), qPrintable(mimeType), qPrintable(QString(flavor)));
-#endif
- ret << mimeType;
- }
- }
- }
- return ret;
-}
-
-bool
-QMacPasteboard::hasFormat(const QString &format) const
-{
- if (!paste)
- return false;
-
- sync();
-
- ItemCount cnt = 0;
- if(PasteboardGetItemCount(paste, &cnt) || !cnt)
- return false;
-
-#ifdef DEBUG_PASTEBOARD
- qDebug("PasteBoard: hasFormat [%s]", qPrintable(format));
-#endif
- for(uint index = 1; index <= cnt; ++index) {
-
- PasteboardItemID id;
- if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
- continue;
-
- QCFType<CFArrayRef> types;
- if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
- continue;
-
- const int type_count = CFArrayGetCount(types);
- for(int i = 0; i < type_count; ++i) {
- const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
-#ifdef DEBUG_PASTEBOARD
- qDebug(" -%s [0x%x]", qPrintable(QString(flavor)), mime_type);
-#endif
- QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
-#ifdef DEBUG_PASTEBOARD
- if(!mimeType.isEmpty())
- qDebug(" - %s", qPrintable(mimeType));
-#endif
- if(mimeType == format)
- return true;
- }
- }
- return false;
-}
-
-QVariant
-QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
-{
- if (!paste)
- return QVariant();
-
- sync();
-
- ItemCount cnt = 0;
- if(PasteboardGetItemCount(paste, &cnt) || !cnt)
- return QByteArray();
-
-#ifdef DEBUG_PASTEBOARD
- qDebug("Pasteboard: retrieveData [%s]", qPrintable(format));
-#endif
- const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type);
- for(int mime = 0; mime < mimes.size(); ++mime) {
- QMacPasteboardMime *c = mimes.at(mime);
- QString c_flavor = c->flavorFor(format);
- if(!c_flavor.isEmpty()) {
- // Handle text/plain a little differently. Try handling Unicode first.
- bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text")
- || c_flavor == QLatin1String("public.utf8-plain-text"));
- if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) {
- // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped
- // correctly (as '\n') in this data. The 'public.utf16-plain-text' type
- // usually maps newlines to '\r' instead.
- QString str = qt_mac_get_pasteboardString(paste);
- if (!str.isEmpty())
- return str;
- }
- if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text")))
- c_flavor = QLatin1String("public.utf16-plain-text");
-
- QVariant ret;
- QList<QByteArray> retList;
- for(uint index = 1; index <= cnt; ++index) {
- PasteboardItemID id;
- if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
- continue;
-
- QCFType<CFArrayRef> types;
- if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
- continue;
-
- const int type_count = CFArrayGetCount(types);
- for(int i = 0; i < type_count; ++i) {
- CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i));
- if(c_flavor == QCFString::toQString(flavor)) {
- QCFType<CFDataRef> macBuffer;
- if(PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) {
- QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer));
- if(!buffer.isEmpty()) {
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
-#endif
- buffer.detach(); //detach since we release the macBuffer
- retList.append(buffer);
- break; //skip to next element
- }
- }
- } else {
-#ifdef DEBUG_PASTEBOARD
- qDebug(" - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
-#endif
- }
- }
- }
-
- if (!retList.isEmpty()) {
- ret = c->convertToMime(format, retList, c_flavor);
- return ret;
- }
- }
- }
- return QVariant();
-}
-
-void QMacPasteboard::clear_helper()
-{
- if (paste)
- PasteboardClear(paste);
- promises.clear();
-}
-
-void
-QMacPasteboard::clear()
-{
-#ifdef DEBUG_PASTEBOARD
- qDebug("PasteBoard: clear!");
-#endif
- clear_helper();
-}
-
-bool
-QMacPasteboard::sync() const
-{
- if (!paste)
- return false;
- const bool fromGlobal = PasteboardSynchronize(paste) & kPasteboardModified;
-
- if (fromGlobal)
- const_cast<QMacPasteboard *>(this)->setMimeData(0);
-
-#ifdef DEBUG_PASTEBOARD
- if(fromGlobal)
- qDebug("Pasteboard: Synchronize!");
-#endif
- return fromGlobal;
-}
-
-
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qcocoaapplication_mac.mm b/src/gui/platforms/mac/qcocoaapplication_mac.mm
deleted file mode 100644
index 872f31dec7..0000000000
--- a/src/gui/platforms/mac/qcocoaapplication_mac.mm
+++ /dev/null
@@ -1,222 +0,0 @@
-/****************************************************************************
-**
-** 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 <qglobal.h>
-#ifdef QT_MAC_USE_COCOA
-#include <private/qcocoaapplication_mac_p.h>
-#include <private/qcocoaapplicationdelegate_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qcocoaintrospection_p.h>
-
-QT_USE_NAMESPACE
-
-@implementation NSApplication (QT_MANGLE_NAMESPACE(QApplicationIntegration))
-
-- (void)QT_MANGLE_NAMESPACE(qt_setDockMenu):(NSMenu *)newMenu
-{
- [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] setDockMenu:newMenu];
-}
-
-- (QApplicationPrivate *)QT_MANGLE_NAMESPACE(qt_qappPrivate)
-{
- return [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] qAppPrivate];
-}
-
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)
-{
- return [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] menuLoader];
-}
-
-- (int)QT_MANGLE_NAMESPACE(qt_validModesForFontPanel):(NSFontPanel *)fontPanel
-{
- Q_UNUSED(fontPanel);
- // only display those things that QFont can handle
- return NSFontPanelFaceModeMask
- | NSFontPanelSizeModeMask
- | NSFontPanelCollectionModeMask
- | NSFontPanelUnderlineEffectModeMask
- | NSFontPanelStrikethroughEffectModeMask;
-}
-
-- (void)qt_sendPostedMessage:(NSEvent *)event
-{
- // WARNING: data1 and data2 is truncated to from 64-bit to 32-bit on OS 10.5!
- // That is why we need to split the address in two parts:
- quint64 lower = [event data1];
- quint64 upper = [event data2];
- QCocoaPostMessageArgs *args = reinterpret_cast<QCocoaPostMessageArgs *>(lower | (upper << 32));
- // Special case for convenience: if the argument is an NSNumber, we unbox it directly.
- // Use NSValue instead if this behaviour is unwanted.
- id a1 = ([args->arg1 isKindOfClass:[NSNumber class]]) ? (id)[args->arg1 intValue] : args->arg1;
- id a2 = ([args->arg2 isKindOfClass:[NSNumber class]]) ? (id)[args->arg2 intValue] : args->arg2;
- switch (args->argCount) {
- case 0:
- [args->target performSelector:args->selector];
- break;
- case 1:
- [args->target performSelector:args->selector withObject:a1];
- break;
- case 3:
- [args->target performSelector:args->selector withObject:a1 withObject:a2];
- break;
- }
-
- delete args;
-}
-
-- (BOOL)qt_filterEvent:(NSEvent *)event
-{
- if (qApp->macEventFilter(0, reinterpret_cast<EventRef>(event)))
- return true;
-
- if ([event type] == NSApplicationDefined) {
- switch ([event subtype]) {
- case QtCocoaEventSubTypePostMessage:
- [NSApp qt_sendPostedMessage:event];
- return true;
- default:
- break;
- }
- }
- return false;
-}
-
-@end
-
-@implementation QNSApplication
-
-- (void)qt_sendEvent_original:(NSEvent *)event
-{
- Q_UNUSED(event);
- // This method will only be used as a signature
- // template for the method we add into NSApplication
- // containing the original [NSApplication sendEvent:] implementation
-}
-
-- (void)qt_sendEvent_replacement:(NSEvent *)event
-{
- // This method (or its implementation to be precise) will
- // be called instead of sendEvent if redirection occurs.
- // 'self' will then be an instance of NSApplication
- // (and not QNSApplication)
- if (![NSApp qt_filterEvent:event])
- [self qt_sendEvent_original:event];
-}
-
-- (void)sendEvent:(NSEvent *)event
-{
- // This method will be called if
- // no redirection occurs
- if (![NSApp qt_filterEvent:event])
- [super sendEvent:event];
-}
-
-- (void)qtDispatcherToQAction:(id)sender
-{
- // Forward actions sendt from the menu bar (e.g. quit) to the menu loader.
- // Having this method here means that we are the last stop in the responder
- // chain, and that we are able to handle menu actions even when no window is
- // visible on screen. Note: If Qt is used as a plugin, Qt will not use a
- // native menu bar. Hence, we will also not need to do any redirection etc. as
- // we do with sendEvent.
- [[NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)] qtDispatcherToQAction:sender];
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-
-void qt_redirectNSApplicationSendEvent()
-{
- if ([NSApp isMemberOfClass:[QNSApplication class]]) {
- // No need to change implementation since Qt
- // already controls a subclass of NSApplication
- return;
- }
-
- // Change the implementation of [NSApplication sendEvent] to the
- // implementation of qt_sendEvent_replacement found in QNSApplication.
- // And keep the old implementation that gets overwritten inside a new
- // method 'qt_sendEvent_original' that we add to NSApplication
- qt_cocoa_change_implementation(
- [NSApplication class],
- @selector(sendEvent:),
- [QNSApplication class],
- @selector(qt_sendEvent_replacement:),
- @selector(qt_sendEvent_original:));
- }
-
-QT_END_NAMESPACE
-#endif
diff --git a/src/gui/platforms/mac/qcocoaapplication_mac_p.h b/src/gui/platforms/mac/qcocoaapplication_mac_p.h
deleted file mode 100644
index 0c3f5e442d..0000000000
--- a/src/gui/platforms/mac/qcocoaapplication_mac_p.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/****************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-/*
- Cocoa Application Categories
-*/
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <AppKit/AppKit.h>
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
-@class QT_MANGLE_NAMESPACE(QCocoaMenuLoader);
-
-@interface NSApplication (QT_MANGLE_NAMESPACE(QApplicationIntegration))
-- (void)QT_MANGLE_NAMESPACE(qt_setDockMenu):(NSMenu *)newMenu;
-- (QApplicationPrivate *)QT_MANGLE_NAMESPACE(qt_qappPrivate);
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader);
-- (int)QT_MANGLE_NAMESPACE(qt_validModesForFontPanel):(NSFontPanel *)fontPanel;
-
-- (void)qt_sendPostedMessage:(NSEvent *)event;
-- (BOOL)qt_filterEvent:(NSEvent *)event;
-@end
-
-@interface QNSApplication : NSApplication {
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-void qt_redirectNSApplicationSendEvent();
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/platforms/mac/qcocoaapplicationdelegate_mac.mm b/src/gui/platforms/mac/qcocoaapplicationdelegate_mac.mm
deleted file mode 100644
index 77cd8902c3..0000000000
--- a/src/gui/platforms/mac/qcocoaapplicationdelegate_mac.mm
+++ /dev/null
@@ -1,354 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-
-#import <private/qcocoaapplicationdelegate_mac_p.h>
-#import <private/qcocoamenuloader_mac_p.h>
-#import <private/qcocoaapplication_mac_p.h>
-#include <private/qapplication_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qdesktopwidget_mac_p.h>
-#include <qevent.h>
-#include <qurl.h>
-#include <qapplication.h>
-
-QT_BEGIN_NAMESPACE
-extern void onApplicationChangedActivation(bool); // qapplication_mac.mm
-extern void qt_release_apple_event_handler(); //qapplication_mac.mm
-extern QPointer<QWidget> qt_last_mouse_receiver; // qapplication_mac.cpp
-extern QPointer<QWidget> qt_last_native_mouse_receiver; // qt_cocoa_helpers_mac.mm
-extern QPointer<QWidget> qt_button_down; // qapplication_mac.cpp
-
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QDesktopWidgetImplementation)
-QT_USE_NAMESPACE
-
-static QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *sharedCocoaApplicationDelegate = nil;
-
-static void cleanupCocoaApplicationDelegate()
-{
- [sharedCocoaApplicationDelegate release];
-}
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)
-
-- (id)init
-{
- self = [super init];
- if (self)
- inLaunch = true;
- return self;
-}
-
-- (void)dealloc
-{
- sharedCocoaApplicationDelegate = nil;
- [dockMenu release];
- [qtMenuLoader release];
- if (reflectionDelegate) {
- [NSApp setDelegate:reflectionDelegate];
- [reflectionDelegate release];
- }
- [super dealloc];
-}
-
-+ (id)allocWithZone:(NSZone *)zone
-{
- @synchronized(self) {
- if (sharedCocoaApplicationDelegate == nil) {
- sharedCocoaApplicationDelegate = [super allocWithZone:zone];
- return sharedCocoaApplicationDelegate;
- qAddPostRoutine(cleanupCocoaApplicationDelegate);
- }
- }
- return nil;
-}
-
-+ (QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)*)sharedDelegate
-{
- @synchronized(self) {
- if (sharedCocoaApplicationDelegate == nil)
- [[self alloc] init];
- }
- return [[sharedCocoaApplicationDelegate retain] autorelease];
-}
-
-- (void)setDockMenu:(NSMenu*)newMenu
-{
- [newMenu retain];
- [dockMenu release];
- dockMenu = newMenu;
-}
-
-- (NSMenu *)applicationDockMenu
-{
- return [[dockMenu retain] autorelease];
-}
-
-- (QApplicationPrivate *)qAppPrivate
-{
- return qtPrivate;
-}
-
-- (void)setQtPrivate:(QApplicationPrivate *)value
-{
- qtPrivate = value;
-}
-
-- (void)setMenuLoader:(QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader
-{
- [menuLoader retain];
- [qtMenuLoader release];
- qtMenuLoader = menuLoader;
-}
-
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader
-{
- return [[qtMenuLoader retain] autorelease];
-}
-
-// This function will only be called when NSApp is actually running. Before
-// that, the kAEQuitApplication Apple event will be sent to
-// QApplicationPrivate::globalAppleEventProcessor in qapplication_mac.mm
-- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
-{
- Q_UNUSED(sender);
- // The reflection delegate gets precedence
- if (reflectionDelegate
- && [reflectionDelegate respondsToSelector:@selector(applicationShouldTerminate:)]) {
- return [reflectionDelegate applicationShouldTerminate:sender];
- }
-
- if (qtPrivate->canQuit()) {
- if (!startedQuit) {
- startedQuit = true;
- qAppInstance()->quit();
- startedQuit = false;
- }
- }
-
- if (qtPrivate->threadData->eventLoops.size() == 0) {
- // INVARIANT: No event loop is executing. This probably
- // means that Qt is used as a plugin, or as a part of a native
- // Cocoa application. In any case it should be fine to
- // terminate now:
- return NSTerminateNow;
- }
-
- return NSTerminateCancel;
-}
-
-- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
-{
- Q_UNUSED(aNotification);
- inLaunch = false;
- qt_release_apple_event_handler();
-}
-
-- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
-{
- for (NSString *fileName in filenames) {
- QString qtFileName = qt_mac_NSStringToQString(fileName);
- if (inLaunch) {
- // We need to be careful because Cocoa will be nice enough to take
- // command line arguments and send them to us as events. Given the history
- // of Qt Applications, this will result in behavior people don't want, as
- // they might be doing the opening themselves with the command line parsing.
- if (qApp->arguments().contains(qtFileName))
- continue;
- }
- QFileOpenEvent foe(qtFileName);
- qt_sendSpontaneousEvent(qAppInstance(), &foe);
- }
-
- if (reflectionDelegate &&
- [reflectionDelegate respondsToSelector:@selector(application:openFiles:)])
- [reflectionDelegate application:sender openFiles:filenames];
-}
-
-- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
-{
- // If we have a reflection delegate, that will get to call the shots.
- if (reflectionDelegate
- && [reflectionDelegate respondsToSelector:
- @selector(applicationShouldTerminateAfterLastWindowClosed:)])
- return [reflectionDelegate applicationShouldTerminateAfterLastWindowClosed:sender];
- return NO; // Someday qApp->quitOnLastWindowClosed(); when QApp and NSApp work closer together.
-}
-
-
-- (void)applicationDidBecomeActive:(NSNotification *)notification
-{
- if (reflectionDelegate
- && [reflectionDelegate respondsToSelector:@selector(applicationDidBecomeActive:)])
- [reflectionDelegate applicationDidBecomeActive:notification];
-
- onApplicationChangedActivation(true);
-
- if (!QWidget::mouseGrabber()){
- // Update enter/leave immidiatly, don't wait for a move event. But only
- // if no grab exists (even if the grab points to this widget, it seems, ref X11)
- QPoint qlocal, qglobal;
- QWidget *widgetUnderMouse = 0;
- qt_mac_getTargetForMouseEvent(0, QEvent::Enter, qlocal, qglobal, 0, &widgetUnderMouse);
- QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, 0);
- qt_last_mouse_receiver = widgetUnderMouse;
- qt_last_native_mouse_receiver = widgetUnderMouse ?
- (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
- }
-}
-
-- (void)applicationDidResignActive:(NSNotification *)notification
-{
- if (reflectionDelegate
- && [reflectionDelegate respondsToSelector:@selector(applicationDidResignActive:)])
- [reflectionDelegate applicationDidResignActive:notification];
-
- onApplicationChangedActivation(false);
-
- if (!QWidget::mouseGrabber())
- QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
- qt_last_mouse_receiver = 0;
- qt_last_native_mouse_receiver = 0;
- qt_button_down = 0;
-}
-
-- (void)applicationDidChangeScreenParameters:(NSNotification *)notification
-{
- Q_UNUSED(notification);
- QDesktopWidgetImplementation::instance()->onResize();
-}
-
-- (void)setReflectionDelegate:(NSObject <NSApplicationDelegate> *)oldDelegate
-{
- [oldDelegate retain];
- [reflectionDelegate release];
- reflectionDelegate = oldDelegate;
-}
-
-- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
-{
- NSMethodSignature *result = [super methodSignatureForSelector:aSelector];
- if (!result && reflectionDelegate) {
- result = [reflectionDelegate methodSignatureForSelector:aSelector];
- }
- return result;
-}
-
-- (BOOL)respondsToSelector:(SEL)aSelector
-{
- BOOL result = [super respondsToSelector:aSelector];
- if (!result && reflectionDelegate)
- result = [reflectionDelegate respondsToSelector:aSelector];
- return result;
-}
-
-- (void)forwardInvocation:(NSInvocation *)invocation
-{
- SEL invocationSelector = [invocation selector];
- if (reflectionDelegate && [reflectionDelegate respondsToSelector:invocationSelector])
- [invocation invokeWithTarget:reflectionDelegate];
- else
- [self doesNotRecognizeSelector:invocationSelector];
-}
-
-- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
-{
- Q_UNUSED(replyEvent);
-
- NSString *urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
- QUrl url(qt_mac_NSStringToQString(urlString));
- QFileOpenEvent qtEvent(url);
- qt_sendSpontaneousEvent(qAppInstance(), &qtEvent);
-}
-
-- (void)appleEventQuit:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
-{
- Q_UNUSED(event);
- Q_UNUSED(replyEvent);
- [NSApp terminate:self];
-}
-
-- (void)qtDispatcherToQAction:(id)sender
-{
- [[NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)] qtDispatcherToQAction:sender];
-}
-
-@end
-#endif
diff --git a/src/gui/platforms/mac/qcocoaapplicationdelegate_mac_p.h b/src/gui/platforms/mac/qcocoaapplicationdelegate_mac_p.h
deleted file mode 100644
index 714c046f48..0000000000
--- a/src/gui/platforms/mac/qcocoaapplicationdelegate_mac_p.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** 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.
- **
- ****************************************************************************/
-
-//
-// 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 "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate);
-
-@class QT_MANGLE_NAMESPACE(QCocoaMenuLoader);
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSApplicationDelegate <NSObject>
-- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
-- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
-- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames;
-- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender;
-- (void)applicationDidBecomeActive:(NSNotification *)notification;
-- (void)applicationDidResignActive:(NSNotification *)notification;
-@end
-
-#endif
-
-@interface QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) : NSObject <NSApplicationDelegate> {
- bool startedQuit;
- QApplicationPrivate *qtPrivate;
- NSMenu *dockMenu;
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader;
- NSObject <NSApplicationDelegate> *reflectionDelegate;
- bool inLaunch;
-}
-+ (QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)*)sharedDelegate;
-- (void)setDockMenu:(NSMenu *)newMenu;
-- (void)setQtPrivate:(QApplicationPrivate *)value;
-- (QApplicationPrivate *)qAppPrivate;
-- (void)setMenuLoader:(QT_MANGLE_NAMESPACE(QCocoaMenuLoader)*)menuLoader;
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader;
-- (void)setReflectionDelegate:(NSObject <NSApplicationDelegate> *)oldDelegate;
-- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent;
-@end
-#endif
diff --git a/src/gui/platforms/mac/qcocoaintrospection_mac.mm b/src/gui/platforms/mac/qcocoaintrospection_mac.mm
deleted file mode 100644
index 70c893aeec..0000000000
--- a/src/gui/platforms/mac/qcocoaintrospection_mac.mm
+++ /dev/null
@@ -1,125 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qcocoaintrospection_p.h>
-
-QT_BEGIN_NAMESPACE
-
-void qt_cocoa_change_implementation(Class baseClass, SEL originalSel, Class proxyClass, SEL replacementSel, SEL backupSel)
-{
-#ifndef QT_MAC_USE_COCOA
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5)
-#endif
- {
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
- // The following code replaces the _implementation_ for the selector we want to hack
- // (originalSel) with the implementation found in proxyClass. Then it creates
- // a new 'backup' method inside baseClass containing the old, original,
- // implementation (fakeSel). You can let the proxy implementation of originalSel
- // call fakeSel if needed (similar approach to calling a super class implementation).
- // fakeSel must also be implemented in proxyClass, as the signature is used
- // as template for the method one we add into baseClass.
- // NB: You will typically never create any instances of proxyClass; we use it
- // only for stealing its contents and put it into baseClass.
- if (!replacementSel)
- replacementSel = originalSel;
-
- Method originalMethod = class_getInstanceMethod(baseClass, originalSel);
- Method replacementMethod = class_getInstanceMethod(proxyClass, replacementSel);
- IMP originalImp = method_setImplementation(originalMethod, method_getImplementation(replacementMethod));
-
- if (backupSel) {
- Method backupMethod = class_getInstanceMethod(proxyClass, backupSel);
- class_addMethod(baseClass, backupSel, originalImp, method_getTypeEncoding(backupMethod));
- }
-#endif
- }
-}
-
-void qt_cocoa_change_back_implementation(Class baseClass, SEL originalSel, SEL backupSel)
-{
-#ifndef QT_MAC_USE_COCOA
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5)
-#endif
- {
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
- Method originalMethod = class_getInstanceMethod(baseClass, originalSel);
- Method backupMethodInBaseClass = class_getInstanceMethod(baseClass, backupSel);
- method_setImplementation(originalMethod, method_getImplementation(backupMethodInBaseClass));
-#endif
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qcocoaintrospection_p.h b/src/gui/platforms/mac/qcocoaintrospection_p.h
deleted file mode 100644
index 1c7d6ac13c..0000000000
--- a/src/gui/platforms/mac/qcocoaintrospection_p.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** 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 <qglobal.h>
-#import <objc/objc-class.h>
-
-QT_BEGIN_NAMESPACE
-
-void qt_cocoa_change_implementation(Class baseClass, SEL originalSel, Class proxyClass, SEL replacementSel = 0, SEL backupSel = 0);
-void qt_cocoa_change_back_implementation(Class baseClass, SEL originalSel, SEL backupSel);
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qcocoamenuloader_mac.mm b/src/gui/platforms/mac/qcocoamenuloader_mac.mm
deleted file mode 100644
index 71ff011069..0000000000
--- a/src/gui/platforms/mac/qcocoamenuloader_mac.mm
+++ /dev/null
@@ -1,264 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#include <qaction.h>
-#include <qcoreapplication.h>
-#include <private/qcocoamenuloader_mac_p.h>
-#include <private/qapplication_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qmenubar_p.h>
-#include <qmenubar.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-
-QT_FORWARD_DECLARE_CLASS(QCFString)
-QT_FORWARD_DECLARE_CLASS(QString)
-
-#ifndef QT_NO_TRANSLATION
- QT_BEGIN_NAMESPACE
- extern QString qt_mac_applicationmenu_string(int type);
- QT_END_NAMESPACE
-#endif
-
-QT_USE_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaMenuLoader)
-
-- (void)awakeFromNib
-{
- servicesItem = [[appMenu itemWithTitle:@"Services"] retain];
- hideAllOthersItem = [[appMenu itemWithTitle:@"Hide Others"] retain];
- showAllItem = [[appMenu itemWithTitle:@"Show All"] retain];
-
- // Get the names in the nib to match the app name set by Qt.
- const NSString *appName = reinterpret_cast<const NSString*>(QCFString::toCFStringRef(qAppName()));
- [quitItem setTitle:[[quitItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
- withString:const_cast<NSString *>(appName)]];
- [hideItem setTitle:[[hideItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
- withString:const_cast<NSString *>(appName)]];
- [aboutItem setTitle:[[aboutItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
- withString:const_cast<NSString *>(appName)]];
- [appName release];
- // Disable the items that don't do anything. If someone associates a QAction with them
- // They should get synced back in.
- [preferencesItem setEnabled:NO];
- [preferencesItem setHidden:YES];
- [aboutItem setEnabled:NO];
- [aboutItem setHidden:YES];
-}
-
-- (void)ensureAppMenuInMenu:(NSMenu *)menu
-{
- // The application menu is the menu in the menu bar that contains the
- // 'Quit' item. When changing menu bar (e.g when switching between
- // windows with different menu bars), we never recreate this menu, but
- // instead pull it out the current menu bar and place into the new one:
- NSMenu *mainMenu = [NSApp mainMenu];
- if ([NSApp mainMenu] == menu)
- return; // nothing to do (menu is the current menu bar)!
-
-#ifndef QT_NAMESPACE
- Q_ASSERT(mainMenu);
-#endif
- // Grab the app menu out of the current menu.
- int numItems = [mainMenu numberOfItems];
- NSMenuItem *oldAppMenuItem = 0;
- for (int i = 0; i < numItems; ++i) {
- NSMenuItem *item = [mainMenu itemAtIndex:i];
- if ([item submenu] == appMenu) {
- oldAppMenuItem = item;
- [oldAppMenuItem retain];
- [mainMenu removeItemAtIndex:i];
- break;
- }
- }
-
- if (oldAppMenuItem) {
- [oldAppMenuItem setSubmenu:nil];
- [oldAppMenuItem release];
- NSMenuItem *appMenuItem = [[NSMenuItem alloc] initWithTitle:@"Apple"
- action:nil keyEquivalent:@""];
- [appMenuItem setSubmenu:appMenu];
- [menu insertItem:appMenuItem atIndex:0];
- }
-}
-
-- (void)removeActionsFromAppMenu
-{
- for (NSMenuItem *item in [appMenu itemArray])
- [item setTag:nil];
-}
-
-- (void)dealloc
-{
- [servicesItem release];
- [hideAllOthersItem release];
- [showAllItem release];
-
- [lastAppSpecificItem release];
- [theMenu release];
- [appMenu release];
- [super dealloc];
-}
-
-- (NSMenu *)menu
-{
- return [[theMenu retain] autorelease];
-}
-
-- (NSMenu *)applicationMenu
-{
- return [[appMenu retain] autorelease];
-}
-
-- (NSMenuItem *)quitMenuItem
-{
- return [[quitItem retain] autorelease];
-}
-
-- (NSMenuItem *)preferencesMenuItem
-{
- return [[preferencesItem retain] autorelease];
-}
-
-- (NSMenuItem *)aboutMenuItem
-{
- return [[aboutItem retain] autorelease];
-}
-
-- (NSMenuItem *)aboutQtMenuItem
-{
- return [[aboutQtItem retain] autorelease];
-}
-
-- (NSMenuItem *)hideMenuItem
-{
- return [[hideItem retain] autorelease];
-}
-
-- (NSMenuItem *)appSpecificMenuItem
-{
- // Create an App-Specific menu item, insert it into the menu and return
- // it as an autorelease item.
- NSMenuItem *item = [[NSMenuItem alloc] init];
-
- NSInteger location;
- if (lastAppSpecificItem == nil) {
- location = [appMenu indexOfItem:aboutQtItem];
- } else {
- location = [appMenu indexOfItem:lastAppSpecificItem];
- [lastAppSpecificItem release];
- }
- lastAppSpecificItem = item; // Keep track of this for later (i.e., don't release it)
- [appMenu insertItem:item atIndex:location + 1];
-
- return [[item retain] autorelease];
-}
-
-- (BOOL) acceptsFirstResponder
-{
- return YES;
-}
-
-- (void)terminate:(id)sender
-{
- [NSApp terminate:sender];
-}
-
-- (void)orderFrontStandardAboutPanel:(id)sender
-{
- [NSApp orderFrontStandardAboutPanel:sender];
-}
-
-- (void)hideOtherApplications:(id)sender
-{
- [NSApp hideOtherApplications:sender];
-}
-
-- (void)unhideAllApplications:(id)sender
-{
- [NSApp unhideAllApplications:sender];
-}
-
-- (void)hide:(id)sender
-{
- [NSApp hide:sender];
-}
-
-- (void)qtUpdateMenubar
-{
- QMenuBarPrivate::macUpdateMenuBarImmediatly();
-}
-
-- (void)qtTranslateApplicationMenu
-{
-#ifndef QT_NO_TRANSLATION
- [servicesItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(0))];
- [hideItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(1).arg(qAppName()))];
- [hideAllOthersItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(2))];
- [showAllItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(3))];
- [preferencesItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(4))];
- [quitItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(5).arg(qAppName()))];
- [aboutItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(6).arg(qAppName()))];
-#endif
-}
-
-- (IBAction)qtDispatcherToQAction:(id)sender
-{
- QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
- NSMenuItem *item = static_cast<NSMenuItem *>(sender);
- if (QAction *action = reinterpret_cast<QAction *>([item tag])) {
- action->trigger();
- } else if (item == quitItem) {
- // We got here because someone was once the quitItem, but it has been
- // abandoned (e.g., the menubar was deleted). In the meantime, just do
- // normal QApplication::quit().
- qApp->quit();
- }
-}
-
- - (void)orderFrontCharacterPalette:(id)sender
- {
- [NSApp orderFrontCharacterPalette:sender];
- }
-@end
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/platforms/mac/qcocoamenuloader_mac_p.h b/src/gui/platforms/mac/qcocoamenuloader_mac_p.h
deleted file mode 100644
index cfcc7e00c6..0000000000
--- a/src/gui/platforms/mac/qcocoamenuloader_mac_p.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOCOAMENULOADER_P_H
-#define QCOCOAMENULOADER_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-@interface QT_MANGLE_NAMESPACE(QCocoaMenuLoader) : NSResponder
-{
- IBOutlet NSMenu *theMenu;
- IBOutlet NSMenu *appMenu;
- IBOutlet NSMenuItem *quitItem;
- IBOutlet NSMenuItem *preferencesItem;
- IBOutlet NSMenuItem *aboutItem;
- IBOutlet NSMenuItem *aboutQtItem;
- IBOutlet NSMenuItem *hideItem;
- NSMenuItem *lastAppSpecificItem;
- NSMenuItem *servicesItem;
- NSMenuItem *hideAllOthersItem;
- NSMenuItem *showAllItem;
-}
-- (void)ensureAppMenuInMenu:(NSMenu *)menu;
-- (void)removeActionsFromAppMenu;
-- (NSMenu *)applicationMenu;
-- (NSMenu *)menu;
-- (NSMenuItem *)quitMenuItem;
-- (NSMenuItem *)preferencesMenuItem;
-- (NSMenuItem *)aboutMenuItem;
-- (NSMenuItem *)aboutQtMenuItem;
-- (NSMenuItem *)hideMenuItem;
-- (NSMenuItem *)appSpecificMenuItem;
-- (IBAction)terminate:(id)sender;
-- (IBAction)orderFrontStandardAboutPanel:(id)sender;
-- (IBAction)hideOtherApplications:(id)sender;
-- (IBAction)unhideAllApplications:(id)sender;
-- (IBAction)hide:(id)sender;
-- (IBAction)qtDispatcherToQAction:(id)sender;
-- (void)qtUpdateMenubar;
-- (void)orderFrontCharacterPalette:(id)sender;
-@end
-
-#endif // QT_MAC_USE_COCOA
-#endif // QCOCOAMENULOADER_P_H
diff --git a/src/gui/platforms/mac/qcocoapanel_mac.mm b/src/gui/platforms/mac/qcocoapanel_mac.mm
deleted file mode 100644
index 67a12e25f8..0000000000
--- a/src/gui/platforms/mac/qcocoapanel_mac.mm
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#import <private/qcocoapanel_mac_p.h>
-#ifdef QT_MAC_USE_COCOA
-#import <private/qt_cocoa_helpers_mac_p.h>
-#import <private/qcocoawindow_mac_p.h>
-#import <private/qcocoawindowdelegate_mac_p.h>
-#import <private/qcocoaview_mac_p.h>
-#import <private/qcocoawindowcustomthemeframe_mac_p.h>
-#import <private/qcocoaapplication_mac_p.h>
-#import <private/qmultitouch_mac_p.h>
-#import <private/qapplication_p.h>
-#import <private/qbackingstore_p.h>
-#import <private/qdnd_p.h>
-
-#include <QtGui/QWidget>
-
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_USE_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaPanel)
-
-/***********************************************************************
- Copy and Paste between QCocoaWindow and QCocoaPanel
- This is a bit unfortunate, but thanks to the dynamic dispatch we
- have to duplicate this code or resort to really silly forwarding methods
-**************************************************************************/
-#include "qcocoasharedwindowmethods_mac_p.h"
-
-@end
-#endif
diff --git a/src/gui/platforms/mac/qcocoapanel_mac_p.h b/src/gui/platforms/mac/qcocoapanel_mac_p.h
deleted file mode 100644
index 542615903e..0000000000
--- a/src/gui/platforms/mac/qcocoapanel_mac_p.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QCOCOAPANEL_MAC_P
-#define QCOCOAPANEL_MAC_P
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_FORWARD_DECLARE_CLASS(QStringList);
-QT_FORWARD_DECLARE_CLASS(QCocoaDropData);
-
-@interface NSPanel (QtIntegration)
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender;
-- (void)draggingExited:(id <NSDraggingInfo>)sender;
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
-@end
-
-@interface QT_MANGLE_NAMESPACE(QCocoaPanel) : NSPanel {
- QStringList *currentCustomDragTypes;
- QCocoaDropData *dropData;
- NSInteger dragEnterSequence;
-}
-
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
-- (void)registerDragTypes;
-- (void)drawRectOriginal:(NSRect)rect;
-
-@end
-#endif
-
-#endif
diff --git a/src/gui/platforms/mac/qcocoasharedwindowmethods_mac_p.h b/src/gui/platforms/mac/qcocoasharedwindowmethods_mac_p.h
deleted file mode 100644
index ee1115bd4e..0000000000
--- a/src/gui/platforms/mac/qcocoasharedwindowmethods_mac_p.h
+++ /dev/null
@@ -1,610 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/****************************************************************************
- NB: This is not a header file, dispite the file name suffix. This file is
- included directly into the source code of qcocoawindow_mac.mm and
- qcocoapanel_mac.mm to avoid manually doing copy and paste of the exact
- same code needed at both places. This solution makes it more difficult
- to e.g fix a bug in qcocoawindow_mac.mm, but forget to do the same in
- qcocoapanel_mac.mm.
- The reason we need to do copy and paste in the first place, rather than
- resolve to method overriding, is that QCocoaPanel needs to inherit from
- NSPanel, while QCocoaWindow needs to inherit NSWindow rather than NSPanel).
-****************************************************************************/
-
-// WARNING: Don't include any header files from within this file. Put them
-// directly into qcocoawindow_mac_p.h and qcocoapanel_mac_p.h
-
-QT_BEGIN_NAMESPACE
-extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum); // qcocoaview.mm
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-extern const QStringList& qEnabledDraggedTypes(); // qmime_mac.cpp
-extern void qt_event_request_window_change(QWidget *); // qapplication_mac.mm
-extern void qt_mac_send_posted_gl_updates(QWidget *widget); // qapplication_mac.mm
-
-Q_GLOBAL_STATIC(QPointer<QWidget>, currentDragTarget);
-QT_END_NAMESPACE
-
-- (id)initWithContentRect:(NSRect)contentRect
- styleMask:(NSUInteger)windowStyle
- backing:(NSBackingStoreType)bufferingType
- defer:(BOOL)deferCreation
-{
- self = [super initWithContentRect:contentRect styleMask:windowStyle
- backing:bufferingType defer:deferCreation];
- if (self) {
- currentCustomDragTypes = 0;
- }
- return self;
-}
-
-- (void)dealloc
-{
- delete currentCustomDragTypes;
- [super dealloc];
-}
-
-- (BOOL)canBecomeKeyWindow
-{
- QWidget *widget = [self QT_MANGLE_NAMESPACE(qt_qwidget)];
- if (!widget)
- return NO; // This should happen only for qt_root_win
- if (QApplicationPrivate::isBlockedByModal(widget))
- return NO;
-
- bool isToolTip = (widget->windowType() == Qt::ToolTip);
- bool isPopup = (widget->windowType() == Qt::Popup);
- return !(isPopup || isToolTip);
-}
-
-- (BOOL)canBecomeMainWindow
-{
- QWidget *widget = [self QT_MANGLE_NAMESPACE(qt_qwidget)];
- if (!widget)
- return NO; // This should happen only for qt_root_win
- if ([self isSheet])
- return NO;
-
- bool isToolTip = (widget->windowType() == Qt::ToolTip);
- bool isPopup = (widget->windowType() == Qt::Popup);
- bool isTool = (widget->windowType() == Qt::Tool);
- return !(isPopup || isToolTip || isTool);
-}
-
-- (void)becomeMainWindow
-{
- [super becomeMainWindow];
- // Cocoa sometimes tell a hidden window to become the
- // main window (and as such, show it). This can e.g
- // happend when the application gets activated. If
- // this is the case, we tell it to hide again:
- if (![self isVisible])
- [self orderOut:self];
-}
-
-- (void)toggleToolbarShown:(id)sender
-{
- macSendToolbarChangeEvent([self QT_MANGLE_NAMESPACE(qt_qwidget)]);
- [super toggleToolbarShown:sender];
-}
-
-- (void)flagsChanged:(NSEvent *)theEvent
-{
- qt_dispatchModifiersChanged(theEvent, [self QT_MANGLE_NAMESPACE(qt_qwidget)]);
- [super flagsChanged:theEvent];
-}
-
-
-- (void)tabletProximity:(NSEvent *)tabletEvent
-{
- qt_dispatchTabletProximityEvent(tabletEvent);
-}
-
-- (void)terminate:(id)sender
-{
- // This function is called from the quit item in the menubar when this window
- // is in the first responder chain (see also qtDispatcherToQAction above)
- [NSApp terminate:sender];
-}
-
-- (void)setLevel:(NSInteger)windowLevel
-{
- // Cocoa will upon activating/deactivating applications level modal
- // windows up and down, regardsless of any explicit set window level.
- // To ensure that modal stays-on-top dialogs actually stays on top after
- // the application is activated (and therefore stacks in front of
- // other stays-on-top windows), we need to add this little special-case override:
- QWidget *widget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
- if (widget && widget->isModal() && (widget->windowFlags() & Qt::WindowStaysOnTopHint))
- [super setLevel:NSPopUpMenuWindowLevel];
- else
- [super setLevel:windowLevel];
-}
-
-- (void)sendEvent:(NSEvent *)event
-{
- [self retain];
-
- bool handled = false;
- switch([event type]) {
- case NSMouseMoved:
- // Cocoa sends move events to a parent and all its children under the mouse, much
- // like Qt handles hover events. But we only want to handle the move event once, so
- // to optimize a bit (since we subscribe for move event for all views), we handle it
- // here before this logic happends. Note: it might be tempting to do this shortcut for
- // all mouse events. The problem is that Cocoa does more than just find the correct view
- // when sending the event, like raising windows etc. So avoid it as much as possible:
- handled = qt_mac_handleMouseEvent(event, QEvent::MouseMove, Qt::NoButton, 0);
- break;
- default:
- break;
- }
-
- if (!handled) {
- [super sendEvent:event];
- qt_mac_handleNonClientAreaMouseEvent(self, event);
- }
- [self release];
-}
-
-- (void)setInitialFirstResponder:(NSView *)view
-{
- // This method is called the first time the window is placed on screen and
- // is the earliest point in time we can connect OpenGL contexts to NSViews.
- QWidget *qwidget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
- if (qwidget) {
- qt_event_request_window_change(qwidget);
- qt_mac_send_posted_gl_updates(qwidget);
- }
-
- [super setInitialFirstResponder:view];
-}
-
-- (BOOL)makeFirstResponder:(NSResponder *)responder
-{
- // For some reason Cocoa wants to flip the first responder
- // when Qt doesn't want to, sorry, but "No" :-)
- if (responder == nil && qApp->focusWidget())
- return NO;
- return [super makeFirstResponder:responder];
-}
-
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask
-{
- if (styleMask & QtMacCustomizeWindow)
- return [QT_MANGLE_NAMESPACE(QCocoaWindowCustomThemeFrame) class];
- return [super frameViewClassForStyleMask:styleMask];
-}
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-- (void)touchesBeganWithEvent:(NSEvent *)event;
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetTouch = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
- if (!widgetToGetTouch)
- return;
-
- bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
- qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-
-- (void)touchesMovedWithEvent:(NSEvent *)event;
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetTouch = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
- if (!widgetToGetTouch)
- return;
-
- bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
- qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-
-- (void)touchesEndedWithEvent:(NSEvent *)event;
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetTouch = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
- if (!widgetToGetTouch)
- return;
-
- bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
- qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-
-- (void)touchesCancelledWithEvent:(NSEvent *)event;
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetTouch = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
- if (!widgetToGetTouch)
- return;
-
- bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
- qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
--(void)registerDragTypes
-{
- // Calling registerForDraggedTypes below is slow, so only do
- // it once for each window, or when the custom types change.
- QMacCocoaAutoReleasePool pool;
- const QStringList& customTypes = qEnabledDraggedTypes();
- if (currentCustomDragTypes == 0 || *currentCustomDragTypes != customTypes) {
- if (currentCustomDragTypes == 0)
- currentCustomDragTypes = new QStringList();
- *currentCustomDragTypes = customTypes;
- const NSString* mimeTypeGeneric = @"com.trolltech.qt.MimeTypeName";
- NSMutableArray *supportedTypes = [NSMutableArray arrayWithObjects:NSColorPboardType,
- NSFilenamesPboardType, NSStringPboardType,
- NSFilenamesPboardType, NSPostScriptPboardType, NSTIFFPboardType,
- NSRTFPboardType, NSTabularTextPboardType, NSFontPboardType,
- NSRulerPboardType, NSFileContentsPboardType, NSColorPboardType,
- NSRTFDPboardType, NSHTMLPboardType, NSPICTPboardType,
- NSURLPboardType, NSPDFPboardType, NSVCardPboardType,
- NSFilesPromisePboardType, NSInkTextPboardType,
- NSMultipleTextSelectionPboardType, mimeTypeGeneric, nil];
- // Add custom types supported by the application.
- for (int i = 0; i < customTypes.size(); i++) {
- [supportedTypes addObject:qt_mac_QStringToNSString(customTypes[i])];
- }
- [self registerForDraggedTypes:supportedTypes];
- }
-}
-
-- (void)removeDropData
-{
- if (dropData) {
- delete dropData;
- dropData = 0;
- }
-}
-
-- (void)addDropData:(id <NSDraggingInfo>)sender
-{
- [self removeDropData];
- CFStringRef dropPasteboard = (CFStringRef) [[sender draggingPasteboard] name];
- dropData = new QCocoaDropData(dropPasteboard);
-}
-
-- (void)changeDraggingCursor:(NSDragOperation)newOperation
-{
- static SEL action = nil;
- static bool operationSupported = false;
- if (action == nil) {
- action = NSSelectorFromString(@"operationNotAllowedCursor");
- if ([NSCursor respondsToSelector:action]) {
- operationSupported = true;
- }
- }
- if (operationSupported) {
- NSCursor *notAllowedCursor = [NSCursor performSelector:action];
- bool isNotAllowedCursor = ([NSCursor currentCursor] == notAllowedCursor);
- if (newOperation == NSDragOperationNone && !isNotAllowedCursor) {
- [notAllowedCursor push];
- } else if (newOperation != NSDragOperationNone && isNotAllowedCursor) {
- [notAllowedCursor pop];
- }
-
- }
-}
-
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
-{
- // The user dragged something into the window. Send a draggingEntered message
- // to the QWidget under the mouse. As the drag moves over the window, and over
- // different widgets, we will handle enter and leave events from within
- // draggingUpdated below. The reason why we handle this ourselves rather than
- // subscribing for drag events directly in QCocoaView is that calling
- // registerForDraggedTypes on the views will severly degrade initialization time
- // for an application that uses a lot of drag subscribing widgets.
-
- NSPoint nswindowPoint = [sender draggingLocation];
- NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
- QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
- QWidget *qwidget = QApplication::widgetAt(globalPoint);
- *currentDragTarget() = qwidget;
- if (!qwidget)
- return [super draggingEntered:sender];
- if (qwidget->testAttribute(Qt::WA_DropSiteRegistered) == false)
- return NSDragOperationNone;
-
- [self addDropData:sender];
-
- QMimeData *mimeData = dropData;
- if (QDragManager::self()->source())
- mimeData = QDragManager::self()->dragPrivate()->data;
-
- NSDragOperation nsActions = [sender draggingSourceOperationMask];
- Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations(nsActions);
- QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) = nsActions;
- Qt::KeyboardModifiers modifiers = Qt::NoModifier;
-
- if ([sender draggingSource] != nil) {
- // modifier flags might have changed, update it here since we don't send any input events.
- QApplicationPrivate::modifier_buttons = qt_cocoaModifiers2QtModifiers([[NSApp currentEvent] modifierFlags]);
- modifiers = QApplication::keyboardModifiers();
- } else {
- // when the source is from another application the above technique will not work.
- modifiers = qt_cocoaDragOperation2QtModifiers(nsActions);
- }
-
- // send the drag enter event to the widget.
- QPoint localPoint(qwidget->mapFromGlobal(globalPoint));
- QDragEnterEvent qDEEvent(localPoint, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
- QApplication::sendEvent(qwidget, &qDEEvent);
-
- if (!qDEEvent.isAccepted()) {
- // The enter event was not accepted. We mark this by removing
- // the drop data so we don't send subsequent drag move events:
- [self removeDropData];
- [self changeDraggingCursor:NSDragOperationNone];
- return NSDragOperationNone;
- } else {
- // Send a drag move event immediately after a drag enter event (as per documentation).
- QDragMoveEvent qDMEvent(localPoint, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
- qDMEvent.setDropAction(qDEEvent.dropAction());
- qDMEvent.accept(); // accept by default, since enter event was accepted.
- QApplication::sendEvent(qwidget, &qDMEvent);
-
- if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction) {
- // Since we accepted the drag enter event, the widget expects
- // future drage move events.
- nsActions = NSDragOperationNone;
- // Save as ignored in the answer rect.
- qDMEvent.setDropAction(Qt::IgnoreAction);
- } else {
- nsActions = QT_PREPEND_NAMESPACE(qt_mac_mapDropAction)(qDMEvent.dropAction());
- }
-
- QT_PREPEND_NAMESPACE(qt_mac_copy_answer_rect)(qDMEvent);
- [self changeDraggingCursor:nsActions];
- return nsActions;
- }
- }
-
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
-{
- NSPoint nswindowPoint = [sender draggingLocation];
- NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
- QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
- QWidget *qwidget = QApplication::widgetAt(globalPoint);
- if (!qwidget)
- return [super draggingEntered:sender];
-
- // First, check if the widget under the mouse has changed since the
- // last drag move events. If so, we need to change target, and dispatch
- // syntetic drag enter/leave events:
- if (qwidget != *currentDragTarget()) {
- if (*currentDragTarget() && dropData) {
- QDragLeaveEvent de;
- QApplication::sendEvent(*currentDragTarget(), &de);
- [self removeDropData];
- }
- return [self draggingEntered:sender];
- }
-
- if (qwidget->testAttribute(Qt::WA_DropSiteRegistered) == false)
- return NSDragOperationNone;
-
- // If we have no drop data (which will be assigned inside draggingEntered), it means
- // that the current drag target did not accept the enter event. If so, we ignore
- // subsequent move events as well:
- if (dropData == 0) {
- [self changeDraggingCursor:NSDragOperationNone];
- return NSDragOperationNone;
- }
-
- // If the mouse is still within the accepted rect (provided by
- // the application on a previous event), we follow the optimization
- // and just return the answer given at that point:
- NSDragOperation nsActions = [sender draggingSourceOperationMask];
- QPoint localPoint(qwidget->mapFromGlobal(globalPoint));
- if (qt_mac_mouse_inside_answer_rect(localPoint)
- && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) == nsActions) {
- NSDragOperation operation = QT_PREPEND_NAMESPACE(qt_mac_mapDropActions)(QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastAction));
- [self changeDraggingCursor:operation];
- return operation;
- }
-
- QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) = nsActions;
- Qt::DropActions qtAllowed = QT_PREPEND_NAMESPACE(qt_mac_mapNSDragOperations)(nsActions);
- Qt::KeyboardModifiers modifiers = Qt::NoModifier;
-
- // Update modifiers:
- if ([sender draggingSource] != nil) {
- QApplicationPrivate::modifier_buttons = qt_cocoaModifiers2QtModifiers([[NSApp currentEvent] modifierFlags]);
- modifiers = QApplication::keyboardModifiers();
- } else {
- modifiers = qt_cocoaDragOperation2QtModifiers(nsActions);
- }
-
- QMimeData *mimeData = dropData;
- if (QDragManager::self()->source())
- mimeData = QDragManager::self()->dragPrivate()->data;
-
- // Insert the same drop action on the event according to
- // what the application told us it should be on the previous event:
- QDragMoveEvent qDMEvent(localPoint, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
- if (QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).lastAction != Qt::IgnoreAction
- && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).buttons == qDMEvent.mouseButtons()
- && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).modifiers == qDMEvent.keyboardModifiers())
- qDMEvent.setDropAction(QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).lastAction);
-
- // Now, end the drag move event to the widget:
- qDMEvent.accept();
- QApplication::sendEvent(qwidget, &qDMEvent);
-
- NSDragOperation operation = qt_mac_mapDropAction(qDMEvent.dropAction());
- if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction) {
- // Ignore this event (we will still receive further
- // notifications), save as ignored in the answer rect:
- operation = NSDragOperationNone;
- qDMEvent.setDropAction(Qt::IgnoreAction);
- }
-
- qt_mac_copy_answer_rect(qDMEvent);
- [self changeDraggingCursor:operation];
-
- return operation;
-}
-
-- (void)draggingExited:(id <NSDraggingInfo>)sender
-{
- NSPoint nswindowPoint = [sender draggingLocation];
- NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
- QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
- QWidget *qwidget = *currentDragTarget();
- if (!qwidget)
- return [super draggingExited:sender];
-
- if (dropData) {
- QDragLeaveEvent de;
- QApplication::sendEvent(qwidget, &de);
- [self removeDropData];
- }
-
- // Clean-up:
- [self removeDropData];
- *currentDragTarget() = 0;
- [self changeDraggingCursor:NSDragOperationEvery];
-}
-
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
-{
- QWidget *qwidget = *currentDragTarget();
- if (!qwidget)
- return NO;
-
- *currentDragTarget() = 0;
- NSPoint nswindowPoint = [sender draggingLocation];
- NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
- QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
- [self addDropData:sender];
-
- NSDragOperation nsActions = [sender draggingSourceOperationMask];
- Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations(nsActions);
- QMimeData *mimeData = dropData;
-
- if (QDragManager::self()->source())
- mimeData = QDragManager::self()->dragPrivate()->data;
- if (QDragManager::self()->object)
- QDragManager::self()->dragPrivate()->target = qwidget;
-
- QPoint localPoint(qwidget->mapFromGlobal(globalPoint));
- QDropEvent de(localPoint, qtAllowed, mimeData,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- QApplication::sendEvent(qwidget, &de);
-
- if (QDragManager::self()->object)
- QDragManager::self()->dragPrivate()->executed_action = de.dropAction();
-
- return de.isAccepted();
-}
-
-// This is a hack and it should be removed once we find the real cause for
-// the painting problems.
-// We have a static variable that signals if we have been called before or not.
-static bool firstDrawingInvocation = true;
-
-// The method below exists only as a workaround to draw/not draw the baseline
-// in the title bar. This is to support unifiedToolbar look.
-
-// This method is very special. To begin with, it is a
-// method that will get called only if we enable documentMode.
-// Furthermore, it won't get called as a normal method, we swap
-// this method with the normal implementation of drawRect in
-// _NSThemeFrame. When this method is active, its mission is to
-// first call the original drawRect implementation so the widget
-// gets proper painting. After that, it needs to detect if there
-// is a toolbar or not, in order to decide how to handle the unified
-// look. The distinction is important since the presence and
-// visibility of a toolbar change the way we enter into unified mode.
-// When there is a toolbar and that toolbar is visible, the problem
-// is as simple as to tell the toolbar not to draw its baseline.
-// However when there is not toolbar or the toolbar is not visible,
-// we need to draw a line on top of the baseline, because the baseline
-// in that case will belong to the title. For this case we need to draw
-// a line on top of the baseline.
-// As usual, there is a special case. When we first are called, we might
-// need to repaint ourselves one more time. We only need that if we
-// didn't get the activation, i.e. when we are launched via the command
-// line. And this only if the toolbar is visible from the beginning,
-// so we have a special flag that signals if we need to repaint or not.
-- (void)drawRectSpecial:(NSRect)rect
-{
- // Call the original drawing method.
- [id(self) drawRectOriginal:rect];
- NSWindow *window = [id(self) window];
- NSToolbar *toolbar = [window toolbar];
- if(!toolbar) {
- // There is no toolbar, we have to draw a line on top of the line drawn by Cocoa.
- macDrawRectOnTop((void *)window);
- } else {
- if([toolbar isVisible]) {
- // We tell Cocoa to avoid drawing the line at the end.
- if(firstDrawingInvocation) {
- firstDrawingInvocation = false;
- macSyncDrawingOnFirstInvocation((void *)window);
- } else
- [toolbar setShowsBaselineSeparator:NO];
- } else {
- // There is a toolbar but it is not visible so
- // we have to draw a line on top of the line drawn by Cocoa.
- macDrawRectOnTop((void *)window);
- }
- }
-}
-
-- (void)drawRectOriginal:(NSRect)rect
-{
- Q_UNUSED(rect)
- // This method implementation is here to silenct the compiler.
- // See drawRectSpecial for information.
-}
-
diff --git a/src/gui/platforms/mac/qcocoaview_mac.mm b/src/gui/platforms/mac/qcocoaview_mac.mm
deleted file mode 100644
index e885d1552c..0000000000
--- a/src/gui/platforms/mac/qcocoaview_mac.mm
+++ /dev/null
@@ -1,1388 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#import <private/qcocoaview_mac_p.h>
-#ifdef QT_MAC_USE_COCOA
-
-#include <private/qwidget_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qapplication_p.h>
-#include <private/qabstractscrollarea_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qdnd_p.h>
-#include <private/qmacinputcontext_p.h>
-#include <private/qevent_p.h>
-#include <private/qbackingstore_p.h>
-#include <private/qwindowsurface_raster_p.h>
-#include <private/qunifiedtoolbarsurface_mac_p.h>
-
-#include <qscrollarea.h>
-#include <qhash.h>
-#include <qtextformat.h>
-#include <qpaintengine.h>
-#include <QUrl>
-#include <QAccessible>
-#include <QFileInfo>
-#include <QFile>
-
-#include <qdebug.h>
-
-@interface NSEvent (Qt_Compile_Leopard_DeviceDelta)
- - (CGFloat)deviceDeltaX;
- - (CGFloat)deviceDeltaY;
- - (CGFloat)deviceDeltaZ;
-@end
-
-@interface NSEvent (Qt_Compile_Leopard_Gestures)
- - (CGFloat)magnification;
-@end
-
-QT_BEGIN_NAMESPACE
-
-extern void qt_mac_update_cursor(); // qcursor_mac.mm
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); // qapplication.cpp
-extern QPointer<QWidget> qt_last_mouse_receiver; // qapplication_mac.cpp
-extern QPointer<QWidget> qt_last_native_mouse_receiver; // qt_cocoa_helpers_mac.mm
-extern OSViewRef qt_mac_nativeview_for(const QWidget *w); // qwidget_mac.mm
-extern OSViewRef qt_mac_effectiveview_for(const QWidget *w); // qwidget_mac.mm
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum);
-extern QWidget *mac_mouse_grabber;
-extern bool qt_mac_clearDirtyOnWidgetInsideDrawWidget; // qwidget.cpp
-
-static QColor colorFrom(NSColor *color)
-{
- QColor qtColor;
- NSString *colorSpace = [color colorSpaceName];
- if (colorSpace == NSDeviceCMYKColorSpace) {
- CGFloat cyan, magenta, yellow, black, alpha;
- [color getCyan:&cyan magenta:&magenta yellow:&yellow black:&black alpha:&alpha];
- qtColor.setCmykF(cyan, magenta, yellow, black, alpha);
- } else {
- NSColor *tmpColor;
- tmpColor = [color colorUsingColorSpaceName:NSDeviceRGBColorSpace];
- CGFloat red, green, blue, alpha;
- [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
- qtColor.setRgbF(red, green, blue, alpha);
- }
- return qtColor;
-}
-
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QMacCocoaAutoReleasePool)
-QT_FORWARD_DECLARE_CLASS(QCFString)
-QT_FORWARD_DECLARE_CLASS(QDragManager)
-QT_FORWARD_DECLARE_CLASS(QMimeData)
-QT_FORWARD_DECLARE_CLASS(QPoint)
-QT_FORWARD_DECLARE_CLASS(QApplication)
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
-QT_FORWARD_DECLARE_CLASS(QDragEnterEvent)
-QT_FORWARD_DECLARE_CLASS(QDragMoveEvent)
-QT_FORWARD_DECLARE_CLASS(QStringList)
-QT_FORWARD_DECLARE_CLASS(QString)
-QT_FORWARD_DECLARE_CLASS(QRect)
-QT_FORWARD_DECLARE_CLASS(QRegion)
-QT_FORWARD_DECLARE_CLASS(QAbstractScrollArea)
-QT_FORWARD_DECLARE_CLASS(QAbstractScrollAreaPrivate)
-QT_FORWARD_DECLARE_CLASS(QPaintEvent)
-QT_FORWARD_DECLARE_CLASS(QPainter)
-QT_FORWARD_DECLARE_CLASS(QHoverEvent)
-QT_FORWARD_DECLARE_CLASS(QCursor)
-QT_USE_NAMESPACE
-extern "C" {
- extern NSString *NSTextInputReplacementRangeAttributeName;
-}
-
-//#define ALIEN_DEBUG 1
-#ifdef ALIEN_DEBUG
-static int qCocoaViewCount = 0;
-#endif
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaView)
-
-- (id)initWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate
-{
- self = [super init];
- if (self) {
- [self finishInitWithQWidget:widget widgetPrivate:widgetprivate];
- }
- [self setFocusRingType:NSFocusRingTypeNone];
- composingText = new QString();
-
-#ifdef ALIEN_DEBUG
- ++qCocoaViewCount;
- qDebug() << "Alien: create native view for" << widget << ". qCocoaViewCount is:" << qCocoaViewCount;
-#endif
-
- composing = false;
- sendKeyEvents = true;
- fromKeyDownEvent = false;
- alienTouchCount = 0;
-
- [self setHidden:YES];
- return self;
-}
-
-- (void) finishInitWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate
-{
- qwidget = widget;
- qwidgetprivate = widgetprivate;
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(frameDidChange:)
- name:@"NSViewFrameDidChangeNotification"
- object:self];
-}
-
-- (void)dealloc
-{
- QMacCocoaAutoReleasePool pool;
- delete composingText;
- [[NSNotificationCenter defaultCenter] removeObserver:self];
-
-#ifdef ALIEN_DEBUG
- --qCocoaViewCount;
- qDebug() << "Alien: widget deallocated. qCocoaViewCount is:" << qCocoaViewCount;
-#endif
-
- [super dealloc];
-}
-
-- (BOOL)isOpaque
-{
- if (!qwidgetprivate)
- return [super isOpaque];
- return qwidgetprivate->isOpaque;
-}
-
-- (BOOL)isFlipped
-{
- return YES;
-}
-
-// We preserve the content of the view if WA_StaticContents is defined.
-//
-// More info in the Cocoa documentation:
-// http://developer.apple.com/mac/library/documentation/cocoa/conceptual/CocoaViewsGuide/Optimizing/Optimizing.html
-- (BOOL) preservesContentDuringLiveResize
-{
- return qwidget->testAttribute(Qt::WA_StaticContents);
-}
-
-- (void) setFrameSize:(NSSize)newSize
-{
- [super setFrameSize:newSize];
-
- // A change in size has required the view to be invalidated.
- if ([self inLiveResize]) {
- NSRect rects[4];
- NSInteger count;
- [self getRectsExposedDuringLiveResize:rects count:&count];
- while (count-- > 0)
- {
- [self setNeedsDisplayInRect:rects[count]];
- }
- } else {
- [self setNeedsDisplay:YES];
- }
-
- // Make sure the opengl context is updated on resize.
- if (qwidgetprivate && qwidgetprivate->isGLWidget && [self window]) {
- qwidgetprivate->needWindowChange = true;
- QEvent event(QEvent::MacGLWindowChange);
- qApp->sendEvent(qwidget, &event);
- }
-}
-
-// We catch the 'setNeedsDisplay:' message in order to avoid a useless full repaint.
-// During the resize, the top of the widget is repainted, probably because of the
-// change of coordinate space (Quartz vs Qt). This is then followed by this message:
-// -[NSView _setNeedsDisplayIfTopLeftChanged]
-// which force a full repaint by sending the message 'setNeedsDisplay:'.
-// That is what we are preventing here.
-- (void)setNeedsDisplay:(BOOL)flag {
- if (![self inLiveResize] || !(qwidget->testAttribute(Qt::WA_StaticContents))) {
- [super setNeedsDisplay:flag];
- }
-}
-
-- (void)drawRect:(NSRect)aRect
-{
- if (!qwidget)
- return;
-
- // Getting context.
- CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
- qt_mac_retain_graphics_context(context);
-
- // We use a different graphics system.
- //
- // Widgets that are set to paint on screen, specifically QGLWidget,
- // requires the native engine to execute in order to be drawn.
- if (QApplicationPrivate::graphicsSystem() != 0 && !qwidget->testAttribute(Qt::WA_PaintOnScreen)) {
-
- // Raster engine.
- if (QApplicationPrivate::graphics_system_name == QLatin1String("raster")) {
-
- if (!qwidgetprivate->isInUnifiedToolbar) {
-
- // Qt handles the painting occuring inside the window.
- // Cocoa also keeps track of all widgets as NSView and therefore might
- // ask for a repainting of a widget even if Qt is already taking care of it.
- //
- // The only valid reason for Cocoa to call drawRect: is for window manipulation
- // (ie. resize, ...).
- //
- // Qt will then forward the update to the children.
- if (!qwidget->isWindow()) {
- qt_mac_release_graphics_context(context);
- return;
- }
-
- QRasterWindowSurface *winSurface = dynamic_cast<QRasterWindowSurface *>(qwidget->windowSurface());
- if (!winSurface || !winSurface->needsFlush) {
- qt_mac_release_graphics_context(context);
- return;
- }
-
- // Clip to region.
- const QVector<QRect> &rects = winSurface->regionToFlush.rects();
- for (int i = 0; i < rects.size(); ++i) {
- const QRect &rect = rects.at(i);
- CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()));
- }
- CGContextClip(context);
-
- QRect r = winSurface->regionToFlush.boundingRect();
- const CGRect area = CGRectMake(r.x(), r.y(), r.width(), r.height());
-
- qt_mac_draw_image(context, winSurface->imageContext(), area, area);
-
- winSurface->needsFlush = false;
- winSurface->regionToFlush = QRegion();
-
- } else {
-
- QUnifiedToolbarSurface *unifiedSurface = qwidgetprivate->unifiedSurface;
- if (!unifiedSurface) {
- qt_mac_release_graphics_context(context);
- return;
- }
-
- int areaX = qwidgetprivate->toolbar_offset.x();
- int areaY = qwidgetprivate->toolbar_offset.y();
- int areaWidth = qwidget->geometry().width();
- int areaHeight = qwidget->geometry().height();
- const CGRect area = CGRectMake(areaX, areaY, areaWidth, areaHeight);
- const CGRect drawingArea = CGRectMake(0, 0, areaWidth, areaHeight);
-
- qt_mac_draw_image(context, unifiedSurface->imageContext(), area, drawingArea);
-
- qwidgetprivate->flushRequested = false;
-
- }
-
- CGContextFlush(context);
- qt_mac_release_graphics_context(context);
- return;
- }
-
- // Qt handles the painting occuring inside the window.
- // Cocoa also keeps track of all widgets as NSView and therefore might
- // ask for a repainting of a widget even if Qt is already taking care of it.
- //
- // The only valid reason for Cocoa to call drawRect: is for window manipulation
- // (ie. resize, ...).
- //
- // Qt will then forward the update to the children.
- if (qwidget->isWindow()) {
- qwidgetprivate->syncBackingStore(qwidget->rect());
- }
- }
-
- // Native engine.
- qwidgetprivate->hd = context;
-
- if (qwidget->isVisible() && qwidget->updatesEnabled()) { //process the actual paint event.
- if (qwidget->testAttribute(Qt::WA_WState_InPaintEvent))
- qWarning("QWidget::repaint: Recursive repaint detected");
-
- const QRect qrect = QRect(aRect.origin.x, aRect.origin.y, aRect.size.width, aRect.size.height);
- QRegion qrgn;
-
- const NSRect *rects;
- NSInteger count;
- [self getRectsBeingDrawn:&rects count:&count];
- for (int i = 0; i < count; ++i) {
- QRect tmpRect = QRect(rects[i].origin.x, rects[i].origin.y, rects[i].size.width, rects[i].size.height);
- qrgn += tmpRect;
- }
-
- if (!qwidget->isWindow() && !qobject_cast<QAbstractScrollArea *>(qwidget->parent())) {
- const QRegion &parentMask = qwidget->window()->mask();
- if (!parentMask.isEmpty()) {
- const QPoint mappedPoint = qwidget->mapTo(qwidget->window(), qrect.topLeft());
- qrgn.translate(mappedPoint);
- qrgn &= parentMask;
- qrgn.translate(-mappedPoint.x(), -mappedPoint.y());
- }
- }
-
- QPoint redirectionOffset(0, 0);
- //setup the context
- qwidget->setAttribute(Qt::WA_WState_InPaintEvent);
- QPaintEngine *engine = qwidget->paintEngine();
- if (engine)
- engine->setSystemClip(qrgn);
- if (qwidgetprivate->extra && qwidgetprivate->extra->hasMask) {
- CGRect widgetRect = CGRectMake(0, 0, qwidget->width(), qwidget->height());
- CGContextTranslateCTM (context, 0, widgetRect.size.height);
- CGContextScaleCTM(context, 1, -1);
- if (qwidget->isWindow())
- CGContextClearRect(context, widgetRect);
- CGContextClipToMask(context, widgetRect, qwidgetprivate->extra->imageMask);
- CGContextScaleCTM(context, 1, -1);
- CGContextTranslateCTM (context, 0, -widgetRect.size.height);
- }
-
- if (qwidget->isWindow() && !qwidgetprivate->isOpaque
- && !qwidget->testAttribute(Qt::WA_MacBrushedMetal)) {
- CGContextClearRect(context, NSRectToCGRect(aRect));
- }
-
- qwidget->setAttribute(Qt::WA_WState_InPaintEvent, false);
- QWidgetPrivate *qwidgetPrivate = qt_widget_private(qwidget);
-
- // We specify that we want to draw the widget itself, and
- // all its children recursive. But we skip native children, because
- // they will receive drawRect calls by themselves as needed:
- int flags = QWidgetPrivate::DrawPaintOnScreen
- | QWidgetPrivate::DrawRecursive
- | QWidgetPrivate::DontDrawNativeChildren;
-
- if (qwidget->isWindow())
- flags |= QWidgetPrivate::DrawAsRoot;
-
- // Start to draw:
- qt_mac_clearDirtyOnWidgetInsideDrawWidget = true;
- qwidgetPrivate->drawWidget(qwidget, qrgn, QPoint(), flags, 0);
- qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
-
- if (!redirectionOffset.isNull())
- QPainter::restoreRedirected(qwidget);
- if (engine)
- engine->setSystemClip(QRegion());
- qwidget->setAttribute(Qt::WA_WState_InPaintEvent, false);
- if(!qwidget->testAttribute(Qt::WA_PaintOutsidePaintEvent) && qwidget->paintingActive())
- qWarning("QWidget: It is dangerous to leave painters active on a"
- " widget outside of the PaintEvent");
- }
- qwidgetprivate->hd = 0;
- qt_mac_release_graphics_context(context);
-}
-
-- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
-{
- // Find the widget that should receive the event:
- QPoint qlocal, qglobal;
- QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(theEvent, QEvent::MouseButtonPress, qlocal, qglobal, qwidget, 0);
- if (!widgetToGetMouse)
- return NO;
-
- return !widgetToGetMouse->testAttribute(Qt::WA_MacNoClickThrough);
-}
-
-- (NSView *)hitTest:(NSPoint)aPoint
-{
- if (!qwidget)
- return [super hitTest:aPoint];
-
- if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents))
- return nil; // You cannot hit a transparent for mouse event widget.
- return [super hitTest:aPoint];
-}
-
-- (void)updateTrackingAreas
-{
- if (!qwidget)
- return;
-
- // [NSView addTrackingArea] is slow, so bail out early if we can:
- if (NSIsEmptyRect([self visibleRect]))
- return;
-
- QMacCocoaAutoReleasePool pool;
- if (NSArray *trackingArray = [self trackingAreas]) {
- NSUInteger size = [trackingArray count];
- for (NSUInteger i = 0; i < size; ++i) {
- NSTrackingArea *t = [trackingArray objectAtIndex:i];
- [self removeTrackingArea:t];
- }
- }
-
- // Ideally, we shouldn't have NSTrackingMouseMoved events included below, it should
- // only be turned on if mouseTracking, hover is on or a tool tip is set.
- // Unfortunately, Qt will send "tooltip" events on mouse moves, so we need to
- // turn it on in ALL case. That means EVERY QCocoaView gets to pay the cost of
- // mouse moves delivered to it (Apple recommends keeping it OFF because there
- // is a performance hit). So it goes.
- NSUInteger trackingOptions = NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp
- | NSTrackingInVisibleRect | NSTrackingMouseMoved;
- NSTrackingArea *ta = [[NSTrackingArea alloc] initWithRect:NSMakeRect(0, 0,
- qwidget->width(),
- qwidget->height())
- options:trackingOptions
- owner:self
- userInfo:nil];
- [self addTrackingArea:ta];
- [ta release];
-}
-
-- (void)mouseEntered:(NSEvent *)event
-{
- // Cocoa will not send a move event on mouseEnter. But since
- // Qt expect this, we fake one now. See also mouseExited below
- // for info about enter/leave event handling
- NSEvent *nsmoveEvent = [NSEvent
- mouseEventWithType:NSMouseMoved
- location:[[self window] mouseLocationOutsideOfEventStream]
- modifierFlags: [event modifierFlags]
- timestamp: [event timestamp]
- windowNumber: [event windowNumber]
- context: [event context]
- eventNumber: [event eventNumber]
- clickCount: 0
- pressure: 0];
-
- // Important: Cocoa sends us mouseEnter on all views under the mouse
- // and not just the one on top. Therefore, to we cannot use qwidget
- // as native widget for this case. Instead, we let qt_mac_handleMouseEvent
- // resolve it (last argument set to 0):
- qt_mac_handleMouseEvent(nsmoveEvent, QEvent::MouseMove, Qt::NoButton, 0);
-}
-
-- (void)mouseExited:(NSEvent *)event
-{
- // Note: normal enter/leave handling is done from within mouseMove. This handler
- // catches the case when the mouse moves out of the window (which mouseMove do not).
- // Updating the mouse cursor follows the same logic as enter/leave. And we update
- // neither if a grab exists (even if the grab points to this widget, it seems, ref X11)
- Q_UNUSED(event);
- if (self == [[self window] contentView] && !qt_button_down && !QWidget::mouseGrabber()) {
- qt_mac_update_cursor();
- // If the mouse exits the content view, but qt_mac_getTargetForMouseEvent still
- // reports a target, it means that either there is a grab involved, or the mouse
- // hovered over another window in the application. In both cases, move events will
- // cause qt_mac_handleMouseEvent to be called, which will handle enter/leave.
- QPoint qlocal, qglobal;
- QWidget *widgetUnderMouse = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Leave, qlocal, qglobal, qwidget, &widgetUnderMouse);
-
- if (widgetUnderMouse == 0) {
- QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
- qt_last_mouse_receiver = 0;
- qt_last_native_mouse_receiver = 0;
- }
- }
-}
-
-- (void)flagsChanged:(NSEvent *)theEvent
-{
- QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
- if (!widgetToGetKey)
- return;
-
- qt_dispatchModifiersChanged(theEvent, widgetToGetKey);
- [super flagsChanged:theEvent];
-}
-
-- (void)mouseMoved:(NSEvent *)theEvent
-{
- // Important: this method will only be called when the view's window is _not_ inside
- // QCocoaWindow/QCocoaPanel. Otherwise, [QCocoaWindow sendEvent] will handle the event
- // before it ends up here. So, this method is added for supporting QMacNativeWidget.
- // TODO: Cocoa send move events to all views under the mouse. So make sure we only
- // handle the event for the widget on top when using QMacNativeWidget.
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)mouseDown:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonPress, Qt::LeftButton, qwidget);
- // Don't call super here. This prevents us from getting the mouseUp event,
- // which we need to send even if the mouseDown event was not accepted.
- // (this is standard Qt behavior.)
-}
-
-- (void)mouseUp:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonRelease, Qt::LeftButton, qwidget);
-}
-
-- (void)rightMouseDown:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonPress, Qt::RightButton, qwidget);
-}
-
-- (void)rightMouseUp:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonRelease, Qt::RightButton, qwidget);
-}
-
-- (void)otherMouseDown:(NSEvent *)theEvent
-{
- Qt::MouseButton mouseButton = cocoaButton2QtButton([theEvent buttonNumber]);
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonPress, mouseButton, qwidget);
-}
-
-- (void)otherMouseUp:(NSEvent *)theEvent
-{
- Qt::MouseButton mouseButton = cocoaButton2QtButton([theEvent buttonNumber]);
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonRelease, mouseButton, qwidget);
-}
-
-- (void)mouseDragged:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)rightMouseDragged:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)otherMouseDragged:(NSEvent *)theEvent
-{
- qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)scrollWheel:(NSEvent *)theEvent
-{
- // Give the Input Manager a chance to process the wheel event.
- NSInputManager *currentIManager = [NSInputManager currentInputManager];
- if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
- [currentIManager handleMouseEvent:theEvent];
- }
-
- Qt::MouseButtons buttons = QApplication::mouseButtons();
- Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([theEvent modifierFlags]);
-
- // Find the widget that should receive the event:
- QPoint qlocal, qglobal;
- QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(theEvent, QEvent::Wheel, qlocal, qglobal, qwidget, 0);
- if (!widgetToGetMouse)
- return;
-
- int deltaX = 0;
- int deltaY = 0;
- int deltaZ = 0;
-
- const EventRef carbonEvent = (EventRef)[theEvent eventRef];
- const UInt32 carbonEventKind = carbonEvent ? ::GetEventKind(carbonEvent) : 0;
- const bool scrollEvent = carbonEventKind == kEventMouseScroll;
-
- if (scrollEvent) {
- // The mouse device containts pixel scroll wheel support (Mighty Mouse, Trackpad).
- // Since deviceDelta 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; // 8 * 1/4
- deltaX = [theEvent deviceDeltaX] * pixelsToDegrees;
- deltaY = [theEvent deviceDeltaY] * pixelsToDegrees;
- deltaZ = [theEvent deviceDeltaZ] * pixelsToDegrees;
- } else {
- // carbonEventKind == kEventMouseWheelMoved
- // Remove acceleration, and use either -120 or 120 as delta:
- deltaX = qBound(-120, int([theEvent deltaX] * 10000), 120);
- deltaY = qBound(-120, int([theEvent deltaY] * 10000), 120);
- deltaZ = qBound(-120, int([theEvent deltaZ] * 10000), 120);
- }
-
-#ifndef QT_NO_WHEELEVENT
- // ### Qt 5: Send one QWheelEvent with dx, dy and dz
-
- if (deltaX != 0 && deltaY != 0)
- QMacScrollOptimization::initDelayedScroll();
-
- if (deltaX != 0) {
- QWheelEvent qwe(qlocal, qglobal, deltaX, buttons, keyMods, Qt::Horizontal);
- qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
- }
-
- if (deltaY != 0) {
- QWheelEvent qwe(qlocal, qglobal, deltaY, buttons, keyMods, Qt::Vertical);
- qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
- }
-
- if (deltaZ != 0) {
- // Qt doesn't explicitly support wheels with a Z component. In a misguided attempt to
- // try to be ahead of the pack, I'm adding this extra value.
- QWheelEvent qwe(qlocal, qglobal, deltaZ, buttons, keyMods, (Qt::Orientation)3);
- qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
- }
-
- if (deltaX != 0 && deltaY != 0)
- QMacScrollOptimization::performDelayedScroll();
-#endif //QT_NO_WHEELEVENT
-}
-
-- (void)tabletProximity:(NSEvent *)tabletEvent
-{
- qt_dispatchTabletProximityEvent(tabletEvent);
-}
-
-- (void)tabletPoint:(NSEvent *)tabletEvent
-{
- if (!qt_mac_handleTabletEvent(self, tabletEvent))
- [super tabletPoint:tabletEvent];
-}
-
-- (void)magnifyWithEvent:(NSEvent *)event
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetGesture = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
- if (!widgetToGetGesture)
- return;
- if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
- return;
-
-#ifndef QT_NO_GESTURES
- QNativeGestureEvent qNGEvent;
- qNGEvent.gestureType = QNativeGestureEvent::Zoom;
- NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
- qNGEvent.position = flipPoint(p).toPoint();
- qNGEvent.percentage = [event magnification];
- qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)rotateWithEvent:(NSEvent *)event
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetGesture = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
- if (!widgetToGetGesture)
- return;
- if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
- return;
-
-#ifndef QT_NO_GESTURES
- QNativeGestureEvent qNGEvent;
- qNGEvent.gestureType = QNativeGestureEvent::Rotate;
- NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
- qNGEvent.position = flipPoint(p).toPoint();
- qNGEvent.percentage = -[event rotation];
- qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)swipeWithEvent:(NSEvent *)event
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetGesture = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
- if (!widgetToGetGesture)
- return;
- if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
- return;
-
-#ifndef QT_NO_GESTURES
- QNativeGestureEvent qNGEvent;
- qNGEvent.gestureType = QNativeGestureEvent::Swipe;
- NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
- qNGEvent.position = flipPoint(p).toPoint();
- if ([event deltaX] == 1)
- qNGEvent.angle = 180.0f;
- else if ([event deltaX] == -1)
- qNGEvent.angle = 0.0f;
- else if ([event deltaY] == 1)
- qNGEvent.angle = 90.0f;
- else if ([event deltaY] == -1)
- qNGEvent.angle = 270.0f;
- qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)beginGestureWithEvent:(NSEvent *)event
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetGesture = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
- if (!widgetToGetGesture)
- return;
- if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
- return;
-
-#ifndef QT_NO_GESTURES
- QNativeGestureEvent qNGEvent;
- qNGEvent.gestureType = QNativeGestureEvent::GestureBegin;
- NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
- qNGEvent.position = flipPoint(p).toPoint();
- qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)endGestureWithEvent:(NSEvent *)event
-{
- QPoint qlocal, qglobal;
- QWidget *widgetToGetGesture = 0;
- qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
- if (!widgetToGetGesture)
- return;
- if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
- return;
-
-#ifndef QT_NO_GESTURES
- QNativeGestureEvent qNGEvent;
- qNGEvent.gestureType = QNativeGestureEvent::GestureEnd;
- NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
- qNGEvent.position = flipPoint(p).toPoint();
- qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-}
-#endif // QT_NO_GESTURES
-
-- (void)frameDidChange:(NSNotification *)note
-{
- Q_UNUSED(note);
- if (!qwidget)
- return;
- if (qwidget->isWindow())
- return;
- NSRect newFrame = [self frame];
- QRect newGeo(newFrame.origin.x, newFrame.origin.y, newFrame.size.width, newFrame.size.height);
- bool moved = qwidget->testAttribute(Qt::WA_Moved);
- bool resized = qwidget->testAttribute(Qt::WA_Resized);
- qwidget->setGeometry(newGeo);
- qwidget->setAttribute(Qt::WA_Moved, moved);
- qwidget->setAttribute(Qt::WA_Resized, resized);
- qwidgetprivate->syncCocoaMask();
-}
-
-- (BOOL)isEnabled
-{
- if (!qwidget)
- return [super isEnabled];
- return [super isEnabled] && qwidget->isEnabled();
-}
-
-- (void)setEnabled:(BOOL)flag
-{
- QMacCocoaAutoReleasePool pool;
- [super setEnabled:flag];
- if (qwidget && qwidget->isEnabled() != flag)
- qwidget->setEnabled(flag);
-}
-
-+ (Class)cellClass
-{
- return [NSActionCell class];
-}
-
-- (BOOL)acceptsFirstResponder
-{
- if (!qwidget)
- return NO;
-
- // Disabled widget shouldn't get focus even if it's a window.
- // hence disabled windows will not get any key or mouse events.
- if (!qwidget->isEnabled())
- return NO;
-
- if (qwidget->isWindow() && !qt_widget_private(qwidget)->topData()->embedded) {
- QWidget *focusWidget = qApp->focusWidget();
- if (!focusWidget) {
- // There is no focus widget, but we still want to receive key events
- // for shortcut handling etc. So we accept first responer for the
- // content view as a last resort:
- return YES;
- }
- if (!focusWidget->internalWinId() && focusWidget->nativeParentWidget() == qwidget) {
- // The current focus widget is alien, and hence, cannot get acceptsFirstResponder
- // calls. Since the focus widget is a child of qwidget, we let this view say YES:
- return YES;
- }
- if (focusWidget->window() != qwidget) {
- // The current focus widget is in another window. Since cocoa
- // suggest that this window should be key now, we accept:
- return YES;
- }
- }
-
- return qwidget->focusPolicy() != Qt::NoFocus;
-}
-
-- (BOOL)resignFirstResponder
-{
- if (!qwidget)
- return YES;
-
- // Seems like the following test only triggers if this
- // view is inside a QMacNativeWidget:
-// if (QWidget *fw = QApplication::focusWidget()) {
-// if (qwidget == fw || qwidget == fw->nativeParentWidget())
-// fw->clearFocus();
-// }
- return YES;
-}
-
-- (BOOL)becomeFirstResponder
-{
- // see the comment in the acceptsFirstResponder - if the window "stole" focus
- // let it become the responder, but don't tell Qt
- if (qwidget && qt_widget_private(qwidget->window())->topData()->embedded
- && !QApplication::focusWidget() && qwidget->focusPolicy() != Qt::NoFocus)
- qwidget->setFocus(Qt::OtherFocusReason);
- return YES;
-}
-
-- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
-{
- Q_UNUSED(isLocal);
- return supportedActions;
-}
-
-- (void)setSupportedActions:(NSDragOperation)actions
-{
- supportedActions = actions;
-}
-
-- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
-{
- Q_UNUSED(anImage);
- Q_UNUSED(aPoint);
- macCurrentDnDParameters()->performedAction = operation;
- if (QDragManager::self()->object
- && QDragManager::self()->dragPrivate()->executed_action != Qt::ActionMask) {
- macCurrentDnDParameters()->performedAction =
- qt_mac_mapDropAction(QDragManager::self()->dragPrivate()->executed_action);
- }
-}
-
-- (QWidget *)qt_qwidget
-{
- return qwidget;
-}
-
-- (void) qt_clearQWidget
-{
- qwidget = 0;
- qwidgetprivate = 0;
-}
-
-- (void)keyDown:(NSEvent *)theEvent
-{
- if (!qwidget)
- return;
- QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
- if (!widgetToGetKey)
- return;
-
- sendKeyEvents = true;
-
- if (widgetToGetKey->testAttribute(Qt::WA_InputMethodEnabled)
- && !(widgetToGetKey->inputMethodHints() & Qt::ImhDigitsOnly
- || widgetToGetKey->inputMethodHints() & Qt::ImhFormattedNumbersOnly
- || widgetToGetKey->inputMethodHints() & Qt::ImhHiddenText)) {
- fromKeyDownEvent = true;
- [qt_mac_nativeview_for(qwidget) interpretKeyEvents:[NSArray arrayWithObject: theEvent]];
- fromKeyDownEvent = false;
- }
-
- if (sendKeyEvents && !composing) {
- bool keyEventEaten = qt_dispatchKeyEvent(theEvent, widgetToGetKey);
- if (!keyEventEaten && qwidget) {
- // The event is not yet eaten, and if Qt is embedded inside a native
- // cocoa application, send it to first responder not owned by Qt.
- // The exception is if widgetToGetKey was redirected to a popup.
- QWidget *toplevel = qwidget->window();
- if (toplevel == widgetToGetKey->window()) {
- if (qt_widget_private(toplevel)->topData()->embedded) {
- if (NSResponder *w = [qt_mac_nativeview_for(toplevel) superview])
- [w keyDown:theEvent];
- }
- }
- }
- }
-}
-
-
-- (void)keyUp:(NSEvent *)theEvent
-{
- if (sendKeyEvents) {
- QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
- if (!widgetToGetKey)
- return;
-
- bool keyEventEaten = qt_dispatchKeyEvent(theEvent, widgetToGetKey);
- if (!keyEventEaten && qwidget) {
- // The event is not yet eaten, and if Qt is embedded inside a native
- // cocoa application, send it to first responder not owned by Qt.
- // The exception is if widgetToGetKey was redirected to a popup.
- QWidget *toplevel = qwidget->window();
- if (toplevel == widgetToGetKey->window()) {
- if (qt_widget_private(toplevel)->topData()->embedded) {
- if (NSResponder *w = [qt_mac_nativeview_for(toplevel) superview])
- [w keyUp:theEvent];
- }
- }
- }
- }
-}
-
-- (void)viewWillMoveToWindow:(NSWindow *)window
-{
- if (qwidget == 0)
- return;
-
- if (qwidget->windowFlags() & Qt::MSWindowsOwnDC
- && (window != [self window])) { // OpenGL Widget
- QEvent event(QEvent::MacGLClearDrawable);
- qApp->sendEvent(qwidget, &event);
- }
-}
-
-- (void)viewDidMoveToWindow
-{
- if (qwidget == 0)
- return;
-
- if (qwidget->windowFlags() & Qt::MSWindowsOwnDC && [self window]) {
- // call update paint event
- qwidgetprivate->needWindowChange = true;
- QEvent event(QEvent::MacGLWindowChange);
- qApp->sendEvent(qwidget, &event);
- }
-}
-
-
-// NSTextInput Protocol implementation
-
-- (void) insertText:(id)aString
-{
- QString commitText;
- if ([aString length]) {
- if ([aString isKindOfClass:[NSAttributedString class]]) {
- commitText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
- } else {
- commitText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
- };
- }
-
- // When entering characters through Character Viewer or Keyboard Viewer, the text is passed
- // through this insertText method. Since we dont receive a keyDown Event in such cases, the
- // composing flag will be false.
- if (([aString length] && composing) || !fromKeyDownEvent) {
- // Send the commit string to the widget.
- composing = false;
- sendKeyEvents = false;
- QInputMethodEvent e;
- e.setCommitString(commitText);
- if (QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget))
- qt_sendSpontaneousEvent(widgetToGetKey, &e);
- } else {
- // The key sequence "`q" on a French Keyboard will generate two calls to insertText before
- // it returns from interpretKeyEvents. The first call will turn off 'composing' and accept
- // the "`" key. The last keyDown event needs to be processed by the widget to get the
- // character "q". The string parameter is ignored for the second call.
- sendKeyEvents = true;
- }
-
- composingText->clear();
-}
-
-- (void) setMarkedText:(id)aString selectedRange:(NSRange)selRange
-{
- // Generate the QInputMethodEvent with preedit string and the attributes
- // for rendering it. The attributes handled here are 'underline',
- // 'underline color' and 'cursor position'.
- sendKeyEvents = false;
- composing = true;
- QString qtText;
- // Cursor position is retrived from the range.
- QList<QInputMethodEvent::Attribute> attrs;
- attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, selRange.location + selRange.length, 1, QVariant());
- if ([aString isKindOfClass:[NSAttributedString class]]) {
- qtText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
- composingLength = qtText.length();
- int index = 0;
- // Create attributes for individual sections of preedit text
- while (index < composingLength) {
- NSRange effectiveRange;
- NSRange range = NSMakeRange(index, composingLength-index);
- NSDictionary *attributes = [aString attributesAtIndex:index
- longestEffectiveRange:&effectiveRange
- inRange:range];
- NSNumber *underlineStyle = [attributes objectForKey:NSUnderlineStyleAttributeName];
- if (underlineStyle) {
- QColor clr (Qt::black);
- NSColor *color = [attributes objectForKey:NSUnderlineColorAttributeName];
- if (color) {
- clr = colorFrom(color);
- }
- QTextCharFormat format;
- format.setFontUnderline(true);
- format.setUnderlineColor(clr);
- attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- effectiveRange.location,
- effectiveRange.length,
- format);
- }
- index = effectiveRange.location + effectiveRange.length;
- }
- } else {
- // No attributes specified, take only the preedit text.
- qtText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
- composingLength = qtText.length();
- }
- // Make sure that we have at least one text format.
- if (attrs.size() <= 1) {
- QTextCharFormat format;
- format.setFontUnderline(true);
- attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
- 0, composingLength, format);
- }
- *composingText = qtText;
-
- QInputMethodEvent e(qtText, attrs);
- if (QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget))
- qt_sendSpontaneousEvent(widgetToGetKey, &e);
-
- if (!composingLength)
- composing = false;
-}
-
-- (void) unmarkText
-{
- if (composing) {
- QInputMethodEvent e;
- e.setCommitString(*composingText);
- if (QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget))
- qt_sendSpontaneousEvent(widgetToGetKey, &e);
- }
- composingText->clear();
- composing = false;
-}
-
-- (BOOL) hasMarkedText
-{
- return (composing ? YES: NO);
-}
-
-- (void) doCommandBySelector:(SEL)aSelector
-{
- Q_UNUSED(aSelector);
-}
-
-- (BOOL)isComposing
-{
- return composing;
-}
-
-- (NSInteger) conversationIdentifier
-{
- // Return a unique identifier fot this ime conversation
- return (NSInteger)self;
-}
-
-- (NSAttributedString *) attributedSubstringFromRange:(NSRange)theRange
-{
- QString selectedText(qwidget->inputMethodQuery(Qt::ImCurrentSelection).toString());
- if (!selectedText.isEmpty()) {
- QCFString string(selectedText.mid(theRange.location, theRange.length));
- const NSString *tmpString = reinterpret_cast<const NSString *>((CFStringRef)string);
- return [[[NSAttributedString alloc] initWithString:const_cast<NSString *>(tmpString)] autorelease];
- } else {
- return nil;
- }
-}
-
-- (NSRange) markedRange
-{
- NSRange range;
- if (composing) {
- range.location = 0;
- range.length = composingLength;
- } else {
- range.location = NSNotFound;
- range.length = 0;
- }
- return range;
-}
-
-- (NSRange) selectedRange
-{
- NSRange selRange;
- QString selectedText(qwidget->inputMethodQuery(Qt::ImCurrentSelection).toString());
- if (!selectedText.isEmpty()) {
- // Consider only the selected text.
- selRange.location = 0;
- selRange.length = selectedText.length();
- } else {
- // No selected text.
- selRange.location = NSNotFound;
- selRange.length = 0;
- }
- return selRange;
-
-}
-
-- (NSRect) firstRectForCharacterRange:(NSRange)theRange
-{
- Q_UNUSED(theRange);
- // The returned rect is always based on the internal cursor.
- QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
- if (!widgetToGetKey)
- return NSZeroRect;
-
- QRect mr(widgetToGetKey->inputMethodQuery(Qt::ImMicroFocus).toRect());
- QPoint mp(widgetToGetKey->mapToGlobal(QPoint(mr.bottomLeft())));
- NSRect rect ;
- rect.origin.x = mp.x();
- rect.origin.y = flipYCoordinate(mp.y());
- rect.size.width = mr.width();
- rect.size.height = mr.height();
- return rect;
-}
-
-- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
-{
- // We dont support cursor movements using mouse while composing.
- Q_UNUSED(thePoint);
- return NSNotFound;
-}
-
-- (NSArray*) validAttributesForMarkedText
-{
- QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
- if (!widgetToGetKey)
- return nil;
-
- if (!widgetToGetKey->testAttribute(Qt::WA_InputMethodEnabled))
- return nil; // Not sure if that's correct, but it's saves a malloc.
-
- // Support only underline color/style.
- return [NSArray arrayWithObjects:NSUnderlineColorAttributeName,
- NSUnderlineStyleAttributeName, nil];
-}
-@end
-
-QT_BEGIN_NAMESPACE
-void QMacInputContext::reset()
-{
- QWidget *w = QInputContext::focusWidget();
- if (w) {
- NSView *view = qt_mac_effectiveview_for(w);
- if ([view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QCocoaView) *qc = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
- NSInputManager *currentIManager = [NSInputManager currentInputManager];
- if (currentIManager) {
- [currentIManager markedTextAbandoned:view];
- [qc unmarkText];
- }
- }
- }
-}
-
-bool QMacInputContext::isComposing() const
-{
- QWidget *w = QInputContext::focusWidget();
- if (w) {
- NSView *view = qt_mac_effectiveview_for(w);
- if ([view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
- return [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view) isComposing];
- }
- }
- return false;
-}
-
-extern bool qt_mac_in_drag;
-void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm);
-static const int default_pm_hotx = -2;
-static const int default_pm_hoty = -16;
-static const char* default_pm[] = {
- "13 9 3 1",
- ". c None",
- " c #000000",
- "X c #FFFFFF",
- "X X X X X X X",
- " X X X X X X ",
- "X ......... X",
- " X.........X ",
- "X ......... X",
- " X.........X ",
- "X ......... X",
- " X X X X X X ",
- "X X X X X X X",
-};
-
-Qt::DropAction QDragManager::drag(QDrag *o)
-{
- if(qt_mac_in_drag) { //just make sure..
- qWarning("Qt: Internal error: WH0A, unexpected condition reached");
- return Qt::IgnoreAction;
- }
- if(object == o)
- return Qt::IgnoreAction;
- /* At the moment it seems clear that Mac OS X does not want to drag with a non-left button
- so we just bail early to prevent it */
- if(!(GetCurrentEventButtonState() & kEventMouseButtonPrimary))
- return Qt::IgnoreAction;
-
- if(object) {
- dragPrivate()->source->removeEventFilter(this);
- cancel();
- beingCancelled = false;
- }
-
- object = o;
- dragPrivate()->target = 0;
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
-#endif
-
- // setup the data
- QMacPasteboard dragBoard((CFStringRef) NSDragPboard, QMacPasteboardMime::MIME_DND);
- dragPrivate()->data->setData(QLatin1String("application/x-qt-mime-type-name"), QByteArray("dummy"));
- dragBoard.setMimeData(dragPrivate()->data);
-
- // create the image
- QPoint hotspot;
- QPixmap pix = dragPrivate()->pixmap;
- if(pix.isNull()) {
- if(dragPrivate()->data->hasText() || dragPrivate()->data->hasUrls()) {
- // get the string
- QString s = dragPrivate()->data->hasText() ? dragPrivate()->data->text()
- : dragPrivate()->data->urls().first().toString();
- if(s.length() > 26)
- s = s.left(23) + QChar(0x2026);
- if(!s.isEmpty()) {
- // draw it
- QFont f(qApp->font());
- f.setPointSize(12);
- QFontMetrics fm(f);
- QPixmap tmp(fm.width(s), fm.height());
- if(!tmp.isNull()) {
- QPainter p(&tmp);
- p.fillRect(0, 0, tmp.width(), tmp.height(), Qt::color0);
- p.setPen(Qt::color1);
- p.setFont(f);
- p.drawText(0, fm.ascent(), s);
- // save it
- pix = tmp;
- hotspot = QPoint(tmp.width() / 2, tmp.height() / 2);
- }
- }
- } else {
- pix = QPixmap(default_pm);
- hotspot = QPoint(default_pm_hotx, default_pm_hoty);
- }
- } else {
- hotspot = dragPrivate()->hotspot;
- }
-
- // Convert the image to NSImage:
- NSImage *image = (NSImage *)qt_mac_create_nsimage(pix);
- [image retain];
-
- DnDParams *dndParams = macCurrentDnDParameters();
- QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(dndParams->view);
-
- // Save supported actions:
- [theView setSupportedActions: qt_mac_mapDropActions(dragPrivate()->possible_actions)];
- QPoint pointInView = [theView qt_qwidget]->mapFromGlobal(dndParams->globalPoint);
- NSPoint imageLoc = {pointInView.x() - hotspot.x(), pointInView.y() + pix.height() - hotspot.y()};
- NSSize mouseOffset = {0.0, 0.0};
- NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
- dragPrivate()->executed_action = Qt::ActionMask;
-
- // Execute the drag:
- [theView retain];
- [theView dragImage:image
- at:imageLoc
- offset:mouseOffset
- event:dndParams->theEvent
- pasteboard:pboard
- source:theView
- slideBack:YES];
-
- // Reset the implicit grab widget when drag ends because we will not
- // receive the mouse release event when DND is active:
- qt_button_down = 0;
- [theView release];
- [image release];
- if (dragPrivate())
- dragPrivate()->executed_action = Qt::IgnoreAction;
- object = 0;
- Qt::DropAction performedAction(qt_mac_mapNSDragOperation(dndParams->performedAction));
-
- // Do post drag processing, if required.
- if (performedAction != Qt::IgnoreAction) {
- // Check if the receiver points us to a file location.
- // if so, we need to do the file copy/move ourselves.
- QCFType<CFURLRef> pasteLocation = 0;
- PasteboardCopyPasteLocation(dragBoard.pasteBoard(), &pasteLocation);
- if (pasteLocation) {
- QList<QUrl> urls = o->mimeData()->urls();
- for (int i = 0; i < urls.size(); ++i) {
- QUrl fromUrl = urls.at(i);
- QString filename = QFileInfo(fromUrl.path()).fileName();
- QUrl toUrl(QCFString::toQString(CFURLGetString(pasteLocation)) + filename);
- if (performedAction == Qt::MoveAction)
- QFile::rename(fromUrl.path(), toUrl.path());
- else if (performedAction == Qt::CopyAction)
- QFile::copy(fromUrl.path(), toUrl.path());
- }
- }
- }
-
- // Clean-up:
- o->setMimeData(0);
- o->deleteLater();
- return performedAction;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/platforms/mac/qcocoaview_mac_p.h b/src/gui/platforms/mac/qcocoaview_mac_p.h
deleted file mode 100644
index cc79b6705b..0000000000
--- a/src/gui/platforms/mac/qcocoaview_mac_p.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qevent.h>
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-@class QT_MANGLE_NAMESPACE(QCocoaView);
-QT_FORWARD_DECLARE_CLASS(QWidgetPrivate);
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_FORWARD_DECLARE_CLASS(QEvent);
-QT_FORWARD_DECLARE_CLASS(QString);
-QT_FORWARD_DECLARE_CLASS(QStringList);
-
-Q_GUI_EXPORT
-@interface QT_MANGLE_NAMESPACE(QCocoaView) : NSControl <NSTextInput> {
- QWidget *qwidget;
- QWidgetPrivate *qwidgetprivate;
- NSDragOperation supportedActions;
- bool composing;
- int composingLength;
- bool sendKeyEvents;
- bool fromKeyDownEvent;
- QString *composingText;
- @public int alienTouchCount;
-}
-- (id)initWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate;
-- (void) finishInitWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate;
-- (void)frameDidChange:(NSNotification *)note;
-- (void)setSupportedActions:(NSDragOperation)actions;
-- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal;
-- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation;
-- (BOOL)isComposing;
-- (QWidget *)qt_qwidget;
-- (void) qt_clearQWidget;
-
-@end
-#endif
diff --git a/src/gui/platforms/mac/qcocoawindow_mac.mm b/src/gui/platforms/mac/qcocoawindow_mac.mm
deleted file mode 100644
index 6e5023aaca..0000000000
--- a/src/gui/platforms/mac/qcocoawindow_mac.mm
+++ /dev/null
@@ -1,90 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <private/qcocoawindow_mac_p.h>
-#import <private/qcocoawindowdelegate_mac_p.h>
-#import <private/qcocoaview_mac_p.h>
-#import <private/qt_cocoa_helpers_mac_p.h>
-#import <private/qcocoawindowcustomthemeframe_mac_p.h>
-#import <private/qcocoaapplication_mac_p.h>
-#import <private/qdnd_p.h>
-#import <private/qmultitouch_mac_p.h>
-
-#include <QtGui/QWidget>
-
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_USE_NAMESPACE
-
-@implementation NSWindow (QT_MANGLE_NAMESPACE(QWidgetIntegration))
-
-- (id)QT_MANGLE_NAMESPACE(qt_initWithQWidget):(QWidget*)widget contentRect:(NSRect)rect styleMask:(NSUInteger)mask
-{
- self = [self initWithContentRect:rect styleMask:mask backing:NSBackingStoreBuffered defer:YES];
- if (self) {
- [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] becomeDelegteForWindow:self widget:widget];
- [self setReleasedWhenClosed:NO];
- }
- return self;
-}
-
-- (QWidget *)QT_MANGLE_NAMESPACE(qt_qwidget)
-{
- QWidget *widget = 0;
- if ([self delegate] == [QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate])
- widget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
- return widget;
-}
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaWindow)
-
-/***********************************************************************
- Copy and Paste between QCocoaWindow and QCocoaPanel
- This is a bit unfortunate, but thanks to the dynamic dispatch we
- have to duplicate this code or resort to really silly forwarding methods
-**************************************************************************/
-#include "qcocoasharedwindowmethods_mac_p.h"
-
-@end
-#endif
diff --git a/src/gui/platforms/mac/qcocoawindow_mac_p.h b/src/gui/platforms/mac/qcocoawindow_mac_p.h
deleted file mode 100644
index d567cab244..0000000000
--- a/src/gui/platforms/mac/qcocoawindow_mac_p.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QCOCOAWINDOW_MAC_P
-#define QCOCOAWINDOW_MAC_P
-
-#ifdef QT_MAC_USE_COCOA
-#include "qmacdefines_mac.h"
-#import <Cocoa/Cocoa.h>
-#include <private/qapplication_p.h>
-#include <private/qbackingstore_p.h>
-
-enum { QtMacCustomizeWindow = 1 << 21 }; // This will one day be run over by
-
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_FORWARD_DECLARE_CLASS(QStringList);
-QT_FORWARD_DECLARE_CLASS(QCocoaDropData);
-
-@interface NSWindow (QtCoverForHackWithCategory)
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
-@end
-
-@interface NSWindow (QT_MANGLE_NAMESPACE(QWidgetIntegration))
-- (id)QT_MANGLE_NAMESPACE(qt_initWithQWidget):(QWidget *)widget contentRect:(NSRect)rect styleMask:(NSUInteger)mask;
-- (QWidget *)QT_MANGLE_NAMESPACE(qt_qwidget);
-@end
-
-@interface NSWindow (QtIntegration)
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender;
-- (void)draggingExited:(id <NSDraggingInfo>)sender;
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
-@end
-
-@interface QT_MANGLE_NAMESPACE(QCocoaWindow) : NSWindow {
- QStringList *currentCustomDragTypes;
- QCocoaDropData *dropData;
- NSInteger dragEnterSequence;
-}
-
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
-- (void)registerDragTypes;
-- (void)drawRectOriginal:(NSRect)rect;
-
-@end
-#endif
-
-#endif
diff --git a/src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac.mm b/src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac.mm
deleted file mode 100644
index b761934c01..0000000000
--- a/src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac.mm
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmacdefines_mac.h"
-
-#ifdef QT_MAC_USE_COCOA
-
-#import "private/qcocoawindowcustomthemeframe_mac_p.h"
-#import "private/qcocoawindow_mac_p.h"
-#include "private/qt_cocoa_helpers_mac_p.h"
-#include "qwidget.h"
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaWindowCustomThemeFrame)
-
-- (void)_updateButtons
-{
- [super _updateButtons];
- NSWindow *window = [self window];
- qt_syncCocoaTitleBarButtons(window, [window QT_MANGLE_NAMESPACE(qt_qwidget)]);
-}
-
-@end
-
-#endif
diff --git a/src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac_p.h b/src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac_p.h
deleted file mode 100644
index 09b40875f6..0000000000
--- a/src/gui/platforms/mac/qcocoawindowcustomthemeframe_mac_p.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-#import <Cocoa/Cocoa.h>
-#include "qmacdefines_mac.h"
-#import "qnsthemeframe_mac_p.h"
-
-@interface QT_MANGLE_NAMESPACE(QCocoaWindowCustomThemeFrame) : NSThemeFrame
-{
-}
-
-@end
diff --git a/src/gui/platforms/mac/qcocoawindowdelegate_mac.mm b/src/gui/platforms/mac/qcocoawindowdelegate_mac.mm
deleted file mode 100644
index 1faf068a12..0000000000
--- a/src/gui/platforms/mac/qcocoawindowdelegate_mac.mm
+++ /dev/null
@@ -1,439 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#import "private/qcocoawindowdelegate_mac_p.h"
-#ifdef QT_MAC_USE_COCOA
-#include <private/qwidget_p.h>
-#include <private/qapplication_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <qevent.h>
-#include <qlayout.h>
-#include <qcoreapplication.h>
-#include <qmenubar.h>
-#include <QMainWindow>
-#include <QToolBar>
-#include <private/qmainwindowlayout_p.h>
-
-QT_BEGIN_NAMESPACE
-extern QWidgetData *qt_qwidget_data(QWidget *); // qwidget.cpp
-extern void onApplicationWindowChangedActivation(QWidget *, bool); //qapplication_mac.mm
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); // qapplication.cpp
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-static QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) *sharedCocoaWindowDelegate = nil;
-
-// This is a singleton, but unlike most Cocoa singletons, it lives in a library and could be
-// pontentially loaded and unloaded. This means we should at least attempt to do the
-// memory management correctly.
-
-static void cleanupCocoaWindowDelegate()
-{
- [sharedCocoaWindowDelegate release];
-}
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaWindowDelegate)
-
-- (id)init
-{
- self = [super init];
- if (self != nil) {
- m_windowHash = new QHash<NSWindow *, QWidget *>();
- m_drawerHash = new QHash<NSDrawer *, QWidget *>();
- }
- return self;
-}
-
-- (void)dealloc
-{
- sharedCocoaWindowDelegate = nil;
- QHash<NSWindow *, QWidget *>::const_iterator windowIt = m_windowHash->constBegin();
- while (windowIt != m_windowHash->constEnd()) {
- [windowIt.key() setDelegate:nil];
- ++windowIt;
- }
- delete m_windowHash;
- QHash<NSDrawer *, QWidget *>::const_iterator drawerIt = m_drawerHash->constBegin();
- while (drawerIt != m_drawerHash->constEnd()) {
- [drawerIt.key() setDelegate:nil];
- ++drawerIt;
- }
- delete m_drawerHash;
- [super dealloc];
-}
-
-+ (id)allocWithZone:(NSZone *)zone
-{
- @synchronized(self) {
- if (sharedCocoaWindowDelegate == nil) {
- sharedCocoaWindowDelegate = [super allocWithZone:zone];
- return sharedCocoaWindowDelegate;
- qAddPostRoutine(cleanupCocoaWindowDelegate);
- }
- }
- return nil;
-}
-
-+ (QT_MANGLE_NAMESPACE(QCocoaWindowDelegate)*)sharedDelegate
-{
- @synchronized(self) {
- if (sharedCocoaWindowDelegate == nil)
- [[self alloc] init];
- }
- return [[sharedCocoaWindowDelegate retain] autorelease];
-}
-
--(void)syncSizeForWidget:(QWidget *)qwidget toSize:(const QSize &)newSize fromSize:(const QSize &)oldSize
-{
- qt_qwidget_data(qwidget)->crect.setSize(newSize);
- // ### static contents optimization needs to go here
- const OSViewRef view = qt_mac_nativeview_for(qwidget);
- [view setFrameSize:NSMakeSize(newSize.width(), newSize.height())];
- if (!qwidget->isVisible()) {
- qwidget->setAttribute(Qt::WA_PendingResizeEvent, true);
- } else {
- QResizeEvent qre(newSize, oldSize);
- if (qwidget->testAttribute(Qt::WA_PendingResizeEvent)) {
- qwidget->setAttribute(Qt::WA_PendingResizeEvent, false);
- QApplication::sendEvent(qwidget, &qre);
- } else {
- qt_sendSpontaneousEvent(qwidget, &qre);
- }
- }
-}
-
-- (void)dumpMaximizedStateforWidget:(QWidget*)qwidget window:(NSWindow *)window
-{
- if (!window)
- return; // Nothing to do.
- QWidgetData *widgetData = qt_qwidget_data(qwidget);
- if ((widgetData->window_state & Qt::WindowMaximized) && ![window isZoomed]) {
- widgetData->window_state &= ~Qt::WindowMaximized;
- QWindowStateChangeEvent e(Qt::WindowState(widgetData->window_state | Qt::WindowMaximized));
- qt_sendSpontaneousEvent(qwidget, &e);
- }
-}
-
-- (NSSize)closestAcceptableSizeForWidget:(QWidget *)qwidget window:(NSWindow *)window
- withNewSize:(NSSize)proposedSize
-{
- [self dumpMaximizedStateforWidget:qwidget window:window];
- QSize newSize = QLayout::closestAcceptableSize(qwidget,
- QSize(proposedSize.width, proposedSize.height));
- return [NSWindow frameRectForContentRect:
- NSMakeRect(0., 0., newSize.width(), newSize.height())
- styleMask:[window styleMask]].size;
-}
-
-- (NSSize)windowWillResize:(NSWindow *)windowToResize toSize:(NSSize)proposedFrameSize
-{
- QWidget *qwidget = m_windowHash->value(windowToResize);
- return [self closestAcceptableSizeForWidget:qwidget window:windowToResize
- withNewSize:[NSWindow contentRectForFrameRect:
- NSMakeRect(0, 0,
- proposedFrameSize.width,
- proposedFrameSize.height)
- styleMask:[windowToResize styleMask]].size];
-}
-
-- (NSSize)drawerWillResizeContents:(NSDrawer *)sender toSize:(NSSize)contentSize
-{
- QWidget *qwidget = m_drawerHash->value(sender);
- return [self closestAcceptableSizeForWidget:qwidget window:nil withNewSize:contentSize];
-}
-
--(void)windowDidMiniaturize:(NSNotification*)notification
-{
- QWidget *qwidget = m_windowHash->value([notification object]);
- if (!qwidget->isMinimized()) {
- QWidgetData *widgetData = qt_qwidget_data(qwidget);
- widgetData->window_state = widgetData->window_state | Qt::WindowMinimized;
- QWindowStateChangeEvent e(Qt::WindowStates(widgetData->window_state & ~Qt::WindowMinimized));
- qt_sendSpontaneousEvent(qwidget, &e);
- }
- // Send hide to match Qt on X11 and Windows
- QEvent e(QEvent::Hide);
- qt_sendSpontaneousEvent(qwidget, &e);
-}
-
-- (void)windowDidResize:(NSNotification *)notification
-{
- NSWindow *window = [notification object];
- QWidget *qwidget = m_windowHash->value(window);
- QWidgetData *widgetData = qt_qwidget_data(qwidget);
- if (!(qwidget->windowState() & (Qt::WindowMaximized | Qt::WindowFullScreen)) && [window isZoomed]) {
- widgetData->window_state = widgetData->window_state | Qt::WindowMaximized;
- QWindowStateChangeEvent e(Qt::WindowStates(widgetData->window_state
- & ~Qt::WindowMaximized));
- qt_sendSpontaneousEvent(qwidget, &e);
- } else {
- widgetData->window_state = widgetData->window_state & ~Qt::WindowMaximized;
- QWindowStateChangeEvent e(Qt::WindowStates(widgetData->window_state
- | Qt::WindowMaximized));
- qt_sendSpontaneousEvent(qwidget, &e);
- }
- NSRect rect = [[window contentView] frame];
- const QSize newSize(rect.size.width, rect.size.height);
- const QSize &oldSize = widgetData->crect.size();
- if (newSize != oldSize) {
- QWidgetPrivate::qt_mac_update_sizer(qwidget);
- [self syncSizeForWidget:qwidget toSize:newSize fromSize:oldSize];
- }
-
- // We force the repaint to be synchronized with the resize of the window.
- // Otherwise, the resize looks sluggish because we paint one event loop later.
- if ([[window contentView] inLiveResize]) {
- qwidget->repaint();
-
- // We need to repaint the toolbar as well.
- QMainWindow* mWindow = qobject_cast<QMainWindow*>(qwidget->window());
- if (mWindow) {
- QMainWindowLayout *mLayout = qobject_cast<QMainWindowLayout*>(mWindow->layout());
- QList<QToolBar *> toolbarList = mLayout->qtoolbarsInUnifiedToolbarList;
-
- for (int i = 0; i < toolbarList.size(); ++i) {
- QToolBar* toolbar = toolbarList.at(i);
- toolbar->repaint();
- }
- }
- }
-}
-
-- (void)windowDidMove:(NSNotification *)notification
-{
- // The code underneath needs to translate the window location
- // from bottom left (which is the origin used by Cocoa) to
- // upper left (which is the origin used by Qt):
- NSWindow *window = [notification object];
- NSRect newRect = [window frame];
- QWidget *qwidget = m_windowHash->value(window);
- QPoint qtPoint = flipPoint(NSMakePoint(newRect.origin.x,
- newRect.origin.y + newRect.size.height)).toPoint();
- const QRect &oldRect = qwidget->frameGeometry();
-
- if (qtPoint.x() != oldRect.x() || qtPoint.y() != oldRect.y()) {
- QWidgetData *widgetData = qt_qwidget_data(qwidget);
- QRect oldCRect = widgetData->crect;
- QWidgetPrivate *widgetPrivate = qt_widget_private(qwidget);
- const QRect &fStrut = widgetPrivate->frameStrut();
- widgetData->crect.moveTo(qtPoint.x() + fStrut.left(), qtPoint.y() + fStrut.top());
- if (!qwidget->isVisible()) {
- qwidget->setAttribute(Qt::WA_PendingMoveEvent, true);
- } else {
- QMoveEvent qme(qtPoint, oldRect.topLeft());
- qt_sendSpontaneousEvent(qwidget, &qme);
- }
- }
-}
-
--(BOOL)windowShouldClose:(id)windowThatWantsToClose
-{
- QWidget *qwidget = m_windowHash->value(windowThatWantsToClose);
- QScopedLoopLevelCounter counter(qt_widget_private(qwidget)->threadData);
- return qt_widget_private(qwidget)->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-}
-
--(void)windowDidDeminiaturize:(NSNotification *)notification
-{
- QWidget *qwidget = m_windowHash->value([notification object]);
- QWidgetData *widgetData = qt_qwidget_data(qwidget);
- Qt::WindowStates currState = Qt::WindowStates(widgetData->window_state);
- Qt::WindowStates newState = currState;
- if (currState & Qt::WindowMinimized)
- newState &= ~Qt::WindowMinimized;
- if (!(currState & Qt::WindowActive))
- newState |= Qt::WindowActive;
- if (newState != currState) {
- widgetData->window_state = newState;
- QWindowStateChangeEvent e(currState);
- qt_sendSpontaneousEvent(qwidget, &e);
- }
- QShowEvent qse;
- qt_sendSpontaneousEvent(qwidget, &qse);
-}
-
--(void)windowDidBecomeMain:(NSNotification*)notification
-{
- QWidget *qwidget = m_windowHash->value([notification object]);
- Q_ASSERT(qwidget);
- onApplicationWindowChangedActivation(qwidget, true);
-}
-
--(void)windowDidResignMain:(NSNotification*)notification
-{
- QWidget *qwidget = m_windowHash->value([notification object]);
- Q_ASSERT(qwidget);
- onApplicationWindowChangedActivation(qwidget, false);
-}
-
-// These are the same as main, but they are probably better to keep separate since there is a
-// tiny difference between main and key windows.
--(void)windowDidBecomeKey:(NSNotification*)notification
-{
- QWidget *qwidget = m_windowHash->value([notification object]);
- Q_ASSERT(qwidget);
- onApplicationWindowChangedActivation(qwidget, true);
-}
-
--(void)windowDidResignKey:(NSNotification*)notification
-{
- QWidget *qwidget = m_windowHash->value([notification object]);
- Q_ASSERT(qwidget);
- onApplicationWindowChangedActivation(qwidget, false);
-}
-
--(QWidget *)qt_qwidgetForWindow:(NSWindow *)window
-{
- return m_windowHash->value(window);
-}
-
-- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame
-{
- Q_UNUSED(newFrame);
- // saving the current window geometry before the window is maximized
- QWidget *qwidget = m_windowHash->value(window);
- QWidgetPrivate *widgetPrivate = qt_widget_private(qwidget);
- if (qwidget->isWindow()) {
- if(qwidget->windowState() & Qt::WindowMaximized) {
- // Restoring
- widgetPrivate->topData()->wasMaximized = false;
- } else {
- // Maximizing
- widgetPrivate->topData()->normalGeometry = qwidget->geometry();
- // If the window was maximized we need to update the coordinates since now it will start at 0,0.
- // We do this in a special field that is only used when not restoring but manually resizing the window.
- // Since the coordinates are fixed we just set a boolean flag.
- widgetPrivate->topData()->wasMaximized = true;
- }
- }
- return YES;
-}
-
-- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)defaultFrame
-{
- NSRect frameToReturn = defaultFrame;
- QWidget *qwidget = m_windowHash->value(window);
- QSizeF size = qwidget->maximumSize();
- NSRect windowFrameRect = [window frame];
- NSRect viewFrameRect = [[window contentView] frame];
- // consider additional size required for titlebar & frame
- frameToReturn.size.width = qMin<CGFloat>(frameToReturn.size.width,
- size.width()+(windowFrameRect.size.width - viewFrameRect.size.width));
- frameToReturn.size.height = qMin<CGFloat>(frameToReturn.size.height,
- size.height()+(windowFrameRect.size.height - viewFrameRect.size.height));
- return frameToReturn;
-}
-
-- (void)becomeDelegteForWindow:(NSWindow *)window widget:(QWidget *)widget
-{
- m_windowHash->insert(window, widget);
- [window setDelegate:self];
-}
-
-- (void)resignDelegateForWindow:(NSWindow *)window
-{
- [window setDelegate:nil];
- m_windowHash->remove(window);
-}
-
-- (void)becomeDelegateForDrawer:(NSDrawer *)drawer widget:(QWidget *)widget
-{
- m_drawerHash->insert(drawer, widget);
- [drawer setDelegate:self];
- NSWindow *window = [[drawer contentView] window];
- [self becomeDelegteForWindow:window widget:widget];
-}
-
-- (void)resignDelegateForDrawer:(NSDrawer *)drawer
-{
- QWidget *widget = m_drawerHash->value(drawer);
- [drawer setDelegate:nil];
- if (widget)
- [self resignDelegateForWindow:[[drawer contentView] window]];
- m_drawerHash->remove(drawer);
-}
-
-- (BOOL)window:(NSWindow *)window shouldPopUpDocumentPathMenu:(NSMenu *)menu
-{
- Q_UNUSED(menu);
- QWidget *qwidget = m_windowHash->value(window);
- if (qwidget && !qwidget->windowFilePath().isEmpty()) {
- return YES;
- }
- return NO;
-}
-
-- (BOOL)window:(NSWindow *)window shouldDragDocumentWithEvent:(NSEvent *)event
- from:(NSPoint)dragImageLocation
- withPasteboard:(NSPasteboard *)pasteboard
-{
- Q_UNUSED(event);
- Q_UNUSED(dragImageLocation);
- Q_UNUSED(pasteboard);
- QWidget *qwidget = m_windowHash->value(window);
- if (qwidget && !qwidget->windowFilePath().isEmpty()) {
- return YES;
- }
- return NO;
-}
-
-- (void)syncContentViewFrame: (NSNotification *)notification
-{
- NSView *cView = [notification object];
- if (cView) {
- NSWindow *window = [cView window];
- QWidget *qwidget = m_windowHash->value(window);
- if (qwidget) {
- QWidgetData *widgetData = qt_qwidget_data(qwidget);
- NSRect rect = [cView frame];
- const QSize newSize(rect.size.width, rect.size.height);
- const QSize &oldSize = widgetData->crect.size();
- if (newSize != oldSize) {
- [self syncSizeForWidget:qwidget toSize:newSize fromSize:oldSize];
- }
- }
-
- }
-}
-
-@end
-#endif// QT_MAC_USE_COCOA
diff --git a/src/gui/platforms/mac/qcocoawindowdelegate_mac_p.h b/src/gui/platforms/mac/qcocoawindowdelegate_mac_p.h
deleted file mode 100644
index 638ce2df9a..0000000000
--- a/src/gui/platforms/mac/qcocoawindowdelegate_mac_p.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmacdefines_mac.h"
-
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_BEGIN_NAMESPACE
-template <class Key, class T> class QHash;
-QT_END_NAMESPACE
-using QT_PREPEND_NAMESPACE(QHash);
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QSize)
-QT_FORWARD_DECLARE_CLASS(QWidgetData)
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-@protocol NSWindowDelegate <NSObject>
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize;
-- (void)windowDidMiniaturize:(NSNotification*)notification;
-- (void)windowDidResize:(NSNotification *)notification;
-- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)defaultFrame;
-- (void)windowDidMove:(NSNotification *)notification;
-- (BOOL)windowShouldClose:(id)window;
-- (void)windowDidDeminiaturize:(NSNotification *)notification;
-- (void)windowDidBecomeMain:(NSNotification*)notification;
-- (void)windowDidResignMain:(NSNotification*)notification;
-- (void)windowDidBecomeKey:(NSNotification*)notification;
-- (void)windowDidResignKey:(NSNotification*)notification;
-- (BOOL)window:(NSWindow *)window shouldPopUpDocumentPathMenu:(NSMenu *)menu;
-- (BOOL)window:(NSWindow *)window shouldDragDocumentWithEvent:(NSEvent *)event from:(NSPoint)dragImageLocation withPasteboard:(NSPasteboard *)pasteboard;
-- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame;
-@end
-
-@protocol NSDrawerDelegate <NSObject>
-- (NSSize)drawerWillResizeContents:(NSDrawer *)sender toSize:(NSSize)contentSize;
-@end
-
-#endif
-
-
-
-@interface QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) : NSObject<NSWindowDelegate, NSDrawerDelegate> {
- QHash<NSWindow *, QWidget *> *m_windowHash;
- QHash<NSDrawer *, QWidget *> *m_drawerHash;
-}
-+ (QT_MANGLE_NAMESPACE(QCocoaWindowDelegate)*)sharedDelegate;
-- (void)becomeDelegteForWindow:(NSWindow *)window widget:(QWidget *)widget;
-- (void)resignDelegateForWindow:(NSWindow *)window;
-- (void)becomeDelegateForDrawer:(NSDrawer *)drawer widget:(QWidget *)widget;
-- (void)resignDelegateForDrawer:(NSDrawer *)drawer;
-- (void)dumpMaximizedStateforWidget:(QWidget*)qwidget window:(NSWindow *)window;
-- (void)syncSizeForWidget:(QWidget *)qwidget
- toSize:(const QSize &)newSize
- fromSize:(const QSize &)oldSize;
-- (NSSize)closestAcceptableSizeForWidget:(QWidget *)qwidget
- window:(NSWindow *)window withNewSize:(NSSize)proposedSize;
-- (QWidget *)qt_qwidgetForWindow:(NSWindow *)window;
-- (void)syncContentViewFrame: (NSNotification *)notification;
-@end
-#endif
diff --git a/src/gui/platforms/mac/qcolormap_mac.cpp b/src/gui/platforms/mac/qcolormap_mac.cpp
deleted file mode 100644
index 28589f41b8..0000000000
--- a/src/gui/platforms/mac/qcolormap_mac.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolormap.h"
-#include "qcolor.h"
-
-QT_BEGIN_NAMESPACE
-
-class QColormapPrivate
-{
-public:
- inline QColormapPrivate()
- : ref(1)
- { }
-
- QAtomicInt ref;
-};
-static QColormap *qt_mac_global_map = 0;
-
-void QColormap::initialize()
-{
- qt_mac_global_map = new QColormap;
-}
-
-void QColormap::cleanup()
-{
- delete qt_mac_global_map;
- qt_mac_global_map = 0;
-}
-
-QColormap QColormap::instance(int)
-{
- return *qt_mac_global_map;
-}
-
-QColormap::QColormap() : d(new QColormapPrivate)
-{}
-
-QColormap::QColormap(const QColormap &colormap) :d (colormap.d)
-{ d->ref.ref(); }
-
-QColormap::~QColormap()
-{
- if (!d->ref.deref())
- delete d;
-}
-
-QColormap::Mode QColormap::mode() const
-{ return QColormap::Direct; }
-
-int QColormap::depth() const
-{
- return 32;
-}
-
-int QColormap::size() const
-{
- return -1;
-}
-
-uint QColormap::pixel(const QColor &color) const
-{ return color.rgba(); }
-
-const QColor QColormap::colorAt(uint pixel) const
-{ return QColor(pixel); }
-
-const QVector<QColor> QColormap::colormap() const
-{ return QVector<QColor>(); }
-
-QColormap &QColormap::operator=(const QColormap &colormap)
-{ qAtomicAssign(d, colormap.d); return *this; }
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qcursor_mac.mm b/src/gui/platforms/mac/qcursor_mac.mm
deleted file mode 100644
index 0afa3ee4f0..0000000000
--- a/src/gui/platforms/mac/qcursor_mac.mm
+++ /dev/null
@@ -1,689 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qcursor_p.h>
-#include <private/qpixmap_mac_p.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcursor.h>
-#include <qevent.h>
-#include <string.h>
-#include <unistd.h>
-#include <AppKit/NSCursor.h>
-#include <qpainter.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qapplication_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern QCursorData *qt_cursorTable[Qt::LastCursor + 1];
-extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
-extern GrafPtr qt_mac_qd_context(const QPaintDevice *); //qpaintdevice_mac.cpp
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); //qapplication_mac.cpp
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-
-/*****************************************************************************
- Internal QCursorData class
- *****************************************************************************/
-
-class QMacAnimateCursor : public QObject
-{
- int timerId, step;
- ThemeCursor curs;
-public:
- QMacAnimateCursor() : QObject(), timerId(-1) { }
- void start(ThemeCursor c) {
- step = 1;
- if(timerId != -1)
- killTimer(timerId);
- timerId = startTimer(300);
- curs = c;
- }
- void stop() {
- if(timerId != -1) {
- killTimer(timerId);
- timerId = -1;
- }
- }
-protected:
- void timerEvent(QTimerEvent *e) {
- if(e->timerId() == timerId) {
- /*
- if(SetAnimatedThemeCursor(curs, step++) == themeBadCursorIndexErr)
- stop();
- */
- }
- }
-};
-
-inline void *qt_mac_nsCursorForQCursor(const QCursor &c)
-{
- c.d->update();
- return [[static_cast<NSCursor *>(c.d->curs.cp.nscursor) retain] autorelease];
-}
-
-static QCursorData *currentCursor = 0; //current cursor
-
-void qt_mac_set_cursor(const QCursor *c)
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- [static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(*c)) set];
-#else
- if (!c) {
- currentCursor = 0;
- return;
- }
- c->handle(); //force the cursor to get loaded, if it's not
-
- if(currentCursor && currentCursor->type == QCursorData::TYPE_ThemeCursor
- && currentCursor->curs.tc.anim)
- currentCursor->curs.tc.anim->stop();
- if(c->d->type == QCursorData::TYPE_ImageCursor) {
- [static_cast<NSCursor *>(c->d->curs.cp.nscursor) set];
- } else if(c->d->type == QCursorData::TYPE_ThemeCursor) {
- if(SetAnimatedThemeCursor(c->d->curs.tc.curs, 0) == themeBadCursorIndexErr) {
- SetThemeCursor(c->d->curs.tc.curs);
- } else {
- if(!c->d->curs.tc.anim)
- c->d->curs.tc.anim = new QMacAnimateCursor;
- c->d->curs.tc.anim->start(c->d->curs.tc.curs);
- }
- }
-
- currentCursor = c->d;
-#endif
-}
-
-static QPointer<QWidget> lastWidgetUnderMouse = 0;
-static QPointer<QWidget> lastMouseCursorWidget = 0;
-static bool qt_button_down_on_prev_call = false;
-static QCursor *grabCursor = 0;
-
-void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse)
-{
- QCursor cursor(Qt::ArrowCursor);
- if (qt_button_down) {
- // The widget that is currently pressed
- // grabs the mouse cursor:
- widgetUnderMouse = qt_button_down;
- qt_button_down_on_prev_call = true;
- } else if (qt_button_down_on_prev_call) {
- // Grab has been released, so do
- // a full check:
- qt_button_down_on_prev_call = false;
- lastWidgetUnderMouse = 0;
- lastMouseCursorWidget = 0;
- }
-
- if (QApplication::overrideCursor()) {
- cursor = *QApplication::overrideCursor();
- } else if (grabCursor) {
- cursor = *grabCursor;
- } else if (widgetUnderMouse) {
- if (widgetUnderMouse == lastWidgetUnderMouse) {
- // Optimization that should hit when the widget under
- // the mouse does not change as the mouse moves:
- if (lastMouseCursorWidget)
- cursor = lastMouseCursorWidget->cursor();
- } else {
- QWidget *w = widgetUnderMouse;
- for (; w; w = w->parentWidget()) {
- if (w->testAttribute(Qt::WA_SetCursor)) {
- cursor = w->cursor();
- break;
- }
- if (w->isWindow())
- break;
- }
- // One final check in case we ran out of parents in the loop:
- if (w && !w->testAttribute(Qt::WA_SetCursor))
- w = 0;
-
- lastWidgetUnderMouse = widgetUnderMouse;
- lastMouseCursorWidget = w;
- }
- }
-
-#ifdef QT_MAC_USE_COCOA
- cursor.d->update();
- NSCursor *nsCursor = static_cast<NSCursor *>(cursor.d->curs.cp.nscursor);
- if ([NSCursor currentCursor] != nsCursor) {
- QMacCocoaAutoReleasePool pool;
- [nsCursor set];
- }
-#else
- qt_mac_set_cursor(&cursor);
-#endif
-}
-
-void qt_mac_update_cursor()
-{
- // This function is similar to qt_mac_updateCursorWithWidgetUnderMouse
- // except that is clears the optimization cache, and finds the widget
- // under mouse itself. Clearing the cache is useful in cases where the
- // application has been deactivated/activated etc.
- // NB: since we dont have any true native widget, the call to
- // qt_mac_getTargetForMouseEvent will fail when the mouse is over QMacNativeWidgets.
-#ifdef QT_MAC_USE_COCOA
- lastWidgetUnderMouse = 0;
- lastMouseCursorWidget = 0;
- QWidget *widgetUnderMouse = 0;
-
- if (qt_button_down) {
- widgetUnderMouse = qt_button_down;
- } else {
- QPoint localPoint;
- QPoint globalPoint;
- qt_mac_getTargetForMouseEvent(0, QEvent::None, localPoint, globalPoint, 0, &widgetUnderMouse);
- }
- qt_mac_updateCursorWithWidgetUnderMouse(widgetUnderMouse);
-#else
- qt_mac_updateCursorWithWidgetUnderMouse(QApplication::widgetAt(QCursor::pos()));
-#endif
-}
-
-void qt_mac_setMouseGrabCursor(bool set, QCursor *const cursor = 0)
-{
- if (grabCursor) {
- delete grabCursor;
- grabCursor = 0;
- }
- if (set) {
- if (cursor)
- grabCursor = new QCursor(*cursor);
- else if (lastMouseCursorWidget)
- grabCursor = new QCursor(lastMouseCursorWidget->cursor());
- else
- grabCursor = new QCursor(Qt::ArrowCursor);
- }
- qt_mac_update_cursor();
-}
-
-#ifndef QT_MAC_USE_COCOA
-void qt_mac_update_cursor_at_global_pos(const QPoint &globalPos)
-{
- qt_mac_updateCursorWithWidgetUnderMouse(QApplication::widgetAt(globalPos));
-}
-#endif
-
-static int nextCursorId = Qt::BitmapCursor;
-
-QCursorData::QCursorData(Qt::CursorShape s)
- : cshape(s), bm(0), bmm(0), hx(-1), hy(-1), mId(s), type(TYPE_None)
-{
- ref = 1;
- memset(&curs, '\0', sizeof(curs));
-}
-
-QCursorData::~QCursorData()
-{
- if (type == TYPE_ImageCursor) {
- if (curs.cp.my_cursor) {
- QMacCocoaAutoReleasePool pool;
- [static_cast<NSCursor *>(curs.cp.nscursor) release];
- }
- } else if(type == TYPE_ThemeCursor) {
- delete curs.tc.anim;
- }
- type = TYPE_None;
-
- delete bm;
- delete bmm;
- if(currentCursor == this)
- currentCursor = 0;
-}
-
-QCursorData *QCursorData::setBitmap(const QBitmap &bitmap, const QBitmap &mask, int hotX, int hotY)
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (bitmap.depth() != 1 || mask.depth() != 1 || bitmap.size() != mask.size()) {
- qWarning("Qt: QCursor: Cannot create bitmap cursor; invalid bitmap(s)");
- QCursorData *c = qt_cursorTable[0];
- c->ref.ref();
- return c;
- }
- // This is silly, but this is apparently called outside the constructor, so we have
- // to be ready for that case.
- QCursorData *x = new QCursorData;
- x->ref = 1;
- x->mId = ++nextCursorId;
- x->bm = new QBitmap(bitmap);
- x->bmm = new QBitmap(mask);
- x->cshape = Qt::BitmapCursor;
- x->hx = hotX >= 0 ? hotX : bitmap.width() / 2;
- x->hy = hotY >= 0 ? hotY : bitmap.height() / 2;
- return x;
-}
-
-Qt::HANDLE QCursor::handle() const
-{
- if(!QCursorData::initialized)
- QCursorData::initialize();
- if(d->type == QCursorData::TYPE_None)
- d->update();
- return (Qt::HANDLE)d->mId;
-}
-
-QPoint QCursor::pos()
-{
- return flipPoint([NSEvent mouseLocation]).toPoint();
-}
-
-void QCursor::setPos(int x, int y)
-{
-#ifdef QT_MAC_USE_COCOA
- CGPoint pos;
- pos.x = x;
- pos.y = y;
-
- CGEventRef e = CGEventCreateMouseEvent(0, kCGEventMouseMoved, pos, 0);
- CGEventPost(kCGHIDEventTap, e);
- CFRelease(e);
-#else
- CGWarpMouseCursorPosition(CGPointMake(x, y));
-
- /* I'm not too keen on doing this, but this makes it a lot easier, so I just
- send the event back through the event system and let it get propagated correctly
- ideally this would not really need to be faked --Sam
- */
- QWidget *widget = 0;
- if(QWidget *grb = QWidget::mouseGrabber())
- widget = grb;
- else
- widget = QApplication::widgetAt(QPoint(x, y));
- if(widget) {
- QMouseEvent me(QMouseEvent::MouseMove, widget->mapFromGlobal(QPoint(x, y)), Qt::NoButton,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- qt_sendSpontaneousEvent(widget, &me);
- }
-#endif
-}
-
-void QCursorData::initCursorFromBitmap()
-{
- NSImage *nsimage;
- QImage finalCursor(bm->size(), QImage::Format_ARGB32);
- QImage bmi = bm->toImage().convertToFormat(QImage::Format_RGB32);
- QImage bmmi = bmm->toImage().convertToFormat(QImage::Format_RGB32);
- for (int row = 0; row < finalCursor.height(); ++row) {
- QRgb *bmData = reinterpret_cast<QRgb *>(bmi.scanLine(row));
- QRgb *bmmData = reinterpret_cast<QRgb *>(bmmi.scanLine(row));
- QRgb *finalData = reinterpret_cast<QRgb *>(finalCursor.scanLine(row));
- for (int col = 0; col < finalCursor.width(); ++col) {
- if (bmmData[col] == 0xff000000 && bmData[col] == 0xffffffff) {
- finalData[col] = 0xffffffff;
- } else if (bmmData[col] == 0xff000000 && bmData[col] == 0xffffffff) {
- finalData[col] = 0x7f000000;
- } else if (bmmData[col] == 0xffffffff && bmData[col] == 0xffffffff) {
- finalData[col] = 0x00000000;
- } else {
- finalData[col] = 0xff000000;
- }
- }
- }
- type = QCursorData::TYPE_ImageCursor;
- curs.cp.my_cursor = true;
- QPixmap bmCopy = QPixmap::fromImage(finalCursor);
- NSPoint hotSpot = { hx, hy };
- nsimage = static_cast<NSImage*>(qt_mac_create_nsimage(bmCopy));
- curs.cp.nscursor = [[NSCursor alloc] initWithImage:nsimage hotSpot: hotSpot];
- [nsimage release];
-}
-
-void QCursorData::initCursorFromPixmap()
-{
- type = QCursorData::TYPE_ImageCursor;
- curs.cp.my_cursor = true;
- NSPoint hotSpot = { hx, hy };
- NSImage *nsimage;
- nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(pixmap));
- curs.cp.nscursor = [[NSCursor alloc] initWithImage:nsimage hotSpot: hotSpot];
- [nsimage release];
-}
-
-void QCursorData::update()
-{
- if(!QCursorData::initialized)
- QCursorData::initialize();
- if(type != QCursorData::TYPE_None)
- return;
-
- /* Note to self... ***
- * mask x data
- * 0xFF x 0x00 == fully opaque white
- * 0x00 x 0xFF == xor'd black
- * 0xFF x 0xFF == fully opaque black
- * 0x00 x 0x00 == fully transparent
- */
-
- if (hx < 0)
- hx = 0;
- if (hy < 0)
- hy = 0;
-
-#define QT_USE_APPROXIMATE_CURSORS
-#ifdef QT_USE_APPROXIMATE_CURSORS
- static const uchar cur_ver_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xc0, 0x07, 0xe0, 0x0f, 0xf0,
- 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x0f, 0xf0,
- 0x07, 0xe0, 0x03, 0xc0, 0x01, 0x80, 0x00, 0x00 };
- static const uchar mcur_ver_bits[] = {
- 0x00, 0x00, 0x03, 0x80, 0x07, 0xc0, 0x0f, 0xe0, 0x1f, 0xf0, 0x3f, 0xf8,
- 0x7f, 0xfc, 0x07, 0xc0, 0x07, 0xc0, 0x07, 0xc0, 0x7f, 0xfc, 0x3f, 0xf8,
- 0x1f, 0xf0, 0x0f, 0xe0, 0x07, 0xc0, 0x03, 0x80 };
-
- static const uchar cur_hor_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x20, 0x18, 0x30,
- 0x38, 0x38, 0x7f, 0xfc, 0x7f, 0xfc, 0x38, 0x38, 0x18, 0x30, 0x08, 0x20,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar mcur_hor_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x04, 0x40, 0x0c, 0x60, 0x1c, 0x70, 0x3c, 0x78,
- 0x7f, 0xfc, 0xff, 0xfe, 0xff, 0xfe, 0xff, 0xfe, 0x7f, 0xfc, 0x3c, 0x78,
- 0x1c, 0x70, 0x0c, 0x60, 0x04, 0x40, 0x00, 0x00 };
-
- static const uchar cur_fdiag_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf8, 0x00, 0xf8, 0x00, 0x78,
- 0x00, 0xf8, 0x01, 0xd8, 0x23, 0x88, 0x37, 0x00, 0x3e, 0x00, 0x3c, 0x00,
- 0x3e, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar mcur_fdiag_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x07, 0xfc, 0x03, 0xfc, 0x01, 0xfc, 0x00, 0xfc,
- 0x41, 0xfc, 0x63, 0xfc, 0x77, 0xdc, 0x7f, 0x8c, 0x7f, 0x04, 0x7e, 0x00,
- 0x7f, 0x00, 0x7f, 0x80, 0x7f, 0xc0, 0x00, 0x00 };
-
- static const uchar cur_bdiag_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x3e, 0x00, 0x3c, 0x00, 0x3e, 0x00,
- 0x37, 0x00, 0x23, 0x88, 0x01, 0xd8, 0x00, 0xf8, 0x00, 0x78, 0x00, 0xf8,
- 0x01, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar mcur_bdiag_bits[] = {
- 0x00, 0x00, 0x7f, 0xc0, 0x7f, 0x80, 0x7f, 0x00, 0x7e, 0x00, 0x7f, 0x04,
- 0x7f, 0x8c, 0x77, 0xdc, 0x63, 0xfc, 0x41, 0xfc, 0x00, 0xfc, 0x01, 0xfc,
- 0x03, 0xfc, 0x07, 0xfc, 0x00, 0x00, 0x00, 0x00 };
-
- static const unsigned char cur_up_arrow_bits[] = {
- 0x00, 0x80, 0x01, 0x40, 0x01, 0x40, 0x02, 0x20, 0x02, 0x20, 0x04, 0x10,
- 0x04, 0x10, 0x08, 0x08, 0x0f, 0x78, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40,
- 0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0xc0 };
- static const unsigned char mcur_up_arrow_bits[] = {
- 0x00, 0x80, 0x01, 0xc0, 0x01, 0xc0, 0x03, 0xe0, 0x03, 0xe0, 0x07, 0xf0,
- 0x07, 0xf0, 0x0f, 0xf8, 0x0f, 0xf8, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0,
- 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0 };
-#endif
- const uchar *cursorData = 0;
- const uchar *cursorMaskData = 0;
-#ifdef QT_MAC_USE_COCOA
- switch (cshape) { // map Q cursor to MAC cursor
- case Qt::BitmapCursor: {
- if (pixmap.isNull())
- initCursorFromBitmap();
- else
- initCursorFromPixmap();
- break; }
- case Qt::BlankCursor: {
- pixmap = QPixmap(16, 16);
- pixmap.fill(Qt::transparent);
- initCursorFromPixmap();
- break; }
- case Qt::ArrowCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor arrowCursor];
- break; }
- case Qt::CrossCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor crosshairCursor];
- break; }
- case Qt::WaitCursor: {
- pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/spincursor.png"));
- initCursorFromPixmap();
- break; }
- case Qt::IBeamCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor IBeamCursor];
- break; }
- case Qt::SizeAllCursor: {
- pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/pluscursor.png"));
- initCursorFromPixmap();
- break; }
- case Qt::WhatsThisCursor: { //for now just use the pointing hand
- case Qt::PointingHandCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor pointingHandCursor];
- break; }
- case Qt::BusyCursor: {
- pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/waitcursor.png"));
- initCursorFromPixmap();
- break; }
- case Qt::SplitVCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor resizeUpDownCursor];
- break; }
- case Qt::SplitHCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor resizeLeftRightCursor];
- break; }
- case Qt::ForbiddenCursor: {
- pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/forbiddencursor.png"));
- initCursorFromPixmap();
- break; }
- case Qt::OpenHandCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor openHandCursor];
- break;
- case Qt::ClosedHandCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor closedHandCursor];
- break;
- case Qt::DragCopyCursor:
- type = QCursorData::TYPE_ThemeCursor;
- if ([NSCursor respondsToSelector:@selector(dragCopyCursor)])
- curs.cp.nscursor = [NSCursor performSelector:@selector(dragCopyCursor)];
- break;
- case Qt::DragMoveCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.cp.nscursor = [NSCursor arrowCursor];
- break;
- case Qt::DragLinkCursor:
- type = QCursorData::TYPE_ThemeCursor;
- if ([NSCursor respondsToSelector:@selector(dragLinkCursor)])
- curs.cp.nscursor = [NSCursor performSelector:@selector(dragLinkCursor)];
- break;
-#define QT_USE_APPROXIMATE_CURSORS
-#ifdef QT_USE_APPROXIMATE_CURSORS
- case Qt::SizeVerCursor:
- cursorData = cur_ver_bits;
- cursorMaskData = mcur_ver_bits;
- hx = hy = 8;
- break;
- case Qt::SizeHorCursor:
- cursorData = cur_hor_bits;
- cursorMaskData = mcur_hor_bits;
- hx = hy = 8;
- break;
- case Qt::SizeBDiagCursor:
- cursorData = cur_fdiag_bits;
- cursorMaskData = mcur_fdiag_bits;
- hx = hy = 8;
- break;
- case Qt::SizeFDiagCursor:
- cursorData = cur_bdiag_bits;
- cursorMaskData = mcur_bdiag_bits;
- hx = hy = 8;
- break;
- case Qt::UpArrowCursor:
- cursorData = cur_up_arrow_bits;
- cursorMaskData = mcur_up_arrow_bits;
- hx = 8;
- break;
-#endif
- default:
- qWarning("Qt: QCursor::update: Invalid cursor shape %d", cshape);
- return;
- }
-#else
- // Carbon
- switch (cshape) { // map Q cursor to MAC cursor
- case Qt::BitmapCursor: {
- if (pixmap.isNull())
- initCursorFromBitmap();
- else
- initCursorFromPixmap();
- break; }
- case Qt::BlankCursor: {
- pixmap = QPixmap(16, 16);
- pixmap.fill(Qt::transparent);
- initCursorFromPixmap();
- break; }
- case Qt::ArrowCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeArrowCursor;
- break; }
- case Qt::CrossCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeCrossCursor;
- break; }
- case Qt::WaitCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeWatchCursor;
- break; }
- case Qt::IBeamCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeIBeamCursor;
- break; }
- case Qt::SizeAllCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemePlusCursor;
- break; }
- case Qt::WhatsThisCursor: { //for now just use the pointing hand
- case Qt::PointingHandCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemePointingHandCursor;
- break; }
- case Qt::BusyCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeSpinningCursor;
- break; }
- case Qt::SplitVCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeResizeUpDownCursor;
- break; }
- case Qt::SplitHCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeResizeLeftRightCursor;
- break; }
- case Qt::ForbiddenCursor: {
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeNotAllowedCursor;
- break; }
- case Qt::OpenHandCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeOpenHandCursor;
- break;
- case Qt::ClosedHandCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeClosedHandCursor;
- break;
- case Qt::DragMoveCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeArrowCursor;
- break;
- case Qt::DragCopyCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeCopyArrowCursor;
- break;
- case Qt::DragLinkCursor:
- type = QCursorData::TYPE_ThemeCursor;
- curs.tc.curs = kThemeAliasArrowCursor;
- break;
-#define QT_USE_APPROXIMATE_CURSORS
-#ifdef QT_USE_APPROXIMATE_CURSORS
- case Qt::SizeVerCursor:
- cursorData = cur_ver_bits;
- cursorMaskData = mcur_ver_bits;
- hx = hy = 8;
- break;
- case Qt::SizeHorCursor:
- cursorData = cur_hor_bits;
- cursorMaskData = mcur_hor_bits;
- hx = hy = 8;
- break;
- case Qt::SizeBDiagCursor:
- cursorData = cur_fdiag_bits;
- cursorMaskData = mcur_fdiag_bits;
- hx = hy = 8;
- break;
- case Qt::SizeFDiagCursor:
- cursorData = cur_bdiag_bits;
- cursorMaskData = mcur_bdiag_bits;
- hx = hy = 8;
- break;
- case Qt::UpArrowCursor:
- cursorData = cur_up_arrow_bits;
- cursorMaskData = mcur_up_arrow_bits;
- hx = 8;
- break;
-#endif
- default:
- qWarning("Qt: QCursor::update: Invalid cursor shape %d", cshape);
- return;
- }
-#endif
-
- if (cursorData) {
- bm = new QBitmap(QBitmap::fromData(QSize(16, 16), cursorData,
- QImage::Format_Mono));
- bmm = new QBitmap(QBitmap::fromData(QSize(16, 16), cursorMaskData,
- QImage::Format_Mono));
- initCursorFromBitmap();
- }
-
-#if 0
- if(type == QCursorData::TYPE_CursPtr && curs.cp.hcurs && curs.cp.my_cursor) {
- curs.cp.hcurs->hotSpot.h = hx >= 0 ? hx : 8;
- curs.cp.hcurs->hotSpot.v = hy >= 0 ? hy : 8;
- }
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qdesktopwidget_mac.mm b/src/gui/platforms/mac/qdesktopwidget_mac.mm
deleted file mode 100644
index 0b529c9843..0000000000
--- a/src/gui/platforms/mac/qdesktopwidget_mac.mm
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-#import <Cocoa/Cocoa.h>
-
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include <private/qt_mac_p.h>
-#include "qwidget_p.h"
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qdesktopwidget_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-
-/*****************************************************************************
- QDesktopWidget member functions
- *****************************************************************************/
-
-Q_GLOBAL_STATIC(QDesktopWidgetImplementation, qdesktopWidgetImplementation)
-
-QDesktopWidgetImplementation::QDesktopWidgetImplementation()
- : appScreen(0)
-{
- onResize();
-}
-
-QDesktopWidgetImplementation::~QDesktopWidgetImplementation()
-{
-}
-
-QDesktopWidgetImplementation *QDesktopWidgetImplementation::instance()
-{
- return qdesktopWidgetImplementation();
-}
-
-QRect QDesktopWidgetImplementation::availableRect(int screenIndex) const
-{
- if (screenIndex < 0 || screenIndex >= screenCount)
- screenIndex = appScreen;
-
- return availableRects[screenIndex].toRect();
-}
-
-QRect QDesktopWidgetImplementation::screenRect(int screenIndex) const
-{
- if (screenIndex < 0 || screenIndex >= screenCount)
- screenIndex = appScreen;
-
- return screenRects[screenIndex].toRect();
-}
-
-void QDesktopWidgetImplementation::onResize()
-{
- QMacCocoaAutoReleasePool pool;
- NSArray *displays = [NSScreen screens];
- screenCount = [displays count];
-
- screenRects.clear();
- availableRects.clear();
- NSRect primaryRect = [[displays objectAtIndex:0] frame];
- for (int i = 0; i<screenCount; i++) {
- NSRect r = [[displays objectAtIndex:i] frame];
- int flippedY = - r.origin.y + // account for position offset and
- primaryRect.size.height - r.size.height; // height difference.
- screenRects.append(QRectF(r.origin.x, flippedY,
- r.size.width, r.size.height));
-
- r = [[displays objectAtIndex:i] visibleFrame];
- flippedY = - r.origin.y + // account for position offset and
- primaryRect.size.height - r.size.height; // height difference.
- availableRects.append(QRectF(r.origin.x, flippedY,
- r.size.width, r.size.height));
- }
-}
-
-
-
-QDesktopWidget::QDesktopWidget()
- : QWidget(0, Qt::Desktop)
-{
- setObjectName(QLatin1String("desktop"));
- setAttribute(Qt::WA_WState_Visible);
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
- return true;
-}
-
-int QDesktopWidget::primaryScreen() const
-{
- return qdesktopWidgetImplementation()->appScreen;
-}
-
-int QDesktopWidget::numScreens() const
-{
- return qdesktopWidgetImplementation()->screenCount;
-}
-
-QWidget *QDesktopWidget::screen(int)
-{
- return this;
-}
-
-const QRect QDesktopWidget::availableGeometry(int screen) const
-{
- return qdesktopWidgetImplementation()->availableRect(screen);
-}
-
-const QRect QDesktopWidget::screenGeometry(int screen) const
-{
- return qdesktopWidgetImplementation()->screenRect(screen);
-}
-
-int QDesktopWidget::screenNumber(const QWidget *widget) const
-{
- QDesktopWidgetImplementation *d = qdesktopWidgetImplementation();
- if (!widget)
- return d->appScreen;
- QRect frame = widget->frameGeometry();
- if (!widget->isWindow())
- frame.moveTopLeft(widget->mapToGlobal(QPoint(0,0)));
- int maxSize = -1, maxScreen = -1;
- for (int i = 0; i < d->screenCount; ++i) {
- QRect rr = d->screenRect(i);
- QRect sect = rr.intersected(frame);
- int size = sect.width() * sect.height();
- if (size > maxSize && sect.width() > 0 && sect.height() > 0) {
- maxSize = size;
- maxScreen = i;
- }
- }
- return maxScreen;
-}
-
-int QDesktopWidget::screenNumber(const QPoint &point) const
-{
- QDesktopWidgetImplementation *d = qdesktopWidgetImplementation();
- int closestScreen = -1;
- int shortestDistance = INT_MAX;
- for (int i = 0; i < d->screenCount; ++i) {
- QRect rr = d->screenRect(i);
- int thisDistance = QWidgetPrivate::pointToRect(point, rr);
- if (thisDistance < shortestDistance) {
- shortestDistance = thisDistance;
- closestScreen = i;
- }
- }
- return closestScreen;
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
- QDesktopWidgetImplementation *d = qdesktopWidgetImplementation();
-
- const int oldScreenCount = d->screenCount;
- const QVector<QRectF> oldRects(d->screenRects);
- const QVector<QRectF> oldWorks(d->availableRects);
-
- d->onResize();
-
- for (int i = 0; i < qMin(oldScreenCount, d->screenCount); ++i) {
- if (oldRects.at(i) != d->screenRects.at(i))
- emit resized(i);
- }
- for (int i = 0; i < qMin(oldScreenCount, d->screenCount); ++i) {
- if (oldWorks.at(i) != d->availableRects.at(i))
- emit workAreaResized(i);
- }
-
- if (oldScreenCount != d->screenCount)
- emit screenCountChanged(d->screenCount);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qdesktopwidget_mac_p.h b/src/gui/platforms/mac/qdesktopwidget_mac_p.h
deleted file mode 100644
index ac638ea7d8..0000000000
--- a/src/gui/platforms/mac/qdesktopwidget_mac_p.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qrect.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDesktopWidgetImplementation
-{
-public:
- QDesktopWidgetImplementation();
- ~QDesktopWidgetImplementation();
- static QDesktopWidgetImplementation *instance();
-
- int appScreen;
- int screenCount;
-
- QVector<QRectF> availableRects;
- QVector<QRectF> screenRects;
-
- QRect availableRect(int screenIndex) const;
- QRect screenRect(int screenIndex) const;
- void onResize();
-};
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qdnd_mac.mm b/src/gui/platforms/mac/qdnd_mac.mm
deleted file mode 100644
index 3af2ba007c..0000000000
--- a/src/gui/platforms/mac/qdnd_mac.mm
+++ /dev/null
@@ -1,753 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#ifndef QT_NO_DRAGANDDROP
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qurl.h"
-#include "qwidget.h"
-#include "qfile.h"
-#include "qfileinfo.h"
-#include <stdlib.h>
-#include <string.h>
-#ifndef QT_NO_ACCESSIBILITY
-# include "qaccessible.h"
-#endif
-
-#include <private/qapplication_p.h>
-#include <private/qwidget_p.h>
-#include <private/qdnd_p.h>
-#include <private/qt_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-QMacDndAnswerRecord qt_mac_dnd_answer_rec;
-
-/*****************************************************************************
- QDnD debug facilities
- *****************************************************************************/
-//#define DEBUG_DRAG_EVENTS
-//#define DEBUG_DRAG_PROMISES
-
-/*****************************************************************************
- QDnD globals
- *****************************************************************************/
-bool qt_mac_in_drag = false;
-#ifndef QT_MAC_USE_COCOA
-static DragReference qt_mac_current_dragRef = 0;
-#endif
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern void qt_mac_send_modifiers_changed(quint32, QObject *); //qapplication_mac.cpp
-extern uint qGlobalPostedEventsCount(); //qapplication.cpp
-extern RgnHandle qt_mac_get_rgn(); // qregion_mac.cpp
-extern void qt_mac_dispose_rgn(RgnHandle); // qregion_mac.cpp
-/*****************************************************************************
- QDnD utility functions
- *****************************************************************************/
-
-//default pixmap
-static const int default_pm_hotx = -2;
-static const int default_pm_hoty = -16;
-#ifndef QT_MAC_USE_COCOA
-static const char * const default_pm[] = {
- "13 9 3 1",
- ". c None",
- " c #000000",
- "X c #FFFFFF",
- "X X X X X X X",
- " X X X X X X ",
- "X ......... X",
- " X.........X ",
- "X ......... X",
- " X.........X ",
- "X ......... X",
- " X X X X X X ",
- "X X X X X X X",
-};
-#endif
-
-//action management
-#ifdef DEBUG_DRAG_EVENTS
-# define MAP_MAC_ENUM(x) x, #x
-#else
-# define MAP_MAC_ENUM(x) x
-#endif
-struct mac_enum_mapper
-{
- int mac_code;
- int qt_code;
-#ifdef DEBUG_DRAG_EVENTS
- char *qt_desc;
-#endif
-};
-#ifndef QT_MAC_USE_COCOA
-static mac_enum_mapper dnd_action_symbols[] = {
- { kDragActionAlias, MAP_MAC_ENUM(Qt::LinkAction) },
- { kDragActionMove, MAP_MAC_ENUM(Qt::MoveAction) },
- { kDragActionGeneric, MAP_MAC_ENUM(Qt::CopyAction) },
- { kDragActionCopy, MAP_MAC_ENUM(Qt::CopyAction) },
- { 0, MAP_MAC_ENUM(0) }
-};
-static DragActions qt_mac_dnd_map_qt_actions(Qt::DropActions qActions)
-{
- DragActions ret = kDragActionNothing;
- for(int i = 0; dnd_action_symbols[i].qt_code; ++i) {
- if(qActions & dnd_action_symbols[i].qt_code)
- ret |= dnd_action_symbols[i].mac_code;
- }
- return ret;
-}
-static Qt::DropActions qt_mac_dnd_map_mac_actions(DragActions macActions)
-{
-#ifdef DEBUG_DRAG_EVENTS
- qDebug("Converting DND ActionList: 0x%lx", macActions);
-#endif
- Qt::DropActions ret = Qt::IgnoreAction;
- for(int i = 0; dnd_action_symbols[i].qt_code; ++i) {
-#ifdef DEBUG_DRAG_EVENTS
- qDebug(" %d) [%s] : %s", i, dnd_action_symbols[i].qt_desc,
- (macActions & dnd_action_symbols[i].mac_code) ? "true" : "false");
-#endif
- if(macActions & dnd_action_symbols[i].mac_code)
- ret |= Qt::DropAction(dnd_action_symbols[i].qt_code);
- }
- return ret;
-}
-static Qt::DropAction qt_mac_dnd_map_mac_default_action(DragActions macActions)
-{
- static Qt::DropAction preferred_actions[] = { Qt::CopyAction, Qt::LinkAction, //in order
- Qt::MoveAction, Qt::IgnoreAction };
- Qt::DropAction ret = Qt::IgnoreAction;
- const Qt::DropActions qtActions = qt_mac_dnd_map_mac_actions(macActions);
- for(int i = 0; preferred_actions[i] != Qt::IgnoreAction; ++i) {
- if(qtActions & preferred_actions[i]) {
- ret = preferred_actions[i];
- break;
- }
- }
-#ifdef DEBUG_DRAG_EVENTS
- for(int i = 0; dnd_action_symbols[i].qt_code; ++i) {
- if(dnd_action_symbols[i].qt_code == ret) {
- qDebug("Got default action: %s [0x%lx]", dnd_action_symbols[i].qt_desc, macActions);
- break;
- }
- }
-#endif
- return ret;
-}
-static void qt_mac_dnd_update_action(DragReference dragRef) {
- SInt16 modifiers;
- GetDragModifiers(dragRef, &modifiers, 0, 0);
- qt_mac_send_modifiers_changed(modifiers, qApp);
-
- Qt::DropAction qtAction = Qt::IgnoreAction;
- {
- DragActions macAllowed = kDragActionNothing;
- GetDragDropAction(dragRef, &macAllowed);
- Qt::DropActions qtAllowed = qt_mac_dnd_map_mac_actions(macAllowed);
- qtAction = QDragManager::self()->defaultAction(qtAllowed, QApplication::keyboardModifiers());
-#if 1
- if(!(qtAllowed & qtAction))
- qtAction = qt_mac_dnd_map_mac_default_action(macAllowed);
-#endif
- }
- DragActions macAction = qt_mac_dnd_map_qt_actions(qtAction);
-
- DragActions currentActions;
- GetDragDropAction(dragRef, &currentActions);
- if(currentActions != macAction) {
- SetDragDropAction(dragRef, macAction);
- QDragManager::self()->emitActionChanged(qtAction);
- }
-}
-#endif // !QT_MAC_USE_COCOA
-
-/*****************************************************************************
- DnD functions
- *****************************************************************************/
-bool QDropData::hasFormat_sys(const QString &mime) const
-{
-#ifndef QT_MAC_USE_COCOA
- OSPasteboardRef board;
- if(GetDragPasteboard(qt_mac_current_dragRef, &board) != noErr) {
- qDebug("DnD: Cannot get PasteBoard!");
- return false;
- }
- return QMacPasteboard(board, QMacPasteboardMime::MIME_DND).hasFormat(mime);
-#else
- Q_UNUSED(mime);
- return false;
-#endif // !QT_MAC_USE_COCOA
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mime, QVariant::Type type) const
-{
-#ifndef QT_MAC_USE_COCOA
- OSPasteboardRef board;
- if(GetDragPasteboard(qt_mac_current_dragRef, &board) != noErr) {
- qDebug("DnD: Cannot get PasteBoard!");
- return QVariant();
- }
- return QMacPasteboard(board, QMacPasteboardMime::MIME_DND).retrieveData(mime, type);
-#else
- Q_UNUSED(mime);
- Q_UNUSED(type);
- return QVariant();
-#endif // !QT_MAC_USE_COCOA
-}
-
-QStringList QDropData::formats_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
- OSPasteboardRef board;
- if(GetDragPasteboard(qt_mac_current_dragRef, &board) != noErr) {
- qDebug("DnD: Cannot get PasteBoard!");
- return QStringList();
- }
- return QMacPasteboard(board, QMacPasteboardMime::MIME_DND).formats();
-#else
- return QStringList();
-#endif
-}
-
-void QDragManager::timerEvent(QTimerEvent*)
-{
-}
-
-bool QDragManager::eventFilter(QObject *, QEvent *)
-{
- return false;
-}
-
-void QDragManager::updateCursor()
-{
-}
-
-void QDragManager::cancel(bool)
-{
- if(object) {
- beingCancelled = true;
- object = 0;
- }
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DragDropEnd);
-#endif
-}
-
-void QDragManager::move(const QPoint &)
-{
-}
-
-void QDragManager::drop()
-{
-}
-
-/**
- If a drop action is already set on the carbon event
- (from e.g. an earlier enter event), we insert the same
- action on the new Qt event that has yet to be sendt.
-*/
-static inline bool qt_mac_set_existing_drop_action(const DragRef &dragRef, QDropEvent &event)
-{
-#ifndef QT_MAC_USE_COCOA
- DragActions currentAction = kDragActionNothing;
- OSStatus err = GetDragDropAction(dragRef, &currentAction);
- if (err == noErr && currentAction != kDragActionNothing) {
- // This looks a bit evil, but we only ever set one action, so it's OK.
- event.setDropAction(Qt::DropAction(int(qt_mac_dnd_map_mac_actions(currentAction))));
- return true;
- }
-#else
- Q_UNUSED(dragRef);
- Q_UNUSED(event);
-#endif
- return false;
-}
-
-/**
- If an answer rect has been set on the event (after being sent
- to the global event processor), we store that rect so we can
- check if the mouse is in the same area upon next drag move event.
-*/
-void qt_mac_copy_answer_rect(const QDragMoveEvent &event)
-{
- if (!event.answerRect().isEmpty()) {
- qt_mac_dnd_answer_rec.rect = event.answerRect();
- qt_mac_dnd_answer_rec.buttons = event.mouseButtons();
- qt_mac_dnd_answer_rec.modifiers = event.keyboardModifiers();
- qt_mac_dnd_answer_rec.lastAction = event.dropAction();
- }
-}
-
-bool qt_mac_mouse_inside_answer_rect(QPoint mouse)
-{
- if (!qt_mac_dnd_answer_rec.rect.isEmpty()
- && qt_mac_dnd_answer_rec.rect.contains(mouse)
- && QApplication::mouseButtons() == qt_mac_dnd_answer_rec.buttons
- && QApplication::keyboardModifiers() == qt_mac_dnd_answer_rec.modifiers)
- return true;
- else
- return false;
-}
-
-bool QWidgetPrivate::qt_mac_dnd_event(uint kind, DragRef dragRef)
-{
-#ifndef QT_MAC_USE_COCOA
- Q_Q(QWidget);
- qt_mac_current_dragRef = dragRef;
- if (kind != kEventControlDragLeave)
- qt_mac_dnd_update_action(dragRef);
-
- Point mouse;
- GetDragMouse(dragRef, &mouse, 0L);
- if(!mouse.h && !mouse.v)
- GetGlobalMouse(&mouse);
-
- if(QApplicationPrivate::modalState()) {
- for(QWidget *modal = q; modal; modal = modal->parentWidget()) {
- if(modal->isWindow()) {
- if(modal != QApplication::activeModalWidget())
- return noErr;
- break;
- }
- }
- }
-
- //lookup the possible actions
- DragActions allowed = kDragActionNothing;
- GetDragAllowableActions(dragRef, &allowed);
- Qt::DropActions qtAllowed = qt_mac_dnd_map_mac_actions(allowed);
-
- //lookup the source dragAccepted
- QMimeData *dropdata = QDragManager::self()->dropData;
- if(QDragManager::self()->source())
- dropdata = QDragManager::self()->dragPrivate()->data;
-
- // 'interrestedInDrag' should end up being 'true' if a later drop
- // will be accepted by the widget for the current mouse position
- bool interrestedInDrag = true;
-
- //Dispatch events
- if (kind == kEventControlDragWithin) {
- if (qt_mac_mouse_inside_answer_rect(q->mapFromGlobal(QPoint(mouse.h, mouse.v))))
- return qt_mac_dnd_answer_rec.lastAction == Qt::IgnoreAction;
- else
- qt_mac_dnd_answer_rec.clear();
-
- QDragMoveEvent qDMEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
-
- // Accept the event by default if a
- // drag action exists on the carbon event
- if (qt_mac_set_existing_drop_action(dragRef, qDMEvent))
- qDMEvent.accept();
-
- QApplication::sendEvent(q, &qDMEvent);
- if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction)
- interrestedInDrag = false;
-
- qt_mac_copy_answer_rect(qDMEvent);
- SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDMEvent.dropAction()));
-
- } else if (kind == kEventControlDragEnter) {
- qt_mac_dnd_answer_rec.clear();
-
- QDragEnterEvent qDEEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- qt_mac_set_existing_drop_action(dragRef, qDEEvent);
- QApplication::sendEvent(q, &qDEEvent);
- SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDEEvent.dropAction()));
-
- if (!qDEEvent.isAccepted())
- // The widget is simply not interested in this
- // drag. So tell carbon this by returning 'false'. We will then
- // not receive any further move, drop or leave events for this widget.
- return false;
- else {
- // Documentation states that a drag move event is sent immediately after
- // a drag enter event. So we do that. This will honor widgets overriding
- // 'dragMoveEvent' only, and not 'dragEnterEvent'
- QDragMoveEvent qDMEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- qDMEvent.accept(); // accept by default, since enter event was accepted.
- qDMEvent.setDropAction(qDEEvent.dropAction());
- QApplication::sendEvent(q, &qDMEvent);
- if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction)
- interrestedInDrag = false;
-
- qt_mac_copy_answer_rect(qDMEvent);
- SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDMEvent.dropAction()));
- }
-
- } else if(kind == kEventControlDragLeave) {
- QDragLeaveEvent de;
- QApplication::sendEvent(q, &de);
- } else if(kind == kEventControlDragReceive) {
- QDropEvent de(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- if(QDragManager::self()->object)
- QDragManager::self()->dragPrivate()->target = q;
- QApplication::sendEvent(q, &de);
- if(!de.isAccepted()) {
- interrestedInDrag = false;
- SetDragDropAction(dragRef, kDragActionNothing);
- } else {
- if(QDragManager::self()->object)
- QDragManager::self()->dragPrivate()->executed_action = de.dropAction();
- SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(de.dropAction()));
- }
- }
-
-#ifdef DEBUG_DRAG_EVENTS
- {
- const char *desc = 0;
- switch(kind) {
- case kEventControlDragWithin: desc = "DragMove"; break;
- case kEventControlDragEnter: desc = "DragEnter"; break;
- case kEventControlDragLeave: desc = "DragLeave"; break;
- case kEventControlDragReceive: desc = "DragDrop"; break;
- }
- if(desc) {
- QPoint pos(q->mapFromGlobal(QPoint(mouse.h, mouse.v)));
- qDebug("Sending <%s>(%d, %d) event to %p(%s::%s) [%d] (%p)",
- desc, pos.x(), pos.y(), q, q->metaObject()->className(),
- q->objectName().toLocal8Bit().constData(), ret, dragRef);
- }
- }
-#endif
-
- //set the cursor
- bool found_cursor = false;
- if(kind == kEventControlDragWithin || kind == kEventControlDragEnter) {
- ThemeCursor cursor = kThemeNotAllowedCursor;
- found_cursor = true;
- if (interrestedInDrag) {
- DragActions action = kDragActionNothing;
- GetDragDropAction(dragRef, &action);
- switch(qt_mac_dnd_map_mac_default_action(action)) {
- case Qt::IgnoreAction:
- cursor = kThemeNotAllowedCursor;
- break;
- case Qt::MoveAction:
- cursor = kThemeArrowCursor;
- break;
- case Qt::CopyAction:
- cursor = kThemeCopyArrowCursor;
- break;
- case Qt::LinkAction:
- cursor = kThemeAliasArrowCursor;
- break;
- default:
- cursor = kThemeNotAllowedCursor;
- break;
- }
- }
- SetThemeCursor(cursor);
- }
- if(found_cursor) {
- qt_mac_set_cursor(0); //just use our's
- } else {
- QCursor cursor(Qt::ArrowCursor);
- if(qApp && qApp->overrideCursor()) {
- cursor = *qApp->overrideCursor();
- } else if(q) {
- for(QWidget *p = q; p; p = p->parentWidget()) {
- if(p->isEnabled() && p->testAttribute(Qt::WA_SetCursor)) {
- cursor = p->cursor();
- break;
- }
- }
- }
- qt_mac_set_cursor(&cursor);
- }
-
- //idle things
- if(qGlobalPostedEventsCount()) {
- QApplication::sendPostedEvents();
- QApplication::flush();
- }
-
- // If this was not a drop, tell carbon that we will be interresed in receiving more
- // events for the current drag. We do that by returning true.
- if (kind == kEventControlDragReceive)
- return interrestedInDrag;
- else
- return true;
-#else
- Q_UNUSED(kind);
- Q_UNUSED(dragRef);
- return false;
-#endif // !QT_MAC_USE_COCOA
-}
-
-#ifndef QT_MAC_USE_COCOA
-Qt::DropAction QDragManager::drag(QDrag *o)
-{
-
- if(qt_mac_in_drag) { //just make sure..
- qWarning("Qt: Internal error: WH0A, unexpected condition reached");
- return Qt::IgnoreAction;
- }
- if(object == o)
- return Qt::IgnoreAction;
- /* At the moment it seems clear that Mac OS X does not want to drag with a non-left button
- so we just bail early to prevent it */
- if(!(GetCurrentEventButtonState() & kEventMouseButtonPrimary))
- return Qt::IgnoreAction;
-
- if(object) {
- dragPrivate()->source->removeEventFilter(this);
- cancel();
- beingCancelled = false;
- }
-
- object = o;
- dragPrivate()->target = 0;
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
-#endif
-
- //setup the data
- QMacPasteboard dragBoard(QMacPasteboardMime::MIME_DND);
- dragBoard.setMimeData(dragPrivate()->data);
-
- //create the drag
- OSErr result;
- DragRef dragRef;
- if((result = NewDragWithPasteboard(dragBoard.pasteBoard(), &dragRef)))
- return Qt::IgnoreAction;
- //setup the actions
- DragActions possibleActions = qt_mac_dnd_map_qt_actions(dragPrivate()->possible_actions);
- SetDragAllowableActions(dragRef, //local
- possibleActions,
- true);
- SetDragAllowableActions(dragRef, //remote (same as local)
- possibleActions,
- false);
-
-
- QPoint hotspot;
- QPixmap pix = dragPrivate()->pixmap;
- if(pix.isNull()) {
- if(dragPrivate()->data->hasText() || dragPrivate()->data->hasUrls()) {
- //get the string
- QString s = dragPrivate()->data->hasText() ? dragPrivate()->data->text()
- : dragPrivate()->data->urls().first().toString();
- if(s.length() > 26)
- s = s.left(23) + QChar(0x2026);
- if(!s.isEmpty()) {
- //draw it
- QFont f(qApp->font());
- f.setPointSize(12);
- QFontMetrics fm(f);
- const int width = fm.width(s);
- const int height = fm.height();
- if(width > 0 && height > 0) {
- QPixmap tmp(width, height);
- QPainter p(&tmp);
- p.fillRect(0, 0, tmp.width(), tmp.height(), Qt::color0);
- p.setPen(Qt::color1);
- p.setFont(f);
- p.drawText(0, fm.ascent(), s);
- p.end();
- //save it
- pix = tmp;
- hotspot = QPoint(tmp.width() / 2, tmp.height() / 2);
- }
- }
- } else {
- pix = QPixmap(default_pm);
- hotspot = QPoint(default_pm_hotx, default_pm_hoty);
- }
- } else {
- hotspot = dragPrivate()->hotspot;
- }
-
- //so we must fake an event
- EventRecord fakeEvent;
- GetGlobalMouse(&(fakeEvent.where));
- fakeEvent.message = 0;
- fakeEvent.what = mouseDown;
- fakeEvent.when = EventTimeToTicks(GetCurrentEventTime());
- fakeEvent.modifiers = GetCurrentKeyModifiers();
- if(GetCurrentEventButtonState() & 2)
- fakeEvent.modifiers |= controlKey;
-
- //find the hotspot in relation to the pixmap
- Point boundsPoint;
- boundsPoint.h = fakeEvent.where.h - hotspot.x();
- boundsPoint.v = fakeEvent.where.v - hotspot.y();
- Rect boundsRect;
- SetRect(&boundsRect, boundsPoint.h, boundsPoint.v, boundsPoint.h + pix.width(), boundsPoint.v + pix.height());
-
- //set the drag image
- QRegion dragRegion(boundsPoint.h, boundsPoint.v, pix.width(), pix.height()), pixRegion;
- if(!pix.isNull()) {
- HIPoint hipoint = { -hotspot.x(), -hotspot.y() };
- CGImageRef img = (CGImageRef)pix.macCGHandle();
- SetDragImageWithCGImage(dragRef, img, &hipoint, 0);
- CGImageRelease(img);
- }
-
- SetDragItemBounds(dragRef, (ItemReference)1 , &boundsRect);
- { //do the drag
- qt_mac_in_drag = true;
- qt_mac_dnd_update_action(dragRef);
- result = TrackDrag(dragRef, &fakeEvent, QMacSmartQuickDrawRegion(dragRegion.toQDRgn()));
- qt_mac_in_drag = false;
- }
- object = 0;
- if(result == noErr) {
- // Check if the receiver points us to
- // a file location. If so, we need to do
- // the file copy/move ourselves:
- QCFType<CFURLRef> pasteLocation = 0;
- PasteboardCopyPasteLocation(dragBoard.pasteBoard(), &pasteLocation);
- if (pasteLocation){
- Qt::DropAction action = o->d_func()->defaultDropAction;
- if (action == Qt::IgnoreAction){
- if (o->d_func()->possible_actions & Qt::MoveAction)
- action = Qt::MoveAction;
- else if (o->d_func()->possible_actions & Qt::CopyAction)
- action = Qt::CopyAction;
-
- }
- bool atleastOne = false;
- QList<QUrl> urls = o->mimeData()->urls();
- for (int i = 0; i < urls.size(); ++i){
- QUrl fromUrl = urls.at(i);
- QString filename = QFileInfo(fromUrl.path()).fileName();
- QUrl toUrl(QCFString::toQString(CFURLGetString(pasteLocation)) + filename);
- if (action == Qt::MoveAction){
- if (QFile::rename(fromUrl.path(), toUrl.path()))
- atleastOne = true;
- } else if (action == Qt::CopyAction){
- if (QFile::copy(fromUrl.path(), toUrl.path()))
- atleastOne = true;
- }
- }
- if (atleastOne){
- DisposeDrag(dragRef);
- o->setMimeData(0);
- o->deleteLater();
- return action;
- }
- }
-
- DragActions ret = kDragActionNothing;
- GetDragDropAction(dragRef, &ret);
- DisposeDrag(dragRef); //cleanup
- o->setMimeData(0);
- o->deleteLater();
- return qt_mac_dnd_map_mac_default_action(ret);
- }
- DisposeDrag(dragRef); //cleanup
- return Qt::IgnoreAction;
-}
-#endif
-
-void QDragManager::updatePixmap()
-{
-}
-
-QCocoaDropData::QCocoaDropData(CFStringRef pasteboard)
- : QInternalMimeData()
-{
- NSString* pasteboardName = (NSString*)pasteboard;
- [pasteboardName retain];
- dropPasteboard = pasteboard;
-}
-
-QCocoaDropData::~QCocoaDropData()
-{
- NSString* pasteboardName = (NSString*)dropPasteboard;
- [pasteboardName release];
-}
-
-QStringList QCocoaDropData::formats_sys() const
-{
- QStringList formats;
- OSPasteboardRef board;
- if (PasteboardCreate(dropPasteboard, &board) != noErr) {
- qDebug("DnD: Cannot get PasteBoard!");
- return formats;
- }
- formats = QMacPasteboard(board, QMacPasteboardMime::MIME_DND).formats();
- return formats;
-}
-
-QVariant QCocoaDropData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
-{
- QVariant data;
- OSPasteboardRef board;
- if (PasteboardCreate(dropPasteboard, &board) != noErr) {
- qDebug("DnD: Cannot get PasteBoard!");
- return data;
- }
- data = QMacPasteboard(board, QMacPasteboardMime::MIME_DND).retrieveData(mimeType, type);
- CFRelease(board);
- return data;
-}
-
-bool QCocoaDropData::hasFormat_sys(const QString &mimeType) const
-{
- bool has = false;
- OSPasteboardRef board;
- if (PasteboardCreate(dropPasteboard, &board) != noErr) {
- qDebug("DnD: Cannot get PasteBoard!");
- return has;
- }
- has = QMacPasteboard(board, QMacPasteboardMime::MIME_DND).hasFormat(mimeType);
- CFRelease(board);
- return has;
-}
-
-#endif // QT_NO_DRAGANDDROP
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qeventdispatcher_mac.mm b/src/gui/platforms/mac/qeventdispatcher_mac.mm
deleted file mode 100644
index 677a7368b4..0000000000
--- a/src/gui/platforms/mac/qeventdispatcher_mac.mm
+++ /dev/null
@@ -1,1200 +0,0 @@
-/****************************************************************************
-**
-** 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 "qplatformdefs.h"
-#include "private/qt_mac_p.h"
-#include "qeventdispatcher_mac_p.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qdialog.h"
-#include "qhash.h"
-#include "qsocketnotifier.h"
-#include "private/qwidget_p.h"
-#include "private/qthread_p.h"
-#include "private/qapplication_p.h"
-
-#include <private/qcocoaapplication_mac_p.h>
-#include "private/qt_cocoa_helpers_mac_p.h"
-
-#ifndef QT_NO_THREAD
-# include "qmutex.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern void qt_event_request_timer(MacTimerInfo *); //qapplication_mac.cpp
-extern MacTimerInfo *qt_event_get_timer(EventRef); //qapplication_mac.cpp
-extern void qt_event_request_select(QEventDispatcherMac *); //qapplication_mac.cpp
-extern void qt_event_request_updates(); //qapplication_mac.cpp
-extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
-extern bool qt_is_gui_used; //qapplication.cpp
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
-extern bool qt_mac_is_macsheet(const QWidget *); //qwidget_mac.cpp
-
-static inline CFRunLoopRef mainRunLoop()
-{
-#ifndef QT_MAC_USE_COCOA
- return reinterpret_cast<CFRunLoopRef>(const_cast<void *>(GetCFRunLoopFromEventLoop(GetMainEventLoop())));
-#else
- return CFRunLoopGetMain();
-#endif
-}
-
-/*****************************************************************************
- Timers stuff
- *****************************************************************************/
-
-/* timer call back */
-void QEventDispatcherMacPrivate::activateTimer(CFRunLoopTimerRef, void *info)
-{
- int timerID =
-#ifdef Q_OS_MAC64
- qint64(info);
-#else
- int(info);
-#endif
-
- MacTimerInfo *tmr;
- tmr = macTimerHash.value(timerID);
- if (tmr == 0 || tmr->pending == true)
- return; // Can't send another timer event if it's pending.
-
-
- if (blockSendPostedEvents) {
- QCoreApplication::postEvent(tmr->obj, new QTimerEvent(tmr->id));
- } else {
- tmr->pending = true;
- QTimerEvent e(tmr->id);
- qt_sendSpontaneousEvent(tmr->obj, &e);
- // Get the value again in case the timer gets unregistered during the sendEvent.
- tmr = macTimerHash.value(timerID);
- if (tmr != 0)
- tmr->pending = false;
- }
-
-}
-
-void QEventDispatcherMac::registerTimer(int timerId, int interval, QObject *obj)
-{
-#ifndef QT_NO_DEBUG
- if (timerId < 1 || interval < 0 || !obj) {
- qWarning("QEventDispatcherMac::registerTimer: invalid arguments");
- return;
- } else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
- qWarning("QObject::startTimer: timers cannot be started from another thread");
- return;
- }
-#endif
-
- MacTimerInfo *t = new MacTimerInfo();
- t->id = timerId;
- t->interval = interval;
- t->obj = obj;
- t->runLoopTimer = 0;
- t->pending = false;
-
- CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent();
- CFTimeInterval cfinterval = qMax(CFTimeInterval(interval) / 1000, 0.0000001);
- fireDate += cfinterval;
- QEventDispatcherMacPrivate::macTimerHash.insert(timerId, t);
- CFRunLoopTimerContext info = { 0, (void *)timerId, 0, 0, 0 };
- t->runLoopTimer = CFRunLoopTimerCreate(0, fireDate, cfinterval, 0, 0,
- QEventDispatcherMacPrivate::activateTimer, &info);
- if (t->runLoopTimer == 0) {
- qFatal("QEventDispatcherMac::registerTimer: Cannot create timer");
- }
- CFRunLoopAddTimer(mainRunLoop(), t->runLoopTimer, kCFRunLoopCommonModes);
-}
-
-bool QEventDispatcherMac::unregisterTimer(int identifier)
-{
-#ifndef QT_NO_DEBUG
- if (identifier < 1) {
- qWarning("QEventDispatcherMac::unregisterTimer: invalid argument");
- return false;
- } else if (thread() != QThread::currentThread()) {
- qWarning("QObject::killTimer: timers cannot be stopped from another thread");
- return false;
- }
-#endif
- if (identifier <= 0)
- return false; // not init'd or invalid timer
-
- MacTimerInfo *timerInfo = QEventDispatcherMacPrivate::macTimerHash.take(identifier);
- if (timerInfo == 0)
- return false;
-
- if (!QObjectPrivate::get(timerInfo->obj)->inThreadChangeEvent)
- QAbstractEventDispatcherPrivate::releaseTimerId(identifier);
- CFRunLoopTimerInvalidate(timerInfo->runLoopTimer);
- CFRelease(timerInfo->runLoopTimer);
- delete timerInfo;
-
- return true;
-}
-
-bool QEventDispatcherMac::unregisterTimers(QObject *obj)
-{
-#ifndef QT_NO_DEBUG
- if (!obj) {
- qWarning("QEventDispatcherMac::unregisterTimers: invalid argument");
- return false;
- } else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
- qWarning("QObject::killTimers: timers cannot be stopped from another thread");
- return false;
- }
-#endif
-
- MacTimerHash::iterator it = QEventDispatcherMacPrivate::macTimerHash.begin();
- while (it != QEventDispatcherMacPrivate::macTimerHash.end()) {
- MacTimerInfo *timerInfo = it.value();
- if (timerInfo->obj != obj) {
- ++it;
- } else {
- if (!QObjectPrivate::get(timerInfo->obj)->inThreadChangeEvent)
- QAbstractEventDispatcherPrivate::releaseTimerId(timerInfo->id);
- CFRunLoopTimerInvalidate(timerInfo->runLoopTimer);
- CFRelease(timerInfo->runLoopTimer);
- delete timerInfo;
- it = QEventDispatcherMacPrivate::macTimerHash.erase(it);
- }
- }
- return true;
-}
-
-QList<QEventDispatcherMac::TimerInfo>
-QEventDispatcherMac::registeredTimers(QObject *object) const
-{
- if (!object) {
- qWarning("QEventDispatcherMac:registeredTimers: invalid argument");
- return QList<TimerInfo>();
- }
-
- QList<TimerInfo> list;
-
- MacTimerHash::const_iterator it = QEventDispatcherMacPrivate::macTimerHash.constBegin();
- while (it != QEventDispatcherMacPrivate::macTimerHash.constEnd()) {
- MacTimerInfo *t = it.value();
- if (t->obj == object)
- list << TimerInfo(t->id, t->interval);
- ++it;
- }
- return list;
-}
-
-/**************************************************************************
- Socket Notifiers
- *************************************************************************/
-void qt_mac_socket_callback(CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef,
- const void *, void *info) {
- QEventDispatcherMacPrivate *const eventDispatcher
- = static_cast<QEventDispatcherMacPrivate *>(info);
- int nativeSocket = CFSocketGetNative(s);
- MacSocketInfo *socketInfo = eventDispatcher->macSockets.value(nativeSocket);
- QEvent notifierEvent(QEvent::SockAct);
-
- // There is a race condition that happen where we disable the notifier and
- // the kernel still has a notification to pass on. We then get this
- // notification after we've successfully disabled the CFSocket, but our Qt
- // notifier is now gone. The upshot is we have to check the notifier
- // everytime.
- if (callbackType == kCFSocketReadCallBack) {
- if (socketInfo->readNotifier)
- QApplication::sendEvent(socketInfo->readNotifier, &notifierEvent);
- } else if (callbackType == kCFSocketWriteCallBack) {
- if (socketInfo->writeNotifier)
- QApplication::sendEvent(socketInfo->writeNotifier, &notifierEvent);
- }
-}
-
-/*
- Adds a loop source for the given socket to the current run loop.
-*/
-CFRunLoopSourceRef qt_mac_add_socket_to_runloop(const CFSocketRef socket)
-{
- CFRunLoopSourceRef loopSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
- if (!loopSource)
- return 0;
-
- CFRunLoopAddSource(mainRunLoop(), loopSource, kCFRunLoopCommonModes);
- return loopSource;
-}
-
-/*
- Removes the loop source for the given socket from the current run loop.
-*/
-void qt_mac_remove_socket_from_runloop(const CFSocketRef socket, CFRunLoopSourceRef runloop)
-{
- Q_ASSERT(runloop);
- CFRunLoopRemoveSource(mainRunLoop(), runloop, kCFRunLoopCommonModes);
- CFSocketDisableCallBacks(socket, kCFSocketReadCallBack);
- CFSocketDisableCallBacks(socket, kCFSocketWriteCallBack);
- CFRunLoopSourceInvalidate(runloop);
-}
-
-/*
- Register a QSocketNotifier with the mac event system by creating a CFSocket with
- with a read/write callback.
-
- Qt has separate socket notifiers for reading and writing, but on the mac there is
- a limitation of one CFSocket object for each native socket.
-*/
-void QEventDispatcherMac::registerSocketNotifier(QSocketNotifier *notifier)
-{
- Q_ASSERT(notifier);
- int nativeSocket = notifier->socket();
- int type = notifier->type();
-#ifndef QT_NO_DEBUG
- if (nativeSocket < 0 || nativeSocket > FD_SETSIZE) {
- qWarning("QSocketNotifier: Internal error");
- return;
- } else if (notifier->thread() != thread()
- || thread() != QThread::currentThread()) {
- qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
- return;
- }
-#endif
-
- Q_D(QEventDispatcherMac);
-
- if (type == QSocketNotifier::Exception) {
- qWarning("QSocketNotifier::Exception is not supported on Mac OS X");
- return;
- }
-
- // Check if we have a CFSocket for the native socket, create one if not.
- MacSocketInfo *socketInfo = d->macSockets.value(nativeSocket);
- if (!socketInfo) {
- socketInfo = new MacSocketInfo();
-
- // Create CFSocket, specify that we want both read and write callbacks (the callbacks
- // are enabled/disabled later on).
- const int callbackTypes = kCFSocketReadCallBack | kCFSocketWriteCallBack;
- CFSocketContext context = {0, d, 0, 0, 0};
- socketInfo->socket = CFSocketCreateWithNative(kCFAllocatorDefault, nativeSocket, callbackTypes, qt_mac_socket_callback, &context);
- if (CFSocketIsValid(socketInfo->socket) == false) {
- qWarning("QEventDispatcherMac::registerSocketNotifier: Failed to create CFSocket");
- return;
- }
-
- CFOptionFlags flags = CFSocketGetSocketFlags(socketInfo->socket);
- flags |= kCFSocketAutomaticallyReenableWriteCallBack; //QSocketNotifier stays enabled after a write
- flags &= ~kCFSocketCloseOnInvalidate; //QSocketNotifier doesn't close the socket upon destruction/invalidation
- CFSocketSetSocketFlags(socketInfo->socket, flags);
-
- // Add CFSocket to runloop.
- if(!(socketInfo->runloop = qt_mac_add_socket_to_runloop(socketInfo->socket))) {
- qWarning("QEventDispatcherMac::registerSocketNotifier: Failed to add CFSocket to runloop");
- CFSocketInvalidate(socketInfo->socket);
- CFRelease(socketInfo->socket);
- return;
- }
-
- // Disable both callback types by default. This must be done after
- // we add the CFSocket to the runloop, or else these calls will have
- // no effect.
- CFSocketDisableCallBacks(socketInfo->socket, kCFSocketReadCallBack);
- CFSocketDisableCallBacks(socketInfo->socket, kCFSocketWriteCallBack);
-
- d->macSockets.insert(nativeSocket, socketInfo);
- }
-
- // Increment read/write counters and select enable callbacks if necessary.
- if (type == QSocketNotifier::Read) {
- Q_ASSERT(socketInfo->readNotifier == 0);
- socketInfo->readNotifier = notifier;
- CFSocketEnableCallBacks(socketInfo->socket, kCFSocketReadCallBack);
- } else if (type == QSocketNotifier::Write) {
- Q_ASSERT(socketInfo->writeNotifier == 0);
- socketInfo->writeNotifier = notifier;
- CFSocketEnableCallBacks(socketInfo->socket, kCFSocketWriteCallBack);
- }
-}
-
-/*
- Unregister QSocketNotifer. The CFSocket correspoding to this notifier is
- removed from the runloop of this is the last notifier that users
- that CFSocket.
-*/
-void QEventDispatcherMac::unregisterSocketNotifier(QSocketNotifier *notifier)
-{
- Q_ASSERT(notifier);
- int nativeSocket = notifier->socket();
- int type = notifier->type();
-#ifndef QT_NO_DEBUG
- if (nativeSocket < 0 || nativeSocket > FD_SETSIZE) {
- qWarning("QSocketNotifier: Internal error");
- return;
- } else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
- qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
- return;
- }
-#endif
-
- Q_D(QEventDispatcherMac);
-
- if (type == QSocketNotifier::Exception) {
- qWarning("QSocketNotifier::Exception is not supported on Mac OS X");
- return;
- }
- MacSocketInfo *socketInfo = d->macSockets.value(nativeSocket);
- if (!socketInfo) {
- qWarning("QEventDispatcherMac::unregisterSocketNotifier: Tried to unregister a not registered notifier");
- return;
- }
-
- // Decrement read/write counters and disable callbacks if necessary.
- if (type == QSocketNotifier::Read) {
- Q_ASSERT(notifier == socketInfo->readNotifier);
- socketInfo->readNotifier = 0;
- CFSocketDisableCallBacks(socketInfo->socket, kCFSocketReadCallBack);
- } else if (type == QSocketNotifier::Write) {
- Q_ASSERT(notifier == socketInfo->writeNotifier);
- socketInfo->writeNotifier = 0;
- CFSocketDisableCallBacks(socketInfo->socket, kCFSocketWriteCallBack);
- }
-
- // Remove CFSocket from runloop if this was the last QSocketNotifier.
- if (socketInfo->readNotifier == 0 && socketInfo->writeNotifier == 0) {
- if (CFSocketIsValid(socketInfo->socket))
- qt_mac_remove_socket_from_runloop(socketInfo->socket, socketInfo->runloop);
- CFRunLoopSourceInvalidate(socketInfo->runloop);
- CFRelease(socketInfo->runloop);
- CFSocketInvalidate(socketInfo->socket);
- CFRelease(socketInfo->socket);
- delete socketInfo;
- d->macSockets.remove(nativeSocket);
- }
-}
-
-bool QEventDispatcherMac::hasPendingEvents()
-{
- extern uint qGlobalPostedEventsCount();
- return qGlobalPostedEventsCount() || (qt_is_gui_used && GetNumEventsInQueue(GetMainEventQueue()));
-}
-
-
-static bool qt_mac_send_event(QEventLoop::ProcessEventsFlags, OSEventRef event, OSWindowRef pt)
-{
-#ifndef QT_MAC_USE_COCOA
- if(pt && SendEventToWindow(event, pt) != eventNotHandledErr)
- return true;
- return !SendEventToEventTarget(event, GetEventDispatcherTarget());
-#else // QT_MAC_USE_COCOA
- if (pt)
- [pt sendEvent:event];
- else
- [NSApp sendEvent:event];
- return true;
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-static bool IsMouseOrKeyEvent( NSEvent* event )
-{
- bool result = false;
-
- switch( [event type] )
- {
- case NSLeftMouseDown:
- case NSLeftMouseUp:
- case NSRightMouseDown:
- case NSRightMouseUp:
- case NSMouseMoved: // ??
- case NSLeftMouseDragged:
- case NSRightMouseDragged:
- case NSMouseEntered:
- case NSMouseExited:
- case NSKeyDown:
- case NSKeyUp:
- case NSFlagsChanged: // key modifiers changed?
- case NSCursorUpdate: // ??
- case NSScrollWheel:
- case NSTabletPoint:
- case NSTabletProximity:
- case NSOtherMouseDown:
- case NSOtherMouseUp:
- case NSOtherMouseDragged:
-#ifndef QT_NO_GESTURES
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
- case NSEventTypeGesture: // touch events
- case NSEventTypeMagnify:
- case NSEventTypeSwipe:
- case NSEventTypeRotate:
- case NSEventTypeBeginGesture:
- case NSEventTypeEndGesture:
-#endif
-#endif // QT_NO_GESTURES
- result = true;
- break;
-
- default:
- break;
- }
- return result;
-}
-#endif
-
-static inline void qt_mac_waitForMoreEvents()
-{
-#ifndef QT_MAC_USE_COCOA
- while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e20, true) == kCFRunLoopRunTimedOut) ;
-#else
- // If no event exist in the cocoa event que, wait
- // (and free up cpu time) until at least one event occur.
- // This implementation is a bit on the edge, but seems to
- // work fine:
- NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
- untilDate:[NSDate distantFuture]
- inMode:NSDefaultRunLoopMode
- dequeue:YES];
- if (event)
- [NSApp postEvent:event atStart:YES];
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-static inline void qt_mac_waitForMoreModalSessionEvents()
-{
- // If no event exist in the cocoa event que, wait
- // (and free up cpu time) until at least one event occur.
- // This implementation is a bit on the edge, but seems to
- // work fine:
- NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
- untilDate:[NSDate distantFuture]
- inMode:NSModalPanelRunLoopMode
- dequeue:YES];
- if (event)
- [NSApp postEvent:event atStart:YES];
-}
-#endif
-
-bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
- Q_D(QEventDispatcherMac);
- d->interrupt = false;
-
-#ifdef QT_MAC_USE_COCOA
- bool interruptLater = false;
- QtMacInterruptDispatcherHelp::cancelInterruptLater();
-#endif
-
- // In case we end up recursing while we now process events, make sure
- // that we send remaining posted Qt events before this call returns:
- wakeUp();
- emit awake();
-
- bool excludeUserEvents = flags & QEventLoop::ExcludeUserInputEvents;
- bool retVal = false;
- forever {
- if (d->interrupt)
- break;
-
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- NSEvent* event = 0;
-
- // First, send all previously excluded input events, if any:
- if (!excludeUserEvents) {
- while (!d->queuedUserInputEvents.isEmpty()) {
- event = static_cast<NSEvent *>(d->queuedUserInputEvents.takeFirst());
- if (!filterEvent(event)) {
- qt_mac_send_event(flags, event, 0);
- retVal = true;
- }
- [event release];
- }
- }
-
- // If Qt is used as a plugin, or as an extension in a native cocoa
- // application, we should not run or stop NSApplication; This will be
- // done from the application itself. And if processEvents is called
- // manually (rather than from a QEventLoop), we cannot enter a tight
- // loop and block this call, but instead we need to return after one flush.
- // Finally, if we are to exclude user input events, we cannot call [NSApp run]
- // as we then loose control over which events gets dispatched:
- const bool canExec_3rdParty = d->nsAppRunCalledByQt || ![NSApp isRunning];
- const bool canExec_Qt = !excludeUserEvents &&
- (flags & QEventLoop::DialogExec || flags & QEventLoop::EventLoopExec) ;
-
- if (canExec_Qt && canExec_3rdParty) {
- // We can use exec-mode, meaning that we can stay in a tight loop until
- // interrupted. This is mostly an optimization, but it allow us to use
- // [NSApp run], which is the normal code path for cocoa applications.
- if (NSModalSession session = d->currentModalSession()) {
- QBoolBlocker execGuard(d->currentExecIsNSAppRun, false);
- while ([NSApp runModalSession:session] == NSRunContinuesResponse && !d->interrupt)
- qt_mac_waitForMoreModalSessionEvents();
-
- if (!d->interrupt && session == d->currentModalSessionCached) {
- // Someone called [NSApp stopModal:] from outside the event
- // dispatcher (e.g to stop a native dialog). But that call wrongly stopped
- // 'session' as well. As a result, we need to restart all internal sessions:
- d->temporarilyStopAllModalSessions();
- }
- } else {
- d->nsAppRunCalledByQt = true;
- QBoolBlocker execGuard(d->currentExecIsNSAppRun, true);
- [NSApp run];
- }
- retVal = true;
- } else {
- // We cannot block the thread (and run in a tight loop).
- // Instead we will process all current pending events and return.
- d->ensureNSAppInitialized();
- if (NSModalSession session = d->currentModalSession()) {
- // INVARIANT: a modal window is executing.
- if (!excludeUserEvents) {
- // Since we can dispatch all kinds of events, we choose
- // to use cocoa's native way of running modal sessions:
- if (flags & QEventLoop::WaitForMoreEvents)
- qt_mac_waitForMoreModalSessionEvents();
- NSInteger status = [NSApp runModalSession:session];
- if (status != NSRunContinuesResponse && session == d->currentModalSessionCached) {
- // INVARIANT: Someone called [NSApp stopModal:] from outside the event
- // dispatcher (e.g to stop a native dialog). But that call wrongly stopped
- // 'session' as well. As a result, we need to restart all internal sessions:
- d->temporarilyStopAllModalSessions();
- }
- retVal = true;
- } else do {
- // Dispatch all non-user events (but que non-user events up for later). In
- // this case, we need more control over which events gets dispatched, and
- // cannot use [NSApp runModalSession:session]:
- event = [NSApp nextEventMatchingMask:NSAnyEventMask
- untilDate:nil
- inMode:NSModalPanelRunLoopMode
- dequeue: YES];
-
- if (event) {
- if (IsMouseOrKeyEvent(event)) {
- [event retain];
- d->queuedUserInputEvents.append(event);
- continue;
- }
- if (!filterEvent(event) && qt_mac_send_event(flags, event, 0))
- retVal = true;
- }
- } while (!d->interrupt && event != nil);
- } else do {
- // INVARIANT: No modal window is executing.
- event = [NSApp nextEventMatchingMask:NSAnyEventMask
- untilDate:nil
- inMode:NSDefaultRunLoopMode
- dequeue: YES];
-
- if (event) {
- if (flags & QEventLoop::ExcludeUserInputEvents) {
- if (IsMouseOrKeyEvent(event)) {
- [event retain];
- d->queuedUserInputEvents.append(event);
- continue;
- }
- }
- if (!filterEvent(event) && qt_mac_send_event(flags, event, 0))
- retVal = true;
- }
- } while (!d->interrupt && event != nil);
-
- // Be sure to flush the Qt posted events when not using exec mode
- // (exec mode will always do this call from the event loop source):
- if (!d->interrupt)
- QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
-
- // Since the window that holds modality might have changed while processing
- // events, we we need to interrupt when we return back the previous process
- // event recursion to ensure that we spin the correct modal session.
- // We do the interruptLater at the end of the function to ensure that we don't
- // disturb the 'wait for more events' below (as deleteLater will post an event):
- interruptLater = true;
- }
-#else
- do {
- EventRef event;
- if (!(flags & QEventLoop::ExcludeUserInputEvents)
- && !d->queuedUserInputEvents.isEmpty()) {
- // process a pending user input event
- event = static_cast<EventRef>(d->queuedUserInputEvents.takeFirst());
- } else {
- OSStatus err = ReceiveNextEvent(0,0, kEventDurationNoWait, true, &event);
- if(err != noErr)
- continue;
- // else
- if (flags & QEventLoop::ExcludeUserInputEvents) {
- UInt32 ekind = GetEventKind(event),
- eclass = GetEventClass(event);
- switch(eclass) {
- case kEventClassQt:
- if(ekind != kEventQtRequestContext)
- break;
- // fall through
- case kEventClassMouse:
- case kEventClassKeyboard:
- d->queuedUserInputEvents.append(event);
- continue;
- }
- }
- }
-
- if (!filterEvent(&event) && qt_mac_send_event(flags, event, 0))
- retVal = true;
- ReleaseEvent(event);
- } while(!d->interrupt && GetNumEventsInQueue(GetMainEventQueue()) > 0);
-
-#endif
-
- bool canWait = (d->threadData->canWait
- && !retVal
- && !d->interrupt
- && (flags & QEventLoop::WaitForMoreEvents));
- if (canWait) {
- // INVARIANT: We haven't processed any events yet. And we're told
- // to stay inside this function until at least one event is processed.
- qt_mac_waitForMoreEvents();
- flags &= ~QEventLoop::WaitForMoreEvents;
- } else {
- // Done with event processing for now.
- // Leave the function:
- break;
- }
- }
-
- // If we're interrupted, we need to interrupt the _current_
- // recursion as well to check if it is still supposed to be
- // executing. This way we wind down the stack until we land
- // on a recursion that again calls processEvents (typically
- // from QEventLoop), and set interrupt to false:
- if (d->interrupt)
- interrupt();
-
-#ifdef QT_MAC_USE_COCOA
- if (interruptLater)
- QtMacInterruptDispatcherHelp::interruptLater();
-#endif
-
- return retVal;
-}
-
-void QEventDispatcherMac::wakeUp()
-{
- Q_D(QEventDispatcherMac);
- d->serialNumber.ref();
- CFRunLoopSourceSignal(d->postedEventsSource);
- CFRunLoopWakeUp(mainRunLoop());
-}
-
-void QEventDispatcherMac::flush()
-{
- if(qApp) {
- QWidgetList tlws = QApplication::topLevelWidgets();
- for(int i = 0; i < tlws.size(); i++) {
- QWidget *tlw = tlws.at(i);
- if(tlw->isVisible())
- macWindowFlush(qt_mac_window_for(tlw));
- }
- }
-}
-
-/*****************************************************************************
- QEventDispatcherMac Implementation
- *****************************************************************************/
-MacTimerHash QEventDispatcherMacPrivate::macTimerHash;
-bool QEventDispatcherMacPrivate::blockSendPostedEvents = false;
-bool QEventDispatcherMacPrivate::interrupt = false;
-
-#ifdef QT_MAC_USE_COCOA
-QStack<QCocoaModalSessionInfo> QEventDispatcherMacPrivate::cocoaModalSessionStack;
-bool QEventDispatcherMacPrivate::currentExecIsNSAppRun = false;
-bool QEventDispatcherMacPrivate::nsAppRunCalledByQt = false;
-bool QEventDispatcherMacPrivate::cleanupModalSessionsNeeded = false;
-NSModalSession QEventDispatcherMacPrivate::currentModalSessionCached = 0;
-
-void QEventDispatcherMacPrivate::ensureNSAppInitialized()
-{
- // Some elements in Cocoa require NSApplication to be running before
- // they get fully initialized, in particular the menu bar. This
- // function is intended for cases where a dialog is told to execute before
- // QApplication::exec is called, or the application spins the events loop
- // manually rather than calling QApplication:exec.
- // The function makes sure that NSApplication starts running, but stops
- // it again as soon as the send posted events callback is called. That way
- // we let Cocoa finish the initialization it seems to need. We'll only
- // apply this trick at most once for any application, and we avoid doing it
- // for the common case where main just starts QApplication::exec.
- if (nsAppRunCalledByQt || [NSApp isRunning])
- return;
- nsAppRunCalledByQt = true;
- QBoolBlocker block1(interrupt, true);
- QBoolBlocker block2(currentExecIsNSAppRun, true);
- [NSApp run];
-}
-
-void QEventDispatcherMacPrivate::temporarilyStopAllModalSessions()
-{
- // Flush, and Stop, all created modal session, and as
- // such, make them pending again. The next call to
- // currentModalSession will recreate them again. The
- // reason to stop all session like this is that otherwise
- // a call [NSApp stop] would not stop NSApp, but rather
- // the current modal session. So if we need to stop NSApp
- // we need to stop all the modal session first. To avoid changing
- // the stacking order of the windows while doing so, we put
- // up a block that is used in QCocoaWindow and QCocoaPanel:
- int stackSize = cocoaModalSessionStack.size();
- for (int i=0; i<stackSize; ++i) {
- QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (info.session) {
- [NSApp endModalSession:info.session];
- info.session = 0;
- }
- }
- currentModalSessionCached = 0;
-}
-
-NSModalSession QEventDispatcherMacPrivate::currentModalSession()
-{
- // If we have one or more modal windows, this function will create
- // a session for each of those, and return the one for the top.
- if (currentModalSessionCached)
- return currentModalSessionCached;
-
- if (cocoaModalSessionStack.isEmpty())
- return 0;
-
- int sessionCount = cocoaModalSessionStack.size();
- for (int i=0; i<sessionCount; ++i) {
- QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (!info.widget)
- continue;
- if (info.widget->testAttribute(Qt::WA_DontShowOnScreen))
- continue;
- if (!info.session) {
- QMacCocoaAutoReleasePool pool;
- NSWindow *window = qt_mac_window_for(info.widget);
- if (!window)
- continue;
-
- ensureNSAppInitialized();
- QBoolBlocker block1(blockSendPostedEvents, true);
- info.nswindow = window;
- [(NSWindow*) info.nswindow retain];
- int levelBeforeEnterModal = [window level];
- info.session = [NSApp beginModalSessionForWindow:window];
- // Make sure we don't stack the window lower that it was before
- // entering modal, in case it e.g. had the stays-on-top flag set:
- if (levelBeforeEnterModal > [window level])
- [window setLevel:levelBeforeEnterModal];
- }
- currentModalSessionCached = info.session;
- cleanupModalSessionsNeeded = false;
- }
- return currentModalSessionCached;
-}
-
-static void setChildrenWorksWhenModal(QWidget *widget, bool worksWhenModal)
-{
- // For NSPanels (but not NSWindows, sadly), we can set the flag
- // worksWhenModal, so that they are active even when they are not modal.
- QList<QDialog *> dialogs = widget->findChildren<QDialog *>();
- for (int i=0; i<dialogs.size(); ++i){
- NSWindow *window = qt_mac_window_for(dialogs[i]);
- if (window && [window isKindOfClass:[NSPanel class]]) {
- [static_cast<NSPanel *>(window) setWorksWhenModal:worksWhenModal];
- if (worksWhenModal && [window isVisible]){
- [window orderFront:window];
- }
- }
- }
-}
-
-void QEventDispatcherMacPrivate::updateChildrenWorksWhenModal()
-{
- // Make the dialog children of the widget
- // active. And make the dialog children of
- // the previous modal dialog unactive again:
- QMacCocoaAutoReleasePool pool;
- int size = cocoaModalSessionStack.size();
- if (size > 0){
- if (QWidget *prevModal = cocoaModalSessionStack[size-1].widget)
- setChildrenWorksWhenModal(prevModal, true);
- if (size > 1){
- if (QWidget *prevModal = cocoaModalSessionStack[size-2].widget)
- setChildrenWorksWhenModal(prevModal, false);
- }
- }
-}
-
-void QEventDispatcherMacPrivate::cleanupModalSessions()
-{
- // Go through the list of modal sessions, and end those
- // that no longer has a widget assosiated; no widget means
- // the the session has logically ended. The reason we wait like
- // this to actually end the sessions for real (rather than at the
- // point they were marked as stopped), is that ending a session
- // when no other session runs below it on the stack will make cocoa
- // drop some events on the floor.
- QMacCocoaAutoReleasePool pool;
- int stackSize = cocoaModalSessionStack.size();
-
- for (int i=stackSize-1; i>=0; --i) {
- QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (info.widget) {
- // This session has a widget, and is therefore not marked
- // as stopped. So just make it current. There might still be other
- // stopped sessions on the stack, but those will be stopped on
- // a later "cleanup" call.
- currentModalSessionCached = info.session;
- break;
- }
- cocoaModalSessionStack.remove(i);
- currentModalSessionCached = 0;
- if (info.session) {
- [NSApp endModalSession:info.session];
- [(NSWindow *)info.nswindow release];
- }
- }
-
- updateChildrenWorksWhenModal();
- cleanupModalSessionsNeeded = false;
-}
-
-void QEventDispatcherMacPrivate::beginModalSession(QWidget *widget)
-{
- // Add a new, empty (null), NSModalSession to the stack.
- // It will become active the next time QEventDispatcher::processEvents is called.
- // A QCocoaModalSessionInfo is considered pending to become active if the widget pointer
- // is non-zero, and the session pointer is zero (it will become active upon a call to
- // currentModalSession). A QCocoaModalSessionInfo is considered pending to be stopped if
- // the widget pointer is zero, and the session pointer is non-zero (it will be fully
- // stopped in cleanupModalSessions()).
- QCocoaModalSessionInfo info = {widget, 0, 0};
- cocoaModalSessionStack.push(info);
- updateChildrenWorksWhenModal();
- currentModalSessionCached = 0;
-}
-
-void QEventDispatcherMacPrivate::endModalSession(QWidget *widget)
-{
- // Mark all sessions attached to widget as pending to be stopped. We do this
- // by setting the widget pointer to zero, but leave the session pointer.
- // We don't tell cocoa to stop any sessions just yet, because cocoa only understands
- // when we stop the _current_ modal session (which is the session on top of
- // the stack, and might not belong to 'widget').
- int stackSize = cocoaModalSessionStack.size();
- for (int i=stackSize-1; i>=0; --i) {
- QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
- if (info.widget == widget) {
- info.widget = 0;
- if (i == stackSize-1) {
- // The top sessions ended. Interrupt the event dispatcher
- // to start spinning the correct session immidiatly:
- currentModalSessionCached = 0;
- cleanupModalSessionsNeeded = true;
- QEventDispatcherMac::instance()->interrupt();
- }
- }
- }
-}
-
-#endif
-
-QEventDispatcherMacPrivate::QEventDispatcherMacPrivate()
-{
-}
-
-QEventDispatcherMac::QEventDispatcherMac(QObject *parent)
- : QAbstractEventDispatcher(*new QEventDispatcherMacPrivate, parent)
-{
- Q_D(QEventDispatcherMac);
- CFRunLoopSourceContext context;
- bzero(&context, sizeof(CFRunLoopSourceContext));
- context.info = d;
- context.equal = QEventDispatcherMacPrivate::postedEventSourceEqualCallback;
- context.perform = QEventDispatcherMacPrivate::postedEventsSourcePerformCallback;
- d->postedEventsSource = CFRunLoopSourceCreate(0, 0, &context);
- Q_ASSERT(d->postedEventsSource);
- CFRunLoopAddSource(mainRunLoop(), d->postedEventsSource, kCFRunLoopCommonModes);
-
- CFRunLoopObserverContext observerContext;
- bzero(&observerContext, sizeof(CFRunLoopObserverContext));
- observerContext.info = this;
- d->waitingObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
- kCFRunLoopBeforeWaiting | kCFRunLoopAfterWaiting,
- true, 0,
- QEventDispatcherMacPrivate::waitingObserverCallback,
- &observerContext);
- CFRunLoopAddObserver(mainRunLoop(), d->waitingObserver, kCFRunLoopCommonModes);
-
- /* The first cycle in the loop adds the source and the events of the source
- are not processed.
- We use an observer to process the posted events for the first
- execution of the loop. */
- CFRunLoopObserverContext firstTimeObserverContext;
- bzero(&firstTimeObserverContext, sizeof(CFRunLoopObserverContext));
- firstTimeObserverContext.info = d;
- d->firstTimeObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
- kCFRunLoopEntry,
- /* repeats = */ false,
- 0,
- QEventDispatcherMacPrivate::firstLoopEntry,
- &firstTimeObserverContext);
- CFRunLoopAddObserver(mainRunLoop(), d->firstTimeObserver, kCFRunLoopCommonModes);
-}
-
-void QEventDispatcherMacPrivate::waitingObserverCallback(CFRunLoopObserverRef,
- CFRunLoopActivity activity, void *info)
-{
- if (activity == kCFRunLoopBeforeWaiting)
- emit static_cast<QEventDispatcherMac*>(info)->aboutToBlock();
- else
- emit static_cast<QEventDispatcherMac*>(info)->awake();
-}
-
-Boolean QEventDispatcherMacPrivate::postedEventSourceEqualCallback(const void *info1, const void *info2)
-{
- return info1 == info2;
-}
-
-inline static void processPostedEvents(QEventDispatcherMacPrivate *const d, const bool blockSendPostedEvents)
-{
- if (blockSendPostedEvents) {
- // We're told to not send posted events (because the event dispatcher
- // is currently working on setting up the correct session to run). But
- // we still need to make sure that we don't fall asleep until pending events
- // are sendt, so we just signal this need, and return:
- CFRunLoopSourceSignal(d->postedEventsSource);
- return;
- }
-
-#ifdef QT_MAC_USE_COCOA
- if (d->cleanupModalSessionsNeeded)
- d->cleanupModalSessions();
-#endif
-
- if (d->interrupt) {
-#ifdef QT_MAC_USE_COCOA
- if (d->currentExecIsNSAppRun) {
- // The event dispatcher has been interrupted. But since
- // [NSApplication run] is running the event loop, we
- // delayed stopping it until now (to let cocoa process
- // pending cocoa events first).
- if (d->currentModalSessionCached)
- d->temporarilyStopAllModalSessions();
- [NSApp stop:NSApp];
- d->cancelWaitForMoreEvents();
- }
-#endif
- return;
- }
-
- if (!d->threadData->canWait || (d->serialNumber != d->lastSerial)) {
- d->lastSerial = d->serialNumber;
- QApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
- }
-}
-
-void QEventDispatcherMacPrivate::firstLoopEntry(CFRunLoopObserverRef ref,
- CFRunLoopActivity activity,
- void *info)
-{
- Q_UNUSED(ref);
- Q_UNUSED(activity);
-#ifdef QT_MAC_USE_COCOA
- QApplicationPrivate::qt_initAfterNSAppStarted();
-#endif
- processPostedEvents(static_cast<QEventDispatcherMacPrivate *>(info), blockSendPostedEvents);
-}
-
-void QEventDispatcherMacPrivate::postedEventsSourcePerformCallback(void *info)
-{
- processPostedEvents(static_cast<QEventDispatcherMacPrivate *>(info), blockSendPostedEvents);
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QEventDispatcherMacPrivate::cancelWaitForMoreEvents()
-{
- // In case the event dispatcher is waiting for more
- // events somewhere, we post a dummy event to wake it up:
- QMacCocoaAutoReleasePool pool;
- [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined location:NSZeroPoint
- modifierFlags:0 timestamp:0. windowNumber:0 context:0
- subtype:QtCocoaEventSubTypeWakeup data1:0 data2:0] atStart:NO];
-}
-#endif
-
-void QEventDispatcherMac::interrupt()
-{
- Q_D(QEventDispatcherMac);
- d->interrupt = true;
- wakeUp();
-
-#ifndef QT_MAC_USE_COCOA
- CFRunLoopStop(mainRunLoop());
-#else
- // We do nothing more here than setting d->interrupt = true, and
- // poke the event loop if it is sleeping. Actually stopping
- // NSApp, or the current modal session, is done inside the send
- // posted events callback. We do this to ensure that all current pending
- // cocoa events gets delivered before we stop. Otherwise, if we now stop
- // the last event loop recursion, cocoa will just drop pending posted
- // events on the floor before we get a chance to reestablish a new session.
- d->cancelWaitForMoreEvents();
-#endif
-}
-
-QEventDispatcherMac::~QEventDispatcherMac()
-{
- Q_D(QEventDispatcherMac);
- //timer cleanup
- MacTimerHash::iterator it = QEventDispatcherMacPrivate::macTimerHash.begin();
- while (it != QEventDispatcherMacPrivate::macTimerHash.end()) {
- MacTimerInfo *t = it.value();
- if (t->runLoopTimer) {
- CFRunLoopTimerInvalidate(t->runLoopTimer);
- CFRelease(t->runLoopTimer);
- }
- delete t;
- ++it;
- }
- QEventDispatcherMacPrivate::macTimerHash.clear();
-
- // Remove CFSockets from the runloop.
- for (MacSocketHash::ConstIterator it = d->macSockets.constBegin(); it != d->macSockets.constEnd(); ++it) {
- MacSocketInfo *socketInfo = (*it);
- if (CFSocketIsValid(socketInfo->socket)) {
- qt_mac_remove_socket_from_runloop(socketInfo->socket, socketInfo->runloop);
- CFRunLoopSourceInvalidate(socketInfo->runloop);
- CFRelease(socketInfo->runloop);
- CFSocketInvalidate(socketInfo->socket);
- CFRelease(socketInfo->socket);
- }
- }
- CFRunLoopRemoveSource(mainRunLoop(), d->postedEventsSource, kCFRunLoopCommonModes);
- CFRelease(d->postedEventsSource);
-
- CFRunLoopObserverInvalidate(d->waitingObserver);
- CFRelease(d->waitingObserver);
-
- CFRunLoopObserverInvalidate(d->firstTimeObserver);
- CFRelease(d->firstTimeObserver);
-}
-
-#ifdef QT_MAC_USE_COCOA
-
-QtMacInterruptDispatcherHelp* QtMacInterruptDispatcherHelp::instance = 0;
-
-QtMacInterruptDispatcherHelp::QtMacInterruptDispatcherHelp() : cancelled(false)
-{
- // The whole point of this class is that we enable a way to interrupt
- // the event dispatcher when returning back to a lower recursion level
- // than where interruptLater was called. This is needed to detect if
- // [NSApp run] should still be running at the recursion level it is at.
- // Since the interrupt is canceled if processEvents is called before
- // this object gets deleted, we also avoid interrupting unnecessary.
- deleteLater();
-}
-
-QtMacInterruptDispatcherHelp::~QtMacInterruptDispatcherHelp()
-{
- if (cancelled)
- return;
- instance = 0;
- QEventDispatcherMac::instance()->interrupt();
-}
-
-void QtMacInterruptDispatcherHelp::cancelInterruptLater()
-{
- if (!instance)
- return;
- instance->cancelled = true;
- delete instance;
- instance = 0;
-}
-
-void QtMacInterruptDispatcherHelp::interruptLater()
-{
- cancelInterruptLater();
- instance = new QtMacInterruptDispatcherHelp;
-}
-
-#endif
-
-QT_END_NAMESPACE
-
diff --git a/src/gui/platforms/mac/qeventdispatcher_mac_p.h b/src/gui/platforms/mac/qeventdispatcher_mac_p.h
deleted file mode 100644
index 12fcafbb01..0000000000
--- a/src/gui/platforms/mac/qeventdispatcher_mac_p.h
+++ /dev/null
@@ -1,224 +0,0 @@
-/****************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-#ifndef QEVENTDISPATCHER_MAC_P_H
-#define QEVENTDISPATCHER_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/qwindowdefs.h>
-#include <QtCore/qhash.h>
-#include <QtCore/qstack.h>
-#include "private/qabstracteventdispatcher_p.h"
-#include "private/qt_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-typedef struct _NSModalSession *NSModalSession;
-typedef struct _QCocoaModalSessionInfo {
- QPointer<QWidget> widget;
- NSModalSession session;
- void *nswindow;
-} QCocoaModalSessionInfo;
-#endif
-
-class QEventDispatcherMacPrivate;
-
-class QEventDispatcherMac : public QAbstractEventDispatcher
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QEventDispatcherMac)
-
-public:
- explicit QEventDispatcherMac(QObject *parent = 0);
- ~QEventDispatcherMac();
-
- bool processEvents(QEventLoop::ProcessEventsFlags flags);
- bool hasPendingEvents();
-
- void registerSocketNotifier(QSocketNotifier *notifier);
- void unregisterSocketNotifier(QSocketNotifier *notifier);
-
- void registerTimer(int timerId, int interval, QObject *object);
- bool unregisterTimer(int timerId);
- bool unregisterTimers(QObject *object);
- QList<TimerInfo> registeredTimers(QObject *object) const;
-
- void wakeUp();
- void flush();
- void interrupt();
-
-private:
- friend void qt_mac_select_timer_callbk(__EventLoopTimer*, void*);
- friend class QApplicationPrivate;
-};
-
-struct MacTimerInfo {
- int id;
- int interval;
- QObject *obj;
- bool pending;
- CFRunLoopTimerRef runLoopTimer;
- bool operator==(const MacTimerInfo &other)
- {
- return (id == other.id);
- }
-};
-typedef QHash<int, MacTimerInfo *> MacTimerHash;
-
-struct MacSocketInfo {
- MacSocketInfo() : socket(0), runloop(0), readNotifier(0), writeNotifier(0) {}
- CFSocketRef socket;
- CFRunLoopSourceRef runloop;
- QObject *readNotifier;
- QObject *writeNotifier;
-};
-typedef QHash<int, MacSocketInfo *> MacSocketHash;
-
-class QEventDispatcherMacPrivate : public QAbstractEventDispatcherPrivate
-{
- Q_DECLARE_PUBLIC(QEventDispatcherMac)
-
-public:
- QEventDispatcherMacPrivate();
-
- static MacTimerHash macTimerHash;
- // Set 'blockSendPostedEvents' to true if you _really_ need
- // to make sure that qt events are not posted while calling
- // low-level cocoa functions (like beginModalForWindow). And
- // use a QBoolBlocker to be safe:
- static bool blockSendPostedEvents;
-#ifdef QT_MAC_USE_COCOA
- // The following variables help organizing modal sessions:
- static QStack<QCocoaModalSessionInfo> cocoaModalSessionStack;
- static bool currentExecIsNSAppRun;
- static bool nsAppRunCalledByQt;
- static bool cleanupModalSessionsNeeded;
- static NSModalSession currentModalSessionCached;
- static NSModalSession currentModalSession();
- static void updateChildrenWorksWhenModal();
- static void temporarilyStopAllModalSessions();
- static void beginModalSession(QWidget *widget);
- static void endModalSession(QWidget *widget);
- static void cancelWaitForMoreEvents();
- static void cleanupModalSessions();
- static void ensureNSAppInitialized();
-#endif
-
- MacSocketHash macSockets;
- QList<void *> queuedUserInputEvents; // List of EventRef in Carbon, and NSEvent * in Cocoa
- CFRunLoopSourceRef postedEventsSource;
- CFRunLoopObserverRef waitingObserver;
- CFRunLoopObserverRef firstTimeObserver;
- QAtomicInt serialNumber;
- int lastSerial;
- static bool interrupt;
-private:
- static Boolean postedEventSourceEqualCallback(const void *info1, const void *info2);
- static void postedEventsSourcePerformCallback(void *info);
- static void activateTimer(CFRunLoopTimerRef, void *info);
- static void waitingObserverCallback(CFRunLoopObserverRef observer,
- CFRunLoopActivity activity, void *info);
- static void firstLoopEntry(CFRunLoopObserverRef ref, CFRunLoopActivity activity, void *info);
-};
-
-#ifdef QT_MAC_USE_COCOA
-class QtMacInterruptDispatcherHelp : public QObject
-{
- static QtMacInterruptDispatcherHelp *instance;
- bool cancelled;
-
- QtMacInterruptDispatcherHelp();
- ~QtMacInterruptDispatcherHelp();
-
- public:
- static void interruptLater();
- static void cancelInterruptLater();
-};
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QEVENTDISPATCHER_MAC_P_H
diff --git a/src/gui/platforms/mac/qfont_mac.cpp b/src/gui/platforms/mac/qfont_mac.cpp
deleted file mode 100644
index daf68c03ea..0000000000
--- a/src/gui/platforms/mac/qfont_mac.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfont.h"
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qfontengine_mac_p.h"
-#include "qfontinfo.h"
-#include "qfontmetrics.h"
-#include "qpaintdevice.h"
-#include "qstring.h"
-#include <private/qt_mac_p.h>
-#include <private/qtextengine_p.h>
-#include <private/qunicodetables_p.h>
-#include <qapplication.h>
-#include "qfontdatabase.h"
-#include <qpainter.h>
-#include "qtextengine_p.h"
-#include <stdlib.h>
-
-QT_BEGIN_NAMESPACE
-
-extern float qt_mac_defaultDpi_x(); //qpaintdevice_mac.cpp
-
-int qt_mac_pixelsize(const QFontDef &def, int dpi)
-{
- float ret;
- if(def.pixelSize == -1)
- ret = def.pointSize * dpi / qt_mac_defaultDpi_x();
- else
- ret = def.pixelSize;
- return qRound(ret);
-}
-int qt_mac_pointsize(const QFontDef &def, int dpi)
-{
- float ret;
- if(def.pointSize < 0)
- ret = def.pixelSize * qt_mac_defaultDpi_x() / float(dpi);
- else
- ret = def.pointSize;
- return qRound(ret);
-}
-
-QString QFont::rawName() const
-{
- return family();
-}
-
-void QFont::setRawName(const QString &name)
-{
- setFamily(name);
-}
-
-void QFont::cleanup()
-{
- QFontCache::cleanup();
-}
-
-/*!
- Returns an ATSUFontID
-*/
-quint32 QFont::macFontID() const // ### need 64-bit version
-{
-#ifdef QT_MAC_USE_COCOA
- return 0;
-#elif 1
- QFontEngine *fe = d->engineForScript(QUnicodeTables::Common);
- if (fe && fe->type() == QFontEngine::Multi)
- return static_cast<QFontEngineMacMulti*>(fe)->macFontID();
-#else
- Str255 name;
- if(FMGetFontFamilyName((FMFontFamily)((UInt32)handle()), name) == noErr) {
- short fnum;
- GetFNum(name, &fnum);
- return fnum;
- }
-#endif
- return 0;
-}
-
-// Returns an ATSUFonFamilyRef
-Qt::HANDLE QFont::handle() const
-{
-#if 0
- QFontEngine *fe = d->engineForScript(QUnicodeTables::Common);
- if (fe && fe->type() == QFontEngine::Mac)
- return (Qt::HANDLE)static_cast<QFontEngineMacMulti*>(fe)->fontFamilyRef();
-#endif
- return 0;
-}
-
-void QFont::initialize()
-{ }
-
-QString QFont::defaultFamily() const
-{
- switch(d->request.styleHint) {
- case QFont::Times:
- return QString::fromLatin1("Times New Roman");
- case QFont::Courier:
- return QString::fromLatin1("Courier New");
- case QFont::Monospace:
- return QString::fromLatin1("Courier");
- case QFont::Decorative:
- return QString::fromLatin1("Bookman Old Style");
- case QFont::Cursive:
- return QString::fromLatin1("Apple Chancery");
- case QFont::Fantasy:
- return QString::fromLatin1("Papyrus");
- case QFont::Helvetica:
- case QFont::System:
- default:
- return QString::fromLatin1("Helvetica");
- }
-}
-
-QString QFont::lastResortFamily() const
-{
- return QString::fromLatin1("Helvetica");
-}
-
-QString QFont::lastResortFont() const
-{
- return QString::fromLatin1("Geneva");
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qfontdatabase_mac.cpp b/src/gui/platforms/mac/qfontdatabase_mac.cpp
deleted file mode 100644
index 5ba236b5f7..0000000000
--- a/src/gui/platforms/mac/qfontdatabase_mac.cpp
+++ /dev/null
@@ -1,466 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qt_mac_p.h>
-#include "qfontengine_p.h"
-#include <qfile.h>
-#include <qabstractfileengine.h>
-#include <stdlib.h>
-#include <qendian.h>
-#include <private/qfontengine_coretext_p.h>
-#include <private/qfontengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-int qt_mac_pixelsize(const QFontDef &def, int dpi); //qfont_mac.cpp
-int qt_mac_pointsize(const QFontDef &def, int dpi); //qfont_mac.cpp
-
-#ifndef QT_MAC_USE_COCOA
-static void initWritingSystems(QtFontFamily *family, ATSFontRef atsFont)
-{
- ByteCount length = 0;
- if (ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 0, 0, 0, &length) != noErr)
- return;
- QVarLengthArray<uchar> os2Table(length);
- if (length < 86
- || ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 0, length, os2Table.data(), &length) != noErr)
- return;
-
- // See also qfontdatabase_win.cpp, offsets taken from OS/2 table in the TrueType spec
- quint32 unicodeRange[4] = {
- qFromBigEndian<quint32>(os2Table.data() + 42),
- qFromBigEndian<quint32>(os2Table.data() + 46),
- qFromBigEndian<quint32>(os2Table.data() + 50),
- qFromBigEndian<quint32>(os2Table.data() + 54)
- };
- quint32 codePageRange[2] = { qFromBigEndian<quint32>(os2Table.data() + 78), qFromBigEndian<quint32>(os2Table.data() + 82) };
- QList<QFontDatabase::WritingSystem> systems = qt_determine_writing_systems_from_truetype_bits(unicodeRange, codePageRange);
-#if 0
- QCFString name;
- ATSFontGetName(atsFont, kATSOptionFlagsDefault, &name);
- qDebug() << systems.count() << "writing systems for" << QString(name);
-qDebug() << "first char" << hex << unicodeRange[0];
- for (int i = 0; i < systems.count(); ++i)
- qDebug() << QFontDatabase::writingSystemName(systems.at(i));
-#endif
- for (int i = 0; i < systems.count(); ++i)
- family->writingSystems[systems.at(i)] = QtFontFamily::Supported;
-}
-#endif
-
-static void initializeDb()
-{
- QFontDatabasePrivate *db = privateDb();
- if(!db || db->count)
- return;
-
-#if defined(QT_MAC_USE_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- QCFType<CTFontCollectionRef> collection = CTFontCollectionCreateFromAvailableFonts(0);
- if(!collection)
- return;
- QCFType<CFArrayRef> fonts = CTFontCollectionCreateMatchingFontDescriptors(collection);
- if(!fonts)
- return;
- QString foundry_name = "CoreText";
- const int numFonts = CFArrayGetCount(fonts);
- for(int i = 0; i < numFonts; ++i) {
- CTFontDescriptorRef font = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fonts, i);
-
- QCFString family_name = (CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontFamilyNameAttribute);
- QtFontFamily *family = db->family(family_name, true);
- for(int ws = 1; ws < QFontDatabase::WritingSystemsCount; ++ws)
- family->writingSystems[ws] = QtFontFamily::Supported;
- QtFontFoundry *foundry = family->foundry(foundry_name, true);
-
- QtFontStyle::Key styleKey;
- if(QCFType<CFDictionaryRef> styles = (CFDictionaryRef)CTFontDescriptorCopyAttribute(font, kCTFontTraitsAttribute)) {
- if(CFNumberRef weight = (CFNumberRef)CFDictionaryGetValue(styles, kCTFontWeightTrait)) {
- Q_ASSERT(CFNumberIsFloatType(weight));
- double d;
- if(CFNumberGetValue(weight, kCFNumberDoubleType, &d)) {
- //qDebug() << "BOLD" << (QString)family_name << d;
- styleKey.weight = (d > 0.0) ? QFont::Bold : QFont::Normal;
- }
- }
- if(CFNumberRef italic = (CFNumberRef)CFDictionaryGetValue(styles, kCTFontSlantTrait)) {
- Q_ASSERT(CFNumberIsFloatType(italic));
- double d;
- if(CFNumberGetValue(italic, kCFNumberDoubleType, &d)) {
- //qDebug() << "ITALIC" << (QString)family_name << d;
- if (d > 0.0)
- styleKey.style = QFont::StyleItalic;
- }
- }
- }
-
- QtFontStyle *style = foundry->style(styleKey, true);
- style->smoothScalable = true;
- if(QCFType<CFNumberRef> size = (CFNumberRef)CTFontDescriptorCopyAttribute(font, kCTFontSizeAttribute)) {
- //qDebug() << "WHEE";
- int pixel_size=0;
- if(CFNumberIsFloatType(size)) {
- double d;
- CFNumberGetValue(size, kCFNumberDoubleType, &d);
- pixel_size = d;
- } else {
- CFNumberGetValue(size, kCFNumberIntType, &pixel_size);
- }
- //qDebug() << "SIZE" << (QString)family_name << pixel_size;
- if(pixel_size)
- style->pixelSize(pixel_size, true);
- } else {
- //qDebug() << "WTF?";
- }
- }
-} else
-#endif
- {
-#ifndef QT_MAC_USE_COCOA
- FMFontIterator it;
- if (!FMCreateFontIterator(0, 0, kFMUseGlobalScopeOption, &it)) {
- while (true) {
- FMFont fmFont;
- if (FMGetNextFont(&it, &fmFont) != noErr)
- break;
-
- FMFontFamily fmFamily;
- FMFontStyle fmStyle;
- QString familyName;
-
- QtFontStyle::Key styleKey;
-
- ATSFontRef atsFont = FMGetATSFontRefFromFont(fmFont);
-
- if (!FMGetFontFamilyInstanceFromFont(fmFont, &fmFamily, &fmStyle)) {
- { //sanity check the font, and see if we can use it at all! --Sam
- ATSUFontID fontID;
- if(ATSUFONDtoFontID(fmFamily, 0, &fontID) != noErr)
- continue;
- }
-
- if (fmStyle & ::italic)
- styleKey.style = QFont::StyleItalic;
- if (fmStyle & ::bold)
- styleKey.weight = QFont::Bold;
-
- ATSFontFamilyRef familyRef = FMGetATSFontFamilyRefFromFontFamily(fmFamily);
- QCFString cfFamilyName;;
- ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &cfFamilyName);
- familyName = cfFamilyName;
- } else {
- QCFString cfFontName;
- ATSFontGetName(atsFont, kATSOptionFlagsDefault, &cfFontName);
- familyName = cfFontName;
- quint16 macStyle = 0;
- {
- uchar data[4];
- ByteCount len = 4;
- if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 44, 4, &data, &len) == noErr)
- macStyle = qFromBigEndian<quint16>(data);
- }
- if (macStyle & 1)
- styleKey.weight = QFont::Bold;
- if (macStyle & 2)
- styleKey.style = QFont::StyleItalic;
- }
-
- QtFontFamily *family = db->family(familyName, true);
- QtFontFoundry *foundry = family->foundry(QString(), true);
- QtFontStyle *style = foundry->style(styleKey, true);
- style->pixelSize(0, true);
- style->smoothScalable = true;
-
- initWritingSystems(family, atsFont);
- }
- FMDisposeFontIterator(&it);
- }
-#endif
- }
-
-}
-
-static inline void load(const QString & = QString(), int = -1)
-{
- initializeDb();
-}
-
-static const char *styleHint(const QFontDef &request)
-{
- const char *stylehint = 0;
- switch (request.styleHint) {
- case QFont::SansSerif:
- stylehint = "Arial";
- break;
- case QFont::Serif:
- stylehint = "Times New Roman";
- break;
- case QFont::TypeWriter:
- stylehint = "Courier New";
- break;
- default:
- if (request.fixedPitch)
- stylehint = "Courier New";
- break;
- }
- return stylehint;
-}
-
-static inline float weightToFloat(unsigned int weight)
-{
- return (weight - 50) / 100.0;
-}
-
-void QFontDatabase::load(const QFontPrivate *d, int script)
-{
- // sanity checks
- if(!qApp)
- qWarning("QFont: Must construct a QApplication before a QFont");
-
- Q_ASSERT(script >= 0 && script < QUnicodeTables::ScriptCount);
- Q_UNUSED(script);
-
- QFontDef req = d->request;
- req.pixelSize = qt_mac_pixelsize(req, d->dpi);
-
- // set the point size to 0 to get better caching
- req.pointSize = 0;
- QFontCache::Key key = QFontCache::Key(req, QUnicodeTables::Common, d->screen);
-
- if(!(d->engineData = QFontCache::instance()->findEngineData(key))) {
- d->engineData = new QFontEngineData;
- QFontCache::instance()->insertEngineData(key, d->engineData);
- } else {
- d->engineData->ref.ref();
- }
- if(d->engineData->engine) // already loaded
- return;
-
- // set it to the actual pointsize, so QFontInfo will do the right thing
- req.pointSize = qRound(qt_mac_pointsize(d->request, d->dpi));
-
- QFontEngine *e = QFontCache::instance()->findEngine(key);
- if(!e && qt_enable_test_font && req.family == QLatin1String("__Qt__Box__Engine__")) {
- e = new QTestFontEngine(req.pixelSize);
- e->fontDef = req;
- }
-
- if(e) {
- e->ref.ref();
- d->engineData->engine = e;
- return; // the font info and fontdef should already be filled
- }
-
- //find the font
- QStringList family_list = familyList(req);
-
- const char *stylehint = styleHint(req);
- if (stylehint)
- family_list << QLatin1String(stylehint);
-
- // add QFont::defaultFamily() to the list, for compatibility with
- // previous versions
- family_list << QApplication::font().defaultFamily();
-
-#if defined(QT_MAC_USE_COCOA)
- QCFString fontName = NULL, familyName = NULL;
-#else
- ATSFontFamilyRef familyRef = 0;
- ATSFontRef fontRef = 0;
-#endif
-
- QMutexLocker locker(fontDatabaseMutex());
- QFontDatabasePrivate *db = privateDb();
- if (!db->count)
- initializeDb();
- for(int i = 0; i < family_list.size(); ++i) {
- for (int k = 0; k < db->count; ++k) {
- if (db->families[k]->name.compare(family_list.at(i), Qt::CaseInsensitive) == 0) {
- QByteArray family_name = db->families[k]->name.toUtf8();
-#if defined(QT_MAC_USE_COCOA)
- QCFType<CTFontRef> ctFont = CTFontCreateWithName(QCFString(db->families[k]->name), 12, NULL);
- if (ctFont) {
- fontName = CTFontCopyFullName(ctFont);
- familyName = CTFontCopyFamilyName(ctFont);
- goto FamilyFound;
- }
-#else
- familyRef = ATSFontFamilyFindFromName(QCFString(db->families[k]->name), kATSOptionFlagsDefault);
- if (familyRef) {
- fontRef = ATSFontFindFromName(QCFString(db->families[k]->name), kATSOptionFlagsDefault);
- goto FamilyFound;
- }
-#endif
- }
- }
- }
-FamilyFound:
- //fill in the engine's font definition
- QFontDef fontDef = d->request; //copy..
- if(fontDef.pointSize < 0)
- fontDef.pointSize = qt_mac_pointsize(fontDef, d->dpi);
- else
- fontDef.pixelSize = qt_mac_pixelsize(fontDef, d->dpi);
-
-#ifdef QT_MAC_USE_COCOA
- fontDef.family = familyName;
- QFontEngine *engine = new QCoreTextFontEngineMulti(fontName, fontDef, d->kerning);
-#else
- QCFString actualName;
- if (ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &actualName) == noErr)
- fontDef.family = actualName;
- QFontEngine *engine = new QFontEngineMacMulti(familyRef, fontRef, fontDef, d->kerning);
-#endif
- d->engineData->engine = engine;
- engine->ref.ref(); //a ref for the engineData->engine
- QFontCache::instance()->insertEngine(key, engine);
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
-{
- ATSFontContainerRef handle;
- OSStatus e = noErr;
-
- if(fnt->data.isEmpty()) {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- extern OSErr qt_mac_create_fsref(const QString &, FSRef *); // qglobal.cpp
- FSRef ref;
- if(qt_mac_create_fsref(fnt->fileName, &ref) != noErr)
- return;
-
- ATSFontActivateFromFileReference(&ref, kATSFontContextLocal, kATSFontFormatUnspecified, 0, kATSOptionFlagsDefault, &handle);
- } else
-#endif
- {
-#ifndef Q_WS_MAC64
- extern Q_CORE_EXPORT OSErr qt_mac_create_fsspec(const QString &, FSSpec *); // global.cpp
- FSSpec spec;
- if(qt_mac_create_fsspec(fnt->fileName, &spec) != noErr)
- return;
-
- e = ATSFontActivateFromFileSpecification(&spec, kATSFontContextLocal, kATSFontFormatUnspecified,
- 0, kATSOptionFlagsDefault, &handle);
-#endif
- }
- } else {
- e = ATSFontActivateFromMemory((void *)fnt->data.constData(), fnt->data.size(), kATSFontContextLocal,
- kATSFontFormatUnspecified, 0, kATSOptionFlagsDefault, &handle);
-
- fnt->data = QByteArray();
- }
-
- if(e != noErr)
- return;
-
- ItemCount fontCount = 0;
- e = ATSFontFindFromContainer(handle, kATSOptionFlagsDefault, 0, 0, &fontCount);
- if(e != noErr)
- return;
-
- QVarLengthArray<ATSFontRef> containedFonts(fontCount);
- e = ATSFontFindFromContainer(handle, kATSOptionFlagsDefault, fontCount, containedFonts.data(), &fontCount);
- if(e != noErr)
- return;
-
- fnt->families.clear();
-#if defined(QT_MAC_USE_COCOA)
- // Make sure that the family name set on the font matches what
- // kCTFontFamilyNameAttribute returns in initializeDb().
- // So far the best solution seems find the installed font
- // using CoreText and get the family name from it.
- // (ATSFontFamilyGetName appears to be the correct API, but also
- // returns the font display name.)
- for(int i = 0; i < containedFonts.size(); ++i) {
- QCFString fontPostScriptName;
- ATSFontGetPostScriptName(containedFonts[i], kATSOptionFlagsDefault, &fontPostScriptName);
- QCFType<CTFontDescriptorRef> font = CTFontDescriptorCreateWithNameAndSize(fontPostScriptName, 14);
- QCFString familyName = (CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontFamilyNameAttribute);
- fnt->families.append(familyName);
- }
-#else
- for(int i = 0; i < containedFonts.size(); ++i) {
- QCFString family;
- ATSFontGetName(containedFonts[i], kATSOptionFlagsDefault, &family);
- fnt->families.append(family);
- }
-#endif
-
- fnt->handle = handle;
-}
-
-bool QFontDatabase::removeApplicationFont(int handle)
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- if(handle < 0 || handle >= db->applicationFonts.count())
- return false;
-
- OSStatus e = ATSFontDeactivate(db->applicationFonts.at(handle).handle,
- /*iRefCon=*/0, kATSOptionFlagsDefault);
- if(e != noErr)
- return false;
-
- db->applicationFonts[handle] = QFontDatabasePrivate::ApplicationFont();
-
- db->invalidate();
- return true;
-}
-
-bool QFontDatabase::removeAllApplicationFonts()
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- for(int i = 0; i < db->applicationFonts.count(); ++i) {
- if(!removeApplicationFont(i))
- return false;
- }
- return true;
-}
-
-bool QFontDatabase::supportsThreadedFontRendering()
-{
- return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qfontengine_coretext.mm b/src/gui/platforms/mac/qfontengine_coretext.mm
deleted file mode 100644
index d4df2183ed..0000000000
--- a/src/gui/platforms/mac/qfontengine_coretext.mm
+++ /dev/null
@@ -1,880 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfontengine_coretext_p.h"
-
-#include <QtCore/qendian.h>
-#include <QtCore/qsettings.h>
-
-#include <private/qimage_p.h>
-
-#if !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-
-QT_BEGIN_NAMESPACE
-
-static float SYNTHETIC_ITALIC_SKEW = tanf(14 * acosf(0) / 90);
-
-static void loadAdvancesForGlyphs(CTFontRef ctfont,
- QVarLengthArray<CGGlyph> &cgGlyphs,
- QGlyphLayout *glyphs, int len,
- QTextEngine::ShaperFlags flags,
- const QFontDef &fontDef)
-{
- Q_UNUSED(flags);
- QVarLengthArray<CGSize> advances(len);
- CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, cgGlyphs.data(), advances.data(), len);
-
- for (int i = 0; i < len; ++i) {
- if (glyphs->glyphs[i] & 0xff000000)
- continue;
- glyphs->advances_x[i] = QFixed::fromReal(advances[i].width);
- glyphs->advances_y[i] = QFixed::fromReal(advances[i].height);
- }
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- for (int i = 0; i < len; ++i) {
- glyphs->advances_x[i] = glyphs->advances_x[i].round();
- glyphs->advances_y[i] = glyphs->advances_y[i].round();
- }
- }
-}
-
-QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(const QCFString &name, const QFontDef &fontDef, bool kerning)
- : QFontEngineMulti(0)
-{
- this->fontDef = fontDef;
- CTFontSymbolicTraits symbolicTraits = 0;
- if (fontDef.weight >= QFont::Bold)
- symbolicTraits |= kCTFontBoldTrait;
- switch (fontDef.style) {
- case QFont::StyleNormal:
- break;
- case QFont::StyleItalic:
- case QFont::StyleOblique:
- symbolicTraits |= kCTFontItalicTrait;
- break;
- }
-
- transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100) {
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- }
-
- QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithNameAndSize(name, fontDef.pixelSize);
- QCFType<CTFontRef> baseFont = CTFontCreateWithFontDescriptor(descriptor, fontDef.pixelSize, &transform);
- ctfont = CTFontCreateCopyWithSymbolicTraits(baseFont, fontDef.pixelSize, &transform, symbolicTraits, symbolicTraits);
-
- // CTFontCreateCopyWithSymbolicTraits returns NULL if we ask for a trait that does
- // not exist for the given font. (for example italic)
- if (ctfont == 0) {
- ctfont = baseFont;
- CFRetain(ctfont);
- }
- init(kerning);
-}
-
-QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(CGFontRef cgFontRef, const QFontDef &fontDef, bool kerning)
- : QFontEngineMulti(0)
-{
- this->fontDef = fontDef;
-
- transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100) {
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- }
-
- ctfont = CTFontCreateWithGraphicsFont(cgFontRef, fontDef.pixelSize, &transform, NULL);
- init(kerning);
-}
-
-QCoreTextFontEngineMulti::~QCoreTextFontEngineMulti()
-{
- CFRelease(ctfont);
-}
-
-void QCoreTextFontEngineMulti::init(bool kerning)
-{
- Q_ASSERT(ctfont != NULL);
- attributeDict = CFDictionaryCreateMutable(0, 2,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- CFDictionaryAddValue(attributeDict, NSFontAttributeName, ctfont);
- if (!kerning) {
- float zero = 0.0;
- QCFType<CFNumberRef> noKern = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero);
- CFDictionaryAddValue(attributeDict, kCTKernAttributeName, noKern);
- }
-
- QCoreTextFontEngine *fe = new QCoreTextFontEngine(ctfont, fontDef);
- fe->ref.ref();
- engines.append(fe);
-}
-
-uint QCoreTextFontEngineMulti::fontIndexForFont(CTFontRef font) const
-{
- for (int i = 0; i < engines.count(); ++i) {
- if (CFEqual(engineAt(i)->ctfont, font))
- return i;
- }
-
- QCoreTextFontEngineMulti *that = const_cast<QCoreTextFontEngineMulti *>(this);
- QCoreTextFontEngine *fe = new QCoreTextFontEngine(font, fontDef);
- fe->ref.ref();
- that->engines.append(fe);
- return engines.count() - 1;
-}
-
-bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
- int *nglyphs, QTextEngine::ShaperFlags flags,
- unsigned short *logClusters, const HB_CharAttributes *,
- QScriptItem *si) const
-{
- QCFType<CFStringRef> cfstring = CFStringCreateWithCharactersNoCopy(0,
- reinterpret_cast<const UniChar *>(str),
- len, kCFAllocatorNull);
- QCFType<CFAttributedStringRef> attributedString = CFAttributedStringCreate(0, cfstring, attributeDict);
- QCFType<CTTypesetterRef> typeSetter;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
- if (flags & QTextEngine::RightToLeft) {
- const void *optionKeys[] = { kCTTypesetterOptionForcedEmbeddingLevel };
- const short rtlForcedEmbeddingLevelValue = 1;
- const void *rtlOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &rtlForcedEmbeddingLevelValue) };
- QCFType<CFDictionaryRef> options = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, rtlOptionValues, 1,
- &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
- typeSetter = CTTypesetterCreateWithAttributedStringAndOptions(attributedString, options);
- } else
-#else
- Q_UNUSED(flags);
-#endif
- typeSetter = CTTypesetterCreateWithAttributedString(attributedString);
-
- CFRange range = {0, 0};
- QCFType<CTLineRef> line = CTTypesetterCreateLine(typeSetter, range);
- CFArrayRef array = CTLineGetGlyphRuns(line);
- uint arraySize = CFArrayGetCount(array);
- glyph_t *outGlyphs = glyphs->glyphs;
- HB_GlyphAttributes *outAttributes = glyphs->attributes;
- QFixed *outAdvances_x = glyphs->advances_x;
- QFixed *outAdvances_y = glyphs->advances_y;
- glyph_t *initialGlyph = outGlyphs;
-
- if (arraySize == 0) {
- // CoreText failed to shape the text we gave it, so we assume one glyph
- // per character and build a list of invalid glyphs with zero advance
- *nglyphs = len;
- for (int i = 0; i < len; ++i) {
- outGlyphs[i] = 0;
- if (logClusters)
- logClusters[i] = i;
- outAdvances_x[i] = QFixed();
- outAdvances_y[i] = QFixed();
- outAttributes[i].clusterStart = true;
- }
- return true;
- }
-
- const bool rtl = (CTRunGetStatus(static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, 0))) & kCTRunStatusRightToLeft);
-
- bool outOBounds = false;
- for (uint i = 0; i < arraySize; ++i) {
- CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, rtl ? (arraySize - 1 - i) : i));
- CFIndex glyphCount = CTRunGetGlyphCount(run);
- if (glyphCount == 0)
- continue;
-
- Q_ASSERT((CTRunGetStatus(run) & kCTRunStatusRightToLeft) == rtl);
- CFRange stringRange = CTRunGetStringRange(run);
- int prepend = 0;
-#if MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5
- UniChar beginGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location);
- QChar dir = QChar::direction(beginGlyph);
- bool beginWithOverride = dir == QChar::DirLRO || dir == QChar::DirRLO || dir == QChar::DirLRE || dir == QChar::DirRLE;
- if (beginWithOverride) {
- logClusters[stringRange.location] = 0;
- outGlyphs[0] = 0xFFFF;
- outAdvances_x[0] = 0;
- outAdvances_y[0] = 0;
- outAttributes[0].clusterStart = true;
- outAttributes[0].dontPrint = true;
- outGlyphs++;
- outAdvances_x++;
- outAdvances_y++;
- outAttributes++;
- prepend = 1;
- }
-#endif
- UniChar endGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location + stringRange.length - 1);
- bool endWithPDF = QChar::direction(endGlyph) == QChar::DirPDF;
- if (endWithPDF)
- glyphCount++;
-
- if (!outOBounds && outGlyphs + glyphCount - initialGlyph > *nglyphs) {
- outOBounds = true;
- }
- if (!outOBounds) {
- CFDictionaryRef runAttribs = CTRunGetAttributes(run);
- //NSLog(@"Dictionary %@", runAttribs);
- if (!runAttribs)
- runAttribs = attributeDict;
- CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttribs, NSFontAttributeName));
- uint fontIndex = fontIndexForFont(runFont);
- const QFontEngine *engine = engineAt(fontIndex);
- fontIndex <<= 24;
- si->ascent = qMax(engine->ascent(), si->ascent);
- si->descent = qMax(engine->descent(), si->descent);
- si->leading = qMax(engine->leading(), si->leading);
- //NSLog(@"Run Font Name = %@", CTFontCopyFamilyName(runFont));
- if (endWithPDF)
- glyphCount--;
-
- QVarLengthArray<CGGlyph, 512> cgglyphs(0);
- const CGGlyph *tmpGlyphs = CTRunGetGlyphsPtr(run);
- if (!tmpGlyphs) {
- cgglyphs.resize(glyphCount);
- CTRunGetGlyphs(run, range, cgglyphs.data());
- tmpGlyphs = cgglyphs.constData();
- }
- QVarLengthArray<CGPoint, 512> cgpoints(0);
- const CGPoint *tmpPoints = CTRunGetPositionsPtr(run);
- if (!tmpPoints) {
- cgpoints.resize(glyphCount);
- CTRunGetPositions(run, range, cgpoints.data());
- tmpPoints = cgpoints.constData();
- }
-
- const int rtlOffset = rtl ? (glyphCount - 1) : 0;
- const int rtlSign = rtl ? -1 : 1;
-
- if (logClusters) {
- CFRange stringRange = CTRunGetStringRange(run);
- QVarLengthArray<CFIndex, 512> stringIndices(0);
- const CFIndex *tmpIndices = CTRunGetStringIndicesPtr(run);
- if (!tmpIndices) {
- stringIndices.resize(glyphCount);
- CTRunGetStringIndices(run, range, stringIndices.data());
- tmpIndices = stringIndices.constData();
- }
-
- const int firstGlyphIndex = outGlyphs - initialGlyph;
- outAttributes[0].clusterStart = true;
-
- CFIndex k = 0;
- CFIndex i = 0;
- for (i = stringRange.location + prepend;
- (i < stringRange.location + stringRange.length) && (k < glyphCount); ++i) {
- if (tmpIndices[k * rtlSign + rtlOffset] == i || i == stringRange.location + prepend) {
- logClusters[i] = k + firstGlyphIndex;
- outAttributes[k].clusterStart = true;
- ++k;
- } else {
- logClusters[i] = k + firstGlyphIndex - 1;
- }
- }
- // in case of a ligature at the end, fill the remaining logcluster entries
- for (;i < stringRange.location + stringRange.length; i++) {
- logClusters[i] = k + firstGlyphIndex - 1;
- }
- }
- for (CFIndex i = 0; i < glyphCount - 1; ++i) {
- int idx = rtlOffset + rtlSign * i;
- outGlyphs[idx] = tmpGlyphs[i] | fontIndex;
- outAdvances_x[idx] = QFixed::fromReal(tmpPoints[i + 1].x - tmpPoints[i].x);
- // Use negative y advance for flipped coordinate system
- outAdvances_y[idx] = QFixed::fromReal(tmpPoints[i].y - tmpPoints[i + 1].y);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- outAdvances_x[idx] = outAdvances_x[idx].round();
- outAdvances_y[idx] = outAdvances_y[idx].round();
- }
- }
- CGSize lastGlyphAdvance;
- CTFontGetAdvancesForGlyphs(runFont, kCTFontHorizontalOrientation, tmpGlyphs + glyphCount - 1, &lastGlyphAdvance, 1);
-
- outGlyphs[rtl ? 0 : (glyphCount - 1)] = tmpGlyphs[glyphCount - 1] | fontIndex;
- outAdvances_x[rtl ? 0 : (glyphCount - 1)] =
- (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(lastGlyphAdvance.width).round()
- : QFixed::fromReal(lastGlyphAdvance.width);
-
- if (endWithPDF) {
- logClusters[stringRange.location + stringRange.length - 1] = glyphCount + prepend;
- outGlyphs[glyphCount] = 0xFFFF;
- outAdvances_x[glyphCount] = 0;
- outAdvances_y[glyphCount] = 0;
- outAttributes[glyphCount].clusterStart = true;
- outAttributes[glyphCount].dontPrint = true;
- glyphCount++;
- }
- }
- outGlyphs += glyphCount;
- outAttributes += glyphCount;
- outAdvances_x += glyphCount;
- outAdvances_y += glyphCount;
- }
- *nglyphs = (outGlyphs - initialGlyph);
- return !outOBounds;
-}
-
-bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
- int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- *nglyphs = len;
- QCFType<CFStringRef> cfstring;
-
- QVarLengthArray<CGGlyph> cgGlyphs(len);
- CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len);
-
- for (int i = 0; i < len; ++i) {
- if (cgGlyphs[i]) {
- glyphs->glyphs[i] = cgGlyphs[i];
- } else {
- if (!cfstring)
- cfstring = CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar *>(str), len, kCFAllocatorNull);
- QCFType<CTFontRef> substituteFont = CTFontCreateForString(ctfont, cfstring, CFRangeMake(i, 1));
- CGGlyph substituteGlyph = 0;
- CTFontGetGlyphsForCharacters(substituteFont, (const UniChar*)str + i, &substituteGlyph, 1);
- if (substituteGlyph) {
- const uint fontIndex = (fontIndexForFont(substituteFont) << 24);
- glyphs->glyphs[i] = substituteGlyph | fontIndex;
- if (!(flags & QTextEngine::GlyphIndicesOnly)) {
- CGSize advance;
- CTFontGetAdvancesForGlyphs(substituteFont, kCTFontHorizontalOrientation, &substituteGlyph, &advance, 1);
- glyphs->advances_x[i] = QFixed::fromReal(advance.width);
- glyphs->advances_y[i] = QFixed::fromReal(advance.height);
- }
- }
- }
- }
-
- if (flags & QTextEngine::GlyphIndicesOnly)
- return true;
-
- loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, len, flags, fontDef);
- return true;
-}
-
-void QCoreTextFontEngineMulti::loadEngine(int)
-{
- // Do nothing
- Q_ASSERT(false);
-}
-
-extern int qt_antialiasing_threshold; // from qapplication.cpp
-
-static inline CGAffineTransform transformFromFontDef(const QFontDef &fontDef)
-{
- CGAffineTransform transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100)
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- return transform;
-}
-
-QCoreTextFontEngine::QCoreTextFontEngine(CTFontRef font, const QFontDef &def)
-{
- fontDef = def;
- transform = transformFromFontDef(fontDef);
- ctfont = font;
- CFRetain(ctfont);
- cgFont = CTFontCopyGraphicsFont(font, NULL);
- init();
-}
-
-QCoreTextFontEngine::QCoreTextFontEngine(CGFontRef font, const QFontDef &def)
-{
- fontDef = def;
- transform = transformFromFontDef(fontDef);
- cgFont = font;
- // Keep reference count balanced
- CFRetain(cgFont);
- ctfont = CTFontCreateWithGraphicsFont(font, fontDef.pixelSize, &transform, NULL);
- init();
-}
-
-QCoreTextFontEngine::~QCoreTextFontEngine()
-{
- CFRelease(cgFont);
- CFRelease(ctfont);
-}
-
-extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
-
-int getTraitValue(CFDictionaryRef allTraits, CFStringRef trait)
-{
- if (CFDictionaryContainsKey(allTraits, trait)) {
- CFNumberRef traitNum = (CFNumberRef) CFDictionaryGetValue(allTraits, trait);
- float v = 0;
- CFNumberGetValue(traitNum, kCFNumberFloatType, &v);
- // the value we get from CFNumberRef is from -1.0 to 1.0
- int value = v * 500 + 500;
- return value;
- }
-
- return 0;
-}
-
-void QCoreTextFontEngine::init()
-{
- Q_ASSERT(ctfont != NULL);
- Q_ASSERT(cgFont != NULL);
-
- QCFString family = CTFontCopyFamilyName(ctfont);
- fontDef.family = family;
-
- synthesisFlags = 0;
- CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctfont);
- if (traits & kCTFontItalicTrait)
- fontDef.style = QFont::StyleItalic;
-
- CFDictionaryRef allTraits = CTFontCopyTraits(ctfont);
- fontDef.weight = weightFromInteger(getTraitValue(allTraits, kCTFontWeightTrait));
- int slant = getTraitValue(allTraits, kCTFontSlantTrait);
- if (slant > 500 && !(traits & kCTFontItalicTrait))
- fontDef.style = QFont::StyleOblique;
- CFRelease(allTraits);
-
- if (fontDef.weight >= QFont::Bold && !(traits & kCTFontBoldTrait))
- synthesisFlags |= SynthesizedBold;
- // XXX: we probably don't need to synthesis italic for oblique font
- if (fontDef.style != QFont::StyleNormal && !(traits & kCTFontItalicTrait))
- synthesisFlags |= SynthesizedItalic;
-
- avgCharWidth = 0;
- QByteArray os2Table = getSfntTable(MAKE_TAG('O', 'S', '/', '2'));
- unsigned emSize = CTFontGetUnitsPerEm(ctfont);
- if (os2Table.size() >= 10) {
- fsType = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(os2Table.constData() + 8));
- // qAbs is a workaround for weird fonts like Lucida Grande
- qint16 width = qAbs(qFromBigEndian<qint16>(reinterpret_cast<const uchar *>(os2Table.constData() + 2)));
- avgCharWidth = QFixed::fromReal(width * fontDef.pixelSize / emSize);
- } else
- avgCharWidth = QFontEngine::averageCharWidth();
-
- ctMaxCharWidth = ctMinLeftBearing = ctMinRightBearing = 0;
- QByteArray hheaTable = getSfntTable(MAKE_TAG('h', 'h', 'e', 'a'));
- if (hheaTable.size() >= 16) {
- quint16 width = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(hheaTable.constData() + 10));
- ctMaxCharWidth = width * fontDef.pixelSize / emSize;
- qint16 bearing = qFromBigEndian<qint16>(reinterpret_cast<const uchar *>(hheaTable.constData() + 12));
- ctMinLeftBearing = bearing * fontDef.pixelSize / emSize;
- bearing = qFromBigEndian<qint16>(reinterpret_cast<const uchar *>(hheaTable.constData() + 14));
- ctMinRightBearing = bearing * fontDef.pixelSize / emSize;
- }
-}
-
-bool QCoreTextFontEngine::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
- int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- *nglyphs = len;
- QCFType<CFStringRef> cfstring;
-
- QVarLengthArray<CGGlyph> cgGlyphs(len);
- CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len);
-
- for (int i = 0; i < len; ++i)
- if (cgGlyphs[i])
- glyphs->glyphs[i] = cgGlyphs[i];
-
- if (flags & QTextEngine::GlyphIndicesOnly)
- return true;
-
- loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, len, flags, fontDef);
- return true;
-}
-
-glyph_metrics_t QCoreTextFontEngine::boundingBox(const QGlyphLayout &glyphs)
-{
- QFixed w;
- bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
-
- for (int i = 0; i < glyphs.numGlyphs; ++i) {
- w += round ? glyphs.effectiveAdvance(i).round()
- : glyphs.effectiveAdvance(i);
- }
- return glyph_metrics_t(0, -(ascent()), w - lastRightBearing(glyphs, round), ascent()+descent(), w, 0);
-}
-
-glyph_metrics_t QCoreTextFontEngine::boundingBox(glyph_t glyph)
-{
- glyph_metrics_t ret;
- CGGlyph g = glyph;
- CGRect rect = CTFontGetBoundingRectsForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, 0, 1);
- if (synthesisFlags & QFontEngine::SynthesizedItalic) {
- rect.size.width += rect.size.height * SYNTHETIC_ITALIC_SKEW;
- }
- ret.width = QFixed::fromReal(rect.size.width);
- ret.height = QFixed::fromReal(rect.size.height);
- ret.x = QFixed::fromReal(rect.origin.x);
- ret.y = -QFixed::fromReal(rect.origin.y) - ret.height;
- CGSize advances[1];
- CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, advances, 1);
- ret.xoff = QFixed::fromReal(advances[0].width);
- ret.yoff = QFixed::fromReal(advances[0].height);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- ret.xoff = ret.xoff.round();
- ret.yoff = ret.yoff.round();
- }
-
- return ret;
-}
-
-QFixed QCoreTextFontEngine::ascent() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(CTFontGetAscent(ctfont)).round()
- : QFixed::fromReal(CTFontGetAscent(ctfont));
-}
-QFixed QCoreTextFontEngine::descent() const
-{
- QFixed d = QFixed::fromReal(CTFontGetDescent(ctfont));
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- d = d.round();
-
- // subtract a pixel to even out the historical +1 in QFontMetrics::height().
- // Fix in Qt 5.
- return d - 1;
-}
-QFixed QCoreTextFontEngine::leading() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(CTFontGetLeading(ctfont)).round()
- : QFixed::fromReal(CTFontGetLeading(ctfont));
-}
-QFixed QCoreTextFontEngine::xHeight() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(CTFontGetXHeight(ctfont)).round()
- : QFixed::fromReal(CTFontGetXHeight(ctfont));
-}
-
-QFixed QCoreTextFontEngine::averageCharWidth() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? avgCharWidth.round() : avgCharWidth;
-}
-
-qreal QCoreTextFontEngine::maxCharWidth() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? qRound(ctMaxCharWidth) : ctMaxCharWidth;
-}
-
-qreal QCoreTextFontEngine::minLeftBearing() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? qRound(ctMinLeftBearing) : ctMinLeftBearing;
-}
-
-qreal QCoreTextFontEngine::minRightBearing() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? qRound(ctMinRightBearing) : ctMinLeftBearing;
-}
-
-void QCoreTextFontEngine::draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight)
-{
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> glyphs;
- QTransform matrix;
- matrix.translate(x, y);
- getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
- if (glyphs.size() == 0)
- return;
-
- CGContextSetFontSize(ctx, fontDef.pixelSize);
-
- CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
-
- CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, -1, 0, -paintDeviceHeight);
-
- CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
-
- cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
- CGContextSetTextMatrix(ctx, cgMatrix);
-
- CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
-
- QVarLengthArray<CGSize> advances(glyphs.size());
- QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size());
-
- for (int i = 0; i < glyphs.size() - 1; ++i) {
- advances[i].width = (positions[i + 1].x - positions[i].x).toReal();
- advances[i].height = (positions[i + 1].y - positions[i].y).toReal();
- cgGlyphs[i] = glyphs[i];
- }
- advances[glyphs.size() - 1].width = 0;
- advances[glyphs.size() - 1].height = 0;
- cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1];
-
- CGContextSetFont(ctx, cgFont);
- //NSLog(@"Font inDraw %@ ctfont %@", CGFontCopyFullName(cgFont), CTFontCopyFamilyName(ctfont));
-
- CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal());
-
- CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-
- if (synthesisFlags & QFontEngine::SynthesizedBold) {
- CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(),
- positions[0].y.toReal());
-
- CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
- }
-
- CGContextSetTextMatrix(ctx, oldTextMatrix);
-}
-
-struct ConvertPathInfo
-{
- ConvertPathInfo(QPainterPath *newPath, const QPointF &newPos) : path(newPath), pos(newPos) {}
- QPainterPath *path;
- QPointF pos;
-};
-
-static void convertCGPathToQPainterPath(void *info, const CGPathElement *element)
-{
- ConvertPathInfo *myInfo = static_cast<ConvertPathInfo *>(info);
- switch(element->type) {
- case kCGPathElementMoveToPoint:
- myInfo->path->moveTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y());
- break;
- case kCGPathElementAddLineToPoint:
- myInfo->path->lineTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y());
- break;
- case kCGPathElementAddQuadCurveToPoint:
- myInfo->path->quadTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y(),
- element->points[1].x + myInfo->pos.x(),
- element->points[1].y + myInfo->pos.y());
- break;
- case kCGPathElementAddCurveToPoint:
- myInfo->path->cubicTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y(),
- element->points[1].x + myInfo->pos.x(),
- element->points[1].y + myInfo->pos.y(),
- element->points[2].x + myInfo->pos.x(),
- element->points[2].y + myInfo->pos.y());
- break;
- case kCGPathElementCloseSubpath:
- myInfo->path->closeSubpath();
- break;
- default:
- qDebug() << "Unhandled path transform type: " << element->type;
- }
-
-}
-
-void QCoreTextFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs,
- QPainterPath *path, QTextItem::RenderFlags)
-{
- CGAffineTransform cgMatrix = CGAffineTransformIdentity;
- cgMatrix = CGAffineTransformScale(cgMatrix, 1, -1);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
-
- for (int i = 0; i < nGlyphs; ++i) {
- QCFType<CGPathRef> cgpath = CTFontCreatePathForGlyph(ctfont, glyphs[i], &cgMatrix);
- ConvertPathInfo info(path, positions[i].toPointF());
- CGPathApply(cgpath, &info, convertCGPathToQPainterPath);
- }
-}
-
-QImage QCoreTextFontEngine::imageForGlyph(glyph_t glyph, QFixed subPixelPosition, int /*margin*/, bool aa)
-{
- const glyph_metrics_t br = boundingBox(glyph);
- QImage im(qRound(br.width)+2, qRound(br.height)+2, QImage::Format_RGB32);
- im.fill(0);
-
- CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
- uint cgflags = kCGImageAlphaNoneSkipFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- cgflags |= kCGBitmapByteOrder32Host;
-#endif
- CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(),
- 8, im.bytesPerLine(), colorspace,
- cgflags);
- CGContextSetFontSize(ctx, fontDef.pixelSize);
- CGContextSetShouldAntialias(ctx, aa ||
- (fontDef.pointSize > qt_antialiasing_threshold
- && !(fontDef.styleStrategy & QFont::NoAntialias)));
- CGContextSetShouldSmoothFonts(ctx, aa);
- CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
- CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
-
- CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
-
- cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
- CGContextSetTextMatrix(ctx, cgMatrix);
- CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
- CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
- CGContextSetFont(ctx, cgFont);
-
- qreal pos_x = -br.x.toReal() + subPixelPosition.toReal();
- qreal pos_y = im.height() + br.y.toReal() - 1;
- CGContextSetTextPosition(ctx, pos_x, pos_y);
-
- CGSize advance;
- advance.width = 0;
- advance.height = 0;
- CGGlyph cgGlyph = glyph;
- CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-
- if (synthesisFlags & QFontEngine::SynthesizedBold) {
- CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y);
- CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
- }
-
- CGContextRelease(ctx);
-
- return im;
-}
-
-QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
-{
- QImage im = imageForGlyph(glyph, subPixelPosition, 0, false);
-
- QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
- QVector<QRgb> colors(256);
- for (int i=0; i<256; ++i)
- colors[i] = qRgba(0, 0, 0, i);
- indexed.setColorTable(colors);
-
- for (int y=0; y<im.height(); ++y) {
- uint *src = (uint*) im.scanLine(y);
- uchar *dst = indexed.scanLine(y);
- for (int x=0; x<im.width(); ++x) {
- *dst = qGray(*src);
- ++dst;
- ++src;
- }
- }
-
- return indexed;
-}
-
-QImage QCoreTextFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed subPixelPosition, int margin, const QTransform &x)
-{
- if (x.type() >= QTransform::TxScale)
- return QFontEngine::alphaRGBMapForGlyph(glyph, subPixelPosition, margin, x);
-
- QImage im = imageForGlyph(glyph, subPixelPosition, margin, true);
- qGamma_correct_back_to_linear_cs(&im);
- return im;
-}
-
-void QCoreTextFontEngine::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
- int i, numGlyphs = glyphs->numGlyphs;
- QVarLengthArray<CGGlyph> cgGlyphs(numGlyphs);
-
- for (i = 0; i < numGlyphs; ++i) {
- if (glyphs->glyphs[i] & 0xff000000)
- cgGlyphs[i] = 0;
- else
- cgGlyphs[i] = glyphs->glyphs[i];
- }
-
- loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, numGlyphs, flags, fontDef);
-}
-
-QFontEngine::FaceId QCoreTextFontEngine::faceId() const
-{
- return QFontEngine::FaceId();
-}
-
-bool QCoreTextFontEngine::canRender(const QChar *string, int len)
-{
- QVarLengthArray<CGGlyph> cgGlyphs(len);
- return CTFontGetGlyphsForCharacters(ctfont, (const UniChar *) string, cgGlyphs.data(), len);
-}
-
-bool QCoreTextFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
- QCFType<CFDataRef> table = CTFontCopyTable(ctfont, tag, 0);
- if (!table || !length)
- return false;
- CFIndex tableLength = CFDataGetLength(table);
- int availableLength = *length;
- *length = tableLength;
- if (buffer) {
- if (tableLength > availableLength)
- return false;
- CFDataGetBytes(table, CFRangeMake(0, tableLength), buffer);
- }
- return true;
-}
-
-void QCoreTextFontEngine::getUnscaledGlyph(glyph_t, QPainterPath *, glyph_metrics_t *)
-{
- // ###
-}
-
-QFixed QCoreTextFontEngine::emSquareSize() const
-{
- return QFixed::QFixed(int(CTFontGetUnitsPerEm(ctfont)));
-}
-
-QFontEngine *QCoreTextFontEngine::cloneWithSize(qreal pixelSize) const
-{
- QFontDef newFontDef = fontDef;
- newFontDef.pixelSize = pixelSize;
- newFontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi();
-
- return new QCoreTextFontEngine(cgFont, fontDef);
-}
-
-QT_END_NAMESPACE
-
-#endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-
diff --git a/src/gui/platforms/mac/qfontengine_coretext_p.h b/src/gui/platforms/mac/qfontengine_coretext_p.h
deleted file mode 100644
index bb80a9b2f3..0000000000
--- a/src/gui/platforms/mac/qfontengine_coretext_p.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTENGINE_CORETEXT_P_H
-#define QFONTENGINE_CORETEXT_P_H
-
-#include <private/qfontengine_p.h>
-
-#if !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-
-class QRawFontPrivate;
-class QCoreTextFontEngineMulti;
-class QCoreTextFontEngine : public QFontEngine
-{
-public:
- QCoreTextFontEngine(CTFontRef font, const QFontDef &def);
- QCoreTextFontEngine(CGFontRef font, const QFontDef &def);
- ~QCoreTextFontEngine();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
- virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- virtual glyph_metrics_t boundingBox(glyph_t glyph);
-
- virtual QFixed ascent() const;
- virtual QFixed descent() const;
- virtual QFixed leading() const;
- virtual QFixed xHeight() const;
- virtual qreal maxCharWidth() const;
- virtual QFixed averageCharWidth() const;
-
- virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
- QPainterPath *path, QTextItem::RenderFlags);
-
- virtual const char *name() const { return "QCoreTextFontEngine"; }
-
- virtual bool canRender(const QChar *string, int len);
-
- virtual int synthesized() const { return synthesisFlags; }
- virtual bool supportsSubPixelPositions() const { return true; }
-
- virtual Type type() const { return QFontEngine::Mac; }
-
- void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
-
- virtual FaceId faceId() const;
- virtual bool getSfntTableData(uint /*tag*/, uchar * /*buffer*/, uint * /*length*/) const;
- virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
- virtual QImage alphaMapForGlyph(glyph_t, QFixed subPixelPosition);
- virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
- virtual qreal minRightBearing() const;
- virtual qreal minLeftBearing() const;
- virtual QFixed emSquareSize() const;
-
- virtual QFontEngine *cloneWithSize(qreal pixelSize) const;
-
-private:
- friend class QRawFontPrivate;
-
- void init();
- QImage imageForGlyph(glyph_t glyph, QFixed subPixelPosition, int margin, bool colorful);
- CTFontRef ctfont;
- CGFontRef cgFont;
- int synthesisFlags;
- CGAffineTransform transform;
- QFixed avgCharWidth;
- qreal ctMaxCharWidth;
- qreal ctMinLeftBearing;
- qreal ctMinRightBearing;
- friend class QCoreTextFontEngineMulti;
-};
-
-class QCoreTextFontEngineMulti : public QFontEngineMulti
-{
-public:
- QCoreTextFontEngineMulti(const QCFString &name, const QFontDef &fontDef, bool kerning);
- QCoreTextFontEngineMulti(CGFontRef cgFontRef, const QFontDef &fontDef, bool kerning);
- ~QCoreTextFontEngineMulti();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
- QTextEngine::ShaperFlags flags) const;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
- QTextEngine::ShaperFlags flags,
- unsigned short *logClusters, const HB_CharAttributes *charAttributes,
- QScriptItem *si) const;
-
- virtual const char *name() const { return "CoreText"; }
-protected:
- virtual void loadEngine(int at);
-
-private:
- void init(bool kerning);
- inline const QCoreTextFontEngine *engineAt(int i) const
- { return static_cast<const QCoreTextFontEngine *>(engines.at(i)); }
-
- uint fontIndexForFont(CTFontRef font) const;
- CTFontRef ctfont;
- mutable QCFType<CFMutableDictionaryRef> attributeDict;
- CGAffineTransform transform;
- friend class QFontDialogPrivate;
-};
-
-#endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-
-#endif // QFONTENGINE_CORETEXT_P_H
diff --git a/src/gui/platforms/mac/qfontengine_mac.mm b/src/gui/platforms/mac/qfontengine_mac.mm
deleted file mode 100644
index 9f094ad7d1..0000000000
--- a/src/gui/platforms/mac/qfontengine_mac.mm
+++ /dev/null
@@ -1,1236 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfontengine_mac_p.h"
-
-#include <private/qapplication_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qpainter_p.h>
-#include <private/qtextengine_p.h>
-#include <qbitmap.h>
-#include <private/qpaintengine_mac_p.h>
-#include <private/qprintengine_mac_p.h>
-#include <qglobal.h>
-#include <qpixmap.h>
-#include <qpixmapcache.h>
-#include <qvarlengtharray.h>
-#include <qdebug.h>
-#include <qendian.h>
-#include <qmath.h>
-#include <private/qimage_p.h>
-
-#include <ApplicationServices/ApplicationServices.h>
-#include <AppKit/AppKit.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- QFontEngine debug facilities
- *****************************************************************************/
-//#define DEBUG_ADVANCES
-
-extern int qt_antialiasing_threshold; // QApplication.cpp
-
-#ifndef FixedToQFixed
-#define FixedToQFixed(a) QFixed::fromFixed((a) >> 10)
-#define QFixedToFixed(x) ((x).value() << 10)
-#endif
-
-class QMacFontPath
-{
- float x, y;
- QPainterPath *path;
-public:
- inline QMacFontPath(float _x, float _y, QPainterPath *_path) : x(_x), y(_y), path(_path) { }
- inline void setPosition(float _x, float _y) { x = _x; y = _y; }
- inline void advance(float _x) { x += _x; }
- static OSStatus lineTo(const Float32Point *, void *);
- static OSStatus cubicTo(const Float32Point *, const Float32Point *,
- const Float32Point *, void *);
- static OSStatus moveTo(const Float32Point *, void *);
- static OSStatus closePath(void *);
-};
-
-OSStatus QMacFontPath::lineTo(const Float32Point *pt, void *data)
-
-{
- QMacFontPath *p = static_cast<QMacFontPath*>(data);
- p->path->lineTo(p->x + pt->x, p->y + pt->y);
- return noErr;
-}
-
-OSStatus QMacFontPath::cubicTo(const Float32Point *cp1, const Float32Point *cp2,
- const Float32Point *ep, void *data)
-
-{
- QMacFontPath *p = static_cast<QMacFontPath*>(data);
- p->path->cubicTo(p->x + cp1->x, p->y + cp1->y,
- p->x + cp2->x, p->y + cp2->y,
- p->x + ep->x, p->y + ep->y);
- return noErr;
-}
-
-OSStatus QMacFontPath::moveTo(const Float32Point *pt, void *data)
-{
- QMacFontPath *p = static_cast<QMacFontPath*>(data);
- p->path->moveTo(p->x + pt->x, p->y + pt->y);
- return noErr;
-}
-
-OSStatus QMacFontPath::closePath(void *data)
-{
- static_cast<QMacFontPath*>(data)->path->closeSubpath();
- return noErr;
-}
-
-
-#ifndef QT_MAC_USE_COCOA
-QFontEngineMacMulti::QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning)
- : QFontEngineMulti(0)
-{
- this->fontDef = fontDef;
- this->kerning = kerning;
-
- // hopefully (CTFontCreateWithName or CTFontCreateWithFontDescriptor) + CTFontCreateCopyWithSymbolicTraits
- // (or CTFontCreateWithQuickdrawInstance)
- FMFontFamily fmFamily;
- FMFontStyle fntStyle = 0;
- fmFamily = FMGetFontFamilyFromATSFontFamilyRef(atsFamily);
- if (fmFamily == kInvalidFontFamily) {
- // Use the ATSFont then...
- fontID = FMGetFontFromATSFontRef(atsFontRef);
- } else {
- if (fontDef.weight >= QFont::Bold)
- fntStyle |= ::bold;
- if (fontDef.style != QFont::StyleNormal)
- fntStyle |= ::italic;
-
- FMFontStyle intrinsicStyle;
- FMFont fnt = 0;
- if (FMGetFontFromFontFamilyInstance(fmFamily, fntStyle, &fnt, &intrinsicStyle) == noErr)
- fontID = FMGetATSFontRefFromFont(fnt);
- }
-
- // CFDictionaryRef, <CTStringAttributes.h>
- OSStatus status;
-
- status = ATSUCreateTextLayout(&textLayout);
- Q_ASSERT(status == noErr);
-
- const int maxAttributeCount = 5;
- ATSUAttributeTag tags[maxAttributeCount + 1];
- ByteCount sizes[maxAttributeCount + 1];
- ATSUAttributeValuePtr values[maxAttributeCount + 1];
- int attributeCount = 0;
-
- Fixed size = FixRatio(fontDef.pixelSize, 1);
- tags[attributeCount] = kATSUSizeTag;
- sizes[attributeCount] = sizeof(size);
- values[attributeCount] = &size;
- ++attributeCount;
-
- tags[attributeCount] = kATSUFontTag;
- sizes[attributeCount] = sizeof(fontID);
- values[attributeCount] = &this->fontID;
- ++attributeCount;
-
- transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100) {
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- tags[attributeCount] = kATSUFontMatrixTag;
- sizes[attributeCount] = sizeof(transform);
- values[attributeCount] = &transform;
- ++attributeCount;
- }
-
- status = ATSUCreateStyle(&style);
- Q_ASSERT(status == noErr);
-
- Q_ASSERT(attributeCount < maxAttributeCount + 1);
- status = ATSUSetAttributes(style, attributeCount, tags, sizes, values);
- Q_ASSERT(status == noErr);
-
- QFontEngineMac *fe = new QFontEngineMac(style, fontID, fontDef, this);
- fe->ref.ref();
- engines.append(fe);
-}
-
-QFontEngineMacMulti::~QFontEngineMacMulti()
-{
- ATSUDisposeTextLayout(textLayout);
- ATSUDisposeStyle(style);
-
- for (int i = 0; i < engines.count(); ++i) {
- QFontEngineMac *fe = const_cast<QFontEngineMac *>(static_cast<const QFontEngineMac *>(engines.at(i)));
- fe->multiEngine = 0;
- if (!fe->ref.deref())
- delete fe;
- }
- engines.clear();
-}
-
-struct QGlyphLayoutInfo
-{
- QGlyphLayout *glyphs;
- int *numGlyphs;
- bool callbackCalled;
- int *mappedFonts;
- QTextEngine::ShaperFlags flags;
- QFontEngineMacMulti::ShaperItem *shaperItem;
- unsigned int styleStrategy;
-};
-
-static OSStatus atsuPostLayoutCallback(ATSULayoutOperationSelector selector, ATSULineRef lineRef, URefCon refCon,
- void *operationExtraParameter, ATSULayoutOperationCallbackStatus *callbackStatus)
-{
- Q_UNUSED(selector);
- Q_UNUSED(operationExtraParameter);
-
- QGlyphLayoutInfo *nfo = reinterpret_cast<QGlyphLayoutInfo *>(refCon);
- nfo->callbackCalled = true;
-
- ATSLayoutRecord *layoutData = 0;
- ItemCount itemCount = 0;
-
- OSStatus e = noErr;
- e = ATSUDirectGetLayoutDataArrayPtrFromLineRef(lineRef, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
- /*iCreate =*/ false,
- (void **) &layoutData,
- &itemCount);
- if (e != noErr)
- return e;
-
- *nfo->numGlyphs = itemCount - 1;
-
- Fixed *baselineDeltas = 0;
-
- e = ATSUDirectGetLayoutDataArrayPtrFromLineRef(lineRef, kATSUDirectDataBaselineDeltaFixedArray,
- /*iCreate =*/ true,
- (void **) &baselineDeltas,
- &itemCount);
- if (e != noErr)
- return e;
-
- int nextCharStop = -1;
- int currentClusterGlyph = -1; // first glyph in log cluster
- QFontEngineMacMulti::ShaperItem *item = nfo->shaperItem;
- if (item->charAttributes) {
- item = nfo->shaperItem;
-#if !defined(QT_NO_DEBUG)
- int surrogates = 0;
- const QChar *str = item->string;
- for (int i = item->from; i < item->from + item->length - 1; ++i) {
- surrogates += (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00
- && str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
- }
-#endif
- for (nextCharStop = item->from; nextCharStop < item->from + item->length; ++nextCharStop)
- if (item->charAttributes[nextCharStop].charStop)
- break;
- nextCharStop -= item->from;
- }
-
- nfo->glyphs->attributes[0].clusterStart = true;
- int glyphIdx = 0;
- int glyphIncrement = 1;
- if (nfo->flags & QTextEngine::RightToLeft) {
- glyphIdx = itemCount - 2;
- glyphIncrement = -1;
- }
- for (int i = 0; i < *nfo->numGlyphs; ++i, glyphIdx += glyphIncrement) {
-
- int charOffset = layoutData[glyphIdx].originalOffset / sizeof(UniChar);
- const int fontIdx = nfo->mappedFonts[charOffset];
-
- ATSGlyphRef glyphId = layoutData[glyphIdx].glyphID;
-
- QFixed yAdvance = FixedToQFixed(baselineDeltas[glyphIdx]);
- QFixed xAdvance = FixedToQFixed(layoutData[glyphIdx + 1].realPos - layoutData[glyphIdx].realPos);
-
- if (nfo->styleStrategy & QFont::ForceIntegerMetrics) {
- yAdvance = yAdvance.round();
- xAdvance = xAdvance.round();
- }
-
- if (glyphId != 0xffff || i == 0) {
- if (i < nfo->glyphs->numGlyphs)
- {
- nfo->glyphs->glyphs[i] = (glyphId & 0x00ffffff) | (fontIdx << 24);
-
- nfo->glyphs->advances_y[i] = yAdvance;
- nfo->glyphs->advances_x[i] = xAdvance;
- }
- } else {
- // ATSUI gives us 0xffff as glyph id at the index in the glyph array for
- // a character position that maps to a ligtature. Such a glyph id does not
- // result in any visual glyph, but it may have an advance, which is why we
- // sum up the glyph advances.
- --i;
- nfo->glyphs->advances_y[i] += yAdvance;
- nfo->glyphs->advances_x[i] += xAdvance;
- *nfo->numGlyphs -= 1;
- }
-
- if (item->log_clusters) {
- if (charOffset >= nextCharStop) {
- nfo->glyphs->attributes[i].clusterStart = true;
- currentClusterGlyph = i;
-
- ++nextCharStop;
- for (; nextCharStop < item->length; ++nextCharStop)
- if (item->charAttributes[item->from + nextCharStop].charStop)
- break;
- } else {
- if (currentClusterGlyph == -1)
- currentClusterGlyph = i;
- }
- item->log_clusters[charOffset] = currentClusterGlyph;
-
- // surrogate handling
- if (charOffset < item->length - 1) {
- QChar current = item->string[item->from + charOffset];
- QChar next = item->string[item->from + charOffset + 1];
- if (current.unicode() >= 0xd800 && current.unicode() < 0xdc00
- && next.unicode() >= 0xdc00 && next.unicode() < 0xe000) {
- item->log_clusters[charOffset + 1] = currentClusterGlyph;
- }
- }
- }
- }
-
- /*
- if (item) {
- qDebug() << "resulting logclusters:";
- for (int i = 0; i < item->length; ++i)
- qDebug() << "logClusters[" << i << "] =" << item->log_clusters[i];
- qDebug() << "clusterstarts:";
- for (int i = 0; i < *nfo->numGlyphs; ++i)
- qDebug() << "clusterStart[" << i << "] =" << nfo->glyphs[i].attributes.clusterStart;
- }
- */
-
- ATSUDirectReleaseLayoutDataArrayPtr(lineRef, kATSUDirectDataBaselineDeltaFixedArray,
- (void **) &baselineDeltas);
-
- ATSUDirectReleaseLayoutDataArrayPtr(lineRef, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
- (void **) &layoutData);
-
- *callbackStatus = kATSULayoutOperationCallbackStatusHandled;
- return noErr;
-}
-
-int QFontEngineMacMulti::fontIndexForFontID(ATSUFontID id) const
-{
- for (int i = 0; i < engines.count(); ++i) {
- if (engineAt(i)->fontID == id)
- return i;
- }
-
- QFontEngineMacMulti *that = const_cast<QFontEngineMacMulti *>(this);
- QFontEngineMac *fe = new QFontEngineMac(style, id, fontDef, that);
- fe->ref.ref();
- that->engines.append(fe);
- return engines.count() - 1;
-}
-
-bool QFontEngineMacMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- return stringToCMap(str, len, glyphs, nglyphs, flags, /*logClusters=*/0, /*charAttributes=*/0);
-}
-
-bool QFontEngineMacMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,
- unsigned short *logClusters, const HB_CharAttributes *charAttributes, QScriptItem *) const
-{
- if (*nglyphs < len) {
- *nglyphs = len;
- return false;
- }
-
- ShaperItem shaperItem;
- shaperItem.string = str;
- shaperItem.from = 0;
- shaperItem.length = len;
- shaperItem.glyphs = *glyphs;
- shaperItem.glyphs.numGlyphs = *nglyphs;
- shaperItem.flags = flags;
- shaperItem.log_clusters = logClusters;
- shaperItem.charAttributes = charAttributes;
-
- const int maxChars = qMax(1,
- int(SHRT_MAX / maxCharWidth())
- - 10 // subtract a few to be on the safe side
- );
- if (len < maxChars || !charAttributes)
- return stringToCMapInternal(str, len, glyphs, nglyphs, flags, &shaperItem);
-
- int charIdx = 0;
- int glyphIdx = 0;
- ShaperItem tmpItem = shaperItem;
-
- do {
- tmpItem.from = shaperItem.from + charIdx;
-
- int charCount = qMin(maxChars, len - charIdx);
-
- int lastWhitespace = tmpItem.from + charCount - 1;
- int lastSoftBreak = lastWhitespace;
- int lastCharStop = lastSoftBreak;
- for (int i = lastCharStop; i >= tmpItem.from; --i) {
- if (tmpItem.charAttributes[i].whiteSpace) {
- lastWhitespace = i;
- break;
- } if (tmpItem.charAttributes[i].lineBreakType != HB_NoBreak) {
- lastSoftBreak = i;
- } if (tmpItem.charAttributes[i].charStop) {
- lastCharStop = i;
- }
- }
- charCount = qMin(lastWhitespace, qMin(lastSoftBreak, lastCharStop)) - tmpItem.from + 1;
-
- int glyphCount = shaperItem.glyphs.numGlyphs - glyphIdx;
- if (glyphCount <= 0)
- return false;
- tmpItem.length = charCount;
- tmpItem.glyphs = shaperItem.glyphs.mid(glyphIdx, glyphCount);
- tmpItem.log_clusters = shaperItem.log_clusters + charIdx;
- if (!stringToCMapInternal(tmpItem.string + tmpItem.from, tmpItem.length,
- &tmpItem.glyphs, &glyphCount, flags,
- &tmpItem)) {
- *nglyphs = glyphIdx + glyphCount;
- return false;
- }
- for (int i = 0; i < charCount; ++i)
- tmpItem.log_clusters[i] += glyphIdx;
- glyphIdx += glyphCount;
- charIdx += charCount;
- } while (charIdx < len);
- *nglyphs = glyphIdx;
- glyphs->numGlyphs = glyphIdx;
-
- return true;
-}
-
-bool QFontEngineMacMulti::stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,ShaperItem *shaperItem) const
-{
- //qDebug() << "stringToCMap" << QString(str, len);
-
- OSStatus e = noErr;
-
- e = ATSUSetTextPointerLocation(textLayout, (UniChar *)(str), 0, len, len);
- if (e != noErr) {
- qWarning("Qt: internal: %ld: Error ATSUSetTextPointerLocation %s: %d", long(e), __FILE__, __LINE__);
- return false;
- }
-
- QGlyphLayoutInfo nfo;
- nfo.glyphs = glyphs;
- nfo.numGlyphs = nglyphs;
- nfo.callbackCalled = false;
- nfo.flags = flags;
- nfo.shaperItem = shaperItem;
- nfo.styleStrategy = fontDef.styleStrategy;
-
- int prevNumGlyphs = *nglyphs;
-
- QVarLengthArray<int> mappedFonts(len);
- for (int i = 0; i < len; ++i)
- mappedFonts[i] = 0;
- nfo.mappedFonts = mappedFonts.data();
-
- Q_ASSERT(sizeof(void *) <= sizeof(URefCon));
- e = ATSUSetTextLayoutRefCon(textLayout, (URefCon)&nfo);
- if (e != noErr) {
- qWarning("Qt: internal: %ld: Error ATSUSetTextLayoutRefCon %s: %d", long(e), __FILE__, __LINE__);
- return false;
- }
-
- {
- const int maxAttributeCount = 3;
- ATSUAttributeTag tags[maxAttributeCount + 1];
- ByteCount sizes[maxAttributeCount + 1];
- ATSUAttributeValuePtr values[maxAttributeCount + 1];
- int attributeCount = 0;
-
- tags[attributeCount] = kATSULineLayoutOptionsTag;
- ATSLineLayoutOptions layopts = kATSLineHasNoOpticalAlignment
- | kATSLineIgnoreFontLeading
- | kATSLineNoSpecialJustification // we do kashidas ourselves
- | kATSLineDisableAllJustification
- ;
-
- if (fontDef.styleStrategy & QFont::NoAntialias)
- layopts |= kATSLineNoAntiAliasing;
-
- if (!kerning)
- layopts |= kATSLineDisableAllKerningAdjustments;
-
- values[attributeCount] = &layopts;
- sizes[attributeCount] = sizeof(layopts);
- ++attributeCount;
-
- tags[attributeCount] = kATSULayoutOperationOverrideTag;
- ATSULayoutOperationOverrideSpecifier spec;
- spec.operationSelector = kATSULayoutOperationPostLayoutAdjustment;
- spec.overrideUPP = atsuPostLayoutCallback;
- values[attributeCount] = &spec;
- sizes[attributeCount] = sizeof(spec);
- ++attributeCount;
-
- // CTWritingDirection
- Boolean direction;
- if (flags & QTextEngine::RightToLeft)
- direction = kATSURightToLeftBaseDirection;
- else
- direction = kATSULeftToRightBaseDirection;
- tags[attributeCount] = kATSULineDirectionTag;
- values[attributeCount] = &direction;
- sizes[attributeCount] = sizeof(direction);
- ++attributeCount;
-
- Q_ASSERT(attributeCount < maxAttributeCount + 1);
- e = ATSUSetLayoutControls(textLayout, attributeCount, tags, sizes, values);
- if (e != noErr) {
- qWarning("Qt: internal: %ld: Error ATSUSetLayoutControls %s: %d", long(e), __FILE__, __LINE__);
- return false;
- }
-
- }
-
- e = ATSUSetRunStyle(textLayout, style, 0, len);
- if (e != noErr) {
- qWarning("Qt: internal: %ld: Error ATSUSetRunStyle %s: %d", long(e), __FILE__, __LINE__);
- return false;
- }
-
- if (!(fontDef.styleStrategy & QFont::NoFontMerging)) {
- int pos = 0;
- do {
- ATSUFontID substFont = 0;
- UniCharArrayOffset changedOffset = 0;
- UniCharCount changeCount = 0;
-
- e = ATSUMatchFontsToText(textLayout, pos, len - pos,
- &substFont, &changedOffset,
- &changeCount);
- if (e == kATSUFontsMatched) {
- int fontIdx = fontIndexForFontID(substFont);
- for (uint i = 0; i < changeCount; ++i)
- mappedFonts[changedOffset + i] = fontIdx;
- pos = changedOffset + changeCount;
- ATSUSetRunStyle(textLayout, engineAt(fontIdx)->style, changedOffset, changeCount);
- } else if (e == kATSUFontsNotMatched) {
- pos = changedOffset + changeCount;
- }
- } while (pos < len && e != noErr);
- }
- { // trigger the a layout
- // CFAttributedStringCreate, CTFramesetterCreateWithAttributedString (or perhaps Typesetter)
- Rect rect;
- e = ATSUMeasureTextImage(textLayout, kATSUFromTextBeginning, kATSUToTextEnd,
- /*iLocationX =*/ 0, /*iLocationY =*/ 0,
- &rect);
- if (e != noErr) {
- qWarning("Qt: internal: %ld: Error ATSUMeasureTextImage %s: %d", long(e), __FILE__, __LINE__);
- return false;
- }
- }
-
- if (!nfo.callbackCalled) {
- qWarning("Qt: internal: %ld: Error ATSUMeasureTextImage did not trigger callback %s: %d", long(e), __FILE__, __LINE__);
- return false;
- }
-
- ATSUClearLayoutCache(textLayout, kATSUFromTextBeginning);
- if (prevNumGlyphs < *nfo.numGlyphs)
- return false;
- return true;
-}
-
-void QFontEngineMacMulti::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
- Q_ASSERT(false);
- Q_UNUSED(glyphs);
- Q_UNUSED(flags);
-}
-
-void QFontEngineMacMulti::doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const
-{
- //Q_ASSERT(false);
-}
-
-void QFontEngineMacMulti::loadEngine(int /*at*/)
-{
- // should never be called!
- Q_ASSERT(false);
-}
-
-bool QFontEngineMacMulti::canRender(const QChar *string, int len)
-{
- ATSUSetTextPointerLocation(textLayout, reinterpret_cast<const UniChar *>(string), 0, len, len);
- ATSUSetRunStyle(textLayout, style, 0, len);
-
- OSStatus e = noErr;
- int pos = 0;
- do {
- FMFont substFont = 0;
- UniCharArrayOffset changedOffset = 0;
- UniCharCount changeCount = 0;
-
- // CTFontCreateForString
- e = ATSUMatchFontsToText(textLayout, pos, len - pos,
- &substFont, &changedOffset,
- &changeCount);
- if (e == kATSUFontsMatched) {
- pos = changedOffset + changeCount;
- } else if (e == kATSUFontsNotMatched) {
- break;
- }
- } while (pos < len && e != noErr);
-
- return e == noErr || e == kATSUFontsMatched;
-}
-
-QFontEngineMac::QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine)
- : fontID(fontID), multiEngine(multiEngine), cmap(0), symbolCMap(false)
-{
- fontDef = def;
- ATSUCreateAndCopyStyle(baseStyle, &style);
- ATSFontRef atsFont = FMGetATSFontRefFromFont(fontID);
- cgFont = CGFontCreateWithPlatformFont(&atsFont);
-
- const int maxAttributeCount = 4;
- ATSUAttributeTag tags[maxAttributeCount + 1];
- ByteCount sizes[maxAttributeCount + 1];
- ATSUAttributeValuePtr values[maxAttributeCount + 1];
- int attributeCount = 0;
-
- synthesisFlags = 0;
-
- // synthesizing using CG is not recommended
- quint16 macStyle = 0;
- {
- uchar data[4];
- ByteCount len = 4;
- if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 44, 4, &data, &len) == noErr)
- macStyle = qFromBigEndian<quint16>(data);
- }
-
- Boolean atsuBold = false;
- Boolean atsuItalic = false;
- if (fontDef.weight >= QFont::Bold) {
- if (!(macStyle & 1)) {
- synthesisFlags |= SynthesizedBold;
- atsuBold = true;
- tags[attributeCount] = kATSUQDBoldfaceTag;
- sizes[attributeCount] = sizeof(atsuBold);
- values[attributeCount] = &atsuBold;
- ++attributeCount;
- }
- }
- if (fontDef.style != QFont::StyleNormal) {
- if (!(macStyle & 2)) {
- synthesisFlags |= SynthesizedItalic;
- atsuItalic = true;
- tags[attributeCount] = kATSUQDItalicTag;
- sizes[attributeCount] = sizeof(atsuItalic);
- values[attributeCount] = &atsuItalic;
- ++attributeCount;
- }
- }
-
- tags[attributeCount] = kATSUFontTag;
- values[attributeCount] = &fontID;
- sizes[attributeCount] = sizeof(fontID);
- ++attributeCount;
-
- Q_ASSERT(attributeCount < maxAttributeCount + 1);
- OSStatus err = ATSUSetAttributes(style, attributeCount, tags, sizes, values);
- Q_ASSERT(err == noErr);
- Q_UNUSED(err);
-
- // CTFontCopyTable
- quint16 tmpFsType;
- if (ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 8, 2, &tmpFsType, 0) == noErr)
- fsType = qFromBigEndian<quint16>(tmpFsType);
- else
- fsType = 0;
-
- if (multiEngine)
- transform = multiEngine->transform;
- else
- transform = CGAffineTransformIdentity;
-
- ATSUTextMeasurement metric;
-
- ATSUGetAttribute(style, kATSUAscentTag, sizeof(metric), &metric, 0);
- m_ascent = FixRound(metric);
-
- ATSUGetAttribute(style, kATSUDescentTag, sizeof(metric), &metric, 0);
- m_descent = FixRound(metric);
-
- ATSUGetAttribute(style, kATSULeadingTag, sizeof(metric), &metric, 0);
- m_leading = FixRound(metric);
-
- ATSFontMetrics metrics;
-
- ATSFontGetHorizontalMetrics(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &metrics);
- m_maxCharWidth = metrics.maxAdvanceWidth * fontDef.pointSize;
-
- ATSFontGetHorizontalMetrics(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &metrics);
- m_xHeight = QFixed::fromReal(metrics.xHeight * fontDef.pointSize);
-
- ATSFontGetHorizontalMetrics(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &metrics);
- m_averageCharWidth = QFixed::fromReal(metrics.avgAdvanceWidth * fontDef.pointSize);
-
- // Use width of 'X' if ATSFontGetHorizontalMetrics returns 0 for avgAdvanceWidth.
- if (m_averageCharWidth == QFixed(0)) {
- QChar c('X');
- QGlyphLayoutArray<1> glyphs;
- int nglyphs = 1;
- stringToCMap(&c, 1, &glyphs, &nglyphs, 0);
- glyph_metrics_t metrics = boundingBox(glyphs);
- m_averageCharWidth = metrics.width;
- }
-}
-
-QFontEngineMac::~QFontEngineMac()
-{
- ATSUDisposeStyle(style);
-}
-
-static inline unsigned int getChar(const QChar *str, int &i, const int len)
-{
- unsigned int uc = str[i].unicode();
- if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
- uint low = str[i+1].unicode();
- if (low >= 0xdc00 && low < 0xe000) {
- uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
- ++i;
- }
- }
- return uc;
-}
-
-// Not used directly for shaping, only used to calculate m_averageCharWidth
-bool QFontEngineMac::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- if (!cmap) {
- cmapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p'));
- int size = 0;
- cmap = getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()), cmapTable.size(), &symbolCMap, &size);
- if (!cmap)
- return false;
- }
- if (symbolCMap) {
- for (int i = 0; i < len; ++i) {
- unsigned int uc = getChar(str, i, len);
- glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc);
- if(!glyphs->glyphs[i] && uc < 0x100)
- glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
- }
- } else {
- for (int i = 0; i < len; ++i) {
- unsigned int uc = getChar(str, i, len);
- glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc);
- }
- }
-
- *nglyphs = len;
- glyphs->numGlyphs = *nglyphs;
-
- if (!(flags & QTextEngine::GlyphIndicesOnly))
- recalcAdvances(glyphs, flags);
-
- return true;
-}
-
-void QFontEngineMac::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
- Q_UNUSED(flags)
-
- QVarLengthArray<GlyphID> atsuGlyphs(glyphs->numGlyphs);
- for (int i = 0; i < glyphs->numGlyphs; ++i)
- atsuGlyphs[i] = glyphs->glyphs[i];
-
- QVarLengthArray<ATSGlyphScreenMetrics> metrics(glyphs->numGlyphs);
-
- ATSUGlyphGetScreenMetrics(style, glyphs->numGlyphs, atsuGlyphs.data(), sizeof(GlyphID),
- /* iForcingAntiAlias =*/ false,
- /* iAntiAliasSwitch =*/true,
- metrics.data());
-
- for (int i = 0; i < glyphs->numGlyphs; ++i) {
- glyphs->advances_x[i] = QFixed::fromReal(metrics[i].deviceAdvance.x);
- glyphs->advances_y[i] = QFixed::fromReal(metrics[i].deviceAdvance.y);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- glyphs->advances_x[i] = glyphs->advances_x[i].round();
- glyphs->advances_y[i] = glyphs->advances_y[i].round();
- }
- }
-}
-
-glyph_metrics_t QFontEngineMac::boundingBox(const QGlyphLayout &glyphs)
-{
- QFixed w;
- bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
- for (int i = 0; i < glyphs.numGlyphs; ++i) {
- w += round ? glyphs.effectiveAdvance(i).round()
- : glyphs.effectiveAdvance(i);
- }
- return glyph_metrics_t(0, -(ascent()), w - lastRightBearing(glyphs, round), ascent()+descent(), w, 0);
-}
-
-glyph_metrics_t QFontEngineMac::boundingBox(glyph_t glyph)
-{
- GlyphID atsuGlyph = glyph;
-
- ATSGlyphScreenMetrics metrics;
-
- ATSUGlyphGetScreenMetrics(style, 1, &atsuGlyph, 0,
- /* iForcingAntiAlias =*/ false,
- /* iAntiAliasSwitch =*/true,
- &metrics);
-
- // ### check again
-
- glyph_metrics_t gm;
- gm.width = int(metrics.width);
- gm.height = int(metrics.height);
- gm.x = QFixed::fromReal(metrics.topLeft.x);
- gm.y = -QFixed::fromReal(metrics.topLeft.y);
- gm.xoff = QFixed::fromReal(metrics.deviceAdvance.x);
- gm.yoff = QFixed::fromReal(metrics.deviceAdvance.y);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- gm.x = gm.x.floor();
- gm.y = gm.y.floor();
- gm.xoff = gm.xoff.round();
- gm.yoff = gm.yoff.round();
- }
-
- return gm;
-}
-
-QFixed QFontEngineMac::ascent() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? m_ascent.round()
- : m_ascent;
-}
-
-QFixed QFontEngineMac::descent() const
-{
- // subtract a pixel to even out the historical +1 in QFontMetrics::height().
- // Fix in Qt 5.
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? m_descent.round() - 1
- : m_descent;
-}
-
-QFixed QFontEngineMac::leading() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? m_leading.round()
- : m_leading;
-}
-
-qreal QFontEngineMac::maxCharWidth() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? qRound(m_maxCharWidth)
- : m_maxCharWidth;
-}
-
-QFixed QFontEngineMac::xHeight() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? m_xHeight.round()
- : m_xHeight;
-}
-
-QFixed QFontEngineMac::averageCharWidth() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? m_averageCharWidth.round()
- : m_averageCharWidth;
-}
-
-static void addGlyphsToPathHelper(ATSUStyle style, glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path)
-{
- if (!numGlyphs)
- return;
-
- OSStatus e;
-
- QMacFontPath fontpath(0, 0, path);
- ATSCubicMoveToUPP moveTo = NewATSCubicMoveToUPP(QMacFontPath::moveTo);
- ATSCubicLineToUPP lineTo = NewATSCubicLineToUPP(QMacFontPath::lineTo);
- ATSCubicCurveToUPP cubicTo = NewATSCubicCurveToUPP(QMacFontPath::cubicTo);
- ATSCubicClosePathUPP closePath = NewATSCubicClosePathUPP(QMacFontPath::closePath);
-
- // CTFontCreatePathForGlyph
- for (int i = 0; i < numGlyphs; ++i) {
- GlyphID glyph = glyphs[i];
-
- fontpath.setPosition(positions[i].x.toReal(), positions[i].y.toReal());
- ATSUGlyphGetCubicPaths(style, glyph, moveTo, lineTo,
- cubicTo, closePath, &fontpath, &e);
- }
-
- DisposeATSCubicMoveToUPP(moveTo);
- DisposeATSCubicLineToUPP(lineTo);
- DisposeATSCubicCurveToUPP(cubicTo);
- DisposeATSCubicClosePathUPP(closePath);
-}
-
-void QFontEngineMac::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path,
- QTextItem::RenderFlags)
-{
- addGlyphsToPathHelper(style, glyphs, positions, numGlyphs, path);
-}
-
-
-/*!
- Helper function for alphaMapForGlyph and alphaRGBMapForGlyph. The two are identical, except for
- the subpixel antialiasing...
-*/
-QImage QFontEngineMac::imageForGlyph(glyph_t glyph, int margin, bool colorful)
-{
- const glyph_metrics_t br = boundingBox(glyph);
- QImage im(qRound(br.width)+2, qRound(br.height)+4, QImage::Format_RGB32);
- im.fill(0xff000000);
-
- CGColorSpaceRef colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
- uint cgflags = kCGImageAlphaNoneSkipFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- cgflags |= kCGBitmapByteOrder32Host;
-#endif
- CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(),
- 8, im.bytesPerLine(), colorspace,
- cgflags);
- CGContextSetFontSize(ctx, fontDef.pixelSize);
- CGContextSetShouldAntialias(ctx, fontDef.pointSize > qt_antialiasing_threshold && !(fontDef.styleStrategy & QFont::NoAntialias));
- // turn off sub-pixel hinting - no support for that in OpenGL
- CGContextSetShouldSmoothFonts(ctx, colorful);
- CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
- CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
- CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, tanf(14 * acosf(0) / 90), 1, 0, 0));
-
- cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
- CGContextSetTextMatrix(ctx, cgMatrix);
- CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
- CGContextSetTextDrawingMode(ctx, kCGTextFill);
- CGContextSetFont(ctx, cgFont);
-
- qreal pos_x = -br.x.toReal() + 1;
- qreal pos_y = im.height() + br.y.toReal() - 2;
- CGContextSetTextPosition(ctx, pos_x, pos_y);
-
- CGSize advance;
- advance.width = 0;
- advance.height = 0;
- CGGlyph cgGlyph = glyph;
- CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-
- if (synthesisFlags & QFontEngine::SynthesizedBold) {
- CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y);
- CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
- }
-
- CGContextRelease(ctx);
-
- return im;
-}
-
-QImage QFontEngineMac::alphaMapForGlyph(glyph_t glyph)
-{
- QImage im = imageForGlyph(glyph, 2, false);
-
- QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
- QVector<QRgb> colors(256);
- for (int i=0; i<256; ++i)
- colors[i] = qRgba(0, 0, 0, i);
- indexed.setColorTable(colors);
-
- for (int y=0; y<im.height(); ++y) {
- uint *src = (uint*) im.scanLine(y);
- uchar *dst = indexed.scanLine(y);
- for (int x=0; x<im.width(); ++x) {
- *dst = qGray(*src);
- ++dst;
- ++src;
- }
- }
-
- return indexed;
-}
-
-QImage QFontEngineMac::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, const QTransform &t)
-{
- QImage im = imageForGlyph(glyph, margin, true);
-
- if (t.type() >= QTransform::TxScale) {
- im = im.transformed(t);
- }
-
- qGamma_correct_back_to_linear_cs(&im);
-
- return im;
-}
-
-
-bool QFontEngineMac::canRender(const QChar *string, int len)
-{
- Q_ASSERT(false);
- Q_UNUSED(string);
- Q_UNUSED(len);
- return false;
-}
-
-void QFontEngineMac::draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight)
-{
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> glyphs;
- QTransform matrix;
- matrix.translate(x, y);
- getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
- if (glyphs.size() == 0)
- return;
-
- CGContextSetFontSize(ctx, fontDef.pixelSize);
-
- CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
-
- CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, -1, 0, -paintDeviceHeight);
-
- CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -tanf(14 * acosf(0) / 90), 1, 0, 0));
-
- cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
- CGContextSetTextMatrix(ctx, cgMatrix);
-
- CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
-
- QVarLengthArray<CGSize> advances(glyphs.size());
- QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size());
-
- for (int i = 0; i < glyphs.size() - 1; ++i) {
- advances[i].width = (positions[i + 1].x - positions[i].x).toReal();
- advances[i].height = (positions[i + 1].y - positions[i].y).toReal();
- cgGlyphs[i] = glyphs[i];
- }
- advances[glyphs.size() - 1].width = 0;
- advances[glyphs.size() - 1].height = 0;
- cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1];
-
- CGContextSetFont(ctx, cgFont);
-
- CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal());
-
- CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-
- if (synthesisFlags & QFontEngine::SynthesizedBold) {
- CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(),
- positions[0].y.toReal());
-
- CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
- }
-
- CGContextSetTextMatrix(ctx, oldTextMatrix);
-}
-
-QFontEngine::FaceId QFontEngineMac::faceId() const
-{
- FaceId ret;
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- // CTFontGetPlatformFont
- FSRef ref;
- if (ATSFontGetFileReference(FMGetATSFontRefFromFont(fontID), &ref) != noErr)
- return ret;
- ret.filename = QByteArray(128, 0);
- ret.index = fontID;
- FSRefMakePath(&ref, (UInt8 *)ret.filename.data(), ret.filename.size());
-}else
-#endif
-{
- FSSpec spec;
- if (ATSFontGetFileSpecification(FMGetATSFontRefFromFont(fontID), &spec) != noErr)
- return ret;
-
- FSRef ref;
- FSpMakeFSRef(&spec, &ref);
- ret.filename = QByteArray(128, 0);
- ret.index = fontID;
- FSRefMakePath(&ref, (UInt8 *)ret.filename.data(), ret.filename.size());
-}
- return ret;
-}
-
-QByteArray QFontEngineMac::getSfntTable(uint tag) const
-{
- ATSFontRef atsFont = FMGetATSFontRefFromFont(fontID);
-
- ByteCount length;
- OSStatus status = ATSFontGetTable(atsFont, tag, 0, 0, 0, &length);
- if (status != noErr)
- return QByteArray();
- QByteArray table(length, 0);
- // CTFontCopyTable
- status = ATSFontGetTable(atsFont, tag, 0, table.length(), table.data(), &length);
- if (status != noErr)
- return QByteArray();
- return table;
-}
-
-QFontEngine::Properties QFontEngineMac::properties() const
-{
- QFontEngine::Properties props;
- ATSFontRef atsFont = FMGetATSFontRefFromFont(fontID);
- quint16 tmp;
- // CTFontGetUnitsPerEm
- if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 18, 2, &tmp, 0) == noErr)
- props.emSquare = qFromBigEndian<quint16>(tmp);
- struct {
- qint16 xMin;
- qint16 yMin;
- qint16 xMax;
- qint16 yMax;
- } bbox;
- bbox.xMin = bbox.xMax = bbox.yMin = bbox.yMax = 0;
- // CTFontGetBoundingBox
- if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 36, 8, &bbox, 0) == noErr) {
- bbox.xMin = qFromBigEndian<quint16>(bbox.xMin);
- bbox.yMin = qFromBigEndian<quint16>(bbox.yMin);
- bbox.xMax = qFromBigEndian<quint16>(bbox.xMax);
- bbox.yMax = qFromBigEndian<quint16>(bbox.yMax);
- }
- struct {
- qint16 ascender;
- qint16 descender;
- qint16 linegap;
- } metrics;
- metrics.ascender = metrics.descender = metrics.linegap = 0;
- // CTFontGetAscent, etc.
- if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'h', 'e', 'a'), 4, 6, &metrics, 0) == noErr) {
- metrics.ascender = qFromBigEndian<quint16>(metrics.ascender);
- metrics.descender = qFromBigEndian<quint16>(metrics.descender);
- metrics.linegap = qFromBigEndian<quint16>(metrics.linegap);
- }
- props.ascent = metrics.ascender;
- props.descent = -metrics.descender;
- props.leading = metrics.linegap;
- props.boundingBox = QRectF(bbox.xMin, -bbox.yMax,
- bbox.xMax - bbox.xMin,
- bbox.yMax - bbox.yMin);
- props.italicAngle = 0;
- props.capHeight = props.ascent;
-
- qint16 lw = 0;
- // fonts lie
- if (ATSFontGetTable(atsFont, MAKE_TAG('p', 'o', 's', 't'), 10, 2, &lw, 0) == noErr)
- lw = qFromBigEndian<quint16>(lw);
- props.lineWidth = lw;
-
- // CTFontCopyPostScriptName
- QCFString psName;
- if (ATSFontGetPostScriptName(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &psName) == noErr)
- props.postscriptName = QString(psName).toUtf8();
- props.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(props.postscriptName);
- return props;
-}
-
-void QFontEngineMac::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
-{
- ATSUStyle unscaledStyle;
- ATSUCreateAndCopyStyle(style, &unscaledStyle);
-
- int emSquare = properties().emSquare.toInt();
-
- const int maxAttributeCount = 4;
- ATSUAttributeTag tags[maxAttributeCount + 1];
- ByteCount sizes[maxAttributeCount + 1];
- ATSUAttributeValuePtr values[maxAttributeCount + 1];
- int attributeCount = 0;
-
- Fixed size = FixRatio(emSquare, 1);
- tags[attributeCount] = kATSUSizeTag;
- sizes[attributeCount] = sizeof(size);
- values[attributeCount] = &size;
- ++attributeCount;
-
- Q_ASSERT(attributeCount < maxAttributeCount + 1);
- OSStatus err = ATSUSetAttributes(unscaledStyle, attributeCount, tags, sizes, values);
- Q_ASSERT(err == noErr);
- Q_UNUSED(err);
-
- // various CTFont metrics functions: CTFontGetBoundingRectsForGlyphs, CTFontGetAdvancesForGlyphs
- GlyphID atsuGlyph = glyph;
- ATSGlyphScreenMetrics atsuMetrics;
- ATSUGlyphGetScreenMetrics(unscaledStyle, 1, &atsuGlyph, 0,
- /* iForcingAntiAlias =*/ false,
- /* iAntiAliasSwitch =*/true,
- &atsuMetrics);
-
- metrics->width = int(atsuMetrics.width);
- metrics->height = int(atsuMetrics.height);
- metrics->x = QFixed::fromReal(atsuMetrics.topLeft.x);
- metrics->y = -QFixed::fromReal(atsuMetrics.topLeft.y);
- metrics->xoff = QFixed::fromReal(atsuMetrics.deviceAdvance.x);
- metrics->yoff = QFixed::fromReal(atsuMetrics.deviceAdvance.y);
-
- QFixedPoint p;
- addGlyphsToPathHelper(unscaledStyle, &glyph, &p, 1, path);
-
- ATSUDisposeStyle(unscaledStyle);
-}
-#endif // !QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qfontengine_mac_p.h b/src/gui/platforms/mac/qfontengine_mac_p.h
deleted file mode 100644
index 292ea98d9a..0000000000
--- a/src/gui/platforms/mac/qfontengine_mac_p.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTENGINE_MAC_P_H
-#define QFONTENGINE_MAC_P_H
-
-#include <private/qfontengine_p.h>
-
-#ifndef QT_MAC_USE_COCOA
-class QFontEngineMacMulti;
-class QFontEngineMac : public QFontEngine
-{
- friend class QFontEngineMacMulti;
-public:
- QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine = 0);
- virtual ~QFontEngineMac();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *numGlyphs, QTextEngine::ShaperFlags flags) const;
- virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- virtual glyph_metrics_t boundingBox(glyph_t glyph);
-
- virtual QFixed ascent() const;
- virtual QFixed descent() const;
- virtual QFixed leading() const;
- virtual QFixed xHeight() const;
- virtual qreal maxCharWidth() const;
- virtual QFixed averageCharWidth() const;
-
- virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
- QPainterPath *path, QTextItem::RenderFlags);
-
- virtual const char *name() const { return "QFontEngineMac"; }
-
- virtual bool canRender(const QChar *string, int len);
-
- virtual int synthesized() const { return synthesisFlags; }
-
- virtual Type type() const { return QFontEngine::Mac; }
-
- void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
-
- virtual FaceId faceId() const;
- virtual QByteArray getSfntTable(uint tag) const;
- virtual Properties properties() const;
- virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
- virtual QImage alphaMapForGlyph(glyph_t);
- virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
-
-private:
- QImage imageForGlyph(glyph_t glyph, int margin, bool colorful);
-
- ATSUFontID fontID;
- QCFType<CGFontRef> cgFont;
- ATSUStyle style;
- int synthesisFlags;
- mutable QGlyphLayout kashidaGlyph;
- QFontEngineMacMulti *multiEngine;
- mutable const unsigned char *cmap;
- mutable bool symbolCMap;
- mutable QByteArray cmapTable;
- CGAffineTransform transform;
- QFixed m_ascent;
- QFixed m_descent;
- QFixed m_leading;
- qreal m_maxCharWidth;
- QFixed m_xHeight;
- QFixed m_averageCharWidth;
-};
-
-class QFontEngineMacMulti : public QFontEngineMulti
-{
- friend class QFontEngineMac;
-public:
- // internal
- struct ShaperItem
- {
- inline ShaperItem() : string(0), from(0), length(0),
- log_clusters(0), charAttributes(0) {}
-
- const QChar *string;
- int from;
- int length;
- QGlyphLayout glyphs;
- unsigned short *log_clusters;
- const HB_CharAttributes *charAttributes;
- QTextEngine::ShaperFlags flags;
- };
-
- QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning);
- virtual ~QFontEngineMacMulti();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,
- unsigned short *logClusters, const HB_CharAttributes *charAttributes, QScriptItem *) const;
-
- virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
- virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual const char *name() const { return "ATSUI"; }
-
- virtual bool canRender(const QChar *string, int len);
-
- inline ATSUFontID macFontID() const { return fontID; }
-
-protected:
- virtual void loadEngine(int at);
-
-private:
- inline const QFontEngineMac *engineAt(int i) const
- { return static_cast<const QFontEngineMac *>(engines.at(i)); }
-
- bool stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, ShaperItem *item) const;
-
- int fontIndexForFontID(ATSUFontID id) const;
-
- ATSUFontID fontID;
- uint kerning : 1;
-
- mutable ATSUTextLayout textLayout;
- mutable ATSUStyle style;
- CGAffineTransform transform;
-};
-#endif //!QT_MAC_USE_COCOA
-
-#endif // QFONTENGINE_MAC_P_H
diff --git a/src/gui/platforms/mac/qkeymapper_mac.cpp b/src/gui/platforms/mac/qkeymapper_mac.cpp
deleted file mode 100644
index d3bbf89711..0000000000
--- a/src/gui/platforms/mac/qkeymapper_mac.cpp
+++ /dev/null
@@ -1,1023 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qt_mac_p.h>
-#include <qdebug.h>
-#include <qevent.h>
-#include <private/qevent_p.h>
-#include <qtextcodec.h>
-#include <qapplication.h>
-#include <qinputcontext.h>
-#include <private/qkeymapper_p.h>
-#include <private/qapplication_p.h>
-#include <private/qmacinputcontext_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
- QKeyMapper debug facilities
- *****************************************************************************/
-//#define DEBUG_KEY_BINDINGS
-//#define DEBUG_KEY_BINDINGS_MODIFIERS
-//#define DEBUG_KEY_MAPS
-
-/*****************************************************************************
- Internal variables and functions
- *****************************************************************************/
-bool qt_mac_eat_unicode_key = false;
-extern bool qt_sendSpontaneousEvent(QObject *obj, QEvent *event); //qapplication_mac.cpp
-
-Q_GUI_EXPORT void qt_mac_secure_keyboard(bool b)
-{
- static bool secure = false;
- if (b != secure){
- b ? EnableSecureEventInput() : DisableSecureEventInput();
- secure = b;
- }
-}
-
-/*
- \internal
- A Mac KeyboardLayoutItem has 8 possible states:
- 1. Unmodified
- 2. Shift
- 3. Control
- 4. Control + Shift
- 5. Alt
- 6. Alt + Shift
- 7. Alt + Control
- 8. Alt + Control + Shift
- 9. Meta
- 10. Meta + Shift
- 11. Meta + Control
- 12. Meta + Control + Shift
- 13. Meta + Alt
- 14. Meta + Alt + Shift
- 15. Meta + Alt + Control
- 16. Meta + Alt + Control + Shift
-*/
-struct KeyboardLayoutItem {
- bool dirty;
- quint32 qtKey[16]; // Can by any Qt::Key_<foo>, or unicode character
-};
-
-// Possible modifier states.
-// NOTE: The order of these states match the order in QKeyMapperPrivate::updatePossibleKeyCodes()!
-static const Qt::KeyboardModifiers ModsTbl[] = {
- Qt::NoModifier, // 0
- Qt::ShiftModifier, // 1
- Qt::ControlModifier, // 2
- Qt::ControlModifier | Qt::ShiftModifier, // 3
- Qt::AltModifier, // 4
- Qt::AltModifier | Qt::ShiftModifier, // 5
- Qt::AltModifier | Qt::ControlModifier, // 6
- Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier, // 7
- Qt::MetaModifier, // 8
- Qt::MetaModifier | Qt::ShiftModifier, // 9
- Qt::MetaModifier | Qt::ControlModifier, // 10
- Qt::MetaModifier | Qt::ControlModifier | Qt::ShiftModifier,// 11
- Qt::MetaModifier | Qt::AltModifier, // 12
- Qt::MetaModifier | Qt::AltModifier | Qt::ShiftModifier, // 13
- Qt::MetaModifier | Qt::AltModifier | Qt::ControlModifier, // 14
- Qt::MetaModifier | Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier, // 15
-};
-
-/* key maps */
-struct qt_mac_enum_mapper
-{
- int mac_code;
- int qt_code;
-#if defined(DEBUG_KEY_BINDINGS)
-# define QT_MAC_MAP_ENUM(x) x, #x
- const char *desc;
-#else
-# define QT_MAC_MAP_ENUM(x) x
-#endif
-};
-
-//modifiers
-static qt_mac_enum_mapper qt_mac_modifier_symbols[] = {
- { shiftKey, QT_MAC_MAP_ENUM(Qt::ShiftModifier) },
- { rightShiftKey, QT_MAC_MAP_ENUM(Qt::ShiftModifier) },
- { controlKey, QT_MAC_MAP_ENUM(Qt::MetaModifier) },
- { rightControlKey, QT_MAC_MAP_ENUM(Qt::MetaModifier) },
- { cmdKey, QT_MAC_MAP_ENUM(Qt::ControlModifier) },
- { optionKey, QT_MAC_MAP_ENUM(Qt::AltModifier) },
- { rightOptionKey, QT_MAC_MAP_ENUM(Qt::AltModifier) },
- { kEventKeyModifierNumLockMask, QT_MAC_MAP_ENUM(Qt::KeypadModifier) },
- { 0, QT_MAC_MAP_ENUM(0) }
-};
-Qt::KeyboardModifiers qt_mac_get_modifiers(int keys)
-{
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("Qt: internal: **Mapping modifiers: %d (0x%04x)", keys, keys);
-#endif
- Qt::KeyboardModifiers ret = Qt::NoModifier;
- for (int i = 0; qt_mac_modifier_symbols[i].qt_code; i++) {
- if (keys & qt_mac_modifier_symbols[i].mac_code) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("Qt: internal: got modifier: %s", qt_mac_modifier_symbols[i].desc);
-#endif
- ret |= Qt::KeyboardModifier(qt_mac_modifier_symbols[i].qt_code);
- }
- }
- if (qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) {
- Qt::KeyboardModifiers oldModifiers = ret;
- ret &= ~(Qt::MetaModifier | Qt::ControlModifier);
- if (oldModifiers & Qt::ControlModifier)
- ret |= Qt::MetaModifier;
- if (oldModifiers & Qt::MetaModifier)
- ret |= Qt::ControlModifier;
- }
- return ret;
-}
-static int qt_mac_get_mac_modifiers(Qt::KeyboardModifiers keys)
-{
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("Qt: internal: **Mapping modifiers: %d (0x%04x)", (int)keys, (int)keys);
-#endif
- int ret = 0;
- for (int i = 0; qt_mac_modifier_symbols[i].qt_code; i++) {
- if (keys & qt_mac_modifier_symbols[i].qt_code) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("Qt: internal: got modifier: %s", qt_mac_modifier_symbols[i].desc);
-#endif
- ret |= qt_mac_modifier_symbols[i].mac_code;
- }
- }
-
- if (qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) {
- int oldModifiers = ret;
- ret &= ~(controlKeyBit | cmdKeyBit);
- if (oldModifiers & controlKeyBit)
- ret |= cmdKeyBit;
- if (oldModifiers & cmdKeyBit)
- ret |= controlKeyBit;
- }
- return ret;
-}
-void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object)
-{
- static quint32 cachedModifiers = 0;
- quint32 lastModifiers = cachedModifiers,
- changedModifiers = lastModifiers ^ modifiers;
- cachedModifiers = modifiers;
-
- //check the bits
- static qt_mac_enum_mapper modifier_key_symbols[] = {
- { shiftKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Shift) },
- { rightShiftKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Shift) }, //???
- { controlKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Meta) },
- { rightControlKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Meta) }, //???
- { cmdKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Control) },
- { optionKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Alt) },
- { rightOptionKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Alt) }, //???
- { alphaLockBit, QT_MAC_MAP_ENUM(Qt::Key_CapsLock) },
- { kEventKeyModifierNumLockBit, QT_MAC_MAP_ENUM(Qt::Key_NumLock) },
- { 0, QT_MAC_MAP_ENUM(0) } };
- for (int i = 0; i <= 32; i++) { //just check each bit
- if (!(changedModifiers & (1 << i)))
- continue;
- QEvent::Type etype = QEvent::KeyPress;
- if (lastModifiers & (1 << i))
- etype = QEvent::KeyRelease;
- int key = 0;
- for (uint x = 0; modifier_key_symbols[x].mac_code; x++) {
- if (modifier_key_symbols[x].mac_code == i) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("got modifier changed: %s", modifier_key_symbols[x].desc);
-#endif
- key = modifier_key_symbols[x].qt_code;
- break;
- }
- }
- if (!key) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("could not get modifier changed: %d", i);
-#endif
- continue;
- }
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("KeyEvent (modif): Sending %s to %s::%s: %d - 0x%08x",
- etype == QEvent::KeyRelease ? "KeyRelease" : "KeyPress",
- object ? object->metaObject()->className() : "none",
- object ? object->objectName().toLatin1().constData() : "",
- key, (int)modifiers);
-#endif
- QKeyEvent ke(etype, key, qt_mac_get_modifiers(modifiers ^ (1 << i)), QLatin1String(""));
- qt_sendSpontaneousEvent(object, &ke);
- }
-}
-
-//keyboard keys (non-modifiers)
-static qt_mac_enum_mapper qt_mac_keyboard_symbols[] = {
- { kHomeCharCode, QT_MAC_MAP_ENUM(Qt::Key_Home) },
- { kEnterCharCode, QT_MAC_MAP_ENUM(Qt::Key_Enter) },
- { kEndCharCode, QT_MAC_MAP_ENUM(Qt::Key_End) },
- { kBackspaceCharCode, QT_MAC_MAP_ENUM(Qt::Key_Backspace) },
- { kTabCharCode, QT_MAC_MAP_ENUM(Qt::Key_Tab) },
- { kPageUpCharCode, QT_MAC_MAP_ENUM(Qt::Key_PageUp) },
- { kPageDownCharCode, QT_MAC_MAP_ENUM(Qt::Key_PageDown) },
- { kReturnCharCode, QT_MAC_MAP_ENUM(Qt::Key_Return) },
- { kEscapeCharCode, QT_MAC_MAP_ENUM(Qt::Key_Escape) },
- { kLeftArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Left) },
- { kRightArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Right) },
- { kUpArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Up) },
- { kDownArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Down) },
- { kHelpCharCode, QT_MAC_MAP_ENUM(Qt::Key_Help) },
- { kDeleteCharCode, QT_MAC_MAP_ENUM(Qt::Key_Delete) },
-//ascii maps, for debug
- { ':', QT_MAC_MAP_ENUM(Qt::Key_Colon) },
- { ';', QT_MAC_MAP_ENUM(Qt::Key_Semicolon) },
- { '<', QT_MAC_MAP_ENUM(Qt::Key_Less) },
- { '=', QT_MAC_MAP_ENUM(Qt::Key_Equal) },
- { '>', QT_MAC_MAP_ENUM(Qt::Key_Greater) },
- { '?', QT_MAC_MAP_ENUM(Qt::Key_Question) },
- { '@', QT_MAC_MAP_ENUM(Qt::Key_At) },
- { ' ', QT_MAC_MAP_ENUM(Qt::Key_Space) },
- { '!', QT_MAC_MAP_ENUM(Qt::Key_Exclam) },
- { '"', QT_MAC_MAP_ENUM(Qt::Key_QuoteDbl) },
- { '#', QT_MAC_MAP_ENUM(Qt::Key_NumberSign) },
- { '$', QT_MAC_MAP_ENUM(Qt::Key_Dollar) },
- { '%', QT_MAC_MAP_ENUM(Qt::Key_Percent) },
- { '&', QT_MAC_MAP_ENUM(Qt::Key_Ampersand) },
- { '\'', QT_MAC_MAP_ENUM(Qt::Key_Apostrophe) },
- { '(', QT_MAC_MAP_ENUM(Qt::Key_ParenLeft) },
- { ')', QT_MAC_MAP_ENUM(Qt::Key_ParenRight) },
- { '*', QT_MAC_MAP_ENUM(Qt::Key_Asterisk) },
- { '+', QT_MAC_MAP_ENUM(Qt::Key_Plus) },
- { ',', QT_MAC_MAP_ENUM(Qt::Key_Comma) },
- { '-', QT_MAC_MAP_ENUM(Qt::Key_Minus) },
- { '.', QT_MAC_MAP_ENUM(Qt::Key_Period) },
- { '/', QT_MAC_MAP_ENUM(Qt::Key_Slash) },
- { '[', QT_MAC_MAP_ENUM(Qt::Key_BracketLeft) },
- { ']', QT_MAC_MAP_ENUM(Qt::Key_BracketRight) },
- { '\\', QT_MAC_MAP_ENUM(Qt::Key_Backslash) },
- { '_', QT_MAC_MAP_ENUM(Qt::Key_Underscore) },
- { '`', QT_MAC_MAP_ENUM(Qt::Key_QuoteLeft) },
- { '{', QT_MAC_MAP_ENUM(Qt::Key_BraceLeft) },
- { '}', QT_MAC_MAP_ENUM(Qt::Key_BraceRight) },
- { '|', QT_MAC_MAP_ENUM(Qt::Key_Bar) },
- { '~', QT_MAC_MAP_ENUM(Qt::Key_AsciiTilde) },
- { '^', QT_MAC_MAP_ENUM(Qt::Key_AsciiCircum) },
- { 0, QT_MAC_MAP_ENUM(0) }
-};
-
-static qt_mac_enum_mapper qt_mac_keyvkey_symbols[] = { //real scan codes
- { 122, QT_MAC_MAP_ENUM(Qt::Key_F1) },
- { 120, QT_MAC_MAP_ENUM(Qt::Key_F2) },
- { 99, QT_MAC_MAP_ENUM(Qt::Key_F3) },
- { 118, QT_MAC_MAP_ENUM(Qt::Key_F4) },
- { 96, QT_MAC_MAP_ENUM(Qt::Key_F5) },
- { 97, QT_MAC_MAP_ENUM(Qt::Key_F6) },
- { 98, QT_MAC_MAP_ENUM(Qt::Key_F7) },
- { 100, QT_MAC_MAP_ENUM(Qt::Key_F8) },
- { 101, QT_MAC_MAP_ENUM(Qt::Key_F9) },
- { 109, QT_MAC_MAP_ENUM(Qt::Key_F10) },
- { 103, QT_MAC_MAP_ENUM(Qt::Key_F11) },
- { 111, QT_MAC_MAP_ENUM(Qt::Key_F12) },
- { 105, QT_MAC_MAP_ENUM(Qt::Key_F13) },
- { 107, QT_MAC_MAP_ENUM(Qt::Key_F14) },
- { 113, QT_MAC_MAP_ENUM(Qt::Key_F15) },
- { 106, QT_MAC_MAP_ENUM(Qt::Key_F16) },
- { 0, QT_MAC_MAP_ENUM(0) }
-};
-
-static qt_mac_enum_mapper qt_mac_private_unicode[] = {
- { 0xF700, QT_MAC_MAP_ENUM(Qt::Key_Up) }, //NSUpArrowFunctionKey
- { 0xF701, QT_MAC_MAP_ENUM(Qt::Key_Down) }, //NSDownArrowFunctionKey
- { 0xF702, QT_MAC_MAP_ENUM(Qt::Key_Left) }, //NSLeftArrowFunctionKey
- { 0xF703, QT_MAC_MAP_ENUM(Qt::Key_Right) }, //NSRightArrowFunctionKey
- { 0xF727, QT_MAC_MAP_ENUM(Qt::Key_Insert) }, //NSInsertFunctionKey
- { 0xF728, QT_MAC_MAP_ENUM(Qt::Key_Delete) }, //NSDeleteFunctionKey
- { 0xF729, QT_MAC_MAP_ENUM(Qt::Key_Home) }, //NSHomeFunctionKey
- { 0xF72B, QT_MAC_MAP_ENUM(Qt::Key_End) }, //NSEndFunctionKey
- { 0xF72C, QT_MAC_MAP_ENUM(Qt::Key_PageUp) }, //NSPageUpFunctionKey
- { 0xF72D, QT_MAC_MAP_ENUM(Qt::Key_PageDown) }, //NSPageDownFunctionKey
- { 0xF72F, QT_MAC_MAP_ENUM(Qt::Key_ScrollLock) }, //NSScrollLockFunctionKey
- { 0xF730, QT_MAC_MAP_ENUM(Qt::Key_Pause) }, //NSPauseFunctionKey
- { 0xF731, QT_MAC_MAP_ENUM(Qt::Key_SysReq) }, //NSSysReqFunctionKey
- { 0xF735, QT_MAC_MAP_ENUM(Qt::Key_Menu) }, //NSMenuFunctionKey
- { 0xF738, QT_MAC_MAP_ENUM(Qt::Key_Print) }, //NSPrintFunctionKey
- { 0xF73A, QT_MAC_MAP_ENUM(Qt::Key_Clear) }, //NSClearDisplayFunctionKey
- { 0xF73D, QT_MAC_MAP_ENUM(Qt::Key_Insert) }, //NSInsertCharFunctionKey
- { 0xF73E, QT_MAC_MAP_ENUM(Qt::Key_Delete) }, //NSDeleteCharFunctionKey
- { 0xF741, QT_MAC_MAP_ENUM(Qt::Key_Select) }, //NSSelectFunctionKey
- { 0xF742, QT_MAC_MAP_ENUM(Qt::Key_Execute) }, //NSExecuteFunctionKey
- { 0xF746, QT_MAC_MAP_ENUM(Qt::Key_Help) }, //NSHelpFunctionKey
- { 0xF747, QT_MAC_MAP_ENUM(Qt::Key_Mode_switch) }, //NSModeSwitchFunctionKey
- { 0, QT_MAC_MAP_ENUM(0) }
-};
-
-static int qt_mac_get_key(int modif, const QChar &key, int virtualKey)
-{
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("**Mapping key: %d (0x%04x) - %d (0x%04x)", key.unicode(), key.unicode(), virtualKey, virtualKey);
-#endif
-
- if (key == kClearCharCode && virtualKey == 0x47)
- return Qt::Key_Clear;
-
- if (key.isDigit()) {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("%d: got key: %d", __LINE__, key.digitValue());
-#endif
- return key.digitValue() + Qt::Key_0;
- }
-
- if (key.isLetter()) {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("%d: got key: %d", __LINE__, (key.toUpper().unicode() - 'A'));
-#endif
- return (key.toUpper().unicode() - 'A') + Qt::Key_A;
- }
- if (key.isSymbol()) {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("%d: got key: %d", __LINE__, (key.unicode()));
-#endif
- return key.unicode();
- }
-
- for (int i = 0; qt_mac_keyboard_symbols[i].qt_code; i++) {
- if (qt_mac_keyboard_symbols[i].mac_code == key) {
- /* To work like Qt for X11 we issue Backtab when Shift + Tab are pressed */
- if (qt_mac_keyboard_symbols[i].qt_code == Qt::Key_Tab && (modif & Qt::ShiftModifier)) {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("%d: got key: Qt::Key_Backtab", __LINE__);
-#endif
- return Qt::Key_Backtab;
- }
-
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("%d: got key: %s", __LINE__, qt_mac_keyboard_symbols[i].desc);
-#endif
- return qt_mac_keyboard_symbols[i].qt_code;
- }
- }
-
- //last ditch try to match the scan code
- for (int i = 0; qt_mac_keyvkey_symbols[i].qt_code; i++) {
- if (qt_mac_keyvkey_symbols[i].mac_code == virtualKey) {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("%d: got key: %s", __LINE__, qt_mac_keyvkey_symbols[i].desc);
-#endif
- return qt_mac_keyvkey_symbols[i].qt_code;
- }
- }
-
- // check if they belong to key codes in private unicode range
- if (key >= 0xf700 && key <= 0xf747) {
- if (key >= 0xf704 && key <= 0xf726) {
- return Qt::Key_F1 + (key.unicode() - 0xf704) ;
- }
- for (int i = 0; qt_mac_private_unicode[i].qt_code; i++) {
- if (qt_mac_private_unicode[i].mac_code == key) {
- return qt_mac_private_unicode[i].qt_code;
- }
- }
-
- }
-
- //oh well
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("Unknown case.. %s:%d %d[%d] %d", __FILE__, __LINE__, key.unicode(), key.toLatin1(), virtualKey);
-#endif
- return Qt::Key_unknown;
-}
-
-static Boolean qt_KeyEventComparatorProc(EventRef inEvent, void *data)
-{
- UInt32 ekind = GetEventKind(inEvent),
- eclass = GetEventClass(inEvent);
- return (eclass == kEventClassKeyboard && (void *)ekind == data);
-}
-
-static bool translateKeyEventInternal(EventHandlerCallRef er, EventRef keyEvent, int *qtKey,
- QChar *outChar, Qt::KeyboardModifiers *outModifiers, bool *outHandled)
-{
-#if !defined(QT_MAC_USE_COCOA) || defined(Q_OS_MAC64)
- Q_UNUSED(er);
- Q_UNUSED(outHandled);
-#endif
- const UInt32 ekind = GetEventKind(keyEvent);
- {
- UInt32 mac_modifiers = 0;
- GetEventParameter(keyEvent, kEventParamKeyModifiers, typeUInt32, 0,
- sizeof(mac_modifiers), 0, &mac_modifiers);
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("************ Mapping modifiers and key ***********");
-#endif
- *outModifiers = qt_mac_get_modifiers(mac_modifiers);
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
- qDebug("------------ Mapping modifiers and key -----------");
-#endif
- }
-
- //get keycode
- UInt32 keyCode = 0;
- GetEventParameter(keyEvent, kEventParamKeyCode, typeUInt32, 0, sizeof(keyCode), 0, &keyCode);
-
- //get mac mapping
- static UInt32 tmp_unused_state = 0L;
- const UCKeyboardLayout *uchrData = 0;
-#if defined(Q_OS_MAC32)
- KeyboardLayoutRef keyLayoutRef = 0;
- KLGetCurrentKeyboardLayout(&keyLayoutRef);
- OSStatus err;
- if (keyLayoutRef != 0) {
- err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLuchrData,
- (reinterpret_cast<const void **>(&uchrData)));
- if (err != noErr) {
- qWarning("Qt::internal::unable to get keyboardlayout %ld %s:%d",
- long(err), __FILE__, __LINE__);
- }
- }
-#else
- QCFType<TISInputSourceRef> inputSource = TISCopyCurrentKeyboardInputSource();
- Q_ASSERT(inputSource != 0);
- CFDataRef data = static_cast<CFDataRef>(TISGetInputSourceProperty(inputSource,
- kTISPropertyUnicodeKeyLayoutData));
- uchrData = data ? reinterpret_cast<const UCKeyboardLayout *>(CFDataGetBytePtr(data)) : 0;
-#endif
- *qtKey = Qt::Key_unknown;
- if (uchrData) {
- // The easy stuff; use the unicode stuff!
- UniChar string[4];
- UniCharCount actualLength;
- UInt32 currentModifiers = GetCurrentEventKeyModifiers();
- UInt32 currentModifiersWOAltOrControl = currentModifiers & ~(controlKey | optionKey);
- int keyAction;
- switch (ekind) {
- default:
- case kEventRawKeyDown:
- keyAction = kUCKeyActionDown;
- break;
- case kEventRawKeyUp:
- keyAction = kUCKeyActionUp;
- break;
- case kEventRawKeyRepeat:
- keyAction = kUCKeyActionAutoKey;
- break;
- }
- OSStatus err = UCKeyTranslate(uchrData, keyCode, keyAction,
- ((currentModifiersWOAltOrControl >> 8) & 0xff), LMGetKbdType(),
- kUCKeyTranslateNoDeadKeysMask, &tmp_unused_state, 4, &actualLength,
- string);
- if (err == noErr) {
- *outChar = QChar(string[0]);
- *qtKey = qt_mac_get_key(*outModifiers, *outChar, keyCode);
- if (currentModifiersWOAltOrControl != currentModifiers) {
- // Now get the real char.
- err = UCKeyTranslate(uchrData, keyCode, keyAction,
- ((currentModifiers >> 8) & 0xff), LMGetKbdType(),
- kUCKeyTranslateNoDeadKeysMask, &tmp_unused_state, 4, &actualLength,
- string);
- if (err == noErr)
- *outChar = QChar(string[0]);
- }
- } else {
- qWarning("Qt::internal::UCKeyTranslate is returnining %ld %s:%d",
- long(err), __FILE__, __LINE__);
- }
- }
-#ifdef Q_OS_MAC32
- else {
- // The road less travelled; use KeyTranslate
- const void *keyboard_layout;
- KeyboardLayoutRef keyLayoutRef = 0;
- KLGetCurrentKeyboardLayout(&keyLayoutRef);
- err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLKCHRData,
- reinterpret_cast<const void **>(&keyboard_layout));
-
- int translatedChar = KeyTranslate(keyboard_layout, (GetCurrentEventKeyModifiers() &
- (kEventKeyModifierNumLockMask|shiftKey|cmdKey|
- rightShiftKey|alphaLock)) | keyCode,
- &tmp_unused_state);
- if (!translatedChar) {
-#ifdef QT_MAC_USE_COCOA
- if (outHandled) {
- qt_mac_eat_unicode_key = false;
- if (er)
- CallNextEventHandler(er, keyEvent);
- *outHandled = qt_mac_eat_unicode_key;
- }
-#endif
- return false;
- }
-
- //map it into qt keys
- *qtKey = qt_mac_get_key(*outModifiers, QChar(translatedChar), keyCode);
- if (*outModifiers & (Qt::AltModifier | Qt::ControlModifier)) {
- if (translatedChar & (1 << 7)) //high ascii
- translatedChar = 0;
- } else { //now get the real ascii value
- UInt32 tmp_mod = 0L;
- static UInt32 tmp_state = 0L;
- if (*outModifiers & Qt::ShiftModifier)
- tmp_mod |= shiftKey;
- if (*outModifiers & Qt::MetaModifier)
- tmp_mod |= controlKey;
- if (*outModifiers & Qt::ControlModifier)
- tmp_mod |= cmdKey;
- if (GetCurrentEventKeyModifiers() & alphaLock) //no Qt mapper
- tmp_mod |= alphaLock;
- if (*outModifiers & Qt::AltModifier)
- tmp_mod |= optionKey;
- if (*outModifiers & Qt::KeypadModifier)
- tmp_mod |= kEventKeyModifierNumLockMask;
- translatedChar = KeyTranslate(keyboard_layout, tmp_mod | keyCode, &tmp_state);
- }
- {
- ByteCount unilen = 0;
- if (GetEventParameter(keyEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, 0, &unilen, 0)
- == noErr && unilen == 2) {
- GetEventParameter(keyEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, unilen, 0, outChar);
- } else if (translatedChar) {
- static QTextCodec *c = 0;
- if (!c)
- c = QTextCodec::codecForName("Apple Roman");
- char tmpChar = (char)translatedChar; // **sigh**
- *outChar = c->toUnicode(&tmpChar, 1).at(0);
- } else {
- *qtKey = qt_mac_get_key(*outModifiers, QChar(translatedChar), keyCode);
- }
- }
- }
-#endif
- if (*qtKey == Qt::Key_unknown)
- *qtKey = qt_mac_get_key(*outModifiers, *outChar, keyCode);
- return true;
-}
-
-QKeyMapperPrivate::QKeyMapperPrivate()
-{
- memset(keyLayout, 0, sizeof(keyLayout));
- keyboard_layout_format.unicode = 0;
-#ifdef Q_OS_MAC32
- keyboard_mode = NullMode;
-#else
- currentInputSource = 0;
-#endif
-}
-
-QKeyMapperPrivate::~QKeyMapperPrivate()
-{
- deleteLayouts();
-}
-
-bool
-QKeyMapperPrivate::updateKeyboard()
-{
- const UCKeyboardLayout *uchrData = 0;
-#ifdef Q_OS_MAC32
- KeyboardLayoutRef keyLayoutRef = 0;
- KLGetCurrentKeyboardLayout(&keyLayoutRef);
-
- if (keyboard_mode != NullMode && currentKeyboardLayout == keyLayoutRef)
- return false;
-
- OSStatus err;
- if (keyLayoutRef != 0) {
- err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLuchrData,
- const_cast<const void **>(reinterpret_cast<const void **>(&uchrData)));
- if (err != noErr) {
- qWarning("Qt::internal::unable to get unicode keyboardlayout %ld %s:%d",
- long(err), __FILE__, __LINE__);
- }
- }
-#else
- QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
- if (keyboard_mode != NullMode && source == currentInputSource) {
- return false;
- }
- Q_ASSERT(source != 0);
- CFDataRef data = static_cast<CFDataRef>(TISGetInputSourceProperty(source,
- kTISPropertyUnicodeKeyLayoutData));
- uchrData = data ? reinterpret_cast<const UCKeyboardLayout *>(CFDataGetBytePtr(data)) : 0;
-#endif
-
- keyboard_kind = LMGetKbdType();
- if (uchrData) {
- keyboard_layout_format.unicode = uchrData;
- keyboard_mode = UnicodeMode;
- }
-#ifdef Q_OS_MAC32
- else {
- void *happy;
- err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLKCHRData,
- const_cast<const void **>(reinterpret_cast<void **>(&happy)));
- if (err != noErr) {
- qFatal("Qt::internal::unable to get non-unicode layout, cannot procede %ld %s:%d",
- long(err), __FILE__, __LINE__);
- }
- keyboard_layout_format.other = happy;
- keyboard_mode = OtherMode;
- }
-
- currentKeyboardLayout = keyLayoutRef;
-#else
- currentInputSource = source;
-#endif
- keyboard_dead = 0;
- CFStringRef iso639Code;
-#ifdef Q_OS_MAC32
-# ifndef kKLLanguageCode
-# define kKLLanguageCode 9
-# endif
- KLGetKeyboardLayoutProperty(currentKeyboardLayout, kKLLanguageCode,
- reinterpret_cast<const void **>(&iso639Code));
-#else
- CFArrayRef array = static_cast<CFArrayRef>(TISGetInputSourceProperty(currentInputSource, kTISPropertyInputSourceLanguages));
- iso639Code = static_cast<CFStringRef>(CFArrayGetValueAtIndex(array, 0)); // Actually a RFC3066bis, but it's close enough
-#endif
- if (iso639Code) {
- keyboardInputLocale = QLocale(QCFString::toQString(iso639Code));
- keyboardInputDirection = keyboardInputLocale.textDirection();
- } else {
- keyboardInputLocale = QLocale::c();
- keyboardInputDirection = Qt::LeftToRight;
- }
- return true;
-}
-
-void
-QKeyMapperPrivate::deleteLayouts()
-{
- keyboard_mode = NullMode;
- for (int i = 0; i < 255; ++i) {
- if (keyLayout[i]) {
- delete keyLayout[i];
- keyLayout[i] = 0;
- }
- }
-}
-
-void
-QKeyMapperPrivate::clearMappings()
-{
- deleteLayouts();
- updateKeyboard();
-}
-
-QList<int>
-QKeyMapperPrivate::possibleKeys(QKeyEvent *e)
-{
- QList<int> ret;
-
- KeyboardLayoutItem *kbItem = keyLayout[e->nativeVirtualKey()];
- if (!kbItem) // Key is not in any keyboard layout (e.g. eisu-key on Japanese keyboard)
- return ret;
-
- int baseKey = kbItem->qtKey[0];
- Qt::KeyboardModifiers keyMods = e->modifiers();
- ret << int(baseKey + keyMods); // The base key is _always_ valid, of course
-
- for (int i = 1; i < 8; ++i) {
- Qt::KeyboardModifiers neededMods = ModsTbl[i];
- int key = kbItem->qtKey[i];
- if (key && key != baseKey && ((keyMods & neededMods) == neededMods))
- ret << int(key + (keyMods & ~neededMods));
- }
-
- return ret;
-}
-
-bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, EventHandlerCallRef er, EventRef event,
- void *info, bool grab)
-{
- Q_ASSERT(GetEventClass(event) == kEventClassKeyboard);
- bool handled_event=true;
- UInt32 ekind = GetEventKind(event);
-
- // unfortunately modifiers changed event looks quite different, so I have a separate
- // code path
- if (ekind == kEventRawKeyModifiersChanged) {
- //figure out changed modifiers, wish Apple would just send a delta
- UInt32 modifiers = 0;
- GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
- sizeof(modifiers), 0, &modifiers);
- qt_mac_send_modifiers_changed(modifiers, widget);
- return true;
- }
-
- QInputContext *currentContext = qApp->inputContext();
- if (currentContext && currentContext->isComposing()) {
- if (ekind == kEventRawKeyDown) {
- QMacInputContext *context = qobject_cast<QMacInputContext*>(currentContext);
- if (context)
- context->setLastKeydownEvent(event);
- }
- return false;
- }
- // Once we process the key down , we don't need to send the saved event again from
- // kEventTextInputUnicodeForKeyEvent, so clear it.
- if (currentContext && ekind == kEventRawKeyDown) {
- QMacInputContext *context = qobject_cast<QMacInputContext*>(currentContext);
- if (context)
- context->setLastKeydownEvent(0);
- }
-
- //get modifiers
- Qt::KeyboardModifiers modifiers;
- int qtKey;
- QChar ourChar;
- if (translateKeyEventInternal(er, event, &qtKey, &ourChar, &modifiers,
- &handled_event) == false)
- return handled_event;
- QString text(ourChar);
- /* This is actually wrong - but unfortunately it is the best that can be
- done for now because of the Control/Meta mapping problems */
- if (modifiers & (Qt::ControlModifier | Qt::MetaModifier)
- && !qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) {
- text = QString();
- }
-
-
- if (widget) {
-#ifndef QT_MAC_USE_COCOA
- Q_UNUSED(info);
- // Try not to call "other" event handlers if we have a popup,
- // However, if the key has text
- // then we should pass it along because otherwise then people
- // can use input method stuff.
- if (!qApp->activePopupWidget()
- || (qApp->activePopupWidget() && !text.isEmpty())) {
- //Find out if someone else wants the event, namely
- //is it of use to text services? If so we won't bother
- //with a QKeyEvent.
- qt_mac_eat_unicode_key = false;
- if (er)
- CallNextEventHandler(er, event);
- extern bool qt_mac_menubar_is_open();
- if (qt_mac_eat_unicode_key || qt_mac_menubar_is_open()) {
- return true;
- }
- }
-#endif
- // Try to compress key events.
- if (!text.isEmpty() && widget->testAttribute(Qt::WA_KeyCompression)) {
- EventTime lastTime = GetEventTime(event);
- for (;;) {
- EventRef releaseEvent = FindSpecificEventInQueue(GetMainEventQueue(),
- qt_KeyEventComparatorProc,
- (void*)kEventRawKeyUp);
- if (!releaseEvent)
- break;
- const EventTime releaseTime = GetEventTime(releaseEvent);
- if (releaseTime < lastTime)
- break;
- lastTime = releaseTime;
-
- EventRef pressEvent = FindSpecificEventInQueue(GetMainEventQueue(),
- qt_KeyEventComparatorProc,
- (void*)kEventRawKeyDown);
- if (!pressEvent)
- break;
- const EventTime pressTime = GetEventTime(pressEvent);
- if (pressTime < lastTime)
- break;
- lastTime = pressTime;
-
- Qt::KeyboardModifiers compressMod;
- int compressQtKey = 0;
- QChar compressChar;
- if (translateKeyEventInternal(er, pressEvent,
- &compressQtKey, &compressChar, &compressMod, 0)
- == false) {
- break;
- }
- // Copied from qapplication_x11.cpp (change both).
-
- bool stopCompression =
- // 1) misc keys
- (compressQtKey >= Qt::Key_Escape && compressQtKey <= Qt::Key_SysReq)
- // 2) cursor movement
- || (compressQtKey >= Qt::Key_Home && compressQtKey <= Qt::Key_PageDown)
- // 3) extra keys
- || (compressQtKey >= Qt::Key_Super_L && compressQtKey <= Qt::Key_Direction_R)
- // 4) something that a) doesn't translate to text or b) translates
- // to newline text
- || (compressQtKey == 0)
- || (compressChar == QLatin1Char('\n'))
- || (compressQtKey == Qt::Key_unknown);
-
- if (compressMod == modifiers && !compressChar.isNull() && !stopCompression) {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("compressing away %c", compressChar.toLatin1());
-#endif
- text += compressChar;
- // Clean up
- RemoveEventFromQueue(GetMainEventQueue(), releaseEvent);
- RemoveEventFromQueue(GetMainEventQueue(), pressEvent);
- } else {
-#ifdef DEBUG_KEY_BINDINGS
- qDebug("stoping compression..");
-#endif
- break;
- }
- }
- }
-
- // There is no way to get the scan code from carbon. But we cannot use the value 0, since
- // it indicates that the event originates from somewhere else than the keyboard
- UInt32 macScanCode = 1;
- UInt32 macVirtualKey = 0;
- GetEventParameter(event, kEventParamKeyCode, typeUInt32, 0, sizeof(macVirtualKey), 0, &macVirtualKey);
- UInt32 macModifiers = 0;
- GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
- sizeof(macModifiers), 0, &macModifiers);
-#ifdef QT_MAC_USE_COCOA
- // The unicode characters in the range 0xF700-0xF747 are reserved
- // by Mac OS X for transient use as keyboard function keys. We
- // wont send 'text' for such key events. This is done to match
- // behavior on other platforms.
- unsigned int *unicodeKey = (unsigned int*)info;
- if (*unicodeKey >= 0xf700 && *unicodeKey <= 0xf747)
- text = QString();
- bool isAccepted;
-#endif
- handled_event = QKeyMapper::sendKeyEvent(widget, grab,
- (ekind == kEventRawKeyUp) ? QEvent::KeyRelease : QEvent::KeyPress,
- qtKey, modifiers, text, ekind == kEventRawKeyRepeat, 0,
- macScanCode, macVirtualKey, macModifiers
-#ifdef QT_MAC_USE_COCOA
- ,&isAccepted
-#endif
- );
-#ifdef QT_MAC_USE_COCOA
- *unicodeKey = (unsigned int)isAccepted;
-#endif
- }
- return handled_event;
-}
-
-void
-QKeyMapperPrivate::updateKeyMap(EventHandlerCallRef, EventRef event, void *
-#if defined(QT_MAC_USE_COCOA)
- unicodeKey // unicode character from NSEvent (modifiers applied)
-#endif
- )
-{
- UInt32 macVirtualKey = 0;
- GetEventParameter(event, kEventParamKeyCode, typeUInt32, 0, sizeof(macVirtualKey), 0, &macVirtualKey);
- if (updateKeyboard())
- QKeyMapper::changeKeyboard();
- else if (keyLayout[macVirtualKey])
- return;
-
- UniCharCount buffer_size = 10;
- UniChar buffer[buffer_size];
- keyLayout[macVirtualKey] = new KeyboardLayoutItem;
- for (int i = 0; i < 16; ++i) {
- UniCharCount out_buffer_size = 0;
- keyLayout[macVirtualKey]->qtKey[i] = 0;
-#ifdef Q_WS_MAC32
- if (keyboard_mode == UnicodeMode) {
-#endif
- const UInt32 keyModifier = ((qt_mac_get_mac_modifiers(ModsTbl[i]) >> 8) & 0xFF);
- OSStatus err = UCKeyTranslate(keyboard_layout_format.unicode, macVirtualKey, kUCKeyActionDown, keyModifier,
- keyboard_kind, 0, &keyboard_dead, buffer_size, &out_buffer_size, buffer);
- if (err == noErr && out_buffer_size) {
- const QChar unicode(buffer[0]);
- int qtkey = qt_mac_get_key(keyModifier, unicode, macVirtualKey);
- if (qtkey == Qt::Key_unknown)
- qtkey = unicode.unicode();
- keyLayout[macVirtualKey]->qtKey[i] = qtkey;
- }
-#ifndef Q_WS_MAC32
- else {
- const QChar unicode(*((UniChar *)unicodeKey));
- int qtkey = qt_mac_get_key(keyModifier, unicode, macVirtualKey);
- if (qtkey == Qt::Key_unknown)
- qtkey = unicode.unicode();
- keyLayout[macVirtualKey]->qtKey[i] = qtkey;
- }
-#endif
-#ifdef Q_WS_MAC32
- } else {
- const UInt32 keyModifier = (qt_mac_get_mac_modifiers(ModsTbl[i]));
-
- uchar translatedChar = KeyTranslate(keyboard_layout_format.other, keyModifier | macVirtualKey, &keyboard_dead);
- if (translatedChar) {
- static QTextCodec *c = 0;
- if (!c)
- c = QTextCodec::codecForName("Apple Roman");
- const QChar unicode(c->toUnicode((const char *)&translatedChar, 1).at(0));
- int qtkey = qt_mac_get_key(keyModifier, unicode, macVirtualKey);
- if (qtkey == Qt::Key_unknown)
- qtkey = unicode.unicode();
- keyLayout[macVirtualKey]->qtKey[i] = qtkey;
- }
- }
-#endif
- }
-#ifdef DEBUG_KEY_MAPS
- qDebug("updateKeyMap for virtual key = 0x%02x!", (uint)macVirtualKey);
- for (int i = 0; i < 16; ++i) {
- qDebug(" [%d] (%d,0x%02x,'%c')", i,
- keyLayout[macVirtualKey]->qtKey[i],
- keyLayout[macVirtualKey]->qtKey[i],
- keyLayout[macVirtualKey]->qtKey[i]);
- }
-#endif
-}
-
-bool
-QKeyMapper::sendKeyEvent(QWidget *widget, bool grab,
- QEvent::Type type, int code, Qt::KeyboardModifiers modifiers,
- const QString &text, bool autorepeat, int count,
- quint32 nativeScanCode, quint32 nativeVirtualKey,
- quint32 nativeModifiers, bool *isAccepted)
-{
- Q_UNUSED(count);
- if (widget && widget->isEnabled()) {
- bool key_event = true;
-#if defined(QT3_SUPPORT) && !defined(QT_NO_SHORTCUT)
- if (type == QEvent::KeyPress && !grab
- && QApplicationPrivate::instance()->use_compat()) {
- QKeyEventEx accel_ev(type, code, modifiers,
- text, autorepeat, qMax(1, int(text.length())),
- nativeScanCode, nativeVirtualKey, nativeModifiers);
- if (QApplicationPrivate::instance()->qt_tryAccelEvent(widget, &accel_ev)) {
-#if defined(DEBUG_KEY_BINDINGS) || defined(DEBUG_KEY_BINDINGS_MODIFIERS)
- qDebug("KeyEvent: %s::%s consumed Accel: %s",
- widget ? widget->metaObject()->className() : "none",
- widget ? widget->objectName().toLatin1().constData() : "",
- text.toLatin1().constData());
-#endif
- key_event = false;
- } else {
- if (accel_ev.isAccepted()) {
-#if defined(DEBUG_KEY_BINDINGS) || defined(DEBUG_KEY_BINDINGS_MODIFIERS)
- qDebug("KeyEvent: %s::%s overrode Accel: %s",
- widget ? widget->metaObject()->className() : "none",
- widget ? widget->objectName().toLatin1().constData() : "",
- text.toLatin1().constData());
-#endif
- }
- }
- }
-#else
-Q_UNUSED(grab);
-#endif // QT3_SUPPORT && !QT_NO_SHORTCUT
- if (key_event) {
-#if defined(DEBUG_KEY_BINDINGS) || defined(DEBUG_KEY_BINDINGS_MODIFIERS)
- qDebug("KeyEvent: Sending %s to %s::%s: %s 0x%08x%s",
- type == QEvent::KeyRelease ? "KeyRelease" : "KeyPress",
- widget ? widget->metaObject()->className() : "none",
- widget ? widget->objectName().toLatin1().constData() : "",
- text.toLatin1().constData(), int(modifiers),
- autorepeat ? " Repeat" : "");
-#endif
- QKeyEventEx ke(type, code, modifiers, text, autorepeat, qMax(1, text.length()),
- nativeScanCode, nativeVirtualKey, nativeModifiers);
- bool retMe = qt_sendSpontaneousEvent(widget,&ke);
- if (isAccepted)
- *isAccepted = ke.isAccepted();
- return retMe;
- }
- }
- return false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qmacdefines_mac.h b/src/gui/platforms/mac/qmacdefines_mac.h
deleted file mode 100644
index d6ccb93593..0000000000
--- a/src/gui/platforms/mac/qmacdefines_mac.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/****************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-/*
- * qmacdefines_mac_p.h
- * All the defines you'll ever need for Qt/Mac :-)
- */
-
-/* This is just many defines. Therefore it doesn't need things like:
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-Yes, it is an informative comment ;-)
-*/
-
-#include <QtCore/qglobal.h>
-
-#ifdef qDebug
-# define old_qDebug qDebug
-# undef qDebug
-#endif
-
-#ifdef __LP64__
-typedef signed int OSStatus;
-#else
-typedef signed long OSStatus;
-#endif
-
-#ifdef __OBJC__
-# ifdef slots
-# define old_slots slots
-# undef slots
-# endif
-#include <Cocoa/Cocoa.h>
-# ifdef old_slots
-# undef slots
-# define slots
-# undef old_slots
-# endif
-#endif
-#ifdef QT_MAC_USE_COCOA
- typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
- typedef struct OpaqueEventRef * EventRef;
- typedef struct OpaqueMenuRef * MenuRef;
- typedef struct OpaquePasteboardRef* PasteboardRef;
- typedef struct OpaqueRgnHandle * RgnHandle;
- typedef const struct __HIShape *HIShapeRef;
- typedef struct __HIShape *HIMutableShapeRef;
- typedef struct CGRect CGRect;
- typedef struct CGImage *CGImageRef;
- typedef struct CGContext *CGContextRef;
- typedef struct GDevice * GDPtr;
- typedef GDPtr * GDHandle;
- typedef struct OpaqueIconRef * IconRef;
-# ifdef __OBJC__
- typedef NSWindow* OSWindowRef;
- typedef NSView *OSViewRef;
- typedef NSMenu *OSMenuRef;
- typedef NSEvent *OSEventRef;
-# else
- typedef void *OSWindowRef;
- typedef void *OSViewRef;
- typedef void *OSMenuRef;
- typedef void *OSEventRef;
-# endif
-#else // Carbon
- typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
- typedef struct OpaqueEventRef * EventRef;
- typedef struct OpaqueMenuRef * MenuRef;
- typedef struct OpaquePasteboardRef* PasteboardRef;
- typedef struct OpaqueRgnHandle * RgnHandle;
- typedef const struct __HIShape *HIShapeRef;
- typedef struct __HIShape *HIMutableShapeRef;
- typedef struct CGRect CGRect;
- typedef struct CGImage *CGImageRef;
- typedef struct CGContext *CGContextRef;
- typedef struct GDevice * GDPtr;
- typedef GDPtr * GDHandle;
- typedef struct OpaqueIconRef * IconRef;
- typedef struct OpaqueWindowPtr * WindowRef;
- typedef struct OpaqueControlRef * HIViewRef;
- typedef WindowRef OSWindowRef;
- typedef HIViewRef OSViewRef;
- typedef MenuRef OSMenuRef;
- typedef EventRef OSEventRef;
-#endif // QT_MAC_USE_COCOA
-
-typedef PasteboardRef OSPasteboardRef;
-typedef struct AEDesc AEDescList;
-typedef AEDescList AERecord;
-typedef AERecord AppleEvent;
-
-#ifdef check
-#undef check
-#endif
-
-#ifdef old_qDebug
-# undef qDebug
-# define qDebug QT_NO_QDEBUG_MACRO
-# undef old_qDebug
-#endif
diff --git a/src/gui/platforms/mac/qmacgesturerecognizer_mac.mm b/src/gui/platforms/mac/qmacgesturerecognizer_mac.mm
deleted file mode 100644
index 6a4f0bb445..0000000000
--- a/src/gui/platforms/mac/qmacgesturerecognizer_mac.mm
+++ /dev/null
@@ -1,272 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmacgesturerecognizer_mac_p.h"
-#include "qgesture.h"
-#include "qgesture_p.h"
-#include "qevent.h"
-#include "qevent_p.h"
-#include "qwidget.h"
-#include "qdebug.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-QMacSwipeGestureRecognizer::QMacSwipeGestureRecognizer()
-{
-}
-
-QGesture *QMacSwipeGestureRecognizer::create(QObject * /*target*/)
-{
- return new QSwipeGesture;
-}
-
-QGestureRecognizer::Result
-QMacSwipeGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *event)
-{
- if (event->type() == QEvent::NativeGesture && obj->isWidgetType()) {
- QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event);
- switch (ev->gestureType) {
- case QNativeGestureEvent::Swipe: {
- QSwipeGesture *g = static_cast<QSwipeGesture *>(gesture);
- g->setSwipeAngle(ev->angle);
- g->setHotSpot(ev->position);
- return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
- break; }
- default:
- break;
- }
- }
-
- return QGestureRecognizer::Ignore;
-}
-
-void QMacSwipeGestureRecognizer::reset(QGesture *gesture)
-{
- QSwipeGesture *g = static_cast<QSwipeGesture *>(gesture);
- g->setSwipeAngle(0);
- QGestureRecognizer::reset(gesture);
-}
-
-////////////////////////////////////////////////////////////////////////
-
-QMacPinchGestureRecognizer::QMacPinchGestureRecognizer()
-{
-}
-
-QGesture *QMacPinchGestureRecognizer::create(QObject * /*target*/)
-{
- return new QPinchGesture;
-}
-
-QGestureRecognizer::Result
-QMacPinchGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *event)
-{
- if (event->type() == QEvent::NativeGesture && obj->isWidgetType()) {
- QPinchGesture *g = static_cast<QPinchGesture *>(gesture);
- QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event);
- switch(ev->gestureType) {
- case QNativeGestureEvent::GestureBegin:
- reset(gesture);
- g->setStartCenterPoint(static_cast<QWidget*>(obj)->mapFromGlobal(ev->position));
- g->setCenterPoint(g->startCenterPoint());
- g->setChangeFlags(QPinchGesture::CenterPointChanged);
- g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->position);
- return QGestureRecognizer::MayBeGesture | QGestureRecognizer::ConsumeEventHint;
- case QNativeGestureEvent::Rotate: {
- g->setLastScaleFactor(g->scaleFactor());
- g->setLastRotationAngle(g->rotationAngle());
- g->setRotationAngle(g->rotationAngle() + ev->percentage);
- g->setChangeFlags(QPinchGesture::RotationAngleChanged);
- g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->position);
- return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
- }
- case QNativeGestureEvent::Zoom:
- g->setLastScaleFactor(g->scaleFactor());
- g->setLastRotationAngle(g->rotationAngle());
- g->setScaleFactor(g->scaleFactor() * (1 + ev->percentage));
- g->setChangeFlags(QPinchGesture::ScaleFactorChanged);
- g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
- g->setHotSpot(ev->position);
- return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
- case QNativeGestureEvent::GestureEnd:
- return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
- default:
- break;
- }
- }
-
- return QGestureRecognizer::Ignore;
-}
-
-void QMacPinchGestureRecognizer::reset(QGesture *gesture)
-{
- QPinchGesture *g = static_cast<QPinchGesture *>(gesture);
- g->setChangeFlags(0);
- g->setTotalChangeFlags(0);
- g->setScaleFactor(1.0f);
- g->setTotalScaleFactor(1.0f);
- g->setLastScaleFactor(1.0f);
- g->setRotationAngle(0.0f);
- g->setTotalRotationAngle(0.0f);
- g->setLastRotationAngle(0.0f);
- g->setCenterPoint(QPointF());
- g->setStartCenterPoint(QPointF());
- g->setLastCenterPoint(QPointF());
- QGestureRecognizer::reset(gesture);
-}
-
-////////////////////////////////////////////////////////////////////////
-
-#if defined(QT_MAC_USE_COCOA)
-
-QMacPanGestureRecognizer::QMacPanGestureRecognizer() : _panCanceled(true)
-{
-}
-
-QGesture *QMacPanGestureRecognizer::create(QObject *target)
-{
- if (!target)
- return new QPanGesture;
-
- if (QWidget *w = qobject_cast<QWidget *>(target)) {
- w->setAttribute(Qt::WA_AcceptTouchEvents);
- w->setAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
- return new QPanGesture;
- }
- return 0;
-}
-
-QGestureRecognizer::Result
-QMacPanGestureRecognizer::recognize(QGesture *gesture, QObject *target, QEvent *event)
-{
- const int panBeginDelay = 300;
- const int panBeginRadius = 3;
-
- QPanGesture *g = static_cast<QPanGesture *>(gesture);
-
- switch (event->type()) {
- case QEvent::TouchBegin: {
- const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
- if (ev->touchPoints().size() == 1) {
- reset(gesture);
- _startPos = QCursor::pos();
- _panTimer.start(panBeginDelay, target);
- _panCanceled = false;
- return QGestureRecognizer::MayBeGesture;
- }
- break;}
- case QEvent::TouchEnd: {
- if (_panCanceled)
- break;
-
- const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
- if (ev->touchPoints().size() == 1)
- return QGestureRecognizer::FinishGesture;
- break;}
- case QEvent::TouchUpdate: {
- if (_panCanceled)
- break;
-
- const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
- if (ev->touchPoints().size() == 1) {
- if (_panTimer.isActive()) {
- // INVARIANT: Still in maybeGesture. Check if the user
- // moved his finger so much that it makes sense to cancel the pan:
- const QPointF p = QCursor::pos();
- if ((p - _startPos).manhattanLength() > panBeginRadius) {
- _panCanceled = true;
- _panTimer.stop();
- return QGestureRecognizer::CancelGesture;
- }
- } else {
- const QPointF p = QCursor::pos();
- const QPointF posOffset = p - _startPos;
- g->setLastOffset(g->offset());
- g->setOffset(QPointF(posOffset.x(), posOffset.y()));
- g->setHotSpot(_startPos);
- return QGestureRecognizer::TriggerGesture;
- }
- } else if (_panTimer.isActive()) {
- // I only want to cancel the pan if the user is pressing
- // more than one finger, and the pan hasn't started yet:
- _panCanceled = true;
- _panTimer.stop();
- return QGestureRecognizer::CancelGesture;
- }
- break;}
- case QEvent::Timer: {
- QTimerEvent *ev = static_cast<QTimerEvent *>(event);
- if (ev->timerId() == _panTimer.timerId()) {
- _panTimer.stop();
- if (_panCanceled)
- break;
- // Begin new pan session!
- _startPos = QCursor::pos();
- g->setHotSpot(_startPos);
- return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
- }
- break; }
- default:
- break;
- }
-
- return QGestureRecognizer::Ignore;
-}
-
-void QMacPanGestureRecognizer::reset(QGesture *gesture)
-{
- QPanGesture *g = static_cast<QPanGesture *>(gesture);
- _startPos = QPointF();
- _panCanceled = true;
- g->setOffset(QPointF(0, 0));
- g->setLastOffset(QPointF(0, 0));
- g->setAcceleration(qreal(1));
- QGestureRecognizer::reset(gesture);
-}
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/platforms/mac/qmacgesturerecognizer_mac_p.h b/src/gui/platforms/mac/qmacgesturerecognizer_mac_p.h
deleted file mode 100644
index 465f6a2ac8..0000000000
--- a/src/gui/platforms/mac/qmacgesturerecognizer_mac_p.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** 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 QMACSWIPEGESTURERECOGNIZER_MAC_P_H
-#define QMACSWIPEGESTURERECOGNIZER_MAC_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 "qtimer.h"
-#include "qpoint.h"
-#include "qgesturerecognizer.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-class QMacSwipeGestureRecognizer : public QGestureRecognizer
-{
-public:
- QMacSwipeGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *gesture, QObject *watched, QEvent *event);
- void reset(QGesture *gesture);
-};
-
-class QMacPinchGestureRecognizer : public QGestureRecognizer
-{
-public:
- QMacPinchGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *gesture, QObject *watched, QEvent *event);
- void reset(QGesture *gesture);
-};
-
-#if defined(QT_MAC_USE_COCOA)
-
-class QMacPanGestureRecognizer : public QObject, public QGestureRecognizer
-{
-public:
- QMacPanGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *gesture, QObject *watched, QEvent *event);
- void reset(QGesture *gesture);
-private:
- QPointF _startPos;
- QBasicTimer _panTimer;
- bool _panCanceled;
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QMACSWIPEGESTURERECOGNIZER_MAC_P_H
diff --git a/src/gui/platforms/mac/qmime_mac.cpp b/src/gui/platforms/mac/qmime_mac.cpp
deleted file mode 100644
index d6f6222c23..0000000000
--- a/src/gui/platforms/mac/qmime_mac.cpp
+++ /dev/null
@@ -1,1310 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmime.h"
-
-//#define USE_INTERNET_CONFIG
-
-#ifndef USE_INTERNET_CONFIG
-# include "qfile.h"
-# include "qfileinfo.h"
-# include "qtextstream.h"
-# include "qdir.h"
-# include <unistd.h>
-# include <sys/types.h>
-# include <sys/stat.h>
-# include <sys/fcntl.h>
-#endif
-
-#include "qdebug.h"
-#include "qpixmap.h"
-#include "qimagewriter.h"
-#include "qimagereader.h"
-#include "qdatastream.h"
-#include "qbuffer.h"
-#include "qdatetime.h"
-#include "qapplication_p.h"
-#include "qtextcodec.h"
-#include "qregexp.h"
-#include "qurl.h"
-#include "qmap.h"
-#include <private/qt_mac_p.h>
-
-
-#ifdef Q_WS_MAC32
-#include <QuickTime/QuickTime.h>
-#include <qlibrary.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0); // qpaintengine_mac.cpp
-
-typedef QList<QMacPasteboardMime*> MimeList;
-Q_GLOBAL_STATIC(MimeList, globalMimeList)
-
-static void cleanup_mimes()
-{
- MimeList *mimes = globalMimeList();
- while (!mimes->isEmpty())
- delete mimes->takeFirst();
-}
-
-Q_GLOBAL_STATIC(QStringList, globalDraggedTypesList)
-
-/*!
- \fn void qRegisterDraggedTypes(const QStringList &types)
- \relates QMacPasteboardMime
-
- Registers the given \a types as custom pasteboard types.
-
- This function should be called to enable the Drag and Drop events
- for custom pasteboard types on Cocoa implementations. This is required
- in addition to a QMacPasteboardMime subclass implementation. By default
- drag and drop is enabled for all standard pasteboard types.
-
- \sa QMacPasteboardMime
-*/
-Q_GUI_EXPORT void qRegisterDraggedTypes(const QStringList &types)
-{
- (*globalDraggedTypesList()) += types;
-}
-
-const QStringList& qEnabledDraggedTypes()
-{
- return (*globalDraggedTypesList());
-}
-
-
-/*****************************************************************************
- QDnD debug facilities
- *****************************************************************************/
-//#define DEBUG_MIME_MAPS
-
-//functions
-extern QString qt_mac_from_pascal_string(const Str255); //qglobal.cpp
-extern void qt_mac_from_pascal_string(QString, Str255, TextEncoding encoding=0, int len=-1); //qglobal.cpp
-
-ScrapFlavorType qt_mac_mime_type = 'CUTE';
-CFStringRef qt_mac_mime_typeUTI = CFSTR("com.pasteboard.trolltech.marker");
-
-/*!
- \class QMacPasteboardMime
- \brief The QMacPasteboardMime class converts between a MIME type and a
- \l{http://developer.apple.com/macosx/uniformtypeidentifiers.html}{Uniform
- Type Identifier (UTI)} format.
- \since 4.2
-
- \ingroup draganddrop
-
- Qt's drag and drop and clipboard facilities use the MIME
- standard. On X11, this maps trivially to the Xdnd protocol. On
- Mac, although some applications use MIME to describe clipboard
- contents, it is more common to use Apple's UTI format.
-
- QMacPasteboardMime's role is to bridge the gap between MIME and UTI;
- By subclasses this class, one can extend Qt's drag and drop
- and clipboard handling to convert to and from unsupported, or proprietary, UTI formats.
-
- A subclass of QMacPasteboardMime will automatically be registered, and active, upon instantiation.
-
- Qt has predefined support for the following UTIs:
- \list
- \i public.utf8-plain-text - converts to "text/plain"
- \i public.utf16-plain-text - converts to "text/plain"
- \i public.html - converts to "text/html"
- \i public.url - converts to "text/uri-list"
- \i public.file-url - converts to "text/uri-list"
- \i public.tiff - converts to "application/x-qt-image"
- \i public.vcard - converts to "text/plain"
- \i com.apple.traditional-mac-plain-text - converts to "text/plain"
- \i com.apple.pict - converts to "application/x-qt-image"
- \endlist
-
- When working with MIME data, Qt will interate through all instances of QMacPasteboardMime to
- find an instance that can convert to, or from, a specific MIME type. It will do this by calling
- canConvert() on each instance, starting with (and choosing) the last created instance first.
- The actual conversions will be done by using convertToMime() and convertFromMime().
-
- \note The API uses the term "flavor" in some cases. This is for backwards
- compatibility reasons, and should now be understood as UTIs.
-*/
-
-/*! \enum QMacPasteboardMime::QMacPasteboardMimeType
- \internal
-*/
-
-/*!
- Constructs a new conversion object of type \a t, adding it to the
- globally accessed list of available convertors.
-*/
-QMacPasteboardMime::QMacPasteboardMime(char t) : type(t)
-{
- globalMimeList()->append(this);
-}
-
-/*!
- Destroys a conversion object, removing it from the global
- list of available convertors.
-*/
-QMacPasteboardMime::~QMacPasteboardMime()
-{
- if(!QApplication::closingDown())
- globalMimeList()->removeAll(this);
-}
-
-class QMacPasteboardMimeAny : public QMacPasteboardMime {
-private:
-
-public:
- QMacPasteboardMimeAny() : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL) {
- }
- ~QMacPasteboardMimeAny() {
- }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeAny::convertorName()
-{
- return QLatin1String("Any-Mime");
-}
-
-QString QMacPasteboardMimeAny::flavorFor(const QString &mime)
-{
- // do not handle the mime type name in the drag pasteboard
- if(mime == QLatin1String("application/x-qt-mime-type-name"))
- return QString();
- QString ret = QLatin1String("com.trolltech.anymime.") + mime;
- return ret.replace(QLatin1Char('/'), QLatin1String("--"));
-}
-
-QString QMacPasteboardMimeAny::mimeFor(QString flav)
-{
- const QString any_prefix = QLatin1String("com.trolltech.anymime.");
- if(flav.size() > any_prefix.length() && flav.startsWith(any_prefix))
- return flav.mid(any_prefix.length()).replace(QLatin1String("--"), QLatin1String("/"));
- return QString();
-}
-
-bool QMacPasteboardMimeAny::canConvert(const QString &mime, QString flav)
-{
- return mimeFor(flav) == mime;
-}
-
-QVariant QMacPasteboardMimeAny::convertToMime(const QString &mime, QList<QByteArray> data, QString)
-{
- if(data.count() > 1)
- qWarning("QMacPasteboardMimeAny: Cannot handle multiple member data");
- QVariant ret;
- if (mime == QLatin1String("text/plain"))
- ret = QString::fromUtf8(data.first());
- else
- ret = data.first();
- return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimeAny::convertFromMime(const QString &mime, QVariant data, QString)
-{
- QList<QByteArray> ret;
- if (mime == QLatin1String("text/plain"))
- ret.append(data.toString().toUtf8());
- else
- ret.append(data.toByteArray());
- return ret;
-}
-
-class QMacPasteboardMimeTypeName : public QMacPasteboardMime {
-private:
-
-public:
- QMacPasteboardMimeTypeName() : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL) {
- }
- ~QMacPasteboardMimeTypeName() {
- }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeTypeName::convertorName()
-{
- return QLatin1String("Qt-Mime-Type");
-}
-
-QString QMacPasteboardMimeTypeName::flavorFor(const QString &mime)
-{
- if(mime == QLatin1String("application/x-qt-mime-type-name"))
- return QLatin1String("com.trolltech.qt.MimeTypeName");
- return QString();
-}
-
-QString QMacPasteboardMimeTypeName::mimeFor(QString)
-{
- return QString();
-}
-
-bool QMacPasteboardMimeTypeName::canConvert(const QString &, QString)
-{
- return false;
-}
-
-QVariant QMacPasteboardMimeTypeName::convertToMime(const QString &, QList<QByteArray>, QString)
-{
- QVariant ret;
- return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimeTypeName::convertFromMime(const QString &, QVariant, QString)
-{
- QList<QByteArray> ret;
- ret.append(QString("x-qt-mime-type-name").toUtf8());
- return ret;
-}
-
-class QMacPasteboardMimePlainText : public QMacPasteboardMime {
-public:
- QMacPasteboardMimePlainText() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimePlainText::convertorName()
-{
- return QLatin1String("PlainText");
-}
-
-QString QMacPasteboardMimePlainText::flavorFor(const QString &mime)
-{
- if (mime == QLatin1String("text/plain"))
- return QLatin1String("com.apple.traditional-mac-plain-text");
- return QString();
-}
-
-QString QMacPasteboardMimePlainText::mimeFor(QString flav)
-{
- if (flav == QLatin1String("com.apple.traditional-mac-plain-text"))
- return QLatin1String("text/plain");
- return QString();
-}
-
-bool QMacPasteboardMimePlainText::canConvert(const QString &mime, QString flav)
-{
- return flavorFor(mime) == flav;
-}
-
-QVariant QMacPasteboardMimePlainText::convertToMime(const QString &mimetype, QList<QByteArray> data, QString flavor)
-{
- if(data.count() > 1)
- qWarning("QMacPasteboardMimePlainText: Cannot handle multiple member data");
- const QByteArray &firstData = data.first();
- QVariant ret;
- if(flavor == QCFString(QLatin1String("com.apple.traditional-mac-plain-text"))) {
- QCFString str(CFStringCreateWithBytes(kCFAllocatorDefault,
- reinterpret_cast<const UInt8 *>(firstData.constData()),
- firstData.size(), CFStringGetSystemEncoding(), false));
- ret = QString(str);
- } else {
- qWarning("QMime::convertToMime: unhandled mimetype: %s", qPrintable(mimetype));
- }
- return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimePlainText::convertFromMime(const QString &, QVariant data, QString flavor)
-{
- QList<QByteArray> ret;
- QString string = data.toString();
- if(flavor == QCFString(QLatin1String("com.apple.traditional-mac-plain-text")))
- ret.append(string.toLatin1());
- return ret;
-}
-
-class QMacPasteboardMimeUnicodeText : public QMacPasteboardMime {
-public:
- QMacPasteboardMimeUnicodeText() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeUnicodeText::convertorName()
-{
- return QLatin1String("UnicodeText");
-}
-
-QString QMacPasteboardMimeUnicodeText::flavorFor(const QString &mime)
-{
- if (mime == QLatin1String("text/plain"))
- return QLatin1String("public.utf16-plain-text");
- int i = mime.indexOf(QLatin1String("charset="));
- if (i >= 0) {
- QString cs(mime.mid(i+8).toLower());
- i = cs.indexOf(QLatin1Char(';'));
- if (i>=0)
- cs = cs.left(i);
- if (cs == QLatin1String("system"))
- return QLatin1String("public.utf8-plain-text");
- else if (cs == QLatin1String("iso-10646-ucs-2")
- || cs == QLatin1String("utf16"))
- return QLatin1String("public.utf16-plain-text");
- }
- return QString();
-}
-
-QString QMacPasteboardMimeUnicodeText::mimeFor(QString flav)
-{
- if (flav == QLatin1String("public.utf16-plain-text") || flav == QLatin1String("public.utf8-plain-text"))
- return QLatin1String("text/plain");
- return QString();
-}
-
-bool QMacPasteboardMimeUnicodeText::canConvert(const QString &mime, QString flav)
-{
- return flavorFor(mime) == flav;
-}
-
-QVariant QMacPasteboardMimeUnicodeText::convertToMime(const QString &mimetype, QList<QByteArray> data, QString flavor)
-{
- if(data.count() > 1)
- qWarning("QMacPasteboardMimeUnicodeText: Cannot handle multiple member data");
- const QByteArray &firstData = data.first();
- // I can only handle two types (system and unicode) so deal with them that way
- QVariant ret;
- if(flavor == QLatin1String("public.utf8-plain-text")) {
- QCFString str(CFStringCreateWithBytes(kCFAllocatorDefault,
- reinterpret_cast<const UInt8 *>(firstData.constData()),
- firstData.size(), CFStringGetSystemEncoding(), false));
- ret = QString(str);
- } else if (flavor == QLatin1String("public.utf16-plain-text")) {
- ret = QString(reinterpret_cast<const QChar *>(firstData.constData()),
- firstData.size() / sizeof(QChar));
- } else {
- qWarning("QMime::convertToMime: unhandled mimetype: %s", qPrintable(mimetype));
- }
- return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimeUnicodeText::convertFromMime(const QString &, QVariant data, QString flavor)
-{
- QList<QByteArray> ret;
- QString string = data.toString();
- if(flavor == QLatin1String("public.utf8-plain-text"))
- ret.append(string.toUtf8());
- else if (flavor == QLatin1String("public.utf16-plain-text"))
- ret.append(QByteArray((char*)string.utf16(), string.length()*2));
- return ret;
-}
-
-class QMacPasteboardMimeHTMLText : public QMacPasteboardMime {
-public:
- QMacPasteboardMimeHTMLText() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeHTMLText::convertorName()
-{
- return QLatin1String("HTML");
-}
-
-QString QMacPasteboardMimeHTMLText::flavorFor(const QString &mime)
-{
- if (mime == QLatin1String("text/html"))
- return QLatin1String("public.html");
- return QString();
-}
-
-QString QMacPasteboardMimeHTMLText::mimeFor(QString flav)
-{
- if (flav == QLatin1String("public.html"))
- return QLatin1String("text/html");
- return QString();
-}
-
-bool QMacPasteboardMimeHTMLText::canConvert(const QString &mime, QString flav)
-{
- return flavorFor(mime) == flav;
-}
-
-QVariant QMacPasteboardMimeHTMLText::convertToMime(const QString &mimeType, QList<QByteArray> data, QString flavor)
-{
- if (!canConvert(mimeType, flavor))
- return QVariant();
- if (data.count() > 1)
- qWarning("QMacPasteboardMimeHTMLText: Cannot handle multiple member data");
- return data.first();
-}
-
-QList<QByteArray> QMacPasteboardMimeHTMLText::convertFromMime(const QString &mime, QVariant data, QString flavor)
-{
- QList<QByteArray> ret;
- if (!canConvert(mime, flavor))
- return ret;
- ret.append(data.toByteArray());
- return ret;
-}
-
-
-#ifdef Q_WS_MAC32
-
-// This can be removed once 10.6 is the minimum (or we have to require 64-bit) whichever comes first.
-
-typedef ComponentResult (*PtrGraphicsImportSetDataHandle)(GraphicsImportComponent, Handle);
-typedef ComponentResult (*PtrGraphicsImportCreateCGImage)(GraphicsImportComponent, CGImageRef*, UInt32);
-typedef ComponentResult (*PtrGraphicsExportSetInputCGImage)(GraphicsExportComponent, CGImageRef);
-typedef ComponentResult (*PtrGraphicsExportSetOutputHandle)(GraphicsExportComponent, Handle);
-typedef ComponentResult (*PtrGraphicsExportDoExport)(GraphicsExportComponent, unsigned long *);
-
-static PtrGraphicsImportSetDataHandle ptrGraphicsImportSetDataHandle = 0;
-static PtrGraphicsImportCreateCGImage ptrGraphicsImportCreateCGImage = 0;
-static PtrGraphicsExportSetInputCGImage ptrGraphicsExportSetInputCGImage = 0;
-static PtrGraphicsExportSetOutputHandle ptrGraphicsExportSetOutputHandle = 0;
-static PtrGraphicsExportDoExport ptrGraphicsExportDoExport = 0;
-
-static bool resolveMimeQuickTimeSymbols()
-{
- if (ptrGraphicsImportSetDataHandle == 0) {
- QLibrary library(QLatin1String("/System/Library/Frameworks/QuickTime.framework/QuickTime"));
- ptrGraphicsImportSetDataHandle = reinterpret_cast<PtrGraphicsImportSetDataHandle>(library.resolve("GraphicsImportSetDataHandle"));
- ptrGraphicsImportCreateCGImage = reinterpret_cast<PtrGraphicsImportCreateCGImage>(library.resolve("GraphicsImportCreateCGImage"));
- ptrGraphicsExportSetInputCGImage = reinterpret_cast<PtrGraphicsExportSetInputCGImage>(library.resolve("GraphicsExportSetInputCGImage"));
- ptrGraphicsExportSetOutputHandle = reinterpret_cast<PtrGraphicsExportSetOutputHandle>(library.resolve("GraphicsExportSetOutputHandle"));
- ptrGraphicsExportDoExport = reinterpret_cast<PtrGraphicsExportDoExport>(library.resolve("GraphicsExportDoExport"));
- }
-
- return ptrGraphicsImportSetDataHandle != 0
- && ptrGraphicsImportCreateCGImage != 0 && ptrGraphicsExportSetInputCGImage != 0
- && ptrGraphicsExportSetOutputHandle != 0 && ptrGraphicsExportDoExport != 0;
-}
-
-class QMacPasteboardMimePict : public QMacPasteboardMime {
-public:
- QMacPasteboardMimePict() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimePict::convertorName()
-{
- return QLatin1String("Pict");
-}
-
-QString QMacPasteboardMimePict::flavorFor(const QString &mime)
-{
- if(mime.startsWith(QLatin1String("application/x-qt-image")))
- return QLatin1String("com.apple.pict");
- return QString();
-}
-
-QString QMacPasteboardMimePict::mimeFor(QString flav)
-{
- if(flav == QLatin1String("com.apple.pict"))
- return QLatin1String("application/x-qt-image");
- return QString();
-}
-
-bool QMacPasteboardMimePict::canConvert(const QString &mime, QString flav)
-{
- return flav == QLatin1String("com.apple.pict")
- && mime == QLatin1String("application/x-qt-image");
-}
-
-
-QVariant QMacPasteboardMimePict::convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
-{
- if(data.count() > 1)
- qWarning("QMacPasteboardMimePict: Cannot handle multiple member data");
- QVariant ret;
- if (!resolveMimeQuickTimeSymbols())
- return ret;
-
- if(!canConvert(mime, flav))
- return ret;
- const QByteArray &a = data.first();
-
- // This function expects the 512 header (just to skip it, so create the extra space for it).
- Handle pic = NewHandle(a.size() + 512);
- memcpy(*pic + 512, a.constData(), a.size());
-
- GraphicsImportComponent graphicsImporter;
- ComponentResult result = OpenADefaultComponent(GraphicsImporterComponentType,
- kQTFileTypePicture, &graphicsImporter);
- QCFType<CGImageRef> cgImage;
- if (!result)
- result = ptrGraphicsImportSetDataHandle(graphicsImporter, pic);
- if (!result)
- result = ptrGraphicsImportCreateCGImage(graphicsImporter, &cgImage,
- kGraphicsImportCreateCGImageUsingCurrentSettings);
- if (!result)
- ret = QVariant(QPixmap::fromMacCGImageRef(cgImage).toImage());
- CloseComponent(graphicsImporter);
- DisposeHandle(pic);
- return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimePict::convertFromMime(const QString &mime, QVariant variant,
- QString flav)
-{
- QList<QByteArray> ret;
- if (!resolveMimeQuickTimeSymbols())
- return ret;
-
- if (!canConvert(mime, flav))
- return ret;
- QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(qvariant_cast<QImage>(variant));
- Handle pic = NewHandle(0);
- GraphicsExportComponent graphicsExporter;
- ComponentResult result = OpenADefaultComponent(GraphicsExporterComponentType,
- kQTFileTypePicture, &graphicsExporter);
- if (!result) {
- unsigned long sizeWritten;
- result = ptrGraphicsExportSetInputCGImage(graphicsExporter, cgimage);
- if (!result)
- result = ptrGraphicsExportSetOutputHandle(graphicsExporter, pic);
- if (!result)
- result = ptrGraphicsExportDoExport(graphicsExporter, &sizeWritten);
-
- CloseComponent(graphicsExporter);
- }
-
- int size = GetHandleSize((Handle)pic);
- // Skip the Picture File header (512 bytes) and feed the raw data
- QByteArray ar(reinterpret_cast<char *>(*pic + 512), size - 512);
- ret.append(ar);
- DisposeHandle(pic);
- return ret;
-}
-
-
-#endif //Q_WS_MAC32
-
-class QMacPasteboardMimeTiff : public QMacPasteboardMime {
-public:
- QMacPasteboardMimeTiff() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeTiff::convertorName()
-{
- return QLatin1String("Tiff");
-}
-
-QString QMacPasteboardMimeTiff::flavorFor(const QString &mime)
-{
- if(mime.startsWith(QLatin1String("application/x-qt-image")))
- return QLatin1String("public.tiff");
- return QString();
-}
-
-QString QMacPasteboardMimeTiff::mimeFor(QString flav)
-{
- if(flav == QLatin1String("public.tiff"))
- return QLatin1String("application/x-qt-image");
- return QString();
-}
-
-bool QMacPasteboardMimeTiff::canConvert(const QString &mime, QString flav)
-{
- return flav == QLatin1String("public.tiff") && mime == QLatin1String("application/x-qt-image");
-}
-
-QVariant QMacPasteboardMimeTiff::convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
-{
- if(data.count() > 1)
- qWarning("QMacPasteboardMimeTiff: Cannot handle multiple member data");
- QVariant ret;
- if (!canConvert(mime, flav))
- return ret;
- const QByteArray &a = data.first();
- QCFType<CGImageRef> image;
- QCFType<CFDataRef> tiffData = CFDataCreateWithBytesNoCopy(0,
- reinterpret_cast<const UInt8 *>(a.constData()),
- a.size(), kCFAllocatorNull);
- QCFType<CGImageSourceRef> imageSource = CGImageSourceCreateWithData(tiffData, 0);
- image = CGImageSourceCreateImageAtIndex(imageSource, 0, 0);
-
- if (image != 0)
- ret = QVariant(QPixmap::fromMacCGImageRef(image).toImage());
- return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimeTiff::convertFromMime(const QString &mime, QVariant variant, QString flav)
-{
- QList<QByteArray> ret;
- if (!canConvert(mime, flav))
- return ret;
-
- QImage img = qvariant_cast<QImage>(variant);
- QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(img);
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
- QCFType<CFMutableDataRef> data = CFDataCreateMutable(0, 0);
- QCFType<CGImageDestinationRef> imageDestination = CGImageDestinationCreateWithData(data, kUTTypeTIFF, 1, 0);
- if (imageDestination != 0) {
- CFTypeRef keys[2];
- QCFType<CFTypeRef> values[2];
- QCFType<CFDictionaryRef> options;
- keys[0] = kCGImagePropertyPixelWidth;
- keys[1] = kCGImagePropertyPixelHeight;
- int width = img.width();
- int height = img.height();
- values[0] = CFNumberCreate(0, kCFNumberIntType, &width);
- values[1] = CFNumberCreate(0, kCFNumberIntType, &height);
- options = CFDictionaryCreate(0, reinterpret_cast<const void **>(keys),
- reinterpret_cast<const void **>(values), 2,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- CGImageDestinationAddImage(imageDestination, cgimage, options);
- CGImageDestinationFinalize(imageDestination);
- }
- QByteArray ar(CFDataGetLength(data), 0);
- CFDataGetBytes(data,
- CFRangeMake(0, ar.size()),
- reinterpret_cast<UInt8 *>(ar.data()));
- ret.append(ar);
- } else
-#endif
- {
-#ifdef Q_WS_MAC32
- Handle tiff = NewHandle(0);
- if (resolveMimeQuickTimeSymbols()) {
- GraphicsExportComponent graphicsExporter;
- ComponentResult result = OpenADefaultComponent(GraphicsExporterComponentType,
- kQTFileTypeTIFF, &graphicsExporter);
- if (!result) {
- unsigned long sizeWritten;
- result = ptrGraphicsExportSetInputCGImage(graphicsExporter, cgimage);
- if (!result)
- result = ptrGraphicsExportSetOutputHandle(graphicsExporter, tiff);
- if (!result)
- result = ptrGraphicsExportDoExport(graphicsExporter, &sizeWritten);
-
- CloseComponent(graphicsExporter);
- }
- }
- int size = GetHandleSize((Handle)tiff);
- QByteArray ar(reinterpret_cast<char *>(*tiff), size);
- ret.append(ar);
- DisposeHandle(tiff);
-#endif
- }
- return ret;
-}
-
-
-class QMacPasteboardMimeFileUri : public QMacPasteboardMime {
-public:
- QMacPasteboardMimeFileUri() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeFileUri::convertorName()
-{
- return QLatin1String("FileURL");
-}
-
-QString QMacPasteboardMimeFileUri::flavorFor(const QString &mime)
-{
- if (mime == QLatin1String("text/uri-list"))
- return QCFString(UTTypeCreatePreferredIdentifierForTag(kUTTagClassOSType, CFSTR("furl"), 0));
- return QString();
-}
-
-QString QMacPasteboardMimeFileUri::mimeFor(QString flav)
-{
- if (flav == QCFString(UTTypeCreatePreferredIdentifierForTag(kUTTagClassOSType, CFSTR("furl"), 0)))
- return QLatin1String("text/uri-list");
- return QString();
-}
-
-bool QMacPasteboardMimeFileUri::canConvert(const QString &mime, QString flav)
-{
- return mime == QLatin1String("text/uri-list")
- && flav == QCFString(UTTypeCreatePreferredIdentifierForTag(kUTTagClassOSType, CFSTR("furl"), 0));
-}
-
-QVariant QMacPasteboardMimeFileUri::convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
-{
- if(!canConvert(mime, flav))
- return QVariant();
- QList<QVariant> ret;
- for(int i = 0; i < data.size(); ++i) {
- QUrl url = QUrl::fromEncoded(data.at(i));
- if (url.host().toLower() == QLatin1String("localhost"))
- url.setHost(QString());
- url.setPath(url.path().normalized(QString::NormalizationForm_C));
- ret.append(url);
- }
- return QVariant(ret);
-}
-
-QList<QByteArray> QMacPasteboardMimeFileUri::convertFromMime(const QString &mime, QVariant data, QString flav)
-{
- QList<QByteArray> ret;
- if (!canConvert(mime, flav))
- return ret;
- QList<QVariant> urls = data.toList();
- for(int i = 0; i < urls.size(); ++i) {
- QUrl url = urls.at(i).toUrl();
- if (url.scheme().isEmpty())
- url.setScheme(QLatin1String("file"));
- if (url.scheme().toLower() == QLatin1String("file")) {
- if (url.host().isEmpty())
- url.setHost(QLatin1String("localhost"));
- url.setPath(url.path().normalized(QString::NormalizationForm_D));
- }
- ret.append(url.toEncoded());
- }
- return ret;
-}
-
-class QMacPasteboardMimeUrl : public QMacPasteboardMime {
-public:
- QMacPasteboardMimeUrl() : QMacPasteboardMime(MIME_ALL) { }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeUrl::convertorName()
-{
- return QLatin1String("URL");
-}
-
-QString QMacPasteboardMimeUrl::flavorFor(const QString &mime)
-{
- if(mime.startsWith(QLatin1String("text/uri-list")))
- return QLatin1String("public.url");
- return QString();
-}
-
-QString QMacPasteboardMimeUrl::mimeFor(QString flav)
-{
- if(flav == QLatin1String("public.url"))
- return QLatin1String("text/uri-list");
- return QString();
-}
-
-bool QMacPasteboardMimeUrl::canConvert(const QString &mime, QString flav)
-{
- return flav == QLatin1String("public.url")
- && mime == QLatin1String("text/uri-list");
-}
-
-QVariant QMacPasteboardMimeUrl::convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
-{
- if(!canConvert(mime, flav))
- return QVariant();
-
- QList<QVariant> ret;
- for (int i=0; i<data.size(); ++i) {
- QUrl url = QUrl::fromEncoded(data.at(i));
- if (url.host().toLower() == QLatin1String("localhost"))
- url.setHost(QString());
- url.setPath(url.path().normalized(QString::NormalizationForm_C));
- ret.append(url);
- }
- return QVariant(ret);
-}
-
-QList<QByteArray> QMacPasteboardMimeUrl::convertFromMime(const QString &mime, QVariant data, QString flav)
-{
- QList<QByteArray> ret;
- if (!canConvert(mime, flav))
- return ret;
-
- QList<QVariant> urls = data.toList();
- for(int i=0; i<urls.size(); ++i) {
- QUrl url = urls.at(i).toUrl();
- if (url.scheme().isEmpty())
- url.setScheme(QLatin1String("file"));
- if (url.scheme().toLower() == QLatin1String("file")) {
- if (url.host().isEmpty())
- url.setHost(QLatin1String("localhost"));
- url.setPath(url.path().normalized(QString::NormalizationForm_D));
- }
- ret.append(url.toEncoded());
- }
- return ret;
-}
-
-class QMacPasteboardMimeVCard : public QMacPasteboardMime
-{
-public:
- QMacPasteboardMimeVCard() : QMacPasteboardMime(MIME_ALL){ }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-QString QMacPasteboardMimeVCard::convertorName()
-{
- return QString("VCard");
-}
-
-bool QMacPasteboardMimeVCard::canConvert(const QString &mime, QString flav)
-{
- return mimeFor(flav) == mime;
-}
-
-QString QMacPasteboardMimeVCard::flavorFor(const QString &mime)
-{
- if(mime.startsWith(QLatin1String("text/plain")))
- return QLatin1String("public.vcard");
- return QString();
-}
-
-QString QMacPasteboardMimeVCard::mimeFor(QString flav)
-{
- if (flav == QLatin1String("public.vcard"))
- return QLatin1String("text/plain");
- return QString();
-}
-
-QVariant QMacPasteboardMimeVCard::convertToMime(const QString &mime, QList<QByteArray> data, QString)
-{
- QByteArray cards;
- if (mime == QLatin1String("text/plain")) {
- for (int i=0; i<data.size(); ++i)
- cards += data[i];
- }
- return QVariant(cards);
-}
-
-QList<QByteArray> QMacPasteboardMimeVCard::convertFromMime(const QString &mime, QVariant data, QString)
-{
- QList<QByteArray> ret;
- if (mime == QLatin1String("text/plain"))
- ret.append(data.toString().toUtf8());
- return ret;
-}
-
-#ifdef QT3_SUPPORT
-class QMacPasteboardMimeQt3Any : public QMacPasteboardMime {
-private:
- int current_max;
- QFile library_file;
- QDateTime mime_registry_loaded;
- QMap<QString, int> mime_registry;
- int registerMimeType(const QString &mime);
- bool loadMimeRegistry();
-
-public:
- QMacPasteboardMimeQt3Any() : QMacPasteboardMime(MIME_QT3_CONVERTOR) {
- current_max = 'QT00';
- }
- ~QMacPasteboardMimeQt3Any() {
- }
- QString convertorName();
-
- QString flavorFor(const QString &mime);
- QString mimeFor(QString flav);
- bool canConvert(const QString &mime, QString flav);
- QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav);
- QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav);
-};
-
-static bool qt_mac_openMimeRegistry(bool global, QIODevice::OpenMode mode, QFile &file)
-{
- QString dir = QLatin1String("/Library/Qt");
- if(!global)
- dir.prepend(QDir::homePath());
- file.setFileName(dir + QLatin1String("/.mime_types"));
- if(mode != QIODevice::ReadOnly) {
- if(!QFile::exists(dir)) {
- // Do it with a system call as I don't see much worth in
- // doing it with QDir since we have to chmod anyway.
- bool success = ::mkdir(dir.toLocal8Bit().constData(), S_IRUSR | S_IWUSR | S_IXUSR) == 0;
- if (success)
- success = ::chmod(dir.toLocal8Bit().constData(), S_IRUSR | S_IWUSR | S_IXUSR
- | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH) == 0;
- if (!success)
- return false;
- }
- if (!file.exists()) {
- // Create the file and chmod it so that everyone can write to it.
- int fd = ::open(file.fileName().toLocal8Bit().constData(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
- bool success = fd != -1;
- if (success)
- success = ::fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == 0;
- if (fd != -1)
- ::close(fd);
- if(!success)
- return false;
- }
- }
- return file.open(mode);
-}
-
-static void qt_mac_loadMimeRegistry(QFile &file, QMap<QString, int> &registry, int &max)
-{
- file.reset();
- QTextStream stream(&file);
- while(!stream.atEnd()) {
- QString mime = stream.readLine();
- int mactype = stream.readLine().toInt();
- if(mactype > max)
- max = mactype;
- registry.insert(mime, mactype);
- }
-}
-
-bool QMacPasteboardMimeQt3Any::loadMimeRegistry()
-{
- if(!library_file.isOpen()) {
- if(!qt_mac_openMimeRegistry(true, QIODevice::ReadWrite, library_file)) {
- QFile global;
- if(qt_mac_openMimeRegistry(true, QIODevice::ReadOnly, global)) {
- qt_mac_loadMimeRegistry(global, mime_registry, current_max);
- global.close();
- }
- if(!qt_mac_openMimeRegistry(false, QIODevice::ReadWrite, library_file)) {
- qWarning("QMacPasteboardMimeAnyQt3Mime: Failure to open mime resources %s -- %s", library_file.fileName().toLatin1().constData(),
- library_file.errorString().toLatin1().constData());
- return false;
- }
- }
- }
-
- QFileInfo fi(library_file);
- if(!mime_registry_loaded.isNull() && mime_registry_loaded == fi.lastModified())
- return true;
- mime_registry_loaded = fi.lastModified();
- qt_mac_loadMimeRegistry(library_file, mime_registry, current_max);
- return true;
-}
-
-int QMacPasteboardMimeQt3Any::registerMimeType(const QString &mime)
-{
- if(!mime_registry.contains(mime)) {
- if(!loadMimeRegistry()) {
- qWarning("QMacPasteboardMimeAnyQt3Mime: Internal error");
- return 0;
- }
- if(!mime_registry.contains(mime)) {
- if(!library_file.isOpen()) {
- if(!library_file.open(QIODevice::WriteOnly)) {
- qWarning("QMacPasteboardMimeAnyQt3Mime: Failure to open %s -- %s", library_file.fileName().toLatin1().constData(),
- library_file.errorString().toLatin1().constData());
- return false;
- }
- }
- int ret = ++current_max;
- mime_registry_loaded = QFileInfo(library_file).lastModified();
- QTextStream stream(&library_file);
- stream << mime << endl;
- stream << ret << endl;
- mime_registry.insert(mime, ret);
- library_file.flush(); //flush and set mtime
- return ret;
- }
- }
- return mime_registry[mime];
-}
-
-QString QMacPasteboardMimeQt3Any::convertorName()
-{
- return QLatin1String("Qt3-Any-Mime");
-}
-
-QString QMacPasteboardMimeQt3Any::flavorFor(const QString &mime)
-{
- const int os_flav = registerMimeType(mime);
- QCFType<CFArrayRef> ids = UTTypeCreateAllIdentifiersForTag(0, kUTTagClassOSType,
- QCFString(UTCreateStringForOSType(os_flav)));
- if(ids) {
- const int type_count = CFArrayGetCount(ids);
- if(type_count) {
- if(type_count > 1)
- qDebug("Can't happen!");
- return QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(ids, 0));
- }
- }
- return QString();
-}
-
-QString QMacPasteboardMimeQt3Any::mimeFor(QString flav)
-{
- loadMimeRegistry();
- const int os_flav = UTGetOSTypeFromString(UTTypeCopyPreferredTagWithClass(QCFString(flav), kUTTagClassOSType));
- for(QMap<QString, int>::const_iterator it = mime_registry.constBegin();
- it != mime_registry.constEnd(); ++it) {
- if(it.value() == os_flav)
- return QString::fromLatin1(it.key().toLatin1());
- }
- return QString();
-}
-
-bool QMacPasteboardMimeQt3Any::canConvert(const QString &mime, QString flav)
-{
- loadMimeRegistry();
- const int os_flav = UTGetOSTypeFromString(UTTypeCopyPreferredTagWithClass(QCFString(flav), kUTTagClassOSType));
- if(mime_registry.contains(mime) && mime_registry[mime] == os_flav)
- return true;
- return false;
-}
-
-QVariant QMacPasteboardMimeQt3Any::convertToMime(const QString &, QList<QByteArray>, QString)
-{
- qWarning("QMacPasteboardMimeAnyQt3Mime: Cannot write anything!");
- return QVariant();
-}
-
-QList<QByteArray> QMacPasteboardMimeQt3Any::convertFromMime(const QString &mime, QVariant data, QString)
-{
- QList<QByteArray> ret;
- if (mime == QLatin1String("text/plain")) {
- ret.append(data.toString().toUtf8());
- } else {
- ret.append(data.toByteArray());
- }
- return ret;
-}
-#endif
-
-/*!
- \internal
-
- This is an internal function.
-*/
-void QMacPasteboardMime::initialize()
-{
- if(globalMimeList()->isEmpty()) {
- qAddPostRoutine(cleanup_mimes);
-
- //standard types that we wrap
- new QMacPasteboardMimeTiff;
-#ifdef Q_WS_MAC32
- // 10.6 does automatic synthesis to and from PICT to standard image types (like TIFF),
- // so don't bother doing it ourselves, especially since it's not available in 64-bit.
- if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6)
- new QMacPasteboardMimePict;
-#endif
- new QMacPasteboardMimeUnicodeText;
- new QMacPasteboardMimePlainText;
- new QMacPasteboardMimeHTMLText;
- new QMacPasteboardMimeFileUri;
- new QMacPasteboardMimeUrl;
- new QMacPasteboardMimeTypeName;
- new QMacPasteboardMimeVCard;
- //make sure our "non-standard" types are always last! --Sam
- new QMacPasteboardMimeAny;
-#ifdef QT3_SUPPORT
- new QMacPasteboardMimeQt3Any;
-#endif
- }
-}
-
-/*!
- Returns the most-recently created QMacPasteboardMime of type \a t that can convert
- between the \a mime and \a flav formats. Returns 0 if no such convertor
- exists.
-*/
-QMacPasteboardMime*
-QMacPasteboardMime::convertor(uchar t, const QString &mime, QString flav)
-{
- MimeList *mimes = globalMimeList();
- for(MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) {
-#ifdef DEBUG_MIME_MAPS
- qDebug("QMacPasteboardMime::convertor: seeing if %s (%d) can convert %s to %d[%c%c%c%c] [%d]",
- (*it)->convertorName().toLatin1().constData(),
- (*it)->type & t, mime.toLatin1().constData(),
- flav, (flav >> 24) & 0xFF, (flav >> 16) & 0xFF, (flav >> 8) & 0xFF, (flav) & 0xFF,
- (*it)->canConvert(mime,flav));
- for(int i = 0; i < (*it)->countFlavors(); ++i) {
- int f = (*it)->flavor(i);
- qDebug(" %d) %d[%c%c%c%c] [%s]", i, f,
- (f >> 24) & 0xFF, (f >> 16) & 0xFF, (f >> 8) & 0xFF, (f) & 0xFF,
- (*it)->convertorName().toLatin1().constData());
- }
-#endif
- if(((*it)->type & t) && (*it)->canConvert(mime, flav))
- return (*it);
- }
- return 0;
-}
-/*!
- Returns a MIME type of type \a t for \a flav, or 0 if none exists.
-*/
-QString QMacPasteboardMime::flavorToMime(uchar t, QString flav)
-{
- MimeList *mimes = globalMimeList();
- for(MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) {
-#ifdef DEBUG_MIME_MAPS
- qDebug("QMacMIme::flavorToMime: attempting %s (%d) for flavor %d[%c%c%c%c] [%s]",
- (*it)->convertorName().toLatin1().constData(),
- (*it)->type & t, flav, (flav >> 24) & 0xFF, (flav >> 16) & 0xFF, (flav >> 8) & 0xFF, (flav) & 0xFF,
- (*it)->mimeFor(flav).toLatin1().constData());
-
-#endif
- if((*it)->type & t) {
- QString mimeType = (*it)->mimeFor(flav);
- if(!mimeType.isNull())
- return mimeType;
- }
- }
- return QString();
-}
-
-/*!
- Returns a list of all currently defined QMacPasteboardMime objects of type \a t.
-*/
-QList<QMacPasteboardMime*> QMacPasteboardMime::all(uchar t)
-{
- MimeList ret;
- MimeList *mimes = globalMimeList();
- for(MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) {
- if((*it)->type & t)
- ret.append((*it));
- }
- return ret;
-}
-
-
-/*!
- \fn QString QMacPasteboardMime::convertorName()
-
- Returns a name for the convertor.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn bool QMacPasteboardMime::canConvert(const QString &mime, QString flav)
-
- Returns true if the convertor can convert (both ways) between
- \a mime and \a flav; otherwise returns false.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn QString QMacPasteboardMime::mimeFor(QString flav)
-
- Returns the MIME UTI used for Mac flavor \a flav, or 0 if this
- convertor does not support \a flav.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn QString QMacPasteboardMime::flavorFor(const QString &mime)
-
- Returns the Mac UTI used for MIME type \a mime, or 0 if this
- convertor does not support \a mime.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn QVariant QMacPasteboardMime::convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
-
- Returns \a data converted from Mac UTI \a flav to MIME type \a
- mime.
-
- Note that Mac flavors must all be self-terminating. The input \a
- data may contain trailing data.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn QList<QByteArray> QMacPasteboardMime::convertFromMime(const QString &mime, QVariant data, QString flav)
-
- Returns \a data converted from MIME type \a mime
- to Mac UTI \a flav.
-
- Note that Mac flavors must all be self-terminating. The return
- value may contain trailing data.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qmultitouch_mac.mm b/src/gui/platforms/mac/qmultitouch_mac.mm
deleted file mode 100644
index d9e845a01c..0000000000
--- a/src/gui/platforms/mac/qmultitouch_mac.mm
+++ /dev/null
@@ -1,218 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qmultitouch_mac_p.h>
-#include <qcursor.h>
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-
-QHash<qint64, QCocoaTouch*> QCocoaTouch::_currentTouches;
-QPointF QCocoaTouch::_screenReferencePos;
-QPointF QCocoaTouch::_trackpadReferencePos;
-int QCocoaTouch::_idAssignmentCount = 0;
-int QCocoaTouch::_touchCount = 0;
-bool QCocoaTouch::_updateInternalStateOnly = true;
-
-QCocoaTouch::QCocoaTouch(NSTouch *nstouch)
-{
- if (_currentTouches.size() == 0)
- _idAssignmentCount = 0;
-
- _touchPoint.setId(_idAssignmentCount++);
- _touchPoint.setPressure(1.0);
- _identity = qint64([nstouch identity]);
- _currentTouches.insert(_identity, this);
- updateTouchData(nstouch, NSTouchPhaseBegan);
-}
-
-QCocoaTouch::~QCocoaTouch()
-{
- _currentTouches.remove(_identity);
-}
-
-void QCocoaTouch::updateTouchData(NSTouch *nstouch, NSTouchPhase phase)
-{
- if (_touchCount == 1)
- _touchPoint.setState(toTouchPointState(phase) | Qt::TouchPointPrimary);
- else
- _touchPoint.setState(toTouchPointState(phase));
-
- // From the normalized position on the trackpad, calculate
- // where on screen the touchpoint should be according to the
- // reference position:
- NSPoint npos = [nstouch normalizedPosition];
- QPointF qnpos = QPointF(npos.x, 1 - npos.y);
- _touchPoint.setNormalizedPos(qnpos);
-
- if (_touchPoint.id() == 0 && phase == NSTouchPhaseBegan) {
- _trackpadReferencePos = qnpos;
- _screenReferencePos = QCursor::pos();
- }
-
- NSSize dsize = [nstouch deviceSize];
- float ppiX = (qnpos.x() - _trackpadReferencePos.x()) * dsize.width;
- float ppiY = (qnpos.y() - _trackpadReferencePos.y()) * dsize.height;
- QPointF relativePos = _trackpadReferencePos - QPointF(ppiX, ppiY);
- _touchPoint.setScreenPos(_screenReferencePos - relativePos);
-}
-
-QCocoaTouch *QCocoaTouch::findQCocoaTouch(NSTouch *nstouch)
-{
- qint64 identity = qint64([nstouch identity]);
- if (_currentTouches.contains(identity))
- return _currentTouches.value(identity);
- return 0;
-}
-
-Qt::TouchPointState QCocoaTouch::toTouchPointState(NSTouchPhase nsState)
-{
- Qt::TouchPointState qtState = Qt::TouchPointReleased;
- switch (nsState) {
- case NSTouchPhaseBegan:
- qtState = Qt::TouchPointPressed;
- break;
- case NSTouchPhaseMoved:
- qtState = Qt::TouchPointMoved;
- break;
- case NSTouchPhaseStationary:
- qtState = Qt::TouchPointStationary;
- break;
- case NSTouchPhaseEnded:
- case NSTouchPhaseCancelled:
- qtState = Qt::TouchPointReleased;
- break;
- default:
- break;
- }
- return qtState;
-}
-
-QList<QTouchEvent::TouchPoint>
-QCocoaTouch::getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch)
-{
- QMap<int, QTouchEvent::TouchPoint> touchPoints;
- NSSet *ended = [event touchesMatchingPhase:NSTouchPhaseEnded | NSTouchPhaseCancelled inView:nil];
- NSSet *active = [event
- touchesMatchingPhase:NSTouchPhaseBegan | NSTouchPhaseMoved | NSTouchPhaseStationary
- inView:nil];
- _touchCount = [active count];
-
- // First: remove touches that were ended by the user. If we are
- // currently not accepting single touches, a corresponding 'begin'
- // has never been send to the app for these events.
- // So should therefore not send the following removes either.
-
- for (int i=0; i<int([ended count]); ++i) {
- NSTouch *touch = [[ended allObjects] objectAtIndex:i];
- QCocoaTouch *qcocoaTouch = findQCocoaTouch(touch);
- if (qcocoaTouch) {
- qcocoaTouch->updateTouchData(touch, [touch phase]);
- if (!_updateInternalStateOnly)
- touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
- delete qcocoaTouch;
- }
- }
-
- bool wasUpdateInternalStateOnly = _updateInternalStateOnly;
- _updateInternalStateOnly = !acceptSingleTouch && _touchCount < 2;
-
- // Next: update, or create, existing touches.
- // We always keep track of all touch points, even
- // when not accepting single touches.
-
- for (int i=0; i<int([active count]); ++i) {
- NSTouch *touch = [[active allObjects] objectAtIndex:i];
- QCocoaTouch *qcocoaTouch = findQCocoaTouch(touch);
- if (!qcocoaTouch)
- qcocoaTouch = new QCocoaTouch(touch);
- else
- qcocoaTouch->updateTouchData(touch, wasUpdateInternalStateOnly ? NSTouchPhaseBegan : [touch phase]);
- if (!_updateInternalStateOnly)
- touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
- }
-
- // Next: sadly, we need to check that our touch hash is in
- // sync with cocoa. This is typically not the case after a system
- // gesture happend (like a four-finger-swipe to show expose).
-
- if (_touchCount != _currentTouches.size()) {
- // Remove all instances, and basically start from scratch:
- touchPoints.clear();
- foreach (QCocoaTouch *qcocoaTouch, _currentTouches.values()) {
- if (!_updateInternalStateOnly) {
- qcocoaTouch->_touchPoint.setState(Qt::TouchPointReleased);
- touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
- }
- delete qcocoaTouch;
- }
- _currentTouches.clear();
- _updateInternalStateOnly = !acceptSingleTouch;
- return touchPoints.values();
- }
-
- // Finally: If this call _started_ to reject single
- // touches, we need to fake a relase for the remaining
- // touch now (and refake a begin for it later, if needed).
-
- if (_updateInternalStateOnly && !wasUpdateInternalStateOnly && !_currentTouches.isEmpty()) {
- QCocoaTouch *qcocoaTouch = _currentTouches.values().first();
- qcocoaTouch->_touchPoint.setState(Qt::TouchPointReleased);
- touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
- // Since this last touch also will end up beeing the first
- // touch (if the user adds a second finger without lifting
- // the first), we promote it to be the primary touch:
- qcocoaTouch->_touchPoint.setId(0);
- _idAssignmentCount = 1;
- }
-
- return touchPoints.values();
-}
-
-#endif
-
-QT_END_NAMESPACE
-
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
diff --git a/src/gui/platforms/mac/qmultitouch_mac_p.h b/src/gui/platforms/mac/qmultitouch_mac_p.h
deleted file mode 100644
index 16be930d0a..0000000000
--- a/src/gui/platforms/mac/qmultitouch_mac_p.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-#ifndef QMULTITOUCH_MAC_P_H
-#define QMULTITOUCH_MAC_P_H
-
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-#endif
-
-#include <qevent.h>
-#include <qhash.h>
-#include <QtCore>
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-
-class QCocoaTouch
-{
- public:
- static QList<QTouchEvent::TouchPoint> getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch);
- static void setMouseInDraggingState(bool inDraggingState);
-
- private:
- static QHash<qint64, QCocoaTouch*> _currentTouches;
- static QPointF _screenReferencePos;
- static QPointF _trackpadReferencePos;
- static int _idAssignmentCount;
- static int _touchCount;
- static bool _updateInternalStateOnly;
-
- QTouchEvent::TouchPoint _touchPoint;
- qint64 _identity;
-
- QCocoaTouch(NSTouch *nstouch);
- ~QCocoaTouch();
-
- void updateTouchData(NSTouch *nstouch, NSTouchPhase phase);
- static QCocoaTouch *findQCocoaTouch(NSTouch *nstouch);
- static Qt::TouchPointState toTouchPointState(NSTouchPhase nsState);
-};
-
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
-
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
-#endif // QMULTITOUCH_MAC_P_H
-
diff --git a/src/gui/platforms/mac/qnsframeview_mac_p.h b/src/gui/platforms/mac/qnsframeview_mac_p.h
deleted file mode 100644
index 6ec3f64efa..0000000000
--- a/src/gui/platforms/mac/qnsframeview_mac_p.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-// Private AppKit class (dumped from classdump).
-
-#import <Cocoa/Cocoa.h>
-
-@interface NSFrameView : NSView
-{
- unsigned int styleMask;
- NSString *_title;
- NSCell *titleCell;
- NSButton *closeButton;
- NSButton *zoomButton;
- NSButton *minimizeButton;
- char resizeByIncrement;
- char frameNeedsDisplay;
- unsigned char tabViewCount;
- NSSize resizeParameter;
- int shadowState;
-}
-
-+ (void)initialize;
-+ (void)initTitleCell:fp8 styleMask:(unsigned int)fp12;
-+ (struct _NSRect)frameRectForContentRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (struct _NSRect)contentRectForFrameRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (struct _NSSize)minContentSizeForMinFrameSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
-+ (unsigned int)_validateStyleMask:(unsigned int)fp8;
-- initWithFrame:(struct _NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
-- initWithFrame:(struct _NSRect)fp8;
-- (void)dealloc;
-- (void)shapeWindow;
-- (void)tileAndSetWindowShape:(char)fp8;
-- (void)tile;
-- (void)drawRect:(struct _NSRect)fp8;
-- (void)_drawFrameRects:(struct _NSRect)fp8;
-- (void)drawFrame:(struct _NSRect)fp8;
-- (void)drawThemeContentFill:(struct _NSRect)fp8 inView:fp24;
-- (void)drawWindowBackgroundRect:(struct _NSRect)fp8;
-- (void)drawWindowBackgroundRegion:(void *)fp8;
-- (float)contentAlpha;
-- (void)_windowChangedKeyState;
-- (void)_updateButtonState;
-- (char)_isSheet;
-- (char)_isUtility;
-- (void)setShadowState:(int)fp8;
-- (int)shadowState;
-- (char)_canHaveToolbar;
-- (char)_toolbarIsInTransition;
-- (char)_toolbarIsShown;
-- (char)_toolbarIsHidden;
-- (void)_showToolbarWithAnimation:(char)fp8;
-- (void)_hideToolbarWithAnimation:(char)fp8;
-- (float)_distanceFromToolbarBaseToTitlebar;
-- (int)_shadowType;
-- (unsigned int)_shadowFlags;
-- (void)_setShadowParameters;
-- (void)_drawFrameShadowAndFlushContext:fp8;
-- (void)setUpGState;
-- (void)adjustHalftonePhase;
-- (void)systemColorsDidChange:fp8;
-- frameColor;
-- contentFill;
-- (void)tabViewAdded;
-- (void)tabViewRemoved;
-- title;
-- (void)setTitle:fp8;
-- titleCell;
-- (void)initTitleCell:fp8;
-- (void)setResizeIncrements:(struct _NSSize)fp8;
-- (struct _NSSize)resizeIncrements;
-- (void)setAspectRatio:(struct _NSSize)fp8;
-- (struct _NSSize)aspectRatio;
-- (unsigned int)styleMask;
-- representedFilename;
-- (void)setRepresentedFilename:fp8;
-- (void)setDocumentEdited:(char)fp8;
-- (void)_setFrameNeedsDisplay:(char)fp8;
-- (char)frameNeedsDisplay;
-- titleFont;
-- (struct _NSRect)_maxTitlebarTitleRect;
-- (struct _NSRect)titlebarRect;
-- (void)_setUtilityWindow:(char)fp8;
-- (void)_setNonactivatingPanel:(char)fp8;
-- (void)setIsClosable:(char)fp8;
-- (void)setIsResizable:(char)fp8;
-- closeButton;
-- minimizeButton;
-- zoomButton;
-- (struct _NSSize)miniaturizedSize;
-- (void)_clearDragMargins;
-- (void)_resetDragMargins;
-- (void)setTitle:fp8 andDefeatWrap:(char)fp12;
-- (struct _NSRect)frameRectForContentRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-- (struct _NSRect)contentRectForFrameRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-- (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-- (struct _NSRect)dragRectForFrameRect:(struct _NSRect)fp8;
-- (struct _NSRect)contentRect;
-- (struct _NSSize)minFrameSize;
-- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(struct _NSRect)fp8 isVisibleRect:(char)fp24 rectIsVisibleRectForView:fp28 topView:(char)fp32;
-
-@end
diff --git a/src/gui/platforms/mac/qnsthemeframe_mac_p.h b/src/gui/platforms/mac/qnsthemeframe_mac_p.h
deleted file mode 100644
index 2cb4916c06..0000000000
--- a/src/gui/platforms/mac/qnsthemeframe_mac_p.h
+++ /dev/null
@@ -1,246 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-// Private AppKit class (dumped from classdump).
-
-#import <Cocoa/Cocoa.h>
-#import "qnstitledframe_mac_p.h"
-
-@interface NSThemeFrame : NSTitledFrame
-{
- NSButton *toolbarButton;
- int toolbarVisibleStatus;
- NSImage *showToolbarTransitionImage;
- NSSize showToolbarPreWindowSize;
- NSButton *modeButton;
- int leftGroupTrackingTagNum;
- int rightGroupTrackingTagNum;
- char mouseInsideLeftGroup;
- char mouseInsideRightGroup;
- int widgetState;
- NSString *displayName;
-}
-
-+ (void)initialize;
-+ (float)_windowBorderThickness:(unsigned int)fp8;
-+ (float)_minXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_maxXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_minYWindowBorderHeight:(unsigned int)fp8;
-+ (float)_windowTitlebarButtonSpacingWidth:(unsigned int)fp8;
-+ (float)_windowFileButtonSpacingWidth:(unsigned int)fp8;
-+ (float)_minXTitlebarWidgetInset:(unsigned int)fp8;
-+ (float)_maxXTitlebarWidgetInset:(unsigned int)fp8;
-+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
-+ (float)_windowSideTitlebarTitleMinWidth:(unsigned int)fp8;
-+ (float)_windowTitlebarTitleMinHeight:(unsigned int)fp8;
-+ (float)_sideTitlebarWidth:(unsigned int)fp8;
-+ (float)_titlebarHeight:(unsigned int)fp8;
-+ (float)_resizeHeight:(unsigned int)fp8;
-+ (char)_resizeFromEdge;
-+ (struct _NSSize)sizeOfTitlebarButtons:(unsigned int)fp8;
-+ (float)_contentToFrameMinXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMaxXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMinYHeight:(unsigned int)fp8;
-+ (float)_contentToFrameMaxYHeight:(unsigned int)fp8;
-+ (unsigned int)_validateStyleMask:(unsigned int)fp8;
-- (struct _NSSize)_topCornerSize;
-- (struct _NSSize)_bottomCornerSize;
-- (void *)_createWindowOpaqueShape;
-- (void)shapeWindow;
-- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)fp8 isVisibleRect:(char)fp24 rectIsVisibleRectForView:fp28 topView:(char)fp32;
-- (void *)_regionForOpaqueDescendants:(NSRect)fp8 forMove:(char)fp24;
-- (void)_drawFrameInterior:(NSRect *)fp8 clip:(NSRect)fp12;
-- (void)_setTextShadow:(char)fp8;
-- (void)_drawTitleBar:(NSRect)fp8;
-- (void)_drawResizeIndicators:(NSRect)fp8;
-- (void)_drawFrameRects:(NSRect)fp8;
-- (void)drawFrame:(NSRect)fp8;
-- contentFill;
-- (void)viewDidEndLiveResize;
-- (float)contentAlpha;
-- (void)setThemeFrameWidgetState:(int)fp8;
-- (char)constrainResizeEdge:(int *)fp8 withDelta:(struct _NSSize)fp12 elapsedTime:(float)fp20;
-- (void)addFileButton:fp8;
-- (void)_updateButtons;
-- (void)_updateButtonState;
-- newCloseButton;
-- newZoomButton;
-- newMiniaturizeButton;
-- newToolbarButton;
-- newFileButton;
-- (void)_resetTitleBarButtons;
-- (void)setDocumentEdited:(char)fp8;
-- toolbarButton;
-- modeButton;
-- initWithFrame:(NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
-- (void)dealloc;
-- (void)setFrameSize:(struct _NSSize)fp8;
-- (char)_canHaveToolbar;
-- (char)_toolbarIsInTransition;
-- (char)_toolbarIsShown;
-- (char)_toolbarIsHidden;
-- _toolbarView;
-- _toolbar;
-- (float)_distanceFromToolbarBaseToTitlebar;
-- (unsigned int)_shadowFlags;
-- (NSRect)frameRectForContentRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-- (NSRect)contentRectForFrameRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-- (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-- (NSRect)contentRect;
-- (NSRect)_contentRectExcludingToolbar;
-- (NSRect)_contentRectIncludingToolbarAtHome;
-- (void)_setToolbarShowHideResizeWeightingOptimizationOn:(char)fp8;
-- (char)_usingToolbarShowHideWeightingOptimization;
-- (void)handleSetFrameCommonRedisplay;
-- (void)_startLiveResizeAsTopLevel;
-- (void)_endLiveResizeAsTopLevel;
-- (void)_growContentReshapeContentAndToolbarView:(int)fp8 animate:(char)fp12;
-- (char)_growWindowReshapeContentAndToolbarView:(int)fp8 animate:(char)fp12;
-- (void)_reshapeContentAndToolbarView:(int)fp8 resizeWindow:(char)fp12 animate:(char)fp16;
-- (void)_toolbarFrameSizeChanged:fp8 oldSize:(struct _NSSize)fp12;
-- (void)_syncToolbarPosition;
-- (void)_showHideToolbar:(int)fp8 resizeWindow:(char)fp12 animate:(char)fp16;
-- (void)_showToolbarWithAnimation:(char)fp8;
-- (void)_hideToolbarWithAnimation:(char)fp8;
-- (void)_drawToolbarTransitionIfNecessary;
-- (void)drawRect:(NSRect)fp8;
-- (void)resetCursorRects;
-- (char)shouldBeTreatedAsInkEvent:fp8;
-- (char)_shouldBeTreatedAsInkEventInInactiveWindow:fp8;
-//- hitTest:(struct _NSPoint)fp8; // collides with hittest in qcocoasharedwindowmethods_mac_p.h
-- (NSRect)_leftGroupRect;
-- (NSRect)_rightGroupRect;
-- (void)_updateWidgets;
-- (void)_updateMouseTracking;
-- (void)mouseEntered:fp8;
-- (void)mouseExited:fp8;
-- (void)_setMouseEnteredGroup:(char)fp8 entered:(char)fp12;
-- (char)_mouseInGroup:fp8;
-- (struct _NSSize)miniaturizedSize;
-- (float)_minXTitlebarDecorationMinWidth;
-- (float)_maxXTitlebarDecorationMinWidth;
-- (struct _NSSize)minFrameSize;
-- (float)_windowBorderThickness;
-- (float)_windowTitlebarXResizeBorderThickness;
-- (float)_windowTitlebarYResizeBorderThickness;
-- (float)_windowResizeBorderThickness;
-- (float)_minXWindowBorderWidth;
-- (float)_maxXWindowBorderWidth;
-- (float)_minYWindowBorderHeight;
-- (float)_maxYWindowBorderHeight;
-- (float)_minYTitlebarButtonsOffset;
-- (float)_minYTitlebarTitleOffset;
-- (float)_sideTitlebarWidth;
-- (float)_titlebarHeight;
-- (NSRect)_titlebarTitleRect;
-- (NSRect)titlebarRect;
-- (float)_windowTitlebarTitleMinHeight;
-- (struct _NSSize)_sizeOfTitlebarFileButton;
-- (struct _NSSize)sizeOfTitlebarToolbarButton;
-- (float)_windowTitlebarButtonSpacingWidth;
-- (float)_windowFileButtonSpacingWidth;
-- (float)_minXTitlebarWidgetInset;
-- (float)_maxXTitlebarWidgetInset;
-- (float)_minXTitlebarButtonsWidth;
-- (float)_maxXTitlebarButtonsWidth;
-- (struct _NSPoint)_closeButtonOrigin;
-- (struct _NSPoint)_zoomButtonOrigin;
-- (struct _NSPoint)_collapseButtonOrigin;
-- (struct _NSPoint)_toolbarButtonOrigin;
-- (struct _NSPoint)_fileButtonOrigin;
-- (void)_tileTitlebar;
-- (NSRect)_commandPopupRect;
-- (void)_resetDragMargins;
-- (float)_maxYTitlebarDragHeight;
-- (float)_minXTitlebarDragWidth;
-- (float)_maxXTitlebarDragWidth;
-- (float)_contentToFrameMinXWidth;
-- (float)_contentToFrameMaxXWidth;
-- (float)_contentToFrameMinYHeight;
-- (float)_contentToFrameMaxYHeight;
-- (float)_windowResizeCornerThickness;
-- (NSRect)_minYResizeRect;
-- (NSRect)_minYminXResizeRect;
-- (NSRect)_minYmaxXResizeRect;
-- (NSRect)_minXResizeRect;
-- (NSRect)_minXminYResizeRect;
-- (NSRect)_minXmaxYResizeRect;
-- (NSRect)_maxYResizeRect;
-- (NSRect)_maxYminXResizeRect;
-- (NSRect)_maxYmaxXResizeRect;
-- (NSRect)_maxXResizeRect;
-- (NSRect)_maxXminYResizeRect;
-- (NSRect)_maxXmaxYResizeRect;
-- (NSRect)_minXTitlebarResizeRect;
-- (NSRect)_maxXTitlebarResizeRect;
-- (NSRect)_minXBorderRect;
-- (NSRect)_maxXBorderRect;
-- (NSRect)_maxYBorderRect;
-- (NSRect)_minYBorderRect;
-- (void)_setUtilityWindow:(char)fp8;
-- (char)_isUtility;
-- (float)_sheetHeightAdjustment;
-- (void)_setSheet:(char)fp8;
-- (char)_isSheet;
-- (char)_isResizable;
-- (char)_isClosable;
-- (char)_isMiniaturizable;
-- (char)_hasToolbar;
-- (NSRect)_growBoxRect;
-- (void)_drawGrowBoxWithClip:(NSRect)fp8;
-- (char)_inactiveButtonsNeedMask;
-- (void)mouseDown:fp8;
-- _displayName;
-- (void)_setDisplayName:fp8;
-
-@end
diff --git a/src/gui/platforms/mac/qnstitledframe_mac_p.h b/src/gui/platforms/mac/qnstitledframe_mac_p.h
deleted file mode 100644
index 4eb5332194..0000000000
--- a/src/gui/platforms/mac/qnstitledframe_mac_p.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// 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.
-//
-
-// Private AppKit class (dumped from classdump).
-
-#import <Cocoa/Cocoa.h>
-#import "qnsframeview_mac_p.h"
-
-
-@interface NSTitledFrame : NSFrameView
-{
- int resizeFlags;
- id fileButton; /* NSDocumentDragButton* */
- NSSize titleCellSize;
-}
-
-+ (float)_windowBorderThickness:(unsigned int)fp8;
-+ (float)_minXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_maxXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_minYWindowBorderHeight:(unsigned int)fp8;
-+ (char)_resizeFromEdge;
-+ (NSRect)frameRectForContentRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (NSRect)contentRectForFrameRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (struct _NSSize)minContentSizeForMinFrameSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
-+ (struct _NSSize)_titleCellSizeForTitle:fp8 styleMask:(unsigned int)fp12;
-+ (float)_titleCellHeight:(unsigned int)fp8;
-+ (float)_windowTitlebarTitleMinHeight:(unsigned int)fp8;
-+ (float)_titlebarHeight:(unsigned int)fp8;
-+ (struct _NSSize)sizeOfTitlebarButtons:(unsigned int)fp8;
-+ (float)windowTitlebarLinesSpacingWidth:(unsigned int)fp8;
-+ (float)windowTitlebarTitleLinesSpacingWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMinXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMaxXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMinYHeight:(unsigned int)fp8;
-+ (float)_contentToFrameMaxYHeight:(unsigned int)fp8;
-- initWithFrame:(NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
-- (void)dealloc;
-- (void)setIsClosable:(char)fp8;
-- (void)setIsResizable:(char)fp8;
-- (void)_resetTitleFont;
-- (void)_setUtilityWindow:(char)fp8;
-- (char)isOpaque;
-- (char)worksWhenModal;
-- (void)propagateFrameDirtyRects:(NSRect)fp8;
-- (void)_showDrawRect:(NSRect)fp8;
-- (void)_drawFrameInterior:(NSRect *)fp8 clip:(NSRect)fp12;
-- (void)drawFrame:(NSRect)fp8;
-- (void)_drawFrameRects:(NSRect)fp8;
-- (void)_drawTitlebar:(NSRect)fp8;
-- (void)_drawTitlebarPattern:(int)fp8 inRect:(NSRect)fp12 clippedByRect:(NSRect)fp28 forKey:(char)fp44 alignment:(int)fp48;
-- (void)_drawTitlebarLines:(int)fp8 inRect:(NSRect)fp12 clippedByRect:(NSRect)fp28;
-- frameHighlightColor;
-- frameShadowColor;
-- (void)setFrameSize:(struct _NSSize)fp8;
-- (void)setFrameOrigin:(struct _NSPoint)fp8;
-- (void)tileAndSetWindowShape:(char)fp8;
-- (void)tile;
-- (void)_tileTitlebar;
-- (void)setTitle:fp8;
-- (char)_shouldRepresentFilename;
-- (void)setRepresentedFilename:fp8;
-- (void)_drawTitleStringIn:(NSRect)fp8 withColor:fp24;
-- titleFont;
-- (void)_drawResizeIndicators:(NSRect)fp8;
-- titleButtonOfClass:(Class)fp8;
-- initTitleButton:fp8;
-- newCloseButton;
-- newZoomButton;
-- newMiniaturizeButton;
-- newFileButton;
-- fileButton;
-- (void)_removeButtons;
-- (void)_updateButtons;
-- (char)_eventInTitlebar:fp8;
-- (char)acceptsFirstMouse:fp8;
-- (void)mouseDown:fp8;
-- (void)mouseUp:fp8;
-- (void)rightMouseDown:fp8;
-- (void)rightMouseUp:fp8;
-- (int)resizeEdgeForEvent:fp8;
-- (struct _NSSize)_resizeDeltaFromPoint:(struct _NSPoint)fp8 toEvent:fp16;
-- (NSRect)_validFrameForResizeFrame:(NSRect)fp8 fromResizeEdge:(int)fp24;
-- (NSRect)frame:(NSRect)fp8 resizedFromEdge:(int)fp24 withDelta:(struct _NSSize)fp28;
-- (char)constrainResizeEdge:(int *)fp8 withDelta:(struct _NSSize)fp12 elapsedTime:(float)fp20;
-- (void)resizeWithEvent:fp8;
-- (int)resizeFlags;
-- (void)resetCursorRects;
-- (void)setDocumentEdited:(char)fp8;
-- (struct _NSSize)miniaturizedSize;
-- (struct _NSSize)minFrameSize;
-- (float)_windowBorderThickness;
-- (float)_windowTitlebarXResizeBorderThickness;
-- (float)_windowTitlebarYResizeBorderThickness;
-- (float)_windowResizeBorderThickness;
-- (float)_minXWindowBorderWidth;
-- (float)_maxXWindowBorderWidth;
-- (float)_minYWindowBorderHeight;
-- (void)_invalidateTitleCellSize;
-- (void)_invalidateTitleCellWidth;
-- (float)_titleCellHeight;
-- (struct _NSSize)_titleCellSize;
-- (float)_titlebarHeight;
-- (NSRect)titlebarRect;
-- (NSRect)_maxTitlebarTitleRect;
-- (NSRect)_titlebarTitleRect;
-- (float)_windowTitlebarTitleMinHeight;
-- (NSRect)dragRectForFrameRect:(NSRect)fp8;
-- (struct _NSSize)sizeOfTitlebarButtons;
-- (struct _NSSize)_sizeOfTitlebarFileButton;
-- (float)_windowTitlebarButtonSpacingWidth;
-- (float)_minXTitlebarButtonsWidth;
-- (float)_maxXTitlebarButtonsWidth;
-- (int)_numberOfTitlebarLines;
-- (float)windowTitlebarLinesSpacingWidth;
-- (float)windowTitlebarTitleLinesSpacingWidth;
-- (float)_minLinesWidthWithSpace;
-- (NSRect)_minXTitlebarLinesRectWithTitleCellRect:(NSRect)fp8;
-- (NSRect)_maxXTitlebarLinesRectWithTitleCellRect:(NSRect)fp8;
-- (float)_minXTitlebarDecorationMinWidth;
-- (float)_maxXTitlebarDecorationMinWidth;
-- (struct _NSPoint)_closeButtonOrigin;
-- (struct _NSPoint)_zoomButtonOrigin;
-- (struct _NSPoint)_collapseButtonOrigin;
-- (struct _NSPoint)_fileButtonOrigin;
-- (float)_maxYTitlebarDragHeight;
-- (float)_minXTitlebarDragWidth;
-- (float)_maxXTitlebarDragWidth;
-- (float)_contentToFrameMinXWidth;
-- (float)_contentToFrameMaxXWidth;
-- (float)_contentToFrameMinYHeight;
-- (float)_contentToFrameMaxYHeight;
-- (NSRect)contentRect;
-- (float)_windowResizeCornerThickness;
-- (NSRect)_minYResizeRect;
-- (NSRect)_minYminXResizeRect;
-- (NSRect)_minYmaxXResizeRect;
-- (NSRect)_minXResizeRect;
-- (NSRect)_minXminYResizeRect;
-- (NSRect)_minXmaxYResizeRect;
-- (NSRect)_maxYResizeRect;
-- (NSRect)_maxYminXResizeRect;
-- (NSRect)_maxYmaxXResizeRect;
-- (NSRect)_maxXResizeRect;
-- (NSRect)_maxXminYResizeRect;
-- (NSRect)_maxXmaxYResizeRect;
-- (NSRect)_minXTitlebarResizeRect;
-- (NSRect)_maxXTitlebarResizeRect;
-- (NSRect)_minXBorderRect;
-- (NSRect)_maxXBorderRect;
-- (NSRect)_maxYBorderRect;
-- (NSRect)_minYBorderRect;
-
-@end
diff --git a/src/gui/platforms/mac/qpaintdevice_mac.cpp b/src/gui/platforms/mac/qpaintdevice_mac.cpp
deleted file mode 100644
index 245408a0b0..0000000000
--- a/src/gui/platforms/mac/qpaintdevice_mac.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpaintdevice.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qapplication.h"
-#include "qprinter.h"
-#include <qdebug.h>
-#include <private/qt_mac_p.h>
-#include <private/qprintengine_mac_p.h>
-#include <private/qpixmap_mac_p.h>
-#include <private/qpixmap_raster_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- Internal variables and functions
- *****************************************************************************/
-
-/*! \internal */
-float qt_mac_defaultDpi_x()
-{
- // Mac OS X currently assumes things to be 72 dpi.
- // (see http://developer.apple.com/releasenotes/GraphicsImaging/RN-ResolutionIndependentUI/)
- // This may need to be re-worked as we go further in the resolution-independence stuff.
- return 72;
-}
-
-/*! \internal */
-float qt_mac_defaultDpi_y()
-{
- // Mac OS X currently assumes things to be 72 dpi.
- // (see http://developer.apple.com/releasenotes/GraphicsImaging/RN-ResolutionIndependentUI/)
- // This may need to be re-worked as we go further in the resolution-independence stuff.
- return 72;
-}
-
-
-/*! \internal
-
- Returns the QuickDraw CGrafPtr of the paint device. 0 is returned
- if it can't be obtained. Do not hold the pointer around for long
- as it can be relocated.
-
- \warning This function is only available on Mac OS X.
-*/
-
-Q_GUI_EXPORT GrafPtr qt_mac_qd_context(const QPaintDevice *device)
-{
- if (device->devType() == QInternal::Pixmap) {
- return static_cast<GrafPtr>(static_cast<const QPixmap *>(device)->macQDHandle());
- } else if(device->devType() == QInternal::Widget) {
- return static_cast<GrafPtr>(static_cast<const QWidget *>(device)->macQDHandle());
- } else if(device->devType() == QInternal::Printer) {
- QPaintEngine *engine = static_cast<const QPrinter *>(device)->paintEngine();
- return static_cast<GrafPtr>(static_cast<const QMacPrintEngine *>(engine)->handle());
- }
- return 0;
-}
-
-extern CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *pdev);
-
-/*! \internal
-
- Returns the CoreGraphics CGContextRef of the paint device. 0 is
- returned if it can't be obtained. It is the caller's responsiblity to
- CGContextRelease the context when finished using it.
-
- \warning This function is only available on Mac OS X.
-*/
-
-Q_GUI_EXPORT CGContextRef qt_mac_cg_context(const QPaintDevice *pdev)
-{
- if (pdev->devType() == QInternal::Pixmap) {
- const QPixmap *pm = static_cast<const QPixmap*>(pdev);
- CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
- uint flags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- flags |= kCGBitmapByteOrder32Host;
-#endif
- CGContextRef ret = 0;
-
- // It would make sense to put this into a mac #ifdef'ed
- // virtual function in the QPixmapData at some point
- if (pm->data->classId() == QPixmapData::MacClass) {
- const QMacPixmapData *pmData = static_cast<const QMacPixmapData*>(pm->data.data());
- ret = CGBitmapContextCreate(pmData->pixels, pmData->w, pmData->h,
- 8, pmData->bytesPerRow, colorspace,
- flags);
- if(!ret)
- qWarning("QPaintDevice: Unable to create context for pixmap (%d/%d/%d)",
- pmData->w, pmData->h, (pmData->bytesPerRow * pmData->h));
- } else if (pm->data->classId() == QPixmapData::RasterClass) {
- QImage *image = pm->data->buffer();
- ret = CGBitmapContextCreate(image->bits(), image->width(), image->height(),
- 8, image->bytesPerLine(), colorspace, flags);
- }
-
- CGContextTranslateCTM(ret, 0, pm->height());
- CGContextScaleCTM(ret, 1, -1);
- return ret;
- } else if (pdev->devType() == QInternal::Widget) {
- CGContextRef ret = static_cast<CGContextRef>(static_cast<const QWidget *>(pdev)->macCGHandle());
- CGContextRetain(ret);
- return ret;
- } else if (pdev->devType() == QInternal::MacQuartz) {
- return static_cast<const QMacQuartzPaintDevice *>(pdev)->cgContext();
- }
- return 0;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qpaintengine_mac.cpp b/src/gui/platforms/mac/qpaintengine_mac.cpp
deleted file mode 100644
index c6d061dea8..0000000000
--- a/src/gui/platforms/mac/qpaintengine_mac.cpp
+++ /dev/null
@@ -1,1751 +0,0 @@
-/****************************************************************************
-**
-** 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 <qbitmap.h>
-#include <qpaintdevice.h>
-#include <private/qpaintengine_mac_p.h>
-#include <qpainterpath.h>
-#include <qpixmapcache.h>
-#include <private/qpaintengine_raster_p.h>
-#include <private/qprintengine_mac_p.h>
-#include <qprinter.h>
-#include <qstack.h>
-#include <qtextcodec.h>
-#include <qwidget.h>
-#include <qvarlengtharray.h>
-#include <qdebug.h>
-#include <qcoreapplication.h>
-#include <qmath.h>
-
-#include <private/qfont_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qfontengine_coretext_p.h>
-#include <private/qfontengine_mac_p.h>
-#include <private/qnumeric_p.h>
-#include <private/qpainter_p.h>
-#include <private/qpainterpath_p.h>
-#include <private/qpixmap_mac_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qtextengine_p.h>
-#include <private/qwidget_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-
-#include <string.h>
-
-QT_BEGIN_NAMESPACE
-
-extern int qt_antialiasing_threshold; // QApplication.cpp
-
-/*****************************************************************************
- External functions
- *****************************************************************************/
-extern CGImageRef qt_mac_create_imagemask(const QPixmap &px, const QRectF &sr); //qpixmap_mac.cpp
-extern QPoint qt_mac_posInWindow(const QWidget *w); //qwidget_mac.cpp
-extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
-extern CGContextRef qt_mac_cg_context(const QPaintDevice *); //qpaintdevice_mac.cpp
-extern void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-extern QPixmap qt_pixmapForBrush(int, bool); //qbrush.cpp
-
-void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform);
-
-
-//Implemented for qt_mac_p.h
-QMacCGContext::QMacCGContext(QPainter *p)
-{
- QPaintEngine *pe = p->paintEngine();
- if (pe->type() == QPaintEngine::MacPrinter)
- pe = static_cast<QMacPrintEngine*>(pe)->paintEngine();
- pe->syncState();
- context = 0;
- if(pe->type() == QPaintEngine::CoreGraphics)
- context = static_cast<QCoreGraphicsPaintEngine*>(pe)->handle();
-
- int devType = p->device()->devType();
- if (pe->type() == QPaintEngine::Raster
- && (devType == QInternal::Widget ||
- devType == QInternal::Pixmap ||
- devType == QInternal::Image)) {
-
- extern CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice);
- CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pe->paintDevice());
- uint flags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- flags |= kCGBitmapByteOrder32Host;
-#endif
- const QImage *image = (const QImage *) pe->paintDevice();
-
- context = CGBitmapContextCreate((void *) image->bits(), image->width(), image->height(),
- 8, image->bytesPerLine(), colorspace, flags);
-
- CGContextTranslateCTM(context, 0, image->height());
- CGContextScaleCTM(context, 1, -1);
-
- if (devType == QInternal::Widget) {
- QRegion clip = p->paintEngine()->systemClip();
- QTransform native = p->deviceTransform();
- QTransform logical = p->combinedTransform();
-
- if (p->hasClipping()) {
- QRegion r = p->clipRegion();
- r.translate(native.dx(), native.dy());
- if (clip.isEmpty())
- clip = r;
- else
- clip &= r;
- }
- qt_mac_clip_cg(context, clip, 0);
-
- CGContextTranslateCTM(context, native.dx(), native.dy());
- }
- } else {
- CGContextRetain(context);
- }
-}
-
-
-/*****************************************************************************
- QCoreGraphicsPaintEngine utility functions
- *****************************************************************************/
-
-//conversion
-inline static float qt_mac_convert_color_to_cg(int c) { return ((float)c * 1000 / 255) / 1000; }
-inline static int qt_mac_convert_color_from_cg(float c) { return qRound(c * 255); }
-CGAffineTransform qt_mac_convert_transform_to_cg(const QTransform &t) {
- return CGAffineTransformMake(t.m11(), t.m12(), t.m21(), t.m22(), t.dx(), t.dy());
-}
-
-CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
-{
- bool isWidget = (paintDevice->devType() == QInternal::Widget);
- return QCoreGraphicsPaintEngine::macDisplayColorSpace(isWidget ? static_cast<const QWidget *>(paintDevice)
- : 0);
-}
-
-inline static QCFType<CGColorRef> cgColorForQColor(const QColor &col, QPaintDevice *pdev)
-{
- CGFloat components[] = {
- qt_mac_convert_color_to_cg(col.red()),
- qt_mac_convert_color_to_cg(col.green()),
- qt_mac_convert_color_to_cg(col.blue()),
- qt_mac_convert_color_to_cg(col.alpha())
- };
- return CGColorCreate(qt_mac_colorSpaceForDeviceType(pdev), components);
-}
-
-// There's architectural problems with using native gradients
-// on the Mac at the moment, so disable them.
-// #define QT_MAC_USE_NATIVE_GRADIENTS
-
-#ifdef QT_MAC_USE_NATIVE_GRADIENTS
-static bool drawGradientNatively(const QGradient *gradient)
-{
- return gradient->spread() == QGradient::PadSpread;
-}
-
-// gradiant callback
-static void qt_mac_color_gradient_function(void *info, const CGFloat *in, CGFloat *out)
-{
- QBrush *brush = static_cast<QBrush *>(info);
- Q_ASSERT(brush && brush->gradient());
-
- const QGradientStops stops = brush->gradient()->stops();
- const int n = stops.count();
- Q_ASSERT(n >= 1);
- const QGradientStop *begin = stops.constBegin();
- const QGradientStop *end = begin + n;
-
- qreal p = in[0];
- const QGradientStop *i = begin;
- while (i != end && i->first < p)
- ++i;
-
- QRgb c;
- if (i == begin) {
- c = begin->second.rgba();
- } else if (i == end) {
- c = (end - 1)->second.rgba();
- } else {
- const QGradientStop &s1 = *(i - 1);
- const QGradientStop &s2 = *i;
- qreal p1 = s1.first;
- qreal p2 = s2.first;
- QRgb c1 = s1.second.rgba();
- QRgb c2 = s2.second.rgba();
- int idist = 256 * (p - p1) / (p2 - p1);
- int dist = 256 - idist;
- c = qRgba(INTERPOLATE_PIXEL_256(qRed(c1), dist, qRed(c2), idist),
- INTERPOLATE_PIXEL_256(qGreen(c1), dist, qGreen(c2), idist),
- INTERPOLATE_PIXEL_256(qBlue(c1), dist, qBlue(c2), idist),
- INTERPOLATE_PIXEL_256(qAlpha(c1), dist, qAlpha(c2), idist));
- }
-
- out[0] = qt_mac_convert_color_to_cg(qRed(c));
- out[1] = qt_mac_convert_color_to_cg(qGreen(c));
- out[2] = qt_mac_convert_color_to_cg(qBlue(c));
- out[3] = qt_mac_convert_color_to_cg(qAlpha(c));
-}
-#endif
-
-//clipping handling
-void QCoreGraphicsPaintEnginePrivate::resetClip()
-{
- static bool inReset = false;
- if (inReset)
- return;
- inReset = true;
-
- CGAffineTransform old_xform = CGContextGetCTM(hd);
-
- //setup xforms
- CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
- while (stackCount > 0) {
- restoreGraphicsState();
- }
- saveGraphicsState();
- inReset = false;
- //reset xforms
- CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
- CGContextConcatCTM(hd, old_xform);
-}
-
-static CGRect qt_mac_compose_rect(const QRectF &r, float off=0)
-{
- return CGRectMake(r.x()+off, r.y()+off, r.width(), r.height());
-}
-
-static CGMutablePathRef qt_mac_compose_path(const QPainterPath &p, float off=0)
-{
- CGMutablePathRef ret = CGPathCreateMutable();
- QPointF startPt;
- for (int i=0; i<p.elementCount(); ++i) {
- const QPainterPath::Element &elm = p.elementAt(i);
- switch (elm.type) {
- case QPainterPath::MoveToElement:
- if(i > 0
- && p.elementAt(i - 1).x == startPt.x()
- && p.elementAt(i - 1).y == startPt.y())
- CGPathCloseSubpath(ret);
- startPt = QPointF(elm.x, elm.y);
- CGPathMoveToPoint(ret, 0, elm.x+off, elm.y+off);
- break;
- case QPainterPath::LineToElement:
- CGPathAddLineToPoint(ret, 0, elm.x+off, elm.y+off);
- break;
- case QPainterPath::CurveToElement:
- Q_ASSERT(p.elementAt(i+1).type == QPainterPath::CurveToDataElement);
- Q_ASSERT(p.elementAt(i+2).type == QPainterPath::CurveToDataElement);
- CGPathAddCurveToPoint(ret, 0,
- elm.x+off, elm.y+off,
- p.elementAt(i+1).x+off, p.elementAt(i+1).y+off,
- p.elementAt(i+2).x+off, p.elementAt(i+2).y+off);
- i+=2;
- break;
- default:
- qFatal("QCoreGraphicsPaintEngine::drawPath(), unhandled type: %d", elm.type);
- break;
- }
- }
- if(!p.isEmpty()
- && p.elementAt(p.elementCount() - 1).x == startPt.x()
- && p.elementAt(p.elementCount() - 1).y == startPt.y())
- CGPathCloseSubpath(ret);
- return ret;
-}
-
-CGColorSpaceRef QCoreGraphicsPaintEngine::m_genericColorSpace = 0;
-QHash<CGDirectDisplayID, CGColorSpaceRef> QCoreGraphicsPaintEngine::m_displayColorSpaceHash;
-bool QCoreGraphicsPaintEngine::m_postRoutineRegistered = false;
-
-CGColorSpaceRef QCoreGraphicsPaintEngine::macGenericColorSpace()
-{
-#if 0
- if (!m_genericColorSpace) {
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
- m_genericColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
- } else
-#endif
- {
- m_genericColorSpace = CGColorSpaceCreateDeviceRGB();
- }
- if (!m_postRoutineRegistered) {
- m_postRoutineRegistered = true;
- qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
- }
- }
- return m_genericColorSpace;
-#else
- // Just return the main display colorspace for the moment.
- return macDisplayColorSpace();
-#endif
-}
-
-/*
- Ideally, we should pass the widget in here, and use CGGetDisplaysWithRect() etc.
- to support multiple displays correctly.
-*/
-CGColorSpaceRef QCoreGraphicsPaintEngine::macDisplayColorSpace(const QWidget *widget)
-{
- CGColorSpaceRef colorSpace;
-
- CGDirectDisplayID displayID;
- CMProfileRef displayProfile = 0;
- if (widget == 0) {
- displayID = CGMainDisplayID();
- } else {
- const QRect &qrect = widget->window()->geometry();
- CGRect rect = CGRectMake(qrect.x(), qrect.y(), qrect.width(), qrect.height());
- CGDisplayCount throwAway;
- CGDisplayErr dErr = CGGetDisplaysWithRect(rect, 1, &displayID, &throwAway);
- if (dErr != kCGErrorSuccess)
- return macDisplayColorSpace(0); // fall back on main display
- }
- if ((colorSpace = m_displayColorSpaceHash.value(displayID)))
- return colorSpace;
-
- CMError err = CMGetProfileByAVID((CMDisplayIDType)displayID, &displayProfile);
- if (err == noErr) {
- colorSpace = CGColorSpaceCreateWithPlatformColorSpace(displayProfile);
- } else if (widget) {
- return macDisplayColorSpace(0); // fall back on main display
- }
-
- if (colorSpace == 0)
- colorSpace = CGColorSpaceCreateDeviceRGB();
-
- m_displayColorSpaceHash.insert(displayID, colorSpace);
- CMCloseProfile(displayProfile);
- if (!m_postRoutineRegistered) {
- m_postRoutineRegistered = true;
- qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
- }
- return colorSpace;
-}
-
-void QCoreGraphicsPaintEngine::cleanUpMacColorSpaces()
-{
- if (m_genericColorSpace) {
- CFRelease(m_genericColorSpace);
- m_genericColorSpace = 0;
- }
- QHash<CGDirectDisplayID, CGColorSpaceRef>::const_iterator it = m_displayColorSpaceHash.constBegin();
- while (it != m_displayColorSpaceHash.constEnd()) {
- if (it.value())
- CFRelease(it.value());
- ++it;
- }
- m_displayColorSpaceHash.clear();
-}
-
-void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
-{
- CGAffineTransform old_xform = CGAffineTransformIdentity;
- if(orig_xform) { //setup xforms
- old_xform = CGContextGetCTM(hd);
- CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
- CGContextConcatCTM(hd, *orig_xform);
- }
-
- //do the clipping
- CGContextBeginPath(hd);
- if(rgn.isEmpty()) {
- CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
- } else {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- QCFType<HIMutableShapeRef> shape = rgn.toHIMutableShape();
- Q_ASSERT(!HIShapeIsEmpty(shape));
- HIShapeReplacePathInCGContext(shape, hd);
- } else
-#endif
- {
- QVector<QRect> rects = rgn.rects();
- const int count = rects.size();
- for(int i = 0; i < count; i++) {
- const QRect &r = rects[i];
- CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
- CGContextAddRect(hd, mac_r);
- }
- }
-
- }
- CGContextClip(hd);
-
- if(orig_xform) {//reset xforms
- CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
- CGContextConcatCTM(hd, old_xform);
- }
-}
-
-
-//pattern handling (tiling)
-#if 1
-# define QMACPATTERN_MASK_MULTIPLIER 32
-#else
-# define QMACPATTERN_MASK_MULTIPLIER 1
-#endif
-class QMacPattern
-{
-public:
- QMacPattern() : as_mask(false), pdev(0), image(0) { data.bytes = 0; }
- ~QMacPattern() { CGImageRelease(image); }
- int width() {
- if(image)
- return CGImageGetWidth(image);
- if(data.bytes)
- return 8*QMACPATTERN_MASK_MULTIPLIER;
- return data.pixmap.width();
- }
- int height() {
- if(image)
- return CGImageGetHeight(image);
- if(data.bytes)
- return 8*QMACPATTERN_MASK_MULTIPLIER;
- return data.pixmap.height();
- }
-
- //input
- QColor foreground;
- bool as_mask;
- struct {
- QPixmap pixmap;
- const uchar *bytes;
- } data;
- QPaintDevice *pdev;
- //output
- CGImageRef image;
-};
-static void qt_mac_draw_pattern(void *info, CGContextRef c)
-{
- QMacPattern *pat = (QMacPattern*)info;
- int w = 0, h = 0;
- bool isBitmap = (pat->data.pixmap.depth() == 1);
- if(!pat->image) { //lazy cache
- if(pat->as_mask) {
- Q_ASSERT(pat->data.bytes);
- w = h = 8;
-#if (QMACPATTERN_MASK_MULTIPLIER == 1)
- CGDataProviderRef provider = CGDataProviderCreateWithData(0, pat->data.bytes, w*h, 0);
- pat->image = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
- CGDataProviderRelease(provider);
-#else
- const int numBytes = (w*h)/sizeof(uchar);
- uchar xor_bytes[numBytes];
- for(int i = 0; i < numBytes; ++i)
- xor_bytes[i] = pat->data.bytes[i] ^ 0xFF;
- CGDataProviderRef provider = CGDataProviderCreateWithData(0, xor_bytes, w*h, 0);
- CGImageRef swatch = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
- CGDataProviderRelease(provider);
-
- const QColor c0(0, 0, 0, 0), c1(255, 255, 255, 255);
- QPixmap pm(w*QMACPATTERN_MASK_MULTIPLIER, h*QMACPATTERN_MASK_MULTIPLIER);
- pm.fill(c0);
- CGContextRef pm_ctx = qt_mac_cg_context(&pm);
- CGContextSetFillColorWithColor(c, cgColorForQColor(c1, pat->pdev));
- CGRect rect = CGRectMake(0, 0, w, h);
- for(int x = 0; x < QMACPATTERN_MASK_MULTIPLIER; ++x) {
- rect.origin.x = x * w;
- for(int y = 0; y < QMACPATTERN_MASK_MULTIPLIER; ++y) {
- rect.origin.y = y * h;
- qt_mac_drawCGImage(pm_ctx, &rect, swatch);
- }
- }
- pat->image = qt_mac_create_imagemask(pm, pm.rect());
- CGImageRelease(swatch);
- CGContextRelease(pm_ctx);
- w *= QMACPATTERN_MASK_MULTIPLIER;
- h *= QMACPATTERN_MASK_MULTIPLIER;
-#endif
- } else {
- w = pat->data.pixmap.width();
- h = pat->data.pixmap.height();
- if (isBitmap)
- pat->image = qt_mac_create_imagemask(pat->data.pixmap, pat->data.pixmap.rect());
- else
- pat->image = (CGImageRef)pat->data.pixmap.macCGHandle();
- }
- } else {
- w = CGImageGetWidth(pat->image);
- h = CGImageGetHeight(pat->image);
- }
-
- //draw
- bool needRestore = false;
- if (CGImageIsMask(pat->image)) {
- CGContextSaveGState(c);
- CGContextSetFillColorWithColor(c, cgColorForQColor(pat->foreground, pat->pdev));
- }
- CGRect rect = CGRectMake(0, 0, w, h);
- qt_mac_drawCGImage(c, &rect, pat->image);
- if(needRestore)
- CGContextRestoreGState(c);
-}
-static void qt_mac_dispose_pattern(void *info)
-{
- QMacPattern *pat = (QMacPattern*)info;
- delete pat;
-}
-
-/*****************************************************************************
- QCoreGraphicsPaintEngine member functions
- *****************************************************************************/
-
-inline static QPaintEngine::PaintEngineFeatures qt_mac_cg_features()
-{
- return QPaintEngine::PaintEngineFeatures(QPaintEngine::AllFeatures & ~QPaintEngine::PaintOutsidePaintEvent
- & ~QPaintEngine::PerspectiveTransform
- & ~QPaintEngine::ConicalGradientFill
- & ~QPaintEngine::LinearGradientFill
- & ~QPaintEngine::RadialGradientFill
- & ~QPaintEngine::BrushStroke);
-}
-
-QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine()
-: QPaintEngine(*(new QCoreGraphicsPaintEnginePrivate), qt_mac_cg_features())
-{
-}
-
-QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr)
-: QPaintEngine(dptr, qt_mac_cg_features())
-{
-}
-
-QCoreGraphicsPaintEngine::~QCoreGraphicsPaintEngine()
-{
-}
-
-bool
-QCoreGraphicsPaintEngine::begin(QPaintDevice *pdev)
-{
- Q_D(QCoreGraphicsPaintEngine);
- if(isActive()) { // already active painting
- qWarning("QCoreGraphicsPaintEngine::begin: Painter already active");
- return false;
- }
-
- //initialization
- d->pdev = pdev;
- d->complexXForm = false;
- d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
- d->cosmeticPenSize = 1;
- d->current.clipEnabled = false;
- d->pixelSize = QPoint(1,1);
- d->hd = qt_mac_cg_context(pdev);
- if(d->hd) {
- d->saveGraphicsState();
- d->orig_xform = CGContextGetCTM(d->hd);
- if (d->shading) {
- CGShadingRelease(d->shading);
- d->shading = 0;
- }
- d->setClip(0); //clear the context's clipping
- }
-
- setActive(true);
-
- if(d->pdev->devType() == QInternal::Widget) { // device is a widget
- QWidget *w = (QWidget*)d->pdev;
- bool unclipped = w->testAttribute(Qt::WA_PaintUnclipped);
-
- if((w->windowType() == Qt::Desktop)) {
- if(!unclipped)
- qWarning("QCoreGraphicsPaintEngine::begin: Does not support clipped desktop on Mac OS X");
- // ## need to do [qt_mac_window_for(w) makeKeyAndOrderFront]; (need to rename the file)
- } else if(unclipped) {
- qWarning("QCoreGraphicsPaintEngine::begin: Does not support unclipped painting");
- }
- } else if(d->pdev->devType() == QInternal::Pixmap) { // device is a pixmap
- QPixmap *pm = (QPixmap*)d->pdev;
- if(pm->isNull()) {
- qWarning("QCoreGraphicsPaintEngine::begin: Cannot paint null pixmap");
- end();
- return false;
- }
- }
-
- setDirty(QPaintEngine::DirtyPen);
- setDirty(QPaintEngine::DirtyBrush);
- setDirty(QPaintEngine::DirtyBackground);
- setDirty(QPaintEngine::DirtyHints);
- return true;
-}
-
-bool
-QCoreGraphicsPaintEngine::end()
-{
- Q_D(QCoreGraphicsPaintEngine);
- setActive(false);
- if(d->pdev->devType() == QInternal::Widget && static_cast<QWidget*>(d->pdev)->windowType() == Qt::Desktop) {
-#ifndef QT_MAC_USE_COCOA
- HideWindow(qt_mac_window_for(static_cast<QWidget*>(d->pdev)));
-#else
-// // ### need to do [qt_mac_window_for(static_cast<QWidget *>(d->pdev)) orderOut]; (need to rename)
-#endif
-
- }
- if(d->shading) {
- CGShadingRelease(d->shading);
- d->shading = 0;
- }
- d->pdev = 0;
- if(d->hd) {
- d->restoreGraphicsState();
- CGContextSynchronize(d->hd);
- CGContextRelease(d->hd);
- d->hd = 0;
- }
- return true;
-}
-
-void
-QCoreGraphicsPaintEngine::updateState(const QPaintEngineState &state)
-{
- Q_D(QCoreGraphicsPaintEngine);
- QPaintEngine::DirtyFlags flags = state.state();
-
- if (flags & DirtyTransform)
- updateMatrix(state.transform());
-
- if (flags & DirtyClipEnabled) {
- if (state.isClipEnabled())
- updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
- else
- updateClipPath(QPainterPath(), Qt::NoClip);
- }
-
- if (flags & DirtyClipPath) {
- updateClipPath(state.clipPath(), state.clipOperation());
- } else if (flags & DirtyClipRegion) {
- updateClipRegion(state.clipRegion(), state.clipOperation());
- }
-
- // If the clip has changed we need to update all other states
- // too, since they are included in the system context on OSX,
- // and changing the clip resets that context back to scratch.
- if (flags & (DirtyClipPath | DirtyClipRegion | DirtyClipEnabled))
- flags |= AllDirty;
-
- if (flags & DirtyPen)
- updatePen(state.pen());
- if (flags & (DirtyBrush|DirtyBrushOrigin))
- updateBrush(state.brush(), state.brushOrigin());
- if (flags & DirtyFont)
- updateFont(state.font());
- if (flags & DirtyOpacity)
- updateOpacity(state.opacity());
- if (flags & DirtyHints)
- updateRenderHints(state.renderHints());
- if (flags & DirtyCompositionMode)
- updateCompositionMode(state.compositionMode());
-
- if (flags & (DirtyPen | DirtyTransform)) {
- if (!d->current.pen.isCosmetic()) {
- d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticNone;
- } else if (d->current.transform.m11() < d->current.transform.m22()-1.0 ||
- d->current.transform.m11() > d->current.transform.m22()+1.0) {
- d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath;
- d->cosmeticPenSize = d->adjustPenWidth(d->current.pen.widthF());
- if (!d->cosmeticPenSize)
- d->cosmeticPenSize = 1.0;
- } else {
- d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
- static const float sqrt2 = sqrt(2);
- qreal width = d->current.pen.widthF();
- if (!width)
- width = 1;
- d->cosmeticPenSize = sqrt(pow(d->pixelSize.y(), 2) + pow(d->pixelSize.x(), 2)) / sqrt2 * width;
- }
- }
-}
-
-void
-QCoreGraphicsPaintEngine::updatePen(const QPen &pen)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
- d->current.pen = pen;
- d->setStrokePen(pen);
-}
-
-void
-QCoreGraphicsPaintEngine::updateBrush(const QBrush &brush, const QPointF &brushOrigin)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
- d->current.brush = brush;
-
-#ifdef QT_MAC_USE_NATIVE_GRADIENTS
- // Quartz supports only pad spread
- if (const QGradient *gradient = brush.gradient()) {
- if (drawGradientNatively(gradient)) {
- gccaps |= QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill;
- } else {
- gccaps &= ~(QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill);
- }
- }
-#endif
-
- if (d->shading) {
- CGShadingRelease(d->shading);
- d->shading = 0;
- }
- d->setFillBrush(brushOrigin);
-}
-
-void
-QCoreGraphicsPaintEngine::updateOpacity(qreal opacity)
-{
- Q_D(QCoreGraphicsPaintEngine);
- CGContextSetAlpha(d->hd, opacity);
-}
-
-void
-QCoreGraphicsPaintEngine::updateFont(const QFont &)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
- updatePen(d->current.pen);
-}
-
-void
-QCoreGraphicsPaintEngine::updateMatrix(const QTransform &transform)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (qt_is_nan(transform.m11()) || qt_is_nan(transform.m12()) || qt_is_nan(transform.m13())
- || qt_is_nan(transform.m21()) || qt_is_nan(transform.m22()) || qt_is_nan(transform.m23())
- || qt_is_nan(transform.m31()) || qt_is_nan(transform.m32()) || qt_is_nan(transform.m33()))
- return;
-
- d->current.transform = transform;
- d->setTransform(transform.isIdentity() ? 0 : &transform);
- d->complexXForm = (transform.m11() != 1 || transform.m22() != 1
- || transform.m12() != 0 || transform.m21() != 0);
- d->pixelSize = d->devicePixelSize(d->hd);
-}
-
-void
-QCoreGraphicsPaintEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
- if(op == Qt::NoClip) {
- if(d->current.clipEnabled) {
- d->current.clipEnabled = false;
- d->current.clip = QRegion();
- d->setClip(0);
- }
- } else {
- if(!d->current.clipEnabled)
- op = Qt::ReplaceClip;
- d->current.clipEnabled = true;
- QRegion clipRegion(p.toFillPolygon().toPolygon(), p.fillRule());
- if(op == Qt::ReplaceClip) {
- d->current.clip = clipRegion;
- d->setClip(0);
- if(p.isEmpty()) {
- CGRect rect = CGRectMake(0, 0, 0, 0);
- CGContextClipToRect(d->hd, rect);
- } else {
- CGMutablePathRef path = qt_mac_compose_path(p);
- CGContextBeginPath(d->hd);
- CGContextAddPath(d->hd, path);
- if(p.fillRule() == Qt::WindingFill)
- CGContextClip(d->hd);
- else
- CGContextEOClip(d->hd);
- CGPathRelease(path);
- }
- } else if(op == Qt::IntersectClip) {
- d->current.clip = d->current.clip.intersected(clipRegion);
- d->setClip(&d->current.clip);
- } else if(op == Qt::UniteClip) {
- d->current.clip = d->current.clip.united(clipRegion);
- d->setClip(&d->current.clip);
- }
- }
-}
-
-void
-QCoreGraphicsPaintEngine::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
- if(op == Qt::NoClip) {
- d->current.clipEnabled = false;
- d->current.clip = QRegion();
- d->setClip(0);
- } else {
- if(!d->current.clipEnabled)
- op = Qt::ReplaceClip;
- d->current.clipEnabled = true;
- if(op == Qt::IntersectClip)
- d->current.clip = d->current.clip.intersected(clipRegion);
- else if(op == Qt::ReplaceClip)
- d->current.clip = clipRegion;
- else if(op == Qt::UniteClip)
- d->current.clip = d->current.clip.united(clipRegion);
- d->setClip(&d->current.clip);
- }
-}
-
-void
-QCoreGraphicsPaintEngine::drawPath(const QPainterPath &p)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- CGMutablePathRef path = qt_mac_compose_path(p);
- uchar ops = QCoreGraphicsPaintEnginePrivate::CGStroke;
- if(p.fillRule() == Qt::WindingFill)
- ops |= QCoreGraphicsPaintEnginePrivate::CGFill;
- else
- ops |= QCoreGraphicsPaintEnginePrivate::CGEOFill;
- CGContextBeginPath(d->hd);
- d->drawPath(ops, path);
- CGPathRelease(path);
-}
-
-void
-QCoreGraphicsPaintEngine::drawRects(const QRectF *rects, int rectCount)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- for (int i=0; i<rectCount; ++i) {
- QRectF r = rects[i];
-
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathAddRect(path, 0, qt_mac_compose_rect(r));
- d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill|QCoreGraphicsPaintEnginePrivate::CGStroke,
- path);
- CGPathRelease(path);
- }
-}
-
-void
-QCoreGraphicsPaintEngine::drawPoints(const QPointF *points, int pointCount)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- if (d->current.pen.capStyle() == Qt::FlatCap)
- CGContextSetLineCap(d->hd, kCGLineCapSquare);
-
- CGMutablePathRef path = CGPathCreateMutable();
- for(int i=0; i < pointCount; i++) {
- float x = points[i].x(), y = points[i].y();
- CGPathMoveToPoint(path, 0, x, y);
- CGPathAddLineToPoint(path, 0, x+0.001, y);
- }
-
- bool doRestore = false;
- if(d->cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticNone && !(state->renderHints() & QPainter::Antialiasing)) {
- //we don't want adjusted pens for point rendering
- doRestore = true;
- d->saveGraphicsState();
- CGContextSetLineWidth(d->hd, d->current.pen.widthF());
- }
- d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
- if (doRestore)
- d->restoreGraphicsState();
- CGPathRelease(path);
- if (d->current.pen.capStyle() == Qt::FlatCap)
- CGContextSetLineCap(d->hd, kCGLineCapButt);
-}
-
-void
-QCoreGraphicsPaintEngine::drawEllipse(const QRectF &r)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- CGMutablePathRef path = CGPathCreateMutable();
- CGAffineTransform transform = CGAffineTransformMakeScale(r.width() / r.height(), 1);
- CGPathAddArc(path, &transform,(r.x() + (r.width() / 2)) / (r.width() / r.height()),
- r.y() + (r.height() / 2), r.height() / 2, 0, (2 * M_PI), false);
- d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill | QCoreGraphicsPaintEnginePrivate::CGStroke,
- path);
- CGPathRelease(path);
-}
-
-void
-QCoreGraphicsPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathMoveToPoint(path, 0, points[0].x(), points[0].y());
- for(int x = 1; x < pointCount; ++x)
- CGPathAddLineToPoint(path, 0, points[x].x(), points[x].y());
- if(mode != PolylineMode && points[0] != points[pointCount-1])
- CGPathAddLineToPoint(path, 0, points[0].x(), points[0].y());
- uint op = QCoreGraphicsPaintEnginePrivate::CGStroke;
- if (mode != PolylineMode)
- op |= mode == OddEvenMode ? QCoreGraphicsPaintEnginePrivate::CGEOFill
- : QCoreGraphicsPaintEnginePrivate::CGFill;
- d->drawPath(op, path);
- CGPathRelease(path);
-}
-
-void
-QCoreGraphicsPaintEngine::drawLines(const QLineF *lines, int lineCount)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- CGMutablePathRef path = CGPathCreateMutable();
- for(int i = 0; i < lineCount; i++) {
- const QPointF start = lines[i].p1(), end = lines[i].p2();
- CGPathMoveToPoint(path, 0, start.x(), start.y());
- CGPathAddLineToPoint(path, 0, end.x(), end.y());
- }
- d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
- CGPathRelease(path);
-}
-
-void QCoreGraphicsPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- if(pm.isNull())
- return;
-
- bool differentSize = (QRectF(0, 0, pm.width(), pm.height()) != sr), doRestore = false;
- CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
- QCFType<CGImageRef> image;
- bool isBitmap = (pm.depth() == 1);
- if (isBitmap) {
- doRestore = true;
- d->saveGraphicsState();
-
- const QColor &col = d->current.pen.color();
- CGContextSetFillColorWithColor(d->hd, cgColorForQColor(col, d->pdev));
- image = qt_mac_create_imagemask(pm, sr);
- } else if (differentSize) {
- QCFType<CGImageRef> img = pm.toMacCGImageRef();
- image = CGImageCreateWithImageInRect(img, CGRectMake(qRound(sr.x()), qRound(sr.y()), qRound(sr.width()), qRound(sr.height())));
- } else {
- image = (CGImageRef)pm.macCGHandle();
- }
- qt_mac_drawCGImage(d->hd, &rect, image);
- if (doRestore)
- d->restoreGraphicsState();
-}
-
-static void drawImageReleaseData (void *info, const void *, size_t)
-{
- delete static_cast<QImage *>(info);
-}
-
-CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0)
-{
- QImage *image;
- if (img.depth() != 32)
- image = new QImage(img.convertToFormat(QImage::Format_ARGB32_Premultiplied));
- else
- image = new QImage(img);
-
- uint cgflags = kCGImageAlphaNone;
- switch (image->format()) {
- case QImage::Format_ARGB32_Premultiplied:
- cgflags = kCGImageAlphaPremultipliedFirst;
- break;
- case QImage::Format_ARGB32:
- cgflags = kCGImageAlphaFirst;
- break;
- case QImage::Format_RGB32:
- cgflags = kCGImageAlphaNoneSkipFirst;
- default:
- break;
- }
-#if defined(kCGBitmapByteOrder32Host) //only needed because CGImage.h added symbols in the minor version
- cgflags |= kCGBitmapByteOrder32Host;
-#endif
- QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(image,
- static_cast<const QImage *>(image)->bits(),
- image->byteCount(),
- drawImageReleaseData);
- if (imagePtr)
- *imagePtr = image;
- return CGImageCreate(image->width(), image->height(), 8, 32,
- image->bytesPerLine(),
- QCoreGraphicsPaintEngine::macGenericColorSpace(),
- cgflags, dataProvider, 0, false, kCGRenderingIntentDefault);
-
-}
-
-void QCoreGraphicsPaintEngine::drawImage(const QRectF &r, const QImage &img, const QRectF &sr,
- Qt::ImageConversionFlags flags)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_UNUSED(flags);
- Q_ASSERT(isActive());
-
- if (img.isNull() || state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- const QImage *image;
- QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(img, &image);
- CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
- if (QRectF(0, 0, img.width(), img.height()) != sr)
- cgimage = CGImageCreateWithImageInRect(cgimage, CGRectMake(sr.x(), sr.y(),
- sr.width(), sr.height()));
- qt_mac_drawCGImage(d->hd, &rect, cgimage);
-}
-
-void QCoreGraphicsPaintEngine::initialize()
-{
-}
-
-void QCoreGraphicsPaintEngine::cleanup()
-{
-}
-
-CGContextRef
-QCoreGraphicsPaintEngine::handle() const
-{
- return d_func()->hd;
-}
-
-void
-QCoreGraphicsPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap,
- const QPointF &p)
-{
- Q_D(QCoreGraphicsPaintEngine);
- Q_ASSERT(isActive());
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- //save the old state
- d->saveGraphicsState();
-
- //setup the pattern
- QMacPattern *qpattern = new QMacPattern;
- qpattern->data.pixmap = pixmap;
- qpattern->foreground = d->current.pen.color();
- qpattern->pdev = d->pdev;
- CGPatternCallbacks callbks;
- callbks.version = 0;
- callbks.drawPattern = qt_mac_draw_pattern;
- callbks.releaseInfo = qt_mac_dispose_pattern;
- const int width = qpattern->width(), height = qpattern->height();
- CGAffineTransform trans = CGContextGetCTM(d->hd);
- CGPatternRef pat = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
- trans, width, height,
- kCGPatternTilingNoDistortion, true, &callbks);
- CGColorSpaceRef cs = CGColorSpaceCreatePattern(0);
- CGContextSetFillColorSpace(d->hd, cs);
- CGFloat component = 1.0; //just one
- CGContextSetFillPattern(d->hd, pat, &component);
- CGSize phase = CGSizeApplyAffineTransform(CGSizeMake(-(p.x()-r.x()), -(p.y()-r.y())), trans);
- CGContextSetPatternPhase(d->hd, phase);
-
- //fill the rectangle
- CGRect mac_rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
- CGContextFillRect(d->hd, mac_rect);
-
- //restore the state
- d->restoreGraphicsState();
- //cleanup
- CGColorSpaceRelease(cs);
- CGPatternRelease(pat);
-}
-
-void QCoreGraphicsPaintEngine::drawTextItem(const QPointF &pos, const QTextItem &item)
-{
- Q_D(QCoreGraphicsPaintEngine);
- if (d->current.transform.type() == QTransform::TxProject
-#ifndef QMAC_NATIVE_GRADIENTS
- || painter()->pen().brush().gradient() //Just let the base engine "emulate" the gradient
-#endif
- ) {
- QPaintEngine::drawTextItem(pos, item);
- return;
- }
-
- if (state->compositionMode() == QPainter::CompositionMode_Destination)
- return;
-
- const QTextItemInt &ti = static_cast<const QTextItemInt &>(item);
-
- QPen oldPen = painter()->pen();
- QBrush oldBrush = painter()->brush();
- QPointF oldBrushOrigin = painter()->brushOrigin();
- updatePen(Qt::NoPen);
- updateBrush(oldPen.brush(), QPointF(0, 0));
-
- Q_ASSERT(type() == QPaintEngine::CoreGraphics);
-
- QFontEngine *fe = ti.fontEngine;
-
- const bool textAA = state->renderHints() & QPainter::TextAntialiasing && fe->fontDef.pointSize > qt_antialiasing_threshold && !(fe->fontDef.styleStrategy & QFont::NoAntialias);
- const bool lineAA = state->renderHints() & QPainter::Antialiasing;
- if(textAA != lineAA)
- CGContextSetShouldAntialias(d->hd, textAA);
-
- if (ti.glyphs.numGlyphs) {
- switch (fe->type()) {
- case QFontEngine::Mac:
-#ifdef QT_MAC_USE_COCOA
- static_cast<QCoreTextFontEngine *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
-#else
- static_cast<QFontEngineMac *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
-#endif
- break;
- case QFontEngine::Box:
- d->drawBoxTextItem(pos, ti);
- break;
- default:
- break;
- }
- }
-
- if(textAA != lineAA)
- CGContextSetShouldAntialias(d->hd, !textAA);
-
- updatePen(oldPen);
- updateBrush(oldBrush, oldBrushOrigin);
-}
-
-QPainter::RenderHints
-QCoreGraphicsPaintEngine::supportedRenderHints() const
-{
- return QPainter::RenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
-}
-enum CGCompositeMode {
- kCGCompositeModeClear = 0,
- kCGCompositeModeCopy = 1,
- kCGCompositeModeSourceOver = 2,
- kCGCompositeModeSourceIn = 3,
- kCGCompositeModeSourceOut = 4,
- kCGCompositeModeSourceAtop = 5,
- kCGCompositeModeDestinationOver = 6,
- kCGCompositeModeDestinationIn = 7,
- kCGCompositeModeDestinationOut = 8,
- kCGCompositeModeDestinationAtop = 9,
- kCGCompositeModeXOR = 10,
- kCGCompositeModePlusDarker = 11, // (max (0, (1-d) + (1-s)))
- kCGCompositeModePlusLighter = 12, // (min (1, s + d))
- };
-extern "C" {
- extern void CGContextSetCompositeOperation(CGContextRef, int);
-} // private function, but is in all versions of OS X.
-void
-QCoreGraphicsPaintEngine::updateCompositionMode(QPainter::CompositionMode mode)
-{
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- int cg_mode = kCGBlendModeNormal;
- switch(mode) {
- case QPainter::CompositionMode_Multiply:
- cg_mode = kCGBlendModeMultiply;
- break;
- case QPainter::CompositionMode_Screen:
- cg_mode = kCGBlendModeScreen;
- break;
- case QPainter::CompositionMode_Overlay:
- cg_mode = kCGBlendModeOverlay;
- break;
- case QPainter::CompositionMode_Darken:
- cg_mode = kCGBlendModeDarken;
- break;
- case QPainter::CompositionMode_Lighten:
- cg_mode = kCGBlendModeLighten;
- break;
- case QPainter::CompositionMode_ColorDodge:
- cg_mode = kCGBlendModeColorDodge;
- break;
- case QPainter::CompositionMode_ColorBurn:
- cg_mode = kCGBlendModeColorBurn;
- break;
- case QPainter::CompositionMode_HardLight:
- cg_mode = kCGBlendModeHardLight;
- break;
- case QPainter::CompositionMode_SoftLight:
- cg_mode = kCGBlendModeSoftLight;
- break;
- case QPainter::CompositionMode_Difference:
- cg_mode = kCGBlendModeDifference;
- break;
- case QPainter::CompositionMode_Exclusion:
- cg_mode = kCGBlendModeExclusion;
- break;
- case QPainter::CompositionMode_Plus:
- cg_mode = kCGBlendModePlusLighter;
- break;
- case QPainter::CompositionMode_SourceOver:
- cg_mode = kCGBlendModeNormal;
- break;
- case QPainter::CompositionMode_DestinationOver:
- cg_mode = kCGBlendModeDestinationOver;
- break;
- case QPainter::CompositionMode_Clear:
- cg_mode = kCGBlendModeClear;
- break;
- case QPainter::CompositionMode_Source:
- cg_mode = kCGBlendModeCopy;
- break;
- case QPainter::CompositionMode_Destination:
- cg_mode = -1;
- break;
- case QPainter::CompositionMode_SourceIn:
- cg_mode = kCGBlendModeSourceIn;
- break;
- case QPainter::CompositionMode_DestinationIn:
- cg_mode = kCGCompositeModeDestinationIn;
- break;
- case QPainter::CompositionMode_SourceOut:
- cg_mode = kCGBlendModeSourceOut;
- break;
- case QPainter::CompositionMode_DestinationOut:
- cg_mode = kCGBlendModeDestinationOver;
- break;
- case QPainter::CompositionMode_SourceAtop:
- cg_mode = kCGBlendModeSourceAtop;
- break;
- case QPainter::CompositionMode_DestinationAtop:
- cg_mode = kCGBlendModeDestinationAtop;
- break;
- case QPainter::CompositionMode_Xor:
- cg_mode = kCGBlendModeXOR;
- break;
- default:
- break;
- }
- if (cg_mode > -1) {
- CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
- }
- } else
-#endif
- // The standard porter duff ops.
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3
- && mode <= QPainter::CompositionMode_Xor) {
- int cg_mode = kCGCompositeModeCopy;
- switch (mode) {
- case QPainter::CompositionMode_SourceOver:
- cg_mode = kCGCompositeModeSourceOver;
- break;
- case QPainter::CompositionMode_DestinationOver:
- cg_mode = kCGCompositeModeDestinationOver;
- break;
- case QPainter::CompositionMode_Clear:
- cg_mode = kCGCompositeModeClear;
- break;
- default:
- qWarning("QCoreGraphicsPaintEngine: Unhandled composition mode %d", (int)mode);
- break;
- case QPainter::CompositionMode_Source:
- cg_mode = kCGCompositeModeCopy;
- break;
- case QPainter::CompositionMode_Destination:
- cg_mode = CGCompositeMode(-1);
- break;
- case QPainter::CompositionMode_SourceIn:
- cg_mode = kCGCompositeModeSourceIn;
- break;
- case QPainter::CompositionMode_DestinationIn:
- cg_mode = kCGCompositeModeDestinationIn;
- break;
- case QPainter::CompositionMode_SourceOut:
- cg_mode = kCGCompositeModeSourceOut;
- break;
- case QPainter::CompositionMode_DestinationOut:
- cg_mode = kCGCompositeModeDestinationOut;
- break;
- case QPainter::CompositionMode_SourceAtop:
- cg_mode = kCGCompositeModeSourceAtop;
- break;
- case QPainter::CompositionMode_DestinationAtop:
- cg_mode = kCGCompositeModeDestinationAtop;
- break;
- case QPainter::CompositionMode_Xor:
- cg_mode = kCGCompositeModeXOR;
- break;
- }
- if (cg_mode > -1)
- CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
- } else {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
- bool needPrivateAPI = false;
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
- int cg_mode = kCGBlendModeNormal;
- switch (mode) {
- case QPainter::CompositionMode_Multiply:
- cg_mode = kCGBlendModeMultiply;
- break;
- case QPainter::CompositionMode_Screen:
- cg_mode = kCGBlendModeScreen;
- break;
- case QPainter::CompositionMode_Overlay:
- cg_mode = kCGBlendModeOverlay;
- break;
- case QPainter::CompositionMode_Darken:
- cg_mode = kCGBlendModeDarken;
- break;
- case QPainter::CompositionMode_Lighten:
- cg_mode = kCGBlendModeLighten;
- break;
- case QPainter::CompositionMode_ColorDodge:
- cg_mode = kCGBlendModeColorDodge;
- break;
- case QPainter::CompositionMode_ColorBurn:
- cg_mode = kCGBlendModeColorBurn;
- break;
- case QPainter::CompositionMode_HardLight:
- cg_mode = kCGBlendModeHardLight;
- break;
- case QPainter::CompositionMode_SoftLight:
- cg_mode = kCGBlendModeSoftLight;
- break;
- case QPainter::CompositionMode_Difference:
- cg_mode = kCGBlendModeDifference;
- break;
- case QPainter::CompositionMode_Exclusion:
- cg_mode = kCGBlendModeExclusion;
- break;
- case QPainter::CompositionMode_Plus:
- needPrivateAPI = true;
- cg_mode = kCGCompositeModePlusLighter;
- break;
- default:
- break;
- }
- if (!needPrivateAPI)
- CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
- else
- CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
- }
-#endif
- }
-}
-
-void
-QCoreGraphicsPaintEngine::updateRenderHints(QPainter::RenderHints hints)
-{
- Q_D(QCoreGraphicsPaintEngine);
- CGContextSetShouldAntialias(d->hd, hints & QPainter::Antialiasing);
- static const CGFloat ScaleFactor = qt_mac_get_scalefactor();
- if (ScaleFactor > 1.) {
- CGContextSetInterpolationQuality(d->hd, kCGInterpolationHigh);
- } else {
- CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ?
- kCGInterpolationHigh : kCGInterpolationNone);
- }
- bool textAntialiasing = (hints & QPainter::TextAntialiasing) == QPainter::TextAntialiasing;
- if (!textAntialiasing || d->disabledSmoothFonts) {
- d->disabledSmoothFonts = !textAntialiasing;
- CGContextSetShouldSmoothFonts(d->hd, textAntialiasing);
- }
-}
-
-/*
- Returns the size of one device pixel in user-space coordinates.
-*/
-QPointF QCoreGraphicsPaintEnginePrivate::devicePixelSize(CGContextRef)
-{
- QPointF p1 = current.transform.inverted().map(QPointF(0, 0));
- QPointF p2 = current.transform.inverted().map(QPointF(1, 1));
- return QPointF(qAbs(p2.x() - p1.x()), qAbs(p2.y() - p1.y()));
-}
-
-/*
- Adjusts the pen width so we get correct line widths in the
- non-transformed, aliased case.
-*/
-float QCoreGraphicsPaintEnginePrivate::adjustPenWidth(float penWidth)
-{
- Q_Q(QCoreGraphicsPaintEngine);
- float ret = penWidth;
- if (!complexXForm && !(q->state->renderHints() & QPainter::Antialiasing)) {
- if (penWidth < 2)
- ret = 1;
- else if (penWidth < 3)
- ret = 1.5;
- else
- ret = penWidth -1;
- }
- return ret;
-}
-
-void
-QCoreGraphicsPaintEnginePrivate::setStrokePen(const QPen &pen)
-{
- //pencap
- CGLineCap cglinecap = kCGLineCapButt;
- if(pen.capStyle() == Qt::SquareCap)
- cglinecap = kCGLineCapSquare;
- else if(pen.capStyle() == Qt::RoundCap)
- cglinecap = kCGLineCapRound;
- CGContextSetLineCap(hd, cglinecap);
- CGContextSetLineWidth(hd, adjustPenWidth(pen.widthF()));
-
- //join
- CGLineJoin cglinejoin = kCGLineJoinMiter;
- if(pen.joinStyle() == Qt::BevelJoin)
- cglinejoin = kCGLineJoinBevel;
- else if(pen.joinStyle() == Qt::RoundJoin)
- cglinejoin = kCGLineJoinRound;
- CGContextSetLineJoin(hd, cglinejoin);
-// CGContextSetMiterLimit(hd, pen.miterLimit());
-
- //pen style
- QVector<CGFloat> linedashes;
- if(pen.style() == Qt::CustomDashLine) {
- QVector<qreal> customs = pen.dashPattern();
- for(int i = 0; i < customs.size(); ++i)
- linedashes.append(customs.at(i));
- } else if(pen.style() == Qt::DashLine) {
- linedashes.append(4);
- linedashes.append(2);
- } else if(pen.style() == Qt::DotLine) {
- linedashes.append(1);
- linedashes.append(2);
- } else if(pen.style() == Qt::DashDotLine) {
- linedashes.append(4);
- linedashes.append(2);
- linedashes.append(1);
- linedashes.append(2);
- } else if(pen.style() == Qt::DashDotDotLine) {
- linedashes.append(4);
- linedashes.append(2);
- linedashes.append(1);
- linedashes.append(2);
- linedashes.append(1);
- linedashes.append(2);
- }
- const CGFloat cglinewidth = pen.widthF() <= 0.0f ? 1.0f : float(pen.widthF());
- for(int i = 0; i < linedashes.size(); ++i) {
- linedashes[i] *= cglinewidth;
- if(cglinewidth < 3 && (cglinecap == kCGLineCapSquare || cglinecap == kCGLineCapRound)) {
- if((i%2))
- linedashes[i] += cglinewidth/2;
- else
- linedashes[i] -= cglinewidth/2;
- }
- }
- CGContextSetLineDash(hd, pen.dashOffset() * cglinewidth, linedashes.data(), linedashes.size());
-
- // color
- CGContextSetStrokeColorWithColor(hd, cgColorForQColor(pen.color(), pdev));
-}
-
-// Add our own patterns here to deal with the fact that the coordinate system
-// is flipped vertically with Quartz2D.
-static const uchar *qt_mac_patternForBrush(int brushStyle)
-{
- Q_ASSERT(brushStyle > Qt::SolidPattern && brushStyle < Qt::LinearGradientPattern);
- static const uchar dense1_pat[] = { 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x44, 0x00 };
- static const uchar dense2_pat[] = { 0x00, 0x22, 0x00, 0x88, 0x00, 0x22, 0x00, 0x88 };
- static const uchar dense3_pat[] = { 0x11, 0xaa, 0x44, 0xaa, 0x11, 0xaa, 0x44, 0xaa };
- static const uchar dense4_pat[] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 };
- static const uchar dense5_pat[] = { 0xee, 0x55, 0xbb, 0x55, 0xee, 0x55, 0xbb, 0x55 };
- static const uchar dense6_pat[] = { 0xff, 0xdd, 0xff, 0x77, 0xff, 0xdd, 0xff, 0x77 };
- static const uchar dense7_pat[] = { 0xff, 0xff, 0xbb, 0xff, 0xff, 0xff, 0xbb, 0xff };
- static const uchar hor_pat[] = { 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff };
- static const uchar ver_pat[] = { 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef };
- static const uchar cross_pat[] = { 0xef, 0xef, 0xef, 0xef, 0x00, 0xef, 0xef, 0xef };
- static const uchar fdiag_pat[] = { 0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0xfe };
- static const uchar bdiag_pat[] = { 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f };
- static const uchar dcross_pat[] = { 0x7e, 0xbd, 0xdb, 0xe7, 0xe7, 0xdb, 0xbd, 0x7e };
- static const uchar *const pat_tbl[] = {
- dense1_pat, dense2_pat, dense3_pat, dense4_pat, dense5_pat,
- dense6_pat, dense7_pat,
- hor_pat, ver_pat, cross_pat, bdiag_pat, fdiag_pat, dcross_pat };
- return pat_tbl[brushStyle - Qt::Dense1Pattern];
-}
-
-void QCoreGraphicsPaintEnginePrivate::setFillBrush(const QPointF &offset)
-{
- // pattern
- Qt::BrushStyle bs = current.brush.style();
-#ifdef QT_MAC_USE_NATIVE_GRADIENTS
- if (bs == Qt::LinearGradientPattern || bs == Qt::RadialGradientPattern) {
- const QGradient *grad = static_cast<const QGradient*>(current.brush.gradient());
- if (drawGradientNatively(grad)) {
- Q_ASSERT(grad->spread() == QGradient::PadSpread);
-
- static const CGFloat domain[] = { 0.0f, +1.0f };
- static const CGFunctionCallbacks callbacks = { 0, qt_mac_color_gradient_function, 0 };
- CGFunctionRef fill_func = CGFunctionCreate(reinterpret_cast<void *>(&current.brush),
- 1, domain, 4, 0, &callbacks);
-
- CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
- if (bs == Qt::LinearGradientPattern) {
- const QLinearGradient *linearGrad = static_cast<const QLinearGradient *>(grad);
- const QPointF start(linearGrad->start());
- const QPointF stop(linearGrad->finalStop());
- shading = CGShadingCreateAxial(colorspace, CGPointMake(start.x(), start.y()),
- CGPointMake(stop.x(), stop.y()), fill_func, true, true);
- } else {
- Q_ASSERT(bs == Qt::RadialGradientPattern);
- const QRadialGradient *radialGrad = static_cast<const QRadialGradient *>(grad);
- QPointF center(radialGrad->center());
- QPointF focal(radialGrad->focalPoint());
- qreal radius = radialGrad->radius();
- shading = CGShadingCreateRadial(colorspace, CGPointMake(focal.x(), focal.y()),
- 0.0, CGPointMake(center.x(), center.y()), radius, fill_func, false, true);
- }
-
- CGFunctionRelease(fill_func);
- }
- } else
-#endif
- if(bs != Qt::SolidPattern && bs != Qt::NoBrush
-#ifndef QT_MAC_USE_NATIVE_GRADIENTS
- && (bs < Qt::LinearGradientPattern || bs > Qt::ConicalGradientPattern)
-#endif
- )
- {
- QMacPattern *qpattern = new QMacPattern;
- qpattern->pdev = pdev;
- CGFloat components[4] = { 1.0, 1.0, 1.0, 1.0 };
- CGColorSpaceRef base_colorspace = 0;
- if(bs == Qt::TexturePattern) {
- qpattern->data.pixmap = current.brush.texture();
- if(qpattern->data.pixmap.isQBitmap()) {
- const QColor &col = current.brush.color();
- components[0] = qt_mac_convert_color_to_cg(col.red());
- components[1] = qt_mac_convert_color_to_cg(col.green());
- components[2] = qt_mac_convert_color_to_cg(col.blue());
- base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
- }
- } else {
- qpattern->as_mask = true;
-
- qpattern->data.bytes = qt_mac_patternForBrush(bs);
- const QColor &col = current.brush.color();
- components[0] = qt_mac_convert_color_to_cg(col.red());
- components[1] = qt_mac_convert_color_to_cg(col.green());
- components[2] = qt_mac_convert_color_to_cg(col.blue());
- base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
- }
- int width = qpattern->width(), height = qpattern->height();
- qpattern->foreground = current.brush.color();
-
- CGColorSpaceRef fill_colorspace = CGColorSpaceCreatePattern(base_colorspace);
- CGContextSetFillColorSpace(hd, fill_colorspace);
-
- CGAffineTransform xform = CGContextGetCTM(hd);
- xform = CGAffineTransformConcat(qt_mac_convert_transform_to_cg(current.brush.transform()), xform);
- xform = CGAffineTransformTranslate(xform, offset.x(), offset.y());
-
- CGPatternCallbacks callbks;
- callbks.version = 0;
- callbks.drawPattern = qt_mac_draw_pattern;
- callbks.releaseInfo = qt_mac_dispose_pattern;
- CGPatternRef fill_pattern = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
- xform, width, height, kCGPatternTilingNoDistortion,
- !base_colorspace, &callbks);
- CGContextSetFillPattern(hd, fill_pattern, components);
-
- CGPatternRelease(fill_pattern);
- CGColorSpaceRelease(fill_colorspace);
- } else if(bs != Qt::NoBrush) {
- CGContextSetFillColorWithColor(hd, cgColorForQColor(current.brush.color(), pdev));
- }
-}
-
-void
-QCoreGraphicsPaintEnginePrivate::setClip(const QRegion *rgn)
-{
- Q_Q(QCoreGraphicsPaintEngine);
- if(hd) {
- resetClip();
- QRegion sysClip = q->systemClip();
- if(!sysClip.isEmpty())
- qt_mac_clip_cg(hd, sysClip, &orig_xform);
- if(rgn)
- qt_mac_clip_cg(hd, *rgn, 0);
- }
-}
-
-struct qt_mac_cg_transform_path {
- CGMutablePathRef path;
- CGAffineTransform transform;
-};
-
-void qt_mac_cg_transform_path_apply(void *info, const CGPathElement *element)
-{
- Q_ASSERT(info && element);
- qt_mac_cg_transform_path *t = (qt_mac_cg_transform_path*)info;
- switch(element->type) {
- case kCGPathElementMoveToPoint:
- CGPathMoveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
- break;
- case kCGPathElementAddLineToPoint:
- CGPathAddLineToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
- break;
- case kCGPathElementAddQuadCurveToPoint:
- CGPathAddQuadCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
- element->points[1].x, element->points[1].y);
- break;
- case kCGPathElementAddCurveToPoint:
- CGPathAddCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
- element->points[1].x, element->points[1].y,
- element->points[2].x, element->points[2].y);
- break;
- case kCGPathElementCloseSubpath:
- CGPathCloseSubpath(t->path);
- break;
- default:
- qDebug() << "Unhandled path transform type: " << element->type;
- }
-}
-
-void QCoreGraphicsPaintEnginePrivate::drawPath(uchar ops, CGMutablePathRef path)
-{
- Q_Q(QCoreGraphicsPaintEngine);
- Q_ASSERT((ops & (CGFill | CGEOFill)) != (CGFill | CGEOFill)); //can't really happen
- if((ops & (CGFill | CGEOFill))) {
- if (shading) {
- Q_ASSERT(path);
- CGContextBeginPath(hd);
- CGContextAddPath(hd, path);
- saveGraphicsState();
- if (ops & CGFill)
- CGContextClip(hd);
- else if (ops & CGEOFill)
- CGContextEOClip(hd);
- if (current.brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
- CGRect boundingBox = CGPathGetBoundingBox(path);
- CGContextConcatCTM(hd,
- CGAffineTransformMake(boundingBox.size.width, 0,
- 0, boundingBox.size.height,
- boundingBox.origin.x, boundingBox.origin.y));
- }
- CGContextDrawShading(hd, shading);
- restoreGraphicsState();
- ops &= ~CGFill;
- ops &= ~CGEOFill;
- } else if (current.brush.style() == Qt::NoBrush) {
- ops &= ~CGFill;
- ops &= ~CGEOFill;
- }
- }
- if((ops & CGStroke) && current.pen.style() == Qt::NoPen)
- ops &= ~CGStroke;
-
- if(ops & (CGEOFill | CGFill)) {
- CGContextBeginPath(hd);
- CGContextAddPath(hd, path);
- if (ops & CGEOFill) {
- CGContextEOFillPath(hd);
- } else {
- CGContextFillPath(hd);
- }
- }
-
- // Avoid saving and restoring the context if we can.
- const bool needContextSave = (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone ||
- !(q->state->renderHints() & QPainter::Antialiasing));
- if(ops & CGStroke) {
- if (needContextSave)
- saveGraphicsState();
- CGContextBeginPath(hd);
-
- // Translate a fraction of a pixel size in the y direction
- // to make sure that primitives painted at pixel borders
- // fills the right pixel. This is needed since the y xais
- // in the Quartz coordinate system is inverted compared to Qt.
- if (!(q->state->renderHints() & QPainter::Antialiasing)) {
- if (current.pen.style() == Qt::SolidLine || current.pen.width() >= 3)
- CGContextTranslateCTM(hd, double(pixelSize.x()) * 0.25, double(pixelSize.y()) * 0.25);
- else if (current.pen.style() == Qt::DotLine && QSysInfo::MacintoshVersion == QSysInfo::MV_10_3)
- ; // Do nothing.
- else
- CGContextTranslateCTM(hd, 0, double(pixelSize.y()) * 0.1);
- }
-
- if (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone) {
- // If antialiazing is enabled, use the cosmetic pen size directly.
- if (q->state->renderHints() & QPainter::Antialiasing)
- CGContextSetLineWidth(hd, cosmeticPenSize);
- else if (current.pen.widthF() <= 1)
- CGContextSetLineWidth(hd, cosmeticPenSize * 0.9f);
- else
- CGContextSetLineWidth(hd, cosmeticPenSize);
- }
- if(cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath) {
- qt_mac_cg_transform_path t;
- t.transform = qt_mac_convert_transform_to_cg(current.transform);
- t.path = CGPathCreateMutable();
- CGPathApply(path, &t, qt_mac_cg_transform_path_apply); //transform the path
- setTransform(0); //unset the context transform
- CGContextSetLineWidth(hd, cosmeticPenSize);
- CGContextAddPath(hd, t.path);
- CGPathRelease(t.path);
- } else {
- CGContextAddPath(hd, path);
- }
-
- CGContextStrokePath(hd);
- if (needContextSave)
- restoreGraphicsState();
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qpaintengine_mac_p.h b/src/gui/platforms/mac/qpaintengine_mac_p.h
deleted file mode 100644
index 3e71d6ca6b..0000000000
--- a/src/gui/platforms/mac/qpaintengine_mac_p.h
+++ /dev/null
@@ -1,254 +0,0 @@
-/****************************************************************************
-**
-** 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 QPAINTENGINE_MAC_P_H
-#define QPAINTENGINE_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qpaintengine.h"
-#include "private/qt_mac_p.h"
-#include "private/qpaintengine_p.h"
-#include "private/qpolygonclipper_p.h"
-#include "private/qfont_p.h"
-#include "QtCore/qhash.h"
-
-typedef struct CGColorSpace *CGColorSpaceRef;
-QT_BEGIN_NAMESPACE
-
-class QCoreGraphicsPaintEnginePrivate;
-class QCoreGraphicsPaintEngine : public QPaintEngine
-{
- Q_DECLARE_PRIVATE(QCoreGraphicsPaintEngine)
-
-public:
- QCoreGraphicsPaintEngine();
- ~QCoreGraphicsPaintEngine();
-
- bool begin(QPaintDevice *pdev);
- bool end();
- static CGColorSpaceRef macGenericColorSpace();
- static CGColorSpaceRef macDisplayColorSpace(const QWidget *widget = 0);
-
- void updateState(const QPaintEngineState &state);
-
- void updatePen(const QPen &pen);
- void updateBrush(const QBrush &brush, const QPointF &pt);
- void updateFont(const QFont &font);
- void updateOpacity(qreal opacity);
- void updateMatrix(const QTransform &matrix);
- void updateTransform(const QTransform &matrix);
- void updateClipRegion(const QRegion &region, Qt::ClipOperation op);
- void updateClipPath(const QPainterPath &path, Qt::ClipOperation op);
- void updateCompositionMode(QPainter::CompositionMode mode);
- void updateRenderHints(QPainter::RenderHints hints);
-
- void drawLines(const QLineF *lines, int lineCount);
- void drawRects(const QRectF *rects, int rectCount);
- void drawPoints(const QPointF *p, int pointCount);
- void drawEllipse(const QRectF &r);
- void drawPath(const QPainterPath &path);
-
- void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
- void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
- void drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, const QPointF &s);
-
- void drawTextItem(const QPointF &pos, const QTextItem &item);
- void drawImage(const QRectF &r, const QImage &pm, const QRectF &sr,
- Qt::ImageConversionFlags flags = Qt::AutoColor);
-
- Type type() const { return QPaintEngine::CoreGraphics; }
-
- CGContextRef handle() const;
-
- static void initialize();
- static void cleanup();
-
- QPainter::RenderHints supportedRenderHints() const;
-
- //avoid partial shadowed overload warnings...
- void drawLines(const QLine *lines, int lineCount) { QPaintEngine::drawLines(lines, lineCount); }
- void drawRects(const QRect *rects, int rectCount) { QPaintEngine::drawRects(rects, rectCount); }
- void drawPoints(const QPoint *p, int pointCount) { QPaintEngine::drawPoints(p, pointCount); }
- void drawEllipse(const QRect &r) { QPaintEngine::drawEllipse(r); }
- void drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
- { QPaintEngine::drawPolygon(points, pointCount, mode); }
-
-protected:
- friend class QMacPrintEngine;
- friend class QMacPrintEnginePrivate;
- friend void qt_mac_display_change_callbk(CGDirectDisplayID, CGDisplayChangeSummaryFlags, void *);
- friend void qt_color_profile_changed(CFNotificationCenterRef center, void *,
- CFStringRef , const void *, CFDictionaryRef);
- QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr);
-
-private:
- static bool m_postRoutineRegistered;
- static CGColorSpaceRef m_genericColorSpace;
- static QHash<CGDirectDisplayID, CGColorSpaceRef> m_displayColorSpaceHash;
- static void cleanUpMacColorSpaces();
- Q_DISABLE_COPY(QCoreGraphicsPaintEngine)
-};
-
-/*****************************************************************************
- Private data
- *****************************************************************************/
-class QCoreGraphicsPaintEnginePrivate : public QPaintEnginePrivate
-{
- Q_DECLARE_PUBLIC(QCoreGraphicsPaintEngine)
-public:
- QCoreGraphicsPaintEnginePrivate()
- : hd(0), shading(0), stackCount(0), complexXForm(false), disabledSmoothFonts(false)
- {
- }
-
- struct {
- QPen pen;
- QBrush brush;
- uint clipEnabled : 1;
- QRegion clip;
- QTransform transform;
- } current;
-
- //state info (shared with QD)
- CGAffineTransform orig_xform;
-
- //cg structures
- CGContextRef hd;
- CGShadingRef shading;
- int stackCount;
- bool complexXForm;
- bool disabledSmoothFonts;
- enum { CosmeticNone, CosmeticTransformPath, CosmeticSetPenWidth } cosmeticPen;
-
- // pixel and cosmetic pen size in user coordinates.
- QPointF pixelSize;
- float cosmeticPenSize;
-
- //internal functions
- enum { CGStroke=0x01, CGEOFill=0x02, CGFill=0x04 };
- void drawPath(uchar ops, CGMutablePathRef path = 0);
- void setClip(const QRegion *rgn=0);
- void resetClip();
- void setFillBrush(const QPointF &origin=QPoint());
- void setStrokePen(const QPen &pen);
- inline void saveGraphicsState();
- inline void restoreGraphicsState();
- float penOffset();
- QPointF devicePixelSize(CGContextRef context);
- float adjustPenWidth(float penWidth);
- inline void setTransform(const QTransform *matrix=0)
- {
- CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
- CGAffineTransform xform = orig_xform;
- if(matrix) {
- extern CGAffineTransform qt_mac_convert_transform_to_cg(const QTransform &);
- xform = CGAffineTransformConcat(qt_mac_convert_transform_to_cg(*matrix), xform);
- }
- CGContextConcatCTM(hd, xform);
- CGContextSetTextMatrix(hd, xform);
- }
-};
-
-inline void QCoreGraphicsPaintEnginePrivate::saveGraphicsState()
-{
- ++stackCount;
- CGContextSaveGState(hd);
-}
-
-inline void QCoreGraphicsPaintEnginePrivate::restoreGraphicsState()
-{
- --stackCount;
- Q_ASSERT(stackCount >= 0);
- CGContextRestoreGState(hd);
-}
-
-class QMacQuartzPaintDevice : public QPaintDevice
-{
-public:
- QMacQuartzPaintDevice(CGContextRef cg, int width, int height, int bytesPerLine)
- : mCG(cg), mWidth(width), mHeight(height), mBytesPerLine(bytesPerLine)
- { }
- int devType() const { return QInternal::MacQuartz; }
- CGContextRef cgContext() const { return mCG; }
- int metric(PaintDeviceMetric metric) const {
- switch (metric) {
- case PdmWidth:
- return mWidth;
- case PdmHeight:
- return mHeight;
- case PdmWidthMM:
- return (qt_defaultDpiX() * mWidth) / 2.54;
- case PdmHeightMM:
- return (qt_defaultDpiY() * mHeight) / 2.54;
- case PdmNumColors:
- return 0;
- case PdmDepth:
- return 32;
- case PdmDpiX:
- case PdmPhysicalDpiX:
- return qt_defaultDpiX();
- case PdmDpiY:
- case PdmPhysicalDpiY:
- return qt_defaultDpiY();
- }
- return 0;
- }
- QPaintEngine *paintEngine() const { qWarning("This function should never be called."); return 0; }
-private:
- CGContextRef mCG;
- int mWidth;
- int mHeight;
- int mBytesPerLine;
-};
-
-QT_END_NAMESPACE
-
-#endif // QPAINTENGINE_MAC_P_H
diff --git a/src/gui/platforms/mac/qpixmap_mac.cpp b/src/gui/platforms/mac/qpixmap_mac.cpp
deleted file mode 100644
index 72e2aa6e04..0000000000
--- a/src/gui/platforms/mac/qpixmap_mac.cpp
+++ /dev/null
@@ -1,1195 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpixmap.h"
-#include "qimage.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qmatrix.h"
-#include "qtransform.h"
-#include "qlibrary.h"
-#include "qvarlengtharray.h"
-#include "qdebug.h"
-#include <private/qdrawhelper_p.h>
-#include <private/qpixmap_mac_p.h>
-#include <private/qpixmap_raster_p.h>
-#include <private/qpaintengine_mac_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-
-#include <limits.h>
-#include <string.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern const uchar *qt_get_bitflip_array(); //qimage.cpp
-extern CGContextRef qt_mac_cg_context(const QPaintDevice *pdev); //qpaintdevice_mac.cpp
-extern RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
-extern void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-extern QRegion qt_mac_convert_mac_region(RgnHandle rgn); //qregion_mac.cpp
-
-static int qt_pixmap_serial = 0;
-
-Q_GUI_EXPORT quint32 *qt_mac_pixmap_get_base(const QPixmap *pix)
-{
- return static_cast<QMacPixmapData*>(pix->data.data())->pixels;
-}
-
-Q_GUI_EXPORT int qt_mac_pixmap_get_bytes_per_line(const QPixmap *pix)
-{
- return static_cast<QMacPixmapData*>(pix->data.data())->bytesPerRow;
-}
-
-void qt_mac_cgimage_data_free(void *info, const void *memoryToFree, size_t)
-{
- QMacPixmapData *pmdata = static_cast<QMacPixmapData *>(info);
- if (!pmdata) {
- free(const_cast<void *>(memoryToFree));
- } else {
- if (QMacPixmapData::validDataPointers.contains(pmdata) == false) {
- free(const_cast<void *>(memoryToFree));
- return;
- }
- if (pmdata->pixels == pmdata->pixelsToFree) {
- // something we aren't expecting, just free it.
- Q_ASSERT(memoryToFree != pmdata->pixelsToFree);
- free(const_cast<void *>(memoryToFree));
- } else {
- free(pmdata->pixelsToFree);
- pmdata->pixelsToFree = static_cast<quint32 *>(const_cast<void *>(memoryToFree));
- }
- pmdata->cg_dataBeingReleased = 0;
- }
-}
-
-CGImageRef qt_mac_image_to_cgimage(const QImage &image)
-{
- int bitsPerColor = 8;
- int bitsPerPixel = 32;
- if (image.depth() == 1) {
- bitsPerColor = 1;
- bitsPerPixel = 1;
- }
- QCFType<CGDataProviderRef> provider =
- CGDataProviderCreateWithData(0, image.bits(), image.bytesPerLine() * image.height(),
- 0);
-
- uint cgflags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- cgflags |= kCGBitmapByteOrder32Host;
-#endif
-
- CGImageRef cgImage = CGImageCreate(image.width(), image.height(), bitsPerColor, bitsPerPixel,
- image.bytesPerLine(),
- QCoreGraphicsPaintEngine::macGenericColorSpace(),
- cgflags, provider,
- 0,
- 0,
- kCGRenderingIntentDefault);
-
- return cgImage;
-}
-
-/*****************************************************************************
- QPixmap member functions
- *****************************************************************************/
-
-static inline QRgb qt_conv16ToRgb(ushort c) {
- static const int qt_rbits = (565/100);
- static const int qt_gbits = (565/10%10);
- static const int qt_bbits = (565%10);
- static const int qt_red_shift = qt_bbits+qt_gbits-(8-qt_rbits);
- static const int qt_green_shift = qt_bbits-(8-qt_gbits);
- static const int qt_neg_blue_shift = 8-qt_bbits;
- static const int qt_blue_mask = (1<<qt_bbits)-1;
- static const int qt_green_mask = (1<<(qt_gbits+qt_bbits))-((1<<qt_bbits)-1);
- static const int qt_red_mask = (1<<(qt_rbits+qt_gbits+qt_bbits))-(1<<(qt_gbits+qt_bbits));
-
- const int r=(c & qt_red_mask);
- const int g=(c & qt_green_mask);
- const int b=(c & qt_blue_mask);
- const int tr = r >> qt_red_shift;
- const int tg = g >> qt_green_shift;
- const int tb = b << qt_neg_blue_shift;
-
- return qRgb(tr,tg,tb);
-}
-
-QSet<QMacPixmapData*> QMacPixmapData::validDataPointers;
-
-QMacPixmapData::QMacPixmapData(PixelType type)
- : QPixmapData(type, MacClass), has_alpha(0), has_mask(0),
- uninit(true), pixels(0), pixelsSize(0), pixelsToFree(0),
- bytesPerRow(0), cg_data(0), cg_dataBeingReleased(0), cg_mask(0),
- pengine(0)
-{
-}
-
-QPixmapData *QMacPixmapData::createCompatiblePixmapData() const
-{
- return new QMacPixmapData(pixelType());
-}
-
-#define BEST_BYTE_ALIGNMENT 16
-#define COMPTUE_BEST_BYTES_PER_ROW(bpr) \
- (((bpr) + (BEST_BYTE_ALIGNMENT - 1)) & ~(BEST_BYTE_ALIGNMENT - 1))
-
-void QMacPixmapData::resize(int width, int height)
-{
- setSerialNumber(++qt_pixmap_serial);
-
- w = width;
- h = height;
- is_null = (w <= 0 || h <= 0);
- d = (pixelType() == BitmapType ? 1 : 32);
- bool make_null = w <= 0 || h <= 0; // create null pixmap
- if (make_null || d == 0) {
- w = 0;
- h = 0;
- is_null = true;
- d = 0;
- if (!make_null)
- qWarning("Qt: QPixmap: Invalid pixmap parameters");
- return;
- }
-
- if (w < 1 || h < 1)
- return;
-
- //create the pixels
- bytesPerRow = w * sizeof(quint32); // Minimum bytes per row.
-
- // Quartz2D likes things as a multple of 16 (for now).
- bytesPerRow = COMPTUE_BEST_BYTES_PER_ROW(bytesPerRow);
- macCreatePixels();
-}
-
-#undef COMPUTE_BEST_BYTES_PER_ROW
-
-void QMacPixmapData::fromImage(const QImage &img,
- Qt::ImageConversionFlags flags)
-{
- setSerialNumber(++qt_pixmap_serial);
-
- // the conversion code only handles format >=
- // Format_ARGB32_Premultiplied at the moment..
- if (img.format() > QImage::Format_ARGB32_Premultiplied) {
- QImage image;
- if (img.hasAlphaChannel())
- image = img.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- else
- image = img.convertToFormat(QImage::Format_RGB32);
- fromImage(image, flags);
- return;
- }
-
- w = img.width();
- h = img.height();
- is_null = (w <= 0 || h <= 0);
- d = (pixelType() == BitmapType ? 1 : img.depth());
-
- QImage image = img;
- int dd = QPixmap::defaultDepth();
- bool force_mono = (dd == 1 ||
- (flags & Qt::ColorMode_Mask)==Qt::MonoOnly);
- if (force_mono) { // must be monochrome
- if (d != 1) {
- image = image.convertToFormat(QImage::Format_MonoLSB, flags); // dither
- d = 1;
- }
- } else { // can be both
- bool conv8 = false;
- if(d > 8 && dd <= 8) { // convert to 8 bit
- if ((flags & Qt::DitherMode_Mask) == Qt::AutoDither)
- flags = (flags & ~Qt::DitherMode_Mask)
- | Qt::PreferDither;
- conv8 = true;
- } else if ((flags & Qt::ColorMode_Mask) == Qt::ColorOnly) {
- conv8 = d == 1; // native depth wanted
- } else if (d == 1) {
- if (image.colorCount() == 2) {
- QRgb c0 = image.color(0); // Auto: convert to best
- QRgb c1 = image.color(1);
- conv8 = qMin(c0,c1) != qRgb(0,0,0) || qMax(c0,c1) != qRgb(255,255,255);
- } else {
- // eg. 1-color monochrome images (they do exist).
- conv8 = true;
- }
- }
- if (conv8) {
- image = image.convertToFormat(QImage::Format_Indexed8, flags);
- d = 8;
- }
- }
-
- if (image.depth()==1) {
- image.setColor(0, QColor(Qt::color0).rgba());
- image.setColor(1, QColor(Qt::color1).rgba());
- }
-
- if (d == 16 || d == 24) {
- image = image.convertToFormat(QImage::Format_RGB32, flags);
- fromImage(image, flags);
- return;
- }
-
- // different size or depth, make a new pixmap
- resize(w, h);
-
- quint32 *dptr = pixels, *drow;
- const uint dbpr = bytesPerRow;
-
- const QImage::Format sfmt = image.format();
- const unsigned short sbpr = image.bytesPerLine();
-
- // use const_cast to prevent a detach
- const uchar *sptr = const_cast<const QImage &>(image).bits(), *srow;
-
- for (int y = 0; y < h; ++y) {
- drow = dptr + (y * (dbpr / 4));
- srow = sptr + (y * sbpr);
- switch(sfmt) {
- case QImage::Format_MonoLSB:
- case QImage::Format_Mono:{
- for (int x = 0; x < w; ++x) {
- char one_bit = *(srow + (x / 8));
- if (sfmt == QImage::Format_Mono)
- one_bit = one_bit >> (7 - (x % 8));
- else
- one_bit = one_bit >> (x % 8);
- if ((one_bit & 0x01))
- *(drow+x) = 0xFF000000;
- else
- *(drow+x) = 0xFFFFFFFF;
- }
- break;
- }
- case QImage::Format_Indexed8: {
- int numColors = image.numColors();
- if (numColors > 0) {
- for (int x = 0; x < w; ++x) {
- int index = *(srow + x);
- *(drow+x) = PREMUL(image.color(qMin(index, numColors)));
- }
- }
- } break;
- case QImage::Format_RGB32:
- for (int x = 0; x < w; ++x)
- *(drow+x) = *(((quint32*)srow) + x) | 0xFF000000;
- break;
- case QImage::Format_ARGB32:
- case QImage::Format_ARGB32_Premultiplied:
- for (int x = 0; x < w; ++x) {
- if(sfmt == QImage::Format_RGB32)
- *(drow+x) = 0xFF000000 | (*(((quint32*)srow) + x) & 0x00FFFFFF);
- else if(sfmt == QImage::Format_ARGB32_Premultiplied)
- *(drow+x) = *(((quint32*)srow) + x);
- else
- *(drow+x) = PREMUL(*(((quint32*)srow) + x));
- }
- break;
- default:
- qWarning("Qt: internal: Oops: Forgot a format [%d] %s:%d", sfmt,
- __FILE__, __LINE__);
- break;
- }
- }
- if (sfmt != QImage::Format_RGB32) { //setup the alpha
- bool alphamap = image.depth() == 32;
- if (sfmt == QImage::Format_Indexed8) {
- const QVector<QRgb> rgb = image.colorTable();
- for (int i = 0, count = image.colorCount(); i < count; ++i) {
- const int alpha = qAlpha(rgb[i]);
- if (alpha != 0xff) {
- alphamap = true;
- break;
- }
- }
- }
- macSetHasAlpha(alphamap);
- }
- uninit = false;
-}
-
-int get_index(QImage * qi,QRgb mycol)
-{
- int loopc;
- for(loopc=0;loopc<qi->colorCount();loopc++) {
- if(qi->color(loopc)==mycol)
- return loopc;
- }
- qi->setColorCount(qi->colorCount()+1);
- qi->setColor(qi->colorCount(),mycol);
- return qi->colorCount();
-}
-
-QImage QMacPixmapData::toImage() const
-{
- QImage::Format format = QImage::Format_MonoLSB;
- if (d != 1) //Doesn't support index color modes
- format = (has_alpha ? QImage::Format_ARGB32_Premultiplied :
- QImage::Format_RGB32);
-
- QImage image(w, h, format);
- quint32 *sptr = pixels, *srow;
- const uint sbpr = bytesPerRow;
- if (format == QImage::Format_MonoLSB) {
- image.fill(0);
- image.setColorCount(2);
- image.setColor(0, QColor(Qt::color0).rgba());
- image.setColor(1, QColor(Qt::color1).rgba());
- for (int y = 0; y < h; ++y) {
- uchar *scanLine = image.scanLine(y);
- srow = sptr + (y * (sbpr/4));
- for (int x = 0; x < w; ++x) {
- if (!(*(srow + x) & RGB_MASK))
- scanLine[x >> 3] |= (1 << (x & 7));
- }
- }
- } else {
- for (int y = 0; y < h; ++y) {
- srow = sptr + (y * (sbpr / 4));
- memcpy(image.scanLine(y), srow, w * 4);
- }
-
- }
-
- return image;
-}
-
-void QMacPixmapData::fill(const QColor &fillColor)
-
-{
- { //we don't know what backend to use so we cannot paint here
- quint32 *dptr = pixels;
- Q_ASSERT_X(dptr, "QPixmap::fill", "No dptr");
- const quint32 colr = PREMUL(fillColor.rgba());
- const int nbytes = bytesPerRow * h;
- if (!colr) {
- memset(dptr, 0, nbytes);
- } else {
- for (uint i = 0; i < nbytes / sizeof(quint32); ++i)
- *(dptr + i) = colr;
- }
- }
-
- // If we had an alpha channel from before, don't
- // switch it off. Only go from no alpha to alpha:
- if (fillColor.alpha() != 255)
- macSetHasAlpha(true);
-}
-
-QPixmap QMacPixmapData::alphaChannel() const
-{
- if (!has_alpha)
- return QPixmap();
-
- QMacPixmapData *alpha = new QMacPixmapData(PixmapType);
- alpha->resize(w, h);
- macGetAlphaChannel(alpha, false);
- return QPixmap(alpha);
-}
-
-void QMacPixmapData::setAlphaChannel(const QPixmap &alpha)
-{
- has_mask = true;
- QMacPixmapData *alphaData = static_cast<QMacPixmapData*>(alpha.data.data());
- macSetAlphaChannel(alphaData, false);
-}
-
-QBitmap QMacPixmapData::mask() const
-{
- if (!has_mask && !has_alpha)
- return QBitmap();
-
- QMacPixmapData *mask = new QMacPixmapData(BitmapType);
- mask->resize(w, h);
- macGetAlphaChannel(mask, true);
- return QPixmap(mask);
-}
-
-void QMacPixmapData::setMask(const QBitmap &mask)
-{
- if (mask.isNull()) {
- QMacPixmapData opaque(PixmapType);
- opaque.resize(w, h);
- opaque.fill(QColor(255, 255, 255, 255));
- macSetAlphaChannel(&opaque, true);
- has_alpha = has_mask = false;
- return;
- }
-
- has_alpha = false;
- has_mask = true;
- QMacPixmapData *maskData = static_cast<QMacPixmapData*>(mask.data.data());
- macSetAlphaChannel(maskData, true);
-}
-
-int QMacPixmapData::metric(QPaintDevice::PaintDeviceMetric theMetric) const
-{
- switch (theMetric) {
- case QPaintDevice::PdmWidth:
- return w;
- case QPaintDevice::PdmHeight:
- return h;
- case QPaintDevice::PdmWidthMM:
- return qRound(metric(QPaintDevice::PdmWidth) * 25.4 / qreal(metric(QPaintDevice::PdmDpiX)));
- case QPaintDevice::PdmHeightMM:
- return qRound(metric(QPaintDevice::PdmHeight) * 25.4 / qreal(metric(QPaintDevice::PdmDpiY)));
- case QPaintDevice::PdmNumColors:
- return 1 << d;
- case QPaintDevice::PdmDpiX:
- case QPaintDevice::PdmPhysicalDpiX: {
- extern float qt_mac_defaultDpi_x(); //qpaintdevice_mac.cpp
- return int(qt_mac_defaultDpi_x());
- }
- case QPaintDevice::PdmDpiY:
- case QPaintDevice::PdmPhysicalDpiY: {
- extern float qt_mac_defaultDpi_y(); //qpaintdevice_mac.cpp
- return int(qt_mac_defaultDpi_y());
- }
- case QPaintDevice::PdmDepth:
- return d;
- default:
- qWarning("QPixmap::metric: Invalid metric command");
- }
- return 0;
-}
-
-QMacPixmapData::~QMacPixmapData()
-{
- validDataPointers.remove(this);
- if (cg_mask) {
- CGImageRelease(cg_mask);
- cg_mask = 0;
- }
-
- delete pengine; // Make sure we aren't drawing on the context anymore.
- if (cg_data) {
- CGImageRelease(cg_data);
- } else if (!cg_dataBeingReleased && pixels != pixelsToFree) {
- free(pixels);
- }
- free(pixelsToFree);
-}
-
-void QMacPixmapData::macSetAlphaChannel(const QMacPixmapData *pix, bool asMask)
-{
- if (!pixels || !h || !w || pix->w != w || pix->h != h)
- return;
-
- quint32 *dptr = pixels, *drow;
- const uint dbpr = bytesPerRow;
- const unsigned short sbpr = pix->bytesPerRow;
- quint32 *sptr = pix->pixels, *srow;
- for (int y=0; y < h; ++y) {
- drow = dptr + (y * (dbpr/4));
- srow = sptr + (y * (sbpr/4));
- if(d == 1) {
- for (int x=0; x < w; ++x) {
- if((*(srow+x) & RGB_MASK))
- *(drow+x) = 0xFFFFFFFF;
- }
- } else if(d == 8) {
- for (int x=0; x < w; ++x)
- *(drow+x) = (*(drow+x) & RGB_MASK) | (*(srow+x) << 24);
- } else if(asMask) {
- for (int x=0; x < w; ++x) {
- if(*(srow+x) & RGB_MASK)
- *(drow+x) = (*(drow+x) & RGB_MASK);
- else
- *(drow+x) = (*(drow+x) & RGB_MASK) | 0xFF000000;
- *(drow+x) = PREMUL(*(drow+x));
- }
- } else {
- for (int x=0; x < w; ++x) {
- const uchar alpha = qGray(qRed(*(srow+x)), qGreen(*(srow+x)), qBlue(*(srow+x)));
- const uchar destAlpha = qt_div_255(alpha * qAlpha(*(drow+x)));
-#if 1
- *(drow+x) = (*(drow+x) & RGB_MASK) | (destAlpha << 24);
-#else
- *(drow+x) = qRgba(qt_div_255(qRed(*(drow+x) * alpha)),
- qt_div_255(qGreen(*(drow+x) * alpha)),
- qt_div_255(qBlue(*(drow+x) * alpha)), destAlpha);
-#endif
- *(drow+x) = PREMUL(*(drow+x));
- }
- }
- }
- macSetHasAlpha(true);
-}
-
-void QMacPixmapData::macGetAlphaChannel(QMacPixmapData *pix, bool asMask) const
-{
- quint32 *dptr = pix->pixels, *drow;
- const uint dbpr = pix->bytesPerRow;
- const unsigned short sbpr = bytesPerRow;
- quint32 *sptr = pixels, *srow;
- for(int y=0; y < h; ++y) {
- drow = dptr + (y * (dbpr/4));
- srow = sptr + (y * (sbpr/4));
- if(asMask) {
- for (int x = 0; x < w; ++x) {
- if (*(srow + x) & qRgba(0, 0, 0, 255))
- *(drow + x) = 0x00000000;
- else
- *(drow + x) = 0xFFFFFFFF;
- }
- } else {
- for (int x = 0; x < w; ++x) {
- const int alpha = qAlpha(*(srow + x));
- *(drow + x) = qRgb(alpha, alpha, alpha);
- }
- }
- }
-}
-
-void QMacPixmapData::macSetHasAlpha(bool b)
-{
- has_alpha = b;
- macReleaseCGImageRef();
-}
-
-void QMacPixmapData::macCreateCGImageRef()
-{
- Q_ASSERT(cg_data == 0);
- //create the cg data
- CGColorSpaceRef colorspace = QCoreGraphicsPaintEngine::macDisplayColorSpace();
- QCFType<CGDataProviderRef> provider = CGDataProviderCreateWithData(this,
- pixels, bytesPerRow * h,
- qt_mac_cgimage_data_free);
- validDataPointers.insert(this);
- uint cgflags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- cgflags |= kCGBitmapByteOrder32Host;
-#endif
- cg_data = CGImageCreate(w, h, 8, 32, bytesPerRow, colorspace,
- cgflags, provider, 0, 0, kCGRenderingIntentDefault);
-}
-
-void QMacPixmapData::macReleaseCGImageRef()
-{
- if (!cg_data)
- return; // There's nothing we need to do
-
- cg_dataBeingReleased = cg_data;
- CGImageRelease(cg_data);
- cg_data = 0;
-
- if (pixels != pixelsToFree) {
- macCreatePixels();
- } else {
- pixelsToFree = 0;
- }
-}
-
-
-// We create our space in memory to paint on here. If we already have existing pixels
-// copy them over. This is to preserve the fact that CGImageRef's are immutable.
-void QMacPixmapData::macCreatePixels()
-{
- const int numBytes = bytesPerRow * h;
- quint32 *base_pixels;
- if (pixelsToFree && pixelsToFree != pixels) {
- // Reuse unused block of memory lying around from a previous callback.
- base_pixels = pixelsToFree;
- pixelsToFree = 0;
- } else {
- // We need a block of memory to do stuff with.
- base_pixels = static_cast<quint32 *>(malloc(numBytes));
- }
-
- if (pixels)
- memcpy(base_pixels, pixels, pixelsSize);
- pixels = base_pixels;
- pixelsSize = numBytes;
-}
-
-#if 0
-QPixmap QMacPixmapData::transformed(const QTransform &transform,
- Qt::TransformationMode mode) const
-{
- int w, h; // size of target pixmap
- const int ws = width();
- const int hs = height();
-
- QTransform mat(transform.m11(), transform.m12(),
- transform.m21(), transform.m22(), 0., 0.);
- if (transform.m12() == 0.0F && transform.m21() == 0.0F &&
- transform.m11() >= 0.0F && transform.m22() >= 0.0F)
- {
- h = int(qAbs(mat.m22()) * hs + 0.9999);
- w = int(qAbs(mat.m11()) * ws + 0.9999);
- h = qAbs(h);
- w = qAbs(w);
- } else { // rotation or shearing
- QPolygonF a(QRectF(0,0,ws+1,hs+1));
- a = mat.map(a);
- QRectF r = a.boundingRect().normalized();
- w = int(r.width() + 0.9999);
- h = int(r.height() + 0.9999);
- }
- mat = QPixmap::trueMatrix(mat, ws, hs);
- if (!h || !w)
- return QPixmap();
-
- // create destination
- QMacPixmapData *pm = new QMacPixmapData(pixelType(), w, h);
- const quint32 *sptr = pixels;
- quint32 *dptr = pm->pixels;
- memset(dptr, 0, (pm->bytesPerRow * pm->h));
-
- // do the transform
- if (mode == Qt::SmoothTransformation) {
-#warning QMacPixmapData::transformed not properly implemented
- qWarning("QMacPixmapData::transformed not properly implemented");
-#if 0
- QPainter p(&pm);
- p.setRenderHint(QPainter::Antialiasing);
- p.setRenderHint(QPainter::SmoothPixmapTransform);
- p.setTransform(mat);
- p.drawPixmap(0, 0, *this);
-#endif
- } else {
- bool invertible;
- mat = mat.inverted(&invertible);
- if (!invertible)
- return QPixmap();
-
- const int bpp = 32;
- const int xbpl = (w * bpp) / 8;
- if (!qt_xForm_helper(mat, 0, QT_XFORM_TYPE_MSBFIRST, bpp,
- (uchar*)dptr, xbpl, (pm->bytesPerRow) - xbpl,
- h, (uchar*)sptr, (bytesPerRow), ws, hs)) {
- qWarning("QMacPixmapData::transform(): failure");
- return QPixmap();
- }
- }
-
- // update the alpha
- pm->macSetHasAlpha(true);
- return QPixmap(pm);
-}
-#endif
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <OpenGL/OpenGL.h>
-#include <OpenGL/gl.h>
-QT_END_INCLUDE_NAMESPACE
-
-// Load and resolve the symbols we need from OpenGL manually so QtGui doesn't have to link against the OpenGL framework.
-typedef CGLError (*PtrCGLChoosePixelFormat)(const CGLPixelFormatAttribute *, CGLPixelFormatObj *, long *);
-typedef CGLError (*PtrCGLClearDrawable)(CGLContextObj);
-typedef CGLError (*PtrCGLCreateContext)(CGLPixelFormatObj, CGLContextObj, CGLContextObj *);
-typedef CGLError (*PtrCGLDestroyContext)(CGLContextObj);
-typedef CGLError (*PtrCGLDestroyPixelFormat)(CGLPixelFormatObj);
-typedef CGLError (*PtrCGLSetCurrentContext)(CGLContextObj);
-typedef CGLError (*PtrCGLSetFullScreen)(CGLContextObj);
-typedef void (*PtrglFinish)();
-typedef void (*PtrglPixelStorei)(GLenum, GLint);
-typedef void (*PtrglReadBuffer)(GLenum);
-typedef void (*PtrglReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoid *);
-
-static PtrCGLChoosePixelFormat ptrCGLChoosePixelFormat = 0;
-static PtrCGLClearDrawable ptrCGLClearDrawable = 0;
-static PtrCGLCreateContext ptrCGLCreateContext = 0;
-static PtrCGLDestroyContext ptrCGLDestroyContext = 0;
-static PtrCGLDestroyPixelFormat ptrCGLDestroyPixelFormat = 0;
-static PtrCGLSetCurrentContext ptrCGLSetCurrentContext = 0;
-static PtrCGLSetFullScreen ptrCGLSetFullScreen = 0;
-static PtrglFinish ptrglFinish = 0;
-static PtrglPixelStorei ptrglPixelStorei = 0;
-static PtrglReadBuffer ptrglReadBuffer = 0;
-static PtrglReadPixels ptrglReadPixels = 0;
-
-static bool resolveOpenGLSymbols()
-{
- if (ptrCGLChoosePixelFormat == 0) {
- QLibrary library(QLatin1String("/System/Library/Frameworks/OpenGL.framework/OpenGL"));
- ptrCGLChoosePixelFormat = (PtrCGLChoosePixelFormat)(library.resolve("CGLChoosePixelFormat"));
- ptrCGLClearDrawable = (PtrCGLClearDrawable)(library.resolve("CGLClearDrawable"));
- ptrCGLCreateContext = (PtrCGLCreateContext)(library.resolve("CGLCreateContext"));
- ptrCGLDestroyContext = (PtrCGLDestroyContext)(library.resolve("CGLDestroyContext"));
- ptrCGLDestroyPixelFormat = (PtrCGLDestroyPixelFormat)(library.resolve("CGLDestroyPixelFormat"));
- ptrCGLSetCurrentContext = (PtrCGLSetCurrentContext)(library.resolve("CGLSetCurrentContext"));
- ptrCGLSetFullScreen = (PtrCGLSetFullScreen)(library.resolve("CGLSetFullScreen"));
- ptrglFinish = (PtrglFinish)(library.resolve("glFinish"));
- ptrglPixelStorei = (PtrglPixelStorei)(library.resolve("glPixelStorei"));
- ptrglReadBuffer = (PtrglReadBuffer)(library.resolve("glReadBuffer"));
- ptrglReadPixels = (PtrglReadPixels)(library.resolve("glReadPixels"));
- }
- return ptrCGLChoosePixelFormat && ptrCGLClearDrawable && ptrCGLCreateContext
- && ptrCGLDestroyContext && ptrCGLDestroyPixelFormat && ptrCGLSetCurrentContext
- && ptrCGLSetFullScreen && ptrglFinish && ptrglPixelStorei
- && ptrglReadBuffer && ptrglReadPixels;
-}
-
-// Inverts the given pixmap in the y direction.
-static void qt_mac_flipPixmap(void *data, int rowBytes, int height)
-{
- int bottom = height - 1;
- void *base = data;
- void *buffer = malloc(rowBytes);
-
- int top = 0;
- while ( top < bottom )
- {
- void *topP = (void *)((top * rowBytes) + (intptr_t)base);
- void *bottomP = (void *)((bottom * rowBytes) + (intptr_t)base);
-
- bcopy( topP, buffer, rowBytes );
- bcopy( bottomP, topP, rowBytes );
- bcopy( buffer, bottomP, rowBytes );
-
- ++top;
- --bottom;
- }
- free(buffer);
-}
-
-// Grabs displayRect from display and places it into buffer.
-static void qt_mac_grabDisplayRect(CGDirectDisplayID display, const QRect &displayRect, void *buffer)
-{
- if (display == kCGNullDirectDisplay)
- return;
-
- CGLPixelFormatAttribute attribs[] = {
- kCGLPFAFullScreen,
- kCGLPFADisplayMask,
- (CGLPixelFormatAttribute)0, /* Display mask bit goes here */
- (CGLPixelFormatAttribute)0
- };
-
- attribs[2] = (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(display);
-
- // Build a full-screen GL context
- CGLPixelFormatObj pixelFormatObj;
- long numPixelFormats;
-
- ptrCGLChoosePixelFormat( attribs, &pixelFormatObj, &numPixelFormats );
-
- if (!pixelFormatObj) // No full screen context support
- return;
-
- CGLContextObj glContextObj;
- ptrCGLCreateContext(pixelFormatObj, 0, &glContextObj);
- ptrCGLDestroyPixelFormat(pixelFormatObj) ;
- if (!glContextObj)
- return;
-
- ptrCGLSetCurrentContext(glContextObj);
- ptrCGLSetFullScreen(glContextObj) ;
-
- ptrglReadBuffer(GL_FRONT);
-
- ptrglFinish(); // Finish all OpenGL commands
- ptrglPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment
- ptrglPixelStorei(GL_PACK_ROW_LENGTH, 0);
- ptrglPixelStorei(GL_PACK_SKIP_ROWS, 0);
- ptrglPixelStorei(GL_PACK_SKIP_PIXELS, 0);
-
- // Fetch the data in XRGB format, matching the bitmap context.
- ptrglReadPixels(GLint(displayRect.x()), GLint(displayRect.y()),
- GLint(displayRect.width()), GLint(displayRect.height()),
-#ifdef __BIG_ENDIAN__
- GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, buffer
-#else
- GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, buffer
-#endif
- );
-
- ptrCGLSetCurrentContext(0);
- ptrCGLClearDrawable(glContextObj); // disassociate from full screen
- ptrCGLDestroyContext(glContextObj); // and destroy the context
-}
-
-// Returns a pixmap containing the screen contents at rect.
-static QPixmap qt_mac_grabScreenRect(const QRect &rect)
-{
- if (!resolveOpenGLSymbols())
- return QPixmap();
-
- const int maxDisplays = 128; // 128 displays should be enough for everyone.
- CGDirectDisplayID displays[maxDisplays];
- CGDisplayCount displayCount;
- const CGRect cgRect = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
- const CGDisplayErr err = CGGetDisplaysWithRect(cgRect, maxDisplays, displays, &displayCount);
-
- if (err && displayCount == 0)
- return QPixmap();
-
- long bytewidth = rect.width() * 4; // Assume 4 bytes/pixel for now
- bytewidth = (bytewidth + 3) & ~3; // Align to 4 bytes
- QVarLengthArray<char> buffer(rect.height() * bytewidth);
-
- for (uint i = 0; i < displayCount; ++i) {
- const CGRect bounds = CGDisplayBounds(displays[i]);
- // Translate to display-local coordinates
- QRect displayRect = rect.translated(qRound(-bounds.origin.x), qRound(-bounds.origin.y));
- // Adjust for inverted y axis.
- displayRect.moveTop(qRound(bounds.size.height) - displayRect.y() - rect.height());
- qt_mac_grabDisplayRect(displays[i], displayRect, buffer.data());
- }
-
- qt_mac_flipPixmap(buffer.data(), bytewidth, rect.height());
- QCFType<CGContextRef> bitmap = CGBitmapContextCreate(buffer.data(), rect.width(),
- rect.height(), 8, bytewidth,
- QCoreGraphicsPaintEngine::macGenericColorSpace(),
- kCGImageAlphaNoneSkipFirst);
- QCFType<CGImageRef> image = CGBitmapContextCreateImage(bitmap);
- return QPixmap::fromMacCGImageRef(image);
-}
-
-#ifndef QT_MAC_USE_COCOA // no QuickDraw in 64-bit mode
-static QPixmap qt_mac_grabScreenRect_10_3(int x, int y, int w, int h, QWidget *widget)
-{
- QPixmap pm = QPixmap(w, h);
- extern WindowPtr qt_mac_window_for(const QWidget *); // qwidget_mac.cpp
- const BitMap *windowPort = 0;
- if((widget->windowType() == Qt::Desktop)) {
- GDHandle gdh;
- if(!(gdh=GetMainDevice()))
- qDebug("Qt: internal: Unexpected condition reached: %s:%d", __FILE__, __LINE__);
- windowPort = (BitMap*)(*(*gdh)->gdPMap);
- } else {
- windowPort = GetPortBitMapForCopyBits(GetWindowPort(qt_mac_window_for(widget)));
- }
- const BitMap *pixmapPort = GetPortBitMapForCopyBits(static_cast<GWorldPtr>(pm.macQDHandle()));
- Rect macSrcRect, macDstRect;
- SetRect(&macSrcRect, x, y, x + w, y + h);
- SetRect(&macDstRect, 0, 0, w, h);
- CopyBits(windowPort, pixmapPort, &macSrcRect, &macDstRect, srcCopy, 0);
- return pm;
-}
-#endif
-
-QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
-{
- QWidget *widget = QWidget::find(window);
- if (widget == 0)
- return QPixmap();
-
- if(w == -1)
- w = widget->width() - x;
- if(h == -1)
- h = widget->height() - y;
-
- QPoint globalCoord(0, 0);
- globalCoord = widget->mapToGlobal(globalCoord);
- QRect rect(globalCoord.x() + x, globalCoord.y() + y, w, h);
-
-#ifdef QT_MAC_USE_COCOA
- return qt_mac_grabScreenRect(rect);
-#else
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
- return qt_mac_grabScreenRect(rect);
- } else
-#endif
- {
- return qt_mac_grabScreenRect_10_3(x, y, w, h, widget);
- }
-#endif // ifdef Q_WS_MAC64
-}
-
-/*! \internal
-
- Returns the QuickDraw CGrafPtr of the pixmap. 0 is returned if it can't
- be obtained. Do not hold the pointer around for long as it can be
- relocated.
-
- \warning This function is only available on Mac OS X.
- \warning As of Qt 4.6, this function \e{always} returns zero.
-*/
-
-Qt::HANDLE QPixmap::macQDHandle() const
-{
- return 0;
-}
-
-/*! \internal
-
- Returns the QuickDraw CGrafPtr of the pixmap's alpha channel. 0 is
- returned if it can't be obtained. Do not hold the pointer around for
- long as it can be relocated.
-
- \warning This function is only available on Mac OS X.
- \warning As of Qt 4.6, this function \e{always} returns zero.
-*/
-
-Qt::HANDLE QPixmap::macQDAlphaHandle() const
-{
- return 0;
-}
-
-/*! \internal
-
- Returns the CoreGraphics CGContextRef of the pixmap. 0 is returned if
- it can't be obtained. It is the caller's responsiblity to
- CGContextRelease the context when finished using it.
-
- \warning This function is only available on Mac OS X.
-*/
-
-Qt::HANDLE QPixmap::macCGHandle() const
-{
- if (isNull())
- return 0;
-
- if (data->classId() == QPixmapData::MacClass) {
- QMacPixmapData *d = static_cast<QMacPixmapData *>(data.data());
- if (!d->cg_data)
- d->macCreateCGImageRef();
- CGImageRef ret = d->cg_data;
- CGImageRetain(ret);
- return ret;
- } else if (data->classId() == QPixmapData::RasterClass) {
- return qt_mac_image_to_cgimage(static_cast<QRasterPixmapData *>(data.data())->image);
- }
- return 0;
-}
-
-bool QMacPixmapData::hasAlphaChannel() const
-{
- return has_alpha;
-}
-
-CGImageRef qt_mac_create_imagemask(const QPixmap &pixmap, const QRectF &sr)
-{
- QMacPixmapData *px = static_cast<QMacPixmapData*>(pixmap.data.data());
- if (px->cg_mask) {
- if (px->cg_mask_rect == sr) {
- CGImageRetain(px->cg_mask); //reference for the caller
- return px->cg_mask;
- }
- CGImageRelease(px->cg_mask);
- px->cg_mask = 0;
- }
-
- const int sx = qRound(sr.x()), sy = qRound(sr.y()), sw = qRound(sr.width()), sh = qRound(sr.height());
- const int sbpr = px->bytesPerRow;
- const uint nbytes = sw * sh;
- // alpha is always 255 for bitmaps, ignore it in this case.
- const quint32 mask = px->depth() == 1 ? 0x00ffffff : 0xffffffff;
- quint8 *dptr = static_cast<quint8 *>(malloc(nbytes));
- quint32 *sptr = px->pixels, *srow;
- for(int y = sy, offset=0; y < sh; ++y) {
- srow = sptr + (y * (sbpr / 4));
- for(int x = sx; x < sw; ++x)
- *(dptr+(offset++)) = (*(srow+x) & mask) ? 255 : 0;
- }
- QCFType<CGDataProviderRef> provider = CGDataProviderCreateWithData(0, dptr, nbytes, qt_mac_cgimage_data_free);
- px->cg_mask = CGImageMaskCreate(sw, sh, 8, 8, nbytes / sh, provider, 0, 0);
- px->cg_mask_rect = sr;
- CGImageRetain(px->cg_mask); //reference for the caller
- return px->cg_mask;
-}
-
-#ifndef QT_MAC_USE_COCOA
-IconRef qt_mac_create_iconref(const QPixmap &px)
-{
- if (px.isNull())
- return 0;
-
- //create icon
- IconFamilyHandle iconFamily = reinterpret_cast<IconFamilyHandle>(NewHandle(0));
- //create data
- {
- struct {
- OSType mac_type;
- int width, height, depth;
- bool mask;
- } images[] = {
- { kThumbnail32BitData, 128, 128, 32, false },
- { kThumbnail8BitMask, 128, 128, 8, true },
- { 0, 0, 0, 0, false } //end marker
- };
- for(int i = 0; images[i].mac_type; i++) {
- //get QPixmap data
- QImage scaled_px = px.toImage().scaled(images[i].width, images[i].height);
-
- quint32 *sptr = (quint32 *) scaled_px.bits();
- quint32 *srow;
- uint sbpr = scaled_px.bytesPerLine();
-
- //get Handle data
- const int dbpr = images[i].width * (images[i].depth/8);
- Handle hdl = NewHandle(dbpr*images[i].height);
- if(!sptr) { //handle null pixmap
- memset((*hdl), '\0', dbpr*images[i].height);
- } else if(images[i].mask) {
- if(images[i].mac_type == kThumbnail8BitMask) {
- for(int y = 0, hindex = 0; y < images[i].height; ++y) {
- srow = sptr + (y * (sbpr/4));
- for(int x = 0; x < images[i].width; ++x)
- *((*hdl)+(hindex++)) = qAlpha(*(srow+x));
- }
- }
- } else {
- char *dest = (*hdl);
-#if defined(__i386__)
- if(images[i].depth == 32) {
- for(int y = 0; y < images[i].height; ++y) {
- uint *source = (uint*)((const uchar*)sptr+(sbpr*y));
- for(int x = 0; x < images[i].width; ++x, dest += 4)
- *((uint*)dest) = CFSwapInt32(*(source + x));
- }
- } else
-#endif
- {
- for(int y = 0; y < images[i].height; ++y)
- memcpy(dest+(y*dbpr), ((const uchar*)sptr+(sbpr*y)), dbpr);
- }
- }
-
- //set the family data to the Handle
- OSStatus set = SetIconFamilyData(iconFamily, images[i].mac_type, hdl);
- if(set != noErr)
- qWarning("%s: %d -- Unable to create icon data[%d]!! %ld",
- __FILE__, __LINE__, i, long(set));
- DisposeHandle(hdl);
- }
- }
-
- //acquire and cleanup
- IconRef ret;
- static int counter = 0;
- const OSType kQtCreator = 'CUTE';
- RegisterIconRefFromIconFamily(kQtCreator, (OSType)counter, iconFamily, &ret);
- AcquireIconRef(ret);
- UnregisterIconRef(kQtCreator, (OSType)counter);
- DisposeHandle(reinterpret_cast<Handle>(iconFamily));
- counter++;
- return ret;
-
-}
-#endif
-
-/*! \internal */
-QPaintEngine* QMacPixmapData::paintEngine() const
-{
- if (!pengine) {
- QMacPixmapData *that = const_cast<QMacPixmapData*>(this);
- that->pengine = new QCoreGraphicsPaintEngine();
- }
- return pengine;
-}
-
-void QMacPixmapData::copy(const QPixmapData *data, const QRect &rect)
-{
- if (data->pixelType() == BitmapType) {
- QBitmap::fromImage(toImage().copy(rect));
- return;
- }
-
- const QMacPixmapData *macData = static_cast<const QMacPixmapData*>(data);
-
- resize(rect.width(), rect.height());
-
- has_alpha = macData->has_alpha;
- has_mask = macData->has_mask;
- uninit = false;
-
- const int x = rect.x();
- const int y = rect.y();
- char *dest = reinterpret_cast<char*>(pixels);
- const char *src = reinterpret_cast<const char*>(macData->pixels + x) + y * macData->bytesPerRow;
- for (int i = 0; i < h; ++i) {
- memcpy(dest, src, w * 4);
- dest += bytesPerRow;
- src += macData->bytesPerRow;
- }
-
- has_alpha = macData->has_alpha;
- has_mask = macData->has_mask;
-}
-
-bool QMacPixmapData::scroll(int dx, int dy, const QRect &rect)
-{
- Q_UNUSED(dx);
- Q_UNUSED(dy);
- Q_UNUSED(rect);
- return false;
-}
-
-/*!
- \since 4.2
-
- Creates a \c CGImageRef equivalent to the QPixmap. Returns the \c CGImageRef handle.
-
- It is the caller's responsibility to release the \c CGImageRef data
- after use.
-
- \warning This function is only available on Mac OS X.
-
- \sa fromMacCGImageRef()
-*/
-CGImageRef QPixmap::toMacCGImageRef() const
-{
- return (CGImageRef)macCGHandle();
-}
-
-/*!
- \since 4.2
-
- Returns a QPixmap that is equivalent to the given \a image.
-
- \warning This function is only available on Mac OS X.
-
- \sa toMacCGImageRef(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
-*/
-QPixmap QPixmap::fromMacCGImageRef(CGImageRef image)
-{
- const size_t w = CGImageGetWidth(image),
- h = CGImageGetHeight(image);
- QPixmap ret(w, h);
- ret.fill(Qt::transparent);
- CGRect rect = CGRectMake(0, 0, w, h);
- CGContextRef ctx = qt_mac_cg_context(&ret);
- qt_mac_drawCGImage(ctx, &rect, image);
- CGContextRelease(ctx);
- return ret;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qpixmap_mac_p.h b/src/gui/platforms/mac/qpixmap_mac_p.h
deleted file mode 100644
index 307e38aceb..0000000000
--- a/src/gui/platforms/mac/qpixmap_mac_p.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** 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 QPIXMAP_MAC_P_H
-#define QPIXMAP_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/private/qpixmapdata_p.h>
-#include <QtGui/private/qpixmapdatafactory_p.h>
-#include <QtGui/private/qt_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QMacPixmapData : public QPixmapData
-{
-public:
- QMacPixmapData(PixelType type);
- ~QMacPixmapData();
-
- QPixmapData *createCompatiblePixmapData() const;
-
- void resize(int width, int height);
- void fromImage(const QImage &image, Qt::ImageConversionFlags flags);
- void copy(const QPixmapData *data, const QRect &rect);
- bool scroll(int dx, int dy, const QRect &rect);
-
- int metric(QPaintDevice::PaintDeviceMetric metric) const;
- void fill(const QColor &color);
- QBitmap mask() const;
- void setMask(const QBitmap &mask);
- bool hasAlphaChannel() const;
-// QPixmap transformed(const QTransform &matrix,
-// Qt::TransformationMode mode) const;
- void setAlphaChannel(const QPixmap &alphaChannel);
- QPixmap alphaChannel() const;
- QImage toImage() const;
- QPaintEngine* paintEngine() const;
-
-private:
-
- uint has_alpha : 1, has_mask : 1, uninit : 1;
-
- void macSetHasAlpha(bool b);
- void macGetAlphaChannel(QMacPixmapData *, bool asMask) const;
- void macSetAlphaChannel(const QMacPixmapData *, bool asMask);
- void macCreateCGImageRef();
- void macCreatePixels();
- void macReleaseCGImageRef();
- /*
- pixels stores the pixmap data. pixelsToFree is either 0 or some memory
- block that was bound to a CGImageRef and released, and for which the
- release callback has been called. There are two uses to pixelsToFree:
-
- 1. If pixels == pixelsToFree, then we know that the CGImageRef is done\
- with the data and we can modify pixels without breaking CGImageRef's
- mutability invariant.
-
- 2. If pixels != pixelsToFree and pixelsToFree != 0, then we can reuse
- pixelsToFree later on instead of malloc'ing memory.
- */
- quint32 *pixels;
- uint pixelsSize;
- quint32 *pixelsToFree;
- uint bytesPerRow;
- QRectF cg_mask_rect;
- CGImageRef cg_data, cg_dataBeingReleased, cg_mask;
- static QSet<QMacPixmapData*> validDataPointers;
-
- QPaintEngine *pengine;
-
- friend class QPixmap;
- friend class QRasterBuffer;
- friend class QRasterPaintEngine;
- friend class QCoreGraphicsPaintEngine;
- friend CGImageRef qt_mac_create_imagemask(const QPixmap&, const QRectF&);
- friend quint32 *qt_mac_pixmap_get_base(const QPixmap*);
- friend int qt_mac_pixmap_get_bytes_per_line(const QPixmap*);
- friend void qt_mac_cgimage_data_free(void *, const void*, size_t);
- friend IconRef qt_mac_create_iconref(const QPixmap&);
- friend CGContextRef qt_mac_cg_context(const QPaintDevice*);
- friend QColor qcolorForThemeTextColor(ThemeTextColor themeColor);
-};
-
-QT_END_NAMESPACE
-
-#endif // QPIXMAP_MAC_P_H
diff --git a/src/gui/platforms/mac/qprintengine_mac.mm b/src/gui/platforms/mac/qprintengine_mac.mm
deleted file mode 100644
index 1dce30301f..0000000000
--- a/src/gui/platforms/mac/qprintengine_mac.mm
+++ /dev/null
@@ -1,911 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qprintengine_mac_p.h>
-#include <qdebug.h>
-#include <qthread.h>
-#include <QtCore/qcoreapplication.h>
-
-#ifndef QT_NO_PRINTER
-
-QT_BEGIN_NAMESPACE
-
-extern QSizeF qt_paperSizeToQSizeF(QPrinter::PaperSize size);
-
-QMacPrintEngine::QMacPrintEngine(QPrinter::PrinterMode mode) : QPaintEngine(*(new QMacPrintEnginePrivate))
-{
- Q_D(QMacPrintEngine);
- d->mode = mode;
- d->initialize();
-}
-
-bool QMacPrintEngine::begin(QPaintDevice *dev)
-{
- Q_D(QMacPrintEngine);
-
- Q_ASSERT(dev && dev->devType() == QInternal::Printer);
- if (!static_cast<QPrinter *>(dev)->isValid())
- return false;
-
- if (d->state == QPrinter::Idle && !d->isPrintSessionInitialized()) // Need to reinitialize
- d->initialize();
-
- d->paintEngine->state = state;
- d->paintEngine->begin(dev);
- Q_ASSERT_X(d->state == QPrinter::Idle, "QMacPrintEngine", "printer already active");
-
- if (PMSessionValidatePrintSettings(d->session, d->settings, kPMDontWantBoolean) != noErr
- || PMSessionValidatePageFormat(d->session, d->format, kPMDontWantBoolean) != noErr) {
- d->state = QPrinter::Error;
- return false;
- }
-
- if (!d->outputFilename.isEmpty()) {
- QCFType<CFURLRef> outFile = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault,
- QCFString(d->outputFilename),
- kCFURLPOSIXPathStyle,
- false);
- if (PMSessionSetDestination(d->session, d->settings, kPMDestinationFile,
- kPMDocumentFormatPDF, outFile) != noErr) {
- qWarning("QMacPrintEngine::begin: Problem setting file [%s]", d->outputFilename.toUtf8().constData());
- return false;
- }
- }
- OSStatus status = noErr;
-#ifndef QT_MAC_USE_COCOA
- status = d->shouldSuppressStatus() ? PMSessionBeginCGDocumentNoDialog(d->session, d->settings, d->format)
- : PMSessionBeginCGDocument(d->session, d->settings, d->format);
-#else
- status = PMSessionBeginCGDocumentNoDialog(d->session, d->settings, d->format);
-#endif
-
- if (status != noErr) {
- d->state = QPrinter::Error;
- return false;
- }
-
- d->state = QPrinter::Active;
- setActive(true);
- d->newPage_helper();
- return true;
-}
-
-bool QMacPrintEngine::end()
-{
- Q_D(QMacPrintEngine);
- if (d->state == QPrinter::Aborted)
- return true; // I was just here a function call ago :)
- if(d->paintEngine->type() == QPaintEngine::CoreGraphics) {
- // We dont need the paint engine to call restoreGraphicsState()
- static_cast<QCoreGraphicsPaintEngine*>(d->paintEngine)->d_func()->stackCount = 0;
- static_cast<QCoreGraphicsPaintEngine*>(d->paintEngine)->d_func()->hd = 0;
- }
- d->paintEngine->end();
- if (d->state != QPrinter::Idle)
- d->releaseSession();
- d->state = QPrinter::Idle;
- return true;
-}
-
-QPaintEngine *
-QMacPrintEngine::paintEngine() const
-{
- return d_func()->paintEngine;
-}
-
-Qt::HANDLE QMacPrintEngine::handle() const
-{
- QCoreGraphicsPaintEngine *cgEngine = static_cast<QCoreGraphicsPaintEngine*>(paintEngine());
- return cgEngine->d_func()->hd;
-}
-
-QMacPrintEnginePrivate::~QMacPrintEnginePrivate()
-{
-#ifdef QT_MAC_USE_COCOA
- [printInfo release];
-#endif
- delete paintEngine;
-}
-
-void QMacPrintEnginePrivate::setPaperSize(QPrinter::PaperSize ps)
-{
- Q_Q(QMacPrintEngine);
- QSizeF newSize = qt_paperSizeToQSizeF(ps);
- QCFType<CFArrayRef> formats;
- PMPrinter printer;
-
- if (PMSessionGetCurrentPrinter(session, &printer) == noErr
- && PMSessionCreatePageFormatList(session, printer, &formats) == noErr) {
- CFIndex total = CFArrayGetCount(formats);
- PMPageFormat tmp;
- PMRect paper;
- for (CFIndex idx = 0; idx < total; ++idx) {
- tmp = static_cast<PMPageFormat>(
- const_cast<void *>(CFArrayGetValueAtIndex(formats, idx)));
- PMGetUnadjustedPaperRect(tmp, &paper);
- int wMM = int((paper.right - paper.left) / 72 * 25.4 + 0.5);
- int hMM = int((paper.bottom - paper.top) / 72 * 25.4 + 0.5);
- if (newSize.width() == wMM && newSize.height() == hMM) {
- PMCopyPageFormat(tmp, format);
- // reset the orientation and resolution as they are lost in the copy.
- q->setProperty(QPrintEngine::PPK_Orientation, orient);
- if (PMSessionValidatePageFormat(session, format, kPMDontWantBoolean) != noErr) {
- // Don't know, warn for the moment.
- qWarning("QMacPrintEngine, problem setting format and resolution for this page size");
- }
- break;
- }
- }
- }
-}
-
-QPrinter::PaperSize QMacPrintEnginePrivate::paperSize() const
-{
- PMRect paper;
- PMGetUnadjustedPaperRect(format, &paper);
- int wMM = int((paper.right - paper.left) / 72 * 25.4 + 0.5);
- int hMM = int((paper.bottom - paper.top) / 72 * 25.4 + 0.5);
- for (int i = QPrinter::A4; i < QPrinter::NPaperSize; ++i) {
- QSizeF s = qt_paperSizeToQSizeF(QPrinter::PaperSize(i));
- if (s.width() == wMM && s.height() == hMM)
- return (QPrinter::PaperSize)i;
- }
- return QPrinter::Custom;
-}
-
-QList<QVariant> QMacPrintEnginePrivate::supportedResolutions() const
-{
- Q_ASSERT_X(session, "QMacPrinterEngine::supportedResolutions",
- "must have a valid printer session");
- UInt32 resCount;
- QList<QVariant> resolutions;
- PMPrinter printer;
- if (PMSessionGetCurrentPrinter(session, &printer) == noErr) {
- PMResolution res;
- OSStatus status = PMPrinterGetPrinterResolutionCount(printer, &resCount);
- if (status == kPMNotImplemented) {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
- // *Sigh* we have to use the non-indexed version.
- if (PMPrinterGetPrinterResolution(printer, kPMMinSquareResolution, &res) == noErr)
- resolutions.append(int(res.hRes));
- if (PMPrinterGetPrinterResolution(printer, kPMMaxSquareResolution, &res) == noErr) {
- QVariant var(int(res.hRes));
- if (!resolutions.contains(var))
- resolutions.append(var);
- }
- if (PMPrinterGetPrinterResolution(printer, kPMDefaultResolution, &res) == noErr) {
- QVariant var(int(res.hRes));
- if (!resolutions.contains(var))
- resolutions.append(var);
- }
-#endif
- } else if (status == noErr) {
- // According to the docs, index start at 1.
- for (UInt32 i = 1; i <= resCount; ++i) {
- if (PMPrinterGetIndexedPrinterResolution(printer, i, &res) == noErr)
- resolutions.append(QVariant(int(res.hRes)));
- }
- } else {
- qWarning("QMacPrintEngine::supportedResolutions: Unexpected error: %ld", long(status));
- }
- }
- return resolutions;
-}
-
-bool QMacPrintEnginePrivate::shouldSuppressStatus() const
-{
- if (suppressStatus == true)
- return true;
-
- // Supress displaying the automatic progress dialog if we are printing
- // from a non-gui thread.
- return (qApp->thread() != QThread::currentThread());
-}
-
-QPrinter::PrinterState QMacPrintEngine::printerState() const
-{
- return d_func()->state;
-}
-
-bool QMacPrintEngine::newPage()
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- OSStatus err =
-#ifndef QT_MAC_USE_COCOA
- d->shouldSuppressStatus() ? PMSessionEndPageNoDialog(d->session)
- : PMSessionEndPage(d->session);
-#else
- PMSessionEndPageNoDialog(d->session);
-#endif
- if (err != noErr) {
- if (err == kPMCancel) {
- // User canceled, we need to abort!
- abort();
- } else {
- // Not sure what the problem is...
- qWarning("QMacPrintEngine::newPage: Cannot end current page. %ld", long(err));
- d->state = QPrinter::Error;
- }
- return false;
- }
- return d->newPage_helper();
-}
-
-bool QMacPrintEngine::abort()
-{
- Q_D(QMacPrintEngine);
- if (d->state != QPrinter::Active)
- return false;
- bool ret = end();
- d->state = QPrinter::Aborted;
- return ret;
-}
-
-static inline int qt_get_PDMWidth(PMPageFormat pformat, bool fullPage,
- const PMResolution &resolution)
-{
- int val = 0;
- PMRect r;
- qreal hRatio = resolution.hRes / 72;
- if (fullPage) {
- if (PMGetAdjustedPaperRect(pformat, &r) == noErr)
- val = qRound((r.right - r.left) * hRatio);
- } else {
- if (PMGetAdjustedPageRect(pformat, &r) == noErr)
- val = qRound((r.right - r.left) * hRatio);
- }
- return val;
-}
-
-static inline int qt_get_PDMHeight(PMPageFormat pformat, bool fullPage,
- const PMResolution &resolution)
-{
- int val = 0;
- PMRect r;
- qreal vRatio = resolution.vRes / 72;
- if (fullPage) {
- if (PMGetAdjustedPaperRect(pformat, &r) == noErr)
- val = qRound((r.bottom - r.top) * vRatio);
- } else {
- if (PMGetAdjustedPageRect(pformat, &r) == noErr)
- val = qRound((r.bottom - r.top) * vRatio);
- }
- return val;
-}
-
-
-int QMacPrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
-{
- Q_D(const QMacPrintEngine);
- int val = 1;
- switch (m) {
- case QPaintDevice::PdmWidth:
- if (d->hasCustomPaperSize) {
- val = qRound(d->customSize.width());
- if (d->hasCustomPageMargins) {
- val -= qRound(d->leftMargin + d->rightMargin);
- } else {
- QList<QVariant> margins = property(QPrintEngine::PPK_PageMargins).toList();
- val -= qRound(margins.at(0).toDouble() + margins.at(2).toDouble());
- }
- } else {
- val = qt_get_PDMWidth(d->format, property(PPK_FullPage).toBool(), d->resolution);
- }
- break;
- case QPaintDevice::PdmHeight:
- if (d->hasCustomPaperSize) {
- val = qRound(d->customSize.height());
- if (d->hasCustomPageMargins) {
- val -= qRound(d->topMargin + d->bottomMargin);
- } else {
- QList<QVariant> margins = property(QPrintEngine::PPK_PageMargins).toList();
- val -= qRound(margins.at(1).toDouble() + margins.at(3).toDouble());
- }
- } else {
- val = qt_get_PDMHeight(d->format, property(PPK_FullPage).toBool(), d->resolution);
- }
- break;
- case QPaintDevice::PdmWidthMM:
- val = metric(QPaintDevice::PdmWidth);
- val = int((val * 254 + 5 * d->resolution.hRes) / (10 * d->resolution.hRes));
- break;
- case QPaintDevice::PdmHeightMM:
- val = metric(QPaintDevice::PdmHeight);
- val = int((val * 254 + 5 * d->resolution.vRes) / (10 * d->resolution.vRes));
- break;
- case QPaintDevice::PdmPhysicalDpiX:
- case QPaintDevice::PdmPhysicalDpiY: {
- PMPrinter printer;
- if(PMSessionGetCurrentPrinter(d->session, &printer) == noErr) {
- PMResolution resolution;
-#ifndef QT_MAC_USE_COCOA
-# if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- PMPrinterGetOutputResolution(printer, d->settings, &resolution);
- } else
-# endif
- {
- PMPrinterGetPrinterResolution(printer, kPMCurrentValue, &resolution);
- }
-#else
- PMPrinterGetOutputResolution(printer, d->settings, &resolution);
-#endif
- val = (int)resolution.vRes;
- break;
- }
- //otherwise fall through
- }
- case QPaintDevice::PdmDpiY:
- val = (int)d->resolution.vRes;
- break;
- case QPaintDevice::PdmDpiX:
- val = (int)d->resolution.hRes;
- break;
- case QPaintDevice::PdmNumColors:
- val = (1 << metric(QPaintDevice::PdmDepth));
- break;
- case QPaintDevice::PdmDepth:
- val = 24;
- break;
- default:
- val = 0;
- qWarning("QPrinter::metric: Invalid metric command");
- }
- return val;
-}
-
-void QMacPrintEnginePrivate::initialize()
-{
- Q_Q(QMacPrintEngine);
-
-#ifndef QT_MAC_USE_COCOA
- Q_ASSERT(!session);
-#else
- Q_ASSERT(!printInfo);
-#endif
-
- if (!paintEngine)
- paintEngine = new QCoreGraphicsPaintEngine();
-
- q->gccaps = paintEngine->gccaps;
-
- fullPage = false;
-
-#ifndef QT_MAC_USE_COCOA
- if (PMCreateSession(&session) != 0)
- session = 0;
-#else
- QMacCocoaAutoReleasePool pool;
- printInfo = [[NSPrintInfo alloc] initWithDictionary:[NSDictionary dictionary]];
- session = static_cast<PMPrintSession>([printInfo PMPrintSession]);
-#endif
-
- PMPrinter printer;
- if (session && PMSessionGetCurrentPrinter(session, &printer) == noErr) {
- QList<QVariant> resolutions = supportedResolutions();
- if (!resolutions.isEmpty() && mode != QPrinter::ScreenResolution) {
- if (resolutions.count() > 1 && mode == QPrinter::HighResolution) {
- int max = 0;
- for (int i = 0; i < resolutions.count(); ++i) {
- int value = resolutions.at(i).toInt();
- if (value > max)
- max = value;
- }
- resolution.hRes = resolution.vRes = max;
- } else {
- resolution.hRes = resolution.vRes = resolutions.at(0).toInt();
- }
- if(resolution.hRes == 0)
- resolution.hRes = resolution.vRes = 600;
- } else {
- resolution.hRes = resolution.vRes = qt_defaultDpi();
- }
- }
-
-#ifndef QT_MAC_USE_COCOA
- bool settingsInitialized = (settings != 0);
- bool settingsOK = !settingsInitialized ? PMCreatePrintSettings(&settings) == noErr : true;
- if (settingsOK && !settingsInitialized)
- settingsOK = PMSessionDefaultPrintSettings(session, settings) == noErr;
-
-
- bool formatInitialized = (format != 0);
- bool formatOK = !formatInitialized ? PMCreatePageFormat(&format) == noErr : true;
- if (formatOK) {
- if (!formatInitialized) {
- formatOK = PMSessionDefaultPageFormat(session, format) == noErr;
- }
- formatOK = PMSessionValidatePageFormat(session, format, kPMDontWantBoolean) == noErr;
- }
-#else
- settings = static_cast<PMPrintSettings>([printInfo PMPrintSettings]);
- format = static_cast<PMPageFormat>([printInfo PMPageFormat]);
-#endif
-
-#ifndef QT_MAC_USE_COCOA
- if (!settingsOK || !formatOK) {
- qWarning("QMacPrintEngine::initialize: Unable to initialize QPainter");
- state = QPrinter::Error;
- }
-#endif
-
- QHash<QMacPrintEngine::PrintEnginePropertyKey, QVariant>::const_iterator propC;
- for (propC = valueCache.constBegin(); propC != valueCache.constEnd(); propC++) {
- q->setProperty(propC.key(), propC.value());
- }
-}
-
-void QMacPrintEnginePrivate::releaseSession()
-{
-#ifndef QT_MAC_USE_COCOA
- if (shouldSuppressStatus()) {
- PMSessionEndPageNoDialog(session);
- PMSessionEndDocumentNoDialog(session);
- } else {
- PMSessionEndPage(session);
- PMSessionEndDocument(session);
- }
- PMRelease(session);
-#else
- PMSessionEndPageNoDialog(session);
- PMSessionEndDocumentNoDialog(session);
- [printInfo release];
-#endif
- printInfo = 0;
- session = 0;
-}
-
-bool QMacPrintEnginePrivate::newPage_helper()
-{
- Q_Q(QMacPrintEngine);
- Q_ASSERT(state == QPrinter::Active);
-
- if (PMSessionError(session) != noErr) {
- q->abort();
- return false;
- }
-
- // pop the stack of saved graphic states, in case we get the same
- // context back - either way, the stack count should be 0 when we
- // get the new one
- QCoreGraphicsPaintEngine *cgEngine = static_cast<QCoreGraphicsPaintEngine*>(paintEngine);
- while (cgEngine->d_func()->stackCount > 0)
- cgEngine->d_func()->restoreGraphicsState();
-
- OSStatus status =
-#ifndef QT_MAC_USE_COCOA
- shouldSuppressStatus() ? PMSessionBeginPageNoDialog(session, format, 0)
- : PMSessionBeginPage(session, format, 0);
-#else
- PMSessionBeginPageNoDialog(session, format, 0);
-#endif
- if(status != noErr) {
- state = QPrinter::Error;
- return false;
- }
-
- QRect page = q->property(QPrintEngine::PPK_PageRect).toRect();
- QRect paper = q->property(QPrintEngine::PPK_PaperRect).toRect();
-
- CGContextRef cgContext;
- OSStatus err = noErr;
- err = PMSessionGetCGGraphicsContext(session, &cgContext);
- if(err != noErr) {
- qWarning("QMacPrintEngine::newPage: Cannot retrieve CoreGraphics context: %ld", long(err));
- state = QPrinter::Error;
- return false;
- }
- cgEngine->d_func()->hd = cgContext;
-
- // Set the resolution as a scaling ration of 72 (the default).
- CGContextScaleCTM(cgContext, 72 / resolution.hRes, 72 / resolution.vRes);
-
- CGContextScaleCTM(cgContext, 1, -1);
- CGContextTranslateCTM(cgContext, 0, -paper.height());
- if (!fullPage)
- CGContextTranslateCTM(cgContext, page.x() - paper.x(), page.y() - paper.y());
- cgEngine->d_func()->orig_xform = CGContextGetCTM(cgContext);
- cgEngine->d_func()->setClip(0);
- cgEngine->state->dirtyFlags = QPaintEngine::DirtyFlag(QPaintEngine::AllDirty
- & ~(QPaintEngine::DirtyClipEnabled
- | QPaintEngine::DirtyClipRegion
- | QPaintEngine::DirtyClipPath));
- if (cgEngine->painter()->hasClipping())
- cgEngine->state->dirtyFlags |= QPaintEngine::DirtyClipEnabled;
- cgEngine->syncState();
- return true;
-}
-
-
-void QMacPrintEngine::updateState(const QPaintEngineState &state)
-{
- d_func()->paintEngine->updateState(state);
-}
-
-void QMacPrintEngine::drawRects(const QRectF *r, int num)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawRects(r, num);
-}
-
-void QMacPrintEngine::drawPoints(const QPointF *points, int pointCount)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawPoints(points, pointCount);
-}
-
-void QMacPrintEngine::drawEllipse(const QRectF &r)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawEllipse(r);
-}
-
-void QMacPrintEngine::drawLines(const QLineF *lines, int lineCount)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawLines(lines, lineCount);
-}
-
-void QMacPrintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawPolygon(points, pointCount, mode);
-}
-
-void QMacPrintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawPixmap(r, pm, sr);
-}
-
-void QMacPrintEngine::drawImage(const QRectF &r, const QImage &pm, const QRectF &sr, Qt::ImageConversionFlags flags)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawImage(r, pm, sr, flags);
-}
-
-void QMacPrintEngine::drawTextItem(const QPointF &p, const QTextItem &ti)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawTextItem(p, ti);
-}
-
-void QMacPrintEngine::drawTiledPixmap(const QRectF &dr, const QPixmap &pixmap, const QPointF &sr)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawTiledPixmap(dr, pixmap, sr);
-}
-
-void QMacPrintEngine::drawPath(const QPainterPath &path)
-{
- Q_D(QMacPrintEngine);
- Q_ASSERT(d->state == QPrinter::Active);
- d->paintEngine->drawPath(path);
-}
-
-
-void QMacPrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant &value)
-{
- Q_D(QMacPrintEngine);
-
- d->valueCache.insert(key, value);
- if (!d->session)
- return;
-
- switch (key) {
- case PPK_CollateCopies:
- break;
- case PPK_ColorMode:
- break;
- case PPK_Creator:
- break;
- case PPK_DocumentName:
- break;
- case PPK_PageOrder:
- break;
- case PPK_PaperSource:
- break;
- case PPK_SelectionOption:
- break;
- case PPK_Resolution: {
- PMPrinter printer;
- UInt32 count;
- if (PMSessionGetCurrentPrinter(d->session, &printer) != noErr)
- break;
- if (PMPrinterGetPrinterResolutionCount(printer, &count) != noErr)
- break;
- PMResolution resolution = { 0.0, 0.0 };
- PMResolution bestResolution = { 0.0, 0.0 };
- int dpi = value.toInt();
- int bestDistance = INT_MAX;
- for (UInt32 i = 1; i <= count; ++i) { // Yes, it starts at 1
- if (PMPrinterGetIndexedPrinterResolution(printer, i, &resolution) == noErr) {
- if (dpi == int(resolution.hRes)) {
- bestResolution = resolution;
- break;
- } else {
- int distance = qAbs(dpi - int(resolution.hRes));
- if (distance < bestDistance) {
- bestDistance = distance;
- bestResolution = resolution;
- }
- }
- }
- }
- PMSessionValidatePageFormat(d->session, d->format, kPMDontWantBoolean);
- break;
- }
-
- case PPK_FullPage:
- d->fullPage = value.toBool();
- break;
- case PPK_CopyCount: // fallthrough
- case PPK_NumberOfCopies:
- PMSetCopies(d->settings, value.toInt(), false);
- break;
- case PPK_Orientation: {
- if (d->state == QPrinter::Active) {
- qWarning("QMacPrintEngine::setOrientation: Orientation cannot be changed during a print job, ignoring change");
- } else {
- QPrinter::Orientation newOrientation = QPrinter::Orientation(value.toInt());
- if (d->hasCustomPaperSize && (d->orient != newOrientation))
- d->customSize = QSizeF(d->customSize.height(), d->customSize.width());
- d->orient = newOrientation;
- PMOrientation o = d->orient == QPrinter::Portrait ? kPMPortrait : kPMLandscape;
- PMSetOrientation(d->format, o, false);
- PMSessionValidatePageFormat(d->session, d->format, kPMDontWantBoolean);
- }
- break; }
- case PPK_OutputFileName:
- d->outputFilename = value.toString();
- break;
- case PPK_PaperSize:
- d->setPaperSize(QPrinter::PaperSize(value.toInt()));
- break;
- case PPK_PrinterName: {
- bool printerNameSet = false;
- OSStatus status = noErr;
- QCFType<CFArrayRef> printerList;
- status = PMServerCreatePrinterList(kPMServerLocal, &printerList);
- if (status == noErr) {
- CFIndex count = CFArrayGetCount(printerList);
- for (CFIndex i=0; i<count; ++i) {
- PMPrinter printer = static_cast<PMPrinter>(const_cast<void *>(CFArrayGetValueAtIndex(printerList, i)));
- QString name = QCFString::toQString(PMPrinterGetName(printer));
- if (name == value.toString()) {
- status = PMSessionSetCurrentPMPrinter(d->session, printer);
- printerNameSet = true;
- break;
- }
- }
- }
- if (status != noErr)
- qWarning("QMacPrintEngine::setPrinterName: Error setting printer: %ld", long(status));
- if (!printerNameSet) {
- qWarning("QMacPrintEngine::setPrinterName: Failed to set printer named '%s'.", qPrintable(value.toString()));
- d->releaseSession();
- d->state = QPrinter::Idle;
- }
- break; }
- case PPK_SuppressSystemPrintStatus:
- d->suppressStatus = value.toBool();
- break;
- case PPK_CustomPaperSize:
- {
- PMOrientation orientation;
- PMGetOrientation(d->format, &orientation);
- d->hasCustomPaperSize = true;
- d->customSize = value.toSizeF();
- if (orientation != kPMPortrait)
- d->customSize = QSizeF(d->customSize.height(), d->customSize.width());
- break;
- }
- case PPK_PageMargins:
- {
- QList<QVariant> margins(value.toList());
- Q_ASSERT(margins.size() == 4);
- d->leftMargin = margins.at(0).toDouble();
- d->topMargin = margins.at(1).toDouble();
- d->rightMargin = margins.at(2).toDouble();
- d->bottomMargin = margins.at(3).toDouble();
- d->hasCustomPageMargins = true;
- break;
- }
-
- default:
- break;
- }
-}
-
-QVariant QMacPrintEngine::property(PrintEnginePropertyKey key) const
-{
- Q_D(const QMacPrintEngine);
- QVariant ret;
-
- if (!d->session && d->valueCache.contains(key))
- return *d->valueCache.find(key);
-
- switch (key) {
- case PPK_CollateCopies:
- ret = false;
- break;
- case PPK_ColorMode:
- ret = QPrinter::Color;
- break;
- case PPK_Creator:
- break;
- case PPK_DocumentName:
- break;
- case PPK_FullPage:
- ret = d->fullPage;
- break;
- case PPK_NumberOfCopies:
- ret = 1;
- break;
- case PPK_CopyCount: {
- UInt32 copies = 1;
- PMGetCopies(d->settings, &copies);
- ret = (uint) copies;
- break;
- }
- case PPK_SupportsMultipleCopies:
- ret = true;
- break;
- case PPK_Orientation:
- PMOrientation orientation;
- PMGetOrientation(d->format, &orientation);
- ret = orientation == kPMPortrait ? QPrinter::Portrait : QPrinter::Landscape;
- break;
- case PPK_OutputFileName:
- ret = d->outputFilename;
- break;
- case PPK_PageOrder:
- break;
- case PPK_PaperSource:
- break;
- case PPK_PageRect: {
- // PageRect is returned in device pixels
- QRect r;
- PMRect macrect, macpaper;
- qreal hRatio = d->resolution.hRes / 72;
- qreal vRatio = d->resolution.vRes / 72;
- if (d->hasCustomPaperSize) {
- r = QRect(0, 0, qRound(d->customSize.width() * hRatio), qRound(d->customSize.height() * vRatio));
- if (d->hasCustomPageMargins) {
- r.adjust(qRound(d->leftMargin * hRatio), qRound(d->topMargin * vRatio),
- -qRound(d->rightMargin * hRatio), -qRound(d->bottomMargin * vRatio));
- } else {
- QList<QVariant> margins = property(QPrintEngine::PPK_PageMargins).toList();
- r.adjust(qRound(margins.at(0).toDouble() * hRatio),
- qRound(margins.at(1).toDouble() * vRatio),
- -qRound(margins.at(2).toDouble() * hRatio),
- -qRound(margins.at(3).toDouble()) * vRatio);
- }
- } else if (PMGetAdjustedPageRect(d->format, &macrect) == noErr
- && PMGetAdjustedPaperRect(d->format, &macpaper) == noErr)
- {
- if (d->fullPage || d->hasCustomPageMargins) {
- r.setCoords(int(macpaper.left * hRatio), int(macpaper.top * vRatio),
- int(macpaper.right * hRatio), int(macpaper.bottom * vRatio));
- r.translate(-r.x(), -r.y());
- if (d->hasCustomPageMargins) {
- r.adjust(qRound(d->leftMargin * hRatio), qRound(d->topMargin * vRatio),
- -qRound(d->rightMargin * hRatio), -qRound(d->bottomMargin * vRatio));
- }
- } else {
- r.setCoords(int(macrect.left * hRatio), int(macrect.top * vRatio),
- int(macrect.right * hRatio), int(macrect.bottom * vRatio));
- r.translate(int(-macpaper.left * hRatio), int(-macpaper.top * vRatio));
- }
- }
- ret = r;
- break; }
- case PPK_PaperSize:
- ret = d->paperSize();
- break;
- case PPK_PaperRect: {
- QRect r;
- PMRect macrect;
- if (d->hasCustomPaperSize) {
- r = QRect(0, 0, qRound(d->customSize.width()), qRound(d->customSize.height()));
- } else if (PMGetAdjustedPaperRect(d->format, &macrect) == noErr) {
- qreal hRatio = d->resolution.hRes / 72;
- qreal vRatio = d->resolution.vRes / 72;
- r.setCoords(int(macrect.left * hRatio), int(macrect.top * vRatio),
- int(macrect.right * hRatio), int(macrect.bottom * vRatio));
- r.translate(-r.x(), -r.y());
- }
- ret = r;
- break; }
- case PPK_PrinterName: {
- PMPrinter printer;
- OSStatus status = PMSessionGetCurrentPrinter(d->session, &printer);
- if (status != noErr)
- qWarning("QMacPrintEngine::printerName: Failed getting current PMPrinter: %ld", long(status));
- if (printer)
- ret = QCFString::toQString(PMPrinterGetName(printer));
- break; }
- case PPK_Resolution: {
- ret = d->resolution.hRes;
- break;
- }
- case PPK_SupportedResolutions:
- ret = d->supportedResolutions();
- break;
- case PPK_CustomPaperSize:
- ret = d->customSize;
- break;
- case PPK_PageMargins:
- {
- QList<QVariant> margins;
- if (d->hasCustomPageMargins) {
- margins << d->leftMargin << d->topMargin
- << d->rightMargin << d->bottomMargin;
- } else {
- PMPaperMargins paperMargins;
- PMPaper paper;
- PMGetPageFormatPaper(d->format, &paper);
- PMPaperGetMargins(paper, &paperMargins);
- margins << paperMargins.left << paperMargins.top
- << paperMargins.right << paperMargins.bottom;
- }
- ret = margins;
- break;
- }
- default:
- break;
- }
- return ret;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
diff --git a/src/gui/platforms/mac/qprintengine_mac_p.h b/src/gui/platforms/mac/qprintengine_mac_p.h
deleted file mode 100644
index 511705d26f..0000000000
--- a/src/gui/platforms/mac/qprintengine_mac_p.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** 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 QPRINTENGINE_MAC_P_H
-#define QPRINTENGINE_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QT_NO_PRINTER
-
-#include "QtGui/qprinter.h"
-#include "QtGui/qprintengine.h"
-#include "private/qpaintengine_mac_p.h"
-#include "private/qpainter_p.h"
-
-#ifdef __OBJC__
-@class NSPrintInfo;
-#else
-typedef void NSPrintInfo;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QPrinterPrivate;
-class QMacPrintEnginePrivate;
-class QMacPrintEngine : public QPaintEngine, public QPrintEngine
-{
- Q_DECLARE_PRIVATE(QMacPrintEngine)
-public:
- QMacPrintEngine(QPrinter::PrinterMode mode);
-
- Qt::HANDLE handle() const;
-
- bool begin(QPaintDevice *dev);
- bool end();
- virtual QPaintEngine::Type type() const { return QPaintEngine::MacPrinter; }
-
- QPaintEngine *paintEngine() const;
-
- void setProperty(PrintEnginePropertyKey key, const QVariant &value);
- QVariant property(PrintEnginePropertyKey key) const;
-
- QPrinter::PrinterState printerState() const;
-
- bool newPage();
- bool abort();
- int metric(QPaintDevice::PaintDeviceMetric) const;
-
- //forwarded functions
-
- void updateState(const QPaintEngineState &state);
-
- virtual void drawLines(const QLineF *lines, int lineCount);
- virtual void drawRects(const QRectF *r, int num);
- virtual void drawPoints(const QPointF *p, int pointCount);
- virtual void drawEllipse(const QRectF &r);
- virtual void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
- virtual void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
- virtual void drawImage(const QRectF &r, const QImage &pm, const QRectF &sr, Qt::ImageConversionFlags flags);
- virtual void drawTextItem(const QPointF &p, const QTextItem &ti);
- virtual void drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, const QPointF &s);
- virtual void drawPath(const QPainterPath &);
-
-private:
- friend class QPrintDialog;
- friend class QPageSetupDialog;
-};
-
-class QMacPrintEnginePrivate : public QPaintEnginePrivate
-{
- Q_DECLARE_PUBLIC(QMacPrintEngine)
-public:
- QPrinter::PrinterMode mode;
- QPrinter::PrinterState state;
- QPrinter::Orientation orient;
- NSPrintInfo *printInfo;
- PMPageFormat format;
- PMPrintSettings settings;
- PMPrintSession session;
- PMResolution resolution;
- QString outputFilename;
- bool fullPage;
- QPaintEngine *paintEngine;
- bool suppressStatus;
- bool hasCustomPaperSize;
- QSizeF customSize;
- bool hasCustomPageMargins;
- qreal leftMargin;
- qreal topMargin;
- qreal rightMargin;
- qreal bottomMargin;
- QHash<QMacPrintEngine::PrintEnginePropertyKey, QVariant> valueCache;
- QMacPrintEnginePrivate() : mode(QPrinter::ScreenResolution), state(QPrinter::Idle),
- orient(QPrinter::Portrait), printInfo(0), format(0), settings(0),
- session(0), paintEngine(0), suppressStatus(false),
- hasCustomPaperSize(false), hasCustomPageMargins(false) {}
- ~QMacPrintEnginePrivate();
- void initialize();
- void releaseSession();
- bool newPage_helper();
- void setPaperSize(QPrinter::PaperSize ps);
- QPrinter::PaperSize paperSize() const;
- QList<QVariant> supportedResolutions() const;
- inline bool isPrintSessionInitialized() const
- {
-#ifndef QT_MAC_USE_COCOA
- return session != 0;
-#else
- return printInfo != 0;
-#endif
- }
- bool shouldSuppressStatus() const;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
-
-#endif // QPRINTENGINE_WIN_P_H
diff --git a/src/gui/platforms/mac/qprinterinfo_mac.cpp b/src/gui/platforms/mac/qprinterinfo_mac.cpp
deleted file mode 100644
index b24ab70267..0000000000
--- a/src/gui/platforms/mac/qprinterinfo_mac.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** 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 "qprinterinfo.h"
-#include "qprinterinfo_p.h"
-
-#include "private/qt_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_PRINTER
-
-extern QPrinter::PaperSize qSizeFTopaperSize(const QSizeF &size);
-
-QList<QPrinterInfo> QPrinterInfo::availablePrinters()
-{
- QList<QPrinterInfo> printers;
-
- QCFType<CFArrayRef> array;
- if (PMServerCreatePrinterList(kPMServerLocal, &array) == noErr) {
- CFIndex count = CFArrayGetCount(array);
- for (int i = 0; i < count; ++i) {
- PMPrinter printer = static_cast<PMPrinter>(const_cast<void *>(CFArrayGetValueAtIndex(array, i)));
- QString printerName = QCFString::toQString(PMPrinterGetName(printer));
-
- QPrinterInfo printerInfo(printerName);
- if (PMPrinterIsDefault(printer))
- printerInfo.d_ptr->isDefault = true;
- printers.append(printerInfo);
- }
- }
-
- return printers;
-}
-
-QPrinterInfo QPrinterInfo::defaultPrinter()
-{
- QList<QPrinterInfo> printers = availablePrinters();
- foreach (const QPrinterInfo &printerInfo, printers) {
- if (printerInfo.isDefault())
- return printerInfo;
- }
-
- return printers.value(0);
-}
-
-QList<QPrinter::PaperSize> QPrinterInfo::supportedPaperSizes() const
-{
- const Q_D(QPrinterInfo);
-
- QList<QPrinter::PaperSize> paperSizes;
- if (isNull())
- return paperSizes;
-
- PMPrinter cfPrn = PMPrinterCreateFromPrinterID(QCFString::toCFStringRef(d->name));
- if (!cfPrn)
- return paperSizes;
-
- CFArrayRef array;
- if (PMPrinterGetPaperList(cfPrn, &array) != noErr) {
- PMRelease(cfPrn);
- return paperSizes;
- }
-
- int count = CFArrayGetCount(array);
- for (int i = 0; i < count; ++i) {
- PMPaper paper = static_cast<PMPaper>(const_cast<void *>(CFArrayGetValueAtIndex(array, i)));
- double width, height;
- if (PMPaperGetWidth(paper, &width) == noErr && PMPaperGetHeight(paper, &height) == noErr) {
- QSizeF size(width * 0.3527, height * 0.3527);
- paperSizes.append(qSizeFTopaperSize(size));
- }
- }
-
- PMRelease(cfPrn);
-
- return paperSizes;
-}
-
-#endif // QT_NO_PRINTER
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qrawfont_mac.cpp b/src/gui/platforms/mac/qrawfont_mac.cpp
deleted file mode 100644
index 1ed4185a5d..0000000000
--- a/src/gui/platforms/mac/qrawfont_mac.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** 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 test suite 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 <QtCore/qglobal.h>
-
-#if !defined(QT_NO_RAWFONT)
-
-#include "qrawfont_p.h"
-#include "qfontengine_coretext_p.h"
-
-QT_BEGIN_NAMESPACE
-
-void QRawFontPrivate::platformCleanUp()
-{
-}
-
-extern int qt_defaultDpi();
-
-void QRawFontPrivate::platformLoadFromData(const QByteArray &fontData,
- int pixelSize,
- QFont::HintingPreference hintingPreference)
-{
- // Mac OS X ignores it
- Q_UNUSED(hintingPreference);
-
- QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(NULL,
- fontData.constData(), fontData.size(), NULL);
-
- CGFontRef cgFont = CGFontCreateWithDataProvider(dataProvider);
-
- if (cgFont == NULL) {
- qWarning("QRawFont::platformLoadFromData: CGFontCreateWithDataProvider failed");
- } else {
- QFontDef def;
- def.pixelSize = pixelSize;
- def.pointSize = pixelSize * 72.0 / qt_defaultDpi();
- fontEngine = new QCoreTextFontEngine(cgFont, def);
- CFRelease(cgFont);
- fontEngine->ref.ref();
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_RAWFONT
diff --git a/src/gui/platforms/mac/qregion_mac.cpp b/src/gui/platforms/mac/qregion_mac.cpp
deleted file mode 100644
index 50fd783df4..0000000000
--- a/src/gui/platforms/mac/qregion_mac.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qt_mac_p.h>
-#include "qcoreapplication.h"
-#include <qlibrary.h>
-
-QT_BEGIN_NAMESPACE
-
-QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0 };
-
-#if defined(Q_WS_MAC32) && !defined(QT_MAC_USE_COCOA)
-#define RGN_CACHE_SIZE 200
-#ifdef RGN_CACHE_SIZE
-static bool rgncache_init = false;
-static int rgncache_used;
-static RgnHandle rgncache[RGN_CACHE_SIZE];
-static void qt_mac_cleanup_rgncache()
-{
- rgncache_init = false;
- for(int i = 0; i < RGN_CACHE_SIZE; ++i) {
- if(rgncache[i]) {
- --rgncache_used;
- DisposeRgn(rgncache[i]);
- rgncache[i] = 0;
- }
- }
-}
-#endif
-
-Q_GUI_EXPORT RgnHandle qt_mac_get_rgn()
-{
-#ifdef RGN_CACHE_SIZE
- if(!rgncache_init) {
- rgncache_used = 0;
- rgncache_init = true;
- for(int i = 0; i < RGN_CACHE_SIZE; ++i)
- rgncache[i] = 0;
- qAddPostRoutine(qt_mac_cleanup_rgncache);
- } else if(rgncache_used) {
- for(int i = 0; i < RGN_CACHE_SIZE; ++i) {
- if(rgncache[i]) {
- RgnHandle ret = rgncache[i];
- SetEmptyRgn(ret);
- rgncache[i] = 0;
- --rgncache_used;
- return ret;
- }
- }
- }
-#endif
- return NewRgn();
-}
-
-Q_GUI_EXPORT void qt_mac_dispose_rgn(RgnHandle r)
-{
-#ifdef RGN_CACHE_SIZE
- if(rgncache_init && rgncache_used < RGN_CACHE_SIZE) {
- for(int i = 0; i < RGN_CACHE_SIZE; ++i) {
- if(!rgncache[i]) {
- ++rgncache_used;
- rgncache[i] = r;
- return;
- }
- }
- }
-#endif
- DisposeRgn(r);
-}
-
-static OSStatus qt_mac_get_rgn_rect(UInt16 msg, RgnHandle, const Rect *rect, void *reg)
-{
- if(msg == kQDRegionToRectsMsgParse) {
- QRect rct(rect->left, rect->top, (rect->right - rect->left), (rect->bottom - rect->top));
- if(!rct.isEmpty())
- *((QRegion *)reg) += rct;
- }
- return noErr;
-}
-
-Q_GUI_EXPORT QRegion qt_mac_convert_mac_region(RgnHandle rgn)
-{
- return QRegion::fromQDRgn(rgn);
-}
-
-QRegion QRegion::fromQDRgn(RgnHandle rgn)
-{
- QRegion ret;
- ret.detach();
- OSStatus oss = QDRegionToRects(rgn, kQDParseRegionFromTopLeft, qt_mac_get_rgn_rect, (void *)&ret);
- if(oss != noErr)
- return QRegion();
- return ret;
-}
-
-/*!
- \internal
- Create's a RegionHandle, it's the caller's responsibility to release.
-*/
-RgnHandle QRegion::toQDRgn() const
-{
- RgnHandle rgnHandle = qt_mac_get_rgn();
- if(d->qt_rgn && d->qt_rgn->numRects) {
- RgnHandle tmp_rgn = qt_mac_get_rgn();
- int n = d->qt_rgn->numRects;
- const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData();
- while (n--) {
- SetRectRgn(tmp_rgn,
- qMax(SHRT_MIN, qt_r->x()),
- qMax(SHRT_MIN, qt_r->y()),
- qMin(SHRT_MAX, qt_r->right() + 1),
- qMin(SHRT_MAX, qt_r->bottom() + 1));
- UnionRgn(rgnHandle, tmp_rgn, rgnHandle);
- ++qt_r;
- }
- qt_mac_dispose_rgn(tmp_rgn);
- }
- return rgnHandle;
-}
-
-/*!
- \internal
- Create's a RegionHandle, it's the caller's responsibility to release.
- Returns 0 if the QRegion overflows.
-*/
-RgnHandle QRegion::toQDRgnForUpdate_sys() const
-{
- RgnHandle rgnHandle = qt_mac_get_rgn();
- if(d->qt_rgn && d->qt_rgn->numRects) {
- RgnHandle tmp_rgn = qt_mac_get_rgn();
- int n = d->qt_rgn->numRects;
- const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData();
- while (n--) {
-
- // detect overflow. Tested for use with HIViewSetNeedsDisplayInRegion
- // in QWidgetPrivate::update_sys().
- enum { HIViewSetNeedsDisplayInRegionOverflow = 10000 }; // empirically determined conservative value
- if (qt_r->right() > HIViewSetNeedsDisplayInRegionOverflow || qt_r->bottom() > HIViewSetNeedsDisplayInRegionOverflow) {
- qt_mac_dispose_rgn(tmp_rgn);
- qt_mac_dispose_rgn(rgnHandle);
- return 0;
- }
-
- SetRectRgn(tmp_rgn,
- qMax(SHRT_MIN, qt_r->x()),
- qMax(SHRT_MIN, qt_r->y()),
- qMin(SHRT_MAX, qt_r->right() + 1),
- qMin(SHRT_MAX, qt_r->bottom() + 1));
- UnionRgn(rgnHandle, tmp_rgn, rgnHandle);
- ++qt_r;
- }
- qt_mac_dispose_rgn(tmp_rgn);
- }
- return rgnHandle;
-}
-
-#endif
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-OSStatus QRegion::shape2QRegionHelper(int inMessage, HIShapeRef,
- const CGRect *inRect, void *inRefcon)
-{
- QRegion *region = static_cast<QRegion *>(inRefcon);
- if (!region)
- return paramErr;
-
- switch (inMessage) {
- case kHIShapeEnumerateRect:
- *region += QRect(inRect->origin.x, inRect->origin.y,
- inRect->size.width, inRect->size.height);
- break;
- case kHIShapeEnumerateInit:
- // Assume the region is already setup correctly
- case kHIShapeEnumerateTerminate:
- default:
- break;
- }
- return noErr;
-}
-#endif
-
-/*!
- \internal
- Create's a mutable shape, it's the caller's responsibility to release.
- WARNING: this function clamps the coordinates to SHRT_MIN/MAX on 10.4 and below.
-*/
-HIMutableShapeRef QRegion::toHIMutableShape() const
-{
- HIMutableShapeRef shape = HIShapeCreateMutable();
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- if (d->qt_rgn && d->qt_rgn->numRects) {
- int n = d->qt_rgn->numRects;
- const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData();
- while (n--) {
- CGRect cgRect = CGRectMake(qt_r->x(), qt_r->y(), qt_r->width(), qt_r->height());
- HIShapeUnionWithRect(shape, &cgRect);
- ++qt_r;
- }
- }
- } else
-#endif
- {
-#ifndef QT_MAC_USE_COCOA
- QCFType<HIShapeRef> qdShape = HIShapeCreateWithQDRgn(QMacSmartQuickDrawRegion(toQDRgn()));
- HIShapeUnion(qdShape, shape, shape);
-#endif
- }
- return shape;
-}
-
-#if !defined(Q_WS_MAC64) && !defined(QT_MAC_USE_COCOA)
-typedef OSStatus (*PtrHIShapeGetAsQDRgn)(HIShapeRef, RgnHandle);
-static PtrHIShapeGetAsQDRgn ptrHIShapeGetAsQDRgn = 0;
-#endif
-
-
-QRegion QRegion::fromHIShapeRef(HIShapeRef shape)
-{
- QRegion returnRegion;
- returnRegion.detach();
- // Begin gratuitous #if-defery
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-# ifndef Q_WS_MAC64
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-# endif
- HIShapeEnumerate(shape, kHIShapeParseFromTopLeft, shape2QRegionHelper, &returnRegion);
-# ifndef Q_WS_MAC64
- } else
-# endif
-#endif
- {
-#if !defined(Q_WS_MAC64) && !defined(QT_MAC_USE_COCOA)
- if (ptrHIShapeGetAsQDRgn == 0) {
- QLibrary library(QLatin1String("/System/Library/Frameworks/Carbon.framework/Carbon"));
- library.setLoadHints(QLibrary::ExportExternalSymbolsHint);
- ptrHIShapeGetAsQDRgn = reinterpret_cast<PtrHIShapeGetAsQDRgn>(library.resolve("HIShapeGetAsQDRgn"));
- }
- RgnHandle rgn = qt_mac_get_rgn();
- ptrHIShapeGetAsQDRgn(shape, rgn);
- returnRegion = QRegion::fromQDRgn(rgn);
- qt_mac_dispose_rgn(rgn);
-#endif
- }
- return returnRegion;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qsound_mac.mm b/src/gui/platforms/mac/qsound_mac.mm
deleted file mode 100644
index 5a9af135b0..0000000000
--- a/src/gui/platforms/mac/qsound_mac.mm
+++ /dev/null
@@ -1,190 +0,0 @@
-/****************************************************************************
-**
-** 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 <qapplication.h>
-#include "qsound.h"
-#include "qsound_p.h"
-#include <private/qt_mac_p.h>
-#include <qhash.h>
-#include <qdebug.h>
-#import <AppKit/AppKit.h>
-
-#include <AppKit/NSSound.h>
-
-QT_BEGIN_NAMESPACE
-
-void qt_mac_beep()
-{
- NSBeep();
-}
-
-QT_END_NAMESPACE
-
-#ifndef QT_NO_SOUND
-
-QT_BEGIN_NAMESPACE
-
-typedef QHash<QSound *, NSSound const *> Sounds;
-static Sounds sounds;
-
-class QAuServerMac : public QAuServer
-{
- Q_OBJECT
-public:
- QAuServerMac(QObject* parent) : QAuServer(parent) { }
- void play(const QString& filename);
- void play(QSound *s);
- void stop(QSound*);
- bool okay() { return true; }
- using QAuServer::decLoop; // promote to public.
-protected:
- NSSound *createNSSound(const QString &filename, QSound *qSound);
-};
-
-QT_END_NAMESPACE
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-@protocol NSSoundDelegate <NSObject>
--(void)sound:(NSSound *)sound didFinishPlaying:(BOOL)aBool;
-@end
-#endif
-
-QT_USE_NAMESPACE
-
-@interface QT_MANGLE_NAMESPACE(QMacSoundDelegate) : NSObject<NSSoundDelegate> {
- QSound *qSound; // may be null.
- QAuServerMac* server;
-}
--(id)initWithQSound:(QSound*)sound:(QAuServerMac*)server;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QMacSoundDelegate)
--(id)initWithQSound:(QSound*)s:(QAuServerMac*)serv {
- self = [super init];
- if(self) {
- qSound = s;
- server = serv;
- }
- return self;
-}
-
-// Delegate function that gets called each time a sound finishes.
--(void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finishedOk
-{
- // qSound is null if this sound was started by play(QString),
- // in which case there is no corresponding QSound object.
- if (qSound == 0) {
- [sound release];
- [self release];
- return;
- }
-
- // finishedOk is false if the sound cold not be played or
- // if it was interrupted by stop().
- if (finishedOk == false) {
- sounds.remove(qSound);
- [sound release];
- [self release];
- return;
- }
-
- // Check if the sound should loop "forever" (until stop).
- if (qSound->loops() == -1) {
- [sound play];
- return;
- }
-
- const int remainingIterations = server->decLoop(qSound);
- if (remainingIterations > 0) {
- [sound play];
- } else {
- sounds.remove(qSound);
- [sound release];
- [self release];
- }
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-void QAuServerMac::play(const QString &fileName)
-{
- QMacCocoaAutoReleasePool pool;
- NSSound * const nsSound = createNSSound(fileName, 0);
- [nsSound play];
-}
-
-void QAuServerMac::play(QSound *qSound)
-{
- QMacCocoaAutoReleasePool pool;
- NSSound * const nsSound = createNSSound(qSound->fileName(), qSound);
- [nsSound play];
- // Keep track of the nsSound object so we can find it again in stop().
- sounds[qSound] = nsSound;
-}
-
-void QAuServerMac::stop(QSound *qSound)
-{
- Sounds::const_iterator it = sounds.constFind(qSound);
- if (it != sounds.constEnd())
- [*it stop];
-}
-
-// Creates an NSSound object and installs a "sound finished" callack delegate on it.
-NSSound *QAuServerMac::createNSSound(const QString &fileName, QSound *qSound)
-{
- NSString *nsFileName = const_cast<NSString *>(reinterpret_cast<const NSString *>(QCFString::toCFStringRef(fileName)));
- NSSound * const nsSound = [[NSSound alloc] initWithContentsOfFile: nsFileName byReference:YES];
- QT_MANGLE_NAMESPACE(QMacSoundDelegate) * const delegate = [[QT_MANGLE_NAMESPACE(QMacSoundDelegate) alloc] initWithQSound:qSound:this];
- [nsSound setDelegate:delegate];
- [nsFileName release];
- return nsSound;
-}
-
-QAuServer* qt_new_audio_server()
-{
- return new QAuServerMac(qApp);
-}
-
-QT_END_NAMESPACE
-
-#include "qsound_mac.moc"
-
-#endif // QT_NO_SOUND
diff --git a/src/gui/platforms/mac/qt_cocoa_helpers_mac.mm b/src/gui/platforms/mac/qt_cocoa_helpers_mac.mm
deleted file mode 100644
index 32123ee682..0000000000
--- a/src/gui/platforms/mac/qt_cocoa_helpers_mac.mm
+++ /dev/null
@@ -1,1824 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qcore_mac_p.h>
-#include <qaction.h>
-#include <qwidget.h>
-#include <qdesktopwidget.h>
-#include <qevent.h>
-#include <qpixmapcache.h>
-#include <qvarlengtharray.h>
-#include <private/qevent_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qapplication_p.h>
-#include <private/qcocoaapplication_mac_p.h>
-#include <private/qcocoawindow_mac_p.h>
-#include <private/qcocoaview_mac_p.h>
-#include <private/qkeymapper_p.h>
-#include <private/qwidget_p.h>
-#include <private/qcocoawindow_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-// Cmd + left mousebutton should produce a right button
-// press (mainly for mac users with one-button mice):
-static bool qt_leftButtonIsRightButton = false;
-#endif
-
-Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader);
-
-QMacWindowFader::QMacWindowFader()
- : m_duration(0.250)
-{
-}
-
-QMacWindowFader *QMacWindowFader::currentFader()
-{
- return macwindowFader();
-}
-
-void QMacWindowFader::registerWindowToFade(QWidget *window)
-{
- m_windowsToFade.append(window);
-}
-
-void QMacWindowFader::performFade()
-{
- const QWidgetList myWidgetsToFade = m_windowsToFade;
- const int widgetCount = myWidgetsToFade.count();
-#if QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- [NSAnimationContext beginGrouping];
- [[NSAnimationContext currentContext] setDuration:NSTimeInterval(m_duration)];
-#endif
-
- for (int i = 0; i < widgetCount; ++i) {
- QWidget *widget = m_windowsToFade.at(i);
- OSWindowRef window = qt_mac_window_for(widget);
-#if QT_MAC_USE_COCOA
- [[window animator] setAlphaValue:0.0];
- QTimer::singleShot(qRound(m_duration * 1000), widget, SLOT(hide()));
-#else
- TransitionWindowOptions options = {0, m_duration, 0, 0};
- TransitionWindowWithOptions(window, kWindowFadeTransitionEffect, kWindowHideTransitionAction,
- 0, 1, &options);
-#endif
- }
-#if QT_MAC_USE_COCOA
- [NSAnimationContext endGrouping];
-#endif
- m_duration = 0.250;
- m_windowsToFade.clear();
-}
-
-extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); // qapplication.cpp;
-extern QWidget * mac_mouse_grabber;
-extern QWidget *qt_button_down; //qapplication_mac.cpp
-extern QPointer<QWidget> qt_last_mouse_receiver;
-extern OSViewRef qt_mac_effectiveview_for(const QWidget *w);
-extern void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse); // qcursor_mac.mm
-
-void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds)
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
-#endif
- OSWindowRef wnd = static_cast<OSWindowRef>(window);
- if (wnd) {
- QWidget *widget;
-#if QT_MAC_USE_COCOA
- widget = [wnd QT_MANGLE_NAMESPACE(qt_qwidget)];
-#else
- const UInt32 kWidgetCreatorQt = kEventClassQt;
- enum {
- kWidgetPropertyQWidget = 'QWId' //QWidget *
- };
- if (GetWindowProperty(static_cast<WindowRef>(window), kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(widget), 0, &widget) != noErr)
- widget = 0;
-#endif
- if (widget) {
- QMacWindowFader::currentFader()->setFadeDuration(durationSeconds);
- QMacWindowFader::currentFader()->registerWindowToFade(widget);
- QMacWindowFader::currentFader()->performFade();
- }
- }
-}
-struct dndenum_mapper
-{
- NSDragOperation mac_code;
- Qt::DropAction qt_code;
- bool Qt2Mac;
-};
-
-#if defined(QT_MAC_USE_COCOA) && defined(__OBJC__)
-
-static dndenum_mapper dnd_enums[] = {
- { NSDragOperationLink, Qt::LinkAction, true },
- { NSDragOperationMove, Qt::MoveAction, true },
- { NSDragOperationCopy, Qt::CopyAction, true },
- { NSDragOperationGeneric, Qt::CopyAction, false },
- { NSDragOperationEvery, Qt::ActionMask, false },
- { NSDragOperationNone, Qt::IgnoreAction, false }
-};
-
-NSDragOperation qt_mac_mapDropAction(Qt::DropAction action)
-{
- for (int i=0; dnd_enums[i].qt_code; i++) {
- if (dnd_enums[i].Qt2Mac && (action & dnd_enums[i].qt_code)) {
- return dnd_enums[i].mac_code;
- }
- }
- return NSDragOperationNone;
-}
-
-NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions)
-{
- NSDragOperation nsActions = NSDragOperationNone;
- for (int i=0; dnd_enums[i].qt_code; i++) {
- if (dnd_enums[i].Qt2Mac && (actions & dnd_enums[i].qt_code))
- nsActions |= dnd_enums[i].mac_code;
- }
- return nsActions;
-}
-
-Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions)
-{
- Qt::DropAction action = Qt::IgnoreAction;
- for (int i=0; dnd_enums[i].mac_code; i++) {
- if (nsActions & dnd_enums[i].mac_code)
- return dnd_enums[i].qt_code;
- }
- return action;
-}
-
-Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions)
-{
- Qt::DropActions actions = Qt::IgnoreAction;
- for (int i=0; dnd_enums[i].mac_code; i++) {
- if (nsActions & dnd_enums[i].mac_code)
- actions |= dnd_enums[i].qt_code;
- }
- return actions;
-}
-
-Q_GLOBAL_STATIC(DnDParams, currentDnDParameters);
-DnDParams *macCurrentDnDParameters()
-{
- return currentDnDParameters();
-}
-#endif
-
-bool macWindowIsTextured( void * /*OSWindowRef*/ window )
-{
- OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#if QT_MAC_USE_COCOA
- return ( [wnd styleMask] & NSTexturedBackgroundWindowMask ) ? true : false;
-#else
- WindowAttributes currentAttributes;
- GetWindowAttributes(wnd, &currentAttributes);
- return (currentAttributes & kWindowMetalAttribute) ? true : false;
-#endif
-}
-
-void macWindowToolbarShow(const QWidget *widget, bool show )
-{
- OSWindowRef wnd = qt_mac_window_for(widget);
-#if QT_MAC_USE_COCOA
- if (NSToolbar *toolbar = [wnd toolbar]) {
- QMacCocoaAutoReleasePool pool;
- if (show != [toolbar isVisible]) {
- [toolbar setVisible:show];
- } else {
- // The toolbar may be in sync, but we are not, update our framestrut.
- qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
- }
- }
-#else
- qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
- ShowHideWindowToolbar(wnd, show, false);
-#endif
-}
-
-
-void macWindowToolbarSet( void * /*OSWindowRef*/ window, void *toolbarRef )
-{
- OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#if QT_MAC_USE_COCOA
- [wnd setToolbar:static_cast<NSToolbar *>(toolbarRef)];
-#else
- SetWindowToolbar(wnd, static_cast<HIToolbarRef>(toolbarRef));
-#endif
-}
-
-bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window )
-{
- OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#if QT_MAC_USE_COCOA
- if (NSToolbar *toolbar = [wnd toolbar])
- return [toolbar isVisible];
- return false;
-#else
- return IsWindowToolbarVisible(wnd);
-#endif
-}
-
-void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow )
-{
- OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#if QT_MAC_USE_COCOA
- [wnd setHasShadow:BOOL(hasShadow)];
-#else
- if (hasShadow)
- ChangeWindowAttributes(wnd, 0, kWindowNoShadowAttribute);
- else
- ChangeWindowAttributes(wnd, kWindowNoShadowAttribute, 0);
-#endif
-}
-
-void macWindowFlush(void * /*OSWindowRef*/ window)
-{
- OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#if QT_MAC_USE_COCOA
- [wnd flushWindowIfNeeded];
-#else
- HIWindowFlush(wnd);
-#endif
-}
-
-void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm)
-{
- QMacCocoaAutoReleasePool pool;
- if(QCFType<CGImageRef> image = pm.toMacCGImageRef()) {
- NSImage *newImage = 0;
- NSRect imageRect = NSMakeRect(0.0, 0.0, CGImageGetWidth(image), CGImageGetHeight(image));
- newImage = [[NSImage alloc] initWithSize:imageRect.size];
- [newImage lockFocus];
- {
- CGContextRef imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
- CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
- }
- [newImage unlockFocus];
- return newImage;
- }
- return 0;
-}
-
-void qt_mac_update_mouseTracking(QWidget *widget)
-{
-#ifdef QT_MAC_USE_COCOA
- [qt_mac_nativeview_for(widget) updateTrackingAreas];
-#else
- Q_UNUSED(widget);
-#endif
-}
-
-OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
-{
- // Verbatim copy if HIViewDrawCGImage (as shown on Carbon-Dev)
- OSStatus err = noErr;
-
- require_action(inContext != NULL, InvalidContext, err = paramErr);
- require_action(inBounds != NULL, InvalidBounds, err = paramErr);
- require_action(inImage != NULL, InvalidImage, err = paramErr);
-
- CGContextSaveGState( inContext );
- CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
- CGContextScaleCTM(inContext, 1, -1);
-
- CGContextDrawImage(inContext, *inBounds, inImage);
-
- CGContextRestoreGState(inContext);
-InvalidImage:
-InvalidBounds:
-InvalidContext:
- return err;
-}
-
-bool qt_mac_checkForNativeSizeGrip(const QWidget *widget)
-{
-#ifndef QT_MAC_USE_COCOA
- OSViewRef nativeSizeGrip = 0;
- HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(widget->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
- return (nativeSizeGrip != 0);
-#else
- return [[reinterpret_cast<NSView *>(widget->effectiveWinId()) window] showsResizeIndicator];
-#endif
-}
-struct qt_mac_enum_mapper
-{
- int mac_code;
- int qt_code;
-#if defined(DEBUG_MOUSE_MAPS)
-# define QT_MAC_MAP_ENUM(x) x, #x
- const char *desc;
-#else
-# define QT_MAC_MAP_ENUM(x) x
-#endif
-};
-
-//mouse buttons
-static qt_mac_enum_mapper qt_mac_mouse_symbols[] = {
-{ kEventMouseButtonPrimary, QT_MAC_MAP_ENUM(Qt::LeftButton) },
-{ kEventMouseButtonSecondary, QT_MAC_MAP_ENUM(Qt::RightButton) },
-{ kEventMouseButtonTertiary, QT_MAC_MAP_ENUM(Qt::MidButton) },
-{ 4, QT_MAC_MAP_ENUM(Qt::XButton1) },
-{ 5, QT_MAC_MAP_ENUM(Qt::XButton2) },
-{ 0, QT_MAC_MAP_ENUM(0) }
-};
-Qt::MouseButtons qt_mac_get_buttons(int buttons)
-{
-#ifdef DEBUG_MOUSE_MAPS
- qDebug("Qt: internal: **Mapping buttons: %d (0x%04x)", buttons, buttons);
-#endif
- Qt::MouseButtons ret = Qt::NoButton;
- for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
- if (buttons & (0x01<<(qt_mac_mouse_symbols[i].mac_code-1))) {
-#ifdef DEBUG_MOUSE_MAPS
- qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
-#endif
- ret |= Qt::MouseButtons(qt_mac_mouse_symbols[i].qt_code);
- }
- }
- return ret;
-}
-Qt::MouseButton qt_mac_get_button(EventMouseButton button)
-{
-#ifdef DEBUG_MOUSE_MAPS
- qDebug("Qt: internal: **Mapping button: %d (0x%04x)", button, button);
-#endif
- Qt::MouseButtons ret = 0;
- for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
- if (button == qt_mac_mouse_symbols[i].mac_code) {
-#ifdef DEBUG_MOUSE_MAPS
- qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
-#endif
- return Qt::MouseButton(qt_mac_mouse_symbols[i].qt_code);
- }
- }
- return Qt::NoButton;
-}
-
-void macSendToolbarChangeEvent(QWidget *widget)
-{
- QToolBarChangeEvent ev(!(GetCurrentKeyModifiers() & cmdKey));
- qt_sendSpontaneousEvent(widget, &ev);
-}
-
-Q_GLOBAL_STATIC(QMacTabletHash, tablet_hash)
-QMacTabletHash *qt_mac_tablet_hash()
-{
- return tablet_hash();
-}
-
-#ifdef QT_MAC_USE_COCOA
-
-// Clears the QWidget pointer that each QCocoaView holds.
-void qt_mac_clearCocoaViewQWidgetPointers(QWidget *widget)
-{
- QT_MANGLE_NAMESPACE(QCocoaView) *cocoaView = reinterpret_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_nativeview_for(widget));
- if (cocoaView && [cocoaView respondsToSelector:@selector(qt_qwidget)]) {
- [cocoaView qt_clearQWidget];
- }
-}
-
-void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent)
-{
- NSEvent *proximityEvent = static_cast<NSEvent *>(tabletEvent);
- // simply construct a Carbon proximity record and handle it all in one spot.
- TabletProximityRec carbonProximityRec = { [proximityEvent vendorID],
- [proximityEvent tabletID],
- [proximityEvent pointingDeviceID],
- [proximityEvent deviceID],
- [proximityEvent systemTabletID],
- [proximityEvent vendorPointingDeviceType],
- [proximityEvent pointingDeviceSerialNumber],
- [proximityEvent uniqueID],
- [proximityEvent capabilityMask],
- [proximityEvent pointingDeviceType],
- [proximityEvent isEnteringProximity] };
- qt_dispatchTabletProximityEvent(carbonProximityRec);
-}
-#endif // QT_MAC_USE_COCOA
-
-void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec)
-{
- QTabletDeviceData proximityDevice;
- proximityDevice.tabletUniqueID = proxRec.uniqueID;
- proximityDevice.capabilityMask = proxRec.capabilityMask;
-
- switch (proxRec.pointerType) {
- case NSUnknownPointingDevice:
- default:
- proximityDevice.tabletPointerType = QTabletEvent::UnknownPointer;
- break;
- case NSPenPointingDevice:
- proximityDevice.tabletPointerType = QTabletEvent::Pen;
- break;
- case NSCursorPointingDevice:
- proximityDevice.tabletPointerType = QTabletEvent::Cursor;
- break;
- case NSEraserPointingDevice:
- proximityDevice.tabletPointerType = QTabletEvent::Eraser;
- break;
- }
- uint bits = proxRec.vendorPointerType;
- if (bits == 0 && proximityDevice.tabletUniqueID != 0) {
- // Fallback. It seems that the driver doesn't always include all the information.
- // High-End Wacom devices store their "type" in the uper bits of the Unique ID.
- // I'm not sure how to handle it for consumer devices, but I'll test that in a bit.
- bits = proximityDevice.tabletUniqueID >> 32;
- }
- // Defined in the "EN0056-NxtGenImpGuideX"
- // on Wacom's Developer Website (www.wacomeng.com)
- if (((bits & 0x0006) == 0x0002) && ((bits & 0x0F06) != 0x0902)) {
- proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
- } else {
- switch (bits & 0x0F06) {
- case 0x0802:
- proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
- break;
- case 0x0902:
- proximityDevice.tabletDeviceType = QTabletEvent::Airbrush;
- break;
- case 0x0004:
- proximityDevice.tabletDeviceType = QTabletEvent::FourDMouse;
- break;
- case 0x0006:
- proximityDevice.tabletDeviceType = QTabletEvent::Puck;
- break;
- case 0x0804:
- proximityDevice.tabletDeviceType = QTabletEvent::RotationStylus;
- break;
- default:
- proximityDevice.tabletDeviceType = QTabletEvent::NoDevice;
- }
- }
- // The deviceID is "unique" while in the proximity, it's a key that we can use for
- // linking up TabletDeviceData to an event (especially if there are two devices in action).
- bool entering = proxRec.enterProximity;
- if (entering) {
- qt_mac_tablet_hash()->insert(proxRec.deviceID, proximityDevice);
- } else {
- qt_mac_tablet_hash()->remove(proxRec.deviceID);
- }
-
- QTabletEvent qtabletProximity(entering ? QEvent::TabletEnterProximity
- : QEvent::TabletLeaveProximity,
- QPoint(), QPoint(), QPointF(), proximityDevice.tabletDeviceType,
- proximityDevice.tabletPointerType, 0., 0, 0, 0., 0., 0, 0,
- proximityDevice.tabletUniqueID);
-
- qt_sendSpontaneousEvent(qApp, &qtabletProximity);
-}
-
-// Use this method to keep all the information in the TextSegment. As long as it is ordered
-// we are in OK shape, and we can influence that ourselves.
-struct KeyPair
-{
- QChar cocoaKey;
- Qt::Key qtKey;
-};
-
-bool operator==(const KeyPair &entry, QChar qchar)
-{
- return entry.cocoaKey == qchar;
-}
-
-bool operator<(const KeyPair &entry, QChar qchar)
-{
- return entry.cocoaKey < qchar;
-}
-
-bool operator<(QChar qchar, const KeyPair &entry)
-{
- return qchar < entry.cocoaKey;
-}
-
-bool operator<(const Qt::Key &key, const KeyPair &entry)
-{
- return key < entry.qtKey;
-}
-
-bool operator<(const KeyPair &entry, const Qt::Key &key)
-{
- return entry.qtKey < key;
-}
-
-static bool qtKey2CocoaKeySortLessThan(const KeyPair &entry1, const KeyPair &entry2)
-{
- return entry1.qtKey < entry2.qtKey;
-}
-
-static const int NumEntries = 59;
-static const KeyPair entries[NumEntries] = {
- { NSEnterCharacter, Qt::Key_Enter },
- { NSBackspaceCharacter, Qt::Key_Backspace },
- { NSTabCharacter, Qt::Key_Tab },
- { NSNewlineCharacter, Qt::Key_Return },
- { NSCarriageReturnCharacter, Qt::Key_Return },
- { NSBackTabCharacter, Qt::Key_Backtab },
- { kEscapeCharCode, Qt::Key_Escape },
- // Cocoa sends us delete when pressing backspace!
- // (NB when we reverse this list in qtKey2CocoaKey, there
- // will be two indices of Qt::Key_Backspace. But is seems to work
- // ok for menu shortcuts (which uses that function):
- { NSDeleteCharacter, Qt::Key_Backspace },
- { NSUpArrowFunctionKey, Qt::Key_Up },
- { NSDownArrowFunctionKey, Qt::Key_Down },
- { NSLeftArrowFunctionKey, Qt::Key_Left },
- { NSRightArrowFunctionKey, Qt::Key_Right },
- { NSF1FunctionKey, Qt::Key_F1 },
- { NSF2FunctionKey, Qt::Key_F2 },
- { NSF3FunctionKey, Qt::Key_F3 },
- { NSF4FunctionKey, Qt::Key_F4 },
- { NSF5FunctionKey, Qt::Key_F5 },
- { NSF6FunctionKey, Qt::Key_F6 },
- { NSF7FunctionKey, Qt::Key_F7 },
- { NSF8FunctionKey, Qt::Key_F8 },
- { NSF9FunctionKey, Qt::Key_F8 },
- { NSF10FunctionKey, Qt::Key_F10 },
- { NSF11FunctionKey, Qt::Key_F11 },
- { NSF12FunctionKey, Qt::Key_F12 },
- { NSF13FunctionKey, Qt::Key_F13 },
- { NSF14FunctionKey, Qt::Key_F14 },
- { NSF15FunctionKey, Qt::Key_F15 },
- { NSF16FunctionKey, Qt::Key_F16 },
- { NSF17FunctionKey, Qt::Key_F17 },
- { NSF18FunctionKey, Qt::Key_F18 },
- { NSF19FunctionKey, Qt::Key_F19 },
- { NSF20FunctionKey, Qt::Key_F20 },
- { NSF21FunctionKey, Qt::Key_F21 },
- { NSF22FunctionKey, Qt::Key_F22 },
- { NSF23FunctionKey, Qt::Key_F23 },
- { NSF24FunctionKey, Qt::Key_F24 },
- { NSF25FunctionKey, Qt::Key_F25 },
- { NSF26FunctionKey, Qt::Key_F26 },
- { NSF27FunctionKey, Qt::Key_F27 },
- { NSF28FunctionKey, Qt::Key_F28 },
- { NSF29FunctionKey, Qt::Key_F29 },
- { NSF30FunctionKey, Qt::Key_F30 },
- { NSF31FunctionKey, Qt::Key_F31 },
- { NSF32FunctionKey, Qt::Key_F32 },
- { NSF33FunctionKey, Qt::Key_F33 },
- { NSF34FunctionKey, Qt::Key_F34 },
- { NSF35FunctionKey, Qt::Key_F35 },
- { NSInsertFunctionKey, Qt::Key_Insert },
- { NSDeleteFunctionKey, Qt::Key_Delete },
- { NSHomeFunctionKey, Qt::Key_Home },
- { NSEndFunctionKey, Qt::Key_End },
- { NSPageUpFunctionKey, Qt::Key_PageUp },
- { NSPageDownFunctionKey, Qt::Key_PageDown },
- { NSPrintScreenFunctionKey, Qt::Key_Print },
- { NSScrollLockFunctionKey, Qt::Key_ScrollLock },
- { NSPauseFunctionKey, Qt::Key_Pause },
- { NSSysReqFunctionKey, Qt::Key_SysReq },
- { NSMenuFunctionKey, Qt::Key_Menu },
- { NSHelpFunctionKey, Qt::Key_Help },
-};
-static const KeyPair * const end = entries + NumEntries;
-
-QChar qtKey2CocoaKey(Qt::Key key)
-{
- // The first time this function is called, create a reverse
- // looup table sorted on Qt Key rather than Cocoa key:
- static QVector<KeyPair> rev_entries(NumEntries);
- static bool mustInit = true;
- if (mustInit){
- mustInit = false;
- for (int i=0; i<NumEntries; ++i)
- rev_entries[i] = entries[i];
- qSort(rev_entries.begin(), rev_entries.end(), qtKey2CocoaKeySortLessThan);
- }
- const QVector<KeyPair>::iterator i
- = qBinaryFind(rev_entries.begin(), rev_entries.end(), key);
- if (i == rev_entries.end())
- return QChar();
- return i->cocoaKey;
-}
-
-#ifdef QT_MAC_USE_COCOA
-static Qt::Key cocoaKey2QtKey(QChar keyCode)
-{
- const KeyPair *i = qBinaryFind(entries, end, keyCode);
- if (i == end)
- return Qt::Key(keyCode.unicode());
- return i->qtKey;
-}
-
-Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags)
-{
- Qt::KeyboardModifiers qtMods =Qt::NoModifier;
- if (modifierFlags & NSShiftKeyMask)
- qtMods |= Qt::ShiftModifier;
- if (modifierFlags & NSControlKeyMask)
- qtMods |= Qt::MetaModifier;
- if (modifierFlags & NSAlternateKeyMask)
- qtMods |= Qt::AltModifier;
- if (modifierFlags & NSCommandKeyMask)
- qtMods |= Qt::ControlModifier;
- if (modifierFlags & NSNumericPadKeyMask)
- qtMods |= Qt::KeypadModifier;
- return qtMods;
-}
-
-NSString *qt_mac_removePrivateUnicode(NSString* string)
-{
- int len = [string length];
- if (len) {
- QVarLengthArray <unichar, 10> characters(len);
- bool changed = false;
- for (int i = 0; i<len; i++) {
- characters[i] = [string characterAtIndex:i];
- // check if they belong to key codes in private unicode range
- // currently we need to handle only the NSDeleteFunctionKey
- if (characters[i] == NSDeleteFunctionKey) {
- characters[i] = NSDeleteCharacter;
- changed = true;
- }
- }
- if (changed)
- return [NSString stringWithCharacters:characters.data() length:len];
- }
- return string;
-}
-
-Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations)
-{
- Qt::KeyboardModifiers qtMods =Qt::NoModifier;
- if (dragOperations & NSDragOperationLink)
- qtMods |= Qt::MetaModifier;
- if (dragOperations & NSDragOperationGeneric)
- qtMods |= Qt::ControlModifier;
- if (dragOperations & NSDragOperationCopy)
- qtMods |= Qt::AltModifier;
- return qtMods;
-}
-
-static inline QEvent::Type cocoaEvent2QtEvent(NSUInteger eventType)
-{
- // Handle the trivial cases that can be determined from the type.
- switch (eventType) {
- case NSKeyDown:
- return QEvent::KeyPress;
- case NSKeyUp:
- return QEvent::KeyRelease;
- case NSLeftMouseDown:
- case NSRightMouseDown:
- case NSOtherMouseDown:
- return QEvent::MouseButtonPress;
- case NSLeftMouseUp:
- case NSRightMouseUp:
- case NSOtherMouseUp:
- return QEvent::MouseButtonRelease;
- case NSMouseMoved:
- case NSLeftMouseDragged:
- case NSRightMouseDragged:
- case NSOtherMouseDragged:
- return QEvent::MouseMove;
- case NSScrollWheel:
- return QEvent::Wheel;
- }
- return QEvent::None;
-}
-
-static bool mustUseCocoaKeyEvent()
-{
- QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
- return TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) == 0;
-}
-
-bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
-{
- NSEvent *event = static_cast<NSEvent *>(keyEvent);
- NSString *keyChars = [event charactersIgnoringModifiers];
- int keyLength = [keyChars length];
- if (keyLength == 0)
- return false; // Dead Key, nothing to do!
- bool ignoreText = false;
- Qt::Key qtKey = Qt::Key_unknown;
- if (keyLength == 1) {
- QChar ch([keyChars characterAtIndex:0]);
- if (ch.isLower())
- ch = ch.toUpper();
- qtKey = cocoaKey2QtKey(ch);
- // Do not set the text for Function-Key Unicodes characters (0xF700–0xF8FF).
- ignoreText = (ch.unicode() >= 0xF700 && ch.unicode() <= 0xF8FF);
- }
- Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
- QString text;
-
- // To quote from the Carbon port: This is actually wrong--but it is the best that
- // can be done for now because of the Control/Meta mapping issues
- // (we always get text on the Mac)
- if (!ignoreText && !(keyMods & (Qt::ControlModifier | Qt::MetaModifier)))
- text = QCFString::toQString(reinterpret_cast<CFStringRef>(keyChars));
-
- UInt32 macScanCode = 1;
- QKeyEventEx ke(cocoaEvent2QtEvent([event type]), qtKey, keyMods, text, [event isARepeat], qMax(1, keyLength),
- macScanCode, [event keyCode], [event modifierFlags]);
- return qt_sendSpontaneousEvent(widgetToGetEvent, &ke) && ke.isAccepted();
-}
-#endif
-
-Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
-{
- if (buttonNum == 0)
- return Qt::LeftButton;
- if (buttonNum == 1)
- return Qt::RightButton;
- if (buttonNum == 2)
- return Qt::MidButton;
- if (buttonNum == 3)
- return Qt::XButton1;
- if (buttonNum == 4)
- return Qt::XButton2;
- return Qt::NoButton;
-}
-
-bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
-{
-#ifndef QT_MAC_USE_COCOA
- Q_UNUSED(keyEvent);
- Q_UNUSED(widgetToGetEvent);
- return false;
-#else
- NSEvent *event = static_cast<NSEvent *>(keyEvent);
- EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
- Q_ASSERT(key_event);
- unsigned int info = 0;
-
- if ([event type] == NSKeyDown) {
- NSString *characters = [event characters];
- if ([characters length]) {
- unichar value = [characters characterAtIndex:0];
- qt_keymapper_private()->updateKeyMap(0, key_event, (void *)&value);
- info = value;
- }
- }
-
- if (qt_mac_sendMacEventToWidget(widgetToGetEvent, key_event))
- return true;
-
- if (mustUseCocoaKeyEvent())
- return qt_dispatchKeyEventWithCocoa(keyEvent, widgetToGetEvent);
-
- bool consumed = qt_keymapper_private()->translateKeyEvent(widgetToGetEvent, 0, key_event, &info, true);
- return consumed && (info != 0);
-#endif
-}
-
-void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent)
-{
-#ifndef QT_MAC_USE_COCOA
- Q_UNUSED(flagsChangedEvent);
- Q_UNUSED(widgetToGetEvent);
-#else
- UInt32 modifiers = 0;
- // Sync modifiers with Qt
- NSEvent *event = static_cast<NSEvent *>(flagsChangedEvent);
- EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
- Q_ASSERT(key_event);
- GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
- sizeof(modifiers), 0, &modifiers);
- extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object);
- qt_mac_send_modifiers_changed(modifiers, widgetToGetEvent);
-#endif
-}
-
-QPointF flipPoint(const NSPoint &p)
-{
- return QPointF(p.x, flipYCoordinate(p.y));
-}
-
-NSPoint flipPoint(const QPoint &p)
-{
- return NSMakePoint(p.x(), flipYCoordinate(p.y()));
-}
-
-NSPoint flipPoint(const QPointF &p)
-{
- return NSMakePoint(p.x(), flipYCoordinate(p.y()));
-}
-
-#if QT_MAC_USE_COCOA && __OBJC__
-
-void qt_mac_handleNonClientAreaMouseEvent(NSWindow *window, NSEvent *event)
-{
- QWidget *widgetToGetEvent = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
- if (widgetToGetEvent == 0)
- return;
-
- NSEventType evtType = [event type];
- QPoint qlocalPoint;
- QPoint qglobalPoint;
- bool processThisEvent = false;
- bool fakeNCEvents = false;
- bool fakeMouseEvents = false;
-
- // Check if this is a mouse event.
- if (evtType == NSLeftMouseDown || evtType == NSLeftMouseUp
- || evtType == NSRightMouseDown || evtType == NSRightMouseUp
- || evtType == NSOtherMouseDown || evtType == NSOtherMouseUp
- || evtType == NSMouseMoved || evtType == NSLeftMouseDragged
- || evtType == NSRightMouseDragged || evtType == NSOtherMouseDragged) {
- // Check if we want to pass this message to another window
- if (mac_mouse_grabber && mac_mouse_grabber != widgetToGetEvent) {
- NSWindow *grabWindow = static_cast<NSWindow *>(qt_mac_window_for(mac_mouse_grabber));
- if (window != grabWindow) {
- window = grabWindow;
- widgetToGetEvent = mac_mouse_grabber;
- fakeNCEvents = true;
- }
- }
- // Dont generate normal NC mouse events for Left Button dragged
- if(evtType != NSLeftMouseDragged || fakeNCEvents) {
- NSPoint windowPoint = [event locationInWindow];
- NSPoint globalPoint = [[event window] convertBaseToScreen:windowPoint];
- NSRect frameRect = [window frame];
- if (fakeNCEvents || NSMouseInRect(globalPoint, frameRect, NO)) {
- NSRect contentRect = [window contentRectForFrameRect:frameRect];
- qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
- QWidget *w = widgetToGetEvent->childAt(widgetToGetEvent->mapFromGlobal(qglobalPoint));
- // check that the mouse pointer is on the non-client area and
- // there are not widgets in it.
- if (fakeNCEvents || (!NSMouseInRect(globalPoint, contentRect, NO) && !w)) {
- qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
- qlocalPoint = widgetToGetEvent->mapFromGlobal(qglobalPoint);
- processThisEvent = true;
- }
- }
- }
- }
- // This is not an NC area mouse message.
- if (!processThisEvent)
- return;
-
- // If the window is frame less, generate fake mouse events instead. (floating QToolBar)
- // or if someone already got an explicit or implicit grab
- if (mac_mouse_grabber || qt_button_down ||
- (fakeNCEvents && (widgetToGetEvent->window()->windowFlags() & Qt::FramelessWindowHint)))
- fakeMouseEvents = true;
-
- Qt::MouseButton button;
- QEvent::Type eventType;
- // Convert to Qt::Event type
- switch (evtType) {
- case NSLeftMouseDown:
- button = Qt::LeftButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
- : QEvent::MouseButtonPress;
- break;
- case NSLeftMouseUp:
- button = Qt::LeftButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
- : QEvent::MouseButtonRelease;
- break;
- case NSRightMouseDown:
- button = Qt::RightButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
- : QEvent::MouseButtonPress;
- break;
- case NSRightMouseUp:
- button = Qt::RightButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
- : QEvent::MouseButtonRelease;
- break;
- case NSOtherMouseDown:
- button = cocoaButton2QtButton([event buttonNumber]);
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
- : QEvent::MouseButtonPress;
- break;
- case NSOtherMouseUp:
- button = cocoaButton2QtButton([event buttonNumber]);
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
- : QEvent::MouseButtonRelease;
- break;
- case NSMouseMoved:
- button = Qt::NoButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
- : QEvent::MouseMove;
- break;
- case NSLeftMouseDragged:
- button = Qt::LeftButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
- : QEvent::MouseMove;
- break;
- case NSRightMouseDragged:
- button = Qt::RightButton;
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
- : QEvent::MouseMove;
- break;
- case NSOtherMouseDragged:
- button = cocoaButton2QtButton([event buttonNumber]);
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
- : QEvent::MouseMove;
- break;
- default:
- qWarning("not handled! Non client area mouse message");
- return;
- }
-
- Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
- if (eventType == QEvent::NonClientAreaMouseButtonPress || eventType == QEvent::MouseButtonPress) {
- NSInteger clickCount = [event clickCount];
- if (clickCount % 2 == 0)
- eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonDblClick
- : QEvent::MouseButtonDblClick;
- if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
- button = Qt::RightButton;
- qt_leftButtonIsRightButton = true;
- }
- } else if (eventType == QEvent::NonClientAreaMouseButtonRelease || eventType == QEvent::MouseButtonRelease) {
- if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
- button = Qt::RightButton;
- qt_leftButtonIsRightButton = false;
- }
- }
-
- Qt::MouseButtons buttons = 0;
- {
- UInt32 mac_buttons;
- if (GetEventParameter((EventRef)[event eventRef], kEventParamMouseChord, typeUInt32, 0,
- sizeof(mac_buttons), 0, &mac_buttons) == noErr)
- buttons = qt_mac_get_buttons(mac_buttons);
- }
-
- QMouseEvent qme(eventType, qlocalPoint, qglobalPoint, button, buttons, keyMods);
- qt_sendSpontaneousEvent(widgetToGetEvent, &qme);
-
- // We don't need to set the implicit grab widget here because we won't
- // reach this point if then event type is Press over a Qt widget.
- // However we might need to unset it if the event is Release.
- if (eventType == QEvent::MouseButtonRelease)
- qt_button_down = 0;
-}
-
-QWidget *qt_mac_getTargetForKeyEvent(QWidget *widgetThatReceivedEvent)
-{
- if (QWidget *popup = QApplication::activePopupWidget()) {
- QWidget *focusInPopup = popup->focusWidget();
- return focusInPopup ? focusInPopup : popup;
- }
-
- QWidget *widgetToGetKey = qApp->focusWidget();
- if (!widgetToGetKey)
- widgetToGetKey = widgetThatReceivedEvent;
-
- return widgetToGetKey;
-}
-
-// This function will find the widget that should receive the
-// mouse event. Because of explicit/implicit mouse grabs, popups,
-// etc, this might not end up being the same as the widget under
-// the mouse (which is more interresting when handling enter/leave
-// events
-QWidget *qt_mac_getTargetForMouseEvent(
- // You can call this function without providing an event.
- NSEvent *event,
- QEvent::Type eventType,
- QPoint &returnLocalPoint,
- QPoint &returnGlobalPoint,
- QWidget *nativeWidget,
- QWidget **returnWidgetUnderMouse)
-{
- Q_UNUSED(event);
- NSPoint nsglobalpoint = event ? [[event window] convertBaseToScreen:[event locationInWindow]] : [NSEvent mouseLocation];
- returnGlobalPoint = flipPoint(nsglobalpoint).toPoint();
- QWidget *mouseGrabber = QWidget::mouseGrabber();
- bool buttonDownNotBlockedByModal = qt_button_down && !QApplicationPrivate::isBlockedByModal(qt_button_down);
- QWidget *popup = QApplication::activePopupWidget();
-
- // Resolve the widget under the mouse:
- QWidget *widgetUnderMouse = 0;
- if (popup || qt_button_down || !nativeWidget || !nativeWidget->isVisible()) {
- // Using QApplication::widgetAt for finding the widget under the mouse
- // is most safe, since it ignores cocoas own mouse down redirections (which
- // we need to be prepared for when using nativeWidget as starting point).
- // (the only exception is for QMacNativeWidget, where QApplication::widgetAt fails).
- // But it is also slower (I guess), so we try to avoid it and use nativeWidget if we can:
- widgetUnderMouse = QApplication::widgetAt(returnGlobalPoint);
- }
-
- if (!widgetUnderMouse && nativeWidget) {
- // Entering here should be the common case. We
- // also handle the QMacNativeWidget fallback case.
- QPoint p = nativeWidget->mapFromGlobal(returnGlobalPoint);
- widgetUnderMouse = nativeWidget->childAt(p);
- if (!widgetUnderMouse && nativeWidget->rect().contains(p))
- widgetUnderMouse = nativeWidget;
- }
-
- if (widgetUnderMouse) {
- // Check if widgetUnderMouse is blocked by a modal
- // window, or the mouse if over the frame strut:
- if (widgetUnderMouse == qt_button_down) {
- // Small optimization to avoid an extra call to isBlockedByModal:
- if (buttonDownNotBlockedByModal == false)
- widgetUnderMouse = 0;
- } else if (QApplicationPrivate::isBlockedByModal(widgetUnderMouse)) {
- widgetUnderMouse = 0;
- }
-
- if (widgetUnderMouse && widgetUnderMouse->isWindow()) {
- // Exclude the titlebar (and frame strut) when finding widget under mouse:
- QPoint p = widgetUnderMouse->mapFromGlobal(returnGlobalPoint);
- if (!widgetUnderMouse->rect().contains(p))
- widgetUnderMouse = 0;
- }
- }
- if (returnWidgetUnderMouse)
- *returnWidgetUnderMouse = widgetUnderMouse;
-
- // Resolve the target for the mouse event. Default will be
- // widgetUnderMouse, except if there is a grab (popup/mouse/button-down):
- if (popup && !mouseGrabber) {
- // We special case handling of popups, since they have an implicitt mouse grab.
- QWidget *candidate = buttonDownNotBlockedByModal ? qt_button_down : widgetUnderMouse;
- if (!popup->isAncestorOf(candidate)) {
- // INVARIANT: we have a popup, but the candidate is not
- // in it. But the popup will grab the mouse anyway,
- // except if the user scrolls:
- if (eventType == QEvent::Wheel)
- return 0;
- returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
- return popup;
- } else if (popup == candidate) {
- // INVARIANT: The candidate is the popup itself, and not a child:
- returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
- return popup;
- } else {
- // INVARIANT: The candidate is a child inside the popup:
- returnLocalPoint = candidate->mapFromGlobal(returnGlobalPoint);
- return candidate;
- }
- }
-
- QWidget *target = mouseGrabber;
- if (!target && buttonDownNotBlockedByModal)
- target = qt_button_down;
- if (!target)
- target = widgetUnderMouse;
- if (!target)
- return 0;
-
- returnLocalPoint = target->mapFromGlobal(returnGlobalPoint);
- return target;
-}
-
-QPointer<QWidget> qt_last_native_mouse_receiver = 0;
-
-static inline void qt_mac_checkEnterLeaveForNativeWidgets(QWidget *maybeEnterWidget)
-{
- // Dispatch enter/leave for the cases where QApplicationPrivate::sendMouseEvent do
- // not. This will in general be the cases when alien widgets are not involved:
- // 1. from a native widget to another native widget or
- // 2. from a native widget to no widget
- // 3. from no widget to a native or alien widget
-
- if (qt_button_down || QWidget::mouseGrabber())
- return;
-
- if ((maybeEnterWidget == qt_last_native_mouse_receiver) && qt_last_native_mouse_receiver)
- return;
- if (maybeEnterWidget) {
- if (!qt_last_native_mouse_receiver) {
- // case 3
- QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, 0);
- qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
- } else if (maybeEnterWidget->internalWinId()) {
- // case 1
- QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, qt_last_native_mouse_receiver);
- qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
- } // else at lest one of the widgets are alien, so enter/leave will be handled in QApplicationPrivate
- } else {
- if (qt_last_native_mouse_receiver) {
- // case 2
- QApplicationPrivate::dispatchEnterLeave(0, qt_last_native_mouse_receiver);
- qt_last_mouse_receiver = 0;
- qt_last_native_mouse_receiver = 0;
- }
- }
-}
-
-bool qt_mac_handleMouseEvent(NSEvent *event, QEvent::Type eventType, Qt::MouseButton button, QWidget *nativeWidget)
-{
- // Give the Input Manager a chance to process the mouse events.
- NSInputManager *currentIManager = [NSInputManager currentInputManager];
- if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
- [currentIManager handleMouseEvent:event];
- }
-
- // Find the widget that should receive the event, and the widget under the mouse. Those
- // can differ if an implicit or explicit mouse grab is active:
- QWidget *widgetUnderMouse = 0;
- QPoint localPoint, globalPoint;
- QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(event, eventType, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
- if (!widgetToGetMouse)
- return false;
-
- // From here on, we let nativeWidget actually be the native widget under widgetUnderMouse. The reason
- // for this, is that qt_mac_getTargetForMouseEvent will set cocoa's mouse event redirection aside when
- // determining which widget is under the mouse (in other words, it will usually ignore nativeWidget).
- // nativeWidget will be used in QApplicationPrivate::sendMouseEvent to correctly dispatch enter/leave events.
- if (widgetUnderMouse)
- nativeWidget = widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget();
- if (!nativeWidget)
- return false;
- NSView *view = qt_mac_effectiveview_for(nativeWidget);
-
- // Handle tablet events (if any) first.
- if (qt_mac_handleTabletEvent(view, event)) {
- // Tablet event was handled. In Qt we aren't supposed to send the mouse event.
- return true;
- }
-
- EventRef carbonEvent = static_cast<EventRef>(const_cast<void *>([event eventRef]));
- if (qt_mac_sendMacEventToWidget(widgetToGetMouse, carbonEvent))
- return true;
-
- // Keep previousButton to make sure we don't send double click
- // events when the user double clicks using two different buttons:
- static Qt::MouseButton previousButton = Qt::NoButton;
-
- Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
- NSInteger clickCount = [event clickCount];
- Qt::MouseButtons buttons = 0;
- {
- UInt32 mac_buttons;
- if (GetEventParameter(carbonEvent, kEventParamMouseChord, typeUInt32, 0,
- sizeof(mac_buttons), 0, &mac_buttons) == noErr)
- buttons = qt_mac_get_buttons(mac_buttons);
- }
-
- // Send enter/leave events for the cases when QApplicationPrivate::sendMouseEvent do not:
- qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
-
- switch (eventType) {
- default:
- qWarning("not handled! %d", eventType);
- break;
- case QEvent::MouseMove:
- if (button == Qt::LeftButton && qt_leftButtonIsRightButton)
- button = Qt::RightButton;
- break;
- case QEvent::MouseButtonPress:
- qt_button_down = widgetUnderMouse;
- if (clickCount % 2 == 0 && (previousButton == Qt::NoButton || previousButton == button))
- eventType = QEvent::MouseButtonDblClick;
- if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
- button = Qt::RightButton;
- qt_leftButtonIsRightButton = true;
- }
- break;
- case QEvent::MouseButtonRelease:
- if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
- button = Qt::RightButton;
- qt_leftButtonIsRightButton = false;
- }
- qt_button_down = 0;
- break;
- }
-
- qt_mac_updateCursorWithWidgetUnderMouse(widgetUnderMouse);
-
- DnDParams *dndParams = currentDnDParameters();
- dndParams->view = view;
- dndParams->theEvent = event;
- dndParams->globalPoint = globalPoint;
-
- // Send the mouse event:
- QMouseEvent qme(eventType, localPoint, globalPoint, button, buttons, keyMods);
- QApplicationPrivate::sendMouseEvent(
- widgetToGetMouse, &qme, widgetUnderMouse, nativeWidget,
- &qt_button_down, qt_last_mouse_receiver, true);
-
- if (eventType == QEvent::MouseButtonPress && button == Qt::RightButton) {
- QContextMenuEvent qcme(QContextMenuEvent::Mouse, localPoint, globalPoint, keyMods);
- qt_sendSpontaneousEvent(widgetToGetMouse, &qcme);
- }
-
- if (eventType == QEvent::MouseButtonRelease) {
- // A mouse button was released, which means that the implicit grab was
- // released. We therefore need to re-check if should send (delayed) enter leave events:
- // qt_button_down has now become NULL since the call at the top of the function. Also, since
- // the relase might have closed a window, we dont give the nativeWidget hint
- qt_mac_getTargetForMouseEvent(0, QEvent::None, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
- qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
- }
-
- previousButton = button;
- return true;
-}
-#endif
-
-bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */tabletEvent)
-{
-#ifndef QT_MAC_USE_COCOA
- Q_UNUSED(view);
- Q_UNUSED(tabletEvent);
- return false;
-#else
- QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
- NSView *theNSView = static_cast<NSView *>(view);
- NSEvent *theTabletEvent = static_cast<NSEvent *>(tabletEvent);
-
- NSEventType eventType = [theTabletEvent type];
- if (eventType != NSTabletPoint && [theTabletEvent subtype] != NSTabletPointEventSubtype)
- return false; // Not a tablet event.
-
- NSPoint windowPoint = [theTabletEvent locationInWindow];
- NSPoint globalPoint = [[theTabletEvent window] convertBaseToScreen:windowPoint];
-
- QWidget *qwidget = [theView qt_qwidget];
- QWidget *widgetToGetMouse = qwidget;
- QWidget *popup = qAppInstance()->activePopupWidget();
- if (popup && popup != qwidget->window())
- widgetToGetMouse = popup;
-
- if (qt_mac_sendMacEventToWidget(widgetToGetMouse,
- static_cast<EventRef>(const_cast<void *>([theTabletEvent eventRef]))))
- return true;
- if (widgetToGetMouse != qwidget) {
- theNSView = qt_mac_nativeview_for(widgetToGetMouse);
- windowPoint = [[theNSView window] convertScreenToBase:globalPoint];
- }
- NSPoint localPoint = [theNSView convertPoint:windowPoint fromView:nil];
- // Tablet events do not handle WA_TransparentForMouseEvents ATM
- // In theory, people who set the WA_TransparentForMouseEvents attribute won't handle
- // tablet events either in which case they will fall into the mouse event case and get
- // them passed on. This will NOT handle the raw events, but that might not be a big problem.
-
- const QMacTabletHash *tabletHash = qt_mac_tablet_hash();
- if (!tabletHash->contains([theTabletEvent deviceID])) {
- qWarning("QCocoaView handleTabletEvent: This tablet device is unknown"
- " (received no proximity event for it). Discarding event.");
- return false;
- }
- const QTabletDeviceData &deviceData = tabletHash->value([theTabletEvent deviceID]);
-
-
- QEvent::Type qType;
- switch (eventType) {
- case NSLeftMouseDown:
- case NSRightMouseDown:
- qType = QEvent::TabletPress;
- break;
- case NSLeftMouseUp:
- case NSRightMouseUp:
- qType = QEvent::TabletRelease;
- break;
- case NSMouseMoved:
- case NSTabletPoint:
- case NSLeftMouseDragged:
- case NSRightMouseDragged:
- default:
- qType = QEvent::TabletMove;
- break;
- }
-
- qreal pressure;
- if (eventType != NSMouseMoved) {
- pressure = [theTabletEvent pressure];
- } else {
- pressure = 0.0;
- }
-
- NSPoint tilt = [theTabletEvent tilt];
- int xTilt = qRound(tilt.x * 60.0);
- int yTilt = qRound(tilt.y * -60.0);
- qreal tangentialPressure = 0;
- qreal rotation = 0;
- int z = 0;
- if (deviceData.capabilityMask & 0x0200)
- z = [theTabletEvent absoluteZ];
-
- if (deviceData.capabilityMask & 0x0800)
- tangentialPressure = [theTabletEvent tangentialPressure];
-
- rotation = [theTabletEvent rotation];
- QPointF hiRes = flipPoint(globalPoint);
- QTabletEvent qtabletEvent(qType, QPoint(localPoint.x, localPoint.y),
- hiRes.toPoint(), hiRes,
- deviceData.tabletDeviceType, deviceData.tabletPointerType,
- pressure, xTilt, yTilt, tangentialPressure, rotation, z,
- qt_cocoaModifiers2QtModifiers([theTabletEvent modifierFlags]),
- deviceData.tabletUniqueID);
-
- qt_sendSpontaneousEvent(widgetToGetMouse, &qtabletEvent);
- return qtabletEvent.isAccepted();
-#endif
-}
-
-void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics)
-{
- OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-#if !defined(QT_MAC_USE_COCOA)
-# if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- ::HIWindowSetContentBorderThickness(theWindow, &metrics);
- }
-# else
- Q_UNUSED(window);
- Q_UNUSED(metrics);
-# endif
-#else
- if ([theWindow styleMask] & NSTexturedBackgroundWindowMask)
- [theWindow setContentBorderThickness:metrics.top forEdge:NSMaxYEdge];
- [theWindow setContentBorderThickness:metrics.bottom forEdge:NSMinYEdge];
-#endif
-}
-
-#if QT_MAC_USE_COCOA
-void qt_mac_replaceDrawRect(void * /*OSWindowRef */window, QWidgetPrivate *widget)
-{
- QMacCocoaAutoReleasePool pool;
- OSWindowRef theWindow = static_cast<OSWindowRef>(window);
- if(!theWindow)
- return;
- id theClass = [[[theWindow contentView] superview] class];
- // What we do here is basically to add a new selector to NSThemeFrame called
- // "drawRectOriginal:" which will contain the original implementation of
- // "drawRect:". After that we get the new implementation from QCocoaWindow
- // and exchange them. The new implementation is called drawRectSpecial.
- // We cannot just add the method because it might have been added before and since
- // we cannot remove a method once it has been added we need to ask QCocoaWindow if
- // we did the swap or not.
- if(!widget->drawRectOriginalAdded) {
- Method m2 = class_getInstanceMethod(theClass, @selector(drawRect:));
- if(!m2) {
- // This case is pretty extreme, no drawRect means no drawing!
- return;
- }
- class_addMethod(theClass, @selector(drawRectOriginal:), method_getImplementation(m2), method_getTypeEncoding(m2));
- widget->drawRectOriginalAdded = true;
- }
- if(widget->originalDrawMethod) {
- Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
- if(!m0) {
- // Ok, this means the methods were never swapped. Just ignore
- return;
- }
- Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
- if(!m1) {
- // Ok, this means the methods were never swapped. Just ignore
- return;
- }
- // We have the original method here. Proceed and swap the methods.
- method_exchangeImplementations(m1, m0);
- widget->originalDrawMethod = false;
- [theWindow display];
- }
-}
-
-void qt_mac_replaceDrawRectOriginal(void * /*OSWindowRef */window, QWidgetPrivate *widget)
-{
- QMacCocoaAutoReleasePool pool;
- OSWindowRef theWindow = static_cast<OSWindowRef>(window);
- id theClass = [[[theWindow contentView] superview] class];
- // Now we need to revert the methods to their original state.
- // We cannot remove the method, so we just keep track of it in QCocoaWindow.
- Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
- if(!m0) {
- // Ok, this means the methods were never swapped. Just ignore
- return;
- }
- Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
- if(!m1) {
- // Ok, this means the methods were never swapped. Just ignore
- return;
- }
- method_exchangeImplementations(m1, m0);
- widget->originalDrawMethod = true;
- [theWindow display];
-}
-#endif // QT_MAC_USE_COCOA
-
-#if QT_MAC_USE_COCOA
-void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show)
-{
- if(!window)
- return;
- QMacCocoaAutoReleasePool pool;
- OSWindowRef theWindow = static_cast<OSWindowRef>(window);
- NSToolbar *macToolbar = [theWindow toolbar];
- [macToolbar setShowsBaselineSeparator:show];
-}
-#endif // QT_MAC_USE_COCOA
-
-QStringList qt_mac_NSArrayToQStringList(void *nsarray)
-{
- QStringList result;
- NSArray *array = static_cast<NSArray *>(nsarray);
- for (NSUInteger i=0; i<[array count]; ++i)
- result << qt_mac_NSStringToQString([array objectAtIndex:i]);
- return result;
-}
-
-void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list)
-{
- NSMutableArray *result = [NSMutableArray arrayWithCapacity:list.size()];
- for (int i=0; i<list.size(); ++i){
- [result addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(list[i]))];
- }
- return result;
-}
-
-#if QT_MAC_USE_COCOA
-void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow)
-{
- if (!widgetForWindow)
- return;
-
- Qt::WindowFlags flags = widgetForWindow->windowFlags();
- bool customize = flags & Qt::CustomizeWindowHint;
-
- NSButton *btn = [window standardWindowButton:NSWindowZoomButton];
- // BOOL is not an int, so the bitwise AND doesn't work.
- bool go = uint(customize && !(flags & Qt::WindowMaximizeButtonHint)) == 0;
- [btn setEnabled:go];
-
- btn = [window standardWindowButton:NSWindowMiniaturizeButton];
- go = uint(customize && !(flags & Qt::WindowMinimizeButtonHint)) == 0;
- [btn setEnabled:go];
-
- btn = [window standardWindowButton:NSWindowCloseButton];
- go = uint(customize && !(flags & Qt::WindowSystemMenuHint
- || flags & Qt::WindowCloseButtonHint)) == 0;
- [btn setEnabled:go];
-
- [window setShowsToolbarButton:uint(flags & Qt::MacWindowToolBarButtonHint) != 0];
-}
-#endif // QT_MAC_USE_COCOA
-
-// Carbon: Make sure you call QDEndContext on the context when done with it.
-CGContextRef qt_mac_graphicsContextFor(QWidget *widget)
-{
- if (!widget)
- return 0;
-
-#ifndef QT_MAC_USE_COCOA
- CGContextRef context;
- CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
- QDBeginCGContext(port, &context);
-#else
- CGContextRef context = (CGContextRef)[[NSGraphicsContext graphicsContextWithWindow:qt_mac_window_for(widget)] graphicsPort];
-#endif
- return context;
-}
-
-void qt_mac_dispatchPendingUpdateRequests(QWidget *widget)
-{
- if (!widget)
- return;
-#ifndef QT_MAC_USE_COCOA
- HIViewRender(qt_mac_nativeview_for(widget));
-#else
- [qt_mac_nativeview_for(widget) displayIfNeeded];
-#endif
-}
-
-CGFloat qt_mac_get_scalefactor()
-{
-#ifndef QT_MAC_USE_COCOA
- return HIGetScaleFactor();
-#else
- return [[NSScreen mainScreen] userSpaceScaleFactor];
-#endif
-}
-
-QString qt_mac_get_pasteboardString(OSPasteboardRef paste)
-{
- QMacCocoaAutoReleasePool pool;
- NSPasteboard *pb = nil;
- CFStringRef pbname;
- if (PasteboardCopyName(paste, &pbname) == noErr) {
- pb = [NSPasteboard pasteboardWithName:const_cast<NSString *>(reinterpret_cast<const NSString *>(pbname))];
- CFRelease(pbname);
- } else {
- pb = [NSPasteboard generalPasteboard];
- }
- if (pb) {
- NSString *text = [pb stringForType:NSStringPboardType];
- if (text)
- return qt_mac_NSStringToQString(text);
- }
- return QString();
-}
-
-QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
-{
- QPixmap ret(width, height);
- ret.fill(QColor(0, 0, 0, 0));
-
- CGRect rect = CGRectMake(0, 0, width, height);
-
- CGContextRef ctx = qt_mac_cg_context(&ret);
- CGAffineTransform old_xform = CGContextGetCTM(ctx);
- CGContextConcatCTM(ctx, CGAffineTransformInvert(old_xform));
- CGContextConcatCTM(ctx, CGAffineTransformIdentity);
-
- ::RGBColor b;
- b.blue = b.green = b.red = 255*255;
- PlotIconRefInContext(ctx, &rect, kAlignNone, kTransformNone, &b, kPlotIconRefNormalFlags, icon);
- CGContextRelease(ctx);
- return ret;
-}
-
-void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon, QStyle::StandardPixmap standardIcon)
-{
- int size = 16;
- while (size <= 128) {
-
- const QString cacheKey = QLatin1String("qt_mac_constructQIconFromIconRef") + QString::number(standardIcon) + QString::number(size);
- QPixmap mainIcon;
- if (standardIcon >= QStyle::SP_CustomBase) {
- mainIcon = qt_mac_convert_iconref(icon, size, size);
- } else if (QPixmapCache::find(cacheKey, mainIcon) == false) {
- mainIcon = qt_mac_convert_iconref(icon, size, size);
- QPixmapCache::insert(cacheKey, mainIcon);
- }
-
- if (overlayIcon) {
- int littleSize = size / 2;
- QPixmap overlayPix = qt_mac_convert_iconref(overlayIcon, littleSize, littleSize);
- QPainter painter(&mainIcon);
- painter.drawPixmap(size - littleSize, size - littleSize, overlayPix);
- }
-
- retIcon->addPixmap(mainIcon);
- size += size; // 16 -> 32 -> 64 -> 128
- }
-}
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_menu_collapseSeparators(void */*NSMenu **/ theMenu, bool collapse)
-{
- QMacCocoaAutoReleasePool pool;
- OSMenuRef menu = static_cast<OSMenuRef>(theMenu);
- if (collapse) {
- bool previousIsSeparator = true; // setting to true kills all the separators placed at the top.
- NSMenuItem *previousItem = nil;
-
- NSArray *itemArray = [menu itemArray];
- for (unsigned int i = 0; i < [itemArray count]; ++i) {
- NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
- if ([item isSeparatorItem]) {
- [item setHidden:previousIsSeparator];
- }
-
- if (![item isHidden]) {
- previousItem = item;
- previousIsSeparator = ([previousItem isSeparatorItem]);
- }
- }
-
- // We now need to check the final item since we don't want any separators at the end of the list.
- if (previousItem && previousIsSeparator)
- [previousItem setHidden:YES];
- } else {
- NSArray *itemArray = [menu itemArray];
- for (unsigned int i = 0; i < [itemArray count]; ++i) {
- NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
- if (QAction *action = reinterpret_cast<QAction *>([item tag]))
- [item setHidden:!action->isVisible()];
- }
- }
-}
-
-class CocoaPostMessageAfterEventLoopExitHelp : public QObject
-{
- id target;
- SEL selector;
- int argCount;
- id arg1;
- id arg2;
-public:
- CocoaPostMessageAfterEventLoopExitHelp(id target, SEL selector, int argCount, id arg1, id arg2)
- : target(target), selector(selector), argCount(argCount), arg1(arg1), arg2(arg2){
- deleteLater();
- }
-
- ~CocoaPostMessageAfterEventLoopExitHelp()
- {
- qt_cocoaPostMessage(target, selector, argCount, arg1, arg2);
- }
-};
-
-void qt_cocoaPostMessage(id target, SEL selector, int argCount, id arg1, id arg2)
-{
- // WARNING: data1 and data2 is truncated to from 64-bit to 32-bit on OS 10.5!
- // That is why we need to split the address in two parts:
- QCocoaPostMessageArgs *args = new QCocoaPostMessageArgs(target, selector, argCount, arg1, arg2);
- quint32 lower = quintptr(args);
- quint32 upper = quintptr(args) >> 32;
- NSEvent *e = [NSEvent otherEventWithType:NSApplicationDefined
- location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0
- context:nil subtype:QtCocoaEventSubTypePostMessage data1:lower data2:upper];
- [NSApp postEvent:e atStart:NO];
-}
-
-void qt_cocoaPostMessageAfterEventLoopExit(id target, SEL selector, int argCount, id arg1, id arg2)
-{
- if (QApplicationPrivate::instance()->threadData->eventLoops.size() <= 1)
- qt_cocoaPostMessage(target, selector, argCount, arg1, arg2);
- else
- new CocoaPostMessageAfterEventLoopExitHelp(target, selector, argCount, arg1, arg2);
-}
-
-#endif
-
-QMacCocoaAutoReleasePool::QMacCocoaAutoReleasePool()
-{
-#ifndef QT_MAC_USE_COCOA
- NSApplicationLoad();
-#endif
- pool = (void*)[[NSAutoreleasePool alloc] init];
-}
-
-QMacCocoaAutoReleasePool::~QMacCocoaAutoReleasePool()
-{
- [(NSAutoreleasePool*)pool release];
-}
-
-void qt_mac_post_retranslateAppMenu()
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- qt_cocoaPostMessage([NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)], @selector(qtTranslateApplicationMenu));
-#endif
-}
-
-QWidgetPrivate *QMacScrollOptimization::_target = 0;
-bool QMacScrollOptimization::_inWheelEvent = false;
-int QMacScrollOptimization::_dx = 0;
-int QMacScrollOptimization::_dy = 0;
-QRect QMacScrollOptimization::_scrollRect = QRect(0, 0, -1, -1);
-
-#ifdef QT_MAC_USE_COCOA
-// This method implements the magic for the drawRectSpecial method.
-// We draw a line at the upper edge of the content view in order to
-// override the title baseline.
-void macDrawRectOnTop(void * /*OSWindowRef */window)
-{
- OSWindowRef theWindow = static_cast<OSWindowRef>(window);
- NSView *contentView = [theWindow contentView];
- if(!contentView)
- return;
- // Get coordinates of the content view
- NSRect contentRect = [contentView frame];
- // Draw a line on top of the already drawn line.
- // We need to check if we are active or not to use the proper color.
- if([theWindow isKeyWindow] || [theWindow isMainWindow]) {
- [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
- } else {
- [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
- }
- NSPoint origin = NSMakePoint(0, contentRect.size.height);
- NSPoint end = NSMakePoint(contentRect.size.width, contentRect.size.height);
- [NSBezierPath strokeLineFromPoint:origin toPoint:end];
-}
-
-// This method will (or at least should) get called only once.
-// Its mission is to find out if we are active or not. If we are active
-// we assume that we were launched via finder, otherwise we assume
-// we were called from the command line. The distinction is important,
-// since in the first case we don't need to trigger a paintEvent, while
-// in the second case we do.
-void macSyncDrawingOnFirstInvocation(void * /*OSWindowRef */window)
-{
- OSWindowRef theWindow = static_cast<OSWindowRef>(window);
- NSApplication *application = [NSApplication sharedApplication];
- NSToolbar *toolbar = [theWindow toolbar];
- if([application isActive]) {
- // Launched from finder
- [toolbar setShowsBaselineSeparator:NO];
- } else {
- // Launched from commandline
- [toolbar setVisible:false];
- [toolbar setShowsBaselineSeparator:NO];
- [toolbar setVisible:true];
- [theWindow display];
- }
-}
-
-void qt_cocoaStackChildWindowOnTopOfOtherChildren(QWidget *childWidget)
-{
- if (!childWidget)
- return;
-
- QWidget *parent = childWidget->parentWidget();
- if (childWidget->isWindow() && parent) {
- if ([[qt_mac_window_for(parent) childWindows] containsObject:qt_mac_window_for(childWidget)]) {
- QWidgetPrivate *d = qt_widget_private(childWidget);
- d->setSubWindowStacking(false);
- d->setSubWindowStacking(true);
- }
- }
-}
-
-void qt_mac_display(QWidget *widget)
-{
- NSView *theNSView = qt_mac_nativeview_for(widget);
- [theNSView display];
-}
-
-void qt_mac_setNeedsDisplay(QWidget *widget)
-{
- NSView *theNSView = qt_mac_nativeview_for(widget);
- [theNSView setNeedsDisplay:YES];
-}
-
-void qt_mac_setNeedsDisplayInRect(QWidget *widget, QRegion region)
-{
- NSView *theNSView = qt_mac_nativeview_for(widget);
- if (region.isEmpty()) {
- [theNSView setNeedsDisplay:YES];
- return;
- }
-
- QVector<QRect> rects = region.rects();
- for (int i = 0; i < rects.count(); ++i) {
- const QRect &rect = rects.at(i);
- NSRect nsrect = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
- [theNSView setNeedsDisplayInRect:nsrect];
- }
-
-}
-
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qt_cocoa_helpers_mac_p.h b/src/gui/platforms/mac/qt_cocoa_helpers_mac_p.h
deleted file mode 100644
index a49753ae2f..0000000000
--- a/src/gui/platforms/mac/qt_cocoa_helpers_mac_p.h
+++ /dev/null
@@ -1,340 +0,0 @@
-/****************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-#ifndef QT_COCOA_HELPERS_MAC_P_H
-#define QT_COCOA_HELPERS_MAC_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 <private/qt_mac_p.h>
-
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <qwidget.h>
-#include <qevent.h>
-#include <qhash.h>
-#include <qlabel.h>
-#include <qpointer.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qstylepainter.h>
-#include <qtimer.h>
-#include <qtooltip.h>
-#include <private/qeffects_p.h>
-#include <private/qwidget_p.h>
-#include <qtextdocument.h>
-#include <qdebug.h>
-#include <qpoint.h>
-#include "private/qt_mac_p.h"
-
-struct HIContentBorderMetrics;
-
-#ifdef Q_WS_MAC32
-typedef struct _NSPoint NSPoint; // Just redefine here so I don't have to pull in all of Cocoa.
-#else
-typedef struct CGPoint NSPoint;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-enum {
- QtCocoaEventSubTypeWakeup = SHRT_MAX,
- QtCocoaEventSubTypePostMessage = SHRT_MAX-1
-};
-
-Qt::MouseButtons qt_mac_get_buttons(int buttons);
-Qt::MouseButton qt_mac_get_button(EventMouseButton button);
-void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds = 0.15);
-bool macWindowIsTextured(void * /*OSWindowRef*/ window);
-void macWindowToolbarShow(const QWidget *widget, bool show );
-void macWindowToolbarSet( void * /*OSWindowRef*/ window, void* toolbarRef );
-bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window );
-void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow );
-void macWindowFlush(void * /*OSWindowRef*/ window);
-void macSendToolbarChangeEvent(QWidget *widget);
-void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics);
-void qt_mac_replaceDrawRect(void * /*OSWindowRef */window, QWidgetPrivate *widget);
-void qt_mac_replaceDrawRectOriginal(void * /*OSWindowRef */window, QWidgetPrivate *widget);
-void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show);
-void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm);
-void qt_mac_update_mouseTracking(QWidget *widget);
-OSStatus qt_mac_drawCGImage(CGContextRef cg, const CGRect *inbounds, CGImageRef);
-bool qt_mac_checkForNativeSizeGrip(const QWidget *widget);
-void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent);
-#ifdef QT_MAC_USE_COCOA
-bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent);
-// These methods exists only for supporting unified mode.
-void macDrawRectOnTop(void * /*OSWindowRef */ window);
-void macSyncDrawingOnFirstInvocation(void * /*OSWindowRef */window);
-void qt_cocoaStackChildWindowOnTopOfOtherChildren(QWidget *widget);
-void qt_mac_menu_collapseSeparators(void * /*NSMenu */ menu, bool collapse);
-#endif
-bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent);
-void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent);
-bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */event);
-inline QApplication *qAppInstance() { return static_cast<QApplication *>(QCoreApplication::instance()); }
-struct ::TabletProximityRec;
-void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec);
-Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags);
-Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations);
-QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height);
-void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon,
- QStyle::StandardPixmap standardIcon = QStyle::SP_CustomBase);
-
-#if QT_MAC_USE_COCOA && __OBJC__
-struct DnDParams
-{
- NSView *view;
- NSEvent *theEvent;
- QPoint globalPoint;
- NSDragOperation performedAction;
-};
-
-DnDParams *macCurrentDnDParameters();
-NSDragOperation qt_mac_mapDropAction(Qt::DropAction action);
-NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions);
-Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions);
-Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions);
-
-QWidget *qt_mac_getTargetForKeyEvent(QWidget *widgetThatReceivedEvent);
-QWidget *qt_mac_getTargetForMouseEvent(NSEvent *event, QEvent::Type eventType,
- QPoint &returnLocalPoint, QPoint &returnGlobalPoint, QWidget *nativeWidget, QWidget **returnWidgetUnderMouse);
-bool qt_mac_handleMouseEvent(NSEvent *event, QEvent::Type eventType, Qt::MouseButton button, QWidget *nativeWidget);
-void qt_mac_handleNonClientAreaMouseEvent(NSWindow *window, NSEvent *event);
-#endif
-
-inline int flipYCoordinate(int y)
-{
- return QApplication::desktop()->screenGeometry(0).height() - y;
-}
-
-inline qreal flipYCoordinate(qreal y)
-{
- return QApplication::desktop()->screenGeometry(0).height() - y;
-}
-
-QPointF flipPoint(const NSPoint &p);
-NSPoint flipPoint(const QPoint &p);
-NSPoint flipPoint(const QPointF &p);
-
-QStringList qt_mac_NSArrayToQStringList(void *nsarray);
-void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list);
-
-void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow);
-
-CGFloat qt_mac_get_scalefactor();
-QString qt_mac_get_pasteboardString(OSPasteboardRef paste);
-
-#ifdef __OBJC__
-inline NSMutableArray *qt_mac_QStringListToNSMutableArray(const QStringList &qstrlist)
-{ return reinterpret_cast<NSMutableArray *>(qt_mac_QStringListToNSMutableArrayVoid(qstrlist)); }
-
-inline QString qt_mac_NSStringToQString(const NSString *nsstr)
-{ return QCFString::toQString(reinterpret_cast<const CFStringRef>(nsstr)); }
-
-inline NSString *qt_mac_QStringToNSString(const QString &qstr)
-{ return [reinterpret_cast<const NSString *>(QCFString::toCFStringRef(qstr)) autorelease]; }
-
-#ifdef QT_MAC_USE_COCOA
-class QCocoaPostMessageArgs {
-public:
- id target;
- SEL selector;
- int argCount;
- id arg1;
- id arg2;
- QCocoaPostMessageArgs(id target, SEL selector, int argCount=0, id arg1=0, id arg2=0)
- : target(target), selector(selector), argCount(argCount), arg1(arg1), arg2(arg2)
- {
- [target retain];
- [arg1 retain];
- [arg2 retain];
- }
-
- ~QCocoaPostMessageArgs()
- {
- [arg2 release];
- [arg1 release];
- [target release];
- }
-};
-void qt_cocoaPostMessage(id target, SEL selector, int argCount=0, id arg1=0, id arg2=0);
-void qt_cocoaPostMessageAfterEventLoopExit(id target, SEL selector, int argCount=0, id arg1=0, id arg2=0);
-#endif
-
-#endif
-
-class QMacScrollOptimization {
- // This class is made to optimize for the case when the user
- // scrolls both horizontally and vertically at the same
- // time. This will result in two QWheelEvents (one for each
- // direction), which will typically result in two calls to
- // QWidget::_scroll_sys. Rather than copying pixels twize on
- // screen because of this, we add this helper class to try to
- // get away with only one blit.
- static QWidgetPrivate *_target;
- static bool _inWheelEvent;
- static int _dx;
- static int _dy;
- static QRect _scrollRect;
-
-public:
- static void initDelayedScroll()
- {
- _inWheelEvent = true;
- }
-
- static bool delayScroll(QWidgetPrivate *target, int dx, int dy, const QRect &scrollRect)
- {
- if (!_inWheelEvent)
- return false;
- if (_target && _target != target)
- return false;
- if (_scrollRect.width() != -1 && _scrollRect != scrollRect)
- return false;
-
- _target = target;
- _dx += dx;
- _dy += dy;
- _scrollRect = scrollRect;
- return true;
- }
-
- static void performDelayedScroll()
- {
- if (!_inWheelEvent)
- return;
- _inWheelEvent = false;
- if (!_target)
- return;
-
- _target->scroll_sys(_dx, _dy, _scrollRect);
-
- _target = 0;
- _dx = 0;
- _dy = 0;
- _scrollRect = QRect(0, 0, -1, -1);
- }
-};
-
-void qt_mac_post_retranslateAppMenu();
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_display(QWidget *widget);
-void qt_mac_setNeedsDisplay(QWidget *widget);
-void qt_mac_setNeedsDisplayInRect(QWidget *widget, QRegion region);
-#endif // QT_MAC_USE_COCOA
-
-
-// Utility functions to ease the use of Core Graphics contexts.
-
-inline void qt_mac_retain_graphics_context(CGContextRef context)
-{
- CGContextRetain(context);
- CGContextSaveGState(context);
-}
-
-inline void qt_mac_release_graphics_context(CGContextRef context)
-{
- CGContextRestoreGState(context);
- CGContextRelease(context);
-}
-
-inline void qt_mac_draw_image(CGContextRef context, CGContextRef imageContext, CGRect area, CGRect drawingArea)
-{
- CGImageRef image = CGBitmapContextCreateImage(imageContext);
- CGImageRef subImage = CGImageCreateWithImageInRect(image, area);
-
- CGContextTranslateCTM (context, 0, drawingArea.origin.y + CGRectGetMaxY(drawingArea));
- CGContextScaleCTM(context, 1, -1);
- CGContextDrawImage(context, drawingArea, subImage);
-
- CGImageRelease(subImage);
- CGImageRelease(image);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_COCOA_HELPERS_MAC_P_H
diff --git a/src/gui/platforms/mac/qt_mac.cpp b/src/gui/platforms/mac/qt_mac.cpp
deleted file mode 100644
index 046bcf6a54..0000000000
--- a/src/gui/platforms/mac/qt_mac.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qt_mac_p.h>
-#include <private/qpixmap_mac_p.h>
-#include <private/qnativeimage_p.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-#ifdef QT_MAC_USE_COCOA
-static CTFontRef CopyCTThemeFont(ThemeFontID themeID)
-{
- CTFontUIFontType ctID = HIThemeGetUIFontType(themeID);
- return CTFontCreateUIFontForLanguage(ctID, 0, 0);
-}
-#endif
-
-QFont qfontForThemeFont(ThemeFontID themeID)
-{
-#ifndef QT_MAC_USE_COCOA
- static const ScriptCode Script = smRoman;
- Str255 f_name;
- SInt16 f_size;
- Style f_style;
- GetThemeFont(themeID, Script, f_name, &f_size, &f_style);
- extern QString qt_mac_from_pascal_string(const Str255); //qglobal.cpp
- return QFont(qt_mac_from_pascal_string(f_name), f_size,
- (f_style & ::bold) ? QFont::Bold : QFont::Normal,
- (bool)(f_style & ::italic));
-#else
- QCFType<CTFontRef> ctfont = CopyCTThemeFont(themeID);
- QString familyName = QCFString(CTFontCopyFamilyName(ctfont));
- QCFType<CFDictionaryRef> dict = CTFontCopyTraits(ctfont);
- CFNumberRef num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontWeightTrait));
- float fW;
- CFNumberGetValue(num, kCFNumberFloat32Type, &fW);
- QFont::Weight wght = fW > 0. ? QFont::Bold : QFont::Normal;
- num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontSlantTrait));
- CFNumberGetValue(num, kCFNumberFloatType, &fW);
- bool italic = (fW != 0.0);
- return QFont(familyName, CTFontGetSize(ctfont), wght, italic);
-#endif
-}
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-static QColor qcolorFromCGColor(CGColorRef cgcolor)
-{
- QColor pc;
- CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgcolor));
- const CGFloat *components = CGColorGetComponents(cgcolor);
- if (model == kCGColorSpaceModelRGB) {
- pc.setRgbF(components[0], components[1], components[2], components[3]);
- } else if (model == kCGColorSpaceModelCMYK) {
- pc.setCmykF(components[0], components[1], components[2], components[3]);
- } else if (model == kCGColorSpaceModelMonochrome) {
- pc.setRgbF(components[0], components[0], components[0], components[1]);
- } else {
- // Colorspace we can't deal with.
- qWarning("Qt: qcolorFromCGColor: cannot convert from colorspace model: %d", model);
- Q_ASSERT(false);
- }
- return pc;
-}
-
-static inline QColor leopardBrush(ThemeBrush brush)
-{
- QCFType<CGColorRef> cgClr = 0;
- HIThemeBrushCreateCGColor(brush, &cgClr);
- return qcolorFromCGColor(cgClr);
-}
-#endif
-
-QColor qcolorForTheme(ThemeBrush brush)
-{
-#ifndef QT_MAC_USE_COCOA
-# if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- return leopardBrush(brush);
- } else
-# endif
- {
- RGBColor rgbcolor;
- GetThemeBrushAsColor(brush, 32, true, &rgbcolor);
- return QColor(rgbcolor.red / 256, rgbcolor.green / 256, rgbcolor.blue / 256);
- }
-#else
- return leopardBrush(brush);
-#endif
-}
-
-QColor qcolorForThemeTextColor(ThemeTextColor themeColor)
-{
-#ifdef Q_OS_MAC32
- RGBColor c;
- GetThemeTextColor(themeColor, 32, true, &c);
- QColor color = QColor(c.red / 256, c.green / 256, c.blue / 256);
- return color;
-#else
- // There is no equivalent to GetThemeTextColor in 64-bit and it was rather bad that
- // I didn't file a request to implement this for Snow Leopard. So, in the meantime
- // I've encoded the values from the GetThemeTextColor. This is not exactly ideal
- // as if someone really wants to mess with themeing, these colors will be wrong.
- // It also means that we need to make sure the values for differences between
- // OS releases (and it will be likely that we are a step behind.)
- switch (themeColor) {
- case kThemeTextColorAlertActive:
- case kThemeTextColorTabFrontActive:
- case kThemeTextColorBevelButtonActive:
- case kThemeTextColorListView:
- case kThemeTextColorPlacardActive:
- case kThemeTextColorPopupButtonActive:
- case kThemeTextColorPopupLabelActive:
- case kThemeTextColorPushButtonActive:
- return Qt::black;
- case kThemeTextColorAlertInactive:
- case kThemeTextColorDialogInactive:
- case kThemeTextColorPlacardInactive:
- return QColor(69, 69, 69, 255);
- case kThemeTextColorPopupButtonInactive:
- case kThemeTextColorPopupLabelInactive:
- case kThemeTextColorPushButtonInactive:
- case kThemeTextColorTabFrontInactive:
- case kThemeTextColorBevelButtonInactive:
- return QColor(127, 127, 127, 255);
- default: {
- QNativeImage nativeImage(16,16, QNativeImage::systemFormat());
- CGRect cgrect = CGRectMake(0, 0, 16, 16);
- HIThemeSetTextFill(themeColor, 0, nativeImage.cg, kHIThemeOrientationNormal);
- CGContextFillRect(nativeImage.cg, cgrect);
- QColor color = nativeImage.image.pixel(0,0);
- return QColor(nativeImage.image.pixel(0 , 0));
- }
- }
-#endif
-}
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qt_mac_p.h b/src/gui/platforms/mac/qt_mac_p.h
deleted file mode 100644
index b2bb804ff0..0000000000
--- a/src/gui/platforms/mac/qt_mac_p.h
+++ /dev/null
@@ -1,286 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_MAC_P_H
-#define QT_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmacdefines_mac.h"
-
-#ifdef __OBJC__
-#include <Cocoa/Cocoa.h>
-#ifdef QT_MAC_USE_COCOA
-#include <objc/runtime.h>
-#endif // QT_MAC_USE_COCOA
-#endif
-
-#include <CoreServices/CoreServices.h>
-
-#include "QtCore/qglobal.h"
-#include "QtCore/qvariant.h"
-#include "QtCore/qmimedata.h"
-#include "QtCore/qpointer.h"
-#include "private/qcore_mac_p.h"
-
-
-#include "QtGui/qpainter.h"
-
-#include <Carbon/Carbon.h>
-
-QT_BEGIN_NAMESPACE
-class QWidget;
-class QDragMoveEvent;
-
-/* Event masks */
-// internal Qt types
-
- // Event class for our own Carbon events.
-#if defined(QT_NAMESPACE) && defined(QT_NAMESPACE_MAC_CRC)
-// Take the CRC we generated at configure time. This *may* result in a
-// collision with another value If that is the case, please change the value
-// here to something other than 'Cute'.
-const UInt32 kEventClassQt = QT_NAMESPACE_MAC_CRC;
-#else
-const UInt32 kEventClassQt = 'Cute';
-#endif
-
-enum {
- //AE types
- typeAEClipboardChanged = 1,
- //types
- typeQWidget = 1, /* QWidget * */
- //params
- kEventParamQWidget = 'qwid', /* typeQWidget */
- //events
- kEventQtRequestContext = 13,
- kEventQtRequestMenubarUpdate = 14,
- kEventQtRequestShowSheet = 17,
- kEventQtRequestActivate = 18,
- kEventQtRequestWindowChange = 20
-};
-
-// Simple class to manage short-lived regions
-class QMacSmartQuickDrawRegion
-{
- RgnHandle qdRgn;
- Q_DISABLE_COPY(QMacSmartQuickDrawRegion)
-public:
- explicit QMacSmartQuickDrawRegion(RgnHandle rgn) : qdRgn(rgn) {}
- ~QMacSmartQuickDrawRegion() {
- extern void qt_mac_dispose_rgn(RgnHandle); // qregion_mac.cpp
- qt_mac_dispose_rgn(qdRgn);
- }
- operator RgnHandle() {
- return qdRgn;
- }
-};
-
-// Class for chaining to gether a bunch of fades. It pretty much is only used for qmenu fading.
-class QMacWindowFader
-{
- QWidgetList m_windowsToFade;
- float m_duration;
- Q_DISABLE_COPY(QMacWindowFader)
-public:
- QMacWindowFader(); // PLEASE DON'T CALL THIS.
- static QMacWindowFader *currentFader();
- void registerWindowToFade(QWidget *window);
- void setFadeDuration(float durationInSecs) { m_duration = durationInSecs; }
- float fadeDuration() const { return m_duration; }
- void performFade();
-};
-
-class Q_GUI_EXPORT QMacCocoaAutoReleasePool
-{
-private:
- void *pool;
-public:
- QMacCocoaAutoReleasePool();
- ~QMacCocoaAutoReleasePool();
-
- inline void *handle() const { return pool; }
-};
-
-QString qt_mac_removeMnemonics(const QString &original); //implemented in qmacstyle_mac.cpp
-
-class Q_GUI_EXPORT QMacWindowChangeEvent
-{
-private:
- static QList<QMacWindowChangeEvent*> *change_events;
-public:
- QMacWindowChangeEvent() {
- }
- virtual ~QMacWindowChangeEvent() {
- }
- static inline void exec(bool ) {
- }
-protected:
- virtual void windowChanged() = 0;
- virtual void flushWindowChanged() = 0;
-};
-
-class QMacCGContext
-{
- CGContextRef context;
-public:
- QMacCGContext(QPainter *p); //qpaintengine_mac.cpp
- inline QMacCGContext() { context = 0; }
- inline QMacCGContext(const QPaintDevice *pdev) {
- extern CGContextRef qt_mac_cg_context(const QPaintDevice *);
- context = qt_mac_cg_context(pdev);
- }
- inline QMacCGContext(CGContextRef cg, bool takeOwnership=false) {
- context = cg;
- if(!takeOwnership)
- CGContextRetain(context);
- }
- inline QMacCGContext(const QMacCGContext &copy) : context(0) { *this = copy; }
- inline ~QMacCGContext() {
- if(context)
- CGContextRelease(context);
- }
- inline bool isNull() const { return context; }
- inline operator CGContextRef() { return context; }
- inline QMacCGContext &operator=(const QMacCGContext &copy) {
- if(context)
- CGContextRelease(context);
- context = copy.context;
- CGContextRetain(context);
- return *this;
- }
- inline QMacCGContext &operator=(CGContextRef cg) {
- if(context)
- CGContextRelease(context);
- context = cg;
- CGContextRetain(context); //we do not take ownership
- return *this;
- }
-};
-
-class QMacPasteboardMime;
-class QMimeData;
-
-class QMacPasteboard
-{
- struct Promise {
- Promise() : itemId(0), convertor(0) { }
- Promise(int itemId, QMacPasteboardMime *c, QString m, QVariant d, int o=0) : itemId(itemId), offset(o), convertor(c), mime(m), data(d) { }
- int itemId, offset;
- QMacPasteboardMime *convertor;
- QString mime;
- QVariant data;
- };
- QList<Promise> promises;
-
- OSPasteboardRef paste;
- uchar mime_type;
- mutable QPointer<QMimeData> mime;
- mutable bool mac_mime_source;
- static OSStatus promiseKeeper(OSPasteboardRef, PasteboardItemID, CFStringRef, void *);
- void clear_helper();
-public:
- QMacPasteboard(OSPasteboardRef p, uchar mime_type=0);
- QMacPasteboard(uchar mime_type);
- QMacPasteboard(CFStringRef name=0, uchar mime_type=0);
- ~QMacPasteboard();
-
- bool hasFlavor(QString flavor) const;
- bool hasOSType(int c_flavor) const;
-
- OSPasteboardRef pasteBoard() const;
- QMimeData *mimeData() const;
- void setMimeData(QMimeData *mime);
-
- QStringList formats() const;
- bool hasFormat(const QString &format) const;
- QVariant retrieveData(const QString &format, QVariant::Type) const;
-
- void clear();
- bool sync() const;
-};
-
-extern QPaintDevice *qt_mac_safe_pdev; //qapplication_mac.cpp
-
-extern OSWindowRef qt_mac_window_for(const QWidget*); //qwidget_mac.mm
-extern OSViewRef qt_mac_nativeview_for(const QWidget *); //qwidget_mac.mm
-extern QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt); //qwidget_mac.mm
-
-#ifdef check
-# undef check
-#endif
-
-QFont qfontForThemeFont(ThemeFontID themeID);
-
-QColor qcolorForTheme(ThemeBrush brush);
-
-QColor qcolorForThemeTextColor(ThemeTextColor themeColor);
-
-struct QMacDndAnswerRecord {
- QRect rect;
- Qt::KeyboardModifiers modifiers;
- Qt::MouseButtons buttons;
- Qt::DropAction lastAction;
- unsigned int lastOperation;
- void clear() {
- rect = QRect();
- modifiers = Qt::NoModifier;
- buttons = Qt::NoButton;
- lastAction = Qt::IgnoreAction;
- lastOperation = 0;
- }
-};
-extern QMacDndAnswerRecord qt_mac_dnd_answer_rec;
-void qt_mac_copy_answer_rect(const QDragMoveEvent &event);
-bool qt_mac_mouse_inside_answer_rect(QPoint mouse);
-
-QT_END_NAMESPACE
-
-#endif // QT_MAC_P_H
diff --git a/src/gui/platforms/mac/qtextengine_mac.cpp b/src/gui/platforms/mac/qtextengine_mac.cpp
deleted file mode 100644
index 2c6e579b45..0000000000
--- a/src/gui/platforms/mac/qtextengine_mac.cpp
+++ /dev/null
@@ -1,656 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtextengine_p.h"
-
-#include <private/qfontengine_coretext_p.h>
-#include <private/qfontengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
-// and no reordering.
-// also computes logClusters heuristically
-static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
-{
- // ### zeroWidth and justification are missing here!!!!!
-
- Q_UNUSED(num_glyphs);
-
-// qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
-
- const bool symbolFont = false; // ####
- glyphs->attributes[0].mark = false;
- glyphs->attributes[0].clusterStart = true;
- glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
-
- int pos = 0;
- int lastCat = QChar::category(uc[0].unicode());
- for (int i = 1; i < length; ++i) {
- if (logClusters[i] == pos)
- // same glyph
- continue;
- ++pos;
- while (pos < logClusters[i]) {
- ++pos;
- }
- // hide soft-hyphens by default
- if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
- glyphs->attributes[pos].dontPrint = true;
- const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
- int cat = prop->category;
-
- // one gets an inter character justification point if the current char is not a non spacing mark.
- // as then the current char belongs to the last one and one gets a space justification point
- // after the space char.
- if (lastCat == QChar::Separator_Space)
- glyphs->attributes[pos-1].justification = HB_Space;
- else if (cat != QChar::Mark_NonSpacing)
- glyphs->attributes[pos-1].justification = HB_Character;
- else
- glyphs->attributes[pos-1].justification = HB_NoJustification;
-
- lastCat = cat;
- }
- pos = logClusters[length-1];
- if (lastCat == QChar::Separator_Space)
- glyphs->attributes[pos].justification = HB_Space;
- else
- glyphs->attributes[pos].justification = HB_Character;
-}
-
-struct QArabicProperties {
- unsigned char shape;
- unsigned char justification;
-};
-Q_DECLARE_TYPEINFO(QArabicProperties, Q_PRIMITIVE_TYPE);
-
-enum QArabicShape {
- XIsolated,
- XFinal,
- XInitial,
- XMedial,
- // intermediate state
- XCausing
-};
-
-
-// these groups correspond to the groups defined in the Unicode standard.
-// Some of these groups are equal with regards to both joining and line breaking behaviour,
-// and thus have the same enum value
-//
-// I'm not sure the mapping of syriac to arabic enums is correct with regards to justification, but as
-// I couldn't find any better document I'll hope for the best.
-enum ArabicGroup {
- // NonJoining
- ArabicNone,
- ArabicSpace,
- // Transparent
- Transparent,
- // Causing
- Center,
- Kashida,
-
- // Arabic
- // Dual
- Beh,
- Noon,
- Meem = Noon,
- Heh = Noon,
- KnottedHeh = Noon,
- HehGoal = Noon,
- SwashKaf = Noon,
- Yeh,
- Hah,
- Seen,
- Sad = Seen,
- Tah,
- Kaf = Tah,
- Gaf = Tah,
- Lam = Tah,
- Ain,
- Feh = Ain,
- Qaf = Ain,
- // Right
- Alef,
- Waw,
- Dal,
- TehMarbuta = Dal,
- Reh,
- HamzaOnHehGoal,
- YehWithTail = HamzaOnHehGoal,
- YehBarre = HamzaOnHehGoal,
-
- // Syriac
- // Dual
- Beth = Beh,
- Gamal = Ain,
- Heth = Noon,
- Teth = Hah,
- Yudh = Noon,
- Kaph = Noon,
- Lamadh = Lam,
- Mim = Noon,
- Nun = Noon,
- Semakh = Noon,
- FinalSemakh = Noon,
- SyriacE = Ain,
- Pe = Ain,
- ReversedPe = Hah,
- Qaph = Noon,
- Shin = Noon,
- Fe = Ain,
-
- // Right
- Alaph = Alef,
- Dalath = Dal,
- He = Dal,
- SyriacWaw = Waw,
- Zain = Alef,
- YudhHe = Waw,
- Sadhe = HamzaOnHehGoal,
- Taw = Dal,
-
- // Compiler bug? Otherwise ArabicGroupsEnd would be equal to Dal + 1.
- Dummy = HamzaOnHehGoal,
- ArabicGroupsEnd
-};
-
-static const unsigned char arabic_group[0x150] = {
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
- ArabicNone, ArabicNone, Alef, Alef,
- Waw, Alef, Yeh, Alef,
- Beh, TehMarbuta, Beh, Beh,
- Hah, Hah, Hah, Dal,
-
- Dal, Reh, Reh, Seen,
- Seen, Sad, Sad, Tah,
- Tah, Ain, Ain, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
- // 0x640
- Kashida, Feh, Qaf, Kaf,
- Lam, Meem, Noon, Heh,
- Waw, Yeh, Yeh, Transparent,
- Transparent, Transparent, Transparent, Transparent,
-
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, Transparent, Transparent,
- Transparent, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, Beh, Qaf,
-
- Transparent, Alef, Alef, Alef,
- ArabicNone, Alef, Waw, Waw,
- Yeh, Beh, Beh, Beh,
- Beh, Beh, Beh, Beh,
-
- // 0x680
- Beh, Hah, Hah, Hah,
- Hah, Hah, Hah, Hah,
- Dal, Dal, Dal, Dal,
- Dal, Dal, Dal, Dal,
-
- Dal, Reh, Reh, Reh,
- Reh, Reh, Reh, Reh,
- Reh, Reh, Seen, Seen,
- Seen, Sad, Sad, Tah,
-
- Ain, Feh, Feh, Feh,
- Feh, Feh, Feh, Qaf,
- Qaf, Gaf, SwashKaf, Gaf,
- Kaf, Kaf, Kaf, Gaf,
-
- Gaf, Gaf, Gaf, Gaf,
- Gaf, Lam, Lam, Lam,
- Lam, Noon, Noon, Noon,
- Noon, Noon, KnottedHeh, Hah,
-
- // 0x6c0
- TehMarbuta, HehGoal, HamzaOnHehGoal, HamzaOnHehGoal,
- Waw, Waw, Waw, Waw,
- Waw, Waw, Waw, Waw,
- Yeh, YehWithTail, Yeh, Waw,
-
- Yeh, Yeh, YehBarre, YehBarre,
- ArabicNone, TehMarbuta, Transparent, Transparent,
- Transparent, Transparent, Transparent, Transparent,
- Transparent, ArabicNone, ArabicNone, Transparent,
-
- Transparent, Transparent, Transparent, Transparent,
- Transparent, ArabicNone, ArabicNone, Transparent,
- Transparent, ArabicNone, Transparent, Transparent,
- Transparent, Transparent, Dal, Reh,
-
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, Seen, Sad,
- Ain, ArabicNone, ArabicNone, KnottedHeh,
-
- // 0x700
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
- ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
- Alaph, Transparent, Beth, Gamal,
- Gamal, Dalath, Dalath, He,
- SyriacWaw, Zain, Heth, Teth,
- Teth, Yudh, YudhHe, Kaph,
-
- Lamadh, Mim, Nun, Semakh,
- FinalSemakh, SyriacE, Pe, ReversedPe,
- Sadhe, Qaph, Dalath, Shin,
- Taw, Beth, Gamal, Dalath,
-
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, Transparent, Transparent,
-
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, Transparent, Transparent,
- Transparent, Transparent, Transparent, ArabicNone,
- ArabicNone, Zain, Kaph, Fe,
-};
-
-static inline ArabicGroup arabicGroup(unsigned short uc)
-{
- if (uc >= 0x0600 && uc < 0x750)
- return (ArabicGroup) arabic_group[uc-0x600];
- else if (uc == 0x200d)
- return Center;
- else if (QChar::category(uc) == QChar::Separator_Space)
- return ArabicSpace;
- else
- return ArabicNone;
-}
-
-
-/*
- Arabic shaping obeys a number of rules according to the joining classes (see Unicode book, section on
- arabic).
-
- Each unicode char has a joining class (right, dual (left&right), center (joincausing) or transparent).
- transparent joining is not encoded in QChar::joining(), but applies to all combining marks and format marks.
-
- Right join-causing: dual + center
- Left join-causing: dual + right + center
-
- Rules are as follows (for a string already in visual order, as we have it here):
-
- R1 Transparent characters do not affect joining behaviour.
- R2 A right joining character, that has a right join-causing char on the right will get form XRight
- (R3 A left joining character, that has a left join-causing char on the left will get form XLeft)
- Note: the above rule is meaningless, as there are no pure left joining characters defined in Unicode
- R4 A dual joining character, that has a left join-causing char on the left and a right join-causing char on
- the right will get form XMedial
- R5 A dual joining character, that has a right join causing char on the right, and no left join causing char on the left
- will get form XRight
- R6 A dual joining character, that has a left join causing char on the left, and no right join causing char on the right
- will get form XLeft
- R7 Otherwise the character will get form XIsolated
-
- Additionally we have to do the minimal ligature support for lam-alef ligatures:
-
- L1 Transparent characters do not affect ligature behaviour.
- L2 Any sequence of Alef(XRight) + Lam(XMedial) will form the ligature Alef.Lam(XLeft)
- L3 Any sequence of Alef(XRight) + Lam(XLeft) will form the ligature Alef.Lam(XIsolated)
-
- The state table below handles rules R1-R7.
-*/
-
-enum Joining {
- JNone,
- JCausing,
- JDual,
- JRight,
- JTransparent
-};
-
-static const Joining joining_for_group[ArabicGroupsEnd] = {
- // NonJoining
- JNone, // ArabicNone
- JNone, // ArabicSpace
- // Transparent
- JTransparent, // Transparent
- // Causing
- JCausing, // Center
- JCausing, // Kashida
- // Dual
- JDual, // Beh
- JDual, // Noon
- JDual, // Yeh
- JDual, // Hah
- JDual, // Seen
- JDual, // Tah
- JDual, // Ain
- // Right
- JRight, // Alef
- JRight, // Waw
- JRight, // Dal
- JRight, // Reh
- JRight // HamzaOnHehGoal
-};
-
-
-struct JoiningPair {
- QArabicShape form1;
- QArabicShape form2;
-};
-
-static const JoiningPair joining_table[5][4] =
-// None, Causing, Dual, Right
-{
- { { XIsolated, XIsolated }, { XIsolated, XCausing }, { XIsolated, XInitial }, { XIsolated, XIsolated } }, // XIsolated
- { { XFinal, XIsolated }, { XFinal, XCausing }, { XFinal, XInitial }, { XFinal, XIsolated } }, // XFinal
- { { XIsolated, XIsolated }, { XInitial, XCausing }, { XInitial, XMedial }, { XInitial, XFinal } }, // XInitial
- { { XFinal, XIsolated }, { XMedial, XCausing }, { XMedial, XMedial }, { XMedial, XFinal } }, // XMedial
- { { XIsolated, XIsolated }, { XIsolated, XCausing }, { XIsolated, XMedial }, { XIsolated, XFinal } }, // XCausing
-};
-
-
-/*
-According to http://www.microsoft.com/middleeast/Arabicdev/IE6/KBase.asp
-
-1. Find the priority of the connecting opportunities in each word
-2. Add expansion at the highest priority connection opportunity
-3. If more than one connection opportunity have the same highest value,
- use the opportunity closest to the end of the word.
-
-Following is a chart that provides the priority for connection
-opportunities and where expansion occurs. The character group names
-are those in table 6.6 of the UNICODE 2.0 book.
-
-
-PrioritY Glyph Condition Kashida Location
-
-Arabic_Kashida User inserted Kashida The user entered a Kashida in a position. After the user
- (Shift+j or Shift+[E with hat]) Thus, it is the highest priority to insert an inserted kashida
- automatic kashida.
-
-Arabic_Seen Seen, Sad Connecting to the next character. After the character.
- (Initial or medial form).
-
-Arabic_HaaDal Teh Marbutah, Haa, Dal Connecting to previous character. Before the final form
- of these characters.
-
-Arabic_Alef Alef, Tah, Lam, Connecting to previous character. Before the final form
- Kaf and Gaf of these characters.
-
-Arabic_BaRa Reh, Yeh Connected to medial Beh Before preceding medial Baa
-
-Arabic_Waw Waw, Ain, Qaf, Feh Connecting to previous character. Before the final form of
- these characters.
-
-Arabic_Normal Other connecting Connecting to previous character. Before the final form
- characters of these characters.
-
-
-
-This seems to imply that we have at most one kashida point per arabic word.
-
-*/
-
-void qt_getArabicProperties(const unsigned short *chars, int len, QArabicProperties *properties)
-{
-// qDebug("arabicSyriacOpenTypeShape: properties:");
- int lastPos = 0;
- int lastGroup = ArabicNone;
-
- ArabicGroup group = arabicGroup(chars[0]);
- Joining j = joining_for_group[group];
- QArabicShape shape = joining_table[XIsolated][j].form2;
- properties[0].justification = HB_NoJustification;
-
- for (int i = 1; i < len; ++i) {
- // #### fix handling for spaces and punktuation
- properties[i].justification = HB_NoJustification;
-
- group = arabicGroup(chars[i]);
- j = joining_for_group[group];
-
- if (j == JTransparent) {
- properties[i].shape = XIsolated;
- continue;
- }
-
- properties[lastPos].shape = joining_table[shape][j].form1;
- shape = joining_table[shape][j].form2;
-
- switch(lastGroup) {
- case Seen:
- if (properties[lastPos].shape == XInitial || properties[lastPos].shape == XMedial)
- properties[i-1].justification = HB_Arabic_Seen;
- break;
- case Hah:
- if (properties[lastPos].shape == XFinal)
- properties[lastPos-1].justification = HB_Arabic_HaaDal;
- break;
- case Alef:
- if (properties[lastPos].shape == XFinal)
- properties[lastPos-1].justification = HB_Arabic_Alef;
- break;
- case Ain:
- if (properties[lastPos].shape == XFinal)
- properties[lastPos-1].justification = HB_Arabic_Waw;
- break;
- case Noon:
- if (properties[lastPos].shape == XFinal)
- properties[lastPos-1].justification = HB_Arabic_Normal;
- break;
- case ArabicNone:
- break;
-
- default:
- Q_ASSERT(false);
- }
-
- lastGroup = ArabicNone;
-
- switch(group) {
- case ArabicNone:
- case Transparent:
- // ### Center should probably be treated as transparent when it comes to justification.
- case Center:
- break;
- case ArabicSpace:
- properties[i].justification = HB_Arabic_Space;
- break;
- case Kashida:
- properties[i].justification = HB_Arabic_Kashida;
- break;
- case Seen:
- lastGroup = Seen;
- break;
-
- case Hah:
- case Dal:
- lastGroup = Hah;
- break;
-
- case Alef:
- case Tah:
- lastGroup = Alef;
- break;
-
- case Yeh:
- case Reh:
- if (properties[lastPos].shape == XMedial && arabicGroup(chars[lastPos]) == Beh)
- properties[lastPos-1].justification = HB_Arabic_BaRa;
- break;
-
- case Ain:
- case Waw:
- lastGroup = Ain;
- break;
-
- case Noon:
- case Beh:
- case HamzaOnHehGoal:
- lastGroup = Noon;
- break;
- case ArabicGroupsEnd:
- Q_ASSERT(false);
- }
-
- lastPos = i;
- }
- properties[lastPos].shape = joining_table[shape][JNone].form1;
-
-
-// for (int i = 0; i < len; ++i)
-// qDebug("arabic properties(%d): uc=%x shape=%d, justification=%d", i, chars[i], properties[i].shape, properties[i].justification);
-}
-
-void QTextEngine::shapeTextMac(int item) const
-{
- QScriptItem &si = layoutData->items[item];
-
- si.glyph_data_offset = layoutData->used;
-
- QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
- if (font->type() != QFontEngine::Multi) {
- shapeTextWithHarfbuzz(item);
- return;
- }
-
-#ifndef QT_MAC_USE_COCOA
- QFontEngineMacMulti *fe = static_cast<QFontEngineMacMulti *>(font);
-#else
- QCoreTextFontEngineMulti *fe = static_cast<QCoreTextFontEngineMulti *>(font);
-#endif
- QTextEngine::ShaperFlags flags;
- if (si.analysis.bidiLevel % 2)
- flags |= RightToLeft;
- if (option.useDesignMetrics())
- flags |= DesignMetrics;
-
- attributes(); // pre-initialize char attributes
-
- const int len = length(item);
- int num_glyphs = length(item);
- const QChar *str = layoutData->string.unicode() + si.position;
- ushort upperCased[256];
- if (si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
- || si.analysis.flags == QScriptAnalysis::Lowercase) {
- ushort *uc = upperCased;
- if (len > 256)
- uc = new ushort[len];
- for (int i = 0; i < len; ++i) {
- if(si.analysis.flags == QScriptAnalysis::Lowercase)
- uc[i] = str[i].toLower().unicode();
- else
- uc[i] = str[i].toUpper().unicode();
- }
- str = reinterpret_cast<const QChar *>(uc);
- }
-
- ensureSpace(num_glyphs);
- num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
-
- QGlyphLayout g = availableGlyphs(&si);
- g.numGlyphs = num_glyphs;
- unsigned short *log_clusters = logClusters(&si);
-
- bool stringToCMapFailed = false;
- if (!fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, attributes(), &si)) {
- ensureSpace(num_glyphs);
- g = availableGlyphs(&si);
- stringToCMapFailed = !fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters,
- attributes(), &si);
- }
-
- if (!stringToCMapFailed) {
- heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
-
- si.num_glyphs = num_glyphs;
-
- layoutData->used += si.num_glyphs;
-
- QGlyphLayout g = shapedGlyphs(&si);
-
- if (si.analysis.script == QUnicodeTables::Arabic) {
- QVarLengthArray<QArabicProperties> props(len + 2);
- QArabicProperties *properties = props.data();
- int f = si.position;
- int l = len;
- if (f > 0) {
- --f;
- ++l;
- ++properties;
- }
- if (f + l < layoutData->string.length()) {
- ++l;
- }
- qt_getArabicProperties((const unsigned short *)(layoutData->string.unicode()+f), l, props.data());
-
- unsigned short *log_clusters = logClusters(&si);
-
- for (int i = 0; i < len; ++i) {
- int gpos = log_clusters[i];
- g.attributes[gpos].justification = properties[i].justification;
- }
- }
- }
-
- const ushort *uc = reinterpret_cast<const ushort *>(str);
-
- if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
- || si.analysis.flags == QScriptAnalysis::Lowercase)
- && uc != upperCased)
- delete [] uc;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/mac/qwidget_mac.mm b/src/gui/platforms/mac/qwidget_mac.mm
deleted file mode 100644
index 354f05ba10..0000000000
--- a/src/gui/platforms/mac/qwidget_mac.mm
+++ /dev/null
@@ -1,5420 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qt_mac_p.h>
-#include <private/qeventdispatcher_mac_p.h>
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qfileinfo.h"
-#include "qimage.h"
-#include "qlayout.h"
-#include "qmenubar.h"
-#include <private/qbackingstore_p.h>
-#include <private/qwindowsurface_mac_p.h>
-#include <private/qpaintengine_mac_p.h>
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qtimer.h"
-#include "qfocusframe.h"
-#include "qdebug.h"
-#include <private/qmainwindowlayout_p.h>
-
-#include <private/qabstractscrollarea_p.h>
-#include <qabstractscrollarea.h>
-#include <ApplicationServices/ApplicationServices.h>
-#include <limits.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qcocoaview_mac_p.h>
-#include <private/qcocoawindow_mac_p.h>
-#include <private/qcocoawindowdelegate_mac_p.h>
-#include <private/qcocoapanel_mac_p.h>
-
-#include "qwidget_p.h"
-#include "qevent_p.h"
-#include "qdnd_p.h"
-#include <QtGui/qgraphicsproxywidget.h>
-#include "qmainwindow.h"
-
-QT_BEGIN_NAMESPACE
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-#define XCOORD_MAX 16383
-#define WRECT_MAX 8191
-
-#ifndef QT_MAC_USE_COCOA
-
-extern "C" {
- extern OSStatus _HIViewScrollRectWithOptions(HIViewRef, const HIRect *, CGFloat, CGFloat,
- OptionBits) __attribute__ ((weak));
-}
-#define kHIViewScrollRectAdjustInvalid 1
-#define kHIViewScrollRectDontInvalidateRevealedArea 2
-#endif
-
-
-/*****************************************************************************
- QWidget debug facilities
- *****************************************************************************/
-//#define DEBUG_WINDOW_RGNS
-//#define DEBUG_WINDOW_CREATE
-//#define DEBUG_WINDOW_STATE
-//#define DEBUG_WIDGET_PAINT
-
-/*****************************************************************************
- QWidget globals
- *****************************************************************************/
-#ifndef QT_MAC_USE_COCOA
-typedef QHash<Qt::WindowFlags, WindowGroupRef> WindowGroupHash;
-Q_GLOBAL_STATIC(WindowGroupHash, qt_mac_window_groups)
-const UInt32 kWidgetCreatorQt = kEventClassQt;
-enum {
- kWidgetPropertyQWidget = 'QWId' //QWidget *
-};
-#endif
-
-static bool qt_mac_raise_process = true;
-static OSWindowRef qt_root_win = 0;
-QWidget *mac_mouse_grabber = 0;
-QWidget *mac_keyboard_grabber = 0;
-
-#ifndef QT_MAC_USE_COCOA
-#ifdef QT_NAMESPACE
-
-// produce the string "com.trolltech.qt-namespace.widget", where "namespace" is the contents of QT_NAMESPACE.
-#define SS(x) #x
-#define S0(x) SS(x)
-#define S "com.trolltech.qt-" S0(QT_NAMESPACE) ".widget"
-
-static CFStringRef kObjectQWidget = CFSTR(S);
-
-#undef SS
-#undef S0
-#undef S
-
-#else
-static CFStringRef kObjectQWidget = CFSTR("com.trolltech.qt.widget");
-#endif // QT_NAMESPACE
-#endif // QT_MAC_USE_COCOA
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-extern QWidget *qt_mac_modal_blocked(QWidget *); //qapplication_mac.mm
-extern void qt_event_request_activate(QWidget *); //qapplication_mac.mm
-extern bool qt_event_remove_activate(); //qapplication_mac.mm
-extern void qt_mac_event_release(QWidget *w); //qapplication_mac.mm
-extern void qt_event_request_showsheet(QWidget *); //qapplication_mac.mm
-extern void qt_event_request_window_change(QWidget *); //qapplication_mac.mm
-extern QPointer<QWidget> qt_last_mouse_receiver; //qapplication_mac.mm
-extern QPointer<QWidget> qt_last_native_mouse_receiver; //qt_cocoa_helpers_mac.mm
-extern IconRef qt_mac_create_iconref(const QPixmap &); //qpixmap_mac.cpp
-extern void qt_mac_set_cursor(const QCursor *, const QPoint &); //qcursor_mac.mm
-extern void qt_mac_update_cursor(); //qcursor_mac.mm
-extern bool qt_nograb();
-extern CGImageRef qt_mac_create_cgimage(const QPixmap &, bool); //qpixmap_mac.cpp
-extern RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
-extern QRegion qt_mac_convert_mac_region(RgnHandle rgn); //qregion_mac.cpp
-extern void qt_mac_setMouseGrabCursor(bool set, QCursor *cursor = 0); // qcursor_mac.mm
-extern QPointer<QWidget> topLevelAt_cache; // qapplication_mac.mm
-/*****************************************************************************
- QWidget utility functions
- *****************************************************************************/
-void Q_GUI_EXPORT qt_mac_set_raise_process(bool b) { qt_mac_raise_process = b; }
-static QSize qt_mac_desktopSize()
-{
- int w = 0, h = 0;
- CGDisplayCount cg_count;
- CGGetActiveDisplayList(0, 0, &cg_count);
- QVector<CGDirectDisplayID> displays(cg_count);
- CGGetActiveDisplayList(cg_count, displays.data(), &cg_count);
- Q_ASSERT(cg_count == (CGDisplayCount)displays.size());
- for(int i = 0; i < (int)cg_count; ++i) {
- CGRect r = CGDisplayBounds(displays.at(i));
- w = qMax<int>(w, qRound(r.origin.x + r.size.width));
- h = qMax<int>(h, qRound(r.origin.y + r.size.height));
- }
- return QSize(w, h);
-}
-
-#ifdef QT_MAC_USE_COCOA
-static NSDrawer *qt_mac_drawer_for(const QWidget *widget)
-{
- NSView *widgetView = reinterpret_cast<NSView *>(widget->window()->effectiveWinId());
- NSArray *windows = [NSApp windows];
- for (NSWindow *window in windows) {
- NSArray *drawers = [window drawers];
- for (NSDrawer *drawer in drawers) {
- if ([drawer contentView] == widgetView)
- return drawer;
- }
- }
- return 0;
-}
-#endif
-
-static void qt_mac_destructView(OSViewRef view)
-{
-#ifdef QT_MAC_USE_COCOA
- NSWindow *window = [view window];
- if ([window contentView] == view)
- [window setContentView:[[NSView alloc] initWithFrame:[view bounds]]];
- [view removeFromSuperview];
- [view release];
-#else
- HIViewRemoveFromSuperview(view);
- CFRelease(view);
-#endif
-}
-
-static void qt_mac_destructWindow(OSWindowRef window)
-{
-#ifdef QT_MAC_USE_COCOA
- if ([window isVisible] && [window isSheet]){
- [NSApp endSheet:window];
- [window orderOut:window];
- }
-
- [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForWindow:window];
- [window release];
-#else
- // Remove property to clean up memory:
- RemoveWindowProperty(window, kWidgetCreatorQt, kWidgetPropertyQWidget);
- CFRelease(window);
-#endif
-}
-
-static void qt_mac_destructDrawer(NSDrawer *drawer)
-{
-#ifdef QT_MAC_USE_COCOA
- [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForDrawer:drawer];
- [drawer release];
-#else
- Q_UNUSED(drawer);
-#endif
-}
-
-bool qt_mac_can_clickThrough(const QWidget *w)
-{
- static int qt_mac_carbon_clickthrough = -1;
- if (qt_mac_carbon_clickthrough < 0)
- qt_mac_carbon_clickthrough = !qgetenv("QT_MAC_NO_COCOA_CLICKTHROUGH").isEmpty();
- bool ret = !qt_mac_carbon_clickthrough;
- for ( ; w; w = w->parentWidget()) {
- if (w->testAttribute(Qt::WA_MacNoClickThrough)) {
- ret = false;
- break;
- }
- }
- return ret;
-}
-
-bool qt_mac_is_macsheet(const QWidget *w)
-{
- if (!w)
- return false;
-
- Qt::WindowModality modality = w->windowModality();
- if (modality == Qt::ApplicationModal)
- return false;
- return w->parentWidget() && (modality == Qt::WindowModal || w->windowType() == Qt::Sheet);
-}
-
-bool qt_mac_is_macdrawer(const QWidget *w)
-{
- return (w && w->parentWidget() && w->windowType() == Qt::Drawer);
-}
-
-bool qt_mac_insideKeyWindow(const QWidget *w)
-{
-#ifdef QT_MAC_USE_COCOA
- return [[reinterpret_cast<NSView *>(w->effectiveWinId()) window] isKeyWindow];
-#else
- Q_UNUSED(w);
-#endif
- return false;
-}
-
-bool qt_mac_set_drawer_preferred_edge(QWidget *w, Qt::DockWidgetArea where) //users of Qt for Mac OS X can use this..
-{
- if(!qt_mac_is_macdrawer(w))
- return false;
-
-#if QT_MAC_USE_COCOA
- NSDrawer *drawer = qt_mac_drawer_for(w);
- if (!drawer)
- return false;
- NSRectEdge edge;
- if (where & Qt::LeftDockWidgetArea)
- edge = NSMinXEdge;
- else if (where & Qt::RightDockWidgetArea)
- edge = NSMaxXEdge;
- else if (where & Qt::TopDockWidgetArea)
- edge = NSMaxYEdge;
- else if (where & Qt::BottomDockWidgetArea)
- edge = NSMinYEdge;
- else
- return false;
-
- if (edge == [drawer preferredEdge]) //no-op
- return false;
-
- if (w->isVisible()) {
- [drawer close];
- [drawer openOnEdge:edge];
- }
- [drawer setPreferredEdge:edge];
-#else
- OSWindowRef window = qt_mac_window_for(w);
- OptionBits edge;
- if(where & Qt::LeftDockWidgetArea)
- edge = kWindowEdgeLeft;
- else if(where & Qt::RightDockWidgetArea)
- edge = kWindowEdgeRight;
- else if(where & Qt::TopDockWidgetArea)
- edge = kWindowEdgeTop;
- else if(where & Qt::BottomDockWidgetArea)
- edge = kWindowEdgeBottom;
- else
- return false;
-
- if(edge == GetDrawerPreferredEdge(window)) //no-op
- return false;
-
- //do it
- SetDrawerPreferredEdge(window, edge);
- if(w->isVisible()) {
- CloseDrawer(window, false);
- OpenDrawer(window, edge, true);
- }
-#endif
- return true;
-}
-
-#ifndef QT_MAC_USE_COCOA
-Q_GUI_EXPORT
-#endif
-QPoint qt_mac_posInWindow(const QWidget *w)
-{
- QPoint ret = w->data->wrect.topLeft();
- while(w && !w->isWindow()) {
- ret += w->pos();
- w = w->parentWidget();
- }
- return ret;
-}
-
-//find a QWidget from a OSWindowRef
-QWidget *qt_mac_find_window(OSWindowRef window)
-{
-#ifdef QT_MAC_USE_COCOA
- return [window QT_MANGLE_NAMESPACE(qt_qwidget)];
-#else
- if(!window)
- return 0;
-
- QWidget *ret;
- if(GetWindowProperty(window, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(ret), 0, &ret) == noErr)
- return ret;
- return 0;
-#endif
-}
-
-inline static void qt_mac_set_fullscreen_mode(bool b)
-{
- extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
- if(qt_mac_app_fullscreen == b)
- return;
- qt_mac_app_fullscreen = b;
- if (b) {
- SetSystemUIMode(kUIModeAllHidden, kUIOptionAutoShowMenuBar);
- } else {
- SetSystemUIMode(kUIModeNormal, 0);
- }
-}
-
-Q_GUI_EXPORT OSViewRef qt_mac_nativeview_for(const QWidget *w)
-{
- return reinterpret_cast<OSViewRef>(w->internalWinId());
-}
-
-Q_GUI_EXPORT OSViewRef qt_mac_effectiveview_for(const QWidget *w)
-{
- // Get the first non-alien (parent) widget for
- // w, and return its NSView (if it has one):
- return reinterpret_cast<OSViewRef>(w->effectiveWinId());
-}
-
-Q_GUI_EXPORT OSViewRef qt_mac_get_contentview_for(OSWindowRef w)
-{
-#ifdef QT_MAC_USE_COCOA
- return [w contentView];
-#else
- HIViewRef contentView = 0;
- OSStatus err = GetRootControl(w, &contentView); // Returns the window's content view (Apple QA1214)
- if (err == errUnknownControl) {
- contentView = HIViewGetRoot(w);
- } else if (err != noErr) {
- qWarning("Qt:Could not get content or root view of window! %s:%d [%ld]",
- __FILE__, __LINE__, err);
- }
- return contentView;
-#endif
-}
-
-bool qt_mac_sendMacEventToWidget(QWidget *widget, EventRef ref)
-{
- return widget->macEvent(0, ref);
-}
-
-Q_GUI_EXPORT OSWindowRef qt_mac_window_for(OSViewRef view)
-{
-#ifdef QT_MAC_USE_COCOA
- if (view)
- return [view window];
- return 0;
-#else
- return HIViewGetWindow(view);
-#endif
-}
-
-static bool qt_isGenuineQWidget(OSViewRef ref)
-{
-#ifdef QT_MAC_USE_COCOA
- return [ref isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]];
-#else
- return HIObjectIsOfClass(HIObjectRef(ref), kObjectQWidget);
-#endif
-}
-
-bool qt_isGenuineQWidget(const QWidget *window)
-{
- if (!window)
- return false;
-
- if (!window->internalWinId())
- return true; //alien
-
- return qt_isGenuineQWidget(OSViewRef(window->internalWinId()));
-}
-
-Q_GUI_EXPORT OSWindowRef qt_mac_window_for(const QWidget *w)
-{
- if (OSViewRef hiview = qt_mac_effectiveview_for(w)) {
- OSWindowRef window = qt_mac_window_for(hiview);
- if (window)
- return window;
-
- if (qt_isGenuineQWidget(hiview)) {
- // This is a workaround for NSToolbar. When a widget is hidden
- // by clicking the toolbar button, Cocoa reparents the widgets
- // to another window (but Qt doesn't know about it).
- // When we start showing them, it reparents back,
- // but at this point it's window is nil, but the window it's being brought
- // into (the Qt one) is for sure created.
- // This stops the hierarchy moving under our feet.
- QWidget *toplevel = w->window();
- if (toplevel != w) {
- hiview = qt_mac_nativeview_for(toplevel);
- if (OSWindowRef w = qt_mac_window_for(hiview))
- return w;
- }
-
- toplevel->d_func()->createWindow_sys();
- // Reget the hiview since "create window" could potentially move the view (I guess).
- hiview = qt_mac_nativeview_for(toplevel);
- return qt_mac_window_for(hiview);
- }
- }
- return 0;
-}
-
-#ifndef QT_MAC_USE_COCOA
-/* Checks if the current group is a 'stay on top' group. If so, the
- group gets removed from the hash table */
-static void qt_mac_release_stays_on_top_group(WindowGroupRef group)
-{
- for (WindowGroupHash::iterator it = qt_mac_window_groups()->begin(); it != qt_mac_window_groups()->end(); ++it) {
- if (it.value() == group) {
- qt_mac_window_groups()->remove(it.key());
- return;
- }
- }
-}
-
-/* Use this function instead of ReleaseWindowGroup, this will be sure to release the
- stays on top window group (created with qt_mac_get_stays_on_top_group below) */
-static void qt_mac_release_window_group(WindowGroupRef group)
-{
- ReleaseWindowGroup(group);
- if (GetWindowGroupRetainCount(group) == 0)
- qt_mac_release_stays_on_top_group(group);
-}
-#define ReleaseWindowGroup(x) Are you sure you wanted to do that? (you wanted qt_mac_release_window_group)
-
-SInt32 qt_mac_get_group_level(WindowClass wclass)
-{
- SInt32 group_level;
- CGWindowLevel tmpLevel;
- GetWindowGroupLevelOfType(GetWindowGroupOfClass(wclass), kWindowGroupLevelActive, &tmpLevel);
- group_level = tmpLevel;
- return group_level;
-}
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-static void qt_mac_set_window_group(OSWindowRef window, Qt::WindowFlags flags, int level)
-{
- WindowGroupRef group = 0;
- if (qt_mac_window_groups()->contains(flags)) {
- group = qt_mac_window_groups()->value(flags);
- RetainWindowGroup(group);
- } else {
- CreateWindowGroup(kWindowActivationScopeNone, &group);
- SetWindowGroupLevel(group, level);
- SetWindowGroupParent(group, GetWindowGroupOfClass(kAllWindowClasses));
- qt_mac_window_groups()->insert(flags, group);
- }
- SetWindowGroup(window, group);
-}
-
-inline static void qt_mac_set_window_group_to_stays_on_top(OSWindowRef window, Qt::WindowType type)
-{
- // We create one static stays on top window group so that
- // all stays on top (aka popups) will fall into the same
- // group and be able to be raise()'d with releation to one another (from
- // within the same window group).
- qt_mac_set_window_group(window, type|Qt::WindowStaysOnTopHint, qt_mac_get_group_level(kOverlayWindowClass));
-}
-
-inline static void qt_mac_set_window_group_to_tooltip(OSWindowRef window)
-{
- // Since new groups are created for 'stays on top' windows, the
- // same must be done for tooltips. Otherwise, tooltips would be drawn
- // below 'stays on top' widgets even tough they are on the same level.
- // Also, add 'two' to the group level to make sure they also get on top of popups.
- qt_mac_set_window_group(window, Qt::ToolTip, qt_mac_get_group_level(kHelpWindowClass)+2);
-}
-
-inline static void qt_mac_set_window_group_to_popup(OSWindowRef window)
-{
- // In Qt, a popup is seen as a 'stay on top' window.
- // Since new groups are created for 'stays on top' windows, the
- // same must be done for popups. Otherwise, popups would be drawn
- // below 'stays on top' windows. Add 1 to get above pure stay-on-top windows.
- qt_mac_set_window_group(window, Qt::Popup, qt_mac_get_group_level(kOverlayWindowClass)+1);
-}
-#endif
-
-inline static bool updateRedirectedToGraphicsProxyWidget(QWidget *widget, const QRect &rect)
-{
- if (!widget)
- return false;
-
-#ifndef QT_NO_GRAPHICSVIEW
- QWidget *tlw = widget->window();
- QWExtra *extra = qt_widget_private(tlw)->extra;
- if (extra && extra->proxyWidget) {
- extra->proxyWidget->update(rect.translated(widget->mapTo(tlw, QPoint())));
- return true;
- }
-#endif
-
- return false;
-}
-
-inline static bool updateRedirectedToGraphicsProxyWidget(QWidget *widget, const QRegion &rgn)
-{
- if (!widget)
- return false;
-
-#ifndef QT_NO_GRAPHICSVIEW
- QWidget *tlw = widget->window();
- QWExtra *extra = qt_widget_private(tlw)->extra;
- if (extra && extra->proxyWidget) {
- const QPoint offset(widget->mapTo(tlw, QPoint()));
- const QVector<QRect> rects = rgn.rects();
- for (int i = 0; i < rects.size(); ++i)
- extra->proxyWidget->update(rects.at(i).translated(offset));
- return true;
- }
-#endif
-
- return false;
-}
-
-void QWidgetPrivate::macSetNeedsDisplay(QRegion region)
-{
- Q_Q(QWidget);
-#ifndef QT_MAC_USE_COCOA
- if (region.isEmpty())
- HIViewSetNeedsDisplay(qt_mac_nativeview_for(q), true);
- else if (RgnHandle rgnHandle = region.toQDRgnForUpdate_sys())
- HIViewSetNeedsDisplayInRegion(qt_mac_nativeview_for(q), QMacSmartQuickDrawRegion(rgnHandle), true);
- else
- HIViewSetNeedsDisplay(qt_mac_nativeview_for(q), true); // do a complete repaint on overflow.
-#else
- if (NSView *nativeView = qt_mac_nativeview_for(q)) {
- // INVARIANT: q is _not_ alien. So we can optimize a little:
- if (region.isEmpty()) {
- [nativeView setNeedsDisplay:YES];
- } else {
- QVector<QRect> rects = region.rects();
- for (int i = 0; i<rects.count(); ++i) {
- const QRect &rect = rects.at(i);
- NSRect nsrect = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
- [nativeView setNeedsDisplayInRect:nsrect];
- }
- }
- } else if (QWidget *effectiveWidget = q->nativeParentWidget()) {
- // INVARIANT: q is alien, and effectiveWidget is native.
- if (NSView *effectiveView = qt_mac_nativeview_for(effectiveWidget)) {
- if (region.isEmpty()) {
- const QRect &rect = q->rect();
- QPoint p = q->mapTo(effectiveWidget, rect.topLeft());
- NSRect nsrect = NSMakeRect(p.x(), p.y(), rect.width(), rect.height());
- [effectiveView setNeedsDisplayInRect:nsrect];
- } else {
- QVector<QRect> rects = region.rects();
- for (int i = 0; i<rects.count(); ++i) {
- const QRect &rect = rects.at(i);
- QPoint p = q->mapTo(effectiveWidget, rect.topLeft());
- NSRect nsrect = NSMakeRect(p.x(), p.y(), rect.width(), rect.height());
- [effectiveView setNeedsDisplayInRect:nsrect];
- }
- }
- }
- }
-#endif
-}
-
-void QWidgetPrivate::macUpdateIsOpaque()
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-#ifndef QT_MAC_USE_COCOA
- HIViewFeatures bits;
- HIViewRef hiview = qt_mac_nativeview_for(q);
- HIViewGetFeatures(hiview, &bits);
- if ((bits & kHIViewIsOpaque) == isOpaque)
- return;
- if (isOpaque) {
- HIViewChangeFeatures(hiview, kHIViewIsOpaque, 0);
- } else {
- HIViewChangeFeatures(hiview, 0, kHIViewIsOpaque);
- }
- if (q->isVisible())
- HIViewReshapeStructure(qt_mac_nativeview_for(q));
-#else
- if (isRealWindow() && !q->testAttribute(Qt::WA_MacBrushedMetal)) {
- bool opaque = isOpaque;
- if (extra && extra->imageMask)
- opaque = false; // we are never opaque when we have a mask.
- [qt_mac_window_for(q) setOpaque:opaque];
- }
-#endif
-}
-#ifdef QT_MAC_USE_COCOA
-static OSWindowRef qt_mac_create_window(QWidget *widget, WindowClass wclass,
- NSUInteger wattr, const QRect &crect)
-{
- // Determine if we need to add in our "custom window" attribute. Cocoa is rather clever
- // in deciding if we need the maximize button or not (i.e., it's resizeable, so you
- // must need a maximize button). So, the only buttons we have control over are the
- // close and minimize buttons. If someone wants to customize and NOT have the maximize
- // button, then we have to do our hack. We only do it for these cases because otherwise
- // the window looks different when activated. This "QtMacCustomizeWindow" attribute is
- // intruding on a public space and WILL BREAK in the future.
- // One can hope that there is a more public API available by that time.
- Qt::WindowFlags flags = widget ? widget->windowFlags() : Qt::WindowFlags(0);
- if ((flags & Qt::CustomizeWindowHint)) {
- if ((flags & (Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint
- | Qt::WindowMinimizeButtonHint | Qt::WindowTitleHint))
- && !(flags & Qt::WindowMaximizeButtonHint))
- wattr |= QtMacCustomizeWindow;
- }
-
- // If we haven't created the desktop widget, you have to pass the rectangle
- // in "cocoa coordinates" (i.e., top points to the lower left coordinate).
- // Otherwise, we do the conversion for you. Since we are the only ones that
- // create the desktop widget, this is OK (but confusing).
- NSRect geo = NSMakeRect(crect.left(),
- (qt_root_win != 0) ? flipYCoordinate(crect.bottom() + 1) : crect.top(),
- crect.width(), crect.height());
- QMacCocoaAutoReleasePool pool;
- OSWindowRef window;
- switch (wclass) {
- case kMovableModalWindowClass:
- case kModalWindowClass:
- case kSheetWindowClass:
- case kFloatingWindowClass:
- case kOverlayWindowClass:
- case kHelpWindowClass: {
- NSPanel *panel;
- BOOL needFloating = NO;
- BOOL worksWhenModal = widget && (widget->windowType() == Qt::Popup);
- // Add in the extra flags if necessary.
- switch (wclass) {
- case kSheetWindowClass:
- wattr |= NSDocModalWindowMask;
- break;
- case kFloatingWindowClass:
- case kHelpWindowClass:
- needFloating = YES;
- wattr |= NSUtilityWindowMask;
- break;
- default:
- break;
- }
- panel = [[QT_MANGLE_NAMESPACE(QCocoaPanel) alloc] QT_MANGLE_NAMESPACE(qt_initWithQWidget):widget contentRect:geo styleMask:wattr];
- [panel setFloatingPanel:needFloating];
- [panel setWorksWhenModal:worksWhenModal];
- window = panel;
- break;
- }
- case kDrawerWindowClass: {
- NSDrawer *drawer = [[NSDrawer alloc] initWithContentSize:geo.size preferredEdge:NSMinXEdge];
- [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] becomeDelegateForDrawer:drawer widget:widget];
- QWidget *parentWidget = widget->parentWidget();
- if (parentWidget)
- [drawer setParentWindow:qt_mac_window_for(parentWidget)];
- [drawer setLeadingOffset:0.0];
- [drawer setTrailingOffset:25.0];
- window = [[drawer contentView] window]; // Just to make sure we actually return a window
- break;
- }
- default:
- window = [[QT_MANGLE_NAMESPACE(QCocoaWindow) alloc] QT_MANGLE_NAMESPACE(qt_initWithQWidget):widget contentRect:geo styleMask:wattr];
- break;
- }
- qt_syncCocoaTitleBarButtons(window, widget);
- return window;
-}
-#else
-static OSWindowRef qt_mac_create_window(QWidget *, WindowClass wclass, WindowAttributes wattr,
- const QRect &crect)
-{
- OSWindowRef window;
- Rect geo;
- SetRect(&geo, crect.left(), crect.top(), crect.right() + 1, crect.bottom() + 1);
- OSStatus err;
- if(geo.right <= geo.left) geo.right = geo.left + 1;
- if(geo.bottom <= geo.top) geo.bottom = geo.top + 1;
- Rect null_rect;
- SetRect(&null_rect, 0, 0, 1, 1);
- err = CreateNewWindow(wclass, wattr, &null_rect, &window);
- if(err == noErr) {
- err = SetWindowBounds(window, kWindowContentRgn, &geo);
- if(err != noErr)
- qWarning("QWidget: Internal error (%s:%d)", __FILE__, __LINE__);
- }
- return window;
-}
-
-#ifndef QT_NO_GESTURES
-#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
-/* We build the release package against the 10.4 SDK.
- So, to enable gestures for applications running on
- 10.6+, we define the missing constants here: */
-enum {
- kEventClassGesture = 'gest',
- kEventGestureStarted = 1,
- kEventGestureEnded = 2,
- kEventGestureMagnify = 4,
- kEventGestureSwipe = 5,
- kEventGestureRotate = 6,
- kEventParamRotationAmount = 'rota',
- kEventParamSwipeDirection = 'swip',
- kEventParamMagnificationAmount = 'magn'
-};
-#endif
-#endif // QT_NO_GESTURES
-
-// window events
-static EventTypeSpec window_events[] = {
- { kEventClassWindow, kEventWindowClose },
- { kEventClassWindow, kEventWindowExpanded },
- { kEventClassWindow, kEventWindowHidden },
- { kEventClassWindow, kEventWindowZoom },
- { kEventClassWindow, kEventWindowZoomed },
- { kEventClassWindow, kEventWindowCollapsed },
- { kEventClassWindow, kEventWindowToolbarSwitchMode },
- { kEventClassWindow, kEventWindowProxyBeginDrag },
- { kEventClassWindow, kEventWindowProxyEndDrag },
- { kEventClassWindow, kEventWindowResizeCompleted },
- { kEventClassWindow, kEventWindowBoundsChanging },
- { kEventClassWindow, kEventWindowGetRegion },
- { kEventClassWindow, kEventWindowGetClickModality },
- { kEventClassWindow, kEventWindowTransitionCompleted },
- { kEventClassGesture, kEventGestureStarted },
- { kEventClassGesture, kEventGestureEnded },
- { kEventClassGesture, kEventGestureMagnify },
- { kEventClassGesture, kEventGestureSwipe },
- { kEventClassGesture, kEventGestureRotate },
- { kEventClassMouse, kEventMouseDown }
-};
-static EventHandlerUPP mac_win_eventUPP = 0;
-static void cleanup_win_eventUPP()
-{
- DisposeEventHandlerUPP(mac_win_eventUPP);
- mac_win_eventUPP = 0;
-}
-static const EventHandlerUPP make_win_eventUPP()
-{
- if(mac_win_eventUPP)
- return mac_win_eventUPP;
- qAddPostRoutine(cleanup_win_eventUPP);
- return mac_win_eventUPP = NewEventHandlerUPP(QWidgetPrivate::qt_window_event);
-}
-OSStatus QWidgetPrivate::qt_window_event(EventHandlerCallRef er, EventRef event, void *)
-{
- QScopedLoopLevelCounter loopLevelCounter(qApp->d_func()->threadData);
- bool handled_event = true;
- UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
- switch(eclass) {
- case kEventClassWindow: {
- WindowRef wid = 0;
- GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
- sizeof(WindowRef), 0, &wid);
- QWidget *widget = qt_mac_find_window(wid);
- if(!widget) {
- handled_event = false;
- } else if(ekind == kEventWindowGetClickModality) {
- // Carbon will send us kEventWindowGetClickModality before every
- // mouse press / release event. By returning 'true', we tell Carbon
- // that we would like the event target to receive the mouse event even
- // if the target is modally shaddowed. In Qt, this makes sense when we
- // e.g. have a popup showing, as the popup will grab the event
- // and perhaps use it to close itself.
- // By also setting the current modal window back into the event, we
- // help Carbon determining which window is supposed to be raised.
- handled_event = qApp->activePopupWidget() ? true : false;
- } else if(ekind == kEventWindowClose) {
- widget->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
- QMenuBar::macUpdateMenuBar();
- } else if (ekind == kEventWindowTransitionCompleted) {
- WindowTransitionAction transitionAction;
- GetEventParameter(event, kEventParamWindowTransitionAction, typeWindowTransitionAction,
- 0, sizeof(transitionAction), 0, &transitionAction);
- if (transitionAction == kWindowHideTransitionAction)
- widget->hide();
- } else if(ekind == kEventWindowExpanded) {
- Qt::WindowStates currState = Qt::WindowStates(widget->data->window_state);
- Qt::WindowStates newState = currState;
- if (currState & Qt::WindowMinimized)
- newState &= ~Qt::WindowMinimized;
- if (!(currState & Qt::WindowActive))
- newState |= Qt::WindowActive;
- if (newState != currState) {
- // newState will differ from currState if the window
- // was expanded after clicking on the jewels (as opposed
- // to calling QWidget::setWindowState)
- widget->data->window_state = newState;
- QWindowStateChangeEvent e(currState);
- QApplication::sendSpontaneousEvent(widget, &e);
- }
-
- QShowEvent qse;
- QApplication::sendSpontaneousEvent(widget, &qse);
- } else if(ekind == kEventWindowZoom) {
- widget->d_func()->topData()->normalGeometry = widget->geometry();
- handled_event = false;
- } else if(ekind == kEventWindowZoomed) {
- WindowPartCode windowPart;
- GetEventParameter(event, kEventParamWindowPartCode,
- typeWindowPartCode, 0, sizeof(windowPart), 0, &windowPart);
- if(windowPart == inZoomIn && widget->isMaximized()) {
-
- widget->data->window_state = widget->data->window_state & ~Qt::WindowMaximized;
- QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state | Qt::WindowMaximized));
- QApplication::sendSpontaneousEvent(widget, &e);
- } else if(windowPart == inZoomOut && !widget->isMaximized()) {
- widget->data->window_state = widget->data->window_state | Qt::WindowMaximized;
- QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state
- & ~Qt::WindowMaximized));
- QApplication::sendSpontaneousEvent(widget, &e);
- }
- qt_button_down = 0;
- } else if(ekind == kEventWindowCollapsed) {
- if (!widget->isMinimized()) {
- widget->data->window_state = widget->data->window_state | Qt::WindowMinimized;
- QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state & ~Qt::WindowMinimized));
- QApplication::sendSpontaneousEvent(widget, &e);
- }
-
- // Deactivate this window:
- if (widget->isActiveWindow() && !(widget->windowType() == Qt::Popup)) {
- QWidget *w = 0;
- if (widget->parentWidget())
- w = widget->parentWidget()->window();
- if (!w || (!w->isVisible() && !w->isMinimized())) {
- for (WindowPtr wp = GetFrontWindowOfClass(kDocumentWindowClass, true);
- wp; wp = GetNextWindowOfClass(wp, kDocumentWindowClass, true)) {
- if ((w = qt_mac_find_window(wp)))
- break;
- }
- }
- if(!(w && w->isVisible() && !w->isMinimized()))
- qApp->setActiveWindow(0);
- }
-
- //we send a hide to be like X11/Windows
- QEvent e(QEvent::Hide);
- QApplication::sendSpontaneousEvent(widget, &e);
- qt_button_down = 0;
- } else if(ekind == kEventWindowToolbarSwitchMode) {
- macSendToolbarChangeEvent(widget);
- HIToolbarRef toolbar;
- if (GetWindowToolbar(wid, &toolbar) == noErr) {
- if (toolbar) {
- // Let HIToolbar do its thang, but things like the OpenGL context
- // needs to know about it.
- CallNextEventHandler(er, event);
- qt_event_request_window_change(widget);
- widget->data->fstrut_dirty = true;
- }
- }
- } else if(ekind == kEventWindowGetRegion) {
- WindowRef window;
- GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
- sizeof(window), 0, &window);
- WindowRegionCode wcode;
- GetEventParameter(event, kEventParamWindowRegionCode, typeWindowRegionCode, 0,
- sizeof(wcode), 0, &wcode);
- if (wcode != kWindowOpaqueRgn){
- // If the region is kWindowOpaqueRgn, don't call next
- // event handler cause this will make the shadow of
- // masked windows become offset. Unfortunately, we're not sure why.
- CallNextEventHandler(er, event);
- }
- RgnHandle rgn;
- GetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, 0,
- sizeof(rgn), 0, &rgn);
-
- if(QWidgetPrivate::qt_widget_rgn(qt_mac_find_window(window), wcode, rgn, false))
- SetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, sizeof(rgn), &rgn);
- } else if(ekind == kEventWindowProxyBeginDrag) {
- QIconDragEvent e;
- QApplication::sendSpontaneousEvent(widget, &e);
- } else if(ekind == kEventWindowResizeCompleted) {
- // Create a mouse up event, since such an event is not send by carbon to the
- // application event handler (while a mouse down <b>is</b> on kEventWindowResizeStarted)
- EventRef mouseUpEvent;
- CreateEvent(0, kEventClassMouse, kEventMouseUp, 0, kEventAttributeUserEvent, &mouseUpEvent);
- UInt16 mbutton = kEventMouseButtonPrimary;
- SetEventParameter(mouseUpEvent, kEventParamMouseButton, typeMouseButton, sizeof(mbutton), &mbutton);
- WindowRef window;
- GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0, sizeof(window), 0, &window);
- Rect dragRect;
- GetWindowBounds(window, kWindowGrowRgn, &dragRect);
- Point pos = {dragRect.bottom, dragRect.right};
- SetEventParameter(mouseUpEvent, kEventParamMouseLocation, typeQDPoint, sizeof(pos), &pos);
- SendEventToApplication(mouseUpEvent);
- ReleaseEvent(mouseUpEvent);
- } else if(ekind == kEventWindowBoundsChanging) {
- UInt32 flags = 0;
- GetEventParameter(event, kEventParamAttributes, typeUInt32, 0,
- sizeof(flags), 0, &flags);
- Rect nr;
- GetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle, 0,
- sizeof(nr), 0, &nr);
-
- QRect newRect(nr.left, nr.top, nr.right - nr.left, nr.bottom - nr.top);
-
- QTLWExtra * const tlwExtra = widget->d_func()->maybeTopData();
- if (tlwExtra && tlwExtra->isSetGeometry == 1) {
- widget->d_func()->setGeometry_sys_helper(newRect.left(), newRect.top(), newRect.width(), newRect.height(), tlwExtra->isMove);
- } else {
- //implicitly removes the maximized bit
- if((widget->data->window_state & Qt::WindowMaximized) &&
- IsWindowInStandardState(wid, 0, 0)) {
- widget->data->window_state &= ~Qt::WindowMaximized;
- QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state
- | Qt::WindowMaximized));
- QApplication::sendSpontaneousEvent(widget, &e);
-
- }
-
- handled_event = false;
- const QRect oldRect = widget->data->crect;
- if((flags & kWindowBoundsChangeOriginChanged)) {
- if(nr.left != oldRect.x() || nr.top != oldRect.y()) {
- widget->data->crect.moveTo(nr.left, nr.top);
- QMoveEvent qme(widget->data->crect.topLeft(), oldRect.topLeft());
- QApplication::sendSpontaneousEvent(widget, &qme);
- }
- }
- if((flags & kWindowBoundsChangeSizeChanged)) {
- if (widget->isWindow()) {
- QSize newSize = QLayout::closestAcceptableSize(widget, newRect.size());
- int dh = newSize.height() - newRect.height();
- int dw = newSize.width() - newRect.width();
- if (dw != 0 || dh != 0) {
- handled_event = true; // We want to change the bounds, so we handle the event
-
- // set the rect, so we can also do the resize down below (yes, we need to resize).
- newRect.setBottom(newRect.bottom() + dh);
- newRect.setRight(newRect.right() + dw);
-
- nr.left = newRect.x();
- nr.top = newRect.y();
- nr.right = nr.left + newRect.width();
- nr.bottom = nr.top + newRect.height();
- SetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle, sizeof(Rect), &nr);
- }
- }
-
- if (oldRect.width() != newRect.width() || oldRect.height() != newRect.height()) {
- widget->data->crect.setSize(newRect.size());
- HIRect bounds = CGRectMake(0, 0, newRect.width(), newRect.height());
-
- // If the WA_StaticContents attribute is set we can optimize the resize
- // by only repainting the newly exposed area. We do this by disabling
- // painting when setting the size of the view. The OS will invalidate
- // the newly exposed area for us.
- const bool staticContents = widget->testAttribute(Qt::WA_StaticContents);
- const HIViewRef view = qt_mac_nativeview_for(widget);
- if (staticContents)
- HIViewSetDrawingEnabled(view, false);
- HIViewSetFrame(view, &bounds);
- if (staticContents)
- HIViewSetDrawingEnabled(view, true);
-
- QResizeEvent qre(newRect.size(), oldRect.size());
- QApplication::sendSpontaneousEvent(widget, &qre);
- qt_event_request_window_change(widget);
- }
- }
- }
- } else if (ekind == kEventWindowHidden) {
- // Make sure that we also hide any visible sheets on our window.
- // Cocoa does the right thing for us.
- const QObjectList children = widget->children();
- const int childCount = children.count();
- for (int i = 0; i < childCount; ++i) {
- QObject *obj = children.at(i);
- if (obj->isWidgetType()) {
- QWidget *widget = static_cast<QWidget *>(obj);
- if (qt_mac_is_macsheet(widget) && widget->isVisible())
- widget->hide();
- }
- }
- } else {
- handled_event = false;
- }
- break; }
- case kEventClassMouse: {
-#if 0
- return SendEventToApplication(event);
-#endif
-
- bool send_to_app = false;
- {
- WindowPartCode wpc;
- if (GetEventParameter(event, kEventParamWindowPartCode, typeWindowPartCode, 0,
- sizeof(wpc), 0, &wpc) == noErr && wpc != inContent)
- send_to_app = true;
- }
- if(!send_to_app) {
- WindowRef window;
- if(GetEventParameter(event, kEventParamWindowRef, typeWindowRef, 0,
- sizeof(window), 0, &window) == noErr) {
- HIViewRef hiview;
- if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) {
- if(QWidget *w = QWidget::find((WId)hiview)) {
-#if 0
- send_to_app = !w->isActiveWindow();
-#else
- Q_UNUSED(w);
- send_to_app = true;
-#endif
- }
- }
- }
- }
- if(send_to_app)
- return SendEventToApplication(event);
- handled_event = false;
- break; }
-
-#ifndef QT_NO_GESTURES
- case kEventClassGesture: {
- // First, find the widget that was under
- // the mouse when the gesture happened:
- HIPoint screenLocation;
- if (GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, 0,
- sizeof(screenLocation), 0, &screenLocation) != noErr) {
- handled_event = false;
- break;
- }
- QWidget *widget = QApplication::widgetAt(screenLocation.x, screenLocation.y);
- if (!widget) {
- handled_event = false;
- break;
- }
-
- QNativeGestureEvent qNGEvent;
- qNGEvent.position = QPoint(screenLocation.x, screenLocation.y);
-
- switch (ekind) {
- case kEventGestureStarted:
- qNGEvent.gestureType = QNativeGestureEvent::GestureBegin;
- break;
- case kEventGestureEnded:
- qNGEvent.gestureType = QNativeGestureEvent::GestureEnd;
- break;
- case kEventGestureRotate: {
- CGFloat amount;
- if (GetEventParameter(event, kEventParamRotationAmount, 'cgfl', 0,
- sizeof(amount), 0, &amount) != noErr) {
- handled_event = false;
- break;
- }
- qNGEvent.gestureType = QNativeGestureEvent::Rotate;
- qNGEvent.percentage = float(-amount);
- break; }
- case kEventGestureSwipe: {
- HIPoint swipeDirection;
- if (GetEventParameter(event, kEventParamSwipeDirection, typeHIPoint, 0,
- sizeof(swipeDirection), 0, &swipeDirection) != noErr) {
- handled_event = false;
- break;
- }
- qNGEvent.gestureType = QNativeGestureEvent::Swipe;
- if (swipeDirection.x == 1)
- qNGEvent.angle = 180.0f;
- else if (swipeDirection.x == -1)
- qNGEvent.angle = 0.0f;
- else if (swipeDirection.y == 1)
- qNGEvent.angle = 90.0f;
- else if (swipeDirection.y == -1)
- qNGEvent.angle = 270.0f;
- break; }
- case kEventGestureMagnify: {
- CGFloat amount;
- if (GetEventParameter(event, kEventParamMagnificationAmount, 'cgfl', 0,
- sizeof(amount), 0, &amount) != noErr) {
- handled_event = false;
- break;
- }
- qNGEvent.gestureType = QNativeGestureEvent::Zoom;
- qNGEvent.percentage = float(amount);
- break; }
- }
-
- QApplication::sendSpontaneousEvent(widget, &qNGEvent);
- break; }
-#endif // QT_NO_GESTURES
-
- default:
- handled_event = false;
- }
- if(!handled_event) //let the event go through
- return eventNotHandledErr;
- return noErr; //we eat the event
-}
-
-// widget events
-static HIObjectClassRef widget_class = 0;
-static EventTypeSpec widget_events[] = {
- { kEventClassHIObject, kEventHIObjectConstruct },
- { kEventClassHIObject, kEventHIObjectDestruct },
-
- { kEventClassControl, kEventControlDraw },
- { kEventClassControl, kEventControlInitialize },
- { kEventClassControl, kEventControlGetPartRegion },
- { kEventClassControl, kEventControlGetClickActivation },
- { kEventClassControl, kEventControlSetFocusPart },
- { kEventClassControl, kEventControlDragEnter },
- { kEventClassControl, kEventControlDragWithin },
- { kEventClassControl, kEventControlDragLeave },
- { kEventClassControl, kEventControlDragReceive },
- { kEventClassControl, kEventControlOwningWindowChanged },
- { kEventClassControl, kEventControlBoundsChanged },
- { kEventClassControl, kEventControlGetSizeConstraints },
- { kEventClassControl, kEventControlVisibilityChanged },
-
- { kEventClassMouse, kEventMouseDown },
- { kEventClassMouse, kEventMouseUp },
- { kEventClassMouse, kEventMouseMoved },
- { kEventClassMouse, kEventMouseDragged }
-};
-static EventHandlerUPP mac_widget_eventUPP = 0;
-static void cleanup_widget_eventUPP()
-{
- DisposeEventHandlerUPP(mac_widget_eventUPP);
- mac_widget_eventUPP = 0;
-}
-static const EventHandlerUPP make_widget_eventUPP()
-{
- if(mac_widget_eventUPP)
- return mac_widget_eventUPP;
- qAddPostRoutine(cleanup_widget_eventUPP);
- return mac_widget_eventUPP = NewEventHandlerUPP(QWidgetPrivate::qt_widget_event);
-}
-OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, void *)
-{
- QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-
- bool handled_event = true;
- UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
- switch(eclass) {
- case kEventClassHIObject: {
- HIViewRef view = 0;
- GetEventParameter(event, kEventParamHIObjectInstance, typeHIObjectRef,
- 0, sizeof(view), 0, &view);
- if(ekind == kEventHIObjectConstruct) {
- if(view) {
- HIViewChangeFeatures(view, kHIViewAllowsSubviews, 0);
- SetEventParameter(event, kEventParamHIObjectInstance,
- typeVoidPtr, sizeof(view), &view);
- }
- } else if(ekind == kEventHIObjectDestruct) {
- //nothing to really do.. or is there?
- } else {
- handled_event = false;
- }
- break; }
- case kEventClassControl: {
- QWidget *widget = 0;
- HIViewRef hiview = 0;
- if(GetEventParameter(event, kEventParamDirectObject, typeControlRef,
- 0, sizeof(hiview), 0, &hiview) == noErr)
- widget = QWidget::find((WId)hiview);
- if (widget && widget->macEvent(er, event))
- return noErr;
- if(ekind == kEventControlDraw) {
- if(widget && qt_isGenuineQWidget(hiview)) {
-
- // if there is a window change event pending for any gl child wigets,
- // send it immediately. (required for flicker-free resizing)
- extern void qt_mac_send_posted_gl_updates(QWidget *widget);
- qt_mac_send_posted_gl_updates(widget);
-
- if (QApplicationPrivate::graphicsSystem() && !widget->d_func()->paintOnScreen()) {
- widget->d_func()->syncBackingStore();
- widget->d_func()->dirtyOnWidget = QRegion();
- return noErr;
- }
-
- //requested rgn
- RgnHandle rgn;
- GetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof(rgn), 0, &rgn);
- QRegion qrgn(qt_mac_convert_mac_region(rgn));
-
- //update handles
- GrafPtr qd = 0;
- CGContextRef cg = 0;
- if(GetEventParameter(event, kEventParamCGContextRef, typeCGContextRef, 0, sizeof(cg), 0, &cg) != noErr) {
- Q_ASSERT(false);
- }
- widget->d_func()->hd = cg;
- widget->d_func()->qd_hd = qd;
- CGContextSaveGState(cg);
-
-#ifdef DEBUG_WIDGET_PAINT
- const bool doDebug = true;
- if(doDebug) {
- qDebug("asked to draw %p[%p] [%s::%s] %p[%p] [%d] [%dx%d]", widget, hiview, widget->metaObject()->className(),
- widget->objectName().local8Bit().data(), widget->parentWidget(),
- (HIViewRef)(widget->parentWidget() ? qt_mac_nativeview_for(widget->parentWidget()) : (HIViewRef)0),
- HIViewIsCompositingEnabled(hiview), qt_mac_posInWindow(widget).x(), qt_mac_posInWindow(widget).y());
-#if 0
- QVector<QRect> region_rects = qrgn.rects();
- qDebug("Region! %d", region_rects.count());
- for(int i = 0; i < region_rects.count(); i++)
- qDebug("%d %d %d %d", region_rects[i].x(), region_rects[i].y(),
- region_rects[i].width(), region_rects[i].height());
- region_rects = widget->d_func()->clp.rects();
- qDebug("Widget Region! %d", region_rects.count());
- for(int i = 0; i < region_rects.count(); i++)
- qDebug("%d %d %d %d", region_rects[i].x(), region_rects[i].y(),
- region_rects[i].width(), region_rects[i].height());
-#endif
- }
-#endif
- if (widget->isVisible() && widget->updatesEnabled()) { //process the actual paint event.
- if(widget->testAttribute(Qt::WA_WState_InPaintEvent))
- qWarning("QWidget::repaint: Recursive repaint detected");
- if (widget->isWindow() && !widget->d_func()->isOpaque
- && !widget->testAttribute(Qt::WA_MacBrushedMetal)) {
- QRect qrgnRect = qrgn.boundingRect();
- CGContextClearRect(cg, CGRectMake(qrgnRect.x(), qrgnRect.y(), qrgnRect.width(), qrgnRect.height()));
- }
-
- QPoint redirectionOffset(0, 0);
- QWidget *tl = widget->window();
- if (tl) {
- Qt::WindowFlags flags = tl->windowFlags();
- if (flags & Qt::FramelessWindowHint
- || (flags & Qt::CustomizeWindowHint && !(flags & Qt::WindowTitleHint))) {
- if(tl->d_func()->extra && !tl->d_func()->extra->mask.isEmpty())
- redirectionOffset += tl->d_func()->extra->mask.boundingRect().topLeft();
- }
- }
-
- //setup the context
- widget->setAttribute(Qt::WA_WState_InPaintEvent);
- QPaintEngine *engine = widget->paintEngine();
- if (engine)
- engine->setSystemClip(qrgn);
-
- //handle the erase
- if (engine && (!widget->testAttribute(Qt::WA_NoSystemBackground)
- && (widget->isWindow() || widget->autoFillBackground())
- || widget->testAttribute(Qt::WA_TintedBackground)
- || widget->testAttribute(Qt::WA_StyledBackground))) {
-#ifdef DEBUG_WIDGET_PAINT
- if(doDebug)
- qDebug(" Handling erase for [%s::%s]", widget->metaObject()->className(),
- widget->objectName().local8Bit().data());
-#endif
- if (!redirectionOffset.isNull())
- widget->d_func()->setRedirected(widget, redirectionOffset);
-
- bool was_unclipped = widget->testAttribute(Qt::WA_PaintUnclipped);
- widget->setAttribute(Qt::WA_PaintUnclipped, false);
- QPainter p(widget);
- p.setClipping(false);
- if(was_unclipped)
- widget->setAttribute(Qt::WA_PaintUnclipped);
- widget->d_func()->paintBackground(&p, qrgn, widget->isWindow() ? DrawAsRoot : 0);
- if (widget->testAttribute(Qt::WA_TintedBackground)) {
- QColor tint = widget->palette().window().color();
- tint.setAlphaF(.6);
- const QVector<QRect> &rects = qrgn.rects();
- for (int i = 0; i < rects.size(); ++i)
- p.fillRect(rects.at(i), tint);
- }
- p.end();
- if (!redirectionOffset.isNull())
- widget->d_func()->restoreRedirected();
- }
-
- if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
- CallNextEventHandler(er, event);
-
- //send the paint
- redirectionOffset += widget->data->wrect.topLeft(); // Map from system to qt coordinates
- if (!redirectionOffset.isNull())
- widget->d_func()->setRedirected(widget, redirectionOffset);
- qrgn.translate(redirectionOffset);
- QPaintEvent e(qrgn);
- widget->d_func()->dirtyOnWidget = QRegion();
-#ifdef QT3_SUPPORT
- e.setErased(true);
-#endif
- QApplication::sendSpontaneousEvent(widget, &e);
- if (!redirectionOffset.isNull())
- widget->d_func()->restoreRedirected();
-
- //cleanup
- if (engine)
- engine->setSystemClip(QRegion());
-
- widget->setAttribute(Qt::WA_WState_InPaintEvent, false);
- if(!widget->testAttribute(Qt::WA_PaintOutsidePaintEvent) && widget->paintingActive())
- qWarning("QWidget: It is dangerous to leave painters active on a widget outside of the PaintEvent");
- }
-
- widget->d_func()->hd = 0;
- widget->d_func()->qd_hd = 0;
- CGContextRestoreGState(cg);
- } else if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) {
- CallNextEventHandler(er, event);
- }
- } else if(ekind == kEventControlInitialize) {
- if(HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) {
- UInt32 features = kControlSupportsDragAndDrop | kControlSupportsClickActivation | kControlSupportsFocus;
- SetEventParameter(event, kEventParamControlFeatures, typeUInt32, sizeof(features), &features);
- } else {
- handled_event = false;
- }
- } else if(ekind == kEventControlSetFocusPart) {
- if(widget) {
- ControlPartCode part;
- GetEventParameter(event, kEventParamControlPart, typeControlPartCode, 0,
- sizeof(part), 0, &part);
- if(part == kControlFocusNoPart){
- if (widget->hasFocus())
- QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
- } else
- widget->setFocus();
- }
- if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
- CallNextEventHandler(er, event);
- } else if(ekind == kEventControlGetClickActivation) {
- ClickActivationResult clickT = kActivateAndIgnoreClick;
- SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult,
- sizeof(clickT), &clickT);
- } else if(ekind == kEventControlGetPartRegion) {
- handled_event = false;
- if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget) && CallNextEventHandler(er, event) == noErr) {
- handled_event = true;
- break;
- }
- if(widget && !widget->isWindow()) {
- ControlPartCode part;
- GetEventParameter(event, kEventParamControlPart, typeControlPartCode, 0,
- sizeof(part), 0, &part);
- if(part == kControlClickableMetaPart && widget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
- RgnHandle rgn;
- GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
- sizeof(rgn), 0, &rgn);
- SetEmptyRgn(rgn);
- handled_event = true;
- } else if(part == kControlStructureMetaPart || part == kControlClickableMetaPart) {
- RgnHandle rgn;
- GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
- sizeof(rgn), 0, &rgn);
- SetRectRgn(rgn, 0, 0, widget->width(), widget->height());
- if(QWidgetPrivate::qt_widget_rgn(widget, kWindowStructureRgn, rgn, false))
- handled_event = true;
- } else if(part == kControlOpaqueMetaPart) {
- if(widget->d_func()->isOpaque) {
- RgnHandle rgn;
- GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
- sizeof(RgnHandle), 0, &rgn);
- SetRectRgn(rgn, 0, 0, widget->width(), widget->height());
- QWidgetPrivate::qt_widget_rgn(widget, kWindowStructureRgn, rgn, false);
- SetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle,
- sizeof(RgnHandle), &rgn);
- handled_event = true;
- }
- }
- }
- } else if(ekind == kEventControlOwningWindowChanged) {
- if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
- CallNextEventHandler(er, event);
- if(widget && qt_mac_window_for(hiview)) {
- WindowRef foo = 0;
- GetEventParameter(event, kEventParamControlCurrentOwningWindow, typeWindowRef, 0,
- sizeof(foo), 0, &foo);
- widget->d_func()->initWindowPtr();
- }
- if (widget)
- qt_event_request_window_change(widget);
- } else if(ekind == kEventControlDragEnter || ekind == kEventControlDragWithin ||
- ekind == kEventControlDragLeave || ekind == kEventControlDragReceive) {
- // dnd are really handled in qdnd_mac.cpp,
- // just modularize the code a little...
- DragRef drag;
- GetEventParameter(event, kEventParamDragRef, typeDragRef, 0, sizeof(drag), 0, &drag);
- handled_event = false;
- bool drag_allowed = false;
-
- QWidget *dropWidget = widget;
- if (qobject_cast<QFocusFrame *>(widget)){
- // We might shadow widgets underneath the focus
- // frame, so stay interrested, and let the dnd through
- drag_allowed = true;
- handled_event = true;
- Point where;
- GetDragMouse(drag, &where, 0);
- dropWidget = QApplication::widgetAt(QPoint(where.h, where.v));
-
- if (dropWidget != QDragManager::self()->currentTarget()) {
- // We have to 'fake' enter and leave events for the shaddowed widgets:
- if (ekind == kEventControlDragEnter) {
- if (QDragManager::self()->currentTarget())
- QDragManager::self()->currentTarget()->d_func()->qt_mac_dnd_event(kEventControlDragLeave, drag);
- if (dropWidget) {
- dropWidget->d_func()->qt_mac_dnd_event(kEventControlDragEnter, drag);
- }
- // Set dropWidget to zero, so qt_mac_dnd_event
- // doesn't get called a second time below:
- dropWidget = 0;
- } else if (ekind == kEventControlDragLeave) {
- dropWidget = QDragManager::self()->currentTarget();
- if (dropWidget) {
- dropWidget->d_func()->qt_mac_dnd_event(kEventControlDragLeave, drag);
- }
- // Set dropWidget to zero, so qt_mac_dnd_event
- // doesn't get called a second time below:
- dropWidget = 0;
- }
- }
- }
-
- // Send the dnd event to the widget:
- if (dropWidget && dropWidget->d_func()->qt_mac_dnd_event(ekind, drag)) {
- drag_allowed = true;
- handled_event = true;
- }
-
- if (ekind == kEventControlDragEnter) {
- // If we don't accept the enter event, we will
- // receive no more drag events for this widget
- const Boolean wouldAccept = drag_allowed ? true : false;
- SetEventParameter(event, kEventParamControlWouldAcceptDrop, typeBoolean,
- sizeof(wouldAccept), &wouldAccept);
- }
- } else if (ekind == kEventControlBoundsChanged) {
- if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_Moved) || widget->testAttribute(Qt::WA_Resized)) {
- handled_event = false;
- } else {
- // Sync our view in case some other (non-Qt) view is controlling us.
- handled_event = true;
- Rect newBounds;
- GetEventParameter(event, kEventParamCurrentBounds,
- typeQDRectangle, 0, sizeof(Rect), 0, &newBounds);
- QRect rect(newBounds.left, newBounds.top,
- newBounds.right - newBounds.left, newBounds.bottom - newBounds.top);
-
- bool moved = widget->testAttribute(Qt::WA_Moved);
- bool resized = widget->testAttribute(Qt::WA_Resized);
- widget->setGeometry(rect);
- widget->setAttribute(Qt::WA_Moved, moved);
- widget->setAttribute(Qt::WA_Resized, resized);
- qt_event_request_window_change(widget);
- }
- } else if (ekind == kEventControlGetSizeConstraints) {
- if (!widget || !qt_isGenuineQWidget(widget)) {
- handled_event = false;
- } else {
- handled_event = true;
- QWidgetItem item(widget);
- QSize size = item.minimumSize();
- HISize hisize = { size.width(), size.height() };
- SetEventParameter(event, kEventParamMinimumSize, typeHISize, sizeof(HISize), &hisize);
- size = item.maximumSize();
- hisize.width = size.width() + 2; // ### shouldn't have to add 2 (but it works).
- hisize.height = size.height();
- SetEventParameter(event, kEventParamMaximumSize, typeHISize, sizeof(HISize), &hisize);
- }
- } else if (ekind == kEventControlVisibilityChanged) {
- handled_event = false;
- if (widget) {
- qt_event_request_window_change(widget);
- if (!HIViewIsVisible(HIViewRef(widget->winId()))) {
- if (widget == qt_button_down)
- qt_button_down = 0;
- }
- }
- }
- break; }
- case kEventClassMouse: {
- bool send_to_app = false;
- if(qt_button_down)
- send_to_app = true;
- if(send_to_app) {
- OSStatus err = SendEventToApplication(event);
- if(err != noErr)
- handled_event = false;
- } else {
- CallNextEventHandler(er, event);
- }
- break; }
- default:
- handled_event = false;
- break;
- }
- if(!handled_event) //let the event go through
- return eventNotHandledErr;
- return noErr; //we eat the event
-}
-#endif
-
-OSViewRef qt_mac_create_widget(QWidget *widget, QWidgetPrivate *widgetPrivate, OSViewRef parent)
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QCocoaView) *view = [[QT_MANGLE_NAMESPACE(QCocoaView) alloc] initWithQWidget:widget widgetPrivate:widgetPrivate];
-
-#ifdef ALIEN_DEBUG
- qDebug() << "Creating NSView for" << widget;
-#endif
-
- if (view && parent)
- [parent addSubview:view];
- return view;
-#else
- Q_UNUSED(widget);
- Q_UNUSED(widgetPrivate);
- if(!widget_class) {
- OSStatus err = HIObjectRegisterSubclass(kObjectQWidget, kHIViewClassID, 0, make_widget_eventUPP(),
- GetEventTypeCount(widget_events), widget_events,
- 0, &widget_class);
- if (err && err != hiObjectClassExistsErr)
- qWarning("QWidget: Internal error (%d)", __LINE__);
- }
- HIViewRef ret = 0;
- if(HIObjectCreate(kObjectQWidget, 0, (HIObjectRef*)&ret) != noErr)
- qWarning("QWidget: Internal error (%d)", __LINE__);
- if(ret && parent)
- HIViewAddSubview(parent, ret);
- return ret;
-#endif
-}
-
-void qt_mac_unregister_widget()
-{
-#ifndef QT_MAC_USE_COCOA
- HIObjectUnregisterClass(widget_class);
- widget_class = 0;
-#endif
-}
-
-void QWidgetPrivate::toggleDrawers(bool visible)
-{
- for (int i = 0; i < children.size(); ++i) {
- register QObject *object = children.at(i);
- if (!object->isWidgetType())
- continue;
- QWidget *widget = static_cast<QWidget*>(object);
- if(qt_mac_is_macdrawer(widget)) {
- bool oldState = widget->testAttribute(Qt::WA_WState_ExplicitShowHide);
- if(visible) {
- if (!widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
- widget->show();
- } else {
- widget->hide();
- if(!oldState)
- widget->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- }
- }
- }
-}
-
-/*****************************************************************************
- QWidgetPrivate member functions
- *****************************************************************************/
-bool QWidgetPrivate::qt_mac_update_sizer(QWidget *w, int up)
-{
- // I'm not sure what "up" is
- if(!w || !w->isWindow())
- return false;
-
- QTLWExtra *topData = w->d_func()->topData();
- QWExtra *extraData = w->d_func()->extraData();
- // topData->resizer is only 4 bits, so subtracting -1 from zero causes bad stuff
- // to happen, prevent that here (you really want the thing hidden).
- if (up >= 0 || topData->resizer != 0)
- topData->resizer += up;
- OSWindowRef windowRef = qt_mac_window_for(OSViewRef(w->effectiveWinId()));
- {
-#ifndef QT_MAC_USE_COCOA
- WindowClass wclass;
- GetWindowClass(windowRef, &wclass);
- if(!(GetAvailableWindowAttributes(wclass) & kWindowResizableAttribute))
- return true;
-#endif
- }
- bool remove_grip = (topData->resizer || (w->windowFlags() & Qt::FramelessWindowHint)
- || (extraData->maxw && extraData->maxh &&
- extraData->maxw == extraData->minw && extraData->maxh == extraData->minh));
-#ifndef QT_MAC_USE_COCOA
- WindowAttributes attr;
- GetWindowAttributes(windowRef, &attr);
- if(remove_grip) {
- if(attr & kWindowResizableAttribute) {
- ChangeWindowAttributes(qt_mac_window_for(w), kWindowNoAttributes,
- kWindowResizableAttribute);
- ReshapeCustomWindow(qt_mac_window_for(w));
- }
- } else if(!(attr & kWindowResizableAttribute)) {
- ChangeWindowAttributes(windowRef, kWindowResizableAttribute,
- kWindowNoAttributes);
- ReshapeCustomWindow(windowRef);
- }
-#else
- [windowRef setShowsResizeIndicator:!remove_grip];
-#endif
- return true;
-}
-
-void QWidgetPrivate::qt_clean_root_win()
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- [qt_root_win release];
-#else
- if(!qt_root_win)
- return;
- CFRelease(qt_root_win);
-#endif
- qt_root_win = 0;
-}
-
-bool QWidgetPrivate::qt_create_root_win()
-{
- if(qt_root_win)
- return false;
- const QSize desktopSize = qt_mac_desktopSize();
- QRect desktopRect(QPoint(0, 0), desktopSize);
-#ifdef QT_MAC_USE_COCOA
- qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, NSBorderlessWindowMask, desktopRect);
-#else
- WindowAttributes wattr = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
- qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, wattr, desktopRect);
-#endif
- if(!qt_root_win)
- return false;
- qAddPostRoutine(qt_clean_root_win);
- return true;
-}
-
-bool QWidgetPrivate::qt_widget_rgn(QWidget *widget, short wcode, RgnHandle rgn, bool force = false)
-{
- bool ret = false;
-#ifndef QT_MAC_USE_COCOA
- switch(wcode) {
- case kWindowStructureRgn: {
- if(widget) {
- if(widget->d_func()->extra && !widget->d_func()->extra->mask.isEmpty()) {
- QRegion rin = qt_mac_convert_mac_region(rgn);
- if(!rin.isEmpty()) {
- QPoint rin_tl = rin.boundingRect().topLeft(); //in offset
- rin.translate(-rin_tl.x(), -rin_tl.y()); //bring into same space as below
- QRegion mask = widget->d_func()->extra->mask;
- Qt::WindowFlags flags = widget->windowFlags();
- if(widget->isWindow()
- && !(flags & Qt::FramelessWindowHint
- || (flags & Qt::CustomizeWindowHint && !(flags & Qt::WindowTitleHint)))) {
- QRegion title;
- {
- QMacSmartQuickDrawRegion rgn(qt_mac_get_rgn());
- GetWindowRegion(qt_mac_window_for(widget), kWindowTitleBarRgn, rgn);
- title = qt_mac_convert_mac_region(rgn);
- }
- QRect br = title.boundingRect();
- mask.translate(0, br.height()); //put the mask 'under' the title bar..
- title.translate(-br.x(), -br.y());
- mask += title;
- }
-
- QRegion cr = rin & mask;
- cr.translate(rin_tl.x(), rin_tl.y()); //translate back to incoming space
- CopyRgn(QMacSmartQuickDrawRegion(cr.toQDRgn()), rgn);
- }
- ret = true;
- } else if(force) {
- QRegion cr(widget->geometry());
- CopyRgn(QMacSmartQuickDrawRegion(cr.toQDRgn()), rgn);
- ret = true;
- }
- }
- break; }
- default: break;
- }
- //qDebug() << widget << ret << wcode << qt_mac_convert_mac_region(rgn);
-#else
- Q_UNUSED(widget);
- Q_UNUSED(wcode);
- Q_UNUSED(rgn);
- Q_UNUSED(force);
-#endif
- return ret;
-}
-
-/*****************************************************************************
- QWidget member functions
- *****************************************************************************/
-void QWidgetPrivate::determineWindowClass()
-{
- Q_Q(QWidget);
-#if !defined(QT_NO_MAINWINDOW) && !defined(QT_NO_TOOLBAR)
- // Make sure that QMainWindow has the MacWindowToolBarButtonHint when the
- // unifiedTitleAndToolBarOnMac property is ON. This is to avoid reentry of
- // setParent() triggered by the QToolBar::event(QEvent::ParentChange).
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(q);
- if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
- data.window_flags |= Qt::MacWindowToolBarButtonHint;
- }
-#endif
-#ifndef QT_MAC_USE_COCOA
-// ### COCOA:Interleave these better!
-
- const Qt::WindowType type = q->windowType();
- Qt::WindowFlags &flags = data.window_flags;
- const bool popup = (type == Qt::Popup);
- if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
- flags |= Qt::FramelessWindowHint;
-
- WindowClass wclass = kSheetWindowClass;
- if(qt_mac_is_macdrawer(q))
- wclass = kDrawerWindowClass;
- else if (q->testAttribute(Qt::WA_ShowModal) && flags & Qt::CustomizeWindowHint)
- wclass = kDocumentWindowClass;
- else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
- wclass = kModalWindowClass;
- else if(q->testAttribute(Qt::WA_ShowModal))
- wclass = kMovableModalWindowClass;
- else if(type == Qt::ToolTip)
- wclass = kHelpWindowClass;
- else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
- && type == Qt::SplashScreen))
- wclass = kFloatingWindowClass;
- else
- wclass = kDocumentWindowClass;
-
- WindowGroupRef grp = 0;
- WindowAttributes wattr = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
- if (q->testAttribute(Qt::WA_MacFrameworkScaled))
- wattr |= kWindowFrameworkScaledAttribute;
- if(qt_mac_is_macsheet(q)) {
- //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
- wclass = kSheetWindowClass;
- } else {
- grp = GetWindowGroupOfClass(wclass);
- // Shift things around a bit to get the correct window class based on the presence
- // (or lack) of the border.
- bool customize = flags & Qt::CustomizeWindowHint;
- bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
- if (framelessWindow) {
- if(wclass == kDocumentWindowClass) {
- wattr |= kWindowNoTitleBarAttribute;
- } else if(wclass == kFloatingWindowClass) {
- wattr |= kWindowNoTitleBarAttribute;
- } else if (wclass == kMovableModalWindowClass) {
- wclass = kModalWindowClass;
- }
- } else {
- if(wclass != kModalWindowClass)
- wattr |= kWindowResizableAttribute;
- }
- // Only add extra decorations (well, buttons) for widgets that can have them
- // and have an actual border we can put them on.
- if(wclass != kModalWindowClass && wclass != kMovableModalWindowClass
- && wclass != kSheetWindowClass && wclass != kPlainWindowClass
- && !framelessWindow && wclass != kDrawerWindowClass
- && wclass != kHelpWindowClass) {
- if (flags & Qt::WindowMaximizeButtonHint)
- wattr |= kWindowFullZoomAttribute;
- if (flags & Qt::WindowMinimizeButtonHint)
- wattr |= kWindowCollapseBoxAttribute;
- if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
- wattr |= kWindowCloseBoxAttribute;
- if (flags & Qt::MacWindowToolBarButtonHint)
- wattr |= kWindowToolbarButtonAttribute;
- } else {
- // Clear these hints so that we aren't call them on invalid windows
- flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
- | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
- }
- }
- if((popup || type == Qt::Tool) && !q->isModal())
- wattr |= kWindowHideOnSuspendAttribute;
- wattr |= kWindowLiveResizeAttribute;
-
-#ifdef DEBUG_WINDOW_CREATE
-#define ADD_DEBUG_WINDOW_NAME(x) { x, #x }
- struct {
- UInt32 tag;
- const char *name;
- } known_attribs[] = {
- ADD_DEBUG_WINDOW_NAME(kWindowCompositingAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowMetalAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowCollapseBoxAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowHorizontalZoomAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowVerticalZoomAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowResizableAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowNoActivatesAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowNoUpdatesAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowOpaqueForEventsAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowLiveResizeAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowCloseBoxAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
- { 0, 0 }
- }, known_classes[] = {
- ADD_DEBUG_WINDOW_NAME(kHelpWindowClass),
- ADD_DEBUG_WINDOW_NAME(kPlainWindowClass),
- ADD_DEBUG_WINDOW_NAME(kDrawerWindowClass),
- ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
- ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
- ADD_DEBUG_WINDOW_NAME(kSheetWindowClass),
- ADD_DEBUG_WINDOW_NAME(kFloatingWindowClass),
- ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
- ADD_DEBUG_WINDOW_NAME(kDocumentWindowClass),
- ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
- ADD_DEBUG_WINDOW_NAME(kMovableModalWindowClass),
- ADD_DEBUG_WINDOW_NAME(kModalWindowClass),
- { 0, 0 }
- };
- qDebug("Qt: internal: ************* Creating new window %p (%s::%s)", q, q->metaObject()->className(),
- q->objectName().toLocal8Bit().constData());
- bool found_class = false;
- for(int i = 0; known_classes[i].name; i++) {
- if(wclass == known_classes[i].tag) {
- found_class = true;
- qDebug("Qt: internal: ** Class: %s", known_classes[i].name);
- break;
- }
- }
- if(!found_class)
- qDebug("Qt: internal: !! Class: Unknown! (%d)", (int)wclass);
- if(wattr) {
- WindowAttributes tmp_wattr = wattr;
- qDebug("Qt: internal: ** Attributes:");
- for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
- if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
- tmp_wattr ^= known_attribs[i].tag;
- qDebug("Qt: internal: * %s %s", known_attribs[i].name,
- (GetAvailableWindowAttributes(wclass) & known_attribs[i].tag) ? "" : "(*)");
- }
- }
- if(tmp_wattr)
- qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
- }
-#endif
-
- /* Just to be extra careful we will change to the kUtilityWindowClass if the
- requested attributes cannot be used */
- if((GetAvailableWindowAttributes(wclass) & wattr) != wattr) {
- WindowClass tmp_class = wclass;
- if(wclass == kToolbarWindowClass || wclass == kUtilityWindowClass)
- wclass = kFloatingWindowClass;
- if(tmp_class != wclass) {
- if(!grp)
- grp = GetWindowGroupOfClass(wclass);
- wclass = tmp_class;
- }
- }
- topData()->wclass = wclass;
- topData()->wattr = wattr;
-#else
- const Qt::WindowType type = q->windowType();
- Qt::WindowFlags &flags = data.window_flags;
- const bool popup = (type == Qt::Popup);
- if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
- flags |= Qt::FramelessWindowHint;
-
- WindowClass wclass = kSheetWindowClass;
- if(qt_mac_is_macdrawer(q))
- wclass = kDrawerWindowClass;
- else if (q->testAttribute(Qt::WA_ShowModal) && flags & Qt::CustomizeWindowHint)
- wclass = kDocumentWindowClass;
- else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
- wclass = kModalWindowClass;
- else if(type == Qt::Dialog)
- wclass = kMovableModalWindowClass;
- else if(type == Qt::ToolTip)
- wclass = kHelpWindowClass;
- else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
- && type == Qt::SplashScreen))
- wclass = kFloatingWindowClass;
- else if(q->testAttribute(Qt::WA_ShowModal))
- wclass = kMovableModalWindowClass;
- else
- wclass = kDocumentWindowClass;
-
- WindowAttributes wattr = NSBorderlessWindowMask;
- if(qt_mac_is_macsheet(q)) {
- //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
- wclass = kSheetWindowClass;
- wattr = NSTitledWindowMask | NSResizableWindowMask;
- } else {
-#ifndef QT_MAC_USE_COCOA
- grp = GetWindowGroupOfClass(wclass);
-#endif
- // Shift things around a bit to get the correct window class based on the presence
- // (or lack) of the border.
- bool customize = flags & Qt::CustomizeWindowHint;
- bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
- if (framelessWindow) {
- if (wclass == kDocumentWindowClass) {
- wclass = kSimpleWindowClass;
- } else if (wclass == kFloatingWindowClass) {
- wclass = kToolbarWindowClass;
- } else if (wclass == kMovableModalWindowClass) {
- wclass = kModalWindowClass;
- }
- } else {
- wattr |= NSTitledWindowMask;
- if (wclass != kModalWindowClass)
- wattr |= NSResizableWindowMask;
- }
- // Only add extra decorations (well, buttons) for widgets that can have them
- // and have an actual border we can put them on.
- if (wclass != kModalWindowClass
- && wclass != kSheetWindowClass && wclass != kPlainWindowClass
- && !framelessWindow && wclass != kDrawerWindowClass
- && wclass != kHelpWindowClass) {
- if (flags & Qt::WindowMinimizeButtonHint)
- wattr |= NSMiniaturizableWindowMask;
- if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
- wattr |= NSClosableWindowMask;
- } else {
- // Clear these hints so that we aren't call them on invalid windows
- flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
- | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
- }
- }
- if (q->testAttribute(Qt::WA_MacBrushedMetal))
- wattr |= NSTexturedBackgroundWindowMask;
-
-#ifdef DEBUG_WINDOW_CREATE
-#define ADD_DEBUG_WINDOW_NAME(x) { x, #x }
- struct {
- UInt32 tag;
- const char *name;
- } known_attribs[] = {
- ADD_DEBUG_WINDOW_NAME(kWindowCompositingAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowMetalAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowCollapseBoxAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowHorizontalZoomAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowVerticalZoomAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowResizableAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowNoActivatesAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowNoUpdatesAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowOpaqueForEventsAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowLiveResizeAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowCloseBoxAttribute),
- ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
- { 0, 0 }
- }, known_classes[] = {
- ADD_DEBUG_WINDOW_NAME(kHelpWindowClass),
- ADD_DEBUG_WINDOW_NAME(kPlainWindowClass),
- ADD_DEBUG_WINDOW_NAME(kDrawerWindowClass),
- ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
- ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
- ADD_DEBUG_WINDOW_NAME(kSheetWindowClass),
- ADD_DEBUG_WINDOW_NAME(kFloatingWindowClass),
- ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
- ADD_DEBUG_WINDOW_NAME(kDocumentWindowClass),
- ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
- ADD_DEBUG_WINDOW_NAME(kMovableModalWindowClass),
- ADD_DEBUG_WINDOW_NAME(kModalWindowClass),
- { 0, 0 }
- };
- qDebug("Qt: internal: ************* Creating new window %p (%s::%s)", q, q->metaObject()->className(),
- q->objectName().toLocal8Bit().constData());
- bool found_class = false;
- for(int i = 0; known_classes[i].name; i++) {
- if(wclass == known_classes[i].tag) {
- found_class = true;
- qDebug("Qt: internal: ** Class: %s", known_classes[i].name);
- break;
- }
- }
- if(!found_class)
- qDebug("Qt: internal: !! Class: Unknown! (%d)", (int)wclass);
- if(wattr) {
- WindowAttributes tmp_wattr = wattr;
- qDebug("Qt: internal: ** Attributes:");
- for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
- if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
- tmp_wattr ^= known_attribs[i].tag;
- }
- }
- if(tmp_wattr)
- qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
- }
-#endif
-
-#ifndef QT_MAC_USE_COCOA
- /* Just to be extra careful we will change to the kUtilityWindowClass if the
- requested attributes cannot be used */
- if((GetAvailableWindowAttributes(wclass) & wattr) != wattr) {
- WindowClass tmp_class = wclass;
- if(wclass == kToolbarWindowClass || wclass == kUtilityWindowClass)
- wclass = kFloatingWindowClass;
- if(tmp_class != wclass) {
- if(!grp)
- grp = GetWindowGroupOfClass(wclass);
- wclass = tmp_class;
- }
- }
-#endif
-#endif
- topData()->wclass = wclass;
- topData()->wattr = wattr;
-}
-
-#ifndef QT_MAC_USE_COCOA // This is handled in Cocoa via our category.
-void QWidgetPrivate::initWindowPtr()
-{
- Q_Q(QWidget);
- OSWindowRef windowRef = qt_mac_window_for(qt_mac_nativeview_for(q)); //do not create!
- if(!windowRef)
- return;
- QWidget *window = q->window(), *oldWindow = 0;
- if(GetWindowProperty(windowRef, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(oldWindow), 0, &oldWindow) == noErr) {
- Q_ASSERT(window == oldWindow);
- return;
- }
-
- if(SetWindowProperty(windowRef, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(window), &window) != noErr)
- qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__); //no real way to recover
- if(!q->windowType() != Qt::Desktop) { //setup an event callback handler on the window
- InstallWindowEventHandler(windowRef, make_win_eventUPP(), GetEventTypeCount(window_events),
- window_events, static_cast<void *>(qApp), &window_event);
- }
-}
-
-void QWidgetPrivate::finishCreateWindow_sys_Carbon(OSWindowRef windowRef)
-{
- Q_Q(QWidget);
- const Qt::WindowType type = q->windowType();
- Qt::WindowFlags &flags = data.window_flags;
- QWidget *parentWidget = q->parentWidget();
-
- const bool desktop = (type == Qt::Desktop);
- const bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet
- || type == Qt::Drawer
- || (flags & Qt::MSWindowsFixedSizeDialogHint));
- QTLWExtra *topExtra = topData();
- quint32 wattr = topExtra->wattr;
- if (!desktop)
- SetAutomaticControlDragTrackingEnabledForWindow(windowRef, true);
- HIWindowChangeFeatures(windowRef, kWindowCanCollapse, 0);
- if (wattr & kWindowHideOnSuspendAttribute)
- HIWindowChangeAvailability(windowRef, kHIWindowExposeHidden, 0);
- else
- HIWindowChangeAvailability(windowRef, 0, kHIWindowExposeHidden);
- if ((flags & Qt::WindowStaysOnTopHint))
- ChangeWindowAttributes(windowRef, kWindowNoAttributes, kWindowHideOnSuspendAttribute);
- if (qt_mac_is_macdrawer(q) && parentWidget)
- SetDrawerParent(windowRef, qt_mac_window_for (parentWidget));
- if (topExtra->group) {
- qt_mac_release_window_group(topExtra->group);
- topExtra->group = 0;
- }
- if (type == Qt::ToolTip)
- qt_mac_set_window_group_to_tooltip(windowRef);
- else if (type == Qt::Popup && (flags & Qt::WindowStaysOnTopHint))
- qt_mac_set_window_group_to_popup(windowRef);
- else if (flags & Qt::WindowStaysOnTopHint)
- qt_mac_set_window_group_to_stays_on_top(windowRef, type);
- else if (dialog)
- SetWindowGroup(windowRef, GetWindowGroupOfClass(kMovableModalWindowClass));
-
-#ifdef DEBUG_WINDOW_CREATE
- if (WindowGroupRef grpf = GetWindowGroup(windowRef)) {
- QCFString cfname;
- CopyWindowGroupName(grpf, &cfname);
- SInt32 lvl;
- GetWindowGroupLevel(grpf, &lvl);
- const char *from = "Default";
- if (topExtra && grpf == topData()->group)
- from = "Created";
- else if (grpf == grp)
- from = "Copied";
- qDebug("Qt: internal: With window group '%s' [%p] @ %d: %s",
- static_cast<QString>(cfname).toLatin1().constData(), grpf, (int)lvl, from);
- } else {
- qDebug("Qt: internal: No window group!!!");
- }
- HIWindowAvailability hi_avail = 0;
- if (HIWindowGetAvailability(windowRef, &hi_avail) == noErr) {
- struct {
- UInt32 tag;
- const char *name;
- } known_avail[] = {
- ADD_DEBUG_WINDOW_NAME(kHIWindowExposeHidden),
- { 0, 0 }
- };
- qDebug("Qt: internal: ** HIWindowAvailibility:");
- for (int i = 0; hi_avail && known_avail[i].name; i++) {
- if ((hi_avail & known_avail[i].tag) == known_avail[i].tag) {
- hi_avail ^= known_avail[i].tag;
- qDebug("Qt: internal: * %s", known_avail[i].name);
- }
- }
- if (hi_avail)
- qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)hi_avail);
- }
-#undef ADD_DEBUG_WINDOW_NAME
-#endif
- if (extra && !extra->mask.isEmpty())
- ReshapeCustomWindow(windowRef);
- SetWindowModality(windowRef, kWindowModalityNone, 0);
- if (qt_mac_is_macdrawer(q))
- SetDrawerOffsets(windowRef, 0.0, 25.0);
- data.fstrut_dirty = true; // when we create a toplevel widget, the frame strut should be dirty
- HIViewRef hiview = (HIViewRef)data.winid;
- HIViewRef window_hiview = qt_mac_get_contentview_for(windowRef);
- if(!hiview) {
- hiview = qt_mac_create_widget(q, this, window_hiview);
- setWinId((WId)hiview);
- } else {
- HIViewAddSubview(window_hiview, hiview);
- }
- if (hiview) {
- Rect win_rect;
- GetWindowBounds(qt_mac_window_for (window_hiview), kWindowContentRgn, &win_rect);
- HIRect bounds = CGRectMake(0, 0, win_rect.right-win_rect.left, win_rect.bottom-win_rect.top);
- HIViewSetFrame(hiview, &bounds);
- HIViewSetVisible(hiview, true);
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- registerDropSite(true);
- transferChildren();
- }
- initWindowPtr();
-
- if (topExtra->posFromMove) {
- updateFrameStrut();
- const QRect &fStrut = frameStrut();
- Rect r;
- SetRect(&r, data.crect.left(), data.crect.top(), data.crect.right() + 1, data.crect.bottom() + 1);
- SetRect(&r, r.left + fStrut.left(), r.top + fStrut.top(),
- (r.left + fStrut.left() + data.crect.width()) - fStrut.right(),
- (r.top + fStrut.top() + data.crect.height()) - fStrut.bottom());
- SetWindowBounds(windowRef, kWindowContentRgn, &r);
- topExtra->posFromMove = false;
- }
-
- if (q->testAttribute(Qt::WA_WState_WindowOpacitySet)){
- q->setWindowOpacity(topExtra->opacity / 255.0f);
- } else if (qt_mac_is_macsheet(q)){
- SetThemeWindowBackground(qt_mac_window_for(q), kThemeBrushSheetBackgroundTransparent, true);
- CGFloat alpha = 0;
- GetWindowAlpha(qt_mac_window_for(q), &alpha);
- if (alpha == 1){
- // For some reason the 'SetThemeWindowBackground' does not seem
- // to work. So we do this little hack until it hopefully starts to
- // work in newer versions of mac OS.
- q->setWindowOpacity(0.95f);
- q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
- }
- } else{
- // If the window has been recreated after beeing e.g. a sheet,
- // make sure that we don't report a faulty opacity:
- q->setWindowOpacity(1.0f);
- q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
- }
-
- // Since we only now have a window, sync our state.
- macUpdateHideOnSuspend();
- macUpdateOpaqueSizeGrip();
- macUpdateMetalAttribute();
- macUpdateIgnoreMouseEvents();
- setWindowTitle_helper(extra->topextra->caption);
- setWindowIconText_helper(extra->topextra->iconText);
- setWindowFilePath_helper(extra->topextra->filePath);
- setWindowModified_sys(q->isWindowModified());
- updateFrameStrut();
- qt_mac_update_sizer(q);
- applyMaxAndMinSizeOnWindow();
-}
-#else // QT_MAC_USE_COCOA
-
-void QWidgetPrivate::setWindowLevel()
-{
- Q_Q(QWidget);
- const QWidget * const windowParent = q->window()->parentWidget();
- const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
- NSInteger winLevel = -1;
-
- if (q->windowType() == Qt::Popup) {
- winLevel = NSPopUpMenuWindowLevel;
- // Popup should be in at least the same level as its parent.
- if (primaryWindow) {
- OSWindowRef parentRef = qt_mac_window_for(primaryWindow);
- winLevel = qMax([parentRef level], winLevel);
- }
- } else if (q->windowType() == Qt::Tool) {
- winLevel = NSFloatingWindowLevel;
- } else if (q->windowType() == Qt::Dialog) {
- // Correct modality level (NSModalPanelWindowLevel) will be
- // set by cocoa when creating a modal session later.
- winLevel = NSNormalWindowLevel;
- }
-
- // StayOnTop window should appear above Tool windows.
- if (data.window_flags & Qt::WindowStaysOnTopHint)
- winLevel = NSPopUpMenuWindowLevel;
- // Tooltips should appear above StayOnTop windows.
- if (q->windowType() == Qt::ToolTip)
- winLevel = NSScreenSaverWindowLevel;
- // All other types are Normal level.
- if (winLevel == -1)
- winLevel = NSNormalWindowLevel;
- [qt_mac_window_for(q) setLevel:winLevel];
-}
-
-void QWidgetPrivate::finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ voidWindowRef)
-{
- Q_Q(QWidget);
- QMacCocoaAutoReleasePool pool;
- NSWindow *windowRef = static_cast<NSWindow *>(voidWindowRef);
- const Qt::WindowType type = q->windowType();
- Qt::WindowFlags &flags = data.window_flags;
- QWidget *parentWidget = q->parentWidget();
-
- const bool popup = (type == Qt::Popup);
- const bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet
- || type == Qt::Drawer
- || (flags & Qt::MSWindowsFixedSizeDialogHint));
- QTLWExtra *topExtra = topData();
-
- if ((popup || type == Qt::Tool || type == Qt::ToolTip) && !q->isModal()) {
- [windowRef setHidesOnDeactivate:YES];
- } else {
- [windowRef setHidesOnDeactivate:NO];
- }
- if (q->testAttribute(Qt::WA_MacNoShadow))
- [windowRef setHasShadow:NO];
- else
- [windowRef setHasShadow:YES];
- Q_UNUSED(parentWidget);
- Q_UNUSED(dialog);
-
- data.fstrut_dirty = true; // when we create a toplevel widget, the frame strut should be dirty
-
- OSViewRef nsview = (OSViewRef)data.winid;
- if (!nsview) {
- nsview = qt_mac_create_widget(q, this, 0);
- setWinId(WId(nsview));
- }
- [windowRef setContentView:nsview];
- [nsview setHidden:NO];
- transferChildren();
-
- // Tell Cocoa explicit that we wan't the view to receive key events
- // (regardless of focus policy) because this is how it works on other
- // platforms (and in the carbon port):
- [windowRef makeFirstResponder:nsview];
-
- if (topExtra->posFromMove) {
- updateFrameStrut();
-
- const QRect &fStrut = frameStrut();
- const QRect &crect = data.crect;
- const QRect frameRect(QPoint(crect.left(), crect.top()),
- QSize(fStrut.left() + fStrut.right() + crect.width(),
- fStrut.top() + fStrut.bottom() + crect.height()));
- NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1),
- frameRect.width(), frameRect.height());
- [windowRef setFrame:cocoaFrameRect display:NO];
- topExtra->posFromMove = false;
- }
-
- if (q->testAttribute(Qt::WA_WState_WindowOpacitySet)){
- q->setWindowOpacity(topExtra->opacity / 255.0f);
- } else if (qt_mac_is_macsheet(q)){
- CGFloat alpha = [qt_mac_window_for(q) alphaValue];
- if (alpha >= 1.0) {
- q->setWindowOpacity(0.95f);
- q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
- }
- } else{
- // If the window has been recreated after beeing e.g. a sheet,
- // make sure that we don't report a faulty opacity:
- q->setWindowOpacity(1.0f);
- q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
- }
-
- // Its more performant to handle the mouse cursor
- // ourselves, expecially when using alien widgets:
- [windowRef disableCursorRects];
-
- setWindowLevel();
- macUpdateHideOnSuspend();
- macUpdateOpaqueSizeGrip();
- macUpdateIgnoreMouseEvents();
- setWindowTitle_helper(extra->topextra->caption);
- setWindowIconText_helper(extra->topextra->iconText);
- setWindowModified_sys(q->isWindowModified());
- updateFrameStrut();
- syncCocoaMask();
- macUpdateIsOpaque();
- qt_mac_update_sizer(q);
- applyMaxAndMinSizeOnWindow();
-}
-
-#endif // QT_MAC_USE_COCOA
-
-/*
- Recreates widget window. Useful if immutable
- properties for it has changed.
- */
-void QWidgetPrivate::recreateMacWindow()
-{
- Q_Q(QWidget);
- OSViewRef myView = qt_mac_nativeview_for(q);
- OSWindowRef oldWindow = qt_mac_window_for(myView);
-#ifndef QT_MAC_USE_COCOA
- HIViewRemoveFromSuperview(myView);
- determineWindowClass();
- createWindow_sys();
-
- if (QMainWindowLayout *mwl = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q))) {
- mwl->updateHIToolBarStatus();
- }
-
- if (IsWindowVisible(oldWindow))
- show_sys();
-#else
- QMacCocoaAutoReleasePool pool;
- [myView removeFromSuperview];
- determineWindowClass();
- createWindow_sys();
- if (NSToolbar *toolbar = [oldWindow toolbar]) {
- OSWindowRef newWindow = qt_mac_window_for(myView);
- [newWindow setToolbar:toolbar];
- [toolbar setVisible:[toolbar isVisible]];
- }
- if ([oldWindow isVisible]){
- if ([oldWindow isSheet])
- [NSApp endSheet:oldWindow];
- [oldWindow orderOut:oldWindow];
- show_sys();
- }
-#endif // QT_MAC_USE_COCOA
-
- // Release the window after creating the new window, because releasing it early
- // may cause the app to quit ("close on last window closed attribute")
- qt_mac_destructWindow(oldWindow);
-}
-
-void QWidgetPrivate::createWindow_sys()
-{
- Q_Q(QWidget);
- Qt::WindowFlags &flags = data.window_flags;
- QWidget *parentWidget = q->parentWidget();
-
- QTLWExtra *topExtra = topData();
- if (topExtra->embedded)
- return; // Simply return because this view "is" the top window.
- quint32 wattr = topExtra->wattr;
-
- if(parentWidget && (parentWidget->window()->windowFlags() & Qt::WindowStaysOnTopHint)) // If our parent has Qt::WStyle_StaysOnTop, so must we
- flags |= Qt::WindowStaysOnTopHint;
-
- data.fstrut_dirty = true;
-
- OSWindowRef windowRef = qt_mac_create_window(q, topExtra->wclass, wattr, data.crect);
- if (windowRef == 0)
- qWarning("QWidget: Internal error: %s:%d: If you reach this error please contact Qt Support and include the\n"
- " WidgetFlags used in creating the widget.", __FILE__, __LINE__);
-#ifndef QT_MAC_USE_COCOA
- finishCreateWindow_sys_Carbon(windowRef);
-#else
- finishCreateWindow_sys_Cocoa(windowRef);
-#endif
-}
-
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
-{
- Q_Q(QWidget);
- QMacCocoaAutoReleasePool pool;
-
- OSViewRef destroyid = 0;
-#ifndef QT_MAC_USE_COCOA
- window_event = 0;
-#endif
-
- Qt::WindowType type = q->windowType();
- Qt::WindowFlags flags = data.window_flags;
- QWidget *parentWidget = q->parentWidget();
-
- bool topLevel = (flags & Qt::Window);
- bool popup = (type == Qt::Popup);
- bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet
- || type == Qt::Drawer
- || (flags & Qt::MSWindowsFixedSizeDialogHint));
- bool desktop = (type == Qt::Desktop);
-
- // Determine this early for top-levels so, we can use it later.
- if (topLevel)
- determineWindowClass();
-
- if (desktop) {
- QSize desktopSize = qt_mac_desktopSize();
- q->setAttribute(Qt::WA_WState_Visible);
- data.crect.setRect(0, 0, desktopSize.width(), desktopSize.height());
- dialog = popup = false; // force these flags off
- } else {
- if (topLevel && (type != Qt::Drawer)) {
- if (QDesktopWidget *dsk = QApplication::desktop()) { // calc pos/size from screen
- const bool wasResized = q->testAttribute(Qt::WA_Resized);
- const bool wasMoved = q->testAttribute(Qt::WA_Moved);
- int deskn = dsk->primaryScreen();
- if (parentWidget && parentWidget->windowType() != Qt::Desktop)
- deskn = dsk->screenNumber(parentWidget);
- QRect screenGeo = dsk->screenGeometry(deskn);
- if (!wasResized) {
-#ifndef QT_MAC_USE_COCOA
- data.crect.setSize(QSize(screenGeo.width()/2, 4*screenGeo.height()/10));
-#else
- NSRect newRect = [NSWindow frameRectForContentRect:NSMakeRect(0, 0,
- screenGeo.width() / 2.,
- 4 * screenGeo.height() / 10.)
- styleMask:topData()->wattr];
- data.crect.setSize(QSize(newRect.size.width, newRect.size.height));
-#endif
- // Constrain to minimums and maximums we've set
- if (extra->minw > 0)
- data.crect.setWidth(qMax(extra->minw, data.crect.width()));
- if (extra->minh > 0)
- data.crect.setHeight(qMax(extra->minh, data.crect.height()));
- if (extra->maxw > 0)
- data.crect.setWidth(qMin(extra->maxw, data.crect.width()));
- if (extra->maxh > 0)
- data.crect.setHeight(qMin(extra->maxh, data.crect.height()));
- }
- if (!wasMoved && !q->testAttribute(Qt::WA_DontShowOnScreen))
- data.crect.moveTopLeft(QPoint(screenGeo.width()/4,
- 3 * screenGeo.height() / 10));
- }
- }
- }
-
-
- if(!window) // always initialize
- initializeWindow=true;
-
- hd = 0;
- if(window) { // override the old window (with a new NSView)
- OSViewRef nativeView = OSViewRef(window);
- OSViewRef parent = 0;
-#ifndef QT_MAC_USE_COCOA
- CFRetain(nativeView);
-#else
- [nativeView retain];
-#endif
- if (destroyOldWindow)
- destroyid = qt_mac_nativeview_for(q);
- bool transfer = false;
- setWinId((WId)nativeView);
-#ifndef QT_MAC_USE_COCOA
-#ifndef HIViewInstallEventHandler
- // Macro taken from the CarbonEvents Header on Tiger
-#define HIViewInstallEventHandler( target, handler, numTypes, list, userData, outHandlerRef ) \
- InstallEventHandler( HIObjectGetEventTarget( (HIObjectRef) (target) ), (handler), (numTypes), (list), (userData), (outHandlerRef) )
-#endif
- HIViewInstallEventHandler(nativeView, make_widget_eventUPP(), GetEventTypeCount(widget_events), widget_events, 0, 0);
-#endif
- if(topLevel) {
- for(int i = 0; i < 2; ++i) {
- if(i == 1) {
- if(!initializeWindow)
- break;
- createWindow_sys();
- }
- if(OSWindowRef windowref = qt_mac_window_for(nativeView)) {
-#ifndef QT_MAC_USE_COCOA
- CFRetain(windowref);
-#else
- [windowref retain];
-#endif
- if (initializeWindow) {
- parent = qt_mac_get_contentview_for(windowref);
- } else {
-#ifndef QT_MAC_USE_COCOA
- parent = HIViewGetSuperview(nativeView);
-#else
- parent = [nativeView superview];
-#endif
- }
- break;
- }
- }
- if(!parent)
- transfer = true;
- } else if (parentWidget) {
- // I need to be added to my parent, therefore my parent needs an NSView
- // Alien note: a 'window' was supplied as argument, meaning this widget
- // is not alien. So therefore the parent cannot be alien either.
- parentWidget->createWinId();
- parent = qt_mac_nativeview_for(parentWidget);
- }
- if(parent != nativeView && parent) {
-#ifndef QT_MAC_USE_COCOA
- HIViewAddSubview(parent, nativeView);
-#else
- [parent addSubview:nativeView];
-#endif
- }
- if(transfer)
- transferChildren();
- data.fstrut_dirty = true; // we'll re calculate this later
- q->setAttribute(Qt::WA_WState_Visible,
-#ifndef QT_MAC_USE_COCOA
- HIViewIsVisible(nativeView)
-#else
- ![nativeView isHidden]
-#endif
- );
- if(initializeWindow) {
-#ifndef QT_MAC_USE_COCOA
- HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
- HIViewSetFrame(nativeView, &bounds);
- q->setAttribute(Qt::WA_WState_Visible, HIViewIsVisible(nativeView));
-#else
- NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
- [nativeView setFrame:bounds];
- q->setAttribute(Qt::WA_WState_Visible, [nativeView isHidden]);
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- initWindowPtr();
-#endif
- } else if (desktop) { // desktop widget
- if (!qt_root_win)
- QWidgetPrivate::qt_create_root_win();
- Q_ASSERT(qt_root_win);
- WId rootWinID = 0;
-#ifndef QT_MAC_USE_COCOA
- CFRetain(qt_root_win);
- if(HIViewRef rootContentView = HIViewGetRoot(qt_root_win)) {
- rootWinID = (WId)rootContentView;
- CFRetain(rootContentView);
- }
-#else
- [qt_root_win retain];
- if (OSViewRef rootContentView = [qt_root_win contentView]) {
- rootWinID = (WId)rootContentView;
- [rootContentView retain];
- }
-#endif
- setWinId(rootWinID);
- } else if (topLevel) {
- determineWindowClass();
- if(OSViewRef osview = qt_mac_create_widget(q, this, 0)) {
-#ifndef QT_MAC_USE_COCOA
- HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(),
- data.crect.width(), data.crect.height());
- HIViewSetFrame(osview, &bounds);
-#else
- NSRect bounds = NSMakeRect(data.crect.x(), flipYCoordinate(data.crect.y()),
- data.crect.width(), data.crect.height());
- [osview setFrame:bounds];
-#endif
- setWinId((WId)osview);
- }
- } else {
- data.fstrut_dirty = false; // non-toplevel widgets don't have a frame, so no need to update the strut
-
-#ifdef QT_MAC_USE_COCOA
- if (q->testAttribute(Qt::WA_NativeWindow) == false || q->internalWinId() != 0) {
- // INVARIANT: q is Alien, and we should not create an NSView to back it up.
- } else
-#endif
- if (OSViewRef osview = qt_mac_create_widget(q, this, qt_mac_nativeview_for(parentWidget))) {
-#ifndef QT_MAC_USE_COCOA
- HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
- HIViewSetFrame(osview, &bounds);
- setWinId((WId)osview);
-#else
- NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
- [osview setFrame:bounds];
- setWinId((WId)osview);
- if (q->isVisible()) {
- // If q were Alien before, but now became native (e.g. if a call to
- // winId was done from somewhere), we need to show the view immidiatly:
- QMacCocoaAutoReleasePool pool;
- [osview setHidden:NO];
- }
-#endif
- }
- }
-
- updateIsOpaque();
-
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- registerDropSite(true);
- if (q->hasFocus())
- setFocus_sys();
- if (!topLevel && initializeWindow)
- setWSGeometry();
- if (destroyid)
- qt_mac_destructView(destroyid);
-}
-
-/*!
- Returns the QuickDraw handle of the widget. Use of this function is not
- portable. This function will return 0 if QuickDraw is not supported, or
- if the handle could not be created.
-
- \warning This function is only available on Mac OS X.
-*/
-
-Qt::HANDLE
-QWidget::macQDHandle() const
-{
-#ifndef QT_MAC_USE_COCOA
- return d_func()->qd_hd;
-#else
- return 0;
-#endif
-}
-
-/*!
- Returns the CoreGraphics handle of the widget. Use of this function is
- not portable. This function will return 0 if no painter context can be
- established, or if the handle could not be created.
-
- \warning This function is only available on Mac OS X.
-*/
-Qt::HANDLE
-QWidget::macCGHandle() const
-{
- return handle();
-}
-
-void qt_mac_repaintParentUnderAlienWidget(QWidget *alienWidget)
-{
- QWidget *nativeParent = alienWidget->nativeParentWidget();
- if (!nativeParent)
- return;
-
- QPoint globalPos = alienWidget->mapToGlobal(QPoint(0, 0));
- QRect dirtyRect = QRect(nativeParent->mapFromGlobal(globalPos), alienWidget->size());
- nativeParent->repaint(dirtyRect);
-}
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
- Q_D(QWidget);
- QMacCocoaAutoReleasePool pool;
- d->aboutToDestroy();
- if (!isWindow() && parentWidget())
- parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry()));
- if (!internalWinId())
- qt_mac_repaintParentUnderAlienWidget(this);
- d->deactivateWidgetCleanup();
- qt_mac_event_release(this);
- if(testAttribute(Qt::WA_WState_Created)) {
- setAttribute(Qt::WA_WState_Created, false);
- QObjectList chldrn = children();
- for(int i = 0; i < chldrn.size(); i++) { // destroy all widget children
- QObject *obj = chldrn.at(i);
- if(obj->isWidgetType())
- static_cast<QWidget*>(obj)->destroy(destroySubWindows, destroySubWindows);
- }
- if(mac_mouse_grabber == this)
- releaseMouse();
- if(mac_keyboard_grabber == this)
- releaseKeyboard();
-
- if(testAttribute(Qt::WA_ShowModal)) // just be sure we leave modal
- QApplicationPrivate::leaveModal(this);
- else if((windowType() == Qt::Popup))
- qApp->d_func()->closePopup(this);
- if (destroyWindow) {
- if(OSViewRef hiview = qt_mac_nativeview_for(this)) {
- OSWindowRef window = 0;
- NSDrawer *drawer = nil;
-#ifdef QT_MAC_USE_COCOA
- if (qt_mac_is_macdrawer(this)) {
- drawer = qt_mac_drawer_for(this);
- } else
-#endif
- if (isWindow())
- window = qt_mac_window_for(hiview);
-
- // Because of how "destruct" works, we have to do just a normal release for the root_win.
- if (window && window == qt_root_win) {
-#ifndef QT_MAC_USE_COCOA
- CFRelease(hiview);
-#else
- [hiview release];
-#endif
- } else {
- qt_mac_destructView(hiview);
- }
- if (drawer)
- qt_mac_destructDrawer(drawer);
- if (window)
- qt_mac_destructWindow(window);
- }
- }
- QT_TRY {
- d->setWinId(0);
- } QT_CATCH (const std::bad_alloc &) {
- // swallow - destructors must not throw
- }
- }
-}
-
-void QWidgetPrivate::transferChildren()
-{
- Q_Q(QWidget);
- if (!q->internalWinId())
- return; // Can't add any views anyway
-
- QObjectList chlist = q->children();
- for (int i = 0; i < chlist.size(); ++i) {
- QObject *obj = chlist.at(i);
- if (obj->isWidgetType()) {
- QWidget *w = (QWidget *)obj;
- if (!w->isWindow()) {
- // This seems weird, no need to call it in a loop right?
- if (!topData()->caption.isEmpty())
- setWindowTitle_helper(extra->topextra->caption);
- if (w->internalWinId()) {
-#ifndef QT_MAC_USE_COCOA
- HIViewAddSubview(qt_mac_nativeview_for(q), qt_mac_nativeview_for(w));
-#else
- // New NSWindows get an extra reference when drops are
- // registered (at least in 10.5) which means that we may
- // access the window later and get a crash (becasue our
- // widget is dead). Work around this be having the drop
- // site disabled until it is part of the new hierarchy.
- bool oldRegistered = w->testAttribute(Qt::WA_DropSiteRegistered);
- w->setAttribute(Qt::WA_DropSiteRegistered, false);
- [qt_mac_nativeview_for(w) retain];
- [qt_mac_nativeview_for(w) removeFromSuperview];
- [qt_mac_nativeview_for(q) addSubview:qt_mac_nativeview_for(w)];
- [qt_mac_nativeview_for(w) release];
- w->setAttribute(Qt::WA_DropSiteRegistered, oldRegistered);
-#endif
- }
- }
- }
- }
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QWidgetPrivate::setSubWindowStacking(bool set)
-{
- // After hitting too many unforeseen bugs trying to put Qt on top of the cocoa child
- // window API, we have decided to revert this behaviour as much as we can. We
- // therefore now only allow child windows to exist for children of modal dialogs.
- static bool use_behaviour_qt473 = !qgetenv("QT_MAC_USE_CHILDWINDOWS").isEmpty();
-
- // This will set/remove a visual relationship between parent and child on screen.
- // The reason for doing this is to ensure that a child always stacks infront of
- // its parent. Unfortunatly is turns out that [NSWindow addChildWindow] has
- // several unwanted side-effects, one of them being the moving of a child when
- // moving the parent, which we choose to accept. A way tougher side-effect is
- // that Cocoa will hide the parent if you hide the child. And in the case of
- // a tool window, since it will normally hide when you deactivate the
- // application, Cocoa will hide the parent upon deactivate as well. The result often
- // being no more visible windows on screen. So, to make a long story short, we only
- // allow parent-child relationships between windows that both are either a plain window
- // or a dialog.
-
- Q_Q(QWidget);
- if (!q->isWindow())
- return;
- NSWindow *qwin = [qt_mac_nativeview_for(q) window];
- if (!qwin)
- return;
- Qt::WindowType qtype = q->windowType();
- if (set && !(qtype == Qt::Window || qtype == Qt::Dialog))
- return;
- if (set && ![qwin isVisible])
- return;
-
- if (QWidget *parent = q->parentWidget()) {
- if (NSWindow *pwin = [qt_mac_nativeview_for(parent) window]) {
- if (set) {
- Qt::WindowType ptype = parent->window()->windowType();
- if ([pwin isVisible]
- && (ptype == Qt::Window || ptype == Qt::Dialog)
- && ![qwin parentWindow]
- && (use_behaviour_qt473 || parent->windowModality() == Qt::ApplicationModal)) {
- NSInteger level = [qwin level];
- [pwin addChildWindow:qwin ordered:NSWindowAbove];
- if ([qwin level] < level)
- [qwin setLevel:level];
- }
- } else {
- [pwin removeChildWindow:qwin];
- }
- }
- }
-
- // Only set-up child windows for q if q is modal:
- if (set && !use_behaviour_qt473 && q->windowModality() != Qt::ApplicationModal)
- return;
-
- QObjectList widgets = q->children();
- for (int i=0; i<widgets.size(); ++i) {
- QWidget *child = qobject_cast<QWidget *>(widgets.at(i));
- if (child && child->isWindow()) {
- if (NSWindow *cwin = [qt_mac_nativeview_for(child) window]) {
- if (set) {
- Qt::WindowType ctype = child->window()->windowType();
- if ([cwin isVisible] && (ctype == Qt::Window || ctype == Qt::Dialog) && ![cwin parentWindow]) {
- NSInteger level = [cwin level];
- [qwin addChildWindow:cwin ordered:NSWindowAbove];
- if ([cwin level] < level)
- [cwin setLevel:level];
- }
- } else {
- [qwin removeChildWindow:qt_mac_window_for(child)];
- }
- }
- }
- }
-}
-#endif
-
-void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
-{
- Q_Q(QWidget);
- QMacCocoaAutoReleasePool pool;
- QTLWExtra *topData = maybeTopData();
- bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
-#ifdef QT_MAC_USE_COCOA
- bool wasWindow = q->isWindow();
-#endif
- OSViewRef old_id = 0;
-
- if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
- q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
-
- // Maintain the glWidgets list on parent change: remove "our" gl widgets
- // from the list on the old parent and grandparents.
- if (glWidgets.isEmpty() == false) {
- QWidget *current = q->parentWidget();
- while (current) {
- for (QList<QWidgetPrivate::GlWidgetInfo>::const_iterator it = glWidgets.constBegin();
- it != glWidgets.constEnd(); ++it)
- current->d_func()->glWidgets.removeAll(*it);
-
- if (current->isWindow())
- break;
- current = current->parentWidget();
- }
- }
-
-#ifndef QT_MAC_USE_COCOA
- EventHandlerRef old_window_event = 0;
-#else
- bool oldToolbarVisible = false;
- NSDrawer *oldDrawer = nil;
- NSToolbar *oldToolbar = 0;
-#endif
- if (wasCreated && !(q->windowType() == Qt::Desktop)) {
- old_id = qt_mac_nativeview_for(q);
-#ifndef QT_MAC_USE_COCOA
- old_window_event = window_event;
-#else
- if (qt_mac_is_macdrawer(q)) {
- oldDrawer = qt_mac_drawer_for(q);
- }
- if (wasWindow) {
- OSWindowRef oldWindow = qt_mac_window_for(old_id);
- oldToolbar = [oldWindow toolbar];
- if (oldToolbar) {
- [oldToolbar retain];
- oldToolbarVisible = [oldToolbar isVisible];
- [oldWindow setToolbar:nil];
- }
- }
-#endif
- }
- QWidget* oldtlw = q->window();
-
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- q->setAttribute(Qt::WA_DropSiteRegistered, false);
-
- //recreate and setup flags
- QObjectPrivate::setParent_helper(parent);
- bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
- if (wasCreated && !qt_isGenuineQWidget(q))
- return;
-
- if (!q->testAttribute(Qt::WA_WState_WindowOpacitySet)) {
- q->setWindowOpacity(1.0f);
- q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
- }
-
- setWinId(0); //do after the above because they may want the id
-
- data.window_flags = f;
- q->setAttribute(Qt::WA_WState_Created, false);
- q->setAttribute(Qt::WA_WState_Visible, false);
- q->setAttribute(Qt::WA_WState_Hidden, false);
- adjustFlags(data.window_flags, q);
- // keep compatibility with previous versions, we need to preserve the created state.
- // (but we recreate the winId for the widget being reparented, again for compatibility,
- // unless this is an alien widget. )
- const bool nonWindowWithCreatedParent = !q->isWindow() && parent->testAttribute(Qt::WA_WState_Created);
- const bool nativeWidget = q->internalWinId() != 0;
- if (wasCreated || (nativeWidget && nonWindowWithCreatedParent)) {
- createWinId();
- if (q->isWindow()) {
-#ifndef QT_MAC_USE_COCOA
- // We do this down below for wasCreated, so avoid doing this twice
- // (only for performance, it gets called a lot anyway).
- if (!wasCreated) {
- if (QMainWindowLayout *mwl = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q))) {
- mwl->updateHIToolBarStatus();
- }
- }
-#else
- // Simply transfer our toolbar over. Everything should stay put, unlike in Carbon.
- if (oldToolbar && !(f & Qt::FramelessWindowHint)) {
- OSWindowRef newWindow = qt_mac_window_for(q);
- [newWindow setToolbar:oldToolbar];
- [oldToolbar release];
- [oldToolbar setVisible:oldToolbarVisible];
- }
-#endif
- }
- }
- if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
- q->setAttribute(Qt::WA_WState_Hidden);
- q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
- if (wasCreated) {
- transferChildren();
-#ifndef QT_MAC_USE_COCOA
- // If we were a unified window, We just transfered our toolbars out of the unified toolbar.
- // So redo the status one more time. It apparently is not an issue with Cocoa.
- if (q->isWindow()) {
- if (QMainWindowLayout *mwl = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q))) {
- mwl->updateHIToolBarStatus();
- }
- }
-#endif
-
- if (topData &&
- (!topData->caption.isEmpty() || !topData->filePath.isEmpty()))
- setWindowTitle_helper(q->windowTitle());
- }
-
- if (q->testAttribute(Qt::WA_AcceptDrops)
- || (!q->isWindow() && q->parentWidget()
- && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
- q->setAttribute(Qt::WA_DropSiteRegistered, true);
-
- //cleanup
-#ifndef QT_MAC_USE_COCOA
- if (old_window_event)
- RemoveEventHandler(old_window_event);
-#endif
- if (old_id) { //don't need old window anymore
- OSWindowRef window = (oldtlw == q) ? qt_mac_window_for(old_id) : 0;
- qt_mac_destructView(old_id);
-
-#ifdef QT_MAC_USE_COCOA
- if (oldDrawer) {
- qt_mac_destructDrawer(oldDrawer);
- } else
-#endif
- if (window)
- qt_mac_destructWindow(window);
- }
-
- // Maintain the glWidgets list on parent change: add "our" gl widgets
- // to the list on the new parent and grandparents.
- if (glWidgets.isEmpty() == false) {
- QWidget *current = q->parentWidget();
- while (current) {
- current->d_func()->glWidgets += glWidgets;
- if (current->isWindow())
- break;
- current = current->parentWidget();
- }
- }
- invalidateBuffer(q->rect());
- qt_event_request_window_change(q);
-}
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- if (!internalWinId()) {
- QPoint p = pos + data->crect.topLeft();
- return isWindow() ? p : parentWidget()->mapToGlobal(p);
- }
-#ifndef QT_MAC_USE_COCOA
- QPoint tmp = d->mapToWS(pos);
- HIPoint hi_pos = CGPointMake(tmp.x(), tmp.y());
- HIViewConvertPoint(&hi_pos, qt_mac_nativeview_for(this), 0);
- Rect win_rect;
- GetWindowBounds(qt_mac_window_for(this), kWindowStructureRgn, &win_rect);
- return QPoint((int)hi_pos.x+win_rect.left, (int)hi_pos.y+win_rect.top);
-#else
- QPoint tmp = d->mapToWS(pos);
- NSPoint hi_pos = NSMakePoint(tmp.x(), tmp.y());
- hi_pos = [qt_mac_nativeview_for(this) convertPoint:hi_pos toView:nil];
- NSRect win_rect = [qt_mac_window_for(this) frame];
- hi_pos.x += win_rect.origin.x;
- hi_pos.y += win_rect.origin.y;
- // If we aren't the desktop we need to flip, if you flip the desktop on itself, you get the other problem.
- return ((window()->windowFlags() & Qt::Desktop) == Qt::Desktop) ? QPointF(hi_pos.x, hi_pos.y).toPoint()
- : flipPoint(hi_pos).toPoint();
-#endif
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- if (!internalWinId()) {
- QPoint p = isWindow() ? pos : parentWidget()->mapFromGlobal(pos);
- return p - data->crect.topLeft();
- }
-#ifndef QT_MAC_USE_COCOA
- Rect win_rect;
- GetWindowBounds(qt_mac_window_for(this), kWindowStructureRgn, &win_rect);
- HIPoint hi_pos = CGPointMake(pos.x()-win_rect.left, pos.y()-win_rect.top);
- HIViewConvertPoint(&hi_pos, 0, qt_mac_nativeview_for(this));
- return d->mapFromWS(QPoint((int)hi_pos.x, (int)hi_pos.y));
-#else
- NSRect win_rect = [qt_mac_window_for(this) frame];
- // The Window point is in "Cocoa coordinates," but the view is in "Qt coordinates"
- // so make sure to keep them in sync.
- NSPoint hi_pos = NSMakePoint(pos.x()-win_rect.origin.x,
- flipYCoordinate(pos.y())-win_rect.origin.y);
- hi_pos = [qt_mac_nativeview_for(this) convertPoint:hi_pos fromView:0];
- return d->mapFromWS(QPoint(qRound(hi_pos.x), qRound(hi_pos.y)));
-#endif
-}
-
-void QWidgetPrivate::updateSystemBackground()
-{
-}
-
-void QWidgetPrivate::setCursor_sys(const QCursor &)
-{
- qt_mac_update_cursor();
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
- qt_mac_update_cursor();
-}
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
- Q_Q(QWidget);
- if (q->isWindow()) {
-#ifndef QT_MAC_USE_COCOA
- SetWindowTitleWithCFString(qt_mac_window_for(q), QCFString(caption));
-#else
- QMacCocoaAutoReleasePool pool;
- [qt_mac_window_for(q) setTitle:qt_mac_QStringToNSString(caption)];
-#endif
- }
-}
-
-void QWidgetPrivate::setWindowModified_sys(bool mod)
-{
- Q_Q(QWidget);
- if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) {
-#ifndef QT_MAC_USE_COCOA
- SetWindowModified(qt_mac_window_for(q), mod);
-#else
- [qt_mac_window_for(q) setDocumentEdited:mod];
-#endif
- }
-}
-
-void QWidgetPrivate::setWindowFilePath_sys(const QString &filePath)
-{
- Q_Q(QWidget);
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- QFileInfo fi(filePath);
- [qt_mac_window_for(q) setRepresentedFilename:fi.exists() ? qt_mac_QStringToNSString(filePath) : @""];
-#else
- bool validRef = false;
- FSRef ref;
- bzero(&ref, sizeof(ref));
- OSStatus status;
-
- if (!filePath.isEmpty()) {
- status = FSPathMakeRef(reinterpret_cast<const UInt8 *>(filePath.toUtf8().constData()), &ref, 0);
- validRef = (status == noErr);
- }
- // Set the proxy regardless, since this is our way of clearing it as well, but ignore the
- // return value as well.
- if (validRef) {
- status = HIWindowSetProxyFSRef(qt_mac_window_for(q), &ref);
- } else {
- status = RemoveWindowProxy(qt_mac_window_for(q));
- }
- if (status != noErr)
- qWarning("QWidget::setWindowFilePath: Error setting proxyicon for path (%s):%ld",
- qPrintable(filePath), status);
-#endif
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
-{
- Q_Q(QWidget);
-
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-
- QTLWExtra *topData = this->topData();
- if (topData->iconPixmap && !forceReset) // already set
- return;
-
- QIcon icon = q->windowIcon();
- QPixmap *pm = 0;
- if (!icon.isNull()) {
- // now create the extra
- if (!topData->iconPixmap) {
- pm = new QPixmap(icon.pixmap(QSize(22, 22)));
- topData->iconPixmap = pm;
- } else {
- pm = topData->iconPixmap;
- }
- }
- if (q->isWindow()) {
-#ifndef QT_MAC_USE_COCOA
- IconRef previousIcon = 0;
- if (icon.isNull()) {
- RemoveWindowProxy(qt_mac_window_for(q));
- previousIcon = topData->windowIcon;
- topData->windowIcon = 0;
- } else {
- WindowClass wclass;
- GetWindowClass(qt_mac_window_for(q), &wclass);
-
- if (wclass == kDocumentWindowClass) {
- IconRef newIcon = qt_mac_create_iconref(*pm);
- previousIcon = topData->windowIcon;
- topData->windowIcon = newIcon;
- SetWindowProxyIcon(qt_mac_window_for(q), newIcon);
- }
- }
-
- // Release the previous icon if it was set by this function.
- if (previousIcon != 0)
- ReleaseIconRef(previousIcon);
-#else
- QMacCocoaAutoReleasePool pool;
- if (icon.isNull())
- return;
- NSButton *iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
- if (iconButton == nil) {
- QCFString string(q->windowTitle());
- const NSString *tmpString = reinterpret_cast<const NSString *>((CFStringRef)string);
- [qt_mac_window_for(q) setRepresentedURL:[NSURL fileURLWithPath:const_cast<NSString *>(tmpString)]];
- iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
- }
- if (icon.isNull()) {
- [iconButton setImage:nil];
- } else {
- QPixmap scaled = pm->scaled(QSize(16,16), Qt::KeepAspectRatio, Qt::SmoothTransformation);
- NSImage *image = static_cast<NSImage *>(qt_mac_create_nsimage(scaled));
- [iconButton setImage:image];
- [image release];
- }
-#endif
- }
-}
-
-void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
-{
- Q_Q(QWidget);
- if(q->isWindow() && !iconText.isEmpty()) {
-#ifndef QT_MAC_USE_COCOA
- SetWindowAlternateTitle(qt_mac_window_for(q), QCFString(iconText));
-#else
- QMacCocoaAutoReleasePool pool;
- [qt_mac_window_for(q) setMiniwindowTitle:qt_mac_QStringToNSString(iconText)];
-#endif
- }
-}
-
-void QWidget::grabMouse()
-{
- if(isVisible() && !qt_nograb()) {
- if(mac_mouse_grabber)
- mac_mouse_grabber->releaseMouse();
- mac_mouse_grabber=this;
- qt_mac_setMouseGrabCursor(true);
- }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
- if(isVisible() && !qt_nograb()) {
- if(mac_mouse_grabber)
- mac_mouse_grabber->releaseMouse();
- mac_mouse_grabber=this;
- qt_mac_setMouseGrabCursor(true, const_cast<QCursor *>(&cursor));
- }
-}
-#endif
-
-void QWidget::releaseMouse()
-{
- if(!qt_nograb() && mac_mouse_grabber == this) {
- mac_mouse_grabber = 0;
- qt_mac_setMouseGrabCursor(false);
- }
-}
-
-void QWidget::grabKeyboard()
-{
- if(!qt_nograb()) {
- if(mac_keyboard_grabber)
- mac_keyboard_grabber->releaseKeyboard();
- mac_keyboard_grabber = this;
- }
-}
-
-void QWidget::releaseKeyboard()
-{
- if(!qt_nograb() && mac_keyboard_grabber == this)
- mac_keyboard_grabber = 0;
-}
-
-QWidget *QWidget::mouseGrabber()
-{
- return mac_mouse_grabber;
-}
-
-QWidget *QWidget::keyboardGrabber()
-{
- return mac_keyboard_grabber;
-}
-
-void QWidget::activateWindow()
-{
- QWidget *tlw = window();
- if(!tlw->isVisible() || !tlw->isWindow() || (tlw->windowType() == Qt::Desktop))
- return;
- qt_event_remove_activate();
-
- QWidget *fullScreenWidget = tlw;
- QWidget *parentW = tlw;
- // Find the oldest parent or the parent with fullscreen, whichever comes first.
- while (parentW) {
- fullScreenWidget = parentW->window();
- if (fullScreenWidget->windowState() & Qt::WindowFullScreen)
- break;
- parentW = fullScreenWidget->parentWidget();
- }
-
- if (fullScreenWidget->windowType() != Qt::ToolTip) {
- qt_mac_set_fullscreen_mode((fullScreenWidget->windowState() & Qt::WindowFullScreen) &&
- qApp->desktop()->screenNumber(this) == 0);
- }
-
- bool windowActive;
- OSWindowRef win = qt_mac_window_for(tlw);
-#ifndef QT_MAC_USE_COCOA
- windowActive = IsWindowActive(win);
-#else
- QMacCocoaAutoReleasePool pool;
- windowActive = [win isKeyWindow];
-#endif
- if ((tlw->windowType() == Qt::Popup)
- || (tlw->windowType() == Qt::Tool)
- || qt_mac_is_macdrawer(tlw)
- || windowActive) {
-#ifndef QT_MAC_USE_COCOA
- ActivateWindow(win, true);
- qApp->setActiveWindow(tlw);
-#else
- [win makeKeyWindow];
-#endif
- } else if(!isMinimized()) {
-#ifndef QT_MAC_USE_COCOA
- SelectWindow(win);
-#else
- [win makeKeyAndOrderFront:win];
-#endif
- }
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
- return new QMacWindowSurface(q_func());
-}
-
-void QWidgetPrivate::update_sys(const QRect &r)
-{
- Q_Q(QWidget);
- if (updateRedirectedToGraphicsProxyWidget(q, r))
- return;
- dirtyOnWidget += r;
- macSetNeedsDisplay(r != q->rect() ? r : QRegion());
-}
-
-void QWidgetPrivate::update_sys(const QRegion &rgn)
-{
- Q_Q(QWidget);
- if (updateRedirectedToGraphicsProxyWidget(q, rgn))
- return;
- dirtyOnWidget += rgn;
- macSetNeedsDisplay(rgn);
-}
-
-bool QWidgetPrivate::isRealWindow() const
-{
- return q_func()->isWindow() && !topData()->embedded;
-}
-
-void QWidgetPrivate::show_sys()
-{
- Q_Q(QWidget);
- if ((q->windowType() == Qt::Desktop)) //desktop is always visible
- return;
-
- invalidateBuffer(q->rect());
- if (q->testAttribute(Qt::WA_OutsideWSRange))
- return;
- QMacCocoaAutoReleasePool pool;
- q->setAttribute(Qt::WA_Mapped);
- if (q->testAttribute(Qt::WA_DontShowOnScreen))
- return;
-
- bool realWindow = isRealWindow();
-#ifndef QT_MAC_USE_COCOA
- if (realWindow && !q->testAttribute(Qt::WA_Moved)) {
- if (qt_mac_is_macsheet(q))
- recreateMacWindow();
- q->createWinId();
- if (QWidget *p = q->parentWidget()) {
- p->createWinId();
- RepositionWindow(qt_mac_window_for(q), qt_mac_window_for(p), kWindowCenterOnParentWindow);
- } else {
- RepositionWindow(qt_mac_window_for(q), 0, kWindowCenterOnMainScreen);
- }
- }
-#endif
-
- data.fstrut_dirty = true;
- if (realWindow) {
- bool isCurrentlyMinimized = (q->windowState() & Qt::WindowMinimized);
- setModal_sys();
- OSWindowRef window = qt_mac_window_for(q);
-#ifndef QT_MAC_USE_COCOA
- SizeWindow(window, q->width(), q->height(), true);
-#endif
-
-#ifdef QT_MAC_USE_COCOA
- // Make sure that we end up sending a repaint event to
- // the widget if the window has been visible one before:
- [qt_mac_get_contentview_for(window) setNeedsDisplay:YES];
-#endif
- if(qt_mac_is_macsheet(q)) {
- qt_event_request_showsheet(q);
- } else if(qt_mac_is_macdrawer(q)) {
-#ifndef QT_MAC_USE_COCOA
- OpenDrawer(window, kWindowEdgeDefault, false);
-#else
- NSDrawer *drawer = qt_mac_drawer_for(q);
- [drawer openOnEdge:[drawer preferredEdge]];
-#endif
- } else {
-#ifndef QT_MAC_USE_COCOA
- ShowHide(window, true);
-#else
- // sync the opacity value back (in case of a fade).
- [window setAlphaValue:q->windowOpacity()];
-
- QWidget *top = 0;
- if (QApplicationPrivate::tryModalHelper(q, &top)) {
- [window makeKeyAndOrderFront:window];
- // If this window is app modal, we need to start spinning
- // a modal session for it. Interrupting
- // the event dispatcher will make this happend:
- if (data.window_modality == Qt::ApplicationModal)
- QEventDispatcherMac::instance()->interrupt();
- } else {
- // The window is modally shaddowed, so we need to make
- // sure that we don't pop in front of the modal window:
- [window orderFront:window];
- if (!top->testAttribute(Qt::WA_DontShowOnScreen)) {
- if (NSWindow *modalWin = qt_mac_window_for(top))
- [modalWin orderFront:window];
- }
- }
- setSubWindowStacking(true);
- qt_mac_update_cursor();
-#endif
- if (q->windowType() == Qt::Popup) {
- qt_button_down = 0;
- if (q->focusWidget())
- q->focusWidget()->d_func()->setFocus_sys();
- else
- setFocus_sys();
- }
- toggleDrawers(true);
- }
- if (isCurrentlyMinimized) { //show in collapsed state
-#ifndef QT_MAC_USE_COCOA
- CollapseWindow(window, true);
-#else
- [window miniaturize:window];
-#endif
- } else if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
-#ifndef QT_MAC_USE_COCOA
- qt_event_request_activate(q);
-#endif
- }
- } else if(topData()->embedded || !q->parentWidget() || q->parentWidget()->isVisible()) {
-#ifndef QT_MAC_USE_COCOA
- HIViewSetVisible(qt_mac_nativeview_for(q), true);
-#else
- if (NSView *view = qt_mac_nativeview_for(q)) {
- // INVARIANT: q is native. Just show the view:
- [view setHidden:NO];
- } else {
- // INVARIANT: q is alien. Repaint q instead:
- q->repaint();
- }
-#endif
- }
-
-#ifdef QT_MAC_USE_COCOA
- if ([NSApp isActive] && !qt_button_down && !QWidget::mouseGrabber()){
- // Update enter/leave immidiatly, don't wait for a move event. But only
- // if no grab exists (even if the grab points to this widget, it seems, ref X11)
- QPoint qlocal, qglobal;
- QWidget *widgetUnderMouse = 0;
- qt_mac_getTargetForMouseEvent(0, QEvent::Enter, qlocal, qglobal, 0, &widgetUnderMouse);
- QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, qt_last_mouse_receiver);
- qt_last_mouse_receiver = widgetUnderMouse;
- qt_last_native_mouse_receiver = widgetUnderMouse ?
- (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
- }
-#endif
-
- topLevelAt_cache = 0;
- qt_event_request_window_change(q);
-}
-
-QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt)
-{
-#ifndef QT_MAC_USE_COCOA
- CGPoint nativePoint = CGPointMake(pt.x(), pt.y());
- HIViewConvertPoint(&nativePoint, qt_mac_nativeview_for(child->parentWidget()),
- qt_mac_nativeview_for(child));
-#else
- NSPoint nativePoint = [qt_mac_nativeview_for(child) convertPoint:NSMakePoint(pt.x(), pt.y()) fromView:qt_mac_nativeview_for(child->parentWidget())];
-#endif
- return QPoint(nativePoint.x, nativePoint.y);
-}
-
-
-void QWidgetPrivate::hide_sys()
-{
- Q_Q(QWidget);
- if((q->windowType() == Qt::Desktop)) //you can't hide the desktop!
- return;
- QMacCocoaAutoReleasePool pool;
- if(q->isWindow()) {
-#ifdef QT_MAC_USE_COCOA
- setSubWindowStacking(false);
-#endif
- OSWindowRef window = qt_mac_window_for(q);
- if(qt_mac_is_macsheet(q)) {
-#ifndef QT_MAC_USE_COCOA
- WindowRef parent = 0;
- if(GetSheetWindowParent(window, &parent) != noErr || !parent)
- ShowHide(window, false);
- else
- HideSheetWindow(window);
-#else
- [NSApp endSheet:window];
- [window orderOut:window];
-#endif
- } else if(qt_mac_is_macdrawer(q)) {
-#ifndef QT_MAC_USE_COCOA
- CloseDrawer(window, false);
-#else
- [qt_mac_drawer_for(q) close];
-#endif
- } else {
-#ifndef QT_MAC_USE_COCOA
- ShowHide(window, false);
-#else
- [window orderOut:window];
- // Unfortunately it is not as easy as just hiding the window, we need
- // to find out if we were in full screen mode. If we were and this is
- // the last window in full screen mode then we need to unset the full screen
- // mode. If this is not the last visible window in full screen mode then we
- // don't change the full screen mode.
- if(q->isFullScreen())
- {
- bool keepFullScreen = false;
- QWidgetList windowList = qApp->topLevelWidgets();
- int windowCount = windowList.count();
- for(int i = 0; i < windowCount; i++)
- {
- QWidget *w = windowList[i];
- // If it is the same window, we don't need to check :-)
- if(q == w)
- continue;
- // If they are not visible or if they are minimized then
- // we just ignore them.
- if(!w->isVisible() || w->isMinimized())
- continue;
- // Is it full screen?
- // Notice that if there is one window in full screen mode then we
- // cannot switch the full screen mode off, therefore we just abort.
- if(w->isFullScreen()) {
- keepFullScreen = true;
- break;
- }
- }
- // No windows in full screen mode, so let just unset that flag.
- if(!keepFullScreen)
- qt_mac_set_fullscreen_mode(false);
- }
-#endif
- toggleDrawers(false);
- qt_mac_update_cursor();
-#ifndef QT_MAC_USE_COCOA
- // Clear modality (because it seems something that we've always done).
- if (data.window_modality != Qt::NonModal) {
- SetWindowModality(window, kWindowModalityNone,
- q->parentWidget() ? qt_mac_window_for(q->parentWidget()->window()) : 0);
- }
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- // If the window we now hide was the active window, we need
- // to find, and activate another window on screen. NB: Cocoa takes care of this
- // logic for us (and distinquishes between main windows and key windows)
- if (q->isActiveWindow() && !(q->windowType() == Qt::Popup)) {
- QWidget *w = 0;
- if(q->parentWidget())
- w = q->parentWidget()->window();
- if(!w || (!w->isVisible() && !w->isMinimized())) {
- for (WindowPtr wp = GetFrontWindowOfClass(kMovableModalWindowClass, true);
- wp; wp = GetNextWindowOfClass(wp, kMovableModalWindowClass, true)) {
- if((w = qt_mac_find_window(wp)))
- break;
- }
- if (!w){
- for (WindowPtr wp = GetFrontWindowOfClass(kDocumentWindowClass, true);
- wp; wp = GetNextWindowOfClass(wp, kDocumentWindowClass, true)) {
- if((w = qt_mac_find_window(wp)))
- break;
- }
- }
- if (!w){
- for(WindowPtr wp = GetFrontWindowOfClass(kSimpleWindowClass, true);
- wp; wp = GetNextWindowOfClass(wp, kSimpleWindowClass, true)) {
- if((w = qt_mac_find_window(wp)))
- break;
- }
- }
- }
- if(w && w->isVisible() && !w->isMinimized()) {
- qt_event_request_activate(w);
- }
- }
-#endif
- } else {
- invalidateBuffer(q->rect());
-#ifndef QT_MAC_USE_COCOA
- HIViewSetVisible(qt_mac_nativeview_for(q), false);
-#else
- if (NSView *view = qt_mac_nativeview_for(q)) {
- // INVARIANT: q is native. Just hide the view:
- [view setHidden:YES];
- } else {
- // INVARIANT: q is alien. Repaint where q is placed instead:
- qt_mac_repaintParentUnderAlienWidget(q);
- }
-#endif
- }
-
-#ifdef QT_MAC_USE_COCOA
- if ([NSApp isActive] && !qt_button_down && !QWidget::mouseGrabber()){
- // Update enter/leave immidiatly, don't wait for a move event. But only
- // if no grab exists (even if the grab points to this widget, it seems, ref X11)
- QPoint qlocal, qglobal;
- QWidget *widgetUnderMouse = 0;
- qt_mac_getTargetForMouseEvent(0, QEvent::Leave, qlocal, qglobal, 0, &widgetUnderMouse);
- QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, qt_last_native_mouse_receiver);
- qt_last_mouse_receiver = widgetUnderMouse;
- qt_last_native_mouse_receiver = widgetUnderMouse ?
- (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
- }
-#endif
-
- topLevelAt_cache = 0;
- qt_event_request_window_change(q);
- deactivateWidgetCleanup();
- qt_mac_event_release(q);
-}
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
- Q_D(QWidget);
- bool needShow = false;
- Qt::WindowStates oldstate = windowState();
- if (oldstate == newstate)
- return;
-
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
-#endif
- bool needSendStateChange = true;
- if(isWindow()) {
- if((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
- if(newstate & Qt::WindowFullScreen) {
- if(QTLWExtra *tlextra = d->topData()) {
- if(tlextra->normalGeometry.width() < 0) {
- if(!testAttribute(Qt::WA_Resized))
- adjustSize();
- tlextra->normalGeometry = geometry();
- }
- tlextra->savedFlags = windowFlags();
- }
- needShow = isVisible();
- const QRect fullscreen(qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(this)));
- setParent(parentWidget(), Qt::Window | Qt::FramelessWindowHint | (windowFlags() & 0xffff0000)); //save
- setGeometry(fullscreen);
- if(!qApp->desktop()->screenNumber(this))
- qt_mac_set_fullscreen_mode(true);
- } else {
- needShow = isVisible();
- if(!qApp->desktop()->screenNumber(this))
- qt_mac_set_fullscreen_mode(false);
- setParent(parentWidget(), d->topData()->savedFlags);
- setGeometry(d->topData()->normalGeometry);
- d->topData()->normalGeometry.setRect(0, 0, -1, -1);
- }
- }
-
- d->createWinId();
-
- OSWindowRef window = qt_mac_window_for(this);
- if((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
- if (newstate & Qt::WindowMinimized) {
-#ifndef QT_MAC_USE_COCOA
- CollapseWindow(window, true);
-#else
- [window miniaturize:window];
-#endif
- } else {
-#ifndef QT_MAC_USE_COCOA
- CollapseWindow(window, false);
-#else
- [window deminiaturize:window];
-#endif
- }
- needSendStateChange = oldstate == windowState(); // Collapse didn't change our flags.
- }
-
- if((newstate & Qt::WindowMaximized) && !((newstate & Qt::WindowFullScreen))) {
- if(QTLWExtra *tlextra = d->topData()) {
- if(tlextra->normalGeometry.width() < 0) {
- if(!testAttribute(Qt::WA_Resized))
- adjustSize();
- tlextra->normalGeometry = geometry();
- }
- }
- } else if(!(newstate & Qt::WindowFullScreen)) {
-// d->topData()->normalGeometry = QRect(0, 0, -1, -1);
- }
-
-#ifdef DEBUG_WINDOW_STATE
-#define WSTATE(x) qDebug("%s -- %s --> %s", #x, (oldstate & x) ? "true" : "false", (newstate & x) ? "true" : "false")
- WSTATE(Qt::WindowMinimized);
- WSTATE(Qt::WindowMaximized);
- WSTATE(Qt::WindowFullScreen);
-#undef WSTATE
-#endif
- if(!(newstate & (Qt::WindowMinimized|Qt::WindowFullScreen)) &&
- ((oldstate & Qt::WindowFullScreen) || (oldstate & Qt::WindowMinimized) ||
- (oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized))) {
- if(newstate & Qt::WindowMaximized) {
- data->fstrut_dirty = true;
-#ifndef QT_MAC_USE_COCOA
- HIToolbarRef toolbarRef;
- if (GetWindowToolbar(window, &toolbarRef) == noErr && toolbarRef
- && !isVisible() && !IsWindowToolbarVisible(window)) {
- // HIToolbar, needs to be shown so that it's in the structure window
- // Typically this is part of a main window and will get shown
- // during the show, but it's will make the maximize all wrong.
- ShowHideWindowToolbar(window, true, false);
- d->updateFrameStrut(); // In theory the dirty would work, but it's optimized out if the window is not visible :(
- }
- Rect bounds;
- QDesktopWidget *dsk = QApplication::desktop();
- QRect avail = dsk->availableGeometry(dsk->screenNumber(this));
- SetRect(&bounds, avail.x(), avail.y(), avail.x() + avail.width(), avail.y() + avail.height());
- if(QWExtra *extra = d->extraData()) {
- if(bounds.right - bounds.left > extra->maxw)
- bounds.right = bounds.left + extra->maxw;
- if(bounds.bottom - bounds.top > extra->maxh)
- bounds.bottom = bounds.top + extra->maxh;
- }
- if(d->topData()) {
- QRect fs = d->frameStrut();
- bounds.left += fs.left();
- if(bounds.right < avail.x()+avail.width())
- bounds.right = qMin<short>((uint)avail.x()+avail.width(), bounds.right+fs.left());
- if(bounds.bottom < avail.y()+avail.height())
- bounds.bottom = qMin<short>((uint)avail.y()+avail.height(), bounds.bottom+fs.top());
- bounds.top += fs.top();
- bounds.right -= fs.right();
- bounds.bottom -= fs.bottom();
- }
- QRect orect(geometry().x(), geometry().y(), width(), height()),
- nrect(bounds.left, bounds.top, bounds.right - bounds.left,
- bounds.bottom - bounds.top);
- if(orect != nrect) { // the new rect differ from the old
- Point idealSize = { nrect.height(), nrect.width() };
- ZoomWindowIdeal(window, inZoomOut, &idealSize);
- }
-#else
- NSToolbar *toolbarRef = [window toolbar];
- if (toolbarRef && !isVisible() && ![toolbarRef isVisible]) {
- // HIToolbar, needs to be shown so that it's in the structure window
- // Typically this is part of a main window and will get shown
- // during the show, but it's will make the maximize all wrong.
- // ### Not sure this is right for NSToolbar...
- [toolbarRef setVisible:true];
-// ShowHideWindowToolbar(window, true, false);
- d->updateFrameStrut(); // In theory the dirty would work, but it's optimized out if the window is not visible :(
- }
- // Everything should be handled by Cocoa.
- [window zoom:window];
-#endif
- needSendStateChange = oldstate == windowState(); // Zoom didn't change flags.
- } else if(oldstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen)) {
-#ifndef QT_MAC_USE_COCOA
- Point idealSize;
- ZoomWindowIdeal(window, inZoomIn, &idealSize);
-#else
- [window zoom:window];
-#endif
- if(QTLWExtra *tlextra = d->topData()) {
- setGeometry(tlextra->normalGeometry);
- tlextra->normalGeometry.setRect(0, 0, -1, -1);
- }
- }
- }
- }
-
- data->window_state = newstate;
-
- if(needShow)
- show();
-
- if(newstate & Qt::WindowActive)
- activateWindow();
-
- qt_event_request_window_change(this);
- if (needSendStateChange) {
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
- }
-}
-
-void QWidgetPrivate::setFocus_sys()
-{
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_WState_Created)) {
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- NSView *view = qt_mac_nativeview_for(q);
- [[view window] makeFirstResponder:view];
-#else
- SetKeyboardFocus(qt_mac_window_for(q), qt_mac_nativeview_for(q), 1);
-#endif
- }
-}
-
-NSComparisonResult compareViews2Raise(id view1, id view2, void *context)
-{
- id topView = reinterpret_cast<id>(context);
- if (view1 == topView)
- return NSOrderedDescending;
- if (view2 == topView)
- return NSOrderedAscending;
- return NSOrderedSame;
-}
-
-void QWidgetPrivate::raise_sys()
-{
- Q_Q(QWidget);
- if((q->windowType() == Qt::Desktop))
- return;
-
-#if QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- if (isRealWindow()) {
- // With the introduction of spaces it is not as simple as just raising the window.
- // First we need to check if we are in the right space. If we are, then we just continue
- // as usual. The problem comes when we are not in the active space. There are two main cases:
- // 1. Our parent was moved to a new space. In this case we want the window to be raised
- // in the same space as its parent.
- // 2. We don't have a parent. For this case we will just raise the window and let Cocoa
- // switch to the corresponding space.
- // NOTICE: There are a lot of corner cases here. We are keeping this simple for now, if
- // required we will introduce special handling for some of them.
- if (!q->testAttribute(Qt::WA_DontShowOnScreen) && q->isVisible()) {
- OSWindowRef window = qt_mac_window_for(q);
- // isOnActiveSpace is available only from 10.6 onwards, so we need to check if it is
- // available before calling it.
- if([window respondsToSelector:@selector(isOnActiveSpace)]) {
- if(![window performSelector:@selector(isOnActiveSpace)]) {
- QWidget *parentWidget = q->parentWidget();
- if(parentWidget) {
- OSWindowRef parentWindow = qt_mac_window_for(parentWidget);
- if(parentWindow && [parentWindow respondsToSelector:@selector(isOnActiveSpace)]) {
- if ([parentWindow performSelector:@selector(isOnActiveSpace)]) {
- // The window was created in a different space. Therefore if we want
- // to show it in the current space we need to recreate it in the new
- // space.
- recreateMacWindow();
- window = qt_mac_window_for(q);
- }
- }
- }
- }
- }
- [window orderFront:window];
- }
- if (qt_mac_raise_process) { //we get to be the active process now
- ProcessSerialNumber psn;
- GetCurrentProcess(&psn);
- SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
- }
- } else {
- NSView *view = qt_mac_nativeview_for(q);
- NSView *parentView = [view superview];
- [parentView sortSubviewsUsingFunction:compareViews2Raise context:reinterpret_cast<void *>(view)];
- }
- topLevelAt_cache = 0;
-#else
- if(q->isWindow()) {
- //raise this window
- BringToFront(qt_mac_window_for(q));
- if(qt_mac_raise_process) { //we get to be the active process now
- ProcessSerialNumber psn;
- GetCurrentProcess(&psn);
- SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
- }
- } else if(q->parentWidget()) {
- HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderAbove, 0);
- qt_event_request_window_change(q);
- }
-#endif
-}
-
-NSComparisonResult compareViews2Lower(id view1, id view2, void *context)
-{
- id topView = reinterpret_cast<id>(context);
- if (view1 == topView)
- return NSOrderedAscending;
- if (view2 == topView)
- return NSOrderedDescending;
- return NSOrderedSame;
-}
-
-void QWidgetPrivate::lower_sys()
-{
- Q_Q(QWidget);
- if((q->windowType() == Qt::Desktop))
- return;
-#ifdef QT_MAC_USE_COCOA
- if (isRealWindow()) {
- OSWindowRef window = qt_mac_window_for(q);
- [window orderBack:window];
- } else {
- NSView *view = qt_mac_nativeview_for(q);
- NSView *parentView = [view superview];
- [parentView sortSubviewsUsingFunction:compareViews2Lower context:reinterpret_cast<void *>(view)];
- }
- topLevelAt_cache = 0;
-#else
- if(q->isWindow()) {
- SendBehind(qt_mac_window_for(q), 0);
- } else if(q->parentWidget()) {
- invalidateBuffer(q->rect());
- HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderBelow, 0);
- qt_event_request_window_change(q);
- }
-#endif
-}
-
-NSComparisonResult compareViews2StackUnder(id view1, id view2, void *context)
-{
- const QHash<NSView *, int> &viewOrder = *reinterpret_cast<QHash<NSView *, int> *>(context);
- if (viewOrder[view1] < viewOrder[view2])
- return NSOrderedAscending;
- if (viewOrder[view1] > viewOrder[view2])
- return NSOrderedDescending;
- return NSOrderedSame;
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget *w)
-{
- // stackUnder
- Q_Q(QWidget);
- if(!w || q->isWindow() || (q->windowType() == Qt::Desktop))
- return;
-#ifdef QT_MAC_USE_COCOA
- // Do the same trick as lower_sys() and put this widget before the widget passed in.
- NSView *myView = qt_mac_nativeview_for(q);
- NSView *wView = qt_mac_nativeview_for(w);
-
- QHash<NSView *, int> viewOrder;
- NSView *parentView = [myView superview];
- NSArray *subviews = [parentView subviews];
- NSUInteger index = 1;
- // make a hash of view->zorderindex and make sure z-value is always odd,
- // so that when we modify the order we create a new (even) z-value which
- // will not interfere with others.
- for (NSView *subview in subviews) {
- viewOrder.insert(subview, index * 2);
- ++index;
- }
- viewOrder[myView] = viewOrder[wView] - 1;
-
- [parentView sortSubviewsUsingFunction:compareViews2StackUnder context:reinterpret_cast<void *>(&viewOrder)];
-#else
- QWidget *p = q->parentWidget();
- if(!p || p != w->parentWidget())
- return;
- invalidateBuffer(q->rect());
- HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderBelow, qt_mac_nativeview_for(w));
- qt_event_request_window_change(q);
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-/*
- Modifies the bounds for a widgets backing HIView during moves and resizes. Also updates the
- widget, either by scrolling its contents or repainting, depending on the WA_StaticContents
- flag
-*/
-static void qt_mac_update_widget_position(QWidget *q, QRect oldRect, QRect newRect)
-{
- HIRect bounds = CGRectMake(newRect.x(), newRect.y(),
- newRect.width(), newRect.height());
-
- const HIViewRef view = qt_mac_nativeview_for(q);
- const bool isMove = (oldRect.topLeft() != newRect.topLeft());
- const bool isResize = (oldRect.size() != newRect.size());
-
-// qDebug() << oldRect << newRect << isMove << isResize << q->testAttribute(Qt::WA_OpaquePaintEvent) << q->testAttribute(Qt::WA_StaticContents);
- QWidgetPrivate *qd = qt_widget_private(q);
-
- // Perform a normal (complete repaint) update in some cases:
- if (
- // always repaint on move.
- (isMove) ||
-
- // limited update on resize requires WA_StaticContents.
- (isResize && q->testAttribute(Qt::WA_StaticContents) == false) ||
-
- // one of the rects are invalid
- (oldRect.isValid() == false || newRect.isValid() == false) ||
-
- // the position update is a part of a drag-and-drop operation
- QDragManager::self()->object ||
-
- // we are on Panther (no HIViewSetNeedsDisplayInRect)
- QSysInfo::MacintoshVersion < QSysInfo::MV_10_4
- ){
- HIViewSetFrame(view, &bounds);
- return;
- }
-
- const int dx = newRect.x() - oldRect.x();
- const int dy = newRect.y() - oldRect.y();
-
- if (isMove) {
- // HIViewScrollRect silently fails if we try to scroll anything under the grow box.
- // Check if there's one present within the widget rect, and if there is fall back
- // to repainting the entire widget.
- QWidget const * const parentWidget = q->parentWidget();
- const HIViewRef parentView = qt_mac_nativeview_for(parentWidget);
- HIViewRef nativeSizeGrip = 0;
- if (q->testAttribute(Qt::WA_WState_Created))
- HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(q->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
- if (nativeSizeGrip) {
- QWidget * const window = q->window();
-
- const int sizeGripSize = 20;
- const QRect oldWidgetRect = QRect(q->mapTo(window, QPoint(0, 0)), QSize(oldRect.width(), oldRect.height()));
- const QRect newWidgetRect = QRect(q->mapTo(window, QPoint(0, 0)), QSize(newRect.width(), newRect.height()));
- const QRect sizeGripRect = QRect(window->rect().bottomRight() - QPoint(sizeGripSize, sizeGripSize),
- window->rect().bottomRight());
-
- if (sizeGripRect.intersects(oldWidgetRect) || sizeGripRect.intersects(newWidgetRect)) {
- HIViewSetFrame(view, &bounds);
- return;
- }
- }
-
- // Don't scroll anything outside the parent widget rect.
- const QRect scrollRect = (oldRect | newRect) & parentWidget->rect();
- const HIRect scrollBounds =
- CGRectMake(scrollRect.x(), scrollRect.y(), scrollRect.width(), scrollRect.height());
-
- // We cannot scroll when the widget has a mask as that would
- // scroll the masked out areas too
- if (qd->extra && qd->extra->hasMask) {
- HIViewMoveBy(view, dx, dy);
- return;
- }
-
- OSStatus err = HIViewScrollRect(parentView, &scrollBounds, dx, dy);
- if (err != noErr) {
- HIViewSetNeedsDisplay(view, true);
- qWarning("QWidget: Internal error (%s:%d)", __FILE__, __LINE__);
- }
- }
- // Set the view bounds with drawing disabled to prevent repaints.
- HIViewSetDrawingEnabled(view, false);
- HIViewSetFrame(view, &bounds);
- HIViewSetDrawingEnabled(view, true);
-
- // Update any newly exposed areas due to resizing.
- const int startx = oldRect.width();
- const int stopx = newRect.width();
- const int starty = oldRect.height();
- const int stopy = newRect.height();
-
- const HIRect verticalSlice = CGRectMake(startx, 0, stopx , stopy);
- HIViewSetNeedsDisplayInRect(view, &verticalSlice, true);
- const HIRect horizontalSlice = CGRectMake(0, starty, startx, stopy);
- HIViewSetNeedsDisplayInRect(view, &horizontalSlice, true);
-}
-#endif
-
-/*
- Helper function for non-toplevel widgets. Helps to map Qt's 32bit
- coordinate system to OS X's 16bit coordinate system.
-
- Sets the geometry of the widget to data.crect, but clipped to sizes
- that OS X can handle. Unmaps widgets that are completely outside the
- valid range.
-
- Maintains data.wrect, which is the geometry of the OS X widget,
- measured in this widget's coordinate system.
-
- if the parent is not clipped, parentWRect is empty, otherwise
- parentWRect is the geometry of the parent's OS X rect, measured in
- parent's coord sys
-*/
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if (!q->internalWinId() && QApplicationPrivate::graphicsSystem() != 0) {
- // We have no view to move, and no paint engine that
- // we can update dirty regions on. So just return:
- return;
- }
-
- QMacCocoaAutoReleasePool pool;
-
- /*
- There are up to four different coordinate systems here:
- Qt coordinate system for this widget.
- X coordinate system for this widget (relative to wrect).
- Qt coordinate system for parent
- X coordinate system for parent (relative to parent's wrect).
- */
-
- // wrect is the same as crect, except that it is
- // clipped to fit inside parent (and screen):
- QRect wrect;
-
- // wrectInParentCoordSys will be the same as wrect, except that it is
- // originated in q's parent rather than q itself. It starts out in
- // parent's Qt coord system, and ends up in parent's coordinate system:
- QRect wrectInParentCoordSys = data.crect;
-
- // If q's parent has been clipped, parentWRect will
- // be filled with the parents clipped crect:
- QRect parentWRect;
-
- // Embedded have different meaning on each platform, and on
- // Mac, it means that q is a QMacNativeWidget.
- bool isEmbeddedWindow = (q->isWindow() && topData()->embedded);
-#ifdef QT_MAC_USE_COCOA
- NSView *nsview = qt_mac_nativeview_for(q);
-#endif
- if (!isEmbeddedWindow) {
- parentWRect = q->parentWidget()->data->wrect;
- } else {
- // INVARIANT: q's parent view is not owned by Qt. So we need to
- // do some extra calls to get the clipped rect of the parent view:
-#ifndef QT_MAC_USE_COCOA
- HIViewRef parentView = HIViewGetSuperview(qt_mac_nativeview_for(q));
-#else
- NSView *parentView = [qt_mac_nativeview_for(q) superview];
-#endif
- if (parentView) {
-#ifndef QT_MAC_USE_COCOA
- HIRect tmpRect;
- HIViewGetFrame(parentView, &tmpRect);
-#else
- NSRect tmpRect = [parentView frame];
-#endif
- parentWRect = QRect(tmpRect.origin.x, tmpRect.origin.y,
- tmpRect.size.width, tmpRect.size.height);
- } else {
- const QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
- parentWRect = wrectRange;
- }
- }
-
- if (parentWRect.isValid()) {
- // INVARIANT: q's parent has been clipped.
- // So we fit our own wrects inside it:
- if (!parentWRect.contains(wrectInParentCoordSys) && !isEmbeddedWindow) {
- wrectInParentCoordSys &= parentWRect;
- wrect = wrectInParentCoordSys;
- // Make sure wrect is originated in q's coordinate system:
- wrect.translate(-data.crect.topLeft());
- }
- // // Make sure wrectInParentCoordSys originated in q's parent coordinate system:
- wrectInParentCoordSys.translate(-parentWRect.topLeft());
- } else {
- // INVARIANT: we dont know yet the clipping rect of q's parent.
- // So we may or may not have to adjust our wrects:
-
- if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
- // This is where the main optimization is: we have an old wrect from an earlier
- // setGeometry call, and the new crect is smaller than it. If the final wrect is
- // also inside the old wrect, we can just move q and its children to the new
- // location without any clipping:
-
- // vrect will be the part of q that's will be visible inside
- // q's parent. If it inside the old wrect, then we can just move:
- QRect vrect = wrectInParentCoordSys & q->parentWidget()->rect();
- vrect.translate(-data.crect.topLeft());
-
- if (data.wrect.contains(vrect)) {
- wrectInParentCoordSys = data.wrect;
- wrectInParentCoordSys.translate(data.crect.topLeft());
-#ifndef QT_MAC_USE_COCOA
- HIRect bounds = CGRectMake(wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
- wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
- HIViewSetFrame(qt_mac_nativeview_for(q), &bounds);
-#else
- if (nsview) {
- // INVARIANT: q is native. Set view frame:
- NSRect bounds = NSMakeRect(wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
- wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
- [nsview setFrame:bounds];
- } else {
- // INVARIANT: q is alien. Repaint wrect instead (includes old and new wrect):
- QWidget *parent = q->parentWidget();
- QPoint globalPosWRect = parent->mapToGlobal(data.wrect.topLeft());
-
- QWidget *nativeParent = q->nativeParentWidget();
- QRect dirtyWRect = QRect(nativeParent->mapFromGlobal(globalPosWRect), data.wrect.size());
-
- nativeParent->update(dirtyWRect);
- }
-#endif
- if (q->testAttribute(Qt::WA_OutsideWSRange)) {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
- if (!dontShow) {
- q->setAttribute(Qt::WA_Mapped);
-#ifndef QT_MAC_USE_COCOA
- HIViewSetVisible(qt_mac_nativeview_for(q), true);
-#else
- // If q is Alien, the following call does nothing:
- [nsview setHidden:NO];
-#endif
- }
- }
- return;
- }
- }
-
-#ifndef QT_MAC_USE_COCOA
- const QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
- if (!validRange.contains(wrectInParentCoordSys)) {
- // We're too big, and must clip:
- QPoint screenOffset(0, 0); // offset of the part being on screen
- const QWidget *parentWidget = q->parentWidget();
- while (parentWidget && !parentWidget->isWindow()) {
- screenOffset -= parentWidget->data->crect.topLeft();
- parentWidget = parentWidget->parentWidget();
- }
- QRect cropRect(screenOffset.x() - WRECT_MAX,
- screenOffset.y() - WRECT_MAX,
- 2*WRECT_MAX,
- 2*WRECT_MAX);
-
- wrectInParentCoordSys &=cropRect;
- wrect = wrectInParentCoordSys;
- wrect.translate(-data.crect.topLeft());
- }
-#endif //QT_MAC_USE_COCOA
- }
-
- // unmap if we are outside the valid window system coord system
- bool outsideRange = !wrectInParentCoordSys.isValid();
- bool mapWindow = false;
- if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
- q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
- if (outsideRange) {
-#ifndef QT_MAC_USE_COCOA
- HIViewSetVisible(qt_mac_nativeview_for(q), false);
-#else
- // If q is Alien, the following call does nothing:
- [nsview setHidden:YES];
-#endif
- q->setAttribute(Qt::WA_Mapped, false);
- } else if (!q->isHidden()) {
- mapWindow = true;
- }
- }
-
- if (outsideRange)
- return;
-
- // Store the new clipped rect:
- bool jump = (data.wrect != wrect);
- data.wrect = wrect;
-
- // and now recursively for all children...
- // ### can be optimized
- for (int i = 0; i < children.size(); ++i) {
- QObject *object = children.at(i);
- if (object->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(object);
- if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
- w->d_func()->setWSGeometry();
- }
- }
-
-#ifndef QT_MAC_USE_COCOA
- // Move the actual HIView:
- qt_mac_update_widget_position(q, oldRect, wrectInParentCoordSys);
- if (jump)
- q->update();
-#else
- if (nsview) {
- // INVARIANT: q is native. Move the actual NSView:
- NSRect bounds = NSMakeRect(
- wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
- wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
- [nsview setFrame:bounds];
- if (jump)
- q->update();
- } else if (QApplicationPrivate::graphicsSystem() == 0){
- // INVARIANT: q is alien and we use native paint engine.
- // Schedule updates where q is moved from and to:
- const QWidget *parent = q->parentWidget();
- const QPoint globalPosOldWRect = parent->mapToGlobal(oldRect.topLeft());
- const QPoint globalPosNewWRect = parent->mapToGlobal(wrectInParentCoordSys.topLeft());
-
- QWidget *nativeParent = q->nativeParentWidget();
- const QRegion dirtyOldWRect = QRect(nativeParent->mapFromGlobal(globalPosOldWRect), oldRect.size());
- const QRegion dirtyNewWRect = QRect(nativeParent->mapFromGlobal(globalPosNewWRect), wrectInParentCoordSys.size());
-
- const bool sizeUnchanged = oldRect.size() == wrectInParentCoordSys.size();
- const bool posUnchanged = oldRect.topLeft() == wrectInParentCoordSys.topLeft();
-
- // Resolve/minimize the region that needs to update:
- if (sizeUnchanged && q->testAttribute(Qt::WA_OpaquePaintEvent)) {
- // INVARIANT: q is opaque, and is only moved (not resized). So in theory we only
- // need to blit pixels, and skip a repaint. But we can only make this work if we
- // had access to the backbuffer, so we need to update all:
- nativeParent->update(dirtyOldWRect | dirtyNewWRect);
- } else if (posUnchanged && q->testAttribute(Qt::WA_StaticContents)) {
- // We only need to redraw exposed areas:
- nativeParent->update(dirtyNewWRect - dirtyOldWRect);
- } else {
- nativeParent->update(dirtyOldWRect | dirtyNewWRect);
- }
- }
-#endif
-
- if (mapWindow && !dontShow) {
- q->setAttribute(Qt::WA_Mapped);
-#ifndef QT_MAC_USE_COCOA
- HIViewSetVisible(qt_mac_nativeview_for(q), true);
-#else
- // If q is Alien, the following call does nothing:
- [nsview setHidden:NO];
-#endif
- }
-}
-
-void QWidgetPrivate::adjustWithinMaxAndMinSize(int &w, int &h)
-{
- if (QWExtra *extra = extraData()) {
- w = qMin(w, extra->maxw);
- h = qMin(h, extra->maxh);
- w = qMax(w, extra->minw);
- h = qMax(h, extra->minh);
-
- // Deal with size increment
- if (QTLWExtra *top = topData()) {
- if(top->incw) {
- w = w/top->incw;
- w *= top->incw;
- }
- if(top->inch) {
- h = h/top->inch;
- h *= top->inch;
- }
- }
- }
-
- if (isRealWindow()) {
- w = qMax(0, w);
- h = qMax(0, h);
- }
-}
-
-void QWidgetPrivate::applyMaxAndMinSizeOnWindow()
-{
- Q_Q(QWidget);
- QMacCocoaAutoReleasePool pool;
-
- const float max_f(20000);
-#ifndef QT_MAC_USE_COCOA
-#define SF(x) ((x > max_f) ? max_f : x)
- HISize max = CGSizeMake(SF(extra->maxw), SF(extra->maxh));
- HISize min = CGSizeMake(SF(extra->minw), SF(extra->minh));
-#undef SF
- SetWindowResizeLimits(qt_mac_window_for(q), &min, &max);
-#else
-#define SF(x) ((x > max_f) ? max_f : x)
- NSSize max = NSMakeSize(SF(extra->maxw), SF(extra->maxh));
- NSSize min = NSMakeSize(SF(extra->minw), SF(extra->minh));
-#undef SF
- [qt_mac_window_for(q) setContentMinSize:min];
- [qt_mac_window_for(q) setContentMaxSize:max];
-#endif
-}
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if(q->windowType() == Qt::Desktop)
- return;
-
- QMacCocoaAutoReleasePool pool;
- bool realWindow = isRealWindow();
-
- if (realWindow && !q->testAttribute(Qt::WA_DontShowOnScreen)){
- adjustWithinMaxAndMinSize(w, h);
-#ifndef QT_MAC_USE_COCOA
- if (w != 0 && h != 0) {
- topData()->isSetGeometry = 1;
- topData()->isMove = isMove;
- Rect r; SetRect(&r, x, y, x + w, y + h);
- SetWindowBounds(qt_mac_window_for(q), kWindowContentRgn, &r);
- topData()->isSetGeometry = 0;
- } else {
- setGeometry_sys_helper(x, y, w, h, isMove);
- }
-#else
- if (!isMove && !q->testAttribute(Qt::WA_Moved) && !q->isVisible()) {
- // INVARIANT: The location of the window has not yet been set. The default will
- // instead be to center it on the desktop, or over the parent, if any. Since we now
- // resize the window, we need to adjust the top left position to keep the window
- // centeralized. And we need to to this now (and before show) in case the positioning
- // of other windows (e.g. sub-windows) depend on this position:
- if (QWidget *p = q->parentWidget()) {
- x = p->geometry().center().x() - (w / 2);
- y = p->geometry().center().y() - (h / 2);
- } else {
- QRect availGeo = QApplication::desktop()->availableGeometry(q);
- x = availGeo.center().x() - (w / 2);
- y = availGeo.center().y() - (h / 2);
- }
- }
-
- QSize olds = q->size();
- const bool isResize = (olds != QSize(w, h));
- NSWindow *window = qt_mac_window_for(q);
- const QRect &fStrut = frameStrut();
- const QRect frameRect(QPoint(x - fStrut.left(), y - fStrut.top()),
- QSize(fStrut.left() + fStrut.right() + w,
- fStrut.top() + fStrut.bottom() + h));
- NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1),
- frameRect.width(), frameRect.height());
- // The setFrame call will trigger a 'windowDidResize' notification for the corresponding
- // NSWindow. The pending flag is set, so that the resize event can be send as non-spontaneous.
- if (isResize)
- q->setAttribute(Qt::WA_PendingResizeEvent);
- QPoint currTopLeft = data.crect.topLeft();
- if (currTopLeft.x() == x && currTopLeft.y() == y
- && cocoaFrameRect.size.width != 0
- && cocoaFrameRect.size.height != 0) {
- [window setFrame:cocoaFrameRect display:realWindow];
- } else {
- // The window is moved and resized (or resized to zero).
- // Since Cocoa usually only sends us a resize callback after
- // setting a window frame, we issue an explicit move as
- // well. To stop Cocoa from optimize away the move (since the move
- // would have the same origin as the setFrame call) we shift the
- // window back and forth inbetween.
- cocoaFrameRect.origin.y += 1;
- [window setFrame:cocoaFrameRect display:realWindow];
- cocoaFrameRect.origin.y -= 1;
- [window setFrameOrigin:cocoaFrameRect.origin];
- }
-#endif
- } else {
- setGeometry_sys_helper(x, y, w, h, isMove);
- }
-
- topLevelAt_cache = 0;
-}
-
-void QWidgetPrivate::setGeometry_sys_helper(int x, int y, int w, int h, bool isMove)
-{
- Q_Q(QWidget);
- bool realWindow = isRealWindow();
-
- QPoint oldp = q->pos();
- QSize olds = q->size();
- const bool isResize = (olds != QSize(w, h));
-
- if (!realWindow && !isResize && QPoint(x, y) == oldp)
- return;
-
- if (isResize)
- data.window_state = data.window_state & ~Qt::WindowMaximized;
-
- const bool visible = q->isVisible();
- // Apply size restrictions, applicable for Windows & Widgets.
- if (QWExtra *extra = extraData()) {
- w = qMin(w, extra->maxw);
- h = qMin(h, extra->maxh);
- w = qMax(w, extra->minw);
- h = qMax(h, extra->minh);
- }
- data.crect = QRect(x, y, w, h);
-
- if (realWindow) {
- adjustWithinMaxAndMinSize(w, h);
- qt_mac_update_sizer(q);
-
-#ifndef QT_MAC_USE_COCOA
- if (q->windowFlags() & Qt::WindowMaximizeButtonHint) {
- OSWindowRef window = qt_mac_window_for(q);
- if (extra->maxw && extra->maxh && extra->maxw == extra->minw
- && extra->maxh == extra->minh) {
- ChangeWindowAttributes(window, kWindowNoAttributes, kWindowFullZoomAttribute);
- } else {
- ChangeWindowAttributes(window, kWindowFullZoomAttribute, kWindowNoAttributes);
- }
- }
- HIRect bounds = CGRectMake(0, 0, w, h);
- HIViewSetFrame(qt_mac_nativeview_for(q), &bounds);
-#else
- [qt_mac_nativeview_for(q) setFrame:NSMakeRect(0, 0, w, h)];
-#endif
- } else {
- const QRect oldRect(oldp, olds);
- if (!isResize && QApplicationPrivate::graphicsSystem())
- moveRect(oldRect, x - oldp.x(), y - oldp.y());
-
- setWSGeometry(false, oldRect);
-
- if (isResize && QApplicationPrivate::graphicsSystem())
- invalidateBuffer_resizeHelper(oldp, olds);
- }
-
- if(isMove || isResize) {
- if(!visible) {
- if(isMove && q->pos() != oldp)
- q->setAttribute(Qt::WA_PendingMoveEvent, true);
- if(isResize)
- q->setAttribute(Qt::WA_PendingResizeEvent, true);
- } else {
- if(isResize) { //send the resize event..
- QResizeEvent e(q->size(), olds);
- QApplication::sendEvent(q, &e);
- }
- if(isMove && q->pos() != oldp) { //send the move event..
- QMoveEvent e(q->pos(), oldp);
- QApplication::sendEvent(q, &e);
- }
- }
- }
- qt_event_request_window_change(q);
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
- updateMaximizeButton_sys();
- applyMaxAndMinSizeOnWindow();
-}
-
-void QWidgetPrivate::updateMaximizeButton_sys()
-{
- Q_Q(QWidget);
- if (q->data->window_flags & Qt::CustomizeWindowHint)
- return;
-
- OSWindowRef window = qt_mac_window_for(q);
- QTLWExtra * tlwExtra = topData();
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- NSButton *maximizeButton = [window standardWindowButton:NSWindowZoomButton];
-#endif
- if (extra->maxw && extra->maxh
- && extra->maxw == extra->minw
- && extra->maxh == extra->minh) {
- // The window has a fixed size, so gray out the maximize button:
- if (!tlwExtra->savedWindowAttributesFromMaximized) {
-#ifndef QT_MAC_USE_COCOA
- GetWindowAttributes(window,
- (WindowAttributes*)&extra->topextra->savedWindowAttributesFromMaximized);
-
-#else
- tlwExtra->savedWindowAttributesFromMaximized = (![maximizeButton isHidden] && [maximizeButton isEnabled]);
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- ChangeWindowAttributes(window, kWindowNoAttributes, kWindowFullZoomAttribute);
-#else
- [maximizeButton setEnabled:NO];
-#endif
-
-
- } else {
- if (tlwExtra->savedWindowAttributesFromMaximized) {
-#ifndef QT_MAC_USE_COCOA
- ChangeWindowAttributes(window,
- extra->topextra->savedWindowAttributesFromMaximized,
- kWindowNoAttributes);
-#else
- [maximizeButton setEnabled:YES];
-#endif
- tlwExtra->savedWindowAttributesFromMaximized = 0;
- }
- }
-
-
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
- if (QApplicationPrivate::graphicsSystem() && !paintOnScreen()) {
- // INVARIANT: Alien paint engine
- scrollChildren(dx, dy);
- scrollRect(q_func()->rect(), dx, dy);
- } else {
- scroll_sys(dx, dy, QRect());
- }
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &qscrollRect)
-{
- if (QMacScrollOptimization::delayScroll(this, dx, dy, qscrollRect))
- return;
-
- Q_Q(QWidget);
- if (QApplicationPrivate::graphicsSystem() && !paintOnScreen()) {
- // INVARIANT: Alien paint engine
- scrollRect(qscrollRect, dx, dy);
- return;
- }
-
- static int accelEnv = -1;
- if (accelEnv == -1) {
- accelEnv = qgetenv("QT_NO_FAST_SCROLL").toInt() == 0;
- }
-
- // Scroll the whole widget if qscrollRect is not valid:
- QRect validScrollRect = qscrollRect.isValid() ? qscrollRect : q->rect();
- validScrollRect &= clipRect();
-
- // If q is overlapped by other widgets, we cannot just blit pixels since
- // this will move overlapping widgets as well. In case we just update:
- const bool overlapped = isOverlapped(validScrollRect.translated(data.crect.topLeft()));
- const bool accelerateScroll = accelEnv && isOpaque && !overlapped;
- const bool isAlien = (q->internalWinId() == 0);
- const QPoint scrollDelta(dx, dy);
-
- // If qscrollRect is valid, we are _not_ supposed to scroll q's children (as documented).
- // But we do scroll children (and the whole of q) if qscrollRect is invalid. This case is
- // documented as undefined, but we exploit it to help factor our code into one function.
- const bool scrollChildren = !qscrollRect.isValid();
-
- if (!q->updatesEnabled()) {
- // We are told not to update anything on q at this point. So unless
- // we are supposed to scroll children, we bail out early:
- if (!scrollChildren || q->children().isEmpty())
- return;
- }
-
- if (!accelerateScroll) {
- if (overlapped) {
- QRegion region(validScrollRect);
- subtractOpaqueSiblings(region);
- update_sys(region);
- }else {
- update_sys(qscrollRect);
- }
- return;
- }
-
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
-#else
- Q_UNUSED(isAlien);
- // We're not sure what the following call is supposed to achive
- // but until we see what it breaks, we don't bring it into the
- // Cocoa port:
- qt_event_request_window_change(q);
-#endif
-
- // First move all native children. Alien children will indirectly be
- // moved when the parent is scrolled. All directly or indirectly moved
- // children will receive a move event before the function call returns.
- QWidgetList movedChildren;
- if (scrollChildren) {
- QObjectList children = q->children();
-
- for (int i=0; i<children.size(); i++) {
- QObject *obj = children.at(i);
- if (QWidget *w = qobject_cast<QWidget*>(obj)) {
- if (!w->isWindow()) {
- w->data->crect = QRect(w->pos() + scrollDelta, w->size());
-#ifndef QT_MAC_USE_COCOA
- if (w->testAttribute(Qt::WA_WState_Created)) {
- HIRect bounds = CGRectMake(w->data->crect.x(), w->data->crect.y(),
- w->data->crect.width(), w->data->crect.height());
- HIViewRef hiview = qt_mac_nativeview_for(w);
- const bool opaque = q->testAttribute(Qt::WA_OpaquePaintEvent);
-
- if (opaque)
- HIViewSetDrawingEnabled(hiview, false);
- HIViewSetFrame(hiview, &bounds);
- if (opaque)
- HIViewSetDrawingEnabled(hiview, true);
- }
-#else
- if (NSView *view = qt_mac_nativeview_for(w)) {
- // INVARIANT: w is not alien
- [view setFrame:NSMakeRect(
- w->data->crect.x(), w->data->crect.y(),
- w->data->crect.width(), w->data->crect.height())];
- }
-#endif
- movedChildren.append(w);
- }
- }
- }
- }
-
- if (q->testAttribute(Qt::WA_WState_Created) && q->isVisible()) {
- // Scroll q itself according to the qscrollRect, and
- // call update on any exposed areas so that they get redrawn:
-
-#ifndef QT_MAC_USE_COCOA
- OSViewRef view = qt_mac_nativeview_for(q);
- HIRect scrollrect = CGRectMake(qscrollRect.x(), qscrollRect.y(), qscrollRect.width(), qscrollRect.height());
- OSStatus err = _HIViewScrollRectWithOptions(view, qscrollRect.isValid() ? &scrollrect : 0, dx, dy, kHIViewScrollRectAdjustInvalid);
- if (err) {
- // The only parameter that can go wrong, is the rect.
- qWarning("QWidget::scroll: Your rectangle was too big for the widget, clipping rect");
- scrollrect = CGRectMake(qMax(qscrollRect.x(), 0), qMax(qscrollRect.y(), 0),
- qMin(qscrollRect.width(), q->width()), qMin(qscrollRect.height(), q->height()));
- _HIViewScrollRectWithOptions(view, qscrollRect.isValid() ? &scrollrect : 0, dx, dy, kHIViewScrollRectAdjustInvalid);
- }
-#else
-
- QWidget *nativeWidget = isAlien ? q->nativeParentWidget() : q;
- if (!nativeWidget)
- return;
- OSViewRef view = qt_mac_nativeview_for(nativeWidget);
- if (!view)
- return;
-
- // Calculate the rectangles that needs to be redrawn
- // after the scroll. This will be source rect minus destination rect:
- QRect deltaXRect;
- if (dx != 0) {
- deltaXRect.setY(validScrollRect.y());
- deltaXRect.setHeight(validScrollRect.height());
- if (dx > 0) {
- deltaXRect.setX(validScrollRect.x());
- deltaXRect.setWidth(dx);
- } else {
- deltaXRect.setX(validScrollRect.x() + validScrollRect.width() + dx);
- deltaXRect.setWidth(-dx);
- }
- }
-
- QRect deltaYRect;
- if (dy != 0) {
- deltaYRect.setX(validScrollRect.x());
- deltaYRect.setWidth(validScrollRect.width());
- if (dy > 0) {
- deltaYRect.setY(validScrollRect.y());
- deltaYRect.setHeight(dy);
- } else {
- deltaYRect.setY(validScrollRect.y() + validScrollRect.height() + dy);
- deltaYRect.setHeight(-dy);
- }
- }
-
- if (isAlien) {
- // Adjust the scroll rect to the location as seen from the native parent:
- QPoint scrollTopLeftInsideNative = nativeWidget->mapFromGlobal(q->mapToGlobal(validScrollRect.topLeft()));
- validScrollRect.moveTo(scrollTopLeftInsideNative);
- }
-
- // Make the pixel copy rect within the validScrollRect bounds:
- NSRect nsscrollRect = NSMakeRect(
- validScrollRect.x() + (dx < 0 ? -dx : 0),
- validScrollRect.y() + (dy < 0 ? -dy : 0),
- validScrollRect.width() + (dx > 0 ? -dx : 0),
- validScrollRect.height() + (dy > 0 ? -dy : 0));
-
- NSSize deltaSize = NSMakeSize(dx, dy);
- [view scrollRect:nsscrollRect by:deltaSize];
-
- // Some areas inside the scroll rect might have been marked as dirty from before, which
- // means that they are scheduled to be redrawn. But as we now scroll, those dirty rects
- // should also move along to ensure that q receives repaints on the correct places.
- // Since some of the dirty rects might lay outside, or only intersect with, the scroll
- // rect, the old calls to setNeedsDisplay still makes sense.
- // NB: Using [view translateRectsNeedingDisplayInRect:nsscrollRect by:deltaSize] have
- // so far not been proven fruitful to solve this problem.
- const QVector<QRect> &dirtyRectsToScroll = dirtyOnWidget.rects();
- for (int i=0; i<dirtyRectsToScroll.size(); ++i) {
- QRect qdirtyRect = dirtyRectsToScroll[i];
- qdirtyRect.translate(dx, dy);
- update_sys(qdirtyRect);
- }
-
- // Update newly exposed areas. This will generate new dirty areas on
- // q, and therefore, we do it after updating the old dirty rects above:
- if (dx != 0)
- update_sys(deltaXRect);
- if (dy != 0)
- update_sys(deltaYRect);
-
-#endif // QT_MAC_USE_COCOA
- }
-
- for (int i=0; i<movedChildren.size(); i++) {
- QWidget *w = movedChildren.at(i);
- QMoveEvent e(w->pos(), w->pos() - scrollDelta);
- QApplication::sendEvent(w, &e);
- }
-}
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
- switch(m) {
- case PdmHeightMM:
- return qRound(metric(PdmHeight) * 25.4 / qreal(metric(PdmDpiY)));
- case PdmWidthMM:
- return qRound(metric(PdmWidth) * 25.4 / qreal(metric(PdmDpiX)));
- case PdmHeight:
- case PdmWidth:
-#ifndef QT_MAC_USE_COCOA
- { HIRect rect;
- HIViewGetFrame(qt_mac_nativeview_for(this), &rect);
- if(m == PdmWidth)
- return (int)rect.size.width;
- return (int)rect.size.height; }
-#else
- if (m == PdmWidth)
- return data->crect.width();
- else
- return data->crect.height();
-#endif
- case PdmDepth:
- return 32;
- case PdmNumColors:
- return INT_MAX;
- case PdmDpiX:
- case PdmPhysicalDpiX: {
- Q_D(const QWidget);
- if (d->extra && d->extra->customDpiX)
- return d->extra->customDpiX;
- else if (d->parent)
- return static_cast<QWidget *>(d->parent)->metric(m);
- extern float qt_mac_defaultDpi_x(); //qpaintdevice_mac.cpp
- return int(qt_mac_defaultDpi_x()); }
- case PdmDpiY:
- case PdmPhysicalDpiY: {
- Q_D(const QWidget);
- if (d->extra && d->extra->customDpiY)
- return d->extra->customDpiY;
- else if (d->parent)
- return static_cast<QWidget *>(d->parent)->metric(m);
- extern float qt_mac_defaultDpi_y(); //qpaintdevice_mac.cpp
- return int(qt_mac_defaultDpi_y()); }
- default: //leave this so the compiler complains when new ones are added
- qWarning("QWidget::metric: Unhandled parameter %d", m);
- return QPaintDevice::metric(m);
- }
- return 0;
-}
-
-void QWidgetPrivate::createSysExtra()
-{
-#ifdef QT_MAC_USE_COCOA
- extra->imageMask = 0;
-#endif
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
-#ifdef QT_MAC_USE_COCOA
- if (extra->imageMask)
- CFRelease(extra->imageMask);
-#endif
-}
-
-void QWidgetPrivate::createTLSysExtra()
-{
- extra->topextra->resizer = 0;
- extra->topextra->isSetGeometry = 0;
- extra->topextra->isMove = 0;
- extra->topextra->wattr = 0;
- extra->topextra->wclass = 0;
- extra->topextra->group = 0;
- extra->topextra->windowIcon = 0;
- extra->topextra->savedWindowAttributesFromMaximized = 0;
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
-#ifndef QT_MAC_USE_COCOA
- if (extra->topextra->group) {
- qt_mac_release_window_group(extra->topextra->group);
- extra->topextra->group = 0;
- }
- if (extra->topextra->windowIcon) {
- ReleaseIconRef(extra->topextra->windowIcon);
- extra->topextra->windowIcon = 0;
- }
-#endif
-}
-
-void QWidgetPrivate::updateFrameStrut()
-{
- Q_Q(QWidget);
-
- QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
-
- that->data.fstrut_dirty = false;
- QTLWExtra *top = that->topData();
-
-#if QT_MAC_USE_COCOA
- // 1 Get the window frame
- OSWindowRef oswnd = qt_mac_window_for(q);
- NSRect frameW = [oswnd frame];
- // 2 Get the content frame - so now
- NSRect frameC = [oswnd contentRectForFrameRect:frameW];
- top->frameStrut.setCoords(frameC.origin.x - frameW.origin.x,
- (frameW.origin.y + frameW.size.height) - (frameC.origin.y + frameC.size.height),
- (frameW.origin.x + frameW.size.width) - (frameC.origin.x + frameC.size.width),
- frameC.origin.y - frameW.origin.y);
-#else
- Rect window_r;
- GetWindowStructureWidths(qt_mac_window_for(q), &window_r);
- top->frameStrut.setCoords(window_r.left, window_r.top, window_r.right, window_r.bottom);
-#endif
-}
-
-void QWidgetPrivate::registerDropSite(bool on)
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-#ifndef QT_MAC_USE_COCOA
- SetControlDragTrackingEnabled(qt_mac_nativeview_for(q), on);
-#else
- NSWindow *win = qt_mac_window_for(q);
- if (on) {
- if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaWindow) class]])
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaWindow) *>(win) registerDragTypes];
- else if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaPanel) class]])
- [static_cast<QT_MANGLE_NAMESPACE(QCocoaPanel) *>(win) registerDragTypes];
- }
-#endif
-}
-
-void QWidgetPrivate::registerTouchWindow(bool enable)
-{
- Q_UNUSED(enable);
-#ifdef QT_MAC_USE_COCOA
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
- if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6)
- return;
-
- Q_Q(QWidget);
- if (enable == touchEventsEnabled)
- return;
-
- QCocoaView *view = static_cast<QCocoaView *>(qt_mac_effectiveview_for(q));
- if (!view)
- return;
-
- if (enable) {
- ++view->alienTouchCount;
- if (view->alienTouchCount == 1) {
- touchEventsEnabled = true;
- [view setAcceptsTouchEvents:YES];
- }
- } else {
- --view->alienTouchCount;
- if (view->alienTouchCount == 0) {
- touchEventsEnabled = false;
- [view setAcceptsTouchEvents:NO];
- }
- }
-#endif
-#endif
-}
-
-void QWidgetPrivate::setMask_sys(const QRegion &region)
-{
- Q_UNUSED(region);
- Q_Q(QWidget);
-
-#ifndef QT_MAC_USE_COCOA
- if (q->isWindow())
- ReshapeCustomWindow(qt_mac_window_for(q));
- else
- HIViewReshapeStructure(qt_mac_nativeview_for(q));
-#else
- if (!q->internalWinId())
- return;
-
- if (extra->mask.isEmpty()) {
- extra->maskBits = QImage();
- finishCocoaMaskSetup();
- } else {
- syncCocoaMask();
- }
-
- topLevelAt_cache = 0;
-#endif
-}
-
-void QWidgetPrivate::setWindowOpacity_sys(qreal level)
-{
- Q_Q(QWidget);
-
- if (!q->isWindow())
- return;
-
- level = qBound(0.0, level, 1.0);
- topData()->opacity = (uchar)(level * 255);
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-
- OSWindowRef oswindow = qt_mac_window_for(q);
-#if QT_MAC_USE_COCOA
- [oswindow setAlphaValue:level];
-#else
- SetWindowAlpha(oswindow, level);
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QWidgetPrivate::syncCocoaMask()
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !extra)
- return;
-
- if (extra->hasMask) {
- if(extra->maskBits.size() != q->size()) {
- extra->maskBits = QImage(q->size(), QImage::Format_Mono);
- }
- extra->maskBits.fill(QColor(Qt::color1).rgba());
- extra->maskBits.setNumColors(2);
- extra->maskBits.setColor(0, QColor(Qt::color0).rgba());
- extra->maskBits.setColor(1, QColor(Qt::color1).rgba());
- QPainter painter(&extra->maskBits);
- painter.setBrush(Qt::color1);
- painter.setPen(Qt::NoPen);
- painter.drawRects(extra->mask.rects());
- painter.end();
- finishCocoaMaskSetup();
- }
-}
-
-void QWidgetPrivate::finishCocoaMaskSetup()
-{
- Q_Q(QWidget);
-
- if (!q->testAttribute(Qt::WA_WState_Created) || !extra)
- return;
-
- // Technically this is too late to release, because the data behind the image
- // has already been released. But it's more tidy to do it here.
- // If you are seeing a crash, consider doing a CFRelease before changing extra->maskBits.
- if (extra->imageMask) {
- CFRelease(extra->imageMask);
- extra->imageMask = 0;
- }
-
- if (!extra->maskBits.isNull()) {
- QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(0,
- extra->maskBits.bits(),
- extra->maskBits.numBytes(),
- 0); // shouldn't need to release.
- CGFloat decode[2] = {1, 0};
- extra->imageMask = CGImageMaskCreate(extra->maskBits.width(), extra->maskBits.height(),
- 1, 1, extra->maskBits.bytesPerLine(), dataProvider,
- decode, false);
- }
- if (q->isWindow()) {
- NSWindow *window = qt_mac_window_for(q);
- [window setOpaque:(extra->imageMask == 0)];
- [window invalidateShadow];
- }
- macSetNeedsDisplay(QRegion());
-}
-#endif
-
-struct QPaintEngineCleanupHandler
-{
- inline QPaintEngineCleanupHandler() : engine(0) {}
- inline ~QPaintEngineCleanupHandler() { delete engine; }
- QPaintEngine *engine;
-};
-
-Q_GLOBAL_STATIC(QPaintEngineCleanupHandler, engineHandler)
-
-QPaintEngine *QWidget::paintEngine() const
-{
- QPaintEngine *&pe = engineHandler()->engine;
- if (!pe)
- pe = new QCoreGraphicsPaintEngine();
- if (pe->isActive()) {
- QPaintEngine *engine = new QCoreGraphicsPaintEngine();
- engine->setAutoDestruct(true);
- return engine;
- }
- return pe;
-}
-
-void QWidgetPrivate::setModal_sys()
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
- return;
- const QWidget * const windowParent = q->window()->parentWidget();
- const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
- OSWindowRef windowRef = qt_mac_window_for(q);
-
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- bool alreadySheet = [windowRef styleMask] & NSDocModalWindowMask;
-
- if (windowParent && q->windowModality() == Qt::WindowModal){
- // INVARIANT: Window should be window-modal (which implies a sheet).
- if (!alreadySheet) {
- // NB: the following call will call setModal_sys recursivly:
- recreateMacWindow();
- windowRef = qt_mac_window_for(q);
- }
- if ([windowRef isKindOfClass:[NSPanel class]]){
- // If the primary window of the sheet parent is a child of a modal dialog,
- // the sheet parent should not be modally shaddowed.
- // This goes for the sheet as well:
- OSWindowRef ref = primaryWindow ? qt_mac_window_for(primaryWindow) : 0;
- bool isDialog = ref ? [ref isKindOfClass:[NSPanel class]] : false;
- bool worksWhenModal = isDialog ? [static_cast<NSPanel *>(ref) worksWhenModal] : false;
- if (worksWhenModal)
- [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
- }
- } else {
- // INVARIANT: Window shold _not_ be window-modal (and as such, not a sheet).
- if (alreadySheet){
- // NB: the following call will call setModal_sys recursivly:
- recreateMacWindow();
- windowRef = qt_mac_window_for(q);
- }
- if (q->windowModality() == Qt::NonModal
- && primaryWindow && primaryWindow->windowModality() == Qt::ApplicationModal) {
- // INVARIANT: Our window has a parent that is application modal.
- // This means that q is supposed to be on top of this window and
- // not be modally shaddowed:
- if ([windowRef isKindOfClass:[NSPanel class]])
- [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
- }
- }
-
-#else
- const bool primaryWindowModal = primaryWindow ? primaryWindow->testAttribute(Qt::WA_ShowModal) : false;
- const bool modal = q->testAttribute(Qt::WA_ShowModal);
-
- WindowClass old_wclass;
- GetWindowClass(windowRef, &old_wclass);
-
- if (modal || primaryWindowModal) {
- if (q->windowModality() == Qt::WindowModal
- || (primaryWindow && primaryWindow->windowModality() == Qt::WindowModal)){
- // Window should be window-modal (which implies a sheet).
- if (old_wclass != kSheetWindowClass){
- // We cannot convert a created window to a sheet.
- // So we recreate the window:
- recreateMacWindow();
- return;
- }
- } else {
- // Window should be application-modal (which implies NOT using a sheet).
- if (old_wclass == kSheetWindowClass){
- // We cannot convert a sheet to a window.
- // So we recreate the window:
- recreateMacWindow();
- return;
- } else if (!(q->data->window_flags & Qt::CustomizeWindowHint)) {
- if (old_wclass == kDocumentWindowClass || old_wclass == kFloatingWindowClass || old_wclass == kUtilityWindowClass){
- // Only change the class to kMovableModalWindowClass if the no explicit jewels
- // are set (kMovableModalWindowClass can't contain them), and the current window class
- // can be converted to modal (according to carbon doc). Mind the order of
- // HIWindowChangeClass and ChangeWindowAttributes.
- WindowGroupRef group = GetWindowGroup(windowRef);
- HIWindowChangeClass(windowRef, kMovableModalWindowClass);
- quint32 tmpWattr = kWindowCloseBoxAttribute | kWindowHorizontalZoomAttribute;
- ChangeWindowAttributes(windowRef, tmpWattr, kWindowNoAttributes);
- ChangeWindowAttributes(windowRef, kWindowNoAttributes, tmpWattr);
- // If the window belongs to a qt-created group, set that group once more:
- if (data.window_flags & Qt::WindowStaysOnTopHint
- || q->windowType() == Qt::Popup
- || q->windowType() == Qt::ToolTip)
- SetWindowGroup(windowRef, group);
- }
- // Popups are usually handled "special" and are never modal.
- Qt::WindowType winType = q->windowType();
- if (winType != Qt::Popup && winType != Qt::ToolTip)
- SetWindowModality(windowRef, kWindowModalityAppModal, 0);
- }
- }
- } else if (windowRef) {
- if (old_wclass == kSheetWindowClass){
- // Converting a sheet to a window is complex. It's easier to recreate:
- recreateMacWindow();
- return;
- }
-
- SetWindowModality(windowRef, kWindowModalityNone, 0);
- if (!(q->data->window_flags & Qt::CustomizeWindowHint)) {
- if (q->window()->d_func()->topData()->wattr |= kWindowCloseBoxAttribute)
- ChangeWindowAttributes(windowRef, kWindowCloseBoxAttribute, kWindowNoAttributes);
- if (q->window()->d_func()->topData()->wattr |= kWindowHorizontalZoomAttribute)
- ChangeWindowAttributes(windowRef, kWindowHorizontalZoomAttribute, kWindowNoAttributes);
- if (q->window()->d_func()->topData()->wattr |= kWindowCollapseBoxAttribute)
- ChangeWindowAttributes(windowRef, kWindowCollapseBoxAttribute, kWindowNoAttributes);
- }
-
- WindowClass newClass = q->window()->d_func()->topData()->wclass;
- if (old_wclass != newClass && newClass != 0){
- WindowGroupRef group = GetWindowGroup(windowRef);
- HIWindowChangeClass(windowRef, newClass);
- // If the window belongs to a qt-created group, set that group once more:
- if (data.window_flags & Qt::WindowStaysOnTopHint
- || q->windowType() == Qt::Popup
- || q->windowType() == Qt::ToolTip)
- SetWindowGroup(windowRef, group);
- }
- }
-
- // Make sure that HIWindowChangeClass didn't remove drag support
- // or reset the opaque size grip setting:
- SetAutomaticControlDragTrackingEnabledForWindow(windowRef, true);
- macUpdateOpaqueSizeGrip();
-#endif
-}
-
-void QWidgetPrivate::macUpdateHideOnSuspend()
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow() || q->windowType() != Qt::Tool)
- return;
-#ifndef QT_MAC_USE_COCOA
- if(q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
- ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowHideOnSuspendAttribute);
- else
- ChangeWindowAttributes(qt_mac_window_for(q), kWindowHideOnSuspendAttribute, 0);
-#else
- if(q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
- [qt_mac_window_for(q) setHidesOnDeactivate:NO];
- else
- [qt_mac_window_for(q) setHidesOnDeactivate:YES];
-#endif
-}
-
-void QWidgetPrivate::macUpdateOpaqueSizeGrip()
-{
- Q_Q(QWidget);
-
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
- return;
-
-#ifndef QT_MAC_USE_COCOA // Growbox is always transparent on Cocoa. Can emulate with setting a QSizeGrip
- HIViewRef growBox;
- HIViewFindByID(HIViewGetRoot(qt_mac_window_for(q)), kHIViewWindowGrowBoxID, &growBox);
- if (!growBox)
- return;
- HIGrowBoxViewSetTransparent(growBox, !q->testAttribute(Qt::WA_MacOpaqueSizeGrip));
-#endif
-}
-
-void QWidgetPrivate::macUpdateSizeAttribute()
-{
- Q_Q(QWidget);
- QEvent event(QEvent::MacSizeChange);
- QApplication::sendEvent(q, &event);
- for (int i = 0; i < children.size(); ++i) {
- QWidget *w = qobject_cast<QWidget *>(children.at(i));
- if (w && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
- && !q->testAttribute(Qt::WA_MacMiniSize) // no attribute set? inherit from parent
- && !w->testAttribute(Qt::WA_MacSmallSize)
- && !w->testAttribute(Qt::WA_MacNormalSize))
- w->d_func()->macUpdateSizeAttribute();
- }
- resolveFont();
-}
-
-void QWidgetPrivate::macUpdateIgnoreMouseEvents()
-{
-#ifndef QT_MAC_USE_COCOA // This is handled inside the mouse handler on Cocoa.
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-
- if(q->isWindow())
- {
- if(q->testAttribute(Qt::WA_TransparentForMouseEvents))
- ChangeWindowAttributes(qt_mac_window_for(q), kWindowIgnoreClicksAttribute, 0);
- else
- ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowIgnoreClicksAttribute);
- ReshapeCustomWindow(qt_mac_window_for(q));
- } else {
-#ifndef kHIViewFeatureIgnoresClicks
-#define kHIViewFeatureIgnoresClicks kHIViewIgnoresClicks
-#endif
- if(q->testAttribute(Qt::WA_TransparentForMouseEvents))
- HIViewChangeFeatures(qt_mac_nativeview_for(q), kHIViewFeatureIgnoresClicks, 0);
- else
- HIViewChangeFeatures(qt_mac_nativeview_for(q), 0, kHIViewFeatureIgnoresClicks);
- HIViewReshapeStructure(qt_mac_nativeview_for(q));
- }
-#endif
-}
-
-void QWidgetPrivate::macUpdateMetalAttribute()
-{
- Q_Q(QWidget);
- bool realWindow = isRealWindow();
- if (!q->testAttribute(Qt::WA_WState_Created) || !realWindow)
- return;
-
- if (realWindow) {
-#if QT_MAC_USE_COCOA
- // Cocoa doesn't let us change the style mask once it's been changed
- // So, that means we need to recreate the window.
- OSWindowRef cocoaWindow = qt_mac_window_for(q);
- if ([cocoaWindow styleMask] & NSTexturedBackgroundWindowMask)
- return;
- recreateMacWindow();
-#else
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q));
- if (q->testAttribute(Qt::WA_MacBrushedMetal)) {
- if (layout)
- layout->updateHIToolBarStatus();
- ChangeWindowAttributes(qt_mac_window_for(q), kWindowMetalAttribute, 0);
- ChangeWindowAttributes(qt_mac_window_for(q), kWindowMetalNoContentSeparatorAttribute, 0);
- } else {
- ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowMetalNoContentSeparatorAttribute);
- ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowMetalAttribute);
- if (layout)
- layout->updateHIToolBarStatus();
- }
-#endif
- }
-}
-
-void QWidgetPrivate::setEnabled_helper_sys(bool enable)
-{
-#ifdef QT_MAC_USE_COCOA
- Q_Q(QWidget);
- NSView *view = qt_mac_nativeview_for(q);
- if ([view isKindOfClass:[NSControl class]])
- [static_cast<NSControl *>(view) setEnabled:enable];
-#else
- Q_UNUSED(enable);
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qapplication_s60.cpp b/src/gui/platforms/s60/qapplication_s60.cpp
deleted file mode 100644
index 408c3b5883..0000000000
--- a/src/gui/platforms/s60/qapplication_s60.cpp
+++ /dev/null
@@ -1,2712 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication_p.h"
-#include "qsessionmanager.h"
-#include "qevent.h"
-#include "qsymbianevent.h"
-#include "qeventdispatcher_s60_p.h"
-#include "qwidget.h"
-#include "qdesktopwidget.h"
-#include "private/qbackingstore_p.h"
-#include "qt_s60_p.h"
-#include "private/qevent_p.h"
-#include "qstring.h"
-#include "qdebug.h"
-#include "qimage.h"
-#include "qcombobox.h"
-#include "private/qkeymapper_p.h"
-#include "private/qfont_p.h"
-#ifndef QT_NO_STYLE_S60
-#include "private/qs60style_p.h"
-#endif
-#include "private/qwindowsurface_s60_p.h"
-#include "qpaintengine.h"
-#include "private/qmenubar_p.h"
-#include "private/qsoftkeymanager_p.h"
-#ifdef QT_GRAPHICSSYSTEM_RUNTIME
-#include "private/qgraphicssystem_runtime_p.h"
-#endif
-
-#include "apgwgnam.h" // For CApaWindowGroupName
-#include <mdaaudiotoneplayer.h> // For CMdaAudioToneUtility
-
-#if defined(Q_OS_SYMBIAN)
-# include <private/qs60mainapplication_p.h>
-# include <centralrepository.h>
-# include "qs60mainappui.h"
-# include "qinputcontext.h"
-#endif
-
-#if defined(Q_WS_S60)
-# if !defined(QT_NO_IM)
-# include <private/qcoefepinputcontext_p.h>
-# endif
-#endif
-
-#include "private/qstylesheetstyle_p.h"
-
-#include <hal.h>
-#include <hal_data.h>
-
-#ifdef Q_SYMBIAN_TRANSITION_EFFECTS
-#include <graphics/wstfxconst.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// Goom Events through Window Server
-static const int KGoomMemoryLowEvent = 0x10282DBF;
-static const int KGoomMemoryGoodEvent = 0x20026790;
-// Split view open/close events from AVKON
-static const int KSplitViewOpenEvent = 0x2001E2C0;
-static const int KSplitViewCloseEvent = 0x2001E2C1;
-
-#if defined(QT_DEBUG)
-static bool appNoGrab = false; // Grabbing enabled
-#endif
-static bool app_do_modal = false; // modal mode
-Q_GLOBAL_STATIC(QS60Data, qt_s60Data);
-
-extern bool qt_sendSpontaneousEvent(QObject*,QEvent*);
-extern QWidgetList *qt_modal_stack; // stack of modal widgets
-extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
-
-QWidget *qt_button_down = 0; // widget got last button-down
-
-QSymbianControl *QSymbianControl::lastFocusedControl = 0;
-
-QS60Data* qGlobalS60Data()
-{
- return qt_s60Data();
-}
-
-#ifdef Q_WS_S60
-void QS60Data::setStatusPaneAndButtonGroupVisibility(bool statusPaneVisible, bool buttonGroupVisible)
-{
- bool buttonGroupVisibilityChanged = false;
- if (CEikButtonGroupContainer *const b = buttonGroupContainer()) {
- buttonGroupVisibilityChanged = (b->IsVisible() != buttonGroupVisible);
- b->MakeVisible(buttonGroupVisible);
- }
- bool statusPaneVisibilityChanged = false;
- if (CEikStatusPane *const s = statusPane()) {
- statusPaneVisibilityChanged = (s->IsVisible() != statusPaneVisible);
- s->MakeVisible(statusPaneVisible);
- }
- if (buttonGroupVisibilityChanged || statusPaneVisibilityChanged) {
- const QSize size = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect()).size();
- const QSize oldSize; // note that QDesktopWidget::resizeEvent ignores the QResizeEvent contents
- QResizeEvent event(size, oldSize);
- QApplication::instance()->sendEvent(QApplication::desktop(), &event);
- }
- if (buttonGroupVisibilityChanged && !statusPaneVisibilityChanged && QApplication::activeWindow())
- // Ensure that control rectangle is updated
- static_cast<QSymbianControl *>(QApplication::activeWindow()->winId())->handleClientAreaChange();
-}
-
-bool QS60Data::setRecursiveDecorationsVisibility(QWidget *window, Qt::WindowStates newState)
-{
- // Show statusbar:
- // Topmost parent: Show unless fullscreen/minimized.
- // Child windows: Follow topmost parent, unless fullscreen, in which case do not show statusbar
- // Show CBA:
- // Topmost parent: Show unless fullscreen/minimized.
- // Exception: Show if fullscreen with Qt::WindowSoftkeysVisibleHint.
- // Child windows:
- // Minimized: Unclear if there is an use case for having focused minimized window at all.
- // Always follow topmost parent just to be safe.
- // Maximized and normal: follow topmost parent.
- // Exception: If topmost parent is not showing CBA, show CBA if any softkey actions are
- // defined.
- // Fullscreen: Show only if Qt::WindowSoftkeysVisibleHint set.
-
- Qt::WindowStates comparisonState = newState;
- QWidget *parentWindow = window->parentWidget();
- if (parentWindow) {
- while (parentWindow->parentWidget())
- parentWindow = parentWindow->parentWidget();
- comparisonState = parentWindow->windowState();
- } else {
- parentWindow = window;
- }
-
- bool decorationsVisible = !(comparisonState & (Qt::WindowFullScreen | Qt::WindowMinimized));
- const bool parentIsFullscreen = comparisonState & Qt::WindowFullScreen;
- const bool parentCbaVisibilityHint = parentWindow->windowFlags() & Qt::WindowSoftkeysVisibleHint;
- bool buttonGroupVisibility = (decorationsVisible || (parentIsFullscreen && parentCbaVisibilityHint));
-
- // Do extra checking for child windows
- if (window->parentWidget()) {
- if (newState & Qt::WindowFullScreen) {
- decorationsVisible = false;
- if (window->windowFlags() & Qt::WindowSoftkeysVisibleHint)
- buttonGroupVisibility = true;
- else
- buttonGroupVisibility = false;
- } else if (!(newState & Qt::WindowMinimized) && !buttonGroupVisibility) {
- for (int i = 0; i < window->actions().size(); ++i) {
- if (window->actions().at(i)->softKeyRole() != QAction::NoSoftKey) {
- buttonGroupVisibility = true;
- break;
- }
- }
- }
- }
-
- S60->setStatusPaneAndButtonGroupVisibility(decorationsVisible, buttonGroupVisibility);
-
- return decorationsVisible;
-}
-#endif
-
-void QS60Data::controlVisibilityChanged(CCoeControl *control, bool visible)
-{
- if (QWidgetPrivate::mapper && QWidgetPrivate::mapper->contains(control)) {
- QWidget *const widget = QWidgetPrivate::mapper->value(control);
- QWidget *const window = widget->window();
- if (QTLWExtra *topData = qt_widget_private(window)->maybeTopData()) {
- QWidgetBackingStoreTracker &backingStore = topData->backingStore;
- if (visible) {
- if (backingStore.data()) {
- backingStore.registerWidget(widget);
- } else {
- backingStore.create(window);
- backingStore.registerWidget(widget);
- qt_widget_private(widget)->invalidateBuffer(widget->rect());
- widget->repaint();
- }
- } else {
- // In certain special scenarios we may get an ENotVisible event
- // without a previous EPartiallyVisible. The backingstore must
- // still be destroyed, hence the registerWidget() call below.
- if (backingStore.data() && widget->internalWinId()
- && qt_widget_private(widget)->maybeBackingStore() == backingStore.data())
- backingStore.registerWidget(widget);
- backingStore.unregisterWidget(widget);
- // In order to ensure that any resources used by the window surface
- // are immediately freed, we flush the WSERV command buffer.
- S60->wsSession().Flush();
- }
- }
- }
-}
-
-bool qt_nograb() // application no-grab option
-{
-#if defined(QT_DEBUG)
- return appNoGrab;
-#else
- return false;
-#endif
-}
-
-// Modified from http://www3.symbian.com/faq.nsf/0/0F1464EE96E737E780256D5E00503DD1?OpenDocument
-class QS60Beep : public CBase, public MMdaAudioToneObserver
-{
-public:
- static QS60Beep* NewL(TInt aFrequency, TTimeIntervalMicroSeconds iDuration);
- void Play();
- ~QS60Beep();
-private:
- void ConstructL(TInt aFrequency, TTimeIntervalMicroSeconds iDuration);
- void MatoPrepareComplete(TInt aError);
- void MatoPlayComplete(TInt aError);
-private:
- typedef enum
- {
- EBeepNotPrepared,
- EBeepPrepared,
- EBeepPlaying
- } TBeepState;
-private:
- CMdaAudioToneUtility* iToneUtil;
- TBeepState iState;
- TInt iFrequency;
- TTimeIntervalMicroSeconds iDuration;
-};
-
-static QS60Beep* qt_S60Beep = 0;
-
-QS60Beep::~QS60Beep()
-{
- if (iToneUtil) {
- switch (iState) {
- case EBeepPlaying:
- iToneUtil->CancelPlay();
- break;
- case EBeepNotPrepared:
- iToneUtil->CancelPrepare();
- break;
- }
- }
- delete iToneUtil;
-}
-
-QS60Beep* QS60Beep::NewL(TInt aFrequency, TTimeIntervalMicroSeconds aDuration)
-{
- QS60Beep* self = new (ELeave) QS60Beep();
- CleanupStack::PushL(self);
- self->ConstructL(aFrequency, aDuration);
- CleanupStack::Pop();
- return self;
-}
-
-void QS60Beep::ConstructL(TInt aFrequency, TTimeIntervalMicroSeconds aDuration)
-{
- iToneUtil = CMdaAudioToneUtility::NewL(*this);
- iState = EBeepNotPrepared;
- iFrequency = aFrequency;
- iDuration = aDuration;
- iToneUtil->PrepareToPlayTone(iFrequency, iDuration);
-}
-
-void QS60Beep::Play()
-{
- if (iState == EBeepPlaying) {
- iToneUtil->CancelPlay();
- iState = EBeepPrepared;
- }
-
- iToneUtil->Play();
- iState = EBeepPlaying;
-}
-
-void QS60Beep::MatoPrepareComplete(TInt aError)
-{
- if (aError == KErrNone) {
- iState = EBeepPrepared;
- Play();
- }
-}
-
-void QS60Beep::MatoPlayComplete(TInt aError)
-{
- Q_UNUSED(aError);
- iState = EBeepPrepared;
-}
-
-
-static Qt::KeyboardModifiers mapToQtModifiers(TUint s60Modifiers)
-{
- Qt::KeyboardModifiers result = Qt::NoModifier;
-
- if (s60Modifiers & EModifierKeypad)
- result |= Qt::KeypadModifier;
- if (s60Modifiers & EModifierShift || s60Modifiers & EModifierLeftShift
- || s60Modifiers & EModifierRightShift)
- result |= Qt::ShiftModifier;
- if (s60Modifiers & EModifierCtrl || s60Modifiers & EModifierLeftCtrl
- || s60Modifiers & EModifierRightCtrl)
- result |= Qt::ControlModifier;
- if (s60Modifiers & EModifierAlt || s60Modifiers & EModifierLeftAlt
- || s60Modifiers & EModifierRightAlt)
- result |= Qt::AltModifier;
-
- return result;
-}
-
-static void mapS60MouseEventTypeToQt(QEvent::Type *type, Qt::MouseButton *button, const TPointerEvent *pEvent)
-{
- switch (pEvent->iType) {
- case TPointerEvent::EButton1Down:
- *type = QEvent::MouseButtonPress;
- *button = Qt::LeftButton;
- break;
- case TPointerEvent::EButton1Up:
- *type = QEvent::MouseButtonRelease;
- *button = Qt::LeftButton;
- break;
- case TPointerEvent::EButton2Down:
- *type = QEvent::MouseButtonPress;
- *button = Qt::MidButton;
- break;
- case TPointerEvent::EButton2Up:
- *type = QEvent::MouseButtonRelease;
- *button = Qt::MidButton;
- break;
- case TPointerEvent::EButton3Down:
- *type = QEvent::MouseButtonPress;
- *button = Qt::RightButton;
- break;
- case TPointerEvent::EButton3Up:
- *type = QEvent::MouseButtonRelease;
- *button = Qt::RightButton;
- break;
- case TPointerEvent::EDrag:
- *type = QEvent::MouseMove;
- *button = Qt::NoButton;
- break;
- case TPointerEvent::EMove:
- // Qt makes no distinction between move and drag
- *type = QEvent::MouseMove;
- *button = Qt::NoButton;
- break;
- default:
- *type = QEvent::None;
- *button = Qt::NoButton;
- break;
- }
- if (pEvent->iModifiers & EModifierDoubleClick){
- *type = QEvent::MouseButtonDblClick;
- }
-
- if (*type == QEvent::MouseButtonPress || *type == QEvent::MouseButtonDblClick)
- QApplicationPrivate::mouse_buttons = QApplicationPrivate::mouse_buttons | (*button);
- else if (*type == QEvent::MouseButtonRelease)
- QApplicationPrivate::mouse_buttons = QApplicationPrivate::mouse_buttons &(~(*button));
-
- QApplicationPrivate::mouse_buttons = QApplicationPrivate::mouse_buttons & Qt::MouseButtonMask;
-}
-
-//### Can be replaced with CAknLongTapDetector if animation is required.
-//NOTE: if CAknLongTapDetector is used make sure it gets variated out of 3.1 and 3.2,.
-//also MLongTapObserver needs to be changed to MAknLongTapDetectorCallBack if CAknLongTapDetector is used.
-class QLongTapTimer : public CTimer
-{
-public:
- static QLongTapTimer* NewL(QAbstractLongTapObserver *observer);
- QLongTapTimer(QAbstractLongTapObserver *observer);
- void ConstructL();
-public:
- void PointerEventL(const TPointerEvent &event);
- void RunL();
-protected:
-private:
- QAbstractLongTapObserver *m_observer;
- TPointerEvent m_event;
- QPoint m_pressedCoordinates;
- int m_dragDistance;
-};
-
-QLongTapTimer* QLongTapTimer::NewL(QAbstractLongTapObserver *observer)
-{
- QLongTapTimer* self = new QLongTapTimer(observer);
- self->ConstructL();
- return self;
-}
-void QLongTapTimer::ConstructL()
-{
- CTimer::ConstructL();
-}
-
-QLongTapTimer::QLongTapTimer(QAbstractLongTapObserver *observer):CTimer(CActive::EPriorityHigh)
-{
- m_observer = observer;
- m_dragDistance = qApp->startDragDistance();
- CActiveScheduler::Add(this);
-}
-
-void QLongTapTimer::PointerEventL(const TPointerEvent& event)
-{
- if ( event.iType == TPointerEvent::EDrag || event.iType == TPointerEvent::EButtonRepeat)
- {
- QPoint diff(QPoint(event.iPosition.iX,event.iPosition.iY) - m_pressedCoordinates);
- if (diff.manhattanLength() < m_dragDistance)
- return;
- }
- Cancel();
- m_event = event;
- if (event.iType == TPointerEvent::EButton1Down)
- {
- m_pressedCoordinates = QPoint(event.iPosition.iX,event.iPosition.iY);
- // must be same as KLongTapDelay in aknlongtapdetector.h
- After(800000);
- }
-}
-void QLongTapTimer::RunL()
-{
- if (m_observer)
- m_observer->HandleLongTapEventL(m_event.iPosition, m_event.iParentPosition);
-}
-
-QSymbianControl::QSymbianControl(QWidget *w)
- : CCoeControl()
- , qwidget(w)
- , m_longTapDetector(0)
- , m_ignoreFocusChanged(0)
- , m_symbianPopupIsOpen(0)
- , m_inExternalScreenOverride(false)
- , m_lastStatusPaneVisibility(0)
-{
-}
-
-void QSymbianControl::ConstructL(bool isWindowOwning, bool desktop)
-{
- if (!desktop)
- {
- if (isWindowOwning || !qwidget->parentWidget()
- || qwidget->parentWidget()->windowType() == Qt::Desktop) {
- RWindowGroup &wg(S60->windowGroup(qwidget));
- CreateWindowL(wg);
- } else {
- /**
- * TODO: in order to avoid creating windows for all ancestors of
- * this widget up to the root window, the parameter passed to
- * CreateWindowL should be
- * qwidget->parentWidget()->effectiveWinId(). However, if we do
- * this, then we need to take care of re-parenting when a window
- * is created for a widget between this one and the root window.
- */
- CreateWindowL(qwidget->parentWidget()->winId());
- }
-
- // Necessary in order to be able to track the activation status of
- // the control's window
- qwidget->d_func()->createExtra();
-
- SetFocusing(true);
- m_longTapDetector = QLongTapTimer::NewL(this);
- m_doubleClickTimer.invalidate();
-
- DrawableWindow()->SetPointerGrab(ETrue);
- }
-
-#ifdef Q_SYMBIAN_TRANSITION_EFFECTS
- if (OwnsWindow()) {
- TTfxWindowPurpose windowPurpose(ETfxPurposeNone);
- switch (qwidget->windowType()) {
- case Qt::Dialog:
- windowPurpose = ETfxPurposeDialogWindow;
- break;
- case Qt::Popup:
- windowPurpose = ETfxPurposePopupWindow;
- break;
- case Qt::Tool:
- windowPurpose = ETfxPurposeToolWindow;
- break;
- case Qt::ToolTip:
- windowPurpose = ETfxPurposeToolTipWindow;
- break;
- case Qt::SplashScreen:
- windowPurpose = ETfxPurposeSplashScreenWindow;
- break;
- default:
- windowPurpose = (isWindowOwning || !qwidget->parentWidget() || qwidget->parentWidget()->windowType() == Qt::Desktop)
- ? ETfxPurposeWindow : ETfxPurposeChildWindow;
- break;
- }
- Window().SetPurpose(windowPurpose);
- }
-#endif
-}
-
-QSymbianControl::~QSymbianControl()
-{
- // Ensure backing store is deleted before the top-level
- // window is destroyed
- qt_widget_private(qwidget)->topData()->backingStore.destroy();
-
- if (S60->curWin == this)
- S60->curWin = 0;
- if (!QApplicationPrivate::is_app_closing) {
- QT_TRY {
- setFocusSafely(false);
- } QT_CATCH(const std::exception&) {
- // ignore exceptions, nothing can be done
- }
- }
- S60->appUi()->RemoveFromStack(this);
- delete m_longTapDetector;
-}
-
-void QSymbianControl::setWidget(QWidget *w)
-{
- qwidget = w;
-}
-
-QPoint QSymbianControl::translatePointForFixedNativeOrientation(const TPoint &pointerEventPos) const
-{
- QPoint pos(pointerEventPos.iX, pointerEventPos.iY);
- if (qwidget->d_func()->fixNativeOrientationCalled) {
- QSize wsize = qwidget->size();
- TSize size = Size();
- if (size.iWidth == wsize.height() && size.iHeight == wsize.width()) {
- qreal x = pos.x();
- qreal y = pos.y();
- pos.setX(size.iHeight - y);
- pos.setY(x);
- }
- }
- return pos;
-}
-
-TRect QSymbianControl::translateRectForFixedNativeOrientation(const TRect &controlRect) const
-{
- TRect rect = controlRect;
- if (qwidget->d_func()->fixNativeOrientationCalled) {
- QPoint a = translatePointForFixedNativeOrientation(rect.iTl);
- QPoint b = translatePointForFixedNativeOrientation(rect.iBr);
- if (a.x() < b.x()) {
- rect.iTl.iX = a.x();
- rect.iBr.iX = b.x();
- } else {
- rect.iTl.iX = b.x();
- rect.iBr.iX = a.x();
- }
- if (a.y() < b.y()) {
- rect.iTl.iY = a.y();
- rect.iBr.iY = b.y();
- } else {
- rect.iTl.iY = b.y();
- rect.iBr.iY = a.y();
- }
- }
- return rect;
-}
-
-void QSymbianControl::HandleLongTapEventL( const TPoint& aPenEventLocation, const TPoint& aPenEventScreenLocation )
-{
- QWidget *alienWidget;
- QPoint widgetPos = translatePointForFixedNativeOrientation(aPenEventLocation);
- QPoint globalPos = translatePointForFixedNativeOrientation(aPenEventScreenLocation);
- alienWidget = qwidget->childAt(widgetPos);
- if (!alienWidget)
- alienWidget = qwidget;
-
-#if !defined(QT_NO_CONTEXTMENU)
- QContextMenuEvent contextMenuEvent(QContextMenuEvent::Mouse, widgetPos, globalPos, Qt::NoModifier);
- qt_sendSpontaneousEvent(alienWidget, &contextMenuEvent);
-#endif
-}
-
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
-void QSymbianControl::translateAdvancedPointerEvent(const TAdvancedPointerEvent *event)
-{
- QApplicationPrivate *d = QApplicationPrivate::instance();
- QPointF screenPos = qwidget->mapToGlobal(translatePointForFixedNativeOrientation(event->iPosition));
- qreal pressure;
- if(d->pressureSupported
- && event->Pressure() > 0) //workaround for misconfigured HAL
- pressure = event->Pressure() / qreal(d->maxTouchPressure);
- else
- pressure = qreal(1.0);
- processTouchEvent(event->PointerNumber(), event->iType, screenPos, pressure);
-}
-#endif
-
-void QSymbianControl::processTouchEvent(int pointerNumber, TPointerEvent::TType type, QPointF screenPos, qreal pressure)
-{
- QRect screenGeometry = qApp->desktop()->screenGeometry(qwidget);
-
- QApplicationPrivate *d = QApplicationPrivate::instance();
-
- QList<QTouchEvent::TouchPoint> points = d->appAllTouchPoints;
- while (points.count() <= pointerNumber)
- points.append(QTouchEvent::TouchPoint(points.count()));
-
- Qt::TouchPointStates allStates = 0;
- for (int i = 0; i < points.count(); ++i) {
- QTouchEvent::TouchPoint &touchPoint = points[i];
-
- if (touchPoint.id() == pointerNumber) {
- Qt::TouchPointStates state;
- switch (type) {
- case TPointerEvent::EButton1Down:
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- case TPointerEvent::EEnterHighPressure:
-#endif
- state = Qt::TouchPointPressed;
- break;
- case TPointerEvent::EButton1Up:
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- case TPointerEvent::EExitCloseProximity:
-#endif
- state = Qt::TouchPointReleased;
- break;
- case TPointerEvent::EDrag:
- state = Qt::TouchPointMoved;
- break;
- default:
- // how likely is this to happen?
- state = Qt::TouchPointStationary;
- break;
- }
- if (pointerNumber == 0)
- state |= Qt::TouchPointPrimary;
- touchPoint.setState(state);
-
- touchPoint.setScreenPos(screenPos);
- touchPoint.setNormalizedPos(QPointF(screenPos.x() / screenGeometry.width(),
- screenPos.y() / screenGeometry.height()));
-
- touchPoint.setPressure(pressure);
- } else if (touchPoint.state() != Qt::TouchPointReleased) {
- // all other active touch points should be marked as stationary
- touchPoint.setState(Qt::TouchPointStationary);
- }
-
- allStates |= touchPoint.state();
- }
-
- if ((allStates & Qt::TouchPointStateMask) == Qt::TouchPointReleased) {
- // all touch points released
- d->appAllTouchPoints.clear();
- } else {
- d->appAllTouchPoints = points;
- }
-
- QApplicationPrivate::translateRawTouchEvent(qwidget,
- QTouchEvent::TouchScreen,
- points);
-}
-
-void QSymbianControl::HandlePointerEventL(const TPointerEvent& pEvent)
-{
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- if (pEvent.IsAdvancedPointerEvent()) {
- const TAdvancedPointerEvent *advancedPointerEvent = pEvent.AdvancedPointerEvent();
- translateAdvancedPointerEvent(advancedPointerEvent);
- if (advancedPointerEvent->PointerNumber() != 0) {
- // only send mouse events for the first touch point
- return;
- }
- }
-#endif
-
- m_longTapDetector->PointerEventL(pEvent);
- QT_TRYCATCH_LEAVING(HandlePointerEvent(pEvent));
-}
-
-void QSymbianControl::HandlePointerEvent(const TPointerEvent& pEvent)
-{
- QMouseEvent::Type type;
- Qt::MouseButton button;
- mapS60MouseEventTypeToQt(&type, &button, &pEvent);
- Qt::KeyboardModifiers modifiers = mapToQtModifiers(pEvent.iModifiers);
-
- QPoint widgetPos = translatePointForFixedNativeOrientation(pEvent.iPosition);
- TPoint controlScreenPos = PositionRelativeToScreen();
- QPoint globalPos = QPoint(controlScreenPos.iX, controlScreenPos.iY) + widgetPos;
- S60->lastCursorPos = globalPos;
- S60->lastPointerEventPos = widgetPos;
-
- QWidget *mouseGrabber = QWidget::mouseGrabber();
-
- QWidget *popupWidget = qApp->activePopupWidget();
- QWidget *popupReceiver = 0;
- if (popupWidget) {
- QWidget *popupChild = popupWidget->childAt(popupWidget->mapFromGlobal(globalPos));
- popupReceiver = popupChild ? popupChild : popupWidget;
- }
-
- if (mouseGrabber) {
- if (popupReceiver) {
- sendMouseEvent(popupReceiver, type, globalPos, button, modifiers);
- } else {
- sendMouseEvent(mouseGrabber, type, globalPos, button, modifiers);
- }
- // No Enter/Leave events in grabbing mode.
- return;
- }
-
- QWidget *widgetUnderPointer = qwidget->childAt(widgetPos);
- if (!widgetUnderPointer)
- widgetUnderPointer = qwidget;
-
- QApplicationPrivate::dispatchEnterLeave(widgetUnderPointer, S60->lastPointerEventTarget);
- S60->lastPointerEventTarget = widgetUnderPointer;
-
- QWidget *receiver;
- if (!popupReceiver && S60->mousePressTarget && type != QEvent::MouseButtonPress) {
- receiver = S60->mousePressTarget;
- if (type == QEvent::MouseButtonRelease)
- S60->mousePressTarget = 0;
- } else {
- receiver = popupReceiver ? popupReceiver : widgetUnderPointer;
- if (type == QEvent::MouseButtonPress)
- S60->mousePressTarget = receiver;
- }
-
-#if !defined(QT_NO_CURSOR) && !defined(Q_SYMBIAN_FIXED_POINTER_CURSORS)
- if (S60->brokenPointerCursors)
- qt_symbian_move_cursor_sprite();
-#endif
-
-//Generate single touch event for S60 5.0 (has touchscreen, does not have advanced pointers)
-#ifndef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- if (S60->hasTouchscreen) {
- processTouchEvent(0, pEvent.iType, QPointF(globalPos), 1.0);
- }
-#endif
-
- sendMouseEvent(receiver, type, globalPos, button, modifiers);
-}
-
-#ifdef Q_WS_S60
-void QSymbianControl::HandleStatusPaneSizeChange()
-{
- QS60MainAppUi *s60AppUi = static_cast<QS60MainAppUi *>(S60->appUi());
- s60AppUi->HandleStatusPaneSizeChange();
-}
-#endif
-
-void QSymbianControl::sendMouseEvent(
- QWidget *receiver,
- QEvent::Type type,
- const QPoint &globalPos,
- Qt::MouseButton button,
- Qt::KeyboardModifiers modifiers)
-{
- Q_ASSERT(receiver);
- QMouseEvent mEvent(type, receiver->mapFromGlobal(globalPos), globalPos,
- button, QApplicationPrivate::mouse_buttons, modifiers);
- QEventDispatcherS60 *dispatcher;
- // It is theoretically possible for someone to install a different event dispatcher.
- if ((dispatcher = qobject_cast<QEventDispatcherS60 *>(receiver->d_func()->threadData->eventDispatcher)) != 0) {
- if (dispatcher->excludeUserInputEvents()) {
- dispatcher->saveInputEvent(this, receiver, new QMouseEvent(mEvent));
- return;
- }
- }
-
- sendMouseEvent(receiver, &mEvent);
-}
-
-bool QSymbianControl::sendMouseEvent(QWidget *widget, QMouseEvent *mEvent)
-{
- return qt_sendSpontaneousEvent(widget, mEvent);
-}
-
-TKeyResponse QSymbianControl::OfferKeyEventL(const TKeyEvent& keyEvent, TEventCode type)
-{
- TKeyResponse r = EKeyWasNotConsumed;
- QT_TRYCATCH_LEAVING(r = OfferKeyEvent(keyEvent, type));
- return r;
-}
-
-TKeyResponse QSymbianControl::OfferKeyEvent(const TKeyEvent& keyEvent, TEventCode type)
-{
- /*
- S60 has a confusing way of delivering key events. There are three types of
- events: EEventKey, EEventKeyDown and EEventKeyUp. When a key is pressed,
- EEventKeyDown is first generated, followed by EEventKey. Then, when the key is
- released, EEventKeyUp is generated.
- However, it is possible that only the EEventKey is generated alone, typically
- in relation to virtual keyboards. In that case we need to take care to
- generate both press and release events in Qt, since applications expect that.
- We do this by having three states for each used scan code, depending on the
- events received. See the switch below for what happens in each state
- transition.
- */
-
- if (type != EEventKeyDown)
- if (handleVirtualMouse(keyEvent, type) == EKeyWasConsumed)
- return EKeyWasConsumed;
-
- TKeyResponse ret = EKeyWasNotConsumed;
-#define GET_RETURN(x) (ret = ((x) == EKeyWasConsumed) ? EKeyWasConsumed : ret)
-
- // This top level switch corresponds to the states, and the inner switches
- // correspond to the transitions.
- QS60Data::ScanCodeState &scanCodeState = S60->scanCodeStates[keyEvent.iScanCode];
- switch (scanCodeState) {
- case QS60Data::Unpressed:
- switch (type) {
- case EEventKeyDown:
- scanCodeState = QS60Data::KeyDown;
- break;
- case EEventKey:
- GET_RETURN(sendSymbianKeyEvent(keyEvent, QEvent::KeyPress));
- GET_RETURN(sendSymbianKeyEvent(keyEvent, QEvent::KeyRelease));
- break;
- case EEventKeyUp:
- // No action.
- break;
- }
- break;
- case QS60Data::KeyDown:
- switch (type) {
- case EEventKeyDown:
- // This should never happen, just stay in this state to be safe.
- break;
- case EEventKey:
- GET_RETURN(sendSymbianKeyEvent(keyEvent, QEvent::KeyPress));
- scanCodeState = QS60Data::KeyDownAndKey;
- break;
- case EEventKeyUp:
- scanCodeState = QS60Data::Unpressed;
- break;
- }
- break;
- case QS60Data::KeyDownAndKey:
- switch (type) {
- case EEventKeyDown:
- // This should never happen, just stay in this state to be safe.
- break;
- case EEventKey:
- GET_RETURN(sendSymbianKeyEvent(keyEvent, QEvent::KeyRelease));
- GET_RETURN(sendSymbianKeyEvent(keyEvent, QEvent::KeyPress));
- break;
- case EEventKeyUp:
- GET_RETURN(sendSymbianKeyEvent(keyEvent, QEvent::KeyRelease));
- scanCodeState = QS60Data::Unpressed;
- break;
- }
- break;
- }
- return ret;
-
-#undef GET_RETURN
-}
-
-TKeyResponse QSymbianControl::sendSymbianKeyEvent(const TKeyEvent &keyEvent, QEvent::Type type)
-{
- // Because S60 does not generate keysyms for EKeyEventDown and EKeyEventUp
- // events, we need to cache the keysyms from the EKeyEvent events. This is what
- // resolveS60ScanCode does.
- TUint s60Keysym = QApplicationPrivate::resolveS60ScanCode(keyEvent.iScanCode,
- keyEvent.iCode);
- int keyCode;
- if (s60Keysym == EKeyNull){ //some key events have 0 in iCode, for them iScanCode should be used
- keyCode = qt_keymapper_private()->mapS60ScanCodesToQt(keyEvent.iScanCode);
- } else if (s60Keysym >= 0x20 && s60Keysym < ENonCharacterKeyBase) {
- // Normal characters keys.
- keyCode = s60Keysym;
- } else {
- // Special S60 keys.
- keyCode = qt_keymapper_private()->mapS60KeyToQt(s60Keysym);
- }
-
- Qt::KeyboardModifiers mods = mapToQtModifiers(keyEvent.iModifiers);
- QKeyEventEx qKeyEvent(type, keyCode, mods, qt_keymapper_private()->translateKeyEvent(keyCode, mods),
- (keyEvent.iRepeats != 0), 1, keyEvent.iScanCode, s60Keysym, keyEvent.iModifiers);
- QWidget *widget;
- widget = QWidget::keyboardGrabber();
- if (!widget) {
- if (QApplicationPrivate::popupWidgets != 0) {
- widget = QApplication::activePopupWidget()->focusWidget();
- if (!widget) {
- widget = QApplication::activePopupWidget();
- }
- } else {
- widget = QApplicationPrivate::focus_widget;
- if (!widget) {
- widget = qwidget;
- }
- }
- }
-
- QEventDispatcherS60 *dispatcher;
- // It is theoretically possible for someone to install a different event dispatcher.
- if ((dispatcher = qobject_cast<QEventDispatcherS60 *>(widget->d_func()->threadData->eventDispatcher)) != 0) {
- if (dispatcher->excludeUserInputEvents()) {
- dispatcher->saveInputEvent(this, widget, new QKeyEventEx(qKeyEvent));
- return EKeyWasConsumed;
- }
- }
- return sendKeyEvent(widget, &qKeyEvent);
-}
-
-TKeyResponse QSymbianControl::handleVirtualMouse(const TKeyEvent& keyEvent,TEventCode type)
-{
-#ifndef QT_NO_CURSOR
- if (S60->mouseInteractionEnabled && S60->virtualMouseRequired) {
- //translate keys to pointer
- if ((keyEvent.iScanCode >= EStdKeyLeftArrow && keyEvent.iScanCode <= EStdKeyDownArrow) ||
- (keyEvent.iScanCode >= EStdKeyDevice10 && keyEvent.iScanCode <= EStdKeyDevice13) ||
- keyEvent.iScanCode == EStdKeyDevice3) {
- QPoint pos = QCursor::pos();
- TPointerEvent fakeEvent;
- fakeEvent.iType = (TPointerEvent::TType)(-1);
- fakeEvent.iModifiers = keyEvent.iModifiers;
- TInt x = pos.x();
- TInt y = pos.y();
- if (type == EEventKeyUp) {
- S60->virtualMouseAccelTimeout.start();
- switch (keyEvent.iScanCode) {
- case EStdKeyLeftArrow:
- S60->virtualMousePressedKeys &= ~QS60Data::Left;
- break;
- case EStdKeyRightArrow:
- S60->virtualMousePressedKeys &= ~QS60Data::Right;
- break;
- case EStdKeyUpArrow:
- S60->virtualMousePressedKeys &= ~QS60Data::Up;
- break;
- case EStdKeyDownArrow:
- S60->virtualMousePressedKeys &= ~QS60Data::Down;
- break;
- // diagonal keys (named aliases don't exist in 3.1 SDK)
- case EStdKeyDevice10:
- S60->virtualMousePressedKeys &= ~QS60Data::LeftUp;
- break;
- case EStdKeyDevice11:
- S60->virtualMousePressedKeys &= ~QS60Data::RightUp;
- break;
- case EStdKeyDevice12:
- S60->virtualMousePressedKeys &= ~QS60Data::RightDown;
- break;
- case EStdKeyDevice13:
- S60->virtualMousePressedKeys &= ~QS60Data::LeftDown;
- break;
- case EStdKeyDevice3: //select
- if (S60->virtualMousePressedKeys & QS60Data::Select)
- fakeEvent.iType = TPointerEvent::EButton1Up;
- S60->virtualMousePressedKeys &= ~QS60Data::Select;
- break;
- }
- }
- else if (type == EEventKey) {
- int dx = 0;
- int dy = 0;
- if (keyEvent.iScanCode != EStdKeyDevice3) {
- m_doubleClickTimer.invalidate();
- //reset mouse accelleration after a short time with no moves
- const int maxTimeBetweenKeyEventsMs = 500;
- if (S60->virtualMouseAccelTimeout.isValid() &&
- S60->virtualMouseAccelTimeout.hasExpired(maxTimeBetweenKeyEventsMs)) {
- S60->virtualMouseAccelDX = 0;
- S60->virtualMouseAccelDY = 0;
- }
- S60->virtualMouseAccelTimeout.invalidate();
- }
- switch (keyEvent.iScanCode) {
- case EStdKeyLeftArrow:
- S60->virtualMousePressedKeys |= QS60Data::Left;
- dx = -1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyRightArrow:
- S60->virtualMousePressedKeys |= QS60Data::Right;
- dx = 1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyUpArrow:
- S60->virtualMousePressedKeys |= QS60Data::Up;
- dy = -1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyDownArrow:
- S60->virtualMousePressedKeys |= QS60Data::Down;
- dy = 1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyDevice10:
- S60->virtualMousePressedKeys |= QS60Data::LeftUp;
- dx = -1;
- dy = -1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyDevice11:
- S60->virtualMousePressedKeys |= QS60Data::RightUp;
- dx = 1;
- dy = -1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyDevice12:
- S60->virtualMousePressedKeys |= QS60Data::RightDown;
- dx = 1;
- dy = 1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyDevice13:
- S60->virtualMousePressedKeys |= QS60Data::LeftDown;
- dx = -1;
- dy = 1;
- fakeEvent.iType = TPointerEvent::EMove;
- break;
- case EStdKeyDevice3:
- // Platform bug. If you start pressing several keys simultaneously (for
- // example for drag'n'drop), Symbian starts producing spurious up and
- // down messages for some keys. Therefore, make sure we have a clean slate
- // of pressed keys before starting a new button press.
- if (S60->virtualMousePressedKeys & QS60Data::Select) {
- return EKeyWasConsumed;
- } else {
- S60->virtualMousePressedKeys |= QS60Data::Select;
- fakeEvent.iType = TPointerEvent::EButton1Down;
- if (m_doubleClickTimer.isValid()
- && !m_doubleClickTimer.hasExpired(QApplication::doubleClickInterval())) {
- fakeEvent.iModifiers |= EModifierDoubleClick;
- m_doubleClickTimer.invalidate();
- } else {
- m_doubleClickTimer.start();
- }
- }
- break;
- }
- if (dx) {
- int cdx = S60->virtualMouseAccelDX;
- //reset accel on change of sign, else double accel
- if (dx * cdx <= 0)
- cdx = dx;
- else
- cdx *= 4;
- //cap accelleration
- if (dx * cdx > S60->virtualMouseMaxAccel)
- cdx = dx * S60->virtualMouseMaxAccel;
- //move mouse position
- x += cdx;
- S60->virtualMouseAccelDX = cdx;
- }
-
- if (dy) {
- int cdy = S60->virtualMouseAccelDY;
- if (dy * cdy <= 0)
- cdy = dy;
- else
- cdy *= 4;
- if (dy * cdy > S60->virtualMouseMaxAccel)
- cdy = dy * S60->virtualMouseMaxAccel;
- y += cdy;
- S60->virtualMouseAccelDY = cdy;
- }
- }
- //clip to screen size (window server allows a sprite hotspot to be outside the screen)
- int screenNumber = S60->screenNumberForWidget(qwidget);
- if (x < 0)
- x = 0;
- else if (x >= S60->screenWidthInPixelsForScreen[screenNumber])
- x = S60->screenWidthInPixelsForScreen[screenNumber] - 1;
- if (y < 0)
- y = 0;
- else if (y >= S60->screenHeightInPixelsForScreen[screenNumber])
- y = S60->screenHeightInPixelsForScreen[screenNumber] - 1;
- TPoint epos(x, y);
- TPoint cpos = epos - PositionRelativeToScreen();
- fakeEvent.iPosition = cpos;
- fakeEvent.iParentPosition = epos;
- if(fakeEvent.iType != -1)
- HandlePointerEvent(fakeEvent);
- return EKeyWasConsumed;
- }
- }
-#endif
-
- return EKeyWasNotConsumed;
-}
-
-void QSymbianControl::sendInputEvent(QWidget *widget, QInputEvent *inputEvent)
-{
- switch (inputEvent->type()) {
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- sendKeyEvent(widget, static_cast<QKeyEvent *>(inputEvent));
- break;
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseMove:
- sendMouseEvent(widget, static_cast<QMouseEvent *>(inputEvent));
- break;
- default:
- // Shouldn't get here.
- Q_ASSERT_X(0 == 1, "QSymbianControl::sendInputEvent()", "inputEvent->type() is unknown");
- break;
- }
-}
-
-TKeyResponse QSymbianControl::sendKeyEvent(QWidget *widget, QKeyEvent *keyEvent)
-{
-#if !defined(QT_NO_IM) && defined(Q_WS_S60)
- if (widget && widget->isEnabled() && widget->testAttribute(Qt::WA_InputMethodEnabled)) {
- QInputContext *qic = widget->inputContext();
- if (qic && qic->filterEvent(keyEvent))
- return EKeyWasConsumed;
- }
-#endif // !defined(QT_NO_IM) && defined(Q_OS_SYMBIAN)
-
- if (widget && qt_sendSpontaneousEvent(widget, keyEvent))
- if (keyEvent->isAccepted())
- return EKeyWasConsumed;
-
- return EKeyWasNotConsumed;
-}
-
-#if !defined(QT_NO_IM) && defined(Q_WS_S60)
-TCoeInputCapabilities QSymbianControl::InputCapabilities() const
-{
- QWidget *w = 0;
-
- if (qwidget->hasFocus())
- w = qwidget;
- else
- w = qwidget->focusWidget();
-
- QCoeFepInputContext *ic;
- if (w && w->isEnabled() && w->testAttribute(Qt::WA_InputMethodEnabled)
- && (ic = qobject_cast<QCoeFepInputContext *>(w->inputContext()))) {
- return ic->inputCapabilities();
- } else {
- return TCoeInputCapabilities(TCoeInputCapabilities::ENone, 0, 0);
- }
-}
-#endif
-
-void QSymbianControl::Draw(const TRect& controlRect) const
-{
- // Set flag to avoid calling DrawNow in window surface
- QWidget *window = qwidget->window();
- Q_ASSERT(window);
- QTLWExtra *topExtra = window->d_func()->maybeTopData();
- Q_ASSERT(topExtra);
-
- TRect wcontrolRect = translateRectForFixedNativeOrientation(controlRect);
-
- if (!topExtra->inExpose) {
- topExtra->inExpose = true;
- if (!qwidget->isWindow()) {
- // If we get here, then it means we have a native child window
- // Since no content should ever be painted to these windows, we
- // erase them with a transparent brush when they get an expose.
- CWindowGc &gc = SystemGc();
- gc.SetBrushColor(TRgb(0, 0, 0, 0));
- gc.Clear(controlRect);
- }
- QRect exposeRect = qt_TRect2QRect(wcontrolRect);
- qwidget->d_func()->syncBackingStore(exposeRect);
- topExtra->inExpose = false;
- }
-
- QWindowSurface *surface = qwidget->windowSurface();
- QPaintEngine *engine = surface ? surface->paintDevice()->paintEngine() : NULL;
-
- if (!engine)
- return;
-
- const bool sendNativePaintEvents = qwidget->d_func()->extraData()->receiveNativePaintEvents;
- if (sendNativePaintEvents) {
- const QRect r = qt_TRect2QRect(wcontrolRect);
- QMetaObject::invokeMethod(qwidget, "beginNativePaintEvent", Qt::DirectConnection, Q_ARG(QRect, r));
- }
-
- // Map source rectangle into coordinates of the backing store.
- const QPoint controlBase(controlRect.iTl.iX, controlRect.iTl.iY);
- const QPoint backingStoreBase = qwidget->mapTo(qwidget->window(), controlBase);
- const TRect backingStoreRect(TPoint(backingStoreBase.x(), backingStoreBase.y()), controlRect.Size());
-
- if (engine->type() == QPaintEngine::Raster) {
- QS60WindowSurface *s60Surface;
-#ifdef QT_GRAPHICSSYSTEM_RUNTIME
- if (QApplicationPrivate::runtime_graphics_system) {
- QRuntimeWindowSurface *rtSurface =
- static_cast<QRuntimeWindowSurface*>(qwidget->windowSurface());
- s60Surface = static_cast<QS60WindowSurface *>(rtSurface->m_windowSurface.data());
- } else
-#endif
- s60Surface = static_cast<QS60WindowSurface *>(qwidget->windowSurface());
-
- CFbsBitmap *bitmap = s60Surface->symbianBitmap();
- CWindowGc &gc = SystemGc();
-
- QWExtra::NativePaintMode nativePaintMode = qwidget->d_func()->extraData()->nativePaintMode;
- if(qwidget->d_func()->paintOnScreen())
- nativePaintMode = QWExtra::Disable;
-
- switch(nativePaintMode) {
- case QWExtra::Disable:
- // Do nothing
- break;
- case QWExtra::Blit:
- case QWExtra::BlitWriteAlpha:
- if (qwidget->d_func()->isOpaque || nativePaintMode == QWExtra::BlitWriteAlpha)
- gc.SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
- gc.BitBlt(controlRect.iTl, bitmap, backingStoreRect);
- break;
- case QWExtra::ZeroFill:
- if (Window().DisplayMode() == EColor16MA
- || Window().DisplayMode() == Q_SYMBIAN_ECOLOR16MAP) {
- gc.SetBrushStyle(CGraphicsContext::ESolidBrush);
- gc.SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
- gc.SetBrushColor(TRgb::Color16MA(0));
- gc.Clear(controlRect);
- } else {
- gc.SetBrushColor(TRgb(0x000000));
- gc.Clear(controlRect);
- };
- break;
- default:
- Q_ASSERT(false);
- }
- }
-
- if (sendNativePaintEvents) {
- const QRect r = qt_TRect2QRect(wcontrolRect);
- // The draw ops aren't actually sent to WSERV until the graphics
- // context is deactivated, which happens in the function calling
- // this one. We therefore delay the delivery of endNativePaintEvent,
- // to ensure that drawing has completed by the time the widget
- // receives the event. Note that, if the widget needs to ensure
- // that the draw ops have actually been executed into the output
- // framebuffer, a call to RWsSession::Flush is required in the
- // endNativePaintEvent implementation.
- QMetaObject::invokeMethod(qwidget, "endNativePaintEvent", Qt::QueuedConnection, Q_ARG(QRect, r));
- }
-}
-
-void QSymbianControl::qwidgetResize_helper(const QSize &newSize)
-{
- QRect cr = qwidget->geometry();
- QSize oldSize(cr.size());
- cr.setSize(newSize);
- qwidget->data->crect = cr;
- if (qwidget->isVisible()) {
- QTLWExtra *tlwExtra = qwidget->d_func()->maybeTopData();
- bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
- if (!slowResize && tlwExtra)
- tlwExtra->inTopLevelResize = true;
- QResizeEvent e(newSize, oldSize);
- qt_sendSpontaneousEvent(qwidget, &e);
- if (!qwidget->testAttribute(Qt::WA_StaticContents))
- qwidget->d_func()->syncBackingStore();
- if (!slowResize && tlwExtra)
- tlwExtra->inTopLevelResize = false;
- } else {
- if (!qwidget->testAttribute(Qt::WA_PendingResizeEvent)) {
- QResizeEvent *e = new QResizeEvent(newSize, oldSize);
- QApplication::postEvent(qwidget, e);
- }
- }
-}
-
-void QSymbianControl::SizeChanged()
-{
- CCoeControl::SizeChanged();
-
- // When FixNativeOrientation had been called, the RWindow/CCoeControl size
- // and the surface/QWidget size have nothing to do with each other.
- if (qwidget->d_func()->fixNativeOrientationCalled)
- return;
-
- QSize oldSize = qwidget->size();
- QSize newSize(Size().iWidth, Size().iHeight);
-
- if (oldSize != newSize) {
- // Enforce the proper size for fullscreen widgets on the secondary screen.
- const bool isFullscreen = qwidget->windowState() & Qt::WindowFullScreen;
- const int screenNumber = S60->screenNumberForWidget(qwidget);
- if (!m_inExternalScreenOverride && isFullscreen && screenNumber > 0) {
- int screenWidth = S60->screenWidthInPixelsForScreen[screenNumber];
- int screenHeight = S60->screenHeightInPixelsForScreen[screenNumber];
- TSize screenSize(screenWidth, screenHeight);
- if (screenWidth > 0 && screenHeight > 0 && screenSize != Size()) {
- m_inExternalScreenOverride = true;
- SetExtent(TPoint(0, 0), screenSize);
- return;
- }
- }
-
- qwidgetResize_helper(newSize);
- }
-
- m_inExternalScreenOverride = false;
-
- // CCoeControl::SetExtent calls SizeChanged, but does not call
- // PositionChanged, so we call it here to ensure that the widget's
- // position is updated.
- PositionChanged();
-}
-
-void QSymbianControl::PositionChanged()
-{
- CCoeControl::PositionChanged();
-
- QPoint oldPos = qwidget->geometry().topLeft();
- QPoint newPos(Position().iX, Position().iY);
-
- if (oldPos != newPos) {
- QRect cr = qwidget->geometry();
- cr.moveTopLeft(newPos);
- qwidget->data->crect = cr;
- QTLWExtra *top = qwidget->d_func()->maybeTopData();
- if (top && (qwidget->windowState() & (~Qt::WindowActive)) == Qt::WindowNoState)
- top->normalGeometry.moveTopLeft(newPos);
- if (qwidget->isVisible()) {
- QMoveEvent e(newPos, oldPos);
- qt_sendSpontaneousEvent(qwidget, &e);
- } else {
- QMoveEvent * e = new QMoveEvent(newPos, oldPos);
- QApplication::postEvent(qwidget, e);
- }
- }
-}
-
-void QSymbianControl::FocusChanged(TDrawNow /* aDrawNow */)
-{
- if (m_ignoreFocusChanged || (qwidget->windowType() & Qt::WindowType_Mask) == Qt::Desktop)
- return;
-
-#ifdef Q_WS_S60
- if (S60->splitViewLastWidget)
- return;
-#endif
-
- // Popups never get focused, but still receive the FocusChanged when they are hidden.
- if (QApplicationPrivate::popupWidgets != 0
- || (qwidget->windowType() & Qt::Popup) == Qt::Popup)
- return;
-
- if (IsFocused() && IsVisible()) {
- if (m_symbianPopupIsOpen) {
- QWidget *fw = QApplication::focusWidget();
- if (fw) {
- QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
- QCoreApplication::sendEvent(fw, &event);
- }
- m_symbianPopupIsOpen = false;
- }
-
- QApplication::setActiveWindow(qwidget->window());
- qwidget->d_func()->setWindowIcon_sys(true);
- qwidget->d_func()->setWindowTitle_sys(qwidget->windowTitle());
-#ifdef Q_WS_S60
- if (qwidget->isWindow())
- S60->setRecursiveDecorationsVisibility(qwidget, qwidget->windowState());
-#endif
- } else if (QApplication::activeWindow() == qwidget->window()) {
- bool focusedControlFound = false;
- WId winId = 0;
- for (QWidget *w = qwidget->parentWidget(); w && (winId = w->internalWinId()); w = w->parentWidget()) {
- if (winId->IsFocused() && winId->IsVisible()) {
- focusedControlFound = true;
- break;
- } else if (w->isWindow())
- break;
- }
- if (!focusedControlFound) {
- if (CCoeEnv::Static()->AppUi()->IsDisplayingMenuOrDialog() || S60->menuBeingConstructed) {
- QWidget *fw = QApplication::focusWidget();
- if (fw) {
- QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
- QCoreApplication::sendEvent(fw, &event);
- }
- m_symbianPopupIsOpen = true;
- return;
- }
-
- QApplication::setActiveWindow(0);
- }
- }
- // else { We don't touch the active window unless we were explicitly activated or deactivated }
-}
-
-void QSymbianControl::handleClientAreaChange()
-{
- const bool cbaVisibilityHint = qwidget->windowFlags() & Qt::WindowSoftkeysVisibleHint;
- if (qwidget->isFullScreen() && !cbaVisibilityHint) {
- SetExtentToWholeScreen();
- } else if (qwidget->isMaximized() || (qwidget->isFullScreen() && cbaVisibilityHint)) {
- TRect r = static_cast<CEikAppUi*>(S60->appUi())->ClientRect();
- SetExtent(r.iTl, r.Size());
- } else if (!qwidget->isMinimized()) { // Normal geometry
- if (!qwidget->testAttribute(Qt::WA_Resized)) {
- qwidget->adjustSize();
- qwidget->setAttribute(Qt::WA_Resized, false); //not a user resize
- }
- if (!qwidget->testAttribute(Qt::WA_Moved) && qwidget->windowType() != Qt::Dialog) {
- TRect r = static_cast<CEikAppUi*>(S60->appUi())->ClientRect();
- SetPosition(r.iTl);
- qwidget->setAttribute(Qt::WA_Moved, false); // not really an explicit position
- }
- }
-}
-
-bool QSymbianControl::isSplitViewWidget(QWidget *widget) {
- bool returnValue = true;
- //Ignore events sent to non-active windows, not visible widgets and not parents of input widget.
- if (!qwidget->isActiveWindow()
- || !qwidget->isVisible()
- || !qwidget->isAncestorOf(widget)) {
-
- returnValue = false;
- }
- return returnValue;
-}
-
-void QSymbianControl::HandleResourceChange(int resourceType)
-{
- switch (resourceType) {
- case KSplitViewCloseEvent: //intentional fall-through
- case KSplitViewOpenEvent: {
-#if !defined(QT_NO_IM) && defined(Q_WS_S60)
-
- //Fetch widget getting the text input
- QWidget *widget = QWidget::keyboardGrabber();
- if (!widget) {
- if (QApplicationPrivate::popupWidgets) {
- widget = QApplication::activePopupWidget()->focusWidget();
- if (!widget) {
- widget = QApplication::activePopupWidget();
- }
- } else {
- widget = QApplicationPrivate::focus_widget;
- if (!widget) {
- widget = qwidget;
- }
- }
- }
- if (widget) {
- QCoeFepInputContext *ic = qobject_cast<QCoeFepInputContext *>(widget->inputContext());
- if (!ic) {
- ic = qobject_cast<QCoeFepInputContext *>(qApp->inputContext());
- }
- if (ic && isSplitViewWidget(widget)) {
- if (resourceType == KSplitViewCloseEvent) {
- ic->resetSplitViewWidget();
- } else {
- ic->ensureFocusWidgetVisible(widget);
- }
- }
- }
-#endif // !defined(QT_NO_IM) && defined(Q_WS_S60)
- }
- break;
- case KInternalStatusPaneChange:
- // When status pane is not visible, only handle client area change if status pane was
- // previously visible, as size changes to hidden status pane should not affect
- // client area.
- if (S60->statusPane() && (S60->statusPane()->IsVisible() || m_lastStatusPaneVisibility)) {
- m_lastStatusPaneVisibility = S60->statusPane()->IsVisible();
- handleClientAreaChange();
- }
- if (IsFocused() && IsVisible()) {
- qwidget->d_func()->setWindowIcon_sys(true);
- qwidget->d_func()->setWindowTitle_sys(qwidget->windowTitle());
- }
- break;
- case KUidValueCoeFontChangeEvent:
- // font change event
- break;
-#ifdef Q_WS_S60
- case KEikDynamicLayoutVariantSwitch:
- {
- handleClientAreaChange();
- // Send resize event to trigger desktopwidget workAreaResized signal
- if (qt_desktopWidget) {
- QResizeEvent e(qt_desktopWidget->size(), qt_desktopWidget->size());
- QApplication::sendEvent(qt_desktopWidget, &e);
- }
- break;
- }
-#endif
- default:
- break;
- }
-
- CCoeControl::HandleResourceChange(resourceType);
-
-}
-void QSymbianControl::CancelLongTapTimer()
-{
- m_longTapDetector->Cancel();
-}
-
-TTypeUid::Ptr QSymbianControl::MopSupplyObject(TTypeUid id)
-{
- if (id.iUid == ETypeId)
- return id.MakePtr(this);
-
- return CCoeControl::MopSupplyObject(id);
-}
-
-void QSymbianControl::setFocusSafely(bool focus)
-{
- // The stack hack in here is very unfortunate, but it is the only way to ensure proper
- // focus in Symbian. If this is not executed, the control which happens to be on
- // the top of the stack may randomly be assigned focus by Symbian, for example
- // when creating new windows (specifically in CCoeAppUi::HandleStackChanged()).
-
- // Close any popups.
- CEikonEnv::Static()->EikAppUi()->StopDisplayingMenuBar();
-
- if (focus) {
- S60->appUi()->RemoveFromStack(this);
- // Symbian doesn't automatically remove focus from the last focused control, so we need to
- // remember it and clear focus ourselves.
- if (lastFocusedControl && lastFocusedControl != this)
- lastFocusedControl->SetFocus(false);
- QT_TRAP_THROWING(S60->appUi()->AddToStackL(this,
- ECoeStackPriorityDefault + 1, ECoeStackFlagStandard)); // Note the + 1
- lastFocusedControl = this;
- this->SetFocus(true);
- } else {
- S60->appUi()->RemoveFromStack(this);
- QT_TRAP_THROWING(S60->appUi()->AddToStackL(this,
- ECoeStackPriorityDefault, ECoeStackFlagStandard));
- if(this == lastFocusedControl)
- lastFocusedControl = 0;
- this->SetFocus(false);
- }
-}
-
-bool QSymbianControl::isControlActive()
-{
- return IsActivated() ? true : false;
-}
-
-void QSymbianControl::ensureFixNativeOrientation()
-{
-#if defined(Q_SYMBIAN_SUPPORTS_FIXNATIVEORIENTATION)
- if (!qwidget->isWindow() || qwidget->windowType() == Qt::Desktop)
- return;
- if (S60->screenNumberForWidget(qwidget) > 0)
- return;
- const bool isFixed = qwidget->d_func()->fixNativeOrientationCalled;
- const bool isFixEnabled = qwidget->testAttribute(Qt::WA_SymbianNoSystemRotation);
- const bool isFullScreen = qwidget->windowState().testFlag(Qt::WindowFullScreen);
- if (isFullScreen && isFixEnabled) {
- const bool surfaceBasedGs =
- QApplicationPrivate::graphics_system_name == QLatin1String("openvg")
- || QApplicationPrivate::graphics_system_name == QLatin1String("opengl");
- if (!surfaceBasedGs)
- qwidget->setAttribute(Qt::WA_SymbianNoSystemRotation, false);
- if (!isFixed && surfaceBasedGs) {
- if (Window().FixNativeOrientation() == KErrNone) {
- qwidget->d_func()->fixNativeOrientationCalled = true;
- // The EGL window surface is now fixed to the native orientation
- // of the device, no matter what size we pass when creating it.
- // Enforce the same size for the QWidget too. For the underlying
- // CCoeControl and RWindow it is up to the system to resize them
- // when the standard auto-rotation mechanism is in use, we must not
- // change that behavior by forcing any size for those. In practice
- // this means that the QWidget and the underlying native control
- // dimensions will be out of sync when FixNativeOrientation was
- // called and the device is turned to the non-native (typically
- // landscape) orientation. The pointer event handling and certain
- // functions like Draw() will need to compensate for this.
- QSize newSize(S60->nativeScreenWidthInPixels, S60->nativeScreenHeightInPixels);
- if (qwidget->size() != newSize)
- qwidgetResize_helper(newSize);
- } else {
- qwidget->setAttribute(Qt::WA_SymbianNoSystemRotation, false);
- }
- }
- } else if (isFixed) {
- qwidget->setAttribute(Qt::WA_SymbianNoSystemRotation, false);
- qwidget->d_func()->fixNativeOrientationCalled = false;
- qwidget->hide();
- qwidget->d_func()->create_sys(0, false, true);
- qwidget->show();
- }
-#else
- qwidget->setAttribute(Qt::WA_SymbianNoSystemRotation, false);
-#endif
-}
-
-/*!
- \typedef QApplication::QS60MainApplicationFactory
- \since 4.6
-
- This is a typedef for a pointer to a function with the following
- signature:
-
- \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 47
-
- \sa QApplication::QApplication()
-*/
-
-/*!
- \since 4.6
-
- Creates an application using the application factory given in
- \a factory, and using \a argc command line arguments in \a argv.
- \a factory can be leaving, but the error will be converted to a
- standard exception.
-
- This function is only available on S60.
-*/
-QApplication::QApplication(QApplication::QS60MainApplicationFactory factory, int &argc, char **argv)
- : QCoreApplication(*new QApplicationPrivate(argc, argv, GuiClient, 0x040000))
-{
- Q_D(QApplication);
- S60->s60ApplicationFactory = factory;
- d->construct();
-}
-
-QApplication::QApplication(QApplication::QS60MainApplicationFactory factory, int &argc, char **argv, int _internal)
- : QCoreApplication(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
-{
- Q_D(QApplication);
- S60->s60ApplicationFactory = factory;
- d->construct();
- QApplicationPrivate::app_compile_version = _internal;
-}
-
-void qt_init(QApplicationPrivate * /* priv */, int)
-{
- if (!CCoeEnv::Static()) {
- // The S60 framework creates a new trap handler which will render any existing traps
- // invalid as long as it is active. This means that all code in main() that occurs after
- // the QApplication construction needs to be surrounded by a new trap, despite having
- // an outer one already. To avoid this, we save the original trap handler here, and set
- // it back after the S60 framework is constructed. Then we restore it right before the S60
- // framework destruction.
- TTrapHandler *origTrapHandler = User::TrapHandler();
-
- // The S60 framework has not been initialized. We need to do it.
- TApaApplicationFactory factory(S60->s60ApplicationFactory ?
- S60->s60ApplicationFactory : newS60Application);
- CApaCommandLine* commandLine = q_check_ptr(QCoreApplicationPrivate::symbianCommandLine());
- if (commandLine) {
- // After this construction, CEikonEnv will be available from CEikonEnv::Static().
- // (much like our qApp).
- QtEikonEnv* coe = new QtEikonEnv;
- //not using QT_TRAP_THROWING, because coe owns the cleanupstack so it can't be pushed there.
- TRAPD(err, coe->ConstructAppFromCommandLineL(factory, *commandLine));
- if(err != KErrNone) {
- qWarning() << "qt_init: Eikon application construct failed ("
- << err
- << "), maybe missing resource file on S60 3.1?";
- delete coe;
- qt_symbian_throwIfError(err);
- }
- }
-
- S60->s60InstalledTrapHandler = User::SetTrapHandler(origTrapHandler);
-
- S60->qtOwnsS60Environment = true;
- } else {
- S60->qtOwnsS60Environment = false;
- }
-
-#ifdef QT_NO_DEBUG
- if (!qgetenv("QT_S60_AUTO_FLUSH_WSERV").isEmpty())
-#endif
- S60->wsSession().SetAutoFlush(ETrue);
-
-#ifdef Q_SYMBIAN_WINDOW_SIZE_CACHE
- TRAP_IGNORE(S60->wsSession().EnableWindowSizeCacheL());
-#endif
-
- S60->updateScreenSize();
-
-
- TDisplayMode mode = S60->screenDevice()->DisplayMode();
- S60->screenDepth = TDisplayModeUtils::NumDisplayModeBitsPerPixel(mode);
-
- //NB: RWsSession::GetColorModeList tells you what window modes are supported,
- //not what bitmap formats.
- if(QSysInfo::symbianVersion() == QSysInfo::SV_9_2)
- S60->supportsPremultipliedAlpha = 0;
- else
- S60->supportsPremultipliedAlpha = 1;
-
- RProcess me;
- TSecureId securId = me.SecureId();
- S60->uid = securId.operator TUid();
-
- // enable focus events - used to re-enable mouse after focus changed between mouse and non mouse app,
- // and for dimming behind modal windows
- S60->windowGroup().EnableFocusChangeEvents();
-
- //Check if mouse interaction is supported (either EMouse=1 in the HAL, or EMachineUID is one of the phones known to support this)
- const TInt KMachineUidSamsungI8510 = 0x2000C51E;
- // HAL::Get(HALData::EPen, TInt& result) may set 'result' to 1 on some 3.1 systems (e.g. N95).
- // But we know that S60 systems below 5.0 did not support touch.
- static const bool touchIsUnsupportedOnSystem =
- QSysInfo::s60Version() == QSysInfo::SV_S60_3_1
- || QSysInfo::s60Version() == QSysInfo::SV_S60_3_2;
- TInt machineUID;
- TInt mouse;
- TInt touch;
- TInt err;
- err = HAL::Get(HALData::EMouse, mouse);
- if (err != KErrNone)
- mouse = 0;
- err = HAL::Get(HALData::EMachineUid, machineUID);
- if (err != KErrNone)
- machineUID = 0;
- err = HAL::Get(HALData::EPen, touch);
- if (err != KErrNone || touchIsUnsupportedOnSystem)
- touch = 0;
-#ifdef __WINS__
- if(QSysInfo::symbianVersion() <= QSysInfo::SV_9_4) {
- //for symbian SDK emulator, force values to match typical devices.
- mouse = 0;
- touch = touchIsUnsupportedOnSystem ? 0 : 1;
- }
-#endif
- if (mouse || machineUID == KMachineUidSamsungI8510) {
- S60->hasTouchscreen = false;
- S60->virtualMouseRequired = false;
- }
- else if (!touch) {
- S60->hasTouchscreen = false;
- S60->virtualMouseRequired = true;
- }
- else {
- S60->hasTouchscreen = true;
- S60->virtualMouseRequired = false;
- }
-
- S60->avkonComponentsSupportTransparency = false;
- S60->menuBeingConstructed = false;
-
-#ifdef Q_WS_S60
- TUid KCRUidAvkon = { 0x101F876E };
- TUint32 KAknAvkonTransparencyEnabled = 0x0000000D;
-
- CRepository* repository = 0;
- TRAP(err, repository = CRepository::NewL(KCRUidAvkon));
-
- if(err == KErrNone) {
- TInt value = 0;
- err = repository->Get(KAknAvkonTransparencyEnabled, value);
- if(err == KErrNone) {
- S60->avkonComponentsSupportTransparency = (value==1) ? true : false;
- }
- }
- delete repository;
- repository = 0;
-#endif
-
- qt_keymapper_private()->updateInputLanguage();
-
-#ifdef QT_KEYPAD_NAVIGATION
- if (touch) {
- QApplicationPrivate::navigationMode = Qt::NavigationModeNone;
- } else {
- QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadDirectional;
- }
-#endif
-
-#ifndef QT_NO_CURSOR
- //Check if window server pointer cursors are supported or not
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- //In generic binary, use the HAL and OS version
- //Any other known good phones should be added here.
- if (machineUID == KMachineUidSamsungI8510 || (QSysInfo::symbianVersion() != QSysInfo::SV_9_4
- && QSysInfo::symbianVersion() != QSysInfo::SV_9_3 && QSysInfo::symbianVersion()
- != QSysInfo::SV_9_2)) {
- S60->brokenPointerCursors = false;
- qt_symbian_setWindowGroupCursor(Qt::ArrowCursor, S60->windowGroup());
- }
- else
- S60->brokenPointerCursors = true;
-#endif
-
- if (S60->mouseInteractionEnabled) {
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors) {
- qt_symbian_set_pointer_sprite(Qt::ArrowCursor);
- qt_symbian_show_pointer_sprite();
- }
- else
-#endif
- S60->wsSession().SetPointerCursorMode(EPointerCursorNormal);
- }
-#endif
-
- QFont systemFont;
- systemFont.setFamily(systemFont.defaultFamily());
- QApplicationPrivate::setSystemFont(systemFont);
-
- QObject::connect(qApp, SIGNAL(aboutToQuit()), qApp, SLOT(_q_aboutToQuit()));
-
-#ifdef Q_SYMBIAN_SEMITRANSPARENT_BG_SURFACE
- QApplicationPrivate::instance()->useTranslucentEGLSurfaces = true;
-
- const TUid KIvePropertyCat = {0x2726beef};
- enum TIvePropertyChipType {
- EVCBCM2727B1 = 0x00000000,
- EVCBCM2763A0 = 0x04000100,
- EVCBCM2763B0 = 0x04000102,
- EVCBCM2763C0 = 0x04000103,
- EVCBCM2763C1 = 0x04000104,
- EVCBCMUnknown = 0x7fffffff
- };
-
- TInt chipType = EVCBCMUnknown;
- if (RProperty::Get(KIvePropertyCat, 0 /*chip type*/, chipType) == KErrNone) {
- if (chipType == EVCBCM2727B1) {
- // We have only 32MB GPU memory. Use raster surfaces
- // for transparent TLWs.
- QApplicationPrivate::instance()->useTranslucentEGLSurfaces = false;
- }
- } else {
- QApplicationPrivate::instance()->useTranslucentEGLSurfaces = false;
- }
- if (QApplicationPrivate::graphics_system_name == QLatin1String("raster"))
- QApplicationPrivate::instance()->useTranslucentEGLSurfaces = false;
-#else
- QApplicationPrivate::instance()->useTranslucentEGLSurfaces = false;
-#endif
-/*
- ### Commented out for now as parameter handling not needed in SOS(yet). Code below will break testlib with -o flag
- int argc = priv->argc;
- char **argv = priv->argv;
-
- // 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;
- }
-
-#if defined(QT_DEBUG)
- if (qstrcmp(argv[i], "-nograb") == 0)
- appNoGrab = !appNoGrab;
- else
-#endif // QT_DEBUG
- ;
- }
-*/
-
- // Register WId with the metatype system. This is to enable
- // QWidgetPrivate::create_sys to used delayed slot invocation in order
- // to destroy WId objects during reparenting.
- qRegisterMetaType<WId>("WId");
-}
-
-#ifdef QT_NO_FREETYPE
-extern void qt_cleanup_symbianFontDatabase(); // qfontdatabase_s60.cpp
-#endif
-
-/*****************************************************************************
- qt_cleanup() - cleans up when the application is finished
- *****************************************************************************/
-void qt_cleanup()
-{
-#ifdef Q_WS_S60
- S60->setButtonGroupContainer(0);
-#endif
- if(qt_S60Beep) {
- delete qt_S60Beep;
- qt_S60Beep = 0;
- }
- QFontCache::cleanup(); // Has to happen now, since QFontEngineS60 has FBS handles
- QPixmapCache::clear(); // Has to happen now, since QS60PixmapData has FBS handles
-
-#ifdef QT_NO_FREETYPE
- qt_cleanup_symbianFontDatabase();
-#endif
-// S60 structure and window server session are freed in eventdispatcher destructor as they are needed there
-
- // It's important that this happens here, before the event dispatcher gets
- // deleted, because the input context needs the event loop one last time before
- // it dies.
- delete QApplicationPrivate::inputContext;
- QApplicationPrivate::inputContext = 0;
-
- //Change mouse pointer back
- S60->wsSession().SetPointerCursorMode(EPointerCursorNone);
-
-#ifdef Q_WS_S60
- // Clear CBA
- CEikonEnv::Static()->AppUiFactory()->SwapButtonGroup(0);
- delete S60->buttonGroupContainer();
- S60->setButtonGroupContainer(0);
-#endif
-
- // Call EndFullScreen() to prevent confusing the system effect state machine.
- qt_endFullScreenEffect();
-
- if (S60->qtOwnsS60Environment) {
- // Restore the S60 framework trap handler. See qt_init().
- User::SetTrapHandler(S60->s60InstalledTrapHandler);
-
- CEikonEnv* coe = CEikonEnv::Static();
- coe->PrepareToExit();
- // The CEikonEnv itself is destroyed in here.
- coe->DestroyEnvironment();
- }
-}
-
-void QApplicationPrivate::initializeWidgetPaletteHash()
-{
- // TODO: Implement QApplicationPrivate::initializeWidgetPaletteHash()
- // Possibly a task fot the S60Style guys
-}
-
-void QApplicationPrivate::createEventDispatcher()
-{
- Q_Q(QApplication);
- eventDispatcher = new QEventDispatcherS60(q);
-}
-
-QString QApplicationPrivate::appName() const
-{
- return QCoreApplicationPrivate::appName();
-}
-
-bool QApplicationPrivate::modalState()
-{
- return app_do_modal;
-}
-
-void QApplicationPrivate::enterModal_sys(QWidget *widget)
-{
-#ifdef Q_SYMBIAN_TRANSITION_EFFECTS
- S60->wsSession().SendEffectCommand(ETfxCmdAppModalModeEnter);
-#endif
- if (widget) {
- static_cast<QSymbianControl *>(widget->effectiveWinId())->FadeBehindPopup(ETrue);
- // Modal partial screen dialogs (like queries) capture pointer events.
- // ### FixMe: Add specialized behaviour for fullscreen modal dialogs
- widget->effectiveWinId()->SetGloballyCapturing(ETrue);
- widget->effectiveWinId()->SetPointerCapture(ETrue);
- }
- 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)
-{
-#ifdef Q_SYMBIAN_TRANSITION_EFFECTS
- S60->wsSession().SendEffectCommand(ETfxCmdAppModalModeExit);
-#endif
- if (widget) {
- static_cast<QSymbianControl *>(widget->effectiveWinId())->FadeBehindPopup(EFalse);
- // ### FixMe: Add specialized behaviour for fullscreen modal dialogs
- widget->effectiveWinId()->SetGloballyCapturing(EFalse);
- widget->effectiveWinId()->SetPointerCapture(EFalse);
- }
- 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;
-}
-
-void QApplicationPrivate::openPopup(QWidget *popup)
-{
- if (popup && qobject_cast<QComboBox *>(popup->parentWidget()))
- static_cast<QSymbianControl *>(popup->effectiveWinId())->FadeBehindPopup(ETrue);
-
- if (!QApplicationPrivate::popupWidgets)
- QApplicationPrivate::popupWidgets = new QWidgetList;
- QApplicationPrivate::popupWidgets->append(popup);
-
- // Cancel focus widget pointer capture and long tap timer
- if (QApplication::focusWidget()) {
- static_cast<QSymbianControl*>(QApplication::focusWidget()->effectiveWinId())->CancelLongTapTimer();
- QApplication::focusWidget()->effectiveWinId()->SetPointerCapture(false);
- }
-
- if (!qt_nograb()) {
- // Cancel pointer capture and long tap timer for earlier popup
- int popupCount = QApplicationPrivate::popupWidgets->count();
- if (popupCount > 1) {
- QWidget* prevPopup = QApplicationPrivate::popupWidgets->at(popupCount-2);
- static_cast<QSymbianControl*>(prevPopup->effectiveWinId())->CancelLongTapTimer();
- prevPopup->effectiveWinId()->SetPointerCapture(false);
- }
-
- // Enable pointer capture for this (topmost) popup
- Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
- WId id = popup->effectiveWinId();
- id->SetPointerCapture(true);
- }
-
- // 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
- QWidget *fw = popup->focusWidget();
- if (fw) {
- fw->setFocus(Qt::PopupFocusReason);
- } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup
- fw = QApplication::focusWidget();
- if (fw) {
- QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
- q_func()->sendEvent(fw, &e);
- }
- }
-}
-
-void QApplicationPrivate::closePopup(QWidget *popup)
-{
- if (popup && qobject_cast<QComboBox *>(popup->parentWidget()))
- static_cast<QSymbianControl *>(popup->effectiveWinId())->FadeBehindPopup(EFalse);
-
- if (!QApplicationPrivate::popupWidgets)
- return;
- QApplicationPrivate::popupWidgets->removeAll(popup);
-
- // Cancel pointer capture and long tap for this popup
- WId id = popup->effectiveWinId();
- id->SetPointerCapture(false);
- static_cast<QSymbianControl*>(id)->CancelLongTapTimer();
-
- if (QApplicationPrivate::popupWidgets->isEmpty()) { // this was the last popup
- delete QApplicationPrivate::popupWidgets;
- QApplicationPrivate::popupWidgets = 0;
- if (!qt_nograb()) { // grabbing not disabled
- Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
- if (QWidgetPrivate::mouseGrabber != 0)
- QWidgetPrivate::mouseGrabber->grabMouse();
-
- if (QWidgetPrivate::keyboardGrabber != 0)
- QWidgetPrivate::keyboardGrabber->grabKeyboard();
-
- QWidget *fw = QApplicationPrivate::active_window ? QApplicationPrivate::active_window->focusWidget()
- : q_func()->focusWidget();
- if (fw) {
- if(fw->window()->isModal()) // restore pointer capture for modal window
- fw->effectiveWinId()->SetPointerCapture(true);
-
- if (fw != q_func()->focusWidget()) {
- fw->setFocus(Qt::PopupFocusReason);
- } else {
- QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
- q_func()->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 = QApplication::focusWidget()) {
- QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
- q_func()->sendEvent(fw, &e);
- }
-
- // Enable pointer capture for previous popup
- if (aw) {
- aw->effectiveWinId()->SetPointerCapture(true);
- }
- }
-}
-
-QWidget * QApplication::topLevelAt(QPoint const& point)
-{
- QWidget *found = 0;
- int lowestZ = INT_MAX;
- QWidgetList list = QApplication::topLevelWidgets();
- for (int i = 0; i < list.count(); ++i) {
- QWidget *widget = list.at(i);
- if (widget->isVisible() && !(widget->windowType() == Qt::Desktop)) {
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- if (widget->geometry().adjusted(0,0,1,1).contains(point)) {
- // At this point we know there is a Qt widget under the point.
- // Now we need to make sure it is the top most in the z-order.
- RDrawableWindow *const window = widget->effectiveWinId()->DrawableWindow();
- int z = window->OrdinalPosition();
- if (z < lowestZ) {
- lowestZ = z;
- found = widget;
- }
- }
- }
- }
- return found;
-}
-
-void QApplication::alert(QWidget * /* widget */, int /* duration */)
-{
- // TODO: Implement QApplication::alert(QWidget *widget, int duration)
-}
-
-int QApplication::doubleClickInterval()
-{
- TTimeIntervalMicroSeconds32 us;
- TInt distance;
- S60->wsSession().GetDoubleClickSettings(us, distance);
- return (us.Int() / 1000);
-}
-
-void QApplication::setDoubleClickInterval(int ms)
-{
- TTimeIntervalMicroSeconds32 newUs( ms * 1000);
- TTimeIntervalMicroSeconds32 us;
- TInt distance;
- S60->wsSession().GetDoubleClickSettings(us, distance);
- if (us != newUs)
- S60->wsSession().SetDoubleClick(newUs, distance);
-}
-
-int QApplication::keyboardInputInterval()
-{
- return QApplicationPrivate::keyboard_input_time;
-}
-
-void QApplication::setKeyboardInputInterval(int ms)
-{
- QApplicationPrivate::keyboard_input_time = ms;
-}
-
-int QApplication::cursorFlashTime()
-{
- return QApplicationPrivate::cursor_flash_time;
-}
-
-void QApplication::setCursorFlashTime(int msecs)
-{
- QApplicationPrivate::cursor_flash_time = msecs;
-}
-
-void QApplication::beep()
-{
- if (!qt_S60Beep) {
- TInt frequency = 880;
- TTimeIntervalMicroSeconds duration(500000);
- TRAP_IGNORE(qt_S60Beep=QS60Beep::NewL(frequency, duration));
- }
- if (qt_S60Beep)
- qt_S60Beep->Play();
-}
-
-static inline bool callSymbianEventFilters(const QSymbianEvent *event)
-{
- long unused;
- return qApp->filterEvent(const_cast<QSymbianEvent *>(event), &unused);
-}
-
-/*!
- \warning This function is only available on Symbian.
- \since 4.6
-
- This function processes an individual Symbian event
- \a event. It returns 1 if the event was handled, 0 if
- the \a event was not handled, and -1 if the event was
- not handled because the event is not known to Qt.
- */
-
-int QApplication::symbianProcessEvent(const QSymbianEvent *event)
-{
- Q_D(QApplication);
-
- QScopedLoopLevelCounter counter(d->threadData);
-
- if (d->eventDispatcher->filterEvent(const_cast<QSymbianEvent *>(event)))
- return 1;
-
- QWidget *w = qApp ? qApp->focusWidget() : 0;
- if (w) {
- QInputContext *ic = w->inputContext();
- if (ic && ic->symbianFilterEvent(w, event))
- return 1;
- }
-
- if (symbianEventFilter(event))
- return 1;
-
- switch (event->type()) {
- case QSymbianEvent::WindowServerEvent:
- return d->symbianProcessWsEvent(event);
- case QSymbianEvent::CommandEvent:
- return d->symbianHandleCommand(event);
- case QSymbianEvent::ResourceChangeEvent:
- return d->symbianResourceChange(event);
- default:
- return -1;
- }
-}
-
-int QApplicationPrivate::symbianProcessWsEvent(const QSymbianEvent *symbianEvent)
-{
- // Qt event handling. Handle some events regardless of if the handle is in our
- // widget map or not.
- const TWsEvent *event = symbianEvent->windowServerEvent();
- CCoeControl* control = reinterpret_cast<CCoeControl*>(event->Handle());
- const bool controlInMap = QWidgetPrivate::mapper && QWidgetPrivate::mapper->contains(control);
- switch (event->Type()) {
- case EEventPointerEnter:
- if (controlInMap) {
- callSymbianEventFilters(symbianEvent);
- return 1; // Qt::Enter will be generated in HandlePointerL
- }
- break;
- case EEventPointerExit:
- if (controlInMap) {
- if (callSymbianEventFilters(symbianEvent))
- return 1;
- if (S60) {
- // mouseEvent outside our window, send leave event to last focused widget
- QMouseEvent mEvent(QEvent::Leave, S60->lastPointerEventPos, S60->lastCursorPos,
- Qt::NoButton, QApplicationPrivate::mouse_buttons, Qt::NoModifier);
- if (S60->lastPointerEventTarget)
- qt_sendSpontaneousEvent(S60->lastPointerEventTarget,&mEvent);
- S60->lastPointerEventTarget = 0;
- }
- return 1;
- }
- break;
- case EEventScreenDeviceChanged: // fallthrough
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- case EEventDisplayChanged:
-#endif
- if (callSymbianEventFilters(symbianEvent))
- return 1;
- if (S60)
- S60->updateScreenSize();
- if (qt_desktopWidget) {
- QSize oldSize = qt_desktopWidget->size();
- qt_desktopWidget->data->crect.setWidth(S60->screenWidthInPixels);
- qt_desktopWidget->data->crect.setHeight(S60->screenHeightInPixels);
- QResizeEvent e(qt_desktopWidget->size(), oldSize);
- QApplication::sendEvent(qt_desktopWidget, &e);
- }
- return 0; // Propagate to CONE
- case EEventWindowVisibilityChanged:
- if (controlInMap) {
- if (callSymbianEventFilters(symbianEvent))
- return 1;
- const TWsVisibilityChangedEvent *visChangedEvent = event->VisibilityChanged();
- if (visChangedEvent->iFlags & TWsVisibilityChangedEvent::ENotVisible)
- S60->controlVisibilityChanged(control, false);
- else if (visChangedEvent->iFlags & TWsVisibilityChangedEvent::EPartiallyVisible)
- S60->controlVisibilityChanged(control, true);
- return 1;
- }
- break;
- case EEventFocusGained:
- if (callSymbianEventFilters(symbianEvent))
- return 1;
-#ifndef QT_NO_CURSOR
- //re-enable mouse interaction
- if (S60->mouseInteractionEnabled) {
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors)
- qt_symbian_show_pointer_sprite();
- else
-#endif
- S60->wsSession().SetPointerCursorMode(EPointerCursorNormal);
- }
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- if (!CEikonEnv::Static()->EikAppUi()->IsDisplayingMenuOrDialog())
- QSoftKeyManager::updateSoftKeys();
-#endif
- break;
- case EEventFocusLost:
- if (callSymbianEventFilters(symbianEvent))
- return 1;
-#ifndef QT_NO_CURSOR
- //disable mouse as may be moving to application that does not support it
- if (S60->mouseInteractionEnabled) {
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors)
- qt_symbian_hide_pointer_sprite();
- else
-#endif
- S60->wsSession().SetPointerCursorMode(EPointerCursorNone);
- }
-#endif
- break;
- case KGoomMemoryLowEvent:
-#ifdef QT_DEBUG
- qDebug() << "QApplicationPrivate::symbianProcessWsEvent - KGoomMemoryLowEvent";
-#endif
- if (callSymbianEventFilters(symbianEvent))
- return 1;
-#ifdef QT_GRAPHICSSYSTEM_RUNTIME
- if(QApplicationPrivate::runtime_graphics_system) {
- bool switchToSwRendering(false);
-
- foreach (QWidget *w, QApplication::topLevelWidgets()) {
- if(w->d_func()->topData()->backingStore) {
- switchToSwRendering = true;
- break;
- }
- }
-
- if (switchToSwRendering) {
- QRuntimeGraphicsSystem *gs =
- static_cast<QRuntimeGraphicsSystem*>(QApplicationPrivate::graphics_system);
- gs->setGraphicsSystem(QLatin1String("raster"));
- }
- }
-#endif
- break;
- case KGoomMemoryGoodEvent:
-#ifdef QT_DEBUG
- qDebug() << "QApplicationPrivate::symbianProcessWsEvent - KGoomMemoryGoodEvent";
-#endif
- if (callSymbianEventFilters(symbianEvent))
- return 1;
-#ifdef QT_GRAPHICSSYSTEM_RUNTIME
- if(QApplicationPrivate::runtime_graphics_system) {
- QRuntimeGraphicsSystem *gs =
- static_cast<QRuntimeGraphicsSystem*>(QApplicationPrivate::graphics_system);
- gs->setGraphicsSystem(QLatin1String("openvg"));
- }
-#endif
- break;
-#ifdef Q_SYMBIAN_SUPPORTS_SURFACES
- case EEventUser:
- {
- // GOOM is looking for candidates to kill so indicate that we are
- // capable of cleaning up by handling this event
- TInt32 *data = reinterpret_cast<TInt32 *>(event->EventData());
- if (data[0] == EApaSystemEventShutdown && data[1] == KGoomMemoryLowEvent)
- return 1;
- }
- break;
-#endif
-
-#ifdef Q_WS_S60
- case KEikInputLanguageChange:
- qt_keymapper_private()->updateInputLanguage();
- break;
-#endif
-
- default:
- break;
- }
-
- if (!controlInMap)
- return -1;
-
- return 0;
-}
-
-/*!
- \warning This virtual function is only available on Symbian.
- \since 4.6
-
- If you create an application that inherits QApplication and reimplement
- this function, you get direct access to events that the are received
- from Symbian. 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, and does nothing with \a event.
- */
-bool QApplication::symbianEventFilter(const QSymbianEvent *event)
-{
- Q_UNUSED(event);
- return false;
-}
-
-/*!
- \warning This function is only available on Symbian.
- \since 4.6
-
- Handles \a{command}s which are typically handled by
- CAknAppUi::HandleCommandL(). Qts Ui integration into Symbian is
- partially achieved by deriving from CAknAppUi. Currently, exit,
- menu and softkey commands are handled.
-
- \sa s60EventFilter(), s60ProcessEvent()
-*/
-int QApplicationPrivate::symbianHandleCommand(const QSymbianEvent *symbianEvent)
-{
- Q_Q(QApplication);
- int ret = 0;
-
- if (callSymbianEventFilters(symbianEvent))
- return 1;
-
- int command = symbianEvent->command();
-
- switch (command) {
-#ifdef Q_WS_S60
- case EAknSoftkeyExit: {
- QCloseEvent ev;
- QApplication::sendSpontaneousEvent(q, &ev);
- if (ev.isAccepted()) {
- q->quit();
- ret = 1;
- }
- break;
- }
-#endif
- case EEikCmdExit:
- q->quit();
- ret = 1;
- break;
- default:
-#ifdef Q_WS_S60
- bool handled = QSoftKeyManager::handleCommand(command);
- if (handled)
- ret = 1;
- else
- ret = QMenuBarPrivate::symbianCommands(command);
-#endif
- break;
- }
-
- return ret;
-}
-
-/*!
- \warning This function is only available on Symbian.
- \since 4.6
-
- Handles the resource change specified by \a type.
-
- Currently, KEikDynamicLayoutVariantSwitch and
- KAknsMessageSkinChange are handled.
- */
-int QApplicationPrivate::symbianResourceChange(const QSymbianEvent *symbianEvent)
-{
- int ret = 0;
-
- int type = symbianEvent->resourceChangeType();
-
- switch (type) {
-#ifdef Q_WS_S60
- case KEikDynamicLayoutVariantSwitch:
- {
- if (callSymbianEventFilters(symbianEvent))
- return 1;
- if (S60)
- S60->updateScreenSize();
-
-#ifndef QT_NO_STYLE_S60
- QS60Style *s60Style = 0;
-
-#ifndef QT_NO_STYLE_STYLESHEET
- QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplication::style());
- if (proxy)
- s60Style = qobject_cast<QS60Style*>(proxy->baseStyle());
- else
-#endif
- s60Style = qobject_cast<QS60Style*>(QApplication::style());
-
- if (s60Style) {
- s60Style->d_func()->handleDynamicLayoutVariantSwitch();
- ret = 1;
- }
-#endif
- }
- break;
-
-#ifndef QT_NO_STYLE_S60
- case KAknsMessageSkinChange:
- if (callSymbianEventFilters(symbianEvent))
- return 1;
- if (QS60Style *s60Style = qobject_cast<QS60Style*>(QApplication::style())) {
- s60Style->d_func()->handleSkinChange();
- ret = 1;
- }
- break;
-#endif
-#endif // Q_WS_S60
- default:
- break;
- }
-
- return ret;
-}
-
-#ifndef QT_NO_WHEELEVENT
-int QApplication::wheelScrollLines()
-{
- return QApplicationPrivate::wheel_scroll_lines;
-}
-
-void QApplication::setWheelScrollLines(int n)
-{
- QApplicationPrivate::wheel_scroll_lines = n;
-}
-#endif //QT_NO_WHEELEVENT
-
-bool QApplication::isEffectEnabled(Qt::UIEffect /* effect */)
-{
- // TODO: Implement QApplication::isEffectEnabled(Qt::UIEffect effect)
- return false;
-}
-
-void QApplication::setEffectEnabled(Qt::UIEffect /* effect */, bool /* enable */)
-{
- // TODO: Implement QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
-}
-
-TUint QApplicationPrivate::resolveS60ScanCode(TInt scanCode, TUint keysym)
-{
- if (!scanCode)
- return keysym;
-
- QApplicationPrivate *d = QApplicationPrivate::instance();
-
- if (keysym) {
- // If keysym is specified, cache it.
- d->scanCodeCache.insert(scanCode, keysym);
- return keysym;
- } else {
- // If not, retrieve the cached version.
- return d->scanCodeCache[scanCode];
- }
-}
-
-void QApplicationPrivate::initializeMultitouch_sys()
-{
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- if (HAL::Get(HALData::EPointer3DPressureSupported, pressureSupported) != KErrNone)
- pressureSupported = 0;
- if (HAL::Get(HALData::EPointer3DMaxPressure, maxTouchPressure) != KErrNone)
- maxTouchPressure = KMaxTInt;
-#else
- pressureSupported = 0;
- maxTouchPressure = KMaxTInt;
-#endif
-}
-
-void QApplicationPrivate::cleanupMultitouch_sys()
-{ }
-
-#ifndef QT_NO_SESSIONMANAGER
-QSessionManager::QSessionManager(QApplication * /* app */, QString & /* id */, QString& /* key */)
-{
-
-}
-
-QSessionManager::~QSessionManager()
-{
-
-}
-
-bool QSessionManager::allowsInteraction()
-{
- return false;
-}
-
-void QSessionManager::cancel()
-{
-
-}
-#endif //QT_NO_SESSIONMANAGER
-
-#ifdef QT_KEYPAD_NAVIGATION
-/*
- * Show/Hide the mouse cursor depending on phone type and chosen mode
- */
-void QApplicationPrivate::setNavigationMode(Qt::NavigationMode mode)
-{
-#ifndef QT_NO_CURSOR
- const bool wasCursorOn = (QApplicationPrivate::navigationMode == Qt::NavigationModeCursorAuto
- && !S60->hasTouchscreen)
- || QApplicationPrivate::navigationMode == Qt::NavigationModeCursorForceVisible;
- const bool isCursorOn = (mode == Qt::NavigationModeCursorAuto
- && !S60->hasTouchscreen)
- || mode == Qt::NavigationModeCursorForceVisible;
-
- if (!wasCursorOn && isCursorOn) {
- //Show the cursor, when changing from another mode to cursor mode
- qt_symbian_set_cursor_visible(true);
- }
- else if (wasCursorOn && !isCursorOn) {
- //Hide the cursor, when leaving cursor mode
- qt_symbian_set_cursor_visible(false);
- }
-#endif
- QApplicationPrivate::navigationMode = mode;
-}
-#endif
-
-#ifndef QT_NO_CURSOR
-/*****************************************************************************
- QApplication cursor stack
- *****************************************************************************/
-
-void QApplication::setOverrideCursor(const QCursor &cursor)
-{
- qApp->d_func()->cursor_list.prepend(cursor);
- qt_symbian_setGlobalCursor(cursor);
-}
-
-void QApplication::restoreOverrideCursor()
-{
- if (qApp->d_func()->cursor_list.isEmpty())
- return;
- qApp->d_func()->cursor_list.removeFirst();
-
- if (!qApp->d_func()->cursor_list.isEmpty()) {
- qt_symbian_setGlobalCursor(qApp->d_func()->cursor_list.first());
- }
- else {
- //determine which widget has focus
- QWidget *w = QApplication::widgetAt(QCursor::pos());
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors) {
- qt_symbian_set_pointer_sprite(w ? w->cursor() : Qt::ArrowCursor);
- }
- else
-#endif
- {
- //because of the internals of window server, we need to force the cursor
- //to be set in all child windows too, otherwise when the cursor is over
- //the child window it may show a widget cursor or arrow cursor instead,
- //depending on construction order.
- QListIterator<WId> iter(QWidgetPrivate::mapper->uniqueKeys());
- while (iter.hasNext()) {
- CCoeControl *ctrl = iter.next();
- if(ctrl->OwnsWindow()) {
- ctrl->DrawableWindow()->ClearPointerCursor();
- }
- }
- if (w)
- qt_symbian_setWindowCursor(w->cursor(), w->effectiveWinId());
- else
- qt_symbian_setWindowGroupCursor(Qt::ArrowCursor, S60->windowGroup());
- }
- }
-}
-
-#endif // QT_NO_CURSOR
-
-void QApplicationPrivate::_q_aboutToQuit()
-{
- qt_beginFullScreenEffect();
-
-#ifdef Q_SYMBIAN_TRANSITION_EFFECTS
- // Send the shutdown tfx command
- S60->wsSession().SendEffectCommand(ETfxCmdAppShutDown);
-#endif
-}
-
-QS60ThreadLocalData::QS60ThreadLocalData()
-{
- CCoeEnv *env = CCoeEnv::Static();
- if (env) {
- //if this is the UI thread, share objects owned by CONE
- usingCONEinstances = true;
- wsSession = env->WsSession();
- screenDevice = env->ScreenDevice();
- }
- else {
- usingCONEinstances = false;
- qt_symbian_throwIfError(wsSession.Connect(qt_s60GetRFs()));
- screenDevice = new CWsScreenDevice(wsSession);
- screenDevice->Construct();
- }
-}
-
-QS60ThreadLocalData::~QS60ThreadLocalData()
-{
- if (!usingCONEinstances) {
- delete screenDevice;
- wsSession.Close();
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qclipboard_s60.cpp b/src/gui/platforms/s60/qclipboard_s60.cpp
deleted file mode 100644
index 0dafae0996..0000000000
--- a/src/gui/platforms/s60/qclipboard_s60.cpp
+++ /dev/null
@@ -1,331 +0,0 @@
-/****************************************************************************
-**
-** 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 "qclipboard.h"
-
-#ifndef QT_NO_CLIPBOARD
-
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qdatetime.h"
-#include "qbuffer.h"
-#include "qwidget.h"
-#include "qevent.h"
-#include "private/qcore_symbian_p.h"
-#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
-#include "txtclipboard.h"
-#endif
-#include "txtetext.h"
-#include <QtDebug>
-
-// Symbian's clipboard
-#include <baclipb.h>
-QT_BEGIN_NAMESPACE
-
-const TUid KQtCbDataStream = {0x2001B2DD};
-const TInt KPlainTextBegin = 0;
-
-class QClipboardData
-{
-public:
- QClipboardData();
- ~QClipboardData();
-
- void setSource(QMimeData* s)
- {
- if (s == src)
- return;
- delete src;
- src = s;
- }
- QMimeData* source()
- { return src; }
- bool connected()
- { return connection; }
- void clear();
-
-private:
- QMimeData* src;
- bool connection;
-};
-
-QClipboardData::QClipboardData():src(0),connection(true)
-{
- clear();
-}
-
-QClipboardData::~QClipboardData()
-{
- connection = false;
- delete src;
-}
-
-void QClipboardData::clear()
-{
- QMimeData* newSrc = new QMimeData;
- delete src;
- src = newSrc;
-}
-
-static QClipboardData *internalCbData = 0;
-
-static void cleanupClipboardData()
-{
- delete internalCbData;
- internalCbData = 0;
-}
-
-static QClipboardData *clipboardData()
-{
- if (internalCbData == 0) {
- internalCbData = new QClipboardData;
- if (internalCbData)
- {
- if (!internalCbData->connected())
- {
- delete internalCbData;
- internalCbData = 0;
- }
- else
- {
- qAddPostRoutine(cleanupClipboardData);
- }
- }
- }
- return internalCbData;
-}
-
-void writeToStreamLX(const QMimeData* aData, RWriteStream& aStream)
-{
- // This function both leaves and throws exceptions. There must be no destructor
- // dependencies between cleanup styles, and no cleanup stack dependencies on stacked objects.
- QStringList headers = aData->formats();
- aStream << TCardinality(headers.count());
- for (QStringList::const_iterator iter= headers.constBegin();iter != headers.constEnd();iter++)
- {
- HBufC* stringData = TPtrC(reinterpret_cast<const TUint16*>((*iter).utf16())).AllocLC();
- QByteArray ba = aData->data((*iter));
- // mime type
- aStream << TCardinality(stringData->Size());
- aStream << *(stringData);
- // mime data
- aStream << TCardinality(ba.size());
- aStream.WriteL(reinterpret_cast<const uchar*>(ba.constData()),ba.size());
- CleanupStack::PopAndDestroy(stringData);
- }
-}
-
-void writeToSymbianStoreLX(const QMimeData* aData, CClipboard* clipboard)
-{
- // This function both leaves and throws exceptions. There must be no destructor
- // dependencies between cleanup styles, and no cleanup stack dependencies on stacked objects.
- if (aData->hasText()) {
- CPlainText* text = CPlainText::NewL();
- CleanupStack::PushL(text);
-
- TPtrC textPtr(qt_QString2TPtrC(aData->text()));
- text->InsertL(KPlainTextBegin, textPtr);
- text->CopyToStoreL(clipboard->Store(), clipboard->StreamDictionary(),
- KPlainTextBegin, textPtr.Length());
- CleanupStack::PopAndDestroy(text);
- }
-}
-
-void readSymbianStoreLX(QMimeData* aData, CClipboard* clipboard)
-{
- // This function both leaves and throws exceptions. There must be no destructor
- // dependencies between cleanup styles, and no cleanup stack dependencies on stacked objects.
- CPlainText* text = CPlainText::NewL();
- CleanupStack::PushL(text);
- TInt dataLength = text->PasteFromStoreL(clipboard->Store(), clipboard->StreamDictionary(),
- KPlainTextBegin);
- if (dataLength == 0) {
- User::Leave(KErrNotFound);
- }
- HBufC* hBuf = HBufC::NewL(dataLength);
- TPtr buf = hBuf->Des();
- text->Extract(buf, KPlainTextBegin, dataLength);
-
- QString string = qt_TDesC2QString(buf);
- CleanupStack::PopAndDestroy(text);
-
- aData->setText(string);
-}
-
-void readFromStreamLX(QMimeData* aData,RReadStream& aStream)
-{
- // This function both leaves and throws exceptions. There must be no destructor
- // dependencies between cleanup styles, and no cleanup stack dependencies on stacked objects.
- TCardinality mimeTypeCount;
- aStream >> mimeTypeCount;
- for (int i = 0; i< mimeTypeCount;i++)
- {
- // mime type
- TCardinality mimeTypeSize;
- aStream >> mimeTypeSize;
- HBufC* mimeTypeBuf = HBufC::NewLC(aStream,mimeTypeSize);
- QString mimeType = QString(reinterpret_cast<const QChar *>(mimeTypeBuf->Des().Ptr()),
- mimeTypeBuf->Length());
- CleanupStack::PopAndDestroy(mimeTypeBuf);
- // mime data
- TCardinality dataSize;
- aStream >> dataSize;
- QByteArray ba;
- ba.reserve(dataSize);
- aStream.ReadL(reinterpret_cast<uchar*>(ba.data_ptr()->data),dataSize);
- ba.data_ptr()->size = dataSize;
- aData->setData(mimeType,ba);
- }
-}
-
-
-/*****************************************************************************
- QClipboard member functions
- *****************************************************************************/
-
-void QClipboard::clear(Mode mode)
-{
- setText(QString(), mode);
-}
-const QMimeData* QClipboard::mimeData(Mode mode) const
-{
- if (mode != Clipboard) return 0;
- QClipboardData *d = clipboardData();
- bool dataExists(false);
- if (d)
- {
- TRAPD(err,{
- RFs fs = qt_s60GetRFs();
- CClipboard* cb = CClipboard::NewForReadingLC(fs);
- Q_ASSERT(cb);
- //stream for qt
- RStoreReadStream stream;
- TStreamId stid = (cb->StreamDictionary()).At(KQtCbDataStream);
- if (stid != 0) {
- stream.OpenLC(cb->Store(),stid);
- QT_TRYCATCH_LEAVING(readFromStreamLX(d->source(),stream));
- CleanupStack::PopAndDestroy(&stream);
- dataExists = true;
- }
- else {
- //symbian clipboard
- RStoreReadStream symbianStream;
- TStreamId symbianStId = (cb->StreamDictionary()).At(KClipboardUidTypePlainText);
- if (symbianStId != 0) {
- symbianStream.OpenLC(cb->Store(), symbianStId);
- QT_TRYCATCH_LEAVING(readSymbianStoreLX(d->source(), cb));
- CleanupStack::PopAndDestroy(&symbianStream);
- dataExists = true;
- }
- }
- CleanupStack::PopAndDestroy(cb);
- });
- if (err != KErrNone){
- qDebug()<< "clipboard is empty/err: " << err;
- }
-
- if (dataExists) {
- return d->source();
- }
- }
- return 0;
-}
-
-
-void QClipboard::setMimeData(QMimeData* src, Mode mode)
-{
- if (mode != Clipboard) return;
- QClipboardData *d = clipboardData();
- if (d)
- {
- TRAPD(err,{
- RFs fs = qt_s60GetRFs();
- CClipboard* cb = CClipboard::NewForWritingLC(fs);
- //stream for qt
- RStoreWriteStream stream;
- TStreamId stid = stream.CreateLC(cb->Store());
- QT_TRYCATCH_LEAVING(writeToStreamLX(src,stream));
- d->setSource(src);
- stream.CommitL();
- (cb->StreamDictionary()).AssignL(KQtCbDataStream,stid);
- cb->CommitL();
-
- //stream for symbian
- RStoreWriteStream symbianStream;
- TStreamId symbianStId = symbianStream.CreateLC(cb->Store());
- QT_TRYCATCH_LEAVING(writeToSymbianStoreLX(src, cb));
- (cb->StreamDictionary()).AssignL(KClipboardUidTypePlainText, symbianStId);
- cb->CommitL();
- CleanupStack::PopAndDestroy(3,cb);
- });
- if (err != KErrNone){
- qDebug()<< "clipboard write err :" << err;
- }
- }
- emitChanged(QClipboard::Clipboard);
-}
-
-bool QClipboard::supportsMode(Mode mode) const
-{
- return (mode == Clipboard);
-}
-
-bool QClipboard::ownsMode(Mode mode) const
-{
- if (mode == Clipboard)
- qWarning("QClipboard::ownsClipboard: UNIMPLEMENTED!");
- return false;
-}
-
-bool QClipboard::event(QEvent * /* e */)
-{
- return true;
-}
-
-void QClipboard::connectNotify( const char * )
-{
-}
-
-void QClipboard::ownerDestroyed()
-{
-}
-QT_END_NAMESPACE
-#endif // QT_NO_CLIPBOARD
diff --git a/src/gui/platforms/s60/qcolormap_s60.cpp b/src/gui/platforms/s60/qcolormap_s60.cpp
deleted file mode 100644
index 2c634db8a5..0000000000
--- a/src/gui/platforms/s60/qcolormap_s60.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolormap.h"
-#include "qcolor.h"
-
-QT_BEGIN_NAMESPACE
-
-class QColormapPrivate
-{
-public:
- inline QColormapPrivate()
- : ref(1)
- { }
-
- QAtomicInt ref;
-};
-
-void QColormap::initialize()
-{
-}
-
-void QColormap::cleanup()
-{
-}
-
-QColormap QColormap::instance(int)
-{
- return QColormap();
-}
-
-QColormap::QColormap() : d(new QColormapPrivate)
-{}
-
-QColormap::QColormap(const QColormap &colormap) :d (colormap.d)
-{ d->ref.ref(); }
-
-QColormap::~QColormap()
-{
- if (!d->ref.deref())
- delete d;
-}
-
-QColormap::Mode QColormap::mode() const
-{ return QColormap::Direct; }
-
-int QColormap::depth() const
-{
- return 32;
-}
-
-int QColormap::size() const
-{
- return -1;
-}
-
-uint QColormap::pixel(const QColor &color) const
-{ return color.rgba(); }
-
-const QColor QColormap::colorAt(uint pixel) const
-{ return QColor(pixel); }
-
-const QVector<QColor> QColormap::colormap() const
-{ return QVector<QColor>(); }
-
-QColormap &QColormap::operator=(const QColormap &colormap)
-{ qAtomicAssign(d, colormap.d); return *this; }
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qcursor_s60.cpp b/src/gui/platforms/s60/qcursor_s60.cpp
deleted file mode 100644
index 8dfe87ef81..0000000000
--- a/src/gui/platforms/s60/qcursor_s60.cpp
+++ /dev/null
@@ -1,533 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qcursor_p.h>
-#include <private/qwidget_p.h>
-#include <private/qapplication_p.h>
-#include <coecntrl.h>
-#include <qcursor.h>
-#include <private/qt_s60_p.h>
-#include <qbitmap.h>
-#include <w32std.h>
-#include <qapplication.h>
-#include <qwidget.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_CURSOR
-static QCursor cursorSprite;
-static int cursorSpriteVisible;
-#endif
-
-//pos and setpos are required whether cursors are configured or not.
-QPoint QCursor::pos()
-{
- return S60->lastCursorPos;
-}
-
-void QCursor::setPos(int x, int y)
-{
- //clip to screen size (window server allows a sprite hotspot to be outside the screen)
- if (x < 0)
- x=0;
- else if (x >= S60->screenWidthInPixels)
- x = S60->screenWidthInPixels - 1;
- if (y < 0)
- y = 0;
- else if (y >= S60->screenHeightInPixels)
- y = S60->screenHeightInPixels - 1;
-
-#ifndef QT_NO_CURSOR
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors && cursorSpriteVisible)
- cursorSprite.d->scurs.SetPosition(TPoint(x,y));
- else
-#endif
- S60->wsSession().SetPointerCursorPosition(TPoint(x, y));
-#endif
- S60->lastCursorPos = QPoint(x, y);
- //send a fake mouse move event, so that enter/leave events go to the widget hierarchy
- QWidget *w = QApplication::topLevelAt(S60->lastCursorPos);
- if (w) {
- CCoeControl* ctrl = w->effectiveWinId();
- TPoint epos(x, y);
- TPoint cpos = epos - ctrl->PositionRelativeToScreen();
- TPointerEvent fakeEvent;
- fakeEvent.iType = TPointerEvent::EMove;
- fakeEvent.iModifiers = 0U;
- fakeEvent.iPosition = cpos;
- fakeEvent.iParentPosition = epos;
- ctrl->HandlePointerEventL(fakeEvent);
- }
-}
-
-#ifndef QT_NO_CURSOR
-/*
- * Request cursor to be turned on or off.
- * Reference counted, so 2 on + 1 off = on, for example
- */
-void qt_symbian_set_cursor_visible(bool visible) {
- if (visible)
- cursorSpriteVisible++;
- else
- cursorSpriteVisible--;
- Q_ASSERT(cursorSpriteVisible >=0);
-
- if (cursorSpriteVisible && !S60->mouseInteractionEnabled) {
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors)
- qt_symbian_show_pointer_sprite();
- else
-#endif
- S60->wsSession().SetPointerCursorMode(EPointerCursorNormal);
- } else if (!cursorSpriteVisible && S60->mouseInteractionEnabled) {
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors)
- qt_symbian_hide_pointer_sprite();
- else
-#endif
- S60->wsSession().SetPointerCursorMode(EPointerCursorNone);
- }
- S60->mouseInteractionEnabled = ((cursorSpriteVisible > 0) ? true : false);
-}
-
-/*
- * Check if the cursor is on or off
- */
-bool qt_symbian_is_cursor_visible() {
- return S60->mouseInteractionEnabled;
-}
-
-QCursorData::QCursorData(Qt::CursorShape s) :
- cshape(s), bm(0), bmm(0), hx(0), hy(0), pcurs()
-{
- ref = 1;
-}
-
-QCursorData::~QCursorData()
-{
- for(int i=0;i<nativeSpriteMembers.Count();i++) {
- delete nativeSpriteMembers[i]->iBitmap;
- delete nativeSpriteMembers[i]->iMaskBitmap;
- }
- nativeSpriteMembers.ResetAndDestroy();
- pcurs.Close();
- delete bm;
- delete bmm;
-}
-
-/* Create a bitmap cursor, this is called by public constructors in the
- * generic QCursor code.
- */
-QCursorData *QCursorData::setBitmap(const QBitmap &bitmap, const QBitmap &mask, int hotX, int hotY)
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (bitmap.depth() != 1 || mask.depth() != 1 || bitmap.size() != mask.size()) {
- qWarning("QCursor: Cannot create bitmap cursor; invalid bitmap(s)");
- QCursorData *c = qt_cursorTable[0];
- c->ref.ref();
- return c;
- }
- QCursorData *d = new QCursorData;
- d->bm = new QBitmap(bitmap);
- d->bmm = new QBitmap(mask);
- d->cshape = Qt::BitmapCursor;
- d->hx = hotX >= 0 ? hotX : bitmap.width() / 2;
- d->hy = hotY >= 0 ? hotY : bitmap.height() / 2;
- return d;
-}
-
-/*
- * returns an opaque native handle to a cursor.
- * It happens to be the address of the native handle, as window server handles
- * are not POD types. Note there is no QCursor(HANDLE) constructor on Symbian,
- * Mac or QWS.
- */
-Qt::HANDLE QCursor::handle() const
-{
- if (d->pcurs.WsHandle())
- return reinterpret_cast<Qt::HANDLE> (&(d->pcurs));
-
-#ifdef Q_SYMBIAN_HAS_SYSTEM_CURSORS
- // don't construct shape cursors, QApplication_s60 will use the system cursor instead
- if (!(d->bm))
- return 0;
-#endif
-
- d->pcurs = RWsPointerCursor(S60->wsSession());
- d->pcurs.Construct(0);
- d->constructCursorSprite(d->pcurs);
- d->pcurs.Activate();
-
- return reinterpret_cast<Qt::HANDLE> (&(d->pcurs));
-}
-
-#ifndef Q_SYMBIAN_HAS_SYSTEM_CURSORS
-/*
- * Loads a single cursor shape from resources and appends it to a native sprite.
- * Animated cursors (e.g. the busy cursor) have multiple members.
- */
-void QCursorData::loadShapeFromResource(RWsSpriteBase& target, QString resource, int hx, int hy, int interval)
-{
- QPixmap pix;
- CFbsBitmap* native;
- QScopedPointer<TSpriteMember> member(new TSpriteMember);
- member->iInterval = interval;
- member->iInvertMask = false;
- member->iMaskBitmap = 0; // all shapes are RGBA
- member->iDrawMode = CGraphicsContext::EDrawModePEN;
- member->iOffset = TPoint(-hx, -hy);
- QString res(QLatin1String(":/trolltech/symbian/cursors/images/%1.png"));
- pix.load(res.arg(resource));
- native = pix.toSymbianCFbsBitmap();
- member->iBitmap = native;
- qt_symbian_throwIfError(nativeSpriteMembers.Append(member.data()));
- target.AppendMember(*(member.take()));
-}
-
-//TODO: after 4.6, connect with style & skins?
-/*
- * Constructs the native cursor from resources compiled into QtGui
- * This is needed only when the platform doesn't have system cursors.
- *
- * System cursors are higher performance, since they are constructed once
- * and shared by all applications by specifying the shape number.
- * Due to symbian platform security considerations, and the fact most
- * existing phones have a broken RWsPointerCursor, system cursors are not
- * being used.
- */
-void QCursorData::constructShapeSprite(RWsSpriteBase& target)
-{
- int i;
- switch (cshape) {
- default:
- qWarning("QCursorData::constructShapeSprite unknown shape %d", cshape);
- //fall through and give arrow cursor
- case Qt::ArrowCursor:
- loadShapeFromResource(target, QLatin1String("pointer"), 1, 1);
- break;
- case Qt::UpArrowCursor:
- loadShapeFromResource(target, QLatin1String("uparrow"), 4, 0);
- break;
- case Qt::CrossCursor:
- loadShapeFromResource(target, QLatin1String("cross"), 7, 7);
- break;
- case Qt::WaitCursor:
- for (i = 1; i <= 12; i++) {
- loadShapeFromResource(target, QString(QLatin1String("wait%1")).arg(i), 7, 7, 1000000);
- }
- break;
- case Qt::IBeamCursor:
- loadShapeFromResource(target, QLatin1String("ibeam"), 3, 10);
- break;
- case Qt::SizeVerCursor:
- loadShapeFromResource(target, QLatin1String("sizever"), 4, 8);
- break;
- case Qt::SizeHorCursor:
- loadShapeFromResource(target, QLatin1String("sizehor"), 8, 4);
- break;
- case Qt::SizeBDiagCursor:
- loadShapeFromResource(target, QLatin1String("sizebdiag"), 8, 8);
- break;
- case Qt::SizeFDiagCursor:
- loadShapeFromResource(target, QLatin1String("sizefdiag"), 8, 8);
- break;
- case Qt::SizeAllCursor:
- loadShapeFromResource(target, QLatin1String("sizeall"), 7, 7);
- break;
- case Qt::BlankCursor:
- loadShapeFromResource(target, QLatin1String("blank"), 0, 0);
- break;
- case Qt::SplitVCursor:
- loadShapeFromResource(target, QLatin1String("splitv"), 7, 7);
- break;
- case Qt::SplitHCursor:
- loadShapeFromResource(target, QLatin1String("splith"), 7, 7);
- break;
- case Qt::PointingHandCursor:
- loadShapeFromResource(target, QLatin1String("handpoint"), 5, 0);
- break;
- case Qt::ForbiddenCursor:
- loadShapeFromResource(target, QLatin1String("forbidden"), 7, 7);
- break;
- case Qt::WhatsThisCursor:
- loadShapeFromResource(target, QLatin1String("whatsthis"), 1, 1);
- break;
- case Qt::BusyCursor:
- loadShapeFromResource(target, QLatin1String("busy3"), 1, 1, 1000000);
- loadShapeFromResource(target, QLatin1String("busy6"), 1, 1, 1000000);
- loadShapeFromResource(target, QLatin1String("busy9"), 1, 1, 1000000);
- loadShapeFromResource(target, QLatin1String("busy12"), 1, 1, 1000000);
- break;
- case Qt::OpenHandCursor:
- loadShapeFromResource(target, QLatin1String("openhand"), 7, 7);
- break;
- case Qt::ClosedHandCursor:
- loadShapeFromResource(target, QLatin1String("closehand"), 7, 7);
- break;
- }
-}
-#endif
-
-/*
- * Common code between the sprite workaround and standard modes of operation.
- * RWsSpriteBase is the base class for both RWsSprite and RWsPointerCursor.
- * It is called from both handle() and qt_s60_show_pointer_sprite()
- */
-void QCursorData::constructCursorSprite(RWsSpriteBase& target)
-{
- int count = nativeSpriteMembers.Count();
- if (count) {
- // already constructed
- for (int i = 0; i < count; i++)
- target.AppendMember(*(nativeSpriteMembers[i]));
-
- return;
- }
- if (pixmap.isNull() && !bm) {
-#ifndef Q_SYMBIAN_HAS_SYSTEM_CURSORS
- //shape cursor
- constructShapeSprite(target);
-#endif
- return;
- }
- QScopedPointer<TSpriteMember> member(new TSpriteMember);
- if (pixmap.isNull()) {
- //construct mono cursor
- member->iBitmap = bm->toSymbianCFbsBitmap();
- member->iMaskBitmap = bmm->toSymbianCFbsBitmap();
- }
- else {
- //construct normal cursor
- member->iBitmap = pixmap.toSymbianCFbsBitmap();
- if (pixmap.hasAlphaChannel()) {
- member->iMaskBitmap = 0; //use alpha blending
- }
- else if (pixmap.hasAlpha()) {
- member->iMaskBitmap = pixmap.mask().toSymbianCFbsBitmap();
- }
- else {
- member->iMaskBitmap = 0; //opaque rectangle cursor (due to EDrawModePEN)
- }
- }
-
- member->iDrawMode = CGraphicsContext::EDrawModePEN;
- member->iInvertMask = EFalse;
- member->iInterval = 0;
- member->iOffset = TPoint(-(hx), -(hy)); //Symbian hotspot coordinates are negative
- qt_symbian_throwIfError(nativeSpriteMembers.Append(member.data()));
- target.AppendMember(*(member.take()));
-}
-
-/*
- * shows the pointer sprite by constructing a native handle, and registering
- * it with the window server.
- * Only used when the sprite workaround is in use.
- */
-void qt_symbian_show_pointer_sprite()
-{
- if (cursorSprite.d) {
- if (cursorSprite.d->scurs.WsHandle())
- cursorSprite.d->scurs.Close();
- } else {
- cursorSprite = QCursor(Qt::ArrowCursor);
- }
-
- cursorSprite.d->scurs = RWsSprite(S60->wsSession());
- QPoint pos = QCursor::pos();
- cursorSprite.d->scurs.Construct(S60->windowGroup(), TPoint(pos.x(), pos.y()), ESpriteNoChildClip | ESpriteNoShadows);
-
- cursorSprite.d->constructCursorSprite(cursorSprite.d->scurs);
- cursorSprite.d->scurs.Activate();
-}
-
-/*
- * hides the pointer sprite by closing the native handle.
- * Only used when the sprite workaround is in use.
- */
-void qt_symbian_hide_pointer_sprite()
-{
- if (cursorSprite.d) {
- cursorSprite.d->scurs.Close();
- }
-}
-
-/*
- * Changes the cursor sprite to the cursor specified.
- * Only used when the sprite workaround is in use.
- */
-void qt_symbian_set_pointer_sprite(const QCursor& cursor)
-{
- if (S60->mouseInteractionEnabled)
- qt_symbian_hide_pointer_sprite();
- cursorSprite = cursor;
- if (S60->mouseInteractionEnabled)
- qt_symbian_show_pointer_sprite();
-}
-
-/*
- * When using sprites as a workaround on phones that have a broken
- * RWsPointerCursor, this function is called in response to pointer events
- * and when QCursor::setPos() is called.
- * Performance is worse than a real pointer cursor, due to extra context
- * switches vs. the window server moving the cursor by itself.
- */
-void qt_symbian_move_cursor_sprite()
-{
- if (S60->mouseInteractionEnabled) {
- cursorSprite.d->scurs.SetPosition(TPoint(S60->lastCursorPos.x(), S60->lastCursorPos.y()));
- }
-}
-
-/*
- * Translate from Qt::CursorShape to OS system pointer cursor list index.
- * Currently we control the implementation of the system pointer cursor list,
- * so this function is trivial. That may not always be the case.
- */
-TInt qt_symbian_translate_cursor_shape(Qt::CursorShape shape)
-{
- return (TInt) shape;
-}
-
-/*
- Internal function called from QWidget::setCursor()
- force is true if this function is called from dispatchEnterLeave, it means that the
- mouse is actually directly under this widget.
-*/
-void qt_symbian_set_cursor(QWidget *w, bool force)
-{
- static QPointer<QWidget> lastUnderMouse = 0;
- if (force) {
- lastUnderMouse = w;
- }
- else if (w->testAttribute(Qt::WA_WState_Created) && lastUnderMouse
- && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
- w = lastUnderMouse;
- }
-
- if (!S60->curWin && w && w->internalWinId())
- return;
- QWidget* cW = w && !w->internalWinId() ? w : QWidget::find(S60->curWin);
- if (!cW || cW->window() != w->window() || !cW->isVisible() || !cW->underMouse()
- || QApplication::overrideCursor())
- return;
-
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors)
- qt_symbian_set_pointer_sprite(cW->cursor());
- else
-#endif
- qt_symbian_setWindowCursor(cW->cursor(), w->effectiveWinId());
-}
-
-/*
- * Makes the specified cursor appear above a specific native window group
- * Called from QSymbianControl and QApplication::restoreOverrideCursor
- *
- * Window server is needed for this, so there is no equivalent when using
- * the sprite workaround.
- */
-void qt_symbian_setWindowGroupCursor(const QCursor &cursor, RWindowTreeNode &node)
-{
- Qt::HANDLE handle = cursor.handle();
- if (handle) {
- RWsPointerCursor *pcurs = reinterpret_cast<RWsPointerCursor *> (handle);
- node.SetCustomPointerCursor(*pcurs);
- } else
-#ifdef Q_SYMBIAN_HAS_SYSTEM_CURSORS
- {
- TInt shape = qt_symbian_translate_cursor_shape(cursor.shape());
- node.SetPointerCursor(shape);
- }
-#else
- qWarning("qt_s60_setWindowGroupCursor - null handle");
-#endif
-}
-
-/*
- * Makes the specified cursor appear above a specific native window
- * Called from QSymbianControl and QApplication::restoreOverrideCursor
- *
- * Window server is needed for this, so there is no equivalent when using
- * the sprite workaround.
- */
-void qt_symbian_setWindowCursor(const QCursor &cursor, const CCoeControl* wid)
-{
- //find the window for this control
- while (!wid->OwnsWindow()) {
- wid = wid->Parent();
- if (!wid)
- return;
- }
- RWindowTreeNode *node = wid->DrawableWindow();
- qt_symbian_setWindowGroupCursor(cursor, *node);
-}
-
-/*
- * Makes the specified cursor appear everywhere.
- * Called from QApplication::setOverrideCursor
- */
-void qt_symbian_setGlobalCursor(const QCursor &cursor)
-{
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- if (S60->brokenPointerCursors) {
- qt_symbian_set_pointer_sprite(cursor);
- } else
-#endif
- {
- //because of the internals of window server, we need to force the cursor
- //to be set in all child windows too, otherwise when the cursor is over
- //the child window it may show a widget cursor or arrow cursor instead,
- //depending on construction order.
- QListIterator<WId> iter(QWidgetPrivate::mapper->uniqueKeys());
- while(iter.hasNext())
- {
- CCoeControl *ctrl = iter.next();
- if(ctrl->OwnsWindow()) {
- RWindowTreeNode *node = ctrl->DrawableWindow();
- qt_symbian_setWindowGroupCursor(cursor, *node);
- }
- }
- }
-}
-QT_END_NAMESPACE
-#endif // QT_NO_CURSOR
diff --git a/src/gui/platforms/s60/qdesktopwidget_s60.cpp b/src/gui/platforms/s60/qdesktopwidget_s60.cpp
deleted file mode 100644
index 62a4d40eba..0000000000
--- a/src/gui/platforms/s60/qdesktopwidget_s60.cpp
+++ /dev/null
@@ -1,316 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdesktopwidget.h"
-#include "qapplication_p.h"
-#include "qwidget_p.h"
-#include "qt_s60_p.h"
-#include <w32std.h>
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
-#include <graphics/displaycontrol.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern int qt_symbian_create_desktop_on_screen;
-
-class QSingleDesktopWidget : public QWidget
-{
-public:
- QSingleDesktopWidget();
- ~QSingleDesktopWidget();
-};
-
-QSingleDesktopWidget::QSingleDesktopWidget()
- : QWidget(0, Qt::Desktop)
-{
-}
-
-QSingleDesktopWidget::~QSingleDesktopWidget()
-{
- const QObjectList &childList = children();
- for (int i = childList.size(); i > 0 ;) {
- --i;
- childList.at(i)->setParent(0);
- }
-}
-
-class QDesktopWidgetPrivate : public QWidgetPrivate
-{
-public:
- QDesktopWidgetPrivate();
- ~QDesktopWidgetPrivate();
- static void init(QDesktopWidget *that);
- static void cleanup();
- static void init_sys();
-
- static int screenCount;
- static int primaryScreen;
-
- static QVector<QRect> *rects;
- static QVector<QRect> *workrects;
- static QVector<QWidget *> *screens;
-
- static int refcount;
-
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- static MDisplayControl *displayControl;
-#endif
-};
-
-int QDesktopWidgetPrivate::screenCount = 1;
-int QDesktopWidgetPrivate::primaryScreen = 0;
-QVector<QRect> *QDesktopWidgetPrivate::rects = 0;
-QVector<QRect> *QDesktopWidgetPrivate::workrects = 0;
-QVector<QWidget *> *QDesktopWidgetPrivate::screens = 0;
-int QDesktopWidgetPrivate::refcount = 0;
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
-MDisplayControl *QDesktopWidgetPrivate::displayControl = 0;
-#endif
-
-QDesktopWidgetPrivate::QDesktopWidgetPrivate()
-{
- ++refcount;
-}
-
-QDesktopWidgetPrivate::~QDesktopWidgetPrivate()
-{
- if (!--refcount)
- cleanup();
-}
-
-void QDesktopWidgetPrivate::init(QDesktopWidget *that)
-{
- // Note that on S^3 devices the screen count retrieved via RWsSession
- // will always be 2 but the width and height for screen number 1 will
- // be 0 as long as TV-out is not connected.
- //
- // On the other hand a valid size for screen 1 will be reported even
- // after the cable is disconnected. In order to overcome this, we use
- // MDisplayControl::NumberOfResolutions() to check if the display is
- // valid or not.
-
- screenCount = S60->screenCount();
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- if (displayControl) {
- if (displayControl->NumberOfResolutions() < 1)
- screenCount = 1;
- }
-#endif
- if (screenCount < 1) {
- qWarning("No screen available");
- screenCount = 1;
- }
-
- rects = new QVector<QRect>();
- workrects = new QVector<QRect>();
- screens = new QVector<QWidget *>();
-
- rects->resize(screenCount);
- workrects->resize(screenCount);
- screens->resize(screenCount);
-
- for (int i = 0; i < screenCount; ++i) {
- // All screens will have a position of (0, 0) as there is no true virtual desktop
- // or pointer event support for multiple screens on Symbian.
- QRect r(0, 0,
- S60->screenWidthInPixelsForScreen[i], S60->screenHeightInPixelsForScreen[i]);
- // Stop here if empty and ignore this screen.
- if (r.isEmpty()) {
- screenCount = i;
- break;
- }
- (*rects)[i] = r;
- QRect wr;
- if (i == 0)
- wr = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect());
- else
- wr = rects->at(i);
- (*workrects)[i].setRect(wr.x(), wr.y(), wr.width(), wr.height());
- (*screens)[i] = 0;
- }
- (*screens)[0] = that;
-}
-
-void QDesktopWidgetPrivate::cleanup()
-{
- delete rects;
- rects = 0;
- delete workrects;
- workrects = 0;
- if (screens) {
- // First item is the QDesktopWidget so skip it.
- for (int i = 1; i < screens->count(); ++i)
- delete screens->at(i);
- }
- delete screens;
- screens = 0;
-}
-
-void QDesktopWidgetPrivate::init_sys()
-{
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- if (S60->screenCount() > 1) {
- CWsScreenDevice *dev = S60->screenDevice(1);
- if (dev) {
- displayControl = static_cast<MDisplayControl *>(
- dev->GetInterface(MDisplayControl::ETypeId));
- if (displayControl) {
- displayControl->EnableDisplayChangeEvents(ETrue);
- }
- }
- }
-#endif
-}
-
-
-QDesktopWidget::QDesktopWidget()
- : QWidget(*new QDesktopWidgetPrivate, 0, Qt::Desktop)
-{
- setObjectName(QLatin1String("desktop"));
- QDesktopWidgetPrivate::init_sys();
- QDesktopWidgetPrivate::init(this);
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
- return false;
-}
-
-int QDesktopWidget::primaryScreen() const
-{
- return QDesktopWidgetPrivate::primaryScreen;
-}
-
-int QDesktopWidget::numScreens() const
-{
- Q_D(const QDesktopWidget);
- return QDesktopWidgetPrivate::screenCount;
-}
-
-static inline QWidget *newSingleDesktopWidget(int screen)
-{
- qt_symbian_create_desktop_on_screen = screen;
- QWidget *w = new QSingleDesktopWidget;
- qt_symbian_create_desktop_on_screen = -1;
- return w;
-}
-
-QWidget *QDesktopWidget::screen(int screen)
-{
- Q_D(QDesktopWidget);
- if (screen < 0 || screen >= d->screenCount)
- screen = d->primaryScreen;
- if (!d->screens->at(screen)
- || d->screens->at(screen)->windowType() != Qt::Desktop)
- (*d->screens)[screen] = newSingleDesktopWidget(screen);
- return (*d->screens)[screen];
-}
-
-const QRect QDesktopWidget::availableGeometry(int screen) const
-{
- Q_D(const QDesktopWidget);
- if (screen < 0 || screen >= d->screenCount)
- screen = d->primaryScreen;
-
- return d->workrects->at(screen);
-}
-
-const QRect QDesktopWidget::screenGeometry(int screen) const
-{
- Q_D(const QDesktopWidget);
- if (screen < 0 || screen >= d->screenCount)
- screen = d->primaryScreen;
-
- return d->rects->at(screen);
-}
-
-int QDesktopWidget::screenNumber(const QWidget *widget) const
-{
- Q_D(const QDesktopWidget);
- return widget
- ? S60->screenNumberForWidget(widget)
- : d->primaryScreen;
-}
-
-int QDesktopWidget::screenNumber(const QPoint &point) const
-{
- Q_UNUSED(point);
- Q_D(const QDesktopWidget);
- return d->primaryScreen;
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
- Q_D(QDesktopWidget);
- QVector<QRect> oldrects;
- oldrects = *d->rects;
- QVector<QRect> oldworkrects;
- oldworkrects = *d->workrects;
- int oldscreencount = d->screenCount;
-
- QDesktopWidgetPrivate::cleanup();
- QDesktopWidgetPrivate::init(this);
-
- for (int i = 0; i < qMin(oldscreencount, d->screenCount); ++i) {
- QRect oldrect = oldrects[i];
- QRect newrect = d->rects->at(i);
- if (oldrect != newrect)
- emit resized(i);
- }
-
- for (int j = 0; j < qMin(oldscreencount, d->screenCount); ++j) {
- QRect oldrect = oldworkrects[j];
- QRect newrect = d->workrects->at(j);
- if (oldrect != newrect)
- emit workAreaResized(j);
- }
-
- if (oldscreencount != d->screenCount) {
- emit screenCountChanged(d->screenCount);
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qdnd_s60.cpp b/src/gui/platforms/s60/qdnd_s60.cpp
deleted file mode 100644
index a9847a98f8..0000000000
--- a/src/gui/platforms/s60/qdnd_s60.cpp
+++ /dev/null
@@ -1,359 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-
-#ifndef QT_NO_DRAGANDDROP
-
-#include "qwidget.h"
-#include "qdatetime.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qdnd_p.h"
-#include "qt_s60_p.h"
-
-#include <coecntrl.h>
-// pointer cursor
-#include <w32std.h>
-#include <gdi.h>
-#include <QCursor>
-
-QT_BEGIN_NAMESPACE
-//### artistic impression of Symbians default DnD cursor ?
-
-static QPixmap *defaultPm = 0;
-static const int default_pm_hotx = -50;
-static const int default_pm_hoty = -50;
-static const char *const default_pm[] = {
-"13 9 3 1",
-". c None",
-" c #000000",
-"X c #FFFFFF",
-"X X X X X X X",
-" X X X X X X ",
-"X ......... X",
-" X.........X ",
-"X ......... X",
-" X.........X ",
-"X ......... X",
-" X X X X X X ",
-"X X X X X X X",
-};
-//### actions need to be redefined for S60
-// Shift/Ctrl handling, and final drop status
-static Qt::DropAction global_accepted_action = Qt::MoveAction;
-static Qt::DropActions possible_actions = Qt::IgnoreAction;
-
-
-// static variables in place of a proper cross-process solution
-static QDrag *drag_object;
-static bool qt_symbian_dnd_dragging = false;
-
-
-static Qt::KeyboardModifiers oldstate;
-
-void QDragManager::updatePixmap()
-{
- QPixmap pm;
- QPoint pm_hot(default_pm_hotx,default_pm_hoty);
- if (drag_object) {
- pm = drag_object->pixmap();
- if (!pm.isNull())
- pm_hot = drag_object->hotSpot();
- }
- if (pm.isNull()) {
- if (!defaultPm)
- defaultPm = new QPixmap(default_pm);
- pm = *defaultPm;
- }
-#ifndef QT_NO_CURSOR
- QCursor cursor(pm, pm_hot.x(), pm_hot.y());
- overrideCursor = cursor;
-#endif
-}
-
-void QDragManager::timerEvent(QTimerEvent *) { }
-
-void QDragManager::move(const QPoint&) {
-}
-
-void QDragManager::updateCursor()
-{
-#ifndef QT_NO_CURSOR
- QCursor cursor = willDrop ? overrideCursor : Qt::ForbiddenCursor;
- if (!restoreCursor) {
- QApplication::setOverrideCursor(cursor);
- restoreCursor = true;
- }
- else {
- QApplication::changeOverrideCursor(cursor);
- }
-#endif
-}
-
-
-bool QDragManager::eventFilter(QObject *o, QEvent *e)
-{
- if (beingCancelled) {
- return false;
- }
- if (!o->isWidgetType())
- return false;
-
- switch(e->type()) {
- case QEvent::MouseButtonPress:
- {
- }
- case QEvent::MouseMove:
- {
- if (!object) { //#### this should not happen
- qWarning("QDragManager::eventFilter: No object");
- return true;
- }
- QDragManager *manager = QDragManager::self();
- QMimeData *dropData = manager->object ? manager->dragPrivate()->data : manager->dropData;
- if (manager->object)
- possible_actions = manager->dragPrivate()->possible_actions;
- else
- possible_actions = Qt::IgnoreAction;
-
- QMouseEvent *me = (QMouseEvent *)e;
-
- if (me->buttons()) {
- Qt::DropAction prevAction = global_accepted_action;
- QWidget *cw = QApplication::widgetAt(me->globalPos());
- // map the Coords relative to the window.
- if (!cw)
- return true;
-
- while (cw && !cw->acceptDrops() && !cw->isWindow())
- cw = cw->parentWidget();
-
- bool oldWillDrop = willDrop;
- if (object->target() != cw) {
- if (object->target()) {
- QDragLeaveEvent dle;
- QApplication::sendEvent(object->target(), &dle);
- willDrop = false;
- global_accepted_action = Qt::IgnoreAction;
- if (oldWillDrop != willDrop)
- updateCursor();
- object->d_func()->target = 0;
- }
- if (cw && cw->acceptDrops()) {
- object->d_func()->target = cw;
- QDragEnterEvent dee(cw->mapFromGlobal(me->globalPos()), possible_actions, dropData,
- me->buttons(), me->modifiers());
- QApplication::sendEvent(object->target(), &dee);
- willDrop = dee.isAccepted() && dee.dropAction() != Qt::IgnoreAction;
- global_accepted_action = willDrop ? dee.dropAction() : Qt::IgnoreAction;
- if (oldWillDrop != willDrop)
- updateCursor();
- }
- } else if (cw) {
- QDragMoveEvent dme(cw->mapFromGlobal(me->globalPos()), possible_actions, dropData,
- me->buttons(), me->modifiers());
- if (global_accepted_action != Qt::IgnoreAction) {
- dme.setDropAction(global_accepted_action);
- dme.accept();
- }
- QApplication::sendEvent(cw, &dme);
- willDrop = dme.isAccepted();
- global_accepted_action = willDrop ? dme.dropAction() : Qt::IgnoreAction;
- if (oldWillDrop != willDrop) {
- updatePixmap();
- updateCursor();
- }
- }
- if (global_accepted_action != prevAction)
- emitActionChanged(global_accepted_action);
- }
- return true; // Eat all mouse events
- }
-
- case QEvent::MouseButtonRelease:
- {
- qApp->removeEventFilter(this);
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- QApplication::restoreOverrideCursor();
- willDrop = false;
- restoreCursor = false;
- }
-#endif
- if (object && object->target()) {
-
- QMouseEvent *me = (QMouseEvent *)e;
-
- QDragManager *manager = QDragManager::self();
- QMimeData *dropData = manager->object ? manager->dragPrivate()->data : manager->dropData;
-
- QDropEvent de(object->target()->mapFromGlobal(me->globalPos()), possible_actions, dropData,
- me->buttons(), me->modifiers());
- QApplication::sendEvent(object->target(), &de);
- if (de.isAccepted())
- global_accepted_action = de.dropAction();
- else
- global_accepted_action = Qt::IgnoreAction;
-
- if (object)
- object->deleteLater();
- drag_object = object = 0;
- }
- eventLoop->exit();
- return true; // Eat all mouse events
- }
-
- default:
- break;
- }
- return false;
-}
-
-Qt::DropAction QDragManager::drag(QDrag *o)
-{
- Q_ASSERT(!qt_symbian_dnd_dragging);
- if (object == o || !o || !o->source())
- return Qt::IgnoreAction;
-
- if (object) {
- cancel();
- qApp->removeEventFilter(this);
- beingCancelled = false;
- }
-
- object = drag_object = o;
-
- oldstate = Qt::NoModifier; // #### Should use state that caused the drag
- willDrop = false;
- updatePixmap();
- updateCursor();
-
-#ifndef QT_NO_CURSOR
- qt_symbian_set_cursor_visible(true); //force cursor on even for touch phone
-#endif
-
- object->d_func()->target = 0;
-
- qApp->installEventFilter(this);
-
- global_accepted_action = defaultAction(dragPrivate()->possible_actions, Qt::NoModifier);
- qt_symbian_dnd_dragging = true;
-
- eventLoop = new QEventLoop;
- // block
- (void) eventLoop->exec(QEventLoop::AllEvents);
- delete eventLoop;
- eventLoop = 0;
-
-#ifndef QT_NO_CURSOR
- qt_symbian_set_cursor_visible(false);
-
- overrideCursor = QCursor(); //deref the cursor data
- qt_symbian_dnd_dragging = false;
-#endif
-
- return global_accepted_action;
-}
-
-
-void QDragManager::cancel(bool deleteSource)
-{
- beingCancelled = true;
-
- if (object->target()) {
- QDragLeaveEvent dle;
- QApplication::sendEvent(object->target(), &dle);
- }
-
- if (drag_object) {
- if (deleteSource)
- object->deleteLater();
- drag_object = object = 0;
- }
-
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- QApplication::restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-
- global_accepted_action = Qt::IgnoreAction;
-}
-
-
-void QDragManager::drop()
-{
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- QApplication::restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mimetype, QVariant::Type type) const
-{
- if (!drag_object)
- return QVariant();
- QByteArray data = drag_object->mimeData()->data(mimetype);
- if (type == QVariant::String)
- return QString::fromUtf8(data);
- return data;
-}
-
-bool QDropData::hasFormat_sys(const QString &format) const
-{
- return formats().contains(format);
-}
-
-QStringList QDropData::formats_sys() const
-{
- if (drag_object)
- return drag_object->mimeData()->formats();
- return QStringList();
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_DRAGANDDROP
diff --git a/src/gui/platforms/s60/qeventdispatcher_s60.cpp b/src/gui/platforms/s60/qeventdispatcher_s60.cpp
deleted file mode 100644
index 2d92c89c07..0000000000
--- a/src/gui/platforms/s60/qeventdispatcher_s60.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/****************************************************************************
-**
-** 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 <qwidget.h>
-
-#include "qeventdispatcher_s60_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QtEikonEnv::QtEikonEnv()
- : m_lastIterationCount(0)
- , m_savedStatusCode(KRequestPending)
- , m_hasAlreadyRun(false)
-{
-}
-
-QtEikonEnv::~QtEikonEnv()
-{
-}
-
-void QtEikonEnv::RunL()
-{
- QEventDispatcherS60 *dispatcher = qobject_cast<QEventDispatcherS60 *>(QAbstractEventDispatcher::instance());
- if (!dispatcher) {
- CEikonEnv::RunL();
- return;
- }
-
- if (m_lastIterationCount != dispatcher->iterationCount()) {
- m_hasAlreadyRun = false;
- m_lastIterationCount = dispatcher->iterationCount();
- }
-
- if (m_hasAlreadyRun) {
- // Fool the active scheduler into believing we are still waiting for events.
- // The window server thinks we are not, however.
- m_savedStatusCode = iStatus.Int();
- iStatus = KRequestPending;
- SetActive();
- dispatcher->queueDeferredActiveObjectsCompletion();
- } else {
- m_hasAlreadyRun = true;
- CEikonEnv::RunL();
- }
-}
-
-void QtEikonEnv::DoCancel()
-{
- complete();
-
- CEikonEnv::DoCancel();
-}
-
-void QtEikonEnv::complete()
-{
- if (m_hasAlreadyRun) {
- if (m_savedStatusCode != KRequestPending) {
- TRequestStatus *status = &iStatus;
- QEventDispatcherSymbian::RequestComplete(status, m_savedStatusCode);
- m_savedStatusCode = KRequestPending;
- }
- m_hasAlreadyRun = false;
- }
-}
-
-QEventDispatcherS60::QEventDispatcherS60(QObject *parent)
- : QEventDispatcherSymbian(parent),
- m_noInputEvents(false)
-{
-}
-
-QEventDispatcherS60::~QEventDispatcherS60()
-{
- for (int c = 0; c < m_deferredInputEvents.size(); ++c) {
- delete m_deferredInputEvents[c].event;
- }
-}
-
-bool QEventDispatcherS60::processEvents ( QEventLoop::ProcessEventsFlags flags )
-{
- bool ret = false;
-
- QT_TRY {
- bool oldNoInputEventsValue = m_noInputEvents;
- if (flags & QEventLoop::ExcludeUserInputEvents) {
- m_noInputEvents = true;
- } else {
- m_noInputEvents = false;
- ret = sendDeferredInputEvents() || ret;
- }
-
- ret = QEventDispatcherSymbian::processEvents(flags) || ret;
-
- m_noInputEvents = oldNoInputEventsValue;
- } QT_CATCH (const std::exception& ex) {
-#ifndef QT_NO_EXCEPTIONS
- CActiveScheduler::Current()->Error(qt_symbian_exception2Error(ex));
-#endif
- }
-
- return ret;
-}
-
-bool QEventDispatcherS60::hasPendingEvents()
-{
- return !m_deferredInputEvents.isEmpty() || QEventDispatcherSymbian::hasPendingEvents();
-}
-
-void QEventDispatcherS60::saveInputEvent(QSymbianControl *control, QWidget *widget, QInputEvent *event)
-{
- DeferredInputEvent inputEvent = {control, widget, event};
- m_deferredInputEvents.append(inputEvent);
- connect(widget, SIGNAL(destroyed(QObject*)), SLOT(removeInputEventsForWidget(QObject*)));
-}
-
-bool QEventDispatcherS60::sendDeferredInputEvents()
-{
- bool eventsSent = false;
- while (!m_deferredInputEvents.isEmpty()) {
- DeferredInputEvent inputEvent = m_deferredInputEvents.takeFirst();
-#ifndef QT_NO_EXCEPTIONS
- try {
-#endif
- inputEvent.control->sendInputEvent(inputEvent.widget, inputEvent.event);
-#ifndef QT_NO_EXCEPTIONS
- } catch (...) {
- delete inputEvent.event;
- throw;
- }
-#endif
- delete inputEvent.event;
- eventsSent = true;
- }
-
- return eventsSent;
-}
-
-void QEventDispatcherS60::removeInputEventsForWidget(QObject *object)
-{
- for (int c = 0; c < m_deferredInputEvents.size(); ++c) {
- if (m_deferredInputEvents[c].widget == object) {
- delete m_deferredInputEvents[c].event;
- m_deferredInputEvents.removeAt(c--);
- }
- }
-}
-
-// reimpl
-void QEventDispatcherS60::reactivateDeferredActiveObjects()
-{
- if (S60->qtOwnsS60Environment) {
- static_cast<QtEikonEnv *>(CCoeEnv::Static())->complete();
- }
-
- QEventDispatcherSymbian::reactivateDeferredActiveObjects();
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qeventdispatcher_s60_p.h b/src/gui/platforms/s60/qeventdispatcher_s60_p.h
deleted file mode 100644
index 7c5a8d03d4..0000000000
--- a/src/gui/platforms/s60/qeventdispatcher_s60_p.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/****************************************************************************
-**
-** 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 QEVENTDISPATCHER_S60_P_H
-#define QEVENTDISPATCHER_S60_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <private/qeventdispatcher_symbian_p.h>
-#include "qt_s60_p.h"
-
-#include <eikenv.h>
-
-QT_BEGIN_NAMESPACE
-
-class QEventDispatcherS60;
-
-class QtEikonEnv : public CEikonEnv
-{
-public:
- QtEikonEnv();
- ~QtEikonEnv();
-
- // from CActive.
- void RunL();
- void DoCancel();
-
- void complete();
-
-private:
- // Workaround for a BC break from S60 3.2 -> 5.0, where the CEikonEnv override was removed.
- // To avoid linking to that when we build against 3.2, define an empty body here.
- // Reserved_*() have been verified to be empty in the S60 code.
- void Reserved_1() {}
- void Reserved_2() {}
-
-private:
- int m_lastIterationCount;
- TInt m_savedStatusCode;
- bool m_hasAlreadyRun;
-};
-
-class Q_GUI_EXPORT QEventDispatcherS60 : public QEventDispatcherSymbian
-{
- Q_OBJECT
-
-public:
- QEventDispatcherS60(QObject *parent = 0);
- ~QEventDispatcherS60();
-
- bool processEvents ( QEventLoop::ProcessEventsFlags flags );
- bool hasPendingEvents();
-
- bool excludeUserInputEvents() { return m_noInputEvents; }
-
- void saveInputEvent(QSymbianControl *control, QWidget *widget, QInputEvent *event);
-
- void reactivateDeferredActiveObjects();
-
-private:
- bool sendDeferredInputEvents();
-
-private Q_SLOTS:
- void removeInputEventsForWidget(QObject *object);
-
-private:
- bool m_noInputEvents;
-
- struct DeferredInputEvent
- {
- QSymbianControl *control;
- QWidget *widget;
- QInputEvent *event;
- };
- QList<DeferredInputEvent> m_deferredInputEvents;
-};
-
-QT_END_NAMESPACE
-
-#endif // QEVENTDISPATCHER_S60_P_H
diff --git a/src/gui/platforms/s60/qfont_s60.cpp b/src/gui/platforms/s60/qfont_s60.cpp
deleted file mode 100644
index 114191d765..0000000000
--- a/src/gui/platforms/s60/qfont_s60.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfont.h"
-#include "qfont_p.h"
-#include <private/qt_s60_p.h>
-#include <private/qpixmap_s60_p.h>
-#include "qmutex.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_NO_FREETYPE
-Q_GLOBAL_STATIC(QMutex, lastResortFamilyMutex);
-#endif // QT_NO_FREETYPE
-
-extern QStringList qt_symbian_fontFamiliesOnFontServer(); // qfontdatabase_s60.cpp
-Q_GLOBAL_STATIC_WITH_INITIALIZER(QStringList, fontFamiliesOnFontServer, {
- // We are only interested in the initial font families. No Application fonts.
- // Therefore, we are allowed to cache the list.
- x->append(qt_symbian_fontFamiliesOnFontServer());
-});
-
-QString QFont::lastResortFont() const
-{
- // Symbian's font Api does not distinguish between font and family.
- // Therefore we try to get a "Family" first, then fall back to "Sans".
- static QString font = lastResortFamily();
- if (font.isEmpty())
- font = QLatin1String("Sans");
- return font;
-}
-
-QString QFont::lastResortFamily() const
-{
-#ifdef QT_NO_FREETYPE
- QMutexLocker locker(lastResortFamilyMutex());
- static QString family;
- if (family.isEmpty()) {
-
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
-
- CFont *font;
- const TInt err = S60->screenDevice()->GetNearestFontInTwips(font, TFontSpec());
- Q_ASSERT(err == KErrNone);
- const TFontSpec spec = font->FontSpecInTwips();
- family = QString((const QChar *)spec.iTypeface.iName.Ptr(), spec.iTypeface.iName.Length());
- S60->screenDevice()->ReleaseFont(font);
-
- lock.relock();
- }
- return family;
-#else // QT_NO_FREETYPE
- // For the FreeType case we just hard code the face name, since otherwise on
- // East Asian systems we may get a name for a stroke based (non-ttf) font.
-
- // TODO: Get the type face name in a proper way
-
- const bool isJapaneseOrChineseSystem =
- User::Language() == ELangJapanese || User::Language() == ELangPrcChinese;
-
- static QString family;
- if (family.isEmpty()) {
- QStringList families = qt_symbian_fontFamiliesOnFontServer();
- const char* const preferredFamilies[] = {"Nokia Sans S60", "Series 60 Sans"};
- for (int i = 0; i < sizeof preferredFamilies / sizeof preferredFamilies[0]; ++i) {
- const QString preferredFamily = QLatin1String(preferredFamilies[i]);
- if (families.contains(preferredFamily)) {
- family = preferredFamily;
- break;
- }
- }
- }
-
- return QLatin1String(isJapaneseOrChineseSystem?"Heisei Kaku Gothic S60":family.toLatin1());
-#endif // QT_NO_FREETYPE
-}
-
-QString QFont::defaultFamily() const
-{
-#ifdef QT_NO_FREETYPE
- switch(d->request.styleHint) {
- case QFont::SansSerif: {
- static const char* const preferredSansSerif[] = {"Nokia Sans S60", "Series 60 Sans"};
- for (int i = 0; i < sizeof preferredSansSerif / sizeof preferredSansSerif[0]; ++i) {
- const QString sansSerif = QLatin1String(preferredSansSerif[i]);
- if (fontFamiliesOnFontServer()->contains(sansSerif))
- return sansSerif;
- }
- }
- // No break. Intentional fall through.
- default:
- return lastResortFamily();
- }
-#endif // QT_NO_FREETYPE
- return lastResortFamily();
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qfontdatabase_s60.cpp b/src/gui/platforms/s60/qfontdatabase_s60.cpp
deleted file mode 100644
index 1db4a7d359..0000000000
--- a/src/gui/platforms/s60/qfontdatabase_s60.cpp
+++ /dev/null
@@ -1,1091 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qapplication_p.h>
-#include "qdir.h"
-#include "qfont_p.h"
-#include "qfontengine_s60_p.h"
-#include "qabstractfileengine.h"
-#include "qdesktopservices.h"
-#include "qtemporaryfile.h"
-#include "qtextcodec.h"
-#include <private/qpixmap_s60_p.h>
-#include <private/qt_s60_p.h>
-#include "qendian.h"
-#include <private/qcore_symbian_p.h>
-#ifdef QT_NO_FREETYPE
-#include <openfont.h>
-#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
-#include <graphics/openfontrasterizer.h> // COpenFontRasterizer has moved to a new header file
-#endif // SYMBIAN_ENABLE_SPLIT_HEADERS
-#endif // QT_NO_FREETYPE
-
-QT_BEGIN_NAMESPACE
-
-QStringList qt_symbian_fontFamiliesOnFontServer() // Also used in qfont_s60.cpp
-{
- QStringList result;
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
- const int numTypeFaces = S60->screenDevice()->NumTypefaces();
- for (int i = 0; i < numTypeFaces; i++) {
- TTypefaceSupport typefaceSupport;
- S60->screenDevice()->TypefaceSupport(typefaceSupport, i);
- const QString familyName((const QChar *)typefaceSupport.iTypeface.iName.Ptr(), typefaceSupport.iTypeface.iName.Length());
- result.append(familyName);
- }
- lock.relock();
- return result;
-}
-
-QFileInfoList alternativeFilePaths(const QString &path, const QStringList &nameFilters,
- QDir::Filters filters = QDir::NoFilter, QDir::SortFlags sort = QDir::NoSort,
- bool uniqueFileNames = true)
-{
- QFileInfoList result;
-
- // Prepare a 'soft to hard' drive list: W:, X: ... A:, Z:
- QStringList driveStrings;
- foreach (const QFileInfo &drive, QDir::drives())
- driveStrings.append(drive.absolutePath());
- driveStrings.sort();
- const QString zDriveString(QLatin1String("Z:/"));
- driveStrings.removeAll(zDriveString);
- driveStrings.prepend(zDriveString);
-
- QStringList uniqueFileNameList;
- for (int i = driveStrings.count() - 1; i >= 0; --i) {
- const QDir dirOnDrive(driveStrings.at(i) + path);
- const QFileInfoList entriesOnDrive = dirOnDrive.entryInfoList(nameFilters, filters, sort);
- if (uniqueFileNames) {
- foreach(const QFileInfo &entry, entriesOnDrive) {
- if (!uniqueFileNameList.contains(entry.fileName())) {
- uniqueFileNameList.append(entry.fileName());
- result.append(entry);
- }
- }
- } else {
- result.append(entriesOnDrive);
- }
- }
- return result;
-}
-
-#ifdef QT_NO_FREETYPE
-class QSymbianFontDatabaseExtrasImplementation : public QSymbianFontDatabaseExtras
-{
-public:
- QSymbianFontDatabaseExtrasImplementation();
- ~QSymbianFontDatabaseExtrasImplementation();
-
- const QSymbianTypeFaceExtras *extras(const QString &typeface, bool bold, bool italic) const;
- void removeAppFontData(QFontDatabasePrivate::ApplicationFont *fnt);
- static inline bool appFontLimitReached();
- TUid addFontFileToFontStore(const QFileInfo &fontFileInfo);
- static void clear();
-
- static inline QString tempAppFontFolder();
- static const QString appFontMarkerPrefix;
- static QString appFontMarker(); // 'qaf<shortUid[+shortPid]>'
-
- struct CFontFromFontStoreReleaser {
- static inline void cleanup(CFont *font)
- {
- if (!font)
- return;
- const QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<const QSymbianFontDatabaseExtrasImplementation*>(privateDb()->symbianExtras);
- dbExtras->m_store->ReleaseFont(font);
- }
- };
-
- struct CFontFromScreenDeviceReleaser {
- static inline void cleanup(CFont *font)
- {
- if (!font)
- return;
- S60->screenDevice()->ReleaseFont(font);
- }
- };
-
-// m_heap, m_store, m_rasterizer and m_extras are used if Symbian
-// does not provide the Font Table API
- RHeap* m_heap;
- CFontStore *m_store;
- COpenFontRasterizer *m_rasterizer;
- mutable QList<const QSymbianTypeFaceExtras *> m_extras;
-
- mutable QHash<QString, const QSymbianTypeFaceExtras *> m_extrasHash;
- mutable QSet<QString> m_applicationFontFamilies;
-};
-
-const QString QSymbianFontDatabaseExtrasImplementation::appFontMarkerPrefix =
- QLatin1String("Q");
-
-inline QString QSymbianFontDatabaseExtrasImplementation::tempAppFontFolder()
-{
- return QDir::toNativeSeparators(QDir::tempPath()) + QLatin1Char('\\');
-}
-
-QString QSymbianFontDatabaseExtrasImplementation::appFontMarker()
-{
- static QString result;
- if (result.isEmpty()) {
- quint16 id = 0;
- if (QSymbianTypeFaceExtras::symbianFontTableApiAvailable()) {
- // We are allowed to load app fonts even from previous, crashed runs
- // of this application, since we can access the font tables.
- const quint32 uid = RProcess().Type().MostDerived().iUid;
- id = static_cast<quint16>(uid + (uid >> 16));
- } else {
- // If no font table Api is available, we must not even load a font
- // from a previous (crashed) run of this application. Reason: we
- // won't get the font tables, they are not in the CFontStore.
- // So, we use the pid, for more uniqueness.
- id = static_cast<quint16>(RProcess().Id().Id());
- }
- result = appFontMarkerPrefix + QString::fromLatin1("%1").arg(id & 0x7fff, 3, 32, QLatin1Char('0'));
- Q_ASSERT(appFontMarkerPrefix.length() == 1 && result.length() == 4);
- }
- return result;
-}
-
-static inline bool qt_symbian_fontNameHasAppFontMarker(const QString &fontName)
-{
- const int idLength = 3; // Keep in sync with id length in appFontMarker().
- const QString &prefix = QSymbianFontDatabaseExtrasImplementation::appFontMarkerPrefix;
- if (fontName.length() < prefix.length() + idLength
- || fontName.mid(fontName.length() - idLength - prefix.length(), prefix.length()) != prefix)
- return false;
- // Testing if the the id is base32 data
- for (int i = fontName.length() - idLength; i < fontName.length(); ++i) {
- const QChar &c = fontName.at(i);
- if (!(c >= QLatin1Char('0') && c <= QLatin1Char('9')
- || c >= QLatin1Char('a') && c <= QLatin1Char('v')))
- return false;
- }
- return true;
-}
-
-// If fontName is an application font of this app, prepend the app font marker
-QString qt_symbian_fontNameWithAppFontMarker(const QString &fontName)
-{
- QFontDatabasePrivate *db = privateDb();
- Q_ASSERT(db);
- const QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<const QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras);
- return dbExtras->m_applicationFontFamilies.contains(fontName) ?
- fontName + QSymbianFontDatabaseExtrasImplementation::appFontMarker()
- : fontName;
-}
-
-static inline QString qt_symbian_appFontNameWithoutMarker(const QString &markedFontName)
-{
- return markedFontName.left(markedFontName.length()
- - QSymbianFontDatabaseExtrasImplementation::appFontMarker().length());
-}
-
-QSymbianFontDatabaseExtrasImplementation::QSymbianFontDatabaseExtrasImplementation()
-{
- if (!QSymbianTypeFaceExtras::symbianFontTableApiAvailable()) {
- QStringList filters;
- filters.append(QLatin1String("*.ttf"));
- filters.append(QLatin1String("*.ccc"));
- filters.append(QLatin1String("*.ltt"));
- const QFileInfoList fontFiles = alternativeFilePaths(QLatin1String("resource\\Fonts"), filters);
-
- const TInt heapMinLength = 0x1000;
- const TInt heapMaxLength = qMax(0x20000 * fontFiles.count(), heapMinLength);
- m_heap = User::ChunkHeap(NULL, heapMinLength, heapMaxLength);
- QT_TRAP_THROWING(
- m_store = CFontStore::NewL(m_heap);
- m_rasterizer = COpenFontRasterizer::NewL(TUid::Uid(0x101F7F5E));
- CleanupStack::PushL(m_rasterizer);
- m_store->InstallRasterizerL(m_rasterizer);
- CleanupStack::Pop(m_rasterizer););
-
- foreach (const QFileInfo &fontFileInfo, fontFiles)
- addFontFileToFontStore(fontFileInfo);
- }
-}
-
-void QSymbianFontDatabaseExtrasImplementation::clear()
-{
- QFontDatabasePrivate *db = privateDb();
- if (!db)
- return;
- const QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<const QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras);
- if (!dbExtras)
- return; // initializeDb() has never been called
- if (QSymbianTypeFaceExtras::symbianFontTableApiAvailable()) {
- qDeleteAll(dbExtras->m_extrasHash);
- } else {
- typedef QList<const QSymbianTypeFaceExtras *>::iterator iterator;
- for (iterator p = dbExtras->m_extras.begin(); p != dbExtras->m_extras.end(); ++p) {
- dbExtras->m_store->ReleaseFont((*p)->fontOwner());
- delete *p;
- }
- dbExtras->m_extras.clear();
- }
- dbExtras->m_extrasHash.clear();
-}
-
-void qt_cleanup_symbianFontDatabase()
-{
- QFontDatabasePrivate *db = privateDb();
- if (!db)
- return;
-
- QSymbianFontDatabaseExtrasImplementation::clear();
-
- if (!db->applicationFonts.isEmpty()) {
- QFontDatabase::removeAllApplicationFonts();
- // We remove the left over temporary font files of Qt application.
- // Active fonts are undeletable since the font server holds a handle
- // on them, so we do not need to worry to delete other running
- // applications' fonts.
- const QDir dir(QSymbianFontDatabaseExtrasImplementation::tempAppFontFolder());
- const QStringList filter(
- QSymbianFontDatabaseExtrasImplementation::appFontMarkerPrefix + QLatin1String("*.ttf"));
- foreach (const QFileInfo &ttfFile, dir.entryInfoList(filter))
- QFile(ttfFile.absoluteFilePath()).remove();
- db->applicationFonts.clear();
- }
-}
-
-QSymbianFontDatabaseExtrasImplementation::~QSymbianFontDatabaseExtrasImplementation()
-{
- qt_cleanup_symbianFontDatabase();
- if (!QSymbianTypeFaceExtras::symbianFontTableApiAvailable()) {
- delete m_store;
- m_heap->Close();
- }
-}
-
-#ifndef FNTSTORE_H_INLINES_SUPPORT_FMM
-/*
- Workaround: fntstore.h has an inlined function 'COpenFont* CBitmapFont::OpenFont()'
- that returns a private data member. The header will change between SDKs. But Qt has
- to build on any SDK version and run on other versions of Symbian OS.
- This function performs the needed pointer arithmetic to get the right COpenFont*
-*/
-COpenFont* OpenFontFromBitmapFont(const CBitmapFont* aBitmapFont)
-{
- const TInt offsetIOpenFont = 92; // '_FOFF(CBitmapFont, iOpenFont)' ..if iOpenFont weren't private
- const TUint valueIOpenFont = *(TUint*)PtrAdd(aBitmapFont, offsetIOpenFont);
- return (valueIOpenFont & 1) ?
- (COpenFont*)PtrAdd(aBitmapFont, valueIOpenFont & ~1) : // New behavior: iOpenFont is offset
- (COpenFont*)valueIOpenFont; // Old behavior: iOpenFont is pointer
-}
-#endif // FNTSTORE_H_INLINES_SUPPORT_FMM
-
-const QSymbianTypeFaceExtras *QSymbianFontDatabaseExtrasImplementation::extras(const QString &aTypeface,
- bool bold, bool italic) const
-{
- const QString typeface = qt_symbian_fontNameWithAppFontMarker(aTypeface);
- const QString searchKey = typeface + QString::number(int(bold)) + QString::number(int(italic));
- if (!m_extrasHash.contains(searchKey)) {
- TFontSpec searchSpec(qt_QString2TPtrC(typeface), 1);
- if (bold)
- searchSpec.iFontStyle.SetStrokeWeight(EStrokeWeightBold);
- if (italic)
- searchSpec.iFontStyle.SetPosture(EPostureItalic);
-
- CFont* font = NULL;
- if (QSymbianTypeFaceExtras::symbianFontTableApiAvailable()) {
- const TInt err = S60->screenDevice()->GetNearestFontToDesignHeightInPixels(font, searchSpec);
- Q_ASSERT(err == KErrNone && font);
- QScopedPointer<CFont, CFontFromScreenDeviceReleaser> sFont(font);
- QSymbianTypeFaceExtras *extras = new QSymbianTypeFaceExtras(font);
- sFont.take();
- m_extrasHash.insert(searchKey, extras);
- } else {
- const TInt err = m_store->GetNearestFontToDesignHeightInPixels(font, searchSpec);
- Q_ASSERT(err == KErrNone && font);
- const CBitmapFont *bitmapFont = static_cast<CBitmapFont*>(font);
- COpenFont *openFont =
-#ifdef FNTSTORE_H_INLINES_SUPPORT_FMM
- bitmapFont->OpenFont();
-#else // FNTSTORE_H_INLINES_SUPPORT_FMM
- OpenFontFromBitmapFont(bitmapFont);
-#endif // FNTSTORE_H_INLINES_SUPPORT_FMM
- const TOpenFontFaceAttrib* const attrib = openFont->FaceAttrib();
- const QString foundKey =
- QString((const QChar*)attrib->FullName().Ptr(), attrib->FullName().Length());
- if (!m_extrasHash.contains(foundKey)) {
- QScopedPointer<CFont, CFontFromFontStoreReleaser> sFont(font);
- QSymbianTypeFaceExtras *extras = new QSymbianTypeFaceExtras(font, openFont);
- sFont.take();
- m_extras.append(extras);
- m_extrasHash.insert(searchKey, extras);
- m_extrasHash.insert(foundKey, extras);
- } else {
- m_store->ReleaseFont(font);
- m_extrasHash.insert(searchKey, m_extrasHash.value(foundKey));
- }
- }
- }
- return m_extrasHash.value(searchKey);
-}
-
-void QSymbianFontDatabaseExtrasImplementation::removeAppFontData(
- QFontDatabasePrivate::ApplicationFont *fnt)
-{
- clear();
- if (!QSymbianTypeFaceExtras::symbianFontTableApiAvailable()
- && fnt->fontStoreFontFileUid.iUid != 0)
- m_store->RemoveFile(fnt->fontStoreFontFileUid);
- if (!fnt->families.isEmpty())
- m_applicationFontFamilies.remove(fnt->families.first());
- if (fnt->screenDeviceFontFileId != 0)
- S60->screenDevice()->RemoveFile(fnt->screenDeviceFontFileId);
- QFile::remove(fnt->temporaryFileName);
- *fnt = QFontDatabasePrivate::ApplicationFont();
-}
-
-bool QSymbianFontDatabaseExtrasImplementation::appFontLimitReached()
-{
- QFontDatabasePrivate *db = privateDb();
- if (!db)
- return false;
- const int maxAppFonts = 5;
- int registeredAppFonts = 0;
- foreach (const QFontDatabasePrivate::ApplicationFont &appFont, db->applicationFonts)
- if (!appFont.families.isEmpty() && ++registeredAppFonts == maxAppFonts)
- return true;
- return false;
-}
-
-TUid QSymbianFontDatabaseExtrasImplementation::addFontFileToFontStore(const QFileInfo &fontFileInfo)
-{
- Q_ASSERT(!QSymbianTypeFaceExtras::symbianFontTableApiAvailable());
- const QString fontFile = QDir::toNativeSeparators(fontFileInfo.absoluteFilePath());
- const TPtrC fontFilePtr(qt_QString2TPtrC(fontFile));
- TUid fontUid = {0};
- TRAP_IGNORE(fontUid = m_store->AddFileL(fontFilePtr));
- return fontUid;
-}
-
-#else // QT_NO_FREETYPE
-class QFontEngineFTS60 : public QFontEngineFT
-{
-public:
- QFontEngineFTS60(const QFontDef &fd);
-};
-
-QFontEngineFTS60::QFontEngineFTS60(const QFontDef &fd)
- : QFontEngineFT(fd)
-{
- default_hint_style = HintFull;
-}
-#endif // QT_NO_FREETYPE
-
-/*
- QFontEngineS60::pixelsToPoints, QFontEngineS60::pointsToPixels, QFontEngineMultiS60::QFontEngineMultiS60
- and QFontEngineMultiS60::QFontEngineMultiS60 should be in qfontengine_s60.cpp. But since also the
- Freetype based font rendering need them, they are here.
-*/
-qreal QFontEngineS60::pixelsToPoints(qreal pixels, Qt::Orientation orientation)
-{
- CWsScreenDevice* device = S60->screenDevice();
- return (orientation == Qt::Horizontal?
- device->HorizontalPixelsToTwips(pixels)
- :device->VerticalPixelsToTwips(pixels)) / KTwipsPerPoint;
-}
-
-qreal QFontEngineS60::pointsToPixels(qreal points, Qt::Orientation orientation)
-{
- CWsScreenDevice* device = S60->screenDevice();
- const int twips = points * KTwipsPerPoint;
- return orientation == Qt::Horizontal?
- device->HorizontalTwipsToPixels(twips)
- :device->VerticalTwipsToPixels(twips);
-}
-
-QFontEngineMultiS60::QFontEngineMultiS60(QFontEngine *first, int script, const QStringList &fallbackFamilies)
- : QFontEngineMulti(fallbackFamilies.size() + 1)
- , m_script(script)
- , m_fallbackFamilies(fallbackFamilies)
-{
- engines[0] = first;
- first->ref.ref();
- fontDef = engines[0]->fontDef;
-}
-
-void QFontEngineMultiS60::loadEngine(int at)
-{
- Q_ASSERT(at < engines.size());
- Q_ASSERT(engines.at(at) == 0);
-
- QFontDef request = fontDef;
- request.styleStrategy |= QFont::NoFontMerging;
- request.family = m_fallbackFamilies.at(at-1);
- engines[at] = QFontDatabase::findFont(m_script,
- /*fontprivate*/0,
- request);
- Q_ASSERT(engines[at]);
-}
-
-#ifdef QT_NO_FREETYPE
-static bool registerScreenDeviceFont(int screenDeviceFontIndex,
- const QSymbianFontDatabaseExtrasImplementation *dbExtras)
-{
- TTypefaceSupport typefaceSupport;
- S60->screenDevice()->TypefaceSupport(typefaceSupport, screenDeviceFontIndex);
-
- QString familyName((const QChar*)typefaceSupport.iTypeface.iName.Ptr(), typefaceSupport.iTypeface.iName.Length());
- if (qt_symbian_fontNameHasAppFontMarker(familyName)) {
- const QString &marker = QSymbianFontDatabaseExtrasImplementation::appFontMarker();
- if (familyName.endsWith(marker)) {
- familyName = qt_symbian_appFontNameWithoutMarker(familyName);
- dbExtras->m_applicationFontFamilies.insert(familyName);
- } else {
- return false; // This was somebody else's application font. Skip it.
- }
- }
-
- CFont *font; // We have to get a font instance in order to know all the details
- TFontSpec fontSpec(typefaceSupport.iTypeface.iName, 11);
- if (S60->screenDevice()->GetNearestFontInPixels(font, fontSpec) != KErrNone)
- return false;
- QScopedPointer<CFont, QSymbianFontDatabaseExtrasImplementation::CFontFromScreenDeviceReleaser> sFont(font);
- if (font->TypeUid() != KCFbsFontUid)
- return false;
- TOpenFontFaceAttrib faceAttrib;
- const CFbsFont *cfbsFont = static_cast<const CFbsFont *>(font);
- cfbsFont->GetFaceAttrib(faceAttrib);
-
- QtFontStyle::Key styleKey;
- styleKey.style = faceAttrib.IsItalic()?QFont::StyleItalic:QFont::StyleNormal;
- styleKey.weight = faceAttrib.IsBold()?QFont::Bold:QFont::Normal;
-
- QtFontFamily *family = privateDb()->family(familyName, true);
- family->fixedPitch = faceAttrib.IsMonoWidth();
- QtFontFoundry *foundry = family->foundry(QString(), true);
- QtFontStyle *style = foundry->style(styleKey, true);
- style->smoothScalable = typefaceSupport.iIsScalable;
- style->pixelSize(0, true);
-
- const QSymbianTypeFaceExtras *typeFaceExtras =
- dbExtras->extras(familyName, faceAttrib.IsBold(), faceAttrib.IsItalic());
- const QByteArray os2Table = typeFaceExtras->getSfntTable(MAKE_TAG('O', 'S', '/', '2'));
- const unsigned char* data = reinterpret_cast<const unsigned char*>(os2Table.constData());
- const unsigned char* ulUnicodeRange = data + 42;
- quint32 unicodeRange[4] = {
- qFromBigEndian<quint32>(ulUnicodeRange),
- qFromBigEndian<quint32>(ulUnicodeRange + 4),
- qFromBigEndian<quint32>(ulUnicodeRange + 8),
- qFromBigEndian<quint32>(ulUnicodeRange + 12)
- };
- const unsigned char* ulCodePageRange = data + 78;
- quint32 codePageRange[2] = {
- qFromBigEndian<quint32>(ulCodePageRange),
- qFromBigEndian<quint32>(ulCodePageRange + 4)
- };
- const QList<QFontDatabase::WritingSystem> writingSystems =
- qt_determine_writing_systems_from_truetype_bits(unicodeRange, codePageRange);
- foreach (const QFontDatabase::WritingSystem system, writingSystems)
- family->writingSystems[system] = QtFontFamily::Supported;
- return true;
-}
-#endif
-
-static void initializeDb()
-{
- QFontDatabasePrivate *db = privateDb();
- if(!db || db->count)
- return;
-
-#ifdef QT_NO_FREETYPE
- if (!db->symbianExtras)
- db->symbianExtras = new QSymbianFontDatabaseExtrasImplementation;
-
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
-
- const int numTypeFaces = S60->screenDevice()->NumTypefaces();
- const QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<const QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras);
- for (int i = 0; i < numTypeFaces; i++)
- registerScreenDeviceFont(i, dbExtras);
-
- // We have to clear/release all CFonts, here, in case one of the fonts is
- // an application font of another running Qt app. Otherwise the other Qt app
- // cannot remove it's application font, anymore -> "Zombie Font".
- QSymbianFontDatabaseExtrasImplementation::clear();
-
- lock.relock();
-
-#else // QT_NO_FREETYPE
- QDir dir(QDesktopServices::storageLocation(QDesktopServices::FontsLocation));
- dir.setNameFilters(QStringList() << QLatin1String("*.ttf")
- << QLatin1String("*.ttc") << QLatin1String("*.pfa")
- << QLatin1String("*.pfb"));
- for (int i = 0; i < int(dir.count()); ++i) {
- const QByteArray file = QFile::encodeName(dir.absoluteFilePath(dir[i]));
- db->addTTFile(file);
- }
-#endif // QT_NO_FREETYPE
-}
-
-static inline void load(const QString &family = QString(), int script = -1)
-{
- Q_UNUSED(family)
- Q_UNUSED(script)
- initializeDb();
-}
-
-struct OffsetTable {
- quint32 sfntVersion;
- quint16 numTables, searchRange, entrySelector, rangeShift;
-};
-
-struct TableRecord {
- quint32 tag, checkSum, offset, length;
-};
-
-struct NameTableHead {
- quint16 format, count, stringOffset;
-};
-
-struct NameRecord {
- quint16 platformID, encodingID, languageID, nameID, length, offset;
-};
-
-static quint32 ttfCalcChecksum(const char *data, quint32 bytesCount)
-{
- quint32 result = 0;
- const quint32 *ptr = reinterpret_cast<const quint32*>(data);
- const quint32 *endPtr =
- ptr + (bytesCount + sizeof(quint32) - 1) / sizeof(quint32);
- while (ptr < endPtr) {
- const quint32 unit32Value = *ptr++;
- result += qFromBigEndian(unit32Value);
- }
- return result;
-}
-
-static inline quint32 toDWordBoundary(quint32 value)
-{
- return (value + 3) & ~3;
-}
-
-static inline quint32 dWordPadding(quint32 value)
-{
- return (4 - (value & 3)) & 3;
-}
-
-static inline bool ttfMarkNameTable(QByteArray &table, const QString &marker)
-{
- const quint32 tableLength = static_cast<quint32>(table.size());
-
- if (tableLength > 50000 // hard limit
- || tableLength < sizeof(NameTableHead)) // corrupt name table
- return false;
-
- const NameTableHead *head = reinterpret_cast<const NameTableHead*>(table.constData());
- const quint16 count = qFromBigEndian(head->count);
- const quint16 stringOffset = qFromBigEndian(head->stringOffset);
- if (count > 200 // hard limit
- || stringOffset >= tableLength // corrupt name table
- || sizeof(NameTableHead) + count * sizeof(NameRecord) >= tableLength) // corrupt name table
- return false;
-
- QTextEncoder encoder(QTextCodec::codecForName("UTF-16BE"), QTextCodec::IgnoreHeader);
- const QByteArray markerUtf16BE = encoder.fromUnicode(marker);
- const QByteArray markerAscii = marker.toAscii();
-
- QByteArray markedTable;
- markedTable.reserve(tableLength + marker.length() * 20); // Original size plus some extra
- markedTable.append(table, stringOffset);
- QByteArray markedStrings;
- quint32 stringDataCount = stringOffset;
- for (quint16 i = 0; i < count; ++i) {
- const quint32 nameRecordOffset = sizeof(NameTableHead) + sizeof(NameRecord) * i;
- NameRecord *nameRecord =
- reinterpret_cast<NameRecord*>(markedTable.data() + nameRecordOffset);
- const quint16 nameID = qFromBigEndian(nameRecord->nameID);
- const quint16 platformID = qFromBigEndian(nameRecord->platformID);
- const quint16 encodingID = qFromBigEndian(nameRecord->encodingID);
- const quint16 offset = qFromBigEndian(nameRecord->offset);
- const quint16 length = qFromBigEndian(nameRecord->length);
- stringDataCount += length;
- if (stringDataCount > 80000 // hard limit. String data may be > name table size. Multiple records can reference the same string.
- || static_cast<quint32>(stringOffset + offset + length) > tableLength) // String outside bounds
- return false;
- const bool needsMarker =
- nameID == 1 || nameID == 3 || nameID == 4 || nameID == 16 || nameID == 21;
- const bool isUnicode =
- platformID == 0 || platformID == 3 && encodingID == 1;
- const QByteArray originalString =
- QByteArray::fromRawData(table.constData() + stringOffset + offset, length);
- QByteArray markedString;
- if (needsMarker) {
- const int maxBytesLength = (KMaxTypefaceNameLength - marker.length()) * (isUnicode ? 2 : 1);
- markedString = originalString.left(maxBytesLength) + (isUnicode ? markerUtf16BE : markerAscii);
- } else {
- markedString = originalString;
- }
- nameRecord->offset = qToBigEndian(static_cast<quint16>(markedStrings.length()));
- nameRecord->length = qToBigEndian(static_cast<quint16>(markedString.length()));
- markedStrings.append(markedString);
- }
- markedTable.append(markedStrings);
- table = markedTable;
- return true;
-}
-
-const quint32 ttfMaxFileSize = 3500000;
-
-static inline bool ttfMarkAppFont(QByteArray &ttf, const QString &marker)
-{
- const quint32 ttfChecksumNumber = 0xb1b0afba;
- const quint32 alignment = 4;
- const quint32 ttfLength = static_cast<quint32>(ttf.size());
- if (ttfLength > ttfMaxFileSize // hard limit
- || ttfLength % alignment != 0 // ttf sizes are always factors of 4
- || ttfLength <= sizeof(OffsetTable) // ttf too short
- || ttfCalcChecksum(ttf.constData(), ttf.size()) != ttfChecksumNumber) // ttf checksum is invalid
- return false;
-
- const OffsetTable *offsetTable = reinterpret_cast<const OffsetTable*>(ttf.constData());
- const quint16 numTables = qFromBigEndian(offsetTable->numTables);
- const quint32 recordsLength =
- toDWordBoundary(sizeof(OffsetTable) + numTables * sizeof(TableRecord));
- if (numTables > 30 // hard limit
- || recordsLength + numTables * alignment > ttfLength) // Corrupt ttf. Tables would not fit, even if empty.
- return false;
-
- QByteArray markedTtf;
- markedTtf.reserve(ttfLength + marker.length() * 20); // Original size plus some extra
- markedTtf.append(ttf.constData(), recordsLength);
-
- const quint32 ttfCheckSumAdjustmentOffset = 8; // Offset from the start of 'head'
- int indexOfHeadTable = -1;
- quint32 ttfDataSize = recordsLength;
- typedef QPair<quint32, quint32> Range;
- QList<Range> memoryRanges;
- memoryRanges.reserve(numTables);
- for (int i = 0; i < numTables; ++i) {
- TableRecord *tableRecord =
- reinterpret_cast<TableRecord*>(markedTtf.data() + sizeof(OffsetTable) + i * sizeof(TableRecord));
- const quint32 offset = qFromBigEndian(tableRecord->offset);
- const quint32 length = qFromBigEndian(tableRecord->length);
- const quint32 lengthAligned = toDWordBoundary(length);
- ttfDataSize += lengthAligned;
- if (offset < recordsLength // must not intersect ttf header/records
- || offset % alignment != 0 // must be aligned
- || offset > ttfLength - alignment // table out of bounds
- || offset + lengthAligned > ttfLength // table out of bounds
- || ttfDataSize > ttfLength) // tables would not fit into the ttf
- return false;
-
- foreach (const Range &range, memoryRanges)
- if (offset < range.first + range.second && offset + lengthAligned > range.first)
- return false; // Overlaps with another table
- memoryRanges.append(Range(offset, lengthAligned));
-
- quint32 checkSum = qFromBigEndian(tableRecord->checkSum);
- if (tableRecord->tag == qToBigEndian(static_cast<quint32>('head'))) {
- if (length < ttfCheckSumAdjustmentOffset + sizeof(quint32))
- return false; // Invalid 'head' table
- const quint32 *checkSumAdjustmentTag =
- reinterpret_cast<const quint32*>(ttf.constData() + offset + ttfCheckSumAdjustmentOffset);
- const quint32 checkSumAdjustment = qFromBigEndian(*checkSumAdjustmentTag);
- checkSum += checkSumAdjustment;
- indexOfHeadTable = i; // For the ttf checksum re-calculation, later
- }
- if (checkSum != ttfCalcChecksum(ttf.constData() + offset, length))
- return false; // Table checksum is invalid
-
- bool updateTableChecksum = false;
- QByteArray table;
- if (tableRecord->tag == qToBigEndian(static_cast<quint32>('name'))) {
- table = QByteArray(ttf.constData() + offset, length);
- if (!ttfMarkNameTable(table, marker))
- return false; // Name table was not markable.
- updateTableChecksum = true;
- } else {
- table = QByteArray::fromRawData(ttf.constData() + offset, length);
- }
-
- tableRecord->offset = qToBigEndian(markedTtf.size());
- tableRecord->length = qToBigEndian(table.size());
- markedTtf.append(table);
- markedTtf.append(QByteArray(dWordPadding(table.size()), 0)); // 0-padding
- if (updateTableChecksum) {
- TableRecord *tableRecord = // Need to recalculate, since markedTtf changed
- reinterpret_cast<TableRecord*>(markedTtf.data() + sizeof(OffsetTable) + i * sizeof(TableRecord));
- const quint32 offset = qFromBigEndian(tableRecord->offset);
- const quint32 length = qFromBigEndian(tableRecord->length);
- tableRecord->checkSum = qToBigEndian(ttfCalcChecksum(markedTtf.constData() + offset, length));
- }
- }
- if (indexOfHeadTable == -1 // 'head' table is mandatory
- || ttfDataSize != ttfLength) // We do not allow ttf data "holes". Neither does Symbian.
- return false;
- TableRecord *headRecord =
- reinterpret_cast<TableRecord*>(markedTtf.data() + sizeof(OffsetTable) + indexOfHeadTable * sizeof(TableRecord));
- quint32 *checkSumAdjustmentTag =
- reinterpret_cast<quint32*>(markedTtf.data() + qFromBigEndian(headRecord->offset) + ttfCheckSumAdjustmentOffset);
- *checkSumAdjustmentTag = 0;
- const quint32 ttfChecksum = ttfCalcChecksum(markedTtf.constData(), markedTtf.count());
- *checkSumAdjustmentTag = qToBigEndian(ttfChecksumNumber - ttfChecksum);
- ttf = markedTtf;
- return true;
-}
-
-static inline bool ttfCanSymbianLoadFont(const QByteArray &data, const QString &fileName)
-{
- bool result = false;
- QString ttfFileName;
- QFile tempFileGuard;
- QFileInfo info(fileName);
- if (!data.isEmpty()) {
- QTemporaryFile tempfile(QSymbianFontDatabaseExtrasImplementation::tempAppFontFolder()
- + QSymbianFontDatabaseExtrasImplementation::appFontMarker()
- + QLatin1String("XXXXXX.ttf"));
- if (!tempfile.open() || tempfile.write(data) == -1)
- return false;
- ttfFileName = QDir::toNativeSeparators(QFileInfo(tempfile).canonicalFilePath());
- tempfile.setAutoRemove(false);
- tempfile.close();
- tempFileGuard.setFileName(ttfFileName);
- if (!tempFileGuard.open(QIODevice::ReadOnly))
- return false;
- } else if (info.isFile()) {
- ttfFileName = QDir::toNativeSeparators(info.canonicalFilePath());
- } else {
- return false;
- }
-
- CFontStore *store = 0;
- RHeap* heap = User::ChunkHeap(NULL, 0x1000, 0x20000);
- if (heap) {
- QT_TRAP_THROWING(
- CleanupClosePushL(*heap);
- store = CFontStore::NewL(heap);
- CleanupStack::PushL(store);
- COpenFontRasterizer *rasterizer = COpenFontRasterizer::NewL(TUid::Uid(0x101F7F5E));
- CleanupStack::PushL(rasterizer);
- store->InstallRasterizerL(rasterizer);
- CleanupStack::Pop(rasterizer);
- TUid fontUid = {-1};
- TRAP_IGNORE(fontUid = store->AddFileL(qt_QString2TPtrC(ttfFileName)));
- if (fontUid.iUid != -1)
- result = true;
- CleanupStack::PopAndDestroy(2, heap); // heap, store
- );
- }
-
- if (tempFileGuard.isOpen())
- tempFileGuard.remove();
-
- return result;
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
-{
- if (QSymbianFontDatabaseExtrasImplementation::appFontLimitReached()
- || fnt->data.size() > ttfMaxFileSize // hard limit
- || fnt->data.isEmpty() && (!fnt->fileName.endsWith(QLatin1String(".ttf"), Qt::CaseInsensitive) // Only buffer or .ttf
- || QFileInfo(fnt->fileName).size() > ttfMaxFileSize)) // hard limit
- return;
-
-// Using ttfCanSymbianLoadFont() causes crashes on app destruction (Symbian^3|PR1 and lower).
-// Therefore, not using it for now, but eventually in a later version.
-// if (!ttfCanSymbianLoadFont(fnt->data, fnt->fileName))
-// return;
-
- QFontDatabasePrivate *db = privateDb();
- if (!db)
- return;
-
- if (!db->count)
- initializeDb();
-
- QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras);
- if (!dbExtras)
- return;
-
- const QString &marker = QSymbianFontDatabaseExtrasImplementation::appFontMarker();
-
- // The QTemporaryFile object being used in the following section must be
- // destructed before letting Symbian load the TTF file. Symbian would not
- // load it otherwise, because QTemporaryFile will still keep some handle
- // on it. The scope is used to reduce the life time of the QTemporaryFile.
- // In order to prevent other processes from modifying the file between the
- // moment where the QTemporaryFile is destructed and the file is loaded by
- // Symbian, we have a QFile "tempFileGuard" outside the scope which opens
- // the file in ReadOnly mode while the QTemporaryFile is still alive.
- QFile tempFileGuard;
- {
- QTemporaryFile tempfile(QSymbianFontDatabaseExtrasImplementation::tempAppFontFolder()
- + marker + QLatin1String("XXXXXX.ttf"));
- if (!tempfile.open())
- return;
- const QString tempFileName = QFileInfo(tempfile).canonicalFilePath();
- if (fnt->data.isEmpty()) {
- QFile sourceFile(fnt->fileName);
- if (!sourceFile.open(QIODevice::ReadOnly))
- return;
- fnt->data = sourceFile.readAll();
- }
- if (!ttfMarkAppFont(fnt->data, marker) || tempfile.write(fnt->data) == -1)
- return;
- tempfile.setAutoRemove(false);
- tempfile.close(); // Tempfile still keeps a file handle, forbidding write access
- fnt->data.clear(); // The TTF data was marked and saved. Not needed in memory, anymore.
- tempFileGuard.setFileName(tempFileName);
- if (!tempFileGuard.open(QIODevice::ReadOnly))
- return;
- fnt->temporaryFileName = tempFileName;
- }
-
- const QString fullFileName = QDir::toNativeSeparators(fnt->temporaryFileName);
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
- const QStringList fontsOnServerBefore = qt_symbian_fontFamiliesOnFontServer();
- const TInt err =
- S60->screenDevice()->AddFile(qt_QString2TPtrC(fullFileName), fnt->screenDeviceFontFileId);
- tempFileGuard.close(); // Did its job
- const QStringList fontsOnServerAfter = qt_symbian_fontFamiliesOnFontServer();
- if (err == KErrNone && fontsOnServerBefore.count() < fontsOnServerAfter.count()) { // Added to screen device?
- int fontOnServerIndex = fontsOnServerAfter.count() - 1;
- for (int i = 0; i < fontsOnServerBefore.count(); i++) {
- if (fontsOnServerBefore.at(i) != fontsOnServerAfter.at(i)) {
- fontOnServerIndex = i;
- break;
- }
- }
-
- // Must remove all font engines with their CFonts, first.
- QFontCache::instance()->clear();
- db->free();
- QSymbianFontDatabaseExtrasImplementation::clear();
-
- if (!QSymbianTypeFaceExtras::symbianFontTableApiAvailable())
- fnt->fontStoreFontFileUid = dbExtras->addFontFileToFontStore(QFileInfo(fullFileName));
-
- const QString &appFontName = fontsOnServerAfter.at(fontOnServerIndex);
- fnt->families.append(qt_symbian_appFontNameWithoutMarker(appFontName));
- if (!qt_symbian_fontNameHasAppFontMarker(appFontName)
- || !registerScreenDeviceFont(fontOnServerIndex, dbExtras))
- dbExtras->removeAppFontData(fnt);
- } else {
- if (fnt->screenDeviceFontFileId > 0)
- S60->screenDevice()->RemoveFile(fnt->screenDeviceFontFileId); // May still have the file open!
- QFile::remove(fnt->temporaryFileName);
- *fnt = QFontDatabasePrivate::ApplicationFont();
- }
- lock.relock();
-}
-
-bool QFontDatabase::removeApplicationFont(int handle)
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- if (!db || handle < 0 || handle >= db->applicationFonts.count())
- return false;
- QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras);
- if (!dbExtras)
- return false;
-
- QFontDatabasePrivate::ApplicationFont *fnt = &db->applicationFonts[handle];
- if (fnt->families.isEmpty())
- return true; // Nothing to remove. Return peacefully.
-
- // Must remove all font engines with their CFonts, first
- QFontCache::instance()->clear();
- db->free();
- dbExtras->removeAppFontData(fnt);
-
- db->invalidate(); // This will just emit 'fontDatabaseChanged()'
- return true;
-}
-
-bool QFontDatabase::removeAllApplicationFonts()
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- const int applicationFontsCount = privateDb()->applicationFonts.count();
- for (int i = 0; i < applicationFontsCount; ++i)
- if (!removeApplicationFont(i))
- return false;
- return true;
-}
-
-bool QFontDatabase::supportsThreadedFontRendering()
-{
- return false;
-}
-
-static
-QFontDef cleanedFontDef(const QFontDef &req)
-{
- QFontDef result = req;
- if (result.pixelSize <= 0) {
- result.pixelSize = QFontEngineS60::pointsToPixels(qMax(qreal(1.0), result.pointSize));
- result.pointSize = 0;
- }
- return result;
-}
-
-QFontEngine *QFontDatabase::findFont(int script, const QFontPrivate *d, const QFontDef &req)
-{
- const QFontCache::Key key(cleanedFontDef(req), script);
-
- if (!privateDb()->count)
- initializeDb();
-
- QFontEngine *fe = QFontCache::instance()->findEngine(key);
- if (!fe) {
- // Making sure that fe->fontDef.family will be an existing font.
- initializeDb();
- QFontDatabasePrivate *db = privateDb();
- QtFontDesc desc;
- QList<int> blacklistedFamilies;
- match(script, key.def, key.def.family, QString(), -1, &desc, blacklistedFamilies);
- if (!desc.family) // falling back to application font
- desc.family = db->family(QApplication::font().defaultFamily());
- Q_ASSERT(desc.family);
-
- // Making sure that desc.family supports the requested script
- QtFontDesc mappedDesc;
- bool supportsScript = false;
- do {
- match(script, req, QString(), QString(), -1, &mappedDesc, blacklistedFamilies);
- if (mappedDesc.family == desc.family) {
- supportsScript = true;
- break;
- }
- blacklistedFamilies.append(mappedDesc.familyIndex);
- } while (mappedDesc.family);
- if (!supportsScript) {
- blacklistedFamilies.clear();
- match(script, req, QString(), QString(), -1, &mappedDesc, blacklistedFamilies);
- if (mappedDesc.family)
- desc = mappedDesc;
- }
-
- const QString fontFamily = desc.family->name;
- QFontDef request = req;
- request.family = fontFamily;
-#ifdef QT_NO_FREETYPE
- const QSymbianFontDatabaseExtrasImplementation *dbExtras =
- static_cast<const QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras);
- const QSymbianTypeFaceExtras *typeFaceExtras =
- dbExtras->extras(fontFamily, request.weight > QFont::Normal, request.style != QFont::StyleNormal);
-
- // We need a valid pixelSize, e.g. for lineThickness()
- if (request.pixelSize < 0)
- request.pixelSize = request.pointSize * d->dpi / 72;
-
- fe = new QFontEngineS60(request, typeFaceExtras);
-#else // QT_NO_FREETYPE
- Q_UNUSED(d)
- QFontEngine::FaceId faceId;
- const QtFontFamily * const reqQtFontFamily = db->family(fontFamily);
- faceId.filename = reqQtFontFamily->fontFilename;
- faceId.index = reqQtFontFamily->fontFileIndex;
-
- QFontEngineFTS60 *fte = new QFontEngineFTS60(cleanedFontDef(request));
- if (fte->init(faceId, true, QFontEngineFT::Format_A8))
- fe = fte;
- else
- delete fte;
-#endif // QT_NO_FREETYPE
-
- Q_ASSERT(fe);
- if (script == QUnicodeTables::Common
- && !(req.styleStrategy & QFont::NoFontMerging)
- && !fe->symbol) {
-
- QStringList commonFonts;
- for (int ws = 1; ws < QFontDatabase::WritingSystemsCount; ++ws) {
- if (scriptForWritingSystem[ws] != script)
- continue;
- for (int i = 0; i < db->count; ++i) {
- if (db->families[i]->writingSystems[ws] & QtFontFamily::Supported)
- commonFonts.append(db->families[i]->name);
- }
- }
-
- // Hack: Prioritize .ccc fonts
- const QString niceEastAsianFont(QLatin1String("Sans MT 936_S60"));
- if (commonFonts.removeAll(niceEastAsianFont) > 0)
- commonFonts.prepend(niceEastAsianFont);
-
- fe = new QFontEngineMultiS60(fe, script, commonFonts);
- }
- }
- fe->ref.ref();
- QFontCache::instance()->insertEngine(key, fe);
- return fe;
-}
-
-void QFontDatabase::load(const QFontPrivate *d, int script)
-{
- QFontEngine *fe = 0;
- QFontDef req = d->request;
-
- if (!d->engineData) {
- const QFontCache::Key key(cleanedFontDef(req), script);
- getEngineData(d, key);
- }
-
- // the cached engineData could have already loaded the engine we want
- if (d->engineData->engines[script])
- fe = d->engineData->engines[script];
-
- if (!fe) {
- if (qt_enable_test_font && req.family == QLatin1String("__Qt__Box__Engine__")) {
- fe = new QTestFontEngine(req.pixelSize);
- fe->fontDef = req;
- } else {
- fe = findFont(script, d, req);
- }
- d->engineData->engines[script] = fe;
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qfontengine_s60.cpp b/src/gui/platforms/s60/qfontengine_s60.cpp
deleted file mode 100644
index e9b54e350f..0000000000
--- a/src/gui/platforms/s60/qfontengine_s60.cpp
+++ /dev/null
@@ -1,569 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfontengine_s60_p.h"
-#include "qtextengine_p.h"
-#include "qendian.h"
-#include "qglobal.h"
-#include <private/qapplication_p.h>
-#include "qimage.h"
-#include <private/qt_s60_p.h>
-#include <private/qpixmap_s60_p.h>
-
-#include <e32base.h>
-#include <e32std.h>
-#include <eikenv.h>
-#include <gdi.h>
-#if defined(Q_SYMBIAN_HAS_GLYPHOUTLINE_API)
-#include <graphics/gdi/gdiplatapi.h>
-#endif // Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-
-// Replication of TGetFontTableParam & friends.
-// There is unfortunately no compile time flag like SYMBIAN_FONT_TABLE_API
-// that would help us to only replicate these things for Symbian versions
-// that do not yet have the font table Api. Symbian's public SDK does
-// generally not define any usable macros.
-class QSymbianTGetFontTableParam
-{
-public:
- TUint32 iTag;
- TAny *iContent;
- TInt iLength;
-};
-const TUid QSymbianKFontGetFontTable = {0x102872C1};
-const TUid QSymbianKFontReleaseFontTable = {0x2002AC24};
-
-QT_BEGIN_NAMESPACE
-
-QSymbianTypeFaceExtras::QSymbianTypeFaceExtras(CFont* cFont, COpenFont *openFont)
- : m_cFont(cFont)
- , m_symbolCMap(false)
- , m_openFont(openFont)
-{
- if (!symbianFontTableApiAvailable()) {
- TAny *trueTypeExtension = NULL;
- m_openFont->ExtendedInterface(KUidOpenFontTrueTypeExtension, trueTypeExtension);
- m_trueTypeExtension = static_cast<MOpenFontTrueTypeExtension*>(trueTypeExtension);
- Q_ASSERT(m_trueTypeExtension);
- }
-}
-
-QSymbianTypeFaceExtras::~QSymbianTypeFaceExtras()
-{
- if (symbianFontTableApiAvailable())
- S60->screenDevice()->ReleaseFont(m_cFont);
-}
-
-QByteArray QSymbianTypeFaceExtras::getSfntTable(uint tag) const
-{
- if (symbianFontTableApiAvailable()) {
- QSymbianTGetFontTableParam fontTableParams = { tag, 0, 0 };
- if (m_cFont->ExtendedFunction(QSymbianKFontGetFontTable, &fontTableParams) == KErrNone) {
- const char* const fontTableContent =
- static_cast<const char *>(fontTableParams.iContent);
- const QByteArray fontTable(fontTableContent, fontTableParams.iLength);
- m_cFont->ExtendedFunction(QSymbianKFontReleaseFontTable, &fontTableParams);
- return fontTable;
- }
- return QByteArray();
- } else {
- Q_ASSERT(m_trueTypeExtension->HasTrueTypeTable(tag));
- TInt error = KErrNone;
- TInt tableByteLength = 0;
- TAny *table = m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength);
- Q_CHECK_PTR(table);
- const QByteArray result(static_cast<const char*>(table), tableByteLength);
- m_trueTypeExtension->ReleaseTrueTypeTable(table);
- return result;
- }
-}
-
-bool QSymbianTypeFaceExtras::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
- bool result = true;
- if (symbianFontTableApiAvailable()) {
- QSymbianTGetFontTableParam fontTableParams = { tag, 0, 0 };
- if (m_cFont->ExtendedFunction(QSymbianKFontGetFontTable, &fontTableParams) == KErrNone) {
- if (*length > 0 && *length < fontTableParams.iLength) {
- result = false; // Caller did not allocate enough memory
- } else {
- *length = fontTableParams.iLength;
- if (buffer)
- memcpy(buffer, fontTableParams.iContent, fontTableParams.iLength);
- }
- m_cFont->ExtendedFunction(QSymbianKFontReleaseFontTable, &fontTableParams);
- } else {
- result = false;
- }
- } else {
- if (!m_trueTypeExtension->HasTrueTypeTable(tag))
- return false;
-
- TInt error = KErrNone;
- TInt tableByteLength;
- TAny *table = m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength);
- Q_CHECK_PTR(table);
-
- if (error != KErrNone) {
- return false;
- } else if (*length > 0 && *length < tableByteLength) {
- result = false; // Caller did not allocate enough memory
- } else {
- *length = tableByteLength;
- if (buffer)
- memcpy(buffer, table, tableByteLength);
- }
-
- m_trueTypeExtension->ReleaseTrueTypeTable(table);
- }
- return result;
-}
-
-const uchar *QSymbianTypeFaceExtras::cmap() const
-{
- if (m_cmapTable.isNull()) {
- const QByteArray cmapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p'));
- int size = 0;
- const uchar *cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>
- (cmapTable.constData()), cmapTable.size(), &m_symbolCMap, &size);
- m_cmapTable = QByteArray(reinterpret_cast<const char *>(cmap), size);
- }
- return reinterpret_cast<const uchar *>(m_cmapTable.constData());
-}
-
-bool QSymbianTypeFaceExtras::isSymbolCMap() const
-{
- return m_symbolCMap;
-}
-
-CFont *QSymbianTypeFaceExtras::fontOwner() const
-{
- return m_cFont;
-}
-
-QFixed QSymbianTypeFaceExtras::unitsPerEm() const
-{
- if (m_unitsPerEm.value() != 0)
- return m_unitsPerEm;
- const QByteArray head = getSfntTable(MAKE_TAG('h', 'e', 'a', 'd'));
- const int unitsPerEmOffset = 18;
- if (head.size() > unitsPerEmOffset + sizeof(quint16)) {
- const uchar* tableData = reinterpret_cast<const uchar*>(head.constData());
- const uchar* unitsPerEm = tableData + unitsPerEmOffset;
- m_unitsPerEm = qFromBigEndian<quint16>(unitsPerEm);
- } else {
- // Bitmap font? Corrupt font?
- // We return -1 and let the QFontEngineS60 return the pixel size.
- m_unitsPerEm = -1;
- }
- return m_unitsPerEm;
-}
-
-bool QSymbianTypeFaceExtras::symbianFontTableApiAvailable()
-{
- enum FontTableApiAvailability {
- Unknown,
- Available,
- Unavailable
- };
- static FontTableApiAvailability availability =
- QSysInfo::symbianVersion() < QSysInfo::SV_SF_3 ?
- Unavailable : Unknown;
- if (availability == Unknown) {
- // Actually, we should ask CFeatureDiscovery::IsFeatureSupportedL()
- // with FfFontTable here. But since at the time of writing, the
- // FfFontTable flag check either gave false positives or false
- // negatives. Here comes an implicit check via CFont::ExtendedFunction.
- QSymbianTGetFontTableParam fontTableParams = {
- MAKE_TAG('O', 'S', '/', '2'), 0, 0 };
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
- CFont *font;
- const TInt getFontErr = S60->screenDevice()->GetNearestFontInTwips(font, TFontSpec());
- Q_ASSERT(getFontErr == KErrNone);
- if (font->ExtendedFunction(QSymbianKFontGetFontTable, &fontTableParams) == KErrNone) {
- font->ExtendedFunction(QSymbianKFontReleaseFontTable, &fontTableParams);
- availability = Available;
- } else {
- availability = Unavailable;
- }
- S60->screenDevice()->ReleaseFont(font);
- lock.relock();
- }
- return availability == Available;
-}
-
-// duplicated from qfontengine_xyz.cpp
-static inline unsigned int getChar(const QChar *str, int &i, const int len)
-{
- unsigned int uc = str[i].unicode();
- if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
- uint low = str[i+1].unicode();
- if (low >= 0xdc00 && low < 0xe000) {
- uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
- ++i;
- }
- }
- return uc;
-}
-
-extern QString qt_symbian_fontNameWithAppFontMarker(const QString &fontName); // qfontdatabase_s60.cpp
-
-CFont *QFontEngineS60::fontWithSize(qreal size) const
-{
- CFont *result = 0;
- const QString family = qt_symbian_fontNameWithAppFontMarker(QFontEngine::fontDef.family);
- TFontSpec fontSpec(qt_QString2TPtrC(family), TInt(size));
- fontSpec.iFontStyle.SetBitmapType(EAntiAliasedGlyphBitmap);
- fontSpec.iFontStyle.SetPosture(QFontEngine::fontDef.style == QFont::StyleNormal?EPostureUpright:EPostureItalic);
- fontSpec.iFontStyle.SetStrokeWeight(QFontEngine::fontDef.weight > QFont::Normal?EStrokeWeightBold:EStrokeWeightNormal);
- const TInt errorCode = S60->screenDevice()->GetNearestFontToDesignHeightInPixels(result, fontSpec);
- Q_ASSERT(result && (errorCode == 0));
- return result;
-}
-
-void QFontEngineS60::setFontScale(qreal scale)
-{
- if (qFuzzyCompare(scale, qreal(1))) {
- if (!m_originalFont)
- m_originalFont = fontWithSize(m_originalFontSizeInPixels);
- m_activeFont = m_originalFont;
- } else {
- const qreal scaledFontSizeInPixels = m_originalFontSizeInPixels * scale;
- if (!m_scaledFont ||
- (TInt(scaledFontSizeInPixels) != TInt(m_scaledFontSizeInPixels))) {
- releaseFont(m_scaledFont);
- m_scaledFontSizeInPixels = scaledFontSizeInPixels;
- m_scaledFont = fontWithSize(m_scaledFontSizeInPixels);
- }
- m_activeFont = m_scaledFont;
- }
-}
-
-void QFontEngineS60::releaseFont(CFont *&font)
-{
- if (font) {
- S60->screenDevice()->ReleaseFont(font);
- font = 0;
- }
-}
-
-QFontEngineS60::QFontEngineS60(const QFontDef &request, const QSymbianTypeFaceExtras *extras)
- : m_extras(extras)
- , m_originalFont(0)
- , m_originalFontSizeInPixels((request.pixelSize >= 0)?
- request.pixelSize:pointsToPixels(request.pointSize))
- , m_scaledFont(0)
- , m_scaledFontSizeInPixels(0)
- , m_activeFont(0)
-{
- QFontEngine::fontDef = request;
- setFontScale(1.0);
- cache_cost = sizeof(QFontEngineS60);
-}
-
-QFontEngineS60::~QFontEngineS60()
-{
- releaseFont(m_originalFont);
- releaseFont(m_scaledFont);
-}
-
-QFixed QFontEngineS60::emSquareSize() const
-{
- const QFixed unitsPerEm = m_extras->unitsPerEm();
- return unitsPerEm.toInt() == -1 ?
- QFixed::fromReal(m_originalFontSizeInPixels) : unitsPerEm;
-}
-
-bool QFontEngineS60::stringToCMap(const QChar *characters, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- if (*nglyphs < len) {
- *nglyphs = len;
- return false;
- }
-
- HB_Glyph *g = glyphs->glyphs;
- const unsigned char* cmap = m_extras->cmap();
- const bool isRtl = (flags & QTextEngine::RightToLeft);
- for (int i = 0; i < len; ++i) {
- const unsigned int uc = getChar(characters, i, len);
- *g++ = QFontEngine::getTrueTypeGlyphIndex(cmap,
- (isRtl && !m_extras->isSymbolCMap()) ? QChar::mirroredChar(uc) : uc);
- }
-
- glyphs->numGlyphs = g - glyphs->glyphs;
- *nglyphs = glyphs->numGlyphs;
-
- if (flags & QTextEngine::GlyphIndicesOnly)
- return true;
-
- recalcAdvances(glyphs, flags);
- return true;
-}
-
-void QFontEngineS60::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
- Q_UNUSED(flags);
- TOpenFontCharMetrics metrics;
- const TUint8 *glyphBitmapBytes;
- TSize glyphBitmapSize;
- for (int i = 0; i < glyphs->numGlyphs; i++) {
- getCharacterData(glyphs->glyphs[i], metrics, glyphBitmapBytes, glyphBitmapSize);
- glyphs->advances_x[i] = metrics.HorizAdvance();
- glyphs->advances_y[i] = 0;
- }
-}
-
-#ifdef Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-static bool parseGlyphPathData(const char *dataStr, const char *dataEnd, QPainterPath &path,
- qreal fontPixelSize, const QPointF &offset, bool hinted);
-#endif //Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-
-void QFontEngineS60::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions,
- int nglyphs, QPainterPath *path,
- QTextItem::RenderFlags flags)
-{
-#ifdef Q_SYMBIAN_HAS_GLYPHOUTLINE_API
- Q_UNUSED(flags)
- RGlyphOutlineIterator iterator;
- const TInt error = iterator.Open(*m_activeFont, glyphs, nglyphs);
- if (KErrNone != error)
- return;
- const qreal fontSizeInPixels = qreal(m_activeFont->HeightInPixels());
- int count = 0;
- do {
- const TUint8* outlineUint8 = iterator.Outline();
- const char* const outlineChar = reinterpret_cast<const char*>(outlineUint8);
- const char* const outlineEnd = outlineChar + iterator.OutlineLength();
- parseGlyphPathData(outlineChar, outlineEnd, *path, fontSizeInPixels,
- positions[count++].toPointF(), false);
- } while(KErrNone == iterator.Next() && count <= nglyphs);
- iterator.Close();
-#else // Q_SYMBIAN_HAS_GLYPHOUTLINE_API
- QFontEngine::addGlyphsToPath(glyphs, positions, nglyphs, path, flags);
-#endif //Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-}
-
-QImage QFontEngineS60::alphaMapForGlyph(glyph_t glyph)
-{
- // Note: On some Symbian versions (apparently <= Symbian^1), this
- // function will return gray values 0x00, 0x10 ... 0xe0, 0xf0 due
- // to a bug. The glyphs are nowhere perfectly opaque.
- // This has been fixed for Symbian^3.
-
- TOpenFontCharMetrics metrics;
- const TUint8 *glyphBitmapBytes;
- TSize glyphBitmapSize;
- getCharacterData(glyph, metrics, glyphBitmapBytes, glyphBitmapSize);
- QImage result(glyphBitmapBytes, glyphBitmapSize.iWidth, glyphBitmapSize.iHeight, glyphBitmapSize.iWidth, QImage::Format_Indexed8);
- result.setColorTable(grayPalette());
- return result;
-}
-
-glyph_metrics_t QFontEngineS60::boundingBox(const QGlyphLayout &glyphs)
-{
- if (glyphs.numGlyphs == 0)
- return glyph_metrics_t();
-
- QFixed w = 0;
- for (int i = 0; i < glyphs.numGlyphs; ++i)
- w += glyphs.effectiveAdvance(i);
-
- return glyph_metrics_t(0, -ascent(), w - lastRightBearing(glyphs), ascent()+descent()+1, w, 0);
-}
-
-glyph_metrics_t QFontEngineS60::boundingBox_const(glyph_t glyph) const
-{
- TOpenFontCharMetrics metrics;
- const TUint8 *glyphBitmapBytes;
- TSize glyphBitmapSize;
- getCharacterData(glyph, metrics, glyphBitmapBytes, glyphBitmapSize);
- const glyph_metrics_t result(
- metrics.HorizBearingX(),
- -metrics.HorizBearingY(),
- metrics.Width(),
- metrics.Height(),
- metrics.HorizAdvance(),
- 0
- );
- return result;
-}
-
-glyph_metrics_t QFontEngineS60::boundingBox(glyph_t glyph)
-{
- return boundingBox_const(glyph);
-}
-
-QFixed QFontEngineS60::ascent() const
-{
- // Workaround for QTBUG-8013
- // Stroke based fonts may return an incorrect FontMaxAscent of 0.
- const QFixed ascent = m_originalFont->FontMaxAscent();
- return (ascent > 0) ? ascent : QFixed::fromReal(m_originalFontSizeInPixels) - descent();
-}
-
-QFixed QFontEngineS60::descent() const
-{
- return m_originalFont->FontMaxDescent();
-}
-
-QFixed QFontEngineS60::leading() const
-{
- return 0;
-}
-
-qreal QFontEngineS60::maxCharWidth() const
-{
- return m_originalFont->MaxCharWidthInPixels();
-}
-
-const char *QFontEngineS60::name() const
-{
- return "QFontEngineS60";
-}
-
-bool QFontEngineS60::canRender(const QChar *string, int len)
-{
- const unsigned char *cmap = m_extras->cmap();
- for (int i = 0; i < len; ++i) {
- const unsigned int uc = getChar(string, i, len);
- if (QFontEngine::getTrueTypeGlyphIndex(cmap, uc) == 0)
- return false;
- }
- return true;
-}
-
-QByteArray QFontEngineS60::getSfntTable(uint tag) const
-{
- return m_extras->getSfntTable(tag);
-}
-
-bool QFontEngineS60::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
- return m_extras->getSfntTableData(tag, buffer, length);
-}
-
-QFontEngine::Type QFontEngineS60::type() const
-{
- return QFontEngine::S60FontEngine;
-}
-
-void QFontEngineS60::getCharacterData(glyph_t glyph, TOpenFontCharMetrics& metrics, const TUint8*& bitmap, TSize& bitmapSize) const
-{
- // Setting the most significant bit tells GetCharacterData
- // that 'code' is a Glyph ID, rather than a UTF-16 value
- const TUint specialCode = (TUint)glyph | 0x80000000;
-
- const CFont::TCharacterDataAvailability availability =
- m_activeFont->GetCharacterData(specialCode, metrics, bitmap, bitmapSize);
- const glyph_t fallbackGlyph = '?';
- if (availability != CFont::EAllCharacterData) {
- const CFont::TCharacterDataAvailability fallbackAvailability =
- m_activeFont->GetCharacterData(fallbackGlyph, metrics, bitmap, bitmapSize);
- Q_ASSERT(fallbackAvailability == CFont::EAllCharacterData);
- }
-}
-
-#ifdef Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-static inline void skipSpacesAndComma(const char* &str, const char* const strEnd)
-{
- while (str <= strEnd && (*str == ' ' || *str == ','))
- ++str;
-}
-
-static bool parseGlyphPathData(const char *svgPath, const char *svgPathEnd, QPainterPath &path,
- qreal fontPixelSize, const QPointF &offset, bool hinted)
-{
- Q_UNUSED(hinted)
- QPointF p1, p2, firstSubPathPoint;
- qreal *elementValues[] =
- {&p1.rx(), &p1.ry(), &p2.rx(), &p2.ry()};
- const int unitsPerEm = 2048; // See: http://en.wikipedia.org/wiki/Em_%28typography%29
- const qreal resizeFactor = fontPixelSize / unitsPerEm;
-
- while (svgPath < svgPathEnd) {
- skipSpacesAndComma(svgPath, svgPathEnd);
- const char pathElem = *svgPath++;
- skipSpacesAndComma(svgPath, svgPathEnd);
-
- if (pathElem != 'Z') {
- char *endStr = 0;
- int elementValuesCount = 0;
- for (int i = 0; i < 4; ++i) { // 4 = size of elementValues[]
- qreal coordinateValue = strtod(svgPath, &endStr);
- if (svgPath == endStr)
- break;
- if (i % 2) // Flip vertically
- coordinateValue = -coordinateValue;
- *elementValues[i] = coordinateValue * resizeFactor;
- elementValuesCount++;
- svgPath = endStr;
- skipSpacesAndComma(svgPath, svgPathEnd);
- }
- p1 += offset;
- if (elementValuesCount == 2)
- p2 = firstSubPathPoint;
- else
- p2 += offset;
- }
-
- switch (pathElem) {
- case 'M':
- firstSubPathPoint = p1;
- path.moveTo(p1);
- break;
- case 'Z':
- path.closeSubpath();
- break;
- case 'L':
- path.lineTo(p1);
- break;
- case 'Q':
- path.quadTo(p1, p2);
- break;
- default:
- return false;
- }
- }
- return true;
-}
-#endif // Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qfontengine_s60_p.h b/src/gui/platforms/s60/qfontengine_s60_p.h
deleted file mode 100644
index c0eeef5264..0000000000
--- a/src/gui/platforms/s60/qfontengine_s60_p.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTENGINE_S60_P_H
-#define QFONTENGINE_S60_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qconfig.h"
-#include <private/qfontengine_p.h>
-#include "qsize.h"
-#include <openfont.h>
-
-// The glyph outline code is intentionally disabled. It will be reactivated as
-// soon as the glyph outline API is backported from Symbian(^4) to Symbian(^3).
-#if 0
-#define Q_SYMBIAN_HAS_GLYPHOUTLINE_API
-#endif
-
-class CFont;
-
-QT_BEGIN_NAMESPACE
-
-// ..gives us access to truetype tables
-class QSymbianTypeFaceExtras
-{
-public:
- QSymbianTypeFaceExtras(CFont* cFont, COpenFont *openFont = 0);
- ~QSymbianTypeFaceExtras();
-
- QByteArray getSfntTable(uint tag) const;
- bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
- const uchar *cmap() const;
- CFont *fontOwner() const;
- bool isSymbolCMap() const;
- QFixed unitsPerEm() const;
- static bool symbianFontTableApiAvailable();
-
-private:
- CFont* m_cFont;
- mutable bool m_symbolCMap;
- mutable QByteArray m_cmapTable;
- mutable QFixed m_unitsPerEm;
-
- // m_openFont and m_openFont are used if Symbian does not provide
- // the Font Table API
- COpenFont *m_openFont;
- mutable MOpenFontTrueTypeExtension *m_trueTypeExtension;
-};
-
-class QFontEngineS60 : public QFontEngine
-{
-public:
- QFontEngineS60(const QFontDef &fontDef, const QSymbianTypeFaceExtras *extras);
- ~QFontEngineS60();
-
- QFixed emSquareSize() const;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
- void recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const;
-
- void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags flags);
-
- QImage alphaMapForGlyph(glyph_t glyph);
-
- glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- glyph_metrics_t boundingBox_const(glyph_t glyph) const; // Const correctnes quirk.
- glyph_metrics_t boundingBox(glyph_t glyph);
-
- QFixed ascent() const;
- QFixed descent() const;
- QFixed leading() const;
- qreal maxCharWidth() const;
- qreal minLeftBearing() const { return 0; }
- qreal minRightBearing() const { return 0; }
-
- QByteArray getSfntTable(uint tag) const;
- bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
-
- static qreal pixelsToPoints(qreal pixels, Qt::Orientation orientation = Qt::Horizontal);
- static qreal pointsToPixels(qreal points, Qt::Orientation orientation = Qt::Horizontal);
-
- const char *name() const;
-
- bool canRender(const QChar *string, int len);
-
- Type type() const;
-
- void getCharacterData(glyph_t glyph, TOpenFontCharMetrics& metrics, const TUint8*& bitmap, TSize& bitmapSize) const;
- void setFontScale(qreal scale);
-
-private:
- friend class QFontPrivate;
- friend class QSymbianVGFontGlyphCache;
-
- QFixed glyphAdvance(HB_Glyph glyph) const;
- CFont *fontWithSize(qreal size) const;
- static void releaseFont(CFont *&font);
-
- const QSymbianTypeFaceExtras *m_extras;
- CFont* m_originalFont;
- const qreal m_originalFontSizeInPixels;
- CFont* m_scaledFont;
- qreal m_scaledFontSizeInPixels;
- CFont* m_activeFont;
-};
-
-class QFontEngineMultiS60 : public QFontEngineMulti
-{
-public:
- QFontEngineMultiS60(QFontEngine *first, int script, const QStringList &fallbackFamilies);
- void loadEngine(int at);
-
- int m_script;
- QStringList m_fallbackFamilies;
-};
-
-QT_END_NAMESPACE
-
-#endif // QFONTENGINE_S60_P_H
diff --git a/src/gui/platforms/s60/qkeymapper_s60.cpp b/src/gui/platforms/s60/qkeymapper_s60.cpp
deleted file mode 100644
index 08cfae0d2d..0000000000
--- a/src/gui/platforms/s60/qkeymapper_s60.cpp
+++ /dev/null
@@ -1,258 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qkeymapper_p.h"
-#include <private/qcore_symbian_p.h>
-#include <e32keys.h>
-#include <e32cmn.h>
-#include <centralrepository.h>
-#include <biditext.h>
-
-QT_BEGIN_NAMESPACE
-
-QKeyMapperPrivate::QKeyMapperPrivate()
-{
-}
-
-QKeyMapperPrivate::~QKeyMapperPrivate()
-{
-}
-
-QList<int> QKeyMapperPrivate::possibleKeys(QKeyEvent * /* e */)
-{
- QList<int> result;
- return result;
-}
-
-void QKeyMapperPrivate::clearMappings()
-{
- // stub
-}
-
-QString QKeyMapperPrivate::translateKeyEvent(int keySym, Qt::KeyboardModifiers /* modifiers */)
-{
- if (keySym >= Qt::Key_Escape) {
- switch (keySym) {
- case Qt::Key_Tab:
- return QString(QChar('\t'));
- case Qt::Key_Return: // fall through
- case Qt::Key_Enter:
- return QString(QChar('\r'));
- default:
- return QString();
- }
- }
-
- // Symbian doesn't actually use modifiers, but gives us the character code directly.
-
- return QString(QChar(keySym));
-}
-
-#include <e32keys.h>
-struct KeyMapping{
- TKeyCode s60KeyCode;
- TStdScanCode s60ScanCode;
- Qt::Key qtKey;
-};
-
-using namespace Qt;
-
-static const KeyMapping keyMapping[] = {
- {EKeyBackspace, EStdKeyBackspace, Key_Backspace},
- {EKeyTab, EStdKeyTab, Key_Tab},
- {EKeyEnter, EStdKeyEnter, Key_Enter},
- {EKeyEscape, EStdKeyEscape, Key_Escape},
- {EKeySpace, EStdKeySpace, Key_Space},
- {EKeyDelete, EStdKeyDelete, Key_Delete},
- {EKeyPrintScreen, EStdKeyPrintScreen, Key_SysReq},
- {EKeyPause, EStdKeyPause, Key_Pause},
- {EKeyHome, EStdKeyHome, Key_Home},
- {EKeyEnd, EStdKeyEnd, Key_End},
- {EKeyPageUp, EStdKeyPageUp, Key_PageUp},
- {EKeyPageDown, EStdKeyPageDown, Key_PageDown},
- {EKeyInsert, EStdKeyInsert, Key_Insert},
- {EKeyLeftArrow, EStdKeyLeftArrow, Key_Left},
- {EKeyRightArrow, EStdKeyRightArrow, Key_Right},
- {EKeyUpArrow, EStdKeyUpArrow, Key_Up},
- {EKeyDownArrow, EStdKeyDownArrow, Key_Down},
- {EKeyLeftShift, EStdKeyLeftShift, Key_Shift},
- {EKeyRightShift, EStdKeyRightShift, Key_Shift},
- {EKeyLeftAlt, EStdKeyLeftAlt, Key_Alt},
- {EKeyRightAlt, EStdKeyRightAlt, Key_AltGr},
- {EKeyLeftCtrl, EStdKeyLeftCtrl, Key_Control},
- {EKeyRightCtrl, EStdKeyRightCtrl, Key_Control},
- {EKeyLeftFunc, EStdKeyLeftFunc, Key_Super_L},
- {EKeyRightFunc, EStdKeyRightFunc, Key_Super_R},
- {EKeyCapsLock, EStdKeyCapsLock, Key_CapsLock},
- {EKeyNumLock, EStdKeyNumLock, Key_NumLock},
- {EKeyScrollLock, EStdKeyScrollLock, Key_ScrollLock},
- {EKeyF1, EStdKeyF1, Key_F1},
- {EKeyF2, EStdKeyF2, Key_F2},
- {EKeyF3, EStdKeyF3, Key_F3},
- {EKeyF4, EStdKeyF4, Key_F4},
- {EKeyF5, EStdKeyF5, Key_F5},
- {EKeyF6, EStdKeyF6, Key_F6},
- {EKeyF7, EStdKeyF7, Key_F7},
- {EKeyF8, EStdKeyF8, Key_F8},
- {EKeyF9, EStdKeyF9, Key_F9},
- {EKeyF10, EStdKeyF10, Key_F10},
- {EKeyF11, EStdKeyF11, Key_F11},
- {EKeyF12, EStdKeyF12, Key_F12},
- {EKeyF13, EStdKeyF13, Key_F13},
- {EKeyF14, EStdKeyF14, Key_F14},
- {EKeyF15, EStdKeyF15, Key_F15},
- {EKeyF16, EStdKeyF16, Key_F16},
- {EKeyF17, EStdKeyF17, Key_F17},
- {EKeyF18, EStdKeyF18, Key_F18},
- {EKeyF19, EStdKeyF19, Key_F19},
- {EKeyF20, EStdKeyF20, Key_F20},
- {EKeyF21, EStdKeyF21, Key_F21},
- {EKeyF22, EStdKeyF22, Key_F22},
- {EKeyF23, EStdKeyF23, Key_F23},
- {EKeyF24, EStdKeyF24, Key_F24},
- {EKeyOff, EStdKeyOff, Key_PowerOff},
-// {EKeyMenu, EStdKeyMenu, Key_Menu}, // Menu is EKeyApplication0
- {EKeyHelp, EStdKeyHelp, Key_Help},
- {EKeyDial, EStdKeyDial, Key_Call},
- {EKeyIncVolume, EStdKeyIncVolume, Key_VolumeUp},
- {EKeyDecVolume, EStdKeyDecVolume, Key_VolumeDown},
- {EKeyDevice0, EStdKeyDevice0, Key_Context1}, // Found by manual testing.
- {EKeyDevice1, EStdKeyDevice1, Key_Context2}, // Found by manual testing.
- {EKeyDevice3, EStdKeyDevice3, Key_Select},
- {EKeyDevice7, EStdKeyDevice7, Key_Camera},
- {EKeyApplication0, EStdKeyApplication0, Key_Menu}, // Found by manual testing.
- {EKeyApplication1, EStdKeyApplication1, Key_Launch1}, // Found by manual testing.
- {EKeyApplication2, EStdKeyApplication2, Key_MediaPlay}, // Found by manual testing.
- {EKeyApplication3, EStdKeyApplication3, Key_MediaStop}, // Found by manual testing.
- {EKeyApplication4, EStdKeyApplication4, Key_MediaNext}, // Found by manual testing.
- {EKeyApplication5, EStdKeyApplication5, Key_MediaPrevious}, // Found by manual testing.
- {EKeyApplication6, EStdKeyApplication6, Key_Launch6},
- {EKeyApplication7, EStdKeyApplication7, Key_Launch7},
- {EKeyApplication8, EStdKeyApplication8, Key_Launch8},
- {EKeyApplication9, EStdKeyApplication9, Key_Launch9},
- {EKeyApplicationA, EStdKeyApplicationA, Key_LaunchA},
- {EKeyApplicationB, EStdKeyApplicationB, Key_LaunchB},
- {EKeyApplicationC, EStdKeyApplicationC, Key_LaunchC},
- {EKeyApplicationD, EStdKeyApplicationD, Key_LaunchD},
- {EKeyApplicationE, EStdKeyApplicationE, Key_LaunchE},
- {EKeyApplicationF, EStdKeyApplicationF, Key_LaunchF},
- {EKeyApplication19, EStdKeyApplication19, Key_CameraFocus},
- {EKeyYes, EStdKeyYes, Key_Yes},
- {EKeyNo, EStdKeyNo, Key_No},
- {TKeyCode(0), TStdScanCode(0), Qt::Key(0)}
-};
-
-int QKeyMapperPrivate::mapS60KeyToQt(TUint s60key)
-{
- int res = Qt::Key_unknown;
- for (int i = 0; keyMapping[i].s60KeyCode != 0; i++) {
- if (keyMapping[i].s60KeyCode == s60key) {
- res = keyMapping[i].qtKey;
- break;
- }
- }
- return res;
-}
-
-int QKeyMapperPrivate::mapS60ScanCodesToQt(TUint s60scanCode)
-{
- int res = Qt::Key_unknown;
- for (int i = 0; keyMapping[i].s60KeyCode != 0; i++) {
- if (keyMapping[i].s60ScanCode == s60scanCode) {
- res = keyMapping[i].qtKey;
- break;
- }
- }
- return res;
-}
-
-int QKeyMapperPrivate::mapQtToS60Key(int qtKey)
-{
- int res = KErrUnknown;
- for (int i = 0; keyMapping[i].s60KeyCode != 0; i++) {
- if (keyMapping[i].qtKey == qtKey) {
- res = keyMapping[i].s60KeyCode;
- break;
- }
- }
- return res;
-}
-
-int QKeyMapperPrivate::mapQtToS60ScanCodes(int qtKey)
-{
- int res = KErrUnknown;
- for (int i = 0; keyMapping[i].s60KeyCode != 0; i++) {
- if (keyMapping[i].qtKey == qtKey) {
- res = keyMapping[i].s60ScanCode;
- break;
- }
- }
- return res;
-}
-
-void QKeyMapperPrivate::updateInputLanguage()
-{
-#ifdef Q_WS_S60
- TInt err;
- CRepository *repo;
- const TUid KCRUidAknFep = TUid::Uid(0x101F876D);
- const TUint32 KAknFepInputTxtLang = 0x00000005;
- TRAP(err, repo = CRepository::NewL(KCRUidAknFep));
- if (err != KErrNone)
- return;
-
- TInt symbianLang;
- err = repo->Get(KAknFepInputTxtLang, symbianLang);
- delete repo;
- if (err != KErrNone)
- return;
-
- QString qtLang = QString::fromAscii(qt_symbianLocaleName(symbianLang));
- keyboardInputLocale = QLocale(qtLang);
- keyboardInputDirection = (TBidiText::ScriptDirectionality(TLanguage(symbianLang)) == TBidiText::ERightToLeft)
- ? Qt::RightToLeft : Qt::LeftToRight;
-#else
- keyboardInputLocale = QLocale();
- keyboardInputDirection = Qt::LeftToRight;
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qpaintengine_s60.cpp b/src/gui/platforms/s60/qpaintengine_s60.cpp
deleted file mode 100644
index ca303be03d..0000000000
--- a/src/gui/platforms/s60/qpaintengine_s60.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qpaintengine_s60_p.h>
-#include <private/qpixmap_s60_p.h>
-#include <private/qt_s60_p.h>
-#include <private/qvolatileimage_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QS60PaintEnginePrivate : public QRasterPaintEnginePrivate
-{
-public:
- QS60PaintEnginePrivate() {}
-};
-
-QS60PaintEngine::QS60PaintEngine(QPaintDevice *device, QS60PixmapData *data)
- : QRasterPaintEngine(*(new QS60PaintEnginePrivate), device), pixmapData(data)
-{
-}
-
-bool QS60PaintEngine::begin(QPaintDevice *device)
-{
- Q_D(QS60PaintEngine);
-
- if (pixmapData->classId() == QPixmapData::RasterClass) {
- pixmapData->beginDataAccess();
- bool ret = QRasterPaintEngine::begin(device);
- // Make sure QPaintEngine::paintDevice() returns the proper device.
- // QRasterPaintEngine changes pdev to QImage in case of RasterClass QPixmapData
- // which is incorrect in Symbian.
- d->pdev = device;
- return ret;
- }
-
- return QRasterPaintEngine::begin(device);
-}
-
-bool QS60PaintEngine::end()
-{
- if (pixmapData->classId() == QPixmapData::RasterClass) {
- bool ret = QRasterPaintEngine::end();
- pixmapData->endDataAccess();
- return ret;
- }
- return QRasterPaintEngine::end();
-}
-
-void QS60PaintEngine::drawPixmap(const QPointF &p, const QPixmap &pm)
-{
- if (pm.pixmapData()->classId() == QPixmapData::RasterClass) {
- QS60PixmapData *srcData = static_cast<QS60PixmapData *>(pm.pixmapData());
- srcData->beginDataAccess();
- QRasterPaintEngine::drawPixmap(p, pm);
- srcData->endDataAccess();
- } else {
- void *nativeData = pm.pixmapData()->toNativeType(QPixmapData::VolatileImage);
- if (nativeData) {
- QVolatileImage *img = static_cast<QVolatileImage *>(nativeData);
- img->beginDataAccess();
- QRasterPaintEngine::drawImage(p, img->imageRef());
- img->endDataAccess(true);
- } else {
- QRasterPaintEngine::drawPixmap(p, pm);
- }
- }
-}
-
-void QS60PaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
-{
- if (pm.pixmapData()->classId() == QPixmapData::RasterClass) {
- QS60PixmapData *srcData = static_cast<QS60PixmapData *>(pm.pixmapData());
- srcData->beginDataAccess();
- QRasterPaintEngine::drawPixmap(r, pm, sr);
- srcData->endDataAccess();
- } else {
- void *nativeData = pm.pixmapData()->toNativeType(QPixmapData::VolatileImage);
- if (nativeData) {
- QVolatileImage *img = static_cast<QVolatileImage *>(nativeData);
- img->beginDataAccess();
- QRasterPaintEngine::drawImage(r, img->imageRef(), sr);
- img->endDataAccess(true);
- } else {
- QRasterPaintEngine::drawPixmap(r, pm, sr);
- }
- }
-}
-
-void QS60PaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &sr)
-{
- if (pm.pixmapData()->classId() == QPixmapData::RasterClass) {
- QS60PixmapData *srcData = static_cast<QS60PixmapData *>(pm.pixmapData());
- srcData->beginDataAccess();
- QRasterPaintEngine::drawTiledPixmap(r, pm, sr);
- srcData->endDataAccess();
- } else {
- QRasterPaintEngine::drawTiledPixmap(r, pm, sr);
- }
-}
-
-void QS60PaintEngine::prepare(QImage *image)
-{
- QRasterBuffer *buffer = d_func()->rasterBuffer.data();
- if (buffer)
- buffer->prepare(image);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qpaintengine_s60_p.h b/src/gui/platforms/s60/qpaintengine_s60_p.h
deleted file mode 100644
index a62bdac97c..0000000000
--- a/src/gui/platforms/s60/qpaintengine_s60_p.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** 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 QPAINTENGINE_S60_P_H
-#define QPAINTENGINE_S60_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 "private/qpaintengine_raster_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QS60PaintEnginePrivate;
-class QS60PixmapData;
-
-class QS60PaintEngine : public QRasterPaintEngine
-{
- Q_DECLARE_PRIVATE(QS60PaintEngine)
-
-public:
- QS60PaintEngine(QPaintDevice *device, QS60PixmapData* data);
- bool begin(QPaintDevice *device);
- bool end();
-
- void drawPixmap(const QPointF &p, const QPixmap &pm);
- void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
- void drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &sr);
-
- void prepare(QImage* image);
-
-private:
- QS60PixmapData *pixmapData;
-};
-
-QT_END_NAMESPACE
-
-#endif // QPAINTENGINE_S60_P_H
diff --git a/src/gui/platforms/s60/qpixmap_s60.cpp b/src/gui/platforms/s60/qpixmap_s60.cpp
deleted file mode 100644
index c8aa003ffa..0000000000
--- a/src/gui/platforms/s60/qpixmap_s60.cpp
+++ /dev/null
@@ -1,1040 +0,0 @@
-/****************************************************************************
-**
-** 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 <exception>
-#include <w32std.h>
-#include <fbs.h>
-
-#include <private/qapplication_p.h>
-#include <private/qgraphicssystem_p.h>
-#include <private/qt_s60_p.h>
-#include <private/qpaintengine_s60_p.h>
-#include <private/qfont_p.h>
-
-#include "qpixmap.h"
-#include "qpixmap_raster_p.h"
-#include <qwidget.h>
-#include "qpixmap_s60_p.h"
-#include "qnativeimage_p.h"
-#include "qbitmap.h"
-#include "qimage.h"
-#include "qimage_p.h"
-
-#include <fbs.h>
-
-QT_BEGIN_NAMESPACE
-
-const uchar qt_pixmap_bit_mask[] = { 0x01, 0x02, 0x04, 0x08,
- 0x10, 0x20, 0x40, 0x80 };
-
-static bool cleanup_function_registered = false;
-static QS60PixmapData *firstPixmap = 0;
-
-// static
-void QS60PixmapData::qt_symbian_register_pixmap(QS60PixmapData *pd)
-{
- if (!cleanup_function_registered) {
- qAddPostRoutine(qt_symbian_release_pixmaps);
- cleanup_function_registered = true;
- }
-
- pd->next = firstPixmap;
- pd->prev = 0;
- if (firstPixmap)
- firstPixmap->prev = pd;
- firstPixmap = pd;
-}
-
-// static
-void QS60PixmapData::qt_symbian_unregister_pixmap(QS60PixmapData *pd)
-{
- if (pd->next)
- pd->next->prev = pd->prev;
- if (pd->prev)
- pd->prev->next = pd->next;
- else
- firstPixmap = pd->next;
-}
-
-// static
-void QS60PixmapData::qt_symbian_release_pixmaps()
-{
- // Scan all QS60PixmapData objects in the system and destroy them.
- QS60PixmapData *pd = firstPixmap;
- while (pd != 0) {
- pd->release();
- pd = pd->next;
- }
-}
-
-/*
- \class QSymbianFbsClient
- \since 4.6
- \internal
-
- Symbian Font And Bitmap server client that is
- used to lock the global bitmap heap. Only used in
- S60 v3.1 and S60 v3.2.
-*/
-_LIT(KFBSERVLargeBitmapAccessName,"FbsLargeBitmapAccess");
-class QSymbianFbsClient
-{
-public:
-
- QSymbianFbsClient() : heapLocked(false)
- {
- heapLock.OpenGlobal(KFBSERVLargeBitmapAccessName);
- }
-
- ~QSymbianFbsClient()
- {
- heapLock.Close();
- }
-
- bool lockHeap()
- {
- bool wasLocked = heapLocked;
-
- if (heapLock.Handle() && !heapLocked) {
- heapLock.Wait();
- heapLocked = true;
- }
-
- return wasLocked;
- }
-
- bool unlockHeap()
- {
- bool wasLocked = heapLocked;
-
- if (heapLock.Handle() && heapLocked) {
- heapLock.Signal();
- heapLocked = false;
- }
-
- return wasLocked;
- }
-
-
-private:
-
- RMutex heapLock;
- bool heapLocked;
-};
-
-Q_GLOBAL_STATIC(QSymbianFbsClient, qt_symbianFbsClient);
-
-
-
-// QSymbianFbsHeapLock
-
-QSymbianFbsHeapLock::QSymbianFbsHeapLock(LockAction a)
-: action(a), wasLocked(false)
-{
- QSysInfo::SymbianVersion symbianVersion = QSysInfo::symbianVersion();
- if (symbianVersion == QSysInfo::SV_9_2 || symbianVersion == QSysInfo::SV_9_3)
- wasLocked = qt_symbianFbsClient()->unlockHeap();
-}
-
-QSymbianFbsHeapLock::~QSymbianFbsHeapLock()
-{
- // Do nothing
-}
-
-void QSymbianFbsHeapLock::relock()
-{
- QSysInfo::SymbianVersion symbianVersion = QSysInfo::symbianVersion();
- if (wasLocked && (symbianVersion == QSysInfo::SV_9_2 || symbianVersion == QSysInfo::SV_9_3))
- qt_symbianFbsClient()->lockHeap();
-}
-
-/*
- \class QSymbianBitmapDataAccess
- \since 4.6
- \internal
-
- Data access class that is used to locks/unlocks pixel data
- when drawing or modifying CFbsBitmap pixel data.
-*/
-class QSymbianBitmapDataAccess
-{
-public:
-
- static int heapRefCount;
- QSysInfo::SymbianVersion symbianVersion;
-
- explicit QSymbianBitmapDataAccess()
- {
- symbianVersion = QSysInfo::symbianVersion();
- };
-
- ~QSymbianBitmapDataAccess() {};
-
- inline void beginDataAccess(CFbsBitmap *bitmap)
- {
- if (symbianVersion == QSysInfo::SV_9_2) {
- if (heapRefCount == 0)
- qt_symbianFbsClient()->lockHeap();
- } else {
- bitmap->LockHeap(ETrue);
- }
-
- heapRefCount++;
- }
-
- inline void endDataAccess(CFbsBitmap *bitmap)
- {
- heapRefCount--;
-
- if (symbianVersion == QSysInfo::SV_9_2) {
- if (heapRefCount == 0)
- qt_symbianFbsClient()->unlockHeap();
- } else {
- bitmap->UnlockHeap(ETrue);
- }
- }
-};
-
-int QSymbianBitmapDataAccess::heapRefCount = 0;
-
-
-#define UPDATE_BUFFER() \
- { \
- beginDataAccess(); \
- endDataAccess(); \
-}
-
-
-static CFbsBitmap* createSymbianCFbsBitmap(const TSize& size, TDisplayMode mode)
-{
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
-
- CFbsBitmap* bitmap = 0;
- QT_TRAP_THROWING(bitmap = new (ELeave) CFbsBitmap);
-
- if (bitmap->Create(size, mode) != KErrNone) {
- delete bitmap;
- bitmap = 0;
- }
-
- lock.relock();
-
- return bitmap;
-}
-
-static CFbsBitmap* uncompress(CFbsBitmap* bitmap)
-{
- if(bitmap->IsCompressedInRAM()) {
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
-
- CFbsBitmap *uncompressed = 0;
- QT_TRAP_THROWING(uncompressed = new (ELeave) CFbsBitmap);
-
- if (uncompressed->Create(bitmap->SizeInPixels(), bitmap->DisplayMode()) != KErrNone) {
- delete bitmap;
- bitmap = 0;
- lock.relock();
-
- return bitmap;
- }
-
- lock.relock();
-
- CFbsBitmapDevice* bitmapDevice = 0;
- CFbsBitGc *bitmapGc = 0;
- QT_TRAP_THROWING(bitmapDevice = CFbsBitmapDevice::NewL(uncompressed));
- QT_TRAP_THROWING(bitmapGc = CFbsBitGc::NewL());
- bitmapGc->Activate(bitmapDevice);
-
- bitmapGc->BitBlt(TPoint(), bitmap);
-
- delete bitmapGc;
- delete bitmapDevice;
-
- return uncompressed;
- } else {
- return bitmap;
- }
-}
-
-QPixmap QPixmap::grabWindow(WId winId, int x, int y, int w, int h)
-{
- CWsScreenDevice* screenDevice = S60->screenDevice();
- TSize screenSize = screenDevice->SizeInPixels();
-
- TSize srcSize;
- // Find out if this is one of our windows.
- QSymbianControl *sControl;
- sControl = winId->MopGetObject(sControl);
- if (sControl && sControl->widget()->windowType() == Qt::Desktop) {
- // Grabbing desktop widget
- srcSize = screenSize;
- } else {
- TPoint relativePos = winId->PositionRelativeToScreen();
- x += relativePos.iX;
- y += relativePos.iY;
- srcSize = winId->Size();
- }
-
- TRect srcRect(TPoint(x, y), srcSize);
- // Clip to the screen
- srcRect.Intersection(TRect(screenSize));
-
- if (w > 0 && h > 0) {
- TRect subRect(TPoint(x, y), TSize(w, h));
- // Clip to the subRect
- srcRect.Intersection(subRect);
- }
-
- if (srcRect.IsEmpty())
- return QPixmap();
-
- CFbsBitmap* temporary = createSymbianCFbsBitmap(srcRect.Size(), screenDevice->DisplayMode());
-
- QPixmap pix;
-
- if (temporary && screenDevice->CopyScreenToBitmap(temporary, srcRect) == KErrNone) {
- pix = QPixmap::fromSymbianCFbsBitmap(temporary);
- }
-
- delete temporary;
- return pix;
-}
-
-/*!
- \fn CFbsBitmap *QPixmap::toSymbianCFbsBitmap() const
- \since 4.6
-
- Creates a \c CFbsBitmap that is equivalent to the QPixmap. Internally this
- function will try to duplicate the handle instead of copying the data,
- however in scenarios where this is not possible the data will be copied.
- If the creation fails or the pixmap is null, then this function returns 0.
-
- It is the caller's responsibility to release the \c CFbsBitmap data
- after use either by deleting the bitmap or calling \c Reset().
-
- \warning On S60 3.1 and S60 3.2, semi-transparent pixmaps are always copied
- and not duplicated.
- \warning This function is only available on Symbian OS.
-
- \sa fromSymbianCFbsBitmap()
-*/
-CFbsBitmap *QPixmap::toSymbianCFbsBitmap() const
-{
- QPixmapData *data = pixmapData();
- if (!data || data->isNull())
- return 0;
-
- return reinterpret_cast<CFbsBitmap*>(data->toNativeType(QPixmapData::FbsBitmap));
-}
-
-/*!
- \fn QPixmap QPixmap::fromSymbianCFbsBitmap(CFbsBitmap *bitmap)
- \since 4.6
-
- Creates a QPixmap from a \c CFbsBitmap \a bitmap. Internally this function
- will try to duplicate the bitmap handle instead of copying the data, however
- in scenarios where this is not possible the data will be copied.
- To be sure that QPixmap does not modify your original instance, you should
- make a copy of your \c CFbsBitmap before calling this function.
- If the CFbsBitmap is not valid this function will return a null QPixmap.
- For performance reasons it is recommended to use a \a bitmap with a display
- mode of EColor16MAP or EColor16MU whenever possible.
-
- \warning This function is only available on Symbian OS.
-
- \sa toSymbianCFbsBitmap(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
-*/
-QPixmap QPixmap::fromSymbianCFbsBitmap(CFbsBitmap *bitmap)
-{
- if (!bitmap)
- return QPixmap();
-
- QScopedPointer<QPixmapData> data(QPixmapData::create(0,0, QPixmapData::PixmapType));
- data->fromNativeType(reinterpret_cast<void*>(bitmap), QPixmapData::FbsBitmap);
- QPixmap pixmap(data.take());
- return pixmap;
-}
-
-QS60PixmapData::QS60PixmapData(PixelType type) : QRasterPixmapData(type),
- symbianBitmapDataAccess(new QSymbianBitmapDataAccess),
- cfbsBitmap(0),
- pengine(0),
- bytes(0),
- formatLocked(false),
- next(0),
- prev(0)
-{
- qt_symbian_register_pixmap(this);
-}
-
-QS60PixmapData::~QS60PixmapData()
-{
- release();
- delete symbianBitmapDataAccess;
- qt_symbian_unregister_pixmap(this);
-}
-
-void QS60PixmapData::resize(int width, int height)
-{
- if (width <= 0 || height <= 0) {
- w = width;
- h = height;
- is_null = true;
-
- release();
- return;
- } else if (!cfbsBitmap) {
- TDisplayMode mode;
- if (pixelType() == BitmapType)
- mode = EGray2;
- else
- mode = EColor16MU;
-
- CFbsBitmap* bitmap = createSymbianCFbsBitmap(TSize(width, height), mode);
- fromSymbianBitmap(bitmap);
- } else {
-
- TSize newSize(width, height);
-
- if(cfbsBitmap->SizeInPixels() != newSize) {
- cfbsBitmap->Resize(TSize(width, height));
- if(pengine) {
- delete pengine;
- pengine = 0;
- }
- }
-
- UPDATE_BUFFER();
- }
-}
-
-void QS60PixmapData::release()
-{
- if (cfbsBitmap) {
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
- delete cfbsBitmap;
- lock.relock();
- }
-
- delete pengine;
- image = QImage();
- cfbsBitmap = 0;
- pengine = 0;
- bytes = 0;
-}
-
-/*!
- * Takes ownership of bitmap. Used by window surface
- */
-void QS60PixmapData::fromSymbianBitmap(CFbsBitmap* bitmap, bool lockFormat)
-{
- Q_ASSERT(bitmap);
-
- release();
-
- cfbsBitmap = bitmap;
- formatLocked = lockFormat;
-
- setSerialNumber(cfbsBitmap->Handle());
-
- UPDATE_BUFFER();
-
- // Create default palette if needed
- if (cfbsBitmap->DisplayMode() == EGray2) {
- image.setColorCount(2);
- image.setColor(0, QColor(Qt::color0).rgba());
- image.setColor(1, QColor(Qt::color1).rgba());
-
- //Symbian thinks set pixels are white/transparent, Qt thinks they are foreground/solid
- //So invert mono bitmaps so that masks work correctly.
- image.invertPixels();
- } else if (cfbsBitmap->DisplayMode() == EGray256) {
- for (int i=0; i < 256; ++i)
- image.setColor(i, qRgb(i, i, i));
- } else if (cfbsBitmap->DisplayMode() == EColor256) {
- const TColor256Util *palette = TColor256Util::Default();
- for (int i=0; i < 256; ++i)
- image.setColor(i, (QRgb)(palette->Color256(i).Value()));
- }
-}
-
-QImage QS60PixmapData::toImage(const QRect &r) const
-{
- QS60PixmapData *that = const_cast<QS60PixmapData*>(this);
- that->beginDataAccess();
- QImage copy = that->image.copy(r);
- that->endDataAccess();
-
- return copy;
-}
-
-void QS60PixmapData::fromImage(const QImage &img, Qt::ImageConversionFlags flags)
-{
- release();
-
- QImage sourceImage;
-
- if (pixelType() == BitmapType) {
- sourceImage = img.convertToFormat(QImage::Format_MonoLSB);
- } else {
- if (img.depth() == 1) {
- sourceImage = img.hasAlphaChannel()
- ? img.convertToFormat(QImage::Format_ARGB32_Premultiplied)
- : img.convertToFormat(QImage::Format_RGB32);
- } else {
-
- QImage::Format opaqueFormat = QNativeImage::systemFormat();
- QImage::Format alphaFormat = QImage::Format_ARGB32_Premultiplied;
-
- if (!img.hasAlphaChannel()
- || ((flags & Qt::NoOpaqueDetection) == 0
- && !const_cast<QImage &>(img).data_ptr()->checkForAlphaPixels())) {
- sourceImage = img.convertToFormat(opaqueFormat);
- } else {
- sourceImage = img.convertToFormat(alphaFormat);
- }
- }
- }
-
-
- QImage::Format destFormat = sourceImage.format();
- TDisplayMode mode;
- switch (destFormat) {
- case QImage::Format_MonoLSB:
- mode = EGray2;
- break;
- case QImage::Format_RGB32:
- mode = EColor16MU;
- break;
- case QImage::Format_ARGB32_Premultiplied:
- if (S60->supportsPremultipliedAlpha) {
- mode = Q_SYMBIAN_ECOLOR16MAP;
- break;
- } else {
- destFormat = QImage::Format_ARGB32;
- }
- // Fall through intended
- case QImage::Format_ARGB32:
- mode = EColor16MA;
- break;
- case QImage::Format_Invalid:
- return;
- default:
- qWarning("Image format not supported: %d", image.format());
- return;
- }
-
- cfbsBitmap = createSymbianCFbsBitmap(TSize(sourceImage.width(), sourceImage.height()), mode);
- if (!cfbsBitmap) {
- qWarning("Could not create CFbsBitmap");
- release();
- return;
- }
-
- setSerialNumber(cfbsBitmap->Handle());
-
- const uchar *sptr = const_cast<const QImage &>(sourceImage).bits();
- symbianBitmapDataAccess->beginDataAccess(cfbsBitmap);
- uchar *dptr = (uchar*)cfbsBitmap->DataAddress();
- Mem::Copy(dptr, sptr, sourceImage.byteCount());
- symbianBitmapDataAccess->endDataAccess(cfbsBitmap);
-
- UPDATE_BUFFER();
-
- if (destFormat == QImage::Format_MonoLSB) {
- image.setColorCount(2);
- image.setColor(0, QColor(Qt::color0).rgba());
- image.setColor(1, QColor(Qt::color1).rgba());
- } else {
- image.setColorTable(sourceImage.colorTable());
- }
-}
-
-void QS60PixmapData::copy(const QPixmapData *data, const QRect &rect)
-{
- const QS60PixmapData *s60Data = static_cast<const QS60PixmapData*>(data);
- fromImage(s60Data->toImage(rect), Qt::AutoColor | Qt::OrderedAlphaDither);
-}
-
-bool QS60PixmapData::scroll(int dx, int dy, const QRect &rect)
-{
- beginDataAccess();
- bool res = QRasterPixmapData::scroll(dx, dy, rect);
- endDataAccess();
- return res;
-}
-
-int QS60PixmapData::metric(QPaintDevice::PaintDeviceMetric metric) const
-{
- if (!cfbsBitmap)
- return 0;
-
- switch (metric) {
- case QPaintDevice::PdmWidth:
- return cfbsBitmap->SizeInPixels().iWidth;
- case QPaintDevice::PdmHeight:
- return cfbsBitmap->SizeInPixels().iHeight;
- case QPaintDevice::PdmWidthMM:
- return qRound(cfbsBitmap->SizeInPixels().iWidth * 25.4 / qt_defaultDpiX());
- case QPaintDevice::PdmHeightMM:
- return qRound(cfbsBitmap->SizeInPixels().iHeight * 25.4 / qt_defaultDpiY());
- case QPaintDevice::PdmNumColors:
- return TDisplayModeUtils::NumDisplayModeColors(cfbsBitmap->DisplayMode());
- case QPaintDevice::PdmDpiX:
- case QPaintDevice::PdmPhysicalDpiX:
- return qt_defaultDpiX();
- case QPaintDevice::PdmDpiY:
- case QPaintDevice::PdmPhysicalDpiY:
- return qt_defaultDpiY();
- case QPaintDevice::PdmDepth:
- return TDisplayModeUtils::NumDisplayModeBitsPerPixel(cfbsBitmap->DisplayMode());
- default:
- qWarning("QPixmap::metric: Invalid metric command");
- }
- return 0;
-
-}
-
-void QS60PixmapData::fill(const QColor &color)
-{
- if (color.alpha() != 255) {
- QImage im(width(), height(), QImage::Format_ARGB32_Premultiplied);
- im.fill(PREMUL(color.rgba()));
- release();
- fromImage(im, Qt::AutoColor | Qt::OrderedAlphaDither);
- } else {
- beginDataAccess();
- QRasterPixmapData::fill(color);
- endDataAccess();
- }
-}
-
-void QS60PixmapData::setMask(const QBitmap &mask)
-{
- if (mask.size().isEmpty()) {
- if (image.depth() != 1) {
- QImage newImage = image.convertToFormat(QImage::Format_RGB32);
- release();
- fromImage(newImage, Qt::AutoColor | Qt::OrderedAlphaDither);
- }
- } else if (image.depth() == 1) {
- beginDataAccess();
- QRasterPixmapData::setMask(mask);
- endDataAccess();
- } else {
- const int w = image.width();
- const int h = image.height();
-
- const QImage imageMask = mask.toImage().convertToFormat(QImage::Format_MonoLSB);
- QImage newImage = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
- for (int y = 0; y < h; ++y) {
- const uchar *mscan = imageMask.scanLine(y);
- QRgb *tscan = (QRgb *)newImage.scanLine(y);
- for (int x = 0; x < w; ++x) {
- if (!(mscan[x>>3] & qt_pixmap_bit_mask[x&7]))
- tscan[x] = 0;
- }
- }
- release();
- fromImage(newImage, Qt::AutoColor | Qt::OrderedAlphaDither);
- }
-}
-
-void QS60PixmapData::setAlphaChannel(const QPixmap &alphaChannel)
-{
- QImage img(toImage());
- img.setAlphaChannel(alphaChannel.toImage());
- release();
- fromImage(img, Qt::OrderedDither | Qt::OrderedAlphaDither);
-}
-
-QImage QS60PixmapData::toImage() const
-{
- return toImage(QRect());
-}
-
-QPaintEngine* QS60PixmapData::paintEngine() const
-{
- if (!pengine) {
- QS60PixmapData *that = const_cast<QS60PixmapData*>(this);
- that->pengine = new QS60PaintEngine(&that->image, that);
- }
- return pengine;
-}
-
-void QS60PixmapData::beginDataAccess()
-{
- if(!cfbsBitmap)
- return;
-
- symbianBitmapDataAccess->beginDataAccess(cfbsBitmap);
-
- uchar* newBytes = (uchar*)cfbsBitmap->DataAddress();
-
- TSize size = cfbsBitmap->SizeInPixels();
-
- if (newBytes == bytes && image.width() == size.iWidth && image.height() == size.iHeight)
- return;
-
- bytes = newBytes;
- TDisplayMode mode = cfbsBitmap->DisplayMode();
- QImage::Format format = qt_TDisplayMode2Format(mode);
- // On S60 3.1, premultiplied alpha pixels are stored in a bitmap with 16MA type.
- // S60 window surface needs backing store pixmap for transparent window in ARGB32 format.
- // In that case formatLocked is true.
- if (!formatLocked && format == QImage::Format_ARGB32)
- format = QImage::Format_ARGB32_Premultiplied; // pixel data is actually in premultiplied format
-
- QVector<QRgb> savedColorTable;
- if (!image.isNull())
- savedColorTable = image.colorTable();
-
- image = QImage(bytes, size.iWidth, size.iHeight, format);
-
- // Restore the palette or create a default
- if (!savedColorTable.isEmpty()) {
- image.setColorTable(savedColorTable);
- }
-
- w = size.iWidth;
- h = size.iHeight;
- d = image.depth();
- is_null = (w <= 0 || h <= 0);
-
- if (pengine) {
- QS60PaintEngine *engine = static_cast<QS60PaintEngine *>(pengine);
- engine->prepare(&image);
- }
-}
-
-void QS60PixmapData::endDataAccess(bool readOnly) const
-{
- Q_UNUSED(readOnly);
-
- if(!cfbsBitmap)
- return;
-
- symbianBitmapDataAccess->endDataAccess(cfbsBitmap);
-}
-
-/*!
- \since 4.6
-
- Returns a QPixmap that wraps given \a sgImage graphics resource.
- The data should be valid even when original RSgImage handle has been
- closed.
-
- \warning This function is only available on Symbian OS.
-
- \sa toSymbianRSgImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
-*/
-
-QPixmap QPixmap::fromSymbianRSgImage(RSgImage *sgImage)
-{
- // It is expected that RSgImage will
- // CURRENTLY be used in conjuction with
- // OpenVG graphics system
- //
- // Surely things might change in future
-
- if (!sgImage)
- return QPixmap();
-
- QScopedPointer<QPixmapData> data(QPixmapData::create(0,0, QPixmapData::PixmapType));
- data->fromNativeType(reinterpret_cast<void*>(sgImage), QPixmapData::SgImage);
- QPixmap pixmap(data.take());
- return pixmap;
-}
-
-/*!
-\since 4.6
-
-Returns a \c RSgImage that is equivalent to the QPixmap by copying the data.
-
-It is the caller's responsibility to close/delete the \c RSgImage after use.
-
-\warning This function is only available on Symbian OS.
-
-\sa fromSymbianRSgImage()
-*/
-
-RSgImage *QPixmap::toSymbianRSgImage() const
-{
- // It is expected that RSgImage will
- // CURRENTLY be used in conjuction with
- // OpenVG graphics system
- //
- // Surely things might change in future
-
- if (isNull())
- return 0;
-
- RSgImage *sgImage = reinterpret_cast<RSgImage*>(pixmapData()->toNativeType(QPixmapData::SgImage));
-
- return sgImage;
-}
-
-void* QS60PixmapData::toNativeType(NativeType type)
-{
- if (type == QPixmapData::SgImage) {
- return 0;
- } else if (type == QPixmapData::FbsBitmap) {
-
- if (isNull() || !cfbsBitmap)
- return 0;
-
- bool convertToArgb32 = false;
- bool needsCopy = false;
-
- if (!(S60->supportsPremultipliedAlpha)) {
- // Convert argb32_premultiplied to argb32 since Symbian 9.2 does
- // not support premultipied format.
-
- if (image.format() == QImage::Format_ARGB32_Premultiplied) {
- needsCopy = true;
- convertToArgb32 = true;
- }
- }
-
- CFbsBitmap *bitmap = 0;
-
- TDisplayMode displayMode = cfbsBitmap->DisplayMode();
-
- if(displayMode == EGray2) {
- //Symbian thinks set pixels are white/transparent, Qt thinks they are foreground/solid
- //So invert mono bitmaps so that masks work correctly.
- beginDataAccess();
- image.invertPixels();
- endDataAccess();
- needsCopy = true;
- }
-
- if (needsCopy) {
- QImage source;
-
- if (convertToArgb32) {
- beginDataAccess();
- source = image.convertToFormat(QImage::Format_ARGB32);
- endDataAccess();
- displayMode = EColor16MA;
- } else {
- source = image;
- }
-
- CFbsBitmap *newBitmap = createSymbianCFbsBitmap(TSize(source.width(), source.height()), displayMode);
- const uchar *sptr = source.bits();
- symbianBitmapDataAccess->beginDataAccess(newBitmap);
-
- uchar *dptr = (uchar*)newBitmap->DataAddress();
- Mem::Copy(dptr, sptr, source.byteCount());
-
- symbianBitmapDataAccess->endDataAccess(newBitmap);
-
- bitmap = newBitmap;
- } else {
-
- QT_TRAP_THROWING(bitmap = new (ELeave) CFbsBitmap);
-
- TInt err = bitmap->Duplicate(cfbsBitmap->Handle());
- if (err != KErrNone) {
- qWarning("Could not duplicate CFbsBitmap");
- delete bitmap;
- bitmap = 0;
- }
- }
-
- if(displayMode == EGray2) {
- // restore pixels
- beginDataAccess();
- image.invertPixels();
- endDataAccess();
- }
-
- return reinterpret_cast<void*>(bitmap);
-
- }
-
- return 0;
-}
-
-void QS60PixmapData::fromNativeType(void* pixmap, NativeType nativeType)
-{
- if (nativeType == QPixmapData::SgImage) {
- return;
- } else if (nativeType == QPixmapData::FbsBitmap && pixmap) {
-
- CFbsBitmap *bitmap = reinterpret_cast<CFbsBitmap*>(pixmap);
-
- bool deleteSourceBitmap = false;
- bool needsCopy = false;
-
-#ifdef Q_SYMBIAN_HAS_EXTENDED_BITMAP_TYPE
-
- // Rasterize extended bitmaps
-
- TUid extendedBitmapType = bitmap->ExtendedBitmapType();
- if (extendedBitmapType != KNullUid) {
- CFbsBitmap *rasterBitmap = createSymbianCFbsBitmap(bitmap->SizeInPixels(), EColor16MA);
-
- CFbsBitmapDevice *rasterBitmapDev = 0;
- QT_TRAP_THROWING(rasterBitmapDev = CFbsBitmapDevice::NewL(rasterBitmap));
-
- CFbsBitGc *rasterBitmapGc = 0;
- TInt err = rasterBitmapDev->CreateContext(rasterBitmapGc);
- if (err != KErrNone) {
- delete rasterBitmap;
- delete rasterBitmapDev;
- rasterBitmapDev = 0;
- return;
- }
-
- rasterBitmapGc->BitBlt(TPoint( 0, 0), bitmap);
-
- bitmap = rasterBitmap;
-
- delete rasterBitmapDev;
- delete rasterBitmapGc;
-
- rasterBitmapDev = 0;
- rasterBitmapGc = 0;
-
- deleteSourceBitmap = true;
- }
-#endif
-
-
- deleteSourceBitmap = bitmap->IsCompressedInRAM();
- CFbsBitmap *sourceBitmap = uncompress(bitmap);
-
- TDisplayMode displayMode = sourceBitmap->DisplayMode();
- QImage::Format format = qt_TDisplayMode2Format(displayMode);
-
- QImage::Format opaqueFormat = QNativeImage::systemFormat();
- QImage::Format alphaFormat = QImage::Format_ARGB32_Premultiplied;
-
- if (format != opaqueFormat && format != alphaFormat && format != QImage::Format_MonoLSB)
- needsCopy = true;
-
-
- type = (format != QImage::Format_MonoLSB)
- ? QPixmapData::PixmapType
- : QPixmapData::BitmapType;
-
- if (needsCopy) {
-
- TSize size = sourceBitmap->SizeInPixels();
- int bytesPerLine = sourceBitmap->ScanLineLength(size.iWidth, displayMode);
-
- QSymbianBitmapDataAccess da;
- da.beginDataAccess(sourceBitmap);
- uchar *bytes = (uchar*)sourceBitmap->DataAddress();
- QImage img = QImage(bytes, size.iWidth, size.iHeight, bytesPerLine, format);
- img = img.copy();
- da.endDataAccess(sourceBitmap);
-
- if(displayMode == EGray2) {
- //Symbian thinks set pixels are white/transparent, Qt thinks they are foreground/solid
- //So invert mono bitmaps so that masks work correctly.
- img.invertPixels();
- } else if(displayMode == EColor16M) {
- img = img.rgbSwapped(); // EColor16M is BGR
- }
-
- fromImage(img, Qt::AutoColor);
-
- if(deleteSourceBitmap)
- delete sourceBitmap;
- } else {
- CFbsBitmap* duplicate = 0;
- QT_TRAP_THROWING(duplicate = new (ELeave) CFbsBitmap);
-
- TInt err = duplicate->Duplicate(sourceBitmap->Handle());
- if (err != KErrNone) {
- qWarning("Could not duplicate CFbsBitmap");
-
- if(deleteSourceBitmap)
- delete sourceBitmap;
-
- delete duplicate;
- return;
- }
-
- fromSymbianBitmap(duplicate);
-
- if(deleteSourceBitmap)
- delete sourceBitmap;
- }
- }
-}
-
-void QS60PixmapData::convertToDisplayMode(int mode)
-{
- const TDisplayMode displayMode = static_cast<TDisplayMode>(mode);
- if (!cfbsBitmap || cfbsBitmap->DisplayMode() == displayMode)
- return;
- if (image.depth() != TDisplayModeUtils::NumDisplayModeBitsPerPixel(displayMode)) {
- qWarning("Cannot convert display mode due to depth mismatch");
- return;
- }
-
- const TSize size = cfbsBitmap->SizeInPixels();
- QScopedPointer<CFbsBitmap> newBitmap(createSymbianCFbsBitmap(size, displayMode));
-
- const uchar *sptr = const_cast<const QImage &>(image).bits();
- symbianBitmapDataAccess->beginDataAccess(newBitmap.data());
- uchar *dptr = (uchar*)newBitmap->DataAddress();
- Mem::Copy(dptr, sptr, image.byteCount());
- symbianBitmapDataAccess->endDataAccess(newBitmap.data());
-
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
- delete cfbsBitmap;
- lock.relock();
- cfbsBitmap = newBitmap.take();
- setSerialNumber(cfbsBitmap->Handle());
- UPDATE_BUFFER();
-}
-
-QPixmapData *QS60PixmapData::createCompatiblePixmapData() const
-{
- return new QS60PixmapData(pixelType());
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qpixmap_s60_p.h b/src/gui/platforms/s60/qpixmap_s60_p.h
deleted file mode 100644
index c440bbc33a..0000000000
--- a/src/gui/platforms/s60/qpixmap_s60_p.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** 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 QPIXMAPDATA_S60_P_H
-#define QPIXMAPDATA_S60_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/private/qpixmap_raster_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class CFbsBitmap;
-class CFbsBitmapDevice;
-class CFbsBitGc;
-
-class QSymbianBitmapDataAccess;
-
-class QSymbianFbsHeapLock
-{
-public:
-
- enum LockAction {
- Unlock
- };
-
- explicit QSymbianFbsHeapLock(LockAction a);
- ~QSymbianFbsHeapLock();
- void relock();
-
-private:
-
- LockAction action;
- bool wasLocked;
-};
-
-class QS60PixmapData : public QRasterPixmapData
-{
-public:
- QS60PixmapData(PixelType type);
- ~QS60PixmapData();
-
- QPixmapData *createCompatiblePixmapData() const;
-
- void resize(int width, int height);
- void fromImage(const QImage &image, Qt::ImageConversionFlags flags);
- void copy(const QPixmapData *data, const QRect &rect);
- bool scroll(int dx, int dy, const QRect &rect);
-
- int metric(QPaintDevice::PaintDeviceMetric metric) const;
- void fill(const QColor &color);
- void setMask(const QBitmap &mask);
- void setAlphaChannel(const QPixmap &alphaChannel);
- QImage toImage() const;
- QPaintEngine* paintEngine() const;
-
- void beginDataAccess();
- void endDataAccess(bool readOnly=false) const;
-
- void* toNativeType(NativeType type);
- void fromNativeType(void* pixmap, NativeType type);
-
- void convertToDisplayMode(int mode);
-
-private:
- void release();
- void fromSymbianBitmap(CFbsBitmap* bitmap, bool lockFormat=false);
- QImage toImage(const QRect &r) const;
-
- QSymbianBitmapDataAccess *symbianBitmapDataAccess;
-
- CFbsBitmap *cfbsBitmap;
- QPaintEngine *pengine;
- uchar* bytes;
-
- bool formatLocked;
-
- QS60PixmapData *next;
- QS60PixmapData *prev;
-
- static void qt_symbian_register_pixmap(QS60PixmapData *pd);
- static void qt_symbian_unregister_pixmap(QS60PixmapData *pd);
- static void qt_symbian_release_pixmaps();
-
- friend class QPixmap;
- friend class QS60WindowSurface;
- friend class QS60PaintEngine;
- friend class QS60Data;
-};
-
-QT_END_NAMESPACE
-
-#endif // QPIXMAPDATA_S60_P_H
-
diff --git a/src/gui/platforms/s60/qregion_s60.cpp b/src/gui/platforms/s60/qregion_s60.cpp
deleted file mode 100644
index eafff1b965..0000000000
--- a/src/gui/platforms/s60/qregion_s60.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbitmap.h"
-#include "qbuffer.h"
-#include "qimage.h"
-#include "qpolygon.h"
-#include "qregion.h"
-
-QT_BEGIN_NAMESPACE
-
-QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0 };
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qsoftkeymanager_s60.cpp b/src/gui/platforms/s60/qsoftkeymanager_s60.cpp
deleted file mode 100644
index 79ed91af5b..0000000000
--- a/src/gui/platforms/s60/qsoftkeymanager_s60.cpp
+++ /dev/null
@@ -1,440 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qevent.h"
-#include "qbitmap.h"
-#include "qstyle.h"
-#include "qmenubar.h"
-#include "private/qt_s60_p.h"
-#include "private/qmenu_p.h"
-#include "private/qaction_p.h"
-#include "private/qsoftkeymanager_p.h"
-#include "private/qsoftkeymanager_s60_p.h"
-#include "private/qobject_p.h"
-#include <eiksoftkeyimage.h>
-#include <eikcmbut.h>
-
-#ifndef QT_NO_SOFTKEYMANAGER
-QT_BEGIN_NAMESPACE
-
-const int S60_COMMAND_START = 6000;
-const int LSK_POSITION = 0;
-const int MSK_POSITION = 3;
-const int RSK_POSITION = 2;
-
-QSoftKeyManagerPrivateS60::QSoftKeyManagerPrivateS60() : cbaHasImage(4) // 4 since MSK position index is 3
-{
- cachedCbaIconSize[0] = QSize(0,0);
- cachedCbaIconSize[1] = QSize(0,0);
- cachedCbaIconSize[2] = QSize(0,0);
- cachedCbaIconSize[3] = QSize(0,0);
-}
-
-bool QSoftKeyManagerPrivateS60::skipCbaUpdate()
-{
- // Lets not update softkeys if
- // 1. We don't have application panes, i.e. cba
- // 2. Our CBA is not active, i.e. S60 native dialog or menu with custom CBA is shown
- // 2.1. Except if thre is no current CBA at all and WindowSoftkeysRespondHint is set
-
- // Note: Cannot use IsDisplayingMenuOrDialog since CBA update can be triggered before
- // menu/dialog CBA is actually displayed i.e. it is being costructed.
- CEikButtonGroupContainer *appUiCba = S60->buttonGroupContainer();
- if (!appUiCba)
- return true;
- // CEikButtonGroupContainer::Current returns 0 if CBA is not visible at all
- CEikButtonGroupContainer *currentCba = CEikButtonGroupContainer::Current();
- // Check if softkey need to be update even they are not visible
- bool cbaRespondsWhenInvisible = false;
- QWidget *window = QApplication::activeWindow();
- if (window && (window->windowFlags() & Qt::WindowSoftkeysRespondHint))
- cbaRespondsWhenInvisible = true;
-
- if (QApplication::testAttribute(Qt::AA_S60DontConstructApplicationPanes)
- || (appUiCba != currentCba && !cbaRespondsWhenInvisible)) {
- return true;
- }
- return false;
-}
-
-void QSoftKeyManagerPrivateS60::ensureCbaVisibilityAndResponsiviness(CEikButtonGroupContainer &cba)
-{
- RDrawableWindow *cbaWindow = cba.DrawableWindow();
- Q_ASSERT_X(cbaWindow, Q_FUNC_INFO, "Native CBA does not have window!");
- // Make sure CBA is visible, i.e. CBA window is on top
- cbaWindow->SetOrdinalPosition(0);
- // Qt shares same CBA instance between top-level widgets,
- // make sure we are not faded by underlying window.
- cbaWindow->SetFaded(EFalse, RWindowTreeNode::EFadeIncludeChildren);
- // Modal dialogs capture pointer events, but shared cba instance
- // shall stay responsive. Raise pointer capture priority to keep
- // softkeys responsive in modal dialogs
- cbaWindow->SetPointerCapturePriority(1);
-}
-
-void QSoftKeyManagerPrivateS60::clearSoftkeys(CEikButtonGroupContainer &cba)
-{
-#ifdef SYMBIAN_VERSION_SYMBIAN3
- QT_TRAP_THROWING(
- //EAknSoftkeyEmpty is used, because using -1 adds softkeys without actions on Symbian3
- cba.SetCommandL(0, EAknSoftkeyEmpty, KNullDesC);
- cba.SetCommandL(2, EAknSoftkeyEmpty, KNullDesC);
- );
-#else
- QT_TRAP_THROWING(
- //Using -1 instead of EAknSoftkeyEmpty to avoid flickering.
- cba.SetCommandL(0, -1, KNullDesC);
- // TODO: Should we clear also middle SK?
- cba.SetCommandL(2, -1, KNullDesC);
- );
-#endif
- realSoftKeyActions.clear();
-}
-
-QString QSoftKeyManagerPrivateS60::softkeyText(QAction &softkeyAction)
-{
- // In S60 softkeys and menu items do not support key accelerators (i.e.
- // CTRL+X). Therefore, removing the accelerator characters from both softkey
- // and menu item texts.
- const int underlineShortCut = QApplication::style()->styleHint(QStyle::SH_UnderlineShortcut);
- QString iconText = softkeyAction.iconText();
- return underlineShortCut ? softkeyAction.text() : iconText;
-}
-
-QAction *QSoftKeyManagerPrivateS60::highestPrioritySoftkey(QAction::SoftKeyRole role)
-{
- QAction *ret = NULL;
- // Priority look up is two level
- // 1. First widget with softkeys always has highest priority
- for (int level = 0; !ret; level++) {
- // 2. Highest priority action within widget
- QList<QAction*> actions = requestedSoftKeyActions.values(level);
- if (actions.isEmpty())
- break;
- qSort(actions.begin(), actions.end(), QSoftKeyManagerPrivateS60::actionPriorityMoreThan);
- foreach (QAction *action, actions) {
- if (action->softKeyRole() == role) {
- ret = action;
- break;
- }
- }
- }
- return ret;
-}
-
-bool QSoftKeyManagerPrivateS60::actionPriorityMoreThan(const QAction *firstItem, const QAction *secondItem)
-{
- return firstItem->priority() > secondItem->priority();
-}
-
-void QSoftKeyManagerPrivateS60::setNativeSoftkey(CEikButtonGroupContainer &cba,
- TInt position, TInt command, const TDesC &text)
-{
- // Calling SetCommandL causes CBA redraw
- QT_TRAP_THROWING(cba.SetCommandL(position, command, text));
-}
-
-QPoint QSoftKeyManagerPrivateS60::softkeyIconPosition(int position, QSize sourceSize, QSize targetSize)
-{
- QPoint iconPosition(0,0);
- switch( AknLayoutUtils::CbaLocation() )
- {
- case AknLayoutUtils::EAknCbaLocationBottom:
- // RSK must be moved to right, LSK in on correct position by default
- if (position == RSK_POSITION)
- iconPosition.setX(targetSize.width() - sourceSize.width());
- break;
- case AknLayoutUtils::EAknCbaLocationRight:
- case AknLayoutUtils::EAknCbaLocationLeft:
- // Already in correct position
- default:
- break;
- }
-
- // Align horizontally to center
- iconPosition.setY((targetSize.height() - sourceSize.height()) >> 1);
- return iconPosition;
-}
-
-QPixmap QSoftKeyManagerPrivateS60::prepareSoftkeyPixmap(QPixmap src, int position, QSize targetSize)
-{
- QPixmap target(targetSize);
- target.fill(Qt::transparent);
- QPainter p;
- p.begin(&target);
- p.drawPixmap(softkeyIconPosition(position, src.size(), targetSize), src);
- p.end();
- return target;
-}
-
-bool QSoftKeyManagerPrivateS60::isOrientationLandscape()
-{
- // Hard to believe that there is no public API in S60 to
- // get current orientation. This workaround works with currently supported resolutions
- return S60->screenHeightInPixels < S60->screenWidthInPixels;
-}
-
-QSize QSoftKeyManagerPrivateS60::cbaIconSize(CEikButtonGroupContainer *cba, int position)
-{
-
- int index = position;
- index += isOrientationLandscape() ? 0 : 1;
- if(cachedCbaIconSize[index].isNull()) {
- // Only way I figured out to get CBA icon size without RnD SDK, was
- // to set some dummy icon to CBA first and then ask CBA button CCoeControl::Size()
- // The returned value is cached to avoid unnecessary icon setting every time.
- const bool left = (position == LSK_POSITION);
- if(position == LSK_POSITION || position == RSK_POSITION) {
- CEikImage* tmpImage = NULL;
- QT_TRAP_THROWING(tmpImage = new (ELeave) CEikImage);
- EikSoftkeyImage::SetImage(cba, *tmpImage, left); // Takes myimage ownership
- int command = S60_COMMAND_START + position;
- setNativeSoftkey(*cba, position, command, KNullDesC());
- cachedCbaIconSize[index] = qt_TSize2QSize(cba->ControlOrNull(command)->Size());
- EikSoftkeyImage::SetLabel(cba, left);
-
- if(cachedCbaIconSize[index] == QSize(138,72)) {
- // Hack for S60 5.0 (5800) landscape orientation, which return wrong icon size
- cachedCbaIconSize[index] = QSize(60,60);
- }
- }
- }
-
- return cachedCbaIconSize[index];
-}
-
-bool QSoftKeyManagerPrivateS60::setSoftkeyImage(CEikButtonGroupContainer *cba,
- QAction &action, int position)
-{
- bool ret = false;
-
- const bool left = (position == LSK_POSITION);
- if(position == LSK_POSITION || position == RSK_POSITION) {
- QIcon icon = action.icon();
- if (!icon.isNull()) {
- // Get size of CBA icon area based on button position and orientation
- QSize requiredIconSize = cbaIconSize(cba, position);
- // Get pixmap out of icon based on preferred size, the aspect ratio is kept
- QPixmap pmWihtAspectRatio = icon.pixmap(requiredIconSize);
- // Native softkeys require that pixmap size is exactly the same as requiredIconSize
- // prepareSoftkeyPixmap creates a new pixmap with requiredIconSize and blits the 'pmWihtAspectRatio'
- // to correct location of it
- QPixmap softkeyPixmap = prepareSoftkeyPixmap(pmWihtAspectRatio, position, requiredIconSize);
-
- QPixmap softkeyAlpha = softkeyPixmap.alphaChannel();
- // Alpha channel in 5.1 and older devices need to be inverted
- // TODO: Switch to use toSymbianCFbsBitmap with invert when available
- if(QSysInfo::s60Version() <= QSysInfo::SV_S60_5_1) {
- QImage alphaImage = softkeyAlpha.toImage();
- alphaImage.invertPixels();
- softkeyAlpha = QPixmap::fromImage(alphaImage);
- }
-
- CFbsBitmap* nBitmap = softkeyPixmap.toSymbianCFbsBitmap();
- CFbsBitmap* nMask = softkeyAlpha.toSymbianCFbsBitmap();
-
- CEikImage* myimage = new (ELeave) CEikImage;
- myimage->SetPicture( nBitmap, nMask ); // nBitmap and nMask ownership transferred
-
- EikSoftkeyImage::SetImage(cba, *myimage, left); // Takes myimage ownership
- cbaHasImage[position] = true;
- ret = true;
- } else {
- // Restore softkey to text based
- if (cbaHasImage[position]) {
- EikSoftkeyImage::SetLabel(cba, left);
- cbaHasImage[position] = false;
- }
- }
- }
- return ret;
-}
-
-bool QSoftKeyManagerPrivateS60::setSoftkey(CEikButtonGroupContainer &cba,
- QAction::SoftKeyRole role, int position)
-{
- QAction *action = highestPrioritySoftkey(role);
- if (action) {
- setSoftkeyImage(&cba, *action, position);
- QString text = softkeyText(*action);
- TPtrC nativeText = qt_QString2TPtrC(text);
- int command = S60_COMMAND_START + position;
-#ifdef SYMBIAN_VERSION_SYMBIAN3
- if (softKeyCommandActions.contains(action))
- command = softKeyCommandActions.value(action);
-#endif
- setNativeSoftkey(cba, position, command, nativeText);
- const bool dimmed = !action->isEnabled() && !QSoftKeyManager::isForceEnabledInSofkeys(action);
- cba.DimCommand(command, dimmed);
- realSoftKeyActions.insert(command, action);
- return true;
- }
- return false;
-}
-
-bool QSoftKeyManagerPrivateS60::setLeftSoftkey(CEikButtonGroupContainer &cba)
-{
- return setSoftkey(cba, QAction::PositiveSoftKey, LSK_POSITION);
-}
-
-bool QSoftKeyManagerPrivateS60::setMiddleSoftkey(CEikButtonGroupContainer &cba)
-{
- // Note: In order to get MSK working, application has to have EAknEnableMSK flag set
- // Currently it is not possible very easily)
- // For more information see: http://wiki.forum.nokia.com/index.php/Middle_softkey_usage
- return setSoftkey(cba, QAction::SelectSoftKey, MSK_POSITION);
-}
-
-bool QSoftKeyManagerPrivateS60::setRightSoftkey(CEikButtonGroupContainer &cba)
-{
- if (!setSoftkey(cba, QAction::NegativeSoftKey, RSK_POSITION)) {
- const Qt::WindowType windowType = initialSoftKeySource
- ? initialSoftKeySource->window()->windowType() : Qt::Window;
- if (windowType != Qt::Dialog && windowType != Qt::Popup) {
- QString text(QSoftKeyManager::tr("Exit"));
- TPtrC nativeText = qt_QString2TPtrC(text);
- if (cbaHasImage[RSK_POSITION]) {
- EikSoftkeyImage::SetLabel(&cba, false);
- cbaHasImage[RSK_POSITION] = false;
- }
- setNativeSoftkey(cba, RSK_POSITION, EAknSoftkeyExit, nativeText);
- cba.DimCommand(EAknSoftkeyExit, false);
- return true;
- }
- }
- return false;
-}
-
-void QSoftKeyManagerPrivateS60::setSoftkeys(CEikButtonGroupContainer &cba)
-{
- int requestedSoftkeyCount = requestedSoftKeyActions.count();
- const int maxSoftkeyCount = 2; // TODO: differs based on orientation ans S60 versions (some have MSK)
- if (requestedSoftkeyCount > maxSoftkeyCount) {
- // We have more softkeys than available slots
- // Put highest priority negative action to RSK and Options menu with rest of softkey actions to LSK
- // TODO: Build menu
- setLeftSoftkey(cba);
- if(AknLayoutUtils::MSKEnabled())
- setMiddleSoftkey(cba);
- setRightSoftkey(cba);
- } else {
- // We have less softkeys than available slots
- // Put softkeys to request slots based on role
- setLeftSoftkey(cba);
- if(AknLayoutUtils::MSKEnabled())
- setMiddleSoftkey(cba);
- setRightSoftkey(cba);
- }
-}
-
-void QSoftKeyManagerPrivateS60::updateSoftKeys_sys()
-{
- if (skipCbaUpdate())
- return;
-
- CEikButtonGroupContainer *nativeContainer = S60->buttonGroupContainer();
- Q_ASSERT_X(nativeContainer, Q_FUNC_INFO, "Native CBA does not exist!");
- ensureCbaVisibilityAndResponsiviness(*nativeContainer);
- clearSoftkeys(*nativeContainer);
- setSoftkeys(*nativeContainer);
-
- nativeContainer->DrawDeferred(); // 3.1 needs an extra invitation
-}
-
-static void resetMenuBeingConstructed(TAny* /*aAny*/)
-{
- S60->menuBeingConstructed = false;
-}
-
-void QSoftKeyManagerPrivateS60::tryDisplayMenuBarL()
-{
- CleanupStack::PushL(TCleanupItem(resetMenuBeingConstructed, NULL));
- S60->menuBeingConstructed = true;
- S60->menuBar()->TryDisplayMenuBarL();
- CleanupStack::PopAndDestroy(); // Reset menuBeingConstructed to false in all cases
-}
-
-bool QSoftKeyManagerPrivateS60::handleCommand(int command)
-{
- QAction *action = realSoftKeyActions.value(command);
- if (action) {
- bool property = QActionPrivate::get(action)->menuActionSoftkeys;
- if (property) {
- QT_TRAP_THROWING(tryDisplayMenuBarL());
- } else if (action->menu()) {
- // TODO: This is hack, in order to use exising QMenuBar implementation for Symbian
- // menubar needs to have widget to which it is associated. Since we want to associate
- // menubar to action (which is inherited from QObject), we create and associate QWidget
- // to action and pass that for QMenuBar. This associates the menubar to action, and we
- // can have own menubar for each action.
- QWidget *actionContainer = action->property("_q_action_widget").value<QWidget*>();
- if(!actionContainer) {
- actionContainer = new QWidget(action->parentWidget());
- QMenuBar *menuBar = new QMenuBar(actionContainer);
- foreach(QAction *menuAction, action->menu()->actions()) {
- QMenu *menu = menuAction->menu();
- if(menu)
- menuBar->addMenu(menu);
- else
- menuBar->addAction(menuAction);
- }
- QVariant v;
- v.setValue(actionContainer);
- action->setProperty("_q_action_widget", v);
- }
- qt_symbian_next_menu_from_action(actionContainer);
- QT_TRAP_THROWING(tryDisplayMenuBarL());
- }
-
- Q_ASSERT(action->softKeyRole() != QAction::NoSoftKey);
- QWidget *actionParent = action->parentWidget();
- Q_ASSERT_X(actionParent, Q_FUNC_INFO, "No parent set for softkey action!");
- if (actionParent->isEnabled()) {
- action->activate(QAction::Trigger);
- return true;
- }
- }
- return false;
-}
-
-QT_END_NAMESPACE
-#endif //QT_NO_SOFTKEYMANAGER
diff --git a/src/gui/platforms/s60/qsoftkeymanager_s60_p.h b/src/gui/platforms/s60/qsoftkeymanager_s60_p.h
deleted file mode 100644
index 9cb3787cb8..0000000000
--- a/src/gui/platforms/s60/qsoftkeymanager_s60_p.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** 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 QSOFTKEYMANAGER_S60_P_H
-#define QSOFTKEYMANAGER_S60_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qbitarray.h"
-#include "private/qobject_p.h"
-#include "private/qsoftkeymanager_common_p.h"
-
-QT_BEGIN_HEADER
-
-#ifndef QT_NO_SOFTKEYMANAGER
-
-QT_BEGIN_NAMESPACE
-
-class CEikButtonGroupContainer;
-class QAction;
-
-class QSoftKeyManagerPrivateS60 : public QSoftKeyManagerPrivate
-{
- Q_DECLARE_PUBLIC(QSoftKeyManager)
-
-public:
- QSoftKeyManagerPrivateS60();
-
-public:
- void updateSoftKeys_sys();
- bool handleCommand(int command);
-
-private:
- void tryDisplayMenuBarL();
- bool skipCbaUpdate();
- void ensureCbaVisibilityAndResponsiviness(CEikButtonGroupContainer &cba);
- void clearSoftkeys(CEikButtonGroupContainer &cba);
- QString softkeyText(QAction &softkeyAction);
- QAction *highestPrioritySoftkey(QAction::SoftKeyRole role);
- static bool actionPriorityMoreThan(const QAction* item1, const QAction* item2);
- void setNativeSoftkey(CEikButtonGroupContainer &cba, TInt position, TInt command, const TDesC& text);
- QPoint softkeyIconPosition(int position, QSize sourceSize, QSize targetSize);
- QPixmap prepareSoftkeyPixmap(QPixmap src, int position, QSize targetSize);
- bool isOrientationLandscape();
- QSize cbaIconSize(CEikButtonGroupContainer *cba, int position);
- bool setSoftkeyImage(CEikButtonGroupContainer *cba, QAction &action, int position);
- bool setSoftkey(CEikButtonGroupContainer &cba, QAction::SoftKeyRole role, int position);
- bool setLeftSoftkey(CEikButtonGroupContainer &cba);
- bool setMiddleSoftkey(CEikButtonGroupContainer &cba);
- bool setRightSoftkey(CEikButtonGroupContainer &cba);
- void setSoftkeys(CEikButtonGroupContainer &cba);
-
-private:
- QHash<int, QAction*> realSoftKeyActions;
- QSize cachedCbaIconSize[4];
- QBitArray cbaHasImage;
-};
-
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_SOFTKEYMANAGER
-
-QT_END_HEADER
-
-#endif // QSOFTKEYMANAGER_S60_P_H
diff --git a/src/gui/platforms/s60/qsound_s60.cpp b/src/gui/platforms/s60/qsound_s60.cpp
deleted file mode 100644
index acc5c2a56f..0000000000
--- a/src/gui/platforms/s60/qsound_s60.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_SOUND
-
-#include "qdir.h"
-#include "qapplication.h"
-#include "qsound.h"
-#include "qsound_p.h"
-#include "qfileinfo.h"
-#include <private/qcore_symbian_p.h>
-
-#include <e32std.h>
-#include <mdaaudiosampleplayer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QAuServerS60;
-
-class QAuBucketS60 : public QAuBucket, public MMdaAudioPlayerCallback
-{
-public:
- QAuBucketS60(QAuServerS60 *server, QSound *sound);
- ~QAuBucketS60();
-
- void play();
- void stop();
-
- inline QSound *sound() const { return m_sound; }
-
-public: // from MMdaAudioPlayerCallback
- void MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration);
- void MapcPlayComplete(TInt aError);
-
-private:
- QSound *m_sound;
- QAuServerS60 *m_server;
- bool m_prepared;
- bool m_playCalled;
- CMdaAudioPlayerUtility *m_playUtility;
-};
-
-
-class QAuServerS60 : public QAuServer
-{
-public:
- QAuServerS60(QObject *parent);
-
- void init(QSound *s)
- {
- QAuBucketS60 *bucket = new QAuBucketS60(this, s);
- setBucket(s, bucket);
- }
-
- void play(QSound *s)
- {
- bucket(s)->play();
- }
-
- void stop(QSound *s)
- {
- bucket(s)->stop();
- }
-
- bool okay() { return true; }
-
- void play(const QString& filename);
-
-protected:
- void playCompleted(QAuBucketS60 *bucket, int error);
-
-protected:
- QAuBucketS60 *bucket(QSound *s)
- {
- return (QAuBucketS60 *)QAuServer::bucket( s );
- }
-
- friend class QAuBucketS60;
-
- // static QSound::play(filename) cannot be stopped, meaning that playCompleted
- // will get always called and QSound gets removed form this list.
- QList<QSound *> staticPlayingSounds;
-};
-
-QAuServerS60::QAuServerS60(QObject *parent) :
- QAuServer(parent)
-{
- setObjectName(QLatin1String("QAuServerS60"));
-}
-
-void QAuServerS60::play(const QString& filename)
-{
- QSound *s = new QSound(filename);
- staticPlayingSounds.append(s);
- play(s);
-}
-
-void QAuServerS60::playCompleted(QAuBucketS60 *bucket, int error)
-{
- QSound *sound = bucket->sound();
- if (!error) {
- // We need to handle repeats by ourselves, since with Symbian API we don't
- // know how many loops have been played when user asks it
- if (decLoop(sound)) {
- play(sound);
- } else {
- if (staticPlayingSounds.removeAll(sound))
- delete sound;
- }
- } else {
- // We don't have a way to inform about errors -> just decrement loops
- // in order that QSound::isFinished will return true;
- while (decLoop(sound) > 0) {}
- if (staticPlayingSounds.removeAll(sound))
- delete sound;
- }
-}
-
-QAuServer *qt_new_audio_server()
-{
- return new QAuServerS60(qApp);
-}
-
-QAuBucketS60::QAuBucketS60(QAuServerS60 *server, QSound *sound)
- : m_sound(sound), m_server(server), m_prepared(false), m_playCalled(false)
-{
- QString filepath = QFileInfo(m_sound->fileName()).absoluteFilePath();
- filepath = QDir::toNativeSeparators(filepath);
- TPtrC filepathPtr(qt_QString2TPtrC(filepath));
- TRAPD(err, m_playUtility = CMdaAudioPlayerUtility::NewL(*this);
- m_playUtility->OpenFileL(filepathPtr));
- if (err) {
- m_server->playCompleted(this, err);
- }
-}
-
-void QAuBucketS60::play()
-{
- if (m_prepared) {
- // OpenFileL call is completed we can start playing immediately
- m_playUtility->Play();
- } else {
- m_playCalled = true;
- }
-
-}
-
-void QAuBucketS60::stop()
-{
- m_playCalled = false;
- m_playUtility->Stop();
-}
-
-void QAuBucketS60::MapcPlayComplete(TInt aError)
-{
- m_server->playCompleted(this, aError);
-}
-
-void QAuBucketS60::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& /*aDuration*/)
-{
- if (aError) {
- m_server->playCompleted(this, aError);
- } else {
- m_prepared = true;
- if (m_playCalled){
- play();
- }
- }
-}
-
-QAuBucketS60::~QAuBucketS60()
-{
- if (m_playUtility){
- m_playUtility->Stop();
- m_playUtility->Close();
- }
-
- delete m_playUtility;
-}
-
-
-#endif // QT_NO_SOUND
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/s60/qt_s60_p.h b/src/gui/platforms/s60/qt_s60_p.h
deleted file mode 100644
index 8aba53a168..0000000000
--- a/src/gui/platforms/s60/qt_s60_p.h
+++ /dev/null
@@ -1,625 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_S60_P_H
-#define QT_S60_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qwindowdefs.h"
-#include "private/qcore_symbian_p.h"
-#include "qhash.h"
-#include "qpoint.h"
-#include "QtGui/qfont.h"
-#include "QtGui/qimage.h"
-#include "QtGui/qevent.h"
-#include "qpointer.h"
-#include "qapplication.h"
-#include "qelapsedtimer.h"
-#include "QtCore/qthreadstorage.h"
-#include "qwidget_p.h"
-#include <w32std.h>
-#include <coecntrl.h>
-#include <eikenv.h>
-#include <eikappui.h>
-
-#ifdef Q_WS_S60
-#include <AknUtils.h> // AknLayoutUtils
-#include <avkon.hrh> // EEikStatusPaneUidTitle
-#include <akntitle.h> // CAknTitlePane
-#include <akncontext.h> // CAknContextPane
-#include <eikspane.h> // CEikStatusPane
-#include <AknPopupFader.h> // MAknFadedComponent and TAknPopupFader
-#include <gfxtranseffect/gfxtranseffect.h> // BeginFullScreen
-#ifdef QT_SYMBIAN_HAVE_AKNTRANSEFFECT_H
-#include <akntranseffect.h> // BeginFullScreen
-#endif
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// Application internal HandleResourceChangeL events,
-// system events seems to start with 0x10
-const TInt KInternalStatusPaneChange = 0x50000000;
-
-// For BeginFullScreen().
-const TUint KQtAppExitFlag = 0x400;
-
-static const int qt_symbian_max_screens = 4;
-
-//this macro exists because EColor16MAP enum value doesn't exist in Symbian OS 9.2
-#define Q_SYMBIAN_ECOLOR16MAP TDisplayMode(13)
-
-class Q_AUTOTEST_EXPORT QS60ThreadLocalData
-{
-public:
- QS60ThreadLocalData();
- ~QS60ThreadLocalData();
- bool usingCONEinstances;
- RWsSession wsSession;
- CWsScreenDevice *screenDevice;
-};
-
-class QS60Data
-{
-public:
- QS60Data();
- QThreadStorage<QS60ThreadLocalData *> tls;
- TUid uid;
- int screenDepth;
- QPoint lastCursorPos;
- QPoint lastPointerEventPos;
- QPointer<QWidget> lastPointerEventTarget;
- QPointer<QWidget> mousePressTarget;
- int screenWidthInPixels;
- int screenHeightInPixels;
- int screenWidthInTwips;
- int screenHeightInTwips;
- int defaultDpiX;
- int defaultDpiY;
- WId curWin;
- enum PressedKeys {
- Select = 0x1,
- Right = 0x2,
- Down = 0x4,
- Left = 0x8,
- Up = 0x10,
- LeftUp = 0x20,
- RightUp = 0x40,
- RightDown = 0x80,
- LeftDown = 0x100
- };
- int virtualMousePressedKeys; // of the above type, but avoids casting problems
- int virtualMouseAccelDX;
- int virtualMouseAccelDY;
- QElapsedTimer virtualMouseAccelTimeout;
- int virtualMouseMaxAccel;
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- int brokenPointerCursors : 1;
-#endif
- int hasTouchscreen : 1;
- int mouseInteractionEnabled : 1;
- int virtualMouseRequired : 1;
- int qtOwnsS60Environment : 1;
- int supportsPremultipliedAlpha : 1;
- int avkonComponentsSupportTransparency : 1;
- int menuBeingConstructed : 1;
- int orientationSet : 1;
- int partial_keyboard : 1;
- QApplication::QS60MainApplicationFactory s60ApplicationFactory; // typedef'ed pointer type
- QPointer<QWidget> splitViewLastWidget;
-
- static CEikButtonGroupContainer *cba;
-
- enum ScanCodeState {
- Unpressed,
- KeyDown,
- KeyDownAndKey
- };
- QHash<TInt, ScanCodeState> scanCodeStates;
-
- static inline void updateScreenSize();
- inline RWsSession& wsSession();
- static inline int screenCount();
- static inline RWindowGroup& windowGroup();
- static inline RWindowGroup& windowGroup(const QWidget *widget);
- static inline RWindowGroup& windowGroup(int screenNumber);
- inline CWsScreenDevice* screenDevice();
- inline CWsScreenDevice* screenDevice(const QWidget *widget);
- inline CWsScreenDevice* screenDevice(int screenNumber);
- static inline int screenNumberForWidget(const QWidget *widget);
- static inline CCoeAppUi* appUi();
- static inline CEikMenuBar* menuBar();
-#ifdef Q_WS_S60
- static inline CEikStatusPane* statusPane();
- static inline CCoeControl* statusPaneSubPane(TInt aPaneId);
- static inline CAknTitlePane* titlePane();
- static inline CAknContextPane* contextPane();
- static inline CEikButtonGroupContainer* buttonGroupContainer();
- static inline void setButtonGroupContainer(CEikButtonGroupContainer* newCba);
- static void setStatusPaneAndButtonGroupVisibility(bool statusPaneVisible, bool buttonGroupVisible);
- static bool setRecursiveDecorationsVisibility(QWidget *window, Qt::WindowStates newState);
-#endif
- static void controlVisibilityChanged(CCoeControl *control, bool visible);
-
-#ifdef Q_OS_SYMBIAN
- TTrapHandler *s60InstalledTrapHandler;
-#endif
-
- int screenWidthInPixelsForScreen[qt_symbian_max_screens];
- int screenHeightInPixelsForScreen[qt_symbian_max_screens];
- int screenWidthInTwipsForScreen[qt_symbian_max_screens];
- int screenHeightInTwipsForScreen[qt_symbian_max_screens];
-
- int nativeScreenWidthInPixels;
- int nativeScreenHeightInPixels;
-
- int beginFullScreenCalled : 1;
- int endFullScreenCalled : 1;
-};
-
-Q_AUTOTEST_EXPORT QS60Data* qGlobalS60Data();
-#define S60 qGlobalS60Data()
-
-class QAbstractLongTapObserver
-{
-public:
- virtual void HandleLongTapEventL( const TPoint& aPenEventLocation,
- const TPoint& aPenEventScreenLocation ) = 0;
-};
-class QLongTapTimer;
-
-
-class QSymbianControl : public CCoeControl, public QAbstractLongTapObserver
-#ifdef Q_WS_S60
-, public MAknFadedComponent, public MEikStatusPaneObserver
-#endif
-{
-public:
- DECLARE_TYPE_ID(0x51740000) // Fun fact: the two first values are "Qt" in ASCII.
-
-public:
- QSymbianControl(QWidget *w);
- void ConstructL(bool isWindowOwning = false, bool desktop = false);
- ~QSymbianControl();
- void HandleResourceChange(int resourceType);
- void HandlePointerEventL(const TPointerEvent& aPointerEvent);
- TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType);
-#if !defined(QT_NO_IM) && defined(Q_WS_S60)
- TCoeInputCapabilities InputCapabilities() const;
-#endif
- TTypeUid::Ptr MopSupplyObject(TTypeUid id);
-
- inline QWidget* widget() const { return qwidget; }
- void setWidget(QWidget *w);
- void sendInputEvent(QWidget *widget, QInputEvent *inputEvent);
- void setIgnoreFocusChanged(bool enabled) { m_ignoreFocusChanged = enabled; }
- void CancelLongTapTimer();
-
- void setFocusSafely(bool focus);
-
- bool isControlActive();
-
- void ensureFixNativeOrientation();
- QPoint translatePointForFixedNativeOrientation(const TPoint &pointerEventPos) const;
- TRect translateRectForFixedNativeOrientation(const TRect &controlRect) const;
-
-#ifdef Q_WS_S60
- void FadeBehindPopup(bool fade){ popupFader.FadeBehindPopup( this, this, fade); }
- void HandleStatusPaneSizeChange();
-
-protected: // from MAknFadedComponent
- TInt CountFadedComponents() {return 1;}
- CCoeControl* FadedComponent(TInt /*aIndex*/) {return this;}
-#else
- // #warning No fallback implementation for QSymbianControl::FadeBehindPopup
- void FadeBehindPopup(bool /*fade*/){ }
-#endif
-
-protected:
- void Draw(const TRect& aRect) const;
- void SizeChanged();
- void PositionChanged();
- void FocusChanged(TDrawNow aDrawNow);
-
-protected:
- void qwidgetResize_helper(const QSize &newSize);
-
-private:
- void HandlePointerEvent(const TPointerEvent& aPointerEvent);
- TKeyResponse OfferKeyEvent(const TKeyEvent& aKeyEvent,TEventCode aType);
- TKeyResponse sendSymbianKeyEvent(const TKeyEvent &keyEvent, QEvent::Type type);
- TKeyResponse sendKeyEvent(QWidget *widget, QKeyEvent *keyEvent);
- TKeyResponse handleVirtualMouse(const TKeyEvent& keyEvent,TEventCode type);
- bool sendMouseEvent(QWidget *widget, QMouseEvent *mEvent);
- void sendMouseEvent(
- QWidget *receiver,
- QEvent::Type type,
- const QPoint &globalPos,
- Qt::MouseButton button,
- Qt::KeyboardModifiers modifiers);
- void processTouchEvent(int pointerNumber, TPointerEvent::TType type, QPointF screenPos, qreal pressure);
- void HandleLongTapEventL( const TPoint& aPenEventLocation, const TPoint& aPenEventScreenLocation );
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- void translateAdvancedPointerEvent(const TAdvancedPointerEvent *event);
-#endif
- bool isSplitViewWidget(QWidget *widget);
-
-public:
- void handleClientAreaChange();
-
-private:
- static QSymbianControl *lastFocusedControl;
-
-private:
- QWidget *qwidget;
- QLongTapTimer* m_longTapDetector;
- QElapsedTimer m_doubleClickTimer;
- bool m_ignoreFocusChanged : 1;
- bool m_symbianPopupIsOpen : 1;
-
-#ifdef Q_WS_S60
- // Fader object used to fade everything except this menu and the CBA.
- TAknPopupFader popupFader;
-#endif
-
- bool m_inExternalScreenOverride : 1;
- bool m_lastStatusPaneVisibility : 1;
-};
-
-inline QS60Data::QS60Data()
-: uid(TUid::Null()),
- screenDepth(0),
- screenWidthInPixels(0),
- screenHeightInPixels(0),
- screenWidthInTwips(0),
- screenHeightInTwips(0),
- defaultDpiX(0),
- defaultDpiY(0),
- curWin(0),
- virtualMousePressedKeys(0),
- virtualMouseAccelDX(0),
- virtualMouseAccelDY(0),
- virtualMouseMaxAccel(0),
-#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
- brokenPointerCursors(0),
-#endif
- hasTouchscreen(0),
- mouseInteractionEnabled(0),
- virtualMouseRequired(0),
- qtOwnsS60Environment(0),
- supportsPremultipliedAlpha(0),
- avkonComponentsSupportTransparency(0),
- menuBeingConstructed(0),
- orientationSet(0),
- partial_keyboard(0),
- s60ApplicationFactory(0)
-#ifdef Q_OS_SYMBIAN
- ,s60InstalledTrapHandler(0)
-#endif
- ,beginFullScreenCalled(0),
- endFullScreenCalled(0)
-{
-}
-
-inline void QS60Data::updateScreenSize()
-{
- CWsScreenDevice *dev = S60->screenDevice();
- int screenModeCount = dev->NumScreenModes();
- int mode = dev->CurrentScreenMode();
- TPixelsTwipsAndRotation params;
- dev->GetScreenModeSizeAndRotation(mode, params);
- S60->screenWidthInPixels = params.iPixelSize.iWidth;
- S60->screenHeightInPixels = params.iPixelSize.iHeight;
- S60->screenWidthInTwips = params.iTwipsSize.iWidth;
- S60->screenHeightInTwips = params.iTwipsSize.iHeight;
-
- S60->virtualMouseMaxAccel = qMax(S60->screenHeightInPixels, S60->screenWidthInPixels) / 10;
-
- TReal inches = S60->screenHeightInTwips / (TReal)KTwipsPerInch;
- S60->defaultDpiY = S60->screenHeightInPixels / inches;
- inches = S60->screenWidthInTwips / (TReal)KTwipsPerInch;
- S60->defaultDpiX = S60->screenWidthInPixels / inches;
-
- int screens = S60->screenCount();
- for (int i = 0; i < screens; ++i) {
- CWsScreenDevice *dev = S60->screenDevice(i);
- mode = dev->CurrentScreenMode();
- dev->GetScreenModeSizeAndRotation(mode, params);
- S60->screenWidthInPixelsForScreen[i] = params.iPixelSize.iWidth;
- S60->screenHeightInPixelsForScreen[i] = params.iPixelSize.iHeight;
- S60->screenWidthInTwipsForScreen[i] = params.iTwipsSize.iWidth;
- S60->screenHeightInTwipsForScreen[i] = params.iTwipsSize.iHeight;
- }
-
- // Look for a screen mode with rotation 0
- // in order to decide what the native orientation is.
- for (mode = 0; mode < screenModeCount; ++mode) {
- TPixelsAndRotation sizeAndRotation;
- dev->GetScreenModeSizeAndRotation(mode, sizeAndRotation);
- if (sizeAndRotation.iRotation == CFbsBitGc::EGraphicsOrientationNormal) {
- S60->nativeScreenWidthInPixels = sizeAndRotation.iPixelSize.iWidth;
- S60->nativeScreenHeightInPixels = sizeAndRotation.iPixelSize.iHeight;
- break;
- }
- }
-}
-
-inline RWsSession& QS60Data::wsSession()
-{
- if(!tls.hasLocalData()) {
- tls.setLocalData(new QS60ThreadLocalData);
- }
- return tls.localData()->wsSession;
-}
-
-inline int QS60Data::screenCount()
-{
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- CCoeEnv *env = CCoeEnv::Static();
- if (env) {
- return qMin(env->WsSession().NumberOfScreens(), qt_symbian_max_screens);
- }
-#endif
- return 1;
-}
-
-inline RWindowGroup& QS60Data::windowGroup()
-{
- return CCoeEnv::Static()->RootWin();
-}
-
-inline RWindowGroup& QS60Data::windowGroup(const QWidget *widget)
-{
- return windowGroup(screenNumberForWidget(widget));
-}
-
-inline RWindowGroup& QS60Data::windowGroup(int screenNumber)
-{
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- RWindowGroup *wg = CCoeEnv::Static()->RootWin(screenNumber);
- return wg ? *wg : windowGroup();
-#else
- Q_UNUSED(screenNumber);
- return windowGroup();
-#endif
-}
-
-inline CWsScreenDevice* QS60Data::screenDevice()
-{
- if(!tls.hasLocalData()) {
- tls.setLocalData(new QS60ThreadLocalData);
- }
- return tls.localData()->screenDevice;
-}
-
-inline CWsScreenDevice* QS60Data::screenDevice(const QWidget *widget)
-{
- return screenDevice(screenNumberForWidget(widget));
-}
-
-inline CWsScreenDevice* QS60Data::screenDevice(int screenNumber)
-{
-#if defined(Q_SYMBIAN_SUPPORTS_MULTIPLE_SCREENS)
- CCoeEnv *env = CCoeEnv::Static();
- if (env) {
- CWsScreenDevice *dev = env->ScreenDevice(screenNumber);
- return dev ? dev : screenDevice();
- } else {
- return screenDevice();
- }
-#else
- return screenDevice();
-#endif
-}
-
-inline int QS60Data::screenNumberForWidget(const QWidget *widget)
-{
- if (!widget)
- return 0;
- const QWidget *w = widget;
- while (w->parentWidget())
- w = w->parentWidget();
- return qt_widget_private(const_cast<QWidget *>(w))->symbianScreenNumber;
-}
-
-inline CCoeAppUi* QS60Data::appUi()
-{
- return CCoeEnv::Static()-> AppUi();
-}
-
-inline CEikMenuBar* QS60Data::menuBar()
-{
- return CEikonEnv::Static()->AppUiFactory()->MenuBar();
-}
-
-#ifdef Q_WS_S60
-inline CEikStatusPane* QS60Data::statusPane()
-{
- return CEikonEnv::Static()->AppUiFactory()->StatusPane();
-}
-
-// Returns the application's status pane control, if not present returns NULL.
-inline CCoeControl* QS60Data::statusPaneSubPane( TInt aPaneId )
-{
- const TUid paneUid = { aPaneId };
- CEikStatusPane* statusPane = S60->statusPane();
- if (statusPane && statusPane->PaneCapabilities(paneUid).IsPresent()) {
- CCoeControl* control = NULL;
- // ControlL shouldn't leave because the pane is present
- TRAPD(err, control = statusPane->ControlL(paneUid));
- return err != KErrNone ? NULL : control;
- }
- return NULL;
-}
-
-// Returns the application's title pane, if not present returns NULL.
-inline CAknTitlePane* QS60Data::titlePane()
-{
- return static_cast<CAknTitlePane*>(S60->statusPaneSubPane(EEikStatusPaneUidTitle));
-}
-
-// Returns the application's title pane, if not present returns NULL.
-inline CAknContextPane* QS60Data::contextPane()
-{
- return static_cast<CAknContextPane*>(S60->statusPaneSubPane(EEikStatusPaneUidContext));
-}
-
-inline CEikButtonGroupContainer* QS60Data::buttonGroupContainer()
-{
- return QS60Data::cba;
-}
-
-inline void QS60Data::setButtonGroupContainer(CEikButtonGroupContainer *newCba)
-{
- QS60Data::cba = newCba;
-}
-#endif // Q_WS_S60
-
-static inline QFont qt_TFontSpec2QFontL(const TFontSpec &fontSpec)
-{
- return QFont(
- qt_TDesC2QString(fontSpec.iTypeface.iName),
- fontSpec.iHeight / KTwipsPerPoint,
- fontSpec.iFontStyle.StrokeWeight() == EStrokeWeightNormal ? QFont::Normal : QFont::Bold,
- fontSpec.iFontStyle.Posture() == EPostureItalic
- );
-}
-
-static inline QImage::Format qt_TDisplayMode2Format(TDisplayMode mode)
-{
- QImage::Format format;
- switch(mode) {
- case EGray2:
- format = QImage::Format_MonoLSB;
- break;
- case EColor256:
- case EGray256:
- format = QImage::Format_Indexed8;
- break;
- case EColor4K:
- format = QImage::Format_RGB444;
- break;
- case EColor64K:
- format = QImage::Format_RGB16;
- break;
- case EColor16M:
- format = QImage::Format_RGB888;
- break;
- case EColor16MU:
- format = QImage::Format_RGB32;
- break;
- case EColor16MA:
- format = QImage::Format_ARGB32;
- break;
- case Q_SYMBIAN_ECOLOR16MAP:
- format = QImage::Format_ARGB32_Premultiplied;
- break;
- default:
- format = QImage::Format_Invalid;
- break;
- }
- return format;
-}
-
-#ifndef QT_NO_CURSOR
-void qt_symbian_setWindowCursor(const QCursor &cursor, const CCoeControl* wid);
-void qt_symbian_setWindowGroupCursor(const QCursor &cursor, RWindowTreeNode &node);
-void qt_symbian_setGlobalCursor(const QCursor &cursor);
-void qt_symbian_set_cursor_visible(bool visible);
-bool qt_symbian_is_cursor_visible();
-#endif
-
-static inline bool qt_beginFullScreenEffect()
-{
-#if defined(Q_WS_S60) && defined(QT_SYMBIAN_HAVE_AKNTRANSEFFECT_H)
- // Only for post-S^3. On earlier versions the system transition effects
- // may not be able to capture the non-Avkon content, leading to confusing
- // looking effects, so just skip the whole thing.
- if (S60->beginFullScreenCalled || QSysInfo::s60Version() <= QSysInfo::SV_S60_5_2)
- return false;
- S60->beginFullScreenCalled = true;
- // For Avkon apps the app-exit effect is triggered from CAknAppUi::PrepareToExit().
- // That is good for Avkon apps, but in case of Qt the RWindows are destroyed earlier.
- // Therefore we call BeginFullScreen() ourselves.
- GfxTransEffect::BeginFullScreen(AknTransEffect::EApplicationExit,
- TRect(0, 0, 0, 0),
- AknTransEffect::EParameterType,
- AknTransEffect::GfxTransParam(S60->uid,
- AknTransEffect::TParameter::EAvkonCheck | KQtAppExitFlag));
- return true;
-#else
- return false;
-#endif
-}
-
-static inline void qt_abortFullScreenEffect()
-{
-#if defined(Q_WS_S60) && defined(QT_SYMBIAN_HAVE_AKNTRANSEFFECT_H)
- if (!S60->beginFullScreenCalled || QSysInfo::s60Version() <= QSysInfo::SV_S60_5_2)
- return;
- GfxTransEffect::AbortFullScreen();
- S60->beginFullScreenCalled = S60->endFullScreenCalled = false;
-#endif
-}
-
-static inline void qt_endFullScreenEffect()
-{
-#if defined(Q_WS_S60) && defined(QT_SYMBIAN_HAVE_AKNTRANSEFFECT_H)
- if (S60->endFullScreenCalled || QSysInfo::s60Version() <= QSysInfo::SV_S60_5_2)
- return;
- S60->endFullScreenCalled = true;
- GfxTransEffect::EndFullScreen();
-#endif
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_S60_P_H
diff --git a/src/gui/platforms/s60/qwidget_s60.cpp b/src/gui/platforms/s60/qwidget_s60.cpp
deleted file mode 100644
index e28a75a6ab..0000000000
--- a/src/gui/platforms/s60/qwidget_s60.cpp
+++ /dev/null
@@ -1,1450 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwidget_p.h"
-#include "qdesktopwidget.h"
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "private/qbackingstore_p.h"
-#include "qevent.h"
-#include "qt_s60_p.h"
-
-#include "qbitmap.h"
-#include "private/qwindowsurface_s60_p.h"
-
-#include <qinputcontext.h>
-
-#ifdef Q_WS_S60
-#include <aknappui.h>
-#include <eikbtgpc.h>
-#endif
-
-// This is necessary in order to be able to perform delayed invocation on slots
-// which take arguments of type WId. One example is
-// QWidgetPrivate::_q_delayedDestroy, which is used to delay destruction of
-// CCoeControl objects until after the CONE event handler has finished running.
-Q_DECLARE_METATYPE(WId)
-
-// Workaround for the fact that S60 SDKs 3.x do not contain the akntoolbar.h
-// header, even though the documentation says that it should be there, and indeed
-// it is present in the library.
-class CAknToolbar : public CAknControl,
- public MCoeControlObserver,
- public MCoeControlBackground,
- public MEikCommandObserver,
- public MAknFadedComponent
-{
-public:
- IMPORT_C void SetToolbarVisibility(const TBool visible);
-};
-
-QT_BEGIN_NAMESPACE
-
-extern bool qt_nograb();
-
-QWidget *QWidgetPrivate::mouseGrabber = 0;
-QWidget *QWidgetPrivate::keyboardGrabber = 0;
-CEikButtonGroupContainer *QS60Data::cba = 0;
-
-int qt_symbian_create_desktop_on_screen = -1;
-
-static bool isEqual(const QList<QAction*>& a, const QList<QAction*>& b)
-{
- if ( a.count() != b.count())
- return false;
- int index=0;
- while (index<a.count()) {
- if (a.at(index)->softKeyRole() != b.at(index)->softKeyRole())
- return false;
- if (a.at(index)->text().compare(b.at(index)->text())!=0)
- return false;
- index++;
- }
- return true;
-}
-
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &)
-{
- // Note: based on x11 implementation
-
- static const int XCOORD_MAX = 16383;
- static const int WRECT_MAX = 16383;
-
- Q_Q(QWidget);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- /*
- There are up to four different coordinate systems here:
- Qt coordinate system for this widget.
- Symbian coordinate system for this widget (relative to wrect).
- Qt coordinate system for parent
- Symbian coordinate system for parent (relative to parent's wrect).
- */
-
- QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
- QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
- QRect wrect;
- //xrect is the Symbian geometry of my widget. (starts out in parent's Qt coord sys, and ends up in parent's Symbian coord sys)
- QRect xrect = data.crect;
-
- const QWidget *const parent = q->parentWidget();
- QRect parentWRect = parent->data->wrect;
-
- if (parentWRect.isValid()) {
- // parent is clipped, and we have to clip to the same limit as parent
- if (!parentWRect.contains(xrect)) {
- xrect &= parentWRect;
- wrect = xrect;
- //translate from parent's to my Qt coord sys
- wrect.translate(-data.crect.topLeft());
- }
- //translate from parent's Qt coords to parent's X coords
- xrect.translate(-parentWRect.topLeft());
-
- } else {
- // parent is not clipped, we may or may not have to clip
-
- if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
- // This is where the main optimization is: we are already
- // clipped, and if our clip is still valid, we can just
- // move our window, and do not need to move or clip
- // children
-
- QRect vrect = xrect & parent->rect();
- vrect.translate(-data.crect.topLeft()); //the part of me that's visible through parent, in my Qt coords
- if (data.wrect.contains(vrect)) {
- xrect = data.wrect;
- xrect.translate(data.crect.topLeft());
- if (data.winid)
- data.winid->SetExtent(TPoint(xrect.x(), xrect.y()), TSize(xrect.width(), xrect.height()));
- return;
- }
- }
-
- if (!validRange.contains(xrect)) {
- // we are too big, and must clip
- xrect &=wrectRange;
- wrect = xrect;
- wrect.translate(-data.crect.topLeft());
- //parent's X coord system is equal to parent's Qt coord
- //sys, so we don't need to map xrect.
- }
- }
-
- // unmap if we are outside the valid window system coord system
- bool outsideRange = !xrect.isValid();
- bool mapWindow = false;
- if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
- q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
- if (outsideRange) {
- if (data.winid)
- data.winid->DrawableWindow()->SetVisible(EFalse);
- q->setAttribute(Qt::WA_Mapped, false);
- } else if (!q->isHidden()) {
- mapWindow = true;
- }
- }
-
- if (outsideRange)
- return;
-
- bool jump = (data.wrect != wrect);
- data.wrect = wrect;
-
- // and now recursively for all children...
- for (int i = 0; i < children.size(); ++i) {
- QObject *object = children.at(i);
- if (object->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(object);
- if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
- w->d_func()->setWSGeometry(jump);
- }
- }
-
- if (data.winid) {
- // move ourselves to the new position and map (if necessary) after
- // the movement. Rationale: moving unmapped windows is much faster
- // than moving mapped windows
- if (!parent->internalWinId())
- xrect.translate(parent->mapTo(q->nativeParentWidget(), QPoint(0, 0)));
-
- data.winid->SetExtent(TPoint(xrect.x(), xrect.y()), TSize(xrect.width(), xrect.height()));
- }
-
- if (mapWindow and !dontShow) {
- q->setAttribute(Qt::WA_Mapped);
- if (q->internalWinId())
- q->internalWinId()->DrawableWindow()->SetVisible(ETrue);
- }
-
- if (jump && data.winid) {
- RWindow *const window = static_cast<RWindow *>(data.winid->DrawableWindow());
- window->Invalidate(TRect(0, 0, wrect.width(), wrect.height()));
- }
-}
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
- Q_Q(QWidget);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if ((q->windowType() == Qt::Desktop))
- return;
-
- QPoint oldPos(q->pos());
- QSize oldSize(q->size());
- QRect oldGeom(data.crect);
-
- // Lose maximized status if deliberate resize
- if (w != oldSize.width() || h != oldSize.height())
- data.window_state &= ~Qt::WindowMaximized;
-
- if (extra) { // any size restrictions?
- w = qMin(w,extra->maxw);
- h = qMin(h,extra->maxh);
- w = qMax(w,extra->minw);
- h = qMax(h,extra->minh);
- }
-
- if (q->isWindow())
- topData()->normalGeometry = QRect(0, 0, -1, -1);
- else {
- uint s = data.window_state;
- s &= ~(Qt::WindowMaximized | Qt::WindowFullScreen);
- data.window_state = s;
- }
-
- bool isResize = w != oldSize.width() || h != oldSize.height();
- if (!isMove && !isResize)
- return;
-
- if (q->isWindow()) {
- if (w == 0 || h == 0) {
- q->setAttribute(Qt::WA_OutsideWSRange, true);
- if (q->isVisible() && q->testAttribute(Qt::WA_Mapped))
- hide_sys();
- data.crect = QRect(x, y, w, h);
- data.window_state &= ~Qt::WindowFullScreen;
- } else if (q->isVisible() && q->testAttribute(Qt::WA_OutsideWSRange)) {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
-
- // put the window in its place and show it
- q->internalWinId()->SetRect(TRect(TPoint(x, y), TSize(w, h)));
- data.crect.setRect(x, y, w, h);
- show_sys();
- } else {
- QRect r = QRect(x, y, w, h);
- data.crect = r;
- q->internalWinId()->SetRect(TRect(TPoint(x, y), TSize(w, h)));
- topData()->normalGeometry = data.crect;
- }
- QSymbianControl *window = static_cast<QSymbianControl *>(q->internalWinId());
- window->ensureFixNativeOrientation();
- } else {
- data.crect.setRect(x, y, w, h);
-
- QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- const bool inTopLevelResize = tlwExtra ? tlwExtra->inTopLevelResize : false;
-
- if (q->isVisible() && (!inTopLevelResize || q->internalWinId())) {
- // Top-level resize optimization does not work for native child widgets;
- // disable it for this particular widget.
- if (inTopLevelResize)
- tlwExtra->inTopLevelResize = false;
- if (!isResize && maybeBackingStore())
- moveRect(QRect(oldPos, oldSize), x - oldPos.x(), y - oldPos.y());
- else
- invalidateBuffer_resizeHelper(oldPos, oldSize);
-
- if (inTopLevelResize)
- tlwExtra->inTopLevelResize = true;
- }
- if (q->testAttribute(Qt::WA_WState_Created))
- setWSGeometry();
- }
-
- if (q->isVisible()) {
- if (isMove && q->pos() != oldPos) {
- QMoveEvent e(q->pos(), oldPos);
- QApplication::sendEvent(q, &e);
- }
- if (isResize) {
- bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
- const bool setTopLevelResize = !slowResize && q->isWindow() && extra && extra->topextra
- && !extra->topextra->inTopLevelResize;
- if (setTopLevelResize)
- extra->topextra->inTopLevelResize = true;
- QResizeEvent e(q->size(), oldSize);
- QApplication::sendEvent(q, &e);
- if (!q->testAttribute(Qt::WA_StaticContents) && q->internalWinId())
- q->internalWinId()->DrawDeferred();
- if (setTopLevelResize)
- extra->topextra->inTopLevelResize = false;
- }
- } else {
- if (isMove && q->pos() != oldPos)
- q->setAttribute(Qt::WA_PendingMoveEvent, true);
- if (isResize)
- q->setAttribute(Qt::WA_PendingResizeEvent, true);
- }
-}
-
-void QWidgetPrivate::create_sys(WId window, bool /* initializeWindow */, bool destroyOldWindow)
-{
- Q_Q(QWidget);
-
- Qt::WindowType type = q->windowType();
- Qt::WindowFlags &flags = data.window_flags;
- QWidget *parentWidget = q->parentWidget();
-
- bool topLevel = (flags & Qt::Window);
- bool popup = (type == Qt::Popup);
- bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet
- || (flags & Qt::MSWindowsFixedSizeDialogHint));
- bool desktop = (type == Qt::Desktop);
- //bool tool = (type == Qt::Tool || type == Qt::Drawer);
-
- if (popup)
- flags |= Qt::WindowStaysOnTopHint; // a popup stays on top
-
- TRect clientRect = static_cast<CEikAppUi*>(S60->appUi())->ClientRect();
- int sw = clientRect.Width();
- int sh = clientRect.Height();
-
- if (desktop) {
- symbianScreenNumber = qMax(qt_symbian_create_desktop_on_screen, 0);
- TSize screenSize = S60->screenDevice(symbianScreenNumber)->SizeInPixels();
- data.crect.setRect(0, 0, screenSize.iWidth, screenSize.iHeight);
- q->setAttribute(Qt::WA_DontShowOnScreen);
- } else if (topLevel && !q->testAttribute(Qt::WA_Resized)){
- int width = sw;
- int height = sh;
- if (symbianScreenNumber > 0) {
- TSize screenSize = S60->screenDevice(symbianScreenNumber)->SizeInPixels();
- width = screenSize.iWidth;
- height = screenSize.iHeight;
- }
- if (extra) {
- width = qMax(qMin(width, extra->maxw), extra->minw);
- height = qMax(qMin(height, extra->maxh), extra->minh);
- }
- data.crect.setSize(QSize(width, height));
- }
-
- CCoeControl *const destroyw = destroyOldWindow ? data.winid : 0;
-
- createExtra();
- if (window) {
- setWinId(window);
- TRect tr = window->Rect();
- data.crect.setRect(tr.iTl.iX, tr.iTl.iY, tr.Width(), tr.Height());
-
- } else if (topLevel) {
- if (!q->testAttribute(Qt::WA_Moved) && !q->testAttribute(Qt::WA_DontShowOnScreen))
- data.crect.moveTopLeft(QPoint(clientRect.iTl.iX, clientRect.iTl.iY));
-
- QScopedPointer<QSymbianControl> control( new QSymbianControl(q) );
- Q_CHECK_PTR(control);
-
- QT_TRAP_THROWING(control->ConstructL(true, desktop));
- control->SetMopParent(static_cast<CEikAppUi*>(S60->appUi()));
-
- // Symbian windows are always created in an inactive state
- // We perform this assignment for the case where the window is being re-created
- // as a result of a call to setParent_sys, on either this widget or one of its
- // ancestors.
- extra->activated = 0;
-
- if (!desktop) {
- TInt stackingFlags;
- if ((q->windowType() & Qt::Popup) == Qt::Popup) {
- stackingFlags = ECoeStackFlagRefusesAllKeys | ECoeStackFlagRefusesFocus;
- } else {
- stackingFlags = ECoeStackFlagStandard;
- }
- control->MakeVisible(false);
- QT_TRAP_THROWING(control->ControlEnv()->AppUi()->AddToStackL(control.data(), ECoeStackPriorityDefault, stackingFlags));
- // Avoid keyboard focus to a hidden window.
- control->setFocusSafely(false);
-
- RDrawableWindow *const drawableWindow = control->DrawableWindow();
- // Request mouse move events.
- drawableWindow->PointerFilter(EPointerFilterEnterExit
- | EPointerFilterMove | EPointerFilterDrag, 0);
- drawableWindow->EnableVisibilityChangeEvents();
-
- }
-
- q->setAttribute(Qt::WA_WState_Created);
-
- int x, y, w, h;
- data.crect.getRect(&x, &y, &w, &h);
- control->SetRect(TRect(TPoint(x, y), TSize(w, h)));
-
- // We wait until the control is fully constructed before calling setWinId, because
- // this generates a WinIdChanged event.
- setWinId(control.take());
-
- if (!desktop)
- s60UpdateIsOpaque(); // must be called after setWinId()
-
- } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create native child widget
-
- QScopedPointer<QSymbianControl> control( new QSymbianControl(q) );
- Q_CHECK_PTR(control);
-
- QT_TRAP_THROWING(control->ConstructL(!parentWidget));
-
- // Symbian windows are always created in an inactive state
- // We perform this assignment for the case where the window is being re-created
- // as a result of a call to setParent_sys, on either this widget or one of its
- // ancestors.
- extra->activated = 0;
-
- TInt stackingFlags;
- if ((q->windowType() & Qt::Popup) == Qt::Popup) {
- stackingFlags = ECoeStackFlagRefusesAllKeys | ECoeStackFlagRefusesFocus;
- } else {
- stackingFlags = ECoeStackFlagStandard;
- }
- control->MakeVisible(false);
- QT_TRAP_THROWING(control->ControlEnv()->AppUi()->AddToStackL(control.data(), ECoeStackPriorityDefault, stackingFlags));
- // Avoid keyboard focus to a hidden window.
- control->setFocusSafely(false);
-
- q->setAttribute(Qt::WA_WState_Created);
- int x, y, w, h;
- data.crect.getRect(&x, &y, &w, &h);
- control->SetRect(TRect(TPoint(x, y), TSize(w, h)));
-
- RDrawableWindow *const drawableWindow = control->DrawableWindow();
- // Request mouse move events.
- drawableWindow->PointerFilter(EPointerFilterEnterExit
- | EPointerFilterMove | EPointerFilterDrag, 0);
- drawableWindow->EnableVisibilityChangeEvents();
-
- if (q->isVisible() && q->testAttribute(Qt::WA_Mapped)) {
- activateSymbianWindow(control.data());
- control->MakeVisible(true);
- }
-
- // We wait until the control is fully constructed before calling setWinId, because
- // this generates a WinIdChanged event.
- setWinId(control.take());
- }
-
- if (destroyw) {
- destroyw->ControlEnv()->AppUi()->RemoveFromStack(destroyw);
-
- // Delay deletion of the control in case this function is called in the
- // context of a CONE event handler such as
- // CCoeControl::ProcessPointerEventL
- QMetaObject::invokeMethod(q, "_q_delayedDestroy",
- Qt::QueuedConnection, Q_ARG(WId, destroyw));
- }
-
- if (q->testAttribute(Qt::WA_AcceptTouchEvents))
- registerTouchWindow();
-}
-
-
-void QWidgetPrivate::show_sys()
-{
- Q_Q(QWidget);
-
- if (q->testAttribute(Qt::WA_OutsideWSRange))
- return;
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- q->setAttribute(Qt::WA_Mapped);
-
- if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
- invalidateBuffer(q->rect());
- return;
- }
-
- if (q->internalWinId()) {
- if (!extra->activated)
- activateSymbianWindow();
-
- QSymbianControl *id = static_cast<QSymbianControl *>(q->internalWinId());
- const bool isFullscreen = q->windowState() & Qt::WindowFullScreen;
- const TBool cbaRequested = q->windowFlags() & Qt::WindowSoftkeysVisibleHint;
-
-#ifdef Q_WS_S60
- // Lazily initialize the S60 screen furniture when the first window is shown.
- if (q->isWindow() && !QApplication::testAttribute(Qt::AA_S60DontConstructApplicationPanes)
- && !S60->buttonGroupContainer() && !S60->statusPane()) {
-
- if (!q->testAttribute(Qt::WA_DontShowOnScreen)) {
-
- // Create the status pane and CBA here
- CEikAppUi *ui = static_cast<CEikAppUi *>(S60->appUi());
- MEikAppUiFactory *factory = CEikonEnv::Static()->AppUiFactory();
-
- QT_TRAP_THROWING(
- factory->CreateResourceIndependentFurnitureL(ui);
-
- TRect boundingRect = static_cast<CEikAppUi*>(S60->appUi())->ClientRect();
-
- CEikButtonGroupContainer *cba = CEikButtonGroupContainer::NewL(CEikButtonGroupContainer::ECba,
- CEikButtonGroupContainer::EHorizontal,ui,R_AVKON_SOFTKEYS_EMPTY_WITH_IDS);
- if (isFullscreen && !cbaRequested)
- cba->MakeVisible(false);
-
- CEikButtonGroupContainer *oldCba = factory->SwapButtonGroup(cba);
- Q_ASSERT(!oldCba);
- S60->setButtonGroupContainer(cba);
-
- // If the creation of the first widget is delayed, for example by doing it
- // inside the event loop, S60 somehow "forgets" to set the visibility of the
- // toolbar (the three middle softkeys) when you flip the phone over, so we
- // need to do it ourselves to avoid a "hole" in the application, even though
- // Qt itself does not use the toolbar directly..
- CAknAppUi *appui = dynamic_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
- if (appui) {
- CAknToolbar *toolbar = appui->PopupToolbar();
- if (toolbar && !toolbar->IsVisible())
- toolbar->SetToolbarVisibility(ETrue);
- }
-
- CEikMenuBar *menuBar = new(ELeave) CEikMenuBar;
- menuBar->ConstructL(ui, 0, R_AVKON_MENUPANE_EMPTY);
- menuBar->SetMenuType(CEikMenuBar::EMenuOptions);
- S60->appUi()->AddToStackL(menuBar,ECoeStackPriorityMenu,ECoeStackFlagRefusesFocus);
-
- CEikMenuBar *oldMenu = factory->SwapMenuBar(menuBar);
- Q_ASSERT(!oldMenu);
- )
-
- if (S60->statusPane()) {
- // Use QDesktopWidget as the status pane observer to proxy for the AppUi.
- // Can't use AppUi directly because it privately inherits from MEikStatusPaneObserver.
- QSymbianControl *desktopControl = static_cast<QSymbianControl *>(QApplication::desktop()->winId());
- S60->statusPane()->SetObserver(desktopControl);
- if (isFullscreen) {
- const bool cbaVisible = S60->buttonGroupContainer() && S60->buttonGroupContainer()->IsVisible();
- S60->setStatusPaneAndButtonGroupVisibility(false, cbaVisible);
- }
- }
- }
- }
-#endif
-
- // Fill client area if maximized OR
- // Put window below status pane unless the window has an explicit position.
- if (!isFullscreen) {
- if (q->windowState() & Qt::WindowMaximized) {
- TRect r = static_cast<CEikAppUi*>(S60->appUi())->ClientRect();
- id->SetExtent(r.iTl, r.Size());
- } else if (!q->testAttribute(Qt::WA_Moved) && q->windowType() != Qt::Dialog) {
- id->SetPosition(static_cast<CEikAppUi*>(S60->appUi())->ClientRect().iTl);
- }
- }
-
- id->MakeVisible(true);
-
- if(q->isWindow()&&!q->testAttribute(Qt::WA_ShowWithoutActivating))
- id->setFocusSafely(true);
- }
-
- invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::activateSymbianWindow(WId wid)
-{
- Q_Q(QWidget);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- Q_ASSERT(q->testAttribute(Qt::WA_Mapped));
- Q_ASSERT(!extra->activated);
-
- if(!wid)
- wid = q->internalWinId();
-
- Q_ASSERT(wid);
-
- QT_TRAP_THROWING(wid->ActivateL());
- extra->activated = 1;
-}
-
-void QWidgetPrivate::hide_sys()
-{
- Q_Q(QWidget);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- deactivateWidgetCleanup();
- QSymbianControl *id = static_cast<QSymbianControl *>(q->internalWinId());
-
- if (id) {
- //Incorrect optimization - for popup windows, Qt's focus is moved before
- //hide_sys is called, resulting in the popup window keeping its elevated
- //position in the CONE control stack.
- //This can result in keyboard focus being in an invisible widget in some
- //conditions - e.g. QTBUG-4733
- //if(id->IsFocused()) // Avoid unnecessary calls to FocusChanged()
- id->setFocusSafely(false);
- id->MakeVisible(false);
- if (QWidgetBackingStore *bs = maybeBackingStore())
- bs->releaseBuffer();
- } else {
- invalidateBuffer(q->rect());
- }
-
- q->setAttribute(Qt::WA_Mapped, false);
-}
-
-void QWidgetPrivate::setFocus_sys()
-{
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_WState_Created) && q->window()->windowType() != Qt::Popup)
- if (!q->effectiveWinId()->IsFocused()) // Avoid unnecessry calls to FocusChanged()
- static_cast<QSymbianControl *>(q->effectiveWinId())->setFocusSafely(true);
-}
-
-void QWidgetPrivate::raise_sys()
-{
- Q_Q(QWidget);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId()) {
- q->internalWinId()->DrawableWindow()->SetOrdinalPosition(0);
-
- // If toplevel widget, raise app to foreground
- if (q->isWindow())
- S60->wsSession().SetWindowGroupOrdinalPosition(S60->windowGroup(q).Identifier(), 0);
- }
-}
-
-void QWidgetPrivate::lower_sys()
-{
- Q_Q(QWidget);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId()) {
- // If toplevel widget, lower app to background
- if (q->isWindow())
- S60->wsSession().SetWindowGroupOrdinalPosition(S60->windowGroup(q).Identifier(), -1);
- else
- q->internalWinId()->DrawableWindow()->SetOrdinalPosition(-1);
- }
-
- if (!q->isWindow())
- invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::setModal_sys()
-{
-
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget* w)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if (q->internalWinId() && w->internalWinId()) {
- RDrawableWindow *const thisWindow = q->internalWinId()->DrawableWindow();
- RDrawableWindow *const otherWindow = w->internalWinId()->DrawableWindow();
- thisWindow->SetOrdinalPosition(otherWindow->OrdinalPosition() + 1);
- }
-
- if (!q->isWindow() || !w->internalWinId())
- invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::reparentChildren()
-{
- Q_Q(QWidget);
-
- QObjectList chlist = q->children();
- for (int i = 0; i < chlist.size(); ++i) { // reparent children
- QObject *obj = chlist.at(i);
- if (obj->isWidgetType()) {
- QWidget *w = (QWidget *)obj;
- if (!w->testAttribute(Qt::WA_WState_Created))
- continue;
- if (!w->isWindow()) {
- w->d_func()->invalidateBuffer(w->rect());
- WId parent = q->effectiveWinId();
- WId child = w->effectiveWinId();
- if (parent != child) {
- // Child widget is native. Because Symbian windows cannot be
- // re-parented, we must re-create the window.
- const WId window = 0;
- const bool initializeWindow = false;
- const bool destroyOldWindow = true;
- w->d_func()->create_sys(window, initializeWindow, destroyOldWindow);
- }
- // ### TODO: We probably also need to update the component array here
- w->d_func()->reparentChildren();
- } else {
- bool showIt = w->isVisible();
- QPoint old_pos = w->pos();
- w->setParent(q, w->windowFlags());
- w->move(old_pos);
- if (showIt)
- w->show();
- }
- }
- }
-}
-
-void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
-{
- Q_Q(QWidget);
-
- if (parent && parent->windowType() == Qt::Desktop) {
- symbianScreenNumber = qt_widget_private(parent)->symbianScreenNumber;
- parent = 0;
- }
-
- bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
-
- if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
- q->parentWidget()->d_func()->invalidateBuffer(q->geometry());
-
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- q->setAttribute(Qt::WA_DropSiteRegistered, false);
-
- QSymbianControl *old_winid = static_cast<QSymbianControl *>(wasCreated ? data.winid : 0);
- if ((q->windowType() == Qt::Desktop))
- old_winid = 0;
-
- // old_winid may not have received a 'not visible' visibility
- // changed event before being destroyed; make sure that it is
- // removed from the backing store's list of visible windows.
- if (old_winid)
- S60->controlVisibilityChanged(old_winid, false);
-
- setWinId(0);
-
- // hide and reparent our own window away. Otherwise we might get
- // destroyed when emitting the child remove event below. See QWorkspace.
- if (wasCreated && old_winid) {
- old_winid->MakeVisible(false);
- if (old_winid->IsFocused()) // Avoid unnecessary calls to FocusChanged()
- old_winid->setFocusSafely(false);
- old_winid->SetParent(0);
- }
-
- QObjectPrivate::setParent_helper(parent);
- bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
-
- data.window_flags = f;
- data.fstrut_dirty = true;
- q->setAttribute(Qt::WA_WState_Created, false);
- q->setAttribute(Qt::WA_WState_Visible, false);
- q->setAttribute(Qt::WA_WState_Hidden, false);
- adjustFlags(data.window_flags, q);
- // keep compatibility with previous versions, we need to preserve the created state
- // (but we recreate the winId for the widget being reparented, again for compatibility)
- if (wasCreated || (!q->isWindow() && parent->testAttribute(Qt::WA_WState_Created)))
- createWinId();
- if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
- q->setAttribute(Qt::WA_WState_Hidden);
- q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
- if (wasCreated)
- reparentChildren();
-
- if (old_winid) {
- CBase::Delete(old_winid);
- }
-
- if (q->testAttribute(Qt::WA_AcceptDrops)
- || (!q->isWindow() && q->parentWidget() && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
- q->setAttribute(Qt::WA_DropSiteRegistered, true);
-
- invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
-
-}
-
-
-void QWidgetPrivate::s60UpdateIsOpaque()
-{
- Q_Q(QWidget);
-
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-
- const bool writeAlpha = extraData()->nativePaintMode == QWExtra::BlitWriteAlpha;
- if (!q->testAttribute(Qt::WA_TranslucentBackground) && !writeAlpha)
- return;
- const bool requireAlphaChannel = !isOpaque || writeAlpha;
-
- createTLExtra();
-
- RWindow *const window = static_cast<RWindow *>(q->effectiveWinId()->DrawableWindow());
-
-#ifdef Q_SYMBIAN_SEMITRANSPARENT_BG_SURFACE
- if (QApplicationPrivate::instance()->useTranslucentEGLSurfaces) {
- window->SetSurfaceTransparency(!isOpaque);
- extra->topextra->nativeWindowTransparencyEnabled = !isOpaque;
- return;
- }
-#endif
- if (requireAlphaChannel) {
- const TDisplayMode displayMode = static_cast<TDisplayMode>(window->SetRequiredDisplayMode(EColor16MA));
- if (window->SetTransparencyAlphaChannel() == KErrNone) {
- window->SetBackgroundColor(TRgb(255, 255, 255, 0));
- extra->topextra->nativeWindowTransparencyEnabled = 1;
- if (extra->topextra->backingStore.data() && (
- QApplicationPrivate::graphics_system_name == QLatin1String("openvg")
- || QApplicationPrivate::graphics_system_name == QLatin1String("opengl"))) {
- // Semi-transparent EGL surfaces aren't supported. We need to
- // recreate backing store to get translucent surface (raster surface).
- extra->topextra->backingStore.create(q);
- extra->topextra->backingStore.registerWidget(q);
- // FixNativeOrientation() will not work without an EGL surface.
- q->setAttribute(Qt::WA_SymbianNoSystemRotation, false);
- }
- }
- } else if (extra->topextra->nativeWindowTransparencyEnabled) {
- window->SetTransparentRegion(TRegionFix<1>());
- extra->topextra->nativeWindowTransparencyEnabled = 0;
- }
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
-{
-#ifdef Q_WS_S60
- Q_Q(QWidget);
-
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow() )
- return;
-
- QTLWExtra* topData = this->topData();
- if (topData->iconPixmap && !forceReset)
- // already been set
- return;
-
- TRect cPaneRect;
- TBool found = AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::EContextPane, cPaneRect );
- CAknContextPane* contextPane = S60->contextPane();
- if (found && contextPane) { // We have context pane with valid metrics
- QIcon icon = q->windowIcon();
- if (!icon.isNull()) {
- // Valid icon -> set it as an context pane picture
- QSize size = icon.actualSize(QSize(cPaneRect.Size().iWidth, cPaneRect.Size().iHeight));
- QPixmap pm = icon.pixmap(size);
- QBitmap mask = pm.mask();
- if (mask.isNull()) {
- mask = QBitmap(pm.size());
- mask.fill(Qt::color1);
- }
-
- CFbsBitmap* nBitmap = pm.toSymbianCFbsBitmap();
- CFbsBitmap* nMask = mask.toSymbianCFbsBitmap();
- contextPane->SetPicture(nBitmap,nMask);
- } else {
- // Icon set to null -> set context pane picture to default
- QT_TRAP_THROWING(contextPane->SetPictureToDefaultL());
- }
- } else {
- // Context pane does not exist, try setting small icon to title pane
- TRect titlePaneRect;
- TBool found = AknLayoutUtils::LayoutMetricsRect( AknLayoutUtils::ETitlePane, titlePaneRect );
- CAknTitlePane* titlePane = S60->titlePane();
- if (found && titlePane) { // We have title pane with valid metrics
- // The API to get title_pane graphics size is not public -> assume square space based
- // on titlebar font height. CAknBitmap would be optimum, wihtout setting the size, since
- // then title pane would automatically scale the bitmap. Unfortunately it is not public API
- // Also this function is leaving, although it is not named as such.
- const CFont * font;
- QT_TRAP_THROWING(font = AknLayoutUtils::FontFromId(EAknLogicalFontTitleFont));
- TSize iconSize(font->HeightInPixels(), font->HeightInPixels());
-
- QIcon icon = q->windowIcon();
- if (!icon.isNull()) {
- // Valid icon -> set it as an title pane small picture
- QSize size = icon.actualSize(QSize(iconSize.iWidth, iconSize.iHeight));
- QPixmap pm = icon.pixmap(size);
- QBitmap mask = pm.mask();
- if (mask.isNull()) {
- mask = QBitmap(pm.size());
- mask.fill(Qt::color1);
- }
-
- CFbsBitmap* nBitmap = pm.toSymbianCFbsBitmap();
- CFbsBitmap* nMask = mask.toSymbianCFbsBitmap();
- titlePane->SetSmallPicture( nBitmap, nMask, ETrue );
- } else {
- // Icon set to null -> set context pane picture to default
- titlePane->SetSmallPicture( NULL, NULL, EFalse );
- }
- }
- }
-
-#else
- Q_UNUSED(forceReset)
-#endif
-}
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
-#ifdef Q_WS_S60
- Q_Q(QWidget);
- if (q->isWindow()) {
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- CAknTitlePane* titlePane = S60->titlePane();
- if (titlePane) {
- if (caption.isEmpty()) {
- QT_TRAP_THROWING(titlePane->SetTextToDefaultL());
- } else {
- QT_TRAP_THROWING(titlePane->SetTextL(qt_QString2TPtrC(caption)));
- }
- }
- }
-#else
- Q_UNUSED(caption)
-#endif
-}
-
-void QWidgetPrivate::setWindowIconText_sys(const QString & /*iconText */)
-{
-
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
- Q_Q(QWidget);
-
- scrollChildren(dx, dy);
- if (!paintOnScreen() || !q->internalWinId() || !q->internalWinId()->OwnsWindow()) {
- scrollRect(q->rect(), dx, dy);
- } else {
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- RDrawableWindow *const window = q->internalWinId()->DrawableWindow();
- window->Scroll(TPoint(dx, dy));
- }
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
-{
- Q_Q(QWidget);
-
- if (!paintOnScreen() || !q->internalWinId() || !q->internalWinId()->OwnsWindow()) {
- scrollRect(r, dx, dy);
- } else {
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- RDrawableWindow *const window = q->internalWinId()->DrawableWindow();
- window->Scroll(TPoint(dx, dy), qt_QRect2TRect(r));
- }
-}
-
-/*!
- For this function to work in the emulator, you must add:
- TRANSPARENCY
- To a line in the wsini.ini file.
-*/
-void QWidgetPrivate::setWindowOpacity_sys(qreal)
-{
- // ### TODO: Implement uniform window transparency
-}
-
-void QWidgetPrivate::updateFrameStrut()
-{
-
-}
-
-void QWidgetPrivate::updateSystemBackground()
-{
-
-}
-
-void QWidgetPrivate::registerDropSite(bool /* on */)
-{
-
-}
-
-void QWidgetPrivate::createTLSysExtra()
-{
- extra->topextra->inExpose = 0;
- extra->topextra->nativeWindowTransparencyEnabled = 0;
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
- extra->topextra->backingStore.destroy();
-}
-
-void QWidgetPrivate::createSysExtra()
-{
- extra->activated = 0;
- extra->nativePaintMode = QWExtra::Default;
- extra->receiveNativePaintEvents = 0;
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
- // this should only be non-zero if destroy() has not run due to constructor fail
- if (data.winid) {
- data.winid->ControlEnv()->AppUi()->RemoveFromStack(data.winid);
- delete data.winid;
- data.winid = 0;
- }
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
- return new QS60WindowSurface(q_func());
-}
-
-void QWidgetPrivate::setMask_sys(const QRegion& /* region */)
-{
-
-}
-
-void QWidgetPrivate::registerTouchWindow()
-{
-#ifdef QT_SYMBIAN_SUPPORTS_ADVANCED_POINTER
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_WState_Created) && q->windowType() != Qt::Desktop) {
- RWindow *rwindow = static_cast<RWindow *>(q->effectiveWinId()->DrawableWindow());
- QSymbianControl *window = static_cast<QSymbianControl *>(q->effectiveWinId());
- //Enabling advanced pointer events for controls that already have active windows causes a panic.
- if (!window->isControlActive())
- rwindow->EnableAdvancedPointers();
- }
-#endif
-}
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
- Q_D(const QWidget);
- int val;
- if (m == PdmWidth) {
- val = data->crect.width();
- } else if (m == PdmHeight) {
- val = data->crect.height();
- } else {
- CWsScreenDevice *scr = S60->screenDevice(this);
- switch(m) {
- case PdmDpiX:
- case PdmPhysicalDpiX:
- if (d->extra && d->extra->customDpiX) {
- val = d->extra->customDpiX;
- } else {
- const QWidgetPrivate *p = d;
- while (p->parent) {
- p = static_cast<const QWidget *>(p->parent)->d_func();
- if (p->extra && p->extra->customDpiX) {
- val = p->extra->customDpiX;
- break;
- }
- }
- if (p == d || !(p->extra && p->extra->customDpiX))
- val = S60->defaultDpiX;
- }
- break;
- case PdmDpiY:
- case PdmPhysicalDpiY:
- if (d->extra && d->extra->customDpiY) {
- val = d->extra->customDpiY;
- } else {
- const QWidgetPrivate *p = d;
- while (p->parent) {
- p = static_cast<const QWidget *>(p->parent)->d_func();
- if (p->extra && p->extra->customDpiY) {
- val = p->extra->customDpiY;
- break;
- }
- }
- if (p == d || !(p->extra && p->extra->customDpiY))
- val = S60->defaultDpiY;
- }
- break;
- case PdmWidthMM:
- {
- TInt twips = scr->HorizontalPixelsToTwips(data->crect.width());
- val = (int)(twips * (25.4/KTwipsPerInch));
- break;
- }
- case PdmHeightMM:
- {
- TInt twips = scr->VerticalPixelsToTwips(data->crect.height());
- val = (int)(twips * (25.4/KTwipsPerInch));
- break;
- }
- case PdmNumColors:
- val = TDisplayModeUtils::NumDisplayModeColors(scr->DisplayMode());
- break;
- case PdmDepth:
- val = TDisplayModeUtils::NumDisplayModeBitsPerPixel(scr->DisplayMode());
- break;
- default:
- val = 0;
- qWarning("QWidget::metric: Invalid metric command");
- }
- }
- return val;
-}
-
-QPaintEngine *QWidget::paintEngine() const
-{
- return 0;
-}
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
-
- QPoint p = pos + data->crect.topLeft();
- return (isWindow() || !parentWidget()) ? p : parentWidget()->mapToGlobal(p);
-
- } else if ((d->data.window_flags & Qt::Window) && internalWinId()) { //toplevel
- QPoint tp = geometry().topLeft();
- return pos + tp;
- }
-
- // Native window case
- const TPoint widgetScreenOffset = internalWinId()->PositionRelativeToScreen();
- const QPoint globalPos = QPoint(widgetScreenOffset.iX, widgetScreenOffset.iY) + pos;
- return globalPos;
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
- QPoint p = (isWindow() || !parentWidget()) ? pos : parentWidget()->mapFromGlobal(pos);
- return p - data->crect.topLeft();
- } else if ((d->data.window_flags & Qt::Window) && internalWinId()) { //toplevel
- QPoint tp = geometry().topLeft();
- return pos - tp;
- }
-
- // Native window case
- const TPoint widgetScreenOffset = internalWinId()->PositionRelativeToScreen();
- const QPoint widgetPos = pos - QPoint(widgetScreenOffset.iX, widgetScreenOffset.iY);
- return widgetPos;
-}
-
-static Qt::WindowStates effectiveState(Qt::WindowStates state)
-{
- if (state & Qt::WindowMinimized)
- return Qt::WindowMinimized;
- else if (state & Qt::WindowFullScreen)
- return Qt::WindowFullScreen;
- else if (state & Qt::WindowMaximized)
- return Qt::WindowMaximized;
- return Qt::WindowNoState;
-}
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
- Q_D(QWidget);
-
- Qt::WindowStates oldstate = windowState();
-
- const TBool isFullscreen = newstate & Qt::WindowFullScreen;
-#ifdef Q_WS_S60
- const TBool cbaRequested = windowFlags() & Qt::WindowSoftkeysVisibleHint;
- const TBool cbaVisible = CEikButtonGroupContainer::Current() ? true : false;
- const TBool softkeyVisibilityChange = isFullscreen && (cbaRequested != cbaVisible);
-
- if (oldstate == newstate && !softkeyVisibilityChange)
- return;
-#endif // Q_WS_S60
-
- if (isWindow()) {
- createWinId();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
- const bool wasResized = testAttribute(Qt::WA_Resized);
- const bool wasMoved = testAttribute(Qt::WA_Moved);
-
- QSymbianControl *window = static_cast<QSymbianControl *>(effectiveWinId());
- if (window && newstate & Qt::WindowMinimized) {
- window->setFocusSafely(false);
- window->MakeVisible(false);
- } else if (window && oldstate & Qt::WindowMinimized) {
- window->setFocusSafely(true);
- window->MakeVisible(true);
- }
-
-#ifdef Q_WS_S60
- // The window decoration visibility has to be changed before doing actual window state
- // change since in that order the availableGeometry will return directly the right size and
- // we will avoid unnecessary redraws
- bool decorationsVisible = S60->setRecursiveDecorationsVisibility(this, newstate);
-#endif // Q_WS_S60
-
- // Ensure the initial size is valid, since we store it as normalGeometry below.
- if (!wasResized && !isVisible())
- adjustSize();
-
- QTLWExtra *top = d->topData();
- QRect normalGeometry = (top->normalGeometry.width() < 0) ? geometry() : top->normalGeometry;
-
- const bool cbaVisibilityHint = windowFlags() & Qt::WindowSoftkeysVisibleHint;
- if (newstate & Qt::WindowFullScreen && !cbaVisibilityHint) {
- setAttribute(Qt::WA_OutsideWSRange, false);
- if (d->symbianScreenNumber > 0) {
- int w = S60->screenWidthInPixelsForScreen[d->symbianScreenNumber];
- int h = S60->screenHeightInPixelsForScreen[d->symbianScreenNumber];
- if (w <= 0 || h <= 0)
- window->SetExtentToWholeScreen();
- else
- window->SetExtent(TPoint(0, 0), TSize(w, h));
- } else {
- window->SetExtentToWholeScreen();
- }
- } else if (newstate & Qt::WindowMaximized || ((newstate & Qt::WindowFullScreen) && cbaVisibilityHint)) {
- setAttribute(Qt::WA_OutsideWSRange, false);
- TRect maxExtent = qt_QRect2TRect(qApp->desktop()->availableGeometry(this));
- window->SetExtent(maxExtent.iTl, maxExtent.Size());
- } else {
-#ifdef Q_WS_S60
- // With delayed creation of S60 app panes, the normalGeometry calculated above is not
- // accurate because it did not consider the status pane. This means that when returning
- // normal mode after showing the status pane, the geometry would overlap so we should
- // move it if it never had an explicit position.
- if (!wasMoved && S60->statusPane() && decorationsVisible) {
- TPoint tl = static_cast<CEikAppUi*>(S60->appUi())->ClientRect().iTl;
- normalGeometry.setTopLeft(QPoint(tl.iX, tl.iY));
- }
-#endif
- setGeometry(normalGeometry);
- }
-
- //restore normal geometry
- top->normalGeometry = normalGeometry;
-
- // FixMe QTBUG-8977
- // In some platforms, WA_Resized and WA_Moved are also not set when application window state is
- // anything else than normal. In Symbian we can restore them only for normal window state since
- // restoring for other modes, will make fluidlauncher to be launched in wrong size (200x100)
- if (effectiveState(newstate) == Qt::WindowNoState) {
- setAttribute(Qt::WA_Resized, wasResized);
- setAttribute(Qt::WA_Moved, wasMoved);
- }
- }
-
- data->window_state = newstate;
-
- if (newstate & Qt::WindowActive)
- activateWindow();
-
- if (isWindow()) {
- // Now that the new state is set, fix the display memory layout, if needed.
- QSymbianControl *window = static_cast<QSymbianControl *>(effectiveWinId());
- window->ensureFixNativeOrientation();
- }
-
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
-}
-
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
- Q_D(QWidget);
- d->aboutToDestroy();
- if (!isWindow() && parentWidget())
- parentWidget()->d_func()->invalidateBuffer(geometry());
- d->deactivateWidgetCleanup();
- QSymbianControl *id = static_cast<QSymbianControl *>(internalWinId());
- if (testAttribute(Qt::WA_WState_Created)) {
-
-#ifndef QT_NO_IM
- if (d->ic) {
- delete d->ic;
- } else {
- QInputContext *ic = QApplicationPrivate::inputContext;
- if (ic) {
- ic->widgetDestroyed(this);
- }
- }
-#endif
-
- if (QWidgetPrivate::mouseGrabber == this)
- releaseMouse();
- if (QWidgetPrivate::keyboardGrabber == this)
- releaseKeyboard();
- setAttribute(Qt::WA_WState_Created, false);
- QObjectList childList = children();
- for (int i = 0; i < childList.size(); ++i) { // destroy all widget children
- register QObject *obj = childList.at(i);
- if (obj->isWidgetType())
- static_cast<QWidget*>(obj)->destroy(destroySubWindows,
- destroySubWindows);
- }
- if (destroyWindow && !(windowType() == Qt::Desktop) && id) {
- if (id->IsFocused()) // Avoid unnecessry calls to FocusChanged()
- id->setFocusSafely(false);
- id->ControlEnv()->AppUi()->RemoveFromStack(id);
- }
- }
-
- QT_TRY {
- d->setWinId(0);
- } QT_CATCH (const std::bad_alloc &) {
- // swallow - destructors must not throw
- }
-
- if (destroyWindow) {
- delete id;
- // At this point the backing store should already be destroyed
- // so we flush the command buffer to ensure that the freeing of
- // those resources and deleting the window can happen "atomically"
- if (qApp)
- S60->wsSession().Flush();
- }
-}
-
-QWidget *QWidget::mouseGrabber()
-{
- return QWidgetPrivate::mouseGrabber;
-}
-
-QWidget *QWidget::keyboardGrabber()
-{
- return QWidgetPrivate::keyboardGrabber;
-}
-
-void QWidget::grabKeyboard()
-{
- if (!qt_nograb()) {
- if (QWidgetPrivate::keyboardGrabber && QWidgetPrivate::keyboardGrabber != this)
- QWidgetPrivate::keyboardGrabber->releaseKeyboard();
-
- // ### TODO: Native keyboard grab
-
- QWidgetPrivate::keyboardGrabber = this;
- }
-}
-
-void QWidget::releaseKeyboard()
-{
- if (!qt_nograb() && QWidgetPrivate::keyboardGrabber == this) {
- // ### TODO: Native keyboard release
- QWidgetPrivate::keyboardGrabber = 0;
- }
-}
-
-void QWidget::grabMouse()
-{
- if (isVisible() && !qt_nograb()) {
- if (QWidgetPrivate::mouseGrabber && QWidgetPrivate::mouseGrabber != this)
- QWidgetPrivate::mouseGrabber->releaseMouse();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- WId id = effectiveWinId();
- id->SetPointerCapture(true);
- QWidgetPrivate::mouseGrabber = this;
-
-#ifndef QT_NO_CURSOR
- QApplication::setOverrideCursor(cursor());
-#endif
- }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
- if (isVisible() && !qt_nograb()) {
- if (QWidgetPrivate::mouseGrabber && QWidgetPrivate::mouseGrabber != this)
- QWidgetPrivate::mouseGrabber->releaseMouse();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- WId id = effectiveWinId();
- id->SetPointerCapture(true);
- QWidgetPrivate::mouseGrabber = this;
-
- QApplication::setOverrideCursor(cursor);
- }
-}
-#endif
-
-void QWidget::releaseMouse()
-{
- if (!qt_nograb() && QWidgetPrivate::mouseGrabber == this) {
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- if(!window()->isModal()) {
- WId id = effectiveWinId();
- id->SetPointerCapture(false);
- }
- QWidgetPrivate::mouseGrabber = 0;
-#ifndef QT_NO_CURSOR
- QApplication::restoreOverrideCursor();
-#endif
- }
-}
-
-void QWidget::activateWindow()
-{
- Q_D(QWidget);
-
- QWidget *tlw = window();
- if (tlw->isVisible()) {
- window()->createWinId();
- QSymbianControl *id = static_cast<QSymbianControl *>(tlw->internalWinId());
- if (!id->IsFocused())
- id->setFocusSafely(true);
- }
-}
-
-#ifndef QT_NO_CURSOR
-
-void QWidgetPrivate::setCursor_sys(const QCursor &cursor)
-{
- Q_UNUSED(cursor);
- Q_Q(QWidget);
- qt_symbian_set_cursor(q, false);
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
- Q_Q(QWidget);
- qt_symbian_set_cursor(q, false);
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qapplication_win.cpp b/src/gui/platforms/win/qapplication_win.cpp
deleted file mode 100644
index 72a05afbd0..0000000000
--- a/src/gui/platforms/win/qapplication_win.cpp
+++ /dev/null
@@ -1,4243 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#ifdef Q_WS_WINCE
-#include "qguifunctions_wince.h"
-#include "qmenubar.h"
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_high_dpi(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_smartphone(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_pocket_pc(); //defined in qguifunctions_wince.cpp
-extern void qt_wince_hide_taskbar(HWND hwnd); //defined in qguifunctions_wince.cpp
-#endif
-#ifdef Q_WS_WINCE_WM
-#include <windowsm.h>
-#include <tpcshell.h>
-#ifdef QT_WINCE_GESTURES
-#ifndef QT_NO_GESTURES
-#include <gesture.h>
-#endif
-#endif
-#endif
-
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "private/qeventdispatcher_win_p.h"
-#include "qeventloop.h"
-#include "qclipboard.h"
-#include "qcursor.h"
-#include "qdatetime.h"
-#include "qpointer.h"
-#include "qhash.h"
-#include "qmetaobject.h"
-#include "qmime.h"
-#include "qpainter.h"
-#include "qpixmapcache.h"
-#include "qsessionmanager.h"
-#include "qstyle.h"
-#include "qwhatsthis.h" // ######## dependency
-#include "qwidget.h"
-#include "qcolormap.h"
-#include "qlayout.h"
-#include "qtooltip.h"
-#include "qt_windows.h"
-#include "qscrollbar.h"
-#if defined(QT_NON_COMMERCIAL)
-#include "qnc_win.h"
-#endif
-#include "private/qwininputcontext_p.h"
-#include "private/qcursor_p.h"
-#include "private/qmath_p.h"
-#include "private/qapplication_p.h"
-#include "private/qbackingstore_p.h"
-#include "private/qwindowsurface_raster_p.h"
-#include "qdebug.h"
-#include <private/qkeymapper_p.h>
-#include <private/qlocale_p.h>
-#include <private/qsystemlibrary_p.h>
-#include "qevent_p.h"
-
-//#define ALIEN_DEBUG
-
-#ifndef QT_NO_THREAD
-#include "qmutex.h"
-#endif
-
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-
-#include <oleacc.h>
-#ifndef WM_GETOBJECT
-#define WM_GETOBJECT 0x003D
-#endif
-#endif // QT_NO_ACCESSIBILITY
-
-#if !defined(WINABLEAPI)
-# if defined(Q_WS_WINCE)
-# include <bldver.h>
-# endif
-# if !defined(Q_WS_WINCE)
-# include <winable.h>
-# endif
-#endif
-
-#ifndef QT_NO_GESTURES
-# ifndef GID_ZOOM
-# define GID_ZOOM 3
-# define GID_TWOFINGERTAP 6
-# define GID_PRESSANDTAP 7
-# define GID_ROLLOVER GID_PRESSANDTAP
-# endif
-#endif
-
-#ifndef WM_TOUCH
-# define WM_TOUCH 0x0240
-#endif
-
-#ifndef TOUCHEVENTF_MOVE
-# define TOUCHEVENTF_MOVE 0x0001
-# define TOUCHEVENTF_DOWN 0x0002
-# define TOUCHEVENTF_UP 0x0004
-# define TOUCHEVENTF_INRANGE 0x0008
-# define TOUCHEVENTF_PRIMARY 0x0010
-# define TOUCHEVENTF_NOCOALESCE 0x0020
-# define TOUCHEVENTF_PEN 0x0040
-# define TOUCHEVENTF_PALM 0x0080
-
-# define TOUCHINPUTMASKF_TIMEFROMSYSTEM 0x0001
-# define TOUCHINPUTMASKF_EXTRAINFO 0x0002
-# define TOUCHINPUTMASKF_CONTACTAREA 0x0004
-
-typedef struct tagTOUCHINPUT
-{
- LONG x;
- LONG y;
- HANDLE hSource;
- DWORD dwID;
- DWORD dwFlags;
- DWORD dwMask;
- DWORD dwTime;
- ULONG_PTR dwExtraInfo;
- DWORD cxContact;
- DWORD cyContact;
-} TOUCHINPUT, *PTOUCHINPUT;
-
-#endif
-
-#include <windowsx.h>
-#include <limits.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <math.h>
-
-#define PACKETDATA (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
- | PK_ORIENTATION | PK_CURSOR | PK_Z)
-#define PACKETMODE 0
-
-#include <wintab.h>
-#ifndef CSR_TYPE
-#define CSR_TYPE 20 // Some old Wacom wintab.h may not provide this constant.
-#endif
-#include <pktdef.h>
-
-#if defined(__CYGWIN32__)
-#define __INSIDE_CYGWIN32__
-#include <mywinsock.h>
-#endif
-
-#ifndef IMR_RECONVERTSTRING
-#define IMR_RECONVERTSTRING 4
-#endif
-
-#ifndef IMR_CONFIRMRECONVERTSTRING
-#define IMR_CONFIRMRECONVERTSTRING 0x0005
-#endif
-QT_BEGIN_NAMESPACE
-
-#ifdef Q_WS_WINCE
-#ifndef SHRG_RETURNCMD
-struct SHRGINFO {
- DWORD cbSize;
- HWND hwndClient;
- POINT ptDown;
- DWORD dwFlags;
-};
-#define GN_CONTEXTMENU 1000
-#define SHRG_RETURNCMD 0x00000001
-#define SHRG_NOANIMATION 0x00000010
-#endif
-
-#ifndef SPI_SETSIPINFO
-#define SPI_SETSIPINFO 224
-#endif
-
-#ifndef QT_NO_GESTURES
-typedef DWORD (API *AygRecognizeGesture)(SHRGINFO*);
-static AygRecognizeGesture ptrRecognizeGesture = 0;
-static bool aygResolved = false;
-static void resolveAygLibs()
-{
- if (!aygResolved) {
- aygResolved = true;
- QSystemLibrary ayglib(QLatin1String("aygshell"));
- ptrRecognizeGesture = (AygRecognizeGesture) ayglib.resolve("SHRecognizeGesture");
- }
-}
-#endif // QT_NO_GESTURES
-
-#endif
-
-#ifndef SPI_SETFONTSMOOTHINGTYPE
-# define SPI_SETFONTSMOOTHINGTYPE 0x200B
-#endif
-#ifndef SPI_GETFONTSMOOTHINGTYPE
-# define SPI_GETFONTSMOOTHINGTYPE 0x200A
-#endif
-#ifndef FE_FONTSMOOTHINGCLEARTYPE
-# define FE_FONTSMOOTHINGCLEARTYPE 0x0002
-#endif
-
-Q_GUI_EXPORT qreal qt_fontsmoothing_gamma;
-Q_GUI_EXPORT bool qt_cleartype_enabled;
-Q_GUI_EXPORT bool qt_win_owndc_required; // CS_OWNDC is required if we use the GL graphicssystem as default
-
-typedef HCTX (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
-typedef BOOL (API *PtrWTClose)(HCTX);
-typedef UINT (API *PtrWTInfo)(UINT, UINT, LPVOID);
-typedef BOOL (API *PtrWTEnable)(HCTX, BOOL);
-typedef BOOL (API *PtrWTOverlap)(HCTX, BOOL);
-typedef int (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
-typedef BOOL (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
-typedef int (API *PtrWTQueueSizeGet)(HCTX);
-typedef BOOL (API *PtrWTQueueSizeSet)(HCTX, int);
-
-static PtrWTInfo ptrWTInfo = 0;
-static PtrWTEnable ptrWTEnable = 0;
-static PtrWTOverlap ptrWTOverlap = 0;
-static PtrWTPacketsGet ptrWTPacketsGet = 0;
-static PtrWTGet ptrWTGet = 0;
-
-static PACKET localPacketBuf[QT_TABLET_NPACKETQSIZE]; // our own tablet packet queue.
-HCTX qt_tablet_context; // the hardware context for the tablet (like a window handle)
-bool qt_tablet_tilt_support;
-
-#ifndef QT_NO_TABLETEVENT
-static void tabletInit(const quint64 uniqueId, const UINT csr_type, HCTX hTab);
-static void tabletUpdateCursor(QTabletDeviceData &tdd, const UINT currentCursor);
-static void initWinTabFunctions(); // resolve the WINTAB api functions
-#endif // QT_NO_TABLETEVENT
-
-
-#ifndef QT_NO_ACCESSIBILITY
-extern IAccessible *qt_createWindowsAccessible(QAccessibleInterface *object);
-#endif // QT_NO_ACCESSIBILITY
-
-extern bool qt_tabletChokeMouse;
-extern QWidget* qt_get_tablet_widget();
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-extern QRegion qt_dirtyRegion(QWidget *);
-
-typedef QHash<quint64, QTabletDeviceData> QTabletCursorInfo;
-Q_GLOBAL_STATIC(QTabletCursorInfo, tCursorInfo)
-QTabletDeviceData currentTabletPointer;
-
-// from qregion_win.cpp
-extern HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom);
-
-// support for on-the-fly changes of the XP theme engine
-#ifndef WM_THEMECHANGED
-#define WM_THEMECHANGED 0x031A
-#endif
-#ifndef COLOR_MENUHILIGHT
-#define COLOR_MENUHILIGHT 29
-#define COLOR_MENUBAR 30
-#endif
-
-// support for xbuttons
-#ifndef WM_XBUTTONDOWN
-#define WM_XBUTTONDOWN 0x020B
-#define WM_XBUTTONUP 0x020C
-#define WM_XBUTTONDBLCLK 0x020D
-#endif
-#ifndef GET_KEYSTATE_WPARAM
-#define GET_KEYSTATE_WPARAM(wParam) (LOWORD(wParam))
-#define GET_XBUTTON_WPARAM(wParam) (HIWORD(wParam))
-#define XBUTTON1 0x0001
-#define XBUTTON2 0x0002
-#endif
-#ifndef MK_XBUTTON1
-#define MK_XBUTTON1 0x0020
-#define MK_XBUTTON2 0x0040
-#endif
-
-// support for multi-media-keys
-#ifndef WM_APPCOMMAND
-#define WM_APPCOMMAND 0x0319
-#endif
-
-#ifndef FAPPCOMMAND_MOUSE
-#define FAPPCOMMAND_MOUSE 0x8000
-#define FAPPCOMMAND_KEY 0
-#define FAPPCOMMAND_OEM 0x1000
-#define FAPPCOMMAND_MASK 0xF000
-#define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK))
-#define GET_DEVICE_LPARAM(lParam) ((WORD)(HIWORD(lParam) & FAPPCOMMAND_MASK))
-#define GET_MOUSEORKEY_LPARAM GET_DEVICE_LPARAM
-#define GET_FLAGS_LPARAM(lParam) (LOWORD(lParam))
-#define GET_KEYSTATE_LPARAM(lParam) GET_FLAGS_LPARAM(lParam)
-
-#define APPCOMMAND_BROWSER_BACKWARD 1
-#define APPCOMMAND_BROWSER_FORWARD 2
-#define APPCOMMAND_BROWSER_REFRESH 3
-#define APPCOMMAND_BROWSER_STOP 4
-#define APPCOMMAND_BROWSER_SEARCH 5
-#define APPCOMMAND_BROWSER_FAVORITES 6
-#define APPCOMMAND_BROWSER_HOME 7
-#define APPCOMMAND_VOLUME_MUTE 8
-#define APPCOMMAND_VOLUME_DOWN 9
-#define APPCOMMAND_VOLUME_UP 10
-#define APPCOMMAND_MEDIA_NEXTTRACK 11
-#define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
-#define APPCOMMAND_MEDIA_STOP 13
-#define APPCOMMAND_MEDIA_PLAY_PAUSE 14
-#define APPCOMMAND_LAUNCH_MAIL 15
-#define APPCOMMAND_LAUNCH_MEDIA_SELECT 16
-#define APPCOMMAND_LAUNCH_APP1 17
-#define APPCOMMAND_LAUNCH_APP2 18
-#define APPCOMMAND_BASS_DOWN 19
-#define APPCOMMAND_BASS_BOOST 20
-#define APPCOMMAND_BASS_UP 21
-#define APPCOMMAND_TREBLE_DOWN 22
-#define APPCOMMAND_TREBLE_UP 23
-#endif // FAPPCOMMAND_MOUSE
-
-// New commands from Windows XP (some even Sp1)
-#ifndef APPCOMMAND_MICROPHONE_VOLUME_MUTE
-#define APPCOMMAND_MICROPHONE_VOLUME_MUTE 24
-#define APPCOMMAND_MICROPHONE_VOLUME_DOWN 25
-#define APPCOMMAND_MICROPHONE_VOLUME_UP 26
-#define APPCOMMAND_HELP 27
-#define APPCOMMAND_FIND 28
-#define APPCOMMAND_NEW 29
-#define APPCOMMAND_OPEN 30
-#define APPCOMMAND_CLOSE 31
-#define APPCOMMAND_SAVE 32
-#define APPCOMMAND_PRINT 33
-#define APPCOMMAND_UNDO 34
-#define APPCOMMAND_REDO 35
-#define APPCOMMAND_COPY 36
-#define APPCOMMAND_CUT 37
-#define APPCOMMAND_PASTE 38
-#define APPCOMMAND_REPLY_TO_MAIL 39
-#define APPCOMMAND_FORWARD_MAIL 40
-#define APPCOMMAND_SEND_MAIL 41
-#define APPCOMMAND_SPELL_CHECK 42
-#define APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE 43
-#define APPCOMMAND_MIC_ON_OFF_TOGGLE 44
-#define APPCOMMAND_CORRECTION_LIST 45
-#define APPCOMMAND_MEDIA_PLAY 46
-#define APPCOMMAND_MEDIA_PAUSE 47
-#define APPCOMMAND_MEDIA_RECORD 48
-#define APPCOMMAND_MEDIA_FAST_FORWARD 49
-#define APPCOMMAND_MEDIA_REWIND 50
-#define APPCOMMAND_MEDIA_CHANNEL_UP 51
-#define APPCOMMAND_MEDIA_CHANNEL_DOWN 52
-#endif // APPCOMMAND_MICROPHONE_VOLUME_MUTE
-
-#if (_WIN32_WINNT < 0x0400)
-// This struct is defined in winuser.h if the _WIN32_WINNT >= 0x0400 -- in the
-// other cases we have to define it on our own.
-typedef struct tagTRACKMOUSEEVENT {
- DWORD cbSize;
- DWORD dwFlags;
- HWND hwndTrack;
- DWORD dwHoverTime;
-} TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;
-#endif
-#ifndef WM_MOUSELEAVE
-#define WM_MOUSELEAVE 0x02A3
-#endif
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "private/qwidget_p.h"
-QT_END_INCLUDE_NAMESPACE
-
-static int translateButtonState(int s, int type, int button);
-
-// ##### get rid of this!
-QRgb qt_colorref2qrgb(COLORREF col)
-{
- return qRgb(GetRValue(col),GetGValue(col),GetBValue(col));
-}
-
-
-/*****************************************************************************
- Internal variables and functions
- *****************************************************************************/
-
-static HWND curWin = 0; // current window
-static HDC displayDC = 0; // display device context
-
-// Session management
-static bool sm_blockUserInput = false;
-static bool sm_smActive = false;
-extern QSessionManager* qt_session_manager_self;
-static bool sm_cancel;
-
-static bool replayPopupMouseEvent = false; // replay handling when popups close
-
-// ignore the next release event if return from a modal widget
-Q_GUI_EXPORT bool qt_win_ignoreNextMouseReleaseEvent = false;
-
-
-#if defined(QT_DEBUG)
-static bool appNoGrab = false; // mouse/keyboard grabbing
-#endif
-
-static bool app_do_modal = false; // modal mode
-extern QWidgetList *qt_modal_stack;
-extern QDesktopWidget *qt_desktopWidget;
-static QPointer<QWidget> popupButtonFocus;
-static bool qt_try_modal(QWidget *, MSG *, int& ret);
-
-QWidget *qt_button_down = 0; // widget got last button-down
-QPointer<QWidget> qt_last_mouse_receiver = 0;
-
-static HWND autoCaptureWnd = 0;
-static HWND imeParentWnd = 0;
-static void setAutoCapture(HWND); // automatic capture
-static void releaseAutoCapture();
-
-static void unregWinClasses();
-
-extern QCursor *qt_grab_cursor();
-
-#if defined(Q_WS_WIN)
-#define __export
-#endif
-
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-class QETWidget : public QWidget // event translator widget
-{
-public:
- QWExtra *xtra() { return d_func()->extraData(); }
- QTLWExtra *topData() { return d_func()->topData(); }
- QTLWExtra *maybeTopData() { return d_func()->maybeTopData(); }
- void syncBackingStore(const QRegion &rgn) { d_func()->syncBackingStore(rgn); }
- void syncBackingStore() { d_func()->syncBackingStore(); }
- QWidgetData *dataPtr() { return data; }
- QWidgetPrivate *dptr() { return d_func(); }
- QRect frameStrut() const { return d_func()->frameStrut(); }
- bool winEvent(MSG *m, long *r) { return QWidget::winEvent(m, r); }
- void markFrameStrutDirty() { data->fstrut_dirty = 1; }
- bool translateMouseEvent(const MSG &msg);
- bool translateWheelEvent(const MSG &msg);
- bool translatePaintEvent(const MSG &msg);
- bool translateConfigEvent(const MSG &msg);
- bool translateCloseEvent(const MSG &msg);
- bool translateTabletEvent(const MSG &msg, PACKET *localPacketBuf, int numPackets);
-#ifndef QT_NO_GESTURES
- bool translateGestureEvent(const MSG &msg, const GESTUREINFO &gi);
-#endif
- void repolishStyle(QStyle &style);
- inline void showChildren(bool spontaneous) { d_func()->showChildren(spontaneous); }
- inline void hideChildren(bool spontaneous) { d_func()->hideChildren(spontaneous); }
- inline uint testWindowState(uint teststate){ return dataPtr()->window_state & teststate; }
- inline void setWindowTitle_helper(const QString &title) { d_func()->setWindowTitle_helper(title); }
- inline void forceUpdate() {
- QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
- if (tlwExtra && tlwExtra->backingStore)
- tlwExtra->backingStore->markDirty(rect(), this, true, true);
- }
-};
-
-// need to get default font?
-extern bool qt_app_has_font;
-
-extern QFont qt_LOGFONTtoQFont(LOGFONT& lf,bool scale);
-
-static void qt_set_windows_color_resources()
-{
- // Do the color settings
- QPalette pal;
- pal.setColor(QPalette::WindowText,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOWTEXT))));
- pal.setColor(QPalette::Button,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNFACE))));
- pal.setColor(QPalette::Light,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNHIGHLIGHT))));
- pal.setColor(QPalette::Dark,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNSHADOW))));
- pal.setColor(QPalette::Mid, pal.button().color().darker(150));
- pal.setColor(QPalette::Text,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOWTEXT))));
- pal.setColor(QPalette::BrightText,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNHIGHLIGHT))));
- pal.setColor(QPalette::Base,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOW))));
- pal.setColor(QPalette::Window,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNFACE))));
- pal.setColor(QPalette::ButtonText,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNTEXT))));
- pal.setColor(QPalette::Midlight,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_3DLIGHT))));
- pal.setColor(QPalette::Shadow,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_3DDKSHADOW))));
- pal.setColor(QPalette::Highlight,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHT))));
- pal.setColor(QPalette::HighlightedText,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHTTEXT))));
-
-#if defined(Q_WS_WINCE)
- // ### hardcoded until I find out how to get it from the system settings.
- pal.setColor(QPalette::LinkVisited, pal.highlight().color().dark(150));
- pal.setColor(QPalette::Link, pal.highlight().color().light(130));
- // Background == Base on Windows CE
- if (qt_wince_is_smartphone() || qt_wince_is_pocket_pc())
- pal.setColor(QPalette::Background, pal.base().color());
-#else
- pal.setColor(QPalette::Link, Qt::blue);
- pal.setColor(QPalette::LinkVisited, Qt::magenta);
-#endif
-
-
-
- pal.setColor(QPalette::Inactive, QPalette::Button, pal.button().color());
- pal.setColor(QPalette::Inactive, QPalette::Window, pal.background().color());
- pal.setColor(QPalette::Inactive, QPalette::Light, pal.light().color());
- pal.setColor(QPalette::Inactive, QPalette::Dark, pal.dark().color());
-
- if (pal.midlight() == pal.button())
- pal.setColor(QPalette::Midlight, pal.button().color().lighter(110));
- if (pal.background() != pal.base()) {
- pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Inactive, QPalette::Window));
- pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Inactive, QPalette::Text));
- }
-
- const QColor bg = pal.background().color();
- const QColor fg = pal.foreground().color(), btn = pal.button().color();
- QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2,
- (fg.blue()+btn.blue())/2);
- pal.setColorGroup(QPalette::Disabled, pal.foreground(), pal.button(), pal.light(),
- pal.dark(), pal.mid(), pal.text(), pal.brightText(), pal.base(), pal.background() );
- pal.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
- pal.setColor(QPalette::Disabled, QPalette::Text, disabled);
- pal.setColor(QPalette::Disabled, QPalette::ButtonText, disabled);
- pal.setColor(QPalette::Disabled, QPalette::Highlight,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHT))));
- pal.setColor(QPalette::Disabled, QPalette::HighlightedText,
- QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHTTEXT))));
- pal.setColor(QPalette::Disabled, QPalette::Base, bg);
-
- QApplicationPrivate::setSystemPalette(pal);
-
- QApplicationPrivate::initializeWidgetPaletteHash();
-
- QColor ttip(qt_colorref2qrgb(GetSysColor(COLOR_INFOBK)));
-
- QColor ttipText(qt_colorref2qrgb(GetSysColor(COLOR_INFOTEXT)));
- {
-#ifndef QT_NO_TOOLTIP
- QPalette tiplabel(pal);
- tiplabel.setColor(QPalette::All, QPalette::Button, ttip);
- tiplabel.setColor(QPalette::All, QPalette::Window, ttip);
- tiplabel.setColor(QPalette::All, QPalette::Text, ttipText);
- tiplabel.setColor(QPalette::All, QPalette::WindowText, ttipText);
- tiplabel.setColor(QPalette::All, QPalette::ButtonText, ttipText);
- tiplabel.setColor(QPalette::All, QPalette::Button, ttip);
- tiplabel.setColor(QPalette::All, QPalette::Window, ttip);
- tiplabel.setColor(QPalette::All, QPalette::Text, ttipText);
- tiplabel.setColor(QPalette::All, QPalette::WindowText, ttipText);
- tiplabel.setColor(QPalette::All, QPalette::ButtonText, ttipText);
- const QColor fg = tiplabel.foreground().color(), btn = tiplabel.button().color();
- QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2,
- (fg.blue()+btn.blue())/2);
- tiplabel.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
- tiplabel.setColor(QPalette::Disabled, QPalette::Text, disabled);
- tiplabel.setColor(QPalette::Disabled, QPalette::Base, Qt::white);
- tiplabel.setColor(QPalette::Disabled, QPalette::BrightText, Qt::white);
- QToolTip::setPalette(tiplabel);
-#endif //QT_NO_TOOLTIP
- }
-}
-
-static void qt_set_windows_font_resources()
-{
-#ifndef Q_WS_WINCE
- NONCLIENTMETRICS ncm;
- ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT);
- SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize , &ncm, 0);
-
- QFont menuFont = qt_LOGFONTtoQFont(ncm.lfMenuFont, true);
- QFont messageFont = qt_LOGFONTtoQFont(ncm.lfMessageFont, true);
- QFont statusFont = qt_LOGFONTtoQFont(ncm.lfStatusFont, true);
- QFont titleFont = qt_LOGFONTtoQFont(ncm.lfCaptionFont, true);
-
- LOGFONT lfIconTitleFont;
- SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIconTitleFont), &lfIconTitleFont, 0);
- QFont iconTitleFont = qt_LOGFONTtoQFont(lfIconTitleFont, true);
-
- QApplication::setFont(menuFont, "QMenu");
- QApplication::setFont(menuFont, "QMenuBar");
- QApplication::setFont(messageFont, "QMessageBox");
- QApplication::setFont(statusFont, "QTipLabel");
- QApplication::setFont(statusFont, "QStatusBar");
- QApplication::setFont(titleFont, "Q3TitleBar");
- QApplication::setFont(titleFont, "QWorkspaceTitleBar");
- QApplication::setFont(iconTitleFont, "QAbstractItemView");
- QApplication::setFont(iconTitleFont, "QDockWidgetTitle");
-
-#else
- LOGFONT lf;
- HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT);
- GetObject(stockFont, sizeof(lf), &lf);
- QFont systemFont = qt_LOGFONTtoQFont(lf, true);
- QApplicationPrivate::setSystemFont(systemFont);
- QFont smallerFont = systemFont;
- if (qt_wince_is_mobile()) {
- smallerFont.setPointSize(systemFont.pointSize()-1);
- QApplication::setFont(smallerFont, "QTabBar");
- smallerFont.setBold(true);
- QApplication::setFont(smallerFont, "QAbstractButton");
- }
-#endif// Q_WS_WINCE
-}
-
-static void qt_win_read_cleartype_settings()
-{
- UINT result = 0;
-#ifdef Q_OS_WINCE
- if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &result, 0))
- qt_cleartype_enabled = result;
-#else
- if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0))
- qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE);
-#endif
-
- int winSmooth;
- if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0)) {
- qt_fontsmoothing_gamma = winSmooth / qreal(1000.0);
- } else {
- qt_fontsmoothing_gamma = 1.0;
- }
-
- // Safeguard ourselves against corrupt registry values...
- if (qt_fontsmoothing_gamma > 5 || qt_fontsmoothing_gamma < 1)
- qt_fontsmoothing_gamma = qreal(1.4);
-}
-
-static void qt_set_windows_resources()
-{
- if (QApplication::type() != QApplication::Tty)
- (void) QApplication::style(); // trigger creation of application style
- qt_set_windows_font_resources();
- qt_set_windows_color_resources();
-}
-
-void QApplicationPrivate::initializeWidgetPaletteHash()
-{
- QPalette pal = *QApplicationPrivate::sys_pal;
- QColor menuCol(qt_colorref2qrgb(GetSysColor(COLOR_MENU)));
- QColor menuText(qt_colorref2qrgb(GetSysColor(COLOR_MENUTEXT)));
- BOOL isFlat = false;
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- SystemParametersInfo(SPI_GETFLATMENU, 0, &isFlat, 0);
- QPalette menu(pal);
- // we might need a special color group for the menu.
- menu.setColor(QPalette::Active, QPalette::Button, menuCol);
- menu.setColor(QPalette::Active, QPalette::Text, menuText);
- menu.setColor(QPalette::Active, QPalette::WindowText, menuText);
- menu.setColor(QPalette::Active, QPalette::ButtonText, menuText);
- const QColor fg = menu.foreground().color(), btn = menu.button().color();
- QColor disabled(qt_colorref2qrgb(GetSysColor(COLOR_GRAYTEXT)));
- menu.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
- menu.setColor(QPalette::Disabled, QPalette::Text, disabled);
- menu.setColor(QPalette::Disabled, QPalette::Highlight,
- QColor(qt_colorref2qrgb(GetSysColor(
- (QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
- && isFlat ? COLOR_MENUHILIGHT : COLOR_HIGHLIGHT))));
- menu.setColor(QPalette::Disabled, QPalette::HighlightedText, disabled);
- menu.setColor(QPalette::Disabled, QPalette::Button,
- menu.color(QPalette::Active, QPalette::Button));
- menu.setColor(QPalette::Inactive, QPalette::Button,
- menu.color(QPalette::Active, QPalette::Button));
- menu.setColor(QPalette::Inactive, QPalette::Text,
- menu.color(QPalette::Active, QPalette::Text));
- menu.setColor(QPalette::Inactive, QPalette::WindowText,
- menu.color(QPalette::Active, QPalette::WindowText));
- menu.setColor(QPalette::Inactive, QPalette::ButtonText,
- menu.color(QPalette::Active, QPalette::ButtonText));
- menu.setColor(QPalette::Inactive, QPalette::Highlight,
- menu.color(QPalette::Active, QPalette::Highlight));
- menu.setColor(QPalette::Inactive, QPalette::HighlightedText,
- menu.color(QPalette::Active, QPalette::HighlightedText));
- menu.setColor(QPalette::Inactive, QPalette::ButtonText,
- pal.color(QPalette::Inactive, QPalette::Dark));
- QApplication::setPalette(menu, "QMenu");
-
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based) && isFlat) {
- QColor menubar(qt_colorref2qrgb(GetSysColor(COLOR_MENUBAR)));
- menu.setColor(QPalette::Active, QPalette::Button, menubar);
- menu.setColor(QPalette::Disabled, QPalette::Button, menubar);
- menu.setColor(QPalette::Inactive, QPalette::Button, menubar);
- }
- QApplication::setPalette(menu, "QMenuBar");
-}
-
-static void qt_set_windows_updateScrollBar(QWidget *widget)
-{
- QList<QObject*> children = widget->children();
- for (int i = 0; i < children.size(); ++i) {
- QObject *o = children.at(i);
- if(!o->isWidgetType())
- continue;
- if (QWidget *w = static_cast<QWidget *>(o))
- qt_set_windows_updateScrollBar(w);
- }
-#ifndef QT_NO_SCROLLBAR
- if (qobject_cast<QScrollBar*>(widget))
- widget->updateGeometry();
-#endif
-}
-
-
-/*****************************************************************************
- qt_init() - initializes Qt for Windows
- *****************************************************************************/
-
-typedef BOOL (WINAPI *PtrSetProcessDPIAware) (VOID);
-static PtrSetProcessDPIAware ptrSetProcessDPIAware = 0;
-PtrUpdateLayeredWindow ptrUpdateLayeredWindow = 0;
-PtrUpdateLayeredWindowIndirect ptrUpdateLayeredWindowIndirect = 0;
-static BOOL WINAPI qt_updateLayeredWindowIndirect(HWND hwnd, const Q_UPDATELAYEREDWINDOWINFO *info)
-{
- return (*ptrUpdateLayeredWindow)(hwnd, info->hdcDst, info->pptDst, info->psize, info->hdcSrc,
- info->pptSrc, info->crKey, info->pblend, info->dwFlags);
-}
-
-void qt_init(QApplicationPrivate *priv, int)
-{
-
- int argc = priv->argc;
- char **argv = priv->argv;
- int i, j;
-
- // Get command line params
-
- j = argc ? 1 : 0;
- for (i=1; i<argc; i++) {
- if (argv[i] && *argv[i] != '-') {
- argv[j++] = argv[i];
- continue;
- }
-#if defined(QT_DEBUG)
- if (qstrcmp(argv[i], "-nograb") == 0)
- appNoGrab = !appNoGrab;
- else
-#endif // QT_DEBUG
- argv[j++] = argv[i];
- }
- if(j < priv->argc) {
- priv->argv[j] = 0;
- priv->argc = j;
- }
-
-#ifndef Q_WS_WINCE
- // No message boxes but important ones
- SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
-#endif
-
-#ifndef Q_WS_WINCE
- // Initialize OLE/COM
- // S_OK means success and S_FALSE means that it has already
- // been initialized
- HRESULT r;
- r = OleInitialize(0);
- if (r != S_OK && r != S_FALSE) {
- qWarning("Qt: Could not initialize OLE (error %x)", (unsigned int)r);
- }
-#endif
-
- // Misc. initialization
-#if defined(QT_DEBUG) && !defined(Q_WS_WINCE)
- GdiSetBatchLimit(1);
-#endif
-
- // initialize key mapper
- QKeyMapper::changeKeyboard();
-
- QColormap::initialize();
- QFont::initialize();
-#ifndef QT_NO_CURSOR
- QCursorData::initialize();
-#endif
- qApp->setObjectName(priv->appName());
-
- // default font
-#ifndef Q_WS_WINCE
- HGDIOBJ stockFont = GetStockObject(DEFAULT_GUI_FONT);
-#else
- HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT);
-#endif
-
- LOGFONT lf;
- GetObject(stockFont, sizeof(lf), &lf);
- QFont systemFont = qt_LOGFONTtoQFont(lf, true);
-
-#ifndef Q_WS_WINCE
- if (systemFont.family() == QLatin1String("MS Shell Dlg")) {
- systemFont.setFamily(QLatin1String("MS Shell Dlg 2"));
- }
-#endif
-
- QApplicationPrivate::setSystemFont(systemFont);
-
- // QFont::locale_init(); ### Uncomment when it does something on Windows
-
- if (QApplication::desktopSettingsAware())
- qt_set_windows_resources();
-
-#ifndef QT_NO_TABLETEVENT
- initWinTabFunctions();
-#endif // QT_NO_TABLETEVENT
- QApplicationPrivate::inputContext = new QWinInputContext(0);
-
- // Read the initial cleartype settings...
- qt_win_read_cleartype_settings();
- qt_win_owndc_required = false;
-
- extern void qt_win_initialize_directdraw();
- qt_win_initialize_directdraw();
-
-#ifndef Q_OS_WINCE
- ptrUpdateLayeredWindowIndirect =
- (PtrUpdateLayeredWindowIndirect) QSystemLibrary::resolve(QLatin1String("user32"),
- "UpdateLayeredWindowIndirect");
- ptrUpdateLayeredWindow =
- (PtrUpdateLayeredWindow) QSystemLibrary::resolve(QLatin1String("user32"),
- "UpdateLayeredWindow");
-
- if (ptrUpdateLayeredWindow && !ptrUpdateLayeredWindowIndirect)
- ptrUpdateLayeredWindowIndirect = qt_updateLayeredWindowIndirect;
-
- // Notify Vista and Windows 7 that we support highter DPI settings
- ptrSetProcessDPIAware = (PtrSetProcessDPIAware)
- QSystemLibrary::resolve(QLatin1String("user32"), "SetProcessDPIAware");
- if (ptrSetProcessDPIAware)
- ptrSetProcessDPIAware();
-#endif
-
-#ifndef QT_NO_GESTURES
- priv->GetGestureInfo = 0;
- priv->GetGestureExtraArgs = 0;
- priv->CloseGestureInfoHandle = 0;
- priv->SetGestureConfig = 0;
- priv->GetGestureConfig = 0;
- priv->BeginPanningFeedback = 0;
- priv->UpdatePanningFeedback = 0;
- priv->EndPanningFeedback = 0;
-
-#if defined(Q_WS_WINCE_WM) && defined(QT_WINCE_GESTURES)
- priv->GetGestureInfo = (PtrGetGestureInfo) &TKGetGestureInfo;
- priv->GetGestureExtraArgs = (PtrGetGestureExtraArgs) &TKGetGestureExtraArguments;
-#elif !defined(Q_WS_WINCE)
- #if !defined(QT_NO_NATIVE_GESTURES)
- priv->GetGestureInfo =
- (PtrGetGestureInfo)QSystemLibrary::resolve(QLatin1String("user32"),
- "GetGestureInfo");
- priv->GetGestureExtraArgs =
- (PtrGetGestureExtraArgs)QSystemLibrary::resolve(QLatin1String("user32"),
- "GetGestureExtraArgs");
- priv->CloseGestureInfoHandle =
- (PtrCloseGestureInfoHandle)QSystemLibrary::resolve(QLatin1String("user32"),
- "CloseGestureInfoHandle");
- priv->SetGestureConfig =
- (PtrSetGestureConfig)QSystemLibrary::resolve(QLatin1String("user32"),
- "SetGestureConfig");
- priv->GetGestureConfig =
- (PtrGetGestureConfig)QSystemLibrary::resolve(QLatin1String("user32"),
- "GetGestureConfig");
- #endif // QT_NO_NATIVE_GESTURES
- QSystemLibrary libTheme(QLatin1String("uxtheme"));
- priv->BeginPanningFeedback =
- (PtrBeginPanningFeedback)libTheme.resolve("BeginPanningFeedback");
- priv->UpdatePanningFeedback =
- (PtrUpdatePanningFeedback)libTheme.resolve("UpdatePanningFeedback");
- priv->EndPanningFeedback =
- (PtrEndPanningFeedback)libTheme.resolve("EndPanningFeedback");
-#endif
-#endif // QT_NO_GESTURES
-}
-
-/*****************************************************************************
- qt_cleanup() - cleans up when the application is finished
- *****************************************************************************/
-
-void qt_cleanup()
-{
- unregWinClasses();
- QPixmapCache::clear();
-
-#ifndef QT_NO_CURSOR
- QCursorData::cleanup();
-#endif
- QFont::cleanup();
- QColormap::cleanup();
- if (displayDC) {
- ReleaseDC(0, displayDC);
- displayDC = 0;
- }
-
- delete QApplicationPrivate::inputContext;
- QApplicationPrivate::inputContext = 0;
-
-#ifndef Q_WS_WINCE
- // Deinitialize OLE/COM
- OleUninitialize();
-#endif
-}
-
-
-/*****************************************************************************
- Platform specific global and internal functions
- *****************************************************************************/
-
-Q_GUI_EXPORT HDC qt_win_display_dc() // get display DC
-{
- Q_ASSERT(qApp && qApp->thread() == QThread::currentThread());
- if (!displayDC)
- displayDC = GetDC(0);
- return displayDC;
-}
-
-bool qt_nograb() // application no-grab option
-{
-#if defined(QT_DEBUG)
- return appNoGrab;
-#else
- return false;
-#endif
-}
-
-typedef QHash<QString, int> WinClassNameHash;
-Q_GLOBAL_STATIC(WinClassNameHash, winclassNames)
-
-//
-// If 0 is passed as the widget pointer, register a window class
-// for QWidget as default. This is used in QGLTemporaryContext
-// during GL initialization, where we don't want to use temporary
-// QWidgets or QGLWidgets, neither do we want to have separate code
-// to register window classes.
-//
-const QString qt_reg_winclass(QWidget *w) // register window class
-{
- Qt::WindowFlags flags = w ? w->windowFlags() : (Qt::WindowFlags)0;
- Qt::WindowFlags type = flags & Qt::WindowType_Mask;
-
- uint style;
- bool icon;
- QString cname;
- if (w && qt_widget_private(w)->isGLWidget) {
- cname = QLatin1String("QGLWidget");
- style = CS_DBLCLKS;
-#ifndef Q_WS_WINCE
- style |= CS_OWNDC;
-#endif
- icon = true;
- } else if (w && (flags & Qt::MSWindowsOwnDC)) {
- cname = QLatin1String("QWidgetOwnDC");
- style = CS_DBLCLKS;
-#ifndef Q_WS_WINCE
- style |= CS_OWNDC;
-#endif
- icon = true;
- } else if (w && (type == Qt::Tool || type == Qt::ToolTip)) {
- style = CS_DBLCLKS;
- if (w->inherits("QTipLabel") || w->inherits("QAlphaWidget")) {
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) {
- style |= CS_DROPSHADOW;
- }
- cname = QLatin1String("QToolTip");
- } else {
- cname = QLatin1String("QTool");
- }
-#ifndef Q_WS_WINCE
- style |= CS_SAVEBITS;
-#endif
- icon = false;
- } else if (w && (type == Qt::Popup)) {
- cname = QLatin1String("QPopup");
- style = CS_DBLCLKS;
-#ifndef Q_WS_WINCE
- style |= CS_SAVEBITS;
-#endif
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- style |= CS_DROPSHADOW;
- icon = false;
- } else {
- cname = QLatin1String("QWidget");
- style = CS_DBLCLKS;
- icon = true;
- }
-
-#ifndef Q_WS_WINCE
- // force CS_OWNDC when the GL graphics system is
- // used as the default renderer
- if (qt_win_owndc_required)
- style |= CS_OWNDC;
-#endif
-
-#ifdef Q_OS_WINCE
- // We need to register the classes with the
- // unique ID on WinCE to make sure we can
- // move the windows to the front when starting
- // a second instance.
- wchar_t uniqueAppID[MAX_PATH];
- GetModuleFileName(0, uniqueAppID, MAX_PATH);
- cname = QString::number(RegisterWindowMessage(
- (const wchar_t *) QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1Char('\\'),
- QLatin1Char('_')).utf16()));
-#endif
-
- // since multiple Qt versions can be used in one process
- // each one has to have window class names with a unique name
- // The first instance gets the unmodified name; if the class
- // has already been registered by another instance of Qt then
- // add an instance-specific ID, the address of the window proc.
- static int classExists = -1;
-
- if (classExists == -1) {
- WNDCLASS wcinfo;
- classExists = GetClassInfo((HINSTANCE)qWinAppInst(), (wchar_t*)cname.utf16(), &wcinfo);
- classExists = classExists && wcinfo.lpfnWndProc != QtWndProc;
- }
-
- if (classExists)
- cname += QString::number((quintptr)QtWndProc);
-
- if (winclassNames()->contains(cname)) // already registered in our list
- return cname;
-
-#ifndef Q_WS_WINCE
- WNDCLASSEX wc;
- wc.cbSize = sizeof(WNDCLASSEX);
-#else
- WNDCLASS wc;
-#endif
- wc.style = style;
- wc.lpfnWndProc = (WNDPROC)QtWndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = qWinAppInst();
- if (icon) {
- wc.hIcon = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
-#ifndef Q_WS_WINCE
- if (wc.hIcon) {
- int sw = GetSystemMetrics(SM_CXSMICON);
- int sh = GetSystemMetrics(SM_CYSMICON);
- wc.hIconSm = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, sw, sh, 0);
- } else {
- wc.hIcon = (HICON)LoadImage(0, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
- wc.hIconSm = 0;
- }
-#endif
- } else {
- wc.hIcon = 0;
-#ifndef Q_WS_WINCE
- wc.hIconSm = 0;
-#endif
- }
- wc.hCursor = 0;
-#ifndef Q_WS_WINCE
- HBRUSH brush = 0;
- if (w && !qt_widget_private(w)->isGLWidget)
- brush = (HBRUSH)GetSysColorBrush(COLOR_WINDOW);
- wc.hbrBackground = brush;
-#else
- wc.hbrBackground = 0;
-#endif
- wc.lpszMenuName = 0;
- wc.lpszClassName = (wchar_t*)cname.utf16();
-
-#ifndef Q_WS_WINCE
- ATOM atom = RegisterClassEx(&wc);
-#else
- ATOM atom = RegisterClass(&wc);
-#endif
-
-#ifndef QT_NO_DEBUG
- if (!atom)
- qErrnoWarning("QApplication::regClass: Registering window class failed.");
-#else
- Q_UNUSED(atom);
-#endif
-
- winclassNames()->insert(cname, 1);
- return cname;
-}
-
-Q_GUI_EXPORT const QString qt_getRegisteredWndClass()
-{
- return qt_reg_winclass(0);
-}
-
-static void unregWinClasses()
-{
- WinClassNameHash *hash = winclassNames();
- QHash<QString, int>::ConstIterator it = hash->constBegin();
- while (it != hash->constEnd()) {
- UnregisterClass((wchar_t*)it.key().utf16(), qWinAppInst());
- ++it;
- }
- hash->clear();
-}
-
-
-/*****************************************************************************
- Safe configuration (move,resize,setGeometry) mechanism to avoid
- recursion when processing messages.
- *****************************************************************************/
-
-struct QWinConfigRequest {
- WId id; // widget to be configured
- int req; // 0=move, 1=resize, 2=setGeo
- int x, y, w, h; // request parameters
-};
-
-static QList<QWinConfigRequest*> *configRequests = 0;
-
-void qWinRequestConfig(WId id, int req, int x, int y, int w, int h)
-{
- if (!configRequests) // create queue
- configRequests = new QList<QWinConfigRequest*>;
- QWinConfigRequest *r = new QWinConfigRequest;
- r->id = id; // create new request
- r->req = req;
- r->x = x;
- r->y = y;
- r->w = w;
- r->h = h;
- configRequests->append(r); // store request in queue
-}
-
-static void qWinProcessConfigRequests() // perform requests in queue
-{
- if (!configRequests)
- return;
- QWinConfigRequest *r;
- for (;;) {
- if (configRequests->isEmpty())
- break;
- r = configRequests->takeLast();
- QWidget *w = QWidget::find(r->id);
- QRect rect(r->x, r->y, r->w, r->h);
- int req = r->req;
- delete r;
-
- if ( w ) { // widget exists
- if (w->testAttribute(Qt::WA_WState_ConfigPending))
- return; // biting our tail
- if (req == 0)
- w->move(rect.topLeft());
- else if (req == 1)
- w->resize(rect.size());
- else
- w->setGeometry(rect);
- }
- }
- delete configRequests;
- configRequests = 0;
-}
-
-
-/*****************************************************************************
- GUI event dispatcher
- *****************************************************************************/
-
-class QGuiEventDispatcherWin32 : public QEventDispatcherWin32
-{
- Q_DECLARE_PRIVATE(QEventDispatcherWin32)
-public:
- QGuiEventDispatcherWin32(QObject *parent = 0);
- bool processEvents(QEventLoop::ProcessEventsFlags flags);
-};
-
-QGuiEventDispatcherWin32::QGuiEventDispatcherWin32(QObject *parent)
- : QEventDispatcherWin32(parent)
-{
- createInternalHwnd();
-}
-
-bool QGuiEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
- if (!QEventDispatcherWin32::processEvents(flags))
- return false;
-
- if (configRequests) // any pending configs?
- qWinProcessConfigRequests();
-
- return true;
-}
-
-void QApplicationPrivate::createEventDispatcher()
-{
- Q_Q(QApplication);
- if (q->type() != QApplication::Tty)
- eventDispatcher = new QGuiEventDispatcherWin32(q);
- else
- eventDispatcher = new QEventDispatcherWin32(q);
-}
-
-/*****************************************************************************
- Platform specific QApplication members
- *****************************************************************************/
-
-#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);
- SetCursor(qApp->d_func()->cursor_list.first().handle());
-}
-
-void QApplication::restoreOverrideCursor()
-{
- if (qApp->d_func()->cursor_list.isEmpty())
- return;
- qApp->d_func()->cursor_list.removeFirst();
-
- if (!qApp->d_func()->cursor_list.isEmpty()) {
- SetCursor(qApp->d_func()->cursor_list.first().handle());
- } else {
- QWidget *w = QWidget::find(curWin);
- if (w)
- SetCursor(w->cursor().handle());
- else
- SetCursor(QCursor(Qt::ArrowCursor).handle());
- }
-}
-
-#endif
-
-/*
- Internal function called from QWidget::setCursor()
- force is true if this function is called from dispatchEnterLeave, it means that the
- mouse is actually directly under this widget.
-*/
-
-#ifndef QT_NO_CURSOR
-void qt_win_set_cursor(QWidget *w, bool force)
-{
- static QPointer<QWidget> lastUnderMouse = 0;
- if (force) {
- lastUnderMouse = w;
- } else if (w->testAttribute(Qt::WA_WState_Created) && lastUnderMouse
- && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
- w = lastUnderMouse;
- }
-
- if (!curWin && w && w->internalWinId())
- return;
- QWidget* cW = w && !w->internalWinId() ? w : QWidget::find(curWin);
- if (!cW || cW->window() != w->window() ||
- !cW->isVisible() || !cW->underMouse() || QApplication::overrideCursor())
- return;
-
- SetCursor(cW->cursor().handle());
-}
-#endif // QT_NO_CURSOR
-
-Qt::KeyboardModifiers qt_win_getKeyboardModifiers()
-{
- Qt::KeyboardModifiers modifiers = Qt::NoModifier;
- if (GetKeyState(VK_SHIFT) < 0)
- modifiers |= Qt::ShiftModifier;
- if (GetKeyState(VK_CONTROL) < 0)
- modifiers |= Qt::ControlModifier;
- if (GetKeyState(VK_MENU) < 0)
- modifiers |= Qt::AltModifier;
- return modifiers;
-}
-
-/*****************************************************************************
- Routines to find a Qt widget from a screen position
- *****************************************************************************/
-
-QWidget *QApplication::topLevelAt(const QPoint &pos)
-{
- POINT p;
- HWND win;
- QWidget *w;
- p.x = pos.x();
- p.y = pos.y();
- win = WindowFromPoint(p);
- if (!win)
- return 0;
-
- w = QWidget::find(win);
- while (!w && win) {
- win = GetParent(win);
- w = QWidget::find(win);
- }
- return w ? w->window() : 0;
-}
-
-void QApplication::beep()
-{
- MessageBeep(MB_OK);
-}
-
-static void alert_widget(QWidget *widget, int duration)
-{
-#ifdef Q_OS_WINCE
- Q_UNUSED(widget);
- Q_UNUSED(duration);
-#else
- bool stopFlash = duration < 0;
-
- if (widget && (!widget->isActiveWindow() || stopFlash)) {
- DWORD timeOut = GetCaretBlinkTime();
- if (timeOut <= 0)
- timeOut = 250;
-
- UINT flashCount;
- if (duration == 0)
- flashCount = 10;
- else
- flashCount = duration/timeOut;
-
- FLASHWINFO info;
- info.cbSize = sizeof(info);
- info.hwnd = widget->window()->winId();
- info.dwFlags = stopFlash ? FLASHW_STOP : FLASHW_TRAY;
- info.dwTimeout = stopFlash ? 0 : timeOut;
- info.uCount = stopFlash ? 0 : flashCount;
-
- FlashWindowEx(&info);
- }
-#endif
-}
-
-void QApplication::alert(QWidget *widget, int duration)
-{
- if (!QApplicationPrivate::checkInstance("alert"))
- return;
-
- if (widget) {
- alert_widget(widget, duration);
- } else {
- const QWidgetList toplevels(topLevelWidgets());
- for (int i = 0; i < toplevels.count(); ++i) {
- QWidget *topLevel = toplevels.at(i);
- alert_widget(topLevel, duration);
- }
- }
-}
-
-QString QApplicationPrivate::appName() const
-{
- return QCoreApplicationPrivate::appName();
-}
-
-
-/*****************************************************************************
- Main event loop
- *****************************************************************************/
-
-extern uint qGlobalPostedEventsCount();
-
-void QApplication::winFocus(QWidget *widget, bool gotFocus)
-{
- if (d_func()->inPopupMode()) // some delayed focus event to ignore
- return;
- if (gotFocus) {
- setActiveWindow(widget);
- if (QApplicationPrivate::active_window
- && (QApplicationPrivate::active_window->windowType() == Qt::Dialog)) {
- // raise the entire application, not just the dialog
- QWidget* mw = QApplicationPrivate::active_window;
-#ifndef Q_WS_WINCE
- while(mw->parentWidget() && (mw->windowType() == Qt::Dialog))
- mw = mw->parentWidget()->window();
- if (mw->testAttribute(Qt::WA_WState_Created) && mw != QApplicationPrivate::active_window)
- SetWindowPos(mw->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-#else
- // On Desktop Windows, we set the first parent of the dialog on top
- // Child windows will be automatically set above again.
- // On Windows CE we pass no parent in CreateWindowEx as otherwise
- // dialogs get embedded into the parent window. Thus we need to
- // manually iterate and reactivate all windows from bottom up.
- QList<QWidget*> raiseList;
- raiseList.push_back(mw);
- while(mw->parentWidget() && (mw->windowType() == Qt::Dialog)) {
- mw = mw->parentWidget()->window();
- raiseList.push_back(mw);
- }
- while(!raiseList.isEmpty()) {
- mw = raiseList.takeLast();
- if (mw->testAttribute(Qt::WA_WState_Created)) {
- HWND state = HWND_TOP;
- if (mw->windowFlags() & Qt::WindowStaysOnBottomHint)
- state = HWND_BOTTOM;
- else if (mw->windowFlags() & Qt::WindowStaysOnTopHint)
- state = HWND_TOPMOST;
- SetWindowPos(mw->internalWinId(), state, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
- }
- }
-#endif
- }
- } else {
- setActiveWindow(0);
- }
-}
-
-
-//
-// QtWndProc() receives all messages from the main event loop
-//
-
-static bool inLoop = false;
-static int inputcharset = CP_ACP;
-
-#define RETURN(x) { inLoop=false;return x; }
-
-static bool qt_is_translatable_mouse_event(UINT message)
-{
- return (((message >= WM_MOUSEFIRST && message <= WM_MOUSELAST) ||
- (message >= WM_XBUTTONDOWN && message <= WM_XBUTTONDBLCLK))
- && message != WM_MOUSEWHEEL
- && message != WM_MOUSEHWHEEL)
-
-#ifndef Q_WS_WINCE
- || (message >= WM_NCMOUSEMOVE && message <= WM_NCMBUTTONDBLCLK)
-#endif
- ;
-}
-
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
-{
- bool result = true;
- QEvent::Type evt_type = QEvent::None;
- QETWidget *widget = 0;
-
- // there is no need to process pakcets from tablet unless
- // it is actually on the tablet, a flag to let us know...
- int nPackets; // the number of packets we get from the queue
-
- long res = 0;
- if (!qApp) // unstable app state
- RETURN(QWinInputContext::DefWindowProc(hwnd,message,wParam,lParam))
-
- QScopedLoopLevelCounter loopLevelCounter(QThreadData::get2(qApp->thread()));
-
-#if 0
- // make sure we update widgets also when the user resizes
- if (inLoop && qApp->loopLevel())
- qApp->sendPostedEvents(0, QEvent::Paint);
-#endif
-
- inLoop = true;
-
- MSG msg;
- msg.hwnd = hwnd; // create MSG structure
- msg.message = message; // time and pt fields ignored
- msg.wParam = wParam;
- msg.lParam = lParam;
- msg.pt.x = GET_X_LPARAM(lParam);
- msg.pt.y = GET_Y_LPARAM(lParam);
- // If it's a non-client-area message the coords are screen coords, otherwise they are
- // client coords.
-#ifndef Q_WS_WINCE
- if (message < WM_NCMOUSEMOVE || message > WM_NCMBUTTONDBLCLK)
-#endif
- ClientToScreen(msg.hwnd, &msg.pt);
-
- /*
- // sometimes the autograb is not released, so the clickevent is sent
- // to the wrong window. We ignore this for now, because it doesn't
- // cause any problems.
- if (msg.message == WM_LBUTTONDOWN || msg.message == WM_RBUTTONDOWN || msg.message == WM_MBUTTONDOWN) {
- HWND handle = WindowFromPoint(msg.pt);
- if (msg.hwnd != handle) {
- msg.hwnd = handle;
- hwnd = handle;
- }
- }
- */
-
-#if defined(QT_NON_COMMERCIAL)
- QT_NC_WNDPROC
-#endif
-
- // send through app filter
- if (qApp->filterEvent(&msg, &res))
- return res;
-
- // close any opened ime candidate window (enabled only on a popup widget)
- if (imeParentWnd && QApplication::activePopupWidget()
- && (message == WM_MBUTTONDOWN || message == WM_XBUTTONDOWN
- || message == WM_LBUTTONDOWN || message == WM_RBUTTONDOWN
-#ifndef Q_WS_WINCE
- || message == WM_NCMBUTTONDOWN || message == WM_NCLBUTTONDOWN
- || message == WM_NCRBUTTONDOWN)) {
-#else
- )) {
-#endif
- ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
- }
-
- switch (message) {
-#ifndef Q_WS_WINCE
-#ifndef QT_NO_SESSIONMANAGER
- case WM_QUERYENDSESSION: {
- if (sm_smActive) // bogus message from windows
- RETURN(true);
-
- sm_smActive = true;
- sm_blockUserInput = true; // prevent user-interaction outside interaction windows
- sm_cancel = false;
- if (qt_session_manager_self)
- qApp->commitData(*qt_session_manager_self);
- if (lParam & ENDSESSION_LOGOFF) {
- _flushall();
- }
- RETURN(!sm_cancel);
- }
- case WM_ENDSESSION: {
- sm_smActive = false;
- sm_blockUserInput = false;
- bool endsession = (bool) wParam;
-
- // we receive the message for each toplevel window included internal hidden ones,
- // but the aboutToQuit signal should be emitted only once.
- QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
- if (endsession && !qAppPriv->aboutToQuitEmitted) {
- qAppPriv->aboutToQuitEmitted = true;
- int index = QApplication::staticMetaObject.indexOfSignal("aboutToQuit()");
- qApp->qt_metacall(QMetaObject::InvokeMetaMethod, index,0);
- // since the process will be killed immediately quit() has no real effect
- QApplication::quit();
- }
-
- RETURN(0);
- }
-#endif
- case WM_DISPLAYCHANGE:
- if (QApplication::type() == QApplication::Tty)
- break;
- if (qt_desktopWidget) {
- qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77));
- QSize sz(GetSystemMetrics(78), GetSystemMetrics(79));
- if (sz == qt_desktopWidget->size()) {
- // a screen resized without changing size of the virtual desktop
- QResizeEvent rs(sz, qt_desktopWidget->size());
- QApplication::sendEvent(qt_desktopWidget, &rs);
- } else {
- qt_desktopWidget->resize(sz);
- }
- }
- break;
-#endif
-
- case WM_SETTINGCHANGE:
-#ifdef Q_WS_WINCE
- // CE SIP hide/show
- if (qt_desktopWidget && wParam == SPI_SETSIPINFO) {
- QResizeEvent re(QSize(0, 0), QSize(0, 0)); // Calculated by QDesktopWidget
- QApplication::sendEvent(qt_desktopWidget, &re);
- break;
- }
-#endif
- // ignore spurious XP message when user logs in again after locking
- if (QApplication::type() == QApplication::Tty)
- break;
- if (QApplication::desktopSettingsAware() && wParam != SPI_SETWORKAREA) {
- widget = (QETWidget*)QWidget::find(hwnd);
- if (widget) {
- if (wParam == SPI_SETNONCLIENTMETRICS)
- widget->markFrameStrutDirty();
- }
- }
- else if (qt_desktopWidget && wParam == SPI_SETWORKAREA) {
- qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77));
- QSize sz(GetSystemMetrics(78), GetSystemMetrics(79));
- if (sz == qt_desktopWidget->size()) {
- // a screen resized without changing size of the virtual desktop
- QResizeEvent rs(sz, qt_desktopWidget->size());
- QApplication::sendEvent(qt_desktopWidget, &rs);
- } else {
- qt_desktopWidget->resize(sz);
- }
- }
-
- if (wParam == SPI_SETFONTSMOOTHINGTYPE) {
- qt_win_read_cleartype_settings();
- foreach (QWidget *w, QApplication::topLevelWidgets()) {
- if (!w->isVisible())
- continue;
- ((QETWidget *) w)->forceUpdate();
- }
- }
-
- break;
- case WM_SYSCOLORCHANGE:
- if (QApplication::type() == QApplication::Tty)
- break;
- if (QApplication::desktopSettingsAware()) {
- widget = (QETWidget*)QWidget::find(hwnd);
- if (widget && !widget->parentWidget())
- qt_set_windows_color_resources();
- }
- break;
-
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- case WM_XBUTTONDOWN:
- case WM_LBUTTONDBLCLK:
- case WM_RBUTTONDBLCLK:
- case WM_MBUTTONDBLCLK:
- case WM_XBUTTONDBLCLK:
- if (qt_win_ignoreNextMouseReleaseEvent)
- qt_win_ignoreNextMouseReleaseEvent = false;
- break;
-
- case WM_LBUTTONUP:
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- case WM_XBUTTONUP:
- if (qt_win_ignoreNextMouseReleaseEvent) {
- qt_win_ignoreNextMouseReleaseEvent = false;
- if (qt_button_down && qt_button_down->internalWinId() == autoCaptureWnd) {
- releaseAutoCapture();
- qt_button_down = 0;
- }
-
- RETURN(0);
- }
- break;
-
- default:
- break;
- }
-
- if (!widget)
- widget = (QETWidget*)QWidget::find(hwnd);
- if (!widget) // don't know this widget
- goto do_default;
-
- if (app_do_modal) { // modal event handling
- int ret = 0;
- if (!qt_try_modal(widget, &msg, ret))
- RETURN(ret);
- }
-
- res = 0;
- if (widget->winEvent(&msg, &res)) // send through widget filter
- RETURN(res);
-
- if (qt_is_translatable_mouse_event(message)) {
- if (QApplication::activePopupWidget() != 0) { // in popup mode
- POINT curPos = msg.pt;
- QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
- if (w)
- widget = (QETWidget*)w;
- }
-
- if (!qt_tabletChokeMouse) {
- result = widget->translateMouseEvent(msg); // mouse event
-#if defined(Q_WS_WINCE) && !defined(QT_NO_CONTEXTMENU)
- if (message == WM_LBUTTONDOWN && widget != QApplication::activePopupWidget()) {
- QWidget* alienWidget = widget;
- if ((alienWidget != QApplication::activePopupWidget()) && (alienWidget->contextMenuPolicy() != Qt::PreventContextMenu)) {
- QPoint pos(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
- QPoint globalPos(msg.pt.x, msg.pt.y);
- // In case we are using Alien, then the widget to
- // send the context menu event is a different one
- if (!alienWidget->testAttribute(Qt::WA_NativeWindow) && !alienWidget->testAttribute(Qt::WA_PaintOnScreen)) {
- alienWidget = QApplication::widgetAt(globalPos);
- if (alienWidget)
- pos = alienWidget->mapFromGlobal(globalPos);
- }
- if (alienWidget) {
- SHRGINFO shrg;
- shrg.cbSize = sizeof(shrg);
- shrg.hwndClient = hwnd;
- shrg.ptDown.x = GET_X_LPARAM(lParam);
- shrg.ptDown.y = GET_Y_LPARAM(lParam);
- shrg.dwFlags = SHRG_RETURNCMD | SHRG_NOANIMATION;
- resolveAygLibs();
-#ifndef QT_NO_GESTURES
- if (ptrRecognizeGesture && (ptrRecognizeGesture(&shrg) == GN_CONTEXTMENU)) {
- if (QApplication::activePopupWidget())
- QApplication::activePopupWidget()->close();
- QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos);
- result = qt_sendSpontaneousEvent(alienWidget, &e);
- }
-#endif // QT_NO_GESTURES
- }
- }
- }
-#endif
- } else {
- // Sometimes we only get a WM_MOUSEMOVE message
- // and sometimes we get both a WM_MOUSEMOVE and
- // a WM_LBUTTONDOWN/UP, this creates a spurious mouse
- // press/release event, using the PeekMessage
- // will help us fix this. This leaves us with a
- // question:
- // This effectively kills using the mouse AND the
- // tablet simultaneously, well creates wacky input.
- // Is this going to be a problem? (probably not)
- bool next_is_button = false;
- bool is_mouse_move = (message == WM_MOUSEMOVE);
- if (is_mouse_move) {
- MSG msg1;
- if (PeekMessage(&msg1, msg.hwnd, WM_MOUSEFIRST,
- WM_MOUSELAST, PM_NOREMOVE))
- next_is_button = (msg1.message == WM_LBUTTONUP
- || msg1.message == WM_LBUTTONDOWN);
- }
- if (!is_mouse_move || (is_mouse_move && !next_is_button))
- qt_tabletChokeMouse = false;
- }
- } else {
- switch (message) {
- case WM_TOUCH:
- result = QApplicationPrivate::instance()->translateTouchEvent(msg);
- break;
- case WM_KEYDOWN: // keyboard event
- case WM_SYSKEYDOWN:
- qt_keymapper_private()->updateKeyMap(msg);
- // fall-through intended
- case WM_KEYUP:
- case WM_SYSKEYUP:
-#if Q_OS_WINCE_WM
- case WM_HOTKEY:
- if(HIWORD(msg.lParam) == VK_TBACK) {
- const bool hotKeyDown = !(LOWORD(msg.lParam) & MOD_KEYUP);
- msg.lParam = 0x69 << 16;
- msg.wParam = VK_BACK;
- if (hotKeyDown) {
- msg.message = WM_KEYDOWN;
- qt_keymapper_private()->updateKeyMap(msg);
- } else {
- msg.message = WM_KEYUP;
- }
- }
- // fall-through intended
-#endif
- case WM_IME_CHAR:
- case WM_IME_KEYDOWN:
- case WM_CHAR: {
- MSG msg1;
- bool anyMsg = PeekMessage(&msg1, msg.hwnd, 0, 0, PM_NOREMOVE);
- if (anyMsg && msg1.message == WM_DEADCHAR) {
- result = true; // consume event since there is a dead char next
- break;
- }
- QWidget *g = QWidget::keyboardGrabber();
- if (g && qt_get_tablet_widget() && hwnd == qt_get_tablet_widget()->winId()) {
- // if we get an event for the internal tablet widget,
- // then don't send it to the keyboard grabber, but
- // send it to the widget itself (we don't use it right
- // now, just in case).
- g = 0;
- }
- if (g)
- widget = (QETWidget*)g;
- else if (QApplication::activePopupWidget())
- widget = (QETWidget*)QApplication::activePopupWidget()->focusWidget()
- ? (QETWidget*)QApplication::activePopupWidget()->focusWidget()
- : (QETWidget*)QApplication::activePopupWidget();
- else if (QApplication::focusWidget())
- widget = (QETWidget*)QApplication::focusWidget();
- else if (!widget || widget->internalWinId() == GetFocus()) // We faked the message to go to exactly that widget.
- widget = (QETWidget*)widget->window();
- if (widget->isEnabled())
- result = sm_blockUserInput
- ? true
- : qt_keymapper_private()->translateKeyEvent(widget, msg, g != 0);
- break;
- }
- case WM_SYSCHAR:
- result = true; // consume event
- break;
-
- case WM_MOUSEWHEEL:
- case WM_MOUSEHWHEEL:
- result = widget->translateWheelEvent(msg);
- break;
-
- case WM_APPCOMMAND:
- {
- uint cmd = GET_APPCOMMAND_LPARAM(lParam);
- uint uDevice = GET_DEVICE_LPARAM(lParam);
- uint dwKeys = GET_KEYSTATE_LPARAM(lParam);
-
- int state = translateButtonState(dwKeys, QEvent::KeyPress, 0);
-
- switch (uDevice) {
- case FAPPCOMMAND_KEY:
- {
- int key = 0;
-
- switch(cmd) {
- case APPCOMMAND_BASS_BOOST:
- key = Qt::Key_BassBoost;
- break;
- case APPCOMMAND_BASS_DOWN:
- key = Qt::Key_BassDown;
- break;
- case APPCOMMAND_BASS_UP:
- key = Qt::Key_BassUp;
- break;
- case APPCOMMAND_TREBLE_DOWN:
- key = Qt::Key_TrebleDown;
- break;
- case APPCOMMAND_TREBLE_UP:
- key = Qt::Key_TrebleUp;
- break;
- case APPCOMMAND_HELP:
- key = Qt::Key_Help;
- break;
- case APPCOMMAND_FIND:
- key = Qt::Key_Search;
- break;
- default:
- break;
- }
- if (key) {
- bool res = false;
- QWidget *g = QWidget::keyboardGrabber();
- if (g)
- widget = (QETWidget*)g;
- else if (QApplication::focusWidget())
- widget = (QETWidget*)QApplication::focusWidget();
- else
- widget = (QETWidget*)widget->window();
- if (widget->isEnabled()) {
- res = QKeyMapper::sendKeyEvent(widget, g != 0, QEvent::KeyPress, key,
- Qt::KeyboardModifier(state),
- QString(), false, 0, 0, 0, 0);
- }
- if (res)
- return true;
- }
- }
- break;
-
- default:
- break;
- }
-
- result = false;
- }
- break;
-
-#ifndef Q_WS_WINCE
- case WM_NCHITTEST:
- if (widget->isWindow()) {
- QPoint pos = widget->mapFromGlobal(QPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
- // don't show resize-cursors for fixed-size widgets
- QRect fs = widget->frameStrut();
- if (!widget->isMinimized()) {
- if (widget->minimumHeight() == widget->maximumHeight()) {
- if (pos.y() < -(fs.top() - fs.left()))
- return HTCAPTION;
- if (pos.y() >= widget->height())
- return HTBORDER;
- }
- if (widget->minimumWidth() == widget->maximumWidth() && (pos.x() < 0 || pos.x() >= widget->width()))
- return HTBORDER;
- }
- }
-
- result = false;
- break;
-#endif
-
- case WM_SYSCOMMAND: {
-#ifndef Q_WS_WINCE
- bool window_state_change = false;
- Qt::WindowStates oldstate = Qt::WindowStates(widget->dataPtr()->window_state);
- // MSDN:In WM_SYSCOMMAND messages, the four low-order bits of the wParam parameter are
- // used internally by the system. To obtain the correct result when testing the value of
- // wParam, an application must combine the value 0xFFF0 with the wParam value by using
- // the bitwise AND operator.
- switch(0xfff0 & wParam) {
- case SC_CONTEXTHELP:
-#ifndef QT_NO_WHATSTHIS
- QWhatsThis::enterWhatsThisMode();
-#endif
- DefWindowProc(hwnd, WM_NCPAINT, 1, 0);
- break;
-#if defined(QT_NON_COMMERCIAL)
- QT_NC_SYSCOMMAND
-#endif
- case SC_MINIMIZE:
- window_state_change = true;
- widget->dataPtr()->window_state |= Qt::WindowMinimized;
- if (widget->isVisible()) {
- QHideEvent e;
- qt_sendSpontaneousEvent(widget, &e);
- widget->hideChildren(true);
- const QString title = widget->windowIconText();
- if (!title.isEmpty())
- widget->setWindowTitle_helper(title);
- }
- result = false;
- break;
- case SC_MAXIMIZE:
- if(widget->isWindow())
- widget->topData()->normalGeometry = widget->geometry();
- case SC_RESTORE:
- window_state_change = true;
- if ((0xfff0 & wParam) == SC_MAXIMIZE)
- widget->dataPtr()->window_state |= Qt::WindowMaximized;
- else if (!widget->isMinimized())
- widget->dataPtr()->window_state &= ~Qt::WindowMaximized;
-
- if (widget->isMinimized()) {
- widget->dataPtr()->window_state &= ~Qt::WindowMinimized;
- widget->showChildren(true);
- QShowEvent e;
- qt_sendSpontaneousEvent(widget, &e);
- const QString title = widget->windowTitle();
- if (!title.isEmpty())
- widget->setWindowTitle_helper(title);
- }
- result = false;
- break;
- default:
- result = false;
- break;
- }
-
- if (window_state_change) {
- QWindowStateChangeEvent e(oldstate);
- qt_sendSpontaneousEvent(widget, &e);
- }
-#endif // #ifndef Q_OS_WINCE
-
- break;
- }
-
- case WM_SETTINGCHANGE:
- if ( QApplication::type() == QApplication::Tty )
- break;
-
- if (!msg.wParam) {
-#ifdef Q_WS_WINCE
- // On Windows CE, lParam parameter is a constant, not a char pointer.
- if (msg.lParam == INI_INTL) {
-#else
- QString area = QString::fromWCharArray((wchar_t*)msg.lParam);
- if (area == QLatin1String("intl")) {
-#endif
- QLocalePrivate::updateSystemPrivate();
- if (!widget->testAttribute(Qt::WA_SetLocale))
- widget->dptr()->setLocale_helper(QLocale(), true);
- QEvent e(QEvent::LocaleChange);
- QApplication::sendEvent(qApp, &e);
- }
- }
- else if (msg.wParam == SPI_SETICONTITLELOGFONT) {
- if (QApplication::desktopSettingsAware()) {
- widget = (QETWidget*)QWidget::find(hwnd);
- if (widget && !widget->parentWidget()) {
- qt_set_windows_font_resources();
- }
- }
- }
- else if (msg.wParam == SPI_SETNONCLIENTMETRICS) {
- widget = (QETWidget*)QWidget::find(hwnd);
- if (widget && !widget->parentWidget()) {
- qt_set_windows_updateScrollBar(widget);
- QEvent e(QEvent::LayoutRequest);
- QApplication::sendEvent(widget, &e);
- }
- }
-
- break;
-
- case WM_PAINT: // paint event
- case WM_ERASEBKGND: // erase window background
- result = widget->translatePaintEvent(msg);
- break;
-
-#ifndef Q_WS_WINCE
- case WM_ENTERSIZEMOVE:
- autoCaptureWnd = hwnd;
- break;
- case WM_EXITSIZEMOVE:
- autoCaptureWnd = 0;
- break;
-#endif
- case WM_MOVE: // move window
- case WM_SIZE: // resize window
- result = widget->translateConfigEvent(msg);
- break;
-
- case WM_ACTIVATEAPP:
- if (wParam == FALSE) {
- QApplication::setActiveWindow(0);
- // Another application was activated while our popups are open,
- // then close all popups. In case some popup refuses to close,
- // we give up after 1024 attempts (to avoid an infinite loop).
- int maxiter = 1024;
- QWidget *popup;
- while ((popup=QApplication::activePopupWidget()) && maxiter--)
- popup->close();
- }
- break;
-
- case WM_ACTIVATE:
- if ( QApplication::type() == QApplication::Tty )
- break;
-
- if (ptrWTOverlap && ptrWTEnable) {
- // cooperate with other tablet applications, but when
- // we get focus, I want to use the tablet...
- if (qt_tablet_context && GET_WM_ACTIVATE_STATE(wParam, lParam)) {
- if (ptrWTEnable(qt_tablet_context, true))
- ptrWTOverlap(qt_tablet_context, true);
- }
- }
- if (QApplication::activePopupWidget() && LOWORD(wParam) == WA_INACTIVE &&
- QWidget::find((HWND)lParam) == 0) {
- // Another application was activated while our popups are open,
- // then close all popups. In case some popup refuses to close,
- // we give up after 1024 attempts (to avoid an infinite loop).
- int maxiter = 1024;
- QWidget *popup;
- while ((popup=QApplication::activePopupWidget()) && maxiter--)
- popup->close();
- }
-
- if (LOWORD(wParam) != WA_INACTIVE) {
- // WM_ACTIVATEAPP handles the "true" false case, as this is only when the application
- // loses focus. Doing it here would result in the widget getting focus to not know
- // where it got it from; it would simply get a 0 value as the old focus widget.
-#ifdef Q_WS_WINCE
- {
-#ifdef Q_WS_WINCE_WM
- // On Windows mobile we do not receive WM_SYSCOMMAND / SC_MINIMIZE messages.
- // Thus we have to unset the minimized state explicitly. We must do this for all
- // top-level widgets, because we get the HWND of a random widget here.
- foreach (QWidget* tlw, QApplication::topLevelWidgets()) {
- if (tlw->isMinimized())
- tlw->setWindowState(tlw->windowState() & ~Qt::WindowMinimized);
- }
-#else
- // On Windows CE we do not receive WM_SYSCOMMAND / SC_MINIMIZE messages.
- // Thus we have to unset the minimized state explicitly.
- if (widget->windowState() & Qt::WindowMinimized)
- widget->setWindowState(widget->windowState() & ~Qt::WindowMinimized);
-#endif // Q_WS_WINCE_WM
-
-#else
- if (!(widget->windowState() & Qt::WindowMinimized)) {
-#endif
- // Ignore the activate message send by WindowsXP to a minimized window
-#ifdef Q_WS_WINCE_WM
- if (widget->windowState() & Qt::WindowFullScreen)
- qt_wince_hide_taskbar(widget->winId());
-#endif
- qApp->winFocus(widget, true);
- // reset any window alert flashes
- alert_widget(widget, -1);
- }
- }
-
- // Windows tries to activate a modally blocked window.
- // This happens when restoring an application after "Show Desktop"
- if (app_do_modal && LOWORD(wParam) == WA_ACTIVE) {
- QWidget *top = 0;
- if (!QApplicationPrivate::tryModalHelper(widget, &top) && top && widget != top) {
- if (top->isVisible()) {
- top->activateWindow();
- } else {
- // This is the case when native file dialogs are shown
- QWidget *p = (top->parentWidget() ? top->parentWidget()->window() : 0);
- if (p && p->isVisible())
- p->activateWindow();
- }
- }
- }
- break;
-
-#ifndef Q_WS_WINCE
- case WM_MOUSEACTIVATE:
- if (widget->window()->windowType() == Qt::Tool) {
- QWidget *w = widget;
- if (!w->window()->focusWidget()) {
- while (w && (w->focusPolicy() & Qt::ClickFocus) == 0) {
- if (w->isWindow()) {
- QWidget *fw = w;
- while ((fw = fw->nextInFocusChain()) != w && fw->focusPolicy() == Qt::NoFocus)
- ;
- if (fw != w)
- break;
- QWidget *pw = w->parentWidget();
- while (pw) {
- pw = pw->window();
- if (pw && pw->isVisible() && pw->focusWidget()) {
- Q_ASSERT(pw->testAttribute(Qt::WA_WState_Created));
- SetWindowPos(pw->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
- break;
- }
- pw = pw->parentWidget();
- }
- RETURN(MA_NOACTIVATE);
- }
- w = w->parentWidget();
- }
- }
- }
- RETURN(MA_ACTIVATE);
- break;
-#endif
- case WM_SHOWWINDOW:
- if (lParam == SW_PARENTOPENING) {
- if (widget->testAttribute(Qt::WA_WState_Hidden))
- RETURN(0);
- }
- if (widget->isWindow() && widget->testAttribute(Qt::WA_WState_Visible)
- && !widget->testWindowState(Qt::WindowMinimized)) {
- if (lParam == SW_PARENTOPENING) {
- QShowEvent e;
- qt_sendSpontaneousEvent(widget, &e);
- widget->showChildren(true);
- } else if (lParam == SW_PARENTCLOSING) {
- QHideEvent e;
- qt_sendSpontaneousEvent(widget, &e);
- widget->hideChildren(true);
- }
- }
- if (!wParam && autoCaptureWnd == widget->internalWinId())
- releaseAutoCapture();
- result = false;
- break;
-
- case WM_PALETTECHANGED: // our window changed palette
- if (QColormap::hPal() && (WId)wParam == widget->internalWinId())
- RETURN(0); // otherwise: FALL THROUGH!
- // FALL THROUGH
- case WM_QUERYNEWPALETTE: // realize own palette
- if (QColormap::hPal()) {
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- HDC hdc = GetDC(widget->internalWinId());
- HPALETTE hpalOld = SelectPalette(hdc, QColormap::hPal(), FALSE);
- uint n = RealizePalette(hdc);
- if (n)
- InvalidateRect(widget->internalWinId(), 0, TRUE);
- SelectPalette(hdc, hpalOld, TRUE);
- RealizePalette(hdc);
- ReleaseDC(widget->internalWinId(), hdc);
- RETURN(n);
- }
- break;
- case WM_CLOSE: // close window
- widget->translateCloseEvent(msg);
- RETURN(0); // always handled
-
- case WM_DESTROY: // destroy window
- if (hwnd == curWin) {
- QWidget *enter = QWidget::mouseGrabber();
- if (enter == widget)
- enter = 0;
- QApplicationPrivate::dispatchEnterLeave(enter, widget);
- curWin = enter ? enter->effectiveWinId() : 0;
- qt_last_mouse_receiver = enter;
- }
- if (widget == popupButtonFocus)
- popupButtonFocus = 0;
- result = false;
- break;
-
-#ifndef Q_WS_WINCE
- case WM_WINDOWPOSCHANGING:
- {
- result = false;
- if (widget->isWindow()) {
- WINDOWPOS *winPos = (WINDOWPOS *)lParam;
- if (widget->layout() && widget->layout()->hasHeightForWidth()
- && !(winPos->flags & (SWP_NOCOPYBITS | SWP_NOSIZE))) {
- QRect fs = widget->frameStrut();
- QRect rect = widget->geometry();
- QRect newRect = QRect(winPos->x + fs.left(),
- winPos->y + fs.top(),
- winPos->cx - fs.left() - fs.right(),
- winPos->cy - fs.top() - fs.bottom());
-
- QSize newSize = QLayout::closestAcceptableSize(widget, newRect.size());
-
- int dh = newSize.height() - newRect.height();
- int dw = newSize.width() - newRect.width();
- if (!dw && ! dh)
- break; // Size OK
-
- if (rect.y() != newRect.y()) {
- newRect.setTop(newRect.top() - dh);
- } else {
- newRect.setBottom(newRect.bottom() + dh);
- }
-
- if (rect.x() != newRect.x()) {
- newRect.setLeft(newRect.left() - dw);
- } else {
- newRect.setRight(newRect.right() + dw);
- }
-
- winPos->x = newRect.x() - fs.left();
- winPos->y = newRect.y() - fs.top();
- winPos->cx = newRect.width() + fs.left() + fs.right();
- winPos->cy = newRect.height() + fs.top() + fs.bottom();
-
- RETURN(0);
- }
- if (widget->windowFlags() & Qt::WindowStaysOnBottomHint) {
- winPos->hwndInsertAfter = HWND_BOTTOM;
- }
- }
- }
- break;
-
- case WM_GETMINMAXINFO:
- if (widget->xtra()) {
- MINMAXINFO *mmi = (MINMAXINFO *)lParam;
- QWExtra *x = widget->xtra();
- QRect fs = widget->frameStrut();
- if ( x->minw > 0 )
- mmi->ptMinTrackSize.x = x->minw + fs.right() + fs.left();
- if ( x->minh > 0 )
- mmi->ptMinTrackSize.y = x->minh + fs.top() + fs.bottom();
- qint32 maxw = (x->maxw >= x->minw) ? x->maxw : x->minw;
- qint32 maxh = (x->maxh >= x->minh) ? x->maxh : x->minh;
- if ( maxw < QWIDGETSIZE_MAX ) {
- mmi->ptMaxTrackSize.x = maxw + fs.right() + fs.left();
- // windows with title bar have an implicit size limit of 112 pixels
- if (widget->windowFlags() & Qt::WindowTitleHint)
- mmi->ptMaxTrackSize.x = qMax<long>(mmi->ptMaxTrackSize.x, 112);
- }
- if ( maxh < QWIDGETSIZE_MAX )
- mmi->ptMaxTrackSize.y = maxh + fs.top() + fs.bottom();
- RETURN(0);
- }
- break;
-
-#ifndef QT_NO_CONTEXTMENU
- case WM_CONTEXTMENU:
- {
- // it's not VK_APPS or Shift+F10, but a click in the NC area
- if (lParam != (int)0xffffffff) {
- result = false;
- break;
- }
-
- QWidget *fw = QWidget::keyboardGrabber();
- if (!fw) {
- if (QApplication::activePopupWidget())
- fw = (QApplication::activePopupWidget()->focusWidget()
- ? QApplication::activePopupWidget()->focusWidget()
- : QApplication::activePopupWidget());
- else if (QApplication::focusWidget())
- fw = QApplication::focusWidget();
- else if (widget)
- fw = widget->window();
- }
- if (fw && fw->isEnabled()) {
- QPoint pos = fw->inputMethodQuery(Qt::ImMicroFocus).toRect().center();
- QContextMenuEvent e(QContextMenuEvent::Keyboard, pos, fw->mapToGlobal(pos),
- qt_win_getKeyboardModifiers());
- result = qt_sendSpontaneousEvent(fw, &e);
- }
- }
- break;
-#endif
-#endif
-
- case WM_IME_STARTCOMPOSITION:
- case WM_IME_ENDCOMPOSITION:
- case WM_IME_COMPOSITION: {
- QWidget *fw = QApplication::focusWidget();
- QWinInputContext *im = fw ? qobject_cast<QWinInputContext *>(fw->inputContext()) : 0;
- if (fw && im) {
- if(message == WM_IME_STARTCOMPOSITION)
- result = im->startComposition();
- else if (message == WM_IME_ENDCOMPOSITION)
- result = im->endComposition();
- else if (message == WM_IME_COMPOSITION)
- result = im->composition(lParam);
- }
- break;
- }
- case WM_IME_REQUEST: {
- QWidget *fw = QApplication::focusWidget();
- QWinInputContext *im = fw ? qobject_cast<QWinInputContext *>(fw->inputContext()) : 0;
- if (fw && im) {
- if(wParam == IMR_RECONVERTSTRING) {
- int ret = im->reconvertString((RECONVERTSTRING *)lParam);
- if (ret == -1) {
- result = false;
- } else {
- return ret;
- }
- } else if (wParam == IMR_CONFIRMRECONVERTSTRING) {
- RETURN(TRUE);
- } else {
- // in all other cases, call DefWindowProc()
- result = false;
- }
- }
- break;
- }
-#ifndef Q_WS_WINCE
- case WM_CHANGECBCHAIN:
- case WM_DRAWCLIPBOARD:
-#endif
- case WM_RENDERFORMAT:
- case WM_RENDERALLFORMATS:
-#ifndef QT_NO_CLIPBOARD
- case WM_DESTROYCLIPBOARD:
- if (qt_clipboard) {
- QClipboardEvent e(reinterpret_cast<QEventPrivate *>(&msg));
- qt_sendSpontaneousEvent(qt_clipboard, &e);
- RETURN(0);
- }
- result = false;
- break;
-#endif //QT_NO_CLIPBOARD
-#ifndef QT_NO_ACCESSIBILITY
- case WM_GETOBJECT:
- {
- // Ignoring all requests while starting up
- if (QApplication::startingUp() || QApplication::closingDown() || lParam != (LPARAM)OBJID_CLIENT) {
- result = false;
- break;
- }
-
- typedef LRESULT (WINAPI *PtrLresultFromObject)(REFIID, WPARAM, LPUNKNOWN);
- static PtrLresultFromObject ptrLresultFromObject = 0;
- static bool oleaccChecked = false;
-
- if (!oleaccChecked) {
- oleaccChecked = true;
-#if !defined(Q_OS_WINCE)
- ptrLresultFromObject = (PtrLresultFromObject)QSystemLibrary::resolve(QLatin1String("oleacc"), "LresultFromObject");
-#endif
- }
- if (ptrLresultFromObject) {
- QAccessibleInterface *acc = QAccessible::queryAccessibleInterface(widget);
- if (!acc) {
- result = false;
- break;
- }
-
- // and get an instance of the IAccessibile implementation
- IAccessible *iface = qt_createWindowsAccessible(acc);
- res = ptrLresultFromObject(IID_IAccessible, wParam, iface); // ref == 2
- iface->Release(); // the client will release the object again, and then it will destroy itself
-
- if (res > 0)
- RETURN(res);
- }
- }
- result = false;
- break;
- case WM_GETTEXT:
- if (!widget->isWindow()) {
- int ret = 0;
- QAccessibleInterface *acc = QAccessible::queryAccessibleInterface(widget);
- if (acc) {
- QString text = acc->text(QAccessible::Name, 0);
- if (text.isEmpty())
- text = widget->objectName();
- ret = qMin<int>(wParam - 1, text.size());
- text.resize(ret);
- memcpy((void *)lParam, text.utf16(), (text.size() + 1) * sizeof(ushort));
- delete acc;
- }
- if (!ret) {
- result = false;
- break;
- }
- RETURN(ret);
- }
- result = false;
- break;
-#endif
- case WT_PACKET:
- if (ptrWTPacketsGet) {
- if ((nPackets = ptrWTPacketsGet(qt_tablet_context, QT_TABLET_NPACKETQSIZE, &localPacketBuf))) {
- result = widget->translateTabletEvent(msg, localPacketBuf, nPackets);
- }
- }
- break;
- case WT_PROXIMITY:
-
- #ifndef QT_NO_TABLETEVENT
- if (ptrWTPacketsGet && ptrWTInfo) {
- const bool enteredProximity = LOWORD(lParam) != 0;
- PACKET proximityBuffer[1]; // we are only interested in the first packet in this case
- const int totalPacks = ptrWTPacketsGet(qt_tablet_context, 1, proximityBuffer);
- if (totalPacks > 0) {
- const UINT currentCursor = proximityBuffer[0].pkCursor;
-
- UINT csr_physid;
- ptrWTInfo(WTI_CURSORS + currentCursor, CSR_PHYSID, &csr_physid);
- UINT csr_type;
- ptrWTInfo(WTI_CURSORS + currentCursor, CSR_TYPE, &csr_type);
- const UINT deviceIdMask = 0xFF6; // device type mask && device color mask
- quint64 uniqueId = (csr_type & deviceIdMask);
- uniqueId = (uniqueId << 32) | csr_physid;
-
- // initialising and updating the cursor should be done in response to
- // WT_CSRCHANGE. We do it in WT_PROXIMITY because some wintab never send
- // the event WT_CSRCHANGE even if asked with CXO_CSRMESSAGES
- const QTabletCursorInfo *const globalCursorInfo = tCursorInfo();
- if (!globalCursorInfo->contains(uniqueId))
- tabletInit(uniqueId, csr_type, qt_tablet_context);
-
- currentTabletPointer = globalCursorInfo->value(uniqueId);
- tabletUpdateCursor(currentTabletPointer, currentCursor);
- }
- qt_tabletChokeMouse = false;
-
- QTabletEvent tabletProximity(enteredProximity ? QEvent::TabletEnterProximity
- : QEvent::TabletLeaveProximity,
- QPoint(), QPoint(), QPointF(), currentTabletPointer.currentDevice, currentTabletPointer.currentPointerType, 0, 0,
- 0, 0, 0, 0, 0, currentTabletPointer.llId);
- QApplication::sendEvent(qApp, &tabletProximity);
- }
- #endif // QT_NO_TABLETEVENT
-
- break;
-#ifdef Q_WS_WINCE_WM
- case WM_SETFOCUS: {
- HIMC hC;
- hC = ImmGetContext(hwnd);
- ImmSetOpenStatus(hC, TRUE);
- ImmEscape(NULL, hC, IME_ESC_SET_MODE, (LPVOID)IM_SPELL);
- result = false;
- }
- break;
-#endif
- case WM_KILLFOCUS:
- if (!QWidget::find((HWND)wParam)) { // we don't get focus, so unset it now
- if (!widget->hasFocus()) // work around Windows bug after minimizing/restoring
- widget = (QETWidget*)QApplication::focusWidget();
- HWND focus = ::GetFocus();
- //if there is a current widget and the new widget belongs to the same toplevel window
- //or if the current widget was embedded into non-qt window (i.e. we won't get WM_ACTIVATEAPP)
- //then we clear the focus on the widget
- //in case the new widget belongs to a different widget hierarchy, clearing the focus
- //will be handled because the active window will change
- const bool embedded = widget && ((QETWidget*)widget->window())->topData()->embedded;
- if (widget && (embedded || ::IsChild(widget->window()->internalWinId(), focus))) {
- widget->clearFocus();
- result = true;
- } else {
- result = false;
- }
- } else {
- result = false;
- }
- break;
- case WM_THEMECHANGED:
- if ((widget->windowType() == Qt::Desktop) || !qApp || QApplication::closingDown()
- || QApplication::type() == QApplication::Tty)
- break;
-
- if (widget->testAttribute(Qt::WA_WState_Polished))
- QApplication::style()->unpolish(widget);
-
- if (widget->testAttribute(Qt::WA_WState_Polished))
- QApplication::style()->polish(widget);
- widget->repolishStyle(*QApplication::style());
- if (widget->isVisible())
- widget->update();
- break;
-
-#ifndef Q_WS_WINCE
- case WM_INPUTLANGCHANGE: {
- wchar_t info[7];
- if (!GetLocaleInfo(MAKELCID(lParam, SORT_DEFAULT), LOCALE_IDEFAULTANSICODEPAGE, info, 6)) {
- inputcharset = CP_ACP;
- } else {
- inputcharset = QString::fromWCharArray(info).toInt();
- }
- QKeyMapper::changeKeyboard();
- break;
- }
-#else
- case WM_COMMAND: {
- bool OkCommand = (LOWORD(wParam) == 0x1);
- bool CancelCommand = (LOWORD(wParam) == 0x2);
- if (OkCommand)
- QApplication::postEvent(widget, new QEvent(QEvent::OkRequest));
- if (CancelCommand)
- widget->showMinimized();
- else
-#ifndef QT_NO_MENUBAR
- QMenuBar::wceCommands(LOWORD(wParam));
-#endif
- result = true;
- }
- break;
- case WM_HELP:
- QApplication::postEvent(widget, new QEvent(QEvent::HelpRequest));
- result = true;
- break;
-#endif
-
- case WM_MOUSELEAVE:
- // We receive a mouse leave for curWin, meaning
- // the mouse was moved outside our widgets
- if (widget->internalWinId() == curWin) {
- bool dispatch = !widget->underMouse();
- // hasMouse is updated when dispatching enter/leave,
- // so test if it is actually up-to-date
- if (!dispatch) {
- QRect geom = widget->geometry();
- if (widget->parentWidget() && !widget->isWindow()) {
- QPoint gp = widget->parentWidget()->mapToGlobal(widget->pos());
- geom.setX(gp.x());
- geom.setY(gp.y());
- }
- QPoint cpos = QCursor::pos();
- dispatch = !geom.contains(cpos);
- if ( !dispatch && !QWidget::mouseGrabber()) {
- QWidget *hittest = QApplication::widgetAt(cpos);
- dispatch = !hittest || hittest->internalWinId() != curWin;
- }
- if (!dispatch) {
- HRGN hrgn = qt_tryCreateRegion(QRegion::Rectangle, 0,0,0,0);
- if (GetWindowRgn(curWin, hrgn) != ERROR) {
- QPoint lcpos = widget->mapFromGlobal(cpos);
- dispatch = !PtInRegion(hrgn, lcpos.x(), lcpos.y());
- }
- DeleteObject(hrgn);
- }
- }
- if (dispatch) {
- if (qt_last_mouse_receiver && !qt_last_mouse_receiver->internalWinId())
- QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
- else
- QApplicationPrivate::dispatchEnterLeave(0, QWidget::find((WId)curWin));
- curWin = 0;
- qt_last_mouse_receiver = 0;
- }
- }
- break;
-
- case WM_CANCELMODE:
- {
- // this goes through QMenuBar's event filter
- QEvent e(QEvent::ActivationChange);
- QApplication::sendEvent(qApp, &e);
- }
- break;
-
- case WM_IME_NOTIFY:
- // special handling for ime, only for widgets in a popup
- if (wParam == IMN_OPENCANDIDATE) {
- imeParentWnd = hwnd;
- if (QApplication::activePopupWidget()) {
- // temporarily disable the mouse grab to allow mouse input in
- // the ime candidate window. The actual handle is untouched
- if (autoCaptureWnd)
- ReleaseCapture();
- }
- } else if (wParam == IMN_CLOSECANDIDATE) {
- imeParentWnd = 0;
- if (QApplication::activePopupWidget()) {
- // undo the action above, when candidate window is closed
- if (autoCaptureWnd)
- SetCapture(autoCaptureWnd);
- }
- }
- result = false;
- break;
-#ifndef QT_NO_GESTURES
-#if !defined(Q_WS_WINCE) || defined(QT_WINCE_GESTURES)
- case WM_GESTURE: {
- GESTUREINFO gi;
- memset(&gi, 0, sizeof(GESTUREINFO));
- gi.cbSize = sizeof(GESTUREINFO);
-
- QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
- BOOL bResult = false;
- if (qAppPriv->GetGestureInfo)
- bResult = qAppPriv->GetGestureInfo((HANDLE)msg.lParam, &gi);
- if (bResult) {
- if (gi.dwID == GID_BEGIN) {
- // find the alien widget for the gesture position.
- // This might not be accurate as the position is the center
- // point of two fingers for multi-finger gestures.
- QPoint pt(gi.ptsLocation.x, gi.ptsLocation.y);
- QWidget *w = widget->childAt(widget->mapFromGlobal(pt));
- qAppPriv->gestureWidget = w ? w : widget;
- }
- if (qAppPriv->gestureWidget)
- static_cast<QETWidget*>(qAppPriv->gestureWidget)->translateGestureEvent(msg, gi);
- if (qAppPriv->CloseGestureInfoHandle)
- qAppPriv->CloseGestureInfoHandle((HANDLE)msg.lParam);
- if (gi.dwID == GID_END)
- qAppPriv->gestureWidget = 0;
- } else {
- DWORD dwErr = GetLastError();
- if (dwErr > 0)
- qWarning() << "translateGestureEvent: error = " << dwErr;
- }
- result = true;
- break;
- }
-#endif // !defined(Q_WS_WINCE) || defined(QT_WINCE_GESTURES)
-#endif // QT_NO_GESTURES
-#ifndef QT_NO_CURSOR
- case WM_SETCURSOR: {
- QCursor *ovr = QApplication::overrideCursor();
- if (ovr) {
- SetCursor(ovr->handle());
- RETURN(TRUE);
- }
- result = false;
- break;
- }
-#endif
- default:
- result = false; // event was not processed
- break;
- }
- }
-
- if (evt_type != QEvent::None) { // simple event
- QEvent e(evt_type);
- result = qt_sendSpontaneousEvent(widget, &e);
- }
-
- if (result)
- RETURN(false);
-
-do_default:
- RETURN(QWinInputContext::DefWindowProc(hwnd,message,wParam,lParam))
-}
-
-
-/*****************************************************************************
- Modal widgets; We have implemented our own modal widget mechanism
- to get total control.
- A modal widget without a parent becomes application-modal.
- A modal widget with a parent becomes modal to its parent and grandparents..
-
- QApplicationPrivate::enterModal()
- Enters modal state
- Arguments:
- QWidget *widget A modal widget
-
- QApplicationPrivate::leaveModal()
- Leaves modal state for a widget
- Arguments:
- QWidget *widget A modal widget
- *****************************************************************************/
-
-bool QApplicationPrivate::modalState()
-{
- return app_do_modal;
-}
-
-void QApplicationPrivate::enterModal_sys(QWidget *widget)
-{
- if (!qt_modal_stack)
- qt_modal_stack = new QWidgetList;
-
- releaseAutoCapture();
- ClipCursor(0);
- QWidget *leave = qt_last_mouse_receiver;
- if (!leave)
- leave = QWidget::find((WId)curWin);
- QApplicationPrivate::dispatchEnterLeave(0, leave);
- qt_modal_stack->insert(0, widget);
- app_do_modal = true;
- curWin = 0;
- qt_last_mouse_receiver = 0;
- qt_win_ignoreNextMouseReleaseEvent = false;
-}
-
-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;
- QPoint p(QCursor::pos());
- app_do_modal = false; // necessary, we may get recursively into qt_try_modal below
- QWidget* w = QApplication::widgetAt(p.x(), p.y());
- QWidget *leave = qt_last_mouse_receiver;
- if (!leave)
- leave = QWidget::find((WId)curWin);
- if (QWidget *grabber = QWidget::mouseGrabber()) {
- w = grabber;
- if (leave == w)
- leave = 0;
- }
- QApplicationPrivate::dispatchEnterLeave(w, leave); // send synthetic enter event
- curWin = w ? w->effectiveWinId() : 0;
- qt_last_mouse_receiver = w;
- }
- qt_win_ignoreNextMouseReleaseEvent = true;
- }
- app_do_modal = qt_modal_stack != 0;
-}
-
-bool qt_try_modal(QWidget *widget, MSG *msg, int& ret)
-{
-#if defined(Q_OS_WINCE)
- Q_UNUSED(ret);
-#endif
- QWidget * top = 0;
-
- if (QApplicationPrivate::tryModalHelper(widget, &top))
- return true;
-
- int type = msg->message;
-
- bool block_event = false;
-#ifndef Q_WS_WINCE
- if (type != WM_NCHITTEST) {
-#endif
- if ((type >= WM_MOUSEFIRST && type <= WM_MOUSELAST) ||
- type == WM_MOUSEWHEEL || type == WM_MOUSEHWHEEL ||
- type == WM_MOUSELEAVE ||
- (type >= WM_KEYFIRST && type <= WM_KEYLAST)
-#ifndef Q_WS_WINCE
- || type == WM_NCMOUSEMOVE
-#endif
- ) {
- if (type == WM_MOUSEMOVE
-#ifndef Q_WS_WINCE
- || type == WM_NCMOUSEMOVE
-#endif
- ) {
-#ifndef QT_NO_CURSOR
- QCursor *c = qt_grab_cursor();
- if (!c)
- c = QApplication::overrideCursor();
- if (c) // application cursor defined
- SetCursor(c->handle());
- else
- SetCursor(QCursor(Qt::ArrowCursor).handle());
-#endif // QT_NO_CURSOR
- }
- block_event = true;
- } else if (type == WM_CLOSE) {
- block_event = true;
- }
-#ifndef Q_WS_WINCE
- else if (type == WM_MOUSEACTIVATE || type == WM_NCLBUTTONDOWN){
- if (!top->isActiveWindow()) {
- top->activateWindow();
- } else {
- QApplication::beep();
- }
- block_event = true;
- ret = MA_NOACTIVATEANDEAT;
- } else if (type == WM_SYSCOMMAND) {
- if (!(msg->wParam == SC_RESTORE && widget->isMinimized()))
- block_event = true;
- }
- }
-#endif
-
- return !block_event;
-}
-
-
-/*****************************************************************************
- Popup widget mechanism
-
- openPopup()
- Adds a widget to the list of popup widgets
- Arguments:
- QWidget *widget The popup widget to be added
-
- closePopup()
- Removes a widget from the list of popup widgets
- Arguments:
- QWidget *widget The popup widget to be removed
- *****************************************************************************/
-
-void QApplicationPrivate::openPopup(QWidget *popup)
-{
- if (!QApplicationPrivate::popupWidgets)
- QApplicationPrivate::popupWidgets = new QWidgetList;
- QApplicationPrivate::popupWidgets->append(popup);
- if (!popup->isEnabled())
- return;
-
- // close any opened 'ime candidate window'
- if (imeParentWnd)
- ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
-
- if (QApplicationPrivate::popupWidgets->count() == 1 && !qt_nograb()) {
- Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
- setAutoCapture(popup->internalWinId()); // grab mouse/keyboard
- }
- // 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
- if (QWidget *fw = QApplication::focusWidget()) {
- QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
- QApplication::sendEvent(fw, &e);
- }
- }
-}
-
-void QApplicationPrivate::closePopup(QWidget *popup)
-{
- if (!QApplicationPrivate::popupWidgets)
- return;
- QApplicationPrivate::popupWidgets->removeAll(popup);
- POINT curPos;
- GetCursorPos(&curPos);
-
- // close any opened 'ime candidate window'
- if (imeParentWnd)
- ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
-
- if (QApplicationPrivate::popupWidgets->isEmpty()) { // this was the last popup
- delete QApplicationPrivate::popupWidgets;
- QApplicationPrivate::popupWidgets = 0;
- replayPopupMouseEvent = (!popup->geometry().contains(QPoint(curPos.x, curPos.y))
- && !popup->testAttribute(Qt::WA_NoMouseReplay));
- if (!popup->isEnabled())
- return;
- if (!qt_nograb()) // grabbing not disabled
- releaseAutoCapture();
- QWidget *fw = QApplicationPrivate::active_window ? QApplicationPrivate::active_window->focusWidget()
- : QApplication::focusWidget();
- if (fw) {
- if (fw != QApplication::focusWidget()) {
- fw->setFocus(Qt::PopupFocusReason);
- } else {
- QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
- QApplication::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 (QApplicationPrivate::popupWidgets->count() == 1) {
- Q_ASSERT(aw->testAttribute(Qt::WA_WState_Created));
- setAutoCapture(aw->internalWinId());
- }
- if (QWidget *fw = aw->focusWidget())
- fw->setFocus(Qt::PopupFocusReason);
- }
-}
-
-
-
-
-/*****************************************************************************
- Event translation; translates Windows events to Qt events
- *****************************************************************************/
-
-//
-// Auto-capturing for mouse press and mouse release
-//
-
-static void setAutoCapture(HWND h)
-{
- if (autoCaptureWnd)
- releaseAutoCapture();
- autoCaptureWnd = h;
- SetCapture(h);
-}
-
-static void releaseAutoCapture()
-{
- if (autoCaptureWnd) {
- ReleaseCapture();
- autoCaptureWnd = 0;
- }
-}
-
-
-//
-// Mouse event translation
-//
-// Non-client mouse messages are not translated
-//
-
-static const ushort mouseTbl[] = {
- WM_MOUSEMOVE, QEvent::MouseMove, 0,
- WM_LBUTTONDOWN, QEvent::MouseButtonPress, Qt::LeftButton,
- WM_LBUTTONUP, QEvent::MouseButtonRelease, Qt::LeftButton,
- WM_LBUTTONDBLCLK, QEvent::MouseButtonDblClick, Qt::LeftButton,
- WM_RBUTTONDOWN, QEvent::MouseButtonPress, Qt::RightButton,
- WM_RBUTTONUP, QEvent::MouseButtonRelease, Qt::RightButton,
- WM_RBUTTONDBLCLK, QEvent::MouseButtonDblClick, Qt::RightButton,
- WM_MBUTTONDOWN, QEvent::MouseButtonPress, Qt::MidButton,
- WM_MBUTTONUP, QEvent::MouseButtonRelease, Qt::MidButton,
- WM_MBUTTONDBLCLK, QEvent::MouseButtonDblClick, Qt::MidButton,
- // use XButton1 for now, the real X button is decided later
- WM_XBUTTONDOWN, QEvent::MouseButtonPress, Qt::XButton1,
- WM_XBUTTONUP, QEvent::MouseButtonRelease, Qt::XButton1,
- WM_XBUTTONDBLCLK, QEvent::MouseButtonDblClick, Qt::XButton1,
-
-#ifndef Q_WS_WINCE
- WM_NCMOUSEMOVE, QEvent::NonClientAreaMouseMove, 0,
- WM_NCLBUTTONDOWN, QEvent::NonClientAreaMouseButtonPress, Qt::LeftButton,
- WM_NCLBUTTONUP, QEvent::NonClientAreaMouseButtonRelease, Qt::LeftButton,
- WM_NCLBUTTONDBLCLK, QEvent::NonClientAreaMouseButtonDblClick, Qt::LeftButton,
- WM_NCRBUTTONDOWN, QEvent::NonClientAreaMouseButtonPress, Qt::RightButton,
- WM_NCRBUTTONUP, QEvent::NonClientAreaMouseButtonRelease, Qt::RightButton,
- WM_NCRBUTTONDBLCLK, QEvent::NonClientAreaMouseButtonDblClick, Qt::RightButton,
- WM_NCMBUTTONDOWN, QEvent::NonClientAreaMouseButtonPress, Qt::MidButton,
- WM_NCMBUTTONUP, QEvent::NonClientAreaMouseButtonRelease, Qt::MidButton,
- WM_NCMBUTTONDBLCLK, QEvent::NonClientAreaMouseButtonDblClick, Qt::MidButton,
-#endif
-
- 0, 0, 0
-};
-
-static int translateButtonState(int s, int type, int button)
-{
- Q_UNUSED(type);
- Q_UNUSED(button);
- int bst = 0;
- if (s & MK_LBUTTON)
- bst |= Qt::LeftButton;
- if (s & MK_MBUTTON)
- bst |= Qt::MidButton;
- if (s & MK_RBUTTON)
- bst |= Qt::RightButton;
- if (s & MK_SHIFT)
- bst |= Qt::ShiftModifier;
- if (s & MK_CONTROL)
- bst |= Qt::ControlModifier;
-
- if (s & MK_XBUTTON1)
- bst |= Qt::XButton1;
- if (s & MK_XBUTTON2)
- bst |= Qt::XButton2;
-
- if (GetKeyState(VK_MENU) < 0)
- bst |= Qt::AltModifier;
-
- if ((GetKeyState(VK_LWIN) < 0) ||
- (GetKeyState(VK_RWIN) < 0))
- bst |= Qt::MetaModifier;
-
- return bst;
-}
-
-void qt_win_eatMouseMove()
-{
- // after closing a windows dialog with a double click (i.e. open a file)
- // the message queue still contains a dubious WM_MOUSEMOVE message where
- // the left button is reported to be down (wParam != 0).
- // remove all those messages (usually 1) and post the last one with a
- // reset button state
-
- MSG msg = {0, 0, 0, 0, 0, {0, 0} };
- while (PeekMessage(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE))
- ;
- if (msg.message == WM_MOUSEMOVE)
- PostMessage(msg.hwnd, msg.message, 0, msg.lParam);
-}
-
-// In DnD, the mouse release event never appears, so the
-// mouse button state machine must be manually reset
-void QApplication::winMouseButtonUp()
-{
- qt_button_down = 0;
- releaseAutoCapture();
-}
-
-void QETWidget::repolishStyle(QStyle &)
-{
- QEvent e(QEvent::StyleChange);
- QApplication::sendEvent(this, &e);
-}
-
-bool QETWidget::translateMouseEvent(const MSG &msg)
-{
- if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
- Q_ASSERT(internalWinId());
-
- static QPoint pos;
- static POINT gpos={-1,-1};
- QEvent::Type type; // event parameters
- int button;
- int state;
- int i;
-
- if (sm_blockUserInput) //block user interaction during session management
- return true;
-
- // Compress mouse move events
- if (msg.message == WM_MOUSEMOVE) {
- MSG mouseMsg;
- while (PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEFIRST,
- WM_MOUSELAST, PM_NOREMOVE)) {
- if (mouseMsg.message == WM_MOUSEMOVE) {
-#define PEEKMESSAGE_IS_BROKEN 1
-#ifdef PEEKMESSAGE_IS_BROKEN
- // Since the Windows PeekMessage() function doesn't
- // correctly return the wParam for WM_MOUSEMOVE events
- // if there is a key release event in the queue
- // _before_ the mouse event, we have to also consider
- // key release events (kls 2003-05-13):
- MSG keyMsg;
- bool done = false;
- while (PeekMessage(&keyMsg, 0, WM_KEYFIRST, WM_KEYLAST,
- PM_NOREMOVE)) {
- if (keyMsg.time < mouseMsg.time) {
- if ((keyMsg.lParam & 0xC0000000) == 0x40000000) {
- PeekMessage(&keyMsg, 0, keyMsg.message,
- keyMsg.message, PM_REMOVE);
- } else {
- done = true;
- break;
- }
- } else {
- break; // no key event before the WM_MOUSEMOVE event
- }
- }
- if (done)
- break;
-#else
- // Actually the following 'if' should work instead of
- // the above key event checking, but apparently
- // PeekMessage() is broken :-(
- if (mouseMsg.wParam != msg.wParam)
- break; // leave the message in the queue because
- // the key state has changed
-#endif
- MSG *msgPtr = (MSG *)(&msg);
- // Update the passed in MSG structure with the
- // most recent one.
- msgPtr->lParam = mouseMsg.lParam;
- msgPtr->wParam = mouseMsg.wParam;
- // Extract the x,y coordinates from the lParam as we do in the WndProc
- msgPtr->pt.x = GET_X_LPARAM(mouseMsg.lParam);
- msgPtr->pt.y = GET_Y_LPARAM(mouseMsg.lParam);
- ClientToScreen(msg.hwnd, &(msgPtr->pt));
- // Remove the mouse move message
- PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEMOVE,
- WM_MOUSEMOVE, PM_REMOVE);
- } else {
- break; // there was no more WM_MOUSEMOVE event
- }
- }
- }
-
- for (i=0; (UINT)mouseTbl[i] != msg.message && mouseTbl[i]; i += 3)
- ;
- if (!mouseTbl[i])
- return false;
- type = (QEvent::Type)mouseTbl[++i]; // event type
- button = mouseTbl[++i]; // which button
- if (button == Qt::XButton1) {
- switch(GET_XBUTTON_WPARAM(msg.wParam)) {
- case XBUTTON1:
- button = Qt::XButton1;
- break;
- case XBUTTON2:
- button = Qt::XButton2;
- break;
- }
- }
-#ifndef Q_OS_WINCE
- static bool trackMouseEventLookup = false;
- typedef BOOL (WINAPI *PtrTrackMouseEvent)(LPTRACKMOUSEEVENT);
- static PtrTrackMouseEvent ptrTrackMouseEvent = 0;
-#endif
- state = translateButtonState(msg.wParam, type, button); // button state
- const QPoint widgetPos = mapFromGlobal(QPoint(msg.pt.x, msg.pt.y));
- QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos);
- if (alienWidget && alienWidget->internalWinId())
- alienWidget = 0;
-
- if (type == QEvent::MouseMove || type == QEvent::NonClientAreaMouseMove
- || type == QEvent::TabletMove) {
-
- if (!(state & Qt::MouseButtonMask))
- qt_button_down = 0;
-#ifndef QT_NO_CURSOR
- QCursor *c = qt_grab_cursor();
- if (!c)
- c = QApplication::overrideCursor();
- if (c) // application cursor defined
- SetCursor(c->handle());
- else if (type != QEvent::NonClientAreaMouseMove && !qt_button_down) {
- // use widget cursor if widget is enabled
- QWidget *w = alienWidget ? alienWidget : this;
- while (!w->isWindow() && !w->isEnabled())
- w = w->parentWidget();
- SetCursor(w->cursor().handle());
- }
-#endif // QT_NO_CURSOR
-
- HWND id = effectiveWinId();
- QWidget *mouseGrabber = QWidget::mouseGrabber();
- QWidget *activePopupWidget = QApplication::activePopupWidget();
- if (mouseGrabber) {
- if (!activePopupWidget || (activePopupWidget == this && !rect().contains(widgetPos)))
- id = mouseGrabber->effectiveWinId();
- } else if (type == QEvent::NonClientAreaMouseMove) {
- id = 0;
- }
-
- if (curWin != id) { // new current window
- if (id == 0) {
- QWidget *leave = qt_last_mouse_receiver;
- if (!leave)
- leave = QWidget::find(curWin);
- QApplicationPrivate::dispatchEnterLeave(0, leave);
- qt_last_mouse_receiver = 0;
- curWin = 0;
- } else {
- QWidget *leave = 0;
- if (curWin && qt_last_mouse_receiver)
- leave = qt_last_mouse_receiver;
- else
- leave = QWidget::find(curWin);
- QWidget *enter = alienWidget ? alienWidget : this;
- if (mouseGrabber && activePopupWidget) {
- if (leave != mouseGrabber)
- enter = mouseGrabber;
- else
- enter = activePopupWidget == this ? this : mouseGrabber;
- }
- QApplicationPrivate::dispatchEnterLeave(enter, leave);
- qt_last_mouse_receiver = enter;
- curWin = enter ? enter->effectiveWinId() : 0;
- }
-#ifndef Q_OS_WINCE
-
- if (curWin != 0) {
- if (!trackMouseEventLookup) {
- trackMouseEventLookup = true;
- ptrTrackMouseEvent = (PtrTrackMouseEvent)QSystemLibrary::resolve(QLatin1String("comctl32"), "_TrackMouseEvent");
- }
- if (ptrTrackMouseEvent && !qApp->d_func()->inPopupMode()) {
- // We always have to set the tracking, since
- // Windows detects more leaves than we do..
- TRACKMOUSEEVENT tme;
- tme.cbSize = sizeof(TRACKMOUSEEVENT);
- tme.dwFlags = 0x00000002; // TME_LEAVE
- tme.hwndTrack = curWin; // Track on window receiving msgs
- tme.dwHoverTime = (DWORD)-1; // HOVER_DEFAULT
- ptrTrackMouseEvent(&tme);
- }
- }
-#endif // Q_OS_WINCE
- }
-
- POINT curPos = msg.pt;
- if (curPos.x == gpos.x && curPos.y == gpos.y)
- return true; // same global position
- gpos = curPos;
-
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- ScreenToClient(internalWinId(), &curPos);
-
- pos.rx() = curPos.x;
- pos.ry() = curPos.y;
- pos = d_func()->mapFromWS(pos);
- } else {
- gpos = msg.pt;
- pos = mapFromGlobal(QPoint(gpos.x, gpos.y));
-
- // mouse button pressed
- if (!qt_button_down && (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonDblClick)) {
- QWidget *tlw = window();
- if (QWidget *child = tlw->childAt(mapTo(tlw, pos)))
- qt_button_down = child;
- else
- qt_button_down = this;
- }
- }
-
- bool res = false;
-
- bool nonClientAreaEvent = type >= QEvent::NonClientAreaMouseMove
- && type <= QEvent::NonClientAreaMouseButtonDblClick;
-
- if (qApp->d_func()->inPopupMode()) { // in popup mode
-
- if (nonClientAreaEvent)
- return false;
-
- replayPopupMouseEvent = false;
- QWidget* activePopupWidget = QApplication::activePopupWidget();
- QWidget *target = activePopupWidget;
- const QPoint globalPos(gpos.x, gpos.y);
-
- if (target != this) {
- if ((windowType() == Qt::Popup) && rect().contains(pos) && 0)
- target = this;
- else // send to last popup
- pos = target->mapFromGlobal(globalPos);
- }
- QWidget *popupChild = target->childAt(pos);
- bool releaseAfter = false;
- switch (type) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonDblClick:
- popupButtonFocus = popupChild;
- break;
- case QEvent::MouseButtonRelease:
- case QEvent::TabletRelease:
-
- releaseAfter = true;
- break;
- default:
- break; // nothing for mouse move
- }
-
- if (target->isEnabled()) {
- if (popupButtonFocus) {
- target = popupButtonFocus;
- } else if (popupChild) {
- target = popupChild;
- }
-
- pos = target->mapFromGlobal(globalPos);
- QMouseEvent e(type, pos, globalPos,
- Qt::MouseButton(button),
- Qt::MouseButtons(state & Qt::MouseButtonMask),
- Qt::KeyboardModifiers(state & Qt::KeyboardModifierMask));
- res = QApplicationPrivate::sendMouseEvent(target, &e, alienWidget, this, &qt_button_down,
- qt_last_mouse_receiver);
- res = res && e.isAccepted();
- } else {
- // close disabled popups when a mouse button is pressed or released
- switch (type) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseButtonRelease:
- target->close();
- break;
- default:
- break;
- }
- }
-
- if (releaseAfter) {
- popupButtonFocus = 0;
- qt_button_down = 0;
- }
-
-#ifndef Q_OS_WINCE
- if (type == QEvent::MouseButtonPress
- && QApplication::activePopupWidget() != activePopupWidget
- && ptrTrackMouseEvent
- && curWin) {
- // Since curWin is already the window we clicked on,
- // we have to setup the mouse tracking here.
- TRACKMOUSEEVENT tme;
- tme.cbSize = sizeof(TRACKMOUSEEVENT);
- tme.dwFlags = 0x00000002; // TME_LEAVE
- tme.hwndTrack = curWin; // Track on window receiving msgs
- tme.dwHoverTime = (DWORD)-1; // HOVER_DEFAULT
- ptrTrackMouseEvent(&tme);
- }
-#endif
- if (type == QEvent::MouseButtonPress
- && QApplication::activePopupWidget() != activePopupWidget
- && replayPopupMouseEvent) {
- // the popup disappeared. Replay the event
- QWidget* w = QApplication::widgetAt(gpos.x, gpos.y);
- if (w && !QApplicationPrivate::isBlockedByModal(w)) {
- Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
- HWND hwndTarget = w->effectiveWinId();
- if (QWidget::mouseGrabber() == 0)
- setAutoCapture(hwndTarget);
- if (!w->isActiveWindow())
- w->activateWindow();
- POINT widgetpt = gpos;
- ScreenToClient(hwndTarget, &widgetpt);
- LPARAM lParam = MAKELPARAM(widgetpt.x, widgetpt.y);
- PostMessage(hwndTarget, msg.message, msg.wParam, lParam);
- }
- } else if (type == QEvent::MouseButtonRelease && button == Qt::RightButton
- && QApplication::activePopupWidget() == activePopupWidget) {
- // popup still alive and received right-button-release
-#if !defined(QT_NO_CONTEXTMENU)
- QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos,
- qt_win_getKeyboardModifiers());
- bool res2 = QApplication::sendSpontaneousEvent( target, &e2 );
- if (!res) // RMB not accepted
- res = res2 && e2.isAccepted();
-#endif
- }
- } else { // not popup mode
- int bs = state & Qt::MouseButtonMask;
- if ((type == QEvent::MouseButtonPress ||
- type == QEvent::MouseButtonDblClick) && bs == button) {
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- if (QWidget::mouseGrabber() == 0)
- setAutoCapture(internalWinId());
- } else if (type == QEvent::MouseButtonRelease && bs == 0) {
- if (QWidget::mouseGrabber() == 0)
- releaseAutoCapture();
- }
-
- const QPoint globalPos(gpos.x,gpos.y);
- QWidget *widget = QApplicationPrivate::pickMouseReceiver(this, globalPos, pos, type,
- Qt::MouseButtons(bs),
- qt_button_down, alienWidget);
- if (!widget)
- return false; // don't send event
-
- QMouseEvent e(type, pos, globalPos, Qt::MouseButton(button),
- Qt::MouseButtons(state & Qt::MouseButtonMask),
- Qt::KeyboardModifiers(state & Qt::KeyboardModifierMask));
-
- res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down,
- qt_last_mouse_receiver);
-
- // non client area events are only informational, you cannot "handle" them
- res = res && e.isAccepted() && !nonClientAreaEvent;
-#if !defined(QT_NO_CONTEXTMENU)
- if (type == QEvent::MouseButtonRelease && button == Qt::RightButton) {
- QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos,
- qt_win_getKeyboardModifiers());
- bool res2 = QApplication::sendSpontaneousEvent(widget, &e2);
- if (!res)
- res = res2 && e2.isAccepted();
- }
-#endif
-
- if (type != QEvent::MouseMove)
- pos.rx() = pos.ry() = -9999; // init for move compression
- }
- return res;
-}
-
-bool QETWidget::translateWheelEvent(const MSG &msg)
-{
- int state = 0;
-
- if (sm_blockUserInput) // block user interaction during session management
- return true;
-
- state = translateButtonState(GET_KEYSTATE_WPARAM(msg.wParam), 0, 0);
-
- int delta;
- if (msg.message == WM_MOUSEWHEEL || msg.message == WM_MOUSEHWHEEL)
- delta = (short) HIWORD (msg.wParam);
- else
- delta = (int) msg.wParam;
-
- Qt::Orientation orient = (msg.message == WM_MOUSEHWHEEL || state&Qt::AltModifier
-#if 0
- // disabled for now - Trenton's one-wheel mouse makes trouble...
- // "delta" for usual wheels is +-120. +-240 seems to indicate
- // the second wheel see more recent MSDN for WM_MOUSEWHEEL
-
- ( // <- parantheses added to make update happy, remove if the
- // #if 0 is removed
- || delta == 240 || delta == -240)?Qt::Horizontal:Vertical;
- if (delta == 240 || delta == -240)
- delta /= 2;
-#endif
- ) ? Qt::Horizontal : Qt::Vertical;
-
- // according to the MSDN documentation on WM_MOUSEHWHEEL:
- // a positive value indicates that the wheel was rotated to the right;
- // a negative value indicates that the wheel was rotated to the left.
- // Qt defines this value as the exact opposite, so we have to flip the value!
- if (msg.message == WM_MOUSEHWHEEL)
- delta = -delta;
-
- QPoint globalPos;
-
- globalPos.rx() = (short)LOWORD (msg.lParam);
- globalPos.ry() = (short)HIWORD (msg.lParam);
-
-
- // if there is a widget under the mouse and it is not shadowed
- // by modality, we send the event to it first
- int ret = 0;
- QWidget* w = QApplication::widgetAt(globalPos);
- if (!w || !qt_try_modal(w, (MSG*)&msg, ret)) {
- //synaptics touchpad shows its own widget at this position
- //so widgetAt() will fail with that HWND, try child of this widget
- w = this->childAt(this->mapFromGlobal(globalPos));
- if (!w)
- w = this;
- }
-
- // send the event to the widget or its ancestors
- {
- QWidget* popup = QApplication::activePopupWidget();
- if (popup && w->window() != popup)
- popup->close();
-#ifndef QT_NO_WHEELEVENT
- QWheelEvent e(w->mapFromGlobal(globalPos), globalPos, delta,
- Qt::MouseButtons(state & Qt::MouseButtonMask),
- Qt::KeyboardModifier(state & Qt::KeyboardModifierMask), orient);
-
- if (QApplication::sendSpontaneousEvent(w, &e))
-#else
- Q_UNUSED(orient);
-#endif //QT_NO_WHEELEVENT
- return true;
- }
-
- // send the event to the widget that has the focus or its ancestors, if different
- if (w != QApplication::focusWidget() && (w = QApplication::focusWidget())) {
- QWidget* popup = QApplication::activePopupWidget();
- if (popup && w->window() != popup)
- popup->close();
-#ifndef QT_NO_WHEELEVENT
- QWheelEvent e(w->mapFromGlobal(globalPos), globalPos, delta,
- Qt::MouseButtons(state & Qt::MouseButtonMask),
- Qt::KeyboardModifier(state & Qt::KeyboardModifierMask), orient);
- if (QApplication::sendSpontaneousEvent(w, &e))
-#endif //QT_NO_WHEELEVENT
- return true;
- }
- return false;
-}
-
-
-//
-// Windows Wintab to QTabletEvent translation
-//
-
-// the following is adapted from the wintab syspress example (public domain)
-/* -------------------------------------------------------------------------- */
-// Initialize the "static" information of a cursor device (pen, airbrush, etc).
-// The QTabletDeviceData is initialized with the data that do not change in time
-// (number of button, type of device, etc) but do not initialize the variable data
-// (e.g.: pen or eraser)
-#ifndef QT_NO_TABLETEVENT
-
-static void tabletInit(const quint64 uniqueId, const UINT csr_type, HCTX hTab)
-{
- Q_ASSERT(ptrWTInfo);
- Q_ASSERT(ptrWTGet);
-
- Q_ASSERT(!tCursorInfo()->contains(uniqueId));
-
- /* browse WinTab's many info items to discover pressure handling. */
- AXIS np;
- LOGCONTEXT lc;
-
- /* get the current context for its device variable. */
- ptrWTGet(hTab, &lc);
-
- /* get the size of the pressure axis. */
- QTabletDeviceData tdd;
- tdd.llId = uniqueId;
-
- ptrWTInfo(WTI_DEVICES + lc.lcDevice, DVC_NPRESSURE, &np);
- tdd.minPressure = int(np.axMin);
- tdd.maxPressure = int(np.axMax);
-
- ptrWTInfo(WTI_DEVICES + lc.lcDevice, DVC_TPRESSURE, &np);
- tdd.minTanPressure = int(np.axMin);
- tdd.maxTanPressure = int(np.axMax);
-
- LOGCONTEXT lcMine;
-
- /* get default region */
- ptrWTInfo(WTI_DEFCONTEXT, 0, &lcMine);
-
- tdd.minX = 0;
- tdd.maxX = int(lcMine.lcInExtX) - int(lcMine.lcInOrgX);
-
- tdd.minY = 0;
- tdd.maxY = int(lcMine.lcInExtY) - int(lcMine.lcInOrgY);
-
- tdd.minZ = 0;
- tdd.maxZ = int(lcMine.lcInExtZ) - int(lcMine.lcInOrgZ);
-
- const uint cursorTypeBitMask = 0x0F06; // bitmask to find the specific cursor type (see Wacom FAQ)
- if (((csr_type & 0x0006) == 0x0002) && ((csr_type & cursorTypeBitMask) != 0x0902)) {
- tdd.currentDevice = QTabletEvent::Stylus;
- } else {
- switch (csr_type & cursorTypeBitMask) {
- case 0x0802:
- tdd.currentDevice = QTabletEvent::Stylus;
- break;
- case 0x0902:
- tdd.currentDevice = QTabletEvent::Airbrush;
- break;
- case 0x0004:
- tdd.currentDevice = QTabletEvent::FourDMouse;
- break;
- case 0x0006:
- tdd.currentDevice = QTabletEvent::Puck;
- break;
- case 0x0804:
- tdd.currentDevice = QTabletEvent::RotationStylus;
- break;
- default:
- tdd.currentDevice = QTabletEvent::NoDevice;
- }
- }
- tCursorInfo()->insert(uniqueId, tdd);
-}
-#endif // QT_NO_TABLETEVENT
-
-// Update the "dynamic" information of a cursor device (pen, airbrush, etc).
-// The dynamic information is the information of QTabletDeviceData that can change
-// in time (eraser or pen if a device is turned around).
-#ifndef QT_NO_TABLETEVENT
-
-static void tabletUpdateCursor(QTabletDeviceData &tdd, const UINT currentCursor)
-{
- switch (currentCursor % 3) { // %3 for dual track
- case 0:
- tdd.currentPointerType = QTabletEvent::Cursor;
- break;
- case 1:
- tdd.currentPointerType = QTabletEvent::Pen;
- break;
- case 2:
- tdd.currentPointerType = QTabletEvent::Eraser;
- break;
- default:
- tdd.currentPointerType = QTabletEvent::UnknownPointer;
- }
-}
-#endif // QT_NO_TABLETEVENT
-
-bool QETWidget::translateTabletEvent(const MSG &msg, PACKET *localPacketBuf,
- int numPackets)
-{
- Q_UNUSED(msg);
- POINT ptNew;
- static DWORD btnNew, btnOld, btnChange;
- qreal prsNew;
- ORIENTATION ort;
- static bool button_pressed = false;
- int i,
- tiltX,
- tiltY;
- bool sendEvent = false;
- QEvent::Type t;
- int z = 0;
- qreal rotation = 0.0;
- qreal tangentialPressure;
-
- // the most common event that we get...
- t = QEvent::TabletMove;
- for (i = 0; i < numPackets; i++) {
- // get the unique ID of the device...
- btnOld = btnNew;
- btnNew = localPacketBuf[i].pkButtons;
- btnChange = btnOld ^ btnNew;
-
- if (btnNew & btnChange) {
- button_pressed = true;
- t = QEvent::TabletPress;
- }
- ptNew.x = UINT(localPacketBuf[i].pkX);
- ptNew.y = UINT(localPacketBuf[i].pkY);
-#ifndef QT_NO_TABLETEVENT
- z = (currentTabletPointer.currentDevice == QTabletEvent::FourDMouse) ? UINT(localPacketBuf[i].pkZ) : 0;
-#else
- Q_UNUSED(z);
-#endif // QT_NO_TABLETEVENT
- prsNew = 0.0;
- QRect desktopArea = QApplication::desktop()->geometry();
- QPointF hiResGlobal = currentTabletPointer.scaleCoord(ptNew.x, ptNew.y, desktopArea.left(),
- desktopArea.width(), desktopArea.top(),
- desktopArea.height());
-
- if (btnNew) {
-#ifndef QT_NO_TABLETEVENT
- if (currentTabletPointer.currentPointerType == QTabletEvent::Pen || currentTabletPointer.currentPointerType == QTabletEvent::Eraser)
- prsNew = localPacketBuf[i].pkNormalPressure
- / qreal(currentTabletPointer.maxPressure
- - currentTabletPointer.minPressure);
- else
-#endif // QT_NO_TABLETEVENT
- prsNew = 0;
- } else if (button_pressed) {
- // One button press, should only give one button release
- t = QEvent::TabletRelease;
- button_pressed = false;
- }
- QPoint globalPos(qRound(hiResGlobal.x()), qRound(hiResGlobal.y()));
-
- if (t == QEvent::TabletPress)
- {
- qt_button_down = QApplication::widgetAt(globalPos);
- }
-
- // make sure the tablet event get's sent to the proper widget...
- QWidget *w = 0;
-
- if (qt_button_down)
- w = qt_button_down; // Pass it to the thing that's grabbed it.
- else
- w = QApplication::widgetAt(globalPos);
-
- if (!w)
- w = this;
-
- if (t == QEvent::TabletRelease)
- {
- if (qt_win_ignoreNextMouseReleaseEvent) {
- qt_win_ignoreNextMouseReleaseEvent = false;
- if (qt_button_down && qt_button_down->internalWinId() == autoCaptureWnd) {
- releaseAutoCapture();
- qt_button_down = 0;
- }
- }
-
- }
-
- QPoint localPos = w->mapFromGlobal(globalPos);
-#ifndef QT_NO_TABLETEVENT
- if (currentTabletPointer.currentDevice == QTabletEvent::Airbrush) {
- tangentialPressure = localPacketBuf[i].pkTangentPressure
- / qreal(currentTabletPointer.maxTanPressure
- - currentTabletPointer.minTanPressure);
- } else {
- tangentialPressure = 0.0;
- }
-#else
- tangentialPressure = 0.0;
-#endif // QT_NO_TABLETEVENT
-
- if (!qt_tablet_tilt_support) {
- tiltX = tiltY = 0;
- rotation = 0.0;
- } else {
- ort = localPacketBuf[i].pkOrientation;
- // convert from azimuth and altitude to x tilt and y tilt
- // what follows is the optimized version. Here are the equations
- // I used to get to this point (in case things change :)
- // X = sin(azimuth) * cos(altitude)
- // Y = cos(azimuth) * cos(altitude)
- // Z = sin(altitude)
- // X Tilt = arctan(X / Z)
- // Y Tilt = arctan(Y / Z)
- double radAzim = (ort.orAzimuth / 10) * (Q_PI / 180);
- //double radAlt = abs(ort.orAltitude / 10) * (Q_PI / 180);
- double tanAlt = tan((abs(ort.orAltitude / 10)) * (Q_PI / 180));
-
- double degX = atan(sin(radAzim) / tanAlt);
- double degY = atan(cos(radAzim) / tanAlt);
- tiltX = int(degX * (180 / Q_PI));
- tiltY = int(-degY * (180 / Q_PI));
- rotation = ort.orTwist;
- }
-#ifndef QT_NO_TABLETEVENT
- QTabletEvent e(t, localPos, globalPos, hiResGlobal, currentTabletPointer.currentDevice,
- currentTabletPointer.currentPointerType, prsNew, tiltX, tiltY,
- tangentialPressure, rotation, z, QApplication::keyboardModifiers(), currentTabletPointer.llId);
- sendEvent = QApplication::sendSpontaneousEvent(w, &e);
-#endif // QT_NO_TABLETEVENT
- }
- return sendEvent;
-}
-
-extern bool qt_is_gui_used;
-
-
-#ifndef QT_NO_TABLETEVENT
-
-static void initWinTabFunctions()
-{
-#if defined(Q_OS_WINCE)
- return;
-#else
- if (!qt_is_gui_used)
- return;
-
- QSystemLibrary library(QLatin1String("wintab32"));
- ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW");
- ptrWTGet = (PtrWTGet)library.resolve("WTGetW");
- ptrWTEnable = (PtrWTEnable)library.resolve("WTEnable");
- ptrWTOverlap = (PtrWTEnable)library.resolve("WTOverlap");
- ptrWTPacketsGet = (PtrWTPacketsGet)library.resolve("WTPacketsGet");
-#endif // Q_OS_WINCE
-}
-#endif // QT_NO_TABLETEVENT
-
-
-//
-// Paint event translation
-//
-bool QETWidget::translatePaintEvent(const MSG &msg)
-{
- if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
- Q_ASSERT(internalWinId());
-
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- if (!GetUpdateRect(internalWinId(), 0, FALSE)) { // The update bounding rect is invalid
- d_func()->hd = 0;
- setAttribute(Qt::WA_PendingUpdate, false);
- return false;
- }
-
- if (msg.message == WM_ERASEBKGND)
- return true;
-
- setAttribute(Qt::WA_PendingUpdate, false);
-
- if (d_func()->isGLWidget) {
- if (d_func()->usesDoubleBufferedGLContext)
- InvalidateRect(internalWinId(), 0, false);
- } else {
- const QRegion dirtyInBackingStore(qt_dirtyRegion(this));
- // Make sure the invalidated region contains the region we're about to repaint.
- // BeginPaint will set the clip to the invalidated region and it is impossible
- // to enlarge it afterwards (only shrink it). Using GetDCEx is not suffient
- // as it may return an invalid context (especially on Windows Vista).
- if (!dirtyInBackingStore.isEmpty())
- InvalidateRgn(internalWinId(), dirtyInBackingStore.handle(), false);
- }
- PAINTSTRUCT ps;
- d_func()->hd = BeginPaint(internalWinId(), &ps);
-
- const QRect updateRect(QPoint(ps.rcPaint.left, ps.rcPaint.top),
- QPoint(ps.rcPaint.right, ps.rcPaint.bottom));
-
- // Mapping region from system to qt (32 bit) coordinate system.
- d_func()->syncBackingStore(updateRect.translated(data->wrect.topLeft()));
-
- d_func()->hd = 0;
- EndPaint(internalWinId(), &ps);
-
- return true;
-}
-
-//
-// Window move and resize (configure) events
-//
-
-bool QETWidget::translateConfigEvent(const MSG &msg)
-{
- if (!testAttribute(Qt::WA_WState_Created)) // in QWidget::create()
- return true;
- if (testAttribute(Qt::WA_WState_ConfigPending))
- return true;
- if (testAttribute(Qt::WA_DontShowOnScreen))
- return true;
- if (!isWindow())
- return true;
- setAttribute(Qt::WA_WState_ConfigPending); // set config flag
- QRect cr = geometry();
- if (msg.message == WM_SIZE) { // resize event
- WORD a = LOWORD(msg.lParam);
- WORD b = HIWORD(msg.lParam);
- QSize oldSize = size();
- QSize newSize(a, b);
-#ifdef Q_WS_WINCE_WM
- if (isFullScreen() && (oldSize.width() == newSize.height()) && (oldSize.height() == newSize.width()))
- qt_wince_hide_taskbar(internalWinId());
-#endif
- cr.setSize(newSize);
- if (msg.wParam != SIZE_MINIMIZED)
- data->crect = cr;
- if (isWindow()) { // update title/icon text
- d_func()->createTLExtra();
- // Capture SIZE_MINIMIZED without preceding WM_SYSCOMMAND
- // (like Windows+M)
- if (msg.wParam == SIZE_MINIMIZED && !isMinimized()) {
-#ifndef Q_WS_WINCE
- const QString title = windowIconText();
- if (!title.isEmpty())
- d_func()->setWindowTitle_helper(title);
-#endif
- data->window_state |= Qt::WindowMinimized;
- if (isVisible()) {
- QHideEvent e;
- QApplication::sendSpontaneousEvent(this, &e);
- hideChildren(true);
- }
- } else if (msg.wParam != SIZE_MINIMIZED) {
- bool window_state_changed = false;
- Qt::WindowStates oldstate = Qt::WindowStates(dataPtr()->window_state);
- if (isMinimized()) {
-#ifndef Q_WS_WINCE
- const QString title = windowTitle();
- if (!title.isEmpty())
- d_func()->setWindowTitle_helper(title);
-#endif
- data->window_state &= ~Qt::WindowMinimized;
- showChildren(true);
- QShowEvent e;
- QApplication::sendSpontaneousEvent(this, &e);
- // Capture SIZE_MAXIMIZED and SIZE_RESTORED without preceding WM_SYSCOMMAND
- // (Aero Snap on Win7)
- } else if (msg.wParam == SIZE_MAXIMIZED && !isMaximized()) {
- data->window_state |= Qt::WindowMaximized;
- window_state_changed = true;
- } else if (msg.wParam == SIZE_RESTORED && isMaximized()) {
- data->window_state &= ~(Qt::WindowMaximized);
- window_state_changed = true;
- }
- if (window_state_changed) {
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendSpontaneousEvent(this, &e);
- }
- }
- }
- if (msg.wParam != SIZE_MINIMIZED && oldSize != newSize) {
- if (isVisible()) {
- QTLWExtra *tlwExtra = maybeTopData();
- static bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
- const bool hasStaticContents = tlwExtra && tlwExtra->backingStore
- && tlwExtra->backingStore->hasStaticContents();
- // If we have a backing store with static contents, we have to disable the top-level
- // resize optimization in order to get invalidated regions for resized widgets.
- // The optimization discards all invalidateBuffer() calls since we're going to
- // repaint everything anyways, but that's not the case with static contents.
- if (!slowResize && tlwExtra && !hasStaticContents)
- tlwExtra->inTopLevelResize = true;
- QResizeEvent e(newSize, oldSize);
- QApplication::sendSpontaneousEvent(this, &e);
- if (d_func()->paintOnScreen()) {
- QRegion updateRegion(rect());
- if (testAttribute(Qt::WA_StaticContents))
- updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
- d_func()->syncBackingStore(updateRegion);
- } else {
- d_func()->syncBackingStore();
- }
- if (!slowResize && tlwExtra)
- tlwExtra->inTopLevelResize = false;
- } else {
- QResizeEvent *e = new QResizeEvent(newSize, oldSize);
- QApplication::postEvent(this, e);
- }
- }
- } else if (msg.message == WM_MOVE) { // move event
- int a = (int) (short) LOWORD(msg.lParam);
- int b = (int) (short) HIWORD(msg.lParam);
- QPoint oldPos = geometry().topLeft();
- QPoint newCPos(a, b);
- // Ignore silly Windows move event to wild pos after iconify.
-#if !defined(Q_WS_WINCE)
- if (!IsIconic(internalWinId()) && newCPos != oldPos) {
-#endif
- cr.moveTopLeft(newCPos);
- data->crect = cr;
- if (isVisible()) {
- QMoveEvent e(newCPos, oldPos); // cpos (client position)
- QApplication::sendSpontaneousEvent(this, &e);
- } else {
- QMoveEvent * e = new QMoveEvent(newCPos, oldPos);
- QApplication::postEvent(this, e);
- }
-#if !defined(Q_WS_WINCE)
- }
-#endif
- }
- setAttribute(Qt::WA_WState_ConfigPending, false); // clear config flag
- return true;
-}
-
-
-//
-// Close window event translation.
-//
-// This class is a friend of QApplication because it needs to emit the
-// lastWindowClosed() signal when the last top level widget is closed.
-//
-
-bool QETWidget::translateCloseEvent(const MSG &)
-{
- return d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-}
-
-#ifndef QT_NO_GESTURES
-bool QETWidget::translateGestureEvent(const MSG &, const GESTUREINFO &gi)
-{
- const QPoint widgetPos = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
- QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos);
- if (alienWidget && alienWidget->internalWinId())
- alienWidget = 0;
- QWidget *widget = alienWidget ? alienWidget : this;
-
- QNativeGestureEvent event;
- event.sequenceId = gi.dwSequenceID;
- event.position = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
- event.argument = gi.ullArguments;
-
- switch (gi.dwID) {
- case GID_BEGIN:
- event.gestureType = QNativeGestureEvent::GestureBegin;
- break;
- case GID_END:
- event.gestureType = QNativeGestureEvent::GestureEnd;
- break;
- case GID_ZOOM:
- event.gestureType = QNativeGestureEvent::Zoom;
- break;
- case GID_PAN:
- event.gestureType = QNativeGestureEvent::Pan;
- break;
- case GID_ROTATE:
- event.gestureType = QNativeGestureEvent::Rotate;
- break;
- case GID_TWOFINGERTAP:
- case GID_ROLLOVER:
- default:
- break;
- }
- if (event.gestureType != QNativeGestureEvent::None)
- qt_sendSpontaneousEvent(widget, &event);
- return true;
-}
-#endif // QT_NO_GESTURES
-
-void QApplication::setCursorFlashTime(int msecs)
-{
- SetCaretBlinkTime(msecs / 2);
- QApplicationPrivate::cursor_flash_time = msecs;
-}
-
-
-int QApplication::cursorFlashTime()
-{
- int blink = (int)GetCaretBlinkTime();
- if (!blink)
- return QApplicationPrivate::cursor_flash_time;
- if (blink > 0)
- return 2*blink;
- return 0;
-}
-
-
-void QApplication::setDoubleClickInterval(int ms)
-{
-#ifndef Q_WS_WINCE
- SetDoubleClickTime(ms);
-#endif
- QApplicationPrivate::mouse_double_click_time = ms;
-}
-
-int QApplication::doubleClickInterval()
-{
- int ms = GetDoubleClickTime();
- if (ms != 0)
- return ms;
- 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)
-{
-#ifdef SPI_SETWHEELSCROLLLINES
- if (n < 0)
- n = 0;
- SystemParametersInfo(SPI_SETWHEELSCROLLLINES, (uint)n, 0, 0);
-#else
- QApplicationPrivate::wheel_scroll_lines = n;
-#endif
-}
-
-int QApplication::wheelScrollLines()
-{
-#ifdef SPI_GETWHEELSCROLLLINES
- uint i = 3;
- SystemParametersInfo(SPI_GETWHEELSCROLLLINES, sizeof(uint), &i, 0);
- if (i > INT_MAX)
- i = INT_MAX;
- return i;
-#else
- return QApplicationPrivate::wheel_scroll_lines;
-#endif
-}
-#endif //QT_NO_WHEELEVENT
-
-static bool effect_override = false;
-
-void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
-{
- effect_override = true;
- switch (effect) {
- case Qt::UI_AnimateMenu:
- QApplicationPrivate::animate_menu = enable;
- break;
- case Qt::UI_FadeMenu:
- 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:
- 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)
- return false;
-
- if (!effect_override && desktopSettingsAware()) {
- // we know that they can be used when we are here
- BOOL enabled = false;
- UINT api;
- switch (effect) {
- case Qt::UI_AnimateMenu:
- api = SPI_GETMENUANIMATION;
- break;
- case Qt::UI_FadeMenu:
- api = SPI_GETMENUFADE;
- break;
- case Qt::UI_AnimateCombo:
- api = SPI_GETCOMBOBOXANIMATION;
- break;
- case Qt::UI_AnimateTooltip:
- api = SPI_GETTOOLTIPANIMATION;
- break;
- case Qt::UI_FadeTooltip:
- api = SPI_GETTOOLTIPFADE;
- break;
- default:
- api = SPI_GETUIEFFECTS;
- break;
- }
- SystemParametersInfo(api, 0, &enabled, 0);
- return enabled;
- }
-
- 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_SESSIONMANAGER
-
-bool QSessionManager::allowsInteraction()
-{
- sm_blockUserInput = false;
- return true;
-}
-
-bool QSessionManager::allowsErrorInteraction()
-{
- sm_blockUserInput = false;
- return true;
-}
-
-void QSessionManager::release()
-{
- if (sm_smActive)
- sm_blockUserInput = true;
-}
-
-void QSessionManager::cancel()
-{
- sm_cancel = true;
-}
-
-#endif //QT_NO_SESSIONMANAGER
-
-
-bool QApplicationPrivate::HasTouchSupport = false;
-PtrRegisterTouchWindow QApplicationPrivate::RegisterTouchWindow = 0;
-PtrGetTouchInputInfo QApplicationPrivate::GetTouchInputInfo = 0;
-PtrCloseTouchInputHandle QApplicationPrivate::CloseTouchInputHandle = 0;
-
-void QApplicationPrivate::initializeMultitouch_sys()
-{
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7) {
- static const int QT_SM_DIGITIZER = 94;
- int value = GetSystemMetrics(QT_SM_DIGITIZER);
- static const int QT_NID_INTEGRATED_TOUCH = 0x01;
- static const int QT_NID_EXTERNAL_TOUCH = 0x02;
- static const int QT_NID_MULTI_INPUT = 0x40;
- QApplicationPrivate::HasTouchSupport =
- value & (QT_NID_INTEGRATED_TOUCH | QT_NID_EXTERNAL_TOUCH | QT_NID_MULTI_INPUT);
- }
-
- QSystemLibrary library(QLatin1String("user32"));
- // MinGW (g++ 3.4.5) accepts only C casts.
- RegisterTouchWindow = (PtrRegisterTouchWindow)(library.resolve("RegisterTouchWindow"));
- GetTouchInputInfo = (PtrGetTouchInputInfo)(library.resolve("GetTouchInputInfo"));
- CloseTouchInputHandle = (PtrCloseTouchInputHandle)(library.resolve("CloseTouchInputHandle"));
-
- touchInputIDToTouchPointID.clear();
-}
-
-void QApplicationPrivate::cleanupMultitouch_sys()
-{
- touchInputIDToTouchPointID.clear();
-}
-
-bool QApplicationPrivate::translateTouchEvent(const MSG &msg)
-{
- QWidget *widgetForHwnd = QWidget::find(msg.hwnd);
- if (!widgetForHwnd)
- return false;
-
- QRect screenGeometry = QApplication::desktop()->screenGeometry(widgetForHwnd);
-
- QList<QTouchEvent::TouchPoint> touchPoints;
-
- QVector<TOUCHINPUT> winTouchInputs(msg.wParam);
- memset(winTouchInputs.data(), 0, sizeof(TOUCHINPUT) * winTouchInputs.count());
- Qt::TouchPointStates allStates = 0;
- QApplicationPrivate::GetTouchInputInfo((HANDLE) msg.lParam, msg.wParam, winTouchInputs.data(), sizeof(TOUCHINPUT));
- for (int i = 0; i < winTouchInputs.count(); ++i) {
- const TOUCHINPUT &touchInput = winTouchInputs.at(i);
-
- int touchPointID = touchInputIDToTouchPointID.value(touchInput.dwID, -1);
- if (touchPointID == -1) {
- touchPointID = touchInputIDToTouchPointID.count();
- touchInputIDToTouchPointID.insert(touchInput.dwID, touchPointID);
- }
-
- QTouchEvent::TouchPoint touchPoint(touchPointID);
-
- // update state
- QPointF screenPos(qreal(touchInput.x) / qreal(100.), qreal(touchInput.y) / qreal(100.));
- QRectF screenRect;
- if (touchInput.dwMask & TOUCHINPUTMASKF_CONTACTAREA)
- screenRect.setSize(QSizeF(qreal(touchInput.cxContact) / qreal(100.),
- qreal(touchInput.cyContact) / qreal(100.)));
- screenRect.moveCenter(screenPos);
-
- Qt::TouchPointStates state;
- if (touchInput.dwFlags & TOUCHEVENTF_DOWN) {
- state = Qt::TouchPointPressed;
- } else if (touchInput.dwFlags & TOUCHEVENTF_UP) {
- state = Qt::TouchPointReleased;
- } else {
- state = (screenPos == touchPoint.screenPos()
- ? Qt::TouchPointStationary
- : Qt::TouchPointMoved);
- }
- if (touchInput.dwFlags & TOUCHEVENTF_PRIMARY)
- state |= Qt::TouchPointPrimary;
- touchPoint.setState(state);
- touchPoint.setScreenRect(screenRect);
- touchPoint.setNormalizedPos(QPointF(screenPos.x() / screenGeometry.width(),
- screenPos.y() / screenGeometry.height()));
-
- allStates |= state;
-
- touchPoints.append(touchPoint);
- }
- QApplicationPrivate::CloseTouchInputHandle((HANDLE) msg.lParam);
-
- if ((allStates & Qt::TouchPointStateMask) == Qt::TouchPointReleased) {
- // all touch points released, forget the ids we've seen, they may not be reused
- touchInputIDToTouchPointID.clear();
- }
-
- translateRawTouchEvent(widgetForHwnd, QTouchEvent::TouchScreen, touchPoints);
- return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qclipboard_win.cpp b/src/gui/platforms/win/qclipboard_win.cpp
deleted file mode 100644
index ea41165b9c..0000000000
--- a/src/gui/platforms/win/qclipboard_win.cpp
+++ /dev/null
@@ -1,398 +0,0 @@
-/****************************************************************************
-**
-** 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 "qclipboard.h"
-
-#ifndef QT_NO_CLIPBOARD
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qeventloop.h"
-#include "qwidget.h"
-#include "qevent.h"
-#include "qmime.h"
-#include "qt_windows.h"
-#include "qdnd_p.h"
-#include <private/qwidget_p.h>
-#include <private/qsystemlibrary_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#if defined(Q_OS_WINCE)
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qguifunctions_wince.h"
-QT_END_INCLUDE_NAMESPACE
-
-HRESULT QtCeGetClipboard(IDataObject** obj);
-HRESULT QtCeSetClipboard(IDataObject* obj);
-void QtCeFlushClipboard();
-
-#define OleGetClipboard QtCeGetClipboard
-#define OleSetClipboard QtCeSetClipboard
-#define OleFlushClipboard QtCeFlushClipboard
-
-#endif
-
-typedef BOOL (WINAPI *PtrIsHungAppWindow)(HWND);
-
-static PtrIsHungAppWindow ptrIsHungAppWindow = 0;
-
-class QClipboardWatcher : public QInternalMimeData {
-public:
- QClipboardWatcher()
- : QInternalMimeData()
- {
- }
-
- bool hasFormat_sys(const QString &mimetype) const;
- QStringList formats_sys() const;
- QVariant retrieveData_sys(const QString &mimetype, QVariant::Type preferredType) const;
-};
-
-
-bool QClipboardWatcher::hasFormat_sys(const QString &mime) const
-{
- IDataObject * pDataObj = 0;
-
- if (OleGetClipboard(&pDataObj) != S_OK && !pDataObj) // Sanity
- return false;
-
- bool has = QWindowsMime::converterToMime(mime, pDataObj) != 0;
-
- pDataObj->Release();
-
- return has;
-}
-
-QStringList QClipboardWatcher::formats_sys() const
-{
- QStringList fmts;
- IDataObject * pDataObj = 0;
-
- if (OleGetClipboard(&pDataObj) != S_OK && !pDataObj) // Sanity
- return QStringList();
-
- fmts = QWindowsMime::allMimesForFormats(pDataObj);
-
- pDataObj->Release();
-
- return fmts;
-}
-
-QVariant QClipboardWatcher::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
-{
- QVariant result;
- IDataObject * pDataObj = 0;
-
- if (OleGetClipboard(&pDataObj) != S_OK && !pDataObj) // Sanity
- return result;
-
- QWindowsMime *converter = QWindowsMime::converterToMime(mimeType, pDataObj);
-
- if (converter)
- result = converter->convertToMime(mimeType, pDataObj, type);
-
- pDataObj->Release();
-
- return result;
-}
-
-class QClipboardData
-{
-public:
- QClipboardData()
- : iData(0)
- , nextClipboardViewer(0)
- {
- clipBoardViewer = new QWidget();
- clipBoardViewer->createWinId();
- clipBoardViewer->setObjectName(QLatin1String("internal clipboard owner"));
- // We don't need this internal widget to appear in QApplication::topLevelWidgets()
- if (QWidgetPrivate::allWidgets)
- QWidgetPrivate::allWidgets->remove(clipBoardViewer);
- }
-
- ~QClipboardData()
- {
- Q_ASSERT(clipBoardViewer->testAttribute(Qt::WA_WState_Created));
- ChangeClipboardChain(clipBoardViewer->internalWinId(), nextClipboardViewer);
- delete clipBoardViewer;
- releaseIData();
- }
-
- void releaseIData()
- {
- if (iData) {
- delete iData->mimeData();
- iData->releaseQt();
- iData->Release();
- iData = 0;
- }
- }
-
- QOleDataObject * iData;
- QWidget *clipBoardViewer;
- HWND nextClipboardViewer;
- QClipboardWatcher watcher;
-};
-
-static QClipboardData *ptrClipboardData = 0;
-
-static QClipboardData *clipboardData()
-{
- if (ptrClipboardData == 0) {
- ptrClipboardData = new QClipboardData;
- // this needs to be done here to avoid recursion
- Q_ASSERT(ptrClipboardData->clipBoardViewer->testAttribute(Qt::WA_WState_Created));
- ptrClipboardData->nextClipboardViewer = SetClipboardViewer(ptrClipboardData->clipBoardViewer->internalWinId());
- }
- return ptrClipboardData;
-}
-
-static void cleanupClipboardData()
-{
- delete ptrClipboardData;
- ptrClipboardData = 0;
-}
-
-#if defined(Q_OS_WINCE)
-HRESULT QtCeGetClipboard(IDataObject** obj)
-{
- HWND owner = ptrClipboardData->clipBoardViewer->internalWinId();
- if (!OpenClipboard(owner))
- return !S_OK;
-
- if (!IsClipboardFormatAvailable(CF_TEXT) && !IsClipboardFormatAvailable(CF_UNICODETEXT))
- return !S_OK;
-
- HANDLE clipData = GetClipboardData(CF_TEXT);
- QString clipText;
- if (clipData == 0) {
- clipData = GetClipboardData(CF_UNICODETEXT);
- if (clipData != 0)
- clipText = QString::fromWCharArray((wchar_t *)clipData);
- } else {
- clipText = QString::fromLatin1((const char*)clipData);
- }
-
- QMimeData *mimeData = new QMimeData();
- mimeData->setText(clipText);
- QOleDataObject* data = new QOleDataObject(mimeData);
- *obj = data;
- CloseClipboard();
- return S_OK;
-}
-
-HRESULT QtCeSetClipboard(IDataObject* obj)
-{
- HWND owner = ptrClipboardData->clipBoardViewer->internalWinId();
- if (!OpenClipboard(owner))
- return !S_OK;
-
- bool result = false;
- if (obj == 0) {
- result = true;
- EmptyClipboard();
- CloseClipboard();
- } else {
- QOleDataObject* qobj = static_cast<QOleDataObject*>(obj);
-
- const QMimeData* data = qobj->mimeData();
- if (data->hasText()) {
- EmptyClipboard();
- result = SetClipboardData(CF_UNICODETEXT, wcsdup(reinterpret_cast<const wchar_t *> (data->text().utf16()))) != NULL;
- CloseClipboard();
- result = true;
- }
- }
- return result ? S_OK : !S_OK;
-}
-
-void QtCeFlushClipboard() { }
-#endif
-
-
-
-QClipboard::~QClipboard()
-{
- cleanupClipboardData();
-}
-
-void QClipboard::setMimeData(QMimeData *src, Mode mode)
-{
- if (mode != Clipboard)
- return;
- QClipboardData *d = clipboardData();
-
- if (!(d->iData && d->iData->mimeData() == src)) {
- d->releaseIData();
- d->iData = new QOleDataObject(src);
- }
-
- if (OleSetClipboard(d->iData) != S_OK) {
- d->releaseIData();
- qErrnoWarning("QClipboard::setMimeData: Failed to set data on clipboard");
- return;
- }
-#if defined(Q_OS_WINCE)
- // As WinCE does not support notifications we send the signal here
- // We will get no event when the clipboard changes outside...
- emit dataChanged();
- emit changed(Clipboard);
-#endif
-}
-
-void QClipboard::clear(Mode mode)
-{
- if (mode != Clipboard) return;
-
- QClipboardData *d = clipboardData();
-
- d->releaseIData();
-
- if (OleSetClipboard(0) != S_OK) {
- qErrnoWarning("QClipboard::clear: Failed to clear data on clipboard");
- return;
- }
-#if defined(Q_OS_WINCE)
- // As WinCE does not support notifications we send the signal here
- // We will get no event when the clipboard changes outside...
- emit dataChanged();
- emit changed(Clipboard);
-#endif
-}
-
-bool QClipboard::event(QEvent *e)
-{
- if (e->type() != QEvent::Clipboard)
- return QObject::event(e);
-
- QClipboardData *d = clipboardData();
-
- MSG *m = (MSG *)((QClipboardEvent*)e)->data();
- if (!m) {
- // this is sent to render all formats at app shut down
- if (ownsClipboard()) {
- OleFlushClipboard();
- d->releaseIData();
- }
- return true;
- }
-
- bool propagate = false;
-
- if (m->message == WM_CHANGECBCHAIN) {
- if ((HWND)m->wParam == d->nextClipboardViewer)
- d->nextClipboardViewer = (HWND)m->lParam;
- else
- propagate = true;
- } else if (m->message == WM_DRAWCLIPBOARD) {
- emitChanged(QClipboard::Clipboard);
- if (!ownsClipboard() && d->iData)
- // clean up the clipboard object if we no longer own the clipboard
- d->releaseIData();
- propagate = true;
- }
- if (propagate && d->nextClipboardViewer) {
- if (ptrIsHungAppWindow == 0) {
- QSystemLibrary library(QLatin1String("User32"));
- ptrIsHungAppWindow = (PtrIsHungAppWindow)library.resolve("IsHungAppWindow");
- }
- if (ptrIsHungAppWindow && ptrIsHungAppWindow(d->nextClipboardViewer)) {
- qWarning("%s: Cowardly refusing to send clipboard message to hung application...", Q_FUNC_INFO);
- } else {
- SendMessage(d->nextClipboardViewer, m->message, m->wParam, m->lParam);
- }
- }
-
- return true;
-}
-
-void QClipboard::connectNotify(const char *signal)
-{
- if (qstrcmp(signal,SIGNAL(dataChanged())) == 0) {
- // ensure we are up and running but block signals so the dataChange signal
- // is not emitted while being connected to.
- bool blocked = blockSignals(true);
- QClipboardData *d = clipboardData();
- blockSignals(blocked);
- Q_UNUSED(d);
- }
-}
-
-const QMimeData *QClipboard::mimeData(Mode mode) const
-{
- if (mode != Clipboard)
- return 0;
-
- QClipboardData *data = clipboardData();
- // sort cut for local copy / paste
- if (ownsClipboard() && data->iData->mimeData())
- return data->iData->mimeData();
- return &data->watcher;
-}
-
-bool QClipboard::supportsMode(Mode mode) const
-{
- return (mode == Clipboard);
-}
-
-bool QClipboard::ownsMode(Mode mode) const
-{
- if (mode == Clipboard) {
- QClipboardData *d = clipboardData();
-#if !defined(Q_OS_WINCE)
- return d->iData && OleIsCurrentClipboard(d->iData) == S_OK;
-#else
- return d->iData && GetClipboardOwner() == d->clipBoardViewer->internalWinId();
-#endif
- } else {
- return false;
- }
-}
-
-void QClipboard::ownerDestroyed()
-{
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_CLIPBOARD
diff --git a/src/gui/platforms/win/qcolormap_win.cpp b/src/gui/platforms/win/qcolormap_win.cpp
deleted file mode 100644
index 1773f717c0..0000000000
--- a/src/gui/platforms/win/qcolormap_win.cpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolor.h"
-#include "qcolormap.h"
-#include "qvector.h"
-#include "qt_windows.h"
-
-#if defined(Q_WS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QColormapPrivate
-{
-public:
- inline QColormapPrivate()
- : ref(1), mode(QColormap::Direct), depth(0), hpal(0)
- { }
-
- QAtomicInt ref;
-
- QColormap::Mode mode;
- int depth;
- int numcolors;
-
- HPALETTE hpal;
- QVector<QColor> palette;
-};
-
-static QColormapPrivate *screenMap = 0;
-
-void QColormap::initialize()
-{
- HDC dc = qt_win_display_dc();
-
- screenMap = new QColormapPrivate;
- screenMap->depth = GetDeviceCaps(dc, BITSPIXEL);
-
- screenMap->numcolors = -1;
- if (GetDeviceCaps(dc, RASTERCAPS) & RC_PALETTE)
- screenMap->numcolors = GetDeviceCaps(dc, SIZEPALETTE);
-
- if (screenMap->numcolors <= 16 || screenMap->numcolors > 256) // no need to create palette
- return;
-
- LOGPALETTE* pal = 0;
- int numPalEntries = 6*6*6; // color cube
-
- pal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + numPalEntries * sizeof(PALETTEENTRY));
- // Make 6x6x6 color cube
- int idx = 0;
- for(int ir = 0x0; ir <= 0xff; ir+=0x33) {
- for(int ig = 0x0; ig <= 0xff; ig+=0x33) {
- for(int ib = 0x0; ib <= 0xff; ib+=0x33) {
- pal->palPalEntry[idx].peRed = ir;
- pal->palPalEntry[idx].peGreen = ig;
- pal->palPalEntry[idx].peBlue = ib;
- pal->palPalEntry[idx].peFlags = 0;
- idx++;
- }
- }
- }
-
- pal->palVersion = 0x300;
- pal->palNumEntries = numPalEntries;
-
- screenMap->hpal = CreatePalette(pal);
- if (!screenMap->hpal)
- qErrnoWarning("QColor::initialize: Failed to create logical palette");
- free (pal);
-
- SelectPalette(dc, screenMap->hpal, FALSE);
- RealizePalette(dc);
-
- PALETTEENTRY paletteEntries[256];
- screenMap->numcolors = GetPaletteEntries(screenMap->hpal, 0, 255, paletteEntries);
-
- screenMap->palette.resize(screenMap->numcolors);
- for (int i = 0; i < screenMap->numcolors; i++) {
- screenMap->palette[i] = qRgb(paletteEntries[i].peRed,
- paletteEntries[i].peGreen,
- paletteEntries[i].peBlue);
- }
-}
-
-void QColormap::cleanup()
-{
- if (!screenMap)
- return;
-
- if (screenMap->hpal) { // delete application global
- DeleteObject(screenMap->hpal); // palette
- screenMap->hpal = 0;
- }
-
- delete screenMap;
- screenMap = 0;
-}
-
-QColormap QColormap::instance(int)
-{
- Q_ASSERT_X(screenMap, "QColormap",
- "A QApplication object needs to be constructed before QColormap is used.");
- return QColormap();
-}
-
-QColormap::QColormap()
- : d(screenMap)
-{ d->ref.ref(); }
-
-QColormap::QColormap(const QColormap &colormap)
- :d (colormap.d)
-{ d->ref.ref(); }
-
-QColormap::~QColormap()
-{
- if (!d->ref.deref())
- delete d;
-}
-
-QColormap::Mode QColormap::mode() const
-{ return d->mode; }
-
-int QColormap::depth() const
-{ return d->depth; }
-
-int QColormap::size() const
-{ return d->numcolors; }
-
-uint QColormap::pixel(const QColor &color) const
-{
- const QColor c = color.toRgb();
- COLORREF rgb = RGB(c.red(), c.green(), c.blue());
- if (d->hpal)
- return PALETTEINDEX(GetNearestPaletteIndex(d->hpal, rgb));
- return rgb;
-}
-
-const QColor QColormap::colorAt(uint pixel) const
-{
- if (d->hpal) {
- if (pixel < uint(d->numcolors))
- return d->palette.at(pixel);
- return QColor();
- }
- return QColor(GetRValue(pixel), GetGValue(pixel), GetBValue(pixel));
-}
-
-
-HPALETTE QColormap::hPal()
-{ return screenMap ? screenMap->hpal : 0; }
-
-
-const QVector<QColor> QColormap::colormap() const
-{ return d->palette; }
-
-QColormap &QColormap::operator=(const QColormap &colormap)
-{ qAtomicAssign(d, colormap.d); return *this; }
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qcursor_win.cpp b/src/gui/platforms/win/qcursor_win.cpp
deleted file mode 100644
index 8a9362ebfc..0000000000
--- a/src/gui/platforms/win/qcursor_win.cpp
+++ /dev/null
@@ -1,492 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qcursor_p.h>
-#include <qbitmap.h>
-#include <qcursor.h>
-
-#ifndef QT_NO_CURSOR
-
-#include <qimage.h>
-#include <qt_windows.h>
-#include <private/qapplication_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- Internal QCursorData class
- *****************************************************************************/
-
-QCursorData::QCursorData(Qt::CursorShape s)
- : cshape(s), bm(0), bmm(0), hx(0), hy(0), hcurs(0)
-{
- ref = 1;
-}
-
-QCursorData::~QCursorData()
-{
- delete bm;
- delete bmm;
-#if !defined(Q_WS_WINCE) || defined(GWES_ICONCURS)
- if (hcurs)
- DestroyCursor(hcurs);
-#endif
-}
-
-
-QCursorData *QCursorData::setBitmap(const QBitmap &bitmap, const QBitmap &mask, int hotX, int hotY)
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (bitmap.depth() != 1 || mask.depth() != 1 || bitmap.size() != mask.size()) {
- qWarning("QCursor: Cannot create bitmap cursor; invalid bitmap(s)");
- QCursorData *c = qt_cursorTable[0];
- c->ref.ref();
- return c;
- }
- QCursorData *d = new QCursorData;
- d->bm = new QBitmap(bitmap);
- d->bmm = new QBitmap(mask);
- d->hcurs = 0;
- d->cshape = Qt::BitmapCursor;
- d->hx = hotX >= 0 ? hotX : bitmap.width()/2;
- d->hy = hotY >= 0 ? hotY : bitmap.height()/2;
- return d;
-}
-
-HCURSOR QCursor::handle() const
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (!d->hcurs)
- d->update();
- return d->hcurs;
-}
-
-QCursor::QCursor(HCURSOR handle)
-{
- d = new QCursorData(Qt::CustomCursor);
- d->hcurs = handle;
-}
-
-#endif //QT_NO_CURSOR
-
-QPoint QCursor::pos()
-{
- POINT p;
- GetCursorPos(&p);
- return QPoint(p.x, p.y);
-}
-
-void QCursor::setPos(int x, int y)
-{
- SetCursorPos(x, y);
-}
-
-#ifndef QT_NO_CURSOR
-
-extern HBITMAP qt_createIconMask(const QBitmap &bitmap);
-
-static HCURSOR create32BitCursor(const QPixmap &pixmap, int hx, int hy)
-{
- HCURSOR cur = 0;
-#if !defined(Q_WS_WINCE)
- QBitmap mask = pixmap.mask();
- if (mask.isNull()) {
- mask = QBitmap(pixmap.size());
- mask.fill(Qt::color1);
- }
-
- HBITMAP ic = pixmap.toWinHBITMAP(QPixmap::Alpha);
- HBITMAP im = qt_createIconMask(mask);
-
- ICONINFO ii;
- ii.fIcon = 0;
- ii.xHotspot = hx;
- ii.yHotspot = hy;
- ii.hbmMask = im;
- ii.hbmColor = ic;
-
- cur = CreateIconIndirect(&ii);
-
- DeleteObject(ic);
- DeleteObject(im);
-#elif defined(GWES_ICONCURS)
- QImage bbits, mbits;
- bool invb, invm;
- bbits = pixmap.toImage().convertToFormat(QImage::Format_Mono);
- mbits = pixmap.toImage().convertToFormat(QImage::Format_Mono);
- invb = bbits.colorCount() > 1 && qGray(bbits.color(0)) < qGray(bbits.color(1));
- invm = mbits.colorCount() > 1 && qGray(mbits.color(0)) < qGray(mbits.color(1));
-
- int sysW = GetSystemMetrics(SM_CXCURSOR);
- int sysH = GetSystemMetrics(SM_CYCURSOR);
- int sysN = qMax(1, sysW / 8);
- int n = qMax(1, bbits.width() / 8);
- int h = bbits.height();
-
- uchar* xBits = new uchar[sysH * sysN];
- uchar* xMask = new uchar[sysH * sysN];
- int x = 0;
- for (int i = 0; i < sysH; ++i) {
- if (i >= h) {
- memset(&xBits[x] , 255, sysN);
- memset(&xMask[x] , 0, sysN);
- x += sysN;
- } else {
- int fillWidth = n > sysN ? sysN : n;
- uchar *bits = bbits.scanLine(i);
- uchar *mask = mbits.scanLine(i);
- for (int j = 0; j < fillWidth; ++j) {
- uchar b = bits[j];
- uchar m = mask[j];
- if (invb)
- b ^= 0xFF;
- if (invm)
- m ^= 0xFF;
- xBits[x] = ~m;
- xMask[x] = b ^ m;
- ++x;
- }
- for (int j = fillWidth; j < sysN; ++j ) {
- xBits[x] = 255;
- xMask[x] = 0;
- ++x;
- }
- }
- }
-
- cur = CreateCursor(qWinAppInst(), hx, hy, sysW, sysH,
- xBits, xMask);
-#else
- Q_UNUSED(pixmap);
- Q_UNUSED(hx);
- Q_UNUSED(hy);
-#endif
- return cur;
-}
-
-void QCursorData::update()
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (hcurs)
- return;
-
- if (cshape == Qt::BitmapCursor && !pixmap.isNull()) {
- hcurs = create32BitCursor(pixmap, hx, hy);
- if (hcurs)
- return;
- }
-
-
- // Non-standard Windows cursors are created from bitmaps
-
- static const uchar vsplit_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xe0, 0x03, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xff, 0x7f, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x7f, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xe0, 0x03, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar vsplitm_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x00, 0xe0, 0x03, 0x00, 0x00, 0xf0, 0x07, 0x00,
- 0x00, 0xf8, 0x0f, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00,
- 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00,
- 0x80, 0xff, 0xff, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x00, 0xf8, 0x0f, 0x00, 0x00, 0xf0, 0x07, 0x00,
- 0x00, 0xe0, 0x03, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar hsplit_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x41, 0x82, 0x00, 0x80, 0x41, 0x82, 0x01, 0xc0, 0x7f, 0xfe, 0x03,
- 0x80, 0x41, 0x82, 0x01, 0x00, 0x41, 0x82, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar hsplitm_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
- 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe2, 0x47, 0x00, 0x00, 0xe3, 0xc7, 0x00,
- 0x80, 0xe3, 0xc7, 0x01, 0xc0, 0xff, 0xff, 0x03, 0xe0, 0xff, 0xff, 0x07,
- 0xc0, 0xff, 0xff, 0x03, 0x80, 0xe3, 0xc7, 0x01, 0x00, 0xe3, 0xc7, 0x00,
- 0x00, 0xe2, 0x47, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
- 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar phand_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00,
- 0x80, 0x04, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00,
- 0x80, 0x1c, 0x00, 0x00, 0x80, 0xe4, 0x00, 0x00, 0x80, 0x24, 0x03, 0x00,
- 0x80, 0x24, 0x05, 0x00, 0xb8, 0x24, 0x09, 0x00, 0xc8, 0x00, 0x09, 0x00,
- 0x88, 0x00, 0x08, 0x00, 0x90, 0x00, 0x08, 0x00, 0xa0, 0x00, 0x08, 0x00,
- 0x20, 0x00, 0x08, 0x00, 0x40, 0x00, 0x08, 0x00, 0x40, 0x00, 0x04, 0x00,
- 0x80, 0x00, 0x04, 0x00, 0x80, 0x00, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00,
- 0x00, 0x01, 0x02, 0x00, 0x00, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
- static const uchar phandm_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00,
- 0x80, 0x07, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00,
- 0x80, 0x1f, 0x00, 0x00, 0x80, 0xff, 0x00, 0x00, 0x80, 0xff, 0x03, 0x00,
- 0x80, 0xff, 0x07, 0x00, 0xb8, 0xff, 0x0f, 0x00, 0xf8, 0xff, 0x0f, 0x00,
- 0xf8, 0xff, 0x0f, 0x00, 0xf0, 0xff, 0x0f, 0x00, 0xe0, 0xff, 0x0f, 0x00,
- 0xe0, 0xff, 0x0f, 0x00, 0xc0, 0xff, 0x0f, 0x00, 0xc0, 0xff, 0x07, 0x00,
- 0x80, 0xff, 0x07, 0x00, 0x80, 0xff, 0x07, 0x00, 0x00, 0xff, 0x03, 0x00,
- 0x00, 0xff, 0x03, 0x00, 0x00, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
- static const uchar openhand_bits[] = {
- 0x80,0x01,0x58,0x0e,0x64,0x12,0x64,0x52,0x48,0xb2,0x48,0x92,
- 0x16,0x90,0x19,0x80,0x11,0x40,0x02,0x40,0x04,0x40,0x04,0x20,
- 0x08,0x20,0x10,0x10,0x20,0x10,0x00,0x00};
- static const uchar openhandm_bits[] = {
- 0x80,0x01,0xd8,0x0f,0xfc,0x1f,0xfc,0x5f,0xf8,0xff,0xf8,0xff,
- 0xf6,0xff,0xff,0xff,0xff,0x7f,0xfe,0x7f,0xfc,0x7f,0xfc,0x3f,
- 0xf8,0x3f,0xf0,0x1f,0xe0,0x1f,0x00,0x00};
- static const uchar closedhand_bits[] = {
- 0x00,0x00,0x00,0x00,0x00,0x00,0xb0,0x0d,0x48,0x32,0x08,0x50,
- 0x10,0x40,0x18,0x40,0x04,0x40,0x04,0x20,0x08,0x20,0x10,0x10,
- 0x20,0x10,0x20,0x10,0x00,0x00,0x00,0x00};
- static const uchar closedhandm_bits[] = {
- 0x00,0x00,0x00,0x00,0x00,0x00,0xb0,0x0d,0xf8,0x3f,0xf8,0x7f,
- 0xf0,0x7f,0xf8,0x7f,0xfc,0x7f,0xfc,0x3f,0xf8,0x3f,0xf0,0x1f,
- 0xe0,0x1f,0xe0,0x1f,0x00,0x00,0x00,0x00};
-
- static const uchar * const cursor_bits32[] = {
- vsplit_bits, vsplitm_bits, hsplit_bits, hsplitm_bits,
- phand_bits, phandm_bits
- };
-
- wchar_t *sh = 0;
- switch (cshape) { // map to windows cursor
- case Qt::ArrowCursor:
- sh = IDC_ARROW;
- break;
- case Qt::UpArrowCursor:
- sh = IDC_UPARROW;
- break;
- case Qt::CrossCursor:
- sh = IDC_CROSS;
- break;
- case Qt::WaitCursor:
- sh = IDC_WAIT;
- break;
- case Qt::IBeamCursor:
- sh = IDC_IBEAM;
- break;
- case Qt::SizeVerCursor:
- sh = IDC_SIZENS;
- break;
- case Qt::SizeHorCursor:
- sh = IDC_SIZEWE;
- break;
- case Qt::SizeBDiagCursor:
- sh = IDC_SIZENESW;
- break;
- case Qt::SizeFDiagCursor:
- sh = IDC_SIZENWSE;
- break;
- case Qt::SizeAllCursor:
- sh = IDC_SIZEALL;
- break;
- case Qt::ForbiddenCursor:
- sh = IDC_NO;
- break;
- case Qt::WhatsThisCursor:
- sh = IDC_HELP;
- break;
- case Qt::BusyCursor:
- sh = IDC_APPSTARTING;
- break;
- case Qt::PointingHandCursor:
- sh = IDC_HAND;
- break;
- case Qt::BlankCursor:
- case Qt::SplitVCursor:
- case Qt::SplitHCursor:
- case Qt::OpenHandCursor:
- case Qt::ClosedHandCursor:
- case Qt::BitmapCursor: {
- QImage bbits, mbits;
- bool invb, invm;
- if (cshape == Qt::BlankCursor) {
- bbits = QImage(32, 32, QImage::Format_Mono);
- bbits.fill(0); // ignore color table
- mbits = bbits.copy();
- hx = hy = 16;
- invb = invm = false;
- } else if (cshape == Qt::OpenHandCursor || cshape == Qt::ClosedHandCursor) {
- bool open = cshape == Qt::OpenHandCursor;
- QBitmap cb = QBitmap::fromData(QSize(16, 16), open ? openhand_bits : closedhand_bits);
- QBitmap cm = QBitmap::fromData(QSize(16, 16), open ? openhandm_bits : closedhandm_bits);
- bbits = cb.toImage().convertToFormat(QImage::Format_Mono);
- mbits = cm.toImage().convertToFormat(QImage::Format_Mono);
- hx = hy = 8;
- invb = invm = false;
- } else if (cshape != Qt::BitmapCursor) {
- int i = cshape - Qt::SplitVCursor;
- QBitmap cb = QBitmap::fromData(QSize(32, 32), cursor_bits32[i * 2]);
- QBitmap cm = QBitmap::fromData(QSize(32, 32), cursor_bits32[i * 2 + 1]);
- bbits = cb.toImage().convertToFormat(QImage::Format_Mono);
- mbits = cm.toImage().convertToFormat(QImage::Format_Mono);
- if (cshape == Qt::PointingHandCursor) {
- hx = 7;
- hy = 0;
- } else
- hx = hy = 16;
- invb = invm = false;
- } else {
- bbits = bm->toImage().convertToFormat(QImage::Format_Mono);
- mbits = bmm->toImage().convertToFormat(QImage::Format_Mono);
- invb = bbits.colorCount() > 1 && qGray(bbits.color(0)) < qGray(bbits.color(1));
- invm = mbits.colorCount() > 1 && qGray(mbits.color(0)) < qGray(mbits.color(1));
- }
- int n = qMax(1, bbits.width() / 8);
- int h = bbits.height();
-#if !defined(Q_WS_WINCE)
- uchar* xBits = new uchar[h * n];
- uchar* xMask = new uchar[h * n];
- int x = 0;
- for (int i = 0; i < h; ++i) {
- uchar *bits = bbits.scanLine(i);
- uchar *mask = mbits.scanLine(i);
- for (int j = 0; j < n; ++j) {
- uchar b = bits[j];
- uchar m = mask[j];
- if (invb)
- b ^= 0xff;
- if (invm)
- m ^= 0xff;
- xBits[x] = ~m;
- xMask[x] = b ^ m;
- ++x;
- }
- }
- hcurs = CreateCursor(qWinAppInst(), hx, hy, bbits.width(), bbits.height(),
- xBits, xMask);
- delete [] xBits;
- delete [] xMask;
-#elif defined(GWES_ICONCURS) // Q_WS_WINCE
- // Windows CE only supports fixed cursor size.
- int sysW = GetSystemMetrics(SM_CXCURSOR);
- int sysH = GetSystemMetrics(SM_CYCURSOR);
- int sysN = qMax(1, sysW / 8);
- uchar* xBits = new uchar[sysH * sysN];
- uchar* xMask = new uchar[sysH * sysN];
- int x = 0;
- for (int i = 0; i < sysH; ++i) {
- if (i >= h) {
- memset(&xBits[x] , 255, sysN);
- memset(&xMask[x] , 0, sysN);
- x += sysN;
- } else {
- int fillWidth = n > sysN ? sysN : n;
- uchar *bits = bbits.scanLine(i);
- uchar *mask = mbits.scanLine(i);
- for (int j = 0; j < fillWidth; ++j) {
- uchar b = bits[j];
- uchar m = mask[j];
- if (invb)
- b ^= 0xFF;
- if (invm)
- m ^= 0xFF;
- xBits[x] = ~m;
- xMask[x] = b ^ m;
- ++x;
- }
- for (int j = fillWidth; j < sysN; ++j ) {
- xBits[x] = 255;
- xMask[x] = 0;
- ++x;
- }
- }
- }
-
- hcurs = CreateCursor(qWinAppInst(), hx, hy, sysW, sysH,
- xBits, xMask);
- delete [] xBits;
- delete [] xMask;
-#else
- Q_UNUSED(n);
- Q_UNUSED(h);
-#endif
- return;
- }
- case Qt::DragCopyCursor:
- case Qt::DragMoveCursor:
- case Qt::DragLinkCursor: {
- QPixmap pixmap = QApplicationPrivate::instance()->getPixmapCursor(cshape);
- hcurs = create32BitCursor(pixmap, hx, hy);
- }
- default:
- qWarning("QCursor::update: Invalid cursor shape %d", cshape);
- return;
- }
-#ifdef Q_WS_WINCE
- hcurs = LoadCursor(0, sh);
-#else
- hcurs = (HCURSOR)LoadImage(0, sh, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
-#endif
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_CURSOR
diff --git a/src/gui/platforms/win/qdesktopwidget_win.cpp b/src/gui/platforms/win/qdesktopwidget_win.cpp
deleted file mode 100644
index d57b355ef4..0000000000
--- a/src/gui/platforms/win/qdesktopwidget_win.cpp
+++ /dev/null
@@ -1,387 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdesktopwidget.h"
-#include "qt_windows.h"
-#include "qapplication_p.h"
-#include <private/qsystemlibrary_p.h>
-#include <qvector.h>
-#include <limits.h>
-#ifdef Q_WS_WINCE
-#include <sipapi.h>
-#endif
-#include "qwidget_p.h"
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-class QDesktopWidgetPrivate : public QWidgetPrivate
-{
-public:
- QDesktopWidgetPrivate();
- ~QDesktopWidgetPrivate();
-
- static void init(QDesktopWidget *that);
- static void cleanup();
- static int screenCount;
- static int primaryScreen;
-
- static QVector<QRect> *rects;
- static QVector<QRect> *workrects;
-
- struct MONITORINFO
- {
- DWORD cbSize;
- RECT rcMonitor;
- RECT rcWork;
- DWORD dwFlags;
- };
-
- typedef BOOL (WINAPI *InfoFunc)(HMONITOR, MONITORINFO*);
- typedef BOOL (QT_WIN_CALLBACK *EnumProc)(HMONITOR, HDC, LPRECT, LPARAM);
- typedef BOOL (WINAPI *EnumFunc)(HDC, LPCRECT, EnumProc, LPARAM);
-
- static EnumFunc enumDisplayMonitors;
- static InfoFunc getMonitorInfo;
- static int refcount;
-};
-
-int QDesktopWidgetPrivate::screenCount = 1;
-int QDesktopWidgetPrivate::primaryScreen = 0;
-QDesktopWidgetPrivate::EnumFunc QDesktopWidgetPrivate::enumDisplayMonitors = 0;
-QDesktopWidgetPrivate::InfoFunc QDesktopWidgetPrivate::getMonitorInfo = 0;
-QVector<QRect> *QDesktopWidgetPrivate::rects = 0;
-QVector<QRect> *QDesktopWidgetPrivate::workrects = 0;
-static int screen_number = 0;
-int QDesktopWidgetPrivate::refcount = 0;
-#ifdef Q_WS_WINCE_WM
-// Use SIP information, if available
-// SipGetInfo is not supported by SSDK (no definition!).
-static inline void qt_get_sip_info(QRect &rect)
-{
- SIPINFO sip;
- memset(&sip, 0, sizeof(SIPINFO));
- sip.cbSize = sizeof(SIPINFO);
- if (SipGetInfo(&sip))
- rect = QRect(QPoint(sip.rcVisibleDesktop.left, sip.rcVisibleDesktop.top),
- QPoint(sip.rcVisibleDesktop.right - 1, sip.rcVisibleDesktop.bottom - 1));
-}
-#endif
-
-
-BOOL QT_WIN_CALLBACK enumCallback(HMONITOR hMonitor, HDC, LPRECT, LPARAM)
-{
- QDesktopWidgetPrivate::screenCount++;
- QDesktopWidgetPrivate::rects->resize(QDesktopWidgetPrivate::screenCount);
- QDesktopWidgetPrivate::workrects->resize(QDesktopWidgetPrivate::screenCount);
- // Get the MONITORINFO block
- QDesktopWidgetPrivate::MONITORINFO info;
- memset(&info, 0, sizeof(QDesktopWidgetPrivate::MONITORINFO));
- info.cbSize = sizeof(QDesktopWidgetPrivate::MONITORINFO);
- BOOL res = QDesktopWidgetPrivate::getMonitorInfo(hMonitor, &info);
- if (!res) {
- (*QDesktopWidgetPrivate::rects)[screen_number] = QRect();
- (*QDesktopWidgetPrivate::workrects)[screen_number] = QRect();
- return true;
- }
-
- // Fill list of rects
- RECT r = info.rcMonitor;
- QRect qr(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
- (*QDesktopWidgetPrivate::rects)[screen_number] = qr;
-
- r = info.rcWork;
- qr = QRect(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
- (*QDesktopWidgetPrivate::workrects)[screen_number] = qr;
-
- if (info.dwFlags & 0x00000001) //MONITORINFOF_PRIMARY
- QDesktopWidgetPrivate::primaryScreen = screen_number;
-
- ++screen_number;
- // Stop the enumeration if we have them all
- return true;
-}
-
-QDesktopWidgetPrivate::QDesktopWidgetPrivate()
-{
- ++refcount;
-}
-
-void QDesktopWidgetPrivate::init(QDesktopWidget *that)
-{
- if (rects)
- return;
-
- rects = new QVector<QRect>();
- workrects = new QVector<QRect>();
- screenCount = 0;
-
-#ifndef Q_OS_WINCE
- QSystemLibrary user32Lib(QLatin1String("user32"));
- enumDisplayMonitors = (EnumFunc)user32Lib.resolve("EnumDisplayMonitors");
- getMonitorInfo = (InfoFunc)user32Lib.resolve("GetMonitorInfoW");
-
- if (!enumDisplayMonitors || !getMonitorInfo) {
- screenCount = GetSystemMetrics(80); // SM_CMONITORS
- rects->resize(screenCount);
- for (int i = 0; i < screenCount; ++i)
- rects->replace(i, that->rect());
- return;
- }
- // Calls enumCallback
- enumDisplayMonitors(0, 0, enumCallback, 0);
- enumDisplayMonitors = 0;
- getMonitorInfo = 0;
-#else
- QSystemLibrary coreLib(QLatin1String("coredll"));
- // CE >= 4.0 case
- enumDisplayMonitors = (EnumFunc)coreLib.resolve("EnumDisplayMonitors");
- getMonitorInfo = (InfoFunc)coreLib.resolve("GetMonitorInfo");
-
- if ((!enumDisplayMonitors || !getMonitorInfo)) {
- screenCount = GetSystemMetrics(SM_CMONITORS);
- return;
- }
-
- if (!coreLib.isLoaded() || !enumDisplayMonitors || !getMonitorInfo) {
- rects->resize(screenCount);
- for (int i = 0; i < screenCount; ++i)
- (*rects)[i] = that->rect();
-
- RECT r;
- SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
- QRect qr = QRect(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
-
-#if defined(Q_WS_WINCE_WM)
- qt_get_sip_info(qr);
-#endif
-
- workrects->resize(screenCount);
- for (int j = 0; j < screenCount; ++j)
- (*workrects)[j] = qr;
- return;
- }
-
- // Calls enumCallback
- enumDisplayMonitors(0, 0, enumCallback, 0);
- enumDisplayMonitors = 0;
- getMonitorInfo = 0;
-#endif // Q_WS_WINCE
-}
-
-QDesktopWidgetPrivate::~QDesktopWidgetPrivate()
-{
- if (!--refcount)
- cleanup();
-}
-
-void QDesktopWidgetPrivate::cleanup()
-{
- screen_number = 0;
- screenCount = 1;
- primaryScreen = 0;
- enumDisplayMonitors = 0;
- getMonitorInfo = 0;
- delete rects;
- rects = 0;
- delete workrects;
- workrects = 0;
-}
-
-/*
- \omit
- Function is commented out in header
- \fn void *QDesktopWidget::handle(int screen) const
-
- Returns the window system handle of the display device with the
- index \a screen, for low-level access. Using this function is not
- portable.
-
- The return type varies with platform; see qwindowdefs.h for details.
-
- \sa x11Display(), QPaintDevice::handle()
- \endomit
-*/
-
-QDesktopWidget::QDesktopWidget()
- : QWidget(*new QDesktopWidgetPrivate, 0, Qt::Desktop)
-{
- setObjectName(QLatin1String("desktop"));
- QDesktopWidgetPrivate::init(this);
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
- return true;
-}
-
-int QDesktopWidget::primaryScreen() const
-{
- return d_func()->primaryScreen;
-}
-
-int QDesktopWidget::numScreens() const
-{
- return d_func()->screenCount;
-}
-
-QWidget *QDesktopWidget::screen(int /* screen */)
-{
- // It seems that a Qt::WType_Desktop cannot be moved?
- return this;
-}
-
-//
-// MSVC 7.10 warns that d (the result of the expanded Q_D macro) as a local variable that is not referenced.
-// Therefore, we ignore that warning with the following pragmas
-// I've also tried to eliminate the macro, but to no use...
-// We pop it further down
-#ifdef Q_CC_MSVC
-# pragma warning(push)
-# pragma warning(disable : 4189)
-#endif
-const QRect QDesktopWidget::availableGeometry(int screen) const
-{
- Q_D(const QDesktopWidget);
-#ifdef Q_WS_WINCE_WM
- for(int i=0; i < d->workrects->size(); ++i)
- qt_get_sip_info((*d->workrects)[i]);
-#endif
- if (screen < 0 || screen >= d->screenCount)
- screen = d->primaryScreen;
-
- return d->workrects->at(screen);
-}
-
-const QRect QDesktopWidget::screenGeometry(int screen) const
-{
- const QDesktopWidgetPrivate *d = d_func();
- if (screen < 0 || screen >= d->screenCount)
- screen = d->primaryScreen;
-
- return d->rects->at(screen);
-}
-
-int QDesktopWidget::screenNumber(const QWidget *widget) const
-{
- Q_D(const QDesktopWidget);
- if (!widget)
- return d->primaryScreen;
-
- QRect frame = widget->frameGeometry();
- if (!widget->isWindow())
- frame.moveTopLeft(widget->mapToGlobal(QPoint(0,0)));
-
- int maxSize = -1;
- int maxScreen = -1;
-
- for (int i = 0; i < d->screenCount; ++i) {
- QRect sect = d->rects->at(i).intersected(frame);
- int size = sect.width() * sect.height();
- if (size > maxSize && sect.width() > 0 && sect.height() > 0) {
- maxSize = size;
- maxScreen = i;
- }
- }
-
- return maxScreen;
-}
-
-int QDesktopWidget::screenNumber(const QPoint &point) const
-{
- Q_D(const QDesktopWidget);
-
- int closestScreen = -1;
- int shortestDistance = INT_MAX;
-
- for (int i = 0; i < d->screenCount; ++i) {
- int thisDistance = d->pointToRect(point, d->rects->at(i));
- if (thisDistance < shortestDistance) {
- shortestDistance = thisDistance;
- closestScreen = i;
- }
- }
-
- return closestScreen;
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
- Q_D(QDesktopWidget);
- const QVector<QRect> oldrects(*d->rects);
- const QVector<QRect> oldworkrects(*d->workrects);
- int oldscreencount = d->screenCount;
-
- QDesktopWidgetPrivate::cleanup();
- QDesktopWidgetPrivate::init(this);
-#ifdef Q_WS_WINCE_WM
- for(int i=0; i < d->workrects->size(); ++i)
- qt_get_sip_info((*d->workrects)[i]);
-#endif
-
- for (int i = 0; i < qMin(oldscreencount, d->screenCount); ++i) {
- const QRect oldrect = oldrects[i];
- const QRect newrect = d->rects->at(i);
- if (oldrect != newrect)
- emit resized(i);
- }
-
- for (int j = 0; j < qMin(oldscreencount, d->screenCount); ++j) {
- const QRect oldrect = oldworkrects[j];
- const QRect newrect = d->workrects->at(j);
- if (oldrect != newrect)
- emit workAreaResized(j);
- }
-
- if (oldscreencount != d->screenCount) {
- emit screenCountChanged(d->screenCount);
- }
-}
-
-#ifdef Q_CC_MSVC
-# pragma warning(pop)
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qdnd_win.cpp b/src/gui/platforms/win/qdnd_win.cpp
deleted file mode 100644
index 176e3cef7f..0000000000
--- a/src/gui/platforms/win/qdnd_win.cpp
+++ /dev/null
@@ -1,1027 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-
-#include "qapplication_p.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbuffer.h"
-#include "qdatastream.h"
-#include "qcursor.h"
-#include "qt_windows.h"
-#include <shlobj.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include "qdnd_p.h"
-#include "qdebug.h"
-
-#if defined(Q_OS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-// support for xbuttons
-#ifndef MK_XBUTTON1
-#define MK_XBUTTON1 0x0020
-#define MK_XBUTTON2 0x0040
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#if !(defined(QT_NO_DRAGANDDROP) && defined(QT_NO_CLIPBOARD))
-
-//---------------------------------------------------------------------
-// QOleDataObject Constructor
-//---------------------------------------------------------------------
-
-QOleDataObject::QOleDataObject(QMimeData *mimeData)
-{
- m_refs = 1;
- data = mimeData;
- CF_PERFORMEDDROPEFFECT = RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT);
- performedEffect = DROPEFFECT_NONE;
-}
-
-QOleDataObject::~QOleDataObject()
-{
-}
-
-void QOleDataObject::releaseQt()
-{
- data = 0;
-}
-
-const QMimeData *QOleDataObject::mimeData() const
-{
- return data;
-}
-
-DWORD QOleDataObject::reportedPerformedEffect() const
-{
- return performedEffect;
-}
-
-//---------------------------------------------------------------------
-// IUnknown Methods
-//---------------------------------------------------------------------
-
-STDMETHODIMP
-QOleDataObject::QueryInterface(REFIID iid, void FAR* FAR* ppv)
-{
- if (iid == IID_IUnknown || iid == IID_IDataObject) {
- *ppv = this;
- AddRef();
- return NOERROR;
- }
- *ppv = NULL;
- return ResultFromScode(E_NOINTERFACE);
-}
-
-STDMETHODIMP_(ULONG)
-QOleDataObject::AddRef(void)
-{
- return ++m_refs;
-}
-
-STDMETHODIMP_(ULONG)
-QOleDataObject::Release(void)
-{
- if (--m_refs == 0) {
- releaseQt();
- delete this;
- return 0;
- }
- return m_refs;
-}
-
-//---------------------------------------------------------------------
-// IDataObject Methods
-//
-// The following methods are NOT supported for data transfer using the
-// clipboard or drag-drop:
-//
-// IDataObject::SetData -- return E_NOTIMPL
-// IDataObject::DAdvise -- return OLE_E_ADVISENOTSUPPORTED
-// ::DUnadvise
-// ::EnumDAdvise
-// IDataObject::GetCanonicalFormatEtc -- return E_NOTIMPL
-// (NOTE: must set pformatetcOut->ptd = NULL)
-//---------------------------------------------------------------------
-
-STDMETHODIMP
-QOleDataObject::GetData(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDataObject::GetData(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium)");
-#ifndef Q_OS_WINCE
- wchar_t buf[256] = {0};
- GetClipboardFormatName(pformatetc->cfFormat, buf, 255);
- qDebug("CF = %d : %s", pformatetc->cfFormat, QString::fromWCharArray(buf));
-#endif
-#endif
-
- if (!data)
- return ResultFromScode(DATA_E_FORMATETC);
-
- QWindowsMime *converter = QWindowsMime::converterFromMime(*pformatetc, data);
-
- if (converter && converter->convertFromMime(*pformatetc, data, pmedium))
- return ResultFromScode(S_OK);
- else
- return ResultFromScode(DATA_E_FORMATETC);
-}
-
-STDMETHODIMP
-QOleDataObject::GetDataHere(LPFORMATETC, LPSTGMEDIUM)
-{
- return ResultFromScode(DATA_E_FORMATETC);
-}
-
-STDMETHODIMP
-QOleDataObject::QueryGetData(LPFORMATETC pformatetc)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDataObject::QueryGetData(LPFORMATETC pformatetc)");
-#endif
-
- if (!data)
- return ResultFromScode(DATA_E_FORMATETC);
-
- if (QWindowsMime::converterFromMime(*pformatetc, data))
- return ResultFromScode(S_OK);
- return ResultFromScode(S_FALSE);
-}
-
-STDMETHODIMP
-QOleDataObject::GetCanonicalFormatEtc(LPFORMATETC, LPFORMATETC pformatetcOut)
-{
- pformatetcOut->ptd = NULL;
- return ResultFromScode(E_NOTIMPL);
-}
-
-STDMETHODIMP
-QOleDataObject::SetData(LPFORMATETC pFormatetc, STGMEDIUM *pMedium, BOOL fRelease)
-{
- if (pFormatetc->cfFormat == CF_PERFORMEDDROPEFFECT && pMedium->tymed == TYMED_HGLOBAL) {
- DWORD * val = (DWORD*)GlobalLock(pMedium->hGlobal);
- performedEffect = *val;
- GlobalUnlock(pMedium->hGlobal);
- if (fRelease)
- ReleaseStgMedium(pMedium);
- return ResultFromScode(S_OK);
- }
- return ResultFromScode(E_NOTIMPL);
-}
-
-
-STDMETHODIMP
-QOleDataObject::EnumFormatEtc(DWORD dwDirection, LPENUMFORMATETC FAR* ppenumFormatEtc)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDataObject::EnumFormatEtc(DWORD dwDirection, LPENUMFORMATETC FAR* ppenumFormatEtc)");
-#endif
-
- if (!data)
- return ResultFromScode(DATA_E_FORMATETC);
-
- SCODE sc = S_OK;
-
- QVector<FORMATETC> fmtetcs;
- if (dwDirection == DATADIR_GET) {
- fmtetcs = QWindowsMime::allFormatsForMime(data);
- } else {
- FORMATETC formatetc;
- formatetc.cfFormat = CF_PERFORMEDDROPEFFECT;
- formatetc.dwAspect = DVASPECT_CONTENT;
- formatetc.lindex = -1;
- formatetc.ptd = NULL;
- formatetc.tymed = TYMED_HGLOBAL;
- fmtetcs.append(formatetc);
- }
-
- QOleEnumFmtEtc *enumFmtEtc = new QOleEnumFmtEtc(fmtetcs);
- *ppenumFormatEtc = enumFmtEtc;
- if (enumFmtEtc->isNull()) {
- delete enumFmtEtc;
- *ppenumFormatEtc = NULL;
- sc = E_OUTOFMEMORY;
- }
-
- return ResultFromScode(sc);
-}
-
-STDMETHODIMP
-QOleDataObject::DAdvise(FORMATETC FAR*, DWORD,
- LPADVISESINK, DWORD FAR*)
-{
- return ResultFromScode(OLE_E_ADVISENOTSUPPORTED);
-}
-
-
-STDMETHODIMP
-QOleDataObject::DUnadvise(DWORD)
-{
- return ResultFromScode(OLE_E_ADVISENOTSUPPORTED);
-}
-
-STDMETHODIMP
-QOleDataObject::EnumDAdvise(LPENUMSTATDATA FAR*)
-{
- return ResultFromScode(OLE_E_ADVISENOTSUPPORTED);
-}
-
-#endif // QT_NO_DRAGANDDROP && QT_NO_CLIPBOARD
-
-#ifndef QT_NO_DRAGANDDROP
-
-//#define QDND_DEBUG
-
-#ifdef QDND_DEBUG
-extern QString dragActionsToString(Qt::DropActions actions);
-#endif
-
-Qt::DropActions translateToQDragDropActions(DWORD pdwEffects)
-{
- Qt::DropActions actions = Qt::IgnoreAction;
- if (pdwEffects & DROPEFFECT_LINK)
- actions |= Qt::LinkAction;
- if (pdwEffects & DROPEFFECT_COPY)
- actions |= Qt::CopyAction;
- if (pdwEffects & DROPEFFECT_MOVE)
- actions |= Qt::MoveAction;
- return actions;
-}
-
-Qt::DropAction translateToQDragDropAction(DWORD pdwEffect)
-{
- if (pdwEffect & DROPEFFECT_LINK)
- return Qt::LinkAction;
- if (pdwEffect & DROPEFFECT_COPY)
- return Qt::CopyAction;
- if (pdwEffect & DROPEFFECT_MOVE)
- return Qt::MoveAction;
- return Qt::IgnoreAction;
-}
-
-DWORD translateToWinDragEffects(Qt::DropActions action)
-{
- DWORD effect = DROPEFFECT_NONE;
- if (action & Qt::LinkAction)
- effect |= DROPEFFECT_LINK;
- if (action & Qt::CopyAction)
- effect |= DROPEFFECT_COPY;
- if (action & Qt::MoveAction)
- effect |= DROPEFFECT_MOVE;
- return effect;
-}
-
-Qt::KeyboardModifiers toQtKeyboardModifiers(DWORD keyState)
-{
- Qt::KeyboardModifiers modifiers = Qt::NoModifier;
-
- if (keyState & MK_SHIFT)
- modifiers |= Qt::ShiftModifier;
- if (keyState & MK_CONTROL)
- modifiers |= Qt::ControlModifier;
- if (keyState & MK_ALT)
- modifiers |= Qt::AltModifier;
-
- return modifiers;
-}
-
-Qt::MouseButtons toQtMouseButtons(DWORD keyState)
-{
- Qt::MouseButtons buttons = Qt::NoButton;
-
- if (keyState & MK_LBUTTON)
- buttons |= Qt::LeftButton;
- if (keyState & MK_RBUTTON)
- buttons |= Qt::RightButton;
- if (keyState & MK_MBUTTON)
- buttons |= Qt::MidButton;
-
- return buttons;
-}
-
-class QOleDropSource : public IDropSource
-{
-public:
- QOleDropSource();
- virtual ~QOleDropSource();
-
- void createCursors();
-
- // IUnknown methods
- STDMETHOD(QueryInterface)(REFIID riid, void ** ppvObj);
- STDMETHOD_(ULONG,AddRef)(void);
- STDMETHOD_(ULONG,Release)(void);
-
- // IDropSource methods
- STDMETHOD(QueryContinueDrag)(BOOL fEscapePressed, DWORD grfKeyState);
- STDMETHOD(GiveFeedback)(DWORD dwEffect);
-
-private:
- Qt::MouseButtons currentButtons;
- Qt::DropAction currentAction;
- QMap <Qt::DropAction, QCursor> cursors;
-
- ULONG m_refs;
-};
-
-
-QOleDropSource::QOleDropSource()
-{
- currentButtons = Qt::NoButton;
- m_refs = 1;
- currentAction = Qt::IgnoreAction;
-}
-
-QOleDropSource::~QOleDropSource()
-{
-}
-
-void QOleDropSource::createCursors()
-{
- QDragManager *manager = QDragManager::self();
- if (manager && manager->object
- && (!manager->object->pixmap().isNull()
- || manager->hasCustomDragCursors())) {
- QPixmap pm = manager->object->pixmap();
- QList<Qt::DropAction> actions;
- actions << Qt::MoveAction << Qt::CopyAction << Qt::LinkAction;
- if (!manager->object->pixmap().isNull())
- actions << Qt::IgnoreAction;
- QPoint hotSpot = manager->object->hotSpot();
- for (int cnum = 0; cnum < actions.size(); ++cnum) {
- QPixmap cpm = manager->dragCursor(actions.at(cnum));
- int w = cpm.width();
- int h = cpm.height();
-
- if (!pm.isNull()) {
- int x1 = qMin(-hotSpot.x(), 0);
- int x2 = qMax(pm.width() - hotSpot.x(), cpm.width());
- int y1 = qMin(-hotSpot.y(), 0);
- int y2 = qMax(pm.height() - hotSpot.y(), cpm.height());
-
- w = x2 - x1 + 1;
- h = y2 - y1 + 1;
- }
-
- QRect srcRect = pm.rect();
- QPoint pmDest = QPoint(qMax(0, -hotSpot.x()), qMax(0, -hotSpot.y()));
- QPoint newHotSpot = hotSpot;
-
-#if defined(Q_OS_WINCE)
- // Limited cursor size
- int reqw = GetSystemMetrics(SM_CXCURSOR);
- int reqh = GetSystemMetrics(SM_CYCURSOR);
-
- QPoint hotspotInPM = newHotSpot - pmDest;
- if (reqw < w) {
- // Not wide enough - move objectpm right
- qreal r = qreal(newHotSpot.x()) / w;
- newHotSpot = QPoint(int(r * reqw), newHotSpot.y());
- if (newHotSpot.x() + cpm.width() > reqw)
- newHotSpot.setX(reqw - cpm.width());
-
- srcRect = QRect(QPoint(hotspotInPM.x() - newHotSpot.x(), srcRect.top()), QSize(reqw, srcRect.height()));
- }
- if (reqh < h) {
- qreal r = qreal(newHotSpot.y()) / h;
- newHotSpot = QPoint(newHotSpot.x(), int(r * reqh));
- if (newHotSpot.y() + cpm.height() > reqh)
- newHotSpot.setY(reqh - cpm.height());
-
- srcRect = QRect(QPoint(srcRect.left(), hotspotInPM.y() - newHotSpot.y()), QSize(srcRect.width(), reqh));
- }
- // Always use system cursor size
- w = reqw;
- h = reqh;
-#endif
-
- QPixmap newCursor(w, h);
- if (!pm.isNull()) {
- newCursor.fill(QColor(0, 0, 0, 0));
- QPainter p(&newCursor);
- p.drawPixmap(pmDest, pm, srcRect);
- p.drawPixmap(qMax(0,newHotSpot.x()),qMax(0,newHotSpot.y()),cpm);
- } else {
- newCursor = cpm;
- }
-
-#ifndef QT_NO_CURSOR
- cursors[actions.at(cnum)] = QCursor(newCursor, pm.isNull() ? 0 : qMax(0,newHotSpot.x()),
- pm.isNull() ? 0 : qMax(0,newHotSpot.y()));
-#endif
- }
- }
-}
-
-
-
-//---------------------------------------------------------------------
-// IUnknown Methods
-//---------------------------------------------------------------------
-
-
-STDMETHODIMP
-QOleDropSource::QueryInterface(REFIID iid, void FAR* FAR* ppv)
-{
- if(iid == IID_IUnknown || iid == IID_IDropSource)
- {
- *ppv = this;
- ++m_refs;
- return NOERROR;
- }
- *ppv = NULL;
- return ResultFromScode(E_NOINTERFACE);
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropSource::AddRef(void)
-{
- return ++m_refs;
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropSource::Release(void)
-{
- if(--m_refs == 0)
- {
- delete this;
- return 0;
- }
- return m_refs;
-}
-
-static inline Qt::MouseButtons keystate_to_mousebutton(DWORD grfKeyState)
-{
- Qt::MouseButtons result;
- if (grfKeyState & MK_LBUTTON)
- result |= Qt::LeftButton;
- if (grfKeyState & MK_MBUTTON)
- result |= Qt::MidButton;
- if (grfKeyState & MK_RBUTTON)
- result |= Qt::RightButton;
- if (grfKeyState & MK_XBUTTON1)
- result |= Qt::XButton1;
- if (grfKeyState & MK_XBUTTON2)
- result |= Qt::XButton2;
- return result;
-}
-
-//---------------------------------------------------------------------
-// IDropSource Methods
-//---------------------------------------------------------------------
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropSource::QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDropSource::QueryContinueDrag(fEscapePressed %d, grfKeyState %d)", fEscapePressed, grfKeyState);
-#endif
-
- if (fEscapePressed) {
- return ResultFromScode(DRAGDROP_S_CANCEL);
- } else if ((GetAsyncKeyState(VK_LBUTTON) == 0)
- && (GetAsyncKeyState(VK_MBUTTON) == 0)
- && (GetAsyncKeyState(VK_RBUTTON) == 0)) {
- // grfKeyState is broken on CE & some Windows XP versions,
- // therefore we need to check the state manually
- return ResultFromScode(DRAGDROP_S_DROP);
- } else {
-#if !defined(Q_OS_WINCE)
- if (currentButtons == Qt::NoButton) {
- currentButtons = keystate_to_mousebutton(grfKeyState);
- } else {
- Qt::MouseButtons buttons = keystate_to_mousebutton(grfKeyState);
- if (!(currentButtons & buttons))
- return ResultFromScode(DRAGDROP_S_DROP);
- }
-#endif
- QApplication::processEvents();
- return NOERROR;
- }
-}
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropSource::GiveFeedback(DWORD dwEffect)
-{
- Qt::DropAction action = translateToQDragDropAction(dwEffect);
-
-#ifdef QDND_DEBUG
- qDebug("QOleDropSource::GiveFeedback(DWORD dwEffect)");
- qDebug("dwEffect = %s", dragActionsToString(action).toLatin1().data());
-#endif
-
- if (currentAction != action) {
- currentAction = action;
- QDragManager::self()->emitActionChanged(currentAction);
- }
-
- if (cursors.contains(currentAction)) {
-#ifndef QT_NO_CURSOR
- SetCursor(cursors[currentAction].handle());
-#endif
- return ResultFromScode(S_OK);
- }
-
- return ResultFromScode(DRAGDROP_S_USEDEFAULTCURSORS);
-}
-
-//---------------------------------------------------------------------
-// QOleDropTarget
-//---------------------------------------------------------------------
-
-QOleDropTarget::QOleDropTarget(QWidget* w)
-: widget(w)
-{
- m_refs = 1;
-}
-
-void QOleDropTarget::releaseQt()
-{
- widget = 0;
-}
-
-//---------------------------------------------------------------------
-// IUnknown Methods
-//---------------------------------------------------------------------
-
-
-STDMETHODIMP
-QOleDropTarget::QueryInterface(REFIID iid, void FAR* FAR* ppv)
-{
- if(iid == IID_IUnknown || iid == IID_IDropTarget)
- {
- *ppv = this;
- AddRef();
- return NOERROR;
- }
- *ppv = NULL;
- return ResultFromScode(E_NOINTERFACE);
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropTarget::AddRef(void)
-{
- return ++m_refs;
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropTarget::Release(void)
-{
- if(--m_refs == 0)
- {
- delete this;
- return 0;
- }
- return m_refs;
-}
-
-//---------------------------------------------------------------------
-// IDropTarget Methods
-//---------------------------------------------------------------------
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::DragEnter(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDropTarget::DragEnter(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)");
-#endif
-
- if (!QApplicationPrivate::tryModalHelper(widget)) {
- *pdwEffect = DROPEFFECT_NONE;
- return NOERROR;
- }
-
- QDragManager *manager = QDragManager::self();
- manager->dropData->currentDataObject = pDataObj;
- manager->dropData->currentDataObject->AddRef();
- sendDragEnterEvent(widget, grfKeyState, pt, pdwEffect);
- *pdwEffect = chosenEffect;
-
- return NOERROR;
-}
-
-void QOleDropTarget::sendDragEnterEvent(QWidget *dragEnterWidget, DWORD grfKeyState,
- POINTL pt, LPDWORD pdwEffect)
-{
- Q_ASSERT(dragEnterWidget);
- lastPoint = dragEnterWidget->mapFromGlobal(QPoint(pt.x,pt.y));
- lastKeyState = grfKeyState;
-
- chosenEffect = DROPEFFECT_NONE;
- currentWidget = dragEnterWidget;
-
- QDragManager *manager = QDragManager::self();
- QMimeData * md = manager->source() ? manager->dragPrivate()->data : manager->dropData;
- QDragEnterEvent enterEvent(lastPoint, translateToQDragDropActions(*pdwEffect), md,
- toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
- QApplication::sendEvent(dragEnterWidget, &enterEvent);
- answerRect = enterEvent.answerRect();
-
- if (enterEvent.isAccepted()) {
- chosenEffect = translateToWinDragEffects(enterEvent.dropAction());
- }
-
- // Documentation states that a drag move event is sendt immidiatly after
- // a drag enter event. This will honor widgets overriding dragMoveEvent only:
- if (enterEvent.isAccepted()) {
- QDragMoveEvent moveEvent(lastPoint, translateToQDragDropActions(*pdwEffect), md,
- toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
- answerRect = enterEvent.answerRect();
- moveEvent.setDropAction(enterEvent.dropAction());
- moveEvent.accept(); // accept by default, since enter event was accepted.
-
- QApplication::sendEvent(dragEnterWidget, &moveEvent);
- if (moveEvent.isAccepted()) {
- answerRect = moveEvent.answerRect();
- chosenEffect = translateToWinDragEffects(moveEvent.dropAction());
- } else {
- chosenEffect = DROPEFFECT_NONE;
- }
- }
-
-}
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::DragOver(DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDropTarget::DragOver(grfKeyState %d, pt (%d,%d), pdwEffect %d)", grfKeyState, pt.x, pt.y, pdwEffect);
-#endif
-
- QWidget *dragOverWidget = widget->childAt(widget->mapFromGlobal(QPoint(pt.x, pt.y)));
- if (!dragOverWidget)
- dragOverWidget = widget;
-
-
- if (!QApplicationPrivate::tryModalHelper(dragOverWidget)
- || !dragOverWidget->testAttribute(Qt::WA_DropSiteRegistered)) {
- *pdwEffect = DROPEFFECT_NONE;
- return NOERROR;
- }
-
- QPoint tmpPoint = dragOverWidget->mapFromGlobal(QPoint(pt.x, pt.y));
- // see if we should compress this event
- if ((tmpPoint == lastPoint || answerRect.contains(tmpPoint)) && lastKeyState == grfKeyState) {
- *pdwEffect = chosenEffect;
- return NOERROR;
- }
-
- if (!dragOverWidget->internalWinId() && dragOverWidget != currentWidget) {
- QPointer<QWidget> dragOverWidgetGuard(dragOverWidget);
- // Send drag leave event to the previous drag widget.
- QDragLeaveEvent dragLeave;
- if (currentWidget)
- QApplication::sendEvent(currentWidget, &dragLeave);
- if (!dragOverWidgetGuard) {
- dragOverWidget = widget->childAt(widget->mapFromGlobal(QPoint(pt.x, pt.y)));
- if (!dragOverWidget)
- dragOverWidget = widget;
- }
- // Send drag enter event to the current drag widget.
- sendDragEnterEvent(dragOverWidget, grfKeyState, pt, pdwEffect);
- }
-
- QDragManager *manager = QDragManager::self();
- QMimeData *md = manager->source() ? manager->dragPrivate()->data : manager->dropData;
-
- QDragMoveEvent oldEvent(lastPoint, translateToQDragDropActions(*pdwEffect), md,
- toQtMouseButtons(lastKeyState), toQtKeyboardModifiers(lastKeyState));
-
-
- lastPoint = tmpPoint;
- lastKeyState = grfKeyState;
-
- QDragMoveEvent e(lastPoint, translateToQDragDropActions(*pdwEffect), md,
- toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
- if (chosenEffect != DROPEFFECT_NONE) {
- if (oldEvent.dropAction() == e.dropAction() &&
- oldEvent.keyboardModifiers() == e.keyboardModifiers())
- e.setDropAction(translateToQDragDropAction(chosenEffect));
- e.accept();
- }
- QApplication::sendEvent(dragOverWidget, &e);
-
- answerRect = e.answerRect();
- if (e.isAccepted())
- chosenEffect = translateToWinDragEffects(e.dropAction());
- else
- chosenEffect = DROPEFFECT_NONE;
- *pdwEffect = chosenEffect;
-
- return NOERROR;
-}
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::DragLeave()
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDropTarget::DragLeave()");
-#endif
-
- if (!QApplicationPrivate::tryModalHelper(widget)) {
- return NOERROR;
- }
-
- currentWidget = 0;
- QDragLeaveEvent e;
- QApplication::sendEvent(widget, &e);
-
- QDragManager *manager = QDragManager::self();
-
- if (manager->dropData->currentDataObject) { // Sanity
- manager->dropData->currentDataObject->Release();
- manager->dropData->currentDataObject = 0;
- }
-
- return NOERROR;
-}
-
-#define KEY_STATE_BUTTON_MASK (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::Drop(LPDATAOBJECT /*pDataObj*/, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
-{
-#ifdef QDND_DEBUG
- qDebug("QOleDropTarget::Drop(LPDATAOBJECT /*pDataObj*/, grfKeyState %d, POINTL pt, LPDWORD pdwEffect)", grfKeyState);
-#endif
-
- QWidget *dropWidget = widget->childAt(widget->mapFromGlobal(QPoint(pt.x, pt.y)));
- if (!dropWidget)
- dropWidget = widget;
-
- if (!QApplicationPrivate::tryModalHelper(dropWidget)
- || !dropWidget->testAttribute(Qt::WA_DropSiteRegistered)) {
- *pdwEffect = DROPEFFECT_NONE;
- return NOERROR;
- }
-
- lastPoint = dropWidget->mapFromGlobal(QPoint(pt.x,pt.y));
- // grfKeyState does not all ways contain button state in the drop so if
- // it doesn't then use the last known button state;
- if ((grfKeyState & KEY_STATE_BUTTON_MASK) == 0)
- grfKeyState |= lastKeyState & KEY_STATE_BUTTON_MASK;
- lastKeyState = grfKeyState;
-
- QDragManager *manager = QDragManager::self();
- QMimeData *md = manager->source() ? manager->dragPrivate()->data : manager->dropData;
- QDropEvent e(lastPoint, translateToQDragDropActions(*pdwEffect), md,
- toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
- if (chosenEffect != DROPEFFECT_NONE) {
- e.setDropAction(translateToQDragDropAction(chosenEffect));
- }
- QApplication::sendEvent(dropWidget, &e);
-
- if (chosenEffect != DROPEFFECT_NONE) {
- e.accept();
- }
-
-
- if (e.isAccepted()) {
- if (e.dropAction() == Qt::MoveAction || e.dropAction() == Qt::TargetMoveAction) {
- if (e.dropAction() == Qt::MoveAction)
- chosenEffect = DROPEFFECT_MOVE;
- else
- chosenEffect = DROPEFFECT_COPY;
- HGLOBAL hData = GlobalAlloc(0, sizeof(DWORD));
- if (hData) {
- DWORD *moveEffect = (DWORD *)GlobalLock(hData);;
- *moveEffect = DROPEFFECT_MOVE;
- GlobalUnlock(hData);
- STGMEDIUM medium;
- memset(&medium, 0, sizeof(STGMEDIUM));
- medium.tymed = TYMED_HGLOBAL;
- medium.hGlobal = hData;
- FORMATETC format;
- format.cfFormat = RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT);
- format.tymed = TYMED_HGLOBAL;
- format.ptd = 0;
- format.dwAspect = 1;
- format.lindex = -1;
- manager->dropData->currentDataObject->SetData(&format, &medium, true);
- }
- } else {
- chosenEffect = translateToWinDragEffects(e.dropAction());
- }
- } else {
- chosenEffect = DROPEFFECT_NONE;
- }
- *pdwEffect = chosenEffect;
-
-
- if (manager->dropData->currentDataObject) {
- manager->dropData->currentDataObject->Release();
- manager->dropData->currentDataObject = 0;
- }
-
- return NOERROR;
-
- // We won't get any mouserelease-event, so manually adjust qApp state:
-///### test this QApplication::winMouseButtonUp();
-}
-
-//---------------------------------------------------------------------
-// QDropData
-//---------------------------------------------------------------------
-
-bool QDropData::hasFormat_sys(const QString &mimeType) const
-{
- if (!currentDataObject) // Sanity
- return false;
-
- return QWindowsMime::converterToMime(mimeType, currentDataObject) != 0;
-}
-
-QStringList QDropData::formats_sys() const
-{
- QStringList fmts;
- if (!currentDataObject) // Sanity
- return fmts;
-
- fmts = QWindowsMime::allMimesForFormats(currentDataObject);
-
- return fmts;
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
-{
- QVariant result;
-
- if (!currentDataObject) // Sanity
- return result;
-
- QWindowsMime *converter = QWindowsMime::converterToMime(mimeType, currentDataObject);
-
- if (converter)
- result = converter->convertToMime(mimeType, currentDataObject, type);
-
- return result;
-}
-
-Qt::DropAction QDragManager::drag(QDrag *o)
-
-{
-#ifdef QDND_DEBUG
- qDebug("QDragManager::drag(QDrag *drag)");
-#endif
-
- if (object == o || !o || !o->d_func()->source)
- return Qt::IgnoreAction;
-
- if (object) {
- cancel();
- qApp->removeEventFilter(this);
- beingCancelled = false;
- }
-
- object = o;
-
-#ifdef QDND_DEBUG
- qDebug("actions = %s", dragActionsToString(dragPrivate()->possible_actions).toLatin1().data());
-#endif
-
- dragPrivate()->target = 0;
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
-#endif
-
- DWORD resultEffect;
- QOleDropSource *src = new QOleDropSource();
- src->createCursors();
- QOleDataObject *obj = new QOleDataObject(o->mimeData());
- DWORD allowedEffects = translateToWinDragEffects(dragPrivate()->possible_actions);
-
-#if !defined(Q_OS_WINCE) || defined(GWES_ICONCURS)
- HRESULT r = DoDragDrop(obj, src, allowedEffects, &resultEffect);
-#else
- HRESULT r = DRAGDROP_S_CANCEL;
- resultEffect = DROPEFFECT_MOVE;
-#endif
-
- Qt::DropAction ret = Qt::IgnoreAction;
- if (r == DRAGDROP_S_DROP) {
- if (obj->reportedPerformedEffect() == DROPEFFECT_MOVE && resultEffect != DROPEFFECT_MOVE) {
- ret = Qt::TargetMoveAction;
- resultEffect = DROPEFFECT_MOVE;
- } else {
- ret = translateToQDragDropAction(resultEffect);
- }
- // Force it to be a copy if an unsupported operation occurred.
- // This indicates a bug in the drop target.
- if (resultEffect != DROPEFFECT_NONE && !(resultEffect & allowedEffects))
- ret = Qt::CopyAction;
- } else {
- dragPrivate()->target = 0;
- }
-
- // clean up
- obj->releaseQt();
- obj->Release(); // Will delete obj if refcount becomes 0
- src->Release(); // Will delete src if refcount becomes 0
- object = 0;
- o->setMimeData(0);
- o->deleteLater();
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DragDropEnd);
-#endif
-
- return ret;
-}
-
-void QDragManager::cancel(bool /* deleteSource */)
-{
- if (object) {
- beingCancelled = true;
- object = 0;
- }
-
-#ifndef QT_NO_CURSOR
- // insert cancel code here ######## todo
-
- if (restoreCursor) {
- QApplication::restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::DragDropEnd);
-#endif
-}
-
-void QDragManager::updatePixmap()
-{
- // not used in windows implementation
-}
-
-bool QDragManager::eventFilter(QObject *, QEvent *)
-{
- // not used in windows implementation
- return false;
-}
-
-void QDragManager::timerEvent(QTimerEvent*)
-{
- // not used in windows implementation
-}
-
-void QDragManager::move(const QPoint &)
-{
- // not used in windows implementation
-}
-
-void QDragManager::drop()
-{
- // not used in windows implementation
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DRAGANDDROP
diff --git a/src/gui/platforms/win/qfont_win.cpp b/src/gui/platforms/win/qfont_win.cpp
deleted file mode 100644
index 3ef761bfa5..0000000000
--- a/src/gui/platforms/win/qfont_win.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfont.h"
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qtextengine_p.h"
-#include "qfontmetrics.h"
-#include "qfontinfo.h"
-
-#include "qwidget.h"
-#include "qpainter.h"
-#include <limits.h>
-#include "qt_windows.h"
-#include <private/qapplication_p.h>
-#include "qapplication.h"
-#include <private/qunicodetables_p.h>
-#include <qfontdatabase.h>
-
-QT_BEGIN_NAMESPACE
-
-extern HDC shared_dc(); // common dc for all fonts
-extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
-
-// ### maybe move to qapplication_win
-QFont qt_LOGFONTtoQFont(LOGFONT& lf, bool /*scale*/)
-{
- QString family = QString::fromWCharArray(lf.lfFaceName);
- QFont qf(family);
- qf.setItalic(lf.lfItalic);
- if (lf.lfWeight != FW_DONTCARE)
- qf.setWeight(weightFromInteger(lf.lfWeight));
- int lfh = qAbs(lf.lfHeight);
- qf.setPointSizeF(lfh * 72.0 / GetDeviceCaps(shared_dc(),LOGPIXELSY));
- qf.setUnderline(false);
- qf.setOverline(false);
- qf.setStrikeOut(false);
- return qf;
-}
-
-
-static inline float pixelSize(const QFontDef &request, int dpi)
-{
- float pSize;
- if (request.pointSize != -1)
- pSize = request.pointSize * dpi/ 72.;
- else
- pSize = request.pixelSize;
- return pSize;
-}
-
-static inline float pointSize(const QFontDef &fd, int dpi)
-{
- float pSize;
- if (fd.pointSize < 0)
- pSize = fd.pixelSize * 72. / ((float)dpi);
- else
- pSize = fd.pointSize;
- return pSize;
-}
-
-/*****************************************************************************
- QFont member functions
- *****************************************************************************/
-
-void QFont::initialize()
-{
-}
-
-void QFont::cleanup()
-{
- QFontCache::cleanup();
-}
-
-HFONT QFont::handle() const
-{
- QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
- Q_ASSERT(engine != 0);
- if (engine->type() == QFontEngine::Multi)
- engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
- if (engine->type() == QFontEngine::Win)
- return static_cast<QFontEngineWin *>(engine)->hfont;
- return 0;
-}
-
-QString QFont::rawName() const
-{
- return family();
-}
-
-void QFont::setRawName(const QString &name)
-{
- setFamily(name);
-}
-
-QString QFont::defaultFamily() const
-{
- switch(d->request.styleHint) {
- case QFont::Times:
- return QString::fromLatin1("Times New Roman");
- case QFont::Courier:
- case QFont::Monospace:
- return QString::fromLatin1("Courier New");
- case QFont::Decorative:
- return QString::fromLatin1("Bookman Old Style");
- case QFont::Cursive:
- return QString::fromLatin1("Comic Sans MS");
- case QFont::Fantasy:
- return QString::fromLatin1("Impact");
- case QFont::Helvetica:
- return QString::fromLatin1("Arial");
- case QFont::System:
- default:
- return QString::fromLatin1("MS Sans Serif");
- }
-}
-
-QString QFont::lastResortFamily() const
-{
- return QString::fromLatin1("helvetica");
-}
-
-QString QFont::lastResortFont() const
-{
- return QString::fromLatin1("arial");
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qfontdatabase_win.cpp b/src/gui/platforms/win/qfontdatabase_win.cpp
deleted file mode 100644
index 05b7509bf6..0000000000
--- a/src/gui/platforms/win/qfontdatabase_win.cpp
+++ /dev/null
@@ -1,1348 +0,0 @@
-/****************************************************************************
-**
-** 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 "qt_windows.h"
-#include <qmath.h>
-#include <private/qapplication_p.h>
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qpaintdevice.h"
-#include <private/qsystemlibrary_p.h>
-#include "qabstractfileengine.h"
-#include "qendian.h"
-
-#if !defined(QT_NO_DIRECTWRITE)
-# include "qsettings.h"
-# include "qfontenginedirectwrite_p.h"
-#endif
-
-#ifdef Q_OS_WINCE
-# include <QTemporaryFile>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern HDC shared_dc(); // common dc for all fonts
-
-#ifdef MAKE_TAG
-#undef MAKE_TAG
-#endif
-// GetFontData expects the tags in little endian ;(
-#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
- (((quint32)(ch4)) << 24) | \
- (((quint32)(ch3)) << 16) | \
- (((quint32)(ch2)) << 8) | \
- ((quint32)(ch1)) \
- )
-
-static HFONT stock_sysfont = 0;
-
-static bool localizedName(const QString &name)
-{
- const QChar *c = name.unicode();
- for(int i = 0; i < name.length(); ++i) {
- if(c[i].unicode() >= 0x100)
- return true;
- }
- return false;
-}
-
-static inline quint16 getUShort(const unsigned char *p)
-{
- quint16 val;
- val = *p++ << 8;
- val |= *p;
-
- return val;
-}
-
-static QString getEnglishName(const uchar *table, quint32 bytes)
-{
- QString i18n_name;
- enum {
- NameRecordSize = 12,
- FamilyId = 1,
- MS_LangIdEnglish = 0x009
- };
-
- // get the name table
- quint16 count;
- quint16 string_offset;
- const unsigned char *names;
-
- int microsoft_id = -1;
- int apple_id = -1;
- int unicode_id = -1;
-
- if(getUShort(table) != 0)
- goto error;
-
- count = getUShort(table+2);
- string_offset = getUShort(table+4);
- names = table + 6;
-
- if(string_offset >= bytes || 6 + count*NameRecordSize > string_offset)
- goto error;
-
- for(int i = 0; i < count; ++i) {
- // search for the correct name entry
-
- quint16 platform_id = getUShort(names + i*NameRecordSize);
- quint16 encoding_id = getUShort(names + 2 + i*NameRecordSize);
- quint16 language_id = getUShort(names + 4 + i*NameRecordSize);
- quint16 name_id = getUShort(names + 6 + i*NameRecordSize);
-
- if(name_id != FamilyId)
- continue;
-
- enum {
- PlatformId_Unicode = 0,
- PlatformId_Apple = 1,
- PlatformId_Microsoft = 3
- };
-
- quint16 length = getUShort(names + 8 + i*NameRecordSize);
- quint16 offset = getUShort(names + 10 + i*NameRecordSize);
- if(DWORD(string_offset + offset + length) >= bytes)
- continue;
-
- if ((platform_id == PlatformId_Microsoft
- && (encoding_id == 0 || encoding_id == 1))
- && (language_id & 0x3ff) == MS_LangIdEnglish
- && microsoft_id == -1)
- microsoft_id = i;
- // not sure if encoding id 4 for Unicode is utf16 or ucs4...
- else if(platform_id == PlatformId_Unicode && encoding_id < 4 && unicode_id == -1)
- unicode_id = i;
- else if(platform_id == PlatformId_Apple && encoding_id == 0 && language_id == 0)
- apple_id = i;
- }
- {
- bool unicode = false;
- int id = -1;
- if(microsoft_id != -1) {
- id = microsoft_id;
- unicode = true;
- } else if(apple_id != -1) {
- id = apple_id;
- unicode = false;
- } else if (unicode_id != -1) {
- id = unicode_id;
- unicode = true;
- }
- if(id != -1) {
- quint16 length = getUShort(names + 8 + id*NameRecordSize);
- quint16 offset = getUShort(names + 10 + id*NameRecordSize);
- if(unicode) {
- // utf16
-
- length /= 2;
- i18n_name.resize(length);
- QChar *uc = (QChar *) i18n_name.unicode();
- const unsigned char *string = table + string_offset + offset;
- for(int i = 0; i < length; ++i)
- uc[i] = getUShort(string + 2*i);
- } else {
- // Apple Roman
-
- i18n_name.resize(length);
- QChar *uc = (QChar *) i18n_name.unicode();
- const unsigned char *string = table + string_offset + offset;
- for(int i = 0; i < length; ++i)
- uc[i] = QLatin1Char(string[i]);
- }
- }
- }
- error:
- //qDebug("got i18n name of '%s' for font '%s'", i18n_name.latin1(), familyName.toLocal8Bit().data());
- return i18n_name;
-}
-
-static QString getEnglishName(const QString &familyName)
-{
- QString i18n_name;
-
- HDC hdc = GetDC( 0 );
- LOGFONT lf;
- memset(&lf, 0, sizeof(LOGFONT));
- memcpy(lf.lfFaceName, familyName.utf16(), qMin(LF_FACESIZE, familyName.length()) * sizeof(wchar_t));
- lf.lfCharSet = DEFAULT_CHARSET;
- HFONT hfont = CreateFontIndirect(&lf);
-
- if(!hfont) {
- ReleaseDC(0, hdc);
- return QString();
- }
-
- HGDIOBJ oldobj = SelectObject( hdc, hfont );
-
- const DWORD name_tag = MAKE_TAG( 'n', 'a', 'm', 'e' );
-
- // get the name table
- unsigned char *table = 0;
-
- DWORD bytes = GetFontData( hdc, name_tag, 0, 0, 0 );
- if ( bytes == GDI_ERROR ) {
- // ### Unused variable
- /* int err = GetLastError(); */
- goto error;
- }
-
- table = new unsigned char[bytes];
- GetFontData(hdc, name_tag, 0, table, bytes);
- if ( bytes == GDI_ERROR )
- goto error;
-
- i18n_name = getEnglishName(table, bytes);
-error:
- delete [] table;
- SelectObject( hdc, oldobj );
- DeleteObject( hfont );
- ReleaseDC( 0, hdc );
-
- //qDebug("got i18n name of '%s' for font '%s'", i18n_name.latin1(), familyName.toLocal8Bit().data());
- return i18n_name;
-}
-
-extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
-
-static
-void addFontToDatabase(QString familyName, const QString &scriptName,
- TEXTMETRIC *textmetric,
- const FONTSIGNATURE *signature,
- int type)
-{
- const int script = -1;
- const QString foundryName;
- Q_UNUSED(script);
-
- bool italic = false;
- int weight;
- bool fixed;
- bool ttf;
- bool scalable;
- int size;
-
-// QString escript = QString::fromWCharArray(f->elfScript);
-// qDebug("script=%s", escript.latin1());
-
- NEWTEXTMETRIC *tm = (NEWTEXTMETRIC *)textmetric;
- fixed = !(tm->tmPitchAndFamily & TMPF_FIXED_PITCH);
- ttf = (tm->tmPitchAndFamily & TMPF_TRUETYPE);
- scalable = tm->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE);
- size = scalable ? SMOOTH_SCALABLE : tm->tmHeight;
- italic = tm->tmItalic;
- weight = tm->tmWeight;
-
- // the "@family" fonts are just the same as "family". Ignore them.
- if (familyName[0] != QLatin1Char('@') && !familyName.startsWith(QLatin1String("WST_"))) {
- QtFontStyle::Key styleKey;
- styleKey.style = italic ? QFont::StyleItalic : QFont::StyleNormal;
- styleKey.weight = weightFromInteger(weight);
-
- QtFontFamily *family = privateDb()->family(familyName, true);
-
- if(ttf && localizedName(familyName) && family->english_name.isEmpty())
- family->english_name = getEnglishName(familyName);
-
- QtFontFoundry *foundry = family->foundry(foundryName, true);
- QtFontStyle *style = foundry->style(styleKey, true);
- style->smoothScalable = scalable;
- style->pixelSize( size, TRUE);
-
- // add fonts windows can generate for us:
- if (styleKey.weight <= QFont::DemiBold) {
- QtFontStyle::Key key(styleKey);
- key.weight = QFont::Bold;
- QtFontStyle *style = foundry->style(key, true);
- style->smoothScalable = scalable;
- style->pixelSize( size, TRUE);
- }
- if (styleKey.style != QFont::StyleItalic) {
- QtFontStyle::Key key(styleKey);
- key.style = QFont::StyleItalic;
- QtFontStyle *style = foundry->style(key, true);
- style->smoothScalable = scalable;
- style->pixelSize( size, TRUE);
- }
- if (styleKey.weight <= QFont::DemiBold && styleKey.style != QFont::StyleItalic) {
- QtFontStyle::Key key(styleKey);
- key.weight = QFont::Bold;
- key.style = QFont::StyleItalic;
- QtFontStyle *style = foundry->style(key, true);
- style->smoothScalable = scalable;
- style->pixelSize( size, TRUE);
- }
-
- family->fixedPitch = fixed;
-
- if (!family->writingSystemCheck && type & TRUETYPE_FONTTYPE) {
- quint32 unicodeRange[4] = {
- signature->fsUsb[0], signature->fsUsb[1],
- signature->fsUsb[2], signature->fsUsb[3]
- };
-#ifdef Q_WS_WINCE
- if (signature->fsUsb[0] == 0) {
- // If the unicode ranges bit mask is zero then
- // EnumFontFamiliesEx failed to determine it properly.
- // In this case we just pretend that the font supports all languages.
- unicodeRange[0] = 0xbfffffff; // second most significant bit must be zero
- unicodeRange[1] = 0xffffffff;
- unicodeRange[2] = 0xffffffff;
- unicodeRange[3] = 0xffffffff;
- }
-#endif
- quint32 codePageRange[2] = {
- signature->fsCsb[0], signature->fsCsb[1]
- };
- QList<QFontDatabase::WritingSystem> systems = qt_determine_writing_systems_from_truetype_bits(unicodeRange, codePageRange);
-
- for (int i = 0; i < systems.count(); ++i) {
- QFontDatabase::WritingSystem writingSystem = systems.at(i);
-
- // ### Hack to work around problem with Thai text on Windows 7. Segoe UI contains
- // the symbol for Baht, and Windows thus reports that it supports the Thai script.
- // Since it's the default UI font on this platform, most widgets will be unable to
- // display Thai text by default. As a temporary work around, we special case Segoe UI
- // and remove the Thai script from its list of supported writing systems.
- if (writingSystem != QFontDatabase::Thai || familyName != QLatin1String("Segoe UI"))
- family->writingSystems[writingSystem] = QtFontFamily::Supported;
- }
- } else if (!family->writingSystemCheck) {
- //qDebug("family='%s' script=%s", family->name.latin1(), script.latin1());
- if (scriptName == QLatin1String("Western")
- || scriptName == QLatin1String("Baltic")
- || scriptName == QLatin1String("Central European")
- || scriptName == QLatin1String("Turkish")
- || scriptName == QLatin1String("Vietnamese"))
- family->writingSystems[QFontDatabase::Latin] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Thai"))
- family->writingSystems[QFontDatabase::Thai] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Symbol")
- || scriptName == QLatin1String("Other"))
- family->writingSystems[QFontDatabase::Symbol] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("OEM/Dos"))
- family->writingSystems[QFontDatabase::Latin] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("CHINESE_GB2312"))
- family->writingSystems[QFontDatabase::SimplifiedChinese] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("CHINESE_BIG5"))
- family->writingSystems[QFontDatabase::TraditionalChinese] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Cyrillic"))
- family->writingSystems[QFontDatabase::Cyrillic] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Hangul"))
- family->writingSystems[QFontDatabase::Korean] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Hebrew"))
- family->writingSystems[QFontDatabase::Hebrew] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Greek"))
- family->writingSystems[QFontDatabase::Greek] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Japanese"))
- family->writingSystems[QFontDatabase::Japanese] = QtFontFamily::Supported;
- else if (scriptName == QLatin1String("Arabic"))
- family->writingSystems[QFontDatabase::Arabic] = QtFontFamily::Supported;
- }
- }
-}
-
-static
-int CALLBACK
-storeFont(ENUMLOGFONTEX* f, NEWTEXTMETRICEX *textmetric, int type, LPARAM /*p*/)
-{
- QString familyName = QString::fromWCharArray(f->elfLogFont.lfFaceName);
- QString script = QString::fromWCharArray(f->elfScript);
-
- FONTSIGNATURE signature = textmetric->ntmFontSig;
-
- // NEWTEXTMETRICEX is a NEWTEXTMETRIC, which according to the documentation is
- // identical to a TEXTMETRIC except for the last four members, which we don't use
- // anyway
- addFontToDatabase(familyName, script, (TEXTMETRIC *)textmetric, &signature, type);
- // keep on enumerating
- return 1;
-}
-
-static
-void populate_database(const QString& fam)
-{
- QFontDatabasePrivate *d = privateDb();
- if (!d)
- return;
-
- QtFontFamily *family = 0;
- if(!fam.isEmpty()) {
- family = d->family(fam);
- if(family && family->loaded)
- return;
- } else if (d->count) {
- return;
- }
-
- HDC dummy = GetDC(0);
-
- LOGFONT lf;
- lf.lfCharSet = DEFAULT_CHARSET;
- if (fam.isNull()) {
- lf.lfFaceName[0] = 0;
- } else {
- memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32)); // 32 = Windows hard-coded
- }
- lf.lfPitchAndFamily = 0;
-
- EnumFontFamiliesEx(dummy, &lf,
- (FONTENUMPROC)storeFont, (LPARAM)privateDb(), 0);
-
- ReleaseDC(0, dummy);
-
- for (int i = 0; i < d->applicationFonts.count(); ++i) {
- QFontDatabasePrivate::ApplicationFont fnt = d->applicationFonts.at(i);
- if (!fnt.memoryFont)
- continue;
- for (int j = 0; j < fnt.families.count(); ++j) {
- const QString familyName = fnt.families.at(j);
- HDC hdc = GetDC(0);
- LOGFONT lf;
- memset(&lf, 0, sizeof(LOGFONT));
- memcpy(lf.lfFaceName, familyName.utf16(), sizeof(wchar_t) * qMin(LF_FACESIZE, familyName.size()));
- lf.lfCharSet = DEFAULT_CHARSET;
- HFONT hfont = CreateFontIndirect(&lf);
- HGDIOBJ oldobj = SelectObject(hdc, hfont);
-
- TEXTMETRIC textMetrics;
- GetTextMetrics(hdc, &textMetrics);
-
- addFontToDatabase(familyName, QString(),
- &textMetrics,
- &fnt.signatures.at(j),
- TRUETYPE_FONTTYPE);
-
- SelectObject(hdc, oldobj);
- DeleteObject(hfont);
- ReleaseDC(0, hdc);
- }
- }
-
- if(!fam.isEmpty()) {
- family = d->family(fam);
- if(family) {
- if(!family->writingSystemCheck) {
- }
- family->loaded = true;
- }
- }
-}
-
-static void initializeDb()
-{
- QFontDatabasePrivate *db = privateDb();
- if (!db || db->count)
- return;
-
- populate_database(QString());
-
-#ifdef QFONTDATABASE_DEBUG
- // print the database
- for (int f = 0; f < db->count; f++) {
- QtFontFamily *family = db->families[f];
- qDebug(" %s: %p", qPrintable(family->name), family);
- populate_database(family->name);
-
-#if 0
- qDebug(" scripts supported:");
- for (int i = 0; i < QUnicodeTables::ScriptCount; i++)
- if(family->writingSystems[i] & QtFontFamily::Supported)
- qDebug(" %d", i);
- for (int fd = 0; fd < family->count; fd++) {
- QtFontFoundry *foundry = family->foundries[fd];
- qDebug(" %s", foundry->name.latin1());
- for (int s = 0; s < foundry->count; s++) {
- QtFontStyle *style = foundry->styles[s];
- qDebug(" style: style=%d weight=%d smooth=%d", style->key.style,
- style->key.weight, style->smoothScalable );
- if(!style->smoothScalable) {
- for(int i = 0; i < style->count; ++i) {
- qDebug(" %d", style->pixelSizes[i].pixelSize);
- }
- }
- }
- }
-#endif
- }
-#endif // QFONTDATABASE_DEBUG
-
-}
-
-static inline void load(const QString &family = QString(), int = -1)
-{
- populate_database(family);
-}
-
-
-
-
-
-// --------------------------------------------------------------------------------------
-// font loader
-// --------------------------------------------------------------------------------------
-
-
-
-static void initFontInfo(QFontEngineWin *fe, const QFontDef &request, HDC fontHdc, int dpi)
-{
- fe->fontDef = request; // most settings are equal
-
- HDC dc = ((request.styleStrategy & QFont::PreferDevice) && fontHdc) ? fontHdc : shared_dc();
- SelectObject(dc, fe->hfont);
- wchar_t n[64];
- GetTextFace(dc, 64, n);
- fe->fontDef.family = QString::fromWCharArray(n);
- fe->fontDef.fixedPitch = !(fe->tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
- if (fe->fontDef.pointSize < 0) {
- fe->fontDef.pointSize = fe->fontDef.pixelSize * 72. / dpi;
- } else if (fe->fontDef.pixelSize == -1) {
- fe->fontDef.pixelSize = qRound(fe->fontDef.pointSize * dpi / 72.);
- }
-}
-
-#if !defined(QT_NO_DIRECTWRITE)
-static void initFontInfo(QFontEngineDirectWrite *fe, const QFontDef &request,
- int dpi, IDWriteFont *font)
-{
- fe->fontDef = request;
-
- IDWriteFontFamily *fontFamily = NULL;
- HRESULT hr = font->GetFontFamily(&fontFamily);
-
- IDWriteLocalizedStrings *familyNames = NULL;
- if (SUCCEEDED(hr))
- hr = fontFamily->GetFamilyNames(&familyNames);
-
- UINT32 index = 0;
- BOOL exists = false;
-
- wchar_t localeName[LOCALE_NAME_MAX_LENGTH];
-
- if (SUCCEEDED(hr)) {
- int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH);
-
- if (defaultLocaleSuccess)
- hr = familyNames->FindLocaleName(localeName, &index, &exists);
-
- if (SUCCEEDED(hr) && !exists)
- hr = familyNames->FindLocaleName(L"en-us", &index, &exists);
- }
-
- if (!exists)
- index = 0;
-
- UINT32 length = 0;
- if (SUCCEEDED(hr))
- hr = familyNames->GetStringLength(index, &length);
-
- wchar_t *name = new (std::nothrow) wchar_t[length+1];
- if (name == NULL)
- hr = E_OUTOFMEMORY;
-
- // Get the family name.
- if (SUCCEEDED(hr))
- hr = familyNames->GetString(index, name, length + 1);
-
- if (SUCCEEDED(hr))
- fe->fontDef.family = QString::fromWCharArray(name);
-
- delete[] name;
- if (familyNames != NULL)
- familyNames->Release();
-
- if (FAILED(hr))
- qErrnoWarning(hr, "initFontInfo: Failed to get family name");
-
- if (fe->fontDef.pointSize < 0)
- fe->fontDef.pointSize = fe->fontDef.pixelSize * 72. / dpi;
- else if (fe->fontDef.pixelSize == -1)
- fe->fontDef.pixelSize = qRound(fe->fontDef.pointSize * dpi / 72.);
-}
-#endif
-
-static const char *other_tryFonts[] = {
- "Arial",
- "MS UI Gothic",
- "Gulim",
- "SimSun",
- "PMingLiU",
- "Arial Unicode MS",
- 0
-};
-
-static const char *jp_tryFonts [] = {
- "MS UI Gothic",
- "Arial",
- "Gulim",
- "SimSun",
- "PMingLiU",
- "Arial Unicode MS",
- 0
-};
-
-static const char *ch_CN_tryFonts [] = {
- "SimSun",
- "Arial",
- "PMingLiU",
- "Gulim",
- "MS UI Gothic",
- "Arial Unicode MS",
- 0
-};
-
-static const char *ch_TW_tryFonts [] = {
- "PMingLiU",
- "Arial",
- "SimSun",
- "Gulim",
- "MS UI Gothic",
- "Arial Unicode MS",
- 0
-};
-
-static const char *kr_tryFonts[] = {
- "Gulim",
- "Arial",
- "PMingLiU",
- "SimSun",
- "MS UI Gothic",
- "Arial Unicode MS",
- 0
-};
-
-static const char **tryFonts = 0;
-
-#if !defined(QT_NO_DIRECTWRITE)
-static QString fontNameSubstitute(const QString &familyName)
-{
- QLatin1String key("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\"
- "FontSubstitutes");
- return QSettings(key, QSettings::NativeFormat).value(familyName, familyName).toString();
-}
-#endif
-
-static inline HFONT systemFont()
-{
- if (stock_sysfont == 0)
- stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT);
- return stock_sysfont;
-}
-
-#if !defined(DEFAULT_GUI_FONT)
-#define DEFAULT_GUI_FONT 17
-#endif
-
-static QFontEngine *loadEngine(int script, const QFontDef &request,
- HDC fontHdc, int dpi, bool rawMode,
- const QtFontDesc *desc,
- const QStringList &family_list)
-{
- LOGFONT lf;
- memset(&lf, 0, sizeof(LOGFONT));
-
- bool useDevice = (request.styleStrategy & QFont::PreferDevice) && fontHdc;
-
- HDC hdc = shared_dc();
- QString font_name = desc != 0 ? desc->family->name : request.family;
-
- if (useDevice) {
- hdc = fontHdc;
- font_name = request.family;
- }
-
- bool stockFont = false;
- bool preferClearTypeAA = false;
-
- HFONT hfont = 0;
-
-
-#if !defined(QT_NO_DIRECTWRITE)
- bool useDirectWrite = (request.hintingPreference == QFont::PreferNoHinting)
- || (request.hintingPreference == QFont::PreferVerticalHinting);
- IDWriteFont *directWriteFont = 0;
-#else
- bool useDirectWrite = false;
-#endif
-
- if (rawMode) { // will choose a stock font
- int f, deffnt = SYSTEM_FONT;
- QString fam = desc != 0 ? desc->family->name.toLower() : request.family.toLower();
- if (fam == QLatin1String("default"))
- f = deffnt;
- else if (fam == QLatin1String("system"))
- f = SYSTEM_FONT;
-#ifndef Q_WS_WINCE
- else if (fam == QLatin1String("system_fixed"))
- f = SYSTEM_FIXED_FONT;
- else if (fam == QLatin1String("ansi_fixed"))
- f = ANSI_FIXED_FONT;
- else if (fam == QLatin1String("ansi_var"))
- f = ANSI_VAR_FONT;
- else if (fam == QLatin1String("device_default"))
- f = DEVICE_DEFAULT_FONT;
- else if (fam == QLatin1String("oem_fixed"))
- f = OEM_FIXED_FONT;
-#endif
- else if (fam[0] == QLatin1Char('#'))
- f = fam.right(fam.length()-1).toInt();
- else
- f = deffnt;
- hfont = (HFONT)GetStockObject(f);
- if (!hfont) {
- qErrnoWarning("QFontEngine::loadEngine: GetStockObject failed");
- hfont = systemFont();
- }
- stockFont = true;
- } else {
-
- int hint = FF_DONTCARE;
- switch (request.styleHint) {
- case QFont::Helvetica:
- hint = FF_SWISS;
- break;
- case QFont::Times:
- hint = FF_ROMAN;
- break;
- case QFont::Courier:
- hint = FF_MODERN;
- break;
- case QFont::OldEnglish:
- hint = FF_DECORATIVE;
- break;
- case QFont::System:
- hint = FF_MODERN;
- break;
- default:
- break;
- }
-
- lf.lfHeight = -qRound(request.pixelSize);
- lf.lfWidth = 0;
- lf.lfEscapement = 0;
- lf.lfOrientation = 0;
- if (desc == 0 || desc->style->key.weight == 50)
- lf.lfWeight = FW_DONTCARE;
- else
- lf.lfWeight = (desc->style->key.weight*900)/99;
- lf.lfItalic = (desc != 0 && desc->style->key.style != QFont::StyleNormal);
- lf.lfCharSet = DEFAULT_CHARSET;
-
- int strat = OUT_DEFAULT_PRECIS;
- if (request.styleStrategy & QFont::PreferBitmap) {
- strat = OUT_RASTER_PRECIS;
-#ifndef Q_WS_WINCE
- } else if (request.styleStrategy & QFont::PreferDevice) {
- strat = OUT_DEVICE_PRECIS;
- } else if (request.styleStrategy & QFont::PreferOutline) {
- strat = OUT_OUTLINE_PRECIS;
- } else if (request.styleStrategy & QFont::ForceOutline) {
- strat = OUT_TT_ONLY_PRECIS;
-#endif
- }
-
- lf.lfOutPrecision = strat;
-
- int qual = DEFAULT_QUALITY;
-
- if (request.styleStrategy & QFont::PreferMatch)
- qual = DRAFT_QUALITY;
-#ifndef Q_WS_WINCE
- else if (request.styleStrategy & QFont::PreferQuality)
- qual = PROOF_QUALITY;
-#endif
-
- if (request.styleStrategy & QFont::PreferAntialias) {
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
- qual = CLEARTYPE_QUALITY;
- preferClearTypeAA = true;
- } else {
- qual = ANTIALIASED_QUALITY;
- }
- } else if (request.styleStrategy & QFont::NoAntialias) {
- qual = NONANTIALIASED_QUALITY;
- }
-
- lf.lfQuality = qual;
-
- lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
- lf.lfPitchAndFamily = DEFAULT_PITCH | hint;
-
- QString fam = font_name;
-
- if(fam.isEmpty())
- fam = QLatin1String("MS Sans Serif");
-
- if ((fam == QLatin1String("MS Sans Serif"))
- && (request.style == QFont::StyleItalic || (-lf.lfHeight > 18 && -lf.lfHeight != 24))) {
- fam = QLatin1String("Arial"); // MS Sans Serif has bearing problems in italic, and does not scale
- }
- if (fam == QLatin1String("Courier") && !(request.styleStrategy & QFont::PreferBitmap))
- fam = QLatin1String("Courier New");
-
- memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32)); // 32 = Windows hard-coded
-
- hfont = CreateFontIndirect(&lf);
- if (!hfont)
- qErrnoWarning("QFontEngine::loadEngine: CreateFontIndirect failed");
-
- stockFont = (hfont == 0);
- bool ttf = false;
- int avWidth = 0;
- BOOL res;
- HGDIOBJ oldObj = SelectObject(hdc, hfont);
-
- TEXTMETRIC tm;
- res = GetTextMetrics(hdc, &tm);
- avWidth = tm.tmAveCharWidth;
- ttf = tm.tmPitchAndFamily & TMPF_TRUETYPE;
- SelectObject(hdc, oldObj);
-
- if (!ttf || !useDirectWrite) {
- useDirectWrite = false;
-
- if (hfont && (!ttf || request.stretch != 100)) {
- DeleteObject(hfont);
- if (!res)
- qErrnoWarning("QFontEngine::loadEngine: GetTextMetrics failed");
- lf.lfWidth = avWidth * request.stretch/100;
- hfont = CreateFontIndirect(&lf);
- if (!hfont)
- qErrnoWarning("QFontEngine::loadEngine: CreateFontIndirect with stretch failed");
- }
-
-#ifndef Q_WS_WINCE
- if (hfont == 0) {
- hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
- stockFont = true;
- }
-#else
- if (hfont == 0) {
- hfont = (HFONT)GetStockObject(SYSTEM_FONT);
- stockFont = true;
- }
-#endif
-
- }
-
-#if !defined(QT_NO_DIRECTWRITE)
- else {
- // Default to false for DirectWrite (and re-enable once/if everything
- // turns out okay)
- useDirectWrite = false;
-
- QFontDatabasePrivate *db = privateDb();
- if (db->directWriteFactory == 0) {
- HRESULT hr = DWriteCreateFactory(
- DWRITE_FACTORY_TYPE_SHARED,
- __uuidof(IDWriteFactory),
- reinterpret_cast<IUnknown **>(&db->directWriteFactory)
- );
- if (FAILED(hr)) {
- qErrnoWarning("QFontEngine::loadEngine: DWriteCreateFactory failed");
- } else {
- hr = db->directWriteFactory->GetGdiInterop(&db->directWriteGdiInterop);
- if (FAILED(hr))
- qErrnoWarning("QFontEngine::loadEngine: GetGdiInterop failed");
- }
- }
-
- if (db->directWriteGdiInterop != 0) {
- QString nameSubstitute = fontNameSubstitute(QString::fromWCharArray(lf.lfFaceName));
- memcpy(lf.lfFaceName, nameSubstitute.utf16(),
- sizeof(wchar_t) * qMin(nameSubstitute.length() + 1, LF_FACESIZE));
-
- HRESULT hr = db->directWriteGdiInterop->CreateFontFromLOGFONT(
- &lf,
- &directWriteFont);
- if (FAILED(hr)) {
-#ifndef QT_NO_DEBUG
- qErrnoWarning("QFontEngine::loadEngine: CreateFontFromLOGFONT failed "
- "for %ls (0x%lx)",
- lf.lfFaceName, hr);
-#endif
- } else {
- DeleteObject(hfont);
- useDirectWrite = true;
- }
- }
- }
-#endif
-
- }
-
- QFontEngine *fe = 0;
- if (!useDirectWrite) {
- QFontEngineWin *few = new QFontEngineWin(font_name, hfont, stockFont, lf);
- if (preferClearTypeAA)
- few->glyphFormat = QFontEngineGlyphCache::Raster_RGBMask;
-
- // Also check for OpenType tables when using complex scripts
- // ### TODO: This only works for scripts that require OpenType. More generally
- // for scripts that do not require OpenType we should just look at the list of
- // supported writing systems in the font's OS/2 table.
- if (scriptRequiresOpenType(script)) {
- HB_Face hbFace = few->harfbuzzFace();
- if (!hbFace || !hbFace->supported_scripts[script]) {
- FM_DEBUG(" OpenType support missing for script\n");
- delete few;
- return 0;
- }
- }
-
- initFontInfo(few, request, fontHdc, dpi);
- fe = few;
- }
-
-#if !defined(QT_NO_DIRECTWRITE)
- else {
- QFontDatabasePrivate *db = privateDb();
-
- IDWriteFontFace *directWriteFontFace = NULL;
- HRESULT hr = directWriteFont->CreateFontFace(&directWriteFontFace);
- if (SUCCEEDED(hr)) {
- QFontEngineDirectWrite *fedw = new QFontEngineDirectWrite(db->directWriteFactory,
- directWriteFontFace,
- request.pixelSize);
-
- initFontInfo(fedw, request, dpi, directWriteFont);
-
- fe = fedw;
- } else {
- qErrnoWarning(hr, "QFontEngine::loadEngine: CreateFontFace failed");
- }
- }
-
- if (directWriteFont != 0)
- directWriteFont->Release();
-#endif
-
- if(script == QUnicodeTables::Common
- && !(request.styleStrategy & QFont::NoFontMerging)
- && desc != 0
- && !(desc->family->writingSystems[QFontDatabase::Symbol] & QtFontFamily::Supported)) {
- if(!tryFonts) {
- LANGID lid = GetUserDefaultLangID();
- switch( lid&0xff ) {
- case LANG_CHINESE: // Chinese (Taiwan)
- if ( lid == 0x0804 ) // Taiwan
- tryFonts = ch_TW_tryFonts;
- else
- tryFonts = ch_CN_tryFonts;
- break;
- case LANG_JAPANESE:
- tryFonts = jp_tryFonts;
- break;
- case LANG_KOREAN:
- tryFonts = kr_tryFonts;
- break;
- default:
- tryFonts = other_tryFonts;
- break;
- }
- }
- QStringList fm = QFontDatabase().families();
- QStringList list = family_list;
- const char **tf = tryFonts;
- while(tf && *tf) {
- if(fm.contains(QLatin1String(*tf)))
- list << QLatin1String(*tf);
- ++tf;
- }
- QFontEngine *mfe = new QFontEngineMultiWin(fe, list);
- mfe->fontDef = fe->fontDef;
- fe = mfe;
- }
- return fe;
-}
-
-QFontEngine *qt_load_font_engine_win(const QFontDef &request)
-{
- // From qfont.cpp
- extern int qt_defaultDpi();
-
- QFontCache::Key key(request, QUnicodeTables::Common);
- QFontEngine *fe = QFontCache::instance()->findEngine(key);
- if (fe != 0)
- return fe;
- else
- return loadEngine(QUnicodeTables::Common, request, 0, qt_defaultDpi(), false, 0,
- QStringList());
-}
-
-const char *styleHint(const QFontDef &request)
-{
- const char *stylehint = 0;
- switch (request.styleHint) {
- case QFont::SansSerif:
- stylehint = "Arial";
- break;
- case QFont::Serif:
- stylehint = "Times New Roman";
- break;
- case QFont::TypeWriter:
- stylehint = "Courier New";
- break;
- default:
- if (request.fixedPitch)
- stylehint = "Courier New";
- break;
- }
- return stylehint;
-}
-
-static QFontEngine *loadWin(const QFontPrivate *d, int script, const QFontDef &req)
-{
- // list of families to try
- QStringList family_list = familyList(req);
-
- const char *stylehint = styleHint(d->request);
- if (stylehint)
- family_list << QLatin1String(stylehint);
-
- // append the default fallback font for the specified script
- // family_list << ... ; ###########
-
- // add the default family
- QString defaultFamily = QApplication::font().family();
- if (! family_list.contains(defaultFamily))
- family_list << defaultFamily;
-
- // add QFont::defaultFamily() to the list, for compatibility with
- // previous versions
- family_list << QApplication::font().defaultFamily();
-
- // null family means find the first font matching the specified script
- family_list << QString();
-
- QtFontDesc desc;
- QFontEngine *fe = 0;
- QList<int> blacklistedFamilies;
-
- while (!fe) {
- for (int i = 0; i < family_list.size(); ++i) {
- QString family, foundry;
- parseFontName(family_list.at(i), foundry, family);
- FM_DEBUG("loadWin: >>>>>>>>>>>>>>trying to match '%s'", family.toLatin1().data());
- QT_PREPEND_NAMESPACE(match)(script, req, family, foundry, -1, &desc, blacklistedFamilies);
- if (desc.family)
- break;
- }
- if (!desc.family)
- break;
- fe = loadEngine(script, req, d->hdc, d->dpi, d->rawMode, &desc, family_list);
- if (!fe)
- blacklistedFamilies.append(desc.familyIndex);
- }
- return fe;
-}
-
-void QFontDatabase::load(const QFontPrivate *d, int script)
-{
- // sanity checks
- if (!qApp)
- qWarning("QFontDatabase::load: Must construct QApplication first");
- Q_ASSERT(script >= 0 && script < QUnicodeTables::ScriptCount);
-
- // normalize the request to get better caching
- QFontDef req = d->request;
- if (req.pixelSize <= 0)
- req.pixelSize = floor((100.0 * req.pointSize * d->dpi) / 72. + 0.5) / 100;
- if (req.pixelSize < 1)
- req.pixelSize = 1;
- if (req.weight == 0)
- req.weight = QFont::Normal;
- if (req.stretch == 0)
- req.stretch = 100;
-
- QFontCache::Key key(req, d->rawMode ? QUnicodeTables::Common : script, d->screen);
- if (!d->engineData)
- getEngineData(d, key);
-
- // the cached engineData could have already loaded the engine we want
- if (d->engineData->engines[script])
- return;
-
- QFontEngine *fe = QFontCache::instance()->findEngine(key);
-
- // set it to the actual pointsize, so QFontInfo will do the right thing
- if (req.pointSize < 0)
- req.pointSize = req.pixelSize*72./d->dpi;
-
- if (!fe) {
- if (qt_enable_test_font && req.family == QLatin1String("__Qt__Box__Engine__")) {
- fe = new QTestFontEngine(req.pixelSize);
- fe->fontDef = req;
- } else {
- QMutexLocker locker(fontDatabaseMutex());
- if (!privateDb()->count)
- initializeDb();
- fe = loadWin(d, script, req);
- }
- if (!fe) {
- fe = new QFontEngineBox(req.pixelSize);
- fe->fontDef = QFontDef();
- }
- }
- d->engineData->engines[script] = fe;
- fe->ref.ref();
- QFontCache::instance()->insertEngine(key, fe);
-}
-
-#if !defined(FR_PRIVATE)
-#define FR_PRIVATE 0x10
-#endif
-
-typedef int (WINAPI *PtrAddFontResourceExW)(LPCWSTR, DWORD, PVOID);
-typedef HANDLE (WINAPI *PtrAddFontMemResourceEx)(PVOID, DWORD, PVOID, DWORD *);
-typedef BOOL (WINAPI *PtrRemoveFontResourceExW)(LPCWSTR, DWORD, PVOID);
-typedef BOOL (WINAPI *PtrRemoveFontMemResourceEx)(HANDLE);
-
-static QList<quint32> getTrueTypeFontOffsets(const uchar *fontData)
-{
- QList<quint32> offsets;
- const quint32 headerTag = *reinterpret_cast<const quint32 *>(fontData);
- if (headerTag != MAKE_TAG('t', 't', 'c', 'f')) {
- if (headerTag != MAKE_TAG(0, 1, 0, 0)
- && headerTag != MAKE_TAG('O', 'T', 'T', 'O')
- && headerTag != MAKE_TAG('t', 'r', 'u', 'e')
- && headerTag != MAKE_TAG('t', 'y', 'p', '1'))
- return offsets;
- offsets << 0;
- return offsets;
- }
- const quint32 numFonts = qFromBigEndian<quint32>(fontData + 8);
- for (uint i = 0; i < numFonts; ++i) {
- offsets << qFromBigEndian<quint32>(fontData + 12 + i * 4);
- }
- return offsets;
-}
-
-static void getFontTable(const uchar *fileBegin, const uchar *data, quint32 tag, const uchar **table, quint32 *length)
-{
- const quint16 numTables = qFromBigEndian<quint16>(data + 4);
- for (uint i = 0; i < numTables; ++i) {
- const quint32 offset = 12 + 16 * i;
- if (*reinterpret_cast<const quint32 *>(data + offset) == tag) {
- *table = fileBegin + qFromBigEndian<quint32>(data + offset + 8);
- *length = qFromBigEndian<quint32>(data + offset + 12);
- return;
- }
- }
- *table = 0;
- *length = 0;
- return;
-}
-
-static void getFamiliesAndSignatures(const QByteArray &fontData, QFontDatabasePrivate::ApplicationFont *appFont)
-{
- const uchar *data = reinterpret_cast<const uchar *>(fontData.constData());
-
- QList<quint32> offsets = getTrueTypeFontOffsets(data);
- if (offsets.isEmpty())
- return;
-
- for (int i = 0; i < offsets.count(); ++i) {
- const uchar *font = data + offsets.at(i);
- const uchar *table;
- quint32 length;
- getFontTable(data, font, MAKE_TAG('n', 'a', 'm', 'e'), &table, &length);
- if (!table)
- continue;
- QString name = getEnglishName(table, length);
- if (name.isEmpty())
- continue;
-
- appFont->families << name;
- FONTSIGNATURE signature;
- getFontTable(data, font, MAKE_TAG('O', 'S', '/', '2'), &table, &length);
- if (table && length >= 86) {
- // See also qfontdatabase_mac.cpp, offsets taken from OS/2 table in the TrueType spec
- signature.fsUsb[0] = qFromBigEndian<quint32>(table + 42);
- signature.fsUsb[1] = qFromBigEndian<quint32>(table + 46);
- signature.fsUsb[2] = qFromBigEndian<quint32>(table + 50);
- signature.fsUsb[3] = qFromBigEndian<quint32>(table + 54);
-
- signature.fsCsb[0] = qFromBigEndian<quint32>(table + 78);
- signature.fsCsb[1] = qFromBigEndian<quint32>(table + 82);
- } else {
- memset(&signature, 0, sizeof(signature));
- }
- appFont->signatures << signature;
- }
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
-{
- if(!fnt->data.isEmpty()) {
-#ifndef Q_OS_WINCE
- PtrAddFontMemResourceEx ptrAddFontMemResourceEx = (PtrAddFontMemResourceEx)QSystemLibrary::resolve(QLatin1String("gdi32"),
- "AddFontMemResourceEx");
- if (!ptrAddFontMemResourceEx)
- return;
-#endif
- getFamiliesAndSignatures(fnt->data, fnt);
- if (fnt->families.isEmpty())
- return;
-
-#ifdef Q_OS_WINCE
- HANDLE handle = 0;
-
- {
-#ifdef QT_NO_TEMPORARYFILE
- wchar_t lpBuffer[MAX_PATH];
- GetTempPath(MAX_PATH, lpBuffer);
- QString s = QString::fromWCharArray(lpBuffer);
- QFile tempfile(s + QLatin1String("/font") + QString::number(GetTickCount()) + QLatin1String(".ttf"));
- if (!tempfile.open(QIODevice::ReadWrite))
-#else
- QTemporaryFile tempfile(QLatin1String("XXXXXXXX.ttf"));
- if (!tempfile.open())
-#endif // QT_NO_TEMPORARYFILE
- return;
- if (tempfile.write(fnt->data) == -1)
- return;
-
-#ifndef QT_NO_TEMPORARYFILE
- tempfile.setAutoRemove(false);
-#endif
- fnt->fileName = QFileInfo(tempfile.fileName()).absoluteFilePath();
- }
-
- if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0) {
- QFile(fnt->fileName).remove();
- return;
- }
-#else
- DWORD dummy = 0;
- HANDLE handle = ptrAddFontMemResourceEx((void *)fnt->data.constData(), fnt->data.size(), 0,
- &dummy);
- if (handle == 0)
- return;
-#endif // Q_OS_WINCE
-
- fnt->handle = handle;
- fnt->data = QByteArray();
- fnt->memoryFont = true;
- } else {
- QFile f(fnt->fileName);
- if (!f.open(QIODevice::ReadOnly))
- return;
- QByteArray data = f.readAll();
- f.close();
- getFamiliesAndSignatures(data, fnt);
-
-#ifdef Q_OS_WINCE
- QFileInfo fileinfo(fnt->fileName);
- fnt->fileName = fileinfo.absoluteFilePath();
- if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0)
- return;
-#else
- PtrAddFontResourceExW ptrAddFontResourceExW = (PtrAddFontResourceExW)QSystemLibrary::resolve(QLatin1String("gdi32"),
- "AddFontResourceExW");
- if (!ptrAddFontResourceExW
- || ptrAddFontResourceExW((wchar_t*)fnt->fileName.utf16(), FR_PRIVATE, 0) == 0)
- return;
-#endif // Q_OS_WINCE
-
- fnt->memoryFont = false;
- }
-}
-
-bool QFontDatabase::removeApplicationFont(int handle)
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- if (handle < 0 || handle >= db->applicationFonts.count())
- return false;
-
- const QFontDatabasePrivate::ApplicationFont font = db->applicationFonts.at(handle);
- db->applicationFonts[handle] = QFontDatabasePrivate::ApplicationFont();
- if (font.memoryFont) {
-#ifdef Q_OS_WINCE
- bool removeSucceeded = RemoveFontResource((LPCWSTR)font.fileName.utf16());
- QFile tempfile(font.fileName);
- tempfile.remove();
- if (!removeSucceeded)
- return false;
-#else
- PtrRemoveFontMemResourceEx ptrRemoveFontMemResourceEx = (PtrRemoveFontMemResourceEx)QSystemLibrary::resolve(QLatin1String("gdi32"),
- "RemoveFontMemResourceEx");
- if (!ptrRemoveFontMemResourceEx
- || !ptrRemoveFontMemResourceEx(font.handle))
- return false;
-#endif // Q_OS_WINCE
- } else {
-#ifdef Q_OS_WINCE
- if (!RemoveFontResource((LPCWSTR)font.fileName.utf16()))
- return false;
-#else
- PtrRemoveFontResourceExW ptrRemoveFontResourceExW = (PtrRemoveFontResourceExW)QSystemLibrary::resolve(QLatin1String("gdi32"),
- "RemoveFontResourceExW");
- if (!ptrRemoveFontResourceExW
- || !ptrRemoveFontResourceExW((LPCWSTR)font.fileName.utf16(), FR_PRIVATE, 0))
- return false;
-#endif // Q_OS_WINCE
- }
-
- db->invalidate();
- return true;
-}
-
-bool QFontDatabase::removeAllApplicationFonts()
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- for (int i = 0; i < db->applicationFonts.count(); ++i)
- if (!removeApplicationFont(i))
- return false;
- return true;
-}
-
-bool QFontDatabase::supportsThreadedFontRendering()
-{
- return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qfontengine_win.cpp b/src/gui/platforms/win/qfontengine_win.cpp
deleted file mode 100644
index 54d7ec2980..0000000000
--- a/src/gui/platforms/win/qfontengine_win.cpp
+++ /dev/null
@@ -1,1339 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#if _WIN32_WINNT < 0x0500
-#undef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
-#endif
-
-#include "qfontengine_p.h"
-#include "qtextengine_p.h"
-#include <qglobal.h>
-#include "qt_windows.h"
-#include <private/qapplication_p.h>
-
-#include <private/qsystemlibrary_p.h>
-#include <qpaintdevice.h>
-#include <qpainter.h>
-#include <limits.h>
-
-#include <qendian.h>
-#include <qmath.h>
-#include <qthreadstorage.h>
-
-#include <private/qunicodetables_p.h>
-#include <qbitmap.h>
-
-#include <private/qpainter_p.h>
-#include "qpaintengine.h"
-#include "qvarlengtharray.h"
-#include <private/qpaintengine_raster_p.h>
-#include <private/qnativeimage_p.h>
-
-#if defined(Q_WS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-//### mingw needed define
-#ifndef TT_PRIM_CSPLINE
-#define TT_PRIM_CSPLINE 3
-#endif
-
-#ifdef MAKE_TAG
-#undef MAKE_TAG
-#endif
-// GetFontData expects the tags in little endian ;(
-#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
- (((quint32)(ch4)) << 24) | \
- (((quint32)(ch3)) << 16) | \
- (((quint32)(ch2)) << 8) | \
- ((quint32)(ch1)) \
- )
-
-// common DC for all fonts
-
-QT_BEGIN_NAMESPACE
-
-class QtHDC
-{
- HDC _hdc;
-public:
- QtHDC()
- {
- HDC displayDC = GetDC(0);
- _hdc = CreateCompatibleDC(displayDC);
- ReleaseDC(0, displayDC);
- }
- ~QtHDC()
- {
- if (_hdc)
- DeleteDC(_hdc);
- }
- HDC hdc() const
- {
- return _hdc;
- }
-};
-
-#ifndef QT_NO_THREAD
-Q_GLOBAL_STATIC(QThreadStorage<QtHDC *>, local_shared_dc)
-HDC shared_dc()
-{
- QtHDC *&hdc = local_shared_dc()->localData();
- if (!hdc)
- hdc = new QtHDC;
- return hdc->hdc();
-}
-#else
-HDC shared_dc()
-{
- return 0;
-}
-#endif
-
-#ifndef Q_WS_WINCE
-typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
-static PtrGetCharWidthI ptrGetCharWidthI = 0;
-static bool resolvedGetCharWidthI = false;
-
-static void resolveGetCharWidthI()
-{
- if (resolvedGetCharWidthI)
- return;
- resolvedGetCharWidthI = true;
- ptrGetCharWidthI = (PtrGetCharWidthI)QSystemLibrary::resolve(QLatin1String("gdi32"), "GetCharWidthI");
-}
-#endif // !defined(Q_WS_WINCE)
-
-// defined in qtextengine_win.cpp
-typedef void *SCRIPT_CACHE;
-typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *);
-extern fScriptFreeCache ScriptFreeCache;
-
-static inline quint32 getUInt(unsigned char *p)
-{
- quint32 val;
- val = *p++ << 24;
- val |= *p++ << 16;
- val |= *p++ << 8;
- val |= *p;
-
- return val;
-}
-
-static inline quint16 getUShort(unsigned char *p)
-{
- quint16 val;
- val = *p++ << 8;
- val |= *p;
-
- return val;
-}
-
-// general font engine
-
-QFixed QFontEngineWin::lineThickness() const
-{
- if(lineWidth > 0)
- return lineWidth;
-
- return QFontEngine::lineThickness();
-}
-
-static OUTLINETEXTMETRIC *getOutlineTextMetric(HDC hdc)
-{
- int size;
- size = GetOutlineTextMetrics(hdc, 0, 0);
- OUTLINETEXTMETRIC *otm = (OUTLINETEXTMETRIC *)malloc(size);
- GetOutlineTextMetrics(hdc, size, otm);
- return otm;
-}
-
-void QFontEngineWin::getCMap()
-{
- ttf = (bool)(tm.tmPitchAndFamily & TMPF_TRUETYPE);
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
- bool symb = false;
- if (ttf) {
- cmapTable = getSfntTable(qbswap<quint32>(MAKE_TAG('c', 'm', 'a', 'p')));
- int size = 0;
- cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
- cmapTable.size(), &symb, &size);
- }
- if (!cmap) {
- ttf = false;
- symb = false;
- }
- symbol = symb;
- designToDevice = 1;
- _faceId.index = 0;
- if(cmap) {
- OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc);
- designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight);
- unitsPerEm = otm->otmEMSquare;
- x_height = (int)otm->otmsXHeight;
- loadKerningPairs(designToDevice);
- _faceId.filename = QString::fromWCharArray((wchar_t *)((char *)otm + (quintptr)otm->otmpFullName)).toLatin1();
- lineWidth = otm->otmsUnderscoreSize;
- fsType = otm->otmfsType;
- free(otm);
- } else {
- unitsPerEm = tm.tmHeight;
- }
-}
-
-
-inline unsigned int getChar(const QChar *str, int &i, const int len)
-{
- unsigned int uc = str[i].unicode();
- if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
- uint low = str[i+1].unicode();
- if (low >= 0xdc00 && low < 0xe000) {
- uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
- ++i;
- }
- }
- return uc;
-}
-
-int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs, bool mirrored) const
-{
- int i = 0;
- int glyph_pos = 0;
- if (mirrored) {
-#if defined(Q_WS_WINCE)
- {
-#else
- if (symbol) {
- for (; i < numChars; ++i, ++glyph_pos) {
- unsigned int uc = getChar(str, i, numChars);
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
- if (!glyphs->glyphs[glyph_pos] && uc < 0x100)
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
- }
- } else if (ttf) {
- for (; i < numChars; ++i, ++glyph_pos) {
- unsigned int uc = getChar(str, i, numChars);
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, QChar::mirroredChar(uc));
- }
- } else {
-#endif
- wchar_t first = tm.tmFirstChar;
- wchar_t last = tm.tmLastChar;
-
- for (; i < numChars; ++i, ++glyph_pos) {
- uint ucs = QChar::mirroredChar(getChar(str, i, numChars));
- if (
-#ifdef Q_WS_WINCE
- tm.tmFirstChar > 60000 || // see line 375
-#endif
- ucs >= first && ucs <= last)
- glyphs->glyphs[glyph_pos] = ucs;
- else
- glyphs->glyphs[glyph_pos] = 0;
- }
- }
- } else {
-#if defined(Q_WS_WINCE)
- {
-#else
- if (symbol) {
- for (; i < numChars; ++i, ++glyph_pos) {
- unsigned int uc = getChar(str, i, numChars);
- glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc);
- if(!glyphs->glyphs[glyph_pos] && uc < 0x100)
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
- }
- } else if (ttf) {
- for (; i < numChars; ++i, ++glyph_pos) {
- unsigned int uc = getChar(str, i, numChars);
- glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
- }
- } else {
-#endif
- wchar_t first = tm.tmFirstChar;
- wchar_t last = tm.tmLastChar;
-
- for (; i < numChars; ++i, ++glyph_pos) {
- uint uc = getChar(str, i, numChars);
- if (
-#ifdef Q_WS_WINCE
- tm.tmFirstChar > 60000 || // see comment in QFontEngineWin
-#endif
- uc >= first && uc <= last)
- glyphs->glyphs[glyph_pos] = uc;
- else
- glyphs->glyphs[glyph_pos] = 0;
- }
- }
- }
- glyphs->numGlyphs = glyph_pos;
- return glyph_pos;
-}
-
-
-QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont, LOGFONT lf)
-{
- //qDebug("regular windows font engine created: font='%s', size=%d", name, lf.lfHeight);
-
- _name = name;
-
- cmap = 0;
- hfont = _hfont;
- logfont = lf;
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
- this->stockFont = stockFont;
- fontDef.pixelSize = -lf.lfHeight;
-
- lbearing = SHRT_MIN;
- rbearing = SHRT_MIN;
- synthesized_flags = -1;
- lineWidth = -1;
- x_height = -1;
-
- BOOL res = GetTextMetrics(hdc, &tm);
- fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
- if (!res) {
- qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
- ZeroMemory(&tm, sizeof(TEXTMETRIC));
- }
-
- cache_cost = tm.tmHeight * tm.tmAveCharWidth * 2000;
- getCMap();
-
- widthCache = 0;
- widthCacheSize = 0;
- designAdvances = 0;
- designAdvancesSize = 0;
-
-#ifndef Q_WS_WINCE
- if (!resolvedGetCharWidthI)
- resolveGetCharWidthI();
-#endif
-}
-
-QFontEngineWin::~QFontEngineWin()
-{
- if (designAdvances)
- free(designAdvances);
-
- if (widthCache)
- free(widthCache);
-
- // make sure we aren't by accident still selected
- SelectObject(shared_dc(), (HFONT)GetStockObject(SYSTEM_FONT));
-
- if (!stockFont) {
- if (!DeleteObject(hfont))
- qErrnoWarning("QFontEngineWin: failed to delete non-stock font...");
- }
-}
-
-HGDIOBJ QFontEngineWin::selectDesignFont() const
-{
- LOGFONT f = logfont;
- f.lfHeight = unitsPerEm;
- HFONT designFont = CreateFontIndirect(&f);
- return SelectObject(shared_dc(), designFont);
-}
-
-bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- if (*nglyphs < len) {
- *nglyphs = len;
- return false;
- }
-
- *nglyphs = getGlyphIndexes(str, len, glyphs, flags & QTextEngine::RightToLeft);
-
- if (flags & QTextEngine::GlyphIndicesOnly)
- return true;
-
- recalcAdvances(glyphs, flags);
- return true;
-}
-
-inline void calculateTTFGlyphWidth(HDC hdc, UINT glyph, int &width)
-{
-#if defined(Q_WS_WINCE)
- GetCharWidth32(hdc, glyph, glyph, &width);
-#else
- if (ptrGetCharWidthI)
- ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
-#endif
-}
-
-void QFontEngineWin::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
- HGDIOBJ oldFont = 0;
- HDC hdc = shared_dc();
- if (ttf && (flags & QTextEngine::DesignMetrics)) {
- for(int i = 0; i < glyphs->numGlyphs; i++) {
- unsigned int glyph = glyphs->glyphs[i];
- if(int(glyph) >= designAdvancesSize) {
- int newSize = (glyph + 256) >> 8 << 8;
- designAdvances = q_check_ptr((QFixed *)realloc(designAdvances,
- newSize*sizeof(QFixed)));
- for(int i = designAdvancesSize; i < newSize; ++i)
- designAdvances[i] = -1000000;
- designAdvancesSize = newSize;
- }
- if (designAdvances[glyph] < -999999) {
- if (!oldFont)
- oldFont = selectDesignFont();
-
- int width = 0;
- calculateTTFGlyphWidth(hdc, glyph, width);
- designAdvances[glyph] = QFixed(width) / designToDevice;
- }
- glyphs->advances_x[i] = designAdvances[glyph];
- glyphs->advances_y[i] = 0;
- }
- if(oldFont)
- DeleteObject(SelectObject(hdc, oldFont));
- } else {
- for(int i = 0; i < glyphs->numGlyphs; i++) {
- unsigned int glyph = glyphs->glyphs[i];
-
- glyphs->advances_y[i] = 0;
-
- if (glyph >= widthCacheSize) {
- int newSize = (glyph + 256) >> 8 << 8;
- widthCache = q_check_ptr((unsigned char *)realloc(widthCache,
- newSize*sizeof(QFixed)));
- memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
- widthCacheSize = newSize;
- }
- glyphs->advances_x[i] = widthCache[glyph];
- // font-width cache failed
- if (glyphs->advances_x[i] == 0) {
- int width = 0;
- if (!oldFont)
- oldFont = SelectObject(hdc, hfont);
-
- if (!ttf) {
- QChar ch[2] = { ushort(glyph), 0 };
- int chrLen = 1;
- if (glyph > 0xffff) {
- ch[0] = QChar::highSurrogate(glyph);
- ch[1] = QChar::lowSurrogate(glyph);
- ++chrLen;
- }
- SIZE size = {0, 0};
- GetTextExtentPoint32(hdc, (wchar_t *)ch, chrLen, &size);
- width = size.cx;
- } else {
- calculateTTFGlyphWidth(hdc, glyph, width);
- }
- glyphs->advances_x[i] = width;
- // if glyph's within cache range, store it for later
- if (width > 0 && width < 0x100)
- widthCache[glyph] = width;
- }
- }
-
- if (oldFont)
- SelectObject(hdc, oldFont);
- }
-}
-
-glyph_metrics_t QFontEngineWin::boundingBox(const QGlyphLayout &glyphs)
-{
- if (glyphs.numGlyphs == 0)
- return glyph_metrics_t();
-
- QFixed w = 0;
- for (int i = 0; i < glyphs.numGlyphs; ++i)
- w += glyphs.effectiveAdvance(i);
-
- return glyph_metrics_t(0, -tm.tmAscent, w - lastRightBearing(glyphs), tm.tmHeight, w, 0);
-}
-
-#ifndef Q_WS_WINCE
-bool QFontEngineWin::getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const
-{
- Q_ASSERT(metrics != 0);
-
- HDC hdc = shared_dc();
-
- GLYPHMETRICS gm;
- DWORD res = 0;
- MAT2 mat;
- mat.eM11.value = mat.eM22.value = 1;
- mat.eM11.fract = mat.eM22.fract = 0;
- mat.eM21.value = mat.eM12.value = 0;
- mat.eM21.fract = mat.eM12.fract = 0;
-
- if (t.type() > QTransform::TxTranslate) {
- // We need to set the transform using the HDC's world
- // matrix rather than using the MAT2 above, because the
- // results provided when transforming via MAT2 does not
- // match the glyphs that are drawn using a WorldTransform
- XFORM xform;
- xform.eM11 = t.m11();
- xform.eM12 = t.m12();
- xform.eM21 = t.m21();
- xform.eM22 = t.m22();
- xform.eDx = 0;
- xform.eDy = 0;
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &xform);
- }
-
- uint format = GGO_METRICS;
- if (ttf)
- format |= GGO_GLYPH_INDEX;
- res = GetGlyphOutline(hdc, glyph, format, &gm, 0, 0, &mat);
-
- if (t.type() > QTransform::TxTranslate) {
- XFORM xform;
- xform.eM11 = xform.eM22 = 1;
- xform.eM12 = xform.eM21 = xform.eDx = xform.eDy = 0;
- SetWorldTransform(hdc, &xform);
- SetGraphicsMode(hdc, GM_COMPATIBLE);
- }
-
- if (res != GDI_ERROR) {
- *metrics = glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y,
- (int)gm.gmBlackBoxX, (int)gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY);
- return true;
- } else {
- return false;
- }
-}
-#endif
-
-glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph, const QTransform &t)
-{
-#ifndef Q_WS_WINCE
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
-
- glyph_metrics_t glyphMetrics;
- bool success = getOutlineMetrics(glyph, t, &glyphMetrics);
-
- if (!ttf && !success) {
- // Bitmap fonts
- wchar_t ch = glyph;
- ABCFLOAT abc;
- GetCharABCWidthsFloat(hdc, ch, ch, &abc);
- int width = qRound(abc.abcfB);
-
- return glyph_metrics_t(QFixed::fromReal(abc.abcfA), -tm.tmAscent, width, tm.tmHeight, width, 0).transformed(t);
- }
-
- return glyphMetrics;
-#else
- HDC hdc = shared_dc();
- HGDIOBJ oldFont = SelectObject(hdc, hfont);
-
- ABC abc;
- int width;
- int advance;
-#ifdef GWES_MGTT // true type fonts
- if (GetCharABCWidths(hdc, glyph, glyph, &abc)) {
- width = qAbs(abc.abcA) + abc.abcB + qAbs(abc.abcC);
- advance = abc.abcA + abc.abcB + abc.abcC;
- }
- else
-#endif
-#if defined(GWES_MGRAST) || defined(GWES_MGRAST2) // raster fonts
- if (GetCharWidth32(hdc, glyph, glyph, &width)) {
- advance = width;
- }
- else
-#endif
- { // fallback
- width = tm.tmMaxCharWidth;
- advance = width;
- }
-
- SelectObject(hdc, oldFont);
- return glyph_metrics_t(0, -tm.tmAscent, width, tm.tmHeight, advance, 0).transformed(t);
-#endif
-}
-
-QFixed QFontEngineWin::ascent() const
-{
- return tm.tmAscent;
-}
-
-QFixed QFontEngineWin::descent() const
-{
- // ### we substract 1 to even out the historical +1 in QFontMetrics's
- // ### height=asc+desc+1 equation. Fix in Qt5.
- return tm.tmDescent - 1;
-}
-
-QFixed QFontEngineWin::leading() const
-{
- return tm.tmExternalLeading;
-}
-
-
-QFixed QFontEngineWin::xHeight() const
-{
- if(x_height >= 0)
- return x_height;
- return QFontEngine::xHeight();
-}
-
-QFixed QFontEngineWin::averageCharWidth() const
-{
- return tm.tmAveCharWidth;
-}
-
-qreal QFontEngineWin::maxCharWidth() const
-{
- return tm.tmMaxCharWidth;
-}
-
-enum { max_font_count = 256 };
-static const ushort char_table[] = {
- 40,
- 67,
- 70,
- 75,
- 86,
- 88,
- 89,
- 91,
- 102,
- 114,
- 124,
- 127,
- 205,
- 645,
- 884,
- 922,
- 1070,
- 12386,
- 0
-};
-
-static const int char_table_entries = sizeof(char_table)/sizeof(ushort);
-
-#ifndef Q_CC_MINGW
-void QFontEngineWin::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
-{
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
-
-#ifndef Q_WS_WINCE
- if (ttf)
-#endif
-
- {
- ABC abcWidths;
- GetCharABCWidthsI(hdc, glyph, 1, 0, &abcWidths);
- if (leftBearing)
- *leftBearing = abcWidths.abcA;
- if (rightBearing)
- *rightBearing = abcWidths.abcC;
- }
-
-#ifndef Q_WS_WINCE
- else {
- QFontEngine::getGlyphBearings(glyph, leftBearing, rightBearing);
- }
-#endif
-}
-#endif // Q_CC_MINGW
-
-qreal QFontEngineWin::minLeftBearing() const
-{
- if (lbearing == SHRT_MIN)
- minRightBearing(); // calculates both
-
- return lbearing;
-}
-
-qreal QFontEngineWin::minRightBearing() const
-{
-#ifdef Q_WS_WINCE
- if (rbearing == SHRT_MIN) {
- int ml = 0;
- int mr = 0;
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
- if (ttf) {
- ABC *abc = 0;
- int n = tm.tmLastChar - tm.tmFirstChar;
- if (n <= max_font_count) {
- abc = new ABC[n+1];
- GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc);
- } else {
- abc = new ABC[char_table_entries+1];
- for(int i = 0; i < char_table_entries; i++)
- GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
- n = char_table_entries;
- }
- ml = abc[0].abcA;
- mr = abc[0].abcC;
- for (int i = 1; i < n; i++) {
- if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
- ml = qMin(ml,abc[i].abcA);
- mr = qMin(mr,abc[i].abcC);
- }
- }
- delete [] abc;
- }
- lbearing = ml;
- rbearing = mr;
- }
-
- return rbearing;
-#else
- if (rbearing == SHRT_MIN) {
- int ml = 0;
- int mr = 0;
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
- if (ttf) {
- ABC *abc = 0;
- int n = tm.tmLastChar - tm.tmFirstChar;
- if (n <= max_font_count) {
- abc = new ABC[n+1];
- GetCharABCWidths(hdc, tm.tmFirstChar, tm.tmLastChar, abc);
- } else {
- abc = new ABC[char_table_entries+1];
- for(int i = 0; i < char_table_entries; i++)
- GetCharABCWidths(hdc, char_table[i], char_table[i], abc + i);
- n = char_table_entries;
- }
- ml = abc[0].abcA;
- mr = abc[0].abcC;
- for (int i = 1; i < n; i++) {
- if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
- ml = qMin(ml,abc[i].abcA);
- mr = qMin(mr,abc[i].abcC);
- }
- }
- delete [] abc;
- } else {
- ABCFLOAT *abc = 0;
- int n = tm.tmLastChar - tm.tmFirstChar+1;
- if (n <= max_font_count) {
- abc = new ABCFLOAT[n];
- GetCharABCWidthsFloat(hdc, tm.tmFirstChar, tm.tmLastChar, abc);
- } else {
- abc = new ABCFLOAT[char_table_entries];
- for(int i = 0; i < char_table_entries; i++)
- GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i);
- n = char_table_entries;
- }
- float fml = abc[0].abcfA;
- float fmr = abc[0].abcfC;
- for (int i=1; i<n; i++) {
- if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) {
- fml = qMin(fml,abc[i].abcfA);
- fmr = qMin(fmr,abc[i].abcfC);
- }
- }
- ml = int(fml - 0.9999);
- mr = int(fmr - 0.9999);
- delete [] abc;
- }
- lbearing = ml;
- rbearing = mr;
- }
-
- return rbearing;
-#endif
-}
-
-
-const char *QFontEngineWin::name() const
-{
- return 0;
-}
-
-bool QFontEngineWin::canRender(const QChar *string, int len)
-{
- if (symbol) {
- for (int i = 0; i < len; ++i) {
- unsigned int uc = getChar(string, i, len);
- if (getTrueTypeGlyphIndex(cmap, uc) == 0) {
- if (uc < 0x100) {
- if (getTrueTypeGlyphIndex(cmap, uc + 0xf000) == 0)
- return false;
- } else {
- return false;
- }
- }
- }
- } else if (ttf) {
- for (int i = 0; i < len; ++i) {
- unsigned int uc = getChar(string, i, len);
- if (getTrueTypeGlyphIndex(cmap, uc) == 0)
- return false;
- }
- } else {
- while(len--) {
- if (tm.tmFirstChar > string->unicode() || tm.tmLastChar < string->unicode())
- return false;
- }
- }
- return true;
-}
-
-QFontEngine::Type QFontEngineWin::type() const
-{
- return QFontEngine::Win;
-}
-
-static inline double qt_fixed_to_double(const FIXED &p) {
- return ((p.value << 16) + p.fract) / 65536.0;
-}
-
-static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale) {
- return QPointF(qt_fixed_to_double(pt.x) * scale, -qt_fixed_to_double(pt.y) * scale);
-}
-
-#ifndef GGO_UNHINTED
-#define GGO_UNHINTED 0x0100
-#endif
-
-static bool addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc,
- QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, qreal scale = 1)
-{
-#if defined(Q_WS_WINCE)
- Q_UNUSED(glyph);
- Q_UNUSED(hdc);
-#endif
- MAT2 mat;
- mat.eM11.value = mat.eM22.value = 1;
- mat.eM11.fract = mat.eM22.fract = 0;
- mat.eM21.value = mat.eM12.value = 0;
- mat.eM21.fract = mat.eM12.fract = 0;
- uint glyphFormat = GGO_NATIVE;
-
- if (ttf)
- glyphFormat |= GGO_GLYPH_INDEX;
-
- GLYPHMETRICS gMetric;
- memset(&gMetric, 0, sizeof(GLYPHMETRICS));
- int bufferSize = GDI_ERROR;
-#if !defined(Q_WS_WINCE)
- bufferSize = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
-#endif
- if ((DWORD)bufferSize == GDI_ERROR) {
- return false;
- }
-
- void *dataBuffer = new char[bufferSize];
- DWORD ret = GDI_ERROR;
-#if !defined(Q_WS_WINCE)
- ret = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, bufferSize, dataBuffer, &mat);
-#endif
- if (ret == GDI_ERROR) {
- delete [](char *)dataBuffer;
- return false;
- }
-
- if(metric) {
- // #### obey scale
- *metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
- (int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
- gMetric.gmCellIncX, gMetric.gmCellIncY);
- }
-
- int offset = 0;
- int headerOffset = 0;
- TTPOLYGONHEADER *ttph = 0;
-
- QPointF oset = position.toPointF();
- while (headerOffset < bufferSize) {
- ttph = (TTPOLYGONHEADER*)((char *)dataBuffer + headerOffset);
-
- QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
- path->moveTo(lastPoint + oset);
- offset += sizeof(TTPOLYGONHEADER);
- TTPOLYCURVE *curve;
- while (offset<int(headerOffset + ttph->cb)) {
- curve = (TTPOLYCURVE*)((char*)(dataBuffer) + offset);
- switch (curve->wType) {
- case TT_PRIM_LINE: {
- for (int i=0; i<curve->cpfx; ++i) {
- QPointF p = qt_to_qpointf(curve->apfx[i], scale) + oset;
- path->lineTo(p);
- }
- break;
- }
- case TT_PRIM_QSPLINE: {
- const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1);
- QPointF prev(elm.x, elm.y);
- QPointF endPoint;
- for (int i=0; i<curve->cpfx - 1; ++i) {
- QPointF p1 = qt_to_qpointf(curve->apfx[i], scale) + oset;
- QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + oset;
- if (i < curve->cpfx - 2) {
- endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
- } else {
- endPoint = p2;
- }
-
- path->quadTo(p1, endPoint);
- prev = endPoint;
- }
-
- break;
- }
- case TT_PRIM_CSPLINE: {
- for (int i=0; i<curve->cpfx; ) {
- QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
- QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
- QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
- path->cubicTo(p2, p3, p4);
- }
- break;
- }
- default:
- qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case");
- }
- offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX);
- }
- path->closeSubpath();
- headerOffset += ttph->cb;
- }
- delete [] (char*)dataBuffer;
-
- return true;
-}
-
-void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags)
-{
- LOGFONT lf = logfont;
- // The sign must be negative here to make sure we match against character height instead of
- // hinted cell height. This ensures that we get linear matching, and we need this for
- // paths since we later on apply a scaling transform to the glyph outline to get the
- // font at the correct pixel size.
- lf.lfHeight = -unitsPerEm;
- lf.lfWidth = 0;
- HFONT hf = CreateFontIndirect(&lf);
- HDC hdc = shared_dc();
- HGDIOBJ oldfont = SelectObject(hdc, hf);
-
- for(int i = 0; i < nglyphs; ++i) {
- if (!addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0,
- qreal(fontDef.pixelSize) / unitsPerEm)) {
- // Some windows fonts, like "Modern", are vector stroke
- // fonts, which are reported as TMPF_VECTOR but do not
- // support GetGlyphOutline, and thus we set this bit so
- // that addOutLineToPath can check it and return safely...
- hasOutline = false;
- break;
- }
- }
- DeleteObject(SelectObject(hdc, oldfont));
-}
-
-void QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
- QPainterPath *path, QTextItem::RenderFlags flags)
-{
-#if !defined(Q_WS_WINCE)
- if(tm.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) {
- hasOutline = true;
- QFontEngine::addOutlineToPath(x, y, glyphs, path, flags);
- if (hasOutline) {
- // has_outline is set to false if addGlyphToPath gets
- // false from GetGlyphOutline, meaning its not an outline
- // font.
- return;
- }
- }
-#endif
- QFontEngine::addBitmapFontToPath(x, y, glyphs, path, flags);
-}
-
-QFontEngine::FaceId QFontEngineWin::faceId() const
-{
- return _faceId;
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qdebug.h>
-QT_END_INCLUDE_NAMESPACE
-
-int QFontEngineWin::synthesized() const
-{
- if(synthesized_flags == -1) {
- synthesized_flags = 0;
- if(ttf) {
- const DWORD HEAD = MAKE_TAG('h', 'e', 'a', 'd');
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
- uchar data[4];
- GetFontData(hdc, HEAD, 44, &data, 4);
- USHORT macStyle = getUShort(data);
- if (tm.tmItalic && !(macStyle & 2))
- synthesized_flags = SynthesizedItalic;
- if (fontDef.stretch != 100 && ttf)
- synthesized_flags |= SynthesizedStretch;
- if (tm.tmWeight >= 500 && !(macStyle & 1))
- synthesized_flags |= SynthesizedBold;
- //qDebug() << "font is" << _name <<
- // "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
- }
- }
- return synthesized_flags;
-}
-
-QFixed QFontEngineWin::emSquareSize() const
-{
- return unitsPerEm;
-}
-
-QFontEngine::Properties QFontEngineWin::properties() const
-{
- LOGFONT lf = logfont;
- lf.lfHeight = unitsPerEm;
- HFONT hf = CreateFontIndirect(&lf);
- HDC hdc = shared_dc();
- HGDIOBJ oldfont = SelectObject(hdc, hf);
- OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc);
- Properties p;
- p.emSquare = unitsPerEm;
- p.italicAngle = otm->otmItalicAngle;
- p.postscriptName = QString::fromWCharArray((wchar_t *)((char *)otm + (quintptr)otm->otmpFamilyName)).toLatin1();
- p.postscriptName += QString::fromWCharArray((wchar_t *)((char *)otm + (quintptr)otm->otmpStyleName)).toLatin1();
- p.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(p.postscriptName);
- p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top,
- otm->otmrcFontBox.right - otm->otmrcFontBox.left,
- otm->otmrcFontBox.top - otm->otmrcFontBox.bottom);
- p.ascent = otm->otmAscent;
- p.descent = -otm->otmDescent;
- p.leading = (int)otm->otmLineGap;
- p.capHeight = 0;
- p.lineWidth = otm->otmsUnderscoreSize;
- free(otm);
- DeleteObject(SelectObject(hdc, oldfont));
- return p;
-}
-
-void QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
-{
- LOGFONT lf = logfont;
- lf.lfHeight = unitsPerEm;
- int flags = synthesized();
- if(flags & SynthesizedItalic)
- lf.lfItalic = false;
- lf.lfWidth = 0;
- HFONT hf = CreateFontIndirect(&lf);
- HDC hdc = shared_dc();
- HGDIOBJ oldfont = SelectObject(hdc, hf);
- QFixedPoint p;
- p.x = 0;
- p.y = 0;
- addGlyphToPath(glyph, p, hdc, path, ttf, metrics);
- DeleteObject(SelectObject(hdc, oldfont));
-}
-
-bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
- if (!ttf)
- return false;
- HDC hdc = shared_dc();
- SelectObject(hdc, hfont);
- DWORD t = qbswap<quint32>(tag);
- *length = GetFontData(hdc, t, 0, buffer, *length);
- return *length != GDI_ERROR;
-}
-
-#if !defined(CLEARTYPE_QUALITY)
-# define CLEARTYPE_QUALITY 5
-#endif
-
-extern bool qt_cleartype_enabled;
-
-QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin,
- const QTransform &t, QImage::Format mask_format)
-{
- Q_UNUSED(mask_format)
- glyph_metrics_t gm = boundingBox(glyph);
-
-// printf(" -> for glyph %4x\n", glyph);
-
- int gx = gm.x.toInt();
- int gy = gm.y.toInt();
- int iw = gm.width.toInt();
- int ih = gm.height.toInt();
-
- if (iw <= 0 || iw <= 0)
- return 0;
-
- bool has_transformation = t.type() > QTransform::TxTranslate;
-
-#ifndef Q_WS_WINCE
- unsigned int options = ttf ? ETO_GLYPH_INDEX : 0;
- XFORM xform;
-
- if (has_transformation) {
- xform.eM11 = t.m11();
- xform.eM12 = t.m12();
- xform.eM21 = t.m21();
- xform.eM22 = t.m22();
- xform.eDx = margin;
- xform.eDy = margin;
-
- QtHDC qthdc;
- HDC hdc = qthdc.hdc();
-
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &xform);
- HGDIOBJ old_font = SelectObject(hdc, font);
-
- int ggo_options = GGO_METRICS | (ttf ? GGO_GLYPH_INDEX : 0);
- GLYPHMETRICS tgm;
- MAT2 mat;
- memset(&mat, 0, sizeof(mat));
- mat.eM11.value = mat.eM22.value = 1;
-
- if (GetGlyphOutline(hdc, glyph, ggo_options, &tgm, 0, 0, &mat) == GDI_ERROR) {
- qWarning("QWinFontEngine: unable to query transformed glyph metrics...");
- return 0;
- }
-
- iw = tgm.gmBlackBoxX;
- ih = tgm.gmBlackBoxY;
-
- xform.eDx -= tgm.gmptGlyphOrigin.x;
- xform.eDy += tgm.gmptGlyphOrigin.y;
-
- SetGraphicsMode(hdc, GM_COMPATIBLE);
- SelectObject(hdc, old_font);
- }
-#else // else winc
- unsigned int options = 0;
-#ifdef DEBUG
- Q_ASSERT(!has_transformation);
-#else
- Q_UNUSED(has_transformation);
-#endif
-#endif
-
- QNativeImage *ni = new QNativeImage(iw + 2 * margin + 4,
- ih + 2 * margin + 4,
- QNativeImage::systemFormat(), !qt_cleartype_enabled);
-
- /*If cleartype is enabled we use the standard system format even on Windows CE
- and not the special textbuffer format we have to use if cleartype is disabled*/
-
- ni->image.fill(0xffffffff);
-
- HDC hdc = ni->hdc;
-
- SelectObject(hdc, GetStockObject(NULL_BRUSH));
- SelectObject(hdc, GetStockObject(BLACK_PEN));
- SetTextColor(hdc, RGB(0,0,0));
- SetBkMode(hdc, TRANSPARENT);
- SetTextAlign(hdc, TA_BASELINE);
-
- HGDIOBJ old_font = SelectObject(hdc, font);
-
-#ifndef Q_OS_WINCE
- if (has_transformation) {
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &xform);
- ExtTextOut(hdc, 0, 0, options, 0, (LPCWSTR) &glyph, 1, 0);
- } else
-#endif
- {
- ExtTextOut(hdc, -gx + margin, -gy + margin, options, 0, (LPCWSTR) &glyph, 1, 0);
- }
-
- SelectObject(hdc, old_font);
- return ni;
-}
-
-
-extern uint qt_pow_gamma[256];
-
-QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform)
-{
- HFONT font = hfont;
- if (qt_cleartype_enabled) {
- LOGFONT lf = logfont;
- lf.lfQuality = ANTIALIASED_QUALITY;
- font = CreateFontIndirect(&lf);
- }
- QImage::Format mask_format = QNativeImage::systemFormat();
-#ifndef Q_OS_WINCE
- mask_format = QImage::Format_RGB32;
-#endif
-
- QNativeImage *mask = drawGDIGlyph(font, glyph, 0, xform, mask_format);
- if (mask == 0)
- return QImage();
-
- QImage indexed(mask->width(), mask->height(), QImage::Format_Indexed8);
-
- // ### This part is kinda pointless, but we'll crash later if we don't because some
- // code paths expects there to be colortables for index8-bit...
- QVector<QRgb> colors(256);
- for (int i=0; i<256; ++i)
- colors[i] = qRgba(0, 0, 0, i);
- indexed.setColorTable(colors);
-
- // Copy data... Cannot use QPainter here as GDI has messed up the
- // Alpha channel of the ni.image pixels...
- for (int y=0; y<mask->height(); ++y) {
- uchar *dest = indexed.scanLine(y);
- if (mask->image.format() == QImage::Format_RGB16) {
- const qint16 *src = (qint16 *) ((const QImage &) mask->image).scanLine(y);
- for (int x=0; x<mask->width(); ++x)
- dest[x] = 255 - qGray(src[x]);
- } else {
- const uint *src = (uint *) ((const QImage &) mask->image).scanLine(y);
- for (int x=0; x<mask->width(); ++x) {
-#ifdef Q_OS_WINCE
- dest[x] = 255 - qGray(src[x]);
-#else
- if (QNativeImage::systemFormat() == QImage::Format_RGB16)
- dest[x] = 255 - qGray(src[x]);
- else
- dest[x] = 255 - (qt_pow_gamma[qGray(src[x])] * 255. / 2047.);
-#endif
- }
- }
- }
-
- // Cleanup...
- delete mask;
- if (qt_cleartype_enabled) {
- DeleteObject(font);
- }
-
- return indexed;
-}
-
-#define SPI_GETFONTSMOOTHINGCONTRAST 0x200C
-#define SPI_SETFONTSMOOTHINGCONTRAST 0x200D
-
-QImage QFontEngineWin::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, const QTransform &t)
-{
- HFONT font = hfont;
-
- int contrast;
- SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &contrast, 0);
- SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, (void *) 1000, 0);
-
- QNativeImage *mask = drawGDIGlyph(font, glyph, margin, t, QImage::Format_RGB32);
- SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, (void *) contrast, 0);
-
- if (mask == 0)
- return QImage();
-
- // Gracefully handle the odd case when the display is 16-bit
- const QImage source = mask->image.depth() == 32
- ? mask->image
- : mask->image.convertToFormat(QImage::Format_RGB32);
-
- QImage rgbMask(mask->width(), mask->height(), QImage::Format_RGB32);
- for (int y=0; y<mask->height(); ++y) {
- uint *dest = (uint *) rgbMask.scanLine(y);
- const uint *src = (uint *) source.scanLine(y);
- for (int x=0; x<mask->width(); ++x) {
- dest[x] = 0xffffffff - (0x00ffffff & src[x]);
- }
- }
-
- delete mask;
-
- return rgbMask;
-}
-
-// From qfontdatabase_win.cpp
-extern QFontEngine *qt_load_font_engine_win(const QFontDef &request);
-QFontEngine *QFontEngineWin::cloneWithSize(qreal pixelSize) const
-{
- QFontDef request = fontDef;
- QString actualFontName = request.family;
- if (!uniqueFamilyName.isEmpty())
- request.family = uniqueFamilyName;
- request.pixelSize = pixelSize;
-
- QFontEngine *fontEngine = qt_load_font_engine_win(request);
- if (fontEngine != NULL)
- fontEngine->fontDef.family = actualFontName;
-
- return fontEngine;
-}
-
-// -------------------------------------- Multi font engine
-
-QFontEngineMultiWin::QFontEngineMultiWin(QFontEngine *first, const QStringList &fallbacks)
- : QFontEngineMulti(fallbacks.size()+1),
- fallbacks(fallbacks)
-{
- engines[0] = first;
- first->ref.ref();
- fontDef = engines[0]->fontDef;
- cache_cost = first->cache_cost;
-}
-
-void QFontEngineMultiWin::loadEngine(int at)
-{
- Q_ASSERT(at < engines.size());
- Q_ASSERT(engines.at(at) == 0);
-
- QString fam = fallbacks.at(at-1);
-
- LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont;
- memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32)); // 32 = Windows hard-coded
- HFONT hfont = CreateFontIndirect(&lf);
-
- bool stockFont = false;
- if (hfont == 0) {
- hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
- stockFont = true;
- }
- engines[at] = new QFontEngineWin(fam, hfont, stockFont, lf);
- engines[at]->ref.ref();
- engines[at]->fontDef = fontDef;
-
- // TODO: increase cost in QFontCache for the font engine loaded here
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qfontengine_win_p.h b/src/gui/platforms/win/qfontengine_win_p.h
deleted file mode 100644
index 114149d61f..0000000000
--- a/src/gui/platforms/win/qfontengine_win_p.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTENGINE_WIN_P_H
-#define QFONTENGINE_WIN_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qconfig.h>
-
-QT_BEGIN_NAMESPACE
-
-class QNativeImage;
-
-class QFontEngineWin : public QFontEngine
-{
-public:
- QFontEngineWin(const QString &name, HFONT, bool, LOGFONT);
- ~QFontEngineWin();
-
- virtual QFixed lineThickness() const;
- virtual Properties properties() const;
- virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
- virtual FaceId faceId() const;
- virtual bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
- virtual int synthesized() const;
- virtual QFixed emSquareSize() const;
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
- virtual void recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const;
-
- virtual void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags);
- virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
- QPainterPath *path, QTextItem::RenderFlags flags);
-
- HGDIOBJ selectDesignFont() const;
-
- virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- virtual glyph_metrics_t boundingBox(glyph_t g) { return boundingBox(g, QTransform()); }
- virtual glyph_metrics_t boundingBox(glyph_t g, const QTransform &t);
-
-
- virtual QFixed ascent() const;
- virtual QFixed descent() const;
- virtual QFixed leading() const;
- virtual QFixed xHeight() const;
- virtual QFixed averageCharWidth() const;
- virtual qreal maxCharWidth() const;
- virtual qreal minLeftBearing() const;
- virtual qreal minRightBearing() const;
-
- virtual const char *name() const;
-
- bool canRender(const QChar *string, int len);
-
- Type type() const;
-
- virtual QImage alphaMapForGlyph(glyph_t t) { return alphaMapForGlyph(t, QTransform()); }
- virtual QImage alphaMapForGlyph(glyph_t, const QTransform &xform);
- virtual QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform);
-
- virtual QFontEngine *cloneWithSize(qreal pixelSize) const;
-
-#ifndef Q_CC_MINGW
- virtual void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0);
-#endif
-
- int getGlyphIndexes(const QChar *ch, int numChars, QGlyphLayout *glyphs, bool mirrored) const;
- void getCMap();
-
-#ifndef Q_WS_WINCE
- bool getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const;
-#endif
-
- QString _name;
- QString uniqueFamilyName;
- HFONT hfont;
- LOGFONT logfont;
- uint stockFont : 1;
- uint ttf : 1;
- uint hasOutline : 1;
- TEXTMETRIC tm;
- int lw;
- const unsigned char *cmap;
- QByteArray cmapTable;
- mutable qreal lbearing;
- mutable qreal rbearing;
- QFixed designToDevice;
- int unitsPerEm;
- QFixed x_height;
- FaceId _faceId;
-
- mutable int synthesized_flags;
- mutable QFixed lineWidth;
- mutable unsigned char *widthCache;
- mutable uint widthCacheSize;
- mutable QFixed *designAdvances;
- mutable int designAdvancesSize;
-
-private:
- QNativeImage *drawGDIGlyph(HFONT font, glyph_t, int margin, const QTransform &xform,
- QImage::Format mask_format);
-
-};
-
-class QFontEngineMultiWin : public QFontEngineMulti
-{
-public:
- QFontEngineMultiWin(QFontEngine *first, const QStringList &fallbacks);
- void loadEngine(int at);
-
- QStringList fallbacks;
-};
-
-QT_END_NAMESPACE
-
-#endif // QFONTENGINE_WIN_P_H
diff --git a/src/gui/platforms/win/qguifunctions_wince.cpp b/src/gui/platforms/win/qguifunctions_wince.cpp
deleted file mode 100644
index bb4ed11589..0000000000
--- a/src/gui/platforms/win/qguifunctions_wince.cpp
+++ /dev/null
@@ -1,408 +0,0 @@
-/****************************************************************************
-**
-** 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 "qguifunctions_wince.h"
-#include <shellapi.h>
-#include <QtCore/qlibrary.h>
-
-QT_USE_NAMESPACE
-
-struct AygSHINITDLGINFO
-{
- DWORD dwMask;
- HWND hDlg;
- DWORD dwFlags;
-};
-
-struct AygSIPINFO
-{
- DWORD cbSize;
- DWORD fdwFlags;
- RECT rcVisibleDesktop;
- RECT rcSipRect;
- DWORD dwImDataSize;
- void *pvImData;
-};
-
-#ifndef SHIDIF_CANCELBUTTON
-#define SHIDIF_CANCELBUTTON 0x0080
-#endif
-
-#ifndef SHIDIM_FLAGS
-#define SHIDIM_FLAGS 0x0001
-#endif
-
-#ifndef SHIDIF_DONEBUTTON
-#define SHIDIF_DONEBUTTON 0x0001
-#endif
-#ifndef SHIDIF_SIZEDLGFULLSCREEN
-#define SHIDIF_SIZEDLGFULLSCREEN 0x0004
-#endif
-
-#ifndef SHDB_HIDE
-#define SHDB_HIDE 0x0002
-#endif
-
-#ifndef SHFS_SHOWTASKBAR
-#define SHFS_SHOWTASKBAR 0x0001
-#endif
-#ifndef SHFS_HIDETASKBAR
-#define SHFS_HIDETASKBAR 0x0002
-#endif
-#ifndef SHFS_SHOWSIPBUTTON
-#define SHFS_SHOWSIPBUTTON 0x0004
-#endif
-#ifndef SHFS_HIDESIPBUTTON
-#define SHFS_HIDESIPBUTTON 0x0008
-#endif
-#ifndef SHFS_SHOWSTARTICON
-#define SHFS_SHOWSTARTICON 0x0010
-#endif
-#ifndef SHFS_HIDESTARTICON
-#define SHFS_HIDESTARTICON 0x0020
-#endif
-
-#ifndef SIPF_OFF
-#define SIPF_OFF 0x00000000
-#endif
-#ifndef SIPF_ON
-#define SIPF_ON 0x00000001
-#endif
-
-#ifndef SPI_SETSIPINFO
-#define SPI_SETSIPINFO 224
-#endif
-#ifndef SPI_GETSIPINFO
-#define SPI_GETSIPINFO 225
-#endif
-#ifndef SPI_GETPLATFORMTYPE
-#define SPI_GETPLATFORMTYPE 257
-#endif
-
-typedef BOOL (*AygInitDialog)(AygSHINITDLGINFO*);
-typedef BOOL (*AygFullScreen)(HWND, DWORD);
-typedef BOOL (*AygSHSipInfo)(UINT, UINT, PVOID, UINT);
-typedef BOOL (*AygSHDoneButton)(HWND, DWORD);
-
-static AygInitDialog ptrAygInitDialog = 0;
-static AygFullScreen ptrAygFullScreen = 0;
-static AygSHSipInfo ptrAygSHSipInfo = 0;
-static AygSHDoneButton ptrAygSHDoneButton = 0;
-static bool aygResolved = false;
-
-static void resolveAygLibs()
-{
- if (!aygResolved) {
- aygResolved = true;
- QLibrary ayglib(QLatin1String("aygshell"));
- ptrAygInitDialog = (AygInitDialog) ayglib.resolve("SHInitDialog");
- ptrAygFullScreen = (AygFullScreen) ayglib.resolve("SHFullScreen");
- ptrAygSHSipInfo = (AygSHSipInfo) ayglib.resolve("SHSipInfo");
- ptrAygSHDoneButton = (AygSHDoneButton) ayglib.resolve("SHDoneButton");
- }
-}
-
-int qt_wince_GetDIBits(HDC /*hdc*/ , HBITMAP hSourceBitmap, uint, uint, LPVOID lpvBits, LPBITMAPINFO, uint)
-{
- if (!lpvBits) {
- qWarning("::GetDIBits(), lpvBits NULL");
- return 0;
- }
- BITMAP bm;
- GetObject(hSourceBitmap, sizeof(BITMAP), &bm);
- bm.bmHeight = qAbs(bm.bmHeight);
-
- HBITMAP hTargetBitmap;
- void *pixels;
-
- BITMAPINFO dibInfo;
- memset(&dibInfo, 0, sizeof(dibInfo));
- dibInfo.bmiHeader.biBitCount = 32;
- dibInfo.bmiHeader.biClrImportant = 0;
- dibInfo.bmiHeader.biClrUsed = 0;
- dibInfo.bmiHeader.biCompression = BI_RGB;;
- dibInfo.bmiHeader.biHeight = -bm.bmHeight;
- dibInfo.bmiHeader.biWidth = bm.bmWidth;
- dibInfo.bmiHeader.biPlanes = 1;
- dibInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- dibInfo.bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
-
- HDC displayDC = GetDC(NULL);
- if (!displayDC) {
- qWarning("::GetDIBits(), failed to GetDC");
- return 0;
- }
-
- int ret = bm.bmHeight;
-
- hTargetBitmap = CreateDIBSection(displayDC, (const BITMAPINFO*) &dibInfo, DIB_RGB_COLORS,
- (void**)&pixels, NULL, 0);
- if (!hTargetBitmap) {
- qWarning("::GetDIBits(), failed to CreateDIBSection");
- return 0;
- }
-
- HDC hdcSrc = CreateCompatibleDC(displayDC);
- HDC hdcDst = CreateCompatibleDC(displayDC);
-
- if (!(hdcDst && hdcSrc)) {
- qWarning("::GetDIBits(), failed to CreateCompatibleDC");
- ret = 0;
- }
-
- HBITMAP hOldBitmap1 = (HBITMAP) SelectObject(hdcSrc, hSourceBitmap);
- HBITMAP hOldBitmap2 = (HBITMAP) SelectObject(hdcDst, hTargetBitmap);
-
- if (!(hOldBitmap1 && hOldBitmap2)) {
- qWarning("::GetDIBits(), failed to SelectObject for bitmaps");
- ret = 0;
- }
-
- if (!BitBlt(hdcDst, 0, 0, bm.bmWidth, bm.bmHeight, hdcSrc, 0, 0, SRCCOPY)) {
- qWarning("::GetDIBits(), BitBlt failed");
- ret = 0;
- }
-
- SelectObject(hdcSrc, hOldBitmap1);
- SelectObject(hdcDst, hOldBitmap2);
-
- DeleteDC(hdcSrc);
- DeleteDC(hdcDst);
-
- ReleaseDC(NULL, displayDC);
-
- memcpy(lpvBits, pixels, dibInfo.bmiHeader.biSizeImage);
-
- DeleteObject(hTargetBitmap);
- return ret;
-}
-
-HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCWSTR, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int showCmd)
-{
- SHELLEXECUTEINFO info;
- info.hwnd = hwnd;
- info.lpVerb = L"Open";
- info.lpFile = file;
- info.lpParameters = params;
- info.lpDirectory = dir;
- info.nShow = showCmd;
- info.cbSize = sizeof(info);
- ShellExecuteEx(&info);
- return info.hInstApp;
-}
-
-// Clipboard --------------------------------------------------------
-BOOL qt_wince_ChangeClipboardChain( HWND /*hWndRemove*/, HWND /*hWndNewNext*/ )
-{
- return FALSE;
-}
-
-HWND qt_wince_SetClipboardViewer( HWND /*hWndNewViewer*/ )
-{
- return NULL;
-}
-
-
-// Graphics ---------------------------------------------------------
-COLORREF qt_wince_PALETTEINDEX( WORD /*wPaletteIndex*/)
-{
- return 0;
-}
-
-// Internal Qt -----------------------------------------------------
-bool qt_wince_is_platform(const QString &platformString) {
- wchar_t tszPlatform[64];
- if (SystemParametersInfo(SPI_GETPLATFORMTYPE, sizeof(tszPlatform) / sizeof(wchar_t), tszPlatform, 0))
- if (0 == _tcsicmp(reinterpret_cast<const wchar_t *> (platformString.utf16()), tszPlatform))
- return true;
- return false;
-}
-
-int qt_wince_get_build()
-{
- OSVERSIONINFO osvi;
- osvi.dwOSVersionInfoSize = sizeof(osvi);
- if (GetVersionEx(&osvi)) {
- return osvi.dwBuildNumber;
- }
- return 0;
-}
-
-int qt_wince_get_version()
-{
- OSVERSIONINFO osvi;
- osvi.dwOSVersionInfoSize = sizeof(osvi);
- if (GetVersionEx(&osvi)) {
- return (osvi.dwMajorVersion * 10 + osvi.dwMinorVersion);
- }
- return 0;
-}
-
-bool qt_wince_is_windows_mobile_65()
-{
- const DWORD dwFirstWM65BuildNumber = 21139;
- OSVERSIONINFO osvi;
- osvi.dwOSVersionInfoSize = sizeof(osvi);
- if (!GetVersionEx(&osvi))
- return false;
- return osvi.dwMajorVersion > 5
- || (osvi.dwMajorVersion == 5 && (osvi.dwMinorVersion > 2 ||
- (osvi.dwMinorVersion == 2 && osvi.dwBuildNumber >= dwFirstWM65BuildNumber)));
-}
-
-bool qt_wince_is_pocket_pc() {
- return qt_wince_is_platform(QString::fromLatin1("PocketPC"));
-}
-
-bool qt_wince_is_smartphone() {
- return qt_wince_is_platform(QString::fromLatin1("Smartphone"));
-}
-bool qt_wince_is_mobile() {
- return (qt_wince_is_smartphone() || qt_wince_is_pocket_pc());
-}
-
-bool qt_wince_is_high_dpi() {
- if (!qt_wince_is_pocket_pc())
- return false;
- HDC deviceContext = GetDC(0);
- int dpi = GetDeviceCaps(deviceContext, LOGPIXELSX);
- ReleaseDC(0, deviceContext);
- if ((dpi < 1000) && (dpi > 0))
- return dpi > 96;
- else
- return false;
-}
-
-void qt_wince_maximize(QWidget *widget)
-{
- HWND hwnd = widget->winId();
- if (qt_wince_is_mobile()) {
- AygSHINITDLGINFO shidi;
- shidi.dwMask = SHIDIM_FLAGS;
- shidi.hDlg = hwnd;
- shidi.dwFlags = SHIDIF_SIZEDLGFULLSCREEN;
- if (widget->windowFlags() & Qt::WindowCancelButtonHint)
- shidi.dwFlags |= SHIDIF_CANCELBUTTON;
- if (widget->windowFlags() & Qt::WindowOkButtonHint)
- shidi.dwFlags |= SHIDIF_DONEBUTTON;
- if (!(widget->windowFlags() & (Qt::WindowCancelButtonHint | Qt::WindowOkButtonHint)))
- shidi.dwFlags |= SHIDIF_CANCELBUTTON;
- resolveAygLibs();
- if (ptrAygInitDialog)
- ptrAygInitDialog(&shidi);
- } else {
- RECT r;
- SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
- MoveWindow(hwnd, r.top, r.left, r.right - r.left, r.bottom - r.top, true);
- SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_NODRAG);
- }
-}
-
-void qt_wince_unmaximize(QWidget *widget)
-{
- if (ptrAygSHDoneButton && qt_wince_is_mobile()
- && !(widget->windowFlags() & (Qt::WindowCancelButtonHint | Qt::WindowOkButtonHint)))
- {
- // Hide the [X] button, we've added in qt_wince_maximize.
- ptrAygSHDoneButton(widget->winId(), SHDB_HIDE);
- }
-}
-
-void qt_wince_minimize(HWND hwnd)
-{
-#ifdef Q_OS_WINCE_WM
- ShowWindow(hwnd, SW_HIDE);
-#else
- if (!IsWindowVisible(hwnd)) {
- // Hack for an initial showMinimized.
- // Without it, our widget doesn't appear in the task bar.
- ShowWindow(hwnd, SW_SHOW);
- }
- ShowWindow(hwnd, SW_MINIMIZE);
-#endif
-}
-
-void qt_wince_hide_taskbar(HWND hwnd) {
- if (ptrAygFullScreen)
- ptrAygFullScreen(hwnd, SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);
-}
-
-void qt_wince_full_screen(HWND hwnd, bool fullScreen, UINT swpf) {
- resolveAygLibs();
- if (fullScreen) {
- QRect r = qApp->desktop()->screenGeometry(QWidget::find(hwnd));
- SetWindowPos(hwnd, HWND_TOP, r.left(), r.top(), r.width(), r.height(), swpf);
- if (ptrAygFullScreen)
- ptrAygFullScreen(hwnd, SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);
- if (!qt_wince_is_mobile()) {
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- ShowWindow(handle, 0);
- EnableWindow(handle, false);
- }
- }
- } else {
- if (ptrAygFullScreen)
- ptrAygFullScreen(hwnd, SHFS_SHOWTASKBAR | SHFS_SHOWSIPBUTTON | SHFS_SHOWSTARTICON);
- SetWindowPos(hwnd, 0, 0, 0, 0, 0, swpf);
- if (!qt_wince_is_mobile()) {
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- ShowWindow(handle, 1);
- EnableWindow(handle, true);
- }
- }
- }
-}
-
-void qt_wince_show_SIP(bool show)
-{
- resolveAygLibs();
- if (!ptrAygSHSipInfo)
- return;
-
- AygSIPINFO si;
- memset(&si, 0, sizeof(si));
- si.cbSize = sizeof(si);
- ptrAygSHSipInfo(SPI_GETSIPINFO, 0, &si, 0);
- si.cbSize = sizeof(si);
- si.fdwFlags = (show ? SIPF_ON : SIPF_OFF);
- ptrAygSHSipInfo(SPI_SETSIPINFO, 0, &si, 0);
-}
diff --git a/src/gui/platforms/win/qguifunctions_wince.h b/src/gui/platforms/win/qguifunctions_wince.h
deleted file mode 100644
index 2e14de0693..0000000000
--- a/src/gui/platforms/win/qguifunctions_wince.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/****************************************************************************
-**
-** 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 QGUIFUNCTIONS_WCE_H
-#define QGUIFUNCTIONS_WCE_H
-#ifdef Q_OS_WINCE
-#include <QtCore/qfunctions_wince.h>
-#define UNDER_NT
-#include <wingdi.h>
-
-#ifdef QT_BUILD_GUI_LIB
-QT_BEGIN_HEADER
-QT_BEGIN_NAMESPACE
-QT_MODULE(Gui)
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif
-
-// application defines
-#define SPI_SETNONCLIENTMETRICS 72
-#define SPI_SETICONTITLELOGFONT 0x0022
-#define WM_ACTIVATEAPP 0x001c
-#define SW_PARENTCLOSING 1
-#define SW_OTHERMAXIMIZED 2
-#define SW_PARENTOPENING 3
-#define SW_OTHERRESTORED 4
-#define GET_XBUTTON_WPARAM(wParam) (HIWORD(wParam))
-
-// drag n drop
-#ifndef CFSTR_PERFORMEDDROPEFFECT
-#define CFSTR_PERFORMEDDROPEFFECT TEXT("Performed DropEffect")
-#endif
-int qt_wince_GetDIBits(HDC, HBITMAP, uint, uint, void*, LPBITMAPINFO, uint);
-#define GetDIBits(a,b,c,d,e,f,g) qt_wince_GetDIBits(a,b,c,d,e,f,g)
-
-// QWidget
-#define SW_SHOWMINIMIZED SW_MINIMIZE
-
-// QRegion
-#define ALTERNATE 0
-#define WINDING 1
-
-// QFontEngine
-typedef struct _FIXED {
- WORD fract;
- short value;
-} FIXED;
-
-typedef struct tagPOINTFX {
- FIXED x;
- FIXED y;
-} POINTFX;
-
-typedef struct _MAT2 {
- FIXED eM11;
- FIXED eM12;
- FIXED eM21;
- FIXED eM22;
-} MAT2;
-
-typedef struct _GLYPHMETRICS {
- UINT gmBlackBoxX;
- UINT gmBlackBoxY;
- POINT gmptGlyphOrigin;
- short gmCellIncX;
- short gmCellIncY;
-} GLYPHMETRICS;
-
-typedef struct tagTTPOLYGONHEADER
-{
- DWORD cb;
- DWORD dwType;
- POINTFX pfxStart;
-} TTPOLYGONHEADER;
-
-typedef struct tagTTPOLYCURVE
-{
- WORD wType;
- WORD cpfx;
- POINTFX apfx[1];
-} TTPOLYCURVE;
-
-#define GGO_NATIVE 2
-#define GGO_GLYPH_INDEX 0x0080
-#define TT_PRIM_LINE 1
-#define TT_PRIM_QSPLINE 2
-#define TT_PRIM_CSPLINE 3
-#define ANSI_VAR_FONT 12
-
-HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCWSTR operation, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int showCmd);
-#define ShellExecute(a,b,c,d,e,f) qt_wince_ShellExecute(a,b,c,d,e,f)
-
-
-// Clipboard --------------------------------------------------------
-#define WM_CHANGECBCHAIN 1
-#define WM_DRAWCLIPBOARD 2
-
-BOOL qt_wince_ChangeClipboardChain(
- HWND hWndRemove, // handle to window to remove
- HWND hWndNewNext // handle to next window
-);
-#define ChangeClipboardChain(a,b) qt_wince_ChangeClipboardChain(a,b);
-
-HWND qt_wince_SetClipboardViewer(
- HWND hWndNewViewer // handle to clipboard viewer window
-);
-#define SetClipboardViewer(a) qt_wince_SetClipboardViewer(a)
-
-// Graphics ---------------------------------------------------------
-COLORREF qt_wince_PALETTEINDEX( WORD wPaletteIndex );
-#define PALETTEINDEX(a) qt_wince_PALETTEINDEX(a)
-
-#endif // Q_OS_WINCE
-#endif // QGUIFUNCTIONS_WCE_H
diff --git a/src/gui/platforms/win/qkeymapper_win.cpp b/src/gui/platforms/win/qkeymapper_win.cpp
deleted file mode 100644
index 92fa582617..0000000000
--- a/src/gui/platforms/win/qkeymapper_win.cpp
+++ /dev/null
@@ -1,1207 +0,0 @@
-/****************************************************************************
-**
-** 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 "qkeymapper_p.h"
-
-#include <qt_windows.h>
-#include <qdebug.h>
-#include <private/qevent_p.h>
-#include <private/qlocale_p.h>
-#include <private/qapplication_p.h>
-#include <qwidget.h>
-#include <qapplication.h>
-#include <ctype.h>
-
-QT_BEGIN_NAMESPACE
-
-// Uncommend, to show debugging information for the keymapper
-//#define DEBUG_KEYMAPPER
-
-// Implemented elsewhere
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-extern Q_CORE_EXPORT QLocale qt_localeFromLCID(LCID id);
-#ifndef LANG_PASHTO
-#define LANG_PASHTO 0x63
-#endif
-#ifndef LANG_SYRIAC
-#define LANG_SYRIAC 0x5a
-#endif
-#ifndef LANG_DIVEHI
-#define LANG_DIVEHI 0x65
-#endif
-#ifndef VK_OEM_PLUS
-#define VK_OEM_PLUS 0xBB
-#endif
-#ifndef VK_OEM_3
-#define VK_OEM_3 0xC0
-#endif
-
-#if defined(Q_OS_WINCE)
-bool GetKeyboardState(unsigned char* kbuffer)
-{
- for (int i=0; i< 256; ++i)
- kbuffer[i] = GetAsyncKeyState(i);
- return true;
-}
-#endif
-// Key recorder ------------------------------------------------------------------------[ start ] --
-struct KeyRecord {
- KeyRecord(int c, int a, int s, const QString &t) : code(c), ascii(a), state(s), text(t) {}
- KeyRecord() {}
-
- int code;
- int ascii;
- int state;
- QString text;
-};
-
-static const int QT_MAX_KEY_RECORDINGS = 64; // User has LOTS of fingers...
-struct KeyRecorder
-{
- KeyRecorder() : nrecs(0) {}
-
- inline KeyRecord *findKey(int code, bool remove);
- inline void storeKey(int code, int ascii, int state, const QString& text);
- inline void clearKeys();
-
- int nrecs;
- KeyRecord deleted_record; // A copy of last entry removed from records[]
- KeyRecord records[QT_MAX_KEY_RECORDINGS];
-};
-static KeyRecorder key_recorder;
-
-KeyRecord *KeyRecorder::findKey(int code, bool remove)
-{
- KeyRecord *result = 0;
- for (int i = 0; i < nrecs; ++i) {
- if (records[i].code == code) {
- if (remove) {
- deleted_record = records[i];
- // Move rest down, and decrease count
- while (i + 1 < nrecs) {
- records[i] = records[i + 1];
- ++i;
- }
- --nrecs;
- result = &deleted_record;
- } else {
- result = &records[i];
- }
- break;
- }
- }
- return result;
-}
-
-void KeyRecorder::storeKey(int code, int ascii, int state, const QString& text)
-{
- Q_ASSERT_X(nrecs != QT_MAX_KEY_RECORDINGS,
- "Internal KeyRecorder",
- "Keyboard recorder buffer overflow, consider increasing QT_MAX_KEY_RECORDINGS");
-
- if (nrecs == QT_MAX_KEY_RECORDINGS) {
- qWarning("Qt: Internal keyboard buffer overflow");
- return;
- }
- records[nrecs++] = KeyRecord(code,ascii,state,text);
-}
-
-void KeyRecorder::clearKeys()
-{
- nrecs = 0;
-}
-// Key recorder --------------------------------------------------------------------------[ end ] --
-
-
-// Key translation ---------------------------------------------------------------------[ start ] --
-// Meaning of values:
-// 0 = Character output key, needs keyboard driver mapping
-// Key_unknown = Unknown Virtual Key, no translation possible, ignore
-static const uint KeyTbl[] = { // Keyboard mapping table
- // Dec | Hex | Windows Virtual key
- Qt::Key_unknown, // 0 0x00
- Qt::Key_unknown, // 1 0x01 VK_LBUTTON | Left mouse button
- Qt::Key_unknown, // 2 0x02 VK_RBUTTON | Right mouse button
- Qt::Key_Cancel, // 3 0x03 VK_CANCEL | Control-Break processing
- Qt::Key_unknown, // 4 0x04 VK_MBUTTON | Middle mouse button
- Qt::Key_unknown, // 5 0x05 VK_XBUTTON1 | X1 mouse button
- Qt::Key_unknown, // 6 0x06 VK_XBUTTON2 | X2 mouse button
- Qt::Key_unknown, // 7 0x07 -- unassigned --
- Qt::Key_Backspace, // 8 0x08 VK_BACK | BackSpace key
- Qt::Key_Tab, // 9 0x09 VK_TAB | Tab key
- Qt::Key_unknown, // 10 0x0A -- reserved --
- Qt::Key_unknown, // 11 0x0B -- reserved --
- Qt::Key_Clear, // 12 0x0C VK_CLEAR | Clear key
- Qt::Key_Return, // 13 0x0D VK_RETURN | Enter key
- Qt::Key_unknown, // 14 0x0E -- unassigned --
- Qt::Key_unknown, // 15 0x0F -- unassigned --
- Qt::Key_Shift, // 16 0x10 VK_SHIFT | Shift key
- Qt::Key_Control, // 17 0x11 VK_CONTROL | Ctrl key
- Qt::Key_Alt, // 18 0x12 VK_MENU | Alt key
- Qt::Key_Pause, // 19 0x13 VK_PAUSE | Pause key
- Qt::Key_CapsLock, // 20 0x14 VK_CAPITAL | Caps-Lock
- Qt::Key_unknown, // 21 0x15 VK_KANA / VK_HANGUL | IME Kana or Hangul mode
- Qt::Key_unknown, // 22 0x16 -- unassigned --
- Qt::Key_unknown, // 23 0x17 VK_JUNJA | IME Junja mode
- Qt::Key_unknown, // 24 0x18 VK_FINAL | IME final mode
- Qt::Key_unknown, // 25 0x19 VK_HANJA / VK_KANJI | IME Hanja or Kanji mode
- Qt::Key_unknown, // 26 0x1A -- unassigned --
- Qt::Key_Escape, // 27 0x1B VK_ESCAPE | Esc key
- Qt::Key_unknown, // 28 0x1C VK_CONVERT | IME convert
- Qt::Key_unknown, // 29 0x1D VK_NONCONVERT | IME non-convert
- Qt::Key_unknown, // 30 0x1E VK_ACCEPT | IME accept
- Qt::Key_Mode_switch,// 31 0x1F VK_MODECHANGE | IME mode change request
- Qt::Key_Space, // 32 0x20 VK_SPACE | Spacebar
- Qt::Key_PageUp, // 33 0x21 VK_PRIOR | Page Up key
- Qt::Key_PageDown, // 34 0x22 VK_NEXT | Page Down key
- Qt::Key_End, // 35 0x23 VK_END | End key
- Qt::Key_Home, // 36 0x24 VK_HOME | Home key
- Qt::Key_Left, // 37 0x25 VK_LEFT | Left arrow key
- Qt::Key_Up, // 38 0x26 VK_UP | Up arrow key
- Qt::Key_Right, // 39 0x27 VK_RIGHT | Right arrow key
- Qt::Key_Down, // 40 0x28 VK_DOWN | Down arrow key
- Qt::Key_Select, // 41 0x29 VK_SELECT | Select key
- Qt::Key_Printer, // 42 0x2A VK_PRINT | Print key
- Qt::Key_Execute, // 43 0x2B VK_EXECUTE | Execute key
- Qt::Key_Print, // 44 0x2C VK_SNAPSHOT | Print Screen key
- Qt::Key_Insert, // 45 0x2D VK_INSERT | Ins key
- Qt::Key_Delete, // 46 0x2E VK_DELETE | Del key
- Qt::Key_Help, // 47 0x2F VK_HELP | Help key
- 0, // 48 0x30 (VK_0) | 0 key
- 0, // 49 0x31 (VK_1) | 1 key
- 0, // 50 0x32 (VK_2) | 2 key
- 0, // 51 0x33 (VK_3) | 3 key
- 0, // 52 0x34 (VK_4) | 4 key
- 0, // 53 0x35 (VK_5) | 5 key
- 0, // 54 0x36 (VK_6) | 6 key
- 0, // 55 0x37 (VK_7) | 7 key
- 0, // 56 0x38 (VK_8) | 8 key
- 0, // 57 0x39 (VK_9) | 9 key
- Qt::Key_unknown, // 58 0x3A -- unassigned --
- Qt::Key_unknown, // 59 0x3B -- unassigned --
- Qt::Key_unknown, // 60 0x3C -- unassigned --
- Qt::Key_unknown, // 61 0x3D -- unassigned --
- Qt::Key_unknown, // 62 0x3E -- unassigned --
- Qt::Key_unknown, // 63 0x3F -- unassigned --
- Qt::Key_unknown, // 64 0x40 -- unassigned --
- 0, // 65 0x41 (VK_A) | A key
- 0, // 66 0x42 (VK_B) | B key
- 0, // 67 0x43 (VK_C) | C key
- 0, // 68 0x44 (VK_D) | D key
- 0, // 69 0x45 (VK_E) | E key
- 0, // 70 0x46 (VK_F) | F key
- 0, // 71 0x47 (VK_G) | G key
- 0, // 72 0x48 (VK_H) | H key
- 0, // 73 0x49 (VK_I) | I key
- 0, // 74 0x4A (VK_J) | J key
- 0, // 75 0x4B (VK_K) | K key
- 0, // 76 0x4C (VK_L) | L key
- 0, // 77 0x4D (VK_M) | M key
- 0, // 78 0x4E (VK_N) | N key
- 0, // 79 0x4F (VK_O) | O key
- 0, // 80 0x50 (VK_P) | P key
- 0, // 81 0x51 (VK_Q) | Q key
- 0, // 82 0x52 (VK_R) | R key
- 0, // 83 0x53 (VK_S) | S key
- 0, // 84 0x54 (VK_T) | T key
- 0, // 85 0x55 (VK_U) | U key
- 0, // 86 0x56 (VK_V) | V key
- 0, // 87 0x57 (VK_W) | W key
- 0, // 88 0x58 (VK_X) | X key
- 0, // 89 0x59 (VK_Y) | Y key
- 0, // 90 0x5A (VK_Z) | Z key
- Qt::Key_Meta, // 91 0x5B VK_LWIN | Left Windows - MS Natural kbd
- Qt::Key_Meta, // 92 0x5C VK_RWIN | Right Windows - MS Natural kbd
- Qt::Key_Menu, // 93 0x5D VK_APPS | Application key-MS Natural kbd
- Qt::Key_unknown, // 94 0x5E -- reserved --
- Qt::Key_Sleep, // 95 0x5F VK_SLEEP
- Qt::Key_0, // 96 0x60 VK_NUMPAD0 | Numeric keypad 0 key
- Qt::Key_1, // 97 0x61 VK_NUMPAD1 | Numeric keypad 1 key
- Qt::Key_2, // 98 0x62 VK_NUMPAD2 | Numeric keypad 2 key
- Qt::Key_3, // 99 0x63 VK_NUMPAD3 | Numeric keypad 3 key
- Qt::Key_4, // 100 0x64 VK_NUMPAD4 | Numeric keypad 4 key
- Qt::Key_5, // 101 0x65 VK_NUMPAD5 | Numeric keypad 5 key
- Qt::Key_6, // 102 0x66 VK_NUMPAD6 | Numeric keypad 6 key
- Qt::Key_7, // 103 0x67 VK_NUMPAD7 | Numeric keypad 7 key
- Qt::Key_8, // 104 0x68 VK_NUMPAD8 | Numeric keypad 8 key
- Qt::Key_9, // 105 0x69 VK_NUMPAD9 | Numeric keypad 9 key
- Qt::Key_Asterisk, // 106 0x6A VK_MULTIPLY | Multiply key
- Qt::Key_Plus, // 107 0x6B VK_ADD | Add key
- Qt::Key_Comma, // 108 0x6C VK_SEPARATOR | Separator key
- Qt::Key_Minus, // 109 0x6D VK_SUBTRACT | Subtract key
- Qt::Key_Period, // 110 0x6E VK_DECIMAL | Decimal key
- Qt::Key_Slash, // 111 0x6F VK_DIVIDE | Divide key
- Qt::Key_F1, // 112 0x70 VK_F1 | F1 key
- Qt::Key_F2, // 113 0x71 VK_F2 | F2 key
- Qt::Key_F3, // 114 0x72 VK_F3 | F3 key
- Qt::Key_F4, // 115 0x73 VK_F4 | F4 key
- Qt::Key_F5, // 116 0x74 VK_F5 | F5 key
- Qt::Key_F6, // 117 0x75 VK_F6 | F6 key
- Qt::Key_F7, // 118 0x76 VK_F7 | F7 key
- Qt::Key_F8, // 119 0x77 VK_F8 | F8 key
- Qt::Key_F9, // 120 0x78 VK_F9 | F9 key
- Qt::Key_F10, // 121 0x79 VK_F10 | F10 key
- Qt::Key_F11, // 122 0x7A VK_F11 | F11 key
- Qt::Key_F12, // 123 0x7B VK_F12 | F12 key
- Qt::Key_F13, // 124 0x7C VK_F13 | F13 key
- Qt::Key_F14, // 125 0x7D VK_F14 | F14 key
- Qt::Key_F15, // 126 0x7E VK_F15 | F15 key
- Qt::Key_F16, // 127 0x7F VK_F16 | F16 key
- Qt::Key_F17, // 128 0x80 VK_F17 | F17 key
- Qt::Key_F18, // 129 0x81 VK_F18 | F18 key
- Qt::Key_F19, // 130 0x82 VK_F19 | F19 key
- Qt::Key_F20, // 131 0x83 VK_F20 | F20 key
- Qt::Key_F21, // 132 0x84 VK_F21 | F21 key
- Qt::Key_F22, // 133 0x85 VK_F22 | F22 key
- Qt::Key_F23, // 134 0x86 VK_F23 | F23 key
- Qt::Key_F24, // 135 0x87 VK_F24 | F24 key
- Qt::Key_unknown, // 136 0x88 -- unassigned --
- Qt::Key_unknown, // 137 0x89 -- unassigned --
- Qt::Key_unknown, // 138 0x8A -- unassigned --
- Qt::Key_unknown, // 139 0x8B -- unassigned --
- Qt::Key_unknown, // 140 0x8C -- unassigned --
- Qt::Key_unknown, // 141 0x8D -- unassigned --
- Qt::Key_unknown, // 142 0x8E -- unassigned --
- Qt::Key_unknown, // 143 0x8F -- unassigned --
- Qt::Key_NumLock, // 144 0x90 VK_NUMLOCK | Num Lock key
- Qt::Key_ScrollLock, // 145 0x91 VK_SCROLL | Scroll Lock key
- // Fujitsu/OASYS kbd --------------------
- 0, //Qt::Key_Jisho, // 146 0x92 VK_OEM_FJ_JISHO | 'Dictionary' key /
- // VK_OEM_NEC_EQUAL = key on numpad on NEC PC-9800 kbd
- Qt::Key_Massyo, // 147 0x93 VK_OEM_FJ_MASSHOU | 'Unregister word' key
- Qt::Key_Touroku, // 148 0x94 VK_OEM_FJ_TOUROKU | 'Register word' key
- 0, //Qt::Key_Oyayubi_Left,//149 0x95 VK_OEM_FJ_LOYA | 'Left OYAYUBI' key
- 0, //Qt::Key_Oyayubi_Right,//150 0x96 VK_OEM_FJ_ROYA | 'Right OYAYUBI' key
- Qt::Key_unknown, // 151 0x97 -- unassigned --
- Qt::Key_unknown, // 152 0x98 -- unassigned --
- Qt::Key_unknown, // 153 0x99 -- unassigned --
- Qt::Key_unknown, // 154 0x9A -- unassigned --
- Qt::Key_unknown, // 155 0x9B -- unassigned --
- Qt::Key_unknown, // 156 0x9C -- unassigned --
- Qt::Key_unknown, // 157 0x9D -- unassigned --
- Qt::Key_unknown, // 158 0x9E -- unassigned --
- Qt::Key_unknown, // 159 0x9F -- unassigned --
- Qt::Key_Shift, // 160 0xA0 VK_LSHIFT | Left Shift key
- Qt::Key_Shift, // 161 0xA1 VK_RSHIFT | Right Shift key
- Qt::Key_Control, // 162 0xA2 VK_LCONTROL | Left Ctrl key
- Qt::Key_Control, // 163 0xA3 VK_RCONTROL | Right Ctrl key
- Qt::Key_Alt, // 164 0xA4 VK_LMENU | Left Menu key
- Qt::Key_Alt, // 165 0xA5 VK_RMENU | Right Menu key
- Qt::Key_Back, // 166 0xA6 VK_BROWSER_BACK | Browser Back key
- Qt::Key_Forward, // 167 0xA7 VK_BROWSER_FORWARD | Browser Forward key
- Qt::Key_Refresh, // 168 0xA8 VK_BROWSER_REFRESH | Browser Refresh key
- Qt::Key_Stop, // 169 0xA9 VK_BROWSER_STOP | Browser Stop key
- Qt::Key_Search, // 170 0xAA VK_BROWSER_SEARCH | Browser Search key
- Qt::Key_Favorites, // 171 0xAB VK_BROWSER_FAVORITES| Browser Favorites key
- Qt::Key_HomePage, // 172 0xAC VK_BROWSER_HOME | Browser Start and Home key
- Qt::Key_VolumeMute, // 173 0xAD VK_VOLUME_MUTE | Volume Mute key
- Qt::Key_VolumeDown, // 174 0xAE VK_VOLUME_DOWN | Volume Down key
- Qt::Key_VolumeUp, // 175 0xAF VK_VOLUME_UP | Volume Up key
- Qt::Key_MediaNext, // 176 0xB0 VK_MEDIA_NEXT_TRACK | Next Track key
- Qt::Key_MediaPrevious, //177 0xB1 VK_MEDIA_PREV_TRACK | Previous Track key
- Qt::Key_MediaStop, // 178 0xB2 VK_MEDIA_STOP | Stop Media key
- Qt::Key_MediaPlay, // 179 0xB3 VK_MEDIA_PLAY_PAUSE | Play/Pause Media key
- Qt::Key_LaunchMail, // 180 0xB4 VK_LAUNCH_MAIL | Start Mail key
- Qt::Key_LaunchMedia,// 181 0xB5 VK_LAUNCH_MEDIA_SELECT Select Media key
- Qt::Key_Launch0, // 182 0xB6 VK_LAUNCH_APP1 | Start Application 1 key
- Qt::Key_Launch1, // 183 0xB7 VK_LAUNCH_APP2 | Start Application 2 key
- Qt::Key_unknown, // 184 0xB8 -- reserved --
- Qt::Key_unknown, // 185 0xB9 -- reserved --
- 0, // 186 0xBA VK_OEM_1 | ';:' for US
- 0, // 187 0xBB VK_OEM_PLUS | '+' any country
- 0, // 188 0xBC VK_OEM_COMMA | ',' any country
- 0, // 189 0xBD VK_OEM_MINUS | '-' any country
- 0, // 190 0xBE VK_OEM_PERIOD | '.' any country
- 0, // 191 0xBF VK_OEM_2 | '/?' for US
- 0, // 192 0xC0 VK_OEM_3 | '`~' for US
- Qt::Key_unknown, // 193 0xC1 -- reserved --
- Qt::Key_unknown, // 194 0xC2 -- reserved --
- Qt::Key_unknown, // 195 0xC3 -- reserved --
- Qt::Key_unknown, // 196 0xC4 -- reserved --
- Qt::Key_unknown, // 197 0xC5 -- reserved --
- Qt::Key_unknown, // 198 0xC6 -- reserved --
- Qt::Key_unknown, // 199 0xC7 -- reserved --
- Qt::Key_unknown, // 200 0xC8 -- reserved --
- Qt::Key_unknown, // 201 0xC9 -- reserved --
- Qt::Key_unknown, // 202 0xCA -- reserved --
- Qt::Key_unknown, // 203 0xCB -- reserved --
- Qt::Key_unknown, // 204 0xCC -- reserved --
- Qt::Key_unknown, // 205 0xCD -- reserved --
- Qt::Key_unknown, // 206 0xCE -- reserved --
- Qt::Key_unknown, // 207 0xCF -- reserved --
- Qt::Key_unknown, // 208 0xD0 -- reserved --
- Qt::Key_unknown, // 209 0xD1 -- reserved --
- Qt::Key_unknown, // 210 0xD2 -- reserved --
- Qt::Key_unknown, // 211 0xD3 -- reserved --
- Qt::Key_unknown, // 212 0xD4 -- reserved --
- Qt::Key_unknown, // 213 0xD5 -- reserved --
- Qt::Key_unknown, // 214 0xD6 -- reserved --
- Qt::Key_unknown, // 215 0xD7 -- reserved --
- Qt::Key_unknown, // 216 0xD8 -- unassigned --
- Qt::Key_unknown, // 217 0xD9 -- unassigned --
- Qt::Key_unknown, // 218 0xDA -- unassigned --
- 0, // 219 0xDB VK_OEM_4 | '[{' for US
- 0, // 220 0xDC VK_OEM_5 | '\|' for US
- 0, // 221 0xDD VK_OEM_6 | ']}' for US
- 0, // 222 0xDE VK_OEM_7 | ''"' for US
- 0, // 223 0xDF VK_OEM_8
- Qt::Key_unknown, // 224 0xE0 -- reserved --
- Qt::Key_unknown, // 225 0xE1 VK_OEM_AX | 'AX' key on Japanese AX kbd
- Qt::Key_unknown, // 226 0xE2 VK_OEM_102 | "<>" or "\|" on RT 102-key kbd
- Qt::Key_unknown, // 227 0xE3 VK_ICO_HELP | Help key on ICO
- Qt::Key_unknown, // 228 0xE4 VK_ICO_00 | 00 key on ICO
- Qt::Key_unknown, // 229 0xE5 VK_PROCESSKEY | IME Process key
- Qt::Key_unknown, // 230 0xE6 VK_ICO_CLEAR |
- Qt::Key_unknown, // 231 0xE7 VK_PACKET | Unicode char as keystrokes
- Qt::Key_unknown, // 232 0xE8 -- unassigned --
- // Nokia/Ericsson definitions ---------------
- Qt::Key_unknown, // 233 0xE9 VK_OEM_RESET
- Qt::Key_unknown, // 234 0xEA VK_OEM_JUMP
- Qt::Key_unknown, // 235 0xEB VK_OEM_PA1
- Qt::Key_unknown, // 236 0xEC VK_OEM_PA2
- Qt::Key_unknown, // 237 0xED VK_OEM_PA3
- Qt::Key_unknown, // 238 0xEE VK_OEM_WSCTRL
- Qt::Key_unknown, // 239 0xEF VK_OEM_CUSEL
- Qt::Key_unknown, // 240 0xF0 VK_OEM_ATTN
- Qt::Key_unknown, // 241 0xF1 VK_OEM_FINISH
- Qt::Key_unknown, // 242 0xF2 VK_OEM_COPY
- Qt::Key_unknown, // 243 0xF3 VK_OEM_AUTO
- Qt::Key_unknown, // 244 0xF4 VK_OEM_ENLW
- Qt::Key_unknown, // 245 0xF5 VK_OEM_BACKTAB
- Qt::Key_unknown, // 246 0xF6 VK_ATTN | Attn key
- Qt::Key_unknown, // 247 0xF7 VK_CRSEL | CrSel key
- Qt::Key_unknown, // 248 0xF8 VK_EXSEL | ExSel key
- Qt::Key_unknown, // 249 0xF9 VK_EREOF | Erase EOF key
- Qt::Key_Play, // 250 0xFA VK_PLAY | Play key
- Qt::Key_Zoom, // 251 0xFB VK_ZOOM | Zoom key
- Qt::Key_unknown, // 252 0xFC VK_NONAME | Reserved
- Qt::Key_unknown, // 253 0xFD VK_PA1 | PA1 key
- Qt::Key_Clear, // 254 0xFE VK_OEM_CLEAR | Clear key
- 0
-};
-
-// Possible modifier states.
-// NOTE: The order of these states match the order in QKeyMapperPrivate::updatePossibleKeyCodes()!
-static const Qt::KeyboardModifiers ModsTbl[] = {
- Qt::NoModifier, // 0
- Qt::ShiftModifier, // 1
- Qt::ControlModifier, // 2
- Qt::ControlModifier | Qt::ShiftModifier, // 3
- Qt::AltModifier, // 4
- Qt::AltModifier | Qt::ShiftModifier, // 5
- Qt::AltModifier | Qt::ControlModifier, // 6
- Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier, // 7
- Qt::NoModifier, // Fall-back to raw Key_*
-};
-
-/**
- Remap return or action key to select key for windows mobile.
-*/
-inline int winceKeyBend(int keyCode)
-{
-#if defined(Q_OS_WINCE_WM) && defined(QT_KEYPAD_NAVIGATION)
- // remap return or action key to select key for windows mobile.
- // will be changed to a table remapping function in the next version (4.6/7).
- if (keyCode == VK_RETURN && QApplication::keypadNavigationEnabled())
- return Qt::Key_Select;
- else
- return KeyTbl[keyCode];
-#else
- return KeyTbl[keyCode];
-#endif
-}
-
-#if defined(Q_OS_WINCE)
- // Use the KeyTbl to resolve a Qt::Key out of the virtual keys.
- // In case it is not resolvable, continue using the virtual key itself.
-
-QT_BEGIN_INCLUDE_NAMESPACE
-
-int ToUnicode(UINT vk, int /*scancode*/, unsigned char* /*kbdBuffer*/, LPWSTR unicodeBuffer, int, int)
-{
- QT_USE_NAMESPACE
- QChar* buf = reinterpret_cast< QChar*>(unicodeBuffer);
- if (KeyTbl[vk] == 0) {
- buf[0] = vk;
- return 1;
- }
- return 0;
-}
-
-int ToAscii(UINT vk, int scancode, unsigned char *kbdBuffer, LPWORD unicodeBuffer, int flag)
-{
- return ToUnicode(vk, scancode, kbdBuffer, (LPWSTR) unicodeBuffer, 0, flag);
-
-}
-QT_END_INCLUDE_NAMESPACE
-
-#endif
-
-// Translate a VK into a Qt key code, or unicode character
-static inline int toKeyOrUnicode(int vk, int scancode, unsigned char *kbdBuffer, bool *isDeadkey = 0)
-{
- Q_ASSERT(vk > 0 && vk < 256);
- int code = 0;
- QChar unicodeBuffer[5];
- int res = ToUnicode(vk, scancode, kbdBuffer, reinterpret_cast<LPWSTR>(unicodeBuffer), 5, 0);
- if (res)
- code = unicodeBuffer[0].toUpper().unicode();
-
- // Qt::Key_*'s are not encoded below 0x20, so try again, and DEL keys (0x7f) is encoded with a
- // proper Qt::Key_ code
- if (code < 0x20 || code == 0x7f) // Handles res==0 too
- code = winceKeyBend(vk);
-
- if (isDeadkey)
- *isDeadkey = (res == -1);
-
- return code == Qt::Key_unknown ? 0 : code;
-}
-
-Q_GUI_EXPORT int qt_translateKeyCode(int vk)
-{
- int code = winceKeyBend((vk < 0 || vk > 255) ? 0 : vk);
- return code == Qt::Key_unknown ? 0 : code;
-}
-
-static inline int asciiToKeycode(char a, int state)
-{
- if (a >= 'a' && a <= 'z')
- a = toupper(a);
- if ((state & Qt::ControlModifier) != 0) {
- if (a >= 0 && a <= 31) // Ctrl+@..Ctrl+A..CTRL+Z..Ctrl+_
- a += '@'; // to @..A..Z.._
- }
- return a & 0xff;
-}
-
-static inline bool isModifierKey(int code)
-{
- return (code >= Qt::Key_Shift) && (code <= Qt::Key_ScrollLock);
-}
-// Key translation -----------------------------------------------------------------------[ end ]---
-
-
-static void qt_show_system_menu(QWidget* tlw)
-{
- Q_ASSERT(tlw->testAttribute(Qt::WA_WState_Created));
- HMENU menu = GetSystemMenu(tlw->internalWinId(), FALSE);
- if (!menu)
- return; // no menu for this window
-
-#define enabled (MF_BYCOMMAND | MF_ENABLED)
-#define disabled (MF_BYCOMMAND | MF_GRAYED)
-
-#ifndef Q_OS_WINCE
- EnableMenuItem(menu, SC_MINIMIZE, (tlw->windowFlags() & Qt::WindowMinimizeButtonHint)?enabled:disabled);
- bool maximized = IsZoomed(tlw->internalWinId());
-
- EnableMenuItem(menu, SC_MAXIMIZE, ! (tlw->windowFlags() & Qt::WindowMaximizeButtonHint) || maximized?disabled:enabled);
- EnableMenuItem(menu, SC_RESTORE, maximized?enabled:disabled);
-
- // We should _not_ check with the setFixedSize(x,y) case here, since Windows is not able to check
- // this and our menu here would be out-of-sync with the menu produced by mouse-click on the
- // System Menu, or right-click on the title bar.
- EnableMenuItem(menu, SC_SIZE, (tlw->windowFlags() & Qt::MSWindowsFixedSizeDialogHint) || maximized?disabled:enabled);
- EnableMenuItem(menu, SC_MOVE, maximized?disabled:enabled);
- EnableMenuItem(menu, SC_CLOSE, enabled);
- // Set bold on close menu item
- MENUITEMINFO closeItem;
- closeItem.cbSize = sizeof(MENUITEMINFO);
- closeItem.fMask = MIIM_STATE;
- closeItem.fState = MFS_DEFAULT;
- SetMenuItemInfo(menu, SC_CLOSE, FALSE, &closeItem);
-#endif
-
-#undef enabled
-#undef disabled
- int ret = TrackPopupMenuEx(menu,
- TPM_LEFTALIGN | TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
- tlw->geometry().x(), tlw->geometry().y(),
- tlw->internalWinId(),
- 0);
- if (ret)
- QtWndProc(tlw->internalWinId(), WM_SYSCOMMAND, ret, 0);
-}
-
-
-// QETWidget class is only for accessing the sendSpontaneousEvent function in QApplication
-class QETWidget : public QWidget {
-public:
- static bool sendSpontaneousEvent(QObject *r, QEvent *e)
- { return QApplication::sendSpontaneousEvent(r, e); }
-};
-
-
-// Keyboard map private ----------------------------------------------------------------[ start ]---
-
-/*
- \internal
- A Windows KeyboardLayoutItem has 8 possible states:
- 1. Unmodified
- 2. Shift
- 3. Control
- 4. Control + Shift
- 5. Alt
- 6. Alt + Shift
- 7. Alt + Control
- 8. Alt + Control + Shift
-*/
-struct KeyboardLayoutItem {
- bool dirty;
- quint8 deadkeys;
- quint32 qtKey[9]; // Can by any Qt::Key_<foo>, or unicode character
-};
-
-QKeyMapperPrivate::QKeyMapperPrivate()
-{
- memset(keyLayout, 0, sizeof(keyLayout));
-}
-
-QKeyMapperPrivate::~QKeyMapperPrivate()
-{
- deleteLayouts();
-}
-
-void QKeyMapperPrivate::deleteLayouts()
-{
- for (int i = 0; i < 255; ++i) {
- if (keyLayout[i]) {
- delete keyLayout[i];
- keyLayout[i] = 0;
- }
- }
-}
-
-void QKeyMapperPrivate::clearMappings()
-{
- deleteLayouts();
-
- /* MAKELCID()'s first argument is a WORD, and GetKeyboardLayout()
- * returns a DWORD. */
-
- LCID newLCID = MAKELCID((quintptr)GetKeyboardLayout(0), SORT_DEFAULT);
-// keyboardInputLocale = qt_localeFromLCID(newLCID);
-
- bool bidi = false;
- wchar_t LCIDFontSig[16];
- if (GetLocaleInfo(newLCID, LOCALE_FONTSIGNATURE, LCIDFontSig, sizeof(LCIDFontSig) / sizeof(wchar_t))
- && (LCIDFontSig[7] & (wchar_t)0x0800))
- bidi = true;
-
- keyboardInputDirection = bidi ? Qt::RightToLeft : Qt::LeftToRight;
-}
-
-void QKeyMapperPrivate::clearRecordedKeys()
-{
- key_recorder.clearKeys();
-}
-
-
-inline void setKbdState(unsigned char *kbd, bool shift, bool ctrl, bool alt)
-{
- kbd[VK_LSHIFT ] = (shift ? 0x80 : 0);
- kbd[VK_SHIFT ] = (shift ? 0x80 : 0);
- kbd[VK_LCONTROL] = (ctrl ? 0x80 : 0);
- kbd[VK_CONTROL ] = (ctrl ? 0x80 : 0);
- kbd[VK_RMENU ] = (alt ? 0x80 : 0);
- kbd[VK_MENU ] = (alt ? 0x80 : 0);
-}
-
-void QKeyMapperPrivate::updateKeyMap(const MSG &msg)
-{
- unsigned char kbdBuffer[256]; // Will hold the complete keyboard state
- GetKeyboardState(kbdBuffer);
- quint32 scancode = (msg.lParam >> 16) & 0xfff;
- updatePossibleKeyCodes(kbdBuffer, scancode, msg.wParam);
-}
-
-void QKeyMapperPrivate::updatePossibleKeyCodes(unsigned char *kbdBuffer, quint32 scancode,
- quint32 vk_key)
-{
- if (!vk_key || (keyLayout[vk_key] && !keyLayout[vk_key]->dirty))
- return;
-
- if (!keyLayout[vk_key])
- keyLayout[vk_key] = new KeyboardLayoutItem;
-
- // Copy keyboard state, so we can modify and query output for each possible permutation
- unsigned char buffer[256];
- memcpy(buffer, kbdBuffer, sizeof(buffer));
- // Always 0, as Windows doesn't treat these as modifiers;
- buffer[VK_LWIN ] = 0;
- buffer[VK_RWIN ] = 0;
- buffer[VK_CAPITAL ] = 0;
- buffer[VK_NUMLOCK ] = 0;
- buffer[VK_SCROLL ] = 0;
- // Always 0, since we'll only change the other versions
- buffer[VK_RSHIFT ] = 0;
- buffer[VK_RCONTROL] = 0;
- buffer[VK_LMENU ] = 0; // Use right Alt, since left Ctrl + right Alt is considered AltGraph
-
- bool isDeadKey = false;
- keyLayout[vk_key]->deadkeys = 0;
- keyLayout[vk_key]->dirty = false;
- setKbdState(buffer, false, false, false);
- keyLayout[vk_key]->qtKey[0] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x01 : 0;
- setKbdState(buffer, true, false, false);
- keyLayout[vk_key]->qtKey[1] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x02 : 0;
- setKbdState(buffer, false, true, false);
- keyLayout[vk_key]->qtKey[2] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x04 : 0;
- setKbdState(buffer, true, true, false);
- keyLayout[vk_key]->qtKey[3] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x08 : 0;
- setKbdState(buffer, false, false, true);
- keyLayout[vk_key]->qtKey[4] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x10 : 0;
- setKbdState(buffer, true, false, true);
- keyLayout[vk_key]->qtKey[5] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x20 : 0;
- setKbdState(buffer, false, true, true);
- keyLayout[vk_key]->qtKey[6] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x40 : 0;
- setKbdState(buffer, true, true, true);
- keyLayout[vk_key]->qtKey[7] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
- keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x80 : 0;
- // Add a fall back key for layouts which don't do composition and show non-latin1 characters
- int fallbackKey = winceKeyBend(vk_key);
- if (!fallbackKey || fallbackKey == Qt::Key_unknown) {
- fallbackKey = 0;
- if (vk_key != keyLayout[vk_key]->qtKey[0] && vk_key < 0x5B && vk_key > 0x2F)
- fallbackKey = vk_key;
- }
- keyLayout[vk_key]->qtKey[8] = fallbackKey;
-
- // If this vk_key a Dead Key
- if (MapVirtualKey(vk_key, 2) & 0x80000000) {
- // Push a Space, then the original key through the low-level ToAscii functions.
- // We do this because these functions (ToAscii / ToUnicode) will alter the internal state of
- // the keyboard driver By doing the following, we set the keyboard driver state back to what
- // it was before we wrecked it with the code above.
- // We need to push the space with an empty keystate map, since the driver checks the map for
- // transitions in modifiers, so this helps us capture all possible deadkeys.
- unsigned char emptyBuffer[256];
- memset(emptyBuffer, 0, sizeof(emptyBuffer));
- ::ToAscii(VK_SPACE, 0, emptyBuffer, reinterpret_cast<LPWORD>(&buffer), 0);
- ::ToAscii(vk_key, scancode, kbdBuffer, reinterpret_cast<LPWORD>(&buffer), 0);
- }
-
-#ifdef DEBUG_KEYMAPPER
- qDebug("updatePossibleKeyCodes for virtual key = 0x%02x!", vk_key);
- for (int i = 0; i < 9; ++i) {
- qDebug(" [%d] (%d,0x%02x,'%c') %s", i,
- keyLayout[vk_key]->qtKey[i],
- keyLayout[vk_key]->qtKey[i],
- keyLayout[vk_key]->qtKey[i] ? keyLayout[vk_key]->qtKey[i] : 0x03,
- keyLayout[vk_key]->deadkeys & (1<<i) ? "deadkey" : "");
- }
-#endif // DEBUG_KEYMAPPER
-}
-
-bool QKeyMapperPrivate::isADeadKey(unsigned int vk_key, unsigned int modifiers)
-{
- if (keyLayout && (vk_key < 256) && keyLayout[vk_key]) {
- for(register int i = 0; i < 9; ++i) {
- if (uint(ModsTbl[i]) == modifiers)
- return bool(keyLayout[vk_key]->deadkeys & 1<<i);
- }
- }
- return false;
-}
-
-extern bool qt_use_rtl_extensions;
-
-QList<int> QKeyMapperPrivate::possibleKeys(QKeyEvent *e)
-{
- QList<int> result;
-
- KeyboardLayoutItem *kbItem = keyLayout[e->nativeVirtualKey()];
- if(!kbItem)
- return result;
-
- quint32 baseKey = kbItem->qtKey[0];
- Qt::KeyboardModifiers keyMods = e->modifiers();
- if (baseKey == Qt::Key_Return && (e->nativeModifiers() & ExtendedKey)) {
- result << int(Qt::Key_Enter + keyMods);
- return result;
- }
- result << int(baseKey + keyMods); // The base key is _always_ valid, of course
-
- for(int i = 1; i < 9; ++i) {
- Qt::KeyboardModifiers neededMods = ModsTbl[i];
- quint32 key = kbItem->qtKey[i];
- if (key && key != baseKey && ((keyMods & neededMods) == neededMods))
- result << int(key + (keyMods & ~neededMods));
- }
-
- return result;
-}
-
-bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool grab)
-{
- Q_Q(QKeyMapper);
- Q_UNUSED(q); // Strange, but the compiler complains on q not being referenced, even if it is..
- bool k0 = false;
- bool k1 = false;
- int msgType = msg.message;
-
- quint32 scancode = (msg.lParam >> 16) & 0xfff;
- quint32 vk_key = MapVirtualKey(scancode, 1);
- bool isNumpad = (msg.wParam >= VK_NUMPAD0 && msg.wParam <= VK_NUMPAD9);
- quint32 nModifiers = 0;
-
-#if defined(Q_OS_WINCE)
- nModifiers |= (GetKeyState(VK_SHIFT ) < 0 ? ShiftAny : 0);
- nModifiers |= (GetKeyState(VK_CONTROL) < 0 ? ControlAny : 0);
- nModifiers |= (GetKeyState(VK_MENU ) < 0 ? AltAny : 0);
- nModifiers |= (GetKeyState(VK_LWIN ) < 0 ? MetaLeft : 0);
- nModifiers |= (GetKeyState(VK_RWIN ) < 0 ? MetaRight : 0);
-#else
- // Map native modifiers to some bit representation
- nModifiers |= (GetKeyState(VK_LSHIFT ) & 0x80 ? ShiftLeft : 0);
- nModifiers |= (GetKeyState(VK_RSHIFT ) & 0x80 ? ShiftRight : 0);
- nModifiers |= (GetKeyState(VK_LCONTROL) & 0x80 ? ControlLeft : 0);
- nModifiers |= (GetKeyState(VK_RCONTROL) & 0x80 ? ControlRight : 0);
- nModifiers |= (GetKeyState(VK_LMENU ) & 0x80 ? AltLeft : 0);
- nModifiers |= (GetKeyState(VK_RMENU ) & 0x80 ? AltRight : 0);
- nModifiers |= (GetKeyState(VK_LWIN ) & 0x80 ? MetaLeft : 0);
- nModifiers |= (GetKeyState(VK_RWIN ) & 0x80 ? MetaRight : 0);
- // Add Lock keys to the same bits
- nModifiers |= (GetKeyState(VK_CAPITAL ) & 0x01 ? CapsLock : 0);
- nModifiers |= (GetKeyState(VK_NUMLOCK ) & 0x01 ? NumLock : 0);
- nModifiers |= (GetKeyState(VK_SCROLL ) & 0x01 ? ScrollLock : 0);
-#endif // Q_OS_WINCE
-
- if (msg.lParam & ExtendedKey)
- nModifiers |= msg.lParam & ExtendedKey;
-
- // Get the modifier states (may be altered later, depending on key code)
- int state = 0;
- state |= (nModifiers & ShiftAny ? Qt::ShiftModifier : 0);
- state |= (nModifiers & ControlAny ? Qt::ControlModifier : 0);
- state |= (nModifiers & AltAny ? Qt::AltModifier : 0);
- state |= (nModifiers & MetaAny ? Qt::MetaModifier : 0);
-
- // Now we know enough to either have MapVirtualKey or our own keymap tell us if it's a deadkey
- bool isDeadKey = isADeadKey(msg.wParam, state)
- || MapVirtualKey(msg.wParam, 2) & 0x80000000;
-
- // A multi-character key not found by our look-ahead
- if (msgType == WM_CHAR) {
- QString s;
- QChar ch = QChar((ushort)msg.wParam);
- if (!ch.isNull())
- s += ch;
-
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
- k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
- }
-
- // Input method characters not found by our look-ahead
- else if (msgType == WM_IME_CHAR) {
- QString s;
- QChar ch = QChar((ushort)msg.wParam);
- if (!ch.isNull())
- s += ch;
-
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
- k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
- }
-
- else {
- // handle Directionality changes (BiDi) with RTL extensions
- if (qt_use_rtl_extensions) {
- static int dirStatus = 0;
- if (!dirStatus && state == Qt::ControlModifier
- && msg.wParam == VK_CONTROL
- && msgType == WM_KEYDOWN) {
- if (GetKeyState(VK_LCONTROL) < 0)
- dirStatus = VK_LCONTROL;
- else if (GetKeyState(VK_RCONTROL) < 0)
- dirStatus = VK_RCONTROL;
- } else if (dirStatus) {
- if (msgType == WM_KEYDOWN) {
- if (msg.wParam == VK_SHIFT) {
- if (dirStatus == VK_LCONTROL && GetKeyState(VK_LSHIFT) < 0)
- dirStatus = VK_LSHIFT;
- else if (dirStatus == VK_RCONTROL && GetKeyState(VK_RSHIFT) < 0)
- dirStatus = VK_RSHIFT;
- } else {
- dirStatus = 0;
- }
- } else if (msgType == WM_KEYUP) {
- if (dirStatus == VK_LSHIFT
- && ((msg.wParam == VK_SHIFT && GetKeyState(VK_LCONTROL))
- || (msg.wParam == VK_CONTROL && GetKeyState(VK_LSHIFT)))) {
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, Qt::Key_Direction_L, 0,
- QString(), false, 0,
- scancode, msg.wParam, nModifiers);
- k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, Qt::Key_Direction_L, 0,
- QString(), false, 0,
- scancode, msg.wParam, nModifiers);
- dirStatus = 0;
- } else if (dirStatus == VK_RSHIFT
- && ( (msg.wParam == VK_SHIFT && GetKeyState(VK_RCONTROL))
- || (msg.wParam == VK_CONTROL && GetKeyState(VK_RSHIFT)))) {
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, Qt::Key_Direction_R,
- 0, QString(), false, 0,
- scancode, msg.wParam, nModifiers);
- k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, Qt::Key_Direction_R,
- 0, QString(), false, 0,
- scancode, msg.wParam, nModifiers);
- dirStatus = 0;
- } else {
- dirStatus = 0;
- }
- } else {
- dirStatus = 0;
- }
- }
- }
-
- // IME will process these keys, so simply return
- if(msg.wParam == VK_PROCESSKEY)
- return true;
-
- // Ignore invalid virtual keycodes (see bugs 127424, QTBUG-3630)
- if (msg.wParam == 0 || msg.wParam == 0xFF)
- return true;
-
- // Translate VK_* (native) -> Key_* (Qt) keys
- // If it's a dead key, we cannot use the toKeyOrUnicode() function, since that will change
- // the internal state of the keyboard driver, resulting in that dead keys no longer works.
- // ..also if we're typing numbers on the keypad, while holding down the Alt modifier.
- int code = 0;
- if (isNumpad && (nModifiers & AltAny)) {
- code = winceKeyBend(msg.wParam);
- } else if (!isDeadKey) {
- unsigned char kbdBuffer[256]; // Will hold the complete keyboard state
- GetKeyboardState(kbdBuffer);
- code = toKeyOrUnicode(msg.wParam, scancode, kbdBuffer);
- }
-
- // Invert state logic:
- // If the key actually pressed is a modifier key, then we remove its modifier key from the
- // state, since a modifier-key can't have itself as a modifier
- if (code == Qt::Key_Control)
- state = state ^ Qt::ControlModifier;
- else if (code == Qt::Key_Shift)
- state = state ^ Qt::ShiftModifier;
- else if (code == Qt::Key_Alt)
- state = state ^ Qt::AltModifier;
-
- // If the bit 24 of lParm is set you received a enter,
- // otherwise a Return. (This is the extended key bit)
- if ((code == Qt::Key_Return) && (msg.lParam & 0x1000000))
- code = Qt::Key_Enter;
-
- // All cursor keys without extended bit
- if (!(msg.lParam & 0x1000000)) {
- switch (code) {
- case Qt::Key_Left:
- case Qt::Key_Right:
- case Qt::Key_Up:
- case Qt::Key_Down:
- case Qt::Key_PageUp:
- case Qt::Key_PageDown:
- case Qt::Key_Home:
- case Qt::Key_End:
- case Qt::Key_Insert:
- case Qt::Key_Delete:
- case Qt::Key_Asterisk:
- case Qt::Key_Plus:
- case Qt::Key_Minus:
- case Qt::Key_Period:
- case Qt::Key_0:
- case Qt::Key_1:
- case Qt::Key_2:
- case Qt::Key_3:
- case Qt::Key_4:
- case Qt::Key_5:
- case Qt::Key_6:
- case Qt::Key_7:
- case Qt::Key_8:
- case Qt::Key_9:
- state |= ((msg.wParam >= '0' && msg.wParam <= '9')
- || (msg.wParam >= VK_OEM_PLUS && msg.wParam <= VK_OEM_3))
- ? 0 : Qt::KeypadModifier;
- default:
- if ((uint)msg.lParam == 0x004c0001 || (uint)msg.lParam == 0xc04c0001)
- state |= Qt::KeypadModifier;
- break;
- }
- }
- // Other keys with with extended bit
- else {
- switch (code) {
- case Qt::Key_Enter:
- case Qt::Key_Slash:
- case Qt::Key_NumLock:
- state |= Qt::KeypadModifier;
- default:
- break;
- }
- }
-
- // KEYDOWN ---------------------------------------------------------------------------------
- if (msgType == WM_KEYDOWN || msgType == WM_IME_KEYDOWN || msgType == WM_SYSKEYDOWN) {
- // Get the last record of this key press, so we can validate the current state
- // The record is not removed from the list
- KeyRecord *rec = key_recorder.findKey(msg.wParam, false);
-
- // If rec's state doesn't match the current state, something has changed behind our back
- // (Consumed by modal widget is one possibility) So, remove the record from the list
- // This will stop the auto-repeat of the key, should a modifier change, for example
- if (rec && rec->state != state) {
- key_recorder.findKey(msg.wParam, true);
- rec = 0;
- }
-
- // Find unicode character from Windows Message Queue
- MSG wm_char;
- UINT charType = (msgType == WM_KEYDOWN
- ? WM_CHAR
- : msgType == WM_IME_KEYDOWN ? WM_IME_CHAR : WM_SYSCHAR);
-
- QChar uch;
- if (PeekMessage(&wm_char, 0, charType, charType, PM_REMOVE)) {
- // Found a ?_CHAR
- uch = QChar((ushort)wm_char.wParam);
- if (msgType == WM_SYSKEYDOWN && uch.isLetter() && (msg.lParam & KF_ALTDOWN))
- uch = uch.toLower(); // (See doc of WM_SYSCHAR) Alt-letter
- if (!code && !uch.row())
- code = asciiToKeycode(uch.cell(), state);
- }
-
- // Special handling for the WM_IME_KEYDOWN message. Microsoft IME (Korean) will not
- // generate a WM_IME_CHAR message corresponding to this message. We might get wrong
- // results, if we map this virtual key-code directly (for eg '?' US layouts). So try
- // to find the correct key using the current message parameters & keyboard state.
- if (uch.isNull() && msgType == WM_IME_KEYDOWN) {
- BYTE keyState[256];
- wchar_t newKey[3] = {0};
- GetKeyboardState(keyState);
- int val = ToUnicode(vk_key, scancode, keyState, newKey, 2, 0);
- if (val == 1) {
- uch = QChar(newKey[0]);
- } else {
- // If we are still not able to find a unicode key, pass the WM_IME_KEYDOWN
- // message to DefWindowProc() for generating a proper WM_KEYDOWN.
- return false;
- }
- }
-
- // If no ?_CHAR was found in the queue; deduct character from the ?_KEYDOWN parameters
- if (uch.isNull()) {
- if (msg.wParam == VK_DELETE) {
- uch = QChar(QLatin1Char(0x7f)); // Windows doesn't know this one.
- } else {
- if (msgType != WM_SYSKEYDOWN || !code) {
- UINT map = MapVirtualKey(msg.wParam, 2);
- // If the high bit of the return value is set, it's a deadkey
- if (!(map & 0x80000000))
- uch = QChar((ushort)map);
- }
- }
- if (!code && !uch.row())
- code = asciiToKeycode(uch.cell(), state);
- }
-
- // Special handling of global Windows hotkeys
- if (state == Qt::AltModifier) {
- switch (code) {
- case Qt::Key_Escape:
- case Qt::Key_Tab:
- case Qt::Key_Enter:
- case Qt::Key_F4:
- return false; // Send the event on to Windows
- case Qt::Key_Space:
- // do not pass this key to windows, we will process it ourselves
- qt_show_system_menu(widget->window());
- return true;
- default:
- break;
- }
- }
-
- // Map SHIFT + Tab to SHIFT + BackTab, QShortcutMap knows about this translation
- if (code == Qt::Key_Tab && (state & Qt::ShiftModifier) == Qt::ShiftModifier)
- code = Qt::Key_Backtab;
-
- // If we have a record, it means that the key is already pressed, the state is the same
- // so, we have an auto-repeating key
- if (rec) {
- if (code < Qt::Key_Shift || code > Qt::Key_ScrollLock) {
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, code,
- Qt::KeyboardModifier(state), rec->text, true, 0,
- scancode, msg.wParam, nModifiers);
- k1 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, code,
- Qt::KeyboardModifier(state), rec->text, true, 0,
- scancode, msg.wParam, nModifiers);
- }
- }
- // No record of the key being previous pressed, so we now send a QEvent::KeyPress event,
- // and store the key data into our records.
- else {
- QString text;
- if (!uch.isNull())
- text += uch;
- char a = uch.row() ? 0 : uch.cell();
- key_recorder.storeKey(msg.wParam, a, state, text);
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, code, Qt::KeyboardModifier(state),
- text, false, 0, scancode, msg.wParam, nModifiers);
-
- bool store = true;
- // Alt+<alphanumerical> go to the Win32 menu system if unhandled by Qt
-#if !defined(Q_OS_WINCE)
- if (msgType == WM_SYSKEYDOWN && !k0 && a) {
- HWND parent = GetParent(widget->internalWinId());
- while (parent) {
- if (GetMenu(parent)) {
- SendMessage(parent, WM_SYSCOMMAND, SC_KEYMENU, a);
- store = false;
- k0 = true;
- break;
- }
- parent = GetParent(parent);
- }
- }
-#endif
- if (!store)
- key_recorder.findKey(msg.wParam, true);
- }
- }
-
- // KEYUP -----------------------------------------------------------------------------------
- else {
- // Try to locate the key in our records, and remove it if it exists.
- // The key may not be in our records if, for example, the down event was handled by
- // win32 natively, or our window gets focus while a key is already press, but now gets
- // the key release event.
- KeyRecord* rec = key_recorder.findKey(msg.wParam, true);
- if (!rec && !(code == Qt::Key_Shift
- || code == Qt::Key_Control
- || code == Qt::Key_Meta
- || code == Qt::Key_Alt)) {
- // Someone ate the key down event
- } else {
- if (!code)
- code = asciiToKeycode(rec->ascii ? rec->ascii : msg.wParam, state);
-
- // Map SHIFT + Tab to SHIFT + BackTab, QShortcutMap knows about this translation
- if (code == Qt::Key_Tab && (state & Qt::ShiftModifier) == Qt::ShiftModifier)
- code = Qt::Key_Backtab;
-
- k0 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, code, Qt::KeyboardModifier(state),
- (rec ? rec->text : QString()), false, 0, scancode, msg.wParam, nModifiers);
-
- // don't pass Alt to Windows unless we are embedded in a non-Qt window
-#if !defined(Q_OS_WINCE)
- if (code == Qt::Key_Alt) {
- k0 = true;
- HWND parent = GetParent(widget->internalWinId());
- while (parent) {
- if (!QWidget::find(parent) && GetMenu(parent)) {
- k0 = false;
- break;
- }
- parent = GetParent(parent);
- }
- }
-#endif
- }
- }
- }
-
- // Return true, if a QKeyEvent was sent to a widget
- return k0 || k1;
-}
-
-
-// QKeyMapper (Windows) implementation -------------------------------------------------[ start ]---
-
-bool QKeyMapper::sendKeyEvent(QWidget *widget, bool grab,
- QEvent::Type type, int code, Qt::KeyboardModifiers modifiers,
- const QString &text, bool autorepeat, int count,
- quint32 nativeScanCode, quint32 nativeVirtualKey, quint32 nativeModifiers,
- bool *)
-{
-#if defined(Q_OS_WINCE)
- Q_UNUSED(grab);
-#endif
- Q_UNUSED(count);
-#if defined QT3_SUPPORT && !defined(QT_NO_SHORTCUT)
- if (type == QEvent::KeyPress
- && !grab
- && QApplicationPrivate::instance()->use_compat()) {
- // send accel events if the keyboard is not grabbed
- QKeyEventEx a(type, code, modifiers,
- text, autorepeat, qMax(1, int(text.length())),
- nativeScanCode, nativeVirtualKey, nativeModifiers);
- if (QApplicationPrivate::instance()->qt_tryAccelEvent(widget, &a))
- return true;
- }
-#else
- Q_UNUSED(grab);
-#endif
- if (!widget->isEnabled())
- return false;
-
- QKeyEventEx e(type, code, modifiers,
- text, autorepeat, qMax(1, int(text.length())),
- nativeScanCode, nativeVirtualKey, nativeModifiers);
- QETWidget::sendSpontaneousEvent(widget, &e);
-
- if (!isModifierKey(code)
- && modifiers == Qt::AltModifier
- && ((code >= Qt::Key_A && code <= Qt::Key_Z) || (code >= Qt::Key_0 && code <= Qt::Key_9))
- && type == QEvent::KeyPress
- && !e.isAccepted())
- QApplication::beep(); // Emulate windows behavior
-
- return e.isAccepted();
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qmime_win.cpp b/src/gui/platforms/win/qmime_win.cpp
deleted file mode 100644
index feb8b78eca..0000000000
--- a/src/gui/platforms/win/qmime_win.cpp
+++ /dev/null
@@ -1,1556 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmime.h"
-
-#include "qimagereader.h"
-#include "qimagewriter.h"
-#include "qdatastream.h"
-#include "qbuffer.h"
-#include "qt_windows.h"
-#include "qapplication_p.h"
-#include "qtextcodec.h"
-#include "qregexp.h"
-#include "qalgorithms.h"
-#include "qmap.h"
-#include "qdnd_p.h"
-#include <shlobj.h>
-#include "qurl.h"
-#include "qvariant.h"
-#include "qtextdocument.h"
-#include "qdir.h"
-
-#if defined(Q_OS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_IMAGEFORMAT_BMP
-#ifndef CF_DIBV5
-#define CF_DIBV5 17
-#endif
-/* The MSVC compilers allows multi-byte characters, that has the behavior of
- * that each character gets shifted into position. 0x73524742 below is for MSVC
- * equivalent to doing 'sRGB', but this does of course not work
- * on conformant C++ compilers. */
-#define BMP_LCS_sRGB 0x73524742
-#define BMP_LCS_GM_IMAGES 0x00000004L
-
-struct _CIEXYZ {
- long ciexyzX, ciexyzY, ciexyzZ;
-};
-
-struct _CIEXYZTRIPLE {
- _CIEXYZ ciexyzRed, ciexyzGreen, ciexyzBlue;
-};
-
-struct BMP_BITMAPV5HEADER {
- DWORD bV5Size;
- LONG bV5Width;
- LONG bV5Height;
- WORD bV5Planes;
- WORD bV5BitCount;
- DWORD bV5Compression;
- DWORD bV5SizeImage;
- LONG bV5XPelsPerMeter;
- LONG bV5YPelsPerMeter;
- DWORD bV5ClrUsed;
- DWORD bV5ClrImportant;
- DWORD bV5RedMask;
- DWORD bV5GreenMask;
- DWORD bV5BlueMask;
- DWORD bV5AlphaMask;
- DWORD bV5CSType;
- _CIEXYZTRIPLE bV5Endpoints;
- DWORD bV5GammaRed;
- DWORD bV5GammaGreen;
- DWORD bV5GammaBlue;
- DWORD bV5Intent;
- DWORD bV5ProfileData;
- DWORD bV5ProfileSize;
- DWORD bV5Reserved;
-};
-static const int BMP_BITFIELDS = 3;
-
-extern bool qt_read_dib(QDataStream&, QImage&); // qimage.cpp
-extern bool qt_write_dib(QDataStream&, QImage); // qimage.cpp
-static bool qt_write_dibv5(QDataStream &s, QImage image);
-static bool qt_read_dibv5(QDataStream &s, QImage &image);
-#endif
-
-//#define QMIME_DEBUG
-
-
-// helpers for using global memory
-
-static int getCf(const FORMATETC &formatetc)
-{
- return formatetc.cfFormat;
-}
-
-static FORMATETC setCf(int cf)
-{
- FORMATETC formatetc;
- formatetc.cfFormat = cf;
- formatetc.dwAspect = DVASPECT_CONTENT;
- formatetc.lindex = -1;
- formatetc.ptd = NULL;
- formatetc.tymed = TYMED_HGLOBAL;
- return formatetc;
-}
-
-static bool setData(const QByteArray &data, STGMEDIUM *pmedium)
-{
- HGLOBAL hData = GlobalAlloc(0, data.size());
- if (!hData)
- return false;
-
- void *out = GlobalLock(hData);
- memcpy(out, data.data(), data.size());
- GlobalUnlock(hData);
- pmedium->tymed = TYMED_HGLOBAL;
- pmedium->hGlobal = hData;
- pmedium->pUnkForRelease = 0;
- return true;
-}
-
-static QByteArray getData(int cf, IDataObject *pDataObj)
-{
- QByteArray data;
- FORMATETC formatetc = setCf(cf);
- STGMEDIUM s;
- if (pDataObj->GetData(&formatetc, &s) == S_OK) {
- DWORD * val = (DWORD*)GlobalLock(s.hGlobal);
- data = QByteArray::fromRawData((char*)val, GlobalSize(s.hGlobal));
- data.detach();
- GlobalUnlock(s.hGlobal);
- ReleaseStgMedium(&s);
- } else {
- //Try reading IStream data
- formatetc.tymed = TYMED_ISTREAM;
- if (pDataObj->GetData(&formatetc, &s) == S_OK) {
- char szBuffer[4096];
- ULONG actualRead = 0;
- LARGE_INTEGER pos = {{0, 0}};
- //Move to front (can fail depending on the data model implemented)
- HRESULT hr = s.pstm->Seek(pos, STREAM_SEEK_SET, NULL);
- while(SUCCEEDED(hr)){
- hr = s.pstm->Read(szBuffer, sizeof(szBuffer), &actualRead);
- if (SUCCEEDED(hr) && actualRead > 0) {
- data += QByteArray::fromRawData(szBuffer, actualRead);
- }
- if (actualRead != sizeof(szBuffer))
- break;
- }
- data.detach();
- ReleaseStgMedium(&s);
- }
- }
- return data;
-}
-
-static bool canGetData(int cf, IDataObject * pDataObj)
-{
- FORMATETC formatetc = setCf(cf);
- if (pDataObj->QueryGetData(&formatetc) != S_OK){
- formatetc.tymed = TYMED_ISTREAM;
- return pDataObj->QueryGetData(&formatetc) == S_OK;
- }
- return true;
-}
-
-class QWindowsMimeList
-{
-public:
- QWindowsMimeList();
- ~QWindowsMimeList();
- void addWindowsMime(QWindowsMime * mime);
- void removeWindowsMime(QWindowsMime * mime);
- QList<QWindowsMime*> windowsMimes();
-
-private:
- void init();
- bool initialized;
- QList<QWindowsMime*> mimes;
-};
-
-Q_GLOBAL_STATIC(QWindowsMimeList, theMimeList);
-
-
-/*!
- \class QWindowsMime
- \brief The QWindowsMime class maps open-standard MIME to Window Clipboard formats.
- \ingroup draganddrop
-
- Qt's drag-and-drop and clipboard facilities use the MIME standard.
- On X11, this maps trivially to the Xdnd protocol, but on Windows
- although some applications use MIME types to describe clipboard
- formats, others use arbitrary non-standardized naming conventions,
- or unnamed built-in formats of Windows.
-
- By instantiating subclasses of QWindowsMime that provide conversions
- between Windows Clipboard and MIME formats, you can convert
- proprietary clipboard formats to MIME formats.
-
- Qt has predefined support for the following Windows Clipboard formats:
-
- \table
- \header \o Windows Format \o Equivalent MIME type
- \row \o \c CF_UNICODETEXT \o \c text/plain
- \row \o \c CF_TEXT \o \c text/plain
- \row \o \c CF_DIB \o \c{image/xyz}, where \c xyz is
- a \l{QImageWriter::supportedImageFormats()}{Qt image format}
- \row \o \c CF_HDROP \o \c text/uri-list
- \row \o \c CF_INETURL \o \c text/uri-list
- \row \o \c CF_HTML \o \c text/html
- \endtable
-
- An example use of this class would be to map the Windows Metafile
- clipboard format (\c CF_METAFILEPICT) to and from the MIME type
- \c{image/x-wmf}. This conversion might simply be adding or removing
- a header, or even just passing on the data. See \l{Drag and Drop}
- for more information on choosing and definition MIME types.
-
- You can check if a MIME type is convertible using canConvertFromMime() and
- can perform conversions with convertToMime() and convertFromMime().
-*/
-
-/*!
-Constructs a new conversion object, adding it to the globally accessed
-list of available converters.
-*/
-QWindowsMime::QWindowsMime()
-{
- theMimeList()->addWindowsMime(this);
-}
-
-/*!
-Destroys a conversion object, removing it from the global
-list of available converters.
-*/
-QWindowsMime::~QWindowsMime()
-{
- theMimeList()->removeWindowsMime(this);
-}
-
-
-/*!
- Registers the MIME type \a mime, and returns an ID number
- identifying the format on Windows.
-*/
-int QWindowsMime::registerMimeType(const QString &mime)
-{
- int f = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (mime.utf16()));
- if (!f)
- qErrnoWarning("QWindowsMime::registerMimeType: Failed to register clipboard format");
-
- return f;
-}
-
-
-/*!
-\fn bool QWindowsMime::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-
- Returns true if the converter can convert from the \a mimeData to
- the format specified in \a formatetc.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn bool QWindowsMime::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-
- Returns true if the converter can convert to the \a mimeType from
- the available formats in \a pDataObj.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-\fn QString QWindowsMime::mimeForFormat(const FORMATETC &formatetc) const
-
- Returns the mime type that will be created form the format specified
- in \a formatetc, or an empty string if this converter does not support
- \a formatetc.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-\fn QVector<FORMATETC> QWindowsMime::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-
- Returns a QVector of FORMATETC structures representing the different windows clipboard
- formats that can be provided for the \a mimeType from the \a mimeData.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
- \fn QVariant QWindowsMime::convertToMime(const QString &mimeType, IDataObject *pDataObj,
- QVariant::Type preferredType) const
-
- Returns a QVariant containing the converted data for \a mimeType from \a pDataObj.
- If possible the QVariant should be of the \a preferredType to avoid needless conversions.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-\fn bool QWindowsMime::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-
- Convert the \a mimeData to the format specified in \a formatetc.
- The converted data should then be placed in \a pmedium structure.
-
- Return true if the conversion was successful.
-
- All subclasses must reimplement this pure virtual function.
-*/
-
-
-QWindowsMime *QWindowsMime::converterFromMime(const FORMATETC &formatetc, const QMimeData *mimeData)
-{
- QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
- for (int i=mimes.size()-1; i>=0; --i) {
- if (mimes.at(i)->canConvertFromMime(formatetc, mimeData))
- return mimes.at(i);
- }
- return 0;
-}
-
-QWindowsMime *QWindowsMime::converterToMime(const QString &mimeType, IDataObject *pDataObj)
-{
- QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
- for (int i=mimes.size()-1; i>=0; --i) {
- if (mimes.at(i)->canConvertToMime(mimeType, pDataObj))
- return mimes.at(i);
- }
- return 0;
-}
-
-QVector<FORMATETC> QWindowsMime::allFormatsForMime(const QMimeData *mimeData)
-{
- QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
- QVector<FORMATETC> formatics;
- formatics.reserve(20);
-#ifndef QT_NO_DRAGANDDROP
- QStringList formats = QInternalMimeData::formatsHelper(mimeData);
- for (int f=0; f<formats.size(); ++f) {
- for (int i=mimes.size()-1; i>=0; --i)
- formatics += mimes.at(i)->formatsForMime(formats.at(f), mimeData);
- }
-#else
- Q_UNUSED(mimeData);
-#endif //QT_NO_DRAGANDDROP
- return formatics;
-}
-
-QStringList QWindowsMime::allMimesForFormats(IDataObject *pDataObj)
-{
- QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
- QStringList formats;
- LPENUMFORMATETC FAR fmtenum;
- HRESULT hr = pDataObj->EnumFormatEtc(DATADIR_GET, &fmtenum);
-
- if (hr == NOERROR) {
- FORMATETC fmtetc;
- while (S_OK == fmtenum->Next(1, &fmtetc, 0)) {
-#if defined(QMIME_DEBUG) && !defined(Q_OS_WINCE)
- qDebug("QWindowsMime::allMimesForFormats()");
- wchar_t buf[256] = {0};
- GetClipboardFormatName(fmtetc.cfFormat, buf, 255);
- qDebug("CF = %d : %s", fmtetc.cfFormat, QString::fromWCharArray(buf));
-#endif
- for (int i=mimes.size()-1; i>=0; --i) {
- QString format = mimes.at(i)->mimeForFormat(fmtetc);
- if (!format.isEmpty() && !formats.contains(format)) {
- formats += format;
- }
- }
- // as documented in MSDN to avoid possible memleak
- if (fmtetc.ptd)
- CoTaskMemFree(fmtetc.ptd);
- }
- fmtenum->Release();
- }
-
- return formats;
-}
-
-
-class QWindowsMimeText : public QWindowsMime
-{
-public:
- bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
- QVariant convertToMime(const QString &mime, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const;
- QString mimeForFormat(const FORMATETC &formatetc) const;
- bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
- bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const;
- QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-};
-
-bool QWindowsMimeText::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
- int cf = getCf(formatetc);
- return (cf == CF_UNICODETEXT || cf == CF_TEXT) && mimeData->hasText();
-}
-
-/*
-text/plain is defined as using CRLF, but so many programs don't,
-and programmers just look for '\n' in strings.
-Windows really needs CRLF, so we ensure it here.
-*/
-bool QWindowsMimeText::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const
-{
- if (canConvertFromMime(formatetc, mimeData)) {
- QByteArray data;
- int cf = getCf(formatetc);
- if (cf == CF_TEXT) {
- data = mimeData->text().toLocal8Bit();
- // Anticipate required space for CRLFs at 1/40
- int maxsize=data.size()+data.size()/40+3;
- QByteArray r(maxsize, '\0');
- char* o = r.data();
- const char* d = data.data();
- const int s = data.size();
- bool cr=false;
- int j=0;
- for (int i=0; i<s; i++) {
- char c = d[i];
- if (c=='\r')
- cr=true;
- else {
- if (c=='\n') {
- if (!cr)
- o[j++]='\r';
- }
- cr=false;
- }
- o[j++]=c;
- if (j+3 >= maxsize) {
- maxsize += maxsize/4;
- r.resize(maxsize);
- o = r.data();
- }
- }
- o[j]=0;
- return setData(r, pmedium);
- } else if (cf == CF_UNICODETEXT) {
- QString str = mimeData->text();
- const QChar *u = str.unicode();
- QString res;
- const int s = str.length();
- int maxsize = s + s/40 + 3;
- res.resize(maxsize);
- int ri = 0;
- bool cr = false;
- for (int i=0; i < s; ++i) {
- if (*u == QLatin1Char('\r'))
- cr = true;
- else {
- if (*u == QLatin1Char('\n') && !cr)
- res[ri++] = QLatin1Char('\r');
- cr = false;
- }
- res[ri++] = *u;
- if (ri+3 >= maxsize) {
- maxsize += maxsize/4;
- res.resize(maxsize);
- }
- ++u;
- }
- res.truncate(ri);
- const int byteLength = res.length() * sizeof(ushort);
- QByteArray r(byteLength + 2, '\0');
- memcpy(r.data(), res.unicode(), byteLength);
- r[byteLength] = 0;
- r[byteLength+1] = 0;
- return setData(r, pmedium);
- }
- }
- return false;
-}
-
-bool QWindowsMimeText::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
- return mimeType.startsWith(QLatin1String("text/plain"))
- && (canGetData(CF_UNICODETEXT, pDataObj)
- || canGetData(CF_TEXT, pDataObj));
-}
-
-QString QWindowsMimeText::mimeForFormat(const FORMATETC &formatetc) const
-{
- int cf = getCf(formatetc);
- if (cf == CF_UNICODETEXT || cf == CF_TEXT)
- return QLatin1String("text/plain");
- return QString();
-}
-
-
-QVector<FORMATETC> QWindowsMimeText::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
- QVector<FORMATETC> formatics;
- if (mimeType.startsWith(QLatin1String("text/plain")) && mimeData->hasText()) {
- formatics += setCf(CF_UNICODETEXT);
- formatics += setCf(CF_TEXT);
- }
- return formatics;
-}
-
-QVariant QWindowsMimeText::convertToMime(const QString &mime, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const
-{
- QVariant ret;
-
- if (canConvertToMime(mime, pDataObj)) {
- QString str;
- QByteArray data = getData(CF_UNICODETEXT, pDataObj);
- if (!data.isEmpty()) {
- str = QString::fromWCharArray((const wchar_t *)data.data());
- str.replace(QLatin1String("\r\n"), QLatin1String("\n"));
- } else {
- data = getData(CF_TEXT, pDataObj);
- if (!data.isEmpty()) {
- const char* d = data.data();
- const int s = qstrlen(d);
- QByteArray r(data.size()+1, '\0');
- char* o = r.data();
- int j=0;
- for (int i=0; i<s; i++) {
- char c = d[i];
- if (c!='\r')
- o[j++]=c;
- }
- o[j]=0;
- str = QString::fromLocal8Bit(r);
- }
- }
- if (preferredType == QVariant::String)
- ret = str;
- else
- ret = str.toUtf8();
- }
-
- return ret;
-}
-
-class QWindowsMimeURI : public QWindowsMime
-{
-public:
- QWindowsMimeURI();
- bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
- QVariant convertToMime(const QString &mime, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const;
- QString mimeForFormat(const FORMATETC &formatetc) const;
- bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
- bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const;
- QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-private:
- int CF_INETURL_W; // wide char version
- int CF_INETURL;
-};
-
-QWindowsMimeURI::QWindowsMimeURI()
-{
- CF_INETURL_W = QWindowsMime::registerMimeType(QLatin1String("UniformResourceLocatorW"));
- CF_INETURL = QWindowsMime::registerMimeType(QLatin1String("UniformResourceLocator"));
-}
-
-bool QWindowsMimeURI::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
- if (getCf(formatetc) == CF_HDROP) {
- QList<QUrl> urls = mimeData->urls();
- for (int i=0; i<urls.size(); i++) {
- if (!urls.at(i).toLocalFile().isEmpty())
- return true;
- }
- }
- return (getCf(formatetc) == CF_INETURL_W || getCf(formatetc) == CF_INETURL) && mimeData->hasFormat(QLatin1String("text/uri-list"));
-}
-
-bool QWindowsMimeURI::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const
-{
- if (canConvertFromMime(formatetc, mimeData)) {
- if (getCf(formatetc) == CF_HDROP) {
- QList<QUrl> urls = mimeData->urls();
- QStringList fileNames;
- int size = sizeof(DROPFILES)+2;
- for (int i=0; i<urls.size(); i++) {
- QString fn = QDir::toNativeSeparators(urls.at(i).toLocalFile());
- if (!fn.isEmpty()) {
- size += sizeof(ushort) * (fn.length() + 1);
- fileNames.append(fn);
- }
- }
-
- QByteArray result(size, '\0');
- DROPFILES* d = (DROPFILES*)result.data();
- d->pFiles = sizeof(DROPFILES);
- GetCursorPos(&d->pt); // try
- d->fNC = true;
- char* files = ((char*)d) + d->pFiles;
-
- d->fWide = true;
- wchar_t* f = (wchar_t*)files;
- for (int i=0; i<fileNames.size(); i++) {
- int l = fileNames.at(i).length();
- memcpy(f, fileNames.at(i).utf16(), l * sizeof(ushort));
- f += l;
- *f++ = 0;
- }
- *f = 0;
-
- return setData(result, pmedium);
- } else if (getCf(formatetc) == CF_INETURL_W) {
- QList<QUrl> urls = mimeData->urls();
- QByteArray result;
- if (!urls.isEmpty()) {
- QString url = urls.at(0).toString();
- result = QByteArray((const char *)url.utf16(), url.length() * sizeof(ushort));
- }
- result.append('\0');
- result.append('\0');
- return setData(result, pmedium);
- } else if (getCf(formatetc) == CF_INETURL) {
- QList<QUrl> urls = mimeData->urls();
- QByteArray result;
- if (!urls.isEmpty())
- result = urls.at(0).toString().toLocal8Bit();
- return setData(result, pmedium);
- }
- }
-
- return false;
-}
-
-bool QWindowsMimeURI::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
- return mimeType == QLatin1String("text/uri-list")
- && (canGetData(CF_HDROP, pDataObj) || canGetData(CF_INETURL_W, pDataObj) || canGetData(CF_INETURL, pDataObj));
-}
-
-QString QWindowsMimeURI::mimeForFormat(const FORMATETC &formatetc) const
-{
- QString format;
- if (getCf(formatetc) == CF_HDROP || getCf(formatetc) == CF_INETURL_W || getCf(formatetc) == CF_INETURL)
- format = QLatin1String("text/uri-list");
- return format;
-}
-
-QVector<FORMATETC> QWindowsMimeURI::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
- QVector<FORMATETC> formatics;
- if (mimeType == QLatin1String("text/uri-list")) {
- if (canConvertFromMime(setCf(CF_HDROP), mimeData))
- formatics += setCf(CF_HDROP);
- if (canConvertFromMime(setCf(CF_INETURL_W), mimeData))
- formatics += setCf(CF_INETURL_W);
- if (canConvertFromMime(setCf(CF_INETURL), mimeData))
- formatics += setCf(CF_INETURL);
- }
- return formatics;
-}
-
-QVariant QWindowsMimeURI::convertToMime(const QString &mimeType, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const
-{
- if (mimeType == QLatin1String("text/uri-list")) {
- if (canGetData(CF_HDROP, pDataObj)) {
- QByteArray texturi;
- QList<QVariant> urls;
-
- QByteArray data = getData(CF_HDROP, pDataObj);
- if (data.isEmpty())
- return QVariant();
-
- LPDROPFILES hdrop = (LPDROPFILES)data.data();
- if (hdrop->fWide) {
- const wchar_t* filesw = (const wchar_t *)(data.data() + hdrop->pFiles);
- int i = 0;
- while (filesw[i]) {
- QString fileurl = QString::fromWCharArray(filesw + i);
- urls += QUrl::fromLocalFile(fileurl);
- i += fileurl.length()+1;
- }
- } else {
- const char* files = (const char *)data.data() + hdrop->pFiles;
- int i=0;
- while (files[i]) {
- urls += QUrl::fromLocalFile(QString::fromLocal8Bit(files+i));
- i += int(strlen(files+i))+1;
- }
- }
-
- if (preferredType == QVariant::Url && urls.size() == 1)
- return urls.at(0);
- else if (!urls.isEmpty())
- return urls;
- } else if (canGetData(CF_INETURL_W, pDataObj)) {
- QByteArray data = getData(CF_INETURL_W, pDataObj);
- if (data.isEmpty())
- return QVariant();
- return QUrl(QString::fromWCharArray((const wchar_t *)data.constData()));
- } else if (canGetData(CF_INETURL, pDataObj)) {
- QByteArray data = getData(CF_INETURL, pDataObj);
- if (data.isEmpty())
- return QVariant();
- return QUrl(QString::fromLocal8Bit(data.constData()));
- }
- }
- return QVariant();
-}
-
-class QWindowsMimeHtml : public QWindowsMime
-{
-public:
- QWindowsMimeHtml();
-
- // for converting from Qt
- bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
- bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
- QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
- // for converting to Qt
- bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
- QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
- QString mimeForFormat(const FORMATETC &formatetc) const;
-
-private:
- int CF_HTML;
-};
-
-QWindowsMimeHtml::QWindowsMimeHtml()
-{
- CF_HTML = QWindowsMime::registerMimeType(QLatin1String("HTML Format"));
-}
-
-QVector<FORMATETC> QWindowsMimeHtml::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
- QVector<FORMATETC> formatetcs;
- if (mimeType == QLatin1String("text/html") && (!mimeData->html().isEmpty()))
- formatetcs += setCf(CF_HTML);
- return formatetcs;
-}
-
-QString QWindowsMimeHtml::mimeForFormat(const FORMATETC &formatetc) const
-{
- if (getCf(formatetc) == CF_HTML)
- return QLatin1String("text/html");
- return QString();
-}
-
-bool QWindowsMimeHtml::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
- return mimeType == QLatin1String("text/html") && canGetData(CF_HTML, pDataObj);
-}
-
-
-bool QWindowsMimeHtml::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
- return getCf(formatetc) == CF_HTML && (!mimeData->html().isEmpty());
-}
-
-/*
-The windows HTML clipboard format is as follows (xxxxxxxxxx is a 10 integer number giving the positions
-in bytes). Charset used is mostly utf8, but can be different, ie. we have to look for the <meta> charset tag
-
- Version: 1.0
- StartHTML:xxxxxxxxxx
- EndHTML:xxxxxxxxxx
- StartFragment:xxxxxxxxxx
- EndFragment:xxxxxxxxxx
- ...html...
-
-*/
-QVariant QWindowsMimeHtml::convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
- Q_UNUSED(preferredType);
- QVariant result;
- if (canConvertToMime(mime, pDataObj)) {
- QByteArray html = getData(CF_HTML, pDataObj);
-#ifdef QMIME_DEBUG
- qDebug("QWindowsMimeHtml::convertToMime");
- qDebug("raw :");
- qDebug(html);
-#endif
- int start = html.indexOf("StartFragment:");
- int end = html.indexOf("EndFragment:");
-
- if (start != -1) {
- int startOffset = start + 14;
- int i = startOffset;
- while (html.at(i) != '\r' && html.at(i) != '\n')
- ++i;
- QByteArray bytecount = html.mid(startOffset, i - startOffset);
- start = bytecount.toInt();
- }
-
- if (end != -1) {
- int endOffset = end + 12;
- int i = endOffset ;
- while (html.at(i) != '\r' && html.at(i) != '\n')
- ++i;
- QByteArray bytecount = html.mid(endOffset , i - endOffset);
- end = bytecount.toInt();
- }
-
- if (end > start && start > 0) {
- html = "<!--StartFragment-->" + html.mid(start, end - start);
- html += "<!--EndFragment-->";
- html.replace('\r', "");
- result = QString::fromUtf8(html);
- }
- }
- return result;
-}
-
-bool QWindowsMimeHtml::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
- if (canConvertFromMime(formatetc, mimeData)) {
- QByteArray data = mimeData->html().toUtf8();
- QByteArray result =
- "Version:1.0\r\n" // 0-12
- "StartHTML:0000000105\r\n" // 13-35
- "EndHTML:0000000000\r\n" // 36-55
- "StartFragment:0000000000\r\n" // 58-86
- "EndFragment:0000000000\r\n\r\n"; // 87-105
-
- if (data.indexOf("<!--StartFragment-->") == -1)
- result += "<!--StartFragment-->";
- result += data;
- if (data.indexOf("<!--EndFragment-->") == -1)
- result += "<!--EndFragment-->";
-
- // set the correct number for EndHTML
- QByteArray pos = QString::number(result.size()).toLatin1();
- memcpy((char *)(result.data() + 53 - pos.length()), pos.constData(), pos.length());
-
- // set correct numbers for StartFragment and EndFragment
- pos = QString::number(result.indexOf("<!--StartFragment-->") + 20).toLatin1();
- memcpy((char *)(result.data() + 79 - pos.length()), pos.constData(), pos.length());
- pos = QString::number(result.indexOf("<!--EndFragment-->")).toLatin1();
- memcpy((char *)(result.data() + 103 - pos.length()), pos.constData(), pos.length());
-
- return setData(result, pmedium);
- }
- return false;
-}
-
-
-#ifndef QT_NO_IMAGEFORMAT_BMP
-class QWindowsMimeImage : public QWindowsMime
-{
-public:
- QWindowsMimeImage();
- // for converting from Qt
- bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
- bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
- QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
- // for converting to Qt
- bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
- QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
- QString mimeForFormat(const FORMATETC &formatetc) const;
-private:
- bool hasOriginalDIBV5(IDataObject *pDataObj) const;
- UINT CF_PNG;
-};
-
-QWindowsMimeImage::QWindowsMimeImage()
-{
- CF_PNG = RegisterClipboardFormat(L"PNG");
-}
-
-QVector<FORMATETC> QWindowsMimeImage::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
- QVector<FORMATETC> formatetcs;
- if (mimeData->hasImage() && mimeType == QLatin1String("application/x-qt-image")) {
- //add DIBV5 if image has alpha channel
- QImage image = qvariant_cast<QImage>(mimeData->imageData());
- if (!image.isNull() && image.hasAlphaChannel())
- formatetcs += setCf(CF_DIBV5);
- formatetcs += setCf(CF_DIB);
- }
- return formatetcs;
-}
-
-QString QWindowsMimeImage::mimeForFormat(const FORMATETC &formatetc) const
-{
- int cf = getCf(formatetc);
- if (cf == CF_DIB || cf == CF_DIBV5 || cf == int(CF_PNG))
- return QLatin1String("application/x-qt-image");
- return QString();
-}
-
-bool QWindowsMimeImage::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
- if ((mimeType == QLatin1String("application/x-qt-image")) &&
- (canGetData(CF_DIB, pDataObj) || canGetData(CF_PNG, pDataObj)))
- return true;
- return false;
-}
-
-bool QWindowsMimeImage::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
- int cf = getCf(formatetc);
- if (mimeData->hasImage()) {
- if (cf == CF_DIB)
- return true;
- else if (cf == CF_DIBV5) {
- //support DIBV5 conversion only if the image has alpha channel
- QImage image = qvariant_cast<QImage>(mimeData->imageData());
- if (!image.isNull() && image.hasAlphaChannel())
- return true;
- }
- }
- return false;
-}
-
-bool QWindowsMimeImage::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
- int cf = getCf(formatetc);
- if ((cf == CF_DIB || cf == CF_DIBV5) && mimeData->hasImage()) {
- QImage img = qvariant_cast<QImage>(mimeData->imageData());
- if (img.isNull())
- return false;
- QByteArray ba;
- QDataStream s(&ba, QIODevice::WriteOnly);
- s.setByteOrder(QDataStream::LittleEndian);// Intel byte order ####
- if (cf == CF_DIB) {
- if (img.format() > QImage::Format_ARGB32)
- img = img.convertToFormat(QImage::Format_RGB32);
- if (qt_write_dib(s, img))
- return setData(ba, pmedium);
- } else {
- if (qt_write_dibv5(s, img))
- return setData(ba, pmedium);
- }
- }
- return false;
-}
-
-bool QWindowsMimeImage::hasOriginalDIBV5(IDataObject *pDataObj) const
-{
- bool isSynthesized = true;
- IEnumFORMATETC *pEnum =NULL;
- HRESULT res = pDataObj->EnumFormatEtc(1, &pEnum);
- if (res == S_OK && pEnum) {
- FORMATETC fc;
- while ((res = pEnum->Next(1, &fc, 0)) == S_OK) {
- if (fc.ptd)
- CoTaskMemFree(fc.ptd);
- if (fc.cfFormat == CF_DIB)
- break;
- else if (fc.cfFormat == CF_DIBV5) {
- isSynthesized = false;
- break;
- }
- }
- pEnum->Release();
- }
- return !isSynthesized;
-}
-
-QVariant QWindowsMimeImage::convertToMime(const QString &mimeType, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
- Q_UNUSED(preferredType);
- QVariant result;
- if (mimeType != QLatin1String("application/x-qt-image"))
- return result;
- //Try to convert from a format which has more data
- //DIBV5, use only if its is not synthesized
- if (canGetData(CF_DIBV5, pDataObj) && hasOriginalDIBV5(pDataObj)) {
- QImage img;
- QByteArray data = getData(CF_DIBV5, pDataObj);
- QDataStream s(&data, QIODevice::ReadOnly);
- s.setByteOrder(QDataStream::LittleEndian);
- if (qt_read_dibv5(s, img)) { // #### supports only 32bit DIBV5
- return img;
- }
- }
- //PNG, MS Office place this (undocumented)
- if (canGetData(CF_PNG, pDataObj)) {
- QImage img;
- QByteArray data = getData(CF_PNG, pDataObj);
- if (img.loadFromData(data, "PNG")) {
- return img;
- }
- }
- //Fallback to DIB
- if (canGetData(CF_DIB, pDataObj)) {
- QImage img;
- QByteArray data = getData(CF_DIB, pDataObj);
- QDataStream s(&data, QIODevice::ReadOnly);
- s.setByteOrder(QDataStream::LittleEndian);// Intel byte order ####
- if (qt_read_dib(s, img)) { // ##### encaps "-14"
- return img;
- }
- }
- // Failed
- return result;
-}
-#endif
-
-class QBuiltInMimes : public QWindowsMime
-{
-public:
- QBuiltInMimes();
-
- // for converting from Qt
- bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
- bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
- QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
- // for converting to Qt
- bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
- QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
- QString mimeForFormat(const FORMATETC &formatetc) const;
-
-private:
- QMap<int, QString> outFormats;
- QMap<int, QString> inFormats;
-};
-
-QBuiltInMimes::QBuiltInMimes()
-: QWindowsMime()
-{
- outFormats.insert(QWindowsMime::registerMimeType(QLatin1String("application/x-color")), QLatin1String("application/x-color"));
- inFormats.insert(QWindowsMime::registerMimeType(QLatin1String("application/x-color")), QLatin1String("application/x-color"));
-}
-
-bool QBuiltInMimes::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
- // really check
- return formatetc.tymed & TYMED_HGLOBAL
- && outFormats.contains(formatetc.cfFormat)
- && mimeData->formats().contains(outFormats.value(formatetc.cfFormat));
-}
-
-bool QBuiltInMimes::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
- if (canConvertFromMime(formatetc, mimeData)) {
- QByteArray data;
- if (outFormats.value(getCf(formatetc)) == QLatin1String("text/html")) {
- // text/html is in wide chars on windows (compatible with mozillia)
- QString html = mimeData->html();
- // same code as in the text converter up above
- const QChar *u = html.unicode();
- QString res;
- const int s = html.length();
- int maxsize = s + s/40 + 3;
- res.resize(maxsize);
- int ri = 0;
- bool cr = false;
- for (int i=0; i < s; ++i) {
- if (*u == QLatin1Char('\r'))
- cr = true;
- else {
- if (*u == QLatin1Char('\n') && !cr)
- res[ri++] = QLatin1Char('\r');
- cr = false;
- }
- res[ri++] = *u;
- if (ri+3 >= maxsize) {
- maxsize += maxsize/4;
- res.resize(maxsize);
- }
- ++u;
- }
- res.truncate(ri);
- const int byteLength = res.length() * sizeof(ushort);
- QByteArray r(byteLength + 2, '\0');
- memcpy(r.data(), res.unicode(), byteLength);
- r[byteLength] = 0;
- r[byteLength+1] = 0;
- data = r;
- } else {
-#ifndef QT_NO_DRAGANDDROP
- data = QInternalMimeData::renderDataHelper(outFormats.value(getCf(formatetc)), mimeData);
-#endif //QT_NO_DRAGANDDROP
- }
- return setData(data, pmedium);
- }
- return false;
-}
-
-QVector<FORMATETC> QBuiltInMimes::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
- QVector<FORMATETC> formatetcs;
- if (!outFormats.keys(mimeType).isEmpty() && mimeData->formats().contains(mimeType))
- formatetcs += setCf(outFormats.key(mimeType));
- return formatetcs;
-}
-
-bool QBuiltInMimes::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
- return (!inFormats.keys(mimeType).isEmpty())
- && canGetData(inFormats.key(mimeType), pDataObj);
-}
-
-QVariant QBuiltInMimes::convertToMime(const QString &mimeType, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
- QVariant val;
- if (canConvertToMime(mimeType, pDataObj)) {
- QByteArray data = getData(inFormats.key(mimeType), pDataObj);
- if (!data.isEmpty()) {
-#ifdef QMIME_DEBUG
- qDebug("QBuiltInMimes::convertToMime()");
-#endif
- if (mimeType == QLatin1String("text/html") && preferredType == QVariant::String) {
- // text/html is in wide chars on windows (compatible with Mozilla)
- val = QString::fromWCharArray((const wchar_t *)data.data());
- } else {
- val = data; // it should be enough to return the data and let QMimeData do the rest.
- }
- }
- }
- return val;
-}
-
-QString QBuiltInMimes::mimeForFormat(const FORMATETC &formatetc) const
-{
- return inFormats.value(getCf(formatetc));
-}
-
-
-class QLastResortMimes : public QWindowsMime
-{
-public:
-
- QLastResortMimes();
- // for converting from Qt
- bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
- bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
- QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
- // for converting to Qt
- bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
- QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
- QString mimeForFormat(const FORMATETC &formatetc) const;
-
-private:
- QMap<int, QString> formats;
- static QStringList ianaTypes;
- static QStringList excludeList;
-};
-
-QStringList QLastResortMimes::ianaTypes;
-QStringList QLastResortMimes::excludeList;
-
-QLastResortMimes::QLastResortMimes()
-{
- //MIME Media-Types
- if (!ianaTypes.size()) {
- ianaTypes.append(QLatin1String("application/"));
- ianaTypes.append(QLatin1String("audio/"));
- ianaTypes.append(QLatin1String("example/"));
- ianaTypes.append(QLatin1String("image/"));
- ianaTypes.append(QLatin1String("message/"));
- ianaTypes.append(QLatin1String("model/"));
- ianaTypes.append(QLatin1String("multipart/"));
- ianaTypes.append(QLatin1String("text/"));
- ianaTypes.append(QLatin1String("video/"));
- }
- //Types handled by other classes
- if (!excludeList.size()) {
- excludeList.append(QLatin1String("HTML Format"));
- excludeList.append(QLatin1String("UniformResourceLocator"));
- excludeList.append(QLatin1String("text/html"));
- excludeList.append(QLatin1String("text/plain"));
- excludeList.append(QLatin1String("text/uri-list"));
- excludeList.append(QLatin1String("application/x-qt-image"));
- excludeList.append(QLatin1String("application/x-color"));
- }
-}
-
-bool QLastResortMimes::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
- // really check
-#ifndef QT_NO_DRAGANDDROP
- return formatetc.tymed & TYMED_HGLOBAL
- && (formats.contains(formatetc.cfFormat)
- && QInternalMimeData::hasFormatHelper(formats.value(formatetc.cfFormat), mimeData));
-#else
- Q_UNUSED(mimeData);
- Q_UNUSED(formatetc);
- return formatetc.tymed & TYMED_HGLOBAL
- && formats.contains(formatetc.cfFormat);
-#endif //QT_NO_DRAGANDDROP
-}
-
-bool QLastResortMimes::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
-#ifndef QT_NO_DRAGANDDROP
- return canConvertFromMime(formatetc, mimeData)
- && setData(QInternalMimeData::renderDataHelper(formats.value(getCf(formatetc)), mimeData), pmedium);
-#else
- Q_UNUSED(mimeData);
- Q_UNUSED(formatetc);
- Q_UNUSED(pmedium);
- return false;
-#endif //QT_NO_DRAGANDDROP
-}
-
-QVector<FORMATETC> QLastResortMimes::formatsForMime(const QString &mimeType, const QMimeData * /*mimeData*/) const
-{
- QVector<FORMATETC> formatetcs;
- if (!formats.keys(mimeType).isEmpty()) {
- formatetcs += setCf(formats.key(mimeType));
- } else if (!excludeList.contains(mimeType, Qt::CaseInsensitive)){
- // register any other available formats
- int cf = QWindowsMime::registerMimeType(mimeType);
- QLastResortMimes *that = const_cast<QLastResortMimes *>(this);
- that->formats.insert(cf, mimeType);
- formatetcs += setCf(cf);
- }
- return formatetcs;
-}
-static const char x_qt_windows_mime[] = "application/x-qt-windows-mime;value=\"";
-
-static bool isCustomMimeType(const QString &mimeType)
-{
- return mimeType.startsWith(QLatin1String(x_qt_windows_mime), Qt::CaseInsensitive);
-}
-
-static QString customMimeType(const QString &mimeType)
-{
- int len = sizeof(x_qt_windows_mime) - 1;
- int n = mimeType.lastIndexOf(QLatin1Char('\"'))-len;
- return mimeType.mid(len, n);
-}
-
-bool QLastResortMimes::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
- if (isCustomMimeType(mimeType)) {
- QString clipFormat = customMimeType(mimeType);
- int cf = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (clipFormat.utf16()));
- return canGetData(cf, pDataObj);
- } else if (formats.keys(mimeType).isEmpty()) {
- // if it is not in there then register it an see if we can get it
- int cf = QWindowsMime::registerMimeType(mimeType);
- return canGetData(cf, pDataObj);
- } else {
- return canGetData(formats.key(mimeType), pDataObj);
- }
- return false;
-}
-
-QVariant QLastResortMimes::convertToMime(const QString &mimeType, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
- Q_UNUSED(preferredType);
- QVariant val;
- if (canConvertToMime(mimeType, pDataObj)) {
- QByteArray data;
- if (isCustomMimeType(mimeType)) {
- QString clipFormat = customMimeType(mimeType);
- int cf = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (clipFormat.utf16()));
- data = getData(cf, pDataObj);
- } else if (formats.keys(mimeType).isEmpty()) {
- int cf = QWindowsMime::registerMimeType(mimeType);
- data = getData(cf, pDataObj);
- } else {
- data = getData(formats.key(mimeType), pDataObj);
- }
- if (!data.isEmpty())
- val = data; // it should be enough to return the data and let QMimeData do the rest.
- }
- return val;
-}
-
-QString QLastResortMimes::mimeForFormat(const FORMATETC &formatetc) const
-{
- QString format = formats.value(getCf(formatetc));
- if (!format.isEmpty())
- return format;
-
- wchar_t buffer[256];
- int len = GetClipboardFormatName(getCf(formatetc), buffer, 256);
-
- if (len) {
- QString clipFormat = QString::fromWCharArray(buffer, len);
-#ifndef QT_NO_DRAGANDDROP
- if (QInternalMimeData::canReadData(clipFormat))
- format = clipFormat;
- else if((formatetc.cfFormat >= 0xC000)){
- //create the mime as custom. not registered.
- if (!excludeList.contains(clipFormat, Qt::CaseInsensitive)) {
- //check if this is a mime type
- bool ianaType = false;
- int sz = ianaTypes.size();
- for (int i = 0; i < sz; i++) {
- if (clipFormat.startsWith(ianaTypes[i], Qt::CaseInsensitive)) {
- ianaType = true;
- break;
- }
- }
- if (!ianaType)
- format = QLatin1String(x_qt_windows_mime) + clipFormat + QLatin1Char('\"');
- else
- format = clipFormat;
- }
- }
-#endif //QT_NO_DRAGANDDROP
- }
-
- return format;
-}
-
-QWindowsMimeList::QWindowsMimeList()
- : initialized(false)
-{
-}
-
-QWindowsMimeList::~QWindowsMimeList()
-{
- while (mimes.size())
- delete mimes.first();
-}
-
-
-void QWindowsMimeList::init()
-{
- if (!initialized) {
- initialized = true;
-#ifndef QT_NO_IMAGEFORMAT_BMP
- new QWindowsMimeImage;
-#endif
- new QLastResortMimes;
- new QWindowsMimeText;
- new QWindowsMimeURI;
-
- new QWindowsMimeHtml;
- new QBuiltInMimes;
- }
-}
-
-void QWindowsMimeList::addWindowsMime(QWindowsMime * mime)
-{
- init();
- mimes.append(mime);
-}
-
-void QWindowsMimeList::removeWindowsMime(QWindowsMime * mime)
-{
- init();
- mimes.removeAll(mime);
-}
-
-QList<QWindowsMime*> QWindowsMimeList::windowsMimes()
-{
- init();
- return mimes;
-}
-
-#ifndef QT_NO_IMAGEFORMAT_BMP
-static bool qt_write_dibv5(QDataStream &s, QImage image)
-{
- QIODevice* d = s.device();
- if (!d->isWritable())
- return false;
-
- //depth will be always 32
- int bpl_bmp = image.width()*4;
-
- BMP_BITMAPV5HEADER bi ={0};
- bi.bV5Size = sizeof(BMP_BITMAPV5HEADER);
- bi.bV5Width = image.width();
- bi.bV5Height = image.height();
- bi.bV5Planes = 1;
- bi.bV5BitCount = 32;
- bi.bV5Compression = BI_BITFIELDS;
- bi.bV5SizeImage = bpl_bmp*image.height();
- bi.bV5XPelsPerMeter = 0;
- bi.bV5YPelsPerMeter = 0;
- bi.bV5ClrUsed = 0;
- bi.bV5ClrImportant = 0;
- bi.bV5BlueMask = 0x000000ff;
- bi.bV5GreenMask = 0x0000ff00;
- bi.bV5RedMask = 0x00ff0000;
- bi.bV5AlphaMask = 0xff000000;
- bi.bV5CSType = BMP_LCS_sRGB; //LCS_sRGB
- bi.bV5Intent = BMP_LCS_GM_IMAGES; //LCS_GM_IMAGES
-
- d->write(reinterpret_cast<const char*>(&bi), bi.bV5Size);
- if (s.status() != QDataStream::Ok)
- return false;
-
- DWORD colorSpace[3] = {0x00ff0000,0x0000ff00,0x000000ff};
- d->write(reinterpret_cast<const char*>(colorSpace), sizeof(colorSpace));
- if (s.status() != QDataStream::Ok)
- return false;
-
- if (image.format() != QImage::Format_ARGB32)
- image = image.convertToFormat(QImage::Format_ARGB32);
-
- uchar *buf = new uchar[bpl_bmp];
- uchar *b;
-
- memset(buf, 0, bpl_bmp);
- for (int y=image.height()-1; y>=0; y--) {
- // write the image bits
- QRgb *p = (QRgb *)image.scanLine(y);
- QRgb *end = p + image.width();
- b = buf;
- while (p < end) {
- int alpha = qAlpha(*p);
- if (alpha) {
- *b++ = qBlue(*p);
- *b++ = qGreen(*p);
- *b++ = qRed(*p);
- } else {
- //white for fully transparent pixels.
- *b++ = 0xff;
- *b++ = 0xff;
- *b++ = 0xff;
- }
- *b++ = alpha;
- p++;
- }
- d->write((char*)buf, bpl_bmp);
- if (s.status() != QDataStream::Ok) {
- delete[] buf;
- return false;
- }
- }
- delete[] buf;
- return true;
-}
-
-static int calc_shift(int mask)
-{
- int result = 0;
- while (!(mask & 1)) {
- result++;
- mask >>= 1;
- }
- return result;
-}
-
-//Supports only 32 bit DIBV5
-static bool qt_read_dibv5(QDataStream &s, QImage &image)
-{
- BMP_BITMAPV5HEADER bi;
- QIODevice* d = s.device();
- if (d->atEnd())
- return false;
-
- d->read((char *)&bi, sizeof(bi)); // read BITMAPV5HEADER header
- if (s.status() != QDataStream::Ok)
- return false;
-
- int nbits = bi.bV5BitCount;
- int comp = bi.bV5Compression;
- if (nbits != 32 || bi.bV5Planes != 1 || comp != BMP_BITFIELDS)
- return false; //Unsupported DIBV5 format
-
- int w = bi.bV5Width, h = bi.bV5Height;
- int red_mask = bi.bV5RedMask;
- int green_mask = bi.bV5GreenMask;
- int blue_mask = bi.bV5BlueMask;
- int alpha_mask = bi.bV5AlphaMask;
- int red_shift = 0;
- int green_shift = 0;
- int blue_shift = 0;
- int alpha_shift = 0;
- QImage::Format format = QImage::Format_ARGB32;
-
- if (bi.bV5Height < 0)
- h = -h; // support images with negative height
- if (image.size() != QSize(w, h) || image.format() != format) {
- image = QImage(w, h, format);
- if (image.isNull()) // could not create image
- return false;
- }
- image.setDotsPerMeterX(bi.bV5XPelsPerMeter);
- image.setDotsPerMeterY(bi.bV5YPelsPerMeter);
- // read color table
- DWORD colorSpace[3];
- if (d->read((char *)colorSpace, sizeof(colorSpace)) != sizeof(colorSpace))
- return false;
-
- red_shift = calc_shift(red_mask);
- green_shift = calc_shift(green_mask);
- blue_shift = calc_shift(blue_mask);
- if (alpha_mask) {
- alpha_shift = calc_shift(alpha_mask);
- }
-
- int bpl = image.bytesPerLine();
- uchar *data = image.bits();
- register QRgb *p;
- QRgb *end;
- uchar *buf24 = new uchar[bpl];
- int bpl24 = ((w*nbits+31)/32)*4;
- uchar *b;
- unsigned int c;
-
- while (--h >= 0) {
- p = (QRgb *)(data + h*bpl);
- end = p + w;
- if (d->read((char *)buf24,bpl24) != bpl24)
- break;
- b = buf24;
- while (p < end) {
- c = *b | (*(b+1))<<8 | (*(b+2))<<16 | (*(b+3))<<24;
- *p++ = qRgba(((c & red_mask) >> red_shift) ,
- ((c & green_mask) >> green_shift),
- ((c & blue_mask) >> blue_shift),
- ((c & alpha_mask) >> alpha_shift));
- b += 4;
- }
- }
- delete[] buf24;
-
- if (bi.bV5Height < 0) {
- // Flip the image
- uchar *buf = new uchar[bpl];
- h = -bi.bV5Height;
- for (int y = 0; y < h/2; ++y) {
- memcpy(buf, data + y*bpl, bpl);
- memcpy(data + y*bpl, data + (h-y-1)*bpl, bpl);
- memcpy(data + (h-y-1)*bpl, buf, bpl);
- }
- delete [] buf;
- }
-
- return true;
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qole_win.cpp b/src/gui/platforms/win/qole_win.cpp
deleted file mode 100644
index 24e2d5b292..0000000000
--- a/src/gui/platforms/win/qole_win.cpp
+++ /dev/null
@@ -1,255 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdnd_p.h"
-
-#if !(defined(QT_NO_DRAGANDDROP) && defined(QT_NO_CLIPBOARD))
-
-#if defined(Q_OS_WINCE)
-#include <shlobj.h>
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QOleEnumFmtEtc::QOleEnumFmtEtc(const QVector<FORMATETC> &fmtetcs)
-{
- m_isNull = false;
- m_dwRefs = 1;
- m_nIndex = 0;
-
- for (int idx = 0; idx < fmtetcs.count(); ++idx) {
- LPFORMATETC destetc = new FORMATETC();
- if (copyFormatEtc(destetc, (LPFORMATETC)&(fmtetcs.at(idx)))) {
- m_lpfmtetcs.append(destetc);
- } else {
- m_isNull = true;
- delete destetc;
- break;
- }
- }
-}
-
-QOleEnumFmtEtc::QOleEnumFmtEtc(const QVector<LPFORMATETC> &lpfmtetcs)
-{
- m_isNull = false;
- m_dwRefs = 1;
- m_nIndex = 0;
-
- for (int idx = 0; idx < lpfmtetcs.count(); ++idx) {
- LPFORMATETC srcetc = lpfmtetcs.at(idx);
- LPFORMATETC destetc = new FORMATETC();
- if (copyFormatEtc(destetc, srcetc)) {
- m_lpfmtetcs.append(destetc);
- } else {
- m_isNull = true;
- delete destetc;
- break;
- }
- }
-}
-
-QOleEnumFmtEtc::~QOleEnumFmtEtc()
-{
- LPMALLOC pmalloc;
-
-#if !defined(Q_OS_WINCE)
- if (CoGetMalloc(MEMCTX_TASK, &pmalloc) == NOERROR) {
-#else
- if (SHGetMalloc(&pmalloc) == NOERROR) {
-#endif
- for (int idx = 0; idx < m_lpfmtetcs.count(); ++idx) {
- LPFORMATETC tmpetc = m_lpfmtetcs.at(idx);
- if (tmpetc->ptd)
- pmalloc->Free(tmpetc->ptd);
- delete tmpetc;
- }
-
- pmalloc->Release();
- }
- m_lpfmtetcs.clear();
-}
-
-bool QOleEnumFmtEtc::isNull() const
-{
- return m_isNull;
-}
-
-// IUnknown methods
-STDMETHODIMP
-QOleEnumFmtEtc::QueryInterface(REFIID riid, void FAR* FAR* ppvObj)
-{
- if (riid == IID_IUnknown || riid == IID_IEnumFORMATETC) {
- *ppvObj = this;
- AddRef();
- return NOERROR;
- }
- *ppvObj = NULL;
- return ResultFromScode(E_NOINTERFACE);
-}
-
-STDMETHODIMP_(ULONG)
-QOleEnumFmtEtc::AddRef(void)
-{
- return ++m_dwRefs;
-}
-
-STDMETHODIMP_(ULONG)
-QOleEnumFmtEtc::Release(void)
-{
- if (--m_dwRefs == 0) {
- delete this;
- return 0;
- }
- return m_dwRefs;
-}
-
-// IEnumFORMATETC methods
-STDMETHODIMP
-QOleEnumFmtEtc::Next(ULONG celt, LPFORMATETC rgelt, ULONG FAR* pceltFetched)
-{
- ULONG i=0;
- ULONG nOffset;
-
- if (rgelt == NULL)
- return ResultFromScode(E_INVALIDARG);
-
- while (i < celt) {
- nOffset = m_nIndex + i;
-
- if (nOffset < ULONG(m_lpfmtetcs.count())) {
- copyFormatEtc((LPFORMATETC)&(rgelt[i]), m_lpfmtetcs.at(nOffset));
- i++;
- } else {
- break;
- }
- }
-
- m_nIndex += (WORD)i;
-
- if (pceltFetched != NULL)
- *pceltFetched = i;
-
- if (i != celt)
- return ResultFromScode(S_FALSE);
-
- return NOERROR;
-}
-
-STDMETHODIMP
-QOleEnumFmtEtc::Skip(ULONG celt)
-{
- ULONG i=0;
- ULONG nOffset;
-
- while (i < celt) {
- nOffset = m_nIndex + i;
-
- if (nOffset < ULONG(m_lpfmtetcs.count())) {
- i++;
- } else {
- break;
- }
- }
-
- m_nIndex += (WORD)i;
-
- if (i != celt)
- return ResultFromScode(S_FALSE);
-
- return NOERROR;
-}
-
-STDMETHODIMP
-QOleEnumFmtEtc::Reset()
-{
- m_nIndex = 0;
- return NOERROR;
-}
-
-STDMETHODIMP
-QOleEnumFmtEtc::Clone(LPENUMFORMATETC FAR* newEnum)
-{
- if (newEnum == NULL)
- return ResultFromScode(E_INVALIDARG);
-
- QOleEnumFmtEtc *result = new QOleEnumFmtEtc(m_lpfmtetcs);
- result->m_nIndex = m_nIndex;
-
- if (result->isNull()) {
- delete result;
- return ResultFromScode(E_OUTOFMEMORY);
- } else {
- *newEnum = result;
- }
-
- return NOERROR;
-}
-
-bool QOleEnumFmtEtc::copyFormatEtc(LPFORMATETC dest, LPFORMATETC src) const
-{
- if (dest == NULL || src == NULL)
- return false;
-
- *dest = *src;
-
- if (src->ptd) {
- LPVOID pout;
- LPMALLOC pmalloc;
-
-#if !defined(Q_OS_WINCE)
- if (CoGetMalloc(MEMCTX_TASK, &pmalloc) != NOERROR)
-#else
- if (SHGetMalloc(&pmalloc) != NOERROR)
-#endif
- return false;
-
- pout = (LPVOID)pmalloc->Alloc(src->ptd->tdSize);
- memcpy(dest->ptd, src->ptd, size_t(src->ptd->tdSize));
-
- pmalloc->Release();
- }
-
- return true;
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_DRAGANDDROP && QT_NO_CLIPBOARD
diff --git a/src/gui/platforms/win/qpaintdevice_win.cpp b/src/gui/platforms/win/qpaintdevice_win.cpp
deleted file mode 100644
index 3dbe97492a..0000000000
--- a/src/gui/platforms/win/qpaintdevice_win.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpaintdevice.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qapplication.h"
-#include <private/qapplication_p.h>
-#include "qt_windows.h"
-#include "qprinter.h"
-
-QT_BEGIN_NAMESPACE
-
-HDC QPaintDevice::getDC() const
-{
- return 0;
-}
-
-void QPaintDevice::releaseDC(HDC) const
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qpixmap_win.cpp b/src/gui/platforms/win/qpixmap_win.cpp
deleted file mode 100644
index 9c14ac7726..0000000000
--- a/src/gui/platforms/win/qpixmap_win.cpp
+++ /dev/null
@@ -1,477 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpixmap.h"
-#include "qpixmap_raster_p.h"
-
-#include "qbitmap.h"
-#include "qimage.h"
-#include "qwidget.h"
-#include "qpainter.h"
-#include "qdatastream.h"
-#include "qbuffer.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qfile.h"
-#include "qfileinfo.h"
-#include "qdatetime.h"
-#include "qpixmapcache.h"
-#include "qimagereader.h"
-#include "qimagewriter.h"
-#include "qdebug.h"
-#include "qt_windows.h"
-
-#if defined(Q_WS_WINCE)
-#include <winbase.h>
-#include "qguifunctions_wince.h"
-extern bool qt_wince_is_high_dpi();
-extern bool qt_wince_is_pocket_pc();
-#endif
-
-#ifndef CAPTUREBLT
-#define CAPTUREBLT ((DWORD)0x40000000)
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QPixmap QPixmap::grabWindow(WId winId, int x, int y, int w, int h )
-{
- RECT r;
- GetClientRect(winId, &r);
-
- if (w < 0) w = r.right - r.left;
- if (h < 0) h = r.bottom - r.top;
-
-#ifdef Q_WS_WINCE_WM
- if (qt_wince_is_pocket_pc()) {
- QWidget *widget = QWidget::find(winId);
- if (qobject_cast<QDesktopWidget *>(widget)) {
- RECT rect = {0,0,0,0};
- AdjustWindowRectEx(&rect, WS_BORDER | WS_CAPTION, FALSE, 0);
- int magicNumber = qt_wince_is_high_dpi() ? 4 : 2;
- y += rect.top - magicNumber;
- }
- }
-#endif
-
- // Create and setup bitmap
- HDC display_dc = GetDC(0);
- HDC bitmap_dc = CreateCompatibleDC(display_dc);
- HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h);
- HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap);
-
- // copy data
- HDC window_dc = GetDC(winId);
- BitBlt(bitmap_dc, 0, 0, w, h, window_dc, x, y, SRCCOPY
-#ifndef Q_WS_WINCE
- | CAPTUREBLT
-#endif
- );
-
- // clean up all but bitmap
- ReleaseDC(winId, window_dc);
- SelectObject(bitmap_dc, null_bitmap);
- DeleteDC(bitmap_dc);
-
- QPixmap pixmap = QPixmap::fromWinHBITMAP(bitmap);
-
- DeleteObject(bitmap);
- ReleaseDC(0, display_dc);
-
- return pixmap;
-}
-
-HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const
-{
- if (isNull())
- return 0;
-
- HBITMAP bitmap = 0;
- if (data->classId() == QPixmapData::RasterClass) {
- QRasterPixmapData* d = static_cast<QRasterPixmapData*>(data.data());
- int w = d->image.width();
- int h = d->image.height();
-
- HDC display_dc = GetDC(0);
-
- // Define the header
- BITMAPINFO bmi;
- memset(&bmi, 0, sizeof(bmi));
- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmi.bmiHeader.biWidth = w;
- bmi.bmiHeader.biHeight = -h;
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
- bmi.bmiHeader.biSizeImage = w * h * 4;
-
- // Create the pixmap
- uchar *pixels = 0;
- bitmap = CreateDIBSection(display_dc, &bmi, DIB_RGB_COLORS, (void **) &pixels, 0, 0);
- ReleaseDC(0, display_dc);
- if (!bitmap) {
- qErrnoWarning("QPixmap::toWinHBITMAP(), failed to create dibsection");
- return 0;
- }
- if (!pixels) {
- qErrnoWarning("QPixmap::toWinHBITMAP(), did not allocate pixel data");
- return 0;
- }
-
- // Copy over the data
- QImage::Format imageFormat = QImage::Format_ARGB32;
- if (format == NoAlpha)
- imageFormat = QImage::Format_RGB32;
- else if (format == PremultipliedAlpha)
- imageFormat = QImage::Format_ARGB32_Premultiplied;
- const QImage image = d->image.convertToFormat(imageFormat);
- int bytes_per_line = w * 4;
- for (int y=0; y<h; ++y)
- memcpy(pixels + y * bytes_per_line, image.scanLine(y), bytes_per_line);
-
- } else {
- QPixmapData *data = new QRasterPixmapData(depth() == 1 ?
- QPixmapData::BitmapType : QPixmapData::PixmapType);
- data->fromImage(toImage(), Qt::AutoColor);
- return QPixmap(data).toWinHBITMAP(format);
- }
- return bitmap;
-}
-
-QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format)
-{
- // Verify size
- BITMAP bitmap_info;
- memset(&bitmap_info, 0, sizeof(BITMAP));
-
- int res = GetObject(bitmap, sizeof(BITMAP), &bitmap_info);
- if (!res) {
- qErrnoWarning("QPixmap::fromWinHBITMAP(), failed to get bitmap info");
- return QPixmap();
- }
- int w = bitmap_info.bmWidth;
- int h = bitmap_info.bmHeight;
-
- BITMAPINFO bmi;
- memset(&bmi, 0, sizeof(bmi));
- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmi.bmiHeader.biWidth = w;
- bmi.bmiHeader.biHeight = -h;
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
- bmi.bmiHeader.biSizeImage = w * h * 4;
-
- QImage result;
- // Get bitmap bits
- uchar *data = (uchar *) qMalloc(bmi.bmiHeader.biSizeImage);
-
- HDC display_dc = GetDC(0);
- if (GetDIBits(display_dc, bitmap, 0, h, data, &bmi, DIB_RGB_COLORS)) {
-
- QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied;
- uint mask = 0;
- if (format == NoAlpha) {
- imageFormat = QImage::Format_RGB32;
- mask = 0xff000000;
- }
-
- // Create image and copy data into image.
- QImage image(w, h, imageFormat);
- if (!image.isNull()) { // failed to alloc?
- int bytes_per_line = w * sizeof(QRgb);
- for (int y=0; y<h; ++y) {
- QRgb *dest = (QRgb *) image.scanLine(y);
- const QRgb *src = (const QRgb *) (data + y * bytes_per_line);
- for (int x=0; x<w; ++x) {
- const uint pixel = src[x];
- if ((pixel & 0xff000000) == 0 && (pixel & 0x00ffffff) != 0)
- dest[x] = pixel | 0xff000000;
- else
- dest[x] = pixel | mask;
- }
- }
- }
- result = image;
- } else {
- qWarning("QPixmap::fromWinHBITMAP(), failed to get bitmap bits");
- }
- ReleaseDC(0, display_dc);
- qFree(data);
- return fromImage(result);
-}
-
-HBITMAP qt_createIconMask(const QBitmap &bitmap)
-{
- QImage bm = bitmap.toImage().convertToFormat(QImage::Format_Mono);
- int w = bm.width();
- int h = bm.height();
- int bpl = ((w+15)/16)*2; // bpl, 16 bit alignment
- uchar *bits = new uchar[bpl*h];
- bm.invertPixels();
- for (int y=0; y<h; y++)
- memcpy(bits+y*bpl, bm.scanLine(y), bpl);
- HBITMAP hbm = CreateBitmap(w, h, 1, 1, bits);
- delete [] bits;
- return hbm;
-}
-
-HICON QPixmap::toWinHICON() const
-{
- QBitmap maskBitmap = mask();
- if (maskBitmap.isNull()) {
- maskBitmap= QBitmap(size());
- maskBitmap.fill(Qt::color1);
- }
-
- ICONINFO ii;
- ii.fIcon = true;
- ii.hbmMask = qt_createIconMask(maskBitmap);
- ii.hbmColor = toWinHBITMAP(QPixmap::Alpha);
- ii.xHotspot = 0;
- ii.yHotspot = 0;
-
- HICON hIcon = CreateIconIndirect(&ii);
-
- DeleteObject(ii.hbmColor);
- DeleteObject(ii.hbmMask);
-
- return hIcon;
-}
-
-#ifdef Q_WS_WIN
-#ifndef Q_WS_WINCE
-
-static QImage qt_fromWinHBITMAP(HDC hdc, HBITMAP bitmap, int w, int h)
-{
- BITMAPINFO bmi;
- memset(&bmi, 0, sizeof(bmi));
- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmi.bmiHeader.biWidth = w;
- bmi.bmiHeader.biHeight = -h;
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
- bmi.bmiHeader.biSizeImage = w * h * 4;
-
- QImage image(w, h, QImage::Format_ARGB32_Premultiplied);
- if (image.isNull())
- return image;
-
- // Get bitmap bits
- uchar *data = (uchar *) qMalloc(bmi.bmiHeader.biSizeImage);
-
- if (GetDIBits(hdc, bitmap, 0, h, data, &bmi, DIB_RGB_COLORS)) {
- // Create image and copy data into image.
- for (int y=0; y<h; ++y) {
- void *dest = (void *) image.scanLine(y);
- void *src = data + y * image.bytesPerLine();
- memcpy(dest, src, image.bytesPerLine());
- }
- } else {
- qWarning("qt_fromWinHBITMAP(), failed to get bitmap bits");
- }
- qFree(data);
-
- return image;
-}
-
-QPixmap QPixmap::fromWinHICON(HICON icon)
-{
- bool foundAlpha = false;
- HDC screenDevice = GetDC(0);
- HDC hdc = CreateCompatibleDC(screenDevice);
- ReleaseDC(0, screenDevice);
-
- ICONINFO iconinfo;
- bool result = GetIconInfo(icon, &iconinfo); //x and y Hotspot describes the icon center
- if (!result)
- qWarning("QPixmap::fromWinHICON(), failed to GetIconInfo()");
-
- int w = iconinfo.xHotspot * 2;
- int h = iconinfo.yHotspot * 2;
-
- BITMAPINFOHEADER bitmapInfo;
- bitmapInfo.biSize = sizeof(BITMAPINFOHEADER);
- bitmapInfo.biWidth = w;
- bitmapInfo.biHeight = h;
- bitmapInfo.biPlanes = 1;
- bitmapInfo.biBitCount = 32;
- bitmapInfo.biCompression = BI_RGB;
- bitmapInfo.biSizeImage = 0;
- bitmapInfo.biXPelsPerMeter = 0;
- bitmapInfo.biYPelsPerMeter = 0;
- bitmapInfo.biClrUsed = 0;
- bitmapInfo.biClrImportant = 0;
- DWORD* bits;
-
- HBITMAP winBitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bitmapInfo, DIB_RGB_COLORS, (VOID**)&bits, NULL, 0);
- HGDIOBJ oldhdc = (HBITMAP)SelectObject(hdc, winBitmap);
- DrawIconEx( hdc, 0, 0, icon, iconinfo.xHotspot * 2, iconinfo.yHotspot * 2, 0, 0, DI_NORMAL);
- QImage image = qt_fromWinHBITMAP(hdc, winBitmap, w, h);
-
- for (int y = 0 ; y < h && !foundAlpha ; y++) {
- QRgb *scanLine= reinterpret_cast<QRgb *>(image.scanLine(y));
- for (int x = 0; x < w ; x++) {
- if (qAlpha(scanLine[x]) != 0) {
- foundAlpha = true;
- break;
- }
- }
- }
- if (!foundAlpha) {
- //If no alpha was found, we use the mask to set alpha values
- DrawIconEx( hdc, 0, 0, icon, w, h, 0, 0, DI_MASK);
- QImage mask = qt_fromWinHBITMAP(hdc, winBitmap, w, h);
-
- for (int y = 0 ; y < h ; y++){
- QRgb *scanlineImage = reinterpret_cast<QRgb *>(image.scanLine(y));
- QRgb *scanlineMask = mask.isNull() ? 0 : reinterpret_cast<QRgb *>(mask.scanLine(y));
- for (int x = 0; x < w ; x++){
- if (scanlineMask && qRed(scanlineMask[x]) != 0)
- scanlineImage[x] = 0; //mask out this pixel
- else
- scanlineImage[x] |= 0xff000000; // set the alpha channel to 255
- }
- }
- }
- //dispose resources created by iconinfo call
- DeleteObject(iconinfo.hbmMask);
- DeleteObject(iconinfo.hbmColor);
-
- SelectObject(hdc, oldhdc); //restore state
- DeleteObject(winBitmap);
- DeleteDC(hdc);
- return QPixmap::fromImage(image);
-}
-#else //ifndef Q_WS_WINCE
-QPixmap QPixmap::fromWinHICON(HICON icon)
-{
- HDC screenDevice = GetDC(0);
- HDC hdc = CreateCompatibleDC(screenDevice);
- ReleaseDC(0, screenDevice);
-
- ICONINFO iconinfo;
- bool result = GetIconInfo(icon, &iconinfo);
- if (!result)
- qWarning("QPixmap::fromWinHICON(), failed to GetIconInfo()");
-
- int w = 0;
- int h = 0;
- if (!iconinfo.xHotspot || !iconinfo.yHotspot) {
- // We could not retrieve the icon size via GetIconInfo,
- // so we try again using the icon bitmap.
- BITMAP bm;
- int result = GetObject(iconinfo.hbmColor, sizeof(BITMAP), &bm);
- if (!result) result = GetObject(iconinfo.hbmMask, sizeof(BITMAP), &bm);
- if (!result) {
- qWarning("QPixmap::fromWinHICON(), failed to retrieve icon size");
- return QPixmap();
- }
- w = bm.bmWidth;
- h = bm.bmHeight;
- } else {
- // x and y Hotspot describes the icon center
- w = iconinfo.xHotspot * 2;
- h = iconinfo.yHotspot * 2;
- }
- const DWORD dwImageSize = w * h * 4;
-
- BITMAPINFO bmi;
- memset(&bmi, 0, sizeof(bmi));
- bmi.bmiHeader.biSize = sizeof(BITMAPINFO);
- bmi.bmiHeader.biWidth = w;
- bmi.bmiHeader.biHeight = -h;
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
- bmi.bmiHeader.biSizeImage = dwImageSize;
-
- uchar* bits;
-
- HBITMAP winBitmap = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, (void**) &bits, 0, 0);
- if (winBitmap )
- memset(bits, 0xff, dwImageSize);
- if (!winBitmap) {
- qWarning("QPixmap::fromWinHICON(), failed to CreateDIBSection()");
- return QPixmap();
- }
-
- HGDIOBJ oldhdc = (HBITMAP)SelectObject(hdc, winBitmap);
- if (!DrawIconEx( hdc, 0, 0, icon, w, h, 0, 0, DI_NORMAL))
- qWarning("QPixmap::fromWinHICON(), failed to DrawIcon()");
-
- uint mask = 0xff000000;
- // Create image and copy data into image.
- QImage image(w, h, QImage::Format_ARGB32);
-
- if (!image.isNull()) { // failed to alloc?
- int bytes_per_line = w * sizeof(QRgb);
- for (int y=0; y < h; ++y) {
- QRgb *dest = (QRgb *) image.scanLine(y);
- const QRgb *src = (const QRgb *) (bits + y * bytes_per_line);
- for (int x=0; x < w; ++x) {
- dest[x] = src[x];
- }
- }
- }
- if (!DrawIconEx( hdc, 0, 0, icon, w, h, 0, 0, DI_MASK))
- qWarning("QPixmap::fromWinHICON(), failed to DrawIcon()");
- if (!image.isNull()) { // failed to alloc?
- int bytes_per_line = w * sizeof(QRgb);
- for (int y=0; y < h; ++y) {
- QRgb *dest = (QRgb *) image.scanLine(y);
- const QRgb *src = (const QRgb *) (bits + y * bytes_per_line);
- for (int x=0; x < w; ++x) {
- if (!src[x])
- dest[x] = dest[x] | mask;
- }
- }
- }
- SelectObject(hdc, oldhdc); //restore state
- DeleteObject(winBitmap);
- DeleteDC(hdc);
- return QPixmap::fromImage(image);
-}
-#endif //ifndef Q_WS_WINCE
-#endif //ifdef Q_WS_WIN
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qprintengine_win.cpp b/src/gui/platforms/win/qprintengine_win.cpp
deleted file mode 100644
index 07d66f5bd0..0000000000
--- a/src/gui/platforms/win/qprintengine_win.cpp
+++ /dev/null
@@ -1,1776 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_PRINTER
-
-#include "qprinter_p.h"
-#include "qprintengine_win_p.h"
-
-#include <limits.h>
-
-#include <private/qfont_p.h>
-#include <private/qfontengine_p.h>
-#include <private/qpainter_p.h>
-
-#include <qbitmap.h>
-#include <qdebug.h>
-#include <qvector.h>
-#include <qpicture.h>
-#include <private/qpicture_p.h>
-
-QT_BEGIN_NAMESPACE
-
-extern QPainterPath qt_regionToPath(const QRegion &region);
-
-// #define QT_DEBUG_DRAW
-
-static void draw_text_item_win(const QPointF &_pos, const QTextItemInt &ti, HDC hdc,
- bool convertToText, const QTransform &xform, const QPointF &topLeft);
-
-static const struct {
- int winSizeName;
- QPrinter::PaperSize qtSizeName;
-} dmMapping[] = {
- { DMPAPER_LETTER, QPrinter::Letter },
- { DMPAPER_LETTERSMALL, QPrinter::Letter },
- { DMPAPER_TABLOID, QPrinter::Tabloid },
- { DMPAPER_LEDGER, QPrinter::Ledger },
- { DMPAPER_LEGAL, QPrinter::Legal },
- { DMPAPER_EXECUTIVE, QPrinter::Executive },
- { DMPAPER_A3, QPrinter::A3 },
- { DMPAPER_A4, QPrinter::A4 },
- { DMPAPER_A4SMALL, QPrinter::A4 },
- { DMPAPER_A5, QPrinter::A5 },
- { DMPAPER_B4, QPrinter::B4 },
- { DMPAPER_B5, QPrinter::B5 },
- { DMPAPER_FOLIO, QPrinter::Folio },
- { DMPAPER_ENV_10, QPrinter::Comm10E },
- { DMPAPER_ENV_DL, QPrinter::DLE },
- { DMPAPER_ENV_C3, QPrinter::C5E },
- { DMPAPER_LETTER_EXTRA, QPrinter::Letter },
- { DMPAPER_LEGAL_EXTRA, QPrinter::Legal },
- { DMPAPER_TABLOID_EXTRA, QPrinter::Tabloid },
- { DMPAPER_A4_EXTRA, QPrinter::A4},
- { DMPAPER_LETTER_TRANSVERSE, QPrinter::Letter},
- { DMPAPER_A4_TRANSVERSE, QPrinter::A4},
- { DMPAPER_LETTER_EXTRA_TRANSVERSE, QPrinter::Letter },
- { DMPAPER_A_PLUS, QPrinter::A4 },
- { DMPAPER_B_PLUS, QPrinter::A3 },
- { DMPAPER_LETTER_PLUS, QPrinter::Letter },
- { DMPAPER_A4_PLUS, QPrinter::A4 },
- { DMPAPER_A5_TRANSVERSE, QPrinter::A5 },
- { DMPAPER_B5_TRANSVERSE, QPrinter::B5 },
- { DMPAPER_A3_EXTRA, QPrinter::A3 },
- { DMPAPER_A5_EXTRA, QPrinter::A5 },
- { DMPAPER_B5_EXTRA, QPrinter::B5 },
- { DMPAPER_A2, QPrinter::A2 },
- { DMPAPER_A3_TRANSVERSE, QPrinter::A3 },
- { DMPAPER_A3_EXTRA_TRANSVERSE,QPrinter::A3 },
- { 0, QPrinter::Custom }
-};
-
-QPrinter::PaperSize mapDevmodePaperSize(int s)
-{
- int i = 0;
- while ((dmMapping[i].winSizeName > 0) && (dmMapping[i].winSizeName != s))
- i++;
- return dmMapping[i].qtSizeName;
-}
-
-static int mapPaperSizeDevmode(QPrinter::PaperSize s)
-{
- int i = 0;
- while ((dmMapping[i].winSizeName > 0) && (dmMapping[i].qtSizeName != s))
- i++;
- return dmMapping[i].winSizeName;
-}
-
-static const struct {
- int winSourceName;
- QPrinter::PaperSource qtSourceName;
-} sources[] = {
- { DMBIN_ONLYONE, QPrinter::OnlyOne },
- { DMBIN_LOWER, QPrinter::Lower },
- { DMBIN_MIDDLE, QPrinter::Middle },
- { DMBIN_MANUAL, QPrinter::Manual },
- { DMBIN_ENVELOPE, QPrinter::Envelope },
- { DMBIN_ENVMANUAL, QPrinter::EnvelopeManual },
- { DMBIN_AUTO, QPrinter::Auto },
- { DMBIN_TRACTOR, QPrinter::Tractor },
- { DMBIN_SMALLFMT, QPrinter::SmallFormat },
- { DMBIN_LARGEFMT, QPrinter::LargeFormat },
- { DMBIN_LARGECAPACITY, QPrinter::LargeCapacity },
- { DMBIN_CASSETTE, QPrinter::Cassette },
- { DMBIN_FORMSOURCE, QPrinter::FormSource },
- { 0, (QPrinter::PaperSource) -1 }
-};
-
-static QPrinter::PaperSource mapDevmodePaperSource(int s)
-{
- int i = 0;
- while ((sources[i].winSourceName > 0) && (sources[i].winSourceName != s))
- i++;
- return sources[i].winSourceName ? sources[i].qtSourceName : (QPrinter::PaperSource) s;
-}
-
-static int mapPaperSourceDevmode(QPrinter::PaperSource s)
-{
- int i = 0;
- while ((sources[i].qtSourceName >= 0) && (sources[i].qtSourceName != s))
- i++;
- return sources[i].winSourceName ? sources[i].winSourceName : s;
-}
-
-QWin32PrintEngine::QWin32PrintEngine(QPrinter::PrinterMode mode)
- : QAlphaPaintEngine(*(new QWin32PrintEnginePrivate),
- PaintEngineFeatures(PrimitiveTransform
- | PixmapTransform
- | PerspectiveTransform
- | PainterPaths
- | Antialiasing
- | PaintOutsidePaintEvent))
-{
- Q_D(QWin32PrintEngine);
- d->docName = QLatin1String("document1");
- d->mode = mode;
- d->queryDefault();
- d->initialize();
-}
-
-bool QWin32PrintEngine::begin(QPaintDevice *pdev)
-{
- Q_D(QWin32PrintEngine);
-
- QAlphaPaintEngine::begin(pdev);
- if (!continueCall())
- return true;
-
- if (d->reinit) {
- d->resetDC();
- d->reinit = false;
- }
-
- // ### set default colors and stuff...
-
- bool ok = d->state == QPrinter::Idle;
-
- if (!d->hdc)
- return false;
-
- // Assign the FILE: to get the query...
- if (d->printToFile && d->fileName.isEmpty())
- d->fileName = d->port;
-
- d->devMode->dmCopies = d->num_copies;
-
- DOCINFO di;
- memset(&di, 0, sizeof(DOCINFO));
- di.cbSize = sizeof(DOCINFO);
- di.lpszDocName = reinterpret_cast<const wchar_t *>(d->docName.utf16());
- if (d->printToFile && !d->fileName.isEmpty())
- di.lpszOutput = reinterpret_cast<const wchar_t *>(d->fileName.utf16());
- if (ok && StartDoc(d->hdc, &di) == SP_ERROR) {
- qErrnoWarning("QWin32PrintEngine::begin: StartDoc failed");
- ok = false;
- }
-
- if (StartPage(d->hdc) <= 0) {
- qErrnoWarning("QWin32PrintEngine::begin: StartPage failed");
- ok = false;
- }
-
- if (!ok) {
- d->state = QPrinter::Idle;
- } else {
- d->state = QPrinter::Active;
- }
-
- d->matrix = QTransform();
- d->has_pen = true;
- d->pen = QColor(Qt::black);
- d->has_brush = false;
-
- d->complex_xform = false;
-
- updateMatrix(d->matrix);
-
- if (!ok)
- cleanUp();
-
- return ok;
-}
-
-bool QWin32PrintEngine::end()
-{
- Q_D(QWin32PrintEngine);
-
- if (d->hdc) {
- if (d->state == QPrinter::Aborted) {
- cleanUp();
- AbortDoc(d->hdc);
- return true;
- }
- }
-
- QAlphaPaintEngine::end();
- if (!continueCall())
- return true;
-
- if (d->hdc) {
- EndPage(d->hdc); // end; printing done
- EndDoc(d->hdc);
- }
-
- d->state = QPrinter::Idle;
- d->reinit = true;
- return true;
-}
-
-bool QWin32PrintEngine::newPage()
-{
- Q_D(QWin32PrintEngine);
- Q_ASSERT(isActive());
-
- Q_ASSERT(d->hdc);
-
- flushAndInit();
-
- bool transparent = GetBkMode(d->hdc) == TRANSPARENT;
-
- if (!EndPage(d->hdc)) {
- qErrnoWarning("QWin32PrintEngine::newPage: EndPage failed");
- return false;
- }
-
- if (d->reinit) {
- if (!d->resetDC()) {
- qErrnoWarning("QWin32PrintEngine::newPage: ResetDC failed");
- return false;
- }
- d->reinit = false;
- }
-
- if (!StartPage(d->hdc)) {
- qErrnoWarning("Win32PrintEngine::newPage: StartPage failed");
- return false;
- }
-
- SetTextAlign(d->hdc, TA_BASELINE);
- if (transparent)
- SetBkMode(d->hdc, TRANSPARENT);
-
- // ###
- return true;
-
- bool success = false;
- if (d->hdc && d->state == QPrinter::Active) {
- if (EndPage(d->hdc) != SP_ERROR) {
- // reinitialize the DC before StartPage if needed,
- // because resetdc is disabled between calls to the StartPage and EndPage functions
- // (see StartPage documentation in the Platform SDK:Windows GDI)
-// state = PST_ACTIVEDOC;
-// reinit();
-// state = PST_ACTIVE;
- // start the new page now
- if (d->reinit) {
- if (!d->resetDC())
- qErrnoWarning("QWin32PrintEngine::newPage(), ResetDC failed (2)");
- d->reinit = false;
- }
- success = (StartPage(d->hdc) != SP_ERROR);
- }
- if (!success) {
- d->state = QPrinter::Aborted;
- return false;
- }
- }
- return true;
-}
-
-bool QWin32PrintEngine::abort()
-{
- // do nothing loop.
- return false;
-}
-
-void QWin32PrintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
-{
- Q_D(const QWin32PrintEngine);
-
- QAlphaPaintEngine::drawTextItem(p, textItem);
- if (!continueCall())
- return;
-
- const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
- QRgb brushColor = state->pen().brush().color().rgb();
- bool fallBack = state->pen().brush().style() != Qt::SolidPattern
- || qAlpha(brushColor) != 0xff
- || d->txop >= QTransform::TxProject
- || ti.fontEngine->type() != QFontEngine::Win;
-
-
- if (!fallBack) {
- QFontEngineWin *fe = static_cast<QFontEngineWin *>(ti.fontEngine);
-
- // Try selecting the font to see if we get a substitution font
- SelectObject(d->hdc, fe->hfont);
-
- if (GetDeviceCaps(d->hdc, TECHNOLOGY) != DT_CHARSTREAM) {
- wchar_t n[64];
- GetTextFace(d->hdc, 64, n);
- fallBack = QString::fromWCharArray(n)
- != QString::fromWCharArray(fe->logfont.lfFaceName);
- }
- }
-
-
- if (fallBack) {
- QPaintEngine::drawTextItem(p, textItem);
- return ;
- }
-
- // We only want to convert the glyphs to text if the entire string is compatible with ASCII
- // and if we actually have access to the chars.
- bool convertToText = ti.chars != 0;
- for (int i=0; i < ti.num_chars; ++i) {
- if (ti.chars[i].unicode() >= 0x80) {
- convertToText = false;
- break;
- }
-
- if (ti.logClusters[i] != i) {
- convertToText = false;
- break;
- }
- }
-
- COLORREF cf = RGB(qRed(brushColor), qGreen(brushColor), qBlue(brushColor));
- SelectObject(d->hdc, CreateSolidBrush(cf));
- SelectObject(d->hdc, CreatePen(PS_SOLID, 1, cf));
- SetTextColor(d->hdc, cf);
-
- draw_text_item_win(p, ti, d->hdc, convertToText, d->matrix, d->devPaperRect.topLeft());
- DeleteObject(SelectObject(d->hdc,GetStockObject(HOLLOW_BRUSH)));
- DeleteObject(SelectObject(d->hdc,GetStockObject(BLACK_PEN)));
-}
-
-static inline qreal mmToInches(double mm)
-{
- return mm*0.039370147;
-}
-
-static inline qreal inchesToMM(double in)
-{
- return in/0.039370147;
-}
-
-int QWin32PrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
-{
- Q_D(const QWin32PrintEngine);
-
- if (!d->hdc)
- return 0;
-
- int val;
- int res = d->resolution;
-
- switch (m) {
- case QPaintDevice::PdmWidth:
- if (d->has_custom_paper_size) {
- val = qRound(d->paper_size.width() * res / 72.0);
- } else {
- int logPixelsX = GetDeviceCaps(d->hdc, LOGPIXELSX);
- if (logPixelsX == 0) {
- qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
- "might be a driver problem");
- logPixelsX = 600; // Reasonable default
- }
- val = res
- * GetDeviceCaps(d->hdc, d->fullPage ? PHYSICALWIDTH : HORZRES)
- / logPixelsX;
- }
- if (d->pageMarginsSet)
- val -= int(mmToInches((d->previousDialogMargins.left() +
- d->previousDialogMargins.width()) / 100.0) * res);
- break;
- case QPaintDevice::PdmHeight:
- if (d->has_custom_paper_size) {
- val = qRound(d->paper_size.height() * res / 72.0);
- } else {
- int logPixelsY = GetDeviceCaps(d->hdc, LOGPIXELSY);
- if (logPixelsY == 0) {
- qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
- "might be a driver problem");
- logPixelsY = 600; // Reasonable default
- }
- val = res
- * GetDeviceCaps(d->hdc, d->fullPage ? PHYSICALHEIGHT : VERTRES)
- / logPixelsY;
- }
- if (d->pageMarginsSet)
- val -= int(mmToInches((d->previousDialogMargins.top() +
- d->previousDialogMargins.height()) / 100.0) * res);
- break;
- case QPaintDevice::PdmDpiX:
- val = res;
- break;
- case QPaintDevice::PdmDpiY:
- val = res;
- break;
- case QPaintDevice::PdmPhysicalDpiX:
- val = GetDeviceCaps(d->hdc, LOGPIXELSX);
- break;
- case QPaintDevice::PdmPhysicalDpiY:
- val = GetDeviceCaps(d->hdc, LOGPIXELSY);
- break;
- case QPaintDevice::PdmWidthMM:
- if (d->has_custom_paper_size) {
- val = qRound(d->paper_size.width()*25.4/72);
- } else {
- if (!d->fullPage) {
- val = GetDeviceCaps(d->hdc, HORZSIZE);
- } else {
- float wi = 25.4 * GetDeviceCaps(d->hdc, PHYSICALWIDTH);
- int logPixelsX = GetDeviceCaps(d->hdc, LOGPIXELSX);
- if (logPixelsX == 0) {
- qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
- "might be a driver problem");
- logPixelsX = 600; // Reasonable default
- }
- val = qRound(wi / logPixelsX);
- }
- }
- if (d->pageMarginsSet)
- val -= (d->previousDialogMargins.left() +
- d->previousDialogMargins.width()) / 100.0;
- break;
- case QPaintDevice::PdmHeightMM:
- if (d->has_custom_paper_size) {
- val = qRound(d->paper_size.height()*25.4/72);
- } else {
- if (!d->fullPage) {
- val = GetDeviceCaps(d->hdc, VERTSIZE);
- } else {
- float hi = 25.4 * GetDeviceCaps(d->hdc, PHYSICALHEIGHT);
- int logPixelsY = GetDeviceCaps(d->hdc, LOGPIXELSY);
- if (logPixelsY == 0) {
- qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
- "might be a driver problem");
- logPixelsY = 600; // Reasonable default
- }
- val = qRound(hi / logPixelsY);
- }
- }
- if (d->pageMarginsSet)
- val -= (d->previousDialogMargins.top() +
- d->previousDialogMargins.height()) / 100.0;
- break;
- case QPaintDevice::PdmNumColors:
- {
- int bpp = GetDeviceCaps(d->hdc, BITSPIXEL);
- if(bpp==32)
- val = INT_MAX;
- else if(bpp<=8)
- val = GetDeviceCaps(d->hdc, NUMCOLORS);
- else
- val = 1 << (bpp * GetDeviceCaps(d->hdc, PLANES));
- }
- break;
- case QPaintDevice::PdmDepth:
- val = GetDeviceCaps(d->hdc, PLANES);
- break;
- default:
- qWarning("QPrinter::metric: Invalid metric command");
- return 0;
- }
- return val;
-}
-
-void QWin32PrintEngine::updateState(const QPaintEngineState &state)
-{
- Q_D(QWin32PrintEngine);
-
- QAlphaPaintEngine::updateState(state);
- if (!continueCall())
- return;
-
- if (state.state() & DirtyTransform) {
- updateMatrix(state.transform());
- }
-
- if (state.state() & DirtyPen) {
- d->pen = state.pen();
- d->has_pen = d->pen.style() != Qt::NoPen && d->pen.isSolid();
- }
-
- if (state.state() & DirtyBrush) {
- QBrush brush = state.brush();
- d->has_brush = brush.style() == Qt::SolidPattern;
- d->brush_color = brush.color();
- }
-
- if (state.state() & DirtyClipEnabled) {
- if (state.isClipEnabled())
- updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
- else
- updateClipPath(QPainterPath(), Qt::NoClip);
- }
-
- if (state.state() & DirtyClipPath) {
- updateClipPath(state.clipPath(), state.clipOperation());
- }
-
- if (state.state() & DirtyClipRegion) {
- QRegion clipRegion = state.clipRegion();
- QPainterPath clipPath = qt_regionToPath(clipRegion);
- updateClipPath(clipPath, state.clipOperation());
- }
-}
-
-void QWin32PrintEngine::updateClipPath(const QPainterPath &clipPath, Qt::ClipOperation op)
-{
- Q_D(QWin32PrintEngine);
-
- bool doclip = true;
- if (op == Qt::NoClip) {
- SelectClipRgn(d->hdc, 0);
- doclip = false;
- }
-
- if (doclip) {
- QPainterPath xformed = clipPath * d->matrix;
-
- if (xformed.isEmpty()) {
- QRegion empty(-0x1000000, -0x1000000, 1, 1);
- SelectClipRgn(d->hdc, empty.handle());
- } else {
- d->composeGdiPath(xformed);
- const int ops[] = {
- -1, // Qt::NoClip, covered above
- RGN_COPY, // Qt::ReplaceClip
- RGN_AND, // Qt::IntersectClip
- RGN_OR // Qt::UniteClip
- };
- Q_ASSERT(op > 0 && unsigned(op) <= sizeof(ops) / sizeof(int));
- SelectClipPath(d->hdc, ops[op]);
- }
- }
-
- QPainterPath aclip = qt_regionToPath(alphaClipping());
- if (!aclip.isEmpty()) {
- QTransform tx(d->stretch_x, 0, 0, d->stretch_y, d->origin_x, d->origin_y);
- d->composeGdiPath(tx.map(aclip));
- SelectClipPath(d->hdc, RGN_DIFF);
- }
-}
-
-void QWin32PrintEngine::updateMatrix(const QTransform &m)
-{
- Q_D(QWin32PrintEngine);
-
- QTransform stretch(d->stretch_x, 0, 0, d->stretch_y, d->origin_x, d->origin_y);
- d->painterMatrix = m;
- d->matrix = d->painterMatrix * stretch;
- d->txop = d->matrix.type();
- d->complex_xform = (d->txop > QTransform::TxScale);
-}
-
-void QWin32PrintEngine::drawPixmap(const QRectF &targetRect,
- const QPixmap &originalPixmap,
- const QRectF &sourceRect)
-{
- Q_D(QWin32PrintEngine);
-
- QAlphaPaintEngine::drawPixmap(targetRect, originalPixmap, sourceRect);
- if (!continueCall())
- return;
-
- const int tileSize = 2048;
-
- QRectF r = targetRect;
- QRectF sr = sourceRect;
-
- QPixmap pixmap = originalPixmap;
- if (sr.size() != pixmap.size()) {
- pixmap = pixmap.copy(sr.toRect());
- }
-
- qreal scaleX = 1.0f;
- qreal scaleY = 1.0f;
-
- QTransform scaleMatrix = QTransform::fromScale(r.width() / pixmap.width(), r.height() / pixmap.height());
- QTransform adapted = QPixmap::trueMatrix(d->painterMatrix * scaleMatrix,
- pixmap.width(), pixmap.height());
-
- qreal xform_offset_x = adapted.dx();
- qreal xform_offset_y = adapted.dy();
-
- if (d->complex_xform) {
- pixmap = pixmap.transformed(adapted);
- scaleX = d->stretch_x;
- scaleY = d->stretch_y;
- } else {
- scaleX = d->stretch_x * (r.width() / pixmap.width()) * d->painterMatrix.m11();
- scaleY = d->stretch_y * (r.height() / pixmap.height()) * d->painterMatrix.m22();
- }
-
- QPointF topLeft = r.topLeft() * d->painterMatrix;
- int tx = int(topLeft.x() * d->stretch_x + d->origin_x);
- int ty = int(topLeft.y() * d->stretch_y + d->origin_y);
- int tw = qAbs(int(pixmap.width() * scaleX));
- int th = qAbs(int(pixmap.height() * scaleY));
-
- xform_offset_x *= d->stretch_x;
- xform_offset_y *= d->stretch_y;
-
- int dc_state = SaveDC(d->hdc);
-
- int tilesw = pixmap.width() / tileSize;
- int tilesh = pixmap.height() / tileSize;
- ++tilesw;
- ++tilesh;
-
- int txinc = tileSize*scaleX;
- int tyinc = tileSize*scaleY;
-
- for (int y = 0; y < tilesh; ++y) {
- int tposy = ty + (y * tyinc);
- int imgh = tileSize;
- int height = tyinc;
- if (y == (tilesh - 1)) {
- imgh = pixmap.height() - (y * tileSize);
- height = (th - (y * tyinc));
- }
- for (int x = 0; x < tilesw; ++x) {
- int tposx = tx + (x * txinc);
- int imgw = tileSize;
- int width = txinc;
- if (x == (tilesw - 1)) {
- imgw = pixmap.width() - (x * tileSize);
- width = (tw - (x * txinc));
- }
-
- QPixmap p = pixmap.copy(tileSize * x, tileSize * y, imgw, imgh);
- HBITMAP hbitmap = p.toWinHBITMAP(QPixmap::NoAlpha);
- HDC display_dc = GetDC(0);
- HDC hbitmap_hdc = CreateCompatibleDC(display_dc);
- HGDIOBJ null_bitmap = SelectObject(hbitmap_hdc, hbitmap);
-
- ReleaseDC(0, display_dc);
-
- if (!StretchBlt(d->hdc, qRound(tposx - xform_offset_x), qRound(tposy - xform_offset_y), width, height,
- hbitmap_hdc, 0, 0, p.width(), p.height(), SRCCOPY))
- qErrnoWarning("QWin32PrintEngine::drawPixmap, StretchBlt failed");
-
- SelectObject(hbitmap_hdc, null_bitmap);
- DeleteObject(hbitmap);
- DeleteDC(hbitmap_hdc);
- }
- }
-
- RestoreDC(d->hdc, dc_state);
-}
-
-
-void QWin32PrintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &pos)
-{
- Q_D(QWin32PrintEngine);
-
- QAlphaPaintEngine::drawTiledPixmap(r, pm, pos);
- if (!continueCall())
- return;
-
- if (d->complex_xform || !pos.isNull()) {
- QPaintEngine::drawTiledPixmap(r, pm, pos);
- } else {
- int dc_state = SaveDC(d->hdc);
-
- HDC display_dc = GetDC(0);
- HBITMAP hbitmap = pm.toWinHBITMAP(QPixmap::NoAlpha);
- HDC hbitmap_hdc = CreateCompatibleDC(display_dc);
- HGDIOBJ null_bitmap = SelectObject(hbitmap_hdc, hbitmap);
-
- ReleaseDC(0, display_dc);
-
- QRectF trect = d->painterMatrix.mapRect(r);
- int tx = int(trect.left() * d->stretch_x + d->origin_x);
- int ty = int(trect.top() * d->stretch_y + d->origin_y);
-
- int xtiles = int(trect.width() / pm.width()) + 1;
- int ytiles = int(trect.height() / pm.height()) + 1;
- int xinc = int(pm.width() * d->stretch_x);
- int yinc = int(pm.height() * d->stretch_y);
-
- for (int y = 0; y < ytiles; ++y) {
- int ity = ty + (yinc * y);
- int ith = pm.height();
- if (y == (ytiles - 1)) {
- ith = int(trect.height() - (pm.height() * y));
- }
-
- for (int x = 0; x < xtiles; ++x) {
- int itx = tx + (xinc * x);
- int itw = pm.width();
- if (x == (xtiles - 1)) {
- itw = int(trect.width() - (pm.width() * x));
- }
-
- if (!StretchBlt(d->hdc, itx, ity, int(itw * d->stretch_x), int(ith * d->stretch_y),
- hbitmap_hdc, 0, 0, itw, ith, SRCCOPY))
- qErrnoWarning("QWin32PrintEngine::drawPixmap, StretchBlt failed");
-
- }
- }
-
- SelectObject(hbitmap_hdc, null_bitmap);
- DeleteObject(hbitmap);
- DeleteDC(hbitmap_hdc);
-
- RestoreDC(d->hdc, dc_state);
- }
-}
-
-
-void QWin32PrintEnginePrivate::composeGdiPath(const QPainterPath &path)
-{
- if (!BeginPath(hdc))
- qErrnoWarning("QWin32PrintEnginePrivate::drawPath: BeginPath failed");
-
- // Drawing the subpaths
- int start = -1;
- for (int i=0; i<path.elementCount(); ++i) {
- const QPainterPath::Element &elm = path.elementAt(i);
- switch (elm.type) {
- case QPainterPath::MoveToElement:
- if (start >= 0
- && path.elementAt(start).x == path.elementAt(i-1).x
- && path.elementAt(start).y == path.elementAt(i-1).y)
- CloseFigure(hdc);
- start = i;
- MoveToEx(hdc, qRound(elm.x), qRound(elm.y), 0);
- break;
- case QPainterPath::LineToElement:
- LineTo(hdc, qRound(elm.x), qRound(elm.y));
- break;
- case QPainterPath::CurveToElement: {
- POINT pts[3] = {
- { qRound(elm.x), qRound(elm.y) },
- { qRound(path.elementAt(i+1).x), qRound(path.elementAt(i+1).y) },
- { qRound(path.elementAt(i+2).x), qRound(path.elementAt(i+2).y) }
- };
- i+=2;
- PolyBezierTo(hdc, pts, 3);
- break;
- }
- default:
- qFatal("QWin32PaintEngine::drawPath: Unhandled type: %d", elm.type);
- }
- }
-
- if (start >= 0
- && path.elementAt(start).x == path.elementAt(path.elementCount()-1).x
- && path.elementAt(start).y == path.elementAt(path.elementCount()-1).y)
- CloseFigure(hdc);
-
- if (!EndPath(hdc))
- qErrnoWarning("QWin32PaintEngine::drawPath: EndPath failed");
-
- SetPolyFillMode(hdc, path.fillRule() == Qt::WindingFill ? WINDING : ALTERNATE);
-}
-
-
-void QWin32PrintEnginePrivate::fillPath_dev(const QPainterPath &path, const QColor &color)
-{
-#ifdef QT_DEBUG_DRAW
- qDebug() << " --- QWin32PrintEnginePrivate::fillPath() bound:" << path.boundingRect() << color;
-#endif
-
- composeGdiPath(path);
-
- HBRUSH brush = CreateSolidBrush(RGB(color.red(), color.green(), color.blue()));
- HGDIOBJ old_brush = SelectObject(hdc, brush);
- FillPath(hdc);
- DeleteObject(SelectObject(hdc, old_brush));
-}
-
-void QWin32PrintEnginePrivate::strokePath_dev(const QPainterPath &path, const QColor &color, qreal penWidth)
-{
- composeGdiPath(path);
- LOGBRUSH brush;
- brush.lbStyle = BS_SOLID;
- brush.lbColor = RGB(color.red(), color.green(), color.blue());
- DWORD capStyle = PS_ENDCAP_SQUARE;
- DWORD joinStyle = PS_JOIN_BEVEL;
- if (pen.capStyle() == Qt::FlatCap)
- capStyle = PS_ENDCAP_FLAT;
- else if (pen.capStyle() == Qt::RoundCap)
- capStyle = PS_ENDCAP_ROUND;
-
- if (pen.joinStyle() == Qt::MiterJoin)
- joinStyle = PS_JOIN_MITER;
- else if (pen.joinStyle() == Qt::RoundJoin)
- joinStyle = PS_JOIN_ROUND;
-
- HPEN pen = ExtCreatePen(((penWidth == 0) ? PS_COSMETIC : PS_GEOMETRIC)
- | PS_SOLID | capStyle | joinStyle,
- (penWidth == 0) ? 1 : penWidth, &brush, 0, 0);
-
- HGDIOBJ old_pen = SelectObject(hdc, pen);
- StrokePath(hdc);
- DeleteObject(SelectObject(hdc, old_pen));
-}
-
-
-void QWin32PrintEnginePrivate::fillPath(const QPainterPath &path, const QColor &color)
-{
- fillPath_dev(path * matrix, color);
-}
-
-void QWin32PrintEnginePrivate::strokePath(const QPainterPath &path, const QColor &color)
-{
- QPainterPathStroker stroker;
- if (pen.style() == Qt::CustomDashLine) {
- stroker.setDashPattern(pen.dashPattern());
- stroker.setDashOffset(pen.dashOffset());
- } else {
- stroker.setDashPattern(pen.style());
- }
- stroker.setCapStyle(pen.capStyle());
- stroker.setJoinStyle(pen.joinStyle());
- stroker.setMiterLimit(pen.miterLimit());
-
- QPainterPath stroke;
- qreal width = pen.widthF();
- if (pen.style() == Qt::SolidLine && (pen.isCosmetic() || matrix.type() < QTransform::TxScale)) {
- strokePath_dev(path * matrix, color, width);
- } else {
- stroker.setWidth(width);
- if (pen.isCosmetic()) {
- stroke = stroker.createStroke(path * matrix);
- } else {
- stroke = stroker.createStroke(path) * painterMatrix;
- QTransform stretch(stretch_x, 0, 0, stretch_y, origin_x, origin_y);
- stroke = stroke * stretch;
- }
-
- if (stroke.isEmpty())
- return;
-
- fillPath_dev(stroke, color);
- }
-}
-
-
-void QWin32PrintEngine::drawPath(const QPainterPath &path)
-{
-#ifdef QT_DEBUG_DRAW
- qDebug() << " - QWin32PrintEngine::drawPath(), bounds: " << path.boundingRect();
-#endif
-
- Q_D(QWin32PrintEngine);
-
- QAlphaPaintEngine::drawPath(path);
- if (!continueCall())
- return;
-
- if (d->has_brush)
- d->fillPath(path, d->brush_color);
-
- if (d->has_pen)
- d->strokePath(path, d->pen.color());
-}
-
-
-void QWin32PrintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
-{
-#ifdef QT_DEBUG_DRAW
- qDebug() << " - QWin32PrintEngine::drawPolygon(), pointCount: " << pointCount;
-#endif
-
- QAlphaPaintEngine::drawPolygon(points, pointCount, mode);
- if (!continueCall())
- return;
-
- Q_ASSERT(pointCount > 1);
-
- QPainterPath path(points[0]);
-
- for (int i=1; i<pointCount; ++i) {
- path.lineTo(points[i]);
- }
-
- Q_D(QWin32PrintEngine);
-
- bool has_brush = d->has_brush;
-
- if (mode == PolylineMode)
- d->has_brush = false; // No brush for polylines
- else
- path.closeSubpath(); // polygons are should always be closed.
-
- drawPath(path);
- d->has_brush = has_brush;
-}
-
-void QWin32PrintEnginePrivate::queryDefault()
-{
- /* Read the default printer name, driver and port with the intuitive function
- * Strings "windows" and "device" are specified in the MSDN under EnumPrinters()
- */
- QString noPrinters(QLatin1String("qt_no_printers"));
- wchar_t buffer[256];
- GetProfileString(L"windows", L"device",
- reinterpret_cast<const wchar_t *>(noPrinters.utf16()),
- buffer, 256);
- QString output = QString::fromWCharArray(buffer);
- if (output.isEmpty() || output == noPrinters) // no printers
- return;
-
- QStringList info = output.split(QLatin1Char(','));
- int infoSize = info.size();
- if (infoSize > 0) {
- if (name.isEmpty())
- name = info.at(0);
- if (program.isEmpty() && infoSize > 1)
- program = info.at(1);
- if (port.isEmpty() && infoSize > 2)
- port = info.at(2);
- }
-}
-
-QWin32PrintEnginePrivate::~QWin32PrintEnginePrivate()
-{
- if (hdc)
- release();
-}
-
-void QWin32PrintEnginePrivate::initialize()
-{
- if (hdc)
- release();
- Q_ASSERT(!hPrinter);
- Q_ASSERT(!hdc);
- Q_ASSERT(!devMode);
- Q_ASSERT(!pInfo);
-
- if (name.isEmpty())
- return;
-
- txop = QTransform::TxNone;
-
- bool ok = OpenPrinter((LPWSTR)name.utf16(), (LPHANDLE)&hPrinter, 0);
- if (!ok) {
- qErrnoWarning("QWin32PrintEngine::initialize: OpenPrinter failed");
- return;
- }
-
- // Fetch the PRINTER_INFO_2 with DEVMODE data containing the
- // printer settings.
- DWORD infoSize, numBytes;
- GetPrinter(hPrinter, 2, NULL, 0, &infoSize);
- hMem = GlobalAlloc(GHND, infoSize);
- pInfo = (PRINTER_INFO_2*) GlobalLock(hMem);
- ok = GetPrinter(hPrinter, 2, (LPBYTE)pInfo, infoSize, &numBytes);
-
- if (!ok) {
- qErrnoWarning("QWin32PrintEngine::initialize: GetPrinter failed");
- GlobalUnlock(pInfo);
- GlobalFree(hMem);
- ClosePrinter(hPrinter);
- pInfo = 0;
- hMem = 0;
- hPrinter = 0;
- return;
- }
-
- devMode = pInfo->pDevMode;
- hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()),
- reinterpret_cast<const wchar_t *>(name.utf16()), 0, devMode);
-
- Q_ASSERT(hPrinter);
- Q_ASSERT(pInfo);
-
- if (devMode) {
- num_copies = devMode->dmCopies;
- }
-
- initHDC();
-
-#ifdef QT_DEBUG_DRAW
- qDebug() << "QWin32PrintEngine::initialize()" << endl
- << " - paperRect" << devPaperRect << endl
- << " - pageRect" << devPageRect << endl
- << " - stretch_x" << stretch_x << endl
- << " - stretch_y" << stretch_y << endl
- << " - origin_x" << origin_x << endl
- << " - origin_y" << origin_y << endl;
-#endif
-}
-
-void QWin32PrintEnginePrivate::initHDC()
-{
- Q_ASSERT(hdc);
-
- HDC display_dc = GetDC(0);
- dpi_x = GetDeviceCaps(hdc, LOGPIXELSX);
- dpi_y = GetDeviceCaps(hdc, LOGPIXELSY);
- dpi_display = GetDeviceCaps(display_dc, LOGPIXELSY);
- ReleaseDC(0, display_dc);
- if (dpi_display == 0) {
- qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
- "might be a driver problem");
- dpi_display = 96; // Reasonable default
- }
-
- switch(mode) {
- case QPrinter::ScreenResolution:
- resolution = dpi_display;
- stretch_x = dpi_x / double(dpi_display);
- stretch_y = dpi_y / double(dpi_display);
- break;
- case QPrinter::PrinterResolution:
- case QPrinter::HighResolution:
- resolution = dpi_y;
- stretch_x = 1;
- stretch_y = 1;
- break;
- default:
- break;
- }
-
- initDevRects();
-}
-
-void QWin32PrintEnginePrivate::initDevRects()
-{
- devPaperRect = QRect(0, 0,
- GetDeviceCaps(hdc, PHYSICALWIDTH),
- GetDeviceCaps(hdc, PHYSICALHEIGHT));
- devPhysicalPageRect = QRect(GetDeviceCaps(hdc, PHYSICALOFFSETX),
- GetDeviceCaps(hdc, PHYSICALOFFSETY),
- GetDeviceCaps(hdc, HORZRES),
- GetDeviceCaps(hdc, VERTRES));
- if (!pageMarginsSet)
- devPageRect = devPhysicalPageRect;
- else
- devPageRect = devPaperRect.adjusted(qRound(mmToInches(previousDialogMargins.left() / 100.0) * dpi_x),
- qRound(mmToInches(previousDialogMargins.top() / 100.0) * dpi_y),
- -qRound(mmToInches(previousDialogMargins.width() / 100.0) * dpi_x),
- -qRound(mmToInches(previousDialogMargins.height() / 100.0) * dpi_y));
- updateOrigin();
-}
-
-void QWin32PrintEnginePrivate::setPageMargins(int marginLeft, int marginTop, int marginRight, int marginBottom)
-{
- pageMarginsSet = true;
- previousDialogMargins = QRect(marginLeft, marginTop, marginRight, marginBottom);
-
- devPageRect = devPaperRect.adjusted(qRound(mmToInches(marginLeft / 100.0) * dpi_x),
- qRound(mmToInches(marginTop / 100.0) * dpi_y),
- - qRound(mmToInches(marginRight / 100.0) * dpi_x),
- - qRound(mmToInches(marginBottom / 100.0) * dpi_y));
- updateOrigin();
-}
-
-QRect QWin32PrintEnginePrivate::getPageMargins() const
-{
- if (pageMarginsSet)
- return previousDialogMargins;
- else
- return QRect(qRound(inchesToMM(devPhysicalPageRect.left()) * 100.0 / dpi_x),
- qRound(inchesToMM(devPhysicalPageRect.top()) * 100.0 / dpi_y),
- qRound(inchesToMM(devPaperRect.right() - devPhysicalPageRect.right()) * 100.0 / dpi_x),
- qRound(inchesToMM(devPaperRect.bottom() - devPhysicalPageRect.bottom()) * 100.0 / dpi_y));
-}
-
-void QWin32PrintEnginePrivate::release()
-{
- if (hdc == 0)
- return;
-
- if (globalDevMode) { // Devmode comes from print dialog
- GlobalUnlock(globalDevMode);
- } else { // Devmode comes from initialize...
- // devMode is a part of the same memory block as pInfo so one free is enough...
- GlobalUnlock(hMem);
- GlobalFree(hMem);
- }
- if (hPrinter)
- ClosePrinter(hPrinter);
- DeleteDC(hdc);
-
- hdc = 0;
- hPrinter = 0;
- pInfo = 0;
- hMem = 0;
- devMode = 0;
-}
-
-QList<QVariant> QWin32PrintEnginePrivate::queryResolutions() const
-{
- // Read the supported resolutions of the printer.
- QList<QVariant> list;
-
- DWORD numRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()),
- reinterpret_cast<const wchar_t *>(port.utf16()),
- DC_ENUMRESOLUTIONS, 0, 0);
- if (numRes == (DWORD)-1)
- return list;
-
- LONG *enumRes = (LONG*)malloc(numRes * 2 * sizeof(LONG));
- DWORD errRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()),
- reinterpret_cast<const wchar_t *>(port.utf16()),
- DC_ENUMRESOLUTIONS, (LPWSTR)enumRes, 0);
-
- if (errRes == (DWORD)-1) {
- qErrnoWarning("QWin32PrintEngine::queryResolutions: DeviceCapabilities failed");
- return list;
- }
-
- for (uint i=0; i<numRes; ++i)
- list.append(int(enumRes[i * 2]));
-
- return list;
-}
-
-void QWin32PrintEnginePrivate::doReinit()
-{
- if (state == QPrinter::Active) {
- reinit = true;
- } else {
- resetDC();
- initDevRects();
- reinit = false;
- }
-}
-
-void QWin32PrintEnginePrivate::updateOrigin()
-{
- if (fullPage) {
- // subtract physical margins to make (0,0) absolute top corner of paper
- // then add user defined margins
- origin_x = -devPhysicalPageRect.x();
- origin_y = -devPhysicalPageRect.y();
- if (pageMarginsSet) {
- origin_x += devPageRect.left();
- origin_y += devPageRect.top();
- }
- } else {
- origin_x = 0;
- origin_y = 0;
- if (pageMarginsSet) {
- origin_x = devPageRect.left() - devPhysicalPageRect.x();
- origin_y = devPageRect.top() - devPhysicalPageRect.y();
- }
- }
-}
-
-void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant &value)
-{
- Q_D(QWin32PrintEngine);
- switch (key) {
- case PPK_CollateCopies:
- {
- if (!d->devMode)
- break;
- d->devMode->dmCollate = value.toBool() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE;
- d->doReinit();
- }
- break;
-
- case PPK_ColorMode:
- {
- if (!d->devMode)
- break;
- d->devMode->dmColor = (value.toInt() == QPrinter::Color) ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME;
- d->doReinit();
- }
- break;
-
- case PPK_Creator:
-
- break;
-
- case PPK_DocumentName:
- if (isActive()) {
- qWarning("QWin32PrintEngine: Cannot change document name while printing is active");
- return;
- }
- d->docName = value.toString();
- break;
-
- case PPK_FullPage:
- d->fullPage = value.toBool();
- d->updateOrigin();
- break;
-
- case PPK_CopyCount: // fallthrough
- case PPK_NumberOfCopies:
- if (!d->devMode)
- break;
- d->num_copies = value.toInt();
- d->devMode->dmCopies = d->num_copies;
- d->doReinit();
- break;
-
- case PPK_Orientation:
- {
- if (!d->devMode)
- break;
- int orientation = value.toInt() == QPrinter::Landscape ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
- int old_orientation = d->devMode->dmOrientation;
- d->devMode->dmOrientation = orientation;
- if (d->has_custom_paper_size && old_orientation != orientation)
- d->paper_size = QSizeF(d->paper_size.height(), d->paper_size.width());
- d->doReinit();
- }
- break;
-
- case PPK_OutputFileName:
- if (isActive()) {
- qWarning("QWin32PrintEngine: Cannot change filename while printing");
- } else {
- d->fileName = value.toString();
- d->printToFile = !value.toString().isEmpty();
- }
- break;
-
- case PPK_PaperSize:
- if (!d->devMode)
- break;
- d->devMode->dmPaperSize = mapPaperSizeDevmode(QPrinter::PaperSize(value.toInt()));
- d->has_custom_paper_size = (QPrinter::PaperSize(value.toInt()) == QPrinter::Custom);
- d->doReinit();
- break;
-
- case PPK_PaperSource:
- {
- if (!d->devMode)
- break;
- int dmMapped = DMBIN_AUTO;
-
- QList<QVariant> v = property(PPK_PaperSources).toList();
- if (v.contains(value))
- dmMapped = mapPaperSourceDevmode(QPrinter::PaperSource(value.toInt()));
-
- d->devMode->dmDefaultSource = dmMapped;
- d->doReinit();
- }
- break;
-
- case PPK_PrinterName:
- d->name = value.toString();
- if(d->name.isEmpty())
- d->queryDefault();
- d->initialize();
- break;
-
- case PPK_Resolution:
- {
- d->resolution = value.toInt();
-
- d->stretch_x = d->dpi_x / double(d->resolution);
- d->stretch_y = d->dpi_y / double(d->resolution);
- }
- break;
-
- case PPK_SelectionOption:
-
- break;
-
- case PPK_SupportedResolutions:
-
- break;
-
-
- case PPK_WindowsPageSize:
- if (!d->devMode)
- break;
- d->has_custom_paper_size = false;
- d->devMode->dmPaperSize = value.toInt();
- d->doReinit();
- break;
-
- case PPK_CustomPaperSize:
- {
- d->has_custom_paper_size = true;
- d->paper_size = value.toSizeF();
- if (!d->devMode)
- break;
- int orientation = d->devMode->dmOrientation;
- DWORD needed = 0;
- DWORD returned = 0;
- if (!EnumForms(d->hPrinter, 1, 0, 0, &needed, &returned)) {
- BYTE *forms = (BYTE *) malloc(needed);
- if (EnumForms(d->hPrinter, 1, forms, needed, &needed, &returned)) {
- for (DWORD i=0; i< returned; ++i) {
- FORM_INFO_1 *formArray = reinterpret_cast<FORM_INFO_1 *>(forms);
- // the form sizes are specified in 1000th of a mm,
- // convert the size to Points
- QSizeF size((formArray[i].Size.cx * 72/25.4)/1000.0,
- (formArray[i].Size.cy * 72/25.4)/1000.0);
- if (qAbs(d->paper_size.width() - size.width()) <= 2
- && qAbs(d->paper_size.height() - size.height()) <= 2)
- {
- d->devMode->dmPaperSize = i + 1;
- break;
- }
- }
- }
- free(forms);
- }
- if (orientation != DMORIENT_PORTRAIT)
- d->paper_size = QSizeF(d->paper_size.height(), d->paper_size.width());
- break;
- }
-
- case PPK_PageMargins:
- {
- QList<QVariant> margins(value.toList());
- Q_ASSERT(margins.size() == 4);
- int left, top, right, bottom;
- // specified in 1/100 mm
- left = (margins.at(0).toReal()*25.4/72.0) * 100;
- top = (margins.at(1).toReal()*25.4/72.0) * 100;
- right = (margins.at(2).toReal()*25.4/72.0) * 100;
- bottom = (margins.at(3).toReal()*25.4/72.0) * 100;
- d->setPageMargins(left, top, right, bottom);
- break;
- }
- default:
- // Do nothing
- break;
- }
-}
-
-QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const
-{
- Q_D(const QWin32PrintEngine);
- QVariant value;
- switch (key) {
-
- case PPK_CollateCopies:
- value = false;
- break;
-
- case PPK_ColorMode:
- {
- if (!d->devMode) {
- value = QPrinter::Color;
- } else {
- value = (d->devMode->dmColor == DMCOLOR_COLOR) ? QPrinter::Color : QPrinter::GrayScale;
- }
- }
- break;
-
- case PPK_DocumentName:
- value = d->docName;
- break;
-
- case PPK_FullPage:
- value = d->fullPage;
- break;
-
- case PPK_CopyCount:
- value = d->num_copies;
- break;
-
- case PPK_SupportsMultipleCopies:
- value = true;
- break;
-
- case PPK_NumberOfCopies:
- value = 1;
- break;
-
- case PPK_Orientation:
- {
- if (!d->devMode) {
- value = QPrinter::Portrait;
- } else {
- value = (d->devMode->dmOrientation == DMORIENT_LANDSCAPE) ? QPrinter::Landscape : QPrinter::Portrait;
- }
- }
- break;
-
- case PPK_OutputFileName:
- value = d->fileName;
- break;
-
- case PPK_PageRect:
- if (d->has_custom_paper_size) {
- QRect rect(0, 0,
- qRound(d->paper_size.width() * d->resolution / 72.0),
- qRound(d->paper_size.height() * d->resolution / 72.0));
- if (d->pageMarginsSet) {
- rect = rect.adjusted(qRound(mmToInches(d->previousDialogMargins.left()/100.0) * d->resolution),
- qRound(mmToInches(d->previousDialogMargins.top()/100.0) * d->resolution),
- -qRound(mmToInches(d->previousDialogMargins.width()/100.0) * d->resolution),
- -qRound(mmToInches(d->previousDialogMargins.height()/100.0) * d->resolution));
- }
- value = rect;
- } else {
- value = QTransform(1/d->stretch_x, 0, 0, 1/d->stretch_y, 0, 0)
- .mapRect(d->fullPage ? d->devPhysicalPageRect : d->devPageRect);
- }
- break;
-
- case PPK_PaperSize:
- if (d->has_custom_paper_size) {
- value = QPrinter::Custom;
- } else {
- if (!d->devMode) {
- value = QPrinter::A4;
- } else {
- value = mapDevmodePaperSize(d->devMode->dmPaperSize);
- }
- }
- break;
-
- case PPK_PaperRect:
- if (d->has_custom_paper_size) {
- value = QRect(0, 0,
- qRound(d->paper_size.width() * d->resolution / 72.0),
- qRound(d->paper_size.height() * d->resolution / 72.0));
- } else {
- value = QTransform(1/d->stretch_x, 0, 0, 1/d->stretch_y, 0, 0).mapRect(d->devPaperRect);
- }
- break;
-
- case PPK_PaperSource:
- if (!d->devMode) {
- value = QPrinter::Auto;
- } else {
- value = mapDevmodePaperSource(d->devMode->dmDefaultSource);
- }
- break;
-
- case PPK_PrinterName:
- value = d->name;
- break;
-
- case PPK_Resolution:
- if (d->resolution || !d->name.isEmpty())
- value = d->resolution;
- break;
-
- case PPK_SupportedResolutions:
- value = d->queryResolutions();
- break;
-
- case PPK_WindowsPageSize:
- if (!d->devMode) {
- value = -1;
- } else {
- value = d->devMode->dmPaperSize;
- }
- break;
-
- case PPK_PaperSources:
- {
- int available = DeviceCapabilities((const wchar_t *)d->name.utf16(),
- (const wchar_t *)d->port.utf16(), DC_BINS, 0, d->devMode);
-
- if (available <= 0)
- break;
-
- wchar_t *data = new wchar_t[available];
- int count = DeviceCapabilities((const wchar_t *)d->name.utf16(),
- (const wchar_t *)d->port.utf16(), DC_BINS, data, d->devMode);
-
- QList<QVariant> out;
- for (int i=0; i<count; ++i) {
- QPrinter::PaperSource src = mapDevmodePaperSource(data[i]);
- if (src != -1)
- out << (int) src;
- }
- value = out;
-
- delete [] data;
- }
- break;
-
- case PPK_CustomPaperSize:
- value = d->paper_size;
- break;
-
- case PPK_PageMargins:
- {
- QList<QVariant> margins;
- QRect pageMargins(d->getPageMargins());
-
- // specified in 1/100 mm
- margins << (mmToInches(pageMargins.left()/100.0) * 72)
- << (mmToInches(pageMargins.top()/100.0) * 72)
- << (mmToInches(pageMargins.width()/100.0) * 72)
- << (mmToInches(pageMargins.height()/100.0) * 72);
- value = margins;
- break;
- }
- default:
- // Do nothing
- break;
- }
- return value;
-}
-
-QPrinter::PrinterState QWin32PrintEngine::printerState() const
-{
- return d_func()->state;
-}
-
-HDC QWin32PrintEngine::getDC() const
-{
- return d_func()->hdc;
-}
-
-void QWin32PrintEngine::releaseDC(HDC) const
-{
-
-}
-
-HGLOBAL *QWin32PrintEnginePrivate::createDevNames()
-{
- int size = sizeof(DEVNAMES)
- + program.length() * 2 + 2
- + name.length() * 2 + 2
- + port.length() * 2 + 2;
- HGLOBAL *hGlobal = (HGLOBAL *) GlobalAlloc(GMEM_MOVEABLE, size);
- DEVNAMES *dn = (DEVNAMES*) GlobalLock(hGlobal);
-
- dn->wDriverOffset = sizeof(DEVNAMES) / sizeof(wchar_t);
- dn->wDeviceOffset = dn->wDriverOffset + program.length() + 1;
- dn->wOutputOffset = dn->wDeviceOffset + name.length() + 1;
-
- memcpy((ushort*)dn + dn->wDriverOffset, program.utf16(), program.length() * 2 + 2);
- memcpy((ushort*)dn + dn->wDeviceOffset, name.utf16(), name.length() * 2 + 2);
- memcpy((ushort*)dn + dn->wOutputOffset, port.utf16(), port.length() * 2 + 2);
- dn->wDefault = 0;
-
- GlobalUnlock(hGlobal);
-
-// printf("QPrintDialogWinPrivate::createDevNames()\n"
-// " -> wDriverOffset: %d\n"
-// " -> wDeviceOffset: %d\n"
-// " -> wOutputOffset: %d\n",
-// dn->wDriverOffset,
-// dn->wDeviceOffset,
-// dn->wOutputOffset);
-
-// printf("QPrintDialogWinPrivate::createDevNames(): %s, %s, %s\n",
-// QString::fromWCharArray((wchar_t*)(dn) + dn->wDriverOffset).latin1(),
-// QString::fromWCharArray((wchar_t*)(dn) + dn->wDeviceOffset).latin1(),
-// QString::fromWCharArray((wchar_t*)(dn) + dn->wOutputOffset).latin1());
-
- return hGlobal;
-}
-
-void QWin32PrintEnginePrivate::readDevnames(HGLOBAL globalDevnames)
-{
- if (globalDevnames) {
- DEVNAMES *dn = (DEVNAMES*) GlobalLock(globalDevnames);
- name = QString::fromWCharArray((wchar_t*)(dn) + dn->wDeviceOffset);
- port = QString::fromWCharArray((wchar_t*)(dn) + dn->wOutputOffset);
- program = QString::fromWCharArray((wchar_t*)(dn) + dn->wDriverOffset);
- GlobalUnlock(globalDevnames);
- }
-}
-
-void QWin32PrintEnginePrivate::readDevmode(HGLOBAL globalDevmode)
-{
- if (globalDevmode) {
- DEVMODE *dm = (DEVMODE*) GlobalLock(globalDevmode);
- release();
- globalDevMode = globalDevmode;
- devMode = dm;
- hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()),
- reinterpret_cast<const wchar_t *>(name.utf16()), 0, dm);
-
- num_copies = devMode->dmCopies;
- if (!OpenPrinter((wchar_t*)name.utf16(), &hPrinter, 0))
- qWarning("QPrinter: OpenPrinter() failed after reading DEVMODE.");
- }
-
- if (hdc)
- initHDC();
-}
-
-static void draw_text_item_win(const QPointF &pos, const QTextItemInt &ti, HDC hdc,
- bool convertToText, const QTransform &xform, const QPointF &topLeft)
-{
- QFontEngine *fe = ti.fontEngine;
- QPointF baseline_pos = xform.inverted().map(xform.map(pos) - topLeft);
-
- SetTextAlign(hdc, TA_BASELINE);
- SetBkMode(hdc, TRANSPARENT);
-
- bool has_kerning = ti.f && ti.f->kerning();
- QFontEngineWin *winfe = (fe->type() == QFontEngine::Win) ? static_cast<QFontEngineWin *>(fe) : 0;
-
- HFONT hfont;
- bool ttf = false;
-
- if (winfe) {
- hfont = winfe->hfont;
- ttf = winfe->ttf;
- } else {
- hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
- }
-
- HGDIOBJ old_font = SelectObject(hdc, hfont);
- unsigned int options = (ttf && !convertToText) ? ETO_GLYPH_INDEX : 0;
- wchar_t *convertedGlyphs = (wchar_t *)ti.chars;
- QGlyphLayout glyphs = ti.glyphs;
-
- bool fast = !has_kerning && !(ti.flags & QTextItem::RightToLeft);
- for (int i = 0; fast && i < glyphs.numGlyphs; i++) {
- if (glyphs.offsets[i].x != 0 || glyphs.offsets[i].y != 0 || glyphs.justifications[i].space_18d6 != 0
- || glyphs.attributes[i].dontPrint) {
- fast = false;
- break;
- }
- }
-
-#if !defined(Q_OS_WINCE)
- // Scale, rotate and translate here.
- XFORM win_xform;
- win_xform.eM11 = xform.m11();
- win_xform.eM12 = xform.m12();
- win_xform.eM21 = xform.m21();
- win_xform.eM22 = xform.m22();
- win_xform.eDx = xform.dx();
- win_xform.eDy = xform.dy();
-
- SetGraphicsMode(hdc, GM_ADVANCED);
- SetWorldTransform(hdc, &win_xform);
-#endif
-
- if (fast) {
- // fast path
- QVarLengthArray<wchar_t> g(glyphs.numGlyphs);
- for (int i = 0; i < glyphs.numGlyphs; ++i)
- g[i] = glyphs.glyphs[i];
- ExtTextOut(hdc,
- qRound(baseline_pos.x() + glyphs.offsets[0].x.toReal()),
- qRound(baseline_pos.y() + glyphs.offsets[0].y.toReal()),
- options, 0, convertToText ? convertedGlyphs : g.data(), glyphs.numGlyphs, 0);
- } else {
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> _glyphs;
-
- QTransform matrix = QTransform::fromTranslate(baseline_pos.x(), baseline_pos.y());
- ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags,
- _glyphs, positions);
- if (_glyphs.size() == 0) {
- SelectObject(hdc, old_font);
- return;
- }
-
- convertToText = convertToText && glyphs.numGlyphs == _glyphs.size();
- bool outputEntireItem = _glyphs.size() > 0;
-
- if (outputEntireItem) {
- options |= ETO_PDY;
- QVarLengthArray<INT> glyphDistances(_glyphs.size() * 2);
- QVarLengthArray<wchar_t> g(_glyphs.size());
- for (int i=0; i<_glyphs.size() - 1; ++i) {
- glyphDistances[i * 2] = qRound(positions[i + 1].x) - qRound(positions[i].x);
- glyphDistances[i * 2 + 1] = qRound(positions[i + 1].y) - qRound(positions[i].y);
- g[i] = _glyphs[i];
- }
- glyphDistances[(_glyphs.size() - 1) * 2] = 0;
- glyphDistances[(_glyphs.size() - 1) * 2 + 1] = 0;
- g[_glyphs.size() - 1] = _glyphs[_glyphs.size() - 1];
- ExtTextOut(hdc, qRound(positions[0].x), qRound(positions[0].y), options, 0,
- convertToText ? convertedGlyphs : g.data(), _glyphs.size(),
- glyphDistances.data());
- } else {
- int i = 0;
- while(i < _glyphs.size()) {
- wchar_t g = _glyphs[i];
-
- ExtTextOut(hdc, qRound(positions[i].x),
- qRound(positions[i].y), options, 0,
- convertToText ? convertedGlyphs + i : &g, 1, 0);
- ++i;
- }
- }
- }
-
-#if !defined(Q_OS_WINCE)
- win_xform.eM11 = win_xform.eM22 = 1.0;
- win_xform.eM12 = win_xform.eM21 = win_xform.eDx = win_xform.eDy = 0.0;
- SetWorldTransform(hdc, &win_xform);
-#endif
-
- SelectObject(hdc, old_font);
-}
-
-
-void QWin32PrintEnginePrivate::updateCustomPaperSize()
-{
- uint paperSize = devMode->dmPaperSize;
- if (paperSize > 0 && mapDevmodePaperSize(paperSize) == QPrinter::Custom) {
- has_custom_paper_size = true;
- DWORD needed = 0;
- DWORD returned = 0;
- if (!EnumForms(hPrinter, 1, 0, 0, &needed, &returned)) {
- BYTE *forms = (BYTE *) malloc(needed);
- if (EnumForms(hPrinter, 1, forms, needed, &needed, &returned)) {
- if (paperSize <= returned) {
- FORM_INFO_1 *formArray = (FORM_INFO_1 *) forms;
- int width = formArray[paperSize - 1].Size.cx; // 1/1000 of a mm
- int height = formArray[paperSize - 1].Size.cy; // 1/1000 of a mm
- paper_size = QSizeF((width * 72 /25.4) / 1000.0, (height * 72 / 25.4) / 1000.0);
- } else {
- has_custom_paper_size = false;
- }
- }
- free(forms);
- }
- } else {
- has_custom_paper_size = false;
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
diff --git a/src/gui/platforms/win/qprintengine_win_p.h b/src/gui/platforms/win/qprintengine_win_p.h
deleted file mode 100644
index b4d0670e7b..0000000000
--- a/src/gui/platforms/win/qprintengine_win_p.h
+++ /dev/null
@@ -1,261 +0,0 @@
-/****************************************************************************
-**
-** 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 QPRINTENGINE_WIN_P_H
-#define QPRINTENGINE_WIN_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.
-//
-
-#ifndef QT_NO_PRINTER
-
-#include "QtGui/qprinter.h"
-#include "QtGui/qprintengine.h"
-#include "QtGui/qpaintengine.h"
-#include "QtCore/qt_windows.h"
-#include "private/qpaintengine_alpha_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QWin32PrintEnginePrivate;
-class QPrinterPrivate;
-class QPainterState;
-
-class QWin32PrintEngine : public QAlphaPaintEngine, public QPrintEngine
-{
- Q_DECLARE_PRIVATE(QWin32PrintEngine)
-public:
- QWin32PrintEngine(QPrinter::PrinterMode mode);
-
- // override QWin32PaintEngine
- bool begin(QPaintDevice *dev);
- bool end();
-
- void updateState(const QPaintEngineState &state);
-
- void updateMatrix(const QTransform &matrix);
- void updateClipPath(const QPainterPath &clip, Qt::ClipOperation op);
-
- void drawPath(const QPainterPath &path);
- void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
- void drawTextItem(const QPointF &p, const QTextItem &textItem);
-
- void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
- void drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &p);
- void setProperty(PrintEnginePropertyKey key, const QVariant &value);
- QVariant property(PrintEnginePropertyKey key) const;
-
- bool newPage();
- bool abort();
- int metric(QPaintDevice::PaintDeviceMetric) const;
-
- QPrinter::PrinterState printerState() const;
-
- QPaintEngine::Type type() const { return Windows; }
-
- HDC getDC() const;
- void releaseDC(HDC) const;
-
- HDC getPrinterDC() const { return getDC(); }
- void releasePrinterDC(HDC dc) const { releaseDC(dc); }
-
-private:
- friend class QPrintDialog;
- friend class QPageSetupDialog;
-};
-
-class QWin32PrintEnginePrivate : public QAlphaPaintEnginePrivate
-{
- Q_DECLARE_PUBLIC(QWin32PrintEngine)
-public:
- QWin32PrintEnginePrivate() :
- hPrinter(0),
- globalDevMode(0),
- devMode(0),
- pInfo(0),
- hdc(0),
- mode(QPrinter::ScreenResolution),
- state(QPrinter::Idle),
- resolution(0),
- pageMarginsSet(false),
- num_copies(1),
- printToFile(false),
- fullPage(false),
- reinit(false),
- has_custom_paper_size(false)
- {
- }
-
- ~QWin32PrintEnginePrivate();
-
-
- /* Reads the default printer name and its driver (printerProgram) into
- the engines private data. */
- void queryDefault();
-
- /* Initializes the printer data based on the current printer name. This
- function creates a DEVMODE struct, HDC and a printer handle. If these
- structures are already in use, they are freed using release
- */
- void initialize();
-
- /* Initializes data in the print engine whenever the HDC has been renewed
- */
- void initHDC();
-
- /* Releases all the handles the printer currently holds, HDC, DEVMODE,
- etc and resets the corresponding members to 0. */
- void release();
-
- /* Queries the resolutions for the current printer, and returns them
- in a list. */
- QList<QVariant> queryResolutions() const;
-
- /* Resets the DC with changes in devmode. If the printer is active
- this function only sets the reinit variable to true so it
- is handled in the next begin or newpage. */
- void doReinit();
-
- /* Used by print/page setup dialogs */
- HGLOBAL *createDevNames();
-
- void readDevmode(HGLOBAL globalDevmode);
- void readDevnames(HGLOBAL globalDevnames);
-
- inline bool resetDC() {
- hdc = ResetDC(hdc, devMode);
- return hdc != 0;
- }
-
- void strokePath(const QPainterPath &path, const QColor &color);
- void fillPath(const QPainterPath &path, const QColor &color);
-
- void composeGdiPath(const QPainterPath &path);
- void fillPath_dev(const QPainterPath &path, const QColor &color);
- void strokePath_dev(const QPainterPath &path, const QColor &color, qreal width);
-
- void updateOrigin();
-
- void initDevRects();
- void setPageMargins(int margin_left, int margin_top, int margin_right, int margin_bottom);
- QRect getPageMargins() const;
- void updateCustomPaperSize();
-
- // Windows GDI printer references.
- HANDLE hPrinter;
-
- HGLOBAL globalDevMode;
- DEVMODE *devMode;
- PRINTER_INFO_2 *pInfo;
- HGLOBAL hMem;
-
- HDC hdc;
-
- QPrinter::PrinterMode mode;
-
- // Printer info
- QString name;
- QString program;
- QString port;
-
- // Document info
- QString docName;
- QString fileName;
-
- QPrinter::PrinterState state;
- int resolution;
-
- // This QRect is used to store the exact values
- // entered into the PageSetup Dialog because those are
- // entered in mm but are since converted to device coordinates.
- // If they were to be converted back when displaying the dialog
- // again, there would be inaccuracies so when the user entered 10
- // it may show up as 9.99 the next time the dialog is opened.
- // We don't want that confusion.
- QRect previousDialogMargins;
-
- bool pageMarginsSet;
- QRect devPageRect;
- QRect devPhysicalPageRect;
- QRect devPaperRect;
- qreal stretch_x;
- qreal stretch_y;
- int origin_x;
- int origin_y;
-
- int dpi_x;
- int dpi_y;
- int dpi_display;
- int num_copies;
-
- uint printToFile : 1;
- uint fullPage : 1;
- uint reinit : 1;
-
- uint complex_xform : 1;
- uint has_pen : 1;
- uint has_brush : 1;
- uint has_custom_paper_size : 1;
-
- uint txop;
-
- QColor brush_color;
- QPen pen;
- QColor pen_color;
- QSizeF paper_size;
-
- QTransform painterMatrix;
- QTransform matrix;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
-
-#endif // QPRINTENGINE_WIN_P_H
diff --git a/src/gui/platforms/win/qprinterinfo_win.cpp b/src/gui/platforms/win/qprinterinfo_win.cpp
deleted file mode 100644
index 2c4014d8dc..0000000000
--- a/src/gui/platforms/win/qprinterinfo_win.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** 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 "qprinterinfo.h"
-#include "qprinterinfo_p.h"
-
-#include <qstringlist.h>
-
-#include <qt_windows.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_PRINTER
-
-extern QPrinter::PaperSize mapDevmodePaperSize(int s);
-
-QList<QPrinterInfo> QPrinterInfo::availablePrinters()
-{
- QList<QPrinterInfo> printers;
-
- DWORD needed = 0;
- DWORD returned = 0;
- if (!EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, NULL, 4, 0, 0, &needed, &returned)) {
- LPBYTE buffer = new BYTE[needed];
- if (EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, NULL, 4, buffer, needed, &needed, &returned)) {
- PPRINTER_INFO_4 infoList = reinterpret_cast<PPRINTER_INFO_4>(buffer);
- QPrinterInfo defPrn = defaultPrinter();
- for (uint i = 0; i < returned; ++i) {
- QString printerName(QString::fromWCharArray(infoList[i].pPrinterName));
-
- QPrinterInfo printerInfo(printerName);
- if (printerInfo.printerName() == defPrn.printerName())
- printerInfo.d_ptr->isDefault = true;
- printers.append(printerInfo);
- }
- }
- delete [] buffer;
- }
-
- return printers;
-}
-
-QPrinterInfo QPrinterInfo::defaultPrinter()
-{
- QString noPrinters(QLatin1String("qt_no_printers"));
- wchar_t buffer[256];
- GetProfileString(L"windows", L"device", (wchar_t*)noPrinters.utf16(), buffer, 256);
- QString output = QString::fromWCharArray(buffer);
- if (output != noPrinters) {
- // Filter out the name of the printer, which should be everything before a comma.
- QString printerName = output.split(QLatin1Char(',')).value(0);
- QPrinterInfo printerInfo(printerName);
- printerInfo.d_ptr->isDefault = true;
- return printerInfo;
- }
-
- return QPrinterInfo();
-}
-
-QList<QPrinter::PaperSize> QPrinterInfo::supportedPaperSizes() const
-{
- const Q_D(QPrinterInfo);
-
- QList<QPrinter::PaperSize> paperSizes;
- if (isNull())
- return paperSizes;
-
- DWORD size = DeviceCapabilities(reinterpret_cast<const wchar_t*>(d->name.utf16()),
- NULL, DC_PAPERS, NULL, NULL);
- if ((int)size != -1) {
- wchar_t *papers = new wchar_t[size];
- size = DeviceCapabilities(reinterpret_cast<const wchar_t*>(d->name.utf16()),
- NULL, DC_PAPERS, papers, NULL);
- for (int c = 0; c < (int)size; ++c)
- paperSizes.append(mapDevmodePaperSize(papers[c]));
- delete [] papers;
- }
-
- return paperSizes;
-}
-
-#endif // QT_NO_PRINTER
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qrawfont_win.cpp b/src/gui/platforms/win/qrawfont_win.cpp
deleted file mode 100644
index d8acf57431..0000000000
--- a/src/gui/platforms/win/qrawfont_win.cpp
+++ /dev/null
@@ -1,707 +0,0 @@
-/****************************************************************************
-**
-** 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 test suite 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 "qrawfont_p.h"
-#include <private/qsystemlibrary_p.h>
-
-#if !defined(QT_NO_DIRECTWRITE)
-# include "qfontenginedirectwrite_p.h"
-# include <dwrite.h>
-#endif
-
-#if !defined(QT_NO_RAWFONT)
-
-QT_BEGIN_NAMESPACE
-
-namespace {
-
- template<typename T>
- struct BigEndian
- {
- quint8 data[sizeof(T)];
-
- operator T() const
- {
- T littleEndian = 0;
- for (int i=0; i<sizeof(T); ++i) {
- littleEndian |= data[i] << ((sizeof(T) - i - 1) * 8);
- }
-
- return littleEndian;
- }
-
- BigEndian<T> &operator=(const T &t)
- {
- for (int i=0; i<sizeof(T); ++i) {
- data[i] = ((t >> (sizeof(T) - i - 1) * 8) & 0xff);
- }
-
- return *this;
- }
- };
-
-# pragma pack(1)
-
- // Common structure for all formats of the "name" table
- struct NameTable
- {
- BigEndian<quint16> format;
- BigEndian<quint16> count;
- BigEndian<quint16> stringOffset;
- };
-
- struct NameRecord
- {
- BigEndian<quint16> platformID;
- BigEndian<quint16> encodingID;
- BigEndian<quint16> languageID;
- BigEndian<quint16> nameID;
- BigEndian<quint16> length;
- BigEndian<quint16> offset;
- };
-
- struct OffsetSubTable
- {
- BigEndian<quint32> scalerType;
- BigEndian<quint16> numTables;
- BigEndian<quint16> searchRange;
- BigEndian<quint16> entrySelector;
- BigEndian<quint16> rangeShift;
- };
-
- struct TableDirectory
- {
- BigEndian<quint32> identifier;
- BigEndian<quint32> checkSum;
- BigEndian<quint32> offset;
- BigEndian<quint32> length;
- };
-
- struct OS2Table
- {
- BigEndian<quint16> version;
- BigEndian<qint16> avgCharWidth;
- BigEndian<quint16> weightClass;
- BigEndian<quint16> widthClass;
- BigEndian<quint16> type;
- BigEndian<qint16> subscriptXSize;
- BigEndian<qint16> subscriptYSize;
- BigEndian<qint16> subscriptXOffset;
- BigEndian<qint16> subscriptYOffset;
- BigEndian<qint16> superscriptXSize;
- BigEndian<qint16> superscriptYSize;
- BigEndian<qint16> superscriptXOffset;
- BigEndian<qint16> superscriptYOffset;
- BigEndian<qint16> strikeOutSize;
- BigEndian<qint16> strikeOutPosition;
- BigEndian<qint16> familyClass;
- quint8 panose[10];
- BigEndian<quint32> unicodeRanges[4];
- quint8 vendorID[4];
- BigEndian<quint16> selection;
- BigEndian<quint16> firstCharIndex;
- BigEndian<quint16> lastCharIndex;
- BigEndian<qint16> typoAscender;
- BigEndian<qint16> typoDescender;
- BigEndian<qint16> typoLineGap;
- BigEndian<quint16> winAscent;
- BigEndian<quint16> winDescent;
- BigEndian<quint32> codepageRanges[2];
- BigEndian<qint16> height;
- BigEndian<qint16> capHeight;
- BigEndian<quint16> defaultChar;
- BigEndian<quint16> breakChar;
- BigEndian<quint16> maxContext;
- };
-
-# pragma pack()
-
- class EmbeddedFont
- {
- public:
- EmbeddedFont(const QByteArray &fontData);
-
- QString changeFamilyName(const QString &newFamilyName);
- QByteArray data() const { return m_fontData; }
- TableDirectory *tableDirectoryEntry(const QByteArray &tagName);
- QString familyName(TableDirectory *nameTableDirectory = 0);
-
- private:
- QByteArray m_fontData;
- };
-
- EmbeddedFont::EmbeddedFont(const QByteArray &fontData) : m_fontData(fontData)
- {
- }
-
- TableDirectory *EmbeddedFont::tableDirectoryEntry(const QByteArray &tagName)
- {
- Q_ASSERT(tagName.size() == 4);
-
- const BigEndian<quint32> *tagIdPtr =
- reinterpret_cast<const BigEndian<quint32> *>(tagName.constData());
- quint32 tagId = *tagIdPtr;
-
- OffsetSubTable *offsetSubTable = reinterpret_cast<OffsetSubTable *>(m_fontData.data());
- TableDirectory *tableDirectory = reinterpret_cast<TableDirectory *>(offsetSubTable + 1);
-
- TableDirectory *nameTableDirectoryEntry = 0;
- for (int i=0; i<offsetSubTable->numTables; ++i, ++tableDirectory) {
- if (tableDirectory->identifier == tagId) {
- nameTableDirectoryEntry = tableDirectory;
- break;
- }
- }
-
- return nameTableDirectoryEntry;
- }
-
- QString EmbeddedFont::familyName(TableDirectory *nameTableDirectoryEntry)
- {
- QString name;
-
- if (nameTableDirectoryEntry == 0)
- nameTableDirectoryEntry = tableDirectoryEntry("name");
-
- if (nameTableDirectoryEntry != 0) {
- NameTable *nameTable = reinterpret_cast<NameTable *>(m_fontData.data()
- + nameTableDirectoryEntry->offset);
- NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1);
- for (int i=0; i<nameTable->count; ++i, ++nameRecord) {
- if (nameRecord->nameID == 1
- && nameRecord->platformID == 3 // Windows
- && nameRecord->languageID == 0x0409) { // US English
- const void *ptr = reinterpret_cast<const quint8 *>(nameTable)
- + nameTable->stringOffset
- + nameRecord->offset;
-
- const BigEndian<quint16> *s = reinterpret_cast<const BigEndian<quint16> *>(ptr);
- for (int j=0; j<nameRecord->length / sizeof(quint16); ++j)
- name += QChar(s[j]);
-
- break;
- }
- }
- }
-
- return name;
- }
-
- QString EmbeddedFont::changeFamilyName(const QString &newFamilyName)
- {
- TableDirectory *nameTableDirectoryEntry = tableDirectoryEntry("name");
- if (nameTableDirectoryEntry == 0)
- return QString();
-
- QString oldFamilyName = familyName(nameTableDirectoryEntry);
-
- // Reserve size for name table header, five required name records and string
- const int requiredRecordCount = 5;
- quint16 nameIds[requiredRecordCount] = { 1, 2, 3, 4, 6 };
-
- int sizeOfHeader = sizeof(NameTable) + sizeof(NameRecord) * requiredRecordCount;
- int newFamilyNameSize = newFamilyName.size() * sizeof(quint16);
-
- const QString regularString = QString::fromLatin1("Regular");
- int regularStringSize = regularString.size() * sizeof(quint16);
-
- // Align table size of table to 32 bits (pad with 0)
- int fullSize = ((sizeOfHeader + newFamilyNameSize + regularStringSize) & ~3) + 4;
-
- QByteArray newNameTable(fullSize, char(0));
-
- {
- NameTable *nameTable = reinterpret_cast<NameTable *>(newNameTable.data());
- nameTable->count = requiredRecordCount;
- nameTable->stringOffset = sizeOfHeader;
-
- NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1);
- for (int i=0; i<requiredRecordCount; ++i, nameRecord++) {
- nameRecord->nameID = nameIds[i];
- nameRecord->encodingID = 1;
- nameRecord->languageID = 0x0409;
- nameRecord->platformID = 3;
- nameRecord->length = newFamilyNameSize;
-
- // Special case for sub-family
- if (nameIds[i] == 4) {
- nameRecord->offset = newFamilyNameSize;
- nameRecord->length = regularStringSize;
- }
- }
-
- // nameRecord now points to string data
- BigEndian<quint16> *stringStorage = reinterpret_cast<BigEndian<quint16> *>(nameRecord);
- const quint16 *sourceString = newFamilyName.utf16();
- for (int i=0; i<newFamilyName.size(); ++i)
- stringStorage[i] = sourceString[i];
- stringStorage += newFamilyName.size();
-
- sourceString = regularString.utf16();
- for (int i=0; i<regularString.size(); ++i)
- stringStorage[i] = sourceString[i];
- }
-
- quint32 *p = reinterpret_cast<quint32 *>(newNameTable.data());
- quint32 *tableEnd = reinterpret_cast<quint32 *>(newNameTable.data() + fullSize);
-
- quint32 checkSum = 0;
- while (p < tableEnd)
- checkSum += *(p++);
-
- nameTableDirectoryEntry->checkSum = checkSum;
- nameTableDirectoryEntry->offset = m_fontData.size();
- nameTableDirectoryEntry->length = fullSize;
-
- m_fontData.append(newNameTable);
-
- return oldFamilyName;
- }
-
-#if !defined(QT_NO_DIRECTWRITE)
-
- class DirectWriteFontFileStream: public IDWriteFontFileStream
- {
- public:
- DirectWriteFontFileStream(const QByteArray &fontData)
- : m_fontData(fontData)
- , m_referenceCount(0)
- {
- }
-
- ~DirectWriteFontFileStream()
- {
- }
-
- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **object);
- ULONG STDMETHODCALLTYPE AddRef();
- ULONG STDMETHODCALLTYPE Release();
-
- HRESULT STDMETHODCALLTYPE ReadFileFragment(const void **fragmentStart, UINT64 fileOffset,
- UINT64 fragmentSize, OUT void **fragmentContext);
- void STDMETHODCALLTYPE ReleaseFileFragment(void *fragmentContext);
- HRESULT STDMETHODCALLTYPE GetFileSize(OUT UINT64 *fileSize);
- HRESULT STDMETHODCALLTYPE GetLastWriteTime(OUT UINT64 *lastWriteTime);
-
- private:
- QByteArray m_fontData;
- ULONG m_referenceCount;
- };
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::QueryInterface(REFIID iid, void **object)
- {
- if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileStream)) {
- *object = this;
- AddRef();
- return S_OK;
- } else {
- *object = NULL;
- return E_NOINTERFACE;
- }
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileStream::AddRef()
- {
- return InterlockedIncrement(&m_referenceCount);
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileStream::Release()
- {
- ULONG newCount = InterlockedDecrement(&m_referenceCount);
- if (newCount == 0)
- delete this;
- return newCount;
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::ReadFileFragment(
- const void **fragmentStart,
- UINT64 fileOffset,
- UINT64 fragmentSize,
- OUT void **fragmentContext)
- {
- *fragmentContext = NULL;
- if (fragmentSize + fileOffset <= m_fontData.size()) {
- *fragmentStart = m_fontData.data() + fileOffset;
- return S_OK;
- } else {
- *fragmentStart = NULL;
- return E_FAIL;
- }
- }
-
- void STDMETHODCALLTYPE DirectWriteFontFileStream::ReleaseFileFragment(void *)
- {
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::GetFileSize(UINT64 *fileSize)
- {
- *fileSize = m_fontData.size();
- return S_OK;
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileStream::GetLastWriteTime(UINT64 *lastWriteTime)
- {
- *lastWriteTime = 0;
- return E_NOTIMPL;
- }
-
- class DirectWriteFontFileLoader: public IDWriteFontFileLoader
- {
- public:
- DirectWriteFontFileLoader() : m_referenceCount(0) {}
-
- ~DirectWriteFontFileLoader()
- {
- }
-
- inline void addKey(const void *key, const QByteArray &fontData)
- {
- Q_ASSERT(!m_fontDatas.contains(key));
- m_fontDatas.insert(key, fontData);
- }
-
- inline void removeKey(const void *key)
- {
- m_fontDatas.remove(key);
- }
-
- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **object);
- ULONG STDMETHODCALLTYPE AddRef();
- ULONG STDMETHODCALLTYPE Release();
-
- HRESULT STDMETHODCALLTYPE CreateStreamFromKey(void const *fontFileReferenceKey,
- UINT32 fontFileReferenceKeySize,
- OUT IDWriteFontFileStream **fontFileStream);
-
- private:
- ULONG m_referenceCount;
- QHash<const void *, QByteArray> m_fontDatas;
- };
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::QueryInterface(const IID &iid,
- void **object)
- {
- if (iid == IID_IUnknown || iid == __uuidof(IDWriteFontFileLoader)) {
- *object = this;
- AddRef();
- return S_OK;
- } else {
- *object = NULL;
- return E_NOINTERFACE;
- }
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::AddRef()
- {
- return InterlockedIncrement(&m_referenceCount);
- }
-
- ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::Release()
- {
- ULONG newCount = InterlockedDecrement(&m_referenceCount);
- if (newCount == 0)
- delete this;
- return newCount;
- }
-
- HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::CreateStreamFromKey(
- void const *fontFileReferenceKey,
- UINT32 fontFileReferenceKeySize,
- IDWriteFontFileStream **fontFileStream)
- {
- Q_UNUSED(fontFileReferenceKeySize);
-
- if (fontFileReferenceKeySize != sizeof(const void *)) {
- qWarning("DirectWriteFontFileLoader::CreateStreamFromKey: Wrong key size");
- return E_FAIL;
- }
-
- const void *key = *reinterpret_cast<void * const *>(fontFileReferenceKey);
- *fontFileStream = NULL;
- if (!m_fontDatas.contains(key))
- return E_FAIL;
-
- QByteArray fontData = m_fontDatas.value(key);
- DirectWriteFontFileStream *stream = new DirectWriteFontFileStream(fontData);
- stream->AddRef();
- *fontFileStream = stream;
-
- return S_OK;
- }
-
- class CustomFontFileLoader
- {
- public:
- CustomFontFileLoader() : m_directWriteFactory(0), m_directWriteFontFileLoader(0)
- {
- HRESULT hres = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
- __uuidof(IDWriteFactory),
- reinterpret_cast<IUnknown **>(&m_directWriteFactory));
- if (FAILED(hres)) {
- qErrnoWarning(hres, "CustomFontFileLoader::CustomFontFileLoader: "
- "DWriteCreateFactory failed.");
- } else {
- m_directWriteFontFileLoader = new DirectWriteFontFileLoader();
- m_directWriteFactory->RegisterFontFileLoader(m_directWriteFontFileLoader);
- }
- }
-
- ~CustomFontFileLoader()
- {
- if (m_directWriteFactory != 0 && m_directWriteFontFileLoader != 0)
- m_directWriteFactory->UnregisterFontFileLoader(m_directWriteFontFileLoader);
-
- if (m_directWriteFactory != 0)
- m_directWriteFactory->Release();
- }
-
- void addKey(const void *key, const QByteArray &fontData)
- {
- if (m_directWriteFontFileLoader != 0)
- m_directWriteFontFileLoader->addKey(key, fontData);
- }
-
- void removeKey(const void *key)
- {
- if (m_directWriteFontFileLoader != 0)
- m_directWriteFontFileLoader->removeKey(key);
- }
-
- IDWriteFontFileLoader *loader() const
- {
- return m_directWriteFontFileLoader;
- }
-
- private:
- IDWriteFactory *m_directWriteFactory;
- DirectWriteFontFileLoader *m_directWriteFontFileLoader;
- };
-
-#endif
-
-} // Anonymous namespace
-
-
-// From qfontdatabase_win.cpp
-extern QFontEngine *qt_load_font_engine_win(const QFontDef &request);
-// From qfontdatabase.cpp
-extern QFont::Weight weightFromInteger(int weight);
-
-void QRawFontPrivate::platformCleanUp()
-{
- if (fontHandle != NULL) {
- if (ptrRemoveFontMemResourceEx == NULL) {
- void *func = QSystemLibrary::resolve(QLatin1String("gdi32"), "RemoveFontMemResourceEx");
- ptrRemoveFontMemResourceEx =
- reinterpret_cast<QRawFontPrivate::PtrRemoveFontMemResourceEx>(func);
- }
-
- if (ptrRemoveFontMemResourceEx == NULL) {
- qWarning("QRawFont::platformCleanUp: Can't find RemoveFontMemResourceEx in gdi32");
- fontHandle = NULL;
- } else {
- ptrRemoveFontMemResourceEx(fontHandle);
- fontHandle = NULL;
- }
- }
-}
-
-void QRawFontPrivate::platformLoadFromData(const QByteArray &_fontData,
- int pixelSize,
- QFont::HintingPreference hintingPreference)
-{
- QByteArray fontData(_fontData);
- EmbeddedFont font(fontData);
-
-#if !defined(QT_NO_DIRECTWRITE)
- if (hintingPreference == QFont::PreferDefaultHinting
- || hintingPreference == QFont::PreferFullHinting)
-#endif
- {
- GUID guid;
- CoCreateGuid(&guid);
-
- QString uniqueFamilyName = QString::fromLatin1("f")
- + QString::number(guid.Data1, 36) + QLatin1Char('-')
- + QString::number(guid.Data2, 36) + QLatin1Char('-')
- + QString::number(guid.Data3, 36) + QLatin1Char('-')
- + QString::number(*reinterpret_cast<quint64 *>(guid.Data4), 36);
-
- QString actualFontName = font.changeFamilyName(uniqueFamilyName);
- if (actualFontName.isEmpty()) {
- qWarning("QRawFont::platformLoadFromData: Can't change family name of font");
- return;
- }
-
- if (ptrAddFontMemResourceEx == NULL || ptrRemoveFontMemResourceEx == NULL) {
- void *func = QSystemLibrary::resolve(QLatin1String("gdi32"), "RemoveFontMemResourceEx");
- ptrRemoveFontMemResourceEx =
- reinterpret_cast<QRawFontPrivate::PtrRemoveFontMemResourceEx>(func);
-
- func = QSystemLibrary::resolve(QLatin1String("gdi32"), "AddFontMemResourceEx");
- ptrAddFontMemResourceEx =
- reinterpret_cast<QRawFontPrivate::PtrAddFontMemResourceEx>(func);
- }
-
- Q_ASSERT(fontHandle == NULL);
- if (ptrAddFontMemResourceEx != NULL && ptrRemoveFontMemResourceEx != NULL) {
- DWORD count = 0;
- fontData = font.data();
- fontHandle = ptrAddFontMemResourceEx(fontData.data(), fontData.size(), 0, &count);
-
- if (count == 0 && fontHandle != NULL) {
- ptrRemoveFontMemResourceEx(fontHandle);
- fontHandle = NULL;
- }
- }
-
- if (fontHandle == NULL) {
- qWarning("QRawFont::platformLoadFromData: AddFontMemResourceEx failed");
- } else {
- QFontDef request;
- request.family = uniqueFamilyName;
- request.pixelSize = pixelSize;
- request.styleStrategy = QFont::NoFontMerging | QFont::PreferMatch;
- request.hintingPreference = hintingPreference;
-
- fontEngine = qt_load_font_engine_win(request);
- if (request.family != fontEngine->fontDef.family) {
- qWarning("QRawFont::platformLoadFromData: Failed to load font. "
- "Got fallback instead: %s", qPrintable(fontEngine->fontDef.family));
- if (fontEngine->cache_count == 0 && fontEngine->ref == 0)
- delete fontEngine;
- fontEngine = 0;
- } else {
- Q_ASSERT(fontEngine->cache_count == 0 && fontEngine->ref == 0);
-
- // Override the generated font name
- static_cast<QFontEngineWin *>(fontEngine)->uniqueFamilyName = uniqueFamilyName;
- fontEngine->fontDef.family = actualFontName;
- fontEngine->ref.ref();
- }
- }
- }
-#if !defined(QT_NO_DIRECTWRITE)
- else {
- CustomFontFileLoader fontFileLoader;
- fontFileLoader.addKey(this, fontData);
-
- IDWriteFactory *factory = NULL;
- HRESULT hres = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
- __uuidof(IDWriteFactory),
- reinterpret_cast<IUnknown **>(&factory));
- if (FAILED(hres)) {
- qErrnoWarning(hres, "QRawFont::platformLoadFromData: DWriteCreateFactory failed");
- return;
- }
-
- IDWriteFontFile *fontFile = NULL;
- void *key = this;
-
- hres = factory->CreateCustomFontFileReference(&key, sizeof(void *),
- fontFileLoader.loader(), &fontFile);
- if (FAILED(hres)) {
- qErrnoWarning(hres, "QRawFont::platformLoadFromData: "
- "CreateCustomFontFileReference failed");
- factory->Release();
- return;
- }
-
- BOOL isSupportedFontType;
- DWRITE_FONT_FILE_TYPE fontFileType;
- DWRITE_FONT_FACE_TYPE fontFaceType;
- UINT32 numberOfFaces;
- fontFile->Analyze(&isSupportedFontType, &fontFileType, &fontFaceType, &numberOfFaces);
- if (!isSupportedFontType) {
- fontFile->Release();
- factory->Release();
- return;
- }
-
- IDWriteFontFace *directWriteFontFace = NULL;
- hres = factory->CreateFontFace(fontFaceType, 1, &fontFile, 0, DWRITE_FONT_SIMULATIONS_NONE,
- &directWriteFontFace);
- if (FAILED(hres)) {
- qErrnoWarning(hres, "QRawFont::platformLoadFromData: CreateFontFace failed");
- fontFile->Release();
- factory->Release();
- return;
- }
-
- fontFile->Release();
-
- fontEngine = new QFontEngineDirectWrite(factory, directWriteFontFace, pixelSize);
-
- // Get font family from font data
- fontEngine->fontDef.family = font.familyName();
- fontEngine->ref.ref();
-
- directWriteFontFace->Release();
- factory->Release();
- }
-#endif
-
- // Get style and weight info
- if (fontEngine != 0) {
- TableDirectory *os2TableEntry = font.tableDirectoryEntry("OS/2");
- if (os2TableEntry != 0) {
- const OS2Table *os2Table =
- reinterpret_cast<const OS2Table *>(fontData.constData()
- + os2TableEntry->offset);
-
- bool italic = os2Table->selection & 1;
- bool oblique = os2Table->selection & 128;
-
- if (italic)
- fontEngine->fontDef.style = QFont::StyleItalic;
- else if (oblique)
- fontEngine->fontDef.style = QFont::StyleOblique;
- else
- fontEngine->fontDef.style = QFont::StyleNormal;
-
- fontEngine->fontDef.weight = weightFromInteger(os2Table->weightClass);
- }
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_RAWFONT
diff --git a/src/gui/platforms/win/qregion_win.cpp b/src/gui/platforms/win/qregion_win.cpp
deleted file mode 100644
index 3466b62cbd..0000000000
--- a/src/gui/platforms/win/qregion_win.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/****************************************************************************
-**
-** 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 "qatomic.h"
-#include "qbitmap.h"
-#include "qbuffer.h"
-#include "qimage.h"
-#include "qpolygon.h"
-#include "qregion.h"
-#include "qt_windows.h"
-#include "qpainterpath.h"
-
-QT_BEGIN_NAMESPACE
-
-QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 };
-
-HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom)
-{
- const int tries = 10;
- for (int i = 0; i < tries; ++i) {
- HRGN region = 0;
- switch (type) {
- case QRegion::Rectangle:
- region = CreateRectRgn(left, top, right, bottom);
- break;
- case QRegion::Ellipse:
-#ifndef Q_OS_WINCE
- region = CreateEllipticRgn(left, top, right, bottom);
-#endif
- break;
- }
- if (region) {
- if (GetRegionData(region, 0, 0))
- return region;
- else
- DeleteObject(region);
- }
- }
- return 0;
-}
-
-QRegion qt_region_from_HRGN(HRGN rgn)
-{
- int numBytes = GetRegionData(rgn, 0, 0);
- if (numBytes == 0)
- return QRegion();
-
- char *buf = new char[numBytes];
- if (buf == 0)
- return QRegion();
-
- RGNDATA *rd = reinterpret_cast<RGNDATA*>(buf);
- if (GetRegionData(rgn, numBytes, rd) == 0) {
- delete [] buf;
- return QRegion();
- }
-
- QRegion region;
- RECT *r = reinterpret_cast<RECT*>(rd->Buffer);
- for (uint i = 0; i < rd->rdh.nCount; ++i) {
- QRect rect;
- rect.setCoords(r->left, r->top, r->right - 1, r->bottom - 1);
- ++r;
- region |= rect;
- }
-
- delete [] buf;
-
- return region;
-}
-
-void qt_win_dispose_rgn(HRGN r)
-{
- if (r)
- DeleteObject(r);
-}
-
-static void qt_add_rect(HRGN &winRegion, QRect r)
-{
- HRGN rgn = CreateRectRgn(r.left(), r.top(), r.x() + r.width(), r.y() + r.height());
- if (rgn) {
- HRGN dest = CreateRectRgn(0,0,0,0);
- int result = CombineRgn(dest, winRegion, rgn, RGN_OR);
- if (result) {
- DeleteObject(winRegion);
- winRegion = dest;
- }
- DeleteObject(rgn);
- }
-}
-
-void QRegion::ensureHandle() const
-{
- if (d->rgn)
- DeleteObject(d->rgn);
- d->rgn = CreateRectRgn(0,0,0,0);
- if (d->qt_rgn) {
- if (d->qt_rgn->numRects == 1) {
- QRect r = d->qt_rgn->extents;
- qt_add_rect(d->rgn, r);
- return;
- }
- for (int i = 0;i < d->qt_rgn->numRects;i++) {
- QRect r = d->qt_rgn->rects.at(i);
- qt_add_rect(d->rgn, r);
- }
- }
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/win/qsound_win.cpp b/src/gui/platforms/win/qsound_win.cpp
deleted file mode 100644
index c11482d608..0000000000
--- a/src/gui/platforms/win/qsound_win.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsound.h"
-
-#ifndef QT_NO_SOUND
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include <qfile.h>
-#include "qpointer.h"
-#include "qsound_p.h"
-
-#include <qt_windows.h>
-
-QT_BEGIN_NAMESPACE
-
-class QAuServerWindows : public QAuServer {
- Q_OBJECT
-
-public:
- QAuServerWindows(QObject* parent);
- ~QAuServerWindows();
-
- void playHelper(const QString &filename, int loop, QSound *snd);
- void play(const QString& filename, int loop);
- void play(QSound*);
-
- void stop(QSound*);
- bool okay();
-
- int decLoop(QSound *snd) { return QAuServer::decLoop(snd); }
-
- HANDLE current;
- HANDLE mutex;
- HANDLE event;
-};
-
-QAuServerWindows::QAuServerWindows(QObject* parent) :
- QAuServer(parent), current(0)
-{
- mutex = CreateMutex(0, 0, 0);
- event = CreateEvent(0, FALSE, FALSE, 0);
-}
-
-QAuServerWindows::~QAuServerWindows()
-{
- HANDLE mtx = mutex;
- WaitForSingleObject(mtx, INFINITE);
- mutex = 0;
-
- ReleaseMutex(mtx);
- CloseHandle(mtx);
- CloseHandle(event);
-}
-
-struct SoundInfo
-{
- SoundInfo(const QString &fn, int lp, QSound *snd, QAuServerWindows *srv)
- : sound(snd), server(srv), filename(fn), loops(lp)
- {
- }
-
- QSound *sound;
- QAuServerWindows *server;
- QString filename;
- int loops;
-};
-
-DWORD WINAPI SoundPlayProc(LPVOID param)
-{
- SoundInfo *info = (SoundInfo*)param;
-
- // copy data before waking up GUI thread
- QAuServerWindows *server = info->server;
- QSound *sound = info->sound;
- int loops = info->loops;
- QString filename = info->filename;
- HANDLE mutex = server->mutex;
- HANDLE event = server->event;
- info = 0;
-
- // server must not be destroyed until thread finishes
- // and all other sounds have to wait
- WaitForSingleObject(mutex, INFINITE);
-
- if (loops <= 1) {
- server->current = 0;
- int flags = SND_FILENAME|SND_ASYNC;
- if (loops == -1)
- flags |= SND_LOOP;
-
- PlaySound((wchar_t*)filename.utf16(), 0, flags);
- if (sound && loops == 1)
- server->decLoop(sound);
-
- // GUI thread continues, but we are done as well.
- SetEvent(event);
- } else {
- // signal GUI thread to continue - sound might be reset!
- QPointer<QSound> guarded_sound = sound;
- SetEvent(event);
-
- for (int l = 0; l < loops && server->current; ++l) {
- PlaySound((wchar_t*)filename.utf16(), 0, SND_FILENAME | SND_SYNC);
-
- if (guarded_sound)
- server->decLoop(guarded_sound);
- }
- server->current = 0;
- }
- ReleaseMutex(mutex);
-
- return 0;
-}
-
-void QAuServerWindows::playHelper(const QString &filename, int loop, QSound *snd)
-{
- if (loop == 0)
- return;
- // busy?
- if (WaitForSingleObject(mutex, 0) == WAIT_TIMEOUT)
- return;
- ReleaseMutex(mutex);
-
- DWORD threadid = 0;
- SoundInfo info(filename, loop, snd, this);
- current = CreateThread(0, 0, SoundPlayProc, &info, 0, &threadid);
- CloseHandle(current);
-
- WaitForSingleObject(event, INFINITE);
-}
-
-void QAuServerWindows::play(const QString& filename, int loop)
-{
- playHelper(filename, loop, 0);
-}
-
-void QAuServerWindows::play(QSound* s)
-{
- playHelper(s->fileName(), s->loops(), s);
-}
-
-void QAuServerWindows::stop(QSound*)
-{
- // stop unlooped sound
- if (!current)
- PlaySound(0, 0, 0);
- // stop after loop is done
- current = 0;
-}
-
-bool QAuServerWindows::okay()
-{
- return true;
-}
-
-QAuServer* qt_new_audio_server()
-{
- return new QAuServerWindows(qApp);
-}
-
-QT_END_NAMESPACE
-
-#include "qsound_win.moc"
-
-#endif // QT_NO_SOUND
diff --git a/src/gui/platforms/win/qwidget_win.cpp b/src/gui/platforms/win/qwidget_win.cpp
deleted file mode 100644
index a02c5ba008..0000000000
--- a/src/gui/platforms/win/qwidget_win.cpp
+++ /dev/null
@@ -1,2139 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qapplication_p.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qimage.h"
-#include "qlayout.h"
-#include "qpainter.h"
-#include "qstack.h"
-#include "qt_windows.h"
-#include "qwidget.h"
-#include "qwidget_p.h"
-#include "private/qbackingstore_p.h"
-#include "private/qwindowsurface_raster_p.h"
-
-#include "qscrollbar.h"
-#include "qabstractscrollarea.h"
-#include <private/qabstractscrollarea_p.h>
-
-#include <qdebug.h>
-
-#include <private/qapplication_p.h>
-#include <private/qwininputcontext_p.h>
-#include <private/qpaintengine_raster_p.h>
-#include <private/qsystemlibrary_p.h>
-
-#if defined(Q_WS_WINCE)
-#include "qguifunctions_wince.h"
-QT_USE_NAMESPACE
-extern void qt_wince_maximize(QWidget *widget); //defined in qguifunctions_wince.cpp
-extern void qt_wince_unmaximize(QWidget *widget); //defined in qguifunctions_wince.cpp
-extern void qt_wince_minimize(HWND hwnd); //defined in qguifunctions_wince.cpp
-extern void qt_wince_full_screen(HWND hwnd, bool fullScreen, UINT swpf); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wince.cpp
-#endif
-
-typedef BOOL (WINAPI *PtrSetLayeredWindowAttributes)(HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
-static PtrSetLayeredWindowAttributes ptrSetLayeredWindowAttributes = 0;
-
-#ifndef QT_NO_DIRECTDRAW
-#include <ddraw.h>
-#include <private/qimage_p.h>
-static IDirectDraw *qt_ddraw_object;
-static IDirectDrawSurface *qt_ddraw_primary;
-#endif
-
-
-
-#if defined(QT_NON_COMMERCIAL)
-#include "qnc_win.h"
-#endif
-
-#if !defined(WS_EX_TOOLWINDOW)
-#define WS_EX_TOOLWINDOW 0x00000080
-#endif
-
-#if !defined(GWLP_WNDPROC)
-#define GWLP_WNDPROC GWL_WNDPROC
-#endif
-
-//#define TABLET_DEBUG
-#define PACKETDATA (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
- | PK_ORIENTATION | PK_CURSOR | PK_Z)
-#define PACKETMODE 0
-#include <wintab.h>
-#include <pktdef.h>
-
-QT_BEGIN_NAMESPACE
-
-typedef HCTX (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
-typedef BOOL (API *PtrWTClose)(HCTX);
-typedef UINT (API *PtrWTInfo)(UINT, UINT, LPVOID);
-typedef BOOL (API *PtrWTEnable)(HCTX, BOOL);
-typedef BOOL (API *PtrWTOverlap)(HCTX, BOOL);
-typedef int (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
-typedef BOOL (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
-typedef int (API *PtrWTQueueSizeGet)(HCTX);
-typedef BOOL (API *PtrWTQueueSizeSet)(HCTX, int);
-
-static PtrWTOpen ptrWTOpen = 0;
-static PtrWTClose ptrWTClose = 0;
-static PtrWTInfo ptrWTInfo = 0;
-static PtrWTQueueSizeGet ptrWTQueueSizeGet = 0;
-static PtrWTQueueSizeSet ptrWTQueueSizeSet = 0;
-#ifndef QT_NO_TABLETEVENT
-static void init_wintab_functions();
-static void qt_tablet_init();
-static void qt_tablet_cleanup();
-#endif // QT_NO_TABLETEVENT
-extern HCTX qt_tablet_context;
-extern bool qt_tablet_tilt_support;
-
-static QWidget *qt_tablet_widget = 0;
-QWidget* qt_get_tablet_widget()
-{
- return qt_tablet_widget;
-}
-
-extern bool qt_is_gui_used;
-
-#ifndef QT_NO_TABLETEVENT
-static void init_wintab_functions()
-{
-#if defined(Q_OS_WINCE)
- return;
-#else
- if (!qt_is_gui_used)
- return;
- QSystemLibrary library(QLatin1String("wintab32"));
- ptrWTOpen = (PtrWTOpen)library.resolve("WTOpenW");
- ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW");
- ptrWTClose = (PtrWTClose)library.resolve("WTClose");
- ptrWTQueueSizeGet = (PtrWTQueueSizeGet)library.resolve("WTQueueSizeGet");
- ptrWTQueueSizeSet = (PtrWTQueueSizeSet)library.resolve("WTQueueSizeSet");
-#endif // Q_OS_WINCE
-}
-
-static void qt_tablet_init()
-{
- static bool firstTime = true;
- if (!firstTime)
- return;
- firstTime = false;
- qt_tablet_widget = new QWidget(0);
- qt_tablet_widget->createWinId();
- qt_tablet_widget->setObjectName(QLatin1String("Qt internal tablet widget"));
- // We don't need this internal widget to appear in QApplication::topLevelWidgets()
- if (QWidgetPrivate::allWidgets)
- QWidgetPrivate::allWidgets->remove(qt_tablet_widget);
- LOGCONTEXT lcMine;
- qAddPostRoutine(qt_tablet_cleanup);
- struct tagAXIS tpOri[3];
- init_wintab_functions();
- if (ptrWTInfo && ptrWTOpen && ptrWTQueueSizeGet && ptrWTQueueSizeSet) {
- // make sure we have WinTab
- if (!ptrWTInfo(0, 0, NULL)) {
-#ifdef TABLET_DEBUG
- qWarning("QWidget: Wintab services not available");
-#endif
- return;
- }
-
- // some tablets don't support tilt, check if it is possible,
- qt_tablet_tilt_support = ptrWTInfo(WTI_DEVICES, DVC_ORIENTATION, &tpOri);
- if (qt_tablet_tilt_support) {
- // check for azimuth and altitude
- qt_tablet_tilt_support = tpOri[0].axResolution && tpOri[1].axResolution;
- }
- // build our context from the default context
- ptrWTInfo(WTI_DEFSYSCTX, 0, &lcMine);
- // Go for the raw coordinates, the tablet event will return good stuff
- lcMine.lcOptions |= CXO_MESSAGES | CXO_CSRMESSAGES;
- lcMine.lcPktData = PACKETDATA;
- lcMine.lcPktMode = PACKETMODE;
- lcMine.lcMoveMask = PACKETDATA;
- lcMine.lcOutOrgX = 0;
- lcMine.lcOutExtX = lcMine.lcInExtX;
- lcMine.lcOutOrgY = 0;
- lcMine.lcOutExtY = -lcMine.lcInExtY;
- qt_tablet_context = ptrWTOpen(qt_tablet_widget->winId(), &lcMine, true);
-#ifdef TABLET_DEBUG
- qDebug("Tablet is %p", qt_tablet_context);
-#endif
- if (!qt_tablet_context) {
-#ifdef TABLET_DEBUG
- qWarning("QWidget: Failed to open the tablet");
-#endif
- return;
- }
- // Set the size of the Packet Queue to the correct size...
- int currSize = ptrWTQueueSizeGet(qt_tablet_context);
- if (!ptrWTQueueSizeSet(qt_tablet_context, QT_TABLET_NPACKETQSIZE)) {
- // Ideally one might want to use a smaller
- // multiple, but for now, since we managed to destroy
- // the existing Q with the previous call, set it back
- // to the other size, which should work. If not,
- // there will be trouble.
- if (!ptrWTQueueSizeSet(qt_tablet_context, currSize)) {
- Q_ASSERT_X(0, "Qt::Internal", "There is no packet queue for"
- " the tablet. The tablet will not work");
- }
- }
- }
-}
-
-static void qt_tablet_cleanup()
-{
- if (ptrWTClose)
- ptrWTClose(qt_tablet_context);
- delete qt_tablet_widget;
- qt_tablet_widget = 0;
-}
-#endif // QT_NO_TABLETEVENT
-
-const QString qt_reg_winclass(QWidget *w); // defined in qapplication_win.cpp
-
-#ifndef QT_NO_DRAGANDDROP
-void qt_olednd_unregister(QWidget* widget, QOleDropTarget *dst); // dnd_win
-QOleDropTarget* qt_olednd_register(QWidget* widget);
-#endif
-
-extern bool qt_nograb();
-extern HRGN qt_win_bitmapToRegion(const QBitmap& bitmap);
-
-static QWidget *mouseGrb = 0;
-static QCursor *mouseGrbCur = 0;
-static QWidget *keyboardGrb = 0;
-static HHOOK journalRec = 0;
-
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-#define XCOORD_MAX 16383
-#define WRECT_MAX 16383
-
-/*****************************************************************************
- QWidget member functions
- *****************************************************************************/
-
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
-{
- Q_Q(QWidget);
- static int sw = -1, sh = -1;
-
- Qt::WindowType type = q->windowType();
- Qt::WindowFlags flags = data.window_flags;
-
- bool topLevel = (flags & Qt::Window);
- bool popup = (type == Qt::Popup);
- bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet
- || (flags & Qt::MSWindowsFixedSizeDialogHint));
- bool desktop = (type == Qt::Desktop);
- bool tool = (type == Qt::Tool || type == Qt::Drawer);
-
- HINSTANCE appinst = qWinAppInst();
- HWND parentw, destroyw = 0;
- WId id = 0;
-
- QString windowClassName = qt_reg_winclass(q);
-
- if (!window) // always initialize
- initializeWindow = true;
-
- if (popup)
- flags |= Qt::WindowStaysOnTopHint; // a popup stays on top
-
- if (sw < 0) { // get the (primary) screen size
- sw = GetSystemMetrics(SM_CXSCREEN);
- sh = GetSystemMetrics(SM_CYSCREEN);
- }
-
- if (desktop && !q->testAttribute(Qt::WA_DontShowOnScreen)) { // desktop widget
- popup = false; // force this flags off
- data.crect.setRect(GetSystemMetrics(76 /* SM_XVIRTUALSCREEN */), GetSystemMetrics(77 /* SM_YVIRTUALSCREEN */),
- GetSystemMetrics(78 /* SM_CXVIRTUALSCREEN */), GetSystemMetrics(79 /* SM_CYVIRTUALSCREEN */));
- }
-
- parentw = q->parentWidget() ? q->parentWidget()->effectiveWinId() : 0;
-
- QString title;
- int style = WS_CHILD;
- int exsty = 0;
-
- if (window) {
- style = GetWindowLong(window, GWL_STYLE);
- if (!style)
- qErrnoWarning("QWidget::create: GetWindowLong failed");
- topLevel = false; // #### needed for some IE plugins??
- } else if (popup || (type == Qt::ToolTip) || (type == Qt::SplashScreen)) {
- style = WS_POPUP;
- } else if (topLevel && !desktop) {
- if (flags & Qt::FramelessWindowHint)
- style = WS_POPUP; // no border
- else if (flags & Qt::WindowTitleHint)
- style = WS_OVERLAPPED;
- else
- style = 0;
- }
- if (!desktop) {
- // if (!testAttribute(Qt::WA_PaintUnclipped))
- // ### Commented out for now as it causes some problems, but
- // this should be correct anyway, so dig some more into this
-#ifndef Q_FLATTEN_EXPOSE
- style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN ;
-#endif
- if (topLevel) {
- if ((type == Qt::Window || dialog || tool)) {
- if (!(flags & Qt::FramelessWindowHint)) {
- style |= WS_POPUP;
- if (!(flags & Qt::MSWindowsFixedSizeDialogHint))
- style |= WS_THICKFRAME;
- else
- style |= WS_DLGFRAME;
- }
- if (flags & Qt::WindowTitleHint)
- style |= WS_CAPTION;
- if (flags & Qt::WindowSystemMenuHint)
- style |= WS_SYSMENU;
- if (flags & Qt::WindowMinimizeButtonHint)
- style |= WS_MINIMIZEBOX;
- if (shouldShowMaximizeButton())
- style |= WS_MAXIMIZEBOX;
- if (tool)
- exsty |= WS_EX_TOOLWINDOW;
- if (flags & Qt::WindowContextHelpButtonHint)
- exsty |= WS_EX_CONTEXTHELP;
- } else {
- exsty |= WS_EX_TOOLWINDOW;
- }
- }
- }
-
- if (flags & Qt::WindowTitleHint) {
- title = q->isWindow() ? qAppName() : q->objectName();
- }
-
- // The Qt::WA_WState_Created flag is checked by translateConfigEvent() in
- // qapplication_win.cpp. We switch it off temporarily to avoid move
- // and resize events during creationt
- q->setAttribute(Qt::WA_WState_Created, false);
-
- if (window) { // override the old window
- if (destroyOldWindow)
- destroyw = data.winid;
- id = window;
- setWinId(window);
- LONG res = SetWindowLong(window, GWL_STYLE, style);
- if (!res)
- qErrnoWarning("QWidget::create: Failed to set window style");
-#ifdef _WIN64
- res = SetWindowLongPtr( window, GWLP_WNDPROC, (LONG_PTR)QtWndProc );
-#else
- res = SetWindowLong( window, GWL_WNDPROC, (LONG)QtWndProc );
-#endif
- if (!res)
- qErrnoWarning("QWidget::create: Failed to set window procedure");
- } else if (desktop) { // desktop widget
- id = GetDesktopWindow();
-// QWidget *otherDesktop = QWidget::find(id); // is there another desktop?
-// if (otherDesktop && otherDesktop->testWFlags(Qt::WPaintDesktop)) {
-// otherDesktop->d_func()->setWinId(0); // remove id from widget mapper
-// d->setWinId(id); // make sure otherDesktop is
-// otherDesktop->d_func()->setWinId(id); // found first
-// } else {
- setWinId(id);
-// }
- } else if (topLevel) { // create top-level widget
- if (popup)
- parentw = 0;
-
- const bool wasMoved = q->testAttribute(Qt::WA_Moved);
- int x = wasMoved ? data.crect.left() : CW_USEDEFAULT;
- int y = wasMoved ? data.crect.top() : CW_USEDEFAULT;
- int w = CW_USEDEFAULT;
- int h = CW_USEDEFAULT;
-
- // Adjust for framestrut when needed
- RECT rect = {0,0,0,0};
- bool isVisibleOnScreen = !q->testAttribute(Qt::WA_DontShowOnScreen);
- if (isVisibleOnScreen && AdjustWindowRectEx(&rect, style & ~WS_OVERLAPPED, FALSE, exsty)) {
- QTLWExtra *td = maybeTopData();
- if (wasMoved && (td && !td->posFromMove)) {
- x = data.crect.x() + rect.left;
- y = data.crect.y() + rect.top;
- }
-
- if (q->testAttribute(Qt::WA_Resized)) {
- w = data.crect.width() + (rect.right - rect.left);
- h = data.crect.height() + (rect.bottom - rect.top);
- }
- }
- //update position & initial size of POPUP window
- if (isVisibleOnScreen && topLevel && initializeWindow && (style & WS_POPUP)) {
- if (!q->testAttribute(Qt::WA_Resized)) {
- w = sw/2;
- h = 4*sh/10;
- if (extra) {
- int dx = rect.right - rect.left;
- int dy = rect.bottom - rect.top;
- w = qMin(w, extra->maxw + dx);
- h = qMin(h, extra->maxh + dy);
- w = qMax(w, extra->minw + dx);
- h = qMax(h, extra->minh + dy);
- }
- }
- if (!wasMoved) {
- x = sw/2 - w/2;
- y = sh/2 - h/2;
- }
- }
-
- id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
- reinterpret_cast<const wchar_t *>(title.utf16()), style,
- x, y, w, h,
- parentw, NULL, appinst, NULL);
- if (!id)
- qErrnoWarning("QWidget::create: Failed to create window");
- setWinId(id);
- if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip)) {
- SetWindowPos(id, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
- if (flags & Qt::WindowStaysOnBottomHint)
- qWarning() << "QWidget: Incompatible window flags: the window can't be on top and on bottom at the same time";
- } else if (flags & Qt::WindowStaysOnBottomHint)
- SetWindowPos(id, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
- winUpdateIsOpaque();
- } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create child widget
- id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
- reinterpret_cast<const wchar_t *>(title.utf16()), style,
- data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(),
- parentw, NULL, appinst, NULL);
- if (!id)
- qErrnoWarning("QWidget::create: Failed to create window");
- SetWindowPos(id, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
- setWinId(id);
- }
-
- if (desktop) {
- q->setAttribute(Qt::WA_WState_Visible);
- } else if (topLevel && !q->testAttribute(Qt::WA_DontShowOnScreen)) {
- RECT cr;
- GetClientRect(id, &cr);
- // one cannot trust cr.left and cr.top, use a correction POINT instead
- POINT pt;
- pt.x = 0;
- pt.y = 0;
- ClientToScreen(id, &pt);
-
- if (data.crect.width() == 0 || data.crect.height() == 0) {
- data.crect = QRect(pt.x, pt.y, data.crect.width(), data.crect.height());
- } else {
- data.crect = QRect(QPoint(pt.x, pt.y),
- QPoint(pt.x + cr.right - 1, pt.y + cr.bottom - 1));
- }
-
- if (data.fstrut_dirty) {
- // be nice to activeqt
- updateFrameStrut();
- }
- }
-
- if (topLevel) {
- if (data.window_flags & Qt::CustomizeWindowHint
- && data.window_flags & Qt::WindowTitleHint) {
- HMENU systemMenu = GetSystemMenu((HWND)q->internalWinId(), FALSE);
- if (data.window_flags & Qt::WindowCloseButtonHint)
- EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED);
- else
- EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED);
- }
- }
-
- q->setAttribute(Qt::WA_WState_Created); // accept move/resize events
- hd = 0; // no display context
-
- if (q->testAttribute(Qt::WA_AcceptTouchEvents))
- registerTouchWindow();
-
- if (window) { // got window from outside
- if (IsWindowVisible(window))
- q->setAttribute(Qt::WA_WState_Visible);
- else
- q->setAttribute(Qt::WA_WState_Visible, false);
- }
-
- if (extra && !extra->mask.isEmpty())
- setMask_sys(extra->mask);
-
-#if defined(QT_NON_COMMERCIAL)
- QT_NC_WIDGET_CREATE
-#endif
-
- if (q->hasFocus() && q->testAttribute(Qt::WA_InputMethodEnabled))
- q->inputContext()->setFocusWidget(q);
-
- if (destroyw) {
- DestroyWindow(destroyw);
- }
-
-#ifndef QT_NO_TABLETEVENT
- if (q != qt_tablet_widget && QWidgetPrivate::mapper)
- qt_tablet_init();
-#endif // QT_NO_TABLETEVENT
-
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- registerDropSite(true);
-
- if (maybeTopData() && maybeTopData()->opacity != 255)
- q->setWindowOpacity(maybeTopData()->opacity/255.);
-
- if (topLevel && (data.crect.width() == 0 || data.crect.height() == 0)) {
- q->setAttribute(Qt::WA_OutsideWSRange, true);
- }
-
- if (!topLevel && q->testAttribute(Qt::WA_NativeWindow) && q->testAttribute(Qt::WA_Mapped)) {
- Q_ASSERT(q->internalWinId());
- ShowWindow(q->internalWinId(), SW_SHOW);
- }
-}
-
-#endif //Q_WS_WINCE
-
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
- Q_D(QWidget);
- d->aboutToDestroy();
- if (!isWindow() && parentWidget())
- parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry()));
- d->deactivateWidgetCleanup();
- if (testAttribute(Qt::WA_WState_Created)) {
- setAttribute(Qt::WA_WState_Created, false);
- for(int i = 0; i < d->children.size(); ++i) { // destroy all widget children
- register QObject *obj = d->children.at(i);
- if (obj->isWidgetType())
- ((QWidget*)obj)->destroy(destroySubWindows,
- destroySubWindows);
- }
- if (mouseGrb == this)
- releaseMouse();
- if (keyboardGrb == this)
- releaseKeyboard();
- if (testAttribute(Qt::WA_ShowModal)) // just be sure we leave modal
- QApplicationPrivate::leaveModal(this);
- else if ((windowType() == Qt::Popup))
- qApp->d_func()->closePopup(this);
- if (destroyWindow && !(windowType() == Qt::Desktop) && internalWinId()) {
- DestroyWindow(internalWinId());
- }
-#ifdef Q_WS_WINCE
- if (destroyWindow && (windowType() == Qt::Desktop) && !GetDesktopWindow()) {
- DestroyWindow(internalWinId());
- }
-
-#endif
- QT_TRY {
- d->setWinId(0);
- } QT_CATCH (const std::bad_alloc &) {
- // swallow - destructors must not throw
- }
- }
-}
-
-void QWidgetPrivate::reparentChildren()
-{
- Q_Q(QWidget);
- QObjectList chlist = q->children();
- for(int i = 0; i < chlist.size(); ++i) { // reparent children
- QObject *obj = chlist.at(i);
- if (obj->isWidgetType()) {
- QWidget *w = (QWidget *)obj;
- if ((w->windowType() == Qt::Popup)) {
- ;
- } else if (w->isWindow()) {
- bool showIt = w->isVisible();
- QPoint old_pos = w->pos();
- w->setParent(q, w->windowFlags());
- w->move(old_pos);
- if (showIt)
- w->show();
- } else {
- w->d_func()->invalidateBuffer(w->rect());
- SetParent(w->effectiveWinId(), q->effectiveWinId());
- w->d_func()->reparentChildren();
- }
- }
- }
-}
-
-void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
-{
- Q_Q(QWidget);
- bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
- if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
- q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
-
- WId old_winid = data.winid;
- // hide and reparent our own window away. Otherwise we might get
- // destroyed when emitting the child remove event below. See QWorkspace.
- if (q->isVisible() && data.winid) {
- ShowWindow(data.winid, SW_HIDE);
- SetParent(data.winid, 0);
- }
- bool dropSiteWasRegistered = false;
- if (q->testAttribute(Qt::WA_DropSiteRegistered)) {
- dropSiteWasRegistered = true;
- q->setAttribute(Qt::WA_DropSiteRegistered, false); // ole dnd unregister (we will register again below)
- }
-
- if ((q->windowType() == Qt::Desktop))
- old_winid = 0;
- setWinId(0);
-
- QObjectPrivate::setParent_helper(parent);
- bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
-
- data.window_flags = f;
- data.fstrut_dirty = true;
- q->setAttribute(Qt::WA_WState_Created, false);
- q->setAttribute(Qt::WA_WState_Visible, false);
- q->setAttribute(Qt::WA_WState_Hidden, false);
- adjustFlags(data.window_flags, q);
- // keep compatibility with previous versions, we need to preserve the created state
- // (but we recreate the winId for the widget being reparented, again for compatibility)
- if (wasCreated || (!q->isWindow() && parent->testAttribute(Qt::WA_WState_Created)))
- createWinId();
- if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
- q->setAttribute(Qt::WA_WState_Hidden);
- q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
- if (wasCreated) {
- reparentChildren();
- }
-
- if (extra && !extra->mask.isEmpty()) {
- QRegion r = extra->mask;
- extra->mask = QRegion();
- q->setMask(r);
- }
- if (extra && extra->topextra && !extra->topextra->caption.isEmpty()) {
- setWindowIcon_sys(true);
- setWindowTitle_helper(extra->topextra->caption);
- }
- if (old_winid)
- DestroyWindow(old_winid);
-
- if (q->testAttribute(Qt::WA_AcceptDrops) || dropSiteWasRegistered
- || (!q->isWindow() && q->parentWidget() && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
- q->setAttribute(Qt::WA_DropSiteRegistered, true);
-
-#ifdef Q_WS_WINCE
- // Show borderless toplevel windows in tasklist & NavBar
- if (!parent) {
- QString txt = q->windowTitle().isEmpty()?qAppName():q->windowTitle();
- SetWindowText(q->internalWinId(), (wchar_t*)txt.utf16());
- }
-#endif
- invalidateBuffer(q->rect());
-}
-
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- QWidget *parentWindow = window();
- QWExtra *extra = parentWindow->d_func()->extra;
- if (!isVisible() || parentWindow->isMinimized() || !testAttribute(Qt::WA_WState_Created) || !internalWinId()
- || (extra
-#ifndef QT_NO_GRAPHICSVIEW
- && extra->proxyWidget
-#endif //QT_NO_GRAPHICSVIEW
- )) {
- if (extra && extra->topextra && extra->topextra->embedded) {
- QPoint pt = mapTo(parentWindow, pos);
- POINT p = {pt.x(), pt.y()};
- ClientToScreen(parentWindow->effectiveWinId(), &p);
- return QPoint(p.x, p.y);
- } else {
- QPoint toGlobal = mapTo(parentWindow, pos) + parentWindow->pos();
- // Adjust for window decorations
- toGlobal += parentWindow->geometry().topLeft() - parentWindow->frameGeometry().topLeft();
- return toGlobal;
- }
- }
- POINT p;
- QPoint tmp = d->mapToWS(pos);
- p.x = tmp.x();
- p.y = tmp.y();
- ClientToScreen(internalWinId(), &p);
- return QPoint(p.x, p.y);
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- QWidget *parentWindow = window();
- QWExtra *extra = parentWindow->d_func()->extra;
- if (!isVisible() || parentWindow->isMinimized() || !testAttribute(Qt::WA_WState_Created) || !internalWinId()
- || (extra
-#ifndef QT_NO_GRAPHICSVIEW
- && extra->proxyWidget
-#endif //QT_NO_GRAPHICSVIEW
- )) {
- if (extra && extra->topextra && extra->topextra->embedded) {
- POINT p = {pos.x(), pos.y()};
- ScreenToClient(parentWindow->effectiveWinId(), &p);
- return mapFrom(parentWindow, QPoint(p.x, p.y));
- } else {
- QPoint fromGlobal = mapFrom(parentWindow, pos - parentWindow->pos());
- // Adjust for window decorations
- fromGlobal -= parentWindow->geometry().topLeft() - parentWindow->frameGeometry().topLeft();
- return fromGlobal;
- }
- }
- POINT p;
- p.x = pos.x();
- p.y = pos.y();
- ScreenToClient(internalWinId(), &p);
- return d->mapFromWS(QPoint(p.x, p.y));
-}
-
-void QWidgetPrivate::updateSystemBackground() {}
-
-#ifndef QT_NO_CURSOR
-void QWidgetPrivate::setCursor_sys(const QCursor &cursor)
-{
- Q_UNUSED(cursor);
- Q_Q(QWidget);
- qt_win_set_cursor(q, false);
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
- Q_Q(QWidget);
- qt_win_set_cursor(q, false);
-}
-#endif
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
- Q_Q(QWidget);
- if (!q->isWindow())
- return;
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- SetWindowText(q->internalWinId(), (wchar_t*)caption.utf16());
-}
-
-HICON qt_createIcon(QIcon icon, int xSize, int ySize, QPixmap **cache)
-{
- HICON result = 0;
- if (!icon.isNull()) { // valid icon
- QSize size = icon.actualSize(QSize(xSize, ySize));
- QPixmap pm = icon.pixmap(size);
- if (pm.isNull())
- return 0;
-
- result = pm.toWinHICON();
-
- if (cache) {
- delete *cache;
- *cache = new QPixmap(pm);;
- }
- }
- return result;
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
- return;
- QTLWExtra* x = topData();
- if (x->iconPixmap && !forceReset)
- // already been set
- return;
-
- if (x->winIconBig) {
- DestroyIcon(x->winIconBig);
- x->winIconBig = 0;
- }
- if (x->winIconSmall) {
- DestroyIcon(x->winIconSmall);
- x->winIconSmall = 0;
- }
-
- x->winIconSmall = qt_createIcon(q->windowIcon(),
- GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
- &(x->iconPixmap));
- x->winIconBig = qt_createIcon(q->windowIcon(),
- GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON),
- &(x->iconPixmap));
- if (x->winIconBig) {
- SendMessage(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall);
- SendMessage(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconBig);
- } else {
- SendMessage(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall);
- SendMessage(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconSmall);
- }
-}
-
-
-void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
-{
- Q_UNUSED(iconText);
-}
-
-
-QCursor *qt_grab_cursor()
-{
- return mouseGrbCur;
-}
-
-// The procedure does nothing, but is required for mousegrabbing to work
-#ifndef Q_WS_WINCE
-LRESULT QT_WIN_CALLBACK qJournalRecordProc(int nCode, WPARAM wParam, LPARAM lParam)
-{
- return CallNextHookEx(journalRec, nCode, wParam, lParam);
-}
-#endif //Q_WS_WINCE
-
-/* Works only as long as pointer is inside the application's window,
- which is good enough for QDockWidget.
-
- Doesn't call SetWindowsHookEx() - this function causes a system-wide
- freeze if any other app on the system installs a hook and fails to
- process events. */
-void QWidgetPrivate::grabMouseWhileInWindow()
-{
- Q_Q(QWidget);
- if (!qt_nograb()) {
- if (mouseGrb)
- mouseGrb->releaseMouse();
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- SetCapture(q->effectiveWinId());
- mouseGrb = q;
-#ifndef QT_NO_CURSOR
- mouseGrbCur = new QCursor(mouseGrb->cursor());
-#endif
- }
-}
-
-#ifndef Q_WS_WINCE
-void QWidget::grabMouse()
-{
- if (!qt_nograb()) {
- if (mouseGrb)
- mouseGrb->releaseMouse();
- journalRec = SetWindowsHookEx(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandle(0), 0);
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- SetCapture(effectiveWinId());
- mouseGrb = this;
-#ifndef QT_NO_CURSOR
- mouseGrbCur = new QCursor(mouseGrb->cursor());
-#endif
- }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
- if (!qt_nograb()) {
- if (mouseGrb)
- mouseGrb->releaseMouse();
- journalRec = SetWindowsHookEx(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandle(0), 0);
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- SetCapture(effectiveWinId());
- mouseGrbCur = new QCursor(cursor);
- SetCursor(mouseGrbCur->handle());
- mouseGrb = this;
- }
-}
-#endif
-
-void QWidget::releaseMouse()
-{
- if (!qt_nograb() && mouseGrb == this) {
- ReleaseCapture();
- if (journalRec) {
- UnhookWindowsHookEx(journalRec);
- journalRec = 0;
- }
- if (mouseGrbCur) {
- delete mouseGrbCur;
- mouseGrbCur = 0;
- }
- mouseGrb = 0;
- }
-}
-#endif
-
-void QWidget::grabKeyboard()
-{
- if (!qt_nograb()) {
- if (keyboardGrb)
- keyboardGrb->releaseKeyboard();
- keyboardGrb = this;
- }
-}
-
-void QWidget::releaseKeyboard()
-{
- if (!qt_nograb() && keyboardGrb == this)
- keyboardGrb = 0;
-}
-
-
-QWidget *QWidget::mouseGrabber()
-{
- return mouseGrb;
-}
-
-QWidget *QWidget::keyboardGrabber()
-{
- return keyboardGrb;
-}
-
-void QWidget::activateWindow()
-{
- window()->createWinId();
- SetForegroundWindow(window()->internalWinId());
-}
-
-#ifndef Q_WS_WINCE
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
- Q_D(QWidget);
- Qt::WindowStates oldstate = windowState();
- if (oldstate == newstate)
- return;
-
- int max = SW_MAXIMIZE;
- int min = SW_MINIMIZE;
-
- int normal = SW_SHOWNOACTIVATE;
- if (newstate & Qt::WindowActive) {
- max = SW_SHOWMAXIMIZED;
- min = SW_SHOWMINIMIZED;
- normal = SW_SHOWNORMAL;
- }
-
- if (isWindow()) {
- createWinId();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
- // Ensure the initial size is valid, since we store it as normalGeometry below.
- if (!testAttribute(Qt::WA_Resized) && !isVisible())
- adjustSize();
-
- if ((oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized)) {
- if (newstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen))
- d->topData()->normalGeometry = geometry();
- if (isVisible() && !(newstate & Qt::WindowMinimized)) {
- ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
- if (!(newstate & Qt::WindowFullScreen)) {
- QRect r = d->topData()->normalGeometry;
- if (!(newstate & Qt::WindowMaximized) && r.width() >= 0) {
- if (pos() != r.topLeft() || size() !=r.size()) {
- d->topData()->normalGeometry = QRect(0,0,-1,-1);
- setGeometry(r);
- }
- }
- } else {
- d->updateFrameStrut();
- }
- }
- }
-
- if ((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
- if (newstate & Qt::WindowFullScreen) {
- if (d->topData()->normalGeometry.width() < 0 && !(oldstate & Qt::WindowMaximized))
- d->topData()->normalGeometry = geometry();
- d->topData()->savedFlags = Qt::WindowFlags(GetWindowLong(internalWinId(), GWL_STYLE));
-#ifndef Q_FLATTEN_EXPOSE
- UINT style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP;
-#else
- UINT style = WS_POPUP;
-#endif
- if (ulong(d->topData()->savedFlags) & WS_SYSMENU)
- style |= WS_SYSMENU;
- if (isVisible())
- style |= WS_VISIBLE;
- SetWindowLong(internalWinId(), GWL_STYLE, style);
- QRect r = QApplication::desktop()->screenGeometry(this);
- UINT swpf = SWP_FRAMECHANGED;
- if (newstate & Qt::WindowActive)
- swpf |= SWP_NOACTIVATE;
-
- SetWindowPos(internalWinId(), HWND_TOP, r.left(), r.top(), r.width(), r.height(), swpf);
- d->updateFrameStrut();
- } else {
- UINT style = d->topData()->savedFlags;
- if (isVisible())
- style |= WS_VISIBLE;
- SetWindowLong(internalWinId(), GWL_STYLE, style);
-
- UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE;
- if (newstate & Qt::WindowActive)
- swpf |= SWP_NOACTIVATE;
- SetWindowPos(internalWinId(), 0, 0, 0, 0, 0, swpf);
- d->updateFrameStrut();
-
- // preserve maximized state
- if (isVisible())
- ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
-
- if (!(newstate & Qt::WindowMaximized)) {
- QRect r = d->topData()->normalGeometry;
- d->topData()->normalGeometry = QRect(0,0,-1,-1);
- if (r.isValid())
- setGeometry(r);
- }
- }
- }
-
- if ((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
- if (isVisible())
- ShowWindow(internalWinId(), (newstate & Qt::WindowMinimized) ? min :
- (newstate & Qt::WindowMaximized) ? max : normal);
- }
- }
- data->window_state = newstate;
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
-}
-#endif //Q_WS_WINCE
-
-
-/*
- \internal
- Platform-specific part of QWidget::hide().
-*/
-
-void QWidgetPrivate::hide_sys()
-{
- Q_Q(QWidget);
- deactivateWidgetCleanup();
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-#ifdef Q_WS_WINCE
- if (!qt_wince_is_mobile() && q->isFullScreen()) {
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- ShowWindow(handle, 1);
- EnableWindow(handle, true);
- }
- }
-#endif
- if (q->windowFlags() != Qt::Desktop) {
- if ((q->windowFlags() & Qt::Popup) && q->internalWinId())
- ShowWindow(q->internalWinId(), SW_HIDE);
- else if (q->internalWinId())
- SetWindowPos(q->internalWinId(),0, 0,0,0,0, SWP_HIDEWINDOW|SWP_NOSIZE|SWP_NOMOVE|SWP_NOZORDER);
- }
- if (q->isWindow()) {
- if (QWidgetBackingStore *bs = maybeBackingStore())
- bs->releaseBuffer();
- } else {
- invalidateBuffer(q->rect());
- }
- q->setAttribute(Qt::WA_Mapped, false);
-}
-
-
-/*
- \internal
- Platform-specific part of QWidget::show().
-*/
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::show_sys()
-{
- Q_Q(QWidget);
-#if defined(QT_NON_COMMERCIAL)
- QT_NC_SHOW_WINDOW
-#endif
- if (q->testAttribute(Qt::WA_OutsideWSRange))
- return;
- q->setAttribute(Qt::WA_Mapped);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
- invalidateBuffer(q->rect());
- return;
- }
-
- if (data.window_flags & Qt::Window) {
- QTLWExtra *extra = topData();
- if (!extra->hotkeyRegistered) {
- // Try to set the hotkey using information from STARTUPINFO
- STARTUPINFO startupInfo;
- GetStartupInfo(&startupInfo);
- // If STARTF_USEHOTKEY is set, hStdInput is the virtual keycode
- if (startupInfo.dwFlags & 0x00000200) {
- WPARAM hotKey = (WPARAM)startupInfo.hStdInput;
- SendMessage(data.winid, WM_SETHOTKEY, hotKey, 0);
- }
- extra->hotkeyRegistered = 1;
- }
- }
-
- int sm = SW_SHOWNORMAL;
- bool fakedMaximize = false;
- if (q->isWindow()) {
- if (q->isMinimized()) {
- sm = SW_SHOWMINIMIZED;
- if (!IsWindowVisible(q->internalWinId()))
- sm = SW_SHOWMINNOACTIVE;
- } else if (q->isMaximized()) {
- sm = SW_SHOWMAXIMIZED;
- // Windows will not behave correctly when we try to maximize a window which does not
- // have minimize nor maximize buttons in the window frame. Windows would then ignore
- // non-available geometry, and rather maximize the widget to the full screen, minus the
- // window frame (caption). So, we do a trick here, by adding a maximize button before
- // maximizing the widget, and then remove the maximize button afterwards.
- Qt::WindowFlags &flags = data.window_flags;
- if (flags & Qt::WindowTitleHint &&
- !(flags & (Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint))) {
- fakedMaximize = TRUE;
- int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
- SetWindowLong(q->internalWinId(), GWL_STYLE, style | WS_MAXIMIZEBOX);
- }
- }
- }
- if (q->testAttribute(Qt::WA_ShowWithoutActivating)
- || (q->windowType() == Qt::Popup)
- || (q->windowType() == Qt::ToolTip)
- || (q->windowType() == Qt::Tool)) {
- sm = SW_SHOWNOACTIVATE;
- }
-
-
- if (q->internalWinId())
- ShowWindow(q->internalWinId(), sm);
-
- if (fakedMaximize) {
- int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
- SetWindowLong(q->internalWinId(), GWL_STYLE, style & ~WS_MAXIMIZEBOX);
- SetWindowPos(q->internalWinId(), 0, 0, 0, 0, 0,
- SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER
- | SWP_FRAMECHANGED);
- }
-
- if (q->internalWinId()) {
- if (IsIconic(q->internalWinId()))
- data.window_state |= Qt::WindowMinimized;
- if (IsZoomed(q->internalWinId()))
- data.window_state |= Qt::WindowMaximized;
- // This is to resolve the problem where popups are opened from the
- // system tray and not being implicitly activated
- if (q->windowType() == Qt::Popup &&
- !q->parentWidget() && !qApp->activeWindow())
- q->activateWindow();
- }
-
- winSetupGestures();
-
- invalidateBuffer(q->rect());
-}
-#endif //Q_WS_WINCE
-
-void QWidgetPrivate::setFocus_sys()
-{
- Q_Q(QWidget);
- if (q->testAttribute(Qt::WA_WState_Created) && q->window()->windowType() != Qt::Popup)
- SetFocus(q->effectiveWinId());
-}
-
-void QWidgetPrivate::raise_sys()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId())
- SetWindowPos(q->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-}
-
-void QWidgetPrivate::lower_sys()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId())
- SetWindowPos(q->internalWinId(), HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
- invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget* w)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId() && w->internalWinId())
- SetWindowPos(q->internalWinId(), w->internalWinId() , 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
- invalidateBuffer(q->rect());
-}
-
-
-/*
- Helper function for non-toplevel widgets. Helps to map Qt's 32bit
- coordinate system to Windpws's 16bit coordinate system.
-
- This code is duplicated from the X11 code, so any changes there
- should also (most likely) be reflected here.
-
- (In all comments below: s/X/Windows/g)
- */
-
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- /*
- There are up to four different coordinate systems here:
- Qt coordinate system for this widget.
- X coordinate system for this widget (relative to wrect).
- Qt coordinate system for parent
- X coordinate system for parent (relative to parent's wrect).
- */
- QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
- QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
- QRect wrect;
- //xrect is the X geometry of my X widget. (starts out in parent's Qt coord sys, and ends up in parent's X coord sys)
- QRect xrect = data.crect;
-
- const QWidget *const parent = q->parentWidget();
- QRect parentWRect = parent->data->wrect;
-
- if (parentWRect.isValid()) {
- // parent is clipped, and we have to clip to the same limit as parent
- if (!parentWRect.contains(xrect)) {
- xrect &= parentWRect;
- wrect = xrect;
- //translate from parent's to my Qt coord sys
- wrect.translate(-data.crect.topLeft());
- }
- //translate from parent's Qt coords to parent's X coords
- xrect.translate(-parentWRect.topLeft());
-
- } else {
- // parent is not clipped, we may or may not have to clip
-
- if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
- // This is where the main optimization is: we are already
- // clipped, and if our clip is still valid, we can just
- // move our window, and do not need to move or clip
- // children
-
- QRect vrect = xrect & parent->rect();
- vrect.translate(-data.crect.topLeft()); //the part of me that's visible through parent, in my Qt coords
- if (data.wrect.contains(vrect)) {
- xrect = data.wrect;
- xrect.translate(data.crect.topLeft());
- if (q->internalWinId())
- MoveWindow(q->internalWinId(), xrect.x(), xrect.y(), xrect.width(), xrect.height(), true);
- return;
- }
- }
-
- if (!validRange.contains(xrect)) {
- // we are too big, and must clip
- xrect &=wrectRange;
- wrect = xrect;
- wrect.translate(-data.crect.topLeft());
- //parent's X coord system is equal to parent's Qt coord
- //sys, so we don't need to map xrect.
- }
-
- }
-
-
- // unmap if we are outside the valid window system coord system
- bool outsideRange = !xrect.isValid();
- bool mapWindow = false;
- if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
- q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
- if (outsideRange) {
- if (q->internalWinId())
- ShowWindow(q->internalWinId(), SW_HIDE);
- q->setAttribute(Qt::WA_Mapped, false);
- } else if (!q->isHidden()) {
- mapWindow = true;
- }
- }
-
- if (outsideRange)
- return;
-
- bool jump = (data.wrect != wrect);
- data.wrect = wrect;
-
- // and now recursively for all children...
- for (int i = 0; i < children.size(); ++i) {
- QObject *object = children.at(i);
- if (object->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(object);
- if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
- w->d_func()->setWSGeometry();
- }
- }
-
- // move ourselves to the new position and map (if necessary) after
- // the movement. Rationale: moving unmapped windows is much faster
- // than moving mapped windows
- if (q->internalWinId()) {
- if (!parent->internalWinId())
- xrect.translate(parent->mapTo(q->nativeParentWidget(), QPoint(0, 0)));
- MoveWindow(q->internalWinId(), xrect.x(), xrect.y(), xrect.width(), xrect.height(), !jump);
- }
- if (mapWindow && !dontShow) {
- q->setAttribute(Qt::WA_Mapped);
- if (q->internalWinId())
- ShowWindow(q->internalWinId(), SW_SHOWNOACTIVATE);
- }
-
- if (jump && q->internalWinId())
- InvalidateRect(q->internalWinId(), 0, false);
-
-}
-
-//
-// The internal qWinRequestConfig, defined in qapplication_win.cpp, stores move,
-// resize and setGeometry requests for a widget that is already
-// processing a config event. The purpose is to avoid recursion.
-//
-void qWinRequestConfig(WId, int, int, int, int, int);
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (extra) { // any size restrictions?
- w = qMin(w,extra->maxw);
- h = qMin(h,extra->maxh);
- w = qMax(w,extra->minw);
- h = qMax(h,extra->minh);
- }
- if (q->isWindow())
- topData()->normalGeometry = QRect(0, 0, -1, -1);
-
- QSize oldSize(q->size());
- QPoint oldPos(q->pos());
-
- if (!q->isWindow())
- isMove = (data.crect.topLeft() != QPoint(x, y));
- bool isResize = w != oldSize.width() || h != oldSize.height();
-
- if (!isMove && !isResize)
- return;
-
- if (isResize && !q->testAttribute(Qt::WA_StaticContents) && q->internalWinId())
- ValidateRgn(q->internalWinId(), 0);
-
-#ifdef Q_WS_WINCE
- // On Windows CE we can't just fiddle around with the window state.
- // Too much magic in setWindowState.
- if (isResize && q->isMaximized())
- q->setWindowState(q->windowState() & ~Qt::WindowMaximized);
-#else
- if (isResize)
- data.window_state &= ~Qt::WindowMaximized;
-#endif
-
- if (data.window_state & Qt::WindowFullScreen) {
- QTLWExtra *top = topData();
-
- if (q->isWindow()) {
- // We need to update these flags when we remove the full screen state
- // or the frame will not be updated
- UINT style = top->savedFlags;
- if (q->isVisible())
- style |= WS_VISIBLE;
- SetWindowLong(q->internalWinId(), GWL_STYLE, style);
-
- UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE;
- if (data.window_state & Qt::WindowActive)
- swpf |= SWP_NOACTIVATE;
- SetWindowPos(q->internalWinId(), 0, 0, 0, 0, 0, swpf);
- updateFrameStrut();
- }
- data.window_state &= ~Qt::WindowFullScreen;
- topData()->savedFlags = 0;
- }
-
- QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- const bool inTopLevelResize = tlwExtra ? tlwExtra->inTopLevelResize : false;
- const bool isTranslucentWindow = !isOpaque && ptrUpdateLayeredWindowIndirect && (data.window_flags & Qt::FramelessWindowHint)
- && GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED;
-
- if (q->testAttribute(Qt::WA_WState_ConfigPending)) { // processing config event
- if (q->internalWinId())
- qWinRequestConfig(q->internalWinId(), isMove ? 2 : 1, x, y, w, h);
- } else {
- if (!q->testAttribute(Qt::WA_DontShowOnScreen))
- q->setAttribute(Qt::WA_WState_ConfigPending);
- if (q->windowType() == Qt::Desktop) {
- data.crect.setRect(x, y, w, h);
- } else if (q->isWindow()) {
- QRect fs(frameStrut());
- if (extra) {
- fs.setLeft(x - fs.left());
- fs.setTop(y - fs.top());
- fs.setRight((x + w - 1) + fs.right());
- fs.setBottom((y + h - 1) + fs.bottom());
- }
- if (w == 0 || h == 0) {
- q->setAttribute(Qt::WA_OutsideWSRange, true);
- if (q->isVisible() && q->testAttribute(Qt::WA_Mapped))
- hide_sys();
- data.crect = QRect(x, y, w, h);
- } else if (q->isVisible() && q->testAttribute(Qt::WA_OutsideWSRange)) {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
-
- // put the window in its place and show it
- MoveWindow(q->internalWinId(), fs.x(), fs.y(), fs.width(), fs.height(), true);
- RECT rect;
- if (!q->testAttribute(Qt::WA_DontShowOnScreen)) {
- GetClientRect(q->internalWinId(), &rect);
- data.crect.setRect(x, y, rect.right - rect.left, rect.bottom - rect.top);
- } else {
- data.crect.setRect(x, y, w, h);
- }
-
- show_sys();
- } else if (!q->testAttribute(Qt::WA_DontShowOnScreen)) {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
-#ifndef Q_WS_WINCE
- // If the window is hidden and in maximized state or minimized, instead of moving the
- // window, set the normal position of the window.
- WINDOWPLACEMENT wndpl;
- GetWindowPlacement(q->internalWinId(), &wndpl);
- if ((wndpl.showCmd == SW_MAXIMIZE && !IsWindowVisible(q->internalWinId())) || wndpl.showCmd == SW_SHOWMINIMIZED) {
- RECT normal = {fs.x(), fs.y(), fs.x()+fs.width(), fs.y()+fs.height()};
- wndpl.rcNormalPosition = normal;
- wndpl.showCmd = wndpl.showCmd == SW_SHOWMINIMIZED ? SW_SHOWMINIMIZED : SW_HIDE;
- SetWindowPlacement(q->internalWinId(), &wndpl);
- } else {
-#else
- if (data.window_state & Qt::WindowMaximized) {
- qt_wince_maximize(q);
- } else {
-#endif
- MoveWindow(q->internalWinId(), fs.x(), fs.y(), fs.width(), fs.height(), true);
- }
- if (!q->isVisible())
- InvalidateRect(q->internalWinId(), 0, FALSE);
- RECT rect;
- // If the layout has heightForWidth, the MoveWindow() above can
- // change the size/position, so refresh them.
-
- if (isTranslucentWindow) {
- data.crect.setRect(x, y, w, h);
- } else {
- GetClientRect(q->internalWinId(), &rect);
- RECT rcNormalPosition ={0};
- // Use (0,0) as window position for embedded ActiveQt controls.
- if (!tlwExtra || !tlwExtra->embedded)
- GetWindowRect(q->internalWinId(), &rcNormalPosition);
- QRect fStrut(frameStrut());
- data.crect.setRect(rcNormalPosition.left + fStrut.left(),
- rcNormalPosition.top + fStrut.top(),
- rect.right - rect.left,
- rect.bottom - rect.top);
- isResize = data.crect.size() != oldSize;
- }
- } else {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
- data.crect.setRect(x, y, w, h);
- }
- } else {
- QRect oldGeom(data.crect);
- data.crect.setRect(x, y, w, h);
- if (q->isVisible() && (!inTopLevelResize || q->internalWinId())) {
- // Top-level resize optimization does not work for native child widgets;
- // disable it for this particular widget.
- if (inTopLevelResize)
- tlwExtra->inTopLevelResize = false;
-
- if (!isResize)
- moveRect(QRect(oldPos, oldSize), x - oldPos.x(), y - oldPos.y());
- else
- invalidateBuffer_resizeHelper(oldPos, oldSize);
-
- if (inTopLevelResize)
- tlwExtra->inTopLevelResize = true;
- }
- if (q->testAttribute(Qt::WA_WState_Created))
- setWSGeometry();
- }
- q->setAttribute(Qt::WA_WState_ConfigPending, false);
- }
-
- if (q->isWindow() && q->isVisible() && isResize && !inTopLevelResize) {
- invalidateBuffer(q->rect()); //after the resize
- }
-
- // Process events immediately rather than in translateConfigEvent to
- // avoid windows message process delay.
- if (q->isVisible()) {
- if (isMove && q->pos() != oldPos) {
- QMoveEvent e(q->pos(), oldPos);
- QApplication::sendEvent(q, &e);
- }
- if (isResize) {
- static bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
- // If we have a backing store with static contents, we have to disable the top-level
- // resize optimization in order to get invalidated regions for resized widgets.
- // The optimization discards all invalidateBuffer() calls since we're going to
- // repaint everything anyways, but that's not the case with static contents.
- const bool setTopLevelResize = !slowResize && q->isWindow() && extra && extra->topextra
- && !extra->topextra->inTopLevelResize
- && (!extra->topextra->backingStore
- || !extra->topextra->backingStore->hasStaticContents());
- if (setTopLevelResize)
- extra->topextra->inTopLevelResize = true;
- QResizeEvent e(q->size(), oldSize);
- QApplication::sendEvent(q, &e);
- if (setTopLevelResize)
- extra->topextra->inTopLevelResize = false;
- }
- } else {
- if (isMove && q->pos() != oldPos)
- q->setAttribute(Qt::WA_PendingMoveEvent, true);
- if (isResize)
- q->setAttribute(Qt::WA_PendingResizeEvent, true);
- }
-}
-
-bool QWidgetPrivate::shouldShowMaximizeButton()
-{
- if (data.window_flags & Qt::MSWindowsFixedSizeDialogHint)
- return false;
- // if the user explicitly asked for the maximize button, we try to add
- // it even if the window has fixed size.
- if (data.window_flags & Qt::CustomizeWindowHint &&
- data.window_flags & Qt::WindowMaximizeButtonHint)
- return true;
- if (extra) {
- if ((extra->maxw && extra->maxw != QWIDGETSIZE_MAX && extra->maxw != QLAYOUTSIZE_MAX)
- || (extra->maxh && extra->maxh != QWIDGETSIZE_MAX && extra->maxh != QLAYOUTSIZE_MAX))
- return false;
- }
- return data.window_flags & Qt::WindowMaximizeButtonHint;
-}
-
-void QWidgetPrivate::winUpdateIsOpaque()
-{
-#ifndef Q_WS_WINCE
- Q_Q(QWidget);
-
- if (!q->isWindow() || !q->testAttribute(Qt::WA_TranslucentBackground))
- return;
-
- if ((data.window_flags & Qt::FramelessWindowHint) == 0)
- return;
-
- if (!isOpaque && ptrUpdateLayeredWindowIndirect) {
- SetWindowLong(q->internalWinId(), GWL_EXSTYLE,
- GetWindowLong(q->internalWinId(), GWL_EXSTYLE) | Q_WS_EX_LAYERED);
- } else {
- SetWindowLong(q->internalWinId(), GWL_EXSTYLE,
- GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & ~Q_WS_EX_LAYERED);
- }
-#endif
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
-#ifndef Q_WS_WINCE_WM
- Q_Q(QWidget);
- if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) {
- int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
- if (shouldShowMaximizeButton())
- style |= WS_MAXIMIZEBOX;
- else
- style &= ~WS_MAXIMIZEBOX;
- SetWindowLong(q->internalWinId(), GWL_STYLE, style);
- }
-#endif
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
- Q_Q(QWidget);
- scrollChildren(dx, dy);
-
- if (!paintOnScreen()) {
- scrollRect(q->rect(), dx, dy);
- } else {
- UINT flags = SW_INVALIDATE;
- if (!q->testAttribute(Qt::WA_OpaquePaintEvent))
- flags |= SW_ERASE;
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- ScrollWindowEx(q->internalWinId(), dx, dy, 0, 0, 0, 0, flags);
- UpdateWindow(q->internalWinId());
- }
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
-{
- Q_Q(QWidget);
-
- if (!paintOnScreen()) {
- scrollRect(r, dx, dy);
- } else {
- RECT wr;
- wr.top = r.top();
- wr.left = r.left();
- wr.bottom = r.bottom()+1;
- wr.right = r.right()+1;
-
- UINT flags = SW_INVALIDATE;
- if (!q->testAttribute(Qt::WA_OpaquePaintEvent))
- flags |= SW_ERASE;
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- ScrollWindowEx(q->internalWinId(), dx, dy, &wr, &wr, 0, 0, flags);
- UpdateWindow(q->internalWinId());
- }
-}
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
- Q_D(const QWidget);
- int val;
- if (m == PdmWidth) {
- val = data->crect.width();
- } else if (m == PdmHeight) {
- val = data->crect.height();
- } else {
- HDC gdc = GetDC(0);
- switch (m) {
- case PdmDpiX:
- case PdmPhysicalDpiX:
- if (d->extra && d->extra->customDpiX)
- val = d->extra->customDpiX;
- else if (d->parent)
- val = static_cast<QWidget *>(d->parent)->metric(m);
- else
- val = GetDeviceCaps(gdc, LOGPIXELSX);
- break;
- case PdmDpiY:
- case PdmPhysicalDpiY:
- if (d->extra && d->extra->customDpiY)
- val = d->extra->customDpiY;
- else if (d->parent)
- val = static_cast<QWidget *>(d->parent)->metric(m);
- else
- val = GetDeviceCaps(gdc, LOGPIXELSY);
- break;
- case PdmWidthMM:
- val = data->crect.width()
- * GetDeviceCaps(gdc, HORZSIZE)
- / GetDeviceCaps(gdc, HORZRES);
- break;
- case PdmHeightMM:
- val = data->crect.height()
- * GetDeviceCaps(gdc, VERTSIZE)
- / GetDeviceCaps(gdc, VERTRES);
- break;
- case PdmNumColors:
- if (GetDeviceCaps(gdc, RASTERCAPS) & RC_PALETTE)
- val = GetDeviceCaps(gdc, SIZEPALETTE);
- else {
- HDC hd = d->hd ? HDC(d->hd) : gdc;
- int bpp = GetDeviceCaps(hd, BITSPIXEL);
- if (bpp == 32)
- val = INT_MAX; // ### this is bogus, it should be 2^24 colors for 32 bit as well
- else if(bpp<=8)
- val = GetDeviceCaps(hd, NUMCOLORS);
- else
- val = 1 << (bpp * GetDeviceCaps(hd, PLANES));
- }
- break;
- case PdmDepth:
- val = GetDeviceCaps(gdc, BITSPIXEL);
- break;
- default:
- val = 0;
- qWarning("QWidget::metric: Invalid metric command");
- }
- ReleaseDC(0, gdc);
- }
- return val;
-}
-
-void QWidgetPrivate::createSysExtra()
-{
-#ifndef QT_NO_DRAGANDDROP
- extra->dropTarget = 0;
-#endif
-}
-
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::deleteSysExtra()
-{
-}
-#endif //Q_WS_WINCE
-
-void QWidgetPrivate::createTLSysExtra()
-{
- extra->topextra->hotkeyRegistered = 0;
- extra->topextra->savedFlags = 0;
- extra->topextra->winIconBig = 0;
- extra->topextra->winIconSmall = 0;
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
- if (extra->topextra->winIconSmall)
- DestroyIcon(extra->topextra->winIconSmall);
- if (extra->topextra->winIconBig)
- DestroyIcon(extra->topextra->winIconBig);
-}
-
-void QWidgetPrivate::registerDropSite(bool on)
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
- // Enablement is defined by d->extra->dropTarget != 0.
- if (on) {
- // Turn on.
- createExtra();
-#ifndef QT_NO_DRAGANDDROP
- if (!q->internalWinId())
- q->nativeParentWidget()->d_func()->createExtra();
- QWExtra *extra = extraData();
- if (!extra->dropTarget)
- extra->dropTarget = registerOleDnd(q);
-#endif
- } else {
- // Turn off.
- QWExtra *extra = extraData();
-#ifndef QT_NO_DRAGANDDROP
- if (extra && extra->dropTarget) {
- unregisterOleDnd(q, extra->dropTarget);
- extra->dropTarget = 0;
- }
-#endif
- }
-}
-
-#ifndef QT_NO_DRAGANDDROP
-QOleDropTarget* QWidgetPrivate::registerOleDnd(QWidget *widget)
-{
- QOleDropTarget *dropTarget = new QOleDropTarget(widget);
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- if (!widget->internalWinId()) {
- QWidget *nativeParent = widget->nativeParentWidget();
- Q_ASSERT(nativeParent);
- QWExtra *nativeExtra = nativeParent->d_func()->extra;
- Q_ASSERT(nativeExtra);
- if (!nativeParent->acceptDrops())
- nativeParent->setAcceptDrops(true);
- if (!nativeExtra->oleDropWidgets.contains(widget))
- nativeExtra->oleDropWidgets.append(widget);
- if (!nativeExtra->dropTarget) {
- nativeExtra->dropTarget = registerOleDnd(nativeParent);
- Q_ASSERT(nativeExtra->dropTarget);
-#ifndef Q_OS_WINCE
- CoLockObjectExternal(nativeExtra->dropTarget, false, true);
-#endif
- RegisterDragDrop(nativeParent->internalWinId(), nativeExtra->dropTarget);
- }
- } else {
- RegisterDragDrop(widget->internalWinId(), dropTarget);
-#ifndef Q_OS_WINCE
- CoLockObjectExternal(dropTarget, true, true);
-#endif
- }
- return dropTarget;
-}
-
-void QWidgetPrivate::unregisterOleDnd(QWidget *widget, QOleDropTarget *dropTarget)
-{
- dropTarget->releaseQt();
- dropTarget->Release();
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- if (!widget->internalWinId()) {
- QWidget *nativeParent = widget->nativeParentWidget();
- Q_ASSERT(nativeParent);
- QWExtra *nativeExtra = nativeParent->d_func()->extra;
- Q_ASSERT(nativeExtra);
- nativeExtra->oleDropWidgets.removeAll(widget);
- nativeExtra->oleDropWidgets.removeAll(static_cast<QWidget *>(0));
- if (nativeExtra->oleDropWidgets.isEmpty() && nativeExtra->dropTarget
- && !nativeParent->testAttribute(Qt::WA_DropSiteRegistered)) {
-#ifndef Q_OS_WINCE
- CoLockObjectExternal(nativeExtra->dropTarget, false, true);
-#endif
- RevokeDragDrop(nativeParent->internalWinId());
- nativeExtra->dropTarget = 0;
- }
- } else {
-#ifndef Q_OS_WINCE
- CoLockObjectExternal(dropTarget, false, true);
-#endif
- RevokeDragDrop(widget->internalWinId());
- }
-}
-
-#endif //QT_NO_DRAGANDDROP
-
-// from qregion_win.cpp
-extern HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom);
-void QWidgetPrivate::setMask_sys(const QRegion &region)
-{
- Q_Q(QWidget);
- if (!q->internalWinId())
- return;
-
- if (region.isEmpty()) {
- SetWindowRgn(q->internalWinId(), 0, true);
- return;
- }
-
- // Since SetWindowRegion takes ownership, and we need to translate,
- // we take a copy.
- HRGN wr = qt_tryCreateRegion(QRegion::Rectangle, 0,0,0,0);
- CombineRgn(wr, region.handle(), 0, RGN_COPY);
-
- QPoint offset = (q->isWindow()
- ? frameStrut().topLeft()
- : QPoint(0, 0));
- OffsetRgn(wr, offset.x(), offset.y());
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (!SetWindowRgn(data.winid, wr, true))
- DeleteObject(wr);
-}
-
-void QWidgetPrivate::updateFrameStrut()
-{
- Q_Q(QWidget);
-
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
-
- if (!q->internalWinId()) {
- data.fstrut_dirty = false;
- return;
- }
-
- RECT rect = {0,0,0,0};
-
- QTLWExtra *top = topData();
- uint exstyle = GetWindowLong(q->internalWinId(), GWL_EXSTYLE);
- uint style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-#ifndef Q_WS_WINCE
- if (AdjustWindowRectEx(&rect, style & ~(WS_OVERLAPPED), FALSE, exstyle)) {
-#else
- if (AdjustWindowRectEx(&rect, style, FALSE, exstyle)) {
-#endif
- top->frameStrut.setCoords(-rect.left, -rect.top, rect.right, rect.bottom);
- data.fstrut_dirty = false;
- }
-}
-
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::setWindowOpacity_sys(qreal level)
-{
- Q_Q(QWidget);
-
- if (!isOpaque && ptrUpdateLayeredWindow && (data.window_flags & Qt::FramelessWindowHint)) {
- if (GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED) {
- BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * level), AC_SRC_ALPHA};
- ptrUpdateLayeredWindow(q->internalWinId(), NULL, NULL, NULL, NULL, NULL, 0, &blend, Q_ULW_ALPHA);
- }
- return;
- }
-
- static bool function_resolved = false;
- if (!function_resolved) {
- ptrSetLayeredWindowAttributes =
- (PtrSetLayeredWindowAttributes) QSystemLibrary::resolve(QLatin1String("user32"),
- "SetLayeredWindowAttributes");
- function_resolved = true;
- }
-
- if (!ptrSetLayeredWindowAttributes)
- return;
-
- int wl = GetWindowLong(q->internalWinId(), GWL_EXSTYLE);
-
- if (level != 1.0) {
- if ((wl&Q_WS_EX_LAYERED) == 0)
- SetWindowLong(q->internalWinId(), GWL_EXSTYLE, wl | Q_WS_EX_LAYERED);
- } else if (wl&Q_WS_EX_LAYERED) {
- SetWindowLong(q->internalWinId(), GWL_EXSTYLE, wl & ~Q_WS_EX_LAYERED);
- }
- ptrSetLayeredWindowAttributes(q->internalWinId(), 0, (int)(level * 255), Q_LWA_ALPHA);
-}
-#endif //Q_WS_WINCE
-
-// class QGlobalRasterPaintEngine: public QRasterPaintEngine
-// {
-// public:
-// inline QGlobalRasterPaintEngine() : QRasterPaintEngine() { setFlushOnEnd(false); }
-// };
-// Q_GLOBAL_STATIC(QGlobalRasterPaintEngine, globalRasterPaintEngine)
-
-
-#ifndef QT_NO_DIRECTDRAW
-static uchar *qt_primary_surface_bits;
-static int qt_primary_surface_stride;
-static QImage::Format qt_primary_surface_format;
-
-void qt_win_initialize_directdraw()
-{
- HRESULT res;
-
- // Some initialization...
- if (!qt_ddraw_object) {
- res = DirectDrawCreate(0, &qt_ddraw_object, 0);
-
- if (res != DD_OK)
- qWarning("DirectDrawCreate failed: %d", res);
-
- qt_ddraw_object->SetCooperativeLevel(0, DDSCL_NORMAL);
-
- DDSURFACEDESC surfaceDesc;
- memset(&surfaceDesc, 0, sizeof(DDSURFACEDESC));
-
- surfaceDesc.dwSize = sizeof(DDSURFACEDESC);
- surfaceDesc.dwFlags = DDSD_CAPS;
- surfaceDesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-
- res = qt_ddraw_object->CreateSurface(&surfaceDesc, &qt_ddraw_primary, 0);
- if (res != DD_OK)
- qWarning("CreateSurface failed: %d", res);
-
- memset(&surfaceDesc, 0, sizeof(DDSURFACEDESC));
- surfaceDesc.dwSize = sizeof(DDSURFACEDESC);
- res = qt_ddraw_primary->Lock(0, &surfaceDesc, DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR, 0);
- if (res != DD_OK)
- qWarning("Locking surface failed: %d", res);
-
- if (surfaceDesc.ddpfPixelFormat.dwFlags == DDPF_RGB) {
- qt_primary_surface_bits = (uchar *) surfaceDesc.lpSurface;
- qt_primary_surface_stride = surfaceDesc.lPitch;
- qt_primary_surface_format = QImage::Format_RGB32;
- } else {
- qWarning("QWidget painting: unsupported device depth for onscreen painting...\n");
- }
-
- qt_ddraw_primary->Unlock(0);
- }
-}
-
-class QOnScreenRasterPaintEngine : public QRasterPaintEngine
-{
-public:
- // The image allocated here leaks... Fix if this code is ifdef'ed
- // in
- QOnScreenRasterPaintEngine()
- : QRasterPaintEngine(new QImage(qt_primary_surface_bits,
- QApplication::desktop()->width(),
- QApplication::desktop()->height(),
- qt_primary_surface_stride,
- qt_primary_surface_format))
- {
- device = static_cast<QImage *>(d_func()->device);
- }
-
- bool begin(QPaintDevice *)
- {
- QRegion clip = systemClip();
- originalSystemClip = clip;
- clip.translate(widget->mapToGlobal(QPoint(0, 0)));
- setSystemClip(clip);
-
- QRect bounds = clip.boundingRect();
- DDSURFACEDESC surface;
- surface.dwSize = sizeof(DDSURFACEDESC);
- HRESULT res = qt_ddraw_primary->Lock((RECT *) &bounds, &surface, DDLOCK_WAIT, 0);
- if (res != DD_OK) {
- qWarning("QWidget painting: locking onscreen bits failed: %d\n", res);
- return false;
- }
-
- if (surface.lpSurface == qt_primary_surface_bits) {
- qt_primary_surface_bits = (uchar *) surface.lpSurface;
- device->data_ptr()->data = qt_primary_surface_bits;
- }
-
- return QRasterPaintEngine::begin(device);
- }
-
- bool end()
- {
- HRESULT res = qt_ddraw_primary->Unlock(0);
- if (res != DD_OK)
- qWarning("QWidget::paint, failed to unlock DirectDraw surface: %d", res);
- bool ok = QRasterPaintEngine::end();
- setSystemClip(originalSystemClip);
- return ok;
- }
-
- QPoint coordinateOffset() const {
- return -widget->mapToGlobal(QPoint(0, 0));
- }
-
- const QWidget *widget;
- QImage *device;
- QRegion originalSystemClip;
-};
-Q_GLOBAL_STATIC(QOnScreenRasterPaintEngine, onScreenPaintEngine)
-#else
-void qt_win_initialize_directdraw() { }
-#endif
-
-QPaintEngine *QWidget::paintEngine() const
-{
-#ifndef QT_NO_DIRECTDRAW
- QOnScreenRasterPaintEngine *pe = onScreenPaintEngine();
- pe->widget = this;
- return pe;
-#endif
-
- // We set this bit which is checked in setAttribute for
- // Qt::WA_PaintOnScreen. We do this to allow these two scenarios:
- //
- // 1. Users accidentally set Qt::WA_PaintOnScreen on X and port to
- // windows which would mean suddenly their widgets stop working.
- //
- // 2. Users set paint on screen and subclass paintEngine() to
- // return 0, in which case we have a "hole" in the backingstore
- // allowing use of GDI or DirectX directly.
- //
- // 1 is WRONG, but to minimize silent failures, we have set this
- // bit to ignore the setAttribute call. 2. needs to be
- // supported because its our only means of embeddeding native
- // graphics stuff.
- const_cast<QWidgetPrivate *>(d_func())->noPaintOnScreen = 1;
-
- return 0;
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
- Q_Q(QWidget);
- return new QRasterWindowSurface(q);
-}
-
-void QWidgetPrivate::setModal_sys()
-{
-}
-
-void QWidgetPrivate::registerTouchWindow()
-{
- Q_Q(QWidget);
-
- // enable WM_TOUCH* messages on our window
- if (q->testAttribute(Qt::WA_WState_Created)
- && QApplicationPrivate::RegisterTouchWindow
- && q->windowType() != Qt::Desktop)
- QApplicationPrivate::RegisterTouchWindow(q->effectiveWinId(), 0);
-}
-
-void QWidgetPrivate::winSetupGestures()
-{
-#if !defined(QT_NO_GESTURES) && !defined(QT_NO_NATIVE_GESTURES)
- Q_Q(QWidget);
- if (!q || !q->isVisible() || !nativeGesturePanEnabled)
- return;
-
- if (!QApplicationPrivate::HasTouchSupport)
- return;
- QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
- if (!qAppPriv->SetGestureConfig)
- return;
- WId winid = q->internalWinId();
-
- bool needh = false;
- bool needv = false;
- bool singleFingerPanEnabled = false;
-
-#ifndef QT_NO_SCROLLAREA
- if (QAbstractScrollArea *asa = qobject_cast<QAbstractScrollArea*>(q->parent())) {
- QScrollBar *hbar = asa->horizontalScrollBar();
- QScrollBar *vbar = asa->verticalScrollBar();
- Qt::ScrollBarPolicy hbarpolicy = asa->horizontalScrollBarPolicy();
- Qt::ScrollBarPolicy vbarpolicy = asa->verticalScrollBarPolicy();
- needh = (hbarpolicy == Qt::ScrollBarAlwaysOn ||
- (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum()));
- needv = (vbarpolicy == Qt::ScrollBarAlwaysOn ||
- (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum()));
- singleFingerPanEnabled = asa->d_func()->singleFingerPanEnabled;
- if (!winid) {
- winid = q->winId(); // enforces the native winid on the viewport
- }
- }
-#endif //QT_NO_SCROLLAREA
- if (winid) {
- GESTURECONFIG gc[1];
- memset(gc, 0, sizeof(gc));
- gc[0].dwID = GID_PAN;
- if (nativeGesturePanEnabled) {
- gc[0].dwWant = GC_PAN;
- if (needv && singleFingerPanEnabled)
- gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
- else
- gc[0].dwBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
- if (needh && singleFingerPanEnabled)
- gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
- else
- gc[0].dwBlock |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
- } else {
- gc[0].dwBlock = GC_PAN;
- }
-
- qAppPriv->SetGestureConfig(winid, 0, sizeof(gc)/sizeof(gc[0]), gc, sizeof(gc[0]));
- }
-#endif
-}
-
-QT_END_NAMESPACE
-
-#ifdef Q_WS_WINCE
-# include "qwidget_wince.cpp"
-#endif
diff --git a/src/gui/platforms/win/qwidget_wince.cpp b/src/gui/platforms/win/qwidget_wince.cpp
deleted file mode 100644
index 7676182ef0..0000000000
--- a/src/gui/platforms/win/qwidget_wince.cpp
+++ /dev/null
@@ -1,675 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#ifdef Q_WS_WINCE
-
-#include "qguifunctions_wince.h"
-
-QT_BEGIN_NAMESPACE
-
-const QString qt_reg_winclass(QWidget *w); // defined in qapplication_win.cpp
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-//#define TABLET_DEBUG
-#define PACKETDATA (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
- | PK_ORIENTATION | PK_CURSOR | PK_Z)
-#define PACKETMODE 0
-
-typedef HCTX (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
-typedef BOOL (API *PtrWTClose)(HCTX);
-typedef UINT (API *PtrWTInfo)(UINT, UINT, LPVOID);
-typedef BOOL (API *PtrWTEnable)(HCTX, BOOL);
-typedef BOOL (API *PtrWTOverlap)(HCTX, BOOL);
-typedef int (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
-typedef BOOL (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
-typedef int (API *PtrWTQueueSizeGet)(HCTX);
-typedef BOOL (API *PtrWTQueueSizeSet)(HCTX, int);
-
-#ifndef QT_NO_TABLETEVENT
-static void qt_tablet_init_wce();
-static void qt_tablet_cleanup_wce();
-
-static void qt_tablet_init_wce() {
- static bool firstTime = true;
- if (!firstTime)
- return;
- firstTime = false;
- qt_tablet_widget = new QWidget(0);
- qt_tablet_widget->createWinId();
- qt_tablet_widget->setObjectName(QLatin1String("Qt internal tablet widget"));
- LOGCONTEXT lcMine;
- qAddPostRoutine(qt_tablet_cleanup_wce);
- struct tagAXIS tpOri[3];
- if (ptrWTInfo && ptrWTOpen && ptrWTQueueSizeGet && ptrWTQueueSizeSet) {
- // make sure we have WinTab
- if (!ptrWTInfo(0, 0, NULL)) {
-#ifdef TABLET_DEBUG
- qWarning("QWidget: Wintab services not available");
-#endif
- return;
- }
-
- // some tablets don't support tilt, check if it is possible,
- qt_tablet_tilt_support = ptrWTInfo(WTI_DEVICES, DVC_ORIENTATION, &tpOri);
- if (qt_tablet_tilt_support) {
- // check for azimuth and altitude
- qt_tablet_tilt_support = tpOri[0].axResolution && tpOri[1].axResolution;
- }
- // build our context from the default context
- ptrWTInfo(WTI_DEFSYSCTX, 0, &lcMine);
- // Go for the raw coordinates, the tablet event will return good stuff
- lcMine.lcOptions |= CXO_MESSAGES | CXO_CSRMESSAGES;
- lcMine.lcPktData = PACKETDATA;
- lcMine.lcPktMode = PACKETMODE;
- lcMine.lcMoveMask = PACKETDATA;
- lcMine.lcOutOrgX = 0;
- lcMine.lcOutExtX = lcMine.lcInExtX;
- lcMine.lcOutOrgY = 0;
- lcMine.lcOutExtY = -lcMine.lcInExtY;
- qt_tablet_context = ptrWTOpen(qt_tablet_widget->winId(), &lcMine, true);
-#ifdef TABLET_DEBUG
- qDebug("Tablet is %p", qt_tablet_context);
-#endif
- if (!qt_tablet_context) {
-#ifdef TABLET_DEBUG
- qWarning("QWidget: Failed to open the tablet");
-#endif
- return;
- }
- // Set the size of the Packet Queue to the correct size...
- int currSize = ptrWTQueueSizeGet(qt_tablet_context);
- if (!ptrWTQueueSizeSet(qt_tablet_context, QT_TABLET_NPACKETQSIZE)) {
- // Ideally one might want to use a smaller
- // multiple, but for now, since we managed to destroy
- // the existing Q with the previous call, set it back
- // to the other size, which should work. If not,
- // there will be trouble.
- if (!ptrWTQueueSizeSet(qt_tablet_context, currSize)) {
- Q_ASSERT_X(0, "Qt::Internal", "There is no packet queue for"
- " the tablet. The tablet will not work");
- }
- }
- }
-}
-
-static void qt_tablet_cleanup_wce() {
- if (ptrWTClose)
- ptrWTClose(qt_tablet_context);
- delete qt_tablet_widget;
- qt_tablet_widget = 0;
-}
-#endif // QT_NO_TABLETEVENT
-
-
-// The internal qWinRequestConfig, defined in qapplication_win.cpp, stores move,
-// resize and setGeometry requests for a widget that is already
-// processing a config event. The purpose is to avoid recursion.
-//
-void qWinRequestConfig(WId, int, int, int, int, int);
-
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow) {
- Q_Q(QWidget);
- static int sw = -1, sh = -1;
-
- Qt::WindowType type = q->windowType();
- Qt::WindowFlags flags = data.window_flags;
-
- bool topLevel = (flags & Qt::Window);
- bool popup = (type == Qt::Popup);
- bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet
- || (flags & Qt::MSWindowsFixedSizeDialogHint));
- bool desktop = (type == Qt::Desktop);
- bool tool = (type == Qt::Tool || type == Qt::Drawer);
-
- HINSTANCE appinst = qWinAppInst();
- HWND parentw, destroyw = 0;
- WId id;
-
- QString windowClassName = qt_reg_winclass(q);
-
- if (!window) // always initialize
- initializeWindow = true;
-
- if (popup)
- flags |= Qt::WindowStaysOnTopHint; // a popup stays on top
-
- if (flags & (Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowContextHelpButtonHint)) {
- flags |= Qt::WindowSystemMenuHint;
- flags |= Qt::WindowTitleHint;
- flags &= ~Qt::FramelessWindowHint;
- }
-
- if (sw < 0) { // get the (primary) screen size
- sw = GetSystemMetrics(SM_CXSCREEN);
- sh = GetSystemMetrics(SM_CYSCREEN);
- }
-
- if (desktop) { // desktop widget
- popup = false; // force this flags off
- data.crect.setRect(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
- }
-
- parentw = q->parentWidget() ? q->parentWidget()->effectiveWinId() : 0;
-
- QString title;
- int style = WS_CHILD;
- int exsty = WS_EX_NOPARENTNOTIFY;
-
- if (topLevel) {
- if (!(flags & Qt::FramelessWindowHint) && !tool && !q->testAttribute(Qt::WA_DontShowOnScreen))
- style = (WS_OVERLAPPED) | WS_SYSMENU;
- else
- style = WS_POPUP;
- if ((type == Qt::ToolTip) || (type == Qt::SplashScreen)) {
- style = WS_POPUP;
- exsty |= WS_EX_NOANIMATION;
- } else {
- if (flags & Qt::WindowTitleHint)
- style |= WS_CAPTION;
- if (flags & Qt::WindowSystemMenuHint)
- style |= WS_SYSMENU;
- if (flags & Qt::WindowContextHelpButtonHint)
- exsty |= WS_EX_CONTEXTHELP;
-#ifndef Q_WS_WINCE_WM
- if (flags & Qt::WindowMinimizeButtonHint)
- style |= WS_MINIMIZEBOX;
- if (shouldShowMaximizeButton())
- style |= WS_MAXIMIZEBOX;
-#endif
- if (tool)
- exsty |= WS_EX_TOOLWINDOW;
- }
- }
- if (dialog) {
- style = WS_BORDER | WS_CAPTION;
- if (flags & Qt::WindowOkButtonHint)
- exsty |= WS_EX_CAPTIONOKBTN;
- if (flags & Qt::WindowCancelButtonHint || flags & Qt::WA_DeleteOnClose)
- style |= WS_SYSMENU;
- if (flags & Qt::WindowContextHelpButtonHint)
- exsty |= WS_EX_CONTEXTHELP;
- }
- if (popup) {
- style = WS_POPUP;
- exsty |= WS_EX_NOANIMATION;
- }
-
- if (flags & Qt::WindowTitleHint) {
- title = q->isWindow() ? qAppName() : q->objectName();
- }
-
- // The Qt::WA_WState_Created flag is checked by translateConfigEvent() in
- // qapplication_win.cpp. We switch it off temporarily to avoid move
- // and resize events during creationt
- q->setAttribute(Qt::WA_WState_Created, false);
-
- if (window) { // override the old window
- if (destroyOldWindow)
- destroyw = data.winid;
- id = window;
- setWinId(window);
- LONG res = SetWindowLong(window, GWL_STYLE, style);
- if (!res)
- qErrnoWarning("QWidget::create: Failed to set window style");
-
- res = SetWindowLong( window, GWL_WNDPROC, (LONG)QtWndProc );
-
- if (!res)
- qErrnoWarning("QWidget::create: Failed to set window procedure");
- } else if (desktop) { // desktop widget
- id = GetDesktopWindow();
- if (!id) { //Create a dummy desktop
- RECT r;
- SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
- id = CreateWindow(reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
- reinterpret_cast<const wchar_t *>(title.utf16()), style,
- r.left, r.top, r.right - r.left, r.bottom - r.top,
- 0, 0, appinst, 0);
- }
- setWinId(id);
- } else if (topLevel) { // create top-level widget
- const bool wasMoved = q->testAttribute(Qt::WA_Moved);
-
- int x, y;
- if (qt_wince_is_mobile()) {
- x = wasMoved ? data.crect.left() : CW_USEDEFAULT;
- y = wasMoved ? data.crect.top() : CW_USEDEFAULT;
- } else {
- x = wasMoved ? data.crect.left() : 100;
- y = wasMoved ? data.crect.top() : 100;
- }
-
- int w = CW_USEDEFAULT;
- int h = CW_USEDEFAULT;
-
- // Adjust for framestrut when needed
- RECT rect = {0,0,0,0};
- if (AdjustWindowRectEx(&rect, style, FALSE, exsty)) {
- QTLWExtra *td = maybeTopData();
- if (wasMoved && (td && !td->posFromMove)) {
- x = data.crect.x() + rect.left;
- y = data.crect.y() + rect.top;
- }
-
- if (q->testAttribute(Qt::WA_Resized)) {
- w = data.crect.width() + (rect.right - rect.left);
- h = data.crect.height() + (rect.bottom - rect.top);
- }
- }
-
- id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
- reinterpret_cast<const wchar_t *>(title.utf16()), style,
- x, y, w, h,
- 0, 0, appinst, 0);
-
- if (!id)
- qErrnoWarning("QWidget::create: Failed to create window");
- setWinId(id);
- if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip))
- SetWindowPos(id, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
- } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create child widget
- id = CreateWindowEx(exsty, (wchar_t*)windowClassName.utf16(), (wchar_t*)title.utf16(), style,
- data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(),
- parentw, NULL, appinst, NULL);
- if (!id)
- qErrnoWarning("QWidget::create: Failed to create window");
- SetWindowPos(id, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
- setWinId(id);
- }
-
- if (desktop) {
- q->setAttribute(Qt::WA_WState_Visible);
- } else if (topLevel && !q->testAttribute(Qt::WA_DontShowOnScreen)) {
- RECT cr;
- GetClientRect(id, &cr);
- // one cannot trust cr.left and cr.top, use a correction POINT instead
- POINT pt;
- pt.x = 0;
- pt.y = 0;
- if (!q->testAttribute(Qt::WA_DontShowOnScreen) || q->testAttribute(Qt::WA_Moved))
- ClientToScreen(id, &pt);
- data.crect = QRect(QPoint(pt.x, pt.y),
- QPoint(pt.x + cr.right - 1, pt.y + cr.bottom - 1));
-
- if (data.fstrut_dirty) {
- // be nice to activeqt
- updateFrameStrut();
- }
- }
-
- q->setAttribute(Qt::WA_WState_Created); // accept move/resize events
- hd = 0; // no display context
-
- if (window) { // got window from outside
- if (IsWindowVisible(window))
- q->setAttribute(Qt::WA_WState_Visible);
- else
- q->setAttribute(Qt::WA_WState_Visible, false);
- }
-
- if (extra && !extra->mask.isEmpty())
- setMask_sys(extra->mask);
-
-#if defined(QT_NON_COMMERCIAL)
- QT_NC_WIDGET_CREATE
-#endif
-
- if (q->hasFocus() && q->testAttribute(Qt::WA_InputMethodEnabled))
- q->inputContext()->setFocusWidget(q);
-
- if (destroyw) {
- DestroyWindow(destroyw);
- }
-
-#ifndef QT_NO_TABLETEVENT
- if (q != qt_tablet_widget && QWidgetPrivate::mapper)
- qt_tablet_init_wce();
-#endif // QT_NO_TABLETEVENT
-
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- registerDropSite(true);
-
- if (maybeTopData() && maybeTopData()->opacity != 255)
- q->setWindowOpacity(maybeTopData()->opacity/255.);
-
- if (!topLevel && q->testAttribute(Qt::WA_NativeWindow) && q->testAttribute(Qt::WA_Mapped)) {
- Q_ASSERT(q->internalWinId());
- ShowWindow(q->internalWinId(), SW_SHOW);
- }
-}
-
-/*
- \internal
- Platform-specific part of QWidget::show().
-*/
-void QWidgetPrivate::show_sys() {
- Q_Q(QWidget);
-#if defined(QT_NON_COMMERCIAL)
- QT_NC_SHOW_WINDOW
-#endif
- if (q->testAttribute(Qt::WA_OutsideWSRange))
- return;
-
- q->setAttribute(Qt::WA_Mapped);
-
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
- invalidateBuffer(q->rect());
- return;
- }
-
-
- int sm = SW_SHOW;
- bool fakedMaximize = false;
- if (q->isWindow()) {
-#ifndef Q_WS_WINCE_WM
- if (q->isMinimized()) {
- sm = SW_SHOWMINIMIZED;
- } else if (q->isMaximized()) {
- sm = SW_SHOWMAXIMIZED;
- // Windows will not behave correctly when we try to maximize a window which does not
- // have minimize nor maximize buttons in the window frame. Windows would then ignore
- // non-available geometry, and rather maximize the widget to the full screen, minus the
- // window frame (caption). So, we do a trick here, by adding a maximize button before
- // maximizing the widget, and then remove the maximize button afterwards.
- Qt::WindowFlags &flags = data.window_flags;
- if (flags & Qt::WindowTitleHint &&
- !(flags & (Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint))) {
- fakedMaximize = TRUE;
- int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
- SetWindowLong(q->internalWinId(), GWL_STYLE, style | WS_MAXIMIZEBOX);
- }
- } else
-#else
- // Imitate minimizing on Windows mobile by hiding the widget.
- if (q->isMinimized())
- sm = SW_HIDE;
-#endif
- if (q->isHidden()) {
- sm = SW_HIDE;
- }
- }
- if (q->testAttribute(Qt::WA_ShowWithoutActivating)
- || (q->windowType() == Qt::Popup)
- || (q->windowType() == Qt::ToolTip)
- || (q->windowType() == Qt::Tool)) {
- sm = SW_SHOWNOACTIVATE;
- }
-
- ShowWindow(q->internalWinId(), sm);
-
- if (q->isMaximized() && q->isWindow())
- qt_wince_maximize(q);
-
-#ifndef Q_WS_WINCE_WM
- if (!qt_wince_is_mobile() && q->isFullScreen()) {
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- ShowWindow(handle, SW_HIDE);
- EnableWindow(handle, false);
- }
- }
-
- if (fakedMaximize) {
- int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
- SetWindowLong(q->internalWinId(), GWL_STYLE, style & ~WS_MAXIMIZEBOX);
- SetWindowPos(q->internalWinId(), 0, 0, 0, 0, 0,
- SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER
- | SWP_FRAMECHANGED);
- }
-#else
- Q_UNUSED(fakedMaximize);
-#endif
-
- if (q->isWindow() && sm == SW_SHOW)
- SetForegroundWindow(q->internalWinId());
-
- invalidateBuffer(q->rect());
-}
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
- Q_D(QWidget);
- Qt::WindowStates oldstate = windowState();
- if (oldstate == newstate)
- return;
-
- int max = SW_SHOWNORMAL;
- int normal = SW_SHOWNOACTIVATE;
-
- if ((oldstate & Qt::WindowMinimized) && !(newstate & Qt::WindowMinimized))
- newstate |= Qt::WindowActive;
- if (newstate & Qt::WindowActive)
- normal = SW_SHOWNORMAL;
- if (isWindow()) {
- createWinId();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- // Ensure the initial size is valid, since we store it as normalGeometry below.
- if ((!testAttribute(Qt::WA_Resized) && !isVisible()))
- adjustSize();
- if (!d->topData()->normalGeometry.isValid()) {
- if (newstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen))
- d->topData()->normalGeometry = geometry();
- if (newstate & Qt::WindowMinimized && !(oldstate & Qt::WindowFullScreen))
- d->topData()->normalGeometry = geometry();
- }
- if ((oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized)) {
- if (!(newstate & Qt::WindowMaximized)) {
- int style = GetWindowLong(internalWinId(), GWL_STYLE) | WS_BORDER | WS_POPUP | WS_CAPTION;
- SetWindowLong(internalWinId(), GWL_STYLE, style);
- SetWindowLong(internalWinId(), GWL_EXSTYLE, GetWindowLong (internalWinId(), GWL_EXSTYLE) & ~ WS_EX_NODRAG);
- qt_wince_unmaximize(this);
- }
- if (isVisible() && newstate & Qt::WindowMaximized)
- qt_wince_maximize(this);
- if (isVisible() && !(newstate & Qt::WindowMinimized)) {
- ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
- if (!(newstate & Qt::WindowFullScreen)) {
- QRect r = d->topData()->normalGeometry;
- if (!(newstate & Qt::WindowMaximized) && r.width() >= 0) {
- if (pos() != r.topLeft() || size() !=r.size()) {
- d->topData()->normalGeometry = QRect(0,0,-1,-1);
- setGeometry(r);
- }
- }
- } else {
- d->updateFrameStrut();
- }
- }
- }
- if ((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
- if (newstate & Qt::WindowFullScreen) {
- if (d->topData()->normalGeometry.width() < 0 && !(oldstate & Qt::WindowMaximized))
- d->topData()->normalGeometry = geometry();
- d->topData()->savedFlags = (Qt::WindowFlags)GetWindowLong(internalWinId(), GWL_STYLE);
- UINT style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP;
- if (isVisible())
- style |= WS_VISIBLE;
- SetWindowLong(internalWinId(), GWL_STYLE, style);
- QRect r = qApp->desktop()->screenGeometry(this);
- UINT swpf = SWP_FRAMECHANGED;
- if (newstate & Qt::WindowActive)
- swpf |= SWP_NOACTIVATE;
- qt_wince_full_screen(internalWinId(), true, swpf);
- d->updateFrameStrut();
- } else {
- UINT style = d->topData()->savedFlags;
- if (isVisible())
- style |= WS_VISIBLE;
- SetWindowLong(internalWinId(), GWL_STYLE, style);
- UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE;
- if (newstate & Qt::WindowActive)
- swpf |= SWP_NOACTIVATE;
- qt_wince_full_screen(internalWinId(), false, swpf);
- d->updateFrameStrut();
-
- // preserve maximized state
- if (isVisible()) {
- ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
- if (newstate & Qt::WindowMaximized)
- qt_wince_maximize(this);
- }
- if (!(newstate & Qt::WindowMaximized)) {
- QRect r = d->topData()->normalGeometry;
- d->topData()->normalGeometry = QRect(0,0,-1,-1);
- if (r.isValid())
- setGeometry(r);
- }
- }
- }
- if ((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
- if (newstate & Qt::WindowMinimized)
- qt_wince_minimize(internalWinId());
- else if (newstate & Qt::WindowMaximized) {
- ShowWindow(internalWinId(), max);
- qt_wince_maximize(this);
- } else {
- ShowWindow(internalWinId(), normal);
- }
- }
- }
- data->window_state = newstate;
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
- Q_Q(QWidget);
- if (!qt_wince_is_mobile() && q->isFullScreen()) {
- HWND handle = FindWindow(L"HHTaskBar", L"");
- if (handle) {
- ShowWindow(handle, SW_SHOWNORMAL);
- EnableWindow(handle, true);
- }
- }
-}
-
-void QWidgetPrivate::setWindowOpacity_sys(qreal level) {
- Q_UNUSED(level);
- return;
-}
-
-// The procedure does nothing, but is required for mousegrabbing to work
-LRESULT QT_WIN_CALLBACK qJournalRecordProc(int nCode, WPARAM wParam, LPARAM lParam) {
- Q_UNUSED(nCode);
- Q_UNUSED(wParam);
- Q_UNUSED(lParam);
- return 0;
-}
-
-void QWidget::grabMouse() {
- if (!qt_nograb()) {
- if (mouseGrb)
- mouseGrb->releaseMouse();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- SetCapture(internalWinId());
- mouseGrb = this;
- }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor) {
- if (!qt_nograb()) {
- if (mouseGrb)
- mouseGrb->releaseMouse();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- SetCapture(internalWinId());
- mouseGrbCur = new QCursor(cursor);
- SetCursor(mouseGrbCur->handle());
- mouseGrb = this;
- }
-}
-#endif
-
-void QWidget::releaseMouse() {
- if (!qt_nograb() && mouseGrb == this) {
- ReleaseCapture();
- if (journalRec) {
- journalRec = 0;
- }
- if (mouseGrbCur) {
- delete mouseGrbCur;
- mouseGrbCur = 0;
- }
- mouseGrb = 0;
- }
-}
-
-void QWidget::show()
-{
- Qt::WindowFlags flags = windowFlags() & 0xff;
- int threshold = qApp->autoMaximizeThreshold();
- if ((threshold < 0) || (windowState() & Qt::WindowFullScreen) || (windowState() & Qt::WindowMaximized)) {
- setVisible(true);
- return;
- }
- int height = sizeHint().height();
- int screenHeight = (qreal(threshold) / 100.0f * qApp->desktop()->screenGeometry(this).height());
- bool maximize = height > screenHeight;
- if (!maximize) {
- // If we do not maximize yet we check the widget and its child widgets whether they are
- //vertically expanding. If one of the widgets is expanding we maximize.
- QList<QWidget *> list = findChildren<QWidget *>();
- bool expandingChild = sizePolicy().verticalPolicy () == QSizePolicy::Expanding;
- for (int i = 0; (i < list.size()) && !expandingChild; ++i) {
- expandingChild = list.at(i)->sizePolicy().verticalPolicy () == QSizePolicy::Expanding;
- }
- maximize = expandingChild;
- }
- if ((minimumSizeHint().height() > qApp->desktop()->screenGeometry(this).height()) || (minimumSizeHint().width() > qApp->desktop()->screenGeometry(this).width()))
- maximize = false;
-
- if ((flags == Qt::Window || flags == Qt::Dialog) && maximize) {
- setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
- | Qt::WindowMaximized);
- setVisible(true);
- }
- else {
- setVisible(true);
- }
-}
-
-QT_END_NAMESPACE
-
-#endif // Q_WS_WINCE
diff --git a/src/gui/platforms/win/qwindowdefs_win.h b/src/gui/platforms/win/qwindowdefs_win.h
deleted file mode 100644
index a4dd38410c..0000000000
--- a/src/gui/platforms/win/qwindowdefs_win.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWDEFS_WIN_H
-#define QWINDOWDEFS_WIN_H
-
-#include <QtCore/qglobal.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-QT_END_NAMESPACE
-
-#if !defined(Q_NOWINSTRICT)
-#define Q_WINSTRICT
-#endif
-
-#if defined(Q_WINSTRICT)
-
-#if !defined(STRICT)
-#define STRICT
-#endif
-#undef NO_STRICT
-#define Q_DECLARE_HANDLE(name) struct name##__; typedef struct name##__ *name
-
-#else
-
-#if !defined(NO_STRICT)
-#define NO_STRICT
-#endif
-#undef STRICT
-#define Q_DECLARE_HANDLE(name) typedef HANDLE name
-
-#endif
-
-#ifndef HINSTANCE
-Q_DECLARE_HANDLE(HINSTANCE);
-#endif
-#ifndef HDC
-Q_DECLARE_HANDLE(HDC);
-#endif
-#ifndef HWND
-Q_DECLARE_HANDLE(HWND);
-#endif
-#ifndef HFONT
-Q_DECLARE_HANDLE(HFONT);
-#endif
-#ifndef HPEN
-Q_DECLARE_HANDLE(HPEN);
-#endif
-#ifndef HBRUSH
-Q_DECLARE_HANDLE(HBRUSH);
-#endif
-#ifndef HBITMAP
-Q_DECLARE_HANDLE(HBITMAP);
-#endif
-#ifndef HICON
-Q_DECLARE_HANDLE(HICON);
-#endif
-#ifndef HCURSOR
-typedef HICON HCURSOR;
-#endif
-#ifndef HPALETTE
-Q_DECLARE_HANDLE(HPALETTE);
-#endif
-#ifndef HRGN
-Q_DECLARE_HANDLE(HRGN);
-#endif
-#ifndef HMONITOR
-Q_DECLARE_HANDLE(HMONITOR);
-#endif
-#ifndef HRESULT
-typedef long HRESULT;
-#endif
-
-typedef struct tagMSG MSG;
-typedef HWND WId;
-
-
-QT_BEGIN_NAMESPACE
-
-Q_CORE_EXPORT HINSTANCE qWinAppInst();
-Q_CORE_EXPORT HINSTANCE qWinAppPrevInst();
-Q_CORE_EXPORT int qWinAppCmdShow();
-Q_GUI_EXPORT HDC qt_win_display_dc();
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWINDOWDEFS_WIN_H
diff --git a/src/gui/platforms/win/qwinnativepangesturerecognizer_win.cpp b/src/gui/platforms/win/qwinnativepangesturerecognizer_win.cpp
deleted file mode 100644
index 0d13bafc0c..0000000000
--- a/src/gui/platforms/win/qwinnativepangesturerecognizer_win.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qwinnativepangesturerecognizer_win_p.h"
-
-#include "qevent.h"
-#include "qgraphicsitem.h"
-#include "qgesture.h"
-
-#include "private/qgesture_p.h"
-#include "private/qevent_p.h"
-#include "private/qapplication_p.h"
-#include "private/qwidget_p.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(QT_NO_NATIVE_GESTURES)
-
-QWinNativePanGestureRecognizer::QWinNativePanGestureRecognizer()
-{
-}
-
-QGesture *QWinNativePanGestureRecognizer::create(QObject *target)
-{
- if (!target)
- return new QPanGesture; // a special case
- if (!target->isWidgetType())
- return 0;
- if (qobject_cast<QGraphicsObject *>(target))
- return 0;
-
- QWidget *q = static_cast<QWidget *>(target);
- QWidgetPrivate *d = q->d_func();
- d->nativeGesturePanEnabled = true;
- d->winSetupGestures();
-
- return new QPanGesture;
-}
-
-QGestureRecognizer::Result QWinNativePanGestureRecognizer::recognize(QGesture *state,
- QObject *,
- QEvent *event)
-{
- QPanGesture *q = static_cast<QPanGesture*>(state);
- QPanGesturePrivate *d = q->d_func();
-
- QGestureRecognizer::Result result = QGestureRecognizer::Ignore;
- if (event->type() == QEvent::NativeGesture) {
- QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event);
- switch(ev->gestureType) {
- case QNativeGestureEvent::GestureBegin:
- break;
- case QNativeGestureEvent::Pan:
- result = QGestureRecognizer::TriggerGesture;
- event->accept();
- break;
- case QNativeGestureEvent::GestureEnd:
- if (q->state() == Qt::NoGesture)
- return QGestureRecognizer::Ignore; // some other gesture has ended
- result = QGestureRecognizer::FinishGesture;
- break;
- default:
- return QGestureRecognizer::Ignore;
- }
- if (q->state() == Qt::NoGesture) {
- d->lastOffset = d->offset = QPointF();
- d->startPosition = ev->position;
- } else {
- d->lastOffset = d->offset;
- d->offset = QPointF(ev->position.x() - d->startPosition.x(),
- ev->position.y() - d->startPosition.y());
- }
- }
- return result;
-}
-
-void QWinNativePanGestureRecognizer::reset(QGesture *state)
-{
- QPanGesture *pan = static_cast<QPanGesture*>(state);
- QPanGesturePrivate *d = pan->d_func();
-
- d->lastOffset = d->offset = QPointF();
- d->startPosition = QPoint();
- d->acceleration = 0;
-
- QGestureRecognizer::reset(state);
-}
-
-#endif // QT_NO_NATIVE_GESTURES
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/platforms/win/qwinnativepangesturerecognizer_win_p.h b/src/gui/platforms/win/qwinnativepangesturerecognizer_win_p.h
deleted file mode 100644
index 6d23e41ce3..0000000000
--- a/src/gui/platforms/win/qwinnativepangesturerecognizer_win_p.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINNATIVEPANGESTURERECOGNIZER_WIN_P_H
-#define QWINNATIVEPANGESTURERECOGNIZER_WIN_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 <QGestureRecognizer>
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(QT_NO_NATIVE_GESTURES)
-
-class QWinNativePanGestureRecognizer : public QGestureRecognizer
-{
-public:
- QWinNativePanGestureRecognizer();
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-};
-
-#endif // QT_NO_NATIVE_GESTURES
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QWINNATIVEPANGESTURERECOGNIZER_WIN_P_H
diff --git a/src/gui/platforms/x11/qapplication_x11.cpp b/src/gui/platforms/x11/qapplication_x11.cpp
deleted file mode 100644
index 20542ea328..0000000000
--- a/src/gui/platforms/x11/qapplication_x11.cpp
+++ /dev/null
@@ -1,6239 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-// ### 4.0: examine Q_EXPORT's below. The respective symbols had all
-// been in use (e.g. in the KDE wm) before the introduction of a version
-// map. One might want to turn some of them into proper public API and
-// provide a proper alternative for others. See also the exports in
-// qapplication_win.cpp, which suggest a unification.
-
-#include "qplatformdefs.h"
-
-#include "qcolormap.h"
-#include "qdesktopwidget.h"
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qcursor.h"
-#include "qwidget.h"
-#include "qbitarray.h"
-#include "qpainter.h"
-#include "qfile.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 "qwhatsthis.h"
-#include "qsettings.h"
-#include "qstylefactory.h"
-#include "qfileinfo.h"
-#include "qdir.h"
-#include "qhash.h"
-#include "qevent.h"
-#include "qevent_p.h"
-#include "qvarlengtharray.h"
-#include "qdebug.h"
-#include <private/qcrashhandler_p.h>
-#include <private/qcolor_p.h>
-#include <private/qcursor_p.h>
-#include <private/qiconloader_p.h>
-#include <qgtkstyle.h>
-#include "qstyle.h"
-#include "qmetaobject.h"
-#include "qtimer.h"
-#include "qlibrary.h"
-#include <private/qgraphicssystemfactory_p.h>
-#include "qguiplatformplugin_p.h"
-#include "qkde_p.h"
-
-#if !defined (QT_NO_TABLET)
-extern "C" {
-# define class c_class //XIproto.h has a name member named 'class' which the c++ compiler doesn't like
-# include <wacomcfg.h>
-# undef class
-}
-#endif
-
-#ifndef QT_GUI_DOUBLE_CLICK_RADIUS
-#define QT_GUI_DOUBLE_CLICK_RADIUS 5
-#endif
-
-
-//#define ALIEN_DEBUG
-
-#if !defined(QT_NO_GLIB)
-# include "qguieventdispatcher_glib_p.h"
-#endif
-#include "qeventdispatcher_x11_p.h"
-#include <private/qpaintengine_x11_p.h>
-
-#include <private/qkeymapper_p.h>
-
-// Input method stuff
-#ifndef QT_NO_IM
-#include "qinputcontext.h"
-#include "qinputcontextfactory.h"
-#endif // QT_NO_IM
-
-#ifndef QT_NO_XFIXES
-#include <X11/extensions/Xfixes.h>
-#endif // QT_NO_XFIXES
-
-#include "qt_x11_p.h"
-#include "qx11info_x11.h"
-
-#define XK_MISCELLANY
-#include <X11/keysymdef.h>
-#if !defined(QT_NO_XINPUT)
-#include <X11/extensions/XI.h>
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <locale.h>
-
-#include "qwidget_p.h"
-
-#include <private/qbackingstore_p.h>
-
-#ifdef QT_RX71_MULTITOUCH
-# include <qsocketnotifier.h>
-# include <linux/input.h>
-# include <errno.h>
-#endif
-
-#if _POSIX_VERSION+0 < 200112L && !defined(Q_OS_BSD4)
-# define QT_NO_UNSETENV
-#endif
-
-QT_BEGIN_NAMESPACE
-
-//#define X_NOT_BROKEN
-#ifdef X_NOT_BROKEN
-// Some X libraries are built with setlocale #defined to _Xsetlocale,
-// even though library users are then built WITHOUT such a definition.
-// This creates a problem - Qt might setlocale() one value, but then
-// X looks and doesn't see the value Qt set. The solution here is to
-// implement _Xsetlocale just in case X calls it - redirecting it to
-// the real libC version.
-//
-# ifndef setlocale
-extern "C" char *_Xsetlocale(int category, const char *locale);
-char *_Xsetlocale(int category, const char *locale)
-{
- //qDebug("_Xsetlocale(%d,%s),category,locale");
- return setlocale(category,locale);
-}
-# endif // setlocale
-#endif // X_NOT_BROKEN
-
-/* Warning: if you modify this string, modify the list of atoms in qt_x11_p.h as well! */
-static const char * x11_atomnames = {
- // window-manager <-> client protocols
- "WM_PROTOCOLS\0"
- "WM_DELETE_WINDOW\0"
- "WM_TAKE_FOCUS\0"
- "_NET_WM_PING\0"
- "_NET_WM_CONTEXT_HELP\0"
- "_NET_WM_SYNC_REQUEST\0"
- "_NET_WM_SYNC_REQUEST_COUNTER\0"
-
- // ICCCM window state
- "WM_STATE\0"
- "WM_CHANGE_STATE\0"
-
- // Session management
- "WM_CLIENT_LEADER\0"
- "WM_WINDOW_ROLE\0"
- "SM_CLIENT_ID\0"
-
- // Clipboard
- "CLIPBOARD\0"
- "INCR\0"
- "TARGETS\0"
- "MULTIPLE\0"
- "TIMESTAMP\0"
- "SAVE_TARGETS\0"
- "CLIP_TEMPORARY\0"
- "_QT_SELECTION\0"
- "_QT_CLIPBOARD_SENTINEL\0"
- "_QT_SELECTION_SENTINEL\0"
- "CLIPBOARD_MANAGER\0"
-
- "RESOURCE_MANAGER\0"
-
- "_XSETROOT_ID\0"
-
- "_QT_SCROLL_DONE\0"
- "_QT_INPUT_ENCODING\0"
-
- "_MOTIF_WM_HINTS\0"
-
- "DTWM_IS_RUNNING\0"
- "ENLIGHTENMENT_DESKTOP\0"
- "_DT_SAVE_MODE\0"
- "_SGI_DESKS_MANAGER\0"
-
- // EWMH (aka NETWM)
- "_NET_SUPPORTED\0"
- "_NET_VIRTUAL_ROOTS\0"
- "_NET_WORKAREA\0"
-
- "_NET_MOVERESIZE_WINDOW\0"
- "_NET_WM_MOVERESIZE\0"
-
- "_NET_WM_NAME\0"
- "_NET_WM_ICON_NAME\0"
- "_NET_WM_ICON\0"
-
- "_NET_WM_PID\0"
-
- "_NET_WM_WINDOW_OPACITY\0"
-
- "_NET_WM_STATE\0"
- "_NET_WM_STATE_ABOVE\0"
- "_NET_WM_STATE_BELOW\0"
- "_NET_WM_STATE_FULLSCREEN\0"
- "_NET_WM_STATE_MAXIMIZED_HORZ\0"
- "_NET_WM_STATE_MAXIMIZED_VERT\0"
- "_NET_WM_STATE_MODAL\0"
- "_NET_WM_STATE_STAYS_ON_TOP\0"
- "_NET_WM_STATE_DEMANDS_ATTENTION\0"
-
- "_NET_WM_USER_TIME\0"
- "_NET_WM_USER_TIME_WINDOW\0"
- "_NET_WM_FULL_PLACEMENT\0"
-
- "_NET_WM_WINDOW_TYPE\0"
- "_NET_WM_WINDOW_TYPE_DESKTOP\0"
- "_NET_WM_WINDOW_TYPE_DOCK\0"
- "_NET_WM_WINDOW_TYPE_TOOLBAR\0"
- "_NET_WM_WINDOW_TYPE_MENU\0"
- "_NET_WM_WINDOW_TYPE_UTILITY\0"
- "_NET_WM_WINDOW_TYPE_SPLASH\0"
- "_NET_WM_WINDOW_TYPE_DIALOG\0"
- "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0"
- "_NET_WM_WINDOW_TYPE_POPUP_MENU\0"
- "_NET_WM_WINDOW_TYPE_TOOLTIP\0"
- "_NET_WM_WINDOW_TYPE_NOTIFICATION\0"
- "_NET_WM_WINDOW_TYPE_COMBO\0"
- "_NET_WM_WINDOW_TYPE_DND\0"
- "_NET_WM_WINDOW_TYPE_NORMAL\0"
- "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE\0"
-
- "_KDE_NET_WM_FRAME_STRUT\0"
-
- "_NET_STARTUP_INFO\0"
- "_NET_STARTUP_INFO_BEGIN\0"
-
- "_NET_SUPPORTING_WM_CHECK\0"
-
- "_NET_WM_CM_S0\0"
-
- "_NET_SYSTEM_TRAY_VISUAL\0"
-
- "_NET_ACTIVE_WINDOW\0"
-
- // Property formats
- "COMPOUND_TEXT\0"
- "TEXT\0"
- "UTF8_STRING\0"
-
- // xdnd
- "XdndEnter\0"
- "XdndPosition\0"
- "XdndStatus\0"
- "XdndLeave\0"
- "XdndDrop\0"
- "XdndFinished\0"
- "XdndTypeList\0"
- "XdndActionList\0"
-
- "XdndSelection\0"
-
- "XdndAware\0"
- "XdndProxy\0"
-
- "XdndActionCopy\0"
- "XdndActionLink\0"
- "XdndActionMove\0"
- "XdndActionPrivate\0"
-
- // Motif DND
- "_MOTIF_DRAG_AND_DROP_MESSAGE\0"
- "_MOTIF_DRAG_INITIATOR_INFO\0"
- "_MOTIF_DRAG_RECEIVER_INFO\0"
- "_MOTIF_DRAG_WINDOW\0"
- "_MOTIF_DRAG_TARGETS\0"
-
- "XmTRANSFER_SUCCESS\0"
- "XmTRANSFER_FAILURE\0"
-
- // Xkb
- "_XKB_RULES_NAMES\0"
-
- // XEMBED
- "_XEMBED\0"
- "_XEMBED_INFO\0"
-
- // Wacom old. (before version 0.10)
- "Wacom Stylus\0"
- "Wacom Cursor\0"
- "Wacom Eraser\0"
-
- // Tablet
- "STYLUS\0"
- "ERASER\0"
-};
-
-Q_GUI_EXPORT QX11Data *qt_x11Data = 0;
-
-/*****************************************************************************
- Internal variables and functions
- *****************************************************************************/
-static const char *appName = 0; // application name
-static const char *appClass = 0; // application class
-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
-char *qt_ximServer = 0; // XIM Server will connect to
-static bool appSync = false; // X11 synchronization
-#if defined(QT_DEBUG)
-static bool appNoGrab = false; // X11 grabbing enabled
-static bool appDoGrab = false; // X11 grabbing override (gdb)
-#endif
-static bool app_save_rootinfo = false; // save root info
-static bool app_do_modal = false; // modal mode
-static Window curWin = 0; // current window
-
-
-// function to update the workarea of the screen - in qdesktopwidget_x11.cpp
-extern void qt_desktopwidget_update_workarea();
-
-// Function to change the window manager state (from qwidget_x11.cpp)
-extern void qt_change_net_wm_state(const QWidget *w, bool set, Atom one, Atom two = 0);
-
-// modifier masks for alt, meta, super, hyper, and mode_switch - detected when the application starts
-// and/or keyboard layout changes
-uchar qt_alt_mask = 0;
-uchar qt_meta_mask = 0;
-uchar qt_super_mask = 0;
-uchar qt_hyper_mask = 0;
-uchar qt_mode_switch_mask = 0;
-
-// flags for extensions for special Languages, currently only for RTL languages
-bool qt_use_rtl_extensions = false;
-
-static Window mouseActWindow = 0; // window where mouse is
-static Qt::MouseButton mouseButtonPressed = Qt::NoButton; // last mouse button pressed
-static Qt::MouseButtons mouseButtonState = Qt::NoButton; // mouse button state
-static Time mouseButtonPressTime = 0; // when was a button pressed
-static short mouseXPos, mouseYPos; // mouse pres position in act window
-static short mouseGlobalXPos, mouseGlobalYPos; // global mouse press position
-
-extern QWidgetList *qt_modal_stack; // stack of modal widgets
-
-// window where mouse buttons have been pressed
-static Window pressed_window = XNone;
-
-// popup control
-static bool replayPopupMouseEvent = false;
-static bool popupGrabOk;
-
-bool qt_sm_blockUserInput = false; // session management
-
-Q_GUI_EXPORT int qt_xfocusout_grab_counter = 0;
-
-#if !defined (QT_NO_TABLET)
-Q_GLOBAL_STATIC(QTabletDeviceDataList, tablet_devices)
-QTabletDeviceDataList *qt_tablet_devices()
-{
- return tablet_devices();
-}
-
-extern bool qt_tabletChokeMouse;
-#endif
-
-typedef bool(*QX11FilterFunction)(XEvent *event);
-
-Q_GLOBAL_STATIC(QList<QX11FilterFunction>, x11Filters)
-
-Q_GUI_EXPORT void qt_installX11EventFilter(QX11FilterFunction func)
-{
- Q_ASSERT(func);
-
- if (QList<QX11FilterFunction> *list = x11Filters())
- list->append(func);
-}
-
-Q_GUI_EXPORT void qt_removeX11EventFilter(QX11FilterFunction func)
-{
- Q_ASSERT(func);
-
- if (QList<QX11FilterFunction> *list = x11Filters())
- list->removeOne(func);
-}
-
-
-static bool qt_x11EventFilter(XEvent* ev)
-{
- long unused;
- if (qApp->filterEvent(ev, &unused))
- return true;
- if (const QList<QX11FilterFunction> *list = x11Filters()) {
- for (QList<QX11FilterFunction>::const_iterator it = list->constBegin(); it != list->constEnd(); ++it) {
- if ((*it)(ev))
- return true;
- }
- }
-
- return qApp->x11EventFilter(ev);
-}
-
-#if !defined(QT_NO_XIM)
-XIMStyle qt_xim_preferred_style = 0;
-#endif
-int qt_ximComposingKeycode=0;
-QTextCodec * qt_input_mapper = 0;
-
-extern bool qt_check_clipboard_sentinel(); //def in qclipboard_x11.cpp
-extern bool qt_check_selection_sentinel(); //def in qclipboard_x11.cpp
-extern bool qt_xfixes_clipboard_changed(Window clipboardOwner, Time timestamp); //def in qclipboard_x11.cpp
-extern bool qt_xfixes_selection_changed(Window selectionOwner, Time timestamp); //def in qclipboard_x11.cpp
-
-static void qt_save_rootinfo();
-Q_GUI_EXPORT bool qt_try_modal(QWidget *, XEvent *);
-
-QWidget *qt_button_down = 0; // last widget to be pressed with the mouse
-QPointer<QWidget> qt_last_mouse_receiver = 0;
-static QWidget *qt_popup_down = 0; // popup that contains the pressed widget
-
-extern bool qt_xdnd_dragging;
-
-// gui or non-gui from qapplication.cpp
-extern bool qt_is_gui_used;
-
-/*!
- \internal
- Try to resolve a \a symbol from \a library with the version specified
- by \a vernum.
-
- Note that, in the case of the Xfixes library, \a vernum is not the same as
- \c XFIXES_MAJOR - it is a part of soname and may differ from the Xfixes
- version.
-*/
-static void* qt_load_library_runtime(const char *library, int vernum,
- int highestVernum, const char *symbol)
-{
- QList<int> versions;
- // we try to load in the following order:
- // explicit version -> the default one -> (from the highest (highestVernum) to the lowest (vernum) )
- if (vernum != -1)
- versions << vernum;
- versions << -1;
- if (vernum != -1) {
- for(int i = highestVernum; i > vernum; --i)
- versions << i;
- }
- Q_FOREACH(int version, versions) {
- QLatin1String libName(library);
- QLibrary xfixesLib(libName, version);
- void *ptr = xfixesLib.resolve(symbol);
- if (ptr)
- return ptr;
- }
- return 0;
-}
-
-#ifndef QT_NO_XINPUT
-# ifdef QT_RUNTIME_XINPUT
-# define XINPUT_LOAD_RUNTIME(vernum, symbol, symbol_type) \
- (symbol_type)qt_load_library_runtime("libXi", vernum, 6, #symbol);
-# define XINPUT_LOAD(symbol) \
- XINPUT_LOAD_RUNTIME(1, symbol, Ptr##symbol)
-# else // not runtime XInput
-# define XINPUT_LOAD(symbol) symbol
-# endif // QT_RUNTIME_XINPUT
-#else // not using Xinput at all
-# define XINPUT_LOAD(symbol) 0
-#endif // QT_NO_XINPUT
-
-#ifndef QT_NO_XFIXES
-# ifdef QT_RUNTIME_XFIXES
-# define XFIXES_LOAD_RUNTIME(vernum, symbol, symbol_type) \
- (symbol_type)qt_load_library_runtime("libXfixes", vernum, 4, #symbol);
-# define XFIXES_LOAD_V1(symbol) \
- XFIXES_LOAD_RUNTIME(1, symbol, Ptr##symbol)
-# define XFIXES_LOAD_V2(symbol) \
- XFIXES_LOAD_RUNTIME(2, symbol, Ptr##symbol)
-
-# else // not runtime Xfixes
-
-# if XFIXES_MAJOR >= 2
-# define XFIXES_LOAD_V1(symbol) symbol
-# define XFIXES_LOAD_V2(symbol) symbol
-# elif XFIXES_MAJOR >= 1
-# define XFIXES_LOAD_V1(symbol) symbol
-# define XFIXES_LOAD_V2(symbol) 0
-# else
-# error Unsupported version of Xfixes
-# endif
-# endif // QT_RUNTIME_XFIXES
-#else // not using Xfixes at all
-# define XFIXES_LOAD_V1(symbol) 0
-# define XFIXES_LOAD_V2(symbol) 0
-#endif // QT_NO_XFIXES
-
-#ifndef QT_NO_XFIXES
-
-struct qt_xfixes_selection_event_data
-{
- // which selection to filter out.
- Atom selection;
-};
-
-#if defined(Q_C_CALLBACKS)
-extern "C" {
-#endif
-
-static Bool qt_xfixes_scanner(Display*, XEvent *event, XPointer arg)
-{
- qt_xfixes_selection_event_data *data =
- reinterpret_cast<qt_xfixes_selection_event_data*>(arg);
- if (event->type == X11->xfixes_eventbase + XFixesSelectionNotify) {
- XFixesSelectionNotifyEvent *xfixes_event = reinterpret_cast<XFixesSelectionNotifyEvent*>(event);
- if (xfixes_event->selection == data->selection)
- return true;
- }
- return false;
-}
-
-#if defined(Q_C_CALLBACKS)
-}
-#endif
-
-#endif // QT_NO_XFIXES
-
-class QETWidget : public QWidget // event translator widget
-{
-public:
- QWidgetPrivate* d_func() { return QWidget::d_func(); }
- bool translateMouseEvent(const XEvent *);
- void translatePaintEvent(const XEvent *);
- bool translateConfigEvent(const XEvent *);
- bool translateCloseEvent(const XEvent *);
- bool translateScrollDoneEvent(const XEvent *);
- bool translateWheelEvent(int global_x, int global_y, int delta, Qt::MouseButtons buttons,
- Qt::KeyboardModifiers modifiers, Qt::Orientation orient);
-#if !defined (QT_NO_TABLET)
- bool translateXinputEvent(const XEvent*, QTabletDeviceData *tablet);
-#endif
- bool translatePropertyEvent(const XEvent *);
-
- void doDeferredMap()
- {
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- if (!testAttribute(Qt::WA_Resized)) {
- adjustSize();
- setAttribute(Qt::WA_Resized, false);
- }
-
- /*
- workaround for WM's that throw away ConfigureRequests from the following:
-
- window->hide();
- window->move(x, y); // could also be resize(), move()+resize(), or setGeometry()
- window->show();
- */
- QRect r = geometry();
-
- XMoveResizeWindow(X11->display,
- internalWinId(),
- r.x(),
- r.y(),
- r.width(),
- r.height());
-
- // static gravity!
- XSizeHints sh;
- long unused;
- XGetWMNormalHints(X11->display, internalWinId(), &sh, &unused);
- sh.flags |= USPosition | PPosition | USSize | PSize | PWinGravity;
- sh.x = r.x();
- sh.y = r.y();
- sh.width = r.width();
- sh.height = r.height();
- sh.win_gravity = StaticGravity;
- XSetWMNormalHints(X11->display, internalWinId(), &sh);
-
- setAttribute(Qt::WA_Mapped);
- if (testAttribute(Qt::WA_DontShowOnScreen))
- return;
- d_func()->topData()->waitingForMapNotify = 1;
- XMapWindow(X11->display, internalWinId());
- }
-};
-
-
-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 QGuiEventDispatcherGlib(q)
- : new QEventDispatcherGlib(q));
- else
-#endif
- eventDispatcher = (q->type() != QApplication::Tty
- ? new QEventDispatcherX11(q)
- : new QEventDispatcherUNIX(q));
-}
-
-/*****************************************************************************
- Default X error handlers
- *****************************************************************************/
-
-#if defined(Q_C_CALLBACKS)
-extern "C" {
-#endif
-
-static int (*original_x_errhandler)(Display *dpy, XErrorEvent *);
-static int (*original_xio_errhandler)(Display *dpy);
-
-static int qt_x_errhandler(Display *dpy, XErrorEvent *err)
-{
- if (X11->display != dpy) {
- // only handle X errors for our display
- return 0;
- }
-
- switch (err->error_code) {
- case BadAtom:
- if (err->request_code == 20 /* X_GetProperty */
- && (err->resourceid == XA_RESOURCE_MANAGER
- || err->resourceid == XA_RGB_DEFAULT_MAP
- || err->resourceid == ATOM(_NET_SUPPORTED)
- || err->resourceid == ATOM(_NET_SUPPORTING_WM_CHECK)
- || err->resourceid == ATOM(XdndProxy)
- || err->resourceid == ATOM(XdndAware))) {
- // Perhaps we're running under SECURITY reduction? :/
- return 0;
- }
- break;
-
- case BadWindow:
- if (err->request_code == 2 /* X_ChangeWindowAttributes */
- || err->request_code == 38 /* X_QueryPointer */) {
- for (int i = 0; i < ScreenCount(dpy); ++i) {
- if (err->resourceid == RootWindow(dpy, i)) {
- // Perhaps we're running under SECURITY reduction? :/
- return 0;
- }
- }
- }
- X11->seen_badwindow = true;
- if (err->request_code == 25 /* X_SendEvent */) {
- for (int i = 0; i < ScreenCount(dpy); ++i) {
- if (err->resourceid == RootWindow(dpy, i)) {
- // Perhaps we're running under SECURITY reduction? :/
- return 0;
- }
- }
- if (X11->xdndHandleBadwindow()) {
- qDebug("xdndHandleBadwindow returned true");
- return 0;
- }
- }
- if (X11->ignore_badwindow)
- return 0;
- break;
-
- default:
-#if !defined(QT_NO_XINPUT)
- if (err->request_code == X11->xinput_major
- && err->error_code == (X11->xinput_errorbase + XI_BadDevice)
- && err->minor_code == 3 /* X_OpenDevice */) {
- return 0;
- }
-#endif
- break;
- }
-
- char errstr[256];
- XGetErrorText( dpy, err->error_code, errstr, 256 );
- char buffer[256];
- char request_str[256];
- qsnprintf(buffer, 256, "%d", err->request_code);
- XGetErrorDatabaseText(dpy, "XRequest", buffer, "", request_str, 256);
- if (err->request_code < 128) {
- // X error for a normal protocol request
- qWarning( "X Error: %s %d\n"
- " Major opcode: %d (%s)\n"
- " Resource id: 0x%lx",
- errstr, err->error_code,
- err->request_code,
- request_str,
- err->resourceid );
- } else {
- // X error for an extension request
- const char *extensionName = 0;
- if (err->request_code == X11->xrender_major)
- extensionName = "RENDER";
- else if (err->request_code == X11->xrandr_major)
- extensionName = "RANDR";
- else if (err->request_code == X11->xinput_major)
- extensionName = "XInputExtension";
- else if (err->request_code == X11->mitshm_major)
- extensionName = "MIT-SHM";
-#ifndef QT_NO_XKB
- else if(err->request_code == X11->xkb_major)
- extensionName = "XKEYBOARD";
-#endif
-
- char minor_str[256];
- if (extensionName) {
- qsnprintf(buffer, 256, "%s.%d", extensionName, err->minor_code);
- XGetErrorDatabaseText(dpy, "XRequest", buffer, "", minor_str, 256);
- } else {
- extensionName = "Uknown extension";
- qsnprintf(minor_str, 256, "Unknown request");
- }
- qWarning( "X Error: %s %d\n"
- " Extension: %d (%s)\n"
- " Minor opcode: %d (%s)\n"
- " Resource id: 0x%lx",
- errstr, err->error_code,
- err->request_code,
- extensionName,
- err->minor_code,
- minor_str,
- err->resourceid );
- }
-
- // ### we really should distinguish between severe, non-severe and
- // ### application specific errors
-
- return 0;
-}
-
-
-static int qt_xio_errhandler(Display *)
-{
- qWarning("%s: Fatal IO error: client killed", appName);
- QApplicationPrivate::reset_instance_pointer();
- exit(1);
- //### give the application a chance for a proper shutdown instead,
- //### exit(1) doesn't help.
- return 0;
-}
-
-#if defined(Q_C_CALLBACKS)
-}
-#endif
-
-#ifndef QT_NO_XSYNC
-struct qt_sync_request_event_data
-{
- WId window;
-};
-
-#if defined(Q_C_CALLBACKS)
-extern "C" {
-#endif
-
-static Bool qt_sync_request_scanner(Display*, XEvent *event, XPointer arg)
-{
- qt_sync_request_event_data *data =
- reinterpret_cast<qt_sync_request_event_data*>(arg);
- if (event->type == ClientMessage &&
- event->xany.window == data->window &&
- event->xclient.message_type == ATOM(WM_PROTOCOLS) &&
- (Atom)event->xclient.data.l[0] == ATOM(_NET_WM_SYNC_REQUEST)) {
- QWidget *w = QWidget::find(event->xany.window);
- if (QTLWExtra *tlw = ((QETWidget*)w)->d_func()->maybeTopData()) {
- const ulong timestamp = (const ulong) event->xclient.data.l[1];
- if (timestamp > X11->time)
- X11->time = timestamp;
- if (timestamp == CurrentTime || timestamp > tlw->syncRequestTimestamp) {
- tlw->syncRequestTimestamp = timestamp;
- tlw->newCounterValueLo = event->xclient.data.l[2];
- tlw->newCounterValueHi = event->xclient.data.l[3];
- }
- }
- return true;
- }
- return false;
-}
-
-#if defined(Q_C_CALLBACKS)
-}
-#endif
-#endif // QT_NO_XSYNC
-
-static void qt_x11_create_intern_atoms()
-{
- const char *names[QX11Data::NAtoms];
- const char *ptr = x11_atomnames;
-
- int i = 0;
- while (*ptr) {
- names[i++] = ptr;
- while (*ptr)
- ++ptr;
- ++ptr;
- }
-
- Q_ASSERT(i == QX11Data::NPredefinedAtoms);
-
- QByteArray settings_atom_name("_QT_SETTINGS_TIMESTAMP_");
- settings_atom_name += XDisplayName(X11->displayName);
- names[i++] = settings_atom_name;
-
- Q_ASSERT(i == QX11Data::NAtoms);
-#if defined(XlibSpecificationRelease) && (XlibSpecificationRelease >= 6)
- XInternAtoms(X11->display, (char **)names, i, False, X11->atoms);
-#else
- for (i = 0; i < QX11Data::NAtoms; ++i)
- X11->atoms[i] = XInternAtom(X11->display, (char *)names[i], False);
-#endif
-}
-
-Q_GUI_EXPORT void qt_x11_apply_settings_in_all_apps()
-{
- QByteArray stamp;
- QDataStream s(&stamp, QIODevice::WriteOnly);
- s << QDateTime::currentDateTime();
-
- XChangeProperty(QX11Info::display(), QX11Info::appRootWindow(0),
- ATOM(_QT_SETTINGS_TIMESTAMP), ATOM(_QT_SETTINGS_TIMESTAMP), 8,
- PropModeReplace, (unsigned char *)stamp.data(), stamp.size());
-}
-
-/*! \internal
- apply the settings to the application
-*/
-bool QApplicationPrivate::x11_apply_settings()
-{
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
-
- settings.beginGroup(QLatin1String("Qt"));
-
- /*
- Qt settings. This is now they are written into the datastream.
-
- Palette / * - QPalette
- font - QFont
- libraryPath - QStringList
- style - QString
- doubleClickInterval - int
- keyboardInputInterval - int
- cursorFlashTime - int
- wheelScrollLines - int
- colorSpec - QString
- defaultCodec - QString
- globalStrut/width - int
- globalStrut/height - int
- GUIEffects - QStringList
- Font Substitutions/ * - QStringList
- Font Substitutions/... - QStringList
- */
-
- QStringList strlist;
- int i;
- QPalette pal(Qt::black);
- int groupCount = 0;
- strlist = settings.value(QLatin1String("Palette/active")).toStringList();
- if (!strlist.isEmpty()) {
- ++groupCount;
- for (i = 0; i < qMin(strlist.count(), int(QPalette::NColorRoles)); i++)
- pal.setColor(QPalette::Active, (QPalette::ColorRole) i,
- QColor(strlist[i]));
- }
- strlist = settings.value(QLatin1String("Palette/inactive")).toStringList();
- if (!strlist.isEmpty()) {
- ++groupCount;
- for (i = 0; i < qMin(strlist.count(), int(QPalette::NColorRoles)); i++)
- pal.setColor(QPalette::Inactive, (QPalette::ColorRole) i,
- QColor(strlist[i]));
- }
- strlist = settings.value(QLatin1String("Palette/disabled")).toStringList();
- if (!strlist.isEmpty()) {
- ++groupCount;
- for (i = 0; i < qMin(strlist.count(), int(QPalette::NColorRoles)); i++)
- pal.setColor(QPalette::Disabled, (QPalette::ColorRole) i,
- QColor(strlist[i]));
- }
-
- // ### Fix properly for 4.6
- bool usingGtkSettings = QApplicationPrivate::app_style && QApplicationPrivate::app_style->inherits("QGtkStyle");
- if (!usingGtkSettings) {
- if (groupCount == QPalette::NColorGroups)
- QApplicationPrivate::setSystemPalette(pal);
- }
-
- if (!appFont) {
- // ### Fix properly for 4.6
- if (!usingGtkSettings) {
- QFont font(QApplication::font());
- QString fontDescription;
- // Override Qt font if KDE4 settings can be used
- if (X11->desktopVersion == 4) {
- QSettings kdeSettings(QKde::kdeHome() + QLatin1String("/share/config/kdeglobals"), QSettings::IniFormat);
- fontDescription = kdeSettings.value(QLatin1String("font")).toString();
- if (fontDescription.isEmpty()) {
- // KDE stores fonts without quotes
- fontDescription = kdeSettings.value(QLatin1String("font")).toStringList().join(QLatin1String(","));
- }
- }
- if (fontDescription.isEmpty())
- fontDescription = settings.value(QLatin1String("font")).toString();
- if (!fontDescription .isEmpty()) {
- font.fromString(fontDescription );
- 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(':'));
- if (! pathlist.isEmpty()) {
- QStringList::ConstIterator it = pathlist.constBegin();
- while (it != pathlist.constEnd())
- QApplication::addLibraryPath(*it++);
- }
-
- // read new QStyle
- QString stylename = settings.value(QLatin1String("style")).toString();
-
- if (stylename.isEmpty() && QApplicationPrivate::styleOverride.isNull() && X11->use_xrender) {
- stylename = qt_guiPlatformPlugin()->styleName();
- }
-
- static QString currentStyleName = stylename;
- if (QCoreApplication::startingUp()) {
- if (!stylename.isEmpty() && QApplicationPrivate::styleOverride.isNull())
- QApplicationPrivate::styleOverride = stylename;
- } else {
- if (currentStyleName != stylename) {
- currentStyleName = stylename;
- 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");
-
- 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);
- }
-
- 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")));
-
- if (!X11->has_fontconfig) {
- 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();
- }
-
- qt_use_rtl_extensions =
- settings.value(QLatin1String("useRtlExtensions"), false).toBool();
-
-#ifndef QT_NO_XIM
- if (qt_xim_preferred_style == 0) {
- QString ximInputStyle = settings.value(QLatin1String("XIMInputStyle"),
- QVariant(QLatin1String("on the spot"))).toString().toLower();
- if (ximInputStyle == QLatin1String("on the spot"))
- qt_xim_preferred_style = XIMPreeditCallbacks | XIMStatusNothing;
- else if (ximInputStyle == QLatin1String("over the spot"))
- qt_xim_preferred_style = XIMPreeditPosition | XIMStatusNothing;
- else if (ximInputStyle == QLatin1String("off the spot"))
- qt_xim_preferred_style = XIMPreeditArea | XIMStatusArea;
- else if (ximInputStyle == QLatin1String("root"))
- qt_xim_preferred_style = XIMPreeditNothing | XIMStatusNothing;
- }
-#endif
- QStringList inputMethods = QInputContextFactory::keys();
- if (inputMethods.size() > 2 && inputMethods.contains(QLatin1String("imsw-multi"))) {
- X11->default_im = QLatin1String("imsw-multi");
- } else {
- X11->default_im = settings.value(QLatin1String("DefaultInputMethod"),
- QLatin1String("xim")).toString();
- }
-
- settings.endGroup(); // Qt
-
- return true;
-}
-
-
-/*! \internal
- Resets the QApplication::instance() pointer to zero
-*/
-void QApplicationPrivate::reset_instance_pointer()
-{ QApplication::self = 0; }
-
-
-// read the _QT_INPUT_ENCODING property and apply the settings to
-// the application
-static void qt_set_input_encoding()
-{
- Atom type;
- int format;
- ulong nitems, after = 1;
- unsigned char *data = 0;
-
- int e = XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_QT_INPUT_ENCODING), 0, 1024,
- False, XA_STRING, &type, &format, &nitems,
- &after, &data);
- if (e != Success || !nitems || type == XNone) {
- // Always use the locale codec, since we have no examples of non-local
- // XIMs, and since we cannot get a sensible answer about the encoding
- // from the XIM.
- qt_input_mapper = QTextCodec::codecForLocale();
-
- } else {
- if (!qstricmp((char *)data, "locale"))
- qt_input_mapper = QTextCodec::codecForLocale();
- else
- qt_input_mapper = QTextCodec::codecForName((char *)data);
- // make sure we have an input codec
- if(!qt_input_mapper)
- qt_input_mapper = QTextCodec::codecForName("ISO 8859-1");
- }
- if (qt_input_mapper && qt_input_mapper->mibEnum() == 11) // 8859-8
- qt_input_mapper = QTextCodec::codecForName("ISO 8859-8-I");
- if(data)
- XFree((char *)data);
-}
-
-// set font, foreground and background from x11 resources. The
-// arguments may override the resource settings.
-static void qt_set_x11_resources(const char* font = 0, const char* fg = 0,
- const char* bg = 0, const char* button = 0)
-{
-
- QString resFont, resFG, resBG, resButton, resEF, sysFont, selectBackground, selectForeground;
-
- QApplication::setEffectEnabled(Qt::UI_General, false);
- QApplication::setEffectEnabled(Qt::UI_AnimateMenu, false);
- QApplication::setEffectEnabled(Qt::UI_FadeMenu, false);
- QApplication::setEffectEnabled(Qt::UI_AnimateCombo, false);
- QApplication::setEffectEnabled(Qt::UI_AnimateTooltip, false);
- QApplication::setEffectEnabled(Qt::UI_FadeTooltip, false);
- QApplication::setEffectEnabled(Qt::UI_AnimateToolBox, false);
-
- bool paletteAlreadySet = false;
- if (QApplication::desktopSettingsAware()) {
- // first, read from settings
- QApplicationPrivate::x11_apply_settings();
- // the call to QApplication::style() below creates the system
- // palette, which breaks the logic after the RESOURCE_MANAGER
- // loop... so I have to save this value to be able to use it later
- paletteAlreadySet = (QApplicationPrivate::sys_pal != 0);
-
- // second, parse the RESOURCE_MANAGER property
- int format;
- ulong nitems, after = 1;
- QString res;
- long offset = 0;
- Atom type = XNone;
-
- while (after > 0) {
- uchar *data = 0;
- if (XGetWindowProperty(X11->display, QX11Info::appRootWindow(0),
- ATOM(RESOURCE_MANAGER),
- offset, 8192, False, AnyPropertyType,
- &type, &format, &nitems, &after,
- &data) != Success) {
- res = QString();
- break;
- }
- if (type == XA_STRING)
- res += QString::fromLatin1((char*)data);
- else
- res += QString::fromLocal8Bit((char*)data);
- offset += 2048; // offset is in 32bit quantities... 8192/4 == 2048
- if (data)
- XFree((char *)data);
- }
-
- QString key, value;
- int l = 0, r;
- QString apn = QString::fromLocal8Bit(appName);
- QString apc = QString::fromLocal8Bit(appClass);
- int apnl = apn.length();
- int apcl = apc.length();
- int resl = res.length();
-
- while (l < resl) {
- r = res.indexOf(QLatin1Char('\n'), l);
- if (r < 0)
- r = resl;
- while (res.at(l).isSpace())
- l++;
- bool mine = false;
- QChar sc = res.at(l + 1);
- if (res.at(l) == QLatin1Char('*') &&
- (sc == QLatin1Char('f') || sc == QLatin1Char('b') || sc == QLatin1Char('g') ||
- sc == QLatin1Char('F') || sc == QLatin1Char('B') || sc == QLatin1Char('G') ||
- sc == QLatin1Char('s') || sc == QLatin1Char('S')
- // capital T only, since we're looking for "Text.selectSomething"
- || sc == QLatin1Char('T'))) {
- // OPTIMIZED, since we only want "*[fbgsT].."
- QString item = res.mid(l, r - l).simplified();
- int i = item.indexOf(QLatin1Char(':'));
- key = item.left(i).trimmed().mid(1).toLower();
- value = item.right(item.length() - i - 1).trimmed();
- mine = true;
- } else if ((apnl && res.at(l) == apn.at(0)) || (appClass && apcl && res.at(l) == apc.at(0))) {
- if (res.mid(l,apnl) == apn && (res.at(l+apnl) == QLatin1Char('.')
- || res.at(l+apnl) == QLatin1Char('*'))) {
- QString item = res.mid(l, r - l).simplified();
- int i = item.indexOf(QLatin1Char(':'));
- key = item.left(i).trimmed().mid(apnl+1).toLower();
- value = item.right(item.length() - i - 1).trimmed();
- mine = true;
- } else if (res.mid(l,apcl) == apc && (res.at(l+apcl) == QLatin1Char('.')
- || res.at(l+apcl) == QLatin1Char('*'))) {
- QString item = res.mid(l, r - l).simplified();
- int i = item.indexOf(QLatin1Char(':'));
- key = item.left(i).trimmed().mid(apcl+1).toLower();
- value = item.right(item.length() - i - 1).trimmed();
- mine = true;
- }
- }
-
- if (mine) {
- if (!font && key == QLatin1String("systemfont"))
- sysFont = value.left(value.lastIndexOf(QLatin1Char(':')));
- if (!font && key == QLatin1String("font"))
- resFont = value;
- else if (!fg && !paletteAlreadySet) {
- if (key == QLatin1String("foreground"))
- resFG = value;
- else if (!bg && key == QLatin1String("background"))
- resBG = value;
- else if (!bg && !button && key == QLatin1String("button.background"))
- resButton = value;
- else if (key == QLatin1String("text.selectbackground")) {
- selectBackground = value;
- } else if (key == QLatin1String("text.selectforeground")) {
- selectForeground = value;
- }
- } else if (key == QLatin1String("guieffects"))
- resEF = value;
- // NOTE: if you add more, change the [fbg] stuff above
- }
-
- l = r + 1;
- }
- }
- if (!sysFont.isEmpty())
- resFont = sysFont;
- if (resFont.isEmpty())
- resFont = QString::fromLocal8Bit(font);
- if (resFG.isEmpty())
- resFG = QString::fromLocal8Bit(fg);
- if (resBG.isEmpty())
- resBG = QString::fromLocal8Bit(bg);
- if (resButton.isEmpty())
- resButton = QString::fromLocal8Bit(button);
- if (!resFont.isEmpty()
- && !X11->has_fontconfig
- && !QApplicationPrivate::sys_font) {
- // set application font
- QFont fnt;
- fnt.setRawName(resFont);
-
- // the font we get may actually be an alias for another font,
- // so we reset the application font to the real font info.
- if (! fnt.exactMatch()) {
- QFontInfo fontinfo(fnt);
- fnt.setFamily(fontinfo.family());
- fnt.setRawMode(fontinfo.rawMode());
-
- if (! fnt.rawMode()) {
- fnt.setItalic(fontinfo.italic());
- fnt.setWeight(fontinfo.weight());
- fnt.setUnderline(fontinfo.underline());
- fnt.setStrikeOut(fontinfo.strikeOut());
- fnt.setStyleHint(fontinfo.styleHint());
-
- if (fnt.pointSize() <= 0 && fnt.pixelSize() <= 0) {
- // size is all wrong... fix it
- qreal pointSize = fontinfo.pixelSize() * 72. / (float) QX11Info::appDpiY();
- if (pointSize <= 0)
- pointSize = 12;
- fnt.setPointSize(qRound(pointSize));
- }
- }
- }
-
- QApplicationPrivate::setSystemFont(fnt);
- }
- // QGtkStyle sets it's own system palette
- bool gtkStyle = QApplicationPrivate::app_style && QApplicationPrivate::app_style->inherits("QGtkStyle");
- bool kdeColors = (QApplication::desktopSettingsAware() && X11->desktopEnvironment == DE_KDE);
- if (!gtkStyle && (kdeColors || (button || !resBG.isEmpty() || !resFG.isEmpty()))) {// set app colors
- bool allowX11ColorNames = QColor::allowX11ColorNames();
- QColor::setAllowX11ColorNames(true);
-
- (void) QApplication::style(); // trigger creation of application style and system palettes
- QColor btn;
- QColor bg;
- QColor fg;
- QColor bfg;
- QColor wfg;
- if (!resBG.isEmpty())
- bg = QColor(resBG);
- if (!bg.isValid())
- bg = QApplicationPrivate::sys_pal->color(QPalette::Active, QPalette::Window);
-
- if (!resFG.isEmpty())
- fg = QColor(resFG);
- if (!fg.isValid())
- fg = QApplicationPrivate::sys_pal->color(QPalette::Active, QPalette::WindowText);
-
- if (!resButton.isEmpty())
- btn = QColor(resButton);
- else if (!resBG.isEmpty())
- btn = bg;
- if (!btn.isValid())
- btn = QApplicationPrivate::sys_pal->color(QPalette::Active, 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(125), btn.darker(130), btn.darker(120), wfg.isValid() ? wfg : fg, Qt::white, base, bg);
- 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(130), btn.darker(150), disabled, Qt::white, Qt::white, bg);
-
- QColor highlight, highlightText;
- if (!selectBackground.isEmpty() && !selectForeground.isEmpty()) {
- highlight = QColor(selectBackground);
- highlightText = QColor(selectForeground);
- }
-
- if (highlight.isValid() && highlightText.isValid()) {
- pal.setColor(QPalette::Highlight, highlight);
- pal.setColor(QPalette::HighlightedText, highlightText);
-
- // calculate disabled colors by removing saturation
- highlight.setHsv(highlight.hue(), 0, highlight.value(), highlight.alpha());
- highlightText.setHsv(highlightText.hue(), 0, highlightText.value(), highlightText.alpha());
- pal.setColor(QPalette::Disabled, QPalette::Highlight, highlight);
- pal.setColor(QPalette::Disabled, QPalette::HighlightedText, highlightText);
- } else if (bright_mode) {
- pal.setColor(QPalette::HighlightedText, base);
- pal.setColor(QPalette::Highlight, Qt::white);
- pal.setColor(QPalette::Disabled, QPalette::HighlightedText, base);
- pal.setColor(QPalette::Disabled, QPalette::Highlight, Qt::white);
- } else {
- pal.setColor(QPalette::HighlightedText, Qt::white);
- pal.setColor(QPalette::Highlight, Qt::darkBlue);
- pal.setColor(QPalette::Disabled, QPalette::HighlightedText, Qt::white);
- pal.setColor(QPalette::Disabled, QPalette::Highlight, Qt::darkBlue);
- }
-
- pal = qt_guiPlatformPlugin()->palette().resolve(pal);
- QApplicationPrivate::setSystemPalette(pal);
- QColor::setAllowX11ColorNames(allowX11ColorNames);
- }
-
- if (!resEF.isEmpty()) {
- QStringList effects = resEF.split(QLatin1Char(' '));
- 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")));
- }
-
- QIconLoader::instance()->updateSystemTheme();
-}
-
-
-// update the supported array
-static void qt_get_net_supported()
-{
- Atom type;
- int format;
- long offset = 0;
- unsigned long nitems, after;
- unsigned char *data = 0;
-
- int e = XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_NET_SUPPORTED), 0, 0,
- False, XA_ATOM, &type, &format, &nitems, &after, &data);
- if (data)
- XFree(data);
-
- if (X11->net_supported_list)
- delete [] X11->net_supported_list;
- X11->net_supported_list = 0;
-
- if (e == Success && type == XA_ATOM && format == 32) {
- QBuffer ts;
- ts.open(QIODevice::WriteOnly);
-
- while (after > 0) {
- XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_NET_SUPPORTED), offset, 1024,
- False, XA_ATOM, &type, &format, &nitems, &after, &data);
-
- if (type == XA_ATOM && format == 32) {
- ts.write(reinterpret_cast<char *>(data), nitems * sizeof(long));
- offset += nitems;
- } else
- after = 0;
- if (data)
- XFree(data);
- }
-
- // compute nitems
- QByteArray buffer(ts.buffer());
- nitems = buffer.size() / sizeof(Atom);
- X11->net_supported_list = new Atom[nitems + 1];
- Atom *a = (Atom *) buffer.data();
- uint i;
- for (i = 0; i < nitems; i++)
- X11->net_supported_list[i] = a[i];
- X11->net_supported_list[nitems] = 0;
- }
-}
-
-
-bool QX11Data::isSupportedByWM(Atom atom)
-{
- if (!X11->net_supported_list)
- return false;
-
- bool supported = false;
- int i = 0;
- while (X11->net_supported_list[i] != 0) {
- if (X11->net_supported_list[i++] == atom) {
- supported = true;
- break;
- }
- }
-
- return supported;
-}
-
-
-// update the virtual roots array
-static void qt_get_net_virtual_roots()
-{
- if (X11->net_virtual_root_list)
- delete [] X11->net_virtual_root_list;
- X11->net_virtual_root_list = 0;
-
- if (!X11->isSupportedByWM(ATOM(_NET_VIRTUAL_ROOTS)))
- return;
-
- Atom type;
- int format;
- long offset = 0;
- unsigned long nitems, after;
- unsigned char *data;
-
- int e = XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_NET_VIRTUAL_ROOTS), 0, 0,
- False, XA_ATOM, &type, &format, &nitems, &after, &data);
- if (data)
- XFree(data);
-
- if (e == Success && type == XA_ATOM && format == 32) {
- QBuffer ts;
- ts.open(QIODevice::WriteOnly);
-
- while (after > 0) {
- XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_NET_VIRTUAL_ROOTS), offset, 1024,
- False, XA_ATOM, &type, &format, &nitems, &after, &data);
-
- if (type == XA_ATOM && format == 32) {
- ts.write(reinterpret_cast<char *>(data), nitems * 4);
- offset += nitems;
- } else
- after = 0;
- if (data)
- XFree(data);
- }
-
- // compute nitems
- QByteArray buffer(ts.buffer());
- nitems = buffer.size() / sizeof(Window);
- X11->net_virtual_root_list = new Window[nitems + 1];
- Window *a = (Window *) buffer.data();
- uint i;
- for (i = 0; i < nitems; i++)
- X11->net_virtual_root_list[i] = a[i];
- X11->net_virtual_root_list[nitems] = 0;
- }
-}
-
-void qt_net_remove_user_time(QWidget *tlw)
-{
- Q_ASSERT(tlw);
- QTLWExtra *extra = tlw->d_func()->maybeTopData();
- if (extra && extra->userTimeWindow) {
- Q_ASSERT(tlw->internalWinId());
- XDeleteProperty(X11->display, tlw->internalWinId(), ATOM(_NET_WM_USER_TIME_WINDOW));
- XDestroyWindow(X11->display, extra->userTimeWindow);
- extra->userTimeWindow = 0;
- }
-}
-
-void qt_net_update_user_time(QWidget *tlw, unsigned long timestamp)
-{
- Q_ASSERT(tlw);
- Q_ASSERT(tlw->isWindow());
- Q_ASSERT(tlw->testAttribute(Qt::WA_WState_Created));
- QTLWExtra *extra = tlw->d_func()->topData();
- WId wid = tlw->internalWinId();
- const bool isSupportedByWM = X11->isSupportedByWM(ATOM(_NET_WM_USER_TIME_WINDOW));
- if (extra->userTimeWindow || isSupportedByWM) {
- if (!extra->userTimeWindow) {
- extra->userTimeWindow = XCreateSimpleWindow(X11->display,
- tlw->internalWinId(),
- -1, -1, 1, 1, 0, 0, 0);
- wid = extra->userTimeWindow;
- XChangeProperty(X11->display, tlw->internalWinId(), ATOM(_NET_WM_USER_TIME_WINDOW),
- XA_WINDOW, 32, PropModeReplace,
- (unsigned char *)&wid, 1);
- XDeleteProperty(X11->display, tlw->internalWinId(), ATOM(_NET_WM_USER_TIME));
- } else if (!isSupportedByWM) {
- // WM no longer supports it, then we should remove the
- // _NET_WM_USER_TIME_WINDOW atom.
- qt_net_remove_user_time(tlw);
- } else {
- wid = extra->userTimeWindow;
- }
- }
- XChangeProperty(X11->display, wid, ATOM(_NET_WM_USER_TIME),
- XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &timestamp, 1);
-}
-
-static void qt_check_focus_model()
-{
- Window fw = XNone;
- int unused;
- XGetInputFocus(X11->display, &fw, &unused);
- if (fw == PointerRoot)
- X11->focus_model = QX11Data::FM_PointerRoot;
- else
- X11->focus_model = QX11Data::FM_Other;
-}
-
-#ifndef QT_NO_TABLET
-
-#if !defined (Q_OS_IRIX)
-// from include/Xwacom.h
-# define XWACOM_PARAM_TOOLID 322
-# define XWACOM_PARAM_TOOLSERIAL 323
-
-typedef WACOMCONFIG * (*PtrWacomConfigInit) (Display*, WACOMERRORFUNC);
-typedef WACOMDEVICE * (*PtrWacomConfigOpenDevice) (WACOMCONFIG*, const char*);
-typedef int *(*PtrWacomConfigGetRawParam) (WACOMDEVICE*, int, int*, int, unsigned*);
-typedef int (*PtrWacomConfigCloseDevice) (WACOMDEVICE *);
-typedef void (*PtrWacomConfigTerm) (WACOMCONFIG *);
-
-static PtrWacomConfigInit ptrWacomConfigInit = 0;
-static PtrWacomConfigOpenDevice ptrWacomConfigOpenDevice = 0;
-static PtrWacomConfigGetRawParam ptrWacomConfigGetRawParam = 0;
-static PtrWacomConfigCloseDevice ptrWacomConfigCloseDevice = 0;
-static PtrWacomConfigTerm ptrWacomConfigTerm = 0;
-Q_GLOBAL_STATIC(QByteArray, wacomDeviceName)
-#endif
-
-#endif
-
-/*****************************************************************************
- qt_init() - initializes Qt for X11
- *****************************************************************************/
-
-#if !defined(QT_NO_FONTCONFIG)
-static void getXDefault(const char *group, const char *key, int *val)
-{
- char *str = XGetDefault(X11->display, group, key);
- if (str) {
- char *end = 0;
- int v = strtol(str, &end, 0);
- if (str != end)
- *val = v;
- // otherwise use fontconfig to convert the string to integer
- else
- FcNameConstant((FcChar8 *) str, val);
- }
-}
-
-static void getXDefault(const char *group, const char *key, double *val)
-{
- char *str = XGetDefault(X11->display, group, key);
- if (str) {
- bool ok;
- double v = QByteArray(str).toDouble(&ok);
- if (ok)
- *val = v;
- }
-}
-
-static void getXDefault(const char *group, const char *key, bool *val)
-{
- char *str = XGetDefault(X11->display, group, key);
- if (str) {
- char c = str[0];
- if (isupper((int)c))
- c = tolower(c);
- if (c == 't' || c == 'y' || c == '1')
- *val = true;
- else if (c == 'f' || c == 'n' || c == '0')
- *val = false;
- if (c == 'o') {
- c = str[1];
- if (isupper((int)c))
- c = tolower(c);
- if (c == 'n')
- *val = true;
- if (c == 'f')
- *val = false;
- }
- }
-}
-#endif
-
-// ### This should be static but it isn't because of the friend declaration
-// ### in qpaintdevice.h which then should have a static too but can't have
-// ### it because "storage class specifiers invalid in friend function
-// ### declarations" :-) Ideas anyone?
-void qt_init(QApplicationPrivate *priv, int,
- Display *display, Qt::HANDLE visual, Qt::HANDLE colormap)
-{
- X11 = new QX11Data;
- X11->display = display;
- X11->displayName = 0;
- X11->foreignDisplay = (display != 0);
- X11->focus_model = -1;
-
- // RANDR
- X11->use_xrandr = false;
- X11->xrandr_major = 0;
- X11->xrandr_eventbase = 0;
- X11->xrandr_errorbase = 0;
-
- // RENDER
- X11->use_xrender = false;
- X11->xrender_major = 0;
- X11->xrender_version = 0;
-
- // XFIXES
- X11->use_xfixes = false;
- X11->xfixes_major = 0;
- X11->xfixes_eventbase = 0;
- X11->xfixes_errorbase = 0;
-
- // XInputExtension
- X11->use_xinput = false;
- X11->xinput_major = 0;
- X11->xinput_eventbase = 0;
- X11->xinput_errorbase = 0;
-
- X11->use_xkb = false;
- X11->xkb_major = 0;
- X11->xkb_eventbase = 0;
- X11->xkb_errorbase = 0;
-
- // MIT-SHM
- X11->use_mitshm = false;
- X11->use_mitshm_pixmaps = false;
- X11->mitshm_major = 0;
-
- X11->sip_serial = 0;
- X11->net_supported_list = 0;
- X11->net_virtual_root_list = 0;
- X11->wm_client_leader = 0;
- X11->screens = 0;
- X11->argbVisuals = 0;
- X11->argbColormaps = 0;
- X11->screenCount = 0;
- X11->time = CurrentTime;
- X11->userTime = CurrentTime;
- X11->ignore_badwindow = false;
- X11->seen_badwindow = false;
-
- X11->motifdnd_active = false;
-
- X11->default_im = QLatin1String("imsw-multi");
- priv->inputContext = 0;
-
- // colormap control
- X11->visual_class = -1;
- X11->visual_id = -1;
- X11->color_count = 0;
- X11->custom_cmap = false;
-
- // outside visual/colormap
- X11->visual = reinterpret_cast<Visual *>(visual);
- X11->colormap = colormap;
-
- // Fontconfig
- X11->has_fontconfig = false;
-#if !defined(QT_NO_FONTCONFIG)
- if (qgetenv("QT_X11_NO_FONTCONFIG").isNull())
- X11->has_fontconfig = FcInit();
- X11->fc_antialias = true;
-#endif
-
-#ifndef QT_NO_XRENDER
- memset(X11->solid_fills, 0, sizeof(X11->solid_fills));
- for (int i = 0; i < X11->solid_fill_count; ++i)
- X11->solid_fills[i].screen = -1;
- memset(X11->pattern_fills, 0, sizeof(X11->pattern_fills));
- for (int i = 0; i < X11->pattern_fill_count; ++i)
- X11->pattern_fills[i].screen = -1;
-#endif
-
- X11->startupId = 0;
-
- int argc = priv->argc;
- char **argv = priv->argv;
-
- if (X11->display) {
- // Qt part of other application
-
- // Set application name and class
- appName = qstrdup("Qt-subapplication");
- char *app_class = 0;
- if (argv) {
- const char* p = strrchr(argv[0], '/');
- app_class = qstrdup(p ? p + 1 : argv[0]);
- if (app_class[0])
- app_class[0] = toupper(app_class[0]);
- }
- appClass = app_class;
- } else {
- // Qt controls everything (default)
-
- if (QApplication::testAttribute(Qt::AA_X11InitThreads))
- XInitThreads();
-
- // Set application name and class
- char *app_class = 0;
- if (argv && argv[0]) {
- const char *p = strrchr(argv[0], '/');
- appName = p ? p + 1 : argv[0];
- app_class = qstrdup(appName);
- if (app_class[0])
- app_class[0] = toupper(app_class[0]);
- }
- appClass = app_class;
- }
-
- // Install default error handlers
- original_x_errhandler = XSetErrorHandler(qt_x_errhandler);
- original_xio_errhandler = XSetIOErrorHandler(qt_xio_errhandler);
-
- // 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 == "-display") {
- if (++i < argc && !X11->display)
- X11->displayName = argv[i];
- } else if (arg == "-fn" || arg == "-font") {
- if (++i < argc)
- appFont = argv[i];
- } else if (arg == "-bg" || arg == "-background") {
- if (++i < argc)
- appBGCol = argv[i];
- } else if (arg == "-btn" || arg == "-button") {
- if (++i < argc)
- appBTNCol = argv[i];
- } else if (arg == "-fg" || arg == "-foreground") {
- if (++i < argc)
- appFGCol = argv[i];
- } else if (arg == "-name") {
- if (++i < argc)
- appName = argv[i];
- } else if (arg == "-title") {
- if (++i < argc)
- mwTitle = argv[i];
- } else if (arg == "-geometry") {
- if (++i < argc)
- mwGeometry = argv[i];
- } else if (arg == "-im") {
- if (++i < argc)
- qt_ximServer = argv[i];
- } else if (arg == "-ncols") { // xv and netscape use this name
- if (++i < argc)
- X11->color_count = qMax(0,atoi(argv[i]));
- } else if (arg == "-visual") { // xv and netscape use this name
- if (++i < argc && !X11->visual) {
- QString s = QString::fromLocal8Bit(argv[i]).toLower();
- if (s == QLatin1String("staticgray"))
- X11->visual_class = StaticGray;
- else if (s == QLatin1String("grayscale"))
- X11->visual_class = XGrayScale;
- else if (s == QLatin1String("staticcolor"))
- X11->visual_class = StaticColor;
- else if (s == QLatin1String("pseudocolor"))
- X11->visual_class = PseudoColor;
- else if (s == QLatin1String("truecolor"))
- X11->visual_class = TrueColor;
- else if (s == QLatin1String("directcolor"))
- X11->visual_class = DirectColor;
- else
- X11->visual_id = static_cast<int>(strtol(argv[i], 0, 0));
- }
-#ifndef QT_NO_XIM
- } else if (arg == "-inputstyle") {
- if (++i < argc) {
- QString s = QString::fromLocal8Bit(argv[i]).toLower();
- if (s == QLatin1String("onthespot"))
- qt_xim_preferred_style = XIMPreeditCallbacks |
- XIMStatusNothing;
- else if (s == QLatin1String("overthespot"))
- qt_xim_preferred_style = XIMPreeditPosition |
- XIMStatusNothing;
- else if (s == QLatin1String("offthespot"))
- qt_xim_preferred_style = XIMPreeditArea |
- XIMStatusArea;
- else if (s == QLatin1String("root"))
- qt_xim_preferred_style = XIMPreeditNothing |
- XIMStatusNothing;
- }
-#endif
- } else if (arg == "-cmap") { // xv uses this name
- if (!X11->colormap)
- X11->custom_cmap = true;
- }
- else if (arg == "-sync")
- appSync = !appSync;
-#if defined(QT_DEBUG)
- else if (arg == "-nograb")
- appNoGrab = !appNoGrab;
- else if (arg == "-dograb")
- appDoGrab = !appDoGrab;
-#endif
- else
- argv[j++] = argv[i];
- }
-
- priv->argc = j;
-
-#if defined(QT_DEBUG) && defined(Q_OS_LINUX)
- if (!appNoGrab && !appDoGrab) {
- QString s;
- s.sprintf("/proc/%d/cmdline", getppid());
- QFile f(s);
- if (f.open(QIODevice::ReadOnly)) {
- s.clear();
- char c;
- while (f.getChar(&c) && c) {
- if (c == '/')
- s.clear();
- else
- s += QLatin1Char(c);
- }
- if (s == QLatin1String("gdb")) {
- appNoGrab = true;
- qDebug("Qt: gdb: -nograb added to command-line options.\n"
- "\t Use the -dograb option to enforce grabbing.");
- }
- f.close();
- }
- }
-#endif
-
- // Connect to X server
- if (qt_is_gui_used && !X11->display) {
- if ((X11->display = XOpenDisplay(X11->displayName)) == 0) {
- qWarning("%s: cannot connect to X server %s", appName,
- XDisplayName(X11->displayName));
- QApplicationPrivate::reset_instance_pointer();
- exit(1);
- }
-
- if (appSync) // if "-sync" argument
- XSynchronize(X11->display, true);
- }
-
- // Common code, regardless of whether display is foreign.
-
- // Get X parameters
-
- if (qt_is_gui_used) {
- X11->defaultScreen = DefaultScreen(X11->display);
- X11->screenCount = ScreenCount(X11->display);
-
- X11->screens = new QX11InfoData[X11->screenCount];
- X11->argbVisuals = new Visual *[X11->screenCount];
- X11->argbColormaps = new Colormap[X11->screenCount];
-
- for (int s = 0; s < X11->screenCount; s++) {
- QX11InfoData *screen = X11->screens + s;
- screen->ref = 1; // ensures it doesn't get deleted
- screen->screen = s;
-
- int widthMM = DisplayWidthMM(X11->display, s);
- if (widthMM != 0) {
- screen->dpiX = (DisplayWidth(X11->display, s) * 254 + widthMM * 5) / (widthMM * 10);
- } else {
- screen->dpiX = 72;
- }
-
- int heightMM = DisplayHeightMM(X11->display, s);
- if (heightMM != 0) {
- screen->dpiY = (DisplayHeight(X11->display, s) * 254 + heightMM * 5) / (heightMM * 10);
- } else {
- screen->dpiY = 72;
- }
-
- X11->argbVisuals[s] = 0;
- X11->argbColormaps[s] = 0;
- }
-
-
-#ifndef QT_NO_XRENDER
- int xrender_eventbase, xrender_errorbase;
- // See if XRender is supported on the connected display
- if (XQueryExtension(X11->display, "RENDER", &X11->xrender_major,
- &xrender_eventbase, &xrender_errorbase)
- && XRenderQueryExtension(X11->display, &xrender_eventbase,
- &xrender_errorbase)) {
- // Check the version as well - we need v0.4 or higher
- int major = 0;
- int minor = 0;
- XRenderQueryVersion(X11->display, &major, &minor);
- if (qgetenv("QT_X11_NO_XRENDER").isNull()) {
- X11->use_xrender = (major >= 0 && minor >= 5);
- X11->xrender_version = major*100+minor;
- // workaround for broken XServer on Ubuntu Breezy (6.8 compiled with 7.0
- // protocol headers)
- if (X11->xrender_version == 10
- && VendorRelease(X11->display) < 60900000
- && QByteArray(ServerVendor(X11->display)).contains("X.Org"))
- X11->xrender_version = 9;
- }
- }
-#endif // QT_NO_XRENDER
-
-#ifndef QT_NO_MITSHM
- int mitshm_minor;
- int mitshm_major;
- int mitshm_eventbase;
- int mitshm_errorbase;
- int mitshm_pixmaps;
- if (XQueryExtension(X11->display, "MIT-SHM", &X11->mitshm_major,
- &mitshm_eventbase, &mitshm_errorbase)
- && XShmQueryVersion(X11->display, &mitshm_major, &mitshm_minor,
- &mitshm_pixmaps))
- {
- QString displayName = QLatin1String(XDisplayName(NULL));
-
- // MITSHM only works for local displays, so do a quick check here
- // to determine whether the display is local or not (not 100 % accurate).
- // BGR server layouts are not supported either, since it requires the raster
- // engine to work on a QImage with BGR layout.
- bool local = displayName.isEmpty() || displayName.lastIndexOf(QLatin1Char(':')) == 0;
- if (local && (qgetenv("QT_X11_NO_MITSHM").toInt() == 0)) {
- Visual *defaultVisual = DefaultVisual(X11->display, DefaultScreen(X11->display));
- X11->use_mitshm = ((defaultVisual->red_mask == 0xff0000
- || defaultVisual->red_mask == 0xf800)
- && (defaultVisual->green_mask == 0xff00
- || defaultVisual->green_mask == 0x7e0)
- && (defaultVisual->blue_mask == 0xff
- || defaultVisual->blue_mask == 0x1f));
- X11->use_mitshm_pixmaps = X11->use_mitshm && mitshm_pixmaps;
- }
- }
-#endif // QT_NO_MITSHM
-
- // initialize the graphics system - order is imporant here - it must be done before
- // the QColormap::initialize() call
- QApplicationPrivate::graphics_system = QGraphicsSystemFactory::create(QApplicationPrivate::graphics_system_name);
- QColormap::initialize();
-
- // Support protocols
- X11->xdndSetup();
-
- // Finally create all atoms
- qt_x11_create_intern_atoms();
-
- // initialize NET lists
- qt_get_net_supported();
- qt_get_net_virtual_roots();
-
-#ifndef QT_NO_XRANDR
- // See if XRandR is supported on the connected display
- if (XQueryExtension(X11->display, "RANDR", &X11->xrandr_major,
- &X11->xrandr_eventbase, &X11->xrandr_errorbase)) {
-
-# ifdef QT_RUNTIME_XRANDR
- X11->ptrXRRSelectInput = 0;
- X11->ptrXRRUpdateConfiguration = 0;
- X11->ptrXRRRootToScreen = 0;
- X11->ptrXRRQueryExtension = 0;
- QLibrary xrandrLib(QLatin1String("Xrandr"), 2);
- if (!xrandrLib.load()) { // try without the version number
- xrandrLib.setFileName(QLatin1String("Xrandr"));
- xrandrLib.load();
- }
- if (xrandrLib.isLoaded()) {
- X11->ptrXRRSelectInput =
- (PtrXRRSelectInput) xrandrLib.resolve("XRRSelectInput");
- X11->ptrXRRUpdateConfiguration =
- (PtrXRRUpdateConfiguration) xrandrLib.resolve("XRRUpdateConfiguration");
- X11->ptrXRRRootToScreen =
- (PtrXRRRootToScreen) xrandrLib.resolve("XRRRootToScreen");
- X11->ptrXRRQueryExtension =
- (PtrXRRQueryExtension) xrandrLib.resolve("XRRQueryExtension");
- X11->ptrXRRSizes =
- (PtrXRRSizes) xrandrLib.resolve("XRRSizes");
- }
-# else
- X11->ptrXRRSelectInput = XRRSelectInput;
- X11->ptrXRRUpdateConfiguration = XRRUpdateConfiguration;
- X11->ptrXRRRootToScreen = XRRRootToScreen;
- X11->ptrXRRQueryExtension = XRRQueryExtension;
- X11->ptrXRRSizes = XRRSizes;
-# endif
-
- if (X11->ptrXRRQueryExtension
- && X11->ptrXRRQueryExtension(X11->display, &X11->xrandr_eventbase, &X11->xrandr_errorbase)) {
- // XRandR is supported
- X11->use_xrandr = true;
- }
- }
-#endif // QT_NO_XRANDR
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- // XRender is supported, let's see if we have a PictFormat for the
- // default visual
- XRenderPictFormat *format =
- XRenderFindVisualFormat(X11->display,
- (Visual *) QX11Info::appVisual(X11->defaultScreen));
-
- if (!format) {
- X11->use_xrender = false;
- }
- }
-#endif // QT_NO_XRENDER
-
-#ifndef QT_NO_XFIXES
- // See if Xfixes is supported on the connected display
- if (XQueryExtension(X11->display, "XFIXES", &X11->xfixes_major,
- &X11->xfixes_eventbase, &X11->xfixes_errorbase)) {
- X11->ptrXFixesQueryExtension = XFIXES_LOAD_V1(XFixesQueryExtension);
- X11->ptrXFixesQueryVersion = XFIXES_LOAD_V1(XFixesQueryVersion);
- X11->ptrXFixesSetCursorName = XFIXES_LOAD_V2(XFixesSetCursorName);
- X11->ptrXFixesSelectSelectionInput = XFIXES_LOAD_V2(XFixesSelectSelectionInput);
-
- if(X11->ptrXFixesQueryExtension && X11->ptrXFixesQueryVersion
- && X11->ptrXFixesQueryExtension(X11->display, &X11->xfixes_eventbase,
- &X11->xfixes_errorbase)) {
- // Xfixes is supported.
- // Note: the XFixes protocol version is negotiated using QueryVersion.
- // We supply the highest version we support, the X server replies with
- // the highest version it supports, but no higher than the version we
- // asked for. The version sent back is the protocol version the X server
- // will use to talk us. If this call is removed, the behavior of the
- // X server when it receives an XFixes request is undefined.
- int major = 3;
- int minor = 0;
- X11->ptrXFixesQueryVersion(X11->display, &major, &minor);
- X11->use_xfixes = (major >= 1);
- X11->xfixes_major = major;
- }
- }
-#endif // QT_NO_XFIXES
-
-#ifndef QT_NO_XCURSOR
-#ifdef QT_RUNTIME_XCURSOR
- X11->ptrXcursorLibraryLoadCursor = 0;
- QLibrary xcursorLib(QLatin1String("Xcursor"), 1);
- bool xcursorFound = xcursorLib.load();
- if (!xcursorFound) { //try without the version number
- xcursorLib.setFileName(QLatin1String("Xcursor"));
- xcursorFound = xcursorLib.load();
- }
- if (xcursorFound) {
- X11->ptrXcursorLibraryLoadCursor =
- (PtrXcursorLibraryLoadCursor) xcursorLib.resolve("XcursorLibraryLoadCursor");
- }
-#else
- X11->ptrXcursorLibraryLoadCursor = XcursorLibraryLoadCursor;
-#endif // QT_RUNTIME_XCURSOR
-#endif // QT_NO_XCURSOR
-
-#ifndef QT_NO_XSYNC
- int xsync_evbase, xsync_errbase;
- int major, minor;
- if (XSyncQueryExtension(X11->display, &xsync_evbase, &xsync_errbase))
- XSyncInitialize(X11->display, &major, &minor);
-#endif // QT_NO_XSYNC
-
-#ifndef QT_NO_XINERAMA
-#ifdef QT_RUNTIME_XINERAMA
- X11->ptrXineramaQueryExtension = 0;
- X11->ptrXineramaIsActive = 0;
- X11->ptrXineramaQueryScreens = 0;
- QLibrary xineramaLib(QLatin1String("Xinerama"), 1);
- bool xineramaFound = xineramaLib.load();
- if (!xineramaFound) { //try without the version number
- xineramaLib.setFileName(QLatin1String("Xinerama"));
- xineramaFound = xineramaLib.load();
- }
- if (xineramaFound) {
- X11->ptrXineramaQueryExtension =
- (PtrXineramaQueryExtension) xineramaLib.resolve("XineramaQueryExtension");
- X11->ptrXineramaIsActive =
- (PtrXineramaIsActive) xineramaLib.resolve("XineramaIsActive");
- X11->ptrXineramaQueryScreens =
- (PtrXineramaQueryScreens) xineramaLib.resolve("XineramaQueryScreens");
- }
-#else
- X11->ptrXineramaQueryScreens = XineramaQueryScreens;
- X11->ptrXineramaIsActive = XineramaIsActive;
- X11->ptrXineramaQueryExtension = XineramaQueryExtension;
-#endif // QT_RUNTIME_XINERAMA
-#endif // QT_NO_XINERAMA
-
-#ifndef QT_NO_XINPUT
- // See if Xinput is supported on the connected display
- X11->ptrXCloseDevice = 0;
- X11->ptrXListInputDevices = 0;
- X11->ptrXOpenDevice = 0;
- X11->ptrXFreeDeviceList = 0;
- X11->ptrXSelectExtensionEvent = 0;
- X11->use_xinput = XQueryExtension(X11->display, "XInputExtension", &X11->xinput_major,
- &X11->xinput_eventbase, &X11->xinput_errorbase);
- if (X11->use_xinput) {
- X11->ptrXCloseDevice = XINPUT_LOAD(XCloseDevice);
- X11->ptrXListInputDevices = XINPUT_LOAD(XListInputDevices);
- X11->ptrXOpenDevice = XINPUT_LOAD(XOpenDevice);
- X11->ptrXFreeDeviceList = XINPUT_LOAD(XFreeDeviceList);
- X11->ptrXSelectExtensionEvent = XINPUT_LOAD(XSelectExtensionEvent);
- }
-#endif // QT_NO_XINPUT
-
-#ifndef QT_NO_XKB
- int xkblibMajor = XkbMajorVersion;
- int xkblibMinor = XkbMinorVersion;
- X11->use_xkb = XkbQueryExtension(X11->display,
- &X11->xkb_major,
- &X11->xkb_eventbase,
- &X11->xkb_errorbase,
- &xkblibMajor,
- &xkblibMinor);
- if (X11->use_xkb) {
- // If XKB is detected, set the GrabsUseXKBState option so input method
- // compositions continue to work (ie. deadkeys)
- unsigned int state = XkbPCF_GrabsUseXKBStateMask;
- (void) XkbSetPerClientControls(X11->display, state, &state);
-
- // select for group change events
- XkbSelectEventDetails(X11->display,
- XkbUseCoreKbd,
- XkbStateNotify,
- XkbAllStateComponentsMask,
- XkbGroupStateMask);
-
- // current group state is queried when creating the keymapper, no need to do it here
- }
-#endif
-
-
-#if !defined(QT_NO_FONTCONFIG)
- int dpi = 0;
- getXDefault("Xft", FC_DPI, &dpi);
- if (dpi) {
- for (int s = 0; s < ScreenCount(X11->display); ++s) {
- QX11Info::setAppDpiX(s, dpi);
- QX11Info::setAppDpiY(s, dpi);
- }
- }
- double fc_scale = 1.;
- getXDefault("Xft", FC_SCALE, &fc_scale);
- X11->fc_scale = fc_scale;
- for (int s = 0; s < ScreenCount(X11->display); ++s) {
- int subpixel = FC_RGBA_UNKNOWN;
-#if !defined(QT_NO_XRENDER) && (RENDER_MAJOR > 0 || RENDER_MINOR >= 6)
- if (X11->use_xrender) {
- int rsp = XRenderQuerySubpixelOrder(X11->display, s);
- switch (rsp) {
- default:
- case SubPixelUnknown:
- subpixel = FC_RGBA_UNKNOWN;
- break;
- case SubPixelHorizontalRGB:
- subpixel = FC_RGBA_RGB;
- break;
- case SubPixelHorizontalBGR:
- subpixel = FC_RGBA_BGR;
- break;
- case SubPixelVerticalRGB:
- subpixel = FC_RGBA_VRGB;
- break;
- case SubPixelVerticalBGR:
- subpixel = FC_RGBA_VBGR;
- break;
- case SubPixelNone:
- subpixel = FC_RGBA_NONE;
- break;
- }
- }
-#endif
-
- char *rgba = XGetDefault(X11->display, "Xft", FC_RGBA);
- if (rgba) {
- char *end = 0;
- int v = strtol(rgba, &end, 0);
- if (rgba != end) {
- subpixel = v;
- } else if (qstrncmp(rgba, "unknown", 7) == 0) {
- subpixel = FC_RGBA_UNKNOWN;
- } else if (qstrncmp(rgba, "rgb", 3) == 0) {
- subpixel = FC_RGBA_RGB;
- } else if (qstrncmp(rgba, "bgr", 3) == 0) {
- subpixel = FC_RGBA_BGR;
- } else if (qstrncmp(rgba, "vrgb", 4) == 0) {
- subpixel = FC_RGBA_VRGB;
- } else if (qstrncmp(rgba, "vbgr", 4) == 0) {
- subpixel = FC_RGBA_VBGR;
- } else if (qstrncmp(rgba, "none", 4) == 0) {
- subpixel = FC_RGBA_NONE;
- }
- }
- X11->screens[s].subpixel = subpixel;
- }
- getXDefault("Xft", FC_ANTIALIAS, &X11->fc_antialias);
-#ifdef FC_HINT_STYLE
- X11->fc_hint_style = -1;
- getXDefault("Xft", FC_HINT_STYLE, &X11->fc_hint_style);
-#endif
-#if 0
- // ###### these are implemented by Xft, not sure we need them
- getXDefault("Xft", FC_AUTOHINT, &X11->fc_autohint);
- getXDefault("Xft", FC_HINTING, &X11->fc_autohint);
- getXDefault("Xft", FC_MINSPACE, &X11->fc_autohint);
-#endif
-#endif // QT_NO_XRENDER
-
- // initialize key mapper
- QKeyMapper::changeKeyboard();
-
- // Misc. initialization
-#if 0 //disabled for now..
- QSegfaultHandler::initialize(priv->argv, priv->argc);
-#endif
- QCursorData::initialize();
- }
- QFont::initialize();
-
- if(qt_is_gui_used) {
- qApp->setObjectName(QString::fromLocal8Bit(appName));
-
- int screen;
- for (screen = 0; screen < X11->screenCount; ++screen) {
- XSelectInput(X11->display, QX11Info::appRootWindow(screen),
- KeymapStateMask | EnterWindowMask | LeaveWindowMask | PropertyChangeMask);
-
-#ifndef QT_NO_XRANDR
- if (X11->use_xrandr)
- X11->ptrXRRSelectInput(X11->display, QX11Info::appRootWindow(screen), True);
-#endif // QT_NO_XRANDR
- }
- }
-
- if (qt_is_gui_used) {
- // Attempt to determine the current running X11 Desktop Enviornment
- // Use dbus if/when we can, but fall back to using windowManagerName() for now
-
-#ifndef QT_NO_XFIXES
- if (X11->ptrXFixesSelectSelectionInput)
- X11->ptrXFixesSelectSelectionInput(X11->display, QX11Info::appRootWindow(), ATOM(_NET_WM_CM_S0),
- XFixesSetSelectionOwnerNotifyMask
- | XFixesSelectionWindowDestroyNotifyMask
- | XFixesSelectionClientCloseNotifyMask);
-#endif // QT_NO_XFIXES
- X11->compositingManagerRunning = XGetSelectionOwner(X11->display,
- ATOM(_NET_WM_CM_S0));
- X11->desktopEnvironment = DE_UNKNOWN;
- X11->desktopVersion = 0;
-
- Atom type;
- int format;
- unsigned long length, after;
- uchar *data = 0;
- int rc;
-
- do {
- if (!qgetenv("KDE_FULL_SESSION").isEmpty()) {
- X11->desktopEnvironment = DE_KDE;
- X11->desktopVersion = qgetenv("KDE_SESSION_VERSION").toInt();
- break;
- }
-
- if (qgetenv("DESKTOP_SESSION") == "gnome") {
- X11->desktopEnvironment = DE_GNOME;
- break;
- }
-
- // GNOME_DESKTOP_SESSION_ID is deprecated for some reason, but still check it
- if (!qgetenv("GNOME_DESKTOP_SESSION_ID").isEmpty()) {
- X11->desktopEnvironment = DE_GNOME;
- break;
- }
-
- rc = XGetWindowProperty(X11->display, QX11Info::appRootWindow(), ATOM(_DT_SAVE_MODE),
- 0, 2, False, XA_STRING, &type, &format, &length,
- &after, &data);
- if (rc == Success && length) {
- if (!strcmp(reinterpret_cast<char *>(data), "xfce4")) {
- // Pretend that xfce4 is gnome, as it uses the same libraries.
- // The detection above is stolen from xdg-open.
- X11->desktopEnvironment = DE_GNOME;
- break;
- }
-
- // We got the property but it wasn't xfce4. Free data before it gets overwritten.
- XFree(data);
- data = 0;
- }
-
- rc = XGetWindowProperty(X11->display, QX11Info::appRootWindow(), ATOM(DTWM_IS_RUNNING),
- 0, 1, False, AnyPropertyType, &type, &format, &length,
- &after, &data);
- if (rc == Success && length) {
- // DTWM is running, meaning most likely CDE is running...
- X11->desktopEnvironment = DE_CDE;
- break;
- }
-
- rc = XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_SGI_DESKS_MANAGER), 0, 1, False, XA_WINDOW,
- &type, &format, &length, &after, &data);
- if (rc == Success && length) {
- X11->desktopEnvironment = DE_4DWM;
- break;
- }
-
- if (XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_NET_SUPPORTING_WM_CHECK),
- 0, 1024, False, XA_WINDOW, &type,
- &format, &length, &after, &data) == Success) {
- if (type == XA_WINDOW && format == 32) {
- Window windowManagerWindow = *((Window*) data);
- XFree(data);
- data = 0;
-
- if (windowManagerWindow != XNone) {
- Atom utf8atom = ATOM(UTF8_STRING);
- if (XGetWindowProperty(QX11Info::display(), windowManagerWindow, ATOM(_NET_WM_NAME),
- 0, 1024, False, utf8atom, &type,
- &format, &length, &after, &data) == Success) {
- if (type == utf8atom && format == 8) {
- if (qstrcmp((const char *)data, "MCompositor") == 0)
- X11->desktopEnvironment = DE_MEEGO_COMPOSITOR;
- }
- }
- }
- }
- }
-
- } while(0);
-
- if (data)
- XFree((char *)data);
-
-#if !defined(QT_NO_STYLE_GTK)
- if (X11->desktopEnvironment == DE_GNOME) {
- static bool menusHaveIcons = QGtkStyle::getGConfBool(QLatin1String("/desktop/gnome/interface/menus_have_icons"), true);
- QApplication::setAttribute(Qt::AA_DontShowIconsInMenus, !menusHaveIcons);
- }
-#endif
- qt_set_input_encoding();
-
- qt_set_x11_resources(appFont, appFGCol, appBGCol, appBTNCol);
-
- // be smart about the size of the default font. most X servers have helvetica
- // 12 point available at 2 resolutions:
- // 75dpi (12 pixels) and 100dpi (17 pixels).
- // At 95 DPI, a 12 point font should be 16 pixels tall - in which case a 17
- // pixel font is a closer match than a 12 pixel font
- int ptsz = (X11->use_xrender
- ? 9
- : (int) (((QX11Info::appDpiY() >= 95 ? 17. : 12.) *
- 72. / (float) QX11Info::appDpiY()) + 0.5));
-
- if (!QApplicationPrivate::sys_font) {
- // no font from settings or RESOURCE_MANAGER, provide a fallback
- QFont f(X11->has_fontconfig ? QLatin1String("Sans Serif") : QLatin1String("Helvetica"),
- ptsz);
- QApplicationPrivate::setSystemFont(f);
- }
-
-#if !defined (QT_NO_TABLET)
- if (X11->use_xinput) {
- int ndev,
- i,
- j;
- bool gotStylus,
- gotEraser;
- XDeviceInfo *devices = 0, *devs;
- XInputClassInfo *ip;
- XAnyClassPtr any;
- XValuatorInfoPtr v;
- XAxisInfoPtr a;
- XDevice *dev = 0;
-
- if (X11->ptrXListInputDevices) {
- devices = X11->ptrXListInputDevices(X11->display, &ndev);
- if (!devices)
- qWarning("QApplication: Failed to get list of tablet devices");
- }
- if (!devices)
- ndev = -1;
- QTabletEvent::TabletDevice deviceType;
- for (devs = devices, i = 0; i < ndev && devs; i++, devs++) {
- dev = 0;
- deviceType = QTabletEvent::NoDevice;
- gotStylus = false;
- gotEraser = false;
-
-#if defined(Q_OS_IRIX)
- QString devName = QString::fromLocal8Bit(devs->name).toLower();
- if (devName == QLatin1String(WACOM_NAME)) {
- deviceType = QTabletEvent::Stylus;
- gotStylus = true;
- }
-#else
- if (devs->type == ATOM(XWacomStylus) || devs->type == ATOM(XTabletStylus)) {
- deviceType = QTabletEvent::Stylus;
- if (wacomDeviceName()->isEmpty())
- wacomDeviceName()->append(devs->name);
- gotStylus = true;
- } else if (devs->type == ATOM(XWacomEraser) || devs->type == ATOM(XTabletEraser)) {
- deviceType = QTabletEvent::XFreeEraser;
- gotEraser = true;
- }
-#endif
- if (deviceType == QTabletEvent::NoDevice)
- continue;
-
- if (gotStylus || gotEraser) {
- if (X11->ptrXOpenDevice)
- dev = X11->ptrXOpenDevice(X11->display, devs->id);
-
- if (!dev)
- continue;
-
- QTabletDeviceData device_data;
- device_data.deviceType = deviceType;
- device_data.eventCount = 0;
- device_data.device = dev;
- device_data.xinput_motion = -1;
- device_data.xinput_key_press = -1;
- device_data.xinput_key_release = -1;
- device_data.xinput_button_press = -1;
- device_data.xinput_button_release = -1;
- device_data.xinput_proximity_in = -1;
- device_data.xinput_proximity_out = -1;
- device_data.widgetToGetPress = 0;
-
- if (dev->num_classes > 0) {
- for (ip = dev->classes, j = 0; j < dev->num_classes;
- ip++, j++) {
- switch (ip->input_class) {
- case KeyClass:
- DeviceKeyPress(dev, device_data.xinput_key_press,
- device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- DeviceKeyRelease(dev, device_data.xinput_key_release,
- device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- break;
- case ButtonClass:
- DeviceButtonPress(dev, device_data.xinput_button_press,
- device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- DeviceButtonRelease(dev, device_data.xinput_button_release,
- device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- break;
- case ValuatorClass:
- // I'm only going to be interested in motion when the
- // stylus is already down anyway!
- DeviceMotionNotify(dev, device_data.xinput_motion,
- device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- ProximityIn(dev, device_data.xinput_proximity_in, device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- ProximityOut(dev, device_data.xinput_proximity_out, device_data.eventList[device_data.eventCount]);
- if (device_data.eventList[device_data.eventCount])
- ++device_data.eventCount;
- default:
- break;
- }
- }
- }
-
- // get the min/max value for pressure!
- any = (XAnyClassPtr) (devs->inputclassinfo);
- for (j = 0; j < devs->num_classes; j++) {
- if (any->c_class == ValuatorClass) {
- v = (XValuatorInfoPtr) any;
- a = (XAxisInfoPtr) ((char *) v +
- sizeof (XValuatorInfo));
-#if defined (Q_OS_IRIX)
- // I'm not exaclty wild about this, but the
- // dimensions of the tablet are more relevant here
- // than the min and max values from the axis
- // (actually it seems to be 2/3 or what is in the
- // axis. So we'll try to parse it from this
- // string. --tws
- char returnString[SGIDeviceRtrnLen];
- int tmp;
- if (XSGIMiscQueryExtension(X11->display, &tmp, &tmp)
- && XSGIDeviceQuery(X11->display, devs->id,
- "dimensions", returnString)) {
- QString str = QLatin1String(returnString);
- int comma = str.indexOf(',');
- device_data.minX = 0;
- device_data.minY = 0;
- device_data.maxX = str.left(comma).toInt();
- device_data.maxY = str.mid(comma + 1).toInt();
- } else {
- device_data.minX = a[WAC_XCOORD_I].min_value;
- device_data.maxX = a[WAC_XCOORD_I].max_value;
- device_data.minY = a[WAC_YCOORD_I].min_value;
- device_data.maxY = a[WAC_YCOORD_I].max_value;
- }
- device_data.minPressure = a[WAC_PRESSURE_I].min_value;
- device_data.maxPressure = a[WAC_PRESSURE_I].max_value;
- device_data.minTanPressure = a[WAC_TAN_PRESSURE_I].min_value;
- device_data.maxTanPressure = a[WAC_TAN_PRESSURE_I].max_value;
- device_data.minZ = a[WAC_ZCOORD_I].min_value;
- device_data.maxZ = a[WAC_ZCOORD_I].max_value;
-#else
- device_data.minX = a[0].min_value;
- device_data.maxX = a[0].max_value;
- device_data.minY = a[1].min_value;
- device_data.maxY = a[1].max_value;
- device_data.minPressure = a[2].min_value;
- device_data.maxPressure = a[2].max_value;
- device_data.minTanPressure = 0;
- device_data.maxTanPressure = 0;
- device_data.minZ = 0;
- device_data.maxZ = 0;
-#endif
-
- // got the max pressure no need to go further...
- break;
- }
- any = (XAnyClassPtr) ((char *) any + any->length);
- } // end of for loop
-
- tablet_devices()->append(device_data);
- } // if (gotStylus || gotEraser)
- }
- if (X11->ptrXFreeDeviceList)
- X11->ptrXFreeDeviceList(devices);
- }
-#endif // QT_NO_TABLET
-
- X11->startupId = getenv("DESKTOP_STARTUP_ID");
- if (X11->startupId) {
-#ifndef QT_NO_UNSETENV
- unsetenv("DESKTOP_STARTUP_ID");
-#else
- // it's a small memory leak, however we won't crash if Qt is
- // unloaded and someones tries to use the envoriment.
- putenv(strdup("DESKTOP_STARTUP_ID="));
-#endif
- }
- } else {
- // read some non-GUI settings when not using the X server...
-
- if (QApplication::desktopSettingsAware()) {
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- settings.beginGroup(QLatin1String("Qt"));
-
- // 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.constBegin();
- while (it != pathlist.constEnd())
- QApplication::addLibraryPath(*it++);
- }
-
- 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);
- }
-
- settings.endGroup(); // Qt
- }
- }
-
-#if !defined (Q_OS_IRIX) && !defined (QT_NO_TABLET)
- QLibrary wacom(QString::fromLatin1("wacomcfg"), 0); // version 0 is the latest release at time of writing this.
- // NOTE: C casts instead of reinterpret_cast for GCC 3.3.x
- ptrWacomConfigInit = (PtrWacomConfigInit)wacom.resolve("WacomConfigInit");
- ptrWacomConfigOpenDevice = (PtrWacomConfigOpenDevice)wacom.resolve("WacomConfigOpenDevice");
- ptrWacomConfigGetRawParam = (PtrWacomConfigGetRawParam)wacom.resolve("WacomConfigGetRawParam");
- ptrWacomConfigCloseDevice = (PtrWacomConfigCloseDevice)wacom.resolve("WacomConfigCloseDevice");
- ptrWacomConfigTerm = (PtrWacomConfigTerm)wacom.resolve("WacomConfigTerm");
-
- if (ptrWacomConfigInit == 0 || ptrWacomConfigOpenDevice == 0 || ptrWacomConfigGetRawParam == 0
- || ptrWacomConfigCloseDevice == 0 || ptrWacomConfigTerm == 0) { // either we have all, or we have none.
- ptrWacomConfigInit = 0;
- ptrWacomConfigOpenDevice = 0;
- ptrWacomConfigGetRawParam = 0;
- ptrWacomConfigCloseDevice = 0;
- ptrWacomConfigTerm = 0;
- }
-#endif
-}
-
-void QApplicationPrivate::initializeWidgetPaletteHash()
-{
-}
-
-/*****************************************************************************
- qt_cleanup() - cleans up when the application is finished
- *****************************************************************************/
-
-void qt_cleanup()
-{
- if (app_save_rootinfo) // root window must keep state
- qt_save_rootinfo();
-
- if (qt_is_gui_used) {
- QPixmapCache::clear();
- QCursorData::cleanup();
- QFont::cleanup();
- QColormap::cleanup();
-
-#if !defined (QT_NO_TABLET)
- QTabletDeviceDataList *devices = qt_tablet_devices();
- if (X11->ptrXCloseDevice)
- for (int i = 0; i < devices->size(); ++i)
- X11->ptrXCloseDevice(X11->display, (XDevice*)devices->at(i).device);
- devices->clear();
-#endif
- }
-
-#ifndef QT_NO_XRENDER
- for (int i = 0; i < X11->solid_fill_count; ++i) {
- if (X11->solid_fills[i].picture)
- XRenderFreePicture(X11->display, X11->solid_fills[i].picture);
- }
- for (int i = 0; i < X11->pattern_fill_count; ++i) {
- if (X11->pattern_fills[i].picture)
- XRenderFreePicture(X11->display, X11->pattern_fills[i].picture);
- }
-#endif
-
-#if !defined(QT_NO_IM)
- delete QApplicationPrivate::inputContext;
- QApplicationPrivate::inputContext = 0;
-#endif
-
- // Reset the error handlers
- if (qt_is_gui_used)
- XSync(X11->display, False); // sync first to process all possible errors
- XSetErrorHandler(original_x_errhandler);
- XSetIOErrorHandler(original_xio_errhandler);
-
- if (X11->argbColormaps) {
- for (int s = 0; s < X11->screenCount; s++) {
- if (X11->argbColormaps[s])
- XFreeColormap(X11->display, X11->argbColormaps[s]);
- }
- }
-
- if (qt_is_gui_used && !X11->foreignDisplay)
- XCloseDisplay(X11->display); // close X display
- X11->display = 0;
-
- delete [] X11->screens;
- delete [] X11->argbVisuals;
- delete [] X11->argbColormaps;
-
- if (X11->foreignDisplay) {
- delete [] (char *)appName;
- appName = 0;
- }
-
- delete [] (char *)appClass;
- appClass = 0;
-
- if (X11->net_supported_list)
- delete [] X11->net_supported_list;
- X11->net_supported_list = 0;
-
- if (X11->net_virtual_root_list)
- delete [] X11->net_virtual_root_list;
- X11->net_virtual_root_list = 0;
-
- delete X11;
- X11 = 0;
-}
-
-
-/*****************************************************************************
- Platform specific global and internal functions
- *****************************************************************************/
-
-void qt_save_rootinfo() // save new root info
-{
- Atom type;
- int format;
- unsigned long length, after;
- uchar *data = 0;
-
- if (ATOM(_XSETROOT_ID)) { // kill old pixmap
- if (XGetWindowProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_XSETROOT_ID), 0, 1,
- True, AnyPropertyType, &type, &format,
- &length, &after, &data) == Success) {
- if (type == XA_PIXMAP && format == 32 && length == 1 &&
- after == 0 && data) {
- XKillClient(X11->display, *((Pixmap*)data));
- }
- Pixmap dummy = XCreatePixmap(X11->display, QX11Info::appRootWindow(),
- 1, 1, 1);
- XChangeProperty(X11->display, QX11Info::appRootWindow(),
- ATOM(_XSETROOT_ID), XA_PIXMAP, 32,
- PropModeReplace, (uchar *)&dummy, 1);
- XSetCloseDownMode(X11->display, RetainPermanent);
- }
- }
- if (data)
- XFree((char *)data);
-}
-
-void qt_updated_rootinfo()
-{
- app_save_rootinfo = true;
-}
-
-// ### Cleanup, this function is not in use!
-bool qt_wstate_iconified(WId winid)
-{
- Atom type;
- int format;
- unsigned long length, after;
- uchar *data = 0;
- int r = XGetWindowProperty(X11->display, winid, ATOM(WM_STATE), 0, 2,
- False, AnyPropertyType, &type, &format,
- &length, &after, &data);
- bool iconic = false;
- if (r == Success && data && format == 32) {
- // quint32 *wstate = (quint32*)data;
- unsigned long *wstate = (unsigned long *) data;
- iconic = (*wstate == IconicState);
- XFree((char *)data);
- }
- return iconic;
-}
-
-QString QApplicationPrivate::appName() const
-{
- return QString::fromLocal8Bit(QT_PREPEND_NAMESPACE(appName));
-}
-
-const char *QX11Info::appClass() // get application class
-{
- return QT_PREPEND_NAMESPACE(appClass);
-}
-
-bool qt_nograb() // application no-grab option
-{
-#if defined(QT_DEBUG)
- return appNoGrab;
-#else
- return false;
-#endif
-}
-
-
-/*****************************************************************************
- Platform specific QApplication members
- *****************************************************************************/
-
-#ifdef QT3_SUPPORT
-void QApplication::setMainWidget(QWidget *mainWidget)
-{
-#ifndef QT_NO_DEBUG
- if (mainWidget && mainWidget->parentWidget() && mainWidget->isWindow())
- qWarning("QApplication::setMainWidget: New main widget (%s/%s) "
- "has a parent",
- mainWidget->metaObject()->className(), mainWidget->objectName().toLocal8Bit().constData());
-#endif
- if (mainWidget)
- mainWidget->d_func()->createWinId();
- QApplicationPrivate::main_widget = mainWidget;
- if (QApplicationPrivate::main_widget) // give WM command line
- QApplicationPrivate::applyX11SpecificCommandLineArguments(QApplicationPrivate::main_widget);
-}
-#endif
-
-void QApplicationPrivate::applyX11SpecificCommandLineArguments(QWidget *main_widget)
-{
- static bool beenHereDoneThat = false;
- if (beenHereDoneThat)
- return;
- beenHereDoneThat = true;
- Q_ASSERT(main_widget->testAttribute(Qt::WA_WState_Created));
- if (mwTitle) {
- XStoreName(X11->display, main_widget->effectiveWinId(), (char*)mwTitle);
- QByteArray net_wm_name = QString::fromLocal8Bit(mwTitle).toUtf8();
- XChangeProperty(X11->display, main_widget->effectiveWinId(), ATOM(_NET_WM_NAME), ATOM(UTF8_STRING), 8,
- PropModeReplace, (unsigned char *)net_wm_name.data(), net_wm_name.size());
- }
- if (mwGeometry) { // parse geometry
- int x, y;
- int w, h;
- int m = XParseGeometry((char*)mwGeometry, &x, &y, (uint*)&w, (uint*)&h);
- QSize minSize = main_widget->minimumSize();
- QSize maxSize = main_widget->maximumSize();
- if ((m & XValue) == 0)
- x = main_widget->geometry().x();
- if ((m & YValue) == 0)
- y = main_widget->geometry().y();
- if ((m & WidthValue) == 0)
- w = main_widget->width();
- if ((m & HeightValue) == 0)
- h = main_widget->height();
- w = qMin(w,maxSize.width());
- h = qMin(h,maxSize.height());
- w = qMax(w,minSize.width());
- h = qMax(h,minSize.height());
- if ((m & XNegative)) {
- x = QApplication::desktop()->width() + x - w;
- }
- if ((m & YNegative)) {
- y = QApplication::desktop()->height() + y - h;
- }
- main_widget->setGeometry(x, y, w, h);
- }
-}
-
-#ifndef QT_NO_CURSOR
-
-/*****************************************************************************
- QApplication cursor stack
- *****************************************************************************/
-
-void QApplication::setOverrideCursor(const QCursor &cursor)
-{
- qApp->d_func()->cursor_list.prepend(cursor);
-
- QWidgetList all = allWidgets();
- for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
- register QWidget *w = *it;
- if ((w->testAttribute(Qt::WA_SetCursor) || w->isWindow()) && (w->windowType() != Qt::Desktop))
- qt_x11_enforce_cursor(w);
- }
- XFlush(X11->display); // make X execute it NOW
-}
-
-void QApplication::restoreOverrideCursor()
-{
- if (qApp->d_func()->cursor_list.isEmpty())
- return;
- qApp->d_func()->cursor_list.removeFirst();
-
- if (QWidgetPrivate::mapper != 0 && !closingDown()) {
- QWidgetList all = allWidgets();
- for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
- register QWidget *w = *it;
- if ((w->testAttribute(Qt::WA_SetCursor) || w->isWindow()) && (w->windowType() != Qt::Desktop))
- qt_x11_enforce_cursor(w);
- }
- XFlush(X11->display);
- }
-}
-
-#endif
-
-
-/*****************************************************************************
- Routines to find a Qt widget from a screen position
- *****************************************************************************/
-
-Window QX11Data::findClientWindow(Window win, Atom property, bool leaf)
-{
- Atom type = XNone;
- int format, i;
- ulong nitems, after;
- uchar *data = 0;
- Window root, parent, target=0, *children=0;
- uint nchildren;
- if (XGetWindowProperty(X11->display, win, property, 0, 0, false, AnyPropertyType,
- &type, &format, &nitems, &after, &data) == Success) {
- if (data)
- XFree((char *)data);
- if (type)
- return win;
- }
- if (!XQueryTree(X11->display,win,&root,&parent,&children,&nchildren)) {
- if (children)
- XFree((char *)children);
- return 0;
- }
- for (i=nchildren-1; !target && i >= 0; i--)
- target = X11->findClientWindow(children[i], property, leaf);
- if (children)
- XFree((char *)children);
- return target;
-}
-
-QWidget *QApplication::topLevelAt(const QPoint &p)
-{
-#ifdef QT_NO_CURSOR
- Q_UNUSED(p);
- return 0;
-#else
- int screen = QCursor::x11Screen();
- int unused;
-
- int x = p.x();
- int y = p.y();
- Window target;
- if (!XTranslateCoordinates(X11->display,
- QX11Info::appRootWindow(screen),
- QX11Info::appRootWindow(screen),
- x, y, &unused, &unused, &target)) {
- return 0;
- }
- if (!target || target == QX11Info::appRootWindow(screen))
- return 0;
- QWidget *w;
- w = QWidget::find((WId)target);
-
- if (!w) {
- X11->ignoreBadwindow();
- target = X11->findClientWindow(target, ATOM(WM_STATE), true);
- if (X11->badwindow())
- return 0;
- w = QWidget::find((WId)target);
- if (!w) {
- // Perhaps the widget at (x,y) is inside a foreign application?
- // Search all toplevel widgets to see if one is within target
- QWidgetList list = QApplication::topLevelWidgets();
- for (int i = 0; i < list.count(); ++i) {
- QWidget *widget = list.at(i);
- Window ctarget = target;
- if (widget->isVisible() && !(widget->windowType() == Qt::Desktop)) {
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- Window wid = widget->internalWinId();
- while (ctarget && !w) {
- X11->ignoreBadwindow();
- if (!XTranslateCoordinates(X11->display,
- QX11Info::appRootWindow(screen),
- ctarget, x, y, &unused, &unused, &ctarget)
- || X11->badwindow())
- break;
- if (ctarget == wid) {
- // Found!
- w = widget;
- break;
- }
- }
- }
- if (w)
- break;
- }
- }
- }
- return w ? w->window() : 0;
-#endif
-}
-
-void QApplication::syncX()
-{
- if (X11->display)
- XSync(X11->display, False); // don't discard events
-}
-
-
-void QApplication::beep()
-{
- if (X11->display)
- XBell(X11->display, 0);
- else
- printf("\7");
-}
-
-void QApplication::alert(QWidget *widget, int msec)
-{
- if (!QApplicationPrivate::checkInstance("alert"))
- return;
-
- QWidgetList windowsToMark;
- if (!widget) {
- windowsToMark += topLevelWidgets();
- } else {
- windowsToMark.append(widget->window());
- }
-
- for (int i = 0; i < windowsToMark.size(); ++i) {
- QWidget *window = windowsToMark.at(i);
- if (!window->isActiveWindow()) {
- qt_change_net_wm_state(window, true, ATOM(_NET_WM_STATE_DEMANDS_ATTENTION));
- if (msec != 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(window)) {
- qApp->d_func()->alertTimerHash.remove(window);
- delete oldTimer;
- }
- qApp->d_func()->alertTimerHash.insert(window, timer);
- timer->start(msec);
- }
- }
- }
-}
-
-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) {
- QWidget *window = it.key();
- qt_change_net_wm_state(window, false, ATOM(_NET_WM_STATE_DEMANDS_ATTENTION));
- alertTimerHash.erase(it);
- timer->deleteLater();
- break;
- }
- ++it;
- }
- }
-}
-
-/*****************************************************************************
- Special lookup functions for windows that have been reparented recently
- *****************************************************************************/
-
-static QWidgetMapper *wPRmapper = 0; // alternative widget mapper
-
-void qPRCreate(const QWidget *widget, Window oldwin)
-{ // QWidget::reparent mechanism
- if (!wPRmapper)
- wPRmapper = new QWidgetMapper;
-
- QETWidget *w = static_cast<QETWidget *>(const_cast<QWidget *>(widget));
- wPRmapper->insert((int)oldwin, w); // add old window to mapper
- w->setAttribute(Qt::WA_WState_Reparented); // set reparented flag
-}
-
-void qPRCleanup(QWidget *widget)
-{
- QETWidget *etw = static_cast<QETWidget *>(const_cast<QWidget *>(widget));
- if (!(wPRmapper && widget->testAttribute(Qt::WA_WState_Reparented)))
- return; // not a reparented widget
- QWidgetMapper::Iterator it = wPRmapper->begin();
- while (it != wPRmapper->constEnd()) {
- QWidget *w = *it;
- if (w == etw) { // found widget
- etw->setAttribute(Qt::WA_WState_Reparented, false); // clear flag
- it = wPRmapper->erase(it);// old window no longer needed
- } else {
- ++it;
- }
- }
- if (wPRmapper->size() == 0) { // became empty
- delete wPRmapper; // then reset alt mapper
- wPRmapper = 0;
- }
-}
-
-static QETWidget *qPRFindWidget(Window oldwin)
-{
- return wPRmapper ? (QETWidget*)wPRmapper->value((int)oldwin, 0) : 0;
-}
-
-int QApplication::x11ClientMessage(QWidget* w, XEvent* event, bool passive_only)
-{
- if (w && !w->internalWinId())
- return 0;
- QETWidget *widget = (QETWidget*)w;
- if (event->xclient.format == 32 && event->xclient.message_type) {
- if (event->xclient.message_type == ATOM(WM_PROTOCOLS)) {
- Atom a = event->xclient.data.l[0];
- if (a == ATOM(WM_DELETE_WINDOW)) {
- if (passive_only) return 0;
- widget->translateCloseEvent(event);
- }
- else if (a == ATOM(WM_TAKE_FOCUS)) {
- if ((ulong) event->xclient.data.l[1] > X11->time)
- X11->time = event->xclient.data.l[1];
- QWidget *amw = activeModalWidget();
- if (amw && amw->testAttribute(Qt::WA_X11DoNotAcceptFocus))
- amw = 0;
- if (amw && !QApplicationPrivate::tryModalHelper(widget, 0)) {
- QWidget *p = amw->parentWidget();
- while (p && p != widget)
- p = p->parentWidget();
- if (!p || !X11->net_supported_list)
- amw->raise(); // help broken window managers
- amw->activateWindow();
- }
-#ifndef QT_NO_WHATSTHIS
- } else if (a == ATOM(_NET_WM_CONTEXT_HELP)) {
- QWhatsThis::enterWhatsThisMode();
-#endif // QT_NO_WHATSTHIS
- } else if (a == ATOM(_NET_WM_PING)) {
- // avoid send/reply loops
- Window root = RootWindow(X11->display, w->x11Info().screen());
- if (event->xclient.window != root) {
- event->xclient.window = root;
- XSendEvent(event->xclient.display, event->xclient.window,
- False, SubstructureNotifyMask|SubstructureRedirectMask, event);
- }
-#ifndef QT_NO_XSYNC
- } else if (a == ATOM(_NET_WM_SYNC_REQUEST)) {
- const ulong timestamp = (const ulong) event->xclient.data.l[1];
- if (timestamp > X11->time)
- X11->time = timestamp;
- if (QTLWExtra *tlw = w->d_func()->maybeTopData()) {
- if (timestamp == CurrentTime || timestamp > tlw->syncRequestTimestamp) {
- tlw->syncRequestTimestamp = timestamp;
- tlw->newCounterValueLo = event->xclient.data.l[2];
- tlw->newCounterValueHi = event->xclient.data.l[3];
- }
- }
-#endif
- }
- } else if (event->xclient.message_type == ATOM(_QT_SCROLL_DONE)) {
- widget->translateScrollDoneEvent(event);
- } else if (event->xclient.message_type == ATOM(XdndPosition)) {
- X11->xdndHandlePosition(widget, event, passive_only);
- } else if (event->xclient.message_type == ATOM(XdndEnter)) {
- X11->xdndHandleEnter(widget, event, passive_only);
- } else if (event->xclient.message_type == ATOM(XdndStatus)) {
- X11->xdndHandleStatus(widget, event, passive_only);
- } else if (event->xclient.message_type == ATOM(XdndLeave)) {
- X11->xdndHandleLeave(widget, event, passive_only);
- } else if (event->xclient.message_type == ATOM(XdndDrop)) {
- X11->xdndHandleDrop(widget, event, passive_only);
- } else if (event->xclient.message_type == ATOM(XdndFinished)) {
- X11->xdndHandleFinished(widget, event, passive_only);
- } else {
- if (passive_only) return 0;
- // All other are interactions
- }
- } else {
- X11->motifdndHandle(widget, event, passive_only);
- }
-
- return 0;
-}
-
-int QApplication::x11ProcessEvent(XEvent* event)
-{
- Q_D(QApplication);
- QScopedLoopLevelCounter loopLevelCounter(d->threadData);
-
-#ifdef ALIEN_DEBUG
- //qDebug() << "QApplication::x11ProcessEvent:" << event->type;
-#endif
- switch (event->type) {
- case ButtonPress:
- pressed_window = event->xbutton.window;
- X11->userTime = event->xbutton.time;
- // fallthrough intended
- case ButtonRelease:
- X11->time = event->xbutton.time;
- break;
- case MotionNotify:
- X11->time = event->xmotion.time;
- break;
- case XKeyPress:
- X11->userTime = event->xkey.time;
- // fallthrough intended
- case XKeyRelease:
- X11->time = event->xkey.time;
- break;
- case PropertyNotify:
- X11->time = event->xproperty.time;
- break;
- case EnterNotify:
- case LeaveNotify:
- X11->time = event->xcrossing.time;
- break;
- case SelectionClear:
- X11->time = event->xselectionclear.time;
- break;
- default:
- break;
- }
-#ifndef QT_NO_XFIXES
- if (X11->use_xfixes && event->type == (X11->xfixes_eventbase + XFixesSelectionNotify)) {
- XFixesSelectionNotifyEvent *req =
- reinterpret_cast<XFixesSelectionNotifyEvent *>(event);
- X11->time = req->selection_timestamp;
- if (req->selection == ATOM(_NET_WM_CM_S0))
- X11->compositingManagerRunning = req->owner;
- }
-#endif
-
- QETWidget *widget = (QETWidget*)QWidget::find((WId)event->xany.window);
-
- if (wPRmapper) { // just did a widget reparent?
- if (widget == 0) { // not in std widget mapper
- switch (event->type) { // only for mouse/key events
- case ButtonPress:
- case ButtonRelease:
- case MotionNotify:
- case XKeyPress:
- case XKeyRelease:
- widget = qPRFindWidget(event->xany.window);
- break;
- }
- }
- else if (widget->testAttribute(Qt::WA_WState_Reparented))
- qPRCleanup(widget); // remove from alt mapper
- }
-
- QETWidget *keywidget=0;
- bool grabbed=false;
- if (event->type==XKeyPress || event->type==XKeyRelease) {
- keywidget = (QETWidget*)QWidget::keyboardGrabber();
- if (keywidget) {
- grabbed = true;
- } else if (!keywidget) {
- if (d->inPopupMode()) // no focus widget, see if we have a popup
- keywidget = (QETWidget*) (activePopupWidget()->focusWidget() ? activePopupWidget()->focusWidget() : activePopupWidget());
- else if (QApplicationPrivate::focus_widget)
- keywidget = (QETWidget*)QApplicationPrivate::focus_widget;
- else if (widget)
- keywidget = (QETWidget*)widget->window();
- }
- }
-
-#ifndef QT_NO_IM
- // Filtering input events by the input context. It has to be taken
- // place before any other key event consumers such as eventfilters
- // and accelerators because some input methods require quite
- // various key combination and sequences. It often conflicts with
- // accelerators and so on, so we must give the input context the
- // filtering opportunity first to ensure all input methods work
- // properly regardless of application design.
-
- if(keywidget && keywidget->isEnabled() && keywidget->testAttribute(Qt::WA_InputMethodEnabled)) {
- // block user interaction during session management
- if((event->type==XKeyPress || event->type==XKeyRelease) && qt_sm_blockUserInput)
- return true;
-
- // for XIM handling
- QInputContext *qic = keywidget->inputContext();
- if(qic && qic->x11FilterEvent(keywidget, event))
- return true;
-
- // filterEvent() accepts QEvent *event rather than preexpanded
- // key event attribute values. This is intended to pass other
- // QInputEvent in future. Other non IM-related events should
- // not be forwarded to input contexts to prevent weird event
- // handling.
- if ((event->type == XKeyPress || event->type == XKeyRelease)) {
- int code = -1;
- int count = 0;
- Qt::KeyboardModifiers modifiers;
- QEvent::Type type;
- QString text;
- KeySym keySym;
-
- qt_keymapper_private()->translateKeyEventInternal(keywidget, event, keySym, count,
- text, modifiers, code, type, false);
-
- // both key press/release is required for some complex
- // input methods. don't eliminate anything.
- QKeyEventEx keyevent(type, code, modifiers, text, false, qMax(qMax(count, 1), text.length()),
- event->xkey.keycode, keySym, event->xkey.state);
- if(qic && qic->filterEvent(&keyevent))
- return true;
- }
- } else
-#endif // QT_NO_IM
- {
- if (XFilterEvent(event, XNone))
- return true;
- }
-
- if (qt_x11EventFilter(event)) // send through app filter
- return 1;
-
- if (event->type == MappingNotify) {
- // keyboard mapping changed
- XRefreshKeyboardMapping(&event->xmapping);
-
- QKeyMapper::changeKeyboard();
- return 0;
- }
-#ifndef QT_NO_XKB
- else if (X11->use_xkb && event->type == X11->xkb_eventbase) {
- XkbAnyEvent *xkbevent = (XkbAnyEvent *) event;
- switch (xkbevent->xkb_type) {
- case XkbStateNotify:
- {
- XkbStateNotifyEvent *xkbstateevent = (XkbStateNotifyEvent *) xkbevent;
- if ((xkbstateevent->changed & XkbGroupStateMask) != 0) {
- qt_keymapper_private()->xkb_currentGroup = xkbstateevent->group;
- QKeyMapper::changeKeyboard();
- }
- break;
- }
- default:
- break;
- }
- }
-#endif
-
- if (!widget) { // don't know this windows
- QWidget* popup = QApplication::activePopupWidget();
- if (popup) {
-
- /*
- That is more than suboptimal. The real solution should
- do some keyevent and buttonevent translation, so that
- the popup still continues to work as the user expects.
- Unfortunately this translation is currently only
- possible with a known widget. I'll change that soon
- (Matthias).
- */
-
- // Danger - make sure we don't lock the server
- switch (event->type) {
- case ButtonPress:
- case ButtonRelease:
- case XKeyPress:
- case XKeyRelease:
- do {
- popup->close();
- } while ((popup = qApp->activePopupWidget()));
- return 1;
- }
- }
- return -1;
- }
-
- if (event->type == XKeyPress || event->type == XKeyRelease)
- widget = keywidget; // send XKeyEvents through keywidget->x11Event()
-
- if (app_do_modal) // modal event handling
- if (!qt_try_modal(widget, event)) {
- if (event->type == ClientMessage && !widget->x11Event(event))
- x11ClientMessage(widget, event, true);
- return 1;
- }
-
-
- if (widget->x11Event(event)) // send through widget filter
- return 1;
-#if !defined (QT_NO_TABLET)
- if (!qt_xdnd_dragging) {
- QTabletDeviceDataList *tablets = qt_tablet_devices();
- for (int i = 0; i < tablets->size(); ++i) {
- QTabletDeviceData &tab = tablets->operator [](i);
- if (event->type == tab.xinput_motion
- || event->type == tab.xinput_button_release
- || event->type == tab.xinput_button_press
- || event->type == tab.xinput_proximity_in
- || event->type == tab.xinput_proximity_out) {
- widget->translateXinputEvent(event, &tab);
- return 0;
- }
- }
- }
-#endif
-
-#ifndef QT_NO_XRANDR
- if (X11->use_xrandr && event->type == (X11->xrandr_eventbase + RRScreenChangeNotify)) {
- // update Xlib internals with the latest screen configuration
- X11->ptrXRRUpdateConfiguration(event);
-
- // update the size for desktop widget
- int scr = X11->ptrXRRRootToScreen(X11->display, event->xany.window);
- QDesktopWidget *desktop = QApplication::desktop();
- QWidget *w = desktop->screen(scr);
- QSize oldSize(w->size());
- w->data->crect.setWidth(DisplayWidth(X11->display, scr));
- w->data->crect.setHeight(DisplayHeight(X11->display, scr));
- QResizeEvent e(w->size(), oldSize);
- QApplication::sendEvent(w, &e);
- if (w != desktop)
- QApplication::sendEvent(desktop, &e);
- }
-#endif // QT_NO_XRANDR
-
-#ifndef QT_NO_XFIXES
- if (X11->use_xfixes && event->type == (X11->xfixes_eventbase + XFixesSelectionNotify)) {
- XFixesSelectionNotifyEvent *req = reinterpret_cast<XFixesSelectionNotifyEvent *>(event);
-
- // compress all XFixes events related to this selection
- // we don't want to handle old SelectionNotify events.
- qt_xfixes_selection_event_data xfixes_event;
- xfixes_event.selection = req->selection;
- for (XEvent ev;;) {
- if (!XCheckIfEvent(X11->display, &ev, &qt_xfixes_scanner, (XPointer)&xfixes_event))
- break;
- }
-
- if (req->selection == ATOM(CLIPBOARD)) {
- if (qt_xfixes_clipboard_changed(req->owner, req->selection_timestamp)) {
- emit clipboard()->changed(QClipboard::Clipboard);
- emit clipboard()->dataChanged();
- }
- } else if (req->selection == XA_PRIMARY) {
- if (qt_xfixes_selection_changed(req->owner, req->selection_timestamp)) {
- emit clipboard()->changed(QClipboard::Selection);
- emit clipboard()->selectionChanged();
- }
- }
- }
-#endif // QT_NO_XFIXES
-
- switch (event->type) {
-
- case ButtonRelease: // mouse event
- if (!d->inPopupMode() && !QWidget::mouseGrabber() && pressed_window != widget->internalWinId()
- && (widget = (QETWidget*) QWidget::find((WId)pressed_window)) == 0)
- break;
- // fall through intended
- case ButtonPress:
- if (event->xbutton.root != RootWindow(X11->display, widget->x11Info().screen())
- && ! qt_xdnd_dragging) {
- while (activePopupWidget())
- activePopupWidget()->close();
- return 1;
- }
- if (event->type == ButtonPress)
- qt_net_update_user_time(widget->window(), X11->userTime);
- // fall through intended
- case MotionNotify:
-#if !defined(QT_NO_TABLET)
- if (!qt_tabletChokeMouse) {
-#endif
- if (widget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
- QPoint pos(event->xbutton.x, event->xbutton.y);
- pos = widget->d_func()->mapFromWS(pos);
- QWidget *window = widget->window();
- pos = widget->mapTo(window, pos);
- if (QWidget *child = window->childAt(pos)) {
- widget = static_cast<QETWidget *>(child);
- pos = child->mapFrom(window, pos);
- event->xbutton.x = pos.x();
- event->xbutton.y = pos.y();
- }
- }
- widget->translateMouseEvent(event);
-#if !defined(QT_NO_TABLET)
- } else {
- qt_tabletChokeMouse = false;
- }
-#endif
- break;
-
- case XKeyPress: // keyboard event
- qt_net_update_user_time(widget->window(), X11->userTime);
- // fallthrough intended
- case XKeyRelease:
- {
- if (keywidget && keywidget->isEnabled()) { // should always exist
- // qDebug("sending key event");
- qt_keymapper_private()->translateKeyEvent(keywidget, event, grabbed);
- }
- break;
- }
-
- case GraphicsExpose:
- case Expose: // paint event
- widget->translatePaintEvent(event);
- break;
-
- case ConfigureNotify: // window move/resize event
- if (event->xconfigure.event == event->xconfigure.window)
- widget->translateConfigEvent(event);
- break;
-
- case XFocusIn: { // got focus
- if ((widget->windowType() == Qt::Desktop))
- break;
- if (d->inPopupMode()) // some delayed focus event to ignore
- break;
- if (!widget->isWindow())
- break;
- if (event->xfocus.detail != NotifyAncestor &&
- event->xfocus.detail != NotifyInferior &&
- event->xfocus.detail != NotifyNonlinear)
- break;
- setActiveWindow(widget);
- if (X11->focus_model == QX11Data::FM_PointerRoot) {
- // We got real input focus from somewhere, but we were in PointerRoot
- // mode, so we don't trust this event. Check the focus model to make
- // sure we know what focus mode we are using...
- qt_check_focus_model();
- }
- }
- break;
-
- case XFocusOut: // lost focus
- if ((widget->windowType() == Qt::Desktop))
- break;
- if (!widget->isWindow())
- break;
- if (event->xfocus.mode == NotifyGrab) {
- qt_xfocusout_grab_counter++;
- break;
- }
- if (event->xfocus.detail != NotifyAncestor &&
- event->xfocus.detail != NotifyNonlinearVirtual &&
- event->xfocus.detail != NotifyNonlinear)
- break;
- if (!d->inPopupMode() && widget == QApplicationPrivate::active_window) {
- XEvent ev;
- bool focus_will_change = false;
- if (XCheckTypedEvent(X11->display, XFocusIn, &ev)) {
- // we're about to get an XFocusIn, if we know we will
- // get a new active window, we don't want to set the
- // active window to 0 now
- QWidget *w2 = QWidget::find(ev.xany.window);
- if (w2
- && w2->windowType() != Qt::Desktop
- && !d->inPopupMode() // some delayed focus event to ignore
- && w2->isWindow()
- && (ev.xfocus.detail == NotifyAncestor
- || ev.xfocus.detail == NotifyInferior
- || ev.xfocus.detail == NotifyNonlinear))
- focus_will_change = true;
-
- XPutBackEvent(X11->display, &ev);
- }
- if (!focus_will_change)
- setActiveWindow(0);
- }
- break;
-
- case EnterNotify: { // enter window
- if (QWidget::mouseGrabber() && (!d->inPopupMode() || widget->window() != activePopupWidget()))
- break;
- if ((event->xcrossing.mode != NotifyNormal
- && event->xcrossing.mode != NotifyUngrab)
- || event->xcrossing.detail == NotifyVirtual
- || event->xcrossing.detail == NotifyNonlinearVirtual)
- break;
- if (event->xcrossing.focus &&
- !(widget->windowType() == Qt::Desktop) && !widget->isActiveWindow()) {
- if (X11->focus_model == QX11Data::FM_Unknown) // check focus model
- qt_check_focus_model();
- if (X11->focus_model == QX11Data::FM_PointerRoot) // PointerRoot mode
- setActiveWindow(widget);
- }
-
- if (qt_button_down && !d->inPopupMode())
- break;
-
- QWidget *alien = widget->childAt(widget->d_func()->mapFromWS(QPoint(event->xcrossing.x,
- event->xcrossing.y)));
- QWidget *enter = alien ? alien : widget;
- QWidget *leave = 0;
- if (qt_last_mouse_receiver && !qt_last_mouse_receiver->internalWinId())
- leave = qt_last_mouse_receiver;
- else
- leave = QWidget::find(curWin);
-
- // ### Alien: enter/leave might be wrong here with overlapping siblings
- // if the enter widget is native and stacked under a non-native widget.
- QApplicationPrivate::dispatchEnterLeave(enter, leave);
- curWin = widget->internalWinId();
- qt_last_mouse_receiver = enter;
- if (!d->inPopupMode() || widget->window() == activePopupWidget())
- widget->translateMouseEvent(event); //we don't get MotionNotify, emulate it
- }
- break;
- case LeaveNotify: { // leave window
- QWidget *mouseGrabber = QWidget::mouseGrabber();
- if (mouseGrabber && !d->inPopupMode())
- break;
- if (curWin && widget->internalWinId() != curWin)
- break;
- if ((event->xcrossing.mode != NotifyNormal
- && event->xcrossing.mode != NotifyUngrab)
- || event->xcrossing.detail == NotifyInferior)
- break;
- if (!(widget->windowType() == Qt::Desktop))
- widget->translateMouseEvent(event); //we don't get MotionNotify, emulate it
-
- QWidget* enter = 0;
- QPoint enterPoint;
- XEvent ev;
- while (XCheckMaskEvent(X11->display, EnterWindowMask | LeaveWindowMask , &ev)
- && !qt_x11EventFilter(&ev)) {
- QWidget* event_widget = QWidget::find(ev.xcrossing.window);
- if(event_widget && event_widget->x11Event(&ev))
- break;
- if (ev.type == LeaveNotify
- || (ev.xcrossing.mode != NotifyNormal
- && ev.xcrossing.mode != NotifyUngrab)
- || ev.xcrossing.detail == NotifyVirtual
- || ev.xcrossing.detail == NotifyNonlinearVirtual)
- continue;
- enter = event_widget;
- if (enter)
- enterPoint = enter->d_func()->mapFromWS(QPoint(ev.xcrossing.x, ev.xcrossing.y));
- if (ev.xcrossing.focus &&
- enter && !(enter->windowType() == Qt::Desktop) && !enter->isActiveWindow()) {
- if (X11->focus_model == QX11Data::FM_Unknown) // check focus model
- qt_check_focus_model();
- if (X11->focus_model == QX11Data::FM_PointerRoot) // PointerRoot mode
- setActiveWindow(enter);
- }
- break;
- }
-
- if ((! enter || (enter->windowType() == Qt::Desktop)) &&
- event->xcrossing.focus && widget == QApplicationPrivate::active_window &&
- X11->focus_model == QX11Data::FM_PointerRoot // PointerRoot mode
- ) {
- setActiveWindow(0);
- }
-
- if (qt_button_down && !d->inPopupMode())
- break;
-
- if (!curWin)
- QApplicationPrivate::dispatchEnterLeave(widget, 0);
-
- if (enter) {
- QWidget *alienEnter = enter->childAt(enterPoint);
- if (alienEnter)
- enter = alienEnter;
- }
-
- QWidget *leave = qt_last_mouse_receiver ? qt_last_mouse_receiver : widget;
- QWidget *activePopupWidget = qApp->activePopupWidget();
-
- if (mouseGrabber && activePopupWidget && leave == activePopupWidget)
- enter = mouseGrabber;
- else if (enter != widget && mouseGrabber) {
- if (!widget->rect().contains(widget->d_func()->mapFromWS(QPoint(event->xcrossing.x,
- event->xcrossing.y))))
- break;
- }
-
- QApplicationPrivate::dispatchEnterLeave(enter, leave);
- qt_last_mouse_receiver = enter;
-
- if (enter && QApplicationPrivate::tryModalHelper(enter, 0)) {
- QWidget *nativeEnter = enter->internalWinId() ? enter : enter->nativeParentWidget();
- curWin = nativeEnter->internalWinId();
- static_cast<QETWidget *>(nativeEnter)->translateMouseEvent(&ev); //we don't get MotionNotify, emulate it
- } else {
- curWin = 0;
- qt_last_mouse_receiver = 0;
- }
- }
- break;
-
- case UnmapNotify: // window hidden
- if (widget->isWindow()) {
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- widget->d_func()->topData()->waitingForMapNotify = 0;
-
- if (widget->windowType() != Qt::Popup && !widget->testAttribute(Qt::WA_DontShowOnScreen)) {
- widget->setAttribute(Qt::WA_Mapped, false);
- if (widget->isVisible()) {
- widget->d_func()->topData()->spont_unmapped = 1;
- QHideEvent e;
- QApplication::sendSpontaneousEvent(widget, &e);
- widget->d_func()->hideChildren(true);
- }
- }
-
- if (!widget->d_func()->topData()->validWMState && X11->deferred_map.removeAll(widget))
- widget->doDeferredMap();
- }
- break;
-
- case MapNotify: // window shown
- if (widget->isWindow()) {
- // if we got a MapNotify when we were not waiting for it, it most
- // likely means the user has already asked to hide the window before
- // it ever being shown, so we try to withdraw a window after sending
- // the QShowEvent.
- bool pendingHide = widget->testAttribute(Qt::WA_WState_ExplicitShowHide) && widget->testAttribute(Qt::WA_WState_Hidden);
- widget->d_func()->topData()->waitingForMapNotify = 0;
-
- if (widget->windowType() != Qt::Popup) {
- widget->setAttribute(Qt::WA_Mapped);
- if (widget->d_func()->topData()->spont_unmapped) {
- widget->d_func()->topData()->spont_unmapped = 0;
- widget->d_func()->showChildren(true);
- QShowEvent e;
- QApplication::sendSpontaneousEvent(widget, &e);
-
- // show() must have been called on this widget in
- // order to reach this point, but we could have
- // cleared these 2 attributes in case something
- // previously forced us into WithdrawnState
- // (e.g. kdocker)
- widget->setAttribute(Qt::WA_WState_ExplicitShowHide, true);
- widget->setAttribute(Qt::WA_WState_Visible, true);
- }
- }
- if (pendingHide) // hide the window
- XWithdrawWindow(X11->display, widget->internalWinId(), widget->x11Info().screen());
- }
- break;
-
- case ClientMessage: // client message
- return x11ClientMessage(widget,event,False);
-
- case ReparentNotify: { // window manager reparents
- // compress old reparent events to self
- XEvent ev;
- while (XCheckTypedWindowEvent(X11->display,
- widget->effectiveWinId(),
- ReparentNotify,
- &ev)) {
- if (ev.xreparent.window != ev.xreparent.event) {
- XPutBackEvent(X11->display, &ev);
- break;
- }
- }
- if (widget->isWindow()) {
- QTLWExtra *topData = widget->d_func()->topData();
-
- // store the parent. Useful for many things, embedding for instance.
- topData->parentWinId = event->xreparent.parent;
-
- // the widget frame strut should also be invalidated
- widget->data->fstrut_dirty = 1;
-
- // work around broken window managers... if we get a
- // ReparentNotify before the MapNotify, we assume that
- // we're being managed by a reparenting window
- // manager.
- //
- // however, the WM_STATE property may not have been set
- // yet, but we are going to assume that it will
- // be... otherwise we could try to map again after getting
- // an UnmapNotify... which could then, in turn, trigger a
- // race in the window manager which causes the window to
- // disappear when it really should be hidden.
- if (topData->waitingForMapNotify && !topData->validWMState) {
- topData->waitingForMapNotify = 0;
- topData->validWMState = 1;
- }
-
- if (X11->focus_model != QX11Data::FM_Unknown) {
- // toplevel reparented...
- QWidget *newparent = QWidget::find(event->xreparent.parent);
- if (! newparent || (newparent->windowType() == Qt::Desktop)) {
- // we don't know about the new parent (or we've been
- // reparented to root), perhaps a window manager
- // has been (re)started? reset the focus model to unknown
- X11->focus_model = QX11Data::FM_Unknown;
- }
- }
- }
- break;
- }
- case SelectionRequest: {
- XSelectionRequestEvent *req = &event->xselectionrequest;
- if (! req)
- break;
-
- if (ATOM(XdndSelection) && req->selection == ATOM(XdndSelection)) {
- X11->xdndHandleSelectionRequest(req);
-
- } else if (qt_clipboard) {
- QClipboardEvent e(reinterpret_cast<QEventPrivate*>(event));
- QApplication::sendSpontaneousEvent(qt_clipboard, &e);
- }
- break;
- }
- case SelectionClear: {
- XSelectionClearEvent *req = &event->xselectionclear;
- // don't deliver dnd events to the clipboard, it gets confused
- if (! req || (ATOM(XdndSelection) && req->selection == ATOM(XdndSelection)))
- break;
-
- if (qt_clipboard && !X11->use_xfixes) {
- QClipboardEvent e(reinterpret_cast<QEventPrivate*>(event));
- QApplication::sendSpontaneousEvent(qt_clipboard, &e);
- }
- break;
- }
-
- case SelectionNotify: {
- XSelectionEvent *req = &event->xselection;
- // don't deliver dnd events to the clipboard, it gets confused
- if (! req || (ATOM(XdndSelection) && req->selection == ATOM(XdndSelection)))
- break;
-
- if (qt_clipboard) {
- QClipboardEvent e(reinterpret_cast<QEventPrivate*>(event));
- QApplication::sendSpontaneousEvent(qt_clipboard, &e);
- }
- break;
- }
- case PropertyNotify:
- // some properties changed
- if (event->xproperty.window == QX11Info::appRootWindow(0)) {
- // root properties for the first screen
- if (!X11->use_xfixes && event->xproperty.atom == ATOM(_QT_CLIPBOARD_SENTINEL)) {
- if (qt_check_clipboard_sentinel()) {
- emit clipboard()->changed(QClipboard::Clipboard);
- emit clipboard()->dataChanged();
- }
- } else if (!X11->use_xfixes && event->xproperty.atom == ATOM(_QT_SELECTION_SENTINEL)) {
- if (qt_check_selection_sentinel()) {
- emit clipboard()->changed(QClipboard::Selection);
- emit clipboard()->selectionChanged();
- }
- } else if (QApplicationPrivate::obey_desktop_settings) {
- if (event->xproperty.atom == ATOM(RESOURCE_MANAGER))
- qt_set_x11_resources();
- else if (event->xproperty.atom == ATOM(_QT_SETTINGS_TIMESTAMP))
- qt_set_x11_resources();
- }
- }
- if (event->xproperty.window == QX11Info::appRootWindow()) {
- // root properties for the default screen
- if (event->xproperty.atom == ATOM(_QT_INPUT_ENCODING)) {
- qt_set_input_encoding();
- } else if (event->xproperty.atom == ATOM(_NET_SUPPORTED)) {
- qt_get_net_supported();
- } else if (event->xproperty.atom == ATOM(_NET_VIRTUAL_ROOTS)) {
- qt_get_net_virtual_roots();
- } else if (event->xproperty.atom == ATOM(_NET_WORKAREA)) {
- qt_desktopwidget_update_workarea();
-
- // emit the workAreaResized() signal
- QDesktopWidget *desktop = QApplication::desktop();
- int numScreens = desktop->numScreens();
- for (int i = 0; i < numScreens; ++i)
- emit desktop->workAreaResized(i);
- }
- } else if (widget) {
- widget->translatePropertyEvent(event);
- } else {
- return -1; // don't know this window
- }
- break;
-
- default:
- break;
- }
-
- return 0;
-}
-
-bool QApplication::x11EventFilter(XEvent *)
-{
- return false;
-}
-
-
-
-/*****************************************************************************
- Modal widgets; Since Xlib has little support for this we roll our own
- modal widget mechanism.
- A modal widget without a parent becomes application-modal.
- A modal widget with a parent becomes modal to its parent and grandparents..
-
- QApplicationPrivate::enterModal()
- Enters modal state
- Arguments:
- QWidget *widget A modal widget
-
- QApplicationPrivate::leaveModal()
- Leaves modal state for a widget
- Arguments:
- QWidget *widget A modal widget
- *****************************************************************************/
-
-bool QApplicationPrivate::modalState()
-{
- return app_do_modal;
-}
-
-void QApplicationPrivate::enterModal_sys(QWidget *widget)
-{
- if (!qt_modal_stack)
- qt_modal_stack = new QWidgetList;
-
- QWidget *leave = qt_last_mouse_receiver;
- if (!leave)
- leave = QWidget::find((WId)curWin);
- QApplicationPrivate::dispatchEnterLeave(0, leave);
- qt_modal_stack->insert(0, widget);
- app_do_modal = true;
- curWin = 0;
- qt_last_mouse_receiver = 0;
-}
-
-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;
- QPoint p(QCursor::pos());
- QWidget* w = QApplication::widgetAt(p.x(), p.y());
- QWidget *leave = qt_last_mouse_receiver;
- if (!leave)
- leave = QWidget::find((WId)curWin);
- if (QWidget *grabber = QWidget::mouseGrabber()) {
- w = grabber;
- if (leave == w)
- leave = 0;
- }
- QApplicationPrivate::dispatchEnterLeave(w, leave); // send synthetic enter event
- curWin = w ? w->effectiveWinId() : 0;
- qt_last_mouse_receiver = w;
- }
- }
- app_do_modal = qt_modal_stack != 0;
-}
-
-bool qt_try_modal(QWidget *widget, XEvent *event)
-{
- if (qt_xdnd_dragging) {
- // allow mouse events while DnD is active
- switch (event->type) {
- case ButtonPress:
- case ButtonRelease:
- case MotionNotify:
- return true;
- default:
- break;
- }
- }
-
- // allow mouse release events to be sent to widgets that have been pressed
- if (event->type == ButtonRelease) {
- QWidget *alienWidget = widget->childAt(widget->mapFromGlobal(QPoint(event->xbutton.x_root,
- event->xbutton.y_root)));
- if (widget == qt_button_down || (alienWidget && alienWidget == qt_button_down))
- return true;
- }
-
- if (QApplicationPrivate::tryModalHelper(widget))
- return true;
-
- // disallow mouse/key events
- switch (event->type) {
- case ButtonPress:
- case ButtonRelease:
- case MotionNotify:
- case XKeyPress:
- case XKeyRelease:
- case EnterNotify:
- case LeaveNotify:
- case ClientMessage:
- return false;
- default:
- break;
- }
-
- return true;
-}
-
-
-/*****************************************************************************
- Popup widget mechanism
-
- openPopup()
- Adds a widget to the list of popup widgets
- Arguments:
- QWidget *widget The popup widget to be added
-
- closePopup()
- Removes a widget from the list of popup widgets
- Arguments:
- QWidget *widget The popup widget to be removed
- *****************************************************************************/
-
-
-static int openPopupCount = 0;
-void QApplicationPrivate::openPopup(QWidget *popup)
-{
- Q_Q(QApplication);
- openPopupCount++;
- if (!QApplicationPrivate::popupWidgets) { // create list
- QApplicationPrivate::popupWidgets = new QWidgetList;
- }
- QApplicationPrivate::popupWidgets->append(popup); // add to end of list
- Display *dpy = X11->display;
- if (QApplicationPrivate::popupWidgets->count() == 1 && !qt_nograb()){ // grab mouse/keyboard
- Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
- int r = XGrabKeyboard(dpy, popup->effectiveWinId(), false,
- GrabModeAsync, GrabModeAsync, X11->time);
- if ((popupGrabOk = (r == GrabSuccess))) {
- r = XGrabPointer(dpy, popup->effectiveWinId(), true,
- (ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
- | EnterWindowMask | LeaveWindowMask | PointerMotionMask),
- GrabModeAsync, GrabModeAsync, XNone, XNone, X11->time);
- if (!(popupGrabOk = (r == GrabSuccess))) {
- // transfer grab back to the keyboard grabber if any
- if (QWidgetPrivate::keyboardGrabber != 0)
- QWidgetPrivate::keyboardGrabber->grabKeyboard();
- else
- XUngrabKeyboard(dpy, X11->time);
- }
- }
- }
-
- // 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
- if (QWidget *fw = QApplication::focusWidget()) {
- QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
- q->sendEvent(fw, &e);
- }
- }
-}
-
-void QApplicationPrivate::closePopup(QWidget *popup)
-{
- Q_Q(QApplication);
- if (!QApplicationPrivate::popupWidgets)
- return;
- QApplicationPrivate::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;
- if (!qt_nograb() && popupGrabOk) { // grabbing not disabled
- Display *dpy = X11->display;
- if (popup->geometry().contains(QPoint(mouseGlobalXPos, mouseGlobalYPos))
- || popup->testAttribute(Qt::WA_NoMouseReplay)) {
- // mouse release event or inside
- replayPopupMouseEvent = false;
- } else { // mouse press event
- mouseButtonPressTime -= 10000; // avoid double click
- replayPopupMouseEvent = true;
- }
- // transfer grab back to mouse grabber if any, otherwise release the grab
- if (QWidgetPrivate::mouseGrabber != 0)
- QWidgetPrivate::mouseGrabber->grabMouse();
- else
- XUngrabPointer(dpy, X11->time);
-
- // transfer grab back to keyboard grabber if any, otherwise release the grab
- if (QWidgetPrivate::keyboardGrabber != 0)
- QWidgetPrivate::keyboardGrabber->grabKeyboard();
- else
- XUngrabKeyboard(dpy, X11->time);
-
- XFlush(dpy);
- }
- 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);
-
- // regrab the keyboard and mouse in case 'popup' lost the grab
- if (QApplicationPrivate::popupWidgets->count() == 1 && !qt_nograb()){ // grab mouse/keyboard
- Display *dpy = X11->display;
- Q_ASSERT(aw->testAttribute(Qt::WA_WState_Created));
- int r = XGrabKeyboard(dpy, aw->effectiveWinId(), false,
- GrabModeAsync, GrabModeAsync, X11->time);
- if ((popupGrabOk = (r == GrabSuccess))) {
- r = XGrabPointer(dpy, aw->effectiveWinId(), true,
- (ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
- | EnterWindowMask | LeaveWindowMask | PointerMotionMask),
- GrabModeAsync, GrabModeAsync, XNone, XNone, X11->time);
- if (!(popupGrabOk = (r == GrabSuccess))) {
- // transfer grab back to keyboard grabber
- if (QWidgetPrivate::keyboardGrabber != 0)
- QWidgetPrivate::keyboardGrabber->grabKeyboard();
- else
- XUngrabKeyboard(dpy, X11->time);
- }
- }
- }
- }
-}
-
-/*****************************************************************************
- Event translation; translates X11 events to Qt events
- *****************************************************************************/
-
-//
-// Mouse event translation
-//
-// Xlib doesn't give mouse double click events, so we generate them by
-// comparing window, time and position between two mouse press events.
-//
-
-static Qt::MouseButtons translateMouseButtons(int s)
-{
- Qt::MouseButtons ret = 0;
- if (s & Button1Mask)
- ret |= Qt::LeftButton;
- if (s & Button2Mask)
- ret |= Qt::MidButton;
- if (s & Button3Mask)
- ret |= Qt::RightButton;
- return ret;
-}
-
-Qt::KeyboardModifiers QX11Data::translateModifiers(int s)
-{
- Qt::KeyboardModifiers ret = 0;
- if (s & ShiftMask)
- ret |= Qt::ShiftModifier;
- if (s & ControlMask)
- ret |= Qt::ControlModifier;
- if (s & qt_alt_mask)
- ret |= Qt::AltModifier;
- if (s & qt_meta_mask)
- ret |= Qt::MetaModifier;
- if (s & qt_mode_switch_mask)
- ret |= Qt::GroupSwitchModifier;
- return ret;
-}
-
-bool QETWidget::translateMouseEvent(const XEvent *event)
-{
- if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
- Q_ASSERT(internalWinId());
-
- Q_D(QWidget);
- QEvent::Type type; // event parameters
- QPoint pos;
- QPoint globalPos;
- Qt::MouseButton button = Qt::NoButton;
- Qt::MouseButtons buttons;
- Qt::KeyboardModifiers modifiers;
- XEvent nextEvent;
-
- if (qt_sm_blockUserInput) // block user interaction during session management
- return true;
-
- if (event->type == MotionNotify) { // mouse move
- if (event->xmotion.root != RootWindow(X11->display, x11Info().screen()) &&
- ! qt_xdnd_dragging)
- return false;
-
- XMotionEvent lastMotion = event->xmotion;
- while(XPending(X11->display)) { // compress mouse moves
- XNextEvent(X11->display, &nextEvent);
- if (nextEvent.type == ConfigureNotify
- || nextEvent.type == PropertyNotify
- || nextEvent.type == Expose
- || nextEvent.type == GraphicsExpose
- || nextEvent.type == NoExpose
- || nextEvent.type == KeymapNotify
- || ((nextEvent.type == EnterNotify || nextEvent.type == LeaveNotify)
- && qt_button_down == this)
- || (nextEvent.type == ClientMessage
- && (nextEvent.xclient.message_type == ATOM(_QT_SCROLL_DONE) ||
- (nextEvent.xclient.message_type == ATOM(WM_PROTOCOLS) &&
- (Atom)nextEvent.xclient.data.l[0] == ATOM(_NET_WM_SYNC_REQUEST))))) {
- qApp->x11ProcessEvent(&nextEvent);
- continue;
- } else if (nextEvent.type != MotionNotify ||
- nextEvent.xmotion.window != event->xmotion.window ||
- nextEvent.xmotion.state != event->xmotion.state) {
- XPutBackEvent(X11->display, &nextEvent);
- break;
- }
- if (!qt_x11EventFilter(&nextEvent)
- && !x11Event(&nextEvent)) // send event through filter
- lastMotion = nextEvent.xmotion;
- else
- break;
- }
- type = QEvent::MouseMove;
- pos.rx() = lastMotion.x;
- pos.ry() = lastMotion.y;
- pos = d->mapFromWS(pos);
- globalPos.rx() = lastMotion.x_root;
- globalPos.ry() = lastMotion.y_root;
- buttons = translateMouseButtons(lastMotion.state);
- modifiers = X11->translateModifiers(lastMotion.state);
- if (qt_button_down && !buttons)
- qt_button_down = 0;
- } else if (event->type == EnterNotify || event->type == LeaveNotify) {
- XEvent *xevent = (XEvent *)event;
- //unsigned int xstate = event->xcrossing.state;
- type = QEvent::MouseMove;
- pos.rx() = xevent->xcrossing.x;
- pos.ry() = xevent->xcrossing.y;
- pos = d->mapFromWS(pos);
- globalPos.rx() = xevent->xcrossing.x_root;
- globalPos.ry() = xevent->xcrossing.y_root;
- buttons = translateMouseButtons(xevent->xcrossing.state);
- modifiers = X11->translateModifiers(xevent->xcrossing.state);
- if (qt_button_down && !buttons)
- qt_button_down = 0;
- if (qt_button_down)
- return true;
- } else { // button press or release
- pos.rx() = event->xbutton.x;
- pos.ry() = event->xbutton.y;
- pos = d->mapFromWS(pos);
- globalPos.rx() = event->xbutton.x_root;
- globalPos.ry() = event->xbutton.y_root;
- buttons = translateMouseButtons(event->xbutton.state);
- modifiers = X11->translateModifiers(event->xbutton.state);
- switch (event->xbutton.button) {
- case Button1: button = Qt::LeftButton; break;
- case Button2: button = Qt::MidButton; break;
- case Button3: button = Qt::RightButton; break;
- case Button4:
- case Button5:
- case 6:
- case 7:
- // the fancy mouse wheel.
-
- // We are only interested in ButtonPress.
- if (event->type == ButtonPress){
- // compress wheel events (the X Server will simply
- // send a button press for each single notch,
- // regardless whether the application can catch up
- // or not)
- int delta = 1;
- XEvent xevent;
- while (XCheckTypedWindowEvent(X11->display, effectiveWinId(), ButtonPress, &xevent)){
- if (xevent.xbutton.button != event->xbutton.button){
- XPutBackEvent(X11->display, &xevent);
- break;
- }
- delta++;
- }
-
- // the delta is defined as multiples of
- // WHEEL_DELTA, which is set to 120. Future wheels
- // may offer a finer-resolution. A positive delta
- // indicates forward rotation, a negative one
- // backward rotation respectively.
- int btn = event->xbutton.button;
- delta *= 120 * ((btn == Button4 || btn == 6) ? 1 : -1);
- bool hor = (((btn == Button4 || btn == Button5) && (modifiers & Qt::AltModifier)) ||
- (btn == 6 || btn == 7));
- translateWheelEvent(globalPos.x(), globalPos.y(), delta, buttons,
- modifiers, (hor) ? Qt::Horizontal: Qt::Vertical);
- }
- return true;
- case 8: button = Qt::XButton1; break;
- case 9: button = Qt::XButton2; break;
- }
- if (event->type == ButtonPress) { // mouse button pressed
- buttons |= button;
-#if defined(Q_OS_IRIX) && !defined(QT_NO_TABLET)
- QTabletDeviceDataList *tablets = qt_tablet_devices();
- for (int i = 0; i < tablets->size(); ++i) {
- QTabletDeviceData &tab = tablets->operator[](i);
- XEvent myEv;
- if (XCheckTypedEvent(X11->display, tab.xinput_button_press, &myEv)) {
- if (translateXinputEvent(&myEv, &tab)) {
- //Spontaneous event sent. Check if we need to continue.
- if (qt_tabletChokeMouse) {
- qt_tabletChokeMouse = false;
- return false;
- }
- }
- }
- }
-#endif
- if (!qt_button_down) {
- qt_button_down = childAt(pos); //magic for masked widgets
- if (!qt_button_down)
- qt_button_down = this;
- }
- if (mouseActWindow == event->xbutton.window &&
- mouseButtonPressed == button &&
- (long)event->xbutton.time -(long)mouseButtonPressTime
- < QApplication::doubleClickInterval() &&
- qAbs(event->xbutton.x - mouseXPos) < QT_GUI_DOUBLE_CLICK_RADIUS &&
- qAbs(event->xbutton.y - mouseYPos) < QT_GUI_DOUBLE_CLICK_RADIUS) {
- type = QEvent::MouseButtonDblClick;
- mouseButtonPressTime -= 2000; // no double-click next time
- } else {
- type = QEvent::MouseButtonPress;
- mouseButtonPressTime = event->xbutton.time;
- }
- mouseButtonPressed = button; // save event params for
- mouseXPos = event->xbutton.x; // future double click tests
- mouseYPos = event->xbutton.y;
- mouseGlobalXPos = globalPos.x();
- mouseGlobalYPos = globalPos.y();
- } else { // mouse button released
- buttons &= ~button;
-#if defined(Q_OS_IRIX) && !defined(QT_NO_TABLET)
- QTabletDeviceDataList *tablets = qt_tablet_devices();
- for (int i = 0; i < tablets->size(); ++i) {
- QTabletDeviceData &tab = tablets->operator[](i);
- XEvent myEv;
- if (XCheckTypedEvent(X11->display, tab.xinput_button_press, &myEv)) {
- if (translateXinputEvent(&myEv, &tab)) {
- //Spontaneous event sent. Check if we need to continue.
- if (qt_tabletChokeMouse) {
- qt_tabletChokeMouse = false;
- return false;
- }
- }
- }
- }
-#endif
- type = QEvent::MouseButtonRelease;
- }
- }
- mouseActWindow = effectiveWinId(); // save some event params
- mouseButtonState = buttons;
- if (type == 0) // don't send event
- return false;
-
- if (qApp->d_func()->inPopupMode()) { // in popup mode
- QWidget *activePopupWidget = qApp->activePopupWidget();
- QWidget *popup = qApp->activePopupWidget();
- if (popup != this) {
- if (event->type == LeaveNotify)
- return false;
- if ((windowType() == Qt::Popup) && rect().contains(pos) && 0)
- popup = this;
- else // send to last popup
- pos = popup->mapFromGlobal(globalPos);
- }
- bool releaseAfter = false;
- QWidget *popupChild = popup->childAt(pos);
-
- if (popup != qt_popup_down){
- qt_button_down = 0;
- qt_popup_down = 0;
- }
-
- switch (type) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonDblClick:
- qt_button_down = popupChild;
- qt_popup_down = popup;
- break;
- case QEvent::MouseButtonRelease:
- releaseAfter = true;
- break;
- default:
- break; // nothing for mouse move
- }
-
- int oldOpenPopupCount = openPopupCount;
-
- if (popup->isEnabled()) {
- // deliver event
- replayPopupMouseEvent = false;
- QWidget *receiver = popup;
- QPoint widgetPos = pos;
- if (qt_button_down)
- receiver = qt_button_down;
- else if (popupChild)
- receiver = popupChild;
- if (receiver != popup)
- widgetPos = receiver->mapFromGlobal(globalPos);
- QWidget *alien = childAt(mapFromGlobal(globalPos));
- QMouseEvent e(type, widgetPos, globalPos, button, buttons, modifiers);
- QApplicationPrivate::sendMouseEvent(receiver, &e, alien, this, &qt_button_down, qt_last_mouse_receiver);
- } else {
- // close disabled popups when a mouse button is pressed or released
- switch (type) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseButtonRelease:
- popup->close();
- break;
- default:
- break;
- }
- }
-
- if (qApp->activePopupWidget() != activePopupWidget
- && replayPopupMouseEvent) {
- // the active popup was closed, replay the mouse event
- if (!(windowType() == Qt::Popup)) {
-#if 1
- qt_button_down = 0;
-#else
- if (buttons == button)
- qt_button_down = this;
- QMouseEvent e(type, mapFromGlobal(globalPos), globalPos, button,
- buttons, modifiers);
- QApplication::sendSpontaneousEvent(this, &e);
-
- if (type == QEvent::MouseButtonPress
- && button == Qt::RightButton
- && (openPopupCount == oldOpenPopupCount)) {
- QContextMenuEvent e(QContextMenuEvent::Mouse, mapFromGlobal(globalPos),
- globalPos, modifiers);
- QApplication::sendSpontaneousEvent(this, &e);
- }
-#endif
- }
- replayPopupMouseEvent = false;
- } else if (type == QEvent::MouseButtonPress
- && button == Qt::RightButton
- && (openPopupCount == oldOpenPopupCount)) {
- QWidget *popupEvent = popup;
- if (qt_button_down)
- popupEvent = qt_button_down;
- else if(popupChild)
- popupEvent = popupChild;
- QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos, modifiers);
- QApplication::sendSpontaneousEvent(popupEvent, &e);
- }
-
- if (releaseAfter) {
- qt_button_down = 0;
- qt_popup_down = 0;
- }
- } else {
- QWidget *alienWidget = childAt(pos);
- QWidget *widget = QApplicationPrivate::pickMouseReceiver(this, globalPos, pos, type, buttons,
- qt_button_down, alienWidget);
- if (!widget) {
- if (type == QEvent::MouseButtonRelease)
- QApplicationPrivate::mouse_buttons &= ~button;
- return false; // don't send event
- }
-
- int oldOpenPopupCount = openPopupCount;
- QMouseEvent e(type, pos, globalPos, button, buttons, modifiers);
- QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down,
- qt_last_mouse_receiver);
- if (type == QEvent::MouseButtonPress
- && button == Qt::RightButton
- && (openPopupCount == oldOpenPopupCount)) {
- QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos, modifiers);
- QApplication::sendSpontaneousEvent(widget, &e);
- }
- }
- return true;
-}
-
-
-//
-// Wheel event translation
-//
-bool QETWidget::translateWheelEvent(int global_x, int global_y, int delta,
- Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers,
- Qt::Orientation orient)
-{
- const QPoint globalPos = QPoint(global_x, global_y);
- QPoint pos = mapFromGlobal(globalPos);
- QWidget *widget = childAt(pos);
- if (!widget)
- widget = this;
- else if (!widget->internalWinId())
- pos = widget->mapFromGlobal(globalPos);
-
-#ifdef ALIEN_DEBUG
- qDebug() << "QETWidget::translateWheelEvent: receiver:" << widget << "pos:" << pos;
-#endif
-
- // send the event to the widget or its ancestors
- {
- QWidget* popup = qApp->activePopupWidget();
- if (popup && window() != popup)
- popup->close();
-#ifndef QT_NO_WHEELEVENT
- QWheelEvent e(pos, globalPos, delta, buttons, modifiers, orient);
- if (QApplication::sendSpontaneousEvent(widget, &e))
-#endif
- return true;
- }
-
- // send the event to the widget that has the focus or its ancestors, if different
- if (widget != qApp->focusWidget() && (widget = qApp->focusWidget())) {
- if (widget && !widget->internalWinId())
- pos = widget->mapFromGlobal(globalPos);
- QWidget* popup = qApp->activePopupWidget();
- if (popup && widget != popup)
- popup->hide();
-#ifndef QT_NO_WHEELEVENT
- QWheelEvent e(pos, globalPos, delta, buttons, modifiers, orient);
- if (QApplication::sendSpontaneousEvent(widget, &e))
-#endif
- return true;
- }
- return false;
-}
-
-
-//
-// XInput Translation Event
-//
-#if !defined (QT_NO_TABLET)
-
-#if !defined (Q_OS_IRIX)
-void fetchWacomToolId(int &deviceType, qint64 &serialId)
-{
- if (ptrWacomConfigInit == 0) // we actually have the lib
- return;
- WACOMCONFIG *config = ptrWacomConfigInit(X11->display, 0);
- if (config == 0)
- return;
- WACOMDEVICE *device = ptrWacomConfigOpenDevice (config, wacomDeviceName()->constData());
- if (device == 0)
- return;
- unsigned keys[1];
- int serialInt;
- ptrWacomConfigGetRawParam (device, XWACOM_PARAM_TOOLSERIAL, &serialInt, 1, keys);
- serialId = serialInt;
- int toolId;
- ptrWacomConfigGetRawParam (device, XWACOM_PARAM_TOOLID, &toolId, 1, keys);
- switch(toolId) {
- case 0x007: /* Mouse 4D and 2D */
- case 0x017: /* Intuos3 2D Mouse */
- case 0x094:
- case 0x09c:
- deviceType = QTabletEvent::FourDMouse;
- break;
- case 0x096: /* Lens cursor */
- case 0x097: /* Intuos3 Lens cursor */
- deviceType = QTabletEvent::Puck;
- break;
- case 0x0fa:
- case 0x81b: /* Intuos3 Classic Pen Eraser */
- case 0x82a: /* Eraser */
- case 0x82b: /* Intuos3 Grip Pen Eraser */
- case 0x85a:
- case 0x91a:
- case 0x91b: /* Intuos3 Airbrush Eraser */
- case 0xd1a:
- deviceType = QTabletEvent::XFreeEraser;
- break;
- case 0x112:
- case 0x912:
- case 0x913: /* Intuos3 Airbrush */
- case 0xd12:
- deviceType = QTabletEvent::Airbrush;
- break;
- case 0x012:
- case 0x022:
- case 0x032:
- case 0x801: /* Intuos3 Inking pen */
- case 0x812: /* Inking pen */
- case 0x813: /* Intuos3 Classic Pen */
- case 0x822: /* Pen */
- case 0x823: /* Intuos3 Grip Pen */
- case 0x832: /* Stroke pen */
- case 0x842:
- case 0x852:
- case 0x885: /* Intuos3 Marker Pen */
- default: /* Unknown tool */
- deviceType = QTabletEvent::Stylus;
- }
-
- /* Close device and return */
- ptrWacomConfigCloseDevice (device);
- ptrWacomConfigTerm(config);
-}
-#endif
-
-struct qt_tablet_motion_data
-{
- bool filterByWidget;
- const QWidget *widget;
- const QWidget *etWidget;
- int tabletMotionType;
- bool error; // found a reason to stop searching
-};
-
-static Bool qt_mouseMotion_scanner(Display *, XEvent *event, XPointer arg)
-{
- qt_tablet_motion_data *data = (qt_tablet_motion_data *) arg;
- if (data->error)
- return false;
-
- if (event->type == MotionNotify)
- return true;
-
- data->error = event->type != data->tabletMotionType; // we stop compression when another event gets in between.
- return false;
-}
-
-static Bool qt_tabletMotion_scanner(Display *, XEvent *event, XPointer arg)
-{
- qt_tablet_motion_data *data = (qt_tablet_motion_data *) arg;
- if (data->error)
- return false;
- if (event->type == data->tabletMotionType) {
- const XDeviceMotionEvent *const motion = reinterpret_cast<const XDeviceMotionEvent*>(event);
- if (data->filterByWidget) {
- const QPoint curr(motion->x, motion->y);
- const QWidget *w = data->etWidget;
- const QWidget *const child = w->childAt(curr);
- if (child) {
- w = child;
- }
- if (w == data->widget)
- return true;
- } else {
- return true;
- }
- }
-
- data->error = event->type != MotionNotify; // we stop compression when another event gets in between.
- return false;
-}
-
-bool QETWidget::translateXinputEvent(const XEvent *ev, QTabletDeviceData *tablet)
-{
-#if defined (Q_OS_IRIX)
- // Wacom has put defines in their wacom.h file so it would be quite wise
- // to use them, need to think of a decent way of not using
- // it when it doesn't exist...
- XDeviceState *s;
- XInputClass *iClass;
- XValuatorState *vs;
- int j;
-#endif
-
- Q_ASSERT(tablet != 0);
-
- QWidget *w = this;
- QPoint global,
- curr;
- QPointF hiRes;
- qreal pressure = 0;
- int xTilt = 0,
- yTilt = 0,
- z = 0;
- qreal tangentialPressure = 0;
- qreal rotation = 0;
- int deviceType = QTabletEvent::NoDevice;
- int pointerType = QTabletEvent::UnknownPointer;
- const XDeviceMotionEvent *motion = 0;
- XDeviceButtonEvent *button = 0;
- const XProximityNotifyEvent *proximity = 0;
- QEvent::Type t;
- Qt::KeyboardModifiers modifiers = 0;
-#if !defined (Q_OS_IRIX)
- XID device_id;
-#endif
-
- if (ev->type == tablet->xinput_motion) {
- motion = reinterpret_cast<const XDeviceMotionEvent*>(ev);
- t = QEvent::TabletMove;
- global = QPoint(motion->x_root, motion->y_root);
- curr = QPoint(motion->x, motion->y);
-#if !defined (Q_OS_IRIX)
- device_id = motion->deviceid;
-#endif
- } else if (ev->type == tablet->xinput_button_press || ev->type == tablet->xinput_button_release) {
- if (ev->type == tablet->xinput_button_press) {
- t = QEvent::TabletPress;
- } else {
- t = QEvent::TabletRelease;
- }
- button = (XDeviceButtonEvent*)ev;
-
- global = QPoint(button->x_root, button->y_root);
- curr = QPoint(button->x, button->y);
-#if !defined (Q_OS_IRIX)
- device_id = button->deviceid;
-#endif
- } else { // Proximity
- if (ev->type == tablet->xinput_proximity_in)
- t = QEvent::TabletEnterProximity;
- else
- t = QEvent::TabletLeaveProximity;
- proximity = (const XProximityNotifyEvent*)ev;
-#if !defined (Q_OS_IRIX)
- device_id = proximity->deviceid;
-#endif
- }
-
- qint64 uid = 0;
-#if defined (Q_OS_IRIX)
- QRect screenArea = qApp->desktop()->screenGeometry(this);
- s = XQueryDeviceState(X11->display, static_cast<XDevice *>(tablet->device));
- if (!s)
- return false;
- iClass = s->data;
- for (j = 0; j < s->num_classes; j++) {
- if (iClass->c_class == ValuatorClass) {
- vs = reinterpret_cast<XValuatorState *>(iClass);
- // figure out what device we have, based on bitmasking...
- if (vs->valuators[WAC_TRANSDUCER_I]
- & WAC_TRANSDUCER_PROX_MSK) {
- switch (vs->valuators[WAC_TRANSDUCER_I]
- & WAC_TRANSDUCER_MSK) {
- case WAC_PUCK_ID:
- pointerType = QTabletEvent::Puck;
- break;
- case WAC_STYLUS_ID:
- pointerType = QTabletEvent::Pen;
- break;
- case WAC_ERASER_ID:
- pointerType = QTabletEvent::Eraser;
- break;
- }
- // Get a Unique Id for the device, Wacom gives us this ability
- uid = vs->valuators[WAC_TRANSDUCER_I] & WAC_TRANSDUCER_ID_MSK;
- uid = (uid << 24) | vs->valuators[WAC_SERIAL_NUM_I];
- switch (WAC_TRANSDUCER_I & 0x0F0600) {
- case 0x080200:
- deviceType = QTabletEvent::Stylus;
- break;
- case 0x090200:
- deviceType = QTabletEvent::Airbrush;
- break;
- case 0x000400:
- deviceType = QTabletEvent::FourDMouse;
- break;
- case 0x000600:
- deviceType = QTabletEvent::Puck;
- break;
- case 0x080400:
- deviceType = QTabletEvent::RotationStylus;
- break;
- }
- } else {
- pointerType = QTabletEvent::UnknownPointer;
- deviceType = QTabletEvent::NoDevice;
- uid = 0;
- }
-
- if (!proximity) {
- // apparently Wacom needs a cast for the +/- values to make sense
- xTilt = short(vs->valuators[WAC_XTILT_I]);
- yTilt = short(vs->valuators[WAC_YTILT_I]);
- pressure = vs->valuators[WAC_PRESSURE_I];
- if (deviceType == QTabletEvent::FourDMouse
- || deviceType == QTabletEvent::RotationStylus) {
- rotation = vs->valuators[WAC_ROTATION_I] / 64.0;
- if (deviceType == QTabletEvent::FourDMouse)
- z = vs->valuators[WAC_ZCOORD_I];
- } else if (deviceType == QTabletEvent::Airbrush) {
- tangentialPressure = vs->valuators[WAC_TAN_PRESSURE_I]
- / qreal(tablet->maxTanPressure - tablet->minTanPressure);
- }
-
- hiRes = tablet->scaleCoord(vs->valuators[WAC_XCOORD_I], vs->valuators[WAC_YCOORD_I],
- screenArea.x(), screenArea.width(),
- screenArea.y(), screenArea.height());
- }
- break;
- }
- iClass = reinterpret_cast<XInputClass*>(reinterpret_cast<char*>(iClass) + iClass->length);
- }
- XFreeDeviceState(s);
-#else
- QTabletDeviceDataList *tablet_list = qt_tablet_devices();
- for (int i = 0; i < tablet_list->size(); ++i) {
- const QTabletDeviceData &t = tablet_list->at(i);
- if (device_id == static_cast<XDevice *>(t.device)->device_id) {
- deviceType = t.deviceType;
- if (t.deviceType == QTabletEvent::XFreeEraser) {
- deviceType = QTabletEvent::Stylus;
- pointerType = QTabletEvent::Eraser;
- } else if (t.deviceType == QTabletEvent::Stylus) {
- pointerType = QTabletEvent::Pen;
- }
- break;
- }
- }
-
- fetchWacomToolId(deviceType, uid);
-
- QRect screenArea = qApp->desktop()->rect();
- if (motion) {
- xTilt = (short) motion->axis_data[3];
- yTilt = (short) motion->axis_data[4];
- rotation = ((short) motion->axis_data[5]) / 64.0;
- pressure = (short) motion->axis_data[2];
- modifiers = X11->translateModifiers(motion->state);
- hiRes = tablet->scaleCoord(motion->axis_data[0], motion->axis_data[1],
- screenArea.x(), screenArea.width(),
- screenArea.y(), screenArea.height());
- } else if (button) {
- xTilt = (short) button->axis_data[3];
- yTilt = (short) button->axis_data[4];
- rotation = ((short) button->axis_data[5]) / 64.0;
- pressure = (short) button->axis_data[2];
- modifiers = X11->translateModifiers(button->state);
- hiRes = tablet->scaleCoord(button->axis_data[0], button->axis_data[1],
- screenArea.x(), screenArea.width(),
- screenArea.y(), screenArea.height());
- } else if (proximity) {
- pressure = 0;
- modifiers = 0;
- }
- if (deviceType == QTabletEvent::Airbrush) {
- tangentialPressure = rotation;
- rotation = 0.;
- }
-#endif
-
- if (tablet->widgetToGetPress) {
- w = tablet->widgetToGetPress;
- } else {
- QWidget *child = w->childAt(curr);
- if (child)
- w = child;
- }
- curr = w->mapFromGlobal(global);
-
- if (t == QEvent::TabletPress) {
- tablet->widgetToGetPress = w;
- } else if (t == QEvent::TabletRelease && tablet->widgetToGetPress) {
- w = tablet->widgetToGetPress;
- curr = w->mapFromGlobal(global);
- tablet->widgetToGetPress = 0;
- }
-
- QTabletEvent e(t, curr, global, hiRes,
- deviceType, pointerType,
- qreal(pressure / qreal(tablet->maxPressure - tablet->minPressure)),
- xTilt, yTilt, tangentialPressure, rotation, z, modifiers, uid);
- if (proximity) {
- QApplication::sendSpontaneousEvent(qApp, &e);
- } else {
- QApplication::sendSpontaneousEvent(w, &e);
- const bool accepted = e.isAccepted();
- if (!accepted && ev->type == tablet->xinput_motion) {
- // If the widget does not accept tablet events, we drop the next ones from the event queue
- // for this widget so it is not overloaded with the numerous tablet events.
- qt_tablet_motion_data tabletMotionData;
- tabletMotionData.tabletMotionType = tablet->xinput_motion;
- tabletMotionData.widget = w;
- tabletMotionData.etWidget = this;
- // if nothing is pressed, the events are filtered by position
- tabletMotionData.filterByWidget = (tablet->widgetToGetPress == 0);
-
- bool reinsertMouseEvent = false;
- XEvent mouseMotionEvent;
- while (true) {
- // Find first mouse event since we expect them in pairs inside Qt
- tabletMotionData.error =false;
- if (XCheckIfEvent(X11->display, &mouseMotionEvent, &qt_mouseMotion_scanner, (XPointer) &tabletMotionData)) {
- reinsertMouseEvent = true;
- } else {
- break;
- }
-
- // Now discard any duplicate tablet events.
- tabletMotionData.error = false;
- XEvent dummy;
- while (XCheckIfEvent(X11->display, &dummy, &qt_tabletMotion_scanner, (XPointer) &tabletMotionData)) {
- // just discard the event
- }
- }
-
- if (reinsertMouseEvent) {
- XPutBackEvent(X11->display, &mouseMotionEvent);
- }
- }
- }
- return true;
-}
-#endif
-
-bool QETWidget::translatePropertyEvent(const XEvent *event)
-{
- Q_D(QWidget);
- if (!isWindow()) return true;
-
- Atom ret;
- int format, e;
- unsigned char *data = 0;
- unsigned long nitems, after;
-
- if (event->xproperty.atom == ATOM(_KDE_NET_WM_FRAME_STRUT)) {
- this->data->fstrut_dirty = 1;
-
- if (event->xproperty.state == PropertyNewValue) {
- e = XGetWindowProperty(X11->display, event->xproperty.window, ATOM(_KDE_NET_WM_FRAME_STRUT),
- 0, 4, // struts are 4 longs
- False, XA_CARDINAL, &ret, &format, &nitems, &after, &data);
-
- if (e == Success && ret == XA_CARDINAL &&
- format == 32 && nitems == 4) {
- long *strut = (long *) data;
- d->topData()->frameStrut.setCoords(strut[0], strut[2], strut[1], strut[3]);
- this->data->fstrut_dirty = 0;
- }
- }
- } else if (event->xproperty.atom == ATOM(_NET_WM_STATE)) {
- bool max = false;
- bool full = false;
- Qt::WindowStates oldState = Qt::WindowStates(this->data->window_state);
-
- if (event->xproperty.state == PropertyNewValue) {
- // using length of 1024 should be safe for all current and
- // possible NET states...
- e = XGetWindowProperty(X11->display, event->xproperty.window, ATOM(_NET_WM_STATE), 0, 1024,
- False, XA_ATOM, &ret, &format, &nitems, &after, &data);
-
- if (e == Success && ret == XA_ATOM && format == 32 && nitems > 0) {
- Atom *states = (Atom *) data;
-
- unsigned long i;
- uint maximized = 0;
- for (i = 0; i < nitems; i++) {
- if (states[i] == ATOM(_NET_WM_STATE_MAXIMIZED_VERT))
- maximized |= 1;
- else if (states[i] == ATOM(_NET_WM_STATE_MAXIMIZED_HORZ))
- maximized |= 2;
- else if (states[i] == ATOM(_NET_WM_STATE_FULLSCREEN))
- full = true;
- }
- if (maximized == 3) {
- // only set maximized if both horizontal and vertical properties are set
- max = true;
- }
- }
- }
-
- bool send_event = false;
-
- if (X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_VERT))
- && X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ))) {
- if (max && !isMaximized()) {
- this->data->window_state = this->data->window_state | Qt::WindowMaximized;
- send_event = true;
- } else if (!max && isMaximized()) {
- this->data->window_state &= ~Qt::WindowMaximized;
- send_event = true;
- }
- }
-
- if (X11->isSupportedByWM(ATOM(_NET_WM_STATE_FULLSCREEN))) {
- if (full && !isFullScreen()) {
- this->data->window_state = this->data->window_state | Qt::WindowFullScreen;
- send_event = true;
- } else if (!full && isFullScreen()) {
- this->data->window_state &= ~Qt::WindowFullScreen;
- send_event = true;
- }
- }
-
- if (send_event) {
- QWindowStateChangeEvent e(oldState);
- QApplication::sendSpontaneousEvent(this, &e);
- }
- } else if (event->xproperty.atom == ATOM(WM_STATE)) {
- // the widget frame strut should also be invalidated
- this->data->fstrut_dirty = 1;
-
- if (event->xproperty.state == PropertyDelete) {
- // the window manager has removed the WM State property,
- // so it is now in the withdrawn state (ICCCM 4.1.3.1) and
- // we are free to reuse this window
- d->topData()->parentWinId = 0;
- d->topData()->validWMState = 0;
- // map the window if we were waiting for a transition to
- // withdrawn
- if (X11->deferred_map.removeAll(this)) {
- doDeferredMap();
- } else if (isVisible()
- && !testAttribute(Qt::WA_Mapped)
- && !testAttribute(Qt::WA_OutsideWSRange)) {
- // so that show() will work again. As stated in the
- // ICCCM section 4.1.4: "Only the client can effect a
- // transition into or out of the Withdrawn state.",
- // but apparently this particular window manager
- // doesn't seem to care
- setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- setAttribute(Qt::WA_WState_Visible, false);
- }
- } else {
- // the window manager has changed the WM State property...
- // we are wanting to see if we are withdrawn so that we
- // can reuse this window...
- e = XGetWindowProperty(X11->display, internalWinId(), ATOM(WM_STATE), 0, 2, False,
- ATOM(WM_STATE), &ret, &format, &nitems, &after, &data);
-
- if (e == Success && ret == ATOM(WM_STATE) && format == 32 && nitems > 0) {
- long *state = (long *) data;
- switch (state[0]) {
- case WithdrawnState:
- // if we are in the withdrawn state, we are free
- // to reuse this window provided we remove the
- // WM_STATE property (ICCCM 4.1.3.1)
- XDeleteProperty(X11->display, internalWinId(), ATOM(WM_STATE));
-
- // set the parent id to zero, so that show() will
- // work again
- d->topData()->parentWinId = 0;
- d->topData()->validWMState = 0;
- // map the window if we were waiting for a
- // transition to withdrawn
- if (X11->deferred_map.removeAll(this)) {
- doDeferredMap();
- } else if (isVisible()
- && !testAttribute(Qt::WA_Mapped)
- && !testAttribute(Qt::WA_OutsideWSRange)) {
- // so that show() will work again. As stated
- // in the ICCCM section 4.1.4: "Only the
- // client can effect a transition into or out
- // of the Withdrawn state.", but apparently
- // this particular window manager doesn't seem
- // to care
- setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- setAttribute(Qt::WA_WState_Visible, false);
- }
- break;
-
- case IconicState:
- d->topData()->validWMState = 1;
- if (!isMinimized()) {
- // window was minimized
- this->data->window_state = this->data->window_state | Qt::WindowMinimized;
- QWindowStateChangeEvent e(Qt::WindowStates(this->data->window_state & ~Qt::WindowMinimized));
- QApplication::sendSpontaneousEvent(this, &e);
- }
- break;
-
- default:
- d->topData()->validWMState = 1;
- if (isMinimized()) {
- // window was un-minimized
- this->data->window_state &= ~Qt::WindowMinimized;
- QWindowStateChangeEvent e(Qt::WindowStates(this->data->window_state | Qt::WindowMinimized));
- QApplication::sendSpontaneousEvent(this, &e);
- }
- break;
- }
- }
- }
- } else if (event->xproperty.atom == ATOM(_NET_WM_WINDOW_OPACITY)) {
- // the window opacity was changed
- if (event->xproperty.state == PropertyNewValue) {
- e = XGetWindowProperty(event->xclient.display,
- event->xclient.window,
- ATOM(_NET_WM_WINDOW_OPACITY),
- 0, 1, False, XA_CARDINAL,
- &ret, &format, &nitems, &after, &data);
-
- if (e == Success && ret == XA_CARDINAL && format == 32 && nitems == 1
- && after == 0 && data) {
- ulong value = *(ulong*)(data);
- d->topData()->opacity = uint(value >> 24);
- }
- } else
- d->topData()->opacity = 255;
- }
-
- if (data)
- XFree(data);
-
- return true;
-}
-
-
-//
-// Paint event translation
-//
-// When receiving many expose events, we compress them (union of all expose
-// rectangles) into one event which is sent to the widget.
-
-struct PaintEventInfo {
- Window window;
-};
-
-#if defined(Q_C_CALLBACKS)
-extern "C" {
-#endif
-
-static Bool isPaintOrScrollDoneEvent(Display *, XEvent *ev, XPointer a)
-{
- PaintEventInfo *info = (PaintEventInfo *)a;
- if (ev->type == Expose || ev->type == GraphicsExpose
- || (ev->type == ClientMessage && ev->xclient.message_type == ATOM(_QT_SCROLL_DONE)))
- {
- if (ev->xexpose.window == info->window)
- return True;
- }
- return False;
-}
-
-#if defined(Q_C_CALLBACKS)
-}
-#endif
-
-
-
-static
-bool translateBySips(QWidget* that, QRect& paintRect)
-{
- int dx=0, dy=0;
- int sips=0;
- for (int i = 0; i < X11->sip_list.size(); ++i) {
- const QX11Data::ScrollInProgress &sip = X11->sip_list.at(i);
- if (sip.scrolled_widget == that) {
- if (sips) {
- dx += sip.dx;
- dy += sip.dy;
- }
- sips++;
- }
- }
- if (sips > 1) {
- paintRect.translate(dx, dy);
- return true;
- }
- return false;
-}
-
-void QETWidget::translatePaintEvent(const XEvent *event)
-{
- if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
- Q_ASSERT(internalWinId());
-
- Q_D(QWidget);
- QRect paintRect(event->xexpose.x, event->xexpose.y,
- event->xexpose.width, event->xexpose.height);
- XEvent xevent;
- PaintEventInfo info;
- info.window = internalWinId();
- translateBySips(this, paintRect);
- paintRect = d->mapFromWS(paintRect);
-
- QRegion paintRegion = paintRect;
-
- // WARNING: this is O(number_of_events * number_of_matching_events)
- while (XCheckIfEvent(X11->display,&xevent,isPaintOrScrollDoneEvent,
- (XPointer)&info) &&
- !qt_x11EventFilter(&xevent) &&
- !x11Event(&xevent)) // send event through filter
- {
- if (xevent.type == Expose || xevent.type == GraphicsExpose) {
- QRect exposure(xevent.xexpose.x,
- xevent.xexpose.y,
- xevent.xexpose.width,
- xevent.xexpose.height);
- translateBySips(this, exposure);
- exposure = d->mapFromWS(exposure);
- paintRegion |= exposure;
- } else {
- translateScrollDoneEvent(&xevent);
- }
- }
-
- if (!paintRegion.isEmpty() && !testAttribute(Qt::WA_WState_ConfigPending))
- d->syncBackingStore(paintRegion);
-}
-
-//
-// Scroll-done event translation.
-//
-
-bool QETWidget::translateScrollDoneEvent(const XEvent *event)
-{
- long id = event->xclient.data.l[0];
-
- // Remove any scroll-in-progress record for the given id.
- for (int i = 0; i < X11->sip_list.size(); ++i) {
- const QX11Data::ScrollInProgress &sip = X11->sip_list.at(i);
- if (sip.id == id) {
- X11->sip_list.removeAt(i);
- return true;
- }
- }
-
- return false;
-}
-
-//
-// ConfigureNotify (window move and resize) event translation
-
-bool QETWidget::translateConfigEvent(const XEvent *event)
-{
- Q_ASSERT((!isWindow() && !testAttribute(Qt::WA_NativeWindow)) ? internalWinId() : true);
-
- Q_D(QWidget);
- bool wasResize = testAttribute(Qt::WA_WState_ConfigPending); // set in QWidget::setGeometry_sys()
- setAttribute(Qt::WA_WState_ConfigPending, false);
-
- if (testAttribute(Qt::WA_OutsideWSRange)) {
- // discard events for windows that have a geometry X can't handle
- XEvent xevent;
- while (XCheckTypedWindowEvent(X11->display,internalWinId(), ConfigureNotify,&xevent) &&
- !qt_x11EventFilter(&xevent) &&
- !x11Event(&xevent)) // send event through filter
- ;
- return true;
- }
-
- const QSize oldSize = size();
-
- if (isWindow()) {
- QPoint newCPos(geometry().topLeft());
- QSize newSize(event->xconfigure.width, event->xconfigure.height);
-
- bool trust = isVisible()
- && (d->topData()->parentWinId == XNone ||
- d->topData()->parentWinId == QX11Info::appRootWindow());
- bool isCPos = false;
-
- if (event->xconfigure.send_event || trust) {
- // if a ConfigureNotify comes from a real sendevent request, we can
- // trust its values.
- newCPos.rx() = event->xconfigure.x + event->xconfigure.border_width;
- newCPos.ry() = event->xconfigure.y + event->xconfigure.border_width;
- isCPos = true;
- }
- if (isVisible())
- QApplication::syncX();
-
- if (d->extra->compress_events) {
- // ConfigureNotify compression for faster opaque resizing
- XEvent otherEvent;
- while (XCheckTypedWindowEvent(X11->display, internalWinId(), ConfigureNotify,
- &otherEvent)) {
- if (qt_x11EventFilter(&otherEvent))
- continue;
-
- if (x11Event(&otherEvent))
- continue;
-
- if (otherEvent.xconfigure.event != otherEvent.xconfigure.window)
- continue;
-
- newSize.setWidth(otherEvent.xconfigure.width);
- newSize.setHeight(otherEvent.xconfigure.height);
-
- if (otherEvent.xconfigure.send_event || trust) {
- newCPos.rx() = otherEvent.xconfigure.x +
- otherEvent.xconfigure.border_width;
- newCPos.ry() = otherEvent.xconfigure.y +
- otherEvent.xconfigure.border_width;
- isCPos = true;
- }
- }
-#ifndef QT_NO_XSYNC
- qt_sync_request_event_data sync_event;
- sync_event.window = internalWinId();
- for (XEvent ev;;) {
- if (!XCheckIfEvent(X11->display, &ev, &qt_sync_request_scanner, (XPointer)&sync_event))
- break;
- }
-#endif // QT_NO_XSYNC
- }
-
- if (!isCPos) {
- // we didn't get an updated position of the toplevel.
- // either we haven't moved or there is a bug in the window manager.
- // anyway, let's query the position to be certain.
- int x, y;
- Window child;
- XTranslateCoordinates(X11->display, internalWinId(),
- QApplication::desktop()->screen(d->xinfo.screen())->internalWinId(),
- 0, 0, &x, &y, &child);
- newCPos.rx() = x;
- newCPos.ry() = y;
- }
-
- QRect cr (geometry());
- if (newCPos != cr.topLeft()) { // compare with cpos (exluding frame)
- QPoint oldPos = geometry().topLeft();
- cr.moveTopLeft(newCPos);
- data->crect = cr;
- if (isVisible()) {
- QMoveEvent e(newCPos, oldPos); // pos (including frame), not cpos
- QApplication::sendSpontaneousEvent(this, &e);
- } else {
- setAttribute(Qt::WA_PendingMoveEvent, true);
- }
- }
- if (newSize != cr.size()) { // size changed
- cr.setSize(newSize);
- data->crect = cr;
-
- uint old_state = data->window_state;
- if (!X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_VERT))
- && !X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ)))
- data->window_state &= ~Qt::WindowMaximized;
- if (!X11->isSupportedByWM(ATOM(_NET_WM_STATE_FULLSCREEN)))
- data->window_state &= ~Qt::WindowFullScreen;
-
- if (old_state != data->window_state) {
- QWindowStateChangeEvent e((Qt::WindowStates) old_state);
- QApplication::sendEvent(this, &e);
- }
-
- if (!isVisible())
- setAttribute(Qt::WA_PendingResizeEvent, true);
- wasResize = true;
- }
-
- } else {
- XEvent xevent;
- while (XCheckTypedWindowEvent(X11->display,internalWinId(), ConfigureNotify,&xevent) &&
- !qt_x11EventFilter(&xevent) &&
- !x11Event(&xevent)) // send event through filter
- ;
- }
-
- if (wasResize) {
- if (isVisible() && data->crect.size() != oldSize) {
- Q_ASSERT(d->extra->topextra);
- QWidgetBackingStore *bs = d->extra->topextra->backingStore.data();
- const bool hasStaticContents = bs && bs->hasStaticContents();
- // If we have a backing store with static contents, we have to disable the top-level
- // resize optimization in order to get invalidated regions for resized widgets.
- // The optimization discards all invalidateBuffer() calls since we're going to
- // repaint everything anyways, but that's not the case with static contents.
- if (!hasStaticContents)
- d->extra->topextra->inTopLevelResize = true;
- QResizeEvent e(data->crect.size(), oldSize);
- QApplication::sendSpontaneousEvent(this, &e);
- }
-
- const bool waitingForMapNotify = d->extra->topextra && d->extra->topextra->waitingForMapNotify;
- if (!waitingForMapNotify) {
- if (d->paintOnScreen()) {
- QRegion updateRegion(rect());
- if (testAttribute(Qt::WA_StaticContents))
- updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
- d->syncBackingStore(updateRegion);
- } else {
- d->syncBackingStore();
- }
- }
-
- if (d->extra && d->extra->topextra)
- d->extra->topextra->inTopLevelResize = false;
- }
-#ifndef QT_NO_XSYNC
- if (QTLWExtra *tlwExtra = d->maybeTopData()) {
- if (tlwExtra->newCounterValueLo != 0 || tlwExtra->newCounterValueHi != 0) {
- XSyncValue value;
- XSyncIntsToValue(&value,
- tlwExtra->newCounterValueLo,
- tlwExtra->newCounterValueHi);
-
- XSyncSetCounter(X11->display, tlwExtra->syncUpdateCounter, value);
- tlwExtra->newCounterValueHi = 0;
- tlwExtra->newCounterValueLo = 0;
- }
- }
-#endif
- return true;
-}
-
-//
-// Close window event translation.
-//
-bool QETWidget::translateCloseEvent(const XEvent *)
-{
- Q_D(QWidget);
- return d->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-}
-
-
-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 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_AnimateMenu:
- if (enable) QApplicationPrivate::fade_menu = false;
- 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:
- if (enable) QApplicationPrivate::fade_tooltip = false;
- 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;
- }
-}
-
-/*****************************************************************************
- Session management support
- *****************************************************************************/
-
-#ifndef QT_NO_SESSIONMANAGER
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <X11/SM/SMlib.h>
-QT_END_INCLUDE_NAMESPACE
-
-class QSessionManagerPrivate : public QObjectPrivate
-{
-public:
- QSessionManagerPrivate(QSessionManager* mgr, QString& id, QString& key)
- : QObjectPrivate(), sm(mgr), sessionId(id), sessionKey(key),
- restartHint(QSessionManager::RestartIfRunning), eventLoop(0) {}
- QSessionManager* sm;
- QStringList restartCommand;
- QStringList discardCommand;
- QString& sessionId;
- QString& sessionKey;
- QSessionManager::RestartHint restartHint;
- QEventLoop *eventLoop;
-};
-
-class QSmSocketReceiver : public QObject
-{
- Q_OBJECT
-public:
- QSmSocketReceiver(int socket)
- {
- QSocketNotifier* sn = new QSocketNotifier(socket, QSocketNotifier::Read, this);
- connect(sn, SIGNAL(activated(int)), this, SLOT(socketActivated(int)));
- }
-
-public slots:
- void socketActivated(int);
-};
-
-
-static SmcConn smcConnection = 0;
-static bool sm_interactionActive;
-static bool sm_smActive;
-static int sm_interactStyle;
-static int sm_saveType;
-static bool sm_cancel;
-// static bool sm_waitingForPhase2; ### never used?!?
-static bool sm_waitingForInteraction;
-static bool sm_isshutdown;
-// static bool sm_shouldbefast; ### never used?!?
-static bool sm_phase2;
-static bool sm_in_phase2;
-
-static QSmSocketReceiver* sm_receiver = 0;
-
-static void resetSmState();
-static void sm_setProperty(const char* name, const char* type,
- int num_vals, SmPropValue* vals);
-static void sm_saveYourselfCallback(SmcConn smcConn, SmPointer clientData,
- int saveType, Bool shutdown , int interactStyle, Bool fast);
-static void sm_saveYourselfPhase2Callback(SmcConn smcConn, SmPointer clientData) ;
-static void sm_dieCallback(SmcConn smcConn, SmPointer clientData) ;
-static void sm_shutdownCancelledCallback(SmcConn smcConn, SmPointer clientData);
-static void sm_saveCompleteCallback(SmcConn smcConn, SmPointer clientData);
-static void sm_interactCallback(SmcConn smcConn, SmPointer clientData);
-static void sm_performSaveYourself(QSessionManagerPrivate*);
-
-static void resetSmState()
-{
-// sm_waitingForPhase2 = false; ### never used?!?
- sm_waitingForInteraction = false;
- sm_interactionActive = false;
- sm_interactStyle = SmInteractStyleNone;
- sm_smActive = false;
- qt_sm_blockUserInput = false;
- sm_isshutdown = false;
-// sm_shouldbefast = false; ### never used?!?
- sm_phase2 = false;
- sm_in_phase2 = false;
-}
-
-
-// theoretically it's possible to set several properties at once. For
-// simplicity, however, we do just one property at a time
-static void sm_setProperty(const char* name, const char* type,
- int num_vals, SmPropValue* vals)
-{
- if (num_vals) {
- SmProp prop;
- prop.name = (char*)name;
- prop.type = (char*)type;
- prop.num_vals = num_vals;
- prop.vals = vals;
-
- SmProp* props[1];
- props[0] = &prop;
- SmcSetProperties(smcConnection, 1, props);
- }
- else {
- char* names[1];
- names[0] = (char*) name;
- SmcDeleteProperties(smcConnection, 1, names);
- }
-}
-
-static void sm_setProperty(const QString& name, const QString& value)
-{
- QByteArray v = value.toUtf8();
- SmPropValue prop;
- prop.length = v.length();
- prop.value = (SmPointer) v.constData();
- sm_setProperty(name.toLatin1().data(), SmARRAY8, 1, &prop);
-}
-
-static void sm_setProperty(const QString& name, const QStringList& value)
-{
- SmPropValue *prop = new SmPropValue[value.count()];
- int count = 0;
- QList<QByteArray> vl;
- for (QStringList::ConstIterator it = value.begin(); it != value.end(); ++it) {
- prop[count].length = (*it).length();
- vl.append((*it).toUtf8());
- prop[count].value = (char*)vl.last().data();
- ++count;
- }
- sm_setProperty(name.toLatin1().data(), SmLISTofARRAY8, count, prop);
- delete [] prop;
-}
-
-
-// workaround for broken libsm, see below
-struct QT_smcConn {
- unsigned int save_yourself_in_progress : 1;
- unsigned int shutdown_in_progress : 1;
-};
-
-static void sm_saveYourselfCallback(SmcConn smcConn, SmPointer clientData,
- int saveType, Bool shutdown , int interactStyle, Bool /*fast*/)
-{
- if (smcConn != smcConnection)
- return;
- sm_cancel = false;
- sm_smActive = true;
- sm_isshutdown = shutdown;
- sm_saveType = saveType;
- sm_interactStyle = interactStyle;
-// sm_shouldbefast = fast; ### never used?!?
-
- // ugly workaround for broken libSM. libSM should do that _before_
- // actually invoking the callback in sm_process.c
- ((QT_smcConn*)smcConn)->save_yourself_in_progress = true;
- if (sm_isshutdown)
- ((QT_smcConn*)smcConn)->shutdown_in_progress = true;
-
- sm_performSaveYourself((QSessionManagerPrivate*) clientData);
- if (!sm_isshutdown) // we cannot expect a confirmation message in that case
- resetSmState();
-}
-
-static void sm_performSaveYourself(QSessionManagerPrivate* smd)
-{
- if (sm_isshutdown)
- qt_sm_blockUserInput = true;
-
- QSessionManager* sm = smd->sm;
-
- // generate a new session key
- timeval tv;
- gettimeofday(&tv, 0);
- smd->sessionKey = QString::number(qulonglong(tv.tv_sec)) + QLatin1Char('_') + QString::number(qulonglong(tv.tv_usec));
-
- QStringList arguments = qApp->arguments();
- QString argument0 = arguments.isEmpty() ? qApp->applicationFilePath() : arguments.at(0);
-
- // tell the session manager about our program in best POSIX style
- sm_setProperty(QString::fromLatin1(SmProgram), argument0);
- // tell the session manager about our user as well.
- struct passwd *entryPtr = 0;
-#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) && (_POSIX_THREAD_SAFE_FUNCTIONS - 0 > 0)
- QVarLengthArray<char, 1024> buf(qMax<long>(sysconf(_SC_GETPW_R_SIZE_MAX), 1024L));
- struct passwd entry;
- while (getpwuid_r(geteuid(), &entry, buf.data(), buf.size(), &entryPtr) == ERANGE) {
- if (buf.size() >= 32768) {
- // too big already, fail
- static char badusername[] = "";
- entryPtr = &entry;
- entry.pw_name = badusername;
- break;
- }
-
- // retry with a bigger buffer
- buf.resize(buf.size() * 2);
- }
-#else
- entryPtr = getpwuid(geteuid());
-#endif
- if (entryPtr)
- sm_setProperty(QString::fromLatin1(SmUserID), QString::fromLatin1(entryPtr->pw_name));
-
- // generate a restart and discard command that makes sense
- QStringList restart;
- restart << argument0 << QLatin1String("-session")
- << smd->sessionId + QLatin1Char('_') + smd->sessionKey;
- if (qstricmp(appName, QX11Info::appClass()) != 0)
- restart << QLatin1String("-name") << qAppName();
- sm->setRestartCommand(restart);
- QStringList discard;
- sm->setDiscardCommand(discard);
-
- switch (sm_saveType) {
- case SmSaveBoth:
- qApp->commitData(*sm);
- if (sm_isshutdown && sm_cancel)
- break; // we cancelled the shutdown, no need to save state
- // fall through
- case SmSaveLocal:
- qApp->saveState(*sm);
- break;
- case SmSaveGlobal:
- qApp->commitData(*sm);
- break;
- default:
- break;
- }
-
- if (sm_phase2 && !sm_in_phase2) {
- SmcRequestSaveYourselfPhase2(smcConnection, sm_saveYourselfPhase2Callback, (SmPointer*) smd);
- qt_sm_blockUserInput = false;
- }
- else {
- // close eventual interaction monitors and cancel the
- // shutdown, if required. Note that we can only cancel when
- // performing a shutdown, it does not work for checkpoints
- if (sm_interactionActive) {
- SmcInteractDone(smcConnection, sm_isshutdown && sm_cancel);
- sm_interactionActive = false;
- }
- else if (sm_cancel && sm_isshutdown) {
- if (sm->allowsErrorInteraction()) {
- SmcInteractDone(smcConnection, True);
- sm_interactionActive = false;
- }
- }
-
- // set restart and discard command in session manager
- sm_setProperty(QString::fromLatin1(SmRestartCommand), sm->restartCommand());
- sm_setProperty(QString::fromLatin1(SmDiscardCommand), sm->discardCommand());
-
- // set the restart hint
- SmPropValue prop;
- prop.length = sizeof(int);
- int value = sm->restartHint();
- prop.value = (SmPointer) &value;
- sm_setProperty(SmRestartStyleHint, SmCARD8, 1, &prop);
-
- // we are done
- SmcSaveYourselfDone(smcConnection, !sm_cancel);
- }
-}
-
-static void sm_dieCallback(SmcConn smcConn, SmPointer /* clientData */)
-{
- if (smcConn != smcConnection)
- return;
- resetSmState();
- QEvent quitEvent(QEvent::Quit);
- QApplication::sendEvent(qApp, &quitEvent);
-}
-
-static void sm_shutdownCancelledCallback(SmcConn smcConn, SmPointer clientData)
-{
- if (smcConn != smcConnection)
- return;
- if (sm_waitingForInteraction)
- ((QSessionManagerPrivate *) clientData)->eventLoop->exit();
- resetSmState();
-}
-
-static void sm_saveCompleteCallback(SmcConn smcConn, SmPointer /*clientData */)
-{
- if (smcConn != smcConnection)
- return;
- resetSmState();
-}
-
-static void sm_interactCallback(SmcConn smcConn, SmPointer clientData)
-{
- if (smcConn != smcConnection)
- return;
- if (sm_waitingForInteraction)
- ((QSessionManagerPrivate *) clientData)->eventLoop->exit();
-}
-
-static void sm_saveYourselfPhase2Callback(SmcConn smcConn, SmPointer clientData)
-{
- if (smcConn != smcConnection)
- return;
- sm_in_phase2 = true;
- sm_performSaveYourself((QSessionManagerPrivate*) clientData);
-}
-
-
-void QSmSocketReceiver::socketActivated(int)
-{
- IceProcessMessages(SmcGetIceConnection(smcConnection), 0, 0);
-}
-
-
-#undef Bool
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qapplication_x11.moc"
-QT_END_INCLUDE_NAMESPACE
-
-QSessionManager::QSessionManager(QApplication * app, QString &id, QString& key)
- : QObject(*new QSessionManagerPrivate(this, id, key), app)
-{
- Q_D(QSessionManager);
- d->restartHint = RestartIfRunning;
-
- resetSmState();
- char cerror[256];
- char* myId = 0;
- QByteArray b_id = id.toLatin1();
- char* prevId = b_id.data();
-
- SmcCallbacks cb;
- cb.save_yourself.callback = sm_saveYourselfCallback;
- cb.save_yourself.client_data = (SmPointer) d;
- cb.die.callback = sm_dieCallback;
- cb.die.client_data = (SmPointer) d;
- cb.save_complete.callback = sm_saveCompleteCallback;
- cb.save_complete.client_data = (SmPointer) d;
- cb.shutdown_cancelled.callback = sm_shutdownCancelledCallback;
- cb.shutdown_cancelled.client_data = (SmPointer) d;
-
- // avoid showing a warning message below
- if (qgetenv("SESSION_MANAGER").isEmpty())
- return;
-
- smcConnection = SmcOpenConnection(0, 0, 1, 0,
- SmcSaveYourselfProcMask |
- SmcDieProcMask |
- SmcSaveCompleteProcMask |
- SmcShutdownCancelledProcMask,
- &cb,
- prevId,
- &myId,
- 256, cerror);
-
- id = QString::fromLatin1(myId);
- ::free(myId); // it was allocated by C
-
- QString error = QString::fromLocal8Bit(cerror);
- if (!smcConnection) {
- qWarning("Qt: Session management error: %s", qPrintable(error));
- }
- else {
- sm_receiver = new QSmSocketReceiver(IceConnectionNumber(SmcGetIceConnection(smcConnection)));
- }
-}
-
-QSessionManager::~QSessionManager()
-{
- if (smcConnection)
- SmcCloseConnection(smcConnection, 0, 0);
- smcConnection = 0;
- delete sm_receiver;
-}
-
-QString QSessionManager::sessionId() const
-{
- Q_D(const QSessionManager);
- return d->sessionId;
-}
-
-QString QSessionManager::sessionKey() const
-{
- Q_D(const QSessionManager);
- return d->sessionKey;
-}
-
-
-void* QSessionManager::handle() const
-{
- return (void*) smcConnection;
-}
-
-
-bool QSessionManager::allowsInteraction()
-{
- Q_D(QSessionManager);
- if (sm_interactionActive)
- return true;
-
- if (sm_waitingForInteraction)
- return false;
-
- if (sm_interactStyle == SmInteractStyleAny) {
- sm_waitingForInteraction = SmcInteractRequest(smcConnection, SmDialogNormal,
- sm_interactCallback, (SmPointer*) d);
- }
- if (sm_waitingForInteraction) {
- QEventLoop eventLoop;
- d->eventLoop = &eventLoop;
- (void) eventLoop.exec();
- d->eventLoop = 0;
-
- sm_waitingForInteraction = false;
- if (sm_smActive) { // not cancelled
- sm_interactionActive = true;
- qt_sm_blockUserInput = false;
- return true;
- }
- }
- return false;
-}
-
-bool QSessionManager::allowsErrorInteraction()
-{
- Q_D(QSessionManager);
- if (sm_interactionActive)
- return true;
-
- if (sm_waitingForInteraction)
- return false;
-
- if (sm_interactStyle == SmInteractStyleAny || sm_interactStyle == SmInteractStyleErrors) {
- sm_waitingForInteraction = SmcInteractRequest(smcConnection, SmDialogError,
- sm_interactCallback, (SmPointer*) d);
- }
- if (sm_waitingForInteraction) {
- QEventLoop eventLoop;
- d->eventLoop = &eventLoop;
- (void) eventLoop.exec();
- d->eventLoop = 0;
-
- sm_waitingForInteraction = false;
- if (sm_smActive) { // not cancelled
- sm_interactionActive = true;
- qt_sm_blockUserInput = false;
- return true;
- }
- }
- return false;
-}
-
-void QSessionManager::release()
-{
- if (sm_interactionActive) {
- SmcInteractDone(smcConnection, False);
- sm_interactionActive = false;
- if (sm_smActive && sm_isshutdown)
- qt_sm_blockUserInput = true;
- }
-}
-
-void QSessionManager::cancel()
-{
- sm_cancel = true;
-}
-
-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& name, const QString& value)
-{
- sm_setProperty(name, value);
-}
-
-void QSessionManager::setManagerProperty(const QString& name, const QStringList& value)
-{
- sm_setProperty(name, value);
-}
-
-bool QSessionManager::isPhase2() const
-{
- return sm_in_phase2;
-}
-
-void QSessionManager::requestPhase2()
-{
- sm_phase2 = true;
-}
-
-#endif // QT_NO_SESSIONMANAGER
-
-#if defined(QT_RX71_MULTITOUCH)
-
-static inline int testBit(const char *array, int bit)
-{
- return (array[bit/8] & (1<<(bit%8)));
-}
-
-static int openRX71Device(const QByteArray &deviceName)
-{
- int fd = open(deviceName, O_RDONLY | O_NONBLOCK);
- if (fd == -1) {
- fd = -errno;
- return fd;
- }
-
- // fetch the event type mask and check that the device reports absolute coordinates
- char eventTypeMask[(EV_MAX + sizeof(char) - 1) * sizeof(char) + 1];
- memset(eventTypeMask, 0, sizeof(eventTypeMask));
- if (ioctl(fd, EVIOCGBIT(0, sizeof(eventTypeMask)), eventTypeMask) < 0) {
- close(fd);
- return -1;
- }
- if (!testBit(eventTypeMask, EV_ABS)) {
- close(fd);
- return -1;
- }
-
- // make sure that we can get the absolute X and Y positions from the device
- char absMask[(ABS_MAX + sizeof(char) - 1) * sizeof(char) + 1];
- memset(absMask, 0, sizeof(absMask));
- if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absMask)), absMask) < 0) {
- close(fd);
- return -1;
- }
- if (!testBit(absMask, ABS_X) || !testBit(absMask, ABS_Y)) {
- close(fd);
- return -1;
- }
-
- return fd;
-}
-
-void QApplicationPrivate::initializeMultitouch_sys()
-{
- Q_Q(QApplication);
-
- QByteArray deviceName = QByteArray("/dev/input/event");
- int currentDeviceNumber = 0;
- for (;;) {
- int fd = openRX71Device(QByteArray(deviceName + QByteArray::number(currentDeviceNumber++)));
- if (fd == -ENOENT) {
- // no more devices
- break;
- }
- if (fd < 0) {
- // not a touch device
- continue;
- }
-
- struct input_absinfo abs_x, abs_y, abs_z;
- ioctl(fd, EVIOCGABS(ABS_X), &abs_x);
- ioctl(fd, EVIOCGABS(ABS_Y), &abs_y);
- ioctl(fd, EVIOCGABS(ABS_Z), &abs_z);
-
- int deviceNumber = allRX71TouchPoints.count();
-
- QSocketNotifier *socketNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, q);
- QObject::connect(socketNotifier, SIGNAL(activated(int)), q, SLOT(_q_readRX71MultiTouchEvents()));
-
- RX71TouchPointState touchPointState = {
- socketNotifier,
- QTouchEvent::TouchPoint(deviceNumber),
-
- abs_x.minimum, abs_x.maximum, q->desktop()->screenGeometry().width(),
- abs_y.minimum, abs_y.maximum, q->desktop()->screenGeometry().height(),
- abs_z.minimum, abs_z.maximum
- };
- allRX71TouchPoints.append(touchPointState);
- }
-
- hasRX71MultiTouch = allRX71TouchPoints.count() > 1;
- if (!hasRX71MultiTouch) {
- for (int i = 0; i < allRX71TouchPoints.count(); ++i) {
- QSocketNotifier *socketNotifier = allRX71TouchPoints.at(i).socketNotifier;
- close(socketNotifier->socket());
- delete socketNotifier;
- }
- allRX71TouchPoints.clear();
- }
-}
-
-void QApplicationPrivate::cleanupMultitouch_sys()
-{
- hasRX71MultiTouch = false;
- for (int i = 0; i < allRX71TouchPoints.count(); ++i) {
- QSocketNotifier *socketNotifier = allRX71TouchPoints.at(i).socketNotifier;
- close(socketNotifier->socket());
- delete socketNotifier;
- }
- allRX71TouchPoints.clear();
-}
-
-bool QApplicationPrivate::readRX71MultiTouchEvents(int deviceNumber)
-{
- RX71TouchPointState &touchPointState = allRX71TouchPoints[deviceNumber];
- QSocketNotifier *socketNotifier = touchPointState.socketNotifier;
- int fd = socketNotifier->socket();
-
- QTouchEvent::TouchPoint &touchPoint = touchPointState.touchPoint;
-
- bool down = touchPoint.state() != Qt::TouchPointReleased;
- if (down)
- touchPoint.setState(Qt::TouchPointStationary);
-
- bool changed = false;
- for (;;) {
- struct input_event inputEvent;
- int bytesRead = read(fd, &inputEvent, sizeof(inputEvent));
- if (bytesRead <= 0)
- break;
- if (bytesRead != sizeof(inputEvent)) {
- qWarning("Qt: INTERNAL ERROR: short read in readRX71MultiTouchEvents()");
- return false;
- }
-
- switch (inputEvent.type) {
- case EV_SYN:
- changed = true;
- switch (touchPoint.state()) {
- case Qt::TouchPointPressed:
- case Qt::TouchPointReleased:
- // make sure we don't compress pressed and releases with any other events
- return changed;
- default:
- break;
- }
- continue;
- case EV_KEY:
- case EV_ABS:
- break;
- default:
- qWarning("Qt: WARNING: unknown event type %d on multitouch device", inputEvent.type);
- continue;
- }
-
- QPointF screenPos = touchPoint.screenPos();
- switch (inputEvent.code) {
- case BTN_TOUCH:
- if (!down && inputEvent.value != 0)
- touchPoint.setState(Qt::TouchPointPressed);
- else if (down && inputEvent.value == 0)
- touchPoint.setState(Qt::TouchPointReleased);
- break;
- case ABS_TOOL_WIDTH:
- case ABS_VOLUME:
- case ABS_PRESSURE:
- // ignore for now
- break;
- case ABS_X:
- {
- qreal newValue = ((qreal(inputEvent.value - touchPointState.minX)
- / qreal(touchPointState.maxX - touchPointState.minX))
- * touchPointState.scaleX);
- screenPos.rx() = newValue;
- touchPoint.setScreenPos(screenPos);
- break;
- }
- case ABS_Y:
- {
- qreal newValue = ((qreal(inputEvent.value - touchPointState.minY)
- / qreal(touchPointState.maxY - touchPointState.minY))
- * touchPointState.scaleY);
- screenPos.ry() = newValue;
- touchPoint.setScreenPos(screenPos);
- break;
- }
- case ABS_Z:
- {
- // map Z (signal strength) to pressure for now
- qreal newValue = (qreal(inputEvent.value - touchPointState.minZ)
- / qreal(touchPointState.maxZ - touchPointState.minZ));
- touchPoint.setPressure(newValue);
- break;
- }
- default:
- qWarning("Qt: WARNING: unknown event code %d on multitouch device", inputEvent.code);
- continue;
- }
- }
-
- if (down && touchPoint.state() != Qt::TouchPointReleased)
- touchPoint.setState(changed ? Qt::TouchPointMoved : Qt::TouchPointStationary);
-
- return changed;
-}
-
-void QApplicationPrivate::_q_readRX71MultiTouchEvents()
-{
- // read touch events from all devices
- bool changed = false;
- for (int i = 0; i < allRX71TouchPoints.count(); ++i)
- changed = readRX71MultiTouchEvents(i) || changed;
- if (!changed)
- return;
-
- QList<QTouchEvent::TouchPoint> touchPoints;
- for (int i = 0; i < allRX71TouchPoints.count(); ++i)
- touchPoints.append(allRX71TouchPoints.at(i).touchPoint);
-
- translateRawTouchEvent(0, QTouchEvent::TouchScreen, touchPoints);
-}
-
-#else // !QT_RX71_MULTITOUCH
-
-void QApplicationPrivate::initializeMultitouch_sys()
-{ }
-void QApplicationPrivate::cleanupMultitouch_sys()
-{ }
-
-#endif // QT_RX71_MULTITOUCH
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qclipboard_x11.cpp b/src/gui/platforms/x11/qclipboard_x11.cpp
deleted file mode 100644
index d566c86e04..0000000000
--- a/src/gui/platforms/x11/qclipboard_x11.cpp
+++ /dev/null
@@ -1,1539 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-// #define QCLIPBOARD_DEBUG
-// #define QCLIPBOARD_DEBUG_VERBOSE
-
-#ifdef QCLIPBOARD_DEBUG
-# define DEBUG qDebug
-#else
-# define DEBUG if (false) qDebug
-#endif
-
-#ifdef QCLIPBOARD_DEBUG_VERBOSE
-# define VDEBUG qDebug
-#else
-# define VDEBUG if (false) qDebug
-#endif
-
-#include "qplatformdefs.h"
-
-#include "qclipboard.h"
-#include "qclipboard_p.h"
-
-#ifndef QT_NO_CLIPBOARD
-
-#include "qabstracteventdispatcher.h"
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qbitmap.h"
-#include "qiodevice.h"
-#include "qbuffer.h"
-#include "qtextcodec.h"
-#include "qlist.h"
-#include "qmap.h"
-#include "qapplication_p.h"
-#include "qevent.h"
-#include "qt_x11_p.h"
-#include "qx11info_x11.h"
-#include "qimagewriter.h"
-#include "qelapsedtimer.h"
-#include "qvariant.h"
-#include "qdnd_p.h"
-#include <private/qwidget_p.h>
-
-#ifndef QT_NO_XFIXES
-#include <X11/extensions/Xfixes.h>
-#endif // QT_NO_XFIXES
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- Internal QClipboard functions for X11.
- *****************************************************************************/
-
-static int clipboard_timeout = 5000; // 5s timeout on clipboard operations
-
-static QWidget * owner = 0;
-static QWidget *requestor = 0;
-static bool timer_event_clear = false;
-static int timer_id = 0;
-
-static int pending_timer_id = 0;
-static bool pending_clipboard_changed = false;
-static bool pending_selection_changed = false;
-
-
-// event capture mechanism for qt_xclb_wait_for_event
-static bool waiting_for_data = false;
-static bool has_captured_event = false;
-static Window capture_event_win = XNone;
-static int capture_event_type = -1;
-static XEvent captured_event;
-
-class QClipboardWatcher; // forward decl
-static QClipboardWatcher *selection_watcher = 0;
-static QClipboardWatcher *clipboard_watcher = 0;
-
-static void cleanup()
-{
- delete owner;
- delete requestor;
- owner = 0;
- requestor = 0;
-}
-
-static
-void setupOwner()
-{
- if (owner)
- return;
- owner = new QWidget(0);
- owner->setObjectName(QLatin1String("internal clipboard owner"));
- owner->createWinId();
- requestor = new QWidget(0);
- requestor->createWinId();
- requestor->setObjectName(QLatin1String("internal clipboard requestor"));
- // We don't need this internal widgets to appear in QApplication::topLevelWidgets()
- if (QWidgetPrivate::allWidgets) {
- QWidgetPrivate::allWidgets->remove(owner);
- QWidgetPrivate::allWidgets->remove(requestor);
- }
- qAddPostRoutine(cleanup);
-}
-
-
-class QClipboardWatcher : public QInternalMimeData {
-public:
- QClipboardWatcher(QClipboard::Mode mode);
- ~QClipboardWatcher();
- bool empty() const;
- virtual bool hasFormat_sys(const QString &mimetype) const;
- virtual QStringList formats_sys() const;
-
- QVariant retrieveData_sys(const QString &mimetype, QVariant::Type type) const;
- QByteArray getDataInFormat(Atom fmtatom) const;
-
- Atom atom;
- mutable QStringList formatList;
- mutable QByteArray format_atoms;
-};
-
-class QClipboardData
-{
-private:
- QMimeData *&mimeDataRef() const
- {
- if(mode == QClipboard::Selection)
- return selectionData;
- return clipboardData;
- }
-
-public:
- QClipboardData(QClipboard::Mode mode);
- ~QClipboardData();
-
- void setSource(QMimeData* s)
- {
- if ((mode == QClipboard::Selection && selectionData == s)
- || clipboardData == s) {
- return;
- }
-
- if (selectionData != clipboardData) {
- delete mimeDataRef();
- }
-
- mimeDataRef() = s;
- }
-
- QMimeData *source() const
- {
- return mimeDataRef();
- }
-
- void clear()
- {
- timestamp = CurrentTime;
- if (selectionData == clipboardData) {
- mimeDataRef() = 0;
- } else {
- QMimeData *&src = mimeDataRef();
- delete src;
- src = 0;
- }
- }
-
- static QMimeData *selectionData;
- static QMimeData *clipboardData;
- Time timestamp;
- QClipboard::Mode mode;
-};
-
-QMimeData *QClipboardData::selectionData = 0;
-QMimeData *QClipboardData::clipboardData = 0;
-
-QClipboardData::QClipboardData(QClipboard::Mode clipboardMode)
-{
- timestamp = CurrentTime;
- mode = clipboardMode;
-}
-
-QClipboardData::~QClipboardData()
-{ clear(); }
-
-
-static QClipboardData *internalCbData = 0;
-static QClipboardData *internalSelData = 0;
-
-static void cleanupClipboardData()
-{
- delete internalCbData;
- internalCbData = 0;
-}
-
-static QClipboardData *clipboardData()
-{
- if (internalCbData == 0) {
- internalCbData = new QClipboardData(QClipboard::Clipboard);
- qAddPostRoutine(cleanupClipboardData);
- }
- return internalCbData;
-}
-
-static void cleanupSelectionData()
-{
- delete internalSelData;
- internalSelData = 0;
-}
-
-static QClipboardData *selectionData()
-{
- if (internalSelData == 0) {
- internalSelData = new QClipboardData(QClipboard::Selection);
- qAddPostRoutine(cleanupSelectionData);
- }
- return internalSelData;
-}
-
-class QClipboardINCRTransaction
-{
-public:
- QClipboardINCRTransaction(Window w, Atom p, Atom t, int f, QByteArray d, unsigned int i);
- ~QClipboardINCRTransaction(void);
-
- int x11Event(XEvent *event);
-
- Window window;
- Atom property, target;
- int format;
- QByteArray data;
- unsigned int increment;
- unsigned int offset;
-};
-
-typedef QMap<Window,QClipboardINCRTransaction*> TransactionMap;
-static TransactionMap *transactions = 0;
-static QApplication::EventFilter prev_event_filter = 0;
-static int incr_timer_id = 0;
-
-static bool qt_x11_incr_event_filter(void *message, long *result)
-{
- XEvent *event = reinterpret_cast<XEvent *>(message);
- TransactionMap::Iterator it = transactions->find(event->xany.window);
- if (it != transactions->end()) {
- if ((*it)->x11Event(event) != 0)
- return true;
- }
- if (prev_event_filter)
- return prev_event_filter(event, result);
- return false;
-}
-
-/*
- called when no INCR activity has happened for 'clipboard_timeout'
- milliseconds... we assume that all unfinished transactions have
- timed out and remove everything from the transaction map
-*/
-static void qt_xclb_incr_timeout(void)
-{
- qWarning("QClipboard: Timed out while sending data");
-
- while (transactions)
- delete *transactions->begin();
-}
-
-QClipboardINCRTransaction::QClipboardINCRTransaction(Window w, Atom p, Atom t, int f,
- QByteArray d, unsigned int i)
- : window(w), property(p), target(t), format(f), data(d), increment(i), offset(0u)
-{
- DEBUG("QClipboard: sending %d bytes (INCR transaction %p)", d.size(), this);
-
- XSelectInput(X11->display, window, PropertyChangeMask);
-
- if (! transactions) {
- VDEBUG("QClipboard: created INCR transaction map");
- transactions = new TransactionMap;
- prev_event_filter = qApp->setEventFilter(qt_x11_incr_event_filter);
- incr_timer_id = QApplication::clipboard()->startTimer(clipboard_timeout);
- }
- transactions->insert(window, this);
-}
-
-QClipboardINCRTransaction::~QClipboardINCRTransaction(void)
-{
- VDEBUG("QClipboard: destroyed INCR transacton %p", this);
-
- XSelectInput(X11->display, window, NoEventMask);
-
- transactions->remove(window);
- if (transactions->isEmpty()) {
- VDEBUG("QClipboard: no more INCR transactions");
- delete transactions;
- transactions = 0;
-
- (void)qApp->setEventFilter(prev_event_filter);
-
- if (incr_timer_id != 0) {
- QApplication::clipboard()->killTimer(incr_timer_id);
- incr_timer_id = 0;
- }
- }
-}
-
-int QClipboardINCRTransaction::x11Event(XEvent *event)
-{
- if (event->type != PropertyNotify
- || (event->xproperty.state != PropertyDelete
- || event->xproperty.atom != property))
- return 0;
-
- // restart the INCR timer
- if (incr_timer_id) QApplication::clipboard()->killTimer(incr_timer_id);
- incr_timer_id = QApplication::clipboard()->startTimer(clipboard_timeout);
-
- unsigned int bytes_left = data.size() - offset;
- if (bytes_left > 0) {
- unsigned int xfer = qMin(increment, bytes_left);
- VDEBUG("QClipboard: sending %d bytes, %d remaining (INCR transaction %p)",
- xfer, bytes_left - xfer, this);
-
- XChangeProperty(X11->display, window, property, target, format,
- PropModeReplace, (uchar *) data.data() + offset, xfer);
- offset += xfer;
- } else {
- // INCR transaction finished...
- XChangeProperty(X11->display, window, property, target, format,
- PropModeReplace, (uchar *) data.data(), 0);
- delete this;
- }
-
- return 1;
-}
-
-
-/*****************************************************************************
- QClipboard member functions for X11.
- *****************************************************************************/
-
-struct qt_init_timestamp_data
-{
- Time timestamp;
-};
-
-#if defined(Q_C_CALLBACKS)
-extern "C" {
-#endif
-
-static Bool qt_init_timestamp_scanner(Display*, XEvent *event, XPointer arg)
-{
- qt_init_timestamp_data *data =
- reinterpret_cast<qt_init_timestamp_data*>(arg);
- switch(event->type)
- {
- case ButtonPress:
- case ButtonRelease:
- data->timestamp = event->xbutton.time;
- break;
- case MotionNotify:
- data->timestamp = event->xmotion.time;
- break;
- case XKeyPress:
- case XKeyRelease:
- data->timestamp = event->xkey.time;
- break;
- case PropertyNotify:
- data->timestamp = event->xproperty.time;
- break;
- case EnterNotify:
- case LeaveNotify:
- data->timestamp = event->xcrossing.time;
- break;
- case SelectionClear:
- data->timestamp = event->xselectionclear.time;
- break;
- default:
- break;
- }
-#ifndef QT_NO_XFIXES
- if (X11->use_xfixes && event->type == (X11->xfixes_eventbase + XFixesSelectionNotify)) {
- XFixesSelectionNotifyEvent *req =
- reinterpret_cast<XFixesSelectionNotifyEvent *>(event);
- data->timestamp = req->selection_timestamp;
- }
-#endif
- return false;
-}
-
-#if defined(Q_C_CALLBACKS)
-}
-#endif
-
-QClipboard::QClipboard(QObject *parent)
- : QObject(*new QClipboardPrivate, parent)
-{
- // create desktop widget since we need it to get PropertyNotify or
- // XFixesSelectionNotify events when someone changes the
- // clipboard.
- (void)QApplication::desktop();
-
-#ifndef QT_NO_XFIXES
- if (X11->use_xfixes && X11->ptrXFixesSelectSelectionInput) {
- const unsigned long eventMask =
- XFixesSetSelectionOwnerNotifyMask | XFixesSelectionWindowDestroyNotifyMask | XFixesSelectionClientCloseNotifyMask;
- for (int i = 0; i < X11->screenCount; ++i) {
- X11->ptrXFixesSelectSelectionInput(X11->display, QX11Info::appRootWindow(i),
- XA_PRIMARY, eventMask);
- X11->ptrXFixesSelectSelectionInput(X11->display, QX11Info::appRootWindow(i),
- ATOM(CLIPBOARD), eventMask);
- }
- }
-#endif // QT_NO_XFIXES
-
- if (X11->time == CurrentTime) {
- // send a dummy event to myself to get the timestamp from X11.
- qt_init_timestamp_data data;
- data.timestamp = CurrentTime;
- XEvent ev;
- XCheckIfEvent(X11->display, &ev, &qt_init_timestamp_scanner, (XPointer)&data);
- if (data.timestamp == CurrentTime) {
- setupOwner();
- // We need this value just for completeness, we don't use it.
- long dummy = 0;
- Window ownerId = owner->internalWinId();
- XChangeProperty(X11->display, ownerId,
- ATOM(CLIP_TEMPORARY), XA_INTEGER, 32,
- PropModeReplace, (uchar*)&dummy, 1);
- XWindowEvent(X11->display, ownerId, PropertyChangeMask, &ev);
- data.timestamp = ev.xproperty.time;
- XDeleteProperty(X11->display, ownerId, ATOM(CLIP_TEMPORARY));
- }
- X11->time = data.timestamp;
- }
-}
-
-void QClipboard::clear(Mode mode)
-{
- setMimeData(0, mode);
-}
-
-
-bool QClipboard::supportsMode(Mode mode) const
-{
- return (mode == Clipboard || mode == Selection);
-}
-
-bool QClipboard::ownsMode(Mode mode) const
-{
- if (mode == Clipboard)
- return clipboardData()->timestamp != CurrentTime;
- else if(mode == Selection)
- return selectionData()->timestamp != CurrentTime;
- else
- return false;
-}
-
-
-// event filter function... captures interesting events while
-// qt_xclb_wait_for_event is running the event loop
-static bool qt_x11_clipboard_event_filter(void *message, long *)
-{
- XEvent *event = reinterpret_cast<XEvent *>(message);
- if (event->xany.type == capture_event_type &&
- event->xany.window == capture_event_win) {
- VDEBUG("QClipboard: event_filter(): caught event type %d", event->type);
- has_captured_event = true;
- captured_event = *event;
- return true;
- }
- return false;
-}
-
-static Bool checkForClipboardEvents(Display *, XEvent *e, XPointer)
-{
- return ((e->type == SelectionRequest && (e->xselectionrequest.selection == XA_PRIMARY
- || e->xselectionrequest.selection == ATOM(CLIPBOARD)))
- || (e->type == SelectionClear && (e->xselectionclear.selection == XA_PRIMARY
- || e->xselectionclear.selection == ATOM(CLIPBOARD))));
-}
-
-bool QX11Data::clipboardWaitForEvent(Window win, int type, XEvent *event, int timeout)
-{
- QElapsedTimer started;
- started.start();
- QElapsedTimer now = started;
-
- if (QAbstractEventDispatcher::instance()->inherits("QtMotif")
- || QApplication::clipboard()->property("useEventLoopWhenWaiting").toBool()) {
- if (waiting_for_data) {
- Q_ASSERT(!"QClipboard: internal error, qt_xclb_wait_for_event recursed");
- return false;
- }
- waiting_for_data = true;
-
-
- has_captured_event = false;
- capture_event_win = win;
- capture_event_type = type;
-
- QApplication::EventFilter old_event_filter =
- qApp->setEventFilter(qt_x11_clipboard_event_filter);
-
- do {
- if (XCheckTypedWindowEvent(display, win, type, event)) {
- waiting_for_data = false;
- qApp->setEventFilter(old_event_filter);
- return true;
- }
-
- XSync(X11->display, false);
- usleep(50000);
-
- now.start();
-
- QEventLoop::ProcessEventsFlags flags(QEventLoop::ExcludeUserInputEvents
- | QEventLoop::ExcludeSocketNotifiers
- | QEventLoop::WaitForMoreEvents
- | QEventLoop::X11ExcludeTimers);
- QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance();
- eventDispatcher->processEvents(flags);
-
- if (has_captured_event) {
- waiting_for_data = false;
- *event = captured_event;
- qApp->setEventFilter(old_event_filter);
- return true;
- }
- } while (started.msecsTo(now) < timeout);
-
- waiting_for_data = false;
- qApp->setEventFilter(old_event_filter);
- } else {
- do {
- if (XCheckTypedWindowEvent(X11->display,win,type,event))
- return true;
-
- // process other clipboard events, since someone is probably requesting data from us
- XEvent e;
- if (XCheckIfEvent(X11->display, &e, checkForClipboardEvents, 0))
- qApp->x11ProcessEvent(&e);
-
- now.start();
-
- XFlush(X11->display);
-
- // sleep 50 ms, so we don't use up CPU cycles all the time.
- struct timeval usleep_tv;
- usleep_tv.tv_sec = 0;
- usleep_tv.tv_usec = 50000;
- select(0, 0, 0, 0, &usleep_tv);
- } while (started.msecsTo(now) < timeout);
- }
- return false;
-}
-
-
-static inline int maxSelectionIncr(Display *dpy)
-{ return XMaxRequestSize(dpy) > 65536 ? 65536*4 : XMaxRequestSize(dpy)*4 - 100; }
-
-bool QX11Data::clipboardReadProperty(Window win, Atom property, bool deleteProperty,
- QByteArray *buffer, int *size, Atom *type, int *format)
-{
- int maxsize = maxSelectionIncr(display);
- ulong bytes_left; // bytes_after
- ulong length; // nitems
- uchar *data;
- Atom dummy_type;
- int dummy_format;
- int r;
-
- if (!type) // allow null args
- type = &dummy_type;
- if (!format)
- format = &dummy_format;
-
- // Don't read anything, just get the size of the property data
- r = XGetWindowProperty(display, win, property, 0, 0, False,
- AnyPropertyType, type, format,
- &length, &bytes_left, &data);
- if (r != Success || (type && *type == XNone)) {
- buffer->resize(0);
- return false;
- }
- XFree((char*)data);
-
- int offset = 0, buffer_offset = 0, format_inc = 1, proplen = bytes_left;
-
- VDEBUG("QClipboard: read_property(): initial property length: %d", proplen);
-
- switch (*format) {
- case 8:
- default:
- format_inc = sizeof(char) / 1;
- break;
-
- case 16:
- format_inc = sizeof(short) / 2;
- proplen *= sizeof(short) / 2;
- break;
-
- case 32:
- format_inc = sizeof(long) / 4;
- proplen *= sizeof(long) / 4;
- break;
- }
-
- int newSize = proplen;
- buffer->resize(newSize);
-
- bool ok = (buffer->size() == newSize);
- VDEBUG("QClipboard: read_property(): buffer resized to %d", buffer->size());
-
- if (ok && newSize) {
- // could allocate buffer
-
- while (bytes_left) {
- // more to read...
-
- r = XGetWindowProperty(display, win, property, offset, maxsize/4,
- False, AnyPropertyType, type, format,
- &length, &bytes_left, &data);
- if (r != Success || (type && *type == XNone))
- break;
-
- offset += length / (32 / *format);
- length *= format_inc * (*format) / 8;
-
- // Here we check if we get a buffer overflow and tries to
- // recover -- this shouldn't normally happen, but it doesn't
- // hurt to be defensive
- if ((int)(buffer_offset + length) > buffer->size()) {
- length = buffer->size() - buffer_offset;
-
- // escape loop
- bytes_left = 0;
- }
-
- memcpy(buffer->data() + buffer_offset, data, length);
- buffer_offset += length;
-
- XFree((char*)data);
- }
-
- if (*format == 8 && *type == ATOM(COMPOUND_TEXT)) {
- // convert COMPOUND_TEXT to a multibyte string
- XTextProperty textprop;
- textprop.encoding = *type;
- textprop.format = *format;
- textprop.nitems = buffer_offset;
- textprop.value = (unsigned char *) buffer->data();
-
- char **list_ret = 0;
- int count;
- if (XmbTextPropertyToTextList(display, &textprop, &list_ret,
- &count) == Success && count && list_ret) {
- offset = buffer_offset = strlen(list_ret[0]);
- buffer->resize(offset);
- memcpy(buffer->data(), list_ret[0], offset);
- }
- if (list_ret) XFreeStringList(list_ret);
- }
- }
-
- // correct size, not 0-term.
- if (size)
- *size = buffer_offset;
-
- VDEBUG("QClipboard: read_property(): buffer size %d, buffer offset %d, offset %d",
- buffer->size(), buffer_offset, offset);
-
- if (deleteProperty)
- XDeleteProperty(display, win, property);
-
- XFlush(display);
-
- return ok;
-}
-
-QByteArray QX11Data::clipboardReadIncrementalProperty(Window win, Atom property, int nbytes, bool nullterm)
-{
- XEvent event;
-
- QByteArray buf;
- QByteArray tmp_buf;
- bool alloc_error = false;
- int length;
- int offset = 0;
-
- if (nbytes > 0) {
- // Reserve buffer + zero-terminator (for text data)
- // We want to complete the INCR transfer even if we cannot
- // allocate more memory
- buf.resize(nbytes+1);
- alloc_error = buf.size() != nbytes+1;
- }
-
- for (;;) {
- XFlush(display);
- if (!clipboardWaitForEvent(win,PropertyNotify,&event,clipboard_timeout))
- break;
- if (event.xproperty.atom != property ||
- event.xproperty.state != PropertyNewValue)
- continue;
- if (X11->clipboardReadProperty(win, property, true, &tmp_buf, &length, 0, 0)) {
- if (length == 0) { // no more data, we're done
- if (nullterm) {
- buf.resize(offset+1);
- buf[offset] = '\0';
- } else {
- buf.resize(offset);
- }
- return buf;
- } else if (!alloc_error) {
- if (offset+length > (int)buf.size()) {
- buf.resize(offset+length+65535);
- if (buf.size() != offset+length+65535) {
- alloc_error = true;
- length = buf.size() - offset;
- }
- }
- memcpy(buf.data()+offset, tmp_buf.constData(), length);
- tmp_buf.resize(0);
- offset += length;
- }
- } else {
- break;
- }
- }
-
- // timed out ... create a new requestor window, otherwise the requestor
- // could consider next request to be still part of this timed out request
- delete requestor;
- requestor = new QWidget(0);
- requestor->setObjectName(QLatin1String("internal clipboard requestor"));
- // We don't need this internal widget to appear in QApplication::topLevelWidgets()
- if (QWidgetPrivate::allWidgets)
- QWidgetPrivate::allWidgets->remove(requestor);
-
- return QByteArray();
-}
-
-static Atom send_targets_selection(QClipboardData *d, Window window, Atom property)
-{
- QVector<Atom> types;
- QStringList formats = QInternalMimeData::formatsHelper(d->source());
- for (int i = 0; i < formats.size(); ++i) {
- QList<Atom> atoms = X11->xdndMimeAtomsForFormat(formats.at(i));
- for (int j = 0; j < atoms.size(); ++j) {
- if (!types.contains(atoms.at(j)))
- types.append(atoms.at(j));
- }
- }
- types.append(ATOM(TARGETS));
- types.append(ATOM(MULTIPLE));
- types.append(ATOM(TIMESTAMP));
- types.append(ATOM(SAVE_TARGETS));
-
- XChangeProperty(X11->display, window, property, XA_ATOM, 32,
- PropModeReplace, (uchar *) types.data(), types.size());
- return property;
-}
-
-static Atom send_selection(QClipboardData *d, Atom target, Window window, Atom property)
-{
- Atom atomFormat = target;
- int dataFormat = 0;
- QByteArray data;
-
- QByteArray fmt = X11->xdndAtomToString(target);
- if (fmt.isEmpty()) { // Not a MIME type we have
- DEBUG("QClipboard: send_selection(): converting to type '%s' is not supported", fmt.data());
- return XNone;
- }
- DEBUG("QClipboard: send_selection(): converting to type '%s'", fmt.data());
-
- if (X11->xdndMimeDataForAtom(target, d->source(), &data, &atomFormat, &dataFormat)) {
-
- VDEBUG("QClipboard: send_selection():\n"
- " property type %lx\n"
- " property name '%s'\n"
- " format %d\n"
- " %d bytes\n",
- target, X11->xdndMimeAtomToString(atomFormat).toLatin1().data(), dataFormat, data.size());
-
- // don't allow INCR transfers when using MULTIPLE or to
- // Motif clients (since Motif doesn't support INCR)
- static Atom motif_clip_temporary = ATOM(CLIP_TEMPORARY);
- bool allow_incr = property != motif_clip_temporary;
-
- // X_ChangeProperty protocol request is 24 bytes
- const int increment = (XMaxRequestSize(X11->display) * 4) - 24;
- if (data.size() > increment && allow_incr) {
- long bytes = data.size();
- XChangeProperty(X11->display, window, property,
- ATOM(INCR), 32, PropModeReplace, (uchar *) &bytes, 1);
-
- (void)new QClipboardINCRTransaction(window, property, atomFormat, dataFormat, data, increment);
- return property;
- }
-
- // make sure we can perform the XChangeProperty in a single request
- if (data.size() > increment)
- return XNone; // ### perhaps use several XChangeProperty calls w/ PropModeAppend?
- int dataSize = data.size() / (dataFormat / 8);
- // use a single request to transfer data
- XChangeProperty(X11->display, window, property, atomFormat,
- dataFormat, PropModeReplace, (uchar *) data.data(),
- dataSize);
- }
- return property;
-}
-
-/*! \internal
- Internal cleanup for Windows.
-*/
-void QClipboard::ownerDestroyed()
-{ }
-
-
-/*! \internal
- Internal optimization for Windows.
-*/
-void QClipboard::connectNotify(const char *)
-{ }
-
-
-bool QClipboard::event(QEvent *e)
-{
- if (e->type() == QEvent::Timer) {
- QTimerEvent *te = (QTimerEvent *) e;
-
- if (waiting_for_data) // should never happen
- return false;
-
- if (te->timerId() == timer_id) {
- killTimer(timer_id);
- timer_id = 0;
-
- timer_event_clear = true;
- if (selection_watcher) // clear selection
- selectionData()->clear();
- if (clipboard_watcher) // clear clipboard
- clipboardData()->clear();
- timer_event_clear = false;
-
- return true;
- } else if (te->timerId() == pending_timer_id) {
- // I hate klipper
- killTimer(pending_timer_id);
- pending_timer_id = 0;
-
- if (pending_clipboard_changed) {
- pending_clipboard_changed = false;
- clipboardData()->clear();
- emitChanged(QClipboard::Clipboard);
- }
- if (pending_selection_changed) {
- pending_selection_changed = false;
- selectionData()->clear();
- emitChanged(QClipboard::Selection);
- }
-
- return true;
- } else if (te->timerId() == incr_timer_id) {
- killTimer(incr_timer_id);
- incr_timer_id = 0;
-
- qt_xclb_incr_timeout();
-
- return true;
- } else {
- return QObject::event(e);
- }
- } else if (e->type() != QEvent::Clipboard) {
- return QObject::event(e);
- }
-
- XEvent *xevent = (XEvent *)(((QClipboardEvent *)e)->data());
- Display *dpy = X11->display;
-
- if (!xevent) {
- // That means application exits and we need to give clipboard
- // content to the clipboard manager.
- // First we check if there is a clipboard manager.
- if (XGetSelectionOwner(X11->display, ATOM(CLIPBOARD_MANAGER)) == XNone
- || !owner)
- return true;
-
- Window ownerId = owner->internalWinId();
- Q_ASSERT(ownerId);
- // we delete the property so the manager saves all TARGETS.
- XDeleteProperty(X11->display, ownerId, ATOM(_QT_SELECTION));
- XConvertSelection(X11->display, ATOM(CLIPBOARD_MANAGER), ATOM(SAVE_TARGETS),
- ATOM(_QT_SELECTION), ownerId, X11->time);
- XSync(dpy, false);
-
- XEvent event;
- // waiting until the clipboard manager fetches the content.
- if (!X11->clipboardWaitForEvent(ownerId, SelectionNotify, &event, 10000)) {
- qWarning("QClipboard: Unable to receive an event from the "
- "clipboard manager in a reasonable time");
- }
-
- return true;
- }
-
- switch (xevent->type) {
-
- case SelectionClear:
- // new selection owner
- if (xevent->xselectionclear.selection == XA_PRIMARY) {
- QClipboardData *d = selectionData();
-
- // ignore the event if it was generated before we gained selection ownership
- if (d->timestamp != CurrentTime && xevent->xselectionclear.time <= d->timestamp)
- break;
-
- DEBUG("QClipboard: new selection owner 0x%lx at time %lx (ours %lx)",
- XGetSelectionOwner(dpy, XA_PRIMARY),
- xevent->xselectionclear.time, d->timestamp);
-
- if (! waiting_for_data) {
- d->clear();
- emitChanged(QClipboard::Selection);
- } else {
- pending_selection_changed = true;
- if (! pending_timer_id)
- pending_timer_id = QApplication::clipboard()->startTimer(0);
- }
- } else if (xevent->xselectionclear.selection == ATOM(CLIPBOARD)) {
- QClipboardData *d = clipboardData();
-
- // ignore the event if it was generated before we gained selection ownership
- if (d->timestamp != CurrentTime && xevent->xselectionclear.time <= d->timestamp)
- break;
-
- DEBUG("QClipboard: new clipboard owner 0x%lx at time %lx (%lx)",
- XGetSelectionOwner(dpy, ATOM(CLIPBOARD)),
- xevent->xselectionclear.time, d->timestamp);
-
- if (! waiting_for_data) {
- d->clear();
- emitChanged(QClipboard::Clipboard);
- } else {
- pending_clipboard_changed = true;
- if (! pending_timer_id)
- pending_timer_id = QApplication::clipboard()->startTimer(0);
- }
- } else {
- qWarning("QClipboard: Unknown SelectionClear event received");
- return false;
- }
- break;
-
- case SelectionNotify:
- /*
- Something has delivered data to us, but this was not caught
- by QClipboardWatcher::getDataInFormat()
-
- Just skip the event to prevent Bad Things (tm) from
- happening later on...
- */
- break;
-
- case SelectionRequest:
- {
- // someone wants our data
- XSelectionRequestEvent *req = &xevent->xselectionrequest;
-
- if (requestor && req->requestor == requestor->internalWinId())
- break;
-
- XEvent event;
- event.xselection.type = SelectionNotify;
- event.xselection.display = req->display;
- event.xselection.requestor = req->requestor;
- event.xselection.selection = req->selection;
- event.xselection.target = req->target;
- event.xselection.property = XNone;
- event.xselection.time = req->time;
-
- DEBUG("QClipboard: SelectionRequest from %lx\n"
- " selection 0x%lx (%s) target 0x%lx (%s)",
- req->requestor,
- req->selection,
- X11->xdndAtomToString(req->selection).data(),
- req->target,
- X11->xdndAtomToString(req->target).data());
-
- QClipboardData *d;
- if (req->selection == XA_PRIMARY) {
- d = selectionData();
- } else if (req->selection == ATOM(CLIPBOARD)) {
- d = clipboardData();
- } else {
- qWarning("QClipboard: Unknown selection '%lx'", req->selection);
- XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
- break;
- }
-
- if (! d->source()) {
- qWarning("QClipboard: Cannot transfer data, no data available");
- XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
- break;
- }
-
- DEBUG("QClipboard: SelectionRequest at time %lx (ours %lx)",
- req->time, d->timestamp);
-
- if (d->timestamp == CurrentTime // we don't own the selection anymore
- || (req->time != CurrentTime && req->time < d->timestamp)) {
- DEBUG("QClipboard: SelectionRequest too old");
- XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
- break;
- }
-
- Atom xa_targets = ATOM(TARGETS);
- Atom xa_multiple = ATOM(MULTIPLE);
- Atom xa_timestamp = ATOM(TIMESTAMP);
-
- struct AtomPair { Atom target; Atom property; } *multi = 0;
- Atom multi_type = XNone;
- int multi_format = 0;
- int nmulti = 0;
- int imulti = -1;
- bool multi_writeback = false;
-
- if (req->target == xa_multiple) {
- QByteArray multi_data;
- if (req->property == XNone
- || !X11->clipboardReadProperty(req->requestor, req->property, false, &multi_data,
- 0, &multi_type, &multi_format)
- || multi_format != 32) {
- // MULTIPLE property not formatted correctly
- XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
- break;
- }
- nmulti = multi_data.size()/sizeof(*multi);
- multi = new AtomPair[nmulti];
- memcpy(multi,multi_data.data(),multi_data.size());
- imulti = 0;
- }
-
- for (; imulti < nmulti; ++imulti) {
- Atom target;
- Atom property;
-
- if (multi) {
- target = multi[imulti].target;
- property = multi[imulti].property;
- } else {
- target = req->target;
- property = req->property;
- if (property == XNone) // obsolete client
- property = target;
- }
-
- Atom ret = XNone;
- if (target == XNone || property == XNone) {
- ;
- } else if (target == xa_timestamp) {
- if (d->timestamp != CurrentTime) {
- XChangeProperty(dpy, req->requestor, property, XA_INTEGER, 32,
- PropModeReplace, (uchar *) &d->timestamp, 1);
- ret = property;
- } else {
- qWarning("QClipboard: Invalid data timestamp");
- }
- } else if (target == xa_targets) {
- ret = send_targets_selection(d, req->requestor, property);
- } else {
- ret = send_selection(d, target, req->requestor, property);
- }
-
- if (nmulti > 0) {
- if (ret == XNone) {
- multi[imulti].property = XNone;
- multi_writeback = true;
- }
- } else {
- event.xselection.property = ret;
- break;
- }
- }
-
- if (nmulti > 0) {
- if (multi_writeback) {
- // according to ICCCM 2.6.2 says to put None back
- // into the original property on the requestor window
- XChangeProperty(dpy, req->requestor, req->property, multi_type, 32,
- PropModeReplace, (uchar *) multi, nmulti * 2);
- }
-
- delete [] multi;
- event.xselection.property = req->property;
- }
-
- // send selection notify to requestor
- XSendEvent(dpy, req->requestor, False, NoEventMask, &event);
-
- DEBUG("QClipboard: SelectionNotify to 0x%lx\n"
- " property 0x%lx (%s)",
- req->requestor, event.xselection.property,
- X11->xdndAtomToString(event.xselection.property).data());
- }
- break;
- }
-
- return true;
-}
-
-
-
-
-
-
-QClipboardWatcher::QClipboardWatcher(QClipboard::Mode mode)
- : QInternalMimeData()
-{
- switch (mode) {
- case QClipboard::Selection:
- atom = XA_PRIMARY;
- break;
-
- case QClipboard::Clipboard:
- atom = ATOM(CLIPBOARD);
- break;
-
- default:
- qWarning("QClipboardWatcher: Internal error: Unsupported clipboard mode");
- break;
- }
-
- setupOwner();
-}
-
-QClipboardWatcher::~QClipboardWatcher()
-{
- if(selection_watcher == this)
- selection_watcher = 0;
- if(clipboard_watcher == this)
- clipboard_watcher = 0;
-}
-
-bool QClipboardWatcher::empty() const
-{
- Display *dpy = X11->display;
- Window win = XGetSelectionOwner(dpy, atom);
-
- if(win == requestor->internalWinId()) {
- qWarning("QClipboardWatcher::empty: Internal error: Application owns the selection");
- return true;
- }
-
- return win == XNone;
-}
-
-QStringList QClipboardWatcher::formats_sys() const
-{
- if (empty())
- return QStringList();
-
- if (!formatList.count()) {
- // get the list of targets from the current clipboard owner - we do this
- // once so that multiple calls to this function don't require multiple
- // server round trips...
-
- format_atoms = getDataInFormat(ATOM(TARGETS));
-
- if (format_atoms.size() > 0) {
- Atom *targets = (Atom *) format_atoms.data();
- int size = format_atoms.size() / sizeof(Atom);
-
- for (int i = 0; i < size; ++i) {
- if (targets[i] == 0)
- continue;
-
- QStringList formatsForAtom = X11->xdndMimeFormatsForAtom(targets[i]);
- for (int j = 0; j < formatsForAtom.size(); ++j) {
- if (!formatList.contains(formatsForAtom.at(j)))
- formatList.append(formatsForAtom.at(j));
- }
- VDEBUG(" format: %s", X11->xdndAtomToString(targets[i]).data());
- VDEBUG(" data:\n%s\n", getDataInFormat(targets[i]).data());
- }
- DEBUG("QClipboardWatcher::format: %d formats available", formatList.count());
- }
- }
-
- return formatList;
-}
-
-bool QClipboardWatcher::hasFormat_sys(const QString &format) const
-{
- QStringList list = formats();
- return list.contains(format);
-}
-
-QVariant QClipboardWatcher::retrieveData_sys(const QString &fmt, QVariant::Type requestedType) const
-{
- if (fmt.isEmpty() || empty())
- return QByteArray();
-
- (void)formats(); // trigger update of format list
- DEBUG("QClipboardWatcher::data: fetching format '%s'", fmt.toLatin1().data());
-
- QList<Atom> atoms;
- Atom *targets = (Atom *) format_atoms.data();
- int size = format_atoms.size() / sizeof(Atom);
- for (int i = 0; i < size; ++i)
- atoms.append(targets[i]);
-
- QByteArray encoding;
- Atom fmtatom = X11->xdndMimeAtomForFormat(fmt, requestedType, atoms, &encoding);
-
- if (fmtatom == 0)
- return QVariant();
-
- return X11->xdndMimeConvertToFormat(fmtatom, getDataInFormat(fmtatom), fmt, requestedType, encoding);
-}
-
-QByteArray QClipboardWatcher::getDataInFormat(Atom fmtatom) const
-{
- QByteArray buf;
-
- Display *dpy = X11->display;
- requestor->createWinId();
- Window win = requestor->internalWinId();
- Q_ASSERT(requestor->testAttribute(Qt::WA_WState_Created));
-
- DEBUG("QClipboardWatcher::getDataInFormat: selection '%s' format '%s'",
- X11->xdndAtomToString(atom).data(), X11->xdndAtomToString(fmtatom).data());
-
- XSelectInput(dpy, win, NoEventMask); // don't listen for any events
-
- XDeleteProperty(dpy, win, ATOM(_QT_SELECTION));
- XConvertSelection(dpy, atom, fmtatom, ATOM(_QT_SELECTION), win, X11->time);
- XSync(dpy, false);
-
- VDEBUG("QClipboardWatcher::getDataInFormat: waiting for SelectionNotify event");
-
- XEvent xevent;
- if (!X11->clipboardWaitForEvent(win,SelectionNotify,&xevent,clipboard_timeout) ||
- xevent.xselection.property == XNone) {
- DEBUG("QClipboardWatcher::getDataInFormat: format not available");
- return buf;
- }
-
- VDEBUG("QClipboardWatcher::getDataInFormat: fetching data...");
-
- Atom type;
- XSelectInput(dpy, win, PropertyChangeMask);
-
- if (X11->clipboardReadProperty(win, ATOM(_QT_SELECTION), true, &buf, 0, &type, 0)) {
- if (type == ATOM(INCR)) {
- int nbytes = buf.size() >= 4 ? *((int*)buf.data()) : 0;
- buf = X11->clipboardReadIncrementalProperty(win, ATOM(_QT_SELECTION), nbytes, false);
- }
- }
-
- XSelectInput(dpy, win, NoEventMask);
-
- DEBUG("QClipboardWatcher::getDataInFormat: %d bytes received", buf.size());
-
- return buf;
-}
-
-
-const QMimeData* QClipboard::mimeData(Mode mode) const
-{
- QClipboardData *d = 0;
- switch (mode) {
- case Selection:
- d = selectionData();
- break;
- case Clipboard:
- d = clipboardData();
- break;
- default:
- qWarning("QClipboard::mimeData: unsupported mode '%d'", mode);
- return 0;
- }
-
- if (! d->source() && ! timer_event_clear) {
- if (mode == Selection) {
- if (! selection_watcher)
- selection_watcher = new QClipboardWatcher(mode);
- d->setSource(selection_watcher);
- } else {
- if (! clipboard_watcher)
- clipboard_watcher = new QClipboardWatcher(mode);
- d->setSource(clipboard_watcher);
- }
-
- if (! timer_id) {
- // start a zero timer - we will clear cached data when the timer
- // times out, which will be the next time we hit the event loop...
- // that way, the data is cached long enough for calls within a single
- // loop/function, but the data doesn't linger around in case the selection
- // changes
- QClipboard *that = ((QClipboard *) this);
- timer_id = that->startTimer(0);
- }
- }
-
- return d->source();
-}
-
-
-void QClipboard::setMimeData(QMimeData* src, Mode mode)
-{
- Atom atom, sentinel_atom;
- QClipboardData *d;
- switch (mode) {
- case Selection:
- atom = XA_PRIMARY;
- sentinel_atom = ATOM(_QT_SELECTION_SENTINEL);
- d = selectionData();
- break;
-
- case Clipboard:
- atom = ATOM(CLIPBOARD);
- sentinel_atom = ATOM(_QT_CLIPBOARD_SENTINEL);
- d = clipboardData();
- break;
-
- default:
- qWarning("QClipboard::setMimeData: unsupported mode '%d'", mode);
- return;
- }
-
- Display *dpy = X11->display;
- Window newOwner;
-
- if (! src) { // no data, clear clipboard contents
- newOwner = XNone;
- d->clear();
- } else {
- setupOwner();
-
- newOwner = owner->internalWinId();
-
- d->setSource(src);
- d->timestamp = X11->time;
- }
-
- Window prevOwner = XGetSelectionOwner(dpy, atom);
- // use X11->time, since d->timestamp == CurrentTime when clearing
- XSetSelectionOwner(dpy, atom, newOwner, X11->time);
-
- if (mode == Selection)
- emitChanged(QClipboard::Selection);
- else
- emitChanged(QClipboard::Clipboard);
-
- if (XGetSelectionOwner(dpy, atom) != newOwner) {
- qWarning("QClipboard::setData: Cannot set X11 selection owner for %s",
- X11->xdndAtomToString(atom).data());
- d->clear();
- return;
- }
-
- // Signal to other Qt processes that the selection has changed
- Window owners[2];
- owners[0] = newOwner;
- owners[1] = prevOwner;
- XChangeProperty(dpy, QApplication::desktop()->screen(0)->internalWinId(),
- sentinel_atom, XA_WINDOW, 32, PropModeReplace,
- (unsigned char*)&owners, 2);
-}
-
-
-/*
- Called by the main event loop in qapplication_x11.cpp when either
- the _QT_SELECTION_SENTINEL property has been changed (i.e. when some
- Qt process has performed QClipboard::setData()) or when Xfixes told
- us that an other application changed the selection. If it returns
- true, the QClipBoard dataChanged() signal should be emitted.
-*/
-
-bool qt_check_selection_sentinel()
-{
- bool doIt = true;
- if (owner && !X11->use_xfixes) {
- /*
- Since the X selection mechanism cannot give any signal when
- the selection has changed, we emulate it (for Qt processes) here.
- The notification should be ignored in case of either
- a) This is the process that did setData (because setData()
- then has already emitted dataChanged())
- b) This is the process that owned the selection when dataChanged()
- was called (because we have then received a SelectionClear event,
- and have already emitted dataChanged() as a result of that)
- */
-
- unsigned char *retval;
- Atom actualType;
- int actualFormat;
- ulong nitems;
- ulong bytesLeft;
-
- if (XGetWindowProperty(X11->display,
- QApplication::desktop()->screen(0)->internalWinId(),
- ATOM(_QT_SELECTION_SENTINEL), 0, 2, False, XA_WINDOW,
- &actualType, &actualFormat, &nitems,
- &bytesLeft, &retval) == Success) {
- Window *owners = (Window *)retval;
- if (actualType == XA_WINDOW && actualFormat == 32 && nitems == 2) {
- Window win = owner->internalWinId();
- if (owners[0] == win || owners[1] == win)
- doIt = false;
- }
-
- XFree(owners);
- }
- }
-
- if (doIt) {
- if (waiting_for_data) {
- pending_selection_changed = true;
- if (! pending_timer_id)
- pending_timer_id = QApplication::clipboard()->startTimer(0);
- doIt = false;
- } else {
- selectionData()->clear();
- }
- }
-
- return doIt;
-}
-
-
-bool qt_check_clipboard_sentinel()
-{
- bool doIt = true;
- if (owner && !X11->use_xfixes) {
- unsigned char *retval;
- Atom actualType;
- int actualFormat;
- unsigned long nitems, bytesLeft;
-
- if (XGetWindowProperty(X11->display,
- QApplication::desktop()->screen(0)->internalWinId(),
- ATOM(_QT_CLIPBOARD_SENTINEL), 0, 2, False, XA_WINDOW,
- &actualType, &actualFormat, &nitems, &bytesLeft,
- &retval) == Success) {
- Window *owners = (Window *)retval;
- if (actualType == XA_WINDOW && actualFormat == 32 && nitems == 2) {
- Window win = owner->internalWinId();
- if (owners[0] == win || owners[1] == win)
- doIt = false;
- }
-
- XFree(owners);
- }
- }
-
- if (doIt) {
- if (waiting_for_data) {
- pending_clipboard_changed = true;
- if (! pending_timer_id)
- pending_timer_id = QApplication::clipboard()->startTimer(0);
- doIt = false;
- } else {
- clipboardData()->clear();
- }
- }
-
- return doIt;
-}
-
-bool qt_xfixes_selection_changed(Window selectionOwner, Time timestamp)
-{
- QClipboardData *d = selectionData();
-#ifdef QCLIPBOARD_DEBUG
- DEBUG("qt_xfixes_selection_changed: owner = %u; selectionOwner = %u; internal timestamp = %u; external timestamp = %u",
- (unsigned int)(owner ? (int)owner->internalWinId() : 0), (unsigned int)selectionOwner,
- (unsigned int)(d ? d->timestamp : 0), (unsigned int)timestamp);
-#endif
- if (!owner || (selectionOwner && selectionOwner != owner->internalWinId()) ||
- (!selectionOwner && (d->timestamp == CurrentTime || d->timestamp < timestamp)))
- return qt_check_selection_sentinel();
- return false;
-}
-
-bool qt_xfixes_clipboard_changed(Window clipboardOwner, Time timestamp)
-{
- QClipboardData *d = clipboardData();
-#ifdef QCLIPBOARD_DEBUG
- DEBUG("qt_xfixes_clipboard_changed: owner = %u; clipboardOwner = %u; internal timestamp = %u; external timestamp = %u",
- (unsigned int)(owner ? (int)owner->internalWinId() : 0), (unsigned int)clipboardOwner,
- (unsigned int)(d ? d->timestamp : 0), (unsigned int)timestamp);
-#endif
- if (!owner || (clipboardOwner && clipboardOwner != owner->internalWinId()) ||
- (!clipboardOwner && (d->timestamp == CurrentTime || d->timestamp < timestamp)))
- return qt_check_clipboard_sentinel();
- return false;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_CLIPBOARD
diff --git a/src/gui/platforms/x11/qcolormap_x11.cpp b/src/gui/platforms/x11/qcolormap_x11.cpp
deleted file mode 100644
index 05eefa455b..0000000000
--- a/src/gui/platforms/x11/qcolormap_x11.cpp
+++ /dev/null
@@ -1,670 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcolormap.h"
-
-#include "qapplication.h"
-#include "qdebug.h"
-#include "qdesktopwidget.h"
-#include "qvarlengtharray.h"
-
-#include "qx11info_x11.h"
-#include <private/qt_x11_p.h>
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-class QColormapPrivate
-{
-public:
- QColormapPrivate()
- : ref(1), mode(QColormap::Direct), depth(0),
- colormap(0), defaultColormap(true),
- visual(0), defaultVisual(true),
- r_max(0), g_max(0), b_max(0),
- r_shift(0), g_shift(0), b_shift(0)
- {}
-
- QAtomicInt ref;
-
- QColormap::Mode mode;
- int depth;
-
- Colormap colormap;
- bool defaultColormap;
-
- Visual *visual;
- bool defaultVisual;
-
- int r_max;
- int g_max;
- int b_max;
-
- uint r_shift;
- uint g_shift;
- uint b_shift;
-
- QVector<QColor> colors;
- QVector<int> pixels;
-};
-
-
-static uint right_align(uint v)
-{
- while (!(v & 0x1))
- v >>= 1;
- return v;
-}
-
-static int lowest_bit(uint v)
-{
- int i;
- uint b = 1u;
- for (i = 0; ((v & b) == 0u) && i < 32; ++i)
- b <<= 1u;
- return i == 32 ? -1 : i;
-}
-
-static int cube_root(int v)
-{
- if (v == 1)
- return 1;
- // brute force algorithm
- int i = 1;
- for (;;) {
- const int b = i * i * i;
- if (b <= v) {
- ++i;
- } else {
- --i;
- break;
- }
- }
- return i;
-}
-
-static Visual *find_visual(Display *display,
- int screen,
- int visual_class,
- int visual_id,
- int *depth,
- bool *defaultVisual)
-{
- XVisualInfo *vi, rvi;
- int count;
-
- uint mask = VisualScreenMask;
- rvi.screen = screen;
-
- if (visual_class != -1) {
- rvi.c_class = visual_class;
- mask |= VisualClassMask;
- }
- if (visual_id != -1) {
- rvi.visualid = visual_id;
- mask |= VisualIDMask;
- }
-
- Visual *visual = DefaultVisual(display, screen);
- *defaultVisual = true;
- *depth = DefaultDepth(display, screen);
-
- vi = XGetVisualInfo(display, mask, &rvi, &count);
- if (vi) {
- int best = 0;
- for (int x = 0; x < count; ++x) {
- if (vi[x].depth > vi[best].depth)
- best = x;
- }
- if (best >= 0 && best <= count && vi[best].visualid != XVisualIDFromVisual(visual)) {
- visual = vi[best].visual;
- *defaultVisual = (visual == DefaultVisual(display, screen));
- *depth = vi[best].depth;
- }
- }
- if (vi)
- XFree((char *)vi);
- return visual;
-}
-
-static void query_colormap(QColormapPrivate *d, int screen)
-{
- Display *display = QX11Info::display();
-
- // query existing colormap
- int q_colors = (((1u << d->depth) > 256u) ? 256u : (1u << d->depth));
- XColor queried[256];
- memset(queried, 0, sizeof(queried));
- for (int x = 0; x < q_colors; ++x)
- queried[x].pixel = x;
- XQueryColors(display, d->colormap, queried, q_colors);
-
- d->colors.resize(q_colors);
- for (int x = 0; x < q_colors; ++x) {
- if (queried[x].red == 0
- && queried[x].green == 0
- && queried[x].blue == 0
- && queried[x].pixel != BlackPixel(display, screen)) {
- // unallocated color cell, skip it
- continue;
- }
-
- d->colors[x] = QColor::fromRgbF(queried[x].red / float(USHRT_MAX),
- queried[x].green / float(USHRT_MAX),
- queried[x].blue / float(USHRT_MAX));
- }
-
- // for missing colors, find the closest color in the existing colormap
- Q_ASSERT(d->pixels.size());
- for (int x = 0; x < d->pixels.size(); ++x) {
- if (d->pixels.at(x) != -1)
- continue;
-
- QRgb rgb;
- if (d->mode == QColormap::Indexed) {
- const int r = (x / (d->g_max * d->b_max)) % d->r_max;
- const int g = (x / d->b_max) % d->g_max;
- const int b = x % d->b_max;
- rgb = qRgb((r * 0xff + (d->r_max - 1) / 2) / (d->r_max - 1),
- (g * 0xff + (d->g_max - 1) / 2) / (d->g_max - 1),
- (b * 0xff + (d->b_max - 1) / 2) / (d->b_max - 1));
- } else {
- rgb = qRgb(x, x, x);
- }
-
- // find closest color
- int mindist = INT_MAX, best = -1;
- for (int y = 0; y < q_colors; ++y) {
- int r = qRed(rgb) - (queried[y].red >> 8);
- int g = qGreen(rgb) - (queried[y].green >> 8);
- int b = qBlue(rgb) - (queried[y].blue >> 8);
- int dist = (r * r) + (g * g) + (b * b);
- if (dist < mindist) {
- mindist = dist;
- best = y;
- }
- }
-
- Q_ASSERT(best >= 0 && best < q_colors);
- if (d->visual->c_class & 1) {
- XColor xcolor;
- xcolor.red = queried[best].red;
- xcolor.green = queried[best].green;
- xcolor.blue = queried[best].blue;
- xcolor.pixel = queried[best].pixel;
-
- if (XAllocColor(display, d->colormap, &xcolor)) {
- d->pixels[x] = xcolor.pixel;
- } else {
- // some weird stuff is going on...
- d->pixels[x] = (qGray(rgb) < 127
- ? BlackPixel(display, screen)
- : WhitePixel(display, screen));
- }
- } else {
- d->pixels[x] = best;
- }
- }
-}
-
-static void init_gray(QColormapPrivate *d, int screen)
-{
- d->pixels.resize(d->r_max);
-
- for (int g = 0; g < d->g_max; ++g) {
- const int gray = (g * 0xff + (d->r_max - 1) / 2) / (d->r_max - 1);
- const QRgb rgb = qRgb(gray, gray, gray);
-
- d->pixels[g] = -1;
-
- if (d->visual->c_class & 1) {
- XColor xcolor;
- xcolor.red = qRed(rgb) * 0x101;
- xcolor.green = qGreen(rgb) * 0x101;
- xcolor.blue = qBlue(rgb) * 0x101;
- xcolor.pixel = 0ul;
-
- if (XAllocColor(QX11Info::display(), d->colormap, &xcolor))
- d->pixels[g] = xcolor.pixel;
- }
- }
-
- query_colormap(d, screen);
-}
-
-static void init_indexed(QColormapPrivate *d, int screen)
-{
- d->pixels.resize(d->r_max * d->g_max * d->b_max);
-
- // create color cube
- for (int x = 0, r = 0; r < d->r_max; ++r) {
- for (int g = 0; g < d->g_max; ++g) {
- for (int b = 0; b < d->b_max; ++b, ++x) {
- const QRgb rgb = qRgb((r * 0xff + (d->r_max - 1) / 2) / (d->r_max - 1),
- (g * 0xff + (d->g_max - 1) / 2) / (d->g_max - 1),
- (b * 0xff + (d->b_max - 1) / 2) / (d->b_max - 1));
-
- d->pixels[x] = -1;
-
- if (d->visual->c_class & 1) {
- XColor xcolor;
- xcolor.red = qRed(rgb) * 0x101;
- xcolor.green = qGreen(rgb) * 0x101;
- xcolor.blue = qBlue(rgb) * 0x101;
- xcolor.pixel = 0ul;
-
- if (XAllocColor(QX11Info::display(), d->colormap, &xcolor))
- d->pixels[x] = xcolor.pixel;
- }
- }
- }
- }
-
- query_colormap(d, screen);
-}
-
-static void init_direct(QColormapPrivate *d, bool ownColormap)
-{
- if (d->visual->c_class != DirectColor || !ownColormap)
- return;
-
- // preallocate 768 on the stack, so that we don't have to malloc
- // for the common case (<= 24 bpp)
- QVarLengthArray<XColor, 768> colorTable(d->r_max + d->g_max + d->b_max);
- int i = 0;
-
- for (int r = 0; r < d->r_max; ++r) {
- colorTable[i].red = r << 8 | r;
- colorTable[i].pixel = r << d->r_shift;
- colorTable[i].flags = DoRed;
- ++i;
- }
-
- for (int g = 0; g < d->g_max; ++g) {
- colorTable[i].green = g << 8 | g;
- colorTable[i].pixel = g << d->g_shift;
- colorTable[i].flags = DoGreen;
- ++i;
- }
-
- for (int b = 0; b < d->b_max; ++b) {
- colorTable[i].blue = (b << 8 | b);
- colorTable[i].pixel = b << d->b_shift;
- colorTable[i].flags = DoBlue;
- ++i;
- }
-
- XStoreColors(X11->display, d->colormap, colorTable.data(), colorTable.count());
-}
-
-static QColormap **cmaps = 0;
-
-void QColormap::initialize()
-{
- Display *display = QX11Info::display();
- const int screens = ScreenCount(display);
-
- cmaps = new QColormap*[screens];
-
- for (int i = 0; i < screens; ++i) {
- cmaps[i] = new QColormap;
- QColormapPrivate * const d = cmaps[i]->d;
-
- bool use_stdcmap = false;
- int color_count = X11->color_count;
-
- // defaults
- d->depth = DefaultDepth(display, i);
- d->colormap = DefaultColormap(display, i);
- d->defaultColormap = true;
- d->visual = DefaultVisual(display, i);
- d->defaultVisual = true;
-
- Visual *argbVisual = 0;
-
- if (X11->visual && i == DefaultScreen(display)) {
- // only use the outside colormap on the default screen
- d->visual = find_visual(display, i, X11->visual->c_class,
- XVisualIDFromVisual(X11->visual),
- &d->depth, &d->defaultVisual);
- } else if ((X11->visual_class != -1 && X11->visual_class >= 0 && X11->visual_class < 6)
- || (X11->visual_id != -1)) {
- // look for a specific visual or type of visual
- d->visual = find_visual(display, i, X11->visual_class, X11->visual_id,
- &d->depth, &d->defaultVisual);
- } else if (QApplication::colorSpec() == QApplication::ManyColor) {
- // look for a TrueColor w/ a depth higher than 8bpp
- d->visual = find_visual(display, i, TrueColor, -1, &d->depth, &d->defaultVisual);
- if (d->depth <= 8) {
- d->visual = DefaultVisual(display, i);
- d->defaultVisual = true;
- color_count = 216;
- }
- } else if (!X11->custom_cmap) {
- XStandardColormap *stdcmap = 0;
- int ncmaps = 0;
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- int nvi;
- XVisualInfo templ;
- templ.screen = i;
- templ.depth = 32;
- templ.c_class = TrueColor;
- XVisualInfo *xvi = XGetVisualInfo(X11->display, VisualScreenMask |
- VisualDepthMask |
- VisualClassMask, &templ, &nvi);
- for (int idx = 0; idx < nvi; ++idx) {
- XRenderPictFormat *format = XRenderFindVisualFormat(X11->display,
- xvi[idx].visual);
- if (format->type == PictTypeDirect && format->direct.alphaMask) {
- argbVisual = xvi[idx].visual;
- break;
- }
- }
- XFree(xvi);
- }
-#endif
- if (XGetRGBColormaps(display, RootWindow(display, i),
- &stdcmap, &ncmaps, XA_RGB_DEFAULT_MAP)) {
- if (stdcmap) {
- for (int c = 0; c < ncmaps; ++c) {
- if (!stdcmap[c].red_max ||
- !stdcmap[c].green_max ||
- !stdcmap[c].blue_max ||
- !stdcmap[c].red_mult ||
- !stdcmap[c].green_mult ||
- !stdcmap[c].blue_mult)
- continue; // invalid stdcmap
-
- XVisualInfo proto;
- proto.visualid = stdcmap[c].visualid;
- proto.screen = i;
-
- int nvisuals = 0;
- XVisualInfo *vi = XGetVisualInfo(display, VisualIDMask | VisualScreenMask,
- &proto, &nvisuals);
- if (vi) {
- if (nvisuals > 0) {
- use_stdcmap = true;
-
- d->mode = ((vi[0].visual->c_class < StaticColor)
- ? Gray
- : ((vi[0].visual->c_class < TrueColor)
- ? Indexed
- : Direct));
-
- d->depth = vi[0].depth;
- d->colormap = stdcmap[c].colormap;
- d->defaultColormap = true;
- d->visual = vi[0].visual;
- d->defaultVisual = (d->visual == DefaultVisual(display, i));
-
- d->r_max = stdcmap[c].red_max + 1;
- d->g_max = stdcmap[c].green_max + 1;
- d->b_max = stdcmap[c].blue_max + 1;
-
- if (d->mode == Direct) {
- // calculate offsets
- d->r_shift = lowest_bit(d->visual->red_mask);
- d->g_shift = lowest_bit(d->visual->green_mask);
- d->b_shift = lowest_bit(d->visual->blue_mask);
- } else {
- d->r_shift = 0;
- d->g_shift = 0;
- d->b_shift = 0;
- }
- }
- XFree(vi);
- }
- break;
- }
- XFree(stdcmap);
- }
- }
- }
- if (!use_stdcmap) {
- switch (d->visual->c_class) {
- case StaticGray:
- d->mode = Gray;
-
- d->r_max = d->g_max = d->b_max = d->visual->map_entries;
- break;
-
- case XGrayScale:
- d->mode = Gray;
-
- // follow precedent set in libXmu...
- if (color_count != 0)
- d->r_max = d->g_max = d->b_max = color_count;
- else if (d->visual->map_entries > 65000)
- d->r_max = d->g_max = d->b_max = 4096;
- else if (d->visual->map_entries > 4000)
- d->r_max = d->g_max = d->b_max = 512;
- else if (d->visual->map_entries > 250)
- d->r_max = d->g_max = d->b_max = 12;
- else
- d->r_max = d->g_max = d->b_max = 4;
- break;
-
- case StaticColor:
- d->mode = Indexed;
-
- d->r_max = right_align(d->visual->red_mask) + 1;
- d->g_max = right_align(d->visual->green_mask) + 1;
- d->b_max = right_align(d->visual->blue_mask) + 1;
- break;
-
- case PseudoColor:
- d->mode = Indexed;
-
- // follow precedent set in libXmu...
- if (color_count != 0)
- d->r_max = d->g_max = d->b_max = cube_root(color_count);
- else if (d->visual->map_entries > 65000)
- d->r_max = d->g_max = d->b_max = 27;
- else if (d->visual->map_entries > 4000)
- d->r_max = d->g_max = d->b_max = 12;
- else if (d->visual->map_entries > 250)
- d->r_max = d->g_max = d->b_max = cube_root(d->visual->map_entries - 125);
- else
- d->r_max = d->g_max = d->b_max = cube_root(d->visual->map_entries);
- break;
-
- case TrueColor:
- case DirectColor:
- d->mode = Direct;
-
- d->r_max = right_align(d->visual->red_mask) + 1;
- d->g_max = right_align(d->visual->green_mask) + 1;
- d->b_max = right_align(d->visual->blue_mask) + 1;
-
- d->r_shift = lowest_bit(d->visual->red_mask);
- d->g_shift = lowest_bit(d->visual->green_mask);
- d->b_shift = lowest_bit(d->visual->blue_mask);
- break;
- }
- }
-
- bool ownColormap = false;
- if (X11->colormap && i == DefaultScreen(display)) {
- // only use the outside colormap on the default screen
- d->colormap = X11->colormap;
- d->defaultColormap = (d->colormap == DefaultColormap(display, i));
- } else if ((!use_stdcmap
- && (((d->visual->c_class & 1) && X11->custom_cmap)
- || d->visual != DefaultVisual(display, i)))
- || d->visual->c_class == DirectColor) {
- // allocate custom colormap (we always do this when using DirectColor visuals)
- d->colormap =
- XCreateColormap(display, RootWindow(display, i), d->visual,
- d->visual->c_class == DirectColor ? AllocAll : AllocNone);
- d->defaultColormap = false;
- ownColormap = true;
- }
-
- switch (d->mode) {
- case Gray:
- init_gray(d, i);
- break;
- case Indexed:
- init_indexed(d, i);
- break;
- case Direct:
- init_direct(d, ownColormap);
- break;
- }
-
- QX11InfoData *screen = X11->screens + i;
- screen->depth = d->depth;
- screen->visual = d->visual;
- screen->defaultVisual = d->defaultVisual;
- screen->colormap = d->colormap;
- screen->defaultColormap = d->defaultColormap;
- screen->cells = screen->visual->map_entries;
-
- if (argbVisual) {
- X11->argbVisuals[i] = argbVisual;
- X11->argbColormaps[i] = XCreateColormap(display, RootWindow(display, i), argbVisual, AllocNone);
- }
-
- // ###
- // We assume that 8bpp == pseudocolor, but this is not
- // always the case (according to the X server), so we need
- // to make sure that our internal data is setup in a way
- // that is compatible with our assumptions
- if (screen->visual->c_class == TrueColor && screen->depth == 8 && screen->cells == 8)
- screen->cells = 256;
- }
-}
-
-void QColormap::cleanup()
-{
- Display *display = QX11Info::display();
- const int screens = ScreenCount(display);
-
- for (int i = 0; i < screens; ++i)
- delete cmaps[i];
-
- delete [] cmaps;
- cmaps = 0;
-}
-
-
-QColormap QColormap::instance(int screen)
-{
- if (screen == -1)
- screen = QX11Info::appScreen();
- return *cmaps[screen];
-}
-
-/*! \internal
- Constructs a new colormap.
-*/
-QColormap::QColormap()
- : d(new QColormapPrivate)
-{}
-
-QColormap::QColormap(const QColormap &colormap)
- :d (colormap.d)
-{ d->ref.ref(); }
-
-QColormap::~QColormap()
-{
- if (!d->ref.deref()) {
- if (!d->defaultColormap)
- XFreeColormap(QX11Info::display(), d->colormap);
- delete d;
- }
-}
-
-QColormap::Mode QColormap::mode() const
-{ return d->mode; }
-
-int QColormap::depth() const
-{ return d->depth; }
-
-int QColormap::size() const
-{
- return (d->mode == Gray
- ? d->r_max
- : (d->mode == Indexed
- ? d->r_max * d->g_max * d->b_max
- : -1));
-}
-
-uint QColormap::pixel(const QColor &color) const
-{
- const QColor c = color.toRgb();
- const uint r = (c.ct.argb.red * d->r_max) >> 16;
- const uint g = (c.ct.argb.green * d->g_max) >> 16;
- const uint b = (c.ct.argb.blue * d->b_max) >> 16;
- if (d->mode != Direct) {
- if (d->mode == Gray)
- return d->pixels.at((r * 30 + g * 59 + b * 11) / 100);
- return d->pixels.at(r * d->g_max * d->b_max + g * d->b_max + b);
- }
- return (r << d->r_shift) + (g << d->g_shift) + (b << d->b_shift);
-}
-
-const QColor QColormap::colorAt(uint pixel) const
-{
- if (d->mode != Direct) {
- Q_ASSERT(pixel <= (uint)d->colors.size());
- return d->colors.at(pixel);
- }
-
- const int r = (((pixel & d->visual->red_mask) >> d->r_shift) << 8) / d->r_max;
- const int g = (((pixel & d->visual->green_mask) >> d->g_shift) << 8) / d->g_max;
- const int b = (((pixel & d->visual->blue_mask) >> d->b_shift) << 8) / d->b_max;
- return QColor(r, g, b);
-}
-
-const QVector<QColor> QColormap::colormap() const
-{ return d->colors; }
-
-QColormap &QColormap::operator=(const QColormap &colormap)
-{
- qAtomicAssign(d, colormap.d);
- return *this;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qcursor_x11.cpp b/src/gui/platforms/x11/qcursor_x11.cpp
deleted file mode 100644
index d0ed98e1fe..0000000000
--- a/src/gui/platforms/x11/qcursor_x11.cpp
+++ /dev/null
@@ -1,637 +0,0 @@
-/****************************************************************************
-**
-** 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 <qdebug.h>
-#include <qdatastream.h>
-#include <private/qcursor_p.h>
-#include <private/qt_x11_p.h>
-#include <private/qapplication_p.h>
-#include <qbitmap.h>
-#include <qcursor.h>
-#include <X11/cursorfont.h>
-
-#include <qlibrary.h>
-
-#ifndef QT_NO_XCURSOR
-# include <X11/Xcursor/Xcursor.h>
-#endif // QT_NO_XCURSOR
-
-#ifndef QT_NO_XFIXES
-# include <X11/extensions/Xfixes.h>
-#endif // QT_NO_XFIXES
-
-#include "qx11info_x11.h"
-#include <private/qpixmap_x11_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// Define QT_USE_APPROXIMATE_CURSORS when compiling if you REALLY want to
-// use the ugly X11 cursors.
-
-/*****************************************************************************
- Internal QCursorData class
- *****************************************************************************/
-
-QCursorData::QCursorData(Qt::CursorShape s)
- : cshape(s), bm(0), bmm(0), hx(0), hy(0), hcurs(0), pm(0), pmm(0)
-{
- ref = 1;
-}
-
-QCursorData::~QCursorData()
-{
- Display *dpy = X11 ? X11->display : (Display*)0;
-
- // Add in checking for the display too as on HP-UX
- // we seem to get a core dump as the cursor data is
- // deleted again from main() on exit...
- if (hcurs && dpy)
- XFreeCursor(dpy, hcurs);
- if (pm && dpy)
- XFreePixmap(dpy, pm);
- if (pmm && dpy)
- XFreePixmap(dpy, pmm);
- delete bm;
- delete bmm;
-}
-
-#ifndef QT_NO_CURSOR
-QCursor::QCursor(Qt::HANDLE cursor)
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- d = new QCursorData(Qt::CustomCursor);
- d->hcurs = cursor;
-}
-
-#endif
-
-QCursorData *QCursorData::setBitmap(const QBitmap &bitmap, const QBitmap &mask, int hotX, int hotY)
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (bitmap.depth() != 1 || mask.depth() != 1 || bitmap.size() != mask.size()) {
- qWarning("QCursor: Cannot create bitmap cursor; invalid bitmap(s)");
- QCursorData *c = qt_cursorTable[0];
- c->ref.ref();
- return c;
- }
- QCursorData *d = new QCursorData;
- d->ref = 1;
-
- extern QPixmap qt_toX11Pixmap(const QPixmap &pixmap); // qpixmap_x11.cpp
- d->bm = new QBitmap(qt_toX11Pixmap(bitmap));
- d->bmm = new QBitmap(qt_toX11Pixmap(mask));
-
- d->hcurs = 0;
- d->cshape = Qt::BitmapCursor;
- d->hx = hotX >= 0 ? hotX : bitmap.width() / 2;
- d->hy = hotY >= 0 ? hotY : bitmap.height() / 2;
- d->fg.red = 0x0000;
- d->fg.green = 0x0000;
- d->fg.blue = 0x0000;
- d->bg.red = 0xffff;
- d->bg.green = 0xffff;
- d->bg.blue = 0xffff;
- return d;
-}
-
-
-
-#ifndef QT_NO_CURSOR
-Qt::HANDLE QCursor::handle() const
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (!d->hcurs)
- d->update();
- return d->hcurs;
-}
-#endif
-
-QPoint QCursor::pos()
-{
- Window root;
- Window child;
- int root_x, root_y, win_x, win_y;
- uint buttons;
- Display* dpy = X11->display;
- for (int i = 0; i < ScreenCount(dpy); ++i) {
- if (XQueryPointer(dpy, QX11Info::appRootWindow(i), &root, &child, &root_x, &root_y,
- &win_x, &win_y, &buttons))
-
- return QPoint(root_x, root_y);
- }
- return QPoint();
-}
-
-/*! \internal
-*/
-#ifndef QT_NO_CURSOR
-int QCursor::x11Screen()
-{
- Window root;
- Window child;
- int root_x, root_y, win_x, win_y;
- uint buttons;
- Display* dpy = X11->display;
- for (int i = 0; i < ScreenCount(dpy); ++i) {
- if (XQueryPointer(dpy, QX11Info::appRootWindow(i), &root, &child, &root_x, &root_y,
- &win_x, &win_y, &buttons))
- return i;
- }
- return -1;
-}
-#endif
-
-void QCursor::setPos(int x, int y)
-{
- QPoint current, target(x, y);
-
- // this is copied from pos(), since we need the screen number for the correct
- // root window in the XWarpPointer call
- Window root;
- Window child;
- int root_x, root_y, win_x, win_y;
- uint buttons;
- Display* dpy = X11->display;
- int screen;
- for (screen = 0; screen < ScreenCount(dpy); ++screen) {
- if (XQueryPointer(dpy, QX11Info::appRootWindow(screen), &root, &child, &root_x, &root_y,
- &win_x, &win_y, &buttons)) {
- current = QPoint(root_x, root_y);
- break;
- }
- }
-
- if (screen >= ScreenCount(dpy))
- return;
-
- // Need to check, since some X servers generate null mouse move
- // events, causing looping in applications which call setPos() on
- // every mouse move event.
- //
- if (current == target)
- return;
-
- XWarpPointer(X11->display, XNone, QX11Info::appRootWindow(screen), 0, 0, 0, 0, x, y);
-}
-
-
-/*!
- \internal
-
- Creates the cursor.
-*/
-
-void QCursorData::update()
-{
- if (!QCursorData::initialized)
- QCursorData::initialize();
- if (hcurs)
- return;
-
- Display *dpy = X11->display;
- Window rootwin = QX11Info::appRootWindow();
-
- if (cshape == Qt::BitmapCursor) {
- extern QPixmap qt_toX11Pixmap(const QPixmap &pixmap); // qpixmap_x11.cpp
-#ifndef QT_NO_XRENDER
- if (!pixmap.isNull() && X11->use_xrender) {
- pixmap = qt_toX11Pixmap(pixmap);
- hcurs = XRenderCreateCursor (X11->display, pixmap.x11PictureHandle(), hx, hy);
- } else
-#endif
- {
- hcurs = XCreatePixmapCursor(dpy, bm->handle(), bmm->handle(), &fg, &bg, hx, hy);
- }
- return;
- }
-
- static const char *cursorNames[] = {
- "left_ptr",
- "up_arrow",
- "cross",
- "wait",
- "ibeam",
- "size_ver",
- "size_hor",
- "size_bdiag",
- "size_fdiag",
- "size_all",
- "blank",
- "split_v",
- "split_h",
- "pointing_hand",
- "forbidden",
- "whats_this",
- "left_ptr_watch",
- "openhand",
- "closedhand",
- "copy",
- "move",
- "link"
- };
-
-#ifndef QT_NO_XCURSOR
- if (X11->ptrXcursorLibraryLoadCursor) {
- // special case for non-standard dnd-* cursors
- switch (cshape) {
- case Qt::DragCopyCursor:
- hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, "dnd-copy");
- break;
- case Qt::DragMoveCursor:
- hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, "dnd-move");
- break;
- case Qt::DragLinkCursor:
- hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, "dnd-link");
- break;
- default:
- break;
- }
- if (!hcurs)
- hcurs = X11->ptrXcursorLibraryLoadCursor(dpy, cursorNames[cshape]);
- }
- if (hcurs)
- return;
-#endif // QT_NO_XCURSOR
-
- static const uchar cur_blank_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
- // Non-standard X11 cursors are created from bitmaps
-
-#ifndef QT_USE_APPROXIMATE_CURSORS
- static const uchar cur_ver_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0xc0, 0x03, 0xe0, 0x07, 0xf0, 0x0f,
- 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0xf0, 0x0f,
- 0xe0, 0x07, 0xc0, 0x03, 0x80, 0x01, 0x00, 0x00 };
- static const uchar mcur_ver_bits[] = {
- 0x00, 0x00, 0x80, 0x03, 0xc0, 0x07, 0xe0, 0x0f, 0xf0, 0x1f, 0xf8, 0x3f,
- 0xfc, 0x7f, 0xc0, 0x07, 0xc0, 0x07, 0xc0, 0x07, 0xfc, 0x7f, 0xf8, 0x3f,
- 0xf0, 0x1f, 0xe0, 0x0f, 0xc0, 0x07, 0x80, 0x03 };
- static const uchar cur_hor_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x08, 0x30, 0x18,
- 0x38, 0x38, 0xfc, 0x7f, 0xfc, 0x7f, 0x38, 0x38, 0x30, 0x18, 0x20, 0x08,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar mcur_hor_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x40, 0x04, 0x60, 0x0c, 0x70, 0x1c, 0x78, 0x3c,
- 0xfc, 0x7f, 0xfe, 0xff, 0xfe, 0xff, 0xfe, 0xff, 0xfc, 0x7f, 0x78, 0x3c,
- 0x70, 0x1c, 0x60, 0x0c, 0x40, 0x04, 0x00, 0x00 };
- static const uchar cur_bdiag_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x3e, 0x00, 0x3c, 0x00, 0x3e,
- 0x00, 0x37, 0x88, 0x23, 0xd8, 0x01, 0xf8, 0x00, 0x78, 0x00, 0xf8, 0x00,
- 0xf8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar mcur_bdiag_bits[] = {
- 0x00, 0x00, 0xc0, 0x7f, 0x80, 0x7f, 0x00, 0x7f, 0x00, 0x7e, 0x04, 0x7f,
- 0x8c, 0x7f, 0xdc, 0x77, 0xfc, 0x63, 0xfc, 0x41, 0xfc, 0x00, 0xfc, 0x01,
- 0xfc, 0x03, 0xfc, 0x07, 0x00, 0x00, 0x00, 0x00 };
- static const uchar cur_fdiag_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x01, 0xf8, 0x00, 0x78, 0x00,
- 0xf8, 0x00, 0xd8, 0x01, 0x88, 0x23, 0x00, 0x37, 0x00, 0x3e, 0x00, 0x3c,
- 0x00, 0x3e, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00 };
- static const uchar mcur_fdiag_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xfc, 0x03, 0xfc, 0x01, 0xfc, 0x00,
- 0xfc, 0x41, 0xfc, 0x63, 0xdc, 0x77, 0x8c, 0x7f, 0x04, 0x7f, 0x00, 0x7e,
- 0x00, 0x7f, 0x80, 0x7f, 0xc0, 0x7f, 0x00, 0x00 };
- static const uchar *cursor_bits16[] = {
- cur_ver_bits, mcur_ver_bits, cur_hor_bits, mcur_hor_bits,
- cur_bdiag_bits, mcur_bdiag_bits, cur_fdiag_bits, mcur_fdiag_bits,
- 0, 0, cur_blank_bits, cur_blank_bits };
-
- static const uchar vsplit_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xe0, 0x03, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xff, 0x7f, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x7f, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xe0, 0x03, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar vsplitm_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x00, 0xe0, 0x03, 0x00, 0x00, 0xf0, 0x07, 0x00,
- 0x00, 0xf8, 0x0f, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00,
- 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00,
- 0x80, 0xff, 0xff, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00,
- 0x00, 0xc0, 0x01, 0x00, 0x00, 0xf8, 0x0f, 0x00, 0x00, 0xf0, 0x07, 0x00,
- 0x00, 0xe0, 0x03, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar hsplit_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x41, 0x82, 0x00, 0x80, 0x41, 0x82, 0x01, 0xc0, 0x7f, 0xfe, 0x03,
- 0x80, 0x41, 0x82, 0x01, 0x00, 0x41, 0x82, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
- 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar hsplitm_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
- 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe2, 0x47, 0x00, 0x00, 0xe3, 0xc7, 0x00,
- 0x80, 0xe3, 0xc7, 0x01, 0xc0, 0xff, 0xff, 0x03, 0xe0, 0xff, 0xff, 0x07,
- 0xc0, 0xff, 0xff, 0x03, 0x80, 0xe3, 0xc7, 0x01, 0x00, 0xe3, 0xc7, 0x00,
- 0x00, 0xe2, 0x47, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
- 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
- static const uchar whatsthis_bits[] = {
- 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x05, 0xf0, 0x07, 0x00,
- 0x09, 0x18, 0x0e, 0x00, 0x11, 0x1c, 0x0e, 0x00, 0x21, 0x1c, 0x0e, 0x00,
- 0x41, 0x1c, 0x0e, 0x00, 0x81, 0x1c, 0x0e, 0x00, 0x01, 0x01, 0x07, 0x00,
- 0x01, 0x82, 0x03, 0x00, 0xc1, 0xc7, 0x01, 0x00, 0x49, 0xc0, 0x01, 0x00,
- 0x95, 0xc0, 0x01, 0x00, 0x93, 0xc0, 0x01, 0x00, 0x21, 0x01, 0x00, 0x00,
- 0x20, 0xc1, 0x01, 0x00, 0x40, 0xc2, 0x01, 0x00, 0x40, 0x02, 0x00, 0x00,
- 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
- static const uchar whatsthism_bits[] = {
- 0x01, 0x00, 0x00, 0x00, 0x03, 0xf0, 0x07, 0x00, 0x07, 0xf8, 0x0f, 0x00,
- 0x0f, 0xfc, 0x1f, 0x00, 0x1f, 0x3e, 0x1f, 0x00, 0x3f, 0x3e, 0x1f, 0x00,
- 0x7f, 0x3e, 0x1f, 0x00, 0xff, 0x3e, 0x1f, 0x00, 0xff, 0x9d, 0x0f, 0x00,
- 0xff, 0xc3, 0x07, 0x00, 0xff, 0xe7, 0x03, 0x00, 0x7f, 0xe0, 0x03, 0x00,
- 0xf7, 0xe0, 0x03, 0x00, 0xf3, 0xe0, 0x03, 0x00, 0xe1, 0xe1, 0x03, 0x00,
- 0xe0, 0xe1, 0x03, 0x00, 0xc0, 0xe3, 0x03, 0x00, 0xc0, 0xe3, 0x03, 0x00,
- 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
- static const uchar busy_bits[] = {
- 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
- 0x09, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
- 0x41, 0xe0, 0xff, 0x00, 0x81, 0x20, 0x80, 0x00, 0x01, 0xe1, 0xff, 0x00,
- 0x01, 0x42, 0x40, 0x00, 0xc1, 0x47, 0x40, 0x00, 0x49, 0x40, 0x55, 0x00,
- 0x95, 0x80, 0x2a, 0x00, 0x93, 0x00, 0x15, 0x00, 0x21, 0x01, 0x0a, 0x00,
- 0x20, 0x01, 0x11, 0x00, 0x40, 0x82, 0x20, 0x00, 0x40, 0x42, 0x44, 0x00,
- 0x80, 0x41, 0x4a, 0x00, 0x00, 0x40, 0x55, 0x00, 0x00, 0xe0, 0xff, 0x00,
- 0x00, 0x20, 0x80, 0x00, 0x00, 0xe0, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
- static const uchar busym_bits[] = {
- 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
- 0x0f, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00,
- 0x7f, 0xe0, 0xff, 0x00, 0xff, 0xe0, 0xff, 0x00, 0xff, 0xe1, 0xff, 0x00,
- 0xff, 0xc3, 0x7f, 0x00, 0xff, 0xc7, 0x7f, 0x00, 0x7f, 0xc0, 0x7f, 0x00,
- 0xf7, 0x80, 0x3f, 0x00, 0xf3, 0x00, 0x1f, 0x00, 0xe1, 0x01, 0x0e, 0x00,
- 0xe0, 0x01, 0x1f, 0x00, 0xc0, 0x83, 0x3f, 0x00, 0xc0, 0xc3, 0x7f, 0x00,
- 0x80, 0xc1, 0x7f, 0x00, 0x00, 0xc0, 0x7f, 0x00, 0x00, 0xe0, 0xff, 0x00,
- 0x00, 0xe0, 0xff, 0x00, 0x00, 0xe0, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
- static const uchar * const cursor_bits32[] = {
- vsplit_bits, vsplitm_bits, hsplit_bits, hsplitm_bits,
- 0, 0, 0, 0, whatsthis_bits, whatsthism_bits, busy_bits, busym_bits
- };
-
- static const uchar forbidden_bits[] = {
- 0x00,0x00,0x00,0x80,0x1f,0x00,0xe0,0x7f,0x00,0xf0,0xf0,0x00,0x38,0xc0,0x01,
- 0x7c,0x80,0x03,0xec,0x00,0x03,0xce,0x01,0x07,0x86,0x03,0x06,0x06,0x07,0x06,
- 0x06,0x0e,0x06,0x06,0x1c,0x06,0x0e,0x38,0x07,0x0c,0x70,0x03,0x1c,0xe0,0x03,
- 0x38,0xc0,0x01,0xf0,0xe0,0x00,0xe0,0x7f,0x00,0x80,0x1f,0x00,0x00,0x00,0x00 };
-
- static const uchar forbiddenm_bits[] = {
- 0x80,0x1f,0x00,0xe0,0x7f,0x00,0xf0,0xff,0x00,0xf8,0xff,0x01,0xfc,0xf0,0x03,
- 0xfe,0xc0,0x07,0xfe,0x81,0x07,0xff,0x83,0x0f,0xcf,0x07,0x0f,0x8f,0x0f,0x0f,
- 0x0f,0x1f,0x0f,0x0f,0x3e,0x0f,0x1f,0xfc,0x0f,0x1e,0xf8,0x07,0x3e,0xf0,0x07,
- 0xfc,0xe0,0x03,0xf8,0xff,0x01,0xf0,0xff,0x00,0xe0,0x7f,0x00,0x80,0x1f,0x00};
-
- static const uchar openhand_bits[] = {
- 0x80,0x01,0x58,0x0e,0x64,0x12,0x64,0x52,0x48,0xb2,0x48,0x92,
- 0x16,0x90,0x19,0x80,0x11,0x40,0x02,0x40,0x04,0x40,0x04,0x20,
- 0x08,0x20,0x10,0x10,0x20,0x10,0x00,0x00};
- static const uchar openhandm_bits[] = {
- 0x80,0x01,0xd8,0x0f,0xfc,0x1f,0xfc,0x5f,0xf8,0xff,0xf8,0xff,
- 0xf6,0xff,0xff,0xff,0xff,0x7f,0xfe,0x7f,0xfc,0x7f,0xfc,0x3f,
- 0xf8,0x3f,0xf0,0x1f,0xe0,0x1f,0x00,0x00};
- static const uchar closedhand_bits[] = {
- 0x00,0x00,0x00,0x00,0x00,0x00,0xb0,0x0d,0x48,0x32,0x08,0x50,
- 0x10,0x40,0x18,0x40,0x04,0x40,0x04,0x20,0x08,0x20,0x10,0x10,
- 0x20,0x10,0x20,0x10,0x00,0x00,0x00,0x00};
- static const uchar closedhandm_bits[] = {
- 0x00,0x00,0x00,0x00,0x00,0x00,0xb0,0x0d,0xf8,0x3f,0xf8,0x7f,
- 0xf0,0x7f,0xf8,0x7f,0xfc,0x7f,0xfc,0x3f,0xf8,0x3f,0xf0,0x1f,
- 0xe0,0x1f,0xe0,0x1f,0x00,0x00,0x00,0x00};
-
- static const uchar * const cursor_bits20[] = {
- forbidden_bits, forbiddenm_bits
- };
-
- if ((cshape >= Qt::SizeVerCursor && cshape < Qt::SizeAllCursor)
- || cshape == Qt::BlankCursor) {
- XColor bg, fg;
- bg.red = 255 << 8;
- bg.green = 255 << 8;
- bg.blue = 255 << 8;
- fg.red = 0;
- fg.green = 0;
- fg.blue = 0;
- int i = (cshape - Qt::SizeVerCursor) * 2;
- pm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char*>(cursor_bits16[i]), 16, 16);
- pmm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char*>(cursor_bits16[i + 1]), 16, 16);
- hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 8, 8);
- } else if ((cshape >= Qt::SplitVCursor && cshape <= Qt::SplitHCursor)
- || cshape == Qt::WhatsThisCursor || cshape == Qt::BusyCursor) {
- XColor bg, fg;
- bg.red = 255 << 8;
- bg.green = 255 << 8;
- bg.blue = 255 << 8;
- fg.red = 0;
- fg.green = 0;
- fg.blue = 0;
- int i = (cshape - Qt::SplitVCursor) * 2;
- pm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char *>(cursor_bits32[i]), 32, 32);
- pmm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char *>(cursor_bits32[i + 1]), 32, 32);
- int hs = (cshape == Qt::PointingHandCursor || cshape == Qt::WhatsThisCursor
- || cshape == Qt::BusyCursor) ? 0 : 16;
- hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, hs, hs);
- } else if (cshape == Qt::ForbiddenCursor) {
- XColor bg, fg;
- bg.red = 255 << 8;
- bg.green = 255 << 8;
- bg.blue = 255 << 8;
- fg.red = 0;
- fg.green = 0;
- fg.blue = 0;
- int i = (cshape - Qt::ForbiddenCursor) * 2;
- pm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char *>(cursor_bits20[i]), 20, 20);
- pmm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char *>(cursor_bits20[i + 1]), 20, 20);
- hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 10, 10);
- } else if (cshape == Qt::OpenHandCursor || cshape == Qt::ClosedHandCursor) {
- XColor bg, fg;
- bg.red = 255 << 8;
- bg.green = 255 << 8;
- bg.blue = 255 << 8;
- fg.red = 0;
- fg.green = 0;
- fg.blue = 0;
- bool open = cshape == Qt::OpenHandCursor;
- pm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char *>(open ? openhand_bits : closedhand_bits), 16, 16);
- pmm = XCreateBitmapFromData(dpy, rootwin, reinterpret_cast<const char *>(open ? openhandm_bits : closedhandm_bits), 16, 16);
- hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 8, 8);
- } else if (cshape == Qt::DragCopyCursor || cshape == Qt::DragMoveCursor
- || cshape == Qt::DragLinkCursor) {
- XColor bg, fg;
- bg.red = 255 << 8;
- bg.green = 255 << 8;
- bg.blue = 255 << 8;
- fg.red = 0;
- fg.green = 0;
- fg.blue = 0;
- QImage image = QApplicationPrivate::instance()->getPixmapCursor(cshape).toImage();
- pm = QX11PixmapData::createBitmapFromImage(image);
- pmm = QX11PixmapData::createBitmapFromImage(image.createAlphaMask().convertToFormat(QImage::Format_MonoLSB));
- hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 8, 8);
- }
-
- if (hcurs)
- {
-#ifndef QT_NO_XFIXES
- if (X11->use_xfixes && X11->ptrXFixesSetCursorName)
- X11->ptrXFixesSetCursorName(dpy, hcurs, cursorNames[cshape]);
-#endif /* ! QT_NO_XFIXES */
- return;
- }
-
-#endif /* ! QT_USE_APPROXIMATE_CURSORS */
-
- uint sh;
- switch (cshape) { // map Q cursor to X cursor
- case Qt::ArrowCursor:
- sh = XC_left_ptr;
- break;
- case Qt::UpArrowCursor:
- sh = XC_center_ptr;
- break;
- case Qt::CrossCursor:
- sh = XC_crosshair;
- break;
- case Qt::WaitCursor:
- sh = XC_watch;
- break;
- case Qt::IBeamCursor:
- sh = XC_xterm;
- break;
- case Qt::SizeAllCursor:
- sh = XC_fleur;
- break;
- case Qt::PointingHandCursor:
- sh = XC_hand2;
- break;
-#ifdef QT_USE_APPROXIMATE_CURSORS
- case Qt::SizeBDiagCursor:
- sh = XC_top_right_corner;
- break;
- case Qt::SizeFDiagCursor:
- sh = XC_bottom_right_corner;
- break;
- case Qt::BlankCursor:
- XColor bg, fg;
- bg.red = 255 << 8;
- bg.green = 255 << 8;
- bg.blue = 255 << 8;
- fg.red = 0;
- fg.green = 0;
- fg.blue = 0;
- pm = XCreateBitmapFromData(dpy, rootwin, cur_blank_bits, 16, 16);
- pmm = XCreateBitmapFromData(dpy, rootwin, cur_blank_bits, 16, 16);
- hcurs = XCreatePixmapCursor(dpy, pm, pmm, &fg, &bg, 8, 8);
- return;
- break;
- case Qt::SizeVerCursor:
- case Qt::SplitVCursor:
- sh = XC_sb_v_double_arrow;
- break;
- case Qt::SizeHorCursor:
- case Qt::SplitHCursor:
- sh = XC_sb_h_double_arrow;
- break;
- case Qt::WhatsThisCursor:
- sh = XC_question_arrow;
- break;
- case Qt::ForbiddenCursor:
- sh = XC_circle;
- break;
- case Qt::BusyCursor:
- sh = XC_watch;
- break;
- case Qt::DragCopyCursor:
- sh = XC_tcross;
- break;
- case Qt::DragLinkCursor:
- sh = XC_center_ptr;
- break;
- case Qt::DragMoveCursor:
- sh = XC_top_left_arrow;
- break;
-#endif /* QT_USE_APPROXIMATE_CURSORS */
- default:
- qWarning("QCursor::update: Invalid cursor shape %d", cshape);
- return;
- }
- hcurs = XCreateFontCursor(dpy, sh);
-
-#ifndef QT_NO_XFIXES
- if (X11->use_xfixes && X11->ptrXFixesSetCursorName)
- X11->ptrXFixesSetCursorName(dpy, hcurs, cursorNames[cshape]);
-#endif /* ! QT_NO_XFIXES */
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qdesktopwidget_x11.cpp b/src/gui/platforms/x11/qdesktopwidget_x11.cpp
deleted file mode 100644
index b0f12903a1..0000000000
--- a/src/gui/platforms/x11/qdesktopwidget_x11.cpp
+++ /dev/null
@@ -1,406 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qlibrary.h"
-#include "qt_x11_p.h"
-#include "qvariant.h"
-#include "qwidget_p.h"
-#include "qx11info_x11.h"
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-// defined in qwidget_x11.cpp
-extern int qt_x11_create_desktop_on_screen;
-
-
-// function to update the workarea of the screen
-static bool qt_desktopwidget_workarea_dirty = true;
-void qt_desktopwidget_update_workarea()
-{
- qt_desktopwidget_workarea_dirty = true;
-}
-
-
-class QSingleDesktopWidget : public QWidget
-{
-public:
- QSingleDesktopWidget();
- ~QSingleDesktopWidget();
-};
-
-QSingleDesktopWidget::QSingleDesktopWidget()
- : QWidget(0, Qt::Desktop)
-{
-}
-
-QSingleDesktopWidget::~QSingleDesktopWidget()
-{
- const QObjectList &childList = children();
- for (int i = childList.size(); i > 0 ;) {
- --i;
- childList.at(i)->setParent(0);
- }
-}
-
-
-class QDesktopWidgetPrivate : public QWidgetPrivate
-{
-public:
- QDesktopWidgetPrivate();
- ~QDesktopWidgetPrivate();
-
- void init();
-
- bool use_xinerama;
- int defaultScreen;
- int screenCount;
-
- QWidget **screens;
- QRect *rects;
- QRect *workareas;
-};
-
-QDesktopWidgetPrivate::QDesktopWidgetPrivate()
- : use_xinerama(false), defaultScreen(0), screenCount(1),
- screens(0), rects(0), workareas(0)
-{
-}
-
-QDesktopWidgetPrivate::~QDesktopWidgetPrivate()
-{
- if (screens) {
- for (int i = 0; i < screenCount; ++i) {
- if (i == defaultScreen) continue;
- delete screens[i];
- screens[i] = 0;
- }
-
- free (screens);
- }
-
- if (rects) delete [] rects;
- if (workareas) delete [] workareas;
-}
-
-void QDesktopWidgetPrivate::init()
-{
- // get the screen count
- int newScreenCount = ScreenCount(X11->display);
-#ifndef QT_NO_XINERAMA
-
- XineramaScreenInfo *xinerama_screeninfo = 0;
-
- // we ignore the Xinerama extension when using the display is
- // using traditional multi-screen (with multiple root windows)
- if (newScreenCount == 1
- && X11->ptrXineramaQueryExtension
- && X11->ptrXineramaIsActive
- && X11->ptrXineramaQueryScreens) {
- int unused;
- use_xinerama = (X11->ptrXineramaQueryExtension(X11->display, &unused, &unused)
- && X11->ptrXineramaIsActive(X11->display));
- }
-
- if (use_xinerama) {
- xinerama_screeninfo =
- X11->ptrXineramaQueryScreens(X11->display, &newScreenCount);
- }
-
- if (xinerama_screeninfo) {
- defaultScreen = 0;
- } else
-#endif // QT_NO_XINERAMA
- {
- defaultScreen = DefaultScreen(X11->display);
- newScreenCount = ScreenCount(X11->display);
- use_xinerama = false;
- }
-
- delete [] rects;
- rects = new QRect[newScreenCount];
- delete [] workareas;
- workareas = new QRect[newScreenCount];
-
- // get the geometry of each screen
- int i, j, x, y, w, h;
- for (i = 0, j = 0; i < newScreenCount; i++, j++) {
-
-#ifndef QT_NO_XINERAMA
- if (use_xinerama) {
- x = xinerama_screeninfo[i].x_org;
- y = xinerama_screeninfo[i].y_org;
- w = xinerama_screeninfo[i].width;
- h = xinerama_screeninfo[i].height;
- } else
-#endif // QT_NO_XINERAMA
- {
- x = 0;
- y = 0;
- w = WidthOfScreen(ScreenOfDisplay(X11->display, i));
- h = HeightOfScreen(ScreenOfDisplay(X11->display, i));
- }
-
- rects[j].setRect(x, y, w, h);
-
- if (use_xinerama && j > 0 && rects[j-1].intersects(rects[j])) {
- // merge a "cloned" screen with the previous, hiding all crtcs
- // that are currently showing a sub-rect of the previous screen
- if ((rects[j].width()*rects[j].height()) >
- (rects[j-1].width()*rects[j-1].height()))
- rects[j-1] = rects[j];
- j--;
- }
-
- workareas[i] = QRect();
- }
-
- if (screens) {
- // leaks QWidget* pointers on purpose, can't delete them as pointer escapes
- screens = q_check_ptr((QWidget**) realloc(screens, j * sizeof(QWidget*)));
- if (j > screenCount)
- memset(&screens[screenCount], 0, (j-screenCount) * sizeof(QWidget*));
- }
-
- screenCount = j;
-
-#ifndef QT_NO_XINERAMA
- if (use_xinerama && screenCount == 1)
- use_xinerama = false;
-
- if (xinerama_screeninfo)
- XFree(xinerama_screeninfo);
-#endif // QT_NO_XINERAMA
-
-}
-
-// the QDesktopWidget itself will be created on the default screen
-// as qt_x11_create_desktop_on_screen defaults to -1
-QDesktopWidget::QDesktopWidget()
- : QWidget(*new QDesktopWidgetPrivate, 0, Qt::Desktop)
-{
- Q_D(QDesktopWidget);
- d->init();
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
- Q_D(const QDesktopWidget);
- return d->use_xinerama;
-}
-
-int QDesktopWidget::primaryScreen() const
-{
- Q_D(const QDesktopWidget);
- return d->defaultScreen;
-}
-
-int QDesktopWidget::numScreens() const
-{
- Q_D(const QDesktopWidget);
- return d->screenCount;
-}
-
-QWidget *QDesktopWidget::screen(int screen)
-{
- Q_D(QDesktopWidget);
- if (d->use_xinerama)
- return this;
-
- if (screen < 0 || screen >= d->screenCount)
- screen = d->defaultScreen;
-
- if (! d->screens) {
- d->screens = (QWidget**) calloc( d->screenCount, sizeof(QWidget*));
- d->screens[d->defaultScreen] = this;
- }
-
- if (! d->screens[screen] || // not created yet
- ! (d->screens[screen]->windowType() == Qt::Desktop)) { // reparented away
- qt_x11_create_desktop_on_screen = screen;
- d->screens[screen] = new QSingleDesktopWidget;
- qt_x11_create_desktop_on_screen = -1;
- }
-
- return d->screens[screen];
-}
-
-const QRect QDesktopWidget::availableGeometry(int screen) const
-{
- Q_D(const QDesktopWidget);
- if (qt_desktopwidget_workarea_dirty) {
- // the workareas are dirty, invalidate them
- for (int i = 0; i < d->screenCount; ++i)
- d->workareas[i] = QRect();
- qt_desktopwidget_workarea_dirty = false;
- }
-
- if (screen < 0 || screen >= d->screenCount)
- screen = d->defaultScreen;
-
- if (d->workareas[screen].isValid())
- return d->workareas[screen];
-
- if (X11->isSupportedByWM(ATOM(_NET_WORKAREA))) {
- int x11Screen = isVirtualDesktop() ? DefaultScreen(X11->display) : screen;
-
- Atom ret;
- int format, e;
- unsigned char *data = 0;
- unsigned long nitems, after;
-
- e = XGetWindowProperty(X11->display,
- QX11Info::appRootWindow(x11Screen),
- ATOM(_NET_WORKAREA), 0, 4, False, XA_CARDINAL,
- &ret, &format, &nitems, &after, &data);
-
- QRect workArea;
- if (e == Success && ret == XA_CARDINAL &&
- format == 32 && nitems == 4) {
- long *workarea = (long *) data;
- workArea = QRect(workarea[0], workarea[1], workarea[2], workarea[3]);
- } else {
- workArea = screenGeometry(screen);
- }
-
- if (isVirtualDesktop()) {
- // intersect the workarea (which spawns all Xinerama screens) with the rect for the
- // requested screen
- workArea &= screenGeometry(screen);
- }
-
- d->workareas[screen] = workArea;
-
- if (data)
- XFree(data);
- } else {
- d->workareas[screen] = screenGeometry(screen);
- }
-
- return d->workareas[screen];
-}
-
-const QRect QDesktopWidget::screenGeometry(int screen) const
-{
- Q_D(const QDesktopWidget);
- if (screen < 0 || screen >= d->screenCount)
- screen = d->defaultScreen;
-
- return d->rects[screen];
-}
-
-int QDesktopWidget::screenNumber(const QWidget *widget) const
-{
- Q_D(const QDesktopWidget);
- if (!widget)
- return d->defaultScreen;
-
-#ifndef QT_NO_XINERAMA
- if (d->use_xinerama) {
- // this is how we do it for xinerama
- QRect frame = widget->frameGeometry();
- if (!widget->isWindow())
- frame.moveTopLeft(widget->mapToGlobal(QPoint(0, 0)));
-
- int maxSize = -1;
- int maxScreen = -1;
-
- for (int i = 0; i < d->screenCount; ++i) {
- QRect sect = d->rects[i].intersected(frame);
- int size = sect.width() * sect.height();
- if (size > maxSize && sect.width() > 0 && sect.height() > 0) {
- maxSize = size;
- maxScreen = i;
- }
- }
- return maxScreen;
- }
-#endif // QT_NO_XINERAMA
-
- return widget->x11Info().screen();
-}
-
-int QDesktopWidget::screenNumber(const QPoint &point) const
-{
- Q_D(const QDesktopWidget);
- int closestScreen = -1;
- int shortestDistance = INT_MAX;
- for (int i = 0; i < d->screenCount; ++i) {
- int thisDistance = d->pointToRect(point, d->rects[i]);
- if (thisDistance < shortestDistance) {
- shortestDistance = thisDistance;
- closestScreen = i;
- }
- }
- return closestScreen;
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *event)
-{
- Q_D(QDesktopWidget);
- int oldScreenCount = d->screenCount;
- QVector<QRect> oldRects(oldScreenCount);
- for (int i = 0; i < oldScreenCount; ++i) {
- oldRects[i] = d->rects[i];
- }
-
- d->init();
-
- for (int i = 0; i < qMin(oldScreenCount, d->screenCount); ++i) {
- if (oldRects.at(i) != d->rects[i])
- emit resized(i);
- }
-
- if (oldScreenCount != d->screenCount) {
- emit screenCountChanged(d->screenCount);
- }
-
- qt_desktopwidget_workarea_dirty = true;
- QWidget::resizeEvent(event);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qdnd_x11.cpp b/src/gui/platforms/x11/qdnd_x11.cpp
deleted file mode 100644
index 9ff1543e51..0000000000
--- a/src/gui/platforms/x11/qdnd_x11.cpp
+++ /dev/null
@@ -1,2072 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-
-#ifndef QT_NO_DRAGANDDROP
-
-#include "qwidget.h"
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qbitmap.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qiodevice.h"
-#include "qpointer.h"
-#include "qcursor.h"
-#include "qelapsedtimer.h"
-#include "qvariant.h"
-#include "qvector.h"
-#include "qurl.h"
-#include "qdebug.h"
-#include "qimagewriter.h"
-#include "qbuffer.h"
-#include "qtextcodec.h"
-
-#include "qdnd_p.h"
-#include "qapplication_p.h"
-#include "qt_x11_p.h"
-#include "qx11info_x11.h"
-
-#include "qwidget_p.h"
-#include "qcursor_p.h"
-
-QT_BEGIN_NAMESPACE
-
-// #define DND_DEBUG
-#ifdef DND_DEBUG
-#define DEBUG qDebug
-#else
-#define DEBUG if(0) qDebug
-#endif
-
-#ifdef DND_DEBUG
-#define DNDDEBUG qDebug()
-#else
-#define DNDDEBUG if(0) qDebug()
-#endif
-
-static int findXdndDropTransactionByWindow(Window window)
-{
- int at = -1;
- for (int i = 0; i < X11->dndDropTransactions.count(); ++i) {
- const QXdndDropTransaction &t = X11->dndDropTransactions.at(i);
- if (t.target == window || t.proxy_target == window) {
- at = i;
- break;
- }
- }
- return at;
-}
-
-static int findXdndDropTransactionByTime(Time timestamp)
-{
- int at = -1;
- for (int i = 0; i < X11->dndDropTransactions.count(); ++i) {
- const QXdndDropTransaction &t = X11->dndDropTransactions.at(i);
- if (t.timestamp == timestamp) {
- at = i;
- break;
- }
- }
- return at;
-}
-
-// timer used to discard old XdndDrop transactions
-static int transaction_expiry_timer = -1;
-enum { XdndDropTransactionTimeout = 5000 }; // 5 seconds
-
-static void restartXdndDropExpiryTimer()
-{
- if (transaction_expiry_timer != -1)
- QDragManager::self()->killTimer(transaction_expiry_timer);
- transaction_expiry_timer = QDragManager::self()->startTimer(XdndDropTransactionTimeout);
-}
-
-
-// find an ancestor with XdndAware on it
-static Window findXdndAwareParent(Window window)
-{
- Window target = 0;
- forever {
- // check if window has XdndAware
- Atom type = 0;
- int f;
- unsigned long n, a;
- unsigned char *data = 0;
- if (XGetWindowProperty(X11->display, window, ATOM(XdndAware), 0, 0, False,
- AnyPropertyType, &type, &f,&n,&a,&data) == Success) {
- if (data)
- XFree(data);
- if (type) {
- target = window;
- break;
- }
- }
-
- // try window's parent
- Window root;
- Window parent;
- Window *children;
- uint unused;
- if (!XQueryTree(X11->display, window, &root, &parent, &children, &unused))
- break;
- if (children)
- XFree(children);
- if (window == root)
- break;
- window = parent;
- }
- return target;
-}
-
-
-
-
-// and all this stuff is copied -into- qapp_x11.cpp
-
-static void handle_xdnd_position(QWidget *, const XEvent *, bool);
-static void handle_xdnd_status(QWidget * w, const XEvent * xe, bool /*passive*/);
-
-const int xdnd_version = 5;
-
-static Qt::DropAction xdndaction_to_qtaction(Atom atom)
-{
- if (atom == ATOM(XdndActionCopy) || atom == 0)
- return Qt::CopyAction;
- if (atom == ATOM(XdndActionLink))
- return Qt::LinkAction;
- if (atom == ATOM(XdndActionMove))
- return Qt::MoveAction;
- return Qt::CopyAction;
-}
-
-static int qtaction_to_xdndaction(Qt::DropAction a)
-{
- switch (a) {
- case Qt::CopyAction:
- return ATOM(XdndActionCopy);
- case Qt::LinkAction:
- return ATOM(XdndActionLink);
- case Qt::MoveAction:
- case Qt::TargetMoveAction:
- return ATOM(XdndActionMove);
- case Qt::IgnoreAction:
- return XNone;
- default:
- return ATOM(XdndActionCopy);
- }
-}
-
-// clean up the stuff used.
-static void qt_xdnd_cleanup();
-
-static void qt_xdnd_send_leave();
-
-// real variables:
-// xid of current drag source
-static Atom qt_xdnd_dragsource_xid = 0;
-
-// the types in this drop. 100 is no good, but at least it's big.
-const int qt_xdnd_max_type = 100;
-static Atom qt_xdnd_types[qt_xdnd_max_type + 1];
-
-// timer used when target wants "continuous" move messages (eg. scroll)
-static int heartbeat = -1;
-// rectangle in which the answer will be the same
-static QRect qt_xdnd_source_sameanswer;
-// top-level window we sent position to last.
-static Window qt_xdnd_current_target;
-// window to send events to (always valid if qt_xdnd_current_target)
-static Window qt_xdnd_current_proxy_target;
-static Time qt_xdnd_source_current_time;
-
-// widget we forwarded position to last, and local position
-static QPointer<QWidget> qt_xdnd_current_widget;
-static QPoint qt_xdnd_current_position;
-// timestamp from the XdndPosition and XdndDrop
-static Time qt_xdnd_target_current_time;
-// screen number containing the pointer... -1 means default
-static int qt_xdnd_current_screen = -1;
-// state of dragging... true if dragging, false if not
-bool qt_xdnd_dragging = false;
-
-static bool waiting_for_status = false;
-
-// used to preset each new QDragMoveEvent
-static Qt::DropAction last_target_accepted_action = Qt::IgnoreAction;
-
-// Shift/Ctrl handling, and final drop status
-static Qt::DropAction global_accepted_action = Qt::CopyAction;
-static Qt::DropActions possible_actions = Qt::IgnoreAction;
-
-// for embedding only
-static QWidget* current_embedding_widget = 0;
-static XEvent last_enter_event;
-
-// cursors
-static QCursor *noDropCursor = 0;
-static QCursor *moveCursor = 0;
-static QCursor *copyCursor = 0;
-static QCursor *linkCursor = 0;
-
-static QPixmap *defaultPm = 0;
-
-static const int default_pm_hotx = -2;
-static const int default_pm_hoty = -16;
-static const char* const default_pm[] = {
-"13 9 3 1",
-". c None",
-" c #000000",
-"X c #FFFFFF",
-"X X X X X X X",
-" X X X X X X ",
-"X ......... X",
-" X.........X ",
-"X ......... X",
-" X.........X ",
-"X ......... X",
-" X X X X X X ",
-"X X X X X X X"
-};
-
-class QShapedPixmapWidget : public QWidget
-{
- Q_OBJECT
-public:
- QShapedPixmapWidget(QWidget* w) :
- QWidget(w,
- Qt::Tool | Qt::FramelessWindowHint
- | Qt::X11BypassWindowManagerHint
- | Qt::BypassGraphicsProxyWidget)
- {
- setAttribute(Qt::WA_X11NetWmWindowTypeDND);
- }
-
- void setPixmap(const QPixmap &pm)
- {
- QBitmap mask = pm.mask();
- if (!mask.isNull()) {
- setMask(mask);
- } else {
- clearMask();
- }
- resize(pm.width(),pm.height());
- pixmap = pm;
- update();
- }
- QPoint pm_hot;
-
-protected:
- QPixmap pixmap;
- void paintEvent(QPaintEvent*)
- {
- QPainter p(this);
- p.drawPixmap(0, 0, pixmap);
- }
-};
-
-#include "qdnd_x11.moc"
-
-struct XdndData {
- QShapedPixmapWidget *deco;
- QWidget* desktop_proxy;
-};
-
-static XdndData xdnd_data = { 0, 0 };
-
-class QExtraWidget : public QWidget
-{
- Q_DECLARE_PRIVATE(QWidget)
-public:
- inline QWExtra* extraData();
- inline QTLWExtra* topData();
-};
-
-inline QWExtra* QExtraWidget::extraData() { return d_func()->extraData(); }
-inline QTLWExtra* QExtraWidget::topData() { return d_func()->topData(); }
-
-
-static WId xdndProxy(WId w)
-{
- Atom type = XNone;
- int f;
- unsigned long n, a;
- unsigned char *retval = 0;
- XGetWindowProperty(X11->display, w, ATOM(XdndProxy), 0, 1, False,
- XA_WINDOW, &type, &f,&n,&a,&retval);
- WId *proxy_id_ptr = (WId *)retval;
- WId proxy_id = 0;
- if (type == XA_WINDOW && proxy_id_ptr) {
- proxy_id = *proxy_id_ptr;
- XFree(proxy_id_ptr);
- proxy_id_ptr = 0;
- // Already exists. Real?
- X11->ignoreBadwindow();
- XGetWindowProperty(X11->display, proxy_id, ATOM(XdndProxy), 0, 1, False,
- XA_WINDOW, &type, &f,&n,&a,&retval);
- proxy_id_ptr = (WId *)retval;
- if (X11->badwindow() || type != XA_WINDOW || !proxy_id_ptr || *proxy_id_ptr != proxy_id)
- // Bogus - we will overwrite.
- proxy_id = 0;
- }
- if (proxy_id_ptr)
- XFree(proxy_id_ptr);
- return proxy_id;
-}
-
-static bool xdndEnable(QWidget* w, bool on)
-{
- DNDDEBUG << "xdndEnable" << w << on;
- if (on) {
- QWidget * xdnd_widget = 0;
- if ((w->windowType() == Qt::Desktop)) {
- if (xdnd_data.desktop_proxy) // *WE* already have one.
- return false;
-
- // As per Xdnd4, use XdndProxy
- XGrabServer(X11->display);
- Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
- WId proxy_id = xdndProxy(w->effectiveWinId());
-
- if (!proxy_id) {
- xdnd_widget = xdnd_data.desktop_proxy = new QWidget;
- proxy_id = xdnd_data.desktop_proxy->effectiveWinId();
- XChangeProperty (X11->display, w->effectiveWinId(), ATOM(XdndProxy),
- XA_WINDOW, 32, PropModeReplace, (unsigned char *)&proxy_id, 1);
- XChangeProperty (X11->display, proxy_id, ATOM(XdndProxy),
- XA_WINDOW, 32, PropModeReplace, (unsigned char *)&proxy_id, 1);
- }
-
- XUngrabServer(X11->display);
- } else {
- xdnd_widget = w->window();
- }
- if (xdnd_widget) {
- DNDDEBUG << "setting XdndAware for" << xdnd_widget << xdnd_widget->effectiveWinId();
- Atom atm = (Atom)xdnd_version;
- Q_ASSERT(xdnd_widget->testAttribute(Qt::WA_WState_Created));
- XChangeProperty(X11->display, xdnd_widget->effectiveWinId(), ATOM(XdndAware),
- XA_ATOM, 32, PropModeReplace, (unsigned char *)&atm, 1);
- return true;
- } else {
- return false;
- }
- } else {
- if ((w->windowType() == Qt::Desktop)) {
- XDeleteProperty(X11->display, w->internalWinId(), ATOM(XdndProxy));
- delete xdnd_data.desktop_proxy;
- xdnd_data.desktop_proxy = 0;
- } else {
- DNDDEBUG << "not deleting XDndAware";
- }
- return true;
- }
-}
-
-QByteArray QX11Data::xdndAtomToString(Atom a)
-{
- if (!a) return 0;
-
- if (a == XA_STRING || a == ATOM(UTF8_STRING)) {
- return "text/plain"; // some Xdnd clients are dumb
- }
- char *atom = XGetAtomName(display, a);
- QByteArray result = atom;
- XFree(atom);
- return result;
-}
-
-Atom QX11Data::xdndStringToAtom(const char *mimeType)
-{
- if (!mimeType || !*mimeType)
- return 0;
- return XInternAtom(display, mimeType, False);
-}
-
-//$$$
-QString QX11Data::xdndMimeAtomToString(Atom a)
-{
- QString atomName;
- if (a) {
- char *atom = XGetAtomName(display, a);
- atomName = QString::fromLatin1(atom);
- XFree(atom);
- }
- return atomName;
-}
-
-//$$$
-Atom QX11Data::xdndMimeStringToAtom(const QString &mimeType)
-{
- if (mimeType.isEmpty())
- return 0;
- return XInternAtom(display, mimeType.toLatin1().constData(), False);
-}
-
-//$$$ replace ccxdndAtomToString()
-QStringList QX11Data::xdndMimeFormatsForAtom(Atom a)
-{
- QStringList formats;
- if (a) {
- QString atomName = xdndMimeAtomToString(a);
- formats.append(atomName);
-
- // special cases for string type
- if (a == ATOM(UTF8_STRING) || a == XA_STRING
- || a == ATOM(TEXT) || a == ATOM(COMPOUND_TEXT))
- formats.append(QLatin1String("text/plain"));
-
- // special cases for uris
- if (atomName == QLatin1String("text/x-moz-url"))
- formats.append(QLatin1String("text/uri-list"));
-
- // special case for images
- if (a == XA_PIXMAP)
- formats.append(QLatin1String("image/ppm"));
- }
- return formats;
-}
-
-//$$$
-bool QX11Data::xdndMimeDataForAtom(Atom a, QMimeData *mimeData, QByteArray *data, Atom *atomFormat, int *dataFormat)
-{
- bool ret = false;
- *atomFormat = a;
- *dataFormat = 8;
- QString atomName = xdndMimeAtomToString(a);
- if (QInternalMimeData::hasFormatHelper(atomName, mimeData)) {
- *data = QInternalMimeData::renderDataHelper(atomName, mimeData);
- if (atomName == QLatin1String("application/x-color"))
- *dataFormat = 16;
- ret = true;
- } else {
- if ((a == ATOM(UTF8_STRING) || a == XA_STRING
- || a == ATOM(TEXT) || a == ATOM(COMPOUND_TEXT))
- && QInternalMimeData::hasFormatHelper(QLatin1String("text/plain"), mimeData)) {
- if (a == ATOM(UTF8_STRING)){
- *data = QInternalMimeData::renderDataHelper(QLatin1String("text/plain"), mimeData);
- ret = true;
- } else if (a == XA_STRING) {
- *data = QString::fromUtf8(QInternalMimeData::renderDataHelper(
- QLatin1String("text/plain"), mimeData)).toLocal8Bit();
- ret = true;
- } else if (a == ATOM(TEXT) || a == ATOM(COMPOUND_TEXT)) {
- // the ICCCM states that TEXT and COMPOUND_TEXT are in the
- // encoding of choice, so we choose the encoding of the locale
- QByteArray strData = QString::fromUtf8(QInternalMimeData::renderDataHelper(
- QLatin1String("text/plain"), mimeData)).toLocal8Bit();
- char *list[] = { strData.data(), NULL };
-
- XICCEncodingStyle style = (a == ATOM(COMPOUND_TEXT))
- ? XCompoundTextStyle : XStdICCTextStyle;
- XTextProperty textprop;
- if (list[0] != NULL
- && XmbTextListToTextProperty(X11->display, list, 1, style,
- &textprop) == Success) {
- *atomFormat = textprop.encoding;
- *dataFormat = textprop.format;
- *data = QByteArray((const char *) textprop.value, textprop.nitems * textprop.format / 8);
- ret = true;
-
- DEBUG(" textprop type %lx\n"
- " textprop name '%s'\n"
- " format %d\n"
- " %ld items\n"
- " %d bytes\n",
- textprop.encoding,
- X11->xdndMimeAtomToString(textprop.encoding).toLatin1().data(),
- textprop.format, textprop.nitems, data->size());
-
- XFree(textprop.value);
- }
- }
- } else if (atomName == QLatin1String("text/x-moz-url") &&
- QInternalMimeData::hasFormatHelper(QLatin1String("text/uri-list"), mimeData)) {
- QByteArray uri = QInternalMimeData::renderDataHelper(
- QLatin1String("text/uri-list"), mimeData).split('\n').first();
- QString mozUri = QString::fromLatin1(uri, uri.size());
- mozUri += QLatin1Char('\n');
- *data = QByteArray(reinterpret_cast<const char *>(mozUri.utf16()), mozUri.length() * 2);
- ret = true;
- } else if ((a == XA_PIXMAP || a == XA_BITMAP) && mimeData->hasImage()) {
- QPixmap pm = qvariant_cast<QPixmap>(mimeData->imageData());
- if (a == XA_BITMAP && pm.depth() != 1) {
- QImage img = pm.toImage();
- img = img.convertToFormat(QImage::Format_MonoLSB);
- pm = QPixmap::fromImage(img);
- }
- QDragManager *dm = QDragManager::self();
- if (dm) {
- Pixmap handle = pm.handle();
- *data = QByteArray((const char *) &handle, sizeof(Pixmap));
- dm->xdndMimeTransferedPixmap[dm->xdndMimeTransferedPixmapIndex] = pm;
- dm->xdndMimeTransferedPixmapIndex =
- (dm->xdndMimeTransferedPixmapIndex + 1) % 2;
- ret = true;
- }
- } else {
- DEBUG("QClipboard: xdndMimeDataForAtom(): converting to type '%s' is not supported", qPrintable(atomName));
- }
- }
- return ret && data != 0;
-}
-
-//$$$
-QList<Atom> QX11Data::xdndMimeAtomsForFormat(const QString &format)
-{
- QList<Atom> atoms;
- atoms.append(xdndMimeStringToAtom(format));
-
- // special cases for strings
- if (format == QLatin1String("text/plain")) {
- atoms.append(ATOM(UTF8_STRING));
- atoms.append(XA_STRING);
- atoms.append(ATOM(TEXT));
- atoms.append(ATOM(COMPOUND_TEXT));
- }
-
- // special cases for uris
- if (format == QLatin1String("text/uri-list")) {
- atoms.append(xdndMimeStringToAtom(QLatin1String("text/x-moz-url")));
- }
-
- //special cases for images
- if (format == QLatin1String("image/ppm"))
- atoms.append(XA_PIXMAP);
- if (format == QLatin1String("image/pbm"))
- atoms.append(XA_BITMAP);
-
- return atoms;
-}
-
-//$$$
-QVariant QX11Data::xdndMimeConvertToFormat(Atom a, const QByteArray &data, const QString &format, QVariant::Type requestedType, const QByteArray &encoding)
-{
- QString atomName = xdndMimeAtomToString(a);
- if (atomName == format)
- return data;
-
- if (!encoding.isEmpty()
- && atomName == format + QLatin1String(";charset=") + QString::fromLatin1(encoding)) {
-
- if (requestedType == QVariant::String) {
- QTextCodec *codec = QTextCodec::codecForName(encoding);
- if (codec)
- return codec->toUnicode(data);
- }
-
- return data;
- }
-
- // special cases for string types
- if (format == QLatin1String("text/plain")) {
- if (a == ATOM(UTF8_STRING))
- return QString::fromUtf8(data);
- if (a == XA_STRING)
- return QString::fromLatin1(data);
- if (a == ATOM(TEXT) || a == ATOM(COMPOUND_TEXT))
- // #### might be wrong for COMPUND_TEXT
- return QString::fromLocal8Bit(data, data.size());
- }
-
- // special case for uri types
- if (format == QLatin1String("text/uri-list")) {
- if (atomName == QLatin1String("text/x-moz-url")) {
- // we expect this as utf16 <url><space><title>
- // the first part is a url that should only contain ascci char
- // so it should be safe to check that the second char is 0
- // to verify that it is utf16
- if (data.size() > 1 && data.at(1) == 0)
- return QString::fromRawData((const QChar *)data.constData(),
- data.size() / 2).split(QLatin1Char('\n')).first().toLatin1();
- }
- }
-
- // special cas for images
- if (format == QLatin1String("image/ppm")) {
- if (a == XA_PIXMAP && data.size() == sizeof(Pixmap)) {
- Pixmap xpm = *((Pixmap*)data.data());
- if (!xpm)
- return QByteArray();
- QPixmap qpm = QPixmap::fromX11Pixmap(xpm);
- QImageWriter imageWriter;
- imageWriter.setFormat("PPMRAW");
- QImage imageToWrite = qpm.toImage();
- QBuffer buf;
- buf.open(QIODevice::WriteOnly);
- imageWriter.setDevice(&buf);
- imageWriter.write(imageToWrite);
- return buf.buffer();
- }
- }
- return QVariant();
-}
-
-//$$$ middle of xdndObtainData
-Atom QX11Data::xdndMimeAtomForFormat(const QString &format, QVariant::Type requestedType, const QList<Atom> &atoms, QByteArray *encoding)
-{
- encoding->clear();
-
- // find matches for string types
- if (format == QLatin1String("text/plain")) {
- if (atoms.contains(ATOM(UTF8_STRING)))
- return ATOM(UTF8_STRING);
- if (atoms.contains(ATOM(COMPOUND_TEXT)))
- return ATOM(COMPOUND_TEXT);
- if (atoms.contains(ATOM(TEXT)))
- return ATOM(TEXT);
- if (atoms.contains(XA_STRING))
- return XA_STRING;
- }
-
- // find matches for uri types
- if (format == QLatin1String("text/uri-list")) {
- Atom a = xdndMimeStringToAtom(format);
- if (a && atoms.contains(a))
- return a;
- a = xdndMimeStringToAtom(QLatin1String("text/x-moz-url"));
- if (a && atoms.contains(a))
- return a;
- }
-
- // find match for image
- if (format == QLatin1String("image/ppm")) {
- if (atoms.contains(XA_PIXMAP))
- return XA_PIXMAP;
- }
-
- // for string/text requests try to use a format with a well-defined charset
- // first to avoid encoding problems
- if (requestedType == QVariant::String
- && format.startsWith(QLatin1String("text/"))
- && !format.contains(QLatin1String("charset="))) {
-
- QString formatWithCharset = format;
- formatWithCharset.append(QLatin1String(";charset=utf-8"));
-
- Atom a = xdndMimeStringToAtom(formatWithCharset);
- if (a && atoms.contains(a)) {
- *encoding = "utf-8";
- return a;
- }
- }
-
- Atom a = xdndMimeStringToAtom(format);
- if (a && atoms.contains(a))
- return a;
-
- return 0;
-}
-
-void QX11Data::xdndSetup() {
- QCursorData::initialize();
- qAddPostRoutine(qt_xdnd_cleanup);
-}
-
-
-void qt_xdnd_cleanup()
-{
- delete noDropCursor;
- noDropCursor = 0;
- delete copyCursor;
- copyCursor = 0;
- delete moveCursor;
- moveCursor = 0;
- delete linkCursor;
- linkCursor = 0;
- delete defaultPm;
- defaultPm = 0;
- delete xdnd_data.desktop_proxy;
- xdnd_data.desktop_proxy = 0;
- delete xdnd_data.deco;
- xdnd_data.deco = 0;
-}
-
-
-static QWidget *find_child(QWidget *tlw, QPoint & p)
-{
- QWidget *widget = tlw;
-
- p = widget->mapFromGlobal(p);
- bool done = false;
- while (!done) {
- done = true;
- if (((QExtraWidget*)widget)->extraData() &&
- ((QExtraWidget*)widget)->extraData()->xDndProxy != 0)
- break; // stop searching for widgets under the mouse cursor if found widget is a proxy.
- QObjectList children = widget->children();
- if (!children.isEmpty()) {
- for(int i = children.size(); i > 0;) {
- --i;
- QWidget *w = qobject_cast<QWidget *>(children.at(i));
- if (!w)
- continue;
- if (w->testAttribute(Qt::WA_TransparentForMouseEvents))
- continue;
- if (w->isVisible() &&
- w->geometry().contains(p) &&
- !w->isWindow()) {
- widget = w;
- done = false;
- p = widget->mapFromParent(p);
- break;
- }
- }
- }
- }
- return widget;
-}
-
-
-static bool checkEmbedded(QWidget* w, const XEvent* xe)
-{
- if (!w)
- return false;
-
- if (current_embedding_widget != 0 && current_embedding_widget != w) {
- qt_xdnd_current_target = ((QExtraWidget*)current_embedding_widget)->extraData()->xDndProxy;
- qt_xdnd_current_proxy_target = qt_xdnd_current_target;
- qt_xdnd_send_leave();
- qt_xdnd_current_target = 0;
- qt_xdnd_current_proxy_target = 0;
- current_embedding_widget = 0;
- }
-
- QWExtra* extra = ((QExtraWidget*)w)->extraData();
- if (extra && extra->xDndProxy != 0) {
-
- if (current_embedding_widget != w) {
-
- last_enter_event.xany.window = extra->xDndProxy;
- XSendEvent(X11->display, extra->xDndProxy, False, NoEventMask, &last_enter_event);
- current_embedding_widget = w;
- }
-
- ((XEvent*)xe)->xany.window = extra->xDndProxy;
- XSendEvent(X11->display, extra->xDndProxy, False, NoEventMask, (XEvent*)xe);
- if (qt_xdnd_current_widget != w) {
- qt_xdnd_current_widget = w;
- }
- return true;
- }
- current_embedding_widget = 0;
- return false;
-}
-
-void QX11Data::xdndHandleEnter(QWidget *, const XEvent * xe, bool /*passive*/)
-{
- motifdnd_active = false;
-
- last_enter_event.xclient = xe->xclient;
-
- const long *l = xe->xclient.data.l;
- int version = (int)(((unsigned long)(l[1])) >> 24);
-
- if (version > xdnd_version)
- return;
-
- qt_xdnd_dragsource_xid = l[0];
-
- int j = 0;
- if (l[1] & 1) {
- // get the types from XdndTypeList
- Atom type = XNone;
- int f;
- unsigned long n, a;
- unsigned char *retval = 0;
- XGetWindowProperty(X11->display, qt_xdnd_dragsource_xid, ATOM(XdndTypelist), 0,
- qt_xdnd_max_type, False, XA_ATOM, &type, &f,&n,&a,&retval);
- if (retval) {
- Atom *data = (Atom *)retval;
- for (; j<qt_xdnd_max_type && j < (int)n; j++) {
- qt_xdnd_types[j] = data[j];
- }
- XFree((uchar*)data);
- }
- } else {
- // get the types from the message
- int i;
- for(i=2; i < 5; i++) {
- qt_xdnd_types[j++] = l[i];
- }
- }
- qt_xdnd_types[j] = 0;
-}
-
-static void handle_xdnd_position(QWidget *w, const XEvent * xe, bool passive)
-{
- const unsigned long *l = (const unsigned long *)xe->xclient.data.l;
-
- QPoint p((l[2] & 0xffff0000) >> 16, l[2] & 0x0000ffff);
- QWidget * c = find_child(w, p); // changes p to to c-local coordinates
-
- if (!passive && checkEmbedded(c, xe))
- return;
-
- if (!c || (!c->acceptDrops() && (c->windowType() == Qt::Desktop)))
- return;
-
- if (l[0] != qt_xdnd_dragsource_xid) {
- DEBUG("xdnd drag position from unexpected source (%08lx not %08lx)", l[0], qt_xdnd_dragsource_xid);
- return;
- }
-
- // timestamp from the source
- if (l[3] != 0) {
- // Some X server/client combination swallow the first 32 bit and
- // interpret a set bit 31 as negative sign.
- qt_xdnd_target_current_time = X11->userTime =
- ((sizeof(Time) == 8 && xe->xclient.data.l[3] < 0)
- ? uint(l[3])
- : l[3]);
- }
-
- QDragManager *manager = QDragManager::self();
- QMimeData *dropData = manager->object ? manager->dragPrivate()->data : manager->dropData;
-
- XClientMessageEvent response;
- response.type = ClientMessage;
- response.window = qt_xdnd_dragsource_xid;
- response.format = 32;
- response.message_type = ATOM(XdndStatus);
- response.data.l[0] = w->effectiveWinId();
- response.data.l[1] = 0; // flags
- response.data.l[2] = 0; // x, y
- response.data.l[3] = 0; // w, h
- response.data.l[4] = 0; // action
-
- if (!passive) { // otherwise just reject
- while (c && !c->acceptDrops() && !c->isWindow()) {
- p = c->mapToParent(p);
- c = c->parentWidget();
- }
- QWidget *target_widget = c && c->acceptDrops() ? c : 0;
-
- QRect answerRect(c->mapToGlobal(p), QSize(1,1));
-
- if (manager->object) {
- possible_actions = manager->dragPrivate()->possible_actions;
- } else {
- possible_actions = Qt::DropActions(xdndaction_to_qtaction(l[4]));
-// possible_actions |= Qt::CopyAction;
- }
- QDragMoveEvent me(p, possible_actions, dropData, QApplication::mouseButtons(), QApplication::keyboardModifiers());
-
- Qt::DropAction accepted_action = Qt::IgnoreAction;
-
-
- if (target_widget != qt_xdnd_current_widget) {
- if (qt_xdnd_current_widget) {
- QDragLeaveEvent e;
- QApplication::sendEvent(qt_xdnd_current_widget, &e);
- }
- if (qt_xdnd_current_widget != target_widget) {
- qt_xdnd_current_widget = target_widget;
- }
- if (target_widget) {
- qt_xdnd_current_position = p;
-
- last_target_accepted_action = Qt::IgnoreAction;
- QDragEnterEvent de(p, possible_actions, dropData, QApplication::mouseButtons(), QApplication::keyboardModifiers());
- QApplication::sendEvent(target_widget, &de);
- if (de.isAccepted() && de.dropAction() != Qt::IgnoreAction)
- last_target_accepted_action = de.dropAction();
- }
- }
-
- DEBUG() << "qt_handle_xdnd_position action=" << X11->xdndAtomToString(l[4]);
- if (!target_widget) {
- answerRect = QRect(p, QSize(1, 1));
- } else {
- qt_xdnd_current_widget = c;
- qt_xdnd_current_position = p;
-
- if (last_target_accepted_action != Qt::IgnoreAction) {
- me.setDropAction(last_target_accepted_action);
- me.accept();
- }
- QApplication::sendEvent(c, &me);
- if (me.isAccepted()) {
- response.data.l[1] = 1; // yes
- accepted_action = me.dropAction();
- last_target_accepted_action = accepted_action;
- } else {
- response.data.l[0] = 0;
- last_target_accepted_action = Qt::IgnoreAction;
- }
- answerRect = me.answerRect().intersected(c->rect());
- }
- answerRect = QRect(c->mapToGlobal(answerRect.topLeft()), answerRect.size());
-
- if (answerRect.left() < 0)
- answerRect.setLeft(0);
- if (answerRect.right() > 4096)
- answerRect.setRight(4096);
- if (answerRect.top() < 0)
- answerRect.setTop(0);
- if (answerRect.bottom() > 4096)
- answerRect.setBottom(4096);
- if (answerRect.width() < 0)
- answerRect.setWidth(0);
- if (answerRect.height() < 0)
- answerRect.setHeight(0);
-
- response.data.l[2] = (answerRect.x() << 16) + answerRect.y();
- response.data.l[3] = (answerRect.width() << 16) + answerRect.height();
- response.data.l[4] = qtaction_to_xdndaction(accepted_action);
- }
-
- // reset
- qt_xdnd_target_current_time = CurrentTime;
-
- QWidget * source = QWidget::find(qt_xdnd_dragsource_xid);
- if (source && (source->windowType() == Qt::Desktop) && !source->acceptDrops())
- source = 0;
-
- DEBUG() << "sending XdndStatus";
- if (source)
- handle_xdnd_status(source, (const XEvent *)&response, passive);
- else
- XSendEvent(X11->display, qt_xdnd_dragsource_xid, False, NoEventMask, (XEvent*)&response);
-}
-
-static Bool xdnd_position_scanner(Display *, XEvent *event, XPointer)
-{
- if (event->type != ClientMessage)
- return false;
- XClientMessageEvent *ev = &event->xclient;
-
- if (ev->message_type == ATOM(XdndPosition))
- return true;
-
- return false;
-}
-
-void QX11Data::xdndHandlePosition(QWidget * w, const XEvent * xe, bool passive)
-{
- DEBUG("xdndHandlePosition");
- while (XCheckIfEvent(X11->display, (XEvent *)xe, xdnd_position_scanner, 0))
- ;
-
- handle_xdnd_position(w, xe, passive);
-}
-
-
-static void handle_xdnd_status(QWidget *, const XEvent * xe, bool)
-{
- const unsigned long *l = (const unsigned long *)xe->xclient.data.l;
- // ignore late status messages
- if (l[0] && l[0] != qt_xdnd_current_proxy_target)
- return;
- Qt::DropAction newAction = (l[1] & 0x1) ? xdndaction_to_qtaction(l[4]) : Qt::IgnoreAction;
-
- if ((int)(l[1] & 2) == 0) {
- QPoint p((l[2] & 0xffff0000) >> 16, l[2] & 0x0000ffff);
- QSize s((l[3] & 0xffff0000) >> 16, l[3] & 0x0000ffff);
- qt_xdnd_source_sameanswer = QRect(p, s);
- } else {
- qt_xdnd_source_sameanswer = QRect();
- }
- QDragManager *manager = QDragManager::self();
- manager->willDrop = (l[1] & 0x1);
- if (global_accepted_action != newAction)
- manager->emitActionChanged(newAction);
- global_accepted_action = newAction;
- manager->updateCursor();
- waiting_for_status = false;
-}
-
-static Bool xdnd_status_scanner(Display *, XEvent *event, XPointer)
-{
- if (event->type != ClientMessage)
- return false;
- XClientMessageEvent *ev = &event->xclient;
-
- if (ev->message_type == ATOM(XdndStatus))
- return true;
-
- return false;
-}
-
-void QX11Data::xdndHandleStatus(QWidget * w, const XEvent * xe, bool passive)
-{
- DEBUG("xdndHandleStatus");
- while (XCheckIfEvent(X11->display, (XEvent *)xe, xdnd_status_scanner, 0))
- ;
-
- handle_xdnd_status(w, xe, passive);
- DEBUG("xdndHandleStatus end");
-}
-
-void QX11Data::xdndHandleLeave(QWidget *w, const XEvent * xe, bool /*passive*/)
-{
- DEBUG("xdnd leave");
- if (!qt_xdnd_current_widget ||
- w->window() != qt_xdnd_current_widget->window()) {
- return; // sanity
- }
-
- if (checkEmbedded(current_embedding_widget, xe)) {
- current_embedding_widget = 0;
- qt_xdnd_current_widget = 0;
- return;
- }
-
- const unsigned long *l = (const unsigned long *)xe->xclient.data.l;
-
- QDragLeaveEvent e;
- QApplication::sendEvent(qt_xdnd_current_widget, &e);
-
- if (l[0] != qt_xdnd_dragsource_xid) {
- // This often happens - leave other-process window quickly
- DEBUG("xdnd drag leave from unexpected source (%08lx not %08lx", l[0], qt_xdnd_dragsource_xid);
- qt_xdnd_current_widget = 0;
- return;
- }
-
- qt_xdnd_dragsource_xid = 0;
- qt_xdnd_types[0] = 0;
- qt_xdnd_current_widget = 0;
-}
-
-
-void qt_xdnd_send_leave()
-{
- if (!qt_xdnd_current_target)
- return;
-
- QDragManager *manager = QDragManager::self();
-
- XClientMessageEvent leave;
- leave.type = ClientMessage;
- leave.window = qt_xdnd_current_target;
- leave.format = 32;
- leave.message_type = ATOM(XdndLeave);
- leave.data.l[0] = manager->dragPrivate()->source->effectiveWinId();
- leave.data.l[1] = 0; // flags
- leave.data.l[2] = 0; // x, y
- leave.data.l[3] = 0; // w, h
- leave.data.l[4] = 0; // just null
-
- QWidget * w = QWidget::find(qt_xdnd_current_proxy_target);
-
- if (w && (w->windowType() == Qt::Desktop) && !w->acceptDrops())
- w = 0;
-
- if (w)
- X11->xdndHandleLeave(w, (const XEvent *)&leave, false);
- else
- XSendEvent(X11->display, qt_xdnd_current_proxy_target, False,
- NoEventMask, (XEvent*)&leave);
-
- // reset the drag manager state
- manager->willDrop = false;
- if (global_accepted_action != Qt::IgnoreAction)
- manager->emitActionChanged(Qt::IgnoreAction);
- global_accepted_action = Qt::IgnoreAction;
- manager->updateCursor();
- qt_xdnd_current_target = 0;
- qt_xdnd_current_proxy_target = 0;
- qt_xdnd_source_current_time = 0;
- waiting_for_status = false;
-}
-
-// TODO: remove and use QApplication::currentKeyboardModifiers() in Qt 4.8.
-static Qt::KeyboardModifiers currentKeyboardModifiers()
-{
- Window root;
- Window child;
- int root_x, root_y, win_x, win_y;
- uint keybstate;
- for (int i = 0; i < ScreenCount(X11->display); ++i) {
- if (XQueryPointer(X11->display, QX11Info::appRootWindow(i), &root, &child,
- &root_x, &root_y, &win_x, &win_y, &keybstate))
- return X11->translateModifiers(keybstate & 0x00ff);
- }
- return 0;
-}
-
-void QX11Data::xdndHandleDrop(QWidget *, const XEvent * xe, bool passive)
-{
- DEBUG("xdndHandleDrop");
- if (!qt_xdnd_current_widget) {
- qt_xdnd_dragsource_xid = 0;
- return; // sanity
- }
-
- if (!passive && checkEmbedded(qt_xdnd_current_widget, xe)){
- current_embedding_widget = 0;
- qt_xdnd_dragsource_xid = 0;
- qt_xdnd_current_widget = 0;
- return;
- }
- const unsigned long *l = (const unsigned long *)xe->xclient.data.l;
-
- QDragManager *manager = QDragManager::self();
- DEBUG("xdnd drop");
-
- if (l[0] != qt_xdnd_dragsource_xid) {
- DEBUG("xdnd drop from unexpected source (%08lx not %08lx", l[0], qt_xdnd_dragsource_xid);
- return;
- }
-
- // update the "user time" from the timestamp in the event.
- if (l[2] != 0) {
- // Some X server/client combination swallow the first 32 bit and
- // interpret a set bit 31 as negative sign.
- qt_xdnd_target_current_time = X11->userTime =
- ((sizeof(Time) == 8 && xe->xclient.data.l[2] < 0)
- ? uint(l[2])
- : l[2]);
- }
-
- if (!passive) {
- // this could be a same-application drop, just proxied due to
- // some XEMBEDding, so try to find the real QMimeData used
- // based on the timestamp for this drop.
- QMimeData *dropData = 0;
- int at = findXdndDropTransactionByTime(qt_xdnd_target_current_time);
- if (at != -1)
- dropData = QDragManager::dragPrivate(X11->dndDropTransactions.at(at).object)->data;
- // if we can't find it, then use the data in the drag manager
- if (!dropData)
- dropData = (manager->object) ? manager->dragPrivate()->data : manager->dropData;
-
- // Drop coming from another app? Update keyboard modifiers.
- if (!qt_xdnd_dragging) {
- QApplicationPrivate::modifier_buttons = currentKeyboardModifiers();
- }
-
- QDropEvent de(qt_xdnd_current_position, possible_actions, dropData,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- QApplication::sendEvent(qt_xdnd_current_widget, &de);
- if (!de.isAccepted()) {
- // Ignore a failed drag
- global_accepted_action = Qt::IgnoreAction;
- } else {
- global_accepted_action = de.dropAction();
- }
- XClientMessageEvent finished;
- finished.type = ClientMessage;
- finished.window = qt_xdnd_dragsource_xid;
- finished.format = 32;
- finished.message_type = ATOM(XdndFinished);
- DNDDEBUG << "xdndHandleDrop"
- << "qt_xdnd_current_widget" << qt_xdnd_current_widget
- << (qt_xdnd_current_widget ? qt_xdnd_current_widget->effectiveWinId() : 0)
- << "t_xdnd_current_widget->window()"
- << (qt_xdnd_current_widget ? qt_xdnd_current_widget->window() : 0)
- << (qt_xdnd_current_widget ? qt_xdnd_current_widget->window()->internalWinId() : 0);
- finished.data.l[0] = qt_xdnd_current_widget?qt_xdnd_current_widget->window()->internalWinId():0;
- finished.data.l[1] = de.isAccepted() ? 1 : 0; // flags
- finished.data.l[2] = qtaction_to_xdndaction(global_accepted_action);
- XSendEvent(X11->display, qt_xdnd_dragsource_xid, False,
- NoEventMask, (XEvent*)&finished);
- } else {
- QDragLeaveEvent e;
- QApplication::sendEvent(qt_xdnd_current_widget, &e);
- }
- qt_xdnd_dragsource_xid = 0;
- qt_xdnd_current_widget = 0;
- waiting_for_status = false;
-
- // reset
- qt_xdnd_target_current_time = CurrentTime;
-}
-
-
-void QX11Data::xdndHandleFinished(QWidget *, const XEvent * xe, bool passive)
-{
- DEBUG("xdndHandleFinished");
- const unsigned long *l = (const unsigned long *)xe->xclient.data.l;
-
- DNDDEBUG << "xdndHandleFinished, l[0]" << l[0]
- << "qt_xdnd_current_target" << qt_xdnd_current_target
- << "qt_xdnd_current_proxy_targe" << qt_xdnd_current_proxy_target;
-
- if (l[0]) {
- int at = findXdndDropTransactionByWindow(l[0]);
- if (at != -1) {
- restartXdndDropExpiryTimer();
-
- QXdndDropTransaction t = X11->dndDropTransactions.takeAt(at);
- QDragManager *manager = QDragManager::self();
-
- Window target = qt_xdnd_current_target;
- Window proxy_target = qt_xdnd_current_proxy_target;
- QWidget *embedding_widget = current_embedding_widget;
- QDrag *currentObject = manager->object;
-
- qt_xdnd_current_target = t.target;
- qt_xdnd_current_proxy_target = t.proxy_target;
- current_embedding_widget = t.embedding_widget;
- manager->object = t.object;
-
- if (!passive)
- (void) checkEmbedded(qt_xdnd_current_widget, xe);
-
- current_embedding_widget = 0;
- qt_xdnd_current_target = 0;
- qt_xdnd_current_proxy_target = 0;
-
- if (t.object)
- t.object->deleteLater();
-
- qt_xdnd_current_target = target;
- qt_xdnd_current_proxy_target = proxy_target;
- current_embedding_widget = embedding_widget;
- manager->object = currentObject;
- }
- }
- waiting_for_status = false;
-}
-
-
-void QDragManager::timerEvent(QTimerEvent* e)
-{
- if (e->timerId() == heartbeat && qt_xdnd_source_sameanswer.isNull()) {
- move(QCursor::pos());
- } else if (e->timerId() == transaction_expiry_timer) {
- for (int i = 0; i < X11->dndDropTransactions.count(); ++i) {
- const QXdndDropTransaction &t = X11->dndDropTransactions.at(i);
- if (t.targetWidget) {
- // dnd within the same process, don't delete these
- continue;
- }
- t.object->deleteLater();
- X11->dndDropTransactions.removeAt(i--);
- }
-
- killTimer(transaction_expiry_timer);
- transaction_expiry_timer = -1;
- }
-}
-
-bool QDragManager::eventFilter(QObject * o, QEvent * e)
-{
- if (beingCancelled) {
- if (e->type() == QEvent::KeyRelease && ((QKeyEvent*)e)->key() == Qt::Key_Escape) {
- qApp->removeEventFilter(this);
- Q_ASSERT(object == 0);
- beingCancelled = false;
- eventLoop->exit();
- return true; // block the key release
- }
- return false;
- }
-
- Q_ASSERT(object != 0);
-
- if (!o->isWidgetType())
- return false;
-
- if (e->type() == QEvent::MouseMove) {
- QMouseEvent* me = (QMouseEvent *)e;
- move(me->globalPos());
- return true;
- } else if (e->type() == QEvent::MouseButtonRelease) {
- DEBUG("pre drop");
- qApp->removeEventFilter(this);
- if (willDrop)
- drop();
- else
- cancel();
- DEBUG("drop, resetting object");
- beingCancelled = false;
- eventLoop->exit();
- return true;
- }
-
- if (e->type() == QEvent::ShortcutOverride) {
- // prevent accelerators from firing while dragging
- e->accept();
- return true;
- }
-
- if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) {
- QKeyEvent *ke = ((QKeyEvent*)e);
- if (ke->key() == Qt::Key_Escape && e->type() == QEvent::KeyPress) {
- cancel();
- qApp->removeEventFilter(this);
- beingCancelled = false;
- eventLoop->exit();
- } else {
- qt_xdnd_source_sameanswer = QRect(); // force move
- move(QCursor::pos());
- }
- return true; // Eat all key events
- }
-
- // ### We bind modality to widgets, so we have to do this
- // ### "manually".
- // DnD is modal - eat all other interactive events
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- case QEvent::Wheel:
- case QEvent::ShortcutOverride:
- return true;
- default:
- return false;
- }
-}
-
-void QDragManager::updateCursor()
-{
- if (!noDropCursor) {
-#ifndef QT_NO_CURSOR
- noDropCursor = new QCursor(Qt::ForbiddenCursor);
- moveCursor = new QCursor(Qt::DragMoveCursor);
- copyCursor = new QCursor(Qt::DragCopyCursor);
- linkCursor = new QCursor(Qt::DragLinkCursor);
-#endif
- }
-
- QCursor *c;
- if (willDrop) {
- if (global_accepted_action == Qt::CopyAction) {
- c = copyCursor;
- } else if (global_accepted_action == Qt::LinkAction) {
- c = linkCursor;
- } else {
- c = moveCursor;
- }
- if (xdnd_data.deco) {
- xdnd_data.deco->show();
- xdnd_data.deco->raise();
- }
- } else {
- c = noDropCursor;
- //if (qt_xdnd_deco)
- // qt_xdnd_deco->hide();
- }
-#ifndef QT_NO_CURSOR
- if (c)
- qApp->changeOverrideCursor(*c);
-#endif
-}
-
-
-void QDragManager::cancel(bool deleteSource)
-{
- DEBUG("QDragManager::cancel");
- Q_ASSERT(heartbeat != -1);
- killTimer(heartbeat);
- heartbeat = -1;
- beingCancelled = true;
- qt_xdnd_dragging = false;
-
- if (qt_xdnd_current_target)
- qt_xdnd_send_leave();
-
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- QApplication::restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-
- if (deleteSource && object)
- object->deleteLater();
- object = 0;
- qDeleteInEventHandler(xdnd_data.deco);
- xdnd_data.deco = 0;
-
- global_accepted_action = Qt::IgnoreAction;
-}
-
-static
-Window findRealWindow(const QPoint & pos, Window w, int md)
-{
- if (xdnd_data.deco && w == xdnd_data.deco->effectiveWinId())
- return 0;
-
- if (md) {
- X11->ignoreBadwindow();
- XWindowAttributes attr;
- XGetWindowAttributes(X11->display, w, &attr);
- if (X11->badwindow())
- return 0;
-
- if (attr.map_state == IsViewable
- && QRect(attr.x,attr.y,attr.width,attr.height).contains(pos)) {
- {
- Atom type = XNone;
- int f;
- unsigned long n, a;
- unsigned char *data;
-
- XGetWindowProperty(X11->display, w, ATOM(XdndAware), 0, 0, False,
- AnyPropertyType, &type, &f,&n,&a,&data);
- if (data) XFree(data);
- if (type)
- return w;
- }
-
- Window r, p;
- Window* c;
- uint nc;
- if (XQueryTree(X11->display, w, &r, &p, &c, &nc)) {
- r=0;
- for (uint i=nc; !r && i--;) {
- r = findRealWindow(pos-QPoint(attr.x,attr.y),
- c[i], md-1);
- }
- XFree(c);
- if (r)
- return r;
-
- // We didn't find a client window! Just use the
- // innermost window.
- }
-
- // No children!
- return w;
- }
- }
- return 0;
-}
-
-void QDragManager::move(const QPoint & globalPos)
-{
-#ifdef QT_NO_CURSOR
- Q_UNUSED(globalPos);
- return;
-#else
- DEBUG() << "QDragManager::move enter";
- if (!object) {
- // perhaps the target crashed?
- return;
- }
-
- int screen = QCursor::x11Screen();
- if ((qt_xdnd_current_screen == -1 && screen != X11->defaultScreen) || (screen != qt_xdnd_current_screen)) {
- // recreate the pixmap on the new screen...
- delete xdnd_data.deco;
- QWidget* parent = object->source()->window()->x11Info().screen() == screen
- ? object->source()->window() : QApplication::desktop()->screen(screen);
- xdnd_data.deco = new QShapedPixmapWidget(parent);
- if (!QWidget::mouseGrabber()) {
- updatePixmap();
- xdnd_data.deco->grabMouse();
- }
- }
- xdnd_data.deco->move(QCursor::pos() - xdnd_data.deco->pm_hot);
-
- if (qt_xdnd_source_sameanswer.contains(globalPos) && qt_xdnd_source_sameanswer.isValid())
- return;
-
- qt_xdnd_current_screen = screen;
- Window rootwin = QX11Info::appRootWindow(qt_xdnd_current_screen);
- Window target = 0;
- int lx = 0, ly = 0;
- if (!XTranslateCoordinates(X11->display, rootwin, rootwin, globalPos.x(), globalPos.y(), &lx, &ly, &target))
- // some weird error...
- return;
-
- if (target == rootwin) {
- // Ok.
- } else if (target) {
- //me
- Window src = rootwin;
- while (target != 0) {
- DNDDEBUG << "checking target for XdndAware" << QWidget::find(target) << target;
- int lx2, ly2;
- Window t;
- // translate coordinates
- if (!XTranslateCoordinates(X11->display, src, target, lx, ly, &lx2, &ly2, &t)) {
- target = 0;
- break;
- }
- lx = lx2;
- ly = ly2;
- src = target;
-
- // check if it has XdndAware
- Atom type = 0;
- int f;
- unsigned long n, a;
- unsigned char *data = 0;
- XGetWindowProperty(X11->display, target, ATOM(XdndAware), 0, 0, False,
- AnyPropertyType, &type, &f,&n,&a,&data);
- if (data)
- XFree(data);
- if (type) {
- DNDDEBUG << "Found XdndAware on " << QWidget::find(target) << target;
- break;
- }
-
- // find child at the coordinates
- if (!XTranslateCoordinates(X11->display, src, src, lx, ly, &lx2, &ly2, &target)) {
- target = 0;
- break;
- }
- }
- if (xdnd_data.deco && (!target || target == xdnd_data.deco->effectiveWinId())) {
- DNDDEBUG << "need to find real window";
- target = findRealWindow(globalPos, rootwin, 6);
- DNDDEBUG << "real window found" << QWidget::find(target) << target;
- }
- }
-
- QWidget* w;
- if (target) {
- w = QWidget::find((WId)target);
- if (w && (w->windowType() == Qt::Desktop) && !w->acceptDrops())
- w = 0;
- } else {
- w = 0;
- target = rootwin;
- }
-
- DNDDEBUG << "and the final target is " << QWidget::find(target) << target;
- DNDDEBUG << "the widget w is" << w;
-
- WId proxy_target = xdndProxy(target);
- if (!proxy_target)
- proxy_target = target;
- int target_version = 1;
-
- if (proxy_target) {
- Atom type = XNone;
- int r, f;
- unsigned long n, a;
- unsigned char *retval;
- X11->ignoreBadwindow();
- r = XGetWindowProperty(X11->display, proxy_target, ATOM(XdndAware), 0,
- 1, False, AnyPropertyType, &type, &f,&n,&a,&retval);
- int *tv = (int *)retval;
- if (r != Success || X11->badwindow()) {
- target = 0;
- } else {
- target_version = qMin(xdnd_version,tv ? *tv : 1);
- if (tv)
- XFree(tv);
-// if (!(!X11->badwindow() && type))
-// target = 0;
- }
- }
-
- if (target != qt_xdnd_current_target) {
- if (qt_xdnd_current_target)
- qt_xdnd_send_leave();
-
- qt_xdnd_current_target = target;
- qt_xdnd_current_proxy_target = proxy_target;
- if (target) {
- QVector<Atom> types;
- int flags = target_version << 24;
- QStringList fmts = QInternalMimeData::formatsHelper(dragPrivate()->data);
- for (int i = 0; i < fmts.size(); ++i) {
- QList<Atom> atoms = X11->xdndMimeAtomsForFormat(fmts.at(i));
- for (int j = 0; j < atoms.size(); ++j) {
- if (!types.contains(atoms.at(j)))
- types.append(atoms.at(j));
- }
- }
- if (types.size() > 3) {
- XChangeProperty(X11->display,
- dragPrivate()->source->effectiveWinId(), ATOM(XdndTypelist),
- XA_ATOM, 32, PropModeReplace,
- (unsigned char *)types.data(),
- types.size());
- flags |= 0x0001;
- }
- XClientMessageEvent enter;
- enter.type = ClientMessage;
- enter.window = target;
- enter.format = 32;
- enter.message_type = ATOM(XdndEnter);
- enter.data.l[0] = dragPrivate()->source->effectiveWinId();
- enter.data.l[1] = flags;
- enter.data.l[2] = types.size()>0 ? types.at(0) : 0;
- enter.data.l[3] = types.size()>1 ? types.at(1) : 0;
- enter.data.l[4] = types.size()>2 ? types.at(2) : 0;
- // provisionally set the rectangle to 5x5 pixels...
- qt_xdnd_source_sameanswer = QRect(globalPos.x() - 2,
- globalPos.y() -2 , 5, 5);
-
- DEBUG("sending Xdnd enter");
- if (w)
- X11->xdndHandleEnter(w, (const XEvent *)&enter, false);
- else if (target)
- XSendEvent(X11->display, proxy_target, False, NoEventMask, (XEvent*)&enter);
- waiting_for_status = false;
- }
- }
- if (waiting_for_status)
- return;
-
- if (target) {
- waiting_for_status = true;
-
- XClientMessageEvent move;
- move.type = ClientMessage;
- move.window = target;
- move.format = 32;
- move.message_type = ATOM(XdndPosition);
- move.window = target;
- move.data.l[0] = dragPrivate()->source->effectiveWinId();
- move.data.l[1] = 0; // flags
- move.data.l[2] = (globalPos.x() << 16) + globalPos.y();
- move.data.l[3] = X11->time;
- move.data.l[4] = qtaction_to_xdndaction(defaultAction(dragPrivate()->possible_actions, QApplication::keyboardModifiers()));
- DEBUG("sending Xdnd position");
-
- qt_xdnd_source_current_time = X11->time;
-
- if (w)
- handle_xdnd_position(w, (const XEvent *)&move, false);
- else
- XSendEvent(X11->display, proxy_target, False, NoEventMask,
- (XEvent*)&move);
- } else {
- if (willDrop) {
- willDrop = false;
- updateCursor();
- }
- }
- DEBUG() << "QDragManager::move leave";
-#endif
-}
-
-
-void QDragManager::drop()
-{
- Q_ASSERT(heartbeat != -1);
- killTimer(heartbeat);
- heartbeat = -1;
- qt_xdnd_dragging = false;
-
- if (!qt_xdnd_current_target)
- return;
-
- qDeleteInEventHandler(xdnd_data.deco);
- xdnd_data.deco = 0;
-
- XClientMessageEvent drop;
- drop.type = ClientMessage;
- drop.window = qt_xdnd_current_target;
- drop.format = 32;
- drop.message_type = ATOM(XdndDrop);
- drop.data.l[0] = dragPrivate()->source->effectiveWinId();
- drop.data.l[1] = 0; // flags
- drop.data.l[2] = X11->time;
-
- drop.data.l[3] = 0;
- drop.data.l[4] = 0;
-
- QWidget * w = QWidget::find(qt_xdnd_current_proxy_target);
-
- if (w && (w->windowType() == Qt::Desktop) && !w->acceptDrops())
- w = 0;
-
- QXdndDropTransaction t = {
- X11->time,
- qt_xdnd_current_target,
- qt_xdnd_current_proxy_target,
- w,
- current_embedding_widget,
- object
- };
- X11->dndDropTransactions.append(t);
- restartXdndDropExpiryTimer();
-
- if (w)
- X11->xdndHandleDrop(w, (const XEvent *)&drop, false);
- else
- XSendEvent(X11->display, qt_xdnd_current_proxy_target, False,
- NoEventMask, (XEvent*)&drop);
-
- qt_xdnd_current_target = 0;
- qt_xdnd_current_proxy_target = 0;
- qt_xdnd_source_current_time = 0;
- current_embedding_widget = 0;
- object = 0;
-
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- QApplication::restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-}
-
-
-
-bool QX11Data::xdndHandleBadwindow()
-{
- if (qt_xdnd_current_target) {
- QDragManager *manager = QDragManager::self();
- if (manager->object) {
- qt_xdnd_current_target = 0;
- qt_xdnd_current_proxy_target = 0;
- manager->object->deleteLater();
- manager->object = 0;
- delete xdnd_data.deco;
- xdnd_data.deco = 0;
- return true;
- }
- }
- if (qt_xdnd_dragsource_xid) {
- qt_xdnd_dragsource_xid = 0;
- if (qt_xdnd_current_widget) {
- QApplication::postEvent(qt_xdnd_current_widget, new QDragLeaveEvent);
- qt_xdnd_current_widget = 0;
- }
- return true;
- }
- return false;
-}
-
-void QX11Data::xdndHandleSelectionRequest(const XSelectionRequestEvent * req)
-{
- if (!req)
- return;
- XEvent evt;
- evt.xselection.type = SelectionNotify;
- evt.xselection.display = req->display;
- evt.xselection.requestor = req->requestor;
- evt.xselection.selection = req->selection;
- evt.xselection.target = XNone;
- evt.xselection.property = XNone;
- evt.xselection.time = req->time;
-
- QDragManager *manager = QDragManager::self();
- QDrag *currentObject = manager->object;
-
- // which transaction do we use? (note: -2 means use current manager->object)
- int at = -1;
-
- // figure out which data the requestor is really interested in
- if (manager->object && req->time == qt_xdnd_source_current_time) {
- // requestor wants the current drag data
- at = -2;
- } else {
- // if someone has requested data in response to XdndDrop, find the corresponding transaction. the
- // spec says to call XConvertSelection() using the timestamp from the XdndDrop
- at = findXdndDropTransactionByTime(req->time);
- if (at == -1) {
- // no dice, perhaps the client was nice enough to use the same window id in XConvertSelection()
- // that we sent the XdndDrop event to.
- at = findXdndDropTransactionByWindow(req->requestor);
- }
- if (at == -1 && req->time == CurrentTime) {
- // previous Qt versions always requested the data on a child of the target window
- // using CurrentTime... but it could be asking for either drop data or the current drag's data
- Window target = findXdndAwareParent(req->requestor);
- if (target) {
- if (qt_xdnd_current_target && qt_xdnd_current_target == target)
- at = -2;
- else
- at = findXdndDropTransactionByWindow(target);
- }
- }
- }
- if (at >= 0) {
- restartXdndDropExpiryTimer();
-
- // use the drag object from an XdndDrop tansaction
- manager->object = X11->dndDropTransactions.at(at).object;
- } else if (at != -2) {
- // no transaction found, we'll have to reject the request
- manager->object = 0;
- }
- if (manager->object) {
- Atom atomFormat = req->target;
- int dataFormat = 0;
- QByteArray data;
- if (X11->xdndMimeDataForAtom(req->target, manager->dragPrivate()->data,
- &data, &atomFormat, &dataFormat)) {
- int dataSize = data.size() / (dataFormat / 8);
- XChangeProperty (X11->display, req->requestor, req->property,
- atomFormat, dataFormat, PropModeReplace,
- (unsigned char *)data.data(), dataSize);
- evt.xselection.property = req->property;
- evt.xselection.target = atomFormat;
- }
- }
-
- // reset manager->object in case we modified it above
- manager->object = currentObject;
-
- // ### this can die if req->requestor crashes at the wrong
- // ### moment
- XSendEvent(X11->display, req->requestor, False, 0, &evt);
-}
-
-static QVariant xdndObtainData(const char *format, QVariant::Type requestedType)
-{
- QByteArray result;
-
- QWidget* w;
- QDragManager *manager = QDragManager::self();
- if (qt_xdnd_dragsource_xid && manager->object &&
- (w=QWidget::find(qt_xdnd_dragsource_xid))
- && (!(w->windowType() == Qt::Desktop) || w->acceptDrops()))
- {
- QDragPrivate * o = QDragManager::self()->dragPrivate();
- if (o->data->hasFormat(QLatin1String(format)))
- result = o->data->data(QLatin1String(format));
- return result;
- }
-
- QList<Atom> atoms;
- int i = 0;
- while ((qt_xdnd_types[i])) {
- atoms.append(qt_xdnd_types[i]);
- ++i;
- }
- QByteArray encoding;
- Atom a = X11->xdndMimeAtomForFormat(QLatin1String(format), requestedType, atoms, &encoding);
- if (!a)
- return result;
-
- if (XGetSelectionOwner(X11->display, ATOM(XdndSelection)) == XNone)
- return result; // should never happen?
-
- QWidget* tw = qt_xdnd_current_widget;
- if (!qt_xdnd_current_widget || (qt_xdnd_current_widget->windowType() == Qt::Desktop))
- tw = new QWidget;
-
- XConvertSelection(X11->display, ATOM(XdndSelection), a, ATOM(XdndSelection), tw->effectiveWinId(),
- qt_xdnd_target_current_time);
- XFlush(X11->display);
-
- XEvent xevent;
- bool got=X11->clipboardWaitForEvent(tw->effectiveWinId(), SelectionNotify, &xevent, 5000);
- if (got) {
- Atom type;
-
- if (X11->clipboardReadProperty(tw->effectiveWinId(), ATOM(XdndSelection), true, &result, 0, &type, 0)) {
- if (type == ATOM(INCR)) {
- int nbytes = result.size() >= 4 ? *((int*)result.data()) : 0;
- result = X11->clipboardReadIncrementalProperty(tw->effectiveWinId(), ATOM(XdndSelection), nbytes, false);
- } else if (type != a && type != XNone) {
- DEBUG("Qt clipboard: unknown atom %ld", type);
- }
- }
- }
- if (!qt_xdnd_current_widget || (qt_xdnd_current_widget->windowType() == Qt::Desktop))
- delete tw;
-
- return X11->xdndMimeConvertToFormat(a, result, QLatin1String(format), requestedType, encoding);
-}
-
-
-/*
- Enable drag and drop for widget w by installing the proper
- properties on w's toplevel widget.
-*/
-bool QX11Data::dndEnable(QWidget* w, bool on)
-{
- w = w->window();
-
- if (bool(((QExtraWidget*)w)->topData()->dnd) == on)
- return true; // been there, done that
- ((QExtraWidget*)w)->topData()->dnd = on ? 1 : 0;
-
- motifdndEnable(w, on);
- return xdndEnable(w, on);
-}
-
-Qt::DropAction QDragManager::drag(QDrag * o)
-{
- if (object == o || !o || !o->d_func()->source)
- return Qt::IgnoreAction;
-
- if (object) {
- cancel();
- qApp->removeEventFilter(this);
- beingCancelled = false;
- }
-
- if (object) {
- // the last drag and drop operation hasn't finished, so we are going to wait
- // for one second to see if it does... if the finish message comes after this,
- // then we could still have problems, but this is highly unlikely
- QApplication::flush();
-
- QElapsedTimer timer;
- timer.start();
- do {
- XEvent event;
- if (XCheckTypedEvent(X11->display, ClientMessage, &event))
- qApp->x11ProcessEvent(&event);
-
- // sleep 50 ms, so we don't use up CPU cycles all the time.
- struct timeval usleep_tv;
- usleep_tv.tv_sec = 0;
- usleep_tv.tv_usec = 50000;
- select(0, 0, 0, 0, &usleep_tv);
- } while (object && timer.hasExpired(1000));
- }
-
- object = o;
- object->d_func()->target = 0;
- xdnd_data.deco = new QShapedPixmapWidget(object->source()->window());
-
- willDrop = false;
-
- updatePixmap();
-
- qApp->installEventFilter(this);
- XSetSelectionOwner(X11->display, ATOM(XdndSelection), dragPrivate()->source->window()->internalWinId(), X11->time);
- global_accepted_action = Qt::CopyAction;
- qt_xdnd_source_sameanswer = QRect();
-#ifndef QT_NO_CURSOR
- // set the override cursor (must be done here, since it is updated
- // in the call to move() below)
- qApp->setOverrideCursor(Qt::ArrowCursor);
- restoreCursor = true;
-#endif
- move(QCursor::pos());
- heartbeat = startTimer(200);
-
- qt_xdnd_dragging = true;
-
- if (!QWidget::mouseGrabber())
- xdnd_data.deco->grabMouse();
-
- eventLoop = new QEventLoop;
- (void) eventLoop->exec();
- delete eventLoop;
- eventLoop = 0;
-
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- qApp->restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-
- // delete cursors as they may be different next drag.
- delete noDropCursor;
- noDropCursor = 0;
- delete copyCursor;
- copyCursor = 0;
- delete moveCursor;
- moveCursor = 0;
- delete linkCursor;
- linkCursor = 0;
-
- delete xdnd_data.deco;
- xdnd_data.deco = 0;
- if (heartbeat != -1)
- killTimer(heartbeat);
- heartbeat = -1;
- qt_xdnd_current_screen = -1;
- qt_xdnd_dragging = false;
-
- return global_accepted_action;
- // object persists until we get an xdnd_finish message
-}
-
-void QDragManager::updatePixmap()
-{
- if (xdnd_data.deco) {
- QPixmap pm;
- QPoint pm_hot(default_pm_hotx,default_pm_hoty);
- if (object) {
- pm = dragPrivate()->pixmap;
- if (!pm.isNull())
- pm_hot = dragPrivate()->hotspot;
- }
- if (pm.isNull()) {
- if (!defaultPm)
- defaultPm = new QPixmap(default_pm);
- pm = *defaultPm;
- }
- xdnd_data.deco->pm_hot = pm_hot;
- xdnd_data.deco->setPixmap(pm);
- xdnd_data.deco->move(QCursor::pos()-pm_hot);
- xdnd_data.deco->show();
- }
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mimetype, QVariant::Type requestedType) const
-{
- QByteArray mime = mimetype.toLatin1();
- QVariant data = X11->motifdnd_active
- ? X11->motifdndObtainData(mime)
- : xdndObtainData(mime, requestedType);
- return data;
-}
-
-bool QDropData::hasFormat_sys(const QString &format) const
-{
- return formats().contains(format);
-}
-
-QStringList QDropData::formats_sys() const
-{
- QStringList formats;
- if (X11->motifdnd_active) {
- int i = 0;
- QByteArray fmt;
- while (!(fmt = X11->motifdndFormat(i)).isEmpty()) {
- formats.append(QLatin1String(fmt));
- ++i;
- }
- } else {
- int i = 0;
- while ((qt_xdnd_types[i])) {
- QStringList formatsForAtom = X11->xdndMimeFormatsForAtom(qt_xdnd_types[i]);
- for (int j = 0; j < formatsForAtom.size(); ++j) {
- if (!formats.contains(formatsForAtom.at(j)))
- formats.append(formatsForAtom.at(j));
- }
- ++i;
- }
- }
- return formats;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DRAGANDDROP
diff --git a/src/gui/platforms/x11/qeventdispatcher_x11.cpp b/src/gui/platforms/x11/qeventdispatcher_x11.cpp
deleted file mode 100644
index 110786a378..0000000000
--- a/src/gui/platforms/x11/qeventdispatcher_x11.cpp
+++ /dev/null
@@ -1,191 +0,0 @@
-/****************************************************************************
-**
-** 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 "qeventdispatcher_x11_p.h"
-
-#include "qapplication.h"
-#include "qx11info_x11.h"
-
-#include "qt_x11_p.h"
-#include <private/qeventdispatcher_unix_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QEventDispatcherX11Private : public QEventDispatcherUNIXPrivate
-{
- Q_DECLARE_PUBLIC(QEventDispatcherX11)
-public:
- inline QEventDispatcherX11Private()
- : xfd(-1)
- { }
- int xfd;
- QList<XEvent> queuedUserInputEvents;
-};
-
-QEventDispatcherX11::QEventDispatcherX11(QObject *parent)
- : QEventDispatcherUNIX(*new QEventDispatcherX11Private, parent)
-{ }
-
-QEventDispatcherX11::~QEventDispatcherX11()
-{ }
-
-bool QEventDispatcherX11::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
- Q_D(QEventDispatcherX11);
-
- d->interrupt = false;
- QApplication::sendPostedEvents();
-
- ulong marker = XNextRequest(X11->display);
- int nevents = 0;
- do {
- while (!d->interrupt) {
- XEvent event;
- if (!(flags & QEventLoop::ExcludeUserInputEvents)
- && !d->queuedUserInputEvents.isEmpty()) {
- // process a pending user input event
- event = d->queuedUserInputEvents.takeFirst();
- } else if (XEventsQueued(X11->display, QueuedAlready)) {
- // process events from the X server
- XNextEvent(X11->display, &event);
-
- if (flags & QEventLoop::ExcludeUserInputEvents) {
- // queue user input events
- switch (event.type) {
- case ButtonPress:
- case ButtonRelease:
- case MotionNotify:
- case XKeyPress:
- case XKeyRelease:
- case EnterNotify:
- case LeaveNotify:
- d->queuedUserInputEvents.append(event);
- continue;
-
- case ClientMessage:
- // only keep the wm_take_focus and
- // _qt_scrolldone protocols, queue all other
- // client messages
- if (event.xclient.format == 32) {
- if (event.xclient.message_type == ATOM(WM_PROTOCOLS) &&
- (Atom) event.xclient.data.l[0] == ATOM(WM_TAKE_FOCUS)) {
- break;
- } else if (event.xclient.message_type == ATOM(_QT_SCROLL_DONE)) {
- break;
- }
- }
- d->queuedUserInputEvents.append(event);
- continue;
-
- default:
- break;
- }
- }
- } else {
- // no event to process
- break;
- }
-
- // send through event filter
- if (filterEvent(&event))
- continue;
-
- nevents++;
- if (qApp->x11ProcessEvent(&event) == 1)
- return true;
-
- if (event.xany.serial >= marker) {
- if (XEventsQueued(X11->display, QueuedAfterFlush))
- flags &= ~QEventLoop::WaitForMoreEvents;
- goto out;
- }
- }
- } while (!d->interrupt && XEventsQueued(X11->display, QueuedAfterFlush));
-
- out:
- if (!d->interrupt) {
- const uint exclude_all =
- QEventLoop::ExcludeSocketNotifiers | QEventLoop::X11ExcludeTimers | QEventLoop::WaitForMoreEvents;
- if (nevents > 0 && ((uint)flags & exclude_all) == exclude_all) {
- QApplication::sendPostedEvents();
- return nevents > 0;
- }
- // return true if we handled events, false otherwise
- return QEventDispatcherUNIX::processEvents(flags) || (nevents > 0);
- }
- return nevents > 0;
-}
-
-bool QEventDispatcherX11::hasPendingEvents()
-{
- extern uint qGlobalPostedEventsCount(); // from qapplication.cpp
- return (qGlobalPostedEventsCount() || XPending(X11->display));
-}
-
-void QEventDispatcherX11::flush()
-{
- XFlush(X11->display);
-}
-
-void QEventDispatcherX11::startingUp()
-{
- Q_D(QEventDispatcherX11);
- d->xfd = XConnectionNumber(X11->display);
-}
-
-void QEventDispatcherX11::closingDown()
-{
- Q_D(QEventDispatcherX11);
- d->xfd = -1;
-}
-
-int QEventDispatcherX11::select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
- timeval *timeout)
-{
- Q_D(QEventDispatcherX11);
- if (d->xfd > 0) {
- nfds = qMax(nfds - 1, d->xfd) + 1;
- FD_SET(d->xfd, readfds);
- }
- return QEventDispatcherUNIX::select(nfds, readfds, writefds, exceptfds, timeout);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qeventdispatcher_x11_p.h b/src/gui/platforms/x11/qeventdispatcher_x11_p.h
deleted file mode 100644
index cfdd2a5fa6..0000000000
--- a/src/gui/platforms/x11/qeventdispatcher_x11_p.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** 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 QEVENTDISPATCHER_X11_P_H
-#define QEVENTDISPATCHER_X11_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qeventdispatcher_unix_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QEventDispatcherX11Private;
-
-class QEventDispatcherX11 : public QEventDispatcherUNIX
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QEventDispatcherX11)
-
-public:
- explicit QEventDispatcherX11(QObject *parent = 0);
- ~QEventDispatcherX11();
-
- bool processEvents(QEventLoop::ProcessEventsFlags flags);
- bool hasPendingEvents();
-
- void flush();
-
- void startingUp();
- void closingDown();
-
-protected:
- int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
- timeval *timeout);
-};
-
-QT_END_NAMESPACE
-
-#endif // QEVENTDISPATCHER_X11_P_H
diff --git a/src/gui/platforms/x11/qfont_x11.cpp b/src/gui/platforms/x11/qfont_x11.cpp
deleted file mode 100644
index c72a5fade5..0000000000
--- a/src/gui/platforms/x11/qfont_x11.cpp
+++ /dev/null
@@ -1,368 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#define QT_FATAL_ASSERT
-
-#include "qplatformdefs.h"
-
-#include "qfont.h"
-#include "qapplication.h"
-#include "qfontinfo.h"
-#include "qfontdatabase.h"
-#include "qfontmetrics.h"
-#include "qpaintdevice.h"
-#include "qtextcodec.h"
-#include "qiodevice.h"
-#include "qhash.h"
-
-#include <private/qunicodetables_p.h>
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qfontengine_x11_p.h"
-#include "qtextengine_p.h"
-
-#include <private/qt_x11_p.h>
-#include "qx11info_x11.h"
-
-#include <time.h>
-#include <stdlib.h>
-#include <ctype.h>
-
-#define QFONTLOADER_DEBUG
-#define QFONTLOADER_DEBUG_VERBOSE
-
-QT_BEGIN_NAMESPACE
-
-double qt_pixelSize(double pointSize, int dpi)
-{
- if (pointSize < 0)
- return -1.;
- if (dpi == 75) // the stupid 75 dpi setting on X11
- dpi = 72;
- return (pointSize * dpi) /72.;
-}
-
-double qt_pointSize(double pixelSize, int dpi)
-{
- if (pixelSize < 0)
- return -1.;
- if (dpi == 75) // the stupid 75 dpi setting on X11
- dpi = 72;
- return pixelSize * 72. / ((double) dpi);
-}
-
-/*
- Removes wildcards from an XLFD.
-
- Returns \a xlfd with all wildcards removed if a match for \a xlfd is
- found, otherwise it returns \a xlfd.
-*/
-static QByteArray qt_fixXLFD(const QByteArray &xlfd)
-{
- QByteArray ret = xlfd;
- int count = 0;
- char **fontNames =
- XListFonts(QX11Info::display(), xlfd, 32768, &count);
- if (count > 0)
- ret = fontNames[0];
- XFreeFontNames(fontNames);
- return ret ;
-}
-
-typedef QHash<int, QString> FallBackHash;
-Q_GLOBAL_STATIC(FallBackHash, fallBackHash)
-
-// Returns the user-configured fallback family for the specified script.
-QString qt_fallback_font_family(int script)
-{
- FallBackHash *hash = fallBackHash();
- return hash->value(script);
-}
-
-// Sets the fallback family for the specified script.
-Q_GUI_EXPORT void qt_x11_set_fallback_font_family(int script, const QString &family)
-{
- FallBackHash *hash = fallBackHash();
- if (!family.isEmpty())
- hash->insert(script, family);
- else
- hash->remove(script);
-}
-
-int QFontPrivate::defaultEncodingID = -1;
-
-void QFont::initialize()
-{
- extern int qt_encoding_id_for_mib(int mib); // from qfontdatabase_x11.cpp
- QTextCodec *codec = QTextCodec::codecForLocale();
- // determine the default encoding id using the locale, otherwise
- // fallback to latin1 (mib == 4)
- int mib = codec ? codec->mibEnum() : 4;
-
- // for asian locales, use the mib for the font codec instead of the locale codec
- switch (mib) {
- case 38: // eucKR
- mib = 36;
- break;
-
- case 2025: // GB2312
- mib = 57;
- break;
-
- case 113: // GBK
- mib = -113;
- break;
-
- case 114: // GB18030
- mib = -114;
- break;
-
- case 2026: // Big5
- mib = -2026;
- break;
-
- case 2101: // Big5-HKSCS
- mib = -2101;
- break;
-
- case 16: // JIS7
- mib = 15;
- break;
-
- case 17: // SJIS
- case 18: // eucJP
- mib = 63;
- break;
- }
-
- // get the default encoding id for the locale encoding...
- QFontPrivate::defaultEncodingID = qt_encoding_id_for_mib(mib);
-}
-
-void QFont::cleanup()
-{
- QFontCache::cleanup();
-}
-
-/*!
- \internal
- X11 Only: Returns the screen with which this font is associated.
-*/
-int QFont::x11Screen() const
-{
- return d->screen;
-}
-
-/*! \internal
- X11 Only: Associate the font with the specified \a screen.
-*/
-void QFont::x11SetScreen(int screen)
-{
- if (screen < 0) // assume default
- screen = QX11Info::appScreen();
-
- if (screen == d->screen)
- return; // nothing to do
-
- detach();
- d->screen = screen;
-}
-
-Qt::HANDLE QFont::handle() const
-{
- QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
- Q_ASSERT(engine != 0);
- if (engine->type() == QFontEngine::Multi)
- engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
- if (engine->type() == QFontEngine::XLFD)
- return static_cast<QFontEngineXLFD *>(engine)->fontStruct()->fid;
- return 0;
-}
-
-
-FT_Face QFont::freetypeFace() const
-{
-#ifndef QT_NO_FREETYPE
- QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
- if (engine->type() == QFontEngine::Multi)
- engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
-#ifndef QT_NO_FONTCONFIG
- if (engine->type() == QFontEngine::Freetype) {
- const QFontEngineFT *ft = static_cast<const QFontEngineFT *>(engine);
- return ft->non_locked_face();
- } else
-#endif
- if (engine->type() == QFontEngine::XLFD) {
- const QFontEngineXLFD *xlfd = static_cast<const QFontEngineXLFD *>(engine);
- return xlfd->non_locked_face();
- }
-#endif
- return 0;
-}
-
-QString QFont::rawName() const
-{
- QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
- Q_ASSERT(engine != 0);
- if (engine->type() == QFontEngine::Multi)
- engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
- if (engine->type() == QFontEngine::XLFD)
- return QString::fromLatin1(engine->name());
- return QString();
-}
-struct QtFontDesc;
-
-void QFont::setRawName(const QString &name)
-{
- detach();
-
- // from qfontdatabase_x11.cpp
- extern bool qt_fillFontDef(const QByteArray &xlfd, QFontDef *fd, int dpi, QtFontDesc *desc);
-
- if (!qt_fillFontDef(qt_fixXLFD(name.toLatin1()), &d->request, d->dpi, 0)) {
- qWarning("QFont::setRawName: Invalid XLFD: \"%s\"", name.toLatin1().constData());
-
- setFamily(name);
- setRawMode(true);
- } else {
- resolve_mask = QFont::AllPropertiesResolved;
- }
-}
-
-QString QFont::lastResortFamily() const
-{
- return QString::fromLatin1("Helvetica");
-}
-
-QString QFont::defaultFamily() const
-{
- switch (d->request.styleHint) {
- case QFont::Times:
- return QString::fromLatin1("Times");
-
- case QFont::Courier:
- return QString::fromLatin1("Courier");
-
- case QFont::Monospace:
- return QString::fromLatin1("Courier New");
-
- case QFont::Cursive:
- return QString::fromLatin1("Comic Sans MS");
-
- case QFont::Fantasy:
- return QString::fromLatin1("Impact");
-
- case QFont::Decorative:
- return QString::fromLatin1("Old English");
-
- case QFont::Helvetica:
- case QFont::System:
- default:
- return QString::fromLatin1("Helvetica");
- }
-}
-
-/*
- Returns a last resort raw font name for the font matching algorithm.
- This is used if even the last resort family is not available. It
- returns \e something, almost no matter what. The current
- implementation tries a wide variety of common fonts, returning the
- first one it finds. The implementation may change at any time.
-*/
-static const char * const tryFonts[] = {
- "-*-helvetica-medium-r-*-*-*-120-*-*-*-*-*-*",
- "-*-courier-medium-r-*-*-*-120-*-*-*-*-*-*",
- "-*-times-medium-r-*-*-*-120-*-*-*-*-*-*",
- "-*-lucida-medium-r-*-*-*-120-*-*-*-*-*-*",
- "-*-helvetica-*-*-*-*-*-120-*-*-*-*-*-*",
- "-*-courier-*-*-*-*-*-120-*-*-*-*-*-*",
- "-*-times-*-*-*-*-*-120-*-*-*-*-*-*",
- "-*-lucida-*-*-*-*-*-120-*-*-*-*-*-*",
- "-*-helvetica-*-*-*-*-*-*-*-*-*-*-*-*",
- "-*-courier-*-*-*-*-*-*-*-*-*-*-*-*",
- "-*-times-*-*-*-*-*-*-*-*-*-*-*-*",
- "-*-lucida-*-*-*-*-*-*-*-*-*-*-*-*",
- "-*-fixed-*-*-*-*-*-*-*-*-*-*-*-*",
- "6x13",
- "7x13",
- "8x13",
- "9x15",
- "fixed",
- 0
-};
-
-// Returns true if the font exists, false otherwise
-static bool fontExists(const QString &fontName)
-{
- int count;
- char **fontNames = XListFonts(QX11Info::display(), (char*)fontName.toLatin1().constData(), 32768, &count);
- if (fontNames) XFreeFontNames(fontNames);
-
- return count != 0;
-}
-
-QString QFont::lastResortFont() const
-{
- static QString last;
-
- // already found
- if (! last.isNull())
- return last;
-
- int i = 0;
- const char* f;
-
- while ((f = tryFonts[i])) {
- last = QString::fromLatin1(f);
-
- if (fontExists(last))
- return last;
-
- i++;
- }
-
-#if defined(CHECK_NULL)
- qFatal("QFontPrivate::lastResortFont: Cannot find any reasonable font");
-#endif
- return last;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qfontdatabase_x11.cpp b/src/gui/platforms/x11/qfontdatabase_x11.cpp
deleted file mode 100644
index 0c0c4c8343..0000000000
--- a/src/gui/platforms/x11/qfontdatabase_x11.cpp
+++ /dev/null
@@ -1,2146 +0,0 @@
-/****************************************************************************
-**
-** 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 <qdebug.h>
-#include <qpaintdevice.h>
-#include <qelapsedtimer.h>
-
-#include <private/qt_x11_p.h>
-#include "qx11info_x11.h"
-#include <qdebug.h>
-#include <qfile.h>
-#include <qtemporaryfile.h>
-#include <qabstractfileengine.h>
-#include <qmath.h>
-
-#include <ctype.h>
-#include <stdlib.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <sys/mman.h>
-
-#include <private/qfontengine_x11_p.h>
-
-#ifndef QT_NO_FONTCONFIG
-#include <ft2build.h>
-#include FT_FREETYPE_H
-
-#if FC_VERSION >= 20402
-#include <fontconfig/fcfreetype.h>
-#endif
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// from qfont_x11.cpp
-extern double qt_pointSize(double pixelSize, int dpi);
-extern double qt_pixelSize(double pointSize, int dpi);
-
-// from qapplication.cpp
-extern bool qt_is_gui_used;
-
-static inline void capitalize (char *s)
-{
- bool space = true;
- while(*s) {
- if (space)
- *s = toupper(*s);
- space = (*s == ' ');
- ++s;
- }
-}
-
-
-/*
- To regenerate the writingSystems_for_xlfd_encoding table, run
- 'util/unicode/x11/makeencodings' and paste the generated
- 'encodings.c' here.
-*/
-// ----- begin of generated code -----
-
-#define make_tag( c1, c2, c3, c4 ) \
- ((((unsigned int)c1)<<24) | (((unsigned int)c2)<<16) | \
- (((unsigned int)c3)<<8) | ((unsigned int)c4))
-
-struct XlfdEncoding {
- const char *name;
- int id;
- int mib;
- unsigned int hash1;
- unsigned int hash2;
-};
-
-static const XlfdEncoding xlfd_encoding[] = {
- { "iso8859-1", 0, 4, make_tag('i','s','o','8'), make_tag('5','9','-','1') },
- { "iso8859-2", 1, 5, make_tag('i','s','o','8'), make_tag('5','9','-','2') },
- { "iso8859-3", 2, 6, make_tag('i','s','o','8'), make_tag('5','9','-','3') },
- { "iso8859-4", 3, 7, make_tag('i','s','o','8'), make_tag('5','9','-','4') },
- { "iso8859-9", 4, 12, make_tag('i','s','o','8'), make_tag('5','9','-','9') },
- { "iso8859-10", 5, 13, make_tag('i','s','o','8'), make_tag('9','-','1','0') },
- { "iso8859-13", 6, 109, make_tag('i','s','o','8'), make_tag('9','-','1','3') },
- { "iso8859-14", 7, 110, make_tag('i','s','o','8'), make_tag('9','-','1','4') },
- { "iso8859-15", 8, 111, make_tag('i','s','o','8'), make_tag('9','-','1','5') },
- { "hp-roman8", 9, 2004, make_tag('h','p','-','r'), make_tag('m','a','n','8') },
- { "iso8859-5", 10, 8, make_tag('i','s','o','8'), make_tag('5','9','-','5') },
- { "*-cp1251", 11, 2251, 0, make_tag('1','2','5','1') },
- { "koi8-ru", 12, 2084, make_tag('k','o','i','8'), make_tag('8','-','r','u') },
- { "koi8-u", 13, 2088, make_tag('k','o','i','8'), make_tag('i','8','-','u') },
- { "koi8-r", 14, 2084, make_tag('k','o','i','8'), make_tag('i','8','-','r') },
- { "iso8859-7", 15, 10, make_tag('i','s','o','8'), make_tag('5','9','-','7') },
- { "iso8859-8", 16, 85, make_tag('i','s','o','8'), make_tag('5','9','-','8') },
- { "gb18030-0", 17, -114, make_tag('g','b','1','8'), make_tag('3','0','-','0') },
- { "gb18030.2000-0", 18, -113, make_tag('g','b','1','8'), make_tag('0','0','-','0') },
- { "gbk-0", 19, -113, make_tag('g','b','k','-'), make_tag('b','k','-','0') },
- { "gb2312.*-0", 20, 57, make_tag('g','b','2','3'), 0 },
- { "jisx0201*-0", 21, 15, make_tag('j','i','s','x'), 0 },
- { "jisx0208*-0", 22, 63, make_tag('j','i','s','x'), 0 },
- { "ksc5601*-*", 23, 36, make_tag('k','s','c','5'), 0 },
- { "big5hkscs-0", 24, -2101, make_tag('b','i','g','5'), make_tag('c','s','-','0') },
- { "hkscs-1", 25, -2101, make_tag('h','k','s','c'), make_tag('c','s','-','1') },
- { "big5*-*", 26, -2026, make_tag('b','i','g','5'), 0 },
- { "tscii-*", 27, 2028, make_tag('t','s','c','i'), 0 },
- { "tis620*-*", 28, 2259, make_tag('t','i','s','6'), 0 },
- { "iso8859-11", 29, 2259, make_tag('i','s','o','8'), make_tag('9','-','1','1') },
- { "mulelao-1", 30, -4242, make_tag('m','u','l','e'), make_tag('a','o','-','1') },
- { "ethiopic-unicode", 31, 0, make_tag('e','t','h','i'), make_tag('c','o','d','e') },
- { "iso10646-1", 32, 0, make_tag('i','s','o','1'), make_tag('4','6','-','1') },
- { "unicode-*", 33, 0, make_tag('u','n','i','c'), 0 },
- { "*-symbol", 34, 0, 0, make_tag('m','b','o','l') },
- { "*-fontspecific", 35, 0, 0, make_tag('i','f','i','c') },
- { "fontspecific-*", 36, 0, make_tag('f','o','n','t'), 0 },
- { 0, 0, 0, 0, 0 }
-};
-
-static const char writingSystems_for_xlfd_encoding[sizeof(xlfd_encoding)][QFontDatabase::WritingSystemsCount] = {
- // iso8859-1
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-2
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-3
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-4
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-9
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-10
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-13
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-14
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-15
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // hp-roman8
- { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-5
- { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // *-cp1251
- { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // koi8-ru
- { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // koi8-u
- { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // koi8-r
- { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-7
- { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-8
- { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // gb18030-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
- 0, 0 },
- // gb18030.2000-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
- 0, 0 },
- // gbk-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
- 0, 0 },
- // gb2312.*-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
- 0, 0 },
- // jisx0201*-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
- 0, 0 },
- // jisx0208*-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
- 0, 0 },
- // ksc5601*-*
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
- 0, 0 },
- // big5hkscs-0
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
- 0, 0 },
- // hkscs-1
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
- 0, 0 },
- // big5*-*
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
- 0, 0 },
- // tscii-*
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // tis620*-*
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso8859-11
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // mulelao-1
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // ethiopic-unicode
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0 },
- // iso10646-1
- { 0, 1, 1, 1, 1, 1, 1, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
- 1, 1, 0, 1, 0, 1, 1, 0, 0, 0,
- 0, 0 },
- // unicode-*
- { 0, 1, 1, 1, 1, 1, 1, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
- 1, 1, 0, 1, 0, 1, 1, 0, 0, 0,
- 0, 0 },
- // *-symbol
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 0 },
- // *-fontspecific
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 0 },
- // fontspecific-*
- { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 0 }
-
-};
-
-// ----- end of generated code -----
-
-
-const int numEncodings = sizeof(xlfd_encoding) / sizeof(XlfdEncoding) - 1;
-
-int qt_xlfd_encoding_id(const char *encoding)
-{
- // qDebug("looking for encoding id for '%s'", encoding);
- int len = strlen(encoding);
- if (len < 4)
- return -1;
- unsigned int hash1 = make_tag(encoding[0], encoding[1], encoding[2], encoding[3]);
- const char *ch = encoding + len - 4;
- unsigned int hash2 = make_tag(ch[0], ch[1], ch[2], ch[3]);
-
- const XlfdEncoding *enc = xlfd_encoding;
- for (; enc->name; ++enc) {
- if ((enc->hash1 && enc->hash1 != hash1) ||
- (enc->hash2 && enc->hash2 != hash2))
- continue;
- // hashes match, do a compare if strings match
- // the enc->name can contain '*'s we have to interpret correctly
- const char *n = enc->name;
- const char *e = encoding;
- while (1) {
- // qDebug("bol: *e='%c', *n='%c'", *e, *n);
- if (*e == '\0') {
- if (*n)
- break;
- // qDebug("found encoding id %d", enc->id);
- return enc->id;
- }
- if (*e == *n) {
- ++e;
- ++n;
- continue;
- }
- if (*n != '*')
- break;
- ++n;
- // qDebug("skip: *e='%c', *n='%c'", *e, *n);
- while (*e && *e != *n)
- ++e;
- }
- }
- // qDebug("couldn't find encoding %s", encoding);
- return -1;
-}
-
-int qt_mib_for_xlfd_encoding(const char *encoding)
-{
- int id = qt_xlfd_encoding_id(encoding);
- if (id != -1) return xlfd_encoding[id].mib;
- return 0;
-}
-
-int qt_encoding_id_for_mib(int mib)
-{
- const XlfdEncoding *enc = xlfd_encoding;
- for (; enc->name; ++enc) {
- if (enc->mib == mib)
- return enc->id;
- }
- return -1;
-}
-
-static const char * xlfd_for_id(int id)
-{
- // special case: -1 returns the "*-*" encoding, allowing us to do full
- // database population in a single X server round trip.
- if (id < 0 || id > numEncodings)
- return "*-*";
- return xlfd_encoding[id].name;
-}
-
-enum XLFDFieldNames {
- Foundry,
- Family,
- Weight,
- Slant,
- Width,
- AddStyle,
- PixelSize,
- PointSize,
- ResolutionX,
- ResolutionY,
- Spacing,
- AverageWidth,
- CharsetRegistry,
- CharsetEncoding,
- NFontFields
-};
-
-// Splits an X font name into fields separated by '-'
-static bool parseXFontName(char *fontName, char **tokens)
-{
- if (! fontName || fontName[0] == '0' || fontName[0] != '-') {
- tokens[0] = 0;
- return false;
- }
-
- int i;
- ++fontName;
- for (i = 0; i < NFontFields && fontName && fontName[0]; ++i) {
- tokens[i] = fontName;
- for (;; ++fontName) {
- if (*fontName == '-')
- break;
- if (! *fontName) {
- fontName = 0;
- break;
- }
- }
-
- if (fontName) *fontName++ = '\0';
- }
-
- if (i < NFontFields) {
- for (int j = i ; j < NFontFields; ++j)
- tokens[j] = 0;
- return false;
- }
-
- return true;
-}
-
-static inline bool isZero(char *x)
-{
- return (x[0] == '0' && x[1] == 0);
-}
-
-static inline bool isScalable(char **tokens)
-{
- return (isZero(tokens[PixelSize]) &&
- isZero(tokens[PointSize]) &&
- isZero(tokens[AverageWidth]));
-}
-
-static inline bool isSmoothlyScalable(char **tokens)
-{
- return (isZero(tokens[ResolutionX]) &&
- isZero(tokens[ResolutionY]));
-}
-
-static inline bool isFixedPitch(char **tokens)
-{
- return (tokens[Spacing][0] == 'm' ||
- tokens[Spacing][0] == 'c' ||
- tokens[Spacing][0] == 'M' ||
- tokens[Spacing][0] == 'C');
-}
-
-/*
- Fills in a font definition (QFontDef) from an XLFD (X Logical Font
- Description).
-
- Returns true if the given xlfd is valid.
-*/
-bool qt_fillFontDef(const QByteArray &xlfd, QFontDef *fd, int dpi, QtFontDesc *desc)
-{
- char *tokens[NFontFields];
- QByteArray buffer = xlfd;
- if (! parseXFontName(buffer.data(), tokens))
- return false;
-
- capitalize(tokens[Family]);
- capitalize(tokens[Foundry]);
-
- fd->styleStrategy |= QFont::NoAntialias;
- fd->family = QString::fromLatin1(tokens[Family]);
- QString foundry = QString::fromLatin1(tokens[Foundry]);
- if (! foundry.isEmpty() && foundry != QLatin1String("*") && (!desc || desc->family->count > 1))
- fd->family +=
- QLatin1String(" [") + foundry + QLatin1Char(']');
-
- if (qstrlen(tokens[AddStyle]) > 0)
- fd->addStyle = QString::fromLatin1(tokens[AddStyle]);
- else
- fd->addStyle.clear();
-
- fd->pointSize = atoi(tokens[PointSize])/10.;
- fd->styleHint = QFont::AnyStyle; // ### any until we match families
-
- char slant = tolower((uchar) tokens[Slant][0]);
- fd->style = (slant == 'o' ? QFont::StyleOblique : (slant == 'i' ? QFont::StyleItalic : QFont::StyleNormal));
- char fixed = tolower((uchar) tokens[Spacing][0]);
- fd->fixedPitch = (fixed == 'm' || fixed == 'c');
- fd->weight = getFontWeight(QLatin1String(tokens[Weight]));
-
- int r = atoi(tokens[ResolutionY]);
- fd->pixelSize = atoi(tokens[PixelSize]);
- // not "0" or "*", or required DPI
- if (r && fd->pixelSize && r != dpi) {
- // calculate actual pointsize for display DPI
- fd->pointSize = qt_pointSize(fd->pixelSize, dpi);
- } else if (fd->pixelSize == 0 && fd->pointSize) {
- // calculate pixel size from pointsize/dpi
- fd->pixelSize = qRound(qt_pixelSize(fd->pointSize, dpi));
- }
-
- return true;
-}
-
-/*
- Fills in a font definition (QFontDef) from the font properties in an
- XFontStruct.
-
- Returns true if the QFontDef could be filled with properties from
- the XFontStruct.
-*/
-static bool qt_fillFontDef(XFontStruct *fs, QFontDef *fd, int dpi, QtFontDesc *desc)
-{
- unsigned long value;
- if (!fs || !XGetFontProperty(fs, XA_FONT, &value))
- return false;
-
- char *n = XGetAtomName(QX11Info::display(), value);
- QByteArray xlfd(n);
- if (n)
- XFree(n);
- return qt_fillFontDef(xlfd.toLower(), fd, dpi, desc);
-}
-
-
-static QtFontStyle::Key getStyle(char ** tokens)
-{
- QtFontStyle::Key key;
-
- char slant0 = tolower((uchar) tokens[Slant][0]);
-
- if (slant0 == 'r') {
- if (tokens[Slant][1]) {
- char slant1 = tolower((uchar) tokens[Slant][1]);
-
- if (slant1 == 'o')
- key.style = QFont::StyleOblique;
- else if (slant1 == 'i')
- key.style = QFont::StyleItalic;
- }
- } else if (slant0 == 'o')
- key.style = QFont::StyleOblique;
- else if (slant0 == 'i')
- key.style = QFont::StyleItalic;
-
- key.weight = getFontWeight(QLatin1String(tokens[Weight]));
-
- if (qstrcmp(tokens[Width], "normal") == 0) {
- key.stretch = 100;
- } else if (qstrcmp(tokens[Width], "semi condensed") == 0 ||
- qstrcmp(tokens[Width], "semicondensed") == 0) {
- key.stretch = 90;
- } else if (qstrcmp(tokens[Width], "condensed") == 0) {
- key.stretch = 80;
- } else if (qstrcmp(tokens[Width], "narrow") == 0) {
- key.stretch = 60;
- }
-
- return key;
-}
-
-
-static bool xlfdsFullyLoaded = false;
-static unsigned char encodingLoaded[numEncodings];
-
-static void loadXlfds(const char *reqFamily, int encoding_id)
-{
- QFontDatabasePrivate *db = privateDb();
- QtFontFamily *fontFamily = reqFamily ? db->family(QLatin1String(reqFamily)) : 0;
-
- // make sure we don't load twice
- if ((encoding_id == -1 && xlfdsFullyLoaded)
- || (encoding_id != -1 && encodingLoaded[encoding_id]))
- return;
- if (fontFamily && fontFamily->xlfdLoaded)
- return;
-
- int fontCount;
- // force the X server to give us XLFDs
- QByteArray xlfd_pattern("-*-");
- xlfd_pattern += (reqFamily && reqFamily[0] != '\0') ? reqFamily : "*";
- xlfd_pattern += "-*-*-*-*-*-*-*-*-*-*-";
- xlfd_pattern += xlfd_for_id(encoding_id);
-
- char **fontList = XListFonts(QX11Info::display(),
- xlfd_pattern,
- 0xffff, &fontCount);
- // qDebug("requesting xlfd='%s', got %d fonts", xlfd_pattern.data(), fontCount);
-
-
- char *tokens[NFontFields];
-
- for(int i = 0 ; i < fontCount ; i++) {
- if (! parseXFontName(fontList[i], tokens))
- continue;
-
- // get the encoding_id for this xlfd. we need to do this
- // here, since we can pass -1 to this function to do full
- // database population
- *(tokens[CharsetEncoding] - 1) = '-';
- int encoding_id = qt_xlfd_encoding_id(tokens[CharsetRegistry]);
- if (encoding_id == -1)
- continue;
-
- char *familyName = tokens[Family];
- capitalize(familyName);
- char *foundryName = tokens[Foundry];
- capitalize(foundryName);
- QtFontStyle::Key styleKey = getStyle(tokens);
-
- bool smooth_scalable = false;
- bool bitmap_scalable = false;
- if (isScalable(tokens)) {
- if (isSmoothlyScalable(tokens))
- smooth_scalable = true;
- else
- bitmap_scalable = true;
- }
- uint pixelSize = atoi(tokens[PixelSize]);
- uint xpointSize = atoi(tokens[PointSize]);
- uint xres = atoi(tokens[ResolutionX]);
- uint yres = atoi(tokens[ResolutionY]);
- uint avgwidth = atoi(tokens[AverageWidth]);
- bool fixedPitch = isFixedPitch(tokens);
-
- if (avgwidth == 0 && pixelSize != 0) {
- /*
- Ignore bitmap scalable fonts that are automatically
- generated by some X servers. We know they are bitmap
- scalable because even though they have a specified pixel
- size, the average width is zero.
- */
- continue;
- }
-
- QtFontFamily *family = fontFamily ? fontFamily : db->family(QLatin1String(familyName), true);
- family->fontFileIndex = -1;
- family->symbol_checked = true;
- QtFontFoundry *foundry = family->foundry(QLatin1String(foundryName), true);
- QtFontStyle *style = foundry->style(styleKey, true);
-
- delete [] style->weightName;
- style->weightName = qstrdup(tokens[Weight]);
- delete [] style->setwidthName;
- style->setwidthName = qstrdup(tokens[Width]);
-
- if (smooth_scalable) {
- style->smoothScalable = true;
- style->bitmapScalable = false;
- pixelSize = SMOOTH_SCALABLE;
- }
- if (!style->smoothScalable && bitmap_scalable)
- style->bitmapScalable = true;
- if (!fixedPitch)
- family->fixedPitch = false;
-
- QtFontSize *size = style->pixelSize(pixelSize, true);
- QtFontEncoding *enc =
- size->encodingID(encoding_id, xpointSize, xres, yres, avgwidth, true);
- enc->pitch = *tokens[Spacing];
- if (!enc->pitch) enc->pitch = '*';
-
- for (int i = 0; i < QFontDatabase::WritingSystemsCount; ++i) {
- if (writingSystems_for_xlfd_encoding[encoding_id][i])
- family->writingSystems[i] = QtFontFamily::Supported;
- }
- }
- if (!reqFamily) {
- // mark encoding as loaded
- if (encoding_id == -1)
- xlfdsFullyLoaded = true;
- else
- encodingLoaded[encoding_id] = true;
- }
-
- XFreeFontNames(fontList);
-}
-
-
-#ifndef QT_NO_FONTCONFIG
-
-#ifndef FC_WIDTH
-#define FC_WIDTH "width"
-#endif
-
-static int getFCWeight(int fc_weight)
-{
- int qtweight = QFont::Black;
- if (fc_weight <= (FC_WEIGHT_LIGHT + FC_WEIGHT_MEDIUM) / 2)
- qtweight = QFont::Light;
- else if (fc_weight <= (FC_WEIGHT_MEDIUM + FC_WEIGHT_DEMIBOLD) / 2)
- qtweight = QFont::Normal;
- else if (fc_weight <= (FC_WEIGHT_DEMIBOLD + FC_WEIGHT_BOLD) / 2)
- qtweight = QFont::DemiBold;
- else if (fc_weight <= (FC_WEIGHT_BOLD + FC_WEIGHT_BLACK) / 2)
- qtweight = QFont::Bold;
-
- return qtweight;
-}
-
-QFontDef qt_FcPatternToQFontDef(FcPattern *pattern, const QFontDef &request)
-{
- QFontDef fontDef;
- fontDef.styleStrategy = request.styleStrategy;
-
- fontDef.hintingPreference = request.hintingPreference;
- FcChar8 *value = 0;
- if (FcPatternGetString(pattern, FC_FAMILY, 0, &value) == FcResultMatch) {
- fontDef.family = QString::fromUtf8(reinterpret_cast<const char *>(value));
- }
-
- double dpi;
- if (FcPatternGetDouble(pattern, FC_DPI, 0, &dpi) != FcResultMatch) {
- if (X11->display)
- dpi = QX11Info::appDpiY();
- else
- dpi = qt_defaultDpiY();
- }
-
- double size;
- if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &size) == FcResultMatch)
- fontDef.pixelSize = size;
- else
- fontDef.pixelSize = 12;
-
- fontDef.pointSize = qt_pointSize(fontDef.pixelSize, qRound(dpi));
-
- /* ###
- fontDef.styleHint
- */
-
- int weight;
- if (FcPatternGetInteger(pattern, FC_WEIGHT, 0, &weight) != FcResultMatch)
- weight = FC_WEIGHT_MEDIUM;
- fontDef.weight = getFCWeight(weight);
-
- int slant;
- if (FcPatternGetInteger(pattern, FC_SLANT, 0, &slant) != FcResultMatch)
- slant = FC_SLANT_ROMAN;
- fontDef.style = (slant == FC_SLANT_ITALIC)
- ? QFont::StyleItalic
- : ((slant == FC_SLANT_OBLIQUE)
- ? QFont::StyleOblique
- : QFont::StyleNormal);
-
-
- FcBool scalable;
- if (FcPatternGetBool(pattern, FC_SCALABLE, 0, &scalable) != FcResultMatch)
- scalable = false;
- if (scalable) {
- fontDef.stretch = request.stretch;
- fontDef.style = request.style;
- } else {
- int width;
- if (FcPatternGetInteger(pattern, FC_WIDTH, 0, &width) == FcResultMatch)
- fontDef.stretch = width;
- else
- fontDef.stretch = 100;
- }
-
- int spacing;
- if (FcPatternGetInteger(pattern, FC_SPACING, 0, &spacing) == FcResultMatch) {
- fontDef.fixedPitch = (spacing >= FC_MONO);
- fontDef.ignorePitch = false;
- } else {
- fontDef.ignorePitch = true;
- }
-
- return fontDef;
-}
-
-static const char *specialLanguages[] = {
- "en", // Common
- "el", // Greek
- "ru", // Cyrillic
- "hy", // Armenian
- "he", // Hebrew
- "ar", // Arabic
- "syr", // Syriac
- "div", // Thaana
- "hi", // Devanagari
- "bn", // Bengali
- "pa", // Gurmukhi
- "gu", // Gujarati
- "or", // Oriya
- "ta", // Tamil
- "te", // Telugu
- "kn", // Kannada
- "ml", // Malayalam
- "si", // Sinhala
- "th", // Thai
- "lo", // Lao
- "bo", // Tibetan
- "my", // Myanmar
- "ka", // Georgian
- "ko", // Hangul
- "", // Ogham
- "", // Runic
- "km", // Khmer
- "" // N'Ko
-};
-enum { SpecialLanguageCount = sizeof(specialLanguages) / sizeof(const char *) };
-
-static const ushort specialChars[] = {
- 0, // English
- 0, // Greek
- 0, // Cyrillic
- 0, // Armenian
- 0, // Hebrew
- 0, // Arabic
- 0, // Syriac
- 0, // Thaana
- 0, // Devanagari
- 0, // Bengali
- 0, // Gurmukhi
- 0, // Gujarati
- 0, // Oriya
- 0, // Tamil
- 0xc15, // Telugu
- 0xc95, // Kannada
- 0xd15, // Malayalam
- 0xd9a, // Sinhala
- 0, // Thai
- 0, // Lao
- 0, // Tibetan
- 0x1000, // Myanmar
- 0, // Georgian
- 0, // Hangul
- 0x1681, // Ogham
- 0x16a0, // Runic
- 0, // Khmer
- 0x7ca // N'Ko
-};
-enum { SpecialCharCount = sizeof(specialChars) / sizeof(ushort) };
-
-// this could become a list of all languages used for each writing
-// system, instead of using the single most common language.
-static const char *languageForWritingSystem[] = {
- 0, // Any
- "en", // Latin
- "el", // Greek
- "ru", // Cyrillic
- "hy", // Armenian
- "he", // Hebrew
- "ar", // Arabic
- "syr", // Syriac
- "div", // Thaana
- "hi", // Devanagari
- "bn", // Bengali
- "pa", // Gurmukhi
- "gu", // Gujarati
- "or", // Oriya
- "ta", // Tamil
- "te", // Telugu
- "kn", // Kannada
- "ml", // Malayalam
- "si", // Sinhala
- "th", // Thai
- "lo", // Lao
- "bo", // Tibetan
- "my", // Myanmar
- "ka", // Georgian
- "km", // Khmer
- "zh-cn", // SimplifiedChinese
- "zh-tw", // TraditionalChinese
- "ja", // Japanese
- "ko", // Korean
- "vi", // Vietnamese
- 0, // Symbol
- 0, // Ogham
- 0, // Runic
- 0 // N'Ko
-};
-enum { LanguageCount = sizeof(languageForWritingSystem) / sizeof(const char *) };
-
-// Unfortunately FontConfig doesn't know about some languages. We have to test these through the
-// charset. The lists below contain the systems where we need to do this.
-static const ushort sampleCharForWritingSystem[] = {
- 0, // Any
- 0, // Latin
- 0, // Greek
- 0, // Cyrillic
- 0, // Armenian
- 0, // Hebrew
- 0, // Arabic
- 0, // Syriac
- 0, // Thaana
- 0, // Devanagari
- 0, // Bengali
- 0, // Gurmukhi
- 0, // Gujarati
- 0, // Oriya
- 0, // Tamil
- 0xc15, // Telugu
- 0xc95, // Kannada
- 0xd15, // Malayalam
- 0xd9a, // Sinhala
- 0, // Thai
- 0, // Lao
- 0, // Tibetan
- 0x1000, // Myanmar
- 0, // Georgian
- 0, // Khmer
- 0, // SimplifiedChinese
- 0, // TraditionalChinese
- 0, // Japanese
- 0, // Korean
- 0, // Vietnamese
- 0, // Symbol
- 0x1681, // Ogham
- 0x16a0, // Runic
- 0x7ca // N'Ko
-};
-enum { SampleCharCount = sizeof(sampleCharForWritingSystem) / sizeof(ushort) };
-
-// Newer FontConfig let's us sort out fonts that contain certain glyphs, but no
-// open type tables for is directly. Do this so we don't pick some strange
-// pseudo unicode font
-static const char *openType[] = {
- 0, // Any
- 0, // Latin
- 0, // Greek
- 0, // Cyrillic
- 0, // Armenian
- 0, // Hebrew
- 0, // Arabic
- "syrc", // Syriac
- "thaa", // Thaana
- "deva", // Devanagari
- "beng", // Bengali
- "guru", // Gurmukhi
- "gurj", // Gujarati
- "orya", // Oriya
- "taml", // Tamil
- "telu", // Telugu
- "knda", // Kannada
- "mlym", // Malayalam
- "sinh", // Sinhala
- 0, // Thai
- 0, // Lao
- "tibt", // Tibetan
- "mymr", // Myanmar
- 0, // Georgian
- "khmr", // Khmer
- 0, // SimplifiedChinese
- 0, // TraditionalChinese
- 0, // Japanese
- 0, // Korean
- 0, // Vietnamese
- 0, // Symbol
- 0, // Ogham
- 0, // Runic
- "nko " // N'Ko
-};
-enum { OpenTypeCount = sizeof(openType) / sizeof(const char *) };
-
-
-static void loadFontConfig()
-{
- Q_ASSERT_X(X11, "QFontDatabase",
- "A QApplication object needs to be constructed before FontConfig is used.");
- if (!X11->has_fontconfig)
- return;
-
- Q_ASSERT_X(int(QUnicodeTables::ScriptCount) == SpecialLanguageCount,
- "QFontDatabase", "New scripts have been added.");
- Q_ASSERT_X(int(QUnicodeTables::ScriptCount) == SpecialCharCount,
- "QFontDatabase", "New scripts have been added.");
- Q_ASSERT_X(int(QFontDatabase::WritingSystemsCount) == LanguageCount,
- "QFontDatabase", "New writing systems have been added.");
- Q_ASSERT_X(int(QFontDatabase::WritingSystemsCount) == SampleCharCount,
- "QFontDatabase", "New writing systems have been added.");
- Q_ASSERT_X(int(QFontDatabase::WritingSystemsCount) == OpenTypeCount,
- "QFontDatabase", "New writing systems have been added.");
-
- QFontDatabasePrivate *db = privateDb();
- FcFontSet *fonts;
-
- FcPattern *pattern = FcPatternCreate();
- FcDefaultSubstitute(pattern);
- FcChar8 *lang = 0;
- if (FcPatternGetString(pattern, FC_LANG, 0, &lang) == FcResultMatch)
- db->systemLang = QString::fromUtf8((const char *) lang);
- FcPatternDestroy(pattern);
-
- QString familyName;
- FcChar8 *value = 0;
- int weight_value;
- int slant_value;
- int spacing_value;
- FcChar8 *file_value;
- int index_value;
- FcChar8 *foundry_value;
- FcBool scalable;
-
- {
- FcObjectSet *os = FcObjectSetCreate();
- FcPattern *pattern = FcPatternCreate();
- const char *properties [] = {
- FC_FAMILY, FC_WEIGHT, FC_SLANT,
- FC_SPACING, FC_FILE, FC_INDEX,
- FC_LANG, FC_CHARSET, FC_FOUNDRY, FC_SCALABLE, FC_PIXEL_SIZE, FC_WEIGHT,
- FC_WIDTH,
-#if FC_VERSION >= 20297
- FC_CAPABILITY,
-#endif
- (const char *)0
- };
- const char **p = properties;
- while (*p) {
- FcObjectSetAdd(os, *p);
- ++p;
- }
- fonts = FcFontList(0, pattern, os);
- FcObjectSetDestroy(os);
- FcPatternDestroy(pattern);
- }
-
- for (int i = 0; i < fonts->nfont; i++) {
- if (FcPatternGetString(fonts->fonts[i], FC_FAMILY, 0, &value) != FcResultMatch)
- continue;
- // capitalize(value);
- familyName = QString::fromUtf8((const char *)value);
- slant_value = FC_SLANT_ROMAN;
- weight_value = FC_WEIGHT_MEDIUM;
- spacing_value = FC_PROPORTIONAL;
- file_value = 0;
- index_value = 0;
- scalable = FcTrue;
-
- if (FcPatternGetInteger (fonts->fonts[i], FC_SLANT, 0, &slant_value) != FcResultMatch)
- slant_value = FC_SLANT_ROMAN;
- if (FcPatternGetInteger (fonts->fonts[i], FC_WEIGHT, 0, &weight_value) != FcResultMatch)
- weight_value = FC_WEIGHT_MEDIUM;
- if (FcPatternGetInteger (fonts->fonts[i], FC_SPACING, 0, &spacing_value) != FcResultMatch)
- spacing_value = FC_PROPORTIONAL;
- if (FcPatternGetString (fonts->fonts[i], FC_FILE, 0, &file_value) != FcResultMatch)
- file_value = 0;
- if (FcPatternGetInteger (fonts->fonts[i], FC_INDEX, 0, &index_value) != FcResultMatch)
- index_value = 0;
- if (FcPatternGetBool(fonts->fonts[i], FC_SCALABLE, 0, &scalable) != FcResultMatch)
- scalable = FcTrue;
- if (FcPatternGetString(fonts->fonts[i], FC_FOUNDRY, 0, &foundry_value) != FcResultMatch)
- foundry_value = 0;
- QtFontFamily *family = db->family(familyName, true);
-
- FcLangSet *langset = 0;
- FcResult res = FcPatternGetLangSet(fonts->fonts[i], FC_LANG, 0, &langset);
- if (res == FcResultMatch) {
- for (int i = 1; i < LanguageCount; ++i) {
- const FcChar8 *lang = (const FcChar8*) languageForWritingSystem[i];
- if (!lang) {
- family->writingSystems[i] |= QtFontFamily::UnsupportedFT;
- } else {
- FcLangResult langRes = FcLangSetHasLang(langset, lang);
- if (langRes != FcLangDifferentLang)
- family->writingSystems[i] = QtFontFamily::Supported;
- else
- family->writingSystems[i] |= QtFontFamily::UnsupportedFT;
- }
- }
- family->writingSystems[QFontDatabase::Other] = QtFontFamily::UnsupportedFT;
- family->ftWritingSystemCheck = true;
- } else {
- // we set Other to supported for symbol fonts. It makes no
- // sense to merge these with other ones, as they are
- // special in a way.
- for (int i = 1; i < LanguageCount; ++i)
- family->writingSystems[i] |= QtFontFamily::UnsupportedFT;
- family->writingSystems[QFontDatabase::Other] = QtFontFamily::Supported;
- }
-
- FcCharSet *cs = 0;
- res = FcPatternGetCharSet(fonts->fonts[i], FC_CHARSET, 0, &cs);
- if (res == FcResultMatch) {
- // some languages are not supported by FontConfig, we rather check the
- // charset to detect these
- for (int i = 1; i < SampleCharCount; ++i) {
- if (!sampleCharForWritingSystem[i])
- continue;
- if (FcCharSetHasChar(cs, sampleCharForWritingSystem[i]))
- family->writingSystems[i] = QtFontFamily::Supported;
- }
- }
-
-#if FC_VERSION >= 20297
- for (int j = 1; j < LanguageCount; ++j) {
- if (family->writingSystems[j] == QtFontFamily::Supported && requiresOpenType(j) && openType[j]) {
- FcChar8 *cap;
- res = FcPatternGetString (fonts->fonts[i], FC_CAPABILITY, 0, &cap);
- if (res != FcResultMatch || !strstr((const char *)cap, openType[j]))
- family->writingSystems[j] = QtFontFamily::UnsupportedFT;
- }
- }
-#endif
-
- QByteArray file((const char *)file_value);
- family->fontFilename = file;
- family->fontFileIndex = index_value;
-
- QtFontStyle::Key styleKey;
- styleKey.style = (slant_value == FC_SLANT_ITALIC)
- ? QFont::StyleItalic
- : ((slant_value == FC_SLANT_OBLIQUE)
- ? QFont::StyleOblique
- : QFont::StyleNormal);
- styleKey.weight = getFCWeight(weight_value);
- if (!scalable) {
- int width = 100;
- FcPatternGetInteger (fonts->fonts[i], FC_WIDTH, 0, &width);
- styleKey.stretch = width;
- }
-
- QtFontFoundry *foundry
- = family->foundry(foundry_value ? QString::fromUtf8((const char *)foundry_value) : QString(), true);
- QtFontStyle *style = foundry->style(styleKey, true);
-
- if (spacing_value < FC_MONO)
- family->fixedPitch = false;
-
- QtFontSize *size;
- if (scalable) {
- style->smoothScalable = true;
- size = style->pixelSize(SMOOTH_SCALABLE, true);
- } else {
- double pixel_size = 0;
- FcPatternGetDouble (fonts->fonts[i], FC_PIXEL_SIZE, 0, &pixel_size);
- size = style->pixelSize((int)pixel_size, true);
- }
- QtFontEncoding *enc = size->encodingID(-1, 0, 0, 0, 0, true);
- enc->pitch = (spacing_value >= FC_CHARCELL ? 'c' :
- (spacing_value >= FC_MONO ? 'm' : 'p'));
- }
-
- FcFontSetDestroy (fonts);
-
- struct FcDefaultFont {
- const char *qtname;
- const char *rawname;
- bool fixed;
- };
- const FcDefaultFont defaults[] = {
- { "Serif", "serif", false },
- { "Sans Serif", "sans-serif", false },
- { "Monospace", "monospace", true },
- { 0, 0, false }
- };
- const FcDefaultFont *f = defaults;
- while (f->qtname) {
- QtFontFamily *family = db->family(QLatin1String(f->qtname), true);
- family->fixedPitch = f->fixed;
- family->synthetic = true;
- QtFontFoundry *foundry = family->foundry(QString(), true);
-
- // aliases only make sense for 'common', not for any of the specials
- for (int i = 1; i < LanguageCount; ++i) {
- if (requiresOpenType(i))
- family->writingSystems[i] = QtFontFamily::UnsupportedFT;
- else
- family->writingSystems[i] = QtFontFamily::Supported;
- }
- family->writingSystems[QFontDatabase::Other] = QtFontFamily::UnsupportedFT;
-
- QtFontStyle::Key styleKey;
- for (int i = 0; i < 4; ++i) {
- styleKey.style = (i%2) ? QFont::StyleNormal : QFont::StyleItalic;
- styleKey.weight = (i > 1) ? QFont::Bold : QFont::Normal;
- QtFontStyle *style = foundry->style(styleKey, true);
- style->smoothScalable = true;
- QtFontSize *size = style->pixelSize(SMOOTH_SCALABLE, true);
- QtFontEncoding *enc = size->encodingID(-1, 0, 0, 0, 0, true);
- enc->pitch = (f->fixed ? 'm' : 'p');
- }
- ++f;
- }
-}
-#endif // QT_NO_FONTCONFIG
-
-static void initializeDb();
-
-static void load(const QString &family = QString(), int script = -1, bool forceXLFD = false)
-{
- if (X11->has_fontconfig && !forceXLFD) {
- initializeDb();
- return;
- }
-
-#ifdef QFONTDATABASE_DEBUG
- QElapsedTimer t;
- t.start();
-#endif
-
- if (family.isNull() && script == -1) {
- loadXlfds(0, -1);
- } else {
- if (family.isNull()) {
- // load all families in all writing systems that match \a script
- for (int ws = 1; ws < QFontDatabase::WritingSystemsCount; ++ws) {
- if (scriptForWritingSystem[ws] != script)
- continue;
- for (int i = 0; i < numEncodings; ++i) {
- if (writingSystems_for_xlfd_encoding[i][ws])
- loadXlfds(0, i);
- }
- }
- } else {
- QtFontFamily *f = privateDb()->family(family);
- // could reduce this further with some more magic:
- // would need to remember the encodings loaded for the family.
- if (!f || !f->xlfdLoaded)
- loadXlfds(family.toLatin1(), -1);
- }
- }
-
-#ifdef QFONTDATABASE_DEBUG
- FD_DEBUG("QFontDatabase: load(%s, %d) took %d ms",
- family.toLatin1().constData(), script, t.elapsed());
-#endif
-}
-
-static void checkSymbolFont(QtFontFamily *family)
-{
- if (!family || family->symbol_checked || family->fontFilename.isEmpty())
- return;
-// qDebug() << "checking " << family->rawName;
- family->symbol_checked = true;
-
- QFontEngine::FaceId id;
- id.filename = family->fontFilename;
- id.index = family->fontFileIndex;
- QFreetypeFace *f = QFreetypeFace::getFace(id);
- if (!f) {
- qWarning("checkSymbolFonts: Couldn't open face %s (%s/%d)",
- qPrintable(family->name), family->fontFilename.data(), family->fontFileIndex);
- return;
- }
- for (int i = 0; i < f->face->num_charmaps; ++i) {
- FT_CharMap cm = f->face->charmaps[i];
- if (cm->encoding == FT_ENCODING_ADOBE_CUSTOM
- || cm->encoding == FT_ENCODING_MS_SYMBOL) {
- for (int x = QFontDatabase::Latin; x < QFontDatabase::Other; ++x)
- family->writingSystems[x] = QtFontFamily::Unsupported;
- family->writingSystems[QFontDatabase::Other] = QtFontFamily::Supported;
- break;
- }
- }
- f->release(id);
-}
-
-static void checkSymbolFonts(const QString &family = QString())
-{
-#ifndef QT_NO_FONTCONFIG
- QFontDatabasePrivate *d = privateDb();
-
- if (family.isEmpty()) {
- for (int i = 0; i < d->count; ++i)
- checkSymbolFont(d->families[i]);
- } else {
- checkSymbolFont(d->family(family));
- }
-#endif
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt);
-
-static void initializeDb()
-{
- QFontDatabasePrivate *db = privateDb();
- if (!db || db->count)
- return;
-
- QElapsedTimer t;
- t.start();
-
-#ifndef QT_NO_FONTCONFIG
- if (db->reregisterAppFonts) {
- db->reregisterAppFonts = false;
- for (int i = 0; i < db->applicationFonts.count(); ++i)
- if (!db->applicationFonts.at(i).families.isEmpty()) {
- registerFont(&db->applicationFonts[i]);
- }
- }
-
- loadFontConfig();
- FD_DEBUG("QFontDatabase: loaded FontConfig: %d ms", int(t.elapsed()));
-#endif
-
- t.start();
-
-#ifndef QT_NO_FONTCONFIG
- for (int i = 0; i < db->count; i++) {
- for (int j = 0; j < db->families[i]->count; ++j) { // each foundry
- QtFontFoundry *foundry = db->families[i]->foundries[j];
- for (int k = 0; k < foundry->count; ++k) {
- QtFontStyle *style = foundry->styles[k];
- if (style->key.style != QFont::StyleNormal) continue;
-
- QtFontSize *size = style->pixelSize(SMOOTH_SCALABLE);
- if (! size) continue; // should not happen
- QtFontEncoding *enc = size->encodingID(-1, 0, 0, 0, 0, true);
- if (! enc) continue; // should not happen either
-
- QtFontStyle::Key key = style->key;
-
- // does this style have an italic equivalent?
- key.style = QFont::StyleItalic;
- QtFontStyle *equiv = foundry->style(key);
- if (equiv) continue;
-
- // does this style have an oblique equivalent?
- key.style = QFont::StyleOblique;
- equiv = foundry->style(key);
- if (equiv) continue;
-
- // let's fake one...
- equiv = foundry->style(key, true);
- equiv->smoothScalable = true;
-
- QtFontSize *equiv_size = equiv->pixelSize(SMOOTH_SCALABLE, true);
- QtFontEncoding *equiv_enc = equiv_size->encodingID(-1, 0, 0, 0, 0, true);
-
- // keep the same pitch
- equiv_enc->pitch = enc->pitch;
- }
- }
- }
-#endif
-
-
-#ifdef QFONTDATABASE_DEBUG
-#ifndef QT_NO_FONTCONFIG
- if (!X11->has_fontconfig)
-#endif
- // load everything at startup in debug mode.
- loadXlfds(0, -1);
-
- // print the database
- for (int f = 0; f < db->count; f++) {
- QtFontFamily *family = db->families[f];
- FD_DEBUG("'%s' %s fixed=%s", family->name.latin1(), (family->fixedPitch ? "fixed" : ""),
- (family->fixedPitch ? "yes" : "no"));
- for (int i = 0; i < QFontDatabase::WritingSystemsCount; ++i) {
- QFontDatabase::WritingSystem ws = QFontDatabase::WritingSystem(i);
- FD_DEBUG("\t%s: %s", QFontDatabase::writingSystemName(ws).toLatin1().constData(),
- ((family->writingSystems[i] & QtFontFamily::Supported) ? "Supported" :
- (family->writingSystems[i] & QtFontFamily::Unsupported) == QtFontFamily::Unsupported ?
- "Unsupported" : "Unknown"));
- }
-
- for (int fd = 0; fd < family->count; fd++) {
- QtFontFoundry *foundry = family->foundries[fd];
- FD_DEBUG("\t\t'%s'", foundry->name.latin1());
- for (int s = 0; s < foundry->count; s++) {
- QtFontStyle *style = foundry->styles[s];
- FD_DEBUG("\t\t\tstyle: style=%d weight=%d (%s)\n"
- "\t\t\tstretch=%d (%s)",
- style->key.style, style->key.weight,
- style->weightName, style->key.stretch,
- style->setwidthName ? style->setwidthName : "nil");
- if (style->smoothScalable)
- FD_DEBUG("\t\t\t\tsmooth scalable");
- else if (style->bitmapScalable)
- FD_DEBUG("\t\t\t\tbitmap scalable");
- if (style->pixelSizes) {
- qDebug("\t\t\t\t%d pixel sizes", style->count);
- for (int z = 0; z < style->count; ++z) {
- QtFontSize *size = style->pixelSizes + z;
- for (int e = 0; e < size->count; ++e) {
- FD_DEBUG("\t\t\t\t size %5d pitch %c encoding %s",
- size->pixelSize,
- size->encodings[e].pitch,
- xlfd_for_id(size->encodings[e].encoding));
- }
- }
- }
- }
- }
- }
-#endif // QFONTDATABASE_DEBUG
-}
-
-
-// --------------------------------------------------------------------------------------
-// font loader
-// --------------------------------------------------------------------------------------
-
-static const char *styleHint(const QFontDef &request)
-{
- const char *stylehint = 0;
- switch (request.styleHint) {
- case QFont::SansSerif:
- stylehint = "sans-serif";
- break;
- case QFont::Serif:
- stylehint = "serif";
- break;
- case QFont::TypeWriter:
- stylehint = "monospace";
- break;
- default:
- if (request.fixedPitch)
- stylehint = "monospace";
- break;
- }
- return stylehint;
-}
-
-#ifndef QT_NO_FONTCONFIG
-
-void qt_addPatternProps(FcPattern *pattern, int screen, int script, const QFontDef &request)
-{
- int weight_value = FC_WEIGHT_BLACK;
- if (request.weight == 0)
- weight_value = FC_WEIGHT_MEDIUM;
- else if (request.weight < (QFont::Light + QFont::Normal) / 2)
- weight_value = FC_WEIGHT_LIGHT;
- else if (request.weight < (QFont::Normal + QFont::DemiBold) / 2)
- weight_value = FC_WEIGHT_MEDIUM;
- else if (request.weight < (QFont::DemiBold + QFont::Bold) / 2)
- weight_value = FC_WEIGHT_DEMIBOLD;
- else if (request.weight < (QFont::Bold + QFont::Black) / 2)
- weight_value = FC_WEIGHT_BOLD;
- FcPatternDel(pattern, FC_WEIGHT);
- FcPatternAddInteger(pattern, FC_WEIGHT, weight_value);
-
- int slant_value = FC_SLANT_ROMAN;
- if (request.style == QFont::StyleItalic)
- slant_value = FC_SLANT_ITALIC;
- else if (request.style == QFont::StyleOblique)
- slant_value = FC_SLANT_OBLIQUE;
- FcPatternDel(pattern, FC_SLANT);
- FcPatternAddInteger(pattern, FC_SLANT, slant_value);
-
- double size_value = qMax(qreal(1.), request.pixelSize);
- FcPatternDel(pattern, FC_PIXEL_SIZE);
- FcPatternAddDouble(pattern, FC_PIXEL_SIZE, size_value);
-
- int stretch = request.stretch;
- if (!stretch)
- stretch = 100;
- FcPatternDel(pattern, FC_WIDTH);
- FcPatternAddInteger(pattern, FC_WIDTH, stretch);
-
- if (X11->display && QX11Info::appDepth(screen) <= 8) {
- FcPatternDel(pattern, FC_ANTIALIAS);
- // can't do antialiasing on 8bpp
- FcPatternAddBool(pattern, FC_ANTIALIAS, false);
- } else if (request.styleStrategy & (QFont::PreferAntialias|QFont::NoAntialias)) {
- FcPatternDel(pattern, FC_ANTIALIAS);
- FcPatternAddBool(pattern, FC_ANTIALIAS,
- !(request.styleStrategy & QFont::NoAntialias));
- }
-
- if (script != QUnicodeTables::Common && *specialLanguages[script] != '\0') {
- Q_ASSERT(script < QUnicodeTables::ScriptCount);
- FcLangSet *ls = FcLangSetCreate();
- FcLangSetAdd(ls, (const FcChar8*)specialLanguages[script]);
- FcPatternDel(pattern, FC_LANG);
- FcPatternAddLangSet(pattern, FC_LANG, ls);
- FcLangSetDestroy(ls);
- }
-}
-
-static bool preferScalable(const QFontDef &request)
-{
- return request.styleStrategy & (QFont::PreferOutline|QFont::ForceOutline|QFont::PreferQuality|QFont::PreferAntialias);
-}
-
-
-static FcPattern *getFcPattern(const QFontPrivate *fp, int script, const QFontDef &request)
-{
- if (!X11->has_fontconfig)
- return 0;
-
- FcPattern *pattern = FcPatternCreate();
- if (!pattern)
- return 0;
-
- FcValue value;
- value.type = FcTypeString;
-
- QtFontDesc desc;
- QStringList families_and_foundries = familyList(request);
- for (int i = 0; i < families_and_foundries.size(); ++i) {
- QString family, foundry;
- parseFontName(families_and_foundries.at(i), foundry, family);
- if (!family.isEmpty()) {
- QByteArray cs = family.toUtf8();
- value.u.s = (const FcChar8 *)cs.data();
- FcPatternAdd(pattern, FC_FAMILY, value, FcTrue);
- }
- if (i == 0) {
- QT_PREPEND_NAMESPACE(match)(script, request, family, foundry, -1, &desc);
- if (!foundry.isEmpty()) {
- QByteArray cs = foundry.toUtf8();
- value.u.s = (const FcChar8 *)cs.data();
- FcPatternAddWeak(pattern, FC_FOUNDRY, value, FcTrue);
- }
- }
- }
-
- const char *stylehint = styleHint(request);
- if (stylehint) {
- value.u.s = (const FcChar8 *)stylehint;
- FcPatternAddWeak(pattern, FC_FAMILY, value, FcTrue);
- }
-
- if (!request.ignorePitch) {
- char pitch_value = FC_PROPORTIONAL;
- if (request.fixedPitch || (desc.family && desc.family->fixedPitch))
- pitch_value = FC_MONO;
- FcPatternAddInteger(pattern, FC_SPACING, pitch_value);
- }
- FcPatternAddBool(pattern, FC_OUTLINE, !(request.styleStrategy & QFont::PreferBitmap));
- if (preferScalable(request) || (desc.style && desc.style->smoothScalable))
- FcPatternAddBool(pattern, FC_SCALABLE, true);
-
- qt_addPatternProps(pattern, fp->screen, script, request);
-
- FcDefaultSubstitute(pattern);
- FcConfigSubstitute(0, pattern, FcMatchPattern);
- FcConfigSubstitute(0, pattern, FcMatchFont);
-
- // these should only get added to the pattern _after_ substitution
- // append the default fallback font for the specified script
- extern QString qt_fallback_font_family(int);
- QString fallback = qt_fallback_font_family(script);
- if (!fallback.isEmpty()) {
- QByteArray cs = fallback.toUtf8();
- value.u.s = (const FcChar8 *)cs.data();
- FcPatternAddWeak(pattern, FC_FAMILY, value, FcTrue);
- }
-
- // add the default family
- QString defaultFamily = QApplication::font().family();
- QByteArray cs = defaultFamily.toUtf8();
- value.u.s = (const FcChar8 *)cs.data();
- FcPatternAddWeak(pattern, FC_FAMILY, value, FcTrue);
-
- // add QFont::defaultFamily() to the list, for compatibility with
- // previous versions
- defaultFamily = QApplication::font().defaultFamily();
- cs = defaultFamily.toUtf8();
- value.u.s = (const FcChar8 *)cs.data();
- FcPatternAddWeak(pattern, FC_FAMILY, value, FcTrue);
-
- return pattern;
-}
-
-
-static void FcFontSetRemove(FcFontSet *fs, int at)
-{
- Q_ASSERT(at < fs->nfont);
- FcPatternDestroy(fs->fonts[at]);
- int len = (--fs->nfont - at) * sizeof(FcPattern *);;
- if (len > 0)
- memmove(fs->fonts + at, fs->fonts + at + 1, len);
-}
-
-static QFontEngine *tryPatternLoad(FcPattern *p, int screen,
- const QFontDef &request, int script, FcPattern **matchedPattern = 0)
-{
-#ifdef FONT_MATCH_DEBUG
- FcChar8 *fam;
- FcPatternGetString(p, FC_FAMILY, 0, &fam);
- FM_DEBUG("==== trying %s\n", fam);
-#endif
- FM_DEBUG("passes charset test\n");
- FcPattern *pattern = FcPatternDuplicate(p);
- // add properties back in as the font selected from the
- // list doesn't contain them.
- qt_addPatternProps(pattern, screen, script, request);
-
- FcConfigSubstitute(0, pattern, FcMatchPattern);
- FcDefaultSubstitute(pattern);
- FcResult res;
- FcPattern *match = FcFontMatch(0, pattern, &res);
-
- if (matchedPattern)
- *matchedPattern = 0;
-
- QFontEngineX11FT *engine = 0;
- if (!match) // probably no fonts available.
- goto done;
-
- if (matchedPattern)
- *matchedPattern = FcPatternDuplicate(match);
-
- if (script != QUnicodeTables::Common) {
- // skip font if it doesn't support the language we want
- if (specialChars[script]) {
- // need to check the charset, as the langset doesn't work for these scripts
- FcCharSet *cs;
- if (FcPatternGetCharSet(match, FC_CHARSET, 0, &cs) != FcResultMatch)
- goto done;
- if (!FcCharSetHasChar(cs, specialChars[script]))
- goto done;
- } else if (*specialLanguages[script] != '\0'){
- FcLangSet *langSet = 0;
- if (FcPatternGetLangSet(match, FC_LANG, 0, &langSet) != FcResultMatch)
- goto done;
- if (FcLangSetHasLang(langSet, (const FcChar8*)specialLanguages[script]) != FcLangEqual)
- goto done;
- }
- }
-
- // enforce non-antialiasing if requested. the ft font engine looks at this property.
- if (request.styleStrategy & QFont::NoAntialias) {
- FcPatternDel(match, FC_ANTIALIAS);
- FcPatternAddBool(match, FC_ANTIALIAS, false);
- }
-
- engine = new QFontEngineX11FT(match, qt_FcPatternToQFontDef(match, request), screen);
- if (engine->invalid()) {
- FM_DEBUG(" --> invalid!\n");
- delete engine;
- engine = 0;
- } else if (scriptRequiresOpenType(script)) {
- HB_Face hbFace = engine->harfbuzzFace();
- if (!hbFace || !hbFace->supported_scripts[script]) {
- FM_DEBUG(" OpenType support missing for script\n");
- delete engine;
- engine = 0;
- }
- }
-done:
- FcPatternDestroy(pattern);
- if (!engine && matchedPattern && *matchedPattern) {
- FcPatternDestroy(*matchedPattern);
- *matchedPattern = 0;
- }
- return engine;
-}
-
-FcFontSet *qt_fontSetForPattern(FcPattern *pattern, const QFontDef &request)
-{
- FcResult result;
- FcFontSet *fs = FcFontSort(0, pattern, FcTrue, 0, &result);
-#ifdef FONT_MATCH_DEBUG
- FM_DEBUG("first font in fontset:\n");
- FcPatternPrint(fs->fonts[0]);
-#endif
-
- FcBool forceScalable = request.styleStrategy & QFont::ForceOutline;
-
- // remove fonts if they are not scalable (and should be)
- if (forceScalable && fs) {
- for (int i = 0; i < fs->nfont; ++i) {
- FcPattern *font = fs->fonts[i];
- FcResult res;
- FcBool scalable;
- res = FcPatternGetBool(font, FC_SCALABLE, 0, &scalable);
- if (res != FcResultMatch || !scalable) {
- FcFontSetRemove(fs, i);
-#ifdef FONT_MATCH_DEBUG
- FM_DEBUG("removing pattern:");
- FcPatternPrint(font);
-#endif
- --i; // go back one
- }
- }
- }
-
- FM_DEBUG("final pattern contains %d fonts\n", fs->nfont);
-
- return fs;
-}
-
-static QFontEngine *loadFc(const QFontPrivate *fp, int script, const QFontDef &request)
-{
- FM_DEBUG("===================== loadFc: script=%d family='%s'\n", script, request.family.toLatin1().data());
- FcPattern *pattern = getFcPattern(fp, script, request);
-
-#ifdef FONT_MATCH_DEBUG
- FM_DEBUG("\n\nfinal FcPattern contains:\n");
- FcPatternPrint(pattern);
-#endif
-
- QFontEngine *fe = 0;
- FcPattern *matchedPattern = 0;
- fe = tryPatternLoad(pattern, fp->screen, request, script, &matchedPattern);
- if (!fe) {
- FcFontSet *fs = qt_fontSetForPattern(pattern, request);
-
- if (fs) {
- for (int i = 0; !fe && i < fs->nfont; ++i)
- fe = tryPatternLoad(fs->fonts[i], fp->screen, request, script, &matchedPattern);
- FcFontSetDestroy(fs);
- }
- FM_DEBUG("engine for script %d is %s\n", script, fe ? fe->fontDef.family.toLatin1().data(): "(null)");
- }
- if (fe
- && script == QUnicodeTables::Common
- && !(request.styleStrategy & QFont::NoFontMerging) && !fe->symbol) {
- fe = new QFontEngineMultiFT(fe, matchedPattern, pattern, fp->screen, request);
- } else {
- FcPatternDestroy(pattern);
- if (matchedPattern)
- FcPatternDestroy(matchedPattern);
- }
- return fe;
-}
-
-static FcPattern *queryFont(const FcChar8 *file, const QByteArray &data, int id, FcBlanks *blanks, int *count)
-{
-#if FC_VERSION < 20402
- Q_UNUSED(data)
- return FcFreeTypeQuery(file, id, blanks, count);
-#else
- if (data.isEmpty())
- return FcFreeTypeQuery(file, id, blanks, count);
-
- extern FT_Library qt_getFreetype();
- FT_Library lib = qt_getFreetype();
-
- FcPattern *pattern = 0;
-
- FT_Face face;
- if (!FT_New_Memory_Face(lib, (const FT_Byte *)data.constData(), data.size(), id, &face)) {
- *count = face->num_faces;
-
- pattern = FcFreeTypeQueryFace(face, file, id, blanks);
-
- FT_Done_Face(face);
- }
-
- return pattern;
-#endif
-}
-#endif // QT_NO_FONTCONFIG
-
-static QFontEngine *loadRaw(const QFontPrivate *fp, const QFontDef &request)
-{
- Q_ASSERT(fp && fp->rawMode);
-
- QByteArray xlfd = request.family.toLatin1();
- FM_DEBUG("Loading XLFD (rawmode) '%s'", xlfd.data());
-
- QFontEngine *fe;
- XFontStruct *xfs;
- if (!(xfs = XLoadQueryFont(QX11Info::display(), xlfd.data())))
- if (!(xfs = XLoadQueryFont(QX11Info::display(), "fixed")))
- return 0;
-
- fe = new QFontEngineXLFD(xfs, xlfd, 0);
- if (! qt_fillFontDef(xfs, &fe->fontDef, fp->dpi, 0) &&
- ! qt_fillFontDef(xlfd, &fe->fontDef, fp->dpi, 0))
- fe->fontDef = QFontDef();
- return fe;
-}
-
-QFontEngine *QFontDatabase::loadXlfd(int screen, int script, const QFontDef &request, int force_encoding_id)
-{
- QMutexLocker locker(fontDatabaseMutex());
-
- QtFontDesc desc;
- FM_DEBUG() << "---> loadXlfd: request is" << request.family;
- QStringList families_and_foundries = familyList(request);
- const char *stylehint = styleHint(request);
- if (stylehint)
- families_and_foundries << QString::fromLatin1(stylehint);
- families_and_foundries << QString();
- FM_DEBUG() << "loadXlfd: list is" << families_and_foundries;
- for (int i = 0; i < families_and_foundries.size(); ++i) {
- QString family, foundry;
- QT_PREPEND_NAMESPACE(parseFontName)(families_and_foundries.at(i), foundry, family);
- FM_DEBUG("loadXlfd: >>>>>>>>>>>>>>trying to match '%s' encoding=%d", family.toLatin1().data(), force_encoding_id);
- QT_PREPEND_NAMESPACE(match)(script, request, family, foundry, force_encoding_id, &desc, QList<int>(), true);
- if (desc.family)
- break;
- }
-
- QFontEngine *fe = 0;
- if (force_encoding_id != -1
- || (request.styleStrategy & QFont::NoFontMerging)
- || (desc.family && desc.family->writingSystems[QFontDatabase::Symbol] & QtFontFamily::Supported)) {
- if (desc.family) {
- int px = desc.size->pixelSize;
- if (desc.style->smoothScalable && px == SMOOTH_SCALABLE)
- px = request.pixelSize;
- else if (desc.style->bitmapScalable && px == 0)
- px = request.pixelSize;
-
- QByteArray xlfd("-");
- xlfd += desc.foundry->name.isEmpty() ? QByteArray("*") : desc.foundry->name.toLatin1();
- xlfd += '-';
- xlfd += desc.family->name.isEmpty() ? QByteArray("*") : desc.family->name.toLatin1();
- xlfd += '-';
- xlfd += desc.style->weightName ? desc.style->weightName : "*";
- xlfd += '-';
- xlfd += (desc.style->key.style == QFont::StyleItalic
- ? 'i'
- : (desc.style->key.style == QFont::StyleOblique ? 'o' : 'r'));
- xlfd += '-';
- xlfd += desc.style->setwidthName ? desc.style->setwidthName : "*";
- // ### handle add-style
- xlfd += "-*-";
- xlfd += QByteArray::number(px);
- xlfd += '-';
- xlfd += QByteArray::number(desc.encoding->xpoint);
- xlfd += '-';
- xlfd += QByteArray::number(desc.encoding->xres);
- xlfd += '-';
- xlfd += QByteArray::number(desc.encoding->yres);
- xlfd += '-';
- xlfd += desc.encoding->pitch;
- xlfd += '-';
- xlfd += QByteArray::number(desc.encoding->avgwidth);
- xlfd += '-';
- xlfd += xlfd_for_id(desc.encoding->encoding);
-
- FM_DEBUG(" using XLFD: %s\n", xlfd.data());
-
- const int mib = xlfd_encoding[desc.encoding->encoding].mib;
- XFontStruct *xfs;
- if ((xfs = XLoadQueryFont(QX11Info::display(), xlfd))) {
- fe = new QFontEngineXLFD(xfs, xlfd, mib);
- const int dpi = QX11Info::appDpiY();
- if (!qt_fillFontDef(xfs, &fe->fontDef, dpi, &desc)
- && !qt_fillFontDef(xlfd, &fe->fontDef, dpi, &desc)) {
- initFontDef(desc, request, &fe->fontDef);
- }
- }
- }
- if (!fe) {
- fe = new QFontEngineBox(request.pixelSize);
- fe->fontDef = QFontDef();
- }
- } else {
- QList<int> encodings;
- if (desc.encoding) {
- if (desc.encoding->encoding >= 0)
- encodings.append(int(desc.encoding->encoding));
- }
-
- if (desc.size) {
- // append all other encodings for the matched font
- for (int i = 0; i < desc.size->count; ++i) {
- QtFontEncoding *e = desc.size->encodings + i;
- if (e == desc.encoding || e->encoding < 0)
- continue;
- encodings.append(int(e->encoding));
- }
- }
- // fill in the missing encodings
- const XlfdEncoding *enc = xlfd_encoding;
- for (; enc->name; ++enc) {
- if (!encodings.contains(enc->id) && enc->id >= 0) {
- encodings.append(enc->id);
- }
- }
-
-#if defined(FONT_MATCH_DEBUG)
- FM_DEBUG(" using MultiXLFD, encodings:");
- for (int i = 0; i < encodings.size(); ++i) {
- const int id = encodings.at(i);
- FM_DEBUG(" %2d: %s", xlfd_encoding[id].id, xlfd_encoding[id].name);
- }
-#endif
-
- fe = new QFontEngineMultiXLFD(request, encodings, screen);
- }
- return fe;
-}
-
-#if (defined(QT_ARCH_ARM) || defined(QT_ARCH_ARMV6)) && defined(Q_CC_GNU) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3)
-#define NEEDS_GCC_BUG_WORKAROUND
-#endif
-
-#ifdef NEEDS_GCC_BUG_WORKAROUND
-static inline void gccBugWorkaround(const QFontDef &req)
-{
- char buffer[8];
- snprintf(buffer, 8, "%f", req.pixelSize);
-}
-#endif
-
-/*! \internal
- Loads a QFontEngine for the specified \a script that matches the
- QFontDef \e request member variable.
-*/
-void QFontDatabase::load(const QFontPrivate *d, int script)
-{
- Q_ASSERT(script >= 0 && script < QUnicodeTables::ScriptCount);
-
- // normalize the request to get better caching
- QFontDef req = d->request;
- if (req.pixelSize <= 0)
- req.pixelSize = qFloor(qt_pixelSize(req.pointSize, d->dpi) * 100.0 + 0.5) * 0.01;
- if (req.pixelSize < 1)
- req.pixelSize = 1;
-
-#ifdef NEEDS_GCC_BUG_WORKAROUND
- // req.pixelSize ends up with a bogus value unless this workaround is called
- gccBugWorkaround(req);
-#endif
-
- if (req.weight == 0)
- req.weight = QFont::Normal;
- if (req.stretch == 0)
- req.stretch = 100;
-
- QFontCache::Key key(req, d->rawMode ? QUnicodeTables::Common : script, d->screen);
- if (!d->engineData)
- getEngineData(d, key);
-
- // the cached engineData could have already loaded the engine we want
- if (d->engineData->engines[script])
- return;
-
- // set it to the actual pointsize, so QFontInfo will do the right thing
- if (req.pointSize < 0)
- req.pointSize = qt_pointSize(req.pixelSize, d->dpi);
-
-
- QFontEngine *fe = QFontCache::instance()->findEngine(key);
-
- if (!fe) {
- QMutexLocker locker(fontDatabaseMutex());
- if (!privateDb()->count)
- initializeDb();
-
- const bool mainThread = (qApp->thread() == QThread::currentThread());
- if (qt_enable_test_font && req.family == QLatin1String("__Qt__Box__Engine__")) {
- fe = new QTestFontEngine(req.pixelSize);
- fe->fontDef = req;
- } else if (d->rawMode) {
- if (mainThread)
- fe = loadRaw(d, req);
-#ifndef QT_NO_FONTCONFIG
- } else if (X11->has_fontconfig) {
- fe = loadFc(d, script, req);
-#endif
- } else if (mainThread && qt_is_gui_used) {
- fe = loadXlfd(d->screen, script, req);
- }
- if (!fe) {
- fe = new QFontEngineBox(req.pixelSize);
- fe->fontDef = QFontDef();
- }
- }
- if (fe->symbol || (d->request.styleStrategy & QFont::NoFontMerging)) {
- for (int i = 0; i < QUnicodeTables::ScriptCount; ++i) {
- if (!d->engineData->engines[i]) {
- d->engineData->engines[i] = fe;
- fe->ref.ref();
- }
- }
- } else {
- d->engineData->engines[script] = fe;
- fe->ref.ref();
- }
- QFontCache::instance()->insertEngine(key, fe);
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
-{
-#if defined(QT_NO_FONTCONFIG)
- return;
-#else
- if (!X11->has_fontconfig)
- return;
-
- FcConfig *config = FcConfigGetCurrent();
- if (!config)
- return;
-
- FcFontSet *set = FcConfigGetFonts(config, FcSetApplication);
- if (!set) {
- FcConfigAppFontAddFile(config, (const FcChar8 *)":/non-existent");
- set = FcConfigGetFonts(config, FcSetApplication); // try again
- if (!set)
- return;
- }
-
- QString fileNameForQuery = fnt->fileName;
-#if FC_VERSION < 20402
- QTemporaryFile tmp;
-
- if (!fnt->data.isEmpty()) {
- if (!tmp.open())
- return;
- tmp.write(fnt->data);
- tmp.flush();
- fileNameForQuery = tmp.fileName();
- }
-#endif
-
- int id = 0;
- FcBlanks *blanks = FcConfigGetBlanks(0);
- int count = 0;
-
- QStringList families;
- QFontDatabasePrivate *db = privateDb();
-
- FcPattern *pattern = 0;
- do {
- pattern = queryFont((const FcChar8 *)QFile::encodeName(fileNameForQuery).constData(),
- fnt->data, id, blanks, &count);
- if (!pattern)
- return;
-
- FcPatternDel(pattern, FC_FILE);
- FcPatternAddString(pattern, FC_FILE, (const FcChar8 *)fnt->fileName.toUtf8().constData());
-
- FcChar8 *fam = 0, *familylang = 0;
- int i, n = 0;
- for (i = 0; ; i++) {
- if (FcPatternGetString(pattern, FC_FAMILYLANG, i, &familylang) != FcResultMatch)
- break;
- QString familyLang = QString::fromUtf8((const char *) familylang);
- if (familyLang.compare(db->systemLang, Qt::CaseInsensitive) == 0) {
- n = i;
- break;
- }
- }
-
- if (FcPatternGetString(pattern, FC_FAMILY, n, &fam) == FcResultMatch) {
- QString family = QString::fromUtf8(reinterpret_cast<const char *>(fam));
- families << family;
- }
-
- if (!FcFontSetAdd(set, pattern))
- return;
-
- ++id;
- } while (pattern && id < count);
-
- fnt->families = families;
-#endif
-}
-
-bool QFontDatabase::removeApplicationFont(int handle)
-{
-#if defined(QT_NO_FONTCONFIG)
- return false;
-#else
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- if (handle < 0 || handle >= db->applicationFonts.count())
- return false;
-
- FcConfigAppFontClear(0);
-
- db->applicationFonts[handle] = QFontDatabasePrivate::ApplicationFont();
-
- db->reregisterAppFonts = true;
- db->invalidate();
- return true;
-#endif
-}
-
-bool QFontDatabase::removeAllApplicationFonts()
-{
-#if defined(QT_NO_FONTCONFIG)
- return false;
-#else
- QMutexLocker locker(fontDatabaseMutex());
-
- QFontDatabasePrivate *db = privateDb();
- if (db->applicationFonts.isEmpty())
- return false;
-
- FcConfigAppFontClear(0);
- db->applicationFonts.clear();
- db->invalidate();
- return true;
-#endif
-}
-
-bool QFontDatabase::supportsThreadedFontRendering()
-{
-#if defined(QT_NO_FONTCONFIG)
- return false;
-#else
- return X11->has_fontconfig;
-#endif
-}
-
-QString QFontDatabase::resolveFontFamilyAlias(const QString &family)
-{
-#if defined(QT_NO_FONTCONFIG)
- return family;
-#else
- FcPattern *pattern = FcPatternCreate();
- if (!pattern)
- return family;
-
- FcPatternAddString(pattern, FC_FAMILY, (const FcChar8 *) family.toUtf8().data());
- FcConfigSubstitute(0, pattern, FcMatchPattern);
- FcDefaultSubstitute(pattern);
-
- FcChar8 *familyAfterSubstitution;
- FcPatternGetString(pattern, FC_FAMILY, 0, &familyAfterSubstitution);
- QString resolved = QString::fromUtf8((const char *) familyAfterSubstitution);
- FcPatternDestroy(pattern);
-
- return resolved;
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qfontengine_x11.cpp b/src/gui/platforms/x11/qfontengine_x11.cpp
deleted file mode 100644
index 4260b85b11..0000000000
--- a/src/gui/platforms/x11/qfontengine_x11.cpp
+++ /dev/null
@@ -1,1215 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbitmap.h"
-
-// #define FONTENGINE_DEBUG
-
-#include <qapplication.h>
-#include <qbytearray.h>
-#include <qdebug.h>
-#include <qtextcodec.h>
-#include <qthread.h>
-
-#include "qfontdatabase.h"
-#include "qpaintdevice.h"
-#include "qpainter.h"
-#include "qvarlengtharray.h"
-#include "qwidget.h"
-#include "qsettings.h"
-#include "qfile.h"
-
-#include <private/qpaintengine_x11_p.h>
-#include "qfont.h"
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include <qhash.h>
-
-#include <private/qpainter_p.h>
-#include <private/qunicodetables_p.h>
-
-#include <private/qt_x11_p.h>
-#include <private/qpixmap_x11_p.h>
-#include "qx11info_x11.h"
-#include "qfontengine_x11_p.h"
-
-#include <limits.h>
-
-#include <ft2build.h>
-#if defined(FT_LCD_FILTER_H)
-#include FT_LCD_FILTER_H
-#endif
-
-#if defined(FC_LCD_FILTER)
-
-#ifndef FC_LCD_FILTER_NONE
-#define FC_LCD_FILTER_NONE FC_LCD_NONE
-#endif
-
-#ifndef FC_LCD_FILTER_DEFAULT
-#define FC_LCD_FILTER_DEFAULT FC_LCD_DEFAULT
-#endif
-
-#ifndef FC_LCD_FILTER_LIGHT
-#define FC_LCD_FILTER_LIGHT FC_LCD_LIGHT
-#endif
-
-#ifndef FC_LCD_FILTER_LEGACY
-#define FC_LCD_FILTER_LEGACY FC_LCD_LEGACY
-#endif
-
-#endif
-
-QT_BEGIN_NAMESPACE
-
-
-// ------------------------------------------------------------------
-// Multi XLFD engine
-// ------------------------------------------------------------------
-
-QFontEngineMultiXLFD::QFontEngineMultiXLFD(const QFontDef &r, const QList<int> &l, int s)
- : QFontEngineMulti(l.size()), encodings(l), screen(s), request(r)
-{
- loadEngine(0);
- fontDef = engines[0]->fontDef;
-}
-
-QFontEngineMultiXLFD::~QFontEngineMultiXLFD()
-{ }
-
-void QFontEngineMultiXLFD::loadEngine(int at)
-{
- Q_ASSERT(at < engines.size());
- Q_ASSERT(engines.at(at) == 0);
- const int encoding = encodings.at(at);
- QFontEngine *fontEngine = QFontDatabase::loadXlfd(0, QUnicodeTables::Common, request, encoding);
- Q_ASSERT(fontEngine != 0);
- fontEngine->ref.ref();
- engines[at] = fontEngine;
-}
-
-// ------------------------------------------------------------------
-// Xlfd font engine
-// ------------------------------------------------------------------
-
-#ifndef QT_NO_FREETYPE
-
-static QStringList *qt_fontpath = 0;
-
-static QStringList fontPath()
-{
- if (qt_fontpath)
- return *qt_fontpath;
-
- // append qsettings fontpath
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- settings.beginGroup(QLatin1String("Qt"));
-
- QStringList fontpath;
-
- int npaths;
- char** font_path;
- font_path = XGetFontPath(X11->display, &npaths);
- bool xfsconfig_read = false;
- for (int i=0; i<npaths; i++) {
- // If we're using xfs, append font paths from /etc/X11/fs/config
- // can't hurt, and chances are we'll get all fonts that way.
- if (((font_path[i])[0] != '/') && !xfsconfig_read) {
- // We're using xfs -> read its config
- bool finished = false;
- QFile f(QLatin1String("/etc/X11/fs/config"));
- if (!f.exists())
- f.setFileName(QLatin1String("/usr/X11R6/lib/X11/fs/config"));
- if (!f.exists())
- f.setFileName(QLatin1String("/usr/X11/lib/X11/fs/config"));
- if (f.exists()) {
- f.open(QIODevice::ReadOnly);
- while (f.error()==QFile::NoError && !finished) {
- QString fs = QString::fromLocal8Bit(f.readLine(1024));
- fs=fs.trimmed();
- if (fs.left(9)==QLatin1String("catalogue") && fs.contains(QLatin1Char('='))) {
- fs = fs.mid(fs.indexOf(QLatin1Char('=')) + 1).trimmed();
- bool end = false;
- while (f.error()==QFile::NoError && !end) {
- if (fs[int(fs.length())-1] == QLatin1Char(','))
- fs = fs.left(fs.length()-1);
- else
- end = true;
-
- fs = fs.left(fs.indexOf(QLatin1String(":unscaled")));
- if (fs[0] != QLatin1Char('#'))
- fontpath += fs;
- fs = QLatin1String(f.readLine(1024));
- fs = fs.trimmed();
- if (fs.isEmpty())
- end = true;
- }
- finished = true;
- }
- }
- f.close();
- }
- xfsconfig_read = true;
- } else {
- QString fs = QString::fromLocal8Bit(font_path[i]);
- fontpath += fs.left(fs.indexOf(QLatin1String(":unscaled")));
- }
- }
- XFreeFontPath(font_path);
-
- // append qsettings fontpath
- QStringList fp = settings.value(QLatin1String("fontPath")).toStringList();
- if (!fp.isEmpty())
- fontpath += fp;
-
- qt_fontpath = new QStringList(fontpath);
- return fontpath;
-}
-
-static QFontEngine::FaceId fontFile(const QByteArray &_xname, QFreetypeFace **freetype, int *synth)
-{
- *freetype = 0;
- *synth = 0;
-
- QByteArray xname = _xname.toLower();
-
- int pos = 0;
- int minus = 0;
- while (minus < 5 && (pos = xname.indexOf('-', pos + 1)))
- ++minus;
- QByteArray searchname = xname.left(pos);
- while (minus < 12 && (pos = xname.indexOf('-', pos + 1)))
- ++minus;
- QByteArray encoding = xname.mid(pos + 1);
- //qDebug("xname='%s', searchname='%s', encoding='%s'", xname.data(), searchname.data(), encoding.data());
- QStringList fontpath = fontPath();
- QFontEngine::FaceId face_id;
- face_id.index = 0;
-
- QByteArray best_mapping;
-
- for (QStringList::ConstIterator it = fontpath.constBegin(); it != fontpath.constEnd(); ++it) {
- if (!(*it).startsWith(QLatin1Char('/')))
- continue; // not a path name, a font server
- QString fontmapname;
- int num = 0;
- // search font.dir and font.scale for the right file
- while (num < 2) {
- if (num == 0)
- fontmapname = (*it) + QLatin1String("/fonts.scale");
- else
- fontmapname = (*it) + QLatin1String("/fonts.dir");
- ++num;
- //qWarning(fontmapname);
- QFile fontmap(fontmapname);
- if (!fontmap.open(QIODevice::ReadOnly))
- continue;
- while (!fontmap.atEnd()) {
- QByteArray mapping = fontmap.readLine();
- QByteArray lmapping = mapping.toLower();
-
- //qWarning(xfontname);
- //qWarning(mapping);
- if (!lmapping.contains(searchname))
- continue;
- int index = mapping.indexOf(' ');
- QByteArray ffn = mapping.mid(0,index);
- // remove bitmap formats freetype can't handle
- if (ffn.contains(".spd") || ffn.contains(".phont"))
- continue;
- bool best_match = false;
- if (!best_mapping.isEmpty()) {
- if (lmapping.contains("-0-0-0-0-")) { // scalable font
- best_match = true;
- goto found;
- }
- if (lmapping.contains(encoding) && !best_mapping.toLower().contains(encoding))
- goto found;
- continue;
- }
-
- found:
- int colon = ffn.lastIndexOf(':');
- if (colon != -1) {
- QByteArray s = ffn.left(colon);
- ffn = ffn.mid(colon + 1);
- if (s.contains("ds="))
- *synth |= QFontEngine::SynthesizedBold;
- if (s.contains("ai="))
- *synth |= QFontEngine::SynthesizedItalic;
- }
- face_id.filename = (*it).toLocal8Bit() + '/' + ffn;
- best_mapping = mapping;
- if (best_match)
- goto end;
- }
- }
- }
-end:
-// qDebug("fontfile for %s is from '%s'\n got %s synth=%d", xname.data(),
-// best_mapping.data(), face_id.filename.data(), *synth);
- *freetype = QFreetypeFace::getFace(face_id);
- if (!*freetype) {
- face_id.index = 0;
- face_id.filename = QByteArray();
- }
- return face_id;
-}
-
-#endif // QT_NO_FREETYPE
-
-// defined in qfontdatabase_x11.cpp
-extern int qt_mib_for_xlfd_encoding(const char *encoding);
-extern int qt_xlfd_encoding_id(const char *encoding);
-
-static inline XCharStruct *charStruct(XFontStruct *xfs, uint ch)
-{
- XCharStruct *xcs = 0;
- unsigned char r = ch>>8;
- unsigned char c = ch&0xff;
- if (xfs->per_char &&
- r >= xfs->min_byte1 &&
- r <= xfs->max_byte1 &&
- c >= xfs->min_char_or_byte2 &&
- c <= xfs->max_char_or_byte2) {
- xcs = xfs->per_char + ((r - xfs->min_byte1) *
- (xfs->max_char_or_byte2 -
- xfs->min_char_or_byte2 + 1)) +
- (c - xfs->min_char_or_byte2);
- if (xcs->width == 0 && xcs->ascent == 0 && xcs->descent == 0)
- xcs = 0;
- }
- return xcs;
-}
-
-QFontEngineXLFD::QFontEngineXLFD(XFontStruct *fs, const QByteArray &name, int mib)
- : _fs(fs), _name(name), _codec(0), _cmap(mib)
-{
- if (_cmap) _codec = QTextCodec::codecForMib(_cmap);
-
- cache_cost = (((fs->max_byte1 - fs->min_byte1) *
- (fs->max_char_or_byte2 - fs->min_char_or_byte2 + 1)) +
- fs->max_char_or_byte2 - fs->min_char_or_byte2);
- cache_cost = ((fs->max_bounds.ascent + fs->max_bounds.descent) *
- (fs->max_bounds.width * cache_cost / 8));
- lbearing = SHRT_MIN;
- rbearing = SHRT_MIN;
- face_id.index = -1;
- freetype = 0;
- synth = 0;
-}
-
-QFontEngineXLFD::~QFontEngineXLFD()
-{
- XFreeFont(QX11Info::display(), _fs);
- _fs = 0;
-#ifndef QT_NO_FREETYPE
- if (freetype)
- freetype->release(face_id);
-#endif
-}
-
-bool QFontEngineXLFD::stringToCMap(const QChar *s, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- if (*nglyphs < len) {
- *nglyphs = len;
- return false;
- }
-
- // filter out surrogates, we can't handle them anyway with XLFD fonts
- QVarLengthArray<ushort> _s(len);
- QChar *str = (QChar *)_s.data();
- for (int i = 0; i < len; ++i) {
- if (i < len - 1
- && s[i].unicode() >= 0xd800 && s[i].unicode() < 0xdc00
- && s[i+1].unicode() >= 0xdc00 && s[i].unicode() < 0xe000) {
- *str = QChar();
- ++i;
- } else {
- *str = s[i];
- }
- ++str;
- }
-
- len = str - (QChar *)_s.data();
- str = (QChar *)_s.data();
-
- bool mirrored = flags & QTextEngine::RightToLeft;
- if (_codec) {
- bool haveNbsp = false;
- for (int i = 0; i < len; i++)
- if (str[i].unicode() == 0xa0) {
- haveNbsp = true;
- break;
- }
-
- QVarLengthArray<unsigned short> ch(len);
- QChar *chars = (QChar *)ch.data();
- if (haveNbsp || mirrored) {
- for (int i = 0; i < len; i++)
- chars[i] = (str[i].unicode() == 0xa0 ? 0x20 :
- (mirrored ? QChar::mirroredChar(str[i].unicode()) : str[i].unicode()));
- } else {
- for (int i = 0; i < len; i++)
- chars[i] = str[i].unicode();
- }
- QTextCodec::ConverterState state;
- state.flags = QTextCodec::ConvertInvalidToNull;
- QByteArray ba = _codec->fromUnicode(chars, len, &state);
- if (ba.length() == 2*len) {
- // double byte encoding
- const uchar *data = (const uchar *)ba.constData();
- for (int i = 0; i < len; i++) {
- glyphs->glyphs[i] = ((ushort)data[0] << 8) + data[1];
- data += 2;
- }
- } else {
- const uchar *data = (const uchar *)ba.constData();
- for (int i = 0; i < len; i++)
- glyphs->glyphs[i] = (ushort)data[i];
- }
- } else {
- int i = len;
- const QChar *c = str + len;
- if (mirrored) {
- while (c != str)
- glyphs->glyphs[--i] = (--c)->unicode() == 0xa0 ? 0x20 : QChar::mirroredChar(c->unicode());
- } else {
- while (c != str)
- glyphs->glyphs[--i] = (--c)->unicode() == 0xa0 ? 0x20 : c->unicode();
- }
- }
- *nglyphs = len;
- glyphs->numGlyphs = len;
-
- if (!(flags & QTextEngine::GlyphIndicesOnly))
- recalcAdvances(glyphs, flags);
- return true;
-}
-
-void QFontEngineXLFD::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags /*flags*/) const
-{
- int i = glyphs->numGlyphs;
- XCharStruct *xcs;
- // inlined for better performance
- if (!_fs->per_char) {
- xcs = &_fs->min_bounds;
- while (i != 0) {
- --i;
- const unsigned char r = glyphs->glyphs[i] >> 8;
- const unsigned char c = glyphs->glyphs[i] & 0xff;
- if (r >= _fs->min_byte1 &&
- r <= _fs->max_byte1 &&
- c >= _fs->min_char_or_byte2 &&
- c <= _fs->max_char_or_byte2) {
- glyphs->advances_x[i] = xcs->width;
- } else {
- glyphs->glyphs[i] = 0;
- }
- }
- }
- else if (!_fs->max_byte1) {
- XCharStruct *base = _fs->per_char - _fs->min_char_or_byte2;
- while (i != 0) {
- unsigned int gl = glyphs->glyphs[--i];
- xcs = (gl >= _fs->min_char_or_byte2 && gl <= _fs->max_char_or_byte2) ?
- base + gl : 0;
- if (!xcs || (!xcs->width && !xcs->ascent && !xcs->descent)) {
- glyphs->glyphs[i] = 0;
- } else {
- glyphs->advances_x[i] = xcs->width;
- }
- }
- }
- else {
- while (i != 0) {
- xcs = charStruct(_fs, glyphs->glyphs[--i]);
- if (!xcs) {
- glyphs->glyphs[i] = 0;
- } else {
- glyphs->advances_x[i] = xcs->width;
- }
- }
- }
-}
-
-glyph_metrics_t QFontEngineXLFD::boundingBox(const QGlyphLayout &glyphs)
-{
- int i;
-
- glyph_metrics_t overall;
- // initialize with line height, we get the same behaviour on all platforms
- overall.y = -ascent();
- overall.height = ascent() + descent() + 1;
- QFixed ymax;
- QFixed xmax;
- for (i = 0; i < glyphs.numGlyphs; i++) {
- XCharStruct *xcs = charStruct(_fs, glyphs.glyphs[i]);
- if (xcs) {
- QFixed x = overall.xoff + glyphs.offsets[i].x + xcs->lbearing;
- QFixed y = overall.yoff + glyphs.offsets[i].y - xcs->ascent;
- overall.x = qMin(overall.x, x);
- overall.y = qMin(overall.y, y);
- // XCharStruct::rbearing is defined as distance from left edge to rightmost pixel
- xmax = qMax(xmax, overall.xoff + glyphs.offsets[i].x + xcs->rbearing);
- ymax = qMax(ymax, y + xcs->ascent + xcs->descent);
- overall.xoff += glyphs.advances_x[i] + QFixed::fromFixed(glyphs.justifications[i].space_18d6);
- } else {
- QFixed size = _fs->ascent;
- overall.x = qMin(overall.x, overall.xoff);
- overall.y = qMin(overall.y, overall.yoff - size);
- ymax = qMax(ymax, overall.yoff);
- overall.xoff += size;
- xmax = qMax(xmax, overall.xoff);
- }
- }
- overall.height = qMax(overall.height, ymax - overall.y);
- overall.width = xmax - overall.x;
-
- return overall;
-}
-
-glyph_metrics_t QFontEngineXLFD::boundingBox(glyph_t glyph)
-{
- glyph_metrics_t gm;
- XCharStruct *xcs = charStruct(_fs, glyph);
- if (xcs) {
- // XCharStruct::rbearing is defined as distance from left edge to rightmost pixel
- // XCharStruct::width is defined as the advance
- gm = glyph_metrics_t(xcs->lbearing, -xcs->ascent, xcs->rbearing- xcs->lbearing, xcs->ascent + xcs->descent,
- xcs->width, 0);
- } else {
- QFixed size = ascent();
- gm = glyph_metrics_t(0, size, size, size, size, 0);
- }
- return gm;
-}
-
-QFixed QFontEngineXLFD::ascent() const
-{
- return _fs->ascent;
-}
-
-QFixed QFontEngineXLFD::descent() const
-{
- return (_fs->descent-1);
-}
-
-QFixed QFontEngineXLFD::leading() const
-{
- QFixed l = QFixed(qMin<int>(_fs->ascent, _fs->max_bounds.ascent)
- + qMin<int>(_fs->descent, _fs->max_bounds.descent)) * QFixed::fromReal(0.15);
- return l.ceil();
-}
-
-qreal QFontEngineXLFD::maxCharWidth() const
-{
- return _fs->max_bounds.width;
-}
-
-
-// Loads the font for the specified script
-static inline int maxIndex(XFontStruct *f) {
- return (((f->max_byte1 - f->min_byte1) *
- (f->max_char_or_byte2 - f->min_char_or_byte2 + 1)) +
- f->max_char_or_byte2 - f->min_char_or_byte2);
-}
-
-qreal QFontEngineXLFD::minLeftBearing() const
-{
- if (lbearing == SHRT_MIN) {
- if (_fs->per_char) {
- XCharStruct *cs = _fs->per_char;
- int nc = maxIndex(_fs) + 1;
- int mx = cs->lbearing;
-
- for (int c = 1; c < nc; c++) {
- // ignore the bearings for characters whose ink is
- // completely outside the normal bounding box
- if ((cs[c].lbearing <= 0 && cs[c].rbearing <= 0) ||
- (cs[c].lbearing >= cs[c].width && cs[c].rbearing >= cs[c].width))
- continue;
-
- int nmx = cs[c].lbearing;
-
- if (nmx < mx)
- mx = nmx;
- }
-
- ((QFontEngineXLFD *)this)->lbearing = mx;
- } else
- ((QFontEngineXLFD *)this)->lbearing = _fs->min_bounds.lbearing;
- }
- return lbearing;
-}
-
-qreal QFontEngineXLFD::minRightBearing() const
-{
- if (rbearing == SHRT_MIN) {
- if (_fs->per_char) {
- XCharStruct *cs = _fs->per_char;
- int nc = maxIndex(_fs) + 1;
- int mx = cs->rbearing;
-
- for (int c = 1; c < nc; c++) {
- // ignore the bearings for characters whose ink is
- // completely outside the normal bounding box
- if ((cs[c].lbearing <= 0 && cs[c].rbearing <= 0) ||
- (cs[c].lbearing >= cs[c].width && cs[c].rbearing >= cs[c].width))
- continue;
-
- int nmx = cs[c].rbearing;
-
- if (nmx < mx)
- mx = nmx;
- }
-
- ((QFontEngineXLFD *)this)->rbearing = mx;
- } else
- ((QFontEngineXLFD *)this)->rbearing = _fs->min_bounds.rbearing;
- }
- return rbearing;
-}
-
-const char *QFontEngineXLFD::name() const
-{
- return _name;
-}
-
-bool QFontEngineXLFD::canRender(const QChar *string, int len)
-{
- QVarLengthGlyphLayoutArray glyphs(len);
- int nglyphs = len;
- if (stringToCMap(string, len, &glyphs, &nglyphs, 0) == false) {
- glyphs.resize(nglyphs);
- stringToCMap(string, len, &glyphs, &nglyphs, 0);
- }
-
- bool allExist = true;
- for (int i = 0; i < nglyphs; i++) {
- if (!glyphs.glyphs[i] || !charStruct(_fs, glyphs.glyphs[i])) {
- allExist = false;
- break;
- }
- }
-
- return allExist;
-}
-
-QBitmap QFontEngineXLFD::bitmapForGlyphs(const QGlyphLayout &glyphs, const glyph_metrics_t &metrics, QTextItem::RenderFlags flags)
-{
- int w = metrics.width.toInt();
- int h = metrics.height.toInt();
- if (w <= 0 || h <= 0)
- return QBitmap();
-
- QPixmapData *data = new QX11PixmapData(QPixmapData::BitmapType);
- data->resize(w, h);
- QPixmap bm(data);
- QPainter p(&bm);
- p.fillRect(0, 0, w, h, Qt::color0);
- p.setPen(Qt::color1);
-
- QTextItemInt item;
- item.flags = flags;
- item.ascent = -metrics.y;
- item.descent = metrics.height - item.ascent;
- item.width = metrics.width;
- item.chars = 0;
- item.num_chars = 0;
- item.logClusters = 0;
- item.glyphs = glyphs;
- item.fontEngine = this;
- item.f = 0;
-
- p.drawTextItem(QPointF(-metrics.x.toReal(), item.ascent.toReal()), item);
- p.end();
-
- return QBitmap(bm);
-}
-
-void QFontEngineXLFD::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags)
-{
- // cannot use QFontEngine::addBitmapFontToPath(), since we don't
- // have direct access to the glyph bitmaps, so we have to draw
- // onto a QBitmap, then convert to QImage, then to path
- glyph_metrics_t metrics = boundingBox(glyphs);
-
- QImage image = bitmapForGlyphs(glyphs, metrics, flags).toImage();
- if (image.isNull())
- return;
-
- image = image.convertToFormat(QImage::Format_Mono);
- const uchar *image_data = image.bits();
- uint bpl = image.bytesPerLine();
- // from qfontengine.cpp
- extern void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data,
- int bpl, int w, int h, QPainterPath *path);
- qt_addBitmapToPath(x, y + metrics.y.toReal(), image_data, bpl, image.width(), image.height(), path);
-}
-
-QFontEngine::FaceId QFontEngineXLFD::faceId() const
-{
-#ifndef QT_NO_FREETYPE
- if (face_id.index == -1) {
- face_id = fontFile(_name, &freetype, &synth);
- if (_codec)
- face_id.encoding = _codec->mibEnum();
- if (freetype) {
- const_cast<QFontEngineXLFD *>(this)->fsType = freetype->fsType();
- } else {
- face_id.index = 0;
- face_id.filename = '-' + QFontEngine::properties().postscriptName;
- }
- }
-#endif
-
- return face_id;
-}
-
-QFontEngine::Properties QFontEngineXLFD::properties() const
-{
- if (face_id.index == -1)
- (void)faceId();
-
-#ifndef QT_NO_FREETYPE
- if (freetype)
- return freetype->properties();
-#endif
- return QFontEngine::properties();
-}
-
-void QFontEngineXLFD::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
-{
- if (face_id.index == -1)
- (void)faceId();
-#ifndef QT_NO_FREETYPE
- if (!freetype)
-#endif
- {
- QFontEngine::getUnscaledGlyph(glyph, path, metrics);
- return;
- }
-
-#ifndef QT_NO_FREETYPE
- freetype->lock();
-
- FT_Face face = freetype->face;
- FT_Set_Char_Size(face, face->units_per_EM << 6, face->units_per_EM << 6, 0, 0);
- freetype->xsize = face->units_per_EM << 6;
- freetype->ysize = face->units_per_EM << 6;
- FT_Set_Transform(face, 0, 0);
- glyph = glyphIndexToFreetypeGlyphIndex(glyph);
- FT_Load_Glyph(face, glyph, FT_LOAD_NO_BITMAP);
-
- int left = face->glyph->metrics.horiBearingX;
- int right = face->glyph->metrics.horiBearingX + face->glyph->metrics.width;
- int top = face->glyph->metrics.horiBearingY;
- int bottom = face->glyph->metrics.horiBearingY - face->glyph->metrics.height;
-
- QFixedPoint p;
- p.x = 0;
- p.y = 0;
- metrics->width = QFixed::fromFixed(right-left);
- metrics->height = QFixed::fromFixed(top-bottom);
- metrics->x = QFixed::fromFixed(left);
- metrics->y = QFixed::fromFixed(-top);
- metrics->xoff = QFixed::fromFixed(face->glyph->advance.x);
-
- if (!FT_IS_SCALABLE(freetype->face))
- QFreetypeFace::addBitmapToPath(face->glyph, p, path);
- else
- QFreetypeFace::addGlyphToPath(face, face->glyph, p, path, face->units_per_EM << 6, face->units_per_EM << 6);
-
- FT_Set_Transform(face, &freetype->matrix, 0);
- freetype->unlock();
-#endif // QT_NO_FREETYPE
-}
-
-
-bool QFontEngineXLFD::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
-#ifndef QT_NO_FREETYPE
- if (face_id.index == -1)
- (void)faceId();
- if (!freetype)
- return false;
- return freetype->getSfntTable(tag, buffer, length);
-#else
- Q_UNUSED(tag);
- Q_UNUSED(buffer);
- Q_UNUSED(length);
- return false;
-#endif
-}
-
-int QFontEngineXLFD::synthesized() const
-{
- return synth;
-}
-
-QImage QFontEngineXLFD::alphaMapForGlyph(glyph_t glyph)
-{
- glyph_metrics_t metrics = boundingBox(glyph);
-
-/*
- printf("a) w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\n",
- metrics.width.toReal(),
- metrics.height.toReal(),
- metrics.xoff.toReal(),
- metrics.yoff.toReal(),
- metrics.x.toReal(),
- metrics.y.toReal());
-*/
-
- QGlyphLayoutArray<1> glyphs;
- glyphs.glyphs[0] = glyph;
-
- QImage image = bitmapForGlyphs(glyphs, metrics).toImage();
-//image.save(QString::fromLatin1("x11cache-%1.png").arg((int)glyph));
-
- image = image.convertToFormat(QImage::Format_Indexed8);
- QVector<QRgb> colors(256);
- for (int i = 0; i < 256; ++i)
- colors[i] = qRgba(0, 0, 0, i);
- image.setColorTable(colors);
-
- int width = image.width();
- int height = image.height();
- for (int y = 0; y < height; ++y) {
- uchar *bits = image.scanLine(y);
- for (int x = 0; x < width; ++x)
- bits[x] = ~(bits[x]-1);
- }
-
- return image;
-}
-
-#ifndef QT_NO_FREETYPE
-
-FT_Face QFontEngineXLFD::non_locked_face() const
-{
- return freetype ? freetype->face : 0;
-}
-
-uint QFontEngineXLFD::toUnicode(glyph_t g) const
-{
- if (_codec) {
- QTextCodec::ConverterState state;
- state.flags = QTextCodec::ConvertInvalidToNull;
- uchar data[2];
- int l = 1;
- if (g > 255) {
- data[0] = (g >> 8);
- data[1] = (g & 255);
- l = 2;
- } else {
- data[0] = g;
- }
- QString s = _codec->toUnicode((char *)data, l, &state);
- Q_ASSERT(s.length() == 1);
- g = s.at(0).unicode();
- }
- return g;
-}
-
-glyph_t QFontEngineXLFD::glyphIndexToFreetypeGlyphIndex(glyph_t g) const
-{
- return FT_Get_Char_Index(freetype->face, toUnicode(g));
-}
-#endif
-
-#ifndef QT_NO_FONTCONFIG
-
-// ------------------------------------------------------------------
-// Multi FT engine
-// ------------------------------------------------------------------
-
-static QFontEngine *engineForPattern(FcPattern *pattern, const QFontDef &request,
- int screen)
-{
- FcResult res;
- FcPattern *match = FcFontMatch(0, pattern, &res);
- QFontEngineX11FT *engine = new QFontEngineX11FT(match, request, screen);
- if (!engine->invalid())
- return engine;
-
- delete engine;
- QFontEngine *fe = new QFontEngineBox(request.pixelSize);
- fe->fontDef = request;
- return fe;
-}
-
-QFontEngineMultiFT::QFontEngineMultiFT(QFontEngine *fe, FcPattern *matchedPattern, FcPattern *p, int s, const QFontDef &req)
- : QFontEngineMulti(2), request(req), pattern(p), firstEnginePattern(matchedPattern), fontSet(0), screen(s)
-{
-
- engines[0] = fe;
- engines.at(0)->ref.ref();
- fontDef = engines[0]->fontDef;
- cache_cost = 100;
- firstFontIndex = 1;
-}
-
-QFontEngineMultiFT::~QFontEngineMultiFT()
-{
- extern QMutex *qt_fontdatabase_mutex();
- QMutexLocker locker(qt_fontdatabase_mutex());
-
- FcPatternDestroy(pattern);
- if (firstEnginePattern)
- FcPatternDestroy(firstEnginePattern);
- if (fontSet)
- FcFontSetDestroy(fontSet);
-}
-
-
-void QFontEngineMultiFT::loadEngine(int at)
-{
- extern QMutex *qt_fontdatabase_mutex();
- QMutexLocker locker(qt_fontdatabase_mutex());
-
- extern void qt_addPatternProps(FcPattern *pattern, int screen, int script,
- const QFontDef &request);
- extern QFontDef qt_FcPatternToQFontDef(FcPattern *pattern, const QFontDef &);
- extern FcFontSet *qt_fontSetForPattern(FcPattern *pattern, const QFontDef &request);
-
- Q_ASSERT(at > 0);
- if (!fontSet) {
- fontSet = qt_fontSetForPattern(pattern, request);
-
- // it may happen that the fontset of fallbacks consists of only one font. In this case we
- // have to fall back to the box fontengine as we cannot render the glyph.
- if (fontSet->nfont == 1 && at == 1 && engines.size() == 2) {
- Q_ASSERT(engines.at(at) == 0);
- QFontEngine *fe = new QFontEngineBox(request.pixelSize);
- fe->fontDef = request;
- engines[at] = fe;
- return;
- }
-
- if (firstEnginePattern) {
-
- if (!FcPatternEqual(firstEnginePattern, fontSet->fonts[0]))
- firstFontIndex = 0;
-
- FcPatternDestroy(firstEnginePattern);
- firstEnginePattern = 0;
- }
-
- engines.resize(fontSet->nfont + 1 - firstFontIndex);
- }
- Q_ASSERT(at < engines.size());
- Q_ASSERT(engines.at(at) == 0);
-
- FcPattern *pattern = FcPatternDuplicate(fontSet->fonts[at + firstFontIndex - 1]);
- qt_addPatternProps(pattern, screen, QUnicodeTables::Common, request);
-
- QFontDef fontDef = qt_FcPatternToQFontDef(pattern, this->request);
-
- // note: we use -1 for the script to make sure that we keep real
- // FT engines separate from Multi engines in the font cache
- QFontCache::Key key(fontDef, -1, screen);
- QFontEngine *fontEngine = QFontCache::instance()->findEngine(key);
- if (!fontEngine) {
- FcConfigSubstitute(0, pattern, FcMatchPattern);
- FcDefaultSubstitute(pattern);
- fontEngine = engineForPattern(pattern, request, screen);
- QFontCache::instance()->insertEngine(key, fontEngine);
- }
- FcPatternDestroy(pattern);
- fontEngine->ref.ref();
- engines[at] = fontEngine;
-}
-
-// ------------------------------------------------------------------
-// X11 FT engine
-// ------------------------------------------------------------------
-
-
-
-Q_GUI_EXPORT void qt_x11ft_convert_pattern(FcPattern *pattern, QByteArray *file_name, int *index, bool *antialias)
-{
- FcChar8 *fileName;
- FcPatternGetString(pattern, FC_FILE, 0, &fileName);
- *file_name = (const char *)fileName;
- if (!FcPatternGetInteger(pattern, FC_INDEX, 0, index))
- index = 0;
- FcBool b;
- if (FcPatternGetBool(pattern, FC_ANTIALIAS, 0, &b) == FcResultMatch)
- *antialias = b;
-}
-
-
-QFontEngineX11FT::QFontEngineX11FT(FcPattern *pattern, const QFontDef &fd, int screen)
- : QFontEngineFT(fd)
-{
-// FcPatternPrint(pattern);
-
- bool antialias = X11->fc_antialias;
- QByteArray file_name;
- int face_index;
- qt_x11ft_convert_pattern(pattern, &file_name, &face_index, &antialias);
- QFontEngine::FaceId face_id;
- face_id.filename = file_name;
- face_id.index = face_index;
-
- canUploadGlyphsToServer = QApplication::testAttribute(Qt::AA_X11InitThreads) || (qApp->thread() == QThread::currentThread());
-
- subpixelType = Subpixel_None;
- if (antialias) {
- int subpixel = X11->display ? X11->screens[screen].subpixel : FC_RGBA_UNKNOWN;
- if (subpixel == FC_RGBA_UNKNOWN)
- (void) FcPatternGetInteger(pattern, FC_RGBA, 0, &subpixel);
- if (!antialias || subpixel == FC_RGBA_UNKNOWN)
- subpixel = FC_RGBA_NONE;
-
- switch (subpixel) {
- case FC_RGBA_NONE: subpixelType = Subpixel_None; break;
- case FC_RGBA_RGB: subpixelType = Subpixel_RGB; break;
- case FC_RGBA_BGR: subpixelType = Subpixel_BGR; break;
- case FC_RGBA_VRGB: subpixelType = Subpixel_VRGB; break;
- case FC_RGBA_VBGR: subpixelType = Subpixel_VBGR; break;
- default: break;
- }
- }
-
- if (fd.hintingPreference != QFont::PreferDefaultHinting) {
- switch (fd.hintingPreference) {
- case QFont::PreferNoHinting:
- default_hint_style = HintNone;
- break;
- case QFont::PreferVerticalHinting:
- default_hint_style = HintLight;
- break;
- case QFont::PreferFullHinting:
- default:
- default_hint_style = HintFull;
- break;
- }
- }
-#ifdef FC_HINT_STYLE
- else {
- int hint_style = 0;
- // Try to use Xft.hintstyle from XDefaults first if running in GNOME, to match
- // the behavior of cairo
- if (X11->fc_hint_style > -1 && X11->desktopEnvironment == DE_GNOME)
- hint_style = X11->fc_hint_style;
- else if (FcPatternGetInteger (pattern, FC_HINT_STYLE, 0, &hint_style) == FcResultNoMatch
- && X11->fc_hint_style > -1)
- hint_style = X11->fc_hint_style;
-
- switch (hint_style) {
- case FC_HINT_NONE:
- default_hint_style = HintNone;
- break;
- case FC_HINT_SLIGHT:
- default_hint_style = HintLight;
- break;
- case FC_HINT_MEDIUM:
- default_hint_style = HintMedium;
- break;
- default:
- default_hint_style = HintFull;
- break;
- }
- }
-#endif
-
-#if defined(FC_AUTOHINT) && defined(FT_LOAD_FORCE_AUTOHINT)
- {
- bool autohint = false;
-
- FcBool b;
- if (FcPatternGetBool(pattern, FC_AUTOHINT, 0, &b) == FcResultMatch)
- autohint = b;
-
- if (autohint)
- default_load_flags |= FT_LOAD_FORCE_AUTOHINT;
- }
-#endif
-
-#if defined(FC_LCD_FILTER) && defined(FT_LCD_FILTER_H)
- {
- int filter = FC_LCD_FILTER_NONE;
- if (FcPatternGetInteger(pattern, FC_LCD_FILTER, 0, &filter) == FcResultMatch) {
- switch (filter) {
- case FC_LCD_FILTER_NONE:
- lcdFilterType = FT_LCD_FILTER_NONE;
- break;
- case FC_LCD_FILTER_DEFAULT:
- lcdFilterType = FT_LCD_FILTER_DEFAULT;
- break;
- case FC_LCD_FILTER_LIGHT:
- lcdFilterType = FT_LCD_FILTER_LIGHT;
- break;
- case FC_LCD_FILTER_LEGACY:
- lcdFilterType = FT_LCD_FILTER_LEGACY;
- break;
- default:
- // new unknown lcd filter type?!
- break;
- }
- }
- }
-#endif
-
-#ifdef FC_EMBEDDED_BITMAP
- {
- FcBool b;
- if (FcPatternGetBool(pattern, FC_EMBEDDED_BITMAP, 0, &b) == FcResultMatch)
- embeddedbitmap = b;
- }
-#endif
-
- GlyphFormat defaultFormat = Format_None;
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- int format = PictStandardA8;
- if (!antialias)
- format = PictStandardA1;
- else if (subpixelType == Subpixel_RGB
- || subpixelType == Subpixel_BGR
- || subpixelType == Subpixel_VRGB
- || subpixelType == Subpixel_VBGR)
- format = PictStandardARGB32;
- xglyph_format = format;
-
- if (subpixelType != QFontEngineFT::Subpixel_None)
- defaultFormat = Format_A32;
- else if (antialias)
- defaultFormat = Format_A8;
- else
- defaultFormat = Format_Mono;
- }
-#endif
-
- if (!init(face_id, antialias, defaultFormat)) {
- FcPatternDestroy(pattern);
- return;
- }
-
- if (!freetype->charset) {
- FcCharSet *cs;
- FcPatternGetCharSet (pattern, FC_CHARSET, 0, &cs);
- freetype->charset = FcCharSetCopy(cs);
- }
- FcPatternDestroy(pattern);
-}
-
-QFontEngineX11FT::~QFontEngineX11FT()
-{
- freeGlyphSets();
-}
-
-unsigned long QFontEngineX11FT::allocateServerGlyphSet()
-{
-#ifndef QT_NO_XRENDER
- if (!canUploadGlyphsToServer || !X11->use_xrender)
- return 0;
- return XRenderCreateGlyphSet(X11->display, XRenderFindStandardFormat(X11->display, xglyph_format));
-#else
- return 0;
-#endif
-}
-
-void QFontEngineX11FT::freeServerGlyphSet(unsigned long id)
-{
-#ifndef QT_NO_XRENDER
- if (!id)
- return;
- XRenderFreeGlyphSet(X11->display, id);
-#endif
-}
-
-bool QFontEngineX11FT::uploadGlyphToServer(QGlyphSet *set, uint glyphid, Glyph *g, GlyphInfo *info, int glyphDataSize) const
-{
-#ifndef QT_NO_XRENDER
- if (!canUploadGlyphsToServer)
- return false;
- if (g->format == Format_Mono) {
- /*
- * swap bit order around; FreeType is always MSBFirst
- */
- if (BitmapBitOrder(X11->display) != MSBFirst) {
- unsigned char *line = g->data;
- int i = glyphDataSize;
- while (i--) {
- unsigned char c;
- c = *line;
- c = ((c << 1) & 0xaa) | ((c >> 1) & 0x55);
- c = ((c << 2) & 0xcc) | ((c >> 2) & 0x33);
- c = ((c << 4) & 0xf0) | ((c >> 4) & 0x0f);
- *line++ = c;
- }
- }
- }
-
- ::Glyph xglyph = glyphid;
- XRenderAddGlyphs (X11->display, set->id, &xglyph, info, 1, (const char *)g->data, glyphDataSize);
- delete [] g->data;
- g->data = 0;
- g->format = Format_None;
- g->uploadedToServer = true;
- return true;
-#else
- return false;
-#endif
-}
-
-QFontEngine *QFontEngineX11FT::cloneWithSize(qreal pixelSize) const
-{
- QFontDef fontDef;
- fontDef.pixelSize = pixelSize;
- QFontEngineX11FT *fe = new QFontEngineX11FT(fontDef);
- if (!fe->initFromFontEngine(this)) {
- delete fe;
- return 0;
- } else {
- fe->xglyph_format = xglyph_format;
- return fe;
- }
-}
-
-#endif // QT_NO_FONTCONFIG
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qfontengine_x11_p.h b/src/gui/platforms/x11/qfontengine_x11_p.h
deleted file mode 100644
index d7eb39daaa..0000000000
--- a/src/gui/platforms/x11/qfontengine_x11_p.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTENGINE_X11_P_H
-#define QFONTENGINE_X11_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-#include <private/qt_x11_p.h>
-
-#include <private/qfontengine_ft_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QFreetypeFace;
-
-// --------------------------------------------------------------------------
-
-class QFontEngineMultiXLFD : public QFontEngineMulti
-{
-public:
- QFontEngineMultiXLFD(const QFontDef &r, const QList<int> &l, int s);
- ~QFontEngineMultiXLFD();
-
- void loadEngine(int at);
-
-private:
- QList<int> encodings;
- int screen;
- QFontDef request;
-};
-
-/**
- * \internal The font engine for X Logical Font Description (XLFD) fonts, which is for X11 systems without freetype.
- */
-class QFontEngineXLFD : public QFontEngine
-{
-public:
- QFontEngineXLFD(XFontStruct *f, const QByteArray &name, int mib);
- ~QFontEngineXLFD();
-
- virtual QFontEngine::FaceId faceId() const;
- QFontEngine::Properties properties() const;
- virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
- virtual bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
- virtual int synthesized() const;
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
- QTextEngine::ShaperFlags flags) const;
- virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- virtual glyph_metrics_t boundingBox(glyph_t glyph);
-
- virtual void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags);
- virtual QFixed ascent() const;
- virtual QFixed descent() const;
- virtual QFixed leading() const;
- virtual qreal maxCharWidth() const;
- virtual qreal minLeftBearing() const;
- virtual qreal minRightBearing() const;
- virtual QImage alphaMapForGlyph(glyph_t);
-
- virtual inline Type type() const
- { return QFontEngine::XLFD; }
-
- virtual bool canRender(const QChar *string, int len);
- virtual const char *name() const;
-
- inline XFontStruct *fontStruct() const
- { return _fs; }
-
-#ifndef QT_NO_FREETYPE
- FT_Face non_locked_face() const;
- glyph_t glyphIndexToFreetypeGlyphIndex(glyph_t g) const;
-#endif
- uint toUnicode(glyph_t g) const;
-
-private:
- QBitmap bitmapForGlyphs(const QGlyphLayout &glyphs, const glyph_metrics_t &metrics, QTextItem::RenderFlags flags = 0);
-
- XFontStruct *_fs;
- QByteArray _name;
- QTextCodec *_codec;
- int _cmap;
- int lbearing, rbearing;
- mutable QFontEngine::FaceId face_id;
- mutable QFreetypeFace *freetype;
- mutable int synth;
-};
-
-#ifndef QT_NO_FONTCONFIG
-
-class Q_GUI_EXPORT QFontEngineMultiFT : public QFontEngineMulti
-{
-public:
- QFontEngineMultiFT(QFontEngine *fe, FcPattern *firstEnginePattern, FcPattern *p, int s, const QFontDef &request);
- ~QFontEngineMultiFT();
-
- void loadEngine(int at);
-
-private:
- QFontDef request;
- FcPattern *pattern;
- FcPattern *firstEnginePattern;
- FcFontSet *fontSet;
- int screen;
- int firstFontIndex; // first font in fontset
-};
-
-class Q_GUI_EXPORT QFontEngineX11FT : public QFontEngineFT
-{
-public:
- explicit QFontEngineX11FT(const QFontDef &fontDef) : QFontEngineFT(fontDef) {}
- explicit QFontEngineX11FT(FcPattern *pattern, const QFontDef &fd, int screen);
- ~QFontEngineX11FT();
-
- QFontEngine *cloneWithSize(qreal pixelSize) const;
-
-#ifndef QT_NO_XRENDER
- int xglyph_format;
-#endif
-
-protected:
- virtual bool uploadGlyphToServer(QGlyphSet *set, uint glyphid, Glyph *g, GlyphInfo *info, int glyphDataSize) const;
- virtual unsigned long allocateServerGlyphSet();
- virtual void freeServerGlyphSet(unsigned long id);
-};
-
-#endif // QT_NO_FONTCONFIG
-
-QT_END_NAMESPACE
-
-#endif // QFONTENGINE_X11_P_H
diff --git a/src/gui/platforms/x11/qkde.cpp b/src/gui/platforms/x11/qkde.cpp
deleted file mode 100644
index 7d333feb9a..0000000000
--- a/src/gui/platforms/x11/qkde.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** 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 "qkde_p.h"
-#include <QtCore/QLibrary>
-#include <QtCore/QDir>
-#include <QtCore/qdebug.h>
-#include <QtCore/QSettings>
-#include "QtGui/qstylefactory.h"
-#include "qt_x11_p.h"
-
-#if defined(Q_WS_X11)
-
-QT_BEGIN_NAMESPACE
-
-/*! \internal
-Gets the current KDE home path
-like "/home/troll/.kde"
-*/
-QString QKde::kdeHome()
-{
- static QString kdeHomePath;
- if (kdeHomePath.isEmpty()) {
- kdeHomePath = QString::fromLocal8Bit(qgetenv("KDEHOME"));
- if (kdeHomePath.isEmpty()) {
- QDir homeDir(QDir::homePath());
- QString kdeConfDir(QLatin1String("/.kde"));
- if (4 == X11->desktopVersion && homeDir.exists(QLatin1String(".kde4")))
- kdeConfDir = QLatin1String("/.kde4");
- kdeHomePath = QDir::homePath() + kdeConfDir;
- }
- }
- return kdeHomePath;
-}
-
-/*!\internal
- Reads the color from the config, and store it in the palette with the given color role if found
- */
-static bool kdeColor(QPalette *pal, QPalette::ColorRole role, const QSettings &kdeSettings, const QString &kde4Key, const QString &kde3Key = QString())
-{
- QVariant variant = kdeSettings.value(kde4Key);
- if (!variant.isValid())
- QVariant variant = kdeSettings.value(kde3Key);
- if (variant.isValid()) {
- QStringList values = variant.toStringList();
- if (values.size() == 3) {
- int r = values[0].toInt();
- int g = values[1].toInt();
- int b = values[2].toInt();
- pal->setBrush(role, QColor(r, g, b));
- return true;
- }
- }
- return false;
-}
-
-
-/*!\internal
- Returns the KDE palette
-*/
-QPalette QKde::kdePalette()
-{
- const QSettings theKdeSettings(QKde::kdeHome() +
- QLatin1String("/share/config/kdeglobals"), QSettings::IniFormat);
- QPalette pal;
-
- // Setup KDE palette
- kdeColor(&pal, QPalette::Button, theKdeSettings, QLatin1String("Colors:Button/BackgroundNormal"), QLatin1String("buttonBackground"));
- kdeColor(&pal, QPalette::Window, theKdeSettings, QLatin1String("Colors:Window/BackgroundNormal"), QLatin1String("background"));
- kdeColor(&pal, QPalette::Text, theKdeSettings, QLatin1String("Colors:View/ForegroundNormal"), QLatin1String("foreground"));
- kdeColor(&pal, QPalette::WindowText, theKdeSettings, QLatin1String("Colors:Window/ForegroundNormal"), QLatin1String("windowForeground"));
- kdeColor(&pal, QPalette::Base, theKdeSettings, QLatin1String("Colors:View/BackgroundNormal"), QLatin1String("windowBackground"));
- kdeColor(&pal, QPalette::Highlight, theKdeSettings, QLatin1String("Colors:Selection/BackgroundNormal"), QLatin1String("selectBackground"));
- kdeColor(&pal, QPalette::HighlightedText, theKdeSettings, QLatin1String("Colors:Selection/ForegroundNormal"), QLatin1String("selectForeground"));
- kdeColor(&pal, QPalette::AlternateBase, theKdeSettings, QLatin1String("Colors:View/BackgroundAlternate"), QLatin1String("alternateBackground"));
- kdeColor(&pal, QPalette::ButtonText, theKdeSettings, QLatin1String("Colors:Button/ForegroundNormal"), QLatin1String("buttonForeground"));
- kdeColor(&pal, QPalette::Link, theKdeSettings, QLatin1String("Colors:View/ForegroundLink"), QLatin1String("linkColor"));
- kdeColor(&pal, QPalette::LinkVisited, theKdeSettings, QLatin1String("Colors:View/ForegroundVisited"), QLatin1String("visitedLinkColor"));
- //## TODO tooltip color
-
- return pal;
-}
-
-/*!\internal
- Returns the name of the QStyle to use.
- (read from the kde config if needed)
-*/
-QString QKde::kdeStyle()
-{
- if (X11->desktopVersion >= 4) {
- QSettings kdeSettings(QKde::kdeHome() + QLatin1String("/share/config/kdeglobals"), QSettings::IniFormat);
- QString style = kdeSettings.value(QLatin1String("widgetStyle"), QLatin1String("Oxygen")).toString();
-
- QStringList availableStyles = QStyleFactory::keys();
- if(availableStyles.contains(style, Qt::CaseInsensitive))
- return style;
- }
-
- if (X11->use_xrender)
- return QLatin1String("plastique");
- else
- return QLatin1String("windows");
-}
-
-
-int QKde::kdeToolButtonStyle()
-{
- QSettings settings(QKde::kdeHome() + QLatin1String("/share/config/kdeglobals"),
- QSettings::IniFormat);
- settings.beginGroup(QLatin1String("Toolbar style"));
- QString toolbarStyle = settings.value(QLatin1String("ToolButtonStyle"), QLatin1String("TextBesideIcon")).toString();
- if (toolbarStyle == QLatin1String("TextBesideIcon"))
- return Qt::ToolButtonTextBesideIcon;
- else if (toolbarStyle == QLatin1String("TextOnly"))
- return Qt::ToolButtonTextOnly;
- else if (toolbarStyle == QLatin1String("TextUnderIcon"))
- return Qt::ToolButtonTextUnderIcon;
-
- return Qt::ToolButtonTextBesideIcon;
-}
-
-int QKde::kdeToolBarIconSize()
-{
- static int iconSize = -1;
- if (iconSize == -1) {
- QSettings settings(QKde::kdeHome() + QLatin1String("/share/config/kdeglobals"),
- QSettings::IniFormat);
- settings.beginGroup(QLatin1String("ToolbarIcons"));
- iconSize = settings.value(QLatin1String("Size")).toInt();
- }
- return iconSize;
-}
-
-QT_END_NAMESPACE
-
-#endif //Q_WS_X11
-
diff --git a/src/gui/platforms/x11/qkde_p.h b/src/gui/platforms/x11/qkde_p.h
deleted file mode 100644
index 4e108f6e9e..0000000000
--- a/src/gui/platforms/x11/qkde_p.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** 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 QKDE_H
-#define QKDE_H
-
-#include <QtCore/qglobal.h>
-#include <QtGui/QPalette>
-#include <QtGui/QIcon>
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-#if defined(Q_WS_X11)
-
-
-QT_BEGIN_NAMESPACE
-
-/*!\internal
- This namespace contains helper function to help KDE integration
- They are only used if we detect the use of KDE and the KDE platform plugin is not found (old KDE version)
- Or if the detected KDE version is KDE3
-*/
-namespace QKde {
- QString kdeHome();
- QString kdeStyle();
- QPalette kdePalette();
- int kdeToolButtonStyle();
- int kdeToolBarIconSize();
-}
-
-
-QT_END_NAMESPACE
-
-#endif // Q_WS_X11
-#endif // QKDE_H
diff --git a/src/gui/platforms/x11/qkeymapper_x11.cpp b/src/gui/platforms/x11/qkeymapper_x11.cpp
deleted file mode 100644
index 5383bfd456..0000000000
--- a/src/gui/platforms/x11/qkeymapper_x11.cpp
+++ /dev/null
@@ -1,1869 +0,0 @@
-/****************************************************************************
-**
-** 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 "qkeymapper_p.h"
-
-#include "qdebug.h"
-#include "qtextcodec.h"
-#include "qwidget.h"
-
-#include "qapplication_p.h"
-#include "qevent_p.h"
-#include "qt_x11_p.h"
-
-#ifndef QT_NO_XKB
-# include <X11/XKBlib.h>
-#endif
-
-#define XK_MISCELLANY
-#define XK_LATIN1
-#define XK_KOREAN
-#define XK_XKB_KEYS
-#include <X11/keysymdef.h>
-
-#include <ctype.h>
-
-#ifdef QT_LINUXBASE
-// LSB's IsKeypadKey define is wrong - see
-// http://bugs.linuxbase.org/show_bug.cgi?id=2521
-#undef IsKeypadKey
-#define IsKeypadKey(keysym) \
- (((KeySym)(keysym) >= XK_KP_Space) && ((KeySym)(keysym) <= XK_KP_Equal))
-
-#undef IsPrivateKeypadKey
-#define IsPrivateKeypadKey(keysym) \
- (((KeySym)(keysym) >= 0x11000000) && ((KeySym)(keysym) <= 0x1100FFFF))
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_XKB
-
-// bring in the auto-generated xkbLayoutData
-#include "qkeymapper_x11_p.cpp"
-
-QLocale q_getKeyboardLocale(const QByteArray &layoutName, const QByteArray &variantName)
-{
- int i = 0;
- while (xkbLayoutData[i].layout != 0) {
- if (layoutName == xkbLayoutData[i].layout && variantName == xkbLayoutData[i].variant)
- return QLocale(xkbLayoutData[i].language, xkbLayoutData[i].country);
- ++i;
- }
- return QLocale::c();
-}
-#endif // QT_NO_XKB
-
-// from qapplication_x11.cpp
-extern uchar qt_alt_mask;
-extern uchar qt_meta_mask;
-extern uchar qt_super_mask;
-extern uchar qt_hyper_mask;
-extern uchar qt_mode_switch_mask;
-uchar qt_num_lock_mask = 0;
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-// ### we should really resolve conflicts with other masks by
-// ### decomposing the Qt::KeyboardModifers in possibleKeys()
-#define SETMASK(sym, mask) \
- do { \
- if (qt_alt_mask == 0 \
- && qt_meta_mask != mask \
- && qt_super_mask != mask \
- && qt_hyper_mask != mask \
- && (sym == XK_Alt_L || sym == XK_Alt_R)) { \
- qt_alt_mask = mask; \
- } \
- if (qt_meta_mask == 0 \
- && qt_alt_mask != mask \
- && qt_super_mask != mask \
- && qt_hyper_mask != mask \
- && (sym == XK_Meta_L || sym == XK_Meta_R)) { \
- qt_meta_mask = mask; \
- } \
- if (qt_super_mask == 0 \
- && qt_alt_mask != mask \
- && qt_meta_mask != mask \
- && qt_hyper_mask != mask \
- && (sym == XK_Super_L || sym == XK_Super_R)) { \
- qt_super_mask = mask; \
- } \
- if (qt_hyper_mask == 0 \
- && qt_alt_mask != mask \
- && qt_meta_mask != mask \
- && qt_super_mask != mask \
- && (sym == XK_Hyper_L || sym == XK_Hyper_R)) { \
- qt_hyper_mask = mask; \
- } \
- if (qt_mode_switch_mask == 0 \
- && qt_alt_mask != mask \
- && qt_meta_mask != mask \
- && qt_super_mask != mask \
- && qt_hyper_mask != mask \
- && sym == XK_Mode_switch) { \
- qt_mode_switch_mask = mask; \
- } \
- if (qt_num_lock_mask == 0 \
- && sym == XK_Num_Lock) { \
- qt_num_lock_mask = mask; \
- } \
- } while(false)
-
-// qt_XTranslateKey() is based on _XTranslateKey() taken from:
-
-/* $Xorg: KeyBind.c,v 1.4 2001/02/09 02:03:34 xorgcvs Exp $ */
-
-/*
-
-Copyright 1985, 1987, 1998 The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall not be
-used in advertising or otherwise to promote the sale, use or other dealings
-in this Software without prior written authorization from The Open Group.
-
-*/
-static int
-qt_XTranslateKey(register QXCoreDesc *dpy,
- KeyCode keycode,
- register unsigned int modifiers,
- unsigned int *modifiers_return,
- KeySym *keysym_return)
-{
- int per;
- register KeySym *syms;
- KeySym sym, lsym, usym;
-
- if (! dpy->keysyms)
- return 0;
- *modifiers_return = ((ShiftMask|LockMask)
- | dpy->mode_switch | dpy->num_lock);
- if (((int)keycode < dpy->min_keycode) || ((int)keycode > dpy->max_keycode))
- {
- *keysym_return = NoSymbol;
- return 1;
- }
- per = dpy->keysyms_per_keycode;
- syms = &dpy->keysyms[(keycode - dpy->min_keycode) * per];
- while ((per > 2) && (syms[per - 1] == NoSymbol))
- per--;
- if ((per > 2) && (modifiers & dpy->mode_switch)) {
- syms += 2;
- per -= 2;
- }
- if ((modifiers & dpy->num_lock) &&
- (per > 1 && (IsKeypadKey(syms[1]) || IsPrivateKeypadKey(syms[1])))) {
- if ((modifiers & ShiftMask) ||
- ((modifiers & LockMask) && (dpy->lock_meaning == XK_Shift_Lock)))
- *keysym_return = syms[0];
- else
- *keysym_return = syms[1];
- } else if (!(modifiers & ShiftMask) &&
- (!(modifiers & LockMask) || (dpy->lock_meaning == NoSymbol))) {
- if ((per == 1) || (syms[1] == NoSymbol))
- XConvertCase(syms[0], keysym_return, &usym);
- else
- *keysym_return = syms[0];
- } else if (!(modifiers & LockMask) ||
- (dpy->lock_meaning != XK_Caps_Lock)) {
- if ((per == 1) || ((usym = syms[1]) == NoSymbol))
- XConvertCase(syms[0], &lsym, &usym);
- *keysym_return = usym;
- } else {
- if ((per == 1) || ((sym = syms[1]) == NoSymbol))
- sym = syms[0];
- XConvertCase(sym, &lsym, &usym);
- if (!(modifiers & ShiftMask) && (sym != syms[0]) &&
- ((sym != usym) || (lsym == usym)))
- XConvertCase(syms[0], &lsym, &usym);
- *keysym_return = usym;
- }
- if (*keysym_return == XK_VoidSymbol)
- *keysym_return = NoSymbol;
- return 1;
-}
-
-
-
-
-QKeyMapperPrivate::QKeyMapperPrivate()
- : keyboardInputDirection(Qt::LeftToRight), xkb_currentGroup(0)
-{
- memset(&coreDesc, 0, sizeof(coreDesc));
-
-#ifndef QT_NO_XKB
- if (X11->use_xkb) {
- // get the current group
- XkbStateRec xkbState;
- if (XkbGetState(X11->display, XkbUseCoreKbd, &xkbState) == Success)
- xkb_currentGroup = xkbState.group;
- }
-#endif
-}
-
-QKeyMapperPrivate::~QKeyMapperPrivate()
-{
- if (coreDesc.keysyms)
- XFree(coreDesc.keysyms);
-}
-
-QList<int> QKeyMapperPrivate::possibleKeys(QKeyEvent *event)
-{
-#ifndef QT_NO_XKB
- if (X11->use_xkb)
- return possibleKeysXKB(event);
-#endif
- return possibleKeysCore(event);
-}
-
-enum { MaxBits = sizeof(uint) * 8 };
-static QString translateKeySym(KeySym keysym, uint xmodifiers,
- int &code, Qt::KeyboardModifiers &modifiers,
- QByteArray &chars, int &count);
-
-QList<int> QKeyMapperPrivate::possibleKeysXKB(QKeyEvent *event)
-{
-#ifndef QT_NO_XKB
- const int xkeycode = event->nativeScanCode();
- const uint xmodifiers = event->nativeModifiers();
-
- // first, translate key only using lock modifiers (there are no Qt equivalents for these, so we must
- // always use them when determining the baseKeySym)
- KeySym baseKeySym;
- uint consumedModifiers;
- if (!XkbLookupKeySym(X11->display, xkeycode, (xmodifiers & (LockMask | qt_num_lock_mask)),
- &consumedModifiers, &baseKeySym))
- return QList<int>();
-
- QList<int> result;
-
- // translate sym -> code
- Qt::KeyboardModifiers baseModifiers = 0;
- int baseCode = -1;
- QByteArray chars;
- int count = 0;
- QString text = translateKeySym(baseKeySym, xmodifiers, baseCode, baseModifiers, chars, count);
- if (baseCode == -1) {
- if (text.isEmpty())
- return QList<int>();
- baseCode = text.at(0).unicode();
- }
-
- if (baseCode && baseCode < 0xfffe)
- baseCode = QChar(baseCode).toUpper().unicode();
- result += (baseCode | baseModifiers);
-
- int pos1Bits[MaxBits];
- int num1Bits = 0;
-
- for (int i = 0; i < MaxBits; ++i) {
- if (consumedModifiers & (1 << i))
- pos1Bits[num1Bits++] = i;
- }
-
- const int numPerms = (1 << num1Bits);
-
- // translate the key again using each permutation of consumedModifiers
- for (int i = 1; i < numPerms; ++i) {
- uint val = 0;
- for (int j = 0; j < num1Bits; ++j) {
- if (i & (1 << j))
- val |= (1 << pos1Bits[j]);
- }
-
- if ((xmodifiers & val) != val)
- continue;
-
- KeySym sym;
- uint mods;
- if (!XkbLookupKeySym(X11->display, xkeycode, val, &mods, &sym))
- continue;
-
- // translate sym -> code
- Qt::KeyboardModifiers modifiers = 0;
- int code = -1;
- chars.clear();
- count = 0;
- // mask out the modifiers needed to translate keycode
- text = translateKeySym(sym, xmodifiers & ~val, code, modifiers, chars, count);
- if (code == -1) {
- if (text.isEmpty())
- continue;
- code = text.at(0).unicode();
- }
-
- if (code && code < 0xfffe)
- code = QChar(code).toUpper().unicode();
-
- if (code == Qt::Key_Tab && (baseModifiers & Qt::ShiftModifier)) {
- // map shift+tab to shift+backtab
- code = Qt::Key_Backtab;
- text = QString();
- }
-
- if (code == baseCode)
- continue;
-
- result += (code | modifiers);
- }
-
-#if 0
- qDebug() << "possibleKeysXKB()" << hex << result;
-#endif
- return result;
-#else
- Q_UNUSED(event);
- return QList<int>();
-#endif // QT_NO_XKB
-}
-
-QList<int> QKeyMapperPrivate::possibleKeysCore(QKeyEvent *event)
-{
- const int xkeycode = event->nativeScanCode();
- const uint xmodifiers = event->nativeModifiers();
-
- // first, translate key only using lock modifiers (there are no Qt equivalents for these, so we must
- // always use them when determining the baseKeySym)
- KeySym baseKeySym;
- uint consumedModifiers;
- if (!qt_XTranslateKey(&coreDesc, xkeycode, (xmodifiers & (LockMask | qt_num_lock_mask)),
- &consumedModifiers, &baseKeySym))
- return QList<int>();
-
- QList<int> result;
-
- // translate sym -> code
- Qt::KeyboardModifiers baseModifiers = 0;
- int baseCode = -1;
- QByteArray chars;
- int count = 0;
- QString text = translateKeySym(baseKeySym, xmodifiers, baseCode, baseModifiers, chars, count);
- if (baseCode == -1) {
- if (text.isEmpty())
- return QList<int>();
- baseCode = text.at(0).unicode();
- }
-
- if (baseCode && baseCode < 0xfffe)
- baseCode = QChar(baseCode).toUpper().unicode();
- result += (baseCode | baseModifiers);
-
- int pos1Bits[MaxBits];
- int num1Bits = 0;
-
- for (int i = 0; i < MaxBits; ++i) {
- if (consumedModifiers & (1 << i))
- pos1Bits[num1Bits++] = i;
- }
-
- const int numPerms = (1 << num1Bits);
-
- // translate the key again using each permutation of consumedModifiers
- for (int i = 1; i < numPerms; ++i) {
- uint val = 0;
- for (int j = 0; j < num1Bits; ++j) {
- if (i & (1 << j))
- val |= (1 << pos1Bits[j]);
- }
-
- if ((xmodifiers & val) != val)
- continue;
-
- KeySym sym;
- uint mods;
- if (!qt_XTranslateKey(&coreDesc, xkeycode, val, &mods, &sym))
- continue;
-
- // translate sym -> code
- Qt::KeyboardModifiers modifiers = 0;
- int code = -1;
- chars.clear();
- count = 0;
- // mask out the modifiers needed to translate keycode
- text = translateKeySym(sym, xmodifiers & ~val, code, modifiers, chars, count);
- if (code == -1) {
- if (text.isEmpty())
- continue;
- code = text.at(0).unicode();
- }
-
- if (code && code < 0xfffe)
- code = QChar(code).toUpper().unicode();
-
- if (code == Qt::Key_Tab && (baseModifiers & Qt::ShiftModifier)) {
- // map shift+tab to shift+backtab
- code = Qt::Key_Backtab;
- text = QString();
- }
-
- if (code == baseCode)
- continue;
-
- result += (code | modifiers);
- }
-
-#if 0
- qDebug() << "possibleKeysCore()" << hex << result;
-#endif
- return result;
-}
-
-// for parsing the _XKB_RULES_NAMES property
-enum {
- RulesFileIndex = 0,
- ModelIndex = 1,
- LayoutIndex = 2,
- VariantIndex = 3,
- OptionsIndex = 4
-};
-
-void QKeyMapperPrivate::clearMappings()
-{
-#ifndef QT_NO_XKB
- if (X11->use_xkb) {
- // try to determine the layout name and input direction by reading the _XKB_RULES_NAMES property off
- // the root window
- QByteArray layoutName;
- QByteArray variantName;
-
- Atom type = XNone;
- int format = 0;
- ulong nitems = 0;
- ulong bytesAfter = 0;
- uchar *data = 0;
- if (XGetWindowProperty(X11->display, RootWindow(X11->display, 0), ATOM(_XKB_RULES_NAMES), 0, 1024,
- false, XA_STRING, &type, &format, &nitems, &bytesAfter, &data) == Success
- && type == XA_STRING && format == 8 && nitems > 2) {
- /*
- index 0 == rules file name
- index 1 == model name
- index 2 == layout name
- index 3 == variant name
- index 4 == options
- */
- char *names[5] = { 0, 0, 0, 0, 0 };
- char *p = reinterpret_cast<char *>(data), *end = p + nitems;
- int i = 0;
- do {
- names[i++] = p;
- p += qstrlen(p) + 1;
- } while (p < end);
-
- // the layout names and variants are saved in the _XKB_RULES_NAMES property as a comma separated list
- QList<QByteArray> layoutNames = QByteArray::fromRawData(names[2], qstrlen(names[2])).split(',');
- if (uint(xkb_currentGroup) < uint(layoutNames.count()))
- layoutName = layoutNames.at(xkb_currentGroup);
- QList<QByteArray> variantNames = QByteArray::fromRawData(names[3], qstrlen(names[3])).split(',');
- if (uint(xkb_currentGroup) < uint(variantNames.count()))
- variantName = variantNames.at(xkb_currentGroup);
- }
-
- // ### ???
- // if (keyboardLayoutName.isEmpty())
- // qWarning("Qt: unable to determine keyboard layout, please talk to qt-bugs@trolltech.com"); ?
-
- keyboardInputLocale = q_getKeyboardLocale(layoutName, variantName);
- keyboardInputDirection = keyboardInputLocale.textDirection();
-
-#if 0
- qDebug() << "keyboard input locale ="
- << keyboardInputLocale.name()
- << "direction ="
- << keyboardInputDirection;
-#endif
- if (data)
- XFree(data);
- } else
-#endif // QT_NO_XKB
- {
- if (coreDesc.keysyms)
- XFree(coreDesc.keysyms);
-
- coreDesc.min_keycode = 8;
- coreDesc.max_keycode = 255;
- XDisplayKeycodes(X11->display, &coreDesc.min_keycode, &coreDesc.max_keycode);
-
- coreDesc.keysyms_per_keycode = 0;
- coreDesc.keysyms = XGetKeyboardMapping(X11->display,
- coreDesc.min_keycode,
- coreDesc.max_keycode - coreDesc.min_keycode + 1,
- &coreDesc.keysyms_per_keycode);
-
-#if 0
- qDebug() << "min_keycode =" << coreDesc.min_keycode;
- qDebug() << "max_keycode =" << coreDesc.max_keycode;
- qDebug() << "keysyms_per_keycode =" << coreDesc.keysyms_per_keycode;
- qDebug() << "keysyms =" << coreDesc.keysyms;
-#endif
-
- // ### cannot get/guess the locale with the core protocol
- keyboardInputLocale = QLocale::c();
- // ### could examine group 0 for RTL keys
- keyboardInputDirection = Qt::LeftToRight;
- }
-
- qt_alt_mask = 0;
- qt_meta_mask = 0;
- qt_super_mask = 0;
- qt_hyper_mask = 0;
- qt_mode_switch_mask = 0;
-
- // look at the modifier mapping, and get the correct masks for alt, meta, super, hyper, and mode_switch
-#ifndef QT_NO_XKB
- if (X11->use_xkb) {
- XkbDescPtr xkbDesc = XkbGetMap(X11->display, XkbAllClientInfoMask, XkbUseCoreKbd);
- for (int i = xkbDesc->min_key_code; i < xkbDesc->max_key_code; ++i) {
- const uint mask = xkbDesc->map->modmap ? xkbDesc->map->modmap[i] : 0;
- if (mask == 0) {
- // key is not bound to a modifier
- continue;
- }
-
- for (int j = 0; j < XkbKeyGroupsWidth(xkbDesc, i); ++j) {
- KeySym keySym = XkbKeySym(xkbDesc, i, j);
- if (keySym == NoSymbol)
- continue;
- SETMASK(keySym, mask);
- }
- }
- XkbFreeKeyboard(xkbDesc, XkbAllComponentsMask, true);
- } else
-#endif // QT_NO_XKB
- {
- coreDesc.lock_meaning = NoSymbol;
-
- XModifierKeymap *map = XGetModifierMapping(X11->display);
-
- if (map) {
- int i, maskIndex = 0, mapIndex = 0;
- for (maskIndex = 0; maskIndex < 8; maskIndex++) {
- for (i = 0; i < map->max_keypermod; i++) {
- if (map->modifiermap[mapIndex]) {
- KeySym sym;
- int x = 0;
- do {
- sym = XKeycodeToKeysym(X11->display, map->modifiermap[mapIndex], x++);
- } while (sym == NoSymbol && x < coreDesc.keysyms_per_keycode);
- const uchar mask = 1 << maskIndex;
- SETMASK(sym, mask);
- }
- mapIndex++;
- }
- }
-
- // determine the meaning of the Lock modifier
- for (i = 0; i < map->max_keypermod; ++i) {
- for (int x = 0; x < coreDesc.keysyms_per_keycode; ++x) {
- KeySym sym = XKeycodeToKeysym(X11->display, map->modifiermap[LockMapIndex], x);
- if (sym == XK_Caps_Lock || sym == XK_ISO_Lock) {
- coreDesc.lock_meaning = XK_Caps_Lock;
- break;
- } else if (sym == XK_Shift_Lock) {
- coreDesc.lock_meaning = XK_Shift_Lock;
- }
- }
- }
-
- XFreeModifiermap(map);
- }
-
- // for qt_XTranslateKey()
- coreDesc.num_lock = qt_num_lock_mask;
- coreDesc.mode_switch = qt_mode_switch_mask;
-
-#if 0
- qDebug() << "lock_meaning =" << coreDesc.lock_meaning;
- qDebug() << "num_lock =" << coreDesc.num_lock;
- qDebug() << "mode_switch =" << coreDesc.mode_switch;
-#endif
- }
-
- // set default modifier masks if needed
- if( qt_alt_mask == 0 )
- qt_alt_mask = Mod1Mask;
- if( qt_meta_mask == 0 )
- qt_meta_mask = Mod4Mask;
-
- // if we don't have a meta key (or it's hidden behind alt), use super or hyper to generate
- // Qt::Key_Meta and Qt::MetaModifier, since most newer XFree86/Xorg installations map the Windows
- // key to Super
- if (qt_meta_mask == 0 || qt_meta_mask == qt_alt_mask) {
- // no meta keys... s,meta,super,
- qt_meta_mask = qt_super_mask;
- if (qt_meta_mask == 0 || qt_meta_mask == qt_alt_mask) {
- // no super keys either? guess we'll use hyper then
- qt_meta_mask = qt_hyper_mask;
- }
- }
-
-#if 0
- qDebug() << "qt_alt_mask =" << hex << qt_alt_mask;
- qDebug() << "qt_meta_mask =" << hex << qt_meta_mask;
- qDebug() << "qt_super_mask =" << hex << qt_super_mask;
- qDebug() << "qt_hyper_mask =" << hex << qt_hyper_mask;
- qDebug() << "qt_mode_switch_mask =" << hex << qt_mode_switch_mask;
- qDebug() << "qt_num_lock_mask =" << hex << qt_num_lock_mask;
-#endif
-}
-
-extern bool qt_sm_blockUserInput;
-
-//
-// Keyboard event translation
-//
-
-#ifndef XK_ISO_Left_Tab
-#define XK_ISO_Left_Tab 0xFE20
-#endif
-
-#ifndef XK_dead_hook
-#define XK_dead_hook 0xFE61
-#endif
-
-#ifndef XK_dead_horn
-#define XK_dead_horn 0xFE62
-#endif
-
-#ifndef XK_Codeinput
-#define XK_Codeinput 0xFF37
-#endif
-
-#ifndef XK_Kanji_Bangou
-#define XK_Kanji_Bangou 0xFF37 /* same as codeinput */
-#endif
-
-// Fix old X libraries
-#ifndef XK_KP_Home
-#define XK_KP_Home 0xFF95
-#endif
-#ifndef XK_KP_Left
-#define XK_KP_Left 0xFF96
-#endif
-#ifndef XK_KP_Up
-#define XK_KP_Up 0xFF97
-#endif
-#ifndef XK_KP_Right
-#define XK_KP_Right 0xFF98
-#endif
-#ifndef XK_KP_Down
-#define XK_KP_Down 0xFF99
-#endif
-#ifndef XK_KP_Prior
-#define XK_KP_Prior 0xFF9A
-#endif
-#ifndef XK_KP_Next
-#define XK_KP_Next 0xFF9B
-#endif
-#ifndef XK_KP_End
-#define XK_KP_End 0xFF9C
-#endif
-#ifndef XK_KP_Insert
-#define XK_KP_Insert 0xFF9E
-#endif
-#ifndef XK_KP_Delete
-#define XK_KP_Delete 0xFF9F
-#endif
-
-// the next lines are taken on 10/2009 from X.org (X11/XF86keysym.h), defining some special
-// multimedia keys. They are included here as not every system has them.
-#define XF86XK_MonBrightnessUp 0x1008FF02
-#define XF86XK_MonBrightnessDown 0x1008FF03
-#define XF86XK_KbdLightOnOff 0x1008FF04
-#define XF86XK_KbdBrightnessUp 0x1008FF05
-#define XF86XK_KbdBrightnessDown 0x1008FF06
-#define XF86XK_Standby 0x1008FF10
-#define XF86XK_AudioLowerVolume 0x1008FF11
-#define XF86XK_AudioMute 0x1008FF12
-#define XF86XK_AudioRaiseVolume 0x1008FF13
-#define XF86XK_AudioPlay 0x1008FF14
-#define XF86XK_AudioStop 0x1008FF15
-#define XF86XK_AudioPrev 0x1008FF16
-#define XF86XK_AudioNext 0x1008FF17
-#define XF86XK_HomePage 0x1008FF18
-#define XF86XK_Mail 0x1008FF19
-#define XF86XK_Start 0x1008FF1A
-#define XF86XK_Search 0x1008FF1B
-#define XF86XK_AudioRecord 0x1008FF1C
-#define XF86XK_Calculator 0x1008FF1D
-#define XF86XK_Memo 0x1008FF1E
-#define XF86XK_ToDoList 0x1008FF1F
-#define XF86XK_Calendar 0x1008FF20
-#define XF86XK_PowerDown 0x1008FF21
-#define XF86XK_ContrastAdjust 0x1008FF22
-#define XF86XK_Back 0x1008FF26
-#define XF86XK_Forward 0x1008FF27
-#define XF86XK_Stop 0x1008FF28
-#define XF86XK_Refresh 0x1008FF29
-#define XF86XK_PowerOff 0x1008FF2A
-#define XF86XK_WakeUp 0x1008FF2B
-#define XF86XK_Eject 0x1008FF2C
-#define XF86XK_ScreenSaver 0x1008FF2D
-#define XF86XK_WWW 0x1008FF2E
-#define XF86XK_Sleep 0x1008FF2F
-#define XF86XK_Favorites 0x1008FF30
-#define XF86XK_AudioPause 0x1008FF31
-#define XF86XK_AudioMedia 0x1008FF32
-#define XF86XK_MyComputer 0x1008FF33
-#define XF86XK_LightBulb 0x1008FF35
-#define XF86XK_Shop 0x1008FF36
-#define XF86XK_History 0x1008FF37
-#define XF86XK_OpenURL 0x1008FF38
-#define XF86XK_AddFavorite 0x1008FF39
-#define XF86XK_HotLinks 0x1008FF3A
-#define XF86XK_BrightnessAdjust 0x1008FF3B
-#define XF86XK_Finance 0x1008FF3C
-#define XF86XK_Community 0x1008FF3D
-#define XF86XK_AudioRewind 0x1008FF3E
-#define XF86XK_BackForward 0x1008FF3F
-#define XF86XK_Launch0 0x1008FF40
-#define XF86XK_Launch1 0x1008FF41
-#define XF86XK_Launch2 0x1008FF42
-#define XF86XK_Launch3 0x1008FF43
-#define XF86XK_Launch4 0x1008FF44
-#define XF86XK_Launch5 0x1008FF45
-#define XF86XK_Launch6 0x1008FF46
-#define XF86XK_Launch7 0x1008FF47
-#define XF86XK_Launch8 0x1008FF48
-#define XF86XK_Launch9 0x1008FF49
-#define XF86XK_LaunchA 0x1008FF4A
-#define XF86XK_LaunchB 0x1008FF4B
-#define XF86XK_LaunchC 0x1008FF4C
-#define XF86XK_LaunchD 0x1008FF4D
-#define XF86XK_LaunchE 0x1008FF4E
-#define XF86XK_LaunchF 0x1008FF4F
-#define XF86XK_ApplicationLeft 0x1008FF50
-#define XF86XK_ApplicationRight 0x1008FF51
-#define XF86XK_Book 0x1008FF52
-#define XF86XK_CD 0x1008FF53
-#define XF86XK_Calculater 0x1008FF54
-#define XF86XK_Clear 0x1008FF55
-#define XF86XK_ClearGrab 0x1008FE21
-#define XF86XK_Close 0x1008FF56
-#define XF86XK_Copy 0x1008FF57
-#define XF86XK_Cut 0x1008FF58
-#define XF86XK_Display 0x1008FF59
-#define XF86XK_DOS 0x1008FF5A
-#define XF86XK_Documents 0x1008FF5B
-#define XF86XK_Excel 0x1008FF5C
-#define XF86XK_Explorer 0x1008FF5D
-#define XF86XK_Game 0x1008FF5E
-#define XF86XK_Go 0x1008FF5F
-#define XF86XK_iTouch 0x1008FF60
-#define XF86XK_LogOff 0x1008FF61
-#define XF86XK_Market 0x1008FF62
-#define XF86XK_Meeting 0x1008FF63
-#define XF86XK_MenuKB 0x1008FF65
-#define XF86XK_MenuPB 0x1008FF66
-#define XF86XK_MySites 0x1008FF67
-#define XF86XK_News 0x1008FF69
-#define XF86XK_OfficeHome 0x1008FF6A
-#define XF86XK_Option 0x1008FF6C
-#define XF86XK_Paste 0x1008FF6D
-#define XF86XK_Phone 0x1008FF6E
-#define XF86XK_Reply 0x1008FF72
-#define XF86XK_Reload 0x1008FF73
-#define XF86XK_RotateWindows 0x1008FF74
-#define XF86XK_RotationPB 0x1008FF75
-#define XF86XK_RotationKB 0x1008FF76
-#define XF86XK_Save 0x1008FF77
-#define XF86XK_Send 0x1008FF7B
-#define XF86XK_Spell 0x1008FF7C
-#define XF86XK_SplitScreen 0x1008FF7D
-#define XF86XK_Support 0x1008FF7E
-#define XF86XK_TaskPane 0x1008FF7F
-#define XF86XK_Terminal 0x1008FF80
-#define XF86XK_Tools 0x1008FF81
-#define XF86XK_Travel 0x1008FF82
-#define XF86XK_Video 0x1008FF87
-#define XF86XK_Word 0x1008FF89
-#define XF86XK_Xfer 0x1008FF8A
-#define XF86XK_ZoomIn 0x1008FF8B
-#define XF86XK_ZoomOut 0x1008FF8C
-#define XF86XK_Away 0x1008FF8D
-#define XF86XK_Messenger 0x1008FF8E
-#define XF86XK_WebCam 0x1008FF8F
-#define XF86XK_MailForward 0x1008FF90
-#define XF86XK_Pictures 0x1008FF91
-#define XF86XK_Music 0x1008FF92
-#define XF86XK_Battery 0x1008FF93
-#define XF86XK_Bluetooth 0x1008FF94
-#define XF86XK_WLAN 0x1008FF95
-#define XF86XK_UWB 0x1008FF96
-#define XF86XK_AudioForward 0x1008FF97
-#define XF86XK_AudioRepeat 0x1008FF98
-#define XF86XK_AudioRandomPlay 0x1008FF99
-#define XF86XK_Subtitle 0x1008FF9A
-#define XF86XK_AudioCycleTrack 0x1008FF9B
-#define XF86XK_Time 0x1008FF9F
-#define XF86XK_Select 0x1008FFA0
-#define XF86XK_View 0x1008FFA1
-#define XF86XK_TopMenu 0x1008FFA2
-#define XF86XK_Suspend 0x1008FFA7
-#define XF86XK_Hibernate 0x1008FFA8
-
-
-// end of XF86keysyms.h
-
-// Special keys used by Qtopia, mapped into the X11 private keypad range.
-#define QTOPIAXK_Select 0x11000601
-#define QTOPIAXK_Yes 0x11000602
-#define QTOPIAXK_No 0x11000603
-#define QTOPIAXK_Cancel 0x11000604
-#define QTOPIAXK_Printer 0x11000605
-#define QTOPIAXK_Execute 0x11000606
-#define QTOPIAXK_Sleep 0x11000607
-#define QTOPIAXK_Play 0x11000608
-#define QTOPIAXK_Zoom 0x11000609
-#define QTOPIAXK_Context1 0x1100060A
-#define QTOPIAXK_Context2 0x1100060B
-#define QTOPIAXK_Context3 0x1100060C
-#define QTOPIAXK_Context4 0x1100060D
-#define QTOPIAXK_Call 0x1100060E
-#define QTOPIAXK_Hangup 0x1100060F
-#define QTOPIAXK_Flip 0x11000610
-
-// keyboard mapping table
-static const unsigned int KeyTbl[] = {
-
- // misc keys
-
- XK_Escape, Qt::Key_Escape,
- XK_Tab, Qt::Key_Tab,
- XK_ISO_Left_Tab, Qt::Key_Backtab,
- XK_BackSpace, Qt::Key_Backspace,
- XK_Return, Qt::Key_Return,
- XK_Insert, Qt::Key_Insert,
- XK_Delete, Qt::Key_Delete,
- XK_Clear, Qt::Key_Delete,
- XK_Pause, Qt::Key_Pause,
- XK_Print, Qt::Key_Print,
- 0x1005FF60, Qt::Key_SysReq, // hardcoded Sun SysReq
- 0x1007ff00, Qt::Key_SysReq, // hardcoded X386 SysReq
-
- // cursor movement
-
- XK_Home, Qt::Key_Home,
- XK_End, Qt::Key_End,
- XK_Left, Qt::Key_Left,
- XK_Up, Qt::Key_Up,
- XK_Right, Qt::Key_Right,
- XK_Down, Qt::Key_Down,
- XK_Prior, Qt::Key_PageUp,
- XK_Next, Qt::Key_PageDown,
-
- // modifiers
-
- XK_Shift_L, Qt::Key_Shift,
- XK_Shift_R, Qt::Key_Shift,
- XK_Shift_Lock, Qt::Key_Shift,
- XK_Control_L, Qt::Key_Control,
- XK_Control_R, Qt::Key_Control,
- XK_Meta_L, Qt::Key_Meta,
- XK_Meta_R, Qt::Key_Meta,
- XK_Alt_L, Qt::Key_Alt,
- XK_Alt_R, Qt::Key_Alt,
- XK_Caps_Lock, Qt::Key_CapsLock,
- XK_Num_Lock, Qt::Key_NumLock,
- XK_Scroll_Lock, Qt::Key_ScrollLock,
- XK_Super_L, Qt::Key_Super_L,
- XK_Super_R, Qt::Key_Super_R,
- XK_Menu, Qt::Key_Menu,
- XK_Hyper_L, Qt::Key_Hyper_L,
- XK_Hyper_R, Qt::Key_Hyper_R,
- XK_Help, Qt::Key_Help,
- 0x1000FF74, Qt::Key_Backtab, // hardcoded HP backtab
- 0x1005FF10, Qt::Key_F11, // hardcoded Sun F36 (labeled F11)
- 0x1005FF11, Qt::Key_F12, // hardcoded Sun F37 (labeled F12)
-
- // numeric and function keypad keys
-
- XK_KP_Space, Qt::Key_Space,
- XK_KP_Tab, Qt::Key_Tab,
- XK_KP_Enter, Qt::Key_Enter,
- //XK_KP_F1, Qt::Key_F1,
- //XK_KP_F2, Qt::Key_F2,
- //XK_KP_F3, Qt::Key_F3,
- //XK_KP_F4, Qt::Key_F4,
- XK_KP_Home, Qt::Key_Home,
- XK_KP_Left, Qt::Key_Left,
- XK_KP_Up, Qt::Key_Up,
- XK_KP_Right, Qt::Key_Right,
- XK_KP_Down, Qt::Key_Down,
- XK_KP_Prior, Qt::Key_PageUp,
- XK_KP_Next, Qt::Key_PageDown,
- XK_KP_End, Qt::Key_End,
- XK_KP_Begin, Qt::Key_Clear,
- XK_KP_Insert, Qt::Key_Insert,
- XK_KP_Delete, Qt::Key_Delete,
- XK_KP_Equal, Qt::Key_Equal,
- XK_KP_Multiply, Qt::Key_Asterisk,
- XK_KP_Add, Qt::Key_Plus,
- XK_KP_Separator, Qt::Key_Comma,
- XK_KP_Subtract, Qt::Key_Minus,
- XK_KP_Decimal, Qt::Key_Period,
- XK_KP_Divide, Qt::Key_Slash,
-
- // International input method support keys
-
- // International & multi-key character composition
- XK_ISO_Level3_Shift, Qt::Key_AltGr,
- XK_Multi_key, Qt::Key_Multi_key,
- XK_Codeinput, Qt::Key_Codeinput,
- XK_SingleCandidate, Qt::Key_SingleCandidate,
- XK_MultipleCandidate, Qt::Key_MultipleCandidate,
- XK_PreviousCandidate, Qt::Key_PreviousCandidate,
-
- // Misc Functions
- XK_Mode_switch, Qt::Key_Mode_switch,
- XK_script_switch, Qt::Key_Mode_switch,
-
- // Japanese keyboard support
- XK_Kanji, Qt::Key_Kanji,
- XK_Muhenkan, Qt::Key_Muhenkan,
- //XK_Henkan_Mode, Qt::Key_Henkan_Mode,
- XK_Henkan_Mode, Qt::Key_Henkan,
- XK_Henkan, Qt::Key_Henkan,
- XK_Romaji, Qt::Key_Romaji,
- XK_Hiragana, Qt::Key_Hiragana,
- XK_Katakana, Qt::Key_Katakana,
- XK_Hiragana_Katakana, Qt::Key_Hiragana_Katakana,
- XK_Zenkaku, Qt::Key_Zenkaku,
- XK_Hankaku, Qt::Key_Hankaku,
- XK_Zenkaku_Hankaku, Qt::Key_Zenkaku_Hankaku,
- XK_Touroku, Qt::Key_Touroku,
- XK_Massyo, Qt::Key_Massyo,
- XK_Kana_Lock, Qt::Key_Kana_Lock,
- XK_Kana_Shift, Qt::Key_Kana_Shift,
- XK_Eisu_Shift, Qt::Key_Eisu_Shift,
- XK_Eisu_toggle, Qt::Key_Eisu_toggle,
- //XK_Kanji_Bangou, Qt::Key_Kanji_Bangou,
- //XK_Zen_Koho, Qt::Key_Zen_Koho,
- //XK_Mae_Koho, Qt::Key_Mae_Koho,
- XK_Kanji_Bangou, Qt::Key_Codeinput,
- XK_Zen_Koho, Qt::Key_MultipleCandidate,
- XK_Mae_Koho, Qt::Key_PreviousCandidate,
-
-#ifdef XK_KOREAN
- // Korean keyboard support
- XK_Hangul, Qt::Key_Hangul,
- XK_Hangul_Start, Qt::Key_Hangul_Start,
- XK_Hangul_End, Qt::Key_Hangul_End,
- XK_Hangul_Hanja, Qt::Key_Hangul_Hanja,
- XK_Hangul_Jamo, Qt::Key_Hangul_Jamo,
- XK_Hangul_Romaja, Qt::Key_Hangul_Romaja,
- //XK_Hangul_Codeinput, Qt::Key_Hangul_Codeinput,
- XK_Hangul_Codeinput, Qt::Key_Codeinput,
- XK_Hangul_Jeonja, Qt::Key_Hangul_Jeonja,
- XK_Hangul_Banja, Qt::Key_Hangul_Banja,
- XK_Hangul_PreHanja, Qt::Key_Hangul_PreHanja,
- XK_Hangul_PostHanja, Qt::Key_Hangul_PostHanja,
- //XK_Hangul_SingleCandidate,Qt::Key_Hangul_SingleCandidate,
- //XK_Hangul_MultipleCandidate,Qt::Key_Hangul_MultipleCandidate,
- //XK_Hangul_PreviousCandidate,Qt::Key_Hangul_PreviousCandidate,
- XK_Hangul_SingleCandidate, Qt::Key_SingleCandidate,
- XK_Hangul_MultipleCandidate,Qt::Key_MultipleCandidate,
- XK_Hangul_PreviousCandidate,Qt::Key_PreviousCandidate,
- XK_Hangul_Special, Qt::Key_Hangul_Special,
- //XK_Hangul_switch, Qt::Key_Hangul_switch,
- XK_Hangul_switch, Qt::Key_Mode_switch,
-#endif // XK_KOREAN
-
- // dead keys
- XK_dead_grave, Qt::Key_Dead_Grave,
- XK_dead_acute, Qt::Key_Dead_Acute,
- XK_dead_circumflex, Qt::Key_Dead_Circumflex,
- XK_dead_tilde, Qt::Key_Dead_Tilde,
- XK_dead_macron, Qt::Key_Dead_Macron,
- XK_dead_breve, Qt::Key_Dead_Breve,
- XK_dead_abovedot, Qt::Key_Dead_Abovedot,
- XK_dead_diaeresis, Qt::Key_Dead_Diaeresis,
- XK_dead_abovering, Qt::Key_Dead_Abovering,
- XK_dead_doubleacute, Qt::Key_Dead_Doubleacute,
- XK_dead_caron, Qt::Key_Dead_Caron,
- XK_dead_cedilla, Qt::Key_Dead_Cedilla,
- XK_dead_ogonek, Qt::Key_Dead_Ogonek,
- XK_dead_iota, Qt::Key_Dead_Iota,
- XK_dead_voiced_sound, Qt::Key_Dead_Voiced_Sound,
- XK_dead_semivoiced_sound, Qt::Key_Dead_Semivoiced_Sound,
- XK_dead_belowdot, Qt::Key_Dead_Belowdot,
- XK_dead_hook, Qt::Key_Dead_Hook,
- XK_dead_horn, Qt::Key_Dead_Horn,
-
- // Special keys from X.org - This include multimedia keys,
- // wireless/bluetooth/uwb keys, special launcher keys, etc.
- XF86XK_Back, Qt::Key_Back,
- XF86XK_Forward, Qt::Key_Forward,
- XF86XK_Stop, Qt::Key_Stop,
- XF86XK_Refresh, Qt::Key_Refresh,
- XF86XK_Favorites, Qt::Key_Favorites,
- XF86XK_AudioMedia, Qt::Key_LaunchMedia,
- XF86XK_OpenURL, Qt::Key_OpenUrl,
- XF86XK_HomePage, Qt::Key_HomePage,
- XF86XK_Search, Qt::Key_Search,
- XF86XK_AudioLowerVolume, Qt::Key_VolumeDown,
- XF86XK_AudioMute, Qt::Key_VolumeMute,
- XF86XK_AudioRaiseVolume, Qt::Key_VolumeUp,
- XF86XK_AudioPlay, Qt::Key_MediaPlay,
- XF86XK_AudioStop, Qt::Key_MediaStop,
- XF86XK_AudioPrev, Qt::Key_MediaPrevious,
- XF86XK_AudioNext, Qt::Key_MediaNext,
- XF86XK_AudioRecord, Qt::Key_MediaRecord,
- XF86XK_Mail, Qt::Key_LaunchMail,
- XF86XK_MyComputer, Qt::Key_Launch0, // ### Qt 5: remap properly
- XF86XK_Calculator, Qt::Key_Launch1,
- XF86XK_Memo, Qt::Key_Memo,
- XF86XK_ToDoList, Qt::Key_ToDoList,
- XF86XK_Calendar, Qt::Key_Calendar,
- XF86XK_PowerDown, Qt::Key_PowerDown,
- XF86XK_ContrastAdjust, Qt::Key_ContrastAdjust,
- XF86XK_Standby, Qt::Key_Standby,
- XF86XK_MonBrightnessUp, Qt::Key_MonBrightnessUp,
- XF86XK_MonBrightnessDown, Qt::Key_MonBrightnessDown,
- XF86XK_KbdLightOnOff, Qt::Key_KeyboardLightOnOff,
- XF86XK_KbdBrightnessUp, Qt::Key_KeyboardBrightnessUp,
- XF86XK_KbdBrightnessDown, Qt::Key_KeyboardBrightnessDown,
- XF86XK_PowerOff, Qt::Key_PowerOff,
- XF86XK_WakeUp, Qt::Key_WakeUp,
- XF86XK_Eject, Qt::Key_Eject,
- XF86XK_ScreenSaver, Qt::Key_ScreenSaver,
- XF86XK_WWW, Qt::Key_WWW,
- XF86XK_Sleep, Qt::Key_Sleep,
- XF86XK_LightBulb, Qt::Key_LightBulb,
- XF86XK_Shop, Qt::Key_Shop,
- XF86XK_History, Qt::Key_History,
- XF86XK_AddFavorite, Qt::Key_AddFavorite,
- XF86XK_HotLinks, Qt::Key_HotLinks,
- XF86XK_BrightnessAdjust, Qt::Key_BrightnessAdjust,
- XF86XK_Finance, Qt::Key_Finance,
- XF86XK_Community, Qt::Key_Community,
- XF86XK_AudioRewind, Qt::Key_AudioRewind,
- XF86XK_BackForward, Qt::Key_BackForward,
- XF86XK_ApplicationLeft, Qt::Key_ApplicationLeft,
- XF86XK_ApplicationRight, Qt::Key_ApplicationRight,
- XF86XK_Book, Qt::Key_Book,
- XF86XK_CD, Qt::Key_CD,
- XF86XK_Calculater, Qt::Key_Calculator,
- XF86XK_Clear, Qt::Key_Clear,
- XF86XK_ClearGrab, Qt::Key_ClearGrab,
- XF86XK_Close, Qt::Key_Close,
- XF86XK_Copy, Qt::Key_Copy,
- XF86XK_Cut, Qt::Key_Cut,
- XF86XK_Display, Qt::Key_Display,
- XF86XK_DOS, Qt::Key_DOS,
- XF86XK_Documents, Qt::Key_Documents,
- XF86XK_Excel, Qt::Key_Excel,
- XF86XK_Explorer, Qt::Key_Explorer,
- XF86XK_Game, Qt::Key_Game,
- XF86XK_Go, Qt::Key_Go,
- XF86XK_iTouch, Qt::Key_iTouch,
- XF86XK_LogOff, Qt::Key_LogOff,
- XF86XK_Market, Qt::Key_Market,
- XF86XK_Meeting, Qt::Key_Meeting,
- XF86XK_MenuKB, Qt::Key_MenuKB,
- XF86XK_MenuPB, Qt::Key_MenuPB,
- XF86XK_MySites, Qt::Key_MySites,
- XF86XK_News, Qt::Key_News,
- XF86XK_OfficeHome, Qt::Key_OfficeHome,
- XF86XK_Option, Qt::Key_Option,
- XF86XK_Paste, Qt::Key_Paste,
- XF86XK_Phone, Qt::Key_Phone,
- XF86XK_Reply, Qt::Key_Reply,
- XF86XK_Reload, Qt::Key_Reload,
- XF86XK_RotateWindows, Qt::Key_RotateWindows,
- XF86XK_RotationPB, Qt::Key_RotationPB,
- XF86XK_RotationKB, Qt::Key_RotationKB,
- XF86XK_Save, Qt::Key_Save,
- XF86XK_Send, Qt::Key_Send,
- XF86XK_Spell, Qt::Key_Spell,
- XF86XK_SplitScreen, Qt::Key_SplitScreen,
- XF86XK_Support, Qt::Key_Support,
- XF86XK_TaskPane, Qt::Key_TaskPane,
- XF86XK_Terminal, Qt::Key_Terminal,
- XF86XK_Tools, Qt::Key_Tools,
- XF86XK_Travel, Qt::Key_Travel,
- XF86XK_Video, Qt::Key_Video,
- XF86XK_Word, Qt::Key_Word,
- XF86XK_Xfer, Qt::Key_Xfer,
- XF86XK_ZoomIn, Qt::Key_ZoomIn,
- XF86XK_ZoomOut, Qt::Key_ZoomOut,
- XF86XK_Away, Qt::Key_Away,
- XF86XK_Messenger, Qt::Key_Messenger,
- XF86XK_WebCam, Qt::Key_WebCam,
- XF86XK_MailForward, Qt::Key_MailForward,
- XF86XK_Pictures, Qt::Key_Pictures,
- XF86XK_Music, Qt::Key_Music,
- XF86XK_Battery, Qt::Key_Battery,
- XF86XK_Bluetooth, Qt::Key_Bluetooth,
- XF86XK_WLAN, Qt::Key_WLAN,
- XF86XK_UWB, Qt::Key_UWB,
- XF86XK_AudioForward, Qt::Key_AudioForward,
- XF86XK_AudioRepeat, Qt::Key_AudioRepeat,
- XF86XK_AudioRandomPlay, Qt::Key_AudioRandomPlay,
- XF86XK_Subtitle, Qt::Key_Subtitle,
- XF86XK_AudioCycleTrack, Qt::Key_AudioCycleTrack,
- XF86XK_Time, Qt::Key_Time,
- XF86XK_Select, Qt::Key_Select,
- XF86XK_View, Qt::Key_View,
- XF86XK_TopMenu, Qt::Key_TopMenu,
- XF86XK_Bluetooth, Qt::Key_Bluetooth,
- XF86XK_Suspend, Qt::Key_Suspend,
- XF86XK_Hibernate, Qt::Key_Hibernate,
- XF86XK_Launch0, Qt::Key_Launch2, // ### Qt 5: remap properly
- XF86XK_Launch1, Qt::Key_Launch3,
- XF86XK_Launch2, Qt::Key_Launch4,
- XF86XK_Launch3, Qt::Key_Launch5,
- XF86XK_Launch4, Qt::Key_Launch6,
- XF86XK_Launch5, Qt::Key_Launch7,
- XF86XK_Launch6, Qt::Key_Launch8,
- XF86XK_Launch7, Qt::Key_Launch9,
- XF86XK_Launch8, Qt::Key_LaunchA,
- XF86XK_Launch9, Qt::Key_LaunchB,
- XF86XK_LaunchA, Qt::Key_LaunchC,
- XF86XK_LaunchB, Qt::Key_LaunchD,
- XF86XK_LaunchC, Qt::Key_LaunchE,
- XF86XK_LaunchD, Qt::Key_LaunchF,
- XF86XK_LaunchE, Qt::Key_LaunchG,
- XF86XK_LaunchF, Qt::Key_LaunchH,
-
- // Qtopia keys
- QTOPIAXK_Select, Qt::Key_Select,
- QTOPIAXK_Yes, Qt::Key_Yes,
- QTOPIAXK_No, Qt::Key_No,
- QTOPIAXK_Cancel, Qt::Key_Cancel,
- QTOPIAXK_Printer, Qt::Key_Printer,
- QTOPIAXK_Execute, Qt::Key_Execute,
- QTOPIAXK_Sleep, Qt::Key_Sleep,
- QTOPIAXK_Play, Qt::Key_Play,
- QTOPIAXK_Zoom, Qt::Key_Zoom,
- QTOPIAXK_Context1, Qt::Key_Context1,
- QTOPIAXK_Context2, Qt::Key_Context2,
- QTOPIAXK_Context3, Qt::Key_Context3,
- QTOPIAXK_Context4, Qt::Key_Context4,
- QTOPIAXK_Call, Qt::Key_Call,
- QTOPIAXK_Hangup, Qt::Key_Hangup,
- QTOPIAXK_Flip, Qt::Key_Flip,
-
- 0, 0
-};
-
-static int translateKeySym(uint key)
-{
- int code = -1;
- int i = 0; // any other keys
- while (KeyTbl[i]) {
- if (key == KeyTbl[i]) {
- code = (int)KeyTbl[i+1];
- break;
- }
- i += 2;
- }
- if (qt_meta_mask) {
- // translate Super/Hyper keys to Meta if we're using them as the MetaModifier
- if (qt_meta_mask == qt_super_mask && (code == Qt::Key_Super_L || code == Qt::Key_Super_R)) {
- code = Qt::Key_Meta;
- } else if (qt_meta_mask == qt_hyper_mask && (code == Qt::Key_Hyper_L || code == Qt::Key_Hyper_R)) {
- code = Qt::Key_Meta;
- }
- }
- return code;
-}
-
-#if !defined(QT_NO_XIM)
-static const unsigned short katakanaKeysymsToUnicode[] = {
- 0x0000, 0x3002, 0x300C, 0x300D, 0x3001, 0x30FB, 0x30F2, 0x30A1,
- 0x30A3, 0x30A5, 0x30A7, 0x30A9, 0x30E3, 0x30E5, 0x30E7, 0x30C3,
- 0x30FC, 0x30A2, 0x30A4, 0x30A6, 0x30A8, 0x30AA, 0x30AB, 0x30AD,
- 0x30AF, 0x30B1, 0x30B3, 0x30B5, 0x30B7, 0x30B9, 0x30BB, 0x30BD,
- 0x30BF, 0x30C1, 0x30C4, 0x30C6, 0x30C8, 0x30CA, 0x30CB, 0x30CC,
- 0x30CD, 0x30CE, 0x30CF, 0x30D2, 0x30D5, 0x30D8, 0x30DB, 0x30DE,
- 0x30DF, 0x30E0, 0x30E1, 0x30E2, 0x30E4, 0x30E6, 0x30E8, 0x30E9,
- 0x30EA, 0x30EB, 0x30EC, 0x30ED, 0x30EF, 0x30F3, 0x309B, 0x309C
-};
-
-static const unsigned short cyrillicKeysymsToUnicode[] = {
- 0x0000, 0x0452, 0x0453, 0x0451, 0x0454, 0x0455, 0x0456, 0x0457,
- 0x0458, 0x0459, 0x045a, 0x045b, 0x045c, 0x0000, 0x045e, 0x045f,
- 0x2116, 0x0402, 0x0403, 0x0401, 0x0404, 0x0405, 0x0406, 0x0407,
- 0x0408, 0x0409, 0x040a, 0x040b, 0x040c, 0x0000, 0x040e, 0x040f,
- 0x044e, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433,
- 0x0445, 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e,
- 0x043f, 0x044f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432,
- 0x044c, 0x044b, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044a,
- 0x042e, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413,
- 0x0425, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e,
- 0x041f, 0x042f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412,
- 0x042c, 0x042b, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042a
-};
-
-static const unsigned short greekKeysymsToUnicode[] = {
- 0x0000, 0x0386, 0x0388, 0x0389, 0x038a, 0x03aa, 0x0000, 0x038c,
- 0x038e, 0x03ab, 0x0000, 0x038f, 0x0000, 0x0000, 0x0385, 0x2015,
- 0x0000, 0x03ac, 0x03ad, 0x03ae, 0x03af, 0x03ca, 0x0390, 0x03cc,
- 0x03cd, 0x03cb, 0x03b0, 0x03ce, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
- 0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f,
- 0x03a0, 0x03a1, 0x03a3, 0x0000, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
- 0x03a8, 0x03a9, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
- 0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
- 0x03c0, 0x03c1, 0x03c3, 0x03c2, 0x03c4, 0x03c5, 0x03c6, 0x03c7,
- 0x03c8, 0x03c9, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
-};
-
-static const unsigned short technicalKeysymsToUnicode[] = {
- 0x0000, 0x23B7, 0x250C, 0x2500, 0x2320, 0x2321, 0x2502, 0x23A1,
- 0x23A3, 0x23A4, 0x23A6, 0x239B, 0x239D, 0x239E, 0x23A0, 0x23A8,
- 0x23AC, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x2264, 0x2260, 0x2265, 0x222B,
- 0x2234, 0x221D, 0x221E, 0x0000, 0x0000, 0x2207, 0x0000, 0x0000,
- 0x223C, 0x2243, 0x0000, 0x0000, 0x0000, 0x21D4, 0x21D2, 0x2261,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x221A, 0x0000,
- 0x0000, 0x0000, 0x2282, 0x2283, 0x2229, 0x222A, 0x2227, 0x2228,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2202,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0192, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x2190, 0x2191, 0x2192, 0x2193, 0x0000
-};
-
-static const unsigned short specialKeysymsToUnicode[] = {
- 0x25C6, 0x2592, 0x2409, 0x240C, 0x240D, 0x240A, 0x0000, 0x0000,
- 0x2424, 0x240B, 0x2518, 0x2510, 0x250C, 0x2514, 0x253C, 0x23BA,
- 0x23BB, 0x2500, 0x23BC, 0x23BD, 0x251C, 0x2524, 0x2534, 0x252C,
- 0x2502, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
-};
-
-static const unsigned short publishingKeysymsToUnicode[] = {
- 0x0000, 0x2003, 0x2002, 0x2004, 0x2005, 0x2007, 0x2008, 0x2009,
- 0x200a, 0x2014, 0x2013, 0x0000, 0x0000, 0x0000, 0x2026, 0x2025,
- 0x2153, 0x2154, 0x2155, 0x2156, 0x2157, 0x2158, 0x2159, 0x215a,
- 0x2105, 0x0000, 0x0000, 0x2012, 0x2329, 0x0000, 0x232a, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x215b, 0x215c, 0x215d, 0x215e, 0x0000,
- 0x0000, 0x2122, 0x2613, 0x0000, 0x25c1, 0x25b7, 0x25cb, 0x25af,
- 0x2018, 0x2019, 0x201c, 0x201d, 0x211e, 0x0000, 0x2032, 0x2033,
- 0x0000, 0x271d, 0x0000, 0x25ac, 0x25c0, 0x25b6, 0x25cf, 0x25ae,
- 0x25e6, 0x25ab, 0x25ad, 0x25b3, 0x25bd, 0x2606, 0x2022, 0x25aa,
- 0x25b2, 0x25bc, 0x261c, 0x261e, 0x2663, 0x2666, 0x2665, 0x0000,
- 0x2720, 0x2020, 0x2021, 0x2713, 0x2717, 0x266f, 0x266d, 0x2642,
- 0x2640, 0x260e, 0x2315, 0x2117, 0x2038, 0x201a, 0x201e, 0x0000
-};
-
-static const unsigned short aplKeysymsToUnicode[] = {
- 0x0000, 0x0000, 0x0000, 0x003c, 0x0000, 0x0000, 0x003e, 0x0000,
- 0x2228, 0x2227, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x00af, 0x0000, 0x22a5, 0x2229, 0x230a, 0x0000, 0x005f, 0x0000,
- 0x0000, 0x0000, 0x2218, 0x0000, 0x2395, 0x0000, 0x22a4, 0x25cb,
- 0x0000, 0x0000, 0x0000, 0x2308, 0x0000, 0x0000, 0x222a, 0x0000,
- 0x2283, 0x0000, 0x2282, 0x0000, 0x22a2, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
- 0x0000, 0x0000, 0x0000, 0x0000, 0x22a3, 0x0000, 0x0000, 0x0000
-};
-
-static const unsigned short koreanKeysymsToUnicode[] = {
- 0x0000, 0x3131, 0x3132, 0x3133, 0x3134, 0x3135, 0x3136, 0x3137,
- 0x3138, 0x3139, 0x313a, 0x313b, 0x313c, 0x313d, 0x313e, 0x313f,
- 0x3140, 0x3141, 0x3142, 0x3143, 0x3144, 0x3145, 0x3146, 0x3147,
- 0x3148, 0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e, 0x314f,
- 0x3150, 0x3151, 0x3152, 0x3153, 0x3154, 0x3155, 0x3156, 0x3157,
- 0x3158, 0x3159, 0x315a, 0x315b, 0x315c, 0x315d, 0x315e, 0x315f,
- 0x3160, 0x3161, 0x3162, 0x3163, 0x11a8, 0x11a9, 0x11aa, 0x11ab,
- 0x11ac, 0x11ad, 0x11ae, 0x11af, 0x11b0, 0x11b1, 0x11b2, 0x11b3,
- 0x11b4, 0x11b5, 0x11b6, 0x11b7, 0x11b8, 0x11b9, 0x11ba, 0x11bb,
- 0x11bc, 0x11bd, 0x11be, 0x11bf, 0x11c0, 0x11c1, 0x11c2, 0x316d,
- 0x3171, 0x3178, 0x317f, 0x3181, 0x3184, 0x3186, 0x318d, 0x318e,
- 0x11eb, 0x11f0, 0x11f9, 0x0000, 0x0000, 0x0000, 0x0000, 0x20a9
-};
-
-static QChar keysymToUnicode(unsigned char byte3, unsigned char byte4)
-{
- switch (byte3) {
- case 0x04:
- // katakana
- if (byte4 > 0xa0 && byte4 < 0xe0)
- return QChar(katakanaKeysymsToUnicode[byte4 - 0xa0]);
- else if (byte4 == 0x7e)
- return QChar(0x203e); // Overline
- break;
- case 0x06:
- // russian, use lookup table
- if (byte4 > 0xa0)
- return QChar(cyrillicKeysymsToUnicode[byte4 - 0xa0]);
- break;
- case 0x07:
- // greek
- if (byte4 > 0xa0)
- return QChar(greekKeysymsToUnicode[byte4 - 0xa0]);
- break;
- case 0x08:
- // technical
- if (byte4 > 0xa0)
- return QChar(technicalKeysymsToUnicode[byte4 - 0xa0]);
- break;
- case 0x09:
- // special
- if (byte4 >= 0xe0)
- return QChar(specialKeysymsToUnicode[byte4 - 0xe0]);
- break;
- case 0x0a:
- // publishing
- if (byte4 > 0xa0)
- return QChar(publishingKeysymsToUnicode[byte4 - 0xa0]);
- break;
- case 0x0b:
- // APL
- if (byte4 > 0xa0)
- return QChar(aplKeysymsToUnicode[byte4 - 0xa0]);
- break;
- case 0x0e:
- // Korean
- if (byte4 > 0xa0)
- return QChar(koreanKeysymsToUnicode[byte4 - 0xa0]);
- break;
- default:
- break;
- }
- return QChar(0x0);
-}
-#endif
-
-static QString translateKeySym(KeySym keysym, uint xmodifiers,
- int &code, Qt::KeyboardModifiers &modifiers,
- QByteArray &chars, int &count)
-{
- // all keysyms smaller than 0xff00 are actally keys that can be mapped to unicode chars
-
- extern QTextCodec *qt_input_mapper; // from qapplication_x11.cpp
- QTextCodec *mapper = qt_input_mapper;
- QChar converted;
-
- if (count == 0 && keysym < 0xff00) {
- unsigned char byte3 = (unsigned char)(keysym >> 8);
- int mib = -1;
- switch(byte3) {
- case 0: // Latin 1
- case 1: // Latin 2
- case 2: //latin 3
- case 3: // latin4
- mib = byte3 + 4; break;
- case 5: // arabic
- mib = 82; break;
- case 12: // Hebrew
- mib = 85; break;
- case 13: // Thai
- mib = 2259; break;
- case 4: // kana
- case 6: // cyrillic
- case 7: // greek
- case 8: // technical, no mapping here at the moment
- case 9: // Special
- case 10: // Publishing
- case 11: // APL
- case 14: // Korean, no mapping
- mib = -1; // manual conversion
- mapper = 0;
-#if !defined(QT_NO_XIM)
- converted = keysymToUnicode(byte3, keysym & 0xff);
-#endif
- case 0x20:
- // currency symbols
- if (keysym >= 0x20a0 && keysym <= 0x20ac) {
- mib = -1; // manual conversion
- mapper = 0;
- converted = (uint)keysym;
- }
- break;
- default:
- break;
- }
- if (mib != -1) {
- mapper = QTextCodec::codecForMib(mib);
- if (chars.isEmpty())
- chars.resize(1);
- chars[0] = (unsigned char) (keysym & 0xff); // get only the fourth bit for conversion later
- count++;
- }
- } else if (keysym >= 0x1000000 && keysym <= 0x100ffff) {
- converted = (ushort) (keysym - 0x1000000);
- mapper = 0;
- }
- if (count < (int)chars.size()-1)
- chars[count] = '\0';
-
- QString text;
- if (!mapper && converted.unicode() != 0x0) {
- text = converted;
- } else if (!chars.isEmpty()) {
- // convert chars (8bit) to text (unicode).
- if (mapper)
- text = mapper->toUnicode(chars.data(), count, 0);
- if (text.isEmpty()) {
- // no mapper, or codec couldn't convert to unicode (this
- // can happen when running in the C locale or with no LANG
- // set). try converting from latin-1
- text = QString::fromLatin1(chars);
- }
- }
-
- modifiers = X11->translateModifiers(xmodifiers);
-
- // Commentary in X11/keysymdef says that X codes match ASCII, so it
- // is safe to use the locale functions to process X codes in ISO8859-1.
- //
- // This is mainly for compatibility - applications should not use the
- // Qt keycodes between 128 and 255, but should rather use the
- // QKeyEvent::text().
- //
- extern QTextCodec *qt_input_mapper; // from qapplication_x11.cpp
- if (keysym < 128 || (keysym < 256 && (!qt_input_mapper || qt_input_mapper->mibEnum()==4))) {
- // upper-case key, if known
- code = isprint((int)keysym) ? toupper((int)keysym) : 0;
- } else if (keysym >= XK_F1 && keysym <= XK_F35) {
- // function keys
- code = Qt::Key_F1 + ((int)keysym - XK_F1);
- } else if (keysym >= XK_KP_Space && keysym <= XK_KP_9) {
- if (keysym >= XK_KP_0) {
- // numeric keypad keys
- code = Qt::Key_0 + ((int)keysym - XK_KP_0);
- } else {
- code = translateKeySym(keysym);
- }
- modifiers |= Qt::KeypadModifier;
- } else if (text.length() == 1 && text.unicode()->unicode() > 0x1f && text.unicode()->unicode() != 0x7f && !(keysym >= XK_dead_grave && keysym <= XK_dead_horn)) {
- code = text.unicode()->toUpper().unicode();
- } else {
- // any other keys
- code = translateKeySym(keysym);
-
- if (code == Qt::Key_Tab && (modifiers & Qt::ShiftModifier)) {
- // map shift+tab to shift+backtab, QShortcutMap knows about it
- // and will handle it.
- code = Qt::Key_Backtab;
- text = QString();
- }
- }
-
- return text;
-}
-
-extern bool qt_use_rtl_extensions; // from qapplication_x11.cpp
-
-bool QKeyMapperPrivate::translateKeyEventInternal(QWidget *keyWidget,
- const XEvent *event,
- KeySym &keysym,
- int& count,
- QString& text,
- Qt::KeyboardModifiers &modifiers,
- int& code,
- QEvent::Type &type,
- bool statefulTranslation)
-{
- XKeyEvent xkeyevent = event->xkey;
- int keycode = event->xkey.keycode;
- // save the modifier state, we will use the keystate uint later by passing
- // it to translateButtonState
- uint keystate = event->xkey.state;
-
- type = (event->type == XKeyPress) ? QEvent::KeyPress : QEvent::KeyRelease;
-
- static int directionKeyEvent = 0;
- static unsigned int lastWinId = 0;
-
- // translate pending direction change
- if (statefulTranslation && qt_use_rtl_extensions && type == QEvent::KeyRelease) {
- if (directionKeyEvent == Qt::Key_Direction_R || directionKeyEvent == Qt::Key_Direction_L) {
- type = QEvent::KeyPress;
- code = directionKeyEvent;
- text = QString();
- directionKeyEvent = 0;
- lastWinId = 0;
- return true;
- } else {
- directionKeyEvent = 0;
- lastWinId = 0;
- }
- }
-
- // some XmbLookupString implementations don't return buffer overflow correctly,
- // so we increase the input buffer to allow for long strings...
- // 256 chars * 2 bytes + 1 null-term == 513 bytes
- QByteArray chars;
- chars.resize(513);
-
- count = XLookupString(&xkeyevent, chars.data(), chars.size(), &keysym, 0);
- if (count && !keycode) {
- extern int qt_ximComposingKeycode; // from qapplication_x11.cpp
- keycode = qt_ximComposingKeycode;
- qt_ximComposingKeycode = 0;
- }
-
- // translate the keysym + xmodifiers to Qt::Key_* + Qt::KeyboardModifiers
- text = translateKeySym(keysym, keystate, code, modifiers, chars, count);
-
- // Watch for keypresses and if its a key belonging to the Ctrl-Shift
- // direction-changing accel, remember it.
- // We keep track of those keys instead of using the event's state
- // (to figure out whether the Ctrl modifier is held while Shift is pressed,
- // or Shift is held while Ctrl is pressed) since the 'state' doesn't tell
- // us whether the modifier held is Left or Right.
- if (statefulTranslation && qt_use_rtl_extensions && type == QEvent::KeyPress) {
- if (keysym == XK_Control_L || keysym == XK_Control_R
- || keysym == XK_Shift_L || keysym == XK_Shift_R) {
- if (!directionKeyEvent) {
- directionKeyEvent = keysym;
- // This code exists in order to check that
- // the event is occurred in the same widget.
- lastWinId = keyWidget->internalWinId();
- }
- } else {
- // this can no longer be a direction-changing accel.
- // if any other key was pressed.
- directionKeyEvent = Qt::Key_Space;
- }
-
- if (directionKeyEvent && lastWinId == keyWidget->internalWinId()) {
- if ((keysym == XK_Shift_L && directionKeyEvent == XK_Control_L)
- || (keysym == XK_Control_L && directionKeyEvent == XK_Shift_L)) {
- directionKeyEvent = Qt::Key_Direction_L;
- } else if ((keysym == XK_Shift_R && directionKeyEvent == XK_Control_R)
- || (keysym == XK_Control_R && directionKeyEvent == XK_Shift_R)) {
- directionKeyEvent = Qt::Key_Direction_R;
- }
- } else if (directionKeyEvent == Qt::Key_Direction_L
- || directionKeyEvent == Qt::Key_Direction_R) {
- directionKeyEvent = Qt::Key_Space; // invalid
- }
- }
-
- return true;
-}
-
-
-struct qt_auto_repeat_data
-{
- // match the window and keycode with timestamp delta of 10 ms
- Window window;
- KeyCode keycode;
- Time timestamp;
-
- // queue scanner state
- bool release;
- bool error;
-};
-
-#if defined(Q_C_CALLBACKS)
-extern "C" {
-#endif
-
-static Bool qt_keypress_scanner(Display *, XEvent *event, XPointer arg)
-{
- if (event->type != XKeyPress && event->type != XKeyRelease)
- return false;
-
- qt_auto_repeat_data *data = (qt_auto_repeat_data *) arg;
- if (data->error)
- return false;
-
- if (event->xkey.window != data->window ||
- event->xkey.keycode != data->keycode) {
- // deal breakers: key events in a different window or an event
- // with a different key code
- data->error = true;
- return false;
- }
-
- if (event->type == XKeyPress) {
- data->error = (! data->release || event->xkey.time - data->timestamp > 10);
- return (! data->error);
- }
-
- // must be XKeyRelease event
- if (data->release) {
- // found a second release
- data->error = true;
- return false;
- }
-
- // found a single release
- data->release = true;
- data->timestamp = event->xkey.time;
-
- return false;
-}
-
-static Bool qt_keyrelease_scanner(Display *, XEvent *event, XPointer arg)
-{
- const qt_auto_repeat_data *data = (const qt_auto_repeat_data *) arg;
- return (event->type == XKeyRelease &&
- event->xkey.window == data->window &&
- event->xkey.keycode == data->keycode);
-}
-
-#if defined(Q_C_CALLBACKS)
-}
-#endif
-
-bool QKeyMapperPrivate::translateKeyEvent(QWidget *keyWidget, const XEvent *event, bool grab)
-{
- int code = -1;
- int count = 0;
- Qt::KeyboardModifiers modifiers;
-
- if (qt_sm_blockUserInput) // block user interaction during session management
- return true;
-
- Display *dpy = X11->display;
-
- if (!keyWidget->isEnabled())
- return true;
-
- QEvent::Type type;
- bool autor = false;
- QString text;
-
- KeySym keysym = 0;
- translateKeyEventInternal(keyWidget, event, keysym, count, text, modifiers, code, type);
-
- // was this the last auto-repeater?
- qt_auto_repeat_data auto_repeat_data;
- auto_repeat_data.window = event->xkey.window;
- auto_repeat_data.keycode = event->xkey.keycode;
- auto_repeat_data.timestamp = event->xkey.time;
-
- static uint curr_autorep = 0;
- if (event->type == XKeyPress) {
- if (curr_autorep == event->xkey.keycode) {
- autor = true;
- curr_autorep = 0;
- }
- } else {
- // look ahead for auto-repeat
- XEvent nextpress;
-
- auto_repeat_data.release = true;
- auto_repeat_data.error = false;
- if (XCheckIfEvent(dpy, &nextpress, &qt_keypress_scanner,
- (XPointer) &auto_repeat_data)) {
- autor = true;
-
- // Put it back... we COULD send the event now and not need
- // the static curr_autorep variable.
- XPutBackEvent(dpy,&nextpress);
- }
- curr_autorep = autor ? event->xkey.keycode : 0;
- }
-
-#if defined QT3_SUPPORT && !defined(QT_NO_SHORTCUT)
- // process accelerators before doing key compression
- if (type == QEvent::KeyPress && !grab
- && QApplicationPrivate::instance()->use_compat()) {
- // send accel events if the keyboard is not grabbed
- QKeyEventEx a(type, code, modifiers, text, autor, qMax(qMax(count,1), int(text.length())),
- event->xkey.keycode, keysym, event->xkey.state);
- if (QApplicationPrivate::instance()->qt_tryAccelEvent(keyWidget, &a))
- return true;
- }
-#endif
-
-#ifndef QT_NO_IM
- QInputContext *qic = keyWidget->inputContext();
-#endif
-
- // compress keys
- if (!text.isEmpty() && keyWidget->testAttribute(Qt::WA_KeyCompression) &&
-#ifndef QT_NO_IM
- // Ordinary input methods require discrete key events to work
- // properly, so key compression has to be disabled when input
- // context exists.
- //
- // And further consideration, some complex input method
- // require all key press/release events discretely even if
- // the input method awares of key compression and compressed
- // keys are ordinary alphabets. For example, the uim project
- // is planning to implement "combinational shift" feature for
- // a Japanese input method, uim-skk. It will work as follows.
- //
- // 1. press "r"
- // 2. press "u"
- // 3. release both "r" and "u" in arbitrary order
- // 4. above key sequence generates "Ru"
- //
- // Of course further consideration about other participants
- // such as key repeat mechanism is required to implement such
- // feature.
- !qic &&
-#endif // QT_NO_IM
- // do not compress keys if the key event we just got above matches
- // one of the key ranges used to compute stopCompression
- !((code >= Qt::Key_Escape && code <= Qt::Key_SysReq)
- || (code >= Qt::Key_Home && code <= Qt::Key_PageDown)
- || (code >= Qt::Key_Super_L && code <= Qt::Key_Direction_R)
- || (code == 0)
- || (text.length() == 1 && text.unicode()->unicode() == '\n'))) {
- // the widget wants key compression so it gets it
-
- // sync the event queue, this makes key compress work better
- XSync(dpy, false);
-
- for (;;) {
- XEvent evRelease;
- XEvent evPress;
- if (!XCheckTypedWindowEvent(dpy,event->xkey.window,
- XKeyRelease,&evRelease))
- break;
- if (!XCheckTypedWindowEvent(dpy,event->xkey.window,
- XKeyPress,&evPress)) {
- XPutBackEvent(dpy, &evRelease);
- break;
- }
- QString textIntern;
- int codeIntern = -1;
- int countIntern = 0;
- Qt::KeyboardModifiers modifiersIntern;
- QEvent::Type t;
- KeySym keySymIntern;
- translateKeyEventInternal(keyWidget, &evPress, keySymIntern, countIntern, textIntern,
- modifiersIntern, codeIntern, t);
- // use stopCompression to stop key compression for the following
- // key event ranges:
- bool stopCompression =
- // 1) misc keys
- (codeIntern >= Qt::Key_Escape && codeIntern <= Qt::Key_SysReq)
- // 2) cursor movement
- || (codeIntern >= Qt::Key_Home && codeIntern <= Qt::Key_PageDown)
- // 3) extra keys
- || (codeIntern >= Qt::Key_Super_L && codeIntern <= Qt::Key_Direction_R)
- // 4) something that a) doesn't translate to text or b) translates
- // to newline text
- || (codeIntern == 0)
- || (textIntern.length() == 1 && textIntern.unicode()->unicode() == '\n')
- || (codeIntern == Qt::Key_unknown);
-
- if (modifiersIntern == modifiers && !textIntern.isEmpty() && !stopCompression) {
- text += textIntern;
- count += countIntern;
- } else {
- XPutBackEvent(dpy, &evPress);
- XPutBackEvent(dpy, &evRelease);
- break;
- }
- }
- }
-
- // autorepeat compression makes sense for all widgets (Windows
- // does it automatically ....)
- if (event->type == XKeyPress && text.length() <= 1
-#ifndef QT_NO_IM
- // input methods need discrete key events
- && !qic
-#endif// QT_NO_IM
- ) {
- XEvent dummy;
-
- for (;;) {
- auto_repeat_data.release = false;
- auto_repeat_data.error = false;
- if (! XCheckIfEvent(dpy, &dummy, &qt_keypress_scanner,
- (XPointer) &auto_repeat_data))
- break;
- if (! XCheckIfEvent(dpy, &dummy, &qt_keyrelease_scanner,
- (XPointer) &auto_repeat_data))
- break;
-
- count++;
- if (!text.isEmpty())
- text += text[0];
- }
- }
-
- return QKeyMapper::sendKeyEvent(keyWidget, grab, type, code, modifiers, text, autor,
- qMax(qMax(count,1), int(text.length())),
- event->xkey.keycode, keysym, event->xkey.state);
-}
-
-bool QKeyMapper::sendKeyEvent(QWidget *keyWidget, bool grab,
- QEvent::Type type, int code, Qt::KeyboardModifiers modifiers,
- const QString &text, bool autorepeat, int count,
- quint32 nativeScanCode, quint32 nativeVirtualKey, quint32 nativeModifiers,
- bool *)
-{
- // try the menukey first
- if (type == QEvent::KeyPress && code == Qt::Key_Menu) {
- QVariant v = keyWidget->inputMethodQuery(Qt::ImMicroFocus);
- QPoint globalPos;
- QPoint pos;
- if (v.isNull()) {
- globalPos = QCursor::pos();
- pos = keyWidget->mapFromGlobal(globalPos);
- } else {
- pos = v.toRect().center();
- globalPos = keyWidget->mapToGlobal(pos);
- }
- QContextMenuEvent e(QContextMenuEvent::Keyboard, pos, globalPos);
- qt_sendSpontaneousEvent(keyWidget, &e);
- if(e.isAccepted())
- return true;
- }
-
- Q_UNUSED(grab);
- QKeyEventEx e(type, code, modifiers, text, autorepeat, qMax(qMax(count,1), int(text.length())),
- nativeScanCode, nativeVirtualKey, nativeModifiers);
- return qt_sendSpontaneousEvent(keyWidget, &e);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qkeymapper_x11_p.cpp b/src/gui/platforms/x11/qkeymapper_x11_p.cpp
deleted file mode 100644
index 2dbe1e77a4..0000000000
--- a/src/gui/platforms/x11/qkeymapper_x11_p.cpp
+++ /dev/null
@@ -1,489 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-// This file is auto-generated, do not edit!
-// (Generated using util/xkbdatagen)
-
-static struct {
- const char *layout;
- const char *variant; // 0 means any variant
- Qt::LayoutDirection direction;
- QLocale::Language language;
- QLocale::Country country;
-} xkbLayoutData[] = {
- // name = us, description = U.S. English
- { "us", "", Qt::LeftToRight, QLocale::English, QLocale::UnitedStates },
- // name = us:intl, description = U.S. English
- { "us", "intl", Qt::LeftToRight, QLocale::English, QLocale::UnitedStates },
- // name = us:alt-intl, description = U.S. English
- { "us", "alt-intl", Qt::LeftToRight, QLocale::English, QLocale::UnitedStates },
- // name = us:dvorak, description = U.S. English
- { "us", "dvorak", Qt::LeftToRight, QLocale::English, QLocale::UnitedStates },
- // name = us:rus, description = U.S. English
- { "us", "rus", Qt::LeftToRight, QLocale::Russian, QLocale::UnitedStates },
- // name = ara, description = Arabic
- { "ara", "", Qt::RightToLeft, QLocale::Arabic, QLocale::UnitedArabEmirates },
- // name = ara:azerty, description = Arabic
- { "ara", "azerty", Qt::RightToLeft, QLocale::Arabic, QLocale::UnitedArabEmirates },
- // name = ara:azerty_digits, description = Arabic
- { "ara", "azerty_digits", Qt::RightToLeft, QLocale::Arabic, QLocale::UnitedArabEmirates },
- // name = ara:digits, description = Arabic
- { "ara", "digits", Qt::RightToLeft, QLocale::Arabic, QLocale::UnitedArabEmirates },
- // name = ara:qwerty, description = Arabic
- { "ara", "qwerty", Qt::RightToLeft, QLocale::Arabic, QLocale::UnitedArabEmirates },
- // name = ara:qwerty_digits, description = Arabic
- { "ara", "qwerty_digits", Qt::RightToLeft, QLocale::Arabic, QLocale::UnitedArabEmirates },
- // name = al, description = Albania
- { "al", "", Qt::LeftToRight, QLocale::Albanian, QLocale::Albania },
- // name = am, description = Armenia
- { "am", "", Qt::LeftToRight, QLocale::Armenian, QLocale::Armenia },
- // name = am:phonetic, description = Armenia
- { "am", "phonetic", Qt::LeftToRight, QLocale::Armenian, QLocale::Armenia },
- // name = az, description = Azerbaijan
- { "az", "", Qt::LeftToRight, QLocale::Azerbaijani, QLocale::Azerbaijan },
- // name = az:cyrillic, description = Azerbaijan
- { "az", "cyrillic", Qt::LeftToRight, QLocale::Azerbaijani, QLocale::Azerbaijan },
- // name = by, description = Belarus
- { "by", "", Qt::LeftToRight, QLocale::Byelorussian, QLocale::Belarus },
- // name = by:winkeys, description = Belarus
- { "by", "winkeys", Qt::LeftToRight, QLocale::Byelorussian, QLocale::Belarus },
- // name = be, description = Belgium
- { "be", "", Qt::LeftToRight, QLocale::Dutch, QLocale::Belgium },
- // name = be:iso-alternate, description = Belgium
- { "be", "iso-alternate", Qt::LeftToRight, QLocale::Dutch, QLocale::Belgium },
- // name = be:nodeadkeys, description = Belgium
- { "be", "nodeadkeys", Qt::LeftToRight, QLocale::Dutch, QLocale::Belgium },
- // name = be:sundeadkeys, description = Belgium
- { "be", "sundeadkeys", Qt::LeftToRight, QLocale::Dutch, QLocale::Belgium },
- // name = bd, description = Bangladesh
- { "bd", "", Qt::LeftToRight, QLocale::Bengali, QLocale::Bangladesh },
- // name = bd:probhat, description = Bangladesh
- { "bd", "probhat", Qt::LeftToRight, QLocale::Bengali, QLocale::Bangladesh },
- // name = in, description = India
- { "in", "", Qt::LeftToRight, QLocale::Hindi, QLocale::India },
- // name = in:ben, description = India
- { "in", "ben", Qt::LeftToRight, QLocale::Bengali, QLocale::India },
- // name = in:ben_probhat, description = India
- { "in", "ben_probhat", Qt::LeftToRight, QLocale::Bengali, QLocale::India },
- // name = in:guj, description = India
- { "in", "guj", Qt::LeftToRight, QLocale::Gujarati, QLocale::India },
- // name = in:guru, description = India
- { "in", "guru", Qt::LeftToRight, QLocale::Punjabi, QLocale::India },
- // name = in:kan, description = India
- { "in", "kan", Qt::LeftToRight, QLocale::Kannada, QLocale::India },
- // name = in:mal, description = India
- { "in", "mal", Qt::LeftToRight, QLocale::Malayalam, QLocale::India },
- // name = in:ori, description = India
- { "in", "ori", Qt::LeftToRight, QLocale::Oriya, QLocale::India },
- // name = in:tam_unicode, description = India
- { "in", "tam_unicode", Qt::LeftToRight, QLocale::Tamil, QLocale::India },
- // name = in:tam_TAB, description = India
- { "in", "tam_TAB", Qt::LeftToRight, QLocale::Tamil, QLocale::India },
- // name = in:tam_TSCII, description = India
- { "in", "tam_TSCII", Qt::LeftToRight, QLocale::Tamil, QLocale::India },
- // name = in:tam, description = India
- { "in", "tam", Qt::LeftToRight, QLocale::Tamil, QLocale::India },
- // name = in:tel, description = India
- { "in", "tel", Qt::LeftToRight, QLocale::Telugu, QLocale::India },
- // name = in:urd, description = India
- { "in", "urd", Qt::RightToLeft, QLocale::Urdu, QLocale::India },
- // name = ba, description = Bosnia and Herzegovina
- { "ba", "", Qt::LeftToRight, QLocale::Bosnian, QLocale::BosniaAndHerzegowina },
- // name = br, description = Brazil
- { "br", "", Qt::LeftToRight, QLocale::Portuguese, QLocale::Brazil },
- // name = br:nodeadkeys, description = Brazil
- { "br", "nodeadkeys", Qt::LeftToRight, QLocale::Portuguese, QLocale::Brazil },
- // name = bg, description = Bulgaria
- { "bg", "", Qt::LeftToRight, QLocale::Bulgarian, QLocale::Bulgaria },
- // name = bg:phonetic, description = Bulgaria
- { "bg", "phonetic", Qt::LeftToRight, QLocale::Bulgarian, QLocale::Bulgaria },
- // name = mm, description = Myanmar
- { "mm", "", Qt::LeftToRight, QLocale::Burmese, QLocale::Myanmar },
- // name = ca, description = Canada
- { "ca", "", Qt::LeftToRight, QLocale::English, QLocale::Canada },
- // name = ca:fr-dvorak, description = Canada
- { "ca", "fr-dvorak", Qt::LeftToRight, QLocale::French, QLocale::Canada },
- // name = ca:fr-legacy, description = Canada
- { "ca", "fr-legacy", Qt::LeftToRight, QLocale::French, QLocale::Canada },
- // name = ca:multi, description = Canada
- { "ca", "multi", Qt::LeftToRight, QLocale::English, QLocale::Canada },
- // name = ca:multi-2gr, description = Canada
- { "ca", "multi-2gr", Qt::LeftToRight, QLocale::English, QLocale::Canada },
- // name = ca:ike, description = Canada
- { "ca", "ike", Qt::LeftToRight, QLocale::Inuktitut, QLocale::Canada },
- // name = hr, description = Croatia
- { "hr", "", Qt::LeftToRight, QLocale::Croatian, QLocale::Croatia },
- // name = hr:us, description = Croatia
- { "hr", "us", Qt::LeftToRight, QLocale::Croatian, QLocale::Croatia },
- // name = cz, description = Czechia
- { "cz", "", Qt::LeftToRight, QLocale::Czech, QLocale::CzechRepublic },
- // name = cz:bksl, description = Czechia
- { "cz", "bksl", Qt::LeftToRight, QLocale::Czech, QLocale::CzechRepublic },
- // name = cz:qwerty, description = Czechia
- { "cz", "qwerty", Qt::LeftToRight, QLocale::Czech, QLocale::CzechRepublic },
- // name = cz:qwerty_bksl, description = Czechia
- { "cz", "qwerty_bksl", Qt::LeftToRight, QLocale::Czech, QLocale::CzechRepublic },
- // name = dk, description = Denmark
- { "dk", "", Qt::LeftToRight, QLocale::Danish, QLocale::Denmark },
- // name = dk:nodeadkeys, description = Denmark
- { "dk", "nodeadkeys", Qt::LeftToRight, QLocale::Danish, QLocale::Denmark },
- // name = nl, description = Netherlands
- { "nl", "", Qt::LeftToRight, QLocale::Dutch, QLocale::Netherlands },
- // name = bt, description = Bhutan
- { "bt", "", Qt::LeftToRight, QLocale::Bhutani, QLocale::Bhutan },
- // name = ee, description = Estonia
- { "ee", "", Qt::LeftToRight, QLocale::Estonian, QLocale::Estonia },
- // name = ee:nodeadkeys, description = Estonia
- { "ee", "nodeadkeys", Qt::LeftToRight, QLocale::Estonian, QLocale::Estonia },
- // name = ir, description = Iran
- { "ir", "", Qt::RightToLeft, QLocale::Persian, QLocale::Iran },
- // name = fo, description = Faroe Islands
- { "fo", "", Qt::LeftToRight, QLocale::Faroese, QLocale::FaroeIslands },
- // name = fo:nodeadkeys, description = Faroe Islands
- { "fo", "nodeadkeys", Qt::LeftToRight, QLocale::Faroese, QLocale::FaroeIslands },
- // name = fi, description = Finland
- { "fi", "", Qt::LeftToRight, QLocale::Finnish, QLocale::Finland },
- // name = fi:nodeadkeys, description = Finland
- { "fi", "nodeadkeys", Qt::LeftToRight, QLocale::Finnish, QLocale::Finland },
- // name = fi:smi, description = Finland
- { "fi", "smi", Qt::LeftToRight, QLocale::Finnish, QLocale::Finland },
- // name = fr, description = France
- { "fr", "", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = fr:nodeadkeys, description = France
- { "fr", "nodeadkeys", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = fr:sundeadkeys, description = France
- { "fr", "sundeadkeys", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = fr:latin9, description = France
- { "fr", "latin9", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = fr:latin9_nodeadkeys, description = France
- { "fr", "latin9_nodeadkeys", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = fr:latin9_sundeadkeys, description = France
- { "fr", "latin9_sundeadkeys", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = fr:dvorak, description = France
- { "fr", "dvorak", Qt::LeftToRight, QLocale::French, QLocale::France },
- // name = ge, description = Georgia
- { "ge", "", Qt::LeftToRight, QLocale::Georgian, QLocale::Georgia },
- // name = ge:ru, description = Georgia
- { "ge", "ru", Qt::LeftToRight, QLocale::Russian, QLocale::Georgia },
- // name = de, description = Germany
- { "de", "", Qt::LeftToRight, QLocale::German, QLocale::Germany },
- // name = de:deadacute, description = Germany
- { "de", "deadacute", Qt::LeftToRight, QLocale::German, QLocale::Germany },
- // name = de:deadgraveacute, description = Germany
- { "de", "deadgraveacute", Qt::LeftToRight, QLocale::German, QLocale::Germany },
- // name = de:nodeadkeys, description = Germany
- { "de", "nodeadkeys", Qt::LeftToRight, QLocale::German, QLocale::Germany },
- // name = de:ro, description = Germany
- { "de", "ro", Qt::LeftToRight, QLocale::Romanian, QLocale::Germany },
- // name = de:ro_nodeadkeys, description = Germany
- { "de", "ro_nodeadkeys", Qt::LeftToRight, QLocale::Romanian, QLocale::Germany },
- // name = de:dvorak, description = Germany
- { "de", "dvorak", Qt::LeftToRight, QLocale::German, QLocale::Germany },
- // name = gr, description = Greece
- { "gr", "", Qt::LeftToRight, QLocale::Greek, QLocale::Greece },
- // name = gr:extended, description = Greece
- { "gr", "extended", Qt::LeftToRight, QLocale::Greek, QLocale::Greece },
- // name = gr:nodeadkeys, description = Greece
- { "gr", "nodeadkeys", Qt::LeftToRight, QLocale::Greek, QLocale::Greece },
- // name = gr:polytonic, description = Greece
- { "gr", "polytonic", Qt::LeftToRight, QLocale::Greek, QLocale::Greece },
- // name = hu, description = Hungary
- { "hu", "", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:standard, description = Hungary
- { "hu", "standard", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:nodeadkeys, description = Hungary
- { "hu", "nodeadkeys", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:qwerty, description = Hungary
- { "hu", "qwerty", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwertz_comma_dead, description = Hungary
- { "hu", "101_qwertz_comma_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwertz_comma_nodead, description = Hungary
- { "hu", "101_qwertz_comma_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwertz_dot_dead, description = Hungary
- { "hu", "101_qwertz_dot_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwertz_dot_nodead, description = Hungary
- { "hu", "101_qwertz_dot_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwerty_comma_dead, description = Hungary
- { "hu", "101_qwerty_comma_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwerty_comma_nodead, description = Hungary
- { "hu", "101_qwerty_comma_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwerty_dot_dead, description = Hungary
- { "hu", "101_qwerty_dot_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:101_qwerty_dot_nodead, description = Hungary
- { "hu", "101_qwerty_dot_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwertz_comma_dead, description = Hungary
- { "hu", "102_qwertz_comma_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwertz_comma_nodead, description = Hungary
- { "hu", "102_qwertz_comma_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwertz_dot_dead, description = Hungary
- { "hu", "102_qwertz_dot_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwertz_dot_nodead, description = Hungary
- { "hu", "102_qwertz_dot_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwerty_comma_dead, description = Hungary
- { "hu", "102_qwerty_comma_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwerty_comma_nodead, description = Hungary
- { "hu", "102_qwerty_comma_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwerty_dot_dead, description = Hungary
- { "hu", "102_qwerty_dot_dead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = hu:102_qwerty_dot_nodead, description = Hungary
- { "hu", "102_qwerty_dot_nodead", Qt::LeftToRight, QLocale::Hungarian, QLocale::Hungary },
- // name = is, description = Iceland
- { "is", "", Qt::LeftToRight, QLocale::Icelandic, QLocale::Iceland },
- // name = is:Sundeadkeys, description = Iceland
- { "is", "Sundeadkeys", Qt::LeftToRight, QLocale::Icelandic, QLocale::Iceland },
- // name = is:nodeadkeys, description = Iceland
- { "is", "nodeadkeys", Qt::LeftToRight, QLocale::Icelandic, QLocale::Iceland },
- // name = il, description = Israel
- { "il", "", Qt::RightToLeft, QLocale::Hebrew, QLocale::Israel },
- // name = il:lyx, description = Israel
- { "il", "lyx", Qt::RightToLeft, QLocale::Hebrew, QLocale::Israel },
- // name = il:si1452, description = Israel
- { "il", "si1452", Qt::RightToLeft, QLocale::Hebrew, QLocale::Israel },
- // name = il:phonetic, description = Israel
- { "il", "phonetic", Qt::RightToLeft, QLocale::Hebrew, QLocale::Israel },
- // name = it, description = Italy
- { "it", "", Qt::LeftToRight, QLocale::Italian, QLocale::Italy },
- // name = it:nodeadkeys, description = Italy
- { "it", "nodeadkeys", Qt::LeftToRight, QLocale::Italian, QLocale::Italy },
- // name = jp, description = Japan
- { "jp", "", Qt::LeftToRight, QLocale::Japanese, QLocale::Japan },
- // name = kg, description = Kyrgyzstan
- { "kg", "", Qt::LeftToRight, QLocale::Kirghiz, QLocale::Kyrgyzstan },
- // name = la, description = Laos
- { "la", "", Qt::LeftToRight, QLocale::Laothian, QLocale::Lao },
- // name = latam, description = Latin American
- { "latam", "", Qt::LeftToRight, QLocale::Spanish, QLocale::Mexico },
- // name = latam:nodeadkeys, description = Latin American
- { "latam", "nodeadkeys", Qt::LeftToRight, QLocale::Spanish, QLocale::Mexico },
- // name = latam:sundeadkeys, description = Latin American
- { "latam", "sundeadkeys", Qt::LeftToRight, QLocale::Spanish, QLocale::Mexico },
- // name = lt, description = Lithuania
- { "lt", "", Qt::LeftToRight, QLocale::Lithuanian, QLocale::Lithuania },
- // name = lt:std, description = Lithuania
- { "lt", "std", Qt::LeftToRight, QLocale::Lithuanian, QLocale::Lithuania },
- // name = lt:us, description = Lithuania
- { "lt", "us", Qt::LeftToRight, QLocale::Lithuanian, QLocale::Lithuania },
- // name = lv, description = Latvia
- { "lv", "", Qt::LeftToRight, QLocale::Latvian, QLocale::Latvia },
- // name = lv:apostrophe, description = Latvia
- { "lv", "apostrophe", Qt::LeftToRight, QLocale::Latvian, QLocale::Latvia },
- // name = lv:tilde, description = Latvia
- { "lv", "tilde", Qt::LeftToRight, QLocale::Latvian, QLocale::Latvia },
- // name = lv:fkey, description = Latvia
- { "lv", "fkey", Qt::LeftToRight, QLocale::Latvian, QLocale::Latvia },
- // name = mao, description = Maori
- { "mao", "", Qt::LeftToRight, QLocale::Maori, QLocale::NewZealand },
- // name = mkd, description = Macedonian
- { "mkd", "", Qt::LeftToRight, QLocale::Macedonian, QLocale::Macedonia },
- // name = mkd:nodeadkeys, description = Macedonian
- { "mkd", "nodeadkeys", Qt::LeftToRight, QLocale::Macedonian, QLocale::Macedonia },
- // name = mt, description = Malta
- { "mt", "", Qt::LeftToRight, QLocale::Maltese, QLocale::Malta },
- // name = mt:us, description = Malta
- { "mt", "us", Qt::LeftToRight, QLocale::Maltese, QLocale::Malta },
- // name = mn, description = Mongolia
- { "mn", "", Qt::LeftToRight, QLocale::Mongolian, QLocale::Mongolia },
- // name = no, description = Norway
- { "no", "", Qt::LeftToRight, QLocale::Norwegian, QLocale::Norway },
- // name = no:nodeadkeys, description = Norway
- { "no", "nodeadkeys", Qt::LeftToRight, QLocale::Norwegian, QLocale::Norway },
- // name = no:dvorak, description = Norway
- { "no", "dvorak", Qt::LeftToRight, QLocale::Norwegian, QLocale::Norway },
- // name = no:smi, description = Norway
- { "no", "smi", Qt::LeftToRight, QLocale::Norwegian, QLocale::Norway },
- // name = no:smi_nodeadkeys, description = Norway
- { "no", "smi_nodeadkeys", Qt::LeftToRight, QLocale::Norwegian, QLocale::Norway },
- // name = pl, description = Poland
- { "pl", "", Qt::LeftToRight, QLocale::Polish, QLocale::Poland },
- // name = pl:qwertz, description = Poland
- { "pl", "qwertz", Qt::LeftToRight, QLocale::Polish, QLocale::Poland },
- // name = pl:dvorak, description = Poland
- { "pl", "dvorak", Qt::LeftToRight, QLocale::Polish, QLocale::Poland },
- // name = pl:dvorak_quotes, description = Poland
- { "pl", "dvorak_quotes", Qt::LeftToRight, QLocale::Polish, QLocale::Poland },
- // name = pl:dvorak_altquotes, description = Poland
- { "pl", "dvorak_altquotes", Qt::LeftToRight, QLocale::Polish, QLocale::Poland },
- // name = pt, description = Portugal
- { "pt", "", Qt::LeftToRight, QLocale::Portuguese, QLocale::Portugal },
- // name = pt:nodeadkeys, description = Portugal
- { "pt", "nodeadkeys", Qt::LeftToRight, QLocale::Portuguese, QLocale::Portugal },
- // name = pt:sundeadkeys, description = Portugal
- { "pt", "sundeadkeys", Qt::LeftToRight, QLocale::Portuguese, QLocale::Portugal },
- // name = ro, description = Romania
- { "ro", "", Qt::LeftToRight, QLocale::Romanian, QLocale::Romania },
- // name = ro:us, description = Romania
- { "ro", "us", Qt::LeftToRight, QLocale::English, QLocale::Romania },
- // name = ro:de, description = Romania
- { "ro", "de", Qt::LeftToRight, QLocale::German, QLocale::Romania },
- // name = ru, description = Russia
- { "ru", "", Qt::LeftToRight, QLocale::Russian, QLocale::RussianFederation },
- // name = ru:phonetic, description = Russia
- { "ru", "phonetic", Qt::LeftToRight, QLocale::Russian, QLocale::RussianFederation },
- // name = ru:typewriter, description = Russia
- { "ru", "typewriter", Qt::LeftToRight, QLocale::Russian, QLocale::RussianFederation },
- // name = ru:winkeys, description = Russia
- { "ru", "winkeys", Qt::LeftToRight, QLocale::Russian, QLocale::RussianFederation },
- // name = srp, description = Serbian
- { "srp", "", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:yz, description = Serbian
- { "srp", "yz", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:latin, description = Serbian
- { "srp", "latin", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:latinunicode, description = Serbian
- { "srp", "latinunicode", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:latinyz, description = Serbian
- { "srp", "latinyz", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:latinunicodeyz, description = Serbian
- { "srp", "latinunicodeyz", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:alternatequotes, description = Serbian
- { "srp", "alternatequotes", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = srp:latinalternatequotes, description = Serbian
- { "srp", "latinalternatequotes", Qt::LeftToRight, QLocale::Serbian, QLocale::SerbiaAndMontenegro },
- // name = si, description = Slovenia
- { "si", "", Qt::LeftToRight, QLocale::Slovenian, QLocale::Slovenia },
- // name = sk, description = Slovakia
- { "sk", "", Qt::LeftToRight, QLocale::Slovak, QLocale::Slovakia },
- // name = sk:bksl, description = Slovakia
- { "sk", "bksl", Qt::LeftToRight, QLocale::Slovak, QLocale::Slovakia },
- // name = sk:qwerty, description = Slovakia
- { "sk", "qwerty", Qt::LeftToRight, QLocale::Slovak, QLocale::Slovakia },
- // name = sk:qwerty_bksl, description = Slovakia
- { "sk", "qwerty_bksl", Qt::LeftToRight, QLocale::Slovak, QLocale::Slovakia },
- // name = es, description = Spain
- { "es", "", Qt::LeftToRight, QLocale::Spanish, QLocale::Spain },
- // name = es:nodeadkeys, description = Spain
- { "es", "nodeadkeys", Qt::LeftToRight, QLocale::Spanish, QLocale::Spain },
- // name = es:sundeadkeys, description = Spain
- { "es", "sundeadkeys", Qt::LeftToRight, QLocale::Spanish, QLocale::Spain },
- // name = es:dvorak, description = Spain
- { "es", "dvorak", Qt::LeftToRight, QLocale::Spanish, QLocale::Spain },
- // name = se, description = Sweden
- { "se", "", Qt::LeftToRight, QLocale::Swedish, QLocale::Sweden },
- // name = se:nodeadkeys, description = Sweden
- { "se", "nodeadkeys", Qt::LeftToRight, QLocale::Swedish, QLocale::Sweden },
- // name = se:dvorak, description = Sweden
- { "se", "dvorak", Qt::LeftToRight, QLocale::Swedish, QLocale::Sweden },
- // name = se:rus, description = Sweden
- { "se", "rus", Qt::LeftToRight, QLocale::Russian, QLocale::Sweden },
- // name = se:rus_nodeadkeys, description = Sweden
- { "se", "rus_nodeadkeys", Qt::LeftToRight, QLocale::Russian, QLocale::Sweden },
- // name = se:smi, description = Sweden
- { "se", "smi", Qt::LeftToRight, QLocale::Swedish, QLocale::Sweden },
- // name = ch, description = Switzerland
- { "ch", "", Qt::LeftToRight, QLocale::German, QLocale::Switzerland },
- // name = ch:de_nodeadkeys, description = Switzerland
- { "ch", "de_nodeadkeys", Qt::LeftToRight, QLocale::German, QLocale::Switzerland },
- // name = ch:de_sundeadkeys, description = Switzerland
- { "ch", "de_sundeadkeys", Qt::LeftToRight, QLocale::German, QLocale::Switzerland },
- // name = ch:fr, description = Switzerland
- { "ch", "fr", Qt::LeftToRight, QLocale::French, QLocale::Switzerland },
- // name = ch:fr_nodeadkeys, description = Switzerland
- { "ch", "fr_nodeadkeys", Qt::LeftToRight, QLocale::French, QLocale::Switzerland },
- // name = ch:fr_sundeadkeys, description = Switzerland
- { "ch", "fr_sundeadkeys", Qt::LeftToRight, QLocale::French, QLocale::Switzerland },
- // name = sy, description = Syria
- { "sy", "", Qt::RightToLeft, QLocale::Syriac, QLocale::SyrianArabRepublic },
- // name = sy:syc, description = Syria
- { "sy", "syc", Qt::RightToLeft, QLocale::Syriac, QLocale::SyrianArabRepublic },
- // name = sy:syc_phonetic, description = Syria
- { "sy", "syc_phonetic", Qt::RightToLeft, QLocale::Syriac, QLocale::SyrianArabRepublic },
- // name = tj, description = Tajikistan
- { "tj", "", Qt::LeftToRight, QLocale::Tajik, QLocale::Tajikistan },
- // name = lk, description = Sri Lanka
- { "lk", "", Qt::LeftToRight, QLocale::Singhalese, QLocale::SriLanka },
- // name = lk:tam_unicode, description = Sri Lanka
- { "lk", "tam_unicode", Qt::LeftToRight, QLocale::Tamil, QLocale::SriLanka },
- // name = lk:tam_TAB, description = Sri Lanka
- { "lk", "tam_TAB", Qt::LeftToRight, QLocale::Tamil, QLocale::SriLanka },
- // name = lk:tam_TSCII, description = Sri Lanka
- { "lk", "tam_TSCII", Qt::LeftToRight, QLocale::Tamil, QLocale::SriLanka },
- // name = lk:sin_phonetic, description = Sri Lanka
- { "lk", "sin_phonetic", Qt::LeftToRight, QLocale::Singhalese, QLocale::SriLanka },
- // name = th, description = Thailand
- { "th", "", Qt::LeftToRight, QLocale::Thai, QLocale::Thailand },
- // name = th:tis, description = Thailand
- { "th", "tis", Qt::LeftToRight, QLocale::Thai, QLocale::Thailand },
- // name = th:pat, description = Thailand
- { "th", "pat", Qt::LeftToRight, QLocale::Thai, QLocale::Thailand },
- // name = tr, description = Turkish
- { "tr", "", Qt::LeftToRight, QLocale::Turkish, QLocale::Turkey },
- // name = tr:f, description = Turkish
- { "tr", "f", Qt::LeftToRight, QLocale::Turkish, QLocale::Turkey },
- // name = tr:alt, description = Turkish
- { "tr", "alt", Qt::LeftToRight, QLocale::Turkish, QLocale::Turkey },
- // name = ua, description = Ukraine
- { "ua", "", Qt::LeftToRight, QLocale::Ukrainian, QLocale::Ukraine },
- // name = ua:phonetic, description = Ukraine
- { "ua", "phonetic", Qt::LeftToRight, QLocale::Ukrainian, QLocale::Ukraine },
- // name = ua:typewriter, description = Ukraine
- { "ua", "typewriter", Qt::LeftToRight, QLocale::Ukrainian, QLocale::Ukraine },
- // name = ua:winkeys, description = Ukraine
- { "ua", "winkeys", Qt::LeftToRight, QLocale::Ukrainian, QLocale::Ukraine },
- // name = ua:rstu, description = Ukraine
- { "ua", "rstu", Qt::LeftToRight, QLocale::Ukrainian, QLocale::Ukraine },
- // name = ua:rstu_ru, description = Ukraine
- { "ua", "rstu_ru", Qt::LeftToRight, QLocale::Ukrainian, QLocale::Ukraine },
- // name = gb, description = United Kingdom
- { "gb", "", Qt::LeftToRight, QLocale::English, QLocale::UnitedKingdom },
- // name = gb:intl, description = United Kingdom
- { "gb", "intl", Qt::LeftToRight, QLocale::English, QLocale::UnitedKingdom },
- // name = gb:dvorak, description = United Kingdom
- { "gb", "dvorak", Qt::LeftToRight, QLocale::English, QLocale::UnitedKingdom },
- // name = uz, description = Uzbekistan
- { "uz", "", Qt::LeftToRight, QLocale::Uzbek, QLocale::Uzbekistan },
- // name = vn, description = Vietnam
- { "vn", "", Qt::LeftToRight, QLocale::Vietnamese, QLocale::VietNam },
- // name = nec_vndr/jp, description = PC-98xx Series
- { "nec_vndr/jp", "", Qt::LeftToRight, QLocale::Japanese, QLocale::Japan },
- // name = ie, description = Ireland
- { "ie", "", Qt::LeftToRight, QLocale::Irish, QLocale::Ireland },
- // name = ie:CloGaelach, description = Ireland
- { "ie", "CloGaelach", Qt::LeftToRight, QLocale::Gaelic, QLocale::Ireland },
- // name = ie:UnicodeExpert, description = Ireland
- { "ie", "UnicodeExpert", Qt::LeftToRight, QLocale::Irish, QLocale::Ireland },
- // name = ie:ogam, description = Ireland
- { "ie", "ogam", Qt::LeftToRight, QLocale::Gaelic, QLocale::Ireland },
- // name = ie:ogam_is434, description = Ireland
- { "ie", "ogam_is434", Qt::LeftToRight, QLocale::Gaelic, QLocale::Ireland },
- // name = pk, description = Pakistan
- { "pk", "", Qt::RightToLeft, QLocale::Urdu, QLocale::Pakistan },
- { 0, 0, Qt::LeftToRight, QLocale::C, QLocale::AnyCountry }
-};
diff --git a/src/gui/platforms/x11/qmotifdnd_x11.cpp b/src/gui/platforms/x11/qmotifdnd_x11.cpp
deleted file mode 100644
index eef4cc470b..0000000000
--- a/src/gui/platforms/x11/qmotifdnd_x11.cpp
+++ /dev/null
@@ -1,1031 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/* The following copyright notice pertains to the code as contributed
-to Qt, not to Nokia's modifications. It is replicated
-in doc/dnd.doc, where the documentation system can see it. */
-
-/* Copyright 1996 Daniel Dardailler.
-
- Permission to use, copy, modify, distribute, and sell this software
- for any purpose is hereby granted without fee, provided that the above
- copyright notice appear in all copies and that both that copyright
- notice and this permission notice appear in supporting documentation,
- and that the name of Daniel Dardailler not be used in advertising or
- publicity pertaining to distribution of the software without specific,
- written prior permission. Daniel Dardailler makes no representations
- about the suitability of this software for any purpose. It is
- provided "as is" without express or implied warranty.
-
- Modifications Copyright 1999 Matt Koss, under the same license as
- above.
-************************************************************/
-
-/***********************************************************/
-/* Motif Drag&Drop Dynamic Protocol messaging API code */
-/* Only requires Xlib layer - not MT safe */
-/* Author: Daniel Dardailler, daniel@x.org */
-/* Adapted by: Matt Koss, koss@napri.sk */
-/* Further adaptions by: Nokia Corporation and/or its subsidiary(-ies) */
-/***********************************************************/
-
-#include "qplatformdefs.h"
-
-#include "qapplication.h"
-
-#ifndef QT_NO_DRAGANDDROP
-
-#include "qdebug.h"
-#include "qtextcodec.h"
-#include "qwidget.h"
-#include "qevent.h"
-#include "qt_x11_p.h"
-#include "qx11info_x11.h"
-#include "qiodevice.h"
-#include "qdnd_p.h"
-
-#include <stdlib.h>
-
-QT_BEGIN_NAMESPACE
-
-static Window sourceWindow = XNone;
-static QWidget *dropWidget = 0;
-static Qt::DropAction lastAcceptedAction = Qt::IgnoreAction;
-
-static Atom Dnd_selection = 0;
-static Time Dnd_selection_time;
-
-static Atom * src_targets ;
-static ushort num_src_targets ;
-
-// Motif definitions
-#define DndVersion 1
-#define DndRevision 0
-#define DndIncludeVersion (DndVersion * 10 + DndRevision)
-
-/* The following values are used in the DndData structure */
-
-/* protocol style */
-#define DND_DRAG_NONE 0
-#define DND_DRAG_DROP_ONLY 1
-#define DND_DRAG_DYNAMIC 5
-
-/* message type */
-#define DND_TOP_LEVEL_ENTER 0
-#define DND_TOP_LEVEL_LEAVE 1
-#define DND_DRAG_MOTION 2
-#define DND_DROP_SITE_ENTER 3
-#define DND_DROP_SITE_LEAVE 4
-#define DND_DROP_START 5
-#define DND_OPERATION_CHANGED 8
-
-/* operation(s) */
-#define DND_NOOP 0L
-#define DND_MOVE (1L << 0)
-#define DND_COPY (1L << 1)
-#define DND_LINK (1L << 2)
-
-static Qt::DropActions DndOperationsToQtDropActions(uchar op)
-{
- Qt::DropActions actions = Qt::IgnoreAction;
- if (op | DND_MOVE)
- actions |= Qt::MoveAction;
- if (op | DND_COPY)
- actions |= Qt::CopyAction;
- if (op | DND_LINK)
- actions |= Qt::LinkAction;
- return actions;
-}
-
-static uchar QtDropActionToDndOperation(Qt::DropAction action)
-{
- switch (action & Qt::ActionMask) {
- case Qt::CopyAction:
- default:
- return DND_COPY;
- case Qt::MoveAction:
- return DND_MOVE;
- case Qt::LinkAction:
- return DND_LINK;
- }
-}
-
-
-/* status */
-#define DND_NO_DROP_SITE 1
-#define DND_INVALID_DROP_SITE 2
-#define DND_VALID_DROP_SITE 3
-
-/* completion */
-#define DND_DROP 0
-#define DND_DROP_HELP 1
-#define DND_DROP_CANCEL 2
-
-#define BYTE unsigned char
-#define CARD32 unsigned int
-#define CARD16 unsigned short
-#define INT16 signed short
-
-/* Client side structure used in the API */
-typedef struct {
- unsigned char reason; /* message type: DND_TOP_LEVEL_ENTER, etc */
- Time time ;
- unsigned char operation;
- unsigned char operations;
- unsigned char status;
- unsigned char completion;
- short x ;
- short y ;
- Window src_window ;
- Atom property ;
-} DndData ;
-
-
-typedef struct _DndSrcProp {
- BYTE byte_order ;
- BYTE protocol_version ;
- CARD16 target_index ;
- CARD32 selection ;
-} DndSrcProp ;
-
-typedef struct _DndReceiverProp {
- BYTE byte_order ;
- BYTE protocol_version ;
- BYTE protocol_style ;
- BYTE pad1;
- CARD32 proxy_window;
- CARD16 num_drop_sites ;
- CARD16 pad2;
- CARD32 total_size;
-} DndReceiverProp ;
-
-/* need to use some union hack since window and property are in
- different order depending on the message ... */
-typedef struct _DndTop {
- CARD32 src_window;
- CARD32 property;
-} DndTop ;
-
-typedef struct _DndPot {
- INT16 x;
- INT16 y;
- CARD32 property;
- CARD32 src_window;
-} DndPot ;
-
-typedef struct _DndMessage {
- BYTE reason;
- BYTE byte_order;
- CARD16 flags;
- CARD32 time;
- union {
- DndTop top ;
- DndPot pot ;
- } data ;
-} DndMessage ;
-
-typedef struct {
- BYTE byte_order;
- BYTE protocol_version;
- CARD16 num_target_lists;
- CARD32 data_size;
- /* then come series of CARD16,CARD32,CARD32,CARD32... */
-} DndTargets;
-
-
-/* protocol version */
-#define DND_PROTOCOL_VERSION 0
-
-
-#define DND_EVENT_TYPE_MASK ((BYTE)0x80)
-#define DND_EVENT_TYPE_SHIFT 7
-#define DND_CLEAR_EVENT_TYPE ((BYTE)0x7F)
-
-/* message_type is data[0] of the client_message
- this return 1 (receiver bit up) or 0 (initiator) */
-#define DND_GET_EVENT_TYPE(message_type) \
-((char) (((message_type) & DND_EVENT_TYPE_MASK) >> DND_EVENT_TYPE_SHIFT))
-
-/* event_type can be 0 (initiator) or 1 (receiver) */
-#define DND_SET_EVENT_TYPE(event_type) \
-(((BYTE)(event_type) << DND_EVENT_TYPE_SHIFT) & DND_EVENT_TYPE_MASK)
-
-
-#define DND_OPERATION_MASK ((CARD16) 0x000F)
-#define DND_OPERATION_SHIFT 0
-#define DND_STATUS_MASK ((CARD16) 0x00F0)
-#define DND_STATUS_SHIFT 4
-#define DND_OPERATIONS_MASK ((CARD16) 0x0F00)
-#define DND_OPERATIONS_SHIFT 8
-#define DND_COMPLETION_MASK ((CARD16) 0xF000)
-#define DND_COMPLETION_SHIFT 12
-
-#define DND_GET_OPERATION(flags) \
-((unsigned char) \
-(((flags) & DND_OPERATION_MASK) >> DND_OPERATION_SHIFT))
-
-#define DND_SET_OPERATION(operation) \
-(((CARD16)(operation) << DND_OPERATION_SHIFT)\
-& DND_OPERATION_MASK)
-
-#define DND_GET_STATUS(flags) \
-((unsigned char) \
-(((flags) & DND_STATUS_MASK) >> DND_STATUS_SHIFT))
-
-#define DND_SET_STATUS(status) \
-(((CARD16)(status) << DND_STATUS_SHIFT)\
-& DND_STATUS_MASK)
-
-#define DND_GET_OPERATIONS(flags) \
-((unsigned char) \
-(((flags) & DND_OPERATIONS_MASK) >> DND_OPERATIONS_SHIFT))
-
-#define DND_SET_OPERATIONS(operation) \
-(((CARD16)(operation) << DND_OPERATIONS_SHIFT)\
-& DND_OPERATIONS_MASK)
-
-#define DND_GET_COMPLETION(flags) \
-((unsigned char) \
-(((flags) & DND_COMPLETION_MASK) >> DND_COMPLETION_SHIFT))
-
-#define DND_SET_COMPLETION(completion) \
-(((CARD16)(completion) << DND_COMPLETION_SHIFT)\
-& DND_COMPLETION_MASK)
-
-
-#define SWAP4BYTES(l) {\
-struct { unsigned t :32;} bit32;\
-char n, *tp = (char *) &bit32;\
-bit32.t = l;\
-n = tp[0]; tp[0] = tp[3]; tp[3] = n;\
-n = tp[1]; tp[1] = tp[2]; tp[2] = n;\
-l = bit32.t;\
-}
-
-#define SWAP2BYTES(s) {\
-struct { unsigned t :16; } bit16;\
-char n, *tp = (char *) &bit16;\
-bit16.t = s;\
-n = tp[0]; tp[0] = tp[1]; tp[1] = n;\
-s = bit16.t;\
-}
-
-
-/** Private extern functions */
-
-static unsigned char DndByteOrder ();
-
-
-/***** Targets/Index stuff */
-
-typedef struct {
- int num_targets;
- Atom *targets;
-} DndTargetsTableEntryRec, * DndTargetsTableEntry;
-
-typedef struct {
- int num_entries;
- DndTargetsTableEntry entries;
-} DndTargetsTableRec, * DndTargetsTable;
-
-
-static ushort _DndIndexToTargets(Display * display,
- int index,
- Atom ** targets);
-
-extern void qt_x11_intern_atom(const char *, Atom *);
-
-/////////////////////////////////////////////////////////////////
-
-static unsigned char DndByteOrder ()
-{
- static unsigned char byte_order = 0;
-
- if (!byte_order) {
- unsigned int endian = 1;
- byte_order = (*((char *)&endian))?'l':'B';
- }
- return byte_order ;
-}
-
-
-
-static void DndReadSourceProperty(Display * dpy,
- Window window, Atom dnd_selection,
- Atom ** targets, unsigned short * num_targets)
-{
- unsigned char *retval = 0;
- Atom type ;
- int format ;
- unsigned long bytesafter, lengthRtn;
-
- if ((XGetWindowProperty (dpy, window, dnd_selection, 0L, 100000L,
- False, ATOM(_MOTIF_DRAG_INITIATOR_INFO), &type,
- &format, &lengthRtn, &bytesafter,
- &retval) != Success)
- || (type == XNone)) {
- *num_targets = 0;
- return ;
- }
-
- DndSrcProp * src_prop = (DndSrcProp *)retval;
-
- if (src_prop->byte_order != DndByteOrder()) {
- SWAP2BYTES(src_prop->target_index);
- SWAP4BYTES(src_prop->selection);
- }
-
- *num_targets = _DndIndexToTargets(dpy, src_prop->target_index, targets);
-
- XFree((char*)src_prop);
-}
-
-
-/* Position the _MOTIF_DRAG_RECEIVER_INFO property on the dropsite window.
- Called by the receiver of the drop to indicate the
- supported protocol style : dynamic, drop_only or none */
-static void DndWriteReceiverProperty(Display * dpy, Window window,
- unsigned char protocol_style)
-{
- DndReceiverProp receiver_prop;
-
- // squelch potential valgrind errors about uninitialized reads
- memset(&receiver_prop, 0, sizeof(receiver_prop));
-
- receiver_prop.byte_order = DndByteOrder() ;
- receiver_prop.protocol_version = DND_PROTOCOL_VERSION;
- receiver_prop.protocol_style = protocol_style ;
- receiver_prop.proxy_window = XNone ;
- receiver_prop.num_drop_sites = 0 ;
- receiver_prop.total_size = sizeof(DndReceiverProp);
-
- /* write the buffer to the property */
- XChangeProperty (dpy, window, ATOM(_MOTIF_DRAG_RECEIVER_INFO), ATOM(_MOTIF_DRAG_RECEIVER_INFO),
- 8, PropModeReplace,
- (unsigned char *)&receiver_prop,
- sizeof(DndReceiverProp));
-}
-
-
-/* protocol style equiv (preregister stuff really) */
-#define DND_DRAG_DROP_ONLY_EQUIV 3
-#define DND_DRAG_DYNAMIC_EQUIV1 2
-#define DND_DRAG_DYNAMIC_EQUIV2 4
-
-
-/* Produce a client message to be sent by the caller */
-static void DndFillClientMessage(Display * dpy, Window window,
- XClientMessageEvent *cm,
- DndData * dnd_data,
- char receiver)
-{
- DndMessage * dnd_message = (DndMessage*)&cm->data.b[0] ;
-
- cm->display = dpy;
- cm->type = ClientMessage;
- cm->serial = LastKnownRequestProcessed(dpy);
- cm->send_event = True;
- cm->window = window;
- cm->format = 8;
- cm->message_type = ATOM(_MOTIF_DRAG_AND_DROP_MESSAGE);
-
- dnd_message->reason = dnd_data->reason | DND_SET_EVENT_TYPE(receiver);
-
- dnd_message->byte_order = DndByteOrder();
-
- /* we're filling in flags with more stuff that necessary,
- depending on the reason, but it doesn't matter */
- dnd_message->flags = 0 ;
- dnd_message->flags |= DND_SET_STATUS(dnd_data->status) ;
- dnd_message->flags |= DND_SET_OPERATION(dnd_data->operation) ;
- dnd_message->flags |= DND_SET_OPERATIONS(dnd_data->operations) ;
- dnd_message->flags |= DND_SET_COMPLETION(dnd_data->completion) ;
-
- dnd_message->time = dnd_data->time ;
-
- switch(dnd_data->reason) {
- case DND_DROP_SITE_LEAVE: break ;
- case DND_TOP_LEVEL_ENTER:
- case DND_TOP_LEVEL_LEAVE:
- dnd_message->data.top.src_window = dnd_data->src_window ;
- dnd_message->data.top.property = dnd_data->property ;
- break ; /* cannot fall through since the byte layout is different in
- both set of messages, see top and pot union stuff */
-
- case DND_DRAG_MOTION:
- case DND_OPERATION_CHANGED:
- case DND_DROP_SITE_ENTER:
- case DND_DROP_START:
- dnd_message->data.pot.x = dnd_data->x ; /* mouse position */
- dnd_message->data.pot.y = dnd_data->y ;
- dnd_message->data.pot.src_window = dnd_data->src_window ;
- dnd_message->data.pot.property = dnd_data->property ;
- break ;
- default:
- break ;
- }
-
-}
-
-static Bool DndParseClientMessage(XClientMessageEvent *cm, DndData * dnd_data,
- char * receiver)
-{
- DndMessage * dnd_message = (DndMessage*)&cm->data.b[0] ;
-
- if (cm->message_type != ATOM(_MOTIF_DRAG_AND_DROP_MESSAGE)) {
- return False ;
- }
-
- if (dnd_message->byte_order != DndByteOrder()) {
- SWAP2BYTES(dnd_message->flags);
- SWAP4BYTES(dnd_message->time);
- } /* do the rest in the switch */
-
- dnd_data->reason = dnd_message->reason ;
- if (DND_GET_EVENT_TYPE(dnd_data->reason))
- *receiver = 1 ;
- else
- *receiver = 0 ;
- dnd_data->reason &= DND_CLEAR_EVENT_TYPE ;
-
- dnd_data->time = dnd_message->time ;
-
- /* we're reading in more stuff that necessary. but who cares */
- dnd_data->status = DND_GET_STATUS(dnd_message->flags) ;
- dnd_data->operation = DND_GET_OPERATION(dnd_message->flags) ;
- dnd_data->operations = DND_GET_OPERATIONS(dnd_message->flags) ;
- dnd_data->completion = DND_GET_COMPLETION(dnd_message->flags) ;
-
- switch(dnd_data->reason) {
- case DND_TOP_LEVEL_ENTER:
- case DND_TOP_LEVEL_LEAVE:
- if (dnd_message->byte_order != DndByteOrder()) {
- SWAP4BYTES(dnd_message->data.top.src_window);
- SWAP4BYTES(dnd_message->data.top.property);
- }
- dnd_data->src_window = dnd_message->data.top.src_window ;
- dnd_data->property = dnd_message->data.top.property ;
- break ; /* cannot fall through, see above comment in write msg */
-
- case DND_DRAG_MOTION:
- case DND_OPERATION_CHANGED:
- case DND_DROP_SITE_ENTER:
- case DND_DROP_START:
- if (dnd_message->byte_order != DndByteOrder()) {
- SWAP2BYTES(dnd_message->data.pot.x);
- SWAP2BYTES(dnd_message->data.pot.y);
- SWAP4BYTES(dnd_message->data.pot.property);
- SWAP4BYTES(dnd_message->data.pot.src_window);
- }
- dnd_data->x = dnd_message->data.pot.x ;
- dnd_data->y = dnd_message->data.pot.y ;
- dnd_data->property = dnd_message->data.pot.property ;
- dnd_data->src_window = dnd_message->data.pot.src_window ;
- break ;
-
- case DND_DROP_SITE_LEAVE:
- break;
- default:
- break ;
- }
-
- return True ;
-}
-
-
-static Window MotifWindow(Display *display)
-{
- Atom type;
- int format;
- unsigned long size;
- unsigned long bytes_after;
- unsigned char *property = 0;
- Window motif_window ;
-
- /* this version does no caching, so it's slow: round trip each time */
-
- if ((XGetWindowProperty (display, RootWindow(display, 0),
- ATOM(_MOTIF_DRAG_WINDOW),
- 0L, 100000L, False, AnyPropertyType,
- &type, &format, &size, &bytes_after,
- &property) == Success) &&
- (type != XNone)) {
- motif_window = *(Window *)property;
- } else {
- XSetWindowAttributes sAttributes;
-
- /* really, this should be done on a separate connection,
- with XSetCloseDownMode (RetainPermanent), so that
- others don't have to recreate it; hopefully, some real
- Motif application will be around to do it */
-
- sAttributes.override_redirect = True;
- sAttributes.event_mask = PropertyChangeMask;
- motif_window = XCreateWindow (display,
- RootWindow (display, 0),
- -170, -560, 1, 1, 0, 0,
- InputOnly, CopyFromParent,
- (CWOverrideRedirect |CWEventMask),
- &sAttributes);
- XMapWindow (display, motif_window);
- }
-
- if (property) {
- XFree ((char *)property);
- }
-
- return (motif_window);
-}
-
-
-static DndTargetsTable TargetsTable(Display *display)
-{
- Atom type;
- int format;
- unsigned long size;
- unsigned long bytes_after;
- Window motif_window = MotifWindow(display) ;
- unsigned char *retval;
- DndTargetsTable targets_table ;
- int i,j ;
- char * target_data ;
-
- /* this version does no caching, so it's slow: round trip each time */
- /* ideally, register for property notify on this target_list
- atom and update when necessary only */
-
- if ((XGetWindowProperty (display, motif_window,
- ATOM(_MOTIF_DRAG_TARGETS), 0L, 100000L,
- False, ATOM(_MOTIF_DRAG_TARGETS),
- &type, &format, &size, &bytes_after,
- &retval) != Success) ||
- type == XNone) {
- qWarning("QMotifDND: Cannot get property on Motif window");
- return 0;
- }
-
- DndTargets * target_prop = (DndTargets *)retval;
-
- if (target_prop->protocol_version != DND_PROTOCOL_VERSION) {
- qWarning("QMotifDND: Protocol mismatch");
- }
-
- if (target_prop->byte_order != DndByteOrder()) {
- /* need to swap num_target_lists and size */
- SWAP2BYTES(target_prop->num_target_lists);
- SWAP4BYTES(target_prop->data_size);
- }
-
- /* now parse DndTarget prop data in a TargetsTable */
-
- targets_table = (DndTargetsTable)malloc(sizeof(DndTargetsTableRec));
- targets_table->num_entries = target_prop->num_target_lists ;
- targets_table->entries = (DndTargetsTableEntry)
- malloc(sizeof(DndTargetsTableEntryRec) * target_prop->num_target_lists);
-
- target_data = (char*)target_prop + sizeof(*target_prop) ;
-
- for (i = 0 ; i < targets_table->num_entries; i++) {
- CARD16 num_targets ;
- CARD32 atom ;
-
- memcpy(&num_targets, target_data, 2);
- target_data += 2;
-
- /* potential swap needed here */
- if (target_prop->byte_order != DndByteOrder())
- SWAP2BYTES(num_targets);
-
- targets_table->entries[i].num_targets = num_targets ;
- targets_table->entries[i].targets = (Atom *)
- malloc(sizeof(Atom) * targets_table->entries[i].num_targets);
-
-
- for (j = 0; j < num_targets; j++) {
- memcpy(&atom, target_data, 4);
- target_data += 4;
-
- /* another potential swap needed here */
- if (target_prop->byte_order != DndByteOrder())
- SWAP4BYTES(atom);
-
- targets_table->entries[i].targets[j] = (Atom) atom ;
- }
- }
-
- if (target_prop) {
- XFree((char *)target_prop);
- }
-
- return targets_table ;
-}
-
-
-static ushort _DndIndexToTargets(Display * display,
- int index,
- Atom ** targets)
-{
- DndTargetsTable targets_table;
- int i ;
-
- /* again, slow: no caching here, alloc/free each time */
-
- if (!(targets_table = TargetsTable (display)) ||
- (index >= targets_table->num_entries)) {
- if (targets_table)
- XFree((char*)targets_table);
- return 0;
- }
-
- /* transfer the correct target list index */
- *targets = (Atom*)malloc(sizeof(Atom)*targets_table->
- entries[index].num_targets);
- memcpy((char*)*targets,
- (char*)targets_table->entries[index].targets,
- sizeof(Atom)*targets_table->entries[index].num_targets);
-
- /* free the target table and its guts */
- for (i=0 ; i < targets_table->num_entries; i++)
- XFree((char*)targets_table->entries[i].targets);
-
- int tmp = targets_table->entries[index].num_targets;
- XFree((char*)targets_table);
-
- return tmp; // targets_table->entries[index].num_targets;
-}
-
-
-QByteArray QX11Data::motifdndFormat(int n)
-{
- if (!motifdnd_active)
- return 0; // should not happen
-
- if (n >= num_src_targets)
- return 0;
-
- Atom target = src_targets[n];
-
- if (target == XA_STRING)
- return "text/plain;charset=ISO-8859-1";
- if (target == ATOM(UTF8_STRING))
- return "text/plain;charset=UTF-8";
- if (target == ATOM(COMPOUND_TEXT))
- return QByteArray("text/plain;charset=") + QTextCodec::codecForLocale()->name();
- if (target == ATOM(TEXT))
- return "text/plain";
-
- return ("x-motif-dnd/" + X11->xdndAtomToString(target));
-}
-
-
-QVariant QX11Data::motifdndObtainData(const char *mimeType)
-{
- QByteArray result;
-
- if (Dnd_selection == 0 || !dropWidget)
- return result;
-
- // try to convert the selection to the requested property
- // qDebug("trying to convert to '%s'", mimeType);
-
- int n=0;
- QByteArray f;
- do {
- f = motifdndFormat(n);
- if (f.isEmpty())
- return result;
- n++;
- } while(qstricmp(mimeType, f.data()));
-
- Atom conversion_type = XNone;
- if (f == "text/plain;charset=ISO-8859-1") {
- conversion_type = XA_STRING;
- } else if (f == "text/plain;charset=UTF-8") {
- conversion_type = ATOM(UTF8_STRING);
- } else if (f == (QByteArray("text/plain;charset=") + QTextCodec::codecForLocale()->name())) {
- conversion_type = ATOM(COMPOUND_TEXT);
- } else if (f == "text/plain") {
- conversion_type = ATOM(TEXT);
- } else if (f.startsWith("x-motif-dnd/")) {
- // strip off the "x-motif-dnd/" prefix
- conversion_type = X11->xdndStringToAtom(f.remove(0, 12));
- }
-
- if (XGetSelectionOwner(X11->display, Dnd_selection) == XNone) {
- return result; // should never happen?
- }
-
- QWidget* tw = dropWidget;
- if ((dropWidget->windowType() == Qt::Desktop)) {
- tw = new QWidget;
- }
-
- // convert selection to the appropriate type
- XConvertSelection (X11->display, Dnd_selection, conversion_type,
- Dnd_selection, tw->internalWinId(), Dnd_selection_time);
-
- XFlush(X11->display);
-
- XEvent xevent;
- bool got=X11->clipboardWaitForEvent(tw->internalWinId(), SelectionNotify, &xevent, 5000);
- if (got) {
- Atom type;
-
- if (X11->clipboardReadProperty(tw->internalWinId(), Dnd_selection, true, &result, 0, &type, 0)) {
- }
- }
-
- // we have to convert selection in order to indicate success to the initiator
- XConvertSelection (X11->display, Dnd_selection, ATOM(XmTRANSFER_SUCCESS),
- Dnd_selection, tw->internalWinId(), Dnd_selection_time);
-
- // wait again for SelectionNotify event
- X11->clipboardWaitForEvent(tw->internalWinId(), SelectionNotify, &xevent, 5000);
-
- if ((dropWidget->windowType() == Qt::Desktop)) {
- delete tw;
- }
-
- return result;
-}
-
-
-void QX11Data::motifdndEnable(QWidget *widget, bool)
-{
- DndWriteReceiverProperty(display, widget->internalWinId(), DND_DRAG_DYNAMIC);
-}
-
-
-void QX11Data::motifdndHandle(QWidget *widget, const XEvent * xe, bool /* passive */)
-{
- XEvent event = *xe;
- XClientMessageEvent cm ;
- DndData dnd_data ;
- char receiver ;
-
- if (!(DndParseClientMessage ((XClientMessageEvent*)&event,
- &dnd_data, &receiver))) {
- return;
- }
-
- switch (dnd_data.reason) {
-
- case DND_DRAG_MOTION:
- {
- QPoint p = widget->mapFromGlobal(QPoint(dnd_data.x, dnd_data.y));
- QWidget *c = widget->childAt(p);
-
- if (!c || !c->acceptDrops()) {
- // not over a drop site
- if (dropWidget) {
- QDragLeaveEvent dragLeaveEvent;
- QApplication::sendEvent(dropWidget, &dragLeaveEvent);
-
- dropWidget = 0;
- lastAcceptedAction = Qt::IgnoreAction;
-
- dnd_data.reason = DND_DROP_SITE_LEAVE;
- dnd_data.time = X11->time;
- DndFillClientMessage (event.xclient.display, sourceWindow, &cm, &dnd_data, receiver);
- XSendEvent(event.xbutton.display, sourceWindow, False, 0, (XEvent *)&cm) ;
- } else {
- dnd_data.reason = DND_DRAG_MOTION;
- dnd_data.status = DND_NO_DROP_SITE;
- dnd_data.time = X11->time;
- dnd_data.operation = DND_NOOP;
- dnd_data.operations = DND_NOOP;
- DndFillClientMessage (event.xclient.display, sourceWindow, &cm, &dnd_data, receiver);
- XSendEvent(event.xbutton.display, sourceWindow, False, 0, (XEvent *)&cm) ;
- }
- } else {
- Q_ASSERT(c != 0);
- p = c->mapFrom(widget, p);
-
- if (dropWidget != c) {
- if (dropWidget) {
- QDragLeaveEvent le;
- QApplication::sendEvent(dropWidget, &le);
- }
-
- dropWidget = c;
- lastAcceptedAction = Qt::IgnoreAction;
-
- const Qt::DropActions possibleActions =
- DndOperationsToQtDropActions(dnd_data.operations);
- QDragEnterEvent de(p, possibleActions, QDragManager::self()->dropData,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- QApplication::sendEvent(dropWidget, &de);
-
- dnd_data.reason = DND_DROP_SITE_ENTER;
- dnd_data.time = X11->time;
- if (de.isAccepted()) {
- lastAcceptedAction = de.dropAction();
-
- dnd_data.status = DND_VALID_DROP_SITE;
- dnd_data.operation = QtDropActionToDndOperation(lastAcceptedAction);
- } else {
- dnd_data.status = DND_INVALID_DROP_SITE;
- dnd_data.operation = DND_NOOP;
- dnd_data.operations = DND_NOOP;
- }
- DndFillClientMessage (event.xclient.display, sourceWindow, &cm, &dnd_data, receiver);
- XSendEvent(event.xbutton.display, sourceWindow, False, 0, (XEvent *)&cm);
- } else {
- const Qt::DropActions possibleActions =
- DndOperationsToQtDropActions(dnd_data.operations);
- QDragMoveEvent me(p, possibleActions, QDragManager::self()->dropData,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- if (lastAcceptedAction != Qt::IgnoreAction) {
- me.setDropAction(lastAcceptedAction);
- me.accept();
- }
- QApplication::sendEvent(dropWidget, &me);
-
- dnd_data.reason = DND_DRAG_MOTION;
- dnd_data.time = X11->time;
-
- if (me.isAccepted()) {
- lastAcceptedAction = me.dropAction();
-
- dnd_data.status = DND_VALID_DROP_SITE;
- dnd_data.operation = QtDropActionToDndOperation(lastAcceptedAction);
- } else {
- dnd_data.status = DND_INVALID_DROP_SITE;
- dnd_data.operation = DND_NOOP;
- dnd_data.operations = DND_NOOP;
- }
-
- DndFillClientMessage (event.xclient.display, sourceWindow, &cm, &dnd_data, receiver);
- XSendEvent(event.xbutton.display, sourceWindow, False, 0, (XEvent *)&cm);
- }
- }
-
- break;
- }
-
- case DND_TOP_LEVEL_ENTER:
- {
- /* get the size of our drop site for later use */
-
- motifdnd_active = true;
- sourceWindow = dnd_data.src_window;
-
- /* no answer needed, just read source property */
- DndReadSourceProperty (event.xclient.display,
- sourceWindow,
- dnd_data.property,
- &src_targets, &num_src_targets);
-
- break;
- }
-
- case DND_TOP_LEVEL_LEAVE:
- {
- XEvent nextEvent;
- if (XCheckTypedWindowEvent(X11->display, widget->winId(), ClientMessage, &nextEvent)) {
- // we just want to check, not eat (should use XPeekIfEvent)
- XPutBackEvent(X11->display, &nextEvent);
-
- if (DndParseClientMessage (&nextEvent.xclient, &dnd_data, &receiver)
- && dnd_data.reason == DND_DROP_START) {
- // expecting drop next, keeping DnD alive
- break;
- }
- }
-
- // not expecting drop, need to send drag leave events and such here
- if (dropWidget) {
- QDragLeaveEvent le;
- QApplication::sendEvent(dropWidget, &le);
- }
-
- sourceWindow = XNone;
- dropWidget = 0;
- lastAcceptedAction = Qt::IgnoreAction;
-
- motifdnd_active = false;
-
- break;
- }
-
- case DND_OPERATION_CHANGED:
- // ### need to echo
- break;
-
- case DND_DROP_START:
- {
- Q_ASSERT(motifdnd_active);
- Q_ASSERT(sourceWindow == dnd_data.src_window);
-
- if (!dropWidget || lastAcceptedAction == Qt::IgnoreAction) {
- // echo DROP_START
- dnd_data.reason = DND_DROP_START;
- dnd_data.status = DND_NO_DROP_SITE;
- dnd_data.operation = DND_NOOP;
- dnd_data.operations = DND_NOOP;
- DndFillClientMessage (event.xclient.display, sourceWindow, &cm, &dnd_data, 0);
- XSendEvent(event.xbutton.display, sourceWindow, False, 0, (XEvent *)&cm);
-
- // we have to convert selection in order to indicate failure to the initiator
- XConvertSelection (X11->display, dnd_data.property, ATOM(XmTRANSFER_FAILURE),
- dnd_data.property, dnd_data.src_window, dnd_data.time);
-
- if (dropWidget) {
- QDragLeaveEvent e;
- QApplication::sendEvent(dropWidget, &e);
- }
-
- motifdnd_active = false;
- sourceWindow = XNone;
- dropWidget = 0;
- lastAcceptedAction = Qt::IgnoreAction;
-
- return;
- }
-
- // store selection and its time
- Dnd_selection = dnd_data.property;
- Dnd_selection_time = dnd_data.time;
-
- QPoint p(dnd_data.x, dnd_data.y);
- QDropEvent de(dropWidget->mapFromGlobal(p), Qt::CopyAction, QDragManager::self()->dropData,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- if (lastAcceptedAction != Qt::IgnoreAction) {
- de.setDropAction(lastAcceptedAction);
- de.accept();
- }
- QApplication::sendEvent(dropWidget, &de);
-
- // reset
- Dnd_selection = XNone;
- Dnd_selection_time = 0;
-
- // echo DROP_START depending on the result of the dropEvent
- if (de.isAccepted()) {
- dnd_data.reason = DND_DROP_START;
- dnd_data.status = DND_VALID_DROP_SITE;
- dnd_data.operation = QtDropActionToDndOperation(de.dropAction());
- } else {
- dnd_data.reason = DND_DROP_START;
- dnd_data.status = DND_NO_DROP_SITE;
- dnd_data.operation = DND_NOOP;
- dnd_data.operations = DND_NOOP;
- }
- DndFillClientMessage (event.xclient.display, sourceWindow, &cm, &dnd_data, 0);
- XSendEvent(event.xbutton.display, sourceWindow, False, 0, (XEvent *)&cm);
-
- sourceWindow = XNone;
- dropWidget = 0;
- lastAcceptedAction = Qt::IgnoreAction;
-
- motifdnd_active = false;
-
- break;
- }
-
- default:
- break;
- } // end of switch (dnd_data.reason)
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DRAGANDDROP
diff --git a/src/gui/platforms/x11/qpaintdevice_x11.cpp b/src/gui/platforms/x11/qpaintdevice_x11.cpp
deleted file mode 100644
index 690dea99d7..0000000000
--- a/src/gui/platforms/x11/qpaintdevice_x11.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpaintdevice.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qapplication.h"
-#include <private/qt_x11_p.h>
-#include "qx11info_x11.h"
-
-QT_BEGIN_NAMESPACE
-
-/*! \internal
-
- Returns the X11 Drawable of the paint device. 0 is returned if it
- can't be obtained.
-*/
-
-Drawable Q_GUI_EXPORT qt_x11Handle(const QPaintDevice *pd)
-{
- if (!pd) return 0;
- if (pd->devType() == QInternal::Widget)
- return static_cast<const QWidget *>(pd)->handle();
- else if (pd->devType() == QInternal::Pixmap)
- return static_cast<const QPixmap *>(pd)->handle();
- return 0;
-}
-
-/*!
- \relates QPaintDevice
-
- Returns the QX11Info structure for the \a pd paint device. 0 is
- returned if it can't be obtained.
-*/
-const Q_GUI_EXPORT QX11Info *qt_x11Info(const QPaintDevice *pd)
-{
- if (!pd) return 0;
- if (pd->devType() == QInternal::Widget)
- return &static_cast<const QWidget *>(pd)->x11Info();
- else if (pd->devType() == QInternal::Pixmap)
- return &static_cast<const QPixmap *>(pd)->x11Info();
- return 0;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qpaintengine_x11.cpp b/src/gui/platforms/x11/qpaintengine_x11.cpp
deleted file mode 100644
index 1256996491..0000000000
--- a/src/gui/platforms/x11/qpaintengine_x11.cpp
+++ /dev/null
@@ -1,2507 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qpixmap_x11_p.h"
-
-#include "qapplication.h"
-#include "qdebug.h"
-#include "qfont.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qpixmapcache.h"
-#include "qtextcodec.h"
-#include "qcoreevent.h"
-#include "qiodevice.h"
-#include <qmath.h>
-
-#include "qpainter_p.h"
-#include <qtextlayout.h>
-#include <qvarlengtharray.h>
-#include <private/qfont_p.h>
-#include <private/qtextengine_p.h>
-#include <private/qpaintengine_x11_p.h>
-#include <private/qfontengine_x11_p.h>
-#include <private/qwidget_p.h>
-#include <private/qpainterpath_p.h>
-
-#include "qpen.h"
-#include "qcolor.h"
-#include "qcolormap.h"
-
-#include <private/qpaintengine_p.h>
-#include "qpaintengine_x11_p.h"
-
-#include <private/qt_x11_p.h>
-#include <private/qnumeric_p.h>
-#include <limits.h>
-
-#ifndef QT_NO_XRENDER
-#include <private/qtessellator_p.h>
-#endif
-
-#include <private/qhexstring_p.h>
-
-QT_BEGIN_NAMESPACE
-
-extern Drawable qt_x11Handle(const QPaintDevice *pd);
-extern const QX11Info *qt_x11Info(const QPaintDevice *pd);
-extern QPixmap qt_pixmapForBrush(int brushStyle, bool invert); //in qbrush.cpp
-extern QPixmap qt_toX11Pixmap(const QPixmap &pixmap);
-
-// use the same rounding as in qrasterizer.cpp (6 bit fixed point)
-static const qreal aliasedCoordinateDelta = 0.5 - 0.015625;
-
-#undef X11 // defined in qt_x11_p.h
-/*!
- Returns the X11 specific pen GC for the painter \a p. Note that
- QPainter::begin() must be called before this function returns a
- valid GC.
-*/
-Q_GUI_EXPORT GC qt_x11_get_pen_gc(QPainter *p)
-{
- if (p && p->paintEngine()
- && p->paintEngine()->isActive()
- && p->paintEngine()->type() == QPaintEngine::X11) {
- return static_cast<QX11PaintEngine *>(p->paintEngine())->d_func()->gc;
- }
- return 0;
-}
-
-/*!
- Returns the X11 specific brush GC for the painter \a p. Note that
- QPainter::begin() must be called before this function returns a
- valid GC.
-*/
-Q_GUI_EXPORT GC qt_x11_get_brush_gc(QPainter *p)
-{
- if (p && p->paintEngine()
- && p->paintEngine()->isActive()
- && p->paintEngine()->type() == QPaintEngine::X11) {
- return static_cast<QX11PaintEngine *>(p->paintEngine())->d_func()->gc_brush;
- }
- return 0;
-}
-#define X11 qt_x11Data
-
-#ifndef QT_NO_XRENDER
-static const int compositionModeToRenderOp[QPainter::CompositionMode_Xor + 1] = {
- PictOpOver, //CompositionMode_SourceOver,
- PictOpOverReverse, //CompositionMode_DestinationOver,
- PictOpClear, //CompositionMode_Clear,
- PictOpSrc, //CompositionMode_Source,
- PictOpDst, //CompositionMode_Destination,
- PictOpIn, //CompositionMode_SourceIn,
- PictOpInReverse, //CompositionMode_DestinationIn,
- PictOpOut, //CompositionMode_SourceOut,
- PictOpOutReverse, //CompositionMode_DestinationOut,
- PictOpAtop, //CompositionMode_SourceAtop,
- PictOpAtopReverse, //CompositionMode_DestinationAtop,
- PictOpXor //CompositionMode_Xor
-};
-
-static inline int qpainterOpToXrender(QPainter::CompositionMode mode)
-{
- Q_ASSERT(mode <= QPainter::CompositionMode_Xor);
- return compositionModeToRenderOp[mode];
-}
-#endif
-
-// hack, so we don't have to make QRegion::clipRectangles() public or include
-// X11 headers in qregion.h
-Q_GUI_EXPORT void *qt_getClipRects(const QRegion &r, int &num)
-{
- return r.clipRectangles(num);
-}
-
-static inline void x11SetClipRegion(Display *dpy, GC gc, GC gc2,
-#ifndef QT_NO_XRENDER
- Picture picture,
-#else
- Qt::HANDLE picture,
-#endif
- const QRegion &r)
-{
- int num;
- XRectangle *rects = (XRectangle *)qt_getClipRects(r, num);
-
- if (gc)
- XSetClipRectangles( dpy, gc, 0, 0, rects, num, YXBanded );
- if (gc2)
- XSetClipRectangles( dpy, gc2, 0, 0, rects, num, YXBanded );
-
-#ifndef QT_NO_XRENDER
- if (picture)
- XRenderSetPictureClipRectangles(dpy, picture, 0, 0, rects, num);
-#else
- Q_UNUSED(picture);
-#endif // QT_NO_XRENDER
-}
-
-
-static inline void x11ClearClipRegion(Display *dpy, GC gc, GC gc2,
-#ifndef QT_NO_XRENDER
- Picture picture
-#else
- Qt::HANDLE picture
-#endif
- )
-{
- if (gc)
- XSetClipMask(dpy, gc, XNone);
- if (gc2)
- XSetClipMask(dpy, gc2, XNone);
-
-#ifndef QT_NO_XRENDER
- if (picture) {
- XRenderPictureAttributes attrs;
- attrs.clip_mask = XNone;
- XRenderChangePicture (dpy, picture, CPClipMask, &attrs);
- }
-#else
- Q_UNUSED(picture);
-#endif // QT_NO_XRENDER
-}
-
-
-#define DITHER_SIZE 16
-static const uchar base_dither_matrix[DITHER_SIZE][DITHER_SIZE] = {
- { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
- { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
- { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
- { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
- { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
- { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
- { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
- { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
- { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
- { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
- { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
- { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
- { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
- { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
- { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
- { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
-};
-
-static QPixmap qt_patternForAlpha(uchar alpha, int screen)
-{
- QPixmap pm;
- QString key = QLatin1Literal("$qt-alpha-brush$")
- % HexString<uchar>(alpha)
- % HexString<int>(screen);
-
- if (!QPixmapCache::find(key, pm)) {
- // #### why not use a mono image here????
- QImage pattern(DITHER_SIZE, DITHER_SIZE, QImage::Format_ARGB32);
- pattern.fill(0xffffffff);
- for (int y = 0; y < DITHER_SIZE; ++y) {
- for (int x = 0; x < DITHER_SIZE; ++x) {
- if (base_dither_matrix[x][y] <= alpha)
- pattern.setPixel(x, y, 0x00000000);
- }
- }
- pm = QBitmap::fromImage(pattern);
- pm.x11SetScreen(screen);
- QPixmapCache::insert(key, pm);
- }
- return pm;
-}
-
-#if !defined(QT_NO_XRENDER)
-
-class QXRenderTessellator : public QTessellator
-{
-public:
- QXRenderTessellator() : traps(0), allocated(0), size(0) {}
- ~QXRenderTessellator() { free(traps); }
- XTrapezoid *traps;
- int allocated;
- int size;
- void addTrap(const Trapezoid &trap);
- QRect tessellate(const QPointF *points, int nPoints, bool winding) {
- size = 0;
- setWinding(winding);
- return QTessellator::tessellate(points, nPoints).toRect();
- }
- void done() {
- if (allocated > 64) {
- free(traps);
- traps = 0;
- allocated = 0;
- }
- }
-};
-
-void QXRenderTessellator::addTrap(const Trapezoid &trap)
-{
- if (size == allocated) {
- allocated = qMax(2*allocated, 64);
- traps = q_check_ptr((XTrapezoid *)realloc(traps, allocated * sizeof(XTrapezoid)));
- }
- traps[size].top = Q27Dot5ToXFixed(trap.top);
- traps[size].bottom = Q27Dot5ToXFixed(trap.bottom);
- traps[size].left.p1.x = Q27Dot5ToXFixed(trap.topLeft->x);
- traps[size].left.p1.y = Q27Dot5ToXFixed(trap.topLeft->y);
- traps[size].left.p2.x = Q27Dot5ToXFixed(trap.bottomLeft->x);
- traps[size].left.p2.y = Q27Dot5ToXFixed(trap.bottomLeft->y);
- traps[size].right.p1.x = Q27Dot5ToXFixed(trap.topRight->x);
- traps[size].right.p1.y = Q27Dot5ToXFixed(trap.topRight->y);
- traps[size].right.p2.x = Q27Dot5ToXFixed(trap.bottomRight->x);
- traps[size].right.p2.y = Q27Dot5ToXFixed(trap.bottomRight->y);
- ++size;
-}
-
-#endif // !defined(QT_NO_XRENDER)
-
-
-#ifndef QT_NO_XRENDER
-static Picture getPatternFill(int screen, const QBrush &b)
-{
- if (!X11->use_xrender)
- return XNone;
-
- XRenderColor color = X11->preMultiply(b.color());
- XRenderColor bg_color;
-
- bg_color = X11->preMultiply(QColor(0, 0, 0, 0));
-
- for (int i = 0; i < X11->pattern_fill_count; ++i) {
- if (X11->pattern_fills[i].screen == screen
- && X11->pattern_fills[i].opaque == false
- && X11->pattern_fills[i].style == b.style()
- && X11->pattern_fills[i].color.alpha == color.alpha
- && X11->pattern_fills[i].color.red == color.red
- && X11->pattern_fills[i].color.green == color.green
- && X11->pattern_fills[i].color.blue == color.blue
- && X11->pattern_fills[i].bg_color.alpha == bg_color.alpha
- && X11->pattern_fills[i].bg_color.red == bg_color.red
- && X11->pattern_fills[i].bg_color.green == bg_color.green
- && X11->pattern_fills[i].bg_color.blue == bg_color.blue)
- return X11->pattern_fills[i].picture;
- }
- // none found, replace one
- int i = qrand() % 16;
-
- if (X11->pattern_fills[i].screen != screen && X11->pattern_fills[i].picture) {
- XRenderFreePicture (X11->display, X11->pattern_fills[i].picture);
- X11->pattern_fills[i].picture = 0;
- }
-
- if (!X11->pattern_fills[i].picture) {
- Pixmap pixmap = XCreatePixmap (X11->display, RootWindow (X11->display, screen), 8, 8, 32);
- XRenderPictureAttributes attrs;
- attrs.repeat = True;
- X11->pattern_fills[i].picture = XRenderCreatePicture (X11->display, pixmap,
- XRenderFindStandardFormat(X11->display, PictStandardARGB32),
- CPRepeat, &attrs);
- XFreePixmap (X11->display, pixmap);
- }
-
- X11->pattern_fills[i].screen = screen;
- X11->pattern_fills[i].color = color;
- X11->pattern_fills[i].bg_color = bg_color;
- X11->pattern_fills[i].opaque = false;
- X11->pattern_fills[i].style = b.style();
-
- XRenderFillRectangle(X11->display, PictOpSrc, X11->pattern_fills[i].picture, &bg_color, 0, 0, 8, 8);
-
- QPixmap pattern(qt_pixmapForBrush(b.style(), true));
- XRenderPictureAttributes attrs;
- attrs.repeat = true;
- XRenderChangePicture(X11->display, pattern.x11PictureHandle(), CPRepeat, &attrs);
-
- Picture fill_fg = X11->getSolidFill(screen, b.color());
- XRenderComposite(X11->display, PictOpOver, fill_fg, pattern.x11PictureHandle(),
- X11->pattern_fills[i].picture,
- 0, 0, 0, 0, 0, 0, 8, 8);
-
- return X11->pattern_fills[i].picture;
-}
-
-static void qt_render_bitmap(Display *dpy, int scrn, Picture src, Picture dst,
- int sx, int sy, int x, int y, int sw, int sh,
- const QPen &pen)
-{
- Picture fill_fg = X11->getSolidFill(scrn, pen.color());
- XRenderComposite(dpy, PictOpOver,
- fill_fg, src, dst, sx, sy, sx, sy, x, y, sw, sh);
-}
-#endif
-
-void QX11PaintEnginePrivate::init()
-{
- dpy = 0;
- scrn = 0;
- hd = 0;
- picture = 0;
- xinfo = 0;
-#ifndef QT_NO_XRENDER
- current_brush = 0;
- composition_mode = PictOpOver;
- tessellator = new QXRenderTessellator;
-#endif
-}
-
-void QX11PaintEnginePrivate::setupAdaptedOrigin(const QPoint &p)
-{
- if (adapted_pen_origin)
- XSetTSOrigin(dpy, gc, p.x(), p.y());
- if (adapted_brush_origin)
- XSetTSOrigin(dpy, gc_brush, p.x(), p.y());
-}
-
-void QX11PaintEnginePrivate::resetAdaptedOrigin()
-{
- if (adapted_pen_origin)
- XSetTSOrigin(dpy, gc, 0, 0);
- if (adapted_brush_origin)
- XSetTSOrigin(dpy, gc_brush, 0, 0);
-}
-
-void QX11PaintEnginePrivate::clipPolygon_dev(const QPolygonF &poly, QPolygonF *clipped_poly)
-{
- int clipped_count = 0;
- qt_float_point *clipped_points = 0;
- polygonClipper.clipPolygon((qt_float_point *) poly.data(), poly.size(),
- &clipped_points, &clipped_count);
- clipped_poly->resize(clipped_count);
- for (int i=0; i<clipped_count; ++i)
- (*clipped_poly)[i] = *((QPointF *)(&clipped_points[i]));
-}
-
-void QX11PaintEnginePrivate::systemStateChanged()
-{
- Q_Q(QX11PaintEngine);
- QPainter *painter = q->state ? static_cast<QPainterState *>(q->state)->painter : 0;
- if (painter && painter->hasClipping()) {
- if (q->testDirty(QPaintEngine::DirtyTransform))
- q->updateMatrix(q->state->transform());
- QPolygonF clip_poly_dev(matrix.map(painter->clipPath().toFillPolygon()));
- QPolygonF clipped_poly_dev;
- clipPolygon_dev(clip_poly_dev, &clipped_poly_dev);
- q->updateClipRegion_dev(QRegion(clipped_poly_dev.toPolygon()), Qt::ReplaceClip);
- } else {
- q->updateClipRegion_dev(QRegion(), Qt::NoClip);
- }
-}
-
-static QPaintEngine::PaintEngineFeatures qt_decide_features()
-{
- QPaintEngine::PaintEngineFeatures features =
- QPaintEngine::PrimitiveTransform
- | QPaintEngine::PatternBrush
- | QPaintEngine::AlphaBlend
- | QPaintEngine::PainterPaths
- | QPaintEngine::RasterOpModes;
-
- if (X11->use_xrender) {
- features |= QPaintEngine::Antialiasing;
- features |= QPaintEngine::PorterDuff;
- features |= QPaintEngine::MaskedBrush;
-#if 0
- if (X11->xrender_version > 10) {
- features |= QPaintEngine::LinearGradientFill;
- // ###
- }
-#endif
- }
-
- return features;
-}
-
-/*
- * QX11PaintEngine members
- */
-
-QX11PaintEngine::QX11PaintEngine()
- : QPaintEngine(*(new QX11PaintEnginePrivate), qt_decide_features())
-{
- d_func()->init();
-}
-
-QX11PaintEngine::QX11PaintEngine(QX11PaintEnginePrivate &dptr)
- : QPaintEngine(dptr, qt_decide_features())
-{
- d_func()->init();
-}
-
-QX11PaintEngine::~QX11PaintEngine()
-{
-#ifndef QT_NO_XRENDER
- Q_D(QX11PaintEngine);
- delete d->tessellator;
-#endif
-}
-
-bool QX11PaintEngine::begin(QPaintDevice *pdev)
-{
- Q_D(QX11PaintEngine);
- d->xinfo = qt_x11Info(pdev);
- QWidget *w = d->pdev->devType() == QInternal::Widget ? static_cast<QWidget *>(d->pdev) : 0;
- const bool isAlienWidget = w && !w->internalWinId() && w->testAttribute(Qt::WA_WState_Created);
-#ifndef QT_NO_XRENDER
- if (w) {
- if (isAlienWidget)
- d->picture = (::Picture)w->nativeParentWidget()->x11PictureHandle();
- else
- d->picture = (::Picture)w->x11PictureHandle();
- } else if (pdev->devType() == QInternal::Pixmap) {
- const QPixmap *pm = static_cast<const QPixmap *>(pdev);
- QX11PixmapData *data = static_cast<QX11PixmapData*>(pm->data.data());
- if (X11->use_xrender && data->depth() != 32 && data->x11_mask)
- data->convertToARGB32();
- d->picture = (::Picture)static_cast<const QPixmap *>(pdev)->x11PictureHandle();
- }
-#else
- d->picture = 0;
-#endif
- d->hd = !isAlienWidget ? qt_x11Handle(pdev) : qt_x11Handle(w->nativeParentWidget());
-
- Q_ASSERT(d->xinfo != 0);
- d->dpy = d->xinfo->display(); // get display variable
- d->scrn = d->xinfo->screen(); // get screen variable
-
- d->crgn = QRegion();
- d->gc = XCreateGC(d->dpy, d->hd, 0, 0);
- d->gc_brush = XCreateGC(d->dpy, d->hd, 0, 0);
- d->has_alpha_brush = false;
- d->has_alpha_pen = false;
- d->has_clipping = false;
- d->has_complex_xform = false;
- d->has_scaling_xform = false;
- d->has_non_scaling_xform = true;
- d->xform_scale = 1;
- d->has_custom_pen = false;
- d->matrix = QTransform();
- d->pdev_depth = d->pdev->depth();
- d->render_hints = 0;
- d->txop = QTransform::TxNone;
- d->use_path_fallback = false;
-#if !defined(QT_NO_XRENDER)
- d->composition_mode = PictOpOver;
-#endif
- d->xlibMaxLinePoints = 32762; // a safe number used to avoid, call to XMaxRequestSize(d->dpy) - 3;
- d->opacity = 1;
-
- // Set up the polygon clipper. Note: This will only work in
- // polyline mode as long as we have a buffer zone, since a
- // polyline may be clipped into several non-connected polylines.
- const int BUFFERZONE = 1000;
- QRect devClipRect(-BUFFERZONE, -BUFFERZONE,
- pdev->width() + 2*BUFFERZONE, pdev->height() + 2*BUFFERZONE);
- d->polygonClipper.setBoundingRect(devClipRect);
-
- if (isAlienWidget) {
- // Set system clip for alien widgets painting outside the paint event.
- // This is not a problem with native windows since the windowing system
- // will handle the clip.
- QWidgetPrivate *wd = w->d_func();
- QRegion widgetClip(wd->clipRect());
- wd->clipToEffectiveMask(widgetClip);
- wd->subtractOpaqueSiblings(widgetClip);
- widgetClip.translate(w->mapTo(w->nativeParentWidget(), QPoint()));
- setSystemClip(widgetClip);
- }
-
- QPixmap::x11SetDefaultScreen(d->xinfo->screen());
-
- if (w && w->testAttribute(Qt::WA_PaintUnclipped)) { // paint direct on device
- updatePen(QPen(Qt::black));
- updateBrush(QBrush(Qt::white), QPoint());
- XSetSubwindowMode(d->dpy, d->gc, IncludeInferiors);
- XSetSubwindowMode(d->dpy, d->gc_brush, IncludeInferiors);
-#ifndef QT_NO_XRENDER
- XRenderPictureAttributes attrs;
- attrs.subwindow_mode = IncludeInferiors;
- XRenderChangePicture(d->dpy, d->picture, CPSubwindowMode, &attrs);
-#endif
- }
-
- setDirty(QPaintEngine::DirtyClipRegion);
- setDirty(QPaintEngine::DirtyPen);
- setDirty(QPaintEngine::DirtyBrush);
- setDirty(QPaintEngine::DirtyBackground);
-
- return true;
-}
-
-bool QX11PaintEngine::end()
-{
- Q_D(QX11PaintEngine);
-
-#if !defined(QT_NO_XRENDER)
- if (d->picture) {
- // reset clipping/subwindow mode on our render picture
- XRenderPictureAttributes attrs;
- attrs.subwindow_mode = ClipByChildren;
- attrs.clip_mask = XNone;
- XRenderChangePicture(d->dpy, d->picture, CPClipMask|CPSubwindowMode, &attrs);
- }
-#endif
-
- if (d->gc_brush && d->pdev->painters < 2) {
- XFreeGC(d->dpy, d->gc_brush);
- d->gc_brush = 0;
- }
-
- if (d->gc && d->pdev->painters < 2) {
- XFreeGC(d->dpy, d->gc);
- d->gc = 0;
- }
-
- // Restore system clip for alien widgets painting outside the paint event.
- if (d->pdev->devType() == QInternal::Widget && !static_cast<QWidget *>(d->pdev)->internalWinId())
- setSystemClip(QRegion());
-
- return true;
-}
-
-static bool clipLine(QLineF *line, const QRect &rect)
-{
- qreal x1 = line->x1();
- qreal x2 = line->x2();
- qreal y1 = line->y1();
- qreal y2 = line->y2();
-
- qreal left = rect.x();
- qreal right = rect.x() + rect.width() - 1;
- qreal top = rect.y();
- qreal bottom = rect.y() + rect.height() - 1;
-
- enum { Left, Right, Top, Bottom };
- // clip the lines, after cohen-sutherland, see e.g. http://www.nondot.org/~sabre/graphpro/line6.html
- int p1 = ((x1 < left) << Left)
- | ((x1 > right) << Right)
- | ((y1 < top) << Top)
- | ((y1 > bottom) << Bottom);
- int p2 = ((x2 < left) << Left)
- | ((x2 > right) << Right)
- | ((y2 < top) << Top)
- | ((y2 > bottom) << Bottom);
-
- if (p1 & p2)
- // completely outside
- return false;
-
- if (p1 | p2) {
- qreal dx = x2 - x1;
- qreal dy = y2 - y1;
-
- // clip x coordinates
- if (x1 < left) {
- y1 += dy/dx * (left - x1);
- x1 = left;
- } else if (x1 > right) {
- y1 -= dy/dx * (x1 - right);
- x1 = right;
- }
- if (x2 < left) {
- y2 += dy/dx * (left - x2);
- x2 = left;
- } else if (x2 > right) {
- y2 -= dy/dx * (x2 - right);
- x2 = right;
- }
- p1 = ((y1 < top) << Top)
- | ((y1 > bottom) << Bottom);
- p2 = ((y2 < top) << Top)
- | ((y2 > bottom) << Bottom);
- if (p1 & p2)
- return false;
- // clip y coordinates
- if (y1 < top) {
- x1 += dx/dy * (top - y1);
- y1 = top;
- } else if (y1 > bottom) {
- x1 -= dx/dy * (y1 - bottom);
- y1 = bottom;
- }
- if (y2 < top) {
- x2 += dx/dy * (top - y2);
- y2 = top;
- } else if (y2 > bottom) {
- x2 -= dx/dy * (y2 - bottom);
- y2 = bottom;
- }
- *line = QLineF(QPointF(x1, y1), QPointF(x2, y2));
- }
- return true;
-}
-
-void QX11PaintEngine::drawLines(const QLine *lines, int lineCount)
-{
- Q_ASSERT(lines);
- Q_ASSERT(lineCount);
- Q_D(QX11PaintEngine);
- if (d->has_alpha_brush
- || d->has_alpha_pen
- || d->has_custom_pen
- || (d->cpen.widthF() > 0 && d->has_complex_xform
- && !d->has_non_scaling_xform)
- || (d->render_hints & QPainter::Antialiasing)) {
- for (int i = 0; i < lineCount; ++i) {
- QPainterPath path(lines[i].p1());
- path.lineTo(lines[i].p2());
- drawPath(path);
- }
- return;
- }
-
- if (d->has_pen) {
- for (int i = 0; i < lineCount; ++i) {
- QLineF linef;
- if (d->txop == QTransform::TxNone) {
- linef = lines[i];
- } else {
- linef = d->matrix.map(QLineF(lines[i]));
- }
- if (clipLine(&linef, d->polygonClipper.boundingRect())) {
- int x1 = qRound(linef.x1() + aliasedCoordinateDelta);
- int y1 = qRound(linef.y1() + aliasedCoordinateDelta);
- int x2 = qRound(linef.x2() + aliasedCoordinateDelta);
- int y2 = qRound(linef.y2() + aliasedCoordinateDelta);
-
- XDrawLine(d->dpy, d->hd, d->gc, x1, y1, x2, y2);
- }
- }
- }
-}
-
-void QX11PaintEngine::drawLines(const QLineF *lines, int lineCount)
-{
- Q_ASSERT(lines);
- Q_ASSERT(lineCount);
- Q_D(QX11PaintEngine);
- if (d->has_alpha_brush
- || d->has_alpha_pen
- || d->has_custom_pen
- || (d->cpen.widthF() > 0 && d->has_complex_xform
- && !d->has_non_scaling_xform)
- || (d->render_hints & QPainter::Antialiasing)) {
- for (int i = 0; i < lineCount; ++i) {
- QPainterPath path(lines[i].p1());
- path.lineTo(lines[i].p2());
- drawPath(path);
- }
- return;
- }
-
- if (d->has_pen) {
- for (int i = 0; i < lineCount; ++i) {
- QLineF linef = d->matrix.map(lines[i]);
- if (clipLine(&linef, d->polygonClipper.boundingRect())) {
- int x1 = qRound(linef.x1() + aliasedCoordinateDelta);
- int y1 = qRound(linef.y1() + aliasedCoordinateDelta);
- int x2 = qRound(linef.x2() + aliasedCoordinateDelta);
- int y2 = qRound(linef.y2() + aliasedCoordinateDelta);
-
- XDrawLine(d->dpy, d->hd, d->gc, x1, y1, x2, y2);
- }
- }
- }
-}
-
-static inline QLine clipStraightLine(const QRect &clip, const QLine &l)
-{
- if (l.p1().x() == l.p2().x()) {
- int x = qBound(clip.left(), l.p1().x(), clip.right());
- int y1 = qBound(clip.top(), l.p1().y(), clip.bottom());
- int y2 = qBound(clip.top(), l.p2().y(), clip.bottom());
-
- return QLine(x, y1, x, y2);
- } else {
- Q_ASSERT(l.p1().y() == l.p2().y());
-
- int x1 = qBound(clip.left(), l.p1().x(), clip.right());
- int x2 = qBound(clip.left(), l.p2().x(), clip.right());
- int y = qBound(clip.top(), l.p1().y(), clip.bottom());
-
- return QLine(x1, y, x2, y);
- }
-}
-
-void QX11PaintEngine::drawRects(const QRectF *rects, int rectCount)
-{
- Q_D(QX11PaintEngine);
- Q_ASSERT(rects);
- Q_ASSERT(rectCount);
-
- if (rectCount != 1
- || d->has_pen
- || d->has_alpha_brush
- || d->has_complex_xform
- || d->has_custom_pen
- || d->cbrush.style() != Qt::SolidPattern)
- {
- QPaintEngine::drawRects(rects, rectCount);
- return;
- }
-
- QPoint alignedOffset;
- if (d->txop == QTransform::TxTranslate) {
- QPointF offset(d->matrix.dx(), d->matrix.dy());
- alignedOffset = offset.toPoint();
- if (offset != QPointF(alignedOffset)) {
- QPaintEngine::drawRects(rects, rectCount);
- return;
- }
- }
-
- const QRectF& r = rects[0];
- QRect alignedRect = r.toAlignedRect();
- if (r != QRectF(alignedRect)) {
- QPaintEngine::drawRects(rects, rectCount);
- return;
- }
- alignedRect.translate(alignedOffset);
-
- QRect clip(d->polygonClipper.boundingRect());
- alignedRect = alignedRect.intersected(clip);
- if (alignedRect.isEmpty())
- return;
-
- // simple-case:
- // the rectangle is pixel-aligned
- // the fill brush is just a solid non-alpha color
- // the painter transform is only integer translation
- // ignore: antialiasing and just XFillRectangles directly
- XRectangle xrect;
- xrect.x = short(alignedRect.x());
- xrect.y = short(alignedRect.y());
- xrect.width = ushort(alignedRect.width());
- xrect.height = ushort(alignedRect.height());
- XFillRectangles(d->dpy, d->hd, d->gc_brush, &xrect, 1);
-}
-
-void QX11PaintEngine::drawRects(const QRect *rects, int rectCount)
-{
- Q_D(QX11PaintEngine);
- Q_ASSERT(rects);
- Q_ASSERT(rectCount);
-
- if (d->has_alpha_pen
- || d->has_complex_xform
- || d->has_custom_pen
- || (d->render_hints & QPainter::Antialiasing))
- {
- for (int i = 0; i < rectCount; ++i) {
- QPainterPath path;
- path.addRect(rects[i]);
- drawPath(path);
- }
- return;
- }
-
- QRect clip(d->polygonClipper.boundingRect());
- QPoint offset(qRound(d->matrix.dx()), qRound(d->matrix.dy()));
-#if !defined(QT_NO_XRENDER)
- ::Picture pict = d->picture;
-
- if (X11->use_xrender && pict && d->has_brush && d->pdev_depth != 1
- && (d->has_texture || d->has_alpha_brush))
- {
- XRenderColor xc;
- if (!d->has_texture && !d->has_pattern)
- xc = X11->preMultiply(d->cbrush.color());
-
- for (int i = 0; i < rectCount; ++i) {
- QRect r(rects[i]);
- if (d->txop == QTransform::TxTranslate)
- r.translate(offset);
-
- if (r.width() == 0 || r.height() == 0) {
- if (d->has_pen) {
- const QLine l = clipStraightLine(clip, QLine(r.left(), r.top(), r.left() + r.width(), r.top() + r.height()));
- XDrawLine(d->dpy, d->hd, d->gc, l.p1().x(), l.p1().y(), l.p2().x(), l.p2().y());
- }
- continue;
- }
-
- r = r.intersected(clip);
- if (r.isEmpty())
- continue;
- if (d->has_texture || d->has_pattern) {
- XRenderComposite(d->dpy, d->composition_mode, d->current_brush, 0, pict,
- qRound(r.x() - d->bg_origin.x()), qRound(r.y() - d->bg_origin.y()),
- 0, 0, r.x(), r.y(), r.width(), r.height());
- } else {
- XRenderFillRectangle(d->dpy, d->composition_mode, pict, &xc, r.x(), r.y(), r.width(), r.height());
- }
- if (d->has_pen)
- XDrawRectangle(d->dpy, d->hd, d->gc, r.x(), r.y(), r.width(), r.height());
- }
- } else
-#endif // !QT_NO_XRENDER
- {
- if (d->has_brush && d->has_pen) {
- for (int i = 0; i < rectCount; ++i) {
- QRect r(rects[i]);
- if (d->txop == QTransform::TxTranslate)
- r.translate(offset);
-
- if (r.width() == 0 || r.height() == 0) {
- const QLine l = clipStraightLine(clip, QLine(r.left(), r.top(), r.left() + r.width(), r.top() + r.height()));
- XDrawLine(d->dpy, d->hd, d->gc, l.p1().x(), l.p1().y(), l.p2().x(), l.p2().y());
- continue;
- }
-
- r = r.intersected(clip);
- if (r.isEmpty())
- continue;
- d->setupAdaptedOrigin(r.topLeft());
- XFillRectangle(d->dpy, d->hd, d->gc_brush, r.x(), r.y(), r.width(), r.height());
- XDrawRectangle(d->dpy, d->hd, d->gc, r.x(), r.y(), r.width(), r.height());
- }
- d->resetAdaptedOrigin();
- } else {
- QVarLengthArray<XRectangle> xrects(rectCount);
- int numClipped = rectCount;
- for (int i = 0; i < rectCount; ++i) {
- QRect r(rects[i]);
- if (d->txop == QTransform::TxTranslate)
- r.translate(offset);
-
- if (r.width() == 0 || r.height() == 0) {
- --numClipped;
- if (d->has_pen) {
- const QLine l = clipStraightLine(clip, QLine(r.left(), r.top(), r.left() + r.width(), r.top() + r.height()));
- XDrawLine(d->dpy, d->hd, d->gc, l.p1().x(), l.p1().y(), l.p2().x(), l.p2().y());
- }
- continue;
- }
-
- r = r.intersected(clip);
- if (r.isEmpty()) {
- --numClipped;
- continue;
- }
- xrects[i].x = short(r.x());
- xrects[i].y = short(r.y());
- xrects[i].width = ushort(r.width());
- xrects[i].height = ushort(r.height());
- }
- if (numClipped) {
- d->setupAdaptedOrigin(rects[0].topLeft());
- if (d->has_brush)
- XFillRectangles(d->dpy, d->hd, d->gc_brush, xrects.data(), numClipped);
- else if (d->has_pen)
- XDrawRectangles(d->dpy, d->hd, d->gc, xrects.data(), numClipped);
- d->resetAdaptedOrigin();
- }
- }
- }
-}
-
-static inline void setCapStyle(int cap_style, GC gc)
-{
- ulong mask = GCCapStyle;
- XGCValues vals;
- vals.cap_style = cap_style;
- XChangeGC(X11->display, gc, mask, &vals);
-}
-
-void QX11PaintEngine::drawPoints(const QPoint *points, int pointCount)
-{
- Q_ASSERT(points);
- Q_ASSERT(pointCount);
- Q_D(QX11PaintEngine);
-
- if (!d->has_pen)
- return;
-
- // use the same test here as in drawPath to ensure that we don't use the path fallback
- // and end up in XDrawLines for pens with width <= 1
- if (d->cpen.widthF() > 1.0f
- || (X11->use_xrender && (d->has_alpha_pen || (d->render_hints & QPainter::Antialiasing)))
- || (!d->cpen.isCosmetic() && d->txop > QTransform::TxTranslate))
- {
- Qt::PenCapStyle capStyle = d->cpen.capStyle();
- if (capStyle == Qt::FlatCap) {
- setCapStyle(CapProjecting, d->gc);
- d->cpen.setCapStyle(Qt::SquareCap);
- }
- const QPoint *end = points + pointCount;
- while (points < end) {
- QPainterPath path;
- path.moveTo(*points);
- path.lineTo(points->x()+.005, points->y());
- drawPath(path);
- ++points;
- }
-
- if (capStyle == Qt::FlatCap) {
- setCapStyle(CapButt, d->gc);
- d->cpen.setCapStyle(capStyle);
- }
- return;
- }
-
- static const int BUF_SIZE = 1024;
- XPoint xPoints[BUF_SIZE];
- int i = 0, j = 0;
- while (i < pointCount) {
- while (i < pointCount && j < BUF_SIZE) {
- const QPoint &xformed = d->matrix.map(points[i]);
- int x = xformed.x();
- int y = xformed.y();
- if (x >= SHRT_MIN && y >= SHRT_MIN && x < SHRT_MAX && y < SHRT_MAX) {
- xPoints[j].x = x;
- xPoints[j].y = y;
- ++j;
- }
- ++i;
- }
- if (j)
- XDrawPoints(d->dpy, d->hd, d->gc, xPoints, j, CoordModeOrigin);
-
- j = 0;
- }
-}
-
-void QX11PaintEngine::drawPoints(const QPointF *points, int pointCount)
-{
- Q_ASSERT(points);
- Q_ASSERT(pointCount);
- Q_D(QX11PaintEngine);
-
- if (!d->has_pen)
- return;
-
- // use the same test here as in drawPath to ensure that we don't use the path fallback
- // and end up in XDrawLines for pens with width <= 1
- if (d->cpen.widthF() > 1.0f
- || (X11->use_xrender && (d->has_alpha_pen || (d->render_hints & QPainter::Antialiasing)))
- || (!d->cpen.isCosmetic() && d->txop > QTransform::TxTranslate))
- {
- Qt::PenCapStyle capStyle = d->cpen.capStyle();
- if (capStyle == Qt::FlatCap) {
- setCapStyle(CapProjecting, d->gc);
- d->cpen.setCapStyle(Qt::SquareCap);
- }
-
- const QPointF *end = points + pointCount;
- while (points < end) {
- QPainterPath path;
- path.moveTo(*points);
- path.lineTo(points->x() + 0.005, points->y());
- drawPath(path);
- ++points;
- }
- if (capStyle == Qt::FlatCap) {
- setCapStyle(CapButt, d->gc);
- d->cpen.setCapStyle(capStyle);
- }
- return;
- }
-
- static const int BUF_SIZE = 1024;
- XPoint xPoints[BUF_SIZE];
- int i = 0, j = 0;
- while (i < pointCount) {
- while (i < pointCount && j < BUF_SIZE) {
- const QPointF &xformed = d->matrix.map(points[i]);
- int x = qFloor(xformed.x());
- int y = qFloor(xformed.y());
-
- if (x >= SHRT_MIN && y >= SHRT_MIN && x < SHRT_MAX && y < SHRT_MAX) {
- xPoints[j].x = x;
- xPoints[j].y = y;
- ++j;
- }
- ++i;
- }
- if (j)
- XDrawPoints(d->dpy, d->hd, d->gc, xPoints, j, CoordModeOrigin);
-
- j = 0;
- }
-}
-
-QPainter::RenderHints QX11PaintEngine::supportedRenderHints() const
-{
-#if !defined(QT_NO_XRENDER)
- if (X11->use_xrender)
- return QPainter::Antialiasing;
-#endif
- return QFlag(0);
-}
-
-void QX11PaintEngine::updateState(const QPaintEngineState &state)
-{
- Q_D(QX11PaintEngine);
- QPaintEngine::DirtyFlags flags = state.state();
-
-
- if (flags & DirtyOpacity) {
- d->opacity = state.opacity();
- // Force update pen/brush as to get proper alpha colors propagated
- flags |= DirtyPen;
- flags |= DirtyBrush;
- }
-
- if (flags & DirtyTransform) updateMatrix(state.transform());
- if (flags & DirtyPen) updatePen(state.pen());
- if (flags & (DirtyBrush | DirtyBrushOrigin)) updateBrush(state.brush(), state.brushOrigin());
- if (flags & DirtyFont) updateFont(state.font());
-
- if (state.state() & DirtyClipEnabled) {
- if (state.isClipEnabled()) {
- QPolygonF clip_poly_dev(d->matrix.map(painter()->clipPath().toFillPolygon()));
- QPolygonF clipped_poly_dev;
- d->clipPolygon_dev(clip_poly_dev, &clipped_poly_dev);
- updateClipRegion_dev(QRegion(clipped_poly_dev.toPolygon()), Qt::ReplaceClip);
- } else {
- updateClipRegion_dev(QRegion(), Qt::NoClip);
- }
- }
-
- if (flags & DirtyClipPath) {
- QPolygonF clip_poly_dev(d->matrix.map(state.clipPath().toFillPolygon()));
- QPolygonF clipped_poly_dev;
- d->clipPolygon_dev(clip_poly_dev, &clipped_poly_dev);
- updateClipRegion_dev(QRegion(clipped_poly_dev.toPolygon(), state.clipPath().fillRule()),
- state.clipOperation());
- } else if (flags & DirtyClipRegion) {
- extern QPainterPath qt_regionToPath(const QRegion &region);
- QPainterPath clip_path = qt_regionToPath(state.clipRegion());
- QPolygonF clip_poly_dev(d->matrix.map(clip_path.toFillPolygon()));
- QPolygonF clipped_poly_dev;
- d->clipPolygon_dev(clip_poly_dev, &clipped_poly_dev);
- updateClipRegion_dev(QRegion(clipped_poly_dev.toPolygon()), state.clipOperation());
- }
- if (flags & DirtyHints) updateRenderHints(state.renderHints());
- if (flags & DirtyCompositionMode) {
- int function = GXcopy;
- if (state.compositionMode() >= QPainter::RasterOp_SourceOrDestination) {
- switch (state.compositionMode()) {
- case QPainter::RasterOp_SourceOrDestination:
- function = GXor;
- break;
- case QPainter::RasterOp_SourceAndDestination:
- function = GXand;
- break;
- case QPainter::RasterOp_SourceXorDestination:
- function = GXxor;
- break;
- case QPainter::RasterOp_NotSourceAndNotDestination:
- function = GXnor;
- break;
- case QPainter::RasterOp_NotSourceOrNotDestination:
- function = GXnand;
- break;
- case QPainter::RasterOp_NotSourceXorDestination:
- function = GXequiv;
- break;
- case QPainter::RasterOp_NotSource:
- function = GXcopyInverted;
- break;
- case QPainter::RasterOp_SourceAndNotDestination:
- function = GXandReverse;
- break;
- case QPainter::RasterOp_NotSourceAndDestination:
- function = GXandInverted;
- break;
- default:
- function = GXcopy;
- }
- }
-#if !defined(QT_NO_XRENDER)
- else {
- d->composition_mode =
- qpainterOpToXrender(state.compositionMode());
- }
-#endif
- XSetFunction(X11->display, d->gc, function);
- XSetFunction(X11->display, d->gc_brush, function);
- }
- d->decidePathFallback();
- d->decideCoordAdjust();
-}
-
-void QX11PaintEngine::updateRenderHints(QPainter::RenderHints hints)
-{
- Q_D(QX11PaintEngine);
- d->render_hints = hints;
-
-#if !defined(QT_NO_XRENDER)
- if (X11->use_xrender && d->picture) {
- XRenderPictureAttributes attrs;
- attrs.poly_edge = (hints & QPainter::Antialiasing) ? PolyEdgeSmooth : PolyEdgeSharp;
- XRenderChangePicture(d->dpy, d->picture, CPPolyEdge, &attrs);
- }
-#endif
-}
-
-void QX11PaintEngine::updatePen(const QPen &pen)
-{
- Q_D(QX11PaintEngine);
- d->cpen = pen;
- int cp = CapButt;
- int jn = JoinMiter;
- int ps = pen.style();
-
- if (d->opacity < 1.0) {
- QColor c = d->cpen.color();
- c.setAlpha(qRound(c.alpha()*d->opacity));
- d->cpen.setColor(c);
- }
-
- d->has_pen = (ps != Qt::NoPen);
- d->has_alpha_pen = (pen.color().alpha() != 255);
-
- switch (pen.capStyle()) {
- case Qt::SquareCap:
- cp = CapProjecting;
- break;
- case Qt::RoundCap:
- cp = CapRound;
- break;
- case Qt::FlatCap:
- default:
- cp = CapButt;
- break;
- }
- switch (pen.joinStyle()) {
- case Qt::BevelJoin:
- jn = JoinBevel;
- break;
- case Qt::RoundJoin:
- jn = JoinRound;
- break;
- case Qt::MiterJoin:
- default:
- jn = JoinMiter;
- break;
- }
-
- d->adapted_pen_origin = false;
-
- char dashes[10]; // custom pen dashes
- int dash_len = 0; // length of dash list
- int xStyle = LineSolid;
-
- /*
- We are emulating Windows here. Windows treats cpen.width() == 1
- (or 0) as a very special case. The fudge variable unifies this
- case with the general case.
- */
- qreal pen_width = pen.widthF();
- int scale = qRound(pen_width < 1 ? 1 : pen_width);
- int space = (pen_width < 1 && pen_width > 0 ? 1 : (2 * scale));
- int dot = 1 * scale;
- int dash = 4 * scale;
-
- d->has_custom_pen = false;
-
- switch (ps) {
- case Qt::NoPen:
- case Qt::SolidLine:
- xStyle = LineSolid;
- break;
- case Qt::DashLine:
- dashes[0] = dash;
- dashes[1] = space;
- dash_len = 2;
- xStyle = LineOnOffDash;
- break;
- case Qt::DotLine:
- dashes[0] = dot;
- dashes[1] = space;
- dash_len = 2;
- xStyle = LineOnOffDash;
- break;
- case Qt::DashDotLine:
- dashes[0] = dash;
- dashes[1] = space;
- dashes[2] = dot;
- dashes[3] = space;
- dash_len = 4;
- xStyle = LineOnOffDash;
- break;
- case Qt::DashDotDotLine:
- dashes[0] = dash;
- dashes[1] = space;
- dashes[2] = dot;
- dashes[3] = space;
- dashes[4] = dot;
- dashes[5] = space;
- dash_len = 6;
- xStyle = LineOnOffDash;
- break;
- case Qt::CustomDashLine:
- d->has_custom_pen = true;
- break;
- }
-
- ulong mask = GCForeground | GCBackground | GCGraphicsExposures | GCLineWidth
- | GCCapStyle | GCJoinStyle | GCLineStyle;
- XGCValues vals;
- vals.graphics_exposures = false;
- if (d->pdev_depth == 1) {
- vals.foreground = qGray(pen.color().rgb()) > 127 ? 0 : 1;
- vals.background = qGray(QColor(Qt::transparent).rgb()) > 127 ? 0 : 1;
- } else if (d->pdev->devType() == QInternal::Pixmap && d->pdev_depth == 32
- && X11->use_xrender) {
- vals.foreground = pen.color().rgba();
- vals.background = QColor(Qt::transparent).rgba();
- } else {
- QColormap cmap = QColormap::instance(d->scrn);
- vals.foreground = cmap.pixel(pen.color());
- vals.background = cmap.pixel(QColor(Qt::transparent));
- }
-
-
- vals.line_width = qRound(pen.widthF());
- vals.cap_style = cp;
- vals.join_style = jn;
- vals.line_style = xStyle;
-
- XChangeGC(d->dpy, d->gc, mask, &vals);
-
- if (dash_len) { // make dash list
- XSetDashes(d->dpy, d->gc, 0, dashes, dash_len);
- }
-
- if (!d->has_clipping) { // if clipping is set the paintevent clip region is merged with the clip region
- QRegion sysClip = systemClip();
- if (!sysClip.isEmpty())
- x11SetClipRegion(d->dpy, d->gc, 0, d->picture, sysClip);
- else
- x11ClearClipRegion(d->dpy, d->gc, 0, d->picture);
- }
-}
-
-void QX11PaintEngine::updateBrush(const QBrush &brush, const QPointF &origin)
-{
- Q_D(QX11PaintEngine);
- d->cbrush = brush;
- d->bg_origin = origin;
- d->adapted_brush_origin = false;
-#if !defined(QT_NO_XRENDER)
- d->current_brush = 0;
-#endif
- if (d->opacity < 1.0) {
- QColor c = d->cbrush.color();
- c.setAlpha(qRound(c.alpha()*d->opacity));
- d->cbrush.setColor(c);
- }
-
- int s = FillSolid;
- int bs = d->cbrush.style();
- d->has_brush = (bs != Qt::NoBrush);
- d->has_pattern = bs >= Qt::Dense1Pattern && bs <= Qt::DiagCrossPattern;
- d->has_texture = bs == Qt::TexturePattern;
- d->has_alpha_brush = brush.color().alpha() != 255;
- d->has_alpha_texture = d->has_texture && d->cbrush.texture().hasAlphaChannel();
-
- ulong mask = GCForeground | GCBackground | GCGraphicsExposures
- | GCLineStyle | GCCapStyle | GCJoinStyle | GCFillStyle;
- XGCValues vals;
- vals.graphics_exposures = false;
- if (d->pdev_depth == 1) {
- vals.foreground = qGray(d->cbrush.color().rgb()) > 127 ? 0 : 1;
- vals.background = qGray(QColor(Qt::transparent).rgb()) > 127 ? 0 : 1;
- } else if (X11->use_xrender && d->pdev->devType() == QInternal::Pixmap
- && d->pdev_depth == 32) {
- vals.foreground = d->cbrush.color().rgba();
- vals.background = QColor(Qt::transparent).rgba();
- } else {
- QColormap cmap = QColormap::instance(d->scrn);
- vals.foreground = cmap.pixel(d->cbrush.color());
- vals.background = cmap.pixel(QColor(Qt::transparent));
-
- if (!X11->use_xrender && d->has_brush && !d->has_pattern && !brush.isOpaque()) {
- QPixmap pattern = qt_patternForAlpha(brush.color().alpha(), d->scrn);
- mask |= GCStipple;
- vals.stipple = pattern.handle();
- s = FillStippled;
- d->adapted_brush_origin = true;
- }
- }
- vals.cap_style = CapButt;
- vals.join_style = JoinMiter;
- vals.line_style = LineSolid;
-
- if (d->has_pattern || d->has_texture) {
- if (bs == Qt::TexturePattern) {
- d->brush_pm = qt_toX11Pixmap(d->cbrush.texture());
-#if !defined(QT_NO_XRENDER)
- if (X11->use_xrender) {
- XRenderPictureAttributes attrs;
- attrs.repeat = true;
- XRenderChangePicture(d->dpy, d->brush_pm.x11PictureHandle(), CPRepeat, &attrs);
- QX11PixmapData *data = static_cast<QX11PixmapData*>(d->brush_pm.data.data());
- if (data->mask_picture)
- XRenderChangePicture(d->dpy, data->mask_picture, CPRepeat, &attrs);
- }
-#endif
- } else {
- d->brush_pm = qt_toX11Pixmap(qt_pixmapForBrush(bs, true));
- }
- d->brush_pm.x11SetScreen(d->scrn);
- if (d->brush_pm.depth() == 1) {
- mask |= GCStipple;
- vals.stipple = d->brush_pm.handle();
- s = FillStippled;
-#if !defined(QT_NO_XRENDER)
- if (X11->use_xrender) {
- d->bitmap_texture = QPixmap(d->brush_pm.size());
- d->bitmap_texture.fill(Qt::transparent);
- d->bitmap_texture = qt_toX11Pixmap(d->bitmap_texture);
- d->bitmap_texture.x11SetScreen(d->scrn);
-
- ::Picture src = X11->getSolidFill(d->scrn, d->cbrush.color());
- XRenderComposite(d->dpy, PictOpSrc, src, d->brush_pm.x11PictureHandle(),
- d->bitmap_texture.x11PictureHandle(),
- 0, 0, d->brush_pm.width(), d->brush_pm.height(),
- 0, 0, d->brush_pm.width(), d->brush_pm.height());
-
- XRenderPictureAttributes attrs;
- attrs.repeat = true;
- XRenderChangePicture(d->dpy, d->bitmap_texture.x11PictureHandle(), CPRepeat, &attrs);
-
- d->current_brush = d->bitmap_texture.x11PictureHandle();
- }
-#endif
- } else {
- mask |= GCTile;
-#ifndef QT_NO_XRENDER
- if (d->pdev_depth == 32 && d->brush_pm.depth() != 32) {
- d->brush_pm.detach();
- QX11PixmapData *brushData = static_cast<QX11PixmapData*>(d->brush_pm.data.data());
- brushData->convertToARGB32();
- }
-#endif
- vals.tile = (d->brush_pm.depth() == d->pdev_depth
- ? d->brush_pm.handle()
- : static_cast<QX11PixmapData*>(d->brush_pm.data.data())->x11ConvertToDefaultDepth());
- s = FillTiled;
-#if !defined(QT_NO_XRENDER)
- d->current_brush = d->cbrush.texture().x11PictureHandle();
-#endif
- }
-
- mask |= GCTileStipXOrigin | GCTileStipYOrigin;
- vals.ts_x_origin = qRound(origin.x());
- vals.ts_y_origin = qRound(origin.y());
- }
-#if !defined(QT_NO_XRENDER)
- else if (d->has_alpha_brush) {
- d->current_brush = X11->getSolidFill(d->scrn, d->cbrush.color());
- }
-#endif
-
- vals.fill_style = s;
- XChangeGC(d->dpy, d->gc_brush, mask, &vals);
- if (!d->has_clipping) {
- QRegion sysClip = systemClip();
- if (!sysClip.isEmpty())
- x11SetClipRegion(d->dpy, d->gc_brush, 0, d->picture, sysClip);
- else
- x11ClearClipRegion(d->dpy, d->gc_brush, 0, d->picture);
- }
-}
-
-void QX11PaintEngine::drawEllipse(const QRectF &rect)
-{
- QRect aligned = rect.toAlignedRect();
- if (aligned == rect)
- drawEllipse(aligned);
- else
- QPaintEngine::drawEllipse(rect);
-}
-
-void QX11PaintEngine::drawEllipse(const QRect &rect)
-{
- if (rect.isEmpty()) {
- drawRects(&rect, 1);
- return;
- }
-
- Q_D(QX11PaintEngine);
- QRect devclip(SHRT_MIN, SHRT_MIN, SHRT_MAX*2 - 1, SHRT_MAX*2 - 1);
- QRect r(rect);
- if (d->txop < QTransform::TxRotate) {
- r = d->matrix.mapRect(rect);
- } else if (d->txop == QTransform::TxRotate && rect.width() == rect.height()) {
- QPainterPath path;
- path.addEllipse(rect);
- r = d->matrix.map(path).boundingRect().toRect();
- }
-
- if (d->has_alpha_brush || d->has_alpha_pen || d->has_custom_pen || (d->render_hints & QPainter::Antialiasing)
- || d->has_alpha_texture || devclip.intersected(r) != r
- || (d->has_complex_xform
- && !(d->has_non_scaling_xform && rect.width() == rect.height())))
- {
- QPainterPath path;
- path.addEllipse(rect);
- drawPath(path);
- return;
- }
-
- int x = r.x();
- int y = r.y();
- int w = r.width();
- int h = r.height();
- if (w < 1 || h < 1)
- return;
- if (w == 1 && h == 1) {
- XDrawPoint(d->dpy, d->hd, d->has_pen ? d->gc : d->gc_brush, x, y);
- return;
- }
- d->setupAdaptedOrigin(rect.topLeft());
- if (d->has_brush) { // draw filled ellipse
- XFillArc(d->dpy, d->hd, d->gc_brush, x, y, w, h, 0, 360*64);
- if (!d->has_pen) // make smoother outline
- XDrawArc(d->dpy, d->hd, d->gc_brush, x, y, w-1, h-1, 0, 360*64);
- }
- if (d->has_pen) // draw outline
- XDrawArc(d->dpy, d->hd, d->gc, x, y, w, h, 0, 360*64);
- d->resetAdaptedOrigin();
-}
-
-
-
-void QX11PaintEnginePrivate::fillPolygon_translated(const QPointF *polygonPoints, int pointCount,
- QX11PaintEnginePrivate::GCMode gcMode,
- QPaintEngine::PolygonDrawMode mode)
-{
-
- QVarLengthArray<QPointF> translated_points(pointCount);
- QPointF offset(matrix.dx(), matrix.dy());
-
- qreal offs = adjust_coords ? aliasedCoordinateDelta : 0.0;
- if (!X11->use_xrender || !(render_hints & QPainter::Antialiasing))
- offset += QPointF(aliasedCoordinateDelta, aliasedCoordinateDelta);
-
- for (int i = 0; i < pointCount; ++i) {
- translated_points[i] = polygonPoints[i] + offset;
-
- translated_points[i].rx() = qRound(translated_points[i].x()) + offs;
- translated_points[i].ry() = qRound(translated_points[i].y()) + offs;
- }
-
- fillPolygon_dev(translated_points.data(), pointCount, gcMode, mode);
-}
-
-#ifndef QT_NO_XRENDER
-static void qt_XRenderCompositeTrapezoids(Display *dpy,
- int op,
- Picture src,
- Picture dst,
- _Xconst XRenderPictFormat *maskFormat,
- int xSrc,
- int ySrc,
- const XTrapezoid *traps, int size)
-{
- const int MAX_TRAPS = 50000;
- while (size) {
- int to_draw = size;
- if (to_draw > MAX_TRAPS)
- to_draw = MAX_TRAPS;
- XRenderCompositeTrapezoids(dpy, op, src, dst,
- maskFormat,
- xSrc, ySrc,
- traps, to_draw);
- size -= to_draw;
- traps += to_draw;
- }
-}
-#endif
-
-void QX11PaintEnginePrivate::fillPolygon_dev(const QPointF *polygonPoints, int pointCount,
- QX11PaintEnginePrivate::GCMode gcMode,
- QPaintEngine::PolygonDrawMode mode)
-{
- Q_Q(QX11PaintEngine);
-
- int clippedCount = 0;
- qt_float_point *clippedPoints = 0;
-
-#ifndef QT_NO_XRENDER
- //can change if we switch to pen if gcMode != BrushGC
- bool has_fill_texture = has_texture;
- bool has_fill_pattern = has_pattern;
- ::Picture src;
-#endif
- QBrush fill;
- GC fill_gc;
- if (gcMode == BrushGC) {
- fill = cbrush;
- fill_gc = gc_brush;
-#ifndef QT_NO_XRENDER
- if (current_brush)
- src = current_brush;
- else
- src = X11->getSolidFill(scrn, fill.color());
-#endif
- } else {
- fill = QBrush(cpen.brush());
- fill_gc = gc;
-#ifndef QT_NO_XRENDER
- //we use the pens brush
- has_fill_texture = (fill.style() == Qt::TexturePattern);
- has_fill_pattern = (fill.style() >= Qt::Dense1Pattern && fill.style() <= Qt::DiagCrossPattern);
- if (has_fill_texture)
- src = fill.texture().x11PictureHandle();
- else if (has_fill_pattern)
- src = getPatternFill(scrn, fill);
- else
- src = X11->getSolidFill(scrn, fill.color());
-#endif
- }
-
- polygonClipper.clipPolygon((qt_float_point *) polygonPoints, pointCount,
- &clippedPoints, &clippedCount);
-
-#ifndef QT_NO_XRENDER
- bool solid_fill = fill.color().alpha() == 255;
- if (has_fill_texture && fill.texture().depth() == 1 && solid_fill) {
- has_fill_texture = false;
- has_fill_pattern = true;
- }
-
- bool antialias = render_hints & QPainter::Antialiasing;
-
- if (X11->use_xrender
- && picture
- && !has_fill_pattern
- && (clippedCount > 0)
- && (fill.style() != Qt::NoBrush)
- && ((has_fill_texture && fill.texture().hasAlpha()) || antialias || !solid_fill || has_alpha_pen != has_alpha_brush))
- {
- QRect br = tessellator->tessellate((QPointF *)clippedPoints, clippedCount,
- mode == QPaintEngine::WindingMode);
- if (tessellator->size > 0) {
- XRenderPictureAttributes attrs;
- attrs.poly_edge = antialias ? PolyEdgeSmooth : PolyEdgeSharp;
- XRenderChangePicture(dpy, picture, CPPolyEdge, &attrs);
- int x_offset = int(XFixedToDouble(tessellator->traps[0].left.p1.x) - bg_origin.x());
- int y_offset = int(XFixedToDouble(tessellator->traps[0].left.p1.y) - bg_origin.y());
- qt_XRenderCompositeTrapezoids(dpy, composition_mode, src, picture,
- antialias
- ? XRenderFindStandardFormat(dpy, PictStandardA8)
- : XRenderFindStandardFormat(dpy, PictStandardA1),
- x_offset, y_offset,
- tessellator->traps, tessellator->size);
- tessellator->done();
- }
- } else
-#endif
- if (fill.style() != Qt::NoBrush) {
- if (clippedCount > 200000) {
- QPolygon poly;
- for (int i = 0; i < clippedCount; ++i)
- poly << QPoint(qFloor(clippedPoints[i].x), qFloor(clippedPoints[i].y));
-
- const QRect bounds = poly.boundingRect();
- const QRect aligned = bounds
- & QRect(QPoint(), QSize(pdev->width(), pdev->height()));
-
- QImage img(aligned.size(), QImage::Format_ARGB32_Premultiplied);
- img.fill(0);
-
- QPainter painter(&img);
- painter.translate(-aligned.x(), -aligned.y());
- painter.setPen(Qt::NoPen);
- painter.setBrush(fill);
- if (gcMode == BrushGC)
- painter.setBrushOrigin(q->painter()->brushOrigin());
- painter.drawPolygon(poly);
- painter.end();
-
- q->drawImage(aligned, img, img.rect(), Qt::AutoColor);
- } else if (clippedCount > 0) {
- QVarLengthArray<XPoint> xpoints(clippedCount);
- for (int i = 0; i < clippedCount; ++i) {
- xpoints[i].x = qFloor(clippedPoints[i].x);
- xpoints[i].y = qFloor(clippedPoints[i].y);
- }
- if (mode == QPaintEngine::WindingMode)
- XSetFillRule(dpy, fill_gc, WindingRule);
- setupAdaptedOrigin(QPoint(xpoints[0].x, xpoints[0].y));
- XFillPolygon(dpy, hd, fill_gc,
- xpoints.data(), clippedCount,
- mode == QPaintEngine::ConvexMode ? Convex : Complex, CoordModeOrigin);
- resetAdaptedOrigin();
- if (mode == QPaintEngine::WindingMode)
- XSetFillRule(dpy, fill_gc, EvenOddRule);
- }
- }
-}
-
-void QX11PaintEnginePrivate::strokePolygon_translated(const QPointF *polygonPoints, int pointCount, bool close)
-{
- QVarLengthArray<QPointF> translated_points(pointCount);
- QPointF offset(matrix.dx(), matrix.dy());
- for (int i = 0; i < pointCount; ++i)
- translated_points[i] = polygonPoints[i] + offset;
- strokePolygon_dev(translated_points.data(), pointCount, close);
-}
-
-void QX11PaintEnginePrivate::strokePolygon_dev(const QPointF *polygonPoints, int pointCount, bool close)
-{
- int clippedCount = 0;
- qt_float_point *clippedPoints = 0;
- polygonClipper.clipPolygon((qt_float_point *) polygonPoints, pointCount,
- &clippedPoints, &clippedCount, close);
-
- if (clippedCount > 0) {
- QVarLengthArray<XPoint> xpoints(clippedCount);
- for (int i = 0; i < clippedCount; ++i) {
- xpoints[i].x = qRound(clippedPoints[i].x + aliasedCoordinateDelta);
- xpoints[i].y = qRound(clippedPoints[i].y + aliasedCoordinateDelta);
- }
- uint numberPoints = qMin(clippedCount, xlibMaxLinePoints);
- XPoint *pts = xpoints.data();
- XDrawLines(dpy, hd, gc, pts, numberPoints, CoordModeOrigin);
- pts += numberPoints;
- clippedCount -= numberPoints;
- numberPoints = qMin(clippedCount, xlibMaxLinePoints-1);
- while (clippedCount) {
- XDrawLines(dpy, hd, gc, pts-1, numberPoints+1, CoordModeOrigin);
- pts += numberPoints;
- clippedCount -= numberPoints;
- numberPoints = qMin(clippedCount, xlibMaxLinePoints-1);
- }
- }
-}
-
-void QX11PaintEngine::drawPolygon(const QPointF *polygonPoints, int pointCount, PolygonDrawMode mode)
-{
- Q_D(QX11PaintEngine);
- if (d->use_path_fallback) {
- QPainterPath path(polygonPoints[0]);
- for (int i = 1; i < pointCount; ++i)
- path.lineTo(polygonPoints[i]);
- if (mode == PolylineMode) {
- QBrush oldBrush = d->cbrush;
- d->cbrush = QBrush(Qt::NoBrush);
- path.setFillRule(Qt::WindingFill);
- drawPath(path);
- d->cbrush = oldBrush;
- } else {
- path.setFillRule(mode == OddEvenMode ? Qt::OddEvenFill : Qt::WindingFill);
- path.closeSubpath();
- drawPath(path);
- }
- return;
- }
- if (mode != PolylineMode && d->has_brush)
- d->fillPolygon_translated(polygonPoints, pointCount, QX11PaintEnginePrivate::BrushGC, mode);
-
- if (d->has_pen)
- d->strokePolygon_translated(polygonPoints, pointCount, mode != PolylineMode);
-}
-
-
-void QX11PaintEnginePrivate::fillPath(const QPainterPath &path, QX11PaintEnginePrivate::GCMode gc_mode, bool transform)
-{
- qreal offs = adjust_coords ? aliasedCoordinateDelta : 0.0;
-
- QPainterPath clippedPath;
- QPainterPath clipPath;
- clipPath.addRect(polygonClipper.boundingRect());
-
- if (transform)
- clippedPath = (path*matrix).intersected(clipPath);
- else
- clippedPath = path.intersected(clipPath);
-
- QList<QPolygonF> polys = clippedPath.toFillPolygons();
- for (int i = 0; i < polys.size(); ++i) {
- QVarLengthArray<QPointF> translated_points(polys.at(i).size());
-
- for (int j = 0; j < polys.at(i).size(); ++j) {
- translated_points[j] = polys.at(i).at(j);
- if (!X11->use_xrender || !(render_hints & QPainter::Antialiasing)) {
- translated_points[j].rx() = qRound(translated_points[j].rx() + aliasedCoordinateDelta) + offs;
- translated_points[j].ry() = qRound(translated_points[j].ry() + aliasedCoordinateDelta) + offs;
- }
- }
-
- fillPolygon_dev(translated_points.data(), polys.at(i).size(), gc_mode,
- path.fillRule() == Qt::OddEvenFill ? QPaintEngine::OddEvenMode : QPaintEngine::WindingMode);
- }
-}
-
-void QX11PaintEngine::drawPath(const QPainterPath &path)
-{
- Q_D(QX11PaintEngine);
- if (path.isEmpty())
- return;
- QTransform old_matrix = d->matrix;
-
- if (d->has_brush)
- d->fillPath(path, QX11PaintEnginePrivate::BrushGC, true);
- if (d->has_pen
- && ((X11->use_xrender && (d->has_alpha_pen || (d->render_hints & QPainter::Antialiasing)))
- || (!d->cpen.isCosmetic() && d->txop > QTransform::TxTranslate
- && !d->has_non_scaling_xform)
- || (d->cpen.style() == Qt::CustomDashLine))) {
- QPainterPathStroker stroker;
- if (d->cpen.style() == Qt::CustomDashLine) {
- stroker.setDashPattern(d->cpen.dashPattern());
- stroker.setDashOffset(d->cpen.dashOffset());
- } else {
- stroker.setDashPattern(d->cpen.style());
- }
- stroker.setCapStyle(d->cpen.capStyle());
- stroker.setJoinStyle(d->cpen.joinStyle());
- QPainterPath stroke;
- qreal width = d->cpen.widthF();
- QPolygonF poly;
- QRectF deviceRect(0, 0, d->pdev->width(), d->pdev->height());
- // necessary to get aliased alphablended primitives to be drawn correctly
- if (d->cpen.isCosmetic() || d->has_scaling_xform) {
- if (d->cpen.isCosmetic())
- stroker.setWidth(width == 0 ? 1 : width);
- else
- stroker.setWidth(width * d->xform_scale);
- stroker.d_ptr->stroker.setClipRect(deviceRect);
- stroke = stroker.createStroke(path * d->matrix);
- if (stroke.isEmpty())
- return;
- stroke.setFillRule(Qt::WindingFill);
- d->fillPath(stroke, QX11PaintEnginePrivate::PenGC, false);
- } else {
- stroker.setWidth(width);
- stroker.d_ptr->stroker.setClipRect(d->matrix.inverted().mapRect(deviceRect));
- stroke = stroker.createStroke(path);
- if (stroke.isEmpty())
- return;
- stroke.setFillRule(Qt::WindingFill);
- d->fillPath(stroke, QX11PaintEnginePrivate::PenGC, true);
- }
- } else if (d->has_pen) {
- // if we have a cosmetic pen - use XDrawLine() for speed
- QList<QPolygonF> polys = path.toSubpathPolygons(d->matrix);
- for (int i = 0; i < polys.size(); ++i)
- d->strokePolygon_dev(polys.at(i).data(), polys.at(i).size(), false);
- }
-}
-
-Q_GUI_EXPORT void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const QImage &image,
- Drawable hd, GC gc, Display *dpy, Visual *visual, int depth)
-{
- Q_ASSERT(image.format() == QImage::Format_RGB32);
- Q_ASSERT(image.depth() == 32);
-
- XImage *xi;
- // Note: this code assumes either RGB or BGR, 8 bpc server layouts
- const uint red_mask = (uint) visual->red_mask;
- bool bgr_layout = (red_mask == 0xff);
-
- const int w = rect.width();
- const int h = rect.height();
-
- QImage im;
- int image_byte_order = ImageByteOrder(X11->display);
- if ((QSysInfo::ByteOrder == QSysInfo::BigEndian && ((image_byte_order == LSBFirst) || bgr_layout))
- || (image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian)
- || (image_byte_order == LSBFirst && bgr_layout))
- {
- im = image.copy(rect);
- const int iw = im.bytesPerLine() / 4;
- uint *data = (uint *)im.bits();
- for (int i=0; i < h; i++) {
- uint *p = data;
- uint *end = p + w;
- if (bgr_layout && image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian) {
- while (p < end) {
- *p = ((*p << 8) & 0xffffff00) | ((*p >> 24) & 0x000000ff);
- p++;
- }
- } else if ((image_byte_order == LSBFirst && QSysInfo::ByteOrder == QSysInfo::BigEndian)
- || (image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian)) {
- while (p < end) {
- *p = ((*p << 24) & 0xff000000) | ((*p << 8) & 0x00ff0000)
- | ((*p >> 8) & 0x0000ff00) | ((*p >> 24) & 0x000000ff);
- p++;
- }
- } else if ((image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::BigEndian)
- || (image_byte_order == LSBFirst && bgr_layout))
- {
- while (p < end) {
- *p = ((*p << 16) & 0x00ff0000) | ((*p >> 16) & 0x000000ff)
- | ((*p ) & 0xff00ff00);
- p++;
- }
- }
- data += iw;
- }
- xi = XCreateImage(dpy, visual, depth, ZPixmap,
- 0, (char *) im.bits(), w, h, 32, im.bytesPerLine());
- } else {
- xi = XCreateImage(dpy, visual, depth, ZPixmap,
- 0, (char *) image.scanLine(rect.y())+rect.x()*sizeof(uint), w, h, 32, image.bytesPerLine());
- }
- XPutImage(dpy, hd, gc, xi, 0, 0, pos.x(), pos.y(), w, h);
- xi->data = 0; // QImage owns these bits
- XDestroyImage(xi);
-}
-
-void QX11PaintEngine::drawImage(const QRectF &r, const QImage &image, const QRectF &sr, Qt::ImageConversionFlags flags)
-{
- Q_D(QX11PaintEngine);
-
- if (image.format() == QImage::Format_RGB32
- && d->pdev_depth >= 24 && image.depth() == 32
- && r.size() == sr.size())
- {
- int sx = qRound(sr.x());
- int sy = qRound(sr.y());
- int x = qRound(r.x());
- int y = qRound(r.y());
- int w = qRound(r.width());
- int h = qRound(r.height());
-
- qt_x11_drawImage(QRect(sx, sy, w, h), QPoint(x, y), image, d->hd, d->gc, d->dpy,
- (Visual *)d->xinfo->visual(), d->pdev_depth);
- } else {
- QPaintEngine::drawImage(r, image, sr, flags);
- }
-}
-
-void QX11PaintEngine::drawPixmap(const QRectF &r, const QPixmap &px, const QRectF &_sr)
-{
- Q_D(QX11PaintEngine);
- QRectF sr = _sr;
- int x = qRound(r.x());
- int y = qRound(r.y());
- int sx = qRound(sr.x());
- int sy = qRound(sr.y());
- int sw = qRound(sr.width());
- int sh = qRound(sr.height());
-
- QPixmap pixmap = qt_toX11Pixmap(px);
- if(pixmap.isNull())
- return;
-
- if ((d->xinfo && d->xinfo->screen() != pixmap.x11Info().screen())
- || (pixmap.x11Info().screen() != DefaultScreen(X11->display))) {
- QPixmap* p = const_cast<QPixmap *>(&pixmap);
- p->x11SetScreen(d->xinfo ? d->xinfo->screen() : DefaultScreen(X11->display));
- }
-
- QPixmap::x11SetDefaultScreen(pixmap.x11Info().screen());
-
-#ifndef QT_NO_XRENDER
- ::Picture src_pict = static_cast<QX11PixmapData*>(pixmap.data.data())->picture;
- if (src_pict && d->picture) {
- const int pDepth = pixmap.depth();
- if (pDepth == 1 && (d->has_alpha_pen)) {
- qt_render_bitmap(d->dpy, d->scrn, src_pict, d->picture,
- sx, sy, x, y, sw, sh, d->cpen);
- return;
- } else if (pDepth != 1 && (pDepth == 32 || pDepth != d->pdev_depth)) {
- XRenderComposite(d->dpy, d->composition_mode,
- src_pict, 0, d->picture, sx, sy, 0, 0, x, y, sw, sh);
- return;
- }
- }
-#endif
-
- bool mono_src = pixmap.depth() == 1;
- bool mono_dst = d->pdev_depth == 1;
- bool restore_clip = false;
-
- if (static_cast<QX11PixmapData*>(pixmap.data.data())->x11_mask) { // pixmap has a mask
- QBitmap comb(sw, sh);
- GC cgc = XCreateGC(d->dpy, comb.handle(), 0, 0);
- XSetForeground(d->dpy, cgc, 0);
- XFillRectangle(d->dpy, comb.handle(), cgc, 0, 0, sw, sh);
- XSetBackground(d->dpy, cgc, 0);
- XSetForeground(d->dpy, cgc, 1);
- if (!d->crgn.isEmpty()) {
- int num;
- XRectangle *rects = (XRectangle *)qt_getClipRects(d->crgn, num);
- XSetClipRectangles(d->dpy, cgc, -x, -y, rects, num, Unsorted);
- } else if (d->has_clipping) {
- XSetClipRectangles(d->dpy, cgc, 0, 0, 0, 0, Unsorted);
- }
- XSetFillStyle(d->dpy, cgc, FillOpaqueStippled);
- XSetTSOrigin(d->dpy, cgc, -sx, -sy);
- XSetStipple(d->dpy, cgc,
- static_cast<QX11PixmapData*>(pixmap.data.data())->x11_mask);
- XFillRectangle(d->dpy, comb.handle(), cgc, 0, 0, sw, sh);
- XFreeGC(d->dpy, cgc);
-
- XSetClipOrigin(d->dpy, d->gc, x, y);
- XSetClipMask(d->dpy, d->gc, comb.handle());
- restore_clip = true;
- }
-
- if (mono_src) {
- if (!d->crgn.isEmpty()) {
- Pixmap comb = XCreatePixmap(d->dpy, d->hd, sw, sh, 1);
- GC cgc = XCreateGC(d->dpy, comb, 0, 0);
- XSetForeground(d->dpy, cgc, 0);
- XFillRectangle(d->dpy, comb, cgc, 0, 0, sw, sh);
- int num;
- XRectangle *rects = (XRectangle *)qt_getClipRects(d->crgn, num);
- XSetClipRectangles(d->dpy, cgc, -x, -y, rects, num, Unsorted);
- XCopyArea(d->dpy, pixmap.handle(), comb, cgc, sx, sy, sw, sh, 0, 0);
- XFreeGC(d->dpy, cgc);
-
- XSetClipMask(d->dpy, d->gc, comb);
- XSetClipOrigin(d->dpy, d->gc, x, y);
- XFreePixmap(d->dpy, comb);
- } else {
- XSetClipMask(d->dpy, d->gc, pixmap.handle());
- XSetClipOrigin(d->dpy, d->gc, x - sx, y - sy);
- }
-
- if (mono_dst) {
- XSetForeground(d->dpy, d->gc, qGray(d->cpen.color().rgb()) > 127 ? 0 : 1);
- } else {
- QColormap cmap = QColormap::instance(d->scrn);
- XSetForeground(d->dpy, d->gc, cmap.pixel(d->cpen.color()));
- }
- XFillRectangle(d->dpy, d->hd, d->gc, x, y, sw, sh);
- restore_clip = true;
- } else if (mono_dst && !mono_src) {
- QBitmap bitmap(pixmap);
- XCopyArea(d->dpy, bitmap.handle(), d->hd, d->gc, sx, sy, sw, sh, x, y);
- } else {
- XCopyArea(d->dpy, pixmap.handle(), d->hd, d->gc, sx, sy, sw, sh, x, y);
- }
-
- if (d->pdev->devType() == QInternal::Pixmap) {
- const QPixmap *px = static_cast<const QPixmap*>(d->pdev);
- Pixmap src_mask = static_cast<QX11PixmapData*>(pixmap.data.data())->x11_mask;
- Pixmap dst_mask = static_cast<QX11PixmapData*>(px->data.data())->x11_mask;
- if (dst_mask) {
- GC cgc = XCreateGC(d->dpy, dst_mask, 0, 0);
- if (src_mask) { // copy src mask into dst mask
- XCopyArea(d->dpy, src_mask, dst_mask, cgc, sx, sy, sw, sh, x, y);
- } else { // no src mask, but make sure the area copied is opaque in dest
- XSetBackground(d->dpy, cgc, 0);
- XSetForeground(d->dpy, cgc, 1);
- XFillRectangle(d->dpy, dst_mask, cgc, x, y, sw, sh);
- }
- XFreeGC(d->dpy, cgc);
- }
- }
-
- if (restore_clip) {
- XSetClipOrigin(d->dpy, d->gc, 0, 0);
- int num;
- XRectangle *rects = (XRectangle *)qt_getClipRects(d->crgn, num);
- if (num == 0)
- XSetClipMask(d->dpy, d->gc, XNone);
- else
- XSetClipRectangles(d->dpy, d->gc, 0, 0, rects, num, Unsorted);
- }
-}
-
-void QX11PaintEngine::updateMatrix(const QTransform &mtx)
-{
- Q_D(QX11PaintEngine);
- d->txop = mtx.type();
- d->matrix = mtx;
-
- d->has_complex_xform = (d->txop > QTransform::TxTranslate);
-
- extern bool qt_scaleForTransform(const QTransform &transform, qreal *scale);
- bool scaling = qt_scaleForTransform(d->matrix, &d->xform_scale);
- d->has_scaling_xform = scaling && d->xform_scale != 1.0;
- d->has_non_scaling_xform = scaling && d->xform_scale == 1.0;
-}
-
-/*
- NB! the clip region is expected to be in dev coordinates
-*/
-void QX11PaintEngine::updateClipRegion_dev(const QRegion &clipRegion, Qt::ClipOperation op)
-{
- Q_D(QX11PaintEngine);
- QRegion sysClip = systemClip();
- if (op == Qt::NoClip) {
- d->has_clipping = false;
- d->crgn = sysClip;
- if (!sysClip.isEmpty()) {
- x11SetClipRegion(d->dpy, d->gc, d->gc_brush, d->picture, sysClip);
- } else {
- x11ClearClipRegion(d->dpy, d->gc, d->gc_brush, d->picture);
- }
- return;
- }
-
- switch (op) {
- case Qt::IntersectClip:
- if (d->has_clipping) {
- d->crgn &= clipRegion;
- break;
- }
- // fall through
- case Qt::ReplaceClip:
- if (!sysClip.isEmpty())
- d->crgn = clipRegion.intersected(sysClip);
- else
- d->crgn = clipRegion;
- break;
- case Qt::UniteClip:
- d->crgn |= clipRegion;
- if (!sysClip.isEmpty())
- d->crgn = d->crgn.intersected(sysClip);
- break;
- default:
- break;
- }
- d->has_clipping = true;
- x11SetClipRegion(d->dpy, d->gc, d->gc_brush, d->picture, d->crgn);
-}
-
-void QX11PaintEngine::updateFont(const QFont &)
-{
-}
-
-Qt::HANDLE QX11PaintEngine::handle() const
-{
- Q_D(const QX11PaintEngine);
- Q_ASSERT(isActive());
- Q_ASSERT(d->hd);
- return d->hd;
-}
-
-extern void qt_draw_tile(QPaintEngine *, qreal, qreal, qreal, qreal, const QPixmap &,
- qreal, qreal);
-
-void QX11PaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, const QPointF &p)
-{
- int x = qRound(r.x());
- int y = qRound(r.y());
- int w = qRound(r.width());
- int h = qRound(r.height());
- int sx = qRound(p.x());
- int sy = qRound(p.y());
-
- bool mono_src = pixmap.depth() == 1;
- Q_D(QX11PaintEngine);
-
- if ((d->xinfo && d->xinfo->screen() != pixmap.x11Info().screen())
- || (pixmap.x11Info().screen() != DefaultScreen(X11->display))) {
- QPixmap* p = const_cast<QPixmap *>(&pixmap);
- p->x11SetScreen(d->xinfo ? d->xinfo->screen() : DefaultScreen(X11->display));
- }
-
- QPixmap::x11SetDefaultScreen(pixmap.x11Info().screen());
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender && d->picture && pixmap.x11PictureHandle()) {
-#if 0
- // ### Qt 5: enable this
- XRenderPictureAttributes attrs;
- attrs.repeat = true;
- XRenderChangePicture(d->dpy, pixmap.x11PictureHandle(), CPRepeat, &attrs);
-
- if (mono_src) {
- qt_render_bitmap(d->dpy, d->scrn, pixmap.x11PictureHandle(), d->picture,
- sx, sy, x, y, w, h, d->cpen);
- } else {
- XRenderComposite(d->dpy, d->composition_mode,
- pixmap.x11PictureHandle(), XNone, d->picture,
- sx, sy, 0, 0, x, y, w, h);
- }
-#else
- const int numTiles = (w / pixmap.width()) * (h / pixmap.height());
- if (numTiles < 100) {
- // this is essentially qt_draw_tile(), inlined for
- // the XRenderComposite call
- int yPos, xPos, drawH, drawW, yOff, xOff;
- yPos = y;
- yOff = sy;
- while(yPos < y + h) {
- drawH = pixmap.height() - yOff; // Cropping first row
- if (yPos + drawH > y + h) // Cropping last row
- drawH = y + h - yPos;
- xPos = x;
- xOff = sx;
- while(xPos < x + w) {
- drawW = pixmap.width() - xOff; // Cropping first column
- if (xPos + drawW > x + w) // Cropping last column
- drawW = x + w - xPos;
- if (mono_src) {
- qt_render_bitmap(d->dpy, d->scrn, pixmap.x11PictureHandle(), d->picture,
- xOff, yOff, xPos, yPos, drawW, drawH, d->cpen);
- } else {
- XRenderComposite(d->dpy, d->composition_mode,
- pixmap.x11PictureHandle(), XNone, d->picture,
- xOff, yOff, 0, 0, xPos, yPos, drawW, drawH);
- }
- xPos += drawW;
- xOff = 0;
- }
- yPos += drawH;
- yOff = 0;
- }
- } else {
- w = qMin(w, d->pdev->width() - x);
- h = qMin(h, d->pdev->height() - y);
- if (w <= 0 || h <= 0)
- return;
-
- const int pw = w + sx;
- const int ph = h + sy;
- QPixmap pm(pw, ph);
- if (pixmap.hasAlpha() || mono_src)
- pm.fill(Qt::transparent);
-
- const int mode = pixmap.hasAlpha() ? PictOpOver : PictOpSrc;
- const ::Picture pmPicture = pm.x11PictureHandle();
-
- // first tile
- XRenderComposite(d->dpy, mode,
- pixmap.x11PictureHandle(), XNone, pmPicture,
- 0, 0, 0, 0, 0, 0, qMin(pw, pixmap.width()), qMin(ph, pixmap.height()));
-
- // first row of tiles
- int xPos = pixmap.width();
- const int sh = qMin(ph, pixmap.height());
- while (xPos < pw) {
- const int sw = qMin(xPos, pw - xPos);
- XRenderComposite(d->dpy, mode,
- pmPicture, XNone, pmPicture,
- 0, 0, 0, 0, xPos, 0, sw, sh);
- xPos *= 2;
- }
-
- // remaining rows
- int yPos = pixmap.height();
- const int sw = pw;
- while (yPos < ph) {
- const int sh = qMin(yPos, ph - yPos);
- XRenderComposite(d->dpy, mode,
- pmPicture, XNone, pmPicture,
- 0, 0, 0, 0, 0, yPos, sw, sh);
- yPos *= 2;
- }
-
- // composite
- if (mono_src)
- qt_render_bitmap(d->dpy, d->scrn, pmPicture, d->picture,
- sx, sy, x, y, w, h, d->cpen);
- else
- XRenderComposite(d->dpy, d->composition_mode,
- pmPicture, XNone, d->picture,
- sx, sy, 0, 0, x, y, w, h);
- }
-#endif
- } else
-#endif // !QT_NO_XRENDER
- if (pixmap.depth() > 1 && !static_cast<QX11PixmapData*>(pixmap.data.data())->x11_mask) {
- XSetTile(d->dpy, d->gc, pixmap.handle());
- XSetFillStyle(d->dpy, d->gc, FillTiled);
- XSetTSOrigin(d->dpy, d->gc, x-sx, y-sy);
- XFillRectangle(d->dpy, d->hd, d->gc, x, y, w, h);
- XSetTSOrigin(d->dpy, d->gc, 0, 0);
- XSetFillStyle(d->dpy, d->gc, FillSolid);
- } else {
- qt_draw_tile(this, x, y, w, h, pixmap, sx, sy);
- }
-}
-
-void QX11PaintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
-{
- const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
-
- switch(ti.fontEngine->type()) {
- case QFontEngine::TestFontEngine:
- case QFontEngine::Box:
- d_func()->drawBoxTextItem(p, ti);
- break;
- case QFontEngine::XLFD:
- drawXLFD(p, ti);
- break;
-#ifndef QT_NO_FONTCONFIG
- case QFontEngine::Freetype:
- drawFreetype(p, ti);
- break;
-#endif
- default:
- Q_ASSERT(false);
- }
-}
-
-void QX11PaintEngine::drawXLFD(const QPointF &p, const QTextItemInt &ti)
-{
- Q_D(QX11PaintEngine);
-
- if (d->txop > QTransform::TxTranslate) {
- // XServer or font don't support server side transformations, need to do it by hand
- QPaintEngine::drawTextItem(p, ti);
- return;
- }
-
- if (!ti.glyphs.numGlyphs)
- return;
-
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> glyphs;
- QTransform matrix = d->matrix;
- matrix.translate(p.x(), p.y());
- ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
- if (glyphs.size() == 0)
- return;
-
- QFontEngineXLFD *xlfd = static_cast<QFontEngineXLFD *>(ti.fontEngine);
- Qt::HANDLE font_id = xlfd->fontStruct()->fid;
-
- XSetFont(d->dpy, d->gc, font_id);
-
- const QFixed offs = QFixed::fromReal(aliasedCoordinateDelta);
- for (int i = 0; i < glyphs.size(); i++) {
- int xp = qRound(positions[i].x + offs);
- int yp = qRound(positions[i].y + offs);
- if (xp < SHRT_MAX && xp > SHRT_MIN && yp > SHRT_MIN && yp < SHRT_MAX) {
- XChar2b ch;
- ch.byte1 = glyphs[i] >> 8;
- ch.byte2 = glyphs[i] & 0xff;
- XDrawString16(d->dpy, d->hd, d->gc, xp, yp, &ch, 1);
- }
- }
-}
-
-#ifndef QT_NO_FONTCONFIG
-static QPainterPath path_for_glyphs(const QVarLengthArray<glyph_t> &glyphs,
- const QVarLengthArray<QFixedPoint> &positions,
- const QFontEngineFT *ft)
-{
- QPainterPath path;
- path.setFillRule(Qt::WindingFill);
- ft->lockFace();
- int i = 0;
- while (i < glyphs.size()) {
- QFontEngineFT::Glyph *glyph = ft->loadGlyph(glyphs[i], QFontEngineFT::Format_Mono);
- // #### fix case where we don't get a glyph
- if (!glyph)
- break;
-
- Q_ASSERT(glyph->format == QFontEngineFT::Format_Mono);
- int n = 0;
- int h = glyph->height;
- int xp = qRound(positions[i].x);
- int yp = qRound(positions[i].y);
-
- xp += glyph->x;
- yp += -glyph->y + glyph->height;
- int pitch = ((glyph->width + 31) & ~31) >> 3;
-
- uchar *src = glyph->data;
- while (h--) {
- for (int x = 0; x < glyph->width; ++x) {
- bool set = src[x >> 3] & (0x80 >> (x & 7));
- if (set) {
- QRect r(xp + x, yp - h, 1, 1);
- while (x < glyph->width-1 && src[(x+1) >> 3] & (0x80 >> ((x+1) & 7))) {
- ++x;
- r.setRight(r.right()+1);
- }
-
- path.addRect(r);
- ++n;
- }
- }
- src += pitch;
- }
- ++i;
- }
- ft->unlockFace();
- return path;
-}
-
-void QX11PaintEngine::drawFreetype(const QPointF &p, const QTextItemInt &ti)
-{
- Q_D(QX11PaintEngine);
- if (!ti.glyphs.numGlyphs)
- return;
-
- QFontEngineX11FT *ft = static_cast<QFontEngineX11FT *>(ti.fontEngine);
-
- if (!d->cpen.isSolid()) {
- QPaintEngine::drawTextItem(p, ti);
- return;
- }
-
- const bool xrenderPath = (X11->use_xrender
- && !(d->pdev->devType() == QInternal::Pixmap
- && static_cast<const QPixmap *>(d->pdev)->data->pixelType() == QPixmapData::BitmapType));
-
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> glyphs;
- QTransform matrix;
-
- if (xrenderPath)
- matrix = d->matrix;
- matrix.translate(p.x(), p.y());
- ft->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
- if (glyphs.count() == 0)
- return;
-
-#ifndef QT_NO_XRENDER
- QFontEngineFT::QGlyphSet *set = ft->defaultGlyphs();
- if (d->txop >= QTransform::TxScale && xrenderPath)
- set = ft->loadTransformedGlyphSet(d->matrix);
-
- if (!set || set->outline_drawing
- || !ft->loadGlyphs(set, glyphs.constData(), glyphs.size(), positions.constData(), QFontEngineFT::Format_Render))
- {
- QPaintEngine::drawTextItem(p, ti);
- return;
- }
-
- if (xrenderPath) {
- GlyphSet glyphSet = set->id;
- const QColor &pen = d->cpen.color();
- ::Picture src = X11->getSolidFill(d->scrn, pen);
- XRenderPictFormat *maskFormat = 0;
- if (ft->xglyph_format != PictStandardA1)
- maskFormat = XRenderFindStandardFormat(X11->display, ft->xglyph_format);
-
- enum { t_min = SHRT_MIN, t_max = SHRT_MAX };
-
- int i = 0;
- for (; i < glyphs.size()
- && (positions[i].x < t_min || positions[i].x > t_max
- || positions[i].y < t_min || positions[i].y > t_max);
- ++i)
- ;
-
- if (i >= glyphs.size())
- return;
- ++i;
-
- QFixed xp = positions[i - 1].x;
- QFixed yp = positions[i - 1].y;
- QFixed offs = QFixed::fromReal(aliasedCoordinateDelta);
-
- XGlyphElt32 elt;
- elt.glyphset = glyphSet;
- elt.chars = &glyphs[i - 1];
- elt.nchars = 1;
- elt.xOff = qRound(xp + offs);
- elt.yOff = qRound(yp + offs);
- for (; i < glyphs.size(); ++i) {
- if (positions[i].x < t_min || positions[i].x > t_max
- || positions[i].y < t_min || positions[i].y > t_max) {
- break;
- }
- QFontEngineFT::Glyph *g = ft->cachedGlyph(glyphs[i - 1]);
- if (g
- && positions[i].x == xp + g->advance
- && positions[i].y == yp
- && elt.nchars < 253 // don't draw more than 253 characters as some X servers
- // hang with it
- ) {
- elt.nchars++;
- xp += g->advance;
- } else {
- xp = positions[i].x;
- yp = positions[i].y;
-
- XRenderCompositeText32(X11->display, PictOpOver, src, d->picture,
- maskFormat, 0, 0, 0, 0,
- &elt, 1);
- elt.chars = &glyphs[i];
- elt.nchars = 1;
- elt.xOff = qRound(xp + offs);
- elt.yOff = qRound(yp + offs);
- }
- }
- XRenderCompositeText32(X11->display, PictOpOver, src, d->picture,
- maskFormat, 0, 0, 0, 0,
- &elt, 1);
-
- return;
-
- }
-#endif
-
- QPainterPath path = path_for_glyphs(glyphs, positions, ft);
- if (path.elementCount() <= 1)
- return;
- Q_ASSERT((path.elementCount() % 5) == 0);
- if (d->txop >= QTransform::TxScale) {
- painter()->save();
- painter()->setBrush(d->cpen.brush());
- painter()->setPen(Qt::NoPen);
- painter()->drawPath(path);
- painter()->restore();
- return;
- }
-
- const int rectcount = 256;
- XRectangle rects[rectcount];
- int num_rects = 0;
-
- QPoint delta(qRound(d->matrix.dx()), qRound(d->matrix.dy()));
- QRect clip(d->polygonClipper.boundingRect());
- for (int i=0; i < path.elementCount(); i+=5) {
- int x = qRound(path.elementAt(i).x);
- int y = qRound(path.elementAt(i).y);
- int w = qRound(path.elementAt(i+1).x) - x;
- int h = qRound(path.elementAt(i+2).y) - y;
-
- QRect rect = QRect(x + delta.x(), y + delta.y(), w, h);
- rect = rect.intersected(clip);
- if (rect.isEmpty())
- continue;
-
- rects[num_rects].x = short(rect.x());
- rects[num_rects].y = short(rect.y());
- rects[num_rects].width = ushort(rect.width());
- rects[num_rects].height = ushort(rect.height());
- ++num_rects;
- if (num_rects == rectcount) {
- XFillRectangles(d->dpy, d->hd, d->gc, rects, num_rects);
- num_rects = 0;
- }
- }
- if (num_rects > 0)
- XFillRectangles(d->dpy, d->hd, d->gc, rects, num_rects);
-
-}
-#endif // !QT_NO_XRENDER
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qpaintengine_x11_p.h b/src/gui/platforms/x11/qpaintengine_x11_p.h
deleted file mode 100644
index 897c69f122..0000000000
--- a/src/gui/platforms/x11/qpaintengine_x11_p.h
+++ /dev/null
@@ -1,246 +0,0 @@
-/****************************************************************************
-**
-** 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 QPAINTENGINE_X11_P_H
-#define QPAINTENGINE_X11_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qpaintengine.h"
-#include "QtGui/qregion.h"
-#include "QtGui/qpen.h"
-#include "QtCore/qpoint.h"
-#include "private/qpaintengine_p.h"
-#include "private/qpainter_p.h"
-#include "private/qpolygonclipper_p.h"
-
-typedef unsigned long Picture;
-
-QT_BEGIN_NAMESPACE
-
-class QX11PaintEnginePrivate;
-class QFontEngineFT;
-class QXRenderTessellator;
-
-struct qt_float_point
-{
- qreal x, y;
-};
-
-class QX11PaintEngine : public QPaintEngine
-{
- Q_DECLARE_PRIVATE(QX11PaintEngine)
-public:
- QX11PaintEngine();
- ~QX11PaintEngine();
-
- bool begin(QPaintDevice *pdev);
- bool end();
-
- void updateState(const QPaintEngineState &state);
-
- void updatePen(const QPen &pen);
- void updateBrush(const QBrush &brush, const QPointF &pt);
- void updateRenderHints(QPainter::RenderHints hints);
- void updateFont(const QFont &font);
- void updateMatrix(const QTransform &matrix);
- void updateClipRegion_dev(const QRegion &region, Qt::ClipOperation op);
-
- void drawLines(const QLine *lines, int lineCount);
- void drawLines(const QLineF *lines, int lineCount);
-
- void drawRects(const QRect *rects, int rectCount);
- void drawRects(const QRectF *rects, int rectCount);
-
- void drawPoints(const QPoint *points, int pointCount);
- void drawPoints(const QPointF *points, int pointCount);
-
- void drawEllipse(const QRect &r);
- void drawEllipse(const QRectF &r);
-
- virtual void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
- inline void drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
- { QPaintEngine::drawPolygon(points, pointCount, mode); }
-
- void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
- void drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, const QPointF &s);
- void drawPath(const QPainterPath &path);
- void drawTextItem(const QPointF &p, const QTextItem &textItem);
- void drawImage(const QRectF &r, const QImage &img, const QRectF &sr,
- Qt::ImageConversionFlags flags = Qt::AutoColor);
-
- virtual Qt::HANDLE handle() const;
- inline Type type() const { return QPaintEngine::X11; }
-
- QPainter::RenderHints supportedRenderHints() const;
-
-protected:
- QX11PaintEngine(QX11PaintEnginePrivate &dptr);
-
- void drawXLFD(const QPointF &p, const QTextItemInt &si);
-#ifndef QT_NO_FONTCONFIG
- void drawFreetype(const QPointF &p, const QTextItemInt &si);
-#endif
-
- friend class QPixmap;
- friend class QFontEngineBox;
- friend Q_GUI_EXPORT GC qt_x11_get_pen_gc(QPainter *);
- friend Q_GUI_EXPORT GC qt_x11_get_brush_gc(QPainter *);
-
-private:
- Q_DISABLE_COPY(QX11PaintEngine)
-};
-
-class QX11PaintEnginePrivate : public QPaintEnginePrivate
-{
- Q_DECLARE_PUBLIC(QX11PaintEngine)
-public:
- QX11PaintEnginePrivate()
- {
- scrn = -1;
- hd = 0;
- picture = 0;
- gc = gc_brush = 0;
- dpy = 0;
- xinfo = 0;
- txop = QTransform::TxNone;
- has_clipping = false;
- render_hints = 0;
- xform_scale = 1;
-#ifndef QT_NO_XRENDER
- tessellator = 0;
-#endif
- }
- enum GCMode {
- PenGC,
- BrushGC
- };
-
- void init();
- void fillPolygon_translated(const QPointF *points, int pointCount, GCMode gcMode,
- QPaintEngine::PolygonDrawMode mode);
- void fillPolygon_dev(const QPointF *points, int pointCount, GCMode gcMode,
- QPaintEngine::PolygonDrawMode mode);
- void fillPath(const QPainterPath &path, GCMode gcmode, bool transform);
- void strokePolygon_dev(const QPointF *points, int pointCount, bool close);
- void strokePolygon_translated(const QPointF *points, int pointCount, bool close);
- void setupAdaptedOrigin(const QPoint &p);
- void resetAdaptedOrigin();
- void decidePathFallback() {
- use_path_fallback = has_alpha_brush
- || has_alpha_pen
- || has_custom_pen
- || has_complex_xform
- || (render_hints & QPainter::Antialiasing);
- }
- void decideCoordAdjust() {
- adjust_coords = !(render_hints & QPainter::Antialiasing)
- && (has_alpha_pen
- || (has_alpha_brush && has_pen && !has_alpha_pen)
- || (cpen.style() > Qt::SolidLine));
- }
- void clipPolygon_dev(const QPolygonF &poly, QPolygonF *clipped_poly);
- void systemStateChanged();
-
- Display *dpy;
- int scrn;
- int pdev_depth;
- Qt::HANDLE hd;
- QPixmap brush_pm;
-#if !defined (QT_NO_XRENDER)
- Qt::HANDLE picture;
- Qt::HANDLE current_brush;
- QPixmap bitmap_texture;
- int composition_mode;
-#else
- Qt::HANDLE picture;
-#endif
- GC gc;
- GC gc_brush;
-
- QPen cpen;
- QBrush cbrush;
- QRegion crgn;
- QTransform matrix;
- qreal opacity;
-
- uint has_complex_xform : 1;
- uint has_scaling_xform : 1;
- uint has_non_scaling_xform : 1;
- uint has_custom_pen : 1;
- uint use_path_fallback : 1;
- uint adjust_coords : 1;
- uint has_clipping : 1;
- uint adapted_brush_origin : 1;
- uint adapted_pen_origin : 1;
- uint has_pen : 1;
- uint has_brush : 1;
- uint has_texture : 1;
- uint has_alpha_texture : 1;
- uint has_pattern : 1;
- uint has_alpha_pen : 1;
- uint has_alpha_brush : 1;
- uint render_hints;
-
- const QX11Info *xinfo;
- QPointF bg_origin;
- QTransform::TransformationType txop;
- qreal xform_scale;
- QPolygonClipper<qt_float_point, qt_float_point, float> polygonClipper;
-
- int xlibMaxLinePoints;
-#ifndef QT_NO_XRENDER
- QXRenderTessellator *tessellator;
-#endif
-};
-
-QT_END_NAMESPACE
-
-#endif // QPAINTENGINE_X11_P_H
diff --git a/src/gui/platforms/x11/qpixmap_x11.cpp b/src/gui/platforms/x11/qpixmap_x11.cpp
deleted file mode 100644
index bc468cb7ec..0000000000
--- a/src/gui/platforms/x11/qpixmap_x11.cpp
+++ /dev/null
@@ -1,2419 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-// Uncomment the next line to enable the MIT Shared Memory extension
-//
-// WARNING: This has some problems:
-//
-// 1. Consumes a 800x600 pixmap
-// 2. Qt does not handle the ShmCompletion message, so you will
-// get strange effects if you xForm() repeatedly.
-//
-// #define QT_MITSHM
-
-#if defined(Q_OS_WIN32) && defined(QT_MITSHM)
-#undef QT_MITSHM
-#endif
-
-#include "qplatformdefs.h"
-
-#include "qdebug.h"
-#include "qiodevice.h"
-#include "qpixmap_x11_p.h"
-#include "qbitmap.h"
-#include "qcolormap.h"
-#include "qimage.h"
-#include "qmatrix.h"
-#include "qapplication.h"
-#include <private/qpaintengine_x11_p.h>
-#include <private/qt_x11_p.h>
-#include "qx11info_x11.h"
-#include <private/qdrawhelper_p.h>
-#include <private/qimage_p.h>
-#include <private/qimagepixmapcleanuphooks_p.h>
-
-#include <stdlib.h>
-
-#if defined(Q_CC_MIPS)
-# define for if(0){}else for
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QPixmap qt_toX11Pixmap(const QImage &image)
-{
- QPixmapData *data =
- new QX11PixmapData(image.depth() == 1
- ? QPixmapData::BitmapType
- : QPixmapData::PixmapType);
-
- data->fromImage(image, Qt::AutoColor);
-
- return QPixmap(data);
-}
-
-QPixmap qt_toX11Pixmap(const QPixmap &pixmap)
-{
- if (pixmap.isNull())
- return QPixmap();
-
- if (QPixmap(pixmap).data_ptr()->classId() == QPixmapData::X11Class)
- return pixmap;
-
- return qt_toX11Pixmap(pixmap.toImage());
-}
-
-// For thread-safety:
-// image->data does not belong to X11, so we must free it ourselves.
-
-inline static void qSafeXDestroyImage(XImage *x)
-{
- if (x->data) {
- free(x->data);
- x->data = 0;
- }
- XDestroyImage(x);
-}
-
-QBitmap QX11PixmapData::mask_to_bitmap(int screen) const
-{
- if (!x11_mask)
- return QBitmap();
- QPixmap::x11SetDefaultScreen(screen);
- QBitmap bm(w, h);
- GC gc = XCreateGC(X11->display, bm.handle(), 0, 0);
- XCopyArea(X11->display, x11_mask, bm.handle(), gc, 0, 0,
- bm.data->width(), bm.data->height(), 0, 0);
- XFreeGC(X11->display, gc);
- return bm;
-}
-
-Qt::HANDLE QX11PixmapData::bitmap_to_mask(const QBitmap &bitmap, int screen)
-{
- if (bitmap.isNull())
- return 0;
- QBitmap bm = bitmap;
- bm.x11SetScreen(screen);
-
- Pixmap mask = XCreatePixmap(X11->display, RootWindow(X11->display, screen),
- bm.data->width(), bm.data->height(), 1);
- GC gc = XCreateGC(X11->display, mask, 0, 0);
- XCopyArea(X11->display, bm.handle(), mask, gc, 0, 0,
- bm.data->width(), bm.data->height(), 0, 0);
- XFreeGC(X11->display, gc);
- return mask;
-}
-
-
-/*****************************************************************************
- MIT Shared Memory Extension support: makes xForm noticeably (~20%) faster.
- *****************************************************************************/
-
-#if defined(QT_MITSHM)
-
-static bool xshminit = false;
-static XShmSegmentInfo xshminfo;
-static XImage *xshmimg = 0;
-static Pixmap xshmpm = 0;
-
-static void qt_cleanup_mitshm()
-{
- if (xshmimg == 0)
- return;
- Display *dpy = QX11Info::appDisplay();
- if (xshmpm) {
- XFreePixmap(dpy, xshmpm);
- xshmpm = 0;
- }
- XShmDetach(dpy, &xshminfo); xshmimg->data = 0;
- qSafeXDestroyImage(xshmimg); xshmimg = 0;
- shmdt(xshminfo.shmaddr);
- shmctl(xshminfo.shmid, IPC_RMID, 0);
-}
-
-static bool qt_create_mitshm_buffer(const QPaintDevice* dev, int w, int h)
-{
- static int major, minor;
- static Bool pixmaps_ok;
- Display *dpy = dev->data->xinfo->display();
- int dd = dev->x11Depth();
- Visual *vis = (Visual*)dev->x11Visual();
-
- if (xshminit) {
- qt_cleanup_mitshm();
- } else {
- if (!XShmQueryVersion(dpy, &major, &minor, &pixmaps_ok))
- return false; // MIT Shm not supported
- qAddPostRoutine(qt_cleanup_mitshm);
- xshminit = true;
- }
-
- xshmimg = XShmCreateImage(dpy, vis, dd, ZPixmap, 0, &xshminfo, w, h);
- if (!xshmimg)
- return false;
-
- bool ok;
- xshminfo.shmid = shmget(IPC_PRIVATE,
- xshmimg->bytes_per_line * xshmimg->height,
- IPC_CREAT | 0777);
- ok = xshminfo.shmid != -1;
- if (ok) {
- xshmimg->data = (char*)shmat(xshminfo.shmid, 0, 0);
- xshminfo.shmaddr = xshmimg->data;
- ok = (xshminfo.shmaddr != (char*)-1);
- }
- xshminfo.readOnly = false;
- if (ok)
- ok = XShmAttach(dpy, &xshminfo);
- if (!ok) {
- qSafeXDestroyImage(xshmimg);
- xshmimg = 0;
- if (xshminfo.shmaddr)
- shmdt(xshminfo.shmaddr);
- if (xshminfo.shmid != -1)
- shmctl(xshminfo.shmid, IPC_RMID, 0);
- return false;
- }
- if (pixmaps_ok)
- xshmpm = XShmCreatePixmap(dpy, DefaultRootWindow(dpy), xshmimg->data,
- &xshminfo, w, h, dd);
-
- return true;
-}
-
-#else
-
-// If extern, need a dummy.
-//
-// static bool qt_create_mitshm_buffer(QPaintDevice*, int, int)
-// {
-// return false;
-// }
-
-#endif // QT_MITSHM
-
-
-/*****************************************************************************
- Internal functions
- *****************************************************************************/
-
-extern const uchar *qt_get_bitflip_array(); // defined in qimage.cpp
-
-// Returns position of highest bit set or -1 if none
-static int highest_bit(uint v)
-{
- int i;
- uint b = (uint)1 << 31;
- for (i=31; ((b & v) == 0) && i>=0; i--)
- b >>= 1;
- return i;
-}
-
-// Returns position of lowest set bit in 'v' as an integer (0-31), or -1
-static int lowest_bit(uint v)
-{
- int i;
- ulong lb;
- lb = 1;
- for (i=0; ((v & lb) == 0) && i<32; i++, lb<<=1) {}
- return i==32 ? -1 : i;
-}
-
-// Counts the number of bits set in 'v'
-static uint n_bits(uint v)
-{
- int i = 0;
- while (v) {
- v = v & (v - 1);
- i++;
- }
- return i;
-}
-
-static uint *red_scale_table = 0;
-static uint *green_scale_table = 0;
-static uint *blue_scale_table = 0;
-
-static void cleanup_scale_tables()
-{
- delete[] red_scale_table;
- delete[] green_scale_table;
- delete[] blue_scale_table;
-}
-
-/*
- Could do smart bitshifting, but the "obvious" algorithm only works for
- nBits >= 4. This is more robust.
-*/
-static void build_scale_table(uint **table, uint nBits)
-{
- if (nBits > 7) {
- qWarning("build_scale_table: internal error, nBits = %i", nBits);
- return;
- }
- if (!*table) {
- static bool firstTable = true;
- if (firstTable) {
- qAddPostRoutine(cleanup_scale_tables);
- firstTable = false;
- }
- *table = new uint[256];
- }
- int maxVal = (1 << nBits) - 1;
- int valShift = 8 - nBits;
- int i;
- for(i = 0 ; i < maxVal + 1 ; i++)
- (*table)[i << valShift] = i*255/maxVal;
-}
-
-static int defaultScreen = -1;
-
-/*****************************************************************************
- QPixmap member functions
- *****************************************************************************/
-
-QBasicAtomicInt qt_pixmap_serial = Q_BASIC_ATOMIC_INITIALIZER(0);
-int Q_GUI_EXPORT qt_x11_preferred_pixmap_depth = 0;
-
-QX11PixmapData::QX11PixmapData(PixelType type)
- : QPixmapData(type, X11Class), gl_surface(0), hd(0),
- flags(Uninitialized), x11_mask(0), picture(0), mask_picture(0), hd2(0),
- share_mode(QPixmap::ImplicitlyShared), pengine(0)
-{
-}
-
-QPixmapData *QX11PixmapData::createCompatiblePixmapData() const
-{
- return new QX11PixmapData(pixelType());
-}
-
-void QX11PixmapData::resize(int width, int height)
-{
- setSerialNumber(qt_pixmap_serial.fetchAndAddRelaxed(1));
-
- w = width;
- h = height;
- is_null = (w <= 0 || h <= 0);
-
- if (defaultScreen >= 0 && defaultScreen != xinfo.screen()) {
- QX11InfoData* xd = xinfo.getX11Data(true);
- xd->screen = defaultScreen;
- xd->depth = QX11Info::appDepth(xd->screen);
- xd->cells = QX11Info::appCells(xd->screen);
- xd->colormap = QX11Info::appColormap(xd->screen);
- xd->defaultColormap = QX11Info::appDefaultColormap(xd->screen);
- xd->visual = (Visual *)QX11Info::appVisual(xd->screen);
- xd->defaultVisual = QX11Info::appDefaultVisual(xd->screen);
- xinfo.setX11Data(xd);
- }
-
- int dd = xinfo.depth();
-
- if (qt_x11_preferred_pixmap_depth)
- dd = qt_x11_preferred_pixmap_depth;
-
- bool make_null = w <= 0 || h <= 0; // create null pixmap
- d = (pixelType() == BitmapType ? 1 : dd);
- if (make_null || d == 0) {
- w = 0;
- h = 0;
- is_null = true;
- hd = 0;
- picture = 0;
- d = 0;
- if (!make_null)
- qWarning("QPixmap: Invalid pixmap parameters");
- return;
- }
- hd = (Qt::HANDLE)XCreatePixmap(X11->display,
- RootWindow(X11->display, xinfo.screen()),
- w, h, d);
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- XRenderPictFormat *format = d == 1
- ? XRenderFindStandardFormat(X11->display, PictStandardA1)
- : XRenderFindVisualFormat(X11->display, (Visual *)xinfo.visual());
- picture = XRenderCreatePicture(X11->display, hd, format, 0, 0);
- }
-#endif // QT_NO_XRENDER
-}
-
-struct QX11AlphaDetector
-{
- bool hasAlpha() const {
- if (checked)
- return has;
- // Will implicitly also check format and return quickly for opaque types...
- checked = true;
- has = image->isNull() ? false : const_cast<QImage *>(image)->data_ptr()->checkForAlphaPixels();
- return has;
- }
-
- bool hasXRenderAndAlpha() const {
- if (!X11->use_xrender)
- return false;
- return hasAlpha();
- }
-
- QX11AlphaDetector(const QImage *i, Qt::ImageConversionFlags flags)
- : image(i), checked(false), has(false)
- {
- if (flags & Qt::NoOpaqueDetection) {
- checked = true;
- has = image->hasAlphaChannel();
- }
- }
-
- const QImage *image;
- mutable bool checked;
- mutable bool has;
-};
-
-void QX11PixmapData::fromImage(const QImage &img,
- Qt::ImageConversionFlags flags)
-{
- setSerialNumber(qt_pixmap_serial.fetchAndAddRelaxed(1));
-
- w = img.width();
- h = img.height();
- d = img.depth();
- is_null = (w <= 0 || h <= 0);
-
- if (is_null) {
- w = h = 0;
- return;
- }
-
- if (defaultScreen >= 0 && defaultScreen != xinfo.screen()) {
- QX11InfoData* xd = xinfo.getX11Data(true);
- xd->screen = defaultScreen;
- xd->depth = QX11Info::appDepth(xd->screen);
- xd->cells = QX11Info::appCells(xd->screen);
- xd->colormap = QX11Info::appColormap(xd->screen);
- xd->defaultColormap = QX11Info::appDefaultColormap(xd->screen);
- xd->visual = (Visual *)QX11Info::appVisual(xd->screen);
- xd->defaultVisual = QX11Info::appDefaultVisual(xd->screen);
- xinfo.setX11Data(xd);
- }
-
- if (pixelType() == BitmapType) {
- bitmapFromImage(img);
- return;
- }
-
- if (uint(w) >= 32768 || uint(h) >= 32768) {
- w = h = 0;
- is_null = true;
- return;
- }
-
- QX11AlphaDetector alphaCheck(&img, flags);
- int dd = alphaCheck.hasXRenderAndAlpha() ? 32 : xinfo.depth();
-
- if (qt_x11_preferred_pixmap_depth)
- dd = qt_x11_preferred_pixmap_depth;
-
- QImage image = img;
-
- // must be monochrome
- if (dd == 1 || (flags & Qt::ColorMode_Mask) == Qt::MonoOnly) {
- if (d != 1) {
- // dither
- image = image.convertToFormat(QImage::Format_MonoLSB, flags);
- d = 1;
- }
- } else { // can be both
- bool conv8 = false;
- if (d > 8 && dd <= 8) { // convert to 8 bit
- if ((flags & Qt::DitherMode_Mask) == Qt::AutoDither)
- flags = (flags & ~Qt::DitherMode_Mask)
- | Qt::PreferDither;
- conv8 = true;
- } else if ((flags & Qt::ColorMode_Mask) == Qt::ColorOnly) {
- conv8 = (d == 1); // native depth wanted
- } else if (d == 1) {
- if (image.colorCount() == 2) {
- QRgb c0 = image.color(0); // Auto: convert to best
- QRgb c1 = image.color(1);
- conv8 = qMin(c0,c1) != qRgb(0,0,0) || qMax(c0,c1) != qRgb(255,255,255);
- } else {
- // eg. 1-color monochrome images (they do exist).
- conv8 = true;
- }
- }
- if (conv8) {
- image = image.convertToFormat(QImage::Format_Indexed8, flags);
- d = 8;
- }
- }
-
- if (d == 1 || d == 16 || d == 24) {
- image = image.convertToFormat(QImage::Format_RGB32, flags);
- fromImage(image, Qt::AutoColor);
- return;
- }
-
- Display *dpy = X11->display;
- Visual *visual = (Visual *)xinfo.visual();
- XImage *xi = 0;
- bool trucol = (visual->c_class >= TrueColor);
- int nbytes = image.byteCount();
- uchar *newbits= 0;
-
-#ifndef QT_NO_XRENDER
- if (alphaCheck.hasXRenderAndAlpha()) {
- const QImage &cimage = image;
-
- d = 32;
-
- if (QX11Info::appDepth() != d) {
- if (xinfo.x11data) {
- xinfo.x11data->depth = d;
- } else {
- QX11InfoData *xd = xinfo.getX11Data(true);
- xd->screen = QX11Info::appScreen();
- xd->depth = d;
- xd->cells = QX11Info::appCells();
- xd->colormap = QX11Info::appColormap();
- xd->defaultColormap = QX11Info::appDefaultColormap();
- xd->visual = (Visual *)QX11Info::appVisual();
- xd->defaultVisual = QX11Info::appDefaultVisual();
- xinfo.setX11Data(xd);
- }
- }
-
- hd = (Qt::HANDLE)XCreatePixmap(dpy, RootWindow(dpy, xinfo.screen()),
- w, h, d);
- picture = XRenderCreatePicture(X11->display, hd,
- XRenderFindStandardFormat(X11->display, PictStandardARGB32), 0, 0);
-
- xi = XCreateImage(dpy, visual, d, ZPixmap, 0, 0, w, h, 32, 0);
- Q_CHECK_PTR(xi);
- newbits = (uchar *)malloc(xi->bytes_per_line*h);
- Q_CHECK_PTR(newbits);
- xi->data = (char *)newbits;
-
- switch(cimage.format()) {
- case QImage::Format_Indexed8: {
- QVector<QRgb> colorTable = cimage.colorTable();
- uint *xidata = (uint *)xi->data;
- for (int y = 0; y < h; ++y) {
- const uchar *p = cimage.scanLine(y);
- for (int x = 0; x < w; ++x) {
- const QRgb rgb = colorTable[p[x]];
- const int a = qAlpha(rgb);
- if (a == 0xff)
- *xidata = rgb;
- else
- // RENDER expects premultiplied alpha
- *xidata = qRgba(qt_div_255(qRed(rgb) * a),
- qt_div_255(qGreen(rgb) * a),
- qt_div_255(qBlue(rgb) * a),
- a);
- ++xidata;
- }
- }
- }
- break;
- case QImage::Format_RGB32: {
- uint *xidata = (uint *)xi->data;
- for (int y = 0; y < h; ++y) {
- const QRgb *p = (const QRgb *) cimage.scanLine(y);
- for (int x = 0; x < w; ++x)
- *xidata++ = p[x] | 0xff000000;
- }
- }
- break;
- case QImage::Format_ARGB32: {
- uint *xidata = (uint *)xi->data;
- for (int y = 0; y < h; ++y) {
- const QRgb *p = (const QRgb *) cimage.scanLine(y);
- for (int x = 0; x < w; ++x) {
- const QRgb rgb = p[x];
- const int a = qAlpha(rgb);
- if (a == 0xff)
- *xidata = rgb;
- else
- // RENDER expects premultiplied alpha
- *xidata = qRgba(qt_div_255(qRed(rgb) * a),
- qt_div_255(qGreen(rgb) * a),
- qt_div_255(qBlue(rgb) * a),
- a);
- ++xidata;
- }
- }
-
- }
- break;
- case QImage::Format_ARGB32_Premultiplied: {
- uint *xidata = (uint *)xi->data;
- for (int y = 0; y < h; ++y) {
- const QRgb *p = (const QRgb *) cimage.scanLine(y);
- memcpy(xidata, p, w*sizeof(QRgb));
- xidata += w;
- }
- }
- break;
- default:
- Q_ASSERT(false);
- }
-
- if ((xi->byte_order == MSBFirst) != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
- uint *xidata = (uint *)xi->data;
- uint *xiend = xidata + w*h;
- while (xidata < xiend) {
- *xidata = (*xidata >> 24)
- | ((*xidata >> 8) & 0xff00)
- | ((*xidata << 8) & 0xff0000)
- | (*xidata << 24);
- ++xidata;
- }
- }
-
- GC gc = XCreateGC(dpy, hd, 0, 0);
- XPutImage(dpy, hd, gc, xi, 0, 0, 0, 0, w, h);
- XFreeGC(dpy, gc);
-
- qSafeXDestroyImage(xi);
-
- return;
- }
-#endif // QT_NO_XRENDER
-
- if (trucol) { // truecolor display
- if (image.format() == QImage::Format_ARGB32_Premultiplied)
- image = image.convertToFormat(QImage::Format_ARGB32);
-
- const QImage &cimage = image;
- QRgb pix[256]; // pixel translation table
- const bool d8 = (d == 8);
- const uint red_mask = (uint)visual->red_mask;
- const uint green_mask = (uint)visual->green_mask;
- const uint blue_mask = (uint)visual->blue_mask;
- const int red_shift = highest_bit(red_mask) - 7;
- const int green_shift = highest_bit(green_mask) - 7;
- const int blue_shift = highest_bit(blue_mask) - 7;
- const uint rbits = highest_bit(red_mask) - lowest_bit(red_mask) + 1;
- const uint gbits = highest_bit(green_mask) - lowest_bit(green_mask) + 1;
- const uint bbits = highest_bit(blue_mask) - lowest_bit(blue_mask) + 1;
-
- if (d8) { // setup pixel translation
- QVector<QRgb> ctable = cimage.colorTable();
- for (int i=0; i < cimage.colorCount(); i++) {
- int r = qRed (ctable[i]);
- int g = qGreen(ctable[i]);
- int b = qBlue (ctable[i]);
- r = red_shift > 0 ? r << red_shift : r >> -red_shift;
- g = green_shift > 0 ? g << green_shift : g >> -green_shift;
- b = blue_shift > 0 ? b << blue_shift : b >> -blue_shift;
- pix[i] = (b & blue_mask) | (g & green_mask) | (r & red_mask)
- | ~(blue_mask | green_mask | red_mask);
- }
- }
-
- xi = XCreateImage(dpy, visual, dd, ZPixmap, 0, 0, w, h, 32, 0);
- Q_CHECK_PTR(xi);
- newbits = (uchar *)malloc(xi->bytes_per_line*h);
- Q_CHECK_PTR(newbits);
- if (!newbits) // no memory
- return;
- int bppc = xi->bits_per_pixel;
-
- bool contig_bits = n_bits(red_mask) == rbits &&
- n_bits(green_mask) == gbits &&
- n_bits(blue_mask) == bbits;
- bool dither_tc =
- // Want it?
- (flags & Qt::Dither_Mask) != Qt::ThresholdDither &&
- (flags & Qt::DitherMode_Mask) != Qt::AvoidDither &&
- // Need it?
- bppc < 24 && !d8 &&
- // Can do it? (Contiguous bits?)
- contig_bits;
-
- static bool init=false;
- static int D[16][16];
- if (dither_tc && !init) {
- // I also contributed this code to XV - WWA.
- /*
- The dither matrix, D, is obtained with this formula:
-
- D2 = [0 2]
- [3 1]
-
-
- D2*n = [4*Dn 4*Dn+2*Un]
- [4*Dn+3*Un 4*Dn+1*Un]
- */
- int n,i,j;
- init=1;
-
- /* Set D2 */
- D[0][0]=0;
- D[1][0]=2;
- D[0][1]=3;
- D[1][1]=1;
-
- /* Expand using recursive definition given above */
- for (n=2; n<16; n*=2) {
- for (i=0; i<n; i++) {
- for (j=0; j<n; j++) {
- D[i][j]*=4;
- D[i+n][j]=D[i][j]+2;
- D[i][j+n]=D[i][j]+3;
- D[i+n][j+n]=D[i][j]+1;
- }
- }
- }
- init=true;
- }
-
- enum { BPP8,
- BPP16_565, BPP16_555,
- BPP16_MSB, BPP16_LSB,
- BPP24_888,
- BPP24_MSB, BPP24_LSB,
- BPP32_8888,
- BPP32_MSB, BPP32_LSB
- } mode = BPP8;
-
- bool same_msb_lsb = (xi->byte_order == MSBFirst) == (QSysInfo::ByteOrder == QSysInfo::BigEndian);
-
- if(bppc == 8) // 8 bit
- mode = BPP8;
- else if(bppc == 16) { // 16 bit MSB/LSB
- if(red_shift == 8 && green_shift == 3 && blue_shift == -3 && !d8 && same_msb_lsb)
- mode = BPP16_565;
- else if(red_shift == 7 && green_shift == 2 && blue_shift == -3 && !d8 && same_msb_lsb)
- mode = BPP16_555;
- else
- mode = (xi->byte_order == LSBFirst) ? BPP16_LSB : BPP16_MSB;
- } else if(bppc == 24) { // 24 bit MSB/LSB
- if (red_shift == 16 && green_shift == 8 && blue_shift == 0 && !d8 && same_msb_lsb)
- mode = BPP24_888;
- else
- mode = (xi->byte_order == LSBFirst) ? BPP24_LSB : BPP24_MSB;
- } else if(bppc == 32) { // 32 bit MSB/LSB
- if(red_shift == 16 && green_shift == 8 && blue_shift == 0 && !d8 && same_msb_lsb)
- mode = BPP32_8888;
- else
- mode = (xi->byte_order == LSBFirst) ? BPP32_LSB : BPP32_MSB;
- } else
- qFatal("Logic error 3");
-
-#define GET_PIXEL \
- uint pixel; \
- if (d8) pixel = pix[*src++]; \
- else { \
- int r = qRed (*p); \
- int g = qGreen(*p); \
- int b = qBlue (*p++); \
- r = red_shift > 0 \
- ? r << red_shift : r >> -red_shift; \
- g = green_shift > 0 \
- ? g << green_shift : g >> -green_shift; \
- b = blue_shift > 0 \
- ? b << blue_shift : b >> -blue_shift; \
- pixel = (r & red_mask)|(g & green_mask) | (b & blue_mask) \
- | ~(blue_mask | green_mask | red_mask); \
- }
-
-#define GET_PIXEL_DITHER_TC \
- int r = qRed (*p); \
- int g = qGreen(*p); \
- int b = qBlue (*p++); \
- const int thres = D[x%16][y%16]; \
- if (r <= (255-(1<<(8-rbits))) && ((r<<rbits) & 255) \
- > thres) \
- r += (1<<(8-rbits)); \
- if (g <= (255-(1<<(8-gbits))) && ((g<<gbits) & 255) \
- > thres) \
- g += (1<<(8-gbits)); \
- if (b <= (255-(1<<(8-bbits))) && ((b<<bbits) & 255) \
- > thres) \
- b += (1<<(8-bbits)); \
- r = red_shift > 0 \
- ? r << red_shift : r >> -red_shift; \
- g = green_shift > 0 \
- ? g << green_shift : g >> -green_shift; \
- b = blue_shift > 0 \
- ? b << blue_shift : b >> -blue_shift; \
- uint pixel = (r & red_mask)|(g & green_mask) | (b & blue_mask);
-
-// again, optimized case
-// can't be optimized that much :(
-#define GET_PIXEL_DITHER_TC_OPT(red_shift,green_shift,blue_shift,red_mask,green_mask,blue_mask, \
- rbits,gbits,bbits) \
- const int thres = D[x%16][y%16]; \
- int r = qRed (*p); \
- if (r <= (255-(1<<(8-rbits))) && ((r<<rbits) & 255) \
- > thres) \
- r += (1<<(8-rbits)); \
- int g = qGreen(*p); \
- if (g <= (255-(1<<(8-gbits))) && ((g<<gbits) & 255) \
- > thres) \
- g += (1<<(8-gbits)); \
- int b = qBlue (*p++); \
- if (b <= (255-(1<<(8-bbits))) && ((b<<bbits) & 255) \
- > thres) \
- b += (1<<(8-bbits)); \
- uint pixel = ((r red_shift) & red_mask) \
- | ((g green_shift) & green_mask) \
- | ((b blue_shift) & blue_mask);
-
-#define CYCLE(body) \
- for (int y=0; y<h; y++) { \
- const uchar* src = cimage.scanLine(y); \
- uchar* dst = newbits + xi->bytes_per_line*y; \
- const QRgb* p = (const QRgb *)src; \
- body \
- }
-
- if (dither_tc) {
- switch (mode) {
- case BPP16_565:
- CYCLE(
- quint16* dst16 = (quint16*)dst;
- for (int x=0; x<w; x++) {
- GET_PIXEL_DITHER_TC_OPT(<<8,<<3,>>3,0xf800,0x7e0,0x1f,5,6,5)
- *dst16++ = pixel;
- }
- )
- break;
- case BPP16_555:
- CYCLE(
- quint16* dst16 = (quint16*)dst;
- for (int x=0; x<w; x++) {
- GET_PIXEL_DITHER_TC_OPT(<<7,<<2,>>3,0x7c00,0x3e0,0x1f,5,5,5)
- *dst16++ = pixel;
- }
- )
- break;
- case BPP16_MSB: // 16 bit MSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL_DITHER_TC
- *dst++ = (pixel >> 8);
- *dst++ = pixel;
- }
- )
- break;
- case BPP16_LSB: // 16 bit LSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL_DITHER_TC
- *dst++ = pixel;
- *dst++ = pixel >> 8;
- }
- )
- break;
- default:
- qFatal("Logic error");
- }
- } else {
- switch (mode) {
- case BPP8: // 8 bit
- CYCLE(
- Q_UNUSED(p);
- for (int x=0; x<w; x++)
- *dst++ = pix[*src++];
- )
- break;
- case BPP16_565:
- CYCLE(
- quint16* dst16 = (quint16*)dst;
- for (int x = 0; x < w; x++) {
- *dst16++ = ((*p >> 8) & 0xf800)
- | ((*p >> 5) & 0x7e0)
- | ((*p >> 3) & 0x1f);
- ++p;
- }
- )
- break;
- case BPP16_555:
- CYCLE(
- quint16* dst16 = (quint16*)dst;
- for (int x=0; x<w; x++) {
- *dst16++ = ((*p >> 9) & 0x7c00)
- | ((*p >> 6) & 0x3e0)
- | ((*p >> 3) & 0x1f);
- ++p;
- }
- )
- break;
- case BPP16_MSB: // 16 bit MSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL
- *dst++ = (pixel >> 8);
- *dst++ = pixel;
- }
- )
- break;
- case BPP16_LSB: // 16 bit LSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL
- *dst++ = pixel;
- *dst++ = pixel >> 8;
- }
- )
- break;
- case BPP24_888: // 24 bit MSB
- CYCLE(
- for (int x=0; x<w; x++) {
- *dst++ = qRed (*p);
- *dst++ = qGreen(*p);
- *dst++ = qBlue (*p++);
- }
- )
- break;
- case BPP24_MSB: // 24 bit MSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL
- *dst++ = pixel >> 16;
- *dst++ = pixel >> 8;
- *dst++ = pixel;
- }
- )
- break;
- case BPP24_LSB: // 24 bit LSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL
- *dst++ = pixel;
- *dst++ = pixel >> 8;
- *dst++ = pixel >> 16;
- }
- )
- break;
- case BPP32_8888:
- CYCLE(
- memcpy(dst, p, w * 4);
- )
- break;
- case BPP32_MSB: // 32 bit MSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL
- *dst++ = pixel >> 24;
- *dst++ = pixel >> 16;
- *dst++ = pixel >> 8;
- *dst++ = pixel;
- }
- )
- break;
- case BPP32_LSB: // 32 bit LSB
- CYCLE(
- for (int x=0; x<w; x++) {
- GET_PIXEL
- *dst++ = pixel;
- *dst++ = pixel >> 8;
- *dst++ = pixel >> 16;
- *dst++ = pixel >> 24;
- }
- )
- break;
- default:
- qFatal("Logic error 2");
- }
- }
- xi->data = (char *)newbits;
- }
-
- if (d == 8 && !trucol) { // 8 bit pixmap
- int pop[256]; // pixel popularity
-
- if (image.colorCount() == 0)
- image.setColorCount(1);
-
- const QImage &cimage = image;
- memset(pop, 0, sizeof(int)*256); // reset popularity array
- for (int i = 0; i < h; i++) { // for each scanline...
- const uchar* p = cimage.scanLine(i);
- const uchar *end = p + w;
- while (p < end) // compute popularity
- pop[*p++]++;
- }
-
- newbits = (uchar *)malloc(nbytes); // copy image into newbits
- Q_CHECK_PTR(newbits);
- if (!newbits) // no memory
- return;
- uchar* p = newbits;
- memcpy(p, cimage.bits(), nbytes); // copy image data into newbits
-
- /*
- * The code below picks the most important colors. It is based on the
- * diversity algorithm, implemented in XV 3.10. XV is (C) by John Bradley.
- */
-
- struct PIX { // pixel sort element
- uchar r,g,b,n; // color + pad
- int use; // popularity
- int index; // index in colormap
- int mindist;
- };
- int ncols = 0;
- for (int i=0; i< cimage.colorCount(); i++) { // compute number of colors
- if (pop[i] > 0)
- ncols++;
- }
- for (int i = cimage.colorCount(); i < 256; i++) // ignore out-of-range pixels
- pop[i] = 0;
-
- // works since we make sure above to have at least
- // one color in the image
- if (ncols == 0)
- ncols = 1;
-
- PIX pixarr[256]; // pixel array
- PIX pixarr_sorted[256]; // pixel array (sorted)
- memset(pixarr, 0, ncols*sizeof(PIX));
- PIX *px = &pixarr[0];
- int maxpop = 0;
- int maxpix = 0;
- uint j = 0;
- QVector<QRgb> ctable = cimage.colorTable();
- for (int i = 0; i < 256; i++) { // init pixel array
- if (pop[i] > 0) {
- px->r = qRed (ctable[i]);
- px->g = qGreen(ctable[i]);
- px->b = qBlue (ctable[i]);
- px->n = 0;
- px->use = pop[i];
- if (pop[i] > maxpop) { // select most popular entry
- maxpop = pop[i];
- maxpix = j;
- }
- px->index = i;
- px->mindist = 1000000;
- px++;
- j++;
- }
- }
- pixarr_sorted[0] = pixarr[maxpix];
- pixarr[maxpix].use = 0;
-
- for (int i = 1; i < ncols; i++) { // sort pixels
- int minpix = -1, mindist = -1;
- px = &pixarr_sorted[i-1];
- int r = px->r;
- int g = px->g;
- int b = px->b;
- int dist;
- if ((i & 1) || i<10) { // sort on max distance
- for (int j=0; j<ncols; j++) {
- px = &pixarr[j];
- if (px->use) {
- dist = (px->r - r)*(px->r - r) +
- (px->g - g)*(px->g - g) +
- (px->b - b)*(px->b - b);
- if (px->mindist > dist)
- px->mindist = dist;
- if (px->mindist > mindist) {
- mindist = px->mindist;
- minpix = j;
- }
- }
- }
- } else { // sort on max popularity
- for (int j=0; j<ncols; j++) {
- px = &pixarr[j];
- if (px->use) {
- dist = (px->r - r)*(px->r - r) +
- (px->g - g)*(px->g - g) +
- (px->b - b)*(px->b - b);
- if (px->mindist > dist)
- px->mindist = dist;
- if (px->use > mindist) {
- mindist = px->use;
- minpix = j;
- }
- }
- }
- }
- pixarr_sorted[i] = pixarr[minpix];
- pixarr[minpix].use = 0;
- }
-
- QColormap cmap = QColormap::instance(xinfo.screen());
- uint pix[256]; // pixel translation table
- px = &pixarr_sorted[0];
- for (int i = 0; i < ncols; i++) { // allocate colors
- QColor c(px->r, px->g, px->b);
- pix[px->index] = cmap.pixel(c);
- px++;
- }
-
- p = newbits;
- for (int i = 0; i < nbytes; i++) { // translate pixels
- *p = pix[*p];
- p++;
- }
- }
-
- if (!xi) { // X image not created
- xi = XCreateImage(dpy, visual, dd, ZPixmap, 0, 0, w, h, 32, 0);
- if (xi->bits_per_pixel == 16) { // convert 8 bpp ==> 16 bpp
- ushort *p2;
- int p2inc = xi->bytes_per_line/sizeof(ushort);
- ushort *newerbits = (ushort *)malloc(xi->bytes_per_line * h);
- Q_CHECK_PTR(newerbits);
- if (!newerbits) // no memory
- return;
- uchar* p = newbits;
- for (int y = 0; y < h; y++) { // OOPS: Do right byte order!!
- p2 = newerbits + p2inc*y;
- for (int x = 0; x < w; x++)
- *p2++ = *p++;
- }
- free(newbits);
- newbits = (uchar *)newerbits;
- } else if (xi->bits_per_pixel != 8) {
- qWarning("QPixmap::fromImage: Display not supported "
- "(bpp=%d)", xi->bits_per_pixel);
- }
- xi->data = (char *)newbits;
- }
-
- hd = (Qt::HANDLE)XCreatePixmap(X11->display,
- RootWindow(X11->display, xinfo.screen()),
- w, h, dd);
-
- GC gc = XCreateGC(dpy, hd, 0, 0);
- XPutImage(dpy, hd, gc, xi, 0, 0, 0, 0, w, h);
- XFreeGC(dpy, gc);
-
- qSafeXDestroyImage(xi);
- d = dd;
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- XRenderPictFormat *format = d == 1
- ? XRenderFindStandardFormat(X11->display, PictStandardA1)
- : XRenderFindVisualFormat(X11->display, (Visual *)xinfo.visual());
- picture = XRenderCreatePicture(X11->display, hd, format, 0, 0);
- }
-#endif
-
- if (alphaCheck.hasAlpha()) {
- QBitmap m = QBitmap::fromImage(image.createAlphaMask(flags));
- setMask(m);
- }
-}
-
-Qt::HANDLE QX11PixmapData::createBitmapFromImage(const QImage &image)
-{
- QImage img = image.convertToFormat(QImage::Format_MonoLSB);
- const QRgb c0 = QColor(Qt::black).rgb();
- const QRgb c1 = QColor(Qt::white).rgb();
- if (img.color(0) == c0 && img.color(1) == c1) {
- img.invertPixels();
- img.setColor(0, c1);
- img.setColor(1, c0);
- }
-
- char *bits;
- uchar *tmp_bits;
- int w = img.width();
- int h = img.height();
- int bpl = (w + 7) / 8;
- int ibpl = img.bytesPerLine();
- if (bpl != ibpl) {
- tmp_bits = new uchar[bpl*h];
- bits = (char *)tmp_bits;
- uchar *p, *b;
- int y;
- b = tmp_bits;
- p = img.scanLine(0);
- for (y = 0; y < h; y++) {
- memcpy(b, p, bpl);
- b += bpl;
- p += ibpl;
- }
- } else {
- bits = (char *)img.bits();
- tmp_bits = 0;
- }
- Qt::HANDLE hd = (Qt::HANDLE)XCreateBitmapFromData(X11->display,
- QX11Info::appRootWindow(),
- bits, w, h);
- if (tmp_bits) // Avoid purify complaint
- delete [] tmp_bits;
- return hd;
-}
-
-void QX11PixmapData::bitmapFromImage(const QImage &image)
-{
- w = image.width();
- h = image.height();
- d = 1;
- is_null = (w <= 0 || h <= 0);
- hd = createBitmapFromImage(image);
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender)
- picture = XRenderCreatePicture(X11->display, hd,
- XRenderFindStandardFormat(X11->display, PictStandardA1), 0, 0);
-#endif // QT_NO_XRENDER
-}
-
-void QX11PixmapData::fill(const QColor &fillColor)
-{
- if (fillColor.alpha() != 255) {
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- if (!picture || d != 32)
- convertToARGB32(/*preserveContents = */false);
-
- ::Picture src = X11->getSolidFill(xinfo.screen(), fillColor);
- XRenderComposite(X11->display, PictOpSrc, src, 0, picture,
- 0, 0, width(), height(),
- 0, 0, width(), height());
- } else
-#endif
- {
- QImage im(width(), height(), QImage::Format_ARGB32_Premultiplied);
- im.fill(PREMUL(fillColor.rgba()));
- release();
- fromImage(im, Qt::AutoColor | Qt::OrderedAlphaDither);
- }
- return;
- }
-
- GC gc = XCreateGC(X11->display, hd, 0, 0);
- if (depth() == 1) {
- XSetForeground(X11->display, gc, qGray(fillColor.rgb()) > 127 ? 0 : 1);
- } else if (X11->use_xrender && d >= 24) {
- XSetForeground(X11->display, gc, fillColor.rgba());
- } else {
- XSetForeground(X11->display, gc,
- QColormap::instance(xinfo.screen()).pixel(fillColor));
- }
- XFillRectangle(X11->display, hd, gc, 0, 0, width(), height());
- XFreeGC(X11->display, gc);
-}
-
-QX11PixmapData::~QX11PixmapData()
-{
- // Cleanup hooks have to be called before the handles are freed
- if (is_cached) {
- QImagePixmapCleanupHooks::executePixmapDataDestructionHooks(this);
- is_cached = false;
- }
-
- release();
-}
-
-void QX11PixmapData::release()
-{
- delete pengine;
- pengine = 0;
-
- if (!X11) {
- // At this point, the X server will already have freed our resources,
- // so there is nothing to do.
- return;
- }
-
- if (x11_mask) {
-#ifndef QT_NO_XRENDER
- if (mask_picture)
- XRenderFreePicture(X11->display, mask_picture);
- mask_picture = 0;
-#endif
- XFreePixmap(X11->display, x11_mask);
- x11_mask = 0;
- }
-
- if (hd) {
-#ifndef QT_NO_XRENDER
- if (picture) {
- XRenderFreePicture(X11->display, picture);
- picture = 0;
- }
-#endif // QT_NO_XRENDER
-
- if (hd2) {
- XFreePixmap(xinfo.display(), hd2);
- hd2 = 0;
- }
- if (!(flags & Readonly))
- XFreePixmap(xinfo.display(), hd);
- hd = 0;
- }
-}
-
-QPixmap QX11PixmapData::alphaChannel() const
-{
- if (!hasAlphaChannel()) {
- QPixmap pm(w, h);
- pm.fill(Qt::white);
- return pm;
- }
- QImage im(toImage());
- return QPixmap::fromImage(im.alphaChannel(), Qt::OrderedDither);
-}
-
-void QX11PixmapData::setAlphaChannel(const QPixmap &alpha)
-{
- QImage image(toImage());
- image.setAlphaChannel(alpha.toImage());
- release();
- fromImage(image, Qt::OrderedDither | Qt::OrderedAlphaDither);
-}
-
-
-QBitmap QX11PixmapData::mask() const
-{
- QBitmap mask;
-#ifndef QT_NO_XRENDER
- if (picture && d == 32) {
- // #### slow - there must be a better way..
- mask = QBitmap::fromImage(toImage().createAlphaMask());
- } else
-#endif
- if (d == 1) {
- QX11PixmapData *that = const_cast<QX11PixmapData*>(this);
- mask = QPixmap(that);
- } else {
- mask = mask_to_bitmap(xinfo.screen());
- }
- return mask;
-}
-
-/*!
- Sets a mask bitmap.
-
- The \a newmask bitmap defines the clip mask for this pixmap. Every
- pixel in \a newmask corresponds to a pixel in this pixmap. Pixel
- value 1 means opaque and pixel value 0 means transparent. The mask
- must have the same size as this pixmap.
-
- \warning Setting the mask on a pixmap will cause any alpha channel
- data to be cleared. For example:
- \snippet doc/src/snippets/image/image.cpp 2
- Now, alpha and alphacopy are visually different.
-
- Setting a null mask resets the mask.
-
- The effect of this function is undefined when the pixmap is being
- painted on.
-
- \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap
- Transformations}, QBitmap
-*/
-void QX11PixmapData::setMask(const QBitmap &newmask)
-{
- if (newmask.isNull()) { // clear mask
-#ifndef QT_NO_XRENDER
- if (picture && d == 32) {
- QX11PixmapData newData(pixelType());
- newData.resize(w, h);
- newData.fill(Qt::black);
- XRenderComposite(X11->display, PictOpOver,
- picture, 0, newData.picture,
- 0, 0, 0, 0, 0, 0, w, h);
- release();
- *this = newData;
- // the new QX11PixmapData object isn't referenced yet, so
- // ref it
- ref.ref();
-
- // the below is to make sure the QX11PixmapData destructor
- // doesn't delete our newly created render picture
- newData.hd = 0;
- newData.x11_mask = 0;
- newData.picture = 0;
- newData.mask_picture = 0;
- newData.hd2 = 0;
- } else
-#endif
- if (x11_mask) {
-#ifndef QT_NO_XRENDER
- if (picture) {
- XRenderPictureAttributes attrs;
- attrs.alpha_map = 0;
- XRenderChangePicture(X11->display, picture, CPAlphaMap,
- &attrs);
- }
- if (mask_picture)
- XRenderFreePicture(X11->display, mask_picture);
- mask_picture = 0;
-#endif
- XFreePixmap(X11->display, x11_mask);
- x11_mask = 0;
- }
- return;
- }
-
-#ifndef QT_NO_XRENDER
- if (picture && d == 32) {
- XRenderComposite(X11->display, PictOpSrc,
- picture, newmask.x11PictureHandle(),
- picture, 0, 0, 0, 0, 0, 0, w, h);
- } else
-#endif
- if (depth() == 1) {
- XGCValues vals;
- vals.function = GXand;
- GC gc = XCreateGC(X11->display, hd, GCFunction, &vals);
- XCopyArea(X11->display, newmask.handle(), hd, gc, 0, 0,
- width(), height(), 0, 0);
- XFreeGC(X11->display, gc);
- } else {
- // ##### should or the masks together
- if (x11_mask) {
- XFreePixmap(X11->display, x11_mask);
-#ifndef QT_NO_XRENDER
- if (mask_picture)
- XRenderFreePicture(X11->display, mask_picture);
-#endif
- }
- x11_mask = QX11PixmapData::bitmap_to_mask(newmask, xinfo.screen());
-#ifndef QT_NO_XRENDER
- if (picture) {
- mask_picture = XRenderCreatePicture(X11->display, x11_mask,
- XRenderFindStandardFormat(X11->display, PictStandardA1), 0, 0);
- XRenderPictureAttributes attrs;
- attrs.alpha_map = mask_picture;
- XRenderChangePicture(X11->display, picture, CPAlphaMap, &attrs);
- }
-#endif
- }
-}
-
-int QX11PixmapData::metric(QPaintDevice::PaintDeviceMetric metric) const
-{
- switch (metric) {
- case QPaintDevice::PdmWidth:
- return w;
- case QPaintDevice::PdmHeight:
- return h;
- case QPaintDevice::PdmNumColors:
- return 1 << d;
- case QPaintDevice::PdmDepth:
- return d;
- case QPaintDevice::PdmWidthMM: {
- const int screen = xinfo.screen();
- const int mm = DisplayWidthMM(X11->display, screen) * w
- / DisplayWidth(X11->display, screen);
- return mm;
- }
- case QPaintDevice::PdmHeightMM: {
- const int screen = xinfo.screen();
- const int mm = (DisplayHeightMM(X11->display, screen) * h)
- / DisplayHeight(X11->display, screen);
- return mm;
- }
- case QPaintDevice::PdmDpiX:
- case QPaintDevice::PdmPhysicalDpiX:
- return QX11Info::appDpiX(xinfo.screen());
- case QPaintDevice::PdmDpiY:
- case QPaintDevice::PdmPhysicalDpiY:
- return QX11Info::appDpiY(xinfo.screen());
- default:
- qWarning("QX11PixmapData::metric(): Invalid metric");
- return 0;
- }
-}
-
-struct QXImageWrapper
-{
- XImage *xi;
-};
-
-bool QX11PixmapData::canTakeQImageFromXImage(const QXImageWrapper &xiWrapper) const
-{
- XImage *xi = xiWrapper.xi;
-
- // ARGB32_Premultiplied
- if (picture && depth() == 32)
- return true;
-
- Visual *visual = (Visual *)xinfo.visual();
-
- // RGB32
- if (depth() == 24 && xi->bits_per_pixel == 32 && visual->red_mask == 0xff0000
- && visual->green_mask == 0xff00 && visual->blue_mask == 0xff)
- return true;
-
- // RGB16
- if (depth() == 16 && xi->bits_per_pixel == 16 && visual->red_mask == 0xf800
- && visual->green_mask == 0x7e0 && visual->blue_mask == 0x1f)
- return true;
-
- return false;
-}
-
-QImage QX11PixmapData::takeQImageFromXImage(const QXImageWrapper &xiWrapper) const
-{
- XImage *xi = xiWrapper.xi;
-
- QImage::Format format = QImage::Format_ARGB32_Premultiplied;
- if (depth() == 24)
- format = QImage::Format_RGB32;
- else if (depth() == 16)
- format = QImage::Format_RGB16;
-
- QImage image((uchar *)xi->data, xi->width, xi->height, xi->bytes_per_line, format);
- // take ownership
- image.data_ptr()->own_data = true;
- xi->data = 0;
-
- // we may have to swap the byte order
- if ((QSysInfo::ByteOrder == QSysInfo::LittleEndian && xi->byte_order == MSBFirst)
- || (QSysInfo::ByteOrder == QSysInfo::BigEndian && xi->byte_order == LSBFirst))
- {
- for (int i=0; i < image.height(); i++) {
- if (depth() == 16) {
- ushort *p = (ushort*)image.scanLine(i);
- ushort *end = p + image.width();
- while (p < end) {
- *p = ((*p << 8) & 0xff00) | ((*p >> 8) & 0x00ff);
- p++;
- }
- } else {
- uint *p = (uint*)image.scanLine(i);
- uint *end = p + image.width();
- while (p < end) {
- *p = ((*p << 24) & 0xff000000) | ((*p << 8) & 0x00ff0000)
- | ((*p >> 8) & 0x0000ff00) | ((*p >> 24) & 0x000000ff);
- p++;
- }
- }
- }
- }
-
- // fix-up alpha channel
- if (format == QImage::Format_RGB32) {
- QRgb *p = (QRgb *)image.bits();
- for (int y = 0; y < xi->height; ++y) {
- for (int x = 0; x < xi->width; ++x)
- p[x] |= 0xff000000;
- p += xi->bytes_per_line / 4;
- }
- }
-
- XDestroyImage(xi);
- return image;
-}
-
-QImage QX11PixmapData::toImage(const QRect &rect) const
-{
- QXImageWrapper xiWrapper;
- xiWrapper.xi = XGetImage(X11->display, hd, rect.x(), rect.y(), rect.width(), rect.height(),
- AllPlanes, (depth() == 1) ? XYPixmap : ZPixmap);
-
- Q_CHECK_PTR(xiWrapper.xi);
- if (!xiWrapper.xi)
- return QImage();
-
- if (!x11_mask && canTakeQImageFromXImage(xiWrapper))
- return takeQImageFromXImage(xiWrapper);
-
- QImage image = toImage(xiWrapper, rect);
- qSafeXDestroyImage(xiWrapper.xi);
- return image;
-}
-
-/*!
- Converts the pixmap to a QImage. Returns a null image if the
- conversion fails.
-
- If the pixmap has 1-bit depth, the returned image will also be 1
- bit deep. If the pixmap has 2- to 8-bit depth, the returned image
- has 8-bit depth. If the pixmap has greater than 8-bit depth, the
- returned image has 32-bit depth.
-
- Note that for the moment, alpha masks on monochrome images are
- ignored.
-
- \sa fromImage(), {QImage#Image Formats}{Image Formats}
-*/
-
-QImage QX11PixmapData::toImage() const
-{
- return toImage(QRect(0, 0, w, h));
-}
-
-QImage QX11PixmapData::toImage(const QXImageWrapper &xiWrapper, const QRect &rect) const
-{
- XImage *xi = xiWrapper.xi;
-
- int d = depth();
- Visual *visual = (Visual *)xinfo.visual();
- bool trucol = (visual->c_class >= TrueColor) && d > 1;
-
- QImage::Format format = QImage::Format_Mono;
- if (d > 1 && d <= 8) {
- d = 8;
- format = QImage::Format_Indexed8;
- }
- // we could run into the situation where d == 8 AND trucol is true, which can
- // cause problems when converting to and from images. in this case, always treat
- // the depth as 32...
- if (d > 8 || trucol) {
- d = 32;
- format = QImage::Format_RGB32;
- }
-
- if (d == 1 && xi->bitmap_bit_order == LSBFirst)
- format = QImage::Format_MonoLSB;
- if (x11_mask && format == QImage::Format_RGB32)
- format = QImage::Format_ARGB32;
-
- QImage image(xi->width, xi->height, format);
- if (image.isNull()) // could not create image
- return image;
-
- QImage alpha;
- if (x11_mask) {
- if (rect.contains(QRect(0, 0, w, h)))
- alpha = mask().toImage();
- else
- alpha = mask().toImage().copy(rect);
- }
- bool ale = alpha.format() == QImage::Format_MonoLSB;
-
- if (trucol) { // truecolor
- const uint red_mask = (uint)visual->red_mask;
- const uint green_mask = (uint)visual->green_mask;
- const uint blue_mask = (uint)visual->blue_mask;
- const int red_shift = highest_bit(red_mask) - 7;
- const int green_shift = highest_bit(green_mask) - 7;
- const int blue_shift = highest_bit(blue_mask) - 7;
-
- const uint red_bits = n_bits(red_mask);
- const uint green_bits = n_bits(green_mask);
- const uint blue_bits = n_bits(blue_mask);
-
- static uint red_table_bits = 0;
- static uint green_table_bits = 0;
- static uint blue_table_bits = 0;
-
- if (red_bits < 8 && red_table_bits != red_bits) {
- build_scale_table(&red_scale_table, red_bits);
- red_table_bits = red_bits;
- }
- if (blue_bits < 8 && blue_table_bits != blue_bits) {
- build_scale_table(&blue_scale_table, blue_bits);
- blue_table_bits = blue_bits;
- }
- if (green_bits < 8 && green_table_bits != green_bits) {
- build_scale_table(&green_scale_table, green_bits);
- green_table_bits = green_bits;
- }
-
- int r, g, b;
-
- QRgb *dst;
- uchar *src;
- uint pixel;
- int bppc = xi->bits_per_pixel;
-
- if (bppc > 8 && xi->byte_order == LSBFirst)
- bppc++;
-
- for (int y = 0; y < xi->height; ++y) {
- uchar* asrc = x11_mask ? alpha.scanLine(y) : 0;
- dst = (QRgb *)image.scanLine(y);
- src = (uchar *)xi->data + xi->bytes_per_line*y;
- for (int x = 0; x < xi->width; x++) {
- switch (bppc) {
- case 8:
- pixel = *src++;
- break;
- case 16: // 16 bit MSB
- pixel = src[1] | (uint)src[0] << 8;
- src += 2;
- break;
- case 17: // 16 bit LSB
- pixel = src[0] | (uint)src[1] << 8;
- src += 2;
- break;
- case 24: // 24 bit MSB
- pixel = src[2] | (uint)src[1] << 8 | (uint)src[0] << 16;
- src += 3;
- break;
- case 25: // 24 bit LSB
- pixel = src[0] | (uint)src[1] << 8 | (uint)src[2] << 16;
- src += 3;
- break;
- case 32: // 32 bit MSB
- pixel = src[3] | (uint)src[2] << 8 | (uint)src[1] << 16 | (uint)src[0] << 24;
- src += 4;
- break;
- case 33: // 32 bit LSB
- pixel = src[0] | (uint)src[1] << 8 | (uint)src[2] << 16 | (uint)src[3] << 24;
- src += 4;
- break;
- default: // should not really happen
- x = xi->width; // leave loop
- y = xi->height;
- pixel = 0; // eliminate compiler warning
- qWarning("QPixmap::convertToImage: Invalid depth %d", bppc);
- }
- if (red_shift > 0)
- r = (pixel & red_mask) >> red_shift;
- else
- r = (pixel & red_mask) << -red_shift;
- if (green_shift > 0)
- g = (pixel & green_mask) >> green_shift;
- else
- g = (pixel & green_mask) << -green_shift;
- if (blue_shift > 0)
- b = (pixel & blue_mask) >> blue_shift;
- else
- b = (pixel & blue_mask) << -blue_shift;
-
- if (red_bits < 8)
- r = red_scale_table[r];
- if (green_bits < 8)
- g = green_scale_table[g];
- if (blue_bits < 8)
- b = blue_scale_table[b];
-
- if (x11_mask) {
- if (ale) {
- *dst++ = (asrc[x >> 3] & (1 << (x & 7))) ? qRgba(r, g, b, 0xff) : 0;
- } else {
- *dst++ = (asrc[x >> 3] & (0x80 >> (x & 7))) ? qRgba(r, g, b, 0xff) : 0;
- }
- } else {
- *dst++ = qRgb(r, g, b);
- }
- }
- }
- } else if (xi->bits_per_pixel == d) { // compatible depth
- char *xidata = xi->data; // copy each scanline
- int bpl = qMin(image.bytesPerLine(),xi->bytes_per_line);
- for (int y=0; y<xi->height; y++) {
- memcpy(image.scanLine(y), xidata, bpl);
- xidata += xi->bytes_per_line;
- }
- } else {
- /* Typically 2 or 4 bits display depth */
- qWarning("QPixmap::convertToImage: Display not supported (bpp=%d)",
- xi->bits_per_pixel);
- return QImage();
- }
-
- if (d == 1) { // bitmap
- image.setColorCount(2);
- image.setColor(0, qRgb(255,255,255));
- image.setColor(1, qRgb(0,0,0));
- } else if (!trucol) { // pixmap with colormap
- register uchar *p;
- uchar *end;
- uchar use[256]; // pixel-in-use table
- uchar pix[256]; // pixel translation table
- int ncols, bpl;
- memset(use, 0, 256);
- memset(pix, 0, 256);
- bpl = image.bytesPerLine();
-
- if (x11_mask) { // which pixels are used?
- for (int i = 0; i < xi->height; i++) {
- uchar* asrc = alpha.scanLine(i);
- p = image.scanLine(i);
- if (ale) {
- for (int x = 0; x < xi->width; x++) {
- if (asrc[x >> 3] & (1 << (x & 7)))
- use[*p] = 1;
- ++p;
- }
- } else {
- for (int x = 0; x < xi->width; x++) {
- if (asrc[x >> 3] & (0x80 >> (x & 7)))
- use[*p] = 1;
- ++p;
- }
- }
- }
- } else {
- for (int i = 0; i < xi->height; i++) {
- p = image.scanLine(i);
- end = p + bpl;
- while (p < end)
- use[*p++] = 1;
- }
- }
- ncols = 0;
- for (int i = 0; i < 256; i++) { // build translation table
- if (use[i])
- pix[i] = ncols++;
- }
- for (int i = 0; i < xi->height; i++) { // translate pixels
- p = image.scanLine(i);
- end = p + bpl;
- while (p < end) {
- *p = pix[*p];
- p++;
- }
- }
- if (x11_mask) {
- int trans;
- if (ncols < 256) {
- trans = ncols++;
- image.setColorCount(ncols); // create color table
- image.setColor(trans, 0x00000000);
- } else {
- image.setColorCount(ncols); // create color table
- // oh dear... no spare "transparent" pixel.
- // use first pixel in image (as good as any).
- trans = image.scanLine(0)[0];
- }
- for (int i = 0; i < xi->height; i++) {
- uchar* asrc = alpha.scanLine(i);
- p = image.scanLine(i);
- if (ale) {
- for (int x = 0; x < xi->width; x++) {
- if (!(asrc[x >> 3] & (1 << (x & 7))))
- *p = trans;
- ++p;
- }
- } else {
- for (int x = 0; x < xi->width; x++) {
- if (!(asrc[x >> 3] & (1 << (7 -(x & 7)))))
- *p = trans;
- ++p;
- }
- }
- }
- } else {
- image.setColorCount(ncols); // create color table
- }
- QVector<QColor> colors = QColormap::instance(xinfo.screen()).colormap();
- int j = 0;
- for (int i=0; i<colors.size(); i++) { // translate pixels
- if (use[i])
- image.setColor(j++, 0xff000000 | colors.at(i).rgb());
- }
- }
-
- return image;
-}
-
-/*!
- Returns a copy of the pixmap that is transformed using the given
- transformation \a matrix and transformation \a mode. The original
- pixmap is not changed.
-
- The transformation \a matrix is internally adjusted to compensate
- for unwanted translation; i.e. the pixmap produced is the smallest
- pixmap that contains all the transformed points of the original
- pixmap. Use the trueMatrix() function to retrieve the actual
- matrix used for transforming the pixmap.
-
- This function is slow because it involves transformation to a
- QImage, non-trivial computations and a transformation back to a
- QPixmap.
-
- \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
- Transformations}
-*/
-QPixmap QX11PixmapData::transformed(const QTransform &transform,
- Qt::TransformationMode mode ) const
-{
- if (mode == Qt::SmoothTransformation || transform.type() >= QTransform::TxProject) {
- QImage image = toImage();
- return QPixmap::fromImage(image.transformed(transform, mode));
- }
-
- uint w = 0;
- uint h = 0; // size of target pixmap
- uint ws, hs; // size of source pixmap
- uchar *dptr; // data in target pixmap
- uint dbpl, dbytes; // bytes per line/bytes total
- uchar *sptr; // data in original pixmap
- int sbpl; // bytes per line in original
- int bpp; // bits per pixel
- bool depth1 = depth() == 1;
- Display *dpy = X11->display;
-
- ws = width();
- hs = height();
-
- QTransform mat(transform.m11(), transform.m12(), transform.m13(),
- transform.m21(), transform.m22(), transform.m23(),
- 0., 0., 1);
- bool complex_xform = false;
- qreal scaledWidth;
- qreal scaledHeight;
-
- if (mat.type() <= QTransform::TxScale) {
- scaledHeight = qAbs(mat.m22()) * hs + 0.9999;
- scaledWidth = qAbs(mat.m11()) * ws + 0.9999;
- h = qAbs(int(scaledHeight));
- w = qAbs(int(scaledWidth));
- } else { // rotation or shearing
- QPolygonF a(QRectF(0, 0, ws, hs));
- a = mat.map(a);
- QRect r = a.boundingRect().toAlignedRect();
- w = r.width();
- h = r.height();
- scaledWidth = w;
- scaledHeight = h;
- complex_xform = true;
- }
- mat = QPixmap::trueMatrix(mat, ws, hs); // true matrix
-
- bool invertible;
- mat = mat.inverted(&invertible); // invert matrix
-
- if (h == 0 || w == 0 || !invertible
- || qAbs(scaledWidth) >= 32768 || qAbs(scaledHeight) >= 32768 )
- // error, return null pixmap
- return QPixmap();
-
-#if defined(QT_MITSHM)
- static bool try_once = true;
- if (try_once) {
- try_once = false;
- if (!xshminit)
- qt_create_mitshm_buffer(this, 800, 600);
- }
-
- bool use_mitshm = xshmimg && !depth1 &&
- xshmimg->width >= w && xshmimg->height >= h;
-#endif
- XImage *xi = XGetImage(X11->display, handle(), 0, 0, ws, hs, AllPlanes,
- depth1 ? XYPixmap : ZPixmap);
-
- if (!xi)
- return QPixmap();
-
- sbpl = xi->bytes_per_line;
- sptr = (uchar *)xi->data;
- bpp = xi->bits_per_pixel;
-
- if (depth1)
- dbpl = (w+7)/8;
- else
- dbpl = ((w*bpp+31)/32)*4;
- dbytes = dbpl*h;
-
-#if defined(QT_MITSHM)
- if (use_mitshm) {
- dptr = (uchar *)xshmimg->data;
- uchar fillbyte = bpp == 8 ? white.pixel() : 0xff;
- for (int y=0; y<h; y++)
- memset(dptr + y*xshmimg->bytes_per_line, fillbyte, dbpl);
- } else {
-#endif
- dptr = (uchar *)malloc(dbytes); // create buffer for bits
- Q_CHECK_PTR(dptr);
- if (depth1) // fill with zeros
- memset(dptr, 0, dbytes);
- else if (bpp == 8) // fill with background color
- memset(dptr, WhitePixel(X11->display, xinfo.screen()), dbytes);
- else
- memset(dptr, 0, dbytes);
-#if defined(QT_MITSHM)
- }
-#endif
-
- // #define QT_DEBUG_XIMAGE
-#if defined(QT_DEBUG_XIMAGE)
- qDebug("----IMAGE--INFO--------------");
- qDebug("width............. %d", xi->width);
- qDebug("height............ %d", xi->height);
- qDebug("xoffset........... %d", xi->xoffset);
- qDebug("format............ %d", xi->format);
- qDebug("byte order........ %d", xi->byte_order);
- qDebug("bitmap unit....... %d", xi->bitmap_unit);
- qDebug("bitmap bit order.. %d", xi->bitmap_bit_order);
- qDebug("depth............. %d", xi->depth);
- qDebug("bytes per line.... %d", xi->bytes_per_line);
- qDebug("bits per pixel.... %d", xi->bits_per_pixel);
-#endif
-
- int type;
- if (xi->bitmap_bit_order == MSBFirst)
- type = QT_XFORM_TYPE_MSBFIRST;
- else
- type = QT_XFORM_TYPE_LSBFIRST;
- int xbpl, p_inc;
- if (depth1) {
- xbpl = (w+7)/8;
- p_inc = dbpl - xbpl;
- } else {
- xbpl = (w*bpp)/8;
- p_inc = dbpl - xbpl;
-#if defined(QT_MITSHM)
- if (use_mitshm)
- p_inc = xshmimg->bytes_per_line - xbpl;
-#endif
- }
-
- if (!qt_xForm_helper(mat, xi->xoffset, type, bpp, dptr, xbpl, p_inc, h, sptr, sbpl, ws, hs)){
- qWarning("QPixmap::transform: display not supported (bpp=%d)",bpp);
- QPixmap pm;
- return pm;
- }
-
- qSafeXDestroyImage(xi);
-
- if (depth1) { // mono bitmap
- QBitmap bm = QBitmap::fromData(QSize(w, h), dptr,
- BitmapBitOrder(X11->display) == MSBFirst
- ? QImage::Format_Mono
- : QImage::Format_MonoLSB);
- free(dptr);
- return bm;
- } else { // color pixmap
- QX11PixmapData *x11Data = new QX11PixmapData(QPixmapData::PixmapType);
- QPixmap pm(x11Data);
- x11Data->flags &= ~QX11PixmapData::Uninitialized;
- x11Data->xinfo = xinfo;
- x11Data->d = d;
- x11Data->w = w;
- x11Data->h = h;
- x11Data->is_null = (w <= 0 || h <= 0);
- x11Data->hd = (Qt::HANDLE)XCreatePixmap(X11->display,
- RootWindow(X11->display, xinfo.screen()),
- w, h, d);
- x11Data->setSerialNumber(qt_pixmap_serial.fetchAndAddRelaxed(1));
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- XRenderPictFormat *format = x11Data->d == 32
- ? XRenderFindStandardFormat(X11->display, PictStandardARGB32)
- : XRenderFindVisualFormat(X11->display, (Visual *) x11Data->xinfo.visual());
- x11Data->picture = XRenderCreatePicture(X11->display, x11Data->hd, format, 0, 0);
- }
-#endif // QT_NO_XRENDER
-
- GC gc = XCreateGC(X11->display, x11Data->hd, 0, 0);
-#if defined(QT_MITSHM)
- if (use_mitshm) {
- XCopyArea(dpy, xshmpm, x11Data->hd, gc, 0, 0, w, h, 0, 0);
- } else
-#endif
- {
- xi = XCreateImage(dpy, (Visual*)x11Data->xinfo.visual(),
- x11Data->d,
- ZPixmap, 0, (char *)dptr, w, h, 32, 0);
- XPutImage(dpy, pm.handle(), gc, xi, 0, 0, 0, 0, w, h);
- qSafeXDestroyImage(xi);
- }
- XFreeGC(X11->display, gc);
-
- if (x11_mask) { // xform mask, too
- pm.setMask(mask_to_bitmap(xinfo.screen()).transformed(transform));
- } else if (d != 32 && complex_xform) { // need a mask!
- QBitmap mask(ws, hs);
- mask.fill(Qt::color1);
- pm.setMask(mask.transformed(transform));
- }
- return pm;
- }
-}
-
-int QPixmap::x11SetDefaultScreen(int screen)
-{
- int old = defaultScreen;
- defaultScreen = screen;
- return old;
-}
-
-void QPixmap::x11SetScreen(int screen)
-{
- if (paintingActive()) {
- qWarning("QPixmap::x11SetScreen(): Cannot change screens during painting");
- return;
- }
-
- if (isNull())
- return;
-
- if (data->classId() != QPixmapData::X11Class)
- return;
-
- if (screen < 0)
- screen = QX11Info::appScreen();
-
- QX11PixmapData *x11Data = static_cast<QX11PixmapData*>(data.data());
- if (screen == x11Data->xinfo.screen())
- return; // nothing to do
-
- if (isNull()) {
- QX11InfoData* xd = x11Data->xinfo.getX11Data(true);
- xd->screen = screen;
- xd->depth = QX11Info::appDepth(screen);
- xd->cells = QX11Info::appCells(screen);
- xd->colormap = QX11Info::appColormap(screen);
- xd->defaultColormap = QX11Info::appDefaultColormap(screen);
- xd->visual = (Visual *)QX11Info::appVisual(screen);
- xd->defaultVisual = QX11Info::appDefaultVisual(screen);
- x11Data->xinfo.setX11Data(xd);
- return;
- }
-#if 0
- qDebug("QPixmap::x11SetScreen for %p from %d to %d. Size is %d/%d", x11Data, x11Data->xinfo.screen(), screen, width(), height());
-#endif
-
- x11SetDefaultScreen(screen);
- *this = qt_toX11Pixmap(toImage());
-}
-
-QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
-{
- if (w == 0 || h == 0)
- return QPixmap();
-
- Display *dpy = X11->display;
- XWindowAttributes window_attr;
- if (!XGetWindowAttributes(dpy, window, &window_attr))
- return QPixmap();
-
- if (w < 0)
- w = window_attr.width - x;
- if (h < 0)
- h = window_attr.height - y;
-
- // determine the screen
- int scr;
- for (scr = 0; scr < ScreenCount(dpy); ++scr) {
- if (window_attr.root == RootWindow(dpy, scr)) // found it
- break;
- }
- if (scr >= ScreenCount(dpy)) // sanity check
- return QPixmap();
-
-
- // get the depth of the root window
- XWindowAttributes root_attr;
- if (!XGetWindowAttributes(dpy, window_attr.root, &root_attr))
- return QPixmap();
-
- if (window_attr.depth == root_attr.depth) {
- // if the depth of the specified window and the root window are the
- // same, grab pixels from the root window (so that we get the any
- // overlapping windows and window manager frames)
-
- // map x and y to the root window
- WId unused;
- if (!XTranslateCoordinates(dpy, window, window_attr.root, x, y,
- &x, &y, &unused))
- return QPixmap();
-
- window = window_attr.root;
- window_attr = root_attr;
- }
-
- QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType);
-
- void qt_x11_getX11InfoForWindow(QX11Info * xinfo, const XWindowAttributes &a);
- qt_x11_getX11InfoForWindow(&data->xinfo,window_attr);
-
- data->resize(w, h);
-
- QPixmap pm(data);
-
- data->flags &= ~QX11PixmapData::Uninitialized;
- pm.x11SetScreen(scr);
-
- GC gc = XCreateGC(dpy, pm.handle(), 0, 0);
- XSetSubwindowMode(dpy, gc, IncludeInferiors);
- XCopyArea(dpy, window, pm.handle(), gc, x, y, w, h, 0, 0);
- XFreeGC(dpy, gc);
-
- return pm;
-}
-
-bool QX11PixmapData::hasAlphaChannel() const
-{
- return d == 32;
-}
-
-const QX11Info &QPixmap::x11Info() const
-{
- if (data && data->classId() == QPixmapData::X11Class)
- return static_cast<QX11PixmapData*>(data.data())->xinfo;
- else {
- static QX11Info nullX11Info;
- return nullX11Info;
- }
-}
-
-#if !defined(QT_NO_XRENDER)
-static XRenderPictFormat *qt_renderformat_for_depth(const QX11Info &xinfo, int depth)
-{
- if (depth == 1)
- return XRenderFindStandardFormat(X11->display, PictStandardA1);
- else if (depth == 32)
- return XRenderFindStandardFormat(X11->display, PictStandardARGB32);
- else
- return XRenderFindVisualFormat(X11->display, (Visual *)xinfo.visual());
-}
-#endif
-
-QPaintEngine* QX11PixmapData::paintEngine() const
-{
- QX11PixmapData *that = const_cast<QX11PixmapData*>(this);
-
- if ((flags & Readonly) && share_mode == QPixmap::ImplicitlyShared) {
- // if someone wants to draw onto us, copy the shared contents
- // and turn it into a fully fledged QPixmap
- ::Pixmap hd_copy = XCreatePixmap(X11->display, RootWindow(X11->display, xinfo.screen()),
- w, h, d);
-#if !defined(QT_NO_XRENDER)
- XRenderPictFormat *format = qt_renderformat_for_depth(xinfo, d);
- ::Picture picture_copy = XRenderCreatePicture(X11->display, hd_copy, format, 0, 0);
-
- if (picture && d == 32) {
- XRenderComposite(X11->display, PictOpSrc, picture, 0, picture_copy,
- 0, 0, 0, 0, 0, 0, w, h);
- XRenderFreePicture(X11->display, picture);
- that->picture = picture_copy;
- } else
-#endif
- {
- GC gc = XCreateGC(X11->display, hd_copy, 0, 0);
- XCopyArea(X11->display, hd, hd_copy, gc, 0, 0, w, h, 0, 0);
- XFreeGC(X11->display, gc);
- }
- that->hd = hd_copy;
- that->flags &= ~QX11PixmapData::Readonly;
- }
-
- if (!that->pengine)
- that->pengine = new QX11PaintEngine;
- return that->pengine;
-}
-
-Qt::HANDLE QPixmap::x11PictureHandle() const
-{
-#ifndef QT_NO_XRENDER
- if (data && data->classId() == QPixmapData::X11Class)
- return static_cast<const QX11PixmapData*>(data.data())->picture;
- else
- return 0;
-#else
- return 0;
-#endif // QT_NO_XRENDER
-}
-
-Qt::HANDLE QX11PixmapData::x11ConvertToDefaultDepth()
-{
-#ifndef QT_NO_XRENDER
- if (d == QX11Info::appDepth() || !X11->use_xrender)
- return hd;
- if (!hd2) {
- hd2 = XCreatePixmap(xinfo.display(), hd, w, h, QX11Info::appDepth());
- XRenderPictFormat *format = XRenderFindVisualFormat(xinfo.display(),
- (Visual*) xinfo.visual());
- Picture pic = XRenderCreatePicture(xinfo.display(), hd2, format, 0, 0);
- XRenderComposite(xinfo.display(), PictOpSrc, picture,
- XNone, pic, 0, 0, 0, 0, 0, 0, w, h);
- XRenderFreePicture(xinfo.display(), pic);
- }
- return hd2;
-#else
- return hd;
-#endif
-}
-
-void QX11PixmapData::copy(const QPixmapData *data, const QRect &rect)
-{
- if (data->pixelType() == BitmapType) {
- fromImage(data->toImage().copy(rect), Qt::AutoColor);
- return;
- }
-
- const QX11PixmapData *x11Data = static_cast<const QX11PixmapData*>(data);
-
- setSerialNumber(qt_pixmap_serial.fetchAndAddRelaxed(1));
-
- flags &= ~Uninitialized;
- xinfo = x11Data->xinfo;
- d = x11Data->d;
- w = rect.width();
- h = rect.height();
- is_null = (w <= 0 || h <= 0);
- hd = (Qt::HANDLE)XCreatePixmap(X11->display,
- RootWindow(X11->display, x11Data->xinfo.screen()),
- w, h, d);
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- XRenderPictFormat *format = d == 32
- ? XRenderFindStandardFormat(X11->display, PictStandardARGB32)
- : XRenderFindVisualFormat(X11->display, (Visual *)xinfo.visual());
- picture = XRenderCreatePicture(X11->display, hd, format, 0, 0);
- }
-#endif // QT_NO_XRENDER
- if (x11Data->x11_mask) {
- x11_mask = XCreatePixmap(X11->display, hd, w, h, 1);
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- mask_picture = XRenderCreatePicture(X11->display, x11_mask,
- XRenderFindStandardFormat(X11->display, PictStandardA1), 0, 0);
- XRenderPictureAttributes attrs;
- attrs.alpha_map = x11Data->mask_picture;
- XRenderChangePicture(X11->display, x11Data->picture, CPAlphaMap, &attrs);
- }
-#endif
- }
-
-#if !defined(QT_NO_XRENDER)
- if (x11Data->picture && x11Data->d == 32) {
- XRenderComposite(X11->display, PictOpSrc,
- x11Data->picture, 0, picture,
- rect.x(), rect.y(), 0, 0, 0, 0, w, h);
- } else
-#endif
- {
- GC gc = XCreateGC(X11->display, hd, 0, 0);
- XCopyArea(X11->display, x11Data->hd, hd, gc,
- rect.x(), rect.y(), w, h, 0, 0);
- if (x11Data->x11_mask) {
- GC monogc = XCreateGC(X11->display, x11_mask, 0, 0);
- XCopyArea(X11->display, x11Data->x11_mask, x11_mask, monogc,
- rect.x(), rect.y(), w, h, 0, 0);
- XFreeGC(X11->display, monogc);
- }
- XFreeGC(X11->display, gc);
- }
-}
-
-bool QX11PixmapData::scroll(int dx, int dy, const QRect &rect)
-{
- GC gc = XCreateGC(X11->display, hd, 0, 0);
- XCopyArea(X11->display, hd, hd, gc,
- rect.left(), rect.top(), rect.width(), rect.height(),
- rect.left() + dx, rect.top() + dy);
- XFreeGC(X11->display, gc);
- return true;
-}
-
-#if !defined(QT_NO_XRENDER)
-void QX11PixmapData::convertToARGB32(bool preserveContents)
-{
- if (!X11->use_xrender)
- return;
-
- // Q_ASSERT(count == 1);
- if ((flags & Readonly) && share_mode == QPixmap::ExplicitlyShared)
- return;
-
- Pixmap pm = XCreatePixmap(X11->display, RootWindow(X11->display, xinfo.screen()),
- w, h, 32);
- Picture p = XRenderCreatePicture(X11->display, pm,
- XRenderFindStandardFormat(X11->display, PictStandardARGB32), 0, 0);
- if (picture) {
- if (preserveContents)
- XRenderComposite(X11->display, PictOpSrc, picture, 0, p, 0, 0, 0, 0, 0, 0, w, h);
- if (!(flags & Readonly))
- XRenderFreePicture(X11->display, picture);
- }
- if (hd && !(flags & Readonly))
- XFreePixmap(X11->display, hd);
- if (x11_mask) {
- XFreePixmap(X11->display, x11_mask);
- if (mask_picture)
- XRenderFreePicture(X11->display, mask_picture);
- x11_mask = 0;
- mask_picture = 0;
- }
- hd = pm;
- picture = p;
- d = 32;
-}
-#endif
-
-QPixmap QPixmap::fromX11Pixmap(Qt::HANDLE pixmap, QPixmap::ShareMode mode)
-{
- Window root;
- int x;
- int y;
- uint width;
- uint height;
- uint border_width;
- uint depth;
- XWindowAttributes win_attribs;
- int num_screens = ScreenCount(X11->display);
- int screen = 0;
-
- XGetGeometry(X11->display, pixmap, &root, &x, &y, &width, &height, &border_width, &depth);
- XGetWindowAttributes(X11->display, root, &win_attribs);
-
- for (; screen < num_screens; ++screen) {
- if (win_attribs.screen == ScreenOfDisplay(X11->display, screen))
- break;
- }
-
- QX11PixmapData *data = new QX11PixmapData(depth == 1 ? QPixmapData::BitmapType : QPixmapData::PixmapType);
- data->setSerialNumber(qt_pixmap_serial.fetchAndAddRelaxed(1));
- data->flags = QX11PixmapData::Readonly;
- data->share_mode = mode;
- data->w = width;
- data->h = height;
- data->is_null = (width <= 0 || height <= 0);
- data->d = depth;
- data->hd = pixmap;
-
- if (defaultScreen >= 0 && defaultScreen != screen) {
- QX11InfoData* xd = data->xinfo.getX11Data(true);
- xd->screen = defaultScreen;
- xd->depth = QX11Info::appDepth(xd->screen);
- xd->cells = QX11Info::appCells(xd->screen);
- xd->colormap = QX11Info::appColormap(xd->screen);
- xd->defaultColormap = QX11Info::appDefaultColormap(xd->screen);
- xd->visual = (Visual *)QX11Info::appVisual(xd->screen);
- xd->defaultVisual = QX11Info::appDefaultVisual(xd->screen);
- data->xinfo.setX11Data(xd);
- }
-
-#ifndef QT_NO_XRENDER
- if (X11->use_xrender) {
- XRenderPictFormat *format = qt_renderformat_for_depth(data->xinfo, depth);
- data->picture = XRenderCreatePicture(X11->display, data->hd, format, 0, 0);
- }
-#endif // QT_NO_XRENDER
-
- return QPixmap(data);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qpixmap_x11_p.h b/src/gui/platforms/x11/qpixmap_x11_p.h
deleted file mode 100644
index eb8e5819ad..0000000000
--- a/src/gui/platforms/x11/qpixmap_x11_p.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/****************************************************************************
-**
-** 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 QPIXMAPDATA_X11_P_H
-#define QPIXMAPDATA_X11_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/private/qpixmapdata_p.h>
-#include <QtGui/private/qpixmapdatafactory_p.h>
-
-#include "QtGui/qx11info_x11.h"
-
-QT_BEGIN_NAMESPACE
-
-class QX11PaintEngine;
-
-struct QXImageWrapper;
-
-class Q_GUI_EXPORT QX11PixmapData : public QPixmapData
-{
-public:
- QX11PixmapData(PixelType type);
-// QX11PixmapData(PixelType type, int width, int height);
-// QX11PixmapData(PixelType type, const QImage &image,
-// Qt::ImageConversionFlags flags);
- ~QX11PixmapData();
-
- QPixmapData *createCompatiblePixmapData() const;
-
- void resize(int width, int height);
- void fromImage(const QImage &image, Qt::ImageConversionFlags flags);
- void copy(const QPixmapData *data, const QRect &rect);
- bool scroll(int dx, int dy, const QRect &rect);
-
- void fill(const QColor &color);
- QBitmap mask() const;
- void setMask(const QBitmap &mask);
- bool hasAlphaChannel() const;
- void setAlphaChannel(const QPixmap &alphaChannel);
- QPixmap alphaChannel() const;
- QPixmap transformed(const QTransform &transform,
- Qt::TransformationMode mode) const;
- QImage toImage() const;
- QImage toImage(const QRect &rect) const;
- QPaintEngine* paintEngine() const;
-
- Qt::HANDLE handle() const { return hd; }
- Qt::HANDLE x11ConvertToDefaultDepth();
-
- static Qt::HANDLE createBitmapFromImage(const QImage &image);
-
- void* gl_surface;
-#ifndef QT_NO_XRENDER
- void convertToARGB32(bool preserveContents = true);
-#endif
-
-protected:
- int metric(QPaintDevice::PaintDeviceMetric metric) const;
-
-private:
- friend class QPixmap;
- friend class QBitmap;
- friend class QX11PaintEngine;
- friend class QX11WindowSurface;
- friend class QRasterWindowSurface;
- friend class QGLContextPrivate; // Needs to access xinfo, gl_surface & flags
- friend class QEglContext; // Needs gl_surface
- friend class QGLContext; // Needs gl_surface
- friend class QX11GLPixmapData; // Needs gl_surface
- friend class QMeeGoLivePixmapData; // Needs gl_surface and flags
- friend bool qt_createEGLSurfaceForPixmap(QPixmapData*, bool); // Needs gl_surface
-
- void release();
-
- QImage toImage(const QXImageWrapper &xi, const QRect &rect) const;
-
- QBitmap mask_to_bitmap(int screen) const;
- static Qt::HANDLE bitmap_to_mask(const QBitmap &, int screen);
- void bitmapFromImage(const QImage &image);
-
- bool canTakeQImageFromXImage(const QXImageWrapper &xi) const;
- QImage takeQImageFromXImage(const QXImageWrapper &xi) const;
-
- Qt::HANDLE hd;
-
- enum Flag {
- NoFlags = 0x0,
- Uninitialized = 0x1,
- Readonly = 0x2,
- InvertedWhenBoundToTexture = 0x4,
- GlSurfaceCreatedWithAlpha = 0x8
- };
- uint flags;
-
- QX11Info xinfo;
- Qt::HANDLE x11_mask;
- Qt::HANDLE picture;
- Qt::HANDLE mask_picture;
- Qt::HANDLE hd2; // sorted in the default display depth
- QPixmap::ShareMode share_mode;
-
- QX11PaintEngine *pengine;
-};
-
-QT_END_NAMESPACE
-
-#endif // QPIXMAPDATA_X11_P_H
-
diff --git a/src/gui/platforms/x11/qregion_x11.cpp b/src/gui/platforms/x11/qregion_x11.cpp
deleted file mode 100644
index ef4e844bfa..0000000000
--- a/src/gui/platforms/x11/qregion_x11.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qt_x11_p.h>
-
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-QRegion::QRegionData QRegion::shared_empty = {Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0, 0};
-
-void QRegion::updateX11Region() const
-{
- d->rgn = XCreateRegion();
- if (!d->qt_rgn)
- return;
-
- int n = d->qt_rgn->numRects;
- const QRect *rect = (n == 1 ? &d->qt_rgn->extents : d->qt_rgn->rects.constData());
- while (n--) {
- XRectangle r;
- r.x = qMax(SHRT_MIN, rect->x());
- r.y = qMax(SHRT_MIN, rect->y());
- r.width = qMin((int)USHRT_MAX, rect->width());
- r.height = qMin((int)USHRT_MAX, rect->height());
- XUnionRectWithRegion(&r, d->rgn, d->rgn);
- ++rect;
- }
-}
-
-void *QRegion::clipRectangles(int &num) const
-{
- if (!d->xrectangles && !(d == &shared_empty || d->qt_rgn->numRects == 0)) {
- XRectangle *r = static_cast<XRectangle*>(malloc(d->qt_rgn->numRects * sizeof(XRectangle)));
- d->xrectangles = r;
- int n = d->qt_rgn->numRects;
- const QRect *rect = (n == 1 ? &d->qt_rgn->extents : d->qt_rgn->rects.constData());
- while (n--) {
- r->x = qMax(SHRT_MIN, rect->x());
- r->y = qMax(SHRT_MIN, rect->y());
- r->width = qMin((int)USHRT_MAX, rect->width());
- r->height = qMin((int)USHRT_MAX, rect->height());
- ++r;
- ++rect;
- }
- }
- if (d == &shared_empty || d->qt_rgn->numRects == 0)
- num = 0;
- else
- num = d->qt_rgn->numRects;
- return d->xrectangles;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qsound_x11.cpp b/src/gui/platforms/x11/qsound_x11.cpp
deleted file mode 100644
index 12c06f0aa1..0000000000
--- a/src/gui/platforms/x11/qsound_x11.cpp
+++ /dev/null
@@ -1,296 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsound.h"
-
-#ifndef QT_NO_SOUND
-
-#include "qhash.h"
-#include "qsocketnotifier.h"
-#include "qapplication.h"
-#include "qsound_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_NAS
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <audio/audiolib.h>
-#include <audio/soundlib.h>
-QT_END_INCLUDE_NAMESPACE
-
-static AuServer *nas=0;
-
-static AuBool eventPred(AuServer *, AuEvent *e, AuPointer p)
-{
- if (e && (e->type == AuEventTypeElementNotify)) {
- if (e->auelementnotify.flow == *((AuFlowID *)p))
- return true;
- }
- return false;
-}
-
-class QAuBucketNAS : public QAuBucket {
-public:
- QAuBucketNAS(AuBucketID b, AuFlowID f = 0) : id(b), flow(f), stopped(true), numplaying(0) { }
- ~QAuBucketNAS()
- {
- if (nas) {
- AuSync(nas, false);
- AuDestroyBucket(nas, id, NULL);
-
- AuEvent ev;
- while (AuScanEvents(nas, AuEventsQueuedAfterFlush, true, eventPred, &flow, &ev))
- ;
- }
- }
-
- AuBucketID id;
- AuFlowID flow;
- bool stopped;
- int numplaying;
-};
-
-class QAuServerNAS : public QAuServer {
- Q_OBJECT
-
- QSocketNotifier* sn;
-
-public:
- QAuServerNAS(QObject* parent);
- ~QAuServerNAS();
-
- void init(QSound*);
- void play(const QString& filename);
- void play(QSound*);
- void stop(QSound*);
- bool okay();
- void setDone(QSound*);
-
-public slots:
- void dataReceived();
- void soundDestroyed(QObject *o);
-
-private:
- QAuBucketNAS* bucket(QSound* s)
- {
- return (QAuBucketNAS*)QAuServer::bucket(s);
- }
-};
-
-QAuServerNAS::QAuServerNAS(QObject* parent) :
- QAuServer(parent)
-{
- setObjectName(QLatin1String("Network Audio System"));
- nas = AuOpenServer(NULL, 0, NULL, 0, NULL, NULL);
- if (nas) {
- AuSetCloseDownMode(nas, AuCloseDownDestroy, NULL);
- // Ask Qt for async messages...
- sn=new QSocketNotifier(AuServerConnectionNumber(nas),
- QSocketNotifier::Read);
- QObject::connect(sn, SIGNAL(activated(int)),
- this, SLOT(dataReceived()));
- } else {
- sn = 0;
- }
-}
-
-QAuServerNAS::~QAuServerNAS()
-{
- if (nas)
- AuCloseServer(nas);
- delete sn;
- nas = 0;
-}
-
-typedef QHash<void*,QAuServerNAS*> AuServerHash;
-static AuServerHash *inprogress=0;
-
-void QAuServerNAS::soundDestroyed(QObject *o)
-{
- if (inprogress) {
- QSound *so = static_cast<QSound *>(o);
- while (inprogress->remove(so))
- ; // Loop while remove returns true
- }
-}
-
-void QAuServerNAS::play(const QString& filename)
-{
- if (nas) {
- int iv=100;
- AuFixedPoint volume=AuFixedPointFromFraction(iv,100);
- AuSoundPlayFromFile(nas, filename.toLocal8Bit().constData(), AuNone, volume,
- NULL, NULL, NULL, NULL, NULL, NULL);
- AuFlush(nas);
- dataReceived();
- AuFlush(nas);
- qApp->flush();
- }
-}
-
-static void callback(AuServer*, AuEventHandlerRec*, AuEvent* e, AuPointer p)
-{
- if (inprogress->contains(p) && e) {
- if (e->type==AuEventTypeElementNotify &&
- e->auelementnotify.kind==AuElementNotifyKindState) {
- if (e->auelementnotify.cur_state == AuStateStop) {
- AuServerHash::Iterator it = inprogress->find(p);
- if (it != inprogress->end())
- (*it)->setDone((QSound*)p);
- }
- }
- }
-}
-
-void QAuServerNAS::setDone(QSound* s)
-{
- if (nas) {
- decLoop(s);
- if (s->loopsRemaining() && !bucket(s)->stopped) {
- bucket(s)->stopped = true;
- play(s);
- } else {
- if (--(bucket(s)->numplaying) == 0)
- bucket(s)->stopped = true;
- inprogress->remove(s);
- }
- }
-}
-
-void QAuServerNAS::play(QSound* s)
-{
- if (nas) {
- ++(bucket(s)->numplaying);
- if (!bucket(s)->stopped) {
- stop(s);
- }
-
- bucket(s)->stopped = false;
- if (!inprogress)
- inprogress = new AuServerHash;
- inprogress->insert(s,this);
- int iv=100;
- AuFixedPoint volume=AuFixedPointFromFraction(iv,100);
- QAuBucketNAS *b = bucket(s);
- AuSoundPlayFromBucket(nas, b->id, AuNone, volume,
- callback, s, 0, &b->flow, NULL, NULL, NULL);
- AuFlush(nas);
- dataReceived();
- AuFlush(nas);
- qApp->flush();
- }
-}
-
-void QAuServerNAS::stop(QSound* s)
-{
- if (nas && !bucket(s)->stopped) {
- bucket(s)->stopped = true;
- AuStopFlow(nas, bucket(s)->flow, NULL);
- AuFlush(nas);
- dataReceived();
- AuFlush(nas);
- qApp->flush();
- }
-}
-
-void QAuServerNAS::init(QSound* s)
-{
- connect(s, SIGNAL(destroyed(QObject*)),
- this, SLOT(soundDestroyed(QObject*)));
-
- if (nas) {
- AuBucketID b_id =
- AuSoundCreateBucketFromFile(nas, s->fileName().toLocal8Bit().constData(),
- 0 /*AuAccessAllMasks*/, NULL, NULL);
- setBucket(s, new QAuBucketNAS(b_id));
- }
-}
-
-bool QAuServerNAS::okay()
-{
- return !!nas;
-}
-
-void QAuServerNAS::dataReceived()
-{
- AuHandleEvents(nas);
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qsound_x11.moc"
-QT_END_INCLUDE_NAMESPACE
-
-#endif
-
-
-class QAuServerNull : public QAuServer
-{
-public:
- QAuServerNull(QObject* parent);
-
- void play(const QString&) { }
- void play(QSound*s) { while(decLoop(s) > 0) /* nothing */ ; }
- void stop(QSound*) { }
- bool okay() { return false; }
-};
-
-QAuServerNull::QAuServerNull(QObject* parent)
- : QAuServer(parent)
-{
-}
-
-
-QAuServer* qt_new_audio_server()
-{
-#ifndef QT_NO_NAS
- QAuServer* s = new QAuServerNAS(qApp);
- if (s->okay())
- return s;
- else
- delete s;
-#endif
- return new QAuServerNull(qApp);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SOUND
diff --git a/src/gui/platforms/x11/qt_x11_p.h b/src/gui/platforms/x11/qt_x11_p.h
deleted file mode 100644
index 69079cfaad..0000000000
--- a/src/gui/platforms/x11/qt_x11_p.h
+++ /dev/null
@@ -1,757 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_X11_P_H
-#define QT_X11_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qwindowdefs.h"
-#include "QtCore/qlist.h"
-#include "QtCore/qvariant.h"
-
-// the following is necessary to work around breakage in many versions
-// of XFree86's Xlib.h still in use
-// ### which versions?
-#if defined(_XLIB_H_) // crude hack, but...
-#error "cannot include <X11/Xlib.h> before this file"
-#endif
-#define XRegisterIMInstantiateCallback qt_XRegisterIMInstantiateCallback
-#define XUnregisterIMInstantiateCallback qt_XUnregisterIMInstantiateCallback
-#define XSetIMValues qt_XSetIMValues
-#include <X11/Xlib.h>
-#undef XRegisterIMInstantiateCallback
-#undef XUnregisterIMInstantiateCallback
-#undef XSetIMValues
-
-#include <X11/Xutil.h>
-#include <X11/Xos.h>
-#ifdef index
-# undef index
-#endif
-#ifdef rindex
-# undef rindex
-#endif
-#ifdef Q_OS_VXWORS
-# ifdef open
-# undef open
-# endif
-# ifdef getpid
-# undef getpid
-# endif
-#endif // Q_OS_VXWORKS
-#include <X11/Xatom.h>
-
-//#define QT_NO_SHAPE
-#ifdef QT_NO_SHAPE
-# define XShapeCombineRegion(a,b,c,d,e,f,g)
-# define XShapeCombineMask(a,b,c,d,e,f,g)
-#else
-# include <X11/extensions/shape.h>
-#endif // QT_NO_SHAPE
-
-
-#if !defined (QT_NO_TABLET)
-# include <X11/extensions/XInput.h>
-#if defined (Q_OS_IRIX)
-# include <X11/extensions/SGIMisc.h>
-# include <wacom.h>
-#endif
-#endif // QT_NO_TABLET
-
-
-// #define QT_NO_XINERAMA
-#ifndef QT_NO_XINERAMA
-# if 0 // ### Xsun, but how to detect it?
-// Xinerama is only supported in Solaris 7 with patches 107648/108376 and
-// Solaris 8 or above which introduce the X11R6.4 Xserver.
-// To switch the Xinerama functionality on, you need to add the "+xinerama"
-// argument to the Xsun start line.
-// At least Solaris 7 and 8 are missing Xinerama system headers and function
-// declarations (bug 4284701).
-// The Xinerama API is not documented. In theory it could change but it
-// probably won't because Sun are using it in at least dtlogin (bug 4221829).
-extern "C" Bool XPanoramiXQueryExtension(
- Display*,
- int*,
- int*
-);
-extern "C" Status XPanoramiXQueryVersion(
- Display*,
- int*,
- int*
-);
-extern "C" Status XPanoramiXGetState(
- Display*,
- Drawable,
- XPanoramiXInfo*
-);
-extern "C" Status XPanoramiXGetScreenCount(
- Display *,
- Drawable,
- XPanoramiXInfo*
-);
-extern "C" Status XPanoramiXGetScreenSize(
- Display*,
- Drawable,
- int,
- XPanoramiXInfo*
-);
-# else // XFree86
-// XFree86 does not C++ify Xinerama (at least up to XFree86 4.0.3).
-extern "C" {
-# include <X11/extensions/Xinerama.h>
-}
-# endif
-#endif // QT_NO_XINERAMA
-
-// #define QT_NO_XRANDR
-#ifndef QT_NO_XRANDR
-# include <X11/extensions/Xrandr.h>
-#endif // QT_NO_XRANDR
-
-// #define QT_NO_XRENDER
-#ifndef QT_NO_XRENDER
-# include <X11/extensions/Xrender.h>
-#endif // QT_NO_XRENDER
-
-#ifndef QT_NO_XSYNC
-extern "C" {
-# include "X11/extensions/sync.h"
-}
-#endif
-
-// #define QT_NO_XKB
-#ifndef QT_NO_XKB
-# include <X11/XKBlib.h>
-#endif // QT_NO_XKB
-
-
-#if !defined(XlibSpecificationRelease)
-# define X11R4
-typedef char *XPointer;
-#else
-# undef X11R4
-#endif
-
-// #define QT_NO_XIM
-#if defined(X11R4)
-// X11R4 does not have XIM
-#define QT_NO_XIM
-#elif defined(Q_OS_OSF) && (XlibSpecificationRelease < 6)
-// broken in Xlib up to OSF/1 3.2
-#define QT_NO_XIM
-#elif defined(Q_OS_AIX)
-// broken in Xlib up to what version of AIX?
-#define QT_NO_XIM
-#elif defined(QT_NO_DEBUG) && defined(Q_OS_IRIX)
-// XmbLookupString broken on IRIX
-// XCreateIC broken when compiling -64 on IRIX 6.5.2
-#define QT_NO_XIM
-#elif defined(Q_OS_HPUX) && defined(__LP64__)
-// XCreateIC broken when compiling 64-bit ELF on HP-UX 11.0
-#define QT_NO_XIM
-#elif defined(Q_OS_SCO)
-// ### suggested by user...
-// ### #define QT_NO_XIM
-#endif // QT_NO_XIM
-
-#ifndef QT_NO_XFIXES
-typedef Bool (*PtrXFixesQueryExtension)(Display *, int *, int *);
-typedef Status (*PtrXFixesQueryVersion)(Display *, int *, int *);
-typedef void (*PtrXFixesSetCursorName)(Display *dpy, Cursor cursor, const char *name);
-typedef void (*PtrXFixesSelectSelectionInput)(Display *dpy, Window win, Atom selection, unsigned long eventMask);
-#endif // QT_NO_XFIXES
-
-#ifndef QT_NO_XCURSOR
-#include <X11/Xcursor/Xcursor.h>
-typedef Cursor (*PtrXcursorLibraryLoadCursor)(Display *, const char *);
-#endif // QT_NO_XCURSOR
-
-#ifndef QT_NO_XINERAMA
-typedef Bool (*PtrXineramaQueryExtension)(Display *dpy, int *event_base, int *error_base);
-typedef Bool (*PtrXineramaIsActive)(Display *dpy);
-typedef XineramaScreenInfo *(*PtrXineramaQueryScreens)(Display *dpy, int *number);
-#endif // QT_NO_XINERAMA
-
-#ifndef QT_NO_XRANDR
-typedef void (*PtrXRRSelectInput)(Display *, Window, int);
-typedef int (*PtrXRRUpdateConfiguration)(XEvent *);
-typedef int (*PtrXRRRootToScreen)(Display *, Window);
-typedef Bool (*PtrXRRQueryExtension)(Display *, int *, int *);
-typedef XRRScreenSize *(*PtrXRRSizes)(Display *, int, int *);
-#endif // QT_NO_XRANDR
-
-#ifndef QT_NO_XINPUT
-typedef int (*PtrXCloseDevice)(Display *, XDevice *);
-typedef XDeviceInfo* (*PtrXListInputDevices)(Display *, int *);
-typedef XDevice* (*PtrXOpenDevice)(Display *, XID);
-typedef void (*PtrXFreeDeviceList)(XDeviceInfo *);
-typedef int (*PtrXSelectExtensionEvent)(Display *, Window, XEventClass *, int);
-#endif // QT_NO_XINPUT
-
-/*
- * Solaris patch 108652-47 and higher fixes crases in
- * XRegisterIMInstantiateCallback, but the function doesn't seem to
- * work.
- *
- * Instead, we disabled R6 input, and open the input method
- * immediately at application start.
- */
-#if !defined(QT_NO_XIM) && (XlibSpecificationRelease >= 6) && \
- !defined(Q_OS_SOLARIS)
-#define USE_X11R6_XIM
-
-//######### XFree86 has wrong declarations for XRegisterIMInstantiateCallback
-//######### and XUnregisterIMInstantiateCallback in at least version 3.3.2.
-//######### Many old X11R6 header files lack XSetIMValues.
-//######### Therefore, we have to declare these functions ourselves.
-
-extern "C" Bool XRegisterIMInstantiateCallback(
- Display*,
- struct _XrmHashBucketRec*,
- char*,
- char*,
- XIMProc, //XFree86 has XIDProc, which has to be wrong
- XPointer
-);
-
-extern "C" Bool XUnregisterIMInstantiateCallback(
- Display*,
- struct _XrmHashBucketRec*,
- char*,
- char*,
- XIMProc, //XFree86 has XIDProc, which has to be wrong
- XPointer
-);
-
-extern "C" char *XSetIMValues(XIM /* im */, ...);
-
-#endif
-
-#ifndef QT_NO_FONTCONFIG
-#include <fontconfig/fontconfig.h>
-#endif
-
-#ifndef QT_NO_XIM
-// some platforms (eg. Solaris 2.51) don't have these defines in Xlib.h
-#ifndef XNResetState
-#define XNResetState "resetState"
-#endif
-#ifndef XIMPreserveState
-#define XIMPreserveState (1L<<1)
-#endif
-#endif
-
-
-#ifndef X11R4
-# include <X11/Xlocale.h>
-#endif // X11R4
-
-
-#ifndef QT_NO_MITSHM
-# include <X11/extensions/XShm.h>
-#endif // QT_NO_MITSHM
-
-QT_BEGIN_NAMESPACE
-
-class QWidget;
-
-struct QX11InfoData {
- uint ref;
- int screen;
- int dpiX;
- int dpiY;
- int depth;
- int cells;
- Colormap colormap;
- Visual *visual;
- bool defaultColormap;
- bool defaultVisual;
- int subpixel;
-};
-
-class QDrag;
-struct QXdndDropTransaction
-{
- Time timestamp;
- Window target;
- Window proxy_target;
- QWidget *targetWidget;
- QWidget *embedding_widget;
- QDrag *object;
-};
-
-class QMimeData;
-
-struct QX11Data;
-extern Q_GUI_EXPORT QX11Data *qt_x11Data;
-
-enum DesktopEnvironment {
- DE_UNKNOWN,
- DE_KDE,
- DE_GNOME,
- DE_CDE,
- DE_MEEGO_COMPOSITOR,
- DE_4DWM
-};
-
-struct QX11Data
-{
- static Qt::KeyboardModifiers translateModifiers(int s);
-
- Window findClientWindow(Window, Atom, bool);
-
- // from qclipboard_x11.cpp
- bool clipboardWaitForEvent(Window win, int type, XEvent *event, int timeout);
- bool clipboardReadProperty(Window win, Atom property, bool deleteProperty,
- QByteArray *buffer, int *size, Atom *type, int *format);
- QByteArray clipboardReadIncrementalProperty(Window win, Atom property, int nbytes, bool nullterm);
-
- // from qdnd_x11.cpp
- bool dndEnable(QWidget* w, bool on);
- static void xdndSetup();
- void xdndHandleEnter(QWidget *, const XEvent *, bool);
- void xdndHandlePosition(QWidget *, const XEvent *, bool);
- void xdndHandleStatus(QWidget *, const XEvent *, bool);
- void xdndHandleLeave(QWidget *, const XEvent *, bool);
- void xdndHandleDrop(QWidget *, const XEvent *, bool);
- void xdndHandleFinished(QWidget *, const XEvent *, bool);
- void xdndHandleSelectionRequest(const XSelectionRequestEvent *);
- static bool xdndHandleBadwindow();
- QByteArray xdndAtomToString(Atom a);
- Atom xdndStringToAtom(const char *);
-
- QString xdndMimeAtomToString(Atom a);
- Atom xdndMimeStringToAtom(const QString &mimeType);
- QStringList xdndMimeFormatsForAtom(Atom a);
- bool xdndMimeDataForAtom(Atom a, QMimeData *mimeData, QByteArray *data, Atom *atomFormat, int *dataFormat);
- QList<Atom> xdndMimeAtomsForFormat(const QString &format);
- QVariant xdndMimeConvertToFormat(Atom a, const QByteArray &data, const QString &format, QVariant::Type requestedType, const QByteArray &encoding);
- Atom xdndMimeAtomForFormat(const QString &format, QVariant::Type requestedType, const QList<Atom> &atoms, QByteArray *requestedEncoding);
-
- QList<QXdndDropTransaction> dndDropTransactions;
-
- // from qmotifdnd_x11.cpp
- void motifdndHandle(QWidget *, const XEvent *, bool);
- void motifdndEnable(QWidget *, bool);
- QVariant motifdndObtainData(const char *format);
- QByteArray motifdndFormat(int n);
- bool motifdnd_active;
-
- Display *display;
- char *displayName;
- bool foreignDisplay;
- // current focus model
- enum {
- FM_Unknown = -1,
- FM_Other = 0,
- FM_PointerRoot = 1
- };
- int focus_model;
-
- // true if Qt is compiled w/ RANDR support and RANDR is supported on the connected Display
- bool use_xrandr;
- int xrandr_major;
- int xrandr_eventbase;
- int xrandr_errorbase;
-
- // true if Qt is compiled w/ RENDER support and RENDER is supported on the connected Display
- bool use_xrender;
- int xrender_major;
- int xrender_version;
-
- // true if Qt is compiled w/ XFIXES support and XFIXES is supported on the connected Display
- bool use_xfixes;
- int xfixes_major;
- int xfixes_eventbase;
- int xfixes_errorbase;
-
-#ifndef QT_NO_XFIXES
- PtrXFixesQueryExtension ptrXFixesQueryExtension;
- PtrXFixesQueryVersion ptrXFixesQueryVersion;
- PtrXFixesSetCursorName ptrXFixesSetCursorName;
- PtrXFixesSelectSelectionInput ptrXFixesSelectSelectionInput;
-#endif
-
-#ifndef QT_NO_XINPUT
- PtrXCloseDevice ptrXCloseDevice;
- PtrXListInputDevices ptrXListInputDevices;
- PtrXOpenDevice ptrXOpenDevice;
- PtrXFreeDeviceList ptrXFreeDeviceList;
- PtrXSelectExtensionEvent ptrXSelectExtensionEvent;
-#endif // QT_NO_XINPUT
-
-
- // true if Qt is compiled w/ MIT-SHM support and MIT-SHM is supported on the connected Display
- bool use_mitshm;
- bool use_mitshm_pixmaps;
- int mitshm_major;
-
- // true if Qt is compiled w/ Tablet support and we have a tablet.
- bool use_xinput;
- int xinput_major;
- int xinput_eventbase;
- int xinput_errorbase;
-
- // for XKEYBOARD support
- bool use_xkb;
- int xkb_major;
- int xkb_eventbase;
- int xkb_errorbase;
-
- QList<QWidget *> deferred_map;
- struct ScrollInProgress {
- long id;
- QWidget* scrolled_widget;
- int dx, dy;
- };
- long sip_serial;
- QList<ScrollInProgress> sip_list;
-
- // window managers list of supported "stuff"
- Atom *net_supported_list;
- // list of virtual root windows
- Window *net_virtual_root_list;
- // client leader window
- Window wm_client_leader;
-
- QX11InfoData *screens;
- Visual **argbVisuals;
- Colormap *argbColormaps;
- int screenCount;
- int defaultScreen;
-
- Time time;
- Time userTime;
-
- QString default_im;
-
- // starts to ignore bad window errors from X
- static inline void ignoreBadwindow() {
- qt_x11Data->ignore_badwindow = true;
- qt_x11Data->seen_badwindow = false;
- }
-
- // ends ignoring bad window errors and returns whether an error had happened.
- static inline bool badwindow() {
- qt_x11Data->ignore_badwindow = false;
- return qt_x11Data->seen_badwindow;
- }
-
- bool ignore_badwindow;
- bool seen_badwindow;
-
- // options
- int visual_class;
- int visual_id;
- int color_count;
- bool custom_cmap;
-
- // outside visual/colormap
- Visual *visual;
- Colormap colormap;
-
-#ifndef QT_NO_XRENDER
- enum { solid_fill_count = 16 };
- struct SolidFills {
- XRenderColor color;
- int screen;
- Picture picture;
- } solid_fills[solid_fill_count];
- enum { pattern_fill_count = 16 };
- struct PatternFills {
- XRenderColor color;
- XRenderColor bg_color;
- int screen;
- int style;
- bool opaque;
- Picture picture;
- } pattern_fills[pattern_fill_count];
- Picture getSolidFill(int screen, const QColor &c);
- XRenderColor preMultiply(const QColor &c);
-#endif
-
- bool has_fontconfig;
- qreal fc_scale;
- bool fc_antialias;
- int fc_hint_style;
-
- char *startupId;
-
- DesktopEnvironment desktopEnvironment : 8;
- uint desktopVersion : 8; /* Used only for KDE */
-
- /* Warning: if you modify this list, modify the names of atoms in qapplication_x11.cpp as well! */
- enum X11Atom {
- // window-manager <-> client protocols
- WM_PROTOCOLS,
- WM_DELETE_WINDOW,
- WM_TAKE_FOCUS,
- _NET_WM_PING,
- _NET_WM_CONTEXT_HELP,
- _NET_WM_SYNC_REQUEST,
- _NET_WM_SYNC_REQUEST_COUNTER,
-
- // ICCCM window state
- WM_STATE,
- WM_CHANGE_STATE,
-
- // Session management
- WM_CLIENT_LEADER,
- WM_WINDOW_ROLE,
- SM_CLIENT_ID,
-
- // Clipboard
- CLIPBOARD,
- INCR,
- TARGETS,
- MULTIPLE,
- TIMESTAMP,
- SAVE_TARGETS,
- CLIP_TEMPORARY,
- _QT_SELECTION,
- _QT_CLIPBOARD_SENTINEL,
- _QT_SELECTION_SENTINEL,
- CLIPBOARD_MANAGER,
-
- RESOURCE_MANAGER,
-
- _XSETROOT_ID,
-
- _QT_SCROLL_DONE,
- _QT_INPUT_ENCODING,
-
- _MOTIF_WM_HINTS,
-
- DTWM_IS_RUNNING,
- ENLIGHTENMENT_DESKTOP,
- _DT_SAVE_MODE,
- _SGI_DESKS_MANAGER,
-
- // EWMH (aka NETWM)
- _NET_SUPPORTED,
- _NET_VIRTUAL_ROOTS,
- _NET_WORKAREA,
-
- _NET_MOVERESIZE_WINDOW,
- _NET_WM_MOVERESIZE,
-
- _NET_WM_NAME,
- _NET_WM_ICON_NAME,
- _NET_WM_ICON,
-
- _NET_WM_PID,
-
- _NET_WM_WINDOW_OPACITY,
-
- _NET_WM_STATE,
- _NET_WM_STATE_ABOVE,
- _NET_WM_STATE_BELOW,
- _NET_WM_STATE_FULLSCREEN,
- _NET_WM_STATE_MAXIMIZED_HORZ,
- _NET_WM_STATE_MAXIMIZED_VERT,
- _NET_WM_STATE_MODAL,
- _NET_WM_STATE_STAYS_ON_TOP,
- _NET_WM_STATE_DEMANDS_ATTENTION,
-
- _NET_WM_USER_TIME,
- _NET_WM_USER_TIME_WINDOW,
- _NET_WM_FULL_PLACEMENT,
-
- _NET_WM_WINDOW_TYPE,
- _NET_WM_WINDOW_TYPE_DESKTOP,
- _NET_WM_WINDOW_TYPE_DOCK,
- _NET_WM_WINDOW_TYPE_TOOLBAR,
- _NET_WM_WINDOW_TYPE_MENU,
- _NET_WM_WINDOW_TYPE_UTILITY,
- _NET_WM_WINDOW_TYPE_SPLASH,
- _NET_WM_WINDOW_TYPE_DIALOG,
- _NET_WM_WINDOW_TYPE_DROPDOWN_MENU,
- _NET_WM_WINDOW_TYPE_POPUP_MENU,
- _NET_WM_WINDOW_TYPE_TOOLTIP,
- _NET_WM_WINDOW_TYPE_NOTIFICATION,
- _NET_WM_WINDOW_TYPE_COMBO,
- _NET_WM_WINDOW_TYPE_DND,
- _NET_WM_WINDOW_TYPE_NORMAL,
- _KDE_NET_WM_WINDOW_TYPE_OVERRIDE,
-
- _KDE_NET_WM_FRAME_STRUT,
-
- _NET_STARTUP_INFO,
- _NET_STARTUP_INFO_BEGIN,
-
- _NET_SUPPORTING_WM_CHECK,
-
- _NET_WM_CM_S0,
-
- _NET_SYSTEM_TRAY_VISUAL,
-
- _NET_ACTIVE_WINDOW,
-
- // Property formats
- COMPOUND_TEXT,
- TEXT,
- UTF8_STRING,
-
- // Xdnd
- XdndEnter,
- XdndPosition,
- XdndStatus,
- XdndLeave,
- XdndDrop,
- XdndFinished,
- XdndTypelist,
- XdndActionList,
-
- XdndSelection,
-
- XdndAware,
- XdndProxy,
-
- XdndActionCopy,
- XdndActionLink,
- XdndActionMove,
- XdndActionPrivate,
-
- // Motif DND
- _MOTIF_DRAG_AND_DROP_MESSAGE,
- _MOTIF_DRAG_INITIATOR_INFO,
- _MOTIF_DRAG_RECEIVER_INFO,
- _MOTIF_DRAG_WINDOW,
- _MOTIF_DRAG_TARGETS,
-
- XmTRANSFER_SUCCESS,
- XmTRANSFER_FAILURE,
-
- // Xkb
- _XKB_RULES_NAMES,
-
- // XEMBED
- _XEMBED,
- _XEMBED_INFO,
-
- XWacomStylus,
- XWacomCursor,
- XWacomEraser,
-
- XTabletStylus,
- XTabletEraser,
-
- NPredefinedAtoms,
-
- _QT_SETTINGS_TIMESTAMP = NPredefinedAtoms,
- NAtoms
- };
- Atom atoms[NAtoms];
-
- bool isSupportedByWM(Atom atom);
-
- bool compositingManagerRunning;
-
-#ifndef QT_NO_XCURSOR
- PtrXcursorLibraryLoadCursor ptrXcursorLibraryLoadCursor;
-#endif // QT_NO_XCURSOR
-
-#ifndef QT_NO_XINERAMA
- PtrXineramaQueryExtension ptrXineramaQueryExtension;
- PtrXineramaIsActive ptrXineramaIsActive;
- PtrXineramaQueryScreens ptrXineramaQueryScreens;
-#endif // QT_NO_XINERAMA
-
-#ifndef QT_NO_XRANDR
- PtrXRRSelectInput ptrXRRSelectInput;
- PtrXRRUpdateConfiguration ptrXRRUpdateConfiguration;
- PtrXRRRootToScreen ptrXRRRootToScreen;
- PtrXRRQueryExtension ptrXRRQueryExtension;
- PtrXRRSizes ptrXRRSizes;
-#endif // QT_NO_XRANDR
-};
-
-extern QX11Data *qt_x11Data;
-#define ATOM(x) qt_x11Data->atoms[QX11Data::x]
-#define X11 qt_x11Data
-
-// rename a couple of X defines to get rid of name clashes
-// resolve the conflict between X11's FocusIn and QEvent::FocusIn
-enum {
- XFocusOut = FocusOut,
- XFocusIn = FocusIn,
- XKeyPress = KeyPress,
- XKeyRelease = KeyRelease,
- XNone = None,
- XRevertToParent = RevertToParent,
- XGrayScale = GrayScale,
- XCursorShape = CursorShape
-};
-#undef FocusOut
-#undef FocusIn
-#undef KeyPress
-#undef KeyRelease
-#undef None
-#undef RevertToParent
-#undef GrayScale
-#undef CursorShape
-
-#ifdef FontChange
-#undef FontChange
-#endif
-
-Q_DECLARE_TYPEINFO(XPoint, Q_PRIMITIVE_TYPE);
-Q_DECLARE_TYPEINFO(XRectangle, Q_PRIMITIVE_TYPE);
-Q_DECLARE_TYPEINFO(XChar2b, Q_PRIMITIVE_TYPE);
-#ifndef QT_NO_XRENDER
-Q_DECLARE_TYPEINFO(XGlyphElt32, Q_PRIMITIVE_TYPE);
-#endif
-
-
-QT_END_NAMESPACE
-
-#endif // QT_X11_P_H
diff --git a/src/gui/platforms/x11/qwidget_x11.cpp b/src/gui/platforms/x11/qwidget_x11.cpp
deleted file mode 100644
index 5ece7d65c6..0000000000
--- a/src/gui/platforms/x11/qwidget_x11.cpp
+++ /dev/null
@@ -1,3146 +0,0 @@
-/****************************************************************************
-**
-** 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 "qevent.h"
-#include "qwidget.h"
-#include "qdesktopwidget.h"
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qnamespace.h"
-#include "qpainter.h"
-#include "qbitmap.h"
-#include "qlayout.h"
-#include "qtextcodec.h"
-#include "qelapsedtimer.h"
-#include "qcursor.h"
-#include "qstack.h"
-#include "qcolormap.h"
-#include "qdebug.h"
-#include "qmenu.h"
-#include "private/qmenu_p.h"
-#include "private/qbackingstore_p.h"
-#include "private/qwindowsurface_x11_p.h"
-
-//extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); //qapplication_x11.cpp
-
-#include <private/qpixmap_x11_p.h>
-#include <private/qpaintengine_x11_p.h>
-#include "qt_x11_p.h"
-#include "qx11info_x11.h"
-
-#include <stdlib.h>
-
-//#define ALIEN_DEBUG
-
-// defined in qapplication_x11.cpp
-//bool qt_wstate_iconified(WId);
-//void qt_updated_rootinfo();
-
-
-#if !defined(QT_NO_IM)
-#include "qinputcontext.h"
-#include "qinputcontextfactory.h"
-#endif
-
-#include "qwidget_p.h"
-
-#define XCOORD_MAX 16383
-#define WRECT_MAX 8191
-
-QT_BEGIN_NAMESPACE
-
-extern bool qt_nograb();
-
-QWidget *QWidgetPrivate::mouseGrabber = 0;
-QWidget *QWidgetPrivate::keyboardGrabber = 0;
-
-void qt_net_remove_user_time(QWidget *tlw);
-void qt_net_update_user_time(QWidget *tlw, unsigned long timestamp);
-
-int qt_x11_create_desktop_on_screen = -1;
-
-extern void qt_net_update_user_time(QWidget *tlw, unsigned long timestamp);
-
-// MWM support
-struct QtMWMHints {
- ulong flags, functions, decorations;
- long input_mode;
- ulong status;
-};
-
-enum {
- MWM_HINTS_FUNCTIONS = (1L << 0),
-
- MWM_FUNC_ALL = (1L << 0),
- MWM_FUNC_RESIZE = (1L << 1),
- MWM_FUNC_MOVE = (1L << 2),
- MWM_FUNC_MINIMIZE = (1L << 3),
- MWM_FUNC_MAXIMIZE = (1L << 4),
- MWM_FUNC_CLOSE = (1L << 5),
-
- MWM_HINTS_DECORATIONS = (1L << 1),
-
- MWM_DECOR_ALL = (1L << 0),
- MWM_DECOR_BORDER = (1L << 1),
- MWM_DECOR_RESIZEH = (1L << 2),
- MWM_DECOR_TITLE = (1L << 3),
- MWM_DECOR_MENU = (1L << 4),
- MWM_DECOR_MINIMIZE = (1L << 5),
- MWM_DECOR_MAXIMIZE = (1L << 6),
-
- MWM_HINTS_INPUT_MODE = (1L << 2),
-
- MWM_INPUT_MODELESS = 0L,
- MWM_INPUT_PRIMARY_APPLICATION_MODAL = 1L,
- MWM_INPUT_FULL_APPLICATION_MODAL = 3L
-};
-
-
-static QtMWMHints GetMWMHints(Display *display, Window window)
-{
- QtMWMHints mwmhints;
-
- Atom type;
- int format;
- ulong nitems, bytesLeft;
- uchar *data = 0;
- if ((XGetWindowProperty(display, window, ATOM(_MOTIF_WM_HINTS), 0, 5, false,
- ATOM(_MOTIF_WM_HINTS), &type, &format, &nitems, &bytesLeft,
- &data) == Success)
- && (type == ATOM(_MOTIF_WM_HINTS)
- && format == 32
- && nitems >= 5)) {
- mwmhints = *(reinterpret_cast<QtMWMHints *>(data));
- } else {
- mwmhints.flags = 0L;
- mwmhints.functions = MWM_FUNC_ALL;
- mwmhints.decorations = MWM_DECOR_ALL;
- mwmhints.input_mode = 0L;
- mwmhints.status = 0L;
- }
-
- if (data)
- XFree(data);
-
- return mwmhints;
-}
-
-static void SetMWMHints(Display *display, Window window, const QtMWMHints &mwmhints)
-{
- if (mwmhints.flags != 0l) {
- XChangeProperty(display, window, ATOM(_MOTIF_WM_HINTS), ATOM(_MOTIF_WM_HINTS), 32,
- PropModeReplace, (unsigned char *) &mwmhints, 5);
- } else {
- XDeleteProperty(display, window, ATOM(_MOTIF_WM_HINTS));
- }
-}
-
-// Returns true if we should set WM_TRANSIENT_FOR on \a w
-static inline bool isTransient(const QWidget *w)
-{
- return ((w->windowType() == Qt::Dialog
- || w->windowType() == Qt::Sheet
- || w->windowType() == Qt::Tool
- || w->windowType() == Qt::SplashScreen
- || w->windowType() == Qt::ToolTip
- || w->windowType() == Qt::Drawer
- || w->windowType() == Qt::Popup)
- && !w->testAttribute(Qt::WA_X11BypassTransientForHint));
-}
-
-static void do_size_hints(QWidget* widget, QWExtra *x);
-
-/*****************************************************************************
- QWidget member functions
- *****************************************************************************/
-
-const uint stdWidgetEventMask = // X event mask
- (uint)(
- KeyPressMask | KeyReleaseMask |
- ButtonPressMask | ButtonReleaseMask |
- KeymapStateMask |
- ButtonMotionMask | PointerMotionMask |
- EnterWindowMask | LeaveWindowMask |
- FocusChangeMask |
- ExposureMask |
- PropertyChangeMask |
- StructureNotifyMask
- );
-
-const uint stdDesktopEventMask = // X event mask
- (uint)(
- KeymapStateMask |
- EnterWindowMask | LeaveWindowMask |
- PropertyChangeMask
- );
-
-
-/*
- The qt_ functions below are implemented in qwidgetcreate_x11.cpp.
-*/
-
-Window qt_XCreateWindow(const QWidget *creator,
- Display *display, Window parent,
- int x, int y, uint w, uint h,
- int borderwidth, int depth,
- uint windowclass, Visual *visual,
- ulong valuemask, XSetWindowAttributes *attributes);
-Window qt_XCreateSimpleWindow(const QWidget *creator,
- Display *display, Window parent,
- int x, int y, uint w, uint h, int borderwidth,
- ulong border, ulong background);
-void qt_XDestroyWindow(const QWidget *destroyer,
- Display *display, Window window);
-
-
-static void qt_insert_sip(QWidget* scrolled_widget, int dx, int dy)
-{
- if (!scrolled_widget->isWindow() && !scrolled_widget->internalWinId())
- return;
- QX11Data::ScrollInProgress sip = { X11->sip_serial++, scrolled_widget, dx, dy };
- X11->sip_list.append(sip);
-
- XClientMessageEvent client_message;
- client_message.type = ClientMessage;
- client_message.window = scrolled_widget->internalWinId();
- client_message.format = 32;
- client_message.message_type = ATOM(_QT_SCROLL_DONE);
- client_message.data.l[0] = sip.id;
-
- XSendEvent(X11->display, scrolled_widget->internalWinId(), False, NoEventMask,
- (XEvent*)&client_message);
-}
-
-static int qt_sip_count(QWidget* scrolled_widget)
-{
- int sips=0;
-
- for (int i = 0; i < X11->sip_list.size(); ++i) {
- const QX11Data::ScrollInProgress &sip = X11->sip_list.at(i);
- if (sip.scrolled_widget == scrolled_widget)
- sips++;
- }
-
- return sips;
-}
-
-static void create_wm_client_leader()
-{
- if (X11->wm_client_leader) return;
-
- X11->wm_client_leader =
- XCreateSimpleWindow(X11->display,
- QX11Info::appRootWindow(),
- 0, 0, 1, 1, 0, 0, 0);
-
- // set client leader property to itself
- XChangeProperty(X11->display,
- X11->wm_client_leader, ATOM(WM_CLIENT_LEADER),
- XA_WINDOW, 32, PropModeReplace,
- (unsigned char *)&X11->wm_client_leader, 1);
-
-#ifndef QT_NO_SESSIONMANAGER
- // If we are session managed, inform the window manager about it
- QByteArray session = qApp->sessionId().toLatin1();
- if (!session.isEmpty()) {
- XChangeProperty(X11->display,
- X11->wm_client_leader, ATOM(SM_CLIENT_ID),
- XA_STRING, 8, PropModeReplace,
- (unsigned char *)session.data(), session.size());
- }
-#endif
-}
-
-/*!
- \internal
- Update the X11 cursor of the widget w.
- \a force is true if this function is called from dispatchEnterLeave, it means that the
- mouse is actually directly under this widget.
- */
-void qt_x11_enforce_cursor(QWidget * w, bool force)
-{
- if (!w->testAttribute(Qt::WA_WState_Created))
- return;
-
- static QPointer<QWidget> lastUnderMouse = 0;
- if (force) {
- lastUnderMouse = w;
- } else if (lastUnderMouse && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
- w = lastUnderMouse;
- } else if (!w->internalWinId()) {
- return; //the mouse is not under this widget, and it's not native, so don't change it
- }
-
- while (!w->internalWinId() && w->parentWidget() && !w->isWindow() && !w->testAttribute(Qt::WA_SetCursor))
- w = w->parentWidget();
-
- QWidget *nativeParent = w;
- if (!w->internalWinId())
- nativeParent = w->nativeParentWidget();
- // This does the same as effectiveWinId(), but since it is possible
- // to not have a native parent widget due to a special hack in
- // qwidget for reparenting widgets to a different X11 screen,
- // added additional check to make sure native parent widget exists.
- if (!nativeParent || !nativeParent->internalWinId())
- return;
- WId winid = nativeParent->internalWinId();
-
- if (w->isWindow() || w->testAttribute(Qt::WA_SetCursor)) {
-#ifndef QT_NO_CURSOR
- QCursor *oc = QApplication::overrideCursor();
- if (oc) {
- XDefineCursor(X11->display, winid, oc->handle());
- } else if (w->isEnabled()) {
- XDefineCursor(X11->display, winid, w->cursor().handle());
- } else {
- // enforce the windows behavior of clearing the cursor on
- // disabled widgets
- XDefineCursor(X11->display, winid, XNone);
- }
-#endif
- } else {
- XDefineCursor(X11->display, winid, XNone);
- }
-}
-
-Q_GUI_EXPORT void qt_x11_enforce_cursor(QWidget * w)
-{
- qt_x11_enforce_cursor(w, false);
-}
-
-void qt_x11_wait_for_window_manager(QWidget *w, bool sendPostedEvents)
-{
- if (!w || (!w->isWindow() && !w->internalWinId()))
- return;
- QApplication::flush();
- XEvent ev;
- QElapsedTimer t;
- t.start();
- static const int maximumWaitTime = 2000;
- if (!w->testAttribute(Qt::WA_WState_Created))
- return;
-
- WId winid = w->internalWinId();
-
- // first deliver events that are already in the local queue
- if (sendPostedEvents)
- QApplication::sendPostedEvents();
-
- // the normal sequence is:
- // ... ConfigureNotify ... ReparentNotify ... MapNotify ... Expose
- // with X11BypassWindowManagerHint:
- // ConfigureNotify ... MapNotify ... Expose
-
- enum State {
- Initial, Mapped
- } state = Initial;
-
- do {
- if (XEventsQueued(X11->display, QueuedAlready)) {
- XNextEvent(X11->display, &ev);
- qApp->x11ProcessEvent(&ev);
-
- switch (state) {
- case Initial:
- if (ev.type == MapNotify && ev.xany.window == winid)
- state = Mapped;
- break;
- case Mapped:
- if (ev.type == Expose && ev.xany.window == winid)
- return;
- break;
- }
- } else {
- if (!XEventsQueued(X11->display, QueuedAfterFlush))
- qApp->syncX(); // non-busy wait
- }
- if (t.elapsed() > maximumWaitTime)
- return;
- } while(1);
-}
-
-Q_GUI_EXPORT void qt_x11_wait_for_window_manager(QWidget *w)
-{
- qt_x11_wait_for_window_manager(w, true);
-}
-
-void qt_change_net_wm_state(const QWidget* w, bool set, Atom one, Atom two = 0)
-{
- if (!w->isVisible()) // not managed by the window manager
- return;
-
- XEvent e;
- e.xclient.type = ClientMessage;
- e.xclient.message_type = ATOM(_NET_WM_STATE);
- e.xclient.display = X11->display;
- e.xclient.window = w->internalWinId();
- e.xclient.format = 32;
- e.xclient.data.l[0] = set ? 1 : 0;
- e.xclient.data.l[1] = one;
- e.xclient.data.l[2] = two;
- e.xclient.data.l[3] = 0;
- e.xclient.data.l[4] = 0;
- XSendEvent(X11->display, RootWindow(X11->display, w->x11Info().screen()),
- false, (SubstructureNotifyMask | SubstructureRedirectMask), &e);
-}
-
-struct QX11WindowAttributes {
- const XWindowAttributes *att;
-};
-
-void qt_x11_getX11InfoForWindow(QX11Info * xinfo, const XWindowAttributes &a)
-{
- QX11WindowAttributes att;
- att.att = &a;
- qt_x11_getX11InfoForWindow(xinfo,att);
-}
-
-
-static QVector<Atom> getNetWmState(QWidget *w)
-{
- QVector<Atom> returnValue;
-
- // Don't read anything, just get the size of the property data
- Atom actualType;
- int actualFormat;
- ulong propertyLength;
- ulong bytesLeft;
- uchar *propertyData = 0;
- if (XGetWindowProperty(X11->display, w->internalWinId(), ATOM(_NET_WM_STATE), 0, 0,
- False, XA_ATOM, &actualType, &actualFormat,
- &propertyLength, &bytesLeft, &propertyData) == Success
- && actualType == XA_ATOM && actualFormat == 32) {
- returnValue.resize(bytesLeft / 4);
- XFree((char*) propertyData);
- propertyData = 0;
-
- // fetch all data
- if (XGetWindowProperty(X11->display, w->internalWinId(), ATOM(_NET_WM_STATE), 0,
- returnValue.size(), False, XA_ATOM, &actualType, &actualFormat,
- &propertyLength, &bytesLeft, &propertyData) != Success) {
- returnValue.clear();
- } else if (propertyLength != (ulong)returnValue.size()) {
- returnValue.resize(propertyLength);
- }
-
- // put it into netWmState
- if (!returnValue.isEmpty()) {
- memcpy(returnValue.data(), propertyData, returnValue.size() * sizeof(Atom));
- }
- if (propertyData)
- XFree((char*) propertyData);
- }
-
- return returnValue;
-}
-
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
-{
- Q_Q(QWidget);
- Qt::WindowType type = q->windowType();
- Qt::WindowFlags &flags = data.window_flags;
- QWidget *parentWidget = q->parentWidget();
-
- if (type == Qt::ToolTip)
- flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
- if (type == Qt::Popup)
- flags |= Qt::X11BypassWindowManagerHint;
-
- bool topLevel = (flags & Qt::Window);
- bool popup = (type == Qt::Popup);
- bool dialog = (type == Qt::Dialog
- || type == Qt::Sheet);
- bool desktop = (type == Qt::Desktop);
- bool tool = (type == Qt::Tool || type == Qt::SplashScreen
- || type == Qt::ToolTip || type == Qt::Drawer);
-
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::create_sys START:" << q << "topLevel?" << topLevel << "WId:"
- << window << "initializeWindow:" << initializeWindow << "destroyOldWindow" << destroyOldWindow;
-#endif
- if (topLevel) {
- if (parentWidget) { // if our parent stays on top, so must we
- QWidget *ptl = parentWidget->window();
- if(ptl && (ptl->windowFlags() & Qt::WindowStaysOnTopHint))
- flags |= Qt::WindowStaysOnTopHint;
- }
-
- if (type == Qt::SplashScreen) {
- if (X11->isSupportedByWM(ATOM(_NET_WM_WINDOW_TYPE_SPLASH))) {
- flags &= ~Qt::X11BypassWindowManagerHint;
- } else {
- flags |= Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint;
- }
- }
- // All these buttons depend on the system menu, so we enable it
- if (flags & (Qt::WindowMinimizeButtonHint
- | Qt::WindowMaximizeButtonHint
- | Qt::WindowContextHelpButtonHint))
- flags |= Qt::WindowSystemMenuHint;
- }
-
-
- Window parentw, destroyw = 0;
- WId id = 0;
-
- // always initialize
- if (!window)
- initializeWindow = true;
-
- QX11Info *parentXinfo = parentWidget ? &parentWidget->d_func()->xinfo : 0;
-
- if (desktop &&
- qt_x11_create_desktop_on_screen >= 0 &&
- qt_x11_create_desktop_on_screen != xinfo.screen()) {
- // desktop on a certain screen other than the default requested
- QX11InfoData *xd = &X11->screens[qt_x11_create_desktop_on_screen];
- xinfo.setX11Data(xd);
- } else if (parentXinfo && (parentXinfo->screen() != xinfo.screen()
- || (parentXinfo->visual() != xinfo.visual()
- && !q->inherits("QGLWidget"))))
- {
- // QGLWidgets have to be excluded here as they have a
- // specially crafted QX11Info structure which can't be swapped
- // out with the parent widgets QX11Info. The parent visual,
- // for instance, might not even be GL capable.
- xinfo = *parentXinfo;
- }
-
- //get display, screen number, root window and desktop geometry for
- //the current screen
- Display *dpy = X11->display;
- int scr = xinfo.screen();
- Window root_win = RootWindow(dpy, scr);
- int sw = DisplayWidth(dpy,scr);
- int sh = DisplayHeight(dpy,scr);
-
- if (desktop) { // desktop widget
- dialog = popup = false; // force these flags off
- data.crect.setRect(0, 0, sw, sh);
- } else if (topLevel && !q->testAttribute(Qt::WA_Resized)) {
- QDesktopWidget *desktopWidget = qApp->desktop();
- if (desktopWidget->isVirtualDesktop()) {
- QRect r = desktopWidget->screenGeometry();
- sw = r.width();
- sh = r.height();
- }
-
- int width = sw / 2;
- int height = 4 * sh / 10;
- if (extra) {
- width = qMax(qMin(width, extra->maxw), extra->minw);
- height = qMax(qMin(height, extra->maxh), extra->minh);
- }
- data.crect.setSize(QSize(width, height));
- }
-
- parentw = topLevel ? root_win : parentWidget->effectiveWinId();
-
- XSetWindowAttributes wsa;
-
- if (window) { // override the old window
- if (destroyOldWindow) {
- if (topLevel)
- X11->dndEnable(q, false);
- destroyw = data.winid;
- }
- id = window;
- setWinId(window);
- XWindowAttributes a;
- XGetWindowAttributes(dpy, window, &a);
- data.crect.setRect(a.x, a.y, a.width, a.height);
-
- if (a.map_state == IsUnmapped)
- q->setAttribute(Qt::WA_WState_Visible, false);
- else
- q->setAttribute(Qt::WA_WState_Visible);
-
- qt_x11_getX11InfoForWindow(&xinfo,a);
-
- } else if (desktop) { // desktop widget
-#ifdef QWIDGET_EXTRA_DEBUG
- qDebug() << "create desktop";
-#endif
- id = (WId)parentw; // id = root window
-// QWidget *otherDesktop = find(id); // is there another desktop?
-// if (otherDesktop && otherDesktop->testWFlags(Qt::WPaintDesktop)) {
-// otherDesktop->d->setWinId(0); // remove id from widget mapper
-// d->setWinId(id); // make sure otherDesktop is
-// otherDesktop->d->setWinId(id); // found first
-// } else {
- setWinId(id);
-// }
- } else if (topLevel || q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) {
-#ifdef QWIDGET_EXTRA_DEBUG
- static int topLevels = 0;
- static int children = 0;
- if (parentw == root_win)
- qDebug() << "create toplevel" << ++topLevels;
- else
- qDebug() << "create child" << ++children;
-#endif
- QRect safeRect = data.crect; //##### must handle huge sizes as well.... i.e. wrect
- if (safeRect.width() < 1|| safeRect.height() < 1) {
- if (topLevel) {
- // top-levels must be at least 1x1
- safeRect.setSize(safeRect.size().expandedTo(QSize(1, 1)));
- } else {
- // create it way off screen, and rely on
- // setWSGeometry() to do the right thing with it later
- safeRect = QRect(-1000,-1000,1,1);
- }
- }
-#ifndef QT_NO_XRENDER
- int screen = xinfo.screen();
- if (topLevel && X11->use_xrender
- && xinfo.depth() != 32 && X11->argbVisuals[screen]
- && q->testAttribute(Qt::WA_TranslucentBackground))
- {
- QX11InfoData *xd = xinfo.getX11Data(true);
-
- xd->screen = screen;
- xd->visual = X11->argbVisuals[screen];
- xd->colormap = X11->argbColormaps[screen];
- xd->depth = 32;
- xd->defaultVisual = false;
- xd->defaultColormap = false;
- xd->cells = xd->visual->map_entries;
- xinfo.setX11Data(xd);
- }
-#endif
- if (xinfo.defaultVisual() && xinfo.defaultColormap()) {
- id = (WId)qt_XCreateSimpleWindow(q, dpy, parentw,
- safeRect.left(), safeRect.top(),
- safeRect.width(), safeRect.height(),
- 0,
- BlackPixel(dpy, xinfo.screen()),
- WhitePixel(dpy, xinfo.screen()));
- } else {
- wsa.background_pixel = WhitePixel(dpy, xinfo.screen());
- wsa.border_pixel = BlackPixel(dpy, xinfo.screen());
- wsa.colormap = xinfo.colormap();
- id = (WId)qt_XCreateWindow(q, dpy, parentw,
- safeRect.left(), safeRect.top(),
- safeRect.width(), safeRect.height(),
- 0, xinfo.depth(), InputOutput,
- (Visual *) xinfo.visual(),
- CWBackPixel|CWBorderPixel|CWColormap,
- &wsa);
- }
-
- setWinId(id); // set widget id/handle + hd
- }
-
-#ifndef QT_NO_XRENDER
- if (picture) {
- XRenderFreePicture(X11->display, picture);
- picture = 0;
- }
-
- if (X11->use_xrender && !desktop && q->internalWinId()) {
- XRenderPictFormat *format = XRenderFindVisualFormat(dpy, (Visual *) xinfo.visual());
- if (format)
- picture = XRenderCreatePicture(dpy, id, format, 0, 0);
- }
-#endif // QT_NO_XRENDER
-
- QtMWMHints mwmhints;
- mwmhints.flags = 0L;
- mwmhints.functions = 0L;
- mwmhints.decorations = 0;
- mwmhints.input_mode = 0L;
- mwmhints.status = 0L;
-
- if (topLevel) {
- ulong wsa_mask = 0;
- if (type != Qt::SplashScreen) { // && customize) {
- mwmhints.flags |= MWM_HINTS_DECORATIONS;
-
- bool customize = flags & Qt::CustomizeWindowHint;
- if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
- mwmhints.decorations |= MWM_DECOR_BORDER;
- mwmhints.decorations |= MWM_DECOR_RESIZEH;
-
- if (flags & Qt::WindowTitleHint)
- mwmhints.decorations |= MWM_DECOR_TITLE;
-
- if (flags & Qt::WindowSystemMenuHint)
- mwmhints.decorations |= MWM_DECOR_MENU;
-
- if (flags & Qt::WindowMinimizeButtonHint) {
- mwmhints.decorations |= MWM_DECOR_MINIMIZE;
- mwmhints.functions |= MWM_FUNC_MINIMIZE;
- }
-
- if (flags & Qt::WindowMaximizeButtonHint) {
- mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
- mwmhints.functions |= MWM_FUNC_MAXIMIZE;
- }
-
- if (flags & Qt::WindowCloseButtonHint)
- mwmhints.functions |= MWM_FUNC_CLOSE;
- }
- } else {
- // if type == Qt::SplashScreen
- mwmhints.decorations = MWM_DECOR_ALL;
- }
-
- if (tool) {
- wsa.save_under = True;
- wsa_mask |= CWSaveUnder;
- }
-
- if (flags & Qt::X11BypassWindowManagerHint) {
- wsa.override_redirect = True;
- wsa_mask |= CWOverrideRedirect;
- }
-
- if (wsa_mask && initializeWindow) {
- Q_ASSERT(id);
- XChangeWindowAttributes(dpy, id, wsa_mask, &wsa);
- }
-
- if (mwmhints.functions != 0) {
- mwmhints.flags |= MWM_HINTS_FUNCTIONS;
- mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
- } else {
- mwmhints.functions = MWM_FUNC_ALL;
- }
-
- if (!(flags & Qt::FramelessWindowHint)
- && flags & Qt::CustomizeWindowHint
- && flags & Qt::WindowTitleHint
- && !(flags &
- (Qt::WindowMinimizeButtonHint
- | Qt::WindowMaximizeButtonHint
- | Qt::WindowCloseButtonHint))) {
- // a special case - only the titlebar without any button
- mwmhints.flags = MWM_HINTS_FUNCTIONS;
- mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
- mwmhints.decorations = 0;
- }
- }
-
- if (!initializeWindow) {
- // do no initialization
- } else if (popup) { // popup widget
- // set EWMH window types
- setNetWmWindowTypes();
-
- wsa.override_redirect = True;
- wsa.save_under = True;
- Q_ASSERT(id);
- XChangeWindowAttributes(dpy, id, CWOverrideRedirect | CWSaveUnder,
- &wsa);
- } else if (topLevel && !desktop) { // top-level widget
- if (!X11->wm_client_leader)
- create_wm_client_leader();
-
- // note: WM_TRANSIENT_FOR is set in QWidgetPrivate::show_sys()
-
- XSizeHints size_hints;
- size_hints.flags = USSize | PSize | PWinGravity;
- size_hints.x = data.crect.left();
- size_hints.y = data.crect.top();
- size_hints.width = data.crect.width();
- size_hints.height = data.crect.height();
- size_hints.win_gravity =
- QApplication::isRightToLeft() ? NorthEastGravity : NorthWestGravity;
-
- XWMHints wm_hints; // window manager hints
- memset(&wm_hints, 0, sizeof(wm_hints)); // make valgrind happy
- wm_hints.flags = InputHint | StateHint | WindowGroupHint;
- wm_hints.input = q->testAttribute(Qt::WA_X11DoNotAcceptFocus) ? False : True;
- wm_hints.initial_state = NormalState;
- wm_hints.window_group = X11->wm_client_leader;
-
- XClassHint class_hint;
- QByteArray appName = qAppName().toLatin1();
- class_hint.res_name = appName.data(); // application name
- class_hint.res_class = const_cast<char *>(QX11Info::appClass()); // application class
-
- XSetWMProperties(dpy, id, 0, 0,
- qApp->d_func()->argv, qApp->d_func()->argc,
- &size_hints, &wm_hints, &class_hint);
-
- XResizeWindow(dpy, id,
- qBound(1, data.crect.width(), XCOORD_MAX),
- qBound(1, data.crect.height(), XCOORD_MAX));
- XStoreName(dpy, id, appName.data());
- Atom protocols[5];
- int n = 0;
- protocols[n++] = ATOM(WM_DELETE_WINDOW); // support del window protocol
- protocols[n++] = ATOM(WM_TAKE_FOCUS); // support take focus window protocol
- protocols[n++] = ATOM(_NET_WM_PING); // support _NET_WM_PING protocol
-#ifndef QT_NO_XSYNC
- protocols[n++] = ATOM(_NET_WM_SYNC_REQUEST); // support _NET_WM_SYNC_REQUEST protocol
-#endif // QT_NO_XSYNC
- if (flags & Qt::WindowContextHelpButtonHint)
- protocols[n++] = ATOM(_NET_WM_CONTEXT_HELP);
- XSetWMProtocols(dpy, id, protocols, n);
-
- // set mwm hints
- SetMWMHints(dpy, id, mwmhints);
-
- // set EWMH window types
- setNetWmWindowTypes();
-
- // set _NET_WM_PID
- long curr_pid = getpid();
- XChangeProperty(dpy, id, ATOM(_NET_WM_PID), XA_CARDINAL, 32, PropModeReplace,
- (unsigned char *) &curr_pid, 1);
-
- // when we create a toplevel widget, the frame strut should be dirty
- data.fstrut_dirty = 1;
-
- // declare the widget's window role
- if (QTLWExtra *topData = maybeTopData()) {
- if (!topData->role.isEmpty()) {
- QByteArray windowRole = topData->role.toUtf8();
- XChangeProperty(dpy, id,
- ATOM(WM_WINDOW_ROLE), XA_STRING, 8, PropModeReplace,
- (unsigned char *)windowRole.constData(), windowRole.length());
- }
- }
-
- // set client leader property
- XChangeProperty(dpy, id, ATOM(WM_CLIENT_LEADER),
- XA_WINDOW, 32, PropModeReplace,
- (unsigned char *)&X11->wm_client_leader, 1);
- } else {
- // non-toplevel widgets don't have a frame, so no need to
- // update the strut
- data.fstrut_dirty = 0;
- }
-
- if (initializeWindow && q->internalWinId()) {
- // don't erase when resizing
- wsa.bit_gravity = QApplication::isRightToLeft() ? NorthEastGravity : NorthWestGravity;
- Q_ASSERT(id);
- XChangeWindowAttributes(dpy, id, CWBitGravity, &wsa);
- }
-
- // set X11 event mask
- if (desktop) {
-// QWidget* main_desktop = find(id);
-// if (main_desktop->testWFlags(Qt::WPaintDesktop))
-// XSelectInput(dpy, id, stdDesktopEventMask | ExposureMask);
-// else
- XSelectInput(dpy, id, stdDesktopEventMask);
- } else if (q->internalWinId()) {
- XSelectInput(dpy, id, stdWidgetEventMask);
-#if !defined (QT_NO_TABLET)
- QTabletDeviceDataList *tablet_list = qt_tablet_devices();
- if (X11->ptrXSelectExtensionEvent) {
- for (int i = 0; i < tablet_list->size(); ++i) {
- QTabletDeviceData tablet = tablet_list->at(i);
- X11->ptrXSelectExtensionEvent(dpy, id, reinterpret_cast<XEventClass*>(tablet.eventList),
- tablet.eventCount);
- }
- }
-#endif
- }
-
- if (desktop) {
- q->setAttribute(Qt::WA_WState_Visible);
- } else if (topLevel) { // set X cursor
- if (initializeWindow) {
- qt_x11_enforce_cursor(q);
-
- if (QTLWExtra *topData = maybeTopData())
- if (!topData->caption.isEmpty())
- setWindowTitle_helper(topData->caption);
-
- //always enable dnd: it's not worth the effort to maintain the state
- // NOTE: this always creates topData()
- X11->dndEnable(q, true);
-
- if (maybeTopData() && maybeTopData()->opacity != 255)
- q->setWindowOpacity(maybeTopData()->opacity/255.);
-
- }
- } else if (q->internalWinId()) {
- qt_x11_enforce_cursor(q);
- if (QWidget *p = q->parentWidget()) // reset the cursor on the native parent
- qt_x11_enforce_cursor(p);
- }
-
- if (extra && !extra->mask.isEmpty() && q->internalWinId())
- XShapeCombineRegion(X11->display, q->internalWinId(), ShapeBounding, 0, 0,
- extra->mask.handle(), ShapeSet);
-
- if (q->hasFocus() && q->testAttribute(Qt::WA_InputMethodEnabled)) {
- QInputContext *inputContext = q->inputContext();
- if (inputContext)
- inputContext->setFocusWidget(q);
- }
-
- if (destroyw) {
- qt_XDestroyWindow(q, dpy, destroyw);
- if (QTLWExtra *topData = maybeTopData()) {
-#ifndef QT_NO_XSYNC
- if (topData->syncUpdateCounter)
- XSyncDestroyCounter(dpy, topData->syncUpdateCounter);
-#endif
- // we destroyed our old window - reset the top-level state
- createTLSysExtra();
- }
- }
-
- // newly created windows are positioned at the window system's
- // (0,0) position. If the parent uses wrect mapping to expand the
- // coordinate system, we must also adjust this widget's window
- // system position
- if (!topLevel && !parentWidget->data->wrect.topLeft().isNull())
- setWSGeometry();
- else if (topLevel && (data.crect.width() == 0 || data.crect.height() == 0))
- q->setAttribute(Qt::WA_OutsideWSRange, true);
-
- if (!topLevel && q->testAttribute(Qt::WA_NativeWindow) && q->testAttribute(Qt::WA_Mapped)) {
- Q_ASSERT(q->internalWinId());
- XMapWindow(X11->display, q->internalWinId());
- // Ensure that mapped alien widgets are flushed immediately when re-created as native widgets.
- if (QWindowSurface *surface = q->windowSurface())
- surface->flush(q, q->rect(), q->mapTo(surface->window(), QPoint()));
- }
-
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::create_sys END:" << q;
-#endif
-}
-
-static void qt_x11_recreateWidget(QWidget *widget)
-{
- if (widget->inherits("QGLWidget")) {
- // We send QGLWidgets a ParentChange event which causes them to
- // recreate their GL context, which in turn causes them to choose
- // their visual again. Now that WA_TranslucentBackground is set,
- // QGLContext::chooseVisual will select an ARGB visual.
- QEvent e(QEvent::ParentChange);
- QApplication::sendEvent(widget, &e);
- } else {
- // For regular widgets, reparent them with their parent which
- // also triggers a recreation of the native window
- QPoint pos = widget->pos();
- bool visible = widget->isVisible();
- if (visible)
- widget->hide();
-
- widget->setParent(widget->parentWidget(), widget->windowFlags());
- widget->move(pos);
- if (visible)
- widget->show();
- }
-}
-
-static void qt_x11_recreateNativeWidgetsRecursive(QWidget *widget)
-{
- if (widget->internalWinId())
- qt_x11_recreateWidget(widget);
-
- const QObjectList &children = widget->children();
- for (int i = 0; i < children.size(); ++i) {
- QWidget *child = qobject_cast<QWidget*>(children.at(i));
- if (child)
- qt_x11_recreateNativeWidgetsRecursive(child);
- }
-}
-
-void QWidgetPrivate::x11UpdateIsOpaque()
-{
-#ifndef QT_NO_XRENDER
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->testAttribute(Qt::WA_TranslucentBackground))
- return;
-
- bool topLevel = (data.window_flags & Qt::Window);
- int screen = xinfo.screen();
- if (topLevel && X11->use_xrender
- && X11->argbVisuals[screen] && xinfo.depth() != 32)
- {
- qt_x11_recreateNativeWidgetsRecursive(q);
- }
-#endif
-}
-
-/*
- Returns true if the background is inherited; otherwise returns
- false.
-
- Mainly used in the paintOnScreen case.
-*/
-bool QWidgetPrivate::isBackgroundInherited() const
-{
- Q_Q(const QWidget);
-
- // windows do not inherit their background
- if (q->isWindow() || q->windowType() == Qt::SubWindow)
- return false;
-
- if (q->testAttribute(Qt::WA_NoSystemBackground) || q->testAttribute(Qt::WA_OpaquePaintEvent))
- return false;
-
- const QPalette &pal = q->palette();
- QPalette::ColorRole bg = q->backgroundRole();
- QBrush brush = pal.brush(bg);
-
- // non opaque brushes leaves us no choice, we must inherit
- if (!q->autoFillBackground() || !brush.isOpaque())
- return true;
-
- if (brush.style() == Qt::SolidPattern) {
- // the background is just a solid color. If there is no
- // propagated contents, then we claim as performance
- // optimization that it was not inheritet. This is the normal
- // case in standard Windows or Motif style.
- const QWidget *w = q->parentWidget();
- if (!w->d_func()->isBackgroundInherited())
- return false;
- }
-
- return true;
-}
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
- Q_D(QWidget);
- d->aboutToDestroy();
- if (!isWindow() && parentWidget())
- parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry()));
- d->deactivateWidgetCleanup();
- if (testAttribute(Qt::WA_WState_Created)) {
- setAttribute(Qt::WA_WState_Created, false);
- QObjectList childList = children();
- for (int i = 0; i < childList.size(); ++i) { // destroy all widget children
- register QObject *obj = childList.at(i);
- if (obj->isWidgetType())
- static_cast<QWidget*>(obj)->destroy(destroySubWindows,
- destroySubWindows);
- }
- if (QWidgetPrivate::mouseGrabber == this)
- releaseMouse();
- if (QWidgetPrivate::keyboardGrabber == this)
- releaseKeyboard();
- if (isWindow())
- X11->deferred_map.removeAll(this);
- if (isModal()) {
- // just be sure we leave modal
- QApplicationPrivate::leaveModal(this);
- }
- else if ((windowType() == Qt::Popup))
- qApp->d_func()->closePopup(this);
-
-#ifndef QT_NO_XRENDER
- if (d->picture) {
- if (destroyWindow)
- XRenderFreePicture(X11->display, d->picture);
- d->picture = 0;
- }
-#endif // QT_NO_XRENDER
-
- // delete the _NET_WM_USER_TIME_WINDOW
- qt_net_remove_user_time(this);
-
- if ((windowType() == Qt::Desktop)) {
- if (acceptDrops())
- X11->dndEnable(this, false);
- } else {
- if (isWindow())
- X11->dndEnable(this, false);
- if (destroyWindow)
- qt_XDestroyWindow(this, X11->display, data->winid);
- }
- QT_TRY {
- d->setWinId(0);
- } QT_CATCH (const std::bad_alloc &) {
- // swallow - destructors must not throw
- }
-
- extern void qPRCleanup(QWidget *widget); // from qapplication_x11.cpp
- if (testAttribute(Qt::WA_WState_Reparented))
- qPRCleanup(this);
-
- if(d->ic) {
- delete d->ic;
- } else {
- // release previous focus information participating with
- // preedit preservation of qic
- QInputContext *qic = QApplicationPrivate::inputContext;
- if (qic)
- qic->widgetDestroyed(this);
- }
- }
-}
-
-void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
-{
- Q_Q(QWidget);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::setParent_sys START" << q << "parent:" << parent;
-#endif
- QX11Info old_xinfo = xinfo;
- if (parent && parent->windowType() == Qt::Desktop) {
- // make sure the widget is created on the same screen as the
- // programmer specified desktop widget
- xinfo = parent->d_func()->xinfo;
- parent = 0;
- }
-
- QTLWExtra *topData = maybeTopData();
- bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
- if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
- q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
- extern void qPRCreate(const QWidget *, Window);
-#ifndef QT_NO_CURSOR
- QCursor oldcurs;
-#endif
-
- // dnd unregister (we will register again below)
- if (q->testAttribute(Qt::WA_DropSiteRegistered))
- q->setAttribute(Qt::WA_DropSiteRegistered, false);
-
- // if we are a top then remove our dnd prop for now
- // it will get rest later
- if (q->isWindow() && wasCreated)
- X11->dndEnable(q, false);
-
- if (topData)
- qt_net_remove_user_time(q);
-
-// QWidget *oldparent = q->parentWidget();
- WId old_winid = wasCreated ? data.winid : 0;
- if ((q->windowType() == Qt::Desktop))
- old_winid = 0;
- setWinId(0);
-
-#ifndef QT_NO_XRENDER
- if (picture) {
- XRenderFreePicture(X11->display, picture);
- picture = 0;
- }
-#endif
-
- // hide and reparent our own window away. Otherwise we might get
- // destroyed when emitting the child remove event below. See QWorkspace.
- if (wasCreated && old_winid) {
- XUnmapWindow(X11->display, old_winid);
- if (!old_xinfo.screen() != xinfo.screen())
- XReparentWindow(X11->display, old_winid, RootWindow(X11->display, xinfo.screen()), 0, 0);
- }
- if (topData) {
- topData->parentWinId = 0;
- // zero the frame strut and mark it dirty
- topData->frameStrut.setCoords(0, 0, 0, 0);
-
- // reparenting from top-level, make sure show() works again
- topData->waitingForMapNotify = 0;
- topData->validWMState = 0;
- }
- data.fstrut_dirty = (!parent || (f & Qt::Window)); // toplevels get a dirty framestrut
-
- QObjectPrivate::setParent_helper(parent);
- bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
-
- data.window_flags = f;
- q->setAttribute(Qt::WA_WState_Created, false);
- q->setAttribute(Qt::WA_WState_Visible, false);
- q->setAttribute(Qt::WA_WState_Hidden, false);
- adjustFlags(data.window_flags, q);
- // keep compatibility with previous versions, we need to preserve the created state
- // (but we recreate the winId for the widget being reparented, again for compatibility)
- if (wasCreated)
- createWinId();
- if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
- q->setAttribute(Qt::WA_WState_Hidden);
- q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
- if (wasCreated) {
- QObjectList chlist = q->children();
- for (int i = 0; i < chlist.size(); ++i) { // reparent children
- QObject *obj = chlist.at(i);
- if (obj->isWidgetType()) {
- QWidget *w = (QWidget *)obj;
- if (!w->testAttribute(Qt::WA_WState_Created))
- continue;
- if (xinfo.screen() != w->d_func()->xinfo.screen()) {
- // ### force setParent() to not shortcut out (because
- // ### we're setting the parent to the current parent)
- // ### setParent will add child back to the list
- // ### of children so we need to make sure the
- // ### widget won't be added twice.
- w->d_func()->parent = 0;
- this->children.removeOne(w);
- w->setParent(q);
- } else if (!w->isWindow()) {
- w->d_func()->invalidateBuffer(w->rect());
- if (w->internalWinId()) {
- if (w->testAttribute(Qt::WA_NativeWindow)) {
- QWidget *nativeParentWidget = w->nativeParentWidget();
- // Qt::WA_NativeWindow ensures that we always have a nativeParentWidget
- Q_ASSERT(nativeParentWidget != 0);
- QPoint p = w->mapTo(nativeParentWidget, QPoint());
- XReparentWindow(X11->display,
- w->internalWinId(),
- nativeParentWidget->internalWinId(),
- p.x(), p.y());
- } else {
- w->d_func()->setParent_sys(q, w->data->window_flags);
- }
- }
- } else if (isTransient(w)) {
- /*
- when reparenting toplevel windows with toplevel-transient children,
- we need to make sure that the window manager gets the updated
- WM_TRANSIENT_FOR information... unfortunately, some window managers
- don't handle changing WM_TRANSIENT_FOR before the toplevel window is
- visible, so we unmap and remap all toplevel-transient children *after*
- the toplevel parent has been mapped. thankfully, this is easy in Qt :)
-
- note that the WM_TRANSIENT_FOR hint is actually updated in
- QWidgetPrivate::show_sys()
- */
- if (w->internalWinId())
- XUnmapWindow(X11->display, w->internalWinId());
- QApplication::postEvent(w, new QEvent(QEvent::ShowWindowRequest));
- }
- }
- }
- qPRCreate(q, old_winid);
- updateSystemBackground();
-
- if (old_winid) {
- Window *cmwret;
- int count;
- if (XGetWMColormapWindows(X11->display, old_winid, &cmwret, &count)) {
- Window *cmw;
- int cmw_size = sizeof(Window)*count;
- cmw = new Window[count];
- memcpy((char *)cmw, (char *)cmwret, cmw_size);
- XFree((char *)cmwret);
- int i;
- for (i=0; i<count; i++) {
- if (cmw[i] == old_winid) {
- cmw[i] = q->internalWinId();
- break;
- }
- }
- int top_count;
- if (XGetWMColormapWindows(X11->display, q->window()->internalWinId(),
- &cmwret, &top_count))
- {
- Window *merged_cmw = new Window[count + top_count];
- memcpy((char *)merged_cmw, (char *)cmw, cmw_size);
- memcpy((char *)merged_cmw + cmw_size, (char *)cmwret, sizeof(Window)*top_count);
- delete [] cmw;
- XFree((char *)cmwret);
- cmw = merged_cmw;
- count += top_count;
- }
-
- XSetWMColormapWindows(X11->display, q->window()->internalWinId(), cmw, count);
- delete [] cmw;
- }
-
- qt_XDestroyWindow(q, X11->display, old_winid);
- }
- }
-
- // check if we need to register our dropsite
- if (q->testAttribute(Qt::WA_AcceptDrops)
- || (!q->isWindow() && q->parentWidget() && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))) {
- q->setAttribute(Qt::WA_DropSiteRegistered, true);
- }
-#if !defined(QT_NO_IM)
- ic = 0;
-#endif
- invalidateBuffer(q->rect());
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::setParent_sys END" << q;
-#endif
-}
-
-QPoint QWidgetPrivate::mapToGlobal(const QPoint &pos) const
-{
- Q_Q(const QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->internalWinId()) {
- QPoint p = pos + q->data->crect.topLeft();
- //cannot trust that !isWindow() implies parentWidget() before create
- return (q->isWindow() || !q->parentWidget()) ? p : q->parentWidget()->d_func()->mapToGlobal(p);
- }
- int x, y;
- Window child;
- QPoint p = mapToWS(pos);
- XTranslateCoordinates(X11->display, q->internalWinId(),
- QApplication::desktop()->screen(xinfo.screen())->internalWinId(),
- p.x(), p.y(), &x, &y, &child);
- return QPoint(x, y);
-}
-
-QPoint QWidgetPrivate::mapFromGlobal(const QPoint &pos) const
-{
- Q_Q(const QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->internalWinId()) {
- //cannot trust that !isWindow() implies parentWidget() before create
- QPoint p = (q->isWindow() || !q->parentWidget()) ? pos : q->parentWidget()->d_func()->mapFromGlobal(pos);
- return p - q->data->crect.topLeft();
- }
- int x, y;
- Window child;
- XTranslateCoordinates(X11->display,
- QApplication::desktop()->screen(xinfo.screen())->internalWinId(),
- q->internalWinId(), pos.x(), pos.y(), &x, &y, &child);
- return mapFromWS(QPoint(x, y));
-}
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- QPoint offset = data->crect.topLeft();
- const QWidget *w = this;
- const QWidget *p = w->parentWidget();
- while (!w->isWindow() && p) {
- w = p;
- p = p->parentWidget();
- offset += w->data->crect.topLeft();
- }
-
- const QWidgetPrivate *wd = w->d_func();
- QTLWExtra *tlw = wd->topData();
- if (!tlw->embedded)
- return pos + offset;
-
- return d->mapToGlobal(pos);
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
- Q_D(const QWidget);
- QPoint offset = data->crect.topLeft();
- const QWidget *w = this;
- const QWidget *p = w->parentWidget();
- while (!w->isWindow() && p) {
- w = p;
- p = p->parentWidget();
- offset += w->data->crect.topLeft();
- }
-
- const QWidgetPrivate *wd = w->d_func();
- QTLWExtra *tlw = wd->topData();
- if (!tlw->embedded)
- return pos - offset;
-
- return d->mapFromGlobal(pos);
-}
-
-void QWidgetPrivate::updateSystemBackground()
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created) || !q->internalWinId())
- return;
- QBrush brush = q->palette().brush(QPalette::Active, q->backgroundRole());
- Qt::WindowType type = q->windowType();
- if (brush.style() == Qt::NoBrush
- || q->testAttribute(Qt::WA_NoSystemBackground)
- || q->testAttribute(Qt::WA_UpdatesDisabled)
- || type == Qt::Popup || type == Qt::ToolTip) {
- if (QX11Info::isCompositingManagerRunning()
- && q->testAttribute(Qt::WA_TranslucentBackground)
- && !(q->parent()))
- XSetWindowBackground(X11->display, q->internalWinId(),
- QColormap::instance(xinfo.screen()).pixel(Qt::transparent));
- else
- XSetWindowBackgroundPixmap(X11->display, q->internalWinId(), XNone);
- }
- else if (brush.style() == Qt::SolidPattern && brush.isOpaque())
- XSetWindowBackground(X11->display, q->internalWinId(),
- QColormap::instance(xinfo.screen()).pixel(brush.color()));
- else if (isBackgroundInherited())
- XSetWindowBackgroundPixmap(X11->display, q->internalWinId(), ParentRelative);
- else if (brush.style() == Qt::TexturePattern) {
- extern QPixmap qt_toX11Pixmap(const QPixmap &pixmap); // qpixmap_x11.cpp
- XSetWindowBackgroundPixmap(X11->display, q->internalWinId(),
- static_cast<QX11PixmapData*>(qt_toX11Pixmap(brush.texture()).data.data())->x11ConvertToDefaultDepth());
- } else
- XSetWindowBackground(X11->display, q->internalWinId(),
- QColormap::instance(xinfo.screen()).pixel(brush.color()));
-}
-
-#ifndef QT_NO_CURSOR
-void QWidgetPrivate::setCursor_sys(const QCursor &)
-{
- Q_Q(QWidget);
- qt_x11_enforce_cursor(q);
- XFlush(X11->display);
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
- Q_Q(QWidget);
- qt_x11_enforce_cursor(q);
- XFlush(X11->display);
-}
-#endif
-
-static XTextProperty*
-qstring_to_xtp(const QString& s)
-{
- static XTextProperty tp = { 0, 0, 0, 0 };
- static bool free_prop = true; // we can't free tp.value in case it references
- // the data of the static QCString below.
- if (tp.value) {
- if (free_prop)
- XFree(tp.value);
- tp.value = 0;
- free_prop = true;
- }
-
- static const QTextCodec* mapper = QTextCodec::codecForLocale();
- int errCode = 0;
- if (mapper) {
- QByteArray mapped = mapper->fromUnicode(s);
- char* tl[2];
- tl[0] = mapped.data();
- tl[1] = 0;
- errCode = XmbTextListToTextProperty(X11->display, tl, 1, XStdICCTextStyle, &tp);
-#if defined(QT_DEBUG)
- if (errCode < 0)
- qDebug("qstring_to_xtp result code %d", errCode);
-#endif
- }
- if (!mapper || errCode < 0) {
- static QByteArray qcs;
- qcs = s.toAscii();
- tp.value = (uchar*)qcs.data();
- tp.encoding = XA_STRING;
- tp.format = 8;
- tp.nitems = qcs.length();
- free_prop = false;
- }
-
- // ### If we knew WM could understand unicode, we could use
- // ### a much simpler, cheaper encoding...
- /*
- tp.value = (XChar2b*)s.unicode();
- tp.encoding = XA_UNICODE; // wish
- tp.format = 16;
- tp.nitems = s.length();
- */
-
- return &tp;
-}
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (!q->internalWinId())
- return;
- XSetWMName(X11->display, q->internalWinId(), qstring_to_xtp(caption));
-
- QByteArray net_wm_name = caption.toUtf8();
- XChangeProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_NAME), ATOM(UTF8_STRING), 8,
- PropModeReplace, (unsigned char *)net_wm_name.data(), net_wm_name.size());
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
-{
- Q_Q(QWidget);
- if (!q->testAttribute(Qt::WA_WState_Created))
- return;
- QTLWExtra *topData = this->topData();
- if (topData->iconPixmap && !forceReset)
- // already been set
- return;
-
- // preparing images to set the _NET_WM_ICON property
- QIcon icon = q->windowIcon();
- QVector<long> icon_data;
- Qt::HANDLE pixmap_handle = 0;
- if (!icon.isNull()) {
- QList<QSize> availableSizes = icon.availableSizes();
- if(availableSizes.isEmpty()) {
- // try to use default sizes since the icon can be a scalable image like svg.
- availableSizes.push_back(QSize(16,16));
- availableSizes.push_back(QSize(32,32));
- availableSizes.push_back(QSize(64,64));
- availableSizes.push_back(QSize(128,128));
- }
- for(int i = 0; i < availableSizes.size(); ++i) {
- QSize size = availableSizes.at(i);
- QPixmap pixmap = icon.pixmap(size);
- if (!pixmap.isNull()) {
- QImage image = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
- int pos = icon_data.size();
- icon_data.resize(pos + 2 + image.width()*image.height());
- icon_data[pos++] = image.width();
- icon_data[pos++] = image.height();
- if (sizeof(long) == sizeof(quint32)) {
- memcpy(icon_data.data() + pos, image.scanLine(0), image.byteCount());
- } else {
- for (int y = 0; y < image.height(); ++y) {
- uint *scanLine = reinterpret_cast<uint *>(image.scanLine(y));
- for (int x = 0; x < image.width(); ++x)
- icon_data[pos + y*image.width() + x] = scanLine[x];
- }
- }
- }
- }
- if (!icon_data.isEmpty()) {
- extern QPixmap qt_toX11Pixmap(const QPixmap &pixmap);
- /*
- if the app is running on an unknown desktop, or it is not
- using the default visual, convert the icon to 1bpp as stated
- in the ICCCM section 4.1.2.4; otherwise, create the icon pixmap
- in the default depth (even though this violates the ICCCM)
- */
- if (X11->desktopEnvironment == DE_UNKNOWN
- || !QX11Info::appDefaultVisual(xinfo.screen())
- || !QX11Info::appDefaultColormap(xinfo.screen())) {
- // unknown DE or non-default visual/colormap, use 1bpp bitmap
- if (!forceReset || !topData->iconPixmap)
- topData->iconPixmap = new QPixmap(qt_toX11Pixmap(QBitmap(icon.pixmap(QSize(64,64)))));
- pixmap_handle = topData->iconPixmap->handle();
- } else {
- // default depth, use a normal pixmap (even though this
- // violates the ICCCM), since this works on all DEs known to Qt
- if (!forceReset || !topData->iconPixmap)
- topData->iconPixmap = new QPixmap(qt_toX11Pixmap(icon.pixmap(QSize(64,64))));
- pixmap_handle = static_cast<QX11PixmapData*>(topData->iconPixmap->data.data())->x11ConvertToDefaultDepth();
- }
- }
- }
-
- if (!q->internalWinId())
- return;
-
- if (!icon_data.isEmpty()) {
- XChangeProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_ICON), XA_CARDINAL, 32,
- PropModeReplace, (unsigned char *) icon_data.data(),
- icon_data.size());
- } else {
- XDeleteProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_ICON));
- }
-
- XWMHints *h = XGetWMHints(X11->display, q->internalWinId());
- XWMHints wm_hints;
- if (!h) {
- memset(&wm_hints, 0, sizeof(wm_hints)); // make valgrind happy
- h = &wm_hints;
- }
-
- if (pixmap_handle) {
- h->icon_pixmap = pixmap_handle;
- h->flags |= IconPixmapHint;
- } else {
- h->icon_pixmap = 0;
- h->flags &= ~(IconPixmapHint | IconMaskHint);
- }
-
- XSetWMHints(X11->display, q->internalWinId(), h);
- if (h != &wm_hints)
- XFree((char *)h);
-}
-
-void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
-{
- Q_Q(QWidget);
- if (!q->internalWinId())
- return;
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- XSetWMIconName(X11->display, q->internalWinId(), qstring_to_xtp(iconText));
-
- QByteArray icon_name = iconText.toUtf8();
- XChangeProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_ICON_NAME), ATOM(UTF8_STRING), 8,
- PropModeReplace, (unsigned char *) icon_name.constData(), icon_name.size());
-}
-
-
-void QWidget::grabMouse()
-{
- if (isVisible() && !qt_nograb()) {
- if (QWidgetPrivate::mouseGrabber && QWidgetPrivate::mouseGrabber != this)
- QWidgetPrivate::mouseGrabber->releaseMouse();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-#ifndef QT_NO_DEBUG
- int status =
-#endif
- XGrabPointer(X11->display, effectiveWinId(), False,
- (uint)(ButtonPressMask | ButtonReleaseMask |
- PointerMotionMask | EnterWindowMask |
- LeaveWindowMask),
- GrabModeAsync, GrabModeAsync,
- XNone, XNone, X11->time);
-#ifndef QT_NO_DEBUG
- if (status) {
- const char *s =
- status == GrabNotViewable ? "\"GrabNotViewable\"" :
- status == AlreadyGrabbed ? "\"AlreadyGrabbed\"" :
- status == GrabFrozen ? "\"GrabFrozen\"" :
- status == GrabInvalidTime ? "\"GrabInvalidTime\"" :
- "<?>";
- qWarning("QWidget::grabMouse: Failed with %s", s);
- }
-#endif
- QWidgetPrivate::mouseGrabber = this;
- }
-}
-
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
- if (!qt_nograb()) {
- if (QWidgetPrivate::mouseGrabber && QWidgetPrivate::mouseGrabber != this)
- QWidgetPrivate::mouseGrabber->releaseMouse();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-#ifndef QT_NO_DEBUG
- int status =
-#endif
- XGrabPointer(X11->display, effectiveWinId(), False,
- (uint)(ButtonPressMask | ButtonReleaseMask |
- PointerMotionMask | EnterWindowMask | LeaveWindowMask),
- GrabModeAsync, GrabModeAsync,
- XNone, cursor.handle(), X11->time);
-#ifndef QT_NO_DEBUG
- if (status) {
- const char *s =
- status == GrabNotViewable ? "\"GrabNotViewable\"" :
- status == AlreadyGrabbed ? "\"AlreadyGrabbed\"" :
- status == GrabFrozen ? "\"GrabFrozen\"" :
- status == GrabInvalidTime ? "\"GrabInvalidTime\"" :
- "<?>";
- qWarning("QWidget::grabMouse: Failed with %s", s);
- }
-#endif
- QWidgetPrivate::mouseGrabber = this;
- }
-}
-#endif
-
-
-void QWidget::releaseMouse()
-{
- if (!qt_nograb() && QWidgetPrivate::mouseGrabber == this) {
- XUngrabPointer(X11->display, X11->time);
- XFlush(X11->display);
- QWidgetPrivate::mouseGrabber = 0;
- }
-}
-
-
-void QWidget::grabKeyboard()
-{
- if (!qt_nograb()) {
- if (QWidgetPrivate::keyboardGrabber && QWidgetPrivate::keyboardGrabber != this)
- QWidgetPrivate::keyboardGrabber->releaseKeyboard();
- XGrabKeyboard(X11->display, effectiveWinId(), False, GrabModeAsync, GrabModeAsync,
- X11->time);
- QWidgetPrivate::keyboardGrabber = this;
- }
-}
-
-
-void QWidget::releaseKeyboard()
-{
- if (!qt_nograb() && QWidgetPrivate::keyboardGrabber == this) {
- XUngrabKeyboard(X11->display, X11->time);
- QWidgetPrivate::keyboardGrabber = 0;
- }
-}
-
-
-QWidget *QWidget::mouseGrabber()
-{
- return QWidgetPrivate::mouseGrabber;
-}
-
-
-QWidget *QWidget::keyboardGrabber()
-{
- return QWidgetPrivate::keyboardGrabber;
-}
-
-void QWidget::activateWindow()
-{
- QWidget *tlw = window();
- if (tlw->isVisible() && !tlw->d_func()->topData()->embedded && !X11->deferred_map.contains(tlw)) {
- if (X11->userTime == 0)
- X11->userTime = X11->time;
- qt_net_update_user_time(tlw, X11->userTime);
-
- if (X11->isSupportedByWM(ATOM(_NET_ACTIVE_WINDOW))
- && !(tlw->windowFlags() & Qt::X11BypassWindowManagerHint)) {
- XEvent e;
- e.xclient.type = ClientMessage;
- e.xclient.message_type = ATOM(_NET_ACTIVE_WINDOW);
- e.xclient.display = X11->display;
- e.xclient.window = tlw->internalWinId();
- e.xclient.format = 32;
- e.xclient.data.l[0] = 1; // 1 == application
- e.xclient.data.l[1] = X11->userTime;
- if (QWidget *aw = QApplication::activeWindow())
- e.xclient.data.l[2] = aw->internalWinId();
- else
- e.xclient.data.l[2] = XNone;
- e.xclient.data.l[3] = 0;
- e.xclient.data.l[4] = 0;
- XSendEvent(X11->display, RootWindow(X11->display, tlw->x11Info().screen()),
- false, SubstructureNotifyMask | SubstructureRedirectMask, &e);
- } else {
- if (!qt_widget_private(tlw)->topData()->waitingForMapNotify)
- XSetInputFocus(X11->display, tlw->internalWinId(), XRevertToParent, X11->time);
- }
- }
-}
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
- Q_D(QWidget);
- bool needShow = false;
- Qt::WindowStates oldstate = windowState();
- if (oldstate == newstate)
- return;
- if (isWindow()) {
- // Ensure the initial size is valid, since we store it as normalGeometry below.
- if (!testAttribute(Qt::WA_Resized) && !isVisible())
- adjustSize();
-
- QTLWExtra *top = d->topData();
-
- if ((oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized)) {
- if (X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ))
- && X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_VERT))) {
- if ((newstate & Qt::WindowMaximized) && !(oldstate & Qt::WindowFullScreen))
- top->normalGeometry = geometry();
- qt_change_net_wm_state(this, (newstate & Qt::WindowMaximized),
- ATOM(_NET_WM_STATE_MAXIMIZED_HORZ),
- ATOM(_NET_WM_STATE_MAXIMIZED_VERT));
- } else if (! (newstate & Qt::WindowFullScreen)) {
- if (newstate & Qt::WindowMaximized) {
- // save original geometry
- const QRect normalGeometry = geometry();
-
- if (isVisible()) {
- data->fstrut_dirty = true;
- const QRect maxRect = QApplication::desktop()->availableGeometry(this);
- const QRect r = top->normalGeometry;
- const QRect fs = d->frameStrut();
- setGeometry(maxRect.x() + fs.left(),
- maxRect.y() + fs.top(),
- maxRect.width() - fs.left() - fs.right(),
- maxRect.height() - fs.top() - fs.bottom());
- top->normalGeometry = r;
- }
-
- if (top->normalGeometry.width() < 0)
- top->normalGeometry = normalGeometry;
- } else {
- // restore original geometry
- setGeometry(top->normalGeometry);
- }
- }
- }
-
- if ((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
- if (X11->isSupportedByWM(ATOM(_NET_WM_STATE_FULLSCREEN))) {
- if (newstate & Qt::WindowFullScreen) {
- top->normalGeometry = geometry();
- top->fullScreenOffset = d->frameStrut().topLeft();
- }
- qt_change_net_wm_state(this, (newstate & Qt::WindowFullScreen),
- ATOM(_NET_WM_STATE_FULLSCREEN));
- } else {
- needShow = isVisible();
-
- if (newstate & Qt::WindowFullScreen) {
- data->fstrut_dirty = true;
- const QRect normalGeometry = geometry();
- const QPoint fullScreenOffset = d->frameStrut().topLeft();
-
- top->savedFlags = windowFlags();
- setParent(0, Qt::Window | Qt::FramelessWindowHint);
- const QRect r = top->normalGeometry;
- setGeometry(qApp->desktop()->screenGeometry(this));
- top->normalGeometry = r;
-
- if (top->normalGeometry.width() < 0) {
- top->normalGeometry = normalGeometry;
- top->fullScreenOffset = fullScreenOffset;
- }
- } else {
- setParent(0, top->savedFlags);
-
- if (newstate & Qt::WindowMaximized) {
- // from fullscreen to maximized
- data->fstrut_dirty = true;
- const QRect maxRect = QApplication::desktop()->availableGeometry(this);
- const QRect r = top->normalGeometry;
- const QRect fs = d->frameStrut();
- setGeometry(maxRect.x() + fs.left(),
- maxRect.y() + fs.top(),
- maxRect.width() - fs.left() - fs.right(),
- maxRect.height() - fs.top() - fs.bottom());
- top->normalGeometry = r;
- } else {
- // restore original geometry
- setGeometry(top->normalGeometry.adjusted(-top->fullScreenOffset.x(),
- -top->fullScreenOffset.y(),
- -top->fullScreenOffset.x(),
- -top->fullScreenOffset.y()));
- }
- }
- }
- }
-
- createWinId();
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
- if ((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
- if (isVisible()) {
- if (newstate & Qt::WindowMinimized) {
- XEvent e;
- e.xclient.type = ClientMessage;
- e.xclient.message_type = ATOM(WM_CHANGE_STATE);
- e.xclient.display = X11->display;
- e.xclient.window = data->winid;
- e.xclient.format = 32;
- e.xclient.data.l[0] = IconicState;
- e.xclient.data.l[1] = 0;
- e.xclient.data.l[2] = 0;
- e.xclient.data.l[3] = 0;
- e.xclient.data.l[4] = 0;
- XSendEvent(X11->display,
- RootWindow(X11->display,d->xinfo.screen()),
- False, (SubstructureNotifyMask|SubstructureRedirectMask), &e);
- } else {
- setAttribute(Qt::WA_Mapped);
- XMapWindow(X11->display, effectiveWinId());
- }
- }
-
- needShow = false;
- }
- }
-
- data->window_state = newstate;
-
- if (needShow)
- show();
-
- if (newstate & Qt::WindowActive)
- activateWindow();
-
- QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
-}
-
-/*!
- \internal
- Platform-specific part of QWidget::show().
-*/
-
-void QWidgetPrivate::show_sys()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
- invalidateBuffer(q->rect());
- q->setAttribute(Qt::WA_Mapped);
- if (QTLWExtra *tlwExtra = maybeTopData())
- tlwExtra->waitingForMapNotify = 0;
- return;
- }
-
- if (q->isWindow()) {
- XWMHints *h = XGetWMHints(X11->display, q->internalWinId());
- XWMHints wm_hints;
- bool got_hints = h != 0;
- if (!got_hints) {
- memset(&wm_hints, 0, sizeof(wm_hints)); // make valgrind happy
- h = &wm_hints;
- }
- h->initial_state = q->isMinimized() ? IconicState : NormalState;
- h->flags |= StateHint;
- XSetWMHints(X11->display, q->internalWinId(), h);
- if (got_hints)
- XFree((char *)h);
-
- // update WM_NORMAL_HINTS
- do_size_hints(q, extra);
-
- // udpate WM_TRANSIENT_FOR
- if (isTransient(q)) {
- QWidget *p = q->parentWidget();
-
-#ifndef QT_NO_MENU
- // hackish ... try to find the main window related to this QMenu
- if (qobject_cast<QMenu *>(q)) {
- p = static_cast<QMenuPrivate*>(this)->causedPopup.widget;
- if (!p)
- p = q->parentWidget();
- if (!p)
- p = QApplication::widgetAt(q->pos());
- if (!p)
- p = qApp->activeWindow();
- }
-#endif
- if (p)
- p = p->window();
- if (p) {
- // transient for window
- XSetTransientForHint(X11->display, q->internalWinId(), p->internalWinId());
- } else {
- // transient for group
- XSetTransientForHint(X11->display, q->internalWinId(), X11->wm_client_leader);
- }
- }
-
- // update _MOTIF_WM_HINTS
- QtMWMHints mwmhints = GetMWMHints(X11->display, q->internalWinId());
-
- if (data.window_modality != Qt::NonModal) {
- switch (data.window_modality) {
- case Qt::WindowModal:
- mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
- break;
- case Qt::ApplicationModal:
- default:
- mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
- break;
- }
- mwmhints.flags |= MWM_HINTS_INPUT_MODE;
- } else {
- mwmhints.input_mode = MWM_INPUT_MODELESS;
- mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
- }
-
- if (q->minimumSize() == q->maximumSize()) {
- // fixed size, remove the resize handle (since mwm/dtwm
- // isn't smart enough to do it itself)
- mwmhints.flags |= MWM_HINTS_FUNCTIONS;
- if (mwmhints.functions == MWM_FUNC_ALL) {
- mwmhints.functions = MWM_FUNC_MOVE;
- } else {
- mwmhints.functions &= ~MWM_FUNC_RESIZE;
- }
-
- if (mwmhints.decorations == MWM_DECOR_ALL) {
- mwmhints.flags |= MWM_HINTS_DECORATIONS;
- mwmhints.decorations = (MWM_DECOR_BORDER
- | MWM_DECOR_TITLE
- | MWM_DECOR_MENU);
- } else {
- mwmhints.decorations &= ~MWM_DECOR_RESIZEH;
- }
-
- if (q->windowFlags() & Qt::WindowMinimizeButtonHint) {
- mwmhints.flags |= MWM_HINTS_DECORATIONS;
- mwmhints.decorations |= MWM_DECOR_MINIMIZE;
- mwmhints.functions |= MWM_FUNC_MINIMIZE;
- }
- if (q->windowFlags() & Qt::WindowMaximizeButtonHint) {
- mwmhints.flags |= MWM_HINTS_DECORATIONS;
- mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
- mwmhints.functions |= MWM_FUNC_MAXIMIZE;
- }
- if (q->windowFlags() & Qt::WindowCloseButtonHint)
- mwmhints.functions |= MWM_FUNC_CLOSE;
- }
-
- SetMWMHints(X11->display, q->internalWinId(), mwmhints);
-
- // update _NET_WM_STATE
- QVector<Atom> netWmState = getNetWmState(q);
-
- Qt::WindowFlags flags = q->windowFlags();
- if (flags & Qt::WindowStaysOnTopHint) {
- if (flags & Qt::WindowStaysOnBottomHint)
- qWarning() << "QWidget: Incompatible window flags: the window can't be on top and on bottom at the same time";
- if (!netWmState.contains(ATOM(_NET_WM_STATE_ABOVE)))
- netWmState.append(ATOM(_NET_WM_STATE_ABOVE));
- if (!netWmState.contains(ATOM(_NET_WM_STATE_STAYS_ON_TOP)))
- netWmState.append(ATOM(_NET_WM_STATE_STAYS_ON_TOP));
- } else if (flags & Qt::WindowStaysOnBottomHint) {
- if (!netWmState.contains(ATOM(_NET_WM_STATE_BELOW)))
- netWmState.append(ATOM(_NET_WM_STATE_BELOW));
- }
- if (q->isFullScreen()) {
- if (!netWmState.contains(ATOM(_NET_WM_STATE_FULLSCREEN)))
- netWmState.append(ATOM(_NET_WM_STATE_FULLSCREEN));
- }
- if (q->isMaximized()) {
- if (!netWmState.contains(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ)))
- netWmState.append(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ));
- if (!netWmState.contains(ATOM(_NET_WM_STATE_MAXIMIZED_VERT)))
- netWmState.append(ATOM(_NET_WM_STATE_MAXIMIZED_VERT));
- }
- if (data.window_modality != Qt::NonModal) {
- if (!netWmState.contains(ATOM(_NET_WM_STATE_MODAL)))
- netWmState.append(ATOM(_NET_WM_STATE_MODAL));
- }
-
- if (!netWmState.isEmpty()) {
- XChangeProperty(X11->display, q->internalWinId(),
- ATOM(_NET_WM_STATE), XA_ATOM, 32, PropModeReplace,
- (unsigned char *) netWmState.data(), netWmState.size());
- } else {
- XDeleteProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_STATE));
- }
-
- // set _NET_WM_USER_TIME
- Time userTime = X11->userTime;
- bool setUserTime = false;
- if (q->testAttribute(Qt::WA_ShowWithoutActivating)) {
- userTime = 0;
- setUserTime = true;
- } else if (userTime != CurrentTime) {
- setUserTime = true;
- }
- if (setUserTime)
- qt_net_update_user_time(q, userTime);
-
-#ifndef QT_NO_XSYNC
- if (!topData()->syncUpdateCounter) {
- XSyncValue value;
- XSyncIntToValue(&value, 0);
- topData()->syncUpdateCounter = XSyncCreateCounter(X11->display, value);
-
- XChangeProperty(X11->display, q->internalWinId(),
- ATOM(_NET_WM_SYNC_REQUEST_COUNTER),
- XA_CARDINAL,
- 32, PropModeReplace,
- (uchar *) &topData()->syncUpdateCounter, 1);
-
- topData()->newCounterValueHi = 0;
- topData()->newCounterValueLo = 0;
- }
-#endif
-
- if (!topData()->embedded
- && (topData()->validWMState || topData()->waitingForMapNotify)
- && !q->isMinimized()) {
- X11->deferred_map.append(q);
- return;
- }
-
- if (q->isMaximized() && !q->isFullScreen()
- && !(X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ))
- && X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_VERT)))) {
- XMapWindow(X11->display, q->internalWinId());
- data.fstrut_dirty = true;
- qt_x11_wait_for_window_manager(q);
-
- // if the wm was not smart enough to adjust our size, do that manually
- QRect maxRect = QApplication::desktop()->availableGeometry(q);
-
- QTLWExtra *top = topData();
- QRect normalRect = top->normalGeometry;
- const QRect fs = frameStrut();
-
- q->setGeometry(maxRect.x() + fs.left(),
- maxRect.y() + fs.top(),
- maxRect.width() - fs.left() - fs.right(),
- maxRect.height() - fs.top() - fs.bottom());
-
- // restore the original normalGeometry
- top->normalGeometry = normalRect;
- // internalSetGeometry() clears the maximized flag... make sure we set it back
- data.window_state = data.window_state | Qt::WindowMaximized;
- q->setAttribute(Qt::WA_Mapped);
- return;
- }
-
- if (q->isFullScreen() && !X11->isSupportedByWM(ATOM(_NET_WM_STATE_FULLSCREEN))) {
- XMapWindow(X11->display, q->internalWinId());
- qt_x11_wait_for_window_manager(q);
- q->setAttribute(Qt::WA_Mapped);
- return;
- }
- }
-
- invalidateBuffer(q->rect());
-
- if (q->testAttribute(Qt::WA_OutsideWSRange))
- return;
- q->setAttribute(Qt::WA_Mapped);
- if (q->isWindow())
- topData()->waitingForMapNotify = 1;
-
- if (!q->isWindow()
- && (!q->autoFillBackground()
- || q->palette().brush(q->backgroundRole()).style() == Qt::LinearGradientPattern)) {
- if (q->internalWinId()) {
- XSetWindowBackgroundPixmap(X11->display, q->internalWinId(), XNone);
- XMapWindow(X11->display, q->internalWinId());
- updateSystemBackground();
- }
- return;
- }
-
- if (q->internalWinId())
- XMapWindow(X11->display, q->internalWinId());
-
- // Freedesktop.org Startup Notification
- if (X11->startupId && q->isWindow()) {
- QByteArray message("remove: ID=");
- message.append(X11->startupId);
- sendStartupMessage(message.constData());
- X11->startupId = 0;
- }
-}
-
-/*!
- \internal
- Platform-specific part of QWidget::show().
-*/
-
-void QWidgetPrivate::sendStartupMessage(const char *message) const
-{
- Q_Q(const QWidget);
-
- if (!message)
- return;
-
- XEvent xevent;
- xevent.xclient.type = ClientMessage;
- xevent.xclient.message_type = ATOM(_NET_STARTUP_INFO_BEGIN);
- xevent.xclient.display = X11->display;
- xevent.xclient.window = q->internalWinId();
- xevent.xclient.format = 8;
-
- Window rootWindow = RootWindow(X11->display, DefaultScreen(X11->display));
- uint sent = 0;
- uint length = strlen(message) + 1;
- do {
- if (sent == 20)
- xevent.xclient.message_type = ATOM(_NET_STARTUP_INFO);
-
- for (uint i = 0; i < 20 && i + sent <= length; i++)
- xevent.xclient.data.b[i] = message[i + sent++];
-
- XSendEvent(X11->display, rootWindow, false, PropertyChangeMask, &xevent);
- } while (sent <= length);
-}
-
-void QWidgetPrivate::setNetWmWindowTypes()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- if (!q->isWindow()) {
- if (q->internalWinId())
- XDeleteProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_WINDOW_TYPE));
- return;
- }
-
- QVector<long> windowTypes;
-
- // manual selection 1 (these are never set by Qt and take precedence)
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDesktop))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_DESKTOP));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDock))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_DOCK));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeNotification))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_NOTIFICATION));
-
- // manual selection 2 (Qt uses these during auto selection);
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeUtility))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_UTILITY));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeSplash))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_SPLASH));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDialog))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_DIALOG));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeToolTip))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_TOOLTIP));
-
- // manual selection 3 (these can be set by Qt, but don't have a
- // corresponding Qt::WindowType). note that order of the *MENU
- // atoms is important
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeMenu))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_MENU));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDropDownMenu))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_DROPDOWN_MENU));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypePopupMenu))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_POPUP_MENU));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeToolBar))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeCombo))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_COMBO));
- if (q->testAttribute(Qt::WA_X11NetWmWindowTypeDND))
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_DND));
-
- // automatic selection
- switch (q->windowType()) {
- case Qt::Dialog:
- case Qt::Sheet:
- // dialog netwm type
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_DIALOG));
- break;
-
- case Qt::Tool:
- case Qt::Drawer:
- // utility netwm type
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_UTILITY));
- break;
-
- case Qt::ToolTip:
- // tooltip netwm type
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_TOOLTIP));
- break;
-
- case Qt::SplashScreen:
- // splash netwm type
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_SPLASH));
- break;
-
- default:
- break;
- }
-
- if (q->windowFlags() & Qt::FramelessWindowHint) {
- // override netwm type - quick and easy for KDE noborder
- windowTypes.append(ATOM(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE));
- }
-
- // normal netwm type - default
- windowTypes.append(ATOM(_NET_WM_WINDOW_TYPE_NORMAL));
-
- if (!windowTypes.isEmpty()) {
- XChangeProperty(X11->display, q->winId(), ATOM(_NET_WM_WINDOW_TYPE), XA_ATOM, 32,
- PropModeReplace, (unsigned char *) windowTypes.constData(),
- windowTypes.count());
- } else {
- XDeleteProperty(X11->display, q->winId(), ATOM(_NET_WM_WINDOW_TYPE));
- }
-}
-
-/*!
- \internal
- Platform-specific part of QWidget::hide().
-*/
-
-void QWidgetPrivate::hide_sys()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- deactivateWidgetCleanup();
- if (q->isWindow()) {
- X11->deferred_map.removeAll(q);
- if (q->internalWinId()) // in nsplugin, may be 0
- XWithdrawWindow(X11->display, q->internalWinId(), xinfo.screen());
- XFlush(X11->display);
- } else {
- invalidateBuffer(q->rect());
- if (q->internalWinId()) // in nsplugin, may be 0
- XUnmapWindow(X11->display, q->internalWinId());
- }
- q->setAttribute(Qt::WA_Mapped, false);
-}
-
-void QWidgetPrivate::setFocus_sys()
-{
-
-}
-
-
-void QWidgetPrivate::raise_sys()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId())
- XRaiseWindow(X11->display, q->internalWinId());
-}
-
-void QWidgetPrivate::lower_sys()
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId())
- XLowerWindow(X11->display, q->internalWinId());
- if(!q->isWindow())
- invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget* w)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- if (q->internalWinId() && w->internalWinId()) {
- Window stack[2];
- stack[0] = w->internalWinId();;
- stack[1] = q->internalWinId();
- XRestackWindows(X11->display, stack, 2);
- }
- if(!q->isWindow() || !w->internalWinId())
- invalidateBuffer(q->rect());
-}
-
-
-static void do_size_hints(QWidget* widget, QWExtra *x)
-{
- Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
- XSizeHints s;
- s.flags = 0;
- if (x) {
- QRect g = widget->geometry();
- s.x = g.x();
- s.y = g.y();
- s.width = g.width();
- s.height = g.height();
- if (x->minw > 0 || x->minh > 0) {
- // add minimum size hints
- s.flags |= PMinSize;
- s.min_width = qMin(XCOORD_MAX, x->minw);
- s.min_height = qMin(XCOORD_MAX, x->minh);
- }
- if (x->maxw < QWIDGETSIZE_MAX || x->maxh < QWIDGETSIZE_MAX) {
- // add maximum size hints
- s.flags |= PMaxSize;
- s.max_width = qMin(XCOORD_MAX, x->maxw);
- s.max_height = qMin(XCOORD_MAX, x->maxh);
- }
- if (x->topextra &&
- (x->topextra->incw > 0 || x->topextra->inch > 0)) {
- // add resize increment hints
- s.flags |= PResizeInc | PBaseSize;
- s.width_inc = x->topextra->incw;
- s.height_inc = x->topextra->inch;
- s.base_width = x->topextra->basew;
- s.base_height = x->topextra->baseh;
- }
- }
- if (widget->testAttribute(Qt::WA_Moved)) {
- // user (i.e. command-line) specified position
- s.flags |= USPosition;
- s.flags |= PPosition;
- }
- if (widget->testAttribute(Qt::WA_Resized)) {
- // user (i.e. command-line) specified size
- s.flags |= USSize;
- s.flags |= PSize;
- }
- s.flags |= PWinGravity;
- if (widget->testAttribute(Qt::WA_Moved) && x && x->topextra && !x->topextra->posFromMove) {
- // position came from setGeometry(), tell the WM that we don't
- // want our window gravity-shifted
- s.win_gravity = StaticGravity;
- } else {
- // position came from move()
- s.x = widget->x();
- s.y = widget->y();
- s.win_gravity = QApplication::isRightToLeft() ? NorthEastGravity : NorthWestGravity;
- }
- if (widget->internalWinId())
- XSetWMNormalHints(X11->display, widget->internalWinId(), &s);
-}
-
-
-/*
- Helper function for non-toplevel widgets. Helps to map Qt's 32bit
- coordinate system to X11's 16bit coordinate system.
-
- Sets the geometry of the widget to data.crect, but clipped to sizes
- that X can handle. Unmaps widgets that are completely outside the
- valid range.
-
- Maintains data.wrect, which is the geometry of the X widget,
- measured in this widget's coordinate system.
-
- if the parent is not clipped, parentWRect is empty, otherwise
- parentWRect is the geometry of the parent's X rect, measured in
- parent's coord sys
- */
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
- /*
- There are up to four different coordinate systems here:
- Qt coordinate system for this widget.
- X coordinate system for this widget (relative to wrect).
- Qt coordinate system for parent
- X coordinate system for parent (relative to parent's wrect).
- */
- Display *dpy = xinfo.display();
- QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
- QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
- QRect wrect;
- //xrect is the X geometry of my X widget. (starts out in parent's Qt coord sys, and ends up in parent's X coord sys)
- QRect xrect = data.crect;
-
- const QWidget *const parent = q->parentWidget();
- QRect parentWRect = parent->data->wrect;
-
- if (parentWRect.isValid()) {
- // parent is clipped, and we have to clip to the same limit as parent
- if (!parentWRect.contains(xrect)) {
- xrect &= parentWRect;
- wrect = xrect;
- //translate from parent's to my Qt coord sys
- wrect.translate(-data.crect.topLeft());
- }
- //translate from parent's Qt coords to parent's X coords
- xrect.translate(-parentWRect.topLeft());
-
- } else {
- // parent is not clipped, we may or may not have to clip
-
- if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
- // This is where the main optimization is: we are already
- // clipped, and if our clip is still valid, we can just
- // move our window, and do not need to move or clip
- // children
-
- QRect vrect = xrect & parent->rect();
- vrect.translate(-data.crect.topLeft()); //the part of me that's visible through parent, in my Qt coords
- if (data.wrect.contains(vrect)) {
- xrect = data.wrect;
- xrect.translate(data.crect.topLeft());
- if (data.winid)
- XMoveWindow(dpy, data.winid, xrect.x(), xrect.y());
- return;
- }
- }
-
- if (!validRange.contains(xrect)) {
- // we are too big, and must clip
- xrect &=wrectRange;
- wrect = xrect;
- wrect.translate(-data.crect.topLeft());
- //parent's X coord system is equal to parent's Qt coord
- //sys, so we don't need to map xrect.
- }
-
- }
-
- // unmap if we are outside the valid window system coord system
- bool outsideRange = !xrect.isValid();
- bool mapWindow = false;
- if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
- q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
- if (outsideRange) {
- if (data.winid)
- XUnmapWindow(dpy, data.winid);
- q->setAttribute(Qt::WA_Mapped, false);
- } else if (!q->isHidden()) {
- mapWindow = true;
- }
- }
-
- if (outsideRange)
- return;
-
- bool jump = (data.wrect != wrect);
- data.wrect = wrect;
-
-
- // and now recursively for all children...
- // ### can be optimized
- for (int i = 0; i < children.size(); ++i) {
- QObject *object = children.at(i);
- if (object->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(object);
- if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
- w->d_func()->setWSGeometry(jump);
- }
- }
-
- if (data.winid) {
- // move ourselves to the new position and map (if necessary) after
- // the movement. Rationale: moving unmapped windows is much faster
- // than moving mapped windows
- if (jump) //avoid flicker when jumping
- XSetWindowBackgroundPixmap(dpy, data.winid, XNone);
- if (!parent->internalWinId())
- xrect.translate(parent->mapTo(q->nativeParentWidget(), QPoint(0, 0)));
- XMoveResizeWindow(dpy, data.winid, xrect.x(), xrect.y(), xrect.width(), xrect.height());
- }
-
- //to avoid flicker, we have to show children after the helper widget has moved
- if (jump) {
- for (int i = 0; i < children.size(); ++i) {
- QObject *object = children.at(i);
- if (object->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(object);
- if (!w->testAttribute(Qt::WA_OutsideWSRange) && !w->testAttribute(Qt::WA_Mapped) && !w->isHidden()) {
- w->setAttribute(Qt::WA_Mapped);
- if (w->internalWinId())
- XMapWindow(dpy, w->data->winid);
- }
- }
- }
- }
-
-
- if (jump && data.winid)
- XClearArea(dpy, data.winid, 0, 0, wrect.width(), wrect.height(), True);
-
- if (mapWindow && !dontShow) {
- q->setAttribute(Qt::WA_Mapped);
- if (data.winid)
- XMapWindow(dpy, data.winid);
- }
-}
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
- Q_Q(QWidget);
- Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
- Display *dpy = X11->display;
-
- if ((q->windowType() == Qt::Desktop))
- return;
- if (q->isWindow()) {
- if (!X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_VERT))
- && !X11->isSupportedByWM(ATOM(_NET_WM_STATE_MAXIMIZED_HORZ)))
- data.window_state &= ~Qt::WindowMaximized;
- if (!X11->isSupportedByWM(ATOM(_NET_WM_STATE_FULLSCREEN)))
- data.window_state &= ~Qt::WindowFullScreen;
- if (QTLWExtra *topData = maybeTopData())
- topData->normalGeometry = QRect(0,0,-1,-1);
- } else {
- uint s = data.window_state;
- s &= ~(Qt::WindowMaximized | Qt::WindowFullScreen);
- data.window_state = s;
- }
- if (extra) { // any size restrictions?
- w = qMin(w,extra->maxw);
- h = qMin(h,extra->maxh);
- w = qMax(w,extra->minw);
- h = qMax(h,extra->minh);
- }
- QPoint oldPos(q->pos());
- QSize oldSize(q->size());
- QRect oldGeom(data.crect);
- QRect r(x, y, w, h);
-
- // We only care about stuff that changes the geometry, or may
- // cause the window manager to change its state
- if (!q->isWindow() && oldGeom == r)
- return;
-
- data.crect = r;
- bool isResize = q->size() != oldSize;
-
- if (q->isWindow()) {
- if (w == 0 || h == 0) {
- q->setAttribute(Qt::WA_OutsideWSRange, true);
- if (q->isVisible() && q->testAttribute(Qt::WA_Mapped))
- hide_sys();
- } else if (q->isVisible() && q->testAttribute(Qt::WA_OutsideWSRange)) {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
-
- // put the window in its place and show it
- if (data.winid)
- XMoveResizeWindow(dpy, data.winid, x, y, w, h);
- topData()->posFromMove = false; // force StaticGravity
- do_size_hints(q, extra);
- show_sys();
- } else {
- q->setAttribute(Qt::WA_OutsideWSRange, false);
- if (!q->isVisible())
- do_size_hints(q, extra);
- if (isMove) {
- if ((data.window_flags & Qt::X11BypassWindowManagerHint) == Qt::X11BypassWindowManagerHint
- // work around 4Dwm's incompliance with ICCCM 4.1.5
- || X11->desktopEnvironment == DE_4DWM) {
- if (data.winid)
- XMoveResizeWindow(dpy, data.winid, x, y, w, h);
- } else if (q->isVisible()
- && topData()->validWMState
- && X11->isSupportedByWM(ATOM(_NET_MOVERESIZE_WINDOW))) {
- XEvent e;
- e.xclient.type = ClientMessage;
- e.xclient.message_type = ATOM(_NET_MOVERESIZE_WINDOW);
- e.xclient.display = X11->display;
- e.xclient.window = q->internalWinId();
- e.xclient.format = 32;
- e.xclient.data.l[0] = StaticGravity | 1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12;
- e.xclient.data.l[1] = x;
- e.xclient.data.l[2] = y;
- e.xclient.data.l[3] = w;
- e.xclient.data.l[4] = h;
- XSendEvent(X11->display, RootWindow(X11->display, q->x11Info().screen()),
- false, (SubstructureNotifyMask | SubstructureRedirectMask), &e);
- } else if (data.winid) {
- // pos() is right according to ICCCM 4.1.5
- XMoveResizeWindow(dpy, data.winid, q->pos().x(), q->pos().y(), w, h);
- }
- } else if (isResize && data.winid) {
- if (!q->isVisible()
- && topData()->validWMState
- && !q->testAttribute(Qt::WA_PendingMoveEvent)) {
- /*
- even though we've not visible, we could be in a
- race w/ the window manager, and it may ignore
- our ConfigureRequest. setting posFromMove to
- false makes sure that doDeferredMap() in
- qapplication_x11.cpp keeps the window in the
- right place
- */
- topData()->posFromMove = false;
- }
- XResizeWindow(dpy, data.winid, w, h);
- }
- }
- if (isResize && !q->testAttribute(Qt::WA_DontShowOnScreen)) // set config pending only on resize, see qapplication_x11.cpp, translateConfigEvent()
- q->setAttribute(Qt::WA_WState_ConfigPending);
-
- } else {
- QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- const bool inTopLevelResize = tlwExtra ? tlwExtra->inTopLevelResize : false;
- const bool disableInTopLevelResize = inTopLevelResize && q->internalWinId();
- if (disableInTopLevelResize) {
- // Top-level resize optimization does not work for native child widgets;
- // disable it for this particular widget.
- tlwExtra->inTopLevelResize = false;
- }
-
- if (!isResize && (!inTopLevelResize || disableInTopLevelResize) && q->isVisible()) {
- moveRect(QRect(oldPos, oldSize), x - oldPos.x(), y - oldPos.y());
- }
- if (q->testAttribute(Qt::WA_WState_Created))
- setWSGeometry();
-
- if (isResize && (!inTopLevelResize || disableInTopLevelResize) && q->isVisible())
- invalidateBuffer_resizeHelper(oldPos, oldSize);
-
- if (disableInTopLevelResize)
- tlwExtra->inTopLevelResize = true;
- }
-
- if (q->isVisible()) {
- if (isMove && q->pos() != oldPos) {
- if (X11->desktopEnvironment != DE_4DWM) {
- // pos() is right according to ICCCM 4.1.5
- QMoveEvent e(q->pos(), oldPos);
- QApplication::sendEvent(q, &e);
- } else {
- // work around 4Dwm's incompliance with ICCCM 4.1.5
- QMoveEvent e(data.crect.topLeft(), oldGeom.topLeft());
- QApplication::sendEvent(q, &e);
- }
- }
- if (isResize) {
- static bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
- // If we have a backing store with static contents, we have to disable the top-level
- // resize optimization in order to get invalidated regions for resized widgets.
- // The optimization discards all invalidateBuffer() calls since we're going to
- // repaint everything anyways, but that's not the case with static contents.
- const bool setTopLevelResize = !slowResize && q->isWindow() && extra && extra->topextra
- && !extra->topextra->inTopLevelResize
- && (!extra->topextra->backingStore
- || !extra->topextra->backingStore->hasStaticContents());
- if (setTopLevelResize)
- extra->topextra->inTopLevelResize = true;
- QResizeEvent e(q->size(), oldSize);
- QApplication::sendEvent(q, &e);
- if (setTopLevelResize)
- extra->topextra->inTopLevelResize = false;
- }
- } else {
- if (isMove && q->pos() != oldPos)
- q->setAttribute(Qt::WA_PendingMoveEvent, true);
- if (isResize)
- q->setAttribute(Qt::WA_PendingResizeEvent, true);
- }
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
- Q_Q(QWidget);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::setConstraints_sys START" << q;
-#endif
- if (q->testAttribute(Qt::WA_WState_Created))
- do_size_hints(q, extra);
-#ifdef ALIEN_DEBUG
- qDebug() << "QWidgetPrivate::setConstraints_sys END" << q;
-#endif
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
- Q_Q(QWidget);
-
- scrollChildren(dx, dy);
- if (!paintOnScreen()) {
- scrollRect(q->rect(), dx, dy);
- } else {
- scroll_sys(dx, dy, QRect());
- }
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
-{
- Q_Q(QWidget);
-
- if (!paintOnScreen()) {
- scrollRect(r, dx, dy);
- return;
- }
- bool valid_rect = r.isValid();
- bool just_update = qAbs(dx) > q->width() || qAbs(dy) > q->height();
- QRect sr = valid_rect ? r : clipRect();
- if (just_update)
- q->update();
- else if (!valid_rect)
- dirty.translate(dx, dy);
-
- int x1, y1, x2, y2, w = sr.width(), h = sr.height();
- if (dx > 0) {
- x1 = sr.x();
- x2 = x1+dx;
- w -= dx;
- } else {
- x2 = sr.x();
- x1 = x2-dx;
- w += dx;
- }
- if (dy > 0) {
- y1 = sr.y();
- y2 = y1+dy;
- h -= dy;
- } else {
- y2 = sr.y();
- y1 = y2-dy;
- h += dy;
- }
-
- if (dx == 0 && dy == 0)
- return;
-
- Display *dpy = X11->display;
- // Want expose events
- if (w > 0 && h > 0 && !just_update && q->internalWinId()) {
- GC gc = XCreateGC(dpy, q->internalWinId(), 0, 0);
- XSetGraphicsExposures(dpy, gc, True);
- XCopyArea(dpy, q->internalWinId(), q->internalWinId(), gc, x1, y1, w, h, x2, y2);
- XFreeGC(dpy, gc);
- }
-
- if (!valid_rect && !children.isEmpty()) { // scroll children
- QPoint pd(dx, dy);
- for (int i = 0; i < children.size(); ++i) { // move all children
- register QObject *object = children.at(i);
- if (object->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(object);
- if (!w->isWindow())
- w->move(w->pos() + pd);
- }
- }
- }
-
- if (just_update)
- return;
-
- // Don't let the server be bogged-down with repaint events
- bool repaint_immediately = (qt_sip_count(q) < 3 && !q->testAttribute(Qt::WA_WState_InPaintEvent));
-
- if (dx) {
- int x = x2 == sr.x() ? sr.x()+w : sr.x();
- if (repaint_immediately)
- q->repaint(x, sr.y(), qAbs(dx), sr.height());
- else if (q->internalWinId())
- XClearArea(dpy, data.winid, x, sr.y(), qAbs(dx), sr.height(), True);
- }
- if (dy) {
- int y = y2 == sr.y() ? sr.y()+h : sr.y();
- if (repaint_immediately)
- q->repaint(sr.x(), y, sr.width(), qAbs(dy));
- else if (q->internalWinId())
- XClearArea(dpy, data.winid, sr.x(), y, sr.width(), qAbs(dy), True);
- }
-
- qt_insert_sip(q, dx, dy); // #### ignores r
-}
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
- Q_D(const QWidget);
- int val;
- if (m == PdmWidth) {
- val = data->crect.width();
- } else if (m == PdmHeight) {
- val = data->crect.height();
- } else {
- Display *dpy = X11->display;
- int scr = d->xinfo.screen();
- switch (m) {
- case PdmDpiX:
- case PdmPhysicalDpiX:
- if (d->extra && d->extra->customDpiX)
- val = d->extra->customDpiX;
- else if (d->parent)
- val = static_cast<QWidget *>(d->parent)->metric(m);
- else
- val = QX11Info::appDpiX(scr);
- break;
- case PdmDpiY:
- case PdmPhysicalDpiY:
- if (d->extra && d->extra->customDpiY)
- val = d->extra->customDpiY;
- else if (d->parent)
- val = static_cast<QWidget *>(d->parent)->metric(m);
- else
- val = QX11Info::appDpiY(scr);
- break;
- case PdmWidthMM:
- val = (DisplayWidthMM(dpy,scr)*data->crect.width())/
- DisplayWidth(dpy,scr);
- break;
- case PdmHeightMM:
- val = (DisplayHeightMM(dpy,scr)*data->crect.height())/
- DisplayHeight(dpy,scr);
- break;
- case PdmNumColors:
- val = d->xinfo.cells();
- break;
- case PdmDepth:
- val = d->xinfo.depth();
- break;
- default:
- val = 0;
- qWarning("QWidget::metric: Invalid metric command");
- }
- }
- return val;
-}
-
-void QWidgetPrivate::createSysExtra()
-{
- extra->compress_events = true;
- extra->xDndProxy = 0;
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
-}
-
-void QWidgetPrivate::createTLSysExtra()
-{
- extra->topextra->spont_unmapped = 0;
- extra->topextra->dnd = 0;
- extra->topextra->validWMState = 0;
- extra->topextra->waitingForMapNotify = 0;
- extra->topextra->parentWinId = 0;
- extra->topextra->userTimeWindow = 0;
-#ifndef QT_NO_XSYNC
- extra->topextra->syncUpdateCounter = 0;
- extra->topextra->syncRequestTimestamp = 0;
- extra->topextra->newCounterValueHi = 0;
- extra->topextra->newCounterValueLo = 0;
-#endif
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
- // don't destroy input context here. it will be destroyed in
- // QWidget::destroy() destroyInputContext();
-}
-
-void QWidgetPrivate::registerDropSite(bool on)
-{
- Q_UNUSED(on);
-}
-
-void QWidgetPrivate::setMask_sys(const QRegion &region)
-{
- Q_Q(QWidget);
- if (!q->internalWinId())
- return;
-
- if (region.isEmpty()) {
- XShapeCombineMask(X11->display, q->internalWinId(), ShapeBounding, 0, 0,
- XNone, ShapeSet);
- } else {
- XShapeCombineRegion(X11->display, q->internalWinId(), ShapeBounding, 0, 0,
- region.handle(), ShapeSet);
- }
-}
-
-/*!
- \internal
-
- Computes the frame rectangle when needed. This is an internal function, you
- should never call this.
-*/
-
-void QWidgetPrivate::updateFrameStrut()
-{
- Q_Q(QWidget);
-
- QTLWExtra *top = topData();
- if (!top->validWMState) {
- return;
- }
- if (!q->isWindow() && !q->internalWinId()) {
- data.fstrut_dirty = false;
- return;
- }
-
- Atom type_ret;
- Window l = q->effectiveWinId(), w = l, p, r; // target window, its parent, root
- Window *c;
- int i_unused;
- unsigned int nc;
- unsigned char *data_ret;
- unsigned long l_unused;
-
- while (XQueryTree(X11->display, w, &r, &p, &c, &nc)) {
- if (c && nc > 0)
- XFree(c);
-
- if (! p) {
- qWarning("QWidget::updateFrameStrut: No parent");
- return;
- }
-
- // if the parent window is the root window, an Enlightenment virtual root or
- // a NET WM virtual root window, stop here
- data_ret = 0;
- if (p == r ||
- (XGetWindowProperty(X11->display, p,
- ATOM(ENLIGHTENMENT_DESKTOP), 0, 1, False, XA_CARDINAL,
- &type_ret, &i_unused, &l_unused, &l_unused,
- &data_ret) == Success &&
- type_ret == XA_CARDINAL)) {
- if (data_ret)
- XFree(data_ret);
-
- break;
- } else if (X11->isSupportedByWM(ATOM(_NET_VIRTUAL_ROOTS)) && X11->net_virtual_root_list) {
- int i = 0;
- while (X11->net_virtual_root_list[i] != 0) {
- if (X11->net_virtual_root_list[i++] == p)
- break;
- }
- }
-
- l = w;
- w = p;
- }
-
- // we have our window
- int transx, transy;
- XWindowAttributes wattr;
- if (XTranslateCoordinates(X11->display, l, w,
- 0, 0, &transx, &transy, &p) &&
- XGetWindowAttributes(X11->display, w, &wattr)) {
- top->frameStrut.setCoords(transx,
- transy,
- wattr.width - data.crect.width() - transx,
- wattr.height - data.crect.height() - transy);
-
- // add the border_width for the window managers frame... some window managers
- // do not use a border_width of zero for their frames, and if we the left and
- // top strut, we ensure that pos() is absolutely correct. frameGeometry()
- // will still be incorrect though... perhaps i should have foffset as well, to
- // indicate the frame offset (equal to the border_width on X).
- // - Brad
- top->frameStrut.adjust(wattr.border_width,
- wattr.border_width,
- wattr.border_width,
- wattr.border_width);
- }
-
- data.fstrut_dirty = false;
-}
-
-void QWidgetPrivate::setWindowOpacity_sys(qreal opacity)
-{
- Q_Q(QWidget);
- ulong value = ulong(opacity * 0xffffffff);
- XChangeProperty(QX11Info::display(), q->internalWinId(), ATOM(_NET_WM_WINDOW_OPACITY), XA_CARDINAL,
- 32, PropModeReplace, (uchar*)&value, 1);
-}
-
-const QX11Info &QWidget::x11Info() const
-{
- Q_D(const QWidget);
- return d->xinfo;
-}
-
-void QWidgetPrivate::setWindowRole()
-{
- Q_Q(QWidget);
- if (!q->internalWinId())
- return;
- QByteArray windowRole = topData()->role.toUtf8();
- XChangeProperty(X11->display, q->internalWinId(),
- ATOM(WM_WINDOW_ROLE), XA_STRING, 8, PropModeReplace,
- (unsigned char *)windowRole.constData(), windowRole.length());
-}
-
-Q_GLOBAL_STATIC(QX11PaintEngine, qt_widget_paintengine)
-QPaintEngine *QWidget::paintEngine() const
-{
- Q_D(const QWidget);
- if (qt_widget_paintengine()->isActive()) {
- if (d->extraPaintEngine)
- return d->extraPaintEngine;
- QWidget *self = const_cast<QWidget *>(this);
- self->d_func()->extraPaintEngine = new QX11PaintEngine();
- return d->extraPaintEngine;
- }
- return qt_widget_paintengine();
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
- return new QX11WindowSurface(q_func());
-}
-
-Qt::HANDLE QWidget::x11PictureHandle() const
-{
-#ifndef QT_NO_XRENDER
- Q_D(const QWidget);
- if (!internalWinId() && testAttribute(Qt::WA_WState_Created))
- (void)winId(); // enforce native window
- return d->picture;
-#else
- return 0;
-#endif // QT_NO_XRENDER
-}
-
-#ifndef QT_NO_XRENDER
-XRenderColor QX11Data::preMultiply(const QColor &c)
-{
- XRenderColor color;
- const uint A = c.alpha(),
- R = c.red(),
- G = c.green(),
- B = c.blue();
- color.alpha = (A | A << 8);
- color.red = (R | R << 8) * color.alpha / 0x10000;
- color.green = (G | G << 8) * color.alpha / 0x10000;
- color.blue = (B | B << 8) * color.alpha / 0x10000;
- return color;
-}
-Picture QX11Data::getSolidFill(int screen, const QColor &c)
-{
- if (!X11->use_xrender)
- return XNone;
-
- XRenderColor color = preMultiply(c);
- for (int i = 0; i < X11->solid_fill_count; ++i) {
- if (X11->solid_fills[i].screen == screen
- && X11->solid_fills[i].color.alpha == color.alpha
- && X11->solid_fills[i].color.red == color.red
- && X11->solid_fills[i].color.green == color.green
- && X11->solid_fills[i].color.blue == color.blue)
- return X11->solid_fills[i].picture;
- }
- // none found, replace one
- int i = qrand() % 16;
-
- if (X11->solid_fills[i].screen != screen && X11->solid_fills[i].picture) {
- XRenderFreePicture (X11->display, X11->solid_fills[i].picture);
- X11->solid_fills[i].picture = 0;
- }
-
- if (!X11->solid_fills[i].picture) {
- Pixmap pixmap = XCreatePixmap (X11->display, RootWindow (X11->display, screen), 1, 1, 32);
- XRenderPictureAttributes attrs;
- attrs.repeat = True;
- X11->solid_fills[i].picture = XRenderCreatePicture (X11->display, pixmap,
- XRenderFindStandardFormat(X11->display, PictStandardARGB32),
- CPRepeat, &attrs);
- XFreePixmap (X11->display, pixmap);
- }
-
- X11->solid_fills[i].color = color;
- X11->solid_fills[i].screen = screen;
- XRenderFillRectangle (X11->display, PictOpSrc, X11->solid_fills[i].picture, &color, 0, 0, 1, 1);
- return X11->solid_fills[i].picture;
-}
-#endif
-
-void QWidgetPrivate::setModal_sys()
-{
-}
-
-void qt_x11_getX11InfoForWindow(QX11Info * xinfo, const QX11WindowAttributes &att)
-{
- QX11InfoData* xd = xinfo->getX11Data(true);
- const XWindowAttributes &a = *(att.att);
- // find which screen the window is on...
- xd->screen = QX11Info::appScreen(); // by default, use the default :)
- int i;
- for (i = 0; i < ScreenCount(X11->display); i++) {
- if (RootWindow(X11->display, i) == a.root) {
- xd->screen = i;
- break;
- }
- }
-
- xd->depth = a.depth;
- xd->cells = DisplayCells(X11->display, xd->screen);
- xd->visual = a.visual;
- xd->defaultVisual = (XVisualIDFromVisual((Visual *) a.visual) ==
- XVisualIDFromVisual((Visual *) QX11Info::appVisual(xinfo->screen())));
- xd->colormap = a.colormap;
- xd->defaultColormap = (a.colormap == QX11Info::appColormap(xinfo->screen()));
- xinfo->setX11Data(xd);
-}
-
-void QWidgetPrivate::updateX11AcceptFocus()
-{
- Q_Q(QWidget);
- if (!q->isWindow() || !q->internalWinId())
- return;
-
- XWMHints *h = XGetWMHints(X11->display, q->internalWinId());
- XWMHints wm_hints;
- if (!h) {
- memset(&wm_hints, 0, sizeof(wm_hints)); // make valgrind happy
- h = &wm_hints;
- }
- h->flags |= InputHint;
- h->input = q->testAttribute(Qt::WA_X11DoNotAcceptFocus) ? False : True;
-
- XSetWMHints(X11->display, q->internalWinId(), h);
- if (h != &wm_hints)
- XFree((char *)h);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qwidgetcreate_x11.cpp b/src/gui/platforms/x11/qwidgetcreate_x11.cpp
deleted file mode 100644
index 16bd6abf9a..0000000000
--- a/src/gui/platforms/x11/qwidgetcreate_x11.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwidget.h"
-#include "qt_x11_p.h"
-
-/*
- Internal Qt functions to create X windows. We have put them in
- separate functions to allow the programmer to reimplement them by
- custom versions.
-*/
-
-QT_BEGIN_NAMESPACE
-
-Window qt_XCreateWindow(const QWidget *, Display *display, Window parent,
- int x, int y, uint w, uint h,
- int borderwidth, int depth,
- uint windowclass, Visual *visual,
- ulong valuemask, XSetWindowAttributes *attributes)
-{
- return XCreateWindow(display, parent, x, y, w, h, borderwidth, depth,
- windowclass, visual, valuemask, attributes);
-}
-
-
-Window qt_XCreateSimpleWindow(const QWidget *, Display *display, Window parent,
- int x, int y, uint w, uint h, int borderwidth,
- ulong border, ulong background)
-{
- return XCreateSimpleWindow(display, parent, x, y, w, h, borderwidth,
- border, background);
-}
-
-
-void qt_XDestroyWindow(const QWidget *, Display *display, Window window)
-{
- if (window)
- XDestroyWindow(display, window);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qx11embed_x11.cpp b/src/gui/platforms/x11/qx11embed_x11.cpp
deleted file mode 100644
index 49a819469e..0000000000
--- a/src/gui/platforms/x11/qx11embed_x11.cpp
+++ /dev/null
@@ -1,1808 +0,0 @@
-/****************************************************************************
-**
-** 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 "qx11embed_x11.h"
-#include <qapplication.h>
-#include <qevent.h>
-#include <qpainter.h>
-#include <qlayout.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qelapsedtimer.h>
-#include <qpointer.h>
-#include <qdebug.h>
-#include <qx11info_x11.h>
-#include <private/qt_x11_p.h>
-#include <private/qwidget_p.h>
-
-#define XK_MISCELLANY
-#define XK_LATIN1
-#define None 0
-#include <X11/Xlib.h>
-#include <X11/Xatom.h>
-#include <X11/Xutil.h>
-#include <X11/keysymdef.h>
-#include <X11/X.h>
-
-#ifndef XK_ISO_Left_Tab
-#define XK_ISO_Left_Tab 0xFE20
-#endif
-
-//#define QX11EMBED_DEBUG
-#ifdef QX11EMBED_DEBUG
-#include <qdebug.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QX11EmbedWidget
- \ingroup advanced
-
- \brief The QX11EmbedWidget class provides an XEmbed client widget.
-
- XEmbed is an X11 protocol that supports the embedding of a widget
- from one application into another application.
-
- An XEmbed \e{client widget} is a window that is embedded into a
- \e container. A container is the graphical location that embeds
- (or \e swallows) an external application.
-
- QX11EmbedWidget is a widget used for writing XEmbed applets or
- plugins. When it has been embedded and the container receives tab
- focus, focus is passed on to the widget. When the widget reaches
- the end of its focus chain, focus is passed back to the
- container. Window activation, accelerator support, modality and
- drag and drop (XDND) are also handled.
-
- The widget and container can both initiate the embedding. If the
- widget is the initiator, the X11 window ID of the container that
- it wants to embed itself into must be passed to embedInto().
-
- If the container initiates the embedding, the window ID of the
- embedded widget must be known. The container calls embed(),
- passing the window ID.
-
- This example shows an application that embeds a QX11EmbedWidget
- subclass into the window whose ID is passed as a command-line
- argument:
-
- \snippet doc/src/snippets/qx11embedwidget/main.cpp 0
-
- The problem of obtaining the window IDs is often solved by the
- container invoking the application that provides the widget as a
- separate process (as a panel invokes a docked applet), passing
- its window ID to the new process as a command-line argument. The
- new process can then call embedInto() with the container's window
- ID, as shown in the example code above. Similarly, the new
- process can report its window ID to the container through IPC, in
- which case the container can embed the widget.
-
- When the widget has been embedded, it emits the signal
- embedded(). If it is closed by the container, the widget emits
- containerClosed(). If an error occurs when embedding, error() is
- emitted.
-
- There are XEmbed widgets available for KDE and GTK+. The GTK+
- equivalent of QX11EmbedWidget is GtkPlug. The corresponding KDE 3
- widget is called QXEmbed.
-
- \sa QX11EmbedContainer, {XEmbed Specification}
-*/
-
-/*!
- \class QX11EmbedContainer
- \ingroup advanced
-
- \brief The QX11EmbedContainer class provides an XEmbed container
- widget.
-
- XEmbed is an X11 protocol that supports the embedding of a widget
- from one application into another application.
-
- An XEmbed \e container is the graphical location that embeds an
- external \e {client widget}. A client widget is a window that is
- embedded into a container.
-
- When a widget has been embedded and the container receives tab
- focus, focus is passed on to the widget. When the widget reaches
- the end of its focus chain, focus is passed back to the
- container. Window activation, accelerator support, modality and
- drag and drop (XDND) are also handled.
-
- QX11EmbedContainer is commonly used for writing panels or
- toolbars that hold applets, or for \e swallowing X11
- applications. When writing a panel application, one container
- widget is created on the toolbar, and it can then either swallow
- another widget using embed(), or allow an XEmbed widget to be
- embedded into itself. The container's X11 window ID, which is
- retrieved with winId(), must then be known to the client widget.
- After embedding, the client's window ID can be retrieved with
- clientWinId().
-
- In the following example, a container widget is created as the
- main widget. It then invokes an application called "playmovie",
- passing its window ID as a command line argument. The "playmovie"
- program is an XEmbed client widget. The widget embeds itself into
- the container using the container's window ID.
-
- \snippet doc/src/snippets/qx11embedcontainer/main.cpp 0
-
- When the client widget is embedded, the container emits the
- signal clientIsEmbedded(). The signal clientClosed() is emitted
- when a widget is closed.
-
- It is possible for QX11EmbedContainer to embed XEmbed widgets
- from toolkits other than Qt, such as GTK+. Arbitrary (non-XEmbed)
- X11 widgets can also be embedded, but the XEmbed-specific
- features such as window activation and focus handling are then
- lost.
-
- The GTK+ equivalent of QX11EmbedContainer is GtkSocket. The
- corresponding KDE 3 widget is called QXEmbed.
-
- \sa QX11EmbedWidget, {XEmbed Specification}
-*/
-
-/*! \fn void QX11EmbedWidget::embedded()
-
- This signal is emitted by the widget that has been embedded by an
- XEmbed container.
-*/
-
-/*! \fn void QX11EmbedWidget::containerClosed()
-
- This signal is emitted by the client widget when the container
- closes the widget. This can happen if the container itself
- closes, or if the widget is rejected.
-
- The container can reject a widget for any reason, but the most
- common cause of a rejection is when an attempt is made to embed a
- widget into a container that already has an embedded widget.
-*/
-
-/*! \fn void QX11EmbedContainer::clientIsEmbedded()
-
- This signal is emitted by the container when a client widget has
- been embedded.
-*/
-
-/*! \fn void QX11EmbedContainer::clientClosed()
-
- This signal is emitted by the container when the client widget
- closes.
-*/
-
-/*!
- \fn void QX11EmbedWidget::error(QX11EmbedWidget::Error error)
-
- This signal is emitted if an error occurred as a result of
- embedding into or communicating with a container. The specified
- \a error describes the problem that occurred.
-
- \sa QX11EmbedWidget::Error
-*/
-
-/*!
- \fn QX11EmbedContainer::Error QX11EmbedContainer::error() const
-
- Returns the last error that occurred.
-*/
-
-/*! \fn void QX11EmbedContainer::error(QX11EmbedContainer::Error error)
-
- This signal is emitted if an error occurred when embedding or
- communicating with a client. The specified \a error describes the
- problem that occurred.
-
- \sa QX11EmbedContainer::Error
-*/
-
-/*!
- \enum QX11EmbedWidget::Error
-
- \value Unknown An unrecognized error occurred.
-
- \value InvalidWindowID The X11 window ID of the container was
- invalid. This error is usually triggered by passing an invalid
- window ID to embedInto().
-
- \omitvalue Internal
-*/
-
-/*!
- \enum QX11EmbedContainer::Error
-
- \value Unknown An unrecognized error occurred.
-
- \value InvalidWindowID The X11 window ID of the container was
- invalid. This error is usually triggered by passing an invalid
- window ID to embed().
-
- \omitvalue Internal
-*/
-
-const int XButtonPress = ButtonPress;
-const int XButtonRelease = ButtonRelease;
-#undef ButtonPress
-#undef ButtonRelease
-
-// This is a hack to move topData() out from QWidgetPrivate to public. We
-// need to to inspect window()'s embedded state.
-class QHackWidget : public QWidget
-{
- Q_DECLARE_PRIVATE(QWidget)
-public:
- QTLWExtra* topData() { return d_func()->topData(); }
-};
-
-static unsigned int XEMBED_VERSION = 0;
-
-enum QX11EmbedMessageType {
- XEMBED_EMBEDDED_NOTIFY = 0,
- XEMBED_WINDOW_ACTIVATE = 1,
- XEMBED_WINDOW_DEACTIVATE = 2,
- XEMBED_REQUEST_FOCUS = 3,
- XEMBED_FOCUS_IN = 4,
- XEMBED_FOCUS_OUT = 5,
- XEMBED_FOCUS_NEXT = 6,
- XEMBED_FOCUS_PREV = 7,
- XEMBED_MODALITY_ON = 10,
- XEMBED_MODALITY_OFF = 11,
- XEMBED_REGISTER_ACCELERATOR = 12,
- XEMBED_UNREGISTER_ACCELERATOR = 13,
- XEMBED_ACTIVATE_ACCELERATOR = 14
-};
-
-enum QX11EmbedFocusInDetail {
- XEMBED_FOCUS_CURRENT = 0,
- XEMBED_FOCUS_FIRST = 1,
- XEMBED_FOCUS_LAST = 2
-};
-
-enum QX11EmbedFocusInFlags {
- XEMBED_FOCUS_OTHER = (0 << 0),
- XEMBED_FOCUS_WRAPAROUND = (1 << 0)
-};
-
-enum QX11EmbedInfoFlags {
- XEMBED_MAPPED = (1 << 0)
-};
-
-enum QX11EmbedAccelModifiers {
- XEMBED_MODIFIER_SHIFT = (1 << 0),
- XEMBED_MODIFIER_CONTROL = (1 << 1),
- XEMBED_MODIFIER_ALT = (1 << 2),
- XEMBED_MODIFIER_SUPER = (1 << 3),
- XEMBED_MODIFIER_HYPER = (1 << 4)
-};
-
-enum QX11EmbedAccelFlags {
- XEMBED_ACCELERATOR_OVERLOADED = (1 << 0)
-};
-
-// Silence the default X11 error handler.
-static int x11ErrorHandler(Display *, XErrorEvent *)
-{
- return 0;
-}
-
-// Returns the X11 timestamp. Maintained mainly by qapplication
-// internals, but also updated by the XEmbed widgets.
-static Time x11Time()
-{
- return qt_x11Data->time;
-}
-
-// Gives the version and flags of the supported XEmbed protocol.
-static unsigned int XEmbedVersion()
-{
- return 0;
-}
-
-// Sends an XEmbed message.
-static void sendXEmbedMessage(WId window, Display *display, long message,
- long detail = 0, long data1 = 0, long data2 = 0)
-{
- XClientMessageEvent c;
- memset(&c, 0, sizeof(c));
- c.type = ClientMessage;
- c.message_type = ATOM(_XEMBED);
- c.format = 32;
- c.display = display;
- c.window = window;
-
- c.data.l[0] = x11Time();
- c.data.l[1] = message;
- c.data.l[2] = detail;
- c.data.l[3] = data1;
- c.data.l[4] = data2;
-
- XSendEvent(display, window, false, NoEventMask, (XEvent *) &c);
-}
-
-// From qapplication_x11.cpp
-static XKeyEvent lastKeyEvent;
-
-static QCoreApplication::EventFilter oldX11EventFilter;
-
-// The purpose of this global x11 filter is for one to capture the key
-// events in their original state, but most importantly this is the
-// only way to get the WM_TAKE_FOCUS message from WM_PROTOCOLS.
-static bool x11EventFilter(void *message, long *result)
-{
- XEvent *event = reinterpret_cast<XEvent *>(message);
- if (event->type == XKeyPress || event->type == XKeyRelease)
- lastKeyEvent = event->xkey;
-
- if (oldX11EventFilter && oldX11EventFilter != &x11EventFilter)
- return oldX11EventFilter(message, result);
- else
- return false;
-}
-
-//
-struct functorData
-{
- Window id, rootWindow;
- bool clearedWmState;
- bool reparentedToRoot;
-};
-
-static Bool functor(Display *display, XEvent *event, XPointer arg)
-{
- functorData *data = (functorData *) arg;
-
- if (!data->reparentedToRoot && event->type == ReparentNotify
- && event->xreparent.window == data->id
- && event->xreparent.parent == data->rootWindow) {
- data->reparentedToRoot = true;
- return true;
- }
-
- if (!data->clearedWmState
- && event->type == PropertyNotify
- && event->xproperty.window == data->id
- && event->xproperty.atom == ATOM(WM_STATE)) {
- if (event->xproperty.state == PropertyDelete) {
- data->clearedWmState = true;
- return true;
- }
-
- Atom ret;
- int format, status;
- unsigned char *retval;
- unsigned long nitems, after;
- status = XGetWindowProperty(display, data->id, ATOM(WM_STATE), 0, 2, False, ATOM(WM_STATE),
- &ret, &format, &nitems, &after, &retval );
- if (status == Success && ret == ATOM(WM_STATE) && format == 32 && nitems > 0) {
- long state = *(long *)retval;
- XFree(retval);
- if (state == WithdrawnState) {
- data->clearedWmState = true;
- return true;
- }
- }
- }
-
- return false;
-}
-
-class QX11EmbedWidgetPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QX11EmbedWidget)
-public:
- inline QX11EmbedWidgetPrivate()
- {
- lastError = QX11EmbedWidget::Unknown;
- container = 0;
- }
-
- void setEmbedded();
-
- void emitError(QX11EmbedWidget::Error error) {
- Q_Q(QX11EmbedWidget);
-
- lastError = error;
- emit q->error(error);
- }
-
- enum FocusWidgets {
- FirstFocusWidget,
- LastFocusWidget
- };
-
- int focusOriginator;
- QWidget *getFocusWidget(FocusWidgets fw);
- void checkActivateWindow(QObject *o);
- QX11EmbedWidget *xEmbedWidget(QObject *o) const;
- void clearFocus();
-
- WId container;
- QPointer<QWidget> currentFocus;
-
- QX11EmbedWidget::Error lastError;
-
-};
-
-/*!
- Constructs a QX11EmbedWidget object with the given \a parent.
-*/
-QX11EmbedWidget::QX11EmbedWidget(QWidget *parent)
- : QWidget(*new QX11EmbedWidgetPrivate, parent, 0)
-{
- XSetErrorHandler(x11ErrorHandler);
-
- setAttribute(Qt::WA_NativeWindow);
- setAttribute(Qt::WA_DontCreateNativeAncestors);
- createWinId();
- XSelectInput(x11Info().display(), internalWinId(),
- KeyPressMask | KeyReleaseMask | ButtonPressMask
- | ButtonReleaseMask
- | KeymapStateMask | ButtonMotionMask | PointerMotionMask
- | FocusChangeMask
- | ExposureMask | StructureNotifyMask
- | SubstructureNotifyMask | PropertyChangeMask);
-
- long data[] = {XEMBED_VERSION, XEMBED_MAPPED};
- XChangeProperty(x11Info().display(), internalWinId(), ATOM(_XEMBED_INFO),
- ATOM(_XEMBED_INFO), 32, PropModeReplace,
- (unsigned char*) data, 2);
-
- setFocusPolicy(Qt::StrongFocus);
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- QApplication::instance()->installEventFilter(this);
-
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::QX11EmbedWidget: constructed client"
- << (void *)this << "with winId" << winId();
-#endif
-}
-
-/*!
- Destructs the QX11EmbedWidget object. If the widget is embedded
- when deleted, it is hidden and then detached from its container,
- so that the container is free to embed a new widget.
-*/
-QX11EmbedWidget::~QX11EmbedWidget()
-{
- Q_D(QX11EmbedWidget);
- if (d->container) {
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::~QX11EmbedWidget: unmapping"
- << (void *)this << "with winId" << winId()
- << "from container with winId" << d->container;
-#endif
- XUnmapWindow(x11Info().display(), internalWinId());
- XReparentWindow(x11Info().display(), internalWinId(), x11Info().appRootWindow(x11Info().screen()), 0, 0);
- }
-
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::~QX11EmbedWidget: destructed client"
- << (void *)this << "with winId" << winId();
-#endif
-}
-
-/*!
- Returns the type of error that occurred last. This is the same error code
- that is emitted by the error() signal.
-
- \sa Error
-*/
-QX11EmbedWidget::Error QX11EmbedWidget::error() const
-{
- return d_func()->lastError;
-}
-
-/*!
- When this function is called, the widget embeds itself into the
- container whose window ID is \a id.
-
- If \a id is \e not the window ID of a container this function will
- behave unpredictably.
-*/
-void QX11EmbedWidget::embedInto(WId id)
-{
- Q_D(QX11EmbedWidget);
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::embedInto: embedding client"
- << (void *)this << "with winId" << winId() << "into container"
- << id;
-#endif
-
- d->container = id;
- switch (XReparentWindow(x11Info().display(), internalWinId(), d->container, 0, 0)) {
- case BadWindow:
- d->emitError(InvalidWindowID);
- break;
- case BadMatch:
- d->emitError(Internal);
- break;
- case Success:
- default:
- break;
- }
- QTLWExtra* x = d->extra ? d->extra->topextra : 0;
- if (x)
- x->frameStrut.setCoords(0, 0, 0, 0);
- d->data.fstrut_dirty = false;
-}
-
-/*! \internal
-
- Gets the first or last child widget that can get focus.
-*/
-QWidget *QX11EmbedWidgetPrivate::getFocusWidget(FocusWidgets fw)
-{
- Q_Q(QX11EmbedWidget);
- QWidget *tlw = q;
- QWidget *w = tlw->nextInFocusChain();
-
- QWidget *last = tlw;
-
- extern bool qt_tab_all_widgets;
- uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
-
- while (w != tlw)
- {
- if (((w->focusPolicy() & focus_flag) == focus_flag)
- && w->isVisibleTo(q) && w->isEnabled())
- {
- last = w;
- if (fw == FirstFocusWidget)
- break;
- }
- w = w->nextInFocusChain();
- }
-
- return last;
-}
-
-/*! \internal
-
- Returns the xembed widget that the widget is a child of
-*/
-QX11EmbedWidget *QX11EmbedWidgetPrivate::xEmbedWidget(QObject *o) const
-{
- QX11EmbedWidget *xec = 0;
-
- // Check the widget itself, then its parents, and find the first
- // QX11EmbedWidget.
- do {
- if ((xec = qobject_cast<QX11EmbedWidget *>(o)))
- return xec;
- } while ((o = o->parent()));
- return 0;
-}
-
-/*! \internal
-
- Checks the active window.
-*/
-void QX11EmbedWidgetPrivate::checkActivateWindow(QObject *o)
-{
- Q_Q(QX11EmbedWidget);
- QX11EmbedWidget *xec = xEmbedWidget(o);
-
- // check if we are in the right xembed client
- if (q != xec)
- return;
-
- QWidget *w = qobject_cast<QWidget *>(o);
-
- // if it is no active window, then don't do the change
- if (!(w && qApp->activeWindow()))
- return;
-
- // if it already is the active window, don't do anything
- if (w->window() != qApp->activeWindow())
- {
- qApp->setActiveWindow(w->window());
- currentFocus = w;
-
- sendXEmbedMessage(xec->containerWinId(), q->x11Info().display(), XEMBED_REQUEST_FOCUS);
- }
-}
-
-/*! \internal
-
- Clears the focus
-*/
-void QX11EmbedWidgetPrivate::clearFocus()
-{
- Q_Q(QX11EmbedWidget);
- // Setting focus on the client itself removes Qt's
- // logical focus rectangle. We can't just do a
- // clearFocus here, because when we send the synthetic
- // FocusIn to ourselves on activation, Qt will set
- // focus on focusWidget() again. This way, we "hide"
- // focus rather than clearing it.
-
- if (!q->window()->hasFocus())
- q->window()->setFocus(Qt::OtherFocusReason);
-
- currentFocus = 0;
-}
-
-/*! \internal
-
- Sets the embedded flag on the client.
-*/
-void QX11EmbedWidgetPrivate::setEmbedded()
-{
- Q_Q(QX11EmbedWidget);
- ((QHackWidget *)q->window())->topData()->embedded = 1;
-}
-
-/*! \internal
-
- Handles WindowActivate and FocusIn events for the client.
-*/
-bool QX11EmbedWidget::eventFilter(QObject *o, QEvent *event)
-{
- Q_D(QX11EmbedWidget);
- switch (event->type()) {
- case QEvent::FocusIn:
- switch (((QFocusEvent *)event)->reason()) {
- case Qt::MouseFocusReason:
- // If the user clicks into one of the client widget's
- // children and we didn't have focus already, we request
- // focus from our container.
- if (d->xEmbedWidget(o) == this) {
- if (d->currentFocus.isNull())
- sendXEmbedMessage(d->container, x11Info().display(), XEMBED_REQUEST_FOCUS);
-
- d->currentFocus = qobject_cast<QWidget *>(o);
- }
- break;
- case Qt::TabFocusReason:
- // If the xembed client receives a focus event because of
- // a Tab, then we are at the end of our focus chain and we
- // ask the container to move to its next focus widget.
- if (o == this) {
- d->clearFocus();
- sendXEmbedMessage(d->container, x11Info().display(), XEMBED_FOCUS_NEXT);
- return true;
- } else {
- // We're listening on events from qApp, so in order
- // for us to know who to set focus on if we receive an
- // activation event, we note the widget that got the
- // focusin last.
- if (d->xEmbedWidget(o) == this)
- d->currentFocus = qobject_cast<QWidget *>(o);
- }
- break;
- case Qt::BacktabFocusReason:
- // If the window receives a focus event because of
- // a Backtab, then we are at the start of our focus chain
- // and we ask the container to move to its previous focus
- // widget.
- if (o == this) {
- // See comment for Tab.
- // If we receive a XEMBED_FOCUS_IN
- // XEMBED_FOCUS_CURRENT, we will set focus in
- // currentFocus. To avoid that in this case, we reset
- // currentFocus.
- d->clearFocus();
- sendXEmbedMessage(d->container, x11Info().display(), XEMBED_FOCUS_PREV);
- return true;
- } else {
- if (d->xEmbedWidget(o) == this)
- d->currentFocus = qobject_cast<QWidget *>(o);
- }
- break;
- case Qt::ActiveWindowFocusReason:
- if (isActiveWindow()) {
- if (!d->currentFocus.isNull()) {
- if (!d->currentFocus->hasFocus())
- d->currentFocus->setFocus(Qt::OtherFocusReason);
- } else {
- d->clearFocus();
- return true;
- }
- }
-
- break;
- case Qt::PopupFocusReason:
- case Qt::ShortcutFocusReason:
- case Qt::OtherFocusReason:
- // If focus is received to any child widget because of any
- // other reason, remember the widget so that we can give
- // it focus again if we're activated.
- if (d->xEmbedWidget(o) == this) {
- d->currentFocus = qobject_cast<QWidget *>(o);
- }
- break;
- default:
- break;
- }
- break;
- case QEvent::MouseButtonPress:
- // If we get a mouse button press event inside a embedded widget
- // make sure this is the active window in qapp.
- d->checkActivateWindow(o);
- break;
- default:
- break;
- }
-
- return QWidget::eventFilter(o, event);
-}
-
-/*! \internal
-
- Handles some notification events and client messages. Client side
- XEmbed message receiving is also handled here.
-*/
-bool QX11EmbedWidget::x11Event(XEvent *event)
-{
- Q_D(QX11EmbedWidget);
- switch (event->type) {
- case DestroyNotify:
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::x11Event: client"
- << (void *)this << "with winId" << winId()
- << "received a DestroyNotify";
-#endif
- // If the container window is destroyed, we signal this to the user.
- d->container = 0;
- emit containerClosed();
- break;
- case ReparentNotify:
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::x11Event: client"
- << (void *)this << "with winId" << winId()
- << "received a ReparentNotify to"
- << ((event->xreparent.parent == x11Info().appRootWindow(x11Info().screen()))
- ? QString::fromLatin1("root") : QString::number(event->xreparent.parent));
-#endif
- // If the container shuts down, we will be reparented to the
- // root window. We must also consider the case that we may be
- // reparented from one container to another.
- if (event->xreparent.parent == x11Info().appRootWindow(x11Info().screen())) {
- if (((QHackWidget *)this)->topData()->embedded) {
- d->container = 0;
- emit containerClosed();
- }
- return true;
- } else {
- d->container = event->xreparent.parent;
- }
- break;
- case UnmapNotify:
- // Mapping and unmapping are handled by changes to the
- // _XEMBED_INFO property. Any default map/unmap requests are
- // ignored.
- return true;
- case PropertyNotify:
- // The container sends us map/unmap messages through the
- // _XEMBED_INFO property. We adhere to the XEMBED_MAPPED bit in
- // data2.
- if (event->xproperty.atom == ATOM(_XEMBED_INFO)) {
- Atom actual_type_return;
- int actual_format_return;
- unsigned long nitems_return;
- unsigned long bytes_after_return;
- unsigned char *prop_return = 0;
- if (XGetWindowProperty(x11Info().display(), internalWinId(), ATOM(_XEMBED_INFO), 0, 2,
- false, ATOM(_XEMBED_INFO), &actual_type_return,
- &actual_format_return, &nitems_return,
- &bytes_after_return, &prop_return) == Success) {
- if (nitems_return > 1) {
- if (((long * )prop_return)[1] & XEMBED_MAPPED) {
- XMapWindow(x11Info().display(), internalWinId());
- } else {
- XUnmapWindow(x11Info().display(), internalWinId());
- }
- }
- if (prop_return)
- XFree(prop_return);
- }
- }
-
- break;
- case ClientMessage:
- // XEMBED messages have message_type _XEMBED
- if (event->xclient.message_type == ATOM(_XEMBED)) {
- // Discard XEMBED messages not to ourselves. (### dead code?)
- if (event->xclient.window != internalWinId())
- break;
-
- // Update qt_x_time if necessary
- Time msgtime = (Time) event->xclient.data.l[0];
- if (msgtime > X11->time)
- X11->time = msgtime;
-
- switch (event->xclient.data.l[1]) {
- case XEMBED_WINDOW_ACTIVATE: {
- // When we receive an XEMBED_WINDOW_ACTIVATE, we simply send
- // ourselves a WindowActivate event. Real activation happens
- // when receive XEMBED_FOCUS_IN.
- if (!isActiveWindow()) {
- QEvent ev(QEvent::WindowActivate);
- QApplication::sendEvent(this, &ev);
- }
- }
- break;
- case XEMBED_WINDOW_DEACTIVATE: {
- // When we receive an XEMBED_WINDOW_DEACTIVATE, we simply send
- // ourselves a WindowDeactivate event. Real activation happens
- // when receive XEMBED_FOCUS_IN.
- if (isActiveWindow()) {
- if (!qApp->activePopupWidget())
- QApplication::setActiveWindow(0);
- } else {
- QEvent ev(QEvent::WindowDeactivate);
- QApplication::sendEvent(this, &ev);
- }
- }
- break;
- case XEMBED_EMBEDDED_NOTIFY: {
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedWidget::x11Event: client"
- << (void *)this << "with winId" << winId()
- << "received an XEMBED EMBEDDED NOTIFY message";
-#endif
- // In this message's l[2] we have the max version
- // supported by both the client and the
- // container. QX11EmbedWidget does not use this field.
-
- // We have been embedded, so we set our
- // client's embedded flag.
- d->setEmbedded();
- emit embedded();
- }
- break;
- case XEMBED_FOCUS_IN:
- // don't set the focus if a modal dialog is open
- if (qApp->activeModalWidget())
- break;
-
- // in case we embed more than one topLevel window inside the same
- // host window.
- if (window() != qApp->activeWindow())
- qApp->setActiveWindow(this);
-
- switch (event->xclient.data.l[2]) {
- case XEMBED_FOCUS_CURRENT:
- // The container sends us this message if it wants
- // us to focus on the widget that last had focus.
- // This is the reply when XEMBED_REQUEST_FOCUS is
- // sent to the container.
- if (!d->currentFocus.isNull()) {
- if (!d->currentFocus->hasFocus())
- d->currentFocus->setFocus(Qt::OtherFocusReason);
- } else {
- // No widget currently has focus. We set focus
- // on the first widget next to the
- // client widget. Since the setFocus will not work
- // if the window is disabled, set the currentFocus
- // directly so that it's set on window activate.
- d->currentFocus = d->getFocusWidget(QX11EmbedWidgetPrivate::FirstFocusWidget);
- d->currentFocus->setFocus(Qt::OtherFocusReason);
- }
- break;
- case XEMBED_FOCUS_FIRST:
- // The container sends this message when it wants
- // us to focus on the first widget in our focus
- // chain (typically because of a tab).
- d->currentFocus = d->getFocusWidget(QX11EmbedWidgetPrivate::FirstFocusWidget);
- d->currentFocus->setFocus(Qt::TabFocusReason);
- break;
- case XEMBED_FOCUS_LAST:
- // The container sends this message when it wants
- // us to focus on the last widget in our focus
- // chain (typically because of a backtab).
- d->currentFocus = d->getFocusWidget(QX11EmbedWidgetPrivate::LastFocusWidget);
- d->currentFocus->setFocus(Qt::BacktabFocusReason);
- break;
- default:
- // Ignore any other XEMBED_FOCUS_IN details.
- break;
- }
- break;
- case XEMBED_FOCUS_OUT:
- // The container sends us this message when it wants us
- // to lose focus and forget about the widget that last
- // had focus. Typically sent by the container when it
- // loses focus because of mouse or tab activity. We do
- // then not want to set focus on anything if we're
- // activated.
- if (isActiveWindow())
- d->clearFocus();
-
- break;
- default:
- // Ignore any other XEMBED messages.
- break;
- };
- } else {
- // Non-XEMBED client messages are not interesting.
- }
-
- break;
- default:
- // Ignore all other x11 events.
- break;
- }
-
- // Allow default handling.
- return QWidget::x11Event(event);
-}
-
-/*!
- \reimp
-*/
-bool QX11EmbedWidget::event(QEvent *event)
-{
- if (event->type() == QEvent::ParentChange) {
- XSelectInput(x11Info().display(), internalWinId(),
- KeyPressMask | KeyReleaseMask | ButtonPressMask
- | ButtonReleaseMask
- | KeymapStateMask | ButtonMotionMask | PointerMotionMask
- | FocusChangeMask
- | ExposureMask | StructureNotifyMask
- | SubstructureNotifyMask | PropertyChangeMask);
- }
- return QWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-void QX11EmbedWidget::resizeEvent(QResizeEvent *event)
-{
- if (layout())
- layout()->update();
- QWidget::resizeEvent(event);
-}
-
-/*!
- If the widget is embedded, returns the window ID of the
- container; otherwize returns 0.
-*/
-WId QX11EmbedWidget::containerWinId() const
-{
- Q_D(const QX11EmbedWidget);
- return d->container;
-}
-
-class QX11EmbedContainerPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QX11EmbedContainer)
-public:
- inline QX11EmbedContainerPrivate()
- {
- lastError = QX11EmbedContainer::Unknown;
- client = 0;
- focusProxy = 0;
- clientIsXEmbed = false;
- xgrab = false;
- }
-
- bool isEmbedded() const;
- void moveInputToProxy();
-
- void acceptClient(WId window);
- void rejectClient(WId window);
-
- void checkGrab();
-
- WId topLevelParentWinId() const;
-
- void emitError(QX11EmbedContainer::Error error) {
- Q_Q(QX11EmbedContainer);
- lastError = error;
- emit q->error(error);
- }
-
- WId client;
- QWidget *focusProxy;
- bool clientIsXEmbed;
- bool xgrab;
- QRect clientOriginalRect;
- QSize wmMinimumSizeHint;
-
- QX11EmbedContainer::Error lastError;
-
- static QX11EmbedContainer *activeContainer;
-};
-
-QX11EmbedContainer *QX11EmbedContainerPrivate::activeContainer = 0;
-
-/*!
- Creates a QX11EmbedContainer object with the given \a parent.
-*/
-QX11EmbedContainer::QX11EmbedContainer(QWidget *parent)
- : QWidget(*new QX11EmbedContainerPrivate, parent, 0)
-{
- Q_D(QX11EmbedContainer);
- XSetErrorHandler(x11ErrorHandler);
-
- setAttribute(Qt::WA_NativeWindow);
- setAttribute(Qt::WA_DontCreateNativeAncestors);
- createWinId();
-
- setFocusPolicy(Qt::StrongFocus);
- setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- // ### PORT setKeyCompression(false);
- setAcceptDrops(true);
- setEnabled(false);
-
- // Everybody gets a focus proxy, but only one toplevel container's
- // focus proxy is actually in use.
- d->focusProxy = new QWidget(this);
- d->focusProxy->setAttribute(Qt::WA_NativeWindow);
- d->focusProxy->setAttribute(Qt::WA_DontCreateNativeAncestors);
- d->focusProxy->createWinId();
- d->focusProxy->setGeometry(-1, -1, 1, 1);
-
- // We need events from the window (activation status) and
- // from qApp (keypress/release).
- qApp->installEventFilter(this);
-
- // Install X11 event filter.
- if (!oldX11EventFilter)
- oldX11EventFilter = QCoreApplication::instance()->setEventFilter(x11EventFilter);
-
- XSelectInput(x11Info().display(), internalWinId(),
- KeyPressMask | KeyReleaseMask
- | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
- | KeymapStateMask
- | PointerMotionMask
- | EnterWindowMask | LeaveWindowMask
- | FocusChangeMask
- | ExposureMask
- | StructureNotifyMask
- | SubstructureNotifyMask);
-
- // Make sure our new event mask takes effect as soon as possible.
- XFlush(x11Info().display());
-
- // Move input to our focusProxy if this widget is active, and not
- // shaded by a modal dialog (in which case isActiveWindow() would
- // still return true, but where we must not move input focus).
- if (qApp->activeWindow() == window() && !d->isEmbedded())
- d->moveInputToProxy();
-
-#ifdef QX11EMBED_DEBUG
- qDebug() << "QX11EmbedContainer::QX11EmbedContainer: constructed container"
- << (void *)this << "with winId" << winId();
-#endif
-}
-
-/*!
- Destructs a QX11EmbedContainer.
-*/
-QX11EmbedContainer::~QX11EmbedContainer()
-{
- Q_D(QX11EmbedContainer);
- if (d->client) {
- XUnmapWindow(x11Info().display(), d->client);
- XReparentWindow(x11Info().display(), d->client, x11Info().appRootWindow(x11Info().screen()), 0, 0);
- }
-
- if (d->xgrab)
- XUngrabButton(x11Info().display(), AnyButton, AnyModifier, internalWinId());
-}
-
-
-QX11EmbedContainer::Error QX11EmbedContainer::error() const {
- return d_func()->lastError;
-}
-
-
-/*! \reimp
-*/
-void QX11EmbedContainer::paintEvent(QPaintEvent *)
-{
-}
-
-/*! \internal
-
- Returns whether or not the windows' embedded flag is set.
-*/
-bool QX11EmbedContainerPrivate::isEmbedded() const
-{
- Q_Q(const QX11EmbedContainer);
- return ((QHackWidget *)q->window())->topData()->embedded == 1;
-}
-
-/*! \internal
-
- Returns the parentWinId of the window.
-*/
-WId QX11EmbedContainerPrivate::topLevelParentWinId() const
-{
- Q_Q(const QX11EmbedContainer);
- return ((QHackWidget *)q->window())->topData()->parentWinId;
-}
-
-/*!
- If the container has an embedded widget, this function returns
- the X11 window ID of the client; otherwise it returns 0.
-*/
-WId QX11EmbedContainer::clientWinId() const
-{
- Q_D(const QX11EmbedContainer);
- return d->client;
-}
-
-/*!
- Instructs the container to embed the X11 window with window ID \a
- id. The client widget will then move on top of the container
- window and be resized to fit into the container.
-
- The \a id should be the ID of a window controlled by an XEmbed
- enabled application, but this is not mandatory. If \a id does not
- belong to an XEmbed client widget, then focus handling,
- activation, accelerators and other features will not work
- properly.
-*/
-void QX11EmbedContainer::embedClient(WId id)
-{
- Q_D(QX11EmbedContainer);
-
- if (id == 0) {
- d->emitError(InvalidWindowID);
- return;
- }
-
- // Walk up the tree of parent windows to prevent embedding of ancestors.
- WId thisId = internalWinId();
- Window rootReturn;
- Window parentReturn;
- Window *childrenReturn = 0;
- unsigned int nchildrenReturn;
- do {
- if (XQueryTree(x11Info().display(), thisId, &rootReturn,
- &parentReturn, &childrenReturn, &nchildrenReturn) == 0) {
- d->emitError(InvalidWindowID);
- return;
- }
- if (childrenReturn) {
- XFree(childrenReturn);
- childrenReturn = 0;
- }
-
- thisId = parentReturn;
- if (id == thisId) {
- d->emitError(InvalidWindowID);
- return;
- }
- } while (thisId != rootReturn);
-
- // watch for property notify events (see below)
- XGrabServer(x11Info().display());
- XWindowAttributes attrib;
- if (!XGetWindowAttributes(x11Info().display(), id, &attrib)) {
- XUngrabServer(x11Info().display());
- d->emitError(InvalidWindowID);
- return;
- }
- XSelectInput(x11Info().display(), id, attrib.your_event_mask | PropertyChangeMask | StructureNotifyMask);
- XUngrabServer(x11Info().display());
-
- // Put the window into WithdrawnState
- XUnmapWindow(x11Info().display(), id);
- XSync(x11Info().display(), False); // make sure the window is hidden
-
- /*
- Wait for notification from the window manager that the window is
- in withdrawn state. According to the ICCCM section 4.1.3.1,
- we should wait for the WM_STATE property to either be deleted or
- set to WithdrawnState.
-
- For safety, we will not wait more than 500 ms, so that we can
- preemptively workaround buggy window managers.
- */
- QElapsedTimer t;
- t.start();
-
- functorData data;
- data.id = id;
- data.rootWindow = attrib.root;
- data.clearedWmState = false;
- data.reparentedToRoot = false;
-
- do {
- if (t.elapsed() > 500) // time-out after 500 ms
- break;
-
- XEvent event;
- if (!XCheckIfEvent(x11Info().display(), &event, functor, (XPointer) &data)) {
- XSync(x11Info().display(), False);
- usleep(50000);
- continue;
- }
-
- qApp->x11ProcessEvent(&event);
- } while (!data.clearedWmState || !data.reparentedToRoot);
-
- // restore the event mask
- XSelectInput(x11Info().display(), id, attrib.your_event_mask);
-
- switch (XReparentWindow(x11Info().display(), id, internalWinId(), 0, 0)) {
- case BadWindow:
- case BadMatch:
- d->emitError(InvalidWindowID);
- break;
- default:
- break;
- }
-}
-
-/*! \internal
-
- Handles key, activation and focus events for the container.
-*/
-bool QX11EmbedContainer::eventFilter(QObject *o, QEvent *event)
-{
- Q_D(QX11EmbedContainer);
- switch (event->type()) {
- case QEvent::KeyPress:
- // Forward any keypresses to our client.
- if (o == this && d->client) {
- lastKeyEvent.window = d->client;
- XSendEvent(x11Info().display(), d->client, false, KeyPressMask, (XEvent *) &lastKeyEvent);
- return true;
- }
- break;
- case QEvent::KeyRelease:
- // Forward any keyreleases to our client.
- if (o == this && d->client) {
- lastKeyEvent.window = d->client;
- XSendEvent(x11Info().display(), d->client, false, KeyReleaseMask, (XEvent *) &lastKeyEvent);
- return true;
- }
- break;
-
- case QEvent::WindowActivate:
- // When our container window is activated, we pass the
- // activation message on to our client. Note that X input
- // focus is set to our focus proxy. We want to intercept all
- // keypresses.
- if (o == window() && d->client) {
- if (d->clientIsXEmbed) {
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_WINDOW_ACTIVATE);
- } else {
- d->checkGrab();
- if (hasFocus())
- XSetInputFocus(x11Info().display(), d->client, XRevertToParent, x11Time());
- }
- if (!d->isEmbedded())
- d->moveInputToProxy();
- }
- break;
- case QEvent::WindowDeactivate:
- // When our container window is deactivated, we pass the
- // deactivation message to our client.
- if (o == window() && d->client) {
- if (d->clientIsXEmbed)
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_WINDOW_DEACTIVATE);
- else
- d->checkGrab();
- }
- break;
- case QEvent::FocusIn:
- // When receiving FocusIn events generated by Tab or Backtab,
- // we pass focus on to our client. Any mouse activity is sent
- // directly to the client, and it will ask us for focus with
- // XEMBED_REQUEST_FOCUS.
- if (o == this && d->client) {
- if (!d->isEmbedded())
- d->activeContainer = this;
-
- if (d->clientIsXEmbed) {
- if (!d->isEmbedded())
- d->moveInputToProxy();
-
- QFocusEvent *fe = (QFocusEvent *)event;
- switch (fe->reason()) {
- case Qt::TabFocusReason:
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_FOCUS_IN, XEMBED_FOCUS_FIRST);
- break;
- case Qt::BacktabFocusReason:
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_FOCUS_IN, XEMBED_FOCUS_LAST);
- break;
- default:
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_FOCUS_IN, XEMBED_FOCUS_CURRENT);
- break;
- }
- } else {
- d->checkGrab();
- XSetInputFocus(x11Info().display(), d->client, XRevertToParent, x11Time());
- }
- }
-
- break;
- case QEvent::FocusOut: {
- // When receiving a FocusOut, we ask our client to remove its
- // focus.
- if (o == this && d->client) {
- if (!d->isEmbedded()) {
- d->activeContainer = 0;
- if (isActiveWindow())
- d->moveInputToProxy();
- }
-
- if (d->clientIsXEmbed) {
- QFocusEvent *fe = (QFocusEvent *)event;
- if (o == this && d->client && fe->reason() != Qt::ActiveWindowFocusReason)
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_FOCUS_OUT);
- } else {
- d->checkGrab();
- }
- }
- }
- break;
-
- case QEvent::Close: {
- if (o == this && d->client) {
- // Unmap the client and reparent it to the root window.
- // Wait until the messages have been processed. Then ask
- // the window manager to delete the window.
- XUnmapWindow(x11Info().display(), d->client);
- XReparentWindow(x11Info().display(), d->client, x11Info().appRootWindow(x11Info().screen()), 0, 0);
- XSync(x11Info().display(), false);
-
- XEvent ev;
- memset(&ev, 0, sizeof(ev));
- ev.xclient.type = ClientMessage;
- ev.xclient.window = d->client;
- ev.xclient.message_type = ATOM(WM_PROTOCOLS);
- ev.xclient.format = 32;
- ev.xclient.data.s[0] = ATOM(WM_DELETE_WINDOW);
- XSendEvent(x11Info().display(), d->client, false, NoEventMask, &ev);
-
- XFlush(x11Info().display());
- d->client = 0;
- d->clientIsXEmbed = false;
- d->wmMinimumSizeHint = QSize();
- updateGeometry();
- setEnabled(false);
- update();
-
- emit clientClosed();
- }
- }
- default:
- break;
- }
-
- return QWidget::eventFilter(o, event);
-}
-
-/*! \internal
-
- Handles X11 events for the container.
-*/
-bool QX11EmbedContainer::x11Event(XEvent *event)
-{
- Q_D(QX11EmbedContainer);
-
- switch (event->type) {
- case CreateNotify:
- // The client created an embedded window.
- if (d->client)
- d->rejectClient(event->xcreatewindow.window);
- else
- d->acceptClient(event->xcreatewindow.window);
- break;
- case DestroyNotify:
- if (event->xdestroywindow.window == d->client) {
- // The client died.
- d->client = 0;
- d->clientIsXEmbed = false;
- d->wmMinimumSizeHint = QSize();
- updateGeometry();
- update();
- setEnabled(false);
- emit clientClosed();
- }
- break;
- case ReparentNotify:
- // The client sends us this if it reparents itself out of our
- // widget.
- if (event->xreparent.window == d->client && event->xreparent.parent != internalWinId()) {
- d->client = 0;
- d->clientIsXEmbed = false;
- d->wmMinimumSizeHint = QSize();
- updateGeometry();
- update();
- setEnabled(false);
- emit clientClosed();
- } else if (event->xreparent.parent == internalWinId()) {
- // The client reparented itself into this window.
- if (d->client)
- d->rejectClient(event->xreparent.window);
- else
- d->acceptClient(event->xreparent.window);
- }
- break;
- case ClientMessage: {
- if (event->xclient.message_type == ATOM(_XEMBED)) {
- // Ignore XEMBED messages not to ourselves
- if (event->xclient.window != internalWinId())
- break;
-
- // Receiving an XEmbed message means the client
- // is an XEmbed client.
- d->clientIsXEmbed = true;
-
- Time msgtime = (Time) event->xclient.data.l[0];
- if (msgtime > X11->time)
- X11->time = msgtime;
-
- switch (event->xclient.data.l[1]) {
- case XEMBED_REQUEST_FOCUS: {
- // This typically happens when the client gets focus
- // because of a mouse click.
- if (!hasFocus())
- setFocus(Qt::OtherFocusReason);
-
- // The message is passed along to the topmost container
- // that eventually responds with a XEMBED_FOCUS_IN
- // message. The focus in message is passed all the way
- // back until it reaches the original focus
- // requestor. In the end, not only the original client
- // has focus, but also all its ancestor containers.
- if (d->isEmbedded()) {
- // If our window's embedded flag is set, then
- // that suggests that we are part of a client. The
- // parentWinId will then point to an container to whom
- // we must pass this message.
- sendXEmbedMessage(d->topLevelParentWinId(), x11Info().display(), XEMBED_REQUEST_FOCUS);
- } else {
- // Our window's embedded flag is not set,
- // so we are the topmost container. We respond to
- // the focus request message with a focus in
- // message. This message will pass on from client
- // to container to client until it reaches the
- // originator of the XEMBED_REQUEST_FOCUS message.
- sendXEmbedMessage(d->client, x11Info().display(), XEMBED_FOCUS_IN, XEMBED_FOCUS_CURRENT);
- }
-
- break;
- }
- case XEMBED_FOCUS_NEXT:
- // Client sends this event when it received a tab
- // forward and was at the end of its focus chain. If
- // we are the only widget in the focus chain, we send
- // ourselves a FocusIn event.
- if (d->focus_next != this) {
- focusNextPrevChild(true);
- } else {
- QFocusEvent event(QEvent::FocusIn, Qt::TabFocusReason);
- qApp->sendEvent(this, &event);
- }
-
- break;
- case XEMBED_FOCUS_PREV:
- // Client sends this event when it received a backtab
- // and was at the start of its focus chain. If we are
- // the only widget in the focus chain, we send
- // ourselves a FocusIn event.
- if (d->focus_next != this) {
- focusNextPrevChild(false);
- } else {
- QFocusEvent event(QEvent::FocusIn, Qt::BacktabFocusReason);
- qApp->sendEvent(this, &event);
- }
-
- break;
- default:
- break;
- }
- }
- }
- break;
- case XButtonPress:
- if (!d->clientIsXEmbed) {
- setFocus(Qt::MouseFocusReason);
- XAllowEvents(x11Info().display(), ReplayPointer, CurrentTime);
- return true;
- }
- break;
- case XButtonRelease:
- if (!d->clientIsXEmbed)
- XAllowEvents(x11Info().display(), SyncPointer, CurrentTime);
- break;
- default:
- break;
- }
-
- return QWidget::x11Event(event);
-}
-
-/*! \internal
-
- Whenever the container is resized, we need to resize our client.
-*/
-void QX11EmbedContainer::resizeEvent(QResizeEvent *)
-{
- Q_D(QX11EmbedContainer);
- if (d->client)
- XResizeWindow(x11Info().display(), d->client, width(), height());
-}
-
-/*! \internal
-
- We use the QShowEvent to signal to our client that we want it to
- map itself. We do this by changing its window property
- XEMBED_INFO. The client will get an X11 PropertyNotify.
-*/
-void QX11EmbedContainer::showEvent(QShowEvent *)
-{
- Q_D(QX11EmbedContainer);
- if (d->client) {
- long data[] = {XEMBED_VERSION, XEMBED_MAPPED};
- XChangeProperty(x11Info().display(), d->client, ATOM(_XEMBED_INFO), ATOM(_XEMBED_INFO), 32,
- PropModeReplace, (unsigned char *) data, 2);
- }
-}
-
-/*! \internal
-
- We use the QHideEvent to signal to our client that we want it to
- unmap itself. We do this by changing its window property
- XEMBED_INFO. The client will get an X11 PropertyNotify.
-*/
-void QX11EmbedContainer::hideEvent(QHideEvent *)
-{
- Q_D(QX11EmbedContainer);
- if (d->client) {
- long data[] = {XEMBED_VERSION, XEMBED_MAPPED};
- XChangeProperty(x11Info().display(), d->client, ATOM(_XEMBED_INFO), ATOM(_XEMBED_INFO), 32,
- PropModeReplace, (unsigned char *) data, 2);
- }
-}
-
-/*!
- \reimp
-*/
-bool QX11EmbedContainer::event(QEvent *event)
-{
- if (event->type() == QEvent::ParentChange) {
- XSelectInput(x11Info().display(), internalWinId(),
- KeyPressMask | KeyReleaseMask
- | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
- | KeymapStateMask
- | PointerMotionMask
- | EnterWindowMask | LeaveWindowMask
- | FocusChangeMask
- | ExposureMask
- | StructureNotifyMask
- | SubstructureNotifyMask);
- }
- return QWidget::event(event);
-}
-
-/*! \internal
-
- Rejects a client window by reparenting it to the root window. The
- client will receive a reparentnotify, and will most likely assume
- that the container has shut down. The XEmbed protocol does not
- define any way to reject a client window, but this is a clean way
- to do it.
-*/
-void QX11EmbedContainerPrivate::rejectClient(WId window)
-{
- Q_Q(QX11EmbedContainer);
- q->setEnabled(false);
- XRemoveFromSaveSet(q->x11Info().display(), client);
- XReparentWindow(q->x11Info().display(), window, q->x11Info().appRootWindow(q->x11Info().screen()), 0, 0);
-}
-
-/*! \internal
-
- Accepts a client by mapping it, resizing it and optionally
- activating and giving it logical focusing through XEMBED messages.
-*/
-void QX11EmbedContainerPrivate::acceptClient(WId window)
-{
- Q_Q(QX11EmbedContainer);
- client = window;
- q->setEnabled(true);
-
- // This tells Qt that we wish to forward DnD messages to
- // our client.
- if (!extra)
- createExtra();
- extraData()->xDndProxy = client;
-
- unsigned int version = XEmbedVersion();
-
- Atom actual_type_return;
- int actual_format_return;
- unsigned long nitems_return = 0;
- unsigned long bytes_after_return;
- unsigned char *prop_return = 0;
- unsigned int clientversion = 0;
-
- // Add this client to our saveset, so if we crash, the client window
- // doesn't get destroyed. This is useful for containers that restart
- // automatically after a crash, because it can simply reembed its clients
- // without having to restart them (KDE panel).
- XAddToSaveSet(q->x11Info().display(), client);
-
- // XEmbed clients have an _XEMBED_INFO property in which we can
- // fetch the version
- if (XGetWindowProperty(q->x11Info().display(), client, ATOM(_XEMBED_INFO), 0, 2, false,
- ATOM(_XEMBED_INFO), &actual_type_return, &actual_format_return,
- &nitems_return, &bytes_after_return, &prop_return) == Success) {
-
- if (actual_type_return != None && actual_format_return != 0) {
- // Clients with the _XEMBED_INFO property are XEMBED clients.
- clientIsXEmbed = true;
-
- long *p = (long *)prop_return;
- if (nitems_return >= 2)
- clientversion = (unsigned int)p[0];
- }
-
- XFree(prop_return);
- }
-
- // Store client window's original size and placement.
- Window root;
- int x_return, y_return;
- unsigned int width_return, height_return, border_width_return, depth_return;
- XGetGeometry(q->x11Info().display(), client, &root, &x_return, &y_return,
- &width_return, &height_return, &border_width_return, &depth_return);
- clientOriginalRect.setCoords(x_return, y_return,
- x_return + width_return - 1,
- y_return + height_return - 1);
-
- // Ask the client for its minimum size.
- XSizeHints size;
- long msize;
- if (XGetWMNormalHints(q->x11Info().display(), client, &size, &msize) && (size.flags & PMinSize)) {
- wmMinimumSizeHint = QSize(size.min_width, size.min_height);
- q->updateGeometry();
- }
-
- // The container should set the data2 field to the lowest of its
- // supported version number and that of the client (from
- // _XEMBED_INFO property).
- unsigned int minversion = version > clientversion ? clientversion : version;
- sendXEmbedMessage(client, q->x11Info().display(), XEMBED_EMBEDDED_NOTIFY, q->internalWinId(), minversion);
- XMapWindow(q->x11Info().display(), client);
-
- // Resize it, but no smaller than its minimum size hint.
- XResizeWindow(q->x11Info().display(),
- client,
- qMax(q->width(), wmMinimumSizeHint.width()),
- qMax(q->height(), wmMinimumSizeHint.height()));
- q->update();
-
- // Not mentioned in the protocol is that if the container
- // is already active, the client must be activated to work
- // properly.
- if (q->window()->isActiveWindow())
- sendXEmbedMessage(client, q->x11Info().display(), XEMBED_WINDOW_ACTIVATE);
-
- // Also, if the container already has focus, then it must
- // send a focus in message to its new client; otherwise we ask
- // it to remove focus.
- if (q->focusWidget() == q && q->hasFocus())
- sendXEmbedMessage(client, q->x11Info().display(), XEMBED_FOCUS_IN, XEMBED_FOCUS_FIRST);
- else
- sendXEmbedMessage(client, q->x11Info().display(), XEMBED_FOCUS_OUT);
-
- if (!clientIsXEmbed) {
- checkGrab();
- if (q->hasFocus()) {
- XSetInputFocus(q->x11Info().display(), client, XRevertToParent, x11Time());
- }
- } else {
- if (!isEmbedded())
- moveInputToProxy();
- }
-
- emit q->clientIsEmbedded();
-}
-
-/*! \internal
-
- Moves X11 keyboard input focus to the focusProxy, unless the focus
- is there already. When X11 keyboard input focus is on the
- focusProxy, which is a child of the container and a sibling of the
- client, X11 keypresses and keyreleases will always go to the proxy
- and not to the client.
-*/
-void QX11EmbedContainerPrivate::moveInputToProxy()
-{
- Q_Q(QX11EmbedContainer);
- // Following Owen Taylor's advice from the XEmbed specification to
- // always use CurrentTime when no explicit user action is involved.
- XSetInputFocus(q->x11Info().display(), focusProxy->internalWinId(), XRevertToParent, CurrentTime);
-}
-
-/*! \internal
-
- Ask the window manager to give us a default minimum size.
-*/
-QSize QX11EmbedContainer::minimumSizeHint() const
-{
- Q_D(const QX11EmbedContainer);
- if (!d->client || !d->wmMinimumSizeHint.isValid())
- return QWidget::minimumSizeHint();
- return d->wmMinimumSizeHint;
-}
-
-/*! \internal
-
-*/
-void QX11EmbedContainerPrivate::checkGrab()
-{
- Q_Q(QX11EmbedContainer);
- if (!clientIsXEmbed && q->isActiveWindow() && !q->hasFocus()) {
- if (!xgrab) {
- XGrabButton(q->x11Info().display(), AnyButton, AnyModifier, q->internalWinId(),
- true, ButtonPressMask, GrabModeSync, GrabModeAsync,
- None, None);
- }
- xgrab = true;
- } else {
- if (xgrab)
- XUngrabButton(q->x11Info().display(), AnyButton, AnyModifier, q->internalWinId());
- xgrab = false;
- }
-}
-
-/*!
- Detaches the client from the embedder. The client will appear as a
- standalone window on the desktop.
-*/
-void QX11EmbedContainer::discardClient()
-{
- Q_D(QX11EmbedContainer);
- if (d->client) {
- XResizeWindow(x11Info().display(), d->client, d->clientOriginalRect.width(),
- d->clientOriginalRect.height());
-
- d->rejectClient(d->client);
- }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qx11embed_x11.h b/src/gui/platforms/x11/qx11embed_x11.h
deleted file mode 100644
index 30929f7ba9..0000000000
--- a/src/gui/platforms/x11/qx11embed_x11.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** 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 QX11EMBED_X11_H
-#define QX11EMBED_X11_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QX11EmbedWidgetPrivate;
-class Q_GUI_EXPORT QX11EmbedWidget : public QWidget
-{
- Q_OBJECT
-public:
- QX11EmbedWidget(QWidget *parent = 0);
- ~QX11EmbedWidget();
-
- void embedInto(WId id);
- WId containerWinId() const;
-
- enum Error {
- Unknown,
- Internal,
- InvalidWindowID
- };
- Error error() const;
-
-Q_SIGNALS:
- void embedded();
- void containerClosed();
- void error(QX11EmbedWidget::Error error);
-
-protected:
- bool x11Event(XEvent *);
- bool eventFilter(QObject *, QEvent *);
- bool event(QEvent *);
- void resizeEvent(QResizeEvent *);
-
-private:
- Q_DECLARE_PRIVATE(QX11EmbedWidget)
- Q_DISABLE_COPY(QX11EmbedWidget)
-};
-
-class QX11EmbedContainerPrivate;
-class Q_GUI_EXPORT QX11EmbedContainer : public QWidget
-{
- Q_OBJECT
-public:
- QX11EmbedContainer(QWidget *parent = 0);
- ~QX11EmbedContainer();
-
- void embedClient(WId id);
- void discardClient();
-
- WId clientWinId() const;
-
- QSize minimumSizeHint() const;
-
- enum Error {
- Unknown,
- Internal,
- InvalidWindowID
- };
- Error error() const;
-
-Q_SIGNALS:
- void clientIsEmbedded();
- void clientClosed();
- void error(QX11EmbedContainer::Error);
-
-protected:
- bool x11Event(XEvent *);
- bool eventFilter(QObject *, QEvent *);
- void paintEvent(QPaintEvent *e);
- void resizeEvent(QResizeEvent *);
- void showEvent(QShowEvent *);
- void hideEvent(QHideEvent *);
- bool event(QEvent *);
-
-private:
- Q_DECLARE_PRIVATE(QX11EmbedContainer)
- Q_DISABLE_COPY(QX11EmbedContainer)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QX11EMBED_X11_H
diff --git a/src/gui/platforms/x11/qx11info_x11.cpp b/src/gui/platforms/x11/qx11info_x11.cpp
deleted file mode 100644
index f52443befc..0000000000
--- a/src/gui/platforms/x11/qx11info_x11.cpp
+++ /dev/null
@@ -1,543 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwidget.h"
-#include "qpixmap.h"
-#include "qx11info_x11.h"
-#include "qt_x11_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QX11Info
- \brief The QX11Info class provides information about the X display
- configuration.
-
- \ingroup shared
-
- The class provides two APIs: a set of non-static functions that
- provide information about a specific widget or pixmap, and a set
- of static functions that provide the default information for the
- application.
-
- \warning This class is only available on X11. For querying
- per-screen information in a portable way, use QDesktopWidget.
-
- \sa QWidget::x11Info(), QPixmap::x11Info(), QDesktopWidget
-*/
-
-/*!
- Constructs an empty QX11Info object.
-*/
-QX11Info::QX11Info()
- : x11data(0)
-{
-}
-
-/*!
- Constructs a copy of \a other.
-*/
-QX11Info::QX11Info(const QX11Info &other)
-{
- x11data = other.x11data;
- if (x11data)
- ++x11data->ref;
-}
-
-/*!
- Assigns \a other to this object and returns a reference to this
- object.
-*/
-QX11Info &QX11Info::operator=(const QX11Info &other)
-{
- if (other.x11data)
- ++other.x11data->ref;
- if (x11data && !--x11data->ref)
- delete x11data;
- x11data = other.x11data;
- return *this;
-}
-
-/*!
- Destroys the QX11Info object.
-*/
-QX11Info::~QX11Info()
-{
- if (x11data && !--x11data->ref)
- delete x11data;
-}
-
-/*!
- \internal
- Makes a shallow copy of the X11-specific data of \a fromDevice, if it is not
- null. Otherwise this function sets it to null.
-*/
-
-void QX11Info::copyX11Data(const QPaintDevice *fromDevice)
-{
- QX11InfoData *xd = 0;
- if (fromDevice) {
- if (fromDevice->devType() == QInternal::Widget)
- xd = static_cast<const QWidget *>(fromDevice)->x11Info().x11data;
- else if (fromDevice->devType() == QInternal::Pixmap)
- xd = static_cast<const QPixmap *>(fromDevice)->x11Info().x11data;
- }
- setX11Data(xd);
-}
-
-/*!
- \internal
- Makes a deep copy of the X11-specific data of \a fromDevice, if it is not
- null. Otherwise this function sets it to null.
-*/
-
-void QX11Info::cloneX11Data(const QPaintDevice *fromDevice)
-{
- QX11InfoData *d = 0;
- if (fromDevice) {
- QX11InfoData *xd;
- if (fromDevice->devType() == QInternal::Widget) {
- xd = static_cast<const QWidget *>(fromDevice)->x11Info().x11data;
- } else {
- Q_ASSERT(fromDevice->devType() == QInternal::Pixmap);
- xd = static_cast<const QPixmap *>(fromDevice)->x11Info().x11data;
- }
- d = new QX11InfoData(*xd);
- d->ref = 0;
- }
- setX11Data(d);
-}
-
-/*!
- \internal
- Makes a shallow copy of the X11-specific data \a d and assigns it to this
- class. This function increments the reference code of \a d.
-*/
-
-void QX11Info::setX11Data(const QX11InfoData* d)
-{
- if (x11data && !--x11data->ref)
- delete x11data;
- x11data = (QX11InfoData *)d;
- if (x11data)
- ++x11data->ref;
-}
-
-
-/*!
- \internal
- If \a def is false, returns a deep copy of the x11Data, or 0 if x11Data is 0.
- If \a def is true, makes a QX11Data struct filled with the default
- values.
-
- In either case the caller is responsible for deleting the returned
- struct. But notice that the struct is a shared class, so other
- classes might also have a reference to it. The reference count of
- the returned QX11Data* is 0.
-*/
-
-QX11InfoData* QX11Info::getX11Data(bool def) const
-{
- QX11InfoData* res = 0;
- if (def) {
- res = new QX11InfoData;
- res->ref = 0;
- res->screen = appScreen();
- res->depth = appDepth();
- res->cells = appCells();
- res->colormap = colormap();
- res->defaultColormap = appDefaultColormap();
- res->visual = (Visual*) appVisual();
- res->defaultVisual = appDefaultVisual();
- } else if (x11data) {
- res = new QX11InfoData;
- *res = *x11data;
- res->ref = 0;
- }
- return res;
-}
-
-/*!
- Returns the horizontal resolution of the given \a screen in terms of the
- number of dots per inch.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa setAppDpiX(), appDpiY()
-*/
-int QX11Info::appDpiX(int screen)
-{
- if (!X11)
- return 75;
- if (screen < 0)
- screen = X11->defaultScreen;
- if (screen > X11->screenCount)
- return 0;
- return X11->screens[screen].dpiX;
-}
-
-/*!
- Sets the horizontal resolution of the given \a screen to the number of
- dots per inch specified by \a xdpi.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa appDpiX(), setAppDpiY()
-*/
-
-void QX11Info::setAppDpiX(int screen, int xdpi)
-{
- if (!X11)
- return;
- if (screen < 0)
- screen = X11->defaultScreen;
- if (screen > X11->screenCount)
- return;
- X11->screens[screen].dpiX = xdpi;
-}
-
-/*!
- Returns the vertical resolution of the given \a screen in terms of the
- number of dots per inch.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa setAppDpiY(), appDpiX()
-*/
-
-int QX11Info::appDpiY(int screen)
-{
- if (!X11)
- return 75;
- if (screen < 0)
- screen = X11->defaultScreen;
- if (screen > X11->screenCount)
- return 0;
- return X11->screens[screen].dpiY;
-}
-
-/*!
- Sets the vertical resolution of the given \a screen to the number of
- dots per inch specified by \a ydpi.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa appDpiY(), setAppDpiX()
-*/
-void QX11Info::setAppDpiY(int screen, int ydpi)
-{
- if (!X11)
- return;
- if (screen < 0)
- screen = X11->defaultScreen;
- if (screen > X11->screenCount)
- return;
- X11->screens[screen].dpiY = ydpi;
-}
-
-/*!
- Returns the X11 time.
-
- \sa setAppTime(), appUserTime()
-*/
-unsigned long QX11Info::appTime()
-{
- return X11 ? X11->time : 0;
-}
-
-/*!
- Sets the X11 time to the value specified by \a time.
-
- \sa appTime(), setAppUserTime()
-*/
-void QX11Info::setAppTime(unsigned long time)
-{
- if (X11) {
- X11->time = time;
- }
-}
-
-/*!
- Returns the X11 user time.
-
- \sa setAppUserTime(), appTime()
-*/
-unsigned long QX11Info::appUserTime()
-{
- return X11 ? X11->userTime : 0;
-}
-
-/*!
- Sets the X11 user time as specified by \a time.
-
- \sa appUserTime(), setAppTime()
-*/
-void QX11Info::setAppUserTime(unsigned long time)
-{
- if (X11) {
- X11->userTime = time;
- }
-}
-
-
-/*!
- \fn const char *QX11Info::appClass()
-
- Returns the X11 application class.
-
- \sa display()
-*/
-
-/*!
- Returns the default display for the application.
-
- \sa appScreen()
-*/
-
-Display *QX11Info::display()
-{
- return X11 ? X11->display : 0;
-}
-
-/*!
- Returns the number of the screen where the application is being
- displayed.
-
- \sa display(), screen()
-*/
-int QX11Info::appScreen()
-{
- return X11 ? X11->defaultScreen : 0;
-}
-
-/*!
- Returns a handle for the application's color map on the given \a screen.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa colormap(), defaultColormap()
-*/
-Qt::HANDLE QX11Info::appColormap(int screen)
-{
- return X11 ? X11->screens[screen == -1 ? X11->defaultScreen : screen].colormap : 0;
-}
-
-/*!
- Returns the current visual used by the application on the given
- \a screen.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa visual(), defaultVisual()
-*/
-
-void *QX11Info::appVisual(int screen)
-{
- return X11 ? X11->screens[screen == -1 ? X11->defaultScreen : screen].visual : 0;
-}
-
-/*!
- Returns a handle for the applications root window on the given \a screen.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa QApplication::desktop()
-*/
-Qt::HANDLE QX11Info::appRootWindow(int screen)
-{
- return X11 ? RootWindow(X11->display, screen == -1 ? X11->defaultScreen : screen) : 0;
-}
-
-/*!
- Returns the color depth (bits per pixel) used by the application on the
- given \a screen.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa depth()
-*/
-
-int QX11Info::appDepth(int screen)
-{
- return X11 ? X11->screens[screen == -1 ? X11->defaultScreen : screen].depth : 32;
-}
-
-/*!
- Returns the number of cells used by the application on the given \a screen.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa cells()
-*/
-
-int QX11Info::appCells(int screen)
-{ return X11 ? X11->screens[screen == -1 ? X11->defaultScreen : screen].cells : 0; }
-
-/*!
- Returns true if the application has a default color map on the given
- \a screen; otherwise returns false.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-*/
-bool QX11Info::appDefaultColormap(int screen)
-{ return X11 ? X11->screens[screen == -1 ? X11->defaultScreen : screen].defaultColormap : true; }
-
-/*!
- Returns true if the application has a default visual on the given \a screen;
- otherwise returns false.
-
- The \a screen argument is an X screen number. Be aware that if
- the user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-*/
-bool QX11Info::appDefaultVisual(int screen)
-{ return X11 ? X11->screens[screen == -1 ? X11->defaultScreen : screen].defaultVisual : true; }
-
-/*!
- Returns the number of the screen currently in use.
-
- The return value is an X screen number. Be aware that if the
- user's system uses Xinerama (as opposed to traditional X11
- multiscreen), there is only one X screen. Use QDesktopWidget to
- query for information about Xinerama screens.
-
- \sa appScreen()
-*/
-int QX11Info::screen() const
-{ return x11data ? x11data->screen : QX11Info::appScreen(); }
-
-/*!
- Returns the color depth (bits per pixel) of the X display.
-
- \sa appDepth()
-*/
-
-int QX11Info::depth() const
-{ return x11data ? x11data->depth : QX11Info::appDepth(); }
-
-/*!
- Returns the number of cells.
-
- \sa appCells()
-*/
-
-int QX11Info::cells() const
-{ return x11data ? x11data->cells : QX11Info::appCells(); }
-
-/*!
- Returns a handle for the color map.
-
- \sa defaultColormap()
-*/
-
-Qt::HANDLE QX11Info::colormap() const
-{ return x11data ? x11data->colormap : QX11Info::appColormap(); }
-
-/*!
- Returns true if there is a default color map; otherwise returns false.
-
- \sa colormap()
-*/
-
-bool QX11Info::defaultColormap() const
-{ return x11data ? x11data->defaultColormap : QX11Info::appDefaultColormap(); }
-
-/*!
- Returns the current visual.
-
- \sa appVisual(), defaultVisual()
-*/
-
-void *QX11Info::visual() const
-{ return x11data ? x11data->visual : QX11Info::appVisual(); }
-
-/*!
- Returns true if there is a default visual; otherwise returns false.
-
- \sa visual(), appVisual()
-*/
-
-bool QX11Info::defaultVisual() const
-{ return x11data ? x11data->defaultVisual : QX11Info::appDefaultVisual(); }
-
-
-/*!
- \since 4.4
-
- Returns true if there is a compositing manager running.
-*/
-bool QX11Info::isCompositingManagerRunning()
-{
- return X11 ? X11->compositingManagerRunning : false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/platforms/x11/qx11info_x11.h b/src/gui/platforms/x11/qx11info_x11.h
deleted file mode 100644
index ece85740d2..0000000000
--- a/src/gui/platforms/x11/qx11info_x11.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/****************************************************************************
-**
-** 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 QX11INFO_X11_H
-#define QX11INFO_X11_H
-
-#include <QtCore/qnamespace.h>
-
-typedef struct _XDisplay Display;
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-struct QX11InfoData;
-class QX11Info;
-class QPaintDevice;
-class QApplicationPrivate;
-class QX11InfoPrivate;
-struct QX11WindowAttributes;
-
-void qt_x11_getX11InfoForWindow(QX11Info * xinfo, const QX11WindowAttributes &a);
-class Q_GUI_EXPORT QX11Info
-{
-public:
- QX11Info();
- ~QX11Info();
- QX11Info(const QX11Info &other);
- QX11Info &operator=(const QX11Info &other);
-
- static Display *display();
- static const char *appClass();
- int screen() const;
- int depth() const;
- int cells() const;
- Qt::HANDLE colormap() const;
- bool defaultColormap() const;
- void *visual() const;
- bool defaultVisual() const;
-
- static int appScreen();
- static int appDepth(int screen = -1);
- static int appCells(int screen = -1);
- static Qt::HANDLE appColormap(int screen = -1);
- static void *appVisual(int screen = -1);
- static Qt::HANDLE appRootWindow(int screen = -1);
- static bool appDefaultColormap(int screen = -1);
- static bool appDefaultVisual(int screen = -1);
- static int appDpiX(int screen = -1);
- static int appDpiY(int screen = -1);
- static void setAppDpiX(int screen, int dpi);
- static void setAppDpiY(int screen, int dpi);
- static unsigned long appTime();
- static unsigned long appUserTime();
- static void setAppTime(unsigned long time);
- static void setAppUserTime(unsigned long time);
- static bool isCompositingManagerRunning();
-
-protected:
- void copyX11Data(const QPaintDevice *);
- void cloneX11Data(const QPaintDevice *);
- void setX11Data(const QX11InfoData *);
- QX11InfoData* getX11Data(bool def = false) const;
-
- QX11InfoData *x11data;
-
- friend class QX11PaintEngine;
- friend class QPixmap;
- friend class QX11PixmapData;
- friend class QWidget;
- friend class QWidgetPrivate;
- friend class QGLWidget;
- friend void qt_init(QApplicationPrivate *priv, int, Display *display, Qt::HANDLE visual,
- Qt::HANDLE colormap);
- friend void qt_cleanup();
- friend void qt_x11_getX11InfoForWindow(QX11Info * xinfo, const QX11WindowAttributes &a);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QX11INFO_X11_H
diff --git a/src/gui/s60framework/qs60mainapplication.cpp b/src/gui/s60framework/qs60mainapplication.cpp
deleted file mode 100644
index 289d81cf96..0000000000
--- a/src/gui/s60framework/qs60mainapplication.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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 FILES
-#include <exception>
-#include <private/qcore_symbian_p.h>
-#include "qs60maindocument.h"
-#include "qs60mainapplication_p.h"
-#include "qs60mainapplication.h"
-#include <bautils.h>
-#include <coemain.h>
-#ifndef Q_WS_S60
-# include <eikserverapp.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/**
- * factory function to create the QS60Main application class
- */
-CApaApplication *newS60Application()
-{
- return new QS60MainApplication;
-}
-
-
-/*!
- \class QS60MainApplication
- \since 4.6
- \brief The QS60MainApplication class provides support for migration from S60.
-
- \warning This class is provided only to get access to S60 specific
- functionality in the application framework classes. It is not
- portable. We strongly recommend against using it in new applications.
-
- The QS60MainApplication provides a helper class for use in migrating
- from existing S60 based applications to Qt based applications. It is
- used in the exact same way as the \c CEikApplication class from
- Symbian, but internally provides extensions used by Qt.
-
- When modifying old S60 applications that rely on implementing
- functions in \c CEikApplication, the class should be modified to
- inherit from this class instead of \c CEikApplication. Then the
- application can choose to override only certain functions. To make
- Qt use the custom application objects, pass a factory function to
- \c{QApplication::QApplication(QApplication::QS60MainApplicationFactory, int &, char **)}.
-
- For more information on \c CEikApplication, please see the S60 documentation.
-
- Unlike other Qt classes, QS60MainApplication behaves like an S60 class, and can throw Symbian
- leaves.
-
- \sa QS60MainDocument, QS60MainAppUi, QApplication::QS60MainApplicationFactory
- */
-
-/*!
- * \brief Contructs an instance of QS60MainApplication.
- */
-QS60MainApplication::QS60MainApplication()
-{
-}
-
-/*!
- * \brief Destroys the QS60MainApplication.
- */
-QS60MainApplication::~QS60MainApplication()
-{
-}
-
-/*!
- * \brief Creates an instance of QS60MainDocument.
- *
- * \sa QS60MainDocument
- */
-CApaDocument *QS60MainApplication::CreateDocumentL()
-{
- // Create an QtS60Main document, and return a pointer to it
- return new (ELeave) QS60MainDocument(*this);
-}
-
-
-/*!
- * \brief Returns the UID of the application.
- */
-TUid QS60MainApplication::AppDllUid() const
-{
- // Return the UID for the QtS60Main application
- return RProcess().SecureId().operator TUid();
-}
-
-/*!
- * \brief Returns the resource file name.
- */
-TFileName QS60MainApplication::ResourceFileName() const
-{
- return KNullDesC();
-}
-
-/*!
- \internal
-*/
-void QS60MainApplication::PreDocConstructL()
-{
- QS60MainApplicationBase::PreDocConstructL();
-}
-
-/*!
- \internal
-*/
-CDictionaryStore *QS60MainApplication::OpenIniFileLC(RFs &aFs) const
-{
- return QS60MainApplicationBase::OpenIniFileLC(aFs);
-}
-
-/*!
- \internal
-*/
-void QS60MainApplication::NewAppServerL(CApaAppServer *&aAppServer)
-{
-#ifdef Q_WS_S60
- QS60MainApplicationBase::NewAppServerL(aAppServer);
-#else
- aAppServer = new(ELeave) CEikAppServer;
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/s60framework/qs60mainapplication.h b/src/gui/s60framework/qs60mainapplication.h
deleted file mode 100644
index 133f69a83d..0000000000
--- a/src/gui/s60framework/qs60mainapplication.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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 QS60MAINAPPLICATION_H
-#define QS60MAINAPPLICATION_H
-
-#include <QtCore/qglobal.h>
-
-#ifdef Q_OS_SYMBIAN
-
-#ifdef Q_WS_S60
-#include <aknapp.h>
-typedef CAknApplication QS60MainApplicationBase;
-#else
-#include <eikapp.h>
-typedef CEikApplication QS60MainApplicationBase;
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QS60MainApplication : public QS60MainApplicationBase
-{
-public:
- QS60MainApplication();
- // The virtuals are for qdoc.
- virtual ~QS60MainApplication();
-
- virtual TUid AppDllUid() const;
-
- virtual TFileName ResourceFileName() const;
-
-public:
-
- virtual void PreDocConstructL();
-
- virtual CDictionaryStore *OpenIniFileLC(RFs &aFs) const;
-
- virtual void NewAppServerL(CApaAppServer *&aAppServer);
-
-protected:
-
- virtual CApaDocument *CreateDocumentL();
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // Q_OS_SYMBIAN
-
-#endif // QS60MAINAPPLICATION_H
diff --git a/src/gui/s60framework/qs60mainapplication_p.h b/src/gui/s60framework/qs60mainapplication_p.h
deleted file mode 100644
index bb76676b13..0000000000
--- a/src/gui/s60framework/qs60mainapplication_p.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** 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 QS60MAINAPPLICATION_P_H
-#define QS60MAINAPPLICATION_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qglobal.h>
-
-#include <apparc.h>
-
-QT_BEGIN_NAMESPACE
-
-CApaApplication *newS60Application();
-
-QT_END_NAMESPACE
-
-#endif // QS60MAINAPPLICATION_P_H
diff --git a/src/gui/s60framework/qs60mainappui.cpp b/src/gui/s60framework/qs60mainappui.cpp
deleted file mode 100644
index f591fcba36..0000000000
--- a/src/gui/s60framework/qs60mainappui.cpp
+++ /dev/null
@@ -1,430 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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 FILES
-#include <exception>
-#include <qglobal.h>
-#ifdef Q_WS_S60
-#include <avkon.hrh>
-#include <eikmenub.h>
-#include <eikmenup.h>
-#include <avkon.rsg>
-#endif
-#include <barsread.h>
-#include <coeutils.h>
-#include <qconfig.h>
-
-#include "qs60mainappui.h"
-#include <QtGui/qapplication.h>
-#include <QtGui/qsymbianevent.h>
-#include <QtGui/qmenu.h>
-#include <private/qmenu_p.h>
-#include <private/qt_s60_p.h>
-#include <qdebug.h>
-
-//Animated wallpapers in Qt applications are not supported.
-const TInt KAknDisableAnimationBackground = 0x02000000;
-const TInt KAknSingleClickCompatible = 0x01000000;
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QS60MainAppUi
- \since 4.6
- \brief The QS60MainAppUi class is a helper class for S60 migration.
-
- \warning This class is provided only to get access to S60 specific
- functionality in the application framework classes. It is not
- portable. We strongly recommend against using it in new applications.
-
- The QS60MainAppUi provides a helper class for use in migrating from
- existing S60 based applications to Qt based applications. It is used
- in the exact same way as the \c CAknAppUi class from Symbian, but
- internally provides extensions used by Qt.
-
- When modifying old S60 applications that rely on implementing
- functions in \c CAknAppUi, the class should be modified to inherit
- from this class instead of \c CAknAppUi. Then the application can
- choose to override only certain functions.
-
- For more information on \c CAknAppUi, please see the S60
- documentation.
-
- Unlike other Qt classes, QS60MainAppUi behaves like an S60 class,
- and can throw Symbian leaves.
-
- \sa QS60MainDocument, QS60MainApplication
- */
-
-/*!
- * \brief Second phase Symbian constructor.
- *
- * Constructs all the elements of the class that can cause a leave to happen.
- *
- * If you override this function, you should call the base class implementation as well.
- */
-void QS60MainAppUi::ConstructL()
-{
- // Cone's heap and handle checks on app destruction are not suitable for Qt apps, as many
- // objects can still exist in static data at that point. Instead we will print relevant information
- // so that comparative checks may be made for memory leaks, using ~SPrintExitInfo in corelib.
- iEikonEnv->DisableExitChecks(ETrue);
-
- // Initialise app UI with standard value.
- // ENoAppResourceFile and ENonStandardResourceFile makes UI to work without
- // resource files in most SDKs. S60 3rd FP1 public seems to require resource file
- // even these flags are defined
- TInt flags = CEikAppUi::ENoScreenFurniture
- | CEikAppUi::ENonStandardResourceFile;
-#ifdef Q_WS_S60
- flags |= CAknAppUi::EAknEnableSkin;
- // After 5th Edition S60, native side supports animated wallpapers.
- // However, there is no support for that feature on Qt side, so indicate to
- // native UI framework that this application will not support background animations.
-
- // Also, add support for single touch for post 5th edition platforms.
- // This has only impact when launching native dialogs/menus from inside QApplication.
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0) {
- flags |= (KAknDisableAnimationBackground | KAknSingleClickCompatible);
- }
-#endif
- BaseConstructL(flags);
-}
-
-/*!
- * \brief Contructs an instance of QS60MainAppUi.
- */
-QS60MainAppUi::QS60MainAppUi()
-{
- // No implementation required
-}
-
-/*!
- * \brief Destroys the QS60MainAppUi.
- */
-QS60MainAppUi::~QS60MainAppUi()
-{
-}
-
-/*!
- * \brief Handles commands produced by the S60 framework.
- *
- * \a command holds the ID of the command to handle, and is S60 specific.
- *
- * If you override this function, you should call the base class implementation if you do not
- * handle the command.
- */
-void QS60MainAppUi::HandleCommandL(TInt command)
-{
- if (qApp) {
- QSymbianEvent event(QSymbianEvent::CommandEvent, command);
- QT_TRYCATCH_LEAVING(qApp->symbianProcessEvent(&event));
- }
-}
-
-/*!
- * \brief Handles a resource change in the S60 framework.
- *
- * Resource changes include layout switches. \a type holds the type of resource change that
- * occurred.
- *
- * If you override this function, you should call the base class implementation if you do not
- * handle the resource change.
- */
-void QS60MainAppUi::HandleResourceChangeL(TInt type)
-{
- QS60MainAppUiBase::HandleResourceChangeL(type);
-
- if (qApp) {
- QSymbianEvent event(QSymbianEvent::ResourceChangeEvent, type);
- QT_TRYCATCH_LEAVING(qApp->symbianProcessEvent(&event));
- }
-}
-
-/*!
- * \brief Handles raw window server events.
- *
- * The event type and information is passed in \a wsEvent, while the receiving control is passed in
- * \a destination.
- *
- * If you override this function, you should call the base class implementation if you do not
- * handle the event.
- */
-void QS60MainAppUi::HandleWsEventL(const TWsEvent &wsEvent, CCoeControl *destination)
-{
- int result = 0;
- if (qApp) {
- QSymbianEvent event(&wsEvent);
- QT_TRYCATCH_LEAVING(
- result = qApp->symbianProcessEvent(&event)
- );
- }
-
- if (result <= 0)
- QS60MainAppUiBase::HandleWsEventL(wsEvent, destination);
-}
-
-
-/*!
- * \brief Handles changes to the status pane size.
- *
- * Called by the framework when the application status pane size is changed.
- *
- * If you override this function, you should call the base class implementation if you do not
- * handle the size change.
- */
-void QS60MainAppUi::HandleStatusPaneSizeChange()
-{
- TRAP_IGNORE(HandleResourceChangeL(KInternalStatusPaneChange));
- HandleStackedControlsResourceChange(KInternalStatusPaneChange);
-}
-
-/*!
- * \brief Dynamically initializes a menu bar.
- *
- * The resource associated with the menu is given in \a resourceId, and the actual menu bar is
- * passed in \a menuBar.
- *
- * If you override this function, you should call the base class implementation as well.
- */
-void QS60MainAppUi::DynInitMenuBarL(TInt /* resourceId */, CEikMenuBar * /* menuBar */)
-{
-}
-
-/*!
- * \brief Dynamically initializes a menu pane.
- *
- * The resource associated with the menu is given in \a resourceId, and the actual menu pane is
- * passed in \a menuPane.
- *
- * If you override this function, you should call the base class implementation as well.
- */
-void QS60MainAppUi::DynInitMenuPaneL(TInt resourceId, CEikMenuPane *menuPane)
-{
-#ifdef Q_WS_S60
- if (resourceId == R_AVKON_MENUPANE_EMPTY) {
- if (menuPane->NumberOfItemsInPane() <= 1)
- QT_TRYCATCH_LEAVING(qt_symbian_show_toplevel(menuPane));
-
- } else if (resourceId != R_AVKON_MENUPANE_FEP_DEFAULT
- && resourceId != R_AVKON_MENUPANE_EDITTEXT_DEFAULT
- && resourceId != R_AVKON_MENUPANE_LANGUAGE_DEFAULT) {
- QT_TRYCATCH_LEAVING(qt_symbian_show_submenu(menuPane, resourceId));
- }
-#else
- QS60MainAppUiBase::DynInitMenuPaneL(resourceId, menuPane);
-#endif
-}
-
-/*!
- * \brief Restores a menu window.
- *
- * The menu window to restore is given in \a menuWindow. The resource ID and type of menu is given
- * in \a resourceId and \a menuType, respectively.
- *
- * If you override this function, you should call the base class implementation as well.
- */
-void QS60MainAppUi::RestoreMenuL(CCoeControl *menuWindow, TInt resourceId, TMenuType menuType)
-{
-#ifdef Q_WS_S60
- if (resourceId >= QT_SYMBIAN_FIRST_MENU_ITEM && resourceId <= QT_SYMBIAN_LAST_MENU_ITEM) {
- if (menuType == EMenuPane)
- DynInitMenuPaneL(resourceId, (CEikMenuPane*)menuWindow);
- else
- DynInitMenuBarL(resourceId, (CEikMenuBar*)menuWindow);
- } else if(resourceId == R_AVKON_MENUPANE_EMPTY) {
- CEikMenuBarTitle *title = new(ELeave) CEikMenuBarTitle;
- CleanupStack::PushL(title);
-
- title->iData.iMenuPaneResourceId = R_AVKON_MENUPANE_EMPTY;
- title->iTitleFlags = 0;
-
- S60->menuBar()->TitleArray()->AddTitleL(title);
- CleanupStack::Pop( title );
- }
- else
-#endif
- {
- QS60MainAppUiBase::RestoreMenuL(menuWindow, resourceId, menuType);
- }
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::Exit()
-{
- QS60MainAppUiBase::Exit();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::SetFadedL(TBool aFaded)
-{
- QS60MainAppUiBase::SetFadedL(aFaded);
-}
-
-/*!
- \internal
-*/
-TRect QS60MainAppUi::ApplicationRect() const
-{
- return QS60MainAppUiBase::ApplicationRect();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::HandleScreenDeviceChangedL()
-{
- QS60MainAppUiBase::HandleScreenDeviceChangedL();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::HandleApplicationSpecificEventL(TInt aType, const TWsEvent &aEvent)
-{
- QS60MainAppUiBase::HandleApplicationSpecificEventL(aType, aEvent);
-}
-
-/*!
- \internal
-*/
-TTypeUid::Ptr QS60MainAppUi::MopSupplyObject(TTypeUid aId)
-{
- return QS60MainAppUiBase::MopSupplyObject(aId);
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::ProcessCommandL(TInt aCommand)
-{
- QS60MainAppUiBase::ProcessCommandL(aCommand);
-}
-
-/*!
- \internal
-*/
-TErrorHandlerResponse QS60MainAppUi::HandleError (TInt aError, const SExtendedError &aExtErr, TDes &aErrorText, TDes &aContextText)
-{
- return QS60MainAppUiBase::HandleError(aError, aExtErr, aErrorText, aContextText);
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::HandleViewDeactivation(const TVwsViewId &aViewIdToBeDeactivated, const TVwsViewId &aNewlyActivatedViewId)
-{
- QS60MainAppUiBase::HandleViewDeactivation(aViewIdToBeDeactivated, aNewlyActivatedViewId);
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::PrepareToExit()
-{
- QS60MainAppUiBase::PrepareToExit();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::HandleTouchPaneSizeChange()
-{
- QS60MainAppUiBase::HandleTouchPaneSizeChange();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::HandleSystemEventL(const TWsEvent &aEvent)
-{
- QS60MainAppUiBase::HandleSystemEventL(aEvent);
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::Reserved_MtsmPosition()
-{
- QS60MainAppUiBase::Reserved_MtsmPosition();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::Reserved_MtsmObject()
-{
- QS60MainAppUiBase::Reserved_MtsmObject();
-}
-
-/*!
- \internal
-*/
-void QS60MainAppUi::HandleForegroundEventL(TBool aForeground)
-{
- QS60MainAppUiBase::HandleForegroundEventL(aForeground);
-}
-
-/*!
- \internal
-*/
-TBool QS60MainAppUi::ProcessCommandParametersL(TApaCommand /*aCommand*/, TFileName &/*aDocumentName*/, const TDesC8 &/*aTail*/)
-{
- // bypass CEikAppUi::ProcessCommandParametersL(..) which modifies aDocumentName, preventing apparc document opening from working.
- // The return value is effectively unused in Qt apps (see QS60MainDocument::OpenFileL)
- return EFalse;
-}
-
-#ifndef Q_WS_S60
-
-void QS60StubAknAppUi::HandleViewDeactivation(const TVwsViewId &, const TVwsViewId &) {}
-void QS60StubAknAppUi::HandleTouchPaneSizeChange() {}
-void QS60StubAknAppUi::HandleStatusPaneSizeChange() {}
-void QS60StubAknAppUi::Reserved_MtsmPosition() {}
-void QS60StubAknAppUi::Reserved_MtsmObject() {}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/s60framework/qs60mainappui.h b/src/gui/s60framework/qs60mainappui.h
deleted file mode 100644
index bf118ffbe8..0000000000
--- a/src/gui/s60framework/qs60mainappui.h
+++ /dev/null
@@ -1,152 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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 QS60MAINAPPUI_H
-#define QS60MAINAPPUI_H
-
-#include <QtCore/qglobal.h>
-
-#ifdef Q_OS_SYMBIAN
-
-#ifdef Q_WS_S60
-#include <aknappui.h>
-typedef CAknAppUi QS60MainAppUiBase;
-#else
-#include <eikappui.h>
-// these stub classes simulate the structure of CAknAppUi, to help binary compatibility between Qt configured with and without S60/Avkon
-class QS60StubAknAppUiBase : public CEikAppUi
-{
-private:
- int qS60StubAknAppUiBaseSpace[4];
-};
-
-class QS60StubMEikStatusPaneObserver
-{
-public:
- virtual void HandleStatusPaneSizeChange() = 0;
-};
-
-class QS60StubMAknTouchPaneObserver
-{
-public:
- virtual void HandleTouchPaneSizeChange() = 0;
-};
-
-class QS60StubAknAppUi : public QS60StubAknAppUiBase, QS60StubMEikStatusPaneObserver,
- public MCoeViewDeactivationObserver,
- public QS60StubMAknTouchPaneObserver
-{
-public: // MCoeViewDeactivationObserver
- virtual void HandleViewDeactivation(const TVwsViewId&, const TVwsViewId &);
-
-public: // from MAknTouchPaneObserver
- virtual void HandleTouchPaneSizeChange();
-
-protected: // from MEikStatusPaneObserver
- virtual void HandleStatusPaneSizeChange();
-
-protected: // from CAknAppUi
- virtual void Reserved_MtsmPosition();
- virtual void Reserved_MtsmObject();
-
-private:
- int qS60StubAknAppUiSpace[4];
-};
-
-typedef QS60StubAknAppUi QS60MainAppUiBase;
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QS60MainAppUi : public QS60MainAppUiBase
-{
-public:
- QS60MainAppUi();
- // The virtuals are for qdoc.
- virtual ~QS60MainAppUi();
-
- virtual void ConstructL();
-
- virtual void RestoreMenuL(CCoeControl *menuWindow,TInt resourceId,TMenuType menuType);
- virtual void DynInitMenuBarL(TInt resourceId, CEikMenuBar *menuBar);
- virtual void DynInitMenuPaneL(TInt resourceId, CEikMenuPane *menuPane);
-
- virtual void HandleCommandL( TInt command );
-
- virtual void HandleResourceChangeL(TInt type);
-
- virtual void HandleStatusPaneSizeChange();
-
-protected:
- virtual void HandleWsEventL(const TWsEvent &event, CCoeControl *destination);
-
-public:
- virtual void Exit();
- virtual void SetFadedL(TBool aFaded);
- virtual TRect ApplicationRect() const;
- virtual void ProcessCommandL(TInt aCommand);
- virtual TErrorHandlerResponse HandleError (TInt aError, const SExtendedError &aExtErr, TDes &aErrorText, TDes &aContextText);
- virtual void HandleViewDeactivation(const TVwsViewId &aViewIdToBeDeactivated, const TVwsViewId &aNewlyActivatedViewId);
- virtual void PrepareToExit();
- virtual void HandleTouchPaneSizeChange();
- virtual TBool ProcessCommandParametersL(TApaCommand aCommand, TFileName &aDocumentName, const TDesC8 &aTail);
-
-protected:
- virtual void HandleScreenDeviceChangedL();
- virtual void HandleApplicationSpecificEventL(TInt aType, const TWsEvent &aEvent);
- virtual TTypeUid::Ptr MopSupplyObject(TTypeUid aId);
- virtual void HandleSystemEventL(const TWsEvent &aEvent);
- virtual void Reserved_MtsmPosition();
- virtual void Reserved_MtsmObject();
- virtual void HandleForegroundEventL(TBool aForeground);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // Q_OS_SYMBIAN
-
-#endif // QS60MAINAPPUI_H
diff --git a/src/gui/s60framework/qs60maindocument.cpp b/src/gui/s60framework/qs60maindocument.cpp
deleted file mode 100644
index 37bd55f22e..0000000000
--- a/src/gui/s60framework/qs60maindocument.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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 "qs60mainappui.h"
-#include "qs60maindocument.h"
-#include "qcoreapplication.h"
-#include "qevent.h"
-#include "private/qcore_symbian_p.h"
-
-#include <exception>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QS60MainDocument
- \since 4.6
- \brief The QS60MainDocument class is a helper class for S60 migration.
-
- \warning This class is provided only to get access to S60 specific
- functionality in the application framework classes. It is not
- portable. We strongly recommend against using it in new applications.
-
- The QS60MainDocument provides a helper class for use in migrating
- from existing S60 based applications to Qt based applications. It is
- used in the exact same way as the \c CEikDocument class from
- Symbian, but internally provides extensions used by Qt.
-
- When modifying old S60 applications that rely on implementing
- functions in \c CEikDocument, the class should be modified to
- inherit from this class instead of \c CEikDocument. Then the
- application can choose to override only certain functions.
-
- For more information on \c CEikDocument, please see the S60
- documentation.
-
- Unlike other Qt classes, QS60MainDocument behaves like an S60 class,
- and can throw Symbian leaves.
-
- \sa QS60MainApplication, QS60MainAppUi
- */
-
-/*!
- * \brief Constructs an instance of QS60MainDocument.
- *
- * \a mainApplication should contain a pointer to a QS60MainApplication instance.
- */
-QS60MainDocument::QS60MainDocument(CEikApplication &mainApplication)
- : QS60MainDocumentBase(mainApplication)
-{
- // No implementation required
-}
-
-/*!
- * \brief Destroys the QS60MainDocument.
- */
-QS60MainDocument::~QS60MainDocument()
-{
- // No implementation required
-}
-
-/*!
- * \brief Creates an instance of QS60MainAppUi.
- *
- * \sa QS60MainAppUi
- */
-CEikAppUi *QS60MainDocument::CreateAppUiL()
-{
- // Create the application user interface, and return a pointer to it;
- // the framework takes ownership of this object
- return (static_cast <CEikAppUi*>(new(ELeave)QS60MainAppUi));
-}
-
-/*!
- \internal
- */
-CFileStore *QS60MainDocument::OpenFileL(TBool /*aDoOpen*/, const TDesC &aFilename, RFs &/*aFs*/)
-{
- QT_TRYCATCH_LEAVING( {
- QCoreApplication* app = QCoreApplication::instance();
- QString qname = qt_TDesC2QString(aFilename);
- QFileOpenEvent* event = new QFileOpenEvent(qname);
- app->postEvent(app, event);
- })
- return 0;
-}
-
-/*!
- \internal
- */
-void QS60MainDocument::OpenFileL(CFileStore *&aFileStore, RFile &aFile)
-{
- QT_TRYCATCH_LEAVING( {
- QCoreApplication* app = QCoreApplication::instance();
- QFileOpenEvent* event = new QFileOpenEvent(aFile);
- app->postEvent(app, event);
- aFileStore = 0;
- })
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/s60framework/qs60maindocument.h b/src/gui/s60framework/qs60maindocument.h
deleted file mode 100644
index 16ea92281d..0000000000
--- a/src/gui/s60framework/qs60maindocument.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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 QS60MAINDOCUMENT_H
-#define QS60MAINDOCUMENT_H
-
-#include <QtCore/qglobal.h>
-
-#ifdef Q_OS_SYMBIAN
-
-#ifdef Q_WS_S60
-#include <AknDoc.h>
-typedef CAknDocument QS60MainDocumentBase;
-#else
-#include <eikdoc.h>
-typedef CEikDocument QS60MainDocumentBase;
-#endif
-
-class CEikApplication;
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QS60MainAppUi;
-
-class Q_GUI_EXPORT QS60MainDocument : public QS60MainDocumentBase
-{
-public:
-
- QS60MainDocument(CEikApplication &mainApplication);
- // The virtuals are for qdoc.
- virtual ~QS60MainDocument();
-
-public:
-
- virtual CEikAppUi *CreateAppUiL();
-
-public:
-
- virtual CFileStore *OpenFileL(TBool aDoOpen, const TDesC &aFilename, RFs &aFs);
-
- virtual void OpenFileL(CFileStore *&aFileStore, RFile &aFile);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // Q_OS_SYMBIAN
-
-#endif // QS60MAINDOCUMENT_H
diff --git a/src/gui/s60framework/s60framework.pri b/src/gui/s60framework/s60framework.pri
deleted file mode 100644
index 19525b7fdb..0000000000
--- a/src/gui/s60framework/s60framework.pri
+++ /dev/null
@@ -1,10 +0,0 @@
-SOURCES += s60framework/qs60mainapplication.cpp \
- s60framework/qs60mainappui.cpp \
- s60framework/qs60maindocument.cpp
-
-HEADERS += s60framework/qs60mainapplication_p.h \
- s60framework/qs60mainapplication.h \
- s60framework/qs60mainappui.h \
- s60framework/qs60maindocument.h
-
-!isEmpty(QT_LIBINFIX): DEFINES += QT_LIBINFIX_UNQUOTED=$$QT_LIBINFIX \ No newline at end of file
diff --git a/src/gui/s60framework/s60main.rss b/src/gui/s60framework/s60main.rss
deleted file mode 100644
index a38087ddfc..0000000000
--- a/src/gui/s60framework/s60main.rss
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** 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 Symbian application wrapper 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$
-**
-****************************************************************************/
-
-// Even S60 application have ENoAppResourceFile and ENonStandardResourceFile
-// flags set, the S60 3rd Edition FP1 emulator requires applications to have
-// very minimalistic application resource file, otherwise apps refures to start
-// This file serves the minimalistic resource file for S60 3.1 platforms.
-
-// RESOURCE IDENTIFIER
-NAME QTMA // 4 letter ID
-
-// INCLUDES
-//#include <eikon.rh>
-#include <appinfo.rh>
-#include <eikon.rh>
-#include <avkon.rsg>
-#include <avkon.rh>
-#include <avkon.mbg>
-
-// RESOURCE DEFINITIONS
-RESOURCE RSS_SIGNATURE
- {
- }
-
-RESOURCE TBUF r_default_document_name
- {
- buf="QTMA";
- }
-
-RESOURCE EIK_APP_INFO
- {
- menubar = r_qt_wrapperapp_menubar;
- cba = R_AVKON_SOFTKEYS_EXIT;
- }
-
-RESOURCE MENU_BAR r_qt_wrapperapp_menubar
- {
- titles =
- {
- MENU_TITLE { menu_pane = r_qt_wrapperapp_menu; }
- };
- }
-
-RESOURCE MENU_PANE r_qt_wrapperapp_menu
- {
- }
-// End of File
diff --git a/src/gui/statemachine/qbasickeyeventtransition.cpp b/src/gui/statemachine/qbasickeyeventtransition.cpp
deleted file mode 100644
index 2f1848144c..0000000000
--- a/src/gui/statemachine/qbasickeyeventtransition.cpp
+++ /dev/null
@@ -1,208 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbasickeyeventtransition_p.h"
-
-#ifndef QT_NO_STATEMACHINE
-
-#include <QtGui/qevent.h>
-#include <qdebug.h>
-#include <private/qabstracttransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QBasicKeyEventTransition
- \since 4.6
- \ingroup statemachine
-
- \brief The QBasicKeyEventTransition class provides a transition for Qt key events.
-*/
-
-class QBasicKeyEventTransitionPrivate : public QAbstractTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QBasicKeyEventTransition)
-public:
- QBasicKeyEventTransitionPrivate();
-
- static QBasicKeyEventTransitionPrivate *get(QBasicKeyEventTransition *q);
-
- QEvent::Type eventType;
- int key;
- Qt::KeyboardModifiers modifierMask;
-};
-
-QBasicKeyEventTransitionPrivate::QBasicKeyEventTransitionPrivate()
-{
- eventType = QEvent::None;
- key = 0;
- modifierMask = Qt::NoModifier;
-}
-
-QBasicKeyEventTransitionPrivate *QBasicKeyEventTransitionPrivate::get(QBasicKeyEventTransition *q)
-{
- return q->d_func();
-}
-
-/*!
- Constructs a new key event transition with the given \a sourceState.
-*/
-QBasicKeyEventTransition::QBasicKeyEventTransition(QState *sourceState)
- : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState)
-{
-}
-
-/*!
- Constructs a new event transition for events of the given \a type for the
- given \a key, with the given \a sourceState.
-*/
-QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key,
- QState *sourceState)
- : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState)
-{
- Q_D(QBasicKeyEventTransition);
- d->eventType = type;
- d->key = key;
-}
-
-/*!
- Constructs a new event transition for events of the given \a type for the
- given \a key, with the given \a modifierMask and \a sourceState.
-*/
-QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key,
- Qt::KeyboardModifiers modifierMask,
- QState *sourceState)
- : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState)
-{
- Q_D(QBasicKeyEventTransition);
- d->eventType = type;
- d->key = key;
- d->modifierMask = modifierMask;
-}
-
-/*!
- Destroys this event transition.
-*/
-QBasicKeyEventTransition::~QBasicKeyEventTransition()
-{
-}
-
-/*!
- Returns the event type that this key event transition is associated with.
-*/
-QEvent::Type QBasicKeyEventTransition::eventType() const
-{
- Q_D(const QBasicKeyEventTransition);
- return d->eventType;
-}
-
-/*!
- Sets the event \a type that this key event transition is associated with.
-*/
-void QBasicKeyEventTransition::setEventType(QEvent::Type type)
-{
- Q_D(QBasicKeyEventTransition);
- d->eventType = type;
-}
-
-/*!
- Returns the key that this key event transition checks for.
-*/
-int QBasicKeyEventTransition::key() const
-{
- Q_D(const QBasicKeyEventTransition);
- return d->key;
-}
-
-/*!
- Sets the key that this key event transition will check for.
-*/
-void QBasicKeyEventTransition::setKey(int key)
-{
- Q_D(QBasicKeyEventTransition);
- d->key = key;
-}
-
-/*!
- Returns the keyboard modifier mask that this key event transition checks
- for.
-*/
-Qt::KeyboardModifiers QBasicKeyEventTransition::modifierMask() const
-{
- Q_D(const QBasicKeyEventTransition);
- return d->modifierMask;
-}
-
-/*!
- Sets the keyboard modifier mask that this key event transition will check
- for.
-*/
-void QBasicKeyEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QBasicKeyEventTransition);
- d->modifierMask = modifierMask;
-}
-
-/*!
- \reimp
-*/
-bool QBasicKeyEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QBasicKeyEventTransition);
- if (event->type() == d->eventType) {
- QKeyEvent *ke = static_cast<QKeyEvent*>(event);
- return (ke->key() == d->key)
- && ((ke->modifiers() & d->modifierMask) == d->modifierMask);
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-void QBasicKeyEventTransition::onTransition(QEvent *)
-{
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
diff --git a/src/gui/statemachine/qbasickeyeventtransition_p.h b/src/gui/statemachine/qbasickeyeventtransition_p.h
deleted file mode 100644
index 629cae7009..0000000000
--- a/src/gui/statemachine/qbasickeyeventtransition_p.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/****************************************************************************
-**
-** 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 QBASICKEYEVENTTRANSITION_P_H
-#define QBASICKEYEVENTTRANSITION_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qabstracttransition.h>
-
-#ifndef QT_NO_STATEMACHINE
-
-#include <QtGui/qevent.h>
-
-QT_BEGIN_NAMESPACE
-
-class QBasicKeyEventTransitionPrivate;
-class Q_AUTOTEST_EXPORT QBasicKeyEventTransition : public QAbstractTransition
-{
- Q_OBJECT
-public:
- QBasicKeyEventTransition(QState *sourceState = 0);
- QBasicKeyEventTransition(QEvent::Type type, int key, QState *sourceState = 0);
- QBasicKeyEventTransition(QEvent::Type type, int key,
- Qt::KeyboardModifiers modifierMask,
- QState *sourceState = 0);
- ~QBasicKeyEventTransition();
-
- QEvent::Type eventType() const;
- void setEventType(QEvent::Type type);
-
- int key() const;
- void setKey(int key);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
-protected:
- bool eventTest(QEvent *event);
- void onTransition(QEvent *);
-
-private:
- Q_DISABLE_COPY(QBasicKeyEventTransition)
- Q_DECLARE_PRIVATE(QBasicKeyEventTransition)
-};
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
-
-#endif
diff --git a/src/gui/statemachine/qbasicmouseeventtransition.cpp b/src/gui/statemachine/qbasicmouseeventtransition.cpp
deleted file mode 100644
index d11b537c42..0000000000
--- a/src/gui/statemachine/qbasicmouseeventtransition.cpp
+++ /dev/null
@@ -1,213 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbasicmouseeventtransition_p.h"
-
-#ifndef QT_NO_STATEMACHINE
-
-#include <QtGui/qevent.h>
-#include <QtGui/qpainterpath.h>
-#include <qdebug.h>
-#include <private/qabstracttransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
- \class QBasicMouseEventTransition
- \since 4.6
- \ingroup statemachine
-
- \brief The QBasicMouseEventTransition class provides a transition for Qt mouse events.
-*/
-
-class QBasicMouseEventTransitionPrivate : public QAbstractTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QBasicMouseEventTransition)
-public:
- QBasicMouseEventTransitionPrivate();
-
- static QBasicMouseEventTransitionPrivate *get(QBasicMouseEventTransition *q);
-
- QEvent::Type eventType;
- Qt::MouseButton button;
- Qt::KeyboardModifiers modifierMask;
- QPainterPath path;
-};
-
-QBasicMouseEventTransitionPrivate::QBasicMouseEventTransitionPrivate()
-{
- eventType = QEvent::None;
- button = Qt::NoButton;
-}
-
-QBasicMouseEventTransitionPrivate *QBasicMouseEventTransitionPrivate::get(QBasicMouseEventTransition *q)
-{
- return q->d_func();
-}
-
-/*!
- Constructs a new mouse event transition with the given \a sourceState.
-*/
-QBasicMouseEventTransition::QBasicMouseEventTransition(QState *sourceState)
- : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState)
-{
-}
-
-/*!
- Constructs a new mouse event transition for events of the given \a type.
-*/
-QBasicMouseEventTransition::QBasicMouseEventTransition(QEvent::Type type,
- Qt::MouseButton button,
- QState *sourceState)
- : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState)
-{
- Q_D(QBasicMouseEventTransition);
- d->eventType = type;
- d->button = button;
-}
-
-/*!
- Destroys this mouse event transition.
-*/
-QBasicMouseEventTransition::~QBasicMouseEventTransition()
-{
-}
-
-/*!
- Returns the event type that this mouse event transition is associated with.
-*/
-QEvent::Type QBasicMouseEventTransition::eventType() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->eventType;
-}
-
-/*!
- Sets the event \a type that this mouse event transition is associated with.
-*/
-void QBasicMouseEventTransition::setEventType(QEvent::Type type)
-{
- Q_D(QBasicMouseEventTransition);
- d->eventType = type;
-}
-
-/*!
- Returns the button that this mouse event transition checks for.
-*/
-Qt::MouseButton QBasicMouseEventTransition::button() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->button;
-}
-
-/*!
- Sets the button that this mouse event transition will check for.
-*/
-void QBasicMouseEventTransition::setButton(Qt::MouseButton button)
-{
- Q_D(QBasicMouseEventTransition);
- d->button = button;
-}
-
-/*!
- Returns the keyboard modifier mask that this mouse event transition checks
- for.
-*/
-Qt::KeyboardModifiers QBasicMouseEventTransition::modifierMask() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->modifierMask;
-}
-
-/*!
- Sets the keyboard modifier mask that this mouse event transition will check
- for.
-*/
-void QBasicMouseEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QBasicMouseEventTransition);
- d->modifierMask = modifierMask;
-}
-
-/*!
- Returns the hit test path for this mouse event transition.
-*/
-QPainterPath QBasicMouseEventTransition::hitTestPath() const
-{
- Q_D(const QBasicMouseEventTransition);
- return d->path;
-}
-
-/*!
- Sets the hit test path for this mouse event transition.
-*/
-void QBasicMouseEventTransition::setHitTestPath(const QPainterPath &path)
-{
- Q_D(QBasicMouseEventTransition);
- d->path = path;
-}
-
-/*!
- \reimp
-*/
-bool QBasicMouseEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QBasicMouseEventTransition);
- if (event->type() == d->eventType) {
- QMouseEvent *me = static_cast<QMouseEvent*>(event);
- return (me->button() == d->button)
- && ((me->modifiers() & d->modifierMask) == d->modifierMask)
- && (d->path.isEmpty() || d->path.contains(me->pos()));
- }
- return false;
-}
-
-/*!
- \reimp
-*/
-void QBasicMouseEventTransition::onTransition(QEvent *)
-{
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h
deleted file mode 100644
index 61eefa6cfe..0000000000
--- a/src/gui/statemachine/qbasicmouseeventtransition_p.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/****************************************************************************
-**
-** 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 QBASICMOUSEEVENTTRANSITION_P_H
-#define QBASICMOUSEEVENTTRANSITION_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qabstracttransition.h>
-
-#ifndef QT_NO_STATEMACHINE
-
-#include <QtGui/qevent.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPainterPath;
-
-class QBasicMouseEventTransitionPrivate;
-class Q_AUTOTEST_EXPORT QBasicMouseEventTransition : public QAbstractTransition
-{
- Q_OBJECT
-public:
- QBasicMouseEventTransition(QState *sourceState = 0);
- QBasicMouseEventTransition(QEvent::Type type, Qt::MouseButton button,
- QState *sourceState = 0);
- ~QBasicMouseEventTransition();
-
- QEvent::Type eventType() const;
- void setEventType(QEvent::Type type);
-
- Qt::MouseButton button() const;
- void setButton(Qt::MouseButton button);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
- QPainterPath hitTestPath() const;
- void setHitTestPath(const QPainterPath &path);
-
-protected:
- bool eventTest(QEvent *event);
- void onTransition(QEvent *);
-
-private:
- Q_DISABLE_COPY(QBasicMouseEventTransition)
- Q_DECLARE_PRIVATE(QBasicMouseEventTransition)
-};
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
-
-#endif
diff --git a/src/gui/statemachine/qguistatemachine.cpp b/src/gui/statemachine/qguistatemachine.cpp
deleted file mode 100644
index 031c135158..0000000000
--- a/src/gui/statemachine/qguistatemachine.cpp
+++ /dev/null
@@ -1,500 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qstatemachine.h>
-
-#ifndef QT_NO_STATEMACHINE
-
-#include <private/qstatemachine_p.h>
-#include <QtGui/qevent.h>
-#include <QtGui/qgraphicssceneevent.h>
-
-QT_BEGIN_NAMESPACE
-
-Q_CORE_EXPORT const QStateMachinePrivate::Handler *qcoreStateMachineHandler();
-
-static QEvent *cloneEvent(QEvent *e)
-{
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- return new QMouseEvent(*static_cast<QMouseEvent*>(e));
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- return new QKeyEvent(*static_cast<QKeyEvent*>(e));
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- return new QFocusEvent(*static_cast<QFocusEvent*>(e));
- case QEvent::Enter:
- return new QEvent(*e);
- case QEvent::Leave:
- return new QEvent(*e);
- break;
- case QEvent::Paint:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Move:
- return new QMoveEvent(*static_cast<QMoveEvent*>(e));
- case QEvent::Resize:
- return new QResizeEvent(*static_cast<QResizeEvent*>(e));
- case QEvent::Create:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Destroy:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Show:
- return new QShowEvent(*static_cast<QShowEvent*>(e));
- case QEvent::Hide:
- return new QHideEvent(*static_cast<QHideEvent*>(e));
- case QEvent::Close:
- return new QCloseEvent(*static_cast<QCloseEvent*>(e));
- case QEvent::Quit:
- return new QEvent(*e);
- case QEvent::ParentChange:
- return new QEvent(*e);
- case QEvent::ParentAboutToChange:
- return new QEvent(*e);
- case QEvent::ThreadChange:
- return new QEvent(*e);
-
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- return new QEvent(*e);
-
- case QEvent::ShowToParent:
- return new QEvent(*e);
- case QEvent::HideToParent:
- return new QEvent(*e);
-#ifndef QT_NO_WHEELEVENT
- case QEvent::Wheel:
- return new QWheelEvent(*static_cast<QWheelEvent*>(e));
-#endif //QT_NO_WHEELEVENT
- case QEvent::WindowTitleChange:
- return new QEvent(*e);
- case QEvent::WindowIconChange:
- return new QEvent(*e);
- case QEvent::ApplicationWindowIconChange:
- return new QEvent(*e);
- case QEvent::ApplicationFontChange:
- return new QEvent(*e);
- case QEvent::ApplicationLayoutDirectionChange:
- return new QEvent(*e);
- case QEvent::ApplicationPaletteChange:
- return new QEvent(*e);
- case QEvent::PaletteChange:
- return new QEvent(*e);
- case QEvent::Clipboard:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::Speech:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::MetaCall:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::SockAct:
- return new QEvent(*e);
- case QEvent::WinEventAct:
- return new QEvent(*e);
- case QEvent::DeferredDelete:
- return new QEvent(*e);
-#ifndef QT_NO_DRAGANDDROP
- case QEvent::DragEnter:
- return new QDragEnterEvent(*static_cast<QDragEnterEvent*>(e));
- case QEvent::DragMove:
- return new QDragMoveEvent(*static_cast<QDragMoveEvent*>(e));
- case QEvent::DragLeave:
- return new QDragLeaveEvent(*static_cast<QDragLeaveEvent*>(e));
- case QEvent::Drop:
- return new QDropEvent(*static_cast<QDragMoveEvent*>(e));
- case QEvent::DragResponse:
- return new QDragResponseEvent(*static_cast<QDragResponseEvent*>(e));
-#endif
- case QEvent::ChildAdded:
- return new QChildEvent(*static_cast<QChildEvent*>(e));
- case QEvent::ChildPolished:
- return new QChildEvent(*static_cast<QChildEvent*>(e));
- case QEvent::ChildRemoved:
- return new QChildEvent(*static_cast<QChildEvent*>(e));
- case QEvent::ShowWindowRequest:
- return new QEvent(*e);
- case QEvent::PolishRequest:
- return new QEvent(*e);
- case QEvent::Polish:
- return new QEvent(*e);
- case QEvent::LayoutRequest:
- return new QEvent(*e);
- case QEvent::UpdateRequest:
- return new QEvent(*e);
- case QEvent::UpdateLater:
- return new QEvent(*e);
-
- case QEvent::EmbeddingControl:
- return new QEvent(*e);
- case QEvent::ActivateControl:
- return new QEvent(*e);
- case QEvent::DeactivateControl:
- return new QEvent(*e);
-
-#ifndef QT_NO_CONTEXTMENU
- case QEvent::ContextMenu:
- return new QContextMenuEvent(*static_cast<QContextMenuEvent*>(e));
-#endif
- case QEvent::InputMethod:
- return new QInputMethodEvent(*static_cast<QInputMethodEvent*>(e));
- case QEvent::AccessibilityPrepare:
- return new QEvent(*e);
-#ifndef QT_NO_TABLETEVENT
- case QEvent::TabletMove:
- return new QTabletEvent(*static_cast<QTabletEvent*>(e));
-#endif //QT_NO_TABLETEVENT
- case QEvent::LocaleChange:
- return new QEvent(*e);
- case QEvent::LanguageChange:
- return new QEvent(*e);
- case QEvent::LayoutDirectionChange:
- return new QEvent(*e);
- case QEvent::Style:
- return new QEvent(*e);
-#ifndef QT_NO_TABLETEVENT
- case QEvent::TabletPress:
- return new QTabletEvent(*static_cast<QTabletEvent*>(e));
- case QEvent::TabletRelease:
- return new QTabletEvent(*static_cast<QTabletEvent*>(e));
-#endif //QT_NO_TABLETEVENT
- case QEvent::OkRequest:
- return new QEvent(*e);
- case QEvent::HelpRequest:
- return new QEvent(*e);
-
- case QEvent::IconDrag:
- return new QIconDragEvent(*static_cast<QIconDragEvent*>(e));
-
- case QEvent::FontChange:
- return new QEvent(*e);
- case QEvent::EnabledChange:
- return new QEvent(*e);
- case QEvent::ActivationChange:
- return new QEvent(*e);
- case QEvent::StyleChange:
- return new QEvent(*e);
- case QEvent::IconTextChange:
- return new QEvent(*e);
- case QEvent::ModifiedChange:
- return new QEvent(*e);
- case QEvent::MouseTrackingChange:
- return new QEvent(*e);
-
- case QEvent::WindowBlocked:
- return new QEvent(*e);
- case QEvent::WindowUnblocked:
- return new QEvent(*e);
- case QEvent::WindowStateChange:
- return new QWindowStateChangeEvent(*static_cast<QWindowStateChangeEvent*>(e));
-
- case QEvent::ToolTip:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
- case QEvent::WhatsThis:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
-#ifndef QT_NO_STATUSTIP
- case QEvent::StatusTip:
- return new QStatusTipEvent(*static_cast<QStatusTipEvent*>(e));
-#endif //QT_NO_STATUSTIP
-#ifndef QT_NO_ACTION
- case QEvent::ActionChanged:
- case QEvent::ActionAdded:
- case QEvent::ActionRemoved:
- return new QActionEvent(*static_cast<QActionEvent*>(e));
-#endif
- case QEvent::FileOpen:
- return new QFileOpenEvent(*static_cast<QFileOpenEvent*>(e));
-
-#ifndef QT_NO_SHORTCUT
- case QEvent::Shortcut:
- return new QShortcutEvent(*static_cast<QShortcutEvent*>(e));
-#endif //QT_NO_SHORTCUT
- case QEvent::ShortcutOverride:
- return new QKeyEvent(*static_cast<QKeyEvent*>(e));
-
-#ifndef QT_NO_WHATSTHIS
- case QEvent::WhatsThisClicked:
- return new QWhatsThisClickedEvent(*static_cast<QWhatsThisClickedEvent*>(e));
-#endif //QT_NO_WHATSTHIS
-
-#ifndef QT_NO_TOOLBAR
- case QEvent::ToolBarChange:
- return new QToolBarChangeEvent(*static_cast<QToolBarChangeEvent*>(e));
-#endif //QT_NO_TOOLBAR
-
- case QEvent::ApplicationActivate:
- return new QEvent(*e);
- case QEvent::ApplicationDeactivate:
- return new QEvent(*e);
-
- case QEvent::QueryWhatsThis:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
- case QEvent::EnterWhatsThisMode:
- return new QEvent(*e);
- case QEvent::LeaveWhatsThisMode:
- return new QEvent(*e);
-
- case QEvent::ZOrderChange:
- return new QEvent(*e);
-
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- return new QHoverEvent(*static_cast<QHoverEvent*>(e));
-
- case QEvent::AccessibilityHelp:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- case QEvent::AccessibilityDescription:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::EnterEditFocus:
- return new QEvent(*e);
- case QEvent::LeaveEditFocus:
- return new QEvent(*e);
-#endif
- case QEvent::AcceptDropsChange:
- return new QEvent(*e);
-
- case QEvent::ZeroTimerEvent:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseDoubleClick: {
- QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent*>(e);
- QGraphicsSceneMouseEvent *me2 = new QGraphicsSceneMouseEvent(me->type());
- me2->setWidget(me->widget());
- me2->setPos(me->pos());
- me2->setScenePos(me->scenePos());
- me2->setScreenPos(me->screenPos());
-// ### for all buttons
- me2->setButtonDownPos(Qt::LeftButton, me->buttonDownPos(Qt::LeftButton));
- me2->setButtonDownPos(Qt::RightButton, me->buttonDownPos(Qt::RightButton));
- me2->setButtonDownScreenPos(Qt::LeftButton, me->buttonDownScreenPos(Qt::LeftButton));
- me2->setButtonDownScreenPos(Qt::RightButton, me->buttonDownScreenPos(Qt::RightButton));
- me2->setLastPos(me->lastPos());
- me2->setLastScenePos(me->lastScenePos());
- me2->setLastScreenPos(me->lastScreenPos());
- me2->setButtons(me->buttons());
- me2->setButton(me->button());
- me2->setModifiers(me->modifiers());
- return me2;
- }
-
- case QEvent::GraphicsSceneContextMenu: {
- QGraphicsSceneContextMenuEvent *me = static_cast<QGraphicsSceneContextMenuEvent*>(e);
- QGraphicsSceneContextMenuEvent *me2 = new QGraphicsSceneContextMenuEvent(me->type());
- me2->setWidget(me->widget());
- me2->setPos(me->pos());
- me2->setScenePos(me->scenePos());
- me2->setScreenPos(me->screenPos());
- me2->setModifiers(me->modifiers());
- me2->setReason(me->reason());
- return me2;
- }
-
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverMove:
- case QEvent::GraphicsSceneHoverLeave: {
- QGraphicsSceneHoverEvent *he = static_cast<QGraphicsSceneHoverEvent*>(e);
- QGraphicsSceneHoverEvent *he2 = new QGraphicsSceneHoverEvent(he->type());
- he2->setPos(he->pos());
- he2->setScenePos(he->scenePos());
- he2->setScreenPos(he->screenPos());
- he2->setLastPos(he->lastPos());
- he2->setLastScenePos(he->lastScenePos());
- he2->setLastScreenPos(he->lastScreenPos());
- he2->setModifiers(he->modifiers());
- return he2;
- }
- case QEvent::GraphicsSceneHelp:
- return new QHelpEvent(*static_cast<QHelpEvent*>(e));
- case QEvent::GraphicsSceneDragEnter:
- case QEvent::GraphicsSceneDragMove:
- case QEvent::GraphicsSceneDragLeave:
- case QEvent::GraphicsSceneDrop: {
- QGraphicsSceneDragDropEvent *dde = static_cast<QGraphicsSceneDragDropEvent*>(e);
- QGraphicsSceneDragDropEvent *dde2 = new QGraphicsSceneDragDropEvent(dde->type());
- dde2->setPos(dde->pos());
- dde2->setScenePos(dde->scenePos());
- dde2->setScreenPos(dde->screenPos());
- dde2->setButtons(dde->buttons());
- dde2->setModifiers(dde->modifiers());
- return dde2;
- }
- case QEvent::GraphicsSceneWheel: {
- QGraphicsSceneWheelEvent *we = static_cast<QGraphicsSceneWheelEvent*>(e);
- QGraphicsSceneWheelEvent *we2 = new QGraphicsSceneWheelEvent(we->type());
- we2->setPos(we->pos());
- we2->setScenePos(we->scenePos());
- we2->setScreenPos(we->screenPos());
- we2->setButtons(we->buttons());
- we2->setModifiers(we->modifiers());
- we2->setOrientation(we->orientation());
- we2->setDelta(we->delta());
- return we2;
- }
-#endif
- case QEvent::KeyboardLayoutChange:
- return new QEvent(*e);
-
- case QEvent::DynamicPropertyChange:
- return new QDynamicPropertyChangeEvent(*static_cast<QDynamicPropertyChangeEvent*>(e));
-
-#ifndef QT_NO_TABLETEVENT
- case QEvent::TabletEnterProximity:
- case QEvent::TabletLeaveProximity:
- return new QTabletEvent(*static_cast<QTabletEvent*>(e));
-#endif //QT_NO_TABLETEVENT
-
- case QEvent::NonClientAreaMouseMove:
- case QEvent::NonClientAreaMouseButtonPress:
- case QEvent::NonClientAreaMouseButtonRelease:
- case QEvent::NonClientAreaMouseButtonDblClick:
- return new QMouseEvent(*static_cast<QMouseEvent*>(e));
-
- case QEvent::MacSizeChange:
- return new QEvent(*e);
-
- case QEvent::ContentsRectChange:
- return new QEvent(*e);
-
- case QEvent::MacGLWindowChange:
- return new QEvent(*e);
-
- case QEvent::FutureCallOut:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneResize: {
- QGraphicsSceneResizeEvent *re = static_cast<QGraphicsSceneResizeEvent*>(e);
- QGraphicsSceneResizeEvent *re2 = new QGraphicsSceneResizeEvent();
- re2->setOldSize(re->oldSize());
- re2->setNewSize(re->newSize());
- return re2;
- }
- case QEvent::GraphicsSceneMove: {
- QGraphicsSceneMoveEvent *me = static_cast<QGraphicsSceneMoveEvent*>(e);
- QGraphicsSceneMoveEvent *me2 = new QGraphicsSceneMoveEvent();
- me2->setWidget(me->widget());
- me2->setNewPos(me->newPos());
- me2->setOldPos(me->oldPos());
- return me2;
- }
-#endif
- case QEvent::CursorChange:
- return new QEvent(*e);
- case QEvent::ToolTipChange:
- return new QEvent(*e);
-
- case QEvent::NetworkReplyUpdated:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-
- case QEvent::GrabMouse:
- case QEvent::UngrabMouse:
- case QEvent::GrabKeyboard:
- case QEvent::UngrabKeyboard:
- return new QEvent(*e);
-
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- return new QTouchEvent(*static_cast<QTouchEvent*>(e));
-
-#ifndef QT_NO_GESTURES
- case QEvent::NativeGesture:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
-#endif
-
- case QEvent::RequestSoftwareInputPanel:
- case QEvent::CloseSoftwareInputPanel:
- return new QEvent(*e);
-
- case QEvent::UpdateSoftKeys:
- return new QEvent(*e);
-
- case QEvent::User:
- case QEvent::MaxUser:
- Q_ASSERT_X(false, "cloneEvent()", "not implemented");
- break;
- default:
- ;
- }
- return qcoreStateMachineHandler()->cloneEvent(e);
-}
-
-const QStateMachinePrivate::Handler qt_gui_statemachine_handler = {
- cloneEvent
-};
-
-static const QStateMachinePrivate::Handler *qt_guistatemachine_last_handler = 0;
-int qRegisterGuiStateMachine()
-{
- qt_guistatemachine_last_handler = QStateMachinePrivate::handler;
- QStateMachinePrivate::handler = &qt_gui_statemachine_handler;
- return 1;
-}
-Q_CONSTRUCTOR_FUNCTION(qRegisterGuiStateMachine)
-
-int qUnregisterGuiStateMachine()
-{
- QStateMachinePrivate::handler = qt_guistatemachine_last_handler;
- return 1;
-}
-Q_DESTRUCTOR_FUNCTION(qUnregisterGuiStateMachine)
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp
deleted file mode 100644
index 65af91b382..0000000000
--- a/src/gui/statemachine/qkeyeventtransition.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/****************************************************************************
-**
-** 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 "qkeyeventtransition.h"
-
-#ifndef QT_NO_STATEMACHINE
-
-#include "qbasickeyeventtransition_p.h"
-#include <QtCore/qstatemachine.h>
-#include <private/qeventtransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QKeyEventTransition
-
- \brief The QKeyEventTransition class provides a transition for key events.
-
- \since 4.6
- \ingroup statemachine
-
- QKeyEventTransition is part of \l{The State Machine Framework}.
-
- \sa QState::addTransition()
-*/
-
-/*!
- \property QKeyEventTransition::key
-
- \brief the key that this key event transition is associated with
-*/
-
-/*!
- \property QKeyEventTransition::modifierMask
-
- \brief the keyboard modifier mask that this key event transition checks for
-*/
-
-class QKeyEventTransitionPrivate : public QEventTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QKeyEventTransition)
-public:
- QKeyEventTransitionPrivate() {}
-
- QBasicKeyEventTransition *transition;
-};
-
-/*!
- Constructs a new key event transition with the given \a sourceState.
-*/
-QKeyEventTransition::QKeyEventTransition(QState *sourceState)
- : QEventTransition(*new QKeyEventTransitionPrivate, sourceState)
-{
- Q_D(QKeyEventTransition);
- d->transition = new QBasicKeyEventTransition();
-}
-
-/*!
- Constructs a new key event transition for events of the given \a type for
- the given \a object, with the given \a key and \a sourceState.
-*/
-QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type,
- int key, QState *sourceState)
- : QEventTransition(*new QKeyEventTransitionPrivate, object, type, sourceState)
-{
- Q_D(QKeyEventTransition);
- d->transition = new QBasicKeyEventTransition(type, key);
-}
-
-/*!
- Destroys this key event transition.
-*/
-QKeyEventTransition::~QKeyEventTransition()
-{
- Q_D(QKeyEventTransition);
- delete d->transition;
-}
-
-/*!
- Returns the key that this key event transition checks for.
-*/
-int QKeyEventTransition::key() const
-{
- Q_D(const QKeyEventTransition);
- return d->transition->key();
-}
-
-/*!
- Sets the key that this key event transition will check for.
-*/
-void QKeyEventTransition::setKey(int key)
-{
- Q_D(QKeyEventTransition);
- d->transition->setKey(key);
-}
-
-/*!
- Returns the keyboard modifier mask that this key event transition checks
- for.
-*/
-Qt::KeyboardModifiers QKeyEventTransition::modifierMask() const
-{
- Q_D(const QKeyEventTransition);
- return d->transition->modifierMask();
-}
-
-/*!
- Sets the keyboard modifier mask that this key event transition will
- check for to \a modifierMask.
-*/
-void QKeyEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QKeyEventTransition);
- d->transition->setModifierMask(modifierMask);
-}
-
-/*!
- \reimp
-*/
-bool QKeyEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QKeyEventTransition);
- if (!QEventTransition::eventTest(event))
- return false;
- QStateMachine::WrappedEvent *we = static_cast<QStateMachine::WrappedEvent*>(event);
- d->transition->setEventType(we->event()->type());
- return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event());
-}
-
-/*!
- \reimp
-*/
-void QKeyEventTransition::onTransition(QEvent *event)
-{
- QEventTransition::onTransition(event);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h
deleted file mode 100644
index 2bc47e4178..0000000000
--- a/src/gui/statemachine/qkeyeventtransition.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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 QKEYEVENTTRANSITION_H
-#define QKEYEVENTTRANSITION_H
-
-#include <QtCore/qeventtransition.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_STATEMACHINE
-
-class QKeyEventTransitionPrivate;
-class Q_GUI_EXPORT QKeyEventTransition : public QEventTransition
-{
- Q_OBJECT
- Q_PROPERTY(int key READ key WRITE setKey)
- Q_PROPERTY(Qt::KeyboardModifiers modifierMask READ modifierMask WRITE setModifierMask)
-public:
- QKeyEventTransition(QState *sourceState = 0);
- QKeyEventTransition(QObject *object, QEvent::Type type, int key,
- QState *sourceState = 0);
- ~QKeyEventTransition();
-
- int key() const;
- void setKey(int key);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
-protected:
- void onTransition(QEvent *event);
- bool eventTest(QEvent *event);
-
-private:
- Q_DISABLE_COPY(QKeyEventTransition)
- Q_DECLARE_PRIVATE(QKeyEventTransition)
-};
-
-#endif //QT_NO_STATEMACHINE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp
deleted file mode 100644
index 3ecf1e2fa8..0000000000
--- a/src/gui/statemachine/qmouseeventtransition.cpp
+++ /dev/null
@@ -1,206 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmouseeventtransition.h"
-
-#ifndef QT_NO_STATEMACHINE
-
-#include "qbasicmouseeventtransition_p.h"
-#include <QtCore/qstatemachine.h>
-#include <QtGui/qpainterpath.h>
-#include <private/qeventtransition_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QMouseEventTransition
-
- \brief The QMouseEventTransition class provides a transition for mouse events.
-
- \since 4.6
- \ingroup statemachine
-
- QMouseEventTransition is part of \l{The State Machine Framework}.
-
- \sa QState::addTransition()
-*/
-
-/*!
- \property QMouseEventTransition::button
-
- \brief the button that this mouse event transition is associated with
-*/
-
-/*!
- \property QMouseEventTransition::modifierMask
-
- \brief the keyboard modifier mask that this mouse event transition checks for
-*/
-
-class QMouseEventTransitionPrivate : public QEventTransitionPrivate
-{
- Q_DECLARE_PUBLIC(QMouseEventTransition)
-public:
- QMouseEventTransitionPrivate();
-
- QBasicMouseEventTransition *transition;
-};
-
-QMouseEventTransitionPrivate::QMouseEventTransitionPrivate()
-{
-}
-
-/*!
- Constructs a new mouse event transition with the given \a sourceState.
-*/
-QMouseEventTransition::QMouseEventTransition(QState *sourceState)
- : QEventTransition(*new QMouseEventTransitionPrivate, sourceState)
-{
- Q_D(QMouseEventTransition);
- d->transition = new QBasicMouseEventTransition();
-}
-
-/*!
- Constructs a new mouse event transition for events of the given \a type for
- the given \a object, with the given \a button and \a sourceState.
-*/
-QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type,
- Qt::MouseButton button,
- QState *sourceState)
- : QEventTransition(*new QMouseEventTransitionPrivate, object, type, sourceState)
-{
- Q_D(QMouseEventTransition);
- d->transition = new QBasicMouseEventTransition(type, button);
-}
-
-/*!
- Destroys this mouse event transition.
-*/
-QMouseEventTransition::~QMouseEventTransition()
-{
- Q_D(QMouseEventTransition);
- delete d->transition;
-}
-
-/*!
- Returns the button that this mouse event transition checks for.
-*/
-Qt::MouseButton QMouseEventTransition::button() const
-{
- Q_D(const QMouseEventTransition);
- return d->transition->button();
-}
-
-/*!
- Sets the \a button that this mouse event transition will check for.
-*/
-void QMouseEventTransition::setButton(Qt::MouseButton button)
-{
- Q_D(QMouseEventTransition);
- d->transition->setButton(button);
-}
-
-/*!
- Returns the keyboard modifier mask that this mouse event transition checks
- for.
-*/
-Qt::KeyboardModifiers QMouseEventTransition::modifierMask() const
-{
- Q_D(const QMouseEventTransition);
- return d->transition->modifierMask();
-}
-
-/*!
- Sets the keyboard modifier mask that this mouse event transition will
- check for to \a modifierMask.
-*/
-void QMouseEventTransition::setModifierMask(Qt::KeyboardModifiers modifierMask)
-{
- Q_D(QMouseEventTransition);
- d->transition->setModifierMask(modifierMask);
-}
-
-/*!
- Returns the hit test path for this mouse event transition.
-*/
-QPainterPath QMouseEventTransition::hitTestPath() const
-{
- Q_D(const QMouseEventTransition);
- return d->transition->hitTestPath();
-}
-
-/*!
- Sets the hit test path for this mouse event transition to \a path.
- If a valid path has been set, the transition will only trigger if the mouse
- event position (QMouseEvent::pos()) is inside the path.
-
- \sa QPainterPath::contains()
-*/
-void QMouseEventTransition::setHitTestPath(const QPainterPath &path)
-{
- Q_D(QMouseEventTransition);
- d->transition->setHitTestPath(path);
-}
-
-/*!
- \reimp
-*/
-bool QMouseEventTransition::eventTest(QEvent *event)
-{
- Q_D(const QMouseEventTransition);
- if (!QEventTransition::eventTest(event))
- return false;
- QStateMachine::WrappedEvent *we = static_cast<QStateMachine::WrappedEvent*>(event);
- d->transition->setEventType(we->event()->type());
- return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event());
-}
-
-/*!
- \reimp
-*/
-void QMouseEventTransition::onTransition(QEvent *event)
-{
- QEventTransition::onTransition(event);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_STATEMACHINE
diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h
deleted file mode 100644
index 8be10c8513..0000000000
--- a/src/gui/statemachine/qmouseeventtransition.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************************
-**
-** 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 QMOUSEEVENTTRANSITION_H
-#define QMOUSEEVENTTRANSITION_H
-
-#include <QtCore/qeventtransition.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_STATEMACHINE
-
-class QMouseEventTransitionPrivate;
-class QPainterPath;
-class Q_GUI_EXPORT QMouseEventTransition : public QEventTransition
-{
- Q_OBJECT
- Q_PROPERTY(Qt::MouseButton button READ button WRITE setButton)
- Q_PROPERTY(Qt::KeyboardModifiers modifierMask READ modifierMask WRITE setModifierMask)
-public:
- QMouseEventTransition(QState *sourceState = 0);
- QMouseEventTransition(QObject *object, QEvent::Type type,
- Qt::MouseButton button, QState *sourceState = 0);
- ~QMouseEventTransition();
-
- Qt::MouseButton button() const;
- void setButton(Qt::MouseButton button);
-
- Qt::KeyboardModifiers modifierMask() const;
- void setModifierMask(Qt::KeyboardModifiers modifiers);
-
- QPainterPath hitTestPath() const;
- void setHitTestPath(const QPainterPath &path);
-
-protected:
- void onTransition(QEvent *event);
- bool eventTest(QEvent *event);
-
-private:
- Q_DISABLE_COPY(QMouseEventTransition)
- Q_DECLARE_PRIVATE(QMouseEventTransition)
-};
-
-#endif //QT_NO_STATEMACHINE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/gui/statemachine/statemachine.pri b/src/gui/statemachine/statemachine.pri
deleted file mode 100644
index 2eb1e05be6..0000000000
--- a/src/gui/statemachine/statemachine.pri
+++ /dev/null
@@ -1,13 +0,0 @@
-SOURCES += $$PWD/qguistatemachine.cpp
-!contains(DEFINES, QT_NO_STATEMACHINE_EVENTFILTER) {
- HEADERS += \
- $$PWD/qkeyeventtransition.h \
- $$PWD/qmouseeventtransition.h \
- $$PWD/qbasickeyeventtransition_p.h \
- $$PWD/qbasicmouseeventtransition_p.h
- SOURCES += \
- $$PWD/qkeyeventtransition.cpp \
- $$PWD/qmouseeventtransition.cpp \
- $$PWD/qbasickeyeventtransition.cpp \
- $$PWD/qbasicmouseeventtransition.cpp
-}
diff --git a/src/gui/styles/images/cdr-128.png b/src/gui/styles/images/cdr-128.png
deleted file mode 100644
index c5daa15fc8..0000000000
--- a/src/gui/styles/images/cdr-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/cdr-16.png b/src/gui/styles/images/cdr-16.png
deleted file mode 100644
index 82d7533bd1..0000000000
--- a/src/gui/styles/images/cdr-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/cdr-32.png b/src/gui/styles/images/cdr-32.png
deleted file mode 100644
index dcfb085da5..0000000000
--- a/src/gui/styles/images/cdr-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/closedock-16.png b/src/gui/styles/images/closedock-16.png
deleted file mode 100644
index ab9d669eee..0000000000
--- a/src/gui/styles/images/closedock-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/closedock-down-16.png b/src/gui/styles/images/closedock-down-16.png
deleted file mode 100644
index c1791dd2cc..0000000000
--- a/src/gui/styles/images/closedock-down-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/computer-16.png b/src/gui/styles/images/computer-16.png
deleted file mode 100644
index 43fb0bb581..0000000000
--- a/src/gui/styles/images/computer-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/computer-32.png b/src/gui/styles/images/computer-32.png
deleted file mode 100644
index 6d750ce89b..0000000000
--- a/src/gui/styles/images/computer-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/defaults60theme.blob b/src/gui/styles/images/defaults60theme.blob
deleted file mode 100644
index f3a59528d6..0000000000
--- a/src/gui/styles/images/defaults60theme.blob
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/desktop-16.png b/src/gui/styles/images/desktop-16.png
deleted file mode 100644
index d612dfb0fc..0000000000
--- a/src/gui/styles/images/desktop-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/desktop-32.png b/src/gui/styles/images/desktop-32.png
deleted file mode 100644
index ad85b48d3a..0000000000
--- a/src/gui/styles/images/desktop-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dirclosed-128.png b/src/gui/styles/images/dirclosed-128.png
deleted file mode 100644
index e4fa843162..0000000000
--- a/src/gui/styles/images/dirclosed-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dirclosed-16.png b/src/gui/styles/images/dirclosed-16.png
deleted file mode 100644
index 333fe8eaac..0000000000
--- a/src/gui/styles/images/dirclosed-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dirclosed-32.png b/src/gui/styles/images/dirclosed-32.png
deleted file mode 100644
index 3add907ed5..0000000000
--- a/src/gui/styles/images/dirclosed-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dirlink-128.png b/src/gui/styles/images/dirlink-128.png
deleted file mode 100644
index ec299f8e52..0000000000
--- a/src/gui/styles/images/dirlink-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dirlink-16.png b/src/gui/styles/images/dirlink-16.png
deleted file mode 100644
index 9f16cd3520..0000000000
--- a/src/gui/styles/images/dirlink-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dirlink-32.png b/src/gui/styles/images/dirlink-32.png
deleted file mode 100644
index 776536d131..0000000000
--- a/src/gui/styles/images/dirlink-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/diropen-128.png b/src/gui/styles/images/diropen-128.png
deleted file mode 100644
index b91c4af72a..0000000000
--- a/src/gui/styles/images/diropen-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/diropen-16.png b/src/gui/styles/images/diropen-16.png
deleted file mode 100644
index 95f0771d06..0000000000
--- a/src/gui/styles/images/diropen-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/diropen-32.png b/src/gui/styles/images/diropen-32.png
deleted file mode 100644
index af5f7e7e81..0000000000
--- a/src/gui/styles/images/diropen-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dockdock-16.png b/src/gui/styles/images/dockdock-16.png
deleted file mode 100644
index 4ac9483176..0000000000
--- a/src/gui/styles/images/dockdock-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dockdock-down-16.png b/src/gui/styles/images/dockdock-down-16.png
deleted file mode 100644
index 2e85a679be..0000000000
--- a/src/gui/styles/images/dockdock-down-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/down-128.png b/src/gui/styles/images/down-128.png
deleted file mode 100644
index 09dfe43a93..0000000000
--- a/src/gui/styles/images/down-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/down-16.png b/src/gui/styles/images/down-16.png
deleted file mode 100644
index c60a174e25..0000000000
--- a/src/gui/styles/images/down-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/down-32.png b/src/gui/styles/images/down-32.png
deleted file mode 100644
index 46eadb8e12..0000000000
--- a/src/gui/styles/images/down-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dvd-128.png b/src/gui/styles/images/dvd-128.png
deleted file mode 100644
index 9ed9dc1e55..0000000000
--- a/src/gui/styles/images/dvd-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dvd-16.png b/src/gui/styles/images/dvd-16.png
deleted file mode 100644
index 623386d4ca..0000000000
--- a/src/gui/styles/images/dvd-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/dvd-32.png b/src/gui/styles/images/dvd-32.png
deleted file mode 100644
index 089b72accb..0000000000
--- a/src/gui/styles/images/dvd-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/file-128.png b/src/gui/styles/images/file-128.png
deleted file mode 100644
index 46e6ceb49a..0000000000
--- a/src/gui/styles/images/file-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/file-16.png b/src/gui/styles/images/file-16.png
deleted file mode 100644
index 664b56356b..0000000000
--- a/src/gui/styles/images/file-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/file-32.png b/src/gui/styles/images/file-32.png
deleted file mode 100644
index 83e5c3d311..0000000000
--- a/src/gui/styles/images/file-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/filecontents-128.png b/src/gui/styles/images/filecontents-128.png
deleted file mode 100644
index 50e0a838e2..0000000000
--- a/src/gui/styles/images/filecontents-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/filecontents-16.png b/src/gui/styles/images/filecontents-16.png
deleted file mode 100644
index b9399ccf2e..0000000000
--- a/src/gui/styles/images/filecontents-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/filecontents-32.png b/src/gui/styles/images/filecontents-32.png
deleted file mode 100644
index 3761f70690..0000000000
--- a/src/gui/styles/images/filecontents-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/fileinfo-128.png b/src/gui/styles/images/fileinfo-128.png
deleted file mode 100644
index 8c5b331876..0000000000
--- a/src/gui/styles/images/fileinfo-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/fileinfo-16.png b/src/gui/styles/images/fileinfo-16.png
deleted file mode 100644
index 729be4d5f2..0000000000
--- a/src/gui/styles/images/fileinfo-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/fileinfo-32.png b/src/gui/styles/images/fileinfo-32.png
deleted file mode 100644
index ca795aa49b..0000000000
--- a/src/gui/styles/images/fileinfo-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/filelink-128.png b/src/gui/styles/images/filelink-128.png
deleted file mode 100644
index be86a82901..0000000000
--- a/src/gui/styles/images/filelink-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/filelink-16.png b/src/gui/styles/images/filelink-16.png
deleted file mode 100644
index 6643f2c428..0000000000
--- a/src/gui/styles/images/filelink-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/filelink-32.png b/src/gui/styles/images/filelink-32.png
deleted file mode 100644
index 1e46fdc13c..0000000000
--- a/src/gui/styles/images/filelink-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/floppy-128.png b/src/gui/styles/images/floppy-128.png
deleted file mode 100644
index fa7a3e1334..0000000000
--- a/src/gui/styles/images/floppy-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/floppy-16.png b/src/gui/styles/images/floppy-16.png
deleted file mode 100644
index 91c59c567d..0000000000
--- a/src/gui/styles/images/floppy-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/floppy-32.png b/src/gui/styles/images/floppy-32.png
deleted file mode 100644
index e63b3213bf..0000000000
--- a/src/gui/styles/images/floppy-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/fontbitmap-16.png b/src/gui/styles/images/fontbitmap-16.png
deleted file mode 100644
index 03efc9cbab..0000000000
--- a/src/gui/styles/images/fontbitmap-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/fonttruetype-16.png b/src/gui/styles/images/fonttruetype-16.png
deleted file mode 100644
index 25205021e9..0000000000
--- a/src/gui/styles/images/fonttruetype-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/harddrive-128.png b/src/gui/styles/images/harddrive-128.png
deleted file mode 100644
index 0b73d9de1e..0000000000
--- a/src/gui/styles/images/harddrive-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/harddrive-16.png b/src/gui/styles/images/harddrive-16.png
deleted file mode 100644
index 45d592baa3..0000000000
--- a/src/gui/styles/images/harddrive-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/harddrive-32.png b/src/gui/styles/images/harddrive-32.png
deleted file mode 100644
index 7041452b68..0000000000
--- a/src/gui/styles/images/harddrive-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/left-128.png b/src/gui/styles/images/left-128.png
deleted file mode 100644
index a26a5195f8..0000000000
--- a/src/gui/styles/images/left-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/left-16.png b/src/gui/styles/images/left-16.png
deleted file mode 100644
index 110dd90f2d..0000000000
--- a/src/gui/styles/images/left-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/left-32.png b/src/gui/styles/images/left-32.png
deleted file mode 100644
index ec4107b372..0000000000
--- a/src/gui/styles/images/left-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-pause-16.png b/src/gui/styles/images/media-pause-16.png
deleted file mode 100644
index 6cb1fd7f63..0000000000
--- a/src/gui/styles/images/media-pause-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-pause-32.png b/src/gui/styles/images/media-pause-32.png
deleted file mode 100644
index 3f172a04d6..0000000000
--- a/src/gui/styles/images/media-pause-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-play-16.png b/src/gui/styles/images/media-play-16.png
deleted file mode 100644
index d7ee3ccbe3..0000000000
--- a/src/gui/styles/images/media-play-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-play-32.png b/src/gui/styles/images/media-play-32.png
deleted file mode 100644
index af8d2f7ba5..0000000000
--- a/src/gui/styles/images/media-play-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-seek-backward-16.png b/src/gui/styles/images/media-seek-backward-16.png
deleted file mode 100644
index b8a8ea42d1..0000000000
--- a/src/gui/styles/images/media-seek-backward-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-seek-backward-32.png b/src/gui/styles/images/media-seek-backward-32.png
deleted file mode 100644
index a21d1372fe..0000000000
--- a/src/gui/styles/images/media-seek-backward-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-seek-forward-16.png b/src/gui/styles/images/media-seek-forward-16.png
deleted file mode 100644
index 3c900dcb62..0000000000
--- a/src/gui/styles/images/media-seek-forward-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-seek-forward-32.png b/src/gui/styles/images/media-seek-forward-32.png
deleted file mode 100644
index 4f8d370fa1..0000000000
--- a/src/gui/styles/images/media-seek-forward-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-skip-backward-16.png b/src/gui/styles/images/media-skip-backward-16.png
deleted file mode 100644
index f5b3f4f56d..0000000000
--- a/src/gui/styles/images/media-skip-backward-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-skip-backward-32.png b/src/gui/styles/images/media-skip-backward-32.png
deleted file mode 100644
index 1d338035ef..0000000000
--- a/src/gui/styles/images/media-skip-backward-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-skip-forward-16.png b/src/gui/styles/images/media-skip-forward-16.png
deleted file mode 100644
index 27e205b02f..0000000000
--- a/src/gui/styles/images/media-skip-forward-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-skip-forward-32.png b/src/gui/styles/images/media-skip-forward-32.png
deleted file mode 100644
index a583fa1b11..0000000000
--- a/src/gui/styles/images/media-skip-forward-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-stop-16.png b/src/gui/styles/images/media-stop-16.png
deleted file mode 100644
index 9ce035d696..0000000000
--- a/src/gui/styles/images/media-stop-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-stop-32.png b/src/gui/styles/images/media-stop-32.png
deleted file mode 100644
index aae24ba925..0000000000
--- a/src/gui/styles/images/media-stop-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-volume-16.png b/src/gui/styles/images/media-volume-16.png
deleted file mode 100644
index ad258340f2..0000000000
--- a/src/gui/styles/images/media-volume-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/media-volume-muted-16.png b/src/gui/styles/images/media-volume-muted-16.png
deleted file mode 100644
index 06bded21e7..0000000000
--- a/src/gui/styles/images/media-volume-muted-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/networkdrive-128.png b/src/gui/styles/images/networkdrive-128.png
deleted file mode 100644
index fd4a59c6bd..0000000000
--- a/src/gui/styles/images/networkdrive-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/networkdrive-16.png b/src/gui/styles/images/networkdrive-16.png
deleted file mode 100644
index 1bc62f766a..0000000000
--- a/src/gui/styles/images/networkdrive-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/networkdrive-32.png b/src/gui/styles/images/networkdrive-32.png
deleted file mode 100644
index 6a389dcae4..0000000000
--- a/src/gui/styles/images/networkdrive-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/newdirectory-128.png b/src/gui/styles/images/newdirectory-128.png
deleted file mode 100644
index fdbee27688..0000000000
--- a/src/gui/styles/images/newdirectory-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/newdirectory-16.png b/src/gui/styles/images/newdirectory-16.png
deleted file mode 100644
index 6c9f80318b..0000000000
--- a/src/gui/styles/images/newdirectory-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/newdirectory-32.png b/src/gui/styles/images/newdirectory-32.png
deleted file mode 100644
index 4fd0329216..0000000000
--- a/src/gui/styles/images/newdirectory-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/parentdir-128.png b/src/gui/styles/images/parentdir-128.png
deleted file mode 100644
index 84d14ab079..0000000000
--- a/src/gui/styles/images/parentdir-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/parentdir-16.png b/src/gui/styles/images/parentdir-16.png
deleted file mode 100644
index 665f8280f2..0000000000
--- a/src/gui/styles/images/parentdir-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/parentdir-32.png b/src/gui/styles/images/parentdir-32.png
deleted file mode 100644
index 44f3c4876d..0000000000
--- a/src/gui/styles/images/parentdir-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/refresh-24.png b/src/gui/styles/images/refresh-24.png
deleted file mode 100644
index 4c9b72c489..0000000000
--- a/src/gui/styles/images/refresh-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/refresh-32.png b/src/gui/styles/images/refresh-32.png
deleted file mode 100644
index eecde4b8f9..0000000000
--- a/src/gui/styles/images/refresh-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/right-128.png b/src/gui/styles/images/right-128.png
deleted file mode 100644
index 14b1cfd8eb..0000000000
--- a/src/gui/styles/images/right-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/right-16.png b/src/gui/styles/images/right-16.png
deleted file mode 100644
index 81ca628ff6..0000000000
--- a/src/gui/styles/images/right-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/right-32.png b/src/gui/styles/images/right-32.png
deleted file mode 100644
index 0f6ba8608b..0000000000
--- a/src/gui/styles/images/right-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-apply-128.png b/src/gui/styles/images/standardbutton-apply-128.png
deleted file mode 100644
index 85f07a57ef..0000000000
--- a/src/gui/styles/images/standardbutton-apply-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-apply-16.png b/src/gui/styles/images/standardbutton-apply-16.png
deleted file mode 100644
index 8f11ce6504..0000000000
--- a/src/gui/styles/images/standardbutton-apply-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-apply-32.png b/src/gui/styles/images/standardbutton-apply-32.png
deleted file mode 100644
index e8f7853a1e..0000000000
--- a/src/gui/styles/images/standardbutton-apply-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-cancel-128.png b/src/gui/styles/images/standardbutton-cancel-128.png
deleted file mode 100644
index 16d857030f..0000000000
--- a/src/gui/styles/images/standardbutton-cancel-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-cancel-16.png b/src/gui/styles/images/standardbutton-cancel-16.png
deleted file mode 100644
index 7bd25bd7c7..0000000000
--- a/src/gui/styles/images/standardbutton-cancel-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-cancel-32.png b/src/gui/styles/images/standardbutton-cancel-32.png
deleted file mode 100644
index 64a78727a1..0000000000
--- a/src/gui/styles/images/standardbutton-cancel-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-clear-128.png b/src/gui/styles/images/standardbutton-clear-128.png
deleted file mode 100644
index 107aea2234..0000000000
--- a/src/gui/styles/images/standardbutton-clear-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-clear-16.png b/src/gui/styles/images/standardbutton-clear-16.png
deleted file mode 100644
index 5359134c72..0000000000
--- a/src/gui/styles/images/standardbutton-clear-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-clear-32.png b/src/gui/styles/images/standardbutton-clear-32.png
deleted file mode 100644
index 8b85d6b7b3..0000000000
--- a/src/gui/styles/images/standardbutton-clear-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-close-128.png b/src/gui/styles/images/standardbutton-close-128.png
deleted file mode 100644
index 571aeae2bd..0000000000
--- a/src/gui/styles/images/standardbutton-close-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-close-16.png b/src/gui/styles/images/standardbutton-close-16.png
deleted file mode 100644
index e9e481987a..0000000000
--- a/src/gui/styles/images/standardbutton-close-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-close-32.png b/src/gui/styles/images/standardbutton-close-32.png
deleted file mode 100644
index 47e5733062..0000000000
--- a/src/gui/styles/images/standardbutton-close-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-closetab-16.png b/src/gui/styles/images/standardbutton-closetab-16.png
deleted file mode 100644
index 540694eae3..0000000000
--- a/src/gui/styles/images/standardbutton-closetab-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-closetab-down-16.png b/src/gui/styles/images/standardbutton-closetab-down-16.png
deleted file mode 100644
index ccec241652..0000000000
--- a/src/gui/styles/images/standardbutton-closetab-down-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-closetab-hover-16.png b/src/gui/styles/images/standardbutton-closetab-hover-16.png
deleted file mode 100644
index b22a0ffaf0..0000000000
--- a/src/gui/styles/images/standardbutton-closetab-hover-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-delete-128.png b/src/gui/styles/images/standardbutton-delete-128.png
deleted file mode 100644
index 11947ba681..0000000000
--- a/src/gui/styles/images/standardbutton-delete-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-delete-16.png b/src/gui/styles/images/standardbutton-delete-16.png
deleted file mode 100644
index 63fe93fe98..0000000000
--- a/src/gui/styles/images/standardbutton-delete-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-delete-32.png b/src/gui/styles/images/standardbutton-delete-32.png
deleted file mode 100644
index 336d965d1c..0000000000
--- a/src/gui/styles/images/standardbutton-delete-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-help-128.png b/src/gui/styles/images/standardbutton-help-128.png
deleted file mode 100644
index aa38e6fdfb..0000000000
--- a/src/gui/styles/images/standardbutton-help-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-help-16.png b/src/gui/styles/images/standardbutton-help-16.png
deleted file mode 100644
index e8299418da..0000000000
--- a/src/gui/styles/images/standardbutton-help-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-help-32.png b/src/gui/styles/images/standardbutton-help-32.png
deleted file mode 100644
index 310056a632..0000000000
--- a/src/gui/styles/images/standardbutton-help-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-no-128.png b/src/gui/styles/images/standardbutton-no-128.png
deleted file mode 100644
index 491c048ebd..0000000000
--- a/src/gui/styles/images/standardbutton-no-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-no-16.png b/src/gui/styles/images/standardbutton-no-16.png
deleted file mode 100644
index 812d3f57dd..0000000000
--- a/src/gui/styles/images/standardbutton-no-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-no-32.png b/src/gui/styles/images/standardbutton-no-32.png
deleted file mode 100644
index 9548d59196..0000000000
--- a/src/gui/styles/images/standardbutton-no-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-ok-128.png b/src/gui/styles/images/standardbutton-ok-128.png
deleted file mode 100644
index 63cc5279ae..0000000000
--- a/src/gui/styles/images/standardbutton-ok-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-ok-16.png b/src/gui/styles/images/standardbutton-ok-16.png
deleted file mode 100644
index fb4b4dbf96..0000000000
--- a/src/gui/styles/images/standardbutton-ok-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-ok-32.png b/src/gui/styles/images/standardbutton-ok-32.png
deleted file mode 100644
index 2dadd7a690..0000000000
--- a/src/gui/styles/images/standardbutton-ok-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-open-128.png b/src/gui/styles/images/standardbutton-open-128.png
deleted file mode 100644
index 8a052e829d..0000000000
--- a/src/gui/styles/images/standardbutton-open-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-open-16.png b/src/gui/styles/images/standardbutton-open-16.png
deleted file mode 100644
index 08cdc2b91f..0000000000
--- a/src/gui/styles/images/standardbutton-open-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-open-32.png b/src/gui/styles/images/standardbutton-open-32.png
deleted file mode 100644
index db33c79852..0000000000
--- a/src/gui/styles/images/standardbutton-open-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-save-128.png b/src/gui/styles/images/standardbutton-save-128.png
deleted file mode 100644
index fc6fd7ce1d..0000000000
--- a/src/gui/styles/images/standardbutton-save-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-save-16.png b/src/gui/styles/images/standardbutton-save-16.png
deleted file mode 100644
index dd4e228280..0000000000
--- a/src/gui/styles/images/standardbutton-save-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-save-32.png b/src/gui/styles/images/standardbutton-save-32.png
deleted file mode 100644
index 177678c963..0000000000
--- a/src/gui/styles/images/standardbutton-save-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-yes-128.png b/src/gui/styles/images/standardbutton-yes-128.png
deleted file mode 100644
index 79c8296016..0000000000
--- a/src/gui/styles/images/standardbutton-yes-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-yes-16.png b/src/gui/styles/images/standardbutton-yes-16.png
deleted file mode 100644
index cc16dbbec3..0000000000
--- a/src/gui/styles/images/standardbutton-yes-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/standardbutton-yes-32.png b/src/gui/styles/images/standardbutton-yes-32.png
deleted file mode 100644
index e3340c6453..0000000000
--- a/src/gui/styles/images/standardbutton-yes-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/stop-24.png b/src/gui/styles/images/stop-24.png
deleted file mode 100644
index 99856e9640..0000000000
--- a/src/gui/styles/images/stop-24.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/stop-32.png b/src/gui/styles/images/stop-32.png
deleted file mode 100644
index 4f4952bb2a..0000000000
--- a/src/gui/styles/images/stop-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/trash-128.png b/src/gui/styles/images/trash-128.png
deleted file mode 100644
index 334fe5b6f3..0000000000
--- a/src/gui/styles/images/trash-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/trash-16.png b/src/gui/styles/images/trash-16.png
deleted file mode 100644
index c471791ee8..0000000000
--- a/src/gui/styles/images/trash-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/trash-32.png b/src/gui/styles/images/trash-32.png
deleted file mode 100644
index 68625cf698..0000000000
--- a/src/gui/styles/images/trash-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/up-128.png b/src/gui/styles/images/up-128.png
deleted file mode 100644
index c10df10677..0000000000
--- a/src/gui/styles/images/up-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/up-16.png b/src/gui/styles/images/up-16.png
deleted file mode 100644
index 33e939db8f..0000000000
--- a/src/gui/styles/images/up-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/up-32.png b/src/gui/styles/images/up-32.png
deleted file mode 100644
index d7157c9476..0000000000
--- a/src/gui/styles/images/up-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/viewdetailed-128.png b/src/gui/styles/images/viewdetailed-128.png
deleted file mode 100644
index 363937a857..0000000000
--- a/src/gui/styles/images/viewdetailed-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/viewdetailed-16.png b/src/gui/styles/images/viewdetailed-16.png
deleted file mode 100644
index 44a14b923a..0000000000
--- a/src/gui/styles/images/viewdetailed-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/viewdetailed-32.png b/src/gui/styles/images/viewdetailed-32.png
deleted file mode 100644
index fac1a3e683..0000000000
--- a/src/gui/styles/images/viewdetailed-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/viewlist-128.png b/src/gui/styles/images/viewlist-128.png
deleted file mode 100644
index cc301059c1..0000000000
--- a/src/gui/styles/images/viewlist-128.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/viewlist-16.png b/src/gui/styles/images/viewlist-16.png
deleted file mode 100644
index 9132877ff6..0000000000
--- a/src/gui/styles/images/viewlist-16.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/images/viewlist-32.png b/src/gui/styles/images/viewlist-32.png
deleted file mode 100644
index fae3c24536..0000000000
--- a/src/gui/styles/images/viewlist-32.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/styles/qcdestyle.cpp b/src/gui/styles/qcdestyle.cpp
deleted file mode 100644
index 5acf399396..0000000000
--- a/src/gui/styles/qcdestyle.cpp
+++ /dev/null
@@ -1,305 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcdestyle.h"
-
-#if !defined(QT_NO_STYLE_CDE) || defined(QT_PLUGIN)
-
-#include "qmenu.h"
-#include "qapplication.h"
-#include "qpainter.h"
-#include "qdrawutil.h"
-#include "qpixmap.h"
-#include "qpalette.h"
-#include "qwidget.h"
-#include "qpushbutton.h"
-#include "qscrollbar.h"
-#include "qtabbar.h"
-#include "qtabwidget.h"
-#include "qlistview.h"
-#include "qsplitter.h"
-#include "qslider.h"
-#include "qcombobox.h"
-#include "qlineedit.h"
-#include "qprogressbar.h"
-#include "qimage.h"
-#include "qfocusframe.h"
-#include "qpainterpath.h"
-#include "qdebug.h"
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QCDEStyle
- \brief The QCDEStyle class provides a CDE look and feel.
-
- \ingroup appearance
-
- This style provides a slightly improved Motif look similar to some
- versions of the Common Desktop Environment (CDE). The main
- differences are thinner frames and more modern radio buttons and
- checkboxes. Together with a dark background and a bright
- text/foreground color, the style looks quite attractive (at least
- for Motif fans).
-
- Note that most of the functions provided by QCDEStyle are
- reimplementations of QStyle functions; see QStyle for their
- documentation. QCDEStyle provides overloads for drawControl() and
- drawPrimitive() which are documented here.
-
- \img qcdestyle.png
- \sa QWindowsXPStyle, QMacStyle, QWindowsStyle, QPlastiqueStyle, QMotifStyle
-*/
-
-/*!
- Constructs a QCDEStyle.
-
- If \a useHighlightCols is false (the default), then the style will
- polish the application's color palette to emulate the Motif way of
- highlighting, which is a simple inversion between the base and the
- text color.
-*/
-QCDEStyle::QCDEStyle(bool useHighlightCols)
- : QMotifStyle(useHighlightCols)
-{
-}
-
-/*!
- Destroys the style.
-*/
-QCDEStyle::~QCDEStyle()
-{
-}
-
-
-/*!\reimp
-*/
-int QCDEStyle::pixelMetric(PixelMetric metric, const QStyleOption *option,
- const QWidget *widget) const
-/*
-int QCDEStyle::pixelMetric(PixelMetric metric, const QStyleOption *option,
- const QWidget *widget) const
- */
-{
- int ret = 0;
-
- switch(metric) {
- case PM_MenuBarPanelWidth:
- case PM_DefaultFrameWidth:
- case PM_FocusFrameVMargin:
- case PM_FocusFrameHMargin:
- case PM_MenuPanelWidth:
- case PM_SpinBoxFrameWidth:
- case PM_MenuBarVMargin:
- case PM_MenuBarHMargin:
- case PM_DockWidgetFrameWidth:
- ret = 1;
- break;
- case PM_ScrollBarExtent:
- ret = 13;
- break;
- default:
- ret = QMotifStyle::pixelMetric(metric, option, widget);
- break;
- }
- return ret;
-}
-
-/*!
- \reimp
-*/
-void QCDEStyle::drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *widget) const
-{
-
- switch(element) {
- case CE_MenuBarItem: {
- if (opt->state & State_Selected) // active item
- qDrawShadePanel(p, opt->rect, opt->palette, true, 1,
- &opt->palette.brush(QPalette::Button));
- else // other item
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Button));
- QCommonStyle::drawControl(element, opt, p, widget);
- break; }
- case CE_RubberBand: {
- p->save();
- p->setClipping(false);
- QPainterPath path;
- path.addRect(opt->rect);
- path.addRect(opt->rect.adjusted(2, 2, -2, -2));
- p->fillPath(path, opt->palette.color(QPalette::Active, QPalette::Text));
- p->restore();
- break; }
- default:
- QMotifStyle::drawControl(element, opt, p, widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-void QCDEStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *widget) const
-{
- switch(pe) {
- case PE_IndicatorCheckBox: {
- bool down = opt->state & State_Sunken;
- bool on = opt->state & State_On;
- bool showUp = !(down ^ on);
- QBrush fill = (showUp || (opt->state & State_NoChange)) ? opt->palette.brush(QPalette::Button) : opt->palette.brush(QPalette::Mid);
- qDrawShadePanel(p, opt->rect, opt->palette, !showUp, pixelMetric(PM_DefaultFrameWidth), &opt->palette.brush(QPalette::Button));
-
- if (on || (opt->state & State_NoChange)) {
- QRect r = opt->rect;
- QPolygon a(7 * 2);
- int i, xx, yy;
- xx = r.x() + 3;
- yy = r.y() + 5;
- if (opt->rect.width() <= 9) {
- // When called from CE_MenuItem in QMotifStyle
- xx -= 2;
- yy -= 2;
- }
-
- for (i = 0; i < 3; i++) {
- a.setPoint(2 * i, xx, yy);
- a.setPoint(2 * i + 1, xx, yy + 2);
- xx++; yy++;
- }
- yy -= 2;
- for (i = 3; i < 7; i++) {
- a.setPoint(2 * i, xx, yy);
- a.setPoint(2 * i + 1, xx, yy + 2);
- xx++; yy--;
- }
- if (opt->state & State_NoChange)
- p->setPen(opt->palette.dark().color());
- else
- p->setPen(opt->palette.foreground().color());
- p->drawPolyline(a);
- }
- if (!(opt->state & State_Enabled) && styleHint(SH_DitherDisabledText))
- p->fillRect(opt->rect, QBrush(p->background().color(), Qt::Dense5Pattern));
- } break;
- case PE_IndicatorRadioButton:
- {
- QRect r = opt->rect;
-#define INTARRLEN(x) sizeof(x)/(sizeof(int)*2)
- static const int pts1[] = { // up left lines
- 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 };
- static const int pts4[] = { // bottom right lines
- 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7,
- 11,4, 10,3, 10,2 };
- static const int pts5[] = { // inner fill
- 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 };
- bool down = opt->state & State_Sunken;
- bool on = opt->state & State_On;
- QPolygon a(INTARRLEN(pts1), pts1);
-
- //center when rect is larger than indicator size
- int xOffset = 0;
- int yOffset = 0;
- int indicatorWidth = pixelMetric(PM_ExclusiveIndicatorWidth);
- int indicatorHeight = pixelMetric(PM_ExclusiveIndicatorWidth);
- if (r.width() > indicatorWidth)
- xOffset += (r.width() - indicatorWidth)/2;
- if (r.height() > indicatorHeight)
- yOffset += (r.height() - indicatorHeight)/2;
- p->translate(xOffset, yOffset);
-
- a.translate(r.x(), r.y());
- QPen oldPen = p->pen();
- QBrush oldBrush = p->brush();
- p->setPen((down || on) ? opt->palette.dark().color() : opt->palette.light().color());
- p->drawPolyline(a);
- a.setPoints(INTARRLEN(pts4), pts4);
- a.translate(r.x(), r.y());
- p->setPen((down || on) ? opt->palette.light().color() : opt->palette.dark().color());
- p->drawPolyline(a);
- a.setPoints(INTARRLEN(pts5), pts5);
- a.translate(r.x(), r.y());
- QColor fillColor = on ? opt->palette.dark().color() : opt->palette.background().color();
- p->setPen(fillColor);
- p->setBrush(on ? opt->palette.brush(QPalette::Dark) :
- opt->palette.brush(QPalette::Window));
- p->drawPolygon(a);
- if (!(opt->state & State_Enabled) && styleHint(SH_DitherDisabledText))
- p->fillRect(opt->rect, QBrush(p->background().color(), Qt::Dense5Pattern));
- p->setPen(oldPen);
- p->setBrush(oldBrush);
-
- p->translate(-xOffset, -yOffset);
-
- } break;
- default:
- QMotifStyle::drawPrimitive(pe, opt, p, widget);
- }
-}
-
-/*!\reimp*/
-QPalette QCDEStyle::standardPalette() const
-{
- QColor background(0xb6, 0xb6, 0xcf);
- QColor light = background.lighter();
- QColor mid = background.darker(150);
- QColor dark = background.darker();
- QPalette palette(Qt::black, background, light, dark, mid, Qt::black, Qt::white);
- palette.setBrush(QPalette::Disabled, QPalette::WindowText, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Text, dark);
- palette.setBrush(QPalette::Disabled, QPalette::ButtonText, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Base, background);
- return palette;
-}
-
-/*!
- \internal
-*/
-QIcon QCDEStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt,
- const QWidget *widget) const
-{
- return QMotifStyle::standardIconImplementation(standardIcon, opt, widget);
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/styles/qcdestyle.h b/src/gui/styles/qcdestyle.h
deleted file mode 100644
index ca43b6a530..0000000000
--- a/src/gui/styles/qcdestyle.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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 QCDESTYLE_H
-#define QCDESTYLE_H
-
-#include <QtGui/qmotifstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_CDE)
-
-class Q_GUI_EXPORT QCDEStyle : public QMotifStyle
-{
- Q_OBJECT
-public:
- explicit QCDEStyle(bool useHighlightCols = false);
- virtual ~QCDEStyle();
-
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
- void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- QPalette standardPalette() const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
-};
-
-#endif // QT_NO_STYLE_CDE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCDESTYLE_H
diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp
deleted file mode 100644
index cc5fe10692..0000000000
--- a/src/gui/styles/qcleanlooksstyle.cpp
+++ /dev/null
@@ -1,4466 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcleanlooksstyle.h"
-#include "qcleanlooksstyle_p.h"
-
-#if !defined(QT_NO_STYLE_CLEANLOOKS) || defined(QT_PLUGIN)
-
-#include "qwindowsstyle_p.h"
-#include <qcombobox.h>
-#include <qpushbutton.h>
-#include <qpainter.h>
-#include <qdir.h>
-#include <qhash.h>
-#include <qstyleoption.h>
-#include <qapplication.h>
-#include <qmainwindow.h>
-#include <qfont.h>
-#include <qgroupbox.h>
-#include <qprocess.h>
-#include <qpixmapcache.h>
-#include <qdialogbuttonbox.h>
-#include <qscrollbar.h>
-#include <qspinbox.h>
-#include <qslider.h>
-#include <qsplitter.h>
-#include <qprogressbar.h>
-#include <qtoolbar.h>
-#include <qwizard.h>
-#include <qlibrary.h>
-#include <private/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-using namespace QStyleHelper;
-
-enum Direction {
- TopDown,
- FromLeft,
- BottomUp,
- FromRight
-};
-
-// from windows style
-static const int windowsItemFrame = 2; // menu item frame width
-static const int windowsItemHMargin = 3; // menu item hor text margin
-static const int windowsItemVMargin = 8; // menu item ver text margin
-static const int windowsRightBorder = 15; // right border on windows
-
-/* XPM */
-static const char * const dock_widget_close_xpm[] = {
- "11 13 7 1",
- " c None",
- ". c #D5CFCB",
- "+ c #8F8B88",
- "@ c #6C6A67",
- "# c #ABA6A3",
- "$ c #B5B0AC",
- "% c #A4A09D",
- " ",
- " +@@@@@@@+ ",
- "+# #+",
- "@ $@ @$ @",
- "@ @@@ @@@ @",
- "@ @@@@@ @",
- "@ @@@ @",
- "@ @@@@@ @",
- "@ @@@ @@@ @",
- "@ $@ @$ @",
- "+% #+",
- " +@@@@@@@+ ",
- " "};
-
-static const char * const qt_cleanlooks_arrow_down_xpm[] = {
- "11 7 2 1",
- " c None",
- "x c #000000",
- " ",
- " x x ",
- " xxx xxx ",
- " xxxxxxx ",
- " xxxxx ",
- " xxx ",
- " x "};
-
-static const char * const qt_cleanlooks_arrow_up_xpm[] = {
- "11 7 2 1",
- " c None",
- "x c #000000",
- " x ",
- " xxx ",
- " xxxxx ",
- " xxxxxxx ",
- " xxx xxx ",
- " x x ",
- " "};
-
-static const char * const dock_widget_restore_xpm[] = {
- "11 13 7 1",
- " c None",
- ". c #D5CFCB",
- "+ c #8F8B88",
- "@ c #6C6A67",
- "# c #ABA6A3",
- "$ c #B5B0AC",
- "% c #A4A09D",
- " ",
- " +@@@@@@@+ ",
- "+# #+",
- "@ #@@@# @",
- "@ @ @ @",
- "@ #@@@# @ @",
- "@ @ @ @ @",
- "@ @ @@@ @",
- "@ @ @ @",
- "@ #@@@# @",
- "+% #+",
- " +@@@@@@@+ ",
- " "};
-
-static const char * const workspace_minimize[] = {
- "11 13 7 1",
- " c None",
- ". c #D5CFCB",
- "+ c #8F8B88",
- "@ c #6C6A67",
- "# c #ABA6A3",
- "$ c #B5B0AC",
- "% c #A4A09D",
- " ",
- " +@@@@@@@+ ",
- "+# #+",
- "@ @",
- "@ @",
- "@ @",
- "@ @@@@@@@ @",
- "@ @@@@@@@ @",
- "@ @",
- "@ @",
- "+% #+",
- " +@@@@@@@+ ",
- " "};
-
-
-static const char * const qt_titlebar_context_help[] = {
- "10 10 3 1",
- " c None",
- "# c #000000",
- "+ c #444444",
- " +####+ ",
- " ### ### ",
- " ## ## ",
- " +##+ ",
- " +## ",
- " ## ",
- " ## ",
- " ",
- " ## ",
- " ## "};
-
-static const char * const qt_cleanlooks_radiobutton[] = {
- "13 13 9 1",
- " c None",
- ". c #ABA094",
- "+ c #B7ADA0",
- "@ c #C4BBB2",
- "# c #DDD4CD",
- "$ c #E7E1E0",
- "% c #F4EFED",
- "& c #FFFAF9",
- "* c #FCFEFB",
- " #@...@# ",
- " @+@#$$#+@ ",
- " @+$%%***&@@ ",
- "#+$%**&&**&+#",
- "@@$&&******#@",
- ".#**********.",
- ".$&******&*&.",
- ".$*&******&*.",
- "+#********&#@",
- "#+*********+#",
- " @@*******@@ ",
- " @+#%*%#+@ ",
- " #@...+# "};
-
-static const char * const qt_cleanlooks_radiobutton_checked[] = {
- "13 13 20 1",
- " c None",
- ". c #A8ABAE",
- "+ c #596066",
- "@ c #283138",
- "# c #A9ACAF",
- "$ c #A6A9AB",
- "% c #6B7378",
- "& c #8C9296",
- "* c #A2A6AA",
- "= c #61696F",
- "- c #596065",
- "; c #93989C",
- "> c #777E83",
- ", c #60686E",
- "' c #252D33",
- ") c #535B62",
- "! c #21292E",
- "~ c #242B31",
- "{ c #1F262B",
- "] c #41484E",
- " ",
- " ",
- " ",
- " .+@+# ",
- " $%&*&=# ",
- " -&;>,'+ ",
- " @*>,)!@ ",
- " +&,)~{+ ",
- " #='!{]# ",
- " #+@+# ",
- " ",
- " ",
- " "};
-
-
-static const char * const qt_scrollbar_button_arrow_left[] = {
- "4 7 2 1",
- " c None",
- "* c #BFBFBF",
- " *",
- " **",
- " ***",
- "****",
- " ***",
- " **",
- " *"};
-
-static const char * const qt_scrollbar_button_arrow_right[] = {
- "4 7 2 1",
- " c None",
- "* c #BFBFBF",
- "* ",
- "** ",
- "*** ",
- "****",
- "*** ",
- "** ",
- "* "};
-
-static const char * const qt_scrollbar_button_arrow_up[] = {
- "7 4 2 1",
- " c None",
- "* c #BFBFBF",
- " * ",
- " *** ",
- " ***** ",
- "*******"};
-
-static const char * const qt_scrollbar_button_arrow_down[] = {
- "7 4 2 1",
- " c None",
- "* c #BFBFBF",
- "*******",
- " ***** ",
- " *** ",
- " * "};
-
-static const char * const qt_spinbox_button_arrow_down[] = {
- "7 4 2 1",
- " c None",
- "* c #BFBFBF",
- "*******",
- " ***** ",
- " *** ",
- " * "};
-
-static const char * const qt_spinbox_button_arrow_up[] = {
- "7 4 2 1",
- " c None",
- "* c #BFBFBF",
- " * ",
- " *** ",
- " ***** ",
- "*******"};
-
-static const char * const qt_scrollbar_button_left[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- " .++++++++++++++",
- ".+#############+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- ".+<<<<<<<<<<<<<+",
- " .++++++++++++++"};
-
-static const char * const qt_scrollbar_button_right[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- "++++++++++++++. ",
- "+#############+.",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+<<<<<<<<<<<<<+.",
- "++++++++++++++. "};
-
-static const char * const qt_scrollbar_button_up[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- " .++++++++++++. ",
- ".+############+.",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+<<<<<<<<<<<<<<+",
- "++++++++++++++++"};
-
-static const char * const qt_scrollbar_button_down[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- "++++++++++++++++",
- "+##############+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- ".+<<<<<<<<<<<<+.",
- " .++++++++++++. "};
-
-static const char * const qt_cleanlooks_menuitem_checkbox_checked[] = {
- "8 7 6 1",
- " g None",
- ". g #959595",
- "+ g #676767",
- "@ g #454545",
- "# g #1D1D1D",
- "0 g #101010",
- " ..",
- " .+ ",
- " .+ ",
- "0 .@ ",
- "@#++. ",
- " @# ",
- " . "};
-
-static const char * const qt_cleanlooks_checkbox_checked[] = {
- "13 13 3 1",
- " c None",
- ". c #272D33",
- "% c #666666",
-
- " ",
- " % ",
- " %. ",
- " %.% ",
- " %.. ",
- " %.% %.. ",
- " %..%..% ",
- " %...% ",
- " %..% ",
- " %.% ",
- " % ",
- " ",
- " "};
-
-static void qt_cleanlooks_draw_gradient(QPainter *painter, const QRect &rect, const QColor &gradientStart,
- const QColor &gradientStop, Direction direction = TopDown, QBrush bgBrush = QBrush())
-{
- int x = rect.center().x();
- int y = rect.center().y();
- QLinearGradient *gradient;
- switch(direction) {
- case FromLeft:
- gradient = new QLinearGradient(rect.left(), y, rect.right(), y);
- break;
- case FromRight:
- gradient = new QLinearGradient(rect.right(), y, rect.left(), y);
- break;
- case BottomUp:
- gradient = new QLinearGradient(x, rect.bottom(), x, rect.top());
- break;
- case TopDown:
- default:
- gradient = new QLinearGradient(x, rect.top(), x, rect.bottom());
- break;
- }
- if (bgBrush.gradient())
- gradient->setStops(bgBrush.gradient()->stops());
- else {
- gradient->setColorAt(0, gradientStart);
- gradient->setColorAt(1, gradientStop);
- }
- painter->fillRect(rect, *gradient);
- delete gradient;
-}
-
-static void qt_cleanlooks_draw_buttongradient(QPainter *painter, const QRect &rect, const QColor &gradientStart,
- const QColor &gradientMid, const QColor &gradientStop, Direction direction = TopDown,
- QBrush bgBrush = QBrush())
-{
- int x = rect.center().x();
- int y = rect.center().y();
- QLinearGradient *gradient;
- bool horizontal = false;
- switch(direction) {
- case FromLeft:
- horizontal = true;
- gradient = new QLinearGradient(rect.left(), y, rect.right(), y);
- break;
- case FromRight:
- horizontal = true;
- gradient = new QLinearGradient(rect.right(), y, rect.left(), y);
- break;
- case BottomUp:
- gradient = new QLinearGradient(x, rect.bottom(), x, rect.top());
- break;
- case TopDown:
- default:
- gradient = new QLinearGradient(x, rect.top(), x, rect.bottom());
- break;
- }
- if (bgBrush.gradient())
- gradient->setStops(bgBrush.gradient()->stops());
- else {
- int size = horizontal ? rect.width() : rect.height() ;
- if (size > 4) {
- float edge = 4.0/(float)size;
- gradient->setColorAt(0, gradientStart);
- gradient->setColorAt(edge, gradientMid.lighter(104));
- gradient->setColorAt(1.0 - edge, gradientMid.darker(100));
- gradient->setColorAt(1.0, gradientStop);
- }
- }
- painter->fillRect(rect, *gradient);
- delete gradient;
-}
-
-static void qt_cleanlooks_draw_mdibutton(QPainter *painter, const QStyleOptionTitleBar *option, const QRect &tmp, bool hover, bool sunken)
-{
- QColor dark;
- dark.setHsv(option->palette.button().color().hue(),
- qMin(255, (int)(option->palette.button().color().saturation()*1.9)),
- qMin(255, (int)(option->palette.button().color().value()*0.7)));
-
- QColor highlight = option->palette.highlight().color();
-
- bool active = (option->titleBarState & QStyle::State_Active);
- QColor titleBarHighlight(255, 255, 255, 60);
-
- if (sunken)
- painter->fillRect(tmp.adjusted(1, 1, -1, -1), option->palette.highlight().color().darker(120));
- else if (hover)
- painter->fillRect(tmp.adjusted(1, 1, -1, -1), QColor(255, 255, 255, 20));
-
- QColor mdiButtonGradientStartColor;
- QColor mdiButtonGradientStopColor;
-
- mdiButtonGradientStartColor = QColor(0, 0, 0, 40);
- mdiButtonGradientStopColor = QColor(255, 255, 255, 60);
-
- if (sunken)
- titleBarHighlight = highlight.darker(130);
-
- QLinearGradient gradient(tmp.center().x(), tmp.top(), tmp.center().x(), tmp.bottom());
- gradient.setColorAt(0, mdiButtonGradientStartColor);
- gradient.setColorAt(1, mdiButtonGradientStopColor);
- QColor mdiButtonBorderColor(active ? option->palette.highlight().color().darker(180): dark.darker(110));
-
- painter->setPen(QPen(mdiButtonBorderColor, 1));
- const QLine lines[4] = {
- QLine(tmp.left() + 2, tmp.top(), tmp.right() - 2, tmp.top()),
- QLine(tmp.left() + 2, tmp.bottom(), tmp.right() - 2, tmp.bottom()),
- QLine(tmp.left(), tmp.top() + 2, tmp.left(), tmp.bottom() - 2),
- QLine(tmp.right(), tmp.top() + 2, tmp.right(), tmp.bottom() - 2)
- };
- painter->drawLines(lines, 4);
- const QPoint points[4] = {
- QPoint(tmp.left() + 1, tmp.top() + 1),
- QPoint(tmp.right() - 1, tmp.top() + 1),
- QPoint(tmp.left() + 1, tmp.bottom() - 1),
- QPoint(tmp.right() - 1, tmp.bottom() - 1)
- };
- painter->drawPoints(points, 4);
-
- painter->setPen(titleBarHighlight);
- painter->drawLine(tmp.left() + 2, tmp.top() + 1, tmp.right() - 2, tmp.top() + 1);
- painter->drawLine(tmp.left() + 1, tmp.top() + 2, tmp.left() + 1, tmp.bottom() - 2);
-
- painter->setPen(QPen(gradient, 1));
- painter->drawLine(tmp.right() + 1, tmp.top() + 2, tmp.right() + 1, tmp.bottom() - 2);
- painter->drawPoint(tmp.right() , tmp.top() + 1);
-
- painter->drawLine(tmp.left() + 2, tmp.bottom() + 1, tmp.right() - 2, tmp.bottom() + 1);
- painter->drawPoint(tmp.left() + 1, tmp.bottom());
- painter->drawPoint(tmp.right() - 1, tmp.bottom());
- painter->drawPoint(tmp.right() , tmp.bottom() - 1);
-}
-
-/*!
- \class QCleanlooksStyle
- \brief The QCleanlooksStyle class provides a widget style similar to the
- Clearlooks style available in GNOME.
- \since 4.2
-
- The Cleanlooks style provides a look and feel for widgets
- that closely resembles the Clearlooks style, introduced by Richard
- Stellingwerff and Daniel Borgmann.
-
- \sa {Cleanlooks Style Widget Gallery}, QWindowsXPStyle, QMacStyle, QWindowsStyle,
- QCDEStyle, QMotifStyle, QPlastiqueStyle
-*/
-
-/*!
- Constructs a QCleanlooksStyle object.
-*/
-QCleanlooksStyle::QCleanlooksStyle() : QWindowsStyle(*new QCleanlooksStylePrivate)
-{
- setObjectName(QLatin1String("CleanLooks"));
-}
-
-/*!
- \internal
-
- Constructs a QCleanlooksStyle object.
-*/
-QCleanlooksStyle::QCleanlooksStyle(QCleanlooksStylePrivate &dd) : QWindowsStyle(dd)
-{
-}
-
-/*!
- Destroys the QCleanlooksStyle object.
-*/
-QCleanlooksStyle::~QCleanlooksStyle()
-{
-}
-
-/*!
- \fn void QCleanlooksStyle::drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const
-
- Draws the given \a text in the specified \a rectangle using the
- provided \a painter and \a palette.
-
- Text is drawn using the painter's pen. If an explicit \a textRole
- is specified, then the text is drawn using the \a palette's color
- for the specified role. The \a enabled value indicates whether or
- not the item is enabled; when reimplementing, this value should
- influence how the item is drawn.
-
- The text is aligned and wrapped according to the specified \a
- alignment.
-
- \sa Qt::Alignment
-*/
-void QCleanlooksStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const
-{
- if (text.isEmpty())
- return;
-
- QPen savedPen = painter->pen();
- if (textRole != QPalette::NoRole) {
- painter->setPen(QPen(pal.brush(textRole), savedPen.widthF()));
- }
- if (!enabled) {
- QPen pen = painter->pen();
- painter->setPen(pen);
- }
- painter->drawText(rect, alignment, text);
- painter->setPen(savedPen);
-}
-
-static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50)
-{
- const int maxFactor = 100;
- QColor tmp = colorA;
- tmp.setRed((tmp.red() * factor) / maxFactor + (colorB.red() * (maxFactor - factor)) / maxFactor);
- tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor);
- tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor);
- return tmp;
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::drawPrimitive(PrimitiveElement elem,
- const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const
-{
- Q_ASSERT(option);
- QRect rect = option->rect;
- int state = option->state;
- QColor button = option->palette.button().color();
- QColor buttonShadow = option->palette.button().color().darker(110);
- QColor buttonShadowAlpha = buttonShadow;
- buttonShadowAlpha.setAlpha(128);
- QColor darkOutline;
- QColor dark;
- darkOutline.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*3.0)),
- qMin(255, (int)(button.value()*0.6)));
- dark.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*1.9)),
- qMin(255, (int)(button.value()*0.7)));
- QColor tabFrameColor = mergedColors(option->palette.background().color(),
- dark.lighter(135), 60);
-
- switch(elem) {
-#ifndef QT_NO_TABBAR
- case PE_FrameTabBarBase:
- if (const QStyleOptionTabBarBase *tbb
- = qstyleoption_cast<const QStyleOptionTabBarBase *>(option)) {
- painter->save();
- painter->setPen(QPen(darkOutline.lighter(110), 0));
- switch (tbb->shape) {
- case QTabBar::RoundedNorth: {
- QRegion region(tbb->rect);
- region -= tbb->selectedTabRect;
- painter->drawLine(tbb->rect.topLeft(), tbb->rect.topRight());
- painter->setClipRegion(region);
- painter->setPen(option->palette.light().color());
- painter->drawLine(tbb->rect.topLeft() + QPoint(0, 1),
- tbb->rect.topRight() + QPoint(0, 1));
- }
- break;
- case QTabBar::RoundedWest:
- painter->drawLine(tbb->rect.left(), tbb->rect.top(), tbb->rect.left(), tbb->rect.bottom());
- break;
- case QTabBar::RoundedSouth:
- painter->drawLine(tbb->rect.left(), tbb->rect.bottom(),
- tbb->rect.right(), tbb->rect.bottom());
- break;
- case QTabBar::RoundedEast:
- painter->drawLine(tbb->rect.topRight(), tbb->rect.bottomRight());
- break;
- case QTabBar::TriangularNorth:
- case QTabBar::TriangularEast:
- case QTabBar::TriangularWest:
- case QTabBar::TriangularSouth:
- painter->restore();
- QWindowsStyle::drawPrimitive(elem, option, painter, widget);
- return;
- }
- painter->restore();
- }
- return;
-#endif // QT_NO_TABBAR
- case PE_IndicatorViewItemCheck:
- {
- QStyleOptionButton button;
- button.QStyleOption::operator=(*option);
- button.state &= ~State_MouseOver;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &button, painter, widget);
- }
- return;
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- QRect r = header->rect;
- QImage arrow;
- if (header->sortIndicator & QStyleOptionHeader::SortUp)
- arrow = QImage(qt_cleanlooks_arrow_up_xpm);
- else if (header->sortIndicator & QStyleOptionHeader::SortDown)
- arrow = QImage(qt_cleanlooks_arrow_down_xpm);
- if (!arrow.isNull()) {
- r.setSize(arrow.size());
- r.moveCenter(header->rect.center());
- arrow.setColor(1, header->palette.foreground().color().rgba());
- painter->drawImage(r, arrow);
- }
- }
- break;
- case PE_IndicatorButtonDropDown:
- proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
- break;
- case PE_IndicatorToolBarSeparator:
- {
- QRect rect = option->rect;
- const int margin = 6;
- if (option->state & State_Horizontal) {
- const int offset = rect.width()/2;
- painter->setPen(QPen(option->palette.background().color().darker(110)));
- painter->drawLine(rect.bottomLeft().x() + offset,
- rect.bottomLeft().y() - margin,
- rect.topLeft().x() + offset,
- rect.topLeft().y() + margin);
- painter->setPen(QPen(option->palette.background().color().lighter(110)));
- painter->drawLine(rect.bottomLeft().x() + offset + 1,
- rect.bottomLeft().y() - margin,
- rect.topLeft().x() + offset + 1,
- rect.topLeft().y() + margin);
- } else { //Draw vertical separator
- const int offset = rect.height()/2;
- painter->setPen(QPen(option->palette.background().color().darker(110)));
- painter->drawLine(rect.topLeft().x() + margin ,
- rect.topLeft().y() + offset,
- rect.topRight().x() - margin,
- rect.topRight().y() + offset);
- painter->setPen(QPen(option->palette.background().color().lighter(110)));
- painter->drawLine(rect.topLeft().x() + margin ,
- rect.topLeft().y() + offset + 1,
- rect.topRight().x() - margin,
- rect.topRight().y() + offset + 1);
- }
- }
- break;
- case PE_Frame:
- painter->save();
- painter->setPen(dark.lighter(108));
- painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
- painter->restore();
- break;
- case PE_FrameMenu:
- painter->save();
- {
- painter->setPen(QPen(darkOutline, 1));
- painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
- QColor frameLight = option->palette.background().color().lighter(160);
- QColor frameShadow = option->palette.background().color().darker(110);
-
- //paint beveleffect
- QRect frame = option->rect.adjusted(1, 1, -1, -1);
- painter->setPen(frameLight);
- painter->drawLine(frame.topLeft(), frame.bottomLeft());
- painter->drawLine(frame.topLeft(), frame.topRight());
-
- painter->setPen(frameShadow);
- painter->drawLine(frame.topRight(), frame.bottomRight());
- painter->drawLine(frame.bottomLeft(), frame.bottomRight());
- }
- painter->restore();
- break;
- case PE_FrameDockWidget:
-
- painter->save();
- {
- QColor softshadow = option->palette.background().color().darker(120);
-
- QRect rect= option->rect;
- painter->setPen(softshadow);
- painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
- painter->setPen(QPen(option->palette.light(), 0));
- painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1), QPoint(rect.left() + 1, rect.bottom() - 1));
- painter->setPen(QPen(option->palette.background().color().darker(120), 0));
- painter->drawLine(QPoint(rect.left() + 1, rect.bottom() - 1), QPoint(rect.right() - 2, rect.bottom() - 1));
- painter->drawLine(QPoint(rect.right() - 1, rect.top() + 1), QPoint(rect.right() - 1, rect.bottom() - 1));
-
- }
- painter->restore();
- break;
- case PE_PanelButtonTool:
- painter->save();
- if ((option->state & State_Enabled || option->state & State_On) || !(option->state & State_AutoRaise)) {
- QRect rect = option->rect;
- QPen oldPen = painter->pen();
-
- if (widget && widget->inherits("QDockWidgetTitleButton")) {
- if (option->state & State_MouseOver)
- proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
- } else {
- proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
- }
- }
- painter->restore();
- break;
- case PE_IndicatorDockWidgetResizeHandle:
- {
- QStyleOption dockWidgetHandle = *option;
- bool horizontal = option->state & State_Horizontal;
- if (horizontal)
- dockWidgetHandle.state &= ~State_Horizontal;
- else
- dockWidgetHandle.state |= State_Horizontal;
- proxy()->drawControl(CE_Splitter, &dockWidgetHandle, painter, widget);
- }
- break;
- case PE_FrameWindow:
- painter->save();
- {
- QRect rect= option->rect;
- painter->setPen(QPen(dark.darker(150), 0));
- painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
- painter->setPen(QPen(option->palette.light(), 0));
- painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1),
- QPoint(rect.left() + 1, rect.bottom() - 1));
- painter->setPen(QPen(option->palette.background().color().darker(120), 0));
- painter->drawLine(QPoint(rect.left() + 1, rect.bottom() - 1),
- QPoint(rect.right() - 2, rect.bottom() - 1));
- painter->drawLine(QPoint(rect.right() - 1, rect.top() + 1),
- QPoint(rect.right() - 1, rect.bottom() - 1));
- }
- painter->restore();
- break;
-#ifndef QT_NO_LINEEDIT
- case PE_FrameLineEdit:
- // fall through
-#endif // QT_NO_LINEEDIT
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3ToolBar")) {
- proxy()->drawPrimitive(PE_Q3Separator, option, painter, widget);
- break;
- }
-#endif
- {
- QPen oldPen = painter->pen();
- if (option->state & State_Enabled) {
- painter->setPen(QPen(option->palette.background(), 0));
- painter->drawRect(rect.adjusted(0, 0, 0, 0));
- painter->drawRect(rect.adjusted(1, 1, -1, -1));
- } else {
- painter->fillRect(rect, option->palette.background());
- }
- QRect r = rect.adjusted(0, 1, 0, -1);
- painter->setPen(buttonShadowAlpha);
- painter->drawLine(QPoint(r.left() + 2, r.top() - 1), QPoint(r.right() - 2, r.top() - 1));
- const QPoint points[8] = {
- QPoint(r.right() - 1, r.top()),
- QPoint(r.right(), r.top() + 1),
- QPoint(r.right() - 1, r.bottom()),
- QPoint(r.right(), r.bottom() - 1),
- QPoint(r.left() + 1, r.top() ),
- QPoint(r.left(), r.top() + 1),
- QPoint(r.left() + 1, r.bottom() ),
- QPoint(r.left(), r.bottom() - 1)
- };
- painter->drawPoints(points, 8);
- painter->setPen(QPen(option->palette.background().color(), 1));
- painter->drawLine(QPoint(r.left() + 2, r.top() + 1), QPoint(r.right() - 2, r.top() + 1));
-
- if (option->state & State_HasFocus) {
- QColor darkoutline = option->palette.highlight().color().darker(150);
- QColor innerline = mergedColors(option->palette.highlight().color(), Qt::white);
- painter->setPen(QPen(innerline, 0));
- painter->drawRect(rect.adjusted(1, 2, -2, -3));
- painter->setPen(QPen(darkoutline, 0));
- }
- else {
- QColor highlight = Qt::white;
- highlight.setAlpha(130);
- painter->setPen(option->palette.base().color().darker(120));
- painter->drawLine(QPoint(r.left() + 1, r.top() + 1),
- QPoint(r.right() - 1, r.top() + 1));
- painter->drawLine(QPoint(r.left() + 1, r.top() + 1),
- QPoint(r.left() + 1, r.bottom() - 1));
- painter->setPen(option->palette.base().color());
- painter->drawLine(QPoint(r.right() - 1, r.top() + 1),
- QPoint(r.right() - 1, r.bottom() - 1));
- painter->setPen(highlight);
- painter->drawLine(QPoint(r.left() + 1, r.bottom() + 1),
- QPoint(r.right() - 1, r.bottom() + 1));
- painter->drawPoint(QPoint(r.left(), r.bottom()));
- painter->drawPoint(QPoint(r.right(), r.bottom() ));
- painter->setPen(QPen(darkOutline.lighter(115), 1));
- }
- painter->drawLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2));
- painter->drawLine(QPoint(r.right(), r.top() + 2), QPoint(r.right(), r.bottom() - 2));
- painter->drawLine(QPoint(r.left() + 2, r.bottom()), QPoint(r.right() - 2, r.bottom()));
- const QPoint points2[4] = {
- QPoint(r.right() - 1, r.bottom() - 1),
- QPoint(r.right() - 1, r.top() + 1),
- QPoint(r.left() + 1, r.bottom() - 1),
- QPoint(r.left() + 1, r.top() + 1)
- };
- painter->drawPoints(points2, 4);
- painter->drawLine(QPoint(r.left() + 2, r.top()), QPoint(r.right() - 2, r.top()));
- painter->setPen(oldPen);
- }
- break;
- case PE_IndicatorCheckBox:
- painter->save();
- if (const QStyleOptionButton *checkbox = qstyleoption_cast<const QStyleOptionButton*>(option)) {
- QRect checkRect;
- checkRect.setX(rect.left() );
- checkRect.setY(rect.top() );
- checkRect.setWidth(rect.width() - 1);
- checkRect.setHeight(rect.height() - 1);
- if (state & State_Sunken)
- painter->setBrush(dark.lighter(130));
- else
- painter->setBrush(option->palette.base());
- painter->setPen(QPen(dark.lighter(110), 0));
- painter->drawRect(checkRect);
- if (checkbox->state & (State_On | State_Sunken | State_NoChange)) {
- QImage image(qt_cleanlooks_checkbox_checked);
- QColor fillColor = option->palette.text().color();
- image.setColor(1, fillColor.rgba());
- fillColor.setAlpha(100);
- image.setColor(2, fillColor.rgba());
- painter->drawImage(rect, image);
- if (checkbox->state & State_NoChange) {
- QColor bgc = option->palette.background().color();
- bgc.setAlpha(127);
- painter->fillRect(checkRect.adjusted(1, 1, -1, -1), bgc);
- }
- }
- }
- painter->restore();
- break;
- case PE_IndicatorRadioButton:
- painter->save();
- {
- painter->setRenderHint(QPainter::SmoothPixmapTransform);
- QRect checkRect = rect.adjusted(0, 0, 0, 0);
- if (state & (State_On )) {
- painter->drawImage(rect, QImage(qt_cleanlooks_radiobutton));
- painter->drawImage(checkRect, QImage(qt_cleanlooks_radiobutton_checked));
- }
- else if (state & State_Sunken) {
- painter->drawImage(rect, QImage(qt_cleanlooks_radiobutton));
- QColor bgc = buttonShadow;
- painter->setRenderHint(QPainter::Antialiasing);
- painter->setBrush(bgc);
- painter->setPen(Qt::NoPen);
- painter->drawEllipse(rect.adjusted(1, 1, -1, -1)); }
- else {
- painter->drawImage(rect, QImage(qt_cleanlooks_radiobutton));
- }
- }
- painter->restore();
- break;
- case PE_IndicatorToolBarHandle:
- painter->save();
- if (option->state & State_Horizontal) {
- for (int i = rect.height()/5; i <= 4*(rect.height()/5) ; ++i) {
- int y = rect.topLeft().y() + i + 1;
- int x1 = rect.topLeft().x() + 3;
- int x2 = rect.topRight().x() - 2;
-
- if (i % 2 == 0)
- painter->setPen(QPen(option->palette.light(), 0));
- else
- painter->setPen(QPen(dark.lighter(110), 0));
- painter->drawLine(x1, y, x2, y);
- }
- }
- else { //vertical toolbar
- for (int i = rect.width()/5; i <= 4*(rect.width()/5) ; ++i) {
- int x = rect.topLeft().x() + i + 1;
- int y1 = rect.topLeft().y() + 3;
- int y2 = rect.topLeft().y() + 5;
-
- if (i % 2 == 0)
- painter->setPen(QPen(option->palette.light(), 0));
- else
- painter->setPen(QPen(dark.lighter(110), 0));
- painter->drawLine(x, y1, x, y2);
- }
- }
- painter->restore();
- break;
- case PE_FrameDefaultButton:
- case PE_FrameFocusRect:
- if (const QStyleOptionFocusRect *focusFrame = qstyleoption_cast<const QStyleOptionFocusRect *>(option)) {
- if (!(focusFrame->state & State_KeyboardFocusChange))
- return;
- QRect rect = focusFrame->rect;
- painter->save();
- painter->setBackgroundMode(Qt::TransparentMode);
- painter->setBrush(QBrush(dark.darker(120), Qt::Dense4Pattern));
- painter->setBrushOrigin(rect.topLeft());
- painter->setPen(Qt::NoPen);
- const QRect rects[4] = {
- QRect(rect.left(), rect.top(), rect.width(), 1), // Top
- QRect(rect.left(), rect.bottom(), rect.width(), 1), // Bottom
- QRect(rect.left(), rect.top(), 1, rect.height()), // Left
- QRect(rect.right(), rect.top(), 1, rect.height()) // Right
- };
- painter->drawRects(rects, 4);
- painter->restore();
- }
- break;
- case PE_PanelButtonCommand:
- {
- bool isDefault = false;
- bool isFlat = false;
- bool isDown = (option->state & State_Sunken) || (option->state & State_On);
- QPen oldPen = painter->pen();
- QBrush oldBrush = painter->brush();
- QRect r;
-
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton*>(option)) {
- isDefault = (button->features & QStyleOptionButton::DefaultButton) && (button->state & State_Enabled);
- isFlat = (button->features & QStyleOptionButton::Flat);
- }
-
- if (isFlat && !isDown) {
- if (isDefault) {
- r = option->rect.adjusted(0, 1, 0, -1);
- painter->setPen(QPen(Qt::black, 0));
- const QLine lines[4] = {
- QLine(QPoint(r.left() + 2, r.top()),
- QPoint(r.right() - 2, r.top())),
- QLine(QPoint(r.left(), r.top() + 2),
- QPoint(r.left(), r.bottom() - 2)),
- QLine(QPoint(r.right(), r.top() + 2),
- QPoint(r.right(), r.bottom() - 2)),
- QLine(QPoint(r.left() + 2, r.bottom()),
- QPoint(r.right() - 2, r.bottom()))
- };
- painter->drawLines(lines, 4);
- const QPoint points[4] = {
- QPoint(r.right() - 1, r.bottom() - 1),
- QPoint(r.right() - 1, r.top() + 1),
- QPoint(r.left() + 1, r.bottom() - 1),
- QPoint(r.left() + 1, r.top() + 1)
- };
- painter->drawPoints(points, 4);
- painter->setPen(oldPen);
- }
- return;
- }
-
- BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("pushbutton-%1").arg(isDefault))
- r = rect.adjusted(0, 1, 0, -1);
-
- bool isEnabled = (option->state & State_Enabled);
-
- QColor highlightedGradientStartColor = option->palette.button().color().lighter(107);
- QColor highlightedGradientMidColor = option->palette.button().color().lighter(105);
- QColor highlightedGradientStopColor = buttonShadow.lighter(107);
- QColor gradientStartColor = option->palette.button().color().lighter(108);
-
- QColor buttonColor = option->palette.button().color();
- QColor gradientMidColor = option->palette.button().color();
- QColor gradientStopColor;
- gradientStopColor.setHsv(buttonColor.hue(),
- qMin(255, (int)(buttonColor.saturation()*1.9)),
- qMin(255, (int)(buttonColor.value()*0.96)));
-
- QRect gradRect = rect.adjusted(1, 2, -1, -2);
- // gradient fill
- QRect innerBorder = r.adjusted(1, 1, -1, 0);
-
- if (isDown) {
- QBrush fillColor = gradientStopColor.darker(110);
- if (option->palette.button().gradient())
- fillColor = option->palette.button();
- p->fillRect(gradRect, fillColor);
- p->setPen(gradientStopColor.darker(125));
- p->drawLine(innerBorder.topLeft(), innerBorder.topRight());
- p->drawLine(innerBorder.topLeft(), innerBorder.bottomLeft());
- } else {
- if (isEnabled && option->state & State_MouseOver ) {
- qt_cleanlooks_draw_buttongradient(p, gradRect,
- highlightedGradientStartColor,
- highlightedGradientMidColor,
- highlightedGradientStopColor, TopDown, option->palette.button());
- } else {
- qt_cleanlooks_draw_buttongradient(p, gradRect,
- gradientStartColor,
- gradientMidColor,
- gradientStopColor, TopDown, option->palette.button());
- }
- }
-
- bool hasFocus = option->state & State_HasFocus;
-
- if (!isEnabled)
- p->setPen(QPen(dark.lighter(115)));
- else if (isDefault)
- p->setPen(QPen(Qt::black, 1));
- else
- p->setPen(QPen(darkOutline, 1));
-
- p->drawLine(QPoint(r.left(), r.top() + 2),
- QPoint(r.left(), r.bottom() - 2));
- p->drawLine(QPoint(r.right(), r.top() + 2),
- QPoint(r.right(), r.bottom() - 2));
- p->drawLine(QPoint(r.left() + 2, r.bottom()),
- QPoint(r.right() - 2, r.bottom()));
- const QPoint points[4] = {
- QPoint(r.right() - 1, r.bottom() - 1),
- QPoint(r.right() - 1, r.top() + 1),
- QPoint(r.left() + 1, r.bottom() - 1),
- QPoint(r.left() + 1, r.top() + 1)
- };
- p->drawPoints(points, 4);
-
- if (!isDefault && !hasFocus && isEnabled)
- p->setPen(QPen(darkOutline.darker(110), 0));
-
- p->drawLine(QPoint(r.left() + 2, r.top()),
- QPoint(r.right() - 2, r.top()));
-
- QColor highlight = Qt::white;
- highlight.setAlpha(110);
- p->setPen(highlight);
- p->drawLine(QPoint(r.left() + 1, r.top() + 2),
- QPoint(r.left() + 1, r.bottom() - 2));
- p->drawLine(QPoint(r.left() + 3, r.bottom() + 1),
- QPoint(r.right() - 3, r.bottom() + 1));
-
- QColor topShadow = darkOutline;
- topShadow.setAlpha(60);
-
- p->setPen(topShadow);
- const QPoint points2[8] = {
- QPoint(r.right(), r.top() + 1),
- QPoint(r.right() - 1, r.top() ),
- QPoint(r.right(), r.bottom() - 1),
- QPoint(r.right() - 1, r.bottom() ),
- QPoint(r.left() + 1, r.bottom()),
- QPoint(r.left(), r.bottom() - 1),
- QPoint(r.left() + 1, r.top()),
- QPoint(r.left(), r.top() + 1)
- };
- p->drawPoints(points2, 8);
-
- topShadow.setAlpha(30);
- p->setPen(topShadow);
-
- p->drawLine(QPoint(r.right() - 1, r.top() + 2),
- QPoint(r.right() - 1, r.bottom() - 2));
- p->drawLine(QPoint(r.left() + 2, r.top() - 1),
- QPoint(r.right() - 2, r.top() - 1));
-
- if (isDefault) {
- r.adjust(-1, -1, 1, 1);
- p->setPen(buttonShadowAlpha.darker(120));
- const QLine lines[4] = {
- QLine(r.topLeft() + QPoint(3, 0), r.topRight() - QPoint(3, 0)),
- QLine(r.bottomLeft() + QPoint(3, 0), r.bottomRight() - QPoint(3, 0)),
- QLine(r.topLeft() + QPoint(0, 3), r.bottomLeft() - QPoint(0, 3)),
- QLine(r.topRight() + QPoint(0, 3), r.bottomRight() - QPoint(0, 3))
- };
- p->drawLines(lines, 4);
- const QPoint points3[8] = {
- r.topRight() + QPoint(-2, 1),
- r.topRight() + QPoint(-1, 2),
- r.bottomRight() + QPoint(-1, -2),
- r.bottomRight() + QPoint(-2, -1),
- r.topLeft() + QPoint(1, 2),
- r.topLeft() + QPoint(2, 1),
- r.bottomLeft() + QPoint(1, -2),
- r.bottomLeft() + QPoint(2, -1)
- };
- p->drawPoints(points3, 8);
- }
- painter->setPen(oldPen);
- painter->setBrush(oldBrush);
- END_STYLE_PIXMAPCACHE
- }
- break;
-#ifndef QT_NO_TABBAR
- case PE_FrameTabWidget:
- painter->save();
- {
- painter->fillRect(option->rect, tabFrameColor);
- }
-#ifndef QT_NO_TABWIDGET
- if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option)) {
- QColor borderColor = darkOutline.lighter(110);
- QColor alphaCornerColor = mergedColors(borderColor, option->palette.background().color());
- QColor innerShadow = mergedColors(borderColor, option->palette.base().color());
-
- int borderThickness = proxy()->pixelMetric(PM_TabBarBaseOverlap, twf, widget);
- bool reverse = (twf->direction == Qt::RightToLeft);
- QRect tabBarRect;
-
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- if (reverse) {
- tabBarRect = QRect(twf->rect.right() - twf->leftCornerWidgetSize.width()
- - twf->tabBarSize.width() + 1,
- twf->rect.top(),
- twf->tabBarSize.width(), borderThickness);
- } else {
- tabBarRect = QRect(twf->rect.left() + twf->leftCornerWidgetSize.width(),
- twf->rect.top(),
- twf->tabBarSize.width(), borderThickness);
- }
- break ;
- case QTabBar::RoundedWest:
- tabBarRect = QRect(twf->rect.left(),
- twf->rect.top() + twf->leftCornerWidgetSize.height(),
- borderThickness,
- twf->tabBarSize.height());
- tabBarRect = tabBarRect; //adjust
- break ;
- case QTabBar::RoundedEast:
- tabBarRect = QRect(twf->rect.right() - borderThickness + 1,
- twf->rect.top() + twf->leftCornerWidgetSize.height(),
- 0,
- twf->tabBarSize.height());
- break ;
- case QTabBar::RoundedSouth:
- if (reverse) {
- tabBarRect = QRect(twf->rect.right() - twf->leftCornerWidgetSize.width() - twf->tabBarSize.width() + 1,
- twf->rect.bottom() + 1,
- twf->tabBarSize.width(),
- borderThickness);
- } else {
- tabBarRect = QRect(twf->rect.left() + twf->leftCornerWidgetSize.width(),
- twf->rect.bottom() + 1,
- twf->tabBarSize.width(),
- borderThickness);
- }
- break;
- default:
- break;
- }
-
- QRegion region(twf->rect);
- region -= tabBarRect;
- painter->setClipRegion(region);
-
- // Outer border
- QLine leftLine = QLine(twf->rect.topLeft() + QPoint(0, 2), twf->rect.bottomLeft() - QPoint(0, 2));
- QLine rightLine = QLine(twf->rect.topRight(), twf->rect.bottomRight() - QPoint(0, 2));
- QLine bottomLine = QLine(twf->rect.bottomLeft() + QPoint(2, 0), twf->rect.bottomRight() - QPoint(2, 0));
- QLine topLine = QLine(twf->rect.topLeft(), twf->rect.topRight());
-
- painter->setPen(borderColor);
- painter->drawLine(topLine);
-
- // Inner border
- QLine innerLeftLine = QLine(leftLine.p1() + QPoint(1, 0), leftLine.p2() + QPoint(1, 0));
- QLine innerRightLine = QLine(rightLine.p1() - QPoint(1, -1), rightLine.p2() - QPoint(1, 0));
- QLine innerBottomLine = QLine(bottomLine.p1() - QPoint(0, 1), bottomLine.p2() - QPoint(0, 1));
- QLine innerTopLine = QLine(topLine.p1() + QPoint(0, 1), topLine.p2() + QPoint(-1, 1));
-
- // Rounded Corner
- QPoint leftBottomOuterCorner = QPoint(innerLeftLine.p2() + QPoint(0, 1));
- QPoint leftBottomInnerCorner1 = QPoint(leftLine.p2() + QPoint(0, 1));
- QPoint leftBottomInnerCorner2 = QPoint(bottomLine.p1() - QPoint(1, 0));
- QPoint rightBottomOuterCorner = QPoint(innerRightLine.p2() + QPoint(0, 1));
- QPoint rightBottomInnerCorner1 = QPoint(rightLine.p2() + QPoint(0, 1));
- QPoint rightBottomInnerCorner2 = QPoint(bottomLine.p2() + QPoint(1, 0));
- QPoint leftTopOuterCorner = QPoint(innerLeftLine.p1() - QPoint(0, 1));
- QPoint leftTopInnerCorner1 = QPoint(leftLine.p1() - QPoint(0, 1));
- QPoint leftTopInnerCorner2 = QPoint(topLine.p1() - QPoint(1, 0));
-
- painter->setPen(borderColor);
- painter->drawLine(leftLine);
- painter->drawLine(rightLine);
- painter->drawLine(bottomLine);
- painter->drawPoint(leftBottomOuterCorner);
- painter->drawPoint(rightBottomOuterCorner);
- painter->drawPoint(leftTopOuterCorner);
-
- painter->setPen(option->palette.light().color());
- painter->drawLine(innerLeftLine);
- painter->drawLine(innerTopLine);
-
- painter->setPen(buttonShadowAlpha);
- painter->drawLine(innerRightLine);
- painter->drawLine(innerBottomLine);
-
- painter->setPen(alphaCornerColor);
- const QPoint points[6] = {
- leftBottomInnerCorner1,
- leftBottomInnerCorner2,
- rightBottomInnerCorner1,
- rightBottomInnerCorner2,
- leftTopInnerCorner1,
- leftTopInnerCorner2
- };
- painter->drawPoints(points, 6);
- }
-#endif // QT_NO_TABWIDGET
- painter->restore();
- break ;
-
- case PE_FrameStatusBarItem:
- break;
- case PE_IndicatorTabClose:
- {
- Q_D(const QCleanlooksStyle);
- if (d->tabBarcloseButtonIcon.isNull())
- d->tabBarcloseButtonIcon = standardIcon(SP_DialogCloseButton, option, widget);
- if ((option->state & State_Enabled) && (option->state & State_MouseOver))
- proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
- QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(QSize(16, 16), QIcon::Normal, QIcon::On);
- proxy()->drawItemPixmap(painter, option->rect, Qt::AlignCenter, pixmap);
- }
- break;
-
-#endif // QT_NO_TABBAR
- default:
- QWindowsStyle::drawPrimitive(elem, option, painter, widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter,
- const QWidget *widget) const
-{
- QColor button = option->palette.button().color();
- QColor dark;
- dark.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*1.9)),
- qMin(255, (int)(button.value()*0.7)));
- QColor darkOutline;
- darkOutline.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*2.0)),
- qMin(255, (int)(button.value()*0.6)));
- QRect rect = option->rect;
- QColor shadow = mergedColors(option->palette.background().color().darker(120),
- dark.lighter(130), 60);
- QColor tabFrameColor = mergedColors(option->palette.background().color(),
- dark.lighter(135), 60);
-
- QColor highlight = option->palette.highlight().color();
-
- switch(element) {
- case CE_RadioButton: //fall through
- case CE_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool hover = (btn->state & State_MouseOver && btn->state & State_Enabled);
- if (hover)
- painter->fillRect(rect, btn->palette.background().color().lighter(104));
- QStyleOptionButton copy = *btn;
- copy.rect.adjust(2, 0, -2, 0);
- QWindowsStyle::drawControl(element, &copy, painter, widget);
- }
- break;
- case CE_Splitter:
- painter->save();
- {
- // hover appearance
- QBrush fillColor = option->palette.background().color();
- if (option->state & State_MouseOver && option->state & State_Enabled)
- fillColor = fillColor.color().lighter(106);
-
- painter->fillRect(option->rect, fillColor);
-
- QColor grooveColor = mergedColors(dark.lighter(110), option->palette.button().color(),40);
- QColor gripShadow = grooveColor.darker(110);
- QPalette palette = option->palette;
- bool vertical = !(option->state & State_Horizontal);
- QRect scrollBarSlider = option->rect;
- int gripMargin = 4;
- //draw grips
- if (vertical) {
- for( int i = -20; i< 20 ; i += 2) {
- painter->setPen(QPen(gripShadow, 1));
- painter->drawLine(
- QPoint(scrollBarSlider.center().x() + i ,
- scrollBarSlider.top() + gripMargin),
- QPoint(scrollBarSlider.center().x() + i,
- scrollBarSlider.bottom() - gripMargin));
- painter->setPen(QPen(palette.light(), 1));
- painter->drawLine(
- QPoint(scrollBarSlider.center().x() + i + 1,
- scrollBarSlider.top() + gripMargin ),
- QPoint(scrollBarSlider.center().x() + i + 1,
- scrollBarSlider.bottom() - gripMargin));
- }
- } else {
- for (int i = -20; i < 20 ; i += 2) {
- painter->setPen(QPen(gripShadow, 1));
- painter->drawLine(
- QPoint(scrollBarSlider.left() + gripMargin ,
- scrollBarSlider.center().y()+ i),
- QPoint(scrollBarSlider.right() - gripMargin,
- scrollBarSlider.center().y()+ i));
- painter->setPen(QPen(palette.light(), 1));
- painter->drawLine(
- QPoint(scrollBarSlider.left() + gripMargin,
- scrollBarSlider.center().y() + 1 + i),
- QPoint(scrollBarSlider.right() - gripMargin,
- scrollBarSlider.center().y() + 1 + i));
-
- }
- }
- }
- painter->restore();
- break;
-#ifndef QT_NO_SIZEGRIP
- case CE_SizeGrip:
- painter->save();
- {
- int x, y, w, h;
- option->rect.getRect(&x, &y, &w, &h);
- int sw = qMin(h, w);
- if (h > w)
- painter->translate(0, h - w);
- else
- painter->translate(w - h, 0);
-
- int sx = x;
- int sy = y;
- int s = 4;
- if (option->direction == Qt::RightToLeft) {
- sx = x + sw;
- for (int i = 0; i < 4; ++i) {
- painter->setPen(QPen(option->palette.light().color(), 1));
- painter->drawLine(x, sy - 1 , sx + 1, sw);
- painter->setPen(QPen(dark.lighter(120), 1));
- painter->drawLine(x, sy, sx, sw);
- sx -= s;
- sy += s;
- }
- } else {
- for (int i = 0; i < 4; ++i) {
- painter->setPen(QPen(option->palette.light().color(), 1));
- painter->drawLine(sx - 1, sw, sw, sy - 1);
- painter->setPen(QPen(dark.lighter(120), 1));
- painter->drawLine(sx, sw, sw, sy);
- sx += s;
- sy += s;
- }
- }
- }
- painter->restore();
- break;
-#endif // QT_NO_SIZEGRIP
-#ifndef QT_NO_TOOLBAR
- case CE_ToolBar:
- painter->save();
- if (const QStyleOptionToolBar *toolbar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
- QRect rect = option->rect;
-
- bool paintLeftBorder = true;
- bool paintRightBorder = true;
- bool paintBottomBorder = true;
-
- switch (toolbar->toolBarArea) {
- case Qt::BottomToolBarArea:
- switch(toolbar->positionOfLine) {
- case QStyleOptionToolBar::Beginning:
- case QStyleOptionToolBar::OnlyOne:
- paintBottomBorder = false;
- default:
- break;
- }
- case Qt::TopToolBarArea:
- switch (toolbar->positionWithinLine) {
- case QStyleOptionToolBar::Beginning:
- paintLeftBorder = false;
- break;
- case QStyleOptionToolBar::End:
- paintRightBorder = false;
- break;
- case QStyleOptionToolBar::OnlyOne:
- paintRightBorder = false;
- paintLeftBorder = false;
- default:
- break;
- }
- if (toolbar->direction == Qt::RightToLeft) { //reverse layout changes the order of Beginning/end
- bool tmp = paintLeftBorder;
- paintRightBorder=paintLeftBorder;
- paintLeftBorder=tmp;
- }
- break;
- case Qt::RightToolBarArea:
- switch (toolbar->positionOfLine) {
- case QStyleOptionToolBar::Beginning:
- case QStyleOptionToolBar::OnlyOne:
- paintRightBorder = false;
- break;
- default:
- break;
- }
- break;
- case Qt::LeftToolBarArea:
- switch (toolbar->positionOfLine) {
- case QStyleOptionToolBar::Beginning:
- case QStyleOptionToolBar::OnlyOne:
- paintLeftBorder = false;
- break;
- default:
- break;
- }
- break;
- default:
- break;
- }
-
- QColor light = option->palette.background().color().lighter(110);
-
- //draw top border
- painter->setPen(QPen(light));
- painter->drawLine(rect.topLeft().x(),
- rect.topLeft().y(),
- rect.topRight().x(),
- rect.topRight().y());
-
- if (paintLeftBorder) {
- painter->setPen(QPen(light));
- painter->drawLine(rect.topLeft().x(),
- rect.topLeft().y(),
- rect.bottomLeft().x(),
- rect.bottomLeft().y());
- }
-
- if (paintRightBorder) {
- painter->setPen(QPen(shadow));
- painter->drawLine(rect.topRight().x(),
- rect.topRight().y(),
- rect.bottomRight().x(),
- rect.bottomRight().y());
- }
-
- if (paintBottomBorder) {
- painter->setPen(QPen(shadow));
- painter->drawLine(rect.bottomLeft().x(),
- rect.bottomLeft().y(),
- rect.bottomRight().x(),
- rect.bottomRight().y());
- }
- }
- painter->restore();
- break;
-#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_DOCKWIDGET
- case CE_DockWidgetTitle:
- painter->save();
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(option)) {
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- QRect rect = dwOpt->rect;
- QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, option, widget);
- QRect r = rect.adjusted(0, 0, -1, 0);
- if (verticalTitleBar)
- r.adjust(0, 0, 0, -1);
- painter->setPen(option->palette.light().color());
- painter->drawRect(r.adjusted(1, 1, 1, 1));
- painter->setPen(shadow);
- painter->drawRect(r);
-
- if (verticalTitleBar) {
- QRect r = rect;
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- titleRect = QRect(r.left() + rect.bottom()
- - titleRect.bottom(),
- r.top() + titleRect.left() - rect.left(),
- titleRect.height(), titleRect.width());
-
- painter->translate(r.left(), r.top() + r.width());
- painter->rotate(-90);
- painter->translate(-r.left(), -r.top());
-
- rect = r;
- }
-
- if (!dwOpt->title.isEmpty()) {
- QString titleText
- = painter->fontMetrics().elidedText(dwOpt->title,
- Qt::ElideRight, titleRect.width());
- proxy()->drawItemText(painter,
- titleRect,
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, dwOpt->palette,
- dwOpt->state & State_Enabled, titleText,
- QPalette::WindowText);
- }
- }
- painter->restore();
- break;
-#endif // QT_NO_DOCKWIDGET
- case CE_HeaderSection:
- painter->save();
- // Draws the header in tables.
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("headersection"), option, option->rect.size());
- pixmapName += QString::number(- int(header->position));
- pixmapName += QString::number(- int(header->orientation));
- QRect r = option->rect;
- QColor gradientStopColor;
- QColor gradientStartColor = option->palette.button().color();
- gradientStopColor.setHsv(gradientStartColor.hue(),
- qMin(255, (int)(gradientStartColor.saturation()*2)),
- qMin(255, (int)(gradientStartColor.value()*0.96)));
- QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
- if (option->palette.background().gradient()) {
- gradient.setStops(option->palette.background().gradient()->stops());
- } else {
- gradient.setColorAt(0, gradientStartColor);
- gradient.setColorAt(0.8, gradientStartColor);
- gradient.setColorAt(1, gradientStopColor);
- }
- painter->fillRect(r, gradient);
-
- if (!QPixmapCache::find(pixmapName, cache)) {
- cache = QPixmap(r.size());
- cache.fill(Qt::transparent);
- QRect pixmapRect(0, 0, r.width(), r.height());
- QPainter cachePainter(&cache);
- if (header->orientation == Qt::Vertical) {
- cachePainter.setPen(QPen(dark));
- cachePainter.drawLine(pixmapRect.topRight(), pixmapRect.bottomRight());
- if (header->position != QStyleOptionHeader::End) {
- cachePainter.setPen(QPen(shadow));
- cachePainter.drawLine(pixmapRect.bottomLeft() + QPoint(3, -1), pixmapRect.bottomRight() + QPoint(-3, -1)); cachePainter.setPen(QPen(option->palette.light().color()));
- cachePainter.drawLine(pixmapRect.bottomLeft() + QPoint(3, 0), pixmapRect.bottomRight() + QPoint(-3, 0)); }
- } else {
- cachePainter.setPen(QPen(dark));
- cachePainter.drawLine(pixmapRect.bottomLeft(), pixmapRect.bottomRight());
- cachePainter.setPen(QPen(shadow));
- cachePainter.drawLine(pixmapRect.topRight() + QPoint(-1, 3), pixmapRect.bottomRight() + QPoint(-1, -3)); cachePainter.setPen(QPen(option->palette.light().color()));
- cachePainter.drawLine(pixmapRect.topRight() + QPoint(0, 3), pixmapRect.bottomRight() + QPoint(0, -3)); }
- cachePainter.end();
- QPixmapCache::insert(pixmapName, cache);
- }
- painter->drawPixmap(r.topLeft(), cache);
- }
- painter->restore();
- break;
- case CE_ProgressBarGroove:
- painter->save();
- {
- painter->fillRect(rect, option->palette.base());
- QColor borderColor = dark.lighter(110);
- painter->setPen(QPen(borderColor, 0));
- const QLine lines[4] = {
- QLine(QPoint(rect.left() + 1, rect.top()), QPoint(rect.right() - 1, rect.top())),
- QLine(QPoint(rect.left() + 1, rect.bottom()), QPoint(rect.right() - 1, rect.bottom())),
- QLine(QPoint(rect.left(), rect.top() + 1), QPoint(rect.left(), rect.bottom() - 1)),
- QLine(QPoint(rect.right(), rect.top() + 1), QPoint(rect.right(), rect.bottom() - 1))
- };
- painter->drawLines(lines, 4);
- QColor alphaCorner = mergedColors(borderColor, option->palette.background().color());
- QColor innerShadow = mergedColors(borderColor, option->palette.base().color());
-
- //corner smoothing
- painter->setPen(alphaCorner);
- const QPoint points[4] = {
- rect.topRight(),
- rect.topLeft(),
- rect.bottomRight(),
- rect.bottomLeft()
- };
- painter->drawPoints(points, 4);
-
- //inner shadow
- painter->setPen(innerShadow);
- painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1),
- QPoint(rect.right() - 1, rect.top() + 1));
- painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1),
- QPoint(rect.left() + 1, rect.bottom() + 1));
-
- }
- painter->restore();
- break;
- case CE_ProgressBarContents:
- painter->save();
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- QRect rect = bar->rect;
- bool vertical = false;
- bool inverted = false;
- bool indeterminate = (bar->minimum == 0 && bar->maximum == 0);
-
- // Get extra style options if version 2
- if (const QStyleOptionProgressBarV2 *bar2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- vertical = (bar2->orientation == Qt::Vertical);
- inverted = bar2->invertedAppearance;
- }
-
- // If the orientation is vertical, we use a transform to rotate
- // the progress bar 90 degrees clockwise. This way we can use the
- // same rendering code for both orientations.
- if (vertical) {
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- QTransform m = QTransform::fromTranslate(rect.height()-1, -1.0);
- m.rotate(90.0);
- painter->setTransform(m, true);
- }
-
- int maxWidth = rect.width() - 4;
- int minWidth = 4;
- qreal progress = qMax(bar->progress, bar->minimum); // workaround for bug in QProgressBar
- int progressBarWidth = (progress - bar->minimum) * qreal(maxWidth) / qMax(qreal(1.0), qreal(bar->maximum) - bar->minimum);
- int width = indeterminate ? maxWidth : qMax(minWidth, progressBarWidth);
-
- bool reverse = (!vertical && (bar->direction == Qt::RightToLeft)) || vertical;
- if (inverted)
- reverse = !reverse;
-
- QRect progressBar;
- if (!indeterminate) {
- if (!reverse) {
- progressBar.setRect(rect.left() + 1, rect.top() + 1, width + 1, rect.height() - 3);
- } else {
- progressBar.setRect(rect.right() - 1 - width, rect.top() + 1, width + 1, rect.height() - 3);
- }
- } else {
- Q_D(const QCleanlooksStyle);
- int slideWidth = ((rect.width() - 4) * 2) / 3;
- int step = ((d->animateStep * slideWidth) / d->animationFps) % slideWidth;
- if ((((d->animateStep * slideWidth) / d->animationFps) % (2 * slideWidth)) >= slideWidth)
- step = slideWidth - step;
- progressBar.setRect(rect.left() + 1 + step, rect.top() + 1,
- slideWidth / 2, rect.height() - 3);
- }
- QColor highlight = option->palette.color(QPalette::Normal, QPalette::Highlight);
- painter->setPen(QPen(highlight.darker(140), 0));
-
- QColor highlightedGradientStartColor = highlight.lighter(100);
- QColor highlightedGradientStopColor = highlight.lighter(130);
-
- QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(),
- rect.bottomLeft().y()*2));
-
- gradient.setColorAt(0, highlightedGradientStartColor);
- gradient.setColorAt(1, highlightedGradientStopColor);
-
- painter->setBrush(gradient);
- painter->drawRect(progressBar);
-
- painter->setPen(QPen(highlight.lighter(120), 0));
- painter->drawLine(QPoint(progressBar.left() + 1, progressBar.top() + 1),
- QPoint(progressBar.right(), progressBar.top() + 1));
- painter->drawLine(QPoint(progressBar.left() + 1, progressBar.top() + 1),
- QPoint(progressBar.left() + 1, progressBar.bottom() - 1));
-
- painter->setPen(QPen(highlightedGradientStartColor, 7.0));//QPen(option->palette.highlight(), 3));
-
- painter->save();
- painter->setClipRect(progressBar.adjusted(2, 2, -1, -1));
- for (int x = progressBar.left() - 32; x < rect.right() ; x+=18) {
- painter->drawLine(x, progressBar.bottom() + 1, x + 23, progressBar.top() - 2);
- }
- painter->restore();
-
- }
- painter->restore();
- break;
- case CE_MenuBarItem:
- painter->save();
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option))
- {
- QStyleOptionMenuItem item = *mbi;
- item.rect = mbi->rect.adjusted(0, 3, 0, -1);
- QColor highlightOutline = highlight.darker(125);
- QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(), rect.bottomLeft().y()*2));
-
- if (option->palette.button().gradient()) {
- gradient.setStops(option->palette.button().gradient()->stops());
- } else {
- gradient.setColorAt(0, option->palette.button().color());
- gradient.setColorAt(1, option->palette.button().color().darker(110));
- }
- painter->fillRect(rect, gradient);
-
- QCommonStyle::drawControl(element, &item, painter, widget);
-
- bool act = mbi->state & State_Selected && mbi->state & State_Sunken;
- bool dis = !(mbi->state & State_Enabled);
-
- QRect r = option->rect;
- if (act) {
- qt_cleanlooks_draw_gradient(painter, r.adjusted(1, 1, -1, -1),
- highlight,
- highlightOutline, TopDown,
- option->palette.highlight());
-
- painter->setPen(QPen(highlightOutline, 0));
- const QLine lines[4] = {
- QLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom())),
- QLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom())),
- QLine(QPoint(r.left() + 1, r.bottom()), QPoint(r.right() - 1, r.bottom())),
- QLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top()))
- };
- painter->drawLines(lines, 4);
-
- //draw text
- QPalette::ColorRole textRole = dis ? QPalette::Text : QPalette::HighlightedText;
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, mbi, widget))
- alignment |= Qt::TextHideMnemonic;
- proxy()->drawItemText(painter, item.rect, alignment, mbi->palette, mbi->state & State_Enabled, mbi->text, textRole);
- }
-
- }
- painter->restore();
- break;
- case CE_MenuItem:
- painter->save();
- // Draws one item in a popup menu.
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- QColor highlightOutline = highlight.darker(125);
- QColor menuBackground = option->palette.background().color().lighter(104);
- QColor borderColor = option->palette.background().color().darker(160);
- QColor alphaCornerColor;
-
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
- }
- QColor alphaTextColor = mergedColors(option->palette.background().color(), option->palette.text().color());
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
- painter->fillRect(menuItem->rect, menuBackground);
- int w = 0;
- if (!menuItem->text.isEmpty()) {
- painter->setFont(menuItem->font);
- proxy()->drawItemText(painter, menuItem->rect.adjusted(5, 0, -5, 0), Qt::AlignLeft | Qt::AlignVCenter,
- menuItem->palette, menuItem->state & State_Enabled, menuItem->text,
- QPalette::Text);
- w = menuItem->fontMetrics.width(menuItem->text) + 5;
- }
- painter->setPen(shadow.lighter(106));
- bool reverse = menuItem->direction == Qt::RightToLeft;
- painter->drawLine(menuItem->rect.left() + 5 + (reverse ? 0 : w), menuItem->rect.center().y(),
- menuItem->rect.right() - 5 - (reverse ? w : 0), menuItem->rect.center().y());
- painter->restore();
- break;
- }
- bool selected = menuItem->state & State_Selected && menuItem->state & State_Enabled;
- if (selected) {
- QRect r = option->rect.adjusted(1, 0, -2, -1);
- qt_cleanlooks_draw_gradient(painter, r, highlight,
- highlightOutline, TopDown,
- highlight);
- r = r.adjusted(-1, 0, 1, 0);
- painter->setPen(QPen(highlightOutline, 0));
- const QLine lines[4] = {
- QLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom() - 1)),
- QLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom() - 1)),
- QLine(QPoint(r.left() + 1, r.bottom()), QPoint(r.right() - 1, r.bottom())),
- QLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top()))
- };
- painter->drawLines(lines, 4);
- } else {
- painter->fillRect(option->rect, menuBackground);
- }
-
- bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
- bool checked = menuItem->checked;
- bool sunken = menuItem->state & State_Sunken;
- bool enabled = menuItem->state & State_Enabled;
-
- bool ignoreCheckMark = false;
- int checkcol = qMax(menuItem->maxIconWidth, 20);
-
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox*>(widget))
- ignoreCheckMark = true; //ignore the checkmarks provided by the QComboMenuDelegate
-#endif
-
- if (!ignoreCheckMark) {
- // Check
- QRect checkRect(option->rect.left() + 7, option->rect.center().y() - 6, 13, 13);
- checkRect = visualRect(menuItem->direction, menuItem->rect, checkRect);
- if (checkable) {
- if (menuItem->checkType & QStyleOptionMenuItem::Exclusive) {
- // Radio button
- if (checked || sunken) {
- painter->setRenderHint(QPainter::Antialiasing);
- painter->setPen(Qt::NoPen);
-
- QPalette::ColorRole textRole = !enabled ? QPalette::Text:
- selected ? QPalette::HighlightedText : QPalette::ButtonText;
- painter->setBrush(option->palette.brush( option->palette.currentColorGroup(), textRole));
- painter->drawEllipse(checkRect.adjusted(4, 4, -4, -4));
- }
- } else {
- // Check box
- if (menuItem->icon.isNull()) {
- if (checked || sunken) {
- QImage image(qt_cleanlooks_menuitem_checkbox_checked);
- if (enabled && (menuItem->state & State_Selected)) {
- image.setColor(1, 0x55ffffff);
- image.setColor(2, 0xAAffffff);
- image.setColor(3, 0xBBffffff);
- image.setColor(4, 0xFFffffff);
- image.setColor(5, 0x33ffffff);
- } else {
- image.setColor(1, 0x55000000);
- image.setColor(2, 0xAA000000);
- image.setColor(3, 0xBB000000);
- image.setColor(4, 0xFF000000);
- image.setColor(5, 0x33000000);
- }
- painter->drawImage(QPoint(checkRect.center().x() - image.width() / 2,
- checkRect.center().y() - image.height() / 2), image);
- }
- }
- }
- }
- } else { //ignore checkmark
- if (menuItem->icon.isNull())
- checkcol = 0;
- else
- checkcol = menuItem->maxIconWidth;
- }
-
- // Text and icon, ripped from windows style
- bool dis = !(menuItem->state & State_Enabled);
- bool act = menuItem->state & State_Selected;
- const QStyleOption *opt = option;
- const QStyleOptionMenuItem *menuitem = menuItem;
-
- QPainter *p = painter;
- QRect vCheckRect = visualRect(opt->direction, menuitem->rect,
- QRect(menuitem->rect.x(), menuitem->rect.y(),
- checkcol, menuitem->rect.height()));
- if (!menuItem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap;
-
- int smallIconSize = proxy()->pixelMetric(PM_SmallIconSize, option, widget);
- QSize iconSize(smallIconSize, smallIconSize);
-#ifndef QT_NO_COMBOBOX
- if (const QComboBox *combo = qobject_cast<const QComboBox*>(widget))
- iconSize = combo->iconSize();
-#endif // QT_NO_COMBOBOX
- if (checked)
- pixmap = menuItem->icon.pixmap(iconSize, mode, QIcon::On);
- else
- pixmap = menuItem->icon.pixmap(iconSize, mode);
-
- int pixw = pixmap.width();
- int pixh = pixmap.height();
-
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vCheckRect.center());
- painter->setPen(menuItem->palette.text().color());
- if (checkable && checked) {
- QStyleOption opt = *option;
- if (act) {
- QColor activeColor = mergedColors(option->palette.background().color(),
- option->palette.highlight().color());
- opt.palette.setBrush(QPalette::Button, activeColor);
- }
- opt.state |= State_Sunken;
- opt.rect = vCheckRect;
- proxy()->drawPrimitive(PE_PanelButtonCommand, &opt, painter, widget);
- }
- painter->drawPixmap(pmr.topLeft(), pixmap);
- }
- if (selected) {
- painter->setPen(menuItem->palette.highlightedText().color());
- } else {
- painter->setPen(menuItem->palette.text().color());
- }
- int x, y, w, h;
- menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
- QColor discol;
- if (dis) {
- discol = menuitem->palette.text().color();
- p->setPen(discol);
- }
- int xm = windowsItemFrame + checkcol + windowsItemHMargin;
- int xpos = menuitem->rect.x() + xm;
-
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
- QString s = menuitem->text;
- if (!s.isEmpty()) { // draw text
- p->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
- text_flags |= Qt::AlignLeft;
- if (t >= 0) {
- QRect vShortcutRect = visualRect(opt->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
- if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vShortcutRect.adjusted(1, 1, 1, 1), text_flags, s.mid(t + 1));
- p->setPen(discol);
- }
- p->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- QFont font = menuitem->font;
- // font may not have any "hard" flags set. We override
- // the point size so that when it is resolved against the device, this font will win.
- // This is mainly to handle cases where someone sets the font on the window
- // and then the combo inherits it and passes it onward. At that point the resolve mask
- // is very, very weak. This makes it stonger.
- font.setPointSizeF(QFontInfo(menuItem->font).pointSizeF());
-
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
-
- p->setFont(font);
- if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vTextRect.adjusted(1, 1, 1, 1), text_flags, s.left(t));
- p->setPen(discol);
- }
- p->drawText(vTextRect, text_flags, s.left(t));
- p->restore();
- }
-
- // Arrow
- if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- int dim = (menuItem->rect.height() - 4) / 2;
- PrimitiveElement arrow;
- arrow = QApplication::isRightToLeft() ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- int xpos = menuItem->rect.left() + menuItem->rect.width() - 3 - dim;
- QRect vSubMenuRect = visualRect(option->direction, menuItem->rect,
- QRect(xpos, menuItem->rect.top() + menuItem->rect.height() / 2 - dim / 2, dim, dim));
- QStyleOptionMenuItem newMI = *menuItem;
- newMI.rect = vSubMenuRect;
- newMI.state = !enabled ? State_None : State_Enabled;
- if (selected)
- newMI.palette.setColor(QPalette::ButtonText,
- newMI.palette.highlightedText().color());
- proxy()->drawPrimitive(arrow, &newMI, painter, widget);
- }
- }
- painter->restore();
- break;
- case CE_MenuHMargin:
- case CE_MenuVMargin:
- break;
- case CE_MenuEmptyArea:
- break;
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- QRect ir = button->rect;
- uint tf = Qt::AlignVCenter;
- if (styleHint(SH_UnderlineShortcut, button, widget))
- tf |= Qt::TextShowMnemonic;
- else
- tf |= Qt::TextHideMnemonic;
-
- if (!button->icon.isNull()) {
- //Center both icon and text
- QPoint point;
-
- QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- if (mode == QIcon::Normal && button->state & State_HasFocus)
- mode = QIcon::Active;
- QIcon::State state = QIcon::Off;
- if (button->state & State_On)
- state = QIcon::On;
-
- QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
- int w = pixmap.width();
- int h = pixmap.height();
-
- if (!button->text.isEmpty())
- w += button->fontMetrics.boundingRect(option->rect, tf, button->text).width() + 2;
-
- point = QPoint(ir.x() + ir.width() / 2 - w / 2,
- ir.y() + ir.height() / 2 - h / 2);
-
- if (button->direction == Qt::RightToLeft)
- point.rx() += pixmap.width();
-
- painter->drawPixmap(visualPos(button->direction, button->rect, point), pixmap);
-
- if (button->direction == Qt::RightToLeft)
- ir.translate(-point.x() - 2, 0);
- else
- ir.translate(point.x() + pixmap.width(), 0);
-
- // left-align text if there is
- if (!button->text.isEmpty())
- tf |= Qt::AlignLeft;
-
- } else {
- tf |= Qt::AlignHCenter;
- }
-
- if (button->features & QStyleOptionButton::HasMenu)
- ir = ir.adjusted(0, 0, -proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget), 0);
- proxy()->drawItemText(painter, ir, tf, button->palette, (button->state & State_Enabled),
- button->text, QPalette::ButtonText);
- }
- break;
- case CE_MenuBarEmptyArea:
- painter->save();
- {
- QColor shadow = mergedColors(option->palette.background().color().darker(120),
- dark.lighter(140), 60);
-
- QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(), rect.bottomLeft().y()*2));
- gradient.setColorAt(0, option->palette.button().color());
- gradient.setColorAt(1, option->palette.button().color().darker(110));
- painter->fillRect(rect, gradient);
-
-#ifndef QT_NO_MAINWINDOW
- if (widget && qobject_cast<const QMainWindow *>(widget->parentWidget())) {
- QPen oldPen = painter->pen();
- painter->setPen(QPen(shadow));
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- }
-#endif // QT_NO_MAINWINDOW
- }
- painter->restore();
- break;
-#ifndef QT_NO_TABBAR
- case CE_TabBarTabShape:
- painter->save();
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
-
- bool rtlHorTabs = (tab->direction == Qt::RightToLeft
- && (tab->shape == QTabBar::RoundedNorth
- || tab->shape == QTabBar::RoundedSouth));
- bool selected = tab->state & State_Selected;
- bool lastTab = ((!rtlHorTabs && tab->position == QStyleOptionTab::End)
- || (rtlHorTabs
- && tab->position == QStyleOptionTab::Beginning));
- bool onlyTab = tab->position == QStyleOptionTab::OnlyOneTab;
- bool leftCornerWidget = (tab->cornerWidgets & QStyleOptionTab::LeftCornerWidget);
-
- bool atBeginning = ((tab->position == (tab->direction == Qt::LeftToRight ?
- QStyleOptionTab::Beginning : QStyleOptionTab::End)) || onlyTab);
-
- bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
- bool previousSelected =
- ((!rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
- || (rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::NextIsSelected));
- bool nextSelected =
- ((!rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::NextIsSelected)
- || (rtlHorTabs
- && tab->selectedPosition
- == QStyleOptionTab::PreviousIsSelected));
- int tabBarAlignment = proxy()->styleHint(SH_TabBar_Alignment, tab, widget);
- bool leftAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignLeft)
- || (rtlHorTabs
- && tabBarAlignment == Qt::AlignRight);
-
- bool rightAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignRight)
- || (rtlHorTabs
- && tabBarAlignment == Qt::AlignLeft);
-
- QColor light = tab->palette.light().color();
- QColor midlight = tab->palette.midlight().color();
-
- QColor background = tab->palette.background().color();
- int borderThinkness = proxy()->pixelMetric(PM_TabBarBaseOverlap, tab, widget);
- if (selected)
- borderThinkness /= 2;
- QRect r2(option->rect);
- int x1 = r2.left();
- int x2 = r2.right();
- int y1 = r2.top();
- int y2 = r2.bottom();
-
- QTransform rotMatrix;
- bool flip = false;
- painter->setPen(shadow);
- QColor activeHighlight = option->palette.color(QPalette::Normal, QPalette::Highlight);
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- break;
- case QTabBar::RoundedSouth:
- rotMatrix.rotate(180);
- rotMatrix.translate(0, -rect.height() + 1);
- rotMatrix.scale(-1, 1);
- painter->setTransform(rotMatrix, true);
- break;
- case QTabBar::RoundedWest:
- rotMatrix.rotate(180 + 90);
- rotMatrix.scale(-1, 1);
- flip = true;
- painter->setTransform(rotMatrix, true);
- break;
- case QTabBar::RoundedEast:
- rotMatrix.rotate(90);
- rotMatrix.translate(0, - rect.width() + 1);
- flip = true;
- painter->setTransform(rotMatrix, true);
- break;
- default:
- painter->restore();
- QWindowsStyle::drawControl(element, tab, painter, widget);
- return;
- }
-
- if (flip) {
- QRect tmp = rect;
- rect = QRect(tmp.y(), tmp.x(), tmp.height(), tmp.width());
- int temp = x1;
- x1 = y1;
- y1 = temp;
- temp = x2;
- x2 = y2;
- y2 = temp;
- }
-
- QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
- if (option->palette.button().gradient()) {
- if (selected)
- gradient.setStops(option->palette.background().gradient()->stops());
- else
- gradient.setStops(option->palette.background().gradient()->stops());
- }
- else if (selected) {
- gradient.setColorAt(0, option->palette.background().color().lighter(104));
- gradient.setColorAt(1, tabFrameColor);
- painter->fillRect(rect.adjusted(0, 2, 0, -1), gradient);
- } else {
- y1 += 2;
- gradient.setColorAt(0, option->palette.background().color());
- gradient.setColorAt(1, dark.lighter(120));
- painter->fillRect(rect.adjusted(0, 2, 0, -2), gradient);
- }
-
- // Delete border
- if (selected) {
- painter->setPen(QPen(activeHighlight, 0));
- painter->drawLine(x1 + 1, y1 + 1, x2 - 1, y1 + 1);
- painter->drawLine(x1 , y1 + 2, x2 , y1 + 2);
- } else {
- painter->setPen(dark);
- painter->drawLine(x1, y2 - 1, x2 + 2, y2 - 1 );
- if (tab->shape == QTabBar::RoundedNorth || tab->shape == QTabBar::RoundedWest) {
- painter->setPen(light);
- painter->drawLine(x1, y2 , x2, y2 );
- }
- }
- // Left
- if (atBeginning || selected ) {
- painter->setPen(light);
- painter->drawLine(x1 + 1, y1 + 2 + 1, x1 + 1, y2 - ((onlyOne || atBeginning) && selected && leftAligned ? 0 : borderThinkness) - (atBeginning && leftCornerWidget ? 1 : 0));
- painter->drawPoint(x1 + 1, y1 + 1);
- painter->setPen(dark);
- painter->drawLine(x1, y1 + 2, x1, y2 - ((onlyOne || atBeginning) && leftAligned ? 0 : borderThinkness) - (atBeginning && leftCornerWidget ? 1 : 0));
- }
- // Top
- {
- int beg = x1 + (previousSelected ? 0 : 2);
- int end = x2 - (nextSelected ? 0 : 2);
- painter->setPen(light);
-
- if (!selected)painter->drawLine(beg - 2, y1 + 1, end, y1 + 1);
-
- if (selected)
- painter->setPen(QPen(activeHighlight.darker(150), 0));
- else
- painter->setPen(darkOutline);
- painter->drawLine(beg, y1 , end, y1);
-
- if (atBeginning|| selected) {
- painter->drawPoint(beg - 1, y1 + 1);
- } else if (!atBeginning) {
- painter->drawPoint(beg - 1, y1);
- painter->drawPoint(beg - 2, y1);
- if (!lastTab) {
- painter->setPen(dark.lighter(130));
- painter->drawPoint(end + 1, y1);
- painter->drawPoint(end + 2 , y1);
- painter->drawPoint(end + 2, y1 + 1);
- }
- }
- }
- // Right
- if (lastTab || selected || onlyOne || !nextSelected) {
- painter->setPen(darkOutline);
- painter->drawLine(x2, y1 + 2, x2, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- if (selected)
- painter->setPen(QPen(activeHighlight.darker(150), 0));
- else
- painter->setPen(darkOutline);
- painter->drawPoint(x2 - 1, y1 + 1);
-
- if (selected) {
- painter->setPen(background.darker(110));
- painter->drawLine(x2 - 1, y1 + 3, x2 - 1, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- }
- }
- }
- painter->restore();
- break;
-
-#endif // QT_NO_TABBAR
- default:
- QWindowsStyle::drawControl(element,option,painter,widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-QPalette QCleanlooksStyle::standardPalette () const
-{
- QPalette palette = QWindowsStyle::standardPalette();
- palette.setBrush(QPalette::Active, QPalette::Highlight, QColor(98, 140, 178));
- palette.setBrush(QPalette::Inactive, QPalette::Highlight, QColor(145, 141, 126));
- palette.setBrush(QPalette::Disabled, QPalette::Highlight, QColor(145, 141, 126));
-
- QColor backGround(239, 235, 231);
-
- QColor light = backGround.lighter(150);
- QColor base = Qt::white;
- QColor dark = QColor(170, 156, 143).darker(110);
- dark = backGround.darker(150);
- QColor darkDisabled = QColor(209, 200, 191).darker(110);
-
- //### Find the correct disabled text color
- palette.setBrush(QPalette::Disabled, QPalette::Text, QColor(190, 190, 190));
-
- palette.setBrush(QPalette::Window, backGround);
- palette.setBrush(QPalette::Mid, backGround.darker(130));
- palette.setBrush(QPalette::Light, light);
-
- palette.setBrush(QPalette::Active, QPalette::Base, base);
- palette.setBrush(QPalette::Inactive, QPalette::Base, base);
- palette.setBrush(QPalette::Disabled, QPalette::Base, backGround);
-
- palette.setBrush(QPalette::Midlight, palette.mid().color().lighter(110));
-
- palette.setBrush(QPalette::All, QPalette::Dark, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Dark, darkDisabled);
-
- QColor button = backGround;
-
- palette.setBrush(QPalette::Button, button);
-
- QColor shadow = dark.darker(135);
- palette.setBrush(QPalette::Shadow, shadow);
- palette.setBrush(QPalette::Disabled, QPalette::Shadow, shadow.lighter(150));
- palette.setBrush(QPalette::HighlightedText, QColor(QRgb(0xffffffff)));
- return palette;
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const
-{
- QColor button = option->palette.button().color();
- QColor dark;
- QColor grooveColor;
- QColor darkOutline;
- dark.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*1.9)),
- qMin(255, (int)(button.value()*0.7)));
- grooveColor.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*2.6)),
- qMin(255, (int)(button.value()*0.9)));
- darkOutline.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*3.0)),
- qMin(255, (int)(button.value()*0.6)));
-
- QColor alphaCornerColor;
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), darkOutline);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), darkOutline);
- }
- QColor gripShadow = grooveColor.darker(110);
- QColor buttonShadow = option->palette.button().color().darker(110);
-
- QColor gradientStartColor = option->palette.button().color().lighter(108);
- QColor gradientStopColor = mergedColors(option->palette.button().color().darker(108), dark.lighter(150), 70);
-
- QColor highlightedGradientStartColor = option->palette.button().color();
- QColor highlightedGradientStopColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 85);
-
- QColor highlightedDarkInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 35);
- QColor highlightedLightInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 58);
-
- QColor buttonShadowAlpha = option->palette.background().color().darker(105);
-
- QPalette palette = option->palette;
-
- switch (control) {
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("spinbox"), spinBox, spinBox->rect.size());
- if (!QPixmapCache::find(pixmapName, cache)) {
- cache = QPixmap(spinBox->rect.size());
- cache.fill(Qt::transparent);
- QRect pixmapRect(0, 0, spinBox->rect.width(), spinBox->rect.height());
- QPainter cachePainter(&cache);
-
- bool isEnabled = (spinBox->state & State_Enabled);
- //bool focus = isEnabled && (spinBox->state & State_HasFocus);
- bool hover = isEnabled && (spinBox->state & State_MouseOver);
- bool sunken = (spinBox->state & State_Sunken);
- bool upIsActive = (spinBox->activeSubControls == SC_SpinBoxUp);
- bool downIsActive = (spinBox->activeSubControls == SC_SpinBoxDown);
-
- QRect rect = pixmapRect;
- QStyleOptionSpinBox spinBoxCopy = *spinBox;
- spinBoxCopy.rect = pixmapRect;
- QRect upRect = proxy()->subControlRect(CC_SpinBox, &spinBoxCopy, SC_SpinBoxUp, widget);
- QRect downRect = proxy()->subControlRect(CC_SpinBox, &spinBoxCopy, SC_SpinBoxDown, widget);
-
- int fw = spinBoxCopy.frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, &spinBoxCopy, widget) : 0;
- cachePainter.fillRect(rect.adjusted(1, qMax(fw - 1, 0), -1, -fw),
- option->palette.base());
-
- QRect r = rect.adjusted(0, 1, 0, -1);
- if (spinBox->frame) {
-
- QColor topShadow = darkOutline;
- topShadow.setAlpha(60);
- cachePainter.setPen(topShadow);
-
- // antialias corners
- const QPoint points[8] = {
- QPoint(r.right(), r.top() + 1),
- QPoint(r.right() - 1, r.top() ),
- QPoint(r.right(), r.bottom() - 1),
- QPoint(r.right() - 1, r.bottom() ),
- QPoint(r.left() + 1, r.bottom()),
- QPoint(r.left(), r.bottom() - 1),
- QPoint(r.left() + 1, r.top()),
- QPoint(r.left(), r.top() + 1)
- };
- cachePainter.drawPoints(points, 8);
-
- // draw frame
- topShadow.setAlpha(30);
- cachePainter.setPen(topShadow);
- cachePainter.drawLine(QPoint(r.left() + 2, r.top() - 1), QPoint(r.right() - 2, r.top() - 1));
-
- cachePainter.setPen(QPen(option->palette.background().color(), 1));
- cachePainter.drawLine(QPoint(r.left() + 2, r.top() + 1), QPoint(r.right() - 2, r.top() + 1));
- QColor highlight = Qt::white;
- highlight.setAlpha(130);
- cachePainter.setPen(option->palette.base().color().darker(120));
- cachePainter.drawLine(QPoint(r.left() + 1, r.top() + 1),
- QPoint(r.right() - 1, r.top() + 1));
- cachePainter.drawLine(QPoint(r.left() + 1, r.top() + 1),
- QPoint(r.left() + 1, r.bottom() - 1));
- cachePainter.setPen(option->palette.base().color());
- cachePainter.drawLine(QPoint(r.right() - 1, r.top() + 1),
- QPoint(r.right() - 1, r.bottom() - 1));
- cachePainter.drawLine(QPoint(r.left() + 1, r.bottom() - 1),
- QPoint(r.right() - 1, r.bottom() - 1));
- cachePainter.setPen(highlight);
- cachePainter.drawLine(QPoint(r.left() + 3, r.bottom() + 1),
- QPoint(r.right() - 3, r.bottom() + 1));
-
- cachePainter.setPen(QPen(darkOutline, 1));
-
- // top and bottom lines
- const QLine lines[4] = {
- QLine(QPoint(r.left() + 2, r.bottom()), QPoint(r.right()- 2, r.bottom())),
- QLine(QPoint(r.left() + 2, r.top()), QPoint(r.right() - 2, r.top())),
- QLine(QPoint(r.right(), r.top() + 2), QPoint(r.right(), r.bottom() - 2)),
- QLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2))
- };
- cachePainter.drawLines(lines, 4);
- }
-
- // gradients
- qt_cleanlooks_draw_gradient(&cachePainter, upRect,
- gradientStartColor.darker(106),
- gradientStopColor, TopDown, option->palette.button());
- qt_cleanlooks_draw_gradient(&cachePainter, downRect.adjusted(0, 0, 0, 1),
- gradientStartColor.darker(106),
- gradientStopColor, TopDown, option->palette.button());
- if (isEnabled) {
- if(upIsActive) {
- if (sunken) {
- cachePainter.fillRect(upRect.adjusted(1, 0, 0, 0), gradientStopColor.darker(110));
- } else if (hover) {
- qt_cleanlooks_draw_gradient(&cachePainter, upRect.adjusted(1, 0, 0, 0),
- gradientStartColor.lighter(110),
- gradientStopColor.lighter(110), TopDown, option->palette.button());
- }
- }
- if(downIsActive) {
- if (sunken) {
- cachePainter.fillRect(downRect.adjusted(1, 0, 0, 1), gradientStopColor.darker(110));
-
- } else if (hover) {
- qt_cleanlooks_draw_gradient(&cachePainter, downRect.adjusted(1, 0, 0, 1),
- gradientStartColor.lighter(110),
- gradientStopColor.lighter(110), TopDown, option->palette.button());
- }
- }
- }
-
- if (spinBox->frame) {
- // rounded corners
- const QPoint points[4] = {
- QPoint(r.left() + 1, r.bottom() - 1),
- QPoint(r.left() + 1, r.top() + 1),
- QPoint(r.right() - 1, r.bottom() - 1),
- QPoint(r.right() - 1, r.top() + 1)
- };
- cachePainter.drawPoints(points, 4);
-
- if (option->state & State_HasFocus) {
- QColor darkoutline = option->palette.highlight().color().darker(150);
- QColor innerline = mergedColors(option->palette.highlight().color(), Qt::white);
- cachePainter.setPen(QPen(innerline, 0));
- if (spinBox->direction == Qt::LeftToRight) {
- cachePainter.drawRect(rect.adjusted(1, 2, -3 -downRect.width(), -3));
- cachePainter.setPen(QPen(darkoutline, 0));
- const QLine lines[4] = {
- QLine(QPoint(r.left() + 2, r.bottom()), QPoint(r.right()- downRect.width() - 1, r.bottom())),
- QLine(QPoint(r.left() + 2, r.top()), QPoint(r.right() - downRect.width() - 1, r.top())),
- QLine(QPoint(r.right() - downRect.width() - 1, r.top() + 1), QPoint(r.right()- downRect.width() - 1, r.bottom() - 1)),
- QLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2))
- };
- cachePainter.drawLines(lines, 4);
- cachePainter.drawPoint(QPoint(r.left() + 1, r.bottom() - 1));
- cachePainter.drawPoint(QPoint(r.left() + 1, r.top() + 1));
- cachePainter.drawLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2));
- } else {
- cachePainter.drawRect(rect.adjusted(downRect.width() + 2, 2, -2, -3));
- cachePainter.setPen(QPen(darkoutline, 0));
- cachePainter.drawLine(QPoint(r.left() + downRect.width(), r.bottom()), QPoint(r.right()- 2 - 1, r.bottom()));
- cachePainter.drawLine(QPoint(r.left() + downRect.width(), r.top()), QPoint(r.right() - 2 - 1, r.top()));
-
- cachePainter.drawLine(QPoint(r.right(), r.top() + 2), QPoint(r.right(), r.bottom() - 2));
- cachePainter.drawPoint(QPoint(r.right() - 1, r.bottom() - 1));
- cachePainter.drawPoint(QPoint(r.right() - 1, r.top() + 1));
- cachePainter.drawLine(QPoint(r.left() + downRect.width() + 1, r.top()),
- QPoint(r.left() + downRect.width() + 1, r.bottom()));
- }
- }
- }
-
- // outline the up/down buttons
- cachePainter.setPen(darkOutline);
- QColor light = option->palette.light().color().lighter();
-
- if (spinBox->direction == Qt::RightToLeft) {
- cachePainter.drawLine(upRect.right(), upRect.top() - 1, upRect.right(), downRect.bottom() + 1);
- cachePainter.setPen(light);
- cachePainter.drawLine(upRect.right() - 1, upRect.top() + 3, upRect.right() - 1, downRect.bottom() );
- } else {
- cachePainter.drawLine(upRect.left(), upRect.top() - 1, upRect.left(), downRect.bottom() + 1);
- cachePainter.setPen(light);
- cachePainter.drawLine(upRect.left() + 1, upRect.top() , upRect.left() + 1, downRect.bottom() );
- }
- if (upIsActive && sunken) {
- cachePainter.setPen(gradientStopColor.darker(130));
- cachePainter.drawLine(upRect.left() + 1, upRect.top(), upRect.left() + 1, upRect.bottom());
- cachePainter.drawLine(upRect.left(), upRect.top() - 1, upRect.right(), upRect.top() - 1);
- } else {
- cachePainter.setPen(light);
- cachePainter.drawLine(upRect.topLeft() + QPoint(1, -1), upRect.topRight() + QPoint(-1, -1));
- cachePainter.setPen(darkOutline);
- cachePainter.drawLine(upRect.bottomLeft(), upRect.bottomRight());
- }
- if (downIsActive && sunken) {
- cachePainter.setPen(gradientStopColor.darker(130));
- cachePainter.drawLine(downRect.left() + 1, downRect.top(), downRect.left() + 1, downRect.bottom() + 1);
- cachePainter.drawLine(downRect.left(), downRect.top(), downRect.right(), downRect.top());
- cachePainter.setPen(gradientStopColor.darker(110));
- cachePainter.drawLine(downRect.left(), downRect.bottom() + 1, downRect.right(), downRect.bottom() + 1);
- } else {
- cachePainter.setPen(light);
- cachePainter.drawLine(downRect.topLeft() + QPoint(2,0), downRect.topRight());
- }
-
- if (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) {
- int centerX = upRect.center().x();
- int centerY = upRect.center().y();
- cachePainter.setPen(spinBox->palette.foreground().color());
-
- // plus/minus
- if (spinBox->activeSubControls == SC_SpinBoxUp && sunken) {
- cachePainter.drawLine(1 + centerX - 2, 1 + centerY, 1 + centerX + 2, 1 + centerY);
- cachePainter.drawLine(1 + centerX, 1 + centerY - 2, 1 + centerX, 1 + centerY + 2);
- } else {
- cachePainter.drawLine(centerX - 2, centerY, centerX + 2, centerY);
- cachePainter.drawLine(centerX, centerY - 2, centerX, centerY + 2);
- }
-
- centerX = downRect.center().x();
- centerY = downRect.center().y();
- if (spinBox->activeSubControls == SC_SpinBoxDown && sunken) {
- cachePainter.drawLine(1 + centerX - 2, 1 + centerY, 1 + centerX + 2, 1 + centerY);
- } else {
- cachePainter.drawLine(centerX - 2, centerY, centerX + 2, centerY);
- }
- } else if (spinBox->buttonSymbols == QAbstractSpinBox::UpDownArrows){
- // arrows
- QImage upArrow(qt_spinbox_button_arrow_up);
- upArrow.setColor(1, spinBox->palette.foreground().color().rgba());
-
- cachePainter.drawImage(upRect.center().x() - upArrow.width() / 2,
- upRect.center().y() - upArrow.height() / 2,
- upArrow);
-
- QImage downArrow(qt_spinbox_button_arrow_down);
- downArrow.setColor(1, spinBox->palette.foreground().color().rgba());
-
- cachePainter.drawImage(downRect.center().x() - downArrow.width() / 2,
- downRect.center().y() - downArrow.height() / 2 + 1,
- downArrow);
- }
-
- QColor disabledColor = option->palette.background().color();
- disabledColor.setAlpha(150);
- if (!(spinBox->stepEnabled & QAbstractSpinBox::StepUpEnabled))
- cachePainter.fillRect(upRect.adjusted(1, 0, 0, 0), disabledColor);
- if (!(spinBox->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- cachePainter.fillRect(downRect.adjusted(1, 0, 0, 0), disabledColor);
- }
- cachePainter.end();
- QPixmapCache::insert(pixmapName, cache);
- }
- painter->drawPixmap(spinBox->rect.topLeft(), cache);
- }
- break;
-#endif // QT_NO_SPINBOX
- case CC_TitleBar:
- painter->save();
- if (const QStyleOptionTitleBar *titleBar = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- const int buttonMargin = 5;
- bool active = (titleBar->titleBarState & State_Active);
- QRect fullRect = titleBar->rect;
- QPalette palette = option->palette;
- QColor highlight = option->palette.highlight().color();
-
- QColor titleBarFrameBorder(active ? highlight.darker(180): dark.darker(110));
- QColor titleBarHighlight(active ? highlight.lighter(120): palette.background().color().lighter(120));
- QColor textColor(active ? 0xffffff : 0xff000000);
- QColor textAlphaColor(active ? 0xffffff : 0xff000000 );
-
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- QStyleOptionDockWidgetV2 dockwidget;
- dockwidget.QStyleOption::operator=(*option);
- proxy()->drawControl(CE_DockWidgetTitle, &dockwidget, painter, widget);
- } else
-#endif // QT3_SUPPORT
- {
- // Fill title bar gradient
- QColor titlebarColor = QColor(active ? highlight: palette.background().color());
- QLinearGradient gradient(option->rect.center().x(), option->rect.top(),
- option->rect.center().x(), option->rect.bottom());
-
- gradient.setColorAt(0, titlebarColor.lighter(114));
- gradient.setColorAt(0.5, titlebarColor.lighter(102));
- gradient.setColorAt(0.51, titlebarColor.darker(104));
- gradient.setColorAt(1, titlebarColor);
- painter->fillRect(option->rect.adjusted(1, 1, -1, 0), gradient);
-
- // Frame and rounded corners
- painter->setPen(titleBarFrameBorder);
-
- // top outline
- painter->drawLine(fullRect.left() + 5, fullRect.top(), fullRect.right() - 5, fullRect.top());
- painter->drawLine(fullRect.left(), fullRect.top() + 4, fullRect.left(), fullRect.bottom());
- const QPoint points[5] = {
- QPoint(fullRect.left() + 4, fullRect.top() + 1),
- QPoint(fullRect.left() + 3, fullRect.top() + 1),
- QPoint(fullRect.left() + 2, fullRect.top() + 2),
- QPoint(fullRect.left() + 1, fullRect.top() + 3),
- QPoint(fullRect.left() + 1, fullRect.top() + 4)
- };
- painter->drawPoints(points, 5);
-
- painter->drawLine(fullRect.right(), fullRect.top() + 4, fullRect.right(), fullRect.bottom());
- const QPoint points2[5] = {
- QPoint(fullRect.right() - 3, fullRect.top() + 1),
- QPoint(fullRect.right() - 4, fullRect.top() + 1),
- QPoint(fullRect.right() - 2, fullRect.top() + 2),
- QPoint(fullRect.right() - 1, fullRect.top() + 3),
- QPoint(fullRect.right() - 1, fullRect.top() + 4)
- };
- painter->drawPoints(points2, 5);
-
- // draw bottomline
- painter->drawLine(fullRect.right(), fullRect.bottom(), fullRect.left(), fullRect.bottom());
-
- // top highlight
- painter->setPen(titleBarHighlight);
- painter->drawLine(fullRect.left() + 6, fullRect.top() + 1, fullRect.right() - 6, fullRect.top() + 1);
- }
- // draw title
- QRect textRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarLabel, widget);
- QFont font = painter->font();
- font.setBold(true);
- painter->setFont(font);
- painter->setPen(active? (titleBar->palette.text().color().lighter(120)) :
- titleBar->palette.text().color() );
- // Note workspace also does elliding but it does not use the correct font
- QString title = QFontMetrics(font).elidedText(titleBar->text, Qt::ElideRight, textRect.width() - 14);
- painter->drawText(textRect.adjusted(1, 1, 1, 1), title, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
- painter->setPen(Qt::white);
- if (active)
- painter->drawText(textRect, title, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
- // min button
- if ((titleBar->subControls & SC_TitleBarMinButton) && (titleBar->titleBarFlags & Qt::WindowMinimizeButtonHint) &&
- !(titleBar->titleBarState& Qt::WindowMinimized)) {
- QRect minButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarMinButton, widget);
- if (minButtonRect.isValid()) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarMinButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarMinButton) && (titleBar->state & State_Sunken);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, minButtonRect, hover, sunken);
- QRect minButtonIconRect = minButtonRect.adjusted(buttonMargin ,buttonMargin , -buttonMargin, -buttonMargin);
- painter->setPen(textColor);
- painter->drawLine(minButtonIconRect.center().x() - 2, minButtonIconRect.center().y() + 3,
- minButtonIconRect.center().x() + 3, minButtonIconRect.center().y() + 3);
- painter->drawLine(minButtonIconRect.center().x() - 2, minButtonIconRect.center().y() + 4,
- minButtonIconRect.center().x() + 3, minButtonIconRect.center().y() + 4);
- painter->setPen(textAlphaColor);
- painter->drawLine(minButtonIconRect.center().x() - 3, minButtonIconRect.center().y() + 3,
- minButtonIconRect.center().x() - 3, minButtonIconRect.center().y() + 4);
- painter->drawLine(minButtonIconRect.center().x() + 4, minButtonIconRect.center().y() + 3,
- minButtonIconRect.center().x() + 4, minButtonIconRect.center().y() + 4);
- }
- }
- // max button
- if ((titleBar->subControls & SC_TitleBarMaxButton) && (titleBar->titleBarFlags & Qt::WindowMaximizeButtonHint) &&
- !(titleBar->titleBarState & Qt::WindowMaximized)) {
- QRect maxButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarMaxButton, widget);
- if (maxButtonRect.isValid()) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarMaxButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarMaxButton) && (titleBar->state & State_Sunken);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, maxButtonRect, hover, sunken);
-
- QRect maxButtonIconRect = maxButtonRect.adjusted(buttonMargin, buttonMargin, -buttonMargin, -buttonMargin);
-
- painter->setPen(textColor);
- painter->drawRect(maxButtonIconRect.adjusted(0, 0, -1, -1));
- painter->drawLine(maxButtonIconRect.left() + 1, maxButtonIconRect.top() + 1,
- maxButtonIconRect.right() - 1, maxButtonIconRect.top() + 1);
- painter->setPen(textAlphaColor);
- const QPoint points[4] = {
- maxButtonIconRect.topLeft(),
- maxButtonIconRect.topRight(),
- maxButtonIconRect.bottomLeft(),
- maxButtonIconRect.bottomRight()
- };
- painter->drawPoints(points, 4);
- }
- }
-
- // close button
- if ((titleBar->subControls & SC_TitleBarCloseButton) && (titleBar->titleBarFlags & Qt::WindowSystemMenuHint)) {
- QRect closeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarCloseButton, widget);
- if (closeButtonRect.isValid()) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarCloseButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarCloseButton) && (titleBar->state & State_Sunken);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, closeButtonRect, hover, sunken);
- QRect closeIconRect = closeButtonRect.adjusted(buttonMargin, buttonMargin, -buttonMargin, -buttonMargin);
- painter->setPen(textAlphaColor);
- const QLine lines[4] = {
- QLine(closeIconRect.left() + 1, closeIconRect.top(),
- closeIconRect.right(), closeIconRect.bottom() - 1),
- QLine(closeIconRect.left(), closeIconRect.top() + 1,
- closeIconRect.right() - 1, closeIconRect.bottom()),
- QLine(closeIconRect.right() - 1, closeIconRect.top(),
- closeIconRect.left(), closeIconRect.bottom() - 1),
- QLine(closeIconRect.right(), closeIconRect.top() + 1,
- closeIconRect.left() + 1, closeIconRect.bottom())
- };
- painter->drawLines(lines, 4);
- const QPoint points[4] = {
- closeIconRect.topLeft(),
- closeIconRect.topRight(),
- closeIconRect.bottomLeft(),
- closeIconRect.bottomRight()
- };
- painter->drawPoints(points, 4);
-
- painter->setPen(textColor);
- painter->drawLine(closeIconRect.left() + 1, closeIconRect.top() + 1,
- closeIconRect.right() - 1, closeIconRect.bottom() - 1);
- painter->drawLine(closeIconRect.left() + 1, closeIconRect.bottom() - 1,
- closeIconRect.right() - 1, closeIconRect.top() + 1);
- }
- }
-
- // normalize button
- if ((titleBar->subControls & SC_TitleBarNormalButton) &&
- (((titleBar->titleBarFlags & Qt::WindowMinimizeButtonHint) &&
- (titleBar->titleBarState & Qt::WindowMinimized)) ||
- ((titleBar->titleBarFlags & Qt::WindowMaximizeButtonHint) &&
- (titleBar->titleBarState & Qt::WindowMaximized)))) {
- QRect normalButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarNormalButton, widget);
- if (normalButtonRect.isValid()) {
-
- bool hover = (titleBar->activeSubControls & SC_TitleBarNormalButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarNormalButton) && (titleBar->state & State_Sunken);
- QRect normalButtonIconRect = normalButtonRect.adjusted(buttonMargin, buttonMargin, -buttonMargin, -buttonMargin);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, normalButtonRect, hover, sunken);
-
- QRect frontWindowRect = normalButtonIconRect.adjusted(0, 3, -3, 0);
- painter->setPen(textColor);
- painter->drawRect(frontWindowRect.adjusted(0, 0, -1, -1));
- painter->drawLine(frontWindowRect.left() + 1, frontWindowRect.top() + 1,
- frontWindowRect.right() - 1, frontWindowRect.top() + 1);
- painter->setPen(textAlphaColor);
- const QPoint points[4] = {
- frontWindowRect.topLeft(),
- frontWindowRect.topRight(),
- frontWindowRect.bottomLeft(),
- frontWindowRect.bottomRight()
- };
- painter->drawPoints(points, 4);
-
- QRect backWindowRect = normalButtonIconRect.adjusted(3, 0, 0, -3);
- QRegion clipRegion = backWindowRect;
- clipRegion -= frontWindowRect;
- painter->save();
- painter->setClipRegion(clipRegion);
- painter->setPen(textColor);
- painter->drawRect(backWindowRect.adjusted(0, 0, -1, -1));
- painter->drawLine(backWindowRect.left() + 1, backWindowRect.top() + 1,
- backWindowRect.right() - 1, backWindowRect.top() + 1);
- painter->setPen(textAlphaColor);
- const QPoint points2[4] = {
- backWindowRect.topLeft(),
- backWindowRect.topRight(),
- backWindowRect.bottomLeft(),
- backWindowRect.bottomRight()
- };
- painter->drawPoints(points2, 4);
- painter->restore();
- }
- }
-
- // context help button
- if (titleBar->subControls & SC_TitleBarContextHelpButton
- && (titleBar->titleBarFlags & Qt::WindowContextHelpButtonHint)) {
- QRect contextHelpButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarContextHelpButton, widget);
- if (contextHelpButtonRect.isValid()) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarContextHelpButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarContextHelpButton) && (titleBar->state & State_Sunken);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, contextHelpButtonRect, hover, sunken);
-
- QColor blend;
- QImage image(qt_titlebar_context_help);
- QColor alpha = textColor;
- alpha.setAlpha(128);
- image.setColor(1, textColor.rgba());
- image.setColor(2, alpha.rgba());
- painter->setRenderHint(QPainter::SmoothPixmapTransform);
- painter->drawImage(contextHelpButtonRect.adjusted(4, 4, -4, -4), image);
- }
- }
-
- // shade button
- if (titleBar->subControls & SC_TitleBarShadeButton && (titleBar->titleBarFlags & Qt::WindowShadeButtonHint)) {
- QRect shadeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarShadeButton, widget);
- if (shadeButtonRect.isValid()) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarShadeButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarShadeButton) && (titleBar->state & State_Sunken);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, shadeButtonRect, hover, sunken);
- QImage image(qt_scrollbar_button_arrow_up);
- image.setColor(1, textColor.rgba());
- painter->drawImage(shadeButtonRect.adjusted(5, 7, -5, -7), image);
- }
- }
-
- // unshade button
- if (titleBar->subControls & SC_TitleBarUnshadeButton && (titleBar->titleBarFlags & Qt::WindowShadeButtonHint)) {
- QRect unshadeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarUnshadeButton, widget);
- if (unshadeButtonRect.isValid()) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarUnshadeButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarUnshadeButton) && (titleBar->state & State_Sunken);
- qt_cleanlooks_draw_mdibutton(painter, titleBar, unshadeButtonRect, hover, sunken);
- QImage image(qt_scrollbar_button_arrow_down);
- image.setColor(1, textColor.rgba());
- painter->drawImage(unshadeButtonRect.adjusted(5, 7, -5, -7), image);
- }
- }
-
- if ((titleBar->subControls & SC_TitleBarSysMenu) && (titleBar->titleBarFlags & Qt::WindowSystemMenuHint)) {
- QRect iconRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarSysMenu, widget);
- if (iconRect.isValid()) {
- if (!titleBar->icon.isNull()) {
- titleBar->icon.paint(painter, iconRect);
- } else {
- QStyleOption tool(0);
- tool.palette = titleBar->palette;
- QPixmap pm = standardIcon(SP_TitleBarMenuButton, &tool, widget).pixmap(16, 16);
- tool.rect = iconRect;
- painter->save();
- proxy()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, pm);
- painter->restore();
- }
- }
- }
- }
- painter->restore();
- break;
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- painter->save();
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- bool isEnabled = scrollBar->state & State_Enabled;
- bool reverse = scrollBar->direction == Qt::RightToLeft;
- bool horizontal = scrollBar->orientation == Qt::Horizontal;
- bool sunken = scrollBar->state & State_Sunken;
-
- painter->fillRect(option->rect, option->palette.background());
-
- QRect scrollBarSubLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSubLine, widget);
- QRect scrollBarAddLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarAddLine, widget);
- QRect scrollBarSlider = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSlider, widget);
- QRect grooveRect = proxy()->subControlRect(control, scrollBar, SC_ScrollBarGroove, widget);
-
- // paint groove
- if (scrollBar->subControls & SC_ScrollBarGroove) {
- painter->setBrush(grooveColor);
- painter->setPen(Qt::NoPen);
- if (horizontal) {
- painter->drawRect(grooveRect);
- painter->setPen(darkOutline);
- painter->drawLine(grooveRect.topLeft(), grooveRect.topRight());
- painter->drawLine(grooveRect.bottomLeft(), grooveRect.bottomRight());
- } else {
- painter->drawRect(grooveRect);
- painter->setPen(darkOutline);
- painter->drawLine(grooveRect.topLeft(), grooveRect.bottomLeft());
- painter->drawLine(grooveRect.topRight(), grooveRect.bottomRight());
- }
- }
- //paint slider
- if (scrollBar->subControls & SC_ScrollBarSlider) {
- QRect pixmapRect = scrollBarSlider;
- if (horizontal)
- pixmapRect.adjust(-1, 0, 0, -1);
- else
- pixmapRect.adjust(0, -1, -1, 0);
-
- if (isEnabled) {
- QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top(),
- pixmapRect.center().x(), pixmapRect.bottom());
- if (!horizontal)
- gradient = QLinearGradient(pixmapRect.left(), pixmapRect.center().y(),
- pixmapRect.right(), pixmapRect.center().y());
-
- if (option->palette.button().gradient()) {
- gradient.setStops(option->palette.button().gradient()->stops());
- } else {
- if (sunken || (option->state & State_MouseOver &&
- (scrollBar->activeSubControls & SC_ScrollBarSlider))) {
- gradient.setColorAt(0, gradientStartColor.lighter(110));
- gradient.setColorAt(1, gradientStopColor.lighter(110));
- } else {
- gradient.setColorAt(0, gradientStartColor);
- gradient.setColorAt(1, gradientStopColor);
- }
- }
- painter->setPen(QPen(darkOutline, 0));
- painter->setBrush(gradient);
- painter->drawRect(pixmapRect);
-
-
- //calculate offsets used by highlight and shadow
- int yoffset, xoffset;
- if (option->state & State_Horizontal) {
- xoffset = 0;
- yoffset = 1;
- } else {
- xoffset = 1;
- yoffset = 0;
- }
- //draw slider highlights
- painter->setPen(QPen(gradientStopColor, 0));
- painter->drawLine(scrollBarSlider.left() + xoffset,
- scrollBarSlider.bottom() - yoffset,
- scrollBarSlider.right() - xoffset,
- scrollBarSlider.bottom() - yoffset);
- painter->drawLine(scrollBarSlider.right() - xoffset,
- scrollBarSlider.top() + yoffset,
- scrollBarSlider.right() - xoffset,
- scrollBarSlider.bottom() - yoffset);
-
- //draw slider shadow
- painter->setPen(QPen(gradientStartColor, 0));
- painter->drawLine(scrollBarSlider.left() + xoffset,
- scrollBarSlider.top() + yoffset,
- scrollBarSlider.right() - xoffset,
- scrollBarSlider.top() + yoffset);
- painter->drawLine(scrollBarSlider.left() + xoffset,
- scrollBarSlider.top() + yoffset,
- scrollBarSlider.left() + xoffset,
- scrollBarSlider.bottom() - yoffset);
- } else {
- QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top(),
- pixmapRect.center().x(), pixmapRect.bottom());
- if (!horizontal) {
- gradient = QLinearGradient(pixmapRect.left(), pixmapRect.center().y(),
- pixmapRect.right(), pixmapRect.center().y());
- }
- if (sunken) {
- gradient.setColorAt(0, gradientStartColor.lighter(110));
- gradient.setColorAt(1, gradientStopColor.lighter(110));
- } else {
- gradient.setColorAt(0, gradientStartColor);
- gradient.setColorAt(1, gradientStopColor);
- }
- painter->setPen(darkOutline);
- painter->setBrush(gradient);
- painter->drawRect(pixmapRect);
- }
- int gripMargin = 4;
- //draw grips
- if (horizontal) {
- for (int i = -3; i< 6 ; i += 3) {
- painter->setPen(QPen(gripShadow, 1));
- painter->drawLine(
- QPoint(scrollBarSlider.center().x() + i ,
- scrollBarSlider.top() + gripMargin),
- QPoint(scrollBarSlider.center().x() + i,
- scrollBarSlider.bottom() - gripMargin));
- painter->setPen(QPen(palette.light(), 1));
- painter->drawLine(
- QPoint(scrollBarSlider.center().x() + i + 1,
- scrollBarSlider.top() + gripMargin ),
- QPoint(scrollBarSlider.center().x() + i + 1,
- scrollBarSlider.bottom() - gripMargin));
- }
- } else {
- for (int i = -3; i < 6 ; i += 3) {
- painter->setPen(QPen(gripShadow, 1));
- painter->drawLine(
- QPoint(scrollBarSlider.left() + gripMargin ,
- scrollBarSlider.center().y()+ i),
- QPoint(scrollBarSlider.right() - gripMargin,
- scrollBarSlider.center().y()+ i));
- painter->setPen(QPen(palette.light(), 1));
- painter->drawLine(
- QPoint(scrollBarSlider.left() + gripMargin,
- scrollBarSlider.center().y() + 1 + i),
- QPoint(scrollBarSlider.right() - gripMargin,
- scrollBarSlider.center().y() + 1 + i));
- }
- }
- }
-
- // The SubLine (up/left) buttons
- if (scrollBar->subControls & SC_ScrollBarSubLine) {
- //int scrollBarExtent = proxy()->pixelMetric(PM_ScrollBarExtent, option, widget);
- QRect pixmapRect = scrollBarSubLine;
- if (isEnabled ) {
- QRect fillRect = pixmapRect.adjusted(1, 1, -1, -1);
- // Gradients
- if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken) {
- qt_cleanlooks_draw_gradient(painter,
- QRect(fillRect),
- gradientStopColor.darker(120),
- gradientStopColor.darker(120),
- horizontal ? TopDown : FromLeft, option->palette.button());
- } else {
- qt_cleanlooks_draw_gradient(painter,
- QRect(fillRect),
- gradientStartColor.lighter(105),
- gradientStopColor,
- horizontal ? TopDown : FromLeft, option->palette.button());
- }
- }
- // Details
- QImage subButton;
- if (horizontal) {
- subButton = QImage(reverse ? qt_scrollbar_button_right : qt_scrollbar_button_left);
- } else {
- subButton = QImage(qt_scrollbar_button_up);
- }
- subButton.setColor(1, alphaCornerColor.rgba());
- subButton.setColor(2, darkOutline.rgba());
- if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken) {
- subButton.setColor(3, gradientStopColor.darker(140).rgba());
- subButton.setColor(4, gradientStopColor.darker(120).rgba());
- } else {
- subButton.setColor(3, gradientStartColor.lighter(105).rgba());
- subButton.setColor(4, gradientStopColor.rgba());
- }
- subButton.setColor(5, scrollBar->palette.text().color().rgba());
- painter->drawImage(pixmapRect, subButton);
-
- // Arrows
- PrimitiveElement arrow;
- if (option->state & State_Horizontal)
- arrow = option->direction == Qt::LeftToRight ? PE_IndicatorArrowLeft: PE_IndicatorArrowRight;
- else
- arrow = PE_IndicatorArrowUp;
- QStyleOption arrowOpt = *option;
- arrowOpt.rect = scrollBarSubLine.adjusted(3, 3, -2, -2);
- proxy()->drawPrimitive(arrow, &arrowOpt, painter, widget);
-
-
- // The AddLine (down/right) button
- if (scrollBar->subControls & SC_ScrollBarAddLine) {
- QString addLinePixmapName = QStyleHelper::uniqueName(QLatin1String("scrollbar_addline"), option, QSize(16, 16));
- QRect pixmapRect = scrollBarAddLine;
- if (isEnabled) {
- QRect fillRect = pixmapRect.adjusted(1, 1, -1, -1);
- // Gradients
- if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken) {
- qt_cleanlooks_draw_gradient(painter,
- fillRect,
- gradientStopColor.darker(120),
- gradientStopColor.darker(120),
- horizontal ? TopDown: FromLeft, option->palette.button());
- } else {
- qt_cleanlooks_draw_gradient(painter,
- fillRect,
- gradientStartColor.lighter(105),
- gradientStopColor,
- horizontal ? TopDown : FromLeft, option->palette.button());
- }
- }
- // Details
- QImage addButton;
- if (horizontal) {
- addButton = QImage(reverse ? qt_scrollbar_button_left : qt_scrollbar_button_right);
- } else {
- addButton = QImage(qt_scrollbar_button_down);
- }
- addButton.setColor(1, alphaCornerColor.rgba());
- addButton.setColor(2, darkOutline.rgba());
- if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken) {
- addButton.setColor(3, gradientStopColor.darker(140).rgba());
- addButton.setColor(4, gradientStopColor.darker(120).rgba());
- } else {
- addButton.setColor(3, gradientStartColor.lighter(105).rgba());
- addButton.setColor(4, gradientStopColor.rgba());
- }
- addButton.setColor(5, scrollBar->palette.text().color().rgba());
- painter->drawImage(pixmapRect, addButton);
-
- PrimitiveElement arrow;
- if (option->state & State_Horizontal)
- arrow = option->direction == Qt::LeftToRight ? PE_IndicatorArrowRight : PE_IndicatorArrowLeft;
- else
- arrow = PE_IndicatorArrowDown;
-
- QStyleOption arrowOpt = *option;
- arrowOpt.rect = scrollBarAddLine.adjusted(3, 3, -2, -2);
- proxy()->drawPrimitive(arrow, &arrowOpt, painter, widget);
- }
- }
- }
- painter->restore();
- break;;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- painter->save();
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- bool sunken = comboBox->state & State_On; // play dead, if combobox has no items
- bool isEnabled = (comboBox->state & State_Enabled);
- bool focus = isEnabled && (comboBox->state & State_HasFocus);
- QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("combobox"), option, comboBox->rect.size());
- if (sunken)
- pixmapName += QLatin1String("-sunken");
- if (comboBox->editable)
- pixmapName += QLatin1String("-editable");
- if (isEnabled)
- pixmapName += QLatin1String("-enabled");
-
- if (!QPixmapCache::find(pixmapName, cache)) {
- cache = QPixmap(comboBox->rect.size());
- cache.fill(Qt::transparent);
- QPainter cachePainter(&cache);
- QRect pixmapRect(0, 0, comboBox->rect.width(), comboBox->rect.height());
- QStyleOptionComboBox comboBoxCopy = *comboBox;
- comboBoxCopy.rect = pixmapRect;
-
- QRect rect = pixmapRect;
- QRect downArrowRect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy,
- SC_ComboBoxArrow, widget);
- QRect editRect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy,
- SC_ComboBoxEditField, widget);
- // Draw a push button
- if (comboBox->editable) {
- QStyleOptionFrame buttonOption;
- buttonOption.QStyleOption::operator=(*comboBox);
- buttonOption.rect = rect;
- buttonOption.state = comboBox->state & (State_Enabled | State_MouseOver);
-
- if (sunken) {
- buttonOption.state |= State_Sunken;
- buttonOption.state &= ~State_MouseOver;
- }
-
- proxy()->drawPrimitive(PE_PanelButtonCommand, &buttonOption, &cachePainter, widget);
-
- //remove shadow from left side of edit field when pressed:
- if (comboBox->direction != Qt::RightToLeft)
- cachePainter.fillRect(editRect.left() - 1, editRect.top() + 1, editRect.left(),
- editRect.bottom() - 3, option->palette.base());
-
- cachePainter.setPen(dark.lighter(110));
- if (!sunken) {
- int borderSize = 2;
- if (comboBox->direction == Qt::RightToLeft) {
- cachePainter.drawLine(QPoint(downArrowRect.right() - 1, downArrowRect.top() + borderSize ),
- QPoint(downArrowRect.right() - 1, downArrowRect.bottom() - borderSize));
- cachePainter.setPen(option->palette.light().color());
- cachePainter.drawLine(QPoint(downArrowRect.right(), downArrowRect.top() + borderSize),
- QPoint(downArrowRect.right(), downArrowRect.bottom() - borderSize));
- } else {
- cachePainter.drawLine(QPoint(downArrowRect.left() , downArrowRect.top() + borderSize),
- QPoint(downArrowRect.left() , downArrowRect.bottom() - borderSize));
- cachePainter.setPen(option->palette.light().color());
- cachePainter.drawLine(QPoint(downArrowRect.left() + 1, downArrowRect.top() + borderSize),
- QPoint(downArrowRect.left() + 1, downArrowRect.bottom() - borderSize));
- }
- } else {
- if (comboBox->direction == Qt::RightToLeft) {
- cachePainter.drawLine(QPoint(downArrowRect.right(), downArrowRect.top() + 2),
- QPoint(downArrowRect.right(), downArrowRect.bottom() - 2));
-
- } else {
- cachePainter.drawLine(QPoint(downArrowRect.left(), downArrowRect.top() + 2),
- QPoint(downArrowRect.left(), downArrowRect.bottom() - 2));
- }
- }
- } else {
- QStyleOptionButton buttonOption;
- buttonOption.QStyleOption::operator=(*comboBox);
- buttonOption.rect = rect;
- buttonOption.state = comboBox->state & (State_Enabled | State_MouseOver);
- if (sunken) {
- buttonOption.state |= State_Sunken;
- buttonOption.state &= ~State_MouseOver;
- }
- proxy()->drawPrimitive(PE_PanelButtonCommand, &buttonOption, &cachePainter, widget);
-
- cachePainter.setPen(buttonShadow.darker(102));
- int borderSize = 4;
-
- if (!sunken) {
- if (comboBox->direction == Qt::RightToLeft) {
- cachePainter.drawLine(QPoint(downArrowRect.right() + 1, downArrowRect.top() + borderSize),
- QPoint(downArrowRect.right() + 1, downArrowRect.bottom() - borderSize));
- cachePainter.setPen(option->palette.light().color());
- cachePainter.drawLine(QPoint(downArrowRect.right(), downArrowRect.top() + borderSize),
- QPoint(downArrowRect.right(), downArrowRect.bottom() - borderSize));
- } else {
- cachePainter.drawLine(QPoint(downArrowRect.left() - 1, downArrowRect.top() + borderSize),
- QPoint(downArrowRect.left() - 1, downArrowRect.bottom() - borderSize));
- cachePainter.setPen(option->palette.light().color());
- cachePainter.drawLine(QPoint(downArrowRect.left() , downArrowRect.top() + borderSize),
- QPoint(downArrowRect.left() , downArrowRect.bottom() - borderSize));
- }
- } else {
- cachePainter.setPen(dark.lighter(110));
- if (comboBox->direction == Qt::RightToLeft) {
- cachePainter.drawLine(QPoint(downArrowRect.right() + 1, downArrowRect.top() + borderSize),
- QPoint(downArrowRect.right() + 1, downArrowRect.bottom() - borderSize));
-
- } else {
- cachePainter.drawLine(QPoint(downArrowRect.left() - 1, downArrowRect.top() + borderSize),
- QPoint(downArrowRect.left() - 1, downArrowRect.bottom() - borderSize));
- }
- }
- }
-
-
- if (comboBox->subControls & SC_ComboBoxArrow) {
- if (comboBox->editable) {
- // Draw the down arrow
- QImage downArrow(qt_cleanlooks_arrow_down_xpm);
- downArrow.setColor(1, comboBox->palette.foreground().color().rgba());
- cachePainter.drawImage(downArrowRect.center().x() - downArrow.width() / 2,
- downArrowRect.center().y() - downArrow.height() / 2 + 1, downArrow);
- } else {
- // Draw the up/down arrow
- QImage upArrow(qt_scrollbar_button_arrow_up);
- upArrow.setColor(1, comboBox->palette.foreground().color().rgba());
- QImage downArrow(qt_scrollbar_button_arrow_down);
- downArrow.setColor(1, comboBox->palette.foreground().color().rgba());
- cachePainter.drawImage(downArrowRect.center().x() - downArrow.width() / 2,
- downArrowRect.center().y() - upArrow.height() - 1 , upArrow);
- cachePainter.drawImage(downArrowRect.center().x() - downArrow.width() / 2,
- downArrowRect.center().y() + 2, downArrow);
- }
- }
- // Draw the focus rect
- if (focus && !comboBox->editable
- && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget))) {
- QStyleOptionFocusRect focus;
- focus.rect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy, SC_ComboBoxEditField, widget)
- .adjusted(0, 2, option->direction == Qt::RightToLeft ? 1 : -1, -2);
- proxy()->drawPrimitive(PE_FrameFocusRect, &focus, &cachePainter, widget);
- }
- cachePainter.end();
- QPixmapCache::insert(pixmapName, cache);
- }
- painter->drawPixmap(comboBox->rect.topLeft(), cache);
- }
- painter->restore();
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- painter->save();
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- QRect textRect = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxLabel, widget);
- QRect checkBoxRect = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxCheckBox, widget);
- bool flat = groupBox->features & QStyleOptionFrameV2::Flat;
-
- if(!flat) {
- if (groupBox->subControls & QStyle::SC_GroupBoxFrame) {
- QStyleOptionFrameV2 frame;
- frame.QStyleOption::operator=(*groupBox);
- frame.features = groupBox->features;
- frame.lineWidth = groupBox->lineWidth;
- frame.midLineWidth = groupBox->midLineWidth;
- frame.rect = proxy()->subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);
-
- painter->save();
- QRegion region(groupBox->rect);
- bool ltr = groupBox->direction == Qt::LeftToRight;
- region -= checkBoxRect.united(textRect).adjusted(ltr ? -4 : 0, 0, ltr ? 0 : 4, 0);
- if (!groupBox->text.isEmpty() || groupBox->subControls & SC_GroupBoxCheckBox)
- painter->setClipRegion(region);
- frame.palette.setBrush(QPalette::Dark, option->palette.mid().color().lighter(110));
- proxy()->drawPrimitive(PE_FrameGroupBox, &frame, painter);
- painter->restore();
- }
- }
- // Draw title
- if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
- if (!groupBox->text.isEmpty()) {
- QColor textColor = groupBox->textColor;
- if (textColor.isValid())
- painter->setPen(textColor);
- int alignment = int(groupBox->textAlignment);
- if (!styleHint(QStyle::SH_UnderlineShortcut, option, widget))
- alignment |= Qt::TextHideMnemonic;
- if (flat) {
- QFont font = painter->font();
- font.setBold(true);
- painter->setFont(font);
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- textRect.adjust(checkBoxRect.right() + 4, 0, checkBoxRect.right() + 4, 0);
- }
- }
- painter->drawText(textRect, Qt::TextShowMnemonic | Qt::AlignLeft| alignment, groupBox->text);
- }
- }
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*groupBox);
- box.rect = checkBoxRect;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &box, painter, widget);
- }
- }
- painter->restore();
- break;
-#endif // QT_NO_GROUPBOX
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- QRect groove = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget);
- QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget);
- QRect ticks = proxy()->subControlRect(CC_Slider, option, SC_SliderTickmarks, widget);
-
- bool horizontal = slider->orientation == Qt::Horizontal;
- bool ticksAbove = slider->tickPosition & QSlider::TicksAbove;
- bool ticksBelow = slider->tickPosition & QSlider::TicksBelow;
- QColor activeHighlight = option->palette.color(QPalette::Normal, QPalette::Highlight);
- QPixmap cache;
-
- QBrush oldBrush = painter->brush();
- QPen oldPen = painter->pen();
-
- QColor shadowAlpha(Qt::black);
- shadowAlpha.setAlpha(10);
- QColor highlightAlpha(Qt::white);
- highlightAlpha.setAlpha(80);
-
- if ((option->subControls & SC_SliderGroove) && groove.isValid()) {
- QString groovePixmapName = QStyleHelper::uniqueName(QLatin1String("slider_groove"), option, groove.size());
- QRect pixmapRect(0, 0, groove.width(), groove.height());
-
- // draw background groove
- if (!QPixmapCache::find(groovePixmapName, cache)) {
- cache = QPixmap(pixmapRect.size());
- cache.fill(Qt::transparent);
- QPainter groovePainter(&cache);
-
- groovePainter.setPen(shadowAlpha);
- groovePainter.drawLine(1, 0, groove.width(), 0);
- groovePainter.drawLine(0, 0, 0, groove.height() - 1);
-
- groovePainter.setPen(highlightAlpha);
- groovePainter.drawLine(1, groove.height() - 1, groove.width() - 1, groove.height() - 1);
- groovePainter.drawLine(groove.width() - 1, 1, groove.width() - 1, groove.height() - 1);
- QLinearGradient gradient;
- if (horizontal) {
- gradient.setStart(pixmapRect.center().x(), pixmapRect.top());
- gradient.setFinalStop(pixmapRect.center().x(), pixmapRect.bottom());
- }
- else {
- gradient.setStart(pixmapRect.left(), pixmapRect.center().y());
- gradient.setFinalStop(pixmapRect.right(), pixmapRect.center().y());
- }
- groovePainter.setPen(QPen(darkOutline.darker(110), 0));
- gradient.setColorAt(0, grooveColor.darker(110));//dark.lighter(120));
- gradient.setColorAt(1, grooveColor.lighter(110));//palette.button().color().darker(115));
- groovePainter.setBrush(gradient);
- groovePainter.drawRect(pixmapRect.adjusted(1, 1, -2, -2));
- groovePainter.end();
- QPixmapCache::insert(groovePixmapName, cache);
- }
- painter->drawPixmap(groove.topLeft(), cache);
-
- // draw blue groove highlight
- QRect clipRect;
- groovePixmapName += QLatin1String("_blue");
- if (!QPixmapCache::find(groovePixmapName, cache)) {
- cache = QPixmap(pixmapRect.size());
- cache.fill(Qt::transparent);
- QPainter groovePainter(&cache);
- QLinearGradient gradient;
- if (horizontal) {
- gradient.setStart(pixmapRect.center().x(), pixmapRect.top());
- gradient.setFinalStop(pixmapRect.center().x(), pixmapRect.bottom());
- }
- else {
- gradient.setStart(pixmapRect.left(), pixmapRect.center().y());
- gradient.setFinalStop(pixmapRect.right(), pixmapRect.center().y());
- }
- groovePainter.setPen(QPen(activeHighlight.darker(150), 0));
- gradient.setColorAt(0, activeHighlight.darker(120));
- gradient.setColorAt(1, activeHighlight.lighter(160));
- groovePainter.setBrush(gradient);
- groovePainter.drawRect(pixmapRect.adjusted(1, 1, -2, -2));
- groovePainter.end();
- QPixmapCache::insert(groovePixmapName, cache);
- }
- if (horizontal) {
- if (slider->upsideDown)
- clipRect = QRect(handle.right(), groove.top(), groove.right() - handle.right(), groove.height());
- else
- clipRect = QRect(groove.left(), groove.top(), handle.left(), groove.height());
- } else {
- if (slider->upsideDown)
- clipRect = QRect(groove.left(), handle.bottom(), groove.width(), groove.height() - handle.bottom());
- else
- clipRect = QRect(groove.left(), groove.top(), groove.width(), handle.top() - groove.top());
- }
- painter->save();
- painter->setClipRect(clipRect.adjusted(0, 0, 1, 1));
- painter->drawPixmap(groove.topLeft(), cache);
- painter->restore();
- }
-
- // draw handle
- if ((option->subControls & SC_SliderHandle) ) {
- QString handlePixmapName = QStyleHelper::uniqueName(QLatin1String("slider_handle"), option, handle.size());
- if (!QPixmapCache::find(handlePixmapName, cache)) {
- cache = QPixmap(handle.size());
- cache.fill(Qt::transparent);
- QRect pixmapRect(0, 0, handle.width(), handle.height());
- QPainter handlePainter(&cache);
-
- QColor highlightedGradientStartColor = option->palette.button().color();
- QColor highlightedGradientStopColor = option->palette.light().color();
- QColor gradientStartColor = mergedColors(option->palette.button().color().lighter(155),
- dark.lighter(155), 50);
- QColor gradientStopColor = gradientStartColor.darker(108);
- QRect gradRect = pixmapRect.adjusted(2, 2, -2, -2);
-
- QColor gradientBgStartColor = gradientStartColor;
- QColor gradientBgStopColor = gradientStopColor;
-
- QColor outline = option->state & State_Enabled ? dark : dark.lighter(130);
- if (option->state & State_Enabled && option->activeSubControls & SC_SliderHandle) {
- gradientBgStartColor = option->palette.highlight().color().lighter(180);
- gradientBgStopColor = option->palette.highlight().color().lighter(110);
- outline = option->palette.highlight().color().darker(130);
- }
-
- // gradient fill
- QRect innerBorder = gradRect;
- QRect r = pixmapRect.adjusted(1, 1, -1, -1);
-
- qt_cleanlooks_draw_gradient(&handlePainter, gradRect,
- gradientBgStartColor,
- gradientBgStopColor,
- horizontal ? TopDown : FromLeft, option->palette.button());
-
- handlePainter.setPen(QPen(outline.darker(110), 1));
- handlePainter.drawLine(QPoint(r.left(), r.top() + 3), QPoint(r.left(), r.bottom() - 3));
- handlePainter.drawLine(QPoint(r.right(), r.top() + 3), QPoint(r.right(), r.bottom() - 3));
- handlePainter.drawLine(QPoint(r.left() + 3, r.bottom()), QPoint(r.right() - 3, r.bottom()));
-
- handlePainter.save();
- handlePainter.setRenderHint(QPainter::Antialiasing);
- handlePainter.translate(0.5, 0.5);
- const QLine lines[4] = {
- QLine(QPoint(r.left(), r.bottom() - 2), QPoint(r.left() + 2, r.bottom())),
- QLine(QPoint(r.left(), r.top() + 2), QPoint(r.left() + 2, r.top())),
- QLine(QPoint(r.right(), r.bottom() - 2), QPoint(r.right() - 2, r.bottom())),
- QLine(QPoint(r.right(), r.top() + 2), QPoint(r.right() - 2, r.top()))
- };
- handlePainter.drawLines(lines, 4);
- handlePainter.restore();;
- handlePainter.setPen(QPen(outline.darker(130), 1));
- handlePainter.drawLine(QPoint(r.left() + 3, r.top()), QPoint(r.right() - 3, r.top()));
- QColor cornerAlpha = outline.darker(120);
- cornerAlpha.setAlpha(80);
-
- handlePainter.setPen(cornerAlpha);
- if (horizontal) {
- handlePainter.drawLine(QPoint(r.left() + 6, r.top()), QPoint(r.left() + 6, r.bottom()));
- handlePainter.drawLine(QPoint(r.right() - 6, r.top()), QPoint(r.right() - 6, r.bottom()));
- } else {
- handlePainter.drawLine(QPoint(r.left(), r.top() + 6), QPoint(r.right(), r.top() + 6));
- handlePainter.drawLine(QPoint(r.left(), r.bottom() - 6), QPoint(r.right(), r.bottom() - 6));
- }
-
- //handle shadow
- handlePainter.setPen(shadowAlpha);
- handlePainter.drawLine(QPoint(r.left() + 2, r.bottom() + 1), QPoint(r.right() - 2, r.bottom() + 1));
- handlePainter.drawLine(QPoint(r.right() + 1, r.bottom() - 3), QPoint(r.right() + 1, r.top() + 4));
- handlePainter.drawLine(QPoint(r.right() - 1, r.bottom()), QPoint(r.right() + 1, r.bottom() - 2));
-
- qt_cleanlooks_draw_gradient(&handlePainter, horizontal ?
- gradRect.adjusted(6, 0, -6, 0) : gradRect.adjusted(0, 6, 0, -6),
- gradientStartColor,
- gradientStopColor.darker(106),
- horizontal ? TopDown : FromLeft,
- option->palette.button());
-
- //draw grips
- for (int i = -3; i< 6 ; i += 3) {
- for (int j = -3; j< 6 ; j += 3) {
- handlePainter.fillRect(r.center().x() + i, r.center().y() + j, 2, 2, highlightAlpha);
- handlePainter.setPen(gripShadow);
- handlePainter.drawPoint(r.center().x() + i, r.center().y() + j );
- }
- }
- handlePainter.end();
- QPixmapCache::insert(handlePixmapName, cache);
- }
-
- painter->drawPixmap(handle.topLeft(), cache);
-
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = slider->rect;
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- }
- if (option->subControls & SC_SliderTickmarks) {
- painter->setPen(darkOutline);
- int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
- int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
- int interval = slider->tickInterval;
- if (interval <= 0) {
- interval = slider->singleStep;
- if (QStyle::sliderPositionFromValue(slider->minimum, slider->maximum, interval,
- available)
- - QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- 0, available) < 3)
- interval = slider->pageStep;
- }
- if (interval <= 0)
- interval = 1;
-
- int v = slider->minimum;
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- while (v <= slider->maximum + 1) {
- if (v == slider->maximum + 1 && interval == 1)
- break;
- const int v_ = qMin(v, slider->maximum);
- int pos = sliderPositionFromValue(slider->minimum, slider->maximum,
- v_, (horizontal
- ? slider->rect.width()
- : slider->rect.height()) - len,
- slider->upsideDown) + len / 2;
- int extra = 2 - ((v_ == slider->minimum || v_ == slider->maximum) ? 1 : 0);
-
- if (horizontal) {
- if (ticksAbove) {
- painter->drawLine(pos, slider->rect.top() + extra,
- pos, slider->rect.top() + tickSize);
- }
- if (ticksBelow) {
- painter->drawLine(pos, slider->rect.bottom() - extra,
- pos, slider->rect.bottom() - tickSize);
- }
- } else {
- if (ticksAbove) {
- painter->drawLine(slider->rect.left() + extra, pos,
- slider->rect.left() + tickSize, pos);
- }
- if (ticksBelow) {
- painter->drawLine(slider->rect.right() - extra, pos,
- slider->rect.right() - tickSize, pos);
- }
- }
- // in the case where maximum is max int
- int nextInterval = v + interval;
- if (nextInterval < v)
- break;
- v = nextInterval;
- }
- }
- painter->setBrush(oldBrush);
- painter->setPen(oldPen);
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_DIAL
- case CC_Dial:
- if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(option))
- QStyleHelper::drawDial(dial, painter);
- break;
-#endif // QT_NO_DIAL
- default:
- QWindowsStyle::drawComplexControl(control, option, painter, widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-int QCleanlooksStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
-{
- int ret = -1;
- switch (metric) {
- case PM_ToolTipLabelFrameWidth:
- ret = 2;
- break;
- case PM_ButtonDefaultIndicator:
- ret = 0;
- break;
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- ret = 0;
- break;
- case PM_MessageBoxIconSize:
- ret = 48;
- break;
- case PM_ListViewIconSize:
- ret = 24;
- break;
- case PM_DialogButtonsSeparator:
- case PM_SplitterWidth:
- ret = 6;
- break;
- case PM_ScrollBarSliderMin:
- ret = 26;
- break;
- case PM_MenuPanelWidth: //menu framewidth
- ret = 2;
- break;
- case PM_TitleBarHeight:
- ret = 24;
- break;
- case PM_ScrollBarExtent:
- ret = 15;
- break;
- case PM_SliderThickness:
- ret = 15;
- break;
- case PM_SliderLength:
- ret = 27;
- break;
- case PM_DockWidgetTitleMargin:
- ret = 1;
- break;
- case PM_MenuBarVMargin:
- ret = 1;
- break;
- case PM_DefaultFrameWidth:
- ret = 2;
- break;
- case PM_SpinBoxFrameWidth:
- ret = 3;
- break;
- case PM_MenuBarItemSpacing:
- ret = 6;
- break;
- case PM_MenuBarHMargin:
- ret = 0;
- break;
- case PM_ToolBarHandleExtent:
- ret = 9;
- break;
- case PM_ToolBarItemSpacing:
- ret = 2;
- break;
- case PM_ToolBarFrameWidth:
- ret = 0;
- break;
- case PM_ToolBarItemMargin:
- ret = 1;
- break;
- case PM_SmallIconSize:
- ret = 16;
- break;
- case PM_ButtonIconSize:
- ret = 24;
- break;
- case PM_MenuVMargin:
- case PM_MenuHMargin:
- ret = 0;
- break;
- case PM_DockWidgetTitleBarButtonMargin:
- ret = 4;
- break;
- case PM_MaximumDragDistance:
- return -1;
- case PM_TabCloseIndicatorWidth:
- case PM_TabCloseIndicatorHeight:
- return 20;
- default:
- break;
- }
-
- return ret != -1 ? ret : QWindowsStyle::pixelMetric(metric, option, widget);
-}
-
-/*!
- \reimp
-*/
-QSize QCleanlooksStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const
-{
- QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget);
- switch (type) {
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- if (!btn->text.isEmpty() && newSize.width() < 80)
- newSize.setWidth(80);
- if (!btn->icon.isNull() && btn->iconSize.height() > 16)
- newSize -= QSize(0, 2);
- newSize += QSize(0, 1);
- }
- if (const QPushButton *button = qobject_cast<const QPushButton *>(widget)) {
- if (qobject_cast<const QDialogButtonBox *>(button->parentWidget())) {
- if (newSize.height() < 32)
- newSize.setHeight(32);
- }
- }
- break;
-#ifndef QT_NO_GROUPBOX
- case CT_GroupBox:
- // Since we use a bold font we have to recalculate base width
- if (const QGroupBox *gb = qobject_cast<const QGroupBox*>(widget)) {
- QFont font = gb->font();
- font.setBold(true);
- QFontMetrics metrics(font);
- int baseWidth = metrics.width(gb->title()) + metrics.width(QLatin1Char(' '));
- if (gb->isCheckable()) {
- baseWidth += proxy()->pixelMetric(QStyle::PM_IndicatorWidth, option, widget);
- baseWidth += proxy()->pixelMetric(QStyle::PM_CheckBoxLabelSpacing, option, widget);
- }
- newSize.setWidth(qMax(baseWidth, newSize.width()));
- }
- newSize += QSize(0, 1);
- break;
-#endif //QT_NO_GROUPBOX
- case CT_RadioButton:
- case CT_CheckBox:
- newSize += QSize(0, 1);
- break;
- case CT_ToolButton:
-#ifndef QT_NO_TOOLBAR
- if (widget && qobject_cast<QToolBar *>(widget->parentWidget()))
- newSize += QSize(4, 6);
-#endif // QT_NO_TOOLBAR
- break;
- case CT_SpinBox:
- newSize += QSize(0, -2);
- break;
- case CT_ComboBox:
- newSize += QSize(2, 4);
- break;
- case CT_LineEdit:
- newSize += QSize(0, 4);
- break;
- case CT_MenuBarItem:
- newSize += QSize(0, 2);
- break;
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
- if (!menuItem->text.isEmpty()) {
- newSize.setHeight(menuItem->fontMetrics.height());
- }
- }
-#ifndef QT_NO_COMBOBOX
- else if (!menuItem->icon.isNull()) {
- if (const QComboBox *combo = qobject_cast<const QComboBox*>(widget)) {
- newSize.setHeight(qMax(combo->iconSize().height() + 2, newSize.height()));
- }
- }
-#endif // QT_NO_COMBOBOX
- }
- break;
- case CT_SizeGrip:
- newSize += QSize(4, 4);
- break;
- case CT_MdiControls:
- if (const QStyleOptionComplex *styleOpt = qstyleoption_cast<const QStyleOptionComplex *>(option)) {
- int width = 0;
- if (styleOpt->subControls & SC_MdiMinButton)
- width += 19 + 1;
- if (styleOpt->subControls & SC_MdiNormalButton)
- width += 19 + 1;
- if (styleOpt->subControls & SC_MdiCloseButton)
- width += 19 + 1;
- newSize = QSize(width, 19);
- } else {
- newSize = QSize(60, 19);
- }
- break;
- default:
- break;
- }
- return newSize;
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::polish(QApplication *app)
-{
- QWindowsStyle::polish(app);
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::polish(QWidget *widget)
-{
- QWindowsStyle::polish(widget);
- if (qobject_cast<QAbstractButton*>(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<QComboBox *>(widget)
-#endif
-#ifndef QT_NO_PROGRESSBAR
- || qobject_cast<QProgressBar *>(widget)
-#endif
-#ifndef QT_NO_SCROLLBAR
- || qobject_cast<QScrollBar *>(widget)
-#endif
-#ifndef QT_NO_SPLITTER
- || qobject_cast<QSplitterHandle *>(widget)
-#endif
- || qobject_cast<QAbstractSlider *>(widget)
-#ifndef QT_NO_SPINBOX
- || qobject_cast<QAbstractSpinBox *>(widget)
-#endif
- || (widget->inherits("QWorkspaceChild"))
- || (widget->inherits("QDockSeparator"))
- || (widget->inherits("QDockWidgetSeparator"))
- ) {
- widget->setAttribute(Qt::WA_Hover, true);
- }
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::polish(QPalette &pal)
-{
- QWindowsStyle::polish(pal);
- //this is a workaround for some themes such as Human, where the contrast
- //between text and background is too low.
- QColor highlight = pal.highlight().color();
- QColor highlightText = pal.highlightedText().color();
- if (qAbs(qGray(highlight.rgb()) - qGray(highlightText.rgb())) < 150) {
- if (qGray(highlightText.rgb()) < 128)
- pal.setBrush(QPalette::Highlight, highlight.lighter(145));
- }
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::unpolish(QWidget *widget)
-{
- QWindowsStyle::unpolish(widget);
- if (qobject_cast<QAbstractButton*>(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<QComboBox *>(widget)
-#endif
-#ifndef QT_NO_PROGRESSBAR
- || qobject_cast<QProgressBar *>(widget)
-#endif
-#ifndef QT_NO_SCROLLBAR
- || qobject_cast<QScrollBar *>(widget)
-#endif
-#ifndef QT_NO_SPLITTER
- || qobject_cast<QSplitterHandle *>(widget)
-#endif
- || qobject_cast<QAbstractSlider *>(widget)
-#ifndef QT_NO_SPINBOX
- || qobject_cast<QAbstractSpinBox *>(widget)
-#endif
- || (widget->inherits("QWorkspaceChild"))
- || (widget->inherits("QDockSeparator"))
- || (widget->inherits("QDockWidgetSeparator"))
- ) {
- widget->setAttribute(Qt::WA_Hover, false);
- }
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::unpolish(QApplication *app)
-{
- QWindowsStyle::unpolish(app);
-}
-
-/*!
- \reimp
-*/
-QRect QCleanlooksStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const
-{
- QRect rect = QWindowsStyle::subControlRect(control, option, subControl, widget);
-
- switch (control) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
- switch (subControl) {
- case SC_SliderHandle: {
- if (slider->orientation == Qt::Horizontal) {
- rect.setHeight(proxy()->pixelMetric(PM_SliderThickness));
- rect.setWidth(proxy()->pixelMetric(PM_SliderLength));
- int centerY = slider->rect.center().y() - rect.height() / 2;
- if (slider->tickPosition & QSlider::TicksAbove)
- centerY += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- centerY -= tickSize;
- rect.moveTop(centerY);
- } else {
- rect.setWidth(proxy()->pixelMetric(PM_SliderThickness));
- rect.setHeight(proxy()->pixelMetric(PM_SliderLength));
- int centerX = slider->rect.center().x() - rect.width() / 2;
- if (slider->tickPosition & QSlider::TicksAbove)
- centerX += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- centerX -= tickSize;
- rect.moveLeft(centerX);
- }
- }
- break;
- case SC_SliderGroove: {
- QPoint grooveCenter = slider->rect.center();
- if (slider->orientation == Qt::Horizontal) {
- rect.setHeight(7);
- if (slider->tickPosition & QSlider::TicksAbove)
- grooveCenter.ry() += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- grooveCenter.ry() -= tickSize;
- } else {
- rect.setWidth(7);
- if (slider->tickPosition & QSlider::TicksAbove)
- grooveCenter.rx() += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- grooveCenter.rx() -= tickSize;
- }
- rect.moveCenter(grooveCenter);
- break;
- }
- default:
- break;
- }
- }
- break;
-#endif // QT_NO_SLIDER
- case CC_ScrollBar:
- break;
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QSize bs;
- int center = spinbox->rect.height() / 2;
- int fw = spinbox->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
- int y = fw;
- bs.setHeight(qMax(8, spinbox->rect.height()/2 - y));
- bs.setWidth(15);
- int x, lx, rx;
- x = spinbox->rect.width() - y - bs.width() + 2;
- lx = fw;
- rx = x - fw;
- switch (subControl) {
- case SC_SpinBoxUp:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- rect = QRect(x, fw, bs.width(), center - fw);
- break;
- case SC_SpinBoxDown:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
-
- rect = QRect(x, center, bs.width(), spinbox->rect.bottom() - center - fw + 1);
- break;
- case SC_SpinBoxEditField:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons) {
- rect = QRect(lx, fw, spinbox->rect.width() - 2*fw, spinbox->rect.height() - 2*fw);
- } else {
- rect = QRect(lx, fw, rx - qMax(fw - 1, 0), spinbox->rect.height() - 2*fw);
- }
- break;
- case SC_SpinBoxFrame:
- rect = spinbox->rect;
- default:
- break;
- }
- rect = visualRect(spinbox->direction, spinbox->rect, rect);
- }
- break;
-#endif // Qt_NO_SPINBOX
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- int topMargin = 0;
- int topHeight = 0;
- int verticalAlignment = proxy()->styleHint(SH_GroupBox_TextLabelVerticalAlignment, groupBox, widget);
- bool flat = groupBox->features & QStyleOptionFrameV2::Flat;
- if (!groupBox->text.isEmpty()) {
- topHeight = groupBox->fontMetrics.height();
- if (verticalAlignment & Qt::AlignVCenter)
- topMargin = topHeight / 2;
- else if (verticalAlignment & Qt::AlignTop)
- topMargin = topHeight;
- }
- QRect frameRect = groupBox->rect;
- frameRect.setTop(topMargin);
- if (subControl == SC_GroupBoxFrame) {
- return rect;
- }
- else if (subControl == SC_GroupBoxContents) {
- if( flat ) {
- int margin = 0;
- int leftMarginExtension = 16;
- rect = frameRect.adjusted(leftMarginExtension + margin, margin + topHeight, -margin, -margin);
- }
- break;
- }
- if(flat) {
- if (const QGroupBox *groupBoxWidget = qobject_cast<const QGroupBox *>(widget)) {
- //Prepare metrics for a bold font
- QFont font = widget->font();
- font.setBold(true);
- QFontMetrics fontMetrics(font);
-
- QSize textRect = fontMetrics.boundingRect(groupBoxWidget->title()).size() + QSize(2, 2);
- if (subControl == SC_GroupBoxCheckBox) {
- int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, option, widget);
- int indicatorHeight = proxy()->pixelMetric(PM_IndicatorHeight, option, widget);
- rect.setWidth(indicatorWidth);
- rect.setHeight(indicatorHeight);
- rect.moveTop((fontMetrics.height() - indicatorHeight) / 2 + 2);
- } else if (subControl == SC_GroupBoxLabel) {
- rect.setSize(textRect);
- }
- }
- }
- }
- return rect;
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- switch (subControl) {
- case SC_ComboBoxArrow:
- rect = visualRect(option->direction, option->rect, rect);
- rect.setRect(rect.right() - 18, rect.top() - 2,
- 19, rect.height() + 4);
- rect = visualRect(option->direction, option->rect, rect);
- break;
- case SC_ComboBoxEditField: {
- int frameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth);
- rect = visualRect(option->direction, option->rect, rect);
- rect.setRect(option->rect.left() + frameWidth, option->rect.top() + frameWidth,
- option->rect.width() - 19 - 2 * frameWidth,
- option->rect.height() - 2 * frameWidth);
- if (const QStyleOptionComboBox *box = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- if (!box->editable) {
- rect.adjust(2, 0, 0, 0);
- if (box->state & (State_Sunken | State_On))
- rect.translate(1, 1);
- }
- }
- rect = visualRect(option->direction, option->rect, rect);
- break;
- }
- default:
- break;
- }
- break;
-#endif // QT_NO_COMBOBOX
-#endif //QT_NO_GROUPBOX
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- SubControl sc = subControl;
- QRect &ret = rect;
- const int indent = 3;
- const int controlTopMargin = 3;
- const int controlBottomMargin = 3;
- const int controlWidthMargin = 2;
- const int controlHeight = tb->rect.height() - controlTopMargin - controlBottomMargin ;
- const int delta = controlHeight + controlWidthMargin;
- int offset = 0;
-
- bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
-
- switch (sc) {
- case SC_TitleBarLabel:
- if (tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)) {
- ret = tb->rect;
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- ret.adjust(delta, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowMinimizeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowMaximizeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowShadeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- ret.adjust(0, 0, -delta, 0);
- }
- break;
- case SC_TitleBarContextHelpButton:
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- offset += delta;
- case SC_TitleBarMinButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarMinButton)
- break;
- case SC_TitleBarNormalButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarNormalButton)
- break;
- case SC_TitleBarMaxButton:
- if (!isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarMaxButton)
- break;
- case SC_TitleBarShadeButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarShadeButton)
- break;
- case SC_TitleBarUnshadeButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarUnshadeButton)
- break;
- case SC_TitleBarCloseButton:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- offset += delta;
- else if (sc == SC_TitleBarCloseButton)
- break;
- ret.setRect(tb->rect.right() - indent - offset, tb->rect.top() + controlTopMargin,
- controlHeight, controlHeight);
- break;
- case SC_TitleBarSysMenu:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- ret.setRect(tb->rect.left() + controlWidthMargin + indent, tb->rect.top() + controlTopMargin,
- controlHeight, controlHeight);
- }
- break;
- default:
- break;
- }
- ret = visualRect(tb->direction, tb->rect, ret);
- }
- break;
- default:
- break;
- }
-
- return rect;
-}
-
-
-/*!
- \reimp
-*/
-QRect QCleanlooksStyle::itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const
-{
- return QWindowsStyle::itemPixmapRect(r, flags, pixmap);
-}
-
-/*!
- \reimp
-*/
-void QCleanlooksStyle::drawItemPixmap(QPainter *painter, const QRect &rect,
- int alignment, const QPixmap &pixmap) const
-{
- QWindowsStyle::drawItemPixmap(painter, rect, alignment, pixmap);
-}
-
-/*!
- \reimp
-*/
-QStyle::SubControl QCleanlooksStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w) const
-{
- return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
-}
-
-/*!
- \reimp
-*/
-QPixmap QCleanlooksStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const
-{
- return QWindowsStyle::generatedIconPixmap(iconMode, pixmap, opt);
-}
-
-/*!
- \reimp
-*/
-int QCleanlooksStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget,
- QStyleHintReturn *returnData) const
-{
- int ret = 0;
- switch (hint) {
- case SH_ScrollBar_MiddleClickAbsolutePosition:
- ret = true;
- break;
- case SH_EtchDisabledText:
- ret = 1;
- break;
- case SH_Menu_AllowActiveAndDisabled:
- ret = false;
- break;
- case SH_MainWindow_SpaceBelowMenuBar:
- ret = 0;
- break;
- case SH_MenuBar_MouseTracking:
- ret = 1;
- break;
- case SH_TitleBar_AutoRaise:
- ret = 1;
- break;
- case SH_TitleBar_NoBorder:
- ret = 1;
- break;
- case SH_ItemView_ShowDecorationSelected:
- ret = true;
- break;
- case SH_Table_GridLineColor:
- if (option) {
- ret = option->palette.background().color().darker(120).rgb();
- break;
- }
- case SH_ComboBox_Popup:
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3ComboBox"))
- return 0;
-#endif
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option))
- ret = !cmb->editable;
- else
- ret = 0;
- break;
- case SH_WindowFrame_Mask:
- ret = 1;
- if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask *>(returnData)) {
- //left rounded corner
- mask->region = option->rect;
- mask->region -= QRect(option->rect.left(), option->rect.top(), 5, 1);
- mask->region -= QRect(option->rect.left(), option->rect.top() + 1, 3, 1);
- mask->region -= QRect(option->rect.left(), option->rect.top() + 2, 2, 1);
- mask->region -= QRect(option->rect.left(), option->rect.top() + 3, 1, 2);
-
- //right rounded corner
- mask->region -= QRect(option->rect.right() - 4, option->rect.top(), 5, 1);
- mask->region -= QRect(option->rect.right() - 2, option->rect.top() + 1, 3, 1);
- mask->region -= QRect(option->rect.right() - 1, option->rect.top() + 2, 2, 1);
- mask->region -= QRect(option->rect.right() , option->rect.top() + 3, 1, 2);
- }
- break;
- case SH_MessageBox_TextInteractionFlags:
- ret = Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse;
- break;
- case SH_DialogButtonBox_ButtonsHaveIcons:
- ret = true;
- break;
- case SH_MessageBox_CenterButtons:
- ret = false;
- break;
-#ifndef QT_NO_WIZARD
- case SH_WizardStyle:
- ret = QWizard::ClassicStyle;
- break;
-#endif
- case SH_ItemView_ArrowKeysNavigateIntoChildren:
- ret = false;
- break;
- case SH_Menu_SubMenuPopupDelay:
- ret = 225; // default from GtkMenu
- break;
- default:
- ret = QWindowsStyle::styleHint(hint, option, widget, returnData);
- break;
- }
- return ret;
-}
-
-/*! \reimp */
-QRect QCleanlooksStyle::subElementRect(SubElement sr, const QStyleOption *opt, const QWidget *w) const
-{
- QRect r = QWindowsStyle::subElementRect(sr, opt, w);
- switch (sr) {
- case SE_PushButtonFocusRect:
- r.adjust(0, 1, 0, -1);
- break;
- case SE_DockWidgetTitleBarText: {
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
- if (verticalTitleBar) {
- r.adjust(0, 0, 0, -4);
- } else {
- if (opt->direction == Qt::LeftToRight)
- r.adjust(4, 0, 0, 0);
- else
- r.adjust(0, 0, -4, 0);
- }
-
- break;
- }
- case SE_ProgressBarContents:
- r = subElementRect(SE_ProgressBarGroove, opt, w);
- break;
- default:
- break;
- }
- return r;
-}
-
-/*!
- \internal
-*/
-QIcon QCleanlooksStyle::standardIconImplementation(StandardPixmap standardIcon,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- return QWindowsStyle::standardIconImplementation(standardIcon, option, widget);
-}
-
-/*!
- \reimp
- */
-QPixmap QCleanlooksStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget) const
-{
- QPixmap pixmap;
-
-#ifndef QT_NO_IMAGEFORMAT_XPM
- switch (standardPixmap) {
- case SP_TitleBarNormalButton:
- return QPixmap((const char **)dock_widget_restore_xpm);
- case SP_TitleBarMinButton:
- return QPixmap((const char **)workspace_minimize);
- case SP_TitleBarCloseButton:
- case SP_DockWidgetCloseButton:
- return QPixmap((const char **)dock_widget_close_xpm);
-
- default:
- break;
- }
-#endif //QT_NO_IMAGEFORMAT_XPM
-
- return QWindowsStyle::standardPixmap(standardPixmap, opt, widget);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_CLEANLOOKS || QT_PLUGIN
diff --git a/src/gui/styles/qcleanlooksstyle.h b/src/gui/styles/qcleanlooksstyle.h
deleted file mode 100644
index 9ffa5789c0..0000000000
--- a/src/gui/styles/qcleanlooksstyle.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/****************************************************************************
-**
-** 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 QCLEANLOOKSSTYLE_H
-#define QCLEANLOOKSSTYLE_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_CLEANLOOKS)
-
-class QCleanlooksStylePrivate;
-class Q_GUI_EXPORT QCleanlooksStyle : public QWindowsStyle
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QCleanlooksStyle)
-
-public:
- QCleanlooksStyle();
- ~QCleanlooksStyle();
-
- QPalette standardPalette () const;
- void drawPrimitive(PrimitiveElement elem,
- const QStyleOption *option,
- QPainter *painter, const QWidget *widget = 0) const;
- void drawControl(ControlElement ce, const QStyleOption *option, QPainter *painter,
- const QWidget *widget) const;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
- QSize sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const;
- SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const;
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const;
- int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
- QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const;
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const;
- void drawItemPixmap(QPainter *painter, const QRect &rect,
- int alignment, const QPixmap &pixmap) const;
- void drawItemText(QPainter *painter, const QRect &rect,
- int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const;
- void polish(QWidget *widget);
- void polish(QApplication *app);
- void polish(QPalette &pal);
- void unpolish(QWidget *widget);
- void unpolish(QApplication *app);
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget = 0) const;
-
-protected:
- QCleanlooksStyle(QCleanlooksStylePrivate &dd);
-
-};
-
-#endif // QT_NO_STYLE_CLEANLOOKS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCLEANLOOKSSTYLE_H
diff --git a/src/gui/styles/qcleanlooksstyle_p.h b/src/gui/styles/qcleanlooksstyle_p.h
deleted file mode 100644
index 52cc282578..0000000000
--- a/src/gui/styles/qcleanlooksstyle_p.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** 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 QCLEANLOOKSSTYLE_P_H
-#define QCLEANLOOKSSTYLE_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qwindowsstyle.h"
-#include "qwindowsstyle_p.h"
-
-#ifndef QT_NO_STYLE_CLEANLOOKS
-
-QT_BEGIN_NAMESPACE
-
-class QCleanlooksStylePrivate : public QWindowsStylePrivate
-{
- Q_DECLARE_PUBLIC(QCleanlooksStyle)
-public:
- QCleanlooksStylePrivate()
- : QWindowsStylePrivate() {
- animationFps = 24;
- }
-
- ~QCleanlooksStylePrivate() {
- }
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_CLEANLOOKS
-
-#endif //QCLEANLOOKSSTYLE_P_H
diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp
deleted file mode 100644
index 8f99d6ad26..0000000000
--- a/src/gui/styles/qcommonstyle.cpp
+++ /dev/null
@@ -1,6085 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcommonstyle.h"
-#include "qcommonstyle_p.h"
-
-#include <qfile.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcache.h>
-#include <qdockwidget.h>
-#include <qdrawutil.h>
-#include <qdialogbuttonbox.h>
-#include <qformlayout.h>
-#include <qgroupbox.h>
-#include <qmath.h>
-#include <qmenu.h>
-#include <qpainter.h>
-#include <qpaintengine.h>
-#include <qpainterpath.h>
-#include <qslider.h>
-#include <qstyleoption.h>
-#include <qtabbar.h>
-#include <qtabwidget.h>
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qrubberband.h>
-#include <private/qcommonstylepixmaps_p.h>
-#include <private/qmath_p.h>
-#include <qdebug.h>
-#include <qtextformat.h>
-#include <qwizard.h>
-#include <qtabbar.h>
-#include <qfileinfo.h>
-#include <qdir.h>
-#include <qsettings.h>
-#include <qpixmapcache.h>
-#include <private/qguiplatformplugin_p.h>
-
-#include <limits.h>
-
-#ifndef QT_NO_ITEMVIEWS
-# include "private/qtextengine_p.h"
-#endif
-
-#ifdef Q_WS_X11
-# include <private/qt_x11_p.h>
-#elif defined(Q_WS_MAC)
-# include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#include <private/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QCommonStyle
- \brief The QCommonStyle class encapsulates the common Look and Feel of a GUI.
-
- \ingroup appearance
-
- This abstract class implements some of the widget's look and feel
- that is common to all GUI styles provided and shipped as part of
- Qt.
-
- Since QCommonStyle inherits QStyle, all of its functions are fully documented
- in the QStyle documentation.
- \omit
- , although the
- extra functions that QCommonStyle provides, e.g.
- drawComplexControl(), drawControl(), drawPrimitive(),
- hitTestComplexControl(), subControlRect(), sizeFromContents(), and
- subElementRect() are documented here.
- \endomit
-
- \sa QStyle, QMotifStyle, QWindowsStyle
-*/
-
-/*!
- Constructs a QCommonStyle.
-*/
-QCommonStyle::QCommonStyle()
- : QStyle(*new QCommonStylePrivate)
-{ }
-
-/*! \internal
-*/
-QCommonStyle::QCommonStyle(QCommonStylePrivate &dd)
- : QStyle(dd)
-{ }
-
-/*!
- Destroys the style.
-*/
-QCommonStyle::~QCommonStyle()
-{ }
-
-
-/*!
- \reimp
-*/
-void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *widget) const
-{
- Q_D(const QCommonStyle);
- switch (pe) {
- case PE_FrameButtonBevel:
- case PE_FrameButtonTool:
- qDrawShadeRect(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), 1, 0);
- break;
- case PE_PanelButtonCommand:
- case PE_PanelButtonBevel:
- case PE_PanelButtonTool:
- case PE_IndicatorButtonDropDown:
- qDrawShadePanel(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), 1,
- &opt->palette.brush(QPalette::Button));
- break;
- case PE_IndicatorViewItemCheck:
- proxy()->drawPrimitive(PE_IndicatorCheckBox, opt, p, widget);
- break;
- case PE_IndicatorCheckBox:
- if (opt->state & State_NoChange) {
- p->setPen(opt->palette.foreground().color());
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Button));
- p->drawRect(opt->rect);
- p->drawLine(opt->rect.topLeft(), opt->rect.bottomRight());
- } else {
- qDrawShadePanel(p, opt->rect.x(), opt->rect.y(), opt->rect.width(), opt->rect.height(),
- opt->palette, opt->state & (State_Sunken | State_On), 1,
- &opt->palette.brush(QPalette::Button));
- }
- break;
- case PE_IndicatorRadioButton: {
- QRect ir = opt->rect;
- p->setPen(opt->palette.dark().color());
- p->drawArc(opt->rect, 0, 5760);
- if (opt->state & (State_Sunken | State_On)) {
- ir.adjust(2, 2, -2, -2);
- p->setBrush(opt->palette.foreground());
- p->drawEllipse(ir);
- }
- break; }
- case PE_FrameFocusRect:
- if (const QStyleOptionFocusRect *fropt = qstyleoption_cast<const QStyleOptionFocusRect *>(opt)) {
- QColor bg = fropt->backgroundColor;
- QPen oldPen = p->pen();
- if (bg.isValid()) {
- int h, s, v;
- bg.getHsv(&h, &s, &v);
- if (v >= 128)
- p->setPen(Qt::black);
- else
- p->setPen(Qt::white);
- } else {
- p->setPen(opt->palette.foreground().color());
- }
- QRect focusRect = opt->rect.adjusted(1, 1, -1, -1);
- p->drawRect(focusRect.adjusted(0, 0, -1, -1)); //draw pen inclusive
- p->setPen(oldPen);
- }
- break;
- case PE_IndicatorMenuCheckMark: {
- const int markW = opt->rect.width() > 7 ? 7 : opt->rect.width();
- const int markH = markW;
- int posX = opt->rect.x() + (opt->rect.width() - markW)/2 + 1;
- int posY = opt->rect.y() + (opt->rect.height() - markH)/2;
-
- QVector<QLineF> a;
- a.reserve(markH);
-
- int i, xx, yy;
- xx = posX;
- yy = 3 + posY;
- for (i = 0; i < markW/2; ++i) {
- a << QLineF(xx, yy, xx, yy + 2);
- ++xx;
- ++yy;
- }
- yy -= 2;
- for (; i < markH; ++i) {
- a << QLineF(xx, yy, xx, yy + 2);
- ++xx;
- --yy;
- }
- if (!(opt->state & State_Enabled) && !(opt->state & State_On)) {
- int pnt;
- p->setPen(opt->palette.highlightedText().color());
- QPoint offset(1, 1);
- for (pnt = 0; pnt < a.size(); ++pnt)
- a[pnt].translate(offset.x(), offset.y());
- p->drawLines(a);
- for (pnt = 0; pnt < a.size(); ++pnt)
- a[pnt].translate(offset.x(), offset.y());
- }
- p->setPen(opt->palette.text().color());
- p->drawLines(a);
- break; }
- case PE_Frame:
- case PE_FrameMenu:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (pe == PE_FrameMenu || (frame->state & State_Sunken) || (frame->state & State_Raised)) {
- qDrawShadePanel(p, frame->rect, frame->palette, frame->state & State_Sunken,
- frame->lineWidth);
- } else {
- qDrawPlainRect(p, frame->rect, frame->palette.foreground().color(), frame->lineWidth);
- }
- }
- break;
-#ifndef QT_NO_TOOLBAR
- case PE_PanelMenuBar:
- if (widget && qobject_cast<QToolBar *>(widget->parentWidget()))
- break;
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)){
- qDrawShadePanel(p, frame->rect, frame->palette, false, frame->lineWidth,
- &frame->palette.brush(QPalette::Button));
-
- }
- else if (const QStyleOptionToolBar *frame = qstyleoption_cast<const QStyleOptionToolBar *>(opt)){
- qDrawShadePanel(p, frame->rect, frame->palette, false, frame->lineWidth,
- &frame->palette.brush(QPalette::Button));
- }
-
- break;
- case PE_PanelMenu:
- break;
- case PE_PanelToolBar:
- break;
-#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_PROGRESSBAR
- case PE_IndicatorProgressChunk:
- {
- bool vertical = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt))
- vertical = (pb2->orientation == Qt::Vertical);
- if (!vertical) {
- p->fillRect(opt->rect.x(), opt->rect.y() + 3, opt->rect.width() -2, opt->rect.height() - 6,
- opt->palette.brush(QPalette::Highlight));
- } else {
- p->fillRect(opt->rect.x() + 2, opt->rect.y(), opt->rect.width() -6, opt->rect.height() - 2,
- opt->palette.brush(QPalette::Highlight));
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
-#ifdef QT3_SUPPORT
- case PE_Q3CheckListController:
-#ifndef QT_NO_IMAGEFORMAT_XPM
- p->drawPixmap(opt->rect.topLeft(), QPixmap(check_list_controller_xpm));
-#endif
- break;
- case PE_Q3CheckListExclusiveIndicator:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- if (lv->items.isEmpty())
- return;
- int x = lv->rect.x(),
- y = lv->rect.y();
-#define INTARRLEN(x) sizeof(x)/(sizeof(int)*2)
- static const int pts1[] = { // dark lines
- 1,9, 1,8, 0,7, 0,4, 1,3, 1,2, 2,1, 3,1, 4,0, 7,0, 8,1, 9,1 };
- static const int pts2[] = { // black lines
- 2,8, 1,7, 1,4, 2,3, 2,2, 3,2, 4,1, 7,1, 8,2, 9,2 };
- static const int pts3[] = { // background lines
- 2,9, 3,9, 4,10, 7,10, 8,9, 9,9, 9,8, 10,7, 10,4, 9,3 };
- static const int pts4[] = { // white lines
- 2,10, 3,10, 4,11, 7,11, 8,10, 9,10, 10,9, 10,8, 11,7,
- 11,4, 10,3, 10,2 };
- // static const int pts5[] = { // inner fill
- // 4,2, 7,2, 9,4, 9,7, 7,9, 4,9, 2,7, 2,4 };
- //QPolygon a;
-
- if (lv->state & State_Enabled)
- p->setPen(lv->palette.text().color());
- else
- p->setPen(QPen(lv->viewportPalette.color(QPalette::Disabled, QPalette::Text)));
- QPolygon a(INTARRLEN(pts1), pts1);
- a.translate(x, y);
- //p->setPen(pal.dark());
- p->drawPolyline(a);
- a.setPoints(INTARRLEN(pts2), pts2);
- a.translate(x, y);
- p->drawPolyline(a);
- a.setPoints(INTARRLEN(pts3), pts3);
- a.translate(x, y);
- // p->setPen(black);
- p->drawPolyline(a);
- a.setPoints(INTARRLEN(pts4), pts4);
- a.translate(x, y);
- // p->setPen(blue);
- p->drawPolyline(a);
- // a.setPoints(INTARRLEN(pts5), pts5);
- // a.translate(x, y);
- // QColor fillColor = isDown() ? g.background() : g.base();
- // p->setPen(fillColor);
- // p->setBrush(fillColor);
- // p->drawPolygon(a);
- if (opt->state & State_On) {
- p->setPen(Qt::NoPen);
- p->setBrush(opt->palette.text());
- p->drawRect(x + 5, y + 4, 2, 4);
- p->drawRect(x + 4, y + 5, 4, 2);
- }
-#undef INTARRLEN
- }
- break;
- case PE_Q3CheckListIndicator:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- if(lv->items.isEmpty())
- break;
- QStyleOptionQ3ListViewItem item = lv->items.at(0);
- int x = lv->rect.x(),
- y = lv->rect.y(),
- w = lv->rect.width(),
- h = lv->rect.width(),
- marg = lv->itemMargin;
-
- if (lv->state & State_Enabled)
- p->setPen(QPen(lv->palette.text().color(), 2));
- else
- p->setPen(QPen(lv->viewportPalette.color(QPalette::Disabled, QPalette::Text), 2));
- if (opt->state & State_Selected && !lv->rootIsDecorated
- && !(item.features & QStyleOptionQ3ListViewItem::ParentControl)) {
- p->fillRect(0, 0, x + marg + w + 4, item.height,
- lv->palette.brush(QPalette::Highlight));
- if (item.state & State_Enabled)
- p->setPen(QPen(lv->palette.highlightedText().color(), 2));
- }
-
- if (lv->state & State_NoChange)
- p->setBrush(lv->palette.brush(QPalette::Button));
- p->drawRect(x + marg, y + 2, w - 4, h - 4);
- /////////////////////
- ++x;
- ++y;
- if (lv->state & State_On || lv->state & State_NoChange) {
- QLineF lines[7];
- int i,
- xx = x + 1 + marg,
- yy = y + 5;
- for (i = 0; i < 3; ++i) {
- lines[i] = QLineF(xx, yy, xx, yy + 2);
- ++xx;
- ++yy;
- }
- yy -= 2;
- for (i = 3; i < 7; ++i) {
- lines[i] = QLineF(xx, yy, xx, yy + 2);
- ++xx;
- --yy;
- }
- p->drawLines(lines, 7);
- }
- }
- break;
-#endif // QT3_SUPPORT
- case PE_IndicatorBranch: {
- int mid_h = opt->rect.x() + opt->rect.width() / 2;
- int mid_v = opt->rect.y() + opt->rect.height() / 2;
- int bef_h = mid_h;
- int bef_v = mid_v;
- int aft_h = mid_h;
- int aft_v = mid_v;
-#ifndef QT_NO_IMAGEFORMAT_XPM
- static const int decoration_size = 9;
- static QPixmap open(tree_branch_open_xpm);
- static QPixmap closed(tree_branch_closed_xpm);
- if (opt->state & State_Children) {
- int delta = decoration_size / 2;
- bef_h -= delta;
- bef_v -= delta;
- aft_h += delta;
- aft_v += delta;
- p->drawPixmap(bef_h, bef_v, opt->state & State_Open ? open : closed);
- }
-#endif // QT_NO_IMAGEFORMAT_XPM
- if (opt->state & State_Item) {
- if (opt->direction == Qt::RightToLeft)
- p->drawLine(opt->rect.left(), mid_v, bef_h, mid_v);
- else
- p->drawLine(aft_h, mid_v, opt->rect.right(), mid_v);
- }
- if (opt->state & State_Sibling)
- p->drawLine(mid_h, aft_v, mid_h, opt->rect.bottom());
- if (opt->state & (State_Open | State_Children | State_Item | State_Sibling))
- p->drawLine(mid_h, opt->rect.y(), mid_h, bef_v);
- break; }
-#ifdef QT3_SUPPORT
- case PE_Q3Separator:
- qDrawShadeLine(p, opt->rect.left(), opt->rect.top(), opt->rect.right(), opt->rect.bottom(),
- opt->palette, opt->state & State_Sunken, 1, 0);
- break;
-#endif // QT3_SUPPORT
- case PE_FrameStatusBarItem:
- qDrawShadeRect(p, opt->rect, opt->palette, true, 1, 0, 0);
- break;
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QPen oldPen = p->pen();
- if (header->sortIndicator & QStyleOptionHeader::SortUp) {
- QPolygon pa(3);
- p->setPen(QPen(opt->palette.light(), 0));
- p->drawLine(opt->rect.x() + opt->rect.width(), opt->rect.y(),
- opt->rect.x() + opt->rect.width() / 2, opt->rect.y() + opt->rect.height());
- p->setPen(QPen(opt->palette.dark(), 0));
- pa.setPoint(0, opt->rect.x() + opt->rect.width() / 2, opt->rect.y() + opt->rect.height());
- pa.setPoint(1, opt->rect.x(), opt->rect.y());
- pa.setPoint(2, opt->rect.x() + opt->rect.width(), opt->rect.y());
- p->drawPolyline(pa);
- } else if (header->sortIndicator & QStyleOptionHeader::SortDown) {
- QPolygon pa(3);
- p->setPen(QPen(opt->palette.light(), 0));
- pa.setPoint(0, opt->rect.x(), opt->rect.y() + opt->rect.height());
- pa.setPoint(1, opt->rect.x() + opt->rect.width(), opt->rect.y() + opt->rect.height());
- pa.setPoint(2, opt->rect.x() + opt->rect.width() / 2, opt->rect.y());
- p->drawPolyline(pa);
- p->setPen(QPen(opt->palette.dark(), 0));
- p->drawLine(opt->rect.x(), opt->rect.y() + opt->rect.height(),
- opt->rect.x() + opt->rect.width() / 2, opt->rect.y());
- }
- p->setPen(oldPen);
- }
- break;
-#ifndef QT_NO_TABBAR
- case PE_FrameTabBarBase:
- if (const QStyleOptionTabBarBase *tbb
- = qstyleoption_cast<const QStyleOptionTabBarBase *>(opt)) {
- p->save();
- switch (tbb->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- p->setPen(QPen(tbb->palette.light(), 0));
- p->drawLine(tbb->rect.topLeft(), tbb->rect.topRight());
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- p->setPen(QPen(tbb->palette.light(), 0));
- p->drawLine(tbb->rect.topLeft(), tbb->rect.bottomLeft());
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- p->setPen(QPen(tbb->palette.shadow(), 0));
- p->drawLine(tbb->rect.left(), tbb->rect.bottom(),
- tbb->rect.right(), tbb->rect.bottom());
- p->setPen(QPen(tbb->palette.dark(), 0));
- p->drawLine(tbb->rect.left(), tbb->rect.bottom() - 1,
- tbb->rect.right() - 1, tbb->rect.bottom() - 1);
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- p->setPen(QPen(tbb->palette.dark(), 0));
- p->drawLine(tbb->rect.topRight(), tbb->rect.bottomRight());
- break;
- }
- p->restore();
- }
- break;
- case PE_IndicatorTabClose: {
- if (d->tabBarcloseButtonIcon.isNull()) {
- d->tabBarcloseButtonIcon.addPixmap(QPixmap(
- QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-closetab-16.png")),
- QIcon::Normal, QIcon::Off);
- d->tabBarcloseButtonIcon.addPixmap(QPixmap(
- QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-closetab-down-16.png")),
- QIcon::Normal, QIcon::On);
- d->tabBarcloseButtonIcon.addPixmap(QPixmap(
- QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-closetab-hover-16.png")),
- QIcon::Active, QIcon::Off);
- }
-
- int size = proxy()->pixelMetric(QStyle::PM_SmallIconSize);
- QIcon::Mode mode = opt->state & State_Enabled ?
- (opt->state & State_Raised ? QIcon::Active : QIcon::Normal)
- : QIcon::Disabled;
- if (!(opt->state & State_Raised)
- && !(opt->state & State_Sunken)
- && !(opt->state & QStyle::State_Selected))
- mode = QIcon::Disabled;
-
- QIcon::State state = opt->state & State_Sunken ? QIcon::On : QIcon::Off;
- QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(size, mode, state);
- proxy()->drawItemPixmap(p, opt->rect, Qt::AlignCenter, pixmap);
- break;
- }
-#endif // QT_NO_TABBAR
- case PE_FrameTabWidget:
- case PE_FrameWindow:
- qDrawWinPanel(p, opt->rect, opt->palette, false, 0);
- break;
- case PE_FrameLineEdit:
- proxy()->drawPrimitive(PE_Frame, opt, p, widget);
- break;
-#ifndef QT_NO_GROUPBOX
- case PE_FrameGroupBox:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- const QStyleOptionFrameV2 *frame2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(opt);
- if (frame2 && (frame2->features & QStyleOptionFrameV2::Flat)) {
- QRect fr = frame->rect;
- QPoint p1(fr.x(), fr.y() + 1);
- QPoint p2(fr.x() + fr.width(), p1.y());
- qDrawShadeLine(p, p1, p2, frame->palette, true,
- frame->lineWidth, frame->midLineWidth);
- } else {
- qDrawShadeRect(p, frame->rect.x(), frame->rect.y(), frame->rect.width(),
- frame->rect.height(), frame->palette, true,
- frame->lineWidth, frame->midLineWidth);
- }
- }
- break;
-#endif // QT_NO_GROUPBOX
-#ifndef QT_NO_DOCKWIDGET
- case PE_FrameDockWidget:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- int lw = frame->lineWidth;
- if (lw <= 0)
- lw = proxy()->pixelMetric(PM_DockWidgetFrameWidth);
-
- qDrawShadePanel(p, frame->rect, frame->palette, false, lw);
- }
- break;
-#endif // QT_NO_DOCKWIDGET
-#ifndef QT_NO_TOOLBAR
- case PE_IndicatorToolBarHandle:
- p->save();
- p->translate(opt->rect.x(), opt->rect.y());
- if (opt->state & State_Horizontal) {
- int x = opt->rect.width() / 3;
- if (opt->direction == Qt::RightToLeft)
- x -= 2;
- if (opt->rect.height() > 4) {
- qDrawShadePanel(p, x, 2, 3, opt->rect.height() - 4,
- opt->palette, false, 1, 0);
- qDrawShadePanel(p, x+3, 2, 3, opt->rect.height() - 4,
- opt->palette, false, 1, 0);
- }
- } else {
- if (opt->rect.width() > 4) {
- int y = opt->rect.height() / 3;
- qDrawShadePanel(p, 2, y, opt->rect.width() - 4, 3,
- opt->palette, false, 1, 0);
- qDrawShadePanel(p, 2, y+3, opt->rect.width() - 4, 3,
- opt->palette, false, 1, 0);
- }
- }
- p->restore();
- break;
- case PE_Q3DockWindowSeparator:
- proxy()->drawPrimitive(PE_IndicatorToolBarSeparator, opt, p, widget);
- break;
- case PE_IndicatorToolBarSeparator:
- {
- QPoint p1, p2;
- if (opt->state & State_Horizontal) {
- p1 = QPoint(opt->rect.width()/2, 0);
- p2 = QPoint(p1.x(), opt->rect.height());
- } else {
- p1 = QPoint(0, opt->rect.height()/2);
- p2 = QPoint(opt->rect.width(), p1.y());
- }
- qDrawShadeLine(p, p1, p2, opt->palette, 1, 1, 0);
- break;
- }
-#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_SPINBOX
- case PE_IndicatorSpinPlus:
- case PE_IndicatorSpinMinus: {
- QRect r = opt->rect;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- QRect br = r.adjusted(fw, fw, -fw, -fw);
-
- int offset = (opt->state & State_Sunken) ? 1 : 0;
- int step = (br.width() + 4) / 5;
- p->fillRect(br.x() + offset, br.y() + offset +br.height() / 2 - step / 2,
- br.width(), step,
- opt->palette.buttonText());
- if (pe == PE_IndicatorSpinPlus)
- p->fillRect(br.x() + br.width() / 2 - step / 2 + offset, br.y() + offset,
- step, br.height(),
- opt->palette.buttonText());
-
- break; }
- case PE_IndicatorSpinUp:
- case PE_IndicatorSpinDown: {
- QRect r = opt->rect;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- // QRect br = r.adjusted(fw, fw, -fw, -fw);
- int x = r.x(), y = r.y(), w = r.width(), h = r.height();
- int sw = w-4;
- if (sw < 3)
- break;
- else if (!(sw & 1))
- sw--;
- sw -= (sw / 7) * 2; // Empty border
- int sh = sw/2 + 2; // Must have empty row at foot of arrow
-
- int sx = x + w / 2 - sw / 2;
- int sy = y + h / 2 - sh / 2;
-
- if (pe == PE_IndicatorSpinUp && fw)
- --sy;
-
- QPolygon a;
- if (pe == PE_IndicatorSpinDown)
- a.setPoints(3, 0, 1, sw-1, 1, sh-2, sh-1);
- else
- a.setPoints(3, 0, sh-1, sw-1, sh-1, sh-2, 1);
- int bsx = 0;
- int bsy = 0;
- if (opt->state & State_Sunken) {
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
- }
- p->save();
- p->translate(sx + bsx, sy + bsy);
- p->setPen(opt->palette.buttonText().color());
- p->setBrush(opt->palette.buttonText());
- p->drawPolygon(a);
- p->restore();
- break; }
-#endif // QT_NO_SPINBOX
- case PE_PanelTipLabel: {
- QBrush oldBrush = p->brush();
- QPen oldPen = p->pen();
- p->setPen(QPen(opt->palette.toolTipText(), 0));
- p->setBrush(opt->palette.toolTipBase());
- p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
- p->setPen(oldPen);
- p->setBrush(oldBrush);
- break;
- }
-#ifndef QT_NO_TABBAR
- case PE_IndicatorTabTear:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- bool rtl = tab->direction == Qt::RightToLeft;
- QRect rect = tab->rect;
- QPainterPath path;
-
- rect.setTop(rect.top() + ((tab->state & State_Selected) ? 1 : 3));
- rect.setBottom(rect.bottom() - ((tab->state & State_Selected) ? 0 : 2));
-
- path.moveTo(QPoint(rtl ? rect.right() : rect.left(), rect.top()));
- int count = 4;
- for(int jags = 1; jags <= count; ++jags, rtl = !rtl)
- path.lineTo(QPoint(rtl ? rect.left() : rect.right(), rect.top() + jags * rect.height()/count));
-
- p->setPen(QPen(tab->palette.light(), qreal(.8)));
- p->setBrush(tab->palette.background());
- p->setRenderHint(QPainter::Antialiasing);
- p->drawPath(path);
- }
- break;
-#endif // QT_NO_TABBAR
-#ifndef QT_NO_LINEEDIT
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- p->fillRect(panel->rect.adjusted(panel->lineWidth, panel->lineWidth, -panel->lineWidth, -panel->lineWidth),
- panel->palette.brush(QPalette::Base));
-
- if (panel->lineWidth > 0)
- proxy()->drawPrimitive(PE_FrameLineEdit, panel, p, widget);
- }
- break;
-#endif // QT_NO_LINEEDIT
-#ifndef QT_NO_COLUMNVIEW
- case PE_IndicatorColumnViewArrow: {
- if (const QStyleOptionViewItem *viewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
- bool reverse = (viewOpt->direction == Qt::RightToLeft);
- p->save();
- QPainterPath path;
- int x = viewOpt->rect.x() + 1;
- int offset = (viewOpt->rect.height() / 3);
- int height = (viewOpt->rect.height()) - offset * 2;
- if (height % 2 == 1)
- --height;
- int x2 = x + height - 1;
- if (reverse) {
- x = viewOpt->rect.x() + viewOpt->rect.width() - 1;
- x2 = x - height + 1;
- }
- path.moveTo(x, viewOpt->rect.y() + offset);
- path.lineTo(x, viewOpt->rect.y() + offset + height);
- path.lineTo(x2, viewOpt->rect.y() + offset+height/2);
- path.closeSubpath();
- if (viewOpt->state & QStyle::State_Selected ) {
- if (viewOpt->showDecorationSelected) {
- QColor color = viewOpt->palette.color(QPalette::Active, QPalette::HighlightedText);
- p->setPen(color);
- p->setBrush(color);
- } else {
- QColor color = viewOpt->palette.color(QPalette::Active, QPalette::WindowText);
- p->setPen(color);
- p->setBrush(color);
- }
-
- } else {
- QColor color = viewOpt->palette.color(QPalette::Active, QPalette::Mid);
- p->setPen(color);
- p->setBrush(color);
- }
- p->drawPath(path);
-
- // draw the vertical and top triangle line
- if (!(viewOpt->state & QStyle::State_Selected)) {
- QPainterPath lines;
- lines.moveTo(x, viewOpt->rect.y() + offset);
- lines.lineTo(x, viewOpt->rect.y() + offset + height);
- lines.moveTo(x, viewOpt->rect.y() + offset);
- lines.lineTo(x2, viewOpt->rect.y() + offset+height/2);
- QColor color = viewOpt->palette.color(QPalette::Active, QPalette::Dark);
- p->setPen(color);
- p->drawPath(lines);
- }
- p->restore();
- }
- break; }
-#endif //QT_NO_COLUMNVIEW
- case PE_IndicatorItemViewItemDrop: {
- QRect rect = opt->rect;
- if (opt->rect.height() == 0)
- p->drawLine(rect.topLeft(), rect.topRight());
- else
- p->drawRect(rect);
- break; }
-#ifndef QT_NO_ITEMVIEWS
- case PE_PanelItemViewRow:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- QPalette::ColorGroup cg = (widget ? widget->isEnabled() : (vopt->state & QStyle::State_Enabled))
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- if ((vopt->state & QStyle::State_Selected) && proxy()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, opt, widget))
- p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::Highlight));
- else if (vopt->features & QStyleOptionViewItemV2::Alternate)
- p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::AlternateBase));
- }
- break;
- case PE_PanelItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- QPalette::ColorGroup cg = (widget ? widget->isEnabled() : (vopt->state & QStyle::State_Enabled))
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- if (vopt->showDecorationSelected && (vopt->state & QStyle::State_Selected)) {
- p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::Highlight));
- } else {
- if (vopt->backgroundBrush.style() != Qt::NoBrush) {
- QPointF oldBO = p->brushOrigin();
- p->setBrushOrigin(vopt->rect.topLeft());
- p->fillRect(vopt->rect, vopt->backgroundBrush);
- p->setBrushOrigin(oldBO);
- }
-
- if (vopt->state & QStyle::State_Selected) {
- QRect textRect = subElementRect(QStyle::SE_ItemViewItemText, opt, widget);
- p->fillRect(textRect, vopt->palette.brush(cg, QPalette::Highlight));
- }
- }
- }
- break;
-#endif //QT_NO_ITEMVIEWS
- case PE_PanelScrollAreaCorner: {
- const QBrush brush(opt->palette.brush(QPalette::Window));
- p->fillRect(opt->rect, brush);
- } break;
- default:
- break;
- }
-}
-
-#ifndef QT_NO_TOOLBUTTON
-static void drawArrow(const QStyle *style, const QStyleOptionToolButton *toolbutton,
- const QRect &rect, QPainter *painter, const QWidget *widget = 0)
-{
- QStyle::PrimitiveElement pe;
- switch (toolbutton->arrowType) {
- case Qt::LeftArrow:
- pe = QStyle::PE_IndicatorArrowLeft;
- break;
- case Qt::RightArrow:
- pe = QStyle::PE_IndicatorArrowRight;
- break;
- case Qt::UpArrow:
- pe = QStyle::PE_IndicatorArrowUp;
- break;
- case Qt::DownArrow:
- pe = QStyle::PE_IndicatorArrowDown;
- break;
- default:
- return;
- }
- QStyleOption arrowOpt;
- arrowOpt.rect = rect;
- arrowOpt.palette = toolbutton->palette;
- arrowOpt.state = toolbutton->state;
- style->drawPrimitive(pe, &arrowOpt, painter, widget);
-}
-#endif // QT_NO_TOOLBUTTON
-
-#ifndef QT_NO_ITEMVIEWS
-
-QSize QCommonStylePrivate::viewItemSize(const QStyleOptionViewItemV4 *option, int role) const
-{
- Q_Q(const QCommonStyle);
-
- const QWidget *widget = option->widget;
- switch (role) {
- case Qt::CheckStateRole:
- if (option->features & QStyleOptionViewItemV2::HasCheckIndicator)
- return QSize(q->pixelMetric(QStyle::PM_IndicatorWidth, option, widget),
- q->pixelMetric(QStyle::PM_IndicatorHeight, option, widget));
- break;
- case Qt::DisplayRole:
- if (option->features & QStyleOptionViewItemV2::HasDisplay) {
- QTextOption textOption;
- textOption.setWrapMode(QTextOption::WordWrap);
- QTextLayout textLayout;
- textLayout.setTextOption(textOption);
- textLayout.setFont(option->font);
- textLayout.setText(option->text);
- const bool wrapText = option->features & QStyleOptionViewItemV2::WrapText;
- const int textMargin = q->pixelMetric(QStyle::PM_FocusFrameHMargin, option, widget) + 1;
- QRect bounds = option->rect;
- switch (option->decorationPosition) {
- case QStyleOptionViewItem::Left:
- case QStyleOptionViewItem::Right:
- bounds.setWidth(wrapText && bounds.isValid() ? bounds.width() - 2 * textMargin : QFIXED_MAX);
- break;
- case QStyleOptionViewItem::Top:
- case QStyleOptionViewItem::Bottom:
- bounds.setWidth(wrapText ? option->decorationSize.width() : QFIXED_MAX);
- break;
- default:
- break;
- }
-
- qreal height = 0, widthUsed = 0;
- textLayout.beginLayout();
- while (true) {
- QTextLine line = textLayout.createLine();
- if (!line.isValid())
- break;
- line.setLineWidth(bounds.width());
- line.setPosition(QPointF(0, height));
- height += line.height();
- widthUsed = qMax(widthUsed, line.naturalTextWidth());
- }
- textLayout.endLayout();
- const QSize size(qCeil(widthUsed), qCeil(height));
- return QSize(size.width() + 2 * textMargin, size.height());
- }
- break;
- case Qt::DecorationRole:
- if (option->features & QStyleOptionViewItemV2::HasDecoration) {
- return option->decorationSize;
- }
- break;
- default:
- break;
- }
-
- return QSize(0, 0);
-}
-
-static QSizeF viewItemTextLayout(QTextLayout &textLayout, int lineWidth)
-{
- qreal height = 0;
- qreal widthUsed = 0;
- textLayout.beginLayout();
- while (true) {
- QTextLine line = textLayout.createLine();
- if (!line.isValid())
- break;
- line.setLineWidth(lineWidth);
- line.setPosition(QPointF(0, height));
- height += line.height();
- widthUsed = qMax(widthUsed, line.naturalTextWidth());
- }
- textLayout.endLayout();
- return QSizeF(widthUsed, height);
-}
-
-void QCommonStylePrivate::viewItemDrawText(QPainter *p, const QStyleOptionViewItemV4 *option, const QRect &rect) const
-{
- Q_Q(const QCommonStyle);
- const QWidget *widget = option->widget;
- const int textMargin = q->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1;
-
- QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding
- const bool wrapText = option->features & QStyleOptionViewItemV2::WrapText;
- QTextOption textOption;
- textOption.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap);
- textOption.setTextDirection(option->direction);
- textOption.setAlignment(QStyle::visualAlignment(option->direction, option->displayAlignment));
- QTextLayout textLayout;
- textLayout.setTextOption(textOption);
- textLayout.setFont(option->font);
- textLayout.setText(option->text);
-
- QSizeF textLayoutSize = viewItemTextLayout(textLayout, textRect.width());
-
- QString elidedText;
- qreal height = 0;
- qreal width = 0;
- int elidedIndex = -1;
- const int lineCount = textLayout.lineCount();
- for (int j = 0; j < lineCount; ++j) {
- const QTextLine line = textLayout.lineAt(j);
- if (j + 1 <= lineCount - 1) {
- const QTextLine nextLine = textLayout.lineAt(j + 1);
- if ((nextLine.y() + nextLine.height()) > textRect.height()) {
- int start = line.textStart();
- int length = line.textLength() + nextLine.textLength();
- const QStackTextEngine engine(textLayout.text().mid(start, length), option->font);
- elidedText = engine.elidedText(option->textElideMode, textRect.width());
- height += line.height();
- width = textRect.width();
- elidedIndex = j;
- break;
- }
- }
- if (line.naturalTextWidth() > textRect.width()) {
- int start = line.textStart();
- int length = line.textLength();
- const QStackTextEngine engine(textLayout.text().mid(start, length), option->font);
- elidedText = engine.elidedText(option->textElideMode, textRect.width());
- height += line.height();
- width = textRect.width();
- elidedIndex = j;
- break;
- }
- width = qMax<qreal>(width, line.width());
- height += line.height();
- }
-
- const QRect layoutRect = QStyle::alignedRect(option->direction, option->displayAlignment,
- QSize(int(width), int(height)), textRect);
- const QPointF position = layoutRect.topLeft();
- for (int i = 0; i < lineCount; ++i) {
- const QTextLine line = textLayout.lineAt(i);
- if (i == elidedIndex) {
- qreal x = position.x() + line.x();
- qreal y = position.y() + line.y() + line.ascent();
- p->save();
- p->setFont(option->font);
- p->drawText(QPointF(x, y), elidedText);
- p->restore();
- break;
- }
- line.draw(p, position);
- }
-}
-
-/*! \internal
- compute the position for the different component of an item (pixmap, text, checkbox)
-
- Set sizehint to false to layout the elements inside opt->rect. Set sizehint to true to ignore
- opt->rect and return rectangles in infinite space
-
- Code duplicated in QItemDelegate::doLayout
-*/
-void QCommonStylePrivate::viewItemLayout(const QStyleOptionViewItemV4 *opt, QRect *checkRect,
- QRect *pixmapRect, QRect *textRect, bool sizehint) const
-{
- Q_Q(const QCommonStyle);
- Q_ASSERT(checkRect && pixmapRect && textRect);
- *pixmapRect = QRect(QPoint(0, 0), viewItemSize(opt, Qt::DecorationRole));
- *textRect = QRect(QPoint(0, 0), viewItemSize(opt, Qt::DisplayRole));
- *checkRect = QRect(QPoint(0, 0), viewItemSize(opt, Qt::CheckStateRole));
-
- const QWidget *widget = opt->widget;
- const bool hasCheck = checkRect->isValid();
- const bool hasPixmap = pixmapRect->isValid();
- const bool hasText = textRect->isValid();
- const int textMargin = hasText ? q->pixelMetric(QStyle::PM_FocusFrameHMargin, opt, widget) + 1 : 0;
- const int pixmapMargin = hasPixmap ? q->pixelMetric(QStyle::PM_FocusFrameHMargin, opt, widget) + 1 : 0;
- const int checkMargin = hasCheck ? q->pixelMetric(QStyle::PM_FocusFrameHMargin, opt, widget) + 1 : 0;
- int x = opt->rect.left();
- int y = opt->rect.top();
- int w, h;
-
- if (textRect->height() == 0 && (!hasPixmap || !sizehint)) {
- //if there is no text, we still want to have a decent height for the item sizeHint and the editor size
- textRect->setHeight(opt->fontMetrics.height());
- }
-
- QSize pm(0, 0);
- if (hasPixmap) {
- pm = pixmapRect->size();
- pm.rwidth() += 2 * pixmapMargin;
- }
- if (sizehint) {
- h = qMax(checkRect->height(), qMax(textRect->height(), pm.height()));
- if (opt->decorationPosition == QStyleOptionViewItem::Left
- || opt->decorationPosition == QStyleOptionViewItem::Right) {
- w = textRect->width() + pm.width();
- } else {
- w = qMax(textRect->width(), pm.width());
- }
- } else {
- w = opt->rect.width();
- h = opt->rect.height();
- }
-
- int cw = 0;
- QRect check;
- if (hasCheck) {
- cw = checkRect->width() + 2 * checkMargin;
- if (sizehint) w += cw;
- if (opt->direction == Qt::RightToLeft) {
- check.setRect(x + w - cw, y, cw, h);
- } else {
- check.setRect(x, y, cw, h);
- }
- }
-
- QRect display;
- QRect decoration;
- switch (opt->decorationPosition) {
- case QStyleOptionViewItem::Top: {
- if (hasPixmap)
- pm.setHeight(pm.height() + pixmapMargin); // add space
- h = sizehint ? textRect->height() : h - pm.height();
-
- if (opt->direction == Qt::RightToLeft) {
- decoration.setRect(x, y, w - cw, pm.height());
- display.setRect(x, y + pm.height(), w - cw, h);
- } else {
- decoration.setRect(x + cw, y, w - cw, pm.height());
- display.setRect(x + cw, y + pm.height(), w - cw, h);
- }
- break; }
- case QStyleOptionViewItem::Bottom: {
- if (hasText)
- textRect->setHeight(textRect->height() + textMargin); // add space
- h = sizehint ? textRect->height() + pm.height() : h;
-
- if (opt->direction == Qt::RightToLeft) {
- display.setRect(x, y, w - cw, textRect->height());
- decoration.setRect(x, y + textRect->height(), w - cw, h - textRect->height());
- } else {
- display.setRect(x + cw, y, w - cw, textRect->height());
- decoration.setRect(x + cw, y + textRect->height(), w - cw, h - textRect->height());
- }
- break; }
- case QStyleOptionViewItem::Left: {
- if (opt->direction == Qt::LeftToRight) {
- decoration.setRect(x + cw, y, pm.width(), h);
- display.setRect(decoration.right() + 1, y, w - pm.width() - cw, h);
- } else {
- display.setRect(x, y, w - pm.width() - cw, h);
- decoration.setRect(display.right() + 1, y, pm.width(), h);
- }
- break; }
- case QStyleOptionViewItem::Right: {
- if (opt->direction == Qt::LeftToRight) {
- display.setRect(x + cw, y, w - pm.width() - cw, h);
- decoration.setRect(display.right() + 1, y, pm.width(), h);
- } else {
- decoration.setRect(x, y, pm.width(), h);
- display.setRect(decoration.right() + 1, y, w - pm.width() - cw, h);
- }
- break; }
- default:
- qWarning("doLayout: decoration position is invalid");
- decoration = *pixmapRect;
- break;
- }
-
- if (!sizehint) { // we only need to do the internal layout if we are going to paint
- *checkRect = QStyle::alignedRect(opt->direction, Qt::AlignCenter,
- checkRect->size(), check);
- *pixmapRect = QStyle::alignedRect(opt->direction, opt->decorationAlignment,
- pixmapRect->size(), decoration);
- // the text takes up all available space, unless the decoration is not shown as selected
- if (opt->showDecorationSelected)
- *textRect = display;
- else
- *textRect = QStyle::alignedRect(opt->direction, opt->displayAlignment,
- textRect->size().boundedTo(display.size()), display);
- } else {
- *checkRect = check;
- *pixmapRect = decoration;
- *textRect = display;
- }
-}
-#endif // QT_NO_ITEMVIEWS
-
-
-#ifndef QT_NO_TABBAR
-/*! \internal
- Compute the textRect and the pixmapRect from the opt rect
-
- Uses the same computation than in QTabBar::tabSizeHint
- */
-void QCommonStylePrivate::tabLayout(const QStyleOptionTabV3 *opt, const QWidget *widget, QRect *textRect, QRect *iconRect) const
-{
- Q_ASSERT(textRect);
- Q_ASSERT(iconRect);
- QRect tr = opt->rect;
- bool verticalTabs = opt->shape == QTabBar::RoundedEast
- || opt->shape == QTabBar::RoundedWest
- || opt->shape == QTabBar::TriangularEast
- || opt->shape == QTabBar::TriangularWest;
- if (verticalTabs)
- tr.setRect(0, 0, tr.height(), tr.width()); //0, 0 as we will have a translate transform
-
- int verticalShift = proxyStyle->pixelMetric(QStyle::PM_TabBarTabShiftVertical, opt, widget);
- int horizontalShift = proxyStyle->pixelMetric(QStyle::PM_TabBarTabShiftHorizontal, opt, widget);
- int hpadding = proxyStyle->pixelMetric(QStyle::PM_TabBarTabHSpace, opt, widget) / 2;
- int vpadding = proxyStyle->pixelMetric(QStyle::PM_TabBarTabVSpace, opt, widget) / 2;
- if (opt->shape == QTabBar::RoundedSouth || opt->shape == QTabBar::TriangularSouth)
- verticalShift = -verticalShift;
- tr.adjust(hpadding, verticalShift - vpadding, horizontalShift - hpadding, vpadding);
- bool selected = opt->state & QStyle::State_Selected;
- if (selected) {
- tr.setTop(tr.top() - verticalShift);
- tr.setRight(tr.right() - horizontalShift);
- }
-
- // left widget
- if (!opt->leftButtonSize.isEmpty()) {
- tr.setLeft(tr.left() + 4 +
- (verticalTabs ? opt->leftButtonSize.height() : opt->leftButtonSize.width()));
- }
- // right widget
- if (!opt->rightButtonSize.isEmpty()) {
- tr.setRight(tr.right() - 4 -
- (verticalTabs ? opt->rightButtonSize.height() : opt->rightButtonSize.width()));
- }
-
- // icon
- if (!opt->icon.isNull()) {
- QSize iconSize = opt->iconSize;
- if (!iconSize.isValid()) {
- int iconExtent = proxyStyle->pixelMetric(QStyle::PM_SmallIconSize);
- iconSize = QSize(iconExtent, iconExtent);
- }
- QSize tabIconSize = opt->icon.actualSize(iconSize,
- (opt->state & QStyle::State_Enabled) ? QIcon::Normal : QIcon::Disabled,
- (opt->state & QStyle::State_Selected) ? QIcon::On : QIcon::Off );
-
- *iconRect = QRect(tr.left(), tr.center().y() - tabIconSize.height() / 2,
- tabIconSize.width(), tabIconSize .height());
- if (!verticalTabs)
- *iconRect = proxyStyle->visualRect(opt->direction, opt->rect, *iconRect);
- tr.setLeft(tr.left() + tabIconSize.width() + 4);
- }
-
- if (!verticalTabs)
- tr = proxyStyle->visualRect(opt->direction, opt->rect, tr);
-
- *textRect = tr;
-}
-#endif //QT_NO_TABBAR
-
-
-/*!
- \reimp
-*/
-void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt,
- QPainter *p, const QWidget *widget) const
-{
- Q_D(const QCommonStyle);
- switch (element) {
-
- case CE_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- proxy()->drawControl(CE_PushButtonBevel, btn, p, widget);
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(SE_PushButtonContents, btn, widget);
- proxy()->drawControl(CE_PushButtonLabel, &subopt, p, widget);
- if (btn->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*btn);
- fropt.rect = subElementRect(SE_PushButtonFocusRect, btn, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- break;
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QRect br = btn->rect;
- int dbi = proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget);
- if (btn->features & QStyleOptionButton::DefaultButton)
- proxy()->drawPrimitive(PE_FrameDefaultButton, opt, p, widget);
- if (btn->features & QStyleOptionButton::AutoDefaultButton)
- br.setCoords(br.left() + dbi, br.top() + dbi, br.right() - dbi, br.bottom() - dbi);
- if (!(btn->features & (QStyleOptionButton::Flat | QStyleOptionButton::CommandLinkButton))
- || btn->state & (State_Sunken | State_On)
- || (btn->features & QStyleOptionButton::CommandLinkButton && btn->state & State_MouseOver)) {
- QStyleOptionButton tmpBtn = *btn;
- tmpBtn.rect = br;
- proxy()->drawPrimitive(PE_PanelButtonCommand, &tmpBtn, p, widget);
- }
- if (btn->features & QStyleOptionButton::HasMenu) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, btn, widget);
- QRect ir = btn->rect;
- QStyleOptionButton newBtn = *btn;
- newBtn.rect = QRect(ir.right() - mbi + 2, ir.height()/2 - mbi/2 + 3, mbi - 6, mbi - 6);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
- }
- }
- break;
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QRect textRect = button->rect;
- uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
- if (!proxy()->styleHint(SH_UnderlineShortcut, button, widget))
- tf |= Qt::TextHideMnemonic;
-
- if (!button->icon.isNull()) {
- //Center both icon and text
- QRect iconRect;
- QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- if (mode == QIcon::Normal && button->state & State_HasFocus)
- mode = QIcon::Active;
- QIcon::State state = QIcon::Off;
- if (button->state & State_On)
- state = QIcon::On;
-
- QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
- int labelWidth = pixmap.width();
- int labelHeight = pixmap.height();
- int iconSpacing = 4;//### 4 is currently hardcoded in QPushButton::sizeHint()
- int textWidth = button->fontMetrics.boundingRect(opt->rect, tf, button->text).width();
- if (!button->text.isEmpty())
- labelWidth += (textWidth + iconSpacing);
-
- iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
- textRect.y() + (textRect.height() - labelHeight) / 2,
- pixmap.width(), pixmap.height());
-
- iconRect = visualRect(button->direction, textRect, iconRect);
-
- tf |= Qt::AlignLeft; //left align, we adjust the text-rect instead
-
- if (button->direction == Qt::RightToLeft)
- textRect.setRight(iconRect.left() - iconSpacing);
- else
- textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);
-
- if (button->state & (State_On | State_Sunken))
- iconRect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget));
- p->drawPixmap(iconRect, pixmap);
- } else {
- tf |= Qt::AlignHCenter;
- }
- if (button->state & (State_On | State_Sunken))
- textRect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, opt, widget));
-
- if (button->features & QStyleOptionButton::HasMenu) {
- int indicatorSize = proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget);
- if (button->direction == Qt::LeftToRight)
- textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
- else
- textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
- }
- proxy()->drawItemText(p, textRect, tf, button->palette, (button->state & State_Enabled),
- button->text, QPalette::ButtonText);
- }
- break;
- case CE_RadioButton:
- case CE_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- bool isRadio = (element == CE_RadioButton);
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, btn, widget);
- proxy()->drawPrimitive(isRadio ? PE_IndicatorRadioButton : PE_IndicatorCheckBox,
- &subopt, p, widget);
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonContents
- : SE_CheckBoxContents, btn, widget);
- proxy()->drawControl(isRadio ? CE_RadioButtonLabel : CE_CheckBoxLabel, &subopt, p, widget);
- if (btn->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*btn);
- fropt.rect = subElementRect(isRadio ? SE_RadioButtonFocusRect
- : SE_CheckBoxFocusRect, btn, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- break;
- case CE_RadioButtonLabel:
- case CE_CheckBoxLabel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- uint alignment = visualAlignment(btn->direction, Qt::AlignLeft | Qt::AlignVCenter);
-
- if (!proxy()->styleHint(SH_UnderlineShortcut, btn, widget))
- alignment |= Qt::TextHideMnemonic;
- QPixmap pix;
- QRect textRect = btn->rect;
- if (!btn->icon.isNull()) {
- pix = btn->icon.pixmap(btn->iconSize, btn->state & State_Enabled ? QIcon::Normal : QIcon::Disabled);
- proxy()->drawItemPixmap(p, btn->rect, alignment, pix);
- if (btn->direction == Qt::RightToLeft)
- textRect.setRight(textRect.right() - btn->iconSize.width() - 4);
- else
- textRect.setLeft(textRect.left() + btn->iconSize.width() + 4);
- }
- if (!btn->text.isEmpty()){
- proxy()->drawItemText(p, textRect, alignment | Qt::TextShowMnemonic,
- btn->palette, btn->state & State_Enabled, btn->text, QPalette::WindowText);
- }
- }
- break;
-#ifndef QT_NO_MENU
- case CE_MenuScroller: {
- p->fillRect(opt->rect, opt->palette.background());
- QStyleOption arrowOpt = *opt;
- arrowOpt.state |= State_Enabled;
- proxy()->drawPrimitive(((opt->state & State_DownArrow) ? PE_IndicatorArrowDown : PE_IndicatorArrowUp),
- &arrowOpt, p, widget);
- break; }
- case CE_MenuTearoff:
- if (opt->state & State_Selected)
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Highlight));
- else
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Button));
- p->setPen(QPen(opt->palette.dark().color(), 1, Qt::DashLine));
- p->drawLine(opt->rect.x() + 2, opt->rect.y() + opt->rect.height() / 2 - 1,
- opt->rect.x() + opt->rect.width() - 4,
- opt->rect.y() + opt->rect.height() / 2 - 1);
- p->setPen(QPen(opt->palette.light().color(), 1, Qt::DashLine));
- p->drawLine(opt->rect.x() + 2, opt->rect.y() + opt->rect.height() / 2,
- opt->rect.x() + opt->rect.width() - 4, opt->rect.y() + opt->rect.height() / 2);
- break;
-#endif // QT_NO_MENU
-#ifndef QT_NO_MENUBAR
- case CE_MenuBarItem:
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip
- | Qt::TextSingleLine;
- if (!proxy()->styleHint(SH_UnderlineShortcut, mbi, widget))
- alignment |= Qt::TextHideMnemonic;
- QPixmap pix = mbi->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize), (mbi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
- if (!pix.isNull())
- proxy()->drawItemPixmap(p,mbi->rect, alignment, pix);
- else
- proxy()->drawItemText(p, mbi->rect, alignment, mbi->palette, mbi->state & State_Enabled,
- mbi->text, QPalette::ButtonText);
- }
- break;
- case CE_MenuBarEmptyArea:
- if (widget && !widget->testAttribute(Qt::WA_NoSystemBackground))
- p->eraseRect(opt->rect);
- break;
-#endif // QT_NO_MENUBAR
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBar:
- if (const QStyleOptionProgressBar *pb
- = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- QStyleOptionProgressBarV2 subopt = *pb;
- subopt.rect = subElementRect(SE_ProgressBarGroove, pb, widget);
- proxy()->drawControl(CE_ProgressBarGroove, &subopt, p, widget);
- subopt.rect = subElementRect(SE_ProgressBarContents, pb, widget);
- proxy()->drawControl(CE_ProgressBarContents, &subopt, p, widget);
- if (pb->textVisible) {
- subopt.rect = subElementRect(SE_ProgressBarLabel, pb, widget);
- proxy()->drawControl(CE_ProgressBarLabel, &subopt, p, widget);
- }
- }
- break;
- case CE_ProgressBarGroove:
- if (opt->rect.isValid())
- qDrawShadePanel(p, opt->rect, opt->palette, true, 1,
- &opt->palette.brush(QPalette::Window));
- break;
- case CE_ProgressBarLabel:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- bool vertical = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- vertical = (pb2->orientation == Qt::Vertical);
- }
- if (!vertical) {
- QPalette::ColorRole textRole = QPalette::NoRole;
- if ((pb->textAlignment & Qt::AlignCenter) && pb->textVisible
- && ((qint64(pb->progress) - qint64(pb->minimum)) * 2 >= (qint64(pb->maximum) - qint64(pb->minimum)))) {
- textRole = QPalette::HighlightedText;
- //Draw text shadow, This will increase readability when the background of same color
- QRect shadowRect(pb->rect);
- shadowRect.translate(1,1);
- QColor shadowColor = (pb->palette.color(textRole).value() <= 128)
- ? QColor(255,255,255,160) : QColor(0,0,0,160);
- QPalette shadowPalette = pb->palette;
- shadowPalette.setColor(textRole, shadowColor);
- proxy()->drawItemText(p, shadowRect, Qt::AlignCenter | Qt::TextSingleLine, shadowPalette,
- pb->state & State_Enabled, pb->text, textRole);
- }
- proxy()->drawItemText(p, pb->rect, Qt::AlignCenter | Qt::TextSingleLine, pb->palette,
- pb->state & State_Enabled, pb->text, textRole);
- }
- }
- break;
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
-
- QRect rect = pb->rect;
- bool vertical = false;
- bool inverted = false;
- qint64 minimum = qint64(pb->minimum);
- qint64 maximum = qint64(pb->maximum);
- qint64 progress = qint64(pb->progress);
-
- // Get extra style options if version 2
- const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt);
- if (pb2) {
- vertical = (pb2->orientation == Qt::Vertical);
- inverted = pb2->invertedAppearance;
- }
- QMatrix m;
-
- if (vertical) {
- rect = QRect(rect.y(), rect.x(), rect.height(), rect.width()); // flip width and height
- m.rotate(90);
- m.translate(0, -(rect.height() + rect.y()*2));
- }
-
- QPalette pal2 = pb->palette;
- // Correct the highlight color if it is the same as the background
- if (pal2.highlight() == pal2.background())
- pal2.setColor(QPalette::Highlight, pb->palette.color(QPalette::Active,
- QPalette::Highlight));
- bool reverse = ((!vertical && (pb->direction == Qt::RightToLeft)) || vertical);
- if (inverted)
- reverse = !reverse;
- int w = rect.width();
- if (pb->minimum == 0 && pb->maximum == 0) {
- // draw busy indicator
- int x = (progress - minimum) % (w * 2);
- if (x > w)
- x = 2 * w - x;
- x = reverse ? rect.right() - x : x + rect.x();
- p->setPen(QPen(pal2.highlight().color(), 4));
- p->drawLine(x, rect.y(), x, rect.height());
- } else {
- const int unit_width = proxy()->pixelMetric(PM_ProgressBarChunkWidth, pb, widget);
- if (!unit_width)
- return;
-
- int u;
- if (unit_width > 1)
- u = ((rect.width() + unit_width) / unit_width);
- else
- u = w / unit_width;
- qint64 p_v = progress - minimum;
- qint64 t_s = (maximum - minimum) ? (maximum - minimum) : qint64(1);
-
- if (u > 0 && p_v >= INT_MAX / u && t_s >= u) {
- // scale down to something usable.
- p_v /= u;
- t_s /= u;
- }
-
- // nu < tnu, if last chunk is only a partial chunk
- int tnu, nu;
- tnu = nu = p_v * u / t_s;
-
- if (nu * unit_width > w)
- --nu;
-
- // Draw nu units out of a possible u of unit_width
- // width, each a rectangle bordered by background
- // color, all in a sunken panel with a percentage text
- // display at the end.
- int x = 0;
- int x0 = reverse ? rect.right() - ((unit_width > 1) ? unit_width : 0)
- : rect.x();
-
- QStyleOptionProgressBarV2 pbBits = *pb;
- pbBits.rect = rect;
- pbBits.palette = pal2;
- int myY = pbBits.rect.y();
- int myHeight = pbBits.rect.height();
- pbBits.state = State_None;
- for (int i = 0; i < nu; ++i) {
- pbBits.rect.setRect(x0 + x, myY, unit_width, myHeight);
- pbBits.rect = m.mapRect(QRectF(pbBits.rect)).toRect();
- proxy()->drawPrimitive(PE_IndicatorProgressChunk, &pbBits, p, widget);
- x += reverse ? -unit_width : unit_width;
- }
-
- // Draw the last partial chunk to fill up the
- // progress bar entirely
- if (nu < tnu) {
- int pixels_left = w - (nu * unit_width);
- int offset = reverse ? x0 + x + unit_width-pixels_left : x0 + x;
- pbBits.rect.setRect(offset, myY, pixels_left, myHeight);
- pbBits.rect = m.mapRect(QRectF(pbBits.rect)).toRect();
- proxy()->drawPrimitive(PE_IndicatorProgressChunk, &pbBits, p, widget);
- }
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
- case CE_HeaderLabel:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QRect rect = header->rect;
- if (!header->icon.isNull()) {
- QPixmap pixmap
- = header->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize), (header->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
- int pixw = pixmap.width();
-
- QRect aligned = alignedRect(header->direction, QFlag(header->iconAlignment), pixmap.size(), rect);
- QRect inter = aligned.intersected(rect);
- p->drawPixmap(inter.x(), inter.y(), pixmap, inter.x() - aligned.x(), inter.y() - aligned.y(), inter.width(), inter.height());
-
- if (header->direction == Qt::LeftToRight)
- rect.setLeft(rect.left() + pixw + 2);
- else
- rect.setRight(rect.right() - pixw - 2);
- }
- if (header->state & QStyle::State_On) {
- QFont fnt = p->font();
- fnt.setBold(true);
- p->setFont(fnt);
- }
- proxy()->drawItemText(p, rect, header->textAlignment, header->palette,
- (header->state & State_Enabled), header->text, QPalette::ButtonText);
- }
- break;
-#ifndef QT_NO_TOOLBUTTON
- case CE_ToolButtonLabel:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- QRect rect = toolbutton->rect;
- int shiftX = 0;
- int shiftY = 0;
- if (toolbutton->state & (State_Sunken | State_On)) {
- shiftX = proxy()->pixelMetric(PM_ButtonShiftHorizontal, toolbutton, widget);
- shiftY = proxy()->pixelMetric(PM_ButtonShiftVertical, toolbutton, widget);
- }
- // Arrow type always overrules and is always shown
- bool hasArrow = toolbutton->features & QStyleOptionToolButton::Arrow;
- if (((!hasArrow && toolbutton->icon.isNull()) && !toolbutton->text.isEmpty())
- || toolbutton->toolButtonStyle == Qt::ToolButtonTextOnly) {
- int alignment = Qt::AlignCenter | Qt::TextShowMnemonic;
- if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget))
- alignment |= Qt::TextHideMnemonic;
- rect.translate(shiftX, shiftY);
- p->setFont(toolbutton->font);
- proxy()->drawItemText(p, rect, alignment, toolbutton->palette,
- opt->state & State_Enabled, toolbutton->text,
- QPalette::ButtonText);
- } else {
- QPixmap pm;
- QSize pmSize = toolbutton->iconSize;
- if (!toolbutton->icon.isNull()) {
- QIcon::State state = toolbutton->state & State_On ? QIcon::On : QIcon::Off;
- QIcon::Mode mode;
- if (!(toolbutton->state & State_Enabled))
- mode = QIcon::Disabled;
- else if ((opt->state & State_MouseOver) && (opt->state & State_AutoRaise))
- mode = QIcon::Active;
- else
- mode = QIcon::Normal;
- pm = toolbutton->icon.pixmap(toolbutton->rect.size().boundedTo(toolbutton->iconSize),
- mode, state);
- pmSize = pm.size();
- }
-
- if (toolbutton->toolButtonStyle != Qt::ToolButtonIconOnly) {
- p->setFont(toolbutton->font);
- QRect pr = rect,
- tr = rect;
- int alignment = Qt::TextShowMnemonic;
- if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget))
- alignment |= Qt::TextHideMnemonic;
-
- if (toolbutton->toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
- pr.setHeight(pmSize.height() + 6);
- tr.adjust(0, pr.height() - 1, 0, -2);
- pr.translate(shiftX, shiftY);
- if (!hasArrow) {
- proxy()->drawItemPixmap(p, pr, Qt::AlignCenter, pm);
- } else {
- drawArrow(this, toolbutton, pr, p, widget);
- }
- alignment |= Qt::AlignCenter;
- } else {
- pr.setWidth(pmSize.width() + 8);
- tr.adjust(pr.width(), 0, 0, 0);
- pr.translate(shiftX, shiftY);
- if (!hasArrow) {
- proxy()->drawItemPixmap(p, QStyle::visualRect(opt->direction, rect, pr), Qt::AlignCenter, pm);
- } else {
- drawArrow(this, toolbutton, pr, p, widget);
- }
- alignment |= Qt::AlignLeft | Qt::AlignVCenter;
- }
- tr.translate(shiftX, shiftY);
- proxy()->drawItemText(p, QStyle::visualRect(opt->direction, rect, tr), alignment, toolbutton->palette,
- toolbutton->state & State_Enabled, toolbutton->text,
- QPalette::ButtonText);
- } else {
- rect.translate(shiftX, shiftY);
- if (hasArrow) {
- drawArrow(this, toolbutton, rect, p, widget);
- } else {
- proxy()->drawItemPixmap(p, rect, Qt::AlignCenter, pm);
- }
- }
- }
- }
- break;
-#endif // QT_NO_TOOLBUTTON
-#ifndef QT_NO_TOOLBOX
- case CE_ToolBoxTab:
- if (const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
- proxy()->drawControl(CE_ToolBoxTabShape, tb, p, widget);
- proxy()->drawControl(CE_ToolBoxTabLabel, tb, p, widget);
- }
- break;
- case CE_ToolBoxTabShape:
- if (const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
- int d = 20 + tb->rect.height() - 3;
- QPolygon a(7);
- if (tb->direction != Qt::RightToLeft) {
- a.setPoint(0, -1, tb->rect.height() + 1);
- a.setPoint(1, -1, 1);
- a.setPoint(2, tb->rect.width() - d, 1);
- a.setPoint(3, tb->rect.width() - 20, tb->rect.height() - 2);
- a.setPoint(4, tb->rect.width() - 1, tb->rect.height() - 2);
- a.setPoint(5, tb->rect.width() - 1, tb->rect.height() + 1);
- a.setPoint(6, -1, tb->rect.height() + 1);
- } else {
- a.setPoint(0, tb->rect.width(), tb->rect.height() + 1);
- a.setPoint(1, tb->rect.width(), 1);
- a.setPoint(2, d - 1, 1);
- a.setPoint(3, 20 - 1, tb->rect.height() - 2);
- a.setPoint(4, 0, tb->rect.height() - 2);
- a.setPoint(5, 0, tb->rect.height() + 1);
- a.setPoint(6, tb->rect.width(), tb->rect.height() + 1);
- }
-
- p->setPen(tb->palette.mid().color().darker(150));
- p->drawPolygon(a);
- p->setPen(tb->palette.light().color());
- if (tb->direction != Qt::RightToLeft) {
- p->drawLine(0, 2, tb->rect.width() - d, 2);
- p->drawLine(tb->rect.width() - d - 1, 2, tb->rect.width() - 21, tb->rect.height() - 1);
- p->drawLine(tb->rect.width() - 20, tb->rect.height() - 1,
- tb->rect.width(), tb->rect.height() - 1);
- } else {
- p->drawLine(tb->rect.width() - 1, 2, d - 1, 2);
- p->drawLine(d, 2, 20, tb->rect.height() - 1);
- p->drawLine(19, tb->rect.height() - 1,
- -1, tb->rect.height() - 1);
- }
- p->setBrush(Qt::NoBrush);
- }
- break;
-#endif // QT_NO_TOOLBOX
-#ifndef QT_NO_TABBAR
- case CE_TabBarTab:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- proxy()->drawControl(CE_TabBarTabShape, tab, p, widget);
- proxy()->drawControl(CE_TabBarTabLabel, tab, p, widget);
- }
- break;
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- p->save();
-
- QRect rect(tab->rect);
- bool selected = tab->state & State_Selected;
- bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
- int tabOverlap = onlyOne ? 0 : proxy()->pixelMetric(PM_TabBarTabOverlap, opt, widget);
-
- if (!selected) {
- switch (tab->shape) {
- case QTabBar::TriangularNorth:
- rect.adjust(0, 0, 0, -tabOverlap);
- if(!selected)
- rect.adjust(1, 1, -1, 0);
- break;
- case QTabBar::TriangularSouth:
- rect.adjust(0, tabOverlap, 0, 0);
- if(!selected)
- rect.adjust(1, 0, -1, -1);
- break;
- case QTabBar::TriangularEast:
- rect.adjust(tabOverlap, 0, 0, 0);
- if(!selected)
- rect.adjust(0, 1, -1, -1);
- break;
- case QTabBar::TriangularWest:
- rect.adjust(0, 0, -tabOverlap, 0);
- if(!selected)
- rect.adjust(1, 1, 0, -1);
- break;
- default:
- break;
- }
- }
-
- p->setPen(QPen(tab->palette.foreground(), 0));
- if (selected) {
- p->setBrush(tab->palette.base());
- } else {
- if (widget && widget->parentWidget())
- p->setBrush(widget->parentWidget()->palette().background());
- else
- p->setBrush(tab->palette.background());
- }
-
- int y;
- int x;
- QPolygon a(10);
- switch (tab->shape) {
- case QTabBar::TriangularNorth:
- case QTabBar::TriangularSouth: {
- a.setPoint(0, 0, -1);
- a.setPoint(1, 0, 0);
- y = rect.height() - 2;
- x = y / 3;
- a.setPoint(2, x++, y - 1);
- ++x;
- a.setPoint(3, x++, y++);
- a.setPoint(4, x, y);
-
- int i;
- int right = rect.width() - 1;
- for (i = 0; i < 5; ++i)
- a.setPoint(9 - i, right - a.point(i).x(), a.point(i).y());
- if (tab->shape == QTabBar::TriangularNorth)
- for (i = 0; i < 10; ++i)
- a.setPoint(i, a.point(i).x(), rect.height() - 1 - a.point(i).y());
-
- a.translate(rect.left(), rect.top());
- p->setRenderHint(QPainter::Antialiasing);
- p->translate(0, 0.5);
-
- QPainterPath path;
- path.addPolygon(a);
- p->drawPath(path);
- break; }
- case QTabBar::TriangularEast:
- case QTabBar::TriangularWest: {
- a.setPoint(0, -1, 0);
- a.setPoint(1, 0, 0);
- x = rect.width() - 2;
- y = x / 3;
- a.setPoint(2, x - 1, y++);
- ++y;
- a.setPoint(3, x++, y++);
- a.setPoint(4, x, y);
- int i;
- int bottom = rect.height() - 1;
- for (i = 0; i < 5; ++i)
- a.setPoint(9 - i, a.point(i).x(), bottom - a.point(i).y());
- if (tab->shape == QTabBar::TriangularWest)
- for (i = 0; i < 10; ++i)
- a.setPoint(i, rect.width() - 1 - a.point(i).x(), a.point(i).y());
- a.translate(rect.left(), rect.top());
- p->setRenderHint(QPainter::Antialiasing);
- p->translate(0.5, 0);
- QPainterPath path;
- path.addPolygon(a);
- p->drawPath(path);
- break; }
- default:
- break;
- }
- p->restore();
- }
- break;
- case CE_ToolBoxTabLabel:
- if (const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
- bool enabled = tb->state & State_Enabled;
- bool selected = tb->state & State_Selected;
- QPixmap pm = tb->icon.pixmap(proxy()->pixelMetric(QStyle::PM_SmallIconSize, tb, widget),
- enabled ? QIcon::Normal : QIcon::Disabled);
-
- QRect cr = subElementRect(QStyle::SE_ToolBoxTabContents, tb, widget);
- QRect tr, ir;
- int ih = 0;
- if (pm.isNull()) {
- tr = cr;
- tr.adjust(4, 0, -8, 0);
- } else {
- int iw = pm.width() + 4;
- ih = pm.height();
- ir = QRect(cr.left() + 4, cr.top(), iw + 2, ih);
- tr = QRect(ir.right(), cr.top(), cr.width() - ir.right() - 4, cr.height());
- }
-
- if (selected && proxy()->styleHint(QStyle::SH_ToolBox_SelectedPageTitleBold, tb, widget)) {
- QFont f(p->font());
- f.setBold(true);
- p->setFont(f);
- }
-
- QString txt = tb->fontMetrics.elidedText(tb->text, Qt::ElideRight, tr.width());
-
- if (ih)
- p->drawPixmap(ir.left(), (tb->rect.height() - ih) / 2, pm);
-
- int alignment = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic;
- if (!proxy()->styleHint(QStyle::SH_UnderlineShortcut, tb, widget))
- alignment |= Qt::TextHideMnemonic;
- proxy()->drawItemText(p, tr, alignment, tb->palette, enabled, txt, QPalette::ButtonText);
-
- if (!txt.isEmpty() && opt->state & State_HasFocus) {
- QStyleOptionFocusRect opt;
- opt.rect = tr;
- opt.palette = tb->palette;
- opt.state = QStyle::State_None;
- proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, p, widget);
- }
- }
- break;
- case CE_TabBarTabLabel:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- QStyleOptionTabV3 tabV2(*tab);
- QRect tr = tabV2.rect;
- bool verticalTabs = tabV2.shape == QTabBar::RoundedEast
- || tabV2.shape == QTabBar::RoundedWest
- || tabV2.shape == QTabBar::TriangularEast
- || tabV2.shape == QTabBar::TriangularWest;
-
- int alignment = Qt::AlignCenter | Qt::TextShowMnemonic;
- if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget))
- alignment |= Qt::TextHideMnemonic;
-
- if (verticalTabs) {
- p->save();
- int newX, newY, newRot;
- if (tabV2.shape == QTabBar::RoundedEast || tabV2.shape == QTabBar::TriangularEast) {
- newX = tr.width() + tr.x();
- newY = tr.y();
- newRot = 90;
- } else {
- newX = tr.x();
- newY = tr.y() + tr.height();
- newRot = -90;
- }
- QTransform m = QTransform::fromTranslate(newX, newY);
- m.rotate(newRot);
- p->setTransform(m, true);
- }
- QRect iconRect;
- d->tabLayout(&tabV2, widget, &tr, &iconRect);
- tr = proxy()->subElementRect(SE_TabBarTabText, opt, widget); //we compute tr twice because the style may override subElementRect
-
- if (!tabV2.icon.isNull()) {
- QPixmap tabIcon = tabV2.icon.pixmap(tabV2.iconSize,
- (tabV2.state & State_Enabled) ? QIcon::Normal
- : QIcon::Disabled,
- (tabV2.state & State_Selected) ? QIcon::On
- : QIcon::Off);
- p->drawPixmap(iconRect.x(), iconRect.y(), tabIcon);
- }
-
- proxy()->drawItemText(p, tr, alignment, tab->palette, tab->state & State_Enabled, tab->text, QPalette::WindowText);
- if (verticalTabs)
- p->restore();
-
- if (tabV2.state & State_HasFocus) {
- const int OFFSET = 1 + pixelMetric(PM_DefaultFrameWidth);
-
- int x1, x2;
- x1 = tabV2.rect.left();
- x2 = tabV2.rect.right() - 1;
-
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*tab);
- fropt.rect.setRect(x1 + 1 + OFFSET, tabV2.rect.y() + OFFSET,
- x2 - x1 - 2*OFFSET, tabV2.rect.height() - 2*OFFSET);
- drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- break;
-#endif // QT_NO_TABBAR
-#ifndef QT_NO_SIZEGRIP
- case CE_SizeGrip: {
- p->save();
- int x, y, w, h;
- opt->rect.getRect(&x, &y, &w, &h);
-
- int sw = qMin(h, w);
- if (h > w)
- p->translate(0, h - w);
- else
- p->translate(w - h, 0);
-
- int sx = x;
- int sy = y;
- int s = sw / 3;
-
- Qt::Corner corner;
- if (const QStyleOptionSizeGrip *sgOpt = qstyleoption_cast<const QStyleOptionSizeGrip *>(opt))
- corner = sgOpt->corner;
- else if (opt->direction == Qt::RightToLeft)
- corner = Qt::BottomLeftCorner;
- else
- corner = Qt::BottomRightCorner;
-
- if (corner == Qt::BottomLeftCorner) {
- sx = x + sw;
- for (int i = 0; i < 4; ++i) {
- p->setPen(QPen(opt->palette.light().color(), 1));
- p->drawLine(x, sy - 1 , sx + 1, sw);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(x, sy, sx, sw);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(x, sy + 1, sx - 1, sw);
- sx -= s;
- sy += s;
- }
- } else if (corner == Qt::BottomRightCorner) {
- for (int i = 0; i < 4; ++i) {
- p->setPen(QPen(opt->palette.light().color(), 1));
- p->drawLine(sx - 1, sw, sw, sy - 1);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(sx, sw, sw, sy);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(sx + 1, sw, sw, sy + 1);
- sx += s;
- sy += s;
- }
- } else if (corner == Qt::TopRightCorner) {
- sy = y + sw;
- for (int i = 0; i < 4; ++i) {
- p->setPen(QPen(opt->palette.light().color(), 1));
- p->drawLine(sx - 1, y, sw, sy + 1);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(sx, y, sw, sy);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(sx + 1, y, sw, sy - 1);
- sx += s;
- sy -= s;
- }
- } else if (corner == Qt::TopLeftCorner) {
- for (int i = 0; i < 4; ++i) {
- p->setPen(QPen(opt->palette.light().color(), 1));
- p->drawLine(x, sy - 1, sx - 1, y);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(x, sy, sx, y);
- p->setPen(QPen(opt->palette.dark().color(), 1));
- p->drawLine(x, sy + 1, sx + 1, y);
- sx += s;
- sy += s;
- }
- }
- p->restore();
- break; }
-#endif // QT_NO_SIZEGRIP
-#ifndef QT_NO_RUBBERBAND
- case CE_RubberBand: {
- if (const QStyleOptionRubberBand *rbOpt = qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
- QPixmap tiledPixmap(16, 16);
- QPainter pixmapPainter(&tiledPixmap);
- pixmapPainter.setPen(Qt::NoPen);
- pixmapPainter.setBrush(Qt::Dense4Pattern);
- pixmapPainter.setBackground(QBrush(opt->palette.base()));
- pixmapPainter.setBackgroundMode(Qt::OpaqueMode);
- pixmapPainter.drawRect(0, 0, tiledPixmap.width(), tiledPixmap.height());
- pixmapPainter.end();
- // ### workaround for borked XRENDER
- tiledPixmap = QPixmap::fromImage(tiledPixmap.toImage());
-
- p->save();
- QRect r = opt->rect;
- QStyleHintReturnMask mask;
- if (proxy()->styleHint(QStyle::SH_RubberBand_Mask, opt, widget, &mask))
- p->setClipRegion(mask.region);
- p->drawTiledPixmap(r.x(), r.y(), r.width(), r.height(), tiledPixmap);
- p->setPen(opt->palette.color(QPalette::Active, QPalette::WindowText));
- p->setBrush(Qt::NoBrush);
- p->drawRect(r.adjusted(0, 0, -1, -1));
- if (rbOpt->shape == QRubberBand::Rectangle)
- p->drawRect(r.adjusted(3, 3, -4, -4));
- p->restore();
- }
- break; }
-#endif // QT_NO_RUBBERBAND
-#ifndef QT_NO_DOCKWIDGET
- case CE_DockWidgetTitle:
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
- QRect r = dwOpt->rect.adjusted(0, 0, -1, -1);
- if (dwOpt->movable) {
- p->setPen(dwOpt->palette.color(QPalette::Dark));
- p->drawRect(r);
- }
-
- if (!dwOpt->title.isEmpty()) {
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- if (verticalTitleBar) {
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- p->save();
- p->translate(r.left(), r.top() + r.width());
- p->rotate(-90);
- p->translate(-r.left(), -r.top());
- }
-
- const int indent = p->fontMetrics().descent();
- proxy()->drawItemText(p, r.adjusted(indent + 1, 1, -indent - 1, -1),
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, dwOpt->palette,
- dwOpt->state & State_Enabled, dwOpt->title,
- QPalette::WindowText);
-
- if (verticalTitleBar)
- p->restore();
- }
- }
- break;
-#endif // QT_NO_DOCKWIDGET
- case CE_Header:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QRegion clipRegion = p->clipRegion();
- p->setClipRect(opt->rect);
- proxy()->drawControl(CE_HeaderSection, header, p, widget);
- QStyleOptionHeader subopt = *header;
- subopt.rect = subElementRect(SE_HeaderLabel, header, widget);
- if (subopt.rect.isValid())
- proxy()->drawControl(CE_HeaderLabel, &subopt, p, widget);
- if (header->sortIndicator != QStyleOptionHeader::None) {
- subopt.rect = subElementRect(SE_HeaderArrow, opt, widget);
- proxy()->drawPrimitive(PE_IndicatorHeaderArrow, &subopt, p, widget);
- }
- p->setClipRegion(clipRegion);
- }
- break;
- case CE_FocusFrame:
- p->fillRect(opt->rect, opt->palette.foreground());
- break;
- case CE_HeaderSection:
- qDrawShadePanel(p, opt->rect, opt->palette,
- opt->state & State_Sunken, 1,
- &opt->palette.brush(QPalette::Button));
- break;
- case CE_HeaderEmptyArea:
- p->fillRect(opt->rect, opt->palette.background());
- break;
-#ifndef QT_NO_COMBOBOX
- case CE_ComboBoxLabel:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QRect editRect = proxy()->subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget);
- p->save();
- p->setClipRect(editRect);
- if (!cb->currentIcon.isNull()) {
- QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
- QRect iconRect(editRect);
- iconRect.setWidth(cb->iconSize.width() + 4);
- iconRect = alignedRect(cb->direction,
- Qt::AlignLeft | Qt::AlignVCenter,
- iconRect.size(), editRect);
- if (cb->editable)
- p->fillRect(iconRect, opt->palette.brush(QPalette::Base));
- proxy()->drawItemPixmap(p, iconRect, Qt::AlignCenter, pixmap);
-
- if (cb->direction == Qt::RightToLeft)
- editRect.translate(-4 - cb->iconSize.width(), 0);
- else
- editRect.translate(cb->iconSize.width() + 4, 0);
- }
- if (!cb->currentText.isEmpty() && !cb->editable) {
- proxy()->drawItemText(p, editRect.adjusted(1, 0, -1, 0),
- visualAlignment(cb->direction, Qt::AlignLeft | Qt::AlignVCenter),
- cb->palette, cb->state & State_Enabled, cb->currentText);
- }
- p->restore();
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_TOOLBAR
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
- // Compatibility with styles that use PE_PanelToolBar
- QStyleOptionFrame frame;
- frame.QStyleOption::operator=(*toolBar);
- frame.lineWidth = toolBar->lineWidth;
- frame.midLineWidth = toolBar->midLineWidth;
- proxy()->drawPrimitive(PE_PanelToolBar, opt, p, widget);
-
- if (widget && qobject_cast<QToolBar *>(widget->parentWidget()))
- break;
- qDrawShadePanel(p, toolBar->rect, toolBar->palette, false, toolBar->lineWidth,
- &toolBar->palette.brush(QPalette::Button));
- }
- break;
-#endif // QT_NO_TOOLBAR
- case CE_ColumnViewGrip: {
- // draw background gradients
- QLinearGradient g(0, 0, opt->rect.width(), 0);
- g.setColorAt(0, opt->palette.color(QPalette::Active, QPalette::Mid));
- g.setColorAt(0.5, Qt::white);
- p->fillRect(QRect(0, 0, opt->rect.width(), opt->rect.height()), g);
-
- // draw the two lines
- QPen pen(p->pen());
- pen.setWidth(opt->rect.width()/20);
- pen.setColor(opt->palette.color(QPalette::Active, QPalette::Dark));
- p->setPen(pen);
-
- int line1starting = opt->rect.width()*8 / 20;
- int line2starting = opt->rect.width()*13 / 20;
- int top = opt->rect.height()*20/75;
- int bottom = opt->rect.height() - 1 - top;
- p->drawLine(line1starting, top, line1starting, bottom);
- p->drawLine(line2starting, top, line2starting, bottom);
- }
- break;
-
-#ifndef QT_NO_ITEMVIEWS
- case CE_ItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- p->save();
- p->setClipRect(opt->rect);
-
- QRect checkRect = subElementRect(SE_ItemViewItemCheckIndicator, vopt, widget);
- QRect iconRect = subElementRect(SE_ItemViewItemDecoration, vopt, widget);
- QRect textRect = subElementRect(SE_ItemViewItemText, vopt, widget);
-
- // draw the background
- proxy()->drawPrimitive(PE_PanelItemViewItem, opt, p, widget);
-
- // draw the check mark
- if (vopt->features & QStyleOptionViewItemV2::HasCheckIndicator) {
- QStyleOptionViewItemV4 option(*vopt);
- option.rect = checkRect;
- option.state = option.state & ~QStyle::State_HasFocus;
-
- switch (vopt->checkState) {
- case Qt::Unchecked:
- option.state |= QStyle::State_Off;
- break;
- case Qt::PartiallyChecked:
- option.state |= QStyle::State_NoChange;
- break;
- case Qt::Checked:
- option.state |= QStyle::State_On;
- break;
- }
- proxy()->drawPrimitive(QStyle::PE_IndicatorViewItemCheck, &option, p, widget);
- }
-
- // draw the icon
- QIcon::Mode mode = QIcon::Normal;
- if (!(vopt->state & QStyle::State_Enabled))
- mode = QIcon::Disabled;
- else if (vopt->state & QStyle::State_Selected)
- mode = QIcon::Selected;
- QIcon::State state = vopt->state & QStyle::State_Open ? QIcon::On : QIcon::Off;
- vopt->icon.paint(p, iconRect, vopt->decorationAlignment, mode, state);
-
- // draw the text
- if (!vopt->text.isEmpty()) {
- QPalette::ColorGroup cg = vopt->state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- if (vopt->state & QStyle::State_Selected) {
- p->setPen(vopt->palette.color(cg, QPalette::HighlightedText));
- } else {
- p->setPen(vopt->palette.color(cg, QPalette::Text));
- }
- if (vopt->state & QStyle::State_Editing) {
- p->setPen(vopt->palette.color(cg, QPalette::Text));
- p->drawRect(textRect.adjusted(0, 0, -1, -1));
- }
-
- d->viewItemDrawText(p, vopt, textRect);
- }
-
- // draw the focus rect
- if (vopt->state & QStyle::State_HasFocus) {
- QStyleOptionFocusRect o;
- o.QStyleOption::operator=(*vopt);
- o.rect = proxy()->subElementRect(SE_ItemViewItemFocusRect, vopt, widget);
- o.state |= QStyle::State_KeyboardFocusChange;
- o.state |= QStyle::State_Item;
- QPalette::ColorGroup cg = (vopt->state & QStyle::State_Enabled)
- ? QPalette::Normal : QPalette::Disabled;
- o.backgroundColor = vopt->palette.color(cg, (vopt->state & QStyle::State_Selected)
- ? QPalette::Highlight : QPalette::Window);
- proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, p, widget);
- }
-
- p->restore();
- }
- break;
-
-#endif // QT_NO_ITEMVIEWS
-#ifndef QT_NO_FRAME
- case CE_ShapedFrame:
- if (const QStyleOptionFrameV3 *f = qstyleoption_cast<const QStyleOptionFrameV3 *>(opt)) {
- int frameShape = f->frameShape;
- int frameShadow = QFrame::Plain;
- if (f->state & QStyle::State_Sunken) {
- frameShadow = QFrame::Sunken;
- } else if (f->state & QStyle::State_Raised) {
- frameShadow = QFrame::Raised;
- }
-
- int lw = f->lineWidth;
- int mlw = f->midLineWidth;
- QPalette::ColorRole foregroundRole = QPalette::WindowText;
- if (widget)
- foregroundRole = widget->foregroundRole();
-
- switch (frameShape) {
- case QFrame::Box:
- if (frameShadow == QFrame::Plain) {
- qDrawPlainRect(p, f->rect, f->palette.color(foregroundRole), lw);
- } else {
- qDrawShadeRect(p, f->rect, f->palette, frameShadow == QFrame::Sunken, lw, mlw);
- }
- break;
- case QFrame::StyledPanel:
- //keep the compatibility with Qt 4.4 if there is a proxy style.
- //be sure to call drawPrimitive(QStyle::PE_Frame) on the proxy style
- if (widget) {
- widget->style()->drawPrimitive(QStyle::PE_Frame, opt, p, widget);
- } else {
- proxy()->drawPrimitive(QStyle::PE_Frame, opt, p, widget);
- }
- break;
- case QFrame::Panel:
- if (frameShadow == QFrame::Plain) {
- qDrawPlainRect(p, f->rect, f->palette.color(foregroundRole), lw);
- } else {
- qDrawShadePanel(p, f->rect, f->palette, frameShadow == QFrame::Sunken, lw);
- }
- break;
- case QFrame::WinPanel:
- if (frameShadow == QFrame::Plain) {
- qDrawPlainRect(p, f->rect, f->palette.color(foregroundRole), lw);
- } else {
- qDrawWinPanel(p, f->rect, f->palette, frameShadow == QFrame::Sunken);
- }
- break;
- case QFrame::HLine:
- case QFrame::VLine: {
- QPoint p1, p2;
- if (frameShape == QFrame::HLine) {
- p1 = QPoint(opt->rect.x(), opt->rect.height() / 2);
- p2 = QPoint(opt->rect.x() + opt->rect.width(), p1.y());
- } else {
- p1 = QPoint(opt->rect.x()+opt->rect.width() / 2, 0);
- p2 = QPoint(p1.x(), opt->rect.height());
- }
- if (frameShadow == QFrame::Plain) {
- QPen oldPen = p->pen();
- p->setPen(QPen(opt->palette.brush(foregroundRole), lw));
- p->drawLine(p1, p2);
- p->setPen(oldPen);
- } else {
- qDrawShadeLine(p, p1, p2, f->palette, frameShadow == QFrame::Sunken, lw, mlw);
- }
- break;
- }
- }
- }
- break;
-#endif
- default:
- break;
- }
-}
-
-/*!
- \reimp
-*/
-QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt,
- const QWidget *widget) const
-{
- Q_D(const QCommonStyle);
- QRect r;
- switch (sr) {
- case SE_PushButtonContents:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- int dx1, dx2;
- dx1 = proxy()->pixelMetric(PM_DefaultFrameWidth, btn, widget);
- if (btn->features & QStyleOptionButton::AutoDefaultButton)
- dx1 += proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget);
- dx2 = dx1 * 2;
- r.setRect(opt->rect.x() + dx1, opt->rect.y() + dx1, opt->rect.width() - dx2,
- opt->rect.height() - dx2);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
- case SE_PushButtonFocusRect:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- int dbw1 = 0, dbw2 = 0;
- if (btn->features & QStyleOptionButton::AutoDefaultButton){
- dbw1 = proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget);
- dbw2 = dbw1 * 2;
- }
-
- int dfw1 = proxy()->pixelMetric(PM_DefaultFrameWidth, btn, widget) + 1,
- dfw2 = dfw1 * 2;
-
- r.setRect(btn->rect.x() + dfw1 + dbw1, btn->rect.y() + dfw1 + dbw1,
- btn->rect.width() - dfw2 - dbw2, btn->rect.height()- dfw2 - dbw2);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
- case SE_CheckBoxIndicator:
- {
- int h = proxy()->pixelMetric(PM_IndicatorHeight, opt, widget);
- r.setRect(opt->rect.x(), opt->rect.y() + ((opt->rect.height() - h) / 2),
- proxy()->pixelMetric(PM_IndicatorWidth, opt, widget), h);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-
- case SE_CheckBoxContents:
- {
- // Deal with the logical first, then convert it back to screen coords.
- QRect ir = visualRect(opt->direction, opt->rect,
- subElementRect(SE_CheckBoxIndicator, opt, widget));
- int spacing = proxy()->pixelMetric(PM_CheckBoxLabelSpacing, opt, widget);
- r.setRect(ir.right() + spacing, opt->rect.y(), opt->rect.width() - ir.width() - spacing,
- opt->rect.height());
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-
- case SE_CheckBoxFocusRect:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (btn->icon.isNull() && btn->text.isEmpty()) {
- r = subElementRect(SE_CheckBoxIndicator, opt, widget);
- r.adjust(1, 1, -1, -1);
- break;
- }
- // As above, deal with the logical first, then convert it back to screen coords.
- QRect cr = visualRect(btn->direction, btn->rect,
- subElementRect(SE_CheckBoxContents, btn, widget));
-
- QRect iconRect, textRect;
- if (!btn->text.isEmpty()) {
- textRect = itemTextRect(opt->fontMetrics, cr, Qt::AlignAbsolute | Qt::AlignLeft
- | Qt::AlignVCenter | Qt::TextShowMnemonic,
- btn->state & State_Enabled, btn->text);
- }
- if (!btn->icon.isNull()) {
- iconRect = itemPixmapRect(cr, Qt::AlignAbsolute | Qt::AlignLeft | Qt::AlignVCenter
- | Qt::TextShowMnemonic,
- btn->icon.pixmap(btn->iconSize, QIcon::Normal));
- if (!textRect.isEmpty())
- textRect.translate(iconRect.right() + 4, 0);
- }
- r = iconRect | textRect;
- r.adjust(-3, -2, 3, 2);
- r = r.intersected(btn->rect);
- r = visualRect(btn->direction, btn->rect, r);
- }
- break;
-
- case SE_RadioButtonIndicator:
- {
- int h = proxy()->pixelMetric(PM_ExclusiveIndicatorHeight, opt, widget);
- r.setRect(opt->rect.x(), opt->rect.y() + ((opt->rect.height() - h) / 2),
- proxy()->pixelMetric(PM_ExclusiveIndicatorWidth, opt, widget), h);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-
- case SE_RadioButtonContents:
- {
- QRect ir = visualRect(opt->direction, opt->rect,
- subElementRect(SE_RadioButtonIndicator, opt, widget));
- int spacing = proxy()->pixelMetric(PM_RadioButtonLabelSpacing, opt, widget);
- r.setRect(ir.left() + ir.width() + spacing, opt->rect.y(), opt->rect.width() - ir.width() - spacing,
- opt->rect.height());
- r = visualRect(opt->direction, opt->rect, r);
- break;
- }
-
- case SE_RadioButtonFocusRect:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (btn->icon.isNull() && btn->text.isEmpty()) {
- r = subElementRect(SE_RadioButtonIndicator, opt, widget);
- r.adjust(1, 1, -1, -1);
- break;
- }
- QRect cr = visualRect(btn->direction, btn->rect,
- subElementRect(SE_RadioButtonContents, opt, widget));
-
- QRect iconRect, textRect;
- if (!btn->text.isEmpty()){
- textRect = itemTextRect(opt->fontMetrics, cr, Qt::AlignAbsolute | Qt::AlignLeft | Qt::AlignVCenter
- | Qt::TextShowMnemonic, btn->state & State_Enabled, btn->text);
- }
- if (!btn->icon.isNull()) {
- iconRect = itemPixmapRect(cr, Qt::AlignAbsolute | Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic,
- btn->icon.pixmap(btn->iconSize, QIcon::Normal));
- if (!textRect.isEmpty())
- textRect.translate(iconRect.right() + 4, 0);
- }
- r = iconRect | textRect;
- r.adjust(-3, -2, 3, 2);
- r = r.intersected(btn->rect);
- r = visualRect(btn->direction, btn->rect, r);
- }
- break;
-#ifndef QT_NO_SLIDER
- case SE_SliderFocusRect:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int tickOffset = proxy()->pixelMetric(PM_SliderTickmarkOffset, slider, widget);
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
- if (slider->orientation == Qt::Horizontal)
- r.setRect(0, tickOffset - 1, slider->rect.width(), thickness + 2);
- else
- r.setRect(tickOffset - 1, 0, thickness + 2, slider->rect.height());
- r = r.intersected(slider->rect);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_PROGRESSBAR
- case SE_ProgressBarGroove:
- case SE_ProgressBarContents:
- case SE_ProgressBarLabel:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- int textw = 0;
- bool vertical = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- vertical = (pb2->orientation == Qt::Vertical);
- }
- if (!vertical) {
- if (pb->textVisible)
- textw = qMax(pb->fontMetrics.width(pb->text), pb->fontMetrics.width(QLatin1String("100%"))) + 6;
- }
-
- if ((pb->textAlignment & Qt::AlignCenter) == 0) {
- if (sr != SE_ProgressBarLabel)
- r.setCoords(pb->rect.left(), pb->rect.top(),
- pb->rect.right() - textw, pb->rect.bottom());
- else
- r.setCoords(pb->rect.right() - textw, pb->rect.top(),
- pb->rect.right(), pb->rect.bottom());
- } else {
- r = pb->rect;
- }
- r = visualRect(pb->direction, pb->rect, r);
- }
- break;
-#endif // QT_NO_PROGRESSBAR
-#ifdef QT3_SUPPORT
- case SE_Q3DockWindowHandleRect:
- if (const QStyleOptionQ3DockWindow *dw = qstyleoption_cast<const QStyleOptionQ3DockWindow *>(opt)) {
- if (!dw->docked || !dw->closeEnabled)
- r.setRect(0, 0, dw->rect.width(), dw->rect.height());
- else {
- if (dw->state & State_Horizontal)
- r.setRect(0, 15, dw->rect.width(), dw->rect.height() - 15);
- else
- r.setRect(0, 1, dw->rect.width() - 15, dw->rect.height() - 1);
- }
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-#endif // QT3_SUPPORT
-#ifndef QT_NO_COMBOBOX
- case SE_ComboBoxFocusRect:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- int margin = cb->frame ? 3 : 0;
- r.setRect(opt->rect.left() + margin, opt->rect.top() + margin,
- opt->rect.width() - 2*margin - 16, opt->rect.height() - 2*margin);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_TOOLBOX
- case SE_ToolBoxTabContents:
- r = opt->rect;
- r.adjust(0, 0, -30, 0);
- break;
-#endif // QT_NO_TOOLBOX
- case SE_HeaderLabel: {
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, opt, widget);
- r.setRect(opt->rect.x() + margin, opt->rect.y() + margin,
- opt->rect.width() - margin * 2, opt->rect.height() - margin * 2);
-
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- // Subtract width needed for arrow, if there is one
- if (header->sortIndicator != QStyleOptionHeader::None) {
- if (opt->state & State_Horizontal)
- r.setWidth(r.width() - (opt->rect.height() / 2) - (margin * 2));
- else
- r.setHeight(r.height() - (opt->rect.width() / 2) - (margin * 2));
- }
- }
- r = visualRect(opt->direction, opt->rect, r);
- break; }
- case SE_HeaderArrow: {
- int h = opt->rect.height();
- int w = opt->rect.width();
- int x = opt->rect.x();
- int y = opt->rect.y();
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, opt, widget);
-
- if (opt->state & State_Horizontal) {
- int horiz_size = h / 2;
- r.setRect(x + w - margin * 2 - horiz_size, y + 5,
- horiz_size, h - margin * 2 - 5);
- } else {
- int vert_size = w / 2;
- r.setRect(x + 5, y + h - margin * 2 - vert_size,
- w - margin * 2 - 5, vert_size);
- }
- r = visualRect(opt->direction, opt->rect, r);
- break; }
-
- case SE_RadioButtonClickRect:
- r = subElementRect(SE_RadioButtonFocusRect, opt, widget);
- r |= subElementRect(SE_RadioButtonIndicator, opt, widget);
- break;
- case SE_CheckBoxClickRect:
- r = subElementRect(SE_CheckBoxFocusRect, opt, widget);
- r |= subElementRect(SE_CheckBoxIndicator, opt, widget);
- break;
-#ifndef QT_NO_TABWIDGET
- case SE_TabWidgetTabBar:
- if (const QStyleOptionTabWidgetFrame *twf
- = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- r.setSize(twf->tabBarSize);
- const uint alingMask = Qt::AlignLeft | Qt::AlignRight | Qt::AlignHCenter;
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- // Constrain the size now, otherwise, center could get off the page
- // This of course repeated for all the other directions
- r.setWidth(qMin(r.width(), twf->rect.width()
- - twf->leftCornerWidgetSize.width()
- - twf->rightCornerWidgetSize.width()));
- switch (proxy()->styleHint(SH_TabBar_Alignment, twf, widget) & alingMask) {
- default:
- case Qt::AlignLeft:
- r.moveTopLeft(QPoint(twf->leftCornerWidgetSize.width(), 0));
- break;
- case Qt::AlignHCenter:
- r.moveTopLeft(QPoint(twf->rect.center().x() - qRound(r.width() / 2.0f)
- + (twf->leftCornerWidgetSize.width() / 2)
- - (twf->rightCornerWidgetSize.width() / 2), 0));
- break;
- case Qt::AlignRight:
- r.moveTopLeft(QPoint(twf->rect.width() - twf->tabBarSize.width()
- - twf->rightCornerWidgetSize.width(), 0));
- break;
- }
- r = visualRect(twf->direction, twf->rect, r);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- r.setWidth(qMin(r.width(), twf->rect.width()
- - twf->leftCornerWidgetSize.width()
- - twf->rightCornerWidgetSize.width()));
- switch (proxy()->styleHint(SH_TabBar_Alignment, twf, widget) & alingMask) {
- default:
- case Qt::AlignLeft:
- r.moveTopLeft(QPoint(twf->leftCornerWidgetSize.width(),
- twf->rect.height() - twf->tabBarSize.height()));
- break;
- case Qt::AlignHCenter:
- r.moveTopLeft(QPoint(twf->rect.center().x() - qRound(r.width() / 2.0f)
- + (twf->leftCornerWidgetSize.width() / 2)
- - (twf->rightCornerWidgetSize.width() / 2),
- twf->rect.height() - twf->tabBarSize.height()));
- break;
- case Qt::AlignRight:
- r.moveTopLeft(QPoint(twf->rect.width() - twf->tabBarSize.width()
- - twf->rightCornerWidgetSize.width(),
- twf->rect.height() - twf->tabBarSize.height()));
- break;
- }
- r = visualRect(twf->direction, twf->rect, r);
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- r.setHeight(qMin(r.height(), twf->rect.height()
- - twf->leftCornerWidgetSize.height()
- - twf->rightCornerWidgetSize.height()));
- switch (proxy()->styleHint(SH_TabBar_Alignment, twf, widget) & alingMask) {
- default:
- case Qt::AlignLeft:
- r.moveTopLeft(QPoint(twf->rect.width() - twf->tabBarSize.width(),
- twf->leftCornerWidgetSize.height()));
- break;
- case Qt::AlignHCenter:
- r.moveTopLeft(QPoint(twf->rect.width() - twf->tabBarSize.width(),
- twf->rect.center().y() - r.height() / 2));
- break;
- case Qt::AlignRight:
- r.moveTopLeft(QPoint(twf->rect.width() - twf->tabBarSize.width(),
- twf->rect.height() - twf->tabBarSize.height()
- - twf->rightCornerWidgetSize.height()));
- break;
- }
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- r.setHeight(qMin(r.height(), twf->rect.height()
- - twf->leftCornerWidgetSize.height()
- - twf->rightCornerWidgetSize.height()));
- switch (proxy()->styleHint(SH_TabBar_Alignment, twf, widget) & alingMask) {
- default:
- case Qt::AlignLeft:
- r.moveTopLeft(QPoint(0, twf->leftCornerWidgetSize.height()));
- break;
- case Qt::AlignHCenter:
- r.moveTopLeft(QPoint(0, twf->rect.center().y() - r.height() / 2));
- break;
- case Qt::AlignRight:
- r.moveTopLeft(QPoint(0, twf->rect.height() - twf->tabBarSize.height()
- - twf->rightCornerWidgetSize.height()));
- break;
- }
- break;
- }
- }
- break;
- case SE_TabWidgetTabPane:
- case SE_TabWidgetTabContents:
- if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- QStyleOptionTab tabopt;
- tabopt.shape = twf->shape;
- int overlap = proxy()->pixelMetric(PM_TabBarBaseOverlap, &tabopt, widget);
- if (twf->lineWidth == 0)
- overlap = 0;
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- r = QRect(QPoint(0,qMax(twf->tabBarSize.height() - overlap, 0)),
- QSize(twf->rect.width(), qMin(twf->rect.height() - twf->tabBarSize.height() + overlap, twf->rect.height())));
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- r = QRect(QPoint(0,0), QSize(twf->rect.width(), qMin(twf->rect.height() - twf->tabBarSize.height() + overlap, twf->rect.height())));
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- r = QRect(QPoint(0, 0), QSize(qMin(twf->rect.width() - twf->tabBarSize.width() + overlap, twf->rect.width()), twf->rect.height()));
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- r = QRect(QPoint(qMax(twf->tabBarSize.width() - overlap, 0), 0),
- QSize(qMin(twf->rect.width() - twf->tabBarSize.width() + overlap, twf->rect.width()), twf->rect.height()));
- break;
- }
- if (sr == SE_TabWidgetTabContents && twf->lineWidth > 0)
- r.adjust(2, 2, -2, -2);
- }
- break;
- case SE_TabWidgetLeftCorner:
- if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- QRect paneRect = subElementRect(SE_TabWidgetTabPane, twf, widget);
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- r = QRect(QPoint(paneRect.x(), paneRect.y() - twf->leftCornerWidgetSize.height()),
- twf->leftCornerWidgetSize);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- r = QRect(QPoint(paneRect.x(), paneRect.height()), twf->leftCornerWidgetSize);
- break;
- default:
- break;
- }
- r = visualRect(twf->direction, twf->rect, r);
- }
- break;
- case SE_TabWidgetRightCorner:
- if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- QRect paneRect = subElementRect(SE_TabWidgetTabPane, twf, widget);
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- r = QRect(QPoint(paneRect.width() - twf->rightCornerWidgetSize.width(),
- paneRect.y() - twf->rightCornerWidgetSize.height()),
- twf->rightCornerWidgetSize);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- r = QRect(QPoint(paneRect.width() - twf->rightCornerWidgetSize.width(),
- paneRect.height()), twf->rightCornerWidgetSize);
- break;
- default:
- break;
- }
- r = visualRect(twf->direction, twf->rect, r);
- }
- break;
- case SE_TabBarTabText:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- QStyleOptionTabV3 tabV3(*tab);
- QRect dummyIconRect;
- d->tabLayout(&tabV3, widget, &r, &dummyIconRect);
- }
- break;
- case SE_TabBarTabLeftButton:
- case SE_TabBarTabRightButton:
- if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(opt)) {
- bool selected = tab->state & State_Selected;
- int verticalShift = proxy()->pixelMetric(QStyle::PM_TabBarTabShiftVertical, tab, widget);
- int horizontalShift = proxy()->pixelMetric(QStyle::PM_TabBarTabShiftHorizontal, tab, widget);
- int hpadding = proxy()->pixelMetric(QStyle::PM_TabBarTabHSpace, opt, widget) / 2;
- hpadding = qMax(hpadding, 4); //workaround KStyle returning 0 because they workaround an old bug in Qt
-
- bool verticalTabs = tab->shape == QTabBar::RoundedEast
- || tab->shape == QTabBar::RoundedWest
- || tab->shape == QTabBar::TriangularEast
- || tab->shape == QTabBar::TriangularWest;
-
- QRect tr = tab->rect;
- if (tab->shape == QTabBar::RoundedSouth || tab->shape == QTabBar::TriangularSouth)
- verticalShift = -verticalShift;
- if (verticalTabs) {
- qSwap(horizontalShift, verticalShift);
- horizontalShift *= -1;
- verticalShift *= -1;
- }
- if (tab->shape == QTabBar::RoundedWest || tab->shape == QTabBar::TriangularWest)
- horizontalShift = -horizontalShift;
-
- tr.adjust(0, 0, horizontalShift, verticalShift);
- if (selected)
- {
- tr.setBottom(tr.bottom() - verticalShift);
- tr.setRight(tr.right() - horizontalShift);
- }
-
- QSize size = (sr == SE_TabBarTabLeftButton) ? tab->leftButtonSize : tab->rightButtonSize;
- int w = size.width();
- int h = size.height();
- int midHeight = static_cast<int>(qCeil(float(tr.height() - h) / 2));
- int midWidth = ((tr.width() - w) / 2);
-
- bool atTheTop = true;
- switch (tab->shape) {
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- atTheTop = (sr == SE_TabBarTabLeftButton);
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- atTheTop = (sr == SE_TabBarTabRightButton);
- break;
- default:
- if (sr == SE_TabBarTabLeftButton)
- r = QRect(tab->rect.x() + hpadding, midHeight, w, h);
- else
- r = QRect(tab->rect.right() - w - hpadding, midHeight, w, h);
- r = visualRect(tab->direction, tab->rect, r);
- }
- if (verticalTabs) {
- if (atTheTop)
- r = QRect(midWidth, tr.y() + tab->rect.height() - hpadding - h, w, h);
- else
- r = QRect(midWidth, tr.y() + hpadding, w, h);
- }
- }
-
- break;
-#endif // QT_NO_TABWIDGET
-#ifndef QT_NO_TABBAR
- case SE_TabBarTearIndicator:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- r.setRect(tab->rect.left(), tab->rect.top(), 4, opt->rect.height());
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- r.setRect(tab->rect.left(), tab->rect.top(), opt->rect.width(), 4);
- break;
- default:
- break;
- }
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
-#endif
- case SE_TreeViewDisclosureItem:
- r = opt->rect;
- break;
- case SE_LineEditContents:
- if (const QStyleOptionFrame *f = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- r = f->rect.adjusted(f->lineWidth, f->lineWidth, -f->lineWidth, -f->lineWidth);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
- case SE_FrameContents:
- if (const QStyleOptionFrameV2 *f = qstyleoption_cast<const QStyleOptionFrameV2 *>(opt)) {
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, f, widget);
- r = opt->rect.adjusted(fw, fw, -fw, -fw);
- r = visualRect(opt->direction, opt->rect, r);
- }
- break;
- case SE_ShapedFrameContents:
- if (const QStyleOptionFrameV3 *f = qstyleoption_cast<const QStyleOptionFrameV3 *>(opt)) {
- int frameShape = f->frameShape;
- int frameShadow = QFrame::Plain;
- if (f->state & QStyle::State_Sunken) {
- frameShadow = QFrame::Sunken;
- } else if (f->state & QStyle::State_Raised) {
- frameShadow = QFrame::Raised;
- }
-
- int frameWidth = 0;
-
- switch (frameShape) {
- case QFrame::NoFrame:
- frameWidth = 0;
- break;
-
- case QFrame::Box:
- case QFrame::HLine:
- case QFrame::VLine:
- switch (frameShadow) {
- case QFrame::Plain:
- frameWidth = f->lineWidth;
- break;
- case QFrame::Raised:
- case QFrame::Sunken:
- frameWidth = (short)(f->lineWidth*2 + f->midLineWidth);
- break;
- }
- break;
-
- case QFrame::StyledPanel:
- //keep the compatibility with Qt 4.4 if there is a proxy style.
- //be sure to call drawPrimitive(QStyle::SE_FrameContents) on the proxy style
- if (widget)
- return widget->style()->subElementRect(QStyle::SE_FrameContents, opt, widget);
- else
- return subElementRect(QStyle::SE_FrameContents, opt, widget);
- break;
-
- case QFrame::WinPanel:
- frameWidth = 2;
- break;
-
- case QFrame::Panel:
- switch (frameShadow) {
- case QFrame::Plain:
- case QFrame::Raised:
- case QFrame::Sunken:
- frameWidth = f->lineWidth;
- break;
- }
- break;
- }
- r = f->rect.adjusted(frameWidth, frameWidth, -frameWidth, -frameWidth);
- }
- break;
-#ifndef QT_NO_DOCKWIDGET
- case SE_DockWidgetCloseButton:
- case SE_DockWidgetFloatButton:
- case SE_DockWidgetTitleBarText:
- case SE_DockWidgetIcon: {
- int iconSize = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
- int buttonMargin = proxy()->pixelMetric(PM_DockWidgetTitleBarButtonMargin, opt, widget);
- int margin = proxy()->pixelMetric(QStyle::PM_DockWidgetTitleMargin, opt, widget);
- QRect rect = opt->rect;
-
- const QStyleOptionDockWidget *dwOpt
- = qstyleoption_cast<const QStyleOptionDockWidget*>(opt);
- bool canClose = dwOpt == 0 ? true : dwOpt->closable;
- bool canFloat = dwOpt == 0 ? false : dwOpt->floatable;
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- // If this is a vertical titlebar, we transpose and work as if it was
- // horizontal, then transpose again.
-
- if (verticalTitleBar) {
- QSize size = rect.size();
- size.transpose();
- rect.setSize(size);
- }
-
- do {
-
- int right = rect.right();
- int left = rect.left();
-
- QRect closeRect;
- if (canClose) {
- QSize sz = standardIcon(QStyle::SP_TitleBarCloseButton,
- opt, widget).actualSize(QSize(iconSize, iconSize));
- sz += QSize(buttonMargin, buttonMargin);
- if (verticalTitleBar)
- sz.transpose();
- closeRect = QRect(right - sz.width(),
- rect.center().y() - sz.height()/2,
- sz.width(), sz.height());
- right = closeRect.left() - 1;
- }
- if (sr == SE_DockWidgetCloseButton) {
- r = closeRect;
- break;
- }
-
- QRect floatRect;
- if (canFloat) {
- QSize sz = standardIcon(QStyle::SP_TitleBarNormalButton,
- opt, widget).actualSize(QSize(iconSize, iconSize));
- sz += QSize(buttonMargin, buttonMargin);
- if (verticalTitleBar)
- sz.transpose();
- floatRect = QRect(right - sz.width(),
- rect.center().y() - sz.height()/2,
- sz.width(), sz.height());
- right = floatRect.left() - 1;
- }
- if (sr == SE_DockWidgetFloatButton) {
- r = floatRect;
- break;
- }
-
- QRect iconRect;
- if (const QDockWidget *dw = qobject_cast<const QDockWidget*>(widget)) {
- QIcon icon;
- if (dw->isFloating())
- icon = dw->windowIcon();
- if (!icon.isNull()
- && icon.cacheKey() != QApplication::windowIcon().cacheKey()) {
- QSize sz = icon.actualSize(QSize(r.height(), r.height()));
- if (verticalTitleBar)
- sz.transpose();
- iconRect = QRect(left, rect.center().y() - sz.height()/2,
- sz.width(), sz.height());
- left = iconRect.right() + margin;
- }
- }
- if (sr == SE_DockWidgetIcon) {
- r = iconRect;
- break;
- }
-
- QRect textRect = QRect(left, rect.top(),
- right - left, rect.height());
- if (sr == SE_DockWidgetTitleBarText) {
- r = textRect;
- break;
- }
-
- } while (false);
-
- if (verticalTitleBar) {
- r = QRect(rect.left() + r.top() - rect.top(),
- rect.top() + rect.right() - r.right(),
- r.height(), r.width());
- } else {
- r = visualRect(opt->direction, rect, r);
- }
- break;
- }
-#endif
-#ifndef QT_NO_ITEMVIEWS
- case SE_ItemViewItemCheckIndicator:
- if (!qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- r = subElementRect(SE_CheckBoxIndicator, opt, widget);
- break;
- }
- case SE_ItemViewItemDecoration:
- case SE_ItemViewItemText:
- case SE_ItemViewItemFocusRect:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- if (!d->isViewItemCached(*vopt)) {
- d->viewItemLayout(vopt, &d->checkRect, &d->decorationRect, &d->displayRect, false);
- if (d->cachedOption) {
- delete d->cachedOption;
- d->cachedOption = 0;
- }
- d->cachedOption = new QStyleOptionViewItemV4(*vopt);
- }
- if (sr == SE_ViewItemCheckIndicator)
- r = d->checkRect;
- else if (sr == SE_ItemViewItemDecoration)
- r = d->decorationRect;
- else if (sr == SE_ItemViewItemText || sr == SE_ItemViewItemFocusRect)
- r = d->displayRect;
- }
- break;
-#endif //QT_NO_ITEMVIEWS
-#ifndef QT_NO_TOOLBAR
- case SE_ToolBarHandle:
- if (const QStyleOptionToolBar *tbopt = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
- if (tbopt->features & QStyleOptionToolBar::Movable) {
- ///we need to access the widget here because the style option doesn't
- //have all the information we need (ie. the layout's margin)
- const QToolBar *tb = qobject_cast<const QToolBar*>(widget);
- const int margin = tb && tb->layout() ? tb->layout()->margin() : 2;
- const int handleExtent = pixelMetric(QStyle::PM_ToolBarHandleExtent, opt, tb);
- if (tbopt->state & QStyle::State_Horizontal) {
- r = QRect(margin, margin, handleExtent, tbopt->rect.height() - 2*margin);
- r = QStyle::visualRect(tbopt->direction, tbopt->rect, r);
- } else {
- r = QRect(margin, margin, tbopt->rect.width() - 2*margin, handleExtent);
- }
- }
- }
- break;
-#endif //QT_NO_TOOLBAR
- default:
- break;
- }
- return r;
-}
-
-#ifndef QT_NO_DIAL
-
-static QPolygonF calcArrow(const QStyleOptionSlider *dial, qreal &a)
-{
- int width = dial->rect.width();
- int height = dial->rect.height();
- int r = qMin(width, height) / 2;
- int currentSliderPosition = dial->upsideDown ? dial->sliderPosition : (dial->maximum - dial->sliderPosition);
-
- if (dial->maximum == dial->minimum)
- a = Q_PI / 2;
- else if (dial->dialWrapping)
- a = Q_PI * 3 / 2 - (currentSliderPosition - dial->minimum) * 2 * Q_PI
- / (dial->maximum - dial->minimum);
- else
- a = (Q_PI * 8 - (currentSliderPosition - dial->minimum) * 10 * Q_PI
- / (dial->maximum - dial->minimum)) / 6;
-
- int xc = width / 2;
- int yc = height / 2;
-
- int len = r - QStyleHelper::calcBigLineSize(r) - 5;
- if (len < 5)
- len = 5;
- int back = len / 2;
-
- QPolygonF arrow(3);
- arrow[0] = QPointF(0.5 + xc + len * qCos(a),
- 0.5 + yc - len * qSin(a));
- arrow[1] = QPointF(0.5 + xc + back * qCos(a + Q_PI * 5 / 6),
- 0.5 + yc - back * qSin(a + Q_PI * 5 / 6));
- arrow[2] = QPointF(0.5 + xc + back * qCos(a - Q_PI * 5 / 6),
- 0.5 + yc - back * qSin(a - Q_PI * 5 / 6));
- return arrow;
-}
-
-#endif // QT_NO_DIAL
-
-/*!
- \reimp
-*/
-void QCommonStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- QPainter *p, const QWidget *widget) const
-{
- switch (cc) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- if (slider->subControls == SC_SliderTickmarks) {
- int tickOffset = proxy()->pixelMetric(PM_SliderTickmarkOffset, slider, widget);
- int ticks = slider->tickPosition;
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
- int interval = slider->tickInterval;
- if (interval <= 0) {
- interval = slider->singleStep;
- if (QStyle::sliderPositionFromValue(slider->minimum, slider->maximum, interval,
- available)
- - QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- 0, available) < 3)
- interval = slider->pageStep;
- }
- if (!interval)
- interval = 1;
- int fudge = len / 2;
- int pos;
- // Since there is no subrect for tickmarks do a translation here.
- p->save();
- p->translate(slider->rect.x(), slider->rect.y());
- p->setPen(slider->palette.foreground().color());
- int v = slider->minimum;
- while (v <= slider->maximum + 1) {
- if (v == slider->maximum + 1 && interval == 1)
- break;
- const int v_ = qMin(v, slider->maximum);
- pos = QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- v_, available) + fudge;
- if (slider->orientation == Qt::Horizontal) {
- if (ticks & QSlider::TicksAbove)
- p->drawLine(pos, 0, pos, tickOffset - 2);
- if (ticks & QSlider::TicksBelow)
- p->drawLine(pos, tickOffset + thickness + 1, pos,
- slider->rect.height()-1);
- } else {
- if (ticks & QSlider::TicksAbove)
- p->drawLine(0, pos, tickOffset - 2, pos);
- if (ticks & QSlider::TicksBelow)
- p->drawLine(tickOffset + thickness + 1, pos,
- slider->rect.width()-1, pos);
- }
- // in the case where maximum is max int
- int nextInterval = v + interval;
- if (nextInterval < v)
- break;
- v = nextInterval;
- }
- p->restore();
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- // Make a copy here and reset it for each primitive.
- QStyleOptionSlider newScrollbar = *scrollbar;
- State saveFlags = scrollbar->state;
-
- if (scrollbar->subControls & SC_ScrollBarSubLine) {
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarSubLine, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarSubLine))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarSubLine, &newScrollbar, p, widget);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarAddLine) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarAddLine, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarAddLine))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarAddLine, &newScrollbar, p, widget);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarSubPage) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarSubPage, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarSubPage))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarSubPage, &newScrollbar, p, widget);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarAddPage) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarAddPage, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarAddPage))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarAddPage, &newScrollbar, p, widget);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarFirst) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarFirst, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarFirst))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarFirst, &newScrollbar, p, widget);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarLast) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarLast, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarLast))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarLast, &newScrollbar, p, widget);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarSlider) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(cc, &newScrollbar, SC_ScrollBarSlider, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarSlider))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- proxy()->drawControl(CE_ScrollBarSlider, &newScrollbar, p, widget);
-
- if (scrollbar->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(newScrollbar);
- fropt.rect.setRect(newScrollbar.rect.x() + 2, newScrollbar.rect.y() + 2,
- newScrollbar.rect.width() - 5,
- newScrollbar.rect.height() - 5);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- }
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifdef QT3_SUPPORT
- case CC_Q3ListView:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- if (lv->subControls & SC_Q3ListView)
- p->fillRect(lv->rect, lv->viewportPalette.brush(lv->viewportBGRole));
- }
- break;
-#endif // QT3_SUPPORT
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QStyleOptionSpinBox copy = *sb;
- PrimitiveElement pe;
-
- if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
- QRect r = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxFrame, widget);
- qDrawWinPanel(p, r, sb->palette, true);
- }
-
- if (sb->subControls & SC_SpinBoxUp) {
- copy.subControls = SC_SpinBoxUp;
- QPalette pal2 = sb->palette;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepUpEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
-
- copy.palette = pal2;
-
- if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinPlus
- : PE_IndicatorSpinUp);
-
- copy.rect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxUp, widget);
- proxy()->drawPrimitive(PE_PanelButtonBevel, &copy, p, widget);
- copy.rect.adjust(3, 0, -4, 0);
- proxy()->drawPrimitive(pe, &copy, p, widget);
- }
-
- if (sb->subControls & SC_SpinBoxDown) {
- copy.subControls = SC_SpinBoxDown;
- copy.state = sb->state;
- QPalette pal2 = sb->palette;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
-
- if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinMinus
- : PE_IndicatorSpinDown);
-
- copy.rect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxDown, widget);
- proxy()->drawPrimitive(PE_PanelButtonBevel, &copy, p, widget);
- copy.rect.adjust(3, 0, -4, 0);
- proxy()->drawPrimitive(pe, &copy, p, widget);
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_TOOLBUTTON
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- QRect button, menuarea;
- button = proxy()->subControlRect(cc, toolbutton, SC_ToolButton, widget);
- menuarea = proxy()->subControlRect(cc, toolbutton, SC_ToolButtonMenu, widget);
-
- State bflags = toolbutton->state & ~State_Sunken;
-
- if (bflags & State_AutoRaise) {
- if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) {
- bflags &= ~State_Raised;
- }
- }
- State mflags = bflags;
- if (toolbutton->state & State_Sunken) {
- if (toolbutton->activeSubControls & SC_ToolButton)
- bflags |= State_Sunken;
- mflags |= State_Sunken;
- }
-
- QStyleOption tool(0);
- tool.palette = toolbutton->palette;
- if (toolbutton->subControls & SC_ToolButton) {
- if (bflags & (State_Sunken | State_On | State_Raised)) {
- tool.rect = button;
- tool.state = bflags;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- }
- }
-
- if (toolbutton->state & State_HasFocus) {
- QStyleOptionFocusRect fr;
- fr.QStyleOption::operator=(*toolbutton);
- fr.rect.adjust(3, 3, -3, -3);
- if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup)
- fr.rect.adjust(0, 0, -proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator,
- toolbutton, widget), 0);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fr, p, widget);
- }
- QStyleOptionToolButton label = *toolbutton;
- label.state = bflags;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- label.rect = button.adjusted(fw, fw, -fw, -fw);
- proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget);
-
- if (toolbutton->subControls & SC_ToolButtonMenu) {
- tool.rect = menuarea;
- tool.state = mflags;
- if (mflags & (State_Sunken | State_On | State_Raised))
- proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, p, widget);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, p, widget);
- } else if (toolbutton->features & QStyleOptionToolButton::HasMenu) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolbutton, widget);
- QRect ir = toolbutton->rect;
- QStyleOptionToolButton newBtn = *toolbutton;
- newBtn.rect = QRect(ir.right() + 5 - mbi, ir.y() + ir.height() - mbi + 4, mbi - 6, mbi - 6);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
- }
- }
- break;
-#endif // QT_NO_TOOLBUTTON
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- QRect ir;
- if (opt->subControls & SC_TitleBarLabel) {
- QColor left = tb->palette.highlight().color();
- QColor right = tb->palette.base().color();
-
- QBrush fillBrush(left);
- if (left != right) {
- QPoint p1(tb->rect.x(), tb->rect.top() + tb->rect.height()/2);
- QPoint p2(tb->rect.right(), tb->rect.top() + tb->rect.height()/2);
- QLinearGradient lg(p1, p2);
- lg.setColorAt(0, left);
- lg.setColorAt(1, right);
- fillBrush = lg;
- }
-
- p->fillRect(opt->rect, fillBrush);
-
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarLabel, widget);
-
- p->setPen(tb->palette.highlightedText().color());
- p->drawText(ir.x() + 2, ir.y(), ir.width() - 2, ir.height(),
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
- }
-
- bool down = false;
- QPixmap pm;
-
- QStyleOption tool(0);
- tool.palette = tb->palette;
- if (tb->subControls & SC_TitleBarCloseButton && tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarCloseButton, widget);
- down = tb->activeSubControls & SC_TitleBarCloseButton && (opt->state & State_Sunken);
- if ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool
-#ifndef QT_NO_DOCKWIDGET
- || qobject_cast<const QDockWidget *>(widget)
-#endif
- )
- pm = standardIcon(SP_DockWidgetCloseButton, &tool, widget).pixmap(10, 10);
- else
- pm = standardIcon(SP_TitleBarCloseButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
-
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
-
- if (tb->subControls & SC_TitleBarMaxButton
- && tb->titleBarFlags & Qt::WindowMaximizeButtonHint
- && !(tb->titleBarState & Qt::WindowMaximized)) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarMaxButton, widget);
-
- down = tb->activeSubControls & SC_TitleBarMaxButton && (opt->state & State_Sunken);
- pm = standardIcon(SP_TitleBarMaxButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
-
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
-
- if (tb->subControls & SC_TitleBarMinButton
- && tb->titleBarFlags & Qt::WindowMinimizeButtonHint
- && !(tb->titleBarState & Qt::WindowMinimized)) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarMinButton, widget);
- down = tb->activeSubControls & SC_TitleBarMinButton && (opt->state & State_Sunken);
- pm = standardIcon(SP_TitleBarMinButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
-
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
-
- bool drawNormalButton = (tb->subControls & SC_TitleBarNormalButton)
- && (((tb->titleBarFlags & Qt::WindowMinimizeButtonHint)
- && (tb->titleBarState & Qt::WindowMinimized))
- || ((tb->titleBarFlags & Qt::WindowMaximizeButtonHint)
- && (tb->titleBarState & Qt::WindowMaximized)));
-
- if (drawNormalButton) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarNormalButton, widget);
- down = tb->activeSubControls & SC_TitleBarNormalButton && (opt->state & State_Sunken);
- pm = standardIcon(SP_TitleBarNormalButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
-
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
-
- if (tb->subControls & SC_TitleBarShadeButton
- && tb->titleBarFlags & Qt::WindowShadeButtonHint
- && !(tb->titleBarState & Qt::WindowMinimized)) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarShadeButton, widget);
- down = (tb->activeSubControls & SC_TitleBarShadeButton && (opt->state & State_Sunken));
- pm = standardIcon(SP_TitleBarShadeButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
-
- if (tb->subControls & SC_TitleBarUnshadeButton
- && tb->titleBarFlags & Qt::WindowShadeButtonHint
- && tb->titleBarState & Qt::WindowMinimized) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarUnshadeButton, widget);
-
- down = tb->activeSubControls & SC_TitleBarUnshadeButton && (opt->state & State_Sunken);
- pm = standardIcon(SP_TitleBarUnshadeButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
- if (tb->subControls & SC_TitleBarContextHelpButton
- && tb->titleBarFlags & Qt::WindowContextHelpButtonHint) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarContextHelpButton, widget);
-
- down = tb->activeSubControls & SC_TitleBarContextHelpButton && (opt->state & State_Sunken);
- pm = standardIcon(SP_TitleBarContextHelpButton, &tool, widget).pixmap(10, 10);
- tool.rect = ir;
- tool.state = down ? State_Sunken : State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- p->save();
- if (down)
- p->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, tb, widget));
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
- if (tb->subControls & SC_TitleBarSysMenu && tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarSysMenu, widget);
- if (!tb->icon.isNull()) {
- tb->icon.paint(p, ir);
- } else {
- int iconSize = proxy()->pixelMetric(PM_SmallIconSize, tb, widget);
- pm = standardIcon(SP_TitleBarMenuButton, &tool, widget).pixmap(iconSize, iconSize);
- tool.rect = ir;
- p->save();
- proxy()->drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- p->restore();
- }
- }
- }
- break;
-#ifndef QT_NO_DIAL
- case CC_Dial:
- if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- // OK, this is more a port of things over
- p->save();
-
- // avoid dithering
- if (p->paintEngine()->hasFeature(QPaintEngine::Antialiasing))
- p->setRenderHint(QPainter::Antialiasing);
-
- int width = dial->rect.width();
- int height = dial->rect.height();
- qreal r = qMin(width, height) / 2;
- qreal d_ = r / 6;
- qreal dx = dial->rect.x() + d_ + (width - 2 * r) / 2 + 1;
- qreal dy = dial->rect.y() + d_ + (height - 2 * r) / 2 + 1;
- QRect br = QRect(int(dx), int(dy), int(r * 2 - 2 * d_ - 2), int(r * 2 - 2 * d_ - 2));
-
- QPalette pal = opt->palette;
- // draw notches
- if (dial->subControls & QStyle::SC_DialTickmarks) {
- p->setPen(pal.foreground().color());
- p->drawLines(QStyleHelper::calcLines(dial));
- }
-
- if (dial->state & State_Enabled) {
- p->setBrush(pal.brush(QPalette::ColorRole(proxy()->styleHint(SH_Dial_BackgroundRole,
- dial, widget))));
- p->setPen(Qt::NoPen);
- p->drawEllipse(br);
- p->setBrush(Qt::NoBrush);
- }
- p->setPen(QPen(pal.dark().color()));
- p->drawArc(br, 60 * 16, 180 * 16);
- p->setPen(QPen(pal.light().color()));
- p->drawArc(br, 240 * 16, 180 * 16);
-
- qreal a;
- QPolygonF arrow(calcArrow(dial, a));
-
- p->setPen(Qt::NoPen);
- p->setBrush(pal.button());
- p->drawPolygon(arrow);
-
- a = QStyleHelper::angle(QPointF(width / 2, height / 2), arrow[0]);
- p->setBrush(Qt::NoBrush);
-
- if (a <= 0 || a > 200) {
- p->setPen(pal.light().color());
- p->drawLine(arrow[2], arrow[0]);
- p->drawLine(arrow[1], arrow[2]);
- p->setPen(pal.dark().color());
- p->drawLine(arrow[0], arrow[1]);
- } else if (a > 0 && a < 45) {
- p->setPen(pal.light().color());
- p->drawLine(arrow[2], arrow[0]);
- p->setPen(pal.dark().color());
- p->drawLine(arrow[1], arrow[2]);
- p->drawLine(arrow[0], arrow[1]);
- } else if (a >= 45 && a < 135) {
- p->setPen(pal.dark().color());
- p->drawLine(arrow[2], arrow[0]);
- p->drawLine(arrow[1], arrow[2]);
- p->setPen(pal.light().color());
- p->drawLine(arrow[0], arrow[1]);
- } else if (a >= 135 && a < 200) {
- p->setPen(pal.dark().color());
- p->drawLine(arrow[2], arrow[0]);
- p->setPen(pal.light().color());
- p->drawLine(arrow[0], arrow[1]);
- p->drawLine(arrow[1], arrow[2]);
- }
-
- // draw focus rect around the dial
- QStyleOptionFocusRect fropt;
- fropt.rect = dial->rect;
- fropt.state = dial->state;
- fropt.palette = dial->palette;
- if (fropt.state & QStyle::State_HasFocus) {
- br.adjust(0, 0, 2, 2);
- if (dial->subControls & SC_DialTickmarks) {
- int r = qMin(width, height) / 2;
- br.translate(-r / 6, - r / 6);
- br.setWidth(br.width() + r / 3);
- br.setHeight(br.height() + r / 3);
- }
- fropt.rect = br.adjusted(-2, -2, 2, 2);
- proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, p, widget);
- }
- p->restore();
- }
- break;
-#endif // QT_NO_DIAL
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- // Draw frame
- QRect textRect = proxy()->subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, widget);
- QRect checkBoxRect = proxy()->subControlRect(CC_GroupBox, opt, SC_GroupBoxCheckBox, widget);
- if (groupBox->subControls & QStyle::SC_GroupBoxFrame) {
- QStyleOptionFrameV2 frame;
- frame.QStyleOption::operator=(*groupBox);
- frame.features = groupBox->features;
- frame.lineWidth = groupBox->lineWidth;
- frame.midLineWidth = groupBox->midLineWidth;
- frame.rect = proxy()->subControlRect(CC_GroupBox, opt, SC_GroupBoxFrame, widget);
- p->save();
- QRegion region(groupBox->rect);
- if (!groupBox->text.isEmpty()) {
- bool ltr = groupBox->direction == Qt::LeftToRight;
- QRect finalRect;
- if (groupBox->subControls & QStyle::SC_GroupBoxCheckBox) {
- finalRect = checkBoxRect.united(textRect);
- finalRect.adjust(ltr ? -4 : 0, 0, ltr ? 0 : 4, 0);
- } else {
- finalRect = textRect;
- }
- region -= finalRect;
- }
- p->setClipRegion(region);
- proxy()->drawPrimitive(PE_FrameGroupBox, &frame, p, widget);
- p->restore();
- }
-
- // Draw title
- if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
- QColor textColor = groupBox->textColor;
- if (textColor.isValid())
- p->setPen(textColor);
- int alignment = int(groupBox->textAlignment);
- if (!proxy()->styleHint(QStyle::SH_UnderlineShortcut, opt, widget))
- alignment |= Qt::TextHideMnemonic;
-
- proxy()->drawItemText(p, textRect, Qt::TextShowMnemonic | Qt::AlignHCenter | alignment,
- groupBox->palette, groupBox->state & State_Enabled, groupBox->text,
- textColor.isValid() ? QPalette::NoRole : QPalette::WindowText);
-
- if (groupBox->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*groupBox);
- fropt.rect = textRect;
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
-
- // Draw checkbox
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*groupBox);
- box.rect = checkBoxRect;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &box, p, widget);
- }
- }
- break;
-#endif // QT_NO_GROUPBOX
-#ifndef QT_NO_WORKSPACE
- case CC_MdiControls:
- {
- QStyleOptionButton btnOpt;
- btnOpt.QStyleOption::operator=(*opt);
- btnOpt.state &= ~State_MouseOver;
- int bsx = 0;
- int bsy = 0;
- if (opt->subControls & QStyle::SC_MdiCloseButton) {
- if (opt->activeSubControls & QStyle::SC_MdiCloseButton && (opt->state & State_Sunken)) {
- btnOpt.state |= State_Sunken;
- btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
- } else {
- btnOpt.state |= State_Raised;
- btnOpt.state &= ~State_Sunken;
- bsx = 0;
- bsy = 0;
- }
- btnOpt.rect = proxy()->subControlRect(CC_MdiControls, opt, SC_MdiCloseButton, widget);
- proxy()->drawPrimitive(PE_PanelButtonCommand, &btnOpt, p, widget);
- QPixmap pm = standardIcon(SP_TitleBarCloseButton).pixmap(16, 16);
- proxy()->drawItemPixmap(p, btnOpt.rect.translated(bsx, bsy), Qt::AlignCenter, pm);
- }
- if (opt->subControls & QStyle::SC_MdiNormalButton) {
- if (opt->activeSubControls & QStyle::SC_MdiNormalButton && (opt->state & State_Sunken)) {
- btnOpt.state |= State_Sunken;
- btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
- } else {
- btnOpt.state |= State_Raised;
- btnOpt.state &= ~State_Sunken;
- bsx = 0;
- bsy = 0;
- }
- btnOpt.rect = proxy()->subControlRect(CC_MdiControls, opt, SC_MdiNormalButton, widget);
- proxy()->drawPrimitive(PE_PanelButtonCommand, &btnOpt, p, widget);
- QPixmap pm = standardIcon(SP_TitleBarNormalButton).pixmap(16, 16);
- proxy()->drawItemPixmap(p, btnOpt.rect.translated(bsx, bsy), Qt::AlignCenter, pm);
- }
- if (opt->subControls & QStyle::SC_MdiMinButton) {
- if (opt->activeSubControls & QStyle::SC_MdiMinButton && (opt->state & State_Sunken)) {
- btnOpt.state |= State_Sunken;
- btnOpt.state &= ~State_Raised;
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
- } else {
- btnOpt.state |= State_Raised;
- btnOpt.state &= ~State_Sunken;
- bsx = 0;
- bsy = 0;
- }
- btnOpt.rect = proxy()->subControlRect(CC_MdiControls, opt, SC_MdiMinButton, widget);
- proxy()->drawPrimitive(PE_PanelButtonCommand, &btnOpt, p, widget);
- QPixmap pm = standardIcon(SP_TitleBarMinButton).pixmap(16, 16);
- proxy()->drawItemPixmap(p, btnOpt.rect.translated(bsx, bsy), Qt::AlignCenter, pm);
- }
- }
- break;
-#endif // QT_NO_WORKSPACE
-
- default:
- qWarning("QCommonStyle::drawComplexControl: Control %d not handled", cc);
- }
-}
-
-/*!
- \reimp
-*/
-QStyle::SubControl QCommonStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *widget) const
-{
- SubControl sc = SC_None;
- switch (cc) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QRect r = proxy()->subControlRect(cc, slider, SC_SliderHandle, widget);
- if (r.isValid() && r.contains(pt)) {
- sc = SC_SliderHandle;
- } else {
- r = proxy()->subControlRect(cc, slider, SC_SliderGroove ,widget);
- if (r.isValid() && r.contains(pt))
- sc = SC_SliderGroove;
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QRect r;
- uint ctrl = SC_ScrollBarAddLine;
- while (ctrl <= SC_ScrollBarGroove) {
- r = proxy()->subControlRect(cc, scrollbar, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl <<= 1;
- }
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_TOOLBUTTON
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- QRect r;
- uint ctrl = SC_ToolButton;
- while (ctrl <= SC_ToolButtonMenu) {
- r = proxy()->subControlRect(cc, toolbutton, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl <<= 1;
- }
- }
- break;
-#endif // QT_NO_TOOLBUTTON
-#ifdef QT3_SUPPORT
- case CC_Q3ListView:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- if (pt.x() >= 0 && pt.x() < lv->treeStepSize)
- sc = SC_Q3ListViewExpand;
- }
- break;
-#endif // QT3_SUPPORT
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QRect r;
- uint ctrl = SC_SpinBoxUp;
- while (ctrl <= SC_SpinBoxEditField) {
- r = proxy()->subControlRect(cc, spinbox, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl <<= 1;
- }
- }
- break;
-#endif // QT_NO_SPINBOX
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- QRect r;
- uint ctrl = SC_TitleBarSysMenu;
-
- while (ctrl <= SC_TitleBarLabel) {
- r = proxy()->subControlRect(cc, tb, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl <<= 1;
- }
- }
- break;
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QRect r;
- uint ctrl = SC_ComboBoxArrow; // Start here and go down.
- while (ctrl > 0) {
- r = proxy()->subControlRect(cc, cb, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl >>= 1;
- }
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- QRect r;
- uint ctrl = SC_GroupBoxCheckBox;
- while (ctrl <= SC_GroupBoxFrame) {
- r = proxy()->subControlRect(cc, groupBox, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl <<= 1;
- }
- }
- break;
-#endif // QT_NO_GROUPBOX
- case CC_MdiControls:
- {
- QRect r;
- uint ctrl = SC_MdiMinButton;
- while (ctrl <= SC_MdiCloseButton) {
- r = proxy()->subControlRect(CC_MdiControls, opt, QStyle::SubControl(ctrl), widget);
- if (r.isValid() && r.contains(pt) && (opt->subControls & ctrl)) {
- sc = QStyle::SubControl(ctrl);
- return sc;
- }
- ctrl <<= 1;
- }
- }
- break;
- default:
- qWarning("QCommonStyle::hitTestComplexControl: Case %d not handled", cc);
- }
- return sc;
-}
-
-/*!
- \reimp
-*/
-QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const
-{
- QRect ret;
- switch (cc) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int tickOffset = proxy()->pixelMetric(PM_SliderTickmarkOffset, slider, widget);
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
-
- switch (sc) {
- case SC_SliderHandle: {
- int sliderPos = 0;
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- bool horizontal = slider->orientation == Qt::Horizontal;
- sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum,
- slider->sliderPosition,
- (horizontal ? slider->rect.width()
- : slider->rect.height()) - len,
- slider->upsideDown);
- if (horizontal)
- ret.setRect(slider->rect.x() + sliderPos, slider->rect.y() + tickOffset, len, thickness);
- else
- ret.setRect(slider->rect.x() + tickOffset, slider->rect.y() + sliderPos, thickness, len);
- break; }
- case SC_SliderGroove:
- if (slider->orientation == Qt::Horizontal)
- ret.setRect(slider->rect.x(), slider->rect.y() + tickOffset,
- slider->rect.width(), thickness);
- else
- ret.setRect(slider->rect.x() + tickOffset, slider->rect.y(),
- thickness, slider->rect.height());
- break;
- default:
- break;
- }
- ret = visualRect(slider->direction, slider->rect, ret);
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- const QRect scrollBarRect = scrollbar->rect;
- int sbextent = proxy()->pixelMetric(PM_ScrollBarExtent, scrollbar, widget);
- int maxlen = ((scrollbar->orientation == Qt::Horizontal) ?
- scrollBarRect.width() : scrollBarRect.height()) - (sbextent * 2);
- int sliderlen;
-
- // calculate slider length
- if (scrollbar->maximum != scrollbar->minimum) {
- uint range = scrollbar->maximum - scrollbar->minimum;
- sliderlen = (qint64(scrollbar->pageStep) * maxlen) / (range + scrollbar->pageStep);
-
- int slidermin = proxy()->pixelMetric(PM_ScrollBarSliderMin, scrollbar, widget);
- if (sliderlen < slidermin || range > INT_MAX / 2)
- sliderlen = slidermin;
- if (sliderlen > maxlen)
- sliderlen = maxlen;
- } else {
- sliderlen = maxlen;
- }
-
- int sliderstart = sbextent + sliderPositionFromValue(scrollbar->minimum,
- scrollbar->maximum,
- scrollbar->sliderPosition,
- maxlen - sliderlen,
- scrollbar->upsideDown);
-
- switch (sc) {
- case SC_ScrollBarSubLine: // top/left button
- if (scrollbar->orientation == Qt::Horizontal) {
- int buttonWidth = qMin(scrollBarRect.width() / 2, sbextent);
- ret.setRect(0, 0, buttonWidth, scrollBarRect.height());
- } else {
- int buttonHeight = qMin(scrollBarRect.height() / 2, sbextent);
- ret.setRect(0, 0, scrollBarRect.width(), buttonHeight);
- }
- break;
- case SC_ScrollBarAddLine: // bottom/right button
- if (scrollbar->orientation == Qt::Horizontal) {
- int buttonWidth = qMin(scrollBarRect.width()/2, sbextent);
- ret.setRect(scrollBarRect.width() - buttonWidth, 0, buttonWidth, scrollBarRect.height());
- } else {
- int buttonHeight = qMin(scrollBarRect.height()/2, sbextent);
- ret.setRect(0, scrollBarRect.height() - buttonHeight, scrollBarRect.width(), buttonHeight);
- }
- break;
- case SC_ScrollBarSubPage: // between top/left button and slider
- if (scrollbar->orientation == Qt::Horizontal)
- ret.setRect(sbextent, 0, sliderstart - sbextent, scrollBarRect.height());
- else
- ret.setRect(0, sbextent, scrollBarRect.width(), sliderstart - sbextent);
- break;
- case SC_ScrollBarAddPage: // between bottom/right button and slider
- if (scrollbar->orientation == Qt::Horizontal)
- ret.setRect(sliderstart + sliderlen, 0,
- maxlen - sliderstart - sliderlen + sbextent, scrollBarRect.height());
- else
- ret.setRect(0, sliderstart + sliderlen, scrollBarRect.width(),
- maxlen - sliderstart - sliderlen + sbextent);
- break;
- case SC_ScrollBarGroove:
- if (scrollbar->orientation == Qt::Horizontal)
- ret.setRect(sbextent, 0, scrollBarRect.width() - sbextent * 2,
- scrollBarRect.height());
- else
- ret.setRect(0, sbextent, scrollBarRect.width(),
- scrollBarRect.height() - sbextent * 2);
- break;
- case SC_ScrollBarSlider:
- if (scrollbar->orientation == Qt::Horizontal)
- ret.setRect(sliderstart, 0, sliderlen, scrollBarRect.height());
- else
- ret.setRect(0, sliderstart, scrollBarRect.width(), sliderlen);
- break;
- default:
- break;
- }
- ret = visualRect(scrollbar->direction, scrollBarRect, ret);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QSize bs;
- int fw = spinbox->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
- bs.setHeight(qMax(8, spinbox->rect.height()/2 - fw));
- // 1.6 -approximate golden mean
- bs.setWidth(qMax(16, qMin(bs.height() * 8 / 5, spinbox->rect.width() / 4)));
- bs = bs.expandedTo(QApplication::globalStrut());
- int y = fw + spinbox->rect.y();
- int x, lx, rx;
- x = spinbox->rect.x() + spinbox->rect.width() - fw - bs.width();
- lx = fw;
- rx = x - fw;
- switch (sc) {
- case SC_SpinBoxUp:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- ret = QRect(x, y, bs.width(), bs.height());
- break;
- case SC_SpinBoxDown:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
-
- ret = QRect(x, y + bs.height(), bs.width(), bs.height());
- break;
- case SC_SpinBoxEditField:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons) {
- ret = QRect(lx, fw, spinbox->rect.width() - 2*fw, spinbox->rect.height() - 2*fw);
- } else {
- ret = QRect(lx, fw, rx, spinbox->rect.height() - 2*fw);
- }
- break;
- case SC_SpinBoxFrame:
- ret = spinbox->rect;
- default:
- break;
- }
- ret = visualRect(spinbox->direction, spinbox->rect, ret);
- }
- break;
-#endif // Qt_NO_SPINBOX
-#ifndef QT_NO_TOOLBUTTON
- case CC_ToolButton:
- if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, tb, widget);
- ret = tb->rect;
- switch (sc) {
- case SC_ToolButton:
- if ((tb->features
- & (QStyleOptionToolButton::MenuButtonPopup | QStyleOptionToolButton::PopupDelay))
- == QStyleOptionToolButton::MenuButtonPopup)
- ret.adjust(0, 0, -mbi, 0);
- break;
- case SC_ToolButtonMenu:
- if ((tb->features
- & (QStyleOptionToolButton::MenuButtonPopup | QStyleOptionToolButton::PopupDelay))
- == QStyleOptionToolButton::MenuButtonPopup)
- ret.adjust(ret.width() - mbi, 0, 0, 0);
- break;
- default:
- break;
- }
- ret = visualRect(tb->direction, tb->rect, ret);
- }
- break;
-#endif // QT_NO_TOOLBUTTON
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- int x = cb->rect.x(),
- y = cb->rect.y(),
- wi = cb->rect.width(),
- he = cb->rect.height();
- int xpos = x;
- int margin = cb->frame ? 3 : 0;
- int bmarg = cb->frame ? 2 : 0;
- xpos += wi - bmarg - 16;
-
-
- switch (sc) {
- case SC_ComboBoxFrame:
- ret = cb->rect;
- break;
- case SC_ComboBoxArrow:
- ret.setRect(xpos, y + bmarg, 16, he - 2*bmarg);
- break;
- case SC_ComboBoxEditField:
- ret.setRect(x + margin, y + margin, wi - 2 * margin - 16, he - 2 * margin);
- break;
- case SC_ComboBoxListBoxPopup:
- ret = cb->rect;
- break;
- default:
- break;
- }
- ret = visualRect(cb->direction, cb->rect, ret);
- }
- break;
-#endif // QT_NO_COMBOBOX
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- const int controlMargin = 2;
- const int controlHeight = tb->rect.height() - controlMargin *2;
- const int delta = controlHeight + controlMargin;
- int offset = 0;
-
- bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
-
- switch (sc) {
- case SC_TitleBarLabel:
- if (tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)) {
- ret = tb->rect;
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- ret.adjust(delta, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowMinimizeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowMaximizeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowShadeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- ret.adjust(0, 0, -delta, 0);
- }
- break;
- case SC_TitleBarContextHelpButton:
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- offset += delta;
- case SC_TitleBarMinButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarMinButton)
- break;
- case SC_TitleBarNormalButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarNormalButton)
- break;
- case SC_TitleBarMaxButton:
- if (!isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarMaxButton)
- break;
- case SC_TitleBarShadeButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarShadeButton)
- break;
- case SC_TitleBarUnshadeButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarUnshadeButton)
- break;
- case SC_TitleBarCloseButton:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- offset += delta;
- else if (sc == SC_TitleBarCloseButton)
- break;
- ret.setRect(tb->rect.right() - offset, tb->rect.top() + controlMargin,
- controlHeight, controlHeight);
- break;
- case SC_TitleBarSysMenu:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- ret.setRect(tb->rect.left() + controlMargin, tb->rect.top() + controlMargin,
- controlHeight, controlHeight);
- }
- break;
- default:
- break;
- }
- ret = visualRect(tb->direction, tb->rect, ret);
- }
- break;
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox: {
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- switch (sc) {
- case SC_GroupBoxFrame:
- // FALL THROUGH
- case SC_GroupBoxContents: {
- int topMargin = 0;
- int topHeight = 0;
- int verticalAlignment = proxy()->styleHint(SH_GroupBox_TextLabelVerticalAlignment, groupBox, widget);
- if (groupBox->text.size() || (groupBox->subControls & QStyle::SC_GroupBoxCheckBox)) {
- topHeight = groupBox->fontMetrics.height();
- if (verticalAlignment & Qt::AlignVCenter)
- topMargin = topHeight / 2;
- else if (verticalAlignment & Qt::AlignTop)
- topMargin = topHeight;
- }
-
- QRect frameRect = groupBox->rect;
- frameRect.setTop(topMargin);
-
- if (sc == SC_GroupBoxFrame) {
- ret = frameRect;
- break;
- }
-
- int frameWidth = 0;
- if (!(widget && widget->inherits("Q3GroupBox"))
- && ((groupBox->features & QStyleOptionFrameV2::Flat) == 0)) {
- frameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth, groupBox, widget);
- }
- ret = frameRect.adjusted(frameWidth, frameWidth + topHeight - topMargin,
- -frameWidth, -frameWidth);
- break;
- }
- case SC_GroupBoxCheckBox:
- // FALL THROUGH
- case SC_GroupBoxLabel: {
- QFontMetrics fontMetrics = groupBox->fontMetrics;
- int h = fontMetrics.height();
- int tw = fontMetrics.size(Qt::TextShowMnemonic, groupBox->text + QLatin1Char(' ')).width();
- int marg = (groupBox->features & QStyleOptionFrameV2::Flat) ? 0 : 8;
- ret = groupBox->rect.adjusted(marg, 0, -marg, 0);
- ret.setHeight(h);
-
- int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, opt, widget);
- int indicatorSpace = proxy()->pixelMetric(PM_CheckBoxLabelSpacing, opt, widget) - 1;
- bool hasCheckBox = groupBox->subControls & QStyle::SC_GroupBoxCheckBox;
- int checkBoxSize = hasCheckBox ? (indicatorWidth + indicatorSpace) : 0;
-
- // Adjusted rect for label + indicatorWidth + indicatorSpace
- QRect totalRect = alignedRect(groupBox->direction, groupBox->textAlignment,
- QSize(tw + checkBoxSize, h), ret);
-
- // Adjust totalRect if checkbox is set
- if (hasCheckBox) {
- bool ltr = groupBox->direction == Qt::LeftToRight;
- int left = 0;
- // Adjust for check box
- if (sc == SC_GroupBoxCheckBox) {
- int indicatorHeight = proxy()->pixelMetric(PM_IndicatorHeight, opt, widget);
- left = ltr ? totalRect.left() : (totalRect.right() - indicatorWidth);
- int top = totalRect.top() + (fontMetrics.height() - indicatorHeight) / 2;
- totalRect.setRect(left, top, indicatorWidth, indicatorHeight);
- // Adjust for label
- } else {
- left = ltr ? (totalRect.left() + checkBoxSize - 2) : totalRect.left();
- totalRect.setRect(left, totalRect.top(),
- totalRect.width() - checkBoxSize, totalRect.height());
- }
- }
- ret = totalRect;
- break;
- }
- default:
- break;
- }
- }
- break;
- }
-#endif // QT_NO_GROUPBOX
-#ifndef QT_NO_WORKSPACE
- case CC_MdiControls:
- {
- int numSubControls = 0;
- if (opt->subControls & SC_MdiCloseButton)
- ++numSubControls;
- if (opt->subControls & SC_MdiMinButton)
- ++numSubControls;
- if (opt->subControls & SC_MdiNormalButton)
- ++numSubControls;
- if (numSubControls == 0)
- break;
-
- int buttonWidth = opt->rect.width()/ numSubControls - 1;
- int offset = 0;
- switch (sc) {
- case SC_MdiCloseButton:
- // Only one sub control, no offset needed.
- if (numSubControls == 1)
- break;
- offset += buttonWidth + 2;
- //FALL THROUGH
- case SC_MdiNormalButton:
- // No offset needed if
- // 1) There's only one sub control
- // 2) We have a close button and a normal button (offset already added in SC_MdiClose)
- if (numSubControls == 1 || (numSubControls == 2 && !(opt->subControls & SC_MdiMinButton)))
- break;
- if (opt->subControls & SC_MdiNormalButton)
- offset += buttonWidth;
- break;
- default:
- break;
- }
-
- // Subtract one pixel if we only have one sub control. At this point
- // buttonWidth is the actual width + 1 pixel margin, but we don't want the
- // margin when there are no other controllers.
- if (numSubControls == 1)
- --buttonWidth;
- ret = QRect(offset, 0, buttonWidth, opt->rect.height());
- break;
- }
-#endif // QT_NO_WORKSPACE
- default:
- qWarning("QCommonStyle::subControlRect: Case %d not handled", cc);
- }
- return ret;
-}
-
-/*! \reimp */
-int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWidget *widget) const
-{
- int ret;
-
- switch (m) {
- case PM_FocusFrameVMargin:
- case PM_FocusFrameHMargin:
- ret = 2;
- break;
- case PM_MenuBarVMargin:
- case PM_MenuBarHMargin:
- ret = 0;
- break;
- case PM_DialogButtonsSeparator:
- ret = int(QStyleHelper::dpiScaled(5.));
- break;
- case PM_DialogButtonsButtonWidth:
- ret = int(QStyleHelper::dpiScaled(70.));
- break;
- case PM_DialogButtonsButtonHeight:
- ret = int(QStyleHelper::dpiScaled(30.));
- break;
- case PM_CheckListControllerSize:
- case PM_CheckListButtonSize:
- ret = int(QStyleHelper::dpiScaled(16.));
- break;
- case PM_TitleBarHeight: {
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- if ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool) {
- ret = qMax(widget ? widget->fontMetrics().height() : opt->fontMetrics.height(), 16);
-#ifndef QT_NO_DOCKWIDGET
- } else if (qobject_cast<const QDockWidget*>(widget)) {
- ret = qMax(widget->fontMetrics().height(), int(QStyleHelper::dpiScaled(13)));
-#endif
- } else {
- ret = qMax(widget ? widget->fontMetrics().height() : opt->fontMetrics.height(), 18);
- }
- } else {
- ret = int(QStyleHelper::dpiScaled(18.));
- }
-
- break; }
- case PM_ScrollBarSliderMin:
- ret = int(QStyleHelper::dpiScaled(9.));
- break;
-
- case PM_ButtonMargin:
- ret = int(QStyleHelper::dpiScaled(6.));
- break;
-
- case PM_DockWidgetTitleBarButtonMargin:
- ret = int(QStyleHelper::dpiScaled(2.));
- break;
-
- case PM_ButtonDefaultIndicator:
- ret = 0;
- break;
-
- case PM_MenuButtonIndicator:
- ret = int(QStyleHelper::dpiScaled(12.));
- break;
-
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
-
- case PM_DefaultFrameWidth:
- ret = 2;
- break;
-
- case PM_ComboBoxFrameWidth:
- case PM_SpinBoxFrameWidth:
- case PM_MenuPanelWidth:
- case PM_TabBarBaseOverlap:
- case PM_TabBarBaseHeight:
- ret = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- break;
-
- case PM_MdiSubWindowFrameWidth:
- ret = int(QStyleHelper::dpiScaled(4.));
- break;
-
- case PM_MdiSubWindowMinimizedWidth:
- ret = int(QStyleHelper::dpiScaled(196.));
- break;
-
-#ifndef QT_NO_SCROLLBAR
- case PM_ScrollBarExtent:
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int s = sb->orientation == Qt::Horizontal ?
- QApplication::globalStrut().height()
- : QApplication::globalStrut().width();
- ret = qMax(16, s);
- } else {
- ret = int(QStyleHelper::dpiScaled(16.));
- }
- break;
-#endif
- case PM_MaximumDragDistance:
- ret = -1;
- break;
-
-#ifndef QT_NO_SLIDER
- case PM_SliderThickness:
- ret = int(QStyleHelper::dpiScaled(16.));
- break;
-
- case PM_SliderTickmarkOffset:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int space = (sl->orientation == Qt::Horizontal) ? sl->rect.height()
- : sl->rect.width();
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, sl, widget);
- int ticks = sl->tickPosition;
-
- if (ticks == QSlider::TicksBothSides)
- ret = (space - thickness) / 2;
- else if (ticks == QSlider::TicksAbove)
- ret = space - thickness;
- else
- ret = 0;
- } else {
- ret = 0;
- }
- break;
-
- case PM_SliderSpaceAvailable:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- if (sl->orientation == Qt::Horizontal)
- ret = sl->rect.width() - proxy()->pixelMetric(PM_SliderLength, sl, widget);
- else
- ret = sl->rect.height() - proxy()->pixelMetric(PM_SliderLength, sl, widget);
- } else {
- ret = 0;
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_DOCKWIDGET
- case PM_DockWidgetSeparatorExtent:
- ret = int(QStyleHelper::dpiScaled(6.));
- break;
-
- case PM_DockWidgetHandleExtent:
- ret = int(QStyleHelper::dpiScaled(8.));
- break;
- case PM_DockWidgetTitleMargin:
- ret = 0;
- break;
- case PM_DockWidgetFrameWidth:
- ret = 1;
- break;
-#endif // QT_NO_DOCKWIDGET
-
- case PM_SpinBoxSliderHeight:
- case PM_MenuBarPanelWidth:
- ret = 2;
- break;
-
- case PM_MenuBarItemSpacing:
- ret = 0;
- break;
-
-#ifndef QT_NO_TOOLBAR
- case PM_ToolBarFrameWidth:
- ret = 1;
- break;
-
- case PM_ToolBarItemMargin:
- ret = 0;
- break;
-
- case PM_ToolBarItemSpacing:
- ret = int(QStyleHelper::dpiScaled(4.));
- break;
-
- case PM_ToolBarHandleExtent:
- ret = int(QStyleHelper::dpiScaled(8.));
- break;
-
- case PM_ToolBarSeparatorExtent:
- ret = int(QStyleHelper::dpiScaled(6.));
- break;
-
- case PM_ToolBarExtensionExtent:
- ret = int(QStyleHelper::dpiScaled(12.));
- break;
-#endif // QT_NO_TOOLBAR
-
-#ifndef QT_NO_TABBAR
- case PM_TabBarTabOverlap:
- ret = 3;
- break;
-
- case PM_TabBarTabHSpace:
- ret = int(QStyleHelper::dpiScaled(24.));
- break;
-
- case PM_TabBarTabShiftHorizontal:
- ret = 0;
- break;
-
- case PM_TabBarTabShiftVertical:
- ret = 2;
- break;
-
- case PM_TabBarTabVSpace: {
- const QStyleOptionTab *tb = qstyleoption_cast<const QStyleOptionTab *>(opt);
- if (tb && (tb->shape == QTabBar::RoundedNorth || tb->shape == QTabBar::RoundedSouth
- || tb->shape == QTabBar::RoundedWest || tb->shape == QTabBar::RoundedEast))
- ret = 8;
- else
- if(tb && (tb->shape == QTabBar::TriangularWest || tb->shape == QTabBar::TriangularEast))
- ret = 3;
- else
- ret = 2;
- break; }
-#endif
-
- case PM_ProgressBarChunkWidth:
- ret = 9;
- break;
-
- case PM_IndicatorWidth:
- ret = int(QStyleHelper::dpiScaled(13.));
- break;
-
- case PM_IndicatorHeight:
- ret = int(QStyleHelper::dpiScaled(13.));
- break;
-
- case PM_ExclusiveIndicatorWidth:
- ret = int(QStyleHelper::dpiScaled(12.));
- break;
-
- case PM_ExclusiveIndicatorHeight:
- ret = int(QStyleHelper::dpiScaled(12.));
- break;
-
- case PM_MenuTearoffHeight:
- ret = int(QStyleHelper::dpiScaled(10.));
- break;
-
- case PM_MenuScrollerHeight:
- ret = int(QStyleHelper::dpiScaled(10.));
- break;
-
- case PM_MenuDesktopFrameWidth:
- case PM_MenuHMargin:
- case PM_MenuVMargin:
- ret = 0;
- break;
-
- case PM_HeaderMargin:
- ret = int(QStyleHelper::dpiScaled(4.));
- break;
- case PM_HeaderMarkSize:
- ret = int(QStyleHelper::dpiScaled(32.));
- break;
- case PM_HeaderGripMargin:
- ret = int(QStyleHelper::dpiScaled(4.));
- break;
- case PM_TabBarScrollButtonWidth:
- ret = int(QStyleHelper::dpiScaled(16.));
- break;
- case PM_LayoutLeftMargin:
- case PM_LayoutTopMargin:
- case PM_LayoutRightMargin:
- case PM_LayoutBottomMargin:
- {
- bool isWindow = false;
- if (opt) {
- isWindow = (opt->state & State_Window);
- } else if (widget) {
- isWindow = widget->isWindow();
- }
- ret = proxy()->pixelMetric(isWindow ? PM_DefaultTopLevelMargin : PM_DefaultChildMargin);
- }
- break;
- case PM_LayoutHorizontalSpacing:
- case PM_LayoutVerticalSpacing:
- ret = proxy()->pixelMetric(PM_DefaultLayoutSpacing);
- break;
-
- case PM_DefaultTopLevelMargin:
- ret = int(QStyleHelper::dpiScaled(11.));
- break;
- case PM_DefaultChildMargin:
- ret = int(QStyleHelper::dpiScaled(9.));
- break;
- case PM_DefaultLayoutSpacing:
- ret = int(QStyleHelper::dpiScaled(6.));
- break;
-
- case PM_ToolBarIconSize:
- ret = qt_guiPlatformPlugin()->platformHint(QGuiPlatformPlugin::PH_ToolBarIconSize);
- if (!ret)
- ret = int(QStyleHelper::dpiScaled(24.));
- break;
-
- case PM_TabBarIconSize:
- case PM_ListViewIconSize:
- ret = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
- break;
-
- case PM_ButtonIconSize:
- case PM_SmallIconSize:
- ret = int(QStyleHelper::dpiScaled(16.));
- break;
- case PM_IconViewIconSize:
- ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget);
- break;
-
- case PM_LargeIconSize:
- ret = int(QStyleHelper::dpiScaled(32.));
- break;
-
- case PM_ToolTipLabelFrameWidth:
- ret = 1;
- break;
- case PM_CheckBoxLabelSpacing:
- case PM_RadioButtonLabelSpacing:
- ret = int(QStyleHelper::dpiScaled(6.));
- break;
- case PM_SizeGripSize:
- ret = int(QStyleHelper::dpiScaled(13.));
- break;
- case PM_MessageBoxIconSize:
-#ifdef Q_WS_MAC
- if (QApplication::desktopSettingsAware()) {
- ret = 64; // No DPI scaling, it's handled elsewhere.
- } else
-#endif
- {
- ret = int(QStyleHelper::dpiScaled(32.));
- }
- break;
- case PM_TextCursorWidth:
- ret = 1;
- break;
- case PM_TabBar_ScrollButtonOverlap:
- ret = 1;
- break;
- case PM_TabCloseIndicatorWidth:
- case PM_TabCloseIndicatorHeight:
- ret = int(QStyleHelper::dpiScaled(16.));
- break;
- case PM_ScrollView_ScrollBarSpacing:
- ret = 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- break;
- case PM_SubMenuOverlap:
- ret = -proxy()->pixelMetric(QStyle::PM_MenuPanelWidth, opt, widget);
- break;
- default:
- ret = 0;
- break;
- }
-
- return ret;
-}
-
-/*!
- \reimp
-*/
-QSize QCommonStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &csz, const QWidget *widget) const
-{
- Q_D(const QCommonStyle);
- QSize sz(csz);
- switch (ct) {
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- int w = csz.width(),
- h = csz.height(),
- bm = proxy()->pixelMetric(PM_ButtonMargin, btn, widget),
- fw = proxy()->pixelMetric(PM_DefaultFrameWidth, btn, widget) * 2;
- w += bm + fw;
- h += bm + fw;
- if (btn->features & QStyleOptionButton::AutoDefaultButton){
- int dbw = proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget) * 2;
- w += dbw;
- h += dbw;
- }
- sz = QSize(w, h);
- }
- break;
- case CT_RadioButton:
- case CT_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- bool isRadio = (ct == CT_RadioButton);
-
- int w = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorWidth
- : PM_IndicatorWidth, btn, widget);
- int h = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
- : PM_IndicatorHeight, btn, widget);
-
- int margins = 0;
- // we add 4 pixels for label margins
- if (!btn->icon.isNull() || !btn->text.isEmpty())
- margins = 4 + proxy()->pixelMetric(isRadio ? PM_RadioButtonLabelSpacing
- : PM_CheckBoxLabelSpacing, opt, widget);
- sz += QSize(w + margins, 4);
- sz.setHeight(qMax(sz.height(), h));
- }
- break;
-#ifndef QT_NO_MENU
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- bool checkable = mi->menuHasCheckableItems;
- int maxpmw = mi->maxIconWidth;
- int w = sz.width(), h = sz.height();
- if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
- w = 10;
- h = 2;
- } else {
- h = mi->fontMetrics.height() + 8;
- if (!mi->icon.isNull()) {
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
- h = qMax(h, mi->icon.actualSize(QSize(iconExtent, iconExtent)).height() + 4);
- }
- }
- if (mi->text.contains(QLatin1Char('\t')))
- w += 12;
- if (maxpmw > 0)
- w += maxpmw + 6;
- if (checkable && maxpmw < 20)
- w += 20 - maxpmw;
- if (checkable || maxpmw > 0)
- w += 2;
- w += 12;
- sz = QSize(w, h);
- }
- break;
-#endif // QT_NO_MENU
-#ifndef QT_NO_TOOLBUTTON
- case CT_ToolButton:
- sz = QSize(sz.width() + 6, sz.height() + 5);
- break;
-#endif // QT_NO_TOOLBUTTON
-#ifndef QT_NO_COMBOBOX
- case CT_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- int fw = cmb->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth, opt, widget) * 2 : 0;
- const int textMargins = 2*(proxy()->pixelMetric(PM_FocusFrameHMargin) + 1);
- // QItemDelegate::sizeHint expands the textMargins two times, thus the 2*textMargins...
- int other = qMax(23, 2*textMargins + proxy()->pixelMetric(QStyle::PM_ScrollBarExtent, opt, widget));
- sz = QSize(sz.width() + fw + other, sz.height() + fw);
- }
- break;
-#endif // QT_NO_COMBOBOX
- case CT_HeaderSection:
- if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- bool nullIcon = hdr->icon.isNull();
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, hdr, widget);
- int iconSize = nullIcon ? 0 : proxy()->pixelMetric(QStyle::PM_SmallIconSize, hdr, widget);
- QSize txt = hdr->fontMetrics.size(0, hdr->text);
- sz.setHeight(margin + qMax(iconSize, txt.height()) + margin);
- sz.setWidth((nullIcon ? 0 : margin) + iconSize
- + (hdr->text.isNull() ? 0 : margin) + txt.width() + margin);
- }
- break;
- case CT_TabWidget:
- sz += QSize(4, 4);
- break;
- case CT_LineEdit:
- if (const QStyleOptionFrame *f = qstyleoption_cast<const QStyleOptionFrame *>(opt))
- sz += QSize(2*f->lineWidth, 2*f->lineWidth);
- break;
-#ifndef QT_NO_GROUPBOX
- case CT_GroupBox:
- if (const QGroupBox *grb = static_cast<const QGroupBox *>(widget))
- sz += QSize(!grb->isFlat() ? 16 : 0, 0);
- break;
-#endif // QT_NO_GROUPBOX
- case CT_MdiControls:
- if (const QStyleOptionComplex *styleOpt = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
- int width = 1;
- if (styleOpt->subControls & SC_MdiMinButton)
- width += 16 + 1;
- if (styleOpt->subControls & SC_MdiNormalButton)
- width += 16 + 1;
- if (styleOpt->subControls & SC_MdiCloseButton)
- width += 16 + 1;
- sz = QSize(width, 16);
- } else {
- sz = QSize(52, 16);
- }
- break;
-#ifndef QT_NO_ITEMVIEWS
- case CT_ItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- QRect decorationRect, displayRect, checkRect;
- d->viewItemLayout(vopt, &checkRect, &decorationRect, &displayRect, true);
- sz = (decorationRect|displayRect|checkRect).size();
- }
- break;
-#endif // QT_NO_ITEMVIEWS
- case CT_ScrollBar:
- case CT_MenuBar:
- case CT_Menu:
- case CT_MenuBarItem:
- case CT_Q3Header:
- case CT_Slider:
- case CT_ProgressBar:
- case CT_TabBarTab:
- // just return the contentsSize for now
- // fall through intended
- default:
- break;
- }
- return sz;
-}
-
-
-/*! \reimp */
-int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *widget,
- QStyleHintReturn *hret) const
-{
- int ret = 0;
-
- switch (sh) {
- case SH_Menu_KeyboardSearch:
- ret = false;
- break;
- case SH_Slider_AbsoluteSetButtons:
- ret = Qt::MidButton;
- break;
- case SH_Slider_PageSetButtons:
- ret = Qt::LeftButton;
- break;
- case SH_ScrollBar_ContextMenu:
- ret = true;
- break;
- case SH_DialogButtons_DefaultButton: // This value not used anywhere.
- ret = QDialogButtonBox::AcceptRole;
- break;
-#ifndef QT_NO_GROUPBOX
- case SH_GroupBox_TextLabelVerticalAlignment:
- ret = Qt::AlignVCenter;
- break;
-
- case SH_GroupBox_TextLabelColor:
- ret = opt ? int(opt->palette.color(QPalette::Text).rgba()) : 0;
- break;
-#endif // QT_NO_GROUPBOX
-
- case SH_Q3ListViewExpand_SelectMouseType:
- case SH_TabBar_SelectMouseType:
- ret = QEvent::MouseButtonPress;
- break;
-
-#ifdef QT3_SUPPORT
- case SH_GUIStyle:
- ret = Qt::WindowsStyle;
- break;
-#endif
-
- case SH_TabBar_Alignment:
- case SH_Header_ArrowAlignment:
- ret = Qt::AlignLeft;
- break;
-
- case SH_TitleBar_AutoRaise:
- ret = false;
- break;
-
- case SH_Menu_SubMenuPopupDelay:
- ret = 256;
- break;
-
- case SH_ProgressDialog_TextLabelAlignment:
- ret = Qt::AlignCenter;
- break;
-
- case SH_BlinkCursorWhenTextSelected:
- ret = 1;
- break;
-
- case SH_Table_GridLineColor:
- if (opt)
- ret = opt->palette.color(QPalette::Mid).rgb();
- else
- ret = -1;
- break;
- case SH_LineEdit_PasswordCharacter: {
- const QFontMetrics &fm = opt ? opt->fontMetrics
- : (widget ? widget->fontMetrics() : QFontMetrics(QFont()));
- ret = 0;
- if (fm.inFont(QChar(0x25CF))) {
- ret = 0x25CF;
- } else if (fm.inFont(QChar(0x2022))) {
- ret = 0x2022;
- } else {
- ret = '*';
- }
- break;
- }
-
-
- case SH_ToolBox_SelectedPageTitleBold:
- ret = 1;
- break;
-
- case SH_UnderlineShortcut:
- ret = 1;
- break;
-
- case SH_SpinBox_ClickAutoRepeatRate:
- ret = 150;
- break;
-
- case SH_SpinBox_ClickAutoRepeatThreshold:
- ret = 500;
- break;
-
- case SH_SpinBox_KeyPressAutoRepeatRate:
- ret = 75;
- break;
-
- case SH_Menu_SelectionWrap:
- ret = true;
- break;
-
- case SH_Menu_FillScreenWithScroll:
- ret = true;
- break;
-
- case SH_ToolTipLabel_Opacity:
- ret = 255;
- break;
-
- case SH_Button_FocusPolicy:
- ret = Qt::StrongFocus;
- break;
-
- case SH_MenuBar_DismissOnSecondClick:
- ret = 1;
- break;
-
- case SH_MessageBox_UseBorderForButtonSpacing:
- ret = 0;
- break;
-
- case SH_ToolButton_PopupDelay:
- ret = 600;
- break;
-
- case SH_FocusFrame_Mask:
- ret = 1;
- if (widget) {
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
- mask->region = widget->rect();
- int vmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameVMargin),
- hmargin = proxy()->pixelMetric(QStyle::PM_FocusFrameHMargin);
- mask->region -= QRect(widget->rect().adjusted(hmargin, vmargin, -hmargin, -vmargin));
- }
- }
- break;
-#ifndef QT_NO_RUBBERBAND
- case SH_RubberBand_Mask:
- if (const QStyleOptionRubberBand *rbOpt = qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
- ret = 0;
- if (rbOpt->shape == QRubberBand::Rectangle) {
- ret = true;
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
- mask->region = opt->rect;
- int margin = proxy()->pixelMetric(PM_DefaultFrameWidth) * 2;
- mask->region -= opt->rect.adjusted(margin, margin, -margin, -margin);
- }
- }
- }
- break;
-#endif // QT_NO_RUBBERBAND
- case SH_SpinControls_DisableOnBounds:
- ret = 1;
- break;
-
- case SH_Dial_BackgroundRole:
- ret = QPalette::Window;
- break;
-
- case SH_ComboBox_LayoutDirection:
- ret = opt ? opt->direction : Qt::LeftToRight;
- break;
-
- case SH_ItemView_EllipsisLocation:
- ret = Qt::AlignTrailing;
- break;
-
- case SH_ItemView_ShowDecorationSelected:
- ret = false;
- break;
-
- case SH_ItemView_ActivateItemOnSingleClick:
- ret = qt_guiPlatformPlugin()->platformHint(QGuiPlatformPlugin::PH_ItemView_ActivateItemOnSingleClick);
- break;
-
- case SH_TitleBar_ModifyNotification:
- ret = true;
- break;
- case SH_ScrollBar_RollBetweenButtons:
- ret = false;
- break;
- case SH_TabBar_ElideMode:
- ret = Qt::ElideNone;
- break;
- case SH_DialogButtonLayout:
- ret = QDialogButtonBox::WinLayout;
-#ifdef Q_WS_X11
- if (X11->desktopEnvironment == DE_KDE)
- ret = QDialogButtonBox::KdeLayout;
- else if (X11->desktopEnvironment == DE_GNOME)
- ret = QDialogButtonBox::GnomeLayout;
-#endif
- break;
- case SH_ComboBox_PopupFrameStyle:
- ret = QFrame::StyledPanel | QFrame::Plain;
- break;
- case SH_MessageBox_TextInteractionFlags:
- ret = Qt::LinksAccessibleByMouse;
- break;
- case SH_DialogButtonBox_ButtonsHaveIcons:
-#ifdef Q_WS_X11
- return true;
-#endif
- ret = 0;
- break;
- case SH_SpellCheckUnderlineStyle:
- ret = QTextCharFormat::WaveUnderline;
- break;
- case SH_MessageBox_CenterButtons:
- ret = true;
- break;
- case SH_ItemView_MovementWithoutUpdatingSelection:
- ret = true;
- break;
- case SH_FocusFrame_AboveWidget:
- ret = false;
- break;
-#ifndef QT_NO_TABWIDGET
- case SH_TabWidget_DefaultTabPosition:
- ret = QTabWidget::North;
- break;
-#endif
- case SH_ToolBar_Movable:
- ret = true;
- break;
- case SH_TextControl_FocusIndicatorTextCharFormat:
- ret = true;
- if (QStyleHintReturnVariant *vret = qstyleoption_cast<QStyleHintReturnVariant*>(hret)) {
- QPen outline(opt->palette.color(QPalette::Text), 1, Qt::DotLine);
- QTextCharFormat fmt;
- fmt.setProperty(QTextFormat::OutlinePen, outline);
- vret->variant = fmt;
- }
- break;
-#ifndef QT_NO_WIZARD
- case SH_WizardStyle:
- ret = QWizard::ClassicStyle;
- break;
-#endif
- case SH_FormLayoutWrapPolicy:
- ret = QFormLayout::DontWrapRows;
- break;
- case SH_FormLayoutFieldGrowthPolicy:
- ret = QFormLayout::AllNonFixedFieldsGrow;
- break;
- case SH_FormLayoutFormAlignment:
- ret = Qt::AlignLeft | Qt::AlignTop;
- break;
- case SH_FormLayoutLabelAlignment:
- ret = Qt::AlignLeft;
- break;
- case SH_ItemView_ArrowKeysNavigateIntoChildren:
- ret = false;
- break;
- case SH_ItemView_DrawDelegateFrame:
- ret = 0;
- break;
-#ifndef QT_NO_TABBAR
- case SH_TabBar_CloseButtonPosition:
- ret = QTabBar::RightSide;
- break;
-#endif
- case SH_DockWidget_ButtonsHaveFrame:
- ret = true;
- break;
- case SH_ToolButtonStyle:
- ret = qt_guiPlatformPlugin()->platformHint(QGuiPlatformPlugin::PH_ToolButtonStyle);
- break;
- case SH_RequestSoftwareInputPanel:
- ret = RSIP_OnMouseClickAndAlreadyFocused;
- break;
- default:
- ret = 0;
- break;
- }
-
- return ret;
-}
-
-/*! \reimp */
-QPixmap QCommonStyle::standardPixmap(StandardPixmap sp, const QStyleOption *option,
- const QWidget *widget) const
-{
- const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QApplication::isRightToLeft());
-#ifdef QT_NO_IMAGEFORMAT_PNG
- Q_UNUSED(widget);
- Q_UNUSED(sp);
-#else
- QPixmap pixmap;
-
- if (QApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
- switch (sp) {
- case SP_DialogYesButton:
- case SP_DialogOkButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-ok")).pixmap(16);
- break;
- case SP_DialogApplyButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-ok-apply")).pixmap(16);
- break;
- case SP_DialogDiscardButton:
- pixmap = QIcon::fromTheme(QLatin1String("edit-delete")).pixmap(16);
- break;
- case SP_DialogCloseButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-close")).pixmap(16);
- break;
- case SP_DirHomeIcon:
- pixmap = QIcon::fromTheme(QLatin1String("user-home")).pixmap(16);
- break;
- case SP_MessageBoxInformation:
- pixmap = QIcon::fromTheme(QLatin1String("messagebox_info")).pixmap(16);
- break;
- case SP_MessageBoxWarning:
- pixmap = QIcon::fromTheme(QLatin1String("messagebox_warning")).pixmap(16);
- break;
- case SP_MessageBoxCritical:
- pixmap = QIcon::fromTheme(QLatin1String("messagebox_critical")).pixmap(16);
- break;
- case SP_MessageBoxQuestion:
- pixmap = QIcon::fromTheme(QLatin1String("help")).pixmap(16);
- break;
- case SP_DialogOpenButton:
- case SP_DirOpenIcon:
- pixmap = QIcon::fromTheme(QLatin1String("folder-open")).pixmap(16);
- break;
- case SP_FileIcon:
- pixmap = QIcon::fromTheme(QLatin1String("text-x-generic"),
- QIcon::fromTheme(QLatin1String("empty"))).pixmap(16);
- break;
- case SP_DirClosedIcon:
- case SP_DirIcon:
- pixmap = QIcon::fromTheme(QLatin1String("folder")).pixmap(16);
- break;
- case SP_DriveFDIcon:
- pixmap = QIcon::fromTheme(QLatin1String("media-floppy"),
- QIcon::fromTheme(QLatin1String("3floppy_unmount"))).pixmap(16);
- break;
- case SP_ComputerIcon:
- pixmap = QIcon::fromTheme(QLatin1String("computer"),
- QIcon::fromTheme(QLatin1String("system"))).pixmap(16);
- break;
- case SP_DesktopIcon:
- pixmap = QIcon::fromTheme(QLatin1String("user-desktop"),
- QIcon::fromTheme(QLatin1String("desktop"))).pixmap(16);
- break;
- case SP_TrashIcon:
- pixmap = QIcon::fromTheme(QLatin1String("user-trash"),
- QIcon::fromTheme(QLatin1String("trashcan_empty"))).pixmap(16);
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- pixmap = QIcon::fromTheme(QLatin1String("media-optical"),
- QIcon::fromTheme(QLatin1String("cdrom_unmount"))).pixmap(16);
- break;
- case SP_DriveHDIcon:
- pixmap = QIcon::fromTheme(QLatin1String("drive-harddisk"),
- QIcon::fromTheme(QLatin1String("hdd_unmount"))).pixmap(16);
- break;
- case SP_FileDialogToParent:
- pixmap = QIcon::fromTheme(QLatin1String("go-up"),
- QIcon::fromTheme(QLatin1String("up"))).pixmap(16);
- break;
- case SP_FileDialogNewFolder:
- pixmap = QIcon::fromTheme(QLatin1String("folder_new")).pixmap(16);
- break;
- case SP_ArrowUp:
- pixmap = QIcon::fromTheme(QLatin1String("go-up"),
- QIcon::fromTheme(QLatin1String("up"))).pixmap(16);
- break;
- case SP_ArrowDown:
- pixmap = QIcon::fromTheme(QLatin1String("go-down"),
- QIcon::fromTheme(QLatin1String("down"))).pixmap(16);
- break;
- case SP_ArrowRight:
- pixmap = QIcon::fromTheme(QLatin1String("go-next"),
- QIcon::fromTheme(QLatin1String("forward"))).pixmap(16);
- break;
- case SP_ArrowLeft:
- pixmap = QIcon::fromTheme(QLatin1String("go-previous"),
- QIcon::fromTheme(QLatin1String("back"))).pixmap(16);
- break;
- case SP_FileDialogDetailedView:
- pixmap = QIcon::fromTheme(QLatin1String("view_detailed")).pixmap(16);
- break;
- case SP_FileDialogListView:
- pixmap = QIcon::fromTheme(QLatin1String("view_icon")).pixmap(16);
- break;
- case SP_BrowserReload:
- pixmap = QIcon::fromTheme(QLatin1String("reload")).pixmap(16);
- break;
- case SP_BrowserStop:
- pixmap = QIcon::fromTheme(QLatin1String("process-stop")).pixmap(16);
- break;
- case SP_MediaPlay:
- pixmap = QIcon::fromTheme(QLatin1String("media-playback-start")).pixmap(16);
- break;
- case SP_MediaPause:
- pixmap = QIcon::fromTheme(QLatin1String("media-playback-pause")).pixmap(16);
- break;
- case SP_MediaStop:
- pixmap = QIcon::fromTheme(QLatin1String("media-playback-stop")).pixmap(16);
- break;
- case SP_MediaSeekForward:
- pixmap = QIcon::fromTheme(QLatin1String("media-seek-forward")).pixmap(16);
- break;
- case SP_MediaSeekBackward:
- pixmap = QIcon::fromTheme(QLatin1String("media-seek-backward")).pixmap(16);
- break;
- case SP_MediaSkipForward:
- pixmap = QIcon::fromTheme(QLatin1String("media-skip-backward")).pixmap(16);
- break;
- case SP_MediaSkipBackward:
- pixmap = QIcon::fromTheme(QLatin1String("media-skip-backward")).pixmap(16);
- break;
- case SP_DialogResetButton:
- pixmap = QIcon::fromTheme(QLatin1String("edit-clear")).pixmap(24);
- break;
- case SP_DialogHelpButton:
- pixmap = QIcon::fromTheme(QLatin1String("help-contents")).pixmap(24);
- break;
- case SP_DialogNoButton:
- case SP_DialogCancelButton:
- pixmap = QIcon::fromTheme(QLatin1String("dialog-cancel"),
- QIcon::fromTheme(QLatin1String("process-stop"))).pixmap(24);
- break;
- case SP_DialogSaveButton:
- pixmap = QIcon::fromTheme(QLatin1String("document-save")).pixmap(24);
- break;
- case SP_FileLinkIcon:
- pixmap = QIcon::fromTheme(QLatin1String("emblem-symbolic-link")).pixmap(16);
- if (!pixmap.isNull()) {
- QPixmap fileIcon = QIcon::fromTheme(QLatin1String("text-x-generic")).pixmap(16);
- if (fileIcon.isNull())
- fileIcon = QIcon::fromTheme(QLatin1String("empty")).pixmap(16);
- if (!fileIcon.isNull()) {
- QPainter painter(&fileIcon);
- painter.drawPixmap(0, 0, 16, 16, pixmap);
- return fileIcon;
- }
- }
- break;
- case SP_DirLinkIcon:
- pixmap = QIcon::fromTheme(QLatin1String("emblem-symbolic-link")).pixmap(16);
- if (!pixmap.isNull()) {
- QPixmap dirIcon = QIcon::fromTheme(QLatin1String("folder")).pixmap(16);
- if (!dirIcon.isNull()) {
- QPainter painter(&dirIcon);
- painter.drawPixmap(0, 0, 16, 16, pixmap);
- return dirIcon;
- }
- }
- break;
- default:
- break;
- }
- }
-
- if (!pixmap.isNull())
- return pixmap;
-#endif //QT_NO_IMAGEFORMAT_PNG
- switch (sp) {
-#ifndef QT_NO_IMAGEFORMAT_XPM
- case SP_ToolBarHorizontalExtensionButton:
- if (rtl) {
- QImage im(tb_extension_arrow_h_xpm);
- im = im.convertToFormat(QImage::Format_ARGB32).mirrored(true, false);
- return QPixmap::fromImage(im);
- }
- return QPixmap(tb_extension_arrow_h_xpm);
- case SP_ToolBarVerticalExtensionButton:
- return QPixmap(tb_extension_arrow_v_xpm);
- case SP_FileDialogStart:
- return QPixmap(filedialog_start_xpm);
- case SP_FileDialogEnd:
- return QPixmap(filedialog_end_xpm);
-#endif
-#ifndef QT_NO_IMAGEFORMAT_PNG
- case SP_CommandLink:
- case SP_ArrowForward:
- if (rtl)
- return proxy()->standardPixmap(SP_ArrowLeft, option, widget);
- return proxy()->standardPixmap(SP_ArrowRight, option, widget);
- case SP_ArrowBack:
- if (rtl)
- return proxy()->standardPixmap(SP_ArrowRight, option, widget);
- return proxy()->standardPixmap(SP_ArrowLeft, option, widget);
- case SP_ArrowLeft:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/left-16.png"));
- case SP_ArrowRight:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/right-16.png"));
- case SP_ArrowUp:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/up-16.png"));
- case SP_ArrowDown:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/down-16.png"));
- case SP_FileDialogToParent:
- return proxy()->standardPixmap(SP_ArrowUp, option, widget);
- case SP_FileDialogNewFolder:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-16.png"));
- case SP_FileDialogDetailedView:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-16.png"));
- case SP_FileDialogInfoView:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-16.png"));
- case SP_FileDialogContentsView:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-16.png"));
- case SP_FileDialogListView:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-16.png"));
- case SP_FileDialogBack:
- return proxy()->standardPixmap(SP_ArrowBack, option, widget);
- case SP_DriveHDIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/harddrive-16.png"));
- case SP_TrashIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/trash-16.png"));
- case SP_DriveFDIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/floppy-16.png"));
- case SP_DriveNetIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/networkdrive-16.png"));
- case SP_DesktopIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/desktop-16.png"));
- case SP_ComputerIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/computer-16.png"));
- case SP_DriveCDIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-16.png"));
- case SP_DriveDVDIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-16.png"));
- case SP_DirHomeIcon:
- case SP_DirOpenIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/diropen-16.png"));
- case SP_DirIcon:
- case SP_DirClosedIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/dirclosed-16.png"));
- case SP_DirLinkIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/dirlink-16.png"));
- case SP_FileIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/file-16.png"));
- case SP_FileLinkIcon:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-16.png"));
- case SP_DialogOkButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-16.png"));
- case SP_DialogCancelButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-16.png"));
- case SP_DialogHelpButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-16.png"));
- case SP_DialogOpenButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-16.png"));
- case SP_DialogSaveButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-16.png"));
- case SP_DialogCloseButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-16.png"));
- case SP_DialogApplyButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-16.png"));
- case SP_DialogResetButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-16.png"));
- case SP_DialogDiscardButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-16.png"));
- case SP_DialogYesButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-16.png"));
- case SP_DialogNoButton:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-16.png"));
- case SP_BrowserReload:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-24.png"));
- case SP_BrowserStop:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/stop-24.png"));
- case SP_MediaPlay:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-32.png"));
- case SP_MediaPause:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-32.png"));
- case SP_MediaStop:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-32.png"));
- case SP_MediaSeekForward:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-32.png"));
- case SP_MediaSeekBackward:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-32.png"));
- case SP_MediaSkipForward:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-32.png"));
- case SP_MediaSkipBackward:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-32.png"));
- case SP_MediaVolume:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-16.png"));
- case SP_MediaVolumeMuted:
- return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-muted-16.png"));
-#endif // QT_NO_IMAGEFORMAT_PNG
- default:
- break;
- }
- return QPixmap();
-}
-
-/*!
- \internal
-*/
-QIcon QCommonStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
-{
- QIcon icon;
- const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QApplication::isRightToLeft());
- if (QApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
- switch (standardIcon) {
- case SP_DirHomeIcon:
- icon = QIcon::fromTheme(QLatin1String("user-home"));
- break;
- case SP_MessageBoxInformation:
- icon = QIcon::fromTheme(QLatin1String("dialog-information"));
- break;
- case SP_MessageBoxWarning:
- icon = QIcon::fromTheme(QLatin1String("dialog-warning"));
- break;
- case SP_MessageBoxCritical:
- icon = QIcon::fromTheme(QLatin1String("dialog-error"));
- break;
- case SP_MessageBoxQuestion:
- icon = QIcon::fromTheme(QLatin1String("dialog-question"));
- break;
- case SP_DialogOpenButton:
- case SP_DirOpenIcon:
- icon = QIcon::fromTheme(QLatin1String("folder-open"));
- break;
- case SP_DialogSaveButton:
- icon = QIcon::fromTheme(QLatin1String("document-save"));
- break;
- case SP_DialogApplyButton:
- icon = QIcon::fromTheme(QLatin1String("dialog-ok-apply"));
- break;
- case SP_DialogYesButton:
- case SP_DialogOkButton:
- icon = QIcon::fromTheme(QLatin1String("dialog-ok"));
- break;
- case SP_DialogDiscardButton:
- icon = QIcon::fromTheme(QLatin1String("edit-delete"));
- break;
- case SP_DialogResetButton:
- icon = QIcon::fromTheme(QLatin1String("edit-clear"));
- break;
- case SP_DialogHelpButton:
- icon = QIcon::fromTheme(QLatin1String("help-contents"));
- break;
- case SP_FileIcon:
- icon = QIcon::fromTheme(QLatin1String("text-x-generic"));
- break;
- case SP_DirClosedIcon:
- case SP_DirIcon:
- icon = QIcon::fromTheme(QLatin1String("folder"));
- break;
- case SP_DriveFDIcon:
- icon = QIcon::fromTheme(QLatin1String("floppy_unmount"));
- break;
- case SP_ComputerIcon:
- icon = QIcon::fromTheme(QLatin1String("computer"),
- QIcon::fromTheme(QLatin1String("system")));
- break;
- case SP_DesktopIcon:
- icon = QIcon::fromTheme(QLatin1String("user-desktop"));
- break;
- case SP_TrashIcon:
- icon = QIcon::fromTheme(QLatin1String("user-trash"));
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- icon = QIcon::fromTheme(QLatin1String("media-optical"));
- break;
- case SP_DriveHDIcon:
- icon = QIcon::fromTheme(QLatin1String("drive-harddisk"));
- break;
- case SP_FileDialogToParent:
- icon = QIcon::fromTheme(QLatin1String("go-up"));
- break;
- case SP_FileDialogNewFolder:
- icon = QIcon::fromTheme(QLatin1String("folder-new"));
- break;
- case SP_ArrowUp:
- icon = QIcon::fromTheme(QLatin1String("go-up"));
- break;
- case SP_ArrowDown:
- icon = QIcon::fromTheme(QLatin1String("go-down"));
- break;
- case SP_ArrowRight:
- icon = QIcon::fromTheme(QLatin1String("go-next"));
- break;
- case SP_ArrowLeft:
- icon = QIcon::fromTheme(QLatin1String("go-previous"));
- break;
- case SP_DialogCancelButton:
- icon = QIcon::fromTheme(QLatin1String("dialog-cancel"),
- QIcon::fromTheme(QLatin1String("process-stop")));
- break;
- case SP_DialogCloseButton:
- icon = QIcon::fromTheme(QLatin1String("window-close"));
- break;
- case SP_FileDialogDetailedView:
- icon = QIcon::fromTheme(QLatin1String("view-list-details"));
- break;
- case SP_FileDialogListView:
- icon = QIcon::fromTheme(QLatin1String("view-list-icons"));
- break;
- case SP_BrowserReload:
- icon = QIcon::fromTheme(QLatin1String("view-refresh"));
- break;
- case SP_BrowserStop:
- icon = QIcon::fromTheme(QLatin1String("process-stop"));
- break;
- case SP_MediaPlay:
- icon = QIcon::fromTheme(QLatin1String("media-playback-start"));
- break;
- case SP_MediaPause:
- icon = QIcon::fromTheme(QLatin1String("media-playback-pause"));
- break;
- case SP_MediaStop:
- icon = QIcon::fromTheme(QLatin1String("media-playback-stop"));
- break;
- case SP_MediaSeekForward:
- icon = QIcon::fromTheme(QLatin1String("media-seek-forward"));
- break;
- case SP_MediaSeekBackward:
- icon = QIcon::fromTheme(QLatin1String("media-seek-backward"));
- break;
- case SP_MediaSkipForward:
- icon = QIcon::fromTheme(QLatin1String("media-skip-forward"));
- break;
- case SP_MediaSkipBackward:
- icon = QIcon::fromTheme(QLatin1String("media-skip-backward"));
- break;
- case SP_MediaVolume:
- icon = QIcon::fromTheme(QLatin1String("audio-volume-medium"));
- break;
- case SP_MediaVolumeMuted:
- icon = QIcon::fromTheme(QLatin1String("audio-volume-muted"));
- break;
- case SP_ArrowForward:
- if (rtl)
- return standardIconImplementation(SP_ArrowLeft, option, widget);
- return standardIconImplementation(SP_ArrowRight, option, widget);
- case SP_ArrowBack:
- if (rtl)
- return standardIconImplementation(SP_ArrowRight, option, widget);
- return standardIconImplementation(SP_ArrowLeft, option, widget);
- case SP_FileLinkIcon:
- {
- QIcon linkIcon = QIcon::fromTheme(QLatin1String("emblem-symbolic-link"));
- if (!linkIcon.isNull()) {
- QIcon baseIcon = standardIconImplementation(SP_FileIcon, option, widget);
- const QList<QSize> sizes = baseIcon.availableSizes(QIcon::Normal, QIcon::Off);
- for (int i = 0 ; i < sizes.size() ; ++i) {
- int size = sizes[i].width();
- QPixmap basePixmap = baseIcon.pixmap(size);
- QPixmap linkPixmap = linkIcon.pixmap(size/2);
- QPainter painter(&basePixmap);
- painter.drawPixmap(size/2, size/2, linkPixmap);
- icon.addPixmap(basePixmap);
- }
- }
- }
- break;
- case SP_DirLinkIcon:
- {
- QIcon linkIcon = QIcon::fromTheme(QLatin1String("emblem-symbolic-link"));
- if (!linkIcon.isNull()) {
- QIcon baseIcon = standardIconImplementation(SP_DirIcon, option, widget);
- const QList<QSize> sizes = baseIcon.availableSizes(QIcon::Normal, QIcon::Off);
- for (int i = 0 ; i < sizes.size() ; ++i) {
- int size = sizes[i].width();
- QPixmap basePixmap = baseIcon.pixmap(size);
- QPixmap linkPixmap = linkIcon.pixmap(size/2);
- QPainter painter(&basePixmap);
- painter.drawPixmap(size/2, size/2, linkPixmap);
- icon.addPixmap(basePixmap);
- }
- }
- }
- break;
- default:
- break;
- }
- } // if (QApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty())
- if (!icon.isNull())
- return icon;
-#if defined(Q_WS_MAC)
- if (QApplication::desktopSettingsAware()) {
- OSType iconType = 0;
- switch (standardIcon) {
- case QStyle::SP_MessageBoxQuestion:
- iconType = kQuestionMarkIcon;
- break;
- case QStyle::SP_MessageBoxInformation:
- iconType = kAlertNoteIcon;
- break;
- case QStyle::SP_MessageBoxWarning:
- iconType = kAlertCautionIcon;
- break;
- case QStyle::SP_MessageBoxCritical:
- iconType = kAlertStopIcon;
- break;
- case SP_DesktopIcon:
- iconType = kDesktopIcon;
- break;
- case SP_TrashIcon:
- iconType = kTrashIcon;
- break;
- case SP_ComputerIcon:
- iconType = kComputerIcon;
- break;
- case SP_DriveFDIcon:
- iconType = kGenericFloppyIcon;
- break;
- case SP_DriveHDIcon:
- iconType = kGenericHardDiskIcon;
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- iconType = kGenericCDROMIcon;
- break;
- case SP_DriveNetIcon:
- iconType = kGenericNetworkIcon;
- break;
- case SP_DirOpenIcon:
- iconType = kOpenFolderIcon;
- break;
- case SP_DirClosedIcon:
- case SP_DirLinkIcon:
- iconType = kGenericFolderIcon;
- break;
- case SP_FileLinkIcon:
- case SP_FileIcon:
- iconType = kGenericDocumentIcon;
- break;
- case SP_DirIcon: {
- // A rather special case
- QIcon closeIcon = QStyle::standardIcon(SP_DirClosedIcon, option, widget);
- QIcon openIcon = QStyle::standardIcon(SP_DirOpenIcon, option, widget);
- closeIcon.addPixmap(openIcon.pixmap(16, 16), QIcon::Normal, QIcon::On);
- closeIcon.addPixmap(openIcon.pixmap(32, 32), QIcon::Normal, QIcon::On);
- closeIcon.addPixmap(openIcon.pixmap(64, 64), QIcon::Normal, QIcon::On);
- closeIcon.addPixmap(openIcon.pixmap(128, 128), QIcon::Normal, QIcon::On);
- return closeIcon;
- }
- case SP_TitleBarNormalButton:
- case SP_TitleBarCloseButton: {
- QIcon titleBarIcon;
- if (standardIcon == SP_TitleBarCloseButton) {
- titleBarIcon.addFile(QLatin1String(":/trolltech/styles/macstyle/images/closedock-16.png"));
- titleBarIcon.addFile(QLatin1String(":/trolltech/styles/macstyle/images/closedock-down-16.png"), QSize(16, 16), QIcon::Normal, QIcon::On);
- } else {
- titleBarIcon.addFile(QLatin1String(":/trolltech/styles/macstyle/images/dockdock-16.png"));
- titleBarIcon.addFile(QLatin1String(":/trolltech/styles/macstyle/images/dockdock-down-16.png"), QSize(16, 16), QIcon::Normal, QIcon::On);
- }
- return titleBarIcon;
- }
- default:
- break;
- }
- if (iconType != 0) {
- QIcon retIcon;
- IconRef icon;
- IconRef overlayIcon = 0;
- if (iconType != kGenericApplicationIcon) {
- GetIconRef(kOnSystemDisk, kSystemIconsCreator, iconType, &icon);
- } else {
- FSRef fsRef;
- ProcessSerialNumber psn = { 0, kCurrentProcess };
- GetProcessBundleLocation(&psn, &fsRef);
- GetIconRefFromFileInfo(&fsRef, 0, 0, 0, 0, kIconServicesNormalUsageFlag, &icon, 0);
- if (standardIcon == SP_MessageBoxCritical) {
- overlayIcon = icon;
- GetIconRef(kOnSystemDisk, kSystemIconsCreator, kAlertCautionIcon, &icon);
- }
- }
- if (icon) {
- qt_mac_constructQIconFromIconRef(icon, overlayIcon, &retIcon, standardIcon);
- ReleaseIconRef(icon);
- }
- if (overlayIcon)
- ReleaseIconRef(overlayIcon);
- return retIcon;
- }
- } // if (QApplication::desktopSettingsAware())
-#endif // Q_WS_MAC
-
- switch (standardIcon) {
-#ifndef QT_NO_IMAGEFORMAT_PNG
- case SP_FileDialogNewFolder:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/newdirectory-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogBack:
- return standardIconImplementation(SP_ArrowBack, option, widget);
- case SP_FileDialogToParent:
- return standardIconImplementation(SP_ArrowUp, option, widget);
- case SP_FileDialogDetailedView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewdetailed-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogInfoView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/fileinfo-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogContentsView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filecontents-128.png"), QSize(128, 128));
- break;
- case SP_FileDialogListView:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/viewlist-128.png"), QSize(128, 128));
- break;
- case SP_DialogOkButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-ok-128.png"), QSize(128, 128));
- break;
- case SP_DialogCancelButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-cancel-128.png"), QSize(128, 128));
- break;
- case SP_DialogHelpButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-help-128.png"), QSize(128, 128));
- break;
- case SP_DialogOpenButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-open-128.png"), QSize(128, 128));
- break;
- case SP_DialogSaveButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-save-128.png"), QSize(128, 128));
- break;
- case SP_DialogCloseButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-close-128.png"), QSize(128, 128));
- break;
- case SP_DialogApplyButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-apply-128.png"), QSize(128, 128));
- break;
- case SP_DialogResetButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-clear-128.png"), QSize(128, 128));
- break;
- case SP_DialogDiscardButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-delete-128.png"), QSize(128, 128));
- break;
- case SP_DialogYesButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-yes-128.png"), QSize(128, 128));
- break;
- case SP_DialogNoButton:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/standardbutton-no-128.png"), QSize(128, 128));
- break;
- case SP_ArrowForward:
- if (rtl)
- return standardIconImplementation(SP_ArrowLeft, option, widget);
- return standardIconImplementation(SP_ArrowRight, option, widget);
- case SP_ArrowBack:
- if (rtl)
- return standardIconImplementation(SP_ArrowRight, option, widget);
- return standardIconImplementation(SP_ArrowLeft, option, widget);
- case SP_ArrowLeft:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/left-128.png"), QSize(128, 128));
- break;
- case SP_ArrowRight:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/right-128.png"), QSize(128, 128));
- break;
- case SP_ArrowUp:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/up-128.png"), QSize(128, 128));
- break;
- case SP_ArrowDown:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/down-128.png"), QSize(128, 128));
- break;
- case SP_DirHomeIcon:
- case SP_DirIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dirclosed-16.png"),
- QSize(), QIcon::Normal, QIcon::Off);
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/diropen-16.png"),
- QSize(), QIcon::Normal, QIcon::On);
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dirclosed-32.png"),
- QSize(32, 32), QIcon::Normal, QIcon::Off);
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/diropen-32.png"),
- QSize(32, 32), QIcon::Normal, QIcon::On);
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dirclosed-128.png"),
- QSize(128, 128), QIcon::Normal, QIcon::Off);
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/diropen-128.png"),
- QSize(128, 128), QIcon::Normal, QIcon::On);
- break;
- case SP_DriveCDIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/cdr-128.png"), QSize(128, 128));
- break;
- case SP_DriveDVDIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/dvd-128.png"), QSize(128, 128));
- break;
- case SP_FileIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/file-128.png"), QSize(128, 128));
- break;
- case SP_FileLinkIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/filelink-128.png"), QSize(128, 128));
- break;
- case SP_TrashIcon:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-32.png"), QSize(32, 32));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/trash-128.png"), QSize(128, 128));
- break;
- case SP_BrowserReload:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-24.png"), QSize(24, 24));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/refresh-32.png"), QSize(32, 32));
- break;
- case SP_BrowserStop:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/stop-24.png"), QSize(24, 24));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/stop-32.png"), QSize(32, 32));
- break;
- case SP_MediaPlay:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-play-32.png"), QSize(32, 32));
- break;
- case SP_MediaPause:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-pause-32.png"), QSize(32, 32));
- break;
- case SP_MediaStop:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-stop-32.png"), QSize(32, 32));
- break;
- case SP_MediaSeekForward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-forward-32.png"), QSize(32, 32));
- break;
- case SP_MediaSeekBackward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-seek-backward-32.png"), QSize(32, 32));
- break;
- case SP_MediaSkipForward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-forward-32.png"), QSize(32, 32));
- break;
- case SP_MediaSkipBackward:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-16.png"), QSize(16, 16));
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-skip-backward-32.png"), QSize(32, 32));
- break;
- case SP_MediaVolume:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-16.png"), QSize(16, 16));
- break;
- case SP_MediaVolumeMuted:
- icon.addFile(QLatin1String(":/trolltech/styles/commonstyle/images/media-volume-muted-16.png"), QSize(16, 16));
- break;
-#endif // QT_NO_IMAGEFORMAT_PNG
- default:
- icon.addPixmap(proxy()->standardPixmap(standardIcon, option, widget));
- break;
- }
- return icon;
-}
-
-static inline uint qt_intensity(uint r, uint g, uint b)
-{
- // 30% red, 59% green, 11% blue
- return (77 * r + 150 * g + 28 * b) / 255;
-}
-
-/*! \reimp */
-QPixmap QCommonStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const
-{
- switch (iconMode) {
- case QIcon::Disabled: {
- QImage im = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
-
- // Create a colortable based on the background (black -> bg -> white)
- QColor bg = opt->palette.color(QPalette::Disabled, QPalette::Window);
- int red = bg.red();
- int green = bg.green();
- int blue = bg.blue();
- uchar reds[256], greens[256], blues[256];
- for (int i=0; i<128; ++i) {
- reds[i] = uchar((red * (i<<1)) >> 8);
- greens[i] = uchar((green * (i<<1)) >> 8);
- blues[i] = uchar((blue * (i<<1)) >> 8);
- }
- for (int i=0; i<128; ++i) {
- reds[i+128] = uchar(qMin(red + (i << 1), 255));
- greens[i+128] = uchar(qMin(green + (i << 1), 255));
- blues[i+128] = uchar(qMin(blue + (i << 1), 255));
- }
-
- int intensity = qt_intensity(red, green, blue);
- const int factor = 191;
-
- // High intensity colors needs dark shifting in the color table, while
- // low intensity colors needs light shifting. This is to increase the
- // percieved contrast.
- if ((red - factor > green && red - factor > blue)
- || (green - factor > red && green - factor > blue)
- || (blue - factor > red && blue - factor > green))
- intensity = qMin(255, intensity + 91);
- else if (intensity <= 128)
- intensity -= 51;
-
- for (int y=0; y<im.height(); ++y) {
- QRgb *scanLine = (QRgb*)im.scanLine(y);
- for (int x=0; x<im.width(); ++x) {
- QRgb pixel = *scanLine;
- // Calculate color table index, taking intensity adjustment
- // and a magic offset into account.
- uint ci = uint(qGray(pixel)/3 + (130 - intensity / 3));
- *scanLine = qRgba(reds[ci], greens[ci], blues[ci], qAlpha(pixel));
- ++scanLine;
- }
- }
-
- return QPixmap::fromImage(im);
- }
- case QIcon::Selected: {
- QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied);
- QColor color = opt->palette.color(QPalette::Normal, QPalette::Highlight);
- color.setAlphaF(qreal(0.3));
- QPainter painter(&img);
- painter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
- painter.fillRect(0, 0, img.width(), img.height(), color);
- painter.end();
- return QPixmap::fromImage(img); }
- case QIcon::Active:
- return pixmap;
- default:
- break;
- }
- return pixmap;
-}
-
-/*!
- \reimp
-*/
-void QCommonStyle::polish(QPalette &pal)
-{
- QStyle::polish(pal);
-}
-
-/*!
- \reimp
- */
-void QCommonStyle::polish(QWidget *widget)
-{
- QStyle::polish(widget);
-}
-
-/*!
- \reimp
- */
-void QCommonStyle::unpolish(QWidget *widget)
-{
- QStyle::unpolish(widget);
-}
-
-/*!
- \reimp
-*/
-void QCommonStyle::polish(QApplication *app)
-{
- QStyle::polish(app);
-}
-
-/*!
- \reimp
- */
-void QCommonStyle::unpolish(QApplication *application)
-{
- Q_D(const QCommonStyle);
- d->tabBarcloseButtonIcon = QIcon();
- QStyle::unpolish(application);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qcommonstyle.h b/src/gui/styles/qcommonstyle.h
deleted file mode 100644
index 2b42367aac..0000000000
--- a/src/gui/styles/qcommonstyle.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMMONSTYLE_H
-#define QCOMMONSTYLE_H
-
-#include <QtGui/qstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-QT_MODULE(Gui)
-
-class QCommonStylePrivate;
-
-class Q_GUI_EXPORT QCommonStyle: public QStyle
-{
- Q_OBJECT
-
-public:
- QCommonStyle();
- ~QCommonStyle();
-
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
- void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const;
- SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *w = 0) const;
- QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const;
-
- int pixelMetric(PixelMetric m, const QStyleOption *opt = 0, const QWidget *widget = 0) const;
-
- int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
- QStyleHintReturn *shret = 0) const;
-
- QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
-
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const;
-
- void polish(QPalette &);
- void polish(QApplication *app);
- void polish(QWidget *widget);
- void unpolish(QWidget *widget);
- void unpolish(QApplication *application);
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
-
-protected:
- QCommonStyle(QCommonStylePrivate &dd);
-
-private:
- Q_DECLARE_PRIVATE(QCommonStyle)
- Q_DISABLE_COPY(QCommonStyle)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOMMONSTYLE_H
diff --git a/src/gui/styles/qcommonstyle_p.h b/src/gui/styles/qcommonstyle_p.h
deleted file mode 100644
index a02bd44259..0000000000
--- a/src/gui/styles/qcommonstyle_p.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMMONSTYLE_P_H
-#define QCOMMONSTYLE_P_H
-
-#include "qcommonstyle.h"
-#include "qstyle_p.h"
-
-#include "qstyleoption.h"
-
-QT_BEGIN_NAMESPACE
-
-//
-// 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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-class QStringList;
-
-// Private class
-class QCommonStylePrivate : public QStylePrivate
-{
- Q_DECLARE_PUBLIC(QCommonStyle)
-public:
- inline QCommonStylePrivate()
-#ifndef QT_NO_ITEMVIEWS
- : cachedOption(0)
-#endif
- { }
-
-#ifndef QT_NO_ITEMVIEWS
- ~QCommonStylePrivate()
- {
- delete cachedOption;
- }
- void viewItemDrawText(QPainter *p, const QStyleOptionViewItemV4 *option, const QRect &rect) const;
- void viewItemLayout(const QStyleOptionViewItemV4 *opt, QRect *checkRect,
- QRect *pixmapRect, QRect *textRect, bool sizehint) const;
- QSize viewItemSize(const QStyleOptionViewItemV4 *option, int role) const;
-
- mutable QRect decorationRect, displayRect, checkRect;
- mutable QStyleOptionViewItemV4 *cachedOption;
- bool isViewItemCached(const QStyleOptionViewItemV4 &option) const {
- return cachedOption && (option.rect == cachedOption->rect
- && option.direction == cachedOption->direction
- && option.state == cachedOption->state
- && option.displayAlignment == cachedOption->displayAlignment
- && option.decorationAlignment == cachedOption->decorationAlignment
- && option.decorationPosition == cachedOption->decorationPosition
- && option.decorationSize == cachedOption->decorationSize
- && option.font == cachedOption->font
- && option.features == cachedOption->features
- && option.widget == cachedOption->widget
- && option.index == cachedOption->index
- && option.icon.isNull() == cachedOption->icon.isNull()
- && option.text == cachedOption->text
- && option.viewItemPosition == cachedOption->viewItemPosition);
- }
-#endif
- mutable QIcon tabBarcloseButtonIcon;
-#ifndef QT_NO_TABBAR
- void tabLayout(const QStyleOptionTabV3 *opt, const QWidget *widget, QRect *textRect, QRect *pixmapRect) const;
-#endif
-};
-
-QT_END_NAMESPACE
-
-#endif //QCOMMONSTYLE_P_H
diff --git a/src/gui/styles/qcommonstylepixmaps_p.h b/src/gui/styles/qcommonstylepixmaps_p.h
deleted file mode 100644
index fb87c0e7a7..0000000000
--- a/src/gui/styles/qcommonstylepixmaps_p.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/****************************************************************************
-**
-** 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 QT_NO_IMAGEFORMAT_XPM
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-static const char * const check_list_controller_xpm[] = {
-"16 16 4 1",
-" c None",
-". c #000000000000",
-"X c #FFFFFFFF0000",
-"o c #C71BC30BC71B",
-" ",
-" ",
-" .......... ",
-" .XXXXXXXX. ",
-" .XXXXXXXX.oo ",
-" .XXXXXXXX.oo ",
-" .XXXXXXXX.oo ",
-" .XXXXXXXX.oo ",
-" .XXXXXXXX.oo ",
-" .XXXXXXXX.oo ",
-" .XXXXXXXX.oo ",
-" ..........oo ",
-" oooooooooo ",
-" oooooooooo ",
-" ",
-" "};
-
-static const char * const tree_branch_open_xpm[] = {
-"9 9 2 1",
-" c None",
-"# c #000000",
-"#########",
-"# #",
-"# ##### #",
-"# ### #",
-"# ### #",
-"# # #",
-"# # #",
-"# #",
-"#########"};
-
-static const char * const tree_branch_closed_xpm[] = {
-"9 9 2 1",
-" c None",
-"# c #000000",
-"#########",
-"# #",
-"# # #",
-"# ### #",
-"# ##### #",
-"# ### #",
-"# # #",
-"# #",
-"#########"};
-
-static const char * const tb_extension_arrow_v_xpm[] = {
- "5 8 3 1",
- " c None",
- ". c #000000",
- "+ c none",
- ".+++.",
- "..+..",
- "+...+",
- "++.++",
- ".+++.",
- "..+..",
- "+...+",
- "++.++"
-};
-
-static const char * const tb_extension_arrow_h_xpm[] = {
- "8 5 3 1",
- " c None",
- ". c #000000",
- "+ c none",
- "..++..++",
- "+..++..+",
- "++..++..",
- "+..++..+",
- "..++..++",
-};
-
-static const char * const filedialog_start_xpm[]={
- "16 15 8 1",
- "a c #cec6bd",
- "# c #000000",
- "e c #ffff00",
- "b c #999999",
- "f c #cccccc",
- "d c #dcdcdc",
- "c c #ffffff",
- ". c None",
- ".....######aaaaa",
- "...bb#cccc##aaaa",
- "..bcc#cccc#d#aaa",
- ".bcef#cccc#dd#aa",
- ".bcfe#cccc#####a",
- ".bcef#ccccccccc#",
- "bbbbbbbbbbbbccc#",
- "bccccccccccbbcc#",
- "bcefefefefee#bc#",
- ".bcefefefefef#c#",
- ".bcfefefefefe#c#",
- "..bcfefefefeeb##",
- "..bbbbbbbbbbbbb#",
- "...#############",
- "................"};
-
-static const char * const filedialog_end_xpm[]={
- "16 15 9 1",
- "d c #a0a0a0",
- "c c #c3c3c3",
- "# c #cec6bd",
- ". c #000000",
- "f c #ffff00",
- "e c #999999",
- "g c #cccccc",
- "b c #ffffff",
- "a c None",
- "......####aaaaaa",
- ".bbbb..###aaaaaa",
- ".bbbb.c.##aaaaaa",
- ".bbbb....ddeeeea",
- ".bbbbbbb.bbbbbe.",
- ".bbbbbbb.bcfgfe.",
- "eeeeeeeeeeeeefe.",
- "ebbbbbbbbbbeege.",
- "ebfgfgfgfgff.ee.",
- "aebfgfgfgfgfg.e.",
- "aebgfgfgfgfgf.e.",
- "aaebgfgfgfgffe..",
- "aaeeeeeeeeeeeee.",
- "aaa.............",
- "aaaaaaaaaaaaaaaa"};
-
-#endif // QT_NO_IMAGEFORMAT_XPM
diff --git a/src/gui/styles/qdrawutil.cpp b/src/gui/styles/qdrawutil.cpp
deleted file mode 100644
index c674da8394..0000000000
--- a/src/gui/styles/qdrawutil.cpp
+++ /dev/null
@@ -1,1053 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdrawutil.h"
-#include "qbitmap.h"
-#include "qpixmapcache.h"
-#include "qpainter.h"
-#include "qpalette.h"
-#include <private/qpaintengineex_p.h>
-#include <qvarlengtharray.h>
-#include <qmath.h>
-#include <private/qhexstring_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \headerfile <qdrawutil.h>
- \title Drawing Utility Functions
-
- \sa QPainter
-*/
-
-/*!
- \fn void qDrawShadeLine(QPainter *painter, int x1, int y1, int x2, int y2,
- const QPalette &palette, bool sunken,
- int lineWidth, int midLineWidth)
- \relates <qdrawutil.h>
-
- Draws a horizontal (\a y1 == \a y2) or vertical (\a x1 == \a x2)
- shaded line using the given \a painter. Note that nothing is
- drawn if \a y1 != \a y2 and \a x1 != \a x2 (i.e. the line is
- neither horizontal nor vertical).
-
- The provided \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors). The given \a lineWidth
- specifies the line width for each of the lines; it is not the
- total line width. The given \a midLineWidth specifies the width of
- a middle line drawn in the QPalette::mid() color.
-
- The line appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to
- make widgets that follow the current GUI style.
-
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded line:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 0
-
- \sa qDrawShadeRect(), qDrawShadePanel(), QStyle
-*/
-
-void qDrawShadeLine(QPainter *p, int x1, int y1, int x2, int y2,
- const QPalette &pal, bool sunken,
- int lineWidth, int midLineWidth)
-{
- if (!(p && lineWidth >= 0 && midLineWidth >= 0)) {
- qWarning("qDrawShadeLine: Invalid parameters");
- return;
- }
- int tlw = lineWidth*2 + midLineWidth; // total line width
- QPen oldPen = p->pen(); // save pen
- if (sunken)
- p->setPen(pal.color(QPalette::Dark));
- else
- p->setPen(pal.light().color());
- QPolygon a;
- int i;
- if (y1 == y2) { // horizontal line
- int y = y1 - tlw/2;
- if (x1 > x2) { // swap x1 and x2
- int t = x1;
- x1 = x2;
- x2 = t;
- }
- x2--;
- for (i=0; i<lineWidth; i++) { // draw top shadow
- a.setPoints(3, x1+i, y+tlw-1-i,
- x1+i, y+i,
- x2-i, y+i);
- p->drawPolyline(a);
- }
- if (midLineWidth > 0) {
- p->setPen(pal.mid().color());
- for (i=0; i<midLineWidth; i++) // draw lines in the middle
- p->drawLine(x1+lineWidth, y+lineWidth+i,
- x2-lineWidth, y+lineWidth+i);
- }
- if (sunken)
- p->setPen(pal.light().color());
- else
- p->setPen(pal.dark().color());
- for (i=0; i<lineWidth; i++) { // draw bottom shadow
- a.setPoints(3, x1+i, y+tlw-i-1,
- x2-i, y+tlw-i-1,
- x2-i, y+i+1);
- p->drawPolyline(a);
- }
- }
- else if (x1 == x2) { // vertical line
- int x = x1 - tlw/2;
- if (y1 > y2) { // swap y1 and y2
- int t = y1;
- y1 = y2;
- y2 = t;
- }
- y2--;
- for (i=0; i<lineWidth; i++) { // draw left shadow
- a.setPoints(3, x+i, y2,
- x+i, y1+i,
- x+tlw-1, y1+i);
- p->drawPolyline(a);
- }
- if (midLineWidth > 0) {
- p->setPen(pal.mid().color());
- for (i=0; i<midLineWidth; i++) // draw lines in the middle
- p->drawLine(x+lineWidth+i, y1+lineWidth, x+lineWidth+i, y2);
- }
- if (sunken)
- p->setPen(pal.light().color());
- else
- p->setPen(pal.dark().color());
- for (i=0; i<lineWidth; i++) { // draw right shadow
- a.setPoints(3, x+lineWidth, y2-i,
- x+tlw-i-1, y2-i,
- x+tlw-i-1, y1+lineWidth);
- p->drawPolyline(a);
- }
- }
- p->setPen(oldPen);
-}
-
-/*!
- \fn void qDrawShadeRect(QPainter *painter, int x, int y, int width, int height,
- const QPalette &palette, bool sunken,
- int lineWidth, int midLineWidth,
- const QBrush *fill)
- \relates <qdrawutil.h>
-
- Draws the shaded rectangle beginning at (\a x, \a y) with the
- given \a width and \a height using the provided \a painter.
-
- The provide \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors. The given \a lineWidth
- specifies the line width for each of the lines; it is not the
- total line width. The \a midLineWidth specifies the width of a
- middle line drawn in the QPalette::mid() color. The rectangle's
- interior is filled with the \a fill brush unless \a fill is 0.
-
- The rectangle appears sunken if \a sunken is true, otherwise
- raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded rectangle:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 1
-
- \sa qDrawShadeLine(), qDrawShadePanel(), qDrawPlainRect(), QStyle
-*/
-
-void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken,
- int lineWidth, int midLineWidth,
- const QBrush *fill)
-{
- if (w == 0 || h == 0)
- return;
- if (! (w > 0 && h > 0 && lineWidth >= 0 && midLineWidth >= 0)) {
- qWarning("qDrawShadeRect: Invalid parameters");
- return;
- }
- QPen oldPen = p->pen();
- if (sunken)
- p->setPen(pal.dark().color());
- else
- p->setPen(pal.light().color());
- int x1=x, y1=y, x2=x+w-1, y2=y+h-1;
-
- if (lineWidth == 1 && midLineWidth == 0) {// standard shade rectangle
- p->drawRect(x1, y1, w-2, h-2);
- if (sunken)
- p->setPen(pal.light().color());
- else
- p->setPen(pal.dark().color());
- QLineF lines[4] = { QLineF(x1+1, y1+1, x2-2, y1+1),
- QLineF(x1+1, y1+2, x1+1, y2-2),
- QLineF(x1, y2, x2, y2),
- QLineF(x2,y1, x2,y2-1) };
- p->drawLines(lines, 4); // draw bottom/right lines
- } else { // more complicated
- int m = lineWidth+midLineWidth;
- int i, j=0, k=m;
- for (i=0; i<lineWidth; i++) { // draw top shadow
- QLineF lines[4] = { QLineF(x1+i, y2-i, x1+i, y1+i),
- QLineF(x1+i, y1+i, x2-i, y1+i),
- QLineF(x1+k, y2-k, x2-k, y2-k),
- QLineF(x2-k, y2-k, x2-k, y1+k) };
- p->drawLines(lines, 4);
- k++;
- }
- p->setPen(pal.mid().color());
- j = lineWidth*2;
- for (i=0; i<midLineWidth; i++) { // draw lines in the middle
- p->drawRect(x1+lineWidth+i, y1+lineWidth+i, w-j-1, h-j-1);
- j += 2;
- }
- if (sunken)
- p->setPen(pal.light().color());
- else
- p->setPen(pal.dark().color());
- k = m;
- for (i=0; i<lineWidth; i++) { // draw bottom shadow
- QLineF lines[4] = { QLineF(x1+1+i, y2-i, x2-i, y2-i),
- QLineF(x2-i, y2-i, x2-i, y1+i+1),
- QLineF(x1+k, y2-k, x1+k, y1+k),
- QLineF(x1+k, y1+k, x2-k, y1+k) };
- p->drawLines(lines, 4);
- k++;
- }
- }
- if (fill) {
- QBrush oldBrush = p->brush();
- int tlw = lineWidth + midLineWidth;
- p->setPen(Qt::NoPen);
- p->setBrush(*fill);
- p->drawRect(x+tlw, y+tlw, w-2*tlw, h-2*tlw);
- p->setBrush(oldBrush);
- }
- p->setPen(oldPen); // restore pen
-}
-
-
-/*!
- \fn void qDrawShadePanel(QPainter *painter, int x, int y, int width, int height,
- const QPalette &palette, bool sunken,
- int lineWidth, const QBrush *fill)
- \relates <qdrawutil.h>
-
- Draws the shaded panel beginning at (\a x, \a y) with the given \a
- width and \a height using the provided \a painter and the given \a
- lineWidth.
-
- The given \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors). The panel's interior is filled
- with the \a fill brush unless \a fill is 0.
-
- The panel appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded panel:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 2
-
- \sa qDrawWinPanel(), qDrawShadeLine(), qDrawShadeRect(), QStyle
-*/
-
-void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken,
- int lineWidth, const QBrush *fill)
-{
- if (w == 0 || h == 0)
- return;
- if (!(w > 0 && h > 0 && lineWidth >= 0)) {
- qWarning("qDrawShadePanel: Invalid parameters");
- }
- QColor shade = pal.dark().color();
- QColor light = pal.light().color();
- if (fill) {
- if (fill->color() == shade)
- shade = pal.shadow().color();
- if (fill->color() == light)
- light = pal.midlight().color();
- }
- QPen oldPen = p->pen(); // save pen
- QVector<QLineF> lines;
- lines.reserve(2*lineWidth);
-
- if (sunken)
- p->setPen(shade);
- else
- p->setPen(light);
- int x1, y1, x2, y2;
- int i;
- x1 = x;
- y1 = y2 = y;
- x2 = x+w-2;
- for (i=0; i<lineWidth; i++) { // top shadow
- lines << QLineF(x1, y1++, x2--, y2++);
- }
- x2 = x1;
- y1 = y+h-2;
- for (i=0; i<lineWidth; i++) { // left shado
- lines << QLineF(x1++, y1, x2++, y2--);
- }
- p->drawLines(lines);
- lines.clear();
- if (sunken)
- p->setPen(light);
- else
- p->setPen(shade);
- x1 = x;
- y1 = y2 = y+h-1;
- x2 = x+w-1;
- for (i=0; i<lineWidth; i++) { // bottom shadow
- lines << QLineF(x1++, y1--, x2, y2--);
- }
- x1 = x2;
- y1 = y;
- y2 = y+h-lineWidth-1;
- for (i=0; i<lineWidth; i++) { // right shadow
- lines << QLineF(x1--, y1++, x2--, y2);
- }
- p->drawLines(lines);
- if (fill) // fill with fill color
- p->fillRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2, *fill);
- p->setPen(oldPen); // restore pen
-}
-
-
-/*!
- \internal
- This function draws a rectangle with two pixel line width.
- It is called from qDrawWinButton() and qDrawWinPanel().
-
- c1..c4 and fill are used:
-
- 1 1 1 1 1 2
- 1 3 3 3 4 2
- 1 3 F F 4 2
- 1 3 F F 4 2
- 1 4 4 4 4 2
- 2 2 2 2 2 2
-*/
-
-static void qDrawWinShades(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill)
-{
- if (w < 2 || h < 2) // can't do anything with that
- return;
- QPen oldPen = p->pen();
- QPoint a[3] = { QPoint(x, y+h-2), QPoint(x, y), QPoint(x+w-2, y) };
- p->setPen(c1);
- p->drawPolyline(a, 3);
- QPoint b[3] = { QPoint(x, y+h-1), QPoint(x+w-1, y+h-1), QPoint(x+w-1, y) };
- p->setPen(c2);
- p->drawPolyline(b, 3);
- if (w > 4 && h > 4) {
- QPoint c[3] = { QPoint(x+1, y+h-3), QPoint(x+1, y+1), QPoint(x+w-3, y+1) };
- p->setPen(c3);
- p->drawPolyline(c, 3);
- QPoint d[3] = { QPoint(x+1, y+h-2), QPoint(x+w-2, y+h-2), QPoint(x+w-2, y+1) };
- p->setPen(c4);
- p->drawPolyline(d, 3);
- if (fill)
- p->fillRect(QRect(x+2, y+2, w-4, h-4), *fill);
- }
- p->setPen(oldPen);
-}
-
-
-/*!
- \fn void qDrawWinButton(QPainter *painter, int x, int y, int width, int height,
- const QPalette &palette, bool sunken,
- const QBrush *fill)
- \relates <qdrawutil.h>
-
- Draws the Windows-style button specified by the given point (\a x,
- \a y}, \a width and \a height using the provided \a painter with a
- line width of 2 pixels. The button's interior is filled with the
- \a{fill} brush unless \a fill is 0.
-
- The given \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors).
-
- The button appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style()-> Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- \sa qDrawWinPanel(), QStyle
-*/
-
-void qDrawWinButton(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken,
- const QBrush *fill)
-{
- if (sunken)
- qDrawWinShades(p, x, y, w, h,
- pal.shadow().color(), pal.light().color(), pal.dark().color(),
- pal.button().color(), fill);
- else
- qDrawWinShades(p, x, y, w, h,
- pal.light().color(), pal.shadow().color(), pal.button().color(),
- pal.dark().color(), fill);
-}
-
-/*!
- \fn void qDrawWinPanel(QPainter *painter, int x, int y, int width, int height,
- const QPalette &palette, bool sunken,
- const QBrush *fill)
- \relates <qdrawutil.h>
-
- Draws the Windows-style panel specified by the given point(\a x,
- \a y), \a width and \a height using the provided \a painter with a
- line width of 2 pixels. The button's interior is filled with the
- \a fill brush unless \a fill is 0.
-
- The given \a palette specifies the shading colors. The panel
- appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded panel:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 3
-
- \sa qDrawShadePanel(), qDrawWinButton(), QStyle
-*/
-
-void qDrawWinPanel(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken,
- const QBrush *fill)
-{
- if (sunken)
- qDrawWinShades(p, x, y, w, h,
- pal.dark().color(), pal.light().color(), pal.shadow().color(),
- pal.midlight().color(), fill);
- else
- qDrawWinShades(p, x, y, w, h,
- pal.light().color(), pal.shadow().color(), pal.midlight().color(),
- pal.dark().color(), fill);
-}
-
-/*!
- \fn void qDrawPlainRect(QPainter *painter, int x, int y, int width, int height, const QColor &lineColor,
- int lineWidth, const QBrush *fill)
- \relates <qdrawutil.h>
-
- Draws the plain rectangle beginning at (\a x, \a y) with the given
- \a width and \a height, using the specified \a painter, \a lineColor
- and \a lineWidth. The rectangle's interior is filled with the \a
- fill brush unless \a fill is 0.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a plain rectangle:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 4
-
- \sa qDrawShadeRect(), QStyle
-*/
-
-void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &c,
- int lineWidth, const QBrush *fill)
-{
- if (w == 0 || h == 0)
- return;
- if (!(w > 0 && h > 0 && lineWidth >= 0)) {
- qWarning("qDrawPlainRect: Invalid parameters");
- }
- QPen oldPen = p->pen();
- QBrush oldBrush = p->brush();
- p->setPen(c);
- p->setBrush(Qt::NoBrush);
- for (int i=0; i<lineWidth; i++)
- p->drawRect(x+i, y+i, w-i*2 - 1, h-i*2 - 1);
- if (fill) { // fill with fill color
- p->setPen(Qt::NoPen);
- p->setBrush(*fill);
- p->drawRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2);
- }
- p->setPen(oldPen);
- p->setBrush(oldBrush);
-}
-
-/*****************************************************************************
- Overloaded functions.
- *****************************************************************************/
-
-/*!
- \fn void qDrawShadeLine(QPainter *painter, const QPoint &p1, const QPoint &p2,
- const QPalette &palette, bool sunken, int lineWidth, int midLineWidth)
- \relates <qdrawutil.h>
- \overload
-
- Draws a horizontal or vertical shaded line between \a p1 and \a p2
- using the given \a painter. Note that nothing is drawn if the line
- between the points would be neither horizontal nor vertical.
-
- The provided \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors). The given \a lineWidth
- specifies the line width for each of the lines; it is not the
- total line width. The given \a midLineWidth specifies the width of
- a middle line drawn in the QPalette::mid() color.
-
- The line appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to
- make widgets that follow the current GUI style.
-
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded line:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 5
-
- \sa qDrawShadeRect(), qDrawShadePanel(), QStyle
-*/
-
-void qDrawShadeLine(QPainter *p, const QPoint &p1, const QPoint &p2,
- const QPalette &pal, bool sunken,
- int lineWidth, int midLineWidth)
-{
- qDrawShadeLine(p, p1.x(), p1.y(), p2.x(), p2.y(), pal, sunken,
- lineWidth, midLineWidth);
-}
-
-/*!
- \fn void qDrawShadeRect(QPainter *painter, const QRect &rect, const QPalette &palette,
- bool sunken, int lineWidth, int midLineWidth, const QBrush *fill)
- \relates <qdrawutil.h>
- \overload
-
- Draws the shaded rectangle specified by \a rect using the given \a painter.
-
- The provide \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors. The given \a lineWidth
- specifies the line width for each of the lines; it is not the
- total line width. The \a midLineWidth specifies the width of a
- middle line drawn in the QPalette::mid() color. The rectangle's
- interior is filled with the \a fill brush unless \a fill is 0.
-
- The rectangle appears sunken if \a sunken is true, otherwise
- raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded rectangle:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 6
-
- \sa qDrawShadeLine(), qDrawShadePanel(), qDrawPlainRect(), QStyle
-*/
-
-void qDrawShadeRect(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken,
- int lineWidth, int midLineWidth,
- const QBrush *fill)
-{
- qDrawShadeRect(p, r.x(), r.y(), r.width(), r.height(), pal, sunken,
- lineWidth, midLineWidth, fill);
-}
-
-/*!
- \fn void qDrawShadePanel(QPainter *painter, const QRect &rect, const QPalette &palette,
- bool sunken, int lineWidth, const QBrush *fill)
- \relates <qdrawutil.h>
- \overload
-
- Draws the shaded panel at the rectangle specified by \a rect using the
- given \a painter and the given \a lineWidth.
-
- The given \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors). The panel's interior is filled
- with the \a fill brush unless \a fill is 0.
-
- The panel appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded panel:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 7
-
- \sa qDrawWinPanel(), qDrawShadeLine(), qDrawShadeRect(), QStyle
-*/
-
-void qDrawShadePanel(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken,
- int lineWidth, const QBrush *fill)
-{
- qDrawShadePanel(p, r.x(), r.y(), r.width(), r.height(), pal, sunken,
- lineWidth, fill);
-}
-
-/*!
- \fn void qDrawWinButton(QPainter *painter, const QRect &rect, const QPalette &palette,
- bool sunken, const QBrush *fill)
- \relates <qdrawutil.h>
- \overload
-
- Draws the Windows-style button at the rectangle specified by \a rect using
- the given \a painter with a line width of 2 pixels. The button's interior
- is filled with the \a{fill} brush unless \a fill is 0.
-
- The given \a palette specifies the shading colors (\l
- {QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
- {QPalette::mid()}{middle} colors).
-
- The button appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style()-> Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- \sa qDrawWinPanel(), QStyle
-*/
-
-void qDrawWinButton(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken, const QBrush *fill)
-{
- qDrawWinButton(p, r.x(), r.y(), r.width(), r.height(), pal, sunken, fill);
-}
-
-/*!
- \fn void qDrawWinPanel(QPainter *painter, const QRect &rect, const QPalette &palette,
- bool sunken, const QBrush *fill)
- \overload
-
- Draws the Windows-style panel at the rectangle specified by \a rect using
- the given \a painter with a line width of 2 pixels. The button's interior
- is filled with the \a fill brush unless \a fill is 0.
-
- The given \a palette specifies the shading colors. The panel
- appears sunken if \a sunken is true, otherwise raised.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a shaded panel:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 8
-
- \sa qDrawShadePanel(), qDrawWinButton(), QStyle
-*/
-
-void qDrawWinPanel(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken, const QBrush *fill)
-{
- qDrawWinPanel(p, r.x(), r.y(), r.width(), r.height(), pal, sunken, fill);
-}
-
-/*!
- \fn void qDrawPlainRect(QPainter *painter, const QRect &rect, const QColor &lineColor, int lineWidth, const QBrush *fill)
- \relates <qdrawutil.h>
- \overload
-
- Draws the plain rectangle specified by \a rect using the given \a painter,
- \a lineColor and \a lineWidth. The rectangle's interior is filled with the
- \a fill brush unless \a fill is 0.
-
- \warning This function does not look at QWidget::style() or
- QApplication::style(). Use the drawing functions in QStyle to make
- widgets that follow the current GUI style.
-
- Alternatively you can use a QFrame widget and apply the
- QFrame::setFrameStyle() function to display a plain rectangle:
-
- \snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 9
-
- \sa qDrawShadeRect(), QStyle
-*/
-
-void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &c,
- int lineWidth, const QBrush *fill)
-{
- qDrawPlainRect(p, r.x(), r.y(), r.width(), r.height(), c,
- lineWidth, fill);
-}
-
-
-/*!
- \class QTileRules
- \since 4.6
-
- Holds the rules used to draw a pixmap or image split into nine segments,
- similar to \l{http://www.w3.org/TR/css3-background/}{CSS3 border-images}.
-
- \sa Qt::TileRule, QMargins
-*/
-
-/*! \fn QTileRules::QTileRules(Qt::TileRule horizontalRule, Qt::TileRule verticalRule)
- Constructs a QTileRules with the given \a horizontalRule and
- \a verticalRule.
- */
-
-/*! \fn QTileRules::QTileRules(Qt::TileRule rule)
- Constructs a QTileRules with the given \a rule used for both
- the horizontal rule and the vertical rule.
- */
-
-/*!
- \fn void qDrawBorderPixmap(QPainter *painter, const QRect &target, const QMargins &margins, const QPixmap &pixmap)
- \relates <qdrawutil.h>
- \since 4.6
- \overload
-
- \brief The qDrawBorderPixmap function is for drawing a pixmap into
- the margins of a rectangle.
-
- Draws the given \a pixmap into the given \a target rectangle, using the
- given \a painter. The pixmap will be split into nine segments and drawn
- according to the \a margins structure.
-*/
-
-typedef QVarLengthArray<QPainter::PixmapFragment, 16> QPixmapFragmentsArray;
-
-/*!
- \since 4.6
-
- Draws the indicated \a sourceRect rectangle from the given \a pixmap into
- the given \a targetRect rectangle, using the given \a painter. The pixmap
- will be split into nine segments according to the given \a targetMargins
- and \a sourceMargins structures. Finally, the pixmap will be drawn
- according to the given \a rules.
-
- This function is used to draw a scaled pixmap, similar to
- \l{http://www.w3.org/TR/css3-background/}{CSS3 border-images}
-
- \sa Qt::TileRule, QTileRules, QMargins
-*/
-
-void qDrawBorderPixmap(QPainter *painter, const QRect &targetRect, const QMargins &targetMargins,
- const QPixmap &pixmap, const QRect &sourceRect,const QMargins &sourceMargins,
- const QTileRules &rules, QDrawBorderPixmap::DrawingHints hints)
-{
- QPainter::PixmapFragment d;
- d.opacity = 1.0;
- d.rotation = 0.0;
-
- QPixmapFragmentsArray opaqueData;
- QPixmapFragmentsArray translucentData;
-
- // source center
- const int sourceCenterTop = sourceRect.top() + sourceMargins.top();
- const int sourceCenterLeft = sourceRect.left() + sourceMargins.left();
- const int sourceCenterBottom = sourceRect.bottom() - sourceMargins.bottom() + 1;
- const int sourceCenterRight = sourceRect.right() - sourceMargins.right() + 1;
- const int sourceCenterWidth = sourceCenterRight - sourceCenterLeft;
- const int sourceCenterHeight = sourceCenterBottom - sourceCenterTop;
- // target center
- const int targetCenterTop = targetRect.top() + targetMargins.top();
- const int targetCenterLeft = targetRect.left() + targetMargins.left();
- const int targetCenterBottom = targetRect.bottom() - targetMargins.bottom() + 1;
- const int targetCenterRight = targetRect.right() - targetMargins.right() + 1;
- const int targetCenterWidth = targetCenterRight - targetCenterLeft;
- const int targetCenterHeight = targetCenterBottom - targetCenterTop;
-
- QVarLengthArray<qreal, 16> xTarget; // x-coordinates of target rectangles
- QVarLengthArray<qreal, 16> yTarget; // y-coordinates of target rectangles
-
- int columns = 3;
- int rows = 3;
- if (rules.horizontal != Qt::StretchTile && sourceCenterWidth != 0)
- columns = qMax(3, 2 + qCeil(targetCenterWidth / qreal(sourceCenterWidth)));
- if (rules.vertical != Qt::StretchTile && sourceCenterHeight != 0)
- rows = qMax(3, 2 + qCeil(targetCenterHeight / qreal(sourceCenterHeight)));
-
- xTarget.resize(columns + 1);
- yTarget.resize(rows + 1);
-
- bool oldAA = painter->testRenderHint(QPainter::Antialiasing);
- if (painter->paintEngine()->type() != QPaintEngine::OpenGL
- && painter->paintEngine()->type() != QPaintEngine::OpenGL2
- && oldAA && painter->combinedTransform().type() != QTransform::TxNone) {
- painter->setRenderHint(QPainter::Antialiasing, false);
- }
-
- xTarget[0] = targetRect.left();
- xTarget[1] = targetCenterLeft;
- xTarget[columns - 1] = targetCenterRight;
- xTarget[columns] = targetRect.left() + targetRect.width();
-
- yTarget[0] = targetRect.top();
- yTarget[1] = targetCenterTop;
- yTarget[rows - 1] = targetCenterBottom;
- yTarget[rows] = targetRect.top() + targetRect.height();
-
- qreal dx = targetCenterWidth;
- qreal dy = targetCenterHeight;
-
- switch (rules.horizontal) {
- case Qt::StretchTile:
- dx = targetCenterWidth;
- break;
- case Qt::RepeatTile:
- dx = sourceCenterWidth;
- break;
- case Qt::RoundTile:
- dx = targetCenterWidth / qreal(columns - 2);
- break;
- }
-
- for (int i = 2; i < columns - 1; ++i)
- xTarget[i] = xTarget[i - 1] + dx;
-
- switch (rules.vertical) {
- case Qt::StretchTile:
- dy = targetCenterHeight;
- break;
- case Qt::RepeatTile:
- dy = sourceCenterHeight;
- break;
- case Qt::RoundTile:
- dy = targetCenterHeight / qreal(rows - 2);
- break;
- }
-
- for (int i = 2; i < rows - 1; ++i)
- yTarget[i] = yTarget[i - 1] + dy;
-
- // corners
- if (targetMargins.top() > 0 && targetMargins.left() > 0 && sourceMargins.top() > 0 && sourceMargins.left() > 0) { // top left
- d.x = (0.5 * (xTarget[1] + xTarget[0]));
- d.y = (0.5 * (yTarget[1] + yTarget[0]));
- d.sourceLeft = sourceRect.left();
- d.sourceTop = sourceRect.top();
- d.width = sourceMargins.left();
- d.height = sourceMargins.top();
- d.scaleX = qreal(xTarget[1] - xTarget[0]) / d.width;
- d.scaleY = qreal(yTarget[1] - yTarget[0]) / d.height;
- if (hints & QDrawBorderPixmap::OpaqueTopLeft)
- opaqueData.append(d);
- else
- translucentData.append(d);
- }
- if (targetMargins.top() > 0 && targetMargins.right() > 0 && sourceMargins.top() > 0 && sourceMargins.right() > 0) { // top right
- d.x = (0.5 * (xTarget[columns] + xTarget[columns - 1]));
- d.y = (0.5 * (yTarget[1] + yTarget[0]));
- d.sourceLeft = sourceCenterRight;
- d.sourceTop = sourceRect.top();
- d.width = sourceMargins.right();
- d.height = sourceMargins.top();
- d.scaleX = qreal(xTarget[columns] - xTarget[columns - 1]) / d.width;
- d.scaleY = qreal(yTarget[1] - yTarget[0]) / d.height;
- if (hints & QDrawBorderPixmap::OpaqueTopRight)
- opaqueData.append(d);
- else
- translucentData.append(d);
- }
- if (targetMargins.bottom() > 0 && targetMargins.left() > 0 && sourceMargins.bottom() > 0 && sourceMargins.left() > 0) { // bottom left
- d.x = (0.5 * (xTarget[1] + xTarget[0]));
- d.y =(0.5 * (yTarget[rows] + yTarget[rows - 1]));
- d.sourceLeft = sourceRect.left();
- d.sourceTop = sourceCenterBottom;
- d.width = sourceMargins.left();
- d.height = sourceMargins.bottom();
- d.scaleX = qreal(xTarget[1] - xTarget[0]) / d.width;
- d.scaleY = qreal(yTarget[rows] - yTarget[rows - 1]) / d.height;
- if (hints & QDrawBorderPixmap::OpaqueBottomLeft)
- opaqueData.append(d);
- else
- translucentData.append(d);
- }
- if (targetMargins.bottom() > 0 && targetMargins.right() > 0 && sourceMargins.bottom() > 0 && sourceMargins.right() > 0) { // bottom right
- d.x = (0.5 * (xTarget[columns] + xTarget[columns - 1]));
- d.y = (0.5 * (yTarget[rows] + yTarget[rows - 1]));
- d.sourceLeft = sourceCenterRight;
- d.sourceTop = sourceCenterBottom;
- d.width = sourceMargins.right();
- d.height = sourceMargins.bottom();
- d.scaleX = qreal(xTarget[columns] - xTarget[columns - 1]) / d.width;
- d.scaleY = qreal(yTarget[rows] - yTarget[rows - 1]) / d.height;
- if (hints & QDrawBorderPixmap::OpaqueBottomRight)
- opaqueData.append(d);
- else
- translucentData.append(d);
- }
-
- // horizontal edges
- if (targetCenterWidth > 0 && sourceCenterWidth > 0) {
- if (targetMargins.top() > 0 && sourceMargins.top() > 0) { // top
- QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueTop ? opaqueData : translucentData;
- d.sourceLeft = sourceCenterLeft;
- d.sourceTop = sourceRect.top();
- d.width = sourceCenterWidth;
- d.height = sourceMargins.top();
- d.y = (0.5 * (yTarget[1] + yTarget[0]));
- d.scaleX = dx / d.width;
- d.scaleY = qreal(yTarget[1] - yTarget[0]) / d.height;
- for (int i = 1; i < columns - 1; ++i) {
- d.x = (0.5 * (xTarget[i + 1] + xTarget[i]));
- data.append(d);
- }
- if (rules.horizontal == Qt::RepeatTile)
- data[data.size() - 1].width = ((xTarget[columns - 1] - xTarget[columns - 2]) / d.scaleX);
- }
- if (targetMargins.bottom() > 0 && sourceMargins.bottom() > 0) { // bottom
- QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueBottom ? opaqueData : translucentData;
- d.sourceLeft = sourceCenterLeft;
- d.sourceTop = sourceCenterBottom;
- d.width = sourceCenterWidth;
- d.height = sourceMargins.bottom();
- d.y = (0.5 * (yTarget[rows] + yTarget[rows - 1]));
- d.scaleX = dx / d.width;
- d.scaleY = qreal(yTarget[rows] - yTarget[rows - 1]) / d.height;
- for (int i = 1; i < columns - 1; ++i) {
- d.x = (0.5 * (xTarget[i + 1] + xTarget[i]));
- data.append(d);
- }
- if (rules.horizontal == Qt::RepeatTile)
- data[data.size() - 1].width = ((xTarget[columns - 1] - xTarget[columns - 2]) / d.scaleX);
- }
- }
-
- // vertical edges
- if (targetCenterHeight > 0 && sourceCenterHeight > 0) {
- if (targetMargins.left() > 0 && sourceMargins.left() > 0) { // left
- QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueLeft ? opaqueData : translucentData;
- d.sourceLeft = sourceRect.left();
- d.sourceTop = sourceCenterTop;
- d.width = sourceMargins.left();
- d.height = sourceCenterHeight;
- d.x = (0.5 * (xTarget[1] + xTarget[0]));
- d.scaleX = qreal(xTarget[1] - xTarget[0]) / d.width;
- d.scaleY = dy / d.height;
- for (int i = 1; i < rows - 1; ++i) {
- d.y = (0.5 * (yTarget[i + 1] + yTarget[i]));
- data.append(d);
- }
- if (rules.vertical == Qt::RepeatTile)
- data[data.size() - 1].height = ((yTarget[rows - 1] - yTarget[rows - 2]) / d.scaleY);
- }
- if (targetMargins.right() > 0 && sourceMargins.right() > 0) { // right
- QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueRight ? opaqueData : translucentData;
- d.sourceLeft = sourceCenterRight;
- d.sourceTop = sourceCenterTop;
- d.width = sourceMargins.right();
- d.height = sourceCenterHeight;
- d.x = (0.5 * (xTarget[columns] + xTarget[columns - 1]));
- d.scaleX = qreal(xTarget[columns] - xTarget[columns - 1]) / d.width;
- d.scaleY = dy / d.height;
- for (int i = 1; i < rows - 1; ++i) {
- d.y = (0.5 * (yTarget[i + 1] + yTarget[i]));
- data.append(d);
- }
- if (rules.vertical == Qt::RepeatTile)
- data[data.size() - 1].height = ((yTarget[rows - 1] - yTarget[rows - 2]) / d.scaleY);
- }
- }
-
- // center
- if (targetCenterWidth > 0 && targetCenterHeight > 0 && sourceCenterWidth > 0 && sourceCenterHeight > 0) {
- QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueCenter ? opaqueData : translucentData;
- d.sourceLeft = sourceCenterLeft;
- d.sourceTop = sourceCenterTop;
- d.width = sourceCenterWidth;
- d.height = sourceCenterHeight;
- d.scaleX = dx / d.width;
- d.scaleY = dy / d.height;
-
- qreal repeatWidth = (xTarget[columns - 1] - xTarget[columns - 2]) / d.scaleX;
- qreal repeatHeight = (yTarget[rows - 1] - yTarget[rows - 2]) / d.scaleY;
-
- for (int j = 1; j < rows - 1; ++j) {
- d.y = (0.5 * (yTarget[j + 1] + yTarget[j]));
- for (int i = 1; i < columns - 1; ++i) {
- d.x = (0.5 * (xTarget[i + 1] + xTarget[i]));
- data.append(d);
- }
- if (rules.horizontal == Qt::RepeatTile)
- data[data.size() - 1].width = repeatWidth;
- }
- if (rules.vertical == Qt::RepeatTile) {
- for (int i = 1; i < columns - 1; ++i)
- data[data.size() - i].height = repeatHeight;
- }
- }
-
- if (opaqueData.size())
- painter->drawPixmapFragments(opaqueData.data(), opaqueData.size(), pixmap, QPainter::OpaqueHint);
- if (translucentData.size())
- painter->drawPixmapFragments(translucentData.data(), translucentData.size(), pixmap);
-
- if (oldAA)
- painter->setRenderHint(QPainter::Antialiasing, true);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qdrawutil.h b/src/gui/styles/qdrawutil.h
deleted file mode 100644
index f46f720f2c..0000000000
--- a/src/gui/styles/qdrawutil.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/****************************************************************************
-**
-** 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 QDRAWUTIL_H
-#define QDRAWUTIL_H
-
-#include <QtCore/qnamespace.h>
-#include <QtCore/qstring.h> // char*->QString conversion
-#include <QtCore/qmargins.h>
-#include <QtGui/qpixmap.h>
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QPainter;
-class QPalette;
-class QPoint;
-class QColor;
-class QBrush;
-class QRect;
-
-//
-// Standard shade drawing
-//
-
-Q_GUI_EXPORT void qDrawShadeLine(QPainter *p, int x1, int y1, int x2, int y2,
- const QPalette &pal, bool sunken = true,
- int lineWidth = 1, int midLineWidth = 0);
-
-Q_GUI_EXPORT void qDrawShadeLine(QPainter *p, const QPoint &p1, const QPoint &p2,
- const QPalette &pal, bool sunken = true,
- int lineWidth = 1, int midLineWidth = 0);
-
-Q_GUI_EXPORT void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken = false,
- int lineWidth = 1, int midLineWidth = 0,
- const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawShadeRect(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken = false,
- int lineWidth = 1, int midLineWidth = 0,
- const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken = false,
- int lineWidth = 1, const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawShadePanel(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken = false,
- int lineWidth = 1, const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawWinButton(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawWinButton(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawWinPanel(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawWinPanel(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &,
- int lineWidth = 1, const QBrush *fill = 0);
-
-Q_GUI_EXPORT void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &,
- int lineWidth = 1, const QBrush *fill = 0);
-
-
-
-struct QTileRules
-{
- inline QTileRules(Qt::TileRule horizontalRule, Qt::TileRule verticalRule)
- : horizontal(horizontalRule), vertical(verticalRule) {}
- inline QTileRules(Qt::TileRule rule = Qt::StretchTile)
- : horizontal(rule), vertical(rule) {}
- Qt::TileRule horizontal;
- Qt::TileRule vertical;
-};
-
-#ifndef Q_QDOC
-// For internal use only.
-namespace QDrawBorderPixmap
-{
- enum DrawingHint
- {
- OpaqueTopLeft = 0x0001,
- OpaqueTop = 0x0002,
- OpaqueTopRight = 0x0004,
- OpaqueLeft = 0x0008,
- OpaqueCenter = 0x0010,
- OpaqueRight = 0x0020,
- OpaqueBottomLeft = 0x0040,
- OpaqueBottom = 0x0080,
- OpaqueBottomRight = 0x0100,
- OpaqueCorners = OpaqueTopLeft | OpaqueTopRight | OpaqueBottomLeft | OpaqueBottomRight,
- OpaqueEdges = OpaqueTop | OpaqueLeft | OpaqueRight | OpaqueBottom,
- OpaqueFrame = OpaqueCorners | OpaqueEdges,
- OpaqueAll = OpaqueCenter | OpaqueFrame
- };
-
- Q_DECLARE_FLAGS(DrawingHints, DrawingHint)
-}
-#endif
-
-Q_GUI_EXPORT void qDrawBorderPixmap(QPainter *painter,
- const QRect &targetRect,
- const QMargins &targetMargins,
- const QPixmap &pixmap,
- const QRect &sourceRect,
- const QMargins &sourceMargins,
- const QTileRules &rules = QTileRules()
-#ifndef Q_QDOC
- , QDrawBorderPixmap::DrawingHints hints = 0
-#endif
- );
-
-inline void qDrawBorderPixmap(QPainter *painter,
- const QRect &target,
- const QMargins &margins,
- const QPixmap &pixmap)
-{
- qDrawBorderPixmap(painter, target, margins, pixmap, pixmap.rect(), margins);
-}
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDRAWUTIL_H
diff --git a/src/gui/styles/qgtkpainter.cpp b/src/gui/styles/qgtkpainter.cpp
deleted file mode 100644
index 68ade04984..0000000000
--- a/src/gui/styles/qgtkpainter.cpp
+++ /dev/null
@@ -1,721 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgtkpainter_p.h"
-
-#include <QtCore/qglobal.h>
-#if !defined(QT_NO_STYLE_GTK)
-
-// This class is primarily a wrapper around the gtk painter functions
-// and takes care of converting all such calls into cached Qt pixmaps.
-
-#include <private/qstylehelper_p.h>
-#include <QtGui/QWidget>
-#include <QtGui/QStyleOption>
-#include <QtGui/QPixmapCache>
-
-QT_BEGIN_NAMESPACE
-
-#undef GTK_OBJECT_FLAGS
-#define GTK_OBJECT_FLAGS(obj)(((GtkObject*)(obj))->flags)
-
-#if Q_BYTE_ORDER == Q_BIG_ENDIAN
-# define QT_RED 3
-# define QT_GREEN 2
-# define QT_BLUE 1
-# define QT_ALPHA 0
-#else
-# define QT_RED 0
-# define QT_GREEN 1
-# define QT_BLUE 2
-# define QT_ALPHA 3
-#endif
-# define GTK_RED 2
-# define GTK_GREEN 1
-# define GTK_BLUE 0
-# define GTK_ALPHA 3
-
-// To recover alpha we apply the gtk painting function two times to
-// white, and black window backgrounds. This can be used to
-// recover the premultiplied alpha channel
-QPixmap QGtkPainter::renderTheme(uchar *bdata, uchar *wdata, const QRect &rect)
-{
- const int bytecount = rect.width() * rect.height() * 4;
- for (int index = 0; index < bytecount ; index += 4) {
- uchar val = bdata[index + GTK_BLUE];
- if (m_alpha) {
- int alphaval = qMax(bdata[index + GTK_BLUE] - wdata[index + GTK_BLUE],
- bdata[index + GTK_GREEN] - wdata[index + GTK_GREEN]);
- alphaval = qMax(alphaval, bdata[index + GTK_RED] - wdata[index + GTK_RED]) + 255;
- bdata[index + QT_ALPHA] = alphaval;
- }
- bdata[index + QT_RED] = bdata[index + GTK_RED];
- bdata[index + QT_GREEN] = bdata[index + GTK_GREEN];
- bdata[index + QT_BLUE] = val;
- }
- QImage converted((const uchar*)bdata, rect.width(), rect.height(), m_alpha ?
- QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
-
- if (m_hflipped || m_vflipped) {
- return QPixmap::fromImage(converted.mirrored(m_hflipped, m_vflipped));
- } else {
- // on raster graphicssystem we need to do a copy here, because
- // we intend to deallocate the qimage bits shortly after...
- return QPixmap::fromImage(converted.copy());
- }
-}
-
-// This macro is responsible for painting any GtkStyle painting function onto a QPixmap
-#define DRAW_TO_CACHE(draw_func) \
- if (rect.width() > QWIDGETSIZE_MAX || rect.height() > QWIDGETSIZE_MAX) \
- return; \
- QRect pixmapRect(0, 0, rect.width(), rect.height()); \
- { \
- GdkPixmap *pixmap = QGtkStylePrivate::gdk_pixmap_new((GdkDrawable*)(m_window->window), \
- rect.width(), rect.height(), -1); \
- if (!pixmap) \
- return; \
- style = QGtkStylePrivate::gtk_style_attach (style, m_window->window); \
- QGtkStylePrivate::gdk_draw_rectangle(pixmap, m_alpha ? style->black_gc : *style->bg_gc, true, \
- 0, 0, rect.width(), rect.height()); \
- draw_func; \
- GdkPixbuf *imgb = QGtkStylePrivate::gdk_pixbuf_new(GDK_COLORSPACE_RGB, true, 8, rect.width(), rect.height());\
- if (!imgb) \
- return; \
- imgb = QGtkStylePrivate::gdk_pixbuf_get_from_drawable(imgb, pixmap, NULL, 0, 0, 0, 0, \
- rect.width(), rect.height()); \
- uchar* bdata = (uchar*)QGtkStylePrivate::gdk_pixbuf_get_pixels(imgb); \
- if (m_alpha) { \
- QGtkStylePrivate::gdk_draw_rectangle(pixmap, style->white_gc, true, 0, 0, rect.width(), rect.height()); \
- draw_func; \
- GdkPixbuf *imgw = QGtkStylePrivate::gdk_pixbuf_new(GDK_COLORSPACE_RGB, true, 8, rect. \
- width(), rect.height()); \
- if (!imgw) \
- return; \
- imgw = QGtkStylePrivate::gdk_pixbuf_get_from_drawable(imgw, pixmap, NULL, 0, 0, 0, 0, \
- rect.width(), rect.height()); \
- uchar* wdata = (uchar*)QGtkStylePrivate::gdk_pixbuf_get_pixels(imgw); \
- cache = renderTheme(bdata, wdata, rect); \
- QGtkStylePrivate::gdk_pixbuf_unref(imgw); \
- } else { \
- cache = renderTheme(bdata, 0, rect); \
- } \
- QGtkStylePrivate::gdk_drawable_unref(pixmap); \
- QGtkStylePrivate::gdk_pixbuf_unref(imgb); \
- }
-
-QGtkPainter::QGtkPainter(QPainter *_painter)
- : m_window(QGtkStylePrivate::gtkWidget("GtkWindow"))
- , m_painter(_painter)
- , m_alpha(true)
- , m_hflipped(false)
- , m_vflipped(false)
- , m_usePixmapCache(true)
-{}
-
-
-static QString uniqueName(const QString &key, GtkStateType state, GtkShadowType shadow,
- const QSize &size, GtkWidget *widget = 0)
-{
- // Note the widget arg should ideally use the widget path, though would compromise performance
- QString tmp = key
- % HexString<uint>(state)
- % HexString<uint>(shadow)
- % HexString<uint>(size.width())
- % HexString<uint>(size.height())
- % HexString<quint64>(quint64(widget));
- return tmp;
-}
-
-
-GtkStateType QGtkPainter::gtkState(const QStyleOption *option)
-
-{
- GtkStateType state = GTK_STATE_NORMAL;
- if (!(option->state & QStyle::State_Enabled))
- state = GTK_STATE_INSENSITIVE;
- else if (option->state & QStyle::State_MouseOver)
- state = GTK_STATE_PRELIGHT;
-
- return state;
-}
-
-
-GtkStyle* QGtkPainter::getStyle(GtkWidget *gtkWidget)
-
-{
- Q_ASSERT(gtkWidget);
- GtkStyle* style = gtkWidget->style;
- Q_ASSERT(style);
- return style;
-}
-
-QPixmap QGtkPainter::getIcon(const char* iconName, GtkIconSize size)
-{
- GtkStyle *style = QGtkStylePrivate::gtkStyle();
- GtkIconSet* iconSet = QGtkStylePrivate::gtk_icon_factory_lookup_default (iconName);
- GdkPixbuf* icon = QGtkStylePrivate::gtk_icon_set_render_icon(iconSet,
- style,
- GTK_TEXT_DIR_LTR,
- GTK_STATE_NORMAL,
- size,
- NULL,
- "button");
- uchar* data = (uchar*)QGtkStylePrivate::gdk_pixbuf_get_pixels(icon);
- int width = QGtkStylePrivate::gdk_pixbuf_get_width(icon);
- int height = QGtkStylePrivate::gdk_pixbuf_get_height(icon);
- QImage converted(width, height, QImage::Format_ARGB32);
- uchar* tdata = (uchar*)converted.bits();
-
- for ( int index = 0 ; index < height * width*4 ; index +=4 ) {
- //int index = y * rowstride + x;
- tdata[index + QT_RED] = data[index + GTK_RED];
- tdata[index + QT_GREEN] = data[index + GTK_GREEN];
- tdata[index + QT_BLUE] = data[index + GTK_BLUE];
- tdata[index + QT_ALPHA] = data[index + GTK_ALPHA];
- }
-
- QGtkStylePrivate::gdk_pixbuf_unref(icon);
-
- // should we free iconset?
- return QPixmap::fromImage(converted);
-
-}
-
-// Note currently painted without alpha for performance reasons
-void QGtkPainter::paintBoxGap(GtkWidget *gtkWidget, const gchar* part,
- const QRect &paintRect, GtkStateType state,
- GtkShadowType shadow, GtkPositionType gap_side,
- gint x, gint width,
- GtkStyle *style)
-{
- if (!paintRect.isValid())
- return;
-
- QPixmap cache;
- QRect rect = paintRect;
-
- // To avoid exhausting cache on large tabframes we cheat a bit by
- // tiling the center part.
-
- const int maxHeight = 256;
- const int border = 16;
- if (rect.height() > maxHeight && (gap_side == GTK_POS_TOP || gap_side == GTK_POS_BOTTOM))
- rect.setHeight(2 * border + 1);
-
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size(), gtkWidget)
- % HexString<uchar>(gap_side)
- % HexString<gint>(width)
- % HexString<gint>(x);
-
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_box_gap (style,
- pixmap,
- state,
- shadow,
- NULL,
- gtkWidget,
- (gchar*)part,
- 0, 0,
- rect.width(),
- rect.height(),
- gap_side,
- x,
- width));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- if (rect.size() != paintRect.size()) {
- // We assume we can stretch the middle tab part
- // Note: the side effect of this is that pinstripe patterns will get fuzzy
- const QSize size = cache.size();
- // top part
- m_painter->drawPixmap(QRect(paintRect.left(), paintRect.top(),
- paintRect.width(), border), cache,
- QRect(0, 0, size.width(), border));
-
- // tiled center part
- QPixmap tilePart(cache.width(), 1);
- QPainter scanLinePainter(&tilePart);
- scanLinePainter.drawPixmap(QRect(0, 0, tilePart.width(), tilePart.height()), cache, QRect(0, border, size.width(), 1));
- scanLinePainter.end();
- m_painter->drawTiledPixmap(QRect(paintRect.left(), paintRect.top() + border,
- paintRect.width(), paintRect.height() - 2*border), tilePart);
-
- // bottom part
- m_painter->drawPixmap(QRect(paintRect.left(), paintRect.top() + paintRect.height() - border,
- paintRect.width(), border), cache,
- QRect(0, size.height() - border, size.width(), border));
- } else
- m_painter->drawPixmap(paintRect.topLeft(), cache);
-}
-
-void QGtkPainter::paintBox(GtkWidget *gtkWidget, const gchar* part,
- const QRect &paintRect, GtkStateType state,
- GtkShadowType shadow, GtkStyle *style,
- const QString &pmKey)
-{
- if (!paintRect.isValid())
- return;
-
- QPixmap cache;
- QRect rect = paintRect;
-
- // To avoid exhausting cache on large tabframes we cheat a bit by
- // tiling the center part.
-
- const int maxHeight = 256;
- const int maxArea = 256*512;
- const int border = 32;
- if (rect.height() > maxHeight && (rect.width()*rect.height() > maxArea))
- rect.setHeight(2 * border + 1);
-
- QString pixmapName = uniqueName(QLS(part), state, shadow,
- rect.size(), gtkWidget) % pmKey;
-
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_box (style,
- pixmap,
- state,
- shadow,
- NULL,
- gtkWidget,
- part,
- 0, 0,
- rect.width(),
- rect.height()));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- if (rect.size() != paintRect.size()) {
- // We assume we can stretch the middle tab part
- // Note: the side effect of this is that pinstripe patterns will get fuzzy
- const QSize size = cache.size();
- // top part
- m_painter->drawPixmap(QRect(paintRect.left(), paintRect.top(),
- paintRect.width(), border), cache,
- QRect(0, 0, size.width(), border));
-
- // tiled center part
- QPixmap tilePart(cache.width(), 1);
- QPainter scanLinePainter(&tilePart);
- scanLinePainter.drawPixmap(QRect(0, 0, tilePart.width(), tilePart.height()), cache, QRect(0, border, size.width(), 1));
- scanLinePainter.end();
- m_painter->drawTiledPixmap(QRect(paintRect.left(), paintRect.top() + border,
- paintRect.width(), paintRect.height() - 2*border), tilePart);
-
- // bottom part
- m_painter->drawPixmap(QRect(paintRect.left(), paintRect.top() + paintRect.height() - border,
- paintRect.width(), border), cache,
- QRect(0, size.height() - border, size.width(), border));
- } else
- m_painter->drawPixmap(paintRect.topLeft(), cache);
-}
-
-void QGtkPainter::paintHline(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state,
- GtkStyle *style, int x1, int x2, int y,
- const QString &pmKey)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, GTK_SHADOW_NONE, rect.size(), gtkWidget)
- % HexString<int>(x1)
- % HexString<int>(x2)
- % HexString<int>(y)
- % pmKey;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_hline (style,
- pixmap,
- state,
- NULL,
- gtkWidget,
- part,
- x1, x2, y));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-void QGtkPainter::paintVline(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state,
- GtkStyle *style, int y1, int y2, int x,
- const QString &pmKey)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, GTK_SHADOW_NONE, rect.size(), gtkWidget)
- % HexString<int>(y1)
- % HexString<int>(y2)
- % HexString<int>(x)
- % pmKey;
-
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_vline (style,
- pixmap,
- state,
- NULL,
- gtkWidget,
- part,
- y1, y2,
- x));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-
-void QGtkPainter::paintExpander(GtkWidget *gtkWidget,
- const gchar* part, const QRect &rect,
- GtkStateType state, GtkExpanderStyle expander_state,
- GtkStyle *style, const QString &pmKey)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, GTK_SHADOW_NONE, rect.size(), gtkWidget)
- % HexString<uchar>(expander_state)
- % pmKey;
-
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_expander (style, pixmap,
- state, NULL,
- gtkWidget, part,
- rect.width()/2,
- rect.height()/2,
- expander_state));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-void QGtkPainter::paintFocus(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state,
- GtkStyle *style, const QString &pmKey)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, GTK_SHADOW_NONE, rect.size(), gtkWidget) % pmKey;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_focus (style, pixmap, state, NULL,
- gtkWidget,
- part,
- 0, 0,
- rect.width(),
- rect.height()));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-
-void QGtkPainter::paintResizeGrip(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state,
- GtkShadowType shadow, GdkWindowEdge edge,
- GtkStyle *style, const QString &pmKey)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size(), gtkWidget) % pmKey;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_resize_grip (style, pixmap, state,
- NULL, gtkWidget,
- part, edge, 0, 0,
- rect.width(),
- rect.height()));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-
-void QGtkPainter::paintArrow(GtkWidget *gtkWidget, const gchar* part,
- const QRect &arrowrect, GtkArrowType arrow_type,
- GtkStateType state, GtkShadowType shadow,
- gboolean fill, GtkStyle *style, const QString &pmKey)
-{
- QRect rect = m_cliprect.isValid() ? m_cliprect : arrowrect;
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size())
- % HexString<uchar>(arrow_type)
- % pmKey;
-
- GdkRectangle gtkCliprect = {0, 0, rect.width(), rect.height()};
- int xOffset = m_cliprect.isValid() ? arrowrect.x() - m_cliprect.x() : 0;
- int yOffset = m_cliprect.isValid() ? arrowrect.y() - m_cliprect.y() : 0;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_arrow (style, pixmap, state, shadow,
- &gtkCliprect,
- gtkWidget,
- part,
- arrow_type, fill,
- xOffset, yOffset,
- arrowrect.width(),
- arrowrect.height()))
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-
-void QGtkPainter::paintHandle(GtkWidget *gtkWidget, const gchar* part, const QRect &rect,
- GtkStateType state, GtkShadowType shadow,
- GtkOrientation orientation, GtkStyle *style)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size())
- % HexString<uchar>(orientation);
-
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_handle (style,
- pixmap,
- state,
- shadow,
- NULL,
- gtkWidget,
- part, 0, 0,
- rect.width(),
- rect.height(),
- orientation));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-
-void QGtkPainter::paintSlider(GtkWidget *gtkWidget, const gchar* part, const QRect &rect,
- GtkStateType state, GtkShadowType shadow,
- GtkStyle *style, GtkOrientation orientation,
- const QString &pmKey)
-{
- if (!rect.isValid())
- return;
-
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size(), gtkWidget) % pmKey;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_slider (style,
- pixmap,
- state,
- shadow,
- NULL,
- gtkWidget,
- part,
- 0, 0,
- rect.width(),
- rect.height(),
- orientation));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-
-void QGtkPainter::paintShadow(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state,
- GtkShadowType shadow, GtkStyle *style,
- const QString &pmKey)
-
-{
- if (!rect.isValid())
- return;
-
- QRect r = rect;
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size()) % pmKey;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_shadow(style, pixmap, state, shadow, NULL,
- gtkWidget, part, 0, 0, rect.width(), rect.height()));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-void QGtkPainter::paintFlatBox(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state,
- GtkShadowType shadow, GtkStyle *style,
- const QString &pmKey)
-{
- if (!rect.isValid())
- return;
- QRect r = rect;
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size()) % pmKey;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_flat_box (style,
- pixmap,
- state,
- shadow,
- NULL,
- gtkWidget,
- part, 0, 0,
- rect.width(),
- rect.height()));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-void QGtkPainter::paintExtention(GtkWidget *gtkWidget,
- const gchar *part, const QRect &rect,
- GtkStateType state, GtkShadowType shadow,
- GtkPositionType gap_pos, GtkStyle *style)
-{
- if (!rect.isValid())
- return;
-
- QRect r = rect;
- QPixmap cache;
- QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size(), gtkWidget)
- % HexString<uchar>(gap_pos);
-
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_extension (style, pixmap, state, shadow,
- NULL, gtkWidget,
- (gchar*)part, 0, 0,
- rect.width(),
- rect.height(),
- gap_pos));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-void QGtkPainter::paintOption(GtkWidget *gtkWidget, const QRect &radiorect,
- GtkStateType state, GtkShadowType shadow,
- GtkStyle *style, const QString &detail)
-
-{
- QRect rect = m_cliprect.isValid() ? m_cliprect : radiorect;
- if (!rect.isValid())
- return;
-
- QRect r = rect;
- QPixmap cache;
- QString pixmapName = uniqueName(detail, state, shadow, rect.size());
- GdkRectangle gtkCliprect = {0, 0, rect.width(), rect.height()};
- int xOffset = m_cliprect.isValid() ? radiorect.x() - m_cliprect.x() : 0;
- int yOffset = m_cliprect.isValid() ? radiorect.y() - m_cliprect.y() : 0;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_option(style, pixmap,
- state, shadow,
- &gtkCliprect,
- gtkWidget,
- detail.toLatin1(),
- xOffset, yOffset,
- radiorect.width(),
- radiorect.height()));
-
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-void QGtkPainter::paintCheckbox(GtkWidget *gtkWidget, const QRect &checkrect,
- GtkStateType state, GtkShadowType shadow,
- GtkStyle *style, const QString &detail)
-
-{
- QRect rect = m_cliprect.isValid() ? m_cliprect : checkrect;
- if (!rect.isValid())
- return;
-
- QRect r = rect;
- QPixmap cache;
- QString pixmapName = uniqueName(detail, state, shadow, rect.size());
- GdkRectangle gtkCliprect = {0, 0, rect.width(), rect.height()};
- int xOffset = m_cliprect.isValid() ? checkrect.x() - m_cliprect.x() : 0;
- int yOffset = m_cliprect.isValid() ? checkrect.y() - m_cliprect.y() : 0;
- if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) {
- DRAW_TO_CACHE(QGtkStylePrivate::gtk_paint_check (style,
- pixmap,
- state,
- shadow,
- &gtkCliprect,
- gtkWidget,
- detail.toLatin1(),
- xOffset, yOffset,
- checkrect.width(),
- checkrect.height()));
- if (m_usePixmapCache)
- QPixmapCache::insert(pixmapName, cache);
- }
-
- m_painter->drawPixmap(rect.topLeft(), cache);
-}
-
-QT_END_NAMESPACE
-
-#endif //!defined(QT_NO_STYLE_GTK)
diff --git a/src/gui/styles/qgtkpainter_p.h b/src/gui/styles/qgtkpainter_p.h
deleted file mode 100644
index 1c253798a8..0000000000
--- a/src/gui/styles/qgtkpainter_p.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/****************************************************************************
-**
-** 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 QGTKPAINTER_H
-#define QGTKPAINTER_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qglobal.h>
-#if !defined(QT_NO_STYLE_GTK)
-
-#include <QtGui/QCleanlooksStyle>
-#include <QtGui/QPainter>
-#include <QtGui/QPalette>
-#include <QtGui/QFont>
-#include <private/qgtkstyle_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QGtkPainter
-{
-
-public:
- QGtkPainter(QPainter *painter);
- GtkStyle *getStyle(GtkWidget *gtkWidget);
- GtkStateType gtkState(const QStyleOption *option);
-
- void setAlphaSupport(bool value) { m_alpha = value; }
- void setClipRect(const QRect &rect) { m_cliprect = rect; }
- void setFlipHorizontal(bool value) { m_hflipped = value; }
- void setFlipVertical(bool value) { m_vflipped = value; }
- void setUsePixmapCache(bool value) { m_usePixmapCache = value; }
-
- void paintBoxGap(GtkWidget *gtkWidget, const gchar* part, const QRect &rect,
- GtkStateType state, GtkShadowType shadow, GtkPositionType gap_side, gint x,
- gint width, GtkStyle *style);
- void paintBox(GtkWidget *gtkWidget, const gchar* part,
- const QRect &rect, GtkStateType state, GtkShadowType shadow, GtkStyle *style,
- const QString &pmKey = QString());
- void paintHline(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkStyle *style,
- int x1, int x2, int y, const QString &pmKey = QString());
- void paintVline(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkStyle *style,
- int y1, int y2, int x, const QString &pmKey = QString());
- void paintExpander(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state,
- GtkExpanderStyle expander_state, GtkStyle *style, const QString &pmKey = QString());
- void paintFocus(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkStyle *style,
- const QString &pmKey = QString());
- void paintResizeGrip(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkShadowType shadow,
- GdkWindowEdge edge, GtkStyle *style, const QString &pmKey = QString());
- void paintArrow(GtkWidget *gtkWidget, const gchar* part, const QRect &arrowrect, GtkArrowType arrow_type, GtkStateType state, GtkShadowType shadow,
- gboolean fill, GtkStyle *style, const QString &pmKey = QString());
- void paintHandle(GtkWidget *gtkWidget, const gchar* part, const QRect &rect,
- GtkStateType state, GtkShadowType shadow, GtkOrientation orientation, GtkStyle *style);
- void paintSlider(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkShadowType shadow,
- GtkStyle *style, GtkOrientation orientation, const QString &pmKey = QString());
- void paintShadow(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkShadowType shadow,
- GtkStyle *style, const QString &pmKey = QString());
- void paintFlatBox(GtkWidget *gtkWidget, const gchar* part, const QRect &rect, GtkStateType state, GtkShadowType shadow, GtkStyle *style, const QString & = QString());
- void paintExtention(GtkWidget *gtkWidget, const gchar *part, const QRect &rect, GtkStateType state, GtkShadowType shadow,
- GtkPositionType gap_pos, GtkStyle *style);
- void paintOption(GtkWidget *gtkWidget, const QRect &rect, GtkStateType state, GtkShadowType shadow, GtkStyle *style, const QString &detail);
- void paintCheckbox(GtkWidget *gtkWidget, const QRect &rect, GtkStateType state, GtkShadowType shadow, GtkStyle *style, const QString &detail);
-
- static QPixmap getIcon(const char* iconName, GtkIconSize size = GTK_ICON_SIZE_BUTTON);
-private:
- QPixmap renderTheme(uchar *bdata, uchar *wdata, const QRect&);
-
- GtkWidget *m_window;
- QPainter *m_painter;
- bool m_alpha;
- bool m_hflipped;
- bool m_vflipped;
- bool m_usePixmapCache;
- QRect m_cliprect;
-
-};
-
-QT_END_NAMESPACE
-
-#endif //!defined(QT_NO_STYLE_QGTK)
-
-#endif // QGTKPAINTER_H
diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp
deleted file mode 100644
index 277e3025b5..0000000000
--- a/src/gui/styles/qgtkstyle.cpp
+++ /dev/null
@@ -1,3563 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgtkstyle.h"
-
-#if !defined(QT_NO_STYLE_GTK)
-
-#include <private/qapplication_p.h>
-#include <QtCore/QLibrary>
-#include <QtCore/QSettings>
-#include <QtGui/QDialogButtonBox>
-#include <QtGui/QStatusBar>
-#include <QtGui/QLineEdit>
-#include <QtGui/QWidget>
-#include <QtGui/QListView>
-#include <QtGui/QApplication>
-#include <QtGui/QStyleOption>
-#include <QtGui/QPushButton>
-#include <QtGui/QPainter>
-#include <QtGui/QMainWindow>
-#include <QtGui/QToolBar>
-#include <QtGui/QHeaderView>
-#include <QtGui/QMenuBar>
-#include <QtGui/QComboBox>
-#include <QtGui/QSpinBox>
-#include <QtGui/QScrollBar>
-#include <QtGui/QAbstractButton>
-#include <QtGui/QToolButton>
-#include <QtGui/QGroupBox>
-#include <QtGui/QRadioButton>
-#include <QtGui/QCheckBox>
-#include <QtGui/QTreeView>
-#include <QtGui/QStyledItemDelegate>
-#include <qpixmapcache.h>
-#undef signals // Collides with GTK stymbols
-#include <private/qgtkpainter_p.h>
-#include <private/qstylehelper_p.h>
-#include <private/qgtkstyle_p.h>
-#include <private/qcleanlooksstyle_p.h>
-
-
-QT_BEGIN_NAMESPACE
-
-static const char * const dock_widget_close_xpm[] =
- {
- "11 13 5 1",
- " c None",
- ". c #D5CFCB",
- "+ c #6C6A67",
- "@ c #6C6A67",
- "$ c #B5B0AC",
- " ",
- " @@@@@@@@@ ",
- "@+ +@",
- "@ +@ @+ @",
- "@ @@@ @@@ @",
- "@ @@@@@ @",
- "@ @@@ @",
- "@ @@@@@ @",
- "@ @@@ @@@ @",
- "@ +@ @+ @",
- "@+ +@",
- " @@@@@@@@@ ",
- " "
- };
-
-static const char * const dock_widget_restore_xpm[] =
- {
- "11 13 5 1",
- " c None",
- ". c #D5CFCB",
- "+ c #6C6A67",
- "@ c #6C6A67",
- "# c #6C6A67",
- " ",
- " @@@@@@@@@ ",
- "@+ +@",
- "@ #@@@# @",
- "@ @ @ @",
- "@ #@@@# @ @",
- "@ @ @ @ @",
- "@ @ @@@ @",
- "@ @ @ @",
- "@ #@@@@ @",
- "@+ +@",
- " @@@@@@@@@ ",
- " "
- };
-
-static const int groupBoxBottomMargin = 2; // space below the groupbox
-static const int groupBoxTitleMargin = 6; // space between contents and title
-static const int groupBoxTopMargin = 2;
-
-/*!
- Returns the configuration string for \a value.
- Returns \a fallback if \a value is not found.
- */
-QString QGtkStyle::getGConfString(const QString &value, const QString &fallback)
-{
- return QGtkStylePrivate::getGConfString(value, fallback);
-}
-
-/*!
- Returns the configuration boolean for \a key.
- Returns \a fallback if \a key is not found.
- */
-bool QGtkStyle::getGConfBool(const QString &key, bool fallback)
-{
- return QGtkStylePrivate::getGConfBool(key, fallback);
-}
-
-static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50)
-{
- const int maxFactor = 100;
- QColor tmp = colorA;
- tmp.setRed((tmp.red() * factor) / maxFactor + (colorB.red() * (maxFactor - factor)) / maxFactor);
- tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor);
- tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor);
- return tmp;
-}
-
-static GdkColor fromQColor(const QColor &color)
-{
- GdkColor retval;
- retval.red = color.red() * 255;
- retval.green = color.green() * 255;
- retval.blue = color.blue() * 255;
- return retval;
-}
-
-/*!
- \class QGtkStyle
- \brief The QGtkStyle class provides a widget style rendered by GTK+
- \since 4.5
-
- The QGtkStyle style provides a look and feel that integrates well
- into GTK-based desktop environments such as the XFCe and GNOME.
-
- It does this by making use of the GTK+ theme engine, ensuring
- that Qt applications look and feel native on these platforms.
-
- Note: The style requires GTK+ version 2.10 or later.
- The Qt3-based "Qt" GTK+ theme engine will not work with QGtkStyle.
-
- \sa {Cleanlooks Style Widget Gallery}, QWindowsXPStyle, QMacStyle, QWindowsStyle,
- QCDEStyle, QMotifStyle, QPlastiqueStyle, QCleanlooksStyle
-*/
-
-/*!
- Constructs a QGtkStyle object.
-*/
-QGtkStyle::QGtkStyle()
- : QCleanlooksStyle(*new QGtkStylePrivate)
-{
- Q_D(QGtkStyle);
- d->init();
-}
-
-/*!
- \internal
-
- Constructs a QGtkStyle object.
-*/
-QGtkStyle::QGtkStyle(QGtkStylePrivate &dd)
- : QCleanlooksStyle(dd)
-{
- Q_D(QGtkStyle);
- d->init();
-}
-
-
-/*!
- Destroys the QGtkStyle object.
-*/
-QGtkStyle::~QGtkStyle()
-{
-}
-
-/*!
- \reimp
-*/
-QPalette QGtkStyle::standardPalette() const
-{
- Q_D(const QGtkStyle);
-
- QPalette palette = QCleanlooksStyle::standardPalette();
- if (d->isThemeAvailable()) {
- GtkStyle *style = d->gtkStyle();
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- GtkWidget *gtkEntry = d->getTextColorWidget();
- GdkColor gdkBg, gdkBase, gdkText, gdkForeground, gdkSbg, gdkSfg, gdkaSbg, gdkaSfg;
- QColor bg, base, text, fg, highlight, highlightText, inactiveHighlight, inactiveHighlightedTExt;
- gdkBg = style->bg[GTK_STATE_NORMAL];
- gdkForeground = gtkButton->style->fg[GTK_STATE_NORMAL];
-
- // Our base and selected color is primarily used for text
- // so we assume a gtkEntry will have the most correct value
- gdkBase = gtkEntry->style->base[GTK_STATE_NORMAL];
- gdkText = gtkEntry->style->text[GTK_STATE_NORMAL];
- gdkSbg = gtkEntry->style->base[GTK_STATE_SELECTED];
- gdkSfg = gtkEntry->style->text[GTK_STATE_SELECTED];
-
- // The ACTIVE base color is really used for inactive windows
- gdkaSbg = gtkEntry->style->base[GTK_STATE_ACTIVE];
- gdkaSfg = gtkEntry->style->text[GTK_STATE_ACTIVE];
-
- bg = QColor(gdkBg.red>>8, gdkBg.green>>8, gdkBg.blue>>8);
- text = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- fg = QColor(gdkForeground.red>>8, gdkForeground.green>>8, gdkForeground.blue>>8);
- base = QColor(gdkBase.red>>8, gdkBase.green>>8, gdkBase.blue>>8);
- highlight = QColor(gdkSbg.red>>8, gdkSbg.green>>8, gdkSbg.blue>>8);
- highlightText = QColor(gdkSfg.red>>8, gdkSfg.green>>8, gdkSfg.blue>>8);
- inactiveHighlight = QColor(gdkaSbg.red>>8, gdkaSbg.green>>8, gdkaSbg.blue>>8);
- inactiveHighlightedTExt = QColor(gdkaSfg.red>>8, gdkaSfg.green>>8, gdkaSfg.blue>>8);
-
- palette.setColor(QPalette::HighlightedText, highlightText);
-
-
- palette.setColor(QPalette::Light, bg.lighter(125));
- palette.setColor(QPalette::Shadow, bg.darker(130));
- palette.setColor(QPalette::Dark, bg.darker(120));
- palette.setColor(QPalette::Text, text);
- palette.setColor(QPalette::WindowText, fg);
- palette.setColor(QPalette::ButtonText, fg);
- palette.setColor(QPalette::Base, base);
-
- QColor alternateRowColor = palette.base().color().lighter(93); // ref gtkstyle.c draw_flat_box
- GtkWidget *gtkTreeView = d->gtkWidget("GtkTreeView");
- GdkColor *gtkAltBase = NULL;
- d->gtk_widget_style_get(gtkTreeView, "odd-row-color", &gtkAltBase, NULL);
- if (gtkAltBase) {
- alternateRowColor = QColor(gtkAltBase->red>>8, gtkAltBase->green>>8, gtkAltBase->blue>>8);
- d->gdk_color_free(gtkAltBase);
- }
- palette.setColor(QPalette::AlternateBase, alternateRowColor);
-
- palette.setColor(QPalette::Window, bg);
- palette.setColor(QPalette::Button, bg);
- palette.setColor(QPalette::Background, bg);
- QColor disabled((fg.red() + bg.red()) / 2,
- (fg.green() + bg.green())/ 2,
- (fg.blue() + bg.blue()) / 2);
- palette.setColor(QPalette::Disabled, QPalette::Text, disabled);
- palette.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
- palette.setColor(QPalette::Disabled, QPalette::Foreground, disabled);
- palette.setColor(QPalette::Disabled, QPalette::ButtonText, disabled);
- palette.setColor(QPalette::Highlight, highlight);
- // calculate disabled colors by removing saturation
- highlight.setHsv(highlight.hue(), 0, highlight.value(), highlight.alpha());
- highlightText.setHsv(highlightText.hue(), 0, highlightText.value(), highlightText.alpha());
- palette.setColor(QPalette::Disabled, QPalette::Highlight, highlight);
- palette.setColor(QPalette::Disabled, QPalette::HighlightedText, highlightText);
-
- palette.setColor(QPalette::Inactive, QPalette::HighlightedText, inactiveHighlightedTExt);
- palette.setColor(QPalette::Inactive, QPalette::Highlight, inactiveHighlight);
-
- style = d->gtk_rc_get_style_by_paths(d->gtk_settings_get_default(), "gtk-tooltips", "GtkWindow",
- d->gtk_window_get_type());
- if (style) {
- gdkText = style->fg[GTK_STATE_NORMAL];
- text = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- palette.setColor(QPalette::ToolTipText, text);
- }
- }
- return palette;
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::polish(QPalette &palette)
-{
- Q_D(QGtkStyle);
-
- // QCleanlooksStyle will alter the palette, hence we do
- // not want to polish the palette unless we are using it as
- // the fallback
- if (!d->isThemeAvailable())
- QCleanlooksStyle::polish(palette);
- else
- palette = palette.resolve(standardPalette());
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::polish(QApplication *app)
-{
- Q_D(QGtkStyle);
-
- QCleanlooksStyle::polish(app);
- // Custom fonts and palettes with QtConfig are intentionally
- // not supported as these should be entirely determined by
- // current Gtk settings
- if (app->desktopSettingsAware() && d->isThemeAvailable()) {
- QApplicationPrivate::setSystemPalette(standardPalette());
- QApplicationPrivate::setSystemFont(d->getThemeFont());
- d->applyCustomPaletteHash();
- if (!d->isKDE4Session()) {
- qt_filedialog_open_filename_hook = &QGtkStylePrivate::openFilename;
- qt_filedialog_save_filename_hook = &QGtkStylePrivate::saveFilename;
- qt_filedialog_open_filenames_hook = &QGtkStylePrivate::openFilenames;
- qt_filedialog_existing_directory_hook = &QGtkStylePrivate::openDirectory;
- qApp->installEventFilter(&d->filter);
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::unpolish(QApplication *app)
-{
- Q_D(QGtkStyle);
-
- QCleanlooksStyle::unpolish(app);
- QPixmapCache::clear();
-
- if (app->desktopSettingsAware() && d->isThemeAvailable()
- && !d->isKDE4Session()) {
- qt_filedialog_open_filename_hook = 0;
- qt_filedialog_save_filename_hook = 0;
- qt_filedialog_open_filenames_hook = 0;
- qt_filedialog_existing_directory_hook = 0;
- qApp->removeEventFilter(&d->filter);
- }
-}
-
-/*!
- \reimp
-*/
-
-void QGtkStyle::polish(QWidget *widget)
-{
- Q_D(QGtkStyle);
-
- QCleanlooksStyle::polish(widget);
- if (!d->isThemeAvailable())
- return;
- if (qobject_cast<QAbstractButton*>(widget)
- || qobject_cast<QToolButton*>(widget)
- || qobject_cast<QComboBox*>(widget)
- || qobject_cast<QGroupBox*>(widget)
- || qobject_cast<QScrollBar*>(widget)
- || qobject_cast<QSlider*>(widget)
- || qobject_cast<QAbstractSpinBox*>(widget)
- || qobject_cast<QSpinBox*>(widget)
- || qobject_cast<QHeaderView*>(widget))
- widget->setAttribute(Qt::WA_Hover);
- else if (QTreeView *tree = qobject_cast<QTreeView *> (widget))
- tree->viewport()->setAttribute(Qt::WA_Hover);
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::unpolish(QWidget *widget)
-{
- QCleanlooksStyle::unpolish(widget);
-}
-
-/*!
- \reimp
-*/
-int QGtkStyle::pixelMetric(PixelMetric metric,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable())
- return QCleanlooksStyle::pixelMetric(metric, option, widget);
-
- switch (metric) {
- case PM_DefaultFrameWidth:
- if (qobject_cast<const QFrame*>(widget)) {
- if (GtkStyle *style =
- d->gtk_rc_get_style_by_paths(d->gtk_settings_get_default(),
- "*.GtkScrolledWindow",
- "*.GtkScrolledWindow",
- d->gtk_window_get_type()))
- return qMax(style->xthickness, style->ythickness);
- }
- return 2;
-
- case PM_MenuButtonIndicator:
- return 20;
-
- case PM_TabBarBaseOverlap:
- return 1;
-
- case PM_ToolBarSeparatorExtent:
- return 11;
-
- case PM_ToolBarFrameWidth:
- return 1;
-
- case PM_ToolBarItemSpacing:
- return 0;
-
- case PM_ButtonShiftHorizontal: {
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- guint horizontal_shift;
- d->gtk_widget_style_get(gtkButton, "child-displacement-x", &horizontal_shift, NULL);
- return horizontal_shift;
- }
-
- case PM_ButtonShiftVertical: {
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- guint vertical_shift;
- d->gtk_widget_style_get(gtkButton, "child-displacement-y", &vertical_shift, NULL);
- return vertical_shift;
- }
-
- case PM_MenuBarPanelWidth:
- return 0;
-
- case PM_MenuPanelWidth: {
- GtkWidget *gtkMenu = d->gtkWidget("GtkMenu");
- guint horizontal_padding = 0;
- // horizontal-padding is used by Maemo to get thicker borders
- if (!d->gtk_check_version(2, 10, 0))
- d->gtk_widget_style_get(gtkMenu, "horizontal-padding", &horizontal_padding, NULL);
- int padding = qMax<int>(gtkMenu->style->xthickness, horizontal_padding);
- return padding;
- }
-
- case PM_ButtonIconSize: {
- int retVal = 24;
- GtkSettings *settings = d->gtk_settings_get_default();
- gchararray icon_sizes;
- g_object_get(settings, "gtk-icon-sizes", &icon_sizes, NULL);
- QStringList values = QString(QLS(icon_sizes)).split(QLatin1Char(':'));
- g_free(icon_sizes);
- QChar splitChar(QLatin1Char(','));
- foreach (const QString &value, values) {
- if (value.startsWith(QLS("gtk-button="))) {
- QString iconSize = value.right(value.size() - 11);
-
- if (iconSize.contains(splitChar))
- retVal = iconSize.split(splitChar)[0].toInt();
- break;
- }
- }
- return retVal;
- }
-
- case PM_MenuVMargin:
-
- case PM_MenuHMargin:
- return 0;
-
- case PM_DockWidgetTitleMargin:
- return 0;
-
- case PM_DockWidgetTitleBarButtonMargin:
- return 5;
-
- case PM_TabBarTabVSpace:
- return 12;
-
- case PM_TabBarTabHSpace:
- return 14;
-
- case PM_TabBarTabShiftVertical:
- return 2;
-
- case PM_ToolBarHandleExtent:
- return 9;
-
- case PM_SplitterWidth:
- return 6;
-
- case PM_SliderThickness:
- case PM_SliderControlThickness: {
- GtkWidget *gtkScale = d->gtkWidget("GtkHScale");
- gint val;
- d->gtk_widget_style_get(gtkScale, "slider-width", &val, NULL);
- if (metric == PM_SliderControlThickness)
- return val + 2*gtkScale->style->ythickness;
- return val;
- }
-
- case PM_ScrollBarExtent: {
- gint sliderLength;
- gint trough_border;
- GtkWidget *hScrollbar = d->gtkWidget("GtkHScrollbar");
- d->gtk_widget_style_get(hScrollbar,
- "trough-border", &trough_border,
- "slider-width", &sliderLength,
- NULL);
- return sliderLength + trough_border*2;
- }
-
- case PM_ScrollBarSliderMin:
- return 34;
-
- case PM_SliderLength:
- gint val;
- d->gtk_widget_style_get(d->gtkWidget("GtkHScale"), "slider-length", &val, NULL);
- return val;
-
- case PM_ExclusiveIndicatorWidth:
- case PM_ExclusiveIndicatorHeight:
- case PM_IndicatorWidth:
- case PM_IndicatorHeight: {
- GtkWidget *gtkCheckButton = d->gtkWidget("GtkCheckButton");
- gint size, spacing;
- d->gtk_widget_style_get(gtkCheckButton, "indicator-spacing", &spacing, "indicator-size", &size, NULL);
- return size + 2 * spacing;
- }
-
- case PM_MenuBarVMargin: {
- GtkWidget *gtkMenubar = d->gtkWidget("GtkMenuBar");
- return qMax(0, gtkMenubar->style->ythickness);
- }
- case PM_ScrollView_ScrollBarSpacing:
- {
- gint spacing = 3;
- GtkWidget *gtkScrollWindow = d->gtkWidget("GtkScrolledWindow");
- Q_ASSERT(gtkScrollWindow);
- d->gtk_widget_style_get(gtkScrollWindow, "scrollbar-spacing", &spacing, NULL);
- return spacing;
- }
- case PM_SubMenuOverlap: {
- gint offset = 0;
- GtkWidget *gtkMenu = d->gtkWidget("GtkMenu");
- d->gtk_widget_style_get(gtkMenu, "horizontal-offset", &offset, NULL);
- return offset;
- }
- default:
- return QCleanlooksStyle::pixelMetric(metric, option, widget);
- }
-}
-
-/*!
- \reimp
-*/
-int QGtkStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget,
-
- QStyleHintReturn *returnData = 0) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable())
- return QCleanlooksStyle::styleHint(hint, option, widget, returnData);
-
- switch (hint) {
-
- case SH_DialogButtonLayout: {
- int ret = QDialogButtonBox::GnomeLayout;
- gboolean alternateOrder = 0;
- GtkSettings *settings = d->gtk_settings_get_default();
- g_object_get(settings, "gtk-alternative-button-order", &alternateOrder, NULL);
-
- if (alternateOrder)
- ret = QDialogButtonBox::WinLayout;
-
- return ret;
- }
-
- break;
-
- case SH_ToolButtonStyle:
- {
- if (d->isKDE4Session())
- return QCleanlooksStyle::styleHint(hint, option, widget, returnData);
- GtkWidget *gtkToolbar = d->gtkWidget("GtkToolbar");
- GtkToolbarStyle toolbar_style = GTK_TOOLBAR_ICONS;
- g_object_get(gtkToolbar, "toolbar-style", &toolbar_style, NULL);
- switch (toolbar_style) {
- case GTK_TOOLBAR_TEXT:
- return Qt::ToolButtonTextOnly;
- case GTK_TOOLBAR_BOTH:
- return Qt::ToolButtonTextUnderIcon;
- case GTK_TOOLBAR_BOTH_HORIZ:
- return Qt::ToolButtonTextBesideIcon;
- case GTK_TOOLBAR_ICONS:
- default:
- return Qt::ToolButtonIconOnly;
- }
- }
- break;
- case SH_SpinControls_DisableOnBounds:
- return int(true);
-
- case SH_DitherDisabledText:
- return int(false);
-
- case SH_ComboBox_Popup: {
- GtkWidget *gtkComboBox = d->gtkWidget("GtkComboBox");
- gboolean appears_as_list;
- d->gtk_widget_style_get((GtkWidget*)gtkComboBox, "appears-as-list", &appears_as_list, NULL);
- return appears_as_list ? 0 : 1;
- }
-
- case SH_MenuBar_AltKeyNavigation:
- return int(false);
-
- case SH_EtchDisabledText:
- return int(false);
-
- case SH_Menu_SubMenuPopupDelay: {
- gint delay = 225;
- GtkSettings *settings = d->gtk_settings_get_default();
- g_object_get(settings, "gtk-menu-popup-delay", &delay, NULL);
- return delay;
- }
-
- case SH_ScrollView_FrameOnlyAroundContents: {
- gboolean scrollbars_within_bevel = false;
- if (widget && widget->isWindow())
- scrollbars_within_bevel = true;
- else if (!d->gtk_check_version(2, 12, 0)) {
- GtkWidget *gtkScrollWindow = d->gtkWidget("GtkScrolledWindow");
- d->gtk_widget_style_get(gtkScrollWindow, "scrollbars-within-bevel", &scrollbars_within_bevel, NULL);
- }
- return !scrollbars_within_bevel;
- }
-
- case SH_DialogButtonBox_ButtonsHaveIcons: {
- static bool buttonsHaveIcons = d->getGConfBool(QLS("/desktop/gnome/interface/buttons_have_icons"));
- return buttonsHaveIcons;
- }
-
- case SH_UnderlineShortcut: {
- gboolean underlineShortcut = true;
- if (!d->gtk_check_version(2, 12, 0)) {
- GtkSettings *settings = d->gtk_settings_get_default();
- g_object_get(settings, "gtk-enable-mnemonics", &underlineShortcut, NULL);
- }
- return underlineShortcut;
- }
-
- default:
- return QCleanlooksStyle::styleHint(hint, option, widget, returnData);
- }
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::drawPrimitive(PrimitiveElement element,
- const QStyleOption *option,
- QPainter *painter,
- const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable()) {
- QCleanlooksStyle::drawPrimitive(element, option, painter, widget);
- return;
- }
-
- GtkStyle* style = d->gtkStyle();
- QGtkPainter gtkPainter(painter);
-
- switch (element) {
- case PE_Frame: {
- if (widget && widget->inherits("QComboBoxPrivateContainer")){
- QStyleOption copy = *option;
- copy.state |= State_Raised;
- proxy()->drawPrimitive(PE_PanelMenu, &copy, painter, widget);
- break;
- }
- // Drawing the entire itemview frame is very expensive, especially on the native X11 engine
- // Instead we cheat a bit and draw a border image without the center part, hence only scaling
- // thin rectangular images
- const int pmSize = 64;
- const int border = proxy()->pixelMetric(PM_DefaultFrameWidth, option, widget);
- const QString pmKey = QLatin1Literal("windowframe") % HexString<uint>(option->state);
-
- QPixmap pixmap;
- QRect pmRect(QPoint(0,0), QSize(pmSize, pmSize));
-
- // Only draw through style once
- if (!QPixmapCache::find(pmKey, pixmap)) {
- pixmap = QPixmap(pmSize, pmSize);
- pixmap.fill(Qt::transparent);
- QPainter pmPainter(&pixmap);
- QGtkPainter gtkFramePainter(&pmPainter);
- gtkFramePainter.setUsePixmapCache(false); // Don't cache twice
-
- GtkShadowType shadow_type = GTK_SHADOW_NONE;
- if (option->state & State_Sunken)
- shadow_type = GTK_SHADOW_IN;
- else if (option->state & State_Raised)
- shadow_type = GTK_SHADOW_OUT;
-
- GtkStyle *style = d->gtk_rc_get_style_by_paths(d->gtk_settings_get_default(),
- "*.GtkScrolledWindow", "*.GtkScrolledWindow", d->gtk_window_get_type());
- if (style)
- gtkFramePainter.paintShadow(d->gtkWidget("GtkFrame"), "viewport", pmRect,
- option->state & State_Enabled ? GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE,
- shadow_type, style);
- QPixmapCache::insert(pmKey, pixmap);
- }
-
- QRect rect = option->rect;
- const int rw = rect.width() - border;
- const int rh = rect.height() - border;
- const int pw = pmRect.width() - border;
- const int ph = pmRect.height() - border;
-
- // Sidelines
- painter->drawPixmap(rect.adjusted(border, 0, -border, -rh), pixmap, pmRect.adjusted(border, 0, -border,-ph));
- painter->drawPixmap(rect.adjusted(border, rh, -border, 0), pixmap, pmRect.adjusted(border, ph,-border,0));
- painter->drawPixmap(rect.adjusted(0, border, -rw, -border), pixmap, pmRect.adjusted(0, border, -pw, -border));
- painter->drawPixmap(rect.adjusted(rw, border, 0, -border), pixmap, pmRect.adjusted(pw, border, 0, -border));
-
- // Corners
- painter->drawPixmap(rect.adjusted(0, 0, -rw, -rh), pixmap, pmRect.adjusted(0, 0, -pw,-ph));
- painter->drawPixmap(rect.adjusted(rw, 0, 0, -rh), pixmap, pmRect.adjusted(pw, 0, 0,-ph));
- painter->drawPixmap(rect.adjusted(0, rh, -rw, 0), pixmap, pmRect.adjusted(0, ph, -pw,0));
- painter->drawPixmap(rect.adjusted(rw, rh, 0, 0), pixmap, pmRect.adjusted(pw, ph, 0,0));
- }
- break;
-
- case PE_PanelTipLabel: {
- GtkWidget *gtkWindow = d->gtkWidget("GtkWindow"); // The Murrine Engine currently assumes a widget is passed
- style = d->gtk_rc_get_style_by_paths(d->gtk_settings_get_default(), "gtk-tooltips", "GtkWindow",
- d->gtk_window_get_type());
- gtkPainter.paintFlatBox(gtkWindow, "tooltip", option->rect, GTK_STATE_NORMAL, GTK_SHADOW_NONE, style);
- }
- break;
-
- case PE_PanelStatusBar: {
- if (widget && widget->testAttribute(Qt::WA_SetPalette) &&
- option->palette.resolve() & (1 << QPalette::Window)) {
- // Respect custom palette
- painter->fillRect(option->rect, option->palette.window());
- break;
- }
- GtkShadowType shadow_type;
- GtkWidget *gtkStatusbarFrame = d->gtkWidget("GtkStatusbar.GtkFrame");
- d->gtk_widget_style_get(gtkStatusbarFrame->parent, "shadow-type", &shadow_type, NULL);
- gtkPainter.paintShadow(gtkStatusbarFrame, "frame", option->rect, GTK_STATE_NORMAL,
- shadow_type, gtkStatusbarFrame->style);
- }
- break;
-
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- GtkWidget *gtkTreeHeader = d->gtkWidget("GtkTreeView.GtkButton");
- GtkStateType state = gtkPainter.gtkState(option);
- style = gtkTreeHeader->style;
- GtkArrowType type = GTK_ARROW_UP;
- QRect r = header->rect;
- QImage arrow;
- // This sorting indicator inversion is intentional, and follows the GNOME HIG.
- // See http://library.gnome.org/devel/hig-book/stable/controls-lists.html.en#controls-lists-sortable
- if (header->sortIndicator & QStyleOptionHeader::SortUp)
- type = GTK_ARROW_UP;
- else if (header->sortIndicator & QStyleOptionHeader::SortDown)
- type = GTK_ARROW_DOWN;
-
- gtkPainter.paintArrow(gtkTreeHeader, "button", option->rect.adjusted(1, 1, -1, -1), type, state,
- GTK_SHADOW_NONE, FALSE, style);
- }
- break;
-
- case PE_FrameFocusRect:
- if (!widget || qobject_cast<const QAbstractItemView*>(widget))
- QCleanlooksStyle::drawPrimitive(element, option, painter, widget);
- else {
- // ### this mess should move to subcontrolrect
- QRect frameRect = option->rect.adjusted(1, 1, -1, -2);
-
- if (qobject_cast<const QTabBar*>(widget)) {
- GtkWidget *gtkNotebook = d->gtkWidget("GtkNotebook");
- style = gtkPainter.getStyle(gtkNotebook);
- gtkPainter.paintFocus(gtkNotebook, "tab", frameRect.adjusted(-1, 1, 1, 1), GTK_STATE_ACTIVE, style);
- } else {
- gtkPainter.paintFocus(NULL, "tab", frameRect, GTK_STATE_ACTIVE, style);
- }
- }
- break;
-
- case PE_IndicatorBranch:
- if (option->state & State_Children) {
- QRect rect = option->rect;
- rect = QRect(0, 0, 12, 12);
- rect.moveCenter(option->rect.center());
- rect.translate(2, 0);
- GtkExpanderStyle openState = GTK_EXPANDER_EXPANDED;
- GtkExpanderStyle closedState = GTK_EXPANDER_COLLAPSED;
- GtkWidget *gtkTreeView = d->gtkWidget("GtkTreeView");
-
- GtkStateType state = GTK_STATE_NORMAL;
- if (!(option->state & State_Enabled))
- state = GTK_STATE_INSENSITIVE;
- else if (option->state & State_MouseOver)
- state = GTK_STATE_PRELIGHT;
-
- gtkPainter.paintExpander(gtkTreeView, "treeview", rect, state,
- option->state & State_Open ? openState : closedState , gtkTreeView->style);
- }
- break;
-
- case PE_PanelItemViewRow:
- // This primitive is only used to draw selection behind selected expander arrows.
- // We try not to decorate the tree branch background unless you inherit from StyledItemDelegate
- // The reason for this is that a lot of code that relies on custom item delegates will look odd having
- // a gradient on the branch but a flat shaded color on the item itself.
- QCommonStyle::drawPrimitive(element, option, painter, widget);
- if (!option->state & State_Selected) {
- break;
- } else {
- if (const QAbstractItemView *view = qobject_cast<const QAbstractItemView*>(widget)) {
- if (!qobject_cast<QStyledItemDelegate*>(view->itemDelegate()))
- break;
- }
- } // fall through
-
- case PE_PanelItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- uint resolve_mask = vopt->palette.resolve();
- if (vopt->backgroundBrush.style() != Qt::NoBrush
- || (resolve_mask & (1 << QPalette::Base)))
- {
- QPointF oldBO = painter->brushOrigin();
- painter->setBrushOrigin(vopt->rect.topLeft());
- painter->fillRect(vopt->rect, vopt->backgroundBrush);
- painter->setBrushOrigin(oldBO);
- if (!(option->state & State_Selected))
- break;
- }
- if (GtkWidget *gtkTreeView = d->gtkWidget("GtkTreeView")) {
- const char *detail = "cell_even_ruled";
- if (vopt && vopt->features & QStyleOptionViewItemV2::Alternate)
- detail = "cell_odd_ruled";
- bool isActive = option->state & State_Active;
- QString key;
- if (isActive ) {
- // Required for active/non-active window appearance
- key = QLS("a");
- GTK_WIDGET_SET_FLAGS(gtkTreeView, GTK_HAS_FOCUS);
- }
- bool isEnabled = (widget ? widget->isEnabled() : (vopt->state & QStyle::State_Enabled));
- gtkPainter.paintFlatBox(gtkTreeView, detail, option->rect,
- option->state & State_Selected ? GTK_STATE_SELECTED :
- isEnabled ? GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE,
- GTK_SHADOW_OUT, gtkTreeView->style, key);
- if (isActive )
- GTK_WIDGET_UNSET_FLAGS(gtkTreeView, GTK_HAS_FOCUS);
- }
- }
- break;
- case PE_IndicatorToolBarSeparator:
- {
- const int margin = 6;
- GtkWidget *gtkSeparator = d->gtkWidget("GtkToolbar.GtkSeparatorToolItem");
- if (option->state & State_Horizontal) {
- const int offset = option->rect.width()/2;
- QRect rect = option->rect.adjusted(offset, margin, 0, -margin);
- painter->setPen(QPen(option->palette.background().color().darker(110)));
- gtkPainter.paintVline( gtkSeparator, "vseparator",
- rect, GTK_STATE_NORMAL, gtkSeparator->style,
- 0, rect.height(), 0);
- } else { //Draw vertical separator
- const int offset = option->rect.height()/2;
- QRect rect = option->rect.adjusted(margin, offset, -margin, 0);
- painter->setPen(QPen(option->palette.background().color().darker(110)));
- gtkPainter.paintHline( gtkSeparator, "hseparator",
- rect, GTK_STATE_NORMAL, gtkSeparator->style,
- 0, rect.width(), 0);
- }
- }
- break;
-
- case PE_IndicatorToolBarHandle: {
- GtkWidget *gtkToolbar = d->gtkWidget("GtkToolbar");
- GtkShadowType shadow_type;
- d->gtk_widget_style_get(gtkToolbar, "shadow-type", &shadow_type, NULL);
- //Note when the toolbar is horizontal, the handle is vertical
- painter->setClipRect(option->rect);
- gtkPainter.paintHandle(gtkToolbar, "toolbar", option->rect.adjusted(-1, -1 ,0 ,1),
- GTK_STATE_NORMAL, shadow_type, !(option->state & State_Horizontal) ?
- GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, gtkToolbar->style);
- }
- break;
-
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowLeft:
- case PE_IndicatorArrowRight: {
-
-
- GtkArrowType type = GTK_ARROW_UP;
-
- switch (element) {
-
- case PE_IndicatorArrowDown:
- type = GTK_ARROW_DOWN;
- break;
-
- case PE_IndicatorArrowLeft:
- type = GTK_ARROW_LEFT;
- break;
-
- case PE_IndicatorArrowRight:
- type = GTK_ARROW_RIGHT;
- break;
-
- default:
- break;
- }
- int size = qMin(option->rect.height(), option->rect.width());
- int border = (size > 9) ? (size/4) : 0; //Allow small arrows to have exact dimensions
- int bsx = 0, bsy = 0;
- if (option->state & State_Sunken) {
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical);
- }
- QRect arrowRect = option->rect.adjusted(border + bsx, border + bsy, -border + bsx, -border + bsy);
- GtkShadowType shadow = option->state & State_Sunken ? GTK_SHADOW_IN : GTK_SHADOW_OUT;
- GtkStateType state = gtkPainter.gtkState(option);
-
- QColor arrowColor = option->palette.buttonText().color();
- GtkWidget *gtkArrow = d->gtkWidget("GtkArrow");
- GdkColor color = fromQColor(arrowColor);
- d->gtk_widget_modify_fg (gtkArrow, state, &color);
- gtkPainter.paintArrow(gtkArrow, "button", arrowRect,
- type, state, shadow, FALSE, gtkArrow->style,
- QString::number(arrowColor.rgba(), 16));
- // Passing NULL will revert the color change
- d->gtk_widget_modify_fg (gtkArrow, state, NULL);
- }
- break;
-
- case PE_FrameGroupBox:
- // Do nothing here, the GNOME groupboxes are flat
- break;
-
- case PE_PanelMenu: {
- GtkWidget *gtkMenu = d->gtkWidget("GtkMenu");
- gtkPainter.setAlphaSupport(false); // Note, alpha disabled for performance reasons
- gtkPainter.paintBox(gtkMenu, "menu", option->rect, GTK_STATE_NORMAL, GTK_SHADOW_OUT, gtkMenu->style, QString());
- }
- break;
-
- case PE_FrameMenu:
- //This is actually done by PE_Widget due to a clipping issue
- //Otherwise Menu items will not be able to span the entire menu width
-
- // This is only used by floating tool bars
- if (qobject_cast<const QToolBar *>(widget)) {
- GtkWidget *gtkMenubar = d->gtkWidget("GtkMenuBar");
- gtkPainter.paintBox( gtkMenubar, "toolbar", option->rect,
- GTK_STATE_NORMAL, GTK_SHADOW_OUT, style);
- gtkPainter.paintBox( gtkMenubar, "menu", option->rect,
- GTK_STATE_NORMAL, GTK_SHADOW_OUT, style);
- }
- break;
-
- case PE_FrameLineEdit: {
- GtkWidget *gtkEntry = d->gtkWidget("GtkEntry");
-
-
- gboolean interior_focus;
- gint focus_line_width;
- QRect rect = option->rect;
- d->gtk_widget_style_get(gtkEntry,
- "interior-focus", &interior_focus,
- "focus-line-width", &focus_line_width, NULL);
-
- // See https://bugzilla.mozilla.org/show_bug.cgi?id=405421 for info about this hack
- g_object_set_data(G_OBJECT(gtkEntry), "transparent-bg-hint", GINT_TO_POINTER(TRUE));
-
- if (!interior_focus && option->state & State_HasFocus)
- rect.adjust(focus_line_width, focus_line_width, -focus_line_width, -focus_line_width);
-
- if (option->state & State_HasFocus)
- GTK_WIDGET_SET_FLAGS(gtkEntry, GTK_HAS_FOCUS);
- gtkPainter.paintShadow(gtkEntry, "entry", rect, option->state & State_Enabled ?
- GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE,
- GTK_SHADOW_IN, gtkEntry->style,
- option->state & State_HasFocus ? QLS("focus") : QString());
- if (!interior_focus && option->state & State_HasFocus)
- gtkPainter.paintShadow(gtkEntry, "entry", option->rect, option->state & State_Enabled ?
- GTK_STATE_ACTIVE : GTK_STATE_INSENSITIVE,
- GTK_SHADOW_IN, gtkEntry->style, QLS("GtkEntryShadowIn"));
-
- if (option->state & State_HasFocus)
- GTK_WIDGET_UNSET_FLAGS(gtkEntry, GTK_HAS_FOCUS);
- }
- break;
-
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- GtkWidget *gtkEntry = d->gtkWidget("GtkEntry");
- if (panel->lineWidth > 0)
- proxy()->drawPrimitive(PE_FrameLineEdit, option, painter, widget);
- uint resolve_mask = option->palette.resolve();
- QRect textRect = option->rect.adjusted(gtkEntry->style->xthickness, gtkEntry->style->ythickness,
- -gtkEntry->style->xthickness, -gtkEntry->style->ythickness);
-
- if (widget && widget->testAttribute(Qt::WA_SetPalette) &&
- resolve_mask & (1 << QPalette::Base)) // Palette overridden by user
- painter->fillRect(textRect, option->palette.base());
- else
- gtkPainter.paintFlatBox( gtkEntry, "entry_bg", textRect,
- option->state & State_Enabled ? GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE, GTK_SHADOW_NONE, gtkEntry->style);
- }
- break;
-
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *frame = qstyleoption_cast<const QStyleOptionTabWidgetFrame*>(option)) {
- GtkWidget *gtkNotebook = d->gtkWidget("GtkNotebook");
- style = gtkPainter.getStyle(gtkNotebook);
- gtkPainter.setAlphaSupport(false);
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = GTK_STATE_NORMAL; // Only state supported by gtknotebook
- bool reverse = (option->direction == Qt::RightToLeft);
- QGtkStylePrivate::gtk_widget_set_direction(gtkNotebook, reverse ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR);
- if (const QStyleOptionTabWidgetFrameV2 *tabframe = qstyleoption_cast<const QStyleOptionTabWidgetFrameV2*>(option)) {
- GtkPositionType frameType = GTK_POS_TOP;
- QTabBar::Shape shape = frame->shape;
- int gapStart = 0;
- int gapSize = 0;
- if (shape == QTabBar::RoundedNorth || shape == QTabBar::RoundedSouth) {
- frameType = (shape == QTabBar::RoundedNorth) ? GTK_POS_TOP : GTK_POS_BOTTOM;
- gapStart = tabframe->selectedTabRect.left();
- gapSize = tabframe->selectedTabRect.width();
- } else {
- frameType = (shape == QTabBar::RoundedWest) ? GTK_POS_LEFT : GTK_POS_RIGHT;
- gapStart = tabframe->selectedTabRect.y();
- gapSize = tabframe->selectedTabRect.height();
- }
- gtkPainter.paintBoxGap(gtkNotebook, "notebook", option->rect, state, shadow, frameType,
- gapStart, gapSize, style);
- break; // done
- }
-
- // Note this is only the fallback option
- gtkPainter.paintBox(gtkNotebook, "notebook", option->rect, state, shadow, style);
- }
- break;
-
- case PE_PanelButtonCommand:
- case PE_PanelButtonTool: {
- bool isDefault = false;
- bool isTool = (element == PE_PanelButtonTool);
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton*>(option))
- isDefault = btn->features & QStyleOptionButton::DefaultButton;
-
- // don't draw a frame for tool buttons that have the autoRaise flag and are not enabled or on
- if (isTool && !(option->state & State_Enabled || option->state & State_On) && (option->state & State_AutoRaise))
- break;
- // don't draw a frame for dock widget buttons, unless we are hovering
- if (widget && widget->inherits("QDockWidgetTitleButton") && !(option->state & State_MouseOver))
- break;
-
- GtkStateType state = gtkPainter.gtkState(option);
- if (option->state & State_On || option->state & State_Sunken)
- state = GTK_STATE_ACTIVE;
- GtkWidget *gtkButton = isTool ? d->gtkWidget("GtkToolButton.GtkButton") : d->gtkWidget("GtkButton");
- gint focusWidth, focusPad;
- gboolean interiorFocus = false;
- d->gtk_widget_style_get (gtkButton,
- "focus-line-width", &focusWidth,
- "focus-padding", &focusPad,
- "interior-focus", &interiorFocus, NULL);
-
- style = gtkButton->style;
-
- QRect buttonRect = option->rect;
-
- QString key;
- if (isDefault) {
- key += QLS("def");
- GTK_WIDGET_SET_FLAGS(gtkButton, GTK_HAS_DEFAULT);
- gtkPainter.paintBox(gtkButton, "buttondefault", buttonRect, state, GTK_SHADOW_IN,
- style, isDefault ? QLS("d") : QString());
- }
-
- bool hasFocus = option->state & State_HasFocus;
-
- if (hasFocus) {
- key += QLS("def");
- GTK_WIDGET_SET_FLAGS(gtkButton, GTK_HAS_FOCUS);
- }
-
- if (!interiorFocus)
- buttonRect = buttonRect.adjusted(focusWidth, focusWidth, -focusWidth, -focusWidth);
-
- GtkShadowType shadow = (option->state & State_Sunken || option->state & State_On ) ?
- GTK_SHADOW_IN : GTK_SHADOW_OUT;
-
- gtkPainter.paintBox(gtkButton, "button", buttonRect, state, shadow,
- style, key);
- if (isDefault)
- GTK_WIDGET_UNSET_FLAGS(gtkButton, GTK_HAS_DEFAULT);
- if (hasFocus)
- GTK_WIDGET_UNSET_FLAGS(gtkButton, GTK_HAS_FOCUS);
- }
- break;
-
- case PE_IndicatorRadioButton: {
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = gtkPainter.gtkState(option);
-
- if (option->state & State_Sunken)
- state = GTK_STATE_ACTIVE;
-
- if (option->state & State_NoChange)
- shadow = GTK_SHADOW_ETCHED_IN;
- else if (option->state & State_On)
- shadow = GTK_SHADOW_IN;
- else
- shadow = GTK_SHADOW_OUT;
-
- GtkWidget *gtkRadioButton = d->gtkWidget("GtkRadioButton");
- gint spacing;
- d->gtk_widget_style_get(gtkRadioButton, "indicator-spacing", &spacing, NULL);
- QRect buttonRect = option->rect.adjusted(spacing, spacing, -spacing, -spacing);
- gtkPainter.setClipRect(option->rect);
- // ### Note: Ubuntulooks breaks when the proper widget is passed
- // Murrine engine requires a widget not to get RGBA check - warnings
- GtkWidget *gtkCheckButton = d->gtkWidget("GtkCheckButton");
- QString key(QLS("radiobutton"));
- if (option->state & State_HasFocus) { // Themes such as Nodoka check this flag
- key += QLatin1Char('f');
- GTK_WIDGET_SET_FLAGS(gtkCheckButton, GTK_HAS_FOCUS);
- }
- gtkPainter.paintOption(gtkCheckButton , buttonRect, state, shadow, gtkRadioButton->style, key);
- if (option->state & State_HasFocus)
- GTK_WIDGET_UNSET_FLAGS(gtkCheckButton, GTK_HAS_FOCUS);
- }
- break;
-
- case PE_IndicatorCheckBox: {
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = gtkPainter.gtkState(option);
-
- if (option->state & State_Sunken)
- state = GTK_STATE_ACTIVE;
-
- if (option->state & State_NoChange)
- shadow = GTK_SHADOW_ETCHED_IN;
- else if (option->state & State_On)
- shadow = GTK_SHADOW_IN;
- else
- shadow = GTK_SHADOW_OUT;
-
- int spacing;
-
- GtkWidget *gtkCheckButton = d->gtkWidget("GtkCheckButton");
- QString key(QLS("checkbutton"));
- if (option->state & State_HasFocus) { // Themes such as Nodoka checks this flag
- key += QLatin1Char('f');
- GTK_WIDGET_SET_FLAGS(gtkCheckButton, GTK_HAS_FOCUS);
- }
-
- // Some styles such as aero-clone assume they can paint in the spacing area
- gtkPainter.setClipRect(option->rect);
-
- d->gtk_widget_style_get(gtkCheckButton, "indicator-spacing", &spacing, NULL);
-
- QRect checkRect = option->rect.adjusted(spacing, spacing, -spacing, -spacing);
-
- gtkPainter.paintCheckbox(gtkCheckButton, checkRect, state, shadow, gtkCheckButton->style,
- key);
- if (option->state & State_HasFocus)
- GTK_WIDGET_UNSET_FLAGS(gtkCheckButton, GTK_HAS_FOCUS);
-
- }
- break;
-
-#ifndef QT_NO_TABBAR
-
- case PE_FrameTabBarBase:
- if (const QStyleOptionTabBarBase *tbb
- = qstyleoption_cast<const QStyleOptionTabBarBase *>(option)) {
- QRect tabRect = tbb->rect;
- painter->save();
- painter->setPen(QPen(option->palette.dark().color().dark(110), 0));
- switch (tbb->shape) {
-
- case QTabBar::RoundedNorth:
- painter->drawLine(tabRect.topLeft(), tabRect.topRight());
- break;
-
- case QTabBar::RoundedWest:
- painter->drawLine(tabRect.left(), tabRect.top(), tabRect.left(), tabRect.bottom());
- break;
-
- case QTabBar::RoundedSouth:
- painter->drawLine(tbb->rect.left(), tbb->rect.bottom(),
- tabRect.right(), tabRect.bottom());
- break;
-
- case QTabBar::RoundedEast:
- painter->drawLine(tabRect.topRight(), tabRect.bottomRight());
- break;
-
- case QTabBar::TriangularNorth:
- case QTabBar::TriangularEast:
- case QTabBar::TriangularWest:
- case QTabBar::TriangularSouth:
- painter->restore();
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- return;
- }
-
- painter->restore();
- }
- return;
-
-#endif // QT_NO_TABBAR
-
- case PE_Widget:
- break;
-
- default:
- QCleanlooksStyle::drawPrimitive(element, option, painter, widget);
- }
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
-
- QPainter *painter, const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable()) {
- QCleanlooksStyle::drawComplexControl(control, option, painter, widget);
- return;
- }
-
- GtkStyle* style = d->gtkStyle();
- QGtkPainter gtkPainter(painter);
- QColor button = option->palette.button().color();
- QColor dark;
- QColor grooveColor;
- QColor darkOutline;
- dark.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*1.9)),
- qMin(255, (int)(button.value()*0.7)));
- grooveColor.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*2.6)),
- qMin(255, (int)(button.value()*0.9)));
- darkOutline.setHsv(button.hue(),
- qMin(255, (int)(button.saturation()*3.0)),
- qMin(255, (int)(button.value()*0.6)));
-
- QColor alphaCornerColor;
-
- if (widget)
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), darkOutline);
- else
- alphaCornerColor = mergedColors(option->palette.background().color(), darkOutline);
-
- switch (control) {
-
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- // Since this is drawn by metacity and not Gtk we
- // have to rely on Cleanlooks for a fallback
- QStyleOptionTitleBar copyOpt = *tb;
- QPalette pal = copyOpt.palette;
- // Bg color is closer to the window selection than
- // the base selection color
- GdkColor gdkBg = style->bg[GTK_STATE_SELECTED];
- QColor bgColor(gdkBg.red>>8, gdkBg.green>>8, gdkBg.blue>>8);
- pal.setBrush(QPalette::Active, QPalette::Highlight, bgColor);
- copyOpt.palette = pal;
- QCleanlooksStyle::drawComplexControl(control, &copyOpt, painter, widget);
- }
- break;
-
-#ifndef QT_NO_GROUPBOX
-
- case CC_GroupBox:
- painter->save();
-
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- QRect textRect = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxLabel, widget);
- QRect checkBoxRect = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxCheckBox, widget);
- // Draw title
-
- if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
- // Draw prelight background
- GtkWidget *gtkCheckButton = d->gtkWidget("GtkCheckButton");
-
- if (option->state & State_MouseOver) {
- QRect bgRect = textRect | checkBoxRect;
- gtkPainter.paintFlatBox(gtkCheckButton, "checkbutton", bgRect.adjusted(0, 0, 0, -2),
- GTK_STATE_PRELIGHT, GTK_SHADOW_ETCHED_OUT, gtkCheckButton->style);
- }
-
- if (!groupBox->text.isEmpty()) {
- int alignment = int(groupBox->textAlignment);
- if (!proxy()->styleHint(QStyle::SH_UnderlineShortcut, option, widget))
- alignment |= Qt::TextHideMnemonic;
- QColor textColor = groupBox->textColor; // Note: custom textColor is currently ignored
- int labelState = GTK_STATE_INSENSITIVE;
-
- if (option->state & State_Enabled)
- labelState = (option->state & State_MouseOver) ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL;
-
- GdkColor gdkText = gtkCheckButton->style->fg[labelState];
- textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- painter->setPen(textColor);
- QFont font = painter->font();
- font.setBold(true);
- painter->setFont(font);
- painter->drawText(textRect, Qt::TextShowMnemonic | Qt::AlignLeft| alignment, groupBox->text);
-
- if (option->state & State_HasFocus)
- gtkPainter.paintFocus( NULL, "tab", textRect.adjusted(-4, -1, 0, -3), GTK_STATE_ACTIVE, style);
- }
- }
-
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*groupBox);
- box.rect = checkBoxRect;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &box, painter, widget);
- }
- }
-
- painter->restore();
- break;
-#endif // QT_NO_GROUPBOX
-
-#ifndef QT_NO_COMBOBOX
-
- case CC_ComboBox:
- // See: http://live.gnome.org/GnomeArt/Tutorials/GtkThemes/GtkComboBox
- // and http://live.gnome.org/GnomeArt/Tutorials/GtkThemes/GtkComboBoxEntry
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- bool sunken = comboBox->state & State_On; // play dead, if combobox has no items
- BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("cb-%0-%1").arg(sunken).arg(comboBox->editable));
- QGtkPainter gtkCachedPainter(p);
- gtkCachedPainter.setUsePixmapCache(false); // cached externally
-
- bool isEnabled = (comboBox->state & State_Enabled);
- bool focus = isEnabled && (comboBox->state & State_HasFocus);
- GtkStateType state = gtkPainter.gtkState(option);
- int appears_as_list = !proxy()->styleHint(QStyle::SH_ComboBox_Popup, comboBox, widget);
- QStyleOptionComboBox comboBoxCopy = *comboBox;
- comboBoxCopy.rect = option->rect;
-
- bool reverse = (option->direction == Qt::RightToLeft);
- QRect rect = option->rect;
- QRect arrowButtonRect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy,
- SC_ComboBoxArrow, widget);
-
- GtkShadowType shadow = (option->state & State_Sunken || option->state & State_On ) ?
- GTK_SHADOW_IN : GTK_SHADOW_OUT;
- const QHashableLatin1Literal comboBoxPath = comboBox->editable ? QHashableLatin1Literal("GtkComboBoxEntry") : QHashableLatin1Literal("GtkComboBox");
-
- // We use the gtk widget to position arrows and separators for us
- GtkWidget *gtkCombo = d->gtkWidget(comboBoxPath);
- GtkAllocation geometry = {0, 0, option->rect.width(), option->rect.height()};
- d->gtk_widget_set_direction(gtkCombo, reverse ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR);
- d->gtk_widget_size_allocate(gtkCombo, &geometry);
-
- QHashableLatin1Literal buttonPath = comboBox->editable ? QHashableLatin1Literal("GtkComboBoxEntry.GtkToggleButton")
- : QHashableLatin1Literal("GtkComboBox.GtkToggleButton");
- GtkWidget *gtkToggleButton = d->gtkWidget(buttonPath);
- d->gtk_widget_set_direction(gtkToggleButton, reverse ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR);
- if (gtkToggleButton && (appears_as_list || comboBox->editable)) {
- if (focus)
- GTK_WIDGET_SET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS);
- // Draw the combo box as a line edit with a button next to it
- if (comboBox->editable || appears_as_list) {
- GtkStateType frameState = (state == GTK_STATE_PRELIGHT) ? GTK_STATE_NORMAL : state;
- QHashableLatin1Literal entryPath = comboBox->editable ? QHashableLatin1Literal("GtkComboBoxEntry.GtkEntry") : QHashableLatin1Literal("GtkComboBox.GtkFrame");
- GtkWidget *gtkEntry = d->gtkWidget(entryPath);
- d->gtk_widget_set_direction(gtkEntry, reverse ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR);
- QRect frameRect = option->rect;
-
- if (reverse)
- frameRect.setLeft(arrowButtonRect.right());
- else
- frameRect.setRight(arrowButtonRect.left());
-
- // Fill the line edit background
- // We could have used flat_box with "entry_bg" but that is probably not worth the overhead
- uint resolve_mask = option->palette.resolve();
- int xt = gtkEntry->style->xthickness;
- int yt = gtkEntry->style->ythickness;
- QRect contentRect = frameRect.adjusted(xt, yt, -xt, -yt);
- // Required for inner blue highlight with clearlooks
- if (focus)
- GTK_WIDGET_SET_FLAGS(gtkEntry, GTK_HAS_FOCUS);
-
- if (widget && widget->testAttribute(Qt::WA_SetPalette) &&
- resolve_mask & (1 << QPalette::Base)) // Palette overridden by user
- p->fillRect(contentRect, option->palette.base().color());
- else {
- gtkCachedPainter.paintFlatBox(gtkEntry, "entry_bg", contentRect,
- option->state & State_Enabled ? GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE,
- GTK_SHADOW_NONE, gtkEntry->style, entryPath.toString() + QString::number(focus));
- }
-
- gtkCachedPainter.paintShadow(gtkEntry, comboBox->editable ? "entry" : "frame", frameRect, frameState,
- GTK_SHADOW_IN, gtkEntry->style, entryPath.toString() +
- QString::number(focus) + QString::number(comboBox->editable) +
- QString::number(option->direction));
- if (focus)
- GTK_WIDGET_UNSET_FLAGS(gtkEntry, GTK_HAS_FOCUS);
- }
-
- GtkStateType buttonState = GTK_STATE_NORMAL;
-
- if (!(option->state & State_Enabled))
- buttonState = GTK_STATE_INSENSITIVE;
- else if (option->state & State_Sunken || option->state & State_On)
- buttonState = GTK_STATE_ACTIVE;
- else if (option->state & State_MouseOver && comboBox->activeSubControls & SC_ComboBoxArrow)
- buttonState = GTK_STATE_PRELIGHT;
-
- Q_ASSERT(gtkToggleButton);
- gtkCachedPainter.paintBox( gtkToggleButton, "button", arrowButtonRect, buttonState,
- shadow, gtkToggleButton->style, buttonPath.toString() +
- QString::number(focus) + QString::number(option->direction));
- if (focus)
- GTK_WIDGET_UNSET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS);
- } else {
- // Draw combo box as a button
- QRect buttonRect = option->rect;
-
- if (focus) // Clearlooks actually check the widget for the default state
- GTK_WIDGET_SET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS);
- gtkCachedPainter.paintBox(gtkToggleButton, "button",
- buttonRect, state,
- shadow, gtkToggleButton->style,
- buttonPath.toString() + QString::number(focus));
- if (focus)
- GTK_WIDGET_UNSET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS);
-
-
- // Draw the separator between label and arrows
- QHashableLatin1Literal vSeparatorPath = comboBox->editable
- ? QHashableLatin1Literal("GtkComboBoxEntry.GtkToggleButton.GtkHBox.GtkVSeparator")
- : QHashableLatin1Literal("GtkComboBox.GtkToggleButton.GtkHBox.GtkVSeparator");
-
- if (GtkWidget *gtkVSeparator = d->gtkWidget(vSeparatorPath)) {
- QRect vLineRect(gtkVSeparator->allocation.x,
- gtkVSeparator->allocation.y,
- gtkVSeparator->allocation.width,
- gtkVSeparator->allocation.height);
-
- gtkCachedPainter.paintVline( gtkVSeparator, "vseparator",
- vLineRect, state, gtkVSeparator->style,
- 0, vLineRect.height(), 0, vSeparatorPath.toString());
-
-
- gint interiorFocus = true;
- d->gtk_widget_style_get(gtkToggleButton, "interior-focus", &interiorFocus, NULL);
- int xt = interiorFocus ? gtkToggleButton->style->xthickness : 0;
- int yt = interiorFocus ? gtkToggleButton->style->ythickness : 0;
- if (focus && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget)))
- gtkCachedPainter.paintFocus(gtkToggleButton, "button",
- option->rect.adjusted(xt, yt, -xt, -yt),
- option->state & State_Sunken ? GTK_STATE_ACTIVE : GTK_STATE_NORMAL,
- gtkToggleButton->style);
- }
- }
-
- if (comboBox->subControls & SC_ComboBoxArrow) {
- if (!isEnabled)
- state = GTK_STATE_INSENSITIVE;
- else if (sunken)
- state = GTK_STATE_ACTIVE;
- else if (option->state & State_MouseOver)
- state = GTK_STATE_PRELIGHT;
- else
- state = GTK_STATE_NORMAL;
-
- QHashableLatin1Literal arrowPath("");
- if (comboBox->editable) {
- if (appears_as_list)
- arrowPath = QHashableLatin1Literal("GtkComboBoxEntry.GtkToggleButton.GtkArrow");
- else
- arrowPath = QHashableLatin1Literal("GtkComboBoxEntry.GtkToggleButton.GtkHBox.GtkArrow");
- } else {
- if (appears_as_list)
- arrowPath = QHashableLatin1Literal("GtkComboBox.GtkToggleButton.GtkArrow");
- else
- arrowPath = QHashableLatin1Literal("GtkComboBox.GtkToggleButton.GtkHBox.GtkArrow");
- }
-
- GtkWidget *gtkArrow = d->gtkWidget(arrowPath);
- gfloat scale = 0.7;
- gint minSize = 15;
- QRect arrowWidgetRect;
-
- if (gtkArrow && !d->gtk_check_version(2, 12, 0)) {
- d->gtk_widget_style_get(gtkArrow, "arrow-scaling", &scale, NULL);
- d->gtk_widget_style_get(gtkCombo, "arrow-size", &minSize, NULL);
- }
- if (gtkArrow) {
- arrowWidgetRect = QRect(gtkArrow->allocation.x, gtkArrow->allocation.y,
- gtkArrow->allocation.width, gtkArrow->allocation.height);
- style = gtkArrow->style;
- }
-
- // Note that for some reason the arrow-size is not properly respected with Hildon
- // Hence we enforce the minimum "arrow-size" ourselves
- int arrowSize = qMax(qMin(rect.height() - gtkCombo->style->ythickness * 2, minSize),
- qMin(arrowWidgetRect.width(), arrowWidgetRect.height()));
- QRect arrowRect(0, 0, static_cast<int>(arrowSize * scale), static_cast<int>(arrowSize * scale));
-
- arrowRect.moveCenter(arrowWidgetRect.center());
-
- if (sunken) {
- int xoff, yoff;
- const QHashableLatin1Literal toggleButtonPath = comboBox->editable
- ? QHashableLatin1Literal("GtkComboBoxEntry.GtkToggleButton")
- : QHashableLatin1Literal("GtkComboBox.GtkToggleButton");
-
- GtkWidget *gtkButton = d->gtkWidget(toggleButtonPath);
- d->gtk_widget_style_get(gtkButton, "child-displacement-x", &xoff, NULL);
- d->gtk_widget_style_get(gtkButton, "child-displacement-y", &yoff, NULL);
- arrowRect = arrowRect.adjusted(xoff, yoff, xoff, yoff);
- }
-
- // Some styles such as Nimbus paint outside the arrowRect
- // hence we have provide the whole widget as the cliprect
- if (gtkArrow) {
- gtkCachedPainter.setClipRect(option->rect);
- gtkCachedPainter.paintArrow( gtkArrow, "arrow", arrowRect,
- GTK_ARROW_DOWN, state, GTK_SHADOW_NONE, TRUE,
- style, arrowPath.toString() + QString::number(option->direction));
- }
- }
- END_STYLE_PIXMAPCACHE;
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_TOOLBUTTON
-
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- QRect button, menuarea;
- button = proxy()->subControlRect(control, toolbutton, SC_ToolButton, widget);
- menuarea = proxy()->subControlRect(control, toolbutton, SC_ToolButtonMenu, widget);
- State bflags = toolbutton->state & ~(State_Sunken | State_MouseOver);
-
- if (bflags & State_AutoRaise)
- if (!(bflags & State_MouseOver))
- bflags &= ~State_Raised;
-
- State mflags = bflags;
-
- if (toolbutton->state & State_Sunken) {
- if (toolbutton->activeSubControls & SC_ToolButton)
- bflags |= State_Sunken;
- if (toolbutton->activeSubControls & SC_ToolButtonMenu)
- mflags |= State_Sunken;
- } else if (toolbutton->state & State_MouseOver) {
- if (toolbutton->activeSubControls & SC_ToolButton)
- bflags |= State_MouseOver;
- if (toolbutton->activeSubControls & SC_ToolButtonMenu)
- mflags |= State_MouseOver;
- }
-
- QStyleOption tool(0);
-
- tool.palette = toolbutton->palette;
-
- if (toolbutton->subControls & SC_ToolButton) {
- if (bflags & (State_Sunken | State_On | State_Raised | State_MouseOver)) {
- tool.rect = button;
- tool.state = bflags;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, painter, widget);
- }
- }
-
- bool drawMenuArrow = toolbutton->features & QStyleOptionToolButton::HasMenu &&
- !(toolbutton->features & QStyleOptionToolButton::MenuButtonPopup);
- int popupArrowSize = drawMenuArrow ? 7 : 0;
-
- if (toolbutton->state & State_HasFocus) {
- QStyleOptionFocusRect fr;
- fr.QStyleOption::operator=(*toolbutton);
- fr.rect = proxy()->subControlRect(CC_ToolButton, toolbutton, SC_ToolButton, widget);
- fr.rect.adjust(1, 1, -1, -1);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fr, painter, widget);
- }
-
- QStyleOptionToolButton label = *toolbutton;
- label.state = bflags;
- GtkWidget *gtkButton = d->gtkWidget("GtkToolButton.GtkButton");
- QPalette pal = toolbutton->palette;
- if (option->state & State_Enabled &&
- option->state & State_MouseOver && !(widget && widget->testAttribute(Qt::WA_SetPalette))) {
- GdkColor gdkText = gtkButton->style->fg[GTK_STATE_PRELIGHT];
- QColor textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- pal.setBrush(QPalette::All, QPalette::ButtonText, textColor);
- label.palette = pal;
- }
- label.rect = button.adjusted(style->xthickness, style->ythickness,
- -style->xthickness - popupArrowSize, -style->ythickness);
- proxy()->drawControl(CE_ToolButtonLabel, &label, painter, widget);
-
- if (toolbutton->subControls & SC_ToolButtonMenu) {
- tool.rect = menuarea;
- tool.state = mflags;
- if ((mflags & State_Enabled && (mflags & (State_Sunken | State_Raised | State_MouseOver))) || !(mflags & State_AutoRaise))
- proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, painter, widget);
-
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, painter, widget);
-
- } else if (drawMenuArrow) {
- QRect ir = toolbutton->rect;
- QStyleOptionToolButton newBtn = *toolbutton;
- newBtn.rect = QRect(ir.right() - popupArrowSize - style->xthickness - 3, ir.height()/2 - 1, popupArrowSize, popupArrowSize);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, painter, widget);
- }
- }
- break;
-
-#endif // QT_NO_TOOLBUTTON
-#ifndef QT_NO_SCROLLBAR
-
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- GtkWidget *gtkHScrollBar = d->gtkWidget("GtkHScrollbar");
- GtkWidget *gtkVScrollBar = d->gtkWidget("GtkVScrollbar");
-
- // Fill background in case the scrollbar is partially transparent
- painter->fillRect(option->rect, option->palette.background());
-
- QRect rect = scrollBar->rect;
- QRect scrollBarSubLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSubLine, widget);
- QRect scrollBarAddLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarAddLine, widget);
- QRect scrollBarSlider = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSlider, widget);
- QRect grooveRect = proxy()->subControlRect(control, scrollBar, SC_ScrollBarGroove, widget);
- bool horizontal = scrollBar->orientation == Qt::Horizontal;
- GtkWidget * scrollbarWidget = horizontal ? gtkHScrollBar : gtkVScrollBar;
- style = scrollbarWidget->style;
- gboolean trough_under_steppers = true;
- gboolean trough_side_details = false;
- gboolean activate_slider = false;
- gboolean stepper_size = 14;
- gint trough_border = 1;
- if (!d->gtk_check_version(2, 10, 0)) {
- d->gtk_widget_style_get((GtkWidget*)(scrollbarWidget),
- "trough-border", &trough_border,
- "trough-side-details", &trough_side_details,
- "trough-under-steppers", &trough_under_steppers,
- "activate-slider", &activate_slider,
- "stepper-size", &stepper_size, NULL);
- }
- if (trough_under_steppers) {
- scrollBarAddLine.adjust(trough_border, trough_border, -trough_border, -trough_border);
- scrollBarSubLine.adjust(trough_border, trough_border, -trough_border, -trough_border);
- scrollBarSlider.adjust(horizontal ? -trough_border : 0, horizontal ? 0 : -trough_border,
- horizontal ? trough_border : 0, horizontal ? 0 : trough_border);
- }
-
- // Some styles check the position of scrollbars in order to determine
- // if lines should be painted when the scrollbar is in max or min positions.
- int maximum = 2;
- int fakePos = 0;
- bool reverse = (option->direction == Qt::RightToLeft);
- if (scrollBar->minimum == scrollBar->maximum)
- maximum = 0;
- if (scrollBar->sliderPosition == scrollBar->maximum)
- fakePos = maximum;
- else if (scrollBar->sliderPosition > scrollBar->minimum)
- fakePos = maximum - 1;
-
-
- GtkRange *range = (GtkRange*)(horizontal ? gtkHScrollBar : gtkVScrollBar);
- GtkAdjustment *adjustment = d->gtk_range_get_adjustment(range);
-
- if (adjustment) {
- d->gtk_adjustment_configure(adjustment, fakePos, 0, maximum, 0, 0, 0);
- } else {
- adjustment = (GtkAdjustment*)d->gtk_adjustment_new(fakePos, 0, maximum, 0, 0, 0);
- d->gtk_range_set_adjustment(range, adjustment);
- }
-
- if (scrollBar->subControls & SC_ScrollBarGroove) {
- GtkStateType state = GTK_STATE_ACTIVE;
-
- if (!(option->state & State_Enabled))
- state = GTK_STATE_INSENSITIVE;
-
- if (trough_under_steppers)
- grooveRect = option->rect;
-
- gtkPainter.paintBox( scrollbarWidget, "trough", grooveRect, state, GTK_SHADOW_IN, style);
- }
-
- //paint slider
- if (scrollBar->subControls & SC_ScrollBarSlider) {
- GtkStateType state = GTK_STATE_NORMAL;
-
- if (!(option->state & State_Enabled))
- state = GTK_STATE_INSENSITIVE;
- else if (activate_slider &&
- option->state & State_Sunken && (scrollBar->activeSubControls & SC_ScrollBarSlider))
- state = GTK_STATE_ACTIVE;
- else if (option->state & State_MouseOver && (scrollBar->activeSubControls & SC_ScrollBarSlider))
- state = GTK_STATE_PRELIGHT;
-
- GtkShadowType shadow = GTK_SHADOW_OUT;
-
- if (trough_under_steppers) {
- if (!horizontal)
- scrollBarSlider.adjust(trough_border, 0, -trough_border, 0);
- else
- scrollBarSlider.adjust(0, trough_border, 0, -trough_border);
- }
-
- gtkPainter.paintSlider( scrollbarWidget, "slider", scrollBarSlider, state, shadow, style,
-
- horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, QString(QLS("%0%1")).arg(fakePos).arg(maximum));
- }
-
- if (scrollBar->subControls & SC_ScrollBarAddLine) {
- gtkVScrollBar->allocation.y = scrollBarAddLine.top();
- gtkVScrollBar->allocation.height = scrollBarAddLine.height() - rect.height() + 6;
- gtkHScrollBar->allocation.x = scrollBarAddLine.right();
- gtkHScrollBar->allocation.width = scrollBarAddLine.width() - rect.width();
-
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = GTK_STATE_NORMAL;
-
- if (!(option->state & State_Enabled) || (fakePos == maximum))
- state = GTK_STATE_INSENSITIVE;
- else if (option->state & State_Sunken && (scrollBar->activeSubControls & SC_ScrollBarAddLine)) {
- state = GTK_STATE_ACTIVE;
- shadow = GTK_SHADOW_IN;
-
- } else if (option->state & State_MouseOver && (scrollBar->activeSubControls & SC_ScrollBarAddLine))
- state = GTK_STATE_PRELIGHT;
-
- gtkPainter.paintBox( scrollbarWidget,
- horizontal ? "hscrollbar" : "vscrollbar", scrollBarAddLine,
- state, shadow, style, QLS("add"));
-
- gtkPainter.paintArrow( scrollbarWidget, horizontal ? "hscrollbar" : "vscrollbar", scrollBarAddLine.adjusted(4, 4, -4, -4),
- horizontal ? (reverse ? GTK_ARROW_LEFT : GTK_ARROW_RIGHT) :
- GTK_ARROW_DOWN, state, GTK_SHADOW_NONE, FALSE, style);
- }
-
- if (scrollBar->subControls & SC_ScrollBarSubLine) {
- gtkVScrollBar->allocation.y = 0;
- gtkVScrollBar->allocation.height = scrollBarSubLine.height();
- gtkHScrollBar->allocation.x = 0;
- gtkHScrollBar->allocation.width = scrollBarSubLine.width();
-
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = GTK_STATE_NORMAL;
-
- if (!(option->state & State_Enabled) || (fakePos == 0))
- state = GTK_STATE_INSENSITIVE;
- else if (option->state & State_Sunken && (scrollBar->activeSubControls & SC_ScrollBarSubLine)) {
- shadow = GTK_SHADOW_IN;
- state = GTK_STATE_ACTIVE;
-
- } else if (option->state & State_MouseOver && (scrollBar->activeSubControls & SC_ScrollBarSubLine))
- state = GTK_STATE_PRELIGHT;
-
- gtkPainter.paintBox(scrollbarWidget, horizontal ? "hscrollbar" : "vscrollbar", scrollBarSubLine,
- state, shadow, style, QLS("sub"));
-
- gtkPainter.paintArrow(scrollbarWidget, horizontal ? "hscrollbar" : "vscrollbar", scrollBarSubLine.adjusted(4, 4, -4, -4),
- horizontal ? (reverse ? GTK_ARROW_RIGHT : GTK_ARROW_LEFT) :
- GTK_ARROW_UP, state, GTK_SHADOW_NONE, FALSE, style);
- }
- }
- break;
-
-#endif //QT_NO_SCROLLBAR
-#ifndef QT_NO_SPINBOX
-
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
-
- GtkWidget *gtkSpinButton = spinBox->buttonSymbols == QAbstractSpinBox::NoButtons
- ? d->gtkWidget("GtkEntry")
- : d->gtkWidget("GtkSpinButton");
- bool isEnabled = (spinBox->state & State_Enabled);
- bool hover = isEnabled && (spinBox->state & State_MouseOver);
- bool sunken = (spinBox->state & State_Sunken);
- bool upIsActive = (spinBox->activeSubControls == SC_SpinBoxUp);
- bool downIsActive = (spinBox->activeSubControls == SC_SpinBoxDown);
- bool reverse = (spinBox->direction == Qt::RightToLeft);
-
- QRect editArea = option->rect;
- QRect editRect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxEditField, widget);
- QRect upRect, downRect, buttonRect;
- if (spinBox->buttonSymbols != QAbstractSpinBox::NoButtons) {
- upRect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxUp, widget);
- downRect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxDown, widget);
-
- //### Move this to subControlRect
- upRect.setTop(option->rect.top());
-
- if (reverse)
- upRect.setLeft(option->rect.left());
- else
- upRect.setRight(option->rect.right());
-
- downRect.setBottom(option->rect.bottom());
-
- if (reverse)
- downRect.setLeft(option->rect.left());
- else
- downRect.setRight(option->rect.right());
-
- buttonRect = upRect | downRect;
-
- if (reverse)
- editArea.setLeft(upRect.right());
- else
- editArea.setRight(upRect.left());
- }
- if (spinBox->frame) {
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = gtkPainter.gtkState(option);
-
- if (!(option->state & State_Enabled))
- state = GTK_STATE_INSENSITIVE;
- else if (option->state & State_HasFocus)
- state = GTK_STATE_NORMAL;
- else if (state == GTK_STATE_PRELIGHT)
- state = GTK_STATE_NORMAL;
-
- shadow = GTK_SHADOW_IN;
- style = gtkPainter.getStyle(gtkSpinButton);
-
-
- QString key;
-
- if (option->state & State_HasFocus) {
- key += QLatin1Char('f');
- GTK_WIDGET_SET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS);
- }
-
- uint resolve_mask = option->palette.resolve();
-
- if (resolve_mask & (1 << QPalette::Base)) // Palette overridden by user
- painter->fillRect(editRect, option->palette.base().color());
- else
- gtkPainter.paintFlatBox(gtkSpinButton, "entry_bg", editArea.adjusted(style->xthickness, style->ythickness,
- -style->xthickness, -style->ythickness),
- option->state & State_Enabled ?
- GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE, GTK_SHADOW_NONE, style, key);
-
- gtkPainter.paintShadow(gtkSpinButton, "entry", editArea, state, GTK_SHADOW_IN, gtkSpinButton->style, key);
- if (spinBox->buttonSymbols != QAbstractSpinBox::NoButtons) {
- gtkPainter.paintBox(gtkSpinButton, "spinbutton", buttonRect, state, GTK_SHADOW_IN, style, key);
-
- upRect.setSize(downRect.size());
- if (!(option->state & State_Enabled))
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_up", upRect, GTK_STATE_INSENSITIVE, GTK_SHADOW_IN, style, key);
- else if (upIsActive && sunken)
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_up", upRect, GTK_STATE_ACTIVE, GTK_SHADOW_IN, style, key);
- else if (upIsActive && hover)
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_up", upRect, GTK_STATE_PRELIGHT, GTK_SHADOW_OUT, style, key);
- else
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_up", upRect, GTK_STATE_NORMAL, GTK_SHADOW_OUT, style, key);
-
- if (!(option->state & State_Enabled))
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_down", downRect, GTK_STATE_INSENSITIVE, GTK_SHADOW_IN, style, key);
- else if (downIsActive && sunken)
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_down", downRect, GTK_STATE_ACTIVE, GTK_SHADOW_IN, style, key);
- else if (downIsActive && hover)
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_down", downRect, GTK_STATE_PRELIGHT, GTK_SHADOW_OUT, style, key);
- else
- gtkPainter.paintBox( gtkSpinButton, "spinbutton_down", downRect, GTK_STATE_NORMAL, GTK_SHADOW_OUT, style, key);
-
- if (option->state & State_HasFocus)
- GTK_WIDGET_UNSET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS);
- }
- }
-
- if (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) {
- int centerX = upRect.center().x();
- int centerY = upRect.center().y();
- // plus/minus
-
- if (spinBox->activeSubControls == SC_SpinBoxUp && sunken) {
- painter->drawLine(1 + centerX - 2, 1 + centerY, 1 + centerX + 2, 1 + centerY);
- painter->drawLine(1 + centerX, 1 + centerY - 2, 1 + centerX, 1 + centerY + 2);
-
- } else {
- painter->drawLine(centerX - 2, centerY, centerX + 2, centerY);
- painter->drawLine(centerX, centerY - 2, centerX, centerY + 2);
- }
- centerX = downRect.center().x();
- centerY = downRect.center().y();
-
- if (spinBox->activeSubControls == SC_SpinBoxDown && sunken) {
- painter->drawLine(1 + centerX - 2, 1 + centerY, 1 + centerX + 2, 1 + centerY);
- } else {
- painter->drawLine(centerX - 2, centerY, centerX + 2, centerY);
- }
-
- } else if (spinBox->buttonSymbols == QAbstractSpinBox::UpDownArrows) {
- int size = d->getSpinboxArrowSize();
- int w = size / 2 - 1;
- w -= w % 2 - 1; // force odd
- int h = (w + 1)/2;
- QRect arrowRect(0, 0, w, h);
- arrowRect.moveCenter(upRect.center());
- // arrows
- GtkStateType state = GTK_STATE_NORMAL;
-
- if (!(option->state & State_Enabled) || !(spinBox->stepEnabled & QAbstractSpinBox::StepUpEnabled))
- state = GTK_STATE_INSENSITIVE;
-
- gtkPainter.paintArrow( gtkSpinButton, "spinbutton", arrowRect, GTK_ARROW_UP, state,
- GTK_SHADOW_NONE, FALSE, style);
-
- arrowRect.moveCenter(downRect.center());
-
- if (!(option->state & State_Enabled) || !(spinBox->stepEnabled & QAbstractSpinBox::StepDownEnabled))
- state = GTK_STATE_INSENSITIVE;
-
- gtkPainter.paintArrow( gtkSpinButton, "spinbutton", arrowRect, GTK_ARROW_DOWN, state,
- GTK_SHADOW_NONE, FALSE, style);
- }
- }
- break;
-
-#endif // QT_NO_SPINBOX
-
-#ifndef QT_NO_SLIDER
-
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- GtkWidget *hScaleWidget = d->gtkWidget("GtkHScale");
- GtkWidget *vScaleWidget = d->gtkWidget("GtkVScale");
-
- QRect groove = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget);
- QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget);
-
- bool horizontal = slider->orientation == Qt::Horizontal;
- bool ticksAbove = slider->tickPosition & QSlider::TicksAbove;
- bool ticksBelow = slider->tickPosition & QSlider::TicksBelow;
-
- QBrush oldBrush = painter->brush();
- QPen oldPen = painter->pen();
-
- QColor shadowAlpha(Qt::black);
- shadowAlpha.setAlpha(10);
- QColor highlightAlpha(Qt::white);
- highlightAlpha.setAlpha(80);
-
- QGtkStylePrivate::gtk_widget_set_direction(hScaleWidget, slider->upsideDown ?
- GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR);
- GtkWidget *scaleWidget = horizontal ? hScaleWidget : vScaleWidget;
- style = scaleWidget->style;
-
- if ((option->subControls & SC_SliderGroove) && groove.isValid()) {
-
- GtkRange *range = (GtkRange*)scaleWidget;
- GtkAdjustment *adjustment = d->gtk_range_get_adjustment(range);
- if (adjustment) {
- d->gtk_adjustment_configure(adjustment,
- slider->sliderPosition,
- slider->minimum,
- slider->maximum,
- slider->singleStep,
- slider->singleStep,
- slider->pageStep);
- } else {
- adjustment = (GtkAdjustment*)d->gtk_adjustment_new(slider->sliderPosition,
- slider->minimum,
- slider->maximum,
- slider->singleStep,
- slider->singleStep,
- slider->pageStep);
- d->gtk_range_set_adjustment(range, adjustment);
- }
-
- int outerSize;
- d->gtk_range_set_inverted(range, !horizontal);
- d->gtk_widget_style_get(scaleWidget, "trough-border", &outerSize, NULL);
- outerSize++;
-
- GtkStateType state = gtkPainter.gtkState(option);
- int focusFrameMargin = 2;
- QRect grooveRect = option->rect.adjusted(focusFrameMargin, outerSize + focusFrameMargin,
- -focusFrameMargin, -outerSize - focusFrameMargin);
-
- gboolean trough_side_details = false; // Indicates if the upper or lower scale background differs
- if (!d->gtk_check_version(2, 10, 0))
- d->gtk_widget_style_get((GtkWidget*)(scaleWidget), "trough-side-details", &trough_side_details, NULL);
-
- if (!trough_side_details) {
- gtkPainter.paintBox( scaleWidget, "trough", grooveRect, state,
- GTK_SHADOW_IN, style, QString(QLS("p%0")).arg(slider->sliderPosition));
- } else {
- QRect upperGroove = grooveRect;
- QRect lowerGroove = grooveRect;
-
- if (horizontal) {
- if (slider->upsideDown) {
- lowerGroove.setLeft(handle.center().x());
- upperGroove.setRight(handle.center().x());
- } else {
- upperGroove.setLeft(handle.center().x());
- lowerGroove.setRight(handle.center().x());
- }
- } else {
- if (!slider->upsideDown) {
- lowerGroove.setBottom(handle.center().y());
- upperGroove.setTop(handle.center().y());
- } else {
- upperGroove.setBottom(handle.center().y());
- lowerGroove.setTop(handle.center().y());
- }
- }
-
- gtkPainter.paintBox( scaleWidget, "trough-upper", upperGroove, state,
- GTK_SHADOW_IN, style, QString(QLS("p%0")).arg(slider->sliderPosition));
- gtkPainter.paintBox( scaleWidget, "trough-lower", lowerGroove, state,
- GTK_SHADOW_IN, style, QString(QLS("p%0")).arg(slider->sliderPosition));
- }
- }
-
- if (option->subControls & SC_SliderTickmarks) {
- painter->setPen(darkOutline);
- int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
- int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
- int interval = slider->tickInterval;
-
- if (interval <= 0) {
- interval = slider->singleStep;
-
- if (QStyle::sliderPositionFromValue(slider->minimum, slider->maximum, interval,
- available)
- - QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- 0, available) < 3)
- interval = slider->pageStep;
- }
-
- if (interval <= 0)
- interval = 1;
-
- int v = slider->minimum;
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- while (v <= slider->maximum + 1) {
- if (v == slider->maximum + 1 && interval == 1)
- break;
- const int v_ = qMin(v, slider->maximum);
- int pos = sliderPositionFromValue(slider->minimum, slider->maximum,
- v_, (horizontal
- ? slider->rect.width()
- : slider->rect.height()) - len,
- slider->upsideDown) + len / 2;
- int extra = 2 - ((v_ == slider->minimum || v_ == slider->maximum) ? 1 : 0);
- if (horizontal) {
- if (ticksAbove)
- painter->drawLine(pos, slider->rect.top() + extra,
- pos, slider->rect.top() + tickSize);
- if (ticksBelow)
- painter->drawLine(pos, slider->rect.bottom() - extra,
- pos, slider->rect.bottom() - tickSize);
-
- } else {
- if (ticksAbove)
- painter->drawLine(slider->rect.left() + extra, pos,
- slider->rect.left() + tickSize, pos);
- if (ticksBelow)
- painter->drawLine(slider->rect.right() - extra, pos,
- slider->rect.right() - tickSize, pos);
- }
-
- // In the case where maximum is max int
- int nextInterval = v + interval;
- if (nextInterval < v)
- break;
- v = nextInterval;
- }
- }
-
- // Draw slider handle
- if (option->subControls & SC_SliderHandle) {
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = GTK_STATE_NORMAL;
-
- if (!(option->state & State_Enabled))
- state = GTK_STATE_INSENSITIVE;
- else if (option->state & State_MouseOver && option->activeSubControls & SC_SliderHandle)
- state = GTK_STATE_PRELIGHT;
-
- bool horizontal = option->state & State_Horizontal;
-
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = slider->rect.adjusted(-1, -1 ,1, 1);
-
- if (horizontal) {
- fropt.rect.setTop(handle.top() - 3);
- fropt.rect.setBottom(handle.bottom() + 4);
-
- } else {
- fropt.rect.setLeft(handle.left() - 3);
- fropt.rect.setRight(handle.right() + 3);
- }
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- gtkPainter.paintSlider( scaleWidget, horizontal ? "hscale" : "vscale", handle, state, shadow, style,
-
- horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL);
- }
- painter->setBrush(oldBrush);
- painter->setPen(oldPen);
- }
- break;
-
-#endif // QT_NO_SLIDER
-
- default:
- QCleanlooksStyle::drawComplexControl(control, option, painter, widget);
-
- break;
- }
-}
-
-
-/*!
- \reimp
-*/
-void QGtkStyle::drawControl(ControlElement element,
- const QStyleOption *option,
- QPainter *painter,
- const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable()) {
- QCleanlooksStyle::drawControl(element, option, painter, widget);
- return;
- }
-
- GtkStyle* style = d->gtkStyle();
- QGtkPainter gtkPainter(painter);
-
- switch (element) {
- case CE_ProgressBarLabel:
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- GtkWidget *gtkProgressBar = d->gtkWidget("GtkProgressBar");
- if (!gtkProgressBar)
- return;
-
- QRect leftRect;
- QRect rect = bar->rect;
- GdkColor gdkText = gtkProgressBar->style->fg[GTK_STATE_NORMAL];
- QColor textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- gdkText = gtkProgressBar->style->fg[GTK_STATE_PRELIGHT];
- QColor alternateTextColor= QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
-
- painter->save();
- bool vertical = false, inverted = false;
- if (const QStyleOptionProgressBarV2 *bar2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- vertical = (bar2->orientation == Qt::Vertical);
- inverted = bar2->invertedAppearance;
- }
- if (vertical)
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- const int progressIndicatorPos = (bar->progress - qreal(bar->minimum)) * rect.width() /
- qMax(qreal(1.0), qreal(bar->maximum) - bar->minimum);
- if (progressIndicatorPos >= 0 && progressIndicatorPos <= rect.width())
- leftRect = QRect(rect.left(), rect.top(), progressIndicatorPos, rect.height());
- if (vertical)
- leftRect.translate(rect.width() - progressIndicatorPos, 0);
-
- bool flip = (!vertical && (((bar->direction == Qt::RightToLeft) && !inverted) ||
- ((bar->direction == Qt::LeftToRight) && inverted)));
-
- QRegion rightRect = rect;
- rightRect = rightRect.subtracted(leftRect);
- painter->setClipRegion(rightRect);
- painter->setPen(flip ? alternateTextColor : textColor);
- painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
- if (!leftRect.isNull()) {
- painter->setPen(flip ? textColor : alternateTextColor);
- painter->setClipRect(leftRect);
- painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
- }
- painter->restore();
- }
- break;
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- QRect ir = button->rect;
- uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
- QPoint buttonShift;
-
- if (option->state & State_Sunken)
- buttonShift = QPoint(pixelMetric(PM_ButtonShiftHorizontal, option, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, option, widget));
-
- if (proxy()->styleHint(SH_UnderlineShortcut, button, widget))
- tf |= Qt::TextShowMnemonic;
- else
- tf |= Qt::TextHideMnemonic;
-
- if (!button->icon.isNull()) {
- //Center both icon and text
- QPoint point;
-
- QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- if (mode == QIcon::Normal && button->state & State_HasFocus)
- mode = QIcon::Active;
-
- QIcon::State state = QIcon::Off;
-
- if (button->state & State_On)
- state = QIcon::On;
-
- QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
- int w = pixmap.width();
- int h = pixmap.height();
-
- if (!button->text.isEmpty())
- w += button->fontMetrics.boundingRect(option->rect, tf, button->text).width() + 4;
-
- point = QPoint(ir.x() + ir.width() / 2 - w / 2,
- ir.y() + ir.height() / 2 - h / 2);
-
- if (button->direction == Qt::RightToLeft)
- point.rx() += pixmap.width();
-
- painter->drawPixmap(visualPos(button->direction, button->rect, point + buttonShift), pixmap);
-
- if (button->direction == Qt::RightToLeft)
- ir.translate(-point.x() - 2, 0);
- else
- ir.translate(point.x() + pixmap.width() + 2, 0);
-
- // left-align text if there is
- if (!button->text.isEmpty())
- tf |= Qt::AlignLeft;
-
- } else {
- tf |= Qt::AlignHCenter;
- }
-
- ir.translate(buttonShift);
-
- if (button->features & QStyleOptionButton::HasMenu)
- ir = ir.adjusted(0, 0, -pixelMetric(PM_MenuButtonIndicator, button, widget), 0);
-
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- QPalette pal = button->palette;
- int labelState = GTK_STATE_INSENSITIVE;
- if (option->state & State_Enabled)
- labelState = (option->state & State_MouseOver && !(option->state & State_Sunken)) ?
- GTK_STATE_PRELIGHT : GTK_STATE_NORMAL;
-
- GdkColor gdkText = gtkButton->style->fg[labelState];
- QColor textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- pal.setBrush(QPalette::ButtonText, textColor);
- proxy()->drawItemText(painter, ir, tf, pal, (button->state & State_Enabled),
- button->text, QPalette::ButtonText);
- }
- break;
-
- case CE_RadioButton: // Fall through
- case CE_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool isRadio = (element == CE_RadioButton);
-
- // Draw prelight background
- GtkWidget *gtkRadioButton = d->gtkWidget("GtkRadioButton");
-
- if (option->state & State_MouseOver) {
- gtkPainter.paintFlatBox(gtkRadioButton, "checkbutton", option->rect,
- GTK_STATE_PRELIGHT, GTK_SHADOW_ETCHED_OUT, gtkRadioButton->style);
- }
-
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, btn, widget);
- proxy()->drawPrimitive(isRadio ? PE_IndicatorRadioButton : PE_IndicatorCheckBox,
- &subopt, painter, widget);
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonContents
- : SE_CheckBoxContents, btn, widget);
- // Get label text color
- QPalette pal = subopt.palette;
- int labelState = GTK_STATE_INSENSITIVE;
- if (option->state & State_Enabled)
- labelState = (option->state & State_MouseOver) ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL;
-
- GdkColor gdkText = gtkRadioButton->style->fg[labelState];
- QColor textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- pal.setBrush(QPalette::WindowText, textColor);
- subopt.palette = pal;
- proxy()->drawControl(isRadio ? CE_RadioButtonLabel : CE_CheckBoxLabel, &subopt, painter, widget);
-
- if (btn->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*btn);
- fropt.rect = subElementRect(isRadio ? SE_RadioButtonFocusRect
- : SE_CheckBoxFocusRect, btn, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- }
- break;
-
-#ifndef QT_NO_COMBOBOX
-
- case CE_ComboBoxLabel:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- QRect editRect = proxy()->subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget);
- bool appearsAsList = !proxy()->styleHint(QStyle::SH_ComboBox_Popup, cb, widget);
- painter->save();
- painter->setClipRect(editRect);
-
- if (!cb->currentIcon.isNull()) {
- QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
- QRect iconRect(editRect);
- iconRect.setWidth(cb->iconSize.width() + 4);
-
- iconRect = alignedRect(cb->direction,
- Qt::AlignLeft | Qt::AlignVCenter,
- iconRect.size(), editRect);
-
- if (cb->editable)
- painter->fillRect(iconRect, option->palette.brush(QPalette::Base));
-
- proxy()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap);
-
- if (cb->direction == Qt::RightToLeft)
- editRect.translate(-4 - cb->iconSize.width(), 0);
- else
- editRect.translate(cb->iconSize.width() + 4, 0);
- }
-
- if (!cb->currentText.isEmpty() && !cb->editable) {
- GtkWidget *gtkCombo = d->gtkWidget("GtkComboBox");
- QPalette pal = cb->palette;
- int labelState = GTK_STATE_INSENSITIVE;
-
- if (option->state & State_Enabled)
- labelState = (option->state & State_MouseOver && !appearsAsList) ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL;
-
- GdkColor gdkText = gtkCombo->style->fg[labelState];
-
- QColor textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
-
- pal.setBrush(QPalette::ButtonText, textColor);
-
- proxy()->drawItemText(painter, editRect.adjusted(1, 0, -1, 0),
- visualAlignment(cb->direction, Qt::AlignLeft | Qt::AlignVCenter),
- pal, cb->state & State_Enabled, cb->currentText, QPalette::ButtonText);
- }
-
- painter->restore();
- }
- break;
-
-#endif // QT_NO_COMBOBOX
-
- case CE_DockWidgetTitle:
- painter->save();
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(option)) {
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- QRect rect = dwOpt->rect;
- QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, option, widget).adjusted(-2, 0, -2, 0);
- QRect r = rect.adjusted(0, 0, -1, -1);
- if (verticalTitleBar)
- r.adjust(0, 0, 0, -1);
-
- if (verticalTitleBar) {
- QRect r = rect;
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- titleRect = QRect(r.left() + rect.bottom()
- - titleRect.bottom(),
- r.top() + titleRect.left() - rect.left(),
- titleRect.height(), titleRect.width());
-
- painter->translate(r.left(), r.top() + r.width());
- painter->rotate(-90);
- painter->translate(-r.left(), -r.top());
-
- rect = r;
- }
-
- if (!dwOpt->title.isEmpty()) {
- QString titleText
- = painter->fontMetrics().elidedText(dwOpt->title,
- Qt::ElideRight, titleRect.width());
- proxy()->drawItemText(painter,
- titleRect,
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, dwOpt->palette,
- dwOpt->state & State_Enabled, titleText,
- QPalette::WindowText);
- }
- }
- painter->restore();
- break;
-
-
-
- case CE_HeaderSection:
- painter->save();
-
- // Draws the header in tables.
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- Q_UNUSED(header);
- GtkWidget *gtkTreeView = d->gtkWidget("GtkTreeView");
- // Get the middle column
- GtkTreeViewColumn *column = d->gtk_tree_view_get_column((GtkTreeView*)gtkTreeView, 1);
- Q_ASSERT(column);
-
- GtkWidget *gtkTreeHeader = column->button;
- GtkStateType state = gtkPainter.gtkState(option);
- GtkShadowType shadow = GTK_SHADOW_OUT;
-
- if (option->state & State_Sunken)
- shadow = GTK_SHADOW_IN;
-
- gtkPainter.paintBox(gtkTreeHeader, "button", option->rect.adjusted(-1, 0, 0, 0), state, shadow, gtkTreeHeader->style);
- }
-
- painter->restore();
- break;
-
-#ifndef QT_NO_SIZEGRIP
-
- case CE_SizeGrip: {
- GtkWidget *gtkStatusbar = d->gtkWidget("GtkStatusbar.GtkFrame");
- QRect gripRect = option->rect.adjusted(0, 0, -gtkStatusbar->style->xthickness, -gtkStatusbar->style->ythickness);
- gtkPainter.paintResizeGrip( gtkStatusbar, "statusbar", gripRect, GTK_STATE_NORMAL,
- GTK_SHADOW_OUT, QApplication::isRightToLeft() ?
- GDK_WINDOW_EDGE_SOUTH_WEST : GDK_WINDOW_EDGE_SOUTH_EAST,
- gtkStatusbar->style);
- }
- break;
-
-#endif // QT_NO_SIZEGRIP
-
- case CE_MenuBarEmptyArea: {
- GtkWidget *gtkMenubar = d->gtkWidget("GtkMenuBar");
- GdkColor gdkBg = gtkMenubar->style->bg[GTK_STATE_NORMAL]; // Theme can depend on transparency
- painter->fillRect(option->rect, QColor(gdkBg.red>>8, gdkBg.green>>8, gdkBg.blue>>8));
- if (widget) { // See CE_MenuBarItem
- QRect menuBarRect = widget->rect();
- QPixmap pixmap(menuBarRect.size());
- pixmap.fill(Qt::transparent);
- QPainter pmPainter(&pixmap);
- QGtkPainter gtkMenuBarPainter(&pmPainter);
- GtkShadowType shadow_type;
- d->gtk_widget_style_get(gtkMenubar, "shadow-type", &shadow_type, NULL);
- gtkMenuBarPainter.paintBox( gtkMenubar, "menubar", menuBarRect,
- GTK_STATE_NORMAL, shadow_type, gtkMenubar->style);
- pmPainter.end();
- painter->drawPixmap(option->rect, pixmap, option->rect);
- }
- }
- break;
-
- case CE_MenuBarItem:
- painter->save();
-
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- GtkWidget *gtkMenubarItem = d->gtkWidget("GtkMenuBar.GtkMenuItem");
- GtkWidget *gtkMenubar = d->gtkWidget("GtkMenuBar");
-
- style = gtkMenubarItem->style;
-
- if (widget) {
- // Since Qt does not currently allow filling the entire background
- // we use a hack for this by making a complete menubar each time and
- // paint with the correct offset inside it. Pixmap caching should resolve
- // most of the performance penalty.
- QRect menuBarRect = widget->rect();
- QPixmap pixmap(menuBarRect.size());
- pixmap.fill(Qt::transparent);
- QPainter pmPainter(&pixmap);
- QGtkPainter menubarPainter(&pmPainter);
- GtkShadowType shadow_type;
- d->gtk_widget_style_get(gtkMenubar, "shadow-type", &shadow_type, NULL);
- GdkColor gdkBg = gtkMenubar->style->bg[GTK_STATE_NORMAL]; // Theme can depend on transparency
- painter->fillRect(option->rect, QColor(gdkBg.red>>8, gdkBg.green>>8, gdkBg.blue>>8));
- menubarPainter.paintBox(gtkMenubar, "menubar", menuBarRect,
- GTK_STATE_NORMAL, shadow_type, gtkMenubar->style);
- pmPainter.end();
- painter->drawPixmap(option->rect, pixmap, option->rect);
- }
-
- QStyleOptionMenuItem item = *mbi;
- bool act = mbi->state & State_Selected && mbi->state & State_Sunken;
- bool dis = !(mbi->state & State_Enabled);
- item.rect = mbi->rect;
- GdkColor gdkText = gtkMenubarItem->style->fg[dis ? GTK_STATE_INSENSITIVE : GTK_STATE_NORMAL];
- GdkColor gdkHText = gtkMenubarItem->style->fg[GTK_STATE_PRELIGHT];
- QColor normalTextColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- QColor highlightedTextColor = QColor(gdkHText.red>>8, gdkHText.green>>8, gdkHText.blue>>8);
- item.palette.setBrush(QPalette::HighlightedText, highlightedTextColor);
- item.palette.setBrush(QPalette::Text, normalTextColor);
- item.palette.setBrush(QPalette::ButtonText, normalTextColor);
- QCommonStyle::drawControl(element, &item, painter, widget);
-
- if (act) {
- GtkShadowType shadowType = GTK_SHADOW_NONE;
- d->gtk_widget_style_get (gtkMenubarItem, "selected-shadow-type", &shadowType, NULL);
- gtkPainter.paintBox(gtkMenubarItem, "menuitem", option->rect.adjusted(0, 0, 0, 3),
- GTK_STATE_PRELIGHT, shadowType, gtkMenubarItem->style);
- //draw text
- QPalette::ColorRole textRole = dis ? QPalette::Text : QPalette::HighlightedText;
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
-
- if (!proxy()->styleHint(SH_UnderlineShortcut, mbi, widget))
- alignment |= Qt::TextHideMnemonic;
-
- proxy()->drawItemText(painter, item.rect, alignment, item.palette, mbi->state & State_Enabled, mbi->text, textRole);
- }
- }
- painter->restore();
- break;
-
- case CE_Splitter: {
- GtkWidget *gtkWindow = d->gtkWidget("GtkWindow"); // The Murrine Engine currently assumes a widget is passed
- gtkPainter.paintHandle(gtkWindow, "splitter", option->rect, gtkPainter.gtkState(option), GTK_SHADOW_NONE,
- !(option->state & State_Horizontal) ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL,
- style);
- }
- break;
-
-#ifndef QT_NO_TOOLBAR
-
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolbar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
- // Reserve the beveled appearance only for mainwindow toolbars
- if (!(widget && qobject_cast<const QMainWindow*> (widget->parentWidget())))
- break;
-
- QRect rect = option->rect;
- // There is a 1 pixel gap between toolbar lines in some styles (i.e Human)
- if (toolbar->positionWithinLine != QStyleOptionToolBar::End)
- rect.adjust(0, 0, 1, 0);
-
- GtkWidget *gtkToolbar = d->gtkWidget("GtkToolbar");
- GtkShadowType shadow_type = GTK_SHADOW_NONE;
- d->gtk_widget_style_get(gtkToolbar, "shadow-type", &shadow_type, NULL);
- gtkPainter.paintBox( gtkToolbar, "toolbar", rect,
- GTK_STATE_NORMAL, shadow_type, gtkToolbar->style);
- }
- break;
-
-#endif // QT_NO_TOOLBAR
-
- case CE_MenuItem:
- painter->save();
-
- // Draws one item in a popup menu.
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- const int windowsItemFrame = 2; // menu item frame width
- const int windowsItemHMargin = 3; // menu item hor text margin
- const int windowsItemVMargin = 26; // menu item ver text margin
- const int windowsRightBorder = 15; // right border on windows
- GtkWidget *gtkMenuItem = menuItem->checked ? d->gtkWidget("GtkMenu.GtkCheckMenuItem") :
- d->gtkWidget("GtkMenu.GtkMenuItem");
-
- style = gtkPainter.getStyle(gtkMenuItem);
- QColor shadow = option->palette.dark().color();
-
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
- GtkWidget *gtkMenuSeparator = d->gtkWidget("GtkMenu.GtkSeparatorMenuItem");
- painter->setPen(shadow.lighter(106));
- gboolean wide_separators = 0;
- gint separator_height = 0;
- guint horizontal_padding = 3;
- QRect separatorRect = option->rect;
- if (!d->gtk_check_version(2, 10, 0)) {
- d->gtk_widget_style_get(gtkMenuSeparator,
- "wide-separators", &wide_separators,
- "separator-height", &separator_height,
- "horizontal-padding", &horizontal_padding,
- NULL);
- }
- separatorRect.setHeight(option->rect.height() - 2 * gtkMenuSeparator->style->ythickness);
- separatorRect.setWidth(option->rect.width() - 2 * (horizontal_padding + gtkMenuSeparator->style->xthickness));
- separatorRect.moveCenter(option->rect.center());
- if (wide_separators)
- gtkPainter.paintBox( gtkMenuSeparator, "hseparator",
- separatorRect, GTK_STATE_NORMAL, GTK_SHADOW_NONE, gtkMenuSeparator->style);
- else
- gtkPainter.paintHline( gtkMenuSeparator, "hseparator",
- separatorRect, GTK_STATE_NORMAL, gtkMenuSeparator->style,
- 0, option->rect.right() - 1, 1);
- painter->restore();
- break;
- }
-
- bool selected = menuItem->state & State_Selected && menuItem->state & State_Enabled;
-
- if (selected) {
- QRect rect = option->rect;
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox*>(widget))
- rect = option->rect;
-#endif
- gtkPainter.paintBox( gtkMenuItem, "menuitem", rect, GTK_STATE_PRELIGHT, GTK_SHADOW_OUT, style);
- }
-
- bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
- bool checked = menuItem->checked;
- bool enabled = menuItem->state & State_Enabled;
- bool ignoreCheckMark = false;
-
- gint checkSize;
- d->gtk_widget_style_get(d->gtkWidget("GtkMenu.GtkCheckMenuItem"), "indicator-size", &checkSize, NULL);
-
- int checkcol = qMax(menuItem->maxIconWidth, qMax(20, checkSize));
-
-#ifndef QT_NO_COMBOBOX
-
- if (qobject_cast<const QComboBox*>(widget))
- ignoreCheckMark = true; // Ignore the checkmarks provided by the QComboMenuDelegate
-
-#endif
- if (!ignoreCheckMark) {
- // Check
- QRect checkRect(option->rect.left() + 7, option->rect.center().y() - checkSize/2 + 1, checkSize, checkSize);
- checkRect = visualRect(menuItem->direction, menuItem->rect, checkRect);
-
- if (checkable && menuItem->icon.isNull()) {
- // Some themes such as aero-clone draw slightly outside the paint rect
- int spacing = 1; // ### Consider using gtkCheckBox : "indicator-spacing" instead
-
- if (menuItem->checkType & QStyleOptionMenuItem::Exclusive) {
- // Radio button
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = gtkPainter.gtkState(option);
-
- if (selected)
- state = GTK_STATE_PRELIGHT;
- if (checked)
- shadow = GTK_SHADOW_IN;
-
- gtkPainter.setClipRect(checkRect.adjusted(-spacing, -spacing, spacing, spacing));
- gtkPainter.paintOption(gtkMenuItem, checkRect.translated(-spacing, -spacing), state, shadow,
- gtkMenuItem->style, QLS("option"));
- gtkPainter.setClipRect(QRect());
-
- } else {
- // Check box
- if (menuItem->icon.isNull()) {
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = gtkPainter.gtkState(option);
-
- if (selected)
- state = GTK_STATE_PRELIGHT;
- if (checked)
- shadow = GTK_SHADOW_IN;
-
- gtkPainter.setClipRect(checkRect.adjusted(-spacing, -spacing, -spacing, -spacing));
- gtkPainter.paintCheckbox(gtkMenuItem, checkRect.translated(-spacing, -spacing), state, shadow,
- gtkMenuItem->style, QLS("check"));
- gtkPainter.setClipRect(QRect());
- }
- }
- }
-
- } else {
- // Ignore checkmark
- if (menuItem->icon.isNull())
- checkcol = 0;
- else
- checkcol = menuItem->maxIconWidth;
- }
-
- bool dis = !(menuItem->state & State_Enabled);
- bool act = menuItem->state & State_Selected;
- const QStyleOption *opt = option;
- const QStyleOptionMenuItem *menuitem = menuItem;
- QPainter *p = painter;
- QRect vCheckRect = visualRect(opt->direction, menuitem->rect,
- QRect(menuitem->rect.x() + 3, menuitem->rect.y(),
- checkcol, menuitem->rect.height()));
-
- if (!menuItem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
-
- if (act && !dis)
- mode = QIcon::Active;
-
- QPixmap pixmap;
- int smallIconSize = proxy()->pixelMetric(PM_SmallIconSize, option, widget);
- QSize iconSize(smallIconSize, smallIconSize);
-
-#ifndef QT_NO_COMBOBOX
- if (const QComboBox *combo = qobject_cast<const QComboBox*>(widget))
- iconSize = combo->iconSize();
-
-#endif // QT_NO_COMBOBOX
- if (checked)
- pixmap = menuItem->icon.pixmap(iconSize, mode, QIcon::On);
- else
- pixmap = menuItem->icon.pixmap(iconSize, mode);
-
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vCheckRect.center() - QPoint(0, 1));
- painter->setPen(menuItem->palette.text().color());
- if (!ignoreCheckMark && checkable && checked) {
- QStyleOption opt = *option;
-
- if (act) {
- QColor activeColor = mergedColors(option->palette.background().color(),
- option->palette.highlight().color());
- opt.palette.setBrush(QPalette::Button, activeColor);
- }
- opt.state |= State_Sunken;
- opt.rect = vCheckRect;
- proxy()->drawPrimitive(PE_PanelButtonCommand, &opt, painter, widget);
- }
- painter->drawPixmap(pmr.topLeft(), pixmap);
- }
-
- GdkColor gdkText = gtkMenuItem->style->fg[GTK_STATE_NORMAL];
- GdkColor gdkDText = gtkMenuItem->style->fg[GTK_STATE_INSENSITIVE];
- GdkColor gdkHText = gtkMenuItem->style->fg[GTK_STATE_PRELIGHT];
- uint resolve_mask = option->palette.resolve();
- QColor textColor = QColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- QColor disabledTextColor = QColor(gdkDText.red>>8, gdkDText.green>>8, gdkDText.blue>>8);
- if (resolve_mask & (1 << QPalette::ButtonText)) {
- textColor = option->palette.buttonText().color();
- disabledTextColor = option->palette.brush(QPalette::Disabled, QPalette::ButtonText).color();
- }
-
- QColor highlightedTextColor = QColor(gdkHText.red>>8, gdkHText.green>>8, gdkHText.blue>>8);
- if (resolve_mask & (1 << QPalette::HighlightedText)) {
- highlightedTextColor = option->palette.highlightedText().color();
- }
-
- if (selected)
- painter->setPen(highlightedTextColor);
- else
- painter->setPen(textColor);
-
- int x, y, w, h;
- menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
- int xm = windowsItemFrame + checkcol + windowsItemHMargin;
- int xpos = menuitem->rect.x() + xm + 1;
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
- QString s = menuitem->text;
-
- if (!s.isEmpty()) { // Draw text
- p->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
-
- if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
-
- // Draw shortcut right aligned
- text_flags |= Qt::AlignRight;
-
- if (t >= 0) {
- int rightMargin = 12; // Hardcode for now
- QRect vShortcutRect = visualRect(opt->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right() - rightMargin, textRect.bottom())));
-
- if (dis)
- p->setPen(disabledTextColor);
- p->drawText(vShortcutRect, text_flags , s.mid(t + 1));
- s = s.left(t);
- }
-
- text_flags &= ~Qt::AlignRight;
- text_flags |= Qt::AlignLeft;
- QFont font = menuitem->font;
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
- p->setFont(font);
-
- if (dis)
- p->setPen(disabledTextColor);
- p->drawText(vTextRect, text_flags, s.left(t));
- p->restore();
- }
-
- // Arrow
- if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
-
- QFontMetrics fm(menuitem->font);
- int arrow_size = fm.ascent() + fm.descent() - 2 * gtkMenuItem->style->ythickness;
- gfloat arrow_scaling = 0.8;
- int extra = 0;
- if (!d->gtk_check_version(2, 16, 0)) {
- // "arrow-scaling" is actually hardcoded and fails on hardy (see gtk+-2.12/gtkmenuitem.c)
- // though the current documentation states otherwise
- d->gtk_widget_style_get(gtkMenuItem, "arrow-scaling", &arrow_scaling, NULL);
- // in versions < 2.16 ythickness was previously subtracted from the arrow_size
- extra = 2 * gtkMenuItem->style->ythickness;
- }
-
- int horizontal_padding;
- d->gtk_widget_style_get(gtkMenuItem, "horizontal-padding", &horizontal_padding, NULL);
-
- const int dim = static_cast<int>(arrow_size * arrow_scaling) + extra;
- int xpos = menuItem->rect.left() + menuItem->rect.width() - horizontal_padding - dim;
- QRect vSubMenuRect = visualRect(option->direction, menuItem->rect,
- QRect(xpos, menuItem->rect.top() +
- menuItem->rect.height() / 2 - dim / 2, dim, dim));
- GtkStateType state = enabled ? (act ? GTK_STATE_PRELIGHT: GTK_STATE_NORMAL) : GTK_STATE_INSENSITIVE;
- GtkShadowType shadowType = (state == GTK_STATE_PRELIGHT) ? GTK_SHADOW_OUT : GTK_SHADOW_IN;
- gtkPainter.paintArrow(gtkMenuItem, "menuitem", vSubMenuRect, QApplication::isRightToLeft() ? GTK_ARROW_LEFT : GTK_ARROW_RIGHT, state,
- shadowType, FALSE, style);
- }
- }
- painter->restore();
- break;
-
- case CE_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- proxy()->drawControl(CE_PushButtonBevel, btn, painter, widget);
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(SE_PushButtonContents, btn, widget);
- gint interiorFocus = true;
- d->gtk_widget_style_get(gtkButton, "interior-focus", &interiorFocus, NULL);
- int xt = interiorFocus ? gtkButton->style->xthickness : 0;
- int yt = interiorFocus ? gtkButton->style->ythickness : 0;
-
- if (btn->features & QStyleOptionButton::Flat && btn->state & State_HasFocus)
- // The normal button focus rect does not work well for flat buttons in Clearlooks
- proxy()->drawPrimitive(PE_FrameFocusRect, option, painter, widget);
- else if (btn->state & State_HasFocus)
- gtkPainter.paintFocus(gtkButton, "button",
- option->rect.adjusted(xt, yt, -xt, -yt),
- btn->state & State_Sunken ? GTK_STATE_ACTIVE : GTK_STATE_NORMAL,
- gtkButton->style);
-
- proxy()->drawControl(CE_PushButtonLabel, &subopt, painter, widget);
- }
- break;
-
-#ifndef QT_NO_TABBAR
-
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- GtkWidget *gtkNotebook = d->gtkWidget("GtkNotebook");
- style = gtkPainter.getStyle(gtkNotebook);
-
- QRect rect = option->rect;
- GtkShadowType shadow = GTK_SHADOW_OUT;
- GtkStateType state = GTK_STATE_ACTIVE;
- if (tab->state & State_Selected)
- state = GTK_STATE_NORMAL;
-
- bool selected = (tab->state & State_Selected);
- bool first = false, last = false;
- if (widget) {
- // This is most accurate and avoids resizing tabs while moving
- first = tab->rect.left() == widget->rect().left();
- last = tab->rect.right() == widget->rect().right();
- } else if (option->direction == Qt::RightToLeft) {
- bool tmp = first;
- first = last;
- last = tmp;
- }
- int topIndent = 3;
- int bottomIndent = 1;
- int tabOverlap = 1;
- painter->save();
-
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- if (!selected)
- rect.adjust(first ? 0 : -tabOverlap, topIndent, last ? 0 : tabOverlap, -bottomIndent);
- gtkPainter.paintExtention( gtkNotebook, "tab", rect,
- state, shadow, GTK_POS_BOTTOM, style);
- break;
-
- case QTabBar::RoundedSouth:
- if (!selected)
- rect.adjust(first ? 0 : -tabOverlap, 0, last ? 0 : tabOverlap, -topIndent);
- gtkPainter.paintExtention( gtkNotebook, "tab", rect.adjusted(0, 1, 0, 0),
- state, shadow, GTK_POS_TOP, style);
- break;
-
- case QTabBar::RoundedWest:
- if (!selected)
- rect.adjust(topIndent, 0, -bottomIndent, 0);
- gtkPainter.paintExtention( gtkNotebook, "tab", rect, state, shadow, GTK_POS_RIGHT, style);
- break;
-
- case QTabBar::RoundedEast:
- if (!selected)
- rect.adjust(bottomIndent, 0, -topIndent, 0);
- gtkPainter.paintExtention( gtkNotebook, "tab", rect, state, shadow, GTK_POS_LEFT, style);
- break;
-
- default:
- QCleanlooksStyle::drawControl(element, option, painter, widget);
- break;
- }
-
- painter->restore();
- }
-
- break;
-
-#endif //QT_NO_TABBAR
-
- case CE_ProgressBarGroove:
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- Q_UNUSED(bar);
- GtkWidget *gtkProgressBar = d->gtkWidget("GtkProgressBar");
- GtkStateType state = gtkPainter.gtkState(option);
- gtkPainter.paintBox( gtkProgressBar, "trough", option->rect, state, GTK_SHADOW_IN, gtkProgressBar->style);
- }
-
- break;
-
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- GtkStateType state = option->state & State_Enabled ? GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE;
- GtkWidget *gtkProgressBar = d->gtkWidget("GtkProgressBar");
- style = gtkProgressBar->style;
- gtkPainter.paintBox( gtkProgressBar, "trough", option->rect, state, GTK_SHADOW_IN, style);
- int xt = style->xthickness;
- int yt = style->ythickness;
- QRect rect = bar->rect.adjusted(xt, yt, -xt, -yt);
- bool vertical = false;
- bool inverted = false;
- bool indeterminate = (bar->minimum == 0 && bar->maximum == 0);
- // Get extra style options if version 2
-
- if (const QStyleOptionProgressBarV2 *bar2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- vertical = (bar2->orientation == Qt::Vertical);
- inverted = bar2->invertedAppearance;
- }
-
- // If the orientation is vertical, we use a transform to rotate
- // the progress bar 90 degrees clockwise. This way we can use the
- // same rendering code for both orientations.
- if (vertical) {
- rect.translate(xt, -yt * 2);
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // Flip width and height
- QTransform m = QTransform::fromTranslate(rect.height(), 0);
- m.rotate(90.0);
- painter->setTransform(m);
- }
-
- int maxWidth = rect.width();
- int minWidth = 4;
-
- qint64 progress = (qint64)qMax(bar->progress, bar->minimum); // Workaround for bug in QProgressBar
- double vc6_workaround = ((progress - qint64(bar->minimum)) / double(qint64(bar->maximum) - qint64(bar->minimum))) * maxWidth;
- int progressBarWidth = (int(vc6_workaround) > minWidth ) ? int(vc6_workaround) : minWidth;
- int width = indeterminate ? maxWidth : progressBarWidth;
- bool reverse = (!vertical && (bar->direction == Qt::RightToLeft)) || vertical;
-
- if (inverted)
- reverse = !reverse;
-
- int maximum = 2;
- int fakePos = 0;
- if (bar->minimum == bar->maximum)
- maximum = 0;
- if (bar->progress == bar->maximum)
- fakePos = maximum;
- else if (bar->progress > bar->minimum)
- fakePos = maximum - 1;
-
- d->gtk_progress_configure((GtkProgress*)gtkProgressBar, fakePos, 0, maximum);
-
- QRect progressBar;
-
- if (!indeterminate) {
- if (!reverse)
- progressBar.setRect(rect.left(), rect.top(), width, rect.height());
- else
- progressBar.setRect(rect.right() - width, rect.top(), width, rect.height());
-
- } else {
- Q_D(const QGtkStyle);
- int slideWidth = ((rect.width() - 4) * 2) / 3;
- int step = ((d->animateStep * slideWidth) / d->animationFps) % slideWidth;
- if ((((d->animateStep * slideWidth) / d->animationFps) % (2 * slideWidth)) >= slideWidth)
- step = slideWidth - step;
- progressBar.setRect(rect.left() + step, rect.top(), slideWidth / 2, rect.height());
- }
-
- QString key = QString(QLS("%0")).arg(fakePos);
- if (inverted) {
- key += QLatin1String("inv");
- gtkPainter.setFlipHorizontal(true);
- }
- gtkPainter.paintBox( gtkProgressBar, "bar", progressBar, GTK_STATE_SELECTED, GTK_SHADOW_OUT, style, key);
- }
-
- break;
-
- default:
- QCleanlooksStyle::drawControl(element, option, painter, widget);
- }
-}
-
-/*!
- \reimp
-*/
-QRect QGtkStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- QRect rect = QWindowsStyle::subControlRect(control, option, subControl, widget);
- if (!d->isThemeAvailable())
- return QCleanlooksStyle::subControlRect(control, option, subControl, widget);
-
- switch (control) {
- case CC_TitleBar:
- return QCleanlooksStyle::subControlRect(control, option, subControl, widget);
-
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- // Reserve space for outside focus rect
- QStyleOptionSlider sliderCopy = *slider;
- sliderCopy.rect = option->rect.adjusted(2, 2, -2, -2);
- return QCleanlooksStyle::subControlRect(control, &sliderCopy, subControl, widget);
- }
-
- break;
-
-#ifndef QT_NO_GROUPBOX
-
- case CC_GroupBox:
- if (qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- rect = option->rect.adjusted(0, groupBoxTopMargin, 0, -groupBoxBottomMargin);
- int topMargin = 0;
- int topHeight = 0;
- topHeight = 10;
- QRect frameRect = rect;
- frameRect.setTop(topMargin);
-
- if (subControl == SC_GroupBoxFrame)
- return rect;
- else if (subControl == SC_GroupBoxContents) {
- int margin = 0;
- int leftMarginExtension = 8;
- return frameRect.adjusted(leftMarginExtension + margin, margin + topHeight + groupBoxTitleMargin, -margin, -margin);
- }
-
- if (const QGroupBox *groupBoxWidget = qobject_cast<const QGroupBox *>(widget)) {
- //Prepare metrics for a bold font
- QFont font = widget->font();
- font.setBold(true);
- QFontMetrics fontMetrics(font);
- QSize textRect = fontMetrics.boundingRect(groupBoxWidget->title()).size() + QSize(4, 4);
- int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, option, widget);
- int indicatorHeight = proxy()->pixelMetric(PM_IndicatorHeight, option, widget);
-
- if (subControl == SC_GroupBoxCheckBox) {
- rect.setWidth(indicatorWidth);
- rect.setHeight(indicatorHeight);
- rect.moveTop((textRect.height() - indicatorHeight) / 2);
-
- } else if (subControl == SC_GroupBoxLabel) {
- if (groupBoxWidget->isCheckable())
- rect.adjust(indicatorWidth + 4, 0, 0, 0);
- rect.setSize(textRect);
- }
- rect = visualRect(option->direction, option->rect, rect);
- }
- }
-
- return rect;
-
-#endif
-#ifndef QT_NO_SPINBOX
-
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- GtkWidget *gtkSpinButton = d->gtkWidget("GtkSpinButton");
- int center = spinbox->rect.height() / 2;
- int xt = spinbox->frame ? gtkSpinButton->style->xthickness : 0;
- int yt = spinbox->frame ? gtkSpinButton->style->ythickness : 0;
- int y = yt;
-
- QSize bs;
- bs.setHeight(qMax(8, spinbox->rect.height()/2 - y));
- bs.setWidth(d->getSpinboxArrowSize());
- int x, lx, rx;
- x = spinbox->rect.width() - y - bs.width() + 2;
- lx = xt;
- rx = x - xt;
-
- switch (subControl) {
-
- case SC_SpinBoxUp:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- rect = QRect(x, xt, bs.width(), center - yt);
- break;
-
- case SC_SpinBoxDown:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- rect = QRect(x, center, bs.width(), spinbox->rect.bottom() - center - yt + 1);
- break;
-
- case SC_SpinBoxEditField:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- rect = QRect(lx, yt, spinbox->rect.width() - 2*xt, spinbox->rect.height() - 2*yt);
- else
- rect = QRect(lx, yt, rx - qMax(xt - 1, 0), spinbox->rect.height() - 2*yt);
- break;
-
- case SC_SpinBoxFrame:
- rect = spinbox->rect;
-
- default:
- break;
- }
-
- rect = visualRect(spinbox->direction, spinbox->rect, rect);
- }
-
- break;
-
-#endif // Qt_NO_SPINBOX
-#ifndef QT_NO_COMBOBOX
-
- case CC_ComboBox:
- if (const QStyleOptionComboBox *box = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- // We employ the gtk widget to position arrows and separators for us
- GtkWidget *gtkCombo = box->editable ? d->gtkWidget("GtkComboBoxEntry")
- : d->gtkWidget("GtkComboBox");
- d->gtk_widget_set_direction(gtkCombo, (option->direction == Qt::RightToLeft) ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR);
- GtkAllocation geometry = {0, 0, qMax(0, option->rect.width()), qMax(0, option->rect.height())};
- d->gtk_widget_size_allocate(gtkCombo, &geometry);
- int appears_as_list = !proxy()->styleHint(QStyle::SH_ComboBox_Popup, option, widget);
- QHashableLatin1Literal arrowPath("GtkComboBoxEntry.GtkToggleButton");
- if (!box->editable) {
- if (appears_as_list)
- arrowPath = "GtkComboBox.GtkToggleButton";
- else
- arrowPath = "GtkComboBox.GtkToggleButton.GtkHBox.GtkArrow";
- }
-
- GtkWidget *arrowWidget = d->gtkWidget(arrowPath);
- if (!arrowWidget)
- return QCleanlooksStyle::subControlRect(control, option, subControl, widget);
-
- QRect buttonRect(option->rect.left() + arrowWidget->allocation.x,
- option->rect.top() + arrowWidget->allocation.y,
- arrowWidget->allocation.width, arrowWidget->allocation.height);
-
- switch (subControl) {
-
- case SC_ComboBoxArrow: // Note: this indicates the arrowbutton for editable combos
- rect = buttonRect;
- break;
-
- case SC_ComboBoxEditField: {
- rect = visualRect(option->direction, option->rect, rect);
- int xMargin = box->editable ? 1 : 4, yMargin = 2;
- rect.setRect(option->rect.left() + gtkCombo->style->xthickness + xMargin,
- option->rect.top() + gtkCombo->style->ythickness + yMargin,
- option->rect.width() - buttonRect.width() - 2*(gtkCombo->style->xthickness + xMargin),
- option->rect.height() - 2*(gtkCombo->style->ythickness + yMargin));
- rect = visualRect(option->direction, option->rect, rect);
- break;
- }
-
- default:
- break;
- }
- }
-
- break;
-
-#endif // QT_NO_COMBOBOX
-
- default:
- break;
- }
-
- return rect;
-}
-
-/*!
- \reimp
-*/
-QSize QGtkStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- QSize newSize = QCleanlooksStyle::sizeFromContents(type, option, size, widget);
- if (!d->isThemeAvailable())
- return newSize;
-
- switch (type) {
-
- case CT_ToolButton:
- if (const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- GtkWidget *gtkButton = d->gtkWidget("GtkToolButton.GtkButton");
- newSize = size + QSize(2 * gtkButton->style->xthickness, 2 + 2 * gtkButton->style->ythickness);
- if (widget && qobject_cast<QToolBar *>(widget->parentWidget())) {
- QSize minSize(0, 25);
- if (toolbutton->toolButtonStyle != Qt::ToolButtonTextOnly)
- minSize = toolbutton->iconSize + QSize(12, 12);
- newSize = newSize.expandedTo(minSize);
- }
-
- if (toolbutton->features & QStyleOptionToolButton::HasMenu)
- newSize += QSize(6, 0);
- }
- break;
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- int textMargin = 8;
-
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
- GtkWidget *gtkMenuSeparator = d->gtkWidget("GtkMenu.GtkSeparatorMenuItem");
- GtkRequisition sizeReq = {0, 0};
- d->gtk_widget_size_request(gtkMenuSeparator, &sizeReq);
- newSize = QSize(size.width(), sizeReq.height);
- break;
- }
-
- GtkWidget *gtkMenuItem = d->gtkWidget("GtkMenu.GtkCheckMenuItem");
- GtkStyle* style = gtkMenuItem->style;
-
- // Note we get the perfect height for the default font since we
- // set a fake text label on the gtkMenuItem
- // But if custom fonts are used on the widget we need a minimum size
- GtkRequisition sizeReq = {0, 0};
- d->gtk_widget_size_request(gtkMenuItem, &sizeReq);
- newSize.setHeight(qMax(newSize.height() - 4, sizeReq.height));
- newSize += QSize(textMargin + style->xthickness - 1, 0);
-
- // Cleanlooks assumes a check column of 20 pixels so we need to
- // expand it a bit
- gint checkSize;
- d->gtk_widget_style_get(gtkMenuItem, "indicator-size", &checkSize, NULL);
- newSize.setWidth(newSize.width() + qMax(0, checkSize - 20));
- }
-
- break;
-
- case CT_SpinBox:
- // QSpinBox does some nasty things that depends on CT_LineEdit
- newSize = size + QSize(0, -d->gtkWidget("GtkSpinButton")->style->ythickness * 2);
- break;
-
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- gint focusPadding, focusWidth;
- d->gtk_widget_style_get(gtkButton, "focus-padding", &focusPadding, NULL);
- d->gtk_widget_style_get(gtkButton, "focus-line-width", &focusWidth, NULL);
- newSize = size;
- newSize += QSize(2*gtkButton->style->xthickness + 4, 2*gtkButton->style->ythickness);
- newSize += QSize(2*(focusWidth + focusPadding + 2), 2*(focusWidth + focusPadding));
-
- GtkWidget *gtkButtonBox = d->gtkWidget("GtkHButtonBox");
- gint minWidth = 85, minHeight = 0;
- d->gtk_widget_style_get(gtkButtonBox, "child-min-width", &minWidth,
- "child-min-height", &minHeight, NULL);
- if (!btn->text.isEmpty() && newSize.width() < minWidth)
- newSize.setWidth(minWidth);
- if (newSize.height() < minHeight)
- newSize.setHeight(minHeight);
- }
-
- break;
-
- case CT_Slider: {
- GtkWidget *gtkSlider = d->gtkWidget("GtkHScale");
- newSize = size + QSize(2*gtkSlider->style->xthickness, 2*gtkSlider->style->ythickness);
- }
- break;
-
- case CT_LineEdit: {
- GtkWidget *gtkEntry = d->gtkWidget("GtkEntry");
- newSize = size + QSize(2*gtkEntry->style->xthickness, 2 + 2*gtkEntry->style->ythickness);
- }
- break;
-
- case CT_ItemViewItem:
- newSize += QSize(0, 2);
- break;
-
- case CT_ComboBox:
- if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- GtkWidget *gtkCombo = d->gtkWidget("GtkComboBox");
- QRect arrowButtonRect = proxy()->subControlRect(CC_ComboBox, combo, SC_ComboBoxArrow, widget);
- newSize = size + QSize(12 + arrowButtonRect.width() + 2*gtkCombo->style->xthickness, 4 + 2*gtkCombo->style->ythickness);
-
- if (!(widget && qobject_cast<QToolBar *>(widget->parentWidget())))
- newSize += QSize(0, 2);
- }
- break;
-
- case CT_GroupBox:
- newSize += QSize(4, groupBoxBottomMargin + groupBoxTopMargin + groupBoxTitleMargin); // Add some space below the groupbox
- break;
-
- case CT_TabBarTab:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- if (!tab->icon.isNull())
- newSize += QSize(6, 0);
- }
- newSize += QSize(1, 1);
- break;
-
- default:
- break;
- }
-
- return newSize;
-}
-
-
-/*! \reimp */
-QPixmap QGtkStyle::standardPixmap(StandardPixmap sp, const QStyleOption *option,
- const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable())
- return QCleanlooksStyle::standardPixmap(sp, option, widget);
-
- QPixmap pixmap;
- switch (sp) {
-
- case SP_TitleBarNormalButton: {
- QImage restoreButton((const char **)dock_widget_restore_xpm);
- QColor alphaCorner = restoreButton.color(2);
- alphaCorner.setAlpha(80);
- restoreButton.setColor(2, alphaCorner.rgba());
- alphaCorner.setAlpha(180);
- restoreButton.setColor(4, alphaCorner.rgba());
- return QPixmap::fromImage(restoreButton);
- }
- break;
-
- case SP_TitleBarCloseButton: // Fall through
- case SP_DockWidgetCloseButton: {
-
- QImage closeButton((const char **)dock_widget_close_xpm);
- QColor alphaCorner = closeButton.color(2);
- alphaCorner.setAlpha(80);
- closeButton.setColor(2, alphaCorner.rgba());
- return QPixmap::fromImage(closeButton);
- }
- break;
-
- case SP_DialogDiscardButton:
- return QGtkPainter::getIcon(GTK_STOCK_DELETE);
- case SP_DialogOkButton:
- return QGtkPainter::getIcon(GTK_STOCK_OK);
- case SP_DialogCancelButton:
- return QGtkPainter::getIcon(GTK_STOCK_CANCEL);
- case SP_DialogYesButton:
- return QGtkPainter::getIcon(GTK_STOCK_YES);
- case SP_DialogNoButton:
- return QGtkPainter::getIcon(GTK_STOCK_NO);
- case SP_DialogOpenButton:
- return QGtkPainter::getIcon(GTK_STOCK_OPEN);
- case SP_DialogCloseButton:
- return QGtkPainter::getIcon(GTK_STOCK_CLOSE);
- case SP_DialogApplyButton:
- return QGtkPainter::getIcon(GTK_STOCK_APPLY);
- case SP_DialogSaveButton:
- return QGtkPainter::getIcon(GTK_STOCK_SAVE);
- case SP_MessageBoxWarning:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
- case SP_MessageBoxQuestion:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
- case SP_MessageBoxInformation:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
- case SP_MessageBoxCritical:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
- default:
- return QCleanlooksStyle::standardPixmap(sp, option, widget);
- }
- return pixmap;
-}
-
-/*!
- \internal
-*/
-QIcon QGtkStyle::standardIconImplementation(StandardPixmap standardIcon,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- if (!d->isThemeAvailable())
- return QCleanlooksStyle::standardIconImplementation(standardIcon, option, widget);
- switch (standardIcon) {
- case SP_DialogDiscardButton:
- return QGtkPainter::getIcon(GTK_STOCK_DELETE);
- case SP_DialogOkButton:
- return QGtkPainter::getIcon(GTK_STOCK_OK);
- case SP_DialogCancelButton:
- return QGtkPainter::getIcon(GTK_STOCK_CANCEL);
- case SP_DialogYesButton:
- return QGtkPainter::getIcon(GTK_STOCK_YES);
- case SP_DialogNoButton:
- return QGtkPainter::getIcon(GTK_STOCK_NO);
- case SP_DialogOpenButton:
- return QGtkPainter::getIcon(GTK_STOCK_OPEN);
- case SP_DialogCloseButton:
- return QGtkPainter::getIcon(GTK_STOCK_CLOSE);
- case SP_DialogApplyButton:
- return QGtkPainter::getIcon(GTK_STOCK_APPLY);
- case SP_DialogSaveButton:
- return QGtkPainter::getIcon(GTK_STOCK_SAVE);
- case SP_MessageBoxWarning:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
- case SP_MessageBoxQuestion:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
- case SP_MessageBoxInformation:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
- case SP_MessageBoxCritical:
- return QGtkPainter::getIcon(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
- default:
- return QCleanlooksStyle::standardIconImplementation(standardIcon, option, widget);
- }
-}
-
-
-/*! \reimp */
-QRect QGtkStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
-{
- Q_D(const QGtkStyle);
-
- QRect r = QCleanlooksStyle::subElementRect(element, option, widget);
- if (!d->isThemeAvailable())
- return r;
-
- switch (element) {
- case SE_ProgressBarLabel:
- case SE_ProgressBarContents:
- case SE_ProgressBarGroove:
- return option->rect;
- case SE_PushButtonContents:
- if (!d->gtk_check_version(2, 10, 0)) {
- GtkWidget *gtkButton = d->gtkWidget("GtkButton");
- GtkBorder *border = 0;
- d->gtk_widget_style_get(gtkButton, "inner-border", &border, NULL);
- if (border) {
- r = option->rect.adjusted(border->left, border->top, -border->right, -border->bottom);
- d->gtk_border_free(border);
- } else {
- r = option->rect.adjusted(1, 1, -1, -1);
- }
- r = visualRect(option->direction, option->rect, r);
- }
- break;
- default:
- break;
- }
-
- return r;
-}
-
-/*!
- \reimp
-*/
-QRect QGtkStyle::itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const
-{
- return QCleanlooksStyle::itemPixmapRect(r, flags, pixmap);
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::drawItemPixmap(QPainter *painter, const QRect &rect,
- int alignment, const QPixmap &pixmap) const
-{
- QCleanlooksStyle::drawItemPixmap(painter, rect, alignment, pixmap);
-}
-
-/*!
- \reimp
-*/
-QStyle::SubControl QGtkStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w) const
-{
- return QCleanlooksStyle::hitTestComplexControl(cc, opt, pt, w);
-}
-
-/*!
- \reimp
-*/
-QPixmap QGtkStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const
-{
- return QCleanlooksStyle::generatedIconPixmap(iconMode, pixmap, opt);
-}
-
-/*!
- \reimp
-*/
-void QGtkStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const
-{
- return QCleanlooksStyle::drawItemText(painter, rect, alignment, pal, enabled, text, textRole);
-}
-
-QT_END_NAMESPACE
-
-#endif //!defined(QT_NO_STYLE_QGTK)
diff --git a/src/gui/styles/qgtkstyle.h b/src/gui/styles/qgtkstyle.h
deleted file mode 100644
index 616ce24509..0000000000
--- a/src/gui/styles/qgtkstyle.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** 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 QGTKSTYLE_H
-#define QGTKSTYLE_H
-
-#include <QtGui/QCleanlooksStyle>
-#include <QtGui/QPalette>
-#include <QtGui/QFont>
-#include <QtGui/QFileDialog>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_GTK)
-
-class QPainterPath;
-class QGtkStylePrivate;
-
-class Q_GUI_EXPORT QGtkStyle : public QCleanlooksStyle
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QGtkStyle)
-
-public:
- QGtkStyle();
- QGtkStyle(QGtkStylePrivate &dd);
-
- ~QGtkStyle();
-
- QPalette standardPalette() const;
-
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const;
- void drawControl(ControlElement control, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const;
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const;
- void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
- const QPixmap &pixmap) const;
- void drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const;
-
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
- int styleHint(StyleHint hint, const QStyleOption *option,
- const QWidget *widget, QStyleHintReturn *returnData) const;
-
- QStyle::SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w) const;
-
- QRect subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const;
- QRect subElementRect(SubElement sr, const QStyleOption *opt, const QWidget *w) const;
- QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const;
-
-
- QSize sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const;
- QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *option,
- const QWidget *widget) const;
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const;
-
- void polish(QWidget *widget);
- void polish(QApplication *app);
- void polish(QPalette &palette);
-
- void unpolish(QWidget *widget);
- void unpolish(QApplication *app);
-
- static bool getGConfBool(const QString &key, bool fallback = 0);
- static QString getGConfString(const QString &key, const QString &fallback = QString());
-
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget = 0) const;
-};
-
-#endif //!defined(QT_NO_STYLE_QGTK)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //QGTKSTYLE_H
diff --git a/src/gui/styles/qgtkstyle_p.cpp b/src/gui/styles/qgtkstyle_p.cpp
deleted file mode 100644
index d7c53c9a91..0000000000
--- a/src/gui/styles/qgtkstyle_p.cpp
+++ /dev/null
@@ -1,1146 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgtkstyle_p.h"
-
-// This file is responsible for resolving all GTK functions we use
-// dynamically. This is done to avoid link-time dependancy on GTK
-// as well as crashes occurring due to usage of the GTK_QT engines
-//
-// Additionally we create a map of common GTK widgets that we can pass
-// to the GTK theme engine as many engines resort to querying the
-// actual widget pointers for details that are not covered by the
-// state flags
-
-#include <QtCore/qglobal.h>
-#if !defined(QT_NO_STYLE_GTK)
-
-#include <QtCore/QEvent>
-#include <QtCore/QFile>
-#include <QtCore/QStringList>
-#include <QtCore/QTextStream>
-#include <QtCore/QHash>
-#include <QtCore/QUrl>
-#include <QtCore/QLibrary>
-#include <QtCore/QDebug>
-
-#include <private/qapplication_p.h>
-#include <private/qiconloader_p.h>
-
-#include <QtGui/QMenu>
-#include <QtGui/QStyle>
-#include <QtGui/QApplication>
-#include <QtGui/QPixmapCache>
-#include <QtGui/QStatusBar>
-#include <QtGui/QMenuBar>
-#include <QtGui/QToolBar>
-#include <QtGui/QToolButton>
-#include <QtGui/QX11Info>
-
-#include <private/qt_x11_p.h>
-
-QT_BEGIN_NAMESPACE
-
-static bool displayDepth = -1;
-Q_GLOBAL_STATIC(QGtkStyleUpdateScheduler, styleScheduler)
-
-Ptr_gtk_container_forall QGtkStylePrivate::gtk_container_forall = 0;
-Ptr_gtk_init QGtkStylePrivate::gtk_init = 0;
-Ptr_gtk_style_attach QGtkStylePrivate::gtk_style_attach = 0;
-Ptr_gtk_window_new QGtkStylePrivate::gtk_window_new = 0;
-Ptr_gtk_widget_destroy QGtkStylePrivate::gtk_widget_destroy = 0;
-Ptr_gtk_widget_realize QGtkStylePrivate::gtk_widget_realize = 0;
-Ptr_gtk_widget_set_default_direction QGtkStylePrivate::gtk_widget_set_default_direction = 0;
-Ptr_gtk_widget_modify_color QGtkStylePrivate::gtk_widget_modify_fg = 0;
-Ptr_gtk_widget_modify_color QGtkStylePrivate::gtk_widget_modify_bg = 0;
-Ptr_gtk_arrow_new QGtkStylePrivate::gtk_arrow_new = 0;
-Ptr_gtk_menu_item_new_with_label QGtkStylePrivate::gtk_menu_item_new_with_label = 0;
-Ptr_gtk_check_menu_item_new_with_label QGtkStylePrivate::gtk_check_menu_item_new_with_label = 0;
-Ptr_gtk_menu_bar_new QGtkStylePrivate::gtk_menu_bar_new = 0;
-Ptr_gtk_menu_new QGtkStylePrivate::gtk_menu_new = 0;
-Ptr_gtk_button_new QGtkStylePrivate::gtk_button_new = 0;
-Ptr_gtk_tool_button_new QGtkStylePrivate::gtk_tool_button_new = 0;
-Ptr_gtk_hbutton_box_new QGtkStylePrivate::gtk_hbutton_box_new = 0;
-Ptr_gtk_check_button_new QGtkStylePrivate::gtk_check_button_new = 0;
-Ptr_gtk_radio_button_new QGtkStylePrivate::gtk_radio_button_new = 0;
-Ptr_gtk_spin_button_new QGtkStylePrivate::gtk_spin_button_new = 0;
-Ptr_gtk_frame_new QGtkStylePrivate::gtk_frame_new = 0;
-Ptr_gtk_expander_new QGtkStylePrivate::gtk_expander_new = 0;
-Ptr_gtk_statusbar_new QGtkStylePrivate::gtk_statusbar_new = 0;
-Ptr_gtk_entry_new QGtkStylePrivate::gtk_entry_new = 0;
-Ptr_gtk_hscale_new QGtkStylePrivate::gtk_hscale_new = 0;
-Ptr_gtk_vscale_new QGtkStylePrivate::gtk_vscale_new = 0;
-Ptr_gtk_hscrollbar_new QGtkStylePrivate::gtk_hscrollbar_new = 0;
-Ptr_gtk_vscrollbar_new QGtkStylePrivate::gtk_vscrollbar_new = 0;
-Ptr_gtk_scrolled_window_new QGtkStylePrivate::gtk_scrolled_window_new = 0;
-Ptr_gtk_notebook_new QGtkStylePrivate::gtk_notebook_new = 0;
-Ptr_gtk_toolbar_new QGtkStylePrivate::gtk_toolbar_new = 0;
-Ptr_gtk_toolbar_insert QGtkStylePrivate::gtk_toolbar_insert = 0;
-Ptr_gtk_separator_tool_item_new QGtkStylePrivate::gtk_separator_tool_item_new = 0;
-Ptr_gtk_tree_view_new QGtkStylePrivate::gtk_tree_view_new = 0;
-Ptr_gtk_combo_box_new QGtkStylePrivate::gtk_combo_box_new = 0;
-Ptr_gtk_combo_box_entry_new QGtkStylePrivate::gtk_combo_box_entry_new = 0;
-Ptr_gtk_progress_bar_new QGtkStylePrivate::gtk_progress_bar_new = 0;
-Ptr_gtk_container_add QGtkStylePrivate::gtk_container_add = 0;
-Ptr_gtk_menu_shell_append QGtkStylePrivate::gtk_menu_shell_append = 0;
-Ptr_gtk_progress_configure QGtkStylePrivate::gtk_progress_configure = 0;
-Ptr_gtk_range_get_adjustment QGtkStylePrivate::gtk_range_get_adjustment = 0;
-Ptr_gtk_range_set_adjustment QGtkStylePrivate::gtk_range_set_adjustment = 0;
-Ptr_gtk_range_set_inverted QGtkStylePrivate::gtk_range_set_inverted = 0;
-Ptr_gtk_icon_factory_lookup_default QGtkStylePrivate::gtk_icon_factory_lookup_default = 0;
-Ptr_gtk_icon_theme_get_default QGtkStylePrivate::gtk_icon_theme_get_default = 0;
-Ptr_gtk_widget_style_get QGtkStylePrivate::gtk_widget_style_get = 0;
-Ptr_gtk_icon_set_render_icon QGtkStylePrivate::gtk_icon_set_render_icon = 0;
-Ptr_gtk_fixed_new QGtkStylePrivate::gtk_fixed_new = 0;
-Ptr_gtk_tree_view_column_new QGtkStylePrivate::gtk_tree_view_column_new = 0;
-Ptr_gtk_tree_view_get_column QGtkStylePrivate::gtk_tree_view_get_column = 0;
-Ptr_gtk_tree_view_append_column QGtkStylePrivate::gtk_tree_view_append_column = 0;
-Ptr_gtk_paint_check QGtkStylePrivate::gtk_paint_check = 0;
-Ptr_gtk_paint_box QGtkStylePrivate::gtk_paint_box = 0;
-Ptr_gtk_paint_box_gap QGtkStylePrivate::gtk_paint_box_gap = 0;
-Ptr_gtk_paint_flat_box QGtkStylePrivate::gtk_paint_flat_box = 0;
-Ptr_gtk_paint_option QGtkStylePrivate::gtk_paint_option = 0;
-Ptr_gtk_paint_extension QGtkStylePrivate::gtk_paint_extension = 0;
-Ptr_gtk_paint_slider QGtkStylePrivate::gtk_paint_slider = 0;
-Ptr_gtk_paint_shadow QGtkStylePrivate::gtk_paint_shadow = 0;
-Ptr_gtk_paint_resize_grip QGtkStylePrivate::gtk_paint_resize_grip = 0;
-Ptr_gtk_paint_focus QGtkStylePrivate::gtk_paint_focus = 0;
-Ptr_gtk_paint_arrow QGtkStylePrivate::gtk_paint_arrow = 0;
-Ptr_gtk_paint_handle QGtkStylePrivate::gtk_paint_handle = 0;
-Ptr_gtk_paint_expander QGtkStylePrivate::gtk_paint_expander = 0;
-Ptr_gtk_adjustment_configure QGtkStylePrivate::gtk_adjustment_configure = 0;
-Ptr_gtk_adjustment_new QGtkStylePrivate::gtk_adjustment_new = 0;
-Ptr_gtk_paint_hline QGtkStylePrivate::gtk_paint_hline = 0;
-Ptr_gtk_paint_vline QGtkStylePrivate::gtk_paint_vline = 0;
-Ptr_gtk_menu_item_set_submenu QGtkStylePrivate::gtk_menu_item_set_submenu = 0;
-Ptr_gtk_settings_get_default QGtkStylePrivate::gtk_settings_get_default = 0;
-Ptr_gtk_separator_menu_item_new QGtkStylePrivate::gtk_separator_menu_item_new = 0;
-Ptr_gtk_widget_size_allocate QGtkStylePrivate::gtk_widget_size_allocate = 0;
-Ptr_gtk_widget_size_request QGtkStylePrivate::gtk_widget_size_request = 0;
-Ptr_gtk_widget_set_direction QGtkStylePrivate::gtk_widget_set_direction = 0;
-Ptr_gtk_widget_path QGtkStylePrivate::gtk_widget_path = 0;
-Ptr_gtk_container_get_type QGtkStylePrivate::gtk_container_get_type = 0;
-Ptr_gtk_window_get_type QGtkStylePrivate::gtk_window_get_type = 0;
-Ptr_gtk_widget_get_type QGtkStylePrivate::gtk_widget_get_type = 0;
-Ptr_gtk_rc_get_style_by_paths QGtkStylePrivate::gtk_rc_get_style_by_paths = 0;
-Ptr_gtk_check_version QGtkStylePrivate::gtk_check_version = 0;
-Ptr_gtk_border_free QGtkStylePrivate::gtk_border_free = 0;
-Ptr_pango_font_description_get_size QGtkStylePrivate::pango_font_description_get_size = 0;
-Ptr_pango_font_description_get_weight QGtkStylePrivate::pango_font_description_get_weight = 0;
-Ptr_pango_font_description_get_family QGtkStylePrivate::pango_font_description_get_family = 0;
-Ptr_pango_font_description_get_style QGtkStylePrivate::pango_font_description_get_style = 0;
-
-Ptr_gtk_file_filter_new QGtkStylePrivate::gtk_file_filter_new = 0;
-Ptr_gtk_file_filter_set_name QGtkStylePrivate::gtk_file_filter_set_name = 0;
-Ptr_gtk_file_filter_add_pattern QGtkStylePrivate::gtk_file_filter_add_pattern = 0;
-Ptr_gtk_file_chooser_add_filter QGtkStylePrivate::gtk_file_chooser_add_filter = 0;
-Ptr_gtk_file_chooser_set_filter QGtkStylePrivate::gtk_file_chooser_set_filter = 0;
-Ptr_gtk_file_chooser_get_filter QGtkStylePrivate::gtk_file_chooser_get_filter = 0;
-Ptr_gtk_file_chooser_dialog_new QGtkStylePrivate::gtk_file_chooser_dialog_new = 0;
-Ptr_gtk_file_chooser_set_current_folder QGtkStylePrivate::gtk_file_chooser_set_current_folder = 0;
-Ptr_gtk_file_chooser_get_filename QGtkStylePrivate::gtk_file_chooser_get_filename = 0;
-Ptr_gtk_file_chooser_get_filenames QGtkStylePrivate::gtk_file_chooser_get_filenames = 0;
-Ptr_gtk_file_chooser_set_current_name QGtkStylePrivate::gtk_file_chooser_set_current_name = 0;
-Ptr_gtk_dialog_run QGtkStylePrivate::gtk_dialog_run = 0;
-Ptr_gtk_file_chooser_set_filename QGtkStylePrivate::gtk_file_chooser_set_filename = 0;
-
-Ptr_gdk_pixbuf_get_pixels QGtkStylePrivate::gdk_pixbuf_get_pixels = 0;
-Ptr_gdk_pixbuf_get_width QGtkStylePrivate::gdk_pixbuf_get_width = 0;
-Ptr_gdk_pixbuf_get_height QGtkStylePrivate::gdk_pixbuf_get_height = 0;
-Ptr_gdk_pixmap_new QGtkStylePrivate::gdk_pixmap_new = 0;
-Ptr_gdk_pixbuf_new QGtkStylePrivate::gdk_pixbuf_new = 0;
-Ptr_gdk_pixbuf_get_from_drawable QGtkStylePrivate::gdk_pixbuf_get_from_drawable = 0;
-Ptr_gdk_draw_rectangle QGtkStylePrivate::gdk_draw_rectangle = 0;
-Ptr_gdk_pixbuf_unref QGtkStylePrivate::gdk_pixbuf_unref = 0;
-Ptr_gdk_drawable_unref QGtkStylePrivate::gdk_drawable_unref = 0;
-Ptr_gdk_drawable_get_depth QGtkStylePrivate::gdk_drawable_get_depth = 0;
-Ptr_gdk_color_free QGtkStylePrivate::gdk_color_free = 0;
-Ptr_gdk_x11_window_set_user_time QGtkStylePrivate::gdk_x11_window_set_user_time = 0;
-Ptr_gdk_x11_drawable_get_xid QGtkStylePrivate::gdk_x11_drawable_get_xid = 0;
-Ptr_gdk_x11_drawable_get_xdisplay QGtkStylePrivate::gdk_x11_drawable_get_xdisplay = 0;
-
-Ptr_gconf_client_get_default QGtkStylePrivate::gconf_client_get_default = 0;
-Ptr_gconf_client_get_string QGtkStylePrivate::gconf_client_get_string = 0;
-Ptr_gconf_client_get_bool QGtkStylePrivate::gconf_client_get_bool = 0;
-
-Ptr_gnome_icon_lookup_sync QGtkStylePrivate::gnome_icon_lookup_sync = 0;
-Ptr_gnome_vfs_init QGtkStylePrivate::gnome_vfs_init = 0;
-
-typedef int (*x11ErrorHandler)(Display*, XErrorEvent*);
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QGtkStylePrivate*);
-
-QT_BEGIN_NAMESPACE
-
-static void gtkStyleSetCallback(GtkWidget*)
-{
- qRegisterMetaType<QGtkStylePrivate *>();
-
- // We have to let this function return and complete the event
- // loop to ensure that all gtk widgets have been styled before
- // updating
- QMetaObject::invokeMethod(styleScheduler(), "updateTheme", Qt::QueuedConnection);
-}
-
-static void update_toolbar_style(GtkWidget *gtkToolBar, GParamSpec *, gpointer)
-{
- GtkToolbarStyle toolbar_style = GTK_TOOLBAR_ICONS;
- g_object_get(gtkToolBar, "toolbar-style", &toolbar_style, NULL);
- QWidgetList widgets = QApplication::allWidgets();
- for (int i = 0; i < widgets.size(); ++i) {
- QWidget *widget = widgets.at(i);
- if (qobject_cast<QToolButton*>(widget)) {
- QEvent event(QEvent::StyleChange);
- QApplication::sendEvent(widget, &event);
- }
- }
-}
-
-static QHashableLatin1Literal classPath(GtkWidget *widget)
-{
- char *class_path;
- QGtkStylePrivate::gtk_widget_path (widget, NULL, &class_path, NULL);
-
- char *copy = class_path;
- if (strncmp(copy, "GtkWindow.", 10) == 0)
- copy += 10;
- if (strncmp(copy, "GtkFixed.", 9) == 0)
- copy += 9;
-
- copy = strdup(copy);
-
- g_free(class_path);
-
- return QHashableLatin1Literal::fromData(copy);
-}
-
-
-
-bool QGtkStyleFilter::eventFilter(QObject *obj, QEvent *e)
-{
- if (e->type() == QEvent::ApplicationPaletteChange) {
- // Only do this the first time since this will also
- // generate applicationPaletteChange events
- if (!qt_app_palettes_hash() || qt_app_palettes_hash()->isEmpty()) {
- stylePrivate->applyCustomPaletteHash();
- }
- }
- return QObject::eventFilter(obj, e);
-}
-
-QList<QGtkStylePrivate *> QGtkStylePrivate::instances;
-QGtkStylePrivate::WidgetMap *QGtkStylePrivate::widgetMap = 0;
-
-QGtkStylePrivate::QGtkStylePrivate()
- : QCleanlooksStylePrivate()
- , filter(this)
-{
- instances.append(this);
-}
-
-QGtkStylePrivate::~QGtkStylePrivate()
-{
- instances.removeOne(this);
-}
-
-void QGtkStylePrivate::init()
-{
- resolveGtk();
- initGtkWidgets();
-}
-
-GtkWidget* QGtkStylePrivate::gtkWidget(const QHashableLatin1Literal &path)
-{
- GtkWidget *widget = gtkWidgetMap()->value(path);
- if (!widget) {
- // Theme might have rearranged widget internals
- widget = gtkWidgetMap()->value(path);
- }
- return widget;
-}
-
-GtkStyle* QGtkStylePrivate::gtkStyle(const QHashableLatin1Literal &path)
-{
- if (GtkWidget *w = gtkWidgetMap()->value(path))
- return w->style;
- return 0;
-}
-
-/*! \internal
- * Get references to gtk functions after we dynamically load the library.
- */
-void QGtkStylePrivate::resolveGtk() const
-{
- // enforce the "0" suffix, so we'll open libgtk-x11-2.0.so.0
- QLibrary libgtk(QLS("gtk-x11-2.0"), 0, 0);
-
- gtk_init = (Ptr_gtk_init)libgtk.resolve("gtk_init");
- gtk_window_new = (Ptr_gtk_window_new)libgtk.resolve("gtk_window_new");
- gtk_style_attach = (Ptr_gtk_style_attach)libgtk.resolve("gtk_style_attach");
- gtk_widget_destroy = (Ptr_gtk_widget_destroy)libgtk.resolve("gtk_widget_destroy");
- gtk_widget_realize = (Ptr_gtk_widget_realize)libgtk.resolve("gtk_widget_realize");
-
- gtk_file_chooser_set_current_folder = (Ptr_gtk_file_chooser_set_current_folder)libgtk.resolve("gtk_file_chooser_set_current_folder");
- gtk_file_filter_new = (Ptr_gtk_file_filter_new)libgtk.resolve("gtk_file_filter_new");
- gtk_file_filter_set_name = (Ptr_gtk_file_filter_set_name)libgtk.resolve("gtk_file_filter_set_name");
- gtk_file_filter_add_pattern = (Ptr_gtk_file_filter_add_pattern)libgtk.resolve("gtk_file_filter_add_pattern");
- gtk_file_chooser_add_filter = (Ptr_gtk_file_chooser_add_filter)libgtk.resolve("gtk_file_chooser_add_filter");
- gtk_file_chooser_set_filter = (Ptr_gtk_file_chooser_set_filter)libgtk.resolve("gtk_file_chooser_set_filter");
- gtk_file_chooser_get_filter = (Ptr_gtk_file_chooser_get_filter)libgtk.resolve("gtk_file_chooser_get_filter");
- gtk_file_chooser_dialog_new = (Ptr_gtk_file_chooser_dialog_new)libgtk.resolve("gtk_file_chooser_dialog_new");
- gtk_file_chooser_set_current_folder = (Ptr_gtk_file_chooser_set_current_folder)libgtk.resolve("gtk_file_chooser_set_current_folder");
- gtk_file_chooser_get_filename = (Ptr_gtk_file_chooser_get_filename)libgtk.resolve("gtk_file_chooser_get_filename");
- gtk_file_chooser_get_filenames = (Ptr_gtk_file_chooser_get_filenames)libgtk.resolve("gtk_file_chooser_get_filenames");
- gtk_file_chooser_set_current_name = (Ptr_gtk_file_chooser_set_current_name)libgtk.resolve("gtk_file_chooser_set_current_name");
- gtk_dialog_run = (Ptr_gtk_dialog_run)libgtk.resolve("gtk_dialog_run");
- gtk_file_chooser_set_filename = (Ptr_gtk_file_chooser_set_filename)libgtk.resolve("gtk_file_chooser_set_filename");
-
- gdk_pixbuf_get_pixels = (Ptr_gdk_pixbuf_get_pixels)libgtk.resolve("gdk_pixbuf_get_pixels");
- gdk_pixbuf_get_width = (Ptr_gdk_pixbuf_get_width)libgtk.resolve("gdk_pixbuf_get_width");
- gdk_pixbuf_get_height = (Ptr_gdk_pixbuf_get_height)libgtk.resolve("gdk_pixbuf_get_height");
- gdk_pixmap_new = (Ptr_gdk_pixmap_new)libgtk.resolve("gdk_pixmap_new");
- gdk_pixbuf_new = (Ptr_gdk_pixbuf_new)libgtk.resolve("gdk_pixbuf_new");
- gdk_pixbuf_get_from_drawable = (Ptr_gdk_pixbuf_get_from_drawable)libgtk.resolve("gdk_pixbuf_get_from_drawable");
- gdk_draw_rectangle = (Ptr_gdk_draw_rectangle)libgtk.resolve("gdk_draw_rectangle");
- gdk_pixbuf_unref = (Ptr_gdk_pixbuf_unref)libgtk.resolve("gdk_pixbuf_unref");
- gdk_drawable_unref = (Ptr_gdk_drawable_unref)libgtk.resolve("gdk_drawable_unref");
- gdk_drawable_get_depth = (Ptr_gdk_drawable_get_depth)libgtk.resolve("gdk_drawable_get_depth");
- gdk_color_free = (Ptr_gdk_color_free)libgtk.resolve("gdk_color_free");
- gdk_x11_window_set_user_time = (Ptr_gdk_x11_window_set_user_time)libgtk.resolve("gdk_x11_window_set_user_time");
- gdk_x11_drawable_get_xid = (Ptr_gdk_x11_drawable_get_xid)libgtk.resolve("gdk_x11_drawable_get_xid");
- gdk_x11_drawable_get_xdisplay = (Ptr_gdk_x11_drawable_get_xdisplay)libgtk.resolve("gdk_x11_drawable_get_xdisplay");
-
- gtk_widget_set_default_direction = (Ptr_gtk_widget_set_default_direction)libgtk.resolve("gtk_widget_set_default_direction");
- gtk_widget_modify_fg = (Ptr_gtk_widget_modify_color)libgtk.resolve("gtk_widget_modify_fg");
- gtk_widget_modify_bg = (Ptr_gtk_widget_modify_color)libgtk.resolve("gtk_widget_modify_bg");
- gtk_arrow_new = (Ptr_gtk_arrow_new)libgtk.resolve("gtk_arrow_new");
- gtk_menu_item_new_with_label = (Ptr_gtk_menu_item_new_with_label)libgtk.resolve("gtk_menu_item_new_with_label");
- gtk_check_menu_item_new_with_label = (Ptr_gtk_check_menu_item_new_with_label)libgtk.resolve("gtk_check_menu_item_new_with_label");
- gtk_menu_bar_new = (Ptr_gtk_menu_bar_new)libgtk.resolve("gtk_menu_bar_new");
- gtk_menu_new = (Ptr_gtk_menu_new)libgtk.resolve("gtk_menu_new");
- gtk_toolbar_new = (Ptr_gtk_toolbar_new)libgtk.resolve("gtk_toolbar_new");
- gtk_separator_tool_item_new = (Ptr_gtk_separator_tool_item_new)libgtk.resolve("gtk_separator_tool_item_new");
- gtk_toolbar_insert = (Ptr_gtk_toolbar_insert)libgtk.resolve("gtk_toolbar_insert");
- gtk_button_new = (Ptr_gtk_button_new)libgtk.resolve("gtk_button_new");
- gtk_tool_button_new = (Ptr_gtk_tool_button_new)libgtk.resolve("gtk_tool_button_new");
- gtk_hbutton_box_new = (Ptr_gtk_hbutton_box_new)libgtk.resolve("gtk_hbutton_box_new");
- gtk_check_button_new = (Ptr_gtk_check_button_new)libgtk.resolve("gtk_check_button_new");
- gtk_radio_button_new = (Ptr_gtk_radio_button_new)libgtk.resolve("gtk_radio_button_new");
- gtk_notebook_new = (Ptr_gtk_notebook_new)libgtk.resolve("gtk_notebook_new");
- gtk_progress_bar_new = (Ptr_gtk_progress_bar_new)libgtk.resolve("gtk_progress_bar_new");
- gtk_spin_button_new = (Ptr_gtk_spin_button_new)libgtk.resolve("gtk_spin_button_new");
- gtk_hscale_new = (Ptr_gtk_hscale_new)libgtk.resolve("gtk_hscale_new");
- gtk_vscale_new = (Ptr_gtk_vscale_new)libgtk.resolve("gtk_vscale_new");
- gtk_hscrollbar_new = (Ptr_gtk_hscrollbar_new)libgtk.resolve("gtk_hscrollbar_new");
- gtk_vscrollbar_new = (Ptr_gtk_vscrollbar_new)libgtk.resolve("gtk_vscrollbar_new");
- gtk_scrolled_window_new = (Ptr_gtk_scrolled_window_new)libgtk.resolve("gtk_scrolled_window_new");
- gtk_menu_shell_append = (Ptr_gtk_menu_shell_append)libgtk.resolve("gtk_menu_shell_append");
- gtk_entry_new = (Ptr_gtk_entry_new)libgtk.resolve("gtk_entry_new");
- gtk_tree_view_new = (Ptr_gtk_tree_view_new)libgtk.resolve("gtk_tree_view_new");
- gtk_combo_box_new = (Ptr_gtk_combo_box_new)libgtk.resolve("gtk_combo_box_new");
- gtk_progress_configure = (Ptr_gtk_progress_configure)libgtk.resolve("gtk_progress_configure");
- gtk_range_get_adjustment = (Ptr_gtk_range_get_adjustment)libgtk.resolve("gtk_range_get_adjustment");
- gtk_range_set_adjustment = (Ptr_gtk_range_set_adjustment)libgtk.resolve("gtk_range_set_adjustment");
- gtk_range_set_inverted = (Ptr_gtk_range_set_inverted)libgtk.resolve("gtk_range_set_inverted");
- gtk_container_add = (Ptr_gtk_container_add)libgtk.resolve("gtk_container_add");
- gtk_icon_factory_lookup_default = (Ptr_gtk_icon_factory_lookup_default)libgtk.resolve("gtk_icon_factory_lookup_default");
- gtk_icon_theme_get_default = (Ptr_gtk_icon_theme_get_default)libgtk.resolve("gtk_icon_theme_get_default");
- gtk_widget_style_get = (Ptr_gtk_widget_style_get)libgtk.resolve("gtk_widget_style_get");
- gtk_icon_set_render_icon = (Ptr_gtk_icon_set_render_icon)libgtk.resolve("gtk_icon_set_render_icon");
- gtk_fixed_new = (Ptr_gtk_fixed_new)libgtk.resolve("gtk_fixed_new");
- gtk_tree_view_column_new = (Ptr_gtk_tree_view_column_new)libgtk.resolve("gtk_tree_view_column_new");
- gtk_tree_view_append_column= (Ptr_gtk_tree_view_append_column )libgtk.resolve("gtk_tree_view_append_column");
- gtk_tree_view_get_column = (Ptr_gtk_tree_view_get_column )libgtk.resolve("gtk_tree_view_get_column");
- gtk_paint_check = (Ptr_gtk_paint_check)libgtk.resolve("gtk_paint_check");
- gtk_paint_box = (Ptr_gtk_paint_box)libgtk.resolve("gtk_paint_box");
- gtk_paint_flat_box = (Ptr_gtk_paint_flat_box)libgtk.resolve("gtk_paint_flat_box");
- gtk_paint_check = (Ptr_gtk_paint_check)libgtk.resolve("gtk_paint_check");
- gtk_paint_box = (Ptr_gtk_paint_box)libgtk.resolve("gtk_paint_box");
- gtk_paint_resize_grip = (Ptr_gtk_paint_resize_grip)libgtk.resolve("gtk_paint_resize_grip");
- gtk_paint_focus = (Ptr_gtk_paint_focus)libgtk.resolve("gtk_paint_focus");
- gtk_paint_shadow = (Ptr_gtk_paint_shadow)libgtk.resolve("gtk_paint_shadow");
- gtk_paint_slider = (Ptr_gtk_paint_slider)libgtk.resolve("gtk_paint_slider");
- gtk_paint_expander = (Ptr_gtk_paint_expander)libgtk.resolve("gtk_paint_expander");
- gtk_paint_handle = (Ptr_gtk_paint_handle)libgtk.resolve("gtk_paint_handle");
- gtk_paint_option = (Ptr_gtk_paint_option)libgtk.resolve("gtk_paint_option");
- gtk_paint_arrow = (Ptr_gtk_paint_arrow)libgtk.resolve("gtk_paint_arrow");
- gtk_paint_box_gap = (Ptr_gtk_paint_box_gap)libgtk.resolve("gtk_paint_box_gap");
- gtk_paint_extension = (Ptr_gtk_paint_extension)libgtk.resolve("gtk_paint_extension");
- gtk_paint_hline = (Ptr_gtk_paint_hline)libgtk.resolve("gtk_paint_hline");
- gtk_paint_vline = (Ptr_gtk_paint_vline)libgtk.resolve("gtk_paint_vline");
- gtk_adjustment_configure = (Ptr_gtk_adjustment_configure)libgtk.resolve("gtk_adjustment_configure");
- gtk_adjustment_new = (Ptr_gtk_adjustment_new)libgtk.resolve("gtk_adjustment_new");
- gtk_menu_item_set_submenu = (Ptr_gtk_menu_item_set_submenu)libgtk.resolve("gtk_menu_item_set_submenu");
- gtk_settings_get_default = (Ptr_gtk_settings_get_default)libgtk.resolve("gtk_settings_get_default");
- gtk_separator_menu_item_new = (Ptr_gtk_separator_menu_item_new)libgtk.resolve("gtk_separator_menu_item_new");
- gtk_frame_new = (Ptr_gtk_frame_new)libgtk.resolve("gtk_frame_new");
- gtk_expander_new = (Ptr_gtk_expander_new)libgtk.resolve("gtk_expander_new");
- gtk_statusbar_new = (Ptr_gtk_statusbar_new)libgtk.resolve("gtk_statusbar_new");
- gtk_combo_box_entry_new = (Ptr_gtk_combo_box_entry_new)libgtk.resolve("gtk_combo_box_entry_new");
- gtk_container_forall = (Ptr_gtk_container_forall)libgtk.resolve("gtk_container_forall");
- gtk_widget_size_allocate =(Ptr_gtk_widget_size_allocate)libgtk.resolve("gtk_widget_size_allocate");
- gtk_widget_size_request =(Ptr_gtk_widget_size_request)libgtk.resolve("gtk_widget_size_request");
- gtk_widget_set_direction =(Ptr_gtk_widget_set_direction)libgtk.resolve("gtk_widget_set_direction");
- gtk_widget_path =(Ptr_gtk_widget_path)libgtk.resolve("gtk_widget_path");
- gtk_container_get_type =(Ptr_gtk_container_get_type)libgtk.resolve("gtk_container_get_type");
- gtk_window_get_type =(Ptr_gtk_window_get_type)libgtk.resolve("gtk_window_get_type");
- gtk_widget_get_type =(Ptr_gtk_widget_get_type)libgtk.resolve("gtk_widget_get_type");
-
- gtk_rc_get_style_by_paths =(Ptr_gtk_rc_get_style_by_paths)libgtk.resolve("gtk_rc_get_style_by_paths");
- gtk_check_version =(Ptr_gtk_check_version)libgtk.resolve("gtk_check_version");
- gtk_border_free =(Ptr_gtk_border_free)libgtk.resolve("gtk_border_free");
- pango_font_description_get_size = (Ptr_pango_font_description_get_size)libgtk.resolve("pango_font_description_get_size");
- pango_font_description_get_weight = (Ptr_pango_font_description_get_weight)libgtk.resolve("pango_font_description_get_weight");
- pango_font_description_get_family = (Ptr_pango_font_description_get_family)libgtk.resolve("pango_font_description_get_family");
- pango_font_description_get_style = (Ptr_pango_font_description_get_style)libgtk.resolve("pango_font_description_get_style");
-
- gnome_icon_lookup_sync = (Ptr_gnome_icon_lookup_sync)QLibrary::resolve(QLS("gnomeui-2"), 0, "gnome_icon_lookup_sync");
- gnome_vfs_init= (Ptr_gnome_vfs_init)QLibrary::resolve(QLS("gnomevfs-2"), 0, "gnome_vfs_init");
-}
-
-/* \internal
- * Initializes a number of gtk menu widgets.
- * The widgets are cached.
- */
-void QGtkStylePrivate::initGtkMenu() const
-{
- // Create menubar
- GtkWidget *gtkMenuBar = QGtkStylePrivate::gtk_menu_bar_new();
- setupGtkWidget(gtkMenuBar);
-
- GtkWidget *gtkMenuBarItem = QGtkStylePrivate::gtk_menu_item_new_with_label("X");
- gtk_menu_shell_append((GtkMenuShell*)(gtkMenuBar), gtkMenuBarItem);
- gtk_widget_realize(gtkMenuBarItem);
-
- // Create menu
- GtkWidget *gtkMenu = QGtkStylePrivate::gtk_menu_new();
- gtk_menu_item_set_submenu((GtkMenuItem*)(gtkMenuBarItem), gtkMenu);
- gtk_widget_realize(gtkMenu);
-
- GtkWidget *gtkMenuItem = QGtkStylePrivate::gtk_menu_item_new_with_label("X");
- gtk_menu_shell_append((GtkMenuShell*)gtkMenu, gtkMenuItem);
- gtk_widget_realize(gtkMenuItem);
-
- GtkWidget *gtkCheckMenuItem = QGtkStylePrivate::gtk_check_menu_item_new_with_label("X");
- gtk_menu_shell_append((GtkMenuShell*)gtkMenu, gtkCheckMenuItem);
- gtk_widget_realize(gtkCheckMenuItem);
-
- GtkWidget *gtkMenuSeparator = QGtkStylePrivate::gtk_separator_menu_item_new();
- gtk_menu_shell_append((GtkMenuShell*)gtkMenu, gtkMenuSeparator);
-
- addAllSubWidgets(gtkMenuBar);
- addAllSubWidgets(gtkMenu);
-}
-
-
-void QGtkStylePrivate::initGtkTreeview() const
-{
- GtkWidget *gtkTreeView = gtk_tree_view_new();
- gtk_tree_view_append_column((GtkTreeView*)gtkTreeView, gtk_tree_view_column_new());
- gtk_tree_view_append_column((GtkTreeView*)gtkTreeView, gtk_tree_view_column_new());
- gtk_tree_view_append_column((GtkTreeView*)gtkTreeView, gtk_tree_view_column_new());
- addWidget(gtkTreeView);
-}
-
-
-/* \internal
- * Initializes a number of gtk widgets that we can later on use to determine some of our styles.
- * The widgets are cached.
- */
-void QGtkStylePrivate::initGtkWidgets() const
-{
- // From gtkmain.c
- uid_t ruid = getuid ();
- uid_t rgid = getgid ();
- uid_t euid = geteuid ();
- uid_t egid = getegid ();
- if (ruid != euid || rgid != egid) {
- qWarning("\nThis process is currently running setuid or setgid.\nGTK+ does not allow this "
- "therefore Qt cannot use the GTK+ integration.\nTry launching your app using \'gksudo\', "
- "\'kdesudo\' or a similar tool.\n\n"
- "See http://www.gtk.org/setuid.html for more information.\n");
- return;
- }
-
- static QString themeName;
- if (!gtkWidgetMap()->contains("GtkWindow") && themeName.isEmpty()) {
- themeName = getThemeName();
-
- if (themeName.isEmpty()) {
- qWarning("QGtkStyle was unable to detect the current GTK+ theme.");
- return;
- } else if (themeName == QLS("Qt") || themeName == QLS("Qt4")) {
- // Due to namespace conflicts with Qt3 and obvious recursion with Qt4,
- // we cannot support the GTK_Qt Gtk engine
- qWarning("QGtkStyle cannot be used together with the GTK_Qt engine.");
- return;
- }
- }
-
- if (QGtkStylePrivate::gtk_init) {
- // Gtk will set the Qt error handler so we have to reset it afterwards
- x11ErrorHandler qt_x_errhandler = XSetErrorHandler(0);
- QGtkStylePrivate::gtk_init (NULL, NULL);
- XSetErrorHandler(qt_x_errhandler);
-
- // make a window
- GtkWidget* gtkWindow = QGtkStylePrivate::gtk_window_new(GTK_WINDOW_POPUP);
- QGtkStylePrivate::gtk_widget_realize(gtkWindow);
- if (displayDepth == -1)
- displayDepth = QGtkStylePrivate::gdk_drawable_get_depth(gtkWindow->window);
- QHashableLatin1Literal widgetPath = QHashableLatin1Literal::fromData(strdup("GtkWindow"));
- removeWidgetFromMap(widgetPath);
- gtkWidgetMap()->insert(widgetPath, gtkWindow);
-
-
- // Make all other widgets. respect the text direction
- if (qApp->layoutDirection() == Qt::RightToLeft)
- QGtkStylePrivate::gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
-
- if (!gtkWidgetMap()->contains("GtkButton")) {
- GtkWidget *gtkButton = QGtkStylePrivate::gtk_button_new();
- addWidget(gtkButton);
- g_signal_connect(gtkButton, "style-set", G_CALLBACK(gtkStyleSetCallback), 0);
- addWidget(QGtkStylePrivate::gtk_tool_button_new(NULL, "Qt"));
- addWidget(QGtkStylePrivate::gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE));
- addWidget(QGtkStylePrivate::gtk_hbutton_box_new());
- addWidget(QGtkStylePrivate::gtk_check_button_new());
- addWidget(QGtkStylePrivate::gtk_radio_button_new(NULL));
- addWidget(QGtkStylePrivate::gtk_combo_box_new());
- addWidget(QGtkStylePrivate::gtk_combo_box_entry_new());
- addWidget(QGtkStylePrivate::gtk_entry_new());
- addWidget(QGtkStylePrivate::gtk_frame_new(NULL));
- addWidget(QGtkStylePrivate::gtk_expander_new(""));
- addWidget(QGtkStylePrivate::gtk_statusbar_new());
- addWidget(QGtkStylePrivate::gtk_hscale_new((GtkAdjustment*)(QGtkStylePrivate::gtk_adjustment_new(1, 0, 1, 0, 0, 0))));
- addWidget(QGtkStylePrivate::gtk_hscrollbar_new(NULL));
- addWidget(QGtkStylePrivate::gtk_scrolled_window_new(NULL, NULL));
-
- initGtkMenu();
- addWidget(QGtkStylePrivate::gtk_notebook_new());
- addWidget(QGtkStylePrivate::gtk_progress_bar_new());
- addWidget(QGtkStylePrivate::gtk_spin_button_new((GtkAdjustment*)
- (QGtkStylePrivate::gtk_adjustment_new(1, 0, 1, 0, 0, 0)), 0.1, 3));
- GtkWidget *toolbar = gtk_toolbar_new();
- g_signal_connect (toolbar, "notify::toolbar-style", G_CALLBACK (update_toolbar_style), toolbar);
- gtk_toolbar_insert((GtkToolbar*)toolbar, gtk_separator_tool_item_new(), -1);
- addWidget(toolbar);
- initGtkTreeview();
- addWidget(gtk_vscale_new((GtkAdjustment*)(QGtkStylePrivate::gtk_adjustment_new(1, 0, 1, 0, 0, 0))));
- addWidget(gtk_vscrollbar_new(NULL));
- }
- else // Rebuild map
- {
- // When styles change subwidgets can get rearranged
- // as with the combo box. We need to update the widget map
- // to reflect this;
- QHash<QHashableLatin1Literal, GtkWidget*> oldMap = *gtkWidgetMap();
- gtkWidgetMap()->clear();
- QHashIterator<QHashableLatin1Literal, GtkWidget*> it(oldMap);
- while (it.hasNext()) {
- it.next();
- if (!strchr(it.key().data(), '.')) {
- addAllSubWidgets(it.value());
- }
- free(const_cast<char *>(it.key().data()));
- }
- }
- } else {
- qWarning("QGtkStyle could not resolve GTK. Make sure you have installed the proper libraries.");
- }
-}
-
-/*! \internal
- * destroys all previously buffered widgets.
- */
-void QGtkStylePrivate::cleanupGtkWidgets()
-{
- if (!widgetMap)
- return;
- if (widgetMap->contains("GtkWindow")) // Gtk will destroy all children
- gtk_widget_destroy(widgetMap->value("GtkWindow"));
- for (QHash<QHashableLatin1Literal, GtkWidget *>::const_iterator it = widgetMap->constBegin();
- it != widgetMap->constEnd(); ++it)
- free(const_cast<char *>(it.key().data()));
-}
-
-static bool resolveGConf()
-{
- if (!QGtkStylePrivate::gconf_client_get_default) {
- QGtkStylePrivate::gconf_client_get_default = (Ptr_gconf_client_get_default)QLibrary::resolve(QLS("gconf-2"), 4, "gconf_client_get_default");
- QGtkStylePrivate::gconf_client_get_string = (Ptr_gconf_client_get_string)QLibrary::resolve(QLS("gconf-2"), 4, "gconf_client_get_string");
- QGtkStylePrivate::gconf_client_get_bool = (Ptr_gconf_client_get_bool)QLibrary::resolve(QLS("gconf-2"), 4, "gconf_client_get_bool");
- }
- return (QGtkStylePrivate::gconf_client_get_default !=0);
-}
-
-QString QGtkStylePrivate::getGConfString(const QString &value, const QString &fallback)
-{
- QString retVal = fallback;
- if (resolveGConf()) {
- g_type_init();
- GConfClient* client = gconf_client_get_default();
- GError *err = 0;
- char *str = gconf_client_get_string(client, qPrintable(value), &err);
- if (!err) {
- retVal = QString::fromUtf8(str);
- g_free(str);
- }
- g_object_unref(client);
- if (err)
- g_error_free (err);
- }
- return retVal;
-}
-
-bool QGtkStylePrivate::getGConfBool(const QString &key, bool fallback)
-{
- bool retVal = fallback;
- if (resolveGConf()) {
- g_type_init();
- GConfClient* client = gconf_client_get_default();
- GError *err = 0;
- bool result = gconf_client_get_bool(client, qPrintable(key), &err);
- g_object_unref(client);
- if (!err)
- retVal = result;
- else
- g_error_free (err);
- }
- return retVal;
-}
-
-QString QGtkStylePrivate::getThemeName()
-{
- QString themeName;
- // We try to parse the gtkrc file first
- // primarily to avoid resolving Gtk functions if
- // the KDE 3 "Qt" style is currently in use
- QString rcPaths = QString::fromLocal8Bit(qgetenv("GTK2_RC_FILES"));
- if (!rcPaths.isEmpty()) {
- QStringList paths = rcPaths.split(QLS(":"));
- foreach (const QString &rcPath, paths) {
- if (!rcPath.isEmpty()) {
- QFile rcFile(rcPath);
- if (rcFile.exists() && rcFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
- QTextStream in(&rcFile);
- while(!in.atEnd()) {
- QString line = in.readLine();
- if (line.contains(QLS("gtk-theme-name"))) {
- line = line.right(line.length() - line.indexOf(QLatin1Char('=')) - 1);
- line.remove(QLatin1Char('\"'));
- line = line.trimmed();
- themeName = line;
- break;
- }
- }
- }
- }
- if (!themeName.isEmpty())
- break;
- }
- }
-
- // Fall back to gconf
- if (themeName.isEmpty() && resolveGConf())
- themeName = getGConfString(QLS("/desktop/gnome/interface/gtk_theme"));
-
- return themeName;
-}
-
-// Get size of the arrow controls in a GtkSpinButton
-int QGtkStylePrivate::getSpinboxArrowSize() const
-{
- const int MIN_ARROW_WIDTH = 6;
- GtkWidget *spinButton = gtkWidget("GtkSpinButton");
- GtkStyle *style = spinButton->style;
- gint size = pango_font_description_get_size (style->font_desc);
- gint arrow_size;
- arrow_size = qMax(PANGO_PIXELS (size), MIN_ARROW_WIDTH) + style->xthickness;
- arrow_size += arrow_size%2 + 1;
- return arrow_size;
-}
-
-
-bool QGtkStylePrivate::isKDE4Session()
-{
- static int version = -1;
- if (version == -1)
- version = qgetenv("KDE_SESSION_VERSION").toInt();
- return (version == 4);
-}
-
-void QGtkStylePrivate::applyCustomPaletteHash()
-{
- QPalette menuPal = gtkWidgetPalette("GtkMenu");
- GdkColor gdkBg = gtkWidget("GtkMenu")->style->bg[GTK_STATE_NORMAL];
- QColor bgColor(gdkBg.red>>8, gdkBg.green>>8, gdkBg.blue>>8);
- menuPal.setBrush(QPalette::Base, bgColor);
- menuPal.setBrush(QPalette::Window, bgColor);
- qApp->setPalette(menuPal, "QMenu");
-
- QPalette toolbarPal = gtkWidgetPalette("GtkToolbar");
- qApp->setPalette(toolbarPal, "QToolBar");
-
- QPalette menuBarPal = gtkWidgetPalette("GtkMenuBar");
- qApp->setPalette(menuBarPal, "QMenuBar");
-}
-
-/*! \internal
- * Returns the gtk Widget that should be used to determine text foreground and background colors.
-*/
-GtkWidget* QGtkStylePrivate::getTextColorWidget() const
-{
- return gtkWidget("GtkEntry");
-}
-
-void QGtkStylePrivate::setupGtkWidget(GtkWidget* widget)
-{
- if (Q_GTK_IS_WIDGET(widget)) {
- static GtkWidget* protoLayout = 0;
- if (!protoLayout) {
- protoLayout = QGtkStylePrivate::gtk_fixed_new();
- QGtkStylePrivate::gtk_container_add((GtkContainer*)(gtkWidgetMap()->value("GtkWindow")), protoLayout);
- }
- Q_ASSERT(protoLayout);
-
- if (!widget->parent && !GTK_WIDGET_TOPLEVEL(widget))
- QGtkStylePrivate::gtk_container_add((GtkContainer*)(protoLayout), widget);
- QGtkStylePrivate::gtk_widget_realize(widget);
- }
-}
-
-void QGtkStylePrivate::removeWidgetFromMap(const QHashableLatin1Literal &path)
-{
- WidgetMap *map = gtkWidgetMap();
- WidgetMap::iterator it = map->find(path);
- if (it != map->end()) {
- free(const_cast<char *>(it.key().data()));
- map->erase(it);
- }
-}
-
-void QGtkStylePrivate::addWidgetToMap(GtkWidget *widget)
-{
- if (Q_GTK_IS_WIDGET(widget)) {
- gtk_widget_realize(widget);
- QHashableLatin1Literal widgetPath = classPath(widget);
-
- removeWidgetFromMap(widgetPath);
- gtkWidgetMap()->insert(widgetPath, widget);
-#ifdef DUMP_GTK_WIDGET_TREE
- qWarning("Inserted Gtk Widget: %s", widgetPath.data());
-#endif
- }
- }
-
-void QGtkStylePrivate::addAllSubWidgets(GtkWidget *widget, gpointer v)
-{
- Q_UNUSED(v);
- addWidgetToMap(widget);
- if (GTK_CHECK_TYPE ((widget), gtk_container_get_type()))
- gtk_container_forall((GtkContainer*)widget, addAllSubWidgets, NULL);
-}
-
-// Updates window/windowtext palette based on the indicated gtk widget
-QPalette QGtkStylePrivate::gtkWidgetPalette(const QHashableLatin1Literal &gtkWidgetName) const
-{
- GtkWidget *gtkWidget = QGtkStylePrivate::gtkWidget(gtkWidgetName);
- Q_ASSERT(gtkWidget);
- QPalette pal = QApplication::palette();
- GdkColor gdkBg = gtkWidget->style->bg[GTK_STATE_NORMAL];
- GdkColor gdkText = gtkWidget->style->fg[GTK_STATE_NORMAL];
- GdkColor gdkDisabledText = gtkWidget->style->fg[GTK_STATE_INSENSITIVE];
- QColor bgColor(gdkBg.red>>8, gdkBg.green>>8, gdkBg.blue>>8);
- QColor textColor(gdkText.red>>8, gdkText.green>>8, gdkText.blue>>8);
- QColor disabledTextColor(gdkDisabledText.red>>8, gdkDisabledText.green>>8, gdkDisabledText.blue>>8);
- pal.setBrush(QPalette::Window, bgColor);
- pal.setBrush(QPalette::Button, bgColor);
- pal.setBrush(QPalette::All, QPalette::WindowText, textColor);
- pal.setBrush(QPalette::Disabled, QPalette::WindowText, disabledTextColor);
- pal.setBrush(QPalette::All, QPalette::ButtonText, textColor);
- pal.setBrush(QPalette::Disabled, QPalette::ButtonText, disabledTextColor);
- return pal;
-}
-
-
-void QGtkStyleUpdateScheduler::updateTheme()
-{
- static QString oldTheme(QLS("qt_not_set"));
- QPixmapCache::clear();
-
- QFont font = QGtkStylePrivate::getThemeFont();
- if (QApplication::font() != font)
- qApp->setFont(font);
-
- if (oldTheme != QGtkStylePrivate::getThemeName()) {
- oldTheme = QGtkStylePrivate::getThemeName();
- QPalette newPalette = qApp->style()->standardPalette();
- QApplicationPrivate::setSystemPalette(newPalette);
- QApplication::setPalette(newPalette);
- if (!QGtkStylePrivate::instances.isEmpty()) {
- QGtkStylePrivate::instances.last()->initGtkWidgets();
- QGtkStylePrivate::instances.last()->applyCustomPaletteHash();
- }
- QList<QWidget*> widgets = QApplication::allWidgets();
- // Notify all widgets that size metrics might have changed
- foreach (QWidget *widget, widgets) {
- QEvent e(QEvent::StyleChange);
- QApplication::sendEvent(widget, &e);
- }
- }
- QIconLoader::instance()->updateSystemTheme();
-}
-
-void QGtkStylePrivate::addWidget(GtkWidget *widget)
-{
- if (widget) {
- setupGtkWidget(widget);
- addAllSubWidgets(widget);
- }
-}
-
-
-// Fetch the application font from the pango font description
-// contained in the theme.
-QFont QGtkStylePrivate::getThemeFont()
-{
- QFont font;
- GtkStyle *style = gtkStyle();
- if (style && qApp->desktopSettingsAware())
- {
- PangoFontDescription *gtk_font = style->font_desc;
- font.setPointSizeF((float)(pango_font_description_get_size(gtk_font))/PANGO_SCALE);
-
- QString family = QString::fromLatin1(pango_font_description_get_family(gtk_font));
- if (!family.isEmpty())
- font.setFamily(family);
-
- int weight = pango_font_description_get_weight(gtk_font);
- if (weight >= PANGO_WEIGHT_HEAVY)
- font.setWeight(QFont::Black);
- else if (weight >= PANGO_WEIGHT_BOLD)
- font.setWeight(QFont::Bold);
- else if (weight >= PANGO_WEIGHT_SEMIBOLD)
- font.setWeight(QFont::DemiBold);
- else if (weight >= PANGO_WEIGHT_NORMAL)
- font.setWeight(QFont::Normal);
- else
- font.setWeight(QFont::Light);
-
- PangoStyle fontstyle = pango_font_description_get_style(gtk_font);
- if (fontstyle == PANGO_STYLE_ITALIC)
- font.setStyle(QFont::StyleItalic);
- else if (fontstyle == PANGO_STYLE_OBLIQUE)
- font.setStyle(QFont::StyleOblique);
- else
- font.setStyle(QFont::StyleNormal);
- }
- return font;
-}
-
-
-// ----------- Native file dialogs -----------
-
-// Extract filter list from expressions of type: foo (*.a *.b *.c)"
-QStringList QGtkStylePrivate::extract_filter(const QString &rawFilter)
-{
- QString result = rawFilter;
- QRegExp r(QString::fromLatin1("^([^()]*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$"));
- int index = r.indexIn(result);
- if (index >= 0)
- result = r.cap(2);
- return result.split(QLatin1Char(' '));
-}
-
-extern QStringList qt_make_filter_list(const QString &filter);
-
-void QGtkStylePrivate::setupGtkFileChooser(GtkWidget* gtkFileChooser, QWidget *parent,
- const QString &dir, const QString &filter, QString *selectedFilter,
- QFileDialog::Options options, bool isSaveDialog,
- QMap<GtkFileFilter *, QString> *filterMap)
-{
- g_object_set(gtkFileChooser, "do-overwrite-confirmation", gboolean(!(options & QFileDialog::DontConfirmOverwrite)), NULL);
- g_object_set(gtkFileChooser, "local_only", gboolean(true), NULL);
- if (!filter.isEmpty()) {
- QStringList filters = qt_make_filter_list(filter);
- foreach (const QString &rawfilter, filters) {
- GtkFileFilter *gtkFilter = QGtkStylePrivate::gtk_file_filter_new ();
- QString name = rawfilter.left(rawfilter.indexOf(QLatin1Char('(')));
- QStringList extensions = extract_filter(rawfilter);
- QGtkStylePrivate::gtk_file_filter_set_name(gtkFilter, qPrintable(name.isEmpty() ? extensions.join(QLS(", ")) : name));
-
- foreach (const QString &fileExtension, extensions) {
- // Note Gtk file dialogs are by default case sensitive
- // and only supports basic glob syntax so we
- // rewrite .xyz to .[xX][yY][zZ]
- QString caseInsensitive;
- for (int i = 0 ; i < fileExtension.length() ; ++i) {
- QChar ch = fileExtension.at(i);
- if (ch.isLetter()) {
- caseInsensitive.append(
- QLatin1Char('[') +
- ch.toLower() +
- ch.toUpper() +
- QLatin1Char(']'));
- } else {
- caseInsensitive.append(ch);
- }
- }
- QGtkStylePrivate::gtk_file_filter_add_pattern (gtkFilter, qPrintable(caseInsensitive));
-
- }
- if (filterMap)
- filterMap->insert(gtkFilter, rawfilter);
- QGtkStylePrivate::gtk_file_chooser_add_filter((GtkFileChooser*)gtkFileChooser, gtkFilter);
- if (selectedFilter && (rawfilter == *selectedFilter))
- QGtkStylePrivate::gtk_file_chooser_set_filter((GtkFileChooser*)gtkFileChooser, gtkFilter);
- }
- }
-
- // Using the currently active window is not entirely correct, however
- // it gives more sensible behavior for applications that do not provide a
- // parent
- QWidget *modalFor = parent ? parent->window() : qApp->activeWindow();
- if (modalFor) {
- QGtkStylePrivate::gtk_widget_realize(gtkFileChooser); // Creates X window
- XSetTransientForHint(QGtkStylePrivate::gdk_x11_drawable_get_xdisplay(gtkFileChooser->window),
- QGtkStylePrivate::gdk_x11_drawable_get_xid(gtkFileChooser->window),
- modalFor->winId());
- QGtkStylePrivate::gdk_x11_window_set_user_time (gtkFileChooser->window, QX11Info::appUserTime());
-
- }
-
- QFileInfo fileinfo(dir);
- if (dir.isEmpty())
- fileinfo.setFile(QDir::currentPath());
- fileinfo.makeAbsolute();
- if (fileinfo.isDir()) {
- QGtkStylePrivate::gtk_file_chooser_set_current_folder((GtkFileChooser*)gtkFileChooser, qPrintable(dir));
- } else if (isSaveDialog) {
- QGtkStylePrivate::gtk_file_chooser_set_current_folder((GtkFileChooser*)gtkFileChooser, qPrintable(fileinfo.absolutePath()));
- QGtkStylePrivate::gtk_file_chooser_set_current_name((GtkFileChooser*)gtkFileChooser, qPrintable(fileinfo.fileName()));
- } else {
- QGtkStylePrivate::gtk_file_chooser_set_filename((GtkFileChooser*)gtkFileChooser, qPrintable(dir));
- }
-}
-
-QString QGtkStylePrivate::openFilename(QWidget *parent, const QString &caption, const QString &dir, const QString &filter,
- QString *selectedFilter, QFileDialog::Options options)
-{
- QMap<GtkFileFilter *, QString> filterMap;
- GtkWidget *gtkFileChooser = QGtkStylePrivate::gtk_file_chooser_dialog_new (qPrintable(caption),
- NULL,
- GTK_FILE_CHOOSER_ACTION_OPEN,
- GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
- GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
- NULL);
-
- setupGtkFileChooser(gtkFileChooser, parent, dir, filter, selectedFilter, options, false, &filterMap);
-
- QWidget modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- QString filename;
- if (QGtkStylePrivate::gtk_dialog_run ((GtkDialog*)gtkFileChooser) == GTK_RESPONSE_ACCEPT) {
- char *gtk_filename = QGtkStylePrivate::gtk_file_chooser_get_filename ((GtkFileChooser*)gtkFileChooser);
- filename = QString::fromUtf8(gtk_filename);
- g_free (gtk_filename);
- if (selectedFilter) {
- GtkFileFilter *gtkFilter = QGtkStylePrivate::gtk_file_chooser_get_filter ((GtkFileChooser*)gtkFileChooser);
- *selectedFilter = filterMap.value(gtkFilter);
- }
- }
-
- QApplicationPrivate::leaveModal(&modal_widget);
- gtk_widget_destroy (gtkFileChooser);
- return filename;
-}
-
-
-QString QGtkStylePrivate::openDirectory(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options)
-{
- QMap<GtkFileFilter *, QString> filterMap;
- GtkWidget *gtkFileChooser = QGtkStylePrivate::gtk_file_chooser_dialog_new (qPrintable(caption),
- NULL,
- GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
- GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
- GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
- NULL);
-
- setupGtkFileChooser(gtkFileChooser, parent, dir, QString(), 0, options);
- QWidget modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- QString filename;
- if (QGtkStylePrivate::gtk_dialog_run ((GtkDialog*)gtkFileChooser) == GTK_RESPONSE_ACCEPT) {
- char *gtk_filename = QGtkStylePrivate::gtk_file_chooser_get_filename ((GtkFileChooser*)gtkFileChooser);
- filename = QString::fromUtf8(gtk_filename);
- g_free (gtk_filename);
- }
-
- QApplicationPrivate::leaveModal(&modal_widget);
- gtk_widget_destroy (gtkFileChooser);
- return filename;
-}
-
-QStringList QGtkStylePrivate::openFilenames(QWidget *parent, const QString &caption, const QString &dir, const QString &filter,
- QString *selectedFilter, QFileDialog::Options options)
-{
- QStringList filenames;
- QMap<GtkFileFilter *, QString> filterMap;
- GtkWidget *gtkFileChooser = QGtkStylePrivate::gtk_file_chooser_dialog_new (qPrintable(caption),
- NULL,
- GTK_FILE_CHOOSER_ACTION_OPEN,
- GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
- GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
- NULL);
-
- setupGtkFileChooser(gtkFileChooser, parent, dir, filter, selectedFilter, options, false, &filterMap);
- g_object_set(gtkFileChooser, "select-multiple", gboolean(true), NULL);
-
- QWidget modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- if (gtk_dialog_run ((GtkDialog*)gtkFileChooser) == GTK_RESPONSE_ACCEPT) {
- GSList *gtk_file_names = QGtkStylePrivate::gtk_file_chooser_get_filenames((GtkFileChooser*)gtkFileChooser);
- for (GSList *iterator = gtk_file_names ; iterator; iterator = iterator->next)
- filenames << QString::fromUtf8((const char*)iterator->data);
- g_slist_free(gtk_file_names);
- if (selectedFilter) {
- GtkFileFilter *gtkFilter = QGtkStylePrivate::gtk_file_chooser_get_filter ((GtkFileChooser*)gtkFileChooser);
- *selectedFilter = filterMap.value(gtkFilter);
- }
- }
-
- QApplicationPrivate::leaveModal(&modal_widget);
- gtk_widget_destroy (gtkFileChooser);
- return filenames;
-}
-
-QString QGtkStylePrivate::saveFilename(QWidget *parent, const QString &caption, const QString &dir, const QString &filter,
- QString *selectedFilter, QFileDialog::Options options)
-{
- QMap<GtkFileFilter *, QString> filterMap;
- GtkWidget *gtkFileChooser = QGtkStylePrivate::gtk_file_chooser_dialog_new (qPrintable(caption),
- NULL,
- GTK_FILE_CHOOSER_ACTION_SAVE,
- GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
- GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
- NULL);
- setupGtkFileChooser(gtkFileChooser, parent, dir, filter, selectedFilter, options, true, &filterMap);
-
- QWidget modal_widget;
- modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
- modal_widget.setParent(parent, Qt::Window);
- QApplicationPrivate::enterModal(&modal_widget);
-
- QString filename;
- if (QGtkStylePrivate::gtk_dialog_run ((GtkDialog*)gtkFileChooser) == GTK_RESPONSE_ACCEPT) {
- char *gtk_filename = QGtkStylePrivate::gtk_file_chooser_get_filename ((GtkFileChooser*)gtkFileChooser);
- filename = QString::fromUtf8(gtk_filename);
- g_free (gtk_filename);
- if (selectedFilter) {
- GtkFileFilter *gtkFilter = QGtkStylePrivate::gtk_file_chooser_get_filter ((GtkFileChooser*)gtkFileChooser);
- *selectedFilter = filterMap.value(gtkFilter);
- }
- }
-
- QApplicationPrivate::leaveModal(&modal_widget);
- gtk_widget_destroy (gtkFileChooser);
- return filename;
-}
-
-QIcon QGtkStylePrivate::getFilesystemIcon(const QFileInfo &info)
-{
- QIcon icon;
- if (gnome_vfs_init && gnome_icon_lookup_sync) {
- gnome_vfs_init();
- GtkIconTheme *theme = gtk_icon_theme_get_default();
- QByteArray fileurl = QUrl::fromLocalFile(info.absoluteFilePath()).toEncoded();
- char * icon_name = gnome_icon_lookup_sync(theme,
- NULL,
- fileurl.data(),
- NULL,
- GNOME_ICON_LOOKUP_FLAGS_NONE,
- NULL);
- QString iconName = QString::fromUtf8(icon_name);
- g_free(icon_name);
- if (iconName.startsWith(QLatin1Char('/')))
- return QIcon(iconName);
- return QIcon::fromTheme(iconName);
- }
- return icon;
-}
-
-bool operator==(const QHashableLatin1Literal &l1, const QHashableLatin1Literal &l2)
-{
- return l1.size() == l2.size() || qstrcmp(l1.data(), l2.data()) == 0;
-}
-
-// copied from qHash.cpp
-uint qHash(const QHashableLatin1Literal &key)
-{
- int n = key.size();
- const uchar *p = reinterpret_cast<const uchar *>(key.data());
- uint h = 0;
- uint g;
-
- while (n--) {
- h = (h << 4) + *p++;
- if ((g = (h & 0xf0000000)) != 0)
- h ^= g >> 23;
- h &= ~g;
- }
- return h;
-}
-
-QT_END_NAMESPACE
-
-#endif // !defined(QT_NO_STYLE_GTK)
diff --git a/src/gui/styles/qgtkstyle_p.h b/src/gui/styles/qgtkstyle_p.h
deleted file mode 100644
index 15a98c8257..0000000000
--- a/src/gui/styles/qgtkstyle_p.h
+++ /dev/null
@@ -1,531 +0,0 @@
-/****************************************************************************
-**
-** 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 QGTKSTYLE_P_H
-#define QGTKSTYLE_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qglobal.h>
-#if !defined(QT_NO_STYLE_GTK)
-
-#include <QtCore/qstring.h>
-#include <QtCore/qstringbuilder.h>
-#include <QtCore/qcoreapplication.h>
-
-#include <QtGui/QFileDialog>
-
-#include <QtGui/QGtkStyle>
-#include <private/qcleanlooksstyle_p.h>
-
-#undef signals // Collides with GTK stymbols
-#include <gtk/gtk.h>
-
-typedef unsigned long XID;
-
-#undef GTK_OBJECT_FLAGS
-#define GTK_OBJECT_FLAGS(obj)(((GtkObject*)(obj))->flags)
-#define Q_GTK_IS_WIDGET(widget) widget && GTK_CHECK_TYPE ((widget), QGtkStylePrivate::gtk_widget_get_type())
-
-#define QLS(x) QLatin1String(x)
-
-QT_BEGIN_NAMESPACE
-
-// ### Qt 4.7 - merge with QLatin1Literal
-class QHashableLatin1Literal
-{
-public:
- int size() const { return m_size; }
- const char *data() const { return m_data; }
-
-#ifdef __SUNPRO_CC
- QHashableLatin1Literal(const char* str)
- : m_size(strlen(str)), m_data(str) {}
-#else
- template <int N>
- QHashableLatin1Literal(const char (&str)[N])
- : m_size(N - 1), m_data(str) {}
-#endif
-
- QHashableLatin1Literal(const QHashableLatin1Literal &other)
- : m_size(other.m_size), m_data(other.m_data)
- {}
-
- QHashableLatin1Literal &operator=(const QHashableLatin1Literal &other)
- {
- if (this == &other)
- return *this;
- *const_cast<int *>(&m_size) = other.m_size;
- *const_cast<char **>(&m_data) = const_cast<char *>(other.m_data);
- return *this;
- }
-
- QString toString() const { return QString::fromLatin1(m_data, m_size); }
-
- static QHashableLatin1Literal fromData(const char *str)
- {
- return QHashableLatin1Literal(str, qstrlen(str));
- }
-
-private:
- QHashableLatin1Literal(const char *str, int length)
- : m_size(length), m_data(str)
- {}
-
- const int m_size;
- const char *m_data;
-};
-
-bool operator==(const QHashableLatin1Literal &l1, const QHashableLatin1Literal &l2);
-inline bool operator!=(const QHashableLatin1Literal &l1, const QHashableLatin1Literal &l2) { return !operator==(l1, l2); }
-uint qHash(const QHashableLatin1Literal &key);
-
-QT_END_NAMESPACE
-
-class GConf;
-class GConfClient;
-
-typedef GConfClient* (*Ptr_gconf_client_get_default)();
-typedef char* (*Ptr_gconf_client_get_string)(GConfClient*, const char*, GError **);
-typedef bool (*Ptr_gconf_client_get_bool)(GConfClient*, const char*, GError **);
-
-typedef void (*Ptr_gtk_init)(int *, char ***);
-typedef GtkWidget* (*Ptr_gtk_window_new) (GtkWindowType);
-typedef GtkStyle* (*Ptr_gtk_style_attach)(GtkStyle *, GdkWindow *);
-typedef void (*Ptr_gtk_widget_destroy) (GtkWidget *);
-typedef void (*Ptr_gtk_widget_realize) (GtkWidget *);
-typedef void (*Ptr_gtk_widget_set_default_direction) (GtkTextDirection);
-typedef void (*Ptr_gtk_widget_modify_color)(GtkWidget *widget, GtkStateType state, const GdkColor *color);
-typedef GtkWidget* (*Ptr_gtk_arrow_new)(GtkArrowType, GtkShadowType);
-typedef GtkWidget* (*Ptr_gtk_menu_item_new_with_label)(const gchar *);
-typedef GtkWidget* (*Ptr_gtk_separator_menu_item_new)(void);
-typedef GtkWidget* (*Ptr_gtk_check_menu_item_new_with_label)(const gchar *);
-typedef GtkWidget* (*Ptr_gtk_menu_bar_new)(void);
-typedef GtkWidget* (*Ptr_gtk_menu_new)(void);
-typedef GtkWidget* (*Ptr_gtk_combo_box_entry_new)(void);
-typedef GtkWidget* (*Ptr_gtk_toolbar_new)(void);
-typedef GtkWidget* (*Ptr_gtk_spin_button_new)(GtkAdjustment*, double, int);
-typedef GtkWidget* (*Ptr_gtk_button_new)(void);
-typedef GtkWidget* (*Ptr_gtk_tool_button_new)(GtkWidget *, const gchar *);
-typedef GtkWidget* (*Ptr_gtk_hbutton_box_new)(void);
-typedef GtkWidget* (*Ptr_gtk_check_button_new)(void);
-typedef GtkWidget* (*Ptr_gtk_radio_button_new)(GSList *);
-typedef GtkWidget* (*Ptr_gtk_notebook_new)(void);
-typedef GtkWidget* (*Ptr_gtk_progress_bar_new)(void);
-typedef GtkWidget* (*Ptr_gtk_hscale_new)(GtkAdjustment*);
-typedef GtkWidget* (*Ptr_gtk_vscale_new)(GtkAdjustment*);
-typedef GtkWidget* (*Ptr_gtk_hscrollbar_new)(GtkAdjustment*);
-typedef GtkWidget* (*Ptr_gtk_vscrollbar_new)(GtkAdjustment*);
-typedef GtkWidget* (*Ptr_gtk_scrolled_window_new)(GtkAdjustment*, GtkAdjustment*);
-typedef gchar* (*Ptr_gtk_check_version)(guint, guint, guint);
-typedef GtkToolItem* (*Ptr_gtk_separator_tool_item_new) (void);
-typedef GtkWidget* (*Ptr_gtk_entry_new)(void);
-typedef GtkWidget* (*Ptr_gtk_tree_view_new)(void);
-typedef GtkTreeViewColumn* (*Ptr_gtk_tree_view_get_column)(GtkTreeView *, gint);
-typedef GtkWidget* (*Ptr_gtk_combo_box_new)(void);
-typedef GtkWidget* (*Ptr_gtk_frame_new)(const gchar *);
-typedef GtkWidget* (*Ptr_gtk_expander_new)(const gchar*);
-typedef GtkWidget* (*Ptr_gtk_statusbar_new)(void);
-typedef GtkSettings* (*Ptr_gtk_settings_get_default)(void);
-typedef GtkAdjustment* (*Ptr_gtk_range_get_adjustment)(GtkRange *);
-typedef void (*Ptr_gtk_range_set_adjustment)(GtkRange *, GtkAdjustment *);
-typedef void (*Ptr_gtk_progress_configure)(GtkProgress *, double, double, double);
-typedef void (*Ptr_gtk_range_set_inverted)(GtkRange*, bool);
-typedef void (*Ptr_gtk_container_add)(GtkContainer *container, GtkWidget *widget);
-typedef GtkIconSet* (*Ptr_gtk_icon_factory_lookup_default) (const gchar*);
-typedef GtkIconTheme* (*Ptr_gtk_icon_theme_get_default) (void);
-typedef void (*Ptr_gtk_widget_style_get)(GtkWidget *, const gchar *first_property_name, ...);
-typedef GtkTreeViewColumn* (*Ptr_gtk_tree_view_column_new)(void);
-typedef GtkWidget* (*Ptr_gtk_fixed_new)(void);
-typedef GdkPixbuf* (*Ptr_gtk_icon_set_render_icon)(GtkIconSet *, GtkStyle *, GtkTextDirection, GtkStateType, GtkIconSize, GtkWidget *,const char *);
-typedef void (*Ptr_gtk_tree_view_append_column) (GtkTreeView*, GtkTreeViewColumn*);
-typedef void (*Ptr_gtk_paint_check) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_box) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_box_gap) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint , gint, GtkPositionType, gint gap_x, gint gap_width);
-typedef void (*Ptr_gtk_paint_resize_grip) (GtkStyle*,GdkWindow*, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, GdkWindowEdge, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_focus) (GtkStyle*,GdkWindow*, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_shadow) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_slider) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint, GtkOrientation);
-typedef void (*Ptr_gtk_paint_expander) (GtkStyle*,GdkWindow*, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , GtkExpanderStyle );
-typedef void (*Ptr_gtk_paint_handle) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint, GtkOrientation);
-typedef void (*Ptr_gtk_paint_arrow) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, GtkArrowType, gboolean, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_option) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_flat_box) (GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint);
-typedef void (*Ptr_gtk_paint_extension) (GtkStyle *, GdkWindow *, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint, gint, GtkPositionType);
-typedef void (*Ptr_gtk_adjustment_configure) (GtkAdjustment *, double, double, double, double, double, double);
-typedef GtkObject* (*Ptr_gtk_adjustment_new) (double, double, double, double, double, double);
-typedef void (*Ptr_gtk_paint_hline) (GtkStyle *, GdkWindow *, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint y);
-typedef void (*Ptr_gtk_paint_vline) (GtkStyle *, GdkWindow *, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint);
-typedef void (*Ptr_gtk_menu_item_set_submenu) (GtkMenuItem *, GtkWidget *);
-typedef void (*Ptr_gtk_container_forall) (GtkContainer *, GtkCallback, gpointer);
-typedef void (*Ptr_gtk_widget_size_allocate) (GtkWidget *, GtkAllocation*);
-typedef void (*Ptr_gtk_widget_size_request) (GtkWidget *widget, GtkRequisition *requisition);
-typedef void (*Ptr_gtk_widget_set_direction) (GtkWidget *, GtkTextDirection);
-typedef void (*Ptr_gtk_widget_path) (GtkWidget *, guint *, gchar **, gchar**);
-
-typedef void (*Ptr_gtk_toolbar_insert) (GtkToolbar *toolbar, GtkToolItem *item, int pos);
-typedef void (*Ptr_gtk_menu_shell_append)(GtkMenuShell *, GtkWidget *);
-typedef GtkType (*Ptr_gtk_container_get_type) (void);
-typedef GtkType (*Ptr_gtk_window_get_type) (void);
-typedef GtkType (*Ptr_gtk_widget_get_type) (void);
-typedef GtkStyle* (*Ptr_gtk_rc_get_style_by_paths) (GtkSettings *, const char *, const char *, GType);
-typedef gint (*Ptr_pango_font_description_get_size) (const PangoFontDescription *);
-typedef PangoWeight (*Ptr_pango_font_description_get_weight) (const PangoFontDescription *);
-typedef const char* (*Ptr_pango_font_description_get_family) (const PangoFontDescription *);
-typedef PangoStyle (*Ptr_pango_font_description_get_style) (const PangoFontDescription *desc);
-typedef gboolean (*Ptr_gtk_file_chooser_set_current_folder)(GtkFileChooser *, const gchar *);
-typedef GtkFileFilter* (*Ptr_gtk_file_filter_new)(void);
-typedef void (*Ptr_gtk_file_filter_set_name)(GtkFileFilter *, const gchar *);
-typedef void (*Ptr_gtk_file_filter_add_pattern)(GtkFileFilter *filter, const gchar *pattern);
-typedef void (*Ptr_gtk_file_chooser_add_filter)(GtkFileChooser *chooser, GtkFileFilter *filter);
-typedef void (*Ptr_gtk_file_chooser_set_filter)(GtkFileChooser *chooser, GtkFileFilter *filter);
-typedef GtkFileFilter* (*Ptr_gtk_file_chooser_get_filter)(GtkFileChooser *chooser);
-typedef gchar* (*Ptr_gtk_file_chooser_get_filename)(GtkFileChooser *chooser);
-typedef GSList* (*Ptr_gtk_file_chooser_get_filenames)(GtkFileChooser *chooser);
-typedef GtkWidget* (*Ptr_gtk_file_chooser_dialog_new)(const gchar *title,
- GtkWindow *parent,
- GtkFileChooserAction action,
- const gchar *first_button_text,
- ...);
-typedef void (*Ptr_gtk_file_chooser_set_current_name) (GtkFileChooser *, const gchar *);
-typedef gboolean (*Ptr_gtk_file_chooser_set_filename) (GtkFileChooser *chooser, const gchar *name);
-typedef gint (*Ptr_gtk_dialog_run) (GtkDialog*);
-typedef void (*Ptr_gtk_border_free)(GtkBorder *);
-
-typedef guchar* (*Ptr_gdk_pixbuf_get_pixels) (const GdkPixbuf *pixbuf);
-typedef int (*Ptr_gdk_pixbuf_get_width) (const GdkPixbuf *pixbuf);
-typedef void (*Ptr_gdk_color_free) (const GdkColor *);
-typedef int (*Ptr_gdk_pixbuf_get_height) (const GdkPixbuf *pixbuf);
-typedef GdkPixbuf* (*Ptr_gdk_pixbuf_get_from_drawable) (GdkPixbuf *dest, GdkDrawable *src,
- GdkColormap *cmap, int src_x,
- int src_y, int dest_x, int dest_y,
- int width, int height);
-typedef GdkPixmap* (*Ptr_gdk_pixmap_new) (GdkDrawable *drawable, gint width, gint height, gint depth);
-typedef GdkPixbuf* (*Ptr_gdk_pixbuf_new) (GdkColorspace colorspace, gboolean has_alpha,
- int bits_per_sample, int width, int height);
-typedef void (*Ptr_gdk_draw_rectangle) (GdkDrawable *drawable, GdkGC *gc,
- gboolean filled, gint x, gint y, gint width, gint height);
-typedef void (*Ptr_gdk_pixbuf_unref)(GdkPixbuf *);
-typedef void (*Ptr_gdk_drawable_unref)(GdkDrawable *);
-typedef gint (*Ptr_gdk_drawable_get_depth)(GdkDrawable *);
-typedef void (*Ptr_gdk_x11_window_set_user_time) (GdkWindow *window, guint32);
-typedef XID (*Ptr_gdk_x11_drawable_get_xid) (GdkDrawable *);
-typedef Display* (*Ptr_gdk_x11_drawable_get_xdisplay) ( GdkDrawable *);
-
-
-QT_BEGIN_NAMESPACE
-
-typedef QStringList (*_qt_filedialog_open_filenames_hook)(QWidget * parent, const QString &caption, const QString &dir,
- const QString &filter, QString *selectedFilter, QFileDialog::Options options);
-typedef QString (*_qt_filedialog_open_filename_hook) (QWidget * parent, const QString &caption, const QString &dir,
- const QString &filter, QString *selectedFilter, QFileDialog::Options options);
-typedef QString (*_qt_filedialog_save_filename_hook) (QWidget * parent, const QString &caption, const QString &dir,
- const QString &filter, QString *selectedFilter, QFileDialog::Options options);
-typedef QString (*_qt_filedialog_existing_directory_hook)(QWidget *parent, const QString &caption, const QString &dir,
- QFileDialog::Options options);
-
-extern Q_GUI_EXPORT _qt_filedialog_open_filename_hook qt_filedialog_open_filename_hook;
-extern Q_GUI_EXPORT _qt_filedialog_open_filenames_hook qt_filedialog_open_filenames_hook;
-extern Q_GUI_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook;
-extern Q_GUI_EXPORT _qt_filedialog_existing_directory_hook qt_filedialog_existing_directory_hook;
-
-class QGtkStylePrivate;
-
-class QGtkStyleFilter : public QObject
-{
-public:
- QGtkStyleFilter(QGtkStylePrivate* sp)
- : stylePrivate(sp)
- {}
-private:
- QGtkStylePrivate* stylePrivate;
- bool eventFilter(QObject *obj, QEvent *e);
-};
-
-typedef enum {
- GNOME_ICON_LOOKUP_FLAGS_NONE = 0,
- GNOME_ICON_LOOKUP_FLAGS_EMBEDDING_TEXT = 1<<0,
- GNOME_ICON_LOOKUP_FLAGS_SHOW_SMALL_IMAGES_AS_THEMSELVES = 1<<1,
- GNOME_ICON_LOOKUP_FLAGS_ALLOW_SVG_AS_THEMSELVES = 1<<2
-} GnomeIconLookupFlags;
-
-typedef enum {
- GNOME_ICON_LOOKUP_RESULT_FLAGS_NONE = 0,
- GNOME_ICON_LOOKUP_RESULT_FLAGS_THUMBNAIL = 1<<0
-} GnomeIconLookupResultFlags;
-
-struct GnomeThumbnailFactory;
-typedef gboolean (*Ptr_gnome_vfs_init) (void);
-typedef char* (*Ptr_gnome_icon_lookup_sync) (
- GtkIconTheme *icon_theme,
- GnomeThumbnailFactory *,
- const char *file_uri,
- const char *custom_icon,
- GnomeIconLookupFlags flags,
- GnomeIconLookupResultFlags *result);
-
-class QGtkStylePrivate : public QCleanlooksStylePrivate
-{
- Q_DECLARE_PUBLIC(QGtkStyle)
-public:
- QGtkStylePrivate();
- ~QGtkStylePrivate();
-
- QGtkStyleFilter filter;
-
- static GtkWidget* gtkWidget(const QHashableLatin1Literal &path);
- static GtkStyle* gtkStyle(const QHashableLatin1Literal &path = QHashableLatin1Literal("GtkWindow"));
-
- virtual void resolveGtk() const;
- virtual void initGtkMenu() const;
- virtual void initGtkTreeview() const;
- virtual void initGtkWidgets() const;
-
- static void cleanupGtkWidgets();
-
- static bool isKDE4Session();
- void applyCustomPaletteHash();
- static QFont getThemeFont();
- static bool isThemeAvailable() { return gtkStyle() != 0; }
-
- static bool getGConfBool(const QString &key, bool fallback = 0);
- static QString getGConfString(const QString &key, const QString &fallback = QString());
-
- static QString getThemeName();
- virtual int getSpinboxArrowSize() const;
-
- static void setupGtkFileChooser(GtkWidget* gtkFileChooser, QWidget *parent,
- const QString &dir, const QString &filter, QString *selectedFilter,
- QFileDialog::Options options, bool isSaveDialog = false,
- QMap<GtkFileFilter *, QString> *filterMap = 0);
-
- static QString openFilename(QWidget *parent, const QString &caption, const QString &dir, const QString &filter,
- QString *selectedFilter, QFileDialog::Options options);
- static QString saveFilename(QWidget *parent, const QString &caption, const QString &dir, const QString &filter,
- QString *selectedFilter, QFileDialog::Options options);
- static QString openDirectory(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options);
- static QStringList openFilenames(QWidget *parent, const QString &caption, const QString &dir, const QString &filter,
- QString *selectedFilter, QFileDialog::Options options);
- static QIcon getFilesystemIcon(const QFileInfo &);
-
- static Ptr_gtk_container_forall gtk_container_forall;
- static Ptr_gtk_init gtk_init;
- static Ptr_gtk_style_attach gtk_style_attach;
- static Ptr_gtk_window_new gtk_window_new;
- static Ptr_gtk_widget_destroy gtk_widget_destroy;
- static Ptr_gtk_widget_realize gtk_widget_realize;
- static Ptr_gtk_widget_set_default_direction gtk_widget_set_default_direction;
- static Ptr_gtk_widget_modify_color gtk_widget_modify_fg;
- static Ptr_gtk_widget_modify_color gtk_widget_modify_bg;
- static Ptr_gtk_menu_item_new_with_label gtk_menu_item_new_with_label;
- static Ptr_gtk_arrow_new gtk_arrow_new;
- static Ptr_gtk_check_menu_item_new_with_label gtk_check_menu_item_new_with_label;
- static Ptr_gtk_menu_bar_new gtk_menu_bar_new;
- static Ptr_gtk_menu_new gtk_menu_new;
- static Ptr_gtk_expander_new gtk_expander_new;
- static Ptr_gtk_button_new gtk_button_new;
- static Ptr_gtk_tool_button_new gtk_tool_button_new;
- static Ptr_gtk_hbutton_box_new gtk_hbutton_box_new;
- static Ptr_gtk_check_button_new gtk_check_button_new;
- static Ptr_gtk_radio_button_new gtk_radio_button_new;
- static Ptr_gtk_spin_button_new gtk_spin_button_new;
- static Ptr_gtk_separator_tool_item_new gtk_separator_tool_item_new;
- static Ptr_gtk_toolbar_insert gtk_toolbar_insert;
- static Ptr_gtk_frame_new gtk_frame_new;
- static Ptr_gtk_statusbar_new gtk_statusbar_new;
- static Ptr_gtk_entry_new gtk_entry_new;
- static Ptr_gtk_hscale_new gtk_hscale_new;
- static Ptr_gtk_vscale_new gtk_vscale_new;
- static Ptr_gtk_hscrollbar_new gtk_hscrollbar_new;
- static Ptr_gtk_vscrollbar_new gtk_vscrollbar_new;
- static Ptr_gtk_scrolled_window_new gtk_scrolled_window_new;
- static Ptr_gtk_notebook_new gtk_notebook_new;
- static Ptr_gtk_toolbar_new gtk_toolbar_new;
- static Ptr_gtk_tree_view_new gtk_tree_view_new;
- static Ptr_gtk_tree_view_get_column gtk_tree_view_get_column;
- static Ptr_gtk_combo_box_new gtk_combo_box_new;
- static Ptr_gtk_combo_box_entry_new gtk_combo_box_entry_new;
- static Ptr_gtk_progress_bar_new gtk_progress_bar_new;
- static Ptr_gtk_container_add gtk_container_add;
- static Ptr_gtk_menu_shell_append gtk_menu_shell_append;
- static Ptr_gtk_progress_configure gtk_progress_configure;
- static Ptr_gtk_range_get_adjustment gtk_range_get_adjustment;
- static Ptr_gtk_range_set_adjustment gtk_range_set_adjustment;
- static Ptr_gtk_range_set_inverted gtk_range_set_inverted;
- static Ptr_gtk_icon_factory_lookup_default gtk_icon_factory_lookup_default;
- static Ptr_gtk_icon_theme_get_default gtk_icon_theme_get_default;
- static Ptr_gtk_widget_style_get gtk_widget_style_get;
- static Ptr_gtk_icon_set_render_icon gtk_icon_set_render_icon;
- static Ptr_gtk_fixed_new gtk_fixed_new;
- static Ptr_gtk_tree_view_column_new gtk_tree_view_column_new;
- static Ptr_gtk_tree_view_append_column gtk_tree_view_append_column;
- static Ptr_gtk_paint_check gtk_paint_check;
- static Ptr_gtk_paint_box gtk_paint_box;
- static Ptr_gtk_paint_box_gap gtk_paint_box_gap;
- static Ptr_gtk_paint_flat_box gtk_paint_flat_box;
- static Ptr_gtk_paint_option gtk_paint_option;
- static Ptr_gtk_paint_extension gtk_paint_extension;
- static Ptr_gtk_paint_slider gtk_paint_slider;
- static Ptr_gtk_paint_shadow gtk_paint_shadow;
- static Ptr_gtk_paint_resize_grip gtk_paint_resize_grip;
- static Ptr_gtk_paint_focus gtk_paint_focus;
- static Ptr_gtk_paint_arrow gtk_paint_arrow;
- static Ptr_gtk_paint_handle gtk_paint_handle;
- static Ptr_gtk_paint_expander gtk_paint_expander;
- static Ptr_gtk_adjustment_configure gtk_adjustment_configure;
- static Ptr_gtk_adjustment_new gtk_adjustment_new;
- static Ptr_gtk_paint_vline gtk_paint_vline;
- static Ptr_gtk_paint_hline gtk_paint_hline;
- static Ptr_gtk_menu_item_set_submenu gtk_menu_item_set_submenu;
- static Ptr_gtk_settings_get_default gtk_settings_get_default;
- static Ptr_gtk_separator_menu_item_new gtk_separator_menu_item_new;
- static Ptr_gtk_widget_size_allocate gtk_widget_size_allocate;
- static Ptr_gtk_widget_size_request gtk_widget_size_request;
- static Ptr_gtk_widget_set_direction gtk_widget_set_direction;
- static Ptr_gtk_widget_path gtk_widget_path;
- static Ptr_gtk_container_get_type gtk_container_get_type;
- static Ptr_gtk_window_get_type gtk_window_get_type;
- static Ptr_gtk_widget_get_type gtk_widget_get_type;
- static Ptr_gtk_rc_get_style_by_paths gtk_rc_get_style_by_paths;
- static Ptr_gtk_check_version gtk_check_version;
- static Ptr_gtk_border_free gtk_border_free;
-
- static Ptr_pango_font_description_get_size pango_font_description_get_size;
- static Ptr_pango_font_description_get_weight pango_font_description_get_weight;
- static Ptr_pango_font_description_get_family pango_font_description_get_family;
- static Ptr_pango_font_description_get_style pango_font_description_get_style;
-
- static Ptr_gtk_file_filter_new gtk_file_filter_new;
- static Ptr_gtk_file_filter_set_name gtk_file_filter_set_name;
- static Ptr_gtk_file_filter_add_pattern gtk_file_filter_add_pattern;
- static Ptr_gtk_file_chooser_add_filter gtk_file_chooser_add_filter;
- static Ptr_gtk_file_chooser_set_filter gtk_file_chooser_set_filter;
- static Ptr_gtk_file_chooser_get_filter gtk_file_chooser_get_filter;
- static Ptr_gtk_file_chooser_dialog_new gtk_file_chooser_dialog_new;
- static Ptr_gtk_file_chooser_set_current_folder gtk_file_chooser_set_current_folder;
- static Ptr_gtk_file_chooser_get_filename gtk_file_chooser_get_filename;
- static Ptr_gtk_file_chooser_get_filenames gtk_file_chooser_get_filenames;
- static Ptr_gtk_file_chooser_set_current_name gtk_file_chooser_set_current_name;
- static Ptr_gtk_dialog_run gtk_dialog_run;
- static Ptr_gtk_file_chooser_set_filename gtk_file_chooser_set_filename;
-
- static Ptr_gdk_pixbuf_get_pixels gdk_pixbuf_get_pixels;
- static Ptr_gdk_pixbuf_get_width gdk_pixbuf_get_width;
- static Ptr_gdk_pixbuf_get_height gdk_pixbuf_get_height;
- static Ptr_gdk_pixmap_new gdk_pixmap_new;
- static Ptr_gdk_pixbuf_new gdk_pixbuf_new;
- static Ptr_gdk_pixbuf_get_from_drawable gdk_pixbuf_get_from_drawable;
- static Ptr_gdk_draw_rectangle gdk_draw_rectangle;
- static Ptr_gdk_pixbuf_unref gdk_pixbuf_unref;
- static Ptr_gdk_drawable_unref gdk_drawable_unref;
- static Ptr_gdk_drawable_get_depth gdk_drawable_get_depth;
- static Ptr_gdk_color_free gdk_color_free;
- static Ptr_gdk_x11_window_set_user_time gdk_x11_window_set_user_time;
- static Ptr_gdk_x11_drawable_get_xid gdk_x11_drawable_get_xid;
- static Ptr_gdk_x11_drawable_get_xdisplay gdk_x11_drawable_get_xdisplay;
-
- static Ptr_gconf_client_get_default gconf_client_get_default;
- static Ptr_gconf_client_get_string gconf_client_get_string;
- static Ptr_gconf_client_get_bool gconf_client_get_bool;
-
- static Ptr_gnome_icon_lookup_sync gnome_icon_lookup_sync;
- static Ptr_gnome_vfs_init gnome_vfs_init;
-
- virtual QPalette gtkWidgetPalette(const QHashableLatin1Literal &gtkWidgetName) const;
-
-protected:
- typedef QHash<QHashableLatin1Literal, GtkWidget*> WidgetMap;
-
- static inline void destroyWidgetMap()
- {
- cleanupGtkWidgets();
- delete widgetMap;
- widgetMap = 0;
- }
-
- static inline WidgetMap *gtkWidgetMap()
- {
- if (!widgetMap) {
- widgetMap = new WidgetMap();
- qAddPostRoutine(destroyWidgetMap);
- }
- return widgetMap;
- }
-
- static QStringList extract_filter(const QString &rawFilter);
-
- virtual GtkWidget* getTextColorWidget() const;
- static void setupGtkWidget(GtkWidget* widget);
- static void addWidgetToMap(GtkWidget* widget);
- static void addAllSubWidgets(GtkWidget *widget, gpointer v = 0);
- static void addWidget(GtkWidget *widget);
- static void removeWidgetFromMap(const QHashableLatin1Literal &path);
-
- virtual void init();
-
-private:
- static QList<QGtkStylePrivate *> instances;
- static WidgetMap *widgetMap;
- friend class QGtkStyleUpdateScheduler;
-};
-
-// Helper to ensure that we have polished all our gtk widgets
-// before updating our own palettes
-class QGtkStyleUpdateScheduler : public QObject
-{
- Q_OBJECT
-public slots:
- void updateTheme();
-};
-
-QT_END_NAMESPACE
-
-#endif // !QT_NO_STYLE_GTK
-#endif // QGTKSTYLE_P_H
diff --git a/src/gui/styles/qmacstyle.qdoc b/src/gui/styles/qmacstyle.qdoc
deleted file mode 100644
index 2f42d7156b..0000000000
--- a/src/gui/styles/qmacstyle.qdoc
+++ /dev/null
@@ -1,247 +0,0 @@
-/****************************************************************************
-**
-** 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 documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** 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 Free Documentation License
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of this
-** file.
-**
-** If you have questions regarding the use of this file, please contact
-** Nokia at qt-info@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-/*!
- \class QMacStyle
- \brief The QMacStyle class provides a Mac OS X style using the Apple Appearance Manager.
-
- \ingroup appearance
-
- This class is implemented as a wrapper to the HITheme
- APIs, allowing applications to be styled according to the current
- theme in use on Mac OS X. This is done by having primitives
- in QStyle implemented in terms of what Mac OS X would normally theme.
-
- \warning This style is only available on Mac OS X because it relies on the
- HITheme APIs.
-
- There are additional issues that should be taken
- into consideration to make an application compatible with the
- \link http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/index.html
- Apple Human Interface Guidelines \endlink. Some of these issues are outlined
- below.
-
- \list
-
- \i Layout - The restrictions on window layout are such that some
- aspects of layout that are style-dependent cannot be achieved
- using QLayout. Changes are being considered (and feedback would be
- appreciated) to make layouts QStyle-able. Some of the restrictions
- involve horizontal and vertical widget alignment and widget size
- (covered below).
-
- \i Widget size - Mac OS X allows widgets to have specific fixed sizes. Qt
- does not fully implement this behavior so as to maintain cross-platform
- compatibility. As a result some widgets sizes may be inappropriate (and
- subsequently not rendered correctly by the HITheme APIs).The
- QWidget::sizeHint() will return the appropriate size for many
- managed widgets (widgets enumerated in \l QStyle::ContentsType).
-
- \i Effects - QMacStyle uses HITheme for performing most of the drawing, but
- also uses emulation in a few cases where HITheme does not provide the
- required functionality (for example, tab bars on Panther, the toolbar
- separator, etc). We tried to make the emulation as close to the original as
- possible. Please report any issues you see in effects or non-standard
- widgets.
-
- \endlist
-
- There are other issues that need to be considered in the feel of
- your application (including the general color scheme to match the
- Aqua colors). The Guidelines mentioned above will remain current
- with new advances and design suggestions for Mac OS X.
-
- Note that the functions provided by QMacStyle are
- reimplementations of QStyle functions; see QStyle for their
- documentation.
-
- \img qmacstyle.png
- \sa QWindowsXPStyle, QWindowsStyle, QPlastiqueStyle, QCDEStyle, QMotifStyle
-*/
-
-
-/*!
- \enum QMacStyle::WidgetSizePolicy
-
- \value SizeSmall
- \value SizeLarge
- \value SizeMini
- \value SizeDefault
- \omitvalue SizeNone
-*/
-
-/*! \fn QMacStyle::QMacStyle()
- Constructs a QMacStyle object.
-*/
-
-/*! \fn QMacStyle::~QMacStyle()
- Destructs a QMacStyle object.
-*/
-
-/*! \fn void QMacStyle::polish(QPalette &pal)
- \reimp
-*/
-
-/*! \fn void QMacStyle::polish(QApplication *)
- \reimp
-*/
-
-/*! \fn void QMacStyle::unpolish(QApplication *)
- \reimp
-*/
-
-/*! \fn void QMacStyle::polish(QWidget* w)
- \reimp
-*/
-
-/*! \fn void QMacStyle::unpolish(QWidget* w)
- \reimp
-*/
-
-/*! \fn int QMacStyle::pixelMetric(PixelMetric metric, const QStyleOption *opt, const QWidget *widget) const
- \reimp
-*/
-
-/*! \fn QPalette QMacStyle::standardPalette() const
- \reimp
-*/
-
-/*! \fn int QMacStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w, QStyleHintReturn *hret) const
- \reimp
-*/
-
-/*! \fn QPixmap QMacStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const
- \reimp
-*/
-
-/*! \fn QPixmap QMacStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget) const
- \reimp
-*/
-
-/*!
- \enum QMacStyle::FocusRectPolicy
-
- This type is used to signify a widget's focus rectangle policy.
-
- \value FocusEnabled show a focus rectangle when the widget has focus.
- \value FocusDisabled never show a focus rectangle for the widget.
- \value FocusDefault show a focus rectangle when the widget has
- focus and the widget is a QSpinWidget, QDateTimeEdit, QLineEdit,
- QListBox, QListView, editable QTextEdit, or one of their
- subclasses.
-*/
-
-/*! \fn void QMacStyle::setFocusRectPolicy(QWidget *w, FocusRectPolicy policy)
- \obsolete
- Sets the focus rectangle policy of \a w. The \a policy can be one of
- \l{QMacStyle::FocusRectPolicy}.
-
- This is now simply an interface to the Qt::WA_MacShowFocusRect attribute and the
- FocusDefault value does nothing anymore. If you want to set a widget back
- to its default value, you must save the old value of the attribute before
- you change it.
-
- \sa focusRectPolicy() QWidget::setAttribute()
-*/
-
-/*! \fn QMacStyle::FocusRectPolicy QMacStyle::focusRectPolicy(const QWidget *w)
- \obsolete
- Returns the focus rectangle policy for the widget \a w.
-
- The focus rectangle policy can be one of \l{QMacStyle::FocusRectPolicy}.
-
- In 4.3 and up this function will simply test for the
- Qt::WA_MacShowFocusRect attribute and will never return
- QMacStyle::FocusDefault.
-
- \sa setFocusRectPolicy(), QWidget::testAttribute()
-*/
-
-/*! \fn void QMacStyle::setWidgetSizePolicy(const QWidget *widget, WidgetSizePolicy policy)
-
- \obsolete
-
- Call QWidget::setAttribute() with Qt::WA_MacMiniSize, Qt::WA_MacSmallSize,
- or Qt::WA_MacNormalSize instead.
-*/
-
-/*! \fn QMacStyle::WidgetSizePolicy QMacStyle::widgetSizePolicy(const QWidget *widget)
- \obsolete
-
- Call QWidget::testAttribute() with Qt::WA_MacMiniSize, Qt::WA_MacSmallSize,
- or Qt::WA_MacNormalSize instead.
-*/
-
-/*! \fn void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p, const QWidget *w) const
-
- \reimp
-*/
-
-/*! \fn void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p, const QWidget *w) const
-
- \reimp
-*/
-
-/*! \fn QRect QMacStyle::subElementRect(SubElement sr, const QStyleOption *opt, const QWidget *widget) const
-
- \reimp
-*/
-
-/*! \fn void QMacStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *widget) const
- \reimp
-*/
-
-/*! \fn QStyle::SubControl QMacStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, const QPoint &pt, const QWidget *widget) const
- \reimp
-*/
-
-/*! \fn QRect QMacStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc, const QWidget *widget) const
- \reimp
-*/
-
-/*! \fn QSize QMacStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt, const QSize &csz, const QWidget *widget) const
- \reimp
-*/
-
-/*! \fn void QMacStyle::drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole) const
- \reimp
-*/
-
-/*! \fn bool QMacStyle::event(QEvent *e)
- \reimp
-*/
-
-/*! \fn QIcon QMacStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt, const QWidget *widget) const
- \internal
-*/
-
-/*! \fn int QMacStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2, Qt::Orientation orientation, const QStyleOption *option, const QWidget *widget) const
-
- \internal
-*/
-
diff --git a/src/gui/styles/qmacstyle_mac.h b/src/gui/styles/qmacstyle_mac.h
deleted file mode 100644
index 78a25ce9b2..0000000000
--- a/src/gui/styles/qmacstyle_mac.h
+++ /dev/null
@@ -1,148 +0,0 @@
-/****************************************************************************
-**
-** 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 QMACSTYLE_MAC_H
-#define QMACSTYLE_MAC_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-
-class QPalette;
-
-#if defined(QT_PLUGIN)
-#define Q_GUI_EXPORT_STYLE_MAC
-#else
-#define Q_GUI_EXPORT_STYLE_MAC Q_GUI_EXPORT
-#endif
-
-class QPushButton;
-class QStyleOptionButton;
-class QMacStylePrivate;
-class Q_GUI_EXPORT_STYLE_MAC QMacStyle : public QWindowsStyle
-{
- Q_OBJECT
-public:
- QMacStyle();
- virtual ~QMacStyle();
-
- void polish(QWidget *w);
- void unpolish(QWidget *w);
-
- void polish(QApplication*);
- void unpolish(QApplication*);
-
- void polish(QPalette &pal);
-
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
- void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const;
- SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *w = 0) const;
- QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *w = 0) const;
-
- int pixelMetric(PixelMetric pm, const QStyleOption *opt = 0, const QWidget *widget = 0) const;
-
- QPalette standardPalette() const;
-
- virtual int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
- QStyleHintReturn *shret = 0) const;
-
- enum FocusRectPolicy { FocusEnabled, FocusDisabled, FocusDefault };
- static void setFocusRectPolicy(QWidget *w, FocusRectPolicy policy);
- static FocusRectPolicy focusRectPolicy(const QWidget *w);
-
- enum WidgetSizePolicy { SizeSmall, SizeLarge, SizeMini, SizeDefault
-#ifdef QT3_SUPPORT
- , SizeNone = SizeDefault
-#endif
- };
- static void setWidgetSizePolicy(const QWidget *w, WidgetSizePolicy policy);
- static WidgetSizePolicy widgetSizePolicy(const QWidget *w);
-
- QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *opt,
- const QWidget *widget = 0) const;
-
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const;
-
- virtual void drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal,
- bool enabled, const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const;
-
- bool event(QEvent *e);
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
- int layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
-
-private:
- Q_DISABLE_COPY(QMacStyle)
-
- QMacStylePrivate *d;
-
- friend bool qt_mac_buttonIsRenderedFlat(const QPushButton *pushButton, const QStyleOptionButton *option);
-};
-
-#endif // Q_WS_MAC
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMACSTYLE_H
diff --git a/src/gui/styles/qmacstyle_mac.mm b/src/gui/styles/qmacstyle_mac.mm
deleted file mode 100644
index 2d21628488..0000000000
--- a/src/gui/styles/qmacstyle_mac.mm
+++ /dev/null
@@ -1,6042 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*
- Note: The qdoc comments for QMacStyle are contained in
- .../doc/src/qstyles.qdoc.
-*/
-
-#include "qmacstyle_mac.h"
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-#define QMAC_QAQUASTYLE_SIZE_CONSTRAIN
-//#define DEBUG_SIZE_CONSTRAINT
-
-#include <private/qapplication_p.h>
-#include <private/qcombobox_p.h>
-#include <private/qmacstylepixmaps_mac_p.h>
-#include <private/qpaintengine_mac_p.h>
-#include <private/qpainter_p.h>
-#include <private/qprintengine_mac_p.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcheckbox.h>
-#include <qcombobox.h>
-#include <qdialogbuttonbox.h>
-#include <qdockwidget.h>
-#include <qevent.h>
-#include <qfocusframe.h>
-#include <qformlayout.h>
-#include <qgroupbox.h>
-#include <qhash.h>
-#include <qheaderview.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qlistview.h>
-#include <qmainwindow.h>
-#include <qmap.h>
-#include <qmenubar.h>
-#include <qpaintdevice.h>
-#include <qpainter.h>
-#include <qpixmapcache.h>
-#include <qpointer.h>
-#include <qprogressbar.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qrubberband.h>
-#include <qsizegrip.h>
-#include <qspinbox.h>
-#include <qsplitter.h>
-#include <qstyleoption.h>
-#include <qtextedit.h>
-#include <qtextstream.h>
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qtreeview.h>
-#include <qtableview.h>
-#include <qwizard.h>
-#include <qdebug.h>
-#include <qlibrary.h>
-#include <qdatetimeedit.h>
-#include <qmath.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qgraphicsview.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include "qmacstyle_mac_p.h"
-#include <private/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// The following constants are used for adjusting the size
-// of push buttons so that they are drawn inside their bounds.
-const int QMacStylePrivate::PushButtonLeftOffset = 6;
-const int QMacStylePrivate::PushButtonTopOffset = 4;
-const int QMacStylePrivate::PushButtonRightOffset = 12;
-const int QMacStylePrivate::PushButtonBottomOffset = 12;
-const int QMacStylePrivate::MiniButtonH = 26;
-const int QMacStylePrivate::SmallButtonH = 30;
-const int QMacStylePrivate::BevelButtonW = 50;
-const int QMacStylePrivate::BevelButtonH = 22;
-const int QMacStylePrivate::PushButtonContentPadding = 6;
-
-// These colors specify the titlebar gradient colors on
-// Leopard. Ideally we should get them from the system.
-static const QColor titlebarGradientActiveBegin(220, 220, 220);
-static const QColor titlebarGradientActiveEnd(151, 151, 151);
-static const QColor titlebarSeparatorLineActive(111, 111, 111);
-static const QColor titlebarGradientInactiveBegin(241, 241, 241);
-static const QColor titlebarGradientInactiveEnd(207, 207, 207);
-static const QColor titlebarSeparatorLineInactive(131, 131, 131);
-
-// Gradient colors used for the dock widget title bar and
-// non-unifed tool bar bacground.
-static const QColor mainWindowGradientBegin(240, 240, 240);
-static const QColor mainWindowGradientEnd(200, 200, 200);
-
-static const int DisclosureOffset = 4;
-
-// Resolve these at run-time, since the functions was moved in Leopard.
-typedef HIRect * (*PtrHIShapeGetBounds)(HIShapeRef, HIRect *);
-static PtrHIShapeGetBounds ptrHIShapeGetBounds = 0;
-
-static int closeButtonSize = 12;
-
-extern QRegion qt_mac_convert_mac_region(RgnHandle); //qregion_mac.cpp
-
-static bool isVerticalTabs(const QTabBar::Shape shape) {
- return (shape == QTabBar::RoundedEast
- || shape == QTabBar::TriangularEast
- || shape == QTabBar::RoundedWest
- || shape == QTabBar::TriangularWest);
-}
-
-void drawTabCloseButton(QPainter *p, bool hover, bool active, bool selected)
-{
- // draw background circle
- p->setRenderHints(QPainter::Antialiasing);
- QRect rect(0, 0, closeButtonSize, closeButtonSize);
- QColor background;
- if (hover) {
- background = QColor(124, 124, 124);
- } else {
- if (active) {
- if (selected)
- background = QColor(104, 104, 104);
- else
- background = QColor(83, 83, 83);
- } else {
- if (selected)
- background = QColor(144, 144, 144);
- else
- background = QColor(114, 114, 114);
- }
- }
- p->setPen(Qt::transparent);
- p->setBrush(background);
- p->drawEllipse(rect);
-
- // draw cross
- int min = 3;
- int max = 9;
- QPen crossPen;
- crossPen.setColor(QColor(194, 194, 194));
- crossPen.setWidthF(1.3);
- crossPen.setCapStyle(Qt::FlatCap);
- p->setPen(crossPen);
- p->drawLine(min, min, max, max);
- p->drawLine(min, max, max, min);
-}
-
-QRect rotateTabPainter(QPainter *p, QTabBar::Shape shape, QRect tabRect)
-{
- if (isVerticalTabs(shape)) {
- int newX, newY, newRot;
- if (shape == QTabBar::RoundedEast
- || shape == QTabBar::TriangularEast) {
- newX = tabRect.width();
- newY = tabRect.y();
- newRot = 90;
- } else {
- newX = 0;
- newY = tabRect.y() + tabRect.height();
- newRot = -90;
- }
- tabRect.setRect(0, 0, tabRect.height(), tabRect.width());
- QMatrix m;
- m.translate(newX, newY);
- m.rotate(newRot);
- p->setMatrix(m, true);
- }
- return tabRect;
-}
-
-void drawTabShape(QPainter *p, const QStyleOptionTabV3 *tabOpt)
-{
- QRect r = tabOpt->rect;
- p->translate(tabOpt->rect.x(), tabOpt->rect.y());
- r.moveLeft(0);
- r.moveTop(0);
- QRect tabRect = rotateTabPainter(p, tabOpt->shape, r);
-
- int width = tabRect.width();
- int height = 20;
- bool active = (tabOpt->state & QStyle::State_Active);
- bool selected = (tabOpt->state & QStyle::State_Selected);
-
- if (selected) {
- QRect rect(1, 0, width - 2, height);
-
- // fill body
- if (active) {
- int d = (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) ? 16 : 0;
- p->fillRect(rect, QColor(151 + d, 151 + d, 151 + d));
- } else {
- int d = (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) ? 9 : 0;
- QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
- gradient.setColorAt(0, QColor(207 + d, 207 + d, 207 + d));
- gradient.setColorAt(0.5, QColor(206 + d, 206 + d, 206 + d));
- gradient.setColorAt(1, QColor(201 + d, 201 + d, 201 + d));
- p->fillRect(rect, gradient);
- }
-
- // draw border
- QColor borderSides;
- QColor borderBottom;
- if (active) {
- borderSides = QColor(88, 88, 88);
- borderBottom = QColor(88, 88, 88);
- } else {
- borderSides = QColor(121, 121, 121);
- borderBottom = QColor(116, 116, 116);
- }
-
- p->setPen(borderSides);
-
- int bottom = height;
- // left line
- p->drawLine(0, 1, 0, bottom-2);
- // right line
- p->drawLine(width-1, 1, width-1, bottom-2);
-
- // bottom line
- if (active) {
- p->setPen(QColor(168, 168, 168));
- p->drawLine(3, bottom-1, width-3, bottom-1);
- }
- p->setPen(borderBottom);
- p->drawLine(2, bottom, width-2, bottom);
-
- int w = 3;
- QRectF rectangleLeft(1, height - w, w, w);
- QRectF rectangleRight(width - 2, height - 1, w, w);
- int startAngle = 180 * 16;
- int spanAngle = 90 * 16;
- p->setRenderHint(QPainter::Antialiasing);
- p->drawArc(rectangleLeft, startAngle, spanAngle);
- p->drawArc(rectangleRight, startAngle, -spanAngle);
- } else {
- // when the mouse is over non selected tabs they get a new color
- bool hover = (tabOpt->state & QStyle::State_MouseOver);
- if (hover) {
- QRect rect(1, 2, width - 1, height - 1);
- p->fillRect(rect, QColor(110, 110, 110));
- }
-
- // seperator lines between tabs
- bool west = (tabOpt->shape == QTabBar::RoundedWest || tabOpt->shape == QTabBar::TriangularWest);
- bool drawOnRight = !west;
- if ((!drawOnRight && tabOpt->selectedPosition != QStyleOptionTab::NextIsSelected)
- || (drawOnRight && tabOpt->selectedPosition != QStyleOptionTab::NextIsSelected)) {
- QColor borderColor;
- QColor borderHighlightColor;
- if (active) {
- borderColor = QColor(64, 64, 64);
- borderHighlightColor = QColor(140, 140, 140);
- } else {
- borderColor = QColor(135, 135, 135);
- borderHighlightColor = QColor(178, 178, 178);
- }
-
- int x = drawOnRight ? width : 0;
-
- // tab seperator line
- p->setPen(borderColor);
- p->drawLine(x, 2, x, height + 1);
-
- // tab seperator highlight
- p->setPen(borderHighlightColor);
- p->drawLine(x-1, 2, x-1, height + 1);
- p->drawLine(x+1, 2, x+1, height + 1);
- }
- }
-}
-
-void drawTabBase(QPainter *p, const QStyleOptionTabBarBaseV2 *tbb, const QWidget *w)
-{
- QRect r = tbb->rect;
- if (isVerticalTabs(tbb->shape)) {
- r.setWidth(w->width());
- } else {
- r.setHeight(w->height());
- }
- QRect tabRect = rotateTabPainter(p, tbb->shape, r);
- int width = tabRect.width();
- int height = tabRect.height();
- bool active = (tbb->state & QStyle::State_Active);
-
- // top border lines
- QColor borderHighlightTop;
- QColor borderTop;
- if (active) {
- borderTop = QColor(64, 64, 64);
- borderHighlightTop = QColor(174, 174, 174);
- } else {
- borderTop = QColor(135, 135, 135);
- borderHighlightTop = QColor(207, 207, 207);
- }
- p->setPen(borderHighlightTop);
- p->drawLine(tabRect.x(), 0, width, 0);
- p->setPen(borderTop);
- p->drawLine(tabRect.x(), 1, width, 1);
-
- // center block
- QRect centralRect(tabRect.x(), 2, width, height - 2);
- if (active) {
- QColor mainColor = QColor(120, 120, 120);
- p->fillRect(centralRect, mainColor);
- } else {
- QLinearGradient gradient(centralRect.topLeft(), centralRect.bottomLeft());
- gradient.setColorAt(0, QColor(165, 165, 165));
- gradient.setColorAt(0.5, QColor(164, 164, 164));
- gradient.setColorAt(1, QColor(158, 158, 158));
- p->fillRect(centralRect, gradient);
- }
-
- // bottom border lines
- QColor borderHighlightBottom;
- QColor borderBottom;
- if (active) {
- borderHighlightBottom = QColor(153, 153, 153);
- borderBottom = QColor(64, 64, 64);
- } else {
- borderHighlightBottom = QColor(177, 177, 177);
- borderBottom = QColor(127, 127, 127);
- }
- p->setPen(borderHighlightBottom);
- p->drawLine(tabRect.x(), height - 2, width, height - 2);
- p->setPen(borderBottom);
- p->drawLine(tabRect.x(), height - 1, width, height - 1);
-}
-
-static int getControlSize(const QStyleOption *option, const QWidget *widget)
-{
- if (option) {
- if (option->state & (QStyle::State_Small | QStyle::State_Mini))
- return (option->state & QStyle::State_Mini) ? QAquaSizeMini : QAquaSizeSmall;
- } else if (widget) {
- switch (QMacStyle::widgetSizePolicy(widget)) {
- case QMacStyle::SizeSmall:
- return QAquaSizeSmall;
- case QMacStyle::SizeMini:
- return QAquaSizeMini;
- default:
- break;
- }
- }
- return QAquaSizeLarge;
-}
-
-
-static inline bool isTreeView(const QWidget *widget)
-{
- return (widget && widget->parentWidget() &&
- (qobject_cast<const QTreeView *>(widget->parentWidget())
-#ifdef QT3_SUPPORT
- || widget->parentWidget()->inherits("Q3ListView")
-#endif
- ));
-}
-
-QString qt_mac_removeMnemonics(const QString &original)
-{
- QString returnText(original.size(), 0);
- int finalDest = 0;
- int currPos = 0;
- int l = original.length();
- while (l) {
- if (original.at(currPos) == QLatin1Char('&')
- && (l == 1 || original.at(currPos + 1) != QLatin1Char('&'))) {
- ++currPos;
- --l;
- if (l == 0)
- break;
- }
- returnText[finalDest] = original.at(currPos);
- ++currPos;
- ++finalDest;
- --l;
- }
- returnText.truncate(finalDest);
- return returnText;
-}
-
-static inline ThemeTabDirection getTabDirection(QTabBar::Shape shape)
-{
- ThemeTabDirection ttd;
- switch (shape) {
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- ttd = kThemeTabSouth;
- break;
- default: // Added to remove the warning, since all values are taken care of, really!
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- ttd = kThemeTabNorth;
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- ttd = kThemeTabWest;
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- ttd = kThemeTabEast;
- break;
- }
- return ttd;
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "moc_qmacstyle_mac.cpp"
-#include "moc_qmacstyle_mac_p.cpp"
-QT_END_INCLUDE_NAMESPACE
-
-/*****************************************************************************
- External functions
- *****************************************************************************/
-extern CGContextRef qt_mac_cg_context(const QPaintDevice *); //qpaintdevice_mac.cpp
-extern QRegion qt_mac_convert_mac_region(HIShapeRef); //qregion_mac.cpp
-void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-extern QPaintDevice *qt_mac_safe_pdev; //qapplication_mac.cpp
-
-/*****************************************************************************
- QMacCGStyle globals
- *****************************************************************************/
-const int qt_mac_hitheme_version = 0; //the HITheme version we speak
-const int macItemFrame = 2; // menu item frame width
-const int macItemHMargin = 3; // menu item hor text margin
-const int macItemVMargin = 2; // menu item ver text margin
-const int macRightBorder = 12; // right border on mac
-const ThemeWindowType QtWinType = kThemeDocumentWindow; // Window type we use for QTitleBar.
-QPixmap *qt_mac_backgroundPattern = 0; // stores the standard widget background.
-
-/*****************************************************************************
- QMacCGStyle utility functions
- *****************************************************************************/
-static inline int qt_mac_hitheme_tab_version()
-{
- return 1;
-}
-
-static inline HIRect qt_hirectForQRect(const QRect &convertRect, const QRect &rect = QRect())
-{
- return CGRectMake(convertRect.x() + rect.x(), convertRect.y() + rect.y(),
- convertRect.width() - rect.width(), convertRect.height() - rect.height());
-}
-
-static inline const QRect qt_qrectForHIRect(const HIRect &hirect)
-{
- return QRect(QPoint(int(hirect.origin.x), int(hirect.origin.y)),
- QSize(int(hirect.size.width), int(hirect.size.height)));
-}
-
-inline bool qt_mac_is_metal(const QWidget *w)
-{
- for (; w; w = w->parentWidget()) {
- if (w->testAttribute(Qt::WA_MacBrushedMetal))
- return true;
- if (w->isWindow() && w->testAttribute(Qt::WA_WState_Created)) { // If not created will fall through to the opaque check and be fine anyway.
- return macWindowIsTextured(qt_mac_window_for(w));
- }
- if (w->d_func()->isOpaque)
- break;
- }
- return false;
-}
-
-static int qt_mac_aqua_get_metric(ThemeMetric met)
-{
- SInt32 ret;
- GetThemeMetric(met, &ret);
- return ret;
-}
-
-static QSize qt_aqua_get_known_size(QStyle::ContentsType ct, const QWidget *widg, QSize szHint,
- QAquaWidgetSize sz)
-{
- QSize ret(-1, -1);
- if (sz != QAquaSizeSmall && sz != QAquaSizeLarge && sz != QAquaSizeMini) {
- qDebug("Not sure how to return this...");
- return ret;
- }
- if ((widg && widg->testAttribute(Qt::WA_SetFont)) || !QApplication::desktopSettingsAware()) {
- // If you're using a custom font and it's bigger than the default font,
- // then no constraints for you. If you are smaller, we can try to help you out
- QFont font = qt_app_fonts_hash()->value(widg->metaObject()->className(), QFont());
- if (widg->font().pointSize() > font.pointSize())
- return ret;
- }
-
- if (ct == QStyle::CT_CustomBase && widg) {
- if (qobject_cast<const QPushButton *>(widg))
- ct = QStyle::CT_PushButton;
- else if (qobject_cast<const QRadioButton *>(widg))
- ct = QStyle::CT_RadioButton;
- else if (qobject_cast<const QCheckBox *>(widg))
- ct = QStyle::CT_CheckBox;
- else if (qobject_cast<const QComboBox *>(widg))
- ct = QStyle::CT_ComboBox;
- else if (qobject_cast<const QToolButton *>(widg))
- ct = QStyle::CT_ToolButton;
- else if (qobject_cast<const QSlider *>(widg))
- ct = QStyle::CT_Slider;
- else if (qobject_cast<const QProgressBar *>(widg))
- ct = QStyle::CT_ProgressBar;
- else if (qobject_cast<const QLineEdit *>(widg))
- ct = QStyle::CT_LineEdit;
- else if (qobject_cast<const QHeaderView *>(widg)
-#ifdef QT3_SUPPORT
- || widg->inherits("Q3Header")
-#endif
- )
- ct = QStyle::CT_HeaderSection;
- else if (qobject_cast<const QMenuBar *>(widg)
-#ifdef QT3_SUPPORT
- || widg->inherits("Q3MenuBar")
-#endif
- )
- ct = QStyle::CT_MenuBar;
- else if (qobject_cast<const QSizeGrip *>(widg))
- ct = QStyle::CT_SizeGrip;
- else
- return ret;
- }
-
- switch (ct) {
- case QStyle::CT_PushButton: {
- const QPushButton *psh = qobject_cast<const QPushButton *>(widg);
- // If this comparison is false, then the widget was not a push button.
- // This is bad and there's very little we can do since we were requested to find a
- // sensible size for a widget that pretends to be a QPushButton but is not.
- if(psh) {
- QString buttonText = qt_mac_removeMnemonics(psh->text());
- if (buttonText.contains(QLatin1Char('\n')))
- ret = QSize(-1, -1);
- else if (sz == QAquaSizeLarge)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPushButtonHeight));
- else if (sz == QAquaSizeSmall)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallPushButtonHeight));
- else if (sz == QAquaSizeMini)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniPushButtonHeight));
-
- if (!psh->icon().isNull()){
- // If the button got an icon, and the icon is larger than the
- // button, we can't decide on a default size
- ret.setWidth(-1);
- if (ret.height() < psh->iconSize().height())
- ret.setHeight(-1);
- }
- else if (buttonText == QLatin1String("OK") || buttonText == QLatin1String("Cancel")){
- // Aqua Style guidelines restrict the size of OK and Cancel buttons to 68 pixels.
- // However, this doesn't work for German, therefore only do it for English,
- // I suppose it would be better to do some sort of lookups for languages
- // that like to have really long words.
- ret.setWidth(77 - 8);
- }
- } else {
- // The only sensible thing to do is to return whatever the style suggests...
- if (sz == QAquaSizeLarge)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPushButtonHeight));
- else if (sz == QAquaSizeSmall)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallPushButtonHeight));
- else if (sz == QAquaSizeMini)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniPushButtonHeight));
- else
- // Since there's no default size we return the large size...
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPushButtonHeight));
- }
-#if 0 //Not sure we are applying the rules correctly for RadioButtons/CheckBoxes --Sam
- } else if (ct == QStyle::CT_RadioButton) {
- QRadioButton *rdo = static_cast<QRadioButton *>(widg);
- // Exception for case where multiline radio button text requires no size constrainment
- if (rdo->text().find('\n') != -1)
- return ret;
- if (sz == QAquaSizeLarge)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricRadioButtonHeight));
- else if (sz == QAquaSizeSmall)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallRadioButtonHeight));
- else if (sz == QAquaSizeMini)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniRadioButtonHeight));
- } else if (ct == QStyle::CT_CheckBox) {
- if (sz == QAquaSizeLarge)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricCheckBoxHeight));
- else if (sz == QAquaSizeSmall)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallCheckBoxHeight));
- else if (sz == QAquaSizeMini)
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniCheckBoxHeight));
-#endif
- break;
- }
- case QStyle::CT_SizeGrip:
- if (sz == QAquaSizeLarge || sz == QAquaSizeSmall) {
- HIRect r;
- HIPoint p = { 0, 0 };
- HIThemeGrowBoxDrawInfo gbi;
- gbi.version = 0;
- gbi.state = kThemeStateActive;
- gbi.kind = kHIThemeGrowBoxKindNormal;
- gbi.direction = QApplication::isRightToLeft() ? kThemeGrowLeft | kThemeGrowDown
- : kThemeGrowRight | kThemeGrowDown;
- gbi.size = sz == QAquaSizeSmall ? kHIThemeGrowBoxSizeSmall : kHIThemeGrowBoxSizeNormal;
- if (HIThemeGetGrowBoxBounds(&p, &gbi, &r) == noErr)
- ret = QSize(r.size.width, r.size.height);
- }
- break;
- case QStyle::CT_ComboBox:
- switch (sz) {
- case QAquaSizeLarge:
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPopupButtonHeight));
- break;
- case QAquaSizeSmall:
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallPopupButtonHeight));
- break;
- case QAquaSizeMini:
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniPopupButtonHeight));
- break;
- default:
- break;
- }
- break;
- case QStyle::CT_ToolButton:
- if (sz == QAquaSizeSmall) {
- int width = 0, height = 0;
- if (szHint == QSize(-1, -1)) { //just 'guess'..
- const QToolButton *bt = qobject_cast<const QToolButton *>(widg);
- // If this conversion fails then the widget was not what it claimed to be.
- if(bt) {
- if (!bt->icon().isNull()) {
- QSize iconSize = bt->iconSize();
- QSize pmSize = bt->icon().actualSize(QSize(32, 32), QIcon::Normal);
- width = qMax(width, qMax(iconSize.width(), pmSize.width()));
- height = qMax(height, qMax(iconSize.height(), pmSize.height()));
- }
- if (!bt->text().isNull() && bt->toolButtonStyle() != Qt::ToolButtonIconOnly) {
- int text_width = bt->fontMetrics().width(bt->text()),
- text_height = bt->fontMetrics().height();
- if (bt->toolButtonStyle() == Qt::ToolButtonTextUnderIcon) {
- width = qMax(width, text_width);
- height += text_height;
- } else {
- width += text_width;
- width = qMax(height, text_height);
- }
- }
- } else {
- // Let's return the size hint...
- width = szHint.width();
- height = szHint.height();
- }
- } else {
- width = szHint.width();
- height = szHint.height();
- }
- width = qMax(20, width + 5); //border
- height = qMax(20, height + 5); //border
- ret = QSize(width, height);
- }
- break;
- case QStyle::CT_Slider: {
- int w = -1;
- const QSlider *sld = qobject_cast<const QSlider *>(widg);
- // If this conversion fails then the widget was not what it claimed to be.
- if(sld) {
- if (sz == QAquaSizeLarge) {
- if (sld->orientation() == Qt::Horizontal) {
- w = qt_mac_aqua_get_metric(kThemeMetricHSliderHeight);
- if (sld->tickPosition() != QSlider::NoTicks)
- w += qt_mac_aqua_get_metric(kThemeMetricHSliderTickHeight);
- } else {
- w = qt_mac_aqua_get_metric(kThemeMetricVSliderWidth);
- if (sld->tickPosition() != QSlider::NoTicks)
- w += qt_mac_aqua_get_metric(kThemeMetricVSliderTickWidth);
- }
- } else if (sz == QAquaSizeSmall) {
- if (sld->orientation() == Qt::Horizontal) {
- w = qt_mac_aqua_get_metric(kThemeMetricSmallHSliderHeight);
- if (sld->tickPosition() != QSlider::NoTicks)
- w += qt_mac_aqua_get_metric(kThemeMetricSmallHSliderTickHeight);
- } else {
- w = qt_mac_aqua_get_metric(kThemeMetricSmallVSliderWidth);
- if (sld->tickPosition() != QSlider::NoTicks)
- w += qt_mac_aqua_get_metric(kThemeMetricSmallVSliderTickWidth);
- }
- } else if (sz == QAquaSizeMini) {
- if (sld->orientation() == Qt::Horizontal) {
- w = qt_mac_aqua_get_metric(kThemeMetricMiniHSliderHeight);
- if (sld->tickPosition() != QSlider::NoTicks)
- w += qt_mac_aqua_get_metric(kThemeMetricMiniHSliderTickHeight);
- } else {
- w = qt_mac_aqua_get_metric(kThemeMetricMiniVSliderWidth);
- if (sld->tickPosition() != QSlider::NoTicks)
- w += qt_mac_aqua_get_metric(kThemeMetricMiniVSliderTickWidth);
- }
- }
- } else {
- // This is tricky, we were requested to find a size for a slider which is not
- // a slider. We don't know if this is vertical or horizontal or if we need to
- // have tick marks or not.
- // For this case we will return an horizontal slider without tick marks.
- w = qt_mac_aqua_get_metric(kThemeMetricHSliderHeight);
- w += qt_mac_aqua_get_metric(kThemeMetricHSliderTickHeight);
- }
- if (sld->orientation() == Qt::Horizontal)
- ret.setHeight(w);
- else
- ret.setWidth(w);
- break;
- }
- case QStyle::CT_ProgressBar: {
- int finalValue = -1;
- Qt::Orientation orient = Qt::Horizontal;
- if (const QProgressBar *pb = qobject_cast<const QProgressBar *>(widg))
- orient = pb->orientation();
-
- if (sz == QAquaSizeLarge)
- finalValue = qt_mac_aqua_get_metric(kThemeMetricLargeProgressBarThickness)
- + qt_mac_aqua_get_metric(kThemeMetricProgressBarShadowOutset);
- else
- finalValue = qt_mac_aqua_get_metric(kThemeMetricNormalProgressBarThickness)
- + qt_mac_aqua_get_metric(kThemeMetricSmallProgressBarShadowOutset);
- if (orient == Qt::Horizontal)
- ret.setHeight(finalValue);
- else
- ret.setWidth(finalValue);
- break;
- }
- case QStyle::CT_LineEdit:
- if (!widg || !qobject_cast<QComboBox *>(widg->parentWidget())) {
- //should I take into account the font dimentions of the lineedit? -Sam
- if (sz == QAquaSizeLarge)
- ret = QSize(-1, 22);
- else
- ret = QSize(-1, 19);
- }
- break;
- case QStyle::CT_HeaderSection:
- if (isTreeView(widg))
- ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricListHeaderHeight));
- break;
- case QStyle::CT_MenuBar:
- if (sz == QAquaSizeLarge) {
-#ifndef QT_MAC_USE_COCOA
- SInt16 size;
- if (!GetThemeMenuBarHeight(&size))
- ret = QSize(-1, size);
-#else
- ret = QSize(-1, [[NSApp mainMenu] menuBarHeight]);
- // In the qt_mac_set_native_menubar(false) case,
- // we come it here with a zero-height main menu,
- // preventing the in-window menu from displaying.
- // Use 22 pixels for the height, by observation.
- if (ret.height() <= 0)
- ret.setHeight(22);
-#endif
- }
- break;
- default:
- break;
- }
- return ret;
-}
-
-
-#if defined(QMAC_QAQUASTYLE_SIZE_CONSTRAIN) || defined(DEBUG_SIZE_CONSTRAINT)
-static QAquaWidgetSize qt_aqua_guess_size(const QWidget *widg, QSize large, QSize small, QSize mini)
-{
- if (large == QSize(-1, -1)) {
- if (small != QSize(-1, -1))
- return QAquaSizeSmall;
- if (mini != QSize(-1, -1))
- return QAquaSizeMini;
- return QAquaSizeUnknown;
- } else if (small == QSize(-1, -1)) {
- if (mini != QSize(-1, -1))
- return QAquaSizeMini;
- return QAquaSizeLarge;
- } else if (mini == QSize(-1, -1)) {
- return QAquaSizeLarge;
- }
-
-#ifndef QT_NO_MAINWINDOW
- if (qobject_cast<QDockWidget *>(widg->window()) || !qgetenv("QWIDGET_ALL_SMALL").isNull()) {
- //if (small.width() != -1 || small.height() != -1)
- return QAquaSizeSmall;
- } else if (!qgetenv("QWIDGET_ALL_MINI").isNull()) {
- return QAquaSizeMini;
- }
-#endif
-
-#if 0
- /* Figure out which size we're closer to, I just hacked this in, I haven't
- tested it as it would probably look pretty strange to have some widgets
- big and some widgets small in the same window?? -Sam */
- int large_delta=0;
- if (large.width() != -1) {
- int delta = large.width() - widg->width();
- large_delta += delta * delta;
- }
- if (large.height() != -1) {
- int delta = large.height() - widg->height();
- large_delta += delta * delta;
- }
- int small_delta=0;
- if (small.width() != -1) {
- int delta = small.width() - widg->width();
- small_delta += delta * delta;
- }
- if (small.height() != -1) {
- int delta = small.height() - widg->height();
- small_delta += delta * delta;
- }
- int mini_delta=0;
- if (mini.width() != -1) {
- int delta = mini.width() - widg->width();
- mini_delta += delta * delta;
- }
- if (mini.height() != -1) {
- int delta = mini.height() - widg->height();
- mini_delta += delta * delta;
- }
- if (mini_delta < small_delta && mini_delta < large_delta)
- return QAquaSizeMini;
- else if (small_delta < large_delta)
- return QAquaSizeSmall;
-#endif
- return QAquaSizeLarge;
-}
-#endif
-
-QAquaWidgetSize QMacStylePrivate::aquaSizeConstrain(const QStyleOption *option, const QWidget *widg,
- QStyle::ContentsType ct, QSize szHint, QSize *insz) const
-{
-#if defined(QMAC_QAQUASTYLE_SIZE_CONSTRAIN) || defined(DEBUG_SIZE_CONSTRAINT)
- if (option) {
- if (option->state & QStyle::State_Small)
- return QAquaSizeSmall;
- if (option->state & QStyle::State_Mini)
- return QAquaSizeMini;
- }
-
- if (!widg) {
- if (insz)
- *insz = QSize();
- if (!qgetenv("QWIDGET_ALL_SMALL").isNull())
- return QAquaSizeSmall;
- if (!qgetenv("QWIDGET_ALL_MINI").isNull())
- return QAquaSizeMini;
- return QAquaSizeUnknown;
- }
- QSize large = qt_aqua_get_known_size(ct, widg, szHint, QAquaSizeLarge),
- small = qt_aqua_get_known_size(ct, widg, szHint, QAquaSizeSmall),
- mini = qt_aqua_get_known_size(ct, widg, szHint, QAquaSizeMini);
- bool guess_size = false;
- QAquaWidgetSize ret = QAquaSizeUnknown;
- QMacStyle::WidgetSizePolicy wsp = q->widgetSizePolicy(widg);
- if (wsp == QMacStyle::SizeDefault)
- guess_size = true;
- else if (wsp == QMacStyle::SizeMini)
- ret = QAquaSizeMini;
- else if (wsp == QMacStyle::SizeSmall)
- ret = QAquaSizeSmall;
- else if (wsp == QMacStyle::SizeLarge)
- ret = QAquaSizeLarge;
- if (guess_size)
- ret = qt_aqua_guess_size(widg, large, small, mini);
-
- QSize *sz = 0;
- if (ret == QAquaSizeSmall)
- sz = &small;
- else if (ret == QAquaSizeLarge)
- sz = &large;
- else if (ret == QAquaSizeMini)
- sz = &mini;
- if (insz)
- *insz = sz ? *sz : QSize(-1, -1);
-#ifdef DEBUG_SIZE_CONSTRAINT
- if (sz) {
- const char *size_desc = "Unknown";
- if (sz == &small)
- size_desc = "Small";
- else if (sz == &large)
- size_desc = "Large";
- else if (sz == &mini)
- size_desc = "Mini";
- qDebug("%s - %s: %s taken (%d, %d) [%d, %d]",
- widg ? widg->objectName().toLatin1().constData() : "*Unknown*",
- widg ? widg->metaObject()->className() : "*Unknown*", size_desc, widg->width(), widg->height(),
- sz->width(), sz->height());
- }
-#endif
- return ret;
-#else
- if (insz)
- *insz = QSize();
- Q_UNUSED(widg);
- Q_UNUSED(ct);
- Q_UNUSED(szHint);
- return QAquaSizeUnknown;
-#endif
-}
-
-/**
- Returns the free space awailable for contents inside the
- button (and not the size of the contents itself)
-*/
-HIRect QMacStylePrivate::pushButtonContentBounds(const QStyleOptionButton *btn,
- const HIThemeButtonDrawInfo *bdi) const
-{
- HIRect outerBounds = qt_hirectForQRect(btn->rect);
- // Adjust the bounds to correct for
- // carbon not calculating the content bounds fully correct
- if (bdi->kind == kThemePushButton || bdi->kind == kThemePushButtonSmall){
- outerBounds.origin.y += QMacStylePrivate::PushButtonTopOffset;
- outerBounds.size.height -= QMacStylePrivate::PushButtonBottomOffset;
- } else if (bdi->kind == kThemePushButtonMini) {
- outerBounds.origin.y += QMacStylePrivate::PushButtonTopOffset;
- }
-
- HIRect contentBounds;
- HIThemeGetButtonContentBounds(&outerBounds, bdi, &contentBounds);
- return contentBounds;
-}
-
-/**
- Calculates the size of the button contents.
- This includes both the text and the icon.
-*/
-QSize QMacStylePrivate::pushButtonSizeFromContents(const QStyleOptionButton *btn) const
-{
- QSize csz(0, 0);
- QSize iconSize = btn->icon.isNull() ? QSize(0, 0)
- : (btn->iconSize + QSize(QMacStylePrivate::PushButtonContentPadding, 0));
- QRect textRect = btn->text.isEmpty() ? QRect(0, 0, 1, 1)
- : btn->fontMetrics.boundingRect(QRect(), Qt::AlignCenter, btn->text);
- csz.setWidth(iconSize.width() + textRect.width()
- + ((btn->features & QStyleOptionButton::HasMenu)
- ? q->proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, btn, 0) : 0));
- csz.setHeight(qMax(iconSize.height(), textRect.height()));
- return csz;
-}
-
-/**
- Checks if the actual contents of btn fits inside the free content bounds of
- 'buttonKindToCheck'. Meant as a helper function for 'initHIThemePushButton'
- for determining which button kind to use for drawing.
-*/
-bool QMacStylePrivate::contentFitsInPushButton(const QStyleOptionButton *btn,
- HIThemeButtonDrawInfo *bdi,
- ThemeButtonKind buttonKindToCheck) const
-{
- ThemeButtonKind tmp = bdi->kind;
- bdi->kind = buttonKindToCheck;
- QSize contentSize = pushButtonSizeFromContents(btn);
- QRect freeContentRect = qt_qrectForHIRect(pushButtonContentBounds(btn, bdi));
- bdi->kind = tmp;
- return freeContentRect.contains(QRect(freeContentRect.x(), freeContentRect.y(),
- contentSize.width(), contentSize.height()));
-}
-
-/**
- Creates a HIThemeButtonDrawInfo structure that specifies the correct button
- kind and other details to use for drawing the given push button. Which
- button kind depends on the size of the button, the size of the contents,
- explicit user style settings, etc.
-*/
-void QMacStylePrivate::initHIThemePushButton(const QStyleOptionButton *btn,
- const QWidget *widget,
- const ThemeDrawState tds,
- HIThemeButtonDrawInfo *bdi) const
-{
- bool drawColorless = btn->palette.currentColorGroup() == QPalette::Active;
- ThemeDrawState tdsModified = tds;
- if (btn->state & QStyle::State_On)
- tdsModified = kThemeStatePressed;
- bdi->version = qt_mac_hitheme_version;
- bdi->state = tdsModified;
- bdi->value = kThemeButtonOff;
-
- if (drawColorless && tdsModified == kThemeStateInactive)
- bdi->state = kThemeStateActive;
- if (btn->state & QStyle::State_HasFocus)
- bdi->adornment = kThemeAdornmentFocus;
- else
- bdi->adornment = kThemeAdornmentNone;
-
-
- if (btn->features & (QStyleOptionButton::Flat)) {
- bdi->kind = kThemeBevelButton;
- } else {
- switch (aquaSizeConstrain(btn, widget)) {
- case QAquaSizeSmall:
- bdi->kind = kThemePushButtonSmall;
- break;
- case QAquaSizeMini:
- bdi->kind = kThemePushButtonMini;
- break;
- case QAquaSizeLarge:
- // ... We should honor if the user is explicit about using the
- // large button. But right now Qt will specify the large button
- // as default rather than QAquaSizeUnknown.
- // So we treat it like QAquaSizeUnknown
- // to get the dynamic choosing of button kind.
- case QAquaSizeUnknown:
- // Choose the button kind that closest match the button rect, but at the
- // same time displays the button contents without clipping.
- bdi->kind = kThemeBevelButton;
- if (btn->rect.width() >= QMacStylePrivate::BevelButtonW && btn->rect.height() >= QMacStylePrivate::BevelButtonH){
- if (widget && widget->testAttribute(Qt::WA_MacVariableSize)) {
- if (btn->rect.height() <= QMacStylePrivate::MiniButtonH){
- if (contentFitsInPushButton(btn, bdi, kThemePushButtonMini))
- bdi->kind = kThemePushButtonMini;
- } else if (btn->rect.height() <= QMacStylePrivate::SmallButtonH){
- if (contentFitsInPushButton(btn, bdi, kThemePushButtonSmall))
- bdi->kind = kThemePushButtonSmall;
- } else if (contentFitsInPushButton(btn, bdi, kThemePushButton)) {
- bdi->kind = kThemePushButton;
- }
- } else {
- bdi->kind = kThemePushButton;
- }
- }
- }
- }
-}
-
-bool qt_mac_buttonIsRenderedFlat(const QPushButton *pushButton, const QStyleOptionButton *option)
-{
- QMacStyle *macStyle = qobject_cast<QMacStyle *>(pushButton->style());
- if (!macStyle)
- return false;
- HIThemeButtonDrawInfo bdi;
- macStyle->d->initHIThemePushButton(option, pushButton, kThemeStateActive, &bdi);
- return bdi.kind == kThemeBevelButton;
-}
-
-/**
- Creates a HIThemeButtonDrawInfo structure that specifies the correct button
- kind and other details to use for drawing the given combobox. Which button
- kind depends on the size of the combo, wether or not it is editable,
- explicit user style settings, etc.
-*/
-void QMacStylePrivate::initComboboxBdi(const QStyleOptionComboBox *combo, HIThemeButtonDrawInfo *bdi,
- const QWidget *widget, const ThemeDrawState &tds)
-{
- bdi->version = qt_mac_hitheme_version;
- bdi->adornment = kThemeAdornmentArrowLeftArrow;
- bdi->value = kThemeButtonOff;
- if (combo->state & QStyle::State_HasFocus)
- bdi->adornment = kThemeAdornmentFocus;
- bool drawColorless = combo->palette.currentColorGroup() == QPalette::Active && tds == kThemeStateInactive;
- if (combo->activeSubControls & QStyle::SC_ComboBoxArrow)
- bdi->state = kThemeStatePressed;
- else if (drawColorless)
- bdi->state = kThemeStateActive;
- else
- bdi->state = tds;
-
- QAquaWidgetSize aSize = aquaSizeConstrain(combo, widget);
- switch (aSize) {
- case QAquaSizeMini:
- bdi->kind = combo->editable ? ThemeButtonKind(kThemeComboBoxMini)
- : ThemeButtonKind(kThemePopupButtonMini);
- break;
- case QAquaSizeSmall:
- bdi->kind = combo->editable ? ThemeButtonKind(kThemeComboBoxSmall)
- : ThemeButtonKind(kThemePopupButtonSmall);
- break;
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- // Unless the user explicitly specified large buttons, determine the
- // kind by looking at the combox size.
- // ... specifying small and mini-buttons it not a current feature of
- // Qt (e.g. QWidget::getAttribute(WA_ButtonSize)). But when it is, add
- // an extra check here before using the mini and small buttons.
- int h = combo->rect.size().height();
- if (combo->editable){
- if (h < 21)
- bdi->kind = kThemeComboBoxMini;
- else if (h < 26)
- bdi->kind = kThemeComboBoxSmall;
- else
- bdi->kind = kThemeComboBox;
- } else {
- // Even if we specify that we want the kThemePopupButton, Carbon
- // will use the kThemePopupButtonSmall if the size matches. So we
- // do the same size check explicit to have the size of the inner
- // text field be correct. Therefore, do this even if the user specifies
- // the use of LargeButtons explicit.
- if (h < 21)
- bdi->kind = kThemePopupButtonMini;
- else if (h < 26)
- bdi->kind = kThemePopupButtonSmall;
- else
- bdi->kind = kThemePopupButton;
- }
- break;
- }
-}
-
-/**
- Carbon draws comboboxes (and other views) outside the rect given as argument. Use this function to obtain
- the corresponding inner rect for drawing the same combobox so that it stays inside the given outerBounds.
-*/
-HIRect QMacStylePrivate::comboboxInnerBounds(const HIRect &outerBounds, int buttonKind)
-{
- HIRect innerBounds = outerBounds;
- // Carbon draw parts of the view outside the rect.
- // So make the rect a bit smaller to compensate
- // (I wish HIThemeGetButtonBackgroundBounds worked)
- switch (buttonKind){
- case kThemePopupButton:
- innerBounds.origin.x += 2;
- innerBounds.origin.y += 3;
- innerBounds.size.width -= 5;
- innerBounds.size.height -= 6;
- break;
- case kThemePopupButtonSmall:
- innerBounds.origin.x += 3;
- innerBounds.origin.y += 3;
- innerBounds.size.width -= 6;
- innerBounds.size.height -= 7;
- break;
- case kThemePopupButtonMini:
- innerBounds.origin.x += 2;
- innerBounds.origin.y += 2;
- innerBounds.size.width -= 5;
- innerBounds.size.height -= 6;
- break;
- case kThemeComboBox:
- innerBounds.origin.x += 3;
- innerBounds.origin.y += 3;
- innerBounds.size.width -= 6;
- innerBounds.size.height -= 6;
- break;
- case kThemeComboBoxSmall:
- innerBounds.origin.x += 3;
- innerBounds.origin.y += 3;
- innerBounds.size.width -= 7;
- innerBounds.size.height -= 8;
- break;
- case kThemeComboBoxMini:
- innerBounds.origin.x += 3;
- innerBounds.origin.y += 3;
- innerBounds.size.width -= 4;
- innerBounds.size.height -= 8;
- break;
- default:
- break;
- }
- return innerBounds;
-}
-
-/**
- Inside a combobox Qt places a line edit widget. The size of this widget should depend on the kind
- of combobox we choose to draw. This function calculates and returns this size.
-*/
-QRect QMacStylePrivate::comboboxEditBounds(const QRect &outerBounds, const HIThemeButtonDrawInfo &bdi)
-{
- QRect ret = outerBounds;
- switch (bdi.kind){
- case kThemeComboBox:
- ret.adjust(5, 8, -21, -4);
- break;
- case kThemeComboBoxSmall:
- ret.adjust(4, 5, -18, 0);
- ret.setHeight(16);
- break;
- case kThemeComboBoxMini:
- ret.adjust(4, 5, -16, 0);
- ret.setHeight(13);
- break;
- case kThemePopupButton:
- ret.adjust(10, 3, -23, -3);
- break;
- case kThemePopupButtonSmall:
- ret.adjust(9, 3, -20, -3);
- break;
- case kThemePopupButtonMini:
- ret.adjust(8, 3, -19, 0);
- ret.setHeight(13);
- break;
- }
- return ret;
-}
-
-/**
- Carbon comboboxes don't scale (sight). If the size of the combo suggest a scaled version,
- create it manually by drawing a small Carbon combo onto a pixmap (use pixmap cache), chop
- it up, and copy it back onto the widget. Othervise, draw the combobox supplied by Carbon directly.
-*/
-void QMacStylePrivate::drawCombobox(const HIRect &outerBounds, const HIThemeButtonDrawInfo &bdi, QPainter *p)
-{
- if (!(bdi.kind == kThemeComboBox && outerBounds.size.height > 28)){
- // We have an unscaled combobox, or popup-button; use Carbon directly.
- HIRect innerBounds = QMacStylePrivate::comboboxInnerBounds(outerBounds, bdi.kind);
- HIThemeDrawButton(&innerBounds, &bdi, QMacCGContext(p), kHIThemeOrientationNormal, 0);
- } else {
- QPixmap buffer;
- QString key = QString(QLatin1String("$qt_cbox%1-%2")).arg(int(bdi.state)).arg(int(bdi.adornment));
- if (!QPixmapCache::find(key, buffer)) {
- HIRect innerBoundsSmallCombo = {{3, 3}, {29, 25}};
- buffer = QPixmap(35, 28);
- buffer.fill(Qt::transparent);
- QPainter buffPainter(&buffer);
- HIThemeDrawButton(&innerBoundsSmallCombo, &bdi, QMacCGContext(&buffPainter), kHIThemeOrientationNormal, 0);
- buffPainter.end();
- QPixmapCache::insert(key, buffer);
- }
-
- const int bwidth = 20;
- const int fwidth = 10;
- const int fheight = 10;
- int w = qRound(outerBounds.size.width);
- int h = qRound(outerBounds.size.height);
- int bstart = w - bwidth;
- int blower = fheight + 1;
- int flower = h - fheight;
- int sheight = flower - fheight;
- int center = qRound(outerBounds.size.height + outerBounds.origin.y) / 2;
-
- // Draw upper and lower gap
- p->drawPixmap(fwidth, 0, bstart - fwidth, fheight, buffer, fwidth, 0, 1, fheight);
- p->drawPixmap(fwidth, flower, bstart - fwidth, fheight, buffer, fwidth, buffer.height() - fheight, 1, fheight);
- // Draw left and right gap. Right gap is drawn top and bottom separatly
- p->drawPixmap(0, fheight, fwidth, sheight, buffer, 0, fheight, fwidth, 1);
- p->drawPixmap(bstart, fheight, bwidth, center - fheight, buffer, buffer.width() - bwidth, fheight - 1, bwidth, 1);
- p->drawPixmap(bstart, center, bwidth, sheight / 2, buffer, buffer.width() - bwidth, fheight + 6, bwidth, 1);
- // Draw arrow
- p->drawPixmap(bstart, center - 4, bwidth - 3, 6, buffer, buffer.width() - bwidth, fheight, bwidth - 3, 6);
- // Draw corners
- p->drawPixmap(0, 0, fwidth, fheight, buffer, 0, 0, fwidth, fheight);
- p->drawPixmap(bstart, 0, bwidth, fheight, buffer, buffer.width() - bwidth, 0, bwidth, fheight);
- p->drawPixmap(0, flower, fwidth, fheight, buffer, 0, buffer.height() - fheight, fwidth, fheight);
- p->drawPixmap(bstart, h - blower, bwidth, blower, buffer, buffer.width() - bwidth, buffer.height() - blower, bwidth, blower);
- }
-}
-
-/**
- Carbon tableheaders don't scale (sight). So create it manually by drawing a small Carbon header
- onto a pixmap (use pixmap cache), chop it up, and copy it back onto the widget.
-*/
-void QMacStylePrivate::drawTableHeader(const HIRect &outerBounds,
- bool drawTopBorder, bool drawLeftBorder, const HIThemeButtonDrawInfo &bdi, QPainter *p)
-{
- static SInt32 headerHeight = 0;
- static OSStatus err = GetThemeMetric(kThemeMetricListHeaderHeight, &headerHeight);
- Q_UNUSED(err);
-
- QPixmap buffer;
- QString key = QString(QLatin1String("$qt_tableh%1-%2-%3")).arg(int(bdi.state)).arg(int(bdi.adornment)).arg(int(bdi.value));
- if (!QPixmapCache::find(key, buffer)) {
- HIRect headerNormalRect = {{0., 0.}, {16., CGFloat(headerHeight)}};
- buffer = QPixmap(headerNormalRect.size.width, headerNormalRect.size.height);
- buffer.fill(Qt::transparent);
- QPainter buffPainter(&buffer);
- HIThemeDrawButton(&headerNormalRect, &bdi, QMacCGContext(&buffPainter), kHIThemeOrientationNormal, 0);
- buffPainter.end();
- QPixmapCache::insert(key, buffer);
- }
- const int buttonw = qRound(outerBounds.size.width);
- const int buttonh = qRound(outerBounds.size.height);
- const int framew = 1;
- const int frameh_n = 4;
- const int frameh_s = 3;
- const int transh = buffer.height() - frameh_n - frameh_s;
- int center = buttonh - frameh_s - int(transh / 2.0f) + 1; // Align bottom;
-
- int skipTopBorder = 0;
- if (!drawTopBorder)
- skipTopBorder = 1;
-
- p->translate(outerBounds.origin.x, outerBounds.origin.y);
-
- p->drawPixmap(QRect(QRect(0, -skipTopBorder, buttonw - framew , frameh_n)), buffer, QRect(framew, 0, 1, frameh_n));
- p->drawPixmap(QRect(0, buttonh - frameh_s, buttonw - framew, frameh_s), buffer, QRect(framew, buffer.height() - frameh_s, 1, frameh_s));
- // Draw upper and lower center blocks
- p->drawPixmap(QRect(0, frameh_n - skipTopBorder, buttonw - framew, center - frameh_n + skipTopBorder), buffer, QRect(framew, frameh_n, 1, 1));
- p->drawPixmap(QRect(0, center, buttonw - framew, buttonh - center - frameh_s), buffer, QRect(framew, buffer.height() - frameh_s, 1, 1));
- // Draw right center block borders
- p->drawPixmap(QRect(buttonw - framew, frameh_n - skipTopBorder, framew, center - frameh_n), buffer, QRect(buffer.width() - framew, frameh_n, framew, 1));
- p->drawPixmap(QRect(buttonw - framew, center, framew, buttonh - center - 1), buffer, QRect(buffer.width() - framew, buffer.height() - frameh_s, framew, 1));
- // Draw right corners
- p->drawPixmap(QRect(buttonw - framew, -skipTopBorder, framew, frameh_n), buffer, QRect(buffer.width() - framew, 0, framew, frameh_n));
- p->drawPixmap(QRect(buttonw - framew, buttonh - frameh_s, framew, frameh_s), buffer, QRect(buffer.width() - framew, buffer.height() - frameh_s, framew, frameh_s));
- // Draw center transition block
- p->drawPixmap(QRect(0, center - qRound(transh / 2.0f), buttonw - framew, buffer.height() - frameh_n - frameh_s), buffer, QRect(framew, frameh_n + 1, 1, transh));
- // Draw right center transition block border
- p->drawPixmap(QRect(buttonw - framew, center - qRound(transh / 2.0f), framew, buffer.height() - frameh_n - frameh_s), buffer, QRect(buffer.width() - framew, frameh_n + 1, framew, transh));
- if (drawLeftBorder){
- // Draw left center block borders
- p->drawPixmap(QRect(0, frameh_n - skipTopBorder, framew, center - frameh_n + skipTopBorder), buffer, QRect(0, frameh_n, framew, 1));
- p->drawPixmap(QRect(0, center, framew, buttonh - center - 1), buffer, QRect(0, buffer.height() - frameh_s, framew, 1));
- // Draw left corners
- p->drawPixmap(QRect(0, -skipTopBorder, framew, frameh_n), buffer, QRect(0, 0, framew, frameh_n));
- p->drawPixmap(QRect(0, buttonh - frameh_s, framew, frameh_s), buffer, QRect(0, buffer.height() - frameh_s, framew, frameh_s));
- // Draw left center transition block border
- p->drawPixmap(QRect(0, center - qRound(transh / 2.0f), framew, buffer.height() - frameh_n - frameh_s), buffer, QRect(0, frameh_n + 1, framew, transh));
- }
-
- p->translate(-outerBounds.origin.x, -outerBounds.origin.y);
-}
-
-/*
- Returns cutoff sizes for scroll bars.
- thumbIndicatorCutoff is the smallest size where the thumb indicator is drawn.
- scrollButtonsCutoff is the smallest size where the up/down buttons is drawn.
-*/
-enum ScrollBarCutoffType { thumbIndicatorCutoff = 0, scrollButtonsCutoff = 1 };
-static int scrollButtonsCutoffSize(ScrollBarCutoffType cutoffType, QMacStyle::WidgetSizePolicy widgetSize)
-{
- // Mini scroll bars do not exist as of version 10.4.
- if (widgetSize == QMacStyle::SizeMini)
- return 0;
-
- const int sizeIndex = (widgetSize == QMacStyle::SizeSmall) ? 1 : 0;
- static const int sizeTable[2][2] = { { 61, 56 }, { 49, 44 } };
- return sizeTable[sizeIndex][cutoffType];
-}
-
-void QMacStylePrivate::getSliderInfo(QStyle::ComplexControl cc, const QStyleOptionSlider *slider,
- HIThemeTrackDrawInfo *tdi, const QWidget *needToRemoveMe)
-{
- memset(tdi, 0, sizeof(HIThemeTrackDrawInfo)); // We don't get it all for some reason or another...
- tdi->version = qt_mac_hitheme_version;
- tdi->reserved = 0;
- tdi->filler1 = 0;
- bool isScrollbar = (cc == QStyle::CC_ScrollBar);
- switch (aquaSizeConstrain(0, needToRemoveMe)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- if (isScrollbar)
- tdi->kind = kThemeMediumScrollBar;
- else
- tdi->kind = kThemeMediumSlider;
- break;
- case QAquaSizeMini:
- if (isScrollbar)
- tdi->kind = kThemeSmallScrollBar; // should be kThemeMiniScrollBar, but not implemented
- else
- tdi->kind = kThemeMiniSlider;
- break;
- case QAquaSizeSmall:
- if (isScrollbar)
- tdi->kind = kThemeSmallScrollBar;
- else
- tdi->kind = kThemeSmallSlider;
- break;
- }
- tdi->bounds = qt_hirectForQRect(slider->rect);
- tdi->min = slider->minimum;
- tdi->max = slider->maximum;
- tdi->value = slider->sliderPosition;
- tdi->attributes = kThemeTrackShowThumb;
- if (slider->upsideDown)
- tdi->attributes |= kThemeTrackRightToLeft;
- if (slider->orientation == Qt::Horizontal) {
- tdi->attributes |= kThemeTrackHorizontal;
- if (isScrollbar && slider->direction == Qt::RightToLeft) {
- if (!slider->upsideDown)
- tdi->attributes |= kThemeTrackRightToLeft;
- else
- tdi->attributes &= ~kThemeTrackRightToLeft;
- }
- }
-
- // Tiger broke reverse scroll bars so put them back and "fake it"
- if (isScrollbar && (tdi->attributes & kThemeTrackRightToLeft)) {
- tdi->attributes &= ~kThemeTrackRightToLeft;
- tdi->value = tdi->max - slider->sliderPosition;
- }
-
- tdi->enableState = (slider->state & QStyle::State_Enabled) ? kThemeTrackActive
- : kThemeTrackDisabled;
- if (!(slider->state & QStyle::State_Active))
- tdi->enableState = kThemeTrackInactive;
- if (!isScrollbar) {
- if (slider->state & QStyle::QStyle::State_HasFocus)
- tdi->attributes |= kThemeTrackHasFocus;
- if (slider->tickPosition == QSlider::NoTicks || slider->tickPosition == QSlider::TicksBothSides)
- tdi->trackInfo.slider.thumbDir = kThemeThumbPlain;
- else if (slider->tickPosition == QSlider::TicksAbove)
- tdi->trackInfo.slider.thumbDir = kThemeThumbUpward;
- else
- tdi->trackInfo.slider.thumbDir = kThemeThumbDownward;
- } else {
- tdi->trackInfo.scrollbar.viewsize = slider->pageStep;
- }
-}
-#endif
-
-QMacStylePrivate::QMacStylePrivate(QMacStyle *style)
- : timerID(-1), progressFrame(0), q(style), mouseDown(false)
-{
- defaultButtonStart = CFAbsoluteTimeGetCurrent();
- memset(&buttonState, 0, sizeof(ButtonState));
-
- if (ptrHIShapeGetBounds == 0) {
- QLibrary library(QLatin1String("/System/Library/Frameworks/Carbon.framework/Carbon"));
- library.setLoadHints(QLibrary::ExportExternalSymbolsHint);
- ptrHIShapeGetBounds = reinterpret_cast<PtrHIShapeGetBounds>(library.resolve("HIShapeGetBounds"));
- }
-
-}
-
-bool QMacStylePrivate::animatable(QMacStylePrivate::Animates as, const QWidget *w) const
-{
- if (!w)
- return false;
-
- if (as == AquaPushButton) {
- QPushButton *pb = const_cast<QPushButton *>(static_cast<const QPushButton *>(w));
- if (w->window()->isActiveWindow() && pb && !mouseDown) {
- if (static_cast<const QPushButton *>(w) != defaultButton) {
- // Changed on its own, update the value.
- const_cast<QMacStylePrivate *>(this)->stopAnimate(as, defaultButton);
- const_cast<QMacStylePrivate *>(this)->startAnimate(as, pb);
- }
- return true;
- }
- } else if (as == AquaProgressBar) {
- if (progressBars.contains((const_cast<QWidget *>(w))))
- return true;
- }
- return false;
-}
-
-void QMacStylePrivate::stopAnimate(QMacStylePrivate::Animates as, QWidget *w)
-{
- if (as == AquaPushButton && defaultButton) {
- QPushButton *tmp = defaultButton;
- defaultButton = 0;
- tmp->update();
- } else if (as == AquaProgressBar) {
- progressBars.removeAll(w);
- }
-}
-
-void QMacStylePrivate::startAnimate(QMacStylePrivate::Animates as, QWidget *w)
-{
- if (as == AquaPushButton)
- defaultButton = static_cast<QPushButton *>(w);
- else if (as == AquaProgressBar)
- progressBars.append(w);
- startAnimationTimer();
-}
-
-void QMacStylePrivate::startAnimationTimer()
-{
- if ((defaultButton || !progressBars.isEmpty()) && timerID <= -1)
- timerID = startTimer(animateSpeed(AquaListViewItemOpen));
-}
-
-bool QMacStylePrivate::addWidget(QWidget *w)
-{
- //already knew of it
- if (static_cast<QPushButton*>(w) == defaultButton
- || progressBars.contains(static_cast<QProgressBar*>(w)))
- return false;
-
- if (QPushButton *btn = qobject_cast<QPushButton *>(w)) {
- btn->installEventFilter(this);
- if (btn->isDefault() || (btn->autoDefault() && btn->hasFocus()))
- startAnimate(AquaPushButton, btn);
- return true;
- } else {
- bool isProgressBar = (qobject_cast<QProgressBar *>(w)
-#ifdef QT3_SUPPORT
- || w->inherits("Q3ProgressBar")
-#endif
- );
- if (isProgressBar) {
- w->installEventFilter(this);
- startAnimate(AquaProgressBar, w);
- return true;
- }
- }
- if (w->isWindow()) {
- w->installEventFilter(this);
- return true;
- }
- return false;
-}
-
-void QMacStylePrivate::removeWidget(QWidget *w)
-{
- QPushButton *btn = qobject_cast<QPushButton *>(w);
- if (btn && btn == defaultButton) {
- stopAnimate(AquaPushButton, btn);
- } else if (qobject_cast<QProgressBar *>(w)
-#ifdef QT3_SUPPORT
- || w->inherits("Q3ProgressBar")
-#endif
- ) {
- stopAnimate(AquaProgressBar, w);
- }
-}
-
-ThemeDrawState QMacStylePrivate::getDrawState(QStyle::State flags)
-{
- ThemeDrawState tds = kThemeStateActive;
- if (flags & QStyle::State_Sunken) {
- tds = kThemeStatePressed;
- } else if (flags & QStyle::State_Active) {
- if (!(flags & QStyle::State_Enabled))
- tds = kThemeStateUnavailable;
- } else {
- if (flags & QStyle::State_Enabled)
- tds = kThemeStateInactive;
- else
- tds = kThemeStateUnavailableInactive;
- }
- return tds;
-}
-
-void QMacStylePrivate::timerEvent(QTimerEvent *)
-{
- int animated = 0;
- if (defaultButton && defaultButton->isEnabled() && defaultButton->window()->isActiveWindow()
- && defaultButton->isVisibleTo(0) && (defaultButton->isDefault()
- || (defaultButton->autoDefault() && defaultButton->hasFocus()))
- && doAnimate(AquaPushButton)) {
- ++animated;
- defaultButton->update();
- }
- if (!progressBars.isEmpty()) {
- int i = 0;
- while (i < progressBars.size()) {
- QWidget *maybeProgress = progressBars.at(i);
- if (!maybeProgress) {
- progressBars.removeAt(i);
- } else {
- if (QProgressBar *pb = qobject_cast<QProgressBar *>(maybeProgress)) {
- if (pb->maximum() == 0 || (pb->value() > 0 && pb->value() < pb->maximum())) {
- if (doAnimate(AquaProgressBar))
- pb->update();
- }
- }
-#ifdef QT3_SUPPORT
- else {
- // Watch me now...
- QVariant progress = maybeProgress->property("progress");
- QVariant totalSteps = maybeProgress->property("totalSteps");
- if (progress.isValid() && totalSteps.isValid()) {
- int intProgress = progress.toInt();
- int intTotalSteps = totalSteps.toInt();
- if (intTotalSteps == 0 || intProgress > 0 && intProgress < intTotalSteps) {
- if (doAnimate(AquaProgressBar))
- maybeProgress->update();
- }
- }
- }
-#endif
- ++i;
- }
- }
- if (i > 0) {
- ++progressFrame;
- animated += i;
- }
- }
- if (animated <= 0) {
- killTimer(timerID);
- timerID = -1;
- }
-}
-
-bool QMacStylePrivate::eventFilter(QObject *o, QEvent *e)
-{
- //animate
- if (QProgressBar *pb = qobject_cast<QProgressBar *>(o)) {
- switch (e->type()) {
- default:
- break;
- case QEvent::Show:
- if (!progressBars.contains(pb))
- startAnimate(AquaProgressBar, pb);
- break;
- case QEvent::Destroy:
- case QEvent::Hide:
- progressBars.removeAll(pb);
- }
- } else if (QPushButton *btn = qobject_cast<QPushButton *>(o)) {
- switch (e->type()) {
- default:
- break;
- case QEvent::FocusIn:
- if (btn->autoDefault())
- startAnimate(AquaPushButton, btn);
- break;
- case QEvent::Destroy:
- case QEvent::Hide:
- if (btn == defaultButton)
- stopAnimate(AquaPushButton, btn);
- break;
- case QEvent::MouseButtonPress:
- // It is very confusing to keep the button pulsing, so just stop the animation.
- if (static_cast<QMouseEvent *>(e)->button() == Qt::LeftButton)
- mouseDown = true;
- stopAnimate(AquaPushButton, btn);
- break;
- case QEvent::MouseButtonRelease:
- if (static_cast<QMouseEvent *>(e)->button() == Qt::LeftButton)
- mouseDown = false;
- // fall through
- case QEvent::FocusOut:
- case QEvent::Show:
- case QEvent::WindowActivate: {
- QList<QPushButton *> list = btn->window()->findChildren<QPushButton *>();
- for (int i = 0; i < list.size(); ++i) {
- QPushButton *pBtn = list.at(i);
- if ((e->type() == QEvent::FocusOut
- && (pBtn->isDefault() || (pBtn->autoDefault() && pBtn->hasFocus()))
- && pBtn != btn)
- || ((e->type() == QEvent::Show || e->type() == QEvent::MouseButtonRelease
- || e->type() == QEvent::WindowActivate)
- && pBtn->isDefault())) {
- if (pBtn->window()->isActiveWindow()) {
- startAnimate(AquaPushButton, pBtn);
- }
- break;
- }
- }
- break; }
- }
- }
- return false;
-}
-
-bool QMacStylePrivate::doAnimate(QMacStylePrivate::Animates as)
-{
- if (as == AquaPushButton) {
- } else if (as == AquaProgressBar) {
- // something for later...
- } else if (as == AquaListViewItemOpen) {
- // To be revived later...
- }
- return true;
-}
-
-void QMacStylePrivate::drawColorlessButton(const HIRect &macRect, HIThemeButtonDrawInfo *bdi,
- QPainter *p, const QStyleOption *opt) const
-{
- int xoff = 0,
- yoff = 0,
- extraWidth = 0,
- extraHeight = 0,
- finalyoff = 0;
-
- const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt);
- int width = int(macRect.size.width) + extraWidth;
- int height = int(macRect.size.height) + extraHeight;
-
- if (width <= 0 || height <= 0)
- return; // nothing to draw
-
- QString key = QLatin1String("$qt_mac_style_ctb_") + QString::number(bdi->kind) + QLatin1Char('_')
- + QString::number(bdi->value) + QLatin1Char('_') + QString::number(width)
- + QLatin1Char('_') + QString::number(height);
- QPixmap pm;
- if (!QPixmapCache::find(key, pm)) {
- QPixmap activePixmap(width, height);
- activePixmap.fill(Qt::transparent);
- {
- if (combo){
- // Carbon combos don't scale. Therefore we draw it
- // ourselves, if a scaled version is needed.
- QPainter tmpPainter(&activePixmap);
- QMacStylePrivate::drawCombobox(macRect, *bdi, &tmpPainter);
- }
- else {
- QMacCGContext cg(&activePixmap);
- HIRect newRect = CGRectMake(xoff, yoff, macRect.size.width, macRect.size.height);
- HIThemeDrawButton(&newRect, bdi, cg, kHIThemeOrientationNormal, 0);
- }
- }
-
- if (!combo && bdi->value == kThemeButtonOff) {
- pm = activePixmap;
- } else if (combo) {
- QImage image = activePixmap.toImage();
-
- for (int y = 0; y < height; ++y) {
- QRgb *scanLine = reinterpret_cast<QRgb *>(image.scanLine(y));
-
- for (int x = 0; x < width; ++x) {
- QRgb &pixel = scanLine[x];
-
- int darkest = qRed(pixel);
- int mid = qGreen(pixel);
- int lightest = qBlue(pixel);
-
- if (darkest > mid)
- qSwap(darkest, mid);
- if (mid > lightest)
- qSwap(mid, lightest);
- if (darkest > mid)
- qSwap(darkest, mid);
-
- int gray = (mid + 2 * lightest) / 3;
- pixel = qRgba(gray, gray, gray, qAlpha(pixel));
- }
- }
- pm = QPixmap::fromImage(image);
- } else {
- QImage activeImage = activePixmap.toImage();
- QImage colorlessImage;
- {
- QPixmap colorlessPixmap(width, height);
- colorlessPixmap.fill(Qt::transparent);
-
- QMacCGContext cg(&colorlessPixmap);
- HIRect newRect = CGRectMake(xoff, yoff, macRect.size.width, macRect.size.height);
- int oldValue = bdi->value;
- bdi->value = kThemeButtonOff;
- HIThemeDrawButton(&newRect, bdi, cg, kHIThemeOrientationNormal, 0);
- bdi->value = oldValue;
- colorlessImage = colorlessPixmap.toImage();
- }
-
- for (int y = 0; y < height; ++y) {
- QRgb *colorlessScanLine = reinterpret_cast<QRgb *>(colorlessImage.scanLine(y));
- const QRgb *activeScanLine = reinterpret_cast<const QRgb *>(activeImage.scanLine(y));
-
- for (int x = 0; x < width; ++x) {
- QRgb &colorlessPixel = colorlessScanLine[x];
- QRgb activePixel = activeScanLine[x];
-
- if (activePixel != colorlessPixel) {
- int max = qMax(qMax(qRed(activePixel), qGreen(activePixel)),
- qBlue(activePixel));
- QRgb newPixel = qRgba(max, max, max, qAlpha(activePixel));
- if (qGray(newPixel) < qGray(colorlessPixel)
- || qAlpha(newPixel) > qAlpha(colorlessPixel))
- colorlessPixel = newPixel;
- }
- }
- }
- pm = QPixmap::fromImage(colorlessImage);
- }
- QPixmapCache::insert(key, pm);
- }
- p->drawPixmap(int(macRect.origin.x), int(macRect.origin.y) + finalyoff, width, height, pm);
-}
-
-QMacStyle::QMacStyle()
- : QWindowsStyle()
-{
- d = new QMacStylePrivate(this);
-}
-
-QMacStyle::~QMacStyle()
-{
- delete qt_mac_backgroundPattern;
- qt_mac_backgroundPattern = 0;
- delete d;
-}
-
-/*! \internal
- Generates the standard widget background pattern.
-*/
-QPixmap QMacStylePrivate::generateBackgroundPattern() const
-{
- QPixmap px(4, 4);
- QMacCGContext cg(&px);
- HIThemeSetFill(kThemeBrushDialogBackgroundActive, 0, cg, kHIThemeOrientationNormal);
- const CGRect cgRect = CGRectMake(0, 0, px.width(), px.height());
- CGContextFillRect(cg, cgRect);
- return px;
-}
-
-/*! \internal
- Fills the given \a rect with the pattern stored in \a brush. As an optimization,
- HIThemeSetFill us used directly if we are filling with the standard background.
-*/
-void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush)
-{
- QPoint dummy;
- const QPaintDevice *target = painter->device();
- const QPaintDevice *redirected = QPainter::redirected(target, &dummy);
- const bool usePainter = redirected && redirected != target;
-
- if (!usePainter && qt_mac_backgroundPattern
- && qt_mac_backgroundPattern->cacheKey() == brush.texture().cacheKey()) {
-
- painter->setClipRegion(rgn);
-
- QCFType<CGContextRef> cg = qt_mac_cg_context(target);
- CGContextSaveGState(cg);
- HIThemeSetFill(kThemeBrushDialogBackgroundActive, 0, cg, kHIThemeOrientationInverted);
-
- const QVector<QRect> &rects = rgn.rects();
- for (int i = 0; i < rects.size(); ++i) {
- const QRect rect(rects.at(i));
- // Anchor the pattern to the top so it stays put when the window is resized.
- CGContextSetPatternPhase(cg, CGSizeMake(rect.width(), rect.height()));
- CGRect mac_rect = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
- CGContextFillRect(cg, mac_rect);
- }
-
- CGContextRestoreGState(cg);
- } else {
- const QRect rect(rgn.boundingRect());
- painter->setClipRegion(rgn);
- painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
- }
-}
-
-void QMacStyle::polish(QPalette &pal)
-{
- if (!qt_mac_backgroundPattern) {
- if (!qApp)
- return;
- qt_mac_backgroundPattern = new QPixmap(d->generateBackgroundPattern());
- }
-
- QColor pc(Qt::black);
- pc = qcolorForTheme(kThemeBrushDialogBackgroundActive);
- QBrush background(pc, *qt_mac_backgroundPattern);
- pal.setBrush(QPalette::All, QPalette::Window, background);
- pal.setBrush(QPalette::All, QPalette::Button, background);
-
- QCFString theme;
- const OSErr err = CopyThemeIdentifier(&theme);
- if (err == noErr && CFStringCompare(theme, kThemeAppearanceAquaGraphite, 0) == kCFCompareEqualTo) {
- pal.setBrush(QPalette::All, QPalette::AlternateBase, QColor(240, 240, 240));
- } else {
- pal.setBrush(QPalette::All, QPalette::AlternateBase, QColor(237, 243, 254));
- }
-}
-
-void QMacStyle::polish(QApplication *)
-{
-}
-
-void QMacStyle::unpolish(QApplication *)
-{
-}
-
-void QMacStyle::polish(QWidget* w)
-{
- d->addWidget(w);
- if (qt_mac_is_metal(w) && !w->testAttribute(Qt::WA_SetPalette)) {
- // Set a clear brush so that the metal shines through.
- QPalette pal = w->palette();
- QBrush background(Qt::transparent);
- pal.setBrush(QPalette::All, QPalette::Window, background);
- pal.setBrush(QPalette::All, QPalette::Button, background);
- w->setPalette(pal);
- w->setAttribute(Qt::WA_SetPalette, false);
- }
-
- if (qobject_cast<QMenu*>(w) || qobject_cast<QComboBoxPrivateContainer *>(w)) {
- w->setWindowOpacity(QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 ? 0.985 : 0.94);
- if (!w->testAttribute(Qt::WA_SetPalette)) {
- QPixmap px(64, 64);
- px.fill(Qt::white);
- HIThemeMenuDrawInfo mtinfo;
- mtinfo.version = qt_mac_hitheme_version;
- mtinfo.menuType = kThemeMenuTypePopUp;
- HIRect rect = CGRectMake(0, 0, px.width(), px.height());
- HIThemeDrawMenuBackground(&rect, &mtinfo, QCFType<CGContextRef>(qt_mac_cg_context(&px)),
- kHIThemeOrientationNormal);
- QPalette pal = w->palette();
- QBrush background(px);
- pal.setBrush(QPalette::All, QPalette::Window, background);
- pal.setBrush(QPalette::All, QPalette::Button, background);
- w->setPalette(pal);
- w->setAttribute(Qt::WA_SetPalette, false);
- }
- }
-
- if (QTabBar *tb = qobject_cast<QTabBar*>(w)) {
- if (tb->documentMode()) {
- w->setAttribute(Qt::WA_Hover);
- w->setFont(qt_app_fonts_hash()->value("QSmallFont", QFont()));
- QPalette p = w->palette();
- p.setColor(QPalette::WindowText, QColor(17, 17, 17));
- w->setPalette(p);
- }
- }
-
- QWindowsStyle::polish(w);
-
- if (QRubberBand *rubber = qobject_cast<QRubberBand*>(w)) {
- rubber->setWindowOpacity(0.25);
- rubber->setAttribute(Qt::WA_PaintOnScreen, false);
- rubber->setAttribute(Qt::WA_NoSystemBackground, false);
- }
-}
-
-void QMacStyle::unpolish(QWidget* w)
-{
- d->removeWidget(w);
- if ((qobject_cast<QMenu*>(w) || qt_mac_is_metal(w)) && !w->testAttribute(Qt::WA_SetPalette)) {
- QPalette pal = qApp->palette(w);
- w->setPalette(pal);
- w->setAttribute(Qt::WA_SetPalette, false);
- w->setWindowOpacity(1.0);
- }
-
- if (QComboBox *combo = qobject_cast<QComboBox *>(w)) {
- if (!combo->isEditable()) {
- if (QWidget *widget = combo->findChild<QComboBoxPrivateContainer *>())
- widget->setWindowOpacity(1.0);
- }
- }
-
- if (QRubberBand *rubber = ::qobject_cast<QRubberBand*>(w)) {
- rubber->setWindowOpacity(1.0);
- rubber->setAttribute(Qt::WA_PaintOnScreen, true);
- rubber->setAttribute(Qt::WA_NoSystemBackground, true);
- }
-
- if (QFocusFrame *frame = qobject_cast<QFocusFrame *>(w))
- frame->setAttribute(Qt::WA_NoSystemBackground, true);
-
- QWindowsStyle::unpolish(w);
-}
-
-int QMacStyle::pixelMetric(PixelMetric metric, const QStyleOption *opt, const QWidget *widget) const
-{
- int controlSize = getControlSize(opt, widget);
- SInt32 ret = 0;
-
- switch (metric) {
- case PM_TabCloseIndicatorWidth:
- case PM_TabCloseIndicatorHeight:
- ret = closeButtonSize;
- break;
- case PM_ToolBarIconSize:
- ret = proxy()->pixelMetric(PM_LargeIconSize);
- break;
- case PM_FocusFrameVMargin:
- case PM_FocusFrameHMargin:
- GetThemeMetric(kThemeMetricFocusRectOutset, &ret);
- break;
- case PM_DialogButtonsSeparator:
- ret = -5;
- break;
- case PM_DialogButtonsButtonHeight: {
- QSize sz;
- ret = d->aquaSizeConstrain(opt, 0, QStyle::CT_PushButton, QSize(-1, -1), &sz);
- if (sz == QSize(-1, -1))
- ret = 32;
- else
- ret = sz.height();
- break; }
- case PM_CheckListButtonSize: {
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- GetThemeMetric(kThemeMetricCheckBoxWidth, &ret);
- break;
- case QAquaSizeMini:
- GetThemeMetric(kThemeMetricMiniCheckBoxWidth, &ret);
- break;
- case QAquaSizeSmall:
- GetThemeMetric(kThemeMetricSmallCheckBoxWidth, &ret);
- break;
- }
- break; }
- case PM_DialogButtonsButtonWidth: {
- QSize sz;
- ret = d->aquaSizeConstrain(opt, 0, QStyle::CT_PushButton, QSize(-1, -1), &sz);
- if (sz == QSize(-1, -1))
- ret = 70;
- else
- ret = sz.width();
- break; }
-
- case PM_MenuBarHMargin:
- ret = 8;
- break;
-
- case PM_MenuBarVMargin:
- ret = 0;
- break;
-
- case QStyle::PM_MenuDesktopFrameWidth:
- ret = 5;
- break;
-
- case PM_CheckBoxLabelSpacing:
- case PM_RadioButtonLabelSpacing:
- ret = 2;
- break;
- case PM_MenuScrollerHeight:
-#if 0
- SInt16 ash, asw;
- GetThemeMenuItemExtra(kThemeMenuItemScrollUpArrow, &ash, &asw);
- ret = ash;
-#else
- ret = 15; // I hate having magic numbers in here...
-#endif
- break;
- case PM_DefaultFrameWidth:
-#ifndef QT_NO_MAINWINDOW
- if (widget && (widget->isWindow() || !widget->parentWidget()
- || (qobject_cast<const QMainWindow*>(widget->parentWidget())
- && static_cast<QMainWindow *>(widget->parentWidget())->centralWidget() == widget))
- && (qobject_cast<const QAbstractScrollArea *>(widget)
-#ifdef QT3_SUPPORT
- || widget->inherits("QScrollView")
-#endif
- || widget->inherits("QWorkspaceChild")))
- ret = 0;
- else
-#endif
- // The combo box popup has no frame.
- if (qstyleoption_cast<const QStyleOptionComboBox *>(opt) != 0)
- ret = 0;
- // Frame of mac style line edits is two pixels on top and one on the bottom
- else if (qobject_cast<const QLineEdit *>(widget) != 0)
- ret = 2;
- else
- ret = 1;
- break;
- case PM_MaximumDragDistance:
- ret = -1;
- break;
- case PM_ScrollBarSliderMin:
- ret = 24;
- break;
- case PM_SpinBoxFrameWidth:
- GetThemeMetric(kThemeMetricEditTextFrameOutset, &ret);
- switch (d->aquaSizeConstrain(opt, widget)) {
- default:
- ret += 2;
- break;
- case QAquaSizeMini:
- ret += 1;
- break;
- }
- break;
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- ret = 0;
- break;
- case PM_SliderLength:
- ret = 17;
- break;
- case PM_ButtonDefaultIndicator:
- ret = 0;
- break;
- case PM_TitleBarHeight:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- HIThemeWindowDrawInfo wdi;
- wdi.version = qt_mac_hitheme_version;
- wdi.state = kThemeStateActive;
- wdi.windowType = QtWinType;
- if (tb->titleBarState)
- wdi.attributes = kThemeWindowHasFullZoom | kThemeWindowHasCloseBox
- | kThemeWindowHasCollapseBox;
- else if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- wdi.attributes = kThemeWindowHasCloseBox;
- else
- wdi.attributes = 0;
- wdi.titleHeight = tb->rect.height();
- wdi.titleWidth = tb->rect.width();
- QCFType<HIShapeRef> region;
- HIRect hirect = qt_hirectForQRect(tb->rect);
- if (hirect.size.width <= 0)
- hirect.size.width = 100;
- if (hirect.size.height <= 0)
- hirect.size.height = 30;
-
- HIThemeGetWindowShape(&hirect, &wdi, kWindowTitleBarRgn, &region);
- HIRect rect;
- ptrHIShapeGetBounds(region, &rect);
- ret = int(rect.size.height);
- ret += 4;
- }
- break;
- case PM_TabBarTabVSpace:
- ret = 4;
- break;
- case PM_TabBarTabShiftHorizontal:
- case PM_TabBarTabShiftVertical:
- ret = 0;
- break;
- case PM_TabBarBaseHeight:
- ret = 0;
- break;
- case PM_TabBarTabOverlap:
- ret = 0;
- break;
- case PM_TabBarBaseOverlap:
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- ret = 11;
- break;
- case QAquaSizeSmall:
- ret = 8;
- break;
- case QAquaSizeMini:
- ret = 7;
- break;
- }
- break;
- case PM_ScrollBarExtent: {
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- GetThemeMetric(kThemeMetricScrollBarWidth, &ret);
- break;
- case QAquaSizeMini:
- case QAquaSizeSmall:
- GetThemeMetric(kThemeMetricSmallScrollBarWidth, &ret);
- break;
- }
- break; }
- case PM_IndicatorHeight: {
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- GetThemeMetric(kThemeMetricCheckBoxHeight, &ret);
- break;
- case QAquaSizeMini:
- GetThemeMetric(kThemeMetricMiniCheckBoxHeight, &ret);
- break;
- case QAquaSizeSmall:
- GetThemeMetric(kThemeMetricSmallCheckBoxHeight, &ret);
- break;
- }
- break; }
- case PM_IndicatorWidth: {
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- GetThemeMetric(kThemeMetricCheckBoxWidth, &ret);
- break;
- case QAquaSizeMini:
- GetThemeMetric(kThemeMetricMiniCheckBoxWidth, &ret);
- break;
- case QAquaSizeSmall:
- GetThemeMetric(kThemeMetricSmallCheckBoxWidth, &ret);
- break;
- }
- ++ret;
- break; }
- case PM_ExclusiveIndicatorHeight: {
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- GetThemeMetric(kThemeMetricRadioButtonHeight, &ret);
- break;
- case QAquaSizeMini:
- GetThemeMetric(kThemeMetricMiniRadioButtonHeight, &ret);
- break;
- case QAquaSizeSmall:
- GetThemeMetric(kThemeMetricSmallRadioButtonHeight, &ret);
- break;
- }
- break; }
- case PM_ExclusiveIndicatorWidth: {
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- GetThemeMetric(kThemeMetricRadioButtonWidth, &ret);
- break;
- case QAquaSizeMini:
- GetThemeMetric(kThemeMetricMiniRadioButtonWidth, &ret);
- break;
- case QAquaSizeSmall:
- GetThemeMetric(kThemeMetricSmallRadioButtonWidth, &ret);
- break;
- }
- ++ret;
- break; }
- case PM_MenuVMargin:
- ret = 4;
- break;
- case PM_MenuPanelWidth:
- ret = 0;
- break;
- case PM_ToolTipLabelFrameWidth:
- ret = 0;
- break;
- case PM_SizeGripSize: {
- QAquaWidgetSize aSize;
- if (widget && widget->window()->windowType() == Qt::Tool)
- aSize = QAquaSizeSmall;
- else
- aSize = QAquaSizeLarge;
- const QSize size = qt_aqua_get_known_size(CT_SizeGrip, widget, QSize(), aSize);
- ret = size.width();
- break; }
- case PM_MdiSubWindowFrameWidth:
- ret = 1;
- break;
- case PM_DockWidgetFrameWidth:
- ret = 2;
- break;
- case PM_DockWidgetTitleMargin:
- ret = 0;
- break;
- case PM_DockWidgetSeparatorExtent:
- ret = 1;
- break;
- case PM_ToolBarHandleExtent:
- ret = 11;
- break;
- case PM_ToolBarItemMargin:
- ret = 0;
- break;
- case PM_ToolBarItemSpacing:
- ret = 4;
- break;
- case PM_SplitterWidth:
- ret = qMax(7, QApplication::globalStrut().width());
- break;
- case PM_LayoutLeftMargin:
- case PM_LayoutTopMargin:
- case PM_LayoutRightMargin:
- case PM_LayoutBottomMargin:
- {
- bool isWindow = false;
- if (opt) {
- isWindow = (opt->state & State_Window);
- } else if (widget) {
- isWindow = widget->isWindow();
- }
-
- if (isWindow) {
- bool isMetal = widget && widget->testAttribute(Qt::WA_MacBrushedMetal);
- if (isMetal) {
- if (metric == PM_LayoutTopMargin) {
- return_SIZE(9 /* AHIG */, 6 /* guess */, 6 /* guess */);
- } else if (metric == PM_LayoutBottomMargin) {
- return_SIZE(18 /* AHIG */, 15 /* guess */, 13 /* guess */);
- } else {
- return_SIZE(14 /* AHIG */, 11 /* guess */, 9 /* guess */);
- }
- } else {
- /*
- AHIG would have (20, 8, 10) here but that makes
- no sense. It would also have 14 for the top margin
- but this contradicts both Builder and most
- applications.
- */
- return_SIZE(20, 10, 10); // AHIG
- }
- } else {
- // hack to detect QTabWidget
- if (widget && widget->parentWidget()
- && widget->parentWidget()->sizePolicy().controlType() == QSizePolicy::TabWidget) {
- if (metric == PM_LayoutTopMargin) {
- /*
- Builder would have 14 (= 20 - 6) instead of 12,
- but that makes the tab look disproportionate.
- */
- return_SIZE(12, 6, 6); // guess
- } else {
- return_SIZE(20 /* Builder */, 8 /* guess */, 8 /* guess */);
- }
- } else {
- /*
- Child margins are highly inconsistent in AHIG and Builder.
- */
- return_SIZE(12, 8, 6); // guess
- }
- }
- }
- case PM_LayoutHorizontalSpacing:
- case PM_LayoutVerticalSpacing:
- return -1;
- case QStyle::PM_TabBarTabHSpace:
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeLarge:
- case QAquaSizeUnknown:
- ret = QWindowsStyle::pixelMetric(metric, opt, widget);
- break;
- case QAquaSizeSmall:
- ret = 20;
- break;
- case QAquaSizeMini:
- ret = 16;
- break;
- }
- break;
- case PM_MenuHMargin:
- ret = 0;
- break;
- case PM_ToolBarFrameWidth:
- ret = 1;
- if (widget) {
- if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(widget->parent()))
- if (mainWindow->unifiedTitleAndToolBarOnMac())
- ret = 0;
- }
- break;
- default:
- ret = QWindowsStyle::pixelMetric(metric, opt, widget);
- break;
- }
- return ret;
-}
-
-QPalette QMacStyle::standardPalette() const
-{
- QPalette pal = QWindowsStyle::standardPalette();
- pal.setColor(QPalette::Disabled, QPalette::Dark, QColor(191, 191, 191));
- pal.setColor(QPalette::Active, QPalette::Dark, QColor(191, 191, 191));
- pal.setColor(QPalette::Inactive, QPalette::Dark, QColor(191, 191, 191));
- return pal;
-}
-
-int QMacStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
- QStyleHintReturn *hret) const
-{
- SInt32 ret = 0;
- switch (sh) {
- case SH_Menu_SelectionWrap:
- ret = false;
- break;
- case SH_Menu_KeyboardSearch:
- ret = true;
- break;
- case SH_Menu_SpaceActivatesItem:
- ret = true;
- break;
- case SH_Slider_AbsoluteSetButtons:
- ret = Qt::LeftButton|Qt::MidButton;
- break;
- case SH_Slider_PageSetButtons:
- ret = 0;
- break;
- case SH_ScrollBar_ContextMenu:
- ret = false;
- break;
- case SH_TitleBar_AutoRaise:
- ret = true;
- break;
- case SH_Menu_AllowActiveAndDisabled:
- ret = false;
- break;
- case SH_Menu_SubMenuPopupDelay:
- ret = 100;
- break;
- case SH_ScrollBar_LeftClickAbsolutePosition: {
- extern bool qt_scrollbar_jump_to_pos; //qapplication_mac.cpp
- if(QApplication::keyboardModifiers() & Qt::AltModifier)
- ret = !qt_scrollbar_jump_to_pos;
- else
- ret = qt_scrollbar_jump_to_pos;
- break; }
- case SH_TabBar_PreferNoArrows:
- ret = true;
- break;
- case SH_LineEdit_PasswordCharacter:
- ret = kBulletUnicode;
- break;
- /*
- case SH_DialogButtons_DefaultButton:
- ret = QDialogButtons::Reject;
- break;
- */
- case SH_Menu_SloppySubMenus:
- ret = true;
- break;
- case SH_GroupBox_TextLabelVerticalAlignment:
- ret = Qt::AlignTop;
- break;
- case SH_ScrollView_FrameOnlyAroundContents:
- if (w && (w->isWindow() || !w->parentWidget() || w->parentWidget()->isWindow())
- && (w->inherits("QWorkspaceChild")
-#ifdef QT3_SUPPORT
- || w->inherits("QScrollView")
-#endif
- ))
- ret = true;
- else
- ret = QWindowsStyle::styleHint(sh, opt, w, hret);
- break;
- case SH_Menu_FillScreenWithScroll:
- ret = false;
- break;
- case SH_Menu_Scrollable:
- ret = true;
- break;
- case SH_RichText_FullWidthSelection:
- ret = true;
- break;
- case SH_BlinkCursorWhenTextSelected:
- ret = false;
- break;
- case SH_ScrollBar_StopMouseOverSlider:
- ret = true;
- break;
- case SH_Q3ListViewExpand_SelectMouseType:
- ret = QEvent::MouseButtonRelease;
- break;
- case SH_TabBar_SelectMouseType:
- if (const QStyleOptionTabBarBaseV2 *opt2 = qstyleoption_cast<const QStyleOptionTabBarBaseV2 *>(opt)) {
- ret = opt2->documentMode ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease;
- } else {
- ret = QEvent::MouseButtonRelease;
- }
- break;
- case SH_ComboBox_Popup:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt))
- ret = !cmb->editable;
- else
- ret = 0;
- break;
- case SH_Workspace_FillSpaceOnMaximize:
- ret = true;
- break;
- case SH_Widget_ShareActivation:
- ret = true;
- break;
- case SH_Header_ArrowAlignment:
- ret = Qt::AlignRight;
- break;
- case SH_TabBar_Alignment: {
- if (const QTabWidget *tab = qobject_cast<const QTabWidget*>(w)) {
- if (tab->documentMode()) {
- ret = Qt::AlignLeft;
- break;
- }
- }
- if (const QTabBar *tab = qobject_cast<const QTabBar*>(w)) {
- if (tab->documentMode()) {
- ret = Qt::AlignLeft;
- break;
- }
- }
- ret = Qt::AlignCenter;
- } break;
- case SH_UnderlineShortcut:
- ret = false;
- break;
- case SH_ToolTipLabel_Opacity:
- ret = 242; // About 95%
- break;
- case SH_Button_FocusPolicy:
- ret = Qt::TabFocus;
- break;
- case SH_EtchDisabledText:
- ret = false;
- break;
- case SH_FocusFrame_Mask: {
- ret = true;
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
- const uchar fillR = 192, fillG = 191, fillB = 190;
- QImage img;
-
- QSize pixmapSize = opt->rect.size();
- if (pixmapSize.isValid()) {
- QPixmap pix(pixmapSize);
- pix.fill(QColor(fillR, fillG, fillB));
- QPainter pix_paint(&pix);
- proxy()->drawControl(CE_FocusFrame, opt, &pix_paint, w);
- pix_paint.end();
- img = pix.toImage();
- }
-
- const QRgb *sptr = (QRgb*)img.bits(), *srow;
- const int sbpl = img.bytesPerLine();
- const int w = sbpl/4, h = img.height();
-
- QImage img_mask(img.width(), img.height(), QImage::Format_ARGB32);
- QRgb *dptr = (QRgb*)img_mask.bits(), *drow;
- const int dbpl = img_mask.bytesPerLine();
-
- for (int y = 0; y < h; ++y) {
- srow = sptr+((y*sbpl)/4);
- drow = dptr+((y*dbpl)/4);
- for (int x = 0; x < w; ++x) {
- const int diff = (((qRed(*srow)-fillR)*(qRed(*srow)-fillR)) +
- ((qGreen(*srow)-fillG)*((qGreen(*srow)-fillG))) +
- ((qBlue(*srow)-fillB)*((qBlue(*srow)-fillB))));
- (*drow++) = (diff < 100) ? 0xffffffff : 0xff000000;
- ++srow;
- }
- }
- QBitmap qmask = QBitmap::fromImage(img_mask);
- mask->region = QRegion(qmask);
- }
- break; }
- case SH_TitleBar_NoBorder:
- ret = 1;
- break;
- case SH_RubberBand_Mask:
- ret = 0;
- break;
- case SH_ComboBox_LayoutDirection:
- ret = Qt::LeftToRight;
- break;
- case SH_ItemView_EllipsisLocation:
- ret = Qt::AlignHCenter;
- break;
- case SH_ItemView_ShowDecorationSelected:
- ret = true;
- break;
- case SH_TitleBar_ModifyNotification:
- ret = false;
- break;
- case SH_ScrollBar_RollBetweenButtons:
- ret = true;
- break;
- case SH_WindowFrame_Mask:
- ret = 1;
- if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask *>(hret)) {
- mask->region = opt->rect;
- mask->region -= QRect(opt->rect.left(), opt->rect.top(), 5, 1);
- mask->region -= QRect(opt->rect.left(), opt->rect.top() + 1, 3, 1);
- mask->region -= QRect(opt->rect.left(), opt->rect.top() + 2, 2, 1);
- mask->region -= QRect(opt->rect.left(), opt->rect.top() + 3, 1, 2);
-
- mask->region -= QRect(opt->rect.right() - 4, opt->rect.top(), 5, 1);
- mask->region -= QRect(opt->rect.right() - 2, opt->rect.top() + 1, 3, 1);
- mask->region -= QRect(opt->rect.right() - 1, opt->rect.top() + 2, 2, 1);
- mask->region -= QRect(opt->rect.right() , opt->rect.top() + 3, 1, 2);
- }
- break;
- case SH_TabBar_ElideMode:
- ret = Qt::ElideRight;
- break;
- case SH_DialogButtonLayout:
- ret = QDialogButtonBox::MacLayout;
- break;
- case SH_FormLayoutWrapPolicy:
- ret = QFormLayout::DontWrapRows;
- break;
- case SH_FormLayoutFieldGrowthPolicy:
- ret = QFormLayout::FieldsStayAtSizeHint;
- break;
- case SH_FormLayoutFormAlignment:
- ret = Qt::AlignHCenter | Qt::AlignTop;
- break;
- case SH_FormLayoutLabelAlignment:
- ret = Qt::AlignRight;
- break;
- case SH_ComboBox_PopupFrameStyle:
- ret = QFrame::NoFrame | QFrame::Plain;
- break;
- case SH_MessageBox_TextInteractionFlags:
- ret = Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse | Qt::TextSelectableByKeyboard;
- break;
- case SH_SpellCheckUnderlineStyle:
- ret = QTextCharFormat::DashUnderline;
- break;
- case SH_MessageBox_CenterButtons:
- ret = false;
- break;
- case SH_MenuBar_AltKeyNavigation:
- ret = false;
- break;
- case SH_ItemView_MovementWithoutUpdatingSelection:
- ret = false;
- break;
- case SH_FocusFrame_AboveWidget:
- ret = true;
- break;
- case SH_WizardStyle:
- ret = QWizard::MacStyle;
- break;
- case SH_ItemView_ArrowKeysNavigateIntoChildren:
- ret = false;
- break;
- case SH_Menu_FlashTriggeredItem:
- ret = true;
- break;
- case SH_Menu_FadeOutOnHide:
- ret = true;
- break;
- case SH_Menu_Mask:
- if (opt) {
- if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
- ret = true;
- HIRect menuRect = CGRectMake(opt->rect.x(), opt->rect.y() + 4,
- opt->rect.width(), opt->rect.height() - 8);
- HIThemeMenuDrawInfo mdi;
- mdi.version = 0;
- if (w && qobject_cast<QMenu *>(w->parentWidget()))
- mdi.menuType = kThemeMenuTypeHierarchical;
- else
- mdi.menuType = kThemeMenuTypePopUp;
- QCFType<HIShapeRef> shape;
- HIThemeGetMenuBackgroundShape(&menuRect, &mdi, &shape);
- mask->region = QRegion::fromHIShapeRef(shape);
- }
- }
- break;
- case SH_ItemView_PaintAlternatingRowColorsForEmptyArea:
- ret = true;
- break;
- case SH_TabBar_CloseButtonPosition:
- ret = QTabBar::LeftSide;
- break;
- case SH_DockWidget_ButtonsHaveFrame:
- ret = false;
- break;
- default:
- ret = QWindowsStyle::styleHint(sh, opt, w, hret);
- break;
- }
- return ret;
-}
-
-QPixmap QMacStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const
-{
- switch (iconMode) {
- case QIcon::Disabled: {
- QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
- int imgh = img.height();
- int imgw = img.width();
- QRgb pixel;
- for (int y = 0; y < imgh; ++y) {
- for (int x = 0; x < imgw; ++x) {
- pixel = img.pixel(x, y);
- img.setPixel(x, y, qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel),
- qAlpha(pixel) / 2));
- }
- }
- return QPixmap::fromImage(img);
- }
- default:
- ;
- }
- return QWindowsStyle::generatedIconPixmap(iconMode, pixmap, opt);
-}
-
-
-QPixmap QMacStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget) const
-{
- // The default implementation of QStyle::standardIconImplementation() is to call standardPixmap()
- // I don't want infinite recursion so if we do get in that situation, just return the Window's
- // standard pixmap instead (since there is no mac-specific icon then). This should be fine until
- // someone changes how Windows standard
- // pixmap works.
- static bool recursionGuard = false;
-
- if (recursionGuard)
- return QWindowsStyle::standardPixmap(standardPixmap, opt, widget);
-
- recursionGuard = true;
- QIcon icon = standardIconImplementation(standardPixmap, opt, widget);
- recursionGuard = false;
- int size;
- switch (standardPixmap) {
- default:
- size = 32;
- break;
- case SP_MessageBoxCritical:
- case SP_MessageBoxQuestion:
- case SP_MessageBoxInformation:
- case SP_MessageBoxWarning:
- size = 64;
- break;
- }
- return icon.pixmap(size, size);
-}
-
-void QMacStyle::setFocusRectPolicy(QWidget *w, FocusRectPolicy policy)
-{
- switch (policy) {
- case FocusDefault:
- break;
- case FocusEnabled:
- case FocusDisabled:
- w->setAttribute(Qt::WA_MacShowFocusRect, policy == FocusEnabled);
- break;
- }
-}
-
-QMacStyle::FocusRectPolicy QMacStyle::focusRectPolicy(const QWidget *w)
-{
- return w->testAttribute(Qt::WA_MacShowFocusRect) ? FocusEnabled : FocusDisabled;
-}
-
-void QMacStyle::setWidgetSizePolicy(const QWidget *widget, WidgetSizePolicy policy)
-{
- QWidget *wadget = const_cast<QWidget *>(widget);
- wadget->setAttribute(Qt::WA_MacNormalSize, policy == SizeLarge);
- wadget->setAttribute(Qt::WA_MacSmallSize, policy == SizeSmall);
- wadget->setAttribute(Qt::WA_MacMiniSize, policy == SizeMini);
-}
-
-QMacStyle::WidgetSizePolicy QMacStyle::widgetSizePolicy(const QWidget *widget)
-{
- while (widget) {
- if (widget->testAttribute(Qt::WA_MacMiniSize)) {
- return SizeMini;
- } else if (widget->testAttribute(Qt::WA_MacSmallSize)) {
- return SizeSmall;
- } else if (widget->testAttribute(Qt::WA_MacNormalSize)) {
- return SizeLarge;
- }
- widget = widget->parentWidget();
- }
- return SizeDefault;
-}
-
-void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w) const
-{
- ThemeDrawState tds = d->getDrawState(opt->state);
- QMacCGContext cg(p);
- switch (pe) {
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowLeft: {
- p->save();
- p->setRenderHint(QPainter::Antialiasing);
- int xOffset = opt->direction == Qt::LeftToRight ? 2 : -1;
- QMatrix matrix;
- matrix.translate(opt->rect.center().x() + xOffset, opt->rect.center().y() + 2);
- QPainterPath path;
- switch(pe) {
- default:
- case PE_IndicatorArrowDown:
- break;
- case PE_IndicatorArrowUp:
- matrix.rotate(180);
- break;
- case PE_IndicatorArrowLeft:
- matrix.rotate(90);
- break;
- case PE_IndicatorArrowRight:
- matrix.rotate(-90);
- break;
- }
- path.moveTo(0, 5);
- path.lineTo(-4, -3);
- path.lineTo(4, -3);
- p->setMatrix(matrix);
- p->setPen(Qt::NoPen);
- p->setBrush(QColor(0, 0, 0, 135));
- p->drawPath(path);
- p->restore();
- break; }
- case PE_FrameTabBarBase:
- if (const QStyleOptionTabBarBaseV2 *tbb
- = qstyleoption_cast<const QStyleOptionTabBarBaseV2 *>(opt)) {
- if (tbb->documentMode) {
- p->save();
- drawTabBase(p, tbb, w);
- p->restore();
- return;
- }
-
- QRegion region(tbb->rect);
- region -= tbb->tabBarRect;
- p->save();
- p->setClipRegion(region);
- QStyleOptionTabWidgetFrame twf;
- twf.QStyleOption::operator=(*tbb);
- twf.shape = tbb->shape;
- switch (getTabDirection(twf.shape)) {
- case kThemeTabNorth:
- twf.rect = twf.rect.adjusted(0, 0, 0, 10);
- break;
- case kThemeTabSouth:
- twf.rect = twf.rect.adjusted(0, -10, 0, 0);
- break;
- case kThemeTabWest:
- twf.rect = twf.rect.adjusted(0, 0, 10, 0);
- break;
- case kThemeTabEast:
- twf.rect = twf.rect.adjusted(0, -10, 0, 0);
- break;
- }
- proxy()->drawPrimitive(PE_FrameTabWidget, &twf, p, w);
- p->restore();
- }
- break;
- case PE_PanelTipLabel:
- p->fillRect(opt->rect, opt->palette.brush(QPalette::ToolTipBase));
- break;
- case PE_FrameGroupBox:
- if (const QStyleOptionFrame *groupBox = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- const QStyleOptionFrameV2 *frame2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(opt);
- if (frame2 && frame2->features & QStyleOptionFrameV2::Flat) {
- QWindowsStyle::drawPrimitive(pe, groupBox, p, w);
- } else {
- HIThemeGroupBoxDrawInfo gdi;
- gdi.version = qt_mac_hitheme_version;
- gdi.state = tds;
- if (w && qobject_cast<QGroupBox *>(w->parentWidget()))
- gdi.kind = kHIThemeGroupBoxKindSecondary;
- else
- gdi.kind = kHIThemeGroupBoxKindPrimary;
- HIRect hirect = qt_hirectForQRect(opt->rect);
- HIThemeDrawGroupBox(&hirect, &gdi, cg, kHIThemeOrientationNormal);
- }
- }
- break;
- case PE_IndicatorToolBarSeparator: {
- QPainterPath path;
- if (opt->state & State_Horizontal) {
- int xpoint = opt->rect.center().x();
- path.moveTo(xpoint + 0.5, opt->rect.top() + 1);
- path.lineTo(xpoint + 0.5, opt->rect.bottom());
- } else {
- int ypoint = opt->rect.center().y();
- path.moveTo(opt->rect.left() + 2 , ypoint + 0.5);
- path.lineTo(opt->rect.right() + 1, ypoint + 0.5);
- }
- QPainterPathStroker theStroker;
- theStroker.setCapStyle(Qt::FlatCap);
- theStroker.setDashPattern(QVector<qreal>() << 1 << 2);
- path = theStroker.createStroke(path);
- p->fillPath(path, QColor(0, 0, 0, 119));
- }
- break;
- case PE_FrameWindow:
- break;
- case PE_IndicatorDockWidgetResizeHandle: {
- // The docwidget resize handle is drawn as a one-pixel wide line.
- p->save();
- if (opt->state & State_Horizontal) {
- p->setPen(QColor(160, 160, 160));
- p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
- } else {
- p->setPen(QColor(145, 145, 145));
- p->drawLine(opt->rect.topRight(), opt->rect.bottomRight());
- }
- p->restore();
- } break;
- case PE_IndicatorToolBarHandle: {
- p->save();
- QPainterPath path;
- int x = opt->rect.x() + 6;
- int y = opt->rect.y() + 5;
- static const int RectHeight = 2;
- if (opt->state & State_Horizontal) {
- while (y < opt->rect.height() - RectHeight - 6) {
- path.moveTo(x, y);
- path.addRect(x, y, RectHeight, RectHeight);
- y += 6;
- }
- } else {
- while (x < opt->rect.width() - RectHeight - 6) {
- path.moveTo(x, y);
- path.addRect(x, y, RectHeight, RectHeight);
- x += 6;
- }
- }
- p->setPen(Qt::NoPen);
- QColor dark = opt->palette.dark().color();
- dark.setAlphaF(0.75);
- QColor light = opt->palette.light().color();
- light.setAlphaF(0.6);
- p->fillPath(path, light);
- p->save();
- p->translate(1, 1);
- p->fillPath(path, dark);
- p->restore();
- p->translate(3, 3);
- p->fillPath(path, light);
- p->translate(1, 1);
- p->fillPath(path, dark);
- p->restore();
-
- break;
- }
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- // In HITheme, up is down, down is up and hamburgers eat people.
- if (header->sortIndicator != QStyleOptionHeader::None)
- proxy()->drawPrimitive(
- (header->sortIndicator == QStyleOptionHeader::SortDown) ?
- PE_IndicatorArrowUp : PE_IndicatorArrowDown, header, p, w);
- }
- break;
- case PE_IndicatorMenuCheckMark: {
- const int checkw = 8;
- const int checkh = 8;
- const int xoff = qMax(0, (opt->rect.width() - checkw) / 2);
- const int yoff = qMax(0, (opt->rect.width() - checkh) / 2);
- const int x1 = xoff + opt->rect.x();
- const int y1 = yoff + opt->rect.y() + checkw/2;
- const int x2 = xoff + opt->rect.x() + checkw/4;
- const int y2 = yoff + opt->rect.y() + checkh;
- const int x3 = xoff + opt->rect.x() + checkw;
- const int y3 = yoff + opt->rect.y();
-
- QVector<QLineF> a(2);
- a << QLineF(x1, y1, x2, y2);
- a << QLineF(x2, y2, x3, y3);
- if (opt->palette.currentColorGroup() == QPalette::Active)
- p->setPen(QPen(Qt::white, 3));
- else
- p->setPen(QPen(QColor(100, 100, 100), 3));
- p->save();
- p->setRenderHint(QPainter::Antialiasing);
- p->drawLines(a);
- p->restore();
- break; }
- case PE_IndicatorViewItemCheck:
- case PE_Q3CheckListExclusiveIndicator:
- case PE_Q3CheckListIndicator:
- case PE_IndicatorRadioButton:
- case PE_IndicatorCheckBox: {
- bool drawColorless = (!(opt->state & State_Active))
- && opt->palette.currentColorGroup() == QPalette::Active;
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = tds;
- if (drawColorless && tds == kThemeStateInactive)
- bdi.state = kThemeStateActive;
- bdi.adornment = kThemeDrawIndicatorOnly;
- if (opt->state & State_HasFocus)
- bdi.adornment |= kThemeAdornmentFocus;
- bool isRadioButton = (pe == PE_Q3CheckListExclusiveIndicator
- || pe == PE_IndicatorRadioButton);
- switch (d->aquaSizeConstrain(opt, w)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- if (isRadioButton)
- bdi.kind = kThemeRadioButton;
- else
- bdi.kind = kThemeCheckBox;
- break;
- case QAquaSizeMini:
- if (isRadioButton)
- bdi.kind = kThemeMiniRadioButton;
- else
- bdi.kind = kThemeMiniCheckBox;
- break;
- case QAquaSizeSmall:
- if (isRadioButton)
- bdi.kind = kThemeSmallRadioButton;
- else
- bdi.kind = kThemeSmallCheckBox;
- break;
- }
- if (opt->state & State_NoChange)
- bdi.value = kThemeButtonMixed;
- else if (opt->state & State_On)
- bdi.value = kThemeButtonOn;
- else
- bdi.value = kThemeButtonOff;
- HIRect macRect;
- if (pe == PE_Q3CheckListExclusiveIndicator || pe == PE_Q3CheckListIndicator)
- macRect = qt_hirectForQRect(opt->rect);
- else
- macRect = qt_hirectForQRect(opt->rect);
- if (!drawColorless)
- HIThemeDrawButton(&macRect, &bdi, cg, kHIThemeOrientationNormal, 0);
- else
- d->drawColorlessButton(macRect, &bdi, p, opt);
- break; }
- case PE_FrameFocusRect:
- // Use the our own focus widget stuff.
- break;
- case PE_IndicatorBranch: {
- if (!(opt->state & State_Children))
- break;
- HIThemeButtonDrawInfo bi;
- bi.version = qt_mac_hitheme_version;
- bi.state = tds;
- if (tds == kThemeStateInactive && opt->palette.currentColorGroup() == QPalette::Active)
- bi.state = kThemeStateActive;
- if (opt->state & State_Sunken)
- bi.state |= kThemeStatePressed;
- bi.kind = kThemeDisclosureButton;
- if (opt->state & State_Open)
- bi.value = kThemeDisclosureDown;
- else
- bi.value = opt->direction == Qt::LeftToRight ? kThemeDisclosureRight : kThemeDisclosureLeft;
- bi.adornment = kThemeAdornmentNone;
- HIRect hirect = qt_hirectForQRect(opt->rect.adjusted(DisclosureOffset,0,-DisclosureOffset,0));
- HIThemeDrawButton(&hirect, &bi, cg, kHIThemeOrientationNormal, 0);
- break; }
-
- case PE_Frame: {
- QPen oldPen = p->pen();
- p->setPen(opt->palette.base().color().darker(140));
- p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
- p->setPen(opt->palette.base().color().darker(180));
- p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
- p->setPen(oldPen);
- break; }
-
- case PE_FrameLineEdit:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (frame->state & State_Sunken) {
- QColor baseColor(frame->palette.background().color());
- HIThemeFrameDrawInfo fdi;
- fdi.version = qt_mac_hitheme_version;
- fdi.state = tds;
- SInt32 frame_size;
- if (pe == PE_FrameLineEdit) {
- fdi.kind = kHIThemeFrameTextFieldSquare;
- GetThemeMetric(kThemeMetricEditTextFrameOutset, &frame_size);
- if ((frame->state & State_ReadOnly) || !(frame->state & State_Enabled))
- fdi.state = kThemeStateInactive;
- } else {
- baseColor = QColor(150, 150, 150); //hardcoded since no query function --Sam
- fdi.kind = kHIThemeFrameListBox;
- GetThemeMetric(kThemeMetricListBoxFrameOutset, &frame_size);
- }
- fdi.isFocused = (frame->state & State_HasFocus);
- int lw = frame->lineWidth;
- if (lw <= 0)
- lw = proxy()->pixelMetric(PM_DefaultFrameWidth, frame, w);
- { //clear to base color
- p->save();
- p->setPen(QPen(baseColor, lw));
- p->setBrush(Qt::NoBrush);
- p->drawRect(frame->rect);
- p->restore();
- }
- HIRect hirect = qt_hirectForQRect(frame->rect,
- QRect(frame_size, frame_size,
- frame_size * 2, frame_size * 2));
-
- HIThemeDrawFrame(&hirect, &fdi, cg, kHIThemeOrientationNormal);
- } else {
- QWindowsStyle::drawPrimitive(pe, opt, p, w);
- }
- }
- break;
- case PE_PanelLineEdit:
- QWindowsStyle::drawPrimitive(pe, opt, p, w);
- // Draw the focus frame for widgets other than QLineEdit (e.g. for line edits in Webkit).
- // Focus frame is drawn outside the rectangle passed in the option-rect.
- if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if ((opt->state & State_HasFocus) && !qobject_cast<const QLineEdit*>(w)) {
- int vmargin = pixelMetric(QStyle::PM_FocusFrameVMargin);
- int hmargin = pixelMetric(QStyle::PM_FocusFrameHMargin);
- QStyleOptionFrame focusFrame = *panel;
- focusFrame.rect = panel->rect.adjusted(-hmargin, -vmargin, hmargin, vmargin);
- drawControl(CE_FocusFrame, &focusFrame, p, w);
- }
- }
-
- break;
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *twf
- = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- HIRect hirect = qt_hirectForQRect(twf->rect);
- HIThemeTabPaneDrawInfo tpdi;
- tpdi.version = qt_mac_hitheme_tab_version();
- tpdi.state = tds;
- tpdi.direction = getTabDirection(twf->shape);
- tpdi.size = kHIThemeTabSizeNormal;
- tpdi.kind = kHIThemeTabKindNormal;
- tpdi.adornment = kHIThemeTabPaneAdornmentNormal;
- HIThemeDrawTabPane(&hirect, &tpdi, cg, kHIThemeOrientationNormal);
- }
- break;
- case PE_PanelScrollAreaCorner: {
- const QBrush brush(opt->palette.brush(QPalette::Base));
- p->fillRect(opt->rect, brush);
- p->setPen(QPen(QColor(217, 217, 217)));
- p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
- p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
- } break;
- case PE_FrameStatusBarItem:
- break;
- case PE_IndicatorTabClose: {
- bool hover = (opt->state & State_MouseOver);
- bool selected = (opt->state & State_Selected);
- bool active = (opt->state & State_Active);
- drawTabCloseButton(p, hover, active, selected);
- } break;
- case PE_PanelStatusBar: {
- if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_4) {
- QWindowsStyle::drawPrimitive(pe, opt, p, w);
- break;
- }
- // Use the Leopard style only if the status bar is the status bar for a
- // QMainWindow with a unifed toolbar.
- if (w == 0 || w->parent() == 0 || qobject_cast<QMainWindow *>(w->parent()) == 0 ||
- qobject_cast<QMainWindow *>(w->parent())->unifiedTitleAndToolBarOnMac() == false ) {
- QWindowsStyle::drawPrimitive(pe, opt, p, w);
- break;
- }
-
- // Fill the status bar with the titlebar gradient.
- QLinearGradient linearGrad(0, opt->rect.top(), 0, opt->rect.bottom());
- if (opt->state & QStyle::State_Active) {
- linearGrad.setColorAt(0, titlebarGradientActiveBegin);
- linearGrad.setColorAt(1, titlebarGradientActiveEnd);
- } else {
- linearGrad.setColorAt(0, titlebarGradientInactiveBegin);
- linearGrad.setColorAt(1, titlebarGradientInactiveEnd);
- }
- p->fillRect(opt->rect, linearGrad);
-
- // Draw the black separator line at the top of the status bar.
- if (opt->state & QStyle::State_Active)
- p->setPen(titlebarSeparatorLineActive);
- else
- p->setPen(titlebarSeparatorLineInactive);
- p->drawLine(opt->rect.left(), opt->rect.top(), opt->rect.right(), opt->rect.top());
-
- break;
- }
-
- default:
- QWindowsStyle::drawPrimitive(pe, opt, p, w);
- break;
- }
-}
-
-static inline QPixmap darkenPixmap(const QPixmap &pixmap)
-{
- QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
- int imgh = img.height();
- int imgw = img.width();
- int h, s, v, a;
- QRgb pixel;
- for (int y = 0; y < imgh; ++y) {
- for (int x = 0; x < imgw; ++x) {
- pixel = img.pixel(x, y);
- a = qAlpha(pixel);
- QColor hsvColor(pixel);
- hsvColor.getHsv(&h, &s, &v);
- s = qMin(100, s * 2);
- v = v / 2;
- hsvColor.setHsv(h, s, v);
- pixel = hsvColor.rgb();
- img.setPixel(x, y, qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel), a));
- }
- }
- return QPixmap::fromImage(img);
-}
-
-
-
-void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
- const QWidget *w) const
-{
- ThemeDrawState tds = d->getDrawState(opt->state);
- QMacCGContext cg(p);
- switch (ce) {
- case CE_HeaderSection:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- State flags = header->state;
- QRect ir = header->rect;
- bdi.kind = kThemeListHeaderButton;
- bdi.adornment = kThemeAdornmentNone;
- bdi.state = kThemeStateActive;
-
- if (flags & State_On)
- bdi.value = kThemeButtonOn;
- else
- bdi.value = kThemeButtonOff;
-
- if (header->orientation == Qt::Horizontal){
- switch (header->position) {
- case QStyleOptionHeader::Beginning:
- ir.adjust(-1, -1, 0, 0);
- break;
- case QStyleOptionHeader::Middle:
- ir.adjust(-1, -1, 0, 0);
- break;
- case QStyleOptionHeader::OnlyOneSection:
- case QStyleOptionHeader::End:
- ir.adjust(-1, -1, 1, 0);
- break;
- default:
- break;
- }
-
- if (header->position != QStyleOptionHeader::Beginning
- && header->position != QStyleOptionHeader::OnlyOneSection) {
- bdi.adornment = header->direction == Qt::LeftToRight
- ? kThemeAdornmentHeaderButtonLeftNeighborSelected
- : kThemeAdornmentHeaderButtonRightNeighborSelected;
- }
- }
-
- if (flags & State_Active) {
- if (!(flags & State_Enabled))
- bdi.state = kThemeStateUnavailable;
- else if (flags & State_Sunken)
- bdi.state = kThemeStatePressed;
- } else {
- if (flags & State_Enabled)
- bdi.state = kThemeStateInactive;
- else
- bdi.state = kThemeStateUnavailableInactive;
- }
-
- if (header->sortIndicator != QStyleOptionHeader::None) {
- bdi.value = kThemeButtonOn;
- if (header->sortIndicator == QStyleOptionHeader::SortDown)
- bdi.adornment = kThemeAdornmentHeaderButtonSortUp;
- }
- if (flags & State_HasFocus)
- bdi.adornment = kThemeAdornmentFocus;
-
- ir = visualRect(header->direction, header->rect, ir);
- HIRect bounds = qt_hirectForQRect(ir);
-
- bool noVerticalHeader = true;
- if (w)
- if (const QTableView *table = qobject_cast<const QTableView *>(w->parentWidget()))
- noVerticalHeader = !table->verticalHeader()->isVisible();
-
- bool drawTopBorder = header->orientation == Qt::Horizontal;
- bool drawLeftBorder = header->orientation == Qt::Vertical
- || header->position == QStyleOptionHeader::OnlyOneSection
- || (header->position == QStyleOptionHeader::Beginning && noVerticalHeader);
- d->drawTableHeader(bounds, drawTopBorder, drawLeftBorder, bdi, p);
- }
- break;
- case CE_HeaderLabel:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QRect textr = header->rect;
- if (!header->icon.isNull()) {
- QIcon::Mode mode = QIcon::Disabled;
- if (opt->state & State_Enabled)
- mode = QIcon::Normal;
- QPixmap pixmap = header->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize), mode);
-
- QRect pixr = header->rect;
- pixr.setY(header->rect.center().y() - (pixmap.height() - 1) / 2);
- proxy()->drawItemPixmap(p, pixr, Qt::AlignVCenter, pixmap);
- textr.translate(pixmap.width() + 2, 0);
- }
-
- proxy()->drawItemText(p, textr, header->textAlignment | Qt::AlignVCenter, header->palette,
- header->state & State_Enabled, header->text, QPalette::ButtonText);
- }
- break;
- case CE_ToolButtonLabel:
- if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- QStyleOptionToolButton myTb = *tb;
- myTb.state &= ~State_AutoRaise;
- if (w && qobject_cast<QToolBar *>(w->parentWidget())) {
- QRect cr = tb->rect;
- int shiftX = 0;
- int shiftY = 0;
- bool needText = false;
- int alignment = 0;
- bool down = tb->state & (State_Sunken | State_On);
- if (down) {
- shiftX = proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, w);
- shiftY = proxy()->pixelMetric(PM_ButtonShiftVertical, tb, w);
- }
- // The down state is special for QToolButtons in a toolbar on the Mac
- // The text is a bit bolder and gets a drop shadow and the icons are also darkened.
- // This doesn't really fit into any particular case in QIcon, so we
- // do the majority of the work ourselves.
- if (!(tb->features & QStyleOptionToolButton::Arrow)) {
- Qt::ToolButtonStyle tbstyle = tb->toolButtonStyle;
- if (tb->icon.isNull() && !tb->text.isEmpty())
- tbstyle = Qt::ToolButtonTextOnly;
-
- switch (tbstyle) {
- case Qt::ToolButtonTextOnly: {
- needText = true;
- alignment = Qt::AlignCenter;
- break; }
- case Qt::ToolButtonIconOnly:
- case Qt::ToolButtonTextBesideIcon:
- case Qt::ToolButtonTextUnderIcon: {
- QRect pr = cr;
- QIcon::Mode iconMode = (tb->state & State_Enabled) ? QIcon::Normal
- : QIcon::Disabled;
- QIcon::State iconState = (tb->state & State_On) ? QIcon::On
- : QIcon::Off;
- QPixmap pixmap = tb->icon.pixmap(tb->rect.size().boundedTo(tb->iconSize), iconMode, iconState);
-
- // Draw the text if it's needed.
- if (tb->toolButtonStyle != Qt::ToolButtonIconOnly) {
- needText = true;
- if (tb->toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
- QMainWindow *mw = qobject_cast<QMainWindow *>(w->window());
- if (mw && mw->unifiedTitleAndToolBarOnMac()) {
- pr.setHeight(pixmap.size().height());
- cr.adjust(0, pr.bottom() + 1, 0, 1);
- } else {
- pr.setHeight(pixmap.size().height() + 6);
- cr.adjust(0, pr.bottom(), 0, -3);
- }
- alignment |= Qt::AlignCenter;
- } else {
- pr.setWidth(pixmap.width() + 8);
- cr.adjust(pr.right(), 0, 0, 0);
- alignment |= Qt::AlignLeft | Qt::AlignVCenter;
- }
- }
- if (opt->state & State_Sunken) {
- pr.translate(shiftX, shiftY);
- pixmap = darkenPixmap(pixmap);
- }
- proxy()->drawItemPixmap(p, pr, Qt::AlignCenter, pixmap);
- break; }
- default:
- Q_ASSERT(false);
- break;
- }
-
- if (needText) {
- QPalette pal = tb->palette;
- QPalette::ColorRole role = QPalette::NoRole;
- if (!proxy()->styleHint(SH_UnderlineShortcut, tb, w))
- alignment |= Qt::TextHideMnemonic;
- if (down)
- cr.translate(shiftX, shiftY);
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5
- && (tbstyle == Qt::ToolButtonTextOnly
- || (tbstyle != Qt::ToolButtonTextOnly && !down))) {
- QPen pen = p->pen();
- QColor light = down ? Qt::black : Qt::white;
- light.setAlphaF(0.375f);
- p->setPen(light);
- p->drawText(cr.adjusted(0, 1, 0, 1), alignment, tb->text);
- p->setPen(pen);
- if (down && tbstyle == Qt::ToolButtonTextOnly) {
- pal = QApplication::palette("QMenu");
- pal.setCurrentColorGroup(tb->palette.currentColorGroup());
- role = QPalette::HighlightedText;
- }
- }
- proxy()->drawItemText(p, cr, alignment, pal,
- tb->state & State_Enabled, tb->text, role);
- if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5 &&
- (tb->state & State_Sunken)) {
- // Draw a "drop shadow" in earlier versions.
- proxy()->drawItemText(p, cr.adjusted(0, 1, 0, 1), alignment,
- tb->palette, tb->state & State_Enabled, tb->text);
- }
- }
- } else {
- QWindowsStyle::drawControl(ce, &myTb, p, w);
- }
- } else {
- QWindowsStyle::drawControl(ce, &myTb, p, w);
- }
- }
- break;
- case CE_ToolBoxTabShape:
- QCommonStyle::drawControl(ce, opt, p, w);
- break;
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *btn = ::qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (!(btn->state & (State_Raised | State_Sunken | State_On)))
- break;
-
- if (btn->features & QStyleOptionButton::CommandLinkButton) {
- QWindowsStyle::drawControl(ce, opt, p, w);
- break;
- }
-
- HIThemeButtonDrawInfo bdi;
- d->initHIThemePushButton(btn, w, tds, &bdi);
- if (btn->features & QStyleOptionButton::DefaultButton
- && d->animatable(QMacStylePrivate::AquaPushButton, w)) {
- bdi.adornment |= kThemeAdornmentDefault;
- bdi.animation.time.start = d->defaultButtonStart;
- bdi.animation.time.current = CFAbsoluteTimeGetCurrent();
- if (d->timerID <= -1)
- QMetaObject::invokeMethod(d, "startAnimationTimer", Qt::QueuedConnection);
- }
- // Unlike Carbon, we want the button to always be drawn inside its bounds.
- // Therefore, make the button a bit smaller, so that even if it got focus,
- // the focus 'shadow' will be inside.
- HIRect newRect = qt_hirectForQRect(btn->rect);
- if (bdi.kind == kThemePushButton || bdi.kind == kThemePushButtonSmall) {
- newRect.origin.x += QMacStylePrivate::PushButtonLeftOffset;
- newRect.origin.y += QMacStylePrivate::PushButtonTopOffset;
- newRect.size.width -= QMacStylePrivate::PushButtonRightOffset;
- newRect.size.height -= QMacStylePrivate::PushButtonBottomOffset;
- } else if (bdi.kind == kThemePushButtonMini) {
- newRect.origin.x += QMacStylePrivate::PushButtonLeftOffset - 2;
- newRect.origin.y += QMacStylePrivate::PushButtonTopOffset;
- newRect.size.width -= QMacStylePrivate::PushButtonRightOffset - 4;
- }
- HIThemeDrawButton(&newRect, &bdi, cg, kHIThemeOrientationNormal, 0);
-
- if (btn->features & QStyleOptionButton::HasMenu) {
- int mbi = proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, btn, w);
- QRect ir = btn->rect;
- HIRect arrowRect = CGRectMake(ir.right() - mbi - QMacStylePrivate::PushButtonRightOffset,
- ir.height() / 2 - 4, mbi, ir.height() / 2);
- bool drawColorless = btn->palette.currentColorGroup() == QPalette::Active;
- if (drawColorless && tds == kThemeStateInactive)
- tds = kThemeStateActive;
-
- HIThemePopupArrowDrawInfo pdi;
- pdi.version = qt_mac_hitheme_version;
- pdi.state = tds;
- pdi.orientation = kThemeArrowDown;
- if (arrowRect.size.width < 8.)
- pdi.size = kThemeArrow5pt;
- else
- pdi.size = kThemeArrow9pt;
- HIThemeDrawPopupArrow(&arrowRect, &pdi, cg, kHIThemeOrientationNormal);
- }
- }
- break;
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- // We really don't want the label to be drawn the same as on
- // windows style if it has an icon and text, then it should be more like a
- // tab. So, cheat a little here. However, if it *is* only an icon
- // the windows style works great, so just use that implementation.
- bool hasMenu = btn->features & QStyleOptionButton::HasMenu;
- bool hasIcon = !btn->icon.isNull();
- bool hasText = !btn->text.isEmpty();
- if (!hasIcon && !hasMenu) {
- // ### this is really overly difficult, simplify.
- // It basically tries to get the right font for "small" and "mini" icons.
- QFont oldFont = p->font();
- QFont newFont = qt_app_fonts_hash()->value("QPushButton", QFont());
- ThemeFontID themeId = kThemePushButtonFont;
- if (oldFont == newFont) { // Yes, use HITheme to draw the text for small sizes.
- switch (d->aquaSizeConstrain(opt, w)) {
- default:
- break;
- case QAquaSizeSmall:
- themeId = kThemeSmallSystemFont;
- break;
- case QAquaSizeMini:
- themeId = kThemeMiniSystemFont;
- break;
- }
- }
- if (themeId == kThemePushButtonFont) {
- QWindowsStyle::drawControl(ce, btn, p, w);
- } else {
- p->save();
- CGContextSetShouldAntialias(cg, true);
- CGContextSetShouldSmoothFonts(cg, true);
- HIThemeTextInfo tti;
- tti.version = qt_mac_hitheme_version;
- tti.state = tds;
- QColor textColor = btn->palette.buttonText().color();
- CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
- textColor.blueF(), textColor.alphaF() };
- CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
- CGContextSetFillColor(cg, colorComp);
- tti.fontID = themeId;
- tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
- tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
- tti.options = kHIThemeTextBoxOptionNone;
- tti.truncationPosition = kHIThemeTextTruncationNone;
- tti.truncationMaxLines = 1 + btn->text.count(QLatin1Char('\n'));
- QCFString buttonText = qt_mac_removeMnemonics(btn->text);
- QRect r = btn->rect;
- HIRect bounds = qt_hirectForQRect(r);
- HIThemeDrawTextBox(buttonText, &bounds, &tti,
- cg, kHIThemeOrientationNormal);
- p->restore();
- }
- } else {
- if (hasIcon && !hasText) {
- QWindowsStyle::drawControl(ce, btn, p, w);
- } else {
- QRect freeContentRect = btn->rect;
- QRect textRect = itemTextRect(
- btn->fontMetrics, freeContentRect, Qt::AlignCenter, btn->state & State_Enabled, btn->text);
- if (hasMenu)
- textRect.adjust(-1, 0, -1, 0);
- // Draw the icon:
- if (hasIcon) {
- int contentW = textRect.width();
- if (hasMenu)
- contentW += proxy()->pixelMetric(PM_MenuButtonIndicator) + 4;
- QIcon::Mode mode = btn->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- if (mode == QIcon::Normal && btn->state & State_HasFocus)
- mode = QIcon::Active;
- // Decide if the icon is should be on or off:
- QIcon::State state = QIcon::Off;
- if (btn->state & State_On)
- state = QIcon::On;
- QPixmap pixmap = btn->icon.pixmap(btn->iconSize, mode, state);
- contentW += pixmap.width() + QMacStylePrivate::PushButtonContentPadding;
- int iconLeftOffset = freeContentRect.x() + (freeContentRect.width() - contentW) / 2;
- int iconTopOffset = freeContentRect.y() + (freeContentRect.height() - pixmap.height()) / 2;
- QRect iconDestRect(iconLeftOffset, iconTopOffset, pixmap.width(), pixmap.height());
- QRect visualIconDestRect = visualRect(btn->direction, freeContentRect, iconDestRect);
- proxy()->drawItemPixmap(p, visualIconDestRect, Qt::AlignLeft | Qt::AlignVCenter, pixmap);
- int newOffset = iconDestRect.x() + iconDestRect.width()
- + QMacStylePrivate::PushButtonContentPadding - textRect.x();
- textRect.adjust(newOffset, 0, newOffset, 0);
- }
- // Draw the text:
- if (hasText) {
- textRect = visualRect(btn->direction, freeContentRect, textRect);
- proxy()->drawItemText(p, textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, btn->palette,
- (btn->state & State_Enabled), btn->text, QPalette::ButtonText);
- }
- }
- }
- }
- break;
- case CE_ComboBoxLabel:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QStyleOptionComboBox comboCopy = *cb;
- comboCopy.direction = Qt::LeftToRight;
- QWindowsStyle::drawControl(CE_ComboBoxLabel, &comboCopy, p, w);
- }
- break;
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tabOpt = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
-
- if (const QStyleOptionTabV3 *tabOptV3 = qstyleoption_cast<const QStyleOptionTabV3 *>(opt)) {
- if (tabOptV3->documentMode) {
- p->save();
- QRect tabRect = tabOptV3->rect;
- drawTabShape(p, tabOptV3);
- p->restore();
- return;
- }
- }
- HIThemeTabDrawInfo tdi;
- tdi.version = 1;
- tdi.style = kThemeTabNonFront;
- tdi.direction = getTabDirection(tabOpt->shape);
- switch (d->aquaSizeConstrain(opt, w)) {
- default:
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- tdi.size = kHIThemeTabSizeNormal;
- break;
- case QAquaSizeSmall:
- tdi.size = kHIThemeTabSizeSmall;
- break;
- case QAquaSizeMini:
- tdi.size = kHIThemeTabSizeMini;
- break;
- }
- bool verticalTabs = tdi.direction == kThemeTabWest || tdi.direction == kThemeTabEast;
- QRect tabRect = tabOpt->rect;
-
- bool selected = tabOpt->state & State_Selected;
- if (selected) {
- if (!(tabOpt->state & State_Active))
- tdi.style = kThemeTabFrontUnavailable;
- else if (!(tabOpt->state & State_Enabled))
- tdi.style = kThemeTabFrontInactive;
- else
- tdi.style = kThemeTabFront;
- } else if (!(tabOpt->state & State_Active)) {
- tdi.style = kThemeTabNonFrontUnavailable;
- } else if (!(tabOpt->state & State_Enabled)) {
- tdi.style = kThemeTabNonFrontInactive;
- } else if (tabOpt->state & State_Sunken) {
- tdi.style = kThemeTabFrontInactive; // (should be kThemeTabNonFrontPressed)
- }
- if (tabOpt->state & State_HasFocus)
- tdi.adornment = kHIThemeTabAdornmentFocus;
- else
- tdi.adornment = kHIThemeTabAdornmentNone;
- tdi.kind = kHIThemeTabKindNormal;
- if (!verticalTabs)
- tabRect.setY(tabRect.y() - 1);
- else
- tabRect.setX(tabRect.x() - 1);
- QStyleOptionTab::TabPosition tp = tabOpt->position;
- QStyleOptionTab::SelectedPosition sp = tabOpt->selectedPosition;
- if (tabOpt->direction == Qt::RightToLeft && !verticalTabs) {
- if (sp == QStyleOptionTab::NextIsSelected)
- sp = QStyleOptionTab::PreviousIsSelected;
- else if (sp == QStyleOptionTab::PreviousIsSelected)
- sp = QStyleOptionTab::NextIsSelected;
- switch (tp) {
- case QStyleOptionTab::Beginning:
- tp = QStyleOptionTab::End;
- break;
- case QStyleOptionTab::End:
- tp = QStyleOptionTab::Beginning;
- break;
- default:
- break;
- }
- }
- bool stretchTabs = (!verticalTabs && tabRect.height() > 22) || (verticalTabs && tabRect.width() > 22);
-
- switch (tp) {
- case QStyleOptionTab::Beginning:
- tdi.position = kHIThemeTabPositionFirst;
- if (sp != QStyleOptionTab::NextIsSelected || stretchTabs)
- tdi.adornment |= kHIThemeTabAdornmentTrailingSeparator;
- break;
- case QStyleOptionTab::Middle:
- tdi.position = kHIThemeTabPositionMiddle;
- if (selected)
- tdi.adornment |= kHIThemeTabAdornmentLeadingSeparator;
- if (sp != QStyleOptionTab::NextIsSelected || stretchTabs) // Also when we're selected.
- tdi.adornment |= kHIThemeTabAdornmentTrailingSeparator;
- break;
- case QStyleOptionTab::End:
- tdi.position = kHIThemeTabPositionLast;
- if (selected)
- tdi.adornment |= kHIThemeTabAdornmentLeadingSeparator;
- break;
- case QStyleOptionTab::OnlyOneTab:
- tdi.position = kHIThemeTabPositionOnly;
- break;
- }
- // HITheme doesn't stretch its tabs. Therefore we have to cheat and do the job ourselves.
- if (stretchTabs) {
- HIRect hirect = CGRectMake(0, 0, 23, 23);
- QPixmap pm(23, 23);
- pm.fill(Qt::transparent);
- {
- QMacCGContext pmcg(&pm);
- HIThemeDrawTab(&hirect, &tdi, pmcg, kHIThemeOrientationNormal, 0);
- }
- QStyleHelper::drawBorderPixmap(pm, p, tabRect, 7, 7, 7, 7);
- } else {
- HIRect hirect = qt_hirectForQRect(tabRect);
- HIThemeDrawTab(&hirect, &tdi, cg, kHIThemeOrientationNormal, 0);
- }
- }
- break;
- case CE_TabBarTabLabel:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- QStyleOptionTabV3 myTab = *tab;
- ThemeTabDirection ttd = getTabDirection(myTab.shape);
- bool verticalTabs = ttd == kThemeTabWest || ttd == kThemeTabEast;
-
- // Check to see if we use have the same as the system font
- // (QComboMenuItem is internal and should never be seen by the
- // outside world, unless they read the source, in which case, it's
- // their own fault).
- bool nonDefaultFont = p->font() != qt_app_fonts_hash()->value("QComboMenuItem");
- if (verticalTabs || nonDefaultFont || !tab->icon.isNull()
- || !myTab.leftButtonSize.isNull() || !myTab.rightButtonSize.isNull()) {
- int heightOffset = 0;
- if (verticalTabs) {
- heightOffset = -1;
- } else if (nonDefaultFont) {
- if (p->fontMetrics().height() == myTab.rect.height())
- heightOffset = 2;
- }
- myTab.rect.setHeight(myTab.rect.height() + heightOffset);
-
- if (myTab.documentMode) {
- p->save();
- rotateTabPainter(p, myTab.shape, myTab.rect);
-
- QPalette np = tab->palette;
- np.setColor(QPalette::WindowText, QColor(255, 255, 255, 75));
- QRect nr = subElementRect(SE_TabBarTabText, opt, w);
- nr.moveTop(-1);
- int alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextHideMnemonic;
- proxy()->drawItemText(p, nr, alignment, np, tab->state & State_Enabled,
- tab->text, QPalette::WindowText);
- p->restore();
- }
-
- QCommonStyle::drawControl(ce, &myTab, p, w);
- } else {
- p->save();
- CGContextSetShouldAntialias(cg, true);
- CGContextSetShouldSmoothFonts(cg, true);
- HIThemeTextInfo tti;
- tti.version = qt_mac_hitheme_version;
- tti.state = tds;
- QColor textColor = myTab.palette.windowText().color();
- CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
- textColor.blueF(), textColor.alphaF() };
- CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
- CGContextSetFillColor(cg, colorComp);
- switch (d->aquaSizeConstrain(opt, w)) {
- default:
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- tti.fontID = kThemeSystemFont;
- break;
- case QAquaSizeSmall:
- tti.fontID = kThemeSmallSystemFont;
- break;
- case QAquaSizeMini:
- tti.fontID = kThemeMiniSystemFont;
- break;
- }
- tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
- tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
- tti.options = verticalTabs ? kHIThemeTextBoxOptionStronglyVertical : kHIThemeTextBoxOptionNone;
- tti.truncationPosition = kHIThemeTextTruncationNone;
- tti.truncationMaxLines = 1 + myTab.text.count(QLatin1Char('\n'));
- QCFString tabText = qt_mac_removeMnemonics(myTab.text);
- QRect r = myTab.rect.adjusted(0, 0, 0, -1);
- HIRect bounds = qt_hirectForQRect(r);
- HIThemeDrawTextBox(tabText, &bounds, &tti, cg, kHIThemeOrientationNormal);
- p->restore();
- }
- }
- break;
- case CE_DockWidgetTitle:
- if (const QDockWidget *dockWidget = qobject_cast<const QDockWidget *>(w)) {
- bool floating = dockWidget->isFloating();
- if (floating) {
- ThemeDrawState tds = d->getDrawState(opt->state);
- HIThemeWindowDrawInfo wdi;
- wdi.version = qt_mac_hitheme_version;
- wdi.state = tds;
- wdi.windowType = kThemeMovableDialogWindow;
- wdi.titleHeight = opt->rect.height();
- wdi.titleWidth = opt->rect.width();
- wdi.attributes = 0;
-
- HIRect titleBarRect;
- HIRect tmpRect = qt_hirectForQRect(opt->rect);
- {
- QCFType<HIShapeRef> titleRegion;
- QRect newr = opt->rect.adjusted(0, 0, 2, 0);
- HIThemeGetWindowShape(&tmpRect, &wdi, kWindowTitleBarRgn, &titleRegion);
- ptrHIShapeGetBounds(titleRegion, &tmpRect);
- newr.translate(newr.x() - int(tmpRect.origin.x), newr.y() - int(tmpRect.origin.y));
- titleBarRect = qt_hirectForQRect(newr);
- }
- QMacCGContext cg(p);
- HIThemeDrawWindowFrame(&titleBarRect, &wdi, cg, kHIThemeOrientationNormal, 0);
- } else {
- // fill title bar background
- QLinearGradient linearGrad(0, opt->rect.top(), 0, opt->rect.bottom());
- linearGrad.setColorAt(0, mainWindowGradientBegin);
- linearGrad.setColorAt(1, mainWindowGradientEnd);
- p->fillRect(opt->rect, linearGrad);
-
- // draw horizontal lines at top and bottom
- p->save();
- p->setPen(mainWindowGradientBegin.lighter(114));
- p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
- p->setPen(mainWindowGradientEnd.darker(114));
- p->drawLine(opt->rect.bottomLeft(), opt->rect.bottomRight());
- p->restore();
- }
- }
-
- // Draw the text...
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
- if (!dwOpt->title.isEmpty()) {
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, opt, w);
- if (verticalTitleBar) {
- QRect rect = dwOpt->rect;
- QRect r = rect;
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- titleRect = QRect(r.left() + rect.bottom()
- - titleRect.bottom(),
- r.top() + titleRect.left() - rect.left(),
- titleRect.height(), titleRect.width());
-
- p->translate(r.left(), r.top() + r.width());
- p->rotate(-90);
- p->translate(-r.left(), -r.top());
- }
-
- QFont oldFont = p->font();
- p->setFont(qt_app_fonts_hash()->value("QToolButton", p->font()));
- QString text = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight,
- titleRect.width());
- drawItemText(p, titleRect,
- Qt::AlignCenter | Qt::TextShowMnemonic, dwOpt->palette,
- dwOpt->state & State_Enabled, text,
- QPalette::WindowText);
- p->setFont(oldFont);
- }
- }
- break;
- case CE_FocusFrame: {
- int xOff = proxy()->pixelMetric(PM_FocusFrameHMargin, opt, w) + 1;
- int yOff = proxy()->pixelMetric(PM_FocusFrameVMargin, opt, w) + 1;
- HIRect hirect = CGRectMake(xOff+opt->rect.x(), yOff+opt->rect.y(), opt->rect.width() - 2 * xOff,
- opt->rect.height() - 2 * yOff);
- HIThemeDrawFocusRect(&hirect, true, QMacCGContext(p), kHIThemeOrientationNormal);
- break; }
- case CE_MenuItem:
- case CE_MenuEmptyArea:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- p->fillRect(mi->rect, opt->palette.background());
- QAquaWidgetSize widgetSize = d->aquaSizeConstrain(opt, w);
- int tabwidth = mi->tabWidth;
- int maxpmw = mi->maxIconWidth;
- bool active = mi->state & State_Selected;
- bool enabled = mi->state & State_Enabled;
- HIRect menuRect = qt_hirectForQRect(mi->menuRect);
- HIRect itemRect = qt_hirectForQRect(mi->rect);
- HIThemeMenuItemDrawInfo mdi;
- mdi.version = qt_mac_hitheme_version;
- mdi.itemType = kThemeMenuItemPlain;
- if (!mi->icon.isNull())
- mdi.itemType |= kThemeMenuItemHasIcon;
- if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
- mdi.itemType |= kThemeMenuItemHierarchical | kThemeMenuItemHierBackground;
- else
- mdi.itemType |= kThemeMenuItemPopUpBackground;
- if (enabled)
- mdi.state = kThemeMenuActive;
- else
- mdi.state = kThemeMenuDisabled;
- if (active)
- mdi.state |= kThemeMenuSelected;
- QRect contentRect;
- if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
- // First arg should be &menurect, but wacky stuff happens then.
- HIThemeDrawMenuSeparator(&itemRect, &itemRect, &mdi,
- cg, kHIThemeOrientationNormal);
- break;
- } else {
- HIRect cr;
- bool needAlpha = mi->palette.color(QPalette::Button) == Qt::transparent;
- if (needAlpha) {
- needAlpha = true;
- CGContextSaveGState(cg);
- CGContextSetAlpha(cg, 0.0);
- }
- HIThemeDrawMenuItem(&menuRect, &itemRect, &mdi,
- cg, kHIThemeOrientationNormal, &cr);
- if (needAlpha)
- CGContextRestoreGState(cg);
- if (ce == CE_MenuEmptyArea)
- break;
- contentRect = qt_qrectForHIRect(cr);
- }
- int xpos = contentRect.x() + 18;
- int checkcol = maxpmw;
- if (!enabled)
- p->setPen(mi->palette.text().color());
- else if (active)
- p->setPen(mi->palette.highlightedText().color());
- else
- p->setPen(mi->palette.buttonText().color());
-
- if (mi->checked) {
- // Use the HIThemeTextInfo foo to draw the check mark correctly, if we do it,
- // we somehow need to use a special encoding as it doesn't look right with our
- // drawText().
- p->save();
- CGContextSetShouldAntialias(cg, true);
- CGContextSetShouldSmoothFonts(cg, true);
- QColor textColor = p->pen().color();
- CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
- textColor.blueF(), textColor.alphaF() };
- CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
- CGContextSetFillColor(cg, colorComp);
- HIThemeTextInfo tti;
- tti.version = qt_mac_hitheme_version;
- tti.state = tds;
- if (active && enabled)
- tti.state = kThemeStatePressed;
- switch (widgetSize) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- tti.fontID = kThemeMenuItemMarkFont;
- break;
- case QAquaSizeSmall:
- tti.fontID = kThemeSmallSystemFont;
- break;
- case QAquaSizeMini:
- tti.fontID = kThemeMiniSystemFont;
- break;
- }
- tti.horizontalFlushness = kHIThemeTextHorizontalFlushLeft;
- tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
- tti.options = kHIThemeTextBoxOptionNone;
- tti.truncationPosition = kHIThemeTextTruncationNone;
- tti.truncationMaxLines = 1;
- QCFString checkmark;
-#if 0
- if (mi->checkType == QStyleOptionMenuItem::Exclusive)
- checkmark = QString(QChar(kDiamondUnicode));
- else
-#endif
- checkmark = QString(QChar(kCheckUnicode));
- int mw = checkcol + macItemFrame;
- int mh = contentRect.height() - 2 * macItemFrame;
- int xp = contentRect.x();
- xp += macItemFrame;
- CGFloat outWidth, outHeight, outBaseline;
- HIThemeGetTextDimensions(checkmark, 0, &tti, &outWidth, &outHeight,
- &outBaseline);
- if (widgetSize == QAquaSizeMini)
- outBaseline += 1;
- QRect r(xp, contentRect.y(), mw, mh);
- r.translate(0, p->fontMetrics().ascent() - int(outBaseline) + 1);
- HIRect bounds = qt_hirectForQRect(r);
- HIThemeDrawTextBox(checkmark, &bounds, &tti,
- cg, kHIThemeOrientationNormal);
- p->restore();
- }
- if (!mi->icon.isNull()) {
- QIcon::Mode mode = (mi->state & State_Enabled) ? QIcon::Normal
- : QIcon::Disabled;
- // Always be normal or disabled to follow the Mac style.
- int smallIconSize = proxy()->pixelMetric(PM_SmallIconSize);
- QSize iconSize(smallIconSize, smallIconSize);
- if (const QComboBox *comboBox = qobject_cast<const QComboBox *>(w)) {
- iconSize = comboBox->iconSize();
- }
- QPixmap pixmap = mi->icon.pixmap(iconSize, mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- QRect cr(xpos, contentRect.y(), checkcol, contentRect.height());
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(cr.center());
- p->drawPixmap(pmr.topLeft(), pixmap);
- xpos += pixw + 6;
- }
-
- QString s = mi->text;
- if (!s.isEmpty()) {
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignRight | Qt::AlignVCenter | Qt::TextHideMnemonic
- | Qt::TextSingleLine | Qt::AlignAbsolute;
- int yPos = contentRect.y();
- if (widgetSize == QAquaSizeMini)
- yPos += 1;
- p->save();
- if (t >= 0) {
- p->setFont(qt_app_fonts_hash()->value("QMenuItem", p->font()));
- int xp = contentRect.right() - tabwidth - macRightBorder
- - macItemHMargin - macItemFrame + 1;
- p->drawText(xp, yPos, tabwidth, contentRect.height(), text_flags,
- s.mid(t + 1));
- s = s.left(t);
- }
-
- const int xm = macItemFrame + maxpmw + macItemHMargin;
- QFont myFont = mi->font;
- // myFont may not have any "hard" flags set. We override
- // the point size so that when it is resolved against the device, this font will win.
- // This is mainly to handle cases where someone sets the font on the window
- // and then the combo inherits it and passes it onward. At that point the resolve mask
- // is very, very weak. This makes it stonger.
- myFont.setPointSizeF(QFontInfo(mi->font).pointSizeF());
- p->setFont(myFont);
- p->drawText(xpos, yPos, contentRect.width() - xm - tabwidth + 1,
- contentRect.height(), text_flags ^ Qt::AlignRight, s);
- p->restore();
- }
- }
- break;
- case CE_MenuHMargin:
- case CE_MenuVMargin:
- case CE_MenuTearoff:
- case CE_MenuScroller:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- p->fillRect(mi->rect, opt->palette.background());
-
- HIRect menuRect = qt_hirectForQRect(mi->menuRect);
- HIRect itemRect = qt_hirectForQRect(mi->rect);
- HIThemeMenuItemDrawInfo mdi;
- mdi.version = qt_mac_hitheme_version;
- if (!(opt->state & State_Enabled))
- mdi.state = kThemeMenuDisabled;
- else if (opt->state & State_Selected)
- mdi.state = kThemeMenuSelected;
- else
- mdi.state = kThemeMenuActive;
- if (ce == CE_MenuScroller) {
- if (opt->state & State_DownArrow)
- mdi.itemType = kThemeMenuItemScrollDownArrow;
- else
- mdi.itemType = kThemeMenuItemScrollUpArrow;
- } else {
- mdi.itemType = kThemeMenuItemPlain;
- }
- HIThemeDrawMenuItem(&menuRect, &itemRect, &mdi,
- cg,
- kHIThemeOrientationNormal, 0);
- if (ce == CE_MenuTearoff) {
- p->setPen(QPen(mi->palette.dark().color(), 1, Qt::DashLine));
- p->drawLine(mi->rect.x() + 2, mi->rect.y() + mi->rect.height() / 2 - 1,
- mi->rect.x() + mi->rect.width() - 4,
- mi->rect.y() + mi->rect.height() / 2 - 1);
- p->setPen(QPen(mi->palette.light().color(), 1, Qt::DashLine));
- p->drawLine(mi->rect.x() + 2, mi->rect.y() + mi->rect.height() / 2,
- mi->rect.x() + mi->rect.width() - 4,
- mi->rect.y() + mi->rect.height() / 2);
- }
- }
- break;
- case CE_MenuBarItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- HIRect menuRect = qt_hirectForQRect(mi->menuRect);
- HIRect itemRect = qt_hirectForQRect(mi->rect);
-
- if ((opt->state & State_Selected) && (opt->state & State_Enabled) && (opt->state & State_Sunken)){
- // Draw a selected menu item background:
- HIThemeMenuItemDrawInfo mdi;
- mdi.version = qt_mac_hitheme_version;
- mdi.state = kThemeMenuSelected;
- mdi.itemType = kThemeMenuItemPlain;
- HIThemeDrawMenuItem(&menuRect, &itemRect, &mdi, cg, kHIThemeOrientationNormal, 0);
- } else {
- // Draw the toolbar background:
- HIThemeMenuBarDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = kThemeMenuBarNormal;
- bdi.attributes = 0;
- HIThemeDrawMenuBarBackground(&menuRect, &bdi, cg, kHIThemeOrientationNormal);
- }
-
- if (!mi->icon.isNull()) {
- drawItemPixmap(p, mi->rect,
- Qt::AlignCenter | Qt::TextHideMnemonic | Qt::TextDontClip
- | Qt::TextSingleLine,
- mi->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize),
- (mi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled));
- } else {
- drawItemText(p, mi->rect,
- Qt::AlignCenter | Qt::TextHideMnemonic | Qt::TextDontClip
- | Qt::TextSingleLine,
- mi->palette, mi->state & State_Enabled,
- mi->text, QPalette::ButtonText);
- }
- }
- break;
- case CE_MenuBarEmptyArea:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- HIThemeMenuBarDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = kThemeMenuBarNormal;
- bdi.attributes = 0;
- HIRect hirect = qt_hirectForQRect(mi->rect);
- HIThemeDrawMenuBarBackground(&hirect, &bdi, cg,
- kHIThemeOrientationNormal);
- break;
- }
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- HIThemeTrackDrawInfo tdi;
- tdi.version = qt_mac_hitheme_version;
- tdi.reserved = 0;
- bool isIndeterminate = (pb->minimum == 0 && pb->maximum == 0);
- bool vertical = false;
- bool inverted = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- vertical = (pb2->orientation == Qt::Vertical);
- inverted = pb2->invertedAppearance;
- }
- bool reverse = (!vertical && (pb->direction == Qt::RightToLeft));
- if (inverted)
- reverse = !reverse;
- switch (d->aquaSizeConstrain(opt, w)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- tdi.kind = !isIndeterminate ? kThemeLargeProgressBar
- : kThemeLargeIndeterminateBar;
- break;
- case QAquaSizeMini:
- case QAquaSizeSmall:
- tdi.kind = !isIndeterminate ? kThemeProgressBar : kThemeIndeterminateBar;
- break;
- }
- tdi.bounds = qt_hirectForQRect(pb->rect);
- tdi.max = pb->maximum;
- tdi.min = pb->minimum;
- tdi.value = pb->progress;
- tdi.attributes = vertical ? 0 : kThemeTrackHorizontal;
- tdi.trackInfo.progress.phase = d->progressFrame;
- if (!(pb->state & State_Active))
- tdi.enableState = kThemeTrackInactive;
- else if (!(pb->state & State_Enabled))
- tdi.enableState = kThemeTrackDisabled;
- else
- tdi.enableState = kThemeTrackActive;
- HIThemeOrientation drawOrientation = kHIThemeOrientationNormal;
- if (reverse) {
- if (vertical) {
- drawOrientation = kHIThemeOrientationInverted;
- } else {
- CGContextSaveGState(cg);
- CGContextTranslateCTM(cg, pb->rect.width(), 0);
- CGContextScaleCTM(cg, -1, 1);
- }
- }
- HIThemeDrawTrack(&tdi, 0, cg, drawOrientation);
- if (reverse && !vertical)
- CGContextRestoreGState(cg);
- }
- break;
- case CE_ProgressBarLabel:
- case CE_ProgressBarGroove:
- break;
- case CE_SizeGrip: {
- if (w && w->testAttribute(Qt::WA_MacOpaqueSizeGrip)) {
- HIThemeGrowBoxDrawInfo gdi;
- gdi.version = qt_mac_hitheme_version;
- gdi.state = tds;
- gdi.kind = kHIThemeGrowBoxKindNormal;
- gdi.direction = kThemeGrowRight | kThemeGrowDown;
- gdi.size = kHIThemeGrowBoxSizeNormal;
- HIPoint pt = CGPointMake(opt->rect.x(), opt->rect.y());
- HIThemeDrawGrowBox(&pt, &gdi, cg, kHIThemeOrientationNormal);
- } else {
- // It isn't possible to draw a transparent size grip with the
- // native API, so we do it ourselves here.
- const bool metal = qt_mac_is_metal(w);
- QPen lineColor = metal ? QColor(236, 236, 236) : QColor(82, 82, 82, 192);
- QPen metalHighlight = QColor(5, 5, 5, 192);
- lineColor.setWidth(1);
- p->save();
- p->setRenderHint(QPainter::Antialiasing);
- p->setPen(lineColor);
- const Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : qApp->layoutDirection();
- const int NumLines = metal ? 4 : 3;
- for (int l = 0; l < NumLines; ++l) {
- const int offset = (l * 4 + (metal ? 2 : 3));
- QPoint start, end;
- if (layoutDirection == Qt::LeftToRight) {
- start = QPoint(opt->rect.width() - offset, opt->rect.height() - 1);
- end = QPoint(opt->rect.width() - 1, opt->rect.height() - offset);
- } else {
- start = QPoint(offset, opt->rect.height() - 1);
- end = QPoint(1, opt->rect.height() - offset);
- }
- p->drawLine(start, end);
- if (metal) {
- p->setPen(metalHighlight);
- p->setRenderHint(QPainter::Antialiasing, false);
- p->drawLine(start + QPoint(0, -1), end + QPoint(0, -1));
- p->setRenderHint(QPainter::Antialiasing, true);
- p->setPen(lineColor);
- }
- }
- p->restore();
- }
- break;
- }
- case CE_Splitter: {
- HIThemeSplitterDrawInfo sdi;
- sdi.version = qt_mac_hitheme_version;
- sdi.state = tds;
- sdi.adornment = qt_mac_is_metal(w) ? kHIThemeSplitterAdornmentMetal
- : kHIThemeSplitterAdornmentNone;
- HIRect hirect = qt_hirectForQRect(opt->rect);
- HIThemeDrawPaneSplitter(&hirect, &sdi, cg, kHIThemeOrientationNormal);
- break; }
- case CE_RubberBand:
- if (const QStyleOptionRubberBand *rubber = qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
- QColor fillColor(opt->palette.color(QPalette::Disabled, QPalette::Highlight));
- if (!rubber->opaque) {
- QColor strokeColor;
- // I retrieved these colors from the Carbon-Dev mailing list
- strokeColor.setHsvF(0, 0, 0.86, 1.0);
- fillColor.setHsvF(0, 0, 0.53, 0.25);
- if (opt->rect.width() * opt->rect.height() <= 3) {
- p->fillRect(opt->rect, strokeColor);
- } else {
- QPen oldPen = p->pen();
- QBrush oldBrush = p->brush();
- QPen pen(strokeColor);
- p->setPen(pen);
- p->setBrush(fillColor);
- p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
- p->setPen(oldPen);
- p->setBrush(oldBrush);
- }
- } else {
- p->fillRect(opt->rect, fillColor);
- }
- }
- break;
- case CE_ToolBar: {
- // For unified tool bars, draw nothing.
- if (w) {
- if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(w->window())) {
- if (mainWindow->unifiedTitleAndToolBarOnMac())
- break;
- }
- }
-
- // draw background gradient
- QLinearGradient linearGrad;
- if (opt->state & State_Horizontal)
- linearGrad = QLinearGradient(0, opt->rect.top(), 0, opt->rect.bottom());
- else
- linearGrad = QLinearGradient(opt->rect.left(), 0, opt->rect.right(), 0);
-
- linearGrad.setColorAt(0, mainWindowGradientBegin);
- linearGrad.setColorAt(1, mainWindowGradientEnd);
- p->fillRect(opt->rect, linearGrad);
-
- p->save();
- if (opt->state & State_Horizontal) {
- p->setPen(mainWindowGradientBegin.lighter(114));
- p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
- p->setPen(mainWindowGradientEnd.darker(114));
- p->drawLine(opt->rect.bottomLeft(), opt->rect.bottomRight());
-
- } else {
- p->setPen(mainWindowGradientBegin.lighter(114));
- p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
- p->setPen(mainWindowGradientEnd.darker(114));
- p->drawLine(opt->rect.topRight(), opt->rect.bottomRight());
- }
- p->restore();
-
-
- } break;
- default:
- QWindowsStyle::drawControl(ce, opt, p, w);
- break;
- }
-}
-
-static void setLayoutItemMargins(int left, int top, int right, int bottom, QRect *rect, Qt::LayoutDirection dir)
-{
- if (dir == Qt::RightToLeft) {
- rect->adjust(-right, top, -left, bottom);
- } else {
- rect->adjust(left, top, right, bottom);
- }
-}
-
-QRect QMacStyle::subElementRect(SubElement sr, const QStyleOption *opt,
- const QWidget *widget) const
-{
- QRect rect;
- int controlSize = getControlSize(opt, widget);
-
- switch (sr) {
- case SE_ItemViewItemText:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- int fw = proxy()->pixelMetric(PM_FocusFrameHMargin, opt, widget);
- // We add the focusframeargin between icon and text in commonstyle
- rect = QCommonStyle::subElementRect(sr, opt, widget);
- if (vopt->features & QStyleOptionViewItemV2::HasDecoration)
- rect.adjust(-fw, 0, 0, 0);
- }
- break;
- case SE_ToolBoxTabContents:
- rect = QCommonStyle::subElementRect(sr, opt, widget);
- break;
- case SE_PushButtonContents:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- // Unlike Carbon, we want the button to always be drawn inside its bounds.
- // Therefore, the button is a bit smaller, so that even if it got focus,
- // the focus 'shadow' will be inside. Adjust the content rect likewise.
- HIThemeButtonDrawInfo bdi;
- d->initHIThemePushButton(btn, widget, d->getDrawState(opt->state), &bdi);
- HIRect contentRect = d->pushButtonContentBounds(btn, &bdi);
- rect = qt_qrectForHIRect(contentRect);
- }
- break;
- case SE_HeaderLabel:
- if (qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- rect = QWindowsStyle::subElementRect(sr, opt, widget);
- if (widget && widget->height() <= 22){
- // We need to allow the text a bit more space when the header is
- // small, otherwise it gets clipped:
- rect.setY(0);
- rect.setHeight(widget->height());
- }
- }
- break;
- case SE_ProgressBarGroove:
- case SE_ProgressBarLabel:
- break;
- case SE_ProgressBarContents:
- rect = opt->rect;
- break;
- case SE_TreeViewDisclosureItem: {
- HIRect inRect = CGRectMake(opt->rect.x(), opt->rect.y(),
- opt->rect.width(), opt->rect.height());
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = kThemeStateActive;
- bdi.kind = kThemeDisclosureButton;
- bdi.value = kThemeDisclosureRight;
- bdi.adornment = kThemeAdornmentNone;
- HIRect contentRect;
- HIThemeGetButtonContentBounds(&inRect, &bdi, &contentRect);
- QCFType<HIShapeRef> shape;
- HIRect outRect;
- HIThemeGetButtonShape(&inRect, &bdi, &shape);
- ptrHIShapeGetBounds(shape, &outRect);
- rect = QRect(int(outRect.origin.x + DisclosureOffset), int(outRect.origin.y),
- int(contentRect.origin.x - outRect.origin.x + DisclosureOffset),
- int(outRect.size.height));
- break;
- }
- case SE_TabWidgetLeftCorner:
- if (const QStyleOptionTabWidgetFrame *twf
- = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- rect = QRect(QPoint(0, 0), twf->leftCornerWidgetSize);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- rect = QRect(QPoint(0, twf->rect.height() - twf->leftCornerWidgetSize.height()),
- twf->leftCornerWidgetSize);
- break;
- default:
- break;
- }
- rect = visualRect(twf->direction, twf->rect, rect);
- }
- break;
- case SE_TabWidgetRightCorner:
- if (const QStyleOptionTabWidgetFrame *twf
- = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- rect = QRect(QPoint(twf->rect.width() - twf->rightCornerWidgetSize.width(), 0),
- twf->rightCornerWidgetSize);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- rect = QRect(QPoint(twf->rect.width() - twf->rightCornerWidgetSize.width(),
- twf->rect.height() - twf->rightCornerWidgetSize.height()),
- twf->rightCornerWidgetSize);
- break;
- default:
- break;
- }
- rect = visualRect(twf->direction, twf->rect, rect);
- }
- break;
- case SE_TabWidgetTabContents:
- rect = QWindowsStyle::subElementRect(sr, opt, widget);
- if (const QStyleOptionTabWidgetFrame *twf
- = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- if (twf->lineWidth != 0) {
- switch (getTabDirection(twf->shape)) {
- case kThemeTabNorth:
- rect.adjust(+1, +14, -1, -1);
- break;
- case kThemeTabSouth:
- rect.adjust(+1, +1, -1, -14);
- break;
- case kThemeTabWest:
- rect.adjust(+14, +1, -1, -1);
- break;
- case kThemeTabEast:
- rect.adjust(+1, +1, -14, -1);
- }
- }
- }
- break;
- case SE_LineEditContents:
- rect = QWindowsStyle::subElementRect(sr, opt, widget);
- if(widget->parentWidget() && qobject_cast<const QComboBox*>(widget->parentWidget()))
- rect.adjust(-1, -2, 0, 0);
- else
- rect.adjust(-1, 0, 0, +1);
- break;
- case SE_CheckBoxLayoutItem:
- rect = opt->rect;
- if (controlSize == QAquaSizeLarge) {
- setLayoutItemMargins(+2, +3, -9, -4, &rect, opt->direction);
- } else if (controlSize == QAquaSizeSmall) {
- setLayoutItemMargins(+1, +5, 0 /* fix */, -6, &rect, opt->direction);
- } else {
- setLayoutItemMargins(0, +7, 0 /* fix */, -6, &rect, opt->direction);
- }
- break;
- case SE_ComboBoxLayoutItem:
- if (widget && qobject_cast<QToolBar *>(widget->parentWidget())) {
- // Do nothing, because QToolbar needs the entire widget rect.
- // Otherwise it will be clipped. Equivalent to
- // widget->setAttribute(Qt::WA_LayoutUsesWidgetRect), but without
- // all the hassle.
- } else {
- rect = opt->rect;
- if (controlSize == QAquaSizeLarge) {
- rect.adjust(+3, +2, -3, -4);
- } else if (controlSize == QAquaSizeSmall) {
- setLayoutItemMargins(+2, +1, -3, -4, &rect, opt->direction);
- } else {
- setLayoutItemMargins(+1, 0, -2, 0, &rect, opt->direction);
- }
- }
- break;
- case SE_LabelLayoutItem:
- rect = opt->rect;
- setLayoutItemMargins(+1, 0 /* SHOULD be -1, done for alignment */, 0, 0 /* SHOULD be -1, done for alignment */, &rect, opt->direction);
- break;
- case SE_ProgressBarLayoutItem: {
- rect = opt->rect;
- int bottom = SIZE(3, 8, 8);
- if (opt->state & State_Horizontal) {
- rect.adjust(0, +1, 0, -bottom);
- } else {
- setLayoutItemMargins(+1, 0, -bottom, 0, &rect, opt->direction);
- }
- break;
- }
- case SE_PushButtonLayoutItem:
- if (const QStyleOptionButton *buttonOpt
- = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if ((buttonOpt->features & QStyleOptionButton::Flat))
- break; // leave rect alone
- }
- rect = opt->rect;
- if (controlSize == QAquaSizeLarge) {
- rect.adjust(+6, +4, -6, -8);
- } else if (controlSize == QAquaSizeSmall) {
- rect.adjust(+5, +4, -5, -6);
- } else {
- rect.adjust(+1, 0, -1, -2);
- }
- break;
- case SE_RadioButtonLayoutItem:
- rect = opt->rect;
- if (controlSize == QAquaSizeLarge) {
- setLayoutItemMargins(+2, +2 /* SHOULD BE +3, done for alignment */,
- 0, -4 /* SHOULD BE -3, done for alignment */, &rect, opt->direction);
- } else if (controlSize == QAquaSizeSmall) {
- rect.adjust(0, +6, 0 /* fix */, -5);
- } else {
- rect.adjust(0, +6, 0 /* fix */, -7);
- }
- break;
- case SE_SliderLayoutItem:
- if (const QStyleOptionSlider *sliderOpt
- = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- rect = opt->rect;
- if (sliderOpt->tickPosition == QSlider::NoTicks) {
- int above = SIZE(3, 0, 2);
- int below = SIZE(4, 3, 0);
- if (sliderOpt->orientation == Qt::Horizontal) {
- rect.adjust(0, +above, 0, -below);
- } else {
- rect.adjust(+above, 0, -below, 0); //### Seems that QSlider flip the position of the ticks in reverse mode.
- }
- } else if (sliderOpt->tickPosition == QSlider::TicksAbove) {
- int below = SIZE(3, 2, 0);
- if (sliderOpt->orientation == Qt::Horizontal) {
- rect.setHeight(rect.height() - below);
- } else {
- rect.setWidth(rect.width() - below);
- }
- } else if (sliderOpt->tickPosition == QSlider::TicksBelow) {
- int above = SIZE(3, 2, 0);
- if (sliderOpt->orientation == Qt::Horizontal) {
- rect.setTop(rect.top() + above);
- } else {
- rect.setLeft(rect.left() + above);
- }
- }
- }
- break;
- case SE_FrameLayoutItem:
- // hack because QStyleOptionFrameV2 doesn't have a frameStyle member
- if (const QFrame *frame = qobject_cast<const QFrame *>(widget)) {
- rect = opt->rect;
- switch (frame->frameStyle() & QFrame::Shape_Mask) {
- case QFrame::HLine:
- rect.adjust(0, +1, 0, -1);
- break;
- case QFrame::VLine:
- rect.adjust(+1, 0, -1, 0);
- break;
- default:
- ;
- }
- }
- break;
- case SE_GroupBoxLayoutItem:
- rect = opt->rect;
- if (const QStyleOptionGroupBox *groupBoxOpt =
- qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- /*
- AHIG is very inconsistent when it comes to group boxes.
- Basically, we make sure that (non-checkable) group boxes
- and tab widgets look good when laid out side by side.
- */
- if (groupBoxOpt->subControls & (QStyle::SC_GroupBoxCheckBox
- | QStyle::SC_GroupBoxLabel)) {
- int delta;
- if (groupBoxOpt->subControls & QStyle::SC_GroupBoxCheckBox) {
- delta = SIZE(8, 4, 4); // guess
- } else {
- delta = SIZE(15, 12, 12); // guess
- }
- rect.setTop(rect.top() + delta);
- }
- }
- rect.setBottom(rect.bottom() - 1);
- break;
- case SE_TabWidgetLayoutItem:
- if (const QStyleOptionTabWidgetFrame *tabWidgetOpt =
- qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- /*
- AHIG specifies "12 or 14" as the distance from the window
- edge. We choose 14 and since the default top margin is 20,
- the overlap is 6.
- */
- rect = tabWidgetOpt->rect;
- if (tabWidgetOpt->shape == QTabBar::RoundedNorth)
- rect.setTop(rect.top() + SIZE(6 /* AHIG */, 3 /* guess */, 2 /* AHIG */));
- }
- break;
- default:
- rect = QWindowsStyle::subElementRect(sr, opt, widget);
- break;
- }
- return rect;
-}
-
-static inline void drawToolbarButtonArrow(const QRect &toolButtonRect, ThemeDrawState tds, CGContextRef cg)
-{
- QRect arrowRect = QRect(toolButtonRect.right() - 9, toolButtonRect.bottom() - 9, 7, 5);
- HIThemePopupArrowDrawInfo padi;
- padi.version = qt_mac_hitheme_version;
- padi.state = tds;
- padi.orientation = kThemeArrowDown;
- padi.size = kThemeArrow7pt;
- HIRect hirect = qt_hirectForQRect(arrowRect);
- HIThemeDrawPopupArrow(&hirect, &padi, cg, kHIThemeOrientationNormal);
-}
-
-void QMacStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *widget) const
-{
- ThemeDrawState tds = d->getDrawState(opt->state);
- QMacCGContext cg(p);
- switch (cc) {
- case CC_Slider:
- case CC_ScrollBar:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- HIThemeTrackDrawInfo tdi;
- d->getSliderInfo(cc, slider, &tdi, widget);
- if (slider->state & State_Sunken) {
- if (cc == CC_Slider) {
- if (slider->activeSubControls == SC_SliderHandle)
- tdi.trackInfo.slider.pressState = kThemeThumbPressed;
- else if (slider->activeSubControls == SC_SliderGroove)
- tdi.trackInfo.slider.pressState = kThemeLeftTrackPressed;
- } else {
- if (slider->activeSubControls == SC_ScrollBarSubLine
- || slider->activeSubControls == SC_ScrollBarAddLine) {
- // This test looks complex but it basically boils down
- // to the following: The "RTL look" on the mac also
- // changed the directions of the controls, that's not
- // what people expect (an arrow is an arrow), so we
- // kind of fake and say the opposite button is hit.
- // This works great, up until 10.4 which broke the
- // scroll bars, so I also have actually do something
- // similar when I have an upside down scroll bar
- // because on Tiger I only "fake" the reverse stuff.
- bool reverseHorizontal = (slider->direction == Qt::RightToLeft
- && slider->orientation == Qt::Horizontal);
- if ((reverseHorizontal
- && slider->activeSubControls == SC_ScrollBarAddLine)
- || (!reverseHorizontal
- && slider->activeSubControls == SC_ScrollBarSubLine)) {
- tdi.trackInfo.scrollbar.pressState = kThemeRightInsideArrowPressed
- | kThemeLeftOutsideArrowPressed;
- } else {
- tdi.trackInfo.scrollbar.pressState = kThemeLeftInsideArrowPressed
- | kThemeRightOutsideArrowPressed;
- }
- } else if (slider->activeSubControls == SC_ScrollBarAddPage) {
- tdi.trackInfo.scrollbar.pressState = kThemeRightTrackPressed;
- } else if (slider->activeSubControls == SC_ScrollBarSubPage) {
- tdi.trackInfo.scrollbar.pressState = kThemeLeftTrackPressed;
- } else if (slider->activeSubControls == SC_ScrollBarSlider) {
- tdi.trackInfo.scrollbar.pressState = kThemeThumbPressed;
- }
- }
- }
- HIRect macRect;
- bool tracking = slider->sliderPosition == slider->sliderValue;
- if (!tracking) {
- // Small optimization, the same as q->subControlRect
- QCFType<HIShapeRef> shape;
- HIThemeGetTrackThumbShape(&tdi, &shape);
- ptrHIShapeGetBounds(shape, &macRect);
- tdi.value = slider->sliderValue;
- }
-
- // Remove controls from the scroll bar if it is to short to draw them correctly.
- // This is done in two stages: first the thumb indicator is removed when it is
- // no longer possible to move it, second the up/down buttons are removed when
- // there is not enough space for them.
- if (cc == CC_ScrollBar) {
- const int scrollBarLength = (slider->orientation == Qt::Horizontal)
- ? slider->rect.width() : slider->rect.height();
- const QMacStyle::WidgetSizePolicy sizePolicy = widgetSizePolicy(widget);
- if (scrollBarLength < scrollButtonsCutoffSize(thumbIndicatorCutoff, sizePolicy))
- tdi.attributes &= ~kThemeTrackShowThumb;
- if (scrollBarLength < scrollButtonsCutoffSize(scrollButtonsCutoff, sizePolicy))
- tdi.enableState = kThemeTrackNothingToScroll;
- } else {
- if (!(slider->subControls & SC_SliderHandle))
- tdi.attributes &= ~kThemeTrackShowThumb;
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
- if (!(slider->subControls & SC_SliderGroove))
- tdi.attributes |= kThemeTrackHideTrack;
-#endif
- }
-
- HIThemeDrawTrack(&tdi, tracking ? 0 : &macRect, cg,
- kHIThemeOrientationNormal);
- if (cc == CC_Slider && slider->subControls & SC_SliderTickmarks) {
- if (qt_mac_is_metal(widget)) {
- if (tdi.enableState == kThemeTrackInactive)
- tdi.enableState = kThemeTrackActive; // Looks more Cocoa-like
- }
- int interval = slider->tickInterval;
- if (interval == 0) {
- interval = slider->pageStep;
- if (interval == 0)
- interval = slider->singleStep;
- if (interval == 0)
- interval = 1;
- }
- int numMarks = 1 + ((slider->maximum - slider->minimum) / interval);
-
- if (tdi.trackInfo.slider.thumbDir == kThemeThumbPlain) {
- // They asked for both, so we'll give it to them.
- tdi.trackInfo.slider.thumbDir = kThemeThumbDownward;
- HIThemeDrawTrackTickMarks(&tdi, numMarks,
- cg,
- kHIThemeOrientationNormal);
- tdi.trackInfo.slider.thumbDir = kThemeThumbUpward;
- HIThemeDrawTrackTickMarks(&tdi, numMarks,
- cg,
- kHIThemeOrientationNormal);
- } else {
- HIThemeDrawTrackTickMarks(&tdi, numMarks,
- cg,
- kHIThemeOrientationNormal);
-
- }
- }
- }
- break;
- case CC_Q3ListView:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- if (lv->subControls & SC_Q3ListView)
- QWindowsStyle::drawComplexControl(cc, lv, p, widget);
- if (lv->subControls & (SC_Q3ListViewBranch | SC_Q3ListViewExpand)) {
- int y = lv->rect.y();
- int h = lv->rect.height();
- int x = lv->rect.right() - 10;
- for (int i = 1; i < lv->items.size() && y < h; ++i) {
- QStyleOptionQ3ListViewItem item = lv->items.at(i);
- if (y + item.height > 0 && (item.childCount > 0
- || (item.features & (QStyleOptionQ3ListViewItem::Expandable
- | QStyleOptionQ3ListViewItem::Visible))
- == (QStyleOptionQ3ListViewItem::Expandable
- | QStyleOptionQ3ListViewItem::Visible))) {
- QStyleOption treeOpt(0);
- treeOpt.rect.setRect(x, y + item.height / 2 - 4, 9, 9);
- treeOpt.palette = lv->palette;
- treeOpt.state = lv->state;
- treeOpt.state |= State_Children;
- if (item.state & State_Open)
- treeOpt.state |= State_Open;
- proxy()->drawPrimitive(PE_IndicatorBranch, &treeOpt, p, widget);
- }
- y += item.totalHeight;
- }
- }
- }
- break;
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QStyleOptionSpinBox newSB = *sb;
- if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
- SInt32 frame_size;
- GetThemeMetric(kThemeMetricEditTextFrameOutset, &frame_size);
-
- QRect lineeditRect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxEditField, widget);
- lineeditRect.adjust(-frame_size, -frame_size, +frame_size, +frame_size);
-
- HIThemeFrameDrawInfo fdi;
- fdi.version = qt_mac_hitheme_version;
- fdi.state = kThemeStateInactive;
- fdi.kind = kHIThemeFrameTextFieldSquare;
- fdi.isFocused = false;
- HIRect hirect = qt_hirectForQRect(lineeditRect);
- HIThemeDrawFrame(&hirect, &fdi, cg, kHIThemeOrientationNormal);
- }
- if (sb->subControls & (SC_SpinBoxUp | SC_SpinBoxDown)) {
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- QAquaWidgetSize aquaSize = d->aquaSizeConstrain(opt, widget);
- switch (aquaSize) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- bdi.kind = kThemeIncDecButton;
- break;
- case QAquaSizeMini:
- bdi.kind = kThemeIncDecButtonMini;
- break;
- case QAquaSizeSmall:
- bdi.kind = kThemeIncDecButtonSmall;
- break;
- }
- if (!(sb->stepEnabled & (QAbstractSpinBox::StepUpEnabled
- | QAbstractSpinBox::StepDownEnabled)))
- tds = kThemeStateUnavailable;
- if (sb->activeSubControls == SC_SpinBoxDown
- && (sb->state & State_Sunken))
- tds = kThemeStatePressedDown;
- else if (sb->activeSubControls == SC_SpinBoxUp
- && (sb->state & State_Sunken))
- tds = kThemeStatePressedUp;
- bdi.state = tds;
- if (!(sb->state & State_Active)
- && sb->palette.currentColorGroup() == QPalette::Active
- && tds == kThemeStateInactive)
- bdi.state = kThemeStateActive;
- bdi.value = kThemeButtonOff;
- bdi.adornment = kThemeAdornmentNone;
-
- QRect updown = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxUp, widget);
-
- updown |= proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxDown, widget);
- HIRect newRect = qt_hirectForQRect(updown);
- QRect off_rct;
- HIRect outRect;
- HIThemeGetButtonBackgroundBounds(&newRect, &bdi, &outRect);
- off_rct.setRect(int(newRect.origin.x - outRect.origin.x),
- int(newRect.origin.y - outRect.origin.y),
- int(outRect.size.width - newRect.size.width),
- int(outRect.size.height - newRect.size.height));
-
- newRect = qt_hirectForQRect(updown, off_rct);
- HIThemeDrawButton(&newRect, &bdi, cg, kHIThemeOrientationNormal, 0);
- }
- }
- break;
- case CC_ComboBox:
- if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)){
- HIThemeButtonDrawInfo bdi;
- d->initComboboxBdi(combo, &bdi, widget, d->getDrawState(opt->state));
- bool drawColorless = combo->palette.currentColorGroup() == QPalette::Active && tds == kThemeStateInactive;
- if (!drawColorless)
- QMacStylePrivate::drawCombobox(qt_hirectForQRect(combo->rect), bdi, p);
- else
- d->drawColorlessButton(qt_hirectForQRect(combo->rect), &bdi, p, opt);
- }
- break;
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *titlebar
- = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- if (titlebar->state & State_Active) {
- if (titlebar->titleBarState & State_Active)
- tds = kThemeStateActive;
- else
- tds = kThemeStateInactive;
- } else {
- tds = kThemeStateInactive;
- }
-
- HIThemeWindowDrawInfo wdi;
- wdi.version = qt_mac_hitheme_version;
- wdi.state = tds;
- wdi.windowType = QtWinType;
- wdi.titleHeight = titlebar->rect.height();
- wdi.titleWidth = titlebar->rect.width();
- wdi.attributes = kThemeWindowHasTitleText;
- // It seems HIThemeDrawTitleBarWidget is not able to draw a dirty
- // close button, so use HIThemeDrawWindowFrame instead.
- if (widget && widget->isWindowModified() && titlebar->subControls & SC_TitleBarCloseButton)
- wdi.attributes |= kThemeWindowHasCloseBox | kThemeWindowHasDirty;
-
- HIRect titleBarRect;
- HIRect tmpRect = qt_hirectForQRect(titlebar->rect);
- {
- QCFType<HIShapeRef> titleRegion;
- QRect newr = titlebar->rect.adjusted(0, 0, 2, 0);
- HIThemeGetWindowShape(&tmpRect, &wdi, kWindowTitleBarRgn, &titleRegion);
- ptrHIShapeGetBounds(titleRegion, &tmpRect);
- newr.translate(newr.x() - int(tmpRect.origin.x), newr.y() - int(tmpRect.origin.y));
- titleBarRect = qt_hirectForQRect(newr);
- }
- HIThemeDrawWindowFrame(&titleBarRect, &wdi, cg, kHIThemeOrientationNormal, 0);
- if (titlebar->subControls & (SC_TitleBarCloseButton
- | SC_TitleBarMaxButton
- | SC_TitleBarMinButton
- | SC_TitleBarNormalButton)) {
- HIThemeWindowWidgetDrawInfo wwdi;
- wwdi.version = qt_mac_hitheme_version;
- wwdi.widgetState = tds;
- if (titlebar->state & State_MouseOver)
- wwdi.widgetState = kThemeStateRollover;
- wwdi.windowType = QtWinType;
- wwdi.attributes = wdi.attributes | kThemeWindowHasFullZoom | kThemeWindowHasCloseBox | kThemeWindowHasCollapseBox;
- wwdi.windowState = wdi.state;
- wwdi.titleHeight = wdi.titleHeight;
- wwdi.titleWidth = wdi.titleWidth;
- ThemeDrawState savedControlState = wwdi.widgetState;
- uint sc = SC_TitleBarMinButton;
- ThemeTitleBarWidget tbw = kThemeWidgetCollapseBox;
- bool active = titlebar->state & State_Active;
- if (qMacVersion() < QSysInfo::MV_10_6) {
- int border = 2;
- titleBarRect.origin.x += border;
- titleBarRect.origin.y -= border;
- }
-
- while (sc <= SC_TitleBarCloseButton) {
- if (sc & titlebar->subControls) {
- uint tmp = sc;
- wwdi.widgetState = savedControlState;
- wwdi.widgetType = tbw;
- if (sc == SC_TitleBarMinButton)
- tmp |= SC_TitleBarNormalButton;
- if (active && (titlebar->activeSubControls & tmp)
- && (titlebar->state & State_Sunken))
- wwdi.widgetState = kThemeStatePressed;
- // Draw all sub controllers except the dirty close button
- // (it is already handled by HIThemeDrawWindowFrame).
- if (!(widget && widget->isWindowModified() && tbw == kThemeWidgetCloseBox)) {
- HIThemeDrawTitleBarWidget(&titleBarRect, &wwdi, cg, kHIThemeOrientationNormal);
- p->paintEngine()->syncState();
- }
- }
- sc = sc << 1;
- tbw = tbw >> 1;
- }
- }
- p->paintEngine()->syncState();
- if (titlebar->subControls & SC_TitleBarLabel) {
- int iw = 0;
- if (!titlebar->icon.isNull()) {
- QCFType<HIShapeRef> titleRegion2;
- HIThemeGetWindowShape(&titleBarRect, &wdi, kWindowTitleProxyIconRgn,
- &titleRegion2);
- ptrHIShapeGetBounds(titleRegion2, &tmpRect);
- if (tmpRect.size.width != 1) {
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
- iw = titlebar->icon.actualSize(QSize(iconExtent, iconExtent)).width();
- }
- }
- if (!titlebar->text.isEmpty()) {
- p->save();
- QCFType<HIShapeRef> titleRegion3;
- HIThemeGetWindowShape(&titleBarRect, &wdi, kWindowTitleTextRgn, &titleRegion3);
- ptrHIShapeGetBounds(titleRegion3, &tmpRect);
- p->setClipRect(qt_qrectForHIRect(tmpRect));
- QRect br = p->clipRegion().boundingRect();
- int x = br.x(),
- y = br.y() + (titlebar->rect.height() / 2 - p->fontMetrics().height() / 2);
- if (br.width() <= (p->fontMetrics().width(titlebar->text) + iw * 2))
- x += iw;
- else
- x += br.width() / 2 - p->fontMetrics().width(titlebar->text) / 2;
- if (iw)
- p->drawPixmap(x - iw, y,
- titlebar->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize), QIcon::Normal));
- drawItemText(p, br, Qt::AlignCenter, opt->palette, tds == kThemeStateActive,
- titlebar->text, QPalette::Text);
- p->restore();
- }
- }
- }
- break;
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox
- = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
-
- QStyleOptionGroupBox groupBoxCopy(*groupBox);
- if ((widget && !widget->testAttribute(Qt::WA_SetFont))
- && QApplication::desktopSettingsAware())
- groupBoxCopy.subControls = groupBoxCopy.subControls & ~SC_GroupBoxLabel;
- QWindowsStyle::drawComplexControl(cc, &groupBoxCopy, p, widget);
- if (groupBoxCopy.subControls != groupBox->subControls) {
- bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
- p->save();
- CGContextSetShouldAntialias(cg, true);
- CGContextSetShouldSmoothFonts(cg, true);
- HIThemeTextInfo tti;
- tti.version = qt_mac_hitheme_version;
- tti.state = tds;
- QColor textColor = groupBox->palette.windowText().color();
- CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
- textColor.blueF(), textColor.alphaF() };
- CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
- CGContextSetFillColor(cg, colorComp);
- tti.fontID = checkable ? kThemeSystemFont : kThemeSmallSystemFont;
- tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
- tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
- tti.options = kHIThemeTextBoxOptionNone;
- tti.truncationPosition = kHIThemeTextTruncationNone;
- tti.truncationMaxLines = 1 + groupBox->text.count(QLatin1Char('\n'));
- QCFString groupText = qt_mac_removeMnemonics(groupBox->text);
- QRect r = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxLabel, widget);
- HIRect bounds = qt_hirectForQRect(r);
- HIThemeDrawTextBox(groupText, &bounds, &tti, cg, kHIThemeOrientationNormal);
- p->restore();
- }
- }
- break;
- case CC_ToolButton:
- if (const QStyleOptionToolButton *tb
- = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- if (widget && qobject_cast<QToolBar *>(widget->parentWidget())) {
- if (tb->subControls & SC_ToolButtonMenu) {
- QStyleOption arrowOpt(0);
- arrowOpt.rect = proxy()->subControlRect(cc, tb, SC_ToolButtonMenu, widget);
- arrowOpt.rect.setY(arrowOpt.rect.y() + arrowOpt.rect.height() / 2);
- arrowOpt.rect.setHeight(arrowOpt.rect.height() / 2);
- arrowOpt.state = tb->state;
- arrowOpt.palette = tb->palette;
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, widget);
- } else if ((tb->features & QStyleOptionToolButton::HasMenu)
- && (tb->toolButtonStyle != Qt::ToolButtonTextOnly && !tb->icon.isNull())) {
- drawToolbarButtonArrow(tb->rect, tds, cg);
- }
- if (tb->state & State_On) {
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- static QPixmap pm(QLatin1String(":/trolltech/mac/style/images/leopard-unified-toolbar-on.png"));
- p->setRenderHint(QPainter::SmoothPixmapTransform);
- QStyleHelper::drawBorderPixmap(pm, p, tb->rect, 2, 2, 2, 2);
- } else {
- QPen oldPen = p->pen();
- p->setPen(QColor(0, 0, 0, 0x3a));
- p->fillRect(tb->rect.adjusted(1, 1, -1, -1), QColor(0, 0, 0, 0x12));
- p->drawLine(tb->rect.left() + 1, tb->rect.top(),
- tb->rect.right() - 1, tb->rect.top());
- p->drawLine(tb->rect.left() + 1, tb->rect.bottom(),
- tb->rect.right() - 1, tb->rect.bottom());
- p->drawLine(tb->rect.topLeft(), tb->rect.bottomLeft());
- p->drawLine(tb->rect.topRight(), tb->rect.bottomRight());
- p->setPen(oldPen);
- }
- }
- proxy()->drawControl(CE_ToolButtonLabel, opt, p, widget);
- } else {
- ThemeButtonKind bkind = kThemeBevelButton;
- switch (d->aquaSizeConstrain(opt, widget)) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- bkind = kThemeBevelButton;
- break;
- case QAquaSizeMini:
- case QAquaSizeSmall:
- bkind = kThemeSmallBevelButton;
- break;
- }
-
- QRect button, menuarea;
- button = proxy()->subControlRect(cc, tb, SC_ToolButton, widget);
- menuarea = proxy()->subControlRect(cc, tb, SC_ToolButtonMenu, widget);
- State bflags = tb->state,
- mflags = tb->state;
- if (tb->subControls & SC_ToolButton)
- bflags |= State_Sunken;
- if (tb->subControls & SC_ToolButtonMenu)
- mflags |= State_Sunken;
-
- if (tb->subControls & SC_ToolButton) {
- if (bflags & (State_Sunken | State_On | State_Raised)) {
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = tds;
- bdi.adornment = kThemeAdornmentNone;
- bdi.kind = bkind;
- bdi.value = kThemeButtonOff;
- if (tb->state & State_HasFocus)
- bdi.adornment = kThemeAdornmentFocus;
- if (tb->state & State_Sunken)
- bdi.state = kThemeStatePressed;
- if (tb->state & State_On)
- bdi.value = kThemeButtonOn;
-
- QRect off_rct(0, 0, 0, 0);
- HIRect myRect, macRect;
- myRect = CGRectMake(tb->rect.x(), tb->rect.y(),
- tb->rect.width(), tb->rect.height());
- HIThemeGetButtonBackgroundBounds(&myRect, &bdi, &macRect);
- off_rct.setRect(int(myRect.origin.x - macRect.origin.x),
- int(myRect.origin.y - macRect.origin.y),
- int(macRect.size.width - myRect.size.width),
- int(macRect.size.height - myRect.size.height));
-
- myRect = qt_hirectForQRect(button, off_rct);
- HIThemeDrawButton(&myRect, &bdi, cg, kHIThemeOrientationNormal, 0);
- }
- }
-
- if (tb->subControls & SC_ToolButtonMenu) {
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = tds;
- bdi.value = kThemeButtonOff;
- bdi.adornment = kThemeAdornmentNone;
- bdi.kind = bkind;
- if (tb->state & State_HasFocus)
- bdi.adornment = kThemeAdornmentFocus;
- if (tb->state & (State_On | State_Sunken)
- || (tb->activeSubControls & SC_ToolButtonMenu))
- bdi.state = kThemeStatePressed;
- HIRect hirect = qt_hirectForQRect(menuarea);
- HIThemeDrawButton(&hirect, &bdi, cg, kHIThemeOrientationNormal, 0);
- QRect r(menuarea.x() + ((menuarea.width() / 2) - 3), menuarea.height() - 8, 8, 8);
- HIThemePopupArrowDrawInfo padi;
- padi.version = qt_mac_hitheme_version;
- padi.state = tds;
- padi.orientation = kThemeArrowDown;
- padi.size = kThemeArrow7pt;
- hirect = qt_hirectForQRect(r);
- HIThemeDrawPopupArrow(&hirect, &padi, cg, kHIThemeOrientationNormal);
- } else if (tb->features & QStyleOptionToolButton::HasMenu) {
- drawToolbarButtonArrow(tb->rect, tds, cg);
- }
- QRect buttonRect = proxy()->subControlRect(CC_ToolButton, tb, SC_ToolButton, widget);
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- QStyleOptionToolButton label = *tb;
- label.rect = buttonRect.adjusted(fw, fw, -fw, -fw);
- proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget);
- }
- }
- break;
- case CC_Dial:
- if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt))
- QStyleHelper::drawDial(dial, p);
- break;
- default:
- QWindowsStyle::drawComplexControl(cc, opt, p, widget);
- break;
- }
-}
-
-QStyle::SubControl QMacStyle::hitTestComplexControl(ComplexControl cc,
- const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *widget) const
-{
- SubControl sc = QStyle::SC_None;
- switch (cc) {
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- sc = QWindowsStyle::hitTestComplexControl(cc, cmb, pt, widget);
- if (!cmb->editable && sc != QStyle::SC_None)
- sc = SC_ComboBoxArrow; // A bit of a lie, but what we want
- }
- break;
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- HIThemeTrackDrawInfo tdi;
- d->getSliderInfo(cc, slider, &tdi, widget);
- ControlPartCode part;
- HIPoint pos = CGPointMake(pt.x(), pt.y());
- if (HIThemeHitTestTrack(&tdi, &pos, &part)) {
- if (part == kControlPageUpPart || part == kControlPageDownPart)
- sc = SC_SliderGroove;
- else
- sc = SC_SliderHandle;
- }
- }
- break;
- case CC_ScrollBar:
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- HIScrollBarTrackInfo sbi;
- sbi.version = qt_mac_hitheme_version;
- if (!(sb->state & State_Active))
- sbi.enableState = kThemeTrackInactive;
- else if (sb->state & State_Enabled)
- sbi.enableState = kThemeTrackActive;
- else
- sbi.enableState = kThemeTrackDisabled;
-
- // The arrow buttons are not drawn if the scroll bar is to short,
- // exclude them from the hit test.
- const int scrollBarLength = (sb->orientation == Qt::Horizontal)
- ? sb->rect.width() : sb->rect.height();
- if (scrollBarLength < scrollButtonsCutoffSize(scrollButtonsCutoff, widgetSizePolicy(widget)))
- sbi.enableState = kThemeTrackNothingToScroll;
-
- sbi.viewsize = sb->pageStep;
- HIPoint pos = CGPointMake(pt.x(), pt.y());
-
- HIRect macSBRect = qt_hirectForQRect(sb->rect);
- ControlPartCode part;
- bool reverseHorizontal = (sb->direction == Qt::RightToLeft
- && sb->orientation == Qt::Horizontal
- && (!sb->upsideDown ||
- (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4
- && sb->upsideDown)));
- if (HIThemeHitTestScrollBarArrows(&macSBRect, &sbi, sb->orientation == Qt::Horizontal,
- &pos, 0, &part)) {
- if (part == kControlUpButtonPart)
- sc = reverseHorizontal ? SC_ScrollBarAddLine : SC_ScrollBarSubLine;
- else if (part == kControlDownButtonPart)
- sc = reverseHorizontal ? SC_ScrollBarSubLine : SC_ScrollBarAddLine;
- } else {
- HIThemeTrackDrawInfo tdi;
- d->getSliderInfo(cc, sb, &tdi, widget);
- if(tdi.enableState == kThemeTrackInactive)
- tdi.enableState = kThemeTrackActive;
- if (HIThemeHitTestTrack(&tdi, &pos, &part)) {
- if (part == kControlPageUpPart)
- sc = reverseHorizontal ? SC_ScrollBarAddPage
- : SC_ScrollBarSubPage;
- else if (part == kControlPageDownPart)
- sc = reverseHorizontal ? SC_ScrollBarSubPage
- : SC_ScrollBarAddPage;
- else
- sc = SC_ScrollBarSlider;
- }
- }
- }
- break;
-/*
- I don't know why, but we only get kWindowContentRgn here, which isn't what we want at all.
- It would be very nice if this would work.
- case QStyle::CC_TitleBar:
- if (const QStyleOptionTitleBar *tbar = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- HIThemeWindowDrawInfo wdi;
- memset(&wdi, 0, sizeof(wdi));
- wdi.version = qt_mac_hitheme_version;
- wdi.state = kThemeStateActive;
- wdi.windowType = QtWinType;
- wdi.titleWidth = tbar->rect.width();
- wdi.titleHeight = tbar->rect.height();
- if (tbar->titleBarState)
- wdi.attributes |= kThemeWindowHasFullZoom | kThemeWindowHasCloseBox
- | kThemeWindowHasCollapseBox;
- else if (tbar->titleBarFlags & Qt::WindowSystemMenuHint)
- wdi.attributes |= kThemeWindowHasCloseBox;
- QRect tmpRect = tbar->rect;
- tmpRect.setHeight(tmpRect.height() + 100);
- HIRect hirect = qt_hirectForQRect(tmpRect);
- WindowRegionCode hit;
- HIPoint hipt = CGPointMake(pt.x(), pt.y());
- if (HIThemeGetWindowRegionHit(&hirect, &wdi, &hipt, &hit)) {
- switch (hit) {
- case kWindowCloseBoxRgn:
- sc = QStyle::SC_TitleBarCloseButton;
- break;
- case kWindowCollapseBoxRgn:
- sc = QStyle::SC_TitleBarMinButton;
- break;
- case kWindowZoomBoxRgn:
- sc = QStyle::SC_TitleBarMaxButton;
- break;
- case kWindowTitleTextRgn:
- sc = QStyle::SC_TitleBarLabel;
- break;
- default:
- qDebug("got something else %d", hit);
- break;
- }
- }
- }
- break;
-*/
- default:
- sc = QWindowsStyle::hitTestComplexControl(cc, opt, pt, widget);
- break;
- }
- return sc;
-}
-
-QRect QMacStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *widget) const
-{
- QRect ret;
- switch (cc) {
- case CC_Slider:
- case CC_ScrollBar:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- HIThemeTrackDrawInfo tdi;
- d->getSliderInfo(cc, slider, &tdi, widget);
- HIRect macRect;
- QCFType<HIShapeRef> shape;
- bool scrollBar = cc == CC_ScrollBar;
- if ((scrollBar && sc == SC_ScrollBarSlider)
- || (!scrollBar && sc == SC_SliderHandle)) {
- HIThemeGetTrackThumbShape(&tdi, &shape);
- ptrHIShapeGetBounds(shape, &macRect);
- } else if (!scrollBar && sc == SC_SliderGroove) {
- HIThemeGetTrackBounds(&tdi, &macRect);
- } else if (sc == SC_ScrollBarGroove) { // Only scroll bar parts available...
- HIThemeGetTrackDragRect(&tdi, &macRect);
- } else {
- ControlPartCode cpc;
- if (sc == SC_ScrollBarSubPage || sc == SC_ScrollBarAddPage) {
- cpc = sc == SC_ScrollBarSubPage ? kControlPageDownPart
- : kControlPageUpPart;
- } else {
- cpc = sc == SC_ScrollBarSubLine ? kControlUpButtonPart
- : kControlDownButtonPart;
- if (slider->direction == Qt::RightToLeft
- && slider->orientation == Qt::Horizontal) {
- if (cpc == kControlDownButtonPart)
- cpc = kControlUpButtonPart;
- else if (cpc == kControlUpButtonPart)
- cpc = kControlDownButtonPart;
- }
- }
- HIThemeGetTrackPartBounds(&tdi, cpc, &macRect);
- }
- ret = qt_qrectForHIRect(macRect);
-
- // Tweak: the dark line between the sub/add line buttons belong to only one of the buttons
- // when doing hit-testing, but both of them have to repaint it. Extend the rect to cover
- // the line in the cases where HIThemeGetTrackPartBounds returns a rect that doesn't.
- if (slider->orientation == Qt::Horizontal) {
- if (slider->direction == Qt::LeftToRight && sc == SC_ScrollBarSubLine)
- ret.adjust(0, 0, 1, 0);
- else if (slider->direction == Qt::RightToLeft && sc == SC_ScrollBarAddLine)
- ret.adjust(-1, 0, 1, 0);
- } else if (sc == SC_ScrollBarAddLine) {
- ret.adjust(0, -1, 0, 1);
- }
- }
- break;
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *titlebar
- = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- HIThemeWindowDrawInfo wdi;
- memset(&wdi, 0, sizeof(wdi));
- wdi.version = qt_mac_hitheme_version;
- wdi.state = kThemeStateActive;
- wdi.windowType = QtWinType;
- wdi.titleHeight = titlebar->rect.height();
- wdi.titleWidth = titlebar->rect.width();
- wdi.attributes = kThemeWindowHasTitleText;
- if (titlebar->subControls & SC_TitleBarCloseButton)
- wdi.attributes |= kThemeWindowHasCloseBox;
- if (titlebar->subControls & SC_TitleBarMaxButton
- | SC_TitleBarNormalButton)
- wdi.attributes |= kThemeWindowHasFullZoom;
- if (titlebar->subControls & SC_TitleBarMinButton)
- wdi.attributes |= kThemeWindowHasCollapseBox;
- WindowRegionCode wrc = kWindowGlobalPortRgn;
-
- if (sc == SC_TitleBarCloseButton)
- wrc = kWindowCloseBoxRgn;
- else if (sc == SC_TitleBarMinButton)
- wrc = kWindowCollapseBoxRgn;
- else if (sc == SC_TitleBarMaxButton)
- wrc = kWindowZoomBoxRgn;
- else if (sc == SC_TitleBarLabel)
- wrc = kWindowTitleTextRgn;
- else if (sc == SC_TitleBarSysMenu)
- ret.setRect(-1024, -1024, 10, proxy()->pixelMetric(PM_TitleBarHeight,
- titlebar, widget));
- if (wrc != kWindowGlobalPortRgn) {
- QCFType<HIShapeRef> region;
- QRect tmpRect = titlebar->rect;
- HIRect titleRect = qt_hirectForQRect(tmpRect);
- HIThemeGetWindowShape(&titleRect, &wdi, kWindowTitleBarRgn, &region);
- ptrHIShapeGetBounds(region, &titleRect);
- CFRelease(region);
- tmpRect.translate(tmpRect.x() - int(titleRect.origin.x),
- tmpRect.y() - int(titleRect.origin.y));
- titleRect = qt_hirectForQRect(tmpRect);
- HIThemeGetWindowShape(&titleRect, &wdi, wrc, &region);
- ptrHIShapeGetBounds(region, &titleRect);
- ret = qt_qrectForHIRect(titleRect);
- }
- }
- break;
- case CC_ComboBox:
- if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- HIThemeButtonDrawInfo bdi;
- d->initComboboxBdi(combo, &bdi, widget, d->getDrawState(opt->state));
-
- switch (sc) {
- case SC_ComboBoxEditField:{
- ret = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
- // hack to posistion the edit feld correctly for QDateTimeEdits
- // in calendarPopup mode.
- if (qobject_cast<const QDateTimeEdit *>(widget)) {
- ret.moveTop(ret.top() - 2);
- ret.setHeight(ret.height() +1);
- }
- break; }
- case SC_ComboBoxArrow:{
- ret = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
- ret.setX(ret.x() + ret.width());
- ret.setWidth(combo->rect.right() - ret.right());
- break; }
- case SC_ComboBoxListBoxPopup:{
- if (combo->editable) {
- HIRect inner = QMacStylePrivate::comboboxInnerBounds(qt_hirectForQRect(combo->rect), bdi.kind);
- QRect editRect = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
- const int comboTop = combo->rect.top();
- ret = QRect(qRound(inner.origin.x),
- comboTop,
- qRound(inner.origin.x - combo->rect.left() + inner.size.width),
- editRect.bottom() - comboTop + 2);
- } else {
- QRect editRect = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
- ret = QRect(combo->rect.x() + 4 - 11,
- combo->rect.y() + 1,
- editRect.width() + 10 + 11,
- 1);
- }
- break; }
- default:
- break;
- }
- }
- break;
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
- bool flat = (groupBox->features & QStyleOptionFrameV2::Flat);
- bool hasNoText = !checkable && groupBox->text.isEmpty();
- switch (sc) {
- case SC_GroupBoxLabel:
- case SC_GroupBoxCheckBox: {
- // Cheat and use the smaller font if we need to
- bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
- bool fontIsSet = (widget && widget->testAttribute(Qt::WA_SetFont))
- || !QApplication::desktopSettingsAware();
- int tw;
- int h;
- int margin = flat || hasNoText ? 0 : 12;
- ret = groupBox->rect.adjusted(margin, 0, -margin, 0);
-
- if (!fontIsSet) {
- HIThemeTextInfo tti;
- tti.version = qt_mac_hitheme_version;
- tti.state = kThemeStateActive;
- tti.fontID = checkable ? kThemeSystemFont : kThemeSmallSystemFont;
- tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
- tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
- tti.options = kHIThemeTextBoxOptionNone;
- tti.truncationPosition = kHIThemeTextTruncationNone;
- tti.truncationMaxLines = 1 + groupBox->text.count(QLatin1Char('\n'));
- CGFloat width;
- CGFloat height;
- QCFString groupText = qt_mac_removeMnemonics(groupBox->text);
- HIThemeGetTextDimensions(groupText, 0, &tti, &width, &height, 0);
- tw = qRound(width);
- h = qCeil(height);
- } else {
- QFontMetricsF fm = QFontMetricsF(groupBox->fontMetrics);
- h = qCeil(fm.height());
- tw = qCeil(fm.size(Qt::TextShowMnemonic, groupBox->text).width());
- }
- ret.setHeight(h);
-
- QRect labelRect = alignedRect(groupBox->direction, groupBox->textAlignment,
- QSize(tw, h), ret);
- int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, opt, widget);
- bool rtl = groupBox->direction == Qt::RightToLeft;
- if (sc == SC_GroupBoxLabel) {
- if (checkable) {
- int newSum = indicatorWidth + 1;
- int newLeft = labelRect.left() + (rtl ? -newSum : newSum);
- labelRect.moveLeft(newLeft);
- } else if (flat) {
- int newLeft = labelRect.left() - (rtl ? 3 : -3);
- labelRect.moveLeft(newLeft);
- labelRect.moveTop(labelRect.top() + 3);
- } else {
- int newLeft = labelRect.left() - (rtl ? 3 : 2);
- labelRect.moveLeft(newLeft);
- labelRect.moveTop(labelRect.top() + 5);
- }
- ret = labelRect;
- }
-
- if (sc == SC_GroupBoxCheckBox) {
- int left = rtl ? labelRect.right() - indicatorWidth : labelRect.left();
- ret.setRect(left, ret.top(),
- indicatorWidth, proxy()->pixelMetric(PM_IndicatorHeight, opt, widget));
- }
- break;
- }
- case SC_GroupBoxContents:
- case SC_GroupBoxFrame: {
- if (flat) {
- ret = QWindowsStyle::subControlRect(cc, groupBox, sc, widget);
- break;
- }
- QFontMetrics fm = groupBox->fontMetrics;
- bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
- int yOffset = 3;
- if (!checkable) {
- if (widget && !widget->testAttribute(Qt::WA_SetFont)
- && QApplication::desktopSettingsAware())
- fm = QFontMetrics(qt_app_fonts_hash()->value("QSmallFont", QFont()));
- yOffset = 5;
- if (hasNoText)
- yOffset = -qCeil(QFontMetricsF(fm).height());
- }
-
- ret = opt->rect.adjusted(0, qCeil(QFontMetricsF(fm).height()) + yOffset, 0, 0);
- if (sc == SC_GroupBoxContents)
- ret.adjust(3, 3, -3, -4); // guess
- }
- break;
- default:
- ret = QWindowsStyle::subControlRect(cc, groupBox, sc, widget);
- break;
- }
- }
- break;
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QAquaWidgetSize aquaSize = d->aquaSizeConstrain(spin, widget);
- int spinner_w;
- int spinBoxSep;
- int fw = proxy()->pixelMetric(PM_SpinBoxFrameWidth, spin, widget);
- switch (aquaSize) {
- default:
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- spinner_w = 14;
- spinBoxSep = 2;
- break;
- case QAquaSizeSmall:
- spinner_w = 12;
- spinBoxSep = 2;
- break;
- case QAquaSizeMini:
- spinner_w = 10;
- spinBoxSep = 1;
- break;
- }
-
- switch (sc) {
- case SC_SpinBoxUp:
- case SC_SpinBoxDown: {
- if (spin->buttonSymbols == QAbstractSpinBox::NoButtons)
- break;
-
- const int y = fw;
- const int x = spin->rect.width() - spinner_w;
- ret.setRect(x + spin->rect.x(), y + spin->rect.y(), spinner_w, spin->rect.height() - y * 2);
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.kind = kThemeIncDecButton;
- int hackTranslateX;
- switch (aquaSize) {
- default:
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- bdi.kind = kThemeIncDecButton;
- hackTranslateX = 0;
- break;
- case QAquaSizeSmall:
- bdi.kind = kThemeIncDecButtonSmall;
- hackTranslateX = -2;
- break;
- case QAquaSizeMini:
- bdi.kind = kThemeIncDecButtonMini;
- hackTranslateX = -1;
- break;
- }
- bdi.state = kThemeStateActive;
- bdi.value = kThemeButtonOff;
- bdi.adornment = kThemeAdornmentNone;
- HIRect hirect = qt_hirectForQRect(ret);
-
- HIRect outRect;
- HIThemeGetButtonBackgroundBounds(&hirect, &bdi, &outRect);
- ret = qt_qrectForHIRect(outRect);
- switch (sc) {
- case SC_SpinBoxUp:
- ret.setHeight(ret.height() / 2);
- break;
- case SC_SpinBoxDown:
- ret.setY(ret.y() + ret.height() / 2);
- break;
- default:
- Q_ASSERT(0);
- break;
- }
- ret.translate(hackTranslateX, 0); // hack: position the buttons correctly (weird that we need this)
- ret = visualRect(spin->direction, spin->rect, ret);
- break;
- }
- case SC_SpinBoxEditField:
- if (spin->buttonSymbols == QAbstractSpinBox::NoButtons) {
- ret.setRect(fw, fw,
- spin->rect.width() - fw * 2,
- spin->rect.height() - fw * 2);
- } else {
- ret.setRect(fw, fw,
- spin->rect.width() - fw * 2 - spinBoxSep - spinner_w,
- spin->rect.height() - fw * 2);
- }
- ret = visualRect(spin->direction, spin->rect, ret);
- break;
- default:
- ret = QWindowsStyle::subControlRect(cc, spin, sc, widget);
- break;
- }
- }
- break;
- case CC_ToolButton:
- ret = QWindowsStyle::subControlRect(cc, opt, sc, widget);
- if (sc == SC_ToolButtonMenu && widget && !qobject_cast<QToolBar*>(widget->parentWidget())) {
- ret.adjust(-1, 0, 0, 0);
- }
- break;
- default:
- ret = QWindowsStyle::subControlRect(cc, opt, sc, widget);
- break;
- }
- return ret;
-}
-
-QSize QMacStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &csz, const QWidget *widget) const
-{
- QSize sz(csz);
- bool useAquaGuideline = true;
-
- switch (ct) {
- case QStyle::CT_SpinBox:
- // hack to work around horrible sizeHint() code in QAbstractSpinBox
- sz.setHeight(sz.height() - 3);
- break;
- case QStyle::CT_TabWidget:
- // the size between the pane and the "contentsRect" (+4,+4)
- // (the "contentsRect" is on the inside of the pane)
- sz = QWindowsStyle::sizeFromContents(ct, opt, csz, widget);
- /**
- This is supposed to show the relationship between the tabBar and
- the stack widget of a QTabWidget.
- Unfortunately ascii is not a good way of representing graphics.....
- PS: The '=' line is the painted frame.
-
- top ---+
- |
- |
- |
- | vvv just outside the painted frame is the "pane"
- - -|- - - - - - - - - - <-+
- TAB BAR +=====^============ | +2 pixels
- - - -|- - -|- - - - - - - <-+
- | | ^ ^^^ just inside the painted frame is the "contentsRect"
- | | |
- | overlap |
- | | |
- bottom ------+ <-+ +14 pixels
- |
- v
- ------------------------------ <- top of stack widget
-
-
- To summarize:
- * 2 is the distance between the pane and the contentsRect
- * The 14 and the 1's are the distance from the contentsRect to the stack widget.
- (same value as used in SE_TabWidgetTabContents)
- * overlap is how much the pane should overlap the tab bar
- */
- // then add the size between the stackwidget and the "contentsRect"
-
- if (const QStyleOptionTabWidgetFrame *twf
- = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- QSize extra(0,0);
- const int overlap = pixelMetric(PM_TabBarBaseOverlap, opt, widget);
- const int gapBetweenTabbarAndStackWidget = 2 + 14 - overlap;
-
- if (getTabDirection(twf->shape) == kThemeTabNorth || getTabDirection(twf->shape) == kThemeTabSouth) {
- extra = QSize(2, gapBetweenTabbarAndStackWidget + 1);
- } else {
- extra = QSize(gapBetweenTabbarAndStackWidget + 1, 2);
- }
- sz+= extra;
- }
-
- break;
- case QStyle::CT_TabBarTab:
- if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(opt)) {
- const QAquaWidgetSize AquaSize = d->aquaSizeConstrain(opt, widget);
- const bool differentFont = (widget && widget->testAttribute(Qt::WA_SetFont))
- || !QApplication::desktopSettingsAware();
- ThemeTabDirection ttd = getTabDirection(tab->shape);
- bool vertTabs = ttd == kThemeTabWest || ttd == kThemeTabEast;
- if (vertTabs)
- sz.transpose();
- int defaultTabHeight;
- int defaultExtraSpace = proxy()->pixelMetric(PM_TabBarTabHSpace, tab, widget); // Remove spurious gcc warning (AFAIK)
- QFontMetrics fm = opt->fontMetrics;
- switch (AquaSize) {
- case QAquaSizeUnknown:
- case QAquaSizeLarge:
- if (tab->documentMode)
- defaultTabHeight = 23;
- else
- defaultTabHeight = 21;
- break;
- case QAquaSizeSmall:
- defaultTabHeight = 18;
- break;
- case QAquaSizeMini:
- defaultTabHeight = 16;
- break;
- }
- bool setWidth = false;
- if (differentFont || !tab->icon.isNull()) {
- sz.rheight() = qMax(defaultTabHeight, sz.height());
- } else {
- QSize textSize = fm.size(Qt::TextShowMnemonic, tab->text);
- sz.rheight() = qMax(defaultTabHeight, textSize.height());
- sz.rwidth() = textSize.width() + defaultExtraSpace;
- setWidth = true;
- }
-
- if (vertTabs)
- sz.transpose();
-
- int maxWidgetHeight = qMax(tab->leftButtonSize.height(), tab->rightButtonSize.height());
- int maxWidgetWidth = qMax(tab->leftButtonSize.width(), tab->rightButtonSize.width());
-
- int widgetWidth = 0;
- int widgetHeight = 0;
- int padding = 0;
- if (tab->leftButtonSize.isValid()) {
- padding += 8;
- widgetWidth += tab->leftButtonSize.width();
- widgetHeight += tab->leftButtonSize.height();
- }
- if (tab->rightButtonSize.isValid()) {
- padding += 8;
- widgetWidth += tab->rightButtonSize.width();
- widgetHeight += tab->rightButtonSize.height();
- }
-
- if (vertTabs) {
- sz.setHeight(sz.height() + widgetHeight + padding);
- sz.setWidth(qMax(sz.width(), maxWidgetWidth));
- } else {
- if (setWidth)
- sz.setWidth(sz.width() + widgetWidth + padding);
- sz.setHeight(qMax(sz.height(), maxWidgetHeight));
- }
- }
- break;
- case QStyle::CT_PushButton:
- // By default, we fit the contents inside a normal rounded push button.
- // Do this by add enough space around the contents so that rounded
- // borders (including highlighting when active) will show.
- sz.rwidth() += QMacStylePrivate::PushButtonLeftOffset + QMacStylePrivate::PushButtonRightOffset + 12;
- sz.rheight() += QMacStylePrivate::PushButtonTopOffset + QMacStylePrivate::PushButtonBottomOffset;
- break;
- case QStyle::CT_MenuItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- int maxpmw = mi->maxIconWidth;
- const QComboBox *comboBox = qobject_cast<const QComboBox *>(widget);
- int w = sz.width(),
- h = sz.height();
- if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
- w = 10;
- SInt16 ash;
- GetThemeMenuSeparatorHeight(&ash);
- h = ash;
- } else {
- h = mi->fontMetrics.height() + 2;
- if (!mi->icon.isNull()) {
- if (comboBox) {
- const QSize &iconSize = comboBox->iconSize();
- h = qMax(h, iconSize.height() + 4);
- maxpmw = qMax(maxpmw, iconSize.width());
- } else {
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
- h = qMax(h, mi->icon.actualSize(QSize(iconExtent, iconExtent)).height() + 4);
- }
- }
- }
- if (mi->text.contains(QLatin1Char('\t')))
- w += 12;
- if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
- w += 20;
- if (maxpmw)
- w += maxpmw + 6;
- // add space for a check. All items have place for a check too.
- w += 20;
- if (comboBox && comboBox->isVisible()) {
- QStyleOptionComboBox cmb;
- cmb.initFrom(comboBox);
- cmb.editable = false;
- cmb.subControls = QStyle::SC_ComboBoxEditField;
- cmb.activeSubControls = QStyle::SC_None;
- w = qMax(w, subControlRect(QStyle::CC_ComboBox, &cmb,
- QStyle::SC_ComboBoxEditField,
- comboBox).width());
- } else {
- w += 12;
- }
- sz = QSize(w, h);
- }
- break;
- case CT_ToolButton:
- if (widget && qobject_cast<const QToolBar *>(widget->parentWidget())) {
- if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(widget->parent())) {
- if (mainWindow->unifiedTitleAndToolBarOnMac()) {
- sz.rwidth() += 4;
- if (sz.height() <= 32) {
- // Workaround strange HIToolBar bug when getting constraints.
- sz.rheight() += 1;
- }
- return sz;
- }
- }
- }
- sz.rwidth() += 10;
- sz.rheight() += 10;
- return sz;
- case CT_ComboBox:
- sz.rwidth() += 50;
- break;
- case CT_Menu: {
- QStyleHintReturnMask menuMask;
- QStyleOption myOption = *opt;
- myOption.rect.setSize(sz);
- if (proxy()->styleHint(SH_Menu_Mask, &myOption, widget, &menuMask)) {
- sz = menuMask.region.boundingRect().size();
- }
- break; }
- case CT_HeaderSection:{
- const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt);
- sz = QWindowsStyle::sizeFromContents(ct, opt, csz, widget);
- if (header->text.contains(QLatin1Char('\n')))
- useAquaGuideline = false;
- break; }
- case CT_ScrollBar :
- // Make sure that the scroll bar is large enough to display the thumb indicator.
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- const int minimumSize = scrollButtonsCutoffSize(thumbIndicatorCutoff, widgetSizePolicy(widget));
- if (slider->orientation == Qt::Horizontal)
- sz = sz.expandedTo(QSize(minimumSize, sz.height()));
- else
- sz = sz.expandedTo(QSize(sz.width(), minimumSize));
- }
- break;
- case CT_ItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- sz = QCommonStyle::sizeFromContents(ct, vopt, csz, widget);
- sz.setHeight(sz.height() + 2);
- }
- break;
-
- default:
- sz = QWindowsStyle::sizeFromContents(ct, opt, csz, widget);
- }
-
- if (useAquaGuideline){
- QSize macsz;
- if (d->aquaSizeConstrain(opt, widget, ct, sz, &macsz) != QAquaSizeUnknown) {
- if (macsz.width() != -1)
- sz.setWidth(macsz.width());
- if (macsz.height() != -1)
- sz.setHeight(macsz.height());
- }
- }
-
- // The sizes that Carbon and the guidelines gives us excludes the focus frame.
- // We compensate for this by adding some extra space here to make room for the frame when drawing:
- if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)){
- QAquaWidgetSize widgetSize = d->aquaSizeConstrain(opt, widget);
- int bkind = 0;
- switch (widgetSize) {
- default:
- case QAquaSizeLarge:
- bkind = combo->editable ? kThemeComboBox : kThemePopupButton;
- break;
- case QAquaSizeSmall:
- bkind = combo->editable ? int(kThemeComboBoxSmall) : int(kThemePopupButtonSmall);
- break;
- case QAquaSizeMini:
- bkind = combo->editable ? kThemeComboBoxMini : kThemePopupButtonMini;
- break;
- }
- HIRect tmpRect = {{0, 0}, {0, 0}};
- HIRect diffRect = QMacStylePrivate::comboboxInnerBounds(tmpRect, bkind);
- sz.rwidth() -= qRound(diffRect.size.width);
- sz.rheight() -= qRound(diffRect.size.height);
- } else if (ct == CT_PushButton || ct == CT_ToolButton){
- ThemeButtonKind bkind;
- QAquaWidgetSize widgetSize = d->aquaSizeConstrain(opt, widget);
- switch (ct) {
- default:
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (btn->features & QStyleOptionButton::CommandLinkButton) {
- return QWindowsStyle::sizeFromContents(ct, opt, sz, widget);
- }
- }
-
- switch (widgetSize) {
- default:
- case QAquaSizeLarge:
- bkind = kThemePushButton;
- break;
- case QAquaSizeSmall:
- bkind = kThemePushButtonSmall;
- break;
- case QAquaSizeMini:
- bkind = kThemePushButtonMini;
- break;
- }
- break;
- case CT_ToolButton:
- switch (widgetSize) {
- default:
- case QAquaSizeLarge:
- bkind = kThemeLargeBevelButton;
- break;
- case QAquaSizeMini:
- case QAquaSizeSmall:
- bkind = kThemeSmallBevelButton;
- }
- break;
- }
-
- HIThemeButtonDrawInfo bdi;
- bdi.version = qt_mac_hitheme_version;
- bdi.state = kThemeStateActive;
- bdi.kind = bkind;
- bdi.value = kThemeButtonOff;
- bdi.adornment = kThemeAdornmentNone;
- HIRect macRect, myRect;
- myRect = CGRectMake(0, 0, sz.width(), sz.height());
- HIThemeGetButtonBackgroundBounds(&myRect, &bdi, &macRect);
- // Mini buttons only return their actual size in HIThemeGetButtonBackgroundBounds, so help them out a bit (guess),
- if (bkind == kThemePushButtonMini)
- macRect.size.height += 8.;
- else if (bkind == kThemePushButtonSmall)
- macRect.size.height -= 10;
- sz.setWidth(sz.width() + int(macRect.size.width - myRect.size.width));
- sz.setHeight(sz.height() + int(macRect.size.height - myRect.size.height));
- }
- return sz;
-}
-
-void QMacStyle::drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal,
- bool enabled, const QString &text, QPalette::ColorRole textRole) const
-{
- if(flags & Qt::TextShowMnemonic)
- flags |= Qt::TextHideMnemonic;
- QWindowsStyle::drawItemText(p, r, flags, pal, enabled, text, textRole);
-}
-
-bool QMacStyle::event(QEvent *e)
-{
- if(e->type() == QEvent::FocusIn) {
- QWidget *f = 0;
- QWidget *focusWidget = QApplication::focusWidget();
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(focusWidget)) {
- QGraphicsItem *focusItem = graphicsView->scene() ? graphicsView->scene()->focusItem() : 0;
- if (focusItem && focusItem->type() == QGraphicsProxyWidget::Type) {
- QGraphicsProxyWidget *proxy = static_cast<QGraphicsProxyWidget *>(focusItem);
- if (proxy->widget())
- focusWidget = proxy->widget()->focusWidget();
- }
- }
-#endif
- if (focusWidget && focusWidget->testAttribute(Qt::WA_MacShowFocusRect)) {
- f = focusWidget;
- QWidget *top = f->parentWidget();
- while (top && !top->isWindow() && !(top->windowType() == Qt::SubWindow))
- top = top->parentWidget();
-#ifndef QT_NO_MAINWINDOW
- if (qobject_cast<QMainWindow *>(top)) {
- QWidget *central = static_cast<QMainWindow *>(top)->centralWidget();
- for (const QWidget *par = f; par; par = par->parentWidget()) {
- if (par == central) {
- top = central;
- break;
- }
- if (par->isWindow())
- break;
- }
- }
-#endif
- }
- if (f) {
- if(!d->focusWidget)
- d->focusWidget = new QFocusFrame(f);
- d->focusWidget->setWidget(f);
- } else if(d->focusWidget) {
- d->focusWidget->setWidget(0);
- }
- } else if(e->type() == QEvent::FocusOut) {
- if(d->focusWidget)
- d->focusWidget->setWidget(0);
- }
- return false;
-}
-
-QIcon QMacStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt,
- const QWidget *widget) const
-{
- switch (standardIcon) {
- default:
- return QWindowsStyle::standardIconImplementation(standardIcon, opt, widget);
- case SP_ToolBarHorizontalExtensionButton:
- case SP_ToolBarVerticalExtensionButton: {
- QPixmap pixmap(qt_mac_toolbar_ext);
- if (standardIcon == SP_ToolBarVerticalExtensionButton) {
- QPixmap pix2(pixmap.height(), pixmap.width());
- pix2.fill(Qt::transparent);
- QPainter p(&pix2);
- p.translate(pix2.width(), 0);
- p.rotate(90);
- p.drawPixmap(0, 0, pixmap);
- return pix2;
- }
- return pixmap;
- }
- }
-}
-
-int QMacStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- const int ButtonMask = QSizePolicy::ButtonBox | QSizePolicy::PushButton;
- bool isMetal = (widget && widget->testAttribute(Qt::WA_MacBrushedMetal));
- int controlSize = getControlSize(option, widget);
-
- if (control2 == QSizePolicy::ButtonBox) {
- /*
- AHIG seems to prefer a 12-pixel margin between group
- boxes and the row of buttons. The 20 pixel comes from
- Builder.
- */
- if (isMetal // (AHIG, guess, guess)
- || (control1 & (QSizePolicy::Frame // guess
- | QSizePolicy::GroupBox // (AHIG, guess, guess)
- | QSizePolicy::TabWidget // guess
- | ButtonMask))) { // AHIG
- return_SIZE(14, 8, 8);
- } else if (control1 == QSizePolicy::LineEdit) {
- return_SIZE(8, 8, 8); // Interface Builder
- } else {
- return_SIZE(20, 7, 7); // Interface Builder
- }
- }
-
- if ((control1 | control2) & ButtonMask) {
- if (control1 == QSizePolicy::LineEdit)
- return_SIZE(8, 8, 8); // Interface Builder
- else if (control2 == QSizePolicy::LineEdit) {
- if (orientation == Qt::Vertical)
- return_SIZE(20, 7, 7); // Interface Builder
- else
- return_SIZE(20, 8, 8);
- }
- return_SIZE(14, 8, 8); // Interface Builder
- }
-
- switch (CT2(control1, control2)) {
- case CT1(QSizePolicy::Label): // guess
- case CT2(QSizePolicy::Label, QSizePolicy::DefaultType): // guess
- case CT2(QSizePolicy::Label, QSizePolicy::CheckBox): // AHIG
- case CT2(QSizePolicy::Label, QSizePolicy::ComboBox): // AHIG
- case CT2(QSizePolicy::Label, QSizePolicy::LineEdit): // guess
- case CT2(QSizePolicy::Label, QSizePolicy::RadioButton): // AHIG
- case CT2(QSizePolicy::Label, QSizePolicy::Slider): // guess
- case CT2(QSizePolicy::Label, QSizePolicy::SpinBox): // guess
- case CT2(QSizePolicy::Label, QSizePolicy::ToolButton): // guess
- return_SIZE(8, 6, 5);
- case CT1(QSizePolicy::ToolButton):
- return 8; // AHIG
- case CT1(QSizePolicy::CheckBox):
- case CT2(QSizePolicy::CheckBox, QSizePolicy::RadioButton):
- case CT2(QSizePolicy::RadioButton, QSizePolicy::CheckBox):
- if (orientation == Qt::Vertical)
- return_SIZE(8, 8, 7); // AHIG and Builder
- break;
- case CT1(QSizePolicy::RadioButton):
- if (orientation == Qt::Vertical)
- return 5; // (Builder, guess, AHIG)
- }
-
- if (orientation == Qt::Horizontal
- && (control2 & (QSizePolicy::CheckBox | QSizePolicy::RadioButton)))
- return_SIZE(12, 10, 8); // guess
-
- if ((control1 | control2) & (QSizePolicy::Frame
- | QSizePolicy::GroupBox
- | QSizePolicy::TabWidget)) {
- /*
- These values were chosen so that nested container widgets
- look good side by side. Builder uses 8, which looks way
- too small, and AHIG doesn't say anything.
- */
- return_SIZE(16, 10, 10); // guess
- }
-
- if ((control1 | control2) & (QSizePolicy::Line | QSizePolicy::Slider))
- return_SIZE(12, 10, 8); // AHIG
-
- if ((control1 | control2) & QSizePolicy::LineEdit)
- return_SIZE(10, 8, 8); // AHIG
-
- /*
- AHIG and Builder differ by up to 4 pixels for stacked editable
- comboboxes. We use some values that work fairly well in all
- cases.
- */
- if ((control1 | control2) & QSizePolicy::ComboBox)
- return_SIZE(10, 8, 7); // guess
-
- /*
- Builder defaults to 8, 6, 5 in lots of cases, but most of the time the
- result looks too cramped.
- */
- return_SIZE(10, 8, 6); // guess
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qmacstyle_mac_p.h b/src/gui/styles/qmacstyle_mac_p.h
deleted file mode 100644
index fbd6d57e09..0000000000
--- a/src/gui/styles/qmacstyle_mac_p.h
+++ /dev/null
@@ -1,241 +0,0 @@
-/****************************************************************************
-**
-** 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 QMACSTYLE_MAC_P_H
-#define QMACSTYLE_MAC_P_H
-
-#include <qmacstyle_mac.h>
-#include <private/qapplication_p.h>
-#include <private/qcombobox_p.h>
-#include <private/qmacstylepixmaps_mac_p.h>
-#include <private/qpaintengine_mac_p.h>
-#include <private/qpainter_p.h>
-#include <private/qprintengine_mac_p.h>
-#include <private/qstylehelper_p.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcheckbox.h>
-#include <qcombobox.h>
-#include <qdialogbuttonbox.h>
-#include <qdockwidget.h>
-#include <qevent.h>
-#include <qfocusframe.h>
-#include <qformlayout.h>
-#include <qgroupbox.h>
-#include <qhash.h>
-#include <qheaderview.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qlistview.h>
-#include <qmainwindow.h>
-#include <qmap.h>
-#include <qmenubar.h>
-#include <qpaintdevice.h>
-#include <qpainter.h>
-#include <qpixmapcache.h>
-#include <qpointer.h>
-#include <qprogressbar.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qrubberband.h>
-#include <qsizegrip.h>
-#include <qspinbox.h>
-#include <qsplitter.h>
-#include <qstyleoption.h>
-#include <qtextedit.h>
-#include <qtextstream.h>
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qtreeview.h>
-#include <qtableview.h>
-#include <qwizard.h>
-#include <qdebug.h>
-#include <qlibrary.h>
-#include <qdatetimeedit.h>
-#include <qmath.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qgraphicsview.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_NAMESPACE
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5)
-enum {
- kThemePushButtonTextured = 31,
- kThemePushButtonTexturedSmall = 32,
- kThemePushButtonTexturedMini = 33
-};
-
-/* Search fields */
-enum {
- kHIThemeFrameTextFieldRound = 1000,
- kHIThemeFrameTextFieldRoundSmall = 1001,
- kHIThemeFrameTextFieldRoundMini = 1002
-};
-#endif
-
-/*
- AHIG:
- Apple Human Interface Guidelines
- http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/
-
- Builder:
- Apple Interface Builder v. 3.1.1
-*/
-
-// this works as long as we have at most 16 different control types
-#define CT1(c) CT2(c, c)
-#define CT2(c1, c2) ((uint(c1) << 16) | uint(c2))
-
-enum QAquaWidgetSize { QAquaSizeLarge = 0, QAquaSizeSmall = 1, QAquaSizeMini = 2,
- QAquaSizeUnknown = -1 };
-
-#define SIZE(large, small, mini) \
- (controlSize == QAquaSizeLarge ? (large) : controlSize == QAquaSizeSmall ? (small) : (mini))
-
-// same as return SIZE(...) but optimized
-#define return_SIZE(large, small, mini) \
- do { \
- static const int sizes[] = { (large), (small), (mini) }; \
- return sizes[controlSize]; \
- } while (0)
-
-bool qt_mac_buttonIsRenderedFlat(const QPushButton *pushButton, const QStyleOptionButton *option);
-
-class QMacStylePrivate : public QObject
-{
- Q_OBJECT
-
-public:
- QMacStylePrivate(QMacStyle *style);
-
- // Ideally these wouldn't exist, but since they already exist we need some accessors.
- static const int PushButtonLeftOffset;
- static const int PushButtonTopOffset;
- static const int PushButtonRightOffset;
- static const int PushButtonBottomOffset;
- static const int MiniButtonH;
- static const int SmallButtonH;
- static const int BevelButtonW;
- static const int BevelButtonH;
- static const int PushButtonContentPadding;
-
-
- // Stuff from QAquaAnimate:
- bool addWidget(QWidget *);
- void removeWidget(QWidget *);
-
- enum Animates { AquaPushButton, AquaProgressBar, AquaListViewItemOpen };
- bool animatable(Animates, const QWidget *) const;
- void stopAnimate(Animates, QWidget *);
- void startAnimate(Animates, QWidget *);
- static ThemeDrawState getDrawState(QStyle::State flags);
- QAquaWidgetSize aquaSizeConstrain(const QStyleOption *option, const QWidget *widg,
- QStyle::ContentsType ct = QStyle::CT_CustomBase,
- QSize szHint=QSize(-1, -1), QSize *insz = 0) const;
- void getSliderInfo(QStyle::ComplexControl cc, const QStyleOptionSlider *slider,
- HIThemeTrackDrawInfo *tdi, const QWidget *needToRemoveMe);
- bool doAnimate(Animates);
- inline int animateSpeed(Animates) const { return 33; }
-
- // Utility functions
- void drawColorlessButton(const HIRect &macRect, HIThemeButtonDrawInfo *bdi,
- QPainter *p, const QStyleOption *opt) const;
-
- QSize pushButtonSizeFromContents(const QStyleOptionButton *btn) const;
-
- HIRect pushButtonContentBounds(const QStyleOptionButton *btn,
- const HIThemeButtonDrawInfo *bdi) const;
-
- void initComboboxBdi(const QStyleOptionComboBox *combo, HIThemeButtonDrawInfo *bdi,
- const QWidget *widget, const ThemeDrawState &tds);
-
- static HIRect comboboxInnerBounds(const HIRect &outerBounds, int buttonKind);
-
- static QRect comboboxEditBounds(const QRect &outerBounds, const HIThemeButtonDrawInfo &bdi);
-
- static void drawCombobox(const HIRect &outerBounds, const HIThemeButtonDrawInfo &bdi, QPainter *p);
- static void drawTableHeader(const HIRect &outerBounds, bool drawTopBorder, bool drawLeftBorder,
- const HIThemeButtonDrawInfo &bdi, QPainter *p);
- bool contentFitsInPushButton(const QStyleOptionButton *btn, HIThemeButtonDrawInfo *bdi,
- ThemeButtonKind buttonKindToCheck) const;
- void initHIThemePushButton(const QStyleOptionButton *btn, const QWidget *widget,
- const ThemeDrawState tds,
- HIThemeButtonDrawInfo *bdi) const;
- QPixmap generateBackgroundPattern() const;
-protected:
- bool eventFilter(QObject *, QEvent *);
- void timerEvent(QTimerEvent *);
-
-private slots:
- void startAnimationTimer();
-
-public:
- QPointer<QPushButton> defaultButton; //default push buttons
- int timerID;
- QList<QPointer<QWidget> > progressBars; //existing progress bars that need animation
-
- struct ButtonState {
- int frame;
- enum { ButtonDark, ButtonLight } dir;
- } buttonState;
- UInt8 progressFrame;
- QPointer<QFocusFrame> focusWidget;
- CFAbsoluteTime defaultButtonStart;
- QMacStyle *q;
- bool mouseDown;
-};
-
-QT_END_NAMESPACE
-
-#endif // QMACSTYLE_MAC_P_H
diff --git a/src/gui/styles/qmacstylepixmaps_mac_p.h b/src/gui/styles/qmacstylepixmaps_mac_p.h
deleted file mode 100644
index 41794387ea..0000000000
--- a/src/gui/styles/qmacstylepixmaps_mac_p.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** 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 QMACSTYLEPIXMAPS_MAC_P_H
-#define QMACSTYLEPIXMAPS_MAC_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-static const char * const qt_mac_toolbar_ext[]={
- "14 9 4 1",
- "# c #858585",
- "b c #d9d9d9",
- ". c #dbdbdb",
- "a c None",
- ".###..###.aaaa",
- "a.###..###.aaa",
- "aab###bb###baa",
- "aaab###bb###ba",
- "aaaa.###..###.",
- "aaa.###..###.a",
- "aab###bb###baa",
- "ab###bb###baaa",
- ".###..###.aaaa"};
-
-#endif // QMACSTYLEPIXMAPS_MAC_P_H
diff --git a/src/gui/styles/qmotifstyle.cpp b/src/gui/styles/qmotifstyle.cpp
deleted file mode 100644
index 3bf8996650..0000000000
--- a/src/gui/styles/qmotifstyle.cpp
+++ /dev/null
@@ -1,2721 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmotifstyle.h"
-#include "qcdestyle.h"
-
-#if !defined(QT_NO_STYLE_MOTIF) || defined(QT_PLUGIN)
-
-#include "qmenu.h"
-#include "qapplication.h"
-#include "qpainter.h"
-#include "qdrawutil.h"
-#include "qpixmap.h"
-#include "qpalette.h"
-#include "qwidget.h"
-#include "qpushbutton.h"
-#include "qscrollbar.h"
-#include "qtabbar.h"
-#include "qtabwidget.h"
-#include "qlistview.h"
-#include "qsplitter.h"
-#include "qslider.h"
-#include "qcombobox.h"
-#include "qlineedit.h"
-#include "qprogressbar.h"
-#include "qimage.h"
-#include "qfocusframe.h"
-#include "qdebug.h"
-#include "qpainterpath.h"
-#include "qmotifstyle_p.h"
-#include "qdialogbuttonbox.h"
-#include "qformlayout.h"
-#include <limits.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qgraphicsview.h>
-
-#ifdef Q_WS_X11
-#include "qx11info_x11.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// old constants that might still be useful...
-static const int motifItemFrame = 2; // menu item frame width
-static const int motifSepHeight = 2; // separator item height
-static const int motifItemHMargin = 3; // menu item hor text margin
-static const int motifItemVMargin = 2; // menu item ver text margin
-static const int motifArrowHMargin = 6; // arrow horizontal margin
-static const int motifTabSpacing = 12; // space between text and tab
-static const int motifCheckMarkHMargin = 2; // horiz. margins of check mark
-static const int motifCheckMarkSpace = 16;
-
-
-/*!
- \class QMotifStyle
- \brief The QMotifStyle class provides Motif look and feel.
-
- \ingroup appearance
-
- This class implements the Motif look and feel. It closely
- resembles the original Motif look as defined by the Open Group,
- but with some minor improvements. The Motif style is Qt's default
- GUI style on Unix platforms.
-
- \img qmotifstyle.png
- \sa QWindowsXPStyle, QMacStyle, QWindowsStyle, QPlastiqueStyle, QCDEStyle
-*/
-
-/*!
- \variable QMotifStyle::focus
- \internal
-*/
-
-/*!
- Constructs a QMotifStyle.
-
- If \a useHighlightCols is false (the default), the style will
- polish the application's color palette to emulate the Motif way of
- highlighting, which is a simple inversion between the base and the
- text color.
-*/
-QMotifStyle::QMotifStyle(bool useHighlightCols)
- : QCommonStyle(*new QMotifStylePrivate)
-{
- focus = 0;
- highlightCols = useHighlightCols;
-}
-
-
-/*!
- \internal
-*/
-QMotifStyle::QMotifStyle(QMotifStylePrivate &dd, bool useHighlightColors)
- : QCommonStyle(dd)
-{
- focus = 0;
- highlightCols = useHighlightColors;
-}
-
-
-/*!
- \overload
-
- Destroys the style.
-*/
-QMotifStyle::~QMotifStyle()
-{
- delete focus;
-}
-
-/*!
- \internal
- Animate indeterminate progress bars only when visible
-*/
-bool QMotifStyle::eventFilter(QObject *o, QEvent *e)
-{
-#ifndef QT_NO_PROGRESSBAR
- Q_D(QMotifStyle);
- switch(e->type()) {
- case QEvent::StyleChange:
- case QEvent::Show:
- if (QProgressBar *bar = qobject_cast<QProgressBar *>(o)) {
- d->bars << bar;
- if (d->bars.size() == 1) {
- Q_ASSERT(d->animationFps> 0);
- d->animateTimer = startTimer(1000 / d->animationFps);
- }
- }
- break;
- case QEvent::Destroy:
- case QEvent::Hide:
- // reinterpret_cast because there is no type info when getting
- // the destroy event. We know that it is a QProgressBar.
- if (QProgressBar *bar = reinterpret_cast<QProgressBar *>(o)) {
- d->bars.removeAll(bar);
- if (d->bars.isEmpty() && d->animateTimer) {
- killTimer(d->animateTimer);
- d->animateTimer = 0;
- }
- }
- default:
- break;
- }
-#endif // QT_NO_PROGRESSBAR
- return QStyle::eventFilter(o, e);
-}
-
-/*!
- \internal
-*/
-QIcon QMotifStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt,
- const QWidget *widget) const
-{
- return QCommonStyle::standardIconImplementation(standardIcon, opt, widget);
-}
-
-/*!
- \reimp
-*/
-void QMotifStyle::timerEvent(QTimerEvent *event)
-{
-#ifndef QT_NO_PROGRESSBAR
- Q_D(QMotifStyle);
- if (event->timerId() == d->animateTimer) {
- Q_ASSERT(d->animationFps > 0);
- d->animateStep = d->startTime.elapsed() / (1000 / d->animationFps);
- foreach (QProgressBar *bar, d->bars) {
- if ((bar->minimum() == 0 && bar->maximum() == 0))
- bar->update();
- }
- }
-#endif // QT_NO_PROGRESSBAR
- event->ignore();
-}
-
-
-QMotifStylePrivate::QMotifStylePrivate()
-#ifndef QT_NO_PROGRESSBAR
- : animationFps(25), animateTimer(0), animateStep(0)
-#endif
-{
-}
-
-/*!
- If \a arg is false, the style will polish the application's color
- palette to emulate the Motif way of highlighting, which is a
- simple inversion between the base and the text color.
-
- The effect will show up the next time an application palette is
- set via QApplication::setPalette(). The current color palette of
- the application remains unchanged.
-
- \sa QStyle::polish()
-*/
-void QMotifStyle::setUseHighlightColors(bool arg)
-{
- highlightCols = arg;
-}
-
-/*!
- Returns true if the style treats the highlight colors of the
- palette in a Motif-like manner, which is a simple inversion
- between the base and the text color; otherwise returns false. The
- default is false.
-*/
-bool QMotifStyle::useHighlightColors() const
-{
- return highlightCols;
-}
-
-/*! \reimp */
-
-void QMotifStyle::polish(QPalette& pal)
-{
- if (pal.brush(QPalette::Active, QPalette::Light) == pal.brush(QPalette::Active, QPalette::Base)) {
- QColor nlight = pal.color(QPalette::Active, QPalette::Light).darker(108);
- pal.setColor(QPalette::Active, QPalette::Light, nlight) ;
- pal.setColor(QPalette::Disabled, QPalette::Light, nlight) ;
- pal.setColor(QPalette::Inactive, QPalette::Light, nlight) ;
- }
-
- if (highlightCols)
- return;
-
- // force the ugly motif way of highlighting *sigh*
- pal.setColor(QPalette::Active, QPalette::Highlight,
- pal.color(QPalette::Active, QPalette::Text));
- pal.setColor(QPalette::Active, QPalette::HighlightedText,
- pal.color(QPalette::Active, QPalette::Base));
- pal.setColor(QPalette::Disabled, QPalette::Highlight,
- pal.color(QPalette::Disabled, QPalette::Text));
- pal.setColor(QPalette::Disabled, QPalette::HighlightedText,
- pal.color(QPalette::Disabled, QPalette::Base));
- pal.setColor(QPalette::Inactive, QPalette::Highlight,
- pal.color(QPalette::Active, QPalette::Text));
- pal.setColor(QPalette::Inactive, QPalette::HighlightedText,
- pal.color(QPalette::Active, QPalette::Base));
-}
-
-/*!
- \reimp
- \internal
- Keep QStyle::polish() visible.
-*/
-void QMotifStyle::polish(QWidget* widget)
-{
- QStyle::polish(widget);
-#ifndef QT_NO_PROGRESSBAR
- if (qobject_cast<QProgressBar *>(widget))
- widget->installEventFilter(this);
-#endif
-}
-
-/*!
- \reimp
- \internal
- Keep QStyle::polish() visible.
-*/
-void QMotifStyle::unpolish(QWidget* widget)
-{
- QCommonStyle::unpolish(widget);
-#ifndef QT_NO_PROGRESSBAR
- if (qobject_cast<QProgressBar *>(widget)) {
- Q_D(QMotifStyle);
- widget->removeEventFilter(this);
- d->bars.removeAll(static_cast<QProgressBar*>(widget));
- }
-#endif
-}
-
-
-/*!
- \reimp
- \internal
- Keep QStyle::polish() visible.
-*/
-void QMotifStyle::polish(QApplication* a)
-{
- QCommonStyle::polish(a);
-}
-
-
-/*!
- \reimp
- \internal
- Keep QStyle::polish() visible.
-*/
-void QMotifStyle::unpolish(QApplication* a)
-{
- QCommonStyle::unpolish(a);
-}
-
-static void rot(QPolygon& a, int n)
-{
- QPolygon r(a.size());
- for (int i = 0; i < (int)a.size(); i++) {
- switch (n) {
- case 1: r.setPoint(i,-a[i].y(),a[i].x()); break;
- case 2: r.setPoint(i,-a[i].x(),-a[i].y()); break;
- case 3: r.setPoint(i,a[i].y(),-a[i].x()); break;
- }
- }
- a = r;
-}
-
-
-/*!
- \reimp
-*/
-void QMotifStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w) const
-{
- switch(pe) {
- case PE_Q3CheckListExclusiveIndicator:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- if (lv->items.isEmpty())
- return;
-
- if (lv->state & State_Enabled)
- p->setPen(QPen(opt->palette.text().color()));
- else
- p->setPen(QPen(lv->palette.color(QPalette::Disabled, QPalette::Text)));
- QPolygon a;
-
- int cx = opt->rect.width()/2 - 1;
- int cy = opt->rect.height()/2;
- int e = opt->rect.width()/2 - 1;
- for (int i = 0; i < 3; i++) { //penWidth 2 doesn't quite work
- a.setPoints(4, cx-e, cy, cx, cy-e, cx+e, cy, cx, cy+e);
- p->drawPolygon(a);
- e--;
- }
- if (opt->state & State_On) {
- if (lv->state & State_Enabled)
- p->setPen(QPen(opt->palette.text().color()));
- else
- p->setPen(QPen(lv->palette.color(QPalette::Disabled,
- QPalette::Text)));
- QBrush saveBrush = p->brush();
- p->setBrush(opt->palette.text());
- e = e - 2;
- a.setPoints(4, cx-e, cy, cx, cy-e, cx+e, cy, cx, cy+e);
- p->drawPolygon(a);
- p->setBrush(saveBrush);
- }
- }
- break;
-
- case PE_FrameTabWidget:
- case PE_FrameWindow:
- qDrawShadePanel(p, opt->rect, opt->palette, QStyle::State_None, proxy()->pixelMetric(PM_DefaultFrameWidth));
- break;
- case PE_FrameFocusRect:
- if (const QStyleOptionFocusRect *fropt = qstyleoption_cast<const QStyleOptionFocusRect *>(opt)) {
- if ((fropt->state & State_HasFocus) && focus && focus->isVisible()
- && !(fropt->state & QStyle::State_Item))
- break;
- QCommonStyle::drawPrimitive(pe, opt, p, w);
- }
- break;
-
- case PE_IndicatorToolBarHandle: {
- p->save();
- p->translate(opt->rect.x(), opt->rect.y());
-
- QColor dark(opt->palette.dark().color());
- QColor light(opt->palette.light().color());
- int i;
- if (opt->state & State_Horizontal) {
- int h = opt->rect.height();
- if (h > 6) {
- if (opt->state & State_On)
- p->fillRect(1, 1, 8, h - 2, opt->palette.highlight());
- QPolygon a(2 * ((h-6)/3));
- int y = 3 + (h%3)/2;
- p->setPen(dark);
- p->drawLine(8, 1, 8, h-2);
- for (i=0; 2*i < a.size(); ++i) {
- a.setPoint(2*i, 5, y+1+3*i);
- a.setPoint(2*i+1, 2, y+2+3*i);
- }
- p->drawPoints(a);
- p->setPen(light);
- p->drawLine(9, 1, 9, h-2);
- for (i=0; 2*i < a.size(); i++) {
- a.setPoint(2*i, 4, y+3*i);
- a.setPoint(2*i+1, 1, y+1+3*i);
- }
- p->drawPoints(a);
- // if (drawBorder) {
- // p->setPen(QPen(Qt::darkGray));
- // p->drawLine(0, opt->rect.height() - 1,
- // tbExtent, opt->rect.height() - 1);
- // }
- }
- } else {
- int w = opt->rect.width();
- if (w > 6) {
- if (opt->state & State_On)
- p->fillRect(1, 1, w - 2, 9, opt->palette.highlight());
- QPolygon a(2 * ((w-6)/3));
-
- int x = 3 + (w%3)/2;
- p->setPen(dark);
- p->drawLine(1, 8, w-2, 8);
- for (i=0; 2*i < a.size(); ++i) {
- a.setPoint(2*i, x+1+3*i, 6);
- a.setPoint(2*i+1, x+2+3*i, 3);
- }
- p->drawPoints(a);
- p->setPen(light);
- p->drawLine(1, 9, w-2, 9);
- for (i=0; 2*i < a.size(); ++i) {
- a.setPoint(2*i, x+3*i, 5);
- a.setPoint(2*i+1, x+1+3*i, 2);
- }
- p->drawPoints(a);
- // if (drawBorder) {
- // p->setPen(QPen(Qt::darkGray));
- // p->drawLine(opt->rect.width() - 1, 0,
- // opt->rect.width() - 1, tbExtent);
- // }
- }
- }
- p->restore();
- break; }
-
- case PE_PanelButtonCommand:
- case PE_PanelButtonBevel:
- case PE_PanelButtonTool: {
- QBrush fill;
- if (opt->state & State_Sunken)
- fill = opt->palette.brush(QPalette::Mid);
- else if ((opt->state & State_On) && (opt->state & State_Enabled))
- fill = QBrush(opt->palette.mid().color(), Qt::Dense4Pattern);
- else
- fill = opt->palette.brush(QPalette::Button);
- if ((opt->state & State_Enabled || opt->state & State_On) || !(opt->state & State_AutoRaise))
- qDrawShadePanel(p, opt->rect, opt->palette, bool(opt->state & (State_Sunken | State_On)),
- proxy()->pixelMetric(PM_DefaultFrameWidth), &fill);
- break; }
-
- case PE_IndicatorCheckBox: {
- bool on = opt->state & State_On;
- bool down = opt->state & State_Sunken;
- bool showUp = !(down ^ on);
- QBrush fill = opt->palette.brush((showUp || opt->state & State_NoChange) ?QPalette::Button : QPalette::Mid);
- if (opt->state & State_NoChange) {
- qDrawPlainRect(p, opt->rect, opt->palette.text().color(),
- 1, &fill);
- p->drawLine(opt->rect.x() + opt->rect.width() - 1, opt->rect.y(),
- opt->rect.x(), opt->rect.y() + opt->rect.height() - 1);
- } else {
- qDrawShadePanel(p, opt->rect, opt->palette, !showUp,
- proxy()->pixelMetric(PM_DefaultFrameWidth), &fill);
- }
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(opt->rect, QBrush(p->background().color(), Qt::Dense5Pattern));
- break; }
-
- case PE_IndicatorRadioButton: {
-#define INTARRLEN(x) sizeof(x)/(sizeof(int)*2)
- int inner_pts[] = { // used for filling diamond
- 2,opt->rect.height()/2,
- opt->rect.width()/2,2,
- opt->rect.width()-3,opt->rect.height()/2,
- opt->rect.width()/2,opt->rect.height()-3
- };
- int top_pts[] = { // top (^) of diamond
- 0,opt->rect.height()/2,
- opt->rect.width()/2,0,
- opt->rect.width()-2,opt->rect.height()/2-1,
- opt->rect.width()-3,opt->rect.height()/2-1,
- opt->rect.width()/2,1,
- 1,opt->rect.height()/2,
- 2,opt->rect.height()/2,
- opt->rect.width()/2,2,
- opt->rect.width()-4,opt->rect.height()/2-1
- };
- int bottom_pts[] = { // bottom (v) of diamond
- 1,opt->rect.height()/2+1,
- opt->rect.width()/2,opt->rect.height()-1,
- opt->rect.width()-1,opt->rect.height()/2,
- opt->rect.width()-2,opt->rect.height()/2,
- opt->rect.width()/2,opt->rect.height()-2,
- 2,opt->rect.height()/2+1,
- 3,opt->rect.height()/2+1,
- opt->rect.width()/2,opt->rect.height()-3,
- opt->rect.width()-3,opt->rect.height()/2
- };
- bool on = opt->state & State_On;
- bool down = opt->state & State_Sunken;
- bool showUp = !(down ^ on);
- QPen oldPen = p->pen();
- QBrush oldBrush = p->brush();
- QPolygon a(INTARRLEN(inner_pts), inner_pts);
- p->setPen(Qt::NoPen);
- p->setBrush(opt->palette.brush(showUp ? QPalette::Button : QPalette::Mid));
- a.translate(opt->rect.x(), opt->rect.y());
- p->drawPolygon(a);
- p->setPen(showUp ? opt->palette.light().color() : opt->palette.dark().color());
- p->setBrush(Qt::NoBrush);
- a.setPoints(INTARRLEN(top_pts), top_pts);
- a.translate(opt->rect.x(), opt->rect.y());
- p->drawPolyline(a);
- p->setPen(showUp ? opt->palette.dark().color() : opt->palette.light().color());
- a.setPoints(INTARRLEN(bottom_pts), bottom_pts);
- a.translate(opt->rect.x(), opt->rect.y());
- p->drawPolyline(a);
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(opt->rect, QBrush(p->background().color(), Qt::Dense5Pattern));
- p->setPen(oldPen);
- p->setBrush(oldBrush);
- break; }
-
- case PE_IndicatorSpinUp:
- case PE_IndicatorSpinPlus:
- case PE_IndicatorSpinDown:
- case PE_IndicatorSpinMinus:
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowLeft: {
- QRect rect = opt->rect;
- QPolygon bFill;
- QPolygon bTop;
- QPolygon bBot;
- QPolygon bLeft;
- if (pe == PE_IndicatorSpinPlus || pe == PE_IndicatorSpinUp)
- pe = PE_IndicatorArrowUp;
- else if (pe == PE_IndicatorSpinMinus || pe == PE_IndicatorSpinDown)
- pe = PE_IndicatorArrowDown;
- bool vertical = pe == PE_IndicatorArrowUp || pe == PE_IndicatorArrowDown;
- bool horizontal = !vertical;
- int dim = rect.width() < rect.height() ? rect.width() : rect.height();
- int colspec = 0x0000;
-
- if (!(opt->state & State_Enabled))
- dim -= 2;
- if(dim < 2)
- break;
-
- // adjust size and center (to fix rotation below)
- if (rect.width() > dim) {
- rect.setX(rect.x() + ((rect.width() - dim) / 2));
- rect.setWidth(dim);
- }
- if (rect.height() > dim) {
- rect.setY(rect.y() + ((rect.height() - dim) / 2));
- rect.setHeight(dim);
- }
-
- if (dim > 3) {
- if (pixelMetric(PM_DefaultFrameWidth) < 2) { // thin style
- bFill.resize( dim & 1 ? 3 : 4 );
- bTop.resize( 2 );
- bBot.resize( 2 );
- bLeft.resize( 2 );
- bLeft.putPoints( 0, 2, 0, 0, 0, dim-1 );
- bTop.putPoints( 0, 2, 1, 0, dim-1, dim/2 );
- bBot.putPoints( 0, 2, 1, dim-1, dim-1, dim/2 );
-
- if ( dim > 6 ) { // dim>6: must fill interior
- bFill.putPoints( 0, 2, 0, dim-1, 0, 0 );
- if ( dim & 1 ) // if size is an odd number
- bFill.setPoint( 2, dim - 1, dim / 2 );
- else
- bFill.putPoints( 2, 2, dim-1, dim/2-1, dim-1, dim/2 );
- }
- } else {
- if (dim > 6)
- bFill.resize(dim & 1 ? 3 : 4);
- bTop.resize((dim/2)*2);
- bBot.resize(dim & 1 ? dim + 1 : dim);
- bLeft.resize(dim > 4 ? 4 : 2);
- bLeft.putPoints(0, 2, 0,0, 0,dim-1);
- if (dim > 4)
- bLeft.putPoints(2, 2, 1,2, 1,dim-3);
- bTop.putPoints(0, 4, 1,0, 1,1, 2,1, 3,1);
- bBot.putPoints(0, 4, 1,dim-1, 1,dim-2, 2,dim-2, 3,dim-2);
-
- for(int i=0; i<dim/2-2 ; i++) {
- bTop.putPoints(i*2+4, 2, 2+i*2,2+i, 5+i*2, 2+i);
- bBot.putPoints(i*2+4, 2, 2+i*2,dim-3-i, 5+i*2,dim-3-i);
- }
- if (dim & 1) // odd number size: extra line
- bBot.putPoints(dim-1, 2, dim-3,dim/2, dim-1,dim/2);
- if (dim > 6) { // dim>6: must fill interior
- bFill.putPoints(0, 2, 1,dim-3, 1,2);
- if (dim & 1) // if size is an odd number
- bFill.setPoint(2, dim - 3, dim / 2);
- else
- bFill.putPoints(2, 2, dim-4,dim/2-1, dim-4,dim/2);
- }
- }
- } else {
- if (dim == 3) { // 3x3 arrow pattern
- bLeft.setPoints(4, 0,0, 0,2, 1,1, 1,1);
- bTop .setPoints(2, 1,0, 1,0);
- bBot .setPoints(2, 1,2, 2,1);
- }
- else { // 2x2 arrow pattern
- bLeft.setPoints(2, 0,0, 0,1);
- bTop .setPoints(2, 1,0, 1,0);
- bBot .setPoints(2, 1,1, 1,1);
- }
- }
-
- // We use rot() and translate() as it is more efficient that
- // matrix transformations on the painter, and because it still
- // works with QT_NO_TRANSFORMATIONS defined.
-
- if (pe == PE_IndicatorArrowUp || pe == PE_IndicatorArrowLeft) {
- if (vertical) {
- rot(bFill,3);
- rot(bLeft,3);
- rot(bTop,3);
- rot(bBot,3);
- bFill.translate(0, rect.height() - 1);
- bLeft.translate(0, rect.height() - 1);
- bTop.translate(0, rect.height() - 1);
- bBot.translate(0, rect.height() - 1);
- } else {
- rot(bFill,2);
- rot(bLeft,2);
- rot(bTop,2);
- rot(bBot,2);
- bFill.translate(rect.width() - 1, rect.height() - 1);
- bLeft.translate(rect.width() - 1, rect.height() - 1);
- bTop.translate(rect.width() - 1, rect.height() - 1);
- bBot.translate(rect.width() - 1, rect.height() - 1);
- }
- if (opt->state & State_Sunken)
- colspec = horizontal ? 0x2334 : 0x2343;
- else
- colspec = horizontal ? 0x1443 : 0x1434;
- } else {
- if (vertical) {
- rot(bFill,1);
- rot(bLeft,1);
- rot(bTop,1);
- rot(bBot,1);
- bFill.translate(rect.width() - 1, 0);
- bLeft.translate(rect.width() - 1, 0);
- bTop.translate(rect.width() - 1, 0);
- bBot.translate(rect.width() - 1, 0);
- }
- if (opt->state & State_Sunken)
- colspec = horizontal ? 0x2443 : 0x2434;
- else
- colspec = horizontal ? 0x1334 : 0x1343;
- }
- bFill.translate(rect.x(), rect.y());
- bLeft.translate(rect.x(), rect.y());
- bTop.translate(rect.x(), rect.y());
- bBot.translate(rect.x(), rect.y());
-
- const QColor *cols[5];
- if (opt->state & State_Enabled) {
- cols[0] = 0;
- cols[1] = &opt->palette.button().color();
- cols[2] = &opt->palette.mid().color();
- cols[3] = &opt->palette.light().color();
- cols[4] = &opt->palette.dark().color();
- } else {
- cols[0] = 0;
- cols[1] = &opt->palette.mid().color();
- cols[2] = &opt->palette.mid().color();
- cols[3] = &opt->palette.mid().color();
- cols[4] = &opt->palette.mid().color();
- }
-
-#define CMID *cols[(colspec>>12) & 0xf]
-#define CLEFT *cols[(colspec>>8) & 0xf]
-#define CTOP *cols[(colspec>>4) & 0xf]
-#define CBOT *cols[colspec & 0xf]
-
- QPen savePen = p->pen();
- QBrush saveBrush = p->brush();
- QPen pen(Qt::NoPen);
- QBrush brush = opt->palette.brush((opt->state & State_Enabled) ?
- QPalette::Button : QPalette::Mid);
- p->setPen(pen);
- p->setBrush(brush);
- p->drawPolygon(bFill);
- p->setBrush(Qt::NoBrush);
-
- p->setPen(CLEFT);
- p->drawPolyline(bLeft);
- p->setPen(CTOP);
- p->drawPolyline(bTop);
- p->setPen(CBOT);
- p->drawPolyline(bBot);
-
- p->setBrush(saveBrush);
- p->setPen(savePen);
-#undef CMID
-#undef CLEFT
-#undef CTOP
-#undef CBOT
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(opt->rect, QBrush(p->background().color(), Qt::Dense5Pattern));
- break; }
-
- case PE_IndicatorDockWidgetResizeHandle: {
- const int motifOffset = 10;
- int sw = proxy()->pixelMetric(PM_SplitterWidth);
- if (opt->state & State_Horizontal) {
- int yPos = opt->rect.y() + opt->rect.height() / 2;
- int kPos = opt->rect.right() - motifOffset - sw;
- int kSize = sw - 2;
-
- qDrawShadeLine(p, opt->rect.left(), yPos, kPos, yPos, opt->palette);
- qDrawShadePanel(p, kPos, yPos - sw / 2 + 1, kSize, kSize,
- opt->palette, false, 1, &opt->palette.brush(QPalette::Button));
- qDrawShadeLine(p, kPos + kSize - 1, yPos, opt->rect.right(), yPos, opt->palette);
- } else {
- int xPos = opt->rect.x() + opt->rect.width() / 2;
- int kPos = motifOffset;
- int kSize = sw - 2;
-
- qDrawShadeLine(p, xPos, opt->rect.top() + kPos + kSize - 1, xPos, opt->rect.bottom(), opt->palette);
- qDrawShadePanel(p, xPos - sw / 2 + 1, opt->rect.top() + kPos, kSize, kSize, opt->palette,
- false, 1, &opt->palette.brush(QPalette::Button));
- qDrawShadeLine(p, xPos, opt->rect.top(), xPos, opt->rect.top() + kPos, opt->palette);
- }
- break; }
-
- case PE_IndicatorMenuCheckMark: {
- const int markW = 6;
- const int markH = 6;
- int posX = opt->rect.x() + (opt->rect.width() - markW) / 2 - 1;
- int posY = opt->rect.y() + (opt->rect.height() - markH) / 2;
- int dfw = proxy()->pixelMetric(PM_DefaultFrameWidth);
-
- if (dfw < 2) {
- // Could do with some optimizing/caching...
- QPolygon a(7*2);
- int i, xx, yy;
- xx = posX;
- yy = 3 + posY;
- for (i=0; i<3; i++) {
- a.setPoint(2*i, xx, yy);
- a.setPoint(2*i+1, xx, yy+2);
- xx++; yy++;
- }
- yy -= 2;
- for (i=3; i<7; i++) {
- a.setPoint(2*i, xx, yy);
- a.setPoint(2*i+1, xx, yy+2);
- xx++; yy--;
- }
- if (! (opt->state & State_Enabled) && ! (opt->state & State_On)) {
- int pnt;
- p->setPen(opt->palette.highlightedText().color());
- QPoint offset(1,1);
- for (pnt = 0; pnt < (int)a.size(); pnt++)
- a[pnt] += offset;
- p->drawPolyline(a);
- for (pnt = 0; pnt < (int)a.size(); pnt++)
- a[pnt] -= offset;
- }
- p->setPen(opt->palette.text().color());
- p->drawPolyline(a);
-
- qDrawShadePanel(p, posX-2, posY-2, markW+4, markH+6, opt->palette, true, dfw);
- } else
- qDrawShadePanel(p, posX, posY, markW, markH, opt->palette, true, dfw,
- &opt->palette.brush(QPalette::Mid));
-
- break; }
-
- case PE_IndicatorProgressChunk:
- {
- bool vertical = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt))
- vertical = (pb2->orientation == Qt::Vertical);
- if (!vertical) {
- p->fillRect(opt->rect.x(), opt->rect.y(), opt->rect.width(),
- opt->rect.height(), opt->palette.brush(QPalette::Highlight));
- } else {
- p->fillRect(opt->rect.x(), opt->rect.y(), opt->rect.width(), opt->rect.height(),
- opt->palette.brush(QPalette::Highlight));
- }
- }
- break;
-
- default:
- QCommonStyle::drawPrimitive(pe, opt, p, w);
- break;
- }
-}
-
-
-/*!
- \reimp
-*/
-void QMotifStyle::drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *widget) const
-{
- switch(element) {
- case CE_Splitter: {
- QStyleOption handleOpt = *opt;
- if (handleOpt.state & State_Horizontal)
- handleOpt.state &= ~State_Horizontal;
- else
- handleOpt.state |= State_Horizontal;
- proxy()->drawPrimitive(PE_IndicatorDockWidgetResizeHandle, &handleOpt, p, widget);
- break; }
-
- case CE_ScrollBarSubLine:
- case CE_ScrollBarAddLine:{
- PrimitiveElement pe;
- if (element == CE_ScrollBarAddLine)
- pe = (opt->state & State_Horizontal) ? (opt->direction == Qt::LeftToRight ? PE_IndicatorArrowRight : PE_IndicatorArrowLeft) : PE_IndicatorArrowDown;
- else
- pe = (opt->state & State_Horizontal) ? (opt->direction == Qt::LeftToRight ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight) : PE_IndicatorArrowUp;
- QStyleOption arrowOpt = *opt;
- arrowOpt.state |= State_Enabled;
- proxy()->drawPrimitive(pe, &arrowOpt, p, widget);
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText)) {
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth);
- p->fillRect(opt->rect.adjusted(fw, fw, -fw, -fw), QBrush(p->background().color(), Qt::Dense5Pattern));
- }
- }break;
-
- case CE_ScrollBarSubPage:
- case CE_ScrollBarAddPage:
- p->fillRect(opt->rect, opt->palette.brush((opt->state & State_Enabled) ? QPalette::Mid : QPalette::Window));
- break;
-
- case CE_ScrollBarSlider: {
- QStyleOption bevelOpt = *opt;
- bevelOpt.state |= State_Raised;
- bevelOpt.state &= ~(State_Sunken | State_On);
- p->save();
- p->setBrushOrigin(bevelOpt.rect.topLeft());
- proxy()->drawPrimitive(PE_PanelButtonBevel, &bevelOpt, p, widget);
- p->restore();
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(opt->rect, QBrush(p->background().color(), Qt::Dense5Pattern));
- break; }
-
- case CE_RadioButton:
- case CE_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- bool isRadio = (element == CE_RadioButton);
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, btn, widget);
- proxy()->drawPrimitive(isRadio ? PE_IndicatorRadioButton : PE_IndicatorCheckBox,
- &subopt, p, widget);
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonContents
- : SE_CheckBoxContents, btn, widget);
- proxy()->drawControl(isRadio ? CE_RadioButtonLabel : CE_CheckBoxLabel, &subopt, p, widget);
- if ((btn->state & State_HasFocus) && (!focus || !focus->isVisible())) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*btn);
- fropt.rect = subElementRect(isRadio ? SE_RadioButtonFocusRect
- : SE_CheckBoxFocusRect, btn, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- break;
- case CE_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- proxy()->drawControl(CE_PushButtonBevel, btn, p, widget);
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(SE_PushButtonContents, btn, widget);
- proxy()->drawControl(CE_PushButtonLabel, &subopt, p, widget);
- if ((btn->state & State_HasFocus) && (!focus || !focus->isVisible())) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*btn);
- fropt.rect = subElementRect(SE_PushButtonFocusRect, btn, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- break;
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- int diw, x1, y1, x2, y2;
- p->setPen(opt->palette.foreground().color());
- p->setBrush(QBrush(opt->palette.button().color(), Qt::NoBrush));
- diw = proxy()->pixelMetric(PM_ButtonDefaultIndicator);
- opt->rect.getCoords(&x1, &y1, &x2, &y2);
- if (btn->features & (QStyleOptionButton::AutoDefaultButton|QStyleOptionButton::DefaultButton)) {
- x1 += diw;
- y1 += diw;
- x2 -= diw;
- y2 -= diw;
- }
- if (btn->features & QStyleOptionButton::DefaultButton) {
- if (diw == 0) {
- QPolygon a;
- a.setPoints(9,
- x1, y1, x2, y1, x2, y2, x1, y2, x1, y1+1,
- x2-1, y1+1, x2-1, y2-1, x1+1, y2-1, x1+1, y1+1);
- p->setPen(opt->palette.shadow().color());
- p->drawPolygon(a);
- x1 += 2;
- y1 += 2;
- x2 -= 2;
- y2 -= 2;
- } else {
- qDrawShadePanel(p, opt->rect.adjusted(1, 1, -1, -1), opt->palette, true);
- }
- }
- if (!(btn->features & QStyleOptionButton::Flat) ||
- (btn->state & (State_Sunken | State_On))) {
- QStyleOptionButton newOpt = *btn;
- newOpt.rect = QRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
- p->setBrushOrigin(p->brushOrigin());
- proxy()->drawPrimitive(PE_PanelButtonCommand, &newOpt, p, widget);
- }
- if (btn->features & QStyleOptionButton::HasMenu) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, btn, widget);
- QRect ir = btn->rect;
- QStyleOptionButton newBtn = *btn;
- newBtn.rect = QRect(ir.right() - mbi - 3, ir.y() + 4, mbi, ir.height() - 8);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
- }
- break;
- }
-
-#ifndef QT_NO_TABBAR
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- const int default_frame = proxy()->pixelMetric(PM_DefaultFrameWidth, tab, widget);
- const int frame_offset = (default_frame > 1) ? 1 : 0;
-
- if (tab->shape == QTabBar::RoundedNorth || tab->shape == QTabBar::RoundedEast ||
- tab->shape == QTabBar::RoundedSouth || tab->shape == QTabBar::RoundedWest) {
- p->save();
- QRect tabRect = opt->rect;
- QColor tabLight = opt->palette.light().color();
- QColor tabDark = opt->palette.dark().color();
-
- p->fillRect(opt->rect.adjusted(default_frame, default_frame,
- -default_frame, -default_frame),
- tab->palette.background());
-
- if(tab->shape == QTabBar::RoundedWest) {
- tabDark = opt->palette.light().color();
- tabLight = opt->palette.dark().color();
- tabRect = QRect(0, 0, tabRect.height(), tabRect.width());
- p->translate(opt->rect.left(), opt->rect.bottom());
- p->rotate(-90);
- } else if(tab->shape == QTabBar::RoundedSouth) {
- tabDark = opt->palette.light().color();
- tabLight = opt->palette.dark().color();
- tabRect = QRect(0, 0, tabRect.width(), tabRect.height());
- p->translate(opt->rect.right(), opt->rect.bottom());
- p->rotate(180);
- } else if(tab->shape == QTabBar::RoundedEast) {
- tabRect = QRect(0, 0, tabRect.height(), tabRect.width());
- p->translate(opt->rect.right(), opt->rect.top());
- p->rotate(90);
- }
-
- if (default_frame > 1) {
- p->setPen(tabLight);
- p->drawLine(tabRect.left(), tabRect.bottom(),
- tabRect.right(), tabRect.bottom());
- p->setPen(tabLight);
- p->drawLine(tabRect.left(), tabRect.bottom()-1,
- tabRect.right(), tabRect.bottom()-1);
- if (tabRect.left() == 0)
- p->drawPoint(tabRect.bottomLeft());
- } else {
- p->setPen(tabLight);
- p->drawLine(tabRect.left(), tabRect.bottom(),
- tabRect.right(), tabRect.bottom());
- }
-
- if (opt->state & State_Selected) {
- p->fillRect(QRect(tabRect.left()+1, tabRect.bottom()-frame_offset,
- tabRect.width()-3, 2),
- tab->palette.brush(QPalette::Active, QPalette::Background));
- p->setPen(tab->palette.background().color());
- p->drawLine(tabRect.left()+1, tabRect.bottom(),
- tabRect.left()+1, tabRect.top()+2);
- p->setPen(tabLight);
- } else {
- p->setPen(tabLight);
- }
- p->drawLine(tabRect.left(), tabRect.bottom()-1,
- tabRect.left(), tabRect.top() + 2);
- p->drawPoint(tabRect.left()+1, tabRect.top() + 1);
- p->drawLine(tabRect.left()+2, tabRect.top(),
- tabRect.right() - 2, tabRect.top());
- p->drawPoint(tabRect.left(), tabRect.bottom());
-
- if (default_frame > 1) {
- p->drawLine(tabRect.left()+1, tabRect.bottom(),
- tabRect.left()+1, tabRect.top() + 2);
- p->drawLine(tabRect.left()+2, tabRect.top()+1,
- tabRect.right() - 2, tabRect.top()+1);
- }
-
- p->setPen(tabDark);
- p->drawLine(tabRect.right() - 1, tabRect.top() + 2,
- tabRect.right() - 1, tabRect.bottom() - 1 +
- ((opt->state & State_Selected) ? frame_offset : -frame_offset));
- if (default_frame > 1) {
- p->drawPoint(tabRect.right() - 1, tabRect.top() + 1);
- p->drawLine(tabRect.right(), tabRect.top() + 2, tabRect.right(),
- tabRect.bottom() -
- ((opt->state & State_Selected) ?
- ((tab->position == QStyleOptionTab::End) ? 0:1):1+frame_offset));
- p->drawPoint(tabRect.right() - 1, tabRect.top() + 1);
- }
- p->restore();
- } else {
- QCommonStyle::drawControl(element, opt, p, widget);
- }
- break; }
-#endif // QT_NO_TABBAR
- case CE_ProgressBarGroove:
- qDrawShadePanel(p, opt->rect, opt->palette, true, 2);
- break;
-
- case CE_ProgressBarLabel:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- QTransform oldMatrix = p->transform();
- QRect rect = pb->rect;
- bool vertical = false;
- bool invert = false;
- bool bottomToTop = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- vertical = (pb2->orientation == Qt::Vertical);
- invert = pb2->invertedAppearance;
- bottomToTop = pb2->bottomToTop;
- }
- if (vertical) {
- QTransform m;
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- if (bottomToTop) {
- m.translate(0.0, rect.width());
- m.rotate(-90);
- } else {
- m.translate(rect.height(), 0.0);
- m.rotate(90);
- }
- p->setTransform(m, true);
- }
- const int unit_width = proxy()->pixelMetric(PM_ProgressBarChunkWidth, opt, widget);
- int u = rect.width() / unit_width;
- int p_v = pb->progress - pb->minimum;
- int t_s = qMax(0, pb->maximum - pb->minimum);
- if (u > 0 && pb->progress >= INT_MAX / u && t_s >= u) {
- // scale down to something usable.
- p_v /= u;
- t_s /= u;
- }
- if (pb->textVisible && t_s) {
- int nu = (u * p_v + t_s/2) / t_s;
- int x = unit_width * nu;
- QRect left(rect.x(), rect.y(), x, rect.height());
- QRect right(rect.x() + x, rect.y(), rect.width() - x, rect.height());
- Qt::LayoutDirection dir;
- dir = vertical ? (bottomToTop ? Qt::LeftToRight : Qt::RightToLeft) : pb->direction;
- if (invert)
- dir = (dir == Qt::LeftToRight) ? Qt::RightToLeft : Qt::LeftToRight;
- const QRect highlighted = visualRect(dir, rect, left);
- const QRect background = visualRect(dir, rect, right);
- p->setPen(opt->palette.highlightedText().color());
- p->setClipRect(highlighted);
- p->drawText(rect, Qt::AlignCenter | Qt::TextSingleLine, pb->text);
-
- if (pb->progress != pb->maximum) {
- p->setClipRect(background);
- p->setPen(opt->palette.highlight().color());
- p->drawText(rect, Qt::AlignCenter | Qt::TextSingleLine, pb->text);
- }
- }
- p->setTransform(oldMatrix, false);
- break;
- }
-
- case CE_MenuTearoff: {
- if(opt->state & State_Selected) {
- if(pixelMetric(PM_MenuPanelWidth, opt, widget) > 1)
- qDrawShadePanel(p, opt->rect.x(), opt->rect.y(), opt->rect.width(),
- opt->rect.height(), opt->palette, false, motifItemFrame,
- &opt->palette.brush(QPalette::Button));
- else
- qDrawShadePanel(p, opt->rect.x()+1, opt->rect.y()+1, opt->rect.width()-2,
- opt->rect.height()-2, opt->palette, true, 1, &opt->palette.brush(QPalette::Button));
- } else {
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Button));
- }
- p->setPen(QPen(opt->palette.dark().color(), 1, Qt::DashLine));
- p->drawLine(opt->rect.x()+2, opt->rect.y()+opt->rect.height()/2-1, opt->rect.x()+opt->rect.width()-4,
- opt->rect.y()+opt->rect.height()/2-1);
- p->setPen(QPen(opt->palette.light().color(), 1, Qt::DashLine));
- p->drawLine(opt->rect.x()+2, opt->rect.y()+opt->rect.height()/2, opt->rect.x()+opt->rect.width()-4,
- opt->rect.y()+opt->rect.height()/2);
- break; }
-
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- int maxpmw = menuitem->maxIconWidth;
- if(menuitem->menuHasCheckableItems)
- maxpmw = qMax(maxpmw, motifCheckMarkSpace);
-
- int x, y, w, h;
- opt->rect.getRect(&x, &y, &w, &h);
-
- if (menuitem->menuItemType == QStyleOptionMenuItem::Separator) { // draw separator
- int textWidth = 0;
- if (!menuitem->text.isEmpty()) {
- QFont oldFont = p->font();
- p->setFont(menuitem->font);
- p->fillRect(x, y, w, h, opt->palette.brush(QPalette::Button));
- proxy()->drawItemText(p, menuitem->rect.adjusted(10, 0, -5, 0), Qt::AlignLeft | Qt::AlignVCenter,
- menuitem->palette, menuitem->state & State_Enabled, menuitem->text,
- QPalette::Text);
- textWidth = menuitem->fontMetrics.width(menuitem->text) + 10;
- y += menuitem->fontMetrics.height() / 2;
- p->setFont(oldFont);
- }
- p->setPen(opt->palette.dark().color());
- p->drawLine(x, y, x + 5, y);
- p->drawLine(x + 5 + textWidth, y, x+w, y);
- p->setPen(opt->palette.light().color());
- p->drawLine(x, y + 1, x + 5, y + 1);
- p->drawLine(x + 5 + textWidth, y + 1, x+w, y + 1);
- return;
- }
-
- int pw = motifItemFrame;
- if((opt->state & State_Selected) && (opt->state & State_Enabled)) { // active item frame
- if(pixelMetric(PM_MenuPanelWidth, opt) > 1)
- qDrawShadePanel(p, x, y, w, h, opt->palette, false, pw,
- &opt->palette.brush(QPalette::Button));
- else
- qDrawShadePanel(p, x+1, y+1, w-2, h-2, opt->palette, true, 1,
- &opt->palette.brush(QPalette::Button));
- } else { // incognito frame
- p->fillRect(x, y, w, h, opt->palette.brush(QPalette::Button));
- }
-
- QRect vrect = visualRect(opt->direction, opt->rect,
- QRect(x+motifItemFrame, y+motifItemFrame, maxpmw,
- h-2*motifItemFrame));
- int xvis = vrect.x();
- if (menuitem->checked) {
- if(!menuitem->icon.isNull())
- qDrawShadePanel(p, xvis, y+motifItemFrame, maxpmw, h-2*motifItemFrame,
- opt->palette, true, 1, &opt->palette.brush(QPalette::Midlight));
- } else if (!(opt->state & State_Selected)) {
- p->fillRect(xvis, y+motifItemFrame, maxpmw, h-2*motifItemFrame,
- opt->palette.brush(QPalette::Button));
- }
-
- if(!menuitem->icon.isNull()) { // draw icon
- QIcon::Mode mode = QIcon::Normal; // no disabled icons in Motif
- if ((opt->state & State_Selected) && !!(opt->state & State_Enabled))
- mode = QIcon::Active;
- QPixmap pixmap;
- if (menuitem->checkType != QStyleOptionMenuItem::NotCheckable && menuitem->checked)
- pixmap = menuitem->icon.pixmap(pixelMetric(PM_SmallIconSize, opt, widget), mode, QIcon::On);
- else
- pixmap = menuitem->icon.pixmap(pixelMetric(PM_SmallIconSize, opt, widget), mode);
-
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vrect.center());
- p->setPen(opt->palette.text().color());
- p->drawPixmap(pmr.topLeft(), pixmap);
-
- } else if (menuitem->checkType != QStyleOptionMenuItem::NotCheckable) { // just "checking"...
- int mh = h - 2*motifItemFrame;
-
- QStyleOptionButton newMenuItem;
- newMenuItem.state = menuitem->checked ? State_On : State_None;
- if (opt->state & State_Enabled) {
- newMenuItem.state |= State_Enabled;
- if (menuitem->state & State_Sunken)
- newMenuItem.state |= State_Sunken;
- }
- if (menuitem->checkType & QStyleOptionMenuItem::Exclusive) {
- newMenuItem.rect.setRect(xvis + 2, y + motifItemFrame + mh / 4, 11, 11);
- proxy()->drawPrimitive(PE_IndicatorRadioButton, &newMenuItem, p, widget);
- } else {
- newMenuItem.rect.setRect(xvis + 5, y + motifItemFrame + mh / 4, 9, 9);
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &newMenuItem, p, widget);
- }
- }
-
- p->setPen(opt->palette.buttonText().color());
-
- QColor discol;
- if (!(opt->state & State_Enabled)) {
- discol = opt->palette.text().color();
- p->setPen(discol);
- }
-
- int xm = motifItemFrame + maxpmw + motifItemHMargin;
-
- vrect = visualRect(opt->direction, opt->rect,
- QRect(x+xm, y+motifItemVMargin, w-xm-menuitem->tabWidth,
- h-2*motifItemVMargin));
- xvis = vrect.x();
-
- QString s = menuitem->text;
- if (!s.isNull()) { // draw text
- int t = s.indexOf(QLatin1Char('\t'));
- int m = motifItemVMargin;
- int text_flags = Qt::AlignVCenter|Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- text_flags |= Qt::AlignLeft;
- QFont oldFont = p->font();
- p->setFont(menuitem->font);
- if (t >= 0) { // draw tab text
- QRect vr = visualRect(opt->direction, opt->rect,
- QRect(x+w-menuitem->tabWidth-motifItemHMargin-motifItemFrame,
- y+motifItemVMargin, menuitem->tabWidth,
- h-2*motifItemVMargin));
- int xv = vr.x();
- QRect tr(xv, y+m, menuitem->tabWidth, h-2*m);
- p->drawText(tr, text_flags, s.mid(t+1));
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(tr, QBrush(p->background().color(), Qt::Dense5Pattern));
- s = s.left(t);
- }
- QRect tr(xvis, y+m, w - xm - menuitem->tabWidth + 1, h-2*m);
- p->drawText(tr, text_flags, s.left(t));
- p->setFont(oldFont);
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(tr, QBrush(p->background().color(), Qt::Dense5Pattern));
- }
- if (menuitem->menuItemType == QStyleOptionMenuItem::SubMenu) { // draw sub menu arrow
- int dim = (h-2*motifItemFrame) / 2;
- QStyle::PrimitiveElement arrow = (opt->direction == Qt::RightToLeft ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight);
- QStyleOption arrowOpt = *opt;
- arrowOpt.rect = visualRect(opt->direction, opt->rect,
- QRect(x+w - motifArrowHMargin - motifItemFrame - dim,
- y+h/2-dim/2, dim, dim));
- if ((opt->state & State_Selected))
- arrowOpt.state = (State_Sunken | ((opt->state & State_Enabled) ? State_Enabled : State_None));
- else
- arrowOpt.state = ((opt->state & State_Enabled) ? State_Enabled : State_None);
- proxy()->drawPrimitive(arrow, &arrowOpt, p, widget);
- }
- break; }
-
- case CE_MenuBarItem:
- if (opt->state & State_Selected) // active item
- qDrawShadePanel(p, opt->rect, opt->palette, false, motifItemFrame,
- &opt->palette.brush(QPalette::Button));
- else // other item
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Button));
- QCommonStyle::drawControl(element, opt, p, widget);
- break;
-
- case CE_HeaderSection:
- p->save();
- p->setBrushOrigin(opt->rect.topLeft());
- qDrawShadePanel(p, opt->rect, opt->palette, bool(opt->state & (State_Sunken|State_On)),
- proxy()->pixelMetric(PM_DefaultFrameWidth),
- &opt->palette.brush((opt->state & State_Sunken) ? QPalette::Mid : QPalette::Button));
- p->restore();
- break;
- case CE_RubberBand: {
- QPixmap tiledPixmap(16, 16);
- QPainter pixmapPainter(&tiledPixmap);
- pixmapPainter.setPen(Qt::NoPen);
- pixmapPainter.setBrush(Qt::Dense4Pattern);
- pixmapPainter.setBackground(QBrush(opt->palette.base()));
- pixmapPainter.setBackgroundMode(Qt::OpaqueMode);
- pixmapPainter.drawRect(0, 0, tiledPixmap.width(), tiledPixmap.height());
- pixmapPainter.end();
- // ### workaround for borked XRENDER
- tiledPixmap = QPixmap::fromImage(tiledPixmap.toImage());
-
- p->save();
- QRect r = opt->rect;
- QStyleHintReturnMask mask;
- if (styleHint(QStyle::SH_RubberBand_Mask, opt, widget, &mask))
- p->setClipRegion(mask.region);
- p->drawTiledPixmap(r.x(), r.y(), r.width(), r.height(), tiledPixmap);
- p->restore();
- }
- break;
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- QRect rect = pb->rect;
- bool vertical = false;
- bool inverted = false;
-
- // Get extra style options if version 2
- const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt);
- if (pb2) {
- vertical = (pb2->orientation == Qt::Vertical);
- inverted = pb2->invertedAppearance;
- }
-
- QTransform m;
- if (vertical) {
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- m.rotate(90);
- m.translate(0, -(rect.height() + rect.y()*2));
- }
-
- QPalette pal2 = pb->palette;
- // Correct the highlight color if it is the same as the background
- if (pal2.highlight() == pal2.background())
- pal2.setColor(QPalette::Highlight, pb->palette.color(QPalette::Active,
- QPalette::Highlight));
- bool reverse = ((!vertical && (pb->direction == Qt::RightToLeft)) || vertical);
- if (inverted)
- reverse = !reverse;
- int w = rect.width();
- if (pb->minimum == 0 && pb->maximum == 0) {
- QRect progressBar;
- Q_D(const QMotifStyle);
- // draw busy indicator
- int x = (d->animateStep*8)% (w * 2);
- if (x > w)
- x = 2 * w - x;
- x = reverse ? rect.right() - x : x + rect.x();
- p->setTransform(m, true);
- p->setPen(QPen(pal2.highlight().color(), 4));
- p->drawLine(x, rect.y(), x, rect.height());
-
- } else
- QCommonStyle::drawControl(element, opt, p, widget);
- }
- break;
-#endif // QT_NO_PROGRESSBAR
- default:
- QCommonStyle::drawControl(element, opt, p, widget);
- break; }
-}
-
-static int get_combo_extra_width(int h, int w, int *return_awh=0)
-{
- int awh,
- tmp;
- if (h < 8) {
- awh = 6;
- } else if (h < 14) {
- awh = h - 2;
- } else {
- awh = h/2;
- }
- tmp = (awh * 3) / 2;
- if (tmp > w / 2) {
- awh = w / 2 - 3;
- tmp = w / 2 + 3;
- }
-
- if (return_awh)
- *return_awh = awh;
-
- return tmp;
-}
-
-static void get_combo_parameters(const QRect &r,
- int &ew, int &awh, int &ax,
- int &ay, int &sh, int &dh,
- int &sy)
-{
- ew = get_combo_extra_width(r.height(), r.width(), &awh);
-
- sh = (awh+3)/4;
- if (sh < 3)
- sh = 3;
- dh = sh/2 + 1;
-
- ay = r.y() + (r.height()-awh-sh-dh)/2;
- if (ay < 0) {
- //panic mode
- ay = 0;
- sy = r.height();
- } else {
- sy = ay+awh+dh;
- }
- ax = r.x() + r.width() - ew;
- ax += (ew-awh)/2;
-}
-
-/*!
- \reimp
-*/
-void QMotifStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *widget) const
-{
- switch (cc) {
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- QRect button, menuarea;
- button = proxy()->subControlRect(cc, toolbutton, SC_ToolButton, widget);
- menuarea = proxy()->subControlRect(cc, toolbutton, SC_ToolButtonMenu, widget);
-
- State bflags = toolbutton->state & ~State_Sunken;
- if (bflags & State_AutoRaise) {
- if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) {
- bflags &= ~State_Raised;
- }
- }
- State mflags = bflags;
- if (toolbutton->state & State_Sunken) {
- if (toolbutton->activeSubControls & SC_ToolButton)
- bflags |= State_Sunken;
- mflags |= State_Sunken;
- }
-
- QStyleOption tool(0);
- tool.palette = toolbutton->palette;
- if (toolbutton->subControls & SC_ToolButton) {
- if (bflags & (State_Sunken | State_On | State_Raised)) {
- tool.rect = button;
- tool.state = bflags;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- }
- }
-
- if ((toolbutton->state & State_HasFocus) && (!focus || !focus->isVisible())) {
- QStyleOptionFocusRect fr;
- fr.QStyleOption::operator=(*toolbutton);
- fr.rect = toolbutton->rect.adjusted(3, 3, -3, -3);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fr, p, widget);
- }
- QStyleOptionToolButton label = *toolbutton;
- label.state = bflags;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- label.rect = button.adjusted(fw, fw, -fw, -fw);
- proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget);
-
- if (toolbutton->subControls & SC_ToolButtonMenu) {
- tool.rect = menuarea;
- tool.state = mflags;
- if (mflags & (State_Sunken | State_On | State_Raised))
- proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, p, widget);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, p, widget);
- } else if (toolbutton->features & QStyleOptionToolButton::HasMenu) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolbutton, widget);
- QRect ir = toolbutton->rect;
- QStyleOptionToolButton newBtn = *toolbutton;
- newBtn.rect = QRect(ir.right() + 5 - mbi, ir.height() - mbi + 4, mbi - 6, mbi - 6);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
- }
- }
- break;
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QStyleOptionSpinBox copy = *spinbox;
- PrimitiveElement pe;
-
- if (spinbox->frame && (spinbox->subControls & SC_SpinBoxFrame)) {
- QRect r = proxy()->subControlRect(CC_SpinBox, spinbox, SC_SpinBoxFrame, widget);
- qDrawShadePanel(p, r, opt->palette, false, proxy()->pixelMetric(PM_SpinBoxFrameWidth));
-
- int fw = proxy()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- r = proxy()->subControlRect(CC_SpinBox, spinbox, SC_SpinBoxEditField, widget).adjusted(-fw,-fw,fw,fw);
- QStyleOptionFrame lineOpt;
- lineOpt.QStyleOption::operator=(*opt);
- lineOpt.rect = r;
- lineOpt.lineWidth = fw;
- lineOpt.midLineWidth = 0;
- lineOpt.state |= QStyle::State_Sunken;
- proxy()->drawPrimitive(QStyle::PE_FrameLineEdit, &lineOpt, p, widget);
- }
-
- if (spinbox->subControls & SC_SpinBoxUp) {
- copy.subControls = SC_SpinBoxUp;
- QPalette pal2 = spinbox->palette;
- if (!(spinbox->stepEnabled & QAbstractSpinBox::StepUpEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
-
- copy.palette = pal2;
-
- if (spinbox->activeSubControls == SC_SpinBoxUp && (spinbox->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (spinbox->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinPlus
- : PE_IndicatorSpinUp);
-
- copy.rect = proxy()->subControlRect(CC_SpinBox, spinbox, SC_SpinBoxUp, widget);
- proxy()->drawPrimitive(pe, &copy, p, widget);
- }
-
- if (spinbox->subControls & SC_SpinBoxDown) {
- copy.subControls = SC_SpinBoxDown;
- copy.state = spinbox->state;
- QPalette pal2 = spinbox->palette;
- if (!(spinbox->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
-
- if (spinbox->activeSubControls == SC_SpinBoxDown && (spinbox->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (spinbox->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinMinus
- : PE_IndicatorSpinDown);
-
- copy.rect = proxy()->subControlRect(CC_SpinBox, spinbox, SC_SpinBoxDown, widget);
- proxy()->drawPrimitive(pe, &copy, p, widget);
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QRect groove = proxy()->subControlRect(CC_Slider, opt, SC_SliderGroove, widget),
- handle = proxy()->subControlRect(CC_Slider, opt, SC_SliderHandle, widget);
-
- if ((opt->subControls & SC_SliderGroove) && groove.isValid()) {
- qDrawShadePanel(p, groove, opt->palette, true, proxy()->pixelMetric(PM_DefaultFrameWidth),
- &opt->palette.brush((opt->state & State_Enabled) ? QPalette::Mid : QPalette::Window));
- if ((opt->state & State_HasFocus) && (!focus || !focus->isVisible())) {
- QStyleOption focusOpt = *opt;
- focusOpt.rect = subElementRect(SE_SliderFocusRect, opt, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &focusOpt, p, widget);
- }
- }
-
- if ((opt->subControls & SC_SliderHandle) && handle.isValid()) {
- QStyleOption bevelOpt = *opt;
- bevelOpt.state = (opt->state | State_Raised) & ~State_Sunken;
- bevelOpt.rect = handle;
- p->save();
- p->setBrushOrigin(bevelOpt.rect.topLeft());
- proxy()->drawPrimitive(PE_PanelButtonBevel, &bevelOpt, p, widget);
- p->restore();
-
- if (slider->orientation == Qt::Horizontal) {
- int mid = handle.x() + handle.width() / 2;
- qDrawShadeLine(p, mid, handle.y(), mid, handle.y() + handle.height() - 2,
- opt->palette, true, 1);
- } else {
- int mid = handle.y() + handle.height() / 2;
- qDrawShadeLine(p, handle.x(), mid, handle.x() + handle.width() - 2, mid, opt->palette,
- true, 1);
- }
- if (!(opt->state & State_Enabled) && proxy()->styleHint(SH_DitherDisabledText))
- p->fillRect(handle, QBrush(p->background().color(), Qt::Dense5Pattern));
- }
-
- if (slider->subControls & SC_SliderTickmarks) {
- QStyleOptionSlider tmpSlider = *slider;
- tmpSlider.subControls = SC_SliderTickmarks;
- int frameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth);
- tmpSlider.rect.translate(frameWidth - 1, 0);
- QCommonStyle::drawComplexControl(cc, &tmpSlider, p, widget);
- }
- }
- break;
-#endif // QT_NO_SLIDER
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- if (opt->subControls & SC_ComboBoxArrow) {
- int awh, ax, ay, sh, sy, dh, ew;
- int fw = cb->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth, opt, widget) : 0;
-
- if (cb->frame) {
- QStyleOptionButton btn;
- btn.QStyleOption::operator=(*cb);
- btn.state |= QStyle::State_Raised;
- proxy()->drawPrimitive(PE_PanelButtonCommand, &btn, p, widget);
- } else {
- p->fillRect(opt->rect, opt->palette.brush(QPalette::Button));
- }
-
- QRect tr = opt->rect;
- tr.adjust(fw, fw, -fw, -fw);
- get_combo_parameters(tr, ew, awh, ax, ay, sh, dh, sy);
-
- QRect ar = QStyle::visualRect(opt->direction, opt->rect, QRect(ax,ay,awh,awh));
-
- QStyleOption arrowOpt = *opt;
- arrowOpt.rect = ar;
- arrowOpt.state |= State_Enabled;
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, widget);
-
-
- // draws the shaded line under the arrow
- p->setPen(opt->palette.light().color());
- p->drawLine(ar.x(), sy, ar.x()+awh-1, sy);
- p->drawLine(ar.x(), sy, ar.x(), sy+sh-1);
- p->setPen(opt->palette.dark().color());
- p->drawLine(ar.x()+1, sy+sh-1, ar.x()+awh-1, sy+sh-1);
- p->drawLine(ar.x()+awh-1, sy+1, ar.x()+awh-1, sy+sh-1);
-
- if ((cb->state & State_HasFocus) && (!focus || !focus->isVisible())) {
- QStyleOptionFocusRect focus;
- focus.QStyleOption::operator=(*opt);
- focus.rect = subElementRect(SE_ComboBoxFocusRect, opt, widget);
- focus.backgroundColor = opt->palette.button().color();
- proxy()->drawPrimitive(PE_FrameFocusRect, &focus, p, widget);
- }
- }
-
- if (opt->subControls & SC_ComboBoxEditField) {
- if (cb->editable) {
- QRect er = proxy()->subControlRect(CC_ComboBox, opt, SC_ComboBoxEditField, widget);
- er.adjust(-1, -1, 1, 1);
- qDrawShadePanel(p, er, opt->palette, true, 1,
- &opt->palette.brush(QPalette::Base));
- }
- }
- p->setPen(opt->palette.buttonText().color());
- }
- break;
-
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar: {
- if (opt->subControls & SC_ScrollBarGroove)
- qDrawShadePanel(p, opt->rect, opt->palette, true,
- proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget),
- &opt->palette.brush((opt->state & State_Enabled) ? QPalette::Mid : QPalette::Window));
-
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QStyleOptionSlider newScrollbar = *scrollbar;
- if (scrollbar->minimum == scrollbar->maximum)
- newScrollbar.state |= State_Enabled; // make sure that the slider is drawn.
- QCommonStyle::drawComplexControl(cc, &newScrollbar, p, widget);
- }
- break; }
-#endif
-
- case CC_Q3ListView:
- if (opt->subControls & (SC_Q3ListViewBranch | SC_Q3ListViewExpand)) {
- int i;
- if (opt->subControls & SC_Q3ListView)
- QCommonStyle::drawComplexControl(cc, opt, p, widget);
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- QStyleOptionQ3ListViewItem item = lv->items.at(0);
- int y = opt->rect.y();
- int c;
- QPolygon dotlines;
- if ((opt->activeSubControls & SC_All) && (opt->subControls & SC_Q3ListViewExpand)) {
- c = 2;
- dotlines.resize(2);
- dotlines[0] = QPoint(opt->rect.right(), opt->rect.top());
- dotlines[1] = QPoint(opt->rect.right(), opt->rect.bottom());
- } else {
- int linetop = 0, linebot = 0;
- // each branch needs at most two lines, ie. four end points
- dotlines.resize(item.childCount * 4);
- c = 0;
-
- // skip the stuff above the exposed rectangle
- for (i = 1; i < lv->items.size(); ++i) {
- QStyleOptionQ3ListViewItem child = lv->items.at(i);
- if (child.height + y > 0)
- break;
- y += child.totalHeight;
- }
-
- int bx = opt->rect.width() / 2;
-
- // paint stuff in the magical area
- while (i < lv->items.size() && y < lv->rect.height()) {
- QStyleOptionQ3ListViewItem child = lv->items.at(i);
- if (child.features & QStyleOptionQ3ListViewItem::Visible) {
- int lh;
- if (!(item.features & QStyleOptionQ3ListViewItem::MultiLine))
- lh = child.height;
- else
- lh = p->fontMetrics().height() + 2 * lv->itemMargin;
- lh = qMax(lh, QApplication::globalStrut().height());
- if (lh % 2 > 0)
- lh++;
- linebot = y + lh/2;
- if ((child.features & QStyleOptionQ3ListViewItem::Expandable || child.childCount > 0) &&
- child.height > 0) {
- // needs a box
- p->setPen(opt->palette.text().color());
- p->drawRect(bx-4, linebot-4, 9, 9);
- QPolygon a;
- if ((child.state & State_Open))
- a.setPoints(3, bx-2, linebot-2,
- bx, linebot+2,
- bx+2, linebot-2); //Qt::RightArrow
- else
- a.setPoints(3, bx-2, linebot-2,
- bx+2, linebot,
- bx-2, linebot+2); //Qt::DownArrow
- p->setBrush(opt->palette.text());
- p->drawPolygon(a);
- p->setBrush(Qt::NoBrush);
- // dotlinery
- dotlines[c++] = QPoint(bx, linetop);
- dotlines[c++] = QPoint(bx, linebot - 5);
- dotlines[c++] = QPoint(bx + 5, linebot);
- dotlines[c++] = QPoint(opt->rect.width(), linebot);
- linetop = linebot + 5;
- } else {
- // just dotlinery
- dotlines[c++] = QPoint(bx+1, linebot);
- dotlines[c++] = QPoint(opt->rect.width(), linebot);
- }
- y += child.totalHeight;
- }
- ++i;
- }
-
- // Expand line height to edge of rectangle if there's any
- // visible child below
- while (i < lv->items.size() && lv->items.at(i).height <= 0)
- ++i;
- if (i < lv->items.size())
- linebot = opt->rect.height();
-
- if (linetop < linebot) {
- dotlines[c++] = QPoint(bx, linetop);
- dotlines[c++] = QPoint(bx, linebot);
- }
- }
-
- int line; // index into dotlines
- p->setPen(opt->palette.text().color());
- if (opt->subControls & SC_Q3ListViewBranch) for(line = 0; line < c; line += 2) {
- p->drawLine(dotlines[line].x(), dotlines[line].y(),
- dotlines[line+1].x(), dotlines[line+1].y());
- }
- }
- break; }
-
- default:
- QCommonStyle::drawComplexControl(cc, opt, p, widget);
- break;
- }
-}
-
-
-/*! \reimp */
-int QMotifStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt,
- const QWidget *widget) const
-{
- int ret = 0;
-
- switch(pm) {
- case PM_ButtonDefaultIndicator:
- ret = 5;
- break;
-
- case PM_CheckBoxLabelSpacing:
- case PM_RadioButtonLabelSpacing:
- ret = 10;
- break;
-
- case PM_ToolBarFrameWidth:
- ret = proxy()->pixelMetric(PM_DefaultFrameWidth);
- break;
-
- case PM_ToolBarItemMargin:
- ret = 1;
- break;
-
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- ret = 0;
- break;
-
- case PM_SplitterWidth:
- ret = qMax(10, QApplication::globalStrut().width());
- break;
-
- case PM_SliderLength:
- ret = 30;
- break;
-
- case PM_SliderThickness:
- ret = 16 + 4 * proxy()->pixelMetric(PM_DefaultFrameWidth);
- break;
-#ifndef QT_NO_SLIDER
- case PM_SliderControlThickness:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int space = (sl->orientation == Qt::Horizontal) ? sl->rect.height() : sl->rect.width();
- int ticks = sl->tickPosition;
- int n = 0;
- if (ticks & QSlider::TicksAbove)
- n++;
- if (ticks & QSlider::TicksBelow)
- n++;
- if (!n) {
- ret = space;
- break;
- }
-
- int thick = 6; // Magic constant to get 5 + 16 + 5
-
- space -= thick;
- //### the two sides may be unequal in size
- if (space > 0)
- thick += (space * 2) / (n + 2);
- ret = thick;
- }
- break;
-
- case PM_SliderSpaceAvailable:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- if (sl->orientation == Qt::Horizontal)
- ret = sl->rect.width() - proxy()->pixelMetric(PM_SliderLength, opt, widget) - 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- else
- ret = sl->rect.height() - proxy()->pixelMetric(PM_SliderLength, opt, widget) - 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- }
- break;
-#endif // QT_NO_SLIDER
- case PM_DockWidgetFrameWidth:
- ret = 2;
- break;
-
- case PM_DockWidgetHandleExtent:
- ret = 9;
- break;
-
- case PM_ProgressBarChunkWidth:
- ret = 1;
- break;
-
- case PM_ExclusiveIndicatorWidth:
- case PM_ExclusiveIndicatorHeight:
- ret = 13;
- break;
-
- case PM_MenuBarHMargin:
- ret = 2; // really ugly, but Motif
- break;
-
- case PM_MenuButtonIndicator:
- if (!opt)
- ret = 12;
- else
- ret = qMax(12, (opt->rect.height() - 4) / 3);
- break;
- default:
- ret = QCommonStyle::pixelMetric(pm, opt, widget);
- break;
- }
- return ret;
-}
-
-
-/*!
- \reimp
-*/
-QRect
-QMotifStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const
-{
- switch (cc) {
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- int fw = spinbox->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
- QSize bs;
- bs.setHeight(opt->rect.height()/2 - fw);
- bs.setWidth(qMin(bs.height() * 8 / 5, opt->rect.width() / 4)); // 1.6 -approximate golden mean
- bs = bs.expandedTo(QApplication::globalStrut());
- int y = fw + spinbox->rect.y();
- int x, lx, rx;
- x = spinbox->rect.x() + opt->rect.width() - fw - bs.width();
- lx = fw;
- rx = x - fw * 2;
- const int margin = spinbox->frame ? 4 : 0;
- switch (sc) {
- case SC_SpinBoxUp:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- return visualRect(spinbox->direction, spinbox->rect,
- QRect(x, y, bs.width(), bs.height() - 1));
- case SC_SpinBoxDown:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- return visualRect(spinbox->direction, spinbox->rect,
- QRect(x, y + bs.height() + 1, bs.width(), bs.height() - 1));
- case SC_SpinBoxEditField:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return visualRect(spinbox->direction, spinbox->rect,
- QRect(lx + margin, y + margin,
- spinbox->rect.width() - 2*fw - 2*margin,
- spinbox->rect.height() - 2*fw - 2*margin));
-
- return visualRect(spinbox->direction, spinbox->rect,
- QRect(lx + margin, y + margin, rx - margin,
- spinbox->rect.height() - 2*fw - 2 * margin));
- case SC_SpinBoxFrame:
- return visualRect(spinbox->direction, spinbox->rect, spinbox->rect);
- default:
- break;
- }
- break; }
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- if (sc == SC_SliderHandle) {
- int tickOffset = proxy()->pixelMetric(PM_SliderTickmarkOffset, opt, widget);
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, opt, widget);
- bool horizontal = slider->orientation == Qt::Horizontal;
- int len = proxy()->pixelMetric(PM_SliderLength, opt, widget);
- int motifBorder = proxy()->pixelMetric(PM_DefaultFrameWidth);
- int sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum, slider->sliderPosition,
- horizontal ? slider->rect.width() - len - 2 * motifBorder
- : slider->rect.height() - len - 2 * motifBorder,
- slider->upsideDown);
- if (horizontal)
- return visualRect(slider->direction, slider->rect,
- QRect(sliderPos + motifBorder, tickOffset + motifBorder, len,
- thickness - 2 * motifBorder));
- return visualRect(slider->direction, slider->rect,
- QRect(tickOffset + motifBorder, sliderPos + motifBorder,
- thickness - 2 * motifBorder, len));
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int dfw = proxy()->pixelMetric(PM_DefaultFrameWidth);
- QRect rect = visualRect(scrollbar->direction, scrollbar->rect,
- QCommonStyle::subControlRect(cc, scrollbar, sc, widget));
- if (sc == SC_ScrollBarSlider) {
- if (scrollbar->orientation == Qt::Horizontal)
- rect.adjust(-dfw, dfw, dfw, -dfw);
- else
- rect.adjust(dfw, -dfw, -dfw, dfw);
- } else if (sc != SC_ScrollBarGroove) {
- if (scrollbar->orientation == Qt::Horizontal)
- rect.adjust(0, dfw, 0, -dfw);
- else
- rect.adjust(dfw, 0, -dfw, 0);
- }
- return visualRect(scrollbar->direction, scrollbar->rect, rect);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- switch (sc) {
- case SC_ComboBoxArrow: {
- int ew, awh, sh, dh, ax, ay, sy;
- int fw = cb->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth, opt, widget) : 0;
- QRect cr = opt->rect;
- cr.adjust(fw, fw, -fw, -fw);
- get_combo_parameters(cr, ew, awh, ax, ay, sh, dh, sy);
- return visualRect(cb->direction, cb->rect, QRect(QPoint(ax, ay), cr.bottomRight()));
- }
-
- case SC_ComboBoxEditField: {
- int fw = cb->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth, opt, widget) : 0;
- QRect rect = opt->rect;
- rect.adjust(fw, fw, -fw, -fw);
- int ew = get_combo_extra_width(rect.height(), rect.width());
- rect.adjust(1, 1, -1-ew, -1);
- return visualRect(cb->direction, cb->rect, rect);
- }
-
- default:
- break;
- }
- }
- break;
-#endif // QT_NO_SCROLLBAR
- default:
- break;
- }
- return QCommonStyle::subControlRect(cc, opt, sc, widget);
-}
-
-/*!
- \reimp
-*/
-QSize
-QMotifStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget) const
-{
- QSize sz(contentsSize);
-
- switch(ct) {
- case CT_RadioButton:
- case CT_CheckBox:
- sz = QCommonStyle::sizeFromContents(ct, opt, contentsSize, widget);
- sz.rwidth() += motifItemFrame;
- break;
-
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- sz = QCommonStyle::sizeFromContents(ct, opt, contentsSize, widget);
- if (!btn->text.isEmpty() && (btn->features & (QStyleOptionButton::AutoDefaultButton|QStyleOptionButton::DefaultButton)))
- sz.setWidth(qMax(75, sz.width()));
- sz += QSize(0, 1); // magical extra pixel
- }
- break;
-
- case CT_MenuBarItem: {
- if(!sz.isEmpty())
- sz += QSize(5*motifItemHMargin+1, 2*motifItemVMargin + motifItemFrame);
- break; }
-
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- sz = QCommonStyle::sizeFromContents(ct, opt, sz, widget);
- int w = sz.width(), h = sz.height();
-
- if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
- w = 10;
- h = (mi->text.isEmpty()) ? motifSepHeight : mi->fontMetrics.height();
- }
-
- // a little bit of border can never harm
- w += 2*motifItemHMargin + 2*motifItemFrame;
-
- if (!mi->text.isNull() && mi->text.indexOf(QLatin1Char('\t')) >= 0)
- // string contains tab
- w += motifTabSpacing;
- else if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
- // submenu indicator needs some room if we don't have a tab column
- w += motifArrowHMargin + 4*motifItemFrame;
-
- int checkColumn = mi->maxIconWidth;
- if (mi->menuHasCheckableItems)
- checkColumn = qMax(checkColumn, motifCheckMarkSpace);
- if (checkColumn > 0)
- w += checkColumn + motifCheckMarkHMargin;
-
- sz = QSize(w, h);
- }
- break;
-
-
- default:
- sz = QCommonStyle::sizeFromContents(ct, opt, contentsSize, widget);
- break;
- }
-
- return sz;
-}
-
-/*!
- \reimp
-*/
-QRect
-QMotifStyle::subElementRect(SubElement sr, const QStyleOption *opt, const QWidget *widget) const
-{
- QRect rect;
-
- switch (sr) {
- case SE_SliderFocusRect:
- rect = QCommonStyle::subElementRect(sr, opt, widget);
- rect.adjust(2, 2, -2, -2);
- break;
-
- case SE_CheckBoxIndicator:
- case SE_RadioButtonIndicator:
- {
- rect = visualRect(opt->direction, opt->rect,
- QCommonStyle::subElementRect(sr, opt, widget));
- rect.adjust(motifItemFrame,0, motifItemFrame,0);
- rect = visualRect(opt->direction, opt->rect, rect);
- }
- break;
-
- case SE_ComboBoxFocusRect:
- {
- int awh, ax, ay, sh, sy, dh, ew;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
- QRect tr = opt->rect;
-
- tr.adjust(fw, fw, -fw, -fw);
- get_combo_parameters(tr, ew, awh, ax, ay, sh, dh, sy);
- rect.setRect(ax-2, ay-2, awh+4, awh+sh+dh+4);
- break;
- }
-
- case SE_Q3DockWindowHandleRect:
- if (const QStyleOptionQ3DockWindow *dw = qstyleoption_cast<const QStyleOptionQ3DockWindow *>(opt)) {
- if (!dw->docked || !dw->closeEnabled)
- rect.setRect(0, 0, opt->rect.width(), opt->rect.height());
- else {
- if (dw->state == State_Horizontal)
- rect.setRect(2, 15, opt->rect.width()-2, opt->rect.height() - 15);
- else
- rect.setRect(0, 2, opt->rect.width() - 15, opt->rect.height() - 2);
- }
- rect = visualRect(dw->direction, dw->rect, rect);
- }
- break;
-
- case SE_ProgressBarLabel:
- case SE_ProgressBarGroove:
- case SE_ProgressBarContents:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- int textw = 0;
- if (pb->textVisible)
- textw = pb->fontMetrics.width(QLatin1String("100%")) + 6;
-
- if (pb->textAlignment == Qt::AlignLeft || pb->textAlignment == Qt::AlignCenter) {
- rect = opt->rect;
- } else {
- if(sr == SE_ProgressBarLabel)
- rect.setCoords(opt->rect.right() - textw, opt->rect.top(),
- opt->rect.right(), opt->rect.bottom());
- else
- rect.setCoords(opt->rect.left(), opt->rect.top(),
- opt->rect.right() - textw, opt->rect.bottom());
- }
- if (sr == SE_ProgressBarContents)
- rect.adjust(2, 2, -2, -2);
- rect = visualRect(pb->direction, pb->rect, rect);
- }
- break;
- case SE_CheckBoxClickRect:
- case SE_RadioButtonClickRect:
- rect = visualRect(opt->direction, opt->rect, opt->rect);
- break;
-
- default:
- rect = QCommonStyle::subElementRect(sr, opt, widget);
- }
- return rect;
-}
-
-#ifndef QT_NO_IMAGEFORMAT_XPM
-static const char * const qt_menu_xpm[] = {
-"16 16 11 1",
-" c #000000",
-", c #336600",
-". c #99CC00",
-"X c #666600",
-"o c #999933",
-"+ c #333300",
-"@ c #669900",
-"# c #999900",
-"$ c #336633",
-"% c #666633",
-"& c #99CC33",
-"................",
-"................",
-".....#,++X#.....",
-"....X X....",
-"...X Xo#% X&..",
-"..# o..&@o o..",
-".., X..#+ @X X..",
-"..+ o.o+ +o# +..",
-"..+ #o+ +## +..",
-".., %@ ++ +, X..",
-"..# o@oo+ #..",
-"...X X##$ o..",
-"....X X..",
-"....&oX++X#oX...",
-"................",
-"................"};
-
-
-static const char * const qt_close_xpm[] = {
- "12 12 2 1",
- " s None c None",
- ". c black",
- " ",
- " ",
- " . . ",
- " ... ... ",
- " ...... ",
- " .... ",
- " .... ",
- " ...... ",
- " ... ... ",
- " . . ",
- " ",
- " "};
-
-static const char * const qt_maximize_xpm[] = {
- "12 12 2 1",
- " s None c None",
- ". c black",
- " ",
- " ",
- " ",
- " . ",
- " ... ",
- " ..... ",
- " ....... ",
- " ......... ",
- " ",
- " ",
- " ",
- " "};
-
-static const char * const qt_minimize_xpm[] = {
- "12 12 2 1",
- " s None c None",
- ". c black",
- " ",
- " ",
- " ",
- " ",
- " ......... ",
- " ....... ",
- " ..... ",
- " ... ",
- " . ",
- " ",
- " ",
- " "};
-
-#if 0 // ### not used???
-static const char * const qt_normalize_xpm[] = {
- "12 12 2 1",
- " s None c None",
- ". c black",
- " ",
- " ",
- " . ",
- " .. ",
- " ... ",
- " .... ",
- " ..... ",
- " ...... ",
- " ....... ",
- " ",
- " ",
- " "};
-#endif
-
-static const char * const qt_normalizeup_xpm[] = {
- "12 12 2 1",
- " s None c None",
- ". c black",
- " ",
- " ",
- " ",
- " ....... ",
- " ...... ",
- " ..... ",
- " .... ",
- " ... ",
- " .. ",
- " . ",
- " ",
- " "};
-
-static const char * const qt_shade_xpm[] = {
- "12 12 2 1", "# c #000000",
- ". c None",
- "............",
- "............",
- ".#########..",
- ".#########..",
- "............",
- "............",
- "............",
- "............",
- "............",
- "............",
- "............",
- "............"};
-
-
-static const char * const qt_unshade_xpm[] = {
- "12 12 2 1",
- "# c #000000",
- ". c None",
- "............",
- "............",
- ".#########..",
- ".#########..",
- ".#.......#..",
- ".#.......#..",
- ".#.......#..",
- ".#.......#..",
- ".#.......#..",
- ".#########..",
- "............",
- "............"};
-
-
-static const char * dock_window_close_xpm[] = {
- "8 8 2 1",
- "# c #000000",
- ". c None",
- "##....##",
- ".##..##.",
- "..####..",
- "...##...",
- "..####..",
- ".##..##.",
- "##....##",
- "........"};
-
-// Message box icons, from page 210 of the Windows style guide.
-
-// Hand-drawn to resemble Microsoft's icons, but in the Mac/Netscape palette.
-// Thanks to TrueColor displays, it is slightly more efficient to have
-// them duplicated.
-/* XPM */
-static const char * const information_xpm[]={
- "32 32 5 1",
- ". c None",
- "c c #000000",
- "* c #999999",
- "a c #ffffff",
- "b c #0000ff",
- "...........********.............",
- "........***aaaaaaaa***..........",
- "......**aaaaaaaaaaaaaa**........",
- ".....*aaaaaaaaaaaaaaaaaa*.......",
- "....*aaaaaaaabbbbaaaaaaaac......",
- "...*aaaaaaaabbbbbbaaaaaaaac.....",
- "..*aaaaaaaaabbbbbbaaaaaaaaac....",
- ".*aaaaaaaaaaabbbbaaaaaaaaaaac...",
- ".*aaaaaaaaaaaaaaaaaaaaaaaaaac*..",
- "*aaaaaaaaaaaaaaaaaaaaaaaaaaaac*.",
- "*aaaaaaaaaabbbbbbbaaaaaaaaaaac*.",
- "*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
- "*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
- "*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
- "*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
- "*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
- ".*aaaaaaaaaaabbbbbaaaaaaaaaac***",
- ".*aaaaaaaaaaabbbbbaaaaaaaaaac***",
- "..*aaaaaaaaaabbbbbaaaaaaaaac***.",
- "...caaaaaaabbbbbbbbbaaaaaac****.",
- "....caaaaaaaaaaaaaaaaaaaac****..",
- ".....caaaaaaaaaaaaaaaaaac****...",
- "......ccaaaaaaaaaaaaaacc****....",
- ".......*cccaaaaaaaaccc*****.....",
- "........***cccaaaac*******......",
- "..........****caaac*****........",
- ".............*caaac**...........",
- "...............caac**...........",
- "................cac**...........",
- ".................cc**...........",
- "..................***...........",
- "...................**..........."};
-/* XPM */
-static const char* const warning_xpm[]={
- "32 32 4 1",
- ". c None",
- "a c #ffff00",
- "* c #000000",
- "b c #999999",
- ".............***................",
- "............*aaa*...............",
- "...........*aaaaa*b.............",
- "...........*aaaaa*bb............",
- "..........*aaaaaaa*bb...........",
- "..........*aaaaaaa*bb...........",
- ".........*aaaaaaaaa*bb..........",
- ".........*aaaaaaaaa*bb..........",
- "........*aaaaaaaaaaa*bb.........",
- "........*aaaa***aaaa*bb.........",
- ".......*aaaa*****aaaa*bb........",
- ".......*aaaa*****aaaa*bb........",
- "......*aaaaa*****aaaaa*bb.......",
- "......*aaaaa*****aaaaa*bb.......",
- ".....*aaaaaa*****aaaaaa*bb......",
- ".....*aaaaaa*****aaaaaa*bb......",
- "....*aaaaaaaa***aaaaaaaa*bb.....",
- "....*aaaaaaaa***aaaaaaaa*bb.....",
- "...*aaaaaaaaa***aaaaaaaaa*bb....",
- "...*aaaaaaaaaa*aaaaaaaaaa*bb....",
- "..*aaaaaaaaaaa*aaaaaaaaaaa*bb...",
- "..*aaaaaaaaaaaaaaaaaaaaaaa*bb...",
- ".*aaaaaaaaaaaa**aaaaaaaaaaa*bb..",
- ".*aaaaaaaaaaa****aaaaaaaaaa*bb..",
- "*aaaaaaaaaaaa****aaaaaaaaaaa*bb.",
- "*aaaaaaaaaaaaa**aaaaaaaaaaaa*bb.",
- "*aaaaaaaaaaaaaaaaaaaaaaaaaaa*bbb",
- "*aaaaaaaaaaaaaaaaaaaaaaaaaaa*bbb",
- ".*aaaaaaaaaaaaaaaaaaaaaaaaa*bbbb",
- "..*************************bbbbb",
- "....bbbbbbbbbbbbbbbbbbbbbbbbbbb.",
- ".....bbbbbbbbbbbbbbbbbbbbbbbbb.."};
-/* XPM */
-static const char* const critical_xpm[]={
- "32 32 4 1",
- ". c None",
- "a c #999999",
- "* c #ff0000",
- "b c #ffffff",
- "...........********.............",
- ".........************...........",
- ".......****************.........",
- "......******************........",
- ".....********************a......",
- "....**********************a.....",
- "...************************a....",
- "..*******b**********b*******a...",
- "..******bbb********bbb******a...",
- ".******bbbbb******bbbbb******a..",
- ".*******bbbbb****bbbbb*******a..",
- "*********bbbbb**bbbbb*********a.",
- "**********bbbbbbbbbb**********a.",
- "***********bbbbbbbb***********aa",
- "************bbbbbb************aa",
- "************bbbbbb************aa",
- "***********bbbbbbbb***********aa",
- "**********bbbbbbbbbb**********aa",
- "*********bbbbb**bbbbb*********aa",
- ".*******bbbbb****bbbbb*******aa.",
- ".******bbbbb******bbbbb******aa.",
- "..******bbb********bbb******aaa.",
- "..*******b**********b*******aa..",
- "...************************aaa..",
- "....**********************aaa...",
- "....a********************aaa....",
- ".....a******************aaa.....",
- "......a****************aaa......",
- ".......aa************aaaa.......",
- ".........aa********aaaaa........",
- "...........aaaaaaaaaaa..........",
- ".............aaaaaaa............"};
-/* XPM */
-static const char *const question_xpm[] = {
- "32 32 5 1",
- ". c None",
- "c c #000000",
- "* c #999999",
- "a c #ffffff",
- "b c #0000ff",
- "...........********.............",
- "........***aaaaaaaa***..........",
- "......**aaaaaaaaaaaaaa**........",
- ".....*aaaaaaaaaaaaaaaaaa*.......",
- "....*aaaaaaaaaaaaaaaaaaaac......",
- "...*aaaaaaaabbbbbbaaaaaaaac.....",
- "..*aaaaaaaabaaabbbbaaaaaaaac....",
- ".*aaaaaaaabbaaaabbbbaaaaaaaac...",
- ".*aaaaaaaabbbbaabbbbaaaaaaaac*..",
- "*aaaaaaaaabbbbaabbbbaaaaaaaaac*.",
- "*aaaaaaaaaabbaabbbbaaaaaaaaaac*.",
- "*aaaaaaaaaaaaabbbbaaaaaaaaaaac**",
- "*aaaaaaaaaaaaabbbaaaaaaaaaaaac**",
- "*aaaaaaaaaaaaabbaaaaaaaaaaaaac**",
- "*aaaaaaaaaaaaabbaaaaaaaaaaaaac**",
- "*aaaaaaaaaaaaaaaaaaaaaaaaaaaac**",
- ".*aaaaaaaaaaaabbaaaaaaaaaaaac***",
- ".*aaaaaaaaaaabbbbaaaaaaaaaaac***",
- "..*aaaaaaaaaabbbbaaaaaaaaaac***.",
- "...caaaaaaaaaabbaaaaaaaaaac****.",
- "....caaaaaaaaaaaaaaaaaaaac****..",
- ".....caaaaaaaaaaaaaaaaaac****...",
- "......ccaaaaaaaaaaaaaacc****....",
- ".......*cccaaaaaaaaccc*****.....",
- "........***cccaaaac*******......",
- "..........****caaac*****........",
- ".............*caaac**...........",
- "...............caac**...........",
- "................cac**...........",
- ".................cc**...........",
- "..................***...........",
- "...................**...........",
-};
-#endif
-
-/*!
- \reimp
-*/
-QPixmap
-QMotifStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget) const
-{
-#ifndef QT_NO_IMAGEFORMAT_XPM
- switch (standardPixmap) {
- case SP_TitleBarMenuButton:
- return QPixmap(qt_menu_xpm);
- case SP_TitleBarShadeButton:
- return QPixmap(qt_shade_xpm);
- case SP_TitleBarUnshadeButton:
- return QPixmap(qt_unshade_xpm);
- case SP_TitleBarNormalButton:
- return QPixmap(qt_normalizeup_xpm);
- case SP_TitleBarMinButton:
- return QPixmap(qt_minimize_xpm);
- case SP_TitleBarMaxButton:
- return QPixmap(qt_maximize_xpm);
- case SP_TitleBarCloseButton:
- return QPixmap(qt_close_xpm);
- case SP_DockWidgetCloseButton:
- return QPixmap(dock_window_close_xpm);
-
- case SP_MessageBoxInformation:
- case SP_MessageBoxWarning:
- case SP_MessageBoxCritical:
- case SP_MessageBoxQuestion:
- {
- const char * const * xpm_data;
- switch (standardPixmap) {
- case SP_MessageBoxInformation:
- xpm_data = information_xpm;
- break;
- case SP_MessageBoxWarning:
- xpm_data = warning_xpm;
- break;
- case SP_MessageBoxCritical:
- xpm_data = critical_xpm;
- break;
- case SP_MessageBoxQuestion:
- xpm_data = question_xpm;
- break;
- default:
- xpm_data = 0;
- break;
- }
- QPixmap pm;
- if (xpm_data) {
- QImage image((const char **) xpm_data);
- // All that color looks ugly in Motif
- const QPalette &pal = QApplication::palette();
- switch (standardPixmap) {
- case SP_MessageBoxInformation:
- case SP_MessageBoxQuestion:
- image.setColor(2, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Dark).rgb());
- image.setColor(3, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Base).rgb());
- image.setColor(4, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Text).rgb());
- break;
- case SP_MessageBoxWarning:
- image.setColor(1, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Base).rgb());
- image.setColor(2, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Text).rgb());
- image.setColor(3, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Dark).rgb());
- break;
- case SP_MessageBoxCritical:
- image.setColor(1, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Dark).rgb());
- image.setColor(2, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Text).rgb());
- image.setColor(3, 0xff000000 |
- pal.color(QPalette::Active, QPalette::Base).rgb());
- break;
- default:
- break;
- }
- pm = QPixmap::fromImage(image);
- }
- return pm;
- }
-
- default:
- break;
- }
-#endif
-
- return QCommonStyle::standardPixmap(standardPixmap, opt, widget);
-}
-
-/*! \reimp */
-bool QMotifStyle::event(QEvent *e)
-{
- if(e->type() == QEvent::FocusIn) {
- if (QWidget *focusWidget = QApplication::focusWidget()) {
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(focusWidget)) {
- QGraphicsItem *focusItem = graphicsView->scene() ? graphicsView->scene()->focusItem() : 0;
- if (focusItem && focusItem->type() == QGraphicsProxyWidget::Type) {
- QGraphicsProxyWidget *proxy = static_cast<QGraphicsProxyWidget *>(focusItem);
- if (proxy->widget())
- focusWidget = proxy->widget()->focusWidget();
- }
- }
-#endif
- if(!focus)
- focus = new QFocusFrame(focusWidget);
- focus->setWidget(focusWidget);
- } else {
- if(focus)
- focus->setWidget(0);
- }
- } else if(e->type() == QEvent::FocusOut) {
- if(focus)
- focus->setWidget(0);
- }
- return QCommonStyle::event(e);
-}
-
-
-/*! \reimp */
-int
-QMotifStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWidget *widget,
- QStyleHintReturn *returnData) const
-{
- int ret;
-
- switch (hint) {
-#ifdef QT3_SUPPORT
- case SH_GUIStyle:
- ret = Qt::MotifStyle;
- break;
-#endif
- case SH_DrawMenuBarSeparator:
- ret = true;
- break;
-
- case SH_ScrollBar_MiddleClickAbsolutePosition:
- case SH_Slider_SloppyKeyEvents:
- case SH_ProgressDialog_CenterCancelButton:
- case SH_Menu_SpaceActivatesItem:
- case SH_ScrollView_FrameOnlyAroundContents:
- case SH_DitherDisabledText:
- ret = 1;
- break;
-
- case SH_Menu_SubMenuPopupDelay:
- ret = 96;
- break;
-
- case SH_ProgressDialog_TextLabelAlignment:
- ret = Qt::AlignLeft | Qt::AlignVCenter;
- break;
-
- case SH_ItemView_ChangeHighlightOnFocus:
- ret = 0;
- break;
-
- case SH_MessageBox_UseBorderForButtonSpacing:
- ret = 1;
- break;
-
- case SH_Dial_BackgroundRole:
- ret = QPalette::Mid;
- break;
-
- case SH_DialogButtonLayout:
- ret = QDialogButtonBox::KdeLayout;
- break;
- case SH_LineEdit_PasswordCharacter:
- ret = '*';
- break;
- case SH_DialogButtonBox_ButtonsHaveIcons:
- ret = 0;
- break;
- default:
- ret = QCommonStyle::styleHint(hint, opt, widget, returnData);
- break;
- }
-
- return ret;
-}
-
-/*! \reimp */
-QPalette QMotifStyle::standardPalette() const
-{
-#ifdef Q_WS_X11
- QColor background(0xcf, 0xcf, 0xcf);
- if (QX11Info::appDepth() <= 8)
- background = QColor(0xc0, 0xc0, 0xc0);
-#else
- QColor background = QColor(0xcf, 0xcf, 0xcf);
-#endif
-
- QColor light = background.lighter();
- QColor mid = QColor(0xa6, 0xa6, 0xa6);
- QColor dark = QColor(0x79, 0x7d, 0x79);
- QPalette palette(Qt::black, background, light, dark, mid, Qt::black, Qt::white);
- palette.setBrush(QPalette::Disabled, QPalette::WindowText, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Text, dark);
- palette.setBrush(QPalette::Disabled, QPalette::ButtonText, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Base, background);
- return palette;
-}
-
-QT_END_NAMESPACE
-
-#endif // !defined(QT_NO_STYLE_MOTIF) || defined(QT_PLUGIN)
diff --git a/src/gui/styles/qmotifstyle.h b/src/gui/styles/qmotifstyle.h
deleted file mode 100644
index 5ca0795216..0000000000
--- a/src/gui/styles/qmotifstyle.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** 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 QMOTIFSTYLE_H
-#define QMOTIFSTYLE_H
-
-#include <QtGui/qcommonstyle.h>
-#include <QtCore/qpointer.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_MOTIF)
-
-class QPalette;
-class QFocusFrame;
-
-class QMotifStylePrivate;
-class Q_GUI_EXPORT QMotifStyle : public QCommonStyle
-{
- Q_OBJECT
-public:
- explicit QMotifStyle(bool useHighlightCols=false);
- virtual ~QMotifStyle();
-
- void setUseHighlightColors(bool);
- bool useHighlightColors() const;
-
- void polish(QPalette&);
- void polish(QWidget*);
- void unpolish(QWidget*);
- void polish(QApplication*);
- void unpolish(QApplication*);
-
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
-
- void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
-
- void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const;
-
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget = 0) const;
-
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
-
- QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const;
-
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
-
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const;
-
- int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
-
- bool event(QEvent *);
- QPalette standardPalette() const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
-
-protected:
- QPointer<QFocusFrame> focus;
- QMotifStyle(QMotifStylePrivate &dd, bool useHighlightCols = false);
- void timerEvent(QTimerEvent *event);
- bool eventFilter(QObject *o, QEvent *e);
-
-private:
- Q_DECLARE_PRIVATE(QMotifStyle)
- Q_DISABLE_COPY(QMotifStyle)
-
- bool highlightCols;
-};
-
-#endif // QT_NO_STYLE_MOTIF
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMOTIFSTYLE_H
diff --git a/src/gui/styles/qmotifstyle_p.h b/src/gui/styles/qmotifstyle_p.h
deleted file mode 100644
index 47043b582b..0000000000
--- a/src/gui/styles/qmotifstyle_p.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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 QMOTIFSTYLE_P_H
-#define QMOTIFSTYLE_P_H
-#include <qlist.h>
-#include <qdatetime.h>
-#include <qprogressbar.h>
-#include "qmotifstyle.h"
-#include "qcommonstyle_p.h"
-
-QT_BEGIN_NAMESPACE
-
-//
-// 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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-// Private class
-class QMotifStylePrivate : public QCommonStylePrivate
-{
- Q_DECLARE_PUBLIC(QMotifStyle)
-public:
- QMotifStylePrivate();
-
-public:
-#ifndef QT_NO_PROGRESSBAR
- QList<QProgressBar *> bars;
- int animationFps;
- int animateTimer;
- QTime startTime;
- int animateStep;
-#endif // QT_NO_PROGRESSBAR
-};
-
-QT_END_NAMESPACE
-
-#endif //QMOTIFSTYLE_P_H
diff --git a/src/gui/styles/qplastiquestyle.cpp b/src/gui/styles/qplastiquestyle.cpp
deleted file mode 100644
index 02ce60efab..0000000000
--- a/src/gui/styles/qplastiquestyle.cpp
+++ /dev/null
@@ -1,6011 +0,0 @@
-/****************************************************************************
-**
-** 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 "qplastiquestyle.h"
-
-#if !defined(QT_NO_STYLE_PLASTIQUE) || defined(QT_PLUGIN)
-
-static const bool AnimateBusyProgressBar = true;
-static const bool AnimateProgressBar = false;
-// #define QPlastique_MaskButtons
-static const int ProgressBarFps = 25;
-static const int blueFrameWidth = 2; // with of line edit focus frame
-
-#include "qwindowsstyle_p.h"
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qabstractitemview.h>
-#include <qcheckbox.h>
-#include <qcombobox.h>
-#include <qdebug.h>
-#include <qdialogbuttonbox.h>
-#include <qformlayout.h>
-#include <qgroupbox.h>
-#include <qimage.h>
-#include <qlineedit.h>
-#include <qmainwindow.h>
-#include <qmenu.h>
-#include <qmenubar.h>
-#include <qpainter.h>
-#include <qpaintengine.h>
-#include <qpainterpath.h>
-#include <qpalette.h>
-#include <qpen.h>
-#include <qpixmap.h>
-#include <qpixmapcache.h>
-#include <qprogressbar.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qscrollbar.h>
-#include <qspinbox.h>
-#include <qsplitter.h>
-#include <qstyleoption.h>
-#include <qtextedit.h>
-#include <qelapsedtimer.h>
-#include <qtoolbar.h>
-#include <qtoolbox.h>
-#include <qtoolbutton.h>
-#include <qworkspace.h>
-#include <qprocess.h>
-#include <qvarlengtharray.h>
-#include <limits.h>
-#include <private/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// from windows style
-static const int windowsItemFrame = 2; // menu item frame width
-static const int windowsSepHeight = 2; // separator item height
-static const int windowsItemHMargin = 3; // menu item hor text margin
-static const int windowsItemVMargin = 2; // menu item ver text margin
-static const int windowsArrowHMargin = 6; // arrow horizontal margin
-static const int windowsTabSpacing = 12; // space between text and tab
-static const int windowsRightBorder = 15; // right border on windows
-static const int windowsCheckMarkWidth = 12; // checkmarks width on windows
-
-static const char * const qt_plastique_slider_verticalhandle[] = {
- "15 11 6 1",
- " c None",
- "+ c #979797",
- "@ c #C9C9C9",
- "$ c #C1C1C1",
- "b c None",
- "d c None",
- " $++++++++$ ",
- "$+bbbbbbbb+$ ",
- "+b $$ +$ ",
- "+b $@ +$ ",
- "+b +$",
- "+b d+",
- "+b d+$",
- "+b $$ d+$ ",
- "+b $@ d+$ ",
- "$+dddddddd+$ ",
- " $++++++++$ "};
-
-static const char * const qt_plastique_slider_verticalhandle_left[] = {
- "15 11 6 1",
- " c None",
- "+ c #979797",
- "@ c #C9C9C9",
- "$ c #C1C1C1",
- "b c None",
- "d c None",
- " $++++++++$ ",
- " $+bbbbbbbb+$",
- " $+b $$ d+",
- " $+b $@ d+",
- "$+b d+",
- "+b d+",
- "$+ d+",
- " $+ $$ d+",
- " $+ $@ d+",
- " $+dddddddd+$",
- " $++++++++$ "};
-
-static const char * const qt_plastique_slider_horizontalhandle[] = {
- "11 15 6 1",
- " c None",
- "+ c #979797",
- "@ c #C9C9C9",
- "$ c #C1C1C1",
- "b c None",
- "d c None",
- " $+++++++$ ",
- "$+bbbbbbb+$",
- "+b d+",
- "+b$$ $$d+",
- "+b$@ $@d+",
- "+b d+",
- "+b d+",
- "+b d+",
- "+b d+",
- "+b d+",
- "$+ d+$",
- " $+ d+$ ",
- " $+ d+$ ",
- " $+d+$ ",
- " $+$ "};
-
-static const char * const qt_plastique_slider_horizontalhandle_up[] = {
- "11 15 6 1",
- " c None",
- "+ c #979797",
- "@ c #C9C9C9",
- "$ c #C1C1C1",
- "b c None",
- "d c None",
- " $+$ ",
- " $+b+$ ",
- " $+b +$ ",
- " $+b +$ ",
- "$+b +$",
- "+b d+",
- "+b d+",
- "+b d+",
- "+b d+",
- "+b d+",
- "+b$$ $$d+",
- "+b$@ $@d+",
- "+b d+",
- "$+ddddddd+$",
- " $+++++++$ "};
-
-static const char * const qt_scrollbar_button_arrow_left[] = {
- "4 7 2 1",
- " c None",
- "* c #BFBFBF",
- " *",
- " **",
- " ***",
- "****",
- " ***",
- " **",
- " *"};
-
-static const char * const qt_scrollbar_button_arrow_right[] = {
- "4 7 2 1",
- " c None",
- "* c #BFBFBF",
- "* ",
- "** ",
- "*** ",
- "****",
- "*** ",
- "** ",
- "* "};
-
-static const char * const qt_scrollbar_button_arrow_up[] = {
- "7 4 2 1",
- " c None",
- "* c #BFBFBF",
- " * ",
- " *** ",
- " ***** ",
- "*******"};
-
-static const char * const qt_scrollbar_button_arrow_down[] = {
- "7 4 2 1",
- " c None",
- "* c #BFBFBF",
- "*******",
- " ***** ",
- " *** ",
- " * "};
-
-static const char * const qt_scrollbar_button_left[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- " .+++++++++++++.",
- ".+#############+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- ".+<<<<<<<<<<<<<+",
- " .+++++++++++++."};
-
-static const char * const qt_scrollbar_button_right[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- ".+++++++++++++. ",
- "+#############+.",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+<<<<<<<<<<<<<+.",
- ".+++++++++++++. "};
-
-static const char * const qt_scrollbar_button_up[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- " .++++++++++++. ",
- ".+############+.",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+<<<<<<<<<<<<<<+",
- ".++++++++++++++."};
-
-static const char * const qt_scrollbar_button_down[] = {
- "16 16 6 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- "# c #FAFAFA",
- "< c #FAFAFA",
- "* c #FAFAFA",
- "++++++++++++++++",
- "+##############+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- "+# <+",
- ".+<<<<<<<<<<<<+.",
- " .++++++++++++. "};
-
-static const char * const qt_scrollbar_slider_pattern_vertical[] = {
- "10 18 3 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- ".. .. ..",
- ".+ .+ .+",
- " ",
- " ",
- ".. .. ..",
- ".+ .+ .+",
- " ",
- " ",
- ".. .. ..",
- ".+ .+ .+",
- " ",
- " ",
- ".. .. ..",
- ".+ .+ .+",
- " ",
- " ",
- ".. .. ..",
- ".+ .+ .+"};
-
-static const char * const qt_scrollbar_slider_pattern_horizontal[] = {
- "18 10 3 1",
- " c None",
- ". c #BFBFBF",
- "+ c #979797",
- ".. .. .. .. ..",
- ".+ .+ .+ .+ .+",
- " ",
- " ",
- ".. .. .. .. ..",
- ".+ .+ .+ .+ .+",
- " ",
- " ",
- ".. .. .. .. ..",
- ".+ .+ .+ .+ .+"};
-
-static const char * const qt_toolbarhandle[] = {
- "6 6 4 1",
- " c None",
- ". c #C5C5C5",
- "+ c #EEEEEE",
- "@ c #FAFAFA",
- ".. ",
- ".+@ ",
- " @@ ",
- " .. ",
- " .+@",
- " @@"};
-
-static const char * const qt_simple_toolbarhandle[] = {
- "3 3 4 1",
- " c None",
- ". c #C5C5C5",
- "+ c #EEEEEE",
- "@ c #FAFAFA",
- ".. ",
- ".+@",
- " @@"};
-
-static const char * const qt_titlebar_context_help[] = {
-"27 27 5 1",
-" c None",
-". c #0A0C12",
-"+ c #1B202D",
-"@ c #293144",
-"# c #3C435D",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" +@##@+ ",
-" .@@@.+@@.. ",
-" .##+ +@@+. ",
-" .##@ @#@+. ",
-" .... +@+.. ",
-" .@+@@.. ",
-" +#@@+ ",
-" .##. ",
-" .++. ",
-" .++. ",
-" +##+ ",
-" .@@. ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" "};
-
-static QLinearGradient qMapGradientToRect(const QLinearGradient &gradient, const QRectF &rect)
-{
- QLinearGradient tmpGrad(rect.center().x(), rect.top(),
- rect.center().x(), rect.bottom());
- tmpGrad.setStops(gradient.stops());
- return tmpGrad;
-}
-
-static QBrush qMapBrushToRect(const QBrush &brush, const QRectF &rect)
-{
- if (!brush.gradient())
- return brush;
-
- // ### Ugly assumption that it's a linear gradient
- QBrush tmp(qMapGradientToRect(*static_cast<const QLinearGradient *>(brush.gradient()), rect));
- return tmp;
-}
-
-static void qBrushSetAlphaF(QBrush *brush, qreal alpha)
-{
- if (const QGradient *gradient = brush->gradient()) {
- // Use the gradient. Call QColor::setAlphaF() on all color stops.
- QGradientStops stops = gradient->stops();
- QMutableVectorIterator<QGradientStop> it(stops);
- QColor tmpColor;
- while (it.hasNext()) {
- it.next();
- tmpColor = it.value().second;
- tmpColor.setAlphaF(alpha * tmpColor.alphaF());
- it.setValue(QPair<qreal, QColor>(it.value().first, tmpColor));
- }
-
- switch (gradient->type()) {
- case QGradient::RadialGradient: {
- QRadialGradient grad = *static_cast<const QRadialGradient *>(gradient);
- grad.setStops(stops);
- *brush = QBrush(grad);
- break;
- }
- case QGradient::ConicalGradient: {
- QConicalGradient grad = *static_cast<const QConicalGradient *>(gradient);
- grad.setStops(stops);
- *brush = QBrush(grad);
- break;
- }
- default:
- qWarning("QPlastiqueStyle::qBrushLight() - unknown gradient type"
- " - falling back to QLinearGradient");
- case QGradient::LinearGradient: {
- QLinearGradient grad = *static_cast<const QLinearGradient *>(gradient);
- grad.setStops(stops);
- *brush = QBrush(grad);
- break;
- }
- }
- } else if (!brush->texture().isNull()) {
- // Modify the texture - ridiculously expensive.
- QPixmap texture = brush->texture();
- QPixmap pixmap;
- QString name = QLatin1Literal("qbrushtexture-alpha")
- % HexString<qreal>(alpha)
- % HexString<qint64>(texture.cacheKey());
- if (!QPixmapCache::find(name, pixmap)) {
- QImage image = texture.toImage();
- QRgb *rgb = reinterpret_cast<QRgb *>(image.bits());
- int pixels = image.width() * image.height();
- QColor tmpColor;
- while (pixels--) {
- tmpColor.setRgb(*rgb);
- tmpColor.setAlphaF(alpha * tmpColor.alphaF());
- *rgb++ = tmpColor.rgba();
- }
- pixmap = QPixmap::fromImage(image);
- QPixmapCache::insert(name, pixmap);
- }
- brush->setTexture(pixmap);
- } else {
- // Use the color
- QColor tmpColor = brush->color();
- tmpColor.setAlphaF(alpha * tmpColor.alphaF());
- brush->setColor(tmpColor);
- }
-}
-
-static QBrush qBrushLight(QBrush brush, int light)
-{
- if (const QGradient *gradient = brush.gradient()) {
- // Use the gradient. Call QColor::lighter() on all color stops.
- QGradientStops stops = gradient->stops();
- QMutableVectorIterator<QGradientStop> it(stops);
- while (it.hasNext()) {
- it.next();
- it.setValue(QPair<qreal, QColor>(it.value().first, it.value().second.lighter(light)));
- }
-
- switch (gradient->type()) {
- case QGradient::RadialGradient: {
- QRadialGradient grad = *static_cast<const QRadialGradient *>(gradient);
- grad.setStops(stops);
- brush = QBrush(grad);
- break;
- }
- case QGradient::ConicalGradient: {
- QConicalGradient grad = *static_cast<const QConicalGradient *>(gradient);
- grad.setStops(stops);
- brush = QBrush(grad);
- break;
- }
- default:
- qWarning("QPlastiqueStyle::qBrushLight() - unknown gradient type"
- " - falling back to QLinearGradient");
- case QGradient::LinearGradient: {
- QLinearGradient grad = *static_cast<const QLinearGradient *>(gradient);
- grad.setStops(stops);
- brush = QBrush(grad);
- break;
- }
- }
- } else if (!brush.texture().isNull()) {
- // Modify the texture - ridiculously expensive.
- QPixmap texture = brush.texture();
- QPixmap pixmap;
- QString name = QLatin1Literal("qbrushtexture-light")
- % HexString<int>(light)
- % HexString<qint64>(texture.cacheKey());
-
- if (!QPixmapCache::find(name, pixmap)) {
- QImage image = texture.toImage();
- QRgb *rgb = reinterpret_cast<QRgb *>(image.bits());
- int pixels = image.width() * image.height();
- QColor tmpColor;
- while (pixels--) {
- tmpColor.setRgb(*rgb);
- *rgb++ = tmpColor.lighter(light).rgba();
- }
- pixmap = QPixmap::fromImage(image);
- QPixmapCache::insert(name, pixmap);
- }
- brush.setTexture(pixmap);
- } else {
- // Use the color
- brush.setColor(brush.color().lighter(light));
- }
- return brush;
-}
-
-static QBrush qBrushDark(QBrush brush, int dark)
-{
- if (const QGradient *gradient = brush.gradient()) {
- // Use the gradient. Call QColor::darker() on all color stops.
- QGradientStops stops = gradient->stops();
- QMutableVectorIterator<QGradientStop> it(stops);
- while (it.hasNext()) {
- it.next();
- it.setValue(QPair<qreal, QColor>(it.value().first, it.value().second.darker(dark)));
- }
-
- switch (gradient->type()) {
- case QGradient::RadialGradient: {
- QRadialGradient grad = *static_cast<const QRadialGradient *>(gradient);
- grad.setStops(stops);
- brush = QBrush(grad);
- break;
- }
- case QGradient::ConicalGradient: {
- QConicalGradient grad = *static_cast<const QConicalGradient *>(gradient);
- grad.setStops(stops);
- brush = QBrush(grad);
- break;
- }
- default:
- qWarning("QPlastiqueStyle::qBrushDark() - unknown gradient type"
- " - falling back to QLinearGradient");
- case QGradient::LinearGradient: {
- QLinearGradient grad = *static_cast<const QLinearGradient *>(gradient);
- grad.setStops(stops);
- brush = QBrush(grad);
- break;
- }
- }
- } else if (!brush.texture().isNull()) {
- // Modify the texture - ridiculously expensive.
- QPixmap texture = brush.texture();
- QPixmap pixmap;
- QString name = QLatin1Literal("qbrushtexture-dark")
- % HexString<int>(dark)
- % HexString<qint64>(texture.cacheKey());
-
- if (!QPixmapCache::find(name, pixmap)) {
- QImage image = texture.toImage();
- QRgb *rgb = reinterpret_cast<QRgb *>(image.bits());
- int pixels = image.width() * image.height();
- QColor tmpColor;
- while (pixels--) {
- tmpColor.setRgb(*rgb);
- *rgb++ = tmpColor.darker(dark).rgba();
- }
- pixmap = QPixmap::fromImage(image);
- QPixmapCache::insert(name, pixmap);
- }
- brush.setTexture(pixmap);
- } else {
- // Use the color
- brush.setColor(brush.color().darker(dark));
- }
- return brush;
-}
-
-/*
- Draws a rounded frame using the provided brush for 1, and adds 0.5 alpha
- for 0.
-
- 0111111110
- 01 10
- 1 1
- 1 1
- 1 1
- 01 10
- 0111111110
-*/
-static void qt_plastique_draw_frame(QPainter *painter, const QRect &rect, const QStyleOption *option,
- QFrame::Shadow shadow = QFrame::Plain)
-{
- QPen oldPen = painter->pen();
- QBrush border;
- QBrush corner;
- QBrush innerTopLeft;
- QBrush innerBottomRight;
-
- if (shadow != QFrame::Plain && (option->state & QStyle::State_HasFocus)) {
- border = option->palette.highlight();
- qBrushSetAlphaF(&border, qreal(0.8));
- corner = option->palette.highlight();
- qBrushSetAlphaF(&corner, 0.5);
- innerTopLeft = qBrushDark(option->palette.highlight(), 125);
- innerBottomRight = option->palette.highlight();
- qBrushSetAlphaF(&innerBottomRight, qreal(0.65));
- } else {
- border = option->palette.shadow();
- qBrushSetAlphaF(&border, qreal(0.4));
- corner = option->palette.shadow();
- qBrushSetAlphaF(&corner, 0.25);
- innerTopLeft = option->palette.shadow();
- innerBottomRight = option->palette.shadow();
- if (shadow == QFrame::Sunken) {
- qBrushSetAlphaF(&innerTopLeft, qreal(0.23));
- qBrushSetAlphaF(&innerBottomRight, qreal(0.075));
- } else {
- qBrushSetAlphaF(&innerTopLeft, qreal(0.075));
- qBrushSetAlphaF(&innerBottomRight, qreal(0.23));
- }
- }
-
- QLine lines[4];
- QPoint points[8];
-
- // Opaque corner lines
- painter->setPen(QPen(border, 0));
- lines[0] = QLine(rect.left() + 2, rect.top(), rect.right() - 2, rect.top());
- lines[1] = QLine(rect.left() + 2, rect.bottom(), rect.right() - 2, rect.bottom());
- lines[2] = QLine(rect.left(), rect.top() + 2, rect.left(), rect.bottom() - 2);
- lines[3] = QLine(rect.right(), rect.top() + 2, rect.right(), rect.bottom() - 2);
- painter->drawLines(lines, 4);
-
- // Opaque corner dots
- points[0] = QPoint(rect.left() + 1, rect.top() + 1);
- points[1] = QPoint(rect.left() + 1, rect.bottom() - 1);
- points[2] = QPoint(rect.right() - 1, rect.top() + 1);
- points[3] = QPoint(rect.right() - 1, rect.bottom() - 1);
- painter->drawPoints(points, 4);
-
- // Shaded corner dots
- painter->setPen(QPen(corner, 0));
- points[0] = QPoint(rect.left(), rect.top() + 1);
- points[1] = QPoint(rect.left(), rect.bottom() - 1);
- points[2] = QPoint(rect.left() + 1, rect.top());
- points[3] = QPoint(rect.left() + 1, rect.bottom());
- points[4] = QPoint(rect.right(), rect.top() + 1);
- points[5] = QPoint(rect.right(), rect.bottom() - 1);
- points[6] = QPoint(rect.right() - 1, rect.top());
- points[7] = QPoint(rect.right() - 1, rect.bottom());
- painter->drawPoints(points, 8);
-
- // Shadows
- if (shadow != QFrame::Plain) {
- painter->setPen(QPen(innerTopLeft, 0));
- lines[0] = QLine(rect.left() + 2, rect.top() + 1, rect.right() - 2, rect.top() + 1);
- lines[1] = QLine(rect.left() + 1, rect.top() + 2, rect.left() + 1, rect.bottom() - 2);
- painter->drawLines(lines, 2);
- painter->setPen(QPen(innerBottomRight, 0));
- lines[0] = QLine(rect.left() + 2, rect.bottom() - 1, rect.right() - 2, rect.bottom() - 1);
- lines[1] = QLine(rect.right() - 1, rect.top() + 2, rect.right() - 1, rect.bottom() - 2);
- painter->drawLines(lines, 2);
- }
-
- painter->setPen(oldPen);
-}
-
-static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50)
-{
- const int maxFactor = 100;
- QColor tmp = colorA;
- tmp.setRed((tmp.red() * factor) / maxFactor + (colorB.red() * (maxFactor - factor)) / maxFactor);
- tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor);
- tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor);
- return tmp;
-}
-
-static void qt_plastique_draw_gradient(QPainter *painter, const QRect &rect, const QColor &gradientStart,
- const QColor &gradientStop)
-{
- QString gradientName = QLatin1Literal("qplastique-g")
- % HexString<int>(rect.width())
- % HexString<int>(rect.height())
- % HexString<QRgb>(gradientStart.rgba())
- % HexString<QRgb>(gradientStop.rgba());
-
- QPixmap cache;
- QPainter *p = painter;
- QRect r = rect;
-
- bool doPixmapCache = painter->deviceTransform().isIdentity()
- && painter->worldMatrix().isIdentity();
- if (doPixmapCache && QPixmapCache::find(gradientName, cache)) {
- painter->drawPixmap(rect, cache);
- } else {
- if (doPixmapCache) {
- cache = QPixmap(rect.size());
- cache.fill(Qt::transparent);
- p = new QPainter(&cache);
- r = QRect(0, 0, rect.width(), rect.height());
- }
-
- int x = r.center().x();
- QLinearGradient gradient(x, r.top(), x, r.bottom());
- gradient.setColorAt(0, gradientStart);
- gradient.setColorAt(1, gradientStop);
- p->fillRect(r, gradient);
-
- if (doPixmapCache) {
- p->end();
- delete p;
- painter->drawPixmap(rect, cache);
- QPixmapCache::insert(gradientName, cache);
- }
- }
-}
-
-static void qt_plastique_drawFrame(QPainter *painter, const QStyleOption *option, const QWidget *widget)
-{
- QRect rect = option->rect;
- QPen oldPen = painter->pen();
-
- QColor borderColor = option->palette.background().color().darker(178);
- QColor gradientStartColor = option->palette.button().color().lighter(104);
- QColor gradientStopColor = option->palette.button().color().darker(105);
- QColor alphaCornerColor;
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
- }
-
- QLine lines[4];
- QPoint points[8];
-
- // outline / border
- painter->setPen(borderColor);
- lines[0] = QLine(rect.left() + 2, rect.top(), rect.right() - 2, rect.top());
- lines[1] = QLine(rect.left() + 2, rect.bottom(), rect.right() - 2, rect.bottom());
- lines[2] = QLine(rect.left(), rect.top() + 2, rect.left(), rect.bottom() - 2);
- lines[3] = QLine(rect.right(), rect.top() + 2, rect.right(), rect.bottom() - 2);
- painter->drawLines(lines, 4);
-
- points[0] = QPoint(rect.left() + 1, rect.top() + 1);
- points[1] = QPoint(rect.right() - 1, rect.top() + 1);
- points[2] = QPoint(rect.left() + 1, rect.bottom() - 1);
- points[3] = QPoint(rect.right() - 1, rect.bottom() - 1);
- painter->drawPoints(points, 4);
-
- painter->setPen(alphaCornerColor);
-
- points[0] = QPoint(rect.left() + 1, rect.top());
- points[1] = QPoint(rect.right() - 1, rect.top());
- points[2] = QPoint(rect.left() + 1, rect.bottom());
- points[3] = QPoint(rect.right() - 1, rect.bottom());
- points[4] = QPoint(rect.left(), rect.top() + 1);
- points[5] = QPoint(rect.right(), rect.top() + 1);
- points[6] = QPoint(rect.left(), rect.bottom() - 1);
- points[7] = QPoint(rect.right(), rect.bottom() - 1);
- painter->drawPoints(points, 8);
-
- // inner border
- if ((option->state & QStyle::State_Sunken) || (option->state & QStyle::State_On))
- painter->setPen(option->palette.button().color().darker(118));
- else
- painter->setPen(gradientStartColor);
-
- lines[0] = QLine(rect.left() + 2, rect.top() + 1, rect.right() - 2, option->rect.top() + 1);
- lines[1] = QLine(rect.left() + 1, rect.top() + 2, rect.left() + 1, option->rect.bottom() - 2);
- painter->drawLines(lines, 2);
-
- if ((option->state & QStyle::State_Sunken) || (option->state & QStyle::State_On))
- painter->setPen(option->palette.button().color().darker(110));
- else
- painter->setPen(gradientStopColor.darker(102));
-
- lines[0] = QLine(rect.left() + 2, rect.bottom() - 1, rect.right() - 2, rect.bottom() - 1);
- lines[1] = QLine(rect.right() - 1, rect.top() + 2, rect.right() - 1, rect.bottom() - 2);
- painter->drawLines(lines, 2);
-
- painter->setPen(oldPen);
-}
-
-static void qt_plastique_drawShadedPanel(QPainter *painter, const QStyleOption *option, bool base,
- const QWidget *widget)
-{
- QRect rect = option->rect;
- QPen oldPen = painter->pen();
-
- QColor gradientStartColor = option->palette.button().color().lighter(104);
- QColor gradientStopColor = option->palette.button().color().darker(105);
-
- // gradient fill
- if ((option->state & QStyle::State_Enabled) || !(option->state & QStyle::State_AutoRaise)) {
- if ((option->state & QStyle::State_Sunken) || (option->state & QStyle::State_On)) {
- qt_plastique_draw_gradient(painter, rect.adjusted(1, 1, -1, -1),
- option->palette.button().color().darker(114),
- option->palette.button().color().darker(106));
- } else {
- qt_plastique_draw_gradient(painter, rect.adjusted(1, 1, -1, -1),
- base ? option->palette.background().color().lighter(105) : gradientStartColor,
- base ? option->palette.background().color().darker(102) : gradientStopColor);
- }
- }
-
- qt_plastique_drawFrame(painter, option, widget);
-
- painter->setPen(oldPen);
-}
-
-static void qt_plastique_draw_mdibutton(QPainter *painter, const QStyleOptionTitleBar *option, const QRect &tmp, bool hover, bool sunken)
-{
- if (tmp.isNull())
- return;
- bool active = (option->titleBarState & QStyle::State_Active);
-
- // ### use palette colors instead
- QColor mdiButtonGradientStartColor;
- QColor mdiButtonGradientStopColor;
- if (active) {
- mdiButtonGradientStartColor = QColor((hover || sunken) ? 0x7d8bb1 : 0x55689a);
- mdiButtonGradientStopColor = QColor((hover || sunken) ? 0x939ebe : 0x7381ab);
- } else {
- mdiButtonGradientStartColor = QColor((hover || sunken) ? 0x9e9e9e : 0x818181);
- mdiButtonGradientStopColor = QColor((hover || sunken) ? 0xababab : 0x929292);
- }
-
- qt_plastique_draw_gradient(painter, tmp.adjusted(1, 1, -1, -1),
- mdiButtonGradientStartColor, mdiButtonGradientStopColor);
-
- QColor mdiButtonBorderColor;
- if (active) {
- mdiButtonBorderColor = (hover || sunken) ? QColor(0x627097) : QColor(0x324577);
- } else {
- mdiButtonBorderColor = (hover || sunken) ? QColor(0x838383) : QColor(0x5e5e5e);
- }
- painter->setPen(QPen(mdiButtonBorderColor, 1));
-
- const QLine lines[4] = {
- QLine(tmp.left() + 2, tmp.top(), tmp.right() - 2, tmp.top()),
- QLine(tmp.left() + 2, tmp.bottom(), tmp.right() - 2, tmp.bottom()),
- QLine(tmp.left(), tmp.top() + 2, tmp.left(), tmp.bottom() - 2),
- QLine(tmp.right(), tmp.top() + 2, tmp.right(), tmp.bottom() - 2) };
- painter->drawLines(lines, 4);
-
- const QPoint points[4] = {
- QPoint(tmp.left() + 1, tmp.top() + 1),
- QPoint(tmp.right() - 1, tmp.top() + 1),
- QPoint(tmp.left() + 1, tmp.bottom() - 1),
- QPoint(tmp.right() - 1, tmp.bottom() - 1) };
- painter->drawPoints(points, 4);
-}
-
-#ifndef QT_NO_DOCKWIDGET
-static QString elliditide(const QString &text, const QFontMetrics &fontMetrics, const QRect &rect, int *textWidth = 0)
-{
- // Chop and insert ellide into title if text is too wide
- QString title = text;
- int width = textWidth ? *textWidth : fontMetrics.width(text);
- QString ellipsis = QLatin1String("...");
- if (width > rect.width()) {
- QString leftHalf = title.left(title.size() / 2);
- QString rightHalf = title.mid(leftHalf.size() + 1);
- while (!leftHalf.isEmpty() && !rightHalf.isEmpty()) {
- leftHalf.chop(1);
- int width = fontMetrics.width(leftHalf + ellipsis + rightHalf);
- if (width < rect.width()) {
- title = leftHalf + ellipsis + rightHalf;
- width = width;
- break;
- }
- rightHalf.remove(0, 1);
- width = fontMetrics.width(leftHalf + ellipsis + rightHalf);
- if (width < rect.width()) {
- title = leftHalf + ellipsis + rightHalf;
- width = width;
- break;
- }
- }
- }
- if (textWidth)
- *textWidth = width;
- return title;
-}
-#endif
-
-#if !defined(QT_NO_DOCKWIDGET) || !defined(QT_NO_SPLITTER)
-static void qt_plastique_draw_handle(QPainter *painter, const QStyleOption *option,
- const QRect &rect, Qt::Orientation orientation,
- const QWidget *widget)
-{
- QColor borderColor = option->palette.background().color().darker(178);
- QColor alphaCornerColor;
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
- }
- QImage handle(qt_simple_toolbarhandle);
- alphaCornerColor.setAlpha(170);
- handle.setColor(1, alphaCornerColor.rgba());
- handle.setColor(2, mergedColors(alphaCornerColor, option->palette.light().color()).rgba());
- handle.setColor(3, option->palette.light().color().rgba());
-
- const int spacing = 2;
-
- if (orientation == Qt::Vertical) {
- int nchunks = rect.width() / (handle.width() + spacing);
- for (int i = 0; i < nchunks; ++i)
- painter->drawImage(QPoint(rect.left() + i * (handle.width() + spacing), rect.top()), handle);
- } else {
- int nchunks = rect.height() / (handle.height() + spacing);
- for (int i = 0; i < nchunks; ++i)
- painter->drawImage(QPoint(rect.left(), rect.top() + i * (handle.height() + spacing)), handle);
- }
-}
-#endif
-
-class QPlastiqueStylePrivate : public QWindowsStylePrivate
-{
- Q_DECLARE_PUBLIC(QPlastiqueStyle)
-public:
- QPlastiqueStylePrivate();
- virtual ~QPlastiqueStylePrivate();
- void drawPartialFrame(QPainter *painter, const QStyleOptionComplex *option,
- const QRect &rect, const QWidget *widget) const;
-
-#ifndef QT_NO_PROGRESSBAR
- QList<QProgressBar *> bars;
- int progressBarAnimateTimer;
- QElapsedTimer timer;
-#endif
-};
-
-/*!
- \internal
- */
-QPlastiqueStylePrivate::QPlastiqueStylePrivate() :
- QWindowsStylePrivate()
-#ifndef QT_NO_PROGRESSBAR
- , progressBarAnimateTimer(0)
-#endif
-{
-}
-
-/*!
- \internal
- */
-QPlastiqueStylePrivate::~QPlastiqueStylePrivate()
-{
-}
-
-/*!
- \class QPlastiqueStyle
- \brief The QPlastiqueStyle class provides a widget style similar to the
- Plastik style available in KDE.
-
- The Plastique style provides a default look and feel for widgets on X11
- that closely resembles the Plastik style, introduced by Sandro Giessl in
- KDE 3.2.
-
- \img qplastiquestyle.png
- \sa QWindowsXPStyle, QMacStyle, QWindowsStyle, QCDEStyle, QMotifStyle
-*/
-
-/*!
- Constructs a QPlastiqueStyle object.
-*/
-QPlastiqueStyle::QPlastiqueStyle()
- : QWindowsStyle(*new QPlastiqueStylePrivate)
-{
- setObjectName(QLatin1String("Plastique"));
-}
-
-/*!
- Destructs the QPlastiqueStyle object.
-*/
-QPlastiqueStyle::~QPlastiqueStyle()
-{
-}
-
-/*
- Used by spin- and combo box.
- Draws a rounded frame around rect but omits the right hand edge
-*/
-void QPlastiqueStylePrivate::drawPartialFrame(QPainter *painter, const QStyleOptionComplex *option,
- const QRect &rect, const QWidget *widget) const
-{
- Q_Q(const QPlastiqueStyle);
- bool reverse = option->direction == Qt::RightToLeft;
- QStyleOptionFrame frameOpt;
-#ifndef QT_NO_LINEEDIT
- if (QLineEdit *lineedit = widget->findChild<QLineEdit *>())
- frameOpt.initFrom(lineedit);
-#else
- Q_UNUSED(widget)
-#endif // QT_NO_LINEEDIT
-
- frameOpt.rect = rect;
- painter->save();
- frameOpt.rect.adjust(-blueFrameWidth + (reverse ? 1 : 0), -blueFrameWidth,
- blueFrameWidth + (reverse ? 0 : -1), blueFrameWidth);
- painter->setClipRect(frameOpt.rect);
- frameOpt.rect.adjust(reverse ? -2 : 0, 0, reverse ? 0 : 2, 0);
- frameOpt.lineWidth = q->pixelMetric(QStyle::PM_DefaultFrameWidth);
- frameOpt.midLineWidth = 0;
- frameOpt.state = option->state | QStyle::State_Sunken;
- frameOpt.palette = option->palette;
- q->drawPrimitive(QStyle::PE_PanelLineEdit, &frameOpt, painter, widget);
- painter->restore();
-
- // Draw a two pixel highlight on the flat edge
- if (option->state & QStyle::State_HasFocus) {
- painter->setPen(QPen(option->palette.highlight(), 0));
- QBrush focusBorder = option->palette.highlight();
- qBrushSetAlphaF(&focusBorder, qreal(0.65));
- if (!reverse) {
- painter->drawLine(rect.topRight() + QPoint(1, -1),
- rect.bottomRight() + QPoint(1, 1));
- painter->setPen(QPen(focusBorder, 0));
- painter->drawLine(rect.topRight(),
- rect.bottomRight());
- }
- else {
- painter->drawLine(rect.topLeft() + QPoint(-1, -1),
- rect.bottomLeft() + QPoint(-1, 1));
- painter->setPen(QPen(focusBorder, 0));
- painter->drawLine(rect.topLeft(),
- rect.bottomLeft());
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const
-{
- Q_ASSERT(option);
-
- QColor borderColor = option->palette.background().color().darker(178);
- QColor alphaCornerColor;
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
- }
- QColor alphaTextColor = mergedColors(option->palette.background().color(), option->palette.text().color());
-
- switch (element) {
- case PE_IndicatorButtonDropDown:
- proxy()->drawPrimitive(PE_PanelButtonTool, option, painter, widget);
- break;
- case PE_FrameDefaultButton: {
- if (!(option->state & QStyle::State_Enabled))
- break;
- painter->setPen(QPen(QColor(0, 0, 0, 127), 0));
- const QLine lines[4] = {
- QLine(option->rect.left() + 2, option->rect.top(),
- option->rect.right() - 2, option->rect.top()),
- QLine(option->rect.left() + 2, option->rect.bottom(),
- option->rect.right() - 2, option->rect.bottom()),
- QLine(option->rect.left(), option->rect.top() + 2,
- option->rect.left(), option->rect.bottom() - 2),
- QLine(option->rect.right(), option->rect.top() + 2,
- option->rect.right(), option->rect.bottom() - 2) };
- painter->drawLines(lines, 4);
-
- QPoint points[8];
- points[0] = QPoint(option->rect.left() + 1, option->rect.top() + 1);
- points[1] = QPoint(option->rect.right() - 1, option->rect.top() + 1);
- points[2] = QPoint(option->rect.left() + 1, option->rect.bottom() - 1);
- points[3] = QPoint(option->rect.right() - 1, option->rect.bottom() - 1);
- painter->drawPoints(points, 4);
-
- painter->setPen(QPen(QColor(0, 0, 0, 63), 0));
- points[0] = QPoint(option->rect.left() + 1, option->rect.top());
- points[1] = QPoint(option->rect.right() - 1, option->rect.top());
- points[2] = QPoint(option->rect.left(), option->rect.top() + 1);
- points[3] = QPoint(option->rect.right(), option->rect.top() + 1);
- points[4] = QPoint(option->rect.left() + 1, option->rect.bottom());
- points[5] = QPoint(option->rect.right() - 1, option->rect.bottom());
- points[6] = QPoint(option->rect.left(), option->rect.bottom() - 1);
- points[7] = QPoint(option->rect.right(), option->rect.bottom() - 1);
- painter->drawPoints(points, 8);
-
- break;
- }
-#ifndef QT_NO_TABWIDGET
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option)) {
- if (twf->shape != QTabBar::RoundedNorth && twf->shape != QTabBar::RoundedWest &&
- twf->shape != QTabBar::RoundedSouth && twf->shape != QTabBar::RoundedEast) {
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- break;
- }
-
- int borderThickness = proxy()->pixelMetric(PM_TabBarBaseOverlap, twf, widget);
- bool reverse = (twf->direction == Qt::RightToLeft);
-
- painter->save();
-
- // Start by filling the contents of the tab widget frame (which is
- // actually a panel).
- painter->fillRect(option->rect.adjusted(1, 1, -1, -1), option->palette.window());
-
- QRect tabBarRect;
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- if (reverse)
- tabBarRect = QRect(twf->rect.right() - twf->leftCornerWidgetSize.width() - twf->tabBarSize.width() + 1, twf->rect.top(), twf->tabBarSize.width(), borderThickness);
- else
- tabBarRect = QRect(twf->rect.left() + twf->leftCornerWidgetSize.width(), twf->rect.top(), twf->tabBarSize.width(), borderThickness);
- break ;
- case QTabBar::RoundedWest:
- tabBarRect = QRect(twf->rect.left(), twf->rect.top() + twf->leftCornerWidgetSize.height(), borderThickness, twf->tabBarSize.height());
- break ;
- case QTabBar::RoundedEast:
- tabBarRect = QRect(twf->rect.right() - borderThickness + 1, twf->rect.top() + twf->leftCornerWidgetSize.height(),
- borderThickness, twf->tabBarSize.height());
- break ;
- case QTabBar::RoundedSouth:
- if (reverse)
- tabBarRect = QRect(twf->rect.right() - twf->leftCornerWidgetSize.width() - twf->tabBarSize.width() + 1,
- twf->rect.bottom() - borderThickness + 1, twf->tabBarSize.width(), borderThickness);
- else
- tabBarRect = QRect(twf->rect.left() + twf->leftCornerWidgetSize.width(),
- twf->rect.bottom() - borderThickness + 1, twf->tabBarSize.width(), borderThickness);
- break ;
- default:
- break;
- }
-
- QRegion region(twf->rect);
- region -= tabBarRect;
- painter->setClipRegion(region);
-
- // Outer border
- QLine leftLine = QLine(twf->rect.topLeft() + QPoint(0, 2), twf->rect.bottomLeft() - QPoint(0, 2));
- QLine rightLine = QLine(twf->rect.topRight() + QPoint(0, 2), twf->rect.bottomRight() - QPoint(0, 2));
- QLine bottomLine = QLine(twf->rect.bottomLeft() + QPoint(2, 0), twf->rect.bottomRight() - QPoint(2, 0));
- QLine topLine = QLine(twf->rect.topLeft() + QPoint(2, 0), twf->rect.topRight() - QPoint(2, 0));
-
- QBrush border = option->palette.shadow();
- qBrushSetAlphaF(&border, qreal(0.4));
- painter->setPen(QPen(border, 0));
-
- QVarLengthArray<QLine, 4> lines;
- QVarLengthArray<QPoint, 8> points;
-
- lines.append(topLine);
-
- // Inner border
- QLine innerLeftLine = QLine(leftLine.p1() + QPoint(1, 0), leftLine.p2() + QPoint(1, 0));
- QLine innerRightLine = QLine(rightLine.p1() - QPoint(1, 0), rightLine.p2() - QPoint(1, 0));
- QLine innerBottomLine = QLine(bottomLine.p1() - QPoint(0, 1), bottomLine.p2() - QPoint(0, 1));
- QLine innerTopLine = QLine(topLine.p1() + QPoint(0, 1), topLine.p2() + QPoint(0, 1));
-
- // Rounded Corner
- QPoint leftBottomOuterCorner = QPoint(innerLeftLine.p2() + QPoint(0, 1));
- QPoint leftBottomInnerCorner1 = QPoint(leftLine.p2() + QPoint(0, 1));
- QPoint leftBottomInnerCorner2 = QPoint(bottomLine.p1() - QPoint(1, 0));
- QPoint rightBottomOuterCorner = QPoint(innerRightLine.p2() + QPoint(0, 1));
- QPoint rightBottomInnerCorner1 = QPoint(rightLine.p2() + QPoint(0, 1));
- QPoint rightBottomInnerCorner2 = QPoint(bottomLine.p2() + QPoint(1, 0));
- QPoint rightTopOuterCorner = QPoint(innerRightLine.p1() - QPoint(0, 1));
- QPoint rightTopInnerCorner1 = QPoint(rightLine.p1() - QPoint(0, 1));
- QPoint rightTopInnerCorner2 = QPoint(topLine.p2() + QPoint(1, 0));
- QPoint leftTopOuterCorner = QPoint(innerLeftLine.p1() - QPoint(0, 1));
- QPoint leftTopInnerCorner1 = QPoint(leftLine.p1() - QPoint(0, 1));
- QPoint leftTopInnerCorner2 = QPoint(topLine.p1() - QPoint(1, 0));
-
- lines.append(leftLine);
- lines.append(rightLine);
- lines.append(bottomLine);
-
- painter->drawLines(lines.constData(), lines.size());
- lines.clear();
-
- points.append(leftBottomOuterCorner);
- points.append(rightBottomOuterCorner);
- points.append(rightTopOuterCorner);
- points.append(leftTopOuterCorner);
-
- painter->drawPoints(points.constData(), points.size());
- points.clear();
-
- QBrush innerTopLeft = option->palette.shadow();
- qBrushSetAlphaF(&innerTopLeft, qreal(0.075));
- painter->setPen(QPen(innerTopLeft, 0));
-
- lines.append(innerLeftLine);
- lines.append(innerTopLine);
- painter->drawLines(lines.constData(), lines.size());
- lines.clear();
-
- QBrush innerBottomRight = option->palette.shadow();
- qBrushSetAlphaF(&innerBottomRight, qreal(0.23));
- painter->setPen(QPen(innerBottomRight, 0));
- lines.append(innerRightLine);
- lines.append(innerBottomLine);
- painter->drawLines(lines.constData(), lines.size());
- lines.clear();
-
- QBrush corner = option->palette.shadow();
- qBrushSetAlphaF(&corner, 0.25);
- painter->setPen(QPen(corner, 0));
- points.append(leftBottomInnerCorner1);
- points.append(leftBottomInnerCorner2);
- points.append(rightBottomInnerCorner1);
- points.append(rightBottomInnerCorner2);
- points.append(rightTopInnerCorner1);
- points.append(rightTopInnerCorner2);
- points.append(leftTopInnerCorner1);
- points.append(leftTopInnerCorner2);
- painter->drawPoints(points.constData(), points.size());
- points.clear();
-
- painter->restore();
- }
- break ;
-#endif // QT_NO_TABWIDGET
-#ifndef QT_NO_TABBAR
- case PE_FrameTabBarBase:
- if (const QStyleOptionTabBarBase *tbb = qstyleoption_cast<const QStyleOptionTabBarBase *>(option)) {
- if (tbb->shape != QTabBar::RoundedNorth && tbb->shape != QTabBar::RoundedWest &&
- tbb->shape != QTabBar::RoundedSouth && tbb->shape != QTabBar::RoundedEast) {
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- break;
- }
-
- painter->save();
-
- QRegion region(tbb->rect);
- region -= tbb->tabBarRect;
- painter->setClipRegion(region);
-
- QLine topLine = QLine(tbb->rect.bottomLeft() - QPoint(0, 1), tbb->rect.bottomRight() - QPoint(0, 1));
- QLine bottomLine = QLine(tbb->rect.bottomLeft(), tbb->rect.bottomRight());
-
- QBrush border = option->palette.shadow();
- qBrushSetAlphaF(&border, qreal(0.4));
- QBrush innerTopLeft = option->palette.shadow();
- qBrushSetAlphaF(&innerTopLeft, qreal(0.075));
- QBrush innerBottomRight = option->palette.shadow();
- qBrushSetAlphaF(&innerBottomRight, qreal(0.23));
- QBrush corner = option->palette.shadow();
- qBrushSetAlphaF(&corner, 0.25);
-
- if (tbb->shape == QTabBar::RoundedSouth)
- painter->setPen(QPen(corner, 0));
- else
- painter->setPen(QPen(border, 0));
- painter->drawLine(topLine);
-
- if (tbb->shape != QTabBar::RoundedSouth)
- painter->setPen(QPen(innerTopLeft, 0));
- else
- painter->setPen(QPen(border, 0));
- painter->drawLine(bottomLine);
-
- painter->restore();
- }
- break ;
-#endif // QT_NO_TABBAR
-#ifndef QT_NO_GROUPBOX
- case PE_FrameGroupBox:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- QStyleOptionFrameV2 frameV2(*frame);
- if (frameV2.features & QStyleOptionFrameV2::Flat) {
- QPen oldPen = painter->pen();
- painter->setPen(borderColor);
- painter->drawLine(frameV2.rect.topLeft(), frameV2.rect.topRight());
- painter->setPen(oldPen);
- } else {
- frameV2.state &= ~(State_Sunken | State_HasFocus);
- proxy()->drawPrimitive(PE_Frame, &frameV2, painter, widget);
- }
- }
- break;
-#endif // QT_NO_GROUPBOX
- case PE_Frame: {
- QFrame::Shadow shadow = QFrame::Plain;
- if (option->state & State_Sunken)
- shadow = QFrame::Sunken;
- else if (option->state & State_Raised)
- shadow = QFrame::Raised;
- qt_plastique_draw_frame(painter, option->rect, option, shadow);
- break;
- }
-#ifndef QT_NO_LINEEDIT
- case PE_FrameLineEdit:
- qt_plastique_draw_frame(painter, option->rect, option, QFrame::Sunken);
- break;
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *lineEdit = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- // Panel of a line edit inside combo box or spin box is drawn in CC_ComboBox and CC_SpinBox
- if (widget) {
-#ifndef QT_NO_SPINBOX
- // Spinbox doesn't need a separate palette for the lineedit
- if (qobject_cast<const QAbstractSpinBox *>(widget->parentWidget()))
- break;
-#endif
- }
-
- painter->save();
-
- // Fill the line edit insides
- QRect filledRect = lineEdit->rect.adjusted(1, 1, -1, -1);
- QBrush baseBrush = qMapBrushToRect(lineEdit->palette.base(), filledRect);
- painter->setBrushOrigin(filledRect.topLeft());
- painter->fillRect(filledRect.adjusted(1, 1, -1, -1), baseBrush);
-
- painter->setPen(QPen(baseBrush, 0));
- const QLine lines[4] = {
- QLine(filledRect.left(), filledRect.top() + 1,
- filledRect.left(), filledRect.bottom() - 1),
- QLine(filledRect.right(), filledRect.top() + 1,
- filledRect.right(), filledRect.bottom() - 1),
- QLine(filledRect.left() + 1, filledRect.top(),
- filledRect.right() - 1, filledRect.top()),
- QLine(filledRect.left() + 1, filledRect.bottom(),
- filledRect.right() - 1, filledRect.bottom()) };
- painter->drawLines(lines, 4);
-
- if (lineEdit->lineWidth != 0)
- qt_plastique_draw_frame(painter, option->rect, option, QFrame::Sunken);
-
- painter->restore();
- break;
- }
-#endif // QT_NO_LINEEDIT
- case PE_FrameDockWidget:
- case PE_FrameMenu:
- case PE_FrameStatusBarItem: {
- // Draws the frame around a popup menu.
- QPen oldPen = painter->pen();
- painter->setPen(borderColor);
- painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
- painter->setPen(alphaCornerColor);
- const QPoint points[4] = {
- QPoint(option->rect.topLeft()),
- QPoint(option->rect.topRight()),
- QPoint(option->rect.bottomLeft()),
- QPoint(option->rect.bottomRight()) };
- painter->drawPoints(points, 4);
- painter->setPen(oldPen);
- break;
- }
-#ifdef QT3_SUPPORT
- case PE_Q3DockWindowSeparator: {
- QPen oldPen = painter->pen();
- painter->setPen(alphaCornerColor);
- QRect rect = option->rect;
- if (option->state & State_Horizontal) {
- painter->drawLine(rect.right(), rect.top() + 2, rect.right(), rect.bottom() - 1);
- } else {
- painter->drawLine(rect.left() + 2, rect.bottom(), rect.right() - 1, rect.bottom());
- }
- painter->setPen(oldPen);
- break;
- }
- case PE_Q3Separator: {
- QPen oldPen = painter->pen();
- painter->setPen(alphaCornerColor);
- if ((option->state & State_Horizontal) == 0)
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- else
- painter->drawLine(option->rect.topRight(), option->rect.bottomRight());
- painter->setPen(option->palette.background().color().lighter(104));
- if ((option->state & State_Horizontal) == 0)
- painter->drawLine(option->rect.topLeft(), option->rect.topRight());
- else
- painter->drawLine(option->rect.topLeft(), option->rect.bottomLeft());
- painter->setPen(oldPen);
- break;
- }
-#endif // QT3_SUPPORT
-#ifndef QT_NO_MAINWINDOW
- case PE_PanelMenuBar:
- if ((widget && qobject_cast<const QMainWindow *>(widget->parentWidget()))
-#ifdef QT3_SUPPORT
- || (widget && widget->parentWidget() && widget->parentWidget()->inherits("Q3MainWindow"))
-#endif
- ) {
- // Draws the light line above and the dark line below menu bars and
- // tool bars.
- QPen oldPen = painter->pen();
- if (element == PE_PanelMenuBar || (option->state & State_Horizontal)) {
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.left(), option->rect.bottom(),
- option->rect.right(), option->rect.bottom());
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.left(), option->rect.top(),
- option->rect.right(), option->rect.top());
- } else {
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.left(), option->rect.top(),
- option->rect.left(), option->rect.bottom());
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.right(), option->rect.top(),
- option->rect.right(), option->rect.bottom());
- }
- painter->setPen(oldPen);
- }
- break;
-#endif // QT_NO_MAINWINDOW
- case PE_IndicatorHeaderArrow: {
- bool usedAntialiasing = painter->renderHints() & QPainter::Antialiasing;
- if (!usedAntialiasing)
- painter->setRenderHint(QPainter::Antialiasing);
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- if (!usedAntialiasing)
- painter->setRenderHint(QPainter::Antialiasing, false);
- break;
- }
- case PE_PanelButtonTool:
- // Draws a tool button (f.ex., in QToolBar and QTabBar)
- if ((option->state & State_Enabled || option->state & State_On) || !(option->state & State_AutoRaise))
- qt_plastique_drawShadedPanel(painter, option, true, widget);
- break;
-#ifndef QT_NO_TOOLBAR
- case PE_IndicatorToolBarHandle: {
- QPixmap cache;
- QRect rect = option->rect;
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindowHandle") && widget->parentWidget()->inherits("Q3DockWindow")) {
- if (!(option->state & State_Horizontal))
- rect.adjust(2, 0, -2, 0);
- }
-#endif
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("toolbarhandle"), option, rect.size());
- if (!QPixmapCache::find(pixmapName, cache)) {
- cache = QPixmap(rect.size());
- cache.fill(Qt::transparent);
- QPainter cachePainter(&cache);
- QRect cacheRect(QPoint(0, 0), rect.size());
- if (widget)
- cachePainter.fillRect(cacheRect, option->palette.brush(widget->backgroundRole()));
- else
- cachePainter.fillRect(cacheRect, option->palette.background());
-
- QImage handle(qt_toolbarhandle);
- alphaCornerColor.setAlpha(170);
- handle.setColor(1, alphaCornerColor.rgba());
- handle.setColor(2, mergedColors(alphaCornerColor, option->palette.light().color()).rgba());
- handle.setColor(3, option->palette.light().color().rgba());
-
- if (option->state & State_Horizontal) {
- int nchunks = cacheRect.height() / handle.height();
- int indent = (cacheRect.height() - (nchunks * handle.height())) / 2;
- for (int i = 0; i < nchunks; ++i)
- cachePainter.drawImage(QPoint(cacheRect.left() + 3, cacheRect.top() + indent + i * handle.height()),
- handle);
- } else {
- int nchunks = cacheRect.width() / handle.width();
- int indent = (cacheRect.width() - (nchunks * handle.width())) / 2;
- for (int i = 0; i < nchunks; ++i)
- cachePainter.drawImage(QPoint(cacheRect.left() + indent + i * handle.width(), cacheRect.top() + 3),
- handle);
- }
- cachePainter.end();
- QPixmapCache::insert(pixmapName, cache);
- }
- painter->drawPixmap(rect.topLeft(), cache);
- break;
- }
- case PE_IndicatorToolBarSeparator: {
- QPen oldPen = painter->pen();
- painter->setPen(alphaCornerColor);
- if (option->state & State_Horizontal) {
- painter->drawLine(option->rect.left(), option->rect.top() + 1, option->rect.left(), option->rect.bottom() - 2);
- painter->setPen(option->palette.base().color());
- painter->drawLine(option->rect.right(), option->rect.top() + 1, option->rect.right(), option->rect.bottom() - 2);
- } else {
- painter->drawLine(option->rect.left() + 1, option->rect.top(), option->rect.right() - 2, option->rect.top());
- painter->setPen(option->palette.base().color());
- painter->drawLine(option->rect.left() + 1, option->rect.bottom(), option->rect.right() - 2, option->rect.bottom());
- }
- painter->setPen(oldPen);
- break;
- }
-#endif // QT_NO_TOOLBAR
- case PE_PanelButtonCommand:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool sunken = (button->state & State_Sunken) || (button->state & State_On);
- if ((button->features & QStyleOptionButton::Flat) && !sunken)
- break;
-
- bool defaultButton = (button->features & (QStyleOptionButton::DefaultButton
- | QStyleOptionButton::AutoDefaultButton));
-
- BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("pushbutton-%1").arg(defaultButton))
-
- QPen oldPen = p->pen();
- bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver);
-
- // Give the painter a different brush origin for sunken buttons
- if (sunken) {
- // ### No such function
- // p->setPenOrigin(rect.left() + 1, rect.top() + 1);
- p->setBrushOrigin(rect.left() + 1, rect.top() + 1);
- }
-
- // Draw border
- qt_plastique_draw_frame(p, rect, option);
-
- // Fill the panel
- QRectF fillRect = rect.adjusted(2, 2, -2, -2);
-
- // Button colors
- QBrush alphaCornerBrush = qMapBrushToRect(qBrushDark(option->palette.button(), 165), rect);
- qBrushSetAlphaF(&alphaCornerBrush, 0.5);
- QBrush buttonGradientBrush;
- QBrush leftLineGradientBrush;
- QBrush rightLineGradientBrush;
- QBrush sunkenButtonGradientBrush;
- QBrush sunkenLeftLineGradientBrush;
- QBrush sunkenRightLineGradientBrush;
- QBrush buttonBrush = qMapBrushToRect(option->palette.button(), rect);
- if (buttonBrush.gradient() || !buttonBrush.texture().isNull()) {
- buttonGradientBrush = buttonBrush;
- sunkenButtonGradientBrush = qBrushDark(buttonBrush, 108);
- leftLineGradientBrush = qBrushLight(buttonBrush, 105);
- rightLineGradientBrush = qBrushDark(buttonBrush, 105);
- sunkenLeftLineGradientBrush = qBrushDark(buttonBrush, 110);
- sunkenRightLineGradientBrush = qBrushDark(buttonBrush, 106);
- } else {
- // Generate gradients
- QLinearGradient buttonGradient(rect.topLeft(), rect.bottomLeft());
- if (hover) {
- buttonGradient.setColorAt(0.0, mergedColors(option->palette.highlight().color(),
- buttonBrush.color().lighter(104), 6));
- buttonGradient.setColorAt(1.0, mergedColors(option->palette.highlight().color(),
- buttonBrush.color().darker(110), 6));
- } else {
- buttonGradient.setColorAt(0.0, buttonBrush.color().lighter(104));
- buttonGradient.setColorAt(1.0, buttonBrush.color().darker(110));
- }
- buttonGradientBrush = QBrush(buttonGradient);
-
- QLinearGradient buttonGradient2(rect.topLeft(), rect.bottomLeft());
- buttonGradient2.setColorAt(0.0, buttonBrush.color().darker(113));
- buttonGradient2.setColorAt(1.0, buttonBrush.color().darker(103));
- sunkenButtonGradientBrush = QBrush(buttonGradient2);
-
- QLinearGradient buttonGradient3(rect.topLeft(), rect.bottomLeft());
- buttonGradient3.setColorAt(0.0, buttonBrush.color().lighter(105));
- buttonGradient3.setColorAt(1.0, buttonBrush.color());
- leftLineGradientBrush = QBrush(buttonGradient3);
-
- QLinearGradient buttonGradient4(rect.topLeft(), rect.bottomLeft());
- buttonGradient4.setColorAt(0.0, buttonBrush.color());
- buttonGradient4.setColorAt(1.0, buttonBrush.color().darker(110));
- rightLineGradientBrush = QBrush(buttonGradient4);
-
- QLinearGradient buttonGradient5(rect.topLeft(), rect.bottomLeft());
- buttonGradient5.setColorAt(0.0, buttonBrush.color().darker(113));
- buttonGradient5.setColorAt(1.0, buttonBrush.color().darker(107));
- sunkenLeftLineGradientBrush = QBrush(buttonGradient5);
-
- QLinearGradient buttonGradient6(rect.topLeft(), rect.bottomLeft());
- buttonGradient6.setColorAt(0.0, buttonBrush.color().darker(108));
- buttonGradient6.setColorAt(1.0, buttonBrush.color().darker(103));
- sunkenRightLineGradientBrush = QBrush(buttonGradient6);
- }
-
- // Main fill
- p->fillRect(fillRect,
- qMapBrushToRect(sunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, rect));
-
- // Top line
- p->setPen(QPen(qBrushLight(qMapBrushToRect(sunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, rect), 105), 0));
- p->drawLine(QPointF(rect.left() + 2, rect.top() + 1),
- QPointF(rect.right() - 2, rect.top() + 1));
-
- // Bottom line
- p->setPen(QPen(qBrushDark(qMapBrushToRect(sunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, rect), 105), 0));
- p->drawLine(QPointF(rect.left() + 2, rect.bottom() - 1),
- QPointF(rect.right() - 2, rect.bottom() - 1));
-
- // Left line
- p->setPen(QPen(qMapBrushToRect(sunken ? sunkenLeftLineGradientBrush
- : leftLineGradientBrush, rect), 1));
- p->drawLine(QPointF(rect.left() + 1, rect.top() + 2),
- QPointF(rect.left() + 1, rect.bottom() - 2));
-
- // Right line
- p->setPen(QPen(qMapBrushToRect(sunken ? sunkenRightLineGradientBrush
- : rightLineGradientBrush, rect), 1));
- p->drawLine(QPointF(rect.right() - 1, rect.top() + 2),
- QPointF(rect.right() - 1, rect.bottom() - 2));
-
- // Hovering
- if (hover && !sunken) {
- QBrush hover = qMapBrushToRect(option->palette.highlight(), rect);
- QBrush hoverOuter = hover;
- qBrushSetAlphaF(&hoverOuter, qreal(0.7));
-
- QLine lines[2];
-
- p->setPen(QPen(hoverOuter, 0));
- lines[0] = QLine(rect.left() + 1, rect.top() + 1, rect.right() - 1, rect.top() + 1);
- lines[1] = QLine(rect.left() + 1, rect.bottom() - 1, rect.right() - 1, rect.bottom() - 1);
- p->drawLines(lines, 2);
-
- QBrush hoverInner = hover;
- qBrushSetAlphaF(&hoverInner, qreal(0.45));
- p->setPen(QPen(hoverInner, 0));
- lines[0] = QLine(rect.left() + 1, rect.top() + 2, rect.right() - 1, rect.top() + 2);
- lines[1] = QLine(rect.left() + 1, rect.bottom() - 2, rect.right() - 1, rect.bottom() - 2);
- p->drawLines(lines, 2);
-
- QBrush hoverSide = hover;
- qBrushSetAlphaF(&hoverSide, qreal(0.075));
- p->setPen(QPen(hoverSide, 0));
- lines[0] = QLine(rect.left() + 1, rect.top() + 2, rect.left() + 1, rect.bottom() - 2);
- lines[1] = QLine(rect.right() - 1, rect.top() + 2, rect.right() - 1, rect.bottom() - 2);
- p->drawLines(lines, 2);
- }
-
- p->setPen(oldPen);
-
- END_STYLE_PIXMAPCACHE
- }
- break;
- case PE_IndicatorCheckBox:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- BEGIN_STYLE_PIXMAPCACHE(QLatin1String("checkbox"))
-
- p->save();
-
- // Outline
- QBrush border = option->palette.shadow();
- qBrushSetAlphaF(&border, qreal(0.4));
- p->setPen(QPen(border, 0));
- const QLine lines[4] = {
- QLine(rect.left() + 1, rect.top(), rect.right() - 1, rect.top()),
- QLine(rect.left() + 1, rect.bottom(), rect.right() - 1, rect.bottom()),
- QLine(rect.left(), rect.top() + 1, rect.left(), rect.bottom() - 1),
- QLine(rect.right(), rect.top() + 1, rect.right(), rect.bottom() - 1) };
- p->drawLines(lines, 4);
-
- QBrush corner = option->palette.shadow();
- qBrushSetAlphaF(&corner, qreal(0.2));
- p->setPen(QPen(corner, 0));
- const QPoint points[4] = {
- rect.topLeft(), rect.topRight(),
- rect.bottomLeft(), rect.bottomRight() };
- p->drawPoints(points, 4);
-
- // Fill
- QBrush baseBrush = qMapBrushToRect(button->palette.base(), rect);
- if (!baseBrush.gradient() && baseBrush.texture().isNull()) {
- QLinearGradient gradient(rect.center().x(), rect.top(), rect.center().x(), rect.bottom());
- gradient.setColorAt(0, baseBrush.color());
- gradient.setColorAt(1, baseBrush.color().darker(105));
- baseBrush = gradient;
- }
- p->fillRect(rect.adjusted(1, 1, -1, -1), baseBrush);
-
- // Hover
- if ((button->state & State_Enabled) && (button->state & State_MouseOver)) {
- QBrush pen = qMapBrushToRect(button->palette.highlight(), rect);
- qBrushSetAlphaF(&pen, qreal(0.8));
- p->setPen(QPen(pen, 0));
- p->drawRect(rect.adjusted(1, 1, -2, -2));
- qBrushSetAlphaF(&pen, 0.5);
- p->setPen(QPen(pen, 0));
- p->drawRect(rect.adjusted(2, 2, -3, -3));
-
- qBrushSetAlphaF(&pen, qreal(0.2));
- p->setBrush(pen);
- p->drawRect(rect.adjusted(2, 2, -3, -3));
- }
-
- // Indicator
- bool on = button->state & State_On;
- bool sunken = button->state & State_Sunken;
- bool unchanged = button->state & State_NoChange;
- bool enabled = button->state & State_Enabled;
- if (on || (enabled && sunken) || unchanged) {
- p->setRenderHint(QPainter::Antialiasing);
- QBrush pointBrush = qMapBrushToRect(button->palette.text(), rect);
- if (sunken)
- qBrushSetAlphaF(&pointBrush, qreal(0.5));
- else if (unchanged)
- qBrushSetAlphaF(&pointBrush, qreal(0.3));
- p->setPen(QPen(pointBrush, 3));
- const QLine lines[2] = {
- QLine(rect.left() + 4, rect.top() + 4, rect.right() - 3, rect.bottom() - 3),
- QLine(rect.right() - 3, rect.top() + 4, rect.left() + 4, rect.bottom() - 3) };
- p->drawLines(lines, 2);
- }
-
- p->restore();
- END_STYLE_PIXMAPCACHE
- }
- break;
- case PE_IndicatorRadioButton:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- BEGIN_STYLE_PIXMAPCACHE(QLatin1String("radiobutton"))
-
- p->save();
- p->setRenderHint(QPainter::Antialiasing);
-
- // The the filled ellipse
- QBrush border = qMapBrushToRect(option->palette.shadow(), rect);
- qBrushSetAlphaF(&border, qreal(0.51));
- p->setPen(QPen(border, 0));
-
- QBrush baseBrush = qMapBrushToRect(button->palette.base(), rect);
- if (!baseBrush.gradient() && baseBrush.texture().isNull()) {
- QLinearGradient gradient(rect.center().x(), rect.top(), rect.center().x(), rect.bottom());
- gradient.setColorAt(0, baseBrush.color());
- gradient.setColorAt(1, baseBrush.color().darker(105));
- baseBrush = gradient;
- }
- p->setBrush(baseBrush);
- p->drawEllipse(QRectF(rect).adjusted(1, 1, -1, -1));
-
- // Hover
- if ((button->state & State_Enabled) && (button->state & State_MouseOver)) {
- QBrush pen = qMapBrushToRect(button->palette.highlight(), rect);
- qBrushSetAlphaF(&pen, qreal(0.8));
- p->setPen(QPen(pen, 0));
- qBrushSetAlphaF(&pen, qreal(0.2));
- p->setBrush(pen);
- p->drawEllipse(QRectF(rect).adjusted(2, 2, -2, -2));
- }
-
- // Indicator
- bool on = button->state & State_On;
- bool sunken = button->state & State_Sunken;
- bool enabled = button->state & State_Enabled;
- if (on || (enabled && sunken)) {
- p->setPen(Qt::NoPen);
- QBrush pointBrush = qMapBrushToRect(button->palette.text(), rect);
- if (sunken)
- qBrushSetAlphaF(&pointBrush, 0.5);
- p->setBrush(pointBrush);
- p->drawEllipse(QRectF(rect).adjusted(3, 3, -3, -3));
- }
-
- p->restore();
- END_STYLE_PIXMAPCACHE
- }
- break;
-#ifndef QT_NO_DOCKWIDGET
- case PE_IndicatorDockWidgetResizeHandle:
- if ((option->state & State_Enabled) && (option->state & State_MouseOver))
- painter->fillRect(option->rect, QColor(255, 255, 255, 128));
- if (option->state & State_Horizontal) {
- int width = option->rect.width() / 3;
- QRect rect(option->rect.center().x() - width / 2,
- option->rect.top() + (option->rect.height() / 2) - 1, width, 3);
- qt_plastique_draw_handle(painter, option, rect, Qt::Vertical, widget);
- } else {
- int height = option->rect.height() / 3;
- QRect rect(option->rect.left() + (option->rect.width() / 2 - 1),
- option->rect.center().y() - height / 2, 3, height);
- qt_plastique_draw_handle(painter, option, rect, Qt::Horizontal, widget);
- }
- break;
-#endif // QT_NO_DOCKWIDGET
- case PE_IndicatorViewItemCheck: {
- QStyleOptionButton button;
- button.QStyleOption::operator=(*option);
- button.state &= ~State_MouseOver;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &button, painter, widget);
- break;
- }
- case PE_FrameWindow: {
- painter->save();
- bool active = (option->state & State_Active);
- int titleBarStop = option->rect.top() + proxy()->pixelMetric(PM_TitleBarHeight, option, widget);
-
- QPalette palette = option->palette;
- if (!active)
- palette.setCurrentColorGroup(QPalette::Disabled);
-
- // Frame and rounded corners
- painter->setPen(mergedColors(palette.highlight().color(), Qt::black, 50));
-
- QLine lines[3];
- QPoint points[4];
-
- // bottom border line
- lines[0] = QLine(option->rect.left() + 1, option->rect.bottom(), option->rect.right() - 1, option->rect.bottom());
-
- // bottom left and right side border lines
- lines[1] = QLine(option->rect.left(), titleBarStop, option->rect.left(), option->rect.bottom() - 1);
- lines[2] = QLine(option->rect.right(), titleBarStop, option->rect.right(), option->rect.bottom() - 1);
- painter->drawLines(lines, 3);
- points[0] = QPoint(option->rect.left() + 1, option->rect.bottom() - 1);
- points[1] = QPoint(option->rect.right() - 1, option->rect.bottom() - 1);
- painter->drawPoints(points, 2);
-
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindow")) {
- // also draw the frame on the title bar
- lines[0] = QLine(option->rect.left() + 1, option->rect.top(),
- option->rect.right() - 1, option->rect.top());
- lines[1] = QLine(option->rect.left(), option->rect.top() + 1,
- option->rect.left(), titleBarStop);
- lines[2] = QLine(option->rect.right(), option->rect.top() + 1,
- option->rect.right(), titleBarStop);
- painter->drawLines(lines, 3);
- }
-#endif
-
- // alpha corners
- painter->setPen(mergedColors(palette.highlight().color(), palette.background().color(), 55));
- points[0] = QPoint(option->rect.left() + 2, option->rect.bottom() - 1);
- points[1] = QPoint(option->rect.left() + 1, option->rect.bottom() - 2);
- points[2] = QPoint(option->rect.right() - 2, option->rect.bottom() - 1);
- points[3] = QPoint(option->rect.right() - 1, option->rect.bottom() - 2);
- painter->drawPoints(points, 4);
-
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindow")) {
- // also draw the frame on the title bar
- points[0] = option->rect.topLeft();
- points[1] = option->rect.topRight();
- painter->drawPoints(points, 2);
- }
-#endif
-
- // upper and lower left inner
- painter->setPen(active ? mergedColors(palette.highlight().color(), palette.background().color()) : palette.background().color().darker(120));
- painter->drawLine(option->rect.left() + 1, titleBarStop, option->rect.left() + 1, option->rect.bottom() - 2);
-
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindow")) {
- // also draw the frame on the title bar
- lines[0] = QLine(option->rect.left() + 1, option->rect.top() + 1,
- option->rect.left() + 1, titleBarStop);
- lines[1] = QLine(option->rect.right() - 1, option->rect.top() + 1,
- option->rect.right() - 1, titleBarStop);
- lines[2] = QLine(option->rect.left() + 1, option->rect.top() + 1,
- option->rect.right() - 1, option->rect.top() + 1);
- painter->drawLines(lines, 3);
- }
-#endif
-
- painter->setPen(active ? mergedColors(palette.highlight().color(), palette.background().color(), 57) : palette.background().color().darker(130));
- lines[0] = QLine(option->rect.right() - 1, titleBarStop, option->rect.right() - 1, option->rect.bottom() - 2);
- lines[1] = QLine(option->rect.left() + 1, option->rect.bottom() - 1, option->rect.right() - 1, option->rect.bottom() - 1);
- painter->drawLines(lines, 2);
-
- painter->restore();
- }
- break;
- case PE_IndicatorBranch: {
- int mid_h = option->rect.x() + option->rect.width() / 2;
- int mid_v = option->rect.y() + option->rect.height() / 2;
- int bef_h = mid_h;
- int bef_v = mid_v;
- int aft_h = mid_h;
- int aft_v = mid_v;
- QBrush brush(option->palette.dark().color(), Qt::Dense4Pattern);
- if (option->state & State_Item) {
- if (option->direction == Qt::RightToLeft)
- painter->fillRect(option->rect.left(), mid_v, bef_h - option->rect.left(), 1, brush);
- else
- painter->fillRect(aft_h, mid_v, option->rect.right() - aft_h + 1, 1, brush);
- }
- if (option->state & State_Sibling)
- painter->fillRect(mid_h, aft_v, 1, option->rect.bottom() - aft_v + 1, brush);
- if (option->state & (State_Open | State_Children | State_Item | State_Sibling))
- painter->fillRect(mid_h, option->rect.y(), 1, bef_v - option->rect.y(), brush);
-
- if (option->state & State_Children) {
- painter->save();
- QPoint center = option->rect.center();
- // border
- QRect fullRect(center.x() - 4, center.y() - 4, 9, 9);
- painter->setPen(borderColor);
-
- const QLine lines[4] = {
- QLine(fullRect.left() + 1, fullRect.top(),
- fullRect.right() - 1, fullRect.top()),
- QLine(fullRect.left() + 1, fullRect.bottom(),
- fullRect.right() - 1, fullRect.bottom()),
- QLine(fullRect.left(), fullRect.top() + 1,
- fullRect.left(), fullRect.bottom() - 1),
- QLine(fullRect.right(), fullRect.top() + 1,
- fullRect.right(), fullRect.bottom() - 1) };
- painter->drawLines(lines, 4);
-
- // "antialiased" corners
- painter->setPen(alphaCornerColor);
- const QPoint points[4] = {
- fullRect.topLeft(),
- fullRect.topRight(),
- fullRect.bottomLeft(),
- fullRect.bottomRight() };
- painter->drawPoints(points, 4);
-
- // fill
- QRect adjustedRect = fullRect;
- QRect gradientRect(adjustedRect.left() + 1, adjustedRect.top() + 1,
- adjustedRect.right() - adjustedRect.left() - 1,
- adjustedRect.bottom() - adjustedRect.top() - 1);
- if (option->palette.base().style() == Qt::SolidPattern) {
- QColor baseGradientStartColor = option->palette.base().color().darker(101);
- QColor baseGradientStopColor = option->palette.base().color().darker(106);
- qt_plastique_draw_gradient(painter, gradientRect, baseGradientStartColor, baseGradientStopColor);
- } else {
- painter->fillRect(gradientRect, option->palette.base());
- }
- // draw "+" or "-"
- painter->setPen(alphaTextColor);
- painter->drawLine(center.x() - 2, center.y(), center.x() + 2, center.y());
- if (!(option->state & State_Open))
- painter->drawLine(center.x(), center.y() - 2, center.x(), center.y() + 2);
- painter->restore();
- }
- }
- break;
- default:
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const
-{
- QColor borderColor = option->palette.background().color().darker(178);
- QColor alphaCornerColor;
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
- }
- QColor alphaTextColor = mergedColors(option->palette.background().color(), option->palette.text().color());
-
- QColor gradientStartColor = option->palette.button().color().lighter(104);
- QColor gradientStopColor = option->palette.button().color().darker(105);
-
- QColor shadowGradientStartColor = option->palette.button().color().darker(115);
- QColor shadowGradientStopColor = option->palette.button().color().darker(120);
-
- QColor highlightedGradientStartColor = option->palette.button().color().lighter(101);
- QColor highlightedGradientStopColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 85);
-
- QColor lightShadowGradientStartColor = highlightedGradientStartColor.lighter(105);
- QColor lightShadowGradientStopColor = highlightedGradientStopColor.lighter(105);
-
- QColor highlightedDarkInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 35);
- QColor highlightedLightInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 58);
-
- QColor alphaInnerColor = mergedColors(highlightedDarkInnerBorderColor, option->palette.base().color());
- QColor lightShadow = lightShadowGradientStartColor;
- QColor shadow = shadowGradientStartColor;
-
- switch (element) {
-#ifndef QT_NO_TABBAR
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
-
- if (tab->shape != QTabBar::RoundedNorth && tab->shape != QTabBar::RoundedWest &&
- tab->shape != QTabBar::RoundedSouth && tab->shape != QTabBar::RoundedEast) {
- QWindowsStyle::drawControl(element, option, painter, widget);
- break;
- }
-
- painter->save();
-
- // Set up some convenience variables
- bool disabled = !(tab->state & State_Enabled);
- bool onlyTab = tab->position == QStyleOptionTab::OnlyOneTab;
- bool selected = tab->state & State_Selected;
- bool mouseOver = (tab->state & State_MouseOver) && !selected && !disabled;
- bool previousSelected = tab->selectedPosition == QStyleOptionTab::PreviousIsSelected;
- bool nextSelected = tab->selectedPosition == QStyleOptionTab::NextIsSelected;
- bool leftCornerWidget = (tab->cornerWidgets & QStyleOptionTab::LeftCornerWidget);
- bool reverse = (tab->direction == Qt::RightToLeft);
-
- int lowerTop = selected ? 0 : 3; // to make the selected tab bigger than the rest
- bool atEnd = (tab->position == QStyleOptionTab::End) || onlyTab;
- bool atBeginning = ((tab->position == QStyleOptionTab::Beginning) || onlyTab)
- && !leftCornerWidget;
- bool reverseShadow = false;
-
- int borderThickness = proxy()->pixelMetric(PM_TabBarBaseOverlap, tab, widget);
- int marginLeft = 0;
- if ((atBeginning && !selected) || (selected && leftCornerWidget && ((tab->position == QStyleOptionTab::Beginning) || onlyTab))) {
- marginLeft = 1;
- }
-
- // I've set the names based on the natural coordinate system. Vectors are used to rotate everything
- // if the orientation of the tab bare is different than north.
- {
- // Coordinates of corners of rectangle for transformation
- QPoint topLeft;
- QPoint topRight;
- QPoint bottomLeft;
- QPoint bottomRight;
-
- // Fill with normalized vectors in the direction of the coordinate system
- // (down and right should be complement of up and left, or it will look odd)
- QPoint vectorUp;
- QPoint vectorDown;
- QPoint vectorLeft;
- QPoint vectorRight;
-
- QBrush border = option->palette.shadow();
- qBrushSetAlphaF(&border, qreal(0.4));
- QBrush innerTopLeft = option->palette.shadow();
- qBrushSetAlphaF(&innerTopLeft, qreal(0.075));
- QBrush innerBottomRight = option->palette.shadow();
- qBrushSetAlphaF(&innerBottomRight, qreal(0.23));
- QBrush corner = option->palette.shadow();
- qBrushSetAlphaF(&corner, qreal(0.25));
-
- QBrush baseColor1;
- QBrush baseColor2;
-
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- vectorUp = QPoint(0, -1);
- vectorDown = QPoint(0, 1);
-
- if (reverse) {
- vectorLeft = QPoint(1, 0);
- vectorRight = QPoint(-1, 0);
- reverseShadow = true;
- } else {
- vectorLeft = QPoint(-1, 0);
- vectorRight = QPoint(1, 0);
- }
-
- if (reverse) {
- topLeft = tab->rect.topRight();
- topRight = tab->rect.topLeft();
- bottomLeft = tab->rect.bottomRight();
- bottomRight = tab->rect.bottomLeft();
- } else {
- topLeft = tab->rect.topLeft();
- topRight = tab->rect.topRight();
- bottomLeft = tab->rect.bottomLeft();
- bottomRight = tab->rect.bottomRight();
- }
-
-
- baseColor1 = border;
- baseColor2 = innerTopLeft;
- break ;
- case QTabBar::RoundedWest:
- vectorUp = QPoint(-1, 0);
- vectorDown = QPoint(1, 0);
- vectorLeft = QPoint(0, -1);
- vectorRight = QPoint(0, 1);
-
- topLeft = tab->rect.topLeft();
- topRight = tab->rect.bottomLeft();
- bottomLeft = tab->rect.topRight();
- bottomRight = tab->rect.bottomRight();
-
- baseColor1 = border;
- baseColor2 = innerTopLeft;
- break ;
- case QTabBar::RoundedEast:
- vectorUp = QPoint(1, 0);
- vectorDown = QPoint(-1, 0);
- vectorLeft = QPoint(0, -1);
- vectorRight = QPoint(0, 1);
-
- topLeft = tab->rect.topRight();
- topRight = tab->rect.bottomRight();
- bottomLeft = tab->rect.topLeft();
- bottomRight = tab->rect.bottomLeft();
-
- baseColor1 = border;
- baseColor2 = innerBottomRight;
- break ;
- case QTabBar::RoundedSouth:
- vectorUp = QPoint(0, 1);
- vectorDown = QPoint(0, -1);
-
- if (reverse) {
- vectorLeft = QPoint(1, 0);
- vectorRight = QPoint(-1, 0);
- reverseShadow = true;
-
- topLeft = tab->rect.bottomRight();
- topRight = tab->rect.bottomLeft();
- bottomLeft = tab->rect.topRight();
- bottomRight = tab->rect.topLeft();
- } else {
- vectorLeft = QPoint(-1, 0);
- vectorRight = QPoint(1, 0);
-
- topLeft = tab->rect.bottomLeft();
- topRight = tab->rect.bottomRight();
- bottomLeft = tab->rect.topLeft();
- bottomRight = tab->rect.topRight();
- }
-
- baseColor1 = border;
- baseColor2 = innerBottomRight;
- break ;
- default:
- break;
- }
-
- // Make the tab smaller when it's at the end, so that we are able to draw the corner
- if (atEnd) {
- topRight += vectorLeft;
- bottomRight += vectorLeft;
- }
-
- {
- // Outer border
- QLine topLine;
- {
- QPoint adjustTopLineLeft = (vectorRight * (marginLeft + (previousSelected ? 0 : 1))) +
- (vectorDown * lowerTop);
- QPoint adjustTopLineRight = (vectorDown * lowerTop);
- if (atBeginning || selected)
- adjustTopLineLeft += vectorRight;
- if (atEnd || selected)
- adjustTopLineRight += 2 * vectorLeft;
-
- topLine = QLine(topLeft + adjustTopLineLeft, topRight + adjustTopLineRight);
- }
-
- QLine leftLine;
- {
- QPoint adjustLeftLineTop = (vectorRight * marginLeft) + (vectorDown * (lowerTop + 1));
- QPoint adjustLeftLineBottom = (vectorRight * marginLeft) + (vectorUp * borderThickness);
- if (atBeginning || selected)
- adjustLeftLineTop += vectorDown; // Make place for rounded corner
- if (atBeginning && selected)
- adjustLeftLineBottom += borderThickness * vectorDown;
- else if (selected)
- adjustLeftLineBottom += vectorUp;
-
- leftLine = QLine(topLeft + adjustLeftLineTop, bottomLeft + adjustLeftLineBottom);
- }
-
- QLine rightLine;
- {
- QPoint adjustRightLineTop = vectorDown * (2 + lowerTop);
- QPoint adjustRightLineBottom = vectorUp * borderThickness;
- if (selected)
- adjustRightLineBottom += vectorUp;
-
- rightLine = QLine(topRight + adjustRightLineTop, bottomRight + adjustRightLineBottom);
- }
-
- // Background
- QPoint startPoint = topLine.p1() + vectorDown + vectorLeft;
- if (mouseOver)
- startPoint += vectorDown;
- QPoint endPoint = rightLine.p2();
-
- if (tab->state & State_Enabled) {
- QRect fillRect = QRect(startPoint, endPoint).normalized();
- if (fillRect.isValid()) {
- if (selected) {
- fillRect = QRect(startPoint, endPoint + vectorLeft + vectorDown * 3).normalized();
- painter->fillRect(fillRect, option->palette.window());
-
- // Connect to the base
- painter->setPen(QPen(option->palette.window(), 0));
- QVarLengthArray<QPoint, 6> points;
- points.append(rightLine.p2() + vectorDown);
- points.append(rightLine.p2() + vectorDown + vectorDown);
- points.append(rightLine.p2() + vectorDown + vectorDown + vectorRight);
- if (tab->position != QStyleOptionTab::Beginning) {
- points.append(leftLine.p2() + vectorDown);
- points.append(leftLine.p2() + vectorDown + vectorDown);
- points.append(leftLine.p2() + vectorDown + vectorDown + vectorLeft);
- }
- painter->drawPoints(points.constData(), points.size());
- } else {
- QBrush buttonGradientBrush;
- QBrush buttonBrush = qMapBrushToRect(option->palette.button(), fillRect);
- if (buttonBrush.gradient() || !buttonBrush.texture().isNull()) {
- buttonGradientBrush = buttonBrush;
- } else {
- // Generate gradients
- QLinearGradient buttonGradient(fillRect.topLeft(), fillRect.bottomLeft());
- buttonGradient.setColorAt(0.0, buttonBrush.color().lighter(104));
- buttonGradient.setColorAt(1.0, buttonBrush.color().darker(110));
- buttonGradientBrush = QBrush(buttonGradient);
- }
-
- painter->fillRect(fillRect, buttonGradientBrush);
- }
- }
- }
-
- QPoint rightCornerDot = topRight + vectorLeft + (lowerTop + 1)*vectorDown;
- QPoint leftCornerDot = topLeft + (marginLeft + 1)*vectorRight + (lowerTop + 1)*vectorDown;
- QPoint bottomRightConnectToBase = rightLine.p2() + vectorRight + vectorDown;
- QPoint bottomLeftConnectToBase = leftLine.p2() + vectorLeft + vectorDown;
-
- painter->setPen(QPen(border, 0));
-
- QVarLengthArray<QLine, 3> lines;
- QVarLengthArray<QPoint, 7> points;
-
- lines.append(topLine);
-
- if (mouseOver) {
- painter->drawLines(lines.constData(), lines.count());
- lines.clear();
-
- QLine secondHoverLine = QLine(topLine.p1() + vectorDown * 2 + vectorLeft, topLine.p2() + vectorDown * 2 + vectorRight);
- painter->setPen(highlightedLightInnerBorderColor);
- painter->drawLine(secondHoverLine);
- }
-
- if (mouseOver)
- painter->setPen(QPen(border, 0));
-
- if (!previousSelected)
- lines.append(leftLine);
- if (atEnd || selected) {
- lines.append(rightLine);
- points.append(rightCornerDot);
- }
- if (atBeginning || selected)
- points.append(leftCornerDot);
- if (selected) {
- points.append(bottomRightConnectToBase);
- points.append(bottomLeftConnectToBase);
- }
- if (lines.size() > 0) {
- painter->drawLines(lines.constData(), lines.size());
- lines.clear();
- }
- if (points.size() > 0) {
- painter->drawPoints(points.constData(), points.size());
- points.clear();
- }
-
- // Antialiasing
- painter->setPen(QPen(corner, 0));
- if (atBeginning || selected)
- points.append(topLine.p1() + vectorLeft);
- if (!previousSelected)
- points.append(leftLine.p1() + vectorUp);
- if (atEnd || selected) {
- points.append(topLine.p2() + vectorRight);
- points.append(rightLine.p1() + vectorUp);
- }
-
- if (selected) {
- points.append(bottomRightConnectToBase + vectorLeft);
- if (!atBeginning) {
- points.append(bottomLeftConnectToBase + vectorRight);
-
- if (((tab->position == QStyleOptionTab::Beginning) || onlyTab) && leftCornerWidget) {
- // A special case: When the first tab is selected and
- // has a left corner widget, it needs to do more work
- // to connect to the base
- QPoint p1 = bottomLeftConnectToBase + vectorDown;
-
- points.append(p1);
- }
- }
- }
- if (points.size() > 0) {
- painter->drawPoints(points.constData(), points.size());
- points.clear();
- }
-
- // Inner border
- QLine innerTopLine = QLine(topLine.p1() + vectorDown, topLine.p2() + vectorDown);
- if (!selected) {
- QLinearGradient topLineGradient(innerTopLine.p1(),innerTopLine.p2());
- topLineGradient.setColorAt(0, lightShadowGradientStartColor);
- topLineGradient.setColorAt(1, lightShadowGradientStopColor);
- painter->setPen(QPen(mouseOver ? QBrush(highlightedDarkInnerBorderColor) : QBrush(topLineGradient), 1));
- } else {
- painter->setPen(QPen(innerTopLeft, 0));
- }
- painter->drawLine(innerTopLine);
-
- QLine innerLeftLine = QLine(leftLine.p1() + vectorRight + vectorDown, leftLine.p2() + vectorRight);
- QLine innerRightLine = QLine(rightLine.p1() + vectorLeft + vectorDown, rightLine.p2() + vectorLeft);
-
- if (selected) {
- innerRightLine = QLine(innerRightLine.p1() + vectorUp, innerRightLine.p2());
- innerLeftLine = QLine(innerLeftLine.p1() + vectorUp, innerLeftLine.p2());
- }
-
- if (selected || atBeginning) {
- QBrush leftLineGradientBrush;
- QRect rect = QRect(innerLeftLine.p1(), innerLeftLine.p2()).normalized();
- QBrush buttonBrush = qMapBrushToRect(option->palette.button(), rect);
- if (buttonBrush.gradient() || !buttonBrush.texture().isNull()) {
- leftLineGradientBrush = qBrushLight(buttonBrush, 105);
- } else {
- QLinearGradient buttonGradient3(rect.topLeft(), rect.bottomLeft());
- buttonGradient3.setColorAt(0.0, buttonBrush.color().lighter(105));
- buttonGradient3.setColorAt(1.0, buttonBrush.color());
- leftLineGradientBrush = QBrush(buttonGradient3);
- }
-
- if (!selected)
- painter->setPen(QPen(leftLineGradientBrush, 0));
-
- // Assume the sun is on the same side in Right-To-Left layouts and draw the
- // light shadow on the left side always (the right line is on the left side in
- // reverse layouts for north and south)
- if (reverseShadow)
- painter->drawLine(innerRightLine);
- else
- painter->drawLine(innerLeftLine);
- }
-
- if (atEnd || selected) {
- if (!selected) {
- QBrush rightLineGradientBrush;
- QRect rect = QRect(innerRightLine.p1(), innerRightLine.p2()).normalized();
- QBrush buttonBrush = qMapBrushToRect(option->palette.button(), rect);
- if (buttonBrush.gradient() || !buttonBrush.texture().isNull()) {
- rightLineGradientBrush = qBrushDark(buttonBrush, 105);
- } else {
- QLinearGradient buttonGradient4(rect.topLeft(), rect.bottomLeft());
- buttonGradient4.setColorAt(0.0, buttonBrush.color());
- buttonGradient4.setColorAt(1.0, buttonBrush.color().darker(110));
- rightLineGradientBrush = QBrush(buttonGradient4);
- }
-
- painter->setPen(QPen(rightLineGradientBrush, 0));
- } else {
- painter->setPen(QPen(innerBottomRight, 0));
- }
-
- if (reverseShadow)
- painter->drawLine(innerLeftLine);
- else
- painter->drawLine(innerRightLine);
- }
-
-
- // Base
- QLine baseLine = QLine(bottomLeft + marginLeft * 2 * vectorRight, bottomRight);
- {
-
- QPoint adjustedLeft;
- QPoint adjustedRight;
-
- if (atEnd && !selected) {
- baseLine = QLine(baseLine.p1(), baseLine.p2() + vectorRight);
- }
-
- if (nextSelected) {
- adjustedRight += vectorLeft;
- baseLine = QLine(baseLine.p1(), baseLine.p2() + vectorLeft);
- }
- if (previousSelected) {
- adjustedLeft += vectorRight;
- baseLine = QLine(baseLine.p1() + vectorRight, baseLine.p2());
- }
- if (atBeginning)
- adjustedLeft += vectorRight;
-
- painter->setPen(QPen(baseColor2, 0));
- if (!selected)
- painter->drawLine(baseLine);
-
- if (atEnd && !selected)
- painter->drawPoint(baseLine.p2() + vectorRight);
-
- if (atBeginning && !selected)
- adjustedLeft = vectorRight;
- else
- adjustedLeft = QPoint(0, 0);
- painter->setPen(QPen(baseColor1, 0));
- if (!selected)
- painter->drawLine(bottomLeft + vectorUp + adjustedLeft, baseLine.p2() + vectorUp);
-
- QPoint endPoint = bottomRight + vectorUp;
- if (atEnd && !selected)
- painter->drawPoint(endPoint);
-
- // For drawing a lower left "fake" corner on the base when the first tab is unselected
- if (atBeginning && !selected) {
- painter->drawPoint(baseLine.p1() + vectorLeft);
- }
-
- painter->setPen(QPen(corner, 0));
- if (nextSelected)
- painter->drawPoint(endPoint);
- else if (selected)
- painter->drawPoint(endPoint + vectorRight);
-
- // For drawing a lower left "fake" corner on the base when the first tab is unselected
- if (atBeginning && !selected) {
- painter->drawPoint(baseLine.p1() + 2 * vectorLeft);
- }
- }
- }
- }
-
- // Yay we're done
-
- painter->restore();
- }
- break;
-#endif // QT_NO_TABBAR
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBarGroove:
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- QRect rect = bar->rect;
- QPen oldPen = painter->pen();
-
- QLine lines[4];
-
- // outline
- painter->setPen(borderColor);
- lines[0] = QLine(rect.left() + 2, rect.top(), rect.right() - 2, rect.top());
- lines[1] = QLine(rect.left() + 2, rect.bottom(), rect.right() - 2, rect.bottom());
- lines[2] = QLine(rect.left(), rect.top() + 2, rect.left(), rect.bottom() - 2);
- lines[3] = QLine(rect.right(), rect.top() + 2, rect.right(), rect.bottom() - 2);
- painter->drawLines(lines, 4);
-
- QPoint points[8];
- points[0] = QPoint(rect.left() + 1, rect.top() + 1);
- points[1] = QPoint(rect.right() - 1, rect.top() + 1);
- points[2] = QPoint(rect.left() + 1, rect.bottom() - 1);
- points[3] = QPoint(rect.right() - 1, rect.bottom() - 1);
- painter->drawPoints(points, 4);
-
- // alpha corners
- painter->setPen(alphaCornerColor);
- points[0] = QPoint(rect.left(), rect.top() + 1);
- points[1] = QPoint(rect.left() + 1, rect.top());
- points[2] = QPoint(rect.right(), rect.top() + 1);
- points[3] = QPoint(rect.right() - 1, rect.top());
- points[4] = QPoint(rect.left(), rect.bottom() - 1);
- points[5] = QPoint(rect.left() + 1, rect.bottom());
- points[6] = QPoint(rect.right(), rect.bottom() - 1);
- points[7] = QPoint(rect.right() - 1, rect.bottom());
- painter->drawPoints(points, 8);
-
- // inner outline, north-west
- painter->setPen(gradientStartColor.darker(105));
- lines[0] = QLine(rect.left() + 2, rect.top() + 1, rect.right() - 2, rect.top() + 1);
- lines[1] = QLine(rect.left() + 1, rect.top() + 2, rect.left() + 1, rect.bottom() - 2);
- painter->drawLines(lines, 2);
-
- // base of the groove
- painter->setPen(QPen());
- painter->fillRect(rect.adjusted(2, 2, -2, -1), QBrush(bar->palette.base().color()));
- painter->setPen(bar->palette.base().color());
- painter->drawLine(rect.right() - 1, rect.top() + 2, rect.right() - 1, rect.bottom() - 2);
-
- painter->setPen(oldPen);
- }
- break;
- case CE_ProgressBarLabel:
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- // The busy indicator doesn't draw a label
- if (bar->minimum == 0 && bar->maximum == 0)
- return;
-
- painter->save();
-
- QRect rect = bar->rect;
- QRect leftRect;
-
- QFont font;
- font.setBold(true);
- painter->setFont(font);
- painter->setPen(bar->palette.text().color());
-
- bool vertical = false;
- bool inverted = false;
- bool bottomToTop = false;
- // Get extra style options if version 2
- if (const QStyleOptionProgressBarV2 *bar2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- vertical = (bar2->orientation == Qt::Vertical);
- inverted = bar2->invertedAppearance;
- bottomToTop = bar2->bottomToTop;
- }
-
- if (vertical) {
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- QTransform m;
- if (bottomToTop) {
- m.translate(0.0, rect.width());
- m.rotate(-90);
- } else {
- m.translate(rect.height(), 0.0);
- m.rotate(90);
- }
- painter->setTransform(m, true);
- }
-
- int progressIndicatorPos = (bar->progress - qreal(bar->minimum)) / qMax(qreal(1.0), qreal(bar->maximum) - bar->minimum) * rect.width();
-
- bool flip = (!vertical && (((bar->direction == Qt::RightToLeft) && !inverted)
- || ((bar->direction == Qt::LeftToRight) && inverted))) || (vertical && ((!inverted && !bottomToTop) || (inverted && bottomToTop)));
- if (flip) {
- int indicatorPos = rect.width() - progressIndicatorPos;
- if (indicatorPos >= 0 && indicatorPos <= rect.width()) {
- painter->setPen(bar->palette.base().color());
- leftRect = QRect(rect.left(), rect.top(), indicatorPos, rect.height());
- } else if (indicatorPos > rect.width()) {
- painter->setPen(bar->palette.text().color());
- } else {
- painter->setPen(bar->palette.base().color());
- }
- } else {
- if (progressIndicatorPos >= 0 && progressIndicatorPos <= rect.width()) {
- leftRect = QRect(rect.left(), rect.top(), progressIndicatorPos, rect.height());
- } else if (progressIndicatorPos > rect.width()) {
- painter->setPen(bar->palette.base().color());
- } else {
- painter->setPen(bar->palette.text().color());
- }
- }
-
- QRegion rightRect = rect;
- rightRect = rightRect.subtracted(leftRect);
- painter->setClipRegion(rightRect);
- painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
- if (!leftRect.isNull()) {
- painter->setPen(flip ? bar->palette.text().color() : bar->palette.base().color());
- painter->setClipRect(leftRect);
- painter->drawText(rect, bar->text, QTextOption(Qt::AlignAbsolute | Qt::AlignHCenter | Qt::AlignVCenter));
- }
-
- painter->restore();
- }
- break;
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- Q_D(const QPlastiqueStyle);
- QRect rect = bar->rect;
- bool vertical = false;
- bool inverted = false;
- bool indeterminate = (bar->minimum == 0 && bar->maximum == 0);
- if (!indeterminate && bar->progress == -1)
- break;
-
- painter->save();
-
- // Get extra style options if version 2
- if (const QStyleOptionProgressBarV2 *bar2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- vertical = (bar2->orientation == Qt::Vertical);
- inverted = bar2->invertedAppearance;
- }
-
- // If the orientation is vertical, we use a transform to rotate
- // the progress bar 90 degrees clockwise. This way we can use the
- // same rendering code for both orientations.
- if (vertical) {
- rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
- QTransform m = QTransform::fromTranslate(rect.height()-1, 0);
- m.rotate(90.0);
- painter->setTransform(m, true);
- }
-
- int maxWidth = rect.width() - 4;
- int minWidth = 4;
- qint64 progress = qMax<qint64>(bar->progress, bar->minimum); // workaround for bug in QProgressBar
- double vc6_workaround = ((progress - qint64(bar->minimum)) / qMax(double(1.0), double(qint64(bar->maximum) - qint64(bar->minimum))) * maxWidth);
- int width = indeterminate ? maxWidth : qMax(int(vc6_workaround), minWidth);
- bool reverse = (!vertical && (bar->direction == Qt::RightToLeft)) || vertical;
- if (inverted)
- reverse = !reverse;
-
- QRect progressBar;
- if (!indeterminate) {
- if (!reverse) {
- progressBar.setRect(rect.left() + 2, rect.top() + 2, width, rect.height() - 4);
- } else {
- progressBar.setRect(rect.right() - 1 - width, rect.top() + 2, width, rect.height() - 4);
- }
- } else {
- int slideWidth = ((rect.width() - 4) * 2) / 3;
- int step = ((d->animateStep * slideWidth) / ProgressBarFps) % slideWidth;
- if ((((d->animateStep * slideWidth) / ProgressBarFps) % (2 * slideWidth)) >= slideWidth)
- step = slideWidth - step;
- progressBar.setRect(rect.left() + 2 + step, rect.top() + 2,
- slideWidth / 2, rect.height() - 4);
- }
-
- // outline
- painter->setPen(highlightedDarkInnerBorderColor);
-
- QVarLengthArray<QLine, 4> lines;
- QVarLengthArray<QPoint, 8> points;
- if (!reverse) {
- if (width == minWidth) {
- points.append(QPoint(progressBar.left() + 1, progressBar.top()));
- points.append(QPoint(progressBar.left() + 1, progressBar.bottom()));
- } else {
- if (indeterminate) {
- lines.append(QLine(progressBar.left() + 2, progressBar.top(),
- progressBar.right() - 2, progressBar.top()));
- lines.append(QLine(progressBar.left() + 2, progressBar.bottom(),
- progressBar.right() - 2, progressBar.bottom()));
- } else {
- lines.append(QLine(progressBar.left() + 1, progressBar.top(),
- progressBar.right() - 2, progressBar.top()));
- lines.append(QLine(progressBar.left() + 1, progressBar.bottom(),
- progressBar.right() - 2, progressBar.bottom()));
- }
- }
-
- if (indeterminate) {
- lines.append(QLine(progressBar.left(), progressBar.top() + 2,
- progressBar.left(), progressBar.bottom() - 2));
- } else {
- lines.append(QLine(progressBar.left(), progressBar.top() + 1,
- progressBar.left(), progressBar.bottom() - 1));
- }
- lines.append(QLine(progressBar.right(), progressBar.top() + 2,
- progressBar.right(), progressBar.bottom() - 2));
- } else {
- if (width == minWidth) {
- points.append(QPoint(progressBar.right() - 1, progressBar.top()));
- points.append(QPoint(progressBar.right() - 1, progressBar.bottom()));
- } else {
- if (indeterminate) {
- lines.append(QLine(progressBar.right() - 2, progressBar.top(),
- progressBar.left() + 2, progressBar.top()));
- lines.append(QLine(progressBar.right() - 2, progressBar.bottom(),
- progressBar.left() + 2, progressBar.bottom()));
- } else {
- lines.append(QLine(progressBar.right() - 1, progressBar.top(),
- progressBar.left() + 2, progressBar.top()));
- lines.append(QLine(progressBar.right() - 1, progressBar.bottom(),
- progressBar.left() + 2, progressBar.bottom()));
- }
- }
- if (indeterminate) {
- lines.append(QLine(progressBar.right(), progressBar.top() + 2,
- progressBar.right(), progressBar.bottom() - 2));
- } else {
- lines.append(QLine(progressBar.right(), progressBar.top() + 1,
- progressBar.right(), progressBar.bottom() - 1));
- }
- lines.append(QLine(progressBar.left(), progressBar.top() + 2,
- progressBar.left(), progressBar.bottom() - 2));
- }
-
- if (points.size() > 0) {
- painter->drawPoints(points.constData(), points.size());
- points.clear();
- }
- painter->drawLines(lines.constData(), lines.size());
- lines.clear();
-
- // alpha corners
- painter->setPen(alphaInnerColor);
- if (!reverse) {
- if (indeterminate) {
- points.append(QPoint(progressBar.left() + 1, progressBar.top()));
- points.append(QPoint(progressBar.left(), progressBar.top() + 1));
- points.append(QPoint(progressBar.left() + 1, progressBar.bottom()));
- points.append(QPoint(progressBar.left(), progressBar.bottom() - 1));
- } else {
- points.append(QPoint(progressBar.left(), progressBar.top()));
- points.append(QPoint(progressBar.left(), progressBar.bottom()));
- }
- points.append(QPoint(progressBar.right() - 1, progressBar.top()));
- points.append(QPoint(progressBar.right(), progressBar.top() + 1));
- points.append(QPoint(progressBar.right() - 1, progressBar.bottom()));
- points.append(QPoint(progressBar.right(), progressBar.bottom() - 1));
- } else {
- if (indeterminate) {
- points.append(QPoint(progressBar.right() - 1, progressBar.top()));
- points.append(QPoint(progressBar.right(), progressBar.top() + 1));
- points.append(QPoint(progressBar.right() - 1, progressBar.bottom()));
- points.append(QPoint(progressBar.right(), progressBar.bottom() - 1));
- } else {
- points.append(QPoint(progressBar.right(), progressBar.top()));
- points.append(QPoint(progressBar.right(), progressBar.bottom()));
- }
- points.append(QPoint(progressBar.left() + 1, progressBar.top()));
- points.append(QPoint(progressBar.left(), progressBar.top() + 1));
- points.append(QPoint(progressBar.left() + 1, progressBar.bottom()));
- points.append(QPoint(progressBar.left(), progressBar.bottom() - 1));
- }
-
- painter->drawPoints(points.constData(), points.size());
- points.clear();
-
- // contents
- painter->setPen(QPen());
-
- QString progressBarName = QStyleHelper::uniqueName(QLatin1String("progressBarContents"),
- option, rect.size());
- QPixmap cache;
- if (!QPixmapCache::find(progressBarName, cache) && rect.height() > 7) {
- QSize size = rect.size();
- cache = QPixmap(QSize(size.width() - 6 + 30, size.height() - 6));
- cache.fill(Qt::white);
- QPainter cachePainter(&cache);
- QRect pixmapRect(0, 0, cache.width(), cache.height());
-
- int leftEdge = 0;
- bool flip = false;
- while (leftEdge < cache.width() + 1) {
- QColor rectColor = option->palette.highlight().color();
- QColor lineColor = option->palette.highlight().color();
- if (flip) {
- flip = false;
- rectColor = rectColor.lighter(105);
- lineColor = lineColor.lighter(105);
- } else {
- flip = true;
- }
-
- cachePainter.setPen(lineColor);
- const QLine cacheLines[2] = {
- QLine(pixmapRect.left() + leftEdge - 1, pixmapRect.top(),
- pixmapRect.left() + leftEdge + 9, pixmapRect.top()),
- QLine(pixmapRect.left() + leftEdge - 1, pixmapRect.bottom(),
- pixmapRect.left() + leftEdge + 9, pixmapRect.bottom()) };
- cachePainter.drawLines(cacheLines, 2);
- cachePainter.fillRect(QRect(pixmapRect.left() + leftEdge, pixmapRect.top(),
- 10, pixmapRect.height()), rectColor);
-
- leftEdge += 10;
- }
-
- QPixmapCache::insert(progressBarName, cache);
- }
- painter->setClipRect(progressBar.adjusted(1, 0, -1, -1));
-
- if (!vertical)
- progressBar.adjust(0, 1, 0, 1);
- if (!indeterminate) {
- int step = (AnimateProgressBar || (indeterminate && AnimateBusyProgressBar)) ? (d->animateStep % 20) : 0;
- if (reverse)
- painter->drawPixmap(progressBar.left() - 25 + step, progressBar.top(), cache);
- else
- painter->drawPixmap(progressBar.left() - 25 - step + width % 20, progressBar.top(), cache);
- } else {
- painter->drawPixmap(progressBar.left(), progressBar.top(), cache);
- }
-
- painter->restore();
- }
- break;
-#endif // QT_NO_PROGRESSBAR
- case CE_HeaderSection:
- // Draws the header in tables.
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("headersection"), option, option->rect.size());
- pixmapName += QString::number(- int(header->position));
- pixmapName += QString::number(- int(header->orientation));
-
- if (!QPixmapCache::find(pixmapName, cache)) {
- cache = QPixmap(option->rect.size());
- cache.fill(Qt::white);
- QRect pixmapRect(0, 0, option->rect.width(), option->rect.height());
- QPainter cachePainter(&cache);
-
- bool sunken = (header->state & State_Enabled) && (header->state & State_Sunken);
-
- QColor headerGradientStart = sunken ? option->palette.background().color().darker(114) : gradientStartColor;
- QColor headerGradientStop = sunken ? option->palette.background().color().darker(106) : gradientStopColor;
-
- QColor lightLine = sunken ? option->palette.background().color().darker(118) : gradientStartColor;
- QColor darkLine = sunken ? option->palette.background().color().darker(110) : gradientStopColor.darker(105);
-
- qt_plastique_draw_gradient(&cachePainter, pixmapRect,
- headerGradientStart, headerGradientStop);
-
- cachePainter.setPen(borderColor);
- cachePainter.drawRect(pixmapRect.adjusted(0, 0, -1, -1));
- cachePainter.setPen(alphaCornerColor);
-
- const QPoint points[4] = {
- pixmapRect.topLeft(), pixmapRect.topRight(),
- pixmapRect.bottomLeft(), pixmapRect.bottomRight() };
- cachePainter.drawPoints(points, 4);
-
- QLine lines[2];
-
- // inner lines
- cachePainter.setPen(lightLine);
- lines[0] = QLine(pixmapRect.left() + 2, pixmapRect.top() + 1,
- pixmapRect.right() - 2, pixmapRect.top() + 1);
- lines[1] = QLine(pixmapRect.left() + 1, pixmapRect.top() + 2,
- pixmapRect.left() + 1, pixmapRect.bottom() - 2);
- cachePainter.drawLines(lines, 2);
-
- cachePainter.setPen(darkLine);
- lines[0] = QLine(pixmapRect.left() + 2, pixmapRect.bottom() - 1,
- pixmapRect.right() - 2, pixmapRect.bottom() - 1);
- lines[1] = QLine(pixmapRect.right() - 1, pixmapRect.bottom() - 2,
- pixmapRect.right() - 1, pixmapRect.top() + 2);
- cachePainter.drawLines(lines, 2);
-
- cachePainter.end();
- QPixmapCache::insert(pixmapName, cache);
- }
- painter->drawPixmap(option->rect.topLeft(), cache);
-
- }
- break;
-#ifndef QT_NO_MENU
- case CE_MenuItem:
- // Draws one item in a popup menu.
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- painter->save();
- QBrush textBrush;
- if (option->palette.resolve() & (1 << QPalette::ButtonText))
- textBrush = option->palette.buttonText();
- else
- textBrush = option->palette.windowText(); // KDE uses windowText rather than buttonText for menus
-
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
- painter->fillRect(menuItem->rect, option->palette.background().color().lighter(103));
-
- int w = 0;
- if (!menuItem->text.isEmpty()) {
- painter->setFont(menuItem->font);
- proxy()->drawItemText(painter, menuItem->rect.adjusted(5, 0, -5, 0), Qt::AlignLeft | Qt::AlignVCenter,
- menuItem->palette, menuItem->state & State_Enabled, menuItem->text,
- QPalette::Text);
- w = menuItem->fontMetrics.width(menuItem->text) + 5;
- }
-
- painter->setPen(alphaCornerColor);
- bool reverse = menuItem->direction == Qt::RightToLeft;
- painter->drawLine(menuItem->rect.left() + 5 + (reverse ? 0 : w), menuItem->rect.center().y(),
- menuItem->rect.right() - 5 - (reverse ? w : 0), menuItem->rect.center().y());
-
- painter->restore();
- break;
- }
-
- bool selected = menuItem->state & State_Selected;
- bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
- bool checked = menuItem->checked;
-
- if (selected) {
- qt_plastique_draw_gradient(painter, menuItem->rect,
- option->palette.highlight().color().lighter(105),
- option->palette.highlight().color().darker(110));
-
- painter->setPen(option->palette.highlight().color().lighter(110));
- painter->drawLine(option->rect.topLeft(), option->rect.topRight());
- painter->setPen(option->palette.highlight().color().darker(115));
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- } else {
- painter->fillRect(option->rect, option->palette.background().color().lighter(103));
- }
-
- // Check
- QRect checkRect(option->rect.left() + 7, option->rect.center().y() - 6, 13, 13);
- checkRect = visualRect(menuItem->direction, menuItem->rect, checkRect);
- if (checkable) {
- if ((menuItem->checkType & QStyleOptionMenuItem::Exclusive) && menuItem->icon.isNull()) {
- QStyleOptionButton button;
- button.rect = checkRect;
- button.state = menuItem->state;
- if (checked)
- button.state |= State_On;
- button.palette = menuItem->palette;
- proxy()->drawPrimitive(PE_IndicatorRadioButton, &button, painter, widget);
- } else {
- if (menuItem->icon.isNull()) {
- QStyleOptionButton button;
- button.rect = checkRect;
- button.state = menuItem->state;
- if (checked)
- button.state |= State_On;
- button.palette = menuItem->palette;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &button, painter, widget);
- } else if (checked) {
- int iconSize = qMax(menuItem->maxIconWidth, 20);
- QRect sunkenRect(option->rect.left() + 1,
- option->rect.top() + (option->rect.height() - iconSize) / 2 + 1,
- iconSize, iconSize);
- sunkenRect = visualRect(menuItem->direction, menuItem->rect, sunkenRect);
-
- QStyleOption opt = *option;
- opt.state |= State_Sunken;
- opt.rect = sunkenRect;
- qt_plastique_drawShadedPanel(painter, &opt, false, widget);
- }
- }
- }
-
- // Text and icon, ripped from windows style
- bool dis = !(menuItem->state & State_Enabled);
- bool act = menuItem->state & State_Selected;
- const QStyleOption *opt = option;
- const QStyleOptionMenuItem *menuitem = menuItem;
- int checkcol = qMax(menuitem->maxIconWidth, 20);
- QPainter *p = painter;
- QRect vCheckRect = visualRect(opt->direction, menuitem->rect,
- QRect(menuitem->rect.x(), menuitem->rect.y(),
- checkcol, menuitem->rect.height()));
- if (!menuItem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap;
- if (checked)
- pixmap = menuItem->icon.pixmap(pixelMetric(PM_SmallIconSize, option, widget), mode, QIcon::On);
- else
- pixmap = menuItem->icon.pixmap(pixelMetric(PM_SmallIconSize, option, widget), mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
-
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vCheckRect.center());
- painter->setPen(textBrush.color());
- if (checkable && checked)
- painter->drawPixmap(QPoint(pmr.left() + 1, pmr.top() + 1), pixmap);
- else
- painter->drawPixmap(pmr.topLeft(), pixmap);
- }
-
- if (selected) {
- painter->setPen(menuItem->palette.highlightedText().color());
- } else {
- painter->setPen(textBrush.color());
- }
- int x, y, w, h;
- menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
- QColor discol;
- if (dis) {
- discol = textBrush.color();
- p->setPen(discol);
- }
- int xm = windowsItemFrame + checkcol + windowsItemHMargin;
- int xpos = menuitem->rect.x() + xm;
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
- QString s = menuitem->text;
- if (!s.isEmpty()) { // draw text
- p->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
- text_flags |= Qt::AlignLeft;
- if (t >= 0) {
- QRect vShortcutRect = visualRect(opt->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
- if (dis && !act && styleHint(SH_EtchDisabledText, option, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vShortcutRect.adjusted(1,1,1,1), text_flags, s.mid(t + 1));
- p->setPen(discol);
- }
- p->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- QFont font = menuitem->font;
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
- p->setFont(font);
- if (dis && !act && styleHint(SH_EtchDisabledText, option, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vTextRect.adjusted(1,1,1,1), text_flags, s.left(t));
- p->setPen(discol);
- }
- p->drawText(vTextRect, text_flags, s.left(t));
- p->restore();
- }
-
- // Arrow
- if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- int dim = (menuItem->rect.height() - 4) / 2;
- PrimitiveElement arrow;
- arrow = (opt->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- int xpos = menuItem->rect.left() + menuItem->rect.width() - 6 - 2 - dim;
- QRect vSubMenuRect = visualRect(option->direction, menuItem->rect,
- QRect(xpos, menuItem->rect.top() + menuItem->rect.height() / 2 - dim / 2, dim, dim));
- QStyleOptionMenuItem newMI = *menuItem;
- newMI.rect = vSubMenuRect;
- newMI.state = option->state & State_Enabled;
- if (selected)
- newMI.palette.setColor(QPalette::ButtonText,
- newMI.palette.highlightedText().color());
- else
- newMI.palette.setColor(QPalette::ButtonText, textBrush.color());
- proxy()->drawPrimitive(arrow, &newMI, painter, widget);
- }
-
- painter->restore();
- }
- break;
-#endif // QT_NO_MENU
-#ifndef QT_NO_MENUBAR
- case CE_MenuBarItem:
- // Draws a menu bar item; File, Edit, Help etc..
- if ((option->state & State_Selected)) {
- QPixmap cache;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("menubaritem"), option, option->rect.size());
- if (!QPixmapCache::find(pixmapName, cache)) {
- cache = QPixmap(option->rect.size());
- cache.fill(Qt::white);
- QRect pixmapRect(0, 0, option->rect.width(), option->rect.height());
- QPainter cachePainter(&cache);
-
- QRect rect = pixmapRect;
-
- // gradient fill
- if ((option->state & QStyle::State_Sunken) || (option->state & QStyle::State_On)) {
- qt_plastique_draw_gradient(&cachePainter, rect.adjusted(1, 1, -1, -1),
- option->palette.button().color().darker(114),
- option->palette.button().color().darker(106));
- } else {
- qt_plastique_draw_gradient(&cachePainter, rect.adjusted(1, 1, -1, -1),
- option->palette.background().color().lighter(105),
- option->palette.background().color().darker(102));
- }
-
- // outer border and corners
- cachePainter.setPen(borderColor);
- cachePainter.drawRect(rect.adjusted(0, 0, -1, -1));
- cachePainter.setPen(alphaCornerColor);
-
- const QPoint points[4] = {
- rect.topLeft(),
- rect.topRight(),
- rect.bottomLeft(),
- rect.bottomRight() };
- cachePainter.drawPoints(points, 4);
-
- // inner border
- if ((option->state & QStyle::State_Sunken) || (option->state & QStyle::State_On))
- cachePainter.setPen(option->palette.button().color().darker(118));
- else
- cachePainter.setPen(gradientStartColor);
-
- QLine lines[2];
- lines[0] = QLine(rect.left() + 1, rect.top() + 1, rect.right() - 1, rect.top() + 1);
- lines[1] = QLine(rect.left() + 1, rect.top() + 2, rect.left() + 1, rect.bottom() - 2);
- cachePainter.drawLines(lines, 2);
-
- if ((option->state & QStyle::State_Sunken) || (option->state & QStyle::State_On))
- cachePainter.setPen(option->palette.button().color().darker(114));
- else
- cachePainter.setPen(gradientStopColor.darker(102));
- lines[0] = QLine(rect.left() + 1, rect.bottom() - 1, rect.right() - 1, rect.bottom() - 1);
- lines[1] = QLine(rect.right() - 1, rect.top() + 1, rect.right() - 1, rect.bottom() - 2);
- cachePainter.drawLines(lines, 2);
- cachePainter.end();
- QPixmapCache::insert(pixmapName, cache);
- }
- painter->drawPixmap(option->rect.topLeft(), cache);
- } else {
- painter->fillRect(option->rect, option->palette.background());
- }
-
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- QStyleOptionMenuItem newMI = *mbi;
- if (!(option->palette.resolve() & (1 << QPalette::ButtonText))) //KDE uses windowText rather than buttonText for menus
- newMI.palette.setColor(QPalette::ButtonText, newMI.palette.windowText().color());
- QCommonStyle::drawControl(element, &newMI, painter, widget);
- }
- break;
-
-#ifndef QT_NO_MAINWINDOW
- case CE_MenuBarEmptyArea:
- if (widget && qobject_cast<const QMainWindow *>(widget->parentWidget())) {
- painter->fillRect(option->rect, option->palette.window());
- QPen oldPen = painter->pen();
- painter->setPen(QPen(option->palette.dark().color()));
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- painter->setPen(oldPen);
- }
- break;
-#endif // QT_NO_MAINWINDOW
-
-#endif // QT_NO_MENUBAR
-
-#ifndef QT_NO_TOOLBOX
- case CE_ToolBoxTabShape:
- if (const QStyleOptionToolBox *toolBox = qstyleoption_cast<const QStyleOptionToolBox *>(option)) {
- painter->save();
-
- int width = toolBox->rect.width();
- int diag = toolBox->rect.height() - 2;
-
- // The essential points
- QPoint rightMost;
- QPoint rightEdge;
- QPoint leftEdge;
- QPoint leftMost;
- QPoint leftOne;
- QPoint rightOne;
- QPoint upOne(0, -1);
- QPoint downOne(0, 1);
-
- if (toolBox->direction != Qt::RightToLeft) {
- rightMost = QPoint(toolBox->rect.right(), toolBox->rect.bottom() - 2);
- rightEdge = QPoint(toolBox->rect.right() - width / 10, toolBox->rect.bottom() - 2);
- leftEdge = QPoint(toolBox->rect.right() - width / 10 - diag, toolBox->rect.top());
- leftMost = QPoint(toolBox->rect.left(), toolBox->rect.top());
- leftOne = QPoint(-1, 0);
- rightOne = QPoint(1, 0);
- } else {
- rightMost = QPoint(toolBox->rect.left(), toolBox->rect.bottom() - 2);
- rightEdge = QPoint(toolBox->rect.left() + width / 10, toolBox->rect.bottom() - 2);
- leftEdge = QPoint(toolBox->rect.left() + width / 10 + diag, toolBox->rect.top());
- leftMost = QPoint(toolBox->rect.right(), toolBox->rect.top());
- leftOne = QPoint(1, 0);
- rightOne = QPoint(-1, 0);
- }
-
- QLine lines[3];
-
- // Draw the outline
- painter->setPen(borderColor);
- lines[0] = QLine(rightMost, rightEdge);
- lines[1] = QLine(rightEdge + leftOne, leftEdge);
- lines[2] = QLine(leftEdge + leftOne, leftMost);
- painter->drawLines(lines, 3);
- painter->setPen(toolBox->palette.base().color());
- lines[0] = QLine(rightMost + downOne, rightEdge + downOne);
- lines[1] = QLine(rightEdge + leftOne + downOne, leftEdge + downOne);
- lines[2] = QLine(leftEdge + leftOne + downOne, leftMost + downOne);
- painter->drawLines(lines, 3);
-
- painter->restore();
- }
- break;
-#endif // QT_NO_TOOLBOX
-#ifndef QT_NO_SPLITTER
- case CE_Splitter:
- if ((option->state & State_Enabled) && (option->state & State_MouseOver))
- painter->fillRect(option->rect, QColor(255, 255, 255, 128));
- if (option->state & State_Horizontal) {
- int height = option->rect.height() / 3;
- QRect rect(option->rect.left() + (option->rect.width() / 2 - 1),
- option->rect.center().y() - height / 2, 3, height);
- qt_plastique_draw_handle(painter, option, rect, Qt::Horizontal, widget);
- } else {
- int width = option->rect.width() / 3;
- QRect rect(option->rect.center().x() - width / 2,
- option->rect.top() + (option->rect.height() / 2) - 1, width, 3);
- qt_plastique_draw_handle(painter, option, rect, Qt::Vertical, widget);
- }
- break;
-#endif // QT_NO_SPLITTER
-#ifndef QT_NO_DOCKWIDGET
- case CE_DockWidgetTitle:
- if (const QStyleOptionDockWidget *dockWidget = qstyleoption_cast<const QStyleOptionDockWidget *>(option)) {
- painter->save();
-
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dockWidget);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- // Find text width and title rect
- int textWidth = option->fontMetrics.width(dockWidget->title);
- int margin = 4;
- QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, option, widget);
- QRect rect = dockWidget->rect;
-
- if (verticalTitleBar) {
- QRect r = rect;
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- titleRect = QRect(r.left() + rect.bottom()
- - titleRect.bottom(),
- r.top() + titleRect.left() - rect.left(),
- titleRect.height(), titleRect.width());
-
- painter->translate(r.left(), r.top() + r.width());
- painter->rotate(-90);
- painter->translate(-r.left(), -r.top());
-
- rect = r;
- }
-
- // Chop and insert ellide into title if text is too wide
- QString title = elliditide(dockWidget->title, dockWidget->fontMetrics, titleRect, &textWidth);
-
- // Draw the toolbar handle pattern to the left and right of the text
- QImage handle(qt_toolbarhandle);
- alphaCornerColor.setAlpha(170);
- handle.setColor(1, alphaCornerColor.rgba());
- handle.setColor(2, mergedColors(alphaCornerColor, option->palette.light().color()).rgba());
- handle.setColor(3, option->palette.light().color().rgba());
-
- if (title.isEmpty()) {
- // Joint handle if there's no title
- QRect r;
-#ifdef QT3_SUPPORT
- // Q3DockWindow doesn't need space for buttons
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- r = rect;
- } else
-#endif
- r.setRect(titleRect.left(), titleRect.top(), titleRect.width(), titleRect.bottom());
- int nchunks = (r.width() / handle.width()) - 1;
- int indent = (r.width() - (nchunks * handle.width())) / 2;
- for (int i = 0; i < nchunks; ++i) {
- painter->drawImage(QPoint(r.left() + indent + i * handle.width(),
- r.center().y() - handle.height() / 2),
- handle);
- }
- } else {
- // Handle pattern to the left of the title
- QRect leftSide(titleRect.left(), titleRect.top(),
- titleRect.width() / 2 - textWidth / 2 - margin, titleRect.bottom());
- int nchunks = leftSide.width() / handle.width();
- int indent = (leftSide.width() - (nchunks * handle.width())) / 2;
- for (int i = 0; i < nchunks; ++i) {
- painter->drawImage(QPoint(leftSide.left() + indent
- + i * handle.width(),
- leftSide.center().y()
- - handle.height() / 2),
- handle);
- }
-
- // Handle pattern to the right of the title
- QRect rightSide = titleRect.adjusted(titleRect.width() / 2 + textWidth / 2 + margin, 0, 0, 0);
- nchunks = rightSide.width() / handle.width();
- indent = (rightSide.width() - (nchunks * handle.width())) / 2;
- for (int j = 0; j < nchunks; ++j) {
- painter->drawImage(QPoint(rightSide.left() + indent + j * handle.width(),
- rightSide.center().y() - handle.height() / 2),
- handle);
- }
- }
-
- // Draw the text centered
- QFont font = painter->font();
- font.setPointSize(QFontInfo(font).pointSize() - 1);
- painter->setFont(font);
- painter->setPen(dockWidget->palette.windowText().color());
- painter->drawText(titleRect,
- int(Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextShowMnemonic),
- title);
-
- painter->restore();
- }
-
- break;
-#endif // QT_NO_DOCKWIDGET
-#ifndef QT_NO_TOOLBAR
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
- // Draws the light line above and the dark line below menu bars and
- // tool bars.
- QPen oldPen = painter->pen();
- if (toolBar->toolBarArea == Qt::TopToolBarArea) {
- if (toolBar->positionOfLine == QStyleOptionToolBar::End
- || toolBar->positionOfLine == QStyleOptionToolBar::OnlyOne) {
- // The end and onlyone top toolbar lines draw a double
- // line at the bottom to blend with the central
- // widget.
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.left(), option->rect.bottom() - 1,
- option->rect.right(), option->rect.bottom() - 1);
- } else {
- // All others draw a single dark line at the bottom.
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- }
- // All top toolbar lines draw a light line at the top.
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.topLeft(), option->rect.topRight());
- } else if (toolBar->toolBarArea == Qt::BottomToolBarArea) {
- if (toolBar->positionOfLine == QStyleOptionToolBar::End
- || toolBar->positionOfLine == QStyleOptionToolBar::Middle) {
- // The end and middle bottom tool bar lines draw a dark
- // line at the bottom.
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- }
- if (toolBar->positionOfLine == QStyleOptionToolBar::Beginning
- || toolBar->positionOfLine == QStyleOptionToolBar::OnlyOne) {
- // The beginning and only one tool bar lines draw a
- // double line at the bottom to blend with the
- // status bar.
- // ### The styleoption could contain whether the
- // main window has a menu bar and a status bar, and
- // possibly dock widgets.
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.left(), option->rect.bottom() - 1,
- option->rect.right(), option->rect.bottom() - 1);
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
- }
- if (toolBar->positionOfLine == QStyleOptionToolBar::End) {
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.topLeft(), option->rect.topRight());
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.left(), option->rect.top() + 1,
- option->rect.right(), option->rect.top() + 1);
-
- } else {
- // All other bottom toolbars draw a light line at the top.
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.topLeft(), option->rect.topRight());
- }
- }
- if (toolBar->toolBarArea == Qt::LeftToolBarArea) {
- if (toolBar->positionOfLine == QStyleOptionToolBar::Middle
- || toolBar->positionOfLine == QStyleOptionToolBar::End) {
- // The middle and left end toolbar lines draw a light
- // line to the left.
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.topLeft(), option->rect.bottomLeft());
- }
- if (toolBar->positionOfLine == QStyleOptionToolBar::End) {
- // All other left toolbar lines draw a dark line to the right
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.right() - 1, option->rect.top(),
- option->rect.right() - 1, option->rect.bottom());
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.topRight(), option->rect.bottomRight());
- } else {
- // All other left toolbar lines draw a dark line to the right
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.topRight(), option->rect.bottomRight());
- }
- } else if (toolBar->toolBarArea == Qt::RightToolBarArea) {
- if (toolBar->positionOfLine == QStyleOptionToolBar::Middle
- || toolBar->positionOfLine == QStyleOptionToolBar::End) {
- // Right middle and end toolbar lines draw the dark right line
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.topRight(), option->rect.bottomRight());
- }
- if (toolBar->positionOfLine == QStyleOptionToolBar::End
- || toolBar->positionOfLine == QStyleOptionToolBar::OnlyOne) {
- // The right end and single toolbar draws the dark
- // line on its left edge
- painter->setPen(alphaCornerColor);
- painter->drawLine(option->rect.topLeft(), option->rect.bottomLeft());
- // And a light line next to it
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.left() + 1, option->rect.top(),
- option->rect.left() + 1, option->rect.bottom());
- } else {
- // Other right toolbars draw a light line on its left edge
- painter->setPen(option->palette.background().color().lighter(104));
- painter->drawLine(option->rect.topLeft(), option->rect.bottomLeft());
- }
- }
- painter->setPen(oldPen);
- }
- break;
-#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_SCROLLBAR
- case CE_ScrollBarAddLine:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
-
- bool horizontal = scrollBar->orientation == Qt::Horizontal;
- bool reverse = scrollBar->direction == Qt::RightToLeft;
- bool sunken = scrollBar->state & State_Sunken;
-
- QString addLinePixmapName = QStyleHelper::uniqueName(QLatin1String("scrollbar_addline"), option, option->rect.size());
- QPixmap cache;
- if (!QPixmapCache::find(addLinePixmapName, cache)) {
- cache = QPixmap(option->rect.size());
- cache.fill(Qt::white);
- QRect pixmapRect(0, 0, cache.width(), cache.height());
- QPainter addLinePainter(&cache);
- addLinePainter.fillRect(pixmapRect, option->palette.background());
-
- if (option->state & State_Enabled) {
- // Gradient
- QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top() + 2,
- pixmapRect.center().x(), pixmapRect.bottom() - 2);
- if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken) {
- gradient.setColorAt(0, gradientStopColor);
- gradient.setColorAt(1, gradientStopColor);
- } else {
- gradient.setColorAt(0, gradientStartColor.lighter(105));
- gradient.setColorAt(1, gradientStopColor);
- }
- addLinePainter.fillRect(pixmapRect.left() + 2, pixmapRect.top() + 2,
- pixmapRect.right() - 3, pixmapRect.bottom() - 3,
- gradient);
- }
-
- // Details
- QImage addButton;
- if (horizontal) {
- addButton = QImage(reverse ? qt_scrollbar_button_left : qt_scrollbar_button_right);
- } else {
- addButton = QImage(qt_scrollbar_button_down);
- }
- addButton.setColor(1, alphaCornerColor.rgba());
- addButton.setColor(2, borderColor.rgba());
- if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken) {
- addButton.setColor(3, gradientStopColor.rgba());
- addButton.setColor(4, gradientStopColor.rgba());
- } else {
- addButton.setColor(3, gradientStartColor.lighter(105).rgba());
- addButton.setColor(4, gradientStopColor.rgba());
- }
- addButton.setColor(5, scrollBar->palette.text().color().rgba());
- addLinePainter.drawImage(pixmapRect, addButton);
-
- // Arrow
- if (horizontal) {
- QImage arrow(reverse ? qt_scrollbar_button_arrow_left : qt_scrollbar_button_arrow_right);
- arrow.setColor(1, scrollBar->palette.foreground().color().rgba());
-
- if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken)
- addLinePainter.translate(1, 1);
- addLinePainter.drawImage(QPoint(pixmapRect.center().x() - 2, pixmapRect.center().y() - 3), arrow);
- } else {
- QImage arrow(qt_scrollbar_button_arrow_down);
- arrow.setColor(1, scrollBar->palette.foreground().color().rgba());
-
- if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken)
- addLinePainter.translate(1, 1);
- addLinePainter.drawImage(QPoint(pixmapRect.center().x() - 3, pixmapRect.center().y() - 2), arrow);
- }
- addLinePainter.end();
- QPixmapCache::insert(addLinePixmapName, cache);
- }
- painter->drawPixmap(option->rect.topLeft(), cache);
- }
- break;
- case CE_ScrollBarSubPage:
- case CE_ScrollBarAddPage:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- bool sunken = scrollBar->state & State_Sunken;
- bool horizontal = scrollBar->orientation == Qt::Horizontal;
-
- QString groovePixmapName = QStyleHelper::uniqueName(QLatin1String("scrollbar_groove"), option, option->rect.size());
- if (sunken)
- groovePixmapName += QLatin1String("-sunken");
- if (element == CE_ScrollBarAddPage)
- groovePixmapName += QLatin1String("-addpage");
-
- QPixmap cache;
- if (!QPixmapCache::find(groovePixmapName, cache)) {
- cache = QPixmap(option->rect.size());
- cache.fill(option->palette.background().color());
- QPainter groovePainter(&cache);
- QRect pixmapRect = QRect(0, 0, option->rect.width(), option->rect.height());
- QColor color = scrollBar->palette.base().color().darker(sunken ? 125 : 100);
- groovePainter.setBrushOrigin((element == CE_ScrollBarAddPage) ? pixmapRect.width() : 0,
- (element == CE_ScrollBarAddPage) ? pixmapRect.height() : 0);
- groovePainter.fillRect(pixmapRect, QBrush(color, Qt::Dense4Pattern));
-
- QColor edgeColor = scrollBar->palette.base().color().darker(125);
- if (horizontal) {
- groovePainter.setBrushOrigin((element == CE_ScrollBarAddPage) ? pixmapRect.width() : 1, 0);
- groovePainter.fillRect(QRect(pixmapRect.topLeft(), QSize(pixmapRect.width(), 1)),
- QBrush(edgeColor, Qt::Dense4Pattern));
- groovePainter.fillRect(QRect(pixmapRect.bottomLeft(), QSize(pixmapRect.width(), 1)),
- QBrush(edgeColor, Qt::Dense4Pattern));
- } else {
- groovePainter.setBrushOrigin(0, (element == CE_ScrollBarAddPage) ? pixmapRect.height() : 1);
- groovePainter.fillRect(QRect(pixmapRect.topLeft(), QSize(1, pixmapRect.height())),
- QBrush(edgeColor, Qt::Dense4Pattern));
- groovePainter.fillRect(QRect(pixmapRect.topRight(), QSize(1, pixmapRect.height())),
- QBrush(edgeColor, Qt::Dense4Pattern));
- }
-
- groovePainter.end();
- QPixmapCache::insert(groovePixmapName, cache);
- }
- painter->drawPixmap(option->rect.topLeft(), cache);
- }
- break;
- case CE_ScrollBarSubLine:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- QRect scrollBarSubLine = scrollBar->rect;
-
- bool horizontal = scrollBar->orientation == Qt::Horizontal;
- bool isEnabled = scrollBar->state & State_Enabled;
- bool reverse = scrollBar->direction == Qt::RightToLeft;
- bool sunken = scrollBar->state & State_Sunken;
-
- // The SubLine (up/left) buttons
- QRect button1;
- QRect button2;
- int scrollBarExtent = proxy()->pixelMetric(PM_ScrollBarExtent, option, widget);
- if (horizontal) {
- button1.setRect(scrollBarSubLine.left(), scrollBarSubLine.top(), scrollBarExtent, scrollBarSubLine.height());
- button2.setRect(scrollBarSubLine.right() - (scrollBarExtent - 1), scrollBarSubLine.top(), scrollBarExtent, scrollBarSubLine.height());
- } else {
- button1.setRect(scrollBarSubLine.left(), scrollBarSubLine.top(), scrollBarSubLine.width(), scrollBarExtent);
- button2.setRect(scrollBarSubLine.left(), scrollBarSubLine.bottom() - (scrollBarExtent - 1), scrollBarSubLine.width(), scrollBarExtent);
- }
-
- QString subLinePixmapName = QStyleHelper::uniqueName(QLatin1String("scrollbar_subline"), option, button1.size());
- QPixmap cache;
- if (!QPixmapCache::find(subLinePixmapName, cache)) {
- cache = QPixmap(button1.size());
- cache.fill(Qt::white);
- QRect pixmapRect(0, 0, cache.width(), cache.height());
- QPainter subLinePainter(&cache);
- subLinePainter.fillRect(pixmapRect, option->palette.background());
-
- if (isEnabled) {
- // Gradients
- if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken) {
- qt_plastique_draw_gradient(&subLinePainter,
- QRect(pixmapRect.left() + 2, pixmapRect.top() + 2,
- pixmapRect.right() - 3, pixmapRect.bottom() - 3),
- gradientStopColor,
- gradientStopColor);
- } else {
- qt_plastique_draw_gradient(&subLinePainter,
- QRect(pixmapRect.left() + 2, pixmapRect.top() + 2,
- pixmapRect.right() - 3, pixmapRect.bottom() - 3),
- gradientStartColor.lighter(105),
- gradientStopColor);
- }
- }
-
- // Details
- QImage subButton;
- if (horizontal) {
- subButton = QImage(reverse ? qt_scrollbar_button_right : qt_scrollbar_button_left);
- } else {
- subButton = QImage(qt_scrollbar_button_up);
- }
- subButton.setColor(1, alphaCornerColor.rgba());
- subButton.setColor(2, borderColor.rgba());
- if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken) {
- subButton.setColor(3, gradientStopColor.rgba());
- subButton.setColor(4, gradientStopColor.rgba());
- } else {
- subButton.setColor(3, gradientStartColor.lighter(105).rgba());
- subButton.setColor(4, gradientStopColor.rgba());
- }
- subButton.setColor(5, scrollBar->palette.text().color().rgba());
- subLinePainter.drawImage(pixmapRect, subButton);
-
- // Arrows
- if (horizontal) {
- QImage arrow(reverse ? qt_scrollbar_button_arrow_right : qt_scrollbar_button_arrow_left);
- arrow.setColor(1, scrollBar->palette.foreground().color().rgba());
-
- if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken)
- subLinePainter.translate(1, 1);
- subLinePainter.drawImage(QPoint(pixmapRect.center().x() - 2, pixmapRect.center().y() - 3), arrow);
- } else {
- QImage arrow(qt_scrollbar_button_arrow_up);
- arrow.setColor(1, scrollBar->palette.foreground().color().rgba());
-
- if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken)
- subLinePainter.translate(1, 1);
- subLinePainter.drawImage(QPoint(pixmapRect.center().x() - 3, pixmapRect.center().y() - 2), arrow);
- }
- subLinePainter.end();
- QPixmapCache::insert(subLinePixmapName, cache);
- }
- painter->drawPixmap(button1.topLeft(), cache);
- painter->drawPixmap(button2.topLeft(), cache);
- }
- break;
- case CE_ScrollBarSlider:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- bool horizontal = scrollBar->orientation == Qt::Horizontal;
- bool isEnabled = scrollBar->state & State_Enabled;
-
- // The slider
- if (option->rect.isValid()) {
- QString sliderPixmapName = QStyleHelper::uniqueName(QLatin1String("scrollbar_slider"), option, option->rect.size());
- if (horizontal)
- sliderPixmapName += QLatin1String("-horizontal");
-
- QPixmap cache;
- if (!QPixmapCache::find(sliderPixmapName, cache)) {
- cache = QPixmap(option->rect.size());
- cache.fill(Qt::white);
- QRect pixmapRect(0, 0, cache.width(), cache.height());
- QPainter sliderPainter(&cache);
- bool sunken = (scrollBar->state & State_Sunken);
-
- if (isEnabled) {
- QLinearGradient gradient(pixmapRect.left(), pixmapRect.center().y(),
- pixmapRect.right(), pixmapRect.center().y());
- if (horizontal)
- gradient = QLinearGradient(pixmapRect.center().x(), pixmapRect.top(),
- pixmapRect.center().x(), pixmapRect.bottom());
-
- if (sunken) {
- gradient.setColorAt(0, gradientStartColor.lighter(110));
- gradient.setColorAt(1, gradientStopColor.lighter(105));
- } else {
- gradient.setColorAt(0, gradientStartColor.lighter(105));
- gradient.setColorAt(1, gradientStopColor);
- }
- sliderPainter.fillRect(pixmapRect.adjusted(2, 2, -2, -2), gradient);
- } else {
- sliderPainter.fillRect(pixmapRect.adjusted(2, 2, -2, -2), option->palette.background());
- }
-
- sliderPainter.setPen(borderColor);
- sliderPainter.drawRect(pixmapRect.adjusted(0, 0, -1, -1));
- sliderPainter.setPen(alphaCornerColor);
- QPoint points[4] = {
- QPoint(pixmapRect.left(), pixmapRect.top()),
- QPoint(pixmapRect.left(), pixmapRect.bottom()),
- QPoint(pixmapRect.right(), pixmapRect.top()),
- QPoint(pixmapRect.right(), pixmapRect.bottom()) };
- sliderPainter.drawPoints(points, 4);
-
- QLine lines[2];
- sliderPainter.setPen(sunken ? gradientStartColor.lighter(110) : gradientStartColor.lighter(105));
- lines[0] = QLine(pixmapRect.left() + 1, pixmapRect.top() + 1,
- pixmapRect.right() - 1, pixmapRect.top() + 1);
- lines[1] = QLine(pixmapRect.left() + 1, pixmapRect.top() + 2,
- pixmapRect.left() + 1, pixmapRect.bottom() - 2);
- sliderPainter.drawLines(lines, 2);
-
- sliderPainter.setPen(sunken ? gradientStopColor.lighter(105) : gradientStopColor);
- lines[0] = QLine(pixmapRect.left() + 1, pixmapRect.bottom() - 1,
- pixmapRect.right() - 1, pixmapRect.bottom() - 1);
- lines[1] = QLine(pixmapRect.right() - 1, pixmapRect.top() + 2,
- pixmapRect.right() - 1, pixmapRect.bottom() - 1);
- sliderPainter.drawLines(lines, 2);
-
- int sliderMinLength = proxy()->pixelMetric(PM_ScrollBarSliderMin, scrollBar, widget);
- if ((horizontal && scrollBar->rect.width() > sliderMinLength)
- || (!horizontal && scrollBar->rect.height() > sliderMinLength)) {
- QImage pattern(horizontal ? qt_scrollbar_slider_pattern_horizontal
- : qt_scrollbar_slider_pattern_vertical);
- pattern.setColor(1, alphaCornerColor.rgba());
- pattern.setColor(2, (sunken ? gradientStartColor.lighter(110) : gradientStartColor.lighter(105)).rgba());
-
- if (horizontal) {
- sliderPainter.drawImage(pixmapRect.center().x() - pattern.width() / 2 + 1,
- pixmapRect.center().y() - 4,
- pattern);
- } else {
- sliderPainter.drawImage(pixmapRect.center().x() - 4,
- pixmapRect.center().y() - pattern.height() / 2 + 1,
- pattern);
- }
- }
- sliderPainter.end();
- // insert the slider into the cache
- QPixmapCache::insert(sliderPixmapName, cache);
- }
- painter->drawPixmap(option->rect.topLeft(), cache);
- }
- }
- break;
-#endif
-#ifndef QT_NO_COMBOBOX
- case CE_ComboBoxLabel:
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- painter->save();
- if (!comboBox->editable) {
- // Plastique's non-editable combo box is drawn as a button, so
- // we need the label to be drawn using ButtonText where it
- // would usually use Text.
- painter->setPen(QPen(comboBox->palette.buttonText(), 0));
- QWindowsStyle::drawControl(element, option, painter, widget);
- } else if (!comboBox->currentIcon.isNull()) {
- {
- QRect editRect = proxy()->subControlRect(CC_ComboBox, comboBox, SC_ComboBoxEditField, widget);
- if (comboBox->direction == Qt::RightToLeft)
- editRect.adjust(0, 2, -2, -2);
- else
- editRect.adjust(2, 2, 0, -2);
- painter->save();
- painter->setClipRect(editRect);
- if (!comboBox->currentIcon.isNull()) {
- QIcon::Mode mode = comboBox->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- QPixmap pixmap = comboBox->currentIcon.pixmap(comboBox->iconSize, mode);
- QRect iconRect(editRect);
- iconRect.setWidth(comboBox->iconSize.width() + 5);
- iconRect = alignedRect(comboBox->direction,
- Qt::AlignLeft | Qt::AlignVCenter,
- iconRect.size(), editRect);
- painter->fillRect(iconRect, option->palette.brush(QPalette::Base));
- proxy()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap);
- }
- painter->restore();
- }
- } else {
- QWindowsStyle::drawControl(element, option, painter, widget);
- }
-
- painter->restore();
- }
- break;
-#endif
- default:
- QWindowsStyle::drawControl(element, option, painter, widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const
-{
- QColor borderColor = option->palette.background().color().darker(178);
- QColor alphaCornerColor;
- if (widget) {
- // ### backgroundrole/foregroundrole should be part of the style option
- alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
- } else {
- alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
- }
- QColor gradientStartColor = option->palette.button().color().lighter(104);
- QColor gradientStopColor = option->palette.button().color().darker(105);
- QColor highlightedGradientStartColor = option->palette.button().color().lighter(101);
- QColor highlightedGradientStopColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 85);
- QColor highlightedDarkInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 35);
- QColor highlightedLightInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 58);
-
- switch (control) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- QRect grooveRegion = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget);
- QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget);
- QRect ticks = proxy()->subControlRect(CC_Slider, option, SC_SliderTickmarks, widget);
- bool horizontal = slider->orientation == Qt::Horizontal;
- bool ticksAbove = slider->tickPosition & QSlider::TicksAbove;
- bool ticksBelow = slider->tickPosition & QSlider::TicksBelow;
-
- QRect groove;
- //The clickable region is 5 px wider than the visible groove for improved usability
- if (grooveRegion.isValid())
- groove = horizontal ? grooveRegion.adjusted(0, 5, 0, -5) : grooveRegion.adjusted(5, 0, -5, 0);
-
-
- QPixmap cache;
-
- if ((option->subControls & SC_SliderGroove) && groove.isValid()) {
- BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("slider_groove-%0-%1").arg(ticksAbove).arg(ticksBelow))
- p->fillRect(groove, option->palette.background());
-
- // draw groove
- if (horizontal) {
- p->setPen(borderColor);
- const QLine lines[4] = {
- QLine(groove.left() + 1, groove.top(),
- groove.right() - 1, groove.top()),
- QLine(groove.left() + 1, groove.bottom(),
- groove.right() - 1, groove.bottom()),
- QLine(groove.left(), groove.top() + 1,
- groove.left(), groove.bottom() - 1),
- QLine(groove.right(), groove.top() + 1,
- groove.right(), groove.bottom() - 1) };
- p->drawLines(lines, 4);
-
- p->setPen(alphaCornerColor);
- const QPoint points[4] = {
- QPoint(groove.left(), groove.top()),
- QPoint(groove.left(), groove.bottom()),
- QPoint(groove.right(), groove.top()),
- QPoint(groove.right(), groove.bottom()) };
- p->drawPoints(points, 4);
- } else {
- p->setPen(borderColor);
- const QLine lines[4] = {
- QLine(groove.left() + 1, groove.top(),
- groove.right() - 1, groove.top()),
- QLine(groove.left() + 1, groove.bottom(),
- groove.right() - 1, groove.bottom()),
- QLine(groove.left(), groove.top() + 1,
- groove.left(), groove.bottom() - 1),
- QLine(groove.right(), groove.top() + 1,
- groove.right(), groove.bottom() - 1) };
- p->drawLines(lines, 4);
-
- p->setPen(alphaCornerColor);
- const QPoint points[4] = {
- QPoint(groove.left(), groove.top()),
- QPoint(groove.right(), groove.top()),
- QPoint(groove.left(), groove.bottom()),
- QPoint(groove.right(), groove.bottom()) };
- p->drawPoints(points, 4);
- }
- END_STYLE_PIXMAPCACHE
- }
-
- if ((option->subControls & SC_SliderHandle) && handle.isValid()) {
- QString handlePixmapName = QStyleHelper::uniqueName(QLatin1String("slider_handle"), option, handle.size());
- if (ticksAbove && !ticksBelow)
- handlePixmapName += QLatin1String("-flipped");
- if ((option->activeSubControls & SC_SliderHandle) && (option->state & State_Sunken))
- handlePixmapName += QLatin1String("-sunken");
-
- if (!QPixmapCache::find(handlePixmapName, cache)) {
- cache = QPixmap(handle.size());
- cache.fill(Qt::white);
- QRect pixmapRect(0, 0, handle.width(), handle.height());
- QPainter handlePainter(&cache);
- handlePainter.fillRect(pixmapRect, option->palette.background());
-
- // draw handle
- if (horizontal) {
- QPainterPath path;
- if (ticksAbove && !ticksBelow) {
- path.moveTo(QPoint(pixmapRect.right(), pixmapRect.bottom()));
- path.lineTo(QPoint(pixmapRect.right(), pixmapRect.bottom() - 10));
- path.lineTo(QPoint(pixmapRect.right() - 5, pixmapRect.bottom() - 14));
- path.lineTo(QPoint(pixmapRect.left() + 1, pixmapRect.bottom() - 10));
- path.lineTo(QPoint(pixmapRect.left() + 1, pixmapRect.bottom()));
- path.lineTo(QPoint(pixmapRect.right(), pixmapRect.bottom()));
- } else {
- path.moveTo(QPoint(pixmapRect.right(), pixmapRect.top() + 1));
- path.lineTo(QPoint(pixmapRect.right(), pixmapRect.top() + 10));
- path.lineTo(QPoint(pixmapRect.right() - 5, pixmapRect.top() + 14));
- path.lineTo(QPoint(pixmapRect.left() + 1, pixmapRect.top() + 10));
- path.lineTo(QPoint(pixmapRect.left() + 1, pixmapRect.top() + 1));
- path.lineTo(QPoint(pixmapRect.right(), pixmapRect.top() + 1));
- }
- if (slider->state & State_Enabled) {
- QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top(),
- pixmapRect.center().x(), pixmapRect.bottom());
- if ((option->activeSubControls & SC_SliderHandle) && (option->state & State_Sunken)) {
- gradient.setColorAt(0, gradientStartColor.lighter(110));
- gradient.setColorAt(1, gradientStopColor.lighter(110));
- } else {
- gradient.setColorAt(0, gradientStartColor);
- gradient.setColorAt(1, gradientStopColor);
- }
- handlePainter.fillPath(path, gradient);
- } else {
- handlePainter.fillPath(path, slider->palette.background());
- }
- } else {
- QPainterPath path;
- if (ticksAbove && !ticksBelow) {
- path.moveTo(QPoint(pixmapRect.right(), pixmapRect.top() + 1));
- path.lineTo(QPoint(pixmapRect.right() - 10, pixmapRect.top() + 1));
- path.lineTo(QPoint(pixmapRect.right() - 14, pixmapRect.top() + 5));
- path.lineTo(QPoint(pixmapRect.right() - 10, pixmapRect.bottom()));
- path.lineTo(QPoint(pixmapRect.right(), pixmapRect.bottom()));
- path.lineTo(QPoint(pixmapRect.right(), pixmapRect.top() + 1));
- } else {
- path.moveTo(QPoint(pixmapRect.left() + 1, pixmapRect.top() + 1));
- path.lineTo(QPoint(pixmapRect.left() + 10, pixmapRect.top() + 1));
- path.lineTo(QPoint(pixmapRect.left() + 14, pixmapRect.top() + 5));
- path.lineTo(QPoint(pixmapRect.left() + 10, pixmapRect.bottom()));
- path.lineTo(QPoint(pixmapRect.left() + 1, pixmapRect.bottom()));
- path.lineTo(QPoint(pixmapRect.left() + 1, pixmapRect.top() + 1));
- }
- if (slider->state & State_Enabled) {
- QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top(),
- pixmapRect.center().x(), pixmapRect.bottom());
- gradient.setColorAt(0, gradientStartColor);
- gradient.setColorAt(1, gradientStopColor);
- handlePainter.fillPath(path, gradient);
- } else {
- handlePainter.fillPath(path, slider->palette.background());
- }
- }
-
- QImage image;
- if (horizontal) {
- image = QImage((ticksAbove && !ticksBelow) ? qt_plastique_slider_horizontalhandle_up : qt_plastique_slider_horizontalhandle);
- } else {
- image = QImage((ticksAbove && !ticksBelow) ? qt_plastique_slider_verticalhandle_left : qt_plastique_slider_verticalhandle);
- }
-
- image.setColor(1, borderColor.rgba());
- image.setColor(2, gradientStartColor.rgba());
- image.setColor(3, alphaCornerColor.rgba());
- if (option->state & State_Enabled) {
- image.setColor(4, 0x80ffffff);
- image.setColor(5, 0x25000000);
- }
- handlePainter.drawImage(pixmapRect, image);
- handlePainter.end();
- QPixmapCache::insert(handlePixmapName, cache);
- }
-
- painter->drawPixmap(handle.topLeft(), cache);
-
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = subElementRect(SE_SliderFocusRect, slider, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- }
-
- if (option->subControls & SC_SliderTickmarks) {
- QPen oldPen = painter->pen();
- painter->setPen(borderColor);
- int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
- int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
- int interval = slider->tickInterval;
- if (interval <= 0) {
- interval = slider->singleStep;
- if (QStyle::sliderPositionFromValue(slider->minimum, slider->maximum, interval,
- available)
- - QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- 0, available) < 3)
- interval = slider->pageStep;
- }
- if (interval <= 0)
- interval = 1;
-
- int v = slider->minimum;
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- QVarLengthArray<QLine, 32> lines;
- while (v <= slider->maximum + 1) {
- if (v == slider->maximum + 1 && interval == 1)
- break;
- const int v_ = qMin(v, slider->maximum);
- int pos = sliderPositionFromValue(slider->minimum, slider->maximum,
- v_, (horizontal
- ? slider->rect.width()
- : slider->rect.height()) - len,
- slider->upsideDown) + len / 2;
-
- int extra = 2 - ((v_ == slider->minimum || v_ == slider->maximum) ? 1 : 0);
-
- if (horizontal) {
- if (ticksAbove) {
- lines.append(QLine(pos, slider->rect.top() + extra,
- pos, slider->rect.top() + tickSize));
- }
- if (ticksBelow) {
- lines.append(QLine(pos, slider->rect.bottom() - extra,
- pos, slider->rect.bottom() - tickSize));
- }
- } else {
- if (ticksAbove) {
- lines.append(QLine(slider->rect.left() + extra, pos,
- slider->rect.left() + tickSize, pos));
- }
- if (ticksBelow) {
- lines.append(QLine(slider->rect.right() - extra, pos,
- slider->rect.right() - tickSize, pos));
- }
- }
-
- // in the case where maximum is max int
- int nextInterval = v + interval;
- if (nextInterval < v)
- break;
- v = nextInterval;
- }
- painter->drawLines(lines.constData(), lines.size());
- painter->setPen(oldPen);
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- painter->save();
- bool upSunken = (spinBox->activeSubControls & SC_SpinBoxUp) && (spinBox->state & (State_Sunken | State_On));
- bool downSunken = (spinBox->activeSubControls & SC_SpinBoxDown) && (spinBox->state & (State_Sunken | State_On));
- bool reverse = (spinBox->direction == Qt::RightToLeft);
-
- // Rects
- QRect upRect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxUp, widget);
- QRect downRect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxDown, widget);
- QRect buttonRect = upRect | downRect;
-
- // Brushes
- QBrush corner = qMapBrushToRect(option->palette.shadow(), buttonRect);
- qBrushSetAlphaF(&corner, qreal(0.25));
- QBrush border = qMapBrushToRect(option->palette.shadow(), buttonRect);
- qBrushSetAlphaF(&border, qreal(0.4));
-
- QVarLengthArray<QPoint, 4> points;
-
- Q_D(const QPlastiqueStyle);
- if (spinBox->buttonSymbols == QAbstractSpinBox::NoButtons) {
- QRect filledRect = option->rect.adjusted(1, 1, -1, -1);
- QBrush baseBrush = qMapBrushToRect(option->palette.base(), filledRect);
- painter->setBrushOrigin(filledRect.topLeft());
- painter->fillRect(filledRect.adjusted(1, 1, -1, -1), baseBrush);
- qt_plastique_draw_frame(painter, option->rect, option, QFrame::Sunken);
- } else {
- d->drawPartialFrame(painter,
- option,
- proxy()->subControlRect(CC_SpinBox, spinBox, SC_SpinBoxEditField, widget),
- widget);
- }
- // Paint buttons
- if (spinBox->buttonSymbols == QAbstractSpinBox::NoButtons) {
- painter->restore();
- break;
- }
- // Button outlines
- painter->setPen(QPen(border, 0));
- if (!reverse)
- painter->drawLine(buttonRect.topLeft() + QPoint(0, 1), buttonRect.bottomLeft() + QPoint(0, -1));
- else
- painter->drawLine(buttonRect.topRight() + QPoint(0, -1), buttonRect.bottomRight() + QPoint(0, 1));
-
- if (!reverse) {
- const QLine lines[4] = {
- QLine(upRect.left(), upRect.top(), upRect.right() - 2, upRect.top()),
- QLine(upRect.left() + 1, upRect.bottom(), upRect.right() - 1, upRect.bottom()),
- QLine(downRect.left(), downRect.bottom(), downRect.right() - 2, downRect.bottom()),
- QLine(buttonRect.right(), buttonRect.top() + 2, buttonRect.right(), buttonRect.bottom() - 2) };
- painter->drawLines(lines, 4);
-
- points.append(QPoint(upRect.right() - 1, upRect.top() + 1));
- points.append(QPoint(downRect.right() - 1, downRect.bottom() - 1));
- painter->drawPoints(points.constData(), points.size());
- points.clear();
- painter->setPen(QPen(corner, 0));
- points.append(QPoint(upRect.right() - 1, upRect.top()));
- points.append(QPoint(upRect.right(), upRect.top() + 1));
- points.append(QPoint(upRect.right(), downRect.bottom() - 1));
- points.append(QPoint(upRect.right() - 1, downRect.bottom()));
- } else {
- const QLine lines[4] = {
- QLine(upRect.right(), upRect.top(), upRect.left() + 2, upRect.top()),
- QLine(upRect.right() - 1, upRect.bottom(), upRect.left() + 1, upRect.bottom()),
- QLine(downRect.right(), downRect.bottom(), downRect.left() + 2, downRect.bottom()),
- QLine(buttonRect.left(), buttonRect.top() + 2, buttonRect.left(), buttonRect.bottom() - 2) };
- painter->drawLines(lines, 4);
-
- points.append(QPoint(upRect.left() + 1, upRect.top() + 1));
- points.append(QPoint(downRect.left() + 1, downRect.bottom() - 1));
- painter->drawPoints(points.constData(), points.size());
- points.clear();
- painter->setPen(QPen(corner, 0));
- points.append(QPoint(upRect.left() + 1, upRect.top()));
- points.append(QPoint(upRect.left(), upRect.top() + 1));
- points.append(QPoint(upRect.left(), downRect.bottom() - 1));
- points.append(QPoint(upRect.left() + 1, downRect.bottom()));
- }
- painter->drawPoints(points.constData(), points.size());
- points.clear();
-
- // Button colors
- QBrush buttonGradientBrush;
- QBrush leftLineGradientBrush;
- QBrush rightLineGradientBrush;
- QBrush sunkenButtonGradientBrush;
- QBrush sunkenLeftLineGradientBrush;
- QBrush sunkenRightLineGradientBrush;
- QBrush buttonBrush = qMapBrushToRect(option->palette.button(), buttonRect);
- if (buttonBrush.gradient() || !buttonBrush.texture().isNull()) {
- buttonGradientBrush = buttonBrush;
- sunkenButtonGradientBrush = qBrushDark(buttonBrush, 108);
- leftLineGradientBrush = qBrushLight(buttonBrush, 105);
- rightLineGradientBrush = qBrushDark(buttonBrush, 105);
- sunkenLeftLineGradientBrush = qBrushDark(buttonBrush, 110);
- sunkenRightLineGradientBrush = qBrushDark(buttonBrush, 106);
- } else {
- // Generate gradients
- QLinearGradient buttonGradient(buttonRect.topLeft(), buttonRect.bottomLeft());
- buttonGradient.setColorAt(0.0, buttonBrush.color().lighter(104));
- buttonGradient.setColorAt(1.0, buttonBrush.color().darker(110));
- buttonGradientBrush = QBrush(buttonGradient);
-
- QLinearGradient buttonGradient2(buttonRect.topLeft(), buttonRect.bottomLeft());
- buttonGradient2.setColorAt(0.0, buttonBrush.color().darker(113));
- buttonGradient2.setColorAt(1.0, buttonBrush.color().darker(103));
- sunkenButtonGradientBrush = QBrush(buttonGradient2);
-
- QLinearGradient buttonGradient3(buttonRect.topLeft(), buttonRect.bottomLeft());
- buttonGradient3.setColorAt(0.0, buttonBrush.color().lighter(105));
- buttonGradient3.setColorAt(1.0, buttonBrush.color());
- leftLineGradientBrush = QBrush(buttonGradient3);
-
- QLinearGradient buttonGradient4(buttonRect.topLeft(), buttonRect.bottomLeft());
- buttonGradient4.setColorAt(0.0, buttonBrush.color());
- buttonGradient4.setColorAt(1.0, buttonBrush.color().darker(110));
- rightLineGradientBrush = QBrush(buttonGradient4);
-
- QLinearGradient buttonGradient5(buttonRect.topLeft(), buttonRect.bottomLeft());
- buttonGradient5.setColorAt(0.0, buttonBrush.color().darker(113));
- buttonGradient5.setColorAt(1.0, buttonBrush.color().darker(107));
- sunkenLeftLineGradientBrush = QBrush(buttonGradient5);
-
- QLinearGradient buttonGradient6(buttonRect.topLeft(), buttonRect.bottomLeft());
- buttonGradient6.setColorAt(0.0, buttonBrush.color().darker(108));
- buttonGradient6.setColorAt(1.0, buttonBrush.color().darker(103));
- sunkenRightLineGradientBrush = QBrush(buttonGradient6);
- }
-
- // Main fill
- painter->fillRect(upRect.adjusted(2, 2, -2, -2),
- qMapBrushToRect(upSunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, upRect));
- painter->fillRect(downRect.adjusted(2, 2, -2, -2),
- qMapBrushToRect(downSunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, downRect));
-
- // Top line
- painter->setPen(QPen(qBrushLight(qMapBrushToRect(upSunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, upRect), 105), 0));
- if (!reverse) {
- painter->drawLine(upRect.left() + 1, upRect.top() + 1,
- upRect.right() - 2, upRect.top() + 1);
- } else {
- painter->drawLine(upRect.right() - 1, upRect.top() + 1,
- upRect.left() + 2, upRect.top() + 1);
- }
- painter->setPen(QPen(qBrushLight(qMapBrushToRect(downSunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, downRect), 105), 0));
- if (!reverse) {
- painter->drawLine(downRect.left() + 1, downRect.top() + 1,
- downRect.right() - 1, downRect.top() + 1);
- } else {
- painter->drawLine(downRect.right() - 1, downRect.top() + 1,
- downRect.left() + 1, downRect.top() + 1);
- }
-
- // Left line
- painter->setPen(QPen(qMapBrushToRect(upSunken ? sunkenLeftLineGradientBrush
- : leftLineGradientBrush, upRect), 1));
- if (!reverse) {
- painter->drawLine(upRect.left() + 1, upRect.top() + 2,
- upRect.left() + 1, upRect.bottom() - 1);
- } else {
- painter->drawLine(upRect.left() + 1, upRect.top() + 2,
- upRect.left() + 1, upRect.bottom() - 1);
- }
- painter->setPen(QPen(qMapBrushToRect(downSunken ? sunkenLeftLineGradientBrush
- : leftLineGradientBrush, downRect), 1));
- if (!reverse) {
- painter->drawLine(downRect.left() + 1, downRect.top() + 2,
- downRect.left() + 1, downRect.bottom() - 1);
- } else {
- painter->drawLine(downRect.left() + 1, downRect.top() + 1,
- downRect.left() + 1, downRect.bottom() - 2);
- }
-
- // Bottom line
- painter->setPen(QPen(qBrushDark(qMapBrushToRect(upSunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, upRect), 105), 0));
- if (!reverse) {
- painter->drawLine(upRect.left() + 2, upRect.bottom() - 1,
- upRect.right() - 1, upRect.bottom() - 1);
- } else {
- painter->drawLine(upRect.right() - 2, upRect.bottom() - 1,
- upRect.left() + 1, upRect.bottom() - 1);
- }
- painter->setPen(QPen(qBrushDark(qMapBrushToRect(downSunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, downRect), 105), 0));
- if (!reverse) {
- painter->drawLine(downRect.left() + 2, downRect.bottom() - 1,
- downRect.right() - 2, downRect.bottom() - 1);
- } else {
- painter->drawLine(downRect.right() - 2, downRect.bottom() - 1,
- downRect.left() + 2, downRect.bottom() - 1);
- }
-
- // Right line
- painter->setPen(QPen(qMapBrushToRect(upSunken ? sunkenRightLineGradientBrush
- : rightLineGradientBrush, upRect), 1));
- if (!reverse) {
- painter->drawLine(upRect.right() - 1, upRect.top() + 2,
- upRect.right() - 1, upRect.bottom() - 1);
- } else {
- painter->drawLine(upRect.right() - 1, upRect.top() + 2,
- upRect.right() - 1, upRect.bottom() - 1);
- }
- painter->setPen(QPen(qMapBrushToRect(downSunken ? sunkenRightLineGradientBrush
- : rightLineGradientBrush, downRect), 1));
- if (!reverse) {
- painter->drawLine(downRect.right() - 1, downRect.top() + 1,
- downRect.right() - 1, downRect.bottom() - 2);
- } else {
- painter->drawLine(downRect.right() - 1, downRect.top() + 2,
- downRect.right() - 1, downRect.bottom() - 1);
- }
-
- QBrush indicatorBrush = qMapBrushToRect(option->palette.buttonText(), buttonRect);
- painter->setPen(QPen(indicatorBrush, 0));
- if (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) {
- QPoint center;
- if (spinBox->subControls & SC_SpinBoxUp) {
- // .......
- // ...X...
- // ...X...
- // .XXXXX.
- // ...X...
- // ...X...
- // .......
- center = upRect.center();
- if (upSunken) {
- ++center.rx();
- ++center.ry();
- }
- painter->drawLine(center.x(), center.y() - 2, center.x(), center.y() + 2);
- painter->drawLine(center.x() - 2, center.y(), center.x() + 2, center.y());
- }
- if (spinBox->subControls & SC_SpinBoxDown) {
- // .......
- // .......
- // .......
- // .XXXXX.
- // .......
- // .......
- // .......
- center = downRect.center();
- if (downSunken) {
- ++center.rx();
- ++center.ry();
- }
- painter->drawLine(center.x() - 2, center.y(), center.x() + 2, center.y());
- }
- } else {
- int offset;
- int centerX;
- if (spinBox->subControls & SC_SpinBoxUp) {
- // ...........
- // .....X.....
- // ....XXX....
- // ...XXXXX...
- // ..XXXXXXX..
- // ...........
- offset = upSunken ? 1 : 0;
- QRect upArrowRect(upRect.center().x() - 3 + offset, upRect.center().y() - 2 + offset, 7, 4);
- centerX = upArrowRect.center().x();
- painter->drawPoint(centerX, upArrowRect.top());
- const QLine lines[3] = {
- QLine(centerX - 1, upArrowRect.top() + 1, centerX + 1, upArrowRect.top() + 1),
- QLine(centerX - 2, upArrowRect.top() + 2, centerX + 2, upArrowRect.top() + 2),
- QLine(centerX - 3, upArrowRect.top() + 3, centerX + 3, upArrowRect.top() + 3) };
- painter->drawLines(lines, 3);
- }
- if (spinBox->subControls & SC_SpinBoxDown) {
- // ...........
- // ..XXXXXXX..
- // ...XXXXX...
- // ....XXX....
- // .....X.....
- // ...........
- offset = downSunken ? 1 : 0;
- QRect downArrowRect(downRect.center().x() - 3 + offset, downRect.center().y() - 2 + offset + 1, 7, 4);
- centerX = downArrowRect.center().x();
- const QLine lines[3] = {
- QLine(centerX - 3, downArrowRect.top(), centerX + 3, downArrowRect.top()),
- QLine(centerX - 2, downArrowRect.top() + 1, centerX + 2, downArrowRect.top() + 1),
- QLine(centerX - 1, downArrowRect.top() + 2, centerX + 1, downArrowRect.top() + 2) };
- painter->drawLines(lines, 3);
- painter->drawPoint(centerX, downArrowRect.top() + 3);
- }
- }
- painter->restore();
- }
- break;
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- bool sunken = comboBox->state & State_On; // play dead if combobox has no items
- bool reverse = comboBox->direction == Qt::RightToLeft;
- int menuButtonWidth = 16;
- int xoffset = sunken ? (reverse ? -1 : 1) : 0;
- int yoffset = sunken ? 1 : 0;
- QRect rect = comboBox->rect;
- QPen oldPen = painter->pen();
-
- // Fill
- if (comboBox->editable) {
- // Button colors
- QBrush alphaCornerBrush = qBrushDark(option->palette.button(), 165);
- qBrushSetAlphaF(&alphaCornerBrush, 0.5);
- QBrush buttonGradientBrush;
- QBrush leftLineGradientBrush;
- QBrush rightLineGradientBrush;
- QBrush sunkenButtonGradientBrush;
- QBrush sunkenLeftLineGradientBrush;
- QBrush sunkenRightLineGradientBrush;
- QBrush button = option->palette.button();
- if (button.gradient() || !button.texture().isNull()) {
- buttonGradientBrush = button;
- sunkenButtonGradientBrush = qBrushDark(button, 108);
- leftLineGradientBrush = qBrushLight(button, 105);
- rightLineGradientBrush = qBrushDark(button, 105);
- sunkenLeftLineGradientBrush = qBrushDark(button, 110);
- sunkenRightLineGradientBrush = qBrushDark(button, 106);
- } else {
- // Generate gradients
- QLinearGradient buttonGradient(option->rect.topLeft(), option->rect.bottomLeft());
- buttonGradient.setColorAt(0.0, button.color().lighter(104));
- buttonGradient.setColorAt(1.0, button.color().darker(110));
- buttonGradientBrush = QBrush(buttonGradient);
-
- QLinearGradient buttonGradient2(option->rect.topLeft(), option->rect.bottomLeft());
- buttonGradient2.setColorAt(0.0, button.color().darker(113));
- buttonGradient2.setColorAt(1.0, button.color().darker(103));
- sunkenButtonGradientBrush = QBrush(buttonGradient2);
-
- QLinearGradient buttonGradient3(option->rect.topLeft(), option->rect.bottomLeft());
- buttonGradient3.setColorAt(0.0, button.color().lighter(105));
- buttonGradient3.setColorAt(1.0, button.color());
- leftLineGradientBrush = QBrush(buttonGradient3);
-
- QLinearGradient buttonGradient4(option->rect.topLeft(), option->rect.bottomLeft());
- buttonGradient4.setColorAt(0.0, button.color());
- buttonGradient4.setColorAt(1.0, button.color().darker(110));
- rightLineGradientBrush = QBrush(buttonGradient4);
-
- QLinearGradient buttonGradient5(option->rect.topLeft(), option->rect.bottomLeft());
- buttonGradient5.setColorAt(0.0, button.color().darker(113));
- buttonGradient5.setColorAt(1.0, button.color().darker(107));
- sunkenLeftLineGradientBrush = QBrush(buttonGradient5);
-
- QLinearGradient buttonGradient6(option->rect.topLeft(), option->rect.bottomLeft());
- buttonGradient6.setColorAt(0.0, button.color().darker(108));
- buttonGradient6.setColorAt(1.0, button.color().darker(103));
- sunkenRightLineGradientBrush = QBrush(buttonGradient6);
- }
-
- // ComboBox starts with a lineedit in place already.
- QRect buttonRect;
- if (!reverse) {
- buttonRect.setRect(rect.right() - menuButtonWidth, rect.top(), menuButtonWidth + 1, rect.height());
- } else {
- buttonRect.setRect(rect.left(), rect.top(), menuButtonWidth + 1, rect.height());
- }
-
- Q_D(const QPlastiqueStyle);
- d->drawPartialFrame(painter,
- option,
- proxy()->subControlRect(CC_ComboBox, option, SC_ComboBoxEditField, widget),
- widget);
-
- QBrush border = qMapBrushToRect(option->palette.shadow(), buttonRect);
- qBrushSetAlphaF(&border, qreal(0.4));
- painter->setPen(QPen(border, 0));
- if (!reverse)
- painter->drawLine(buttonRect.topLeft() + QPoint(0, 1), buttonRect.bottomLeft() + QPoint(0, -1));
- else
- painter->drawLine(buttonRect.topRight() + QPoint(0, -1), buttonRect.bottomRight() + QPoint(0, 1));
-
- // Outline the button border
- if (!reverse) {
- const QLine lines[3] = {
- QLine(buttonRect.left(), buttonRect.top(),
- buttonRect.right() - 2, buttonRect.top()),
- QLine(buttonRect.right(), buttonRect.top() + 2,
- buttonRect.right(), buttonRect.bottom() - 2),
- QLine(buttonRect.left(), buttonRect.bottom(),
- buttonRect.right() - 2, buttonRect.bottom()) };
- painter->drawLines(lines, 3);
- {
- const QPoint points[2] = {
- QPoint(buttonRect.right() - 1, buttonRect.top() + 1),
- QPoint(buttonRect.right() - 1, buttonRect.bottom() - 1) };
- painter->drawPoints(points, 2);
- }
-
- QBrush corner = qMapBrushToRect(option->palette.shadow(), buttonRect);
- qBrushSetAlphaF(&corner, qreal(0.16));
- painter->setPen(QPen(corner, 0));
- {
- const QPoint points[4] = {
- QPoint(buttonRect.right() - 1, buttonRect.top()),
- QPoint(buttonRect.right() - 1, buttonRect.bottom()),
- QPoint(buttonRect.right(), buttonRect.top() + 1),
- QPoint(buttonRect.right(), buttonRect.bottom() - 1) };
- painter->drawPoints(points, 4);
- }
- } else {
- const QLine lines[3] = {
- QLine(buttonRect.right(), buttonRect.top(),
- buttonRect.left() + 2, buttonRect.top()),
- QLine(buttonRect.left(), buttonRect.top() + 2,
- buttonRect.left(), buttonRect.bottom() - 2),
- QLine(buttonRect.right(), buttonRect.bottom(),
- buttonRect.left() + 2, buttonRect.bottom()) };
- painter->drawLines(lines, 3);
- {
- const QPoint points[2] = {
- QPoint(buttonRect.left() + 1, buttonRect.top() + 1),
- QPoint(buttonRect.left() + 1, buttonRect.bottom() - 1) };
- painter->drawPoints(points, 2);
- }
-
- QBrush corner = qMapBrushToRect(option->palette.shadow(), buttonRect);
- qBrushSetAlphaF(&corner, qreal(0.16));
- painter->setPen(QPen(corner, 0));
- {
- const QPoint points[4] = {
- QPoint(buttonRect.left() + 1, buttonRect.top()),
- QPoint(buttonRect.left() + 1, buttonRect.bottom()),
- QPoint(buttonRect.left(), buttonRect.top() + 1),
- QPoint(buttonRect.left(), buttonRect.bottom() - 1) };
- painter->drawPoints(points, 4);
- }
- }
-
- QRect fillRect = buttonRect.adjusted(2, 2, -2, -2);
- // Main fill
- painter->fillRect(fillRect,
- qMapBrushToRect(sunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, option->rect));
-
- // Top line
- painter->setPen(QPen(qBrushLight(qMapBrushToRect(sunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, option->rect), 105), 0));
- if (!reverse) {
- painter->drawLine(QPointF(buttonRect.left() + 1, buttonRect.top() + 1),
- QPointF(buttonRect.right() - 2, buttonRect.top() + 1));
- } else {
- painter->drawLine(QPointF(buttonRect.right() - 1, buttonRect.top() + 1),
- QPointF(buttonRect.left() + 2, buttonRect.top() + 1));
- }
-
- // Bottom line
- painter->setPen(QPen(qBrushDark(qMapBrushToRect(sunken ? sunkenButtonGradientBrush
- : buttonGradientBrush, option->rect), 105), 0));
- if (!reverse) {
- painter->drawLine(QPointF(buttonRect.left() + 1, buttonRect.bottom() - 1),
- QPointF(buttonRect.right() - 2, buttonRect.bottom() - 1));
- } else {
- painter->drawLine(QPointF(buttonRect.right() - 1, buttonRect.bottom() - 1),
- QPointF(buttonRect.left() + 2, buttonRect.bottom() - 1));
- }
-
- // Left line
- painter->setPen(QPen(qMapBrushToRect(sunken ? sunkenLeftLineGradientBrush
- : leftLineGradientBrush, option->rect), 1));
- if (!reverse) {
- painter->drawLine(QPointF(buttonRect.left() + 1, buttonRect.top() + 2),
- QPointF(buttonRect.left() + 1, buttonRect.bottom() - 2));
- } else {
- painter->drawLine(QPointF(buttonRect.left() + 1, buttonRect.top() + 2),
- QPointF(buttonRect.left() + 1, buttonRect.bottom() - 2));
- }
-
- // Right line
- painter->setPen(QPen(qMapBrushToRect(sunken ? sunkenRightLineGradientBrush
- : rightLineGradientBrush, option->rect), 1));
- if (!reverse) {
- painter->drawLine(QPointF(buttonRect.right() - 1, buttonRect.top() + 2),
- QPointF(buttonRect.right() - 1, buttonRect.bottom() - 2));
- } else {
- painter->drawLine(QPointF(buttonRect.right() - 1, buttonRect.top() + 2),
- QPointF(buttonRect.right() - 1, buttonRect.bottom() - 2));
- }
- } else {
- // Start with a standard panel button fill
- QStyleOptionButton buttonOption;
- buttonOption.QStyleOption::operator=(*comboBox);
- if (!sunken) {
- buttonOption.state &= ~State_Sunken;
- }
- proxy()->drawPrimitive(PE_PanelButtonCommand, &buttonOption, painter, widget);
-
- // Draw the menu button separator line
- QBrush border = qMapBrushToRect(option->palette.shadow(), rect);
- qBrushSetAlphaF(&border, qreal(0.35));
- painter->setPen(QPen(border, 0));
- if (!reverse) {
- painter->drawLine(rect.right() - menuButtonWidth + xoffset, rect.top() + 1,
- rect.right() - menuButtonWidth + xoffset, rect.bottom() - 1);
- } else {
- painter->drawLine(rect.left() + menuButtonWidth + xoffset, rect.top() + 1,
- rect.left() + menuButtonWidth + xoffset, rect.bottom() - 1);
- }
- }
-
- // Draw the little arrow
- if (comboBox->subControls & SC_ComboBoxArrow) {
- int left = !reverse ? rect.right() - menuButtonWidth : rect.left();
- int right = !reverse ? rect.right() : rect.left() + menuButtonWidth;
- QRect arrowRect((left + right) / 2 - 3 + xoffset,
- rect.center().y() - 1 + yoffset, 7, 4);
- painter->setPen(QPen(qMapBrushToRect(option->palette.buttonText(), rect), 0));
- const QLine lines[3] = {
- QLine(arrowRect.topLeft(), arrowRect.topRight()),
- QLine(arrowRect.left() + 1, arrowRect.top() + 1,
- arrowRect.right() - 1, arrowRect.top() + 1),
- QLine(arrowRect.left() + 2, arrowRect.top() + 2,
- arrowRect.right() - 2, arrowRect.top() + 2) };
- painter->drawLines(lines, 3);
- painter->drawPoint(arrowRect.center().x(), arrowRect.bottom());
- }
-
- // Draw the focus rect
- if ((option->state & State_HasFocus) && !comboBox->editable
- && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget))) {
- QStyleOptionFocusRect focus;
- focus.rect = proxy()->subControlRect(CC_ComboBox, option, SC_ComboBoxEditField, widget)
- .adjusted(-2, 0, 2, 0);
- proxy()->drawPrimitive(PE_FrameFocusRect, &focus, painter, widget);
- }
-
- painter->setPen(oldPen);
- }
- break;
-#endif // QT_NO_COMBOBOX
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *titleBar = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- painter->save();
- bool active = (titleBar->titleBarState & State_Active);
- QRect fullRect = titleBar->rect;
-
- // ### use palette colors instead
- QColor titleBarGradientStart(active ? 0x3b508a : 0x6e6e6e);
- QColor titleBarGradientStop(active ? 0x5d6e9e : 0x818181);
- QColor titleBarFrameBorder(0x393939);
- QColor titleBarAlphaCorner(active ? 0x4b5e7f : 0x6a6a6a);
- QColor titleBarInnerTopLine(active ? 0x8e98ba : 0xa4a4a4);
- QColor titleBarInnerInnerTopLine(active ? 0x57699b : 0x808080);
- QColor leftCorner(active ? 0x6f7ea8 : 0x8e8e8e);
- QColor rightCorner(active ? 0x44537d : 0x676767);
- QColor textColor(active ? 0x282e40 : 0x282e40);
- QColor textAlphaColor(active ? 0x3f4862 : 0x3f4862);
-
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- QStyleOptionDockWidgetV2 dockwidget;
- dockwidget.QStyleOption::operator=(*option);
- dockwidget.title = titleBar->text;
- proxy()->drawControl(CE_DockWidgetTitle, &dockwidget, painter, widget);
- } else
-#endif // QT3_SUPPORT
-
- {
- // Fill title bar gradient
- qt_plastique_draw_gradient(painter, option->rect.adjusted(1, 1, -1, 0),
- titleBarGradientStart,
- titleBarGradientStop);
-
- // Frame and rounded corners
- painter->setPen(titleBarFrameBorder);
-
- // top border line
- {
- const QLine lines[3] = {
- QLine(fullRect.left() + 2, fullRect.top(), fullRect.right() - 2, fullRect.top()),
- QLine(fullRect.left(), fullRect.top() + 2, fullRect.left(), fullRect.bottom()),
- QLine(fullRect.right(), fullRect.top() + 2, fullRect.right(), fullRect.bottom()) };
- painter->drawLines(lines, 3);
- const QPoint points[2] = {
- QPoint(fullRect.left() + 1, fullRect.top() + 1),
- QPoint(fullRect.right() - 1, fullRect.top() + 1) };
- painter->drawPoints(points, 2);
- }
-
- // alpha corners
- painter->setPen(titleBarAlphaCorner);
- {
- const QPoint points[4] = {
- QPoint(fullRect.left() + 2, fullRect.top() + 1),
- QPoint(fullRect.left() + 1, fullRect.top() + 2),
- QPoint(fullRect.right() - 2, fullRect.top() + 1),
- QPoint(fullRect.right() - 1, fullRect.top() + 2) };
- painter->drawPoints(points, 4);
- }
-
- // inner top line
- painter->setPen(titleBarInnerTopLine);
- painter->drawLine(fullRect.left() + 3, fullRect.top() + 1, fullRect.right() - 3, fullRect.top() + 1);
-
- // inner inner top line
- painter->setPen(titleBarInnerInnerTopLine);
- painter->drawLine(fullRect.left() + 2, fullRect.top() + 2, fullRect.right() - 2, fullRect.top() + 2);
-
- // left and right inner
- painter->setPen(leftCorner);
- painter->drawLine(fullRect.left() + 1, fullRect.top() + 3, fullRect.left() + 1, fullRect.bottom());
- painter->setPen(rightCorner);
- painter->drawLine(fullRect.right() - 1, fullRect.top() + 3, fullRect.right() - 1, fullRect.bottom());
-
- if (titleBar->titleBarState & Qt::WindowMinimized) {
- painter->setPen(titleBarFrameBorder);
- painter->drawLine(fullRect.left() + 2, fullRect.bottom(), fullRect.right() - 2, fullRect.bottom());
- {
- const QPoint points[2] = {
- QPoint(fullRect.left() + 1, fullRect.bottom() - 1),
- QPoint(fullRect.right() - 1, fullRect.bottom() - 1) };
- painter->drawPoints(points, 2);
- }
- painter->setPen(rightCorner);
- painter->drawLine(fullRect.left() + 2, fullRect.bottom() - 1, fullRect.right() - 2, fullRect.bottom() - 1);
- painter->setPen(titleBarAlphaCorner);
- {
- const QPoint points[4] = {
- QPoint(fullRect.left() + 1, fullRect.bottom() - 2),
- QPoint(fullRect.left() + 2, fullRect.bottom() - 1),
- QPoint(fullRect.right() - 1, fullRect.bottom() - 2),
- QPoint(fullRect.right() - 2, fullRect.bottom() - 1) };
- painter->drawPoints(points, 4);
- }
- }
- // draw title
- QRect textRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarLabel, widget);
-
- QFont font = painter->font();
- font.setBold(true);
- painter->setFont(font);
- painter->setPen(titleBar->palette.text().color());
-
- // Attempt to align left if there is not enough room for the title
- // text. Otherwise, align center. QWorkspace does elliding for us,
- // and it doesn't know about the bold title, so we need to work
- // around some of the width mismatches.
- bool tooWide = (QFontMetrics(font).width(titleBar->text) > textRect.width());
- QTextOption option((tooWide ? Qt::AlignLeft : Qt::AlignHCenter) | Qt::AlignVCenter);
- option.setWrapMode(QTextOption::NoWrap);
-
- painter->drawText(textRect.adjusted(1, 1, 1, 1), titleBar->text, option);
- painter->setPen(titleBar->palette.highlightedText().color());
- painter->drawText(textRect, titleBar->text, option);
- }
-
- // min button
- if ((titleBar->subControls & SC_TitleBarMinButton)
- && (titleBar->titleBarFlags & Qt::WindowMinimizeButtonHint)
- && !(titleBar->titleBarState & Qt::WindowMinimized)) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarMinButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarMinButton) && (titleBar->state & State_Sunken);
-
- QRect minButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarMinButton, widget);
- qt_plastique_draw_mdibutton(painter, titleBar, minButtonRect, hover, sunken);
-
- int xoffset = minButtonRect.width() / 3;
- int yoffset = minButtonRect.height() / 3;
-
- QRect minButtonIconRect(minButtonRect.left() + xoffset, minButtonRect.top() + yoffset,
- minButtonRect.width() - xoffset * 2, minButtonRect.height() - yoffset * 2);
-
- painter->setPen(textColor);
- {
- const QLine lines[2] = {
- QLine(minButtonIconRect.center().x() - 2,
- minButtonIconRect.center().y() + 3,
- minButtonIconRect.center().x() + 3,
- minButtonIconRect.center().y() + 3),
- QLine(minButtonIconRect.center().x() - 2,
- minButtonIconRect.center().y() + 4,
- minButtonIconRect.center().x() + 3,
- minButtonIconRect.center().y() + 4) };
- painter->drawLines(lines, 2);
- }
- painter->setPen(textAlphaColor);
- {
- const QLine lines[2] = {
- QLine(minButtonIconRect.center().x() - 3,
- minButtonIconRect.center().y() + 3,
- minButtonIconRect.center().x() - 3,
- minButtonIconRect.center().y() + 4),
- QLine(minButtonIconRect.center().x() + 4,
- minButtonIconRect.center().y() + 3,
- minButtonIconRect.center().x() + 4,
- minButtonIconRect.center().y() + 4) };
- painter->drawLines(lines, 2);
- }
- }
-
- // max button
- if ((titleBar->subControls & SC_TitleBarMaxButton)
- && (titleBar->titleBarFlags & Qt::WindowMaximizeButtonHint)
- && !(titleBar->titleBarState & Qt::WindowMaximized)) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarMaxButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarMaxButton) && (titleBar->state & State_Sunken);
-
- QRect maxButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarMaxButton, widget);
- qt_plastique_draw_mdibutton(painter, titleBar, maxButtonRect, hover, sunken);
-
- int xoffset = maxButtonRect.width() / 3;
- int yoffset = maxButtonRect.height() / 3;
-
- QRect maxButtonIconRect(maxButtonRect.left() + xoffset, maxButtonRect.top() + yoffset,
- maxButtonRect.width() - xoffset * 2, maxButtonRect.height() - yoffset * 2);
-
- painter->setPen(textColor);
- painter->drawRect(maxButtonIconRect.adjusted(0, 0, -1, -1));
- painter->drawLine(maxButtonIconRect.left() + 1, maxButtonIconRect.top() + 1,
- maxButtonIconRect.right() - 1, maxButtonIconRect.top() + 1);
- painter->setPen(textAlphaColor);
- const QPoint points[4] = {
- maxButtonIconRect.topLeft(), maxButtonIconRect.topRight(),
- maxButtonIconRect.bottomLeft(), maxButtonIconRect.bottomRight() };
- painter->drawPoints(points, 4);
- }
-
- // close button
- if (titleBar->subControls & SC_TitleBarCloseButton && titleBar->titleBarFlags & Qt::WindowSystemMenuHint) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarCloseButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarCloseButton) && (titleBar->state & State_Sunken);
-
- QRect closeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarCloseButton, widget);
- qt_plastique_draw_mdibutton(painter, titleBar, closeButtonRect, hover, sunken);
-
- int xoffset = closeButtonRect.width() / 3;
- int yoffset = closeButtonRect.height() / 3;
-
- QRect closeIconRect(closeButtonRect.left() + xoffset, closeButtonRect.top() + yoffset,
- closeButtonRect.width() - xoffset * 2, closeButtonRect.height() - yoffset * 2);
-
- painter->setPen(textAlphaColor);
- {
- const QLine lines[4] = {
- QLine(closeIconRect.left() + 1, closeIconRect.top(),
- closeIconRect.right(), closeIconRect.bottom() - 1),
- QLine(closeIconRect.left(), closeIconRect.top() + 1,
- closeIconRect.right() - 1, closeIconRect.bottom()),
- QLine(closeIconRect.right() - 1, closeIconRect.top(),
- closeIconRect.left(), closeIconRect.bottom() - 1),
- QLine(closeIconRect.right(), closeIconRect.top() + 1,
- closeIconRect.left() + 1, closeIconRect.bottom()) };
- painter->drawLines(lines, 4);
- const QPoint points[4] = {
- closeIconRect.topLeft(), closeIconRect.topRight(),
- closeIconRect.bottomLeft(), closeIconRect.bottomRight() };
- painter->drawPoints(points, 4);
- }
- painter->setPen(textColor);
- {
- const QLine lines[2] = {
- QLine(closeIconRect.left() + 1, closeIconRect.top() + 1,
- closeIconRect.right() - 1, closeIconRect.bottom() - 1),
- QLine(closeIconRect.left() + 1, closeIconRect.bottom() - 1,
- closeIconRect.right() - 1, closeIconRect.top() + 1) };
- painter->drawLines(lines, 2);
- }
- }
-
- // normalize button
- if ((titleBar->subControls & SC_TitleBarNormalButton) &&
- (((titleBar->titleBarFlags & Qt::WindowMinimizeButtonHint) &&
- (titleBar->titleBarState & Qt::WindowMinimized)) ||
- ((titleBar->titleBarFlags & Qt::WindowMaximizeButtonHint) &&
- (titleBar->titleBarState & Qt::WindowMaximized)))) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarNormalButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarNormalButton) && (titleBar->state & State_Sunken);
-
- QRect normalButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarNormalButton, widget);
- qt_plastique_draw_mdibutton(painter, titleBar, normalButtonRect, hover, sunken);
- int xoffset = int(normalButtonRect.width() / 3.5);
- int yoffset = int(normalButtonRect.height() / 3.5);
-
- QRect normalButtonIconRect(normalButtonRect.left() + xoffset, normalButtonRect.top() + yoffset,
- normalButtonRect.width() - xoffset * 2, normalButtonRect.height() - yoffset * 2);
-
- QRect frontWindowRect = normalButtonIconRect.adjusted(0, 3, -3, 0);
- painter->setPen(textColor);
- painter->drawRect(frontWindowRect.adjusted(0, 0, -1, -1));
- painter->drawLine(frontWindowRect.left() + 1, frontWindowRect.top() + 1,
- frontWindowRect.right() - 1, frontWindowRect.top() + 1);
- painter->setPen(textAlphaColor);
- {
- const QPoint points[4] = {
- frontWindowRect.topLeft(), frontWindowRect.topRight(),
- frontWindowRect.bottomLeft(), frontWindowRect.bottomRight() };
- painter->drawPoints(points, 4);
- }
-
- QRect backWindowRect = normalButtonIconRect.adjusted(3, 0, 0, -3);
- QRegion clipRegion = backWindowRect;
- clipRegion -= frontWindowRect;
- painter->save();
- painter->setClipRegion(clipRegion);
- painter->setPen(textColor);
- painter->drawRect(backWindowRect.adjusted(0, 0, -1, -1));
- painter->drawLine(backWindowRect.left() + 1, backWindowRect.top() + 1,
- backWindowRect.right() - 1, backWindowRect.top() + 1);
- painter->setPen(textAlphaColor);
- {
- const QPoint points[4] = {
- backWindowRect.topLeft(), backWindowRect.topRight(),
- backWindowRect.bottomLeft(), backWindowRect.bottomRight() };
- painter->drawPoints(points, 4);
- }
- painter->restore();
- }
-
- // context help button
- if (titleBar->subControls & SC_TitleBarContextHelpButton
- && (titleBar->titleBarFlags & Qt::WindowContextHelpButtonHint)) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarContextHelpButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarContextHelpButton) && (titleBar->state & State_Sunken);
-
- QRect contextHelpButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarContextHelpButton, widget);
-
- qt_plastique_draw_mdibutton(painter, titleBar, contextHelpButtonRect, hover, sunken);
-
- QColor blend;
- // ### Use palette colors
- if (active) {
- blend = mergedColors(QColor(hover ? 0x7d8bb1 : 0x55689a),
- QColor(hover ? 0x939ebe : 0x7381ab));
- } else {
- blend = mergedColors(QColor(hover ? 0x9e9e9e : 0x818181),
- QColor(hover ? 0xababab : 0x929292));
- }
- QImage image(qt_titlebar_context_help);
- image.setColor(4, textColor.rgba());
- image.setColor(3, mergedColors(blend, textColor, 30).rgba());
- image.setColor(2, mergedColors(blend, textColor, 70).rgba());
- image.setColor(1, mergedColors(blend, textColor, 90).rgba());
-
- painter->drawImage(contextHelpButtonRect, image);
- }
-
- // shade button
- if (titleBar->subControls & SC_TitleBarShadeButton) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarShadeButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarShadeButton) && (titleBar->state & State_Sunken);
-
- QRect shadeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarShadeButton, widget);
- qt_plastique_draw_mdibutton(painter, titleBar, shadeButtonRect, hover, sunken);
-
- int xoffset = shadeButtonRect.width() / 3;
- int yoffset = shadeButtonRect.height() / 3;
-
- QRect shadeButtonIconRect(shadeButtonRect.left() + xoffset, shadeButtonRect.top() + yoffset,
- shadeButtonRect.width() - xoffset * 2, shadeButtonRect.height() - yoffset * 2);
-
- QPainterPath path(shadeButtonIconRect.bottomLeft());
- path.lineTo(shadeButtonIconRect.center().x(), shadeButtonIconRect.bottom() - shadeButtonIconRect.height() / 2);
- path.lineTo(shadeButtonIconRect.bottomRight());
- path.lineTo(shadeButtonIconRect.bottomLeft());
-
- painter->setPen(textAlphaColor);
- painter->setBrush(textColor);
- painter->drawPath(path);
- }
-
- // unshade button
- if (titleBar->subControls & SC_TitleBarUnshadeButton) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarUnshadeButton) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarUnshadeButton) && (titleBar->state & State_Sunken);
-
- QRect unshadeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarUnshadeButton, widget);
- qt_plastique_draw_mdibutton(painter, titleBar, unshadeButtonRect, hover, sunken);
-
- int xoffset = unshadeButtonRect.width() / 3;
- int yoffset = unshadeButtonRect.height() / 3;
-
- QRect unshadeButtonIconRect(unshadeButtonRect.left() + xoffset, unshadeButtonRect.top() + yoffset,
- unshadeButtonRect.width() - xoffset * 2, unshadeButtonRect.height() - yoffset * 2);
-
- int midY = unshadeButtonIconRect.bottom() - unshadeButtonIconRect.height() / 2;
- QPainterPath path(QPoint(unshadeButtonIconRect.left(), midY));
- path.lineTo(unshadeButtonIconRect.right(), midY);
- path.lineTo(unshadeButtonIconRect.center().x(), unshadeButtonIconRect.bottom());
- path.lineTo(unshadeButtonIconRect.left(), midY);
-
- painter->setPen(textAlphaColor);
- painter->setBrush(textColor);
- painter->drawPath(path);
- }
-
- // from qwindowsstyle.cpp
- if ((titleBar->subControls & SC_TitleBarSysMenu) && (titleBar->titleBarFlags & Qt::WindowSystemMenuHint)) {
- bool hover = (titleBar->activeSubControls & SC_TitleBarSysMenu) && (titleBar->state & State_MouseOver);
- bool sunken = (titleBar->activeSubControls & SC_TitleBarSysMenu) && (titleBar->state & State_Sunken);
-
- QRect iconRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarSysMenu, widget);
- if (hover)
- qt_plastique_draw_mdibutton(painter, titleBar, iconRect, hover, sunken);
-
- if (!titleBar->icon.isNull()) {
- titleBar->icon.paint(painter, iconRect);
- } else {
- QStyleOption tool(0);
- tool.palette = titleBar->palette;
- QPixmap pm = standardPixmap(SP_TitleBarMenuButton, &tool, widget);
- tool.rect = iconRect;
- painter->save();
- proxy()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, pm);
- painter->restore();
- }
- }
- painter->restore();
- }
- break;
-#ifndef QT_NO_DIAL
- case CC_Dial:
- if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(option))
- QStyleHelper::drawDial(dial, painter);
- break;
-#endif // QT_NO_DIAL
- default:
- QWindowsStyle::drawComplexControl(control, option, painter, widget);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-QSize QPlastiqueStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const
-{
- QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget);
-
- switch (type) {
- case CT_RadioButton:
- ++newSize.rheight();
- ++newSize.rwidth();
- break;
-#ifndef QT_NO_SLIDER
- case CT_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
- if (slider->tickPosition & QSlider::TicksBelow) {
- if (slider->orientation == Qt::Horizontal)
- newSize.rheight() += tickSize;
- else
- newSize.rwidth() += tickSize;
- }
- if (slider->tickPosition & QSlider::TicksAbove) {
- if (slider->orientation == Qt::Horizontal)
- newSize.rheight() += tickSize;
- else
- newSize.rwidth() += tickSize;
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CT_ScrollBar:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int scrollBarExtent = proxy()->pixelMetric(PM_ScrollBarExtent, option, widget);
- int scrollBarSliderMinimum = proxy()->pixelMetric(PM_ScrollBarSliderMin, option, widget);
- if (scrollBar->orientation == Qt::Horizontal) {
- newSize = QSize(scrollBarExtent * 3 + scrollBarSliderMinimum, scrollBarExtent);
- } else {
- newSize = QSize(scrollBarExtent, scrollBarExtent * 3 + scrollBarSliderMinimum);
- }
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_SPINBOX
- case CT_SpinBox:
- // Make sure the size is odd
- newSize.setHeight(sizeFromContents(CT_LineEdit, option, size, widget).height());
- newSize.rheight() -= ((1 - newSize.rheight()) & 1);
- break;
-#endif
-#ifndef QT_NO_TOOLBUTTON
- case CT_ToolButton:
- newSize.rheight() += 3;
- newSize.rwidth() += 3;
- break;
-#endif
-#ifndef QT_NO_COMBOBOX
- case CT_ComboBox:
- newSize = sizeFromContents(CT_PushButton, option, size, widget);
- newSize.rwidth() += 30; // Make room for drop-down indicator
- newSize.rheight() += 4;
- break;
-#endif
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator)
- newSize.setHeight(menuItem->text.isEmpty() ? 2 : menuItem->fontMetrics.height());
- }
- break;
- case CT_MenuBarItem:
- newSize.setHeight(newSize.height());
- break;
- default:
- break;
- }
-
- return newSize;
-}
-
-/*!
- \reimp
-*/
-QRect QPlastiqueStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
-{
- QRect rect;
- switch (element) {
- case SE_RadioButtonIndicator:
- rect = visualRect(option->direction, option->rect,
- QWindowsStyle::subElementRect(element, option, widget)).adjusted(0, 0, 1, 1);
- break;
-#ifndef QT_NO_PROGRESSBAR
- case SE_ProgressBarLabel:
- case SE_ProgressBarContents:
- case SE_ProgressBarGroove:
- return option->rect;
-#endif // QT_NO_PROGRESSBAR
- default:
- return QWindowsStyle::subElementRect(element, option, widget);
- }
-
- return visualRect(option->direction, option->rect, rect);
-}
-
-/*!
- \reimp
-*/
-QRect QPlastiqueStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const
-{
- QRect rect = QWindowsStyle::subControlRect(control, option, subControl, widget);
-
- switch (control) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
-
- switch (subControl) {
- case SC_SliderHandle:
- if (slider->orientation == Qt::Horizontal) {
- rect.setWidth(11);
- rect.setHeight(15);
- int centerY = slider->rect.center().y() - rect.height() / 2;
- if (slider->tickPosition & QSlider::TicksAbove)
- centerY += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- centerY -= tickSize;
- rect.moveTop(centerY);
- } else {
- rect.setWidth(15);
- rect.setHeight(11);
- int centerX = slider->rect.center().x() - rect.width() / 2;
- if (slider->tickPosition & QSlider::TicksAbove)
- centerX += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- centerX -= tickSize;
- rect.moveLeft(centerX);
- }
- break;
- case SC_SliderGroove: {
- QPoint grooveCenter = slider->rect.center();
- if (slider->orientation == Qt::Horizontal) {
- rect.setHeight(14);
- --grooveCenter.ry();
- if (slider->tickPosition & QSlider::TicksAbove)
- grooveCenter.ry() += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- grooveCenter.ry() -= tickSize;
- } else {
- rect.setWidth(14);
- --grooveCenter.rx();
- if (slider->tickPosition & QSlider::TicksAbove)
- grooveCenter.rx() += tickSize;
- if (slider->tickPosition & QSlider::TicksBelow)
- grooveCenter.rx() -= tickSize;
- }
- rect.moveCenter(grooveCenter);
- break;
- }
- default:
- break;
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int scrollBarExtent = proxy()->pixelMetric(PM_ScrollBarExtent, scrollBar, widget);
- int sliderMaxLength = ((scrollBar->orientation == Qt::Horizontal) ?
- scrollBar->rect.width() : scrollBar->rect.height()) - (scrollBarExtent * 3);
- int sliderMinLength = proxy()->pixelMetric(PM_ScrollBarSliderMin, scrollBar, widget);
- int sliderLength;
-
- // calculate slider length
- if (scrollBar->maximum != scrollBar->minimum) {
- uint valueRange = scrollBar->maximum - scrollBar->minimum;
- sliderLength = (scrollBar->pageStep * sliderMaxLength) / (valueRange + scrollBar->pageStep);
-
- if (sliderLength < sliderMinLength || valueRange > INT_MAX / 2)
- sliderLength = sliderMinLength;
- if (sliderLength > sliderMaxLength)
- sliderLength = sliderMaxLength;
- } else {
- sliderLength = sliderMaxLength;
- }
-
- int sliderStart = scrollBarExtent + sliderPositionFromValue(scrollBar->minimum,
- scrollBar->maximum,
- scrollBar->sliderPosition,
- sliderMaxLength - sliderLength,
- scrollBar->upsideDown);
-
- QRect scrollBarRect = scrollBar->rect;
-
- switch (subControl) {
- case SC_ScrollBarSubLine: // top/left button
- if (scrollBar->orientation == Qt::Horizontal) {
- rect.setRect(scrollBarRect.left(), scrollBarRect.top(), scrollBarRect.width() - scrollBarExtent, scrollBarRect.height());
- } else {
- rect.setRect(scrollBarRect.left(), scrollBarRect.top(), scrollBarRect.width(), scrollBarRect.height() - scrollBarExtent);
- }
- break;
- case SC_ScrollBarAddLine: // bottom/right button
- if (scrollBar->orientation == Qt::Horizontal) {
- rect.setRect(scrollBarRect.right() - (scrollBarExtent - 1), scrollBarRect.top(), scrollBarExtent, scrollBarRect.height());
- } else {
- rect.setRect(scrollBarRect.left(), scrollBarRect.bottom() - (scrollBarExtent - 1), scrollBarRect.width(), scrollBarExtent);
- }
- break;
- case SC_ScrollBarSubPage:
- if (scrollBar->orientation == Qt::Horizontal) {
- rect.setRect(scrollBarRect.left() + scrollBarExtent, scrollBarRect.top(),
- sliderStart - (scrollBarRect.left() + scrollBarExtent), scrollBarRect.height());
- } else {
- rect.setRect(scrollBarRect.left(), scrollBarRect.top() + scrollBarExtent,
- scrollBarRect.width(), sliderStart - (scrollBarRect.left() + scrollBarExtent));
- }
- break;
- case SC_ScrollBarAddPage:
- if (scrollBar->orientation == Qt::Horizontal)
- rect.setRect(sliderStart + sliderLength, 0,
- sliderMaxLength - sliderStart - sliderLength + scrollBarExtent, scrollBarRect.height());
- else
- rect.setRect(0, sliderStart + sliderLength,
- scrollBarRect.width(), sliderMaxLength - sliderStart - sliderLength + scrollBarExtent);
- break;
- case SC_ScrollBarGroove:
- if (scrollBar->orientation == Qt::Horizontal) {
- rect = scrollBarRect.adjusted(scrollBarExtent, 0, -2 * scrollBarExtent, 0);
- } else {
- rect = scrollBarRect.adjusted(0, scrollBarExtent, 0, -2 * scrollBarExtent);
- }
- break;
- case SC_ScrollBarSlider:
- if (scrollBar->orientation == Qt::Horizontal) {
- rect.setRect(sliderStart, 0, sliderLength, scrollBarRect.height());
- } else {
- rect.setRect(0, sliderStart, scrollBarRect.width(), sliderLength);
- }
- break;
- default:
- break;
- }
- rect = visualRect(scrollBar->direction, scrollBarRect, rect);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- int center = spinBox->rect.height() / 2;
- switch (subControl) {
- case SC_SpinBoxUp:
- if (spinBox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- rect = visualRect(spinBox->direction, spinBox->rect, rect);
- rect.setRect(spinBox->rect.right() - 16, spinBox->rect.top(), 17, center + 1);
- rect = visualRect(spinBox->direction, spinBox->rect, rect);
- break;
- case SC_SpinBoxDown:
- if (spinBox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- rect = visualRect(spinBox->direction, spinBox->rect, rect);
- rect.setRect(spinBox->rect.right() - 16, spinBox->rect.top() + center, 17, spinBox->rect.height() - center);
- rect = visualRect(spinBox->direction, spinBox->rect, rect);
- break;
- case SC_SpinBoxEditField:
- if (spinBox->buttonSymbols != QAbstractSpinBox::NoButtons) {
- rect = spinBox->rect.adjusted(0, 0, -16, 0);
- } else {
- rect = spinBox->rect;
- }
- rect.adjust(blueFrameWidth, blueFrameWidth, -blueFrameWidth, -blueFrameWidth);
- rect = visualRect(spinBox->direction, spinBox->rect, rect);
- break;
- default:
- break;
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- switch (subControl) {
- case SC_ComboBoxArrow:
- rect = visualRect(option->direction, option->rect, rect);
- rect.setRect(rect.right() - 17, rect.top() - 2,
- 19, rect.height() + 4);
- rect = visualRect(option->direction, option->rect, rect);
- break;
- case SC_ComboBoxEditField: {
- if (const QStyleOptionComboBox *box = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int frameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth);
- rect = visualRect(option->direction, option->rect, rect);
-
- if (box->editable) {
- rect = box->rect.adjusted(blueFrameWidth, blueFrameWidth, -blueFrameWidth, -blueFrameWidth);
- rect.setRight(rect.right() - 16); // Overlaps the combobox button by 2 pixels
- } else {
- rect.setRect(option->rect.left() + frameWidth, option->rect.top() + frameWidth,
- option->rect.width() - 16 - 2 * frameWidth,
- option->rect.height() - 2 * frameWidth);
- rect.setLeft(rect.left() + 2);
- rect.setRight(rect.right() - 2);
- if (box->state & (State_Sunken | State_On))
- rect.translate(1, 1);
- }
- rect = visualRect(option->direction, option->rect, rect);
- }
- break;
- }
- default:
- break;
- }
- break;
-#endif // QT_NO_COMBOBOX
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- SubControl sc = subControl;
- QRect &ret = rect;
- const int indent = 3;
- const int controlTopMargin = 4;
- const int controlBottomMargin = 3;
- const int controlWidthMargin = 1;
- const int controlHeight = tb->rect.height() - controlTopMargin - controlBottomMargin;
- const int delta = controlHeight + controlWidthMargin;
- int offset = 0;
-
- bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
-
- switch (sc) {
- case SC_TitleBarLabel:
- if (tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)) {
- ret = tb->rect;
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- ret.adjust(delta, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowMinimizeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowMaximizeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowShadeButtonHint)
- ret.adjust(0, 0, -delta, 0);
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- ret.adjust(0, 0, -delta, 0);
- ret.adjusted(indent, 0, -indent, 0);
- }
- break;
- case SC_TitleBarContextHelpButton:
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- offset += delta;
- case SC_TitleBarMinButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarMinButton)
- break;
- case SC_TitleBarNormalButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarNormalButton)
- break;
- case SC_TitleBarMaxButton:
- if (!isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarMaxButton)
- break;
- case SC_TitleBarShadeButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarShadeButton)
- break;
- case SC_TitleBarUnshadeButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (sc == SC_TitleBarUnshadeButton)
- break;
- case SC_TitleBarCloseButton:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- offset += delta;
- else if (sc == SC_TitleBarCloseButton)
- break;
- ret.setRect(tb->rect.right() - indent - offset, tb->rect.top() + controlTopMargin,
- controlHeight, controlHeight);
- break;
- case SC_TitleBarSysMenu:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- ret.setRect(tb->rect.left() + controlWidthMargin + indent, tb->rect.top() + controlTopMargin,
- controlHeight, controlHeight);
- }
- break;
- default:
- break;
- }
- ret = visualRect(tb->direction, tb->rect, ret);
- }
- break;
- default:
- break;
- }
-
- return rect;
-}
-
-/*!
- \reimp
-*/
-int QPlastiqueStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget,
- QStyleHintReturn *returnData) const
-{
- int ret = 0;
- switch (hint) {
- case SH_WindowFrame_Mask:
- ret = 1;
- if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask *>(returnData)) {
- mask->region = option->rect;
- mask->region -= QRect(option->rect.left(), option->rect.top(), 2, 1);
- mask->region -= QRect(option->rect.right() - 1, option->rect.top(), 2, 1);
- mask->region -= QRect(option->rect.left(), option->rect.top() + 1, 1, 1);
- mask->region -= QRect(option->rect.right(), option->rect.top() + 1, 1, 1);
-
- const QStyleOptionTitleBar *titleBar = qstyleoption_cast<const QStyleOptionTitleBar *>(option);
- if (titleBar && (titleBar->titleBarState & Qt::WindowMinimized)) {
- mask->region -= QRect(option->rect.left(), option->rect.bottom(), 2, 1);
- mask->region -= QRect(option->rect.right() - 1, option->rect.bottom(), 2, 1);
- mask->region -= QRect(option->rect.left(), option->rect.bottom() - 1, 1, 1);
- mask->region -= QRect(option->rect.right(), option->rect.bottom() - 1, 1, 1);
- } else {
- mask->region -= QRect(option->rect.bottomLeft(), QSize(1, 1));
- mask->region -= QRect(option->rect.bottomRight(), QSize(1, 1));
- }
- }
- break;
- case SH_TitleBar_NoBorder:
- ret = 1;
- break;
- case SH_TitleBar_AutoRaise:
- ret = 1;
- break;
- case SH_ItemView_ShowDecorationSelected:
- ret = true;
- break;
- case SH_ToolBox_SelectedPageTitleBold:
- case SH_ScrollBar_MiddleClickAbsolutePosition:
- ret = true;
- break;
- case SH_MainWindow_SpaceBelowMenuBar:
- ret = 0;
- break;
- case SH_FormLayoutWrapPolicy:
- ret = QFormLayout::DontWrapRows;
- break;
- case SH_FormLayoutFieldGrowthPolicy:
- ret = QFormLayout::ExpandingFieldsGrow;
- break;
- case SH_FormLayoutFormAlignment:
- ret = Qt::AlignLeft | Qt::AlignTop;
- break;
- case SH_FormLayoutLabelAlignment:
- ret = Qt::AlignRight;
- break;
- case SH_MessageBox_TextInteractionFlags:
- ret = Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse;
- break;
- case SH_LineEdit_PasswordCharacter:
- ret = QCommonStyle::styleHint(hint, option, widget, returnData);
- break;
- case SH_ItemView_ArrowKeysNavigateIntoChildren:
- ret = true;
- break;
- case SH_Menu_SubMenuPopupDelay:
- ret = 96; // from Plastik
- break;
-#ifdef Q_WS_X11
- case SH_DialogButtonBox_ButtonsHaveIcons:
- ret = true;
- break;
-#endif
-#ifndef Q_OS_WIN
- case SH_Menu_AllowActiveAndDisabled:
- ret = false;
- break;
-#endif
- default:
- ret = QWindowsStyle::styleHint(hint, option, widget, returnData);
- break;
- }
- return ret;
-}
-
-/*!
- \reimp
-*/
-QStyle::SubControl QPlastiqueStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- const QPoint &pos, const QWidget *widget) const
-{
- SubControl ret = SC_None;
- switch (control) {
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- QRect slider = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSlider, widget);
- if (slider.contains(pos)) {
- ret = SC_ScrollBarSlider;
- break;
- }
-
- QRect scrollBarAddLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarAddLine, widget);
- if (scrollBarAddLine.contains(pos)) {
- ret = SC_ScrollBarAddLine;
- break;
- }
-
- QRect scrollBarSubPage = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSubPage, widget);
- if (scrollBarSubPage.contains(pos)) {
- ret = SC_ScrollBarSubPage;
- break;
- }
-
- QRect scrollBarAddPage = proxy()->subControlRect(control, scrollBar, SC_ScrollBarAddPage, widget);
- if (scrollBarAddPage.contains(pos)) {
- ret = SC_ScrollBarAddPage;
- break;
- }
-
- QRect scrollBarSubLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSubLine, widget);
- if (scrollBarSubLine.contains(pos)) {
- ret = SC_ScrollBarSubLine;
- break;
- }
- }
- break;
-#endif // QT_NO_SCROLLBAR
- default:
- break;
- }
-
- return ret != SC_None ? ret : QWindowsStyle::hitTestComplexControl(control, option, pos, widget);
-}
-
-/*!
- \reimp
-*/
-int QPlastiqueStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
-{
- int ret = -1;
- switch (metric) {
- case PM_MenuVMargin:
- case PM_MenuHMargin:
- ret = 0;
- break;
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- ret = 1;
- break;
- case PM_ButtonDefaultIndicator:
- ret = 0;
- break;
-#ifndef QT_NO_SLIDER
- case PM_SliderThickness:
- ret = 15;
- break;
- case PM_SliderLength:
- case PM_SliderControlThickness:
- ret = 11;
- break;
- case PM_SliderTickmarkOffset:
- ret = 5;
- break;
- case PM_SliderSpaceAvailable:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int size = 15;
- if (slider->tickPosition & QSlider::TicksBelow)
- ++size;
- if (slider->tickPosition & QSlider::TicksAbove)
- ++size;
- ret = size;
- break;
- }
-#endif // QT_NO_SLIDER
- case PM_ScrollBarExtent:
- ret = 16;
- break;
- case PM_ScrollBarSliderMin:
- ret = 26;
- break;
- case PM_ProgressBarChunkWidth:
- ret = 1;
- break;
- case PM_MenuBarItemSpacing:
- ret = 3;
- break;
- case PM_MenuBarVMargin:
- ret = 2;
- break;
- case PM_MenuBarHMargin:
- ret = 0;
- break;
- case PM_MenuBarPanelWidth:
- ret = 1;
- break;
- case PM_ToolBarHandleExtent:
- ret = 9;
- break;
- case PM_ToolBarSeparatorExtent:
- ret = 2;
- break;
- case PM_ToolBarItemSpacing:
- ret = 1;
- break;
- case PM_ToolBarItemMargin:
- ret = 1;
- break;
- case PM_ToolBarFrameWidth:
- ret = 2;
- break;
- case PM_SplitterWidth:
- ret = 6;
- break;
- case PM_DockWidgetSeparatorExtent:
- ret = 6;
- break;
- case PM_DockWidgetHandleExtent:
- ret = 20;
- break;
- case PM_DefaultFrameWidth:
-#ifndef QT_NO_MENU
- if (qobject_cast<const QMenu *>(widget)) {
- ret = 1;
- break;
- }
-#endif
- ret = 2;
- break;
- case PM_MdiSubWindowFrameWidth:
- ret = 4;
- break;
- case PM_TitleBarHeight:
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- // Q3DockWindow has smaller title bars than QDockWidget
- ret = qMax(widget->fontMetrics().height(), 20);
- } else
-#endif
- ret = qMax(widget ? widget->fontMetrics().height() :
- (option ? option->fontMetrics.height() : 0), 30);
- break;
- case PM_MaximumDragDistance:
- return -1;
- case PM_DockWidgetTitleMargin:
- return 2;
- case PM_LayoutHorizontalSpacing:
- case PM_LayoutVerticalSpacing:
- return -1; // rely on layoutHorizontalSpacing()
- case PM_LayoutLeftMargin:
- case PM_LayoutTopMargin:
- case PM_LayoutRightMargin:
- case PM_LayoutBottomMargin:
- {
- bool isWindow = false;
- if (option) {
- isWindow = (option->state & State_Window);
- } else if (widget) {
- isWindow = widget->isWindow();
- }
-
- if (isWindow) {
- ret = 11;
- } else {
- ret = 9;
- }
- }
- default:
- break;
- }
-
- return ret != -1 ? ret : QWindowsStyle::pixelMetric(metric, option, widget);
-}
-
-/*!
- \reimp
-*/
-QPalette QPlastiqueStyle::standardPalette() const
-{
- QPalette palette;
-
- palette.setBrush(QPalette::Disabled, QPalette::WindowText, QColor(QRgb(0xff808080)));
- palette.setBrush(QPalette::Disabled, QPalette::Button, QColor(QRgb(0xffdddfe4)));
- palette.setBrush(QPalette::Disabled, QPalette::Light, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Disabled, QPalette::Midlight, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Disabled, QPalette::Dark, QColor(QRgb(0xff555555)));
- palette.setBrush(QPalette::Disabled, QPalette::Mid, QColor(QRgb(0xffc7c7c7)));
- palette.setBrush(QPalette::Disabled, QPalette::Text, QColor(QRgb(0xffc7c7c7)));
- palette.setBrush(QPalette::Disabled, QPalette::BrightText, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Disabled, QPalette::ButtonText, QColor(QRgb(0xff808080)));
- palette.setBrush(QPalette::Disabled, QPalette::Base, QColor(QRgb(0xffefefef)));
- palette.setBrush(QPalette::Disabled, QPalette::AlternateBase, palette.color(QPalette::Disabled, QPalette::Base).darker(110));
- palette.setBrush(QPalette::Disabled, QPalette::Window, QColor(QRgb(0xffefefef)));
- palette.setBrush(QPalette::Disabled, QPalette::Shadow, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Disabled, QPalette::Highlight, QColor(QRgb(0xff567594)));
- palette.setBrush(QPalette::Disabled, QPalette::HighlightedText, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Disabled, QPalette::Link, QColor(QRgb(0xff0000ee)));
- palette.setBrush(QPalette::Disabled, QPalette::LinkVisited, QColor(QRgb(0xff52188b)));
- palette.setBrush(QPalette::Active, QPalette::WindowText, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Active, QPalette::Button, QColor(QRgb(0xffdddfe4)));
- palette.setBrush(QPalette::Active, QPalette::Light, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Active, QPalette::Midlight, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Active, QPalette::Dark, QColor(QRgb(0xff555555)));
- palette.setBrush(QPalette::Active, QPalette::Mid, QColor(QRgb(0xffc7c7c7)));
- palette.setBrush(QPalette::Active, QPalette::Text, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Active, QPalette::BrightText, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Active, QPalette::ButtonText, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Active, QPalette::Base, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Active, QPalette::AlternateBase, palette.color(QPalette::Active, QPalette::Base).darker(110));
- palette.setBrush(QPalette::Active, QPalette::Window, QColor(QRgb(0xffefefef)));
- palette.setBrush(QPalette::Active, QPalette::Shadow, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Active, QPalette::Highlight, QColor(QRgb(0xff678db2)));
- palette.setBrush(QPalette::Active, QPalette::HighlightedText, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Active, QPalette::Link, QColor(QRgb(0xff0000ee)));
- palette.setBrush(QPalette::Active, QPalette::LinkVisited, QColor(QRgb(0xff52188b)));
- palette.setBrush(QPalette::Inactive, QPalette::WindowText, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Inactive, QPalette::Button, QColor(QRgb(0xffdddfe4)));
- palette.setBrush(QPalette::Inactive, QPalette::Light, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Inactive, QPalette::Midlight, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Inactive, QPalette::Dark, QColor(QRgb(0xff555555)));
- palette.setBrush(QPalette::Inactive, QPalette::Mid, QColor(QRgb(0xffc7c7c7)));
- palette.setBrush(QPalette::Inactive, QPalette::Text, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Inactive, QPalette::BrightText, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Inactive, QPalette::ButtonText, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Inactive, QPalette::Base, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Inactive, QPalette::AlternateBase, palette.color(QPalette::Inactive, QPalette::Base).darker(110));
- palette.setBrush(QPalette::Inactive, QPalette::Window, QColor(QRgb(0xffefefef)));
- palette.setBrush(QPalette::Inactive, QPalette::Shadow, QColor(QRgb(0xff000000)));
- palette.setBrush(QPalette::Inactive, QPalette::Highlight, QColor(QRgb(0xff678db2)));
- palette.setBrush(QPalette::Inactive, QPalette::HighlightedText, QColor(QRgb(0xffffffff)));
- palette.setBrush(QPalette::Inactive, QPalette::Link, QColor(QRgb(0xff0000ee)));
- palette.setBrush(QPalette::Inactive, QPalette::LinkVisited, QColor(QRgb(0xff52188b)));
- return palette;
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::polish(QWidget *widget)
-{
- if (qobject_cast<QPushButton *>(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<QComboBox *>(widget)
-#endif
-#ifndef QT_NO_SPINBOX
- || qobject_cast<QAbstractSpinBox *>(widget)
-#endif
- || qobject_cast<QCheckBox *>(widget)
-#ifndef QT_NO_GROUPBOX
- || qobject_cast<QGroupBox *>(widget)
-#endif
- || qobject_cast<QRadioButton *>(widget)
-#ifndef QT_NO_SPLITTER
- || qobject_cast<QSplitterHandle *>(widget)
-#endif
-#ifndef QT_NO_TABBAR
- || qobject_cast<QTabBar *>(widget)
-#endif
- ) {
- widget->setAttribute(Qt::WA_Hover);
- }
-
- if (widget->inherits("QWorkspaceTitleBar")
- || widget->inherits("QDockSeparator")
- || widget->inherits("QDockWidgetSeparator")
- || widget->inherits("Q3DockWindowResizeHandle")) {
- widget->setAttribute(Qt::WA_Hover);
- }
-
- if (false // to simplify the #ifdefs
-#ifndef QT_NO_MENUBAR
- || qobject_cast<QMenuBar *>(widget)
-#endif
-#ifdef QT3_SUPPORT
- || widget->inherits("Q3ToolBar")
-#endif
-#ifndef QT_NO_TOOLBAR
- || qobject_cast<QToolBar *>(widget)
- || (widget && qobject_cast<QToolBar *>(widget->parent()))
-#endif
- ) {
- widget->setBackgroundRole(QPalette::Window);
- }
-
-#ifndef QT_NO_PROGRESSBAR
- if (AnimateBusyProgressBar && qobject_cast<QProgressBar *>(widget))
- widget->installEventFilter(this);
-#endif
-
-#if defined QPlastique_MaskButtons
- if (qobject_cast<QPushButton *>(widget) || qobject_cast<QToolButton *>(widget))
- widget->installEventFilter(this);
-#endif
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::unpolish(QWidget *widget)
-{
- if (qobject_cast<QPushButton *>(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<QComboBox *>(widget)
-#endif
-#ifndef QT_NO_SPINBOX
- || qobject_cast<QAbstractSpinBox *>(widget)
-#endif
- || qobject_cast<QCheckBox *>(widget)
-#ifndef QT_NO_GROUPBOX
- || qobject_cast<QGroupBox *>(widget)
-#endif
-#ifndef QT_NO_SPLITTER
- || qobject_cast<QSplitterHandle *>(widget)
-#endif
-#ifndef QT_NO_TABBAR
- || qobject_cast<QTabBar *>(widget)
-#endif
- || qobject_cast<QRadioButton *>(widget)) {
- widget->setAttribute(Qt::WA_Hover, false);
- }
-
- if (widget->inherits("QWorkspaceTitleBar")
- || widget->inherits("QDockSeparator")
- || widget->inherits("QDockWidgetSeparator")
- || widget->inherits("Q3DockWindowResizeHandle")) {
- widget->setAttribute(Qt::WA_Hover, false);
- }
-
- if (false // to simplify the #ifdefs
-#ifndef QT_NO_MENUBAR
- || qobject_cast<QMenuBar *>(widget)
-#endif
-#ifndef QT_NO_TOOLBOX
- || qobject_cast<QToolBox *>(widget)
-#endif
-#ifdef QT3_SUPPORT
- || widget->inherits("Q3ToolBar")
-#endif
-#ifndef QT_NO_TOOLBAR
- || qobject_cast<QToolBar *>(widget)
- || (widget && qobject_cast<QToolBar *>(widget->parent()))
-#endif
- ) {
- widget->setBackgroundRole(QPalette::Button);
- }
-
-#ifndef QT_NO_PROGRESSBAR
- if (AnimateBusyProgressBar && qobject_cast<QProgressBar *>(widget)) {
- Q_D(QPlastiqueStyle);
- widget->removeEventFilter(this);
- d->bars.removeAll(static_cast<QProgressBar*>(widget));
- }
-#endif
-
-#if defined QPlastique_MaskButtons
- if (qobject_cast<QPushButton *>(widget) || qobject_cast<QToolButton *>(widget))
- widget->removeEventFilter(this);
-#endif
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::polish(QApplication *app)
-{
- QWindowsStyle::polish(app);
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::polish(QPalette &pal)
-{
- QWindowsStyle::polish(pal);
-#ifdef Q_WS_MAC
- pal.setBrush(QPalette::Shadow, Qt::black);
-#endif
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::unpolish(QApplication *app)
-{
- QWindowsStyle::unpolish(app);
-}
-
-/*!
- \internal
-*/
-QIcon QPlastiqueStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
-{
- return QWindowsStyle::standardIconImplementation(standardIcon, option, widget);
-}
-
-/*!
- \reimp
-*/
-QPixmap QPlastiqueStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget) const
-{
- return QWindowsStyle::standardPixmap(standardPixmap, opt, widget);
-}
-
-// this works as long as we have at most 16 different control types
-#define CT1(c) CT2(c, c)
-#define CT2(c1, c2) (((uint)c1 << 16) | (uint)c2)
-
-/*!
- \internal
-*/
-int QPlastiqueStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption * /* option */,
- const QWidget * /* widget */) const
-{
- const int ButtonMask = QSizePolicy::ButtonBox | QSizePolicy::PushButton;
-
- if (control2 == QSizePolicy::ButtonBox)
- return 11;
-
- if ((control1 | control2) & ButtonMask)
- return (orientation == Qt::Horizontal) ? 10 : 9;
-
- switch (CT2(control1, control2)) {
- case CT1(QSizePolicy::Label):
- case CT2(QSizePolicy::Label, QSizePolicy::DefaultType):
- case CT2(QSizePolicy::Label, QSizePolicy::CheckBox):
- case CT2(QSizePolicy::Label, QSizePolicy::ComboBox):
- case CT2(QSizePolicy::Label, QSizePolicy::LineEdit):
- case CT2(QSizePolicy::Label, QSizePolicy::RadioButton):
- case CT2(QSizePolicy::Label, QSizePolicy::Slider):
- case CT2(QSizePolicy::Label, QSizePolicy::SpinBox):
- case CT2(QSizePolicy::Label, QSizePolicy::ToolButton):
- return 5;
- case CT2(QSizePolicy::CheckBox, QSizePolicy::RadioButton):
- case CT2(QSizePolicy::RadioButton, QSizePolicy::CheckBox):
- case CT1(QSizePolicy::CheckBox):
- if (orientation == Qt::Vertical)
- return 2;
- case CT1(QSizePolicy::RadioButton):
- if (orientation == Qt::Vertical)
- return 1;
- }
-
- if (orientation == Qt::Horizontal
- && (control2 & (QSizePolicy::CheckBox | QSizePolicy::RadioButton)))
- return 8;
-
- if ((control1 | control2) & (QSizePolicy::Frame
- | QSizePolicy::GroupBox
- | QSizePolicy::TabWidget)) {
- return 11;
- }
-
- if ((control1 | control2) & (QSizePolicy::Line | QSizePolicy::Slider
- | QSizePolicy::LineEdit | QSizePolicy::ComboBox
- | QSizePolicy::SpinBox))
- return 7;
-
- return 6;
-}
-
-/*!
- \reimp
-*/
-bool QPlastiqueStyle::eventFilter(QObject *watched, QEvent *event)
-{
-#ifndef QT_NO_PROGRESSBAR
- Q_D(QPlastiqueStyle);
-
- switch (event->type()) {
- case QEvent::Show:
- if (QProgressBar *bar = qobject_cast<QProgressBar *>(watched)) {
- d->bars.append(bar);
- if (d->bars.size() == 1) {
- Q_ASSERT(ProgressBarFps > 0);
- d->timer.start();
- d->progressBarAnimateTimer = startTimer(1000 / ProgressBarFps);
- }
- }
- break;
- case QEvent::Destroy:
- case QEvent::Hide:
- if(!d->bars.isEmpty()) {
- d->bars.removeAll(reinterpret_cast<QProgressBar*>(watched));
- if (d->bars.isEmpty()) {
- killTimer(d->progressBarAnimateTimer);
- d->progressBarAnimateTimer = 0;
- }
- }
- break;
-#if defined QPlastique_MaskButtons
- case QEvent::Resize:
- if (qobject_cast<QPushButton *>(watched) || qobject_cast<QToolButton *>(watched)) {
- QWidget *widget = qobject_cast<QWidget *>(watched);
- QRect rect = widget->rect();
- QRegion region(rect);
- region -= QRect(rect.left(), rect.top(), 2, 1);
- region -= QRect(rect.left(), rect.top() + 1, 1, 1);
- region -= QRect(rect.left(), rect.bottom(), 2, 1);
- region -= QRect(rect.left(), rect.bottom() - 1, 1, 1);
- region -= QRect(rect.right() - 1, rect.top(), 2, 1);
- region -= QRect(rect.right(), rect.top() + 1, 1, 1);
- region -= QRect(rect.right() - 1, rect.bottom(), 2, 1);
- region -= QRect(rect.right(), rect.bottom() - 1, 1, 1);
- widget->setMask(region);
- }
- break;
-#endif
- default:
- break;
- }
-#endif // QT_NO_PROGRESSBAR
-
- return QWindowsStyle::eventFilter(watched, event);
-}
-
-/*!
- \reimp
-*/
-void QPlastiqueStyle::timerEvent(QTimerEvent *event)
-{
-#ifndef QT_NO_PROGRESSBAR
- Q_D(QPlastiqueStyle);
-
- if (event->timerId() == d->progressBarAnimateTimer) {
- Q_ASSERT(ProgressBarFps > 0);
- d->animateStep = d->timer.elapsed() / (1000 / ProgressBarFps);
- foreach (QProgressBar *bar, d->bars) {
- if (AnimateProgressBar || (bar->minimum() == 0 && bar->maximum() == 0))
- bar->update();
- }
- }
-#endif // QT_NO_PROGRESSBAR
- event->ignore();
-}
-
-QT_END_NAMESPACE
-
-#endif // !defined(QT_NO_STYLE_PLASTIQUE) || defined(QT_PLUGIN)
diff --git a/src/gui/styles/qplastiquestyle.h b/src/gui/styles/qplastiquestyle.h
deleted file mode 100644
index 20d2f490a6..0000000000
--- a/src/gui/styles/qplastiquestyle.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** 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 QPLASTIQUESTYLE_H
-#define QPLASTIQUESTYLE_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_PLASTIQUE)
-
-class QPlastiqueStylePrivate;
-class Q_GUI_EXPORT QPlastiqueStyle : public QWindowsStyle
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPlastiqueStyle)
-public:
- QPlastiqueStyle();
- ~QPlastiqueStyle();
-
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget = 0) const;
- void drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const;
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const;
- QSize sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const;
-
- QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const;
-
- int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
- SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- const QPoint &pos, const QWidget *widget = 0) const;
-
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
-
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const;
-
- void polish(QWidget *widget);
- void polish(QApplication *app);
- void polish(QPalette &pal);
- void unpolish(QWidget *widget);
- void unpolish(QApplication *app);
-
- QPalette standardPalette() const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
- int layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
-
-protected:
- bool eventFilter(QObject *watched, QEvent *event);
- void timerEvent(QTimerEvent *event);
-
-private:
- Q_DISABLE_COPY(QPlastiqueStyle)
- void *reserved;
-};
-
-#endif // QT_NO_STYLE_PLASTIQUE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPLASTIQUESTYLE_H
diff --git a/src/gui/styles/qproxystyle.cpp b/src/gui/styles/qproxystyle.cpp
deleted file mode 100644
index 516d17fa69..0000000000
--- a/src/gui/styles/qproxystyle.cpp
+++ /dev/null
@@ -1,420 +0,0 @@
-/****************************************************************************
-**
-** 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 <qstyle.h>
-#include <private/qproxystyle_p.h>
-#include <private/qapplication_p.h>
-#include "qproxystyle.h"
-#include "qstylefactory.h"
-#include <private/qstyle_p.h>
-
-#if !defined(QT_NO_STYLE_PROXY) || defined(QT_PLUGIN)
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QProxyStyle
-
- \brief The QProxyStyle class is a convenience class that simplifies
- dynamically overriding QStyle elements.
-
- \since 4.6
-
- A QProxyStyle wraps a QStyle (usually the default system style) for the
- purpose of dynamically overriding painting or other specific style behavior.
-
- The following example shows how to override the shortcut underline
- behavior on any platform:
-
- \snippet doc/src/snippets/code/src_gui_qproxystyle.cpp 1
-
- Warning: The \l {QCommonStyle} {common styles} provided by Qt will
- respect this hint, because they call QStyle::proxy(), but there is
- no guarantee that QStyle::proxy() will be called for user defined
- or system controlled styles. It would not work on a Mac, for
- example, where menus are handled by the operating system.
-
- \sa QStyle
-*/
-
-void QProxyStylePrivate::ensureBaseStyle() const
-{
- Q_Q(const QProxyStyle);
-
- if (baseStyle)
- return;
-
- if (!baseStyle && !QApplicationPrivate::styleOverride.isEmpty()) {
- baseStyle = QStyleFactory::create(QApplicationPrivate::styleOverride);
- if (baseStyle) {
- // If baseStyle is an instance of the same proxyStyle
- // we destroy it and fall back to the desktop style
- if (qstrcmp(baseStyle->metaObject()->className(),
- q->metaObject()->className()) == 0) {
- delete baseStyle;
- baseStyle = 0;
- }
- }
- }
-
- if (!baseStyle) // Use application desktop style
- baseStyle = QStyleFactory::create(QApplicationPrivate::desktopStyleKey());
-
- if (!baseStyle) // Fallback to windows style
- baseStyle = QStyleFactory::create(QLatin1String("windows"));
-
- baseStyle->setProxy(const_cast<QProxyStyle*>(q));
- baseStyle->setParent(const_cast<QProxyStyle*>(q)); // Take ownership
-}
-
-/*!
- Constructs a QProxyStyle object for overriding behavior in \a style
- or in the current application \l{QStyle}{style} if \a style is 0
- (default). Normally \a style is 0, because you want to override
- behavior in the system style.
-
- Ownership of \a style is transferred to QProxyStyle.
-*/
-QProxyStyle::QProxyStyle(QStyle *style) :
- QCommonStyle(*new QProxyStylePrivate())
-{
- Q_D(QProxyStyle);
- if (style) {
- style->setProxy(this);
- style->setParent(this); // Take ownership
- d->baseStyle = style;
- }
-}
-
-/*!
- Destroys the QProxyStyle object.
-*/
-QProxyStyle::~QProxyStyle()
-{
-}
-
-/*!
- Returns the proxy base style object. If no base style
- is set on the proxy style, QProxyStyle will create
- an instance of the application style instead.
-
- \sa setBaseStyle(), QStyle
-*/
-QStyle *QProxyStyle::baseStyle() const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle;
-}
-
-/*!
- Sets the base style that should be proxied.
-
- Ownership of \a style is transferred to QProxyStyle.
-
- If style is zero, a desktop-dependant style will be
- assigned automatically.
-*/
-void QProxyStyle::setBaseStyle(QStyle *style)
-{
- Q_D (QProxyStyle);
-
- if (d->baseStyle && d->baseStyle->parent() == this)
- d->baseStyle->deleteLater();
-
- d->baseStyle = style;
-
- if (d->baseStyle) {
- d->baseStyle->setProxy(this);
- d->baseStyle->setParent(this);
- }
-}
-
-/*! \reimp
- */
-void QProxyStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->drawPrimitive(element, option, painter, widget);
-}
-
-/*!
- \reimp
- */
-void QProxyStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->drawControl(element, option, painter, widget);
-}
-
-/*! \reimp
- */
-void QProxyStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->drawComplexControl(control, option, painter, widget);
-}
-
-/*! \reimp
- */
-void QProxyStyle::drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->drawItemText(painter, rect, flags, pal, enabled, text, textRole);
-}
-
-/*! \reimp
- */
-void QProxyStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->drawItemPixmap(painter, rect, alignment, pixmap);
-}
-
-/*! \reimp
- */
-QSize QProxyStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->sizeFromContents(type, option, size, widget);
-}
-
-/*! \reimp
- */
-QRect QProxyStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->subElementRect(element, option, widget);
-}
-
-/*! \reimp
- */
-QRect QProxyStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *option, SubControl sc, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->subControlRect(cc, option, sc, widget);
-}
-
-/*! \reimp
- */
-QRect QProxyStyle::itemTextRect(const QFontMetrics &fm, const QRect &r, int flags, bool enabled, const QString &text) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->itemTextRect(fm, r, flags, enabled, text);
-}
-
-/*! \reimp
- */
-QRect QProxyStyle::itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->itemPixmapRect(r, flags, pixmap);
-}
-
-/*! \reimp
- */
-QStyle::SubControl QProxyStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->hitTestComplexControl(control, option, pos, widget);
-}
-
-/*! \reimp
- */
-int QProxyStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->styleHint(hint, option, widget, returnData);
-}
-
-/*! \reimp
- */
-int QProxyStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->pixelMetric(metric, option, widget);
-}
-
-/*! \reimp
- */
-QPixmap QProxyStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->standardPixmap(standardPixmap, opt, widget);
-}
-
-/*! \reimp
- */
-QPixmap QProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->generatedIconPixmap(iconMode, pixmap, opt);
-}
-
-/*! \reimp
- */
-QPalette QProxyStyle::standardPalette() const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->standardPalette();
-}
-
-/*! \reimp
- */
-void QProxyStyle::polish(QWidget *widget)
-{
- Q_D (QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->polish(widget);
-}
-
-/*! \reimp
- */
-void QProxyStyle::polish(QPalette &pal)
-{
- Q_D (QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->polish(pal);
-}
-
-/*! \reimp
- */
-void QProxyStyle::polish(QApplication *app)
-{
- Q_D (QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->polish(app);
-}
-
-/*! \reimp
- */
-void QProxyStyle::unpolish(QWidget *widget)
-{
- Q_D (QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->unpolish(widget);
-}
-
-/*! \reimp
- */
-void QProxyStyle::unpolish(QApplication *app)
-{
- Q_D (QProxyStyle);
- d->ensureBaseStyle();
- d->baseStyle->unpolish(app);
-}
-
-/*! \reimp
- */
-bool QProxyStyle::event(QEvent *e)
-{
- Q_D (QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->event(e);
-}
-
-/*!
- Returns an icon for the given \a standardIcon.
-
- Reimplement this slot to provide your own icons in a QStyle
- subclass. The \a option argument can be used to pass extra
- information required to find the appropriate icon. The \a widget
- argument is optional and can also be used to help find the icon.
-
- \note Because of binary compatibility constraints, standardIcon()
- introduced in Qt 4.1 is not virtual. Therefore it must dynamically
- detect and call \e this slot. This default implementation simply
- calls standardIcon() with the given parameters.
-
- \sa standardIcon()
- */
-QIcon QProxyStyle::standardIconImplementation(StandardPixmap standardIcon,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->standardIcon(standardIcon, option, widget);
-}
-
-/*!
- This slot is called by layoutSpacing() to determine the spacing that
- should be used between \a control1 and \a control2 in a layout. \a
- orientation specifies whether the controls are laid out side by side
- or stacked vertically. The \a option parameter can be used to pass
- extra information about the parent widget. The \a widget parameter
- is optional and can also be used if \a option is 0.
-
- The default implementation returns -1.
-
- \sa layoutSpacing(), combinedLayoutSpacing()
- */
-int QProxyStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- Q_D (const QProxyStyle);
- d->ensureBaseStyle();
- return d->baseStyle->layoutSpacing(control1, control2, orientation, option, widget);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_PROXY
diff --git a/src/gui/styles/qproxystyle.h b/src/gui/styles/qproxystyle.h
deleted file mode 100644
index 9d4a5cc56c..0000000000
--- a/src/gui/styles/qproxystyle.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/****************************************************************************
-**
-** 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 QPROXYSTYLE_H
-#define QPROXYSTYLE_H
-
-#include <QtGui/QCommonStyle>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_PROXY)
-
-class QProxyStylePrivate;
-class Q_GUI_EXPORT QProxyStyle : public QCommonStyle
-{
- Q_OBJECT
-
-public:
- QProxyStyle(QStyle *baseStyle = 0);
- ~QProxyStyle();
-
- QStyle *baseStyle() const;
- void setBaseStyle(QStyle *style);
-
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const;
- void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const;
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = 0) const;
- void drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const;
- virtual void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const;
-
- QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const;
-
- QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc, const QWidget *widget) const;
- QRect itemTextRect(const QFontMetrics &fm, const QRect &r, int flags, bool enabled, const QString &text) const;
- QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const;
-
- SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget = 0) const;
- int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
-
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget = 0) const;
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const;
- QPalette standardPalette() const;
-
- void polish(QWidget *widget);
- void polish(QPalette &pal);
- void polish(QApplication *app);
-
- void unpolish(QWidget *widget);
- void unpolish(QApplication *app);
-
-protected:
- bool event(QEvent *e);
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const;
- int layoutSpacingImplementation(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option = 0, const QWidget *widget = 0) const;
-private:
- Q_DISABLE_COPY(QProxyStyle)
- Q_DECLARE_PRIVATE(QProxyStyle)
-};
-
-#endif // QT_NO_STYLE_PROXY
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPROXYSTYLE_H
diff --git a/src/gui/styles/qproxystyle_p.h b/src/gui/styles/qproxystyle_p.h
deleted file mode 100644
index 8c330d0330..0000000000
--- a/src/gui/styles/qproxystyle_p.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** 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 QPROXYSTYLE_P_H
-#define QPROXYSTYLE_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qcommonstyle.h"
-#include "qcommonstyle_p.h"
-#include "qproxystyle.h"
-
-#ifndef QT_NO_STYLE_PROXY
-
-QT_BEGIN_NAMESPACE
-
-class QProxyStylePrivate : public QCommonStylePrivate
-{
- Q_DECLARE_PUBLIC(QProxyStyle)
-public:
- void ensureBaseStyle() const;
-private:
- QProxyStylePrivate() :
- QCommonStylePrivate(), baseStyle(0) {}
- mutable QPointer <QStyle> baseStyle;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_PROXY
-
-#endif //QPROXYSTYLE_P_H
diff --git a/src/gui/styles/qs60style.cpp b/src/gui/styles/qs60style.cpp
deleted file mode 100644
index fa6eeb7b36..0000000000
--- a/src/gui/styles/qs60style.cpp
+++ /dev/null
@@ -1,3618 +0,0 @@
-/****************************************************************************
-**
-** 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 "qs60style_p.h"
-
-#include "qapplication.h"
-#include "qpainter.h"
-#include "qstyleoption.h"
-#include "qevent.h"
-#include "qpixmapcache.h"
-
-#include "qcalendarwidget.h"
-#include "qdial.h"
-#include "qdialog.h"
-#include "qmessagebox.h"
-#include "qgroupbox.h"
-#include "qheaderview.h"
-#include "qlist.h"
-#include "qlistwidget.h"
-#include "qlistview.h"
-#include "qmenu.h"
-#include "qmenubar.h"
-#include "qpushbutton.h"
-#include "qscrollarea.h"
-#include "qscrollbar.h"
-#include "qtabbar.h"
-#include "qtableview.h"
-#include "qtextedit.h"
-#include "qtoolbar.h"
-#include "qtoolbutton.h"
-#include "qfocusframe.h"
-#include "qformlayout.h"
-#include "qradiobutton.h"
-#include "qcheckbox.h"
-#include "qdesktopwidget.h"
-#include "qprogressbar.h"
-#include "qlabel.h"
-
-#include "private/qtoolbarextension_p.h"
-#include "private/qcombobox_p.h"
-#include "private/qwidget_p.h"
-#include "private/qapplication_p.h"
-#include "private/qfont_p.h"
-
-#if !defined(QT_NO_STYLE_S60) || defined(QT_PLUGIN)
-
-QT_BEGIN_NAMESPACE
-
-const QS60StylePrivate::SkinElementFlags QS60StylePrivate::KDefaultSkinElementFlags =
- SkinElementFlags(SF_PointNorth | SF_StateEnabled);
-
-static const qreal goldenRatio = 1.618;
-
-const layoutHeader QS60StylePrivate::m_layoutHeaders[] = {
-// *** generated layout data ***
-{240,320,1,19,"QVGA Landscape"},
-{320,240,1,19,"QVGA Portrait"},
-{360,640,1,19,"NHD Landscape"},
-{640,360,1,19,"NHD Portrait"},
-{352,800,1,12,"E90 Landscape"},
-{480,640,1,19,"VGA Landscape"}
-// *** End of generated data ***
-};
-const int QS60StylePrivate::m_numberOfLayouts =
- (int)sizeof(QS60StylePrivate::m_layoutHeaders)/sizeof(QS60StylePrivate::m_layoutHeaders[0]);
-
-const short QS60StylePrivate::data[][MAX_PIXELMETRICS] = {
-// *** generated pixel metrics ***
-{5,0,-909,0,0,2,0,2,-1,7,12,22,15,15,7,198,-909,-909,-909,20,13,2,0,0,21,7,18,30,3,3,1,-909,-909,0,1,0,0,12,20,15,15,18,18,1,115,18,0,-909,-909,-909,-909,0,0,16,2,-909,0,0,-909,16,-909,-909,-909,-909,32,18,55,24,55,4,4,4,9,13,-909,5,51,11,5,0,3,3,6,8,3,3,-909,2,-909,-909,-909,-909,5,5,3,1,106},
-{5,0,-909,0,0,1,0,2,-1,8,14,22,15,15,7,164,-909,-909,-909,19,15,2,0,0,21,8,27,28,4,4,1,-909,-909,0,7,6,0,13,23,17,17,21,21,7,115,21,0,-909,-909,-909,-909,0,0,15,1,-909,0,0,-909,15,-909,-909,-909,-909,32,21,65,27,65,3,3,5,10,15,-909,5,58,13,5,0,4,4,7,9,4,4,-909,2,-909,-909,-909,-909,6,6,3,1,106},
-{7,0,-909,0,0,2,0,5,-1,25,69,46,37,37,9,258,-909,-909,-909,23,19,11,0,0,32,25,72,44,5,5,2,-909,-909,0,7,21,0,17,29,22,22,27,27,7,173,29,0,-909,-909,-909,-909,0,0,25,2,-909,0,0,-909,25,-909,-909,-909,-909,87,27,77,35,77,13,3,6,8,19,-909,7,74,19,7,0,5,5,8,12,5,5,-909,3,-909,-909,-909,-909,7,7,3,1,135},
-{7,0,-909,0,0,2,0,5,-1,25,68,46,37,37,9,258,-909,-909,-909,31,19,13,0,0,32,25,60,52,5,5,2,-909,-909,0,7,32,0,17,29,22,22,27,27,7,173,29,0,-909,-909,-909,-909,0,0,26,2,-909,0,0,-909,26,-909,-909,-909,-909,87,27,96,35,96,12,3,6,8,19,-909,7,74,22,7,0,5,5,8,12,5,5,-909,3,-909,-909,-909,-909,7,7,3,1,135},
-{7,0,-909,0,0,2,0,2,-1,10,20,27,18,18,9,301,-909,-909,-909,29,18,5,0,0,35,7,32,30,5,5,2,-909,-909,0,2,8,0,16,28,21,21,26,26,2,170,26,0,-909,-909,-909,-909,0,0,21,6,-909,0,0,-909,-909,-909,-909,-909,-909,54,26,265,34,265,5,5,6,3,18,-909,7,72,19,7,0,5,6,8,11,6,5,-909,2,-909,-909,-909,-909,5,5,3,1,106},
-{9,0,-909,0,0,2,0,5,-1,34,99,76,51,51,25,352,-909,-909,-909,29,25,7,0,0,43,34,42,76,7,7,2,-909,-909,0,9,14,0,23,39,30,30,37,37,9,391,40,0,-909,-909,-909,-909,0,0,29,2,-909,0,0,-909,29,-909,-909,-909,-909,115,37,96,48,96,19,19,9,1,25,-909,9,101,24,9,0,7,7,7,16,7,7,-909,3,-909,-909,-909,-909,9,9,3,1,184}
-// *** End of generated data ***
-};
-
-const short *QS60StylePrivate::m_pmPointer = QS60StylePrivate::data[0];
-
-// theme background texture
-QPixmap *QS60StylePrivate::m_background = 0;
-QPixmap *QS60StylePrivate::m_placeHolderTexture = 0;
-
-// theme palette
-QPalette *QS60StylePrivate::m_themePalette = 0;
-
-qint64 QS60StylePrivate::m_webPaletteKey = 0;
-
-QPointer<QWidget> QS60StylePrivate::m_pressedWidget = 0;
-
-const struct QS60StylePrivate::frameElementCenter QS60StylePrivate::m_frameElementsData[] = {
- {SE_ButtonNormal, QS60StyleEnums::SP_QsnFrButtonTbCenter},
- {SE_ButtonPressed, QS60StyleEnums::SP_QsnFrButtonTbCenterPressed},
- {SE_FrameLineEdit, QS60StyleEnums::SP_QsnFrInputCenter},
- {SE_ListHighlight, QS60StyleEnums::SP_QsnFrListCenter},
- {SE_PopupBackground, QS60StyleEnums::SP_QsnFrPopupCenter},
- {SE_SettingsList, QS60StyleEnums::SP_QsnFrSetOptCenter},
- {SE_TableItem, QS60StyleEnums::SP_QsnFrCaleCenter},
- {SE_TableHeaderItem, QS60StyleEnums::SP_QsnFrCaleHeadingCenter},
- {SE_ToolTip, QS60StyleEnums::SP_QsnFrPopupPreviewCenter},
- {SE_ToolBar, QS60StyleEnums::SP_QsnFrPopupSubCenter},
- {SE_ToolBarButton, QS60StyleEnums::SP_QgnFrSctrlButtonCenter},
- {SE_ToolBarButtonPressed, QS60StyleEnums::SP_QgnFrSctrlButtonCenterPressed},
- {SE_PanelBackground, QS60StyleEnums::SP_QsnFrSetOptCenter},
- {SE_ButtonInactive, QS60StyleEnums::SP_QsnFrButtonCenterInactive},
- {SE_Editor, QS60StyleEnums::SP_QsnFrInputCenter},
- {SE_TableItemPressed, QS60StyleEnums::SP_QsnFrGridCenterPressed},
- {SE_ListItemPressed, QS60StyleEnums::SP_QsnFrListCenterPressed},
-};
-
-static const int frameElementsCount =
- int(sizeof(QS60StylePrivate::m_frameElementsData)/sizeof(QS60StylePrivate::m_frameElementsData[0]));
-
-const int KNotFound = -909;
-const double KTabFontMul = 0.72;
-
-QS60StylePrivate::~QS60StylePrivate()
-{
- clearCaches(); //deletes also background image
- if (m_placeHolderTexture) {
- delete m_placeHolderTexture;
- m_placeHolderTexture = 0;
- }
- deleteThemePalette();
-#ifdef Q_WS_S60
- removeAnimations();
-#endif
-}
-
-void QS60StylePrivate::drawSkinElement(SkinElements element, QPainter *painter,
- const QRect &rect, SkinElementFlags flags)
-{
- switch (element) {
- case SE_ButtonNormal:
- drawFrame(SF_ButtonNormal, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ButtonPressed:
- drawFrame(SF_ButtonPressed, painter, rect, flags | SF_PointNorth);
- break;
- case SE_FrameLineEdit:
- drawFrame(SF_FrameLineEdit, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ProgressBarGrooveHorizontal:
- drawRow(QS60StyleEnums::SP_QgnGrafBarFrameSideL, QS60StyleEnums::SP_QgnGrafBarFrameCenter,
- QS60StyleEnums::SP_QgnGrafBarFrameSideR, Qt::Horizontal, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ProgressBarGrooveVertical:
- drawRow(QS60StyleEnums::SP_QgnGrafBarFrameSideL, QS60StyleEnums::SP_QgnGrafBarFrameCenter,
- QS60StyleEnums::SP_QgnGrafBarFrameSideR, Qt::Vertical, painter, rect, flags | SF_PointEast);
- break;
- case SE_ProgressBarIndicatorHorizontal:
- drawPart(QS60StyleEnums::SP_QgnGrafBarProgress, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ProgressBarIndicatorVertical:
- drawPart(QS60StyleEnums::SP_QgnGrafBarProgress, painter, rect, flags | SF_PointWest);
- break;
- case SE_ScrollBarGrooveHorizontal:
- drawRow(QS60StyleEnums::SP_QsnCpScrollBgBottom, QS60StyleEnums::SP_QsnCpScrollBgMiddle,
- QS60StyleEnums::SP_QsnCpScrollBgTop, Qt::Horizontal, painter, rect, flags | SF_PointEast);
- break;
- case SE_ScrollBarGrooveVertical:
- drawRow(QS60StyleEnums::SP_QsnCpScrollBgTop, QS60StyleEnums::SP_QsnCpScrollBgMiddle,
- QS60StyleEnums::SP_QsnCpScrollBgBottom, Qt::Vertical, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ScrollBarHandleHorizontal:
- drawRow(QS60StyleEnums::SP_QsnCpScrollHandleBottom, QS60StyleEnums::SP_QsnCpScrollHandleMiddle,
- QS60StyleEnums::SP_QsnCpScrollHandleTop, Qt::Horizontal, painter, rect, flags | SF_PointEast);
- break;
- case SE_ScrollBarHandleVertical:
- drawRow(QS60StyleEnums::SP_QsnCpScrollHandleTop, QS60StyleEnums::SP_QsnCpScrollHandleMiddle,
- QS60StyleEnums::SP_QsnCpScrollHandleBottom, Qt::Vertical, painter, rect, flags | SF_PointNorth);
- break;
- case SE_SliderHandleHorizontal:
- drawPart(QS60StyleEnums::SP_QgnGrafNsliderMarker, painter, rect, flags | SF_PointNorth);
- break;
- case SE_SliderHandleVertical:
- drawPart(QS60StyleEnums::SP_QgnGrafNsliderMarker, painter, rect, flags | SF_PointEast);
- break;
- case SE_SliderHandleSelectedHorizontal:
- drawPart(QS60StyleEnums::SP_QgnGrafNsliderMarkerSelected, painter, rect, flags | SF_PointNorth);
- break;
- case SE_SliderHandleSelectedVertical:
- drawPart(QS60StyleEnums::SP_QgnGrafNsliderMarkerSelected, painter, rect, flags | SF_PointEast);
- break;
- case SE_SliderGrooveVertical:
- drawRow(QS60StyleEnums::SP_QgnGrafNsliderEndLeft, QS60StyleEnums::SP_QgnGrafNsliderMiddle,
- QS60StyleEnums::SP_QgnGrafNsliderEndRight, Qt::Vertical, painter, rect, flags | SF_PointEast);
- break;
- case SE_SliderGrooveHorizontal:
- drawRow(QS60StyleEnums::SP_QgnGrafNsliderEndLeft, QS60StyleEnums::SP_QgnGrafNsliderMiddle,
- QS60StyleEnums::SP_QgnGrafNsliderEndRight, Qt::Horizontal, painter, rect, flags | SF_PointNorth);
- break;
- case SE_TabBarTabEastActive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabActiveL, QS60StyleEnums::SP_QgnGrafTabActiveM,
- QS60StyleEnums::SP_QgnGrafTabActiveR, Qt::Vertical, painter, rect, flags | SF_PointEast);
- break;
- case SE_TabBarTabEastInactive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabPassiveL, QS60StyleEnums::SP_QgnGrafTabPassiveM,
- QS60StyleEnums::SP_QgnGrafTabPassiveR, Qt::Vertical, painter, rect, flags | SF_PointEast);
- break;
- case SE_TabBarTabNorthActive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabActiveL, QS60StyleEnums::SP_QgnGrafTabActiveM,
- QS60StyleEnums::SP_QgnGrafTabActiveR, Qt::Horizontal, painter, rect, flags | SF_PointNorth);
- break;
- case SE_TabBarTabNorthInactive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabPassiveL, QS60StyleEnums::SP_QgnGrafTabPassiveM,
- QS60StyleEnums::SP_QgnGrafTabPassiveR, Qt::Horizontal, painter, rect, flags | SF_PointNorth);
- break;
- case SE_TabBarTabSouthActive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabActiveR, QS60StyleEnums::SP_QgnGrafTabActiveM,
- QS60StyleEnums::SP_QgnGrafTabActiveL, Qt::Horizontal, painter, rect, flags | SF_PointSouth);
- break;
- case SE_TabBarTabSouthInactive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabPassiveR, QS60StyleEnums::SP_QgnGrafTabPassiveM,
- QS60StyleEnums::SP_QgnGrafTabPassiveL, Qt::Horizontal, painter, rect, flags | SF_PointSouth);
- break;
- case SE_TabBarTabWestActive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabActiveR, QS60StyleEnums::SP_QgnGrafTabActiveM,
- QS60StyleEnums::SP_QgnGrafTabActiveL, Qt::Vertical, painter, rect, flags | SF_PointWest);
- break;
- case SE_TabBarTabWestInactive:
- drawRow(QS60StyleEnums::SP_QgnGrafTabPassiveR, QS60StyleEnums::SP_QgnGrafTabPassiveM,
- QS60StyleEnums::SP_QgnGrafTabPassiveL, Qt::Vertical, painter, rect, flags | SF_PointWest);
- break;
- case SE_ListHighlight:
- drawFrame(SF_ListHighlight, painter, rect, flags | SF_PointNorth);
- break;
- case SE_PopupBackground:
- drawFrame(SF_PopupBackground, painter, rect, flags | SF_PointNorth);
- break;
- case SE_SettingsList:
- drawFrame(SF_SettingsList, painter, rect, flags | SF_PointNorth);
- break;
- case SE_TableItem:
- drawFrame(SF_TableItem, painter, rect, flags | SF_PointNorth);
- break;
- case SE_TableHeaderItem:
- drawFrame(SF_TableHeaderItem, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ToolTip:
- drawFrame(SF_ToolTip, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ToolBar:
- drawFrame(SF_ToolBar, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ToolBarButton:
- drawFrame(SF_ToolBarButton, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ToolBarButtonPressed:
- drawFrame(SF_ToolBarButtonPressed, painter, rect, flags | SF_PointNorth);
- break;
- case SE_PanelBackground:
- drawFrame(SF_PanelBackground, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ScrollBarHandlePressedHorizontal:
- drawRow(QS60StyleEnums::SP_QsnCpScrollHandleBottomPressed, QS60StyleEnums::SP_QsnCpScrollHandleMiddlePressed,
- QS60StyleEnums::SP_QsnCpScrollHandleTopPressed, Qt::Horizontal, painter, rect, flags | SF_PointEast);
- break;
- case SE_ScrollBarHandlePressedVertical:
- drawRow(QS60StyleEnums::SP_QsnCpScrollHandleTopPressed, QS60StyleEnums::SP_QsnCpScrollHandleMiddlePressed,
- QS60StyleEnums::SP_QsnCpScrollHandleBottomPressed, Qt::Vertical, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ButtonInactive:
- drawFrame(SF_ButtonInactive, painter, rect, flags | SF_PointNorth);
- break;
- case SE_Editor:
- drawFrame(SF_FrameLineEdit, painter, rect, flags | SF_PointNorth);
- break;
- case SE_DropArea:
- drawPart(QS60StyleEnums::SP_QgnGrafOrgBgGrid, painter, rect, flags | SF_PointNorth);
- break;
- case SE_TableItemPressed:
- drawFrame(SF_TableItemPressed, painter, rect, flags | SF_PointNorth);
- break;
- case SE_ListItemPressed:
- drawFrame(SF_ListItemPressed, painter, rect, flags | SF_PointNorth);
- break;
- default:
- break;
- }
-}
-
-void QS60StylePrivate::drawSkinPart(QS60StyleEnums::SkinParts part,
- QPainter *painter, const QRect &rect, SkinElementFlags flags)
-{
- drawPart(part, painter, rect, flags);
-}
-
-short QS60StylePrivate::pixelMetric(int metric)
-{
- //If it is a custom value, need to strip away the base to map to internal
- //pixel metric value table
- if (metric & QStyle::PM_CustomBase) {
- metric -= QStyle::PM_CustomBase;
- metric += MAX_NON_CUSTOM_PIXELMETRICS - 1;
- }
-
- Q_ASSERT(metric < MAX_PIXELMETRICS);
- const short returnValue = m_pmPointer[metric];
- return returnValue;
-}
-
-QColor QS60StylePrivate::stateColor(const QColor &color, const QStyleOption *option)
-{
- QColor retColor (color);
- if (option && !(option->state & QStyle::State_Enabled)) {
- QColor hsvColor = retColor.toHsv();
- int colorSat = hsvColor.saturation();
- int colorVal = hsvColor.value();
- colorSat = (colorSat != 0) ? (colorSat >> 1) : 128;
- colorVal = (colorVal != 0) ? (colorVal >> 1) : 128;
- hsvColor.setHsv(hsvColor.hue(), colorSat, colorVal);
- retColor = hsvColor.toRgb();
- }
- return retColor;
-}
-
-QColor QS60StylePrivate::lighterColor(const QColor &baseColor)
-{
- QColor result(baseColor);
- bool modifyColor = false;
- if (result.saturation() == 0) {
- result.setHsv(result.hue(), 128, result.value());
- modifyColor = true;
- }
- if (result.value() == 0) {
- result.setHsv(result.hue(), result.saturation(), 128);
- modifyColor = true;
- }
- if (modifyColor)
- result = result.lighter(175);
- else
- result = result.lighter(225);
- return result;
-}
-
-bool QS60StylePrivate::drawsOwnThemeBackground(const QWidget *widget)
-{
- return (widget ? (widget->windowType() == Qt::Dialog) : false);
-}
-
-QFont QS60StylePrivate::s60Font(
- QS60StyleEnums::FontCategories fontCategory,
- int pointSize, bool resolveFontSize) const
-{
- QFont result;
- int actualPointSize = pointSize;
- if (actualPointSize <= 0) {
- const QFont appFont = QApplication::font();
- actualPointSize = appFont.pointSize();
- if (actualPointSize <= 0)
- actualPointSize = appFont.pixelSize() * 72 / qt_defaultDpiY();
- }
- Q_ASSERT(actualPointSize > 0);
- const QPair<QS60StyleEnums::FontCategories, int> key(fontCategory, actualPointSize);
- if (!m_mappedFontsCache.contains(key)) {
- result = s60Font_specific(fontCategory, actualPointSize, resolveFontSize);
- m_mappedFontsCache.insert(key, result);
- } else {
- result = m_mappedFontsCache.value(key);
- if (result.pointSize() != actualPointSize)
- result.setPointSize(actualPointSize);
- }
- return result;
-}
-
-void QS60StylePrivate::clearCaches(CacheClearReason reason)
-{
- switch(reason){
- case CC_LayoutChange:
- // when layout changes, the colors remain in cache, but graphics and fonts can change
- m_mappedFontsCache.clear();
- QPixmapCache::clear();
- break;
- case CC_ThemeChange:
- QPixmapCache::clear();
-#ifdef Q_WS_S60
- deleteStoredSettings();
-#endif
- deleteBackground();
- break;
- case CC_UndefinedChange:
- default:
- m_mappedFontsCache.clear();
- QPixmapCache::clear();
- deleteBackground();
- break;
- }
-}
-
-QColor QS60StylePrivate::calculatedColor(SkinFrameElements frame) const
-{
- const int frameCornerWidth = pixelMetric(PM_FrameCornerWidth);
- const int frameCornerHeight = pixelMetric(PM_FrameCornerHeight);
- Q_ASSERT(2 * frameCornerWidth < 32);
- Q_ASSERT(2 * frameCornerHeight < 32);
-
- const QImage frameImage = QS60StylePrivate::frame(frame, QSize(32, 32)).toImage();
- Q_ASSERT(frameImage.bytesPerLine() > 0);
- if (frameImage.isNull())
- return Qt::black;
-
- const QRgb *pixelRgb = (const QRgb*)frameImage.constBits();
- const int pixels = frameImage.byteCount() / sizeof(QRgb);
-
- int estimatedRed = 0;
- int estimatedGreen = 0;
- int estimatedBlue = 0;
-
- int skips = 0;
- int estimations = 0;
-
- const int topBorderLastPixel = frameCornerHeight * frameImage.width() - 1;
- const int bottomBorderFirstPixel = frameImage.width() * frameImage.height() - topBorderLastPixel;
- const int rightBorderFirstPixel = frameImage.width() - frameCornerWidth;
- const int leftBorderLastPixel = frameCornerWidth;
-
- while ((skips + estimations) < pixels) {
- if ((skips + estimations) > topBorderLastPixel &&
- (skips + estimations) < bottomBorderFirstPixel) {
- for (int rowIndex = 0; rowIndex < frameImage.width(); rowIndex++) {
- if (rowIndex > leftBorderLastPixel &&
- rowIndex < rightBorderFirstPixel) {
- estimatedRed += qRed(*pixelRgb);
- estimatedGreen += qGreen(*pixelRgb);
- estimatedBlue += qBlue(*pixelRgb);
- }
- pixelRgb++;
- estimations++;
- }
- } else {
- pixelRgb++;
- skips++;
- }
- }
- QColor frameColor(estimatedRed/estimations, estimatedGreen/estimations, estimatedBlue/estimations);
- return !estimations ? Qt::black : frameColor;
-}
-
-void QS60StylePrivate::setThemePalette(QApplication *app) const
-{
- Q_UNUSED(app)
- QPalette widgetPalette = QPalette(Qt::white);
- setThemePalette(&widgetPalette);
-}
-
-QPalette* QS60StylePrivate::themePalette()
-{
- return m_themePalette;
-}
-
-bool QS60StylePrivate::equalToThemePalette(QColor color, QPalette::ColorRole role)
-{
- if (!m_themePalette)
- return false;
- if (color == m_themePalette->color(role))
- return true;
- return false;
-}
-
-bool QS60StylePrivate::equalToThemePalette(qint64 cacheKey, QPalette::ColorRole role)
-{
- if (!m_themePalette)
- return false;
- if (cacheKey == m_themePalette->brush(role).texture().cacheKey())
- return true;
- return false;
-}
-
-void QS60StylePrivate::setBackgroundTexture(QApplication *app) const
-{
- Q_UNUSED(app)
- QPalette applicationPalette = QApplication::palette();
- // The initial QPalette::Window is just a placeHolder QPixmap to save RAM
- // if the actual texture is not needed. The real texture is created just before
- // painting it in qt_s60_fill_background().
- applicationPalette.setBrush(QPalette::Window, placeHolderTexture());
- setThemePalette(&applicationPalette);
-}
-
-void QS60StylePrivate::deleteBackground()
-{
- if (m_background) {
- delete m_background;
- m_background = 0;
- }
-}
-
-void QS60StylePrivate::setCurrentLayout(int index)
-{
- m_pmPointer = data[index];
-}
-
-void QS60StylePrivate::drawPart(QS60StyleEnums::SkinParts skinPart,
- QPainter *painter, const QRect &rect, SkinElementFlags flags)
-{
- static const bool doCache =
-#if defined(Q_WS_S60)
- // Freezes on 3.1. Anyways, caching is only really needed on touch UI
- !(QSysInfo::s60Version() == QSysInfo::SV_S60_3_1 || QSysInfo::s60Version() == QSysInfo::SV_S60_3_2);
-#else
- true;
-#endif
-
- const QPixmap skinPartPixMap((doCache ? cachedPart : part)(skinPart, rect.size(), painter, flags));
- if (!skinPartPixMap.isNull())
- painter->drawPixmap(rect.topLeft(), skinPartPixMap);
-}
-
-void QS60StylePrivate::drawFrame(SkinFrameElements frameElement, QPainter *painter, const QRect &rect, SkinElementFlags flags)
-{
- static const bool doCache =
-#if defined(Q_WS_S60)
- // Freezes on 3.1. Anyways, caching is only really needed on touch UI
- !(QSysInfo::s60Version() == QSysInfo::SV_S60_3_1 || QSysInfo::s60Version() == QSysInfo::SV_S60_3_2);
-#else
- true;
-#endif
- const QPixmap frameElementPixMap((doCache ? cachedFrame : frame)(frameElement, rect.size(), flags));
- if (!frameElementPixMap.isNull())
- painter->drawPixmap(rect.topLeft(), frameElementPixMap);
-}
-
-void QS60StylePrivate::drawRow(QS60StyleEnums::SkinParts start,
- QS60StyleEnums::SkinParts middle, QS60StyleEnums::SkinParts end,
- Qt::Orientation orientation, QPainter *painter, const QRect &rect,
- SkinElementFlags flags)
-{
- QSize startEndSize(partSize(start, flags));
- startEndSize.scale(rect.size(), Qt::KeepAspectRatio);
-
- QRect startRect = QRect(rect.topLeft(), startEndSize);
- QRect middleRect = rect;
- QRect endRect;
-
- if (orientation == Qt::Horizontal) {
- startRect.setHeight(rect.height());
- startRect.setWidth(qMin((rect.width() >> 1) - 1, startRect.width()));
- endRect = startRect.translated(rect.width() - startRect.width(), 0);
- middleRect.adjust(startRect.width(), 0, -startRect.width(), 0);
- if (startRect.bottomRight().x() > endRect.topLeft().x()) {
- const int overlap = (startRect.bottomRight().x() - endRect.topLeft().x()) >> 1;
- startRect.setWidth(startRect.width() - overlap);
- endRect.adjust(overlap, 0, 0, 0);
- }
- } else {
- startRect.setWidth(rect.width());
- startRect.setHeight(qMin((rect.height() >> 1) - 1, startRect.height()));
- endRect = startRect.translated(0, rect.height() - startRect.height());
- middleRect.adjust(0, startRect.height(), 0, -startRect.height());
- if (startRect.topRight().y() > endRect.bottomLeft().y()) {
- const int overlap = (startRect.topRight().y() - endRect.bottomLeft().y()) >> 1;
- startRect.setHeight(startRect.height() - overlap);
- endRect.adjust(0, overlap, 0, 0);
- }
- }
-
-#if 0
- painter->save();
- painter->setOpacity(.3);
- painter->fillRect(startRect, Qt::red);
- painter->fillRect(middleRect, Qt::green);
- painter->fillRect(endRect, Qt::blue);
- painter->restore();
-#else
- drawPart(start, painter, startRect, flags);
- if (middleRect.isValid())
- drawPart(middle, painter, middleRect, flags);
- drawPart(end, painter, endRect, flags);
-#endif
-}
-
-QPixmap QS60StylePrivate::cachedPart(QS60StyleEnums::SkinParts part,
- const QSize &size, QPainter *painter, SkinElementFlags flags)
-{
- QPixmap result;
- const int animationFrame = (flags & SF_Animation) ? currentAnimationFrame(part) : 0;
-
- const QString cacheKey =
- QString::fromLatin1("S60Style: SkinParts=%1 QSize=%2|%3 SkinPartFlags=%4 AnimationFrame=%5")
- .arg((int)part).arg(size.width()).arg(size.height()).arg((int)flags).arg(animationFrame);
- if (!QPixmapCache::find(cacheKey, result)) {
- result = QS60StylePrivate::part(part, size, painter, flags);
- QPixmapCache::insert(cacheKey, result);
- }
- return result;
-}
-
-QPixmap QS60StylePrivate::cachedFrame(SkinFrameElements frame, const QSize &size, SkinElementFlags flags)
-{
- QPixmap result;
- const QString cacheKey =
- QString::fromLatin1("S60Style: SkinFrameElements=%1 QSize=%2|%3 SkinElementFlags=%4")
- .arg((int)frame).arg(size.width()).arg(size.height()).arg((int)flags);
- if (!QPixmapCache::find(cacheKey, result)) {
- result = QS60StylePrivate::frame(frame, size, flags);
- QPixmapCache::insert(cacheKey, result);
- }
- return result;
-}
-
-void QS60StylePrivate::setFont(QWidget *widget) const
-{
- QS60StyleEnums::FontCategories fontCategory = QS60StyleEnums::FC_Undefined;
- if (!widget)
- return;
- if (qobject_cast<QPushButton *>(widget)){
- fontCategory = QS60StyleEnums::FC_Primary;
- } else if (qobject_cast<QToolButton *>(widget)){
- fontCategory = QS60StyleEnums::FC_Primary;
- } else if (qobject_cast<QHeaderView *>(widget)){
- fontCategory = QS60StyleEnums::FC_Secondary;
- } else if (qobject_cast<QGroupBox *>(widget)){
- fontCategory = QS60StyleEnums::FC_Title;
- } else if (qobject_cast<QMessageBox *>(widget)){
- fontCategory = QS60StyleEnums::FC_Primary;
- } else if (qobject_cast<QMenu *>(widget)){
- fontCategory = QS60StyleEnums::FC_Primary;
- } else if (qobject_cast<QCalendarWidget *>(widget)){
- fontCategory = QS60StyleEnums::FC_Secondary;
- }
- if (fontCategory != QS60StyleEnums::FC_Undefined) {
- const bool resolveFontSize = widget->testAttribute(Qt::WA_SetFont)
- && (widget->font().resolve() & QFont::SizeResolved);
- const QFont suggestedFont =
- s60Font(fontCategory, widget->font().pointSizeF(), resolveFontSize);
- widget->setFont(suggestedFont);
- }
-}
-
-void QS60StylePrivate::setThemePalette(QWidget *widget)
-{
- if(!widget)
- return;
-
- //header view and its viewport need to be set 100% transparent button color, since drawing code will
- //draw transparent theme graphics to table column and row headers.
- if (qobject_cast<QHeaderView *>(widget)){
- QPalette widgetPalette = QApplication::palette(widget);
- widgetPalette.setColor(QPalette::Active, QPalette::ButtonText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 23, 0));
- QHeaderView* header = qobject_cast<QHeaderView *>(widget);
- widgetPalette.setColor(QPalette::Button, Qt::transparent );
- if (header->viewport())
- header->viewport()->setPalette(widgetPalette);
- QApplication::setPalette(widgetPalette, "QHeaderView");
- } else if (qobject_cast<QLabel *>(widget)) {
- if (widget->window() && widget->window()->windowType() == Qt::Dialog) {
- QPalette widgetPalette = widget->palette();
- widgetPalette.setColor(QPalette::WindowText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 19, 0));
- widget->setPalette(widgetPalette);
- }
- }
-}
-
-void QS60StylePrivate::setThemePalette(QPalette *palette) const
-{
- if (!palette)
- return;
-
- // basic colors
- palette->setColor(QPalette::WindowText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 6, 0));
- palette->setColor(QPalette::ButtonText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 20, 0));
- palette->setColor(QPalette::Text,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 6, 0));
- palette->setColor(QPalette::ToolTipText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 55, 0));
- palette->setColor(QPalette::BrightText, palette->color(QPalette::WindowText).lighter());
- palette->setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 24, 0));
- palette->setColor(QPalette::Link,
- s60Color(QS60StyleEnums::CL_QsnHighlightColors, 3, 0));
- palette->setColor(QPalette::LinkVisited, palette->color(QPalette::Link).darker());
- palette->setColor(QPalette::Highlight,
- s60Color(QS60StyleEnums::CL_QsnHighlightColors, 2, 0));
- // The initial QPalette::Window is just a placeHolder QPixmap to save RAM
- // if the actual texture is not needed. The real texture is created just before
- // painting it in qt_s60_fill_background().
- palette->setBrush(QPalette::Window, placeHolderTexture());
- // set as transparent so that styled full screen theme background is visible
- palette->setBrush(QPalette::Base, Qt::transparent);
- // set button color based on pixel colors
-#ifndef Q_WS_S60
- //For emulated style, just calculate the color every time
- const QColor buttonColor = calculatedColor(SF_ButtonNormal);
-#else
- const QColor buttonColor = colorFromFrameGraphics(SF_ButtonNormal);
-#endif
- palette->setColor(QPalette::Button, buttonColor);
- palette->setColor(QPalette::Light, palette->color(QPalette::Button).lighter());
- palette->setColor(QPalette::Dark, palette->color(QPalette::Button).darker());
- palette->setColor(QPalette::Midlight, palette->color(QPalette::Button).lighter(125));
- palette->setColor(QPalette::Mid, palette->color(QPalette::Button).darker(150));
- palette->setColor(QPalette::Shadow, Qt::black);
- QColor alternateBase = palette->light().color();
- alternateBase.setAlphaF(0.8);
- palette->setColor(QPalette::AlternateBase, alternateBase);
-
- QApplication::setPalette(*palette); //calling QApplication::setPalette clears palette hash
- setThemePaletteHash(palette);
- storeThemePalette(palette);
-}
-
-void QS60StylePrivate::deleteThemePalette()
-{
- if (m_themePalette) {
- delete m_themePalette;
- m_themePalette = 0;
- }
-}
-
-void QS60StylePrivate::storeThemePalette(QPalette *palette)
-{
- deleteThemePalette();
- //store specified palette for latter use.
- m_themePalette = new QPalette(*palette);
-}
-
-// set widget specific palettes
-void QS60StylePrivate::setThemePaletteHash(QPalette *palette)
-{
- if (!palette)
- return;
-
- //store the original palette
- QPalette widgetPalette = *palette;
- const QColor mainAreaTextColor =
- s60Color(QS60StyleEnums::CL_QsnTextColors, 6, 0);
-
- widgetPalette.setColor(QPalette::WindowText,
- s60Color(QS60StyleEnums::CL_QsnLineColors, 8, 0));
- QApplication::setPalette(widgetPalette, "QSlider");
- // return to original palette after each widget
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::Active, QPalette::ButtonText, mainAreaTextColor);
- widgetPalette.setColor(QPalette::Inactive, QPalette::ButtonText, mainAreaTextColor);
- const QStyleOption opt;
- widgetPalette.setColor(QPalette::Disabled, QPalette::ButtonText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 6, &opt));
- QApplication::setPalette(widgetPalette, "QPushButton");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::Active, QPalette::ButtonText, mainAreaTextColor);
- widgetPalette.setColor(QPalette::Inactive, QPalette::ButtonText, mainAreaTextColor);
- QApplication::setPalette(widgetPalette, "QToolButton");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::Active, QPalette::ButtonText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 23, 0));
- QApplication::setPalette(widgetPalette, "QHeaderView");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::ButtonText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 8, 0));
- QApplication::setPalette(widgetPalette, "QMenuBar");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::Text,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 22, 0));
- widgetPalette.setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 11, 0));
- QApplication::setPalette(widgetPalette, "QMenu");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::WindowText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 4, 0));
- widgetPalette.setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 3, 0));
- QApplication::setPalette(widgetPalette, "QTabBar");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 10, 0));
- QApplication::setPalette(widgetPalette, "QListView");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::Text,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 22, 0));
- widgetPalette.setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 11, 0));
- QApplication::setPalette(widgetPalette, "QTableView");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::Text,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 27, 0));
- widgetPalette.setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 24, 0));
- QApplication::setPalette(widgetPalette, "QLineEdit");
- QApplication::setPalette(widgetPalette, "QTextEdit");
- QApplication::setPalette(widgetPalette, "QComboBox");
- QApplication::setPalette(widgetPalette, "QSpinBox");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::WindowText, s60Color(QS60StyleEnums::CL_QsnTextColors, 7, 0));
- widgetPalette.setColor(QPalette::HighlightedText,
- s60Color(QS60StyleEnums::CL_QsnTextColors, 11, 0));
- QApplication::setPalette(widgetPalette, "QRadioButton");
- QApplication::setPalette(widgetPalette, "QCheckBox");
- widgetPalette = *palette;
-
- widgetPalette.setColor(QPalette::WindowText, mainAreaTextColor);
- widgetPalette.setColor(QPalette::Button, QApplication::palette().color(QPalette::Button));
- widgetPalette.setColor(QPalette::Dark, mainAreaTextColor.darker());
- widgetPalette.setColor(QPalette::Light, mainAreaTextColor.lighter());
- QApplication::setPalette(widgetPalette, "QDial");
- widgetPalette = *palette;
-
- widgetPalette.setBrush(QPalette::Window, QBrush());
- QApplication::setPalette(widgetPalette, "QScrollArea");
- widgetPalette = *palette;
-
- //Webpages should not use S60 theme colors as they are designed to work
- //with themeBackground and do not generally mesh well with web page backgrounds.
- QPalette webPalette = *palette;
- webPalette.setColor(QPalette::WindowText, Qt::black);
- webPalette.setColor(QPalette::Text, Qt::black);
- webPalette.setBrush(QPalette::Base, Qt::white);
-
- QApplication::setPalette(webPalette, "QWebView");
- QApplication::setPalette(webPalette, "QGraphicsWebView");
-
- m_webPaletteKey = webPalette.cacheKey();
-}
-
-QSize QS60StylePrivate::partSize(QS60StyleEnums::SkinParts part, SkinElementFlags flags)
-{
- QSize result(20, 20);
- switch (part)
- {
- case QS60StyleEnums::SP_QgnGrafBarProgress:
- result.setWidth(pixelMetric(QStyle::PM_ProgressBarChunkWidth));
- break;
- case QS60StyleEnums::SP_QgnGrafTabActiveM:
- case QS60StyleEnums::SP_QgnGrafTabPassiveM:
- case QS60StyleEnums::SP_QgnGrafTabActiveR:
- case QS60StyleEnums::SP_QgnGrafTabPassiveR:
- case QS60StyleEnums::SP_QgnGrafTabPassiveL:
- case QS60StyleEnums::SP_QgnGrafTabActiveL:
- //Returned QSize for tabs must not be square, but narrow rectangle with width:height
- //ratio of 1:2 for horizontal tab bars (and 2:1 for vertical ones).
- result.setWidth(result.height() >> 1);
- break;
-
- case QS60StyleEnums::SP_QgnGrafNsliderEndLeft:
- case QS60StyleEnums::SP_QgnGrafNsliderEndRight:
- case QS60StyleEnums::SP_QgnGrafNsliderMiddle:
- break;
-
- case QS60StyleEnums::SP_QgnGrafNsliderMarker:
- case QS60StyleEnums::SP_QgnGrafNsliderMarkerSelected:
- result.scale(pixelMetric(QStyle::PM_SliderLength),
- pixelMetric(QStyle::PM_SliderControlThickness), Qt::IgnoreAspectRatio);
- break;
-
- case QS60StyleEnums::SP_QgnGrafBarFrameSideL:
- case QS60StyleEnums::SP_QgnGrafBarFrameSideR:
- result.setWidth(pixelMetric(PM_FrameCornerWidth));
- break;
-
- case QS60StyleEnums::SP_QsnCpScrollHandleTopPressed:
- case QS60StyleEnums::SP_QsnCpScrollBgBottom:
- case QS60StyleEnums::SP_QsnCpScrollBgTop:
- case QS60StyleEnums::SP_QsnCpScrollHandleBottom:
- case QS60StyleEnums::SP_QsnCpScrollHandleTop:
- case QS60StyleEnums::SP_QsnCpScrollHandleBottomPressed:
- result.setHeight(pixelMetric(QStyle::PM_ScrollBarExtent));
- result.setWidth(pixelMetric(QStyle::PM_ScrollBarExtent));
- break;
- case QS60StyleEnums::SP_QsnCpScrollHandleMiddlePressed:
- case QS60StyleEnums::SP_QsnCpScrollBgMiddle:
- case QS60StyleEnums::SP_QsnCpScrollHandleMiddle:
- result.setHeight(pixelMetric(QStyle::PM_ScrollBarExtent));
- result.setWidth(pixelMetric(QStyle::PM_ScrollBarSliderMin));
- break;
- default:
- // Generic frame part size gathering.
- for (int i = 0; i < frameElementsCount; ++i)
- {
- switch (m_frameElementsData[i].center - part) {
- case 8: /* CornerTl */
- case 7: /* CornerTr */
- case 6: /* CornerBl */
- case 5: /* CornerBr */
- result.setWidth(pixelMetric(PM_FrameCornerWidth));
- // Falltrough intended...
- case 4: /* SideT */
- case 3: /* SideB */
- result.setHeight(pixelMetric(PM_FrameCornerHeight));
- break;
- case 2: /* SideL */
- case 1: /* SideR */
- result.setWidth(pixelMetric(PM_FrameCornerWidth));
- break;
- case 0: /* center */
- default:
- break;
- }
- }
- break;
- }
- if (flags & (SF_PointEast | SF_PointWest)) {
- const int temp = result.width();
- result.setWidth(result.height());
- result.setHeight(temp);
- }
- return result;
-}
-
-bool QS60StylePrivate::canDrawThemeBackground(const QBrush &backgroundBrush, const QWidget *widget)
-{
- // Always return true for web pages.
- if (widget && m_webPaletteKey == QApplication::palette(widget).cacheKey())
- return true;
- //If brush is not changed from style's default values, draw theme graphics.
- return (backgroundBrush.color() == Qt::transparent ||
- backgroundBrush.style() == Qt::NoBrush) ? true : false;
-}
-
-bool QS60StylePrivate::isWidgetPressed(const QWidget *widget)
-{
- return (widget && widget == m_pressedWidget);
-}
-
-// Generates 1*1 white pixmap as a placeholder for real texture.
-// The actual theme texture is drawn in qt_s60_fill_background().
-QPixmap QS60StylePrivate::placeHolderTexture()
-{
- if (!m_placeHolderTexture) {
- m_placeHolderTexture = new QPixmap(1,1);
- m_placeHolderTexture->fill(Qt::green);
- }
- return *m_placeHolderTexture;
-}
-
-/*!
- \class QS60Style
- \brief The QS60Style class provides a look and feel suitable for applications on S60.
- \since 4.6
- \ingroup appearance
-
- \sa QMacStyle, QWindowsStyle, QWindowsXPStyle, QWindowsVistaStyle, QPlastiqueStyle, QCleanlooksStyle, QMotifStyle
-*/
-
-
-/*!
- Destroys the style.
-*/
-QS60Style::~QS60Style()
-{
-}
-
-/*!
- \reimp
-*/
-void QS60Style::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
-{
- const QS60StylePrivate::SkinElementFlags flags = (option->state & State_Enabled) ? QS60StylePrivate::SF_StateEnabled : QS60StylePrivate::SF_StateDisabled;
- SubControls sub = option->subControls;
-
- switch (control) {
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *optionSlider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- const bool horizontal = optionSlider->orientation == Qt::Horizontal;
-
- const QRect scrollBarSlider = subControlRect(control, optionSlider, SC_ScrollBarSlider, widget);
- const QRect grooveRect = subControlRect(control, optionSlider, SC_ScrollBarGroove, widget);
-
- const QS60StylePrivate::SkinElements grooveElement =
- horizontal ? QS60StylePrivate::SE_ScrollBarGrooveHorizontal : QS60StylePrivate::SE_ScrollBarGrooveVertical;
- QS60StylePrivate::drawSkinElement(grooveElement, painter, grooveRect, flags);
-
- const SubControls subControls = optionSlider->subControls;
-
- // select correct slider (horizontal/vertical/pressed)
- const bool sliderPressed = ((optionSlider->state & State_Sunken) && (subControls & SC_ScrollBarSlider));
- const QS60StylePrivate::SkinElements handleElement =
- horizontal ?
- ( sliderPressed ?
- QS60StylePrivate::SE_ScrollBarHandlePressedHorizontal :
- QS60StylePrivate::SE_ScrollBarHandleHorizontal ) :
- ( sliderPressed ?
- QS60StylePrivate::SE_ScrollBarHandlePressedVertical :
- QS60StylePrivate::SE_ScrollBarHandleVertical);
- QS60StylePrivate::drawSkinElement(handleElement, painter, scrollBarSlider, flags);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *optionSlider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
-
- const QRect sliderGroove = subControlRect(control, optionSlider, SC_SliderGroove, widget);
- const bool horizontal = optionSlider->orientation == Qt::Horizontal;
-
- //Highlight
-/* if (optionSlider->state & State_HasFocus)
- drawPrimitive(PE_FrameFocusRect, optionSlider, painter, widget);*/
-
- //Groove graphics
- if (QS60StylePrivate::hasSliderGrooveGraphic()) {
- const QS60StylePrivate::SkinElements grooveElement = horizontal ?
- QS60StylePrivate::SE_SliderGrooveHorizontal :
- QS60StylePrivate::SE_SliderGrooveVertical;
- QS60StylePrivate::drawSkinElement(grooveElement, painter, sliderGroove, flags);
- } else {
- const QPoint sliderGrooveCenter = sliderGroove.center();
- const bool horizontal = optionSlider->orientation == Qt::Horizontal;
- painter->save();
- if (widget)
- painter->setPen(widget->palette().windowText().color());
- if (horizontal)
- painter->drawLine(0, sliderGrooveCenter.y(), sliderGroove.right(), sliderGrooveCenter.y());
- else
- painter->drawLine(sliderGrooveCenter.x(), 0, sliderGrooveCenter.x(), sliderGroove.bottom());
- painter->restore();
- }
-
- //Handle graphics
- const QRect sliderHandle = subControlRect(control, optionSlider, SC_SliderHandle, widget);
- QS60StylePrivate::SkinElements handleElement;
- if (optionSlider->state & State_Sunken)
- handleElement =
- horizontal ? QS60StylePrivate::SE_SliderHandleSelectedHorizontal : QS60StylePrivate::SE_SliderHandleSelectedVertical;
- else
- handleElement =
- horizontal ? QS60StylePrivate::SE_SliderHandleHorizontal : QS60StylePrivate::SE_SliderHandleVertical;
- QS60StylePrivate::drawSkinElement(handleElement, painter, sliderHandle, flags);
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- const QRect cmbxEditField = subControlRect(CC_ComboBox, option, SC_ComboBoxEditField, widget);
- const QRect cmbxFrame = subControlRect(CC_ComboBox, option, SC_ComboBoxFrame, widget);
- const bool direction = cmb->direction == Qt::LeftToRight;
-
- // Button frame
- QStyleOptionFrame buttonOption;
- buttonOption.QStyleOption::operator=(*cmb);
- const int maxButtonSide = cmbxFrame.width() - cmbxEditField.width();
- const int newTop = cmbxEditField.center().y() - maxButtonSide / 2;
- const int topLeftPoint = direction ?
- (cmbxEditField.right() + 1) : (cmbxEditField.left() + 1 - maxButtonSide);
- const QRect buttonRect(topLeftPoint, newTop, maxButtonSide, maxButtonSide);
- buttonOption.rect = buttonRect;
- buttonOption.state = cmb->state;
- drawPrimitive(PE_PanelButtonCommand, &buttonOption, painter, widget);
-
- // draw label background - label itself is drawn separately
- const QS60StylePrivate::SkinElements skinElement = QS60StylePrivate::SE_FrameLineEdit;
- QS60StylePrivate::drawSkinElement(skinElement, painter, cmbxEditField, flags);
-
- // Draw the combobox arrow
- if (sub & SC_ComboBoxArrow) {
- // Make rect slightly smaller
- buttonOption.rect.adjust(1, 1, -1, -1);
- painter->save();
- painter->setPen(option->palette.buttonText().color());
- drawPrimitive(PE_IndicatorSpinDown, &buttonOption, painter, widget);
- painter->restore();
- }
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_TOOLBUTTON
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolBtn = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- State bflags = toolBtn->state & ~State_Sunken;
-
- if (bflags & State_AutoRaise) {
- if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) {
- bflags &= ~State_Raised;
- }
- }
- State mflags = bflags;
- if (toolBtn->state & State_Sunken) {
- bflags |= State_Sunken;
- mflags |= State_Sunken;
- }
-
- const QRect button(subControlRect(control, toolBtn, SC_ToolButton, widget));
- QRect menuRect = QRect();
- if (toolBtn->subControls & SC_ToolButtonMenu)
- menuRect = subControlRect(control, toolBtn, SC_ToolButtonMenu, widget);
-
- if (toolBtn->subControls & SC_ToolButton) {
- QStyleOption tool(0);
- tool.palette = toolBtn->palette;
-
- if (bflags & (State_Sunken | State_On | State_Raised | State_Enabled)) {
- tool.rect = button.unite(menuRect);
- tool.state = bflags;
- drawPrimitive(PE_PanelButtonTool, &tool, painter, widget);
- }
- if (toolBtn->subControls & SC_ToolButtonMenu) {
- tool.rect = menuRect;
- tool.state = mflags;
- drawPrimitive(PE_IndicatorArrowDown, &tool, painter, widget);
- }
- }
- QStyleOptionToolButton toolButton = *toolBtn;
- if (toolBtn->features & QStyleOptionToolButton::Arrow) {
- PrimitiveElement pe;
- switch (toolBtn->arrowType) {
- case Qt::LeftArrow:
- pe = PE_IndicatorArrowLeft;
- break;
- case Qt::RightArrow:
- pe = PE_IndicatorArrowRight;
- break;
- case Qt::UpArrow:
- pe = PE_IndicatorArrowUp;
- break;
- case Qt::DownArrow:
- pe = PE_IndicatorArrowDown;
- break;
- default:
- break; }
- toolButton.rect = button;
- drawPrimitive(pe, &toolButton, painter, widget);
- }
-
- if (toolBtn->text.length() > 0 ||
- !toolBtn->icon.isNull()) {
- const int frameWidth = pixelMetric(PM_DefaultFrameWidth, option, widget);
- toolButton.rect = button.adjusted(frameWidth, frameWidth, -frameWidth, -frameWidth);
- drawControl(CE_ToolButtonLabel, &toolButton, painter, widget);
- }
- }
- break;
-#endif //QT_NO_TOOLBUTTON
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QStyleOptionSpinBox copy = *spinBox;
- PrimitiveElement pe;
-
- if (spinBox->subControls & SC_SpinBoxUp) {
- copy.subControls = SC_SpinBoxUp;
- QPalette spinBoxPal = spinBox->palette;
- if (!(spinBox->stepEnabled & QAbstractSpinBox::StepUpEnabled)) {
- spinBoxPal.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- copy.palette = spinBoxPal;
- }
-
- if (spinBox->activeSubControls == SC_SpinBoxUp && (spinBox->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) ?
- PE_IndicatorSpinPlus :
- PE_IndicatorSpinUp;
-
- copy.rect = subControlRect(CC_SpinBox, spinBox, SC_SpinBoxUp, widget);
- drawPrimitive(PE_PanelButtonBevel, &copy, painter, widget);
- copy.rect.adjust(1, 1, -1, -1);
- drawPrimitive(pe, &copy, painter, widget);
- }
-
- if (spinBox->subControls & SC_SpinBoxDown) {
- copy.subControls = SC_SpinBoxDown;
- copy.state = spinBox->state;
- QPalette spinBoxPal = spinBox->palette;
- if (!(spinBox->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- spinBoxPal.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- copy.palette = spinBoxPal;
- }
-
- if (spinBox->activeSubControls == SC_SpinBoxDown && (spinBox->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) ?
- PE_IndicatorSpinMinus :
- PE_IndicatorSpinDown;
-
- copy.rect = subControlRect(CC_SpinBox, spinBox, SC_SpinBoxDown, widget);
- drawPrimitive(PE_PanelButtonBevel, &copy, painter, widget);
- copy.rect.adjust(1, 1, -1, -1);
- drawPrimitive(pe, &copy, painter, widget);
- }
- }
- break;
-#endif //QT_NO_SPINBOX
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- // Draw frame
- const QRect textRect = subControlRect(CC_GroupBox, option, SC_GroupBoxLabel, widget);
- const QRect checkBoxRect = subControlRect(CC_GroupBox, option, SC_GroupBoxCheckBox, widget);
- if (groupBox->subControls & SC_GroupBoxFrame) {
- QStyleOptionFrameV2 frame;
- frame.QStyleOption::operator=(*groupBox);
- frame.features = groupBox->features;
- frame.lineWidth = groupBox->lineWidth;
- frame.midLineWidth = groupBox->midLineWidth;
- frame.rect = subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);
- drawPrimitive(PE_FrameGroupBox, &frame, painter, widget);
- }
-
- // Draw title
- if ((groupBox->subControls & SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
- const QColor textColor = groupBox->textColor;
- painter->save();
-
- if (textColor.isValid())
- painter->setPen(textColor);
- int alignment = int(groupBox->textAlignment);
- if (!styleHint(SH_UnderlineShortcut, option, widget))
- alignment |= Qt::TextHideMnemonic;
-
- drawItemText(painter, textRect, Qt::TextShowMnemonic | Qt::AlignHCenter | Qt::AlignVCenter | alignment,
- groupBox->palette, groupBox->state & State_Enabled, groupBox->text,
- textColor.isValid() ? QPalette::NoRole : QPalette::WindowText);
- painter->restore();
- }
-
- // Draw checkbox
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*groupBox);
- box.rect = checkBoxRect;
- drawPrimitive(PE_IndicatorCheckBox, &box, painter, widget);
- }
- }
- break;
-#endif //QT_NO_GROUPBOX
- default:
- QCommonStyle::drawComplexControl(control, option, painter, widget);
- }
-}
-
-/*!
- \reimp
-*/
-void QS60Style::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
-{
- Q_D(const QS60Style);
- const QS60StylePrivate::SkinElementFlags flags = (option->state & State_Enabled) ? QS60StylePrivate::SF_StateEnabled : QS60StylePrivate::SF_StateDisabled;
- switch (element) {
- case CE_CheckBox:
- case CE_RadioButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool isRadio = (element == CE_RadioButton);
- QStyleOptionButton subopt = *btn;
-
- // Highlight needs to be drawn first, as it goes "underneath" the text and indicator.
- if (btn->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*btn);
- fropt.rect = subElementRect(isRadio ? SE_RadioButtonFocusRect
- : SE_CheckBoxFocusRect, btn, widget);
- drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
-
- subopt.palette.setColor(QPalette::Active, QPalette::WindowText,
- subopt.palette.highlightedText().color());
- }
-
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, btn, widget);
- drawPrimitive(isRadio ? PE_IndicatorRadioButton : PE_IndicatorCheckBox,
- &subopt, painter, widget);
- subopt.rect = subElementRect(isRadio ? SE_RadioButtonContents
- : SE_CheckBoxContents, btn, widget);
-
- drawControl(isRadio ? CE_RadioButtonLabel : CE_CheckBoxLabel, &subopt, painter, widget);
- }
- break;
-
- case CE_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
-
- drawControl(CE_PushButtonBevel, btn, painter, widget);
- QStyleOptionButton subopt = *btn;
- subopt.rect = subElementRect(SE_PushButtonContents, btn, widget);
-
- drawControl(CE_PushButtonLabel, &subopt, painter, widget);
- }
- break;
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- const bool isDisabled = !(option->state & State_Enabled);
- const bool isFlat = button->features & QStyleOptionButton::Flat;
- QS60StyleEnums::SkinParts skinPart;
- QS60StylePrivate::SkinElements skinElement;
- if (!isDisabled) {
- const bool isPressed = (option->state & State_Sunken) ||
- (option->state & State_On);
- if (isFlat) {
- skinPart =
- isPressed ? QS60StyleEnums::SP_QsnFrButtonTbCenterPressed : QS60StyleEnums::SP_QsnFrButtonTbCenter;
- } else {
- skinElement =
- isPressed ? QS60StylePrivate::SE_ButtonPressed : QS60StylePrivate::SE_ButtonNormal;
- }
- } else {
- if (isFlat)
- skinPart =QS60StyleEnums::SP_QsnFrButtonCenterInactive;
- else
- skinElement = QS60StylePrivate::SE_ButtonInactive;
- }
- if (isFlat)
- QS60StylePrivate::drawSkinPart(skinPart, painter, option->rect, flags);
- else
- QS60StylePrivate::drawSkinElement(skinElement, painter, option->rect, flags);
- }
- break;
-#ifndef QT_NO_TOOLBUTTON
- case CE_ToolButtonLabel:
- if (const QStyleOptionToolButton *toolBtn = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- QStyleOptionToolButton optionToolButton = *toolBtn;
-
- if (!optionToolButton.icon.isNull() && (optionToolButton.state & State_Sunken)
- && (optionToolButton.state & State_Enabled)) {
-
- const QIcon::State state = optionToolButton.state & State_On ? QIcon::On : QIcon::Off;
- const QPixmap pm(optionToolButton.icon.pixmap(optionToolButton.rect.size().boundedTo(optionToolButton.iconSize),
- QIcon::Normal, state));
- optionToolButton.icon = generatedIconPixmap(QIcon::Selected, pm, &optionToolButton);
- }
-
- QCommonStyle::drawControl(element, &optionToolButton, painter, widget);
- }
- break;
-#endif //QT_NO_TOOLBUTTON
-#ifndef QT_NO_COMBOBOX
- case CE_ComboBoxLabel:
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- QStyleOption optionComboBox = *comboBox;
- optionComboBox.palette.setColor(QPalette::Active, QPalette::WindowText,
- optionComboBox.palette.text().color() );
- optionComboBox.palette.setColor(QPalette::Inactive, QPalette::WindowText,
- optionComboBox.palette.text().color() );
- QRect editRect = subControlRect(CC_ComboBox, comboBox, SC_ComboBoxEditField, widget);
- const int frameW = proxy()->pixelMetric(PM_DefaultFrameWidth, option, widget);
-
- if (!comboBox->currentIcon.isNull()) {
- const QIcon::Mode mode = comboBox->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- const QPixmap pixmap = comboBox->currentIcon.pixmap(comboBox->iconSize, mode);
- QRect iconRect(editRect);
- iconRect.setWidth(comboBox->iconSize.width() + frameW);
- iconRect = alignedRect(comboBox->direction,
- Qt::AlignLeft | Qt::AlignVCenter,
- iconRect.size(), editRect);
- if (comboBox->editable)
- painter->fillRect(iconRect, optionComboBox.palette.brush(QPalette::Base));
- drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap);
-
- if (comboBox->direction == Qt::RightToLeft)
- editRect.setRight(editRect.right() - frameW - comboBox->iconSize.width());
- else
- editRect.setLeft(comboBox->iconSize.width() + frameW);
- }
- if (!comboBox->currentText.isEmpty() && !comboBox->editable) {
- const Qt::TextElideMode elideMode = (comboBox->direction == Qt::LeftToRight) ? Qt::ElideRight : Qt::ElideLeft;
- const QString text = comboBox->fontMetrics.elidedText(comboBox->currentText, elideMode, editRect.width());
-
- QCommonStyle::drawItemText(painter,
- editRect.adjusted(QS60StylePrivate::pixelMetric(PM_FrameCornerWidth), 0, -1, 0),
- visualAlignment(comboBox->direction, Qt::AlignLeft | Qt::AlignVCenter),
- comboBox->palette, comboBox->state & State_Enabled, text);
- }
- }
- break;
-#endif //QT_NO_COMBOBOX
-#ifndef QT_NO_ITEMVIEWS
- case CE_ItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- QStyleOptionViewItemV4 voptAdj = *vopt;
- painter->save();
-
- painter->setClipRect(voptAdj.rect);
- const bool isSelected = (vopt->state & State_Selected);
- const bool hasFocus = (vopt->state & State_HasFocus);
-
- bool isScrollBarVisible = false;
- int scrollBarWidth = 0;
- QList<QScrollBar *> scrollBars = widget->findChildren<QScrollBar *>();
- for (int i = 0; i < scrollBars.size(); ++i) {
- QScrollBar *scrollBar = scrollBars.at(i);
- if (scrollBar && scrollBar->orientation() == Qt::Vertical) {
- isScrollBarVisible = scrollBar->isVisible();
- scrollBarWidth = scrollBar->size().width();
- break;
- }
- }
-
- int rightValue = widget ? widget->contentsRect().right() : voptAdj.rect.right();
-
- if (isScrollBarVisible)
- rightValue -= scrollBarWidth;
-
- if (voptAdj.rect.right() > rightValue)
- voptAdj.rect.setRight(rightValue);
-
- const QRect iconRect = subElementRect(SE_ItemViewItemDecoration, &voptAdj, widget);
- QRect textRect = subElementRect(SE_ItemViewItemText, &voptAdj, widget);
- const QAbstractItemView *itemView = qobject_cast<const QAbstractItemView *>(widget);
-
- const bool singleSelection = itemView &&
- ((itemView->selectionMode() == QAbstractItemView::SingleSelection ||
- itemView->selectionMode() == QAbstractItemView::NoSelection));
- const bool selectItems = itemView && (itemView->selectionBehavior() == QAbstractItemView::SelectItems);
-
- // draw themed background for itemview unless background brush has been defined.
- if (vopt->backgroundBrush == Qt::NoBrush) {
- if (itemView) {
- //With single item selection, use highlight focus as selection indicator.
- if (singleSelection && isSelected){
- voptAdj.state = voptAdj.state | State_HasFocus;
- if (!hasFocus && selectItems) {
- painter->save();
- painter->setOpacity(0.5);
- }
- }
- drawPrimitive(PE_PanelItemViewItem, &voptAdj, painter, widget);
- if (singleSelection && isSelected && !hasFocus && selectItems)
- painter->restore();
- }
- } else { QCommonStyle::drawPrimitive(PE_PanelItemViewItem, &voptAdj, painter, widget);}
-
- // draw the icon
- const QIcon::Mode mode = (voptAdj.state & State_Enabled) ? QIcon::Normal : QIcon::Disabled;
- const QIcon::State state = (voptAdj.state & State_Open) ? QIcon::On : QIcon::Off;
- voptAdj.icon.paint(painter, iconRect, voptAdj.decorationAlignment, mode, state);
-
- // Draw selection check mark or checkbox
- if (itemView && (!singleSelection || (vopt->features & QStyleOptionViewItemV2::HasCheckIndicator))) {
- const QRect selectionRect = subElementRect(SE_ItemViewItemCheckIndicator, &voptAdj, widget);
-
- QStyleOptionViewItemV4 checkMarkOption(voptAdj);
- if (selectionRect.isValid())
- checkMarkOption.rect = selectionRect;
- // Draw selection mark.
- if (isSelected && selectItems) {
- proxy()->drawPrimitive(PE_IndicatorViewItemCheck, &checkMarkOption, painter, widget);
- // @todo: this should happen in the rect retrievel i.e. subElementRect()
- if (textRect.right() > selectionRect.left())
- textRect.setRight(selectionRect.left());
- } else if (voptAdj.features & QStyleOptionViewItemV2::HasCheckIndicator) {
- checkMarkOption.state = checkMarkOption.state & ~State_HasFocus;
-
- switch (vopt->checkState) {
- case Qt::Unchecked:
- checkMarkOption.state |= State_Off;
- break;
- case Qt::PartiallyChecked:
- checkMarkOption.state |= State_NoChange;
- break;
- case Qt::Checked:
- checkMarkOption.state |= State_On;
- break;
- }
- drawPrimitive(PE_IndicatorViewItemCheck, &checkMarkOption, painter, widget);
- }
- }
-
- // draw the text
- if (!voptAdj.text.isEmpty()) {
- if (hasFocus)
- painter->setPen(voptAdj.palette.highlightedText().color());
- else
- painter->setPen(voptAdj.palette.text().color());
- d->viewItemDrawText(painter, &voptAdj, textRect);
- }
- painter->restore();
- }
- break;
-#endif // QT_NO_ITEMVIEWS
-#ifndef QT_NO_TABBAR
- case CE_TabBarTabShape:
- if (const QStyleOptionTabV3 *optionTab = qstyleoption_cast<const QStyleOptionTabV3 *>(option)) {
- QStyleOptionTabV3 optionTabAdj = *optionTab;
- const bool isSelected = optionTab->state & State_Selected;
- const bool directionMirrored = (optionTab->direction == Qt::RightToLeft);
- QS60StylePrivate::SkinElements skinElement;
- switch (optionTab->shape) {
- case QTabBar::TriangularEast:
- case QTabBar::RoundedEast:
- skinElement = isSelected ? QS60StylePrivate::SE_TabBarTabEastActive:
- QS60StylePrivate::SE_TabBarTabEastInactive;
- break;
- case QTabBar::TriangularSouth:
- case QTabBar::RoundedSouth:
- skinElement = isSelected ? QS60StylePrivate::SE_TabBarTabSouthActive:
- QS60StylePrivate::SE_TabBarTabSouthInactive;
- break;
- case QTabBar::TriangularWest:
- case QTabBar::RoundedWest:
- skinElement = isSelected ? QS60StylePrivate::SE_TabBarTabWestActive:
- QS60StylePrivate::SE_TabBarTabWestInactive;
- break;
- case QTabBar::TriangularNorth:
- case QTabBar::RoundedNorth:
- default:
- skinElement = isSelected ? QS60StylePrivate::SE_TabBarTabNorthActive:
- QS60StylePrivate::SE_TabBarTabNorthInactive;
- break;
- }
- if (skinElement == QS60StylePrivate::SE_TabBarTabEastInactive ||
- skinElement == QS60StylePrivate::SE_TabBarTabNorthInactive ||
- skinElement == QS60StylePrivate::SE_TabBarTabSouthInactive ||
- skinElement == QS60StylePrivate::SE_TabBarTabWestInactive ||
- skinElement == QS60StylePrivate::SE_TabBarTabEastActive ||
- skinElement == QS60StylePrivate::SE_TabBarTabNorthActive ||
- skinElement == QS60StylePrivate::SE_TabBarTabSouthActive ||
- skinElement==QS60StylePrivate::SE_TabBarTabWestActive) {
- const int borderThickness =
- QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth);
- int tabOverlap = pixelMetric(PM_TabBarTabOverlap);
- if (tabOverlap > borderThickness)
- tabOverlap -= borderThickness;
-
- const bool usesScrollButtons =
- (widget) ? (qobject_cast<const QTabBar*>(widget))->usesScrollButtons() : false;
- const int roomForScrollButton =
- usesScrollButtons ? QS60StylePrivate::pixelMetric(PM_TabBarScrollButtonWidth) : 0;
-
- // adjust for overlapping tabs and scrollbuttons, if necessary
- if (skinElement == QS60StylePrivate::SE_TabBarTabEastInactive ||
- skinElement == QS60StylePrivate::SE_TabBarTabEastActive ||
- skinElement == QS60StylePrivate::SE_TabBarTabWestInactive ||
- skinElement == QS60StylePrivate::SE_TabBarTabWestActive){
- if (optionTabAdj.position == QStyleOptionTabV3::Beginning)
- optionTabAdj.rect.adjust(0, roomForScrollButton, 0, tabOverlap);
- else if (optionTabAdj.position == QStyleOptionTabV3::End)
- optionTabAdj.rect.adjust(0, 0, 0, tabOverlap);
- else
- optionTabAdj.rect.adjust(0, 0, 0, tabOverlap);
- } else {
- if (directionMirrored) {
- if (optionTabAdj.position == QStyleOptionTabV3::Beginning)
- optionTabAdj.rect.adjust(-tabOverlap, 0, -roomForScrollButton, 0);
- else
- optionTabAdj.rect.adjust(-tabOverlap, 0, 0, 0);
- } else {
- if (optionTabAdj.position == QStyleOptionTabV3::Beginning)
- optionTabAdj.rect.adjust(roomForScrollButton, 0, tabOverlap, 0);
- else
- optionTabAdj.rect.adjust(0, 0, tabOverlap, 0);
- }
- }
- }
- QS60StylePrivate::drawSkinElement(skinElement, painter, optionTabAdj.rect, flags);
- }
- break;
- case CE_TabBarTabLabel:
- if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(option)) {
- QStyleOptionTabV3 optionTab = *tab;
- QRect tr = optionTab.rect;
- const bool directionMirrored = (optionTab.direction == Qt::RightToLeft);
- const int borderThickness =
- QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth);
- int tabOverlap = pixelMetric(PM_TabBarTabOverlap);
- if (tabOverlap > borderThickness)
- tabOverlap -= borderThickness;
- const bool usesScrollButtons =
- (widget) ? (qobject_cast<const QTabBar*>(widget))->usesScrollButtons() : false;
- const int roomForScrollButton =
- usesScrollButtons ? QS60StylePrivate::pixelMetric(PM_TabBarScrollButtonWidth) : 0;
-
- switch (tab->shape) {
- case QTabBar::TriangularWest:
- case QTabBar::RoundedWest:
- case QTabBar::TriangularEast:
- case QTabBar::RoundedEast:
- tr.adjust(0, 0, 0, tabOverlap);
- break;
- case QTabBar::TriangularSouth:
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularNorth:
- case QTabBar::RoundedNorth:
- default:
- if (directionMirrored)
- tr.adjust(-tabOverlap, 0, 0, 0);
- else
- tr.adjust(0, 0, tabOverlap, 0);
- break;
- }
- painter->save();
- QFont f = painter->font();
- f.setPointSizeF(f.pointSizeF() * KTabFontMul);
- painter->setFont(f);
-
- const bool selected = optionTab.state & State_Selected;
- if (selected)
- optionTab.palette.setColor(QPalette::Active, QPalette::WindowText,
- optionTab.palette.highlightedText().color());
-
- const bool verticalTabs = optionTab.shape == QTabBar::RoundedEast
- || optionTab.shape == QTabBar::RoundedWest
- || optionTab.shape == QTabBar::TriangularEast
- || optionTab.shape == QTabBar::TriangularWest;
-
- //make room for scrollbuttons
- if (!verticalTabs) {
- if ((tab->position == QStyleOptionTabV3::Beginning && !directionMirrored))
- tr.adjust(roomForScrollButton, 0, 0, 0);
- else if ((tab->position == QStyleOptionTabV3::Beginning && directionMirrored))
- tr.adjust(0, 0, -roomForScrollButton, 0);
- } else {
- if (tab->position == QStyleOptionTabV3::Beginning)
- tr.adjust(0, roomForScrollButton, 0, 0);
- }
-
- if (verticalTabs) {
- painter->save();
- int newX, newY, newRotation;
- if (optionTab.shape == QTabBar::RoundedEast || optionTab.shape == QTabBar::TriangularEast) {
- newX = tr.width();
- newY = tr.y();
- newRotation = 90;
- } else {
- newX = 0;
- newY = tr.y() + tr.height();
- newRotation = -90;
- }
- tr.setRect(0, 0, tr.height(), tr.width());
- QTransform m;
- m.translate(newX, newY);
- m.rotate(newRotation);
- painter->setTransform(m, true);
- }
- tr.adjust(0, 0, pixelMetric(PM_TabBarTabShiftHorizontal, tab, widget),
- pixelMetric(PM_TabBarTabShiftVertical, tab, widget));
-
- if (selected) {
- tr.setBottom(tr.bottom() - pixelMetric(PM_TabBarTabShiftVertical, tab, widget));
- tr.setRight(tr.right() - pixelMetric(PM_TabBarTabShiftHorizontal, tab, widget));
- }
-
- int alignment = Qt::AlignCenter | Qt::TextShowMnemonic;
- if (!styleHint(SH_UnderlineShortcut, &optionTab, widget))
- alignment |= Qt::TextHideMnemonic;
- if (!optionTab.icon.isNull()) {
- QSize iconSize = optionTab.iconSize;
- if (!iconSize.isValid()) {
- const int iconExtent = pixelMetric(PM_TabBarIconSize);
- iconSize = QSize(iconExtent, iconExtent);
- }
- QPixmap tabIcon = optionTab.icon.pixmap(iconSize,
- (optionTab.state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
- if (tab->text.isEmpty())
- painter->drawPixmap(tr.center().x() - (tabIcon.height() >> 1),
- tr.center().y() - (tabIcon.height() >> 1),
- tabIcon);
- else
- painter->drawPixmap(tr.left() + tabOverlap,
- tr.center().y() - (tabIcon.height() >> 1),
- tabIcon);
- tr.setLeft(tr.left() + iconSize.width() + 4); //todo: magic four
- }
-
- QCommonStyle::drawItemText(painter, tr, alignment, optionTab.palette, tab->state & State_Enabled, tab->text, QPalette::WindowText);
- if (verticalTabs)
- painter->restore();
-
- painter->restore();
- }
- break;
-#endif // QT_NO_TABBAR
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBarV2 *optionProgressBar = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- QRect progressRect = optionProgressBar->rect;
-
- if (optionProgressBar->minimum == optionProgressBar->maximum && optionProgressBar->minimum == 0) {
- // busy indicator
- const QS60StylePrivate::SkinElementFlag orientationFlag = optionProgressBar->orientation == Qt::Horizontal ?
- QS60StylePrivate::SF_PointNorth : QS60StylePrivate::SF_PointWest;
-
- QS60StylePrivate::drawSkinPart(QS60StyleEnums::SP_QgnGrafBarWaitAnim,
- painter, progressRect, flags | orientationFlag | QS60StylePrivate::SF_Animation );
- } else {
- const qreal progressFactor = (optionProgressBar->minimum == optionProgressBar->maximum) ? 1.0
- : (qreal)optionProgressBar->progress / optionProgressBar->maximum;
- const int frameWidth = pixelMetric(PM_DefaultFrameWidth, option, widget);
- if (optionProgressBar->orientation == Qt::Horizontal) {
- progressRect.setWidth(int(progressRect.width() * progressFactor));
- if(optionProgressBar->direction == Qt::RightToLeft)
- progressRect.translate(optionProgressBar->rect.width() - progressRect.width(), 0);
- progressRect.adjust(frameWidth, 0, -frameWidth, 0);
- } else {
- progressRect.adjust(0, frameWidth, 0, -frameWidth);
- progressRect.setTop(progressRect.bottom() - int(progressRect.height() * progressFactor));
- }
-
- const QS60StylePrivate::SkinElements skinElement = optionProgressBar->orientation == Qt::Horizontal ?
- QS60StylePrivate::SE_ProgressBarIndicatorHorizontal : QS60StylePrivate::SE_ProgressBarIndicatorVertical;
- QS60StylePrivate::drawSkinElement(skinElement, painter, progressRect, flags);
- }
- }
- break;
- case CE_ProgressBarGroove:
- if (const QStyleOptionProgressBarV2 *optionProgressBar = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- const QS60StylePrivate::SkinElements skinElement = optionProgressBar->orientation == Qt::Horizontal ?
- QS60StylePrivate::SE_ProgressBarGrooveHorizontal : QS60StylePrivate::SE_ProgressBarGrooveVertical;
- QS60StylePrivate::drawSkinElement(skinElement, painter, option->rect, flags);
- }
- break;
- case CE_ProgressBarLabel:
- if (const QStyleOptionProgressBarV2 *progressbar = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- QStyleOptionProgressBarV2 optionProgressBar = *progressbar;
- QCommonStyle::drawItemText(painter, progressbar->rect, flags | Qt::AlignCenter | Qt::TextSingleLine, optionProgressBar.palette,
- progressbar->state & State_Enabled, progressbar->text, QPalette::WindowText);
- }
- break;
-#endif // QT_NO_PROGRESSBAR
-#ifndef QT_NO_MENU
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- QStyleOptionMenuItem optionMenuItem = *menuItem;
-
- bool drawSubMenuIndicator = false;
- bool drawSeparator = false;
- switch(menuItem->menuItemType) {
- case QStyleOptionMenuItem::Separator:
- drawSeparator = true;
- break;
- case QStyleOptionMenuItem::Scroller:
- return; // no scrollers in S60 menus
- case QStyleOptionMenuItem::SubMenu:
- drawSubMenuIndicator = true;
- break;
- default:
- break;
- }
- if (drawSeparator) {
- painter->save();
- painter->setPen(QS60StylePrivate::s60Color(QS60StyleEnums::CL_QsnLineColors, 10, 0));
- painter->drawLine(optionMenuItem.rect.topLeft(), optionMenuItem.rect.bottomRight());
- painter->restore();
- return;
- }
- const bool enabled = optionMenuItem.state & State_Enabled;
- const bool checkable = optionMenuItem.checkType != QStyleOptionMenuItem::NotCheckable;
- bool ignoreCheckMark = false;
-
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox*>(widget))
- ignoreCheckMark = true; //ignore the checkmarks provided by the QComboMenuDelegate
-#endif
-
- uint text_flags = Qt::AlignLeading | Qt::TextShowMnemonic | Qt::TextDontClip
- | Qt::TextSingleLine | Qt::AlignVCenter;
- if (!styleHint(SH_UnderlineShortcut, menuItem, widget))
- text_flags |= Qt::TextHideMnemonic;
-
- QRect iconRect = subElementRect(SE_ItemViewItemDecoration, &optionMenuItem, widget);
- QRect textRect = subElementRect(SE_ItemViewItemText, &optionMenuItem, widget);
-
- QStyleOptionMenuItem optionCheckBox;
-
- //Regardless of checkbox visibility, make room for it, this mirrors native implementation,
- //where text and icon placement is static regardless of content of menu item.
- optionCheckBox.QStyleOptionMenuItem::operator=(*menuItem);
- optionCheckBox.rect.setWidth(pixelMetric(PM_IndicatorWidth));
- optionCheckBox.rect.setHeight(pixelMetric(PM_IndicatorHeight));
-
- const int vSpacing = QS60StylePrivate::pixelMetric(PM_LayoutVerticalSpacing);
- //The vertical spacing is doubled; it needs one spacing to separate checkbox from
- //highlight and then it needs one to separate it whatever is shown after it (text/icon/both).
- const int moveByX = optionCheckBox.rect.width() + 2 * vSpacing;
- optionCheckBox.rect.moveCenter(QPoint(
- optionCheckBox.rect.center().x() + moveByX >> 1,
- menuItem->rect.center().y()));
-
- if (optionMenuItem.direction != Qt::LeftToRight)
- optionCheckBox.rect.translate(textRect.width() + iconRect.width(), 0);
-
-
- const bool selected = (option->state & State_Selected) && (option->state & State_Enabled);
- if (selected) {
- const int spacing = ignoreCheckMark ? (vSpacing + QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth)) : 0;
- const int start = optionMenuItem.rect.left() + spacing;
- const int end = optionMenuItem.rect.right() - spacing;
- //-1 adjustment to avoid highlight being on top of possible separator item
- const QRect highlightRect = QRect(
- QPoint(start, option->rect.top()),
- QPoint(end, option->rect.bottom() - 1));
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_ListHighlight, painter, highlightRect, flags);
- }
-
- if (checkable && !ignoreCheckMark)
- drawPrimitive(PE_IndicatorMenuCheckMark, &optionCheckBox, painter, widget);
-
- //draw icon and/or checkState
- QPixmap pix = menuItem->icon.pixmap(pixelMetric(PM_SmallIconSize),
- enabled ? QIcon::Normal : QIcon::Disabled);
- const bool itemWithIcon = !pix.isNull();
- if (itemWithIcon) {
- drawItemPixmap(painter, iconRect, text_flags, pix);
- if (optionMenuItem.direction == Qt::LeftToRight)
- textRect.translate(vSpacing, 0);
- else
- textRect.translate(-vSpacing, 0);
- textRect.setWidth(textRect.width() - vSpacing);
- }
-
- //draw indicators
- if (drawSubMenuIndicator) {
- QStyleOptionMenuItem arrowOptions;
- arrowOptions.QStyleOption::operator=(*menuItem);
- const int indicatorWidth = (pixelMetric(PM_ListViewIconSize, option, widget) >> 1) +
- pixelMetric(PM_LayoutVerticalSpacing, option, widget);
- if (optionMenuItem.direction == Qt::LeftToRight)
- arrowOptions.rect.setLeft(textRect.right());
- arrowOptions.rect.setWidth(indicatorWidth);
- //by default sub menu indicator in S60 points to east,so here icon
- // direction is set to north (and south when in RightToLeft)
- const QS60StylePrivate::SkinElementFlag arrowDirection = (arrowOptions.direction == Qt::LeftToRight) ?
- QS60StylePrivate::SF_PointNorth : QS60StylePrivate::SF_PointSouth;
- painter->save();
- painter->setPen(option->palette.windowText().color());
- QS60StylePrivate::drawSkinPart(QS60StyleEnums::SP_QgnIndiSubmenu, painter, arrowOptions.rect,
- (flags | QS60StylePrivate::SF_ColorSkinned | arrowDirection));
- painter->restore();
- }
-
- //draw text
- if (!enabled){
- //In s60, if something becomes disabled, it is removed from menu, so no native look-alike available.
- optionMenuItem.palette.setColor(QPalette::Disabled, QPalette::Text, QS60StylePrivate::lighterColor(
- optionMenuItem.palette.color(QPalette::Disabled, QPalette::Text)));
- painter->save();
- painter->setOpacity(0.5);
- }
- if (selected)
- optionMenuItem.palette.setColor(
- QPalette::Active, QPalette::Text, optionMenuItem.palette.highlightedText().color());
-
- QCommonStyle::drawItemText(painter, textRect, text_flags,
- optionMenuItem.palette, enabled,
- optionMenuItem.text, QPalette::Text);
-
- //In Sym^3, native menu items have "lines" between them
- if (QS60StylePrivate::isSingleClickUi()) {
- int diff = widget->geometry().bottom() - optionMenuItem.rect.bottom();
- if (const QComboBox *cb = qobject_cast<const QComboBox*>(widget))
- diff = cb->view()->geometry().bottom() - optionMenuItem.rect.bottom();
-
- // Skip drawing the horizontal line for the last menu item.
- if (diff > optionMenuItem.rect.height()) {
- const QColor lineColorAlpha = QS60StylePrivate::s60Color(QS60StyleEnums::CL_QsnLineColors, 15, 0);
- //native platform sets each color byte to same value for "line 16" which just defines alpha for
- //menuitem lines; lets use first byte "red".
- QColor lineColor = optionMenuItem.palette.text().color();
- if (lineColorAlpha.isValid())
- lineColor.setAlpha(lineColorAlpha.red());
- painter->save();
- painter->setPen(lineColor);
- const int horizontalMargin = 2 * QS60StylePrivate::pixelMetric(PM_FrameCornerWidth) - QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth);
- const int lineStartX = optionMenuItem.rect.left() + horizontalMargin;
- const int lineEndX = optionMenuItem.rect.right() - horizontalMargin;
- painter->drawLine(QPoint(lineStartX, optionMenuItem.rect.bottom()), QPoint(lineEndX, optionMenuItem.rect.bottom()));
- painter->restore();
- }
- }
- if (!enabled)
- painter->restore();
- }
- break;
- case CE_MenuEmptyArea:
- break;
-#endif //QT_NO_MENU
-
-#ifndef QT_NO_MENUBAR
- case CE_MenuBarEmptyArea:
- break;
-#endif //QT_NO_MENUBAR
-
- case CE_HeaderSection:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- painter->save();
- QPen linePen = QPen(QS60StylePrivate::s60Color(QS60StyleEnums::CL_QsnLineColors, 1, header));
- const int penWidth = (header->orientation == Qt::Horizontal) ?
- linePen.width() + QS60StylePrivate::pixelMetric(PM_BoldLineWidth)
- : linePen.width() + QS60StylePrivate::pixelMetric(PM_ThinLineWidth);
- linePen.setWidth(penWidth);
- painter->setPen(linePen);
- if (header->orientation == Qt::Horizontal){
- painter->drawLine(header->rect.bottomLeft(), header->rect.bottomRight());
- } else {
- if ( header->direction == Qt::LeftToRight ) {
- painter->drawLine(header->rect.topRight(), header->rect.bottomRight());
- } else {
- painter->drawLine(header->rect.topLeft(), header->rect.bottomLeft());
- }
- }
- painter->restore();
-
- //Draw corner button as normal pushButton.
- if (qobject_cast<const QAbstractButton *>(widget)) {
- //Make cornerButton slightly smaller so that it is not on top of table border graphic.
- QStyleOptionHeader subopt = *header;
- const int borderTweak =
- QS60StylePrivate::pixelMetric(PM_FrameCornerWidth) >> 1;
- if (subopt.direction == Qt::LeftToRight)
- subopt.rect.adjust(borderTweak, borderTweak, 0, -borderTweak);
- else
- subopt.rect.adjust(0, borderTweak, -borderTweak, -borderTweak);
- drawPrimitive(PE_PanelButtonBevel, &subopt, painter, widget);
- } else if ((header->palette.brush(QPalette::Button) != Qt::transparent)) {
- //Draw non-themed background. Background for theme is drawn in CE_ShapedFrame
- //to get continuous theme graphic across all the header cells.
- qDrawShadePanel(painter, header->rect, header->palette,
- header->state & (State_Sunken | State_On), penWidth,
- &header->palette.brush(QPalette::Button));
- }
- }
- break;
- case CE_HeaderEmptyArea: // no need to draw this
- break;
- case CE_Header:
- if ( const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- drawControl(CE_HeaderSection, header, painter, widget);
- QStyleOptionHeader subopt = *header;
- subopt.rect = subElementRect(SE_HeaderLabel, header, widget);
- if (subopt.rect.isValid())
- drawControl(CE_HeaderLabel, &subopt, painter, widget);
- if (header->sortIndicator != QStyleOptionHeader::None) {
- subopt.rect = subElementRect(SE_HeaderArrow, option, widget);
- drawPrimitive(PE_IndicatorHeaderArrow, &subopt, painter, widget);
- }
- }
- break;
-#ifndef QT_NO_TOOLBAR
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
- const QToolBar *tbWidget = qobject_cast<const QToolBar *>(widget);
-
- //toolbar within a toolbar, skip
- if (!tbWidget || (widget && qobject_cast<QToolBar *>(widget->parentWidget())))
- break;
-
- // Normally in S60 5.0+ there is no background for toolbar, but in some cases with versatile QToolBar,
- // it looks a bit strange. So, lets fillRect with Button.
- if (!QS60StylePrivate::isToolBarBackground()) {
- QList<QAction *> actions = tbWidget->actions();
- bool justToolButtonsInToolBar = true;
- for (int i = 0; i < actions.size(); ++i) {
- QWidget *childWidget = tbWidget->widgetForAction(actions.at(i));
- const QToolButton *button = qobject_cast<const QToolButton *>(childWidget);
- if (!button){
- justToolButtonsInToolBar = false;
- }
- }
-
- // Draw frame background
- // for vertical toolbars with text only and
- // for toolbars with extension buttons and
- // for toolbars with widgets in them.
- if (!justToolButtonsInToolBar ||
- (tbWidget &&
- (tbWidget->orientation() == Qt::Vertical) &&
- (tbWidget->toolButtonStyle() == Qt::ToolButtonTextOnly))) {
- painter->save();
- if (widget)
- painter->setBrush(widget->palette().button());
- painter->setOpacity(0.3);
- painter->fillRect(toolBar->rect, painter->brush());
- painter->restore();
- }
- } else {
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_ToolBar, painter, toolBar->rect, flags);
- }
- }
- break;
-#endif //QT_NO_TOOLBAR
- case CE_ShapedFrame:
- if (const QTextEdit *textEdit = qobject_cast<const QTextEdit *>(widget)) {
- const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(option);
- if (frame && QS60StylePrivate::canDrawThemeBackground(frame->palette.base(), widget))
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_Editor, painter, option->rect, flags);
- else
- QCommonStyle::drawControl(element, option, painter, widget);
- } else if (qobject_cast<const QTableView *>(widget)) {
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_TableItem, painter, option->rect, flags);
- } else if (const QHeaderView *header = qobject_cast<const QHeaderView *>(widget)) {
- //QS60style draws header background here instead of in each headersection, to get
- //continuous graphic from section to section.
- QS60StylePrivate::SkinElementFlags adjustableFlags = flags;
- QRect headerRect = option->rect;
- if (header->orientation() != Qt::Horizontal) {
- //todo: update to horizontal table graphic
- adjustableFlags = (adjustableFlags | QS60StylePrivate::SF_PointWest);
- } else {
- const int frameWidth = QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth);
- if (option->direction == Qt::LeftToRight)
- headerRect.adjust(-2 * frameWidth, 0, 0, 0);
- else
- headerRect.adjust(0, 0, 2 * frameWidth, 0);
- }
- if (option->palette.brush(QPalette::Button).color() == Qt::transparent)
- QS60StylePrivate::drawSkinElement(
- QS60StylePrivate::SE_TableHeaderItem, painter, headerRect, adjustableFlags);
-
- } else if (qobject_cast<const QFrame *>(widget)) {
- QCommonStyle::drawControl(element, option, painter, widget);
- }
- break;
- case CE_MenuScroller:
- break;
- case CE_FocusFrame: {
-#ifdef QT_KEYPAD_NAVIGATION
- bool editFocus = false;
- if (const QFocusFrame *focusFrame = qobject_cast<const QFocusFrame*>(widget)) {
- if (focusFrame->widget() && focusFrame->widget()->hasEditFocus())
- editFocus = true;
- }
- const qreal opacity = editFocus ? 1 : 0.75; // Trial and error factors. Feel free to improve.
-#else
- const qreal opacity = 0.85;
-#endif
- // We need to reduce the focus frame size if LayoutSpacing is smaller than FocusFrameMargin
- // Otherwise, we would overlay adjacent widgets.
- const int frameHeightReduction =
- qMin(0, pixelMetric(PM_LayoutVerticalSpacing)
- - pixelMetric(PM_FocusFrameVMargin));
- const int frameWidthReduction =
- qMin(0, pixelMetric(PM_LayoutHorizontalSpacing)
- - pixelMetric(PM_FocusFrameHMargin));
- const int rounding =
- qMin(pixelMetric(PM_FocusFrameVMargin),
- pixelMetric(PM_LayoutVerticalSpacing));
- const QRect frameRect =
- option->rect.adjusted(-frameWidthReduction, -frameHeightReduction,
- frameWidthReduction, frameHeightReduction);
- QPainterPath framePath;
- framePath.addRoundedRect(frameRect, rounding, rounding);
-
- painter->save();
- painter->setRenderHint(QPainter::Antialiasing);
- painter->setOpacity(opacity);
- painter->fillPath(framePath, option->palette.color(QPalette::Text));
- painter->restore();
- }
- break;
- case CE_Splitter:
- if (option->state & State_Sunken && option->state & State_Enabled && QS60StylePrivate::themePalette()) {
- painter->save();
- painter->setOpacity(0.5);
- painter->setBrush(QS60StylePrivate::themePalette()->light());
- painter->setRenderHint(QPainter::Antialiasing);
- const qreal roundRectRadius = 4 * goldenRatio;
- painter->drawRoundedRect(option->rect, roundRectRadius, roundRectRadius);
- painter->restore();
- }
- break;
- default:
- QCommonStyle::drawControl(element, option, painter, widget);
- }
-}
-
-/*!
- \reimp
-*/
-void QS60Style::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
-{
- const QS60StylePrivate::SkinElementFlags flags = (option->state & State_Enabled) ? QS60StylePrivate::SF_StateEnabled : QS60StylePrivate::SF_StateDisabled;
- bool commonStyleDraws = false;
-
- switch (element) {
- case PE_FrameFocusRect: {
- //Draw themed highlight to radiobuttons and checkboxes.
- //For other widgets skip, unless palette has been modified. In that case, draw with commonstyle.
- if (QS60StylePrivate::equalToThemePalette(option->palette.highlight().color(), QPalette::Highlight)) {
- if ((qstyleoption_cast<const QStyleOptionFocusRect *>(option) &&
- (qobject_cast<const QRadioButton *>(widget) || qobject_cast<const QCheckBox *>(widget))))
- QS60StylePrivate::drawSkinElement(
- QS60StylePrivate::isWidgetPressed(widget) ?
- QS60StylePrivate::SE_ListItemPressed :
- QS60StylePrivate::SE_ListHighlight, painter, option->rect, flags);
- } else {
- commonStyleDraws = true;
- }
- }
- break;
-#ifndef QT_NO_LINEEDIT
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *lineEdit = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
-#ifndef QT_NO_COMBOBOX
- if (widget && qobject_cast<const QComboBox *>(widget->parentWidget()))
- break;
-#endif
- if (QS60StylePrivate::canDrawThemeBackground(option->palette.base(), widget))
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_FrameLineEdit, painter, option->rect, flags);
- else
- commonStyleDraws = true;
- }
- break;
-#endif // QT_NO_LINEEDIT
- case PE_IndicatorCheckBox: {
- // Draw checkbox indicator as color skinned graphics.
- const QS60StyleEnums::SkinParts skinPart = (option->state & State_On) ?
- QS60StyleEnums::SP_QgnIndiCheckboxOn : QS60StyleEnums::SP_QgnIndiCheckboxOff;
- painter->save();
-
- if (QS60StylePrivate::equalToThemePalette(option->palette.windowText().color(), QPalette::WindowText))
- painter->setPen(option->palette.windowText().color());
-
- QS60StylePrivate::drawSkinPart(skinPart, painter, option->rect, flags | QS60StylePrivate::SF_ColorSkinned );
- painter->restore();
- }
- break;
- case PE_IndicatorViewItemCheck:
-#ifndef QT_NO_ITEMVIEWS
- if (const QAbstractItemView *itemView = (qobject_cast<const QAbstractItemView *>(widget))) {
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- const bool checkBoxVisible = vopt->features & QStyleOptionViewItemV2::HasCheckIndicator;
- const bool singleSelection = itemView->selectionMode() ==
- QAbstractItemView::SingleSelection || itemView->selectionMode() == QAbstractItemView::NoSelection;
- // draw either checkbox at the beginning
- if (checkBoxVisible && singleSelection) {
- drawPrimitive(PE_IndicatorCheckBox, option, painter, widget);
- // ... or normal "tick" selection at the end.
- } else if (option->state & State_Selected) {
- QRect tickRect = option->rect;
- const int frameBorderWidth = QS60StylePrivate::pixelMetric(PM_FrameCornerWidth);
- // adjust tickmark rect to exclude frame border
- tickRect.adjust(0, -frameBorderWidth, 0, -frameBorderWidth);
- QS60StyleEnums::SkinParts skinPart = QS60StyleEnums::SP_QgnIndiMarkedAdd;
- QS60StylePrivate::drawSkinPart(skinPart, painter, tickRect,
- (flags | QS60StylePrivate::SF_ColorSkinned));
- }
- }
- }
-#endif //QT_NO_ITEMVIEWS
- break;
- case PE_IndicatorRadioButton: {
- QRect buttonRect = option->rect;
- //there is empty (a. 33%) space in svg graphics for radiobutton
- const qreal reduceWidth = (qreal)buttonRect.width() / 3.0;
- const qreal rectWidth = (qreal)option->rect.width() != 0 ? option->rect.width() : 1.0;
- // Try to occupy the full area
- const qreal scaler = 1 + (reduceWidth/rectWidth);
- buttonRect.setWidth((int)((buttonRect.width()-reduceWidth) * scaler));
- buttonRect.setHeight((int)(buttonRect.height() * scaler));
- // move the rect up for half of the new height-gain
- const int newY = (buttonRect.bottomRight().y() - option->rect.bottomRight().y()) >> 1 ;
- buttonRect.adjust(0, -newY, -1, -newY);
-
- painter->save();
- const QColor themeColor = QS60StylePrivate::s60Color(QS60StyleEnums::CL_QsnTextColors, 6, option);
- const QColor buttonTextColor = option->palette.buttonText().color();
- if (themeColor != buttonTextColor)
- painter->setPen(buttonTextColor);
- else
- painter->setPen(themeColor);
-
- // Draw radiobutton indicator as color skinned graphics.
- QS60StyleEnums::SkinParts skinPart = (option->state & State_On) ?
- QS60StyleEnums::SP_QgnIndiRadiobuttOn : QS60StyleEnums::SP_QgnIndiRadiobuttOff;
- QS60StylePrivate::drawSkinPart(skinPart, painter, buttonRect,
- (flags | QS60StylePrivate::SF_ColorSkinned));
- painter->restore();
- }
- break;
- case PE_PanelButtonCommand:
- case PE_PanelButtonTool:
- case PE_PanelButtonBevel:
- case PE_FrameButtonBevel:
- if (QS60StylePrivate::canDrawThemeBackground(option->palette.base(), widget)) {
- const bool isPressed = (option->state & State_Sunken) || (option->state & State_On);
- QS60StylePrivate::SkinElements skinElement;
- if (element == PE_PanelButtonTool)
- skinElement = isPressed ? QS60StylePrivate::SE_ToolBarButtonPressed : QS60StylePrivate::SE_ToolBarButton;
- else
- skinElement = isPressed ? QS60StylePrivate::SE_ButtonPressed : QS60StylePrivate::SE_ButtonNormal;
- QS60StylePrivate::drawSkinElement(skinElement, painter, option->rect, flags);
- } else {
- commonStyleDraws = true;
- }
- break;
-#ifndef QT_NO_TOOLBUTTON
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowLeft:
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowUp: {
- QS60StyleEnums::SkinParts skinPart;
- if (element==PE_IndicatorArrowDown)
- skinPart = QS60StyleEnums::SP_QgnGrafScrollArrowDown;
- else if (element==PE_IndicatorArrowLeft)
- skinPart = QS60StyleEnums::SP_QgnGrafScrollArrowLeft;
- else if (element==PE_IndicatorArrowRight)
- skinPart = QS60StyleEnums::SP_QgnGrafScrollArrowRight;
- else if (element==PE_IndicatorArrowUp)
- skinPart = QS60StyleEnums::SP_QgnGrafScrollArrowUp;
-
- QS60StylePrivate::drawSkinPart(skinPart, painter, option->rect, flags);
- }
- break;
-#endif //QT_NO_TOOLBUTTON
-#ifndef QT_NO_SPINBOX
- case PE_IndicatorSpinDown:
- case PE_IndicatorSpinUp:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- if (QS60StylePrivate::canDrawThemeBackground(spinBox->palette.base(), widget)) {
- QStyleOptionSpinBox optionSpinBox = *spinBox;
- const QS60StyleEnums::SkinParts part = (element == PE_IndicatorSpinUp) ?
- QS60StyleEnums::SP_QgnGrafScrollArrowUp :
- QS60StyleEnums::SP_QgnGrafScrollArrowDown;
- const int iconMargin = QS60StylePrivate::pixelMetric(PM_FrameCornerWidth) >> 1;
- optionSpinBox.rect.translate(0, (element == PE_IndicatorSpinDown) ? iconMargin : -iconMargin );
- QS60StylePrivate::drawSkinPart(part, painter, optionSpinBox.rect, flags);
- } else {
- commonStyleDraws = true;
- }
- }
-#endif //QT_NO_SPINBOX
-#ifndef QT_NO_COMBOBOX
- if (const QStyleOptionFrame *cmb = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- if (QS60StylePrivate::canDrawThemeBackground( option->palette.base(), widget)) {
- // We want to draw down arrow here for comboboxes as well.
- QStyleOptionFrame optionsComboBox = *cmb;
- const QS60StyleEnums::SkinParts part = QS60StyleEnums::SP_QgnGrafScrollArrowDown;
- const int iconMargin = QS60StylePrivate::pixelMetric(PM_FrameCornerWidth) >> 1;
- optionsComboBox.rect.translate(0, (element == PE_IndicatorSpinDown) ? iconMargin : -iconMargin );
- QS60StylePrivate::drawSkinPart(part, painter, optionsComboBox.rect, flags);
- } else {
- commonStyleDraws = true;
- }
- }
-#endif //QT_NO_COMBOBOX
- break;
- case PE_IndicatorSpinMinus:
- case PE_IndicatorSpinPlus:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QStyleOptionSpinBox optionSpinBox = *spinBox;
- QCommonStyle::drawPrimitive(element, &optionSpinBox, painter, widget);
- }
-#ifndef QT_NO_COMBOBOX
- else if (const QStyleOptionFrame *cmb = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- // We want to draw down arrow here for comboboxes as well.
- QStyleOptionFrame comboBox = *cmb;
- const int frameWidth = QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth);
- comboBox.rect.adjust(0, frameWidth, 0, -frameWidth);
- QCommonStyle::drawPrimitive(element, &comboBox, painter, widget);
- }
-#endif //QT_NO_COMBOBOX
- break;
- case PE_Widget:
- if (QS60StylePrivate::drawsOwnThemeBackground(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<const QComboBoxListView *>(widget)
-#endif //QT_NO_COMBOBOX
-#ifndef QT_NO_MENU
- || qobject_cast<const QMenu *> (widget)
-#endif //QT_NO_MENU
- ) {
- //Need extra check since dialogs have their own theme background
- if (QS60StylePrivate::canDrawThemeBackground(option->palette.base(), widget)
- && QS60StylePrivate::equalToThemePalette(option->palette.window().texture().cacheKey(), QPalette::Window)) {
- const bool comboMenu = qobject_cast<const QComboBoxListView *>(widget);
- // Add margin area to the background, to avoid background being cut for first and last item.
- const int verticalMenuAdjustment = comboMenu ? QS60StylePrivate::pixelMetric(PM_MenuVMargin) : 0;
- const QRect adjustedMenuRect = option->rect.adjusted(0, -verticalMenuAdjustment, 0, verticalMenuAdjustment);
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_PopupBackground, painter, adjustedMenuRect, flags);
- } else {
- commonStyleDraws = true;
- }
- }
- break;
- case PE_FrameWindow:
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *tabFrame = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option)) {
- QStyleOptionTabWidgetFrame optionTabFrame = *tabFrame;
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_PanelBackground, painter, optionTabFrame.rect, flags);
- }
- break;
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- if (header->sortIndicator & QStyleOptionHeader::SortUp)
- drawPrimitive(PE_IndicatorArrowUp, header, painter, widget);
- else if (header->sortIndicator & QStyleOptionHeader::SortDown)
- drawPrimitive(PE_IndicatorArrowDown, header, painter, widget);
- } // QStyleOptionHeader::None is not drawn => not needed
- break;
-#ifndef QT_NO_GROUPBOX
- case PE_FrameGroupBox:
- if (const QStyleOptionFrameV2 *frame = qstyleoption_cast<const QStyleOptionFrameV2 *>(option))
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_SettingsList, painter, frame->rect, flags);
- break;
-#endif //QT_NO_GROUPBOX
-
- // Qt3 primitives are not supported
- case PE_Q3CheckListController:
- case PE_Q3CheckListExclusiveIndicator:
- case PE_Q3CheckListIndicator:
- case PE_Q3DockWindowSeparator:
- case PE_Q3Separator:
- Q_ASSERT(false);
- break;
- case PE_Frame:
- break;
-#ifndef QT_NO_ITEMVIEWS
- case PE_PanelItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- const bool isSelected = (vopt->state & State_Selected);
- const bool hasFocus = (vopt->state & State_HasFocus);
- const bool isPressed = QS60StylePrivate::isWidgetPressed(widget);
-
- if (QS60StylePrivate::equalToThemePalette(option->palette.highlight().color(), QPalette::Highlight)) {
- QRect highlightRect = vopt->rect.adjusted(1,1,-1,-1);
- const QAbstractItemView *itemView = qobject_cast<const QAbstractItemView *>(widget);
- QAbstractItemView::SelectionBehavior selectionBehavior =
- itemView ? itemView->selectionBehavior() : QAbstractItemView::SelectItems;
- // Set the draw area for highlights (focus, select rect or pressed rect)
- if (hasFocus || isPressed) {
- if (selectionBehavior != QAbstractItemView::SelectItems) {
- // set highlight rect so that it is continuous from cell to cell, yet sligthly
- // smaller than cell rect
- int xBeginning = 0, yBeginning = 0, xEnd = 0, yEnd = 0;
- if (selectionBehavior == QAbstractItemView::SelectRows) {
- yBeginning = 1; yEnd = -1;
- if (vopt->viewItemPosition == QStyleOptionViewItemV4::Beginning)
- xBeginning = 1;
- else if (vopt->viewItemPosition == QStyleOptionViewItemV4::End)
- xEnd = -1;
- } else if (selectionBehavior == QAbstractItemView::SelectColumns) {
- xBeginning = 1; xEnd = -1;
- if (vopt->viewItemPosition == QStyleOptionViewItemV4::Beginning)
- yBeginning = 1;
- else if (vopt->viewItemPosition == QStyleOptionViewItemV4::End)
- yEnd = -1;
- }
- highlightRect = option->rect.adjusted(xBeginning, yBeginning, xEnd, yEnd);
- }
- }
- bool tableView = false;
- if (itemView && qobject_cast<const QTableView *>(widget))
- tableView = true;
-
- QS60StylePrivate::SkinElements element;
- bool themeGraphicDefined = false;
- QRect elementRect = option->rect;
-
- //draw item is drawn as pressed, if it already has focus.
- if (isPressed && hasFocus) {
- themeGraphicDefined = true;
- element = tableView ? QS60StylePrivate::SE_TableItemPressed : QS60StylePrivate::SE_ListItemPressed;
- } else if (hasFocus || (isSelected && selectionBehavior != QAbstractItemView::SelectItems)) {
- element = QS60StylePrivate::SE_ListHighlight;
- elementRect = highlightRect;
- themeGraphicDefined = true;
- }
- if (themeGraphicDefined)
- QS60StylePrivate::drawSkinElement(element, painter, elementRect, flags);
- } else {
- QCommonStyle::drawPrimitive(element, option, painter, widget);
- }
- }
- break;
-#endif //QT_NO_ITEMVIEWS
-
- case PE_IndicatorMenuCheckMark:
- if (const QStyleOptionMenuItem *checkBox = qstyleoption_cast<const QStyleOptionMenuItem *>(option)){
- QStyleOptionMenuItem optionCheckBox = *checkBox;
- if (optionCheckBox.checked)
- optionCheckBox.state = (optionCheckBox.state | State_On);
- drawPrimitive(PE_IndicatorCheckBox, &optionCheckBox, painter, widget);
- }
- break;
-#ifndef QT_NO_TOOLBAR
- case PE_IndicatorToolBarHandle:
- // no toolbar handles in S60/AVKON UI
- case PE_IndicatorToolBarSeparator:
- // no separators in S60/AVKON UI
- break;
-#endif //QT_NO_TOOLBAR
-
- case PE_PanelMenuBar:
- case PE_FrameMenu:
- break; //disable frame in menu
-
- case PE_IndicatorBranch:
-#if defined(Q_WS_S60)
- // 3.1 AVKON UI does not have tree view component, use common style for drawing there
- if (QSysInfo::s60Version() == QSysInfo::SV_S60_3_1) {
-#else
- if (true) {
-#endif
- QCommonStyle::drawPrimitive(element, option, painter, widget);
- } else {
- if (const QStyleOptionViewItemV2 *vopt = qstyleoption_cast<const QStyleOptionViewItemV2 *>(option)) {
- const bool rightLine = option->state & State_Item;
- const bool downLine = option->state & State_Sibling;
- const bool upLine = option->state & (State_Open | State_Children | State_Item | State_Sibling);
- QS60StylePrivate::SkinElementFlags adjustedFlags = flags;
-
- QS60StyleEnums::SkinParts skinPart;
- bool drawSkinPart = false;
- if (rightLine && downLine && upLine) {
- skinPart = QS60StyleEnums::SP_QgnIndiHlLineBranch;
- drawSkinPart = true;
- } else if (rightLine && upLine) {
- skinPart = QS60StyleEnums::SP_QgnIndiHlLineEnd;
- drawSkinPart = true;
- } else if (upLine && downLine) {
- skinPart = QS60StyleEnums::SP_QgnIndiHlLineStraight;
- drawSkinPart = true;
- }
-
- if (option->direction == Qt::RightToLeft)
- adjustedFlags |= QS60StylePrivate::SF_Mirrored_X_Axis;
-
- if (drawSkinPart)
- QS60StylePrivate::drawSkinPart(skinPart, painter, option->rect, adjustedFlags);
-
- if (option->state & State_Children) {
- QS60StyleEnums::SkinParts skinPart =
- (option->state & State_Open) ? QS60StyleEnums::SP_QgnIndiHlColSuper : QS60StyleEnums::SP_QgnIndiHlExpSuper;
- const QRect selectionRect = subElementRect(SE_ItemViewItemCheckIndicator, vopt, widget);
- const int minDimension = qMin(option->rect.width(), option->rect.height());
- const int magicTweak = (option->direction == Qt::RightToLeft) ? -3 : 3; //@todo: magic
- //The branch indicator icon in S60 is supposed to be superimposed on top of branch lines.
- QRect iconRect(QPoint(option->rect.left() + magicTweak, selectionRect.top() + 1), QSize(minDimension, minDimension));
- if (!QS60StylePrivate::isTouchSupported())
- iconRect.translate(0, -4); //@todo: magic
- QS60StylePrivate::drawSkinPart(skinPart, painter, iconRect, adjustedFlags);
- }
- }
- }
- break;
- case PE_PanelItemViewRow: // ### Qt 5: remove
-#ifndef QT_NO_ITEMVIEWS
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- if (!QS60StylePrivate::equalToThemePalette(vopt->palette.base().texture().cacheKey(), QPalette::Base)) {
- //QPalette::Base has been changed, let commonstyle draw the item
- commonStyleDraws = true;
- } else {
- QPalette::ColorGroup cg = vopt->state & State_Enabled ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & State_Active))
- cg = QPalette::Inactive;
- if (vopt->features & QStyleOptionViewItemV2::Alternate)
- painter->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::AlternateBase));
- //apart from alternate base, no background for list item is drawn for S60Style
- }
- }
-#endif
- break;
- case PE_PanelScrollAreaCorner:
- break;
- case PE_IndicatorItemViewItemDrop:
- if (QS60StylePrivate::isTouchSupported())
- QS60StylePrivate::drawSkinElement(QS60StylePrivate::SE_DropArea, painter, option->rect, flags);
- else
- commonStyleDraws = true;
- break;
- // todo: items are below with #ifdefs "just in case". in final version, remove all non-required cases
- case PE_FrameLineEdit:
- case PE_IndicatorDockWidgetResizeHandle:
- case PE_PanelTipLabel:
-
-#ifndef QT_NO_TABBAR
- case PE_IndicatorTabTear: // No tab tear in S60
-#endif // QT_NO_TABBAR
- case PE_FrameDefaultButton:
-#ifndef QT_NO_DOCKWIDGET
- case PE_FrameDockWidget:
-#endif //QT_NO_DOCKWIDGET
-#ifndef QT_NO_PROGRESSBAR
- case PE_IndicatorProgressChunk:
-#endif //QT_NO_PROGRESSBAR
-#ifndef QT_NO_TOOLBAR
- case PE_PanelToolBar:
-#endif //QT_NO_TOOLBAR
-#ifndef QT_NO_COLUMNVIEW
- case PE_IndicatorColumnViewArrow:
-#endif //QT_NO_COLUMNVIEW
- case PE_FrameTabBarBase: // since tabs are in S60 always in navipane, let's use common style for tab base in Qt.
- default:
- commonStyleDraws = true;
- }
- if (commonStyleDraws) {
- QCommonStyle::drawPrimitive(element, option, painter, widget);
- }
-}
-
-/*! \reimp */
-int QS60Style::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
-{
- int metricValue = QS60StylePrivate::pixelMetric(metric);
- if (metricValue == KNotFound)
- metricValue = QCommonStyle::pixelMetric(metric, option, widget);
-
- // Menu scrollers should be set to zero height for combobox popups
- if (metric == PM_MenuScrollerHeight && !qobject_cast<const QMenu *>(widget))
- metricValue = 0;
-
- //if layout direction is mirrored, switch left and right border margins
- if (option && option->direction == Qt::RightToLeft) {
- if (metric == PM_LayoutLeftMargin)
- metricValue = QS60StylePrivate::pixelMetric(PM_LayoutRightMargin);
- else if (metric == PM_LayoutRightMargin)
- metricValue = QS60StylePrivate::pixelMetric(PM_LayoutLeftMargin);
- }
-
- if (widget && (metric == PM_LayoutTopMargin || metric == PM_LayoutLeftMargin || metric == PM_LayoutRightMargin))
- if (widget->windowType() == Qt::Dialog)
- //double the layout margins (except bottom) for dialogs, it is very close to real value
- //without having to define custom pixel metric
- metricValue *= 2;
-
-#if defined(Q_WS_S60)
- if (metric == PM_TabBarTabOverlap && (QSysInfo::s60Version() > QSysInfo::SV_S60_5_2))
- metricValue = 0;
-#endif
-
- return metricValue;
-}
-
-/*! \reimp */
-QSize QS60Style::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &csz, const QWidget *widget) const
-{
- QSize sz(csz);
- switch (ct) {
- case CT_ToolButton:
- sz = QCommonStyle::sizeFromContents( ct, opt, csz, widget);
- //FIXME properly - style should calculate the location of border frame-part
- sz += QSize(2 * pixelMetric(PM_ButtonMargin), 2 * pixelMetric(PM_ButtonMargin));
- if (const QStyleOptionToolButton *toolBtn = qstyleoption_cast<const QStyleOptionToolButton *>(opt))
- if (toolBtn->subControls & SC_ToolButtonMenu)
- sz += QSize(pixelMetric(PM_MenuButtonIndicator), 0);
-
- //Make toolbuttons in toolbar stretch the whole screen area
- if (widget && qobject_cast<const QToolBar *>(widget->parentWidget())) {
- const QToolBar *tb = qobject_cast<const QToolBar *>(widget->parentWidget());
- const bool parentCanGrowHorizontally = !(tb->sizePolicy().horizontalPolicy() == QSizePolicy::Fixed ||
- tb->sizePolicy().horizontalPolicy() == QSizePolicy::Maximum) && tb->orientation() == Qt::Horizontal;
-
- if (parentCanGrowHorizontally) {
- int buttons = 0;
- //Make the auto-stretch to happen only for horizontal orientation
- if (tb && tb->orientation() == Qt::Horizontal) {
- QList<QAction*> actionList = tb->actions();
- for (int i = 0; i < actionList.count(); i++) {
- buttons++;
- }
- }
-
- if (widget->parentWidget() && buttons > 0) {
- QWidget *w = const_cast<QWidget *>(widget);
- int toolBarMaxWidth = 0;
- int totalMargin = 0;
- while (w) {
- //honor fixed width parents
- if (w->maximumWidth() == w->minimumWidth())
- toolBarMaxWidth = qMax(toolBarMaxWidth, w->maximumWidth());
- if (w->layout() && w->windowType() == Qt::Widget) {
- totalMargin += w->layout()->contentsMargins().left() +
- w->layout()->contentsMargins().right();
- }
- w = w->parentWidget();
- }
- totalMargin += 2 * pixelMetric(QStyle::PM_ToolBarFrameWidth);
-
- if (toolBarMaxWidth == 0)
- toolBarMaxWidth =
- QApplication::desktop()->availableGeometry(widget->parentWidget()).width();
- //Reduce the margins, toolbar frame, item spacing and internal margin from available area
- toolBarMaxWidth -= totalMargin;
-
- //ensure that buttons are side-by-side and not on top of each other
- const int toolButtonWidth = (toolBarMaxWidth / buttons)
- - pixelMetric(QStyle::PM_ToolBarItemSpacing)
- - pixelMetric(QStyle::PM_ToolBarItemMargin)
- //toolbar frame needs to be reduced again, since QToolBarLayout adds it for each toolbar action
- - 2 * pixelMetric(QStyle::PM_ToolBarFrameWidth) - 1;
- sz.setWidth(qMax(toolButtonWidth, sz.width()));
- }
- }
- }
- break;
- case CT_PushButton:
- sz = QCommonStyle::sizeFromContents( ct, opt, csz, widget);
- //FIXME properly - style should calculate the location of border frame-part
- if (const QAbstractButton *buttonWidget = (qobject_cast<const QAbstractButton *>(widget))) {
- if (buttonWidget->isCheckable())
- sz += QSize(pixelMetric(PM_IndicatorWidth) + pixelMetric(PM_CheckBoxLabelSpacing), 0);
- const int iconHeight = (!buttonWidget->icon().isNull()) ? buttonWidget->iconSize().height() : 0;
- const int textHeight = (buttonWidget->text().length() > 0) ?
- buttonWidget->fontMetrics().size(Qt::TextSingleLine, buttonWidget->text()).height() : opt->fontMetrics.height();
- const int decoratorHeight = (buttonWidget->isCheckable()) ? pixelMetric(PM_IndicatorHeight) : 0;
-
- const int contentHeight =
- qMax(qMax(iconHeight, decoratorHeight) + pixelMetric(PM_ButtonMargin),
- textHeight + 2*pixelMetric(PM_ButtonMargin));
- sz.setHeight(qMax(sz.height(), contentHeight));
- sz += QSize(2 * pixelMetric(PM_ButtonMargin), 0);
- }
- break;
- case CT_LineEdit:
- if (const QStyleOptionFrame *f = qstyleoption_cast<const QStyleOptionFrame *>(opt))
- sz += QSize(2 * f->lineWidth, 4 * f->lineWidth);
- break;
- case CT_TabBarTab: {
- sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
- // Adjust beginning tabbar item size, if scrollbuttons are used. This is to ensure that the
- // tabbar item content fits, since scrollbuttons are making beginning tabbar item smaller.
- int scrollButtonSize = 0;
- if (const QTabBar *tabBar = qobject_cast<const QTabBar *>(widget))
- scrollButtonSize = tabBar->usesScrollButtons() ? pixelMetric(PM_TabBarScrollButtonWidth) : 0;
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- const bool verticalTabs = tab->shape == QTabBar::RoundedEast
- || tab->shape == QTabBar::RoundedWest
- || tab->shape == QTabBar::TriangularEast
- || tab->shape == QTabBar::TriangularWest;
- if (tab->position == QStyleOptionTab::Beginning)
- sz += QSize(verticalTabs ? 0 : scrollButtonSize, !verticalTabs ? 0 : scrollButtonSize);
- }
- }
- break;
- case CT_MenuItem:
- case CT_ItemViewItem:
- if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
- sz = QSize(menuItem->rect.width() - 2 * pixelMetric(PM_MenuHMargin) - 2 * QS60StylePrivate::pixelMetric(PM_FrameCornerWidth), 1);
- break;
- }
- }
- sz = QCommonStyle::sizeFromContents( ct, opt, csz, widget);
- if (QS60StylePrivate::isTouchSupported()) {
- //Make itemview easier to use in touch devices
- sz.setHeight(sz.height() + 2 * pixelMetric(PM_FocusFrameVMargin));
- //QCommonStyle does not adjust height with horizontal margin, it only adjusts width
- if (ct == CT_MenuItem)
- sz.setHeight(sz.height() - 8); //QCommonstyle adds 8 to height that this style handles through PM values
- }
- break;
-#ifndef QT_NO_COMBOBOX
- case CT_ComboBox: {
- // Fixing Ui design issues with too wide QComboBoxes and greedy SizeHints
- // Make sure, that the combobox stays within the screen.
- const QSize desktopContentSize = QApplication::desktop()->availableGeometry().size()
- - QSize(pixelMetric(PM_LayoutLeftMargin) + pixelMetric(PM_LayoutRightMargin), 0);
- sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget).
- boundedTo(desktopContentSize);
- }
- break;
-#endif
- default:
- sz = QCommonStyle::sizeFromContents( ct, opt, csz, widget);
- break;
- }
- if (!sz.isValid())
- sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
- return sz;
-}
-
-/*! \reimp */
-int QS60Style::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *widget,
- QStyleHintReturn *hret) const
-{
- int retValue = 0;
- switch (sh) {
- case SH_RequestSoftwareInputPanel:
- if (QS60StylePrivate::isSingleClickUi())
- retValue = RSIP_OnMouseClick;
- else
- retValue = RSIP_OnMouseClickAndAlreadyFocused;
- break;
- case SH_ComboBox_Popup:
- retValue = true;
- break;
- case SH_Table_GridLineColor:
- retValue = int(QS60StylePrivate::s60Color(QS60StyleEnums::CL_QsnLineColors, 2, 0).rgba());
- break;
- case SH_GroupBox_TextLabelColor:
- retValue = int(QS60StylePrivate::s60Color(QS60StyleEnums::CL_QsnTextColors, 6, 0).rgba());
- break;
- case SH_ScrollBar_ScrollWhenPointerLeavesControl:
- retValue = true;
- break;
- case SH_Slider_SnapToValue:
- retValue = true;
- break;
- case SH_Slider_StopMouseOverSlider:
- retValue = true;
- break;
- case SH_LineEdit_PasswordCharacter:
- retValue = '*';
- break;
- case SH_ComboBox_PopupFrameStyle:
- retValue = QFrame::NoFrame | QFrame::Plain;
- break;
- case SH_Dial_BackgroundRole:
- retValue = QPalette::Base;
- break;
- case SH_ItemView_ActivateItemOnSingleClick: {
- if (QS60StylePrivate::isSingleClickUi())
- retValue = true;
- else if (opt && opt->state & QStyle::State_Selected)
- retValue = true;
- break;
- }
- case SH_ProgressDialog_TextLabelAlignment:
- retValue = (QApplication::layoutDirection() == Qt::LeftToRight) ?
- Qt::AlignLeft :
- Qt::AlignRight;
- break;
- case SH_Menu_SubMenuPopupDelay:
- retValue = 300;
- break;
- case SH_Menu_Scrollable:
- retValue = true;
- break;
- case SH_Menu_SelectionWrap:
- retValue = true;
- break;
- case SH_Menu_MouseTracking:
- retValue = true;
- break;
- case SH_ItemView_ShowDecorationSelected:
- retValue = true;
- break;
- case SH_ToolBar_Movable:
- retValue = false;
- break;
- case SH_BlinkCursorWhenTextSelected:
- retValue = true;
- break;
- case SH_UnderlineShortcut:
- retValue = 0;
- break;
- case SH_FormLayoutWrapPolicy:
- retValue = QFormLayout::WrapLongRows;
- break;
- case SH_ScrollBar_ContextMenu:
- retValue = false;
- break;
- default:
- retValue = QCommonStyle::styleHint(sh, opt, widget, hret);
- break;
- }
- return retValue;
-}
-
-/*! \reimp */
-QRect QS60Style::subControlRect(ComplexControl control, const QStyleOptionComplex *option, SubControl scontrol, const QWidget *widget) const
-{
- QRect ret;
- switch (control) {
-#ifndef QT_NO_SCROLLBAR
- // This implementation of subControlRect(CC_ScrollBar..) basically just removes the SC_ScrollBarSubLine and SC_ScrollBarAddLine
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbarOption = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- const QRect scrollBarRect = scrollbarOption->rect;
- const bool isHorizontal = scrollbarOption->orientation == Qt::Horizontal;
- const int maxlen = isHorizontal ? scrollBarRect.width() : scrollBarRect.height();
- int sliderlen;
-
- // calculate slider length
- if (scrollbarOption->maximum != scrollbarOption->minimum) {
- const uint range = scrollbarOption->maximum - scrollbarOption->minimum;
- sliderlen = (qint64(scrollbarOption->pageStep) * maxlen) / (range + scrollbarOption->pageStep);
-
- const int slidermin = pixelMetric(PM_ScrollBarSliderMin, scrollbarOption, widget);
- if (sliderlen < slidermin || range > (INT_MAX >> 1))
- sliderlen = slidermin;
- if (sliderlen > maxlen)
- sliderlen = maxlen;
- } else {
- sliderlen = maxlen;
- }
-
- const int sliderstart = sliderPositionFromValue(scrollbarOption->minimum,
- scrollbarOption->maximum,
- scrollbarOption->sliderPosition,
- maxlen - sliderlen,
- scrollbarOption->upsideDown);
-
- switch (scontrol) {
- case SC_ScrollBarSubPage: // between top/left button and slider
- if (isHorizontal)
- ret.setRect(0, 0, sliderstart, scrollBarRect.height());
- else
- ret.setRect(0, 0, scrollBarRect.width(), sliderstart);
- break;
- case SC_ScrollBarAddPage: { // between bottom/right button and slider
- const int addPageLength = sliderstart + sliderlen;
- if (isHorizontal)
- ret = scrollBarRect.adjusted(addPageLength, 0, 0, 0);
- else
- ret = scrollBarRect.adjusted(0, addPageLength, 0, 0);
- }
- break;
- case SC_ScrollBarGroove:
- ret = scrollBarRect;
- break;
- case SC_ScrollBarSlider:
- if (scrollbarOption->orientation == Qt::Horizontal)
- ret.setRect(sliderstart, 0, sliderlen, scrollBarRect.height());
- else
- ret.setRect(0, sliderstart, scrollBarRect.width(), sliderlen);
- break;
- case SC_ScrollBarSubLine: // top/left button
- case SC_ScrollBarAddLine: // bottom/right button
- default:
- break;
- }
- ret = visualRect(scrollbarOption->direction, scrollBarRect, ret);
- }
- break;
-#endif // QT_NO_SCROLLBAR
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- const int frameThickness = spinbox->frame ? pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
- const int buttonMargin = spinbox->frame ? 2 : 0;
- const int buttonContentWidth = QS60StylePrivate::pixelMetric(PM_ButtonIconSize) + 2 * buttonMargin;
- // Spinbox buttons should be no larger than one fourth of total width.
- // Thus, side-by-side buttons would take half of the total width.
- const int maxSize = qMax(spinbox->rect.width() / 4, buttonContentWidth);
- QSize buttonSize;
- buttonSize.setHeight(qMin(maxSize, qMax(8, spinbox->rect.height() - frameThickness)));
- //width should at least be equal to height
- buttonSize.setWidth(qMax(buttonSize.height(), buttonContentWidth));
- buttonSize = buttonSize.expandedTo(QApplication::globalStrut());
-
- // Normally spinbuttons should be side-by-side, but if spinbox grows very big
- // and spinbuttons reach their maximum size, they can be deployed one top of the other.
- const bool sideBySide = (buttonSize.height() * 2 < spinbox->rect.height()) ? false : true;
- const int y = frameThickness + spinbox->rect.y() +
- (spinbox->rect.height() - (sideBySide ? 1 : 2) * buttonSize.height()) / 2;
- const int x = spinbox->rect.x() +
- spinbox->rect.width() - frameThickness - (sideBySide ? 2 : 1) * buttonSize.width();
-
- switch (scontrol) {
- case SC_SpinBoxUp:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- ret = QRect(x, y, buttonSize.width(), buttonSize.height());
- break;
- case SC_SpinBoxDown:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- return QRect();
- ret = QRect(x + (sideBySide ? buttonSize.width() : 0),
- y + (sideBySide ? 0 : buttonSize.height()),
- buttonSize.width(), buttonSize.height());
- break;
- case SC_SpinBoxEditField:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
- ret = QRect(
- frameThickness,
- frameThickness,
- spinbox->rect.width() - 2 * frameThickness,
- spinbox->rect.height() - 2 * frameThickness);
- else
- ret = QRect(
- frameThickness,
- frameThickness,
- x - frameThickness,
- spinbox->rect.height() - 2 * frameThickness);
- break;
- case SC_SpinBoxFrame:
- ret = spinbox->rect;
- break;
- default:
- break;
- }
- ret = visualRect(spinbox->direction, spinbox->rect, ret);
- }
- break;
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- ret = cmb->rect;
- const int width = cmb->rect.width();
- const int height = cmb->rect.height();
- const int buttonMargin = cmb->frame ? 2 : 0;
- // lets use spinbox frame here as well, as no combobox specific value available.
- const int frameThickness = cmb->frame ? pixelMetric(PM_SpinBoxFrameWidth, cmb, widget) : 0;
- const int buttonMinSize = QS60StylePrivate::pixelMetric(PM_ButtonIconSize) + 2 * buttonMargin;
- QSize buttonSize;
- //allow button to grow to one fourth of the frame height, if the frame is really tall
- buttonSize.setHeight(qMin(height, qMax(width / 4, buttonMinSize)));
- buttonSize.setWidth(buttonSize.height());
- buttonSize = buttonSize.expandedTo(QApplication::globalStrut());
- switch (scontrol) {
- case SC_ComboBoxArrow: {
- const int xposMod = cmb->rect.x() + width - buttonMargin - buttonSize.width();
- const int ypos = cmb->rect.y();
- ret.setRect(xposMod, ypos + buttonMargin, buttonSize.width(), height - 2 * buttonMargin);
- }
- break;
- case SC_ComboBoxEditField: {
- ret = QRect(0, 0, cmb->rect.x() + width - buttonSize.width(), height);
- }
- break;
- case SC_ComboBoxListBoxPopup: {
- ret = QApplication::desktop()->availableGeometry();
- }
- break;
- default:
- break;
- }
- ret = visualRect(cmb->direction, cmb->rect, ret);
- }
- break;
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- ret = QCommonStyle::subControlRect(control, option, scontrol, widget);
- switch (scontrol) {
- case SC_GroupBoxCheckBox: //fallthrough
- case SC_GroupBoxLabel: {
- //slightly indent text and boxes, so that dialog border does not mess with them.
- const int horizontalSpacing =
- QS60StylePrivate::pixelMetric(PM_LayoutHorizontalSpacing);
- ret.adjust(2, horizontalSpacing - 3, 0, 0);
- }
- break;
- case SC_GroupBoxFrame: {
- const QRect textBox = subControlRect(control, option, SC_GroupBoxLabel, widget);
- const int tbHeight = textBox.height();
- ret.translate(0, -ret.y());
- // include title to within the groupBox frame
- ret.setHeight(ret.height() + tbHeight);
- if (widget && ret.bottom() > widget->rect().bottom())
- ret.setBottom(widget->rect().bottom());
- }
- break;
- default:
- break;
- }
- }
- break;
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolButton = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- const int indicatorRect = pixelMetric(PM_MenuButtonIndicator) + 2 * pixelMetric(PM_ButtonMargin);
- const int border = pixelMetric(PM_ButtonMargin) + pixelMetric(PM_DefaultFrameWidth);
- ret = toolButton->rect;
- const bool popup = (toolButton->features &
- (QStyleOptionToolButton::MenuButtonPopup | QStyleOptionToolButton::PopupDelay))
- == QStyleOptionToolButton::MenuButtonPopup;
- switch (scontrol) {
- case SC_ToolButton:
- if (popup)
- ret.adjust(0, 0, -indicatorRect, 0);
- break;
- case SC_ToolButtonMenu:
- if (popup)
- ret.adjust(ret.width() - indicatorRect, border, -pixelMetric(PM_ButtonMargin), -border);
- break;
- default:
- break;
- }
- ret = visualRect(toolButton->direction, toolButton->rect, ret);
- }
- break;
- default:
- ret = QCommonStyle::subControlRect(control, option, scontrol, widget);
- }
- return ret;
-}
-
-/*!
- \reimp
-*/
-QRect QS60Style::subElementRect(SubElement element, const QStyleOption *opt, const QWidget *widget) const
-{
- QRect ret;
- switch (element) {
- case SE_RadioButtonFocusRect:
- ret = opt->rect;
- break;
- case SE_LineEditContents: {
- // in S60 the input text box doesn't start from line Edit's TL, but
- // a bit indented (8 pixels).
- const int KLineEditDefaultIndention = 8;
- ret = visualRect(
- opt->direction, opt->rect, opt->rect.adjusted(KLineEditDefaultIndention, 0, 0, 0));
- }
- break;
- case SE_TabBarTearIndicator:
- ret = QRect(0, 0, 0, 0);
- break;
- case SE_TabWidgetTabBar:
- if (const QStyleOptionTabWidgetFrame *optionTab = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- ret = QCommonStyle::subElementRect(element, opt, widget);
-
- if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- const int borderThickness =
- QS60StylePrivate::pixelMetric(PM_DefaultFrameWidth);
- int tabOverlap = pixelMetric(PM_TabBarTabOverlap);
- if (tabOverlap > borderThickness)
- tabOverlap -= borderThickness;
- const QTabWidget *tab = qobject_cast<const QTabWidget *>(widget);
- int gain = (tab) ? tabOverlap * tab->count() : 0;
- switch (twf->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth: {
- if (widget) {
- // make sure that gain does not set the rect outside of widget boundaries
- if (twf->direction == Qt::RightToLeft) {
- if ((ret.left() - gain) < widget->rect().left())
- gain = widget->rect().left() - ret.left();
- ret.adjust(-gain, 0, 0, 0);
- } else {
- if ((ret.right() + gain) > widget->rect().right())
- gain = widget->rect().right() - ret.right();
- ret.adjust(0, 0, gain, 0);
- }
- }
- break;
- }
- default: {
- if (widget) {
- if ((ret.bottom() + gain) > widget->rect().bottom())
- gain = widget->rect().bottom() - ret.bottom();
- ret.adjust(0, 0, 0, gain);
- }
- break;
- }
- }
- }
- }
- break;
- case SE_ItemViewItemText:
- case SE_ItemViewItemDecoration:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- const QAbstractItemView *listItem = qobject_cast<const QAbstractItemView *>(widget);
- const bool multiSelection = !listItem ? false :
- listItem->selectionMode() == QAbstractItemView::MultiSelection ||
- listItem->selectionMode() == QAbstractItemView::ExtendedSelection ||
- listItem->selectionMode() == QAbstractItemView::ContiguousSelection;
- ret = QCommonStyle::subElementRect(element, opt, widget);
- // If both multiselect & check-state, then remove checkbox and move
- // text and decoration towards the beginning
- if (listItem &&
- multiSelection &&
- (vopt->features & QStyleOptionViewItemV2::HasCheckIndicator)) {
- const int verticalSpacing =
- QS60StylePrivate::pixelMetric(PM_LayoutVerticalSpacing);
- //const int horizontalSpacing = QS60StylePrivate::pixelMetric(PM_LayoutHorizontalSpacing);
- const int checkBoxRectWidth = subElementRect(SE_ItemViewItemCheckIndicator, opt, widget).width();
- ret.adjust(-checkBoxRectWidth - verticalSpacing, 0, -checkBoxRectWidth - verticalSpacing, 0);
- }
- } else if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- const bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
- const int indicatorWidth = checkable ?
- pixelMetric(PM_ListViewIconSize, opt, widget) :
- pixelMetric(PM_SmallIconSize, opt, widget);
- ret = menuItem->rect;
-
- QRect checkBoxRect = checkable ? menuItem->rect : QRect();
- if (checkable) {
- checkBoxRect.setWidth(pixelMetric(PM_IndicatorWidth));
- checkBoxRect.setHeight(pixelMetric(PM_IndicatorHeight));
- }
-
- const int vSpacing = QS60StylePrivate::pixelMetric(PM_LayoutVerticalSpacing);
- //The vertical spacing is doubled; it needs one spacing to separate checkbox from
- //highlight and then it needs one to separate it whatever is shown after it (text/icon/both).
- const int moveByX = checkBoxRect.width() + 2 * vSpacing;
-
- if (element == SE_ItemViewItemDecoration) {
- if (menuItem->icon.isNull()) {
- ret = QRect();
- } else {
- if (menuItem->direction == Qt::RightToLeft)
- ret.translate(ret.width() - indicatorWidth - moveByX, 0);
- else
- ret.translate(moveByX, 0);
- ret.setWidth(indicatorWidth);
- }
- } else {
- if (!menuItem->icon.isNull()) {
- if (menuItem->direction == Qt::LeftToRight)
- ret.adjust(indicatorWidth, 0, 0, 0);
- else
- ret.adjust(0, 0, -indicatorWidth, 0);
- }
- if (menuItem->direction == Qt::LeftToRight)
- ret.adjust(moveByX, 0, 0, 0);
- else
- ret.adjust(0, 0, -moveByX, 0);
-
- // Make room for submenu indicator
- if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu){
- // submenu indicator is very small, so lets halve the rect
- if (menuItem->direction == Qt::LeftToRight)
- ret.adjust(0, 0, -(indicatorWidth >> 1), 0);
- else
- ret.adjust((indicatorWidth >> 1), 0, 0, 0);
- }
- }
- }
- break;
- case SE_ItemViewItemCheckIndicator:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- const QAbstractItemView *listItem = qobject_cast<const QAbstractItemView *>(widget);
-
- const bool singleSelection = listItem &&
- (listItem->selectionMode() == QAbstractItemView::SingleSelection ||
- listItem->selectionMode() == QAbstractItemView::NoSelection);
- const bool checkBoxOnly = (vopt->features & QStyleOptionViewItemV2::HasCheckIndicator) &&
- listItem &&
- singleSelection && vopt->text.isEmpty() && vopt->icon.isNull();
-
- // Selection check mark rect.
- const int indicatorWidth = QS60StylePrivate::pixelMetric(PM_IndicatorWidth);
- const int indicatorHeight = QS60StylePrivate::pixelMetric(PM_IndicatorHeight);
- const int spacing = QS60StylePrivate::pixelMetric(PM_CheckBoxLabelSpacing);
-
- const int itemHeight = opt->rect.height();
- int heightOffset = 0;
- if (indicatorHeight < itemHeight)
- heightOffset = ((itemHeight - indicatorHeight) >> 1);
- if (checkBoxOnly) {
- // Move rect and make it slightly smaller, so that
- // a) highlight border does not cross the rect
- // b) in s60 list checkbox is smaller than normal checkbox
- //todo; magic three
- ret.setRect(opt->rect.left() + 3, opt->rect.top() + heightOffset,
- indicatorWidth - 3, indicatorHeight - 3);
- } else {
- ret.setRect(opt->rect.right() - indicatorWidth - spacing, opt->rect.top() + heightOffset,
- indicatorWidth, indicatorHeight);
- }
- } else {
- ret = QCommonStyle::subElementRect(element, opt, widget);
- }
- break;
- case SE_HeaderLabel:
- ret = QCommonStyle::subElementRect(element, opt, widget);
- if (qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- // Subtract area needed for line
- if (opt->state & State_Horizontal)
- ret.setHeight(ret.height() - QS60StylePrivate::pixelMetric(PM_BoldLineWidth));
- else
- ret.setWidth(ret.width() - QS60StylePrivate::pixelMetric(PM_ThinLineWidth));
- }
- ret = visualRect(opt->direction, opt->rect, ret);
- break;
- case SE_RadioButtonIndicator: {
- const int height = pixelMetric(PM_ExclusiveIndicatorHeight, opt, widget);
- ret.setRect(opt->rect.x(), opt->rect.y() + ((opt->rect.height() - height) >> 1),
- pixelMetric(PM_ExclusiveIndicatorWidth, opt, widget), height);
- ret.translate(2, 0); //move indicator slightly to avoid highlight crossing over it
- ret = visualRect(opt->direction, opt->rect, ret);
- }
- break;
- case SE_CheckBoxIndicator: {
- const int height = pixelMetric(PM_IndicatorHeight, opt, widget);
- ret.setRect(opt->rect.x(), opt->rect.y() + ((opt->rect.height() - height) >> 1),
- pixelMetric(PM_IndicatorWidth, opt, widget), height);
- ret.translate(2, 0); //move indicator slightly to avoid highlight crossing over it
- ret = visualRect(opt->direction, opt->rect, ret);
- }
- break;
- case SE_CheckBoxFocusRect:
- ret = opt->rect;
- break;
- case SE_ProgressBarLabel:
- case SE_ProgressBarContents:
- case SE_ProgressBarGroove:
- ret = opt->rect;
- break;
- default:
- ret = QCommonStyle::subElementRect(element, opt, widget);
- }
- return ret;
-}
-
-/*!
- \reimp
- */
-void QS60Style::polish(QWidget *widget)
-{
- Q_D(const QS60Style);
- QCommonStyle::polish(widget);
-
- if (!widget)
- return;
-
- //Currently we only support animations in QProgressBar.
-#ifndef QT_NO_PROGRESSBAR
- if (qobject_cast<QProgressBar *>(widget))
- widget->installEventFilter(this);
-#endif
-
- if (false
-#ifndef QT_NO_SCROLLBAR
- || qobject_cast<QScrollBar *>(widget)
-#endif
- ) {
- widget->setAttribute(Qt::WA_OpaquePaintEvent, false);
- }
-
- if (QS60StylePrivate::drawsOwnThemeBackground(widget)) {
- widget->setAttribute(Qt::WA_StyledBackground);
- } else if (false
-#ifndef QT_NO_MENU
- || qobject_cast<const QMenu *> (widget)
-#endif // QT_NO_MENU
- ) {
- widget->setAttribute(Qt::WA_StyledBackground);
- } else if (false
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<const QComboBoxListView *>(widget)
-#endif //QT_NO_COMBOBOX
- ) {
- widget->setAttribute(Qt::WA_StyledBackground);
- }
- d->setThemePalette(widget);
- d->setFont(widget);
-}
-
-/*!
- \reimp
- */
-void QS60Style::unpolish(QWidget *widget)
-{
- Q_D(QS60Style);
-
- if (false
- #ifndef QT_NO_SCROLLBAR
- || qobject_cast<QScrollBar *>(widget)
- #endif
- )
- widget->setAttribute(Qt::WA_OpaquePaintEvent);
-
- if (QS60StylePrivate::drawsOwnThemeBackground(widget)) {
- widget->setAttribute(Qt::WA_StyledBackground, false);
- } else if (false
-#ifndef QT_NO_MENU
- || qobject_cast<const QMenu *> (widget)
-#endif // QT_NO_MENU
- ) {
- widget->setAttribute(Qt::WA_StyledBackground, false);
- } else if (false
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<const QComboBoxListView *>(widget)
-#endif //QT_NO_COMBOBOX
- ) {
- widget->setAttribute(Qt::WA_StyledBackground, false);
- }
-
- if (widget)
- widget->setPalette(QPalette());
-
-#if defined(Q_WS_S60) && !defined(QT_NO_PROGRESSBAR)
- if (QProgressBar *bar = qobject_cast<QProgressBar *>(widget)) {
- widget->removeEventFilter(this);
- d->m_bars.removeAll(bar);
- }
-#else
- Q_UNUSED(d)
-#endif
- QCommonStyle::unpolish(widget);
-}
-
-/*!
- \reimp
- */
-void QS60Style::polish(QApplication *application)
-{
- Q_D(QS60Style);
- QCommonStyle::polish(qApp);
- d->m_originalPalette = application->palette();
- d->setThemePalette(application);
- if (QS60StylePrivate::isTouchSupported())
- qApp->installEventFilter(this);
-}
-
-/*!
- \reimp
- */
-void QS60Style::unpolish(QApplication *application)
-{
- Q_UNUSED(application)
-
- Q_D(QS60Style);
- QCommonStyle::unpolish(qApp);
- const QPalette newPalette = QApplication::style()->standardPalette();
- QApplication::setPalette(newPalette);
- QApplicationPrivate::setSystemPalette(d->m_originalPalette);
- if (QS60StylePrivate::isTouchSupported())
- qApp->removeEventFilter(this);
-}
-
-/*!
- \reimp
- */
-bool QS60Style::event(QEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- Q_D(QS60Style);
- const QEvent::Type eventType = e->type();
- if ((eventType == QEvent::FocusIn ||
- eventType == QEvent::FocusOut ||
- eventType == QEvent::EnterEditFocus ||
- eventType == QEvent::LeaveEditFocus) &&
- QS60StylePrivate::isTouchSupported())
- return false;
-#endif
-
- switch (e->type()) {
- case QEvent::Timer: {
- QTimerEvent *te = static_cast<QTimerEvent*>(e);
- timerEvent(te);
- }
- break;
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::FocusIn:
- if (QWidget *focusWidget = QApplication::focusWidget()) {
-
- // Menus and combobox popups do not draw focus frame around them
- if (qobject_cast<QComboBoxListView *>(focusWidget) ||
- qobject_cast<QMenu *>(focusWidget))
- break;
-
- if (!d->m_focusFrame)
- d->m_focusFrame = new QFocusFrame(focusWidget);
- d->m_focusFrame->setWidget(focusWidget);
- } else if (d->m_focusFrame) {
- d->m_focusFrame->setWidget(0);
- }
- break;
- case QEvent::FocusOut:
- if (d->m_focusFrame)
- d->m_focusFrame->setWidget(0);
- break;
- case QEvent::EnterEditFocus:
- case QEvent::LeaveEditFocus:
- if (d->m_focusFrame)
- d->m_focusFrame->update();
- break;
-#endif
- default:
- break;
- }
- return false;
-}
-
-/*!
- \internal
- */
-QIcon QS60Style::standardIconImplementation(StandardPixmap standardIcon,
- const QStyleOption *option, const QWidget *widget) const
-{
- QS60StyleEnums::SkinParts part;
- qreal iconHeightMultiplier = 1.0;
- qreal iconWidthMultiplier = 1.0;
- QS60StylePrivate::SkinElementFlags adjustedFlags;
- if (option)
- adjustedFlags = (option->state & State_Enabled || option->state == 0) ?
- QS60StylePrivate::SF_StateEnabled :
- QS60StylePrivate::SF_StateDisabled;
-
- switch(standardIcon) {
- case SP_MessageBoxWarning:
- // By default, S60 messagebox icons have 4:3 ratio. Value is from S60 LAF documentation.
- iconHeightMultiplier = 1.33;
- part = QS60StyleEnums::SP_QgnNoteWarning;
- break;
- case SP_MessageBoxInformation:
- iconHeightMultiplier = 1.33;
- part = QS60StyleEnums::SP_QgnNoteInfo;
- break;
- case SP_MessageBoxCritical:
- iconHeightMultiplier = 1.33;
- part = QS60StyleEnums::SP_QgnNoteError;
- break;
- case SP_MessageBoxQuestion:
- iconHeightMultiplier = 1.33;
- part = QS60StyleEnums::SP_QgnNoteQuery;
- break;
- case SP_ArrowRight:
- part = QS60StyleEnums::SP_QgnIndiNaviArrowRight;
- break;
- case SP_ArrowLeft:
- part = QS60StyleEnums::SP_QgnIndiNaviArrowLeft;
- break;
- case SP_ArrowUp:
- part = QS60StyleEnums::SP_QgnIndiNaviArrowLeft;
- adjustedFlags |= QS60StylePrivate::SF_PointEast;
- break;
- case SP_ArrowDown:
- part = QS60StyleEnums::SP_QgnIndiNaviArrowLeft;
- adjustedFlags |= QS60StylePrivate::SF_PointWest;
- break;
- case SP_ArrowBack:
- if (QApplication::layoutDirection() == Qt::RightToLeft)
- return QS60Style::standardIcon(SP_ArrowRight, option, widget);
- return QS60Style::standardIcon(SP_ArrowLeft, option, widget);
- case SP_ArrowForward:
- if (QApplication::layoutDirection() == Qt::RightToLeft)
- return QS60Style::standardIcon(SP_ArrowLeft, option, widget);
- return QS60Style::standardIcon(SP_ArrowRight, option, widget);
- case SP_ComputerIcon:
- part = QS60StyleEnums::SP_QgnPropPhoneMemcLarge;
- break;
- case SP_DirClosedIcon:
- part = QS60StyleEnums::SP_QgnPropFolderSmall;
- break;
- case SP_DirOpenIcon:
- part = QS60StyleEnums::SP_QgnPropFolderCurrent;
- break;
- case SP_DirIcon:
- part = QS60StyleEnums::SP_QgnPropFolderSmall;
- break;
- case SP_FileDialogNewFolder:
- part = QS60StyleEnums::SP_QgnPropFolderSmallNew;
- break;
- case SP_FileIcon:
- part = QS60StyleEnums::SP_QgnPropFileSmall;
- break;
- case SP_TrashIcon:
- part = QS60StyleEnums::SP_QgnNoteErased;
- break;
- case SP_ToolBarHorizontalExtensionButton:
- part = QS60StyleEnums::SP_QgnIndiSubmenu;
- if (QApplication::layoutDirection() == Qt::RightToLeft)
- adjustedFlags |= QS60StylePrivate::SF_PointSouth;
- break;
- case SP_ToolBarVerticalExtensionButton:
- adjustedFlags |= QS60StylePrivate::SF_PointEast;
- part = QS60StyleEnums::SP_QgnIndiSubmenu;
- break;
- default:
- return QCommonStyle::standardIconImplementation(standardIcon, option, widget);
- }
- const QS60StylePrivate::SkinElementFlags flags = adjustedFlags;
- const int iconDimension = QS60StylePrivate::pixelMetric(PM_ToolBarIconSize);
- const QRect iconSize = (!option) ?
- QRect(0, 0, iconDimension * iconWidthMultiplier, iconDimension * iconHeightMultiplier) : option->rect;
- const QPixmap cachedPixMap(QS60StylePrivate::cachedPart(part, iconSize.size(), 0, flags));
- return cachedPixMap.isNull() ?
- QCommonStyle::standardIconImplementation(standardIcon, option, widget) : QIcon(cachedPixMap);
-}
-
-/*!
- \internal
- Animate indeterminate progress bars only when visible
-*/
-bool QS60Style::eventFilter(QObject *object, QEvent *event)
-{
- Q_D(QS60Style);
- switch(event->type()) {
- case QEvent::MouseButtonPress: {
- QWidget *w = QApplication::widgetAt(QCursor::pos());
- if (w) {
- QWidget *focusW = w->focusProxy();
- if (qobject_cast<QAbstractItemView *>(focusW) ||
- qobject_cast<QRadioButton *>(focusW) ||
- qobject_cast<QCheckBox *>(focusW))
- d->m_pressedWidget = focusW;
- else if (qobject_cast<QAbstractItemView *>(w)||
- qobject_cast<QRadioButton *>(w) ||
- qobject_cast<QCheckBox *>(w))
- d->m_pressedWidget = w;
-
- if (d->m_pressedWidget)
- d->m_pressedWidget->update();
- }
- break;
- }
- case QEvent::MouseButtonRelease: {
- if (d->m_pressedWidget) {
- d->m_pressedWidget->update();
- d->m_pressedWidget = 0;
- }
- break;
- }
- default:
- break;
- }
-
-#ifdef Q_WS_S60
-#ifndef QT_NO_PROGRESSBAR
- switch(event->type()) {
- case QEvent::StyleChange:
- case QEvent::Show:
- if (QProgressBar *bar = qobject_cast<QProgressBar *>(object)) {
- if (!d->m_bars.contains(bar))
- d->m_bars << bar;
- if (d->m_bars.size() == 1) //only start with first animated progressbar
- d->startAnimation(QS60StyleEnums::SP_QgnGrafBarWaitAnim);
- }
- break;
- case QEvent::Destroy:
- case QEvent::Hide:
- if (QProgressBar *bar = reinterpret_cast<QProgressBar *>(object)) {
- d->stopAnimation(QS60StyleEnums::SP_QgnGrafBarWaitAnim);
- d->m_bars.removeAll(bar);
- }
- break;
- default:
- break;
- }
-#endif // QT_NO_PROGRESSBAR
-#endif // Q_WS_S60
- return QCommonStyle::eventFilter(object, event);
-}
-
-/*!
- \internal
- Handle the timer \a event.
-*/
-void QS60Style::timerEvent(QTimerEvent *event)
-{
-#ifdef Q_WS_S60
-#ifndef QT_NO_PROGRESSBAR
- Q_D(QS60Style);
-
- QS60StyleAnimation *progressBarAnimation =
- QS60StylePrivate::animationDefinition(QS60StyleEnums::SP_QgnGrafBarWaitAnim);
-
- if (event->timerId() == progressBarAnimation->timerId()) {
-
- Q_ASSERT(progressBarAnimation->interval() > 0);
-
- if (progressBarAnimation->currentFrame() == progressBarAnimation->frameCount() )
- if (progressBarAnimation->playMode() == QS60StyleEnums::AM_Looping)
- progressBarAnimation->setCurrentFrame(0);
- else
- d->stopAnimation(progressBarAnimation->animationId());
-
- foreach (QProgressBar *bar, d->m_bars) {
- if ((bar->minimum() == 0 && bar->maximum() == 0))
- bar->update();
- }
- progressBarAnimation->setCurrentFrame(progressBarAnimation->currentFrame() + 1);
- }
-#endif // QT_NO_PROGRESSBAR
-#endif // Q_WS_S60
- event->ignore();
-}
-
-extern QPoint qt_s60_fill_background_offset(const QWidget *targetWidget);
-
-bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush)
-{
- // Check if the widget's palette matches placeholder or actual background texture.
- // When accessing backgroundTexture, use parameter value 'true' to avoid creating
- // the texture, if it is not already created.
-
- const QPixmap placeHolder(QS60StylePrivate::placeHolderTexture());
- const QPixmap bg(QS60StylePrivate::backgroundTexture(true));
- if (placeHolder.cacheKey() != brush.texture().cacheKey()
- && bg.cacheKey() != brush.texture().cacheKey())
- return false;
-
- const QPixmap backgroundTexture(QS60StylePrivate::backgroundTexture());
-
- const QPaintDevice *target = painter->device();
- if (target->devType() == QInternal::Widget) {
- const QWidget *widget = static_cast<const QWidget *>(target);
- if (!widget->testAttribute(Qt::WA_TranslucentBackground)) {
- const QVector<QRect> &rects = rgn.rects();
- for (int i = 0; i < rects.size(); ++i) {
- const QRect rect(rects.at(i));
- painter->drawPixmap(rect.topLeft(), backgroundTexture,
- rect.translated(qt_s60_fill_background_offset(widget)));
- }
- }
- }
- return true;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_S60 || QT_PLUGIN
diff --git a/src/gui/styles/qs60style.h b/src/gui/styles/qs60style.h
deleted file mode 100644
index 5f44ca7b9b..0000000000
--- a/src/gui/styles/qs60style.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** 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 QS60STYLE_H
-#define QS60STYLE_H
-
-#include <QtGui/qcommonstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-//Public custom pixel metrics values.
-//These can be used to fetch custom pixel metric value from outside QS60Style.
-enum {
- PM_FrameCornerWidth = QStyle::PM_CustomBase + 1,
- PM_FrameCornerHeight,
- PM_BoldLineWidth,
- PM_ThinLineWidth,
- PM_MessageBoxHeight
- };
-
-class QS60StylePrivate;
-
-class Q_GUI_EXPORT QS60Style : public QCommonStyle
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QS60Style)
-
-public:
- QS60Style();
- ~QS60Style();
-
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = 0) const;
- void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const;
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
- QSize sizeFromContents(ContentsType ct, const QStyleOption *opt, const QSize &contentsSize, const QWidget *w = 0) const;
- int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
- QStyleHintReturn *shret = 0) const;
- QRect subControlRect(ComplexControl control, const QStyleOptionComplex *option, SubControl scontrol, const QWidget *widget = 0) const;
- QRect subElementRect(SubElement element, const QStyleOption *opt, const QWidget *widget = 0) const;
- void polish(QWidget *widget);
- void unpolish(QWidget *widget);
- void polish(QApplication *application);
- void unpolish(QApplication *application);
-#ifndef Q_NO_USING_KEYWORD
- using QCommonStyle::polish;
-#endif
- bool event(QEvent *e);
-
-#ifndef Q_OS_SYMBIAN
- static QStringList partKeys();
- static QStringList colorListKeys();
- void setS60Theme(const QHash<QString, QPicture> &parts,
- const QHash<QPair<QString , int>, QColor> &colors);
- bool loadS60ThemeFromBlob(const QString &blobFile);
- bool saveS60ThemeToBlob(const QString &blobFile) const;
-#endif // !Q_OS_SYMBIAN
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(
- StandardPixmap standardIcon, const QStyleOption * option = 0, const QWidget * widget = 0 ) const;
-
-protected:
- void timerEvent(QTimerEvent *event);
- bool eventFilter(QObject *o, QEvent *e);
-private:
- Q_DISABLE_COPY(QS60Style)
- friend class QStyleFactory;
- friend class QApplicationPrivate;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QS60STYLE_H
diff --git a/src/gui/styles/qs60style_p.h b/src/gui/styles/qs60style_p.h
deleted file mode 100644
index e146a4e3ac..0000000000
--- a/src/gui/styles/qs60style_p.h
+++ /dev/null
@@ -1,638 +0,0 @@
-/****************************************************************************
-**
-** 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 QS60STYLE_P_H
-#define QS60STYLE_P_H
-
-#include "qs60style.h"
-#include "qcommonstyle_p.h"
-#include <QtCore/qhash.h>
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_NAMESPACE
-
-const int MAX_NON_CUSTOM_PIXELMETRICS = 92;
-const int CUSTOMVALUESCOUNT = 5;
-
-const int MAX_PIXELMETRICS = MAX_NON_CUSTOM_PIXELMETRICS + CUSTOMVALUESCOUNT;
-
-typedef struct {
- unsigned short height;
- unsigned short width;
- int major_version;
- int minor_version;
- const char* layoutName;
-} layoutHeader;
-
-#ifdef Q_OS_SYMBIAN
-NONSHARABLE_CLASS (QS60StyleEnums)
-#else
-class QS60StyleEnums
-#endif
-: public QObject
-{
-#ifndef Q_WS_S60
- Q_OBJECT
- Q_ENUMS(FontCategories)
- Q_ENUMS(SkinParts)
- Q_ENUMS(ColorLists)
-#endif // !Q_WS_S60
-
-public:
-
- // S60 definitions within theme
- enum ThemeDefinitions {
- TD_AnimationData,
- };
-
- //Defines which values are contained within animation data (retrieved using TD_AnimationData).
- //Additionally defines the order in which the items are given out in QList<QVariant>.
- enum AnimationData {
- AD_Interval = 0,
- AD_NumberOfFrames,
- AD_AnimationPlayMode, //currently not used as themes seem to contain invalid data
- };
-
- // Animation modes
- enum AnimationMode {
- AM_PlayOnce = 0, //animation is played exactly once
- AM_Looping, //animation is repeated until stopped
- AM_Bounce //animation is played repeatedly until stopped,
- //but frames are played in reverse order every second time
- //(no support yet)
- };
-
- // S60 look-and-feel font categories
- enum FontCategories {
- FC_Undefined,
- FC_Primary,
- FC_Secondary,
- FC_Title,
- FC_PrimarySmall,
- FC_Digital
- };
-
- enum SkinParts {
- SP_QgnGrafBarWaitAnim,
- SP_QgnGrafBarFrameCenter,
- SP_QgnGrafBarFrameSideL,
- SP_QgnGrafBarFrameSideR,
- SP_QgnGrafBarProgress,
- SP_QgnGrafOrgBgGrid,
- SP_QgnGrafScrollArrowDown,
- SP_QgnGrafScrollArrowLeft,
- SP_QgnGrafScrollArrowRight,
- SP_QgnGrafScrollArrowUp,
- SP_QgnGrafTabActiveL,
- SP_QgnGrafTabActiveM,
- SP_QgnGrafTabActiveR,
- SP_QgnGrafTabPassiveL,
- SP_QgnGrafTabPassiveM,
- SP_QgnGrafTabPassiveR,
- SP_QgnGrafNsliderEndLeft,
- SP_QgnGrafNsliderEndRight,
- SP_QgnGrafNsliderMiddle,
- SP_QgnIndiCheckboxOff,
- SP_QgnIndiCheckboxOn,
- SP_QgnIndiHlColSuper, // Available in S60 release 3.2 and later.
- SP_QgnIndiHlExpSuper, // Available in S60 release 3.2 and later.
- SP_QgnIndiHlLineBranch, // Available in S60 release 3.2 and later.
- SP_QgnIndiHlLineEnd, // Available in S60 release 3.2 and later.
- SP_QgnIndiHlLineStraight, // Available in S60 release 3.2 and later.
- SP_QgnIndiMarkedAdd,
- SP_QgnIndiNaviArrowLeft,
- SP_QgnIndiNaviArrowRight,
- SP_QgnIndiRadiobuttOff,
- SP_QgnIndiRadiobuttOn,
- SP_QgnGrafNsliderMarker,
- SP_QgnGrafNsliderMarkerSelected,
- SP_QgnIndiSubmenu,
- SP_QgnNoteErased,
- SP_QgnNoteError,
- SP_QgnNoteInfo,
- SP_QgnNoteOk,
- SP_QgnNoteQuery,
- SP_QgnNoteWarning,
- SP_QgnPropFileSmall,
- SP_QgnPropFolderCurrent,
- SP_QgnPropFolderSmall,
- SP_QgnPropFolderSmallNew,
- SP_QgnPropPhoneMemcLarge,
- SP_QgnFrSctrlButtonCornerTl, // Toolbar button
- SP_QgnFrSctrlButtonCornerTr,
- SP_QgnFrSctrlButtonCornerBl,
- SP_QgnFrSctrlButtonCornerBr,
- SP_QgnFrSctrlButtonSideT,
- SP_QgnFrSctrlButtonSideB,
- SP_QgnFrSctrlButtonSideL,
- SP_QgnFrSctrlButtonSideR,
- SP_QgnFrSctrlButtonCenter,
- SP_QgnFrSctrlButtonCornerTlPressed, // Toolbar button, pressed
- SP_QgnFrSctrlButtonCornerTrPressed,
- SP_QgnFrSctrlButtonCornerBlPressed,
- SP_QgnFrSctrlButtonCornerBrPressed,
- SP_QgnFrSctrlButtonSideTPressed,
- SP_QgnFrSctrlButtonSideBPressed,
- SP_QgnFrSctrlButtonSideLPressed,
- SP_QgnFrSctrlButtonSideRPressed,
- SP_QgnFrSctrlButtonCenterPressed,
- SP_QsnCpScrollHandleBottomPressed, //ScrollBar handle, pressed state
- SP_QsnCpScrollHandleMiddlePressed,
- SP_QsnCpScrollHandleTopPressed,
- SP_QsnBgScreen,
- SP_QsnCpScrollBgBottom,
- SP_QsnCpScrollBgMiddle,
- SP_QsnCpScrollBgTop,
- SP_QsnCpScrollHandleBottom,
- SP_QsnCpScrollHandleMiddle,
- SP_QsnCpScrollHandleTop,
- SP_QsnFrButtonTbCornerTl, // Button, normal state
- SP_QsnFrButtonTbCornerTr,
- SP_QsnFrButtonTbCornerBl,
- SP_QsnFrButtonTbCornerBr,
- SP_QsnFrButtonTbSideT,
- SP_QsnFrButtonTbSideB,
- SP_QsnFrButtonTbSideL,
- SP_QsnFrButtonTbSideR,
- SP_QsnFrButtonTbCenter,
- SP_QsnFrButtonTbCornerTlPressed, // Button, pressed state
- SP_QsnFrButtonTbCornerTrPressed,
- SP_QsnFrButtonTbCornerBlPressed,
- SP_QsnFrButtonTbCornerBrPressed,
- SP_QsnFrButtonTbSideTPressed,
- SP_QsnFrButtonTbSideBPressed,
- SP_QsnFrButtonTbSideLPressed,
- SP_QsnFrButtonTbSideRPressed,
- SP_QsnFrButtonTbCenterPressed,
- SP_QsnFrCaleCornerTl, // calendar grid item
- SP_QsnFrCaleCornerTr,
- SP_QsnFrCaleCornerBl,
- SP_QsnFrCaleCornerBr,
- SP_QsnFrCaleSideT,
- SP_QsnFrCaleSideB,
- SP_QsnFrCaleSideL,
- SP_QsnFrCaleSideR,
- SP_QsnFrCaleCenter,
- SP_QsnFrCaleHeadingCornerTl, // calendar grid header
- SP_QsnFrCaleHeadingCornerTr,
- SP_QsnFrCaleHeadingCornerBl,
- SP_QsnFrCaleHeadingCornerBr,
- SP_QsnFrCaleHeadingSideT,
- SP_QsnFrCaleHeadingSideB,
- SP_QsnFrCaleHeadingSideL,
- SP_QsnFrCaleHeadingSideR,
- SP_QsnFrCaleHeadingCenter,
- SP_QsnFrInputCornerTl, // Text input field
- SP_QsnFrInputCornerTr,
- SP_QsnFrInputCornerBl,
- SP_QsnFrInputCornerBr,
- SP_QsnFrInputSideT,
- SP_QsnFrInputSideB,
- SP_QsnFrInputSideL,
- SP_QsnFrInputSideR,
- SP_QsnFrInputCenter,
- SP_QsnFrListCornerTl, // List background
- SP_QsnFrListCornerTr,
- SP_QsnFrListCornerBl,
- SP_QsnFrListCornerBr,
- SP_QsnFrListSideT,
- SP_QsnFrListSideB,
- SP_QsnFrListSideL,
- SP_QsnFrListSideR,
- SP_QsnFrListCenter,
- SP_QsnFrPopupCornerTl, // Option menu background
- SP_QsnFrPopupCornerTr,
- SP_QsnFrPopupCornerBl,
- SP_QsnFrPopupCornerBr,
- SP_QsnFrPopupSideT,
- SP_QsnFrPopupSideB,
- SP_QsnFrPopupSideL,
- SP_QsnFrPopupSideR,
- SP_QsnFrPopupCenter,
- SP_QsnFrPopupPreviewCornerTl, // tool tip background
- SP_QsnFrPopupPreviewCornerTr,
- SP_QsnFrPopupPreviewCornerBl,
- SP_QsnFrPopupPreviewCornerBr,
- SP_QsnFrPopupPreviewSideT,
- SP_QsnFrPopupPreviewSideB,
- SP_QsnFrPopupPreviewSideL,
- SP_QsnFrPopupPreviewSideR,
- SP_QsnFrPopupPreviewCenter,
- SP_QsnFrSetOptCornerTl, // Settings list
- SP_QsnFrSetOptCornerTr,
- SP_QsnFrSetOptCornerBl,
- SP_QsnFrSetOptCornerBr,
- SP_QsnFrSetOptSideT,
- SP_QsnFrSetOptSideB,
- SP_QsnFrSetOptSideL,
- SP_QsnFrSetOptSideR,
- SP_QsnFrSetOptCenter,
- SP_QsnFrPopupSubCornerTl, // Toolbar background
- SP_QsnFrPopupSubCornerTr,
- SP_QsnFrPopupSubCornerBl,
- SP_QsnFrPopupSubCornerBr,
- SP_QsnFrPopupSubSideT,
- SP_QsnFrPopupSubSideB,
- SP_QsnFrPopupSubSideL,
- SP_QsnFrPopupSubSideR,
- SP_QsnFrPopupSubCenter,
- SP_QsnFrButtonCornerTlInactive, // Inactive button
- SP_QsnFrButtonCornerTrInactive,
- SP_QsnFrButtonCornerBlInactive,
- SP_QsnFrButtonCornerBrInactive,
- SP_QsnFrButtonSideTInactive,
- SP_QsnFrButtonSideBInactive,
- SP_QsnFrButtonSideLInactive,
- SP_QsnFrButtonSideRInactive,
- SP_QsnFrButtonCenterInactive,
- SP_QsnFrGridCornerTlPressed, // Pressed table item
- SP_QsnFrGridCornerTrPressed,
- SP_QsnFrGridCornerBlPressed,
- SP_QsnFrGridCornerBrPressed,
- SP_QsnFrGridSideTPressed,
- SP_QsnFrGridSideBPressed,
- SP_QsnFrGridSideLPressed,
- SP_QsnFrGridSideRPressed,
- SP_QsnFrGridCenterPressed,
- SP_QsnFrListCornerTlPressed, // Pressed list item
- SP_QsnFrListCornerTrPressed,
- SP_QsnFrListCornerBlPressed,
- SP_QsnFrListCornerBrPressed,
- SP_QsnFrListSideTPressed,
- SP_QsnFrListSideBPressed,
- SP_QsnFrListSideLPressed,
- SP_QsnFrListSideRPressed,
- SP_QsnFrListCenterPressed,
- };
-
- enum ColorLists {
- CL_QsnHighlightColors,
- CL_QsnIconColors,
- CL_QsnLineColors,
- CL_QsnOtherColors,
- CL_QsnParentColors,
- CL_QsnTextColors
- };
-};
-
-#ifdef Q_WS_S60
-class CAknBitmapAnimation;
-NONSHARABLE_CLASS (AnimationData) : public QObject
-{
-public:
- AnimationData(const QS60StyleEnums::SkinParts part, int frames, int interval);
-
- const QS60StyleEnums::SkinParts m_id;
- int m_frames;
- int m_interval;
- QS60StyleEnums::AnimationMode m_mode;
-};
-
-
-NONSHARABLE_CLASS (AnimationDataV2) : public AnimationData
-{
-public:
- AnimationDataV2(const AnimationData &data);
- ~AnimationDataV2();
-
- CAknBitmapAnimation *m_animation;
- int m_currentFrame;
- bool m_resourceBased;
- int m_timerId;
-};
-
-
-class QS60StyleAnimation : public QObject
-{
-public:
- QS60StyleAnimation(const QS60StyleEnums::SkinParts part, int frames, int interval);
- ~QS60StyleAnimation();
-
-public:
- QS60StyleEnums::SkinParts animationId() const {return m_currentData->m_id;}
- int frameCount() const { return m_currentData->m_frames;}
- int interval() const {return m_currentData->m_interval;}
- QS60StyleEnums::AnimationMode playMode() const {return m_currentData->m_mode;}
- CAknBitmapAnimation* animationObject() const {return m_currentData->m_animation;}
- bool isResourceBased() const {return m_currentData->m_resourceBased;}
- int timerId() const {return m_currentData->m_timerId;}
- int currentFrame() const {return m_currentData->m_currentFrame;}
-
- void setFrameCount(int frameCount) {m_currentData->m_frames = frameCount;}
- void setInterval(int interval) {m_currentData->m_interval = interval;}
- void setAnimationObject(CAknBitmapAnimation* animation);
- void setResourceBased(bool resourceBased) {m_currentData->m_resourceBased = resourceBased;}
- void setTimerId(int timerId) {m_currentData->m_timerId = timerId;}
- void setCurrentFrame(int currentFrame) {m_currentData->m_currentFrame = currentFrame;}
-
- void resetToDefaults();
-
-private: //data members
- //TODO: consider changing these to non-pointers as the classes are rather small anyway
- AnimationData *m_defaultData;
- AnimationDataV2 *m_currentData;
-};
-
-#endif //Q_WS_S60
-
-
-class QFocusFrame;
-class QProgressBar;
-class QS60StyleAnimation;
-
-// Private class
-#ifdef Q_OS_SYMBIAN
-NONSHARABLE_CLASS (QS60StylePrivate)
-#else
-class QS60StylePrivate
-#endif
-: public QCommonStylePrivate
-{
- Q_DECLARE_PUBLIC(QS60Style)
-
-public:
- QS60StylePrivate();
- ~QS60StylePrivate();
-
- enum SkinElements {
- SE_ButtonNormal,
- SE_ButtonPressed,
- SE_FrameLineEdit,
- SE_ProgressBarGrooveHorizontal,
- SE_ProgressBarIndicatorHorizontal,
- SE_ProgressBarGrooveVertical,
- SE_ProgressBarIndicatorVertical,
- SE_ScrollBarGrooveHorizontal,
- SE_ScrollBarGrooveVertical,
- SE_ScrollBarHandleHorizontal,
- SE_ScrollBarHandleVertical,
- SE_SliderHandleHorizontal,
- SE_SliderHandleVertical,
- SE_SliderHandleSelectedHorizontal,
- SE_SliderHandleSelectedVertical,
- SE_SliderGrooveVertical,
- SE_SliderGrooveHorizontal,
- SE_TabBarTabEastActive,
- SE_TabBarTabEastInactive,
- SE_TabBarTabNorthActive,
- SE_TabBarTabNorthInactive,
- SE_TabBarTabSouthActive,
- SE_TabBarTabSouthInactive,
- SE_TabBarTabWestActive,
- SE_TabBarTabWestInactive,
- SE_ListHighlight,
- SE_PopupBackground,
- SE_SettingsList,
- SE_TableItem,
- SE_TableHeaderItem,
- SE_ToolTip, //own graphic available on 3.2+ releases,
- SE_ToolBar,
- SE_ToolBarButton,
- SE_ToolBarButtonPressed,
- SE_PanelBackground,
- SE_ScrollBarHandlePressedHorizontal,
- SE_ScrollBarHandlePressedVertical,
- SE_ButtonInactive,
- SE_Editor,
- SE_DropArea,
- SE_TableItemPressed,
- SE_ListItemPressed,
- };
-
- enum SkinFrameElements {
- SF_ButtonNormal,
- SF_ButtonPressed,
- SF_FrameLineEdit,
- SF_ListHighlight,
- SF_PopupBackground,
- SF_SettingsList,
- SF_TableItem,
- SF_TableHeaderItem,
- SF_ToolTip,
- SF_ToolBar,
- SF_ToolBarButton,
- SF_ToolBarButtonPressed,
- SF_PanelBackground,
- SF_ButtonInactive,
- SF_TableItemPressed,
- SF_ListItemPressed,
- };
-
- enum SkinElementFlag {
- SF_PointNorth = 0x0001, // North = the default
- SF_PointEast = 0x0002,
- SF_PointSouth = 0x0004,
- SF_PointWest = 0x0008,
-
- SF_StateEnabled = 0x0010, // Enabled = the default
- SF_StateDisabled = 0x0020,
- SF_ColorSkinned = 0x0040, // pixmap is colored with foreground pen color
- SF_Animation = 0x0080,
- SF_Mirrored_X_Axis = 0x0100,
- SF_Mirrored_Y_Axis = 0x0200
- };
-
- enum CacheClearReason {
- CC_UndefinedChange = 0,
- CC_LayoutChange,
- CC_ThemeChange
- };
-
- Q_DECLARE_FLAGS(SkinElementFlags, SkinElementFlag)
-
- // draws skin element
- static void drawSkinElement(SkinElements element, QPainter *painter,
- const QRect &rect, SkinElementFlags flags = KDefaultSkinElementFlags);
- // draws a specific skin part
- static void drawSkinPart(QS60StyleEnums::SkinParts part, QPainter *painter,
- const QRect &rect, SkinElementFlags flags = KDefaultSkinElementFlags);
- // gets pixel metrics value
- static short pixelMetric(int metric);
- // gets color. 'index' is NOT 0-based.
- // It corresponds to the enum key 1-based numbers of TAknsQsnXYZColorsIndex, not the values.
- static QColor s60Color(QS60StyleEnums::ColorLists list,
- int index, const QStyleOption *option);
- // gets state specific color
- static QColor stateColor(const QColor &color, const QStyleOption *option);
- // gets lighter color than base color
- static QColor lighterColor(const QColor &baseColor);
- //deduces if the given widget should have separately themeable background
- static bool drawsOwnThemeBackground(const QWidget *widget);
-
- QFont s60Font(QS60StyleEnums::FontCategories fontCategory,
- int pointSize = -1, bool resolveFontSize = true) const;
- // clears all style caches (fonts, colors, pixmaps)
- void clearCaches(CacheClearReason reason = CC_UndefinedChange);
-
- // themed main background oprations
- void setBackgroundTexture(QApplication *application) const;
- static void deleteBackground();
-
- static bool isTouchSupported();
- static bool isToolBarBackground();
- static bool hasSliderGrooveGraphic();
- static bool isSingleClickUi();
- static bool isWidgetPressed(const QWidget *widget);
-
-#ifdef Q_WS_S60
- static void deleteStoredSettings();
- // calculates average color based on theme graphics (minus borders).
- QColor colorFromFrameGraphics(SkinFrameElements frame) const;
-#endif
- QColor calculatedColor(SkinFrameElements frame) const;
-
- //set theme palette for application
- void setThemePalette(QApplication *application) const;
- //access to theme palette
- static QPalette* themePalette();
-
- static const layoutHeader m_layoutHeaders[];
- static const short data[][MAX_PIXELMETRICS];
-
- void setCurrentLayout(int layoutIndex);
- void setActiveLayout();
- // Pointer
- static short const *m_pmPointer;
- // number of layouts supported by the style
- static const int m_numberOfLayouts;
-
- mutable QHash<QPair<QS60StyleEnums::FontCategories , int>, QFont> m_mappedFontsCache;
-
- // Has one entry per SkinFrameElements
- static const struct frameElementCenter {
- SkinElements element;
- QS60StyleEnums::SkinParts center;
- } m_frameElementsData[];
-
- static QPixmap frame(SkinFrameElements frame, const QSize &size,
- SkinElementFlags flags = KDefaultSkinElementFlags);
- static QPixmap backgroundTexture(bool skipCreation = false);
- static QPixmap placeHolderTexture();
-
-#ifdef Q_WS_S60
- void handleDynamicLayoutVariantSwitch();
- void handleSkinChange();
-#endif // Q_WS_S60
-
- //Checks that the current brush is transparent or has BrushStyle NoBrush,
- //so that theme graphic background can be drawn.
- static bool canDrawThemeBackground(const QBrush &backgroundBrush, const QWidget *widget);
-
- static int currentAnimationFrame(QS60StyleEnums::SkinParts part);
-#ifdef Q_WS_S60
-
- //No support for animations on emulated style
- void startAnimation(QS60StyleEnums::SkinParts animation);
- void stopAnimation(QS60StyleEnums::SkinParts animation);
- static QS60StyleAnimation* animationDefinition(QS60StyleEnums::SkinParts part);
- static void removeAnimations();
-
-#endif
-
-private:
- static void drawPart(QS60StyleEnums::SkinParts part, QPainter *painter,
- const QRect &rect, SkinElementFlags flags = KDefaultSkinElementFlags);
- static void drawRow(QS60StyleEnums::SkinParts start, QS60StyleEnums::SkinParts middle,
- QS60StyleEnums::SkinParts end, Qt::Orientation orientation, QPainter *painter,
- const QRect &rect, SkinElementFlags flags = KDefaultSkinElementFlags);
- static void drawFrame(SkinFrameElements frame, QPainter *painter,
- const QRect &rect, SkinElementFlags flags = KDefaultSkinElementFlags);
-
- static QPixmap cachedPart(QS60StyleEnums::SkinParts part, const QSize &size,
- QPainter *painter, SkinElementFlags flags = KDefaultSkinElementFlags);
- static QPixmap cachedFrame(SkinFrameElements frame, const QSize &size,
- SkinElementFlags flags = KDefaultSkinElementFlags);
-
- // set S60 font for widget
- void setFont(QWidget *widget) const;
- static void setThemePalette(QWidget *widget);
- void setThemePalette(QPalette *palette) const;
- static void setThemePaletteHash(QPalette *palette);
- static void storeThemePalette(QPalette *palette);
- static void deleteThemePalette();
- static bool equalToThemePalette(QColor color, QPalette::ColorRole role);
- static bool equalToThemePalette(qint64 cacheKey, QPalette::ColorRole role);
-
- static QSize partSize(QS60StyleEnums::SkinParts part,
- SkinElementFlags flags = KDefaultSkinElementFlags);
- static QPixmap part(QS60StyleEnums::SkinParts part, const QSize &size,
- QPainter *painter, SkinElementFlags flags = KDefaultSkinElementFlags);
-
- static QFont s60Font_specific(QS60StyleEnums::FontCategories fontCategory,
- int pointSize, bool resolveFontSize);
-
- static QSize screenSize();
-
- // Contains background texture.
- static QPixmap *m_background;
- // Placeholder pixmap for the real background texture.
- static QPixmap *m_placeHolderTexture;
-
- const static SkinElementFlags KDefaultSkinElementFlags;
- // defined theme palette
- static QPalette *m_themePalette;
- QPalette m_originalPalette;
-
- QPointer<QFocusFrame> m_focusFrame;
- static qint64 m_webPaletteKey;
-
- static QPointer<QWidget> m_pressedWidget;
-
-#ifdef Q_WS_S60
- //list of progress bars having animation running
- QList<QProgressBar *> m_bars;
-#endif
-
-};
-
-QT_END_NAMESPACE
-
-#endif // QS60STYLE_P_H
diff --git a/src/gui/styles/qs60style_s60.cpp b/src/gui/styles/qs60style_s60.cpp
deleted file mode 100644
index 1e374cbc09..0000000000
--- a/src/gui/styles/qs60style_s60.cpp
+++ /dev/null
@@ -1,1591 +0,0 @@
-/****************************************************************************
-**
-** 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 "qs60style.h"
-#include "qs60style_p.h"
-#include "qpainter.h"
-#include "qstyleoption.h"
-#include "qstyle.h"
-#include "private/qt_s60_p.h"
-#include "private/qpixmap_s60_p.h"
-#include "private/qcore_symbian_p.h"
-#include "private/qvolatileimage_p.h"
-#include "qapplication.h"
-#include "qsettings.h"
-
-#include <w32std.h>
-#include <AknsConstants.h>
-#include <aknconsts.h>
-#include <AknsItemID.h>
-#include <AknsUtils.h>
-#include <AknsDrawUtils.h>
-#include <AknsSkinInstance.h>
-#include <AknsBasicBackgroundControlContext.h>
-#include <avkon.mbg>
-#include <AknFontAccess.h>
-#include <AknLayoutFont.h>
-#include <AknUtils.h>
-#include <aknnavi.h>
-#include <gulicon.h>
-#include <AknBitmapAnimation.h>
-#include <centralrepository.h>
-
-#if !defined(QT_NO_STYLE_S60) || defined(QT_PLUGIN)
-
-QT_BEGIN_NAMESPACE
-
-enum TDrawType {
- EDrawIcon,
- EDrawGulIcon,
- EDrawBackground,
- EDrawAnimation,
- ENoDraw
-};
-
-const TUid personalisationUID = { 0x101F876F };
-
-enum TSupportRelease {
- ES60_None = 0x0000, //indicates that the commonstyle should draw the graphics
- ES60_3_1 = 0x0001,
- ES60_3_2 = 0x0002,
- ES60_5_0 = 0x0004,
- ES60_5_1 = 0x0008,
- ES60_5_2 = 0x0010,
- ES60_5_3 = 0x0020,
- ES60_3_X = ES60_3_1 | ES60_3_2,
- // Releases before Symbian Foundation
- ES60_PreSF = ES60_3_1 | ES60_3_2 | ES60_5_0,
- // Releases before the S60 5.2
- ES60_Pre52 = ES60_3_1 | ES60_3_2 | ES60_5_0 | ES60_5_1,
- // Releases before S60 5.3
- ES60_Pre53 = ES60_3_1 | ES60_3_2 | ES60_5_0 | ES60_5_1 | ES60_5_2,
- // Add all new releases here
- ES60_All = ES60_3_1 | ES60_3_2 | ES60_5_0 | ES60_5_1 | ES60_5_2 | ES60_5_3
-};
-
-typedef struct {
- const TAknsItemID &skinID; // Determines default theme graphics ID.
- TDrawType drawType; // Determines which native drawing routine is used to draw this item.
- int supportInfo; // Defines the S60 versions that use the default graphics.
- // These two, define new graphics that are used in releases other than partMapEntry.supportInfo defined releases.
- // In general, these are given in numeric form to allow style compilation in earlier
- // native releases that do not contain the new graphics.
- int newMajorSkinId;
- int newMinorSkinId;
-} partMapEntry;
-
-AnimationData::AnimationData(const QS60StyleEnums::SkinParts part, int frames, int interval) : m_id(part),
- m_frames(frames), m_interval(interval), m_mode(QS60StyleEnums::AM_Looping)
-{
-}
-
-AnimationDataV2::AnimationDataV2(const AnimationData &data) : AnimationData(data.m_id, data.m_frames, data.m_interval),
- m_animation(0), m_currentFrame(0), m_resourceBased(false), m_timerId(0)
-{
-}
-AnimationDataV2::~AnimationDataV2()
-{
- delete m_animation;
-}
-
-QS60StyleAnimation::QS60StyleAnimation(const QS60StyleEnums::SkinParts part, int frames, int interval)
-{
- QT_TRAP_THROWING(m_defaultData = new (ELeave) AnimationData(part, frames, interval));
- QT_TRAP_THROWING(m_currentData = new (ELeave) AnimationDataV2(*m_defaultData));
-}
-
-QS60StyleAnimation::~QS60StyleAnimation()
-{
- delete m_currentData;
- delete m_defaultData;
-}
-
-void QS60StyleAnimation::setAnimationObject(CAknBitmapAnimation* animation)
-{
- Q_ASSERT(animation);
- if (m_currentData->m_animation)
- delete m_currentData->m_animation;
- m_currentData->m_animation = animation;
-}
-
-void QS60StyleAnimation::resetToDefaults()
-{
- delete m_currentData;
- m_currentData = 0;
- QT_TRAP_THROWING(m_currentData = new (ELeave) AnimationDataV2(*m_defaultData));
-}
-
-class QS60StyleModeSpecifics
-{
-public:
- static QPixmap skinnedGraphics(QS60StyleEnums::SkinParts stylepart,
- const QSize &size, QS60StylePrivate::SkinElementFlags flags);
- static QPixmap skinnedGraphics(QS60StylePrivate::SkinFrameElements frameElement, const QSize &size, QS60StylePrivate::SkinElementFlags flags);
- static QPixmap colorSkinnedGraphics(const QS60StyleEnums::SkinParts &stylepart,
- const QSize &size, QPainter *painter, QS60StylePrivate::SkinElementFlags flags);
- static QColor colorValue(const TAknsItemID &colorGroup, int colorIndex);
- static QPixmap fromFbsBitmap(CFbsBitmap *icon, CFbsBitmap *mask, QS60StylePrivate::SkinElementFlags flags, const TSize& targetSize);
- static bool disabledPartGraphic(QS60StyleEnums::SkinParts &part);
- static bool disabledFrameGraphic(QS60StylePrivate::SkinFrameElements &frame);
- static QPixmap generateMissingThemeGraphic(QS60StyleEnums::SkinParts &part, const QSize &size, QS60StylePrivate::SkinElementFlags flags);
- static TAknsItemID partSpecificThemeId(int part);
-
- static QVariant themeDefinition(QS60StyleEnums::ThemeDefinitions definition, QS60StyleEnums::SkinParts part);
-
-private:
- static QPixmap createSkinnedGraphicsLX(QS60StyleEnums::SkinParts part,
- const QSize &size, QS60StylePrivate::SkinElementFlags flags);
- static QPixmap createSkinnedGraphicsLX(QS60StylePrivate::SkinFrameElements frameElement, const QSize &size, QS60StylePrivate::SkinElementFlags flags);
- static QPixmap colorSkinnedGraphicsLX(const QS60StyleEnums::SkinParts &stylepart,
- const QSize &size, QPainter *painter, QS60StylePrivate::SkinElementFlags flags);
- static void frameIdAndCenterId(QS60StylePrivate::SkinFrameElements frameElement, TAknsItemID &frameId, TAknsItemID &centerId);
- static TRect innerRectFromElement(QS60StylePrivate::SkinFrameElements frameElement, const TRect &outerRect);
- static void fallbackInfo(const QS60StyleEnums::SkinParts &stylePart, TInt &fallbackIndex);
- static bool checkSupport(const int supportedRelease);
- // Array to match the skin ID, fallback graphics and Qt widget graphics.
- static const partMapEntry m_partMap[];
-};
-
-const partMapEntry QS60StyleModeSpecifics::m_partMap[] = {
- /* SP_QgnGrafBarWaitAnim */ {KAknsIIDQgnGrafBarWaitAnim, EDrawAnimation, ES60_All, -1,-1},
- /* SP_QgnGrafBarFrameCenter */ {KAknsIIDQgnGrafBarFrameCenter, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnGrafBarFrameSideL */ {KAknsIIDQgnGrafBarFrameSideL, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnGrafBarFrameSideR */ {KAknsIIDQgnGrafBarFrameSideR, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnGrafBarProgress */ {KAknsIIDQgnGrafBarProgress, EDrawIcon, ES60_All, -1,-1},
- // No drop area for 3.x non-touch devices
- /* SP_QgnGrafOrgBgGrid */ {KAknsIIDNone, EDrawIcon, ES60_3_X, EAknsMajorGeneric ,0x1eba}, //KAknsIIDQgnGrafOrgBgGrid
- /* SP_QgnGrafScrollArrowDown */ {KAknsIIDQgnGrafScrollArrowDown, EDrawGulIcon, ES60_All, -1,-1},
- /* SP_QgnGrafScrollArrowLeft */ {KAknsIIDQgnGrafScrollArrowLeft, EDrawGulIcon, ES60_All, -1,-1},
- /* SP_QgnGrafScrollArrowRight */ {KAknsIIDQgnGrafScrollArrowRight, EDrawGulIcon, ES60_All, -1,-1},
- /* SP_QgnGrafScrollArrowUp */ {KAknsIIDQgnGrafScrollArrowUp, EDrawGulIcon, ES60_All, -1,-1},
-
- // In S60 5.3 there is a new tab graphic
- /* SP_QgnGrafTabActiveL */ {KAknsIIDQgnGrafTabActiveL, EDrawIcon, ES60_Pre53, EAknsMajorSkin, 0x2219}, //KAknsIIDQtgFrTabActiveNormalL
- /* SP_QgnGrafTabActiveM */ {KAknsIIDQgnGrafTabActiveM, EDrawIcon, ES60_Pre53, EAknsMajorSkin, 0x221b}, //KAknsIIDQtgFrTabActiveNormalC
- /* SP_QgnGrafTabActiveR */ {KAknsIIDQgnGrafTabActiveR, EDrawIcon, ES60_Pre53, EAknsMajorSkin, 0x221a}, //KAknsIIDQtgFrTabActiveNormalR
- /* SP_QgnGrafTabPassiveL */ {KAknsIIDQgnGrafTabPassiveL, EDrawIcon, ES60_Pre53, EAknsMajorSkin, 0x2221}, //KAknsIIDQtgFrTabPassiveNormalL
- /* SP_QgnGrafTabPassiveM */ {KAknsIIDQgnGrafTabPassiveM, EDrawIcon, ES60_Pre53, EAknsMajorSkin, 0x2223}, //KAknsIIDQtgFrTabPassiveNormalC
- /* SP_QgnGrafTabPassiveR */ {KAknsIIDQgnGrafTabPassiveR, EDrawIcon, ES60_Pre53, EAknsMajorSkin, 0x2222}, //KAknsIIDQtgFrTabPassiveNormalR
-
- // In 3.1 there is no slider groove.
- /* SP_QgnGrafNsliderEndLeft */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x19cf /* KAknsIIDQgnGrafNsliderEndLeft */},
- /* SP_QgnGrafNsliderEndRight */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x19d0 /* KAknsIIDQgnGrafNsliderEndRight */},
- /* SP_QgnGrafNsliderMiddle */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x19d2 /* KAknsIIDQgnGrafNsliderMiddle */},
- /* SP_QgnIndiCheckboxOff */ {KAknsIIDQgnIndiCheckboxOff, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnIndiCheckboxOn */ {KAknsIIDQgnIndiCheckboxOn, EDrawIcon, ES60_All, -1,-1},
-
- // Following 5 items (SP_QgnIndiHlColSuper - SP_QgnIndiHlLineStraight) are available starting from S60 release 3.2.
- // In 3.1 CommonStyle drawing is used for these QTreeView elements, since no similar icons in AVKON UI.
- /* SP_QgnIndiHlColSuper */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x17d5 /* KAknsIIDQgnIndiHlColSuper */},
- /* SP_QgnIndiHlExpSuper */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x17d6 /* KAknsIIDQgnIndiHlExpSuper */},
- /* SP_QgnIndiHlLineBranch */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x17d7 /* KAknsIIDQgnIndiHlLineBranch */},
- /* SP_QgnIndiHlLineEnd */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x17d8 /* KAknsIIDQgnIndiHlLineEnd */},
- /* SP_QgnIndiHlLineStraight */ {KAknsIIDNone, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x17d9 /* KAknsIIDQgnIndiHlLineStraight */},
- /* SP_QgnIndiMarkedAdd */ {KAknsIIDQgnIndiMarkedAdd, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnIndiNaviArrowLeft */ {KAknsIIDQgnIndiNaviArrowLeft, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnIndiNaviArrowRight */ {KAknsIIDQgnIndiNaviArrowRight, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnIndiRadiobuttOff */ {KAknsIIDQgnIndiRadiobuttOff, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnIndiRadiobuttOn */ {KAknsIIDQgnIndiRadiobuttOn, EDrawIcon, ES60_All, -1,-1},
-
- // In 3.1 there different slider graphic and no pressed state.
- /* SP_QgnGrafNsliderMarker */ {KAknsIIDQgnIndiSliderEdit, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x19d1 /* KAknsIIDQgnGrafNsliderMarker */},
- /* SP_QgnGrafNsliderMarkerSelected */ {KAknsIIDQgnIndiSliderEdit, EDrawIcon, ES60_3_1, EAknsMajorGeneric, 0x1a4a /* KAknsIIDQgnGrafNsliderMarkerSelected */},
- /* SP_QgnIndiSubmenu */ {KAknsIIDQgnIndiSubmenu, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnNoteErased */ {KAknsIIDQgnNoteErased, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnNoteError */ {KAknsIIDQgnNoteError, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnNoteInfo */ {KAknsIIDQgnNoteInfo, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnNoteOk */ {KAknsIIDQgnNoteOk, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnNoteQuery */ {KAknsIIDQgnNoteQuery, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnNoteWarning */ {KAknsIIDQgnNoteWarning, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnPropFileSmall */ {KAknsIIDQgnPropFileSmall, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnPropFolderCurrent */ {KAknsIIDQgnPropFolderCurrent, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnPropFolderSmall */ {KAknsIIDQgnPropFolderSmall, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnPropFolderSmallNew */ {KAknsIIDQgnPropFolderSmallNew, EDrawIcon, ES60_All, -1,-1},
- /* SP_QgnPropPhoneMemcLarge */ {KAknsIIDQgnPropPhoneMemcLarge, EDrawIcon, ES60_All, -1,-1},
-
- // Toolbar graphics is different in 3.1/3.2 vs. 5.0
- /* SP_QgnFrSctrlButtonCornerTl */ {KAknsIIDQsnFrButtonTbCornerTl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2301}, /* KAknsIIDQgnFrSctrlButtonCornerTl*/
- /* SP_QgnFrSctrlButtonCornerTr */ {KAknsIIDQsnFrButtonTbCornerTr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2302},
- /* SP_QgnFrSctrlButtonCornerBl */ {KAknsIIDQsnFrButtonTbCornerBl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2303},
- /* SP_QgnFrSctrlButtonCornerBr */ {KAknsIIDQsnFrButtonTbCornerBr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2304},
- /* SP_QgnFrSctrlButtonSideT */ {KAknsIIDQsnFrButtonTbSideT, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2305},
- /* SP_QgnFrSctrlButtonSideB */ {KAknsIIDQsnFrButtonTbSideB, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2306},
- /* SP_QgnFrSctrlButtonSideL */ {KAknsIIDQsnFrButtonTbSideL, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2307},
- /* SP_QgnFrSctrlButtonSideR */ {KAknsIIDQsnFrButtonTbSideR, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2308},
- /* SP_QgnFrSctrlButtonCenter */ {KAknsIIDQsnFrButtonTbCenter, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2309}, /*KAknsIIDQgnFrSctrlButtonCenter*/
-
- // No pressed state for toolbar button in 3.1/3.2.
- /* SP_QgnFrSctrlButtonCornerTlPressed */ {KAknsIIDQsnFrButtonTbCornerTl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2621}, /*KAknsIIDQgnFrSctrlButtonCornerTlPressed*/
- /* SP_QgnFrSctrlButtonCornerTrPressed */ {KAknsIIDQsnFrButtonTbCornerTr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2622},
- /* SP_QgnFrSctrlButtonCornerBlPressed */ {KAknsIIDQsnFrButtonTbCornerBl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2623},
- /* SP_QgnFrSctrlButtonCornerBrPressed */ {KAknsIIDQsnFrButtonTbCornerBr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2624},
- /* SP_QgnFrSctrlButtonSideTPressed */ {KAknsIIDQsnFrButtonTbSideT, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2625},
- /* SP_QgnFrSctrlButtonSideBPressed */ {KAknsIIDQsnFrButtonTbSideB, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2626},
- /* SP_QgnFrSctrlButtonSideLPressed */ {KAknsIIDQsnFrButtonTbSideL, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2627},
- /* SP_QgnFrSctrlButtonSideRPressed */ {KAknsIIDQsnFrButtonTbSideR, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2628},
- /* SP_QgnFrSctrlButtonCenterPressed */ {KAknsIIDQsnFrButtonTbCenter, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2629},
-
- // 3.1 & 3.2 do not have pressed state for scrollbar, so use normal scrollbar graphics instead.
- /* SP_QsnCpScrollHandleBottomPressed*/ {KAknsIIDQsnCpScrollHandleBottom, EDrawIcon, ES60_3_X, EAknsMajorGeneric, 0x20f8}, /*KAknsIIDQsnCpScrollHandleBottomPressed*/
- /* SP_QsnCpScrollHandleMiddlePressed*/ {KAknsIIDQsnCpScrollHandleMiddle, EDrawIcon, ES60_3_X, EAknsMajorGeneric, 0x20f9}, /*KAknsIIDQsnCpScrollHandleMiddlePressed*/
- /* SP_QsnCpScrollHandleTopPressed*/ {KAknsIIDQsnCpScrollHandleTop, EDrawIcon, ES60_3_X, EAknsMajorGeneric, 0x20fa}, /*KAknsIIDQsnCpScrollHandleTopPressed*/
-
- /* SP_QsnBgScreen */ {KAknsIIDQsnBgScreen, EDrawBackground, ES60_All, -1,-1},
-
- /* SP_QsnCpScrollBgBottom */ {KAknsIIDQsnCpScrollBgBottom, EDrawIcon, ES60_All, -1,-1},
- /* SP_QsnCpScrollBgMiddle */ {KAknsIIDQsnCpScrollBgMiddle, EDrawIcon, ES60_All, -1,-1},
- /* SP_QsnCpScrollBgTop */ {KAknsIIDQsnCpScrollBgTop, EDrawIcon, ES60_All, -1,-1},
-
- /* SP_QsnCpScrollHandleBottom */ {KAknsIIDQsnCpScrollHandleBottom, EDrawIcon, ES60_All, -1,-1},
- /* SP_QsnCpScrollHandleMiddle */ {KAknsIIDQsnCpScrollHandleMiddle, EDrawIcon, ES60_All, -1,-1},
- /* SP_QsnCpScrollHandleTop */ {KAknsIIDQsnCpScrollHandleTop, EDrawIcon, ES60_All, -1,-1},
-
- /* SP_QsnFrButtonTbCornerTl */ {KAknsIIDQsnFrButtonTbCornerTl, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbCornerTr */ {KAknsIIDQsnFrButtonTbCornerTr, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbCornerBl */ {KAknsIIDQsnFrButtonTbCornerBl, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbCornerBr */ {KAknsIIDQsnFrButtonTbCornerBr, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbSideT */ {KAknsIIDQsnFrButtonTbSideT, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbSideB */ {KAknsIIDQsnFrButtonTbSideB, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbSideL */ {KAknsIIDQsnFrButtonTbSideL, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbSideR */ {KAknsIIDQsnFrButtonTbSideR, ENoDraw, ES60_All, -1, -1},
- /* SP_QsnFrButtonTbCenter */ {KAknsIIDQsnFrButtonTbCenter, EDrawIcon, ES60_All, -1, -1},
-
- /* SP_QsnFrButtonTbCornerTlPressed */{KAknsIIDQsnFrButtonTbCornerTlPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbCornerTrPressed */{KAknsIIDQsnFrButtonTbCornerTrPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbCornerBlPressed */{KAknsIIDQsnFrButtonTbCornerBlPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbCornerBrPressed */{KAknsIIDQsnFrButtonTbCornerBrPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbSideTPressed */ {KAknsIIDQsnFrButtonTbSideTPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbSideBPressed */ {KAknsIIDQsnFrButtonTbSideBPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbSideLPressed */ {KAknsIIDQsnFrButtonTbSideLPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbSideRPressed */ {KAknsIIDQsnFrButtonTbSideRPressed, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrButtonTbCenterPressed */ {KAknsIIDQsnFrButtonTbCenterPressed, EDrawIcon, ES60_All, -1,-1},
-
- /* SP_QsnFrCaleCornerTl */ {KAknsIIDQsnFrCaleCornerTl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleCornerTr */ {KAknsIIDQsnFrCaleCornerTr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleCornerBl */ {KAknsIIDQsnFrCaleCornerBl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleCornerBr */ {KAknsIIDQsnFrCaleCornerBr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleSideT */ {KAknsIIDQsnFrCaleSideT, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleSideB */ {KAknsIIDQsnFrCaleSideB, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleSideL */ {KAknsIIDQsnFrCaleSideL, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleSideR */ {KAknsIIDQsnFrCaleSideR, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleCenter */ {KAknsIIDQsnFrCaleCenter, ENoDraw, ES60_All, -1,-1},
-
- /* SP_QsnFrCaleHeadingCornerTl */ {KAknsIIDQsnFrCaleHeadingCornerTl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingCornerTr */ {KAknsIIDQsnFrCaleHeadingCornerTr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingCornerBl */ {KAknsIIDQsnFrCaleHeadingCornerBl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingCornerBr */ {KAknsIIDQsnFrCaleHeadingCornerBr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingSideT */ {KAknsIIDQsnFrCaleHeadingSideT, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingSideB */ {KAknsIIDQsnFrCaleHeadingSideB, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingSideL */ {KAknsIIDQsnFrCaleHeadingSideL, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingSideR */ {KAknsIIDQsnFrCaleHeadingSideR, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrCaleHeadingCenter */ {KAknsIIDQsnFrCaleHeadingCenter, ENoDraw, ES60_All, -1,-1},
-
- /* SP_QsnFrInputCornerTl */ {KAknsIIDQsnFrInputCornerTl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputCornerTr */ {KAknsIIDQsnFrInputCornerTr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputCornerBl */ {KAknsIIDQsnFrInputCornerBl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputCornerBr */ {KAknsIIDQsnFrInputCornerBr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputSideT */ {KAknsIIDQsnFrInputSideT, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputSideB */ {KAknsIIDQsnFrInputSideB, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputSideL */ {KAknsIIDQsnFrInputSideL, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputSideR */ {KAknsIIDQsnFrInputSideR, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrInputCenter */ {KAknsIIDQsnFrInputCenter, ENoDraw, ES60_All, -1,-1},
-
- /* SP_QsnFrListCornerTl */ {KAknsIIDQsnFrListCornerTl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListCornerTr */ {KAknsIIDQsnFrListCornerTr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListCornerBl */ {KAknsIIDQsnFrListCornerBl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListCornerBr */ {KAknsIIDQsnFrListCornerBr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListSideT */ {KAknsIIDQsnFrListSideT, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListSideB */ {KAknsIIDQsnFrListSideB, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListSideL */ {KAknsIIDQsnFrListSideL, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListSideR */ {KAknsIIDQsnFrListSideR, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrListCenter */ {KAknsIIDQsnFrListCenter, ENoDraw, ES60_All, -1,-1},
-
- /* SP_QsnFrPopupCornerTl */ {KAknsIIDQsnFrPopupCornerTl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupCornerTr */ {KAknsIIDQsnFrPopupCornerTr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupCornerBl */ {KAknsIIDQsnFrPopupCornerBl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupCornerBr */ {KAknsIIDQsnFrPopupCornerBr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupSideT */ {KAknsIIDQsnFrPopupSideT, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupSideB */ {KAknsIIDQsnFrPopupSideB, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupSideL */ {KAknsIIDQsnFrPopupSideL, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupSideR */ {KAknsIIDQsnFrPopupSideR, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrPopupCenter */ {KAknsIIDQsnFrPopupCenterSubmenu, ENoDraw, ES60_All, -1,-1},
-
- // ToolTip graphics different in 3.1 vs. 3.2+.
- /* SP_QsnFrPopupPreviewCornerTl */ {KAknsIIDQsnFrPopupCornerTl, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c5}, /* KAknsIIDQsnFrPopupPreviewCornerTl */
- /* SP_QsnFrPopupPreviewCornerTr */ {KAknsIIDQsnFrPopupCornerTr, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c6},
- /* SP_QsnFrPopupPreviewCornerBl */ {KAknsIIDQsnFrPopupCornerBl, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c3},
- /* SP_QsnFrPopupPreviewCornerBr */ {KAknsIIDQsnFrPopupCornerBr, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c4},
- /* SP_QsnFrPopupPreviewSideT */ {KAknsIIDQsnFrPopupSideT, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19ca},
- /* SP_QsnFrPopupPreviewSideB */ {KAknsIIDQsnFrPopupSideB, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c7},
- /* SP_QsnFrPopupPreviewSideL */ {KAknsIIDQsnFrPopupSideL, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c8},
- /* SP_QsnFrPopupPreviewSideR */ {KAknsIIDQsnFrPopupSideR, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c9},
- /* SP_QsnFrPopupPreviewCenter */ {KAknsIIDQsnFrPopupCenter, ENoDraw, ES60_3_1, EAknsMajorSkin, 0x19c2},
-
- /* SP_QsnFrSetOptCornerTl */ {KAknsIIDQsnFrSetOptCornerTl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptCornerTr */ {KAknsIIDQsnFrSetOptCornerTr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptCornerBl */ {KAknsIIDQsnFrSetOptCornerBl, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptCornerBr */ {KAknsIIDQsnFrSetOptCornerBr, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptSideT */ {KAknsIIDQsnFrSetOptSideT, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptSideB */ {KAknsIIDQsnFrSetOptSideB, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptSideL */ {KAknsIIDQsnFrSetOptSideL, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptSideR */ {KAknsIIDQsnFrSetOptSideR, ENoDraw, ES60_All, -1,-1},
- /* SP_QsnFrSetOptCenter */ {KAknsIIDQsnFrSetOptCenter, ENoDraw, ES60_All, -1,-1},
-
- // No toolbar frame for 5.0+ releases.
- /* SP_QsnFrPopupSubCornerTl */ {KAknsIIDQsnFrPopupSubCornerTl, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubCornerTr */ {KAknsIIDQsnFrPopupSubCornerTr, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubCornerBl */ {KAknsIIDQsnFrPopupSubCornerBl, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubCornerBr */ {KAknsIIDQsnFrPopupSubCornerBr, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubSideT */ {KAknsIIDQsnFrPopupSubSideT, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubSideB */ {KAknsIIDQsnFrPopupSubSideB, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubSideL */ {KAknsIIDQsnFrPopupSubSideL, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubSideR */ {KAknsIIDQsnFrPopupSubSideR, ENoDraw, ES60_3_X, -1,-1},
- /* SP_QsnFrPopupSubCenter */ {KAknsIIDQsnFrPopupCenterSubmenu, ENoDraw, ES60_3_X, -1,-1},
-
- // No inactive button graphics in 3.1/3.2
- /* SP_QsnFrButtonCornerTlInactive */ {KAknsIIDQsnFrButtonTbCornerTl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b1}, /*KAknsIIDQsnFrButtonCornerTlInactive*/
- /* SP_QsnFrButtonCornerTrInactive */ {KAknsIIDQsnFrButtonTbCornerTr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b2},
- /* SP_QsnFrButtonCornerBlInactive */ {KAknsIIDQsnFrButtonTbCornerBl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b3},
- /* SP_QsnFrButtonCornerTrInactive */ {KAknsIIDQsnFrButtonTbCornerBr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b4},
- /* SP_QsnFrButtonSideTInactive */ {KAknsIIDQsnFrButtonTbSideT, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b5},
- /* SP_QsnFrButtonSideBInactive */ {KAknsIIDQsnFrButtonTbSideB, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b6},
- /* SP_QsnFrButtonSideLInactive */ {KAknsIIDQsnFrButtonTbSideL, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b7},
- /* SP_QsnFrButtonSideRInactive */ {KAknsIIDQsnFrButtonTbSideR, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x21b8},
- /* SP_QsnFrButtonCenterInactive */ {KAknsIIDQsnFrButtonTbCenter, EDrawIcon, ES60_3_X, EAknsMajorSkin, 0x21b9},
-
- // No pressed down grid in 3.1/3.2
- /* SP_QsnFrGridCornerTlPressed */ {KAknsIIDQsnFrGridCornerTl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2681}, /*KAknsIIDQsnFrGridCornerTlPressed*/
- /* SP_QsnFrGridCornerTrPressed */ {KAknsIIDQsnFrGridCornerTr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2682},
- /* SP_QsnFrGridCornerBlPressed */ {KAknsIIDQsnFrGridCornerBl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2683},
- /* SP_QsnFrGridCornerBrPressed */ {KAknsIIDQsnFrGridCornerBr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2684},
- /* SP_QsnFrGridSideTPressed */ {KAknsIIDQsnFrGridSideT, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2685},
- /* SP_QsnFrGridSideBPressed */ {KAknsIIDQsnFrGridSideB, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2686},
- /* SP_QsnFrGridSideLPressed */ {KAknsIIDQsnFrGridSideL, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2687},
- /* SP_QsnFrGridSideRPressed */ {KAknsIIDQsnFrGridSideR, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2688},
- /* SP_QsnFrGridCenterPressed */ {KAknsIIDQsnFrGridCenter, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2689},
-
- // No pressed down list in 3.1/3.2
- /* SP_QsnFrListCornerTlPressed */ {KAknsIIDQsnFrListCornerTl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x268b}, /*KAknsIIDQsnFrListCornerTlPressed*/
- /* SP_QsnFrListCornerTrPressed */ {KAknsIIDQsnFrListCornerTr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x268c},
- /* SP_QsnFrListCornerBlPressed */ {KAknsIIDQsnFrListCornerBl, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x268d},
- /* SP_QsnFrListCornerBrPressed */ {KAknsIIDQsnFrListCornerBr, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x268e},
- /* SP_QsnFrListSideTPressed */ {KAknsIIDQsnFrListSideT, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x268f},
- /* SP_QsnFrListSideBPressed */ {KAknsIIDQsnFrListSideB, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2690},
- /* SP_QsnFrListSideLPressed */ {KAknsIIDQsnFrListSideL, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2691},
- /* SP_QsnFrListSideRPressed */ {KAknsIIDQsnFrListSideR, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2692},
- /* SP_QsnFrListCenterPressed */ {KAknsIIDQsnFrListCenter, ENoDraw, ES60_3_X, EAknsMajorSkin, 0x2693},
-};
-
-QPixmap QS60StyleModeSpecifics::skinnedGraphics(
- QS60StyleEnums::SkinParts stylepart, const QSize &size,
- QS60StylePrivate::SkinElementFlags flags)
-{
- QPixmap themedImage;
- TRAPD( error, QT_TRYCATCH_LEAVING({
- const QPixmap skinnedImage = createSkinnedGraphicsLX(stylepart, size, flags);
- themedImage = skinnedImage;
- }));
- if (error)
- return themedImage = QPixmap();
- return themedImage;
-}
-
-QPixmap QS60StyleModeSpecifics::skinnedGraphics(
- QS60StylePrivate::SkinFrameElements frame, const QSize &size, QS60StylePrivate::SkinElementFlags flags)
-{
- QPixmap themedImage;
- TRAPD( error, QT_TRYCATCH_LEAVING({
- const QPixmap skinnedImage = createSkinnedGraphicsLX(frame, size, flags);
- themedImage = skinnedImage;
- }));
- if (error)
- return themedImage = QPixmap();
- return themedImage;
-}
-
-QPixmap QS60StyleModeSpecifics::colorSkinnedGraphics(
- const QS60StyleEnums::SkinParts &stylepart, const QSize &size, QPainter *painter,
- QS60StylePrivate::SkinElementFlags flags)
-{
- QPixmap colorGraphics;
- TRAPD(error, QT_TRYCATCH_LEAVING(colorGraphics = colorSkinnedGraphicsLX(stylepart, size, painter, flags)));
- return error ? QPixmap() : colorGraphics;
-}
-
-void QS60StyleModeSpecifics::fallbackInfo(const QS60StyleEnums::SkinParts &stylePart, TInt &fallbackIndex)
-{
- switch(stylePart) {
- case QS60StyleEnums::SP_QgnGrafBarWaitAnim:
- fallbackIndex = EMbmAvkonQgn_graf_bar_wait_1;
- break;
- case QS60StyleEnums::SP_QgnGrafBarFrameCenter:
- fallbackIndex = EMbmAvkonQgn_graf_bar_frame_center;
- break;
- case QS60StyleEnums::SP_QgnGrafBarFrameSideL:
- fallbackIndex = EMbmAvkonQgn_graf_bar_frame_side_l;
- break;
- case QS60StyleEnums::SP_QgnGrafBarFrameSideR:
- fallbackIndex = EMbmAvkonQgn_graf_bar_frame_side_r;
- break;
- case QS60StyleEnums::SP_QgnGrafBarProgress:
- fallbackIndex = EMbmAvkonQgn_graf_bar_progress;
- break;
- case QS60StyleEnums::SP_QgnGrafTabActiveL:
- fallbackIndex = EMbmAvkonQgn_graf_tab_active_l;
- break;
- case QS60StyleEnums::SP_QgnGrafTabActiveM:
- fallbackIndex = EMbmAvkonQgn_graf_tab_active_m;
- break;
- case QS60StyleEnums::SP_QgnGrafTabActiveR:
- fallbackIndex = EMbmAvkonQgn_graf_tab_active_r;
- break;
- case QS60StyleEnums::SP_QgnGrafTabPassiveL:
- fallbackIndex = EMbmAvkonQgn_graf_tab_passive_l;
- break;
- case QS60StyleEnums::SP_QgnGrafTabPassiveM:
- fallbackIndex = EMbmAvkonQgn_graf_tab_passive_m;
- break;
- case QS60StyleEnums::SP_QgnGrafTabPassiveR:
- fallbackIndex = EMbmAvkonQgn_graf_tab_passive_r;
- break;
- case QS60StyleEnums::SP_QgnIndiCheckboxOff:
- fallbackIndex = EMbmAvkonQgn_indi_checkbox_off;
- break;
- case QS60StyleEnums::SP_QgnIndiCheckboxOn:
- fallbackIndex = EMbmAvkonQgn_indi_checkbox_on;
- break;
- case QS60StyleEnums::SP_QgnIndiHlColSuper:
- fallbackIndex = 0x4456; /* EMbmAvkonQgn_indi_hl_col_super */
- break;
- case QS60StyleEnums::SP_QgnIndiHlExpSuper:
- fallbackIndex = 0x4458; /* EMbmAvkonQgn_indi_hl_exp_super */
- break;
- case QS60StyleEnums::SP_QgnIndiHlLineBranch:
- fallbackIndex = 0x445A; /* EMbmAvkonQgn_indi_hl_line_branch */
- break;
- case QS60StyleEnums::SP_QgnIndiHlLineEnd:
- fallbackIndex = 0x445C; /* EMbmAvkonQgn_indi_hl_line_end */
- break;
- case QS60StyleEnums::SP_QgnIndiHlLineStraight:
- fallbackIndex = 0x445E; /* EMbmAvkonQgn_indi_hl_line_straight */
- break;
- case QS60StyleEnums::SP_QgnIndiMarkedAdd:
- fallbackIndex = EMbmAvkonQgn_indi_marked_add;
- break;
- case QS60StyleEnums::SP_QgnIndiNaviArrowLeft:
- fallbackIndex = EMbmAvkonQgn_indi_navi_arrow_left;
- break;
- case QS60StyleEnums::SP_QgnIndiNaviArrowRight:
- fallbackIndex = EMbmAvkonQgn_indi_navi_arrow_right;
- break;
- case QS60StyleEnums::SP_QgnIndiRadiobuttOff:
- fallbackIndex = EMbmAvkonQgn_indi_radiobutt_off;
- break;
- case QS60StyleEnums::SP_QgnIndiRadiobuttOn:
- fallbackIndex = EMbmAvkonQgn_indi_radiobutt_on;
- break;
- case QS60StyleEnums::SP_QgnGrafNsliderMarker:
- fallbackIndex = 17572; /* EMbmAvkonQgn_graf_nslider_marker */
- break;
- case QS60StyleEnums::SP_QgnGrafNsliderMarkerSelected:
- fallbackIndex = 17574; /* EMbmAvkonQgn_graf_nslider_marker_selected */
- break;
- case QS60StyleEnums::SP_QgnIndiSubmenu:
- fallbackIndex = EMbmAvkonQgn_indi_submenu;
- break;
- case QS60StyleEnums::SP_QgnNoteErased:
- fallbackIndex = EMbmAvkonQgn_note_erased;
- break;
- case QS60StyleEnums::SP_QgnNoteError:
- fallbackIndex = EMbmAvkonQgn_note_error;
- break;
- case QS60StyleEnums::SP_QgnNoteInfo:
- fallbackIndex = EMbmAvkonQgn_note_info;
- break;
- case QS60StyleEnums::SP_QgnNoteOk:
- fallbackIndex = EMbmAvkonQgn_note_ok;
- break;
- case QS60StyleEnums::SP_QgnNoteQuery:
- fallbackIndex = EMbmAvkonQgn_note_query;
- break;
- case QS60StyleEnums::SP_QgnNoteWarning:
- fallbackIndex = EMbmAvkonQgn_note_warning;
- break;
- case QS60StyleEnums::SP_QgnPropFileSmall:
- fallbackIndex = EMbmAvkonQgn_prop_file_small;
- break;
- case QS60StyleEnums::SP_QgnPropFolderCurrent:
- fallbackIndex = EMbmAvkonQgn_prop_folder_current;
- break;
- case QS60StyleEnums::SP_QgnPropFolderSmall:
- fallbackIndex = EMbmAvkonQgn_prop_folder_small;
- break;
- case QS60StyleEnums::SP_QgnPropFolderSmallNew:
- fallbackIndex = EMbmAvkonQgn_prop_folder_small_new;
- break;
- case QS60StyleEnums::SP_QgnPropPhoneMemcLarge:
- fallbackIndex = EMbmAvkonQgn_prop_phone_memc_large;
- break;
- default:
- fallbackIndex = -1;
- break;
- }
-}
-
-QPixmap QS60StyleModeSpecifics::colorSkinnedGraphicsLX(
- const QS60StyleEnums::SkinParts &stylepart,
- const QSize &size, QPainter *painter, QS60StylePrivate::SkinElementFlags flags)
-{
- // this function can throw both exceptions and leaves. There are no cleanup dependencies between Qt and Symbian parts.
- const int stylepartIndex = (int)stylepart;
- const TAknsItemID skinId = m_partMap[stylepartIndex].skinID;
-
- TInt fallbackGraphicID = -1;
- HBufC* iconFile = HBufC::NewLC( KMaxFileName );
- fallbackInfo(stylepart, fallbackGraphicID);
-
- TAknsItemID colorGroup = KAknsIIDQsnIconColors;
- TRgb defaultColor = KRgbBlack;
- int colorIndex = -1; //set a bogus value to color index to ensure that painter color is used
- //to color the icon
- if (painter) {
- QRgb widgetColor = painter->pen().color().rgb();
- defaultColor = TRgb(qRed(widgetColor), qGreen(widgetColor), qBlue(widgetColor));
- }
-
- const bool rotatedBy90or270 =
- (flags & (QS60StylePrivate::SF_PointEast | QS60StylePrivate::SF_PointWest));
- const TSize targetSize =
- rotatedBy90or270?TSize(size.height(), size.width()):TSize(size.width(), size.height());
- CFbsBitmap *icon = 0;
- CFbsBitmap *iconMask = 0;
- const TInt fallbackGraphicsMaskID =
- fallbackGraphicID == KErrNotFound?KErrNotFound:fallbackGraphicID+1; //masks are auto-generated as next in mif files
- MAknsSkinInstance* skinInstance = AknsUtils::SkinInstance();
- AknsUtils::CreateColorIconLC(
- skinInstance,
- skinId,
- colorGroup,
- colorIndex,
- icon,
- iconMask,
- AknIconUtils::AvkonIconFileName(),
- fallbackGraphicID,
- fallbackGraphicsMaskID,
- defaultColor);
-
- QPixmap result = fromFbsBitmap(icon, iconMask, flags, targetSize);
- CleanupStack::PopAndDestroy(3); //icon, iconMask, iconFile
- return result;
-}
-
-QColor QS60StyleModeSpecifics::colorValue(const TAknsItemID &colorGroup, int colorIndex)
-{
- TRgb skinnedColor;
- MAknsSkinInstance* skin = AknsUtils::SkinInstance();
- AknsUtils::GetCachedColor(skin, skinnedColor, colorGroup, colorIndex);
- return QColor(skinnedColor.Red(),skinnedColor.Green(),skinnedColor.Blue());
-}
-
-struct QAutoFbsBitmapHeapLock
-{
- QAutoFbsBitmapHeapLock(CFbsBitmap* aBmp) : mBmp(aBmp) { mBmp->LockHeap(); }
- ~QAutoFbsBitmapHeapLock() { mBmp->UnlockHeap(); }
- CFbsBitmap* mBmp;
-};
-
-QPixmap QS60StyleModeSpecifics::fromFbsBitmap(CFbsBitmap *icon, CFbsBitmap *mask, QS60StylePrivate::SkinElementFlags flags, const TSize &targetSize)
-{
- Q_ASSERT(icon);
-
- AknIconUtils::DisableCompression(icon);
- TInt error = AknIconUtils::SetSize(icon, targetSize, EAspectRatioNotPreserved);
-
- if (mask && !error) {
- AknIconUtils::DisableCompression(mask);
- error = AknIconUtils::SetSize(mask, targetSize, EAspectRatioNotPreserved);
- }
- if (error)
- return QPixmap();
-
- QPixmap pixmap;
- QScopedPointer<QPixmapData> pd(QPixmapData::create(0, 0, QPixmapData::PixmapType));
- if (mask) {
- // Try the efficient path with less copying and conversion.
- QVolatileImage img(icon, mask);
- pd->fromNativeType(&img, QPixmapData::VolatileImage);
- if (!pd->isNull())
- pixmap = QPixmap(pd.take());
- }
- if (pixmap.isNull()) {
- // Potentially more expensive path.
- pd->fromNativeType(icon, QPixmapData::FbsBitmap);
- pixmap = QPixmap(pd.take());
- if (mask) {
- pixmap.setAlphaChannel(QPixmap::fromSymbianCFbsBitmap(mask));
- }
- }
-
- if ((flags & QS60StylePrivate::SF_PointEast) ||
- (flags & QS60StylePrivate::SF_PointSouth) ||
- (flags & QS60StylePrivate::SF_PointWest)) {
- QImage iconImage = pixmap.toImage();
- QTransform imageTransform;
- if (flags & QS60StylePrivate::SF_PointEast) {
- imageTransform.rotate(90);
- } else if (flags & QS60StylePrivate::SF_PointSouth) {
- imageTransform.rotate(180);
- iconImage = iconImage.transformed(imageTransform);
- } else if (flags & QS60StylePrivate::SF_PointWest) {
- imageTransform.rotate(270);
- }
- if (imageTransform.isRotating())
- iconImage = iconImage.transformed(imageTransform);
-
- pixmap = QPixmap::fromImage(iconImage);
- }
- if ((flags & QS60StylePrivate::SF_Mirrored_X_Axis) ||
- (flags & QS60StylePrivate::SF_Mirrored_Y_Axis)) {
- QImage iconImage = pixmap.toImage().mirrored(
- flags & QS60StylePrivate::SF_Mirrored_X_Axis,
- flags & QS60StylePrivate::SF_Mirrored_Y_Axis);
- pixmap = QPixmap::fromImage(iconImage);
- }
-
- return pixmap;
-}
-
-bool QS60StylePrivate::isTouchSupported()
-{
- return bool(AknLayoutUtils::PenEnabled());
-}
-
-bool QS60StylePrivate::isToolBarBackground()
-{
- return (QSysInfo::s60Version() == QSysInfo::SV_S60_3_1 || QSysInfo::s60Version() == QSysInfo::SV_S60_3_2);
-}
-
-bool QS60StylePrivate::hasSliderGrooveGraphic()
-{
- return QSysInfo::s60Version() != QSysInfo::SV_S60_3_1;
-}
-
-bool QS60StylePrivate::isSingleClickUi()
-{
- return (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0);
-}
-
-void QS60StylePrivate::deleteStoredSettings()
-{
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- settings.beginGroup(QLatin1String("QS60Style"));
- settings.remove(QString());
- settings.endGroup();
-}
-
-// Since S60Style has 'button' as a graphic, we don't have any native color which to use
-// for QPalette::Button. Therefore S60Style needs to guesstimate palette color by calculating
-// average rgb values for button pixels.
-// Returns Qt::black if there is an issue with the graphics (image is NULL, or no constBits() found).
-QColor QS60StylePrivate::colorFromFrameGraphics(SkinFrameElements frame) const
-{
-#ifndef QT_NO_SETTINGS
- TInt themeID = 0;
- //First we need to fetch active theme ID. We need to store the themeID at the same time
- //as color, so that we can later check if the stored color is still from the same theme.
- //Native side stores active theme UID/Timestamp into central repository.
- int error = 0;
- QT_TRAP_THROWING(
- CRepository *themeRepository = CRepository::NewLC(personalisationUID);
- if (themeRepository) {
- TBuf<32> value; //themeID is currently max of 8 + 1 + 8 characters, but lets have some extra space
- const TUint32 key = 0x00000002; //active theme key in the repository
- error = themeRepository->Get(key, value);
- if (error == KErrNone) {
- TLex lex(value);
- TPtrC numberToken(lex.NextToken());
- if (numberToken.Length())
- error = TLex(numberToken).Val(themeID);
- else
- error = KErrArgument;
- }
- }
- CleanupStack::PopAndDestroy(themeRepository);
- );
-
- QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
- settings.beginGroup(QLatin1String("QS60Style"));
- if (themeID != 0) {
- QVariant buttonColor = settings.value(QLatin1String("ButtonColor"));
- if (!buttonColor.isNull()) {
- //there is a stored color value, lets see if the theme ID matches
- if (error == KErrNone) {
- QVariant themeUID = settings.value(QLatin1String("ThemeUID"));
- if (!themeUID.isNull() && themeUID.toInt() == themeID) {
- QColor storedColor(buttonColor.value<QColor>());
- if (storedColor.isValid())
- return storedColor;
- }
- }
- settings.remove(QString()); //if color was invalid, or theme has been changed, just delete all stored settings
- }
- }
-#endif
-
- QColor color = calculatedColor(frame);
-
-#ifndef QT_NO_SETTINGS
- settings.setValue(QLatin1String("ThemeUID"), QVariant(themeID));
- if (frame == SF_ButtonNormal) //other colors are not currently calculated from graphics
- settings.setValue(QLatin1String("ButtonColor"), QVariant(color));
- settings.endGroup();
-#endif
-
- return color;
-}
-
-QPoint qt_s60_fill_background_offset(const QWidget *targetWidget)
-{
- CCoeControl *control = targetWidget->effectiveWinId();
- TPoint pos(0,0);
- if (control)
- pos = control->PositionRelativeToScreen();
- return QPoint(pos.iX, pos.iY);
-}
-
-QPixmap QS60StyleModeSpecifics::createSkinnedGraphicsLX(
- QS60StyleEnums::SkinParts part, const QSize &size,
- QS60StylePrivate::SkinElementFlags flags)
-{
- // this function can throw both exceptions and leaves. There are no cleanup dependencies between Qt and Symbian parts.
- if (!size.isValid())
- return QPixmap();
-
- // Check release support and change part, if necessary.
- const TAknsItemID skinId = partSpecificThemeId((int)part);
- const int stylepartIndex = (int)part;
- const TDrawType drawType = m_partMap[stylepartIndex].drawType;
- Q_ASSERT(drawType != ENoDraw);
- const bool rotatedBy90or270 =
- (flags & (QS60StylePrivate::SF_PointEast | QS60StylePrivate::SF_PointWest));
- const TSize targetSize =
- rotatedBy90or270 ? TSize(size.height(), size.width()) : qt_QSize2TSize(size);
-
- MAknsSkinInstance* skinInstance = AknsUtils::SkinInstance();
- static const TDisplayMode displayMode = S60->supportsPremultipliedAlpha ? Q_SYMBIAN_ECOLOR16MAP : EColor16MA;
- static const TInt drawParam = S60->supportsPremultipliedAlpha ? KAknsDrawParamDefault : KAknsDrawParamRGBOnly;
-
- QPixmap result;
-
- switch (drawType) {
- case EDrawGulIcon: {
- CGulIcon* icon = AknsUtils::CreateGulIconL( AknsUtils::SkinInstance(), skinId, EFalse );
- if (icon)
- result = fromFbsBitmap(icon->Bitmap(), icon->Mask(), flags, targetSize);
- delete icon;
- break;
- }
- case EDrawIcon: {
- TInt fallbackGraphicID = -1;
- fallbackInfo(part, fallbackGraphicID);
-
- CFbsBitmap *icon = 0;
- CFbsBitmap *iconMask = 0;
- const TInt fallbackGraphicsMaskID =
- fallbackGraphicID == KErrNotFound?KErrNotFound:fallbackGraphicID+1; //masks are auto-generated as next in mif files
-
- AknsUtils::CreateIconL(
- skinInstance,
- skinId,
- icon,
- iconMask,
- AknIconUtils::AvkonIconFileName(),
- fallbackGraphicID ,
- fallbackGraphicsMaskID);
-
- result = fromFbsBitmap(icon, iconMask, flags, targetSize);
- delete icon;
- delete iconMask;
- break;
- }
- case EDrawBackground: {
- // QS60WindowSurface::unlockBitmapHeap();
- CFbsBitmap *background = new (ELeave) CFbsBitmap(); //offscreen
- CleanupStack::PushL(background);
- User::LeaveIfError(background->Create(targetSize, displayMode));
-
- CFbsBitmapDevice *dev = CFbsBitmapDevice::NewL(background);
- CleanupStack::PushL(dev);
- CFbsBitGc *gc = NULL;
- User::LeaveIfError(dev->CreateContext(gc));
- CleanupStack::PushL(gc);
-
- CAknsBasicBackgroundControlContext *bgContext = CAknsBasicBackgroundControlContext::NewL(
- skinId,
- targetSize,
- EFalse);
- CleanupStack::PushL(bgContext);
-
- const TBool drawn = AknsDrawUtils::DrawBackground(
- skinInstance,
- bgContext,
- NULL,
- *gc,
- TPoint(),
- targetSize,
- drawParam);
-
- if (drawn)
- result = fromFbsBitmap(background, NULL, flags, targetSize);
- // if drawing fails in skin server, just ignore the background (probably OOM case)
-
- CleanupStack::PopAndDestroy(4, background); //background, dev, gc, bgContext
- // QS60WindowSurface::lockBitmapHeap();
- break;
- }
- case EDrawAnimation: {
- CFbsBitmap* animationFrame;
- CFbsBitmap* frameMask;
- CAknBitmapAnimation* aknAnimation = 0;
- TBool constructedFromTheme = ETrue;
-
- QS60StyleAnimation* animation = QS60StylePrivate::animationDefinition(part); //ownership is not passed
- if (animation) {
- if (!animation->animationObject() && !animation->isResourceBased()) {// no pre-made item exists, create new animation
- CAknBitmapAnimation* newAnimation = CAknBitmapAnimation::NewL();
- CleanupStack::PushL(newAnimation);
- if (newAnimation)
- constructedFromTheme = newAnimation->ConstructFromSkinL(skinId);
- if (constructedFromTheme && newAnimation->BitmapAnimData()->FrameArray().Count() > 0) {
- animation->setResourceBased(false);
- animation->setAnimationObject(newAnimation); //animation takes ownership
- }
- CleanupStack::Pop(newAnimation);
- }
- //fill-in stored information
- aknAnimation = animation->animationObject();
- constructedFromTheme = !animation->isResourceBased();
- }
-
- const int currentFrame = QS60StylePrivate::currentAnimationFrame(part);
- if (constructedFromTheme && aknAnimation && aknAnimation->BitmapAnimData()->FrameArray().Count() > 0) {
- //Animation was created successfully and contains frames, just fetch current frame
- if(currentFrame >= aknAnimation->BitmapAnimData()->FrameArray().Count())
- User::Leave(KErrOverflow);
- const CBitmapFrameData* frameData = aknAnimation->BitmapAnimData()->FrameArray().At(currentFrame);
- if (frameData) {
- animationFrame = frameData->Bitmap();
- frameMask = frameData->Mask();
- }
- } else {
- //Theme does not contain animation theming, create frames from resource file
- TInt fallbackGraphicID = -1;
- fallbackInfo(part, fallbackGraphicID);
- fallbackGraphicID = fallbackGraphicID + (currentFrame * 2); //skip masks
- TInt fallbackGraphicsMaskID =
- (fallbackGraphicID == KErrNotFound) ? KErrNotFound : fallbackGraphicID + 1; //masks are auto-generated as next in mif files
- if (fallbackGraphicsMaskID != KErrNotFound)
- fallbackGraphicsMaskID = fallbackGraphicsMaskID + (currentFrame * 2); //skip actual graphics
-
- //Then draw animation frame
- AknsUtils::CreateIconL(
- skinInstance,
- KAknsIIDDefault, //animation is not themed, lets force fallback graphics
- animationFrame,
- frameMask,
- AknIconUtils::AvkonIconFileName(),
- fallbackGraphicID ,
- fallbackGraphicsMaskID);
- }
- result = fromFbsBitmap(animationFrame, frameMask, flags, targetSize);
- if (!constructedFromTheme) {
- delete animationFrame;
- animationFrame = 0;
- delete frameMask;
- frameMask = 0;
- }
- break;
- }
- }
- if (!result)
- result = QPixmap();
-
- return result;
-}
-
-QPixmap QS60StyleModeSpecifics::createSkinnedGraphicsLX(QS60StylePrivate::SkinFrameElements frameElement,
- const QSize &size, QS60StylePrivate::SkinElementFlags flags)
-{
- // this function can throw both exceptions and leaves. There are no cleanup dependencies between Qt and Symbian parts.
- if (!size.isValid())
- return QPixmap();
-
- const bool rotatedBy90or270 =
- (flags & (QS60StylePrivate::SF_PointEast | QS60StylePrivate::SF_PointWest));
- const TSize targetSize =
- rotatedBy90or270 ? TSize(size.height(), size.width()) : qt_QSize2TSize(size);
-
- MAknsSkinInstance* skinInstance = AknsUtils::SkinInstance();
- QPixmap result;
-
- static const TDisplayMode displayMode = S60->supportsPremultipliedAlpha ? Q_SYMBIAN_ECOLOR16MAP : EColor16MA;
- static const TInt drawParam = S60->supportsPremultipliedAlpha ? KAknsDrawParamDefault : KAknsDrawParamNoClearUnderImage|KAknsDrawParamRGBOnly;
-
- CFbsBitmap *frame = new (ELeave) CFbsBitmap(); //offscreen
- CleanupStack::PushL(frame);
- User::LeaveIfError(frame->Create(targetSize, displayMode));
-
- CFbsBitmapDevice* bitmapDev = CFbsBitmapDevice::NewL(frame);
- CleanupStack::PushL(bitmapDev);
- CFbsBitGc* bitmapGc = NULL;
- User::LeaveIfError(bitmapDev->CreateContext(bitmapGc));
- CleanupStack::PushL(bitmapGc);
-
- frame->LockHeap();
- memset(frame->DataAddress(), 0, frame->SizeInPixels().iWidth * frame->SizeInPixels().iHeight * 4); // 4: argb bytes
- frame->UnlockHeap();
-
- const TRect outerRect(TPoint(0, 0), targetSize);
- const TRect innerRect = innerRectFromElement(frameElement, outerRect);
-
- TAknsItemID frameSkinID, centerSkinID;
- frameSkinID = centerSkinID = partSpecificThemeId(QS60StylePrivate::m_frameElementsData[frameElement].center);
- frameIdAndCenterId(frameElement, frameSkinID, centerSkinID);
-
- TBool drawn = AknsDrawUtils::DrawFrame(
- skinInstance,
- *bitmapGc,
- outerRect,
- innerRect,
- frameSkinID,
- centerSkinID,
- drawParam );
-
- if (S60->supportsPremultipliedAlpha) {
- if (drawn) {
- result = fromFbsBitmap(frame, NULL, flags, targetSize);
- } else {
- // Drawing might fail due to OOM (we can do nothing about that),
- // or due to skin item not being available.
- // If the latter occurs, lets try switch to non-release specific items (if available)
- // and re-try the drawing.
- frameSkinID = centerSkinID = m_partMap[(int)QS60StylePrivate::m_frameElementsData[frameElement].center].skinID;
- frameIdAndCenterId(frameElement, frameSkinID, centerSkinID);
- drawn = AknsDrawUtils::DrawFrame( skinInstance,
- *bitmapGc, outerRect, innerRect,
- frameSkinID, centerSkinID,
- drawParam );
- // in case drawing fails, even after using default graphics, ignore the error
- if (drawn)
- result = fromFbsBitmap(frame, NULL, flags, targetSize);
- }
- } else {
- TDisplayMode maskDepth = EGray256;
- // Query the skin item for possible frame graphics mask details.
- if (skinInstance) {
- CAknsMaskedBitmapItemData* skinMaskedBmp = static_cast<CAknsMaskedBitmapItemData*>(
- skinInstance->GetCachedItemData(frameSkinID,EAknsITMaskedBitmap));
- if (skinMaskedBmp && skinMaskedBmp->Mask())
- maskDepth = skinMaskedBmp->Mask()->DisplayMode();
- }
- if (maskDepth != ENone) {
- CFbsBitmap *frameMask = new (ELeave) CFbsBitmap(); //offscreen
- CleanupStack::PushL(frameMask);
- User::LeaveIfError(frameMask->Create(targetSize, maskDepth));
-
- CFbsBitmapDevice* maskBitmapDevice = CFbsBitmapDevice::NewL(frameMask);
- CleanupStack::PushL(maskBitmapDevice);
- CFbsBitGc* maskBitGc = NULL;
- User::LeaveIfError(maskBitmapDevice->CreateContext(maskBitGc));
- CleanupStack::PushL(maskBitGc);
-
- if (drawn) {
- //ensure that the mask is really transparent
- maskBitGc->Activate( maskBitmapDevice );
- maskBitGc->SetPenStyle(CGraphicsContext::ENullPen);
- maskBitGc->SetBrushStyle(CGraphicsContext::ESolidBrush);
- maskBitGc->SetBrushColor(KRgbWhite);
- maskBitGc->Clear();
- maskBitGc->SetBrushStyle(CGraphicsContext::ENullBrush);
-
- drawn = AknsDrawUtils::DrawFrame(skinInstance,
- *maskBitGc, outerRect, innerRect,
- frameSkinID, centerSkinID,
- KAknsSDMAlphaOnly |KAknsDrawParamNoClearUnderImage);
- if (drawn)
- result = fromFbsBitmap(frame, frameMask, flags, targetSize);
- }
- CleanupStack::PopAndDestroy(3, frameMask);
- }
- }
- CleanupStack::PopAndDestroy(3, frame); //frame, bitmapDev, bitmapGc
- return result;
-}
-
-void QS60StyleModeSpecifics::frameIdAndCenterId(QS60StylePrivate::SkinFrameElements frameElement, TAknsItemID &frameId, TAknsItemID &centerId)
-{
-// There are some major mix-ups in skin declarations for some frames.
-// First, the frames are not declared in sequence.
-// Second, the parts use different major than the frame-master.
-
- switch(frameElement) {
- case QS60StylePrivate::SF_ToolTip:
- if (QSysInfo::s60Version() != QSysInfo::SV_S60_3_1) {
- centerId.Set(EAknsMajorGeneric, 0x19c2);
- frameId.Set(EAknsMajorSkin, 0x5300);
- } else {
- centerId.Set(KAknsIIDQsnFrPopupCenter);
- frameId.iMinor = centerId.iMinor - 9;
- }
- break;
- case QS60StylePrivate::SF_ToolBar:
- if (QSysInfo::s60Version() == QSysInfo::SV_S60_3_1 ||
- QSysInfo::s60Version() == QSysInfo::SV_S60_3_2) {
- centerId.Set(KAknsIIDQsnFrPopupCenterSubmenu);
- frameId.Set(KAknsIIDQsnFrPopupSub);
- }
- break;
- case QS60StylePrivate::SF_PopupBackground:
- centerId.Set(KAknsIIDQsnFrPopupCenterSubmenu);
- frameId.Set(KAknsIIDQsnFrPopupSub);
- break;
- case QS60StylePrivate::SF_PanelBackground:
- // remove center piece for panel graphics, so that only border is drawn
- centerId.Set(KAknsIIDNone);
- frameId.Set(KAknsIIDQsnFrSetOpt);
- break;
- default:
- // center should be correct here
- frameId.iMinor = centerId.iMinor - 9;
- break;
- }
-}
-
-TRect QS60StyleModeSpecifics::innerRectFromElement(QS60StylePrivate::SkinFrameElements frameElement, const TRect &outerRect)
-{
- TInt widthShrink = QS60StylePrivate::pixelMetric(PM_FrameCornerWidth);
- TInt heightShrink = QS60StylePrivate::pixelMetric(PM_FrameCornerHeight);
- switch(frameElement) {
- case QS60StylePrivate::SF_PanelBackground:
- // panel should have slightly slimmer border to enable thin line of background graphics between closest component
- widthShrink = widthShrink - 2;
- heightShrink = heightShrink - 2;
- break;
- case QS60StylePrivate::SF_ToolTip:
- widthShrink = widthShrink >> 1;
- heightShrink = heightShrink >> 1;
- break;
- case QS60StylePrivate::SF_ListHighlight:
- //In Sym^3 devices highlights are less blocky
- if (QSysInfo::s60Version() > QSysInfo::SV_S60_5_0) {
- widthShrink += 2;
- heightShrink += 2;
- } else {
- widthShrink -= 2;
- heightShrink -= 2;
- }
- break;
- case QS60StylePrivate::SF_PopupBackground:
- widthShrink = widthShrink + 5;
- heightShrink = heightShrink + 5;
- break;
- default:
- break;
- }
- TRect innerRect(outerRect);
- innerRect.Shrink(widthShrink, heightShrink);
- return innerRect;
-}
-
-bool QS60StyleModeSpecifics::checkSupport(const int supportedRelease)
-{
- const QSysInfo::S60Version currentRelease = QSysInfo::s60Version();
- return ( (currentRelease == QSysInfo::SV_S60_3_1 && supportedRelease & ES60_3_1) ||
- (currentRelease == QSysInfo::SV_S60_3_2 && supportedRelease & ES60_3_2) ||
- (currentRelease == QSysInfo::SV_S60_5_0 && supportedRelease & ES60_5_0) ||
- (currentRelease == QSysInfo::SV_S60_5_1 && supportedRelease & ES60_5_1) ||
- (currentRelease == QSysInfo::SV_S60_5_2 && supportedRelease & ES60_5_2) ||
- (currentRelease == QSysInfo::SV_S60_5_3 && supportedRelease & ES60_5_3) );
-}
-
-TAknsItemID QS60StyleModeSpecifics::partSpecificThemeId(int part)
-{
- TAknsItemID newSkinId;
- if (!checkSupport(m_partMap[(int)part].supportInfo))
- newSkinId.Set(m_partMap[(int)part].newMajorSkinId, m_partMap[(int)part].newMinorSkinId);
- else
- newSkinId.Set(m_partMap[(int)part].skinID);
- return newSkinId;
-}
-
-QFont QS60StylePrivate::s60Font_specific(
- QS60StyleEnums::FontCategories fontCategory,
- int pointSize, bool resolveFontSize)
-{
- Q_UNUSED(resolveFontSize);
-
- TAknFontCategory aknFontCategory = EAknFontCategoryUndefined;
- switch (fontCategory) {
- case QS60StyleEnums::FC_Primary:
- aknFontCategory = EAknFontCategoryPrimary;
- break;
- case QS60StyleEnums::FC_Secondary:
- aknFontCategory = EAknFontCategorySecondary;
- break;
- case QS60StyleEnums::FC_Title:
- aknFontCategory = EAknFontCategoryTitle;
- break;
- case QS60StyleEnums::FC_PrimarySmall:
- aknFontCategory = EAknFontCategoryPrimarySmall;
- break;
- case QS60StyleEnums::FC_Digital:
- aknFontCategory = EAknFontCategoryDigital;
- break;
- case QS60StyleEnums::FC_Undefined:
- default:
- break;
- }
-
- // Create AVKON font according the given parameters
- CWsScreenDevice* dev = CCoeEnv::Static()->ScreenDevice();
- TAknFontSpecification spec(aknFontCategory, TFontSpec(), NULL);
- if (pointSize > 0) {
- const TInt pixelSize = dev->VerticalTwipsToPixels(pointSize * KTwipsPerPoint);
- spec.SetTextPaneHeight(pixelSize + 4); // TODO: Is 4 a reasonable top+bottom margin?
- }
-
- QFont result;
- TRAPD( error, QT_TRYCATCH_LEAVING({
- const CAknLayoutFont* aknFont =
- AknFontAccess::CreateLayoutFontFromSpecificationL(*dev, spec);
-
- result = qt_TFontSpec2QFontL(aknFont->DoFontSpecInTwips());
- if (result.pointSize() != pointSize)
- result.setPointSize(pointSize); // Correct the font size returned by CreateLayoutFontFromSpecificationL()
-
- delete aknFont;
- }));
- if (error) result = QFont();
- return result;
-}
-
-void QS60StylePrivate::setActiveLayout()
-{
- const QSize activeScreenSize(screenSize());
- int activeLayoutIndex = -1;
- const short screenHeight = (short)activeScreenSize.height();
- const short screenWidth = (short)activeScreenSize.width();
- for (int i=0; i<m_numberOfLayouts; i++) {
- if (screenHeight==m_layoutHeaders[i].height &&
- screenWidth==m_layoutHeaders[i].width) {
- activeLayoutIndex = i;
- break;
- }
- }
-
- //not found, lets try with either of dimensions
- if (activeLayoutIndex==-1){
- const QSysInfo::S60Version currentRelease = QSysInfo::s60Version();
- const bool landscape = screenHeight < screenWidth;
-
- activeLayoutIndex = (currentRelease == QSysInfo::SV_S60_3_1 || currentRelease == QSysInfo::SV_S60_3_2) ? 0 : 2;
- activeLayoutIndex += (!landscape) ? 1 : 0;
- }
-
- setCurrentLayout(activeLayoutIndex);
-}
-
-Q_GLOBAL_STATIC(QList<QS60StyleAnimation *>, m_animations)
-
-QS60StylePrivate::QS60StylePrivate()
-{
- //Animation defaults need to be created when style is instantiated
- QS60StyleAnimation* progressBarAnimation = new QS60StyleAnimation(QS60StyleEnums::SP_QgnGrafBarWaitAnim, 7, 100);
- m_animations()->append(progressBarAnimation);
- // No need to set active layout, if dynamic metrics API is available
- setActiveLayout();
-}
-
-void QS60StylePrivate::removeAnimations()
-{
- //currently only one animation in the list.
- m_animations()->removeFirst();
-}
-
-QColor QS60StylePrivate::s60Color(QS60StyleEnums::ColorLists list,
- int index, const QStyleOption *option)
-{
- static const TAknsItemID *idMap[] = {
- &KAknsIIDQsnHighlightColors,
- &KAknsIIDQsnIconColors,
- &KAknsIIDQsnLineColors,
- &KAknsIIDQsnOtherColors,
- &KAknsIIDQsnParentColors,
- &KAknsIIDQsnTextColors
- };
- Q_ASSERT((int)list < (int)sizeof(idMap)/sizeof(idMap[0]));
- const QColor color = QS60StyleModeSpecifics::colorValue(*idMap[(int) list], index - 1);
- return option ? QS60StylePrivate::stateColor(color, option) : color;
-}
-
-// In some cases, the AVKON UI themegraphic is already in 'disabled state'.
-// If so, return true for these parts.
-bool QS60StyleModeSpecifics::disabledPartGraphic(QS60StyleEnums::SkinParts &part)
-{
- bool disabledGraphic = false;
- switch(part){
- // inactive button graphics are available from 5.0 onwards
- case QS60StyleEnums::SP_QsnFrButtonCornerTlInactive:
- case QS60StyleEnums::SP_QsnFrButtonCornerTrInactive:
- case QS60StyleEnums::SP_QsnFrButtonCornerBlInactive:
- case QS60StyleEnums::SP_QsnFrButtonCornerBrInactive:
- case QS60StyleEnums::SP_QsnFrButtonSideTInactive:
- case QS60StyleEnums::SP_QsnFrButtonSideBInactive:
- case QS60StyleEnums::SP_QsnFrButtonSideLInactive:
- case QS60StyleEnums::SP_QsnFrButtonSideRInactive:
- case QS60StyleEnums::SP_QsnFrButtonCenterInactive:
- if (!(QSysInfo::s60Version()==QSysInfo::SV_S60_3_1 ||
- QSysInfo::s60Version()==QSysInfo::SV_S60_3_2))
- disabledGraphic = true;
- break;
- default:
- break;
- }
- return disabledGraphic;
-}
-
-// In some cases, the AVKON UI themegraphic is already in 'disabled state'.
-// If so, return true for these frames.
-bool QS60StyleModeSpecifics::disabledFrameGraphic(QS60StylePrivate::SkinFrameElements &frame)
-{
- bool disabledGraphic = false;
- switch(frame){
- // inactive button graphics are available from 5.0 onwards
- case QS60StylePrivate::SF_ButtonInactive:
- if (!(QSysInfo::s60Version()==QSysInfo::SV_S60_3_1 ||
- QSysInfo::s60Version()==QSysInfo::SV_S60_3_2))
- disabledGraphic = true;
- break;
- default:
- break;
- }
- return disabledGraphic;
-}
-
-QPixmap QS60StyleModeSpecifics::generateMissingThemeGraphic(QS60StyleEnums::SkinParts &part,
- const QSize &size, QS60StylePrivate::SkinElementFlags flags)
-{
- if (!QS60StylePrivate::isTouchSupported())
- return QPixmap();
-
- QS60StyleEnums::SkinParts updatedPart = part;
- switch(part){
- // AVKON UI has a abnormal handling for scrollbar graphics. It is possible that the root
- // skin does not contain mandatory graphics for scrollbar pressed states. Therefore, AVKON UI
- // creates dynamically these graphics by modifying the normal state scrollbar graphics slightly.
- // S60Style needs to work similarly. Therefore if skingraphics call provides to be a miss
- // (i.e. result is not valid), style needs to draw normal graphics instead and apply some
- // modifications (similar to generatedIconPixmap()) to the result.
- case QS60StyleEnums::SP_QsnCpScrollHandleBottomPressed:
- updatedPart = QS60StyleEnums::SP_QsnCpScrollHandleBottom;
- break;
- case QS60StyleEnums::SP_QsnCpScrollHandleMiddlePressed:
- updatedPart = QS60StyleEnums::SP_QsnCpScrollHandleMiddle;
- break;
- case QS60StyleEnums::SP_QsnCpScrollHandleTopPressed:
- updatedPart = QS60StyleEnums::SP_QsnCpScrollHandleTop;
- break;
- default:
- break;
- }
- if (part==updatedPart) {
- return QPixmap();
- } else {
- QPixmap result = skinnedGraphics(updatedPart, size, flags);
- QStyleOption opt;
- QPalette *themePalette = QS60StylePrivate::themePalette();
- if (themePalette)
- opt.palette = *themePalette;
-
- // For now, always generate new icon based on "selected". In the future possibly, expand
- // this to consist other possibilities as well.
- result = QApplication::style()->generatedIconPixmap(QIcon::Selected, result, &opt);
- return result;
- }
-}
-
-QPixmap QS60StylePrivate::part(QS60StyleEnums::SkinParts part,
- const QSize &size, QPainter *painter, SkinElementFlags flags)
-{
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
-
- QPixmap result = (flags & SF_ColorSkinned)?
- QS60StyleModeSpecifics::colorSkinnedGraphics(part, size, painter, flags)
- : QS60StyleModeSpecifics::skinnedGraphics(part, size, flags);
-
- lock.relock();
-
- if (flags & SF_StateDisabled && !QS60StyleModeSpecifics::disabledPartGraphic(part)) {
- QStyleOption opt;
- QPalette *themePalette = QS60StylePrivate::themePalette();
- if (themePalette)
- opt.palette = *themePalette;
- result = QApplication::style()->generatedIconPixmap(QIcon::Disabled, result, &opt);
- }
-
- if (!result)
- result = QS60StyleModeSpecifics::generateMissingThemeGraphic(part, size, flags);
-
- return result;
-}
-
-QPixmap QS60StylePrivate::frame(SkinFrameElements frame, const QSize &size, SkinElementFlags flags)
-{
- QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
- QPixmap result = QS60StyleModeSpecifics::skinnedGraphics(frame, size, flags);
- lock.relock();
-
- if (flags & SF_StateDisabled && !QS60StyleModeSpecifics::disabledFrameGraphic(frame)) {
- QStyleOption opt;
- QPalette *themePalette = QS60StylePrivate::themePalette();
- if (themePalette)
- opt.palette = *themePalette;
- result = QApplication::style()->generatedIconPixmap(QIcon::Disabled, result, &opt);
- }
- return result;
-}
-
-QPixmap QS60StylePrivate::backgroundTexture(bool skipCreation)
-{
- bool createNewBackground = false;
- TRect applicationRect = (static_cast<CEikAppUi*>(S60->appUi())->ApplicationRect());
- if (!m_background) {
- createNewBackground = true;
- } else {
- //if background brush does not match screensize, re-create it
- if (m_background->width() != applicationRect.Width() ||
- m_background->height() != applicationRect.Height()) {
- delete m_background;
- m_background = 0;
- createNewBackground = true;
- }
- }
-
- if (createNewBackground && !skipCreation) {
- QPixmap background = part(QS60StyleEnums::SP_QsnBgScreen,
- QSize(applicationRect.Width(), applicationRect.Height()), 0, SkinElementFlags());
- m_background = new QPixmap(background);
-
- // Notify all widgets that palette is updated with the actual background texture.
- QPalette pal = QApplication::palette();
- pal.setBrush(QPalette::Window, *m_background);
- QApplication::setPalette(pal);
- setThemePaletteHash(&pal);
- storeThemePalette(&pal);
- foreach (QWidget *widget, QApplication::allWidgets()){
- QEvent e(QEvent::PaletteChange);
- QApplication::sendEvent(widget, &e);
- setThemePalette(widget);
- widget->ensurePolished();
- }
- }
- if (!m_background)
- return QPixmap();
- return *m_background;
-}
-
-QSize QS60StylePrivate::screenSize()
-{
- return QSize(S60->screenWidthInPixels, S60->screenHeightInPixels);
-}
-
-QS60Style::QS60Style()
- : QCommonStyle(*new QS60StylePrivate)
-{
-}
-
-#ifdef Q_WS_S60
-void QS60StylePrivate::handleDynamicLayoutVariantSwitch()
-{
- clearCaches(QS60StylePrivate::CC_LayoutChange);
- setBackgroundTexture(qApp);
- setActiveLayout();
- foreach (QWidget *widget, QApplication::allWidgets())
- widget->ensurePolished();
-}
-
-void QS60StylePrivate::handleSkinChange()
-{
- clearCaches(QS60StylePrivate::CC_ThemeChange);
- setThemePalette(qApp);
- foreach (QWidget *topLevelWidget, QApplication::allWidgets()){
- QEvent e(QEvent::StyleChange);
- QApplication::sendEvent(topLevelWidget, &e);
- setThemePalette(topLevelWidget);
- topLevelWidget->ensurePolished();
- }
-#ifndef QT_NO_PROGRESSBAR
- //re-start animation timer
- stopAnimation(QS60StyleEnums::SP_QgnGrafBarWaitAnim); //todo: once we have more animations, we could say "stop all running ones"
- startAnimation(QS60StyleEnums::SP_QgnGrafBarWaitAnim); //and "re-start all previously running ones"
-#endif
-}
-
-int QS60StylePrivate::currentAnimationFrame(QS60StyleEnums::SkinParts part)
-{
- QS60StyleAnimation *animation = animationDefinition(part);
- // todo: looping could be done in QS60Style::timerEvent
- if (animation->frameCount() == animation->currentFrame())
- animation->setCurrentFrame(0);
- return animation->currentFrame();
-}
-
-QS60StyleAnimation* QS60StylePrivate::animationDefinition(QS60StyleEnums::SkinParts part)
-{
- int i = 0;
- const int animationsCount = m_animations()->isEmpty() ? 0 : m_animations()->count();
- for(; i < animationsCount; i++) {
- if (part == m_animations()->at(i)->animationId())
- break;
- }
- return m_animations()->at(i);
-}
-
-void QS60StylePrivate::startAnimation(QS60StyleEnums::SkinParts animationPart)
-{
- Q_Q(QS60Style);
-
- //Query animation data from theme and store values to local struct.
- QVariant themeAnimationDataVariant = QS60StyleModeSpecifics::themeDefinition(
- QS60StyleEnums::TD_AnimationData, animationPart);
- QList<QVariant> themeAnimationData = themeAnimationDataVariant.toList();
-
- QS60StyleAnimation *animation = QS60StylePrivate::animationDefinition(animationPart);
- if (animation) {
- if (themeAnimationData.at(QS60StyleEnums::AD_Interval).toInt() != 0)
- animation->setInterval(themeAnimationData.at(QS60StyleEnums::AD_Interval).toInt());
-
- if (themeAnimationData.at(QS60StyleEnums::AD_NumberOfFrames).toInt() != 0)
- animation->setFrameCount(themeAnimationData.at(QS60StyleEnums::AD_NumberOfFrames).toInt());
-
- //todo: playmode is ignored for now, since it seems to return invalid data on some themes
- //lets use the table values for play mode
-
- animation->setCurrentFrame(0); //always initialize
- const int timerId = q->startTimer(animation->interval());
- animation->setTimerId(timerId);
- }
-}
-
-void QS60StylePrivate::stopAnimation(QS60StyleEnums::SkinParts animationPart)
-{
- Q_Q(QS60Style);
-
- QS60StyleAnimation *animation = QS60StylePrivate::animationDefinition(animationPart);
- if (animation) {
- animation->setCurrentFrame(0);
- if (animation->timerId() != 0) {
- q->killTimer(animation->timerId());
- animation->setTimerId(0);
- }
- animation->resetToDefaults();
- }
-}
-
-QVariant QS60StyleModeSpecifics::themeDefinition(
- QS60StyleEnums::ThemeDefinitions definition, QS60StyleEnums::SkinParts part)
-{
- MAknsSkinInstance* skinInstance = AknsUtils::SkinInstance();
-
- Q_ASSERT(skinInstance);
-
- switch(definition) {
- //Animation definitions
- case QS60StyleEnums::TD_AnimationData:
- {
- CAknsBmpAnimItemData *animationData;
- TAknsItemID animationSkinId = partSpecificThemeId(part);
- QList<QVariant> list;
-
- TRAPD( error, QT_TRYCATCH_LEAVING(
- animationData = static_cast<CAknsBmpAnimItemData*>(skinInstance->CreateUncachedItemDataL(
- animationSkinId, EAknsITBmpAnim))));
- if (error)
- return list;
-
- if (animationData) {
- list.append((int)animationData->FrameInterval());
- list.append((int)animationData->NumberOfImages());
-
- QS60StyleEnums::AnimationMode playMode;
- switch(animationData->PlayMode()) {
- case CBitmapAnimClientData::EPlay:
- playMode = QS60StyleEnums::AM_PlayOnce;
- break;
- case CBitmapAnimClientData::ECycle:
- playMode = QS60StyleEnums::AM_Looping;
- break;
- case CBitmapAnimClientData::EBounce:
- playMode = QS60StyleEnums::AM_Bounce;
- break;
- default:
- break;
- }
- list.append(QVariant((int)playMode));
- delete animationData;
- } else {
- list.append(0);
- list.append(0);
- }
- return list;
- }
- break;
- default:
- break;
- }
- return QVariant();
-}
-
-#endif // Q_WS_S60
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_S60 || QT_PLUGIN
diff --git a/src/gui/styles/qs60style_simulated.cpp b/src/gui/styles/qs60style_simulated.cpp
deleted file mode 100644
index a5aeac3fb9..0000000000
--- a/src/gui/styles/qs60style_simulated.cpp
+++ /dev/null
@@ -1,457 +0,0 @@
-/****************************************************************************
-**
-** 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 "qs60style.h"
-#include "qs60style_p.h"
-#include "qfile.h"
-#include "qhash.h"
-#include "qapplication.h"
-#include "qpainter.h"
-#include "qpicture.h"
-#include "qstyleoption.h"
-#include "qtransform.h"
-#include "qlayout.h"
-#include "qpixmapcache.h"
-#include "qmetaobject.h"
-#include "qdebug.h"
-#include "qbuffer.h"
-#include "qdesktopwidget.h"
-
-#if !defined(QT_NO_STYLE_S60) || defined(QT_PLUGIN)
-
-QT_BEGIN_NAMESPACE
-
-static const quint32 blobVersion = 1;
-static const int pictureSize = 256;
-
-#if defined(Q_CC_GNU)
-#if __GNUC__ >= 2
-#define __FUNCTION__ __func__
-#endif
-#endif
-
-
-bool saveThemeToBlob(const QString &themeBlob,
- const QHash<QString, QPicture> &partPictures,
- const QHash<QPair<QString, int>, QColor> &colors)
-{
- QFile blob(themeBlob);
- if (!blob.open(QIODevice::WriteOnly)) {
- qWarning() << __FUNCTION__ << ": Could not create blob: " << themeBlob;
- return false;
- }
-
- QByteArray data;
- QBuffer dataBuffer(&data);
- dataBuffer.open(QIODevice::WriteOnly);
- QDataStream dataOut(&dataBuffer);
-
- const int colorsCount = colors.count();
- dataOut << colorsCount;
- const QList<QPair<QString, int> > colorKeys = colors.keys();
- for (int i = 0; i < colorsCount; ++i) {
- const QPair<QString, int> &key = colorKeys.at(i);
- dataOut << key;
- const QColor color = colors.value(key);
- dataOut << color;
- }
-
- dataOut << partPictures.count();
- QHashIterator<QString, QPicture> i(partPictures);
- while (i.hasNext()) {
- i.next();
- dataOut << i.key();
- dataOut << i.value(); // the QPicture
- }
-
- QDataStream blobOut(&blob);
- blobOut << blobVersion;
- blobOut << qCompress(data);
- return blobOut.status() == QDataStream::Ok;
-}
-
-bool loadThemeFromBlob(const QString &themeBlob,
- QHash<QString, QPicture> &partPictures,
- QHash<QPair<QString, int>, QColor> &colors)
-{
- QFile blob(themeBlob);
- if (!blob.open(QIODevice::ReadOnly)) {
- qWarning() << __FUNCTION__ << ": Could not read blob: " << themeBlob;
- return false;
- }
- QDataStream blobIn(&blob);
-
- quint32 version;
- blobIn >> version;
-
- if (version != blobVersion) {
- qWarning() << __FUNCTION__ << ": Invalid blob version: " << version << " ...expected: " << blobVersion;
- return false;
- }
-
- QByteArray data;
- blobIn >> data;
- data = qUncompress(data);
- QBuffer dataBuffer(&data);
- dataBuffer.open(QIODevice::ReadOnly);
- QDataStream dataIn(&dataBuffer);
-
- int colorsCount;
- dataIn >> colorsCount;
- for (int i = 0; i < colorsCount; ++i) {
- QPair<QString, int> key;
- dataIn >> key;
- QColor value;
- dataIn >> value;
- colors.insert(key, value);
- }
-
- int picturesCount;
- dataIn >> picturesCount;
- for (int i = 0; i < picturesCount; ++i) {
- QString key;
- dataIn >> key;
- QPicture value;
- dataIn >> value;
- value.setBoundingRect(QRect(0, 0, pictureSize, pictureSize)); // Bug? The forced bounding rect was not deserialized.
- partPictures.insert(key, value);
- }
-
- if (dataIn.status() != QDataStream::Ok) {
- qWarning() << __FUNCTION__ << ": Invalid data blob: " << themeBlob;
- return false;
- }
- return true;
-}
-
-class QS60StyleModeSpecifics
-{
-public:
- static QPixmap skinnedGraphics(QS60StyleEnums::SkinParts stylepart,
- const QSize &size, QS60StylePrivate::SkinElementFlags flags);
- static QHash<QString, QPicture> m_partPictures;
- static QHash<QPair<QString , int>, QColor> m_colors;
-};
-QHash<QString, QPicture> QS60StyleModeSpecifics::m_partPictures;
-QHash<QPair<QString , int>, QColor> QS60StyleModeSpecifics::m_colors;
-
-QS60StylePrivate::QS60StylePrivate()
-{
- setCurrentLayout(0);
-}
-
-QColor QS60StylePrivate::s60Color(QS60StyleEnums::ColorLists list,
- int index, const QStyleOption *option)
-{
- const QString listKey = QS60Style::colorListKeys().at(list);
- return QS60StylePrivate::stateColor(
- QS60StyleModeSpecifics::m_colors.value(QPair<QString, int>(listKey, index)),
- option
- );
-}
-
-QPixmap QS60StylePrivate::part(QS60StyleEnums::SkinParts part, const QSize &size,
- QPainter *painter, QS60StylePrivate::SkinElementFlags flags)
-{
- Q_UNUSED(painter);
-
- const QString partKey = QS60Style::partKeys().at(part);
- const QPicture partPicture = QS60StyleModeSpecifics::m_partPictures.value(partKey);
- QSize partSize(partPicture.boundingRect().size());
- if (flags & (SF_PointEast | SF_PointWest)) {
- const int temp = partSize.width();
- partSize.setWidth(partSize.height());
- partSize.setHeight(temp);
- }
- const qreal scaleX = size.width() / (qreal)partSize.width();
- const qreal scaleY = size.height() / (qreal)partSize.height();
-
- QImage partImage(size, QImage::Format_ARGB32);
- partImage.fill(Qt::transparent);
- QPainter resultPainter(&partImage);
- QTransform t;
-
- if (flags & SF_PointEast)
- t.translate(size.width(), 0);
- else if (flags & SF_PointSouth)
- t.translate(size.width(), size.height());
- else if (flags & SF_PointWest)
- t.translate(0, size.height());
-
- t.scale(scaleX, scaleY);
-
- if (flags & SF_PointEast)
- t.rotate(90);
- else if (flags & SF_PointSouth)
- t.rotate(180);
- else if (flags & SF_PointWest)
- t.rotate(270);
-
- resultPainter.setTransform(t, true);
- const_cast<QPicture *>(&partPicture)->play(&resultPainter);
- resultPainter.end();
-
- QPixmap result = QPixmap::fromImage(partImage);
- if (flags & SF_StateDisabled) {
- QStyleOption opt;
- QPalette *themePalette = QS60StylePrivate::themePalette();
- if (themePalette)
- opt.palette = *themePalette;
- result = QApplication::style()->generatedIconPixmap(QIcon::Disabled, result, &opt);
- }
-
- return result;
-}
-
-QPixmap QS60StylePrivate::frame(SkinFrameElements frame, const QSize &size,
- SkinElementFlags flags)
-{
- const QS60StyleEnums::SkinParts center = m_frameElementsData[frame].center;
- const QS60StyleEnums::SkinParts topLeft = QS60StyleEnums::SkinParts(center - 8);
- const QS60StyleEnums::SkinParts topRight = QS60StyleEnums::SkinParts(center - 7);
- const QS60StyleEnums::SkinParts bottomLeft = QS60StyleEnums::SkinParts(center - 6);
- const QS60StyleEnums::SkinParts bottomRight = QS60StyleEnums::SkinParts(center - 5);
- const QS60StyleEnums::SkinParts top = QS60StyleEnums::SkinParts(center - 4);
- const QS60StyleEnums::SkinParts bottom = QS60StyleEnums::SkinParts(center - 3);
- const QS60StyleEnums::SkinParts left = QS60StyleEnums::SkinParts(center - 2);
- const QS60StyleEnums::SkinParts right = QS60StyleEnums::SkinParts(center - 1);
-
- // The size of topLeft defines all other sizes
- const QSize cornerSize(partSize(topLeft));
- // if frame is so small that corners would cover it completely, draw only center piece
- const bool drawOnlyCenter =
- 2 * cornerSize.width() + 1 >= size.width() || 2 * cornerSize.height() + 1 >= size.height();
-
- const int cornerWidth = cornerSize.width();
- const int cornerHeight = cornerSize.height();
- const int rectWidth = size.width();
- const int rectHeight = size.height();
- const QRect rect(QPoint(), size);
-
- const QRect topLeftRect = QRect(rect.topLeft(), cornerSize);
- const QRect topRect = rect.adjusted(cornerWidth, 0, -cornerWidth, -(rectHeight - cornerHeight));
- const QRect topRightRect = topLeftRect.translated(rectWidth - cornerWidth, 0);
- const QRect rightRect = rect.adjusted(rectWidth - cornerWidth, cornerHeight, 0, -cornerHeight);
- const QRect bottomRightRect = topRightRect.translated(0, rectHeight - cornerHeight);
- const QRect bottomRect = topRect.translated(0, rectHeight - cornerHeight);
- const QRect bottomLeftRect = topLeftRect.translated(0, rectHeight - cornerHeight);
- const QRect leftRect = rightRect.translated(cornerWidth - rectWidth, 0);
- const QRect centerRect = drawOnlyCenter ? rect : rect.adjusted(cornerWidth, cornerWidth, -cornerWidth, -cornerWidth);
-
- QPixmap result(size);
- result.fill(Qt::transparent);
- QPainter painter(&result);
-
-#if 0
- painter.save();
- painter.setOpacity(.3);
- painter.fillRect(topLeftRect, Qt::red);
- painter.fillRect(topRect, Qt::green);
- painter.fillRect(topRightRect, Qt::blue);
- painter.fillRect(rightRect, Qt::green);
- painter.fillRect(bottomRightRect, Qt::red);
- painter.fillRect(bottomRect, Qt::blue);
- painter.fillRect(bottomLeftRect, Qt::green);
- painter.fillRect(leftRect, Qt::blue);
- painter.fillRect(centerRect, Qt::red);
- painter.restore();
-#else
- drawPart(topLeft, &painter, topLeftRect, flags);
- drawPart(top, &painter, topRect, flags);
- drawPart(topRight, &painter, topRightRect, flags);
- drawPart(right, &painter, rightRect, flags);
- drawPart(bottomRight, &painter, bottomRightRect, flags);
- drawPart(bottom, &painter, bottomRect, flags);
- drawPart(bottomLeft, &painter, bottomLeftRect, flags);
- drawPart(left, &painter, leftRect, flags);
- drawPart(center, &painter, centerRect, flags);
-#endif
-
- return result;
-}
-
-QPixmap QS60StylePrivate::backgroundTexture(bool /*skipCreation*/)
-{
- if (!m_background) {
- const QSize size = QApplication::desktop()->screen()->size();
- QPixmap background = part(QS60StyleEnums::SP_QsnBgScreen, size, 0);
- m_background = new QPixmap(background);
- }
- return *m_background;
-}
-
-bool QS60StylePrivate::isTouchSupported()
-{
-#ifdef QT_KEYPAD_NAVIGATION
- return !QApplication::keypadNavigationEnabled();
-#else
- return true;
-#endif
-}
-
-bool QS60StylePrivate::isToolBarBackground()
-{
- return true;
-}
-
-bool QS60StylePrivate::hasSliderGrooveGraphic()
-{
- return false;
-}
-
-bool QS60StylePrivate::isSingleClickUi()
-{
- return false;
-}
-
-QFont QS60StylePrivate::s60Font_specific(
- QS60StyleEnums::FontCategories fontCategory,
- int pointSize, bool resolveFontSize)
-{
- QFont result;
- if (resolveFontSize)
- result.setPointSize(pointSize);
- switch (fontCategory) {
- case QS60StyleEnums::FC_Primary:
- result.setBold(true);
- break;
- case QS60StyleEnums::FC_Secondary:
- case QS60StyleEnums::FC_Title:
- case QS60StyleEnums::FC_PrimarySmall:
- case QS60StyleEnums::FC_Digital:
- case QS60StyleEnums::FC_Undefined:
- default:
- break;
- }
- return result;
-}
-
-int QS60StylePrivate::currentAnimationFrame(QS60StyleEnums::SkinParts part)
-{
- return 0;
-}
-
-/*!
- Constructs a QS60Style object.
-*/
-QS60Style::QS60Style()
- : QCommonStyle(*new QS60StylePrivate)
-{
- const QString defaultBlob = QString::fromLatin1(":/trolltech/styles/s60style/images/defaults60theme.blob");
- if (QFile::exists(defaultBlob))
- loadS60ThemeFromBlob(defaultBlob);
-}
-
-Q_GLOBAL_STATIC_WITH_INITIALIZER(QStringList, enumPartKeys, {
- const int enumIndex = QS60StyleEnums::staticMetaObject.indexOfEnumerator("SkinParts");
- Q_ASSERT(enumIndex >= 0);
- const QMetaEnum metaEnum = QS60StyleEnums::staticMetaObject.enumerator(enumIndex);
- for (int i = 0; i < metaEnum.keyCount(); ++i) {
- const QString enumKey = QString::fromLatin1(metaEnum.key(i));
- QString partKey;
- // Following loop does following conversions: "SP_QgnNoteInfo" to "qgn_note_info"...
- for (int charPosition = 3; charPosition < enumKey.length(); charPosition++) {
- if (charPosition > 3 && enumKey[charPosition].isUpper())
- partKey.append(QChar::fromLatin1('_'));
- partKey.append(enumKey[charPosition].toLower());
- }
- x->append(partKey);
- }
-})
-
-QStringList QS60Style::partKeys()
-{
- return *enumPartKeys();
-}
-
-Q_GLOBAL_STATIC_WITH_INITIALIZER(QStringList, enumColorListKeys, {
- const int enumIndex = QS60StyleEnums::staticMetaObject.indexOfEnumerator("ColorLists");
- Q_ASSERT(enumIndex >= 0);
- const QMetaEnum metaEnum = QS60StyleEnums::staticMetaObject.enumerator(enumIndex);
- for (int i = 0; i < metaEnum.keyCount(); i++) {
- const QString enumKey = QString::fromLatin1(metaEnum.key(i));
- // Following line does following conversions: CL_QsnTextColors to "text"...
- x->append(enumKey.mid(6, enumKey.length() - 12).toLower());
- }
-})
-
-QStringList QS60Style::colorListKeys()
-{
- return *enumColorListKeys();
-}
-
-void QS60Style::setS60Theme(const QHash<QString, QPicture> &parts,
- const QHash<QPair<QString , int>, QColor> &colors)
-{
- Q_D(QS60Style);
- QS60StyleModeSpecifics::m_partPictures = parts;
- QS60StyleModeSpecifics::m_colors = colors;
- d->clearCaches(QS60StylePrivate::CC_ThemeChange);
- d->setBackgroundTexture(qApp);
- d->setThemePalette(qApp);
-}
-
-bool QS60Style::loadS60ThemeFromBlob(const QString &blobFile)
-{
- QHash<QString, QPicture> partPictures;
- QHash<QPair<QString, int>, QColor> colors;
-
- if (!loadThemeFromBlob(blobFile, partPictures, colors))
- return false;
- setS60Theme(partPictures, colors);
- return true;
-}
-
-bool QS60Style::saveS60ThemeToBlob(const QString &blobFile) const
-{
- return saveThemeToBlob(blobFile,
- QS60StyleModeSpecifics::m_partPictures, QS60StyleModeSpecifics::m_colors);
-}
-
-QPoint qt_s60_fill_background_offset(const QWidget *targetWidget)
-{
- Q_UNUSED(targetWidget)
- return QPoint();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_S60 || QT_PLUGIN
diff --git a/src/gui/styles/qs60style_stub.cpp b/src/gui/styles/qs60style_stub.cpp
deleted file mode 100644
index a3a5b9d0ec..0000000000
--- a/src/gui/styles/qs60style_stub.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** 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 "qs60style.h"
-#include "qdebug.h"
-
-#if defined(QT_NO_STYLE_S60)
-QT_BEGIN_NAMESPACE
-
-QS60Style::QS60Style()
-{
- qWarning() << "QS60Style stub created";
-}
-
-QS60Style::~QS60Style()
-{
-}
-
-void QS60Style::drawComplexControl(ComplexControl , const QStyleOptionComplex *, QPainter *, const QWidget *) const
-{
-}
-
-void QS60Style::drawControl(ControlElement , const QStyleOption *, QPainter *, const QWidget *) const
-{
-}
-
-void QS60Style::drawPrimitive(PrimitiveElement , const QStyleOption *, QPainter *, const QWidget *) const
-{
-}
-
-int QS60Style::pixelMetric(PixelMetric , const QStyleOption *, const QWidget *) const
-{
- return 0;
-}
-
-QSize QS60Style::sizeFromContents(ContentsType , const QStyleOption *, const QSize &, const QWidget *) const
-{
- return QSize();
-}
-
-int QS60Style::styleHint(StyleHint , const QStyleOption *, const QWidget *, QStyleHintReturn *) const
-{
- return 0;
-}
-
-QRect QS60Style::subControlRect(ComplexControl , const QStyleOptionComplex *, SubControl , const QWidget *) const
-{
- return QRect();
-}
-
-QRect QS60Style::subElementRect(SubElement , const QStyleOption *, const QWidget *) const
-{
- return QRect();
-}
-
-void QS60Style::polish(QWidget *)
-{
-}
-
-void QS60Style::unpolish(QWidget *)
-{
-}
-
-void QS60Style::polish(QApplication *)
-{
-}
-
-void QS60Style::unpolish(QApplication *)
-{
-}
-
-bool QS60Style::event(QEvent *)
-{
- return false;
-}
-
-QIcon QS60Style::standardIconImplementation(StandardPixmap , const QStyleOption *, const QWidget *) const
-{
- return QIcon();
-}
-
-void QS60Style::timerEvent(QTimerEvent *)
-{
-}
-
-bool QS60Style::eventFilter(QObject *, QEvent *)
-{
- return false;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_S60
diff --git a/src/gui/styles/qstyle.cpp b/src/gui/styles/qstyle.cpp
deleted file mode 100644
index ecb5ee51a1..0000000000
--- a/src/gui/styles/qstyle.cpp
+++ /dev/null
@@ -1,2459 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstyle.h"
-#include "qapplication.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qpixmapcache.h"
-#include "qstyleoption.h"
-#include "private/qstyle_p.h"
-#include "private/qguiapplication_p.h"
-#ifndef QT_NO_DEBUG
-#include "qdebug.h"
-#endif
-
-#ifdef Q_WS_X11
-#include <qx11info_x11.h>
-#endif
-
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-static const int MaxBits = 8 * sizeof(QSizePolicy::ControlType);
-
-static int unpackControlTypes(QSizePolicy::ControlTypes controls, QSizePolicy::ControlType *array)
-{
- if (!controls)
- return 0;
-
- // optimization: exactly one bit is set
- if ((controls & (controls - 1)) == 0) {
- array[0] = QSizePolicy::ControlType(uint(controls));
- return 1;
- }
-
- int count = 0;
- for (int i = 0; i < MaxBits; ++i) {
- if (uint bit = (controls & (0x1 << i)))
- array[count++] = QSizePolicy::ControlType(bit);
- }
- return count;
-}
-
-/*!
- \class QStyle
- \brief The QStyle class is an abstract base class that encapsulates the look and feel of a GUI.
-
- \ingroup appearance
-
- Qt contains a set of QStyle subclasses that emulate the styles of
- the different platforms supported by Qt (QWindowsStyle,
- QMacStyle, QMotifStyle, etc.). By default, these styles are built
- into the QtGui library. Styles can also be made available as
- plugins.
-
- Qt's built-in widgets use QStyle to perform nearly all of their
- drawing, ensuring that they look exactly like the equivalent
- native widgets. The diagram below shows a QComboBox in eight
- different styles.
-
- \img qstyle-comboboxes.png Eight combo boxes
-
- Topics:
-
- \tableofcontents
-
- \section1 Setting a Style
-
- The style of the entire application can be set using the
- QApplication::setStyle() function. It can also be specified by the
- user of the application, using the \c -style command-line option:
-
- \snippet doc/src/snippets/code/src_gui_styles_qstyle.cpp 0
-
- If no style is specified, Qt will choose the most appropriate
- style for the user's platform or desktop environment.
-
- A style can also be set on an individual widget using the
- QWidget::setStyle() function.
-
- \section1 Developing Style-Aware Custom Widgets
-
- If you are developing custom widgets and want them to look good on
- all platforms, you can use QStyle functions to perform parts of
- the widget drawing, such as drawItemText(), drawItemPixmap(),
- drawPrimitive(), drawControl(), and drawComplexControl().
-
- Most QStyle draw functions take four arguments:
- \list
- \o an enum value specifying which graphical element to draw
- \o a QStyleOption specifying how and where to render that element
- \o a QPainter that should be used to draw the element
- \o a QWidget on which the drawing is performed (optional)
- \endlist
-
- For example, if you want to draw a focus rectangle on your
- widget, you can write:
-
- \snippet doc/src/snippets/styles/styles.cpp 1
-
- QStyle gets all the information it needs to render the graphical
- element from QStyleOption. The widget is passed as the last
- argument in case the style needs it to perform special effects
- (such as animated default buttons on Mac OS X), but it isn't
- mandatory. In fact, you can use QStyle to draw on any paint
- device, not just widgets, by setting the QPainter properly.
-
- QStyleOption has various subclasses for the various types of
- graphical elements that can be drawn. For example,
- PE_FrameFocusRect expects a QStyleOptionFocusRect argument.
-
- To ensure that drawing operations are as fast as possible,
- QStyleOption and its subclasses have public data members. See the
- QStyleOption class documentation for details on how to use it.
-
- For convenience, Qt provides the QStylePainter class, which
- combines a QStyle, a QPainter, and a QWidget. This makes it
- possible to write
-
- \snippet doc/src/snippets/styles/styles.cpp 5
- \dots
- \snippet doc/src/snippets/styles/styles.cpp 7
-
- instead of
-
- \snippet doc/src/snippets/styles/styles.cpp 2
- \dots
- \snippet doc/src/snippets/styles/styles.cpp 3
-
- \section1 Creating a Custom Style
-
- You can create a custom look and feel for your application by
- creating a custom style. There are two approaches to creating a
- custom style. In the static approach, you either choose an
- existing QStyle class, subclass it, and reimplement virtual
- functions to provide the custom behavior, or you create an entire
- QStyle class from scratch. In the dynamic approach, you modify the
- behavior of your system style at runtime. The static approach is
- described below. The dynamic approach is described in QProxyStyle.
-
- The first step in the static approach is to pick one of the styles
- provided by Qt from which you will build your custom style. Your
- choice of QStyle class will depend on which style resembles your
- desired style the most. The most general class that you can use as
- a base is QCommonStyle (not QStyle). This is because Qt requires
- its styles to be \l{QCommonStyle}s.
-
- Depending on which parts of the base style you want to change,
- you must reimplement the functions that are used to draw those
- parts of the interface. To illustrate this, we will modify the
- look of the spin box arrows drawn by QWindowsStyle. The arrows
- are \e{primitive elements} that are drawn by the drawPrimitive()
- function, so we need to reimplement that function. We need the
- following class declaration:
-
- \snippet doc/src/snippets/customstyle/customstyle.h 0
-
- To draw its up and down arrows, QSpinBox uses the
- PE_IndicatorSpinUp and PE_IndicatorSpinDown primitive elements.
- Here's how to reimplement the drawPrimitive() function to draw
- them differently:
-
- \snippet doc/src/snippets/customstyle/customstyle.cpp 2
- \snippet doc/src/snippets/customstyle/customstyle.cpp 3
- \snippet doc/src/snippets/customstyle/customstyle.cpp 4
-
- Notice that we don't use the \c widget argument, except to pass it
- on to the QWindowStyle::drawPrimitive() function. As mentioned
- earlier, the information about what is to be drawn and how it
- should be drawn is specified by a QStyleOption object, so there is
- no need to ask the widget.
-
- If you need to use the \c widget argument to obtain additional
- information, be careful to ensure that it isn't 0 and that it is
- of the correct type before using it. For example:
-
- \snippet doc/src/snippets/customstyle/customstyle.cpp 0
- \dots
- \snippet doc/src/snippets/customstyle/customstyle.cpp 1
-
- When implementing a custom style, you cannot assume that the
- widget is a QSpinBox just because the enum value is called
- PE_IndicatorSpinUp or PE_IndicatorSpinDown.
-
- The documentation for the \l{widgets/styles}{Styles} example
- covers this topic in more detail.
-
- \warning Qt style sheets are currently not supported for custom QStyle
- subclasses. We plan to address this in some future release.
-
-
- \section1 Using a Custom Style
-
- There are several ways of using a custom style in a Qt
- application. The simplest way is to pass the custom style to the
- QApplication::setStyle() static function before creating the
- QApplication object:
-
- \snippet snippets/customstyle/main.cpp using a custom style
-
- You can call QApplication::setStyle() at any time, but by calling
- it before the constructor, you ensure that the user's preference,
- set using the \c -style command-line option, is respected.
-
- You may want to make your custom style available for use in other
- applications, which may not be yours and hence not available for
- you to recompile. The Qt Plugin system makes it possible to create
- styles as plugins. Styles created as plugins are loaded as shared
- objects at runtime by Qt itself. Please refer to the \link
- plugins-howto.html Qt Plugin\endlink documentation for more
- information on how to go about creating a style plugin.
-
- Compile your plugin and put it into Qt's \c plugins/styles
- directory. We now have a pluggable style that Qt can load
- automatically. To use your new style with existing applications,
- simply start the application with the following argument:
-
- \snippet doc/src/snippets/code/src_gui_styles_qstyle.cpp 1
-
- The application will use the look and feel from the custom style you
- implemented.
-
- \section1 Right-to-Left Desktops
-
- Languages written from right to left (such as Arabic and Hebrew)
- usually also mirror the whole layout of widgets, and require the
- light to come from the screen's top-right corner instead of
- top-left.
-
- If you create a custom style, you should take special care when
- drawing asymmetric elements to make sure that they also look
- correct in a mirrored layout. An easy way to test your styles is
- to run applications with the \c -reverse command-line option or
- to call QApplication::setLayoutDirection() in your \c main()
- function.
-
- Here are some things to keep in mind when making a style work well in a
- right-to-left environment:
-
- \list
- \o subControlRect() and subElementRect() return rectangles in screen coordinates
- \o QStyleOption::direction indicates in which direction the item should be drawn in
- \o If a style is not right-to-left aware it will display items as if it were left-to-right
- \o visualRect(), visualPos(), and visualAlignment() are helpful functions that will
- translate from logical to screen representations.
- \o alignedRect() will return a logical rect aligned for the current direction
- \endlist
-
- \section1 Styles in Item Views
-
- The painting of items in views is performed by a delegate. Qt's
- default delegate, QStyledItemDelegate, is also used for for calculating bounding
- rectangles of items, and their sub-elements for the various kind
- of item \l{Qt::ItemDataRole}{data roles}
- QStyledItemDelegate supports. See the QStyledItemDelegate class
- description to find out which datatypes and roles are supported. You
- can read more about item data roles in \l{Model/View Programming}.
-
- When QStyledItemDelegate paints its items, it draws
- CE_ItemViewItem, and calculates their size with CT_ItemViewItem.
- Note also that it uses SE_ItemViewItemText to set the size of
- editors. When implementing a style to customize drawing of item
- views, you need to check the implementation of QCommonStyle (and
- any other subclasses from which your style
- inherits). This way, you find out which and how
- other style elements are painted, and you can then reimplement the
- painting of elements that should be drawn differently.
-
- We include a small example where we customize the drawing of item
- backgrounds.
-
- \snippet doc/src/snippets/customviewstyle.cpp 0
-
- The primitive element PE_PanelItemViewItem is responsible for
- painting the background of items, and is called from
- \l{QCommonStyle}'s implementation of CE_ItemViewItem.
-
- To add support for drawing of new datatypes and item data roles,
- it is necessary to create a custom delegate. But if you only
- need to support the datatypes implemented by the default
- delegate, a custom style does not need an accompanying
- delegate. The QStyledItemDelegate class description gives more
- information on custom delegates.
-
- The drawing of item view headers is also done by the style, giving
- control over size of header items and row and column sizes.
-
- \sa QStyleOption, QStylePainter, {Styles Example},
- {Styles and Style Aware Widgets}, QStyledItemDelegate
-*/
-
-/*!
- Constructs a style object.
-*/
-QStyle::QStyle()
- : QObject(*new QStylePrivate)
-{
- Q_D(QStyle);
- d->proxyStyle = this;
-}
-
-/*!
- \internal
-
- Constructs a style object.
-*/
-QStyle::QStyle(QStylePrivate &dd)
- : QObject(dd)
-{
- Q_D(QStyle);
- d->proxyStyle = this;
-}
-
-/*!
- Destroys the style object.
-*/
-QStyle::~QStyle()
-{
-}
-
-/*!
- Initializes the appearance of the given \a widget.
-
- This function is called for every widget at some point after it
- has been fully created but just \e before it is shown for the very
- first time.
-
- Note that the default implementation does nothing. Reasonable
- actions in this function might be to call the
- QWidget::setBackgroundMode() function for the widget. Do not use
- the function to set, for example, the geometry. Reimplementing
- this function provides a back-door through which the appearance
- of a widget can be changed, but with Qt's style engine it is
- rarely necessary to implement this function; reimplement
- drawItemPixmap(), drawItemText(), drawPrimitive(), etc. instead.
-
- The QWidget::inherits() function may provide enough information to
- allow class-specific customizations. But because new QStyle
- subclasses are expected to work reasonably with all current and \e
- future widgets, limited use of hard-coded customization is
- recommended.
-
- \sa unpolish()
-*/
-void QStyle::polish(QWidget * /* widget */)
-{
-}
-
-/*!
- Uninitialize the given \a{widget}'s appearance.
-
- This function is the counterpart to polish(). It is called for
- every polished widget whenever the style is dynamically changed;
- the former style has to unpolish its settings before the new style
- can polish them again.
-
- Note that unpolish() will only be called if the widget is
- destroyed. This can cause problems in some cases, e.g, if you
- remove a widget from the UI, cache it, and then reinsert it after
- the style has changed; some of Qt's classes cache their widgets.
-
- \sa polish()
-*/
-void QStyle::unpolish(QWidget * /* widget */)
-{
-}
-
-/*!
- \fn void QStyle::polish(QApplication * application)
- \overload
-
- Late initialization of the given \a application object.
-*/
-void QStyle::polish(QApplication * /* app */)
-{
-}
-
-/*!
- \fn void QStyle::unpolish(QApplication * application)
- \overload
-
- Uninitialize the given \a application.
-*/
-void QStyle::unpolish(QApplication * /* app */)
-{
-}
-
-/*!
- \fn void QStyle::polish(QPalette & palette)
- \overload
-
- Changes the \a palette according to style specific requirements
- for color palettes (if any).
-
- \sa QPalette, QApplication::setPalette()
-*/
-void QStyle::polish(QPalette & /* pal */)
-{
-}
-
-/*!
- \fn QRect QStyle::itemTextRect(const QFontMetrics &metrics, const QRect &rectangle, int alignment, bool enabled, const QString &text) const
-
- Returns the area within the given \a rectangle in which to draw
- the provided \a text according to the specified font \a metrics
- and \a alignment. The \a enabled parameter indicates whether or
- not the associated item is enabled.
-
- If the given \a rectangle is larger than the area needed to render
- the \a text, the rectangle that is returned will be offset within
- \a rectangle according to the specified \a alignment. For
- example, if \a alignment is Qt::AlignCenter, the returned
- rectangle will be centered within \a rectangle. If the given \a
- rectangle is smaller than the area needed, the returned rectangle
- will be the smallest rectangle large enough to render the \a text.
-
- \sa Qt::Alignment
-*/
-QRect QStyle::itemTextRect(const QFontMetrics &metrics, const QRect &rect, int alignment, bool enabled,
- const QString &text) const
-{
- QRect result;
- int x, y, w, h;
- rect.getRect(&x, &y, &w, &h);
- if (!text.isEmpty()) {
- result = metrics.boundingRect(x, y, w, h, alignment, text);
- if (!enabled && proxy()->styleHint(SH_EtchDisabledText)) {
- result.setWidth(result.width()+1);
- result.setHeight(result.height()+1);
- }
- } else {
- result = QRect(x, y, w, h);
- }
- return result;
-}
-
-/*!
- \fn QRect QStyle::itemPixmapRect(const QRect &rectangle, int alignment, const QPixmap &pixmap) const
-
- Returns the area within the given \a rectangle in which to draw
- the specified \a pixmap according to the defined \a alignment.
-*/
-QRect QStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const
-{
- QRect result;
- int x, y, w, h;
- rect.getRect(&x, &y, &w, &h);
- if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
- y += h/2 - pixmap.height()/2;
- else if ((alignment & Qt::AlignBottom) == Qt::AlignBottom)
- y += h - pixmap.height();
- if ((alignment & Qt::AlignRight) == Qt::AlignRight)
- x += w - pixmap.width();
- else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
- x += w/2 - pixmap.width()/2;
- else if ((alignment & Qt::AlignLeft) != Qt::AlignLeft && QApplication::isRightToLeft())
- x += w - pixmap.width();
- result = QRect(x, y, pixmap.width(), pixmap.height());
- return result;
-}
-
-/*!
- \fn void QStyle::drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette, bool enabled, const QString& text, QPalette::ColorRole textRole) const
-
- Draws the given \a text in the specified \a rectangle using the
- provided \a painter and \a palette.
-
- The text is drawn using the painter's pen, and aligned and wrapped
- according to the specified \a alignment. If an explicit \a
- textRole is specified, the text is drawn using the \a palette's
- color for the given role. The \a enabled parameter indicates
- whether or not the item is enabled; when reimplementing this
- function, the \a enabled parameter should influence how the item is
- drawn.
-
- \sa Qt::Alignment, drawItemPixmap()
-*/
-void QStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const
-{
- if (text.isEmpty())
- return;
- QPen savedPen;
- if (textRole != QPalette::NoRole) {
- savedPen = painter->pen();
- painter->setPen(QPen(pal.brush(textRole), savedPen.widthF()));
- }
- if (!enabled) {
- if (proxy()->styleHint(SH_DitherDisabledText)) {
- QRect br;
- painter->drawText(rect, alignment, text, &br);
- painter->fillRect(br, QBrush(painter->background().color(), Qt::Dense5Pattern));
- return;
- } else if (proxy()->styleHint(SH_EtchDisabledText)) {
- QPen pen = painter->pen();
- painter->setPen(pal.light().color());
- painter->drawText(rect.adjusted(1, 1, 1, 1), alignment, text);
- painter->setPen(pen);
- }
- }
- painter->drawText(rect, alignment, text);
- if (textRole != QPalette::NoRole)
- painter->setPen(savedPen);
-}
-
-/*!
- \fn void QStyle::drawItemPixmap(QPainter *painter, const QRect &rectangle, int alignment,
- const QPixmap &pixmap) const
-
- Draws the given \a pixmap in the specified \a rectangle, according
- to the specified \a alignment, using the provided \a painter.
-
- \sa drawItemText()
-*/
-
-void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
- const QPixmap &pixmap) const
-{
- QRect aligned = alignedRect(QApplication::layoutDirection(), QFlag(alignment), pixmap.size(), rect);
- QRect inter = aligned.intersected(rect);
-
- painter->drawPixmap(inter.x(), inter.y(), pixmap, inter.x() - aligned.x(), inter.y() - aligned.y(), inter.width(), inter.height());
-}
-
-/*!
- \enum QStyle::PrimitiveElement
-
- This enum describes the various primitive elements. A
- primitive element is a common GUI element, such as a checkbox
- indicator or button bevel.
-
- \omitvalue PE_IndicatorViewItemCheck
- \value PE_FrameStatusBar Frame
-
- \value PE_PanelButtonCommand Button used to initiate an action, for
- example, a QPushButton.
-
- \value PE_FrameDefaultButton This frame around a default button, e.g. in a dialog.
- \value PE_PanelButtonBevel Generic panel with a button bevel.
- \value PE_PanelButtonTool Panel for a Tool button, used with QToolButton.
- \value PE_PanelLineEdit Panel for a QLineEdit.
- \value PE_IndicatorButtonDropDown Indicator for a drop down button, for example, a tool
- button that displays a menu.
-
- \value PE_FrameFocusRect Generic focus indicator.
-
- \value PE_IndicatorArrowUp Generic Up arrow.
- \value PE_IndicatorArrowDown Generic Down arrow.
- \value PE_IndicatorArrowRight Generic Right arrow.
- \value PE_IndicatorArrowLeft Generic Left arrow.
-
- \value PE_IndicatorSpinUp Up symbol for a spin widget, for example a QSpinBox.
- \value PE_IndicatorSpinDown Down symbol for a spin widget.
- \value PE_IndicatorSpinPlus Increase symbol for a spin widget.
- \value PE_IndicatorSpinMinus Decrease symbol for a spin widget.
-
- \value PE_IndicatorItemViewItemCheck On/off indicator for a view item.
-
- \value PE_IndicatorCheckBox On/off indicator, for example, a QCheckBox.
- \value PE_IndicatorRadioButton Exclusive on/off indicator, for example, a QRadioButton.
-
- \value PE_Q3DockWindowSeparator Item separator for Qt 3 compatible dock window
- and toolbar contents.
- \value PE_IndicatorDockWidgetResizeHandle Resize handle for dock windows.
-
- \value PE_Frame Generic frame
- \value PE_FrameMenu Frame for popup windows/menus; see also QMenu.
- \value PE_PanelMenuBar Panel for menu bars.
- \value PE_PanelScrollAreaCorner Panel at the bottom-right (or
- bottom-left) corner of a scroll area.
-
- \value PE_FrameDockWidget Panel frame for dock windows and toolbars.
- \value PE_FrameTabWidget Frame for tab widgets.
- \value PE_FrameLineEdit Panel frame for line edits.
- \value PE_FrameGroupBox Panel frame around group boxes.
- \value PE_FrameButtonBevel Panel frame for a button bevel.
- \value PE_FrameButtonTool Panel frame for a tool button.
-
- \value PE_IndicatorHeaderArrow Arrow used to indicate sorting on a list or table
- header.
- \value PE_FrameStatusBarItem Frame for an item of a status bar; see also QStatusBar.
-
- \value PE_FrameWindow Frame around a MDI window or a docking window.
-
- \value PE_Q3Separator Qt 3 compatible generic separator.
-
- \value PE_IndicatorMenuCheckMark Check mark used in a menu.
-
- \value PE_IndicatorProgressChunk Section of a progress bar indicator; see also QProgressBar.
-
- \value PE_Q3CheckListController Qt 3 compatible controller part of a list view item.
- \value PE_Q3CheckListIndicator Qt 3 compatible checkbox part of a list view item.
- \value PE_Q3CheckListExclusiveIndicator Qt 3 compatible radio button part of a list view item.
-
- \value PE_IndicatorBranch Lines used to represent the branch of a tree in a tree view.
- \value PE_IndicatorToolBarHandle The handle of a toolbar.
- \value PE_IndicatorToolBarSeparator The separator in a toolbar.
- \value PE_PanelToolBar The panel for a toolbar.
- \value PE_PanelTipLabel The panel for a tip label.
- \value PE_FrameTabBarBase The frame that is drawn for a tab bar, ususally drawn for a tab bar that isn't part of a tab widget.
- \value PE_IndicatorTabTear An indicator that a tab is partially scrolled out of the visible tab bar when there are many tabs.
- \value PE_IndicatorColumnViewArrow An arrow in a QColumnView.
-
- \value PE_Widget A plain QWidget.
-
- \value PE_CustomBase Base value for custom primitive elements.
- All values above this are reserved for custom use. Custom values
- must be greater than this value.
-
- \value PE_IndicatorItemViewItemDrop An indicator that is drawn to show where an item in an item view is about to be dropped
- during a drag-and-drop operation in an item view.
- \value PE_PanelItemViewItem The background for an item in an item view.
- \value PE_PanelItemViewRow The background of a row in an item view.
-
- \value PE_PanelStatusBar The panel for a status bar.
-
- \value PE_IndicatorTabClose The close button on a tab bar.
- \value PE_PanelMenu The panel for a menu.
-
- \sa drawPrimitive()
-*/
-
-/*!
- \typedef QStyle::SFlags
- \internal
-*/
-
-/*!
- \typedef QStyle::SCFlags
- \internal
-*/
-
-/*!
- \enum QStyle::StateFlag
-
- This enum describes flags that are used when drawing primitive
- elements.
-
- Note that not all primitives use all of these flags, and that the
- flags may mean different things to different items.
-
- \value State_None Indicates that the widget does not have a state.
- \value State_Active Indicates that the widget is active.
- \value State_AutoRaise Used to indicate if auto-raise appearance should be usd on a tool button.
- \value State_Children Used to indicate if an item view branch has children.
- \value State_DownArrow Used to indicate if a down arrow should be visible on the widget.
- \value State_Editing Used to indicate if an editor is opened on the widget.
- \value State_Enabled Used to indicate if the widget is enabled.
- \value State_HasEditFocus Used to indicate if the widget currently has edit focus.
- \value State_HasFocus Used to indicate if the widget has focus.
- \value State_Horizontal Used to indicate if the widget is laid out horizontally, for example. a tool bar.
- \value State_KeyboardFocusChange Used to indicate if the focus was changed with the keyboard, e.g., tab, backtab or shortcut.
- \value State_MouseOver Used to indicate if the widget is under the mouse.
- \value State_NoChange Used to indicate a tri-state checkbox.
- \value State_Off Used to indicate if the widget is not checked.
- \value State_On Used to indicate if the widget is checked.
- \value State_Raised Used to indicate if a button is raised.
- \value State_ReadOnly Used to indicate if a widget is read-only.
- \value State_Selected Used to indicate if a widget is selected.
- \value State_Item Used by item views to indicate if a horizontal branch should be drawn.
- \value State_Open Used by item views to indicate if the tree branch is open.
- \value State_Sibling Used by item views to indicate if a vertical line needs to be drawn (for siblings).
- \value State_Sunken Used to indicate if the widget is sunken or pressed.
- \value State_UpArrow Used to indicate if an up arrow should be visible on the widget.
- \value State_Mini Used to indicate a mini style Mac widget or button.
- \value State_Small Used to indicate a small style Mac widget or button.
- \omitvalue State_Window
- \omitvalue State_Bottom
- \omitvalue State_Default
- \omitvalue State_FocusAtBorder
- \omitvalue State_Top
-
- \sa drawPrimitive()
-*/
-
-/*!
- \fn void QStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, \
- QPainter *painter, const QWidget *widget) const
-
- Draws the given primitive \a element with the provided \a painter using the style
- options specified by \a option.
-
- The \a widget argument is optional and may contain a widget that may
- aid in drawing the primitive element.
-
- The table below is listing the primitive elements and their
- associated style option subclasses. The style options contain all
- the parameters required to draw the elements, including
- QStyleOption::state which holds the style flags that are used when
- drawing. The table also describes which flags that are set when
- casting the given option to the appropriate subclass.
-
- Note that if a primitive element is not listed here, it is because
- it uses a plain QStyleOption object.
-
- \table
- \header \o Primitive Element \o QStyleOption Subclass \o Style Flag \o Remark
- \row \o \l PE_FrameFocusRect \o \l QStyleOptionFocusRect
- \o \l State_FocusAtBorder
- \o Whether the focus is is at the border or inside the widget.
- \row \o{1,2} \l PE_IndicatorCheckBox \o{1,2} \l QStyleOptionButton
- \o \l State_NoChange \o Indicates a "tri-state" checkbox.
- \row \o \l State_On \o Indicates the indicator is checked.
- \row \o \l PE_IndicatorRadioButton \o \l QStyleOptionButton
- \o \l State_On \o Indicates that a radio button is selected.
- \row \o{1,3} \l PE_Q3CheckListExclusiveIndicator, \l PE_Q3CheckListIndicator
- \o{1,3} \l QStyleOptionQ3ListView \o \l State_On
- \o Indicates whether or not the controller is selected.
- \row \o \l State_NoChange \o Indicates a "tri-state" controller.
- \row \o \l State_Enabled \o Indicates the controller is enabled.
- \row \o{1,4} \l PE_IndicatorBranch \o{1,4} \l QStyleOption
- \o \l State_Children \o Indicates that the control for expanding the tree to show child items, should be drawn.
- \row \o \l State_Item \o Indicates that a horizontal branch (to show a child item), should be drawn.
- \row \o \l State_Open \o Indicates that the tree branch is expanded.
- \row \o \l State_Sibling \o Indicates that a vertical line (to show a sibling item), should be drawn.
- \row \o \l PE_IndicatorHeaderArrow \o \l QStyleOptionHeader
- \o \l State_UpArrow \o Indicates that the arrow should be drawn up;
- otherwise it should be down.
- \row \o \l PE_FrameGroupBox, \l PE_Frame, \l PE_FrameLineEdit,
- \l PE_FrameMenu, \l PE_FrameDockWidget, \l PE_FrameWindow
- \o \l QStyleOptionFrame \o \l State_Sunken
- \o Indicates that the Frame should be sunken.
- \row \o \l PE_IndicatorToolBarHandle \o \l QStyleOption
- \o \l State_Horizontal \o Indicates that the window handle is horizontal
- instead of vertical.
- \row \o \l PE_Q3DockWindowSeparator \o \l QStyleOption
- \o \l State_Horizontal \o Indicates that the separator is horizontal
- instead of vertical.
- \row \o \l PE_IndicatorSpinPlus, \l PE_IndicatorSpinMinus, \l PE_IndicatorSpinUp,
- \l PE_IndicatorSpinDown,
- \o \l QStyleOptionSpinBox
- \o \l State_Sunken \o Indicates that the button is pressed.
- \row \o{1,5} \l PE_PanelButtonCommand
- \o{1,5} \l QStyleOptionButton
- \o \l State_Enabled \o Set if the button is enabled.
- \row \o \l State_HasFocus \o Set if the button has input focus.
- \row \o \l State_Raised \o Set if the button is not down, not on and not flat.
- \row \o \l State_On \o Set if the button is a toggle button and is toggled on.
- \row \o \l State_Sunken
- \o Set if the button is down (i.e., the mouse button or the
- space bar is pressed on the button).
- \endtable
-
- \sa drawComplexControl(), drawControl()
-*/
-
-/*!
- \enum QStyle::ControlElement
-
- This enum represents a control element. A control element is a
- part of a widget that performs some action or displays information
- to the user.
-
- \value CE_PushButton A QPushButton, draws CE_PushButtonBevel, CE_PushButtonLabel and PE_FrameFocusRect.
- \value CE_PushButtonBevel The bevel and default indicator of a QPushButton.
- \value CE_PushButtonLabel The label (an icon with text or pixmap) of a QPushButton.
-
- \value CE_DockWidgetTitle Dock window title.
- \value CE_Splitter Splitter handle; see also QSplitter.
-
-
- \value CE_CheckBox A QCheckBox, draws a PE_IndicatorCheckBox, a CE_CheckBoxLabel and a PE_FrameFocusRect.
- \value CE_CheckBoxLabel The label (text or pixmap) of a QCheckBox.
-
- \value CE_RadioButton A QRadioButton, draws a PE_IndicatorRadioButton, a CE_RadioButtonLabel and a PE_FrameFocusRect.
- \value CE_RadioButtonLabel The label (text or pixmap) of a QRadioButton.
-
- \value CE_TabBarTab The tab and label within a QTabBar.
- \value CE_TabBarTabShape The tab shape within a tab bar.
- \value CE_TabBarTabLabel The label within a tab.
-
- \value CE_ProgressBar A QProgressBar, draws CE_ProgressBarGroove, CE_ProgressBarContents and CE_ProgressBarLabel.
- \value CE_ProgressBarGroove The groove where the progress
- indicator is drawn in a QProgressBar.
- \value CE_ProgressBarContents The progress indicator of a QProgressBar.
- \value CE_ProgressBarLabel The text label of a QProgressBar.
-
- \value CE_ToolButtonLabel A tool button's label.
-
- \value CE_MenuBarItem A menu item in a QMenuBar.
- \value CE_MenuBarEmptyArea The empty area of a QMenuBar.
-
- \value CE_MenuItem A menu item in a QMenu.
- \value CE_MenuScroller Scrolling areas in a QMenu when the
- style supports scrolling.
- \value CE_MenuTearoff A menu item representing the tear off section of
- a QMenu.
- \value CE_MenuEmptyArea The area in a menu without menu items.
- \value CE_MenuHMargin The horizontal extra space on the left/right of a menu.
- \value CE_MenuVMargin The vertical extra space on the top/bottom of a menu.
-
- \value CE_Q3DockWindowEmptyArea The empty area of a QDockWidget.
-
- \value CE_ToolBoxTab The toolbox's tab and label within a QToolBox.
- \value CE_SizeGrip Window resize handle; see also QSizeGrip.
-
- \value CE_Header A header.
- \value CE_HeaderSection A header section.
- \value CE_HeaderLabel The header's label.
-
- \value CE_ScrollBarAddLine Scroll bar line increase indicator.
- (i.e., scroll down); see also QScrollBar.
- \value CE_ScrollBarSubLine Scroll bar line decrease indicator (i.e., scroll up).
- \value CE_ScrollBarAddPage Scolllbar page increase indicator (i.e., page down).
- \value CE_ScrollBarSubPage Scroll bar page decrease indicator (i.e., page up).
- \value CE_ScrollBarSlider Scroll bar slider.
- \value CE_ScrollBarFirst Scroll bar first line indicator (i.e., home).
- \value CE_ScrollBarLast Scroll bar last line indicator (i.e., end).
-
- \value CE_RubberBand Rubber band used in for example an icon view.
-
- \value CE_FocusFrame Focus frame that is style controlled.
-
- \value CE_ItemViewItem An item inside an item view.
-
- \value CE_CustomBase Base value for custom control elements;
- custom values must be greater than this value.
- \value CE_ComboBoxLabel The label of a non-editable QComboBox.
- \value CE_ToolBar A toolbar like QToolBar.
- \value CE_ToolBoxTabShape The toolbox's tab shape.
- \value CE_ToolBoxTabLabel The toolbox's tab label.
- \value CE_HeaderEmptyArea The area of a header view where there are no header sections.
-
- \value CE_ShapedFrame The frame with the shape specified in the QStyleOptionFrameV3; see QFrame.
-
- \omitvalue CE_ColumnViewGrip
-
- \sa drawControl()
-*/
-
-/*!
- \fn void QStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
-
- Draws the given \a element with the provided \a painter with the
- style options specified by \a option.
-
- The \a widget argument is optional and can be used as aid in
- drawing the control. The \a option parameter is a pointer to a
- QStyleOption object that can be cast to the correct subclass
- using the qstyleoption_cast() function.
-
- The table below is listing the control elements and their
- associated style option subclass. The style options contain all
- the parameters required to draw the controls, including
- QStyleOption::state which holds the style flags that are used when
- drawing. The table also describes which flags that are set when
- casting the given option to the appropriate subclass.
-
- Note that if a control element is not listed here, it is because
- it uses a plain QStyleOption object.
-
- \table
- \header \o Control Element \o QStyleOption Subclass \o Style Flag \o Remark
- \row \o{1,5} \l CE_MenuItem, \l CE_MenuBarItem
- \o{1,5} \l QStyleOptionMenuItem
- \o \l State_Selected \o The menu item is currently selected item.
- \row \o \l State_Enabled \o The item is enabled.
- \row \o \l State_DownArrow \o Indicates that a scroll down arrow should be drawn.
- \row \o \l State_UpArrow \o Indicates that a scroll up arrow should be drawn
- \row \o \l State_HasFocus \o Set if the menu bar has input focus.
-
- \row \o{1,5} \l CE_PushButton, \l CE_PushButtonBevel, \l CE_PushButtonLabel
- \o{1,5} \l QStyleOptionButton
- \o \l State_Enabled \o Set if the button is enabled.
- \row \o \l State_HasFocus \o Set if the button has input focus.
- \row \o \l State_Raised \o Set if the button is not down, not on and not flat.
- \row \o \l State_On \o Set if the button is a toggle button and is toggled on.
- \row \o \l State_Sunken
- \o Set if the button is down (i.e., the mouse button or the
- space bar is pressed on the button).
-
- \row \o{1,6} \l CE_RadioButton, \l CE_RadioButtonLabel,
- \l CE_CheckBox, \l CE_CheckBoxLabel
- \o{1,6} \l QStyleOptionButton
- \o \l State_Enabled \o Set if the button is enabled.
- \row \o \l State_HasFocus \o Set if the button has input focus.
- \row \o \l State_On \o Set if the button is checked.
- \row \o \l State_Off \o Set if the button is not checked.
- \row \o \l State_NoChange \o Set if the button is in the NoChange state.
- \row \o \l State_Sunken
- \o Set if the button is down (i.e., the mouse button or
- the space bar is pressed on the button).
-
- \row \o{1,2} \l CE_ProgressBarContents, \l CE_ProgressBarLabel,
- \l CE_ProgressBarGroove
- \o{1,2} \l QStyleOptionProgressBar
- \o \l State_Enabled \o Set if the progress bar is enabled.
- \row \o \l State_HasFocus \o Set if the progress bar has input focus.
-
- \row \o \l CE_Header, \l CE_HeaderSection, \l CE_HeaderLabel \o \l QStyleOptionHeader \o \o
-
- \row \o{1,3} \l CE_TabBarTab, CE_TabBarTabShape, CE_TabBarTabLabel
- \o{1,3} \l QStyleOptionTab
- \o \l State_Enabled \o Set if the tab bar is enabled.
- \row \o \l State_Selected \o The tab bar is the currently selected tab bar.
- \row \o \l State_HasFocus \o Set if the tab bar tab has input focus.
-
- \row \o{1,7} \l CE_ToolButtonLabel
- \o{1,7} \l QStyleOptionToolButton
- \o \l State_Enabled \o Set if the tool button is enabled.
- \row \o \l State_HasFocus \o Set if the tool button has input focus.
- \row \o \l State_Sunken
- \o Set if the tool button is down (i.e., a mouse button or
- the space bar is pressed).
- \row \o \l State_On \o Set if the tool button is a toggle button and is toggled on.
- \row \o \l State_AutoRaise \o Set if the tool button has auto-raise enabled.
- \row \o \l State_MouseOver \o Set if the mouse pointer is over the tool button.
- \row \o \l State_Raised \o Set if the button is not down and is not on.
-
- \row \o \l CE_ToolBoxTab \o \l QStyleOptionToolBox
- \o \l State_Selected \o The tab is the currently selected tab.
- \row \o{1,3} \l CE_HeaderSection \o{1,3} \l QStyleOptionHeader
- \o \l State_Sunken \o Indicates that the section is pressed.
- \row \o \l State_UpArrow \o Indicates that the sort indicator should be pointing up.
- \row \o \l State_DownArrow \o Indicates that the sort indicator should be pointing down.
- \endtable
-
- \sa drawPrimitive(), drawComplexControl()
-*/
-
-/*!
- \enum QStyle::SubElement
-
- This enum represents a sub-area of a widget. Style implementations
- use these areas to draw the different parts of a widget.
-
- \value SE_PushButtonContents Area containing the label (icon
- with text or pixmap).
- \value SE_PushButtonFocusRect Area for the focus rect (usually
- larger than the contents rect).
- \value SE_PushButtonLayoutItem Area that counts for the parent layout.
-
- \value SE_CheckBoxIndicator Area for the state indicator (e.g., check mark).
- \value SE_CheckBoxContents Area for the label (text or pixmap).
- \value SE_CheckBoxFocusRect Area for the focus indicator.
- \value SE_CheckBoxClickRect Clickable area, defaults to SE_CheckBoxFocusRect.
- \value SE_CheckBoxLayoutItem Area that counts for the parent layout.
-
- \value SE_DateTimeEditLayoutItem Area that counts for the parent layout.
-
- \value SE_RadioButtonIndicator Area for the state indicator.
- \value SE_RadioButtonContents Area for the label.
- \value SE_RadioButtonFocusRect Area for the focus indicator.
- \value SE_RadioButtonClickRect Clickable area, defaults to SE_RadioButtonFocusRect.
- \value SE_RadioButtonLayoutItem Area that counts for the parent layout.
-
- \value SE_ComboBoxFocusRect Area for the focus indicator.
-
- \value SE_SliderFocusRect Area for the focus indicator.
- \value SE_SliderLayoutItem Area that counts for the parent layout.
-
- \value SE_SpinBoxLayoutItem Area that counts for the parent layout.
-
- \value SE_Q3DockWindowHandleRect Area for the tear-off handle.
-
- \value SE_ProgressBarGroove Area for the groove.
- \value SE_ProgressBarContents Area for the progress indicator.
- \value SE_ProgressBarLabel Area for the text label.
- \value SE_ProgressBarLayoutItem Area that counts for the parent layout.
-
- \omitvalue SE_DialogButtonAccept
- \omitvalue SE_DialogButtonReject
- \omitvalue SE_DialogButtonApply
- \omitvalue SE_DialogButtonHelp
- \omitvalue SE_DialogButtonAll
- \omitvalue SE_DialogButtonRetry
- \omitvalue SE_DialogButtonAbort
- \omitvalue SE_DialogButtonIgnore
- \omitvalue SE_DialogButtonCustom
- \omitvalue SE_ViewItemCheckIndicator
-
- \value SE_FrameContents Area for a frame's contents.
- \value SE_ShapedFrameContents Area for a frame's contents using the shape in QStyleOptionFrameV3; see QFrame
- \value SE_FrameLayoutItem Area that counts for the parent layout.
-
- \value SE_HeaderArrow Area for the sort indicator for a header.
- \value SE_HeaderLabel Area for the label in a header.
-
- \value SE_LabelLayoutItem Area that counts for the parent layout.
-
- \value SE_LineEditContents Area for a line edit's contents.
-
- \value SE_TabWidgetLeftCorner Area for the left corner widget in a tab widget.
- \value SE_TabWidgetRightCorner Area for the right corner widget in a tab widget.
- \value SE_TabWidgetTabBar Area for the tab bar widget in a tab widget.
- \value SE_TabWidgetTabContents Area for the contents of the tab widget.
- \value SE_TabWidgetTabPane Area for the pane of a tab widget.
- \value SE_TabWidgetLayoutItem Area that counts for the parent layout.
-
- \value SE_ToolBoxTabContents Area for a toolbox tab's icon and label.
-
- \value SE_ToolButtonLayoutItem Area that counts for the parent layout.
-
- \value SE_ItemViewItemCheckIndicator Area for a view item's check mark.
-
- \value SE_TabBarTearIndicator Area for the tear indicator on a tab bar with scroll arrows.
-
- \value SE_TreeViewDisclosureItem Area for the actual disclosure item in a tree branch.
-
- \value SE_DialogButtonBoxLayoutItem Area that counts for the parent layout.
-
- \value SE_GroupBoxLayoutItem Area that counts for the parent layout.
-
- \value SE_CustomBase Base value for custom sub-elements.
- Custom values must be greater than this value.
-
- \value SE_DockWidgetFloatButton The float button of a dock
- widget.
- \value SE_DockWidgetTitleBarText The text bounds of the dock
- widgets title.
- \value SE_DockWidgetCloseButton The close button of a dock
- widget.
- \value SE_DockWidgetIcon The icon of a dock widget.
- \value SE_ComboBoxLayoutItem Area that counts for the parent layout.
-
-
- \value SE_ItemViewItemDecoration Area for a view item's decoration (icon).
- \value SE_ItemViewItemText Area for a view item's text.
- \value SE_ItemViewItemFocusRect Area for a view item's focus rect.
-
- \value SE_TabBarTabLeftButton Area for a widget on the left side of a tab in a tab bar.
- \value SE_TabBarTabRightButton Area for a widget on the right side of a tab in a tab bar.
- \value SE_TabBarTabText Area for the text on a tab in a tab bar.
-
- \value SE_ToolBarHandle Area for the handle of a tool bar.
-
- \sa subElementRect()
-*/
-
-/*!
- \fn QRect QStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
-
- Returns the sub-area for the given \a element as described in the
- provided style \a option. The returned rectangle is defined in
- screen coordinates.
-
- The \a widget argument is optional and can be used to aid
- determining the area. The QStyleOption object can be cast to the
- appropriate type using the qstyleoption_cast() function. See the
- table below for the appropriate \a option casts:
-
- \table
- \header \o Sub Element \o QStyleOption Subclass
- \row \o \l SE_PushButtonContents \o \l QStyleOptionButton
- \row \o \l SE_PushButtonFocusRect \o \l QStyleOptionButton
- \row \o \l SE_CheckBoxIndicator \o \l QStyleOptionButton
- \row \o \l SE_CheckBoxContents \o \l QStyleOptionButton
- \row \o \l SE_CheckBoxFocusRect \o \l QStyleOptionButton
- \row \o \l SE_RadioButtonIndicator \o \l QStyleOptionButton
- \row \o \l SE_RadioButtonContents \o \l QStyleOptionButton
- \row \o \l SE_RadioButtonFocusRect \o \l QStyleOptionButton
- \row \o \l SE_ComboBoxFocusRect \o \l QStyleOptionComboBox
- \row \o \l SE_Q3DockWindowHandleRect \o \l QStyleOptionQ3DockWindow
- \row \o \l SE_ProgressBarGroove \o \l QStyleOptionProgressBar
- \row \o \l SE_ProgressBarContents \o \l QStyleOptionProgressBar
- \row \o \l SE_ProgressBarLabel \o \l QStyleOptionProgressBar
- \endtable
-*/
-
-/*!
- \enum QStyle::ComplexControl
-
- This enum describes the available complex controls. Complex
- controls have different behavior depending upon where the user
- clicks on them or which keys are pressed.
-
- \value CC_SpinBox A spinbox, like QSpinBox.
- \value CC_ComboBox A combobox, like QComboBox.
- \value CC_ScrollBar A scroll bar, like QScrollBar.
- \value CC_Slider A slider, like QSlider.
- \value CC_ToolButton A tool button, like QToolButton.
- \value CC_TitleBar A Title bar, like those used in QMdiSubWindow.
- \value CC_Q3ListView Used for drawing the Q3ListView class.
- \value CC_GroupBox A group box, like QGroupBox.
- \value CC_Dial A dial, like QDial.
- \value CC_MdiControls The minimize, close, and normal
- button in the menu bar for a
- maximized MDI subwindow.
-
- \value CC_CustomBase Base value for custom complex controls. Custom
- values must be greater than this value.
-
- \sa SubControl drawComplexControl()
-*/
-
-/*!
- \enum QStyle::SubControl
-
- This enum describes the available sub controls. A subcontrol is a
- control element within a complex control (ComplexControl).
-
- \value SC_None Special value that matches no other sub control.
-
- \value SC_ScrollBarAddLine Scroll bar add line (i.e., down/right
- arrow); see also QScrollBar.
- \value SC_ScrollBarSubLine Scroll bar sub line (i.e., up/left arrow).
- \value SC_ScrollBarAddPage Scroll bar add page (i.e., page down).
- \value SC_ScrollBarSubPage Scroll bar sub page (i.e., page up).
- \value SC_ScrollBarFirst Scroll bar first line (i.e., home).
- \value SC_ScrollBarLast Scroll bar last line (i.e., end).
- \value SC_ScrollBarSlider Scroll bar slider handle.
- \value SC_ScrollBarGroove Special sub-control which contains the
- area in which the slider handle may move.
-
- \value SC_SpinBoxUp Spin widget up/increase; see also QSpinBox.
- \value SC_SpinBoxDown Spin widget down/decrease.
- \value SC_SpinBoxFrame Spin widget frame.
- \value SC_SpinBoxEditField Spin widget edit field.
-
- \value SC_ComboBoxEditField Combobox edit field; see also QComboBox.
- \value SC_ComboBoxArrow Combobox arrow button.
- \value SC_ComboBoxFrame Combobox frame.
- \value SC_ComboBoxListBoxPopup The reference rectangle for the combobox popup.
- Used to calculate the position of the popup.
-
- \value SC_SliderGroove Special sub-control which contains the area
- in which the slider handle may move.
- \value SC_SliderHandle Slider handle.
- \value SC_SliderTickmarks Slider tickmarks.
-
- \value SC_ToolButton Tool button (see also QToolButton).
- \value SC_ToolButtonMenu Sub-control for opening a popup menu in a
- tool button; see also Q3PopupMenu.
-
- \value SC_TitleBarSysMenu System menu button (i.e., restore, close, etc.).
- \value SC_TitleBarMinButton Minimize button.
- \value SC_TitleBarMaxButton Maximize button.
- \value SC_TitleBarCloseButton Close button.
- \value SC_TitleBarLabel Window title label.
- \value SC_TitleBarNormalButton Normal (restore) button.
- \value SC_TitleBarShadeButton Shade button.
- \value SC_TitleBarUnshadeButton Unshade button.
- \value SC_TitleBarContextHelpButton Context Help button.
-
- \value SC_Q3ListView The list view area.
- \value SC_Q3ListViewExpand Expand item (i.e., show/hide child items).
-
- \value SC_DialHandle The handle of the dial (i.e. what you use to control the dial).
- \value SC_DialGroove The groove for the dial.
- \value SC_DialTickmarks The tickmarks for the dial.
-
- \value SC_GroupBoxFrame The frame of a group box.
- \value SC_GroupBoxLabel The title of a group box.
- \value SC_GroupBoxCheckBox The optional check box of a group box.
- \value SC_GroupBoxContents The group box contents.
-
- \value SC_MdiNormalButton The normal button for a MDI
- subwindow in the menu bar.
- \value SC_MdiMinButton The minimize button for a MDI
- subwindow in the menu bar.
- \value SC_MdiCloseButton The close button for a MDI subwindow
- in the menu bar.
-
- \value SC_All Special value that matches all sub-controls.
- \omitvalue SC_Q3ListViewBranch
- \omitvalue SC_CustomBase
-
- \sa ComplexControl
-*/
-
-/*!
- \fn void QStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
-
- Draws the given \a control using the provided \a painter with the
- style options specified by \a option.
-
- The \a widget argument is optional and can be used as aid in
- drawing the control.
-
- The \a option parameter is a pointer to a QStyleOptionComplex
- object that can be cast to the correct subclass using the
- qstyleoption_cast() function. Note that the \c rect member of the
- specified \a option must be in logical
- coordinates. Reimplementations of this function should use
- visualRect() to change the logical coordinates into screen
- coordinates before calling the drawPrimitive() or drawControl()
- function.
-
- The table below is listing the complex control elements and their
- associated style option subclass. The style options contain all
- the parameters required to draw the controls, including
- QStyleOption::state which holds the \l {QStyle::StateFlag}{style
- flags} that are used when drawing. The table also describes which
- flags that are set when casting the given \a option to the
- appropriate subclass.
-
- \table
- \header \o Complex Control \o QStyleOptionComplex Subclass \o Style Flag \o Remark
- \row \o{1,2} \l{CC_SpinBox} \o{1,2} \l QStyleOptionSpinBox
- \o \l State_Enabled \o Set if the spin box is enabled.
- \row \o \l State_HasFocus \o Set if the spin box has input focus.
-
- \row \o{1,2} \l {CC_ComboBox} \o{1,2} \l QStyleOptionComboBox
- \o \l State_Enabled \o Set if the combobox is enabled.
- \row \o \l State_HasFocus \o Set if the combobox has input focus.
-
- \row \o{1,2} \l {CC_ScrollBar} \o{1,2} \l QStyleOptionSlider
- \o \l State_Enabled \o Set if the scroll bar is enabled.
- \row \o \l State_HasFocus \o Set if the scroll bar has input focus.
-
- \row \o{1,2} \l {CC_Slider} \o{1,2} \l QStyleOptionSlider
- \o \l State_Enabled \o Set if the slider is enabled.
- \row \o \l State_HasFocus \o Set if the slider has input focus.
-
- \row \o{1,2} \l {CC_Dial} \o{1,2} \l QStyleOptionSlider
- \o \l State_Enabled \o Set if the dial is enabled.
- \row \o \l State_HasFocus \o Set if the dial has input focus.
-
- \row \o{1,6} \l {CC_ToolButton} \o{1,6} \l QStyleOptionToolButton
- \o \l State_Enabled \o Set if the tool button is enabled.
- \row \o \l State_HasFocus \o Set if the tool button has input focus.
- \row \o \l State_DownArrow \o Set if the tool button is down (i.e., a mouse
- button or the space bar is pressed).
- \row \o \l State_On \o Set if the tool button is a toggle button
- and is toggled on.
- \row \o \l State_AutoRaise \o Set if the tool button has auto-raise enabled.
- \row \o \l State_Raised \o Set if the button is not down, not on, and doesn't
- contain the mouse when auto-raise is enabled.
-
- \row \o \l{CC_TitleBar} \o \l QStyleOptionTitleBar
- \o \l State_Enabled \o Set if the title bar is enabled.
-
- \row \o \l{CC_Q3ListView} \o \l QStyleOptionQ3ListView
- \o \l State_Enabled \o Set if the list view is enabled.
-
- \endtable
-
- \sa drawPrimitive(), drawControl()
-*/
-
-
-/*!
- \fn QRect QStyle::subControlRect(ComplexControl control,
- const QStyleOptionComplex *option, SubControl subControl,
- const QWidget *widget) const = 0
-
- Returns the rectangle containing the specified \a subControl of
- the given complex \a control (with the style specified by \a
- option). The rectangle is defined in screen coordinates.
-
- The \a option argument is a pointer to QStyleOptionComplex or
- one of its subclasses, and can be cast to the appropriate type
- using the qstyleoption_cast() function. See drawComplexControl()
- for details. The \a widget is optional and can contain additional
- information for the function.
-
- \sa drawComplexControl()
-*/
-
-/*!
- \fn QStyle::SubControl QStyle::hitTestComplexControl(ComplexControl control,
- const QStyleOptionComplex *option, const QPoint &position,
- const QWidget *widget) const = 0
-
- Returns the sub control at the given \a position in the given
- complex \a control (with the style options specified by \a
- option).
-
- Note that the \a position is expressed in screen coordinates.
-
- The \a option argument is a pointer to a QStyleOptionComplex
- object (or one of its subclasses). The object can be cast to the
- appropriate type using the qstyleoption_cast() function. See
- drawComplexControl() for details. The \a widget argument is
- optional and can contain additional information for the function.
-
- \sa drawComplexControl(), subControlRect()
-*/
-
-/*!
- \enum QStyle::PixelMetric
-
- This enum describes the various available pixel metrics. A pixel
- metric is a style dependent size represented by a single pixel
- value.
-
- \value PM_ButtonMargin Amount of whitespace between push button
- labels and the frame.
- \value PM_DockWidgetTitleBarButtonMargin Amount of whitespace between dock widget's
- title bar button labels and the frame.
- \value PM_ButtonDefaultIndicator Width of the default-button indicator frame.
- \value PM_MenuButtonIndicator Width of the menu button indicator
- proportional to the widget height.
- \value PM_ButtonShiftHorizontal Horizontal contents shift of a
- button when the button is down.
- \value PM_ButtonShiftVertical Vertical contents shift of a button when the
- button is down.
-
- \value PM_DefaultFrameWidth Default frame width (usually 2).
- \value PM_SpinBoxFrameWidth Frame width of a spin box, defaults to PM_DefaultFrameWidth.
- \value PM_ComboBoxFrameWidth Frame width of a combo box, defaults to PM_DefaultFrameWidth.
-
- \value PM_MDIFrameWidth Obsolete. Use PM_MdiSubWindowFrameWidth instead.
- \value PM_MdiSubWindowFrameWidth Frame width of an MDI window.
- \value PM_MDIMinimizedWidth Obsolete. Use PM_MdiSubWindowMinimizedWidth instead.
- \value PM_MdiSubWindowMinimizedWidth Width of a minimized MDI window.
-
- \value PM_LayoutLeftMargin Default \l{QLayout::setContentsMargins()}{left margin} for a
- QLayout.
- \value PM_LayoutTopMargin Default \l{QLayout::setContentsMargins()}{top margin} for a QLayout.
- \value PM_LayoutRightMargin Default \l{QLayout::setContentsMargins()}{right margin} for a
- QLayout.
- \value PM_LayoutBottomMargin Default \l{QLayout::setContentsMargins()}{bottom margin} for a
- QLayout.
- \value PM_LayoutHorizontalSpacing Default \l{QLayout::spacing}{horizontal spacing} for a
- QLayout.
- \value PM_LayoutVerticalSpacing Default \l{QLayout::spacing}{vertical spacing} for a QLayout.
-
- \value PM_MaximumDragDistance The maximum allowed distance between
- the mouse and a scrollbar when dragging. Exceeding the specified
- distance will cause the slider to jump back to the original
- position; a value of -1 disables this behavior.
-
- \value PM_ScrollBarExtent Width of a vertical scroll bar and the
- height of a horizontal scroll bar.
- \value PM_ScrollBarSliderMin The minimum height of a vertical
- scroll bar's slider and the minimum width of a horizontal
- scroll bar's slider.
-
- \value PM_SliderThickness Total slider thickness.
- \value PM_SliderControlThickness Thickness of the slider handle.
- \value PM_SliderLength Length of the slider.
- \value PM_SliderTickmarkOffset The offset between the tickmarks
- and the slider.
- \value PM_SliderSpaceAvailable The available space for the slider to move.
-
- \value PM_DockWidgetSeparatorExtent Width of a separator in a
- horizontal dock window and the height of a separator in a
- vertical dock window.
- \value PM_DockWidgetHandleExtent Width of the handle in a
- horizontal dock window and the height of the handle in a
- vertical dock window.
- \value PM_DockWidgetFrameWidth Frame width of a dock window.
- \value PM_DockWidgetTitleMargin Margin of the dock window title.
-
- \value PM_MenuBarPanelWidth Frame width of a menu bar, defaults to PM_DefaultFrameWidth.
- \value PM_MenuBarItemSpacing Spacing between menu bar items.
- \value PM_MenuBarHMargin Spacing between menu bar items and left/right of bar.
- \value PM_MenuBarVMargin Spacing between menu bar items and top/bottom of bar.
-
- \value PM_ToolBarFrameWidth Width of the frame around toolbars.
- \value PM_ToolBarHandleExtent Width of a toolbar handle in a
- horizontal toolbar and the height of the handle in a vertical toolbar.
- \value PM_ToolBarItemMargin Spacing between the toolbar frame and the items.
- \value PM_ToolBarItemSpacing Spacing between toolbar items.
- \value PM_ToolBarSeparatorExtent Width of a toolbar separator in a
- horizontal toolbar and the height of a separator in a vertical toolbar.
- \value PM_ToolBarExtensionExtent Width of a toolbar extension
- button in a horizontal toolbar and the height of the button in a
- vertical toolbar.
-
- \value PM_TabBarTabOverlap Number of pixels the tabs should overlap.
- (Currently only used in styles, not inside of QTabBar)
- \value PM_TabBarTabHSpace Extra space added to the tab width.
- \value PM_TabBarTabVSpace Extra space added to the tab height.
- \value PM_TabBarBaseHeight Height of the area between the tab bar
- and the tab pages.
- \value PM_TabBarBaseOverlap Number of pixels the tab bar overlaps
- the tab bar base.
- \value PM_TabBarScrollButtonWidth
- \value PM_TabBarTabShiftHorizontal Horizontal pixel shift when a
- tab is selected.
- \value PM_TabBarTabShiftVertical Vertical pixel shift when a
- tab is selected.
-
- \value PM_ProgressBarChunkWidth Width of a chunk in a progress bar indicator.
-
- \value PM_SplitterWidth Width of a splitter.
-
- \value PM_TitleBarHeight Height of the title bar.
-
- \value PM_IndicatorWidth Width of a check box indicator.
- \value PM_IndicatorHeight Height of a checkbox indicator.
- \value PM_ExclusiveIndicatorWidth Width of a radio button indicator.
- \value PM_ExclusiveIndicatorHeight Height of a radio button indicator.
-
- \value PM_MenuPanelWidth Border width (applied on all sides) for a QMenu.
- \value PM_MenuHMargin Additional border (used on left and right) for a QMenu.
- \value PM_MenuVMargin Additional border (used for bottom and top) for a QMenu.
- \value PM_MenuScrollerHeight Height of the scroller area in a QMenu.
- \value PM_MenuTearoffHeight Height of a tear off area in a QMenu.
- \value PM_MenuDesktopFrameWidth The frame width for the menu on the desktop.
-
- \value PM_CheckListButtonSize Area (width/height) of the
- checkbox/radio button in a Q3CheckListItem.
- \value PM_CheckListControllerSize Area (width/height) of the
- controller in a Q3CheckListItem.
-
- \omitvalue PM_DialogButtonsSeparator
- \omitvalue PM_DialogButtonsButtonWidth
- \omitvalue PM_DialogButtonsButtonHeight
-
- \value PM_HeaderMarkSize The size of the sort indicator in a header.
- \value PM_HeaderGripMargin The size of the resize grip in a header.
- \value PM_HeaderMargin The size of the margin between the sort indicator and the text.
- \value PM_SpinBoxSliderHeight The height of the optional spin box slider.
-
- \value PM_ToolBarIconSize Default tool bar icon size
- \value PM_SmallIconSize Default small icon size
- \value PM_LargeIconSize Default large icon size
-
- \value PM_FocusFrameHMargin Horizontal margin that the focus frame will outset the widget by.
- \value PM_FocusFrameVMargin Vertical margin that the focus frame will outset the widget by.
- \value PM_IconViewIconSize The default size for icons in an icon view.
- \value PM_ListViewIconSize The default size for icons in a list view.
-
- \value PM_ToolTipLabelFrameWidth The frame width for a tool tip label.
- \value PM_CheckBoxLabelSpacing The spacing between a check box indicator and its label.
- \value PM_RadioButtonLabelSpacing The spacing between a radio button indicator and its label.
- \value PM_TabBarIconSize The default icon size for a tab bar.
- \value PM_SizeGripSize The size of a size grip.
- \value PM_MessageBoxIconSize The size of the standard icons in a message box
- \value PM_ButtonIconSize The default size of button icons
- \value PM_TextCursorWidth The width of the cursor in a line edit or text edit
- \value PM_TabBar_ScrollButtonOverlap The distance between the left and right buttons in a tab bar.
-
- \value PM_TabCloseIndicatorWidth The default width of a close button on a tab in a tab bar.
- \value PM_TabCloseIndicatorHeight The default height of a close button on a tab in a tab bar.
-
- \value PM_CustomBase Base value for custom pixel metrics. Custom
- values must be greater than this value.
-
- The following values are obsolete:
-
- \value PM_DefaultTopLevelMargin Use PM_LayoutLeftMargin,
- PM_LayoutTopMargin,
- PM_LayoutRightMargin, and
- PM_LayoutBottomMargin instead.
- \value PM_DefaultChildMargin Use PM_LayoutLeftMargin,
- PM_LayoutTopMargin,
- PM_LayoutRightMargin, and
- PM_LayoutBottomMargin instead.
- \value PM_DefaultLayoutSpacing Use PM_LayoutHorizontalSpacing
- and PM_LayoutVerticalSpacing
- instead.
-
- \value PM_ScrollView_ScrollBarSpacing Distance between frame and scrollbar
- with SH_ScrollView_FrameOnlyAroundContents set.
- \value PM_SubMenuOverlap The horizontal overlap between a submenu and its parent.
-
-
- \sa pixelMetric()
-*/
-
-/*!
- \fn int QStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const;
-
- Returns the value of the given pixel \a metric.
-
- The specified \a option and \a widget can be used for calculating
- the metric. In general, the \a widget argument is not used. The \a
- option can be cast to the appropriate type using the
- qstyleoption_cast() function. Note that the \a option may be zero
- even for PixelMetrics that can make use of it. See the table below
- for the appropriate \a option casts:
-
- \table
- \header \o Pixel Metric \o QStyleOption Subclass
- \row \o \l PM_SliderControlThickness \o \l QStyleOptionSlider
- \row \o \l PM_SliderLength \o \l QStyleOptionSlider
- \row \o \l PM_SliderTickmarkOffset \o \l QStyleOptionSlider
- \row \o \l PM_SliderSpaceAvailable \o \l QStyleOptionSlider
- \row \o \l PM_ScrollBarExtent \o \l QStyleOptionSlider
- \row \o \l PM_TabBarTabOverlap \o \l QStyleOptionTab
- \row \o \l PM_TabBarTabHSpace \o \l QStyleOptionTab
- \row \o \l PM_TabBarTabVSpace \o \l QStyleOptionTab
- \row \o \l PM_TabBarBaseHeight \o \l QStyleOptionTab
- \row \o \l PM_TabBarBaseOverlap \o \l QStyleOptionTab
- \endtable
-
- Some pixel metrics are called from widgets and some are only called
- internally by the style. If the metric is not called by a widget, it is the
- discretion of the style author to make use of it. For some styles, this
- may not be appropriate.
-*/
-
-/*!
- \enum QStyle::ContentsType
-
- This enum describes the available contents types. These are used to
- calculate sizes for the contents of various widgets.
-
- \value CT_CheckBox A check box, like QCheckBox.
- \value CT_ComboBox A combo box, like QComboBox.
- \omitvalue CT_DialogButtons
- \value CT_Q3DockWindow A Q3DockWindow.
- \value CT_HeaderSection A header section, like QHeader.
- \value CT_LineEdit A line edit, like QLineEdit.
- \value CT_Menu A menu, like QMenu.
- \value CT_Q3Header A Qt 3 header section, like Q3Header.
- \value CT_MenuBar A menu bar, like QMenuBar.
- \value CT_MenuBarItem A menu bar item, like the buttons in a QMenuBar.
- \value CT_MenuItem A menu item, like QMenuItem.
- \value CT_ProgressBar A progress bar, like QProgressBar.
- \value CT_PushButton A push button, like QPushButton.
- \value CT_RadioButton A radio button, like QRadioButton.
- \value CT_SizeGrip A size grip, like QSizeGrip.
- \value CT_Slider A slider, like QSlider.
- \value CT_ScrollBar A scroll bar, like QScrollBar.
- \value CT_SpinBox A spin box, like QSpinBox.
- \value CT_Splitter A splitter, like QSplitter.
- \value CT_TabBarTab A tab on a tab bar, like QTabBar.
- \value CT_TabWidget A tab widget, like QTabWidget.
- \value CT_ToolButton A tool button, like QToolButton.
- \value CT_GroupBox A group box, like QGroupBox.
- \value CT_ItemViewItem An item inside an item view.
-
- \value CT_CustomBase Base value for custom contents types.
- Custom values must be greater than this value.
-
- \value CT_MdiControls The minimize, normal, and close button
- in the menu bar for a maximized MDI
- subwindow.
-
- \sa sizeFromContents()
-*/
-
-/*!
- \fn QSize QStyle::sizeFromContents(ContentsType type, const QStyleOption *option, \
- const QSize &contentsSize, const QWidget *widget) const
-
- Returns the size of the element described by the specified
- \a option and \a type, based on the provided \a contentsSize.
-
- The \a option argument is a pointer to a QStyleOption or one of
- its subclasses. The \a option can be cast to the appropriate type
- using the qstyleoption_cast() function. The \a widget is an
- optional argument and can contain extra information used for
- calculating the size.
-
- See the table below for the appropriate \a option casts:
-
- \table
- \header \o Contents Type \o QStyleOption Subclass
- \row \o \l CT_PushButton \o \l QStyleOptionButton
- \row \o \l CT_CheckBox \o \l QStyleOptionButton
- \row \o \l CT_RadioButton \o \l QStyleOptionButton
- \row \o \l CT_ToolButton \o \l QStyleOptionToolButton
- \row \o \l CT_ComboBox \o \l QStyleOptionComboBox
- \row \o \l CT_Splitter \o \l QStyleOption
- \row \o \l CT_Q3DockWindow \o \l QStyleOptionQ3DockWindow
- \row \o \l CT_ProgressBar \o \l QStyleOptionProgressBar
- \row \o \l CT_MenuItem \o \l QStyleOptionMenuItem
- \endtable
-
- \sa ContentsType QStyleOption
-*/
-
-/*!
- \enum QStyle::RequestSoftwareInputPanel
-
- This enum describes under what circumstances a software input panel will be
- requested by input capable widgets.
-
- \value RSIP_OnMouseClickAndAlreadyFocused Requests an input panel if the user
- clicks on the widget, but only if it is already focused.
- \value RSIP_OnMouseClick Requests an input panel if the user clicks on the
- widget.
-
- \sa QEvent::RequestSoftwareInputPanel, QInputContext
-*/
-
-/*!
- \enum QStyle::StyleHint
-
- This enum describes the available style hints. A style hint is a general look
- and/or feel hint.
-
- \value SH_EtchDisabledText Disabled text is "etched" as it is on Windows.
-
- \value SH_DitherDisabledText Disabled text is dithered as it is on Motif.
-
- \value SH_GUIStyle The GUI style to use.
-
- \value SH_ScrollBar_ContextMenu Whether or not a scroll bar has a context menu.
-
- \value SH_ScrollBar_MiddleClickAbsolutePosition A boolean value.
- If true, middle clicking on a scroll bar causes the slider to
- jump to that position. If false, middle clicking is
- ignored.
-
- \value SH_ScrollBar_LeftClickAbsolutePosition A boolean value.
- If true, left clicking on a scroll bar causes the slider to
- jump to that position. If false, left clicking will
- behave as appropriate for each control.
-
- \value SH_ScrollBar_ScrollWhenPointerLeavesControl A boolean
- value. If true, when clicking a scroll bar SubControl, holding
- the mouse button down and moving the pointer outside the
- SubControl, the scroll bar continues to scroll. If false, the
- scollbar stops scrolling when the pointer leaves the
- SubControl.
-
- \value SH_ScrollBar_RollBetweenButtons A boolean value.
- If true, when clicking a scroll bar button (SC_ScrollBarAddLine or
- SC_ScrollBarSubLine) and dragging over to the opposite button (rolling)
- will press the new button and release the old one. When it is false, the
- original button is released and nothing happens (like a push button).
-
- \value SH_TabBar_Alignment The alignment for tabs in a
- QTabWidget. Possible values are Qt::AlignLeft,
- Qt::AlignCenter and Qt::AlignRight.
-
- \value SH_Header_ArrowAlignment The placement of the sorting
- indicator may appear in list or table headers. Possible values
- are Qt::Left or Qt::Right.
-
- \value SH_Slider_SnapToValue Sliders snap to values while moving,
- as they do on Windows.
-
- \value SH_Slider_SloppyKeyEvents Key presses handled in a sloppy
- manner, i.e., left on a vertical slider subtracts a line.
-
- \value SH_ProgressDialog_CenterCancelButton Center button on
- progress dialogs, like Motif, otherwise right aligned.
-
- \value SH_ProgressDialog_TextLabelAlignment The alignment for text
- labels in progress dialogs; Qt::AlignCenter on Windows,
- Qt::AlignVCenter otherwise.
-
- \value SH_PrintDialog_RightAlignButtons Right align buttons in
- the print dialog, as done on Windows.
-
- \value SH_MainWindow_SpaceBelowMenuBar One or two pixel space between
- the menu bar and the dockarea, as done on Windows.
-
- \value SH_FontDialog_SelectAssociatedText Select the text in the
- line edit, or when selecting an item from the listbox, or when
- the line edit receives focus, as done on Windows.
-
- \value SH_Menu_KeyboardSearch Typing causes a menu to be search
- for relevant items, otherwise only mnemnonic is considered.
-
- \value SH_Menu_AllowActiveAndDisabled Allows disabled menu
- items to be active.
-
- \value SH_Menu_SpaceActivatesItem Pressing the space bar activates
- the item, as done on Motif.
-
- \value SH_Menu_SubMenuPopupDelay The number of milliseconds
- to wait before opening a submenu (256 on Windows, 96 on Motif).
-
- \value SH_Menu_Scrollable Whether popup menus must support scrolling.
-
- \value SH_Menu_SloppySubMenus Whether popupmenu's must support
- sloppy submenu; as implemented on Mac OS.
-
- \value SH_ScrollView_FrameOnlyAroundContents Whether scrollviews
- draw their frame only around contents (like Motif), or around
- contents, scroll bars and corner widgets (like Windows).
-
- \value SH_MenuBar_AltKeyNavigation Menu bars items are navigable
- by pressing Alt, followed by using the arrow keys to select
- the desired item.
-
- \value SH_ComboBox_ListMouseTracking Mouse tracking in combobox
- drop-down lists.
-
- \value SH_Menu_MouseTracking Mouse tracking in popup menus.
-
- \value SH_MenuBar_MouseTracking Mouse tracking in menu bars.
-
- \value SH_Menu_FillScreenWithScroll Whether scrolling popups
- should fill the screen as they are scrolled.
-
- \value SH_Menu_SelectionWrap Whether popups should allow the selections
- to wrap, that is when selection should the next item be the first item.
-
- \value SH_ItemView_ChangeHighlightOnFocus Gray out selected items
- when losing focus.
-
- \value SH_Widget_ShareActivation Turn on sharing activation with
- floating modeless dialogs.
-
- \value SH_TabBar_SelectMouseType Which type of mouse event should
- cause a tab to be selected.
-
- \value SH_Q3ListViewExpand_SelectMouseType Which type of mouse event should
- cause a list view expansion to be selected.
-
- \value SH_TabBar_PreferNoArrows Whether a tab bar should suggest a size
- to prevent scoll arrows.
-
- \value SH_ComboBox_Popup Allows popups as a combobox drop-down
- menu.
-
- \value SH_Workspace_FillSpaceOnMaximize The workspace should
- maximize the client area.
-
- \value SH_TitleBar_NoBorder The title bar has no border.
-
- \value SH_ScrollBar_StopMouseOverSlider Obsolete. Use
- SH_Slider_StopMouseOverSlider instead.
-
- \value SH_Slider_StopMouseOverSlider Stops auto-repeat when
- the slider reaches the mouse position.
-
- \value SH_BlinkCursorWhenTextSelected Whether cursor should blink
- when text is selected.
-
- \value SH_RichText_FullWidthSelection Whether richtext selections
- should extend to the full width of the document.
-
- \value SH_GroupBox_TextLabelVerticalAlignment How to vertically align a
- group box's text label.
-
- \value SH_GroupBox_TextLabelColor How to paint a group box's text label.
-
- \value SH_DialogButtons_DefaultButton Which button gets the
- default status in a dialog's button widget.
-
- \value SH_ToolBox_SelectedPageTitleBold Boldness of the selected
- page title in a QToolBox.
-
- \value SH_LineEdit_PasswordCharacter The Unicode character to be
- used for passwords.
-
- \value SH_Table_GridLineColor The RGB value of the grid for a table.
-
- \value SH_UnderlineShortcut Whether shortcuts are underlined.
-
- \value SH_SpellCheckUnderlineStyle A
- QTextCharFormat::UnderlineStyle value that specifies the way
- misspelled words should be underlined.
-
- \value SH_SpinBox_AnimateButton Animate a click when up or down is
- pressed in a spin box.
- \value SH_SpinBox_KeyPressAutoRepeatRate Auto-repeat interval for
- spinbox key presses.
- \value SH_SpinBox_ClickAutoRepeatRate Auto-repeat interval for
- spinbox mouse clicks.
- \value SH_SpinBox_ClickAutoRepeatThreshold Auto-repeat threshold for
- spinbox mouse clicks.
- \value SH_ToolTipLabel_Opacity An integer indicating the opacity for
- the tip label, 0 is completely transparent, 255 is completely
- opaque.
- \value SH_DrawMenuBarSeparator Indicates whether or not the menu bar draws separators.
- \value SH_TitleBar_ModifyNotification Indicates if the title bar should show
- a '*' for windows that are modified.
-
- \value SH_Button_FocusPolicy The default focus policy for buttons.
-
- \value SH_CustomBase Base value for custom style hints.
- Custom values must be greater than this value.
-
- \value SH_MenuBar_DismissOnSecondClick A boolean indicating if a menu in
- the menu bar should be dismissed when it is clicked on a second time. (Example:
- Clicking and releasing on the File Menu in a menu bar and then
- immediately clicking on the File Menu again.)
-
- \value SH_MessageBox_UseBorderForButtonSpacing A boolean indicating what the to
- use the border of the buttons (computed as half the button height) for the spacing
- of the button in a message box.
-
- \value SH_MessageBox_CenterButtons A boolean indicating whether the buttons in the
- message box should be centered or not (see QDialogButtonBox::setCentered()).
-
- \value SH_MessageBox_TextInteractionFlags A boolean indicating if
- the text in a message box should allow user interfactions (e.g.
- selection) or not.
-
- \value SH_TitleBar_AutoRaise A boolean indicating whether
- controls on a title bar ought to update when the mouse is over them.
-
- \value SH_ToolButton_PopupDelay An int indicating the popup delay in milliseconds
- for menus attached to tool buttons.
-
- \value SH_FocusFrame_Mask The mask of the focus frame.
-
- \value SH_RubberBand_Mask The mask of the rubber band.
-
- \value SH_WindowFrame_Mask The mask of the window frame.
-
- \value SH_SpinControls_DisableOnBounds Determines if the spin controls will shown
- as disabled when reaching the spin range boundary.
-
- \value SH_Dial_BackgroundRole Defines the style's preferred
- background role (as QPalette::ColorRole) for a dial widget.
-
- \value SH_ScrollBar_BackgroundMode The background mode for a scroll bar.
-
- \value SH_ComboBox_LayoutDirection The layout direction for the
- combo box. By default it should be the same as indicated by the
- QStyleOption::direction variable.
-
- \value SH_ItemView_EllipsisLocation The location where ellipses should be
- added for item text that is too long to fit in an view item.
-
- \value SH_ItemView_ShowDecorationSelected When an item in an item
- view is selected, also highlight the branch or other decoration.
-
- \value SH_ItemView_ActivateItemOnSingleClick Emit the activated signal
- when the user single clicks on an item in an item in an item view.
- Otherwise the signal is emitted when the user double clicks on an item.
-
- \value SH_Slider_AbsoluteSetButtons Which mouse buttons cause a slider
- to set the value to the position clicked on.
-
- \value SH_Slider_PageSetButtons Which mouse buttons cause a slider
- to page step the value.
-
- \value SH_TabBar_ElideMode The default eliding style for a tab bar.
-
- \value SH_DialogButtonLayout Controls how buttons are laid out in a QDialogButtonBox, returns a QDialogButtonBox::ButtonLayout enum.
-
- \value SH_WizardStyle Controls the look and feel of a QWizard. Returns a QWizard::WizardStyle enum.
-
- \value SH_FormLayoutWrapPolicy Provides a default for how rows are wrapped in a QFormLayout. Returns a QFormLayout::RowWrapPolicy enum.
- \value SH_FormLayoutFieldGrowthPolicy Provides a default for how fields can grow in a QFormLayout. Returns a QFormLayout::FieldGrowthPolicy enum.
- \value SH_FormLayoutFormAlignment Provides a default for how a QFormLayout aligns its contents within the available space. Returns a Qt::Alignment enum.
- \value SH_FormLayoutLabelAlignment Provides a default for how a QFormLayout aligns labels within the available space. Returns a Qt::Alignment enum.
-
- \value SH_ItemView_ArrowKeysNavigateIntoChildren Controls whether the tree view will select the first child when it is exapanded and the right arrow key is pressed.
- \value SH_ComboBox_PopupFrameStyle The frame style used when drawing a combobox popup menu.
-
- \value SH_DialogButtonBox_ButtonsHaveIcons Indicates whether or not StandardButtons in QDialogButtonBox should have icons or not.
- \value SH_ItemView_MovementWithoutUpdatingSelection The item view is able to indicate a current item without changing the selection.
- \value SH_ToolTip_Mask The mask of a tool tip.
-
- \value SH_FocusFrame_AboveWidget The FocusFrame is stacked above the widget that it is "focusing on".
-
- \value SH_TextControl_FocusIndicatorTextCharFormat Specifies the text format used to highlight focused anchors in rich text
- documents displayed for example in QTextBrowser. The format has to be a QTextCharFormat returned in the variant of the
- QStyleHintReturnVariant return value. The QTextFormat::OutlinePen property is used for the outline and QTextFormat::BackgroundBrush
- for the background of the highlighted area.
-
- \value SH_Menu_FlashTriggeredItem Flash triggered item.
- \value SH_Menu_FadeOutOnHide Fade out the menu instead of hiding it immediately.
-
- \value SH_TabWidget_DefaultTabPosition Default position of the tab bar in a tab widget.
-
- \value SH_ToolBar_Movable Determines if the tool bar is movable by default.
-
- \value SH_ItemView_PaintAlternatingRowColorsForEmptyArea Whether QTreeView paints alternating row colors for the area that does not have any items.
-
- \value SH_Menu_Mask The mask for a popup menu.
-
- \value SH_ItemView_DrawDelegateFrame Determines if there should be a frame for a delegate widget.
-
- \value SH_TabBar_CloseButtonPosition Determines the position of the close button on a tab in a tab bar.
-
- \value SH_DockWidget_ButtonsHaveFrame Determines if dockwidget buttons should have frames. Default is true.
-
- \value SH_ToolButtonStyle Determines the default system style for tool buttons that uses Qt::ToolButtonFollowStyle.
-
- \value SH_RequestSoftwareInputPanel Determines when a software input panel should
- be requested by input widgets. Returns an enum of type QStyle::RequestSoftwareInputPanel.
-
- \omitvalue SH_UnderlineAccelerator
-
- \sa styleHint()
-*/
-
-/*!
- \fn int QStyle::styleHint(StyleHint hint, const QStyleOption *option, \
- const QWidget *widget, QStyleHintReturn *returnData) const
-
- Returns an integer representing the specified style \a hint for
- the given \a widget described by the provided style \a option.
-
- \a returnData is used when the querying widget needs more detailed data than
- the integer that styleHint() returns. See the QStyleHintReturn class
- description for details.
-*/
-
-/*!
- \enum QStyle::StandardPixmap
-
- This enum describes the available standard pixmaps. A standard pixmap is a pixmap that
- can follow some existing GUI style or guideline.
-
- \value SP_TitleBarMinButton Minimize button on title bars (e.g.,
- in QMdiSubWindow).
- \value SP_TitleBarMenuButton Menu button on a title bar.
- \value SP_TitleBarMaxButton Maximize button on title bars.
- \value SP_TitleBarCloseButton Close button on title bars.
- \value SP_TitleBarNormalButton Normal (restore) button on title bars.
- \value SP_TitleBarShadeButton Shade button on title bars.
- \value SP_TitleBarUnshadeButton Unshade button on title bars.
- \value SP_TitleBarContextHelpButton The Context help button on title bars.
- \value SP_MessageBoxInformation The "information" icon.
- \value SP_MessageBoxWarning The "warning" icon.
- \value SP_MessageBoxCritical The "critical" icon.
- \value SP_MessageBoxQuestion The "question" icon.
- \value SP_DesktopIcon The "desktop" icon.
- \value SP_TrashIcon The "trash" icon.
- \value SP_ComputerIcon The "My computer" icon.
- \value SP_DriveFDIcon The floppy icon.
- \value SP_DriveHDIcon The harddrive icon.
- \value SP_DriveCDIcon The CD icon.
- \value SP_DriveDVDIcon The DVD icon.
- \value SP_DriveNetIcon The network icon.
- \value SP_DirHomeIcon The home directory icon.
- \value SP_DirOpenIcon The open directory icon.
- \value SP_DirClosedIcon The closed directory icon.
- \value SP_DirIcon The directory icon.
- \value SP_DirLinkIcon The link to directory icon.
- \value SP_FileIcon The file icon.
- \value SP_FileLinkIcon The link to file icon.
- \value SP_FileDialogStart The "start" icon in a file dialog.
- \value SP_FileDialogEnd The "end" icon in a file dialog.
- \value SP_FileDialogToParent The "parent directory" icon in a file dialog.
- \value SP_FileDialogNewFolder The "create new folder" icon in a file dialog.
- \value SP_FileDialogDetailedView The detailed view icon in a file dialog.
- \value SP_FileDialogInfoView The file info icon in a file dialog.
- \value SP_FileDialogContentsView The contents view icon in a file dialog.
- \value SP_FileDialogListView The list view icon in a file dialog.
- \value SP_FileDialogBack The back arrow in a file dialog.
- \value SP_DockWidgetCloseButton Close button on dock windows (see also QDockWidget).
- \value SP_ToolBarHorizontalExtensionButton Extension button for horizontal toolbars.
- \value SP_ToolBarVerticalExtensionButton Extension button for vertical toolbars.
- \value SP_DialogOkButton Icon for a standard OK button in a QDialogButtonBox.
- \value SP_DialogCancelButton Icon for a standard Cancel button in a QDialogButtonBox.
- \value SP_DialogHelpButton Icon for a standard Help button in a QDialogButtonBox.
- \value SP_DialogOpenButton Icon for a standard Open button in a QDialogButtonBox.
- \value SP_DialogSaveButton Icon for a standard Save button in a QDialogButtonBox.
- \value SP_DialogCloseButton Icon for a standard Close button in a QDialogButtonBox.
- \value SP_DialogApplyButton Icon for a standard Apply button in a QDialogButtonBox.
- \value SP_DialogResetButton Icon for a standard Reset button in a QDialogButtonBox.
- \value SP_DialogDiscardButton Icon for a standard Discard button in a QDialogButtonBox.
- \value SP_DialogYesButton Icon for a standard Yes button in a QDialogButtonBox.
- \value SP_DialogNoButton Icon for a standard No button in a QDialogButtonBox.
- \value SP_ArrowUp Icon arrow pointing up.
- \value SP_ArrowDown Icon arrow pointing down.
- \value SP_ArrowLeft Icon arrow pointing left.
- \value SP_ArrowRight Icon arrow pointing right.
- \value SP_ArrowBack Equivalent to SP_ArrowLeft when the current layout direction is Qt::LeftToRight, otherwise SP_ArrowRight.
- \value SP_ArrowForward Equivalent to SP_ArrowRight when the current layout direction is Qt::LeftToRight, otherwise SP_ArrowLeft.
- \value SP_CommandLink Icon used to indicate a Vista style command link glyph.
- \value SP_VistaShield Icon used to indicate UAC prompts on Windows Vista. This will return a null pixmap or icon on all other platforms.
- \value SP_BrowserReload Icon indicating that the current page should be reloaded.
- \value SP_BrowserStop Icon indicating that the page loading should stop.
- \value SP_MediaPlay Icon indicating that media should begin playback.
- \value SP_MediaStop Icon indicating that media should stop playback.
- \value SP_MediaPause Icon indicating that media should pause playback.
- \value SP_MediaSkipForward Icon indicating that media should skip forward.
- \value SP_MediaSkipBackward Icon indicating that media should skip backward.
- \value SP_MediaSeekForward Icon indicating that media should seek forward.
- \value SP_MediaSeekBackward Icon indicating that media should seek backward.
- \value SP_MediaVolume Icon indicating a volume control.
- \value SP_MediaVolumeMuted Icon indicating a muted volume control.
- \value SP_CustomBase Base value for custom standard pixmaps;
- custom values must be greater than this value.
-
- \sa standardIcon()
-*/
-
-/*!
- \fn QPixmap QStyle::generatedIconPixmap(QIcon::Mode iconMode,
- const QPixmap &pixmap, const QStyleOption *option) const
-
- Returns a copy of the given \a pixmap, styled to conform to the
- specified \a iconMode and taking into account the palette
- specified by \a option.
-
- The \a option parameter can pass extra information, but
- it must contain a palette.
-
- Note that not all pixmaps will conform, in which case the returned
- pixmap is a plain copy.
-
- \sa QIcon
-*/
-
-/*!
- \fn QPixmap QStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option, \
- const QWidget *widget) const
-
- \obsolete
- Returns a pixmap for the given \a standardPixmap.
-
- A standard pixmap is a pixmap that can follow some existing GUI
- style or guideline. The \a option argument can be used to pass
- extra information required when defining the appropriate
- pixmap. The \a widget argument is optional and can also be used to
- aid the determination of the pixmap.
-
- Developers calling standardPixmap() should instead call standardIcon()
- Developers who re-implemented standardPixmap() should instead re-implement
- the slot standardIconImplementation().
-
- \sa standardIcon()
-*/
-
-
-/*!
- \fn QRect QStyle::visualRect(Qt::LayoutDirection direction, const QRect &boundingRectangle, const QRect &logicalRectangle)
-
- Returns the given \a logicalRectangle converted to screen
- coordinates based on the specified \a direction. The \a
- boundingRectangle is used when performing the translation.
-
- This function is provided to support right-to-left desktops, and
- is typically used in implementations of the subControlRect()
- function.
-
- \sa QWidget::layoutDirection
-*/
-QRect QStyle::visualRect(Qt::LayoutDirection direction, const QRect &boundingRect, const QRect &logicalRect)
-{
- if (direction == Qt::LeftToRight)
- return logicalRect;
- QRect rect = logicalRect;
- rect.translate(2 * (boundingRect.right() - logicalRect.right()) +
- logicalRect.width() - boundingRect.width(), 0);
- return rect;
-}
-
-/*!
- \fn QPoint QStyle::visualPos(Qt::LayoutDirection direction, const QRect &boundingRectangle, const QPoint &logicalPosition)
-
- Returns the given \a logicalPosition converted to screen
- coordinates based on the specified \a direction. The \a
- boundingRectangle is used when performing the translation.
-
- \sa QWidget::layoutDirection
-*/
-QPoint QStyle::visualPos(Qt::LayoutDirection direction, const QRect &boundingRect, const QPoint &logicalPos)
-{
- if (direction == Qt::LeftToRight)
- return logicalPos;
- return QPoint(boundingRect.right() - logicalPos.x(), logicalPos.y());
-}
-
-/*!
- Returns a new rectangle of the specified \a size that is aligned to the given \a
- rectangle according to the specified \a alignment and \a direction.
- */
-QRect QStyle::alignedRect(Qt::LayoutDirection direction, Qt::Alignment alignment, const QSize &size, const QRect &rectangle)
-{
- alignment = visualAlignment(direction, alignment);
- int x = rectangle.x();
- int y = rectangle.y();
- int w = size.width();
- int h = size.height();
- if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
- y += rectangle.size().height()/2 - h/2;
- else if ((alignment & Qt::AlignBottom) == Qt::AlignBottom)
- y += rectangle.size().height() - h;
- if ((alignment & Qt::AlignRight) == Qt::AlignRight)
- x += rectangle.size().width() - w;
- else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
- x += rectangle.size().width()/2 - w/2;
- return QRect(x, y, w, h);
-}
-
-/*!
- Transforms an \a alignment of Qt::AlignLeft or Qt::AlignRight
- without Qt::AlignAbsolute into Qt::AlignLeft or Qt::AlignRight with
- Qt::AlignAbsolute according to the layout \a direction. The other
- alignment flags are left untouched.
-
- If no horizontal alignment was specified, the function returns the
- default alignment for the given layout \a direction.
-
- QWidget::layoutDirection
-*/
-Qt::Alignment QStyle::visualAlignment(Qt::LayoutDirection direction, Qt::Alignment alignment)
-{
- return QGuiApplicationPrivate::visualAlignment(direction, alignment);
-}
-
-/*!
- Converts the given \a logicalValue to a pixel position. The \a min
- parameter maps to 0, \a max maps to \a span and other values are
- distributed evenly in-between.
-
- This function can handle the entire integer range without
- overflow, providing that \a span is less than 4096.
-
- By default, this function assumes that the maximum value is on the
- right for horizontal items and on the bottom for vertical items.
- Set the \a upsideDown parameter to true to reverse this behavior.
-
- \sa sliderValueFromPosition()
-*/
-
-int QStyle::sliderPositionFromValue(int min, int max, int logicalValue, int span, bool upsideDown)
-{
- if (span <= 0 || logicalValue < min || max <= min)
- return 0;
- if (logicalValue > max)
- return upsideDown ? span : min;
-
- uint range = max - min;
- uint p = upsideDown ? max - logicalValue : logicalValue - min;
-
- if (range > (uint)INT_MAX/4096) {
- double dpos = (double(p))/(double(range)/span);
- return int(dpos);
- } else if (range > (uint)span) {
- return (2 * p * span + range) / (2*range);
- } else {
- uint div = span / range;
- uint mod = span % range;
- return p * div + (2 * p * mod + range) / (2 * range);
- }
- // equiv. to (p * span) / range + 0.5
- // no overflow because of this implicit assumption:
- // span <= 4096
-}
-
-/*!
- \fn int QStyle::sliderValueFromPosition(int min, int max, int position, int span, bool upsideDown)
-
- Converts the given pixel \a position to a logical value. 0 maps to
- the \a min parameter, \a span maps to \a max and other values are
- distributed evenly in-between.
-
- This function can handle the entire integer range without
- overflow.
-
- By default, this function assumes that the maximum value is on the
- right for horizontal items and on the bottom for vertical
- items. Set the \a upsideDown parameter to true to reverse this
- behavior.
-
- \sa sliderPositionFromValue()
-*/
-
-int QStyle::sliderValueFromPosition(int min, int max, int pos, int span, bool upsideDown)
-{
- if (span <= 0 || pos <= 0)
- return upsideDown ? max : min;
- if (pos >= span)
- return upsideDown ? min : max;
-
- uint range = max - min;
-
- if ((uint)span > range) {
- int tmp = (2 * pos * range + span) / (2 * span);
- return upsideDown ? max - tmp : tmp + min;
- } else {
- uint div = range / span;
- uint mod = range % span;
- int tmp = pos * div + (2 * pos * mod + span) / (2 * span);
- return upsideDown ? max - tmp : tmp + min;
- }
- // equiv. to min + (pos*range)/span + 0.5
- // no overflow because of this implicit assumption:
- // pos <= span < sqrt(INT_MAX+0.0625)+0.25 ~ sqrt(INT_MAX)
-}
-
-/*!
- Returns the style's standard palette.
-
- Note that on systems that support system colors, the style's
- standard palette is not used. In particular, the Windows XP,
- Vista, and Mac styles do not use the standard palette, but make
- use of native theme engines. With these styles, you should not set
- the palette with QApplication::setStandardPalette().
-
- */
-QPalette QStyle::standardPalette() const
-{
-#ifdef Q_WS_X11
- QColor background;
- if (QX11Info::appDepth() > 8)
- background = QColor(0xd4, 0xd0, 0xc8); // win 2000 grey
- else
- background = QColor(192, 192, 192);
-#else
- QColor background(0xd4, 0xd0, 0xc8); // win 2000 grey
-#endif
- QColor light(background.lighter());
- QColor dark(background.darker());
- QColor mid(Qt::gray);
- QPalette palette(Qt::black, background, light, dark, mid, Qt::black, Qt::white);
- palette.setBrush(QPalette::Disabled, QPalette::WindowText, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Text, dark);
- palette.setBrush(QPalette::Disabled, QPalette::ButtonText, dark);
- palette.setBrush(QPalette::Disabled, QPalette::Base, background);
- return palette;
-}
-
-/*!
- \since 4.1
-
- Returns an icon for the given \a standardIcon.
-
- The \a standardIcon is a standard pixmap which can follow some
- existing GUI style or guideline. The \a option argument can be
- used to pass extra information required when defining the
- appropriate icon. The \a widget argument is optional and can also
- be used to aid the determination of the icon.
-
- \warning Because of binary compatibility constraints, this
- function is not virtual. If you want to provide your own icons in
- a QStyle subclass, reimplement the standardIconImplementation()
- slot in your subclass instead. The standardIcon() function will
- dynamically detect the slot and call it.
-
- \sa standardIconImplementation()
-*/
-QIcon QStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
-{
- QIcon result;
- // ### Qt 4.1: invokeMethod should accept const functions, to avoid this dirty cast
- QMetaObject::invokeMethod(const_cast<QStyle*>(this),
- "standardIconImplementation", Qt::DirectConnection,
- Q_RETURN_ARG(QIcon, result),
- Q_ARG(StandardPixmap, standardIcon),
- Q_ARG(const QStyleOption*, option),
- Q_ARG(const QWidget*, widget));
- return result;
-}
-
-/*!
- \since 4.1
-
- Returns an icon for the given \a standardIcon.
-
- Reimplement this slot to provide your own icons in a QStyle
- subclass; because of binary compatibility constraints, the
- standardIcon() function (introduced in Qt 4.1) is not
- virtual. Instead, standardIcon() will dynamically detect and call
- \e this slot.
-
- The \a standardIcon is a standard pixmap which can follow some
- existing GUI style or guideline. The \a option argument can be
- used to pass extra information required when defining the
- appropriate icon. The \a widget argument is optional and can also
- be used to aid the determination of the icon.
-
- \sa standardIcon()
-*/
-QIcon QStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
-{
- return QIcon(standardPixmap(standardIcon, option, widget));
-}
-
-/*!
- \since 4.3
-
- Returns the spacing that should be used between \a control1 and
- \a control2 in a layout. \a orientation specifies whether the
- controls are laid out side by side or stacked vertically. The \a
- option parameter can be used to pass extra information about the
- parent widget. The \a widget parameter is optional and can also
- be used if \a option is 0.
-
- This function is called by the layout system. It is used only if
- PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
- negative value.
-
- For binary compatibility reasons, this function is not virtual.
- If you want to specify custom layout spacings in a QStyle
- subclass, implement a slot called layoutSpacingImplementation().
- QStyle will discover the slot at run-time (using Qt's
- \l{meta-object system}) and direct all calls to layoutSpacing()
- to layoutSpacingImplementation().
-
- \sa combinedLayoutSpacing(), layoutSpacingImplementation()
-*/
-int QStyle::layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option,
- const QWidget *widget) const
-{
- Q_D(const QStyle);
- if (d->layoutSpacingIndex == -1) {
- d->layoutSpacingIndex = metaObject()->indexOfMethod(
- "layoutSpacingImplementation(QSizePolicy::ControlType,QSizePolicy::ControlType,"
- "Qt::Orientation,const QStyleOption*,const QWidget*)"
- );
- }
- if (d->layoutSpacingIndex < 0)
- return -1;
- int result = -1;
- void *param[] = {&result, &control1, &control2, &orientation, &option, &widget};
-
- const_cast<QStyle *>(this)->qt_metacall(QMetaObject::InvokeMetaMethod,
- d->layoutSpacingIndex, param);
- return result;
-}
-
-/*!
- \since 4.3
-
- Returns the spacing that should be used between \a controls1 and
- \a controls2 in a layout. \a orientation specifies whether the
- controls are laid out side by side or stacked vertically. The \a
- option parameter can be used to pass extra information about the
- parent widget. The \a widget parameter is optional and can also
- be used if \a option is 0.
-
- \a controls1 and \a controls2 are OR-combination of zero or more
- \l{QSizePolicy::ControlTypes}{control types}.
-
- This function is called by the layout system. It is used only if
- PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
- negative value.
-
- \sa layoutSpacing(), layoutSpacingImplementation()
-*/
-int QStyle::combinedLayoutSpacing(QSizePolicy::ControlTypes controls1,
- QSizePolicy::ControlTypes controls2, Qt::Orientation orientation,
- QStyleOption *option, QWidget *widget) const
-{
- QSizePolicy::ControlType array1[MaxBits];
- QSizePolicy::ControlType array2[MaxBits];
- int count1 = unpackControlTypes(controls1, array1);
- int count2 = unpackControlTypes(controls2, array2);
- int result = -1;
-
- for (int i = 0; i < count1; ++i) {
- for (int j = 0; j < count2; ++j) {
- int spacing = layoutSpacing(array1[i], array2[j], orientation, option, widget);
- result = qMax(spacing, result);
- }
- }
- return result;
-}
-
-/*!
- \since 4.3
-
- This slot is called by layoutSpacing() to determine the spacing
- that should be used between \a control1 and \a control2 in a
- layout. \a orientation specifies whether the controls are laid
- out side by side or stacked vertically. The \a option parameter
- can be used to pass extra information about the parent widget.
- The \a widget parameter is optional and can also be used if \a
- option is 0.
-
- If you want to provide custom layout spacings in a QStyle
- subclass, implement a slot called layoutSpacingImplementation()
- in your subclass. Be aware that this slot will only be called if
- PM_LayoutHorizontalSpacing or PM_LayoutVerticalSpacing returns a
- negative value.
-
- The default implementation returns -1.
-
- \sa layoutSpacing(), combinedLayoutSpacing()
-*/
-int QStyle::layoutSpacingImplementation(QSizePolicy::ControlType /* control1 */,
- QSizePolicy::ControlType /* control2 */,
- Qt::Orientation /*orientation*/,
- const QStyleOption * /* option */,
- const QWidget * /* widget */) const
-{
- return -1;
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <QDebug>
-QT_END_INCLUDE_NAMESPACE
-
-#if !defined(QT_NO_DEBUG_STREAM)
-QDebug operator<<(QDebug debug, QStyle::State state)
-{
-#if !defined(QT_NO_DEBUG)
- debug << "QStyle::State(";
-
- QStringList states;
- if (state & QStyle::State_Active) states << QLatin1String("Active");
- if (state & QStyle::State_AutoRaise) states << QLatin1String("AutoRaise");
- if (state & QStyle::State_Bottom) states << QLatin1String("Bottom");
- if (state & QStyle::State_Children) states << QLatin1String("Children");
- if (state & QStyle::State_DownArrow) states << QLatin1String("DownArrow");
- if (state & QStyle::State_Editing) states << QLatin1String("Editing");
- if (state & QStyle::State_Enabled) states << QLatin1String("Enabled");
- if (state & QStyle::State_FocusAtBorder) states << QLatin1String("FocusAtBorder");
- if (state & QStyle::State_HasFocus) states << QLatin1String("HasFocus");
- if (state & QStyle::State_Horizontal) states << QLatin1String("Horizontal");
- if (state & QStyle::State_Item) states << QLatin1String("Item");
- if (state & QStyle::State_KeyboardFocusChange) states << QLatin1String("KeyboardFocusChange");
- if (state & QStyle::State_MouseOver) states << QLatin1String("MouseOver");
- if (state & QStyle::State_NoChange) states << QLatin1String("NoChange");
- if (state & QStyle::State_Off) states << QLatin1String("Off");
- if (state & QStyle::State_On) states << QLatin1String("On");
- if (state & QStyle::State_Open) states << QLatin1String("Open");
- if (state & QStyle::State_Raised) states << QLatin1String("Raised");
- if (state & QStyle::State_ReadOnly) states << QLatin1String("ReadOnly");
- if (state & QStyle::State_Selected) states << QLatin1String("Selected");
- if (state & QStyle::State_Sibling) states << QLatin1String("Sibling");
- if (state & QStyle::State_Sunken) states << QLatin1String("Sunken");
- if (state & QStyle::State_Top) states << QLatin1String("Top");
- if (state & QStyle::State_UpArrow) states << QLatin1String("UpArrow");
-
- qSort(states);
- debug << states.join(QLatin1String(" | "));
- debug << ')';
-#else
- Q_UNUSED(state);
-#endif
- return debug;
-}
-#endif
-
-/*!
- \since 4.6
-
- \fn const QStyle *QStyle::proxy() const
-
- This function returns the current proxy for this style.
- By default most styles will return themselves. However
- when a proxy style is in use, it will allow the style to
- call back into its proxy.
-*/
-const QStyle * QStyle::proxy() const
-{
- Q_D(const QStyle);
- return d->proxyStyle;
-}
-
-/* \internal
-
- This function sets the base style that style calls will be
- redirected to. Note that ownership is not transferred.
-*/
-void QStyle::setProxy(QStyle *style)
-{
- Q_D(QStyle);
- d->proxyStyle = style;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstyle.h b/src/gui/styles/qstyle.h
deleted file mode 100644
index 94f2ce102f..0000000000
--- a/src/gui/styles/qstyle.h
+++ /dev/null
@@ -1,889 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLE_H
-#define QSTYLE_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qrect.h>
-#include <QtCore/qsize.h>
-#include <QtGui/qicon.h>
-#include <QtGui/qpixmap.h>
-#include <QtGui/qpalette.h>
-#include <QtGui/qsizepolicy.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QAction;
-class QDebug;
-class QTab;
-class QFontMetrics;
-class QStyleHintReturn;
-class QStyleOption;
-class QStyleOptionComplex;
-class QStylePrivate;
-
-class Q_GUI_EXPORT QStyle : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QStyle)
-
-protected:
- QStyle(QStylePrivate &dd);
-
-public:
- QStyle();
- virtual ~QStyle();
-
- virtual void polish(QWidget *);
- virtual void unpolish(QWidget *);
-
- virtual void polish(QApplication *);
- virtual void unpolish(QApplication *);
-
- virtual void polish(QPalette &);
-
- virtual QRect itemTextRect(const QFontMetrics &fm, const QRect &r,
- int flags, bool enabled,
- const QString &text) const;
-
- virtual QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const;
-
- virtual void drawItemText(QPainter *painter, const QRect &rect,
- int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const;
-
- virtual void drawItemPixmap(QPainter *painter, const QRect &rect,
- int alignment, const QPixmap &pixmap) const;
-
- virtual QPalette standardPalette() const;
-
- enum StateFlag {
- State_None = 0x00000000,
-#ifdef QT3_SUPPORT
- State_Default = State_None,
-#endif
- State_Enabled = 0x00000001,
- State_Raised = 0x00000002,
- State_Sunken = 0x00000004,
- State_Off = 0x00000008,
- State_NoChange = 0x00000010,
- State_On = 0x00000020,
- State_DownArrow = 0x00000040,
- State_Horizontal = 0x00000080,
- State_HasFocus = 0x00000100,
- State_Top = 0x00000200,
- State_Bottom = 0x00000400,
- State_FocusAtBorder = 0x00000800,
- State_AutoRaise = 0x00001000,
- State_MouseOver = 0x00002000,
- State_UpArrow = 0x00004000,
- State_Selected = 0x00008000,
- State_Active = 0x00010000,
- State_Window = 0x00020000,
- State_Open = 0x00040000,
- State_Children = 0x00080000,
- State_Item = 0x00100000,
- State_Sibling = 0x00200000,
- State_Editing = 0x00400000,
- State_KeyboardFocusChange = 0x00800000,
-#ifdef QT_KEYPAD_NAVIGATION
- State_HasEditFocus = 0x01000000,
-#endif
- State_ReadOnly = 0x02000000,
- State_Small = 0x04000000,
- State_Mini = 0x08000000
- };
- Q_DECLARE_FLAGS(State, StateFlag)
-
-#ifdef QT3_SUPPORT
- typedef State SFlags;
-#endif
-
- enum PrimitiveElement {
- PE_Q3CheckListController,
- PE_Q3CheckListExclusiveIndicator,
- PE_Q3CheckListIndicator,
- PE_Q3DockWindowSeparator,
- PE_Q3Separator,
-
- PE_Frame,
- PE_FrameDefaultButton,
- PE_FrameDockWidget,
- PE_FrameFocusRect,
- PE_FrameGroupBox,
- PE_FrameLineEdit,
- PE_FrameMenu,
- PE_FrameStatusBar, // obsolete
- PE_FrameStatusBarItem = PE_FrameStatusBar,
- PE_FrameTabWidget,
- PE_FrameWindow,
- PE_FrameButtonBevel,
- PE_FrameButtonTool,
- PE_FrameTabBarBase,
-
- PE_PanelButtonCommand,
- PE_PanelButtonBevel,
- PE_PanelButtonTool,
- PE_PanelMenuBar,
- PE_PanelToolBar,
- PE_PanelLineEdit,
-
- PE_IndicatorArrowDown,
- PE_IndicatorArrowLeft,
- PE_IndicatorArrowRight,
- PE_IndicatorArrowUp,
- PE_IndicatorBranch,
- PE_IndicatorButtonDropDown,
- PE_IndicatorViewItemCheck,
- PE_IndicatorItemViewItemCheck = PE_IndicatorViewItemCheck,
- PE_IndicatorCheckBox,
- PE_IndicatorDockWidgetResizeHandle,
- PE_IndicatorHeaderArrow,
- PE_IndicatorMenuCheckMark,
- PE_IndicatorProgressChunk,
- PE_IndicatorRadioButton,
- PE_IndicatorSpinDown,
- PE_IndicatorSpinMinus,
- PE_IndicatorSpinPlus,
- PE_IndicatorSpinUp,
- PE_IndicatorToolBarHandle,
- PE_IndicatorToolBarSeparator,
- PE_PanelTipLabel,
- PE_IndicatorTabTear,
- PE_PanelScrollAreaCorner,
-
- PE_Widget,
-
- PE_IndicatorColumnViewArrow,
- PE_IndicatorItemViewItemDrop,
-
- PE_PanelItemViewItem,
- PE_PanelItemViewRow, // ### Qt 5: remove
-
- PE_PanelStatusBar,
-
- PE_IndicatorTabClose,
- PE_PanelMenu,
-
- // do not add any values below/greater this
- PE_CustomBase = 0xf000000
- };
-
- virtual void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const = 0;
- enum ControlElement {
- CE_PushButton,
- CE_PushButtonBevel,
- CE_PushButtonLabel,
-
- CE_CheckBox,
- CE_CheckBoxLabel,
-
- CE_RadioButton,
- CE_RadioButtonLabel,
-
- CE_TabBarTab,
- CE_TabBarTabShape,
- CE_TabBarTabLabel,
-
- CE_ProgressBar,
- CE_ProgressBarGroove,
- CE_ProgressBarContents,
- CE_ProgressBarLabel,
-
- CE_MenuItem,
- CE_MenuScroller,
- CE_MenuVMargin,
- CE_MenuHMargin,
- CE_MenuTearoff,
- CE_MenuEmptyArea,
-
- CE_MenuBarItem,
- CE_MenuBarEmptyArea,
-
- CE_ToolButtonLabel,
-
- CE_Header,
- CE_HeaderSection,
- CE_HeaderLabel,
-
- CE_Q3DockWindowEmptyArea,
- CE_ToolBoxTab,
- CE_SizeGrip,
- CE_Splitter,
- CE_RubberBand,
- CE_DockWidgetTitle,
-
- CE_ScrollBarAddLine,
- CE_ScrollBarSubLine,
- CE_ScrollBarAddPage,
- CE_ScrollBarSubPage,
- CE_ScrollBarSlider,
- CE_ScrollBarFirst,
- CE_ScrollBarLast,
-
- CE_FocusFrame,
- CE_ComboBoxLabel,
-
- CE_ToolBar,
- CE_ToolBoxTabShape,
- CE_ToolBoxTabLabel,
- CE_HeaderEmptyArea,
-
- CE_ColumnViewGrip,
-
- CE_ItemViewItem,
-
- CE_ShapedFrame,
-
- // do not add any values below/greater than this
- CE_CustomBase = 0xf0000000
- };
-
- virtual void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const = 0;
-
- enum SubElement {
- SE_PushButtonContents,
- SE_PushButtonFocusRect,
-
- SE_CheckBoxIndicator,
- SE_CheckBoxContents,
- SE_CheckBoxFocusRect,
- SE_CheckBoxClickRect,
-
- SE_RadioButtonIndicator,
- SE_RadioButtonContents,
- SE_RadioButtonFocusRect,
- SE_RadioButtonClickRect,
-
- SE_ComboBoxFocusRect,
-
- SE_SliderFocusRect,
-
- SE_Q3DockWindowHandleRect,
-
- SE_ProgressBarGroove,
- SE_ProgressBarContents,
- SE_ProgressBarLabel,
-
- // ### Qt 5: These values are unused; eliminate them
- SE_DialogButtonAccept,
- SE_DialogButtonReject,
- SE_DialogButtonApply,
- SE_DialogButtonHelp,
- SE_DialogButtonAll,
- SE_DialogButtonAbort,
- SE_DialogButtonIgnore,
- SE_DialogButtonRetry,
- SE_DialogButtonCustom,
-
- SE_ToolBoxTabContents,
-
- SE_HeaderLabel,
- SE_HeaderArrow,
-
- SE_TabWidgetTabBar,
- SE_TabWidgetTabPane,
- SE_TabWidgetTabContents,
- SE_TabWidgetLeftCorner,
- SE_TabWidgetRightCorner,
-
- SE_ViewItemCheckIndicator,
- SE_ItemViewItemCheckIndicator = SE_ViewItemCheckIndicator,
-
- SE_TabBarTearIndicator,
-
- SE_TreeViewDisclosureItem,
-
- SE_LineEditContents,
- SE_FrameContents,
-
- SE_DockWidgetCloseButton,
- SE_DockWidgetFloatButton,
- SE_DockWidgetTitleBarText,
- SE_DockWidgetIcon,
-
- SE_CheckBoxLayoutItem,
- SE_ComboBoxLayoutItem,
- SE_DateTimeEditLayoutItem,
- SE_DialogButtonBoxLayoutItem, // ### remove
- SE_LabelLayoutItem,
- SE_ProgressBarLayoutItem,
- SE_PushButtonLayoutItem,
- SE_RadioButtonLayoutItem,
- SE_SliderLayoutItem,
- SE_SpinBoxLayoutItem,
- SE_ToolButtonLayoutItem,
-
- SE_FrameLayoutItem,
- SE_GroupBoxLayoutItem,
- SE_TabWidgetLayoutItem,
-
- SE_ItemViewItemDecoration,
- SE_ItemViewItemText,
- SE_ItemViewItemFocusRect,
-
- SE_TabBarTabLeftButton,
- SE_TabBarTabRightButton,
- SE_TabBarTabText,
-
- SE_ShapedFrameContents,
-
- SE_ToolBarHandle,
-
- // do not add any values below/greater than this
- SE_CustomBase = 0xf0000000
- };
-
- virtual QRect subElementRect(SubElement subElement, const QStyleOption *option,
- const QWidget *widget = 0) const = 0;
-
-
- enum ComplexControl {
- CC_SpinBox,
- CC_ComboBox,
- CC_ScrollBar,
- CC_Slider,
- CC_ToolButton,
- CC_TitleBar,
- CC_Q3ListView,
- CC_Dial,
- CC_GroupBox,
- CC_MdiControls,
-
- // do not add any values below/greater than this
- CC_CustomBase = 0xf0000000
- };
-
- enum SubControl {
- SC_None = 0x00000000,
-
- SC_ScrollBarAddLine = 0x00000001,
- SC_ScrollBarSubLine = 0x00000002,
- SC_ScrollBarAddPage = 0x00000004,
- SC_ScrollBarSubPage = 0x00000008,
- SC_ScrollBarFirst = 0x00000010,
- SC_ScrollBarLast = 0x00000020,
- SC_ScrollBarSlider = 0x00000040,
- SC_ScrollBarGroove = 0x00000080,
-
- SC_SpinBoxUp = 0x00000001,
- SC_SpinBoxDown = 0x00000002,
- SC_SpinBoxFrame = 0x00000004,
- SC_SpinBoxEditField = 0x00000008,
-
- SC_ComboBoxFrame = 0x00000001,
- SC_ComboBoxEditField = 0x00000002,
- SC_ComboBoxArrow = 0x00000004,
- SC_ComboBoxListBoxPopup = 0x00000008,
-
- SC_SliderGroove = 0x00000001,
- SC_SliderHandle = 0x00000002,
- SC_SliderTickmarks = 0x00000004,
-
- SC_ToolButton = 0x00000001,
- SC_ToolButtonMenu = 0x00000002,
-
- SC_TitleBarSysMenu = 0x00000001,
- SC_TitleBarMinButton = 0x00000002,
- SC_TitleBarMaxButton = 0x00000004,
- SC_TitleBarCloseButton = 0x00000008,
- SC_TitleBarNormalButton = 0x00000010,
- SC_TitleBarShadeButton = 0x00000020,
- SC_TitleBarUnshadeButton = 0x00000040,
- SC_TitleBarContextHelpButton = 0x00000080,
- SC_TitleBarLabel = 0x00000100,
-
- SC_Q3ListView = 0x00000001,
- SC_Q3ListViewBranch = 0x00000002,
- SC_Q3ListViewExpand = 0x00000004,
-
- SC_DialGroove = 0x00000001,
- SC_DialHandle = 0x00000002,
- SC_DialTickmarks = 0x00000004,
-
- SC_GroupBoxCheckBox = 0x00000001,
- SC_GroupBoxLabel = 0x00000002,
- SC_GroupBoxContents = 0x00000004,
- SC_GroupBoxFrame = 0x00000008,
-
- SC_MdiMinButton = 0x00000001,
- SC_MdiNormalButton = 0x00000002,
- SC_MdiCloseButton = 0x00000004,
-
- SC_CustomBase = 0xf0000000,
- SC_All = 0xffffffff
- };
- Q_DECLARE_FLAGS(SubControls, SubControl)
-
-#ifdef QT3_SUPPORT
- typedef SubControls SCFlags;
-#endif
-
- virtual void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *widget = 0) const = 0;
- virtual SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *widget = 0) const = 0;
- virtual QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget = 0) const = 0;
-
- enum PixelMetric {
- PM_ButtonMargin,
- PM_ButtonDefaultIndicator,
- PM_MenuButtonIndicator,
- PM_ButtonShiftHorizontal,
- PM_ButtonShiftVertical,
-
- PM_DefaultFrameWidth,
- PM_SpinBoxFrameWidth,
- PM_ComboBoxFrameWidth,
-
- PM_MaximumDragDistance,
-
- PM_ScrollBarExtent,
- PM_ScrollBarSliderMin,
-
- PM_SliderThickness, // total slider thickness
- PM_SliderControlThickness, // thickness of the business part
- PM_SliderLength, // total length of slider
- PM_SliderTickmarkOffset, //
- PM_SliderSpaceAvailable, // available space for slider to move
-
- PM_DockWidgetSeparatorExtent,
- PM_DockWidgetHandleExtent,
- PM_DockWidgetFrameWidth,
-
- PM_TabBarTabOverlap,
- PM_TabBarTabHSpace,
- PM_TabBarTabVSpace,
- PM_TabBarBaseHeight,
- PM_TabBarBaseOverlap,
-
- PM_ProgressBarChunkWidth,
-
- PM_SplitterWidth,
- PM_TitleBarHeight,
-
- PM_MenuScrollerHeight,
- PM_MenuHMargin,
- PM_MenuVMargin,
- PM_MenuPanelWidth,
- PM_MenuTearoffHeight,
- PM_MenuDesktopFrameWidth,
-
- PM_MenuBarPanelWidth,
- PM_MenuBarItemSpacing,
- PM_MenuBarVMargin,
- PM_MenuBarHMargin,
-
- PM_IndicatorWidth,
- PM_IndicatorHeight,
- PM_ExclusiveIndicatorWidth,
- PM_ExclusiveIndicatorHeight,
- PM_CheckListButtonSize,
- PM_CheckListControllerSize,
-
- PM_DialogButtonsSeparator,
- PM_DialogButtonsButtonWidth,
- PM_DialogButtonsButtonHeight,
-
- PM_MdiSubWindowFrameWidth,
- PM_MDIFrameWidth = PM_MdiSubWindowFrameWidth, //obsolete
- PM_MdiSubWindowMinimizedWidth,
- PM_MDIMinimizedWidth = PM_MdiSubWindowMinimizedWidth, //obsolete
-
- PM_HeaderMargin,
- PM_HeaderMarkSize,
- PM_HeaderGripMargin,
- PM_TabBarTabShiftHorizontal,
- PM_TabBarTabShiftVertical,
- PM_TabBarScrollButtonWidth,
-
- PM_ToolBarFrameWidth,
- PM_ToolBarHandleExtent,
- PM_ToolBarItemSpacing,
- PM_ToolBarItemMargin,
- PM_ToolBarSeparatorExtent,
- PM_ToolBarExtensionExtent,
-
- PM_SpinBoxSliderHeight,
-
- PM_DefaultTopLevelMargin,
- PM_DefaultChildMargin,
- PM_DefaultLayoutSpacing,
-
- PM_ToolBarIconSize,
- PM_ListViewIconSize,
- PM_IconViewIconSize,
- PM_SmallIconSize,
- PM_LargeIconSize,
-
- PM_FocusFrameVMargin,
- PM_FocusFrameHMargin,
-
- PM_ToolTipLabelFrameWidth,
- PM_CheckBoxLabelSpacing,
- PM_TabBarIconSize,
- PM_SizeGripSize,
- PM_DockWidgetTitleMargin,
- PM_MessageBoxIconSize,
- PM_ButtonIconSize,
-
- PM_DockWidgetTitleBarButtonMargin,
-
- PM_RadioButtonLabelSpacing,
- PM_LayoutLeftMargin,
- PM_LayoutTopMargin,
- PM_LayoutRightMargin,
- PM_LayoutBottomMargin,
- PM_LayoutHorizontalSpacing,
- PM_LayoutVerticalSpacing,
- PM_TabBar_ScrollButtonOverlap,
-
- PM_TextCursorWidth,
-
- PM_TabCloseIndicatorWidth,
- PM_TabCloseIndicatorHeight,
-
- PM_ScrollView_ScrollBarSpacing,
- PM_SubMenuOverlap,
-
- // do not add any values below/greater than this
- PM_CustomBase = 0xf0000000
- };
-
- virtual int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
- const QWidget *widget = 0) const = 0;
-
- enum ContentsType {
- CT_PushButton,
- CT_CheckBox,
- CT_RadioButton,
- CT_ToolButton,
- CT_ComboBox,
- CT_Splitter,
- CT_Q3DockWindow,
- CT_ProgressBar,
- CT_MenuItem,
- CT_MenuBarItem,
- CT_MenuBar,
- CT_Menu,
- CT_TabBarTab,
- CT_Slider,
- CT_ScrollBar,
- CT_Q3Header,
- CT_LineEdit,
- CT_SpinBox,
- CT_SizeGrip,
- CT_TabWidget,
- CT_DialogButtons,
- CT_HeaderSection,
- CT_GroupBox,
- CT_MdiControls,
- CT_ItemViewItem,
- // do not add any values below/greater than this
- CT_CustomBase = 0xf0000000
- };
-
- virtual QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *w = 0) const = 0;
-
- enum RequestSoftwareInputPanel {
- RSIP_OnMouseClickAndAlreadyFocused,
- RSIP_OnMouseClick
- };
-
- enum StyleHint {
- SH_EtchDisabledText,
- SH_DitherDisabledText,
- SH_ScrollBar_MiddleClickAbsolutePosition,
- SH_ScrollBar_ScrollWhenPointerLeavesControl,
- SH_TabBar_SelectMouseType,
- SH_TabBar_Alignment,
- SH_Header_ArrowAlignment,
- SH_Slider_SnapToValue,
- SH_Slider_SloppyKeyEvents,
- SH_ProgressDialog_CenterCancelButton,
- SH_ProgressDialog_TextLabelAlignment,
- SH_PrintDialog_RightAlignButtons,
- SH_MainWindow_SpaceBelowMenuBar,
- SH_FontDialog_SelectAssociatedText,
- SH_Menu_AllowActiveAndDisabled,
- SH_Menu_SpaceActivatesItem,
- SH_Menu_SubMenuPopupDelay,
- SH_ScrollView_FrameOnlyAroundContents,
- SH_MenuBar_AltKeyNavigation,
- SH_ComboBox_ListMouseTracking,
- SH_Menu_MouseTracking,
- SH_MenuBar_MouseTracking,
- SH_ItemView_ChangeHighlightOnFocus,
- SH_Widget_ShareActivation,
- SH_Workspace_FillSpaceOnMaximize,
- SH_ComboBox_Popup,
- SH_TitleBar_NoBorder,
- SH_Slider_StopMouseOverSlider,
- SH_ScrollBar_StopMouseOverSlider = SH_Slider_StopMouseOverSlider, // obsolete
- SH_BlinkCursorWhenTextSelected,
- SH_RichText_FullWidthSelection,
- SH_Menu_Scrollable,
- SH_GroupBox_TextLabelVerticalAlignment,
- SH_GroupBox_TextLabelColor,
- SH_Menu_SloppySubMenus,
- SH_Table_GridLineColor,
- SH_LineEdit_PasswordCharacter,
- SH_DialogButtons_DefaultButton,
- SH_ToolBox_SelectedPageTitleBold,
- SH_TabBar_PreferNoArrows,
- SH_ScrollBar_LeftClickAbsolutePosition,
- SH_Q3ListViewExpand_SelectMouseType,
- SH_UnderlineShortcut,
- SH_SpinBox_AnimateButton,
- SH_SpinBox_KeyPressAutoRepeatRate,
- SH_SpinBox_ClickAutoRepeatRate,
- SH_Menu_FillScreenWithScroll,
- SH_ToolTipLabel_Opacity,
- SH_DrawMenuBarSeparator,
- SH_TitleBar_ModifyNotification,
- SH_Button_FocusPolicy,
- SH_MenuBar_DismissOnSecondClick,
- SH_MessageBox_UseBorderForButtonSpacing,
- SH_TitleBar_AutoRaise,
- SH_ToolButton_PopupDelay,
- SH_FocusFrame_Mask,
- SH_RubberBand_Mask,
- SH_WindowFrame_Mask,
- SH_SpinControls_DisableOnBounds,
- SH_Dial_BackgroundRole,
- SH_ComboBox_LayoutDirection,
- SH_ItemView_EllipsisLocation,
- SH_ItemView_ShowDecorationSelected,
- SH_ItemView_ActivateItemOnSingleClick,
- SH_ScrollBar_ContextMenu,
- SH_ScrollBar_RollBetweenButtons,
- SH_Slider_AbsoluteSetButtons,
- SH_Slider_PageSetButtons,
- SH_Menu_KeyboardSearch,
- SH_TabBar_ElideMode,
- SH_DialogButtonLayout,
- SH_ComboBox_PopupFrameStyle,
- SH_MessageBox_TextInteractionFlags,
- SH_DialogButtonBox_ButtonsHaveIcons,
- SH_SpellCheckUnderlineStyle,
- SH_MessageBox_CenterButtons,
- SH_Menu_SelectionWrap,
- SH_ItemView_MovementWithoutUpdatingSelection,
- SH_ToolTip_Mask,
- SH_FocusFrame_AboveWidget,
- SH_TextControl_FocusIndicatorTextCharFormat,
- SH_WizardStyle,
- SH_ItemView_ArrowKeysNavigateIntoChildren,
- SH_Menu_Mask,
- SH_Menu_FlashTriggeredItem,
- SH_Menu_FadeOutOnHide,
- SH_SpinBox_ClickAutoRepeatThreshold,
- SH_ItemView_PaintAlternatingRowColorsForEmptyArea,
- SH_FormLayoutWrapPolicy,
- SH_TabWidget_DefaultTabPosition,
- SH_ToolBar_Movable,
- SH_FormLayoutFieldGrowthPolicy,
- SH_FormLayoutFormAlignment,
- SH_FormLayoutLabelAlignment,
- SH_ItemView_DrawDelegateFrame,
- SH_TabBar_CloseButtonPosition,
- SH_DockWidget_ButtonsHaveFrame,
- SH_ToolButtonStyle,
- SH_RequestSoftwareInputPanel,
- // Add new style hint values here
-
-#ifdef QT3_SUPPORT
- SH_GUIStyle = 0x00000100,
- SH_ScrollBar_BackgroundMode,
- // Add other compat values here
-
- SH_UnderlineAccelerator = SH_UnderlineShortcut,
-#endif
- SH_CustomBase = 0xf0000000
- };
-
- virtual int styleHint(StyleHint stylehint, const QStyleOption *opt = 0,
- const QWidget *widget = 0, QStyleHintReturn* returnData = 0) const = 0;
-
- enum StandardPixmap {
- SP_TitleBarMenuButton,
- SP_TitleBarMinButton,
- SP_TitleBarMaxButton,
- SP_TitleBarCloseButton,
- SP_TitleBarNormalButton,
- SP_TitleBarShadeButton,
- SP_TitleBarUnshadeButton,
- SP_TitleBarContextHelpButton,
- SP_DockWidgetCloseButton,
- SP_MessageBoxInformation,
- SP_MessageBoxWarning,
- SP_MessageBoxCritical,
- SP_MessageBoxQuestion,
- SP_DesktopIcon,
- SP_TrashIcon,
- SP_ComputerIcon,
- SP_DriveFDIcon,
- SP_DriveHDIcon,
- SP_DriveCDIcon,
- SP_DriveDVDIcon,
- SP_DriveNetIcon,
- SP_DirOpenIcon,
- SP_DirClosedIcon,
- SP_DirLinkIcon,
- SP_FileIcon,
- SP_FileLinkIcon,
- SP_ToolBarHorizontalExtensionButton,
- SP_ToolBarVerticalExtensionButton,
- SP_FileDialogStart,
- SP_FileDialogEnd,
- SP_FileDialogToParent,
- SP_FileDialogNewFolder,
- SP_FileDialogDetailedView,
- SP_FileDialogInfoView,
- SP_FileDialogContentsView,
- SP_FileDialogListView,
- SP_FileDialogBack,
- SP_DirIcon,
- SP_DialogOkButton,
- SP_DialogCancelButton,
- SP_DialogHelpButton,
- SP_DialogOpenButton,
- SP_DialogSaveButton,
- SP_DialogCloseButton,
- SP_DialogApplyButton,
- SP_DialogResetButton,
- SP_DialogDiscardButton,
- SP_DialogYesButton,
- SP_DialogNoButton,
- SP_ArrowUp,
- SP_ArrowDown,
- SP_ArrowLeft,
- SP_ArrowRight,
- SP_ArrowBack,
- SP_ArrowForward,
- SP_DirHomeIcon,
- SP_CommandLink,
- SP_VistaShield,
- SP_BrowserReload,
- SP_BrowserStop,
- SP_MediaPlay,
- SP_MediaStop,
- SP_MediaPause,
- SP_MediaSkipForward,
- SP_MediaSkipBackward,
- SP_MediaSeekForward,
- SP_MediaSeekBackward,
- SP_MediaVolume,
- SP_MediaVolumeMuted,
- // do not add any values below/greater than this
- SP_CustomBase = 0xf0000000
- };
-
- virtual QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const = 0;
-
- QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
-
- virtual QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *opt) const = 0;
-
- static QRect visualRect(Qt::LayoutDirection direction, const QRect &boundingRect,
- const QRect &logicalRect);
- static QPoint visualPos(Qt::LayoutDirection direction, const QRect &boundingRect,
- const QPoint &logicalPos);
- static int sliderPositionFromValue(int min, int max, int val, int space,
- bool upsideDown = false);
- static int sliderValueFromPosition(int min, int max, int pos, int space,
- bool upsideDown = false);
- static Qt::Alignment visualAlignment(Qt::LayoutDirection direction, Qt::Alignment alignment);
- static QRect alignedRect(Qt::LayoutDirection direction, Qt::Alignment alignment,
- const QSize &size, const QRect &rectangle);
-
- int layoutSpacing(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2, Qt::Orientation orientation,
- const QStyleOption *option = 0, const QWidget *widget = 0) const;
- int combinedLayoutSpacing(QSizePolicy::ControlTypes controls1,
- QSizePolicy::ControlTypes controls2, Qt::Orientation orientation,
- QStyleOption *option = 0, QWidget *widget = 0) const;
-
- const QStyle * proxy() const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
- int layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
-
-private:
- Q_DISABLE_COPY(QStyle)
- friend class QWidget;
- friend class QWidgetPrivate;
- friend class QApplication;
- friend class QProxyStyle;
- friend class QProxyStylePrivate;
- void setProxy(QStyle *style);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyle::State)
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyle::SubControls)
-
-#if !defined(QT_NO_DEBUG_STREAM)
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, QStyle::State state);
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTYLE_H
diff --git a/src/gui/styles/qstyle.qrc b/src/gui/styles/qstyle.qrc
deleted file mode 100644
index 8654e66a37..0000000000
--- a/src/gui/styles/qstyle.qrc
+++ /dev/null
@@ -1,135 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/styles/commonstyle">
-<file>images/filelink-16.png</file>
-<file>images/filelink-32.png</file>
-<file>images/filelink-128.png</file>
-<file>images/file-16.png</file>
-<file>images/file-32.png</file>
-<file>images/file-128.png</file>
-<file>images/newdirectory-16.png</file>
-<file>images/newdirectory-32.png</file>
-<file>images/newdirectory-128.png</file>
-<file>images/parentdir-16.png</file>
-<file>images/parentdir-32.png</file>
-<file>images/parentdir-128.png</file>
-<file>images/dvd-16.png</file>
-<file>images/dvd-32.png</file>
-<file>images/dvd-128.png</file>
-<file>images/cdr-16.png</file>
-<file>images/cdr-32.png</file>
-<file>images/cdr-128.png</file>
-<file>images/floppy-16.png</file>
-<file>images/floppy-32.png</file>
-<file>images/floppy-128.png</file>
-<file>images/harddrive-16.png</file>
-<file>images/harddrive-32.png</file>
-<file>images/harddrive-128.png</file>
-<file>images/trash-16.png</file>
-<file>images/trash-32.png</file>
-<file>images/trash-128.png</file>
-<file>images/networkdrive-16.png</file>
-<file>images/networkdrive-32.png</file>
-<file>images/networkdrive-128.png</file>
-<file>images/computer-16.png</file>
-<file>images/computer-32.png</file>
-<file>images/desktop-16.png</file>
-<file>images/desktop-32.png</file>
-<file>images/dirclosed-16.png</file>
-<file>images/dirclosed-32.png</file>
-<file>images/dirclosed-128.png</file>
-<file>images/dirlink-16.png</file>
-<file>images/dirlink-32.png</file>
-<file>images/dirlink-128.png</file>
-<file>images/diropen-16.png</file>
-<file>images/diropen-32.png</file>
-<file>images/diropen-128.png</file>
-<file>images/left-16.png</file>
-<file>images/left-32.png</file>
-<file>images/left-128.png</file>
-<file>images/right-16.png</file>
-<file>images/right-32.png</file>
-<file>images/right-128.png</file>
-<file>images/up-16.png</file>
-<file>images/up-32.png</file>
-<file>images/up-128.png</file>
-<file>images/down-16.png</file>
-<file>images/down-32.png</file>
-<file>images/down-128.png</file>
-<file>images/filecontents-16.png</file>
-<file>images/filecontents-32.png</file>
-<file>images/filecontents-128.png</file>
-<file>images/fileinfo-16.png</file>
-<file>images/fileinfo-32.png</file>
-<file>images/fileinfo-128.png</file>
-<file>images/viewdetailed-16.png</file>
-<file>images/viewdetailed-32.png</file>
-<file>images/viewdetailed-128.png</file>
-<file>images/viewlist-16.png</file>
-<file>images/viewlist-32.png</file>
-<file>images/viewlist-128.png</file>
-<file>images/fontbitmap-16.png</file>
-<file>images/fonttruetype-16.png</file>
-<file>images/standardbutton-apply-128.png</file>
-<file>images/standardbutton-apply-16.png</file>
-<file>images/standardbutton-apply-32.png</file>
-<file>images/standardbutton-cancel-128.png</file>
-<file>images/standardbutton-cancel-16.png</file>
-<file>images/standardbutton-cancel-32.png</file>
-<file>images/standardbutton-clear-128.png</file>
-<file>images/standardbutton-clear-16.png</file>
-<file>images/standardbutton-clear-32.png</file>
-<file>images/standardbutton-close-128.png</file>
-<file>images/standardbutton-close-16.png</file>
-<file>images/standardbutton-close-32.png</file>
-<file>images/standardbutton-delete-128.png</file>
-<file>images/standardbutton-delete-16.png</file>
-<file>images/standardbutton-delete-32.png</file>
-<file>images/standardbutton-help-128.png</file>
-<file>images/standardbutton-help-16.png</file>
-<file>images/standardbutton-help-32.png</file>
-<file>images/standardbutton-no-128.png</file>
-<file>images/standardbutton-no-16.png</file>
-<file>images/standardbutton-no-32.png</file>
-<file>images/standardbutton-ok-128.png</file>
-<file>images/standardbutton-ok-16.png</file>
-<file>images/standardbutton-ok-32.png</file>
-<file>images/standardbutton-open-128.png</file>
-<file>images/standardbutton-open-16.png</file>
-<file>images/standardbutton-open-32.png</file>
-<file>images/standardbutton-save-128.png</file>
-<file>images/standardbutton-save-16.png</file>
-<file>images/standardbutton-save-32.png</file>
-<file>images/standardbutton-yes-128.png</file>
-<file>images/standardbutton-yes-16.png</file>
-<file>images/standardbutton-yes-32.png</file>
-<file>images/standardbutton-closetab-16.png</file>
-<file>images/standardbutton-closetab-down-16.png</file>
-<file>images/standardbutton-closetab-hover-16.png</file>
-<file>images/refresh-24.png</file>
-<file>images/refresh-32.png</file>
-<file>images/stop-24.png</file>
-<file>images/stop-32.png</file>
-<file>images/media-stop-16.png</file>
-<file>images/media-stop-32.png</file>
-<file>images/media-play-16.png</file>
-<file>images/media-play-32.png</file>
-<file>images/media-pause-16.png</file>
-<file>images/media-pause-32.png</file>
-<file>images/media-seek-forward-16.png</file>
-<file>images/media-seek-forward-32.png</file>
-<file>images/media-seek-backward-16.png</file>
-<file>images/media-seek-backward-32.png</file>
-<file>images/media-skip-forward-16.png</file>
-<file>images/media-skip-forward-32.png</file>
-<file>images/media-skip-backward-16.png</file>
-<file>images/media-skip-backward-32.png</file>
-<file>images/media-volume-16.png</file>
-<file>images/media-volume-muted-16.png</file>
-</qresource>
-<qresource prefix="/trolltech/styles/macstyle">
-<file>images/closedock-16.png</file>
-<file>images/closedock-down-16.png</file>
-<file>images/dockdock-16.png</file>
-<file>images/dockdock-down-16.png</file>
-</qresource>
-</RCC>
diff --git a/src/gui/styles/qstyle_p.h b/src/gui/styles/qstyle_p.h
deleted file mode 100644
index 1fcd2eaf2a..0000000000
--- a/src/gui/styles/qstyle_p.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLE_P_H
-#define QSTYLE_P_H
-
-#include "private/qobject_p.h"
-#include <QtGui/qstyle.h>
-
-QT_BEGIN_NAMESPACE
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of qstyle_*.cpp. This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-// Private class
-
-class QStyle;
-
-class QStylePrivate: public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QStyle)
-public:
- inline QStylePrivate()
- : layoutSpacingIndex(-1), proxyStyle(0) {}
- mutable int layoutSpacingIndex;
- QStyle *proxyStyle;
-};
-
-
-#define BEGIN_STYLE_PIXMAPCACHE(a) \
- QRect rect = option->rect; \
- QPixmap internalPixmapCache; \
- QImage imageCache; \
- QPainter *p = painter; \
- QString unique = QStyleHelper::uniqueName((a), option, option->rect.size()); \
- int txType = painter->deviceTransform().type() | painter->worldTransform().type(); \
- bool doPixmapCache = txType <= QTransform::TxTranslate; \
- if (doPixmapCache && QPixmapCache::find(unique, internalPixmapCache)) { \
- painter->drawPixmap(option->rect.topLeft(), internalPixmapCache); \
- } else { \
- if (doPixmapCache) { \
- rect.setRect(0, 0, option->rect.width(), option->rect.height()); \
- imageCache = QImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied); \
- imageCache.fill(0); \
- p = new QPainter(&imageCache); \
- }
-
-
-
-#define END_STYLE_PIXMAPCACHE \
- if (doPixmapCache) { \
- p->end(); \
- delete p; \
- internalPixmapCache = QPixmap::fromImage(imageCache); \
- painter->drawPixmap(option->rect.topLeft(), internalPixmapCache); \
- QPixmapCache::insert(unique, internalPixmapCache); \
- } \
- }
-
-QT_END_NAMESPACE
-
-#endif //QSTYLE_P_H
diff --git a/src/gui/styles/qstyle_s60.qrc b/src/gui/styles/qstyle_s60.qrc
deleted file mode 100644
index dbee38b266..0000000000
--- a/src/gui/styles/qstyle_s60.qrc
+++ /dev/null
@@ -1,137 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/styles/commonstyle">
-<!-- <file>images/filelink-16.png</file> -->
-<file>images/filelink-32.png</file>
-<!-- <file>images/filelink-128.png</file> -->
-<!-- <file>images/file-16.png</file> -->
-<file>images/file-32.png</file>
-<!-- <file>images/file-128.png</file> -->
-<!-- <file>images/newdirectory-16.png</file> -->
-<file>images/newdirectory-32.png</file>
-<!-- <file>images/newdirectory-128.png</file> -->
-<!-- <file>images/parentdir-16.png</file> -->
-<file>images/parentdir-32.png</file>
-<!-- <file>images/parentdir-128.png</file> -->
-<!-- <file>images/dvd-16.png</file> -->
-<!-- <file>images/dvd-32.png</file> -->
-<!-- <file>images/dvd-128.png</file> -->
-<!-- <file>images/cdr-16.png</file> -->
-<!-- <file>images/cdr-32.png</file> -->
-<!-- <file>images/cdr-128.png</file> -->
-<!-- <file>images/floppy-16.png</file> -->
-<!-- <file>images/floppy-32.png</file> -->
-<!-- <file>images/floppy-128.png</file> -->
-<!-- <file>images/harddrive-16.png</file> -->
-<file>images/harddrive-32.png</file>
-<!-- <file>images/harddrive-128.png</file> -->
-<!-- <file>images/trash-16.png</file> -->
-<!-- <file>images/trash-32.png</file> -->
-<!-- <file>images/trash-128.png</file> -->
-<!-- <file>images/networkdrive-16.png</file> -->
-<!-- <file>images/networkdrive-32.png</file> -->
-<!-- <file>images/networkdrive-128.png</file> -->
-<!-- <file>images/computer-16.png</file> -->
-<!-- <file>images/computer-32.png</file> -->
-<!-- <file>images/desktop-16.png</file> -->
-<file>images/desktop-32.png</file>
-<!-- <file>images/dirclosed-16.png</file> -->
-<file>images/dirclosed-32.png</file>
-<!-- <file>images/dirclosed-128.png</file> -->
-<!-- <file>images/dirlink-16.png</file> -->
-<file>images/dirlink-32.png</file>
-<!-- <file>images/dirlink-128.png</file> -->
-<!-- <file>images/diropen-16.png</file> -->
-<file>images/diropen-32.png</file>
-<!-- <file>images/diropen-128.png</file> -->
-<!-- <file>images/left-16.png</file> -->
-<file>images/left-32.png</file>
-<!-- <file>images/left-128.png</file> -->
-<!-- <file>images/right-16.png</file> -->
-<file>images/right-32.png</file>
-<!-- <file>images/right-128.png</file> -->
-<!-- <file>images/up-16.png</file> -->
-<file>images/up-32.png</file>
-<!-- <file>images/up-128.png</file> -->
-<!-- <file>images/down-16.png</file> -->
-<file>images/down-32.png</file>
-<!-- <file>images/down-128.png</file> -->
-<!-- <file>images/filecontents-16.png</file> -->
-<file>images/filecontents-32.png</file>
-<!-- <file>images/filecontents-128.png</file> -->
-<!-- <file>images/fileinfo-16.png</file> -->
-<file>images/fileinfo-32.png</file>
-<!-- <file>images/fileinfo-128.png</file> -->
-<!-- <file>images/viewdetailed-16.png</file> -->
-<file>images/viewdetailed-32.png</file>
-<!-- <file>images/viewdetailed-128.png</file> -->
-<!-- <file>images/viewlist-16.png</file> -->
-<file>images/viewlist-32.png</file>
-<!-- <file>images/viewlist-128.png</file> -->
-<file>images/fontbitmap-16.png</file>
-<file>images/fonttruetype-16.png</file>
-<!-- <file>images/standardbutton-apply-128.png</file> -->
-<!-- <file>images/standardbutton-apply-16.png</file> -->
-<file>images/standardbutton-apply-32.png</file>
-<!-- <file>images/standardbutton-cancel-128.png</file> -->
-<!-- <file>images/standardbutton-cancel-16.png</file> -->
-<file>images/standardbutton-cancel-32.png</file>
-<!-- <file>images/standardbutton-clear-128.png</file> -->
-<!-- <file>images/standardbutton-clear-16.png</file> -->
-<file>images/standardbutton-clear-32.png</file>
-<!-- <file>images/standardbutton-close-128.png</file> -->
-<!-- <file>images/standardbutton-close-16.png</file> -->
-<file>images/standardbutton-close-32.png</file>
-<!-- <file>images/standardbutton-delete-128.png</file> -->
-<!-- <file>images/standardbutton-delete-16.png</file> -->
-<file>images/standardbutton-delete-32.png</file>
-<!-- <file>images/standardbutton-help-128.png</file> -->
-<!-- <file>images/standardbutton-help-16.png</file> -->
-<file>images/standardbutton-help-32.png</file>
-<!-- <file>images/standardbutton-no-128.png</file> -->
-<!-- <file>images/standardbutton-no-16.png</file> -->
-<file>images/standardbutton-no-32.png</file>
-<!-- <file>images/standardbutton-ok-128.png</file> -->
-<!-- <file>images/standardbutton-ok-16.png</file> -->
-<file>images/standardbutton-ok-32.png</file>
-<!-- <file>images/standardbutton-open-128.png</file> -->
-<!-- <file>images/standardbutton-open-16.png</file> -->
-<file>images/standardbutton-open-32.png</file>
-<!-- <file>images/standardbutton-save-128.png</file> -->
-<!-- <file>images/standardbutton-save-16.png</file> -->
-<file>images/standardbutton-save-32.png</file>
-<!-- <file>images/standardbutton-yes-128.png</file> -->
-<!-- <file>images/standardbutton-yes-16.png</file> -->
-<file>images/standardbutton-yes-32.png</file>
-<file>images/standardbutton-closetab-16.png</file>
-<file>images/standardbutton-closetab-down-16.png</file>
-<file>images/standardbutton-closetab-hover-16.png</file>
-<!-- <file>images/refresh-24.png</file> -->
-<file>images/refresh-32.png</file>
-<!-- <file>images/stop-24.png</file> -->
-<file>images/stop-32.png</file>
-<!-- <file>images/media-stop-16.png</file> -->
-<file>images/media-stop-32.png</file>
-<!-- <file>images/media-play-16.png</file> -->
-<file>images/media-play-32.png</file>
-<!-- <file>images/media-pause-16.png</file> -->
-<file>images/media-pause-32.png</file>
-<!-- <file>images/media-seek-forward-16.png</file> -->
-<file>images/media-seek-forward-32.png</file>
-<!-- <file>images/media-seek-backward-16.png</file> -->
-<file>images/media-seek-backward-32.png</file>
-<!-- <file>images/media-skip-forward-16.png</file> -->
-<file>images/media-skip-forward-32.png</file>
-<!-- <file>images/media-skip-backward-16.png</file> -->
-<file>images/media-skip-backward-32.png</file>
-<file>images/media-volume-16.png</file>
-<file>images/media-volume-muted-16.png</file>
-</qresource>
-<!--
-<qresource prefix="/trolltech/styles/macstyle">
-<file>images/closedock-16.png</file>
-<file>images/closedock-down-16.png</file>
-<file>images/dockdock-16.png</file>
-<file>images/dockdock-down-16.png</file>
-</qresource>
--->
-</RCC>
diff --git a/src/gui/styles/qstyle_s60_simulated.qrc b/src/gui/styles/qstyle_s60_simulated.qrc
deleted file mode 100644
index 969732e1e0..0000000000
--- a/src/gui/styles/qstyle_s60_simulated.qrc
+++ /dev/null
@@ -1,6 +0,0 @@
-<!DOCTYPE RCC>
-<RCC version="1.0">
- <qresource prefix="/trolltech/styles/s60style">
- <file>images/defaults60theme.blob</file>
- </qresource>
-</RCC>
diff --git a/src/gui/styles/qstyle_wince.qrc b/src/gui/styles/qstyle_wince.qrc
deleted file mode 100644
index bdcf604625..0000000000
--- a/src/gui/styles/qstyle_wince.qrc
+++ /dev/null
@@ -1,97 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/styles/commonstyle">
-<file>images/filelink-16.png</file>
-<file>images/filelink-32.png</file>
-<file>images/file-16.png</file>
-<file>images/file-32.png</file>
-<file>images/newdirectory-16.png</file>
-<file>images/newdirectory-32.png</file>
-<file>images/parentdir-16.png</file>
-<file>images/parentdir-32.png</file>
-<file>images/dvd-16.png</file>
-<file>images/dvd-32.png</file>
-<file>images/cdr-16.png</file>
-<file>images/cdr-32.png</file>
-<file>images/floppy-16.png</file>
-<file>images/floppy-32.png</file>
-<file>images/harddrive-16.png</file>
-<file>images/harddrive-32.png</file>
-<file>images/trash-16.png</file>
-<file>images/trash-32.png</file>
-<file>images/networkdrive-16.png</file>
-<file>images/networkdrive-32.png</file>
-<file>images/computer-16.png</file>
-<file>images/computer-32.png</file>
-<file>images/desktop-16.png</file>
-<file>images/desktop-32.png</file>
-<file>images/dirclosed-16.png</file>
-<file>images/dirclosed-32.png</file>
-<file>images/dirlink-16.png</file>
-<file>images/dirlink-32.png</file>
-<file>images/diropen-16.png</file>
-<file>images/diropen-32.png</file>
-<file>images/left-16.png</file>
-<file>images/left-32.png</file>
-<file>images/right-16.png</file>
-<file>images/right-32.png</file>
-<file>images/up-16.png</file>
-<file>images/up-32.png</file>
-<file>images/down-16.png</file>
-<file>images/down-32.png</file>
-<file>images/filecontents-16.png</file>
-<file>images/filecontents-32.png</file>
-<file>images/fileinfo-16.png</file>
-<file>images/fileinfo-32.png</file>
-<file>images/viewdetailed-16.png</file>
-<file>images/viewdetailed-32.png</file>
-<file>images/viewlist-16.png</file>
-<file>images/viewlist-32.png</file>
-<file>images/fontbitmap-16.png</file>
-<file>images/fonttruetype-16.png</file>
-<file>images/standardbutton-apply-16.png</file>
-<file>images/standardbutton-apply-32.png</file>
-<file>images/standardbutton-cancel-16.png</file>
-<file>images/standardbutton-cancel-32.png</file>
-<file>images/standardbutton-clear-16.png</file>
-<file>images/standardbutton-clear-32.png</file>
-<file>images/standardbutton-close-16.png</file>
-<file>images/standardbutton-close-32.png</file>
-<file>images/standardbutton-delete-16.png</file>
-<file>images/standardbutton-delete-32.png</file>
-<file>images/standardbutton-help-16.png</file>
-<file>images/standardbutton-help-32.png</file>
-<file>images/standardbutton-no-16.png</file>
-<file>images/standardbutton-no-32.png</file>
-<file>images/standardbutton-ok-16.png</file>
-<file>images/standardbutton-ok-32.png</file>
-<file>images/standardbutton-open-16.png</file>
-<file>images/standardbutton-open-32.png</file>
-<file>images/standardbutton-save-16.png</file>
-<file>images/standardbutton-save-32.png</file>
-<file>images/standardbutton-yes-16.png</file>
-<file>images/standardbutton-yes-32.png</file>
-<file>images/standardbutton-closetab-16.png</file>
-<file>images/standardbutton-closetab-down-16.png</file>
-<file>images/standardbutton-closetab-hover-16.png</file>
-<file>images/refresh-24.png</file>
-<file>images/refresh-32.png</file>
-<file>images/stop-24.png</file>
-<file>images/stop-32.png</file>
-<file>images/media-stop-16.png</file>
-<file>images/media-stop-32.png</file>
-<file>images/media-play-16.png</file>
-<file>images/media-play-32.png</file>
-<file>images/media-pause-16.png</file>
-<file>images/media-pause-32.png</file>
-<file>images/media-seek-forward-16.png</file>
-<file>images/media-seek-forward-32.png</file>
-<file>images/media-seek-backward-16.png</file>
-<file>images/media-seek-backward-32.png</file>
-<file>images/media-skip-forward-16.png</file>
-<file>images/media-skip-forward-32.png</file>
-<file>images/media-skip-backward-16.png</file>
-<file>images/media-skip-backward-32.png</file>
-<file>images/media-volume-16.png</file>
-<file>images/media-volume-muted-16.png</file>
-</qresource>
-</RCC>
diff --git a/src/gui/styles/qstylefactory.cpp b/src/gui/styles/qstylefactory.cpp
deleted file mode 100644
index 1a9682a831..0000000000
--- a/src/gui/styles/qstylefactory.cpp
+++ /dev/null
@@ -1,271 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstylefactory.h"
-#include "qstyleplugin.h"
-#include "private/qfactoryloader_p.h"
-#include "qmutex.h"
-
-#include "qapplication.h"
-#include "qwindowsstyle.h"
-#include "qmotifstyle.h"
-#include "qcdestyle.h"
-#ifndef QT_NO_STYLE_PLASTIQUE
-#include "qplastiquestyle.h"
-#endif
-#ifndef QT_NO_STYLE_CLEANLOOKS
-#include "qcleanlooksstyle.h"
-#endif
-#ifndef QT_NO_STYLE_GTK
-#include "qgtkstyle.h"
-#endif
-#ifndef QT_NO_STYLE_WINDOWSXP
-#include "qwindowsxpstyle.h"
-#endif
-#ifndef QT_NO_STYLE_WINDOWSVISTA
-#include "qwindowsvistastyle.h"
-#endif
-#ifndef QT_NO_STYLE_WINDOWSCE
-#include "qwindowscestyle.h"
-#endif
-#ifndef QT_NO_STYLE_WINDOWSMOBILE
-#include "qwindowsmobilestyle.h"
-#endif
-#ifndef QT_NO_STYLE_S60
-#include "qs60style.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(QT_NO_STYLE_MAC) && defined(Q_WS_MAC)
-QT_BEGIN_INCLUDE_NAMESPACE
-# include "qmacstyle_mac.h"
-QT_END_INCLUDE_NAMESPACE
-#endif
-
-#ifndef QT_NO_LIBRARY
-Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
- (QStyleFactoryInterface_iid, QLatin1String("/styles"), Qt::CaseInsensitive))
-#endif
-
-/*!
- \class QStyleFactory
- \brief The QStyleFactory class creates QStyle objects.
-
- \ingroup appearance
-
- The QStyle class is an abstract base class that encapsulates the
- look and feel of a GUI. QStyleFactory creates a QStyle object
- using the create() function and a key identifying the style. The
- styles are either built-in or dynamically loaded from a style
- plugin (see QStylePlugin).
-
- The valid keys can be retrieved using the keys()
- function. Typically they include "windows", "motif", "cde",
- "plastique" and "cleanlooks". Depending on the platform,
- "windowsxp", "windowsvista" and "macintosh" may be available.
- Note that keys are case insensitive.
-
- \sa QStyle
-*/
-
-/*!
- Creates and returns a QStyle object that matches the given \a key, or
- returns 0 if no matching style is found.
-
- Both built-in styles and styles from style plugins are queried for a
- matching style.
-
- \note The keys used are case insensitive.
-
- \sa keys()
-*/
-QStyle *QStyleFactory::create(const QString& key)
-{
- QStyle *ret = 0;
- QString style = key.toLower();
-#ifndef QT_NO_STYLE_WINDOWS
- if (style == QLatin1String("windows"))
- ret = new QWindowsStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_WINDOWSCE
- if (style == QLatin1String("windowsce"))
- ret = new QWindowsCEStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_WINDOWSMOBILE
- if (style == QLatin1String("windowsmobile"))
- ret = new QWindowsMobileStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_WINDOWSXP
- if (style == QLatin1String("windowsxp"))
- ret = new QWindowsXPStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_WINDOWSVISTA
- if (style == QLatin1String("windowsvista"))
- ret = new QWindowsVistaStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_MOTIF
- if (style == QLatin1String("motif"))
- ret = new QMotifStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_CDE
- if (style == QLatin1String("cde"))
- ret = new QCDEStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_S60
- if (style == QLatin1String("s60"))
- ret = new QS60Style;
- else
-#endif
-#ifndef QT_NO_STYLE_PLASTIQUE
- if (style == QLatin1String("plastique"))
- ret = new QPlastiqueStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_CLEANLOOKS
- if (style == QLatin1String("cleanlooks"))
- ret = new QCleanlooksStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_GTK
- if (style == QLatin1String("gtk") || style == QLatin1String("gtk+"))
- ret = new QGtkStyle;
- else
-#endif
-#ifndef QT_NO_STYLE_MAC
- if (style.startsWith(QLatin1String("macintosh"))) {
- ret = new QMacStyle;
-# ifdef Q_WS_MAC
- if (style == QLatin1String("macintosh"))
- style += QLatin1String(" (aqua)");
-# endif
- } else
-#endif
- { } // Keep these here - they make the #ifdefery above work
-#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
- if(!ret) {
- if (QStyleFactoryInterface *factory = qobject_cast<QStyleFactoryInterface*>(loader()->instance(style)))
- ret = factory->create(style);
- }
-#endif
- if(ret)
- ret->setObjectName(style);
- return ret;
-}
-
-/*!
- Returns the list of valid keys, i.e. the keys this factory can
- create styles for.
-
- \sa create()
-*/
-QStringList QStyleFactory::keys()
-{
-#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
- QStringList list = loader()->keys();
-#else
- QStringList list;
-#endif
-#ifndef QT_NO_STYLE_WINDOWS
- if (!list.contains(QLatin1String("Windows")))
- list << QLatin1String("Windows");
-#endif
-#ifndef QT_NO_STYLE_WINDOWSCE
- if (!list.contains(QLatin1String("WindowsCE")))
- list << QLatin1String("WindowsCE");
-#endif
-#ifndef QT_NO_STYLE_WINDOWSMOBILE
- if (!list.contains(QLatin1String("WindowsMobile")))
- list << QLatin1String("WindowsMobile");
-#endif
-#ifndef QT_NO_STYLE_WINDOWSXP
- if (!list.contains(QLatin1String("WindowsXP")) &&
- (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- list << QLatin1String("WindowsXP");
-#endif
-#ifndef QT_NO_STYLE_WINDOWSVISTA
- if (!list.contains(QLatin1String("WindowsVista")) &&
- (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
- list << QLatin1String("WindowsVista");
-#endif
-#ifndef QT_NO_STYLE_MOTIF
- if (!list.contains(QLatin1String("Motif")))
- list << QLatin1String("Motif");
-#endif
-#ifndef QT_NO_STYLE_CDE
- if (!list.contains(QLatin1String("CDE")))
- list << QLatin1String("CDE");
-#endif
-#ifndef QT_NO_STYLE_S60
- if (!list.contains(QLatin1String("S60")))
- list << QLatin1String("S60");
-#endif
-#ifndef QT_NO_STYLE_PLASTIQUE
- if (!list.contains(QLatin1String("Plastique")))
- list << QLatin1String("Plastique");
-#endif
-#ifndef QT_NO_STYLE_GTK
- if (!list.contains(QLatin1String("GTK+")))
- list << QLatin1String("GTK+");
-#endif
-#ifndef QT_NO_STYLE_CLEANLOOKS
- if (!list.contains(QLatin1String("Cleanlooks")))
- list << QLatin1String("Cleanlooks");
-#endif
-#ifndef QT_NO_STYLE_MAC
- QString mstyle = QLatin1String("Macintosh");
-# ifdef Q_WS_MAC
- mstyle += QLatin1String(" (aqua)");
-# endif
- if (!list.contains(mstyle))
- list << mstyle;
-#endif
- return list;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstylefactory.h b/src/gui/styles/qstylefactory.h
deleted file mode 100644
index b665e5fce4..0000000000
--- a/src/gui/styles/qstylefactory.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLEFACTORY_H
-#define QSTYLEFACTORY_H
-
-#include <QtCore/qstringlist.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStyle;
-
-class Q_GUI_EXPORT QStyleFactory
-{
-public:
- static QStringList keys();
- static QStyle *create(const QString&);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTYLEFACTORY_H
diff --git a/src/gui/styles/qstylehelper.cpp b/src/gui/styles/qstylehelper.cpp
deleted file mode 100644
index 59766cae0f..0000000000
--- a/src/gui/styles/qstylehelper.cpp
+++ /dev/null
@@ -1,378 +0,0 @@
-/****************************************************************************
-**
-** 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 <qstyleoption.h>
-#include <qpainter.h>
-#include <qpixmapcache.h>
-#include <private/qmath_p.h>
-#include <private/qstyle_p.h>
-#include <qmath.h>
-
-#if defined(Q_WS_WIN)
-#include "qt_windows.h"
-#elif defined(Q_WS_MAC)
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#include "qstylehelper_p.h"
-#include <qstringbuilder.h>
-
-QT_BEGIN_NAMESPACE
-
-namespace QStyleHelper {
-
-QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size)
-{
- const QStyleOptionComplex *complexOption = qstyleoption_cast<const QStyleOptionComplex *>(option);
- QString tmp = key % HexString<uint>(option->state)
- % HexString<uint>(option->direction)
- % HexString<uint>(complexOption ? uint(complexOption->activeSubControls) : 0u)
- % HexString<quint64>(option->palette.cacheKey())
- % HexString<uint>(size.width())
- % HexString<uint>(size.height());
-
-#ifndef QT_NO_SPINBOX
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- tmp = tmp % HexString<uint>(spinBox->buttonSymbols)
- % HexString<uint>(spinBox->stepEnabled)
- % QLatin1Char(spinBox->frame ? '1' : '0'); ;
- }
-#endif // QT_NO_SPINBOX
- return tmp;
-}
-
-qreal dpiScaled(qreal value)
-{
- static qreal scale = -1;
- if (scale < 0) {
- scale = 1.0;
-#if defined(Q_WS_WIN)
- {
- HDC hdcScreen = GetDC(0);
- int dpi = GetDeviceCaps(hdcScreen, LOGPIXELSX);
- ReleaseDC(0, hdcScreen);
- scale = dpi/96.0;
- }
-#elif defined(Q_WS_MAC)
- scale = qt_mac_get_scalefactor();
-#endif
- }
- return value * scale;
-}
-
-
-#ifndef QT_NO_DIAL
-
-int calcBigLineSize(int radius)
-{
- int bigLineSize = radius / 6;
- if (bigLineSize < 4)
- bigLineSize = 4;
- if (bigLineSize > radius / 2)
- bigLineSize = radius / 2;
- return bigLineSize;
-}
-
-static QPointF calcRadialPos(const QStyleOptionSlider *dial, qreal offset)
-{
- const int width = dial->rect.width();
- const int height = dial->rect.height();
- const int r = qMin(width, height) / 2;
- const int currentSliderPosition = dial->upsideDown ? dial->sliderPosition : (dial->maximum - dial->sliderPosition);
- qreal a = 0;
- if (dial->maximum == dial->minimum)
- a = Q_PI / 2;
- else if (dial->dialWrapping)
- a = Q_PI * 3 / 2 - (currentSliderPosition - dial->minimum) * 2 * Q_PI
- / (dial->maximum - dial->minimum);
- else
- a = (Q_PI * 8 - (currentSliderPosition - dial->minimum) * 10 * Q_PI
- / (dial->maximum - dial->minimum)) / 6;
- qreal xc = width / 2.0;
- qreal yc = height / 2.0;
- qreal len = r - QStyleHelper::calcBigLineSize(r) - 3;
- qreal back = offset * len;
- QPointF pos(QPointF(xc + back * qCos(a), yc - back * qSin(a)));
- return pos;
-}
-
-qreal angle(const QPointF &p1, const QPointF &p2)
-{
- static const qreal rad_factor = 180 / Q_PI;
- qreal _angle = 0;
-
- if (p1.x() == p2.x()) {
- if (p1.y() < p2.y())
- _angle = 270;
- else
- _angle = 90;
- } else {
- qreal x1, x2, y1, y2;
-
- if (p1.x() <= p2.x()) {
- x1 = p1.x(); y1 = p1.y();
- x2 = p2.x(); y2 = p2.y();
- } else {
- x2 = p1.x(); y2 = p1.y();
- x1 = p2.x(); y1 = p2.y();
- }
-
- qreal m = -(y2 - y1) / (x2 - x1);
- _angle = qAtan(m) * rad_factor;
-
- if (p1.x() < p2.x())
- _angle = 180 - _angle;
- else
- _angle = -_angle;
- }
- return _angle;
-}
-
-QPolygonF calcLines(const QStyleOptionSlider *dial)
-{
- QPolygonF poly;
- int width = dial->rect.width();
- int height = dial->rect.height();
- qreal r = qMin(width, height) / 2;
- int bigLineSize = calcBigLineSize(int(r));
-
- qreal xc = width / 2 + 0.5;
- qreal yc = height / 2 + 0.5;
- int ns = dial->tickInterval;
- int notches = (dial->maximum + ns - 1 - dial->minimum) / ns;
- if (notches <= 0)
- return poly;
- if (dial->maximum < dial->minimum || dial->maximum - dial->minimum > 1000) {
- int maximum = dial->minimum + 1000;
- notches = (maximum + ns - 1 - dial->minimum) / ns;
- }
-
- poly.resize(2 + 2 * notches);
- int smallLineSize = bigLineSize / 2;
- for (int i = 0; i <= notches; ++i) {
- qreal angle = dial->dialWrapping ? Q_PI * 3 / 2 - i * 2 * Q_PI / notches
- : (Q_PI * 8 - i * 10 * Q_PI / notches) / 6;
- qreal s = qSin(angle);
- qreal c = qCos(angle);
- if (i == 0 || (((ns * i) % (dial->pageStep ? dial->pageStep : 1)) == 0)) {
- poly[2 * i] = QPointF(xc + (r - bigLineSize) * c,
- yc - (r - bigLineSize) * s);
- poly[2 * i + 1] = QPointF(xc + r * c, yc - r * s);
- } else {
- poly[2 * i] = QPointF(xc + (r - 1 - smallLineSize) * c,
- yc - (r - 1 - smallLineSize) * s);
- poly[2 * i + 1] = QPointF(xc + (r - 1) * c, yc -(r - 1) * s);
- }
- }
- return poly;
-}
-
-// This will draw a nice and shiny QDial for us. We don't want
-// all the shinyness in QWindowsStyle, hence we place it here
-
-void drawDial(const QStyleOptionSlider *option, QPainter *painter)
-{
- QPalette pal = option->palette;
- QColor buttonColor = pal.button().color();
- const int width = option->rect.width();
- const int height = option->rect.height();
- const bool enabled = option->state & QStyle::State_Enabled;
- qreal r = qMin(width, height) / 2;
- r -= r/50;
- const qreal penSize = r/20.0;
-
- painter->save();
- painter->setRenderHint(QPainter::Antialiasing);
-
- // Draw notches
- if (option->subControls & QStyle::SC_DialTickmarks) {
- painter->setPen(option->palette.dark().color().darker(120));
- painter->drawLines(QStyleHelper::calcLines(option));
- }
-
- // Cache dial background
- BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("qdial"));
- p->setRenderHint(QPainter::Antialiasing);
-
- const qreal d_ = r / 6;
- const qreal dx = option->rect.x() + d_ + (width - 2 * r) / 2 + 1;
- const qreal dy = option->rect.y() + d_ + (height - 2 * r) / 2 + 1;
-
- QRectF br = QRectF(dx + 0.5, dy + 0.5,
- int(r * 2 - 2 * d_ - 2),
- int(r * 2 - 2 * d_ - 2));
- buttonColor.setHsv(buttonColor .hue(),
- qMin(140, buttonColor .saturation()),
- qMax(180, buttonColor.value()));
- QColor shadowColor(0, 0, 0, 20);
-
- if (enabled) {
- // Drop shadow
- qreal shadowSize = qMax(1.0, penSize/2.0);
- QRectF shadowRect= br.adjusted(-2*shadowSize, -2*shadowSize,
- 2*shadowSize, 2*shadowSize);
- QRadialGradient shadowGradient(shadowRect.center().x(),
- shadowRect.center().y(), shadowRect.width()/2.0,
- shadowRect.center().x(), shadowRect.center().y());
- shadowGradient.setColorAt(qreal(0.91), QColor(0, 0, 0, 40));
- shadowGradient.setColorAt(qreal(1.0), Qt::transparent);
- p->setBrush(shadowGradient);
- p->setPen(Qt::NoPen);
- p->translate(shadowSize, shadowSize);
- p->drawEllipse(shadowRect);
- p->translate(-shadowSize, -shadowSize);
-
- // Main gradient
- QRadialGradient gradient(br.center().x() - br.width()/3, dy,
- br.width()*1.3, br.center().x(),
- br.center().y() - br.height()/2);
- gradient.setColorAt(0, buttonColor.lighter(110));
- gradient.setColorAt(qreal(0.5), buttonColor);
- gradient.setColorAt(qreal(0.501), buttonColor.darker(102));
- gradient.setColorAt(1, buttonColor.darker(115));
- p->setBrush(gradient);
- } else {
- p->setBrush(Qt::NoBrush);
- }
-
- p->setPen(QPen(buttonColor.darker(280)));
- p->drawEllipse(br);
- p->setBrush(Qt::NoBrush);
- p->setPen(buttonColor.lighter(110));
- p->drawEllipse(br.adjusted(1, 1, -1, -1));
-
- if (option->state & QStyle::State_HasFocus) {
- QColor highlight = pal.highlight().color();
- highlight.setHsv(highlight.hue(),
- qMin(160, highlight.saturation()),
- qMax(230, highlight.value()));
- highlight.setAlpha(127);
- p->setPen(QPen(highlight, 2.0));
- p->setBrush(Qt::NoBrush);
- p->drawEllipse(br.adjusted(-1, -1, 1, 1));
- }
-
- END_STYLE_PIXMAPCACHE
-
- QPointF dp = calcRadialPos(option, qreal(0.70));
- buttonColor = buttonColor.lighter(104);
- buttonColor.setAlphaF(qreal(0.8));
- const qreal ds = r/qreal(7.0);
- QRectF dialRect(dp.x() - ds, dp.y() - ds, 2*ds, 2*ds);
- QRadialGradient dialGradient(dialRect.center().x() + dialRect.width()/2,
- dialRect.center().y() + dialRect.width(),
- dialRect.width()*2,
- dialRect.center().x(), dialRect.center().y());
- dialGradient.setColorAt(1, buttonColor.darker(140));
- dialGradient.setColorAt(qreal(0.4), buttonColor.darker(120));
- dialGradient.setColorAt(0, buttonColor.darker(110));
- if (penSize > 3.0) {
- painter->setPen(QPen(QColor(0, 0, 0, 25), penSize));
- painter->drawLine(calcRadialPos(option, qreal(0.90)), calcRadialPos(option, qreal(0.96)));
- }
-
- painter->setBrush(dialGradient);
- painter->setPen(QColor(255, 255, 255, 150));
- painter->drawEllipse(dialRect.adjusted(-1, -1, 1, 1));
- painter->setPen(QColor(0, 0, 0, 80));
- painter->drawEllipse(dialRect);
- painter->restore();
-}
-#endif //QT_NO_DIAL
-
-void drawBorderPixmap(const QPixmap &pixmap, QPainter *painter, const QRect &rect,
- int left, int top, int right,
- int bottom)
-{
- QSize size = pixmap.size();
- //painter->setRenderHint(QPainter::SmoothPixmapTransform);
-
- //top
- if (top > 0) {
- painter->drawPixmap(QRect(rect.left() + left, rect.top(), rect.width() -right - left, top), pixmap,
- QRect(left, 0, size.width() -right - left, top));
-
- //top-left
- if(left > 0)
- painter->drawPixmap(QRect(rect.left(), rect.top(), left, top), pixmap,
- QRect(0, 0, left, top));
-
- //top-right
- if (right > 0)
- painter->drawPixmap(QRect(rect.left() + rect.width() - right, rect.top(), right, top), pixmap,
- QRect(size.width() - right, 0, right, top));
- }
-
- //left
- if (left > 0)
- painter->drawPixmap(QRect(rect.left(), rect.top()+top, left, rect.height() - top - bottom), pixmap,
- QRect(0, top, left, size.height() - bottom - top));
-
- //center
- painter->drawPixmap(QRect(rect.left() + left, rect.top()+top, rect.width() -right - left,
- rect.height() - bottom - top), pixmap,
- QRect(left, top, size.width() -right -left,
- size.height() - bottom - top));
- //right
- if (right > 0)
- painter->drawPixmap(QRect(rect.left() +rect.width() - right, rect.top()+top, right, rect.height() - top - bottom), pixmap,
- QRect(size.width() - right, top, right, size.height() - bottom - top));
-
- //bottom
- if (bottom > 0) {
- painter->drawPixmap(QRect(rect.left() +left, rect.top() + rect.height() - bottom,
- rect.width() - right - left, bottom), pixmap,
- QRect(left, size.height() - bottom,
- size.width() - right - left, bottom));
- //bottom-left
- if (left > 0)
- painter->drawPixmap(QRect(rect.left(), rect.top() + rect.height() - bottom, left, bottom), pixmap,
- QRect(0, size.height() - bottom, left, bottom));
-
- //bottom-right
- if (right > 0)
- painter->drawPixmap(QRect(rect.left() + rect.width() - right, rect.top() + rect.height() - bottom, right, bottom), pixmap,
- QRect(size.width() - right, size.height() - bottom, right, bottom));
-
- }
-}
-}
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstylehelper_p.h b/src/gui/styles/qstylehelper_p.h
deleted file mode 100644
index 6aeb71c103..0000000000
--- a/src/gui/styles/qstylehelper_p.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qglobal.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qpolygon.h>
-#include <QtCore/qstringbuilder.h>
-
-#ifndef QSTYLEHELPER_P_H
-#define QSTYLEHELPER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <private/qhexstring_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPainter;
-class QPixmap;
-class QStyleOptionSlider;
-class QStyleOption;
-
-namespace QStyleHelper
-{
- QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size);
- qreal dpiScaled(qreal value);
-#ifndef QT_NO_DIAL
- qreal angle(const QPointF &p1, const QPointF &p2);
- QPolygonF calcLines(const QStyleOptionSlider *dial);
- int calcBigLineSize(int radius);
- void drawDial(const QStyleOptionSlider *dial, QPainter *painter);
-#endif //QT_NO_DIAL
- void drawBorderPixmap(const QPixmap &pixmap, QPainter *painter, const QRect &rect,
- int left = 0, int top = 0, int right = 0,
- int bottom = 0);
-}
-
-
-QT_END_NAMESPACE
-
-#endif // QSTYLEHELPER_P_H
diff --git a/src/gui/styles/qstyleoption.cpp b/src/gui/styles/qstyleoption.cpp
deleted file mode 100644
index ee8e177546..0000000000
--- a/src/gui/styles/qstyleoption.cpp
+++ /dev/null
@@ -1,5508 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstyleoption.h"
-#include "qapplication.h"
-#ifdef Q_WS_MAC
-# include "private/qt_mac_p.h"
-# include "qmacstyle_mac.h"
-#endif
-#include <qdebug.h>
-#include <QtCore/qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QStyleOption
- \brief The QStyleOption class stores the parameters used by QStyle functions.
-
- \ingroup appearance
-
- QStyleOption and its subclasses contain all the information that
- QStyle functions need to draw a graphical element.
-
- For performance reasons, there are few member functions and the
- access to the member variables is direct (i.e., using the \c . or
- \c -> operator). This low-level feel makes the structures
- straightforward to use and emphasizes that these are simply
- parameters used by the style functions.
-
- The caller of a QStyle function usually creates QStyleOption
- objects on the stack. This combined with Qt's extensive use of
- \l{implicit sharing} for types such as QString, QPalette, and
- QColor ensures that no memory allocation needlessly takes place.
-
- The following code snippet shows how to use a specific
- QStyleOption subclass to paint a push button:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 0
-
- In our example, the control is a QStyle::CE_PushButton, and
- according to the QStyle::drawControl() documentation the
- corresponding class is QStyleOptionButton.
-
- When reimplementing QStyle functions that take a QStyleOption
- parameter, you often need to cast the QStyleOption to a subclass.
- For safety, you can use qstyleoption_cast() to ensure that the
- pointer type is correct. For example:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 4
-
- The qstyleoption_cast() function will return 0 if the object to
- which \c option points is not of the correct type.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyle, QStylePainter
-*/
-
-/*!
- \enum QStyleOption::OptionType
-
- This enum is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \value SO_Button \l QStyleOptionButton
- \value SO_ComboBox \l QStyleOptionComboBox
- \value SO_Complex \l QStyleOptionComplex
- \value SO_Default QStyleOption
- \value SO_DockWidget \l QStyleOptionDockWidget
- \value SO_FocusRect \l QStyleOptionFocusRect
- \value SO_Frame \l QStyleOptionFrame \l QStyleOptionFrameV2
- \value SO_GraphicsItem \l QStyleOptionGraphicsItem
- \value SO_GroupBox \l QStyleOptionGroupBox
- \value SO_Header \l QStyleOptionHeader
- \value SO_MenuItem \l QStyleOptionMenuItem
- \value SO_ProgressBar \l QStyleOptionProgressBar \l QStyleOptionProgressBarV2
- \value SO_RubberBand \l QStyleOptionRubberBand
- \value SO_SizeGrip \l QStyleOptionSizeGrip
- \value SO_Slider \l QStyleOptionSlider
- \value SO_SpinBox \l QStyleOptionSpinBox
- \value SO_Tab \l QStyleOptionTab
- \value SO_TabBarBase \l QStyleOptionTabBarBase
- \value SO_TabWidgetFrame \l QStyleOptionTabWidgetFrame
- \value SO_TitleBar \l QStyleOptionTitleBar
- \value SO_ToolBar \l QStyleOptionToolBar
- \value SO_ToolBox \l QStyleOptionToolBox
- \value SO_ToolButton \l QStyleOptionToolButton
- \value SO_ViewItem \l QStyleOptionViewItem (used in Interviews)
-
- The following values are used for custom controls:
-
- \value SO_CustomBase Reserved for custom QStyleOptions;
- all custom controls values must be above this value
- \value SO_ComplexCustomBase Reserved for custom QStyleOptions;
- all custom complex controls values must be above this value
-
- Some style options are defined for various Qt3Support controls:
-
- \value SO_Q3DockWindow \l QStyleOptionQ3DockWindow
- \value SO_Q3ListView \l QStyleOptionQ3ListView
- \value SO_Q3ListViewItem \l QStyleOptionQ3ListViewItem
-
- \sa type
-*/
-
-/*!
- Constructs a QStyleOption with the specified \a version and \a
- type.
-
- The version has no special meaning for QStyleOption; it can be
- used by subclasses to distinguish between different version of
- the same option type.
-
- The \l state member variable is initialized to
- QStyle::State_None.
-
- \sa version, type
-*/
-
-QStyleOption::QStyleOption(int version, int type)
- : version(version), type(type), state(QStyle::State_None),
- direction(QApplication::layoutDirection()), fontMetrics(QFont())
-{
-}
-
-
-/*!
- Destroys this style option object.
-*/
-QStyleOption::~QStyleOption()
-{
-}
-
-/*!
- \fn void QStyleOption::initFrom(const QWidget *widget)
- \since 4.1
-
- Initializes the \l state, \l direction, \l rect, \l palette, and
- \l fontMetrics member variables based on the specified \a widget.
-
- This is a convenience function; the member variables can also be
- initialized manually.
-
- \sa QWidget::layoutDirection(), QWidget::rect(),
- QWidget::palette(), QWidget::fontMetrics()
-*/
-
-/*!
- \obsolete
-
- Use initFrom(\a widget) instead.
-*/
-void QStyleOption::init(const QWidget *widget)
-{
- QWidget *window = widget->window();
- state = QStyle::State_None;
- if (widget->isEnabled())
- state |= QStyle::State_Enabled;
- if (widget->hasFocus())
- state |= QStyle::State_HasFocus;
- if (window->testAttribute(Qt::WA_KeyboardFocusChange))
- state |= QStyle::State_KeyboardFocusChange;
- if (widget->underMouse())
- state |= QStyle::State_MouseOver;
- if (window->isActiveWindow())
- state |= QStyle::State_Active;
- if (widget->isWindow())
- state |= QStyle::State_Window;
-#ifdef Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QWidget *w); //qwidget_mac.cpp
- if (!(state & QStyle::State_Active) && !qt_mac_can_clickThrough(widget))
- state &= ~QStyle::State_Enabled;
-
- switch (QMacStyle::widgetSizePolicy(widget)) {
- case QMacStyle::SizeSmall:
- state |= QStyle::State_Small;
- break;
- case QMacStyle::SizeMini:
- state |= QStyle::State_Mini;
- break;
- default:
- ;
- }
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- if (widget->hasEditFocus())
- state |= QStyle::State_HasEditFocus;
-#endif
-
- direction = widget->layoutDirection();
- rect = widget->rect();
- palette = widget->palette();
- fontMetrics = widget->fontMetrics();
-}
-
-/*!
- Constructs a copy of \a other.
-*/
-QStyleOption::QStyleOption(const QStyleOption &other)
- : version(Version), type(Type), state(other.state),
- direction(other.direction), rect(other.rect), fontMetrics(other.fontMetrics),
- palette(other.palette)
-{
-}
-
-/*!
- Assign \a other to this QStyleOption.
-*/
-QStyleOption &QStyleOption::operator=(const QStyleOption &other)
-{
- state = other.state;
- direction = other.direction;
- rect = other.rect;
- fontMetrics = other.fontMetrics;
- palette = other.palette;
- return *this;
-}
-
-/*!
- \enum QStyleOption::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Default} for
- this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOption::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOption::palette
- \brief the palette that should be used when painting the control
-
- By default, the application's default palette is used.
-
- \sa initFrom()
-*/
-
-/*!
- \variable QStyleOption::direction
- \brief the text layout direction that should be used when drawing text in the control
-
- By default, the layout direction is Qt::LeftToRight.
-
- \sa initFrom()
-*/
-
-/*!
- \variable QStyleOption::fontMetrics
- \brief the font metrics that should be used when drawing text in the control
-
- By default, the application's default font is used.
-
- \sa initFrom()
-*/
-
-/*!
- \variable QStyleOption::rect
- \brief the area that should be used for various calculations and painting
-
- This can have different meanings for different types of elements.
- For example, for a \l QStyle::CE_PushButton element it would be
- the rectangle for the entire button, while for a \l
- QStyle::CE_PushButtonLabel element it would be just the area for
- the push button label.
-
- The default value is a null rectangle, i.e. a rectangle with both
- the width and the height set to 0.
-
- \sa initFrom()
-*/
-
-/*!
- \variable QStyleOption::state
- \brief the style flags that are used when drawing the control
-
- The default value is QStyle::State_None.
-
- \sa initFrom(), QStyle::drawPrimitive(), QStyle::drawControl(),
- QStyle::drawComplexControl(), QStyle::State
-*/
-
-/*!
- \variable QStyleOption::type
- \brief the option type of the style option
-
- The default value is SO_Default.
-
- \sa OptionType
-*/
-
-/*!
- \variable QStyleOption::version
- \brief the version of the style option
-
- This value can be used by subclasses to implement extensions
- without breaking compatibility. If you use the qstyleoption_cast()
- function, you normally do not need to check it.
-
- The default value is 1.
-*/
-
-/*!
- \class QStyleOptionFocusRect
- \brief The QStyleOptionFocusRect class is used to describe the
- parameters for drawing a focus rectangle with QStyle.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionFocusRect, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionFocusRect::QStyleOptionFocusRect()
- : QStyleOption(Version, SO_FocusRect)
-{
- state |= QStyle::State_KeyboardFocusChange; // assume we had one, will be corrected in initFrom()
-}
-
-/*!
- \internal
-*/
-QStyleOptionFocusRect::QStyleOptionFocusRect(int version)
- : QStyleOption(version, SO_FocusRect)
-{
- state |= QStyle::State_KeyboardFocusChange; // assume we had one, will be corrected in initFrom()
-}
-
-/*!
- \enum QStyleOptionFocusRect::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_FocusRect} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionFocusRect::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \fn QStyleOptionFocusRect::QStyleOptionFocusRect(const QStyleOptionFocusRect &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \variable QStyleOptionFocusRect::backgroundColor
- \brief the background color on which the focus rectangle is being drawn
-
- The default value is an invalid color with the RGB value (0, 0,
- 0). An invalid color is a color that is not properly set up for
- the underlying window system.
-*/
-
-/*!
- \class QStyleOptionFrame
- \brief The QStyleOptionFrame class is used to describe the
- parameters for drawing a frame.
-
- QStyleOptionFrame is used for drawing several built-in Qt widgets,
- including QFrame, QGroupBox, QLineEdit, and QMenu. Note that to
- describe the parameters necessary for drawing a frame in Qt 4.1 or
- above, you must use the QStyleOptionFrameV2 subclass.
-
- An instance of the QStyleOptionFrame class has
- \l{QStyleOption::type} {type} SO_Frame and \l{QStyleOption::version}
- {version} 1.
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles. The
- version is used by QStyleOption subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast(),
- you normally do not need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionFrame and QStyleOptionFrameV2.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionFrameV2, QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionFrame, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionFrame::QStyleOptionFrame()
- : QStyleOption(Version, SO_Frame), lineWidth(0), midLineWidth(0)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionFrame::QStyleOptionFrame(int version)
- : QStyleOption(version, SO_Frame), lineWidth(0), midLineWidth(0)
-{
-}
-
-/*!
- \fn QStyleOptionFrame::QStyleOptionFrame(const QStyleOptionFrame &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionFrame::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Frame} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionFrame::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionFrame::lineWidth
- \brief the line width for drawing the frame
-
- The default value is 0.
-
- \sa QFrame::lineWidth
-*/
-
-/*!
- \variable QStyleOptionFrame::midLineWidth
- \brief the mid-line width for drawing the frame
-
- This is usually used in drawing sunken or raised frames.
-
- The default value is 0.
-
- \sa QFrame::midLineWidth
-*/
-
-/*!
- \class QStyleOptionFrameV2
- \brief The QStyleOptionFrameV2 class is used to describe the
- parameters necessary for drawing a frame in Qt 4.1 or above.
-
- \since 4.1
-
- QStyleOptionFrameV2 inherits QStyleOptionFrame which is used for
- drawing several built-in Qt widgets, including QFrame, QGroupBox,
- QLineEdit, and QMenu.
-
- An instance of the QStyleOptionFrameV2 class has
- \l{QStyleOption::type} {type} SO_Frame and
- \l{QStyleOption::version} {version} 2. The type is used
- internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles. The
- version is used by QStyleOption subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast(),
- you normally do not need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionFrame and QStyleOptionFrameV2. One way to achieve this
- is to use the QStyleOptionFrameV2 copy constructor. For example:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 1
-
- In the example above: If the \c frameOption's version is 1, \l
- FrameFeature is set to \l None for \c frameOptionV2. If \c
- frameOption's version is 2, the constructor will simply copy the
- \c frameOption's \l FrameFeature value.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionFrame, QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionFrameV2 object.
-*/
-QStyleOptionFrameV2::QStyleOptionFrameV2()
- : QStyleOptionFrame(Version), features(None)
-{
-}
-
-/*!
- \fn QStyleOptionFrameV2::QStyleOptionFrameV2(const QStyleOptionFrameV2 &other)
-
- Constructs a QStyleOptionFrameV2 copy of the \a other style option.
-*/
-
-/*!
- \internal
-*/
-QStyleOptionFrameV2::QStyleOptionFrameV2(int version)
- : QStyleOptionFrame(version), features(None)
-{
-}
-
-/*!
- Constructs a QStyleOptionFrameV2 copy of the \a other style option
- which can be either of the QStyleOptionFrameV2 or
- QStyleOptionFrame types.
-
- If the \a other style option's version is 1, the new style option's \l
- FrameFeature value is set to \l QStyleOptionFrameV2::None. If its
- version is 2, its \l FrameFeature value is simply copied to the
- new style option.
-
- \sa version
-*/
-QStyleOptionFrameV2::QStyleOptionFrameV2(const QStyleOptionFrame &other)
-{
- QStyleOptionFrame::operator=(other);
-
- const QStyleOptionFrameV2 *f2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(&other);
- features = f2 ? f2->features : FrameFeatures(QStyleOptionFrameV2::None);
- version = Version;
-}
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionFrameV2 or
- QStyleOptionFrame types.
-
- If the \a{other} style option's version is 1, this style option's
- \l FrameFeature value is set to \l QStyleOptionFrameV2::None. If
- its version is 2, its \l FrameFeature value is simply copied to
- this style option.
-*/
-QStyleOptionFrameV2 &QStyleOptionFrameV2::operator=(const QStyleOptionFrame &other)
-{
- QStyleOptionFrame::operator=(other);
-
- const QStyleOptionFrameV2 *f2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(&other);
- features = f2 ? f2->features : FrameFeatures(QStyleOptionFrameV2::None);
- version = Version;
- return *this;
-}
-
-/*!
- \enum QStyleOptionFrameV2::FrameFeature
-
- This enum describes the different types of features a frame can have.
-
- \value None Indicates a normal frame.
- \value Flat Indicates a flat frame.
-*/
-
-/*!
- \variable QStyleOptionFrameV2::features
- \brief a bitwise OR of the features that describe this frame.
-
- \sa FrameFeature
-*/
-
-/*!
- \enum QStyleOptionFrameV2::StyleOptionVersion
-
- This enum is used to hold information about the version of the
- style option, and is defined for each QStyleOption subclass.
-
- \value Version 2
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \class QStyleOptionFrameV3
- \brief The QStyleOptionFrameV3 class is used to describe the
- parameters necessary for drawing a frame in Qt 4.1 or above.
-
- \since 4.5
-
- QStyleOptionFrameV3 inherits QStyleOptionFrameV2
-
- An instance of the QStyleOptionFrameV3 class has
- \l{QStyleOption::type} {type} SO_Frame and
- \l{QStyleOption::version} {version} 3. The type is used
- internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles. The
- version is used by QStyleOption subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast(),
- you normally do not need to check it.
-
- \sa QStyleOptionFrameV2, QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionFrameV3 object.
-*/
-QStyleOptionFrameV3::QStyleOptionFrameV3()
- : QStyleOptionFrameV2(Version), frameShape(QFrame::NoFrame), unused(0)
-{
-}
-
-/*!
- \fn QStyleOptionFrameV3::QStyleOptionFrameV3(const QStyleOptionFrameV3 &other)
-
- Constructs a QStyleOptionFrameV3 copy of the \a other style option.
-*/
-
-/*!
- \internal
-*/
-QStyleOptionFrameV3::QStyleOptionFrameV3(int version)
- : QStyleOptionFrameV2(version), frameShape(QFrame::NoFrame), unused(0)
-{
-}
-
-/*!
- Constructs a QStyleOptionFrameV3 copy of the \a other style option
- which can be either of the QStyleOptionFrameV3 or
- QStyleOptionFrame types.
-
- If the \a other style option's version is 1, the new style
- option's \l FrameFeature value is set to
- \l{QStyleOptionFrameV2::None}. If its version is 2 or lower,
- \l{QStyleOptionFrameV3::frameShape} value is QFrame::NoFrame
-
- \sa version
-*/
-QStyleOptionFrameV3::QStyleOptionFrameV3(const QStyleOptionFrame &other)
-{
- operator=(other);
-}
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionFrameV3,
- QStyleOptionFrameV2 or QStyleOptionFrame types.
-
- If the \a other style option's version is 1, the new style
- option's \l FrameFeature value is set to
- \l{QStyleOptionFrameV2::None}. If its version is 2 or lower,
- \l{QStyleOptionFrameV3::frameShape} value is QFrame::NoFrame
-*/
-QStyleOptionFrameV3 &QStyleOptionFrameV3::operator=(const QStyleOptionFrame &other)
-{
- QStyleOptionFrameV2::operator=(other);
-
- const QStyleOptionFrameV3 *f3 = qstyleoption_cast<const QStyleOptionFrameV3 *>(&other);
- frameShape = f3 ? f3->frameShape : QFrame::NoFrame;
- version = Version;
- return *this;
-}
-
-
-/*!
- \variable QStyleOptionFrameV3::frameShape
- \brief This property holds the frame shape value of the frame.
-
- \sa QFrame::frameShape
-*/
-
-/*!
- \enum QStyleOptionFrameV3::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 3
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \class QStyleOptionViewItemV2
- \brief The QStyleOptionViewItemV2 class is used to describe the
- parameters necessary for drawing a frame in Qt 4.2 or above.
- \since 4.2
-
- QStyleOptionViewItemV2 inherits QStyleOptionViewItem.
-
- An instance of the QStyleOptionViewItemV2 class has
- \l{QStyleOption::type} {type} SO_ViewItem and
- \l{QStyleOption::version} {version} 2. The type is used internally
- by QStyleOption, its subclasses, and qstyleoption_cast() to
- determine the type of style option. In general you do not need to
- worry about this unless you want to create your own QStyleOption
- subclass and your own styles. The version is used by QStyleOption
- subclasses to implement extensions without breaking
- compatibility. If you use qstyleoption_cast(), you normally do not
- need to check it.
-
- See QStyleOptionFrameV2's detailed description for a discussion
- of how to handle "V2" classes.
-
- \sa QStyleOptionViewItem, QStyleOption
-*/
-
-/*!
- \enum QStyleOptionViewItemV2::StyleOptionVersion
-
- This enum is used to hold information about the version of the
- style option, and is defined for each QStyleOption subclass.
-
- \value Version 2
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionViewItemV2::features
- \brief a bitwise OR of the features that describe this view item
-
- \sa ViewItemFeature
-*/
-
-/*!
- Constructs a QStyleOptionViewItemV2 object.
-*/
-QStyleOptionViewItemV2::QStyleOptionViewItemV2()
- : QStyleOptionViewItem(Version), features(None)
-{
-}
-
-/*!
- \fn QStyleOptionViewItemV2::QStyleOptionViewItemV2(const QStyleOptionViewItemV2 &other)
-
- Constructs a copy of \a other.
-*/
-
-/*!
- Constructs a QStyleOptionViewItemV2 copy of the \a other style option
- which can be either of the QStyleOptionViewItemV2 or
- QStyleOptionViewItem types.
-
- If the \a other style option's version is 1, the new style option's \l
- ViewItemFeature value is set to \l QStyleOptionViewItemV2::None. If its
- version is 2, its \l ViewItemFeature value is simply copied to the
- new style option.
-
- \sa version
-*/
-QStyleOptionViewItemV2::QStyleOptionViewItemV2(const QStyleOptionViewItem &other)
- : QStyleOptionViewItem(Version)
-{
- (void)QStyleOptionViewItemV2::operator=(other);
-}
-
-/*!
- \internal
-*/
-QStyleOptionViewItemV2::QStyleOptionViewItemV2(int version)
- : QStyleOptionViewItem(version)
-{
-
-}
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionViewItemV2 or
- QStyleOptionViewItem types.
-
- If the \a{other} style option's version is 1, this style option's
- \l ViewItemFeature value is set to \l QStyleOptionViewItemV2::None.
- If its version is 2, its \l ViewItemFeature value is simply copied
- to this style option.
-*/
-QStyleOptionViewItemV2 &QStyleOptionViewItemV2::operator=(const QStyleOptionViewItem &other)
-{
- QStyleOptionViewItem::operator=(other);
- const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(&other);
- features = v2 ? v2->features : ViewItemFeatures(QStyleOptionViewItemV2::None);
- return *this;
-}
-
-/*!
- \enum QStyleOptionViewItemV2::ViewItemFeature
-
- This enum describes the different types of features an item can have.
-
- \value None Indicates a normal item.
- \value WrapText Indicates an item with wrapped text.
- \value Alternate Indicates that the item's background is rendered using alternateBase.
- \value HasCheckIndicator Indicates that the item has a check state indicator.
- \value HasDisplay Indicates that the item has a display role.
- \value HasDecoration Indicates that the item has a decoration role.
-*/
-
-
-
-/*!
- \class QStyleOptionViewItemV3
- \brief The QStyleOptionViewItemV3 class is used to describe the
- parameters necessary for drawing a frame in Qt 4.3 or above.
- \since 4.3
-
- QStyleOptionViewItemV3 inherits QStyleOptionViewItem.
-
- An instance of the QStyleOptionViewItemV3 class has
- \l{QStyleOption::type} {type} SO_ViewItem and \l{QStyleOption::version}
- {version} 3. The type is used internally by QStyleOption, its subclasses,
- and qstyleoption_cast() to determine the type of style option. In general
- you do not need to worry about this unless you want to create your own
- QStyleOption subclass and your own styles. The version is used by
- QStyleOption subclasses to implement extensions without breaking
- compatibility. If you use qstyleoption_cast(), you normally do not need to
- check it.
-
- See QStyleOptionFrameV2's detailed description for a discussion
- of how to handle "V2" and other versioned classes.
-
- \sa QStyleOptionViewItem, QStyleOption
-*/
-
-/*!
- \enum QStyleOptionViewItemV3::StyleOptionVersion
-
- This enum is used to hold information about the version of the
- style option, and is defined for each QStyleOption subclass.
-
- \value Version 3
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- Constructs a QStyleOptionViewItemV3 object.
-*/
-QStyleOptionViewItemV3::QStyleOptionViewItemV3()
- : QStyleOptionViewItemV2(Version), widget(0)
-{
-}
-
-/*!
- Constructs a copy of \a other.
-*/
-QStyleOptionViewItemV3::QStyleOptionViewItemV3(const QStyleOptionViewItem &other)
- : QStyleOptionViewItemV2(Version), widget(0)
-{
- (void)QStyleOptionViewItemV3::operator=(other);
-}
-
-/*!
- \fn QStyleOptionViewItemV3::QStyleOptionViewItemV3(const QStyleOptionViewItemV3 &other)
-
- Constructs a copy of \a other.
-*/
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be an instance of the QStyleOptionViewItemV2,
- QStyleOptionViewItemV3 or QStyleOptionViewItem types.
-*/
-QStyleOptionViewItemV3 &QStyleOptionViewItemV3::operator = (const QStyleOptionViewItem &other)
-{
- QStyleOptionViewItemV2::operator=(other);
- const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3*>(&other);
- locale = v3 ? v3->locale : QLocale();
- widget = v3 ? v3->widget : 0;
- return *this;
-}
-
-/*!
- \internal
-*/
-QStyleOptionViewItemV3::QStyleOptionViewItemV3(int version)
- : QStyleOptionViewItemV2(version), widget(0)
-{
-}
-
-#ifndef QT_NO_ITEMVIEWS
-
-/*!
- \class QStyleOptionViewItemV4
- \brief The QStyleOptionViewItemV4 class is used to describe the
- parameters necessary for drawing a frame in Qt 4.4 or above.
- \since 4.4
-
- QStyleOptionViewItemV4 inherits QStyleOptionViewItemV3.
-
- An instance of the QStyleOptionViewItemV4 class has
- \l{QStyleOption::type} {type} SO_ViewItem and
- \l{QStyleOption::version} {version} 4. The type is used internally
- by QStyleOption, its subclasses, and qstyleoption_cast() to
- determine the type of style option. In general you do not need to
- worry about this unless you want to create your own QStyleOption
- subclass and your own styles. The version is used by QStyleOption
- subclasses to implement extensions without breaking
- compatibility. If you use qstyleoption_cast(), you normally do not
- need to check it.
-
- See QStyleOptionViewItemV3's detailed description for a discussion
- of how to handle "V3" classes.
-
- \sa QStyleOptionViewItem, QStyleOption
-*/
-
-/*!
- \variable QStyleOptionViewItemV4::index
-
- The model index that is to be drawn.
-*/
-
-/*!
- \variable QStyleOptionViewItemV4::checkState
-
- If this view item is checkable, i.e.,
- ViewItemFeature::HasCheckIndicator is true, \c checkState is true
- if the item is checked; otherwise, it is false.
-
-*/
-
-/*!
- \variable QStyleOptionViewItemV4::icon
-
- The icon (if any) to be drawn in the view item.
-*/
-
-
-/*!
- \variable QStyleOptionViewItemV4::text
-
- The text (if any) to be drawn in the view item.
-*/
-
-/*!
- \variable QStyleOptionViewItemV4::backgroundBrush
-
- The QBrush that should be used to paint the view items
- background.
-*/
-
-/*!
- \variable QStyleOptionViewItemV4::viewItemPosition
-
- Gives the position of this view item relative to other items. See
- the \l{QStyleOptionViewItemV4::}{ViewItemPosition} enum for the
- details.
-*/
-
-/*!
- \enum QStyleOptionViewItemV4::StyleOptionVersion
-
- This enum is used to hold information about the version of the
- style option, and is defined for each QStyleOption subclass.
-
- \value Version 4
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \enum QStyleOptionViewItemV4::ViewItemPosition
-
- This enum is used to represent the placement of the item on
- a row. This can be used to draw items differently depending
- on their placement, for example by putting rounded edges at
- the beginning and end, and straight edges in between.
-
- \value Invalid The ViewItemPosition is unknown and should be
- disregarded.
- \value Beginning The item appears at the beginning of the row.
- \value Middle The item appears in the middle of the row.
- \value End The item appears at the end of the row.
- \value OnlyOne The item is the only one on the row, and is
- therefore both at the beginning and the end.
-*/
-
-
-/*!
- Constructs a QStyleOptionViewItemV4 object.
-*/
-QStyleOptionViewItemV4::QStyleOptionViewItemV4()
-: QStyleOptionViewItemV3(Version), checkState(Qt::Unchecked), viewItemPosition(QStyleOptionViewItemV4::Invalid)
-{
-}
-
-/*!
- \fn QStyleOptionViewItemV4::QStyleOptionViewItemV4(const QStyleOptionViewItemV4 &other)
-
- Constructs a copy of \a other.
-*/
-
-/*!
- Constructs a QStyleOptionViewItemV4 copy of the \a other style option
- which can be either of the QStyleOptionViewItemV3 or
- QStyleOptionViewItem types.
-
- \sa version
-*/
-QStyleOptionViewItemV4::QStyleOptionViewItemV4(const QStyleOptionViewItem &other)
- : QStyleOptionViewItemV3(Version)
-{
- (void)QStyleOptionViewItemV4::operator=(other);
-}
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionViewItemV3 or
- QStyleOptionViewItem types.
-*/
-QStyleOptionViewItemV4 &QStyleOptionViewItemV4::operator = (const QStyleOptionViewItem &other)
-{
- QStyleOptionViewItemV3::operator=(other);
- if (const QStyleOptionViewItemV4 *v4 = qstyleoption_cast<const QStyleOptionViewItemV4*>(&other)) {
- index = v4->index;
- checkState = v4->checkState;
- text = v4->text;
- viewItemPosition = v4->viewItemPosition;
- backgroundBrush = v4->backgroundBrush;
- icon = v4->icon;
- } else {
- viewItemPosition = QStyleOptionViewItemV4::Invalid;
- checkState = Qt::Unchecked;
- }
- return *this;
-}
-
-/*!
- \internal
-*/
-QStyleOptionViewItemV4::QStyleOptionViewItemV4(int version)
- : QStyleOptionViewItemV3(version)
-{
-}
-#endif // QT_NO_ITEMVIEWS
-
-/*!
- \class QStyleOptionGroupBox
- \brief The QStyleOptionGroupBox class describes the parameters for
- drawing a group box.
-
- \since 4.1
-
- QStyleOptionButton contains all the information that QStyle
- functions need the various graphical elements of a group box.
-
- It holds the lineWidth and the midLineWidth for drawing the panel,
- the group box's \l {text}{title} and the title's \l
- {textAlignment}{alignment} and \l {textColor}{color}.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionComplex, QGroupBox
-*/
-
-/*!
- \enum QStyleOptionGroupBox::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_GroupBox} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionGroupBox::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionGroupBox::lineWidth
- \brief the line width for drawing the panel
-
- The value of this variable is, currently, always 1.
-
- \sa QFrame::lineWidth
-*/
-
-/*!
- \variable QStyleOptionGroupBox::midLineWidth
- \brief the mid-line width for drawing the panel
-
- The mid-line width is usually used when drawing sunken or raised
- group box frames. The value of this variable is, currently, always 0.
-
- \sa QFrame::midLineWidth
-*/
-
-/*!
- \variable QStyleOptionGroupBox::text
- \brief the text of the group box
-
- The default value is an empty string.
-
- \sa QGroupBox::title
-*/
-
-/*!
- \variable QStyleOptionGroupBox::textAlignment
- \brief the alignment of the group box title
-
- The default value is Qt::AlignLeft.
-
- \sa QGroupBox::alignment
-*/
-
-/*!
- \variable QStyleOptionGroupBox::features
- \brief the features of the group box frame
-
- The frame is flat by default.
-
- \sa QStyleOptionFrameV2::FrameFeature
-*/
-
-/*!
- \variable QStyleOptionGroupBox::textColor
- \brief the color of the group box title
-
- The default value is an invalid color with the RGB value (0, 0,
- 0). An invalid color is a color that is not properly set up for
- the underlying window system.
-*/
-
-/*!
- Constructs a QStyleOptionGroupBox, initializing the members
- variables to their default values.
-*/
-QStyleOptionGroupBox::QStyleOptionGroupBox()
- : QStyleOptionComplex(Version, Type), features(QStyleOptionFrameV2::None),
- textAlignment(Qt::AlignLeft), lineWidth(0), midLineWidth(0)
-{
-}
-
-/*!
- \fn QStyleOptionGroupBox::QStyleOptionGroupBox(const QStyleOptionGroupBox &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \internal
-*/
-QStyleOptionGroupBox::QStyleOptionGroupBox(int version)
- : QStyleOptionComplex(version, Type), features(QStyleOptionFrameV2::None),
- textAlignment(Qt::AlignLeft), lineWidth(0), midLineWidth(0)
-{
-}
-
-/*!
- \class QStyleOptionHeader
- \brief The QStyleOptionHeader class is used to describe the
- parameters for drawing a header.
-
- QStyleOptionHeader contains all the information that QStyle
- functions need to draw the item views' header pane, header sort
- arrow, and header label.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionHeader, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionHeader::QStyleOptionHeader()
- : QStyleOption(QStyleOptionHeader::Version, SO_Header),
- section(0), textAlignment(Qt::AlignLeft), iconAlignment(Qt::AlignLeft),
- position(QStyleOptionHeader::Beginning),
- selectedPosition(QStyleOptionHeader::NotAdjacent), sortIndicator(None),
- orientation(Qt::Horizontal)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionHeader::QStyleOptionHeader(int version)
- : QStyleOption(version, SO_Header),
- section(0), textAlignment(Qt::AlignLeft), iconAlignment(Qt::AlignLeft),
- position(QStyleOptionHeader::Beginning),
- selectedPosition(QStyleOptionHeader::NotAdjacent), sortIndicator(None),
- orientation(Qt::Horizontal)
-{
-}
-
-/*!
- \variable QStyleOptionHeader::orientation
- \brief the header's orientation (horizontal or vertical)
-
- The default orientation is Qt::Horizontal
-*/
-
-/*!
- \fn QStyleOptionHeader::QStyleOptionHeader(const QStyleOptionHeader &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionHeader::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Header} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionHeader::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionHeader::section
- \brief which section of the header is being painted
-
- The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionHeader::text
- \brief the text of the header
-
- The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionHeader::textAlignment
- \brief the alignment flags for the text of the header
-
- The default value is Qt::AlignLeft.
-*/
-
-/*!
- \variable QStyleOptionHeader::icon
- \brief the icon of the header
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-*/
-
-/*!
- \variable QStyleOptionHeader::iconAlignment
- \brief the alignment flags for the icon of the header
-
- The default value is Qt::AlignLeft.
-*/
-
-/*!
- \variable QStyleOptionHeader::position
- \brief the section's position in relation to the other sections
-
- The default value is QStyleOptionHeader::Beginning.
-*/
-
-/*!
- \variable QStyleOptionHeader::selectedPosition
- \brief the section's position in relation to the selected section
-
- The default value is QStyleOptionHeader::NotAdjacent
-*/
-
-/*!
- \variable QStyleOptionHeader::sortIndicator
- \brief the direction the sort indicator should be drawn
-
- The default value is QStyleOptionHeader::None.
-*/
-
-/*!
- \enum QStyleOptionHeader::SectionPosition
-
- This enum lets you know where the section's position is in relation to the other sections.
-
- \value Beginning At the beginining of the header
- \value Middle In the middle of the header
- \value End At the end of the header
- \value OnlyOneSection Only one header section
-
- \sa position
-*/
-
-/*!
- \enum QStyleOptionHeader::SelectedPosition
-
- This enum lets you know where the section's position is in relation to the selected section.
-
- \value NotAdjacent Not adjacent to the selected section
- \value NextIsSelected The next section is selected
- \value PreviousIsSelected The previous section is selected
- \value NextAndPreviousAreSelected Both the next and previous section are selected
-
- \sa selectedPosition
-*/
-
-/*!
- \enum QStyleOptionHeader::SortIndicator
-
- Indicates which direction the sort indicator should be drawn
-
- \value None No sort indicator is needed
- \value SortUp Draw an up indicator
- \value SortDown Draw a down indicator
-
- \sa sortIndicator
-*/
-
-/*!
- \class QStyleOptionButton
- \brief The QStyleOptionButton class is used to describe the
- parameters for drawing buttons.
-
- QStyleOptionButton contains all the information that QStyle
- functions need to draw graphical elements like QPushButton,
- QCheckBox, and QRadioButton.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionToolButton
-*/
-
-/*!
- \enum QStyleOptionButton::ButtonFeature
-
- This enum describes the different types of features a push button can have.
-
- \value None Indicates a normal push button.
- \value Flat Indicates a flat push button.
- \value HasMenu Indicates that the button has a drop down menu.
- \value DefaultButton Indicates that the button is a default button.
- \value AutoDefaultButton Indicates that the button is an auto default button.
- \value CommandLinkButton Indicates that the button is a Windows Vista type command link.
-
- \sa features
-*/
-
-/*!
- Constructs a QStyleOptionButton, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionButton::QStyleOptionButton()
- : QStyleOption(QStyleOptionButton::Version, SO_Button), features(None)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionButton::QStyleOptionButton(int version)
- : QStyleOption(version, SO_Button), features(None)
-{
-}
-
-/*!
- \fn QStyleOptionButton::QStyleOptionButton(const QStyleOptionButton &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionButton::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Button} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionButton::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionButton::features
- \brief a bitwise OR of the features that describe this button
-
- \sa ButtonFeature
-*/
-
-/*!
- \variable QStyleOptionButton::text
- \brief the text of the button
-
- The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionButton::icon
- \brief the icon of the button
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-
- \sa iconSize
-*/
-
-/*!
- \variable QStyleOptionButton::iconSize
- \brief the size of the icon for the button
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-*/
-
-
-#ifndef QT_NO_TOOLBAR
-/*!
- \class QStyleOptionToolBar
- \brief The QStyleOptionToolBar class is used to describe the
- parameters for drawing a toolbar.
-
- \since 4.1
-
- QStyleOptionToolBar contains all the information that QStyle
- functions need to draw QToolBar.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- The QStyleOptionToolBar class holds the lineWidth and the
- midLineWidth for drawing the widget. It also stores information
- about which \l {toolBarArea}{area} the toolbar should be located
- in, whether it is movable or not, which position the toolbar line
- should have (positionOfLine), and the toolbar's position within
- the line (positionWithinLine).
-
- In addition, the class provides a couple of enums: The
- ToolBarFeature enum is used to describe whether a toolbar is
- movable or not, and the ToolBarPosition enum is used to describe
- the position of a toolbar line, as well as the toolbar's position
- within the line.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionToolBar, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionToolBar::QStyleOptionToolBar()
- : QStyleOption(Version, SO_ToolBar), positionOfLine(OnlyOne), positionWithinLine(OnlyOne),
- toolBarArea(Qt::TopToolBarArea), features(None), lineWidth(0), midLineWidth(0)
-{
-}
-
-/*!
- \fn QStyleOptionToolBar::QStyleOptionToolBar(const QStyleOptionToolBar &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \internal
-*/
-QStyleOptionToolBar::QStyleOptionToolBar(int version)
-: QStyleOption(version, SO_ToolBar), positionOfLine(OnlyOne), positionWithinLine(OnlyOne),
- toolBarArea(Qt::TopToolBarArea), features(None), lineWidth(0), midLineWidth(0)
-{
-
-}
-
-/*!
- \enum QStyleOptionToolBar::ToolBarPosition
-
- \image qstyleoptiontoolbar-position.png
-
- This enum is used to describe the position of a toolbar line, as
- well as the toolbar's position within the line.
-
- The order of the positions within a line starts at the top of a
- vertical line, and from the left within a horizontal line. The
- order of the positions for the lines is always from the the
- parent widget's boundary edges.
-
- \value Beginning The toolbar is located at the beginning of the line,
- or the toolbar line is the first of several lines. There can
- only be one toolbar (and only one line) with this position.
- \value Middle The toolbar is located in the middle of the line,
- or the toolbar line is in the middle of several lines. There can
- several toolbars (and lines) with this position.
- \value End The toolbar is located at the end of the line,
- or the toolbar line is the last of several lines. There can
- only be one toolbar (and only one line) with this position.
- \value OnlyOne There is only one toolbar or line. This is the default value
- of the positionOfLine and positionWithinLine variables.
-
- \sa positionWithinLine, positionOfLine
-*/
-
-/*!
- \enum QStyleOptionToolBar::ToolBarFeature
-
- This enum is used to describe whether a toolbar is movable or not.
-
- \value None The toolbar cannot be moved. The default value.
- \value Movable The toolbar is movable, and a handle will appear when
- holding the cursor over the toolbar's boundary.
-
- \sa features, QToolBar::isMovable()
-*/
-
-/*!
- \variable QStyleOptionToolBar::positionOfLine
-
- This variable holds the position of the toolbar line.
-
- The default value is QStyleOptionToolBar::OnlyOne.
-*/
-
-/*!
- \variable QStyleOptionToolBar::positionWithinLine
-
- This variable holds the position of the toolbar within a line.
-
- The default value is QStyleOptionToolBar::OnlyOne.
-*/
-
-/*!
- \variable QStyleOptionToolBar::toolBarArea
-
- This variable holds the location for drawing the toolbar.
-
- The default value is Qt::TopToolBarArea.
-
- \sa Qt::ToolBarArea
-*/
-
-/*!
- \variable QStyleOptionToolBar::features
-
- This variable holds whether the toolbar is movable or not.
-
- The default value is \l None.
-*/
-
-/*!
- \variable QStyleOptionToolBar::lineWidth
-
- This variable holds the line width for drawing the toolbar.
-
- The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionToolBar::midLineWidth
-
- This variable holds the mid-line width for drawing the toolbar.
-
- The default value is 0.
-*/
-
-/*!
- \enum QStyleOptionToolBar::StyleOptionType
-
- This enum is used to hold information about the type of the style
- option, and is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ToolBar} for
- this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionToolBar::StyleOptionVersion
-
- This enum is used to hold information about the version of the
- style option, and is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-#endif
-
-#ifndef QT_NO_TABBAR
-/*!
- \class QStyleOptionTab
- \brief The QStyleOptionTab class is used to describe the
- parameters for drawing a tab bar.
-
- The QStyleOptionTab class is used for drawing several built-in Qt
- widgets including \l QTabBar and the panel for \l QTabWidget. Note
- that to describe the parameters necessary for drawing a frame in
- Qt 4.1 or above, you must use the QStyleOptionFrameV2 subclass.
-
- An instance of the QStyleOptiontabV2 class has
- \l{QStyleOption::type} {type} \l SO_Tab and
- \l{QStyleOption::version} {version} 1. The type is used internally
- by QStyleOption, its subclasses, and qstyleoption_cast() to
- determine the type of style option. In general you do not need to
- worry about this unless you want to create your own QStyleOption
- subclass and your own styles. The version is used by QStyleOption
- subclasses to implement extensions without breaking
- compatibility. If you use qstyleoption_cast(), you normally do not
- need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionTab and QStyleOptionTabV2.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionTabV2, QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionTab object, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionTab::QStyleOptionTab()
- : QStyleOption(QStyleOptionTab::Version, SO_Tab),
- shape(QTabBar::RoundedNorth),
- row(0),
- position(Beginning),
- selectedPosition(NotAdjacent), cornerWidgets(QStyleOptionTab::NoCornerWidgets)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionTab::QStyleOptionTab(int version)
- : QStyleOption(version, SO_Tab),
- shape(QTabBar::RoundedNorth),
- row(0),
- position(Beginning),
- selectedPosition(NotAdjacent), cornerWidgets(QStyleOptionTab::NoCornerWidgets)
-{
-}
-
-/*!
- \fn QStyleOptionTab::QStyleOptionTab(const QStyleOptionTab &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionTab::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Tab} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionTab::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \enum QStyleOptionTab::TabPosition
-
- This enum describes the position of the tab.
-
- \value Beginning The tab is the first tab in the tab bar.
- \value Middle The tab is neither the first nor the last tab in the tab bar.
- \value End The tab is the last tab in the tab bar.
- \value OnlyOneTab The tab is both the first and the last tab in the tab bar.
-
- \sa position
-*/
-
-/*!
- \enum QStyleOptionTab::CornerWidget
-
- These flags indicate the corner widgets in a tab.
-
- \value NoCornerWidgets There are no corner widgets
- \value LeftCornerWidget Left corner widget
- \value RightCornerWidget Right corner widget
-
- \sa cornerWidgets
-*/
-
-/*! \enum QStyleOptionTab::SelectedPosition
-
- This enum describes the position of the selected tab. Some styles
- need to draw a tab differently depending on whether or not it is
- adjacent to the selected tab.
-
- \value NotAdjacent The tab is not adjacent to a selected tab (or is the selected tab).
- \value NextIsSelected The next tab (typically the tab on the right) is selected.
- \value PreviousIsSelected The previous tab (typically the tab on the left) is selected.
-
- \sa selectedPosition
-*/
-
-/*!
- \variable QStyleOptionTab::selectedPosition
- \brief the position of the selected tab in relation to this tab
-
- The default value is NotAdjacent, i.e. the tab is not adjacent to
- a selected tab nor is it the selected tab.
-*/
-
-/*!
- \variable QStyleOptionTab::cornerWidgets
- \brief an OR combination of CornerWidget values indicating the
- corner widgets of the tab bar
-
- The default value is NoCornerWidgets.
-
- \sa CornerWidget
-*/
-
-
-/*!
- \variable QStyleOptionTab::shape
- \brief the tab shape used to draw the tab; by default
- QTabBar::RoundedNorth
-
- \sa QTabBar::Shape
-*/
-
-/*!
- \variable QStyleOptionTab::text
- \brief the text of the tab
-
- The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionTab::icon
- \brief the icon for the tab
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-*/
-
-/*!
- \variable QStyleOptionTab::row
- \brief which row the tab is currently in
-
- The default value is 0, indicating the front row. Currently this
- property can only be 0.
-*/
-
-/*!
- \variable QStyleOptionTab::position
- \brief the position of the tab in the tab bar
-
- The default value is \l Beginning, i.e. the tab is the first tab
- in the tab bar.
-*/
-
-/*!
- \class QStyleOptionTabV2
- \brief The QStyleOptionTabV2 class is used to describe the
- parameters necessary for drawing a tabs in Qt 4.1 or above.
-
- \since 4.1
-
- An instance of the QStyleOptionTabV2 class has
- \l{QStyleOption::type} {type} \l SO_Tab and
- \l{QStyleOption::version} {version} 2. The type is used internally
- by QStyleOption, its subclasses, and qstyleoption_cast() to
- determine the type of style option. In general you do not need to
- worry about this unless you want to create your own QStyleOption
- subclass and your own styles. The version is used by QStyleOption
- subclasses to implement extensions without breaking
- compatibility. If you use qstyleoption_cast(), you normally do not
- need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionTab and QStyleOptionTabV2. One way to achieve this is
- to use the QStyleOptionTabV2 copy constructor. For example:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 3
-
- In the example above: If \c tabOption's version is 1, the extra
- member (\l iconSize) will be set to an invalid size for \c tabV2.
- If \c tabOption's version is 2, the constructor will simply copy
- the \c tab's iconSize.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionTab, QStyleOption
-*/
-
-/*!
- \enum QStyleOptionTabV2::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 2
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionTabV2::iconSize
- \brief the size for the icons
-
- The default value is QSize(-1, -1), i.e. an invalid size; use
- QStyle::pixelMetric() to find the default icon size for tab bars.
-
- \sa QTabBar::iconSize()
-*/
-
-/*!
- Constructs a QStyleOptionTabV2.
-*/
-QStyleOptionTabV2::QStyleOptionTabV2()
- : QStyleOptionTab(Version)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionTabV2::QStyleOptionTabV2(int version)
- : QStyleOptionTab(version)
-{
-}
-
-/*!
- \fn QStyleOptionTabV2::QStyleOptionTabV2(const QStyleOptionTabV2 &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- Constructs a QStyleOptionTabV2 copy of the \a other style option
- which can be either of the QStyleOptionTabV2 or QStyleOptionTab
- types.
-
- If the other style option's version is 1, the new style option's
- \c iconSize is set to an invalid value. If its version is 2, its
- \c iconSize value is simply copied to the new style option.
-*/
-QStyleOptionTabV2::QStyleOptionTabV2(const QStyleOptionTab &other)
- : QStyleOptionTab(Version)
-{
- if (const QStyleOptionTabV2 *tab = qstyleoption_cast<const QStyleOptionTabV2 *>(&other)) {
- *this = *tab;
- } else {
- *((QStyleOptionTab *)this) = other;
- version = Version;
- }
-}
-
-/*!
- Assigns the \a other style option to this QStyleOptionTabV2. The
- \a other style option can be either of the QStyleOptionTabV2 or
- QStyleOptionTab types.
-
- If the other style option's version is 1, this style option's \c
- iconSize is set to an invalid size. If its version is 2, its \c
- iconSize value is simply copied to this style option.
-*/
-QStyleOptionTabV2 &QStyleOptionTabV2::operator=(const QStyleOptionTab &other)
-{
- QStyleOptionTab::operator=(other);
-
- if (const QStyleOptionTabV2 *tab = qstyleoption_cast<const QStyleOptionTabV2 *>(&other))
- iconSize = tab->iconSize;
- else
- iconSize = QSize();
- return *this;
-}
-
-/*!
- \class QStyleOptionTabV3
- \brief The QStyleOptionTabV3 class is used to describe the
- parameters necessary for drawing a tabs in Qt 4.5 or above.
-
- \since 4.5
-
- An instance of the QStyleOptionTabV3 class has
- \l{QStyleOption::type} {type} \l SO_Tab and
- \l{QStyleOption::version} {version} 3. The type is used internally
- by QStyleOption, its subclasses, and qstyleoption_cast() to
- determine the type of style option. In general you do not need to
- worry about this unless you want to create your own QStyleOption
- subclass and your own styles. The version is used by QStyleOption
- subclasses to implement extensions without breaking
- compatibility. If you use qstyleoption_cast(), you normally do not
- need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionTab, QStyleOptionTabV2 and QStyleOptionTabV3.
- One way to achieve this is to use the QStyleOptionTabV3 copy
- constructor. For example:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 3
-
- In the example above: If \c tabOption's version is 1, the extra
- member (\l{QStyleOptionTabV2::iconSize}{iconSize}) will be set to
- an invalid size for \c tabV2. If \c tabOption's version is 2, the
- constructor will simply copy the \c tab's iconSize.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionTab, QStyleOption
-*/
-
-/*!
- \enum QStyleOptionTabV3::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 3
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionTabV3::documentMode
- \brief whether the tabbar is in document mode.
-
- The default value is false;
-*/
-
-/*!
- \variable QStyleOptionTabV3::leftButtonSize
- \brief the size for the left widget on the tab.
-
- The default value is QSize(-1, -1), i.e. an invalid size;
-*/
-
-/*!
- \variable QStyleOptionTabV3::rightButtonSize
- \brief the size for the right widget on the tab.
-
- The default value is QSize(-1, -1), i.e. an invalid size;
-*/
-
-/*!
- Constructs a QStyleOptionTabV3.
-*/
-
-QStyleOptionTabV3::QStyleOptionTabV3()
- : QStyleOptionTabV2(Version)
- , documentMode(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionTabV3::QStyleOptionTabV3(int version)
- : QStyleOptionTabV2(version)
-{
-}
-
-/*!
- \fn QStyleOptionTabV3::QStyleOptionTabV3(const QStyleOptionTabV3 &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \fn QStyleOptionTabV3::QStyleOptionTabV3(const QStyleOptionTabV2 &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- Constructs a QStyleOptionTabV3 copy of the \a other style option
- which can be either of the QStyleOptionTabV3, QStyleOptionTabV2
- or QStyleOptionTab types.
-
- If the other style option's version is 1 or 2, the new style option's
- \c leftButtonSize and \c rightButtonSize is set to an invalid value. If
- its version is 3, its \c leftButtonSize and \c rightButtonSize values
- are simply copied to the new style option.
-*/
-QStyleOptionTabV3::QStyleOptionTabV3(const QStyleOptionTab &other)
- : QStyleOptionTabV2(Version)
-{
- if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(&other)) {
- *this = *tab;
- } else {
- *((QStyleOptionTabV2 *)this) = other;
- version = Version;
- }
-}
-
-/*!
- Assigns the \a other style option to this QStyleOptionTabV3. The
- \a other style option can be either of the QStyleOptionTabV3,
- QStyleOptionTabV2 or QStyleOptionTab types.
-
- If the other style option's version is 1 or 2, the new style option's
- \c leftButtonSize and \c rightButtonSize is set to an invalid value. If
- its version is 3, its \c leftButtonSize and \c rightButtonSize values
- are simply copied to the new style option.
-*/
-QStyleOptionTabV3 &QStyleOptionTabV3::operator=(const QStyleOptionTab &other)
-{
- QStyleOptionTabV2::operator=(other);
-
- if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(&other)) {
- leftButtonSize = tab->leftButtonSize;
- rightButtonSize = tab->rightButtonSize;
- } else {
- leftButtonSize = QSize();
- rightButtonSize = QSize();
- documentMode = false;
- }
- return *this;
-}
-
-#endif // QT_NO_TABBAR
-
-/*!
- \class QStyleOptionProgressBar
- \brief The QStyleOptionProgressBar class is used to describe the
- parameters necessary for drawing a progress bar.
-
- Since Qt 4.1, Qt uses the QStyleOptionProgressBarV2 subclass for
- drawing QProgressBar.
-
- An instance of the QStyleOptionProgressBar class has type
- SO_ProgressBar and version 1.
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles. The
- version is used by QStyleOption subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast(),
- you normally do not need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionProgressBar and QStyleOptionProgressBarV2.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionProgressBarV2, QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionProgressBar, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionProgressBar::QStyleOptionProgressBar()
- : QStyleOption(QStyleOptionProgressBar::Version, SO_ProgressBar),
- minimum(0), maximum(0), progress(0), textAlignment(Qt::AlignLeft), textVisible(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionProgressBar::QStyleOptionProgressBar(int version)
- : QStyleOption(version, SO_ProgressBar),
- minimum(0), maximum(0), progress(0), textAlignment(Qt::AlignLeft), textVisible(false)
-{
-}
-
-/*!
- \fn QStyleOptionProgressBar::QStyleOptionProgressBar(const QStyleOptionProgressBar &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionProgressBar::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ProgressBar} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionProgressBar::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionProgressBar::minimum
- \brief the minimum value for the progress bar
-
- This is the minimum value in the progress bar. The default value
- is 0.
-
- \sa QProgressBar::minimum
-*/
-
-/*!
- \variable QStyleOptionProgressBar::maximum
- \brief the maximum value for the progress bar
-
- This is the maximum value in the progress bar. The default value
- is 0.
-
- \sa QProgressBar::maximum
-*/
-
-/*!
- \variable QStyleOptionProgressBar::text
- \brief the text for the progress bar
-
- The progress bar text is usually just the progress expressed as a
- string. An empty string indicates that the progress bar has not
- started yet. The default value is an empty string.
-
- \sa QProgressBar::text
-*/
-
-/*!
- \variable QStyleOptionProgressBar::textVisible
- \brief a flag indicating whether or not text is visible
-
- If this flag is true then the text is visible. Otherwise, the text
- is not visible. The default value is false.
-
- \sa QProgressBar::textVisible
-*/
-
-
-/*!
- \variable QStyleOptionProgressBar::textAlignment
- \brief the text alignment for the text in the QProgressBar
-
- This can be used as a guide on where the text should be in the
- progress bar. The default value is Qt::AlignLeft.
-*/
-
-/*!
- \variable QStyleOptionProgressBar::progress
- \brief the current progress for the progress bar
-
- The current progress. A value of QStyleOptionProgressBar::minimum
- - 1 indicates that the progress hasn't started yet. The default
- value is 0.
-
- \sa QProgressBar::value
-*/
-
-/*!
- \class QStyleOptionProgressBarV2
- \brief The QStyleOptionProgressBarV2 class is used to describe the
- parameters necessary for drawing a progress bar in Qt 4.1 or above.
-
- \since 4.1
-
- An instance of this class has \l{QStyleOption::type} {type}
- SO_ProgressBar and \l{QStyleOption::version} {version} 2.
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles. The
- version is used by QStyleOption subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast(),
- you normally do not need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionProgressBar and QStyleOptionProgressBarV2. One way
- to achieve this is to use the QStyleOptionProgressBarV2 copy
- constructor. For example:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 2
-
- In the example above: If the \c progressBarOption's version is 1,
- the extra members (\l orientation, \l invertedAppearance, and \l
- bottomToTop) are set to default values for \c progressBarV2. If
- the \c progressBarOption's version is 2, the constructor will
- simply copy the extra members to progressBarV2.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionProgressBar, QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionProgressBarV2, initializing he members
- variables to their default values.
-*/
-
-QStyleOptionProgressBarV2::QStyleOptionProgressBarV2()
- : QStyleOptionProgressBar(2),
- orientation(Qt::Horizontal), invertedAppearance(false), bottomToTop(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionProgressBarV2::QStyleOptionProgressBarV2(int version)
- : QStyleOptionProgressBar(version),
- orientation(Qt::Horizontal), invertedAppearance(false), bottomToTop(false)
-{
-}
-
-/*!
- Constructs a copy of the \a other style option which can be either
- of the QStyleOptionProgressBar and QStyleOptionProgressBarV2
- types.
-
- If the \a{other} style option's version is 1, the extra members (\l
- orientation, \l invertedAppearance, and \l bottomToTop) are set
- to default values for the new style option. If \a{other}'s version
- is 2, the extra members are simply copied.
-
- \sa version
-*/
-QStyleOptionProgressBarV2::QStyleOptionProgressBarV2(const QStyleOptionProgressBar &other)
- : QStyleOptionProgressBar(2), orientation(Qt::Horizontal), invertedAppearance(false), bottomToTop(false)
-{
- const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(&other);
- if (pb2)
- *this = *pb2;
- else
- *((QStyleOptionProgressBar *)this) = other;
-}
-
-/*!
- Constructs a copy of the \a other style option.
-*/
-QStyleOptionProgressBarV2::QStyleOptionProgressBarV2(const QStyleOptionProgressBarV2 &other)
- : QStyleOptionProgressBar(2), orientation(Qt::Horizontal), invertedAppearance(false), bottomToTop(false)
-{
- *this = other;
-}
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionProgressBarV2
- or QStyleOptionProgressBar types.
-
- If the \a{other} style option's version is 1, the extra members
- (\l orientation, \l invertedAppearance, and \l bottomToTop) are
- set to default values for this style option. If \a{other}'s
- version is 2, the extra members are simply copied to this style
- option.
-*/
-QStyleOptionProgressBarV2 &QStyleOptionProgressBarV2::operator=(const QStyleOptionProgressBar &other)
-{
- QStyleOptionProgressBar::operator=(other);
-
- const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(&other);
- orientation = pb2 ? pb2->orientation : Qt::Horizontal;
- invertedAppearance = pb2 ? pb2->invertedAppearance : false;
- bottomToTop = pb2 ? pb2->bottomToTop : false;
- return *this;
-}
-
-/*!
- \variable QStyleOptionProgressBarV2::orientation
- \brief the progress bar's orientation (horizontal or vertical);
- the default orentation is Qt::Horizontal
-
- \sa QProgressBar::orientation
-*/
-
-/*!
- \variable QStyleOptionProgressBarV2::invertedAppearance
- \brief whether the progress bar's appearance is inverted
-
- The default value is false.
-
- \sa QProgressBar::invertedAppearance
-*/
-
-/*!
- \variable QStyleOptionProgressBarV2::bottomToTop
- \brief whether the text reads from bottom to top when the progress
- bar is vertical
-
- The default value is false.
-
- \sa QProgressBar::textDirection
-*/
-
-/*!
- \enum QStyleOptionProgressBarV2::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ProgressBar} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionProgressBarV2::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 2
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-
-/*!
- \class QStyleOptionMenuItem
- \brief The QStyleOptionMenuItem class is used to describe the
- parameter necessary for drawing a menu item.
-
- QStyleOptionMenuItem contains all the information that QStyle
- functions need to draw the menu items from \l QMenu. It is also
- used for drawing other menu-related widgets.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionMenuItem, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionMenuItem::QStyleOptionMenuItem()
- : QStyleOption(QStyleOptionMenuItem::Version, SO_MenuItem), menuItemType(Normal),
- checkType(NotCheckable), checked(false), menuHasCheckableItems(true), maxIconWidth(0), tabWidth(0)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
- : QStyleOption(version, SO_MenuItem), menuItemType(Normal),
- checkType(NotCheckable), checked(false), menuHasCheckableItems(true), maxIconWidth(0), tabWidth(0)
-{
-}
-
-/*!
- \fn QStyleOptionMenuItem::QStyleOptionMenuItem(const QStyleOptionMenuItem &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionMenuItem::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_MenuItem} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionMenuItem::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \enum QStyleOptionMenuItem::MenuItemType
-
- This enum indicates the type of menu item that the structure describes.
-
- \value Normal A normal menu item.
- \value DefaultItem A menu item that is the default action as specified with \l QMenu::defaultAction().
- \value Separator A menu separator.
- \value SubMenu Indicates the menu item points to a sub-menu.
- \value Scroller A popup menu scroller (currently only used on Mac OS X).
- \value TearOff A tear-off handle for the menu.
- \value Margin The margin of the menu.
- \value EmptyArea The empty area of the menu.
-
- \sa menuItemType
-*/
-
-/*!
- \enum QStyleOptionMenuItem::CheckType
-
- This enum is used to indicate whether or not a check mark should be
- drawn for the item, or even if it should be drawn at all.
-
- \value NotCheckable The item is not checkable.
- \value Exclusive The item is an exclusive check item (like a radio button).
- \value NonExclusive The item is a non-exclusive check item (like a check box).
-
- \sa checkType, QAction::checkable, QAction::checked, QActionGroup::exclusive
-*/
-
-/*!
- \variable QStyleOptionMenuItem::menuItemType
- \brief the type of menu item
-
- The default value is \l Normal.
-
- \sa MenuItemType
-*/
-
-/*!
- \variable QStyleOptionMenuItem::checkType
- \brief the type of checkmark of the menu item
-
- The default value is \l NotCheckable.
-
- \sa CheckType
-*/
-
-/*!
- \variable QStyleOptionMenuItem::checked
- \brief whether the menu item is checked or not
-
- The default value is false.
-*/
-
-/*!
- \variable QStyleOptionMenuItem::menuHasCheckableItems
- \brief whether the menu as a whole has checkable items or not
-
- The default value is true.
-
- If this option is set to false, then the menu has no checkable
- items. This makes it possible for GUI styles to save some
- horizontal space that would normally be used for the check column.
-*/
-
-/*!
- \variable QStyleOptionMenuItem::menuRect
- \brief the rectangle for the entire menu
-
- The default value is a null rectangle, i.e. a rectangle with both
- the width and the height set to 0.
-*/
-
-/*!
- \variable QStyleOptionMenuItem::text
- \brief the text for the menu item
-
- Note that the text format is something like this "Menu
- text\bold{\\t}Shortcut".
-
- If the menu item doesn't have a shortcut, it will just contain the
- menu item's text. The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionMenuItem::icon
- \brief the icon for the menu item
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-*/
-
-/*!
- \variable QStyleOptionMenuItem::maxIconWidth
- \brief the maximum icon width for the icon in the menu item
-
- This can be used for drawing the icon into the correct place or
- properly aligning items. The variable must be set regardless of
- whether or not the menu item has an icon. The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionMenuItem::tabWidth
- \brief the tab width for the menu item
-
- The tab width is the distance between the text of the menu item
- and the shortcut. The default value is 0.
-*/
-
-
-/*!
- \variable QStyleOptionMenuItem::font
- \brief the font used for the menu item text
-
- This is the font that should be used for drawing the menu text
- minus the shortcut. The shortcut is usually drawn using the
- painter's font. By default, the application's default font is
- used.
-*/
-
-/*!
- \class QStyleOptionComplex
- \brief The QStyleOptionComplex class is used to hold parameters that are
- common to all complex controls.
-
- This class is not used on its own. Instead it is used to derive
- other complex control options, for example QStyleOptionSlider and
- QStyleOptionSpinBox.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator).
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionComplex of the specified \a type and \a
- version, initializing the member variables to their default
- values. This constructor is usually called by subclasses.
-*/
-
-QStyleOptionComplex::QStyleOptionComplex(int version, int type)
- : QStyleOption(version, type), subControls(QStyle::SC_All), activeSubControls(QStyle::SC_None)
-{
-}
-
-/*!
- \fn QStyleOptionComplex::QStyleOptionComplex(const QStyleOptionComplex &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionComplex::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Complex} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionComplex::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionComplex::subControls
-
- This variable holds a bitwise OR of the \l{QStyle::SubControl}
- {sub-controls} to be drawn for the complex control.
-
- The default value is QStyle::SC_All.
-
- \sa QStyle::SubControl
-*/
-
-/*!
- \variable QStyleOptionComplex::activeSubControls
-
- This variable holds a bitwise OR of the \l{QStyle::SubControl}
- {sub-controls} that are active for the complex control.
-
- The default value is QStyle::SC_None.
-
- \sa QStyle::SubControl
-*/
-
-#ifndef QT_NO_SLIDER
-/*!
- \class QStyleOptionSlider
- \brief The QStyleOptionSlider class is used to describe the
- parameters needed for drawing a slider.
-
- QStyleOptionSlider contains all the information that QStyle
- functions need to draw QSlider and QScrollBar.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionComplex, QSlider, QScrollBar
-*/
-
-/*!
- Constructs a QStyleOptionSlider, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionSlider::QStyleOptionSlider()
- : QStyleOptionComplex(Version, SO_Slider), orientation(Qt::Horizontal), minimum(0), maximum(0),
- tickPosition(QSlider::NoTicks), tickInterval(0), upsideDown(false),
- sliderPosition(0), sliderValue(0), singleStep(0), pageStep(0), notchTarget(0.0),
- dialWrapping(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionSlider::QStyleOptionSlider(int version)
- : QStyleOptionComplex(version, SO_Slider), orientation(Qt::Horizontal), minimum(0), maximum(0),
- tickPosition(QSlider::NoTicks), tickInterval(0), upsideDown(false),
- sliderPosition(0), sliderValue(0), singleStep(0), pageStep(0), notchTarget(0.0),
- dialWrapping(false)
-{
-}
-
-/*!
- \fn QStyleOptionSlider::QStyleOptionSlider(const QStyleOptionSlider &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionSlider::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Slider} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionSlider::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionSlider::orientation
- \brief the slider's orientation (horizontal or vertical)
-
- The default orientation is Qt::Horizontal.
-
- \sa Qt::Orientation
-*/
-
-/*!
- \variable QStyleOptionSlider::minimum
- \brief the minimum value for the slider
-
- The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionSlider::maximum
- \brief the maximum value for the slider
-
- The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionSlider::tickPosition
- \brief the position of the slider's tick marks, if any
-
- The default value is QSlider::NoTicks.
-
- \sa QSlider::TickPosition
-*/
-
-/*!
- \variable QStyleOptionSlider::tickInterval
- \brief the interval that should be drawn between tick marks
-
- The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionSlider::notchTarget
- \brief the number of pixel between notches
-
- The default value is 0.0.
-
- \sa QDial::notchTarget()
-*/
-
-/*!
- \variable QStyleOptionSlider::dialWrapping
- \brief whether the dial should wrap or not
-
- The default value is false, i.e. the dial is not wrapped.
-
- \sa QDial::wrapping()
-*/
-
-/*!
- \variable QStyleOptionSlider::upsideDown
- \brief the slider control orientation
-
- Normally a slider increases as it moves up or to the right;
- upsideDown indicates that it should do the opposite (increase as
- it moves down or to the left). The default value is false,
- i.e. the slider increases as it moves up or to the right.
-
- \sa QStyle::sliderPositionFromValue(),
- QStyle::sliderValueFromPosition(),
- QAbstractSlider::invertedAppearance
-*/
-
-/*!
- \variable QStyleOptionSlider::sliderPosition
- \brief the position of the slider handle
-
- If the slider has active feedback (i.e.,
- QAbstractSlider::tracking is true), this value will be the same as
- \l sliderValue. Otherwise, it will have the current position of
- the handle. The default value is 0.
-
- \sa QAbstractSlider::tracking, sliderValue
-*/
-
-/*!
- \variable QStyleOptionSlider::sliderValue
- \brief the value of the slider
-
- If the slider has active feedback (i.e.,
- QAbstractSlider::tracking is true), this value will be the same
- as \l sliderPosition. Otherwise, it will have the value the
- slider had before the mouse was pressed.
-
- The default value is 0.
-
- \sa QAbstractSlider::tracking sliderPosition
-*/
-
-/*!
- \variable QStyleOptionSlider::singleStep
- \brief the size of the single step of the slider
-
- The default value is 0.
-
- \sa QAbstractSlider::singleStep
-*/
-
-/*!
- \variable QStyleOptionSlider::pageStep
- \brief the size of the page step of the slider
-
- The default value is 0.
-
- \sa QAbstractSlider::pageStep
-*/
-#endif // QT_NO_SLIDER
-
-#ifndef QT_NO_SPINBOX
-/*!
- \class QStyleOptionSpinBox
- \brief The QStyleOptionSpinBox class is used to describe the
- parameters necessary for drawing a spin box.
-
- QStyleOptionSpinBox contains all the information that QStyle
- functions need to draw QSpinBox and QDateTimeEdit.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionComplex
-*/
-
-/*!
- Constructs a QStyleOptionSpinBox, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionSpinBox::QStyleOptionSpinBox()
- : QStyleOptionComplex(Version, SO_SpinBox), buttonSymbols(QAbstractSpinBox::UpDownArrows),
- stepEnabled(QAbstractSpinBox::StepNone), frame(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionSpinBox::QStyleOptionSpinBox(int version)
- : QStyleOptionComplex(version, SO_SpinBox), buttonSymbols(QAbstractSpinBox::UpDownArrows),
- stepEnabled(QAbstractSpinBox::StepNone), frame(false)
-{
-}
-
-/*!
- \fn QStyleOptionSpinBox::QStyleOptionSpinBox(const QStyleOptionSpinBox &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionSpinBox::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_SpinBox} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionSpinBox::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionSpinBox::buttonSymbols
- \brief the type of button symbols to draw for the spin box
-
- The default value is QAbstractSpinBox::UpDownArrows specufying
- little arrows in the classic style.
-
- \sa QAbstractSpinBox::ButtonSymbols
-*/
-
-/*!
- \variable QStyleOptionSpinBox::stepEnabled
- \brief which buttons of the spin box that are enabled
-
- The default value is QAbstractSpinBox::StepNone.
-
- \sa QAbstractSpinBox::StepEnabled
-*/
-
-/*!
- \variable QStyleOptionSpinBox::frame
- \brief whether the spin box has a frame
-
- The default value is false, i.e. the spin box has no frame.
-*/
-#endif // QT_NO_SPINBOX
-
-/*!
- \class QStyleOptionQ3ListViewItem
- \brief The QStyleOptionQ3ListViewItem class is used to describe an
- item drawn in a Q3ListView.
-
- This class is used for drawing the compatibility Q3ListView's
- items. \bold {It is not recommended for new classes}.
-
- QStyleOptionQ3ListViewItem contains all the information that
- QStyle functions need to draw the Q3ListView items.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionQ3ListView, Q3ListViewItem
-*/
-
-/*!
- \enum QStyleOptionQ3ListViewItem::Q3ListViewItemFeature
-
- This enum describes the features a list view item can have.
-
- \value None A standard item.
- \value Expandable The item has children that can be shown.
- \value MultiLine The item is more than one line tall.
- \value Visible The item is visible.
- \value ParentControl The item's parent is a type of item control (Q3CheckListItem::Controller).
-
- \sa features, Q3ListViewItem::isVisible(), Q3ListViewItem::multiLinesEnabled(),
- Q3ListViewItem::isExpandable()
-*/
-
-/*!
- Constructs a QStyleOptionQ3ListViewItem, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionQ3ListViewItem::QStyleOptionQ3ListViewItem()
- : QStyleOption(Version, SO_Q3ListViewItem), features(None), height(0), totalHeight(0),
- itemY(0), childCount(0)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionQ3ListViewItem::QStyleOptionQ3ListViewItem(int version)
- : QStyleOption(version, SO_Q3ListViewItem), features(None), height(0), totalHeight(0),
- itemY(0), childCount(0)
-{
-}
-
-/*!
- \fn QStyleOptionQ3ListViewItem::QStyleOptionQ3ListViewItem(const QStyleOptionQ3ListViewItem &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionQ3ListViewItem::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Q3ListViewItem} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionQ3ListViewItem::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionQ3ListViewItem::features
- \brief the features for this item
-
- This variable is a bitwise OR of the features of the item. The deafult value is \l None.
-
- \sa Q3ListViewItemFeature
-*/
-
-/*!
- \variable QStyleOptionQ3ListViewItem::height
- \brief the height of the item
-
- This doesn't include the height of the item's children. The default height is 0.
-
- \sa Q3ListViewItem::height()
-*/
-
-/*!
- \variable QStyleOptionQ3ListViewItem::totalHeight
- \brief the total height of the item, including its children
-
- The default total height is 0.
-
- \sa Q3ListViewItem::totalHeight()
-*/
-
-/*!
- \variable QStyleOptionQ3ListViewItem::itemY
- \brief the Y-coordinate for the item
-
- The default value is 0.
-
- \sa Q3ListViewItem::itemPos()
-*/
-
-/*!
- \variable QStyleOptionQ3ListViewItem::childCount
- \brief the number of children the item has
-*/
-
-/*!
- \class QStyleOptionQ3ListView
- \brief The QStyleOptionQ3ListView class is used to describe the
- parameters for drawing a Q3ListView.
-
- This class is used for drawing the compatibility Q3ListView. \bold
- {It is not recommended for new classes}.
-
- QStyleOptionQ3ListView contains all the information that QStyle
- functions need to draw Q3ListView.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOptionComplex, Q3ListView, QStyleOptionQ3ListViewItem
-*/
-
-/*!
- Creates a QStyleOptionQ3ListView, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionQ3ListView::QStyleOptionQ3ListView()
- : QStyleOptionComplex(Version, SO_Q3ListView), viewportBGRole(QPalette::Base),
- sortColumn(0), itemMargin(0), treeStepSize(0), rootIsDecorated(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionQ3ListView::QStyleOptionQ3ListView(int version)
- : QStyleOptionComplex(version, SO_Q3ListView), viewportBGRole(QPalette::Base),
- sortColumn(0), itemMargin(0), treeStepSize(0), rootIsDecorated(false)
-{
-}
-
-/*!
- \fn QStyleOptionQ3ListView::QStyleOptionQ3ListView(const QStyleOptionQ3ListView &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionQ3ListView::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Q3ListView} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionQ3ListView::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::items
- \brief a list of items in the Q3ListView
-
- This is a list of \l {QStyleOptionQ3ListViewItem}s. The first item
- can be used for most of the calculation that are needed for
- drawing a list view. Any additional items are the children of
- this first item, which may be used for additional information.
-
- \sa QStyleOptionQ3ListViewItem
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::viewportPalette
- \brief the palette of Q3ListView's viewport
-
- By default, the application's default palette is used.
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::viewportBGRole
- \brief the background role of Q3ListView's viewport
-
- The default value is QPalette::Base.
-
- \sa QWidget::backgroundRole()
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::sortColumn
- \brief the sort column of the list view
-
- The default value is 0.
-
- \sa Q3ListView::sortColumn()
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::itemMargin
- \brief the margin for items in the list view
-
- The default value is 0.
-
- \sa Q3ListView::itemMargin()
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::treeStepSize
- \brief the number of pixel to offset children items from their
- parents
-
- The default value is 0.
-
- \sa Q3ListView::treeStepSize()
-*/
-
-/*!
- \variable QStyleOptionQ3ListView::rootIsDecorated
- \brief whether root items are decorated
-
- The default value is false.
-
- \sa Q3ListView::rootIsDecorated()
-*/
-
-/*!
- \class QStyleOptionQ3DockWindow
- \brief The QStyleOptionQ3DockWindow class is used to describe the
- parameters for drawing various parts of a Q3DockWindow.
-
- This class is used for drawing the old Q3DockWindow and its
- parts. \bold {It is not recommended for new classes}.
-
- QStyleOptionQ3DockWindow contains all the information that QStyle
- functions need to draw Q3DockWindow and its parts.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, Q3DockWindow
-*/
-
-/*!
- Constructs a QStyleOptionQ3DockWindow, initializing the member
- variables to their default values.
-*/
-
-QStyleOptionQ3DockWindow::QStyleOptionQ3DockWindow()
- : QStyleOption(Version, SO_Q3DockWindow), docked(false), closeEnabled(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionQ3DockWindow::QStyleOptionQ3DockWindow(int version)
- : QStyleOption(version, SO_Q3DockWindow), docked(false), closeEnabled(false)
-{
-}
-
-/*!
- \fn QStyleOptionQ3DockWindow::QStyleOptionQ3DockWindow(const QStyleOptionQ3DockWindow &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionQ3DockWindow::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_Q3DockWindow} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionQ3DockWindow::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionQ3DockWindow::docked
- \brief whether the dock window is currently docked
-
- The default value is false.
-*/
-
-/*!
- \variable QStyleOptionQ3DockWindow::closeEnabled
- \brief whether the dock window has a close button
-
- The default value is false.
-*/
-
-/*!
- \class QStyleOptionDockWidget
- \brief The QStyleOptionDockWidget class is used to describe the
- parameters for drawing a dock widget.
-
- QStyleOptionDockWidget contains all the information that QStyle
- functions need to draw graphical elements like QDockWidget.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption
-*/
-
-/*!
- Constructs a QStyleOptionDockWidget, initializing the member
- variables to their default values.
-*/
-
-QStyleOptionDockWidget::QStyleOptionDockWidget()
- : QStyleOption(Version, SO_DockWidget), closable(false),
- movable(false), floatable(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionDockWidget::QStyleOptionDockWidget(int version)
- : QStyleOption(version, SO_DockWidget), closable(false),
- movable(false), floatable(false)
-{
-}
-
-QStyleOptionDockWidgetV2::QStyleOptionDockWidgetV2()
- : QStyleOptionDockWidget(Version), verticalTitleBar(false)
-{
-}
-
-QStyleOptionDockWidgetV2::QStyleOptionDockWidgetV2(
- const QStyleOptionDockWidget &other)
- : QStyleOptionDockWidget(Version)
-{
- (void)QStyleOptionDockWidgetV2::operator=(other);
-}
-
-QStyleOptionDockWidgetV2 &QStyleOptionDockWidgetV2::operator = (
- const QStyleOptionDockWidget &other)
-{
- QStyleOptionDockWidget::operator=(other);
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(&other);
- verticalTitleBar = v2 ? v2->verticalTitleBar : false;
- return *this;
-}
-
-QStyleOptionDockWidgetV2::QStyleOptionDockWidgetV2(int version)
- : QStyleOptionDockWidget(version), verticalTitleBar(false)
-{
-}
-
-/*!
- \fn QStyleOptionDockWidget::QStyleOptionDockWidget(const QStyleOptionDockWidget &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionDockWidget::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_DockWidget} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionDockWidget::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionDockWidget::title
- \brief the title of the dock window
-
- The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionDockWidget::closable
- \brief whether the dock window is closable
-
- The default value is true.
-*/
-
-/*!
- \variable QStyleOptionDockWidget::movable
- \brief whether the dock window is movable
-
- The default value is false.
-*/
-
-/*!
- \variable QStyleOptionDockWidget::floatable
- \brief whether the dock window is floatable
-
- The default value is true.
-*/
-
-/*!
- \class QStyleOptionToolButton
- \brief The QStyleOptionToolButton class is used to describe the
- parameters for drawing a tool button.
-
- QStyleOptionToolButton contains all the information that QStyle
- functions need to draw QToolButton.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionComplex, QStyleOptionButton
-*/
-
-/*!
- \enum QStyleOptionToolButton::ToolButtonFeature
- Describes the various features that a tool button can have.
-
- \value None A normal tool button.
- \value Arrow The tool button is an arrow.
- \value Menu The tool button has a menu.
- \value PopupDelay There is a delay to showing the menu.
- \value HasMenu The button has a popup menu.
- \value MenuButtonPopup The button should display an arrow to
- indicate that a menu is present.
-
- \sa features, QToolButton::toolButtonStyle(), QToolButton::popupMode()
-*/
-
-/*!
- Constructs a QStyleOptionToolButton, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionToolButton::QStyleOptionToolButton()
- : QStyleOptionComplex(Version, SO_ToolButton), features(None), arrowType(Qt::DownArrow)
- , toolButtonStyle(Qt::ToolButtonIconOnly)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionToolButton::QStyleOptionToolButton(int version)
- : QStyleOptionComplex(version, SO_ToolButton), features(None), arrowType(Qt::DownArrow)
- , toolButtonStyle(Qt::ToolButtonIconOnly)
-
-{
-}
-
-/*!
- \fn QStyleOptionToolButton::QStyleOptionToolButton(const QStyleOptionToolButton &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionToolButton::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ToolButton} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionToolButton::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionToolButton::features
- \brief an OR combination of the tool button's features
-
- The default value is \l None.
-
- \sa ToolButtonFeature
-*/
-
-/*!
- \variable QStyleOptionToolButton::icon
- \brief the icon for the tool button
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-
- \sa iconSize
-*/
-
-/*!
- \variable QStyleOptionToolButton::iconSize
- \brief the size of the icon for the tool button
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-*/
-
-/*!
- \variable QStyleOptionToolButton::text
- \brief the text of the tool button
-
- This value is only used if toolButtonStyle is
- Qt::ToolButtonTextUnderIcon, Qt::ToolButtonTextBesideIcon, or
- Qt::ToolButtonTextOnly. The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionToolButton::arrowType
- \brief the direction of the arrow for the tool button
-
- This value is only used if \l features includes \l Arrow. The
- default value is Qt::DownArrow.
-*/
-
-/*!
- \variable QStyleOptionToolButton::toolButtonStyle
- \brief a Qt::ToolButtonStyle value describing the appearance of
- the tool button
-
- The default value is Qt::ToolButtonIconOnly.
-
- \sa QToolButton::toolButtonStyle()
-*/
-
-/*!
- \variable QStyleOptionToolButton::pos
- \brief the position of the tool button
-
- The default value is a null point, i.e. (0, 0)
-*/
-
-/*!
- \variable QStyleOptionToolButton::font
- \brief the font that is used for the text
-
- This value is only used if toolButtonStyle is
- Qt::ToolButtonTextUnderIcon, Qt::ToolButtonTextBesideIcon, or
- Qt::ToolButtonTextOnly. By default, the application's default font
- is used.
-*/
-
-/*!
- \class QStyleOptionComboBox
- \brief The QStyleOptionComboBox class is used to describe the
- parameter for drawing a combobox.
-
- QStyleOptionButton contains all the information that QStyle
- functions need to draw QComboBox.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionComplex, QComboBox
-*/
-
-/*!
- Creates a QStyleOptionComboBox, initializing the members variables
- to their default values.
-*/
-
-QStyleOptionComboBox::QStyleOptionComboBox()
- : QStyleOptionComplex(Version, SO_ComboBox), editable(false), frame(true)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionComboBox::QStyleOptionComboBox(int version)
- : QStyleOptionComplex(version, SO_ComboBox), editable(false), frame(true)
-{
-}
-
-/*!
- \fn QStyleOptionComboBox::QStyleOptionComboBox(const QStyleOptionComboBox &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionComboBox::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ComboBox} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionComboBox::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionComboBox::editable
- \brief whether or not the combobox is editable or not
-
- the default
- value is false
-
- \sa QComboBox::isEditable()
-*/
-
-
-/*!
- \variable QStyleOptionComboBox::frame
- \brief whether the combo box has a frame
-
- The default value is true.
-*/
-
-/*!
- \variable QStyleOptionComboBox::currentText
- \brief the text for the current item of the combo box
-
- The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionComboBox::currentIcon
- \brief the icon for the current item of the combo box
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-*/
-
-/*!
- \variable QStyleOptionComboBox::iconSize
- \brief the icon size for the current item of the combo box
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-*/
-
-/*!
- \variable QStyleOptionComboBox::popupRect
- \brief the popup rectangle for the combobox
-
- The default value is a null rectangle, i.e. a rectangle with both
- the width and the height set to 0.
-
- This variable is currently unused. You can safely ignore it.
-
- \sa QStyle::SC_ComboBoxListBoxPopup
-*/
-
-/*!
- \class QStyleOptionToolBox
- \brief The QStyleOptionToolBox class is used to describe the
- parameters needed for drawing a tool box.
-
- QStyleOptionToolBox contains all the information that QStyle
- functions need to draw QToolBox.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QToolBox
-*/
-
-/*!
- Creates a QStyleOptionToolBox, initializing the members variables
- to their default values.
-*/
-
-QStyleOptionToolBox::QStyleOptionToolBox()
- : QStyleOption(Version, SO_ToolBox)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionToolBox::QStyleOptionToolBox(int version)
- : QStyleOption(version, SO_ToolBox)
-{
-}
-
-/*!
- \fn QStyleOptionToolBox::QStyleOptionToolBox(const QStyleOptionToolBox &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionToolBox::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ToolBox} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionToolBox::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionToolBox::icon
- \brief the icon for the tool box tab
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-*/
-
-/*!
- \variable QStyleOptionToolBox::text
- \brief the text for the tool box tab
-
- The default value is an empty string.
-*/
-
-/*!
- \class QStyleOptionToolBoxV2
- \brief The QStyleOptionToolBoxV2 class is used to describe the parameters necessary for drawing a frame in Qt 4.3 or above.
-
- \since 4.3
- QStyleOptionToolBoxV2 inherits QStyleOptionToolBox which is used for
- drawing the tabs in a QToolBox.
-
- An instance of the QStyleOptionToolBoxV2 class has
- \l{QStyleOption::type} {type} SO_ToolBox and
- \l{QStyleOption::version} {version} 2. The type is used
- internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles. The
- version is used by QStyleOption subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast(),
- you normally do not need to check it.
-
- If you create your own QStyle subclass, you should handle both
- QStyleOptionToolBox and QStyleOptionToolBoxV2.
-
- \sa QStyleOptionToolBox, QStyleOption
-*/
-
-/*!
- Contsructs a QStyleOptionToolBoxV2 object.
-*/
-QStyleOptionToolBoxV2::QStyleOptionToolBoxV2()
- : QStyleOptionToolBox(Version), position(Beginning), selectedPosition(NotAdjacent)
-{
-}
-
-/*!
- \fn QStyleOptionToolBoxV2::QStyleOptionToolBoxV2(const QStyleOptionToolBoxV2 &other)
-
- Constructs a QStyleOptionToolBoxV2 copy of the \a other style option.
-*/
-
-/*!
- \internal
-*/
-QStyleOptionToolBoxV2::QStyleOptionToolBoxV2(int version)
- : QStyleOptionToolBox(version), position(Beginning), selectedPosition(NotAdjacent)
-{
-}
-
-/*!
- Constructs a QStyleOptionToolBoxV2 copy of the \a other style option
- which can be either of the QStyleOptionToolBoxV2 or
- QStyleOptionToolBox types.
-
- If the \a other style option's version is 1, the new style
- option's \l{QStyleOptionTab::position} {position} value is set to
- \l QStyleOptionToolBoxV2::Beginning and \l selectedPosition is set
- to \l QStyleOptionToolBoxV2::NotAdjacent. If its version is 2, the
- \l{QStyleOptionTab::position} {position} selectedPosition values
- are simply copied to the new style option.
-
- \sa version
-*/
-QStyleOptionToolBoxV2::QStyleOptionToolBoxV2(const QStyleOptionToolBox &other)
-{
- QStyleOptionToolBox::operator=(other);
-
- const QStyleOptionToolBoxV2 *f2 = qstyleoption_cast<const QStyleOptionToolBoxV2 *>(&other);
- position = f2 ? f2->position : Beginning;
- selectedPosition = f2 ? f2->selectedPosition : NotAdjacent;
- version = Version;
-}
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionToolBoxV2 or
- QStyleOptionToolBox types.
-
- If the \a{other} style option's version is 1, this style option's
- \l{QStyleOptionTab::position} {position} and \l selectedPosition
- values are set to \l QStyleOptionToolBoxV2::Beginning and \l
- QStyleOptionToolBoxV2::NotAdjacent respectively. If its
- \l{QStyleOption::version} {version} is 2, these values are simply
- copied to this style option.
-*/
-QStyleOptionToolBoxV2 &QStyleOptionToolBoxV2::operator=(const QStyleOptionToolBox &other)
-{
- QStyleOptionToolBox::operator=(other);
-
- const QStyleOptionToolBoxV2 *f2 = qstyleoption_cast<const QStyleOptionToolBoxV2 *>(&other);
- position = f2 ? f2->position : Beginning;
- selectedPosition = f2 ? f2->selectedPosition : NotAdjacent;
- version = Version;
- return *this;
-}
-
-
-/*!
- \enum QStyleOptionToolBoxV2::SelectedPosition
-
- This enum describes the position of the selected tab. Some styles
- need to draw a tab differently depending on whether or not it is
- adjacent to the selected tab.
-
- \value NotAdjacent The tab is not adjacent to a selected tab (or is the selected tab).
- \value NextIsSelected The next tab (typically the tab on the right) is selected.
- \value PreviousIsSelected The previous tab (typically the tab on the left) is selected.
-
- \sa selectedPosition
-*/
-
-/*!
- \enum QStyleOptionToolBoxV2::StyleOptionVersion
-
- This enum holds the version of this style option
-
- \value Version 2
-*/
-
-/*!
- \enum QStyleOptionToolBoxV2::TabPosition
-
- This enum describes tab positions relative to other tabs.
-
- \value Beginning The tab is the first (i.e., top-most) tab in
- the toolbox.
- \value Middle The tab is placed in the middle of the toolbox.
- \value End The tab is placed at the bottom of the toolbox.
- \value OnlyOneTab There is only one tab in the toolbox.
-*/
-
-/*!
- \variable QStyleOptionToolBoxV2::selectedPosition
- \brief the position of the selected tab in relation to this tab
-
- The default value is NotAdjacent, i.e. the tab is not adjacent to
- a selected tab nor is it the selected tab.
-*/
-
-#ifndef QT_NO_RUBBERBAND
-/*!
- \class QStyleOptionRubberBand
- \brief The QStyleOptionRubberBand class is used to describe the
- parameters needed for drawing a rubber band.
-
- QStyleOptionRubberBand contains all the information that
- QStyle functions need to draw QRubberBand.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QRubberBand
-*/
-
-/*!
- Creates a QStyleOptionRubberBand, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionRubberBand::QStyleOptionRubberBand()
- : QStyleOption(Version, SO_RubberBand), shape(QRubberBand::Line), opaque(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionRubberBand::QStyleOptionRubberBand(int version)
- : QStyleOption(version, SO_RubberBand), shape(QRubberBand::Line), opaque(false)
-{
-}
-
-/*!
- \fn QStyleOptionRubberBand::QStyleOptionRubberBand(const QStyleOptionRubberBand &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionRubberBand::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_RubberBand} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionRubberBand::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionRubberBand::shape
- \brief the shape of the rubber band
-
- The default shape is QRubberBand::Line.
-*/
-
-/*!
- \variable QStyleOptionRubberBand::opaque
- \brief whether the rubber band is required to be drawn in an opaque style
-
- The default value is true.
-*/
-#endif // QT_NO_RUBBERBAND
-
-/*!
- \class QStyleOptionTitleBar
- \brief The QStyleOptionTitleBar class is used to describe the
- parameters for drawing a title bar.
-
- QStyleOptionTitleBar contains all the information that QStyle
- functions need to draw the title bar of a QMdiSubWindow.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionComplex, QMdiSubWindow
-*/
-
-/*!
- Constructs a QStyleOptionTitleBar, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionTitleBar::QStyleOptionTitleBar()
- : QStyleOptionComplex(Version, SO_TitleBar), titleBarState(0), titleBarFlags(0)
-{
-}
-
-/*!
- \fn QStyleOptionTitleBar::QStyleOptionTitleBar(const QStyleOptionTitleBar &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionTitleBar::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_TitleBar} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionTitleBar::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \internal
-*/
-QStyleOptionTitleBar::QStyleOptionTitleBar(int version)
- : QStyleOptionComplex(version, SO_TitleBar), titleBarState(0), titleBarFlags(0)
-{
-}
-
-
-/*!
- \variable QStyleOptionTitleBar::text
- \brief the text of the title bar
-
- The default value is an empty string.
-*/
-
-/*!
- \variable QStyleOptionTitleBar::icon
- \brief the icon for the title bar
-
- The default value is an empty icon, i.e. an icon with neither a
- pixmap nor a filename.
-*/
-
-/*!
- \variable QStyleOptionTitleBar::titleBarState
- \brief the state of the title bar
-
- This is basically the window state of the underlying widget. The
- default value is 0.
-
- \sa QWidget::windowState()
-*/
-
-/*!
- \variable QStyleOptionTitleBar::titleBarFlags
- \brief the widget flags for the title bar
-
- The default value is Qt::Widget.
-
- \sa Qt::WindowFlags
-*/
-
-/*!
- \class QStyleOptionViewItem
- \brief The QStyleOptionViewItem class is used to describe the
- parameters used to draw an item in a view widget.
-
- QStyleOptionViewItem contains all the information that QStyle
- functions need to draw the items for Qt's model/view classes.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, {model-view-programming.html}{Model/View
- Programming}
-*/
-
-/*!
- \enum QStyleOptionViewItem::Position
-
- This enum describes the position of the item's decoration.
-
- \value Left On the left of the text.
- \value Right On the right of the text.
- \value Top Above the text.
- \value Bottom Below the text.
-
- \sa decorationPosition
-*/
-
-/*!
- \variable QStyleOptionViewItem::showDecorationSelected
- \brief whether the decoration should be highlighted on selected
- items
-
- If this option is true, the branch and any decorations on selected items
- should be highlighted, indicating that the item is selected; otherwise, no
- highlighting is required. The default value is false.
-
- \sa QStyle::SH_ItemView_ShowDecorationSelected, QAbstractItemView
-*/
-
-/*!
- \variable QStyleOptionViewItem::textElideMode
- \brief where ellipsis should be added for text that is too long to fit
- into an item
-
- The default value is Qt::ElideMiddle, i.e. the ellipsis appears in
- the middle of the text.
-
- \sa Qt::TextElideMode, QStyle::SH_ItemView_EllipsisLocation
-*/
-
-/*!
- Constructs a QStyleOptionViewItem, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionViewItem::QStyleOptionViewItem()
- : QStyleOption(Version, SO_ViewItem),
- displayAlignment(Qt::AlignLeft), decorationAlignment(Qt::AlignLeft),
- textElideMode(Qt::ElideMiddle), decorationPosition(Left),
- showDecorationSelected(false)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionViewItem::QStyleOptionViewItem(int version)
- : QStyleOption(version, SO_ViewItem),
- displayAlignment(Qt::AlignLeft), decorationAlignment(Qt::AlignLeft),
- textElideMode(Qt::ElideMiddle), decorationPosition(Left),
- showDecorationSelected(false)
-{
-}
-
-/*!
- \fn QStyleOptionViewItem::QStyleOptionViewItem(const QStyleOptionViewItem &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \enum QStyleOptionViewItem::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_ViewItem} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionViewItem::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionViewItem::displayAlignment
- \brief the alignment of the display value for the item
-
- The default value is Qt::AlignLeft.
-*/
-
-/*!
- \variable QStyleOptionViewItem::decorationAlignment
- \brief the alignment of the decoration for the item
-
- The default value is Qt::AlignLeft.
-*/
-
-/*!
- \variable QStyleOptionViewItem::decorationPosition
- \brief the position of the decoration for the item
-
- The default value is \l Left.
-
- \sa Position
-*/
-
-/*!
- \variable QStyleOptionViewItem::decorationSize
- \brief the size of the decoration for the item
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-
- \sa decorationAlignment, decorationPosition
-*/
-
-/*!
- \variable QStyleOptionViewItem::font
- \brief the font used for the item
-
- By default, the application's default font is used.
-
- \sa QFont
-*/
-
-/*!
- \fn T qstyleoption_cast<T>(const QStyleOption *option)
- \relates QStyleOption
-
- Returns a T or 0 depending on the \l{QStyleOption::type}{type} and
- \l{QStyleOption::version}{version} of the given \a option.
-
- Example:
-
- \snippet doc/src/snippets/qstyleoption/main.cpp 4
-
- \sa QStyleOption::type, QStyleOption::version
-*/
-
-/*!
- \fn T qstyleoption_cast<T>(QStyleOption *option)
- \overload
- \relates QStyleOption
-
- Returns a T or 0 depending on the type of the given \a option.
-*/
-
-#ifndef QT_NO_TABWIDGET
-/*!
- \class QStyleOptionTabWidgetFrame
- \brief The QStyleOptionTabWidgetFrame class is used to describe the
- parameters for drawing the frame around a tab widget.
-
- QStyleOptionTabWidgetFrame contains all the information that
- QStyle functions need to draw the frame around QTabWidget.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QTabWidget
-*/
-
-/*!
- Constructs a QStyleOptionTabWidgetFrame, initializing the members
- variables to their default values.
-*/
-QStyleOptionTabWidgetFrame::QStyleOptionTabWidgetFrame()
- : QStyleOption(Version, SO_TabWidgetFrame), lineWidth(0), midLineWidth(0),
- shape(QTabBar::RoundedNorth)
-{
-}
-
-/*!
- \fn QStyleOptionTabWidgetFrame::QStyleOptionTabWidgetFrame(const QStyleOptionTabWidgetFrame &other)
-
- Constructs a copy of \a other.
-*/
-
-/*! \internal */
-QStyleOptionTabWidgetFrame::QStyleOptionTabWidgetFrame(int version)
- : QStyleOption(version, SO_TabWidgetFrame), lineWidth(0), midLineWidth(0),
- shape(QTabBar::RoundedNorth)
-{
-}
-
-/*!
- \enum QStyleOptionTabWidgetFrame::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_TabWidgetFrame} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionTabWidgetFrame::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionTabWidgetFrame::lineWidth
- \brief the line width for drawing the panel
-
- The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionTabWidgetFrame::midLineWidth
- \brief the mid-line width for drawing the panel
-
- The mid line width is usually used in drawing sunken or raised
- frames. The default value is 0.
-*/
-
-/*!
- \variable QStyleOptionTabWidgetFrame::shape
- \brief the tab shape used to draw the tabs
-
- The default value is QTabBar::RoundedNorth.
-*/
-
-/*!
- \variable QStyleOptionTabWidgetFrame::tabBarSize
- \brief the size of the tab bar
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-*/
-
-/*!
- \variable QStyleOptionTabWidgetFrame::rightCornerWidgetSize
- \brief the size of the right-corner widget
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-*/
-
-/*! \variable QStyleOptionTabWidgetFrame::leftCornerWidgetSize
- \brief the size of the left-corner widget
-
- The default value is QSize(-1, -1), i.e. an invalid size.
-*/
-
-
-/*!
-
- \class QStyleOptionTabWidgetFrameV2
- \brief The QStyleOptionTabWidgetFrameV2 class is used to describe the
- parameters for drawing the frame around a tab widget.
-
- QStyleOptionTabWidgetFrameV2 contains all the information that
- QStyle functions need to draw the frame around QTabWidget.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QTabWidget
-*/
-
-
-/*!
- \variable QStyleOptionTabWidgetFrameV2::tabBarRect
- \brief the rectangle containing all the tabs
-
- The default value is a null rectangle, i.e. a rectangle with both
- the width and the height set to 0.
-*/
-
-/*!
- \variable QStyleOptionTabWidgetFrameV2::selectedTabRect
- \brief the rectangle containing the selected tab
-
- This rectangle is contained within the tabBarRect. The default
- value is a null rectangle, i.e. a rectangle with both the width
- and the height set to 0.
-*/
-
-
-/*!
- Constructs a QStyleOptionTabWidgetFrameV2, initializing the members
- variables to their default values.
-*/
-
-QStyleOptionTabWidgetFrameV2::QStyleOptionTabWidgetFrameV2()
- : QStyleOptionTabWidgetFrame(Version)
-{
-}
-
-
-/*! \internal */
-QStyleOptionTabWidgetFrameV2::QStyleOptionTabWidgetFrameV2(int version)
- : QStyleOptionTabWidgetFrame(version)
-{
-}
-
-
-/*! \fn QStyleOptionTabWidgetFrameV2::QStyleOptionTabWidgetFrameV2(const QStyleOptionTabWidgetFrameV2 &other)
- Constructs a QStyleOptionTabWidgetFrameV2 copy of the \a other style option.
-
- If the \a other style option's version is 1, the new style option's \l
- selectedTabRect and tabBarRect will contain null rects
-
- \sa version
-*/
-
-/*!
- Constructs a QStyleOptionTabWidgetFrameV2 copy of the \a other style option.
-
- If the \a other style option's version is 1, the new style option's \l
- selectedTabRect and tabBarRect will contain null rects
-
- \sa version
-*/
-QStyleOptionTabWidgetFrameV2::QStyleOptionTabWidgetFrameV2(const QStyleOptionTabWidgetFrame &other)
-{
- QStyleOptionTabWidgetFrameV2::operator=(other);
-
-}
-
-
-/*!
- Assigns the \a other style option to this style option. The \a
- other style option can be either of the QStyleOptionFrameV2 or
- QStyleOptionFrame types.
-
- If the \a{other} style option's version is 1, this style option's
- QStyleOptionFrameV2::FrameFeature value is set to
- QStyleOptionFrameV2::None. If its version is 2, its
- \l{QStyleOptionFrameV2::}{FrameFeature} value is simply copied to
- this style option.
-*/
-QStyleOptionTabWidgetFrameV2 &QStyleOptionTabWidgetFrameV2::operator=(const QStyleOptionTabWidgetFrame &other)
-{
- QStyleOptionTabWidgetFrame::operator=(other);
- if (const QStyleOptionTabWidgetFrameV2 *f2 = qstyleoption_cast<const QStyleOptionTabWidgetFrameV2 *>(&other)) {
- selectedTabRect = f2->selectedTabRect;
- tabBarRect = f2->tabBarRect;
- }
- return *this;
-}
-
-
-/*!
- \enum QStyleOptionTabWidgetFrameV2::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 2
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-
-#endif // QT_NO_TABWIDGET
-
-#ifndef QT_NO_TABBAR
-
-/*!
- \class QStyleOptionTabBarBase
- \brief The QStyleOptionTabBarBase class is used to describe
- the base of a tab bar, i.e. the part that the tab bar usually
- overlaps with.
-
- QStyleOptionTabBarBase contains all the information that QStyle
- functions need to draw the tab bar base. Note that this is only
- drawn for a standalone QTabBar (one that isn't part of a
- QTabWidget).
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QTabBar::drawBase()
-*/
-
-/*!
- Construct a QStyleOptionTabBarBase, initializing the members
- vaiables to their default values.
-*/
-QStyleOptionTabBarBase::QStyleOptionTabBarBase()
- : QStyleOption(Version, SO_TabBarBase), shape(QTabBar::RoundedNorth)
-{
-}
-
-/*! \internal */
-QStyleOptionTabBarBase::QStyleOptionTabBarBase(int version)
- : QStyleOption(version, SO_TabBarBase), shape(QTabBar::RoundedNorth)
-{
-}
-
-/*!
- \fn QStyleOptionTabBarBase::QStyleOptionTabBarBase(const QStyleOptionTabBarBase &other)
-
- Constructs a copy of \a other.
-*/
-
-/*!
- \enum QStyleOptionTabBarBase::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_TabBarBase} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionTabBarBase::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionTabBarBase::shape
- \brief the shape of the tab bar
-
- The default value is QTabBar::RoundedNorth.
-*/
-
-/*!
- \variable QStyleOptionTabBarBase::tabBarRect
- \brief the rectangle containing all the tabs
-
- The default value is a null rectangle, i.e. a rectangle with both
- the width and the height set to 0.
-*/
-
-/*!
- \variable QStyleOptionTabBarBase::selectedTabRect
- \brief the rectangle containing the selected tab
-
- This rectangle is contained within the tabBarRect. The default
- value is a null rectangle, i.e. a rectangle with both the width
- and the height set to 0.
-*/
-
-
-/*!
- \class QStyleOptionTabBarBaseV2
- \brief The QStyleOptionTabBarBaseV2 class is used to describe
- the base of a tab bar, i.e. the part that the tab bar usually
- overlaps with.
- \since 4.5
-
- QStyleOptionTabBarBase contains all the information that QStyle
- functions need to draw the tab bar base.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QTabBar::drawBase()
-*/
-
-/*!
- \enum QStyleOptionTabBarBaseV2::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 2
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleOptionTabBarBaseV2::documentMode
- \brief whether the tabbar is in document mode.
-
- The default value is false;
-*/
-
-/*!
- Construct a QStyleOptionTabBarBaseV2, initializing the members
- vaiables to their default values.
-*/
-QStyleOptionTabBarBaseV2::QStyleOptionTabBarBaseV2()
- : QStyleOptionTabBarBase(Version)
- , documentMode(false)
-{
-}
-
-/*!
- \fn QStyleOptionTabBarBaseV2::QStyleOptionTabBarBaseV2(const QStyleOptionTabBarBaseV2 &other)
-
- Constructs a copy of \a other.
-*/
-
-/*!
- Constructs a copy of \a other.
-*/
-QStyleOptionTabBarBaseV2::QStyleOptionTabBarBaseV2(const QStyleOptionTabBarBase &other)
- : QStyleOptionTabBarBase(Version)
-{
- (void)QStyleOptionTabBarBaseV2::operator=(other);
-}
-
-/*!
- Constructs a QStyleOptionTabBarBaseV2 copy of the \a other style option
- which can be either of the QStyleOptionTabBarBaseV2, or QStyleOptionTabBarBase types.
-
- If the other style option's version is not 1, the new style option's
- \c documentMode is set to false. If its version is 2, its \c documentMode value
- is simply copied to the new style option.
-*/
-QStyleOptionTabBarBaseV2 &QStyleOptionTabBarBaseV2::operator = (const QStyleOptionTabBarBase &other)
-{
- QStyleOptionTabBarBase::operator=(other);
- const QStyleOptionTabBarBaseV2 *v2 = qstyleoption_cast<const QStyleOptionTabBarBaseV2*>(&other);
- documentMode = v2 ? v2->documentMode : false;
- return *this;
-}
-
-/*! \internal */
-QStyleOptionTabBarBaseV2::QStyleOptionTabBarBaseV2(int version)
- : QStyleOptionTabBarBase(version), documentMode(false)
-{
-}
-
-#endif // QT_NO_TABBAR
-
-#ifndef QT_NO_SIZEGRIP
-/*!
- \class QStyleOptionSizeGrip
- \brief The QStyleOptionSizeGrip class is used to describe the
- parameter for drawing a size grip.
- \since 4.2
-
- QStyleOptionButton contains all the information that QStyle
- functions need to draw QSizeGrip.
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters used by the style functions.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QStyleOptionComplex, QSizeGrip
-*/
-
-/*!
- Constructs a QStyleOptionSizeGrip.
-*/
-QStyleOptionSizeGrip::QStyleOptionSizeGrip()
- : QStyleOptionComplex(Version, Type), corner(Qt::BottomRightCorner)
-{
-}
-
-/*!
- \fn QStyleOptionSizeGrip::QStyleOptionSizeGrip(const QStyleOptionSizeGrip &other)
-
- Constructs a copy of the \a other style option.
-*/
-
-/*!
- \internal
-*/
-QStyleOptionSizeGrip::QStyleOptionSizeGrip(int version)
- : QStyleOptionComplex(version, Type), corner(Qt::BottomRightCorner)
-{
-}
-
-/*!
- \variable QStyleOptionSizeGrip::corner
-
- The corner in which the size grip is located.
-*/
-
-/*!
- \enum QStyleOptionSizeGrip::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l{SO_TabBarBase} for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionSizeGrip::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-#endif // QT_NO_SIZEGRIP
-
-/*!
- \class QStyleOptionGraphicsItem
- \brief The QStyleOptionGraphicsItem class is used to describe
- the parameters needed to draw a QGraphicsItem.
- \since 4.2
- \ingroup graphicsview-api
-
- For performance reasons, the access to the member variables is
- direct (i.e., using the \c . or \c -> operator). This low-level feel
- makes the structures straightforward to use and emphasizes that
- these are simply parameters.
-
- For an example demonstrating how style options can be used, see
- the \l {widgets/styles}{Styles} example.
-
- \sa QStyleOption, QGraphicsItem::paint()
-*/
-
-/*!
- \enum QStyleOptionGraphicsItem::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Type The type of style option provided (\l SO_GraphicsItem for this class).
-
- The type is used internally by QStyleOption, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleOption subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleOptionGraphicsItem::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleOption subclass.
-
- \value Version 1
-
- The version is used by QStyleOption subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- Constructs a QStyleOptionGraphicsItem.
-*/
-QStyleOptionGraphicsItem::QStyleOptionGraphicsItem()
- : QStyleOption(Version, Type), levelOfDetail(1)
-{
-}
-
-/*!
- \internal
-*/
-QStyleOptionGraphicsItem::QStyleOptionGraphicsItem(int version)
- : QStyleOption(version, Type), levelOfDetail(1)
-{
-}
-
-/*!
- \since 4.6
-
- Returns the level of detail from the \a worldTransform.
-
- Its value represents the maximum value of the height and
- width of a unity rectangle, mapped using the \a worldTransform
- of the painter used to draw the item. By default, if no
- transformations are applied, its value is 1. If zoomed out 1:2, the level
- of detail will be 0.5, and if zoomed in 2:1, its value is 2.
-*/
-qreal QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &worldTransform)
-{
- if (worldTransform.type() <= QTransform::TxTranslate)
- return 1; // Translation only? The LOD is 1.
-
- // Two unit vectors.
- QLineF v1(0, 0, 1, 0);
- QLineF v2(0, 0, 0, 1);
- // LOD is the transformed area of a 1x1 rectangle.
- return qSqrt(worldTransform.map(v1).length() * worldTransform.map(v2).length());
-}
-
-/*!
- \fn QStyleOptionGraphicsItem::QStyleOptionGraphicsItem(const QStyleOptionGraphicsItem &other)
-
- Constructs a copy of \a other.
-*/
-
-/*!
- \variable QStyleOptionGraphicsItem::exposedRect
- \brief the exposed rectangle, in item coordinates
-
- Make use of this rectangle to speed up item drawing when only parts of the
- item are exposed. If the whole item is exposed, this rectangle will be the
- same as QGraphicsItem::boundingRect().
-
- This member is only initialized for items that have the
- QGraphicsItem::ItemUsesExtendedStyleOption flag set.
-*/
-
-/*!
- \variable QStyleOptionGraphicsItem::matrix
- \brief the complete transformation matrix for the item
- \obsolete
-
- The QMatrix provided through this member does include information about
- any perspective transformations applied to the view or item. To get the
- correct transformation matrix, use QPainter::transform() on the painter
- passed into the QGraphicsItem::paint() implementation.
-
- This matrix is the combination of the item's scene matrix and the matrix
- of the painter used for drawing the item. It is provided for convenience,
- allowing anvanced level-of-detail metrics that can be used to speed up
- item drawing.
-
- To find the dimensions of an item in screen coordinates (i.e., pixels),
- you can use the mapping functions of QMatrix, such as QMatrix::map().
-
- This member is only initialized for items that have the
- QGraphicsItem::ItemUsesExtendedStyleOption flag set.
-
- \sa QStyleOptionGraphicsItem::levelOfDetailFromTransform()
-*/
-
-/*!
- \variable QStyleOptionGraphicsItem::levelOfDetail
- \obsolete
-
- Use QStyleOptionGraphicsItem::levelOfDetailFromTransform()
- together with QPainter::worldTransform() instead.
-*/
-
-/*!
- \class QStyleHintReturn
- \brief The QStyleHintReturn class provides style hints that return more
- than basic data types.
-
- \ingroup appearance
-
- QStyleHintReturn and its subclasses are used to pass information
- from a style back to the querying widget. This is most useful
- when the return value from QStyle::styleHint() does not provide enough
- detail; for example, when a mask is to be returned.
-
- \omit
- ### --Sam
- \endomit
-*/
-
-/*!
- \enum QStyleHintReturn::HintReturnType
-
- \value SH_Default QStyleHintReturn
- \value SH_Mask \l QStyle::SH_RubberBand_Mask QStyle::SH_FocusFrame_Mask
- \value SH_Variant \l QStyle::SH_TextControl_FocusIndicatorTextCharFormat
-*/
-
-/*!
- \enum QStyleHintReturn::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleHintReturn subclass.
-
- \value Type The type of style option provided (\l SH_Default for
- this class).
-
- The type is used internally by QStyleHintReturn, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleHintReturn subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleHintReturn::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleHintReturn subclass.
-
- \value Version 1
-
- The version is used by QStyleHintReturn subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \variable QStyleHintReturn::type
- \brief the type of the style hint container
-
- \sa HintReturnType
-*/
-
-/*!
- \variable QStyleHintReturn::version
- \brief the version of the style hint return container
-
- This value can be used by subclasses to implement extensions
- without breaking compatibility. If you use qstyleoption_cast<T>(), you
- normally do not need to check it.
-*/
-
-/*!
- Constructs a QStyleHintReturn with version \a version and type \a
- type.
-
- The version has no special meaning for QStyleHintReturn; it can be
- used by subclasses to distinguish between different version of
- the same hint type.
-
- \sa QStyleOption::version, QStyleOption::type
-*/
-
-QStyleHintReturn::QStyleHintReturn(int version, int type)
- : version(version), type(type)
-{
-}
-
-/*!
- \internal
-*/
-
-QStyleHintReturn::~QStyleHintReturn()
-{
-
-}
-
-/*!
- \class QStyleHintReturnMask
- \brief The QStyleHintReturnMask class provides style hints that return a QRegion.
-
- \ingroup appearance
-
- \omit
- ### --Sam
- \endomit
-*/
-
-/*!
- \variable QStyleHintReturnMask::region
- \brief the region for style hints that return a QRegion
-*/
-
-/*!
- Constructs a QStyleHintReturnMask. The member variables are
- initialized to default values.
-*/
-QStyleHintReturnMask::QStyleHintReturnMask() : QStyleHintReturn(Version, Type)
-{
-}
-
-/*!
- \enum QStyleHintReturnMask::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleHintReturn subclass.
-
- \value Type The type of style option provided (\l{SH_Mask} for
- this class).
-
- The type is used internally by QStyleHintReturn, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleHintReturn subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleHintReturnMask::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleHintReturn subclass.
-
- \value Version 1
-
- The version is used by QStyleHintReturn subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \class QStyleHintReturnVariant
- \brief The QStyleHintReturnVariant class provides style hints that return a QVariant.
- \since 4.3
- \ingroup appearance
-*/
-
-/*!
- \variable QStyleHintReturnVariant::variant
- \brief the variant for style hints that return a QVariant
-*/
-
-/*!
- Constructs a QStyleHintReturnVariant. The member variables are
- initialized to default values.
-*/
-QStyleHintReturnVariant::QStyleHintReturnVariant() : QStyleHintReturn(Version, Type)
-{
-}
-
-/*!
- \enum QStyleHintReturnVariant::StyleOptionType
-
- This enum is used to hold information about the type of the style option, and
- is defined for each QStyleHintReturn subclass.
-
- \value Type The type of style option provided (\l{SH_Variant} for
- this class).
-
- The type is used internally by QStyleHintReturn, its subclasses, and
- qstyleoption_cast() to determine the type of style option. In
- general you do not need to worry about this unless you want to
- create your own QStyleHintReturn subclass and your own styles.
-
- \sa StyleOptionVersion
-*/
-
-/*!
- \enum QStyleHintReturnVariant::StyleOptionVersion
-
- This enum is used to hold information about the version of the style option, and
- is defined for each QStyleHintReturn subclass.
-
- \value Version 1
-
- The version is used by QStyleHintReturn subclasses to implement
- extensions without breaking compatibility. If you use
- qstyleoption_cast(), you normally do not need to check it.
-
- \sa StyleOptionType
-*/
-
-/*!
- \fn T qstyleoption_cast<T>(const QStyleHintReturn *hint)
- \relates QStyleHintReturn
-
- Returns a T or 0 depending on the \l{QStyleHintReturn::type}{type}
- and \l{QStyleHintReturn::version}{version} of \a hint.
-
- Example:
-
- \snippet doc/src/snippets/code/src_gui_styles_qstyleoption.cpp 0
-
- \sa QStyleHintReturn::type, QStyleHintReturn::version
-*/
-
-/*!
- \fn T qstyleoption_cast<T>(QStyleHintReturn *hint)
- \overload
- \relates QStyleHintReturn
-
- Returns a T or 0 depending on the type of \a hint.
-*/
-
-#if !defined(QT_NO_DEBUG_STREAM)
-QDebug operator<<(QDebug debug, const QStyleOption::OptionType &optionType)
-{
-#if !defined(QT_NO_DEBUG)
- switch (optionType) {
- case QStyleOption::SO_Default:
- debug << "SO_Default"; break;
- case QStyleOption::SO_FocusRect:
- debug << "SO_FocusRect"; break;
- case QStyleOption::SO_Button:
- debug << "SO_Button"; break;
- case QStyleOption::SO_Tab:
- debug << "SO_Tab"; break;
- case QStyleOption::SO_MenuItem:
- debug << "SO_MenuItem"; break;
- case QStyleOption::SO_Frame:
- debug << "SO_Frame"; break;
- case QStyleOption::SO_ProgressBar:
- debug << "SO_ProgressBar"; break;
- case QStyleOption::SO_ToolBox:
- debug << "SO_ToolBox"; break;
- case QStyleOption::SO_Header:
- debug << "SO_Header"; break;
- case QStyleOption::SO_Q3DockWindow:
- debug << "SO_Q3DockWindow"; break;
- case QStyleOption::SO_DockWidget:
- debug << "SO_DockWidget"; break;
- case QStyleOption::SO_Q3ListViewItem:
- debug << "SO_Q3ListViewItem"; break;
- case QStyleOption::SO_ViewItem:
- debug << "SO_ViewItem"; break;
- case QStyleOption::SO_TabWidgetFrame:
- debug << "SO_TabWidgetFrame"; break;
- case QStyleOption::SO_TabBarBase:
- debug << "SO_TabBarBase"; break;
- case QStyleOption::SO_RubberBand:
- debug << "SO_RubberBand"; break;
- case QStyleOption::SO_Complex:
- debug << "SO_Complex"; break;
- case QStyleOption::SO_Slider:
- debug << "SO_Slider"; break;
- case QStyleOption::SO_SpinBox:
- debug << "SO_SpinBox"; break;
- case QStyleOption::SO_ToolButton:
- debug << "SO_ToolButton"; break;
- case QStyleOption::SO_ComboBox:
- debug << "SO_ComboBox"; break;
- case QStyleOption::SO_Q3ListView:
- debug << "SO_Q3ListView"; break;
- case QStyleOption::SO_TitleBar:
- debug << "SO_TitleBar"; break;
- case QStyleOption::SO_CustomBase:
- debug << "SO_CustomBase"; break;
- case QStyleOption::SO_GroupBox:
- debug << "SO_GroupBox"; break;
- case QStyleOption::SO_ToolBar:
- debug << "SO_ToolBar"; break;
- case QStyleOption::SO_ComplexCustomBase:
- debug << "SO_ComplexCustomBase"; break;
- case QStyleOption::SO_SizeGrip:
- debug << "SO_SizeGrip"; break;
- case QStyleOption::SO_GraphicsItem:
- debug << "SO_GraphicsItem"; break;
- }
-#else
- Q_UNUSED(optionType);
-#endif
- return debug;
-}
-
-QDebug operator<<(QDebug debug, const QStyleOption &option)
-{
-#if !defined(QT_NO_DEBUG)
- debug << "QStyleOption(";
- debug << QStyleOption::OptionType(option.type);
- debug << ',' << (option.direction == Qt::RightToLeft ? "RightToLeft" : "LeftToRight");
- debug << ',' << option.state;
- debug << ',' << option.rect;
- debug << ')';
-#else
- Q_UNUSED(option);
-#endif
- return debug;
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstyleoption.h b/src/gui/styles/qstyleoption.h
deleted file mode 100644
index 1b1de9cdf2..0000000000
--- a/src/gui/styles/qstyleoption.h
+++ /dev/null
@@ -1,970 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLEOPTION_H
-#define QSTYLEOPTION_H
-
-#include <QtCore/qvariant.h>
-#include <QtGui/qabstractspinbox.h>
-#include <QtGui/qicon.h>
-#include <QtGui/qmatrix.h>
-#include <QtGui/qslider.h>
-#include <QtGui/qstyle.h>
-#include <QtGui/qtabbar.h>
-#include <QtGui/qtabwidget.h>
-#include <QtGui/qrubberband.h>
-#include <QtGui/qframe.h>
-#ifndef QT_NO_ITEMVIEWS
-# include <QtCore/qabstractitemmodel.h>
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QDebug;
-
-class Q_GUI_EXPORT QStyleOption
-{
-public:
- enum OptionType {
- SO_Default, SO_FocusRect, SO_Button, SO_Tab, SO_MenuItem,
- SO_Frame, SO_ProgressBar, SO_ToolBox, SO_Header, SO_Q3DockWindow,
- SO_DockWidget, SO_Q3ListViewItem, SO_ViewItem, SO_TabWidgetFrame,
- SO_TabBarBase, SO_RubberBand, SO_ToolBar, SO_GraphicsItem,
-
- SO_Complex = 0xf0000, SO_Slider, SO_SpinBox, SO_ToolButton, SO_ComboBox,
- SO_Q3ListView, SO_TitleBar, SO_GroupBox, SO_SizeGrip,
-
- SO_CustomBase = 0xf00,
- SO_ComplexCustomBase = 0xf000000
- };
-
- enum StyleOptionType { Type = SO_Default };
- enum StyleOptionVersion { Version = 1 };
-
- int version;
- int type;
- QStyle::State state;
- Qt::LayoutDirection direction;
- QRect rect;
- QFontMetrics fontMetrics;
- QPalette palette;
-
- QStyleOption(int version = QStyleOption::Version, int type = SO_Default);
- QStyleOption(const QStyleOption &other);
- ~QStyleOption();
-
- void init(const QWidget *w);
- inline void initFrom(const QWidget *w) { init(w); }
- QStyleOption &operator=(const QStyleOption &other);
-};
-
-class Q_GUI_EXPORT QStyleOptionFocusRect : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_FocusRect };
- enum StyleOptionVersion { Version = 1 };
-
- QColor backgroundColor;
-
- QStyleOptionFocusRect();
- QStyleOptionFocusRect(const QStyleOptionFocusRect &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionFocusRect(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionFrame : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Frame };
- enum StyleOptionVersion { Version = 1 };
-
- int lineWidth;
- int midLineWidth;
-
- QStyleOptionFrame();
- QStyleOptionFrame(const QStyleOptionFrame &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionFrame(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionFrameV2 : public QStyleOptionFrame
-{
-public:
- enum StyleOptionVersion { Version = 2 };
- enum FrameFeature {
- None = 0x00,
- Flat = 0x01
- };
- Q_DECLARE_FLAGS(FrameFeatures, FrameFeature)
- FrameFeatures features;
-
- QStyleOptionFrameV2();
- QStyleOptionFrameV2(const QStyleOptionFrameV2 &other) : QStyleOptionFrame(Version) { *this = other; }
- QStyleOptionFrameV2(const QStyleOptionFrame &other);
- QStyleOptionFrameV2 &operator=(const QStyleOptionFrame &other);
-
-protected:
- QStyleOptionFrameV2(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionFrameV2::FrameFeatures)
-
-
-class Q_GUI_EXPORT QStyleOptionFrameV3 : public QStyleOptionFrameV2
-{
-public:
- enum StyleOptionVersion { Version = 3 };
- QFrame::Shape frameShape : 4;
- uint unused : 28;
-
- QStyleOptionFrameV3();
- QStyleOptionFrameV3(const QStyleOptionFrameV3 &other) : QStyleOptionFrameV2(Version) { *this = other; }
- QStyleOptionFrameV3(const QStyleOptionFrame &other);
- QStyleOptionFrameV3 &operator=(const QStyleOptionFrame &other);
-
-protected:
- QStyleOptionFrameV3(int version);
-};
-
-
-#ifndef QT_NO_TABWIDGET
-class Q_GUI_EXPORT QStyleOptionTabWidgetFrame : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_TabWidgetFrame };
- enum StyleOptionVersion { Version = 1 };
-
- int lineWidth;
- int midLineWidth;
- QTabBar::Shape shape;
- QSize tabBarSize;
- QSize rightCornerWidgetSize;
- QSize leftCornerWidgetSize;
-
- QStyleOptionTabWidgetFrame();
- inline QStyleOptionTabWidgetFrame(const QStyleOptionTabWidgetFrame &other)
- : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionTabWidgetFrame(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionTabWidgetFrameV2 : public QStyleOptionTabWidgetFrame
-{
-public:
- enum StyleOptionVersion { Version = 2 };
-
- QRect tabBarRect;
- QRect selectedTabRect;
-
- QStyleOptionTabWidgetFrameV2();
- QStyleOptionTabWidgetFrameV2(const QStyleOptionTabWidgetFrameV2 &other) :
- QStyleOptionTabWidgetFrame(Version) { *this = other; }
- QStyleOptionTabWidgetFrameV2(const QStyleOptionTabWidgetFrame &other);
- QStyleOptionTabWidgetFrameV2 &operator=(const QStyleOptionTabWidgetFrame &other);
-
-protected:
- QStyleOptionTabWidgetFrameV2(int version);
-};
-
-#endif
-
-
-#ifndef QT_NO_TABBAR
-class Q_GUI_EXPORT QStyleOptionTabBarBase : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_TabBarBase };
- enum StyleOptionVersion { Version = 1 };
-
- QTabBar::Shape shape;
- QRect tabBarRect;
- QRect selectedTabRect;
-
- QStyleOptionTabBarBase();
- QStyleOptionTabBarBase(const QStyleOptionTabBarBase &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionTabBarBase(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionTabBarBaseV2 : public QStyleOptionTabBarBase
-{
-public:
- enum StyleOptionVersion { Version = 2 };
- bool documentMode;
- QStyleOptionTabBarBaseV2();
- QStyleOptionTabBarBaseV2(const QStyleOptionTabBarBaseV2 &other) : QStyleOptionTabBarBase(Version) { *this = other; }
- QStyleOptionTabBarBaseV2(const QStyleOptionTabBarBase &other);
- QStyleOptionTabBarBaseV2 &operator=(const QStyleOptionTabBarBase &other);
-
-protected:
- QStyleOptionTabBarBaseV2(int version);
-};
-
-#endif
-
-class Q_GUI_EXPORT QStyleOptionHeader : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Header };
- enum StyleOptionVersion { Version = 1 };
-
- enum SectionPosition { Beginning, Middle, End, OnlyOneSection };
- enum SelectedPosition { NotAdjacent, NextIsSelected, PreviousIsSelected,
- NextAndPreviousAreSelected };
- enum SortIndicator { None, SortUp, SortDown };
-
- int section;
- QString text;
- Qt::Alignment textAlignment;
- QIcon icon;
- Qt::Alignment iconAlignment;
- SectionPosition position;
- SelectedPosition selectedPosition;
- SortIndicator sortIndicator;
- Qt::Orientation orientation;
-
- QStyleOptionHeader();
- QStyleOptionHeader(const QStyleOptionHeader &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionHeader(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionButton : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Button };
- enum StyleOptionVersion { Version = 1 };
-
- enum ButtonFeature { None = 0x00, Flat = 0x01, HasMenu = 0x02, DefaultButton = 0x04,
- AutoDefaultButton = 0x08, CommandLinkButton = 0x10 };
- Q_DECLARE_FLAGS(ButtonFeatures, ButtonFeature)
-
- ButtonFeatures features;
- QString text;
- QIcon icon;
- QSize iconSize;
-
- QStyleOptionButton();
- QStyleOptionButton(const QStyleOptionButton &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionButton(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionButton::ButtonFeatures)
-
-#ifndef QT_NO_TABBAR
-class Q_GUI_EXPORT QStyleOptionTab : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Tab };
- enum StyleOptionVersion { Version = 1 };
-
- enum TabPosition { Beginning, Middle, End, OnlyOneTab };
- enum SelectedPosition { NotAdjacent, NextIsSelected, PreviousIsSelected };
- enum CornerWidget { NoCornerWidgets = 0x00, LeftCornerWidget = 0x01,
- RightCornerWidget = 0x02 };
- Q_DECLARE_FLAGS(CornerWidgets, CornerWidget)
-
- QTabBar::Shape shape;
- QString text;
- QIcon icon;
- int row;
- TabPosition position;
- SelectedPosition selectedPosition;
- CornerWidgets cornerWidgets;
-
- QStyleOptionTab();
- QStyleOptionTab(const QStyleOptionTab &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionTab(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionTab::CornerWidgets)
-
-class Q_GUI_EXPORT QStyleOptionTabV2 : public QStyleOptionTab
-{
-public:
- enum StyleOptionVersion { Version = 2 };
- QSize iconSize;
- QStyleOptionTabV2();
- QStyleOptionTabV2(const QStyleOptionTabV2 &other) : QStyleOptionTab(Version) { *this = other; }
- QStyleOptionTabV2(const QStyleOptionTab &other);
- QStyleOptionTabV2 &operator=(const QStyleOptionTab &other);
-
-protected:
- QStyleOptionTabV2(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionTabV3 : public QStyleOptionTabV2
-{
-public:
- enum StyleOptionVersion { Version = 3 };
- bool documentMode;
- QSize leftButtonSize;
- QSize rightButtonSize;
- QStyleOptionTabV3();
- QStyleOptionTabV3(const QStyleOptionTabV3 &other) : QStyleOptionTabV2(Version) { *this = other; }
- QStyleOptionTabV3(const QStyleOptionTabV2 &other) : QStyleOptionTabV2(Version) { *this = other; }
- QStyleOptionTabV3(const QStyleOptionTab &other);
- QStyleOptionTabV3 &operator=(const QStyleOptionTab &other);
-
-protected:
- QStyleOptionTabV3(int version);
-};
-
-#endif
-
-
-#ifndef QT_NO_TOOLBAR
-
-class Q_GUI_EXPORT QStyleOptionToolBar : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_ToolBar };
- enum StyleOptionVersion { Version = 1 };
- enum ToolBarPosition { Beginning, Middle, End, OnlyOne };
- enum ToolBarFeature { None = 0x0, Movable = 0x1 };
- Q_DECLARE_FLAGS(ToolBarFeatures, ToolBarFeature)
- ToolBarPosition positionOfLine; // The toolbar line position
- ToolBarPosition positionWithinLine; // The position within a toolbar
- Qt::ToolBarArea toolBarArea; // The toolbar docking area
- ToolBarFeatures features;
- int lineWidth;
- int midLineWidth;
- QStyleOptionToolBar();
- QStyleOptionToolBar(const QStyleOptionToolBar &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionToolBar(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionToolBar::ToolBarFeatures)
-
-#endif
-
-
-
-class Q_GUI_EXPORT QStyleOptionProgressBar : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_ProgressBar };
- enum StyleOptionVersion { Version = 1 };
-
- int minimum;
- int maximum;
- int progress;
- QString text;
- Qt::Alignment textAlignment;
- bool textVisible;
-
- QStyleOptionProgressBar();
- QStyleOptionProgressBar(const QStyleOptionProgressBar &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionProgressBar(int version);
-};
-
-// Adds style info for vertical progress bars
-class Q_GUI_EXPORT QStyleOptionProgressBarV2 : public QStyleOptionProgressBar
-{
-public:
- enum StyleOptionType { Type = SO_ProgressBar };
- enum StyleOptionVersion { Version = 2 };
- Qt::Orientation orientation;
- bool invertedAppearance;
- bool bottomToTop;
-
- QStyleOptionProgressBarV2();
- QStyleOptionProgressBarV2(const QStyleOptionProgressBar &other);
- QStyleOptionProgressBarV2(const QStyleOptionProgressBarV2 &other);
- QStyleOptionProgressBarV2 &operator=(const QStyleOptionProgressBar &other);
-
-protected:
- QStyleOptionProgressBarV2(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionMenuItem : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_MenuItem };
- enum StyleOptionVersion { Version = 1 };
-
- enum MenuItemType { Normal, DefaultItem, Separator, SubMenu, Scroller, TearOff, Margin,
- EmptyArea };
- enum CheckType { NotCheckable, Exclusive, NonExclusive };
-
- MenuItemType menuItemType;
- CheckType checkType;
- bool checked;
- bool menuHasCheckableItems;
- QRect menuRect;
- QString text;
- QIcon icon;
- int maxIconWidth;
- int tabWidth;
- QFont font;
-
- QStyleOptionMenuItem();
- QStyleOptionMenuItem(const QStyleOptionMenuItem &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionMenuItem(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionQ3ListViewItem : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Q3ListViewItem };
- enum StyleOptionVersion { Version = 1 };
-
- enum Q3ListViewItemFeature { None = 0x00, Expandable = 0x01, MultiLine = 0x02, Visible = 0x04,
- ParentControl = 0x08 };
- Q_DECLARE_FLAGS(Q3ListViewItemFeatures, Q3ListViewItemFeature)
-
- Q3ListViewItemFeatures features;
- int height;
- int totalHeight;
- int itemY;
- int childCount;
-
- QStyleOptionQ3ListViewItem();
- QStyleOptionQ3ListViewItem(const QStyleOptionQ3ListViewItem &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionQ3ListViewItem(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionQ3ListViewItem::Q3ListViewItemFeatures)
-
-class Q_GUI_EXPORT QStyleOptionQ3DockWindow : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Q3DockWindow };
- enum StyleOptionVersion { Version = 1 };
-
- bool docked;
- bool closeEnabled;
-
- QStyleOptionQ3DockWindow();
- QStyleOptionQ3DockWindow(const QStyleOptionQ3DockWindow &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionQ3DockWindow(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionDockWidget : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_DockWidget };
- enum StyleOptionVersion { Version = 1 };
-
- QString title;
- bool closable;
- bool movable;
- bool floatable;
-
- QStyleOptionDockWidget();
- QStyleOptionDockWidget(const QStyleOptionDockWidget &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionDockWidget(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionDockWidgetV2 : public QStyleOptionDockWidget
-{
-public:
- enum StyleOptionVersion { Version = 2 };
-
- bool verticalTitleBar;
-
- QStyleOptionDockWidgetV2();
- QStyleOptionDockWidgetV2(const QStyleOptionDockWidgetV2 &other)
- : QStyleOptionDockWidget(Version) { *this = other; }
- QStyleOptionDockWidgetV2(const QStyleOptionDockWidget &other);
- QStyleOptionDockWidgetV2 &operator = (const QStyleOptionDockWidget &other);
-
-protected:
- QStyleOptionDockWidgetV2(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionViewItem : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_ViewItem };
- enum StyleOptionVersion { Version = 1 };
-
- enum Position { Left, Right, Top, Bottom };
-
- Qt::Alignment displayAlignment;
- Qt::Alignment decorationAlignment;
- Qt::TextElideMode textElideMode;
- Position decorationPosition;
- QSize decorationSize;
- QFont font;
- bool showDecorationSelected;
-
- QStyleOptionViewItem();
- QStyleOptionViewItem(const QStyleOptionViewItem &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionViewItem(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionViewItemV2 : public QStyleOptionViewItem
-{
-public:
- enum StyleOptionVersion { Version = 2 };
-
- enum ViewItemFeature {
- None = 0x00,
- WrapText = 0x01,
- Alternate = 0x02,
- HasCheckIndicator = 0x04,
- HasDisplay = 0x08,
- HasDecoration = 0x10
- };
- Q_DECLARE_FLAGS(ViewItemFeatures, ViewItemFeature)
-
- ViewItemFeatures features;
-
- QStyleOptionViewItemV2();
- QStyleOptionViewItemV2(const QStyleOptionViewItemV2 &other) : QStyleOptionViewItem(Version) { *this = other; }
- QStyleOptionViewItemV2(const QStyleOptionViewItem &other);
- QStyleOptionViewItemV2 &operator=(const QStyleOptionViewItem &other);
-
-protected:
- QStyleOptionViewItemV2(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionViewItemV2::ViewItemFeatures)
-
-class Q_GUI_EXPORT QStyleOptionViewItemV3 : public QStyleOptionViewItemV2
-{
-public:
- enum StyleOptionVersion { Version = 3 };
-
- QLocale locale;
- const QWidget *widget;
-
- QStyleOptionViewItemV3();
- QStyleOptionViewItemV3(const QStyleOptionViewItemV3 &other)
- : QStyleOptionViewItemV2(Version) { *this = other; }
- QStyleOptionViewItemV3(const QStyleOptionViewItem &other);
- QStyleOptionViewItemV3 &operator = (const QStyleOptionViewItem &other);
-
-protected:
- QStyleOptionViewItemV3(int version);
-};
-
-#ifndef QT_NO_ITEMVIEWS
-class Q_GUI_EXPORT QStyleOptionViewItemV4 : public QStyleOptionViewItemV3
-{
-public:
- enum StyleOptionVersion { Version = 4 };
- enum ViewItemPosition { Invalid, Beginning, Middle, End, OnlyOne };
-
- QModelIndex index;
- Qt::CheckState checkState;
- QIcon icon;
- QString text;
- ViewItemPosition viewItemPosition;
- QBrush backgroundBrush;
-
- QStyleOptionViewItemV4();
- QStyleOptionViewItemV4(const QStyleOptionViewItemV4 &other)
- : QStyleOptionViewItemV3(Version) { *this = other; }
- QStyleOptionViewItemV4(const QStyleOptionViewItem &other);
- QStyleOptionViewItemV4 &operator = (const QStyleOptionViewItem &other);
-
-protected:
- QStyleOptionViewItemV4(int version);
-};
-#endif
-
-class Q_GUI_EXPORT QStyleOptionToolBox : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_ToolBox };
- enum StyleOptionVersion { Version = 1 };
-
- QString text;
- QIcon icon;
-
- QStyleOptionToolBox();
- QStyleOptionToolBox(const QStyleOptionToolBox &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionToolBox(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionToolBoxV2 : public QStyleOptionToolBox
-{
-public:
- enum StyleOptionVersion { Version = 2 };
- enum TabPosition { Beginning, Middle, End, OnlyOneTab };
- enum SelectedPosition { NotAdjacent, NextIsSelected, PreviousIsSelected };
-
- TabPosition position;
- SelectedPosition selectedPosition;
-
- QStyleOptionToolBoxV2();
- QStyleOptionToolBoxV2(const QStyleOptionToolBoxV2 &other) : QStyleOptionToolBox(Version) { *this = other; }
- QStyleOptionToolBoxV2(const QStyleOptionToolBox &other);
- QStyleOptionToolBoxV2 &operator=(const QStyleOptionToolBox &other);
-
-protected:
- QStyleOptionToolBoxV2(int version);
-};
-
-#ifndef QT_NO_RUBBERBAND
-class Q_GUI_EXPORT QStyleOptionRubberBand : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_RubberBand };
- enum StyleOptionVersion { Version = 1 };
-
- QRubberBand::Shape shape;
- bool opaque;
-
- QStyleOptionRubberBand();
- QStyleOptionRubberBand(const QStyleOptionRubberBand &other) : QStyleOption(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionRubberBand(int version);
-};
-#endif // QT_NO_RUBBERBAND
-
-// -------------------------- Complex style options -------------------------------
-class Q_GUI_EXPORT QStyleOptionComplex : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_Complex };
- enum StyleOptionVersion { Version = 1 };
-
- QStyle::SubControls subControls;
- QStyle::SubControls activeSubControls;
-
- QStyleOptionComplex(int version = QStyleOptionComplex::Version, int type = SO_Complex);
- QStyleOptionComplex(const QStyleOptionComplex &other) : QStyleOption(Version, Type) { *this = other; }
-};
-
-#ifndef QT_NO_SLIDER
-class Q_GUI_EXPORT QStyleOptionSlider : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_Slider };
- enum StyleOptionVersion { Version = 1 };
-
- Qt::Orientation orientation;
- int minimum;
- int maximum;
- QSlider::TickPosition tickPosition;
- int tickInterval;
- bool upsideDown;
- int sliderPosition;
- int sliderValue;
- int singleStep;
- int pageStep;
- qreal notchTarget;
- bool dialWrapping;
-
- QStyleOptionSlider();
- QStyleOptionSlider(const QStyleOptionSlider &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionSlider(int version);
-};
-#endif // QT_NO_SLIDER
-
-#ifndef QT_NO_SPINBOX
-class Q_GUI_EXPORT QStyleOptionSpinBox : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_SpinBox };
- enum StyleOptionVersion { Version = 1 };
-
- QAbstractSpinBox::ButtonSymbols buttonSymbols;
- QAbstractSpinBox::StepEnabled stepEnabled;
- bool frame;
-
- QStyleOptionSpinBox();
- QStyleOptionSpinBox(const QStyleOptionSpinBox &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionSpinBox(int version);
-};
-#endif // QT_NO_SPINBOX
-
-class Q_GUI_EXPORT QStyleOptionQ3ListView : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_Q3ListView };
- enum StyleOptionVersion { Version = 1 };
-
- QList<QStyleOptionQ3ListViewItem> items;
- QPalette viewportPalette;
- QPalette::ColorRole viewportBGRole;
- int sortColumn;
- int itemMargin;
- int treeStepSize;
- bool rootIsDecorated;
-
- QStyleOptionQ3ListView();
- QStyleOptionQ3ListView(const QStyleOptionQ3ListView &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionQ3ListView(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionToolButton : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_ToolButton };
- enum StyleOptionVersion { Version = 1 };
-
- enum ToolButtonFeature { None = 0x00, Arrow = 0x01, Menu = 0x04, MenuButtonPopup = Menu, PopupDelay = 0x08,
- HasMenu = 0x10 };
- Q_DECLARE_FLAGS(ToolButtonFeatures, ToolButtonFeature)
-
- ToolButtonFeatures features;
- QIcon icon;
- QSize iconSize;
- QString text;
- Qt::ArrowType arrowType;
- Qt::ToolButtonStyle toolButtonStyle;
- QPoint pos;
- QFont font;
-
- QStyleOptionToolButton();
- QStyleOptionToolButton(const QStyleOptionToolButton &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionToolButton(int version);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QStyleOptionToolButton::ToolButtonFeatures)
-
-class Q_GUI_EXPORT QStyleOptionComboBox : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_ComboBox };
- enum StyleOptionVersion { Version = 1 };
-
- bool editable;
- QRect popupRect;
- bool frame;
- QString currentText;
- QIcon currentIcon;
- QSize iconSize;
-
- QStyleOptionComboBox();
- QStyleOptionComboBox(const QStyleOptionComboBox &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionComboBox(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionTitleBar : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_TitleBar };
- enum StyleOptionVersion { Version = 1 };
-
- QString text;
- QIcon icon;
- int titleBarState;
- Qt::WindowFlags titleBarFlags;
-
- QStyleOptionTitleBar();
- QStyleOptionTitleBar(const QStyleOptionTitleBar &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-
-protected:
- QStyleOptionTitleBar(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionGroupBox : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_GroupBox };
- enum StyleOptionVersion { Version = 1 };
-
- QStyleOptionFrameV2::FrameFeatures features;
- QString text;
- Qt::Alignment textAlignment;
- QColor textColor;
- int lineWidth;
- int midLineWidth;
-
- QStyleOptionGroupBox();
- QStyleOptionGroupBox(const QStyleOptionGroupBox &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-protected:
- QStyleOptionGroupBox(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionSizeGrip : public QStyleOptionComplex
-{
-public:
- enum StyleOptionType { Type = SO_SizeGrip };
- enum StyleOptionVersion { Version = 1 };
-
- Qt::Corner corner;
-
- QStyleOptionSizeGrip();
- QStyleOptionSizeGrip(const QStyleOptionSizeGrip &other) : QStyleOptionComplex(Version, Type) { *this = other; }
-protected:
- QStyleOptionSizeGrip(int version);
-};
-
-class Q_GUI_EXPORT QStyleOptionGraphicsItem : public QStyleOption
-{
-public:
- enum StyleOptionType { Type = SO_GraphicsItem };
- enum StyleOptionVersion { Version = 1 };
-
- QRectF exposedRect;
- QMatrix matrix;
- qreal levelOfDetail;
-
- QStyleOptionGraphicsItem();
- QStyleOptionGraphicsItem(const QStyleOptionGraphicsItem &other) : QStyleOption(Version, Type) { *this = other; }
- static qreal levelOfDetailFromTransform(const QTransform &worldTransform);
-protected:
- QStyleOptionGraphicsItem(int version);
-};
-
-template <typename T>
-T qstyleoption_cast(const QStyleOption *opt)
-{
- if (opt && opt->version >= static_cast<T>(0)->Version && (opt->type == static_cast<T>(0)->Type
- || int(static_cast<T>(0)->Type) == QStyleOption::SO_Default
- || (int(static_cast<T>(0)->Type) == QStyleOption::SO_Complex
- && opt->type > QStyleOption::SO_Complex)))
- return static_cast<T>(opt);
- return 0;
-}
-
-template <typename T>
-T qstyleoption_cast(QStyleOption *opt)
-{
- if (opt && opt->version >= static_cast<T>(0)->Version && (opt->type == static_cast<T>(0)->Type
- || int(static_cast<T>(0)->Type) == QStyleOption::SO_Default
- || (int(static_cast<T>(0)->Type) == QStyleOption::SO_Complex
- && opt->type > QStyleOption::SO_Complex)))
- return static_cast<T>(opt);
- return 0;
-}
-
-// -------------------------- QStyleHintReturn -------------------------------
-class Q_GUI_EXPORT QStyleHintReturn {
-public:
- enum HintReturnType {
- SH_Default=0xf000, SH_Mask, SH_Variant
- };
-
- enum StyleOptionType { Type = SH_Default };
- enum StyleOptionVersion { Version = 1 };
-
- QStyleHintReturn(int version = QStyleOption::Version, int type = SH_Default);
- ~QStyleHintReturn();
-
- int version;
- int type;
-};
-
-class Q_GUI_EXPORT QStyleHintReturnMask : public QStyleHintReturn {
-public:
- enum StyleOptionType { Type = SH_Mask };
- enum StyleOptionVersion { Version = 1 };
-
- QStyleHintReturnMask();
-
- QRegion region;
-};
-
-class Q_GUI_EXPORT QStyleHintReturnVariant : public QStyleHintReturn {
-public:
- enum StyleOptionType { Type = SH_Variant };
- enum StyleOptionVersion { Version = 1 };
-
- QStyleHintReturnVariant();
-
- QVariant variant;
-};
-
-template <typename T>
-T qstyleoption_cast(const QStyleHintReturn *hint)
-{
- if (hint && hint->version <= static_cast<T>(0)->Version &&
- (hint->type == static_cast<T>(0)->Type || int(static_cast<T>(0)->Type) == QStyleHintReturn::SH_Default))
- return static_cast<T>(hint);
- return 0;
-}
-
-template <typename T>
-T qstyleoption_cast(QStyleHintReturn *hint)
-{
- if (hint && hint->version <= static_cast<T>(0)->Version &&
- (hint->type == static_cast<T>(0)->Type || int(static_cast<T>(0)->Type) == QStyleHintReturn::SH_Default))
- return static_cast<T>(hint);
- return 0;
-}
-
-#if !defined(QT_NO_DEBUG_STREAM)
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, const QStyleOption::OptionType &optionType);
-Q_GUI_EXPORT QDebug operator<<(QDebug debug, const QStyleOption &option);
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTYLEOPTION_H
diff --git a/src/gui/styles/qstylepainter.cpp b/src/gui/styles/qstylepainter.cpp
deleted file mode 100644
index c8f9d05315..0000000000
--- a/src/gui/styles/qstylepainter.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstylepainter.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QStylePainter
-
- \brief The QStylePainter class is a convenience class for drawing QStyle
- elements inside a widget.
-
- \ingroup appearance
- \ingroup painting
-
- QStylePainter extends QPainter with a set of high-level \c
- draw...() functions implemented on top of QStyle's API. The
- advantage of using QStylePainter is that the parameter lists get
- considerably shorter. Whereas a QStyle object must be able to
- draw on any widget using any painter (because the application
- normally has one QStyle object shared by all widget), a
- QStylePainter is initialized with a widget, eliminating the need
- to specify the QWidget, the QPainter, and the QStyle for every
- function call.
-
- Example using QStyle directly:
-
- \snippet doc/src/snippets/styles/styles.cpp 1
-
- Example using QStylePainter:
-
- \snippet doc/src/snippets/styles/styles.cpp 0
- \snippet doc/src/snippets/styles/styles.cpp 4
- \snippet doc/src/snippets/styles/styles.cpp 6
-
- \sa QStyle, QStyleOption
-*/
-
-/*!
- \fn QStylePainter::QStylePainter()
-
- Constructs a QStylePainter.
-*/
-
-/*!
- \fn QStylePainter::QStylePainter(QWidget *widget)
-
- Construct a QStylePainter using widget \a widget for its paint device.
-*/
-
-/*!
- \fn QStylePainter::QStylePainter(QPaintDevice *pd, QWidget *widget)
-
- Construct a QStylePainter using \a pd for its paint device, and
- attributes from \a widget.
-*/
-
-
-/*!
- \fn bool QStylePainter::begin(QWidget *widget)
-
- Begin painting operations on the specified \a widget.
- Returns true if the painter is ready to use; otherwise returns false.
-
- This is automatically called by the constructor that takes a QWidget.
-*/
-
-/*!
- \fn bool QStylePainter::begin(QPaintDevice *pd, QWidget *widget)
- \overload
-
- Begin painting operations on paint device \a pd as if it was \a
- widget.
-
- This is automatically called by the constructor that
- takes a QPaintDevice and a QWidget.
-*/
-
-
-/*!
- \fn void QStylePainter::drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &option)
-
- Use the widget's style to draw a primitive element \a pe specified by QStyleOption \a option.
-
- \sa QStyle::drawPrimitive()
-*/
-
-/*!
- \fn void QStylePainter::drawControl(QStyle::ControlElement ce, const QStyleOption &option)
-
- Use the widget's style to draw a control element \a ce specified by QStyleOption \a option.
-
- \sa QStyle::drawControl()
-*/
-
-/*!
- \fn void QStylePainter::drawComplexControl(QStyle::ComplexControl cc,
- const QStyleOptionComplex &option)
-
- Use the widget's style to draw a complex control \a cc specified by the
- QStyleOptionComplex \a option.
-
- \sa QStyle::drawComplexControl()
-*/
-
-/*!
- \fn void QStylePainter::drawItemText(const QRect &rect, int flags, const QPalette &pal,
- bool enabled, const QString &text,
- QPalette::ColorRole textRole = QPalette::NoRole)
-
- Draws the \a text in rectangle \a rect and palette \a pal.
- The text is aligned and wrapped according to \a
- flags.
-
- The pen color is specified with \a textRole. The \a enabled bool
- indicates whether or not the item is enabled; when reimplementing
- this bool should influence how the item is drawn.
-
- \sa QStyle::drawItemText(), Qt::Alignment
-*/
-
-/*!
- \fn void QStylePainter::drawItemPixmap(const QRect &rect, int flags, const QPixmap &pixmap)
-
- Draws the \a pixmap in rectangle \a rect.
- The pixmap is aligned according to \a flags.
-
- \sa QStyle::drawItemPixmap(), Qt::Alignment
-*/
-
-/*!
- \fn QStyle *QStylePainter::style() const
-
- Return the current style used by the QStylePainter.
-*/
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstylepainter.h b/src/gui/styles/qstylepainter.h
deleted file mode 100644
index 0fc3f2b4b9..0000000000
--- a/src/gui/styles/qstylepainter.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLEPAINTER_H
-#define QSTYLEPAINTER_H
-
-#include <QtGui/qpainter.h>
-#include <QtGui/qstyle.h>
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStylePainter : public QPainter
-{
-public:
- inline QStylePainter() : QPainter(), widget(0), wstyle(0) {}
- inline explicit QStylePainter(QWidget *w) { begin(w, w); }
- inline QStylePainter(QPaintDevice *pd, QWidget *w) { begin(pd, w); }
- inline bool begin(QWidget *w) { return begin(w, w); }
- inline bool begin(QPaintDevice *pd, QWidget *w) {
- Q_ASSERT_X(w, "QStylePainter::QStylePainter", "Widget must be non-zero");
- widget = w;
- wstyle = w->style();
- return QPainter::begin(pd);
- };
- inline void drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &opt);
- inline void drawControl(QStyle::ControlElement ce, const QStyleOption &opt);
- inline void drawComplexControl(QStyle::ComplexControl cc, const QStyleOptionComplex &opt);
- inline void drawItemText(const QRect &r, int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole = QPalette::NoRole);
- inline void drawItemPixmap(const QRect &r, int flags, const QPixmap &pixmap);
- inline QStyle *style() const { return wstyle; }
-
-private:
- QWidget *widget;
- QStyle *wstyle;
- Q_DISABLE_COPY(QStylePainter)
-};
-
-void QStylePainter::drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &opt)
-{
- wstyle->drawPrimitive(pe, &opt, this, widget);
-}
-
-void QStylePainter::drawControl(QStyle::ControlElement ce, const QStyleOption &opt)
-{
- wstyle->drawControl(ce, &opt, this, widget);
-}
-
-void QStylePainter::drawComplexControl(QStyle::ComplexControl cc, const QStyleOptionComplex &opt)
-{
- wstyle->drawComplexControl(cc, &opt, this, widget);
-}
-
-void QStylePainter::drawItemText(const QRect &r, int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole)
-{
- wstyle->drawItemText(this, r, flags, pal, enabled, text, textRole);
-}
-
-void QStylePainter::drawItemPixmap(const QRect &r, int flags, const QPixmap &pixmap)
-{
- wstyle->drawItemPixmap(this, r, flags, pixmap);
-}
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTYLEPAINTER_H
diff --git a/src/gui/styles/qstyleplugin.cpp b/src/gui/styles/qstyleplugin.cpp
deleted file mode 100644
index f2143e307a..0000000000
--- a/src/gui/styles/qstyleplugin.cpp
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstyleplugin.h"
-#include "qstyle.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QStylePlugin
- \brief The QStylePlugin class provides an abstract base for custom QStyle plugins.
-
- \ingroup plugins
-
- QStylePlugin is a simple plugin interface that makes it easy
- to create custom styles that can be loaded dynamically into
- applications using the QStyleFactory class.
-
- Writing a style plugin is achieved by subclassing this base class,
- reimplementing the pure virtual keys() and create() functions, and
- exporting the class using the Q_EXPORT_PLUGIN2() macro. See \l
- {How to Create Qt Plugins} for details.
-
- \sa QStyleFactory, QStyle
-*/
-
-/*!
- \fn QStringList QStylePlugin::keys() const
-
- Returns the list of style keys this plugin supports.
-
- These keys are usually the class names of the custom styles that
- are implemented in the plugin.
-
- \sa create()
-*/
-
-/*!
- \fn QStyle *QStylePlugin::create(const QString& key)
-
- Creates and returns a QStyle object for the given style \a key.
- If a plugin cannot create a style, it should return 0 instead.
-
- The style key is usually the class name of the required
- style. Note that the keys are case insensitive. For example:
-
- \snippet doc/src/snippets/qstyleplugin/main.cpp 0
- \codeline
- \snippet doc/src/snippets/qstyleplugin/main.cpp 1
- \snippet doc/src/snippets/qstyleplugin/main.cpp 2
-
- \sa keys()
-*/
-
-/*!
- Constructs a style plugin with the given \a parent.
-
- Note that this constructor is invoked automatically by the
- Q_EXPORT_PLUGIN2() macro, so there is no need for calling it
- explicitly.
-*/
-QStylePlugin::QStylePlugin(QObject *parent)
- : QObject(parent)
-{
-}
-
-/*!
- Destroys the style plugin.
-
- Note that Qt destroys a plugin automatically when it is no longer
- used, so there is no need for calling the destructor explicitly.
-*/
-QStylePlugin::~QStylePlugin()
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstyleplugin.h b/src/gui/styles/qstyleplugin.h
deleted file mode 100644
index 56d690f6ff..0000000000
--- a/src/gui/styles/qstyleplugin.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLEPLUGIN_H
-#define QSTYLEPLUGIN_H
-
-#include <QtCore/qplugin.h>
-#include <QtCore/qfactoryinterface.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStyle;
-
-struct Q_GUI_EXPORT QStyleFactoryInterface : public QFactoryInterface
-{
- virtual QStyle *create(const QString &key) = 0;
-};
-
-#define QStyleFactoryInterface_iid "com.trolltech.Qt.QStyleFactoryInterface"
-
-Q_DECLARE_INTERFACE(QStyleFactoryInterface, QStyleFactoryInterface_iid)
-
-class Q_GUI_EXPORT QStylePlugin : public QObject, public QStyleFactoryInterface
-{
- Q_OBJECT
- Q_INTERFACES(QStyleFactoryInterface:QFactoryInterface)
-public:
- explicit QStylePlugin(QObject *parent = 0);
- ~QStylePlugin();
-
- virtual QStringList keys() const = 0;
- virtual QStyle *create(const QString &key) = 0;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTYLEPLUGIN_H
diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp
deleted file mode 100644
index faa929ebea..0000000000
--- a/src/gui/styles/qstylesheetstyle.cpp
+++ /dev/null
@@ -1,5898 +0,0 @@
-/****************************************************************************
-**
-** 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>
-
-#ifndef QT_NO_STYLE_STYLESHEET
-
-#include "qstylesheetstyle_p.h"
-#include "private/qcssutil_p.h"
-#include <qdebug.h>
-#include <qapplication.h>
-#include <qmenu.h>
-#include <qmenubar.h>
-#include <qpainter.h>
-#include <qstyleoption.h>
-#include <qlineedit.h>
-#include <qwindowsstyle.h>
-#include <qcombobox.h>
-#include <qwindowsstyle.h>
-#include <qplastiquestyle.h>
-#include "private/qcssparser_p.h"
-#include "private/qmath_p.h"
-#include <qabstractscrollarea.h>
-#include "private/qabstractscrollarea_p.h"
-#include <qtooltip.h>
-#include <qshareddata.h>
-#include <qradiobutton.h>
-#include <qtoolbutton.h>
-#include <qscrollbar.h>
-#include <qstring.h>
-#include <qfile.h>
-#include <qcheckbox.h>
-#include <qstatusbar.h>
-#include <qheaderview.h>
-#include <qprogressbar.h>
-#include <private/qwindowsstyle_p.h>
-#include <qtabbar.h>
-#include <QMetaProperty>
-#include <qmainwindow.h>
-#include <qdockwidget.h>
-#include <qmdisubwindow.h>
-#include <qdialog.h>
-#include <private/qwidget_p.h>
-#include <QAbstractSpinBox>
-#include <QLabel>
-#include "qdrawutil.h"
-
-#include <limits.h>
-#include <QtGui/qtoolbar.h>
-
-QT_BEGIN_NAMESPACE
-
-using namespace QCss;
-
-
-class QStyleSheetStylePrivate : public QWindowsStylePrivate
-{
- Q_DECLARE_PUBLIC(QStyleSheetStyle)
-public:
- QStyleSheetStylePrivate() { }
-};
-
-
-static QStyleSheetStyleCaches *styleSheetCaches = 0;
-
-/* RECURSION_GUARD:
- * the QStyleSheetStyle is a proxy. If used with others proxy style, we may end up with something like:
- * QStyleSheetStyle -> ProxyStyle -> QStyleSheetStyle -> OriginalStyle
- * Recursion may happen if the style call the widget()->style() again.
- * Not to mention the performence penalty of having two lookup of rules.
- *
- * The first instance of QStyleSheetStyle will set globalStyleSheetStyle to itself. The second one
- * will notice the globalStyleSheetStyle is not istelf and call its base style directly.
- */
-static const QStyleSheetStyle *globalStyleSheetStyle = 0;
-class QStyleSheetStyleRecursionGuard
-{
- public:
- QStyleSheetStyleRecursionGuard(const QStyleSheetStyle *that)
- : guarded(globalStyleSheetStyle == 0)
- {
- if (guarded) globalStyleSheetStyle = that;
- }
- ~QStyleSheetStyleRecursionGuard() { if (guarded) globalStyleSheetStyle = 0; }
- bool guarded;
-};
-#define RECURSION_GUARD(RETURN) \
- if (globalStyleSheetStyle != 0 && globalStyleSheetStyle != this) { RETURN; } \
- QStyleSheetStyleRecursionGuard recursion_guard(this);
-
-#define ceil(x) ((int)(x) + ((x) > 0 && (x) != (int)(x)))
-
-enum PseudoElement {
- PseudoElement_None,
- PseudoElement_DownArrow,
- PseudoElement_UpArrow,
- PseudoElement_LeftArrow,
- PseudoElement_RightArrow,
- PseudoElement_Indicator,
- PseudoElement_ExclusiveIndicator,
- PseudoElement_PushButtonMenuIndicator,
- PseudoElement_ComboBoxDropDown,
- PseudoElement_ComboBoxArrow,
- PseudoElement_Item,
- PseudoElement_SpinBoxUpButton,
- PseudoElement_SpinBoxUpArrow,
- PseudoElement_SpinBoxDownButton,
- PseudoElement_SpinBoxDownArrow,
- PseudoElement_GroupBoxTitle,
- PseudoElement_GroupBoxIndicator,
- PseudoElement_ToolButtonMenu,
- PseudoElement_ToolButtonMenuArrow,
- PseudoElement_ToolButtonDownArrow,
- PseudoElement_ToolBoxTab,
- PseudoElement_ScrollBarSlider,
- PseudoElement_ScrollBarAddPage,
- PseudoElement_ScrollBarSubPage,
- PseudoElement_ScrollBarAddLine,
- PseudoElement_ScrollBarSubLine,
- PseudoElement_ScrollBarFirst,
- PseudoElement_ScrollBarLast,
- PseudoElement_ScrollBarUpArrow,
- PseudoElement_ScrollBarDownArrow,
- PseudoElement_ScrollBarLeftArrow,
- PseudoElement_ScrollBarRightArrow,
- PseudoElement_SplitterHandle,
- PseudoElement_ToolBarHandle,
- PseudoElement_ToolBarSeparator,
- PseudoElement_MenuScroller,
- PseudoElement_MenuTearoff,
- PseudoElement_MenuCheckMark,
- PseudoElement_MenuSeparator,
- PseudoElement_MenuIcon,
- PseudoElement_MenuRightArrow,
- PseudoElement_TreeViewBranch,
- PseudoElement_HeaderViewSection,
- PseudoElement_HeaderViewUpArrow,
- PseudoElement_HeaderViewDownArrow,
- PseudoElement_ProgressBarChunk,
- PseudoElement_TabBarTab,
- PseudoElement_TabBarScroller,
- PseudoElement_TabBarTear,
- PseudoElement_SliderGroove,
- PseudoElement_SliderHandle,
- PseudoElement_SliderAddPage,
- PseudoElement_SliderSubPage,
- PseudoElement_SliderTickmark,
- PseudoElement_TabWidgetPane,
- PseudoElement_TabWidgetTabBar,
- PseudoElement_TabWidgetLeftCorner,
- PseudoElement_TabWidgetRightCorner,
- PseudoElement_DockWidgetTitle,
- PseudoElement_DockWidgetCloseButton,
- PseudoElement_DockWidgetFloatButton,
- PseudoElement_DockWidgetSeparator,
- PseudoElement_MdiCloseButton,
- PseudoElement_MdiMinButton,
- PseudoElement_MdiNormalButton,
- PseudoElement_TitleBar,
- PseudoElement_TitleBarCloseButton,
- PseudoElement_TitleBarMinButton,
- PseudoElement_TitleBarMaxButton,
- PseudoElement_TitleBarShadeButton,
- PseudoElement_TitleBarUnshadeButton,
- PseudoElement_TitleBarNormalButton,
- PseudoElement_TitleBarContextHelpButton,
- PseudoElement_TitleBarSysMenu,
- PseudoElement_ViewItem,
- PseudoElement_ViewItemIcon,
- PseudoElement_ViewItemText,
- PseudoElement_ViewItemIndicator,
- PseudoElement_ScrollAreaCorner,
- PseudoElement_TabBarTabCloseButton,
- NumPseudoElements
-};
-
-struct PseudoElementInfo {
- QStyle::SubControl subControl;
- const char *name;
-};
-
-static const PseudoElementInfo knownPseudoElements[NumPseudoElements] = {
- { QStyle::SC_None, "" },
- { QStyle::SC_None, "down-arrow" },
- { QStyle::SC_None, "up-arrow" },
- { QStyle::SC_None, "left-arrow" },
- { QStyle::SC_None, "right-arrow" },
- { QStyle::SC_None, "indicator" },
- { QStyle::SC_None, "indicator" },
- { QStyle::SC_None, "menu-indicator" },
- { QStyle::SC_ComboBoxArrow, "drop-down" },
- { QStyle::SC_ComboBoxArrow, "down-arrow" },
- { QStyle::SC_None, "item" },
- { QStyle::SC_SpinBoxUp, "up-button" },
- { QStyle::SC_SpinBoxUp, "up-arrow" },
- { QStyle::SC_SpinBoxDown, "down-button" },
- { QStyle::SC_SpinBoxDown, "down-arrow" },
- { QStyle::SC_GroupBoxLabel, "title" },
- { QStyle::SC_GroupBoxCheckBox, "indicator" },
- { QStyle::SC_ToolButtonMenu, "menu-button" },
- { QStyle::SC_ToolButtonMenu, "menu-arrow" },
- { QStyle::SC_None, "menu-indicator" },
- { QStyle::SC_None, "tab" },
- { QStyle::SC_ScrollBarSlider, "handle" },
- { QStyle::SC_ScrollBarAddPage, "add-page" },
- { QStyle::SC_ScrollBarSubPage, "sub-page" },
- { QStyle::SC_ScrollBarAddLine, "add-line" },
- { QStyle::SC_ScrollBarSubLine, "sub-line" },
- { QStyle::SC_ScrollBarFirst, "first" },
- { QStyle::SC_ScrollBarLast, "last" },
- { QStyle::SC_ScrollBarSubLine, "up-arrow" },
- { QStyle::SC_ScrollBarAddLine, "down-arrow" },
- { QStyle::SC_ScrollBarSubLine, "left-arrow" },
- { QStyle::SC_ScrollBarAddLine, "right-arrow" },
- { QStyle::SC_None, "handle" },
- { QStyle::SC_None, "handle" },
- { QStyle::SC_None, "separator" },
- { QStyle::SC_None, "scroller" },
- { QStyle::SC_None, "tearoff" },
- { QStyle::SC_None, "indicator" },
- { QStyle::SC_None, "separator" },
- { QStyle::SC_None, "icon" },
- { QStyle::SC_None, "right-arrow" },
- { QStyle::SC_None, "branch" },
- { QStyle::SC_None, "section" },
- { QStyle::SC_None, "down-arrow" },
- { QStyle::SC_None, "up-arrow" },
- { QStyle::SC_None, "chunk" },
- { QStyle::SC_None, "tab" },
- { QStyle::SC_None, "scroller" },
- { QStyle::SC_None, "tear" },
- { QStyle::SC_SliderGroove, "groove" },
- { QStyle::SC_SliderHandle, "handle" },
- { QStyle::SC_None, "add-page" },
- { QStyle::SC_None, "sub-page"},
- { QStyle::SC_SliderTickmarks, "tick-mark" },
- { QStyle::SC_None, "pane" },
- { QStyle::SC_None, "tab-bar" },
- { QStyle::SC_None, "left-corner" },
- { QStyle::SC_None, "right-corner" },
- { QStyle::SC_None, "title" },
- { QStyle::SC_None, "close-button" },
- { QStyle::SC_None, "float-button" },
- { QStyle::SC_None, "separator" },
- { QStyle::SC_MdiCloseButton, "close-button" },
- { QStyle::SC_MdiMinButton, "minimize-button" },
- { QStyle::SC_MdiNormalButton, "normal-button" },
- { QStyle::SC_TitleBarLabel, "title" },
- { QStyle::SC_TitleBarCloseButton, "close-button" },
- { QStyle::SC_TitleBarMinButton, "minimize-button" },
- { QStyle::SC_TitleBarMaxButton, "maximize-button" },
- { QStyle::SC_TitleBarShadeButton, "shade-button" },
- { QStyle::SC_TitleBarUnshadeButton, "unshade-button" },
- { QStyle::SC_TitleBarNormalButton, "normal-button" },
- { QStyle::SC_TitleBarContextHelpButton, "contexthelp-button" },
- { QStyle::SC_TitleBarSysMenu, "sys-menu" },
- { QStyle::SC_None, "item" },
- { QStyle::SC_None, "icon" },
- { QStyle::SC_None, "text" },
- { QStyle::SC_None, "indicator" },
- { QStyle::SC_None, "corner" },
- { QStyle::SC_None, "close-button" },
-};
-
-
-struct QStyleSheetBorderImageData : public QSharedData
-{
- QStyleSheetBorderImageData()
- : horizStretch(QCss::TileMode_Unknown), vertStretch(QCss::TileMode_Unknown)
- {
- for (int i = 0; i < 4; i++)
- cuts[i] = -1;
- }
- int cuts[4];
- QPixmap pixmap;
- QImage image;
- QCss::TileMode horizStretch, vertStretch;
-};
-
-struct QStyleSheetBackgroundData : public QSharedData
-{
- QStyleSheetBackgroundData(const QBrush& b, const QPixmap& p, QCss::Repeat r,
- Qt::Alignment a, QCss::Origin o, Attachment t, QCss::Origin c)
- : brush(b), pixmap(p), repeat(r), position(a), origin(o), attachment(t), clip(c) { }
-
- bool isTransparent() const {
- if (brush.style() != Qt::NoBrush)
- return !brush.isOpaque();
- return pixmap.isNull() ? false : pixmap.hasAlpha();
- }
- QBrush brush;
- QPixmap pixmap;
- QCss::Repeat repeat;
- Qt::Alignment position;
- QCss::Origin origin;
- QCss::Attachment attachment;
- QCss::Origin clip;
-};
-
-struct QStyleSheetBorderData : public QSharedData
-{
- QStyleSheetBorderData() : bi(0)
- {
- for (int i = 0; i < 4; i++) {
- borders[i] = 0;
- styles[i] = QCss::BorderStyle_None;
- }
- }
-
- QStyleSheetBorderData(int *b, QBrush *c, QCss::BorderStyle *s, QSize *r) : bi(0)
- {
- for (int i = 0; i < 4; i++) {
- borders[i] = b[i];
- styles[i] = s[i];
- colors[i] = c[i];
- radii[i] = r[i];
- }
- }
-
- int borders[4];
- QBrush colors[4];
- QCss::BorderStyle styles[4];
- QSize radii[4]; // topleft, topright, bottomleft, bottomright
-
- const QStyleSheetBorderImageData *borderImage() const
- { return bi; }
- bool hasBorderImage() const { return bi!=0; }
-
- QSharedDataPointer<QStyleSheetBorderImageData> bi;
-
- bool isOpaque() const
- {
- for (int i = 0; i < 4; i++) {
- if (styles[i] == QCss::BorderStyle_Native || styles[i] == QCss::BorderStyle_None)
- continue;
- if (styles[i] >= QCss::BorderStyle_Dotted && styles[i] <= QCss::BorderStyle_DotDotDash
- && styles[i] != BorderStyle_Solid)
- return false;
- if (!colors[i].isOpaque())
- return false;
- if (!radii[i].isEmpty())
- return false;
- }
- if (bi != 0 && bi->pixmap.hasAlpha())
- return false;
- return true;
- }
-};
-
-
-struct QStyleSheetOutlineData : public QStyleSheetBorderData
-{
- QStyleSheetOutlineData()
- {
- for (int i = 0; i < 4; i++) {
- offsets[i] = 0;
- }
- }
-
- QStyleSheetOutlineData(int *b, QBrush *c, QCss::BorderStyle *s, QSize *r, int *o)
- : QStyleSheetBorderData(b, c, s, r)
- {
- for (int i = 0; i < 4; i++) {
- offsets[i] = o[i];
- }
- }
-
- int offsets[4];
-};
-
-struct QStyleSheetBoxData : public QSharedData
-{
- QStyleSheetBoxData(int *m, int *p, int s) : spacing(s)
- {
- for (int i = 0; i < 4; i++) {
- margins[i] = m[i];
- paddings[i] = p[i];
- }
- }
-
- int margins[4];
- int paddings[4];
-
- int spacing;
-};
-
-struct QStyleSheetPaletteData : public QSharedData
-{
- QStyleSheetPaletteData(const QBrush &fg, const QBrush &sfg, const QBrush &sbg,
- const QBrush &abg)
- : foreground(fg), selectionForeground(sfg), selectionBackground(sbg),
- alternateBackground(abg) { }
-
- QBrush foreground;
- QBrush selectionForeground;
- QBrush selectionBackground;
- QBrush alternateBackground;
-};
-
-struct QStyleSheetGeometryData : public QSharedData
-{
- QStyleSheetGeometryData(int w, int h, int minw, int minh, int maxw, int maxh)
- : minWidth(minw), minHeight(minh), width(w), height(h), maxWidth(maxw), maxHeight(maxh) { }
-
- int minWidth, minHeight, width, height, maxWidth, maxHeight;
-};
-
-struct QStyleSheetPositionData : public QSharedData
-{
- QStyleSheetPositionData(int l, int t, int r, int b, Origin o, Qt::Alignment p, QCss::PositionMode m, Qt::Alignment a = 0)
- : left(l), top(t), bottom(b), right(r), origin(o), position(p), mode(m), textAlignment(a) { }
-
- int left, top, bottom, right;
- Origin origin;
- Qt::Alignment position;
- QCss::PositionMode mode;
- Qt::Alignment textAlignment;
-};
-
-struct QStyleSheetImageData : public QSharedData
-{
- QStyleSheetImageData(const QIcon &i, Qt::Alignment a, const QSize &sz)
- : icon(i), alignment(a), size(sz) { }
-
- QIcon icon;
- Qt::Alignment alignment;
- QSize size;
-};
-
-class QRenderRule
-{
-public:
- QRenderRule() : features(0), hasFont(false), pal(0), b(0), bg(0), bd(0), ou(0), geo(0), p(0), img(0), clipset(0) { }
- QRenderRule(const QVector<QCss::Declaration> &, const QWidget *);
- ~QRenderRule() { }
-
- QRect borderRect(const QRect &r) const;
- QRect outlineRect(const QRect &r) const;
- QRect paddingRect(const QRect &r) const;
- QRect contentsRect(const QRect &r) const;
-
- enum { Margin = 1, Border = 2, Padding = 4, All=Margin|Border|Padding };
- QRect boxRect(const QRect &r, int flags = All) const;
- QSize boxSize(const QSize &s, int flags = All) const;
- QRect originRect(const QRect &rect, Origin origin) const;
-
- QPainterPath borderClip(QRect rect);
- void drawBorder(QPainter *, const QRect&);
- void drawOutline(QPainter *, const QRect&);
- void drawBorderImage(QPainter *, const QRect&);
- void drawBackground(QPainter *, const QRect&, const QPoint& = QPoint(0, 0));
- void drawBackgroundImage(QPainter *, const QRect&, QPoint = QPoint(0, 0));
- void drawFrame(QPainter *, const QRect&);
- void drawImage(QPainter *p, const QRect &rect);
- void drawRule(QPainter *, const QRect&);
- void configurePalette(QPalette *, QPalette::ColorGroup, const QWidget *, bool);
- void configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette::ColorRole br);
-
- const QStyleSheetPaletteData *palette() const { return pal; }
- const QStyleSheetBoxData *box() const { return b; }
- const QStyleSheetBackgroundData *background() const { return bg; }
- const QStyleSheetBorderData *border() const { return bd; }
- const QStyleSheetOutlineData *outline() const { return ou; }
- const QStyleSheetGeometryData *geometry() const { return geo; }
- const QStyleSheetPositionData *position() const { return p; }
-
- bool hasPalette() const { return pal != 0; }
- bool hasBackground() const { return bg != 0 && (!bg->pixmap.isNull() || bg->brush.style() != Qt::NoBrush); }
- bool hasGradientBackground() const { return bg && bg->brush.style() >= Qt::LinearGradientPattern
- && bg->brush.style() <= Qt::ConicalGradientPattern; }
-
- bool hasNativeBorder() const {
- return bd == 0
- || (!bd->hasBorderImage() && bd->styles[0] == BorderStyle_Native);
- }
-
- bool hasNativeOutline() const {
- return (ou == 0
- || (!ou->hasBorderImage() && ou->styles[0] == BorderStyle_Native));
- }
-
- bool baseStyleCanDraw() const {
- if (!hasBackground() || (background()->brush.style() == Qt::NoBrush && bg->pixmap.isNull()))
- return true;
- if (bg && !bg->pixmap.isNull())
- return false;
- if (hasGradientBackground())
- return features & StyleFeature_BackgroundGradient;
- return features & StyleFeature_BackgroundColor;
- }
-
- bool hasBox() const { return b != 0; }
- bool hasBorder() const { return bd != 0; }
- bool hasOutline() const { return ou != 0; }
- bool hasPosition() const { return p != 0; }
- bool hasGeometry() const { return geo != 0; }
- bool hasDrawable() const { return !hasNativeBorder() || hasBackground() || hasImage(); }
- bool hasImage() const { return img != 0; }
-
- QSize minimumContentsSize() const
- { return geo ? QSize(geo->minWidth, geo->minHeight) : QSize(0, 0); }
- QSize minimumSize() const
- { return boxSize(minimumContentsSize()); }
-
- QSize contentsSize() const
- { return geo ? QSize(geo->width, geo->height)
- : ((img && img->size.isValid()) ? img->size : QSize()); }
- QSize contentsSize(const QSize &sz) const
- {
- QSize csz = contentsSize();
- if (csz.width() == -1) csz.setWidth(sz.width());
- if (csz.height() == -1) csz.setHeight(sz.height());
- return csz;
- }
- bool hasContentsSize() const
- { return (geo && (geo->width != -1 || geo->height != -1)) || (img && img->size.isValid()); }
-
- QSize size() const { return boxSize(contentsSize()); }
- QSize size(const QSize &sz) const { return boxSize(contentsSize(sz)); }
- QSize adjustSize(const QSize &sz)
- {
- if (!geo)
- return sz;
- QSize csz = contentsSize();
- if (csz.width() == -1) csz.setWidth(sz.width());
- if (csz.height() == -1) csz.setHeight(sz.height());
- if (geo->maxWidth != -1 && csz.width() > geo->maxWidth) csz.setWidth(geo->maxWidth);
- if (geo->maxHeight != -1 && csz.height() > geo->maxHeight) csz.setHeight(geo->maxHeight);
- csz=csz.expandedTo(QSize(geo->minWidth, geo->minHeight));
- return csz;
- }
-
- int features;
- QBrush defaultBackground;
- QFont font;
- bool hasFont;
-
- QHash<QString, QVariant> styleHints;
- bool hasStyleHint(const QString& sh) const { return styleHints.contains(sh); }
- QVariant styleHint(const QString& sh) const { return styleHints.value(sh); }
-
- void fixupBorder(int);
-
- QSharedDataPointer<QStyleSheetPaletteData> pal;
- QSharedDataPointer<QStyleSheetBoxData> b;
- QSharedDataPointer<QStyleSheetBackgroundData> bg;
- QSharedDataPointer<QStyleSheetBorderData> bd;
- QSharedDataPointer<QStyleSheetOutlineData> ou;
- QSharedDataPointer<QStyleSheetGeometryData> geo;
- QSharedDataPointer<QStyleSheetPositionData> p;
- QSharedDataPointer<QStyleSheetImageData> img;
-
- // Shouldn't be here
- void setClip(QPainter *p, const QRect &rect);
- void unsetClip(QPainter *);
- int clipset;
- QPainterPath clipPath;
-};
-
-///////////////////////////////////////////////////////////////////////////////////////////
-static const char *knownStyleHints[] = {
- "activate-on-singleclick",
- "alignment",
- "arrow-keys-navigate-into-children",
- "backward-icon",
- "button-layout",
- "cd-icon",
- "combobox-list-mousetracking",
- "combobox-popup",
- "computer-icon",
- "desktop-icon",
- "dialog-apply-icon",
- "dialog-cancel-icon",
- "dialog-close-icon",
- "dialog-discard-icon",
- "dialog-help-icon",
- "dialog-no-icon",
- "dialog-ok-icon",
- "dialog-open-icon",
- "dialog-reset-icon",
- "dialog-save-icon",
- "dialog-yes-icon",
- "dialogbuttonbox-buttons-have-icons",
- "directory-closed-icon",
- "directory-icon",
- "directory-link-icon",
- "directory-open-icon",
- "dither-disable-text",
- "dockwidget-close-icon",
- "downarrow-icon",
- "dvd-icon",
- "etch-disabled-text",
- "file-icon",
- "file-link-icon",
- "filedialog-backward-icon", // unused
- "filedialog-contentsview-icon",
- "filedialog-detailedview-icon",
- "filedialog-end-icon",
- "filedialog-infoview-icon",
- "filedialog-listview-icon",
- "filedialog-new-directory-icon",
- "filedialog-parent-directory-icon",
- "filedialog-start-icon",
- "floppy-icon",
- "forward-icon",
- "gridline-color",
- "harddisk-icon",
- "home-icon",
- "icon-size",
- "leftarrow-icon",
- "lineedit-password-character",
- "mdi-fill-space-on-maximize",
- "menu-scrollable",
- "menubar-altkey-navigation",
- "menubar-separator",
- "messagebox-critical-icon",
- "messagebox-information-icon",
- "messagebox-question-icon",
- "messagebox-text-interaction-flags",
- "messagebox-warning-icon",
- "mouse-tracking",
- "network-icon",
- "opacity",
- "paint-alternating-row-colors-for-empty-area",
- "rightarrow-icon",
- "scrollbar-contextmenu",
- "scrollbar-leftclick-absolute-position",
- "scrollbar-middleclick-absolute-position",
- "scrollbar-roll-between-buttons",
- "scrollbar-scroll-when-pointer-leaves-control",
- "scrollview-frame-around-contents",
- "show-decoration-selected",
- "spinbox-click-autorepeat-rate",
- "spincontrol-disable-on-bounds",
- "tabbar-elide-mode",
- "tabbar-prefer-no-arrows",
- "titlebar-close-icon",
- "titlebar-contexthelp-icon",
- "titlebar-maximize-icon",
- "titlebar-menu-icon",
- "titlebar-minimize-icon",
- "titlebar-normal-icon",
- "titlebar-shade-icon",
- "titlebar-unshade-icon",
- "toolbutton-popup-delay",
- "trash-icon",
- "uparrow-icon"
-};
-
-static const int numKnownStyleHints = sizeof(knownStyleHints)/sizeof(knownStyleHints[0]);
-
-static QList<QVariant> subControlLayout(const QString& layout)
-{
- QList<QVariant> buttons;
- for (int i = 0; i < layout.count(); i++) {
- int button = layout[i].toAscii();
- switch (button) {
- case 'm':
- buttons.append(PseudoElement_MdiMinButton);
- buttons.append(PseudoElement_TitleBarMinButton);
- break;
- case 'M':
- buttons.append(PseudoElement_TitleBarMaxButton);
- break;
- case 'X':
- buttons.append(PseudoElement_MdiCloseButton);
- buttons.append(PseudoElement_TitleBarCloseButton);
- break;
- case 'N':
- buttons.append(PseudoElement_MdiNormalButton);
- buttons.append(PseudoElement_TitleBarNormalButton);
- break;
- case 'I':
- buttons.append(PseudoElement_TitleBarSysMenu);
- break;
- case 'T':
- buttons.append(PseudoElement_TitleBar);
- break;
- case 'H':
- buttons.append(PseudoElement_TitleBarContextHelpButton);
- break;
- case 'S':
- buttons.append(PseudoElement_TitleBarShadeButton);
- break;
- default:
- buttons.append(button);
- break;
- }
- }
- return buttons;
-}
-
-namespace {
- struct ButtonInfo {
- QRenderRule rule;
- int element;
- int offset;
- int where;
- int width;
- };
-}
-
-QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget *w, const QStyleOptionTitleBar *tb) const
-{
- QHash<QStyle::SubControl, QRect> layoutRects;
- const bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- const bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
- QRenderRule subRule = renderRule(w, tb);
- QRect cr = subRule.contentsRect(tb->rect);
- QList<QVariant> layout = subRule.styleHint(QLatin1String("button-layout")).toList();
- if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("I(T)HSmMX"));
-
- int offsets[3] = { 0, 0, 0 };
- enum Where { Left, Right, Center, NoWhere } where = Left;
- QList<ButtonInfo> infos;
- for (int i = 0; i < layout.count(); i++) {
- ButtonInfo info;
- info.element = layout[i].toInt();
- if (info.element == '(') {
- where = Center;
- } else if (info.element == ')') {
- where = Right;
- } else {
- switch (info.element) {
- case PseudoElement_TitleBar:
- if (!(tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)))
- continue;
- break;
- case PseudoElement_TitleBarContextHelpButton:
- if (!(tb->titleBarFlags & Qt::WindowContextHelpButtonHint))
- continue;
- break;
- case PseudoElement_TitleBarMinButton:
- if (!(tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- continue;
- if (isMinimized)
- info.element = PseudoElement_TitleBarNormalButton;
- break;
- case PseudoElement_TitleBarMaxButton:
- if (!(tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- continue;
- if (isMaximized)
- info.element = PseudoElement_TitleBarNormalButton;
- break;
- case PseudoElement_TitleBarShadeButton:
- if (!(tb->titleBarFlags & Qt::WindowShadeButtonHint))
- continue;
- if (isMinimized)
- info.element = PseudoElement_TitleBarUnshadeButton;
- break;
- case PseudoElement_TitleBarCloseButton:
- case PseudoElement_TitleBarSysMenu:
- if (!(tb->titleBarFlags & Qt::WindowSystemMenuHint))
- continue;
- break;
- default:
- continue;
- }
- if (info.element == PseudoElement_TitleBar) {
- info.width = tb->fontMetrics.width(tb->text) + 6;
- subRule.geo = new QStyleSheetGeometryData(info.width, tb->fontMetrics.height(), -1, -1, -1, -1);
- } else {
- subRule = renderRule(w, tb, info.element);
- info.width = subRule.size().width();
- }
- info.rule = subRule;
- info.offset = offsets[where];
- info.where = where;
- infos.append(info);
-
- offsets[where] += info.width;
- }
- }
-
- for (int i = 0; i < infos.count(); i++) {
- ButtonInfo info = infos[i];
- QRect lr = cr;
- switch (info.where) {
- case Center: {
- lr.setLeft(cr.left() + offsets[Left]);
- lr.setRight(cr.right() - offsets[Right]);
- QRect r(0, 0, offsets[Center], lr.height());
- r.moveCenter(lr.center());
- r.setLeft(r.left()+info.offset);
- r.setWidth(info.width);
- lr = r;
- break; }
- case Left:
- lr.translate(info.offset, 0);
- lr.setWidth(info.width);
- break;
- case Right:
- lr.moveLeft(cr.right() + 1 - offsets[Right] + info.offset);
- lr.setWidth(info.width);
- break;
- default:
- break;
- }
- QStyle::SubControl control = knownPseudoElements[info.element].subControl;
- layoutRects[control] = positionRect(w, info.rule, info.element, lr, tb->direction);
- }
-
- return layoutRects;
-}
-
-static QStyle::StandardPixmap subControlIcon(int pe)
-{
- switch (pe) {
- case PseudoElement_MdiCloseButton: return QStyle::SP_TitleBarCloseButton;
- case PseudoElement_MdiMinButton: return QStyle::SP_TitleBarMinButton;
- case PseudoElement_MdiNormalButton: return QStyle::SP_TitleBarNormalButton;
- case PseudoElement_TitleBarCloseButton: return QStyle::SP_TitleBarCloseButton;
- case PseudoElement_TitleBarMinButton: return QStyle::SP_TitleBarMinButton;
- case PseudoElement_TitleBarMaxButton: return QStyle::SP_TitleBarMaxButton;
- case PseudoElement_TitleBarShadeButton: return QStyle::SP_TitleBarShadeButton;
- case PseudoElement_TitleBarUnshadeButton: return QStyle::SP_TitleBarUnshadeButton;
- case PseudoElement_TitleBarNormalButton: return QStyle::SP_TitleBarNormalButton;
- case PseudoElement_TitleBarContextHelpButton: return QStyle::SP_TitleBarContextHelpButton;
- default: break;
- }
- return QStyle::SP_CustomBase;
-}
-
-QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QWidget *widget)
-: features(0), hasFont(false), pal(0), b(0), bg(0), bd(0), ou(0), geo(0), p(0), img(0), clipset(0)
-{
- QPalette palette = QApplication::palette(); // ###: ideally widget's palette
- ValueExtractor v(declarations, palette);
- features = v.extractStyleFeatures();
-
- int w = -1, h = -1, minw = -1, minh = -1, maxw = -1, maxh = -1;
- if (v.extractGeometry(&w, &h, &minw, &minh, &maxw, &maxh))
- geo = new QStyleSheetGeometryData(w, h, minw, minh, maxw, maxh);
-
- int left = 0, top = 0, right = 0, bottom = 0;
- Origin origin = Origin_Unknown;
- Qt::Alignment position = 0;
- QCss::PositionMode mode = PositionMode_Unknown;
- Qt::Alignment textAlignment = 0;
- if (v.extractPosition(&left, &top, &right, &bottom, &origin, &position, &mode, &textAlignment))
- p = new QStyleSheetPositionData(left, top, right, bottom, origin, position, mode, textAlignment);
-
- int margins[4], paddings[4], spacing = -1;
- for (int i = 0; i < 4; i++)
- margins[i] = paddings[i] = 0;
- if (v.extractBox(margins, paddings, &spacing))
- b = new QStyleSheetBoxData(margins, paddings, spacing);
-
- int borders[4];
- QBrush colors[4];
- QCss::BorderStyle styles[4];
- QSize radii[4];
- for (int i = 0; i < 4; i++) {
- borders[i] = 0;
- styles[i] = BorderStyle_None;
- }
- if (v.extractBorder(borders, colors, styles, radii))
- bd = new QStyleSheetBorderData(borders, colors, styles, radii);
-
- int offsets[4];
- for (int i = 0; i < 4; i++) {
- borders[i] = offsets[i] = 0;
- styles[i] = BorderStyle_None;
- }
- if (v.extractOutline(borders, colors, styles, radii, offsets))
- ou = new QStyleSheetOutlineData(borders, colors, styles, radii, offsets);
-
- QBrush brush;
- QString uri;
- Repeat repeat = Repeat_XY;
- Qt::Alignment alignment = Qt::AlignTop | Qt::AlignLeft;
- Attachment attachment = Attachment_Scroll;
- origin = Origin_Padding;
- Origin clip = Origin_Border;
- if (v.extractBackground(&brush, &uri, &repeat, &alignment, &origin, &attachment, &clip))
- bg = new QStyleSheetBackgroundData(brush, QPixmap(uri), repeat, alignment, origin, attachment, clip);
-
- QBrush sfg, fg;
- QBrush sbg, abg;
- if (v.extractPalette(&fg, &sfg, &sbg, &abg))
- pal = new QStyleSheetPaletteData(fg, sfg, sbg, abg);
-
- QIcon icon;
- alignment = Qt::AlignCenter;
- QSize size;
- if (v.extractImage(&icon, &alignment, &size))
- img = new QStyleSheetImageData(icon, alignment, size);
-
- int adj = -255;
- hasFont = v.extractFont(&font, &adj);
-
-#ifndef QT_NO_TOOLTIP
- if (widget && qstrcmp(widget->metaObject()->className(), "QTipLabel") == 0)
- palette = QToolTip::palette();
-#endif
-
- for (int i = 0; i < declarations.count(); i++) {
- const Declaration& decl = declarations.at(i);
- if (decl.d->propertyId == BorderImage) {
- QString uri;
- QCss::TileMode horizStretch, vertStretch;
- int cuts[4];
-
- decl.borderImageValue(&uri, cuts, &horizStretch, &vertStretch);
- if (uri.isEmpty() || uri == QLatin1String("none")) {
- if (bd && bd->bi)
- bd->bi->pixmap = QPixmap();
- } else {
- if (!bd)
- bd = new QStyleSheetBorderData;
- if (!bd->bi)
- bd->bi = new QStyleSheetBorderImageData;
-
- QStyleSheetBorderImageData *bi = bd->bi;
- bi->pixmap = QPixmap(uri);
- for (int i = 0; i < 4; i++)
- bi->cuts[i] = cuts[i];
- bi->horizStretch = horizStretch;
- bi->vertStretch = vertStretch;
- }
- } else if (decl.d->propertyId == QtBackgroundRole) {
- if (bg && bg->brush.style() != Qt::NoBrush)
- continue;
- int role = decl.d->values.at(0).variant.toInt();
- if (role >= Value_FirstColorRole && role <= Value_LastColorRole)
- defaultBackground = palette.color((QPalette::ColorRole)(role-Value_FirstColorRole));
- } else if (decl.d->property.startsWith(QLatin1String("qproperty-"), Qt::CaseInsensitive)) {
- // intentionally left blank...
- } else if (decl.d->propertyId == UnknownProperty) {
- bool knownStyleHint = false;
- for (int i = 0; i < numKnownStyleHints; i++) {
- QLatin1String styleHint(knownStyleHints[i]);
- if (decl.d->property.compare(styleHint) == 0) {
- QString hintName = QString(styleHint);
- QVariant hintValue;
- if (hintName.endsWith(QLatin1String("alignment"))) {
- hintValue = (int) decl.alignmentValue();
- } else if (hintName.endsWith(QLatin1String("color"))) {
- hintValue = (int) decl.colorValue().rgba();
- } else if (hintName.endsWith(QLatin1String("size"))) {
- hintValue = decl.sizeValue();
- } else if (hintName.endsWith(QLatin1String("icon"))) {
- hintValue = decl.iconValue();
- } else if (hintName == QLatin1String("button-layout")
- && decl.d->values.count() != 0 && decl.d->values.at(0).type == Value::String) {
- hintValue = subControlLayout(decl.d->values.at(0).variant.toString());
- } else {
- int integer;
- decl.intValue(&integer);
- hintValue = integer;
- }
- styleHints[decl.d->property] = hintValue;
- knownStyleHint = true;
- break;
- }
- }
- if (!knownStyleHint)
- qDebug("Unknown property %s", qPrintable(decl.d->property));
- }
- }
-
- if (widget) {
- QStyleSheetStyle *style = const_cast<QStyleSheetStyle *>(globalStyleSheetStyle);
- if (!style)
- style = qobject_cast<QStyleSheetStyle *>(widget->style());
- if (style)
- fixupBorder(style->nativeFrameWidth(widget));
-
- }
- if (hasBorder() && border()->hasBorderImage())
- defaultBackground = QBrush();
-}
-
-QRect QRenderRule::borderRect(const QRect& r) const
-{
- if (!hasBox())
- return r;
- const int* m = box()->margins;
- return r.adjusted(m[LeftEdge], m[TopEdge], -m[RightEdge], -m[BottomEdge]);
-}
-
-QRect QRenderRule::outlineRect(const QRect& r) const
-{
- QRect br = borderRect(r);
- if (!hasOutline())
- return br;
- const int *b = outline()->borders;
- return r.adjusted(b[LeftEdge], b[TopEdge], -b[RightEdge], -b[BottomEdge]);
-}
-
-QRect QRenderRule::paddingRect(const QRect& r) const
-{
- QRect br = borderRect(r);
- if (!hasBorder())
- return br;
- const int *b = border()->borders;
- return br.adjusted(b[LeftEdge], b[TopEdge], -b[RightEdge], -b[BottomEdge]);
-}
-
-QRect QRenderRule::contentsRect(const QRect& r) const
-{
- QRect pr = paddingRect(r);
- if (!hasBox())
- return pr;
- const int *p = box()->paddings;
- return pr.adjusted(p[LeftEdge], p[TopEdge], -p[RightEdge], -p[BottomEdge]);
-}
-
-QRect QRenderRule::boxRect(const QRect& cr, int flags) const
-{
- QRect r = cr;
- if (hasBox()) {
- if (flags & Margin) {
- const int *m = box()->margins;
- r.adjust(-m[LeftEdge], -m[TopEdge], m[RightEdge], m[BottomEdge]);
- }
- if (flags & Padding) {
- const int *p = box()->paddings;
- r.adjust(-p[LeftEdge], -p[TopEdge], p[RightEdge], p[BottomEdge]);
- }
- }
- if (hasBorder() && (flags & Border)) {
- const int *b = border()->borders;
- r.adjust(-b[LeftEdge], -b[TopEdge], b[RightEdge], b[BottomEdge]);
- }
- return r;
-}
-
-QSize QRenderRule::boxSize(const QSize &cs, int flags) const
-{
- QSize bs = boxRect(QRect(QPoint(0, 0), cs), flags).size();
- if (cs.width() < 0) bs.setWidth(-1);
- if (cs.height() < 0) bs.setHeight(-1);
- return bs;
-}
-
-void QRenderRule::fixupBorder(int nativeWidth)
-{
- if (bd == 0)
- return;
-
- if (!bd->hasBorderImage() || bd->bi->pixmap.isNull()) {
- bd->bi = 0;
- // ignore the color, border of edges that have none border-style
- QBrush color = pal ? pal->foreground : QBrush();
- const bool hasRadius = bd->radii[0].isValid() || bd->radii[1].isValid()
- || bd->radii[2].isValid() || bd->radii[3].isValid();
- for (int i = 0; i < 4; i++) {
- if ((bd->styles[i] == BorderStyle_Native) && hasRadius)
- bd->styles[i] = BorderStyle_None;
-
- switch (bd->styles[i]) {
- case BorderStyle_None:
- // border-style: none forces width to be 0
- bd->colors[i] = QBrush();
- bd->borders[i] = 0;
- break;
- case BorderStyle_Native:
- if (bd->borders[i] == 0)
- bd->borders[i] = nativeWidth;
- // intentional fall through
- default:
- if (!bd->colors[i].style() != Qt::NoBrush) // auto-acquire 'color'
- bd->colors[i] = color;
- break;
- }
- }
-
- return;
- }
-
- // inspect the border image
- QStyleSheetBorderImageData *bi = bd->bi;
- if (bi->cuts[0] == -1) {
- for (int i = 0; i < 4; i++) // assume, cut = border
- bi->cuts[i] = int(border()->borders[i]);
- }
-}
-
-void QRenderRule::drawBorderImage(QPainter *p, const QRect& rect)
-{
- setClip(p, rect);
- static const Qt::TileRule tileMode2TileRule[] = {
- Qt::StretchTile, Qt::RoundTile, Qt::StretchTile, Qt::RepeatTile, Qt::StretchTile };
-
- const QStyleSheetBorderImageData *borderImageData = border()->borderImage();
- const int *targetBorders = border()->borders;
- const int *sourceBorders = borderImageData->cuts;
- QMargins sourceMargins(sourceBorders[LeftEdge], sourceBorders[TopEdge],
- sourceBorders[RightEdge], sourceBorders[BottomEdge]);
- QMargins targetMargins(targetBorders[LeftEdge], targetBorders[TopEdge],
- targetBorders[RightEdge], targetBorders[BottomEdge]);
-
- bool wasSmoothPixmapTransform = p->renderHints() & QPainter::SmoothPixmapTransform;
- p->setRenderHint(QPainter::SmoothPixmapTransform);
- qDrawBorderPixmap(p, rect, targetMargins, borderImageData->pixmap,
- QRect(QPoint(), borderImageData->pixmap.size()), sourceMargins,
- QTileRules(tileMode2TileRule[borderImageData->horizStretch], tileMode2TileRule[borderImageData->vertStretch]));
- p->setRenderHint(QPainter::SmoothPixmapTransform, wasSmoothPixmapTransform);
- unsetClip(p);
-}
-
-QRect QRenderRule::originRect(const QRect &rect, Origin origin) const
-{
- switch (origin) {
- case Origin_Padding:
- return paddingRect(rect);
- case Origin_Border:
- return borderRect(rect);
- case Origin_Content:
- return contentsRect(rect);
- case Origin_Margin:
- default:
- return rect;
- }
-}
-
-void QRenderRule::drawBackgroundImage(QPainter *p, const QRect &rect, QPoint off)
-{
- if (!hasBackground())
- return;
-
- const QPixmap& bgp = background()->pixmap;
- if (bgp.isNull())
- return;
-
- setClip(p, borderRect(rect));
-
- if (background()->origin != background()->clip) {
- p->save();
- p->setClipRect(originRect(rect, background()->clip), Qt::IntersectClip);
- }
-
- if (background()->attachment == Attachment_Fixed)
- off = QPoint(0, 0);
-
- QRect r = originRect(rect, background()->origin);
- QRect aligned = QStyle::alignedRect(Qt::LeftToRight, background()->position, bgp.size(), r);
- QRect inter = aligned.translated(-off).intersected(r);
-
- switch (background()->repeat) {
- case Repeat_Y:
- p->drawTiledPixmap(inter.x(), r.y(), inter.width(), r.height(), bgp,
- inter.x() - aligned.x() + off.x(),
- bgp.height() - int(aligned.y() - r.y()) % bgp.height() + off.y());
- break;
- case Repeat_X:
- p->drawTiledPixmap(r.x(), inter.y(), r.width(), inter.height(), bgp,
- bgp.width() - int(aligned.x() - r.x())%bgp.width() + off.x(),
- inter.y() - aligned.y() + off.y());
- break;
- case Repeat_XY:
- p->drawTiledPixmap(r, bgp,
- QPoint(bgp.width() - int(aligned.x() - r.x())% bgp.width() + off.x(),
- bgp.height() - int(aligned.y() - r.y())%bgp.height() + off.y()));
- break;
- case Repeat_None:
- default:
- p->drawPixmap(inter.x(), inter.y(), bgp, inter.x() - aligned.x() + off.x(),
- inter.y() - aligned.y() + off.y(), inter.width(), inter.height());
- break;
- }
-
-
- if (background()->origin != background()->clip)
- p->restore();
-
- unsetClip(p);
-}
-
-void QRenderRule::drawOutline(QPainter *p, const QRect &rect)
-{
- if (!hasOutline())
- return;
-
- bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
- p->setRenderHint(QPainter::Antialiasing);
- qDrawBorder(p, rect, ou->styles, ou->borders, ou->colors, ou->radii);
- p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
-}
-
-void QRenderRule::drawBorder(QPainter *p, const QRect& rect)
-{
- if (!hasBorder())
- return;
-
- if (border()->hasBorderImage()) {
- drawBorderImage(p, rect);
- return;
- }
-
- bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
- p->setRenderHint(QPainter::Antialiasing);
- qDrawBorder(p, rect, bd->styles, bd->borders, bd->colors, bd->radii);
- p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
-}
-
-QPainterPath QRenderRule::borderClip(QRect r)
-{
- if (!hasBorder())
- return QPainterPath();
-
- QSize tlr, trr, blr, brr;
- qNormalizeRadii(r, bd->radii, &tlr, &trr, &blr, &brr);
- if (tlr.isNull() && trr.isNull() && blr.isNull() && brr.isNull())
- return QPainterPath();
-
- const QRectF rect(r);
- const int *borders = border()->borders;
- QPainterPath path;
- qreal curY = rect.y() + borders[TopEdge]/2.0;
- path.moveTo(rect.x() + tlr.width(), curY);
- path.lineTo(rect.right() - trr.width(), curY);
- qreal curX = rect.right() - borders[RightEdge]/2.0;
- path.arcTo(curX - 2*trr.width() + borders[RightEdge], curY,
- trr.width()*2 - borders[RightEdge], trr.height()*2 - borders[TopEdge], 90, -90);
-
- path.lineTo(curX, rect.bottom() - brr.height());
- curY = rect.bottom() - borders[BottomEdge]/2.0;
- path.arcTo(curX - 2*brr.width() + borders[RightEdge], curY - 2*brr.height() + borders[BottomEdge],
- brr.width()*2 - borders[RightEdge], brr.height()*2 - borders[BottomEdge], 0, -90);
-
- path.lineTo(rect.x() + blr.width(), curY);
- curX = rect.left() + borders[LeftEdge]/2.0;
- path.arcTo(curX, rect.bottom() - 2*blr.height() + borders[BottomEdge]/2,
- blr.width()*2 - borders[LeftEdge], blr.height()*2 - borders[BottomEdge], 270, -90);
-
- path.lineTo(curX, rect.top() + tlr.height());
- path.arcTo(curX, rect.top() + borders[TopEdge]/2,
- tlr.width()*2 - borders[LeftEdge], tlr.height()*2 - borders[TopEdge], 180, -90);
-
- path.closeSubpath();
- return path;
-}
-
-/*! \internal
- Clip the painter to the border (in case we are using radius border)
- */
-void QRenderRule::setClip(QPainter *p, const QRect &rect)
-{
- if (clipset++)
- return;
- clipPath = borderClip(rect);
- if (!clipPath.isEmpty()) {
- p->save();
- p->setClipPath(clipPath, Qt::IntersectClip);
- }
-}
-
-void QRenderRule::unsetClip(QPainter *p)
-{
- if (--clipset)
- return;
- if (!clipPath.isEmpty())
- p->restore();
-}
-
-void QRenderRule::drawBackground(QPainter *p, const QRect& rect, const QPoint& off)
-{
- QBrush brush = hasBackground() ? background()->brush : QBrush();
- if (brush.style() == Qt::NoBrush)
- brush = defaultBackground;
-
- if (brush.style() != Qt::NoBrush) {
- Origin origin = hasBackground() ? background()->clip : Origin_Border;
- // ### fix for gradients
- const QPainterPath &borderPath = borderClip(originRect(rect, origin));
- if (!borderPath.isEmpty()) {
- // Drawn intead of being used as clipping path for better visual quality
- bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
- p->setRenderHint(QPainter::Antialiasing);
- p->fillPath(borderPath, brush);
- p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
- } else {
- p->fillRect(originRect(rect, origin), brush);
- }
- }
-
- drawBackgroundImage(p, rect, off);
-}
-
-void QRenderRule::drawFrame(QPainter *p, const QRect& rect)
-{
- drawBackground(p, rect);
- if (hasBorder())
- drawBorder(p, borderRect(rect));
-}
-
-void QRenderRule::drawImage(QPainter *p, const QRect &rect)
-{
- if (!hasImage())
- return;
- img->icon.paint(p, rect, img->alignment);
-}
-
-void QRenderRule::drawRule(QPainter *p, const QRect& rect)
-{
- drawFrame(p, rect);
- drawImage(p, contentsRect(rect));
-}
-
-// *shudder* , *horror*, *whoa* <-- what you might feel when you see the functions below
-void QRenderRule::configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette::ColorRole br)
-{
- if (bg && bg->brush.style() != Qt::NoBrush) {
- if (br != QPalette::NoRole)
- p->setBrush(br, bg->brush);
- p->setBrush(QPalette::Window, bg->brush);
- if (bg->brush.style() == Qt::SolidPattern) {
- p->setBrush(QPalette::Light, bg->brush.color().lighter(115));
- p->setBrush(QPalette::Midlight, bg->brush.color().lighter(107));
- p->setBrush(QPalette::Dark, bg->brush.color().darker(150));
- p->setBrush(QPalette::Shadow, bg->brush.color().darker(300));
- }
- }
-
- if (!hasPalette())
- return;
-
- if (pal->foreground.style() != Qt::NoBrush) {
- if (fr != QPalette::NoRole)
- p->setBrush(fr, pal->foreground);
- p->setBrush(QPalette::WindowText, pal->foreground);
- p->setBrush(QPalette::Text, pal->foreground);
- }
- if (pal->selectionBackground.style() != Qt::NoBrush)
- p->setBrush(QPalette::Highlight, pal->selectionBackground);
- if (pal->selectionForeground.style() != Qt::NoBrush)
- p->setBrush(QPalette::HighlightedText, pal->selectionForeground);
- if (pal->alternateBackground.style() != Qt::NoBrush)
- p->setBrush(QPalette::AlternateBase, pal->alternateBackground);
-}
-
-void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const QWidget *w, bool embedded)
-{
- if (bg && bg->brush.style() != Qt::NoBrush) {
- p->setBrush(cg, QPalette::Base, bg->brush); // for windows, windowxp
- p->setBrush(cg, QPalette::Button, bg->brush); // for plastique
- p->setBrush(cg, w->backgroundRole(), bg->brush);
- p->setBrush(cg, QPalette::Window, bg->brush);
- }
-
- if (embedded) {
- /* For embedded widgets (ComboBox, SpinBox and ScrollArea) we want the embedded widget
- * to be transparent when we have a transparent background or border image */
- if ((hasBackground() && background()->isTransparent())
- || (hasBorder() && border()->hasBorderImage() && !border()->borderImage()->pixmap.isNull()))
- p->setBrush(cg, w->backgroundRole(), Qt::NoBrush);
- }
-
- if (!hasPalette())
- return;
-
- if (pal->foreground.style() != Qt::NoBrush) {
- p->setBrush(cg, QPalette::ButtonText, pal->foreground);
- p->setBrush(cg, w->foregroundRole(), pal->foreground);
- p->setBrush(cg, QPalette::WindowText, pal->foreground);
- p->setBrush(cg, QPalette::Text, pal->foreground);
- }
- if (pal->selectionBackground.style() != Qt::NoBrush)
- p->setBrush(cg, QPalette::Highlight, pal->selectionBackground);
- if (pal->selectionForeground.style() != Qt::NoBrush)
- p->setBrush(cg, QPalette::HighlightedText, pal->selectionForeground);
- if (pal->alternateBackground.style() != Qt::NoBrush)
- p->setBrush(cg, QPalette::AlternateBase, pal->alternateBackground);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// Style rules
-#define WIDGET(x) (static_cast<QWidget *>(x.ptr))
-
-static inline QWidget *parentWidget(const QWidget *w)
-{
- if(qobject_cast<const QLabel *>(w) && qstrcmp(w->metaObject()->className(), "QTipLabel") == 0) {
- QWidget *p = qvariant_cast<QWidget *>(w->property("_q_stylesheet_parent"));
- if (p)
- return p;
- }
- return w->parentWidget();
-}
-
-class QStyleSheetStyleSelector : public StyleSelector
-{
-public:
- QStyleSheetStyleSelector() { }
-
- QStringList nodeNames(NodePtr node) const
- {
- if (isNullNode(node))
- return QStringList();
- const QMetaObject *metaObject = WIDGET(node)->metaObject();
-#ifndef QT_NO_TOOLTIP
- if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
- return QStringList(QLatin1String("QToolTip"));
-#endif
- QStringList result;
- do {
- result += QString::fromLatin1(metaObject->className()).replace(QLatin1Char(':'), QLatin1Char('-'));
- metaObject = metaObject->superClass();
- } while (metaObject != 0);
- return result;
- }
- QString attribute(NodePtr node, const QString& name) const
- {
- if (isNullNode(node))
- return QString();
-
- QHash<QString, QString> &cache = m_attributeCache[WIDGET(node)];
- QHash<QString, QString>::const_iterator cacheIt = cache.constFind(name);
- if (cacheIt != cache.constEnd())
- return cacheIt.value();
-
- QVariant value = WIDGET(node)->property(name.toLatin1());
- if (!value.isValid()) {
- if (name == QLatin1String("class")) {
- QString className = QString::fromLatin1(WIDGET(node)->metaObject()->className());
- if (className.contains(QLatin1Char(':')))
- className.replace(QLatin1Char(':'), QLatin1Char('-'));
- cache[name] = className;
- return className;
- } else if (name == QLatin1String("style")) {
- QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(WIDGET(node)->style());
- if (proxy) {
- QString styleName = QString::fromLatin1(proxy->baseStyle()->metaObject()->className());
- cache[name] = styleName;
- return styleName;
- }
- }
- }
- QString valueStr;
- if(value.type() == QVariant::StringList || value.type() == QVariant::List)
- valueStr = value.toStringList().join(QLatin1String(" "));
- else
- valueStr = value.toString();
- cache[name] = valueStr;
- return valueStr;
- }
- bool nodeNameEquals(NodePtr node, const QString& nodeName) const
- {
- if (isNullNode(node))
- return false;
- const QMetaObject *metaObject = WIDGET(node)->metaObject();
-#ifndef QT_NO_TOOLTIP
- if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
- return nodeName == QLatin1String("QToolTip");
-#endif
- do {
- const ushort *uc = (const ushort *)nodeName.constData();
- const ushort *e = uc + nodeName.length();
- const uchar *c = (uchar *)metaObject->className();
- while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) {
- ++uc;
- ++c;
- }
- if (uc == e && !*c)
- return true;
- metaObject = metaObject->superClass();
- } while (metaObject != 0);
- return false;
- }
- bool hasAttributes(NodePtr) const
- { return true; }
- QStringList nodeIds(NodePtr node) const
- { return isNullNode(node) ? QStringList() : QStringList(WIDGET(node)->objectName()); }
- bool isNullNode(NodePtr node) const
- { return node.ptr == 0; }
- NodePtr parentNode(NodePtr node) const
- { NodePtr n; n.ptr = isNullNode(node) ? 0 : parentWidget(WIDGET(node)); return n; }
- NodePtr previousSiblingNode(NodePtr) const
- { NodePtr n; n.ptr = 0; return n; }
- NodePtr duplicateNode(NodePtr node) const
- { return node; }
- void freeNode(NodePtr) const
- { }
-
-private:
- mutable QHash<const QWidget *, QHash<QString, QString> > m_attributeCache;
-};
-
-QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QWidget *w) const
-{
- QHash<const QWidget *, QVector<StyleRule> >::const_iterator cacheIt = styleSheetCaches->styleRulesCache.constFind(w);
- if (cacheIt != styleSheetCaches->styleRulesCache.constEnd())
- return cacheIt.value();
-
- if (!initWidget(w)) {
- return QVector<StyleRule>();
- }
-
- QStyleSheetStyleSelector styleSelector;
-
- StyleSheet defaultSs;
- QHash<const void *, StyleSheet>::const_iterator defaultCacheIt = styleSheetCaches->styleSheetCache.constFind(baseStyle());
- if (defaultCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
- defaultSs = getDefaultStyleSheet();
- QStyle *bs = baseStyle();
- styleSheetCaches->styleSheetCache.insert(bs, defaultSs);
- QObject::connect(bs, SIGNAL(destroyed(QObject*)), styleSheetCaches, SLOT(styleDestroyed(QObject*)), Qt::UniqueConnection);
- } else {
- defaultSs = defaultCacheIt.value();
- }
- styleSelector.styleSheets += defaultSs;
-
- if (!qApp->styleSheet().isEmpty()) {
- StyleSheet appSs;
- QHash<const void *, StyleSheet>::const_iterator appCacheIt = styleSheetCaches->styleSheetCache.constFind(qApp);
- if (appCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
- QString ss = qApp->styleSheet();
- if (ss.startsWith(QLatin1String("file:///")))
- ss.remove(0, 8);
- parser.init(ss, qApp->styleSheet() != ss);
- if (!parser.parse(&appSs))
- qWarning("Could not parse application stylesheet");
- appSs.origin = StyleSheetOrigin_Inline;
- appSs.depth = 1;
- styleSheetCaches->styleSheetCache.insert(qApp, appSs);
- } else {
- appSs = appCacheIt.value();
- }
- styleSelector.styleSheets += appSs;
- }
-
- QVector<QCss::StyleSheet> widgetSs;
- for (const QWidget *wid = w; wid; wid = parentWidget(wid)) {
- if (wid->styleSheet().isEmpty())
- continue;
- StyleSheet ss;
- QHash<const void *, StyleSheet>::const_iterator widCacheIt = styleSheetCaches->styleSheetCache.constFind(wid);
- if (widCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
- parser.init(wid->styleSheet());
- if (!parser.parse(&ss)) {
- parser.init(QLatin1String("* {") + wid->styleSheet() + QLatin1Char('}'));
- if (!parser.parse(&ss))
- qWarning("Could not parse stylesheet of widget %p", wid);
- }
- ss.origin = StyleSheetOrigin_Inline;
- styleSheetCaches->styleSheetCache.insert(wid, ss);
- } else {
- ss = widCacheIt.value();
- }
- widgetSs.append(ss);
- }
-
- for (int i = 0; i < widgetSs.count(); i++)
- widgetSs[i].depth = widgetSs.count() - i + 2;
-
- styleSelector.styleSheets += widgetSs;
-
- StyleSelector::NodePtr n;
- n.ptr = (void *)w;
- QVector<QCss::StyleRule> rules = styleSelector.styleRulesForNode(n);
- styleSheetCaches->styleRulesCache.insert(w, rules);
- return rules;
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Rendering rules
-static QVector<Declaration> declarations(const QVector<StyleRule> &styleRules, const QString &part, quint64 pseudoClass = PseudoClass_Unspecified)
-{
- QVector<Declaration> decls;
- for (int i = 0; i < styleRules.count(); i++) {
- const Selector& selector = styleRules.at(i).selectors.at(0);
- // Rules with pseudo elements don't cascade. This is an intentional
- // diversion for CSS
- if (part.compare(selector.pseudoElement(), Qt::CaseInsensitive) != 0)
- continue;
- quint64 negated = 0;
- quint64 cssClass = selector.pseudoClass(&negated);
- if ((pseudoClass == PseudoClass_Any) || (cssClass == PseudoClass_Unspecified)
- || ((((cssClass & pseudoClass) == cssClass)) && ((negated & pseudoClass) == 0)))
- decls += styleRules.at(i).declarations;
- }
- return decls;
-}
-
-int QStyleSheetStyle::nativeFrameWidth(const QWidget *w)
-{
- QStyle *base = baseStyle();
-
-#ifndef QT_NO_SPINBOX
- if (qobject_cast<const QAbstractSpinBox *>(w))
- return base->pixelMetric(QStyle::PM_SpinBoxFrameWidth, 0, w);
-#endif
-
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox *>(w))
- return base->pixelMetric(QStyle::PM_ComboBoxFrameWidth, 0, w);
-#endif
-
-#ifndef QT_NO_MENU
- if (qobject_cast<const QMenu *>(w))
- return base->pixelMetric(QStyle::PM_MenuPanelWidth, 0, w);
-#endif
-
-#ifndef QT_NO_MENUBAR
- if (qobject_cast<const QMenuBar *>(w))
- return base->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, w);
-#endif
-#ifndef QT_NO_FRAME
- if (const QFrame *frame = qobject_cast<const QFrame *>(w)) {
- if (frame->frameShape() == QFrame::NoFrame)
- return 0;
- }
-#endif
-
- if (qstrcmp(w->metaObject()->className(), "QTipLabel") == 0)
- return base->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, w);
-
- return base->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, w);
-}
-
-static quint64 pseudoClass(QStyle::State state)
-{
- quint64 pc = 0;
- if (state & QStyle::State_Enabled) {
- pc |= PseudoClass_Enabled;
- if (state & QStyle::State_MouseOver)
- pc |= PseudoClass_Hover;
- } else {
- pc |= PseudoClass_Disabled;
- }
- if (state & QStyle::State_Active)
- pc |= PseudoClass_Active;
- if (state & QStyle::State_Window)
- pc |= PseudoClass_Window;
- if (state & QStyle::State_Sunken)
- pc |= PseudoClass_Pressed;
- if (state & QStyle::State_HasFocus)
- pc |= PseudoClass_Focus;
- if (state & QStyle::State_On)
- pc |= (PseudoClass_On | PseudoClass_Checked);
- if (state & QStyle::State_Off)
- pc |= (PseudoClass_Off | PseudoClass_Unchecked);
- if (state & QStyle::State_NoChange)
- pc |= PseudoClass_Indeterminate;
- if (state & QStyle::State_Selected)
- pc |= PseudoClass_Selected;
- if (state & QStyle::State_Horizontal)
- pc |= PseudoClass_Horizontal;
- else
- pc |= PseudoClass_Vertical;
- if (state & (QStyle::State_Open | QStyle::State_On | QStyle::State_Sunken))
- pc |= PseudoClass_Open;
- else
- pc |= PseudoClass_Closed;
- if (state & QStyle::State_Children)
- pc |= PseudoClass_Children;
- if (state & QStyle::State_Sibling)
- pc |= PseudoClass_Sibling;
- if (state & QStyle::State_ReadOnly)
- pc |= PseudoClass_ReadOnly;
- if (state & QStyle::State_Item)
- pc |= PseudoClass_Item;
-#ifdef QT_KEYPAD_NAVIGATION
- if (state & QStyle::State_HasEditFocus)
- pc |= PseudoClass_EditFocus;
-#endif
- return pc;
-}
-
-static void qt_check_if_internal_widget(const QWidget **w, int *element)
-{
-#ifdef QT_NO_DOCKWIDGET
- Q_UNUSED(w);
- Q_UNUSED(element);
-#else
- if (*w && qstrcmp((*w)->metaObject()->className(), "QDockWidgetTitleButton") == 0) {
- if ((*w)->objectName() == QLatin1String("qt_dockwidget_closebutton")) {
- *element = PseudoElement_DockWidgetCloseButton;
- } else if ((*w)->objectName() == QLatin1String("qt_dockwidget_floatbutton")) {
- *element = PseudoElement_DockWidgetFloatButton;
- }
- *w = (*w)->parentWidget();
- }
-#endif
-}
-
-QRenderRule QStyleSheetStyle::renderRule(const QWidget *w, int element, quint64 state) const
-{
- qt_check_if_internal_widget(&w, &element);
- QHash<quint64, QRenderRule> &cache = styleSheetCaches->renderRulesCache[w][element];
- QHash<quint64, QRenderRule>::const_iterator cacheIt = cache.constFind(state);
- if (cacheIt != cache.constEnd())
- return cacheIt.value();
-
- if (!initWidget(w))
- return QRenderRule();
-
- quint64 stateMask = 0;
- const QVector<StyleRule> rules = styleRules(w);
- for (int i = 0; i < rules.count(); i++) {
- const Selector& selector = rules.at(i).selectors.at(0);
- quint64 negated = 0;
- stateMask |= selector.pseudoClass(&negated);
- stateMask |= negated;
- }
-
- cacheIt = cache.constFind(state & stateMask);
- if (cacheIt != cache.constEnd()) {
- const QRenderRule &newRule = cacheIt.value();
- cache[state] = newRule;
- return newRule;
- }
-
-
- const QString part = QLatin1String(knownPseudoElements[element].name);
- QVector<Declaration> decls = declarations(rules, part, state);
- QRenderRule newRule(decls, w);
- cache[state] = newRule;
- if ((state & stateMask) != state)
- cache[state&stateMask] = newRule;
- return newRule;
-}
-
-QRenderRule QStyleSheetStyle::renderRule(const QWidget *w, const QStyleOption *opt, int pseudoElement) const
-{
- quint64 extraClass = 0;
- QStyle::State state = opt ? opt->state : QStyle::State(QStyle::State_None);
-
- if (const QStyleOptionComplex *complex = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
- if (pseudoElement != PseudoElement_None) {
- // if not an active subcontrol, just pass enabled/disabled
- QStyle::SubControl subControl = knownPseudoElements[pseudoElement].subControl;
-
- if (!(complex->activeSubControls & subControl))
- state &= (QStyle::State_Enabled | QStyle::State_Horizontal | QStyle::State_HasFocus);
- }
-
- switch (pseudoElement) {
- case PseudoElement_ComboBoxDropDown:
- case PseudoElement_ComboBoxArrow:
- state |= (complex->state & (QStyle::State_On|QStyle::State_ReadOnly));
- break;
- case PseudoElement_SpinBoxUpButton:
- case PseudoElement_SpinBoxDownButton:
- case PseudoElement_SpinBoxUpArrow:
- case PseudoElement_SpinBoxDownArrow:
-#ifndef QT_NO_SPINBOX
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- bool on = false;
- bool up = pseudoElement == PseudoElement_SpinBoxUpButton
- || pseudoElement == PseudoElement_SpinBoxUpArrow;
- if ((sb->stepEnabled & QAbstractSpinBox::StepUpEnabled) && up)
- on = true;
- else if ((sb->stepEnabled & QAbstractSpinBox::StepDownEnabled) && !up)
- on = true;
- state |= (on ? QStyle::State_On : QStyle::State_Off);
- }
-#endif // QT_NO_SPINBOX
- break;
- case PseudoElement_GroupBoxTitle:
- state |= (complex->state & (QStyle::State_MouseOver | QStyle::State_Sunken));
- break;
- case PseudoElement_ToolButtonMenu:
- case PseudoElement_ToolButtonMenuArrow:
- case PseudoElement_ToolButtonDownArrow:
- state |= complex->state & QStyle::State_MouseOver;
- if (complex->state & QStyle::State_Sunken ||
- complex->activeSubControls & QStyle::SC_ToolButtonMenu)
- state |= QStyle::State_Sunken;
- break;
- case PseudoElement_SliderGroove:
- state |= complex->state & QStyle::State_MouseOver;
- break;
- default:
- break;
- }
-
- if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- // QStyle::State_On is set when the popup is being shown
- // Propagate EditField Pressed state
- if (pseudoElement == PseudoElement_None
- && (complex->activeSubControls & QStyle::SC_ComboBoxEditField)
- && (!(state & QStyle::State_MouseOver))) {
- state |= QStyle::State_Sunken;
- }
-
- if (!combo->frame)
- extraClass |= PseudoClass_Frameless;
- if (!combo->editable)
- extraClass |= PseudoClass_ReadOnly;
- else
- extraClass |= PseudoClass_Editable;
-#ifndef QT_NO_SPINBOX
- } else if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- if (!spin->frame)
- extraClass |= PseudoClass_Frameless;
-#endif // QT_NO_SPINBOX
- } else if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- if (gb->features & QStyleOptionFrameV2::Flat)
- extraClass |= PseudoClass_Flat;
- if (gb->lineWidth == 0)
- extraClass |= PseudoClass_Frameless;
- } else if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- if (tb->titleBarState & Qt::WindowMinimized) {
- extraClass |= PseudoClass_Minimized;
- }
- else if (tb->titleBarState & Qt::WindowMaximized)
- extraClass |= PseudoClass_Maximized;
- }
- } else {
- // handle simple style options
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- if (mi->menuItemType == QStyleOptionMenuItem::DefaultItem)
- extraClass |= PseudoClass_Default;
- if (mi->checkType == QStyleOptionMenuItem::Exclusive)
- extraClass |= PseudoClass_Exclusive;
- else if (mi->checkType == QStyleOptionMenuItem::NonExclusive)
- extraClass |= PseudoClass_NonExclusive;
- if (mi->checkType != QStyleOptionMenuItem::NotCheckable)
- extraClass |= (mi->checked) ? (PseudoClass_On|PseudoClass_Checked)
- : (PseudoClass_Off|PseudoClass_Unchecked);
- } else if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- if (hdr->position == QStyleOptionHeader::OnlyOneSection)
- extraClass |= PseudoClass_OnlyOne;
- else if (hdr->position == QStyleOptionHeader::Beginning)
- extraClass |= PseudoClass_First;
- else if (hdr->position == QStyleOptionHeader::End)
- extraClass |= PseudoClass_Last;
- else if (hdr->position == QStyleOptionHeader::Middle)
- extraClass |= PseudoClass_Middle;
-
- if (hdr->selectedPosition == QStyleOptionHeader::NextAndPreviousAreSelected)
- extraClass |= (PseudoClass_NextSelected | PseudoClass_PreviousSelected);
- else if (hdr->selectedPosition == QStyleOptionHeader::NextIsSelected)
- extraClass |= PseudoClass_NextSelected;
- else if (hdr->selectedPosition == QStyleOptionHeader::PreviousIsSelected)
- extraClass |= PseudoClass_PreviousSelected;
-#ifndef QT_NO_TABWIDGET
- } else if (const QStyleOptionTabWidgetFrame *tab = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- extraClass |= PseudoClass_Top;
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- extraClass |= PseudoClass_Bottom;
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- extraClass |= PseudoClass_Left;
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- extraClass |= PseudoClass_Right;
- break;
- default:
- break;
- }
-#endif
-#ifndef QT_NO_TABBAR
- } else if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- if (tab->position == QStyleOptionTab::OnlyOneTab)
- extraClass |= PseudoClass_OnlyOne;
- else if (tab->position == QStyleOptionTab::Beginning)
- extraClass |= PseudoClass_First;
- else if (tab->position == QStyleOptionTab::End)
- extraClass |= PseudoClass_Last;
- else if (tab->position == QStyleOptionTab::Middle)
- extraClass |= PseudoClass_Middle;
-
- if (tab->selectedPosition == QStyleOptionTab::NextIsSelected)
- extraClass |= PseudoClass_NextSelected;
- else if (tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
- extraClass |= PseudoClass_PreviousSelected;
-
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- extraClass |= PseudoClass_Top;
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- extraClass |= PseudoClass_Bottom;
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- extraClass |= PseudoClass_Left;
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- extraClass |= PseudoClass_Right;
- break;
- default:
- break;
- }
-#endif // QT_NO_TABBAR
- } else if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (btn->features & QStyleOptionButton::Flat)
- extraClass |= PseudoClass_Flat;
- if (btn->features & QStyleOptionButton::DefaultButton)
- extraClass |= PseudoClass_Default;
- } else if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (frm->lineWidth == 0)
- extraClass |= PseudoClass_Frameless;
- if (const QStyleOptionFrameV2 *frame2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(opt)) {
- if (frame2->features & QStyleOptionFrameV2::Flat)
- extraClass |= PseudoClass_Flat;
- }
- }
-#ifndef QT_NO_TOOLBAR
- else if (const QStyleOptionToolBar *tb = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
- if (tb->toolBarArea == Qt::LeftToolBarArea)
- extraClass |= PseudoClass_Left;
- else if (tb->toolBarArea == Qt::RightToolBarArea)
- extraClass |= PseudoClass_Right;
- else if (tb->toolBarArea == Qt::TopToolBarArea)
- extraClass |= PseudoClass_Top;
- else if (tb->toolBarArea == Qt::BottomToolBarArea)
- extraClass |= PseudoClass_Bottom;
-
- if (tb->positionWithinLine == QStyleOptionToolBar::Beginning)
- extraClass |= PseudoClass_First;
- else if (tb->positionWithinLine == QStyleOptionToolBar::Middle)
- extraClass |= PseudoClass_Middle;
- else if (tb->positionWithinLine == QStyleOptionToolBar::End)
- extraClass |= PseudoClass_Last;
- else if (tb->positionWithinLine == QStyleOptionToolBar::OnlyOne)
- extraClass |= PseudoClass_OnlyOne;
- }
-#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_TOOLBOX
- else if (const QStyleOptionToolBoxV2 *tab = qstyleoption_cast<const QStyleOptionToolBoxV2 *>(opt)) {
- if (tab->position == QStyleOptionToolBoxV2::OnlyOneTab)
- extraClass |= PseudoClass_OnlyOne;
- else if (tab->position == QStyleOptionToolBoxV2::Beginning)
- extraClass |= PseudoClass_First;
- else if (tab->position == QStyleOptionToolBoxV2::End)
- extraClass |= PseudoClass_Last;
- else if (tab->position == QStyleOptionToolBoxV2::Middle)
- extraClass |= PseudoClass_Middle;
-
- if (tab->selectedPosition == QStyleOptionToolBoxV2::NextIsSelected)
- extraClass |= PseudoClass_NextSelected;
- else if (tab->selectedPosition == QStyleOptionToolBoxV2::PreviousIsSelected)
- extraClass |= PseudoClass_PreviousSelected;
- }
-#endif // QT_NO_TOOLBOX
-#ifndef QT_NO_DOCKWIDGET
- else if (const QStyleOptionDockWidgetV2 *dw = qstyleoption_cast<const QStyleOptionDockWidgetV2 *>(opt)) {
- if (dw->verticalTitleBar)
- extraClass |= PseudoClass_Vertical;
- else
- extraClass |= PseudoClass_Horizontal;
- if (dw->closable)
- extraClass |= PseudoClass_Closable;
- if (dw->floatable)
- extraClass |= PseudoClass_Floatable;
- if (dw->movable)
- extraClass |= PseudoClass_Movable;
- }
-#endif // QT_NO_DOCKWIDGET
-#ifndef QT_NO_ITEMVIEWS
- else if (const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(opt)) {
- if (v2->features & QStyleOptionViewItemV2::Alternate)
- extraClass |= PseudoClass_Alternate;
- if (const QStyleOptionViewItemV4 *v4 = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- if (v4->viewItemPosition == QStyleOptionViewItemV4::OnlyOne)
- extraClass |= PseudoClass_OnlyOne;
- else if (v4->viewItemPosition == QStyleOptionViewItemV4::Beginning)
- extraClass |= PseudoClass_First;
- else if (v4->viewItemPosition == QStyleOptionViewItemV4::End)
- extraClass |= PseudoClass_Last;
- else if (v4->viewItemPosition == QStyleOptionViewItemV4::Middle)
- extraClass |= PseudoClass_Middle;
- }
- }
-#endif
-#ifndef QT_NO_LINEEDIT
- // LineEdit sets Sunken flag to indicate Sunken frame (argh)
- if (const QLineEdit *lineEdit = qobject_cast<const QLineEdit *>(w)) {
- state &= ~QStyle::State_Sunken;
- if (lineEdit->hasFrame()) {
- extraClass &= ~PseudoClass_Frameless;
- } else {
- extraClass |= PseudoClass_Frameless;
- }
- } else
-#endif
- if (const QFrame *frm = qobject_cast<const QFrame *>(w)) {
- if (frm->lineWidth() == 0)
- extraClass |= PseudoClass_Frameless;
- }
- }
-
- return renderRule(w, pseudoElement, pseudoClass(state) | extraClass);
-}
-
-bool QStyleSheetStyle::hasStyleRule(const QWidget *w, int part) const
-{
- QHash<int, bool> &cache = styleSheetCaches->hasStyleRuleCache[w];
- QHash<int, bool>::const_iterator cacheIt = cache.constFind(part);
- if (cacheIt != cache.constEnd())
- return cacheIt.value();
-
- if (!initWidget(w))
- return false;
-
-
- const QVector<StyleRule> &rules = styleRules(w);
- if (part == PseudoElement_None) {
- bool result = w && !rules.isEmpty();
- cache[part] = result;
- return result;
- }
-
- QString pseudoElement = QLatin1String(knownPseudoElements[part].name);
- QVector<Declaration> declarations;
- for (int i = 0; i < rules.count(); i++) {
- const Selector& selector = rules.at(i).selectors.at(0);
- if (pseudoElement.compare(selector.pseudoElement(), Qt::CaseInsensitive) == 0) {
- cache[part] = true;
- return true;
- }
- }
-
- cache[part] = false;
- return false;
-}
-
-static Origin defaultOrigin(int pe)
-{
- switch (pe) {
- case PseudoElement_ScrollBarAddPage:
- case PseudoElement_ScrollBarSubPage:
- case PseudoElement_ScrollBarAddLine:
- case PseudoElement_ScrollBarSubLine:
- case PseudoElement_ScrollBarFirst:
- case PseudoElement_ScrollBarLast:
- case PseudoElement_GroupBoxTitle:
- case PseudoElement_GroupBoxIndicator: // never used
- case PseudoElement_ToolButtonMenu:
- case PseudoElement_SliderAddPage:
- case PseudoElement_SliderSubPage:
- return Origin_Border;
-
- case PseudoElement_SpinBoxUpButton:
- case PseudoElement_SpinBoxDownButton:
- case PseudoElement_PushButtonMenuIndicator:
- case PseudoElement_ComboBoxDropDown:
- case PseudoElement_ToolButtonDownArrow:
- case PseudoElement_MenuCheckMark:
- case PseudoElement_MenuIcon:
- case PseudoElement_MenuRightArrow:
- return Origin_Padding;
-
- case PseudoElement_Indicator:
- case PseudoElement_ExclusiveIndicator:
- case PseudoElement_ComboBoxArrow:
- case PseudoElement_ScrollBarSlider:
- case PseudoElement_ScrollBarUpArrow:
- case PseudoElement_ScrollBarDownArrow:
- case PseudoElement_ScrollBarLeftArrow:
- case PseudoElement_ScrollBarRightArrow:
- case PseudoElement_SpinBoxUpArrow:
- case PseudoElement_SpinBoxDownArrow:
- case PseudoElement_ToolButtonMenuArrow:
- case PseudoElement_HeaderViewUpArrow:
- case PseudoElement_HeaderViewDownArrow:
- case PseudoElement_SliderGroove:
- case PseudoElement_SliderHandle:
- return Origin_Content;
-
- default:
- return Origin_Margin;
- }
-}
-
-static Qt::Alignment defaultPosition(int pe)
-{
- switch (pe) {
- case PseudoElement_Indicator:
- case PseudoElement_ExclusiveIndicator:
- case PseudoElement_MenuCheckMark:
- case PseudoElement_MenuIcon:
- return Qt::AlignLeft | Qt::AlignVCenter;
-
- case PseudoElement_ScrollBarAddLine:
- case PseudoElement_ScrollBarLast:
- case PseudoElement_SpinBoxDownButton:
- case PseudoElement_PushButtonMenuIndicator:
- case PseudoElement_ToolButtonDownArrow:
- return Qt::AlignRight | Qt::AlignBottom;
-
- case PseudoElement_ScrollBarSubLine:
- case PseudoElement_ScrollBarFirst:
- case PseudoElement_SpinBoxUpButton:
- case PseudoElement_ComboBoxDropDown:
- case PseudoElement_ToolButtonMenu:
- case PseudoElement_DockWidgetCloseButton:
- case PseudoElement_DockWidgetFloatButton:
- return Qt::AlignRight | Qt::AlignTop;
-
- case PseudoElement_ScrollBarUpArrow:
- case PseudoElement_ScrollBarDownArrow:
- case PseudoElement_ScrollBarLeftArrow:
- case PseudoElement_ScrollBarRightArrow:
- case PseudoElement_SpinBoxUpArrow:
- case PseudoElement_SpinBoxDownArrow:
- case PseudoElement_ComboBoxArrow:
- case PseudoElement_DownArrow:
- case PseudoElement_ToolButtonMenuArrow:
- case PseudoElement_SliderGroove:
- return Qt::AlignCenter;
-
- case PseudoElement_GroupBoxTitle:
- case PseudoElement_GroupBoxIndicator: // never used
- return Qt::AlignLeft | Qt::AlignTop;
-
- case PseudoElement_HeaderViewUpArrow:
- case PseudoElement_HeaderViewDownArrow:
- case PseudoElement_MenuRightArrow:
- return Qt::AlignRight | Qt::AlignVCenter;
-
- default:
- return 0;
- }
-}
-
-QSize QStyleSheetStyle::defaultSize(const QWidget *w, QSize sz, const QRect& rect, int pe) const
-{
- QStyle *base = baseStyle();
-
- switch (pe) {
- case PseudoElement_Indicator:
- case PseudoElement_MenuCheckMark:
- if (sz.width() == -1)
- sz.setWidth(base->pixelMetric(PM_IndicatorWidth, 0, w));
- if (sz.height() == -1)
- sz.setHeight(base->pixelMetric(PM_IndicatorHeight, 0, w));
- break;
-
- case PseudoElement_ExclusiveIndicator:
- case PseudoElement_GroupBoxIndicator:
- if (sz.width() == -1)
- sz.setWidth(base->pixelMetric(PM_ExclusiveIndicatorWidth, 0, w));
- if (sz.height() == -1)
- sz.setHeight(base->pixelMetric(PM_ExclusiveIndicatorHeight, 0, w));
- break;
-
- case PseudoElement_PushButtonMenuIndicator: {
- int pm = base->pixelMetric(PM_MenuButtonIndicator, 0, w);
- if (sz.width() == -1)
- sz.setWidth(pm);
- if (sz.height() == -1)
- sz.setHeight(pm);
- }
- break;
-
- case PseudoElement_ComboBoxDropDown:
- if (sz.width() == -1)
- sz.setWidth(16);
- break;
-
- case PseudoElement_ComboBoxArrow:
- case PseudoElement_DownArrow:
- case PseudoElement_ToolButtonMenuArrow:
- case PseudoElement_ToolButtonDownArrow:
- case PseudoElement_MenuRightArrow:
- if (sz.width() == -1)
- sz.setWidth(13);
- if (sz.height() == -1)
- sz.setHeight(13);
- break;
-
- case PseudoElement_SpinBoxUpButton:
- case PseudoElement_SpinBoxDownButton:
- if (sz.width() == -1)
- sz.setWidth(16);
- if (sz.height() == -1)
- sz.setHeight(rect.height()/2);
- break;
-
- case PseudoElement_ToolButtonMenu:
- if (sz.width() == -1)
- sz.setWidth(base->pixelMetric(PM_MenuButtonIndicator, 0, w));
- break;
-
- case PseudoElement_HeaderViewUpArrow:
- case PseudoElement_HeaderViewDownArrow: {
- int pm = base->pixelMetric(PM_HeaderMargin, 0, w);
- if (sz.width() == -1)
- sz.setWidth(pm);
- if (sz.height() == 1)
- sz.setHeight(pm);
- break;
- }
-
- case PseudoElement_ScrollBarFirst:
- case PseudoElement_ScrollBarLast:
- case PseudoElement_ScrollBarAddLine:
- case PseudoElement_ScrollBarSubLine:
- case PseudoElement_ScrollBarSlider: {
- int pm = pixelMetric(QStyle::PM_ScrollBarExtent, 0, w);
- if (sz.width() == -1)
- sz.setWidth(pm);
- if (sz.height() == -1)
- sz.setHeight(pm);
- break;
- }
-
- case PseudoElement_DockWidgetCloseButton:
- case PseudoElement_DockWidgetFloatButton: {
- int iconSize = pixelMetric(PM_SmallIconSize, 0, w);
- return QSize(iconSize, iconSize);
- }
-
- default:
- break;
- }
-
- // expand to rectangle
- if (sz.height() == -1)
- sz.setHeight(rect.height());
- if (sz.width() == -1)
- sz.setWidth(rect.width());
-
- return sz;
-}
-
-static PositionMode defaultPositionMode(int pe)
-{
- switch (pe) {
- case PseudoElement_ScrollBarFirst:
- case PseudoElement_ScrollBarLast:
- case PseudoElement_ScrollBarAddLine:
- case PseudoElement_ScrollBarSubLine:
- case PseudoElement_ScrollBarAddPage:
- case PseudoElement_ScrollBarSubPage:
- case PseudoElement_ScrollBarSlider:
- case PseudoElement_SliderGroove:
- case PseudoElement_SliderHandle:
- case PseudoElement_TabWidgetPane:
- return PositionMode_Absolute;
- default:
- return PositionMode_Static;
- }
-}
-
-QRect QStyleSheetStyle::positionRect(const QWidget *w, const QRenderRule &rule2, int pe,
- const QRect &originRect, Qt::LayoutDirection dir) const
-{
- const QStyleSheetPositionData *p = rule2.position();
- PositionMode mode = (p && p->mode != PositionMode_Unknown) ? p->mode : defaultPositionMode(pe);
- Qt::Alignment position = (p && p->position != 0) ? p->position : defaultPosition(pe);
- QRect r;
-
- if (mode != PositionMode_Absolute) {
- QSize sz = defaultSize(w, rule2.size(), originRect, pe);
- sz = sz.expandedTo(rule2.minimumContentsSize());
- r = QStyle::alignedRect(dir, position, sz, originRect);
- if (p) {
- int left = p->left ? p->left : -p->right;
- int top = p->top ? p->top : -p->bottom;
- r.translate(dir == Qt::LeftToRight ? left : -left, top);
- }
- } else {
- r = p ? originRect.adjusted(dir == Qt::LeftToRight ? p->left : p->right, p->top,
- dir == Qt::LeftToRight ? -p->right : -p->left, -p->bottom)
- : originRect;
- if (rule2.hasContentsSize()) {
- QSize sz = rule2.size().expandedTo(rule2.minimumContentsSize());
- if (sz.width() == -1) sz.setWidth(r.width());
- if (sz.height() == -1) sz.setHeight(r.height());
- r = QStyle::alignedRect(dir, position, sz, r);
- }
- }
- return r;
-}
-
-QRect QStyleSheetStyle::positionRect(const QWidget *w, const QRenderRule& rule1, const QRenderRule& rule2, int pe,
- const QRect& rect, Qt::LayoutDirection dir) const
-{
- const QStyleSheetPositionData *p = rule2.position();
- Origin origin = (p && p->origin != Origin_Unknown) ? p->origin : defaultOrigin(pe);
- QRect originRect = rule1.originRect(rect, origin);
- return positionRect(w, rule2, pe, originRect, dir);
-}
-
-
-/** \internal
- For widget that have an embedded widget (such as combobox) return that embedded widget.
- otherwise return the widget itself
- */
-static QWidget *embeddedWidget(QWidget *w)
-{
-#ifndef QT_NO_COMBOBOX
- if (QComboBox *cmb = qobject_cast<QComboBox *>(w)) {
- if (cmb->isEditable())
- return cmb->lineEdit();
- else
- return cmb;
- }
-#endif
-
-#ifndef QT_NO_SPINBOX
- if (QAbstractSpinBox *sb = qobject_cast<QAbstractSpinBox *>(w))
- return sb->findChild<QLineEdit *>();
-#endif
-
-#ifndef QT_NO_SCROLLAREA
- if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w))
- return sa->viewport();
-#endif
-
- return w;
-}
-
-/** \internal
- in case w is an embedded widget, return the container widget
- (i.e, the widget for which the rules actualy apply)
- (exemple, if w is a lineedit embedded in a combobox, return the combobox)
-
- if w is not embedded, return w itself
-*/
-static QWidget *containerWidget(const QWidget *w)
-{
-#ifndef QT_NO_LINEEDIT
- if (qobject_cast<const QLineEdit *>(w)) {
- //if the QLineEdit is an embeddedWidget, we need the rule of the real widget
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox *>(w->parentWidget()))
- return w->parentWidget();
-#endif
-#ifndef QT_NO_SPINBOX
- if (qobject_cast<const QAbstractSpinBox *>(w->parentWidget()))
- return w->parentWidget();
-#endif
- }
-#endif // QT_NO_LINEEDIT
-
-#ifndef QT_NO_SCROLLAREA
- if (const QAbstractScrollArea *sa = qobject_cast<const QAbstractScrollArea *>(w->parentWidget())) {
- if (sa->viewport() == w)
- return w->parentWidget();
- }
-#endif
-
- return const_cast<QWidget *>(w);
-}
-
-/** \internal
- returns true if the widget can NOT be styled directly
- */
-static bool unstylable(const QWidget *w)
-{
- if (w->windowType() == Qt::Desktop)
- return true;
-
- if (!w->styleSheet().isEmpty())
- return false;
-
- if (containerWidget(w) != w)
- return true;
-
-#ifndef QT_NO_FRAME
- // detect QComboBoxPrivateContainer
- else if (qobject_cast<const QFrame *>(w)) {
- if (0
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<const QComboBox *>(w->parentWidget())
-#endif
- )
- return true;
- }
-#endif
- return false;
-}
-
-static quint64 extendedPseudoClass(const QWidget *w)
-{
- quint64 pc = w->isWindow() ? quint64(PseudoClass_Window) : 0;
- if (const QAbstractSlider *slider = qobject_cast<const QAbstractSlider *>(w)) {
- pc |= ((slider->orientation() == Qt::Vertical) ? PseudoClass_Vertical : PseudoClass_Horizontal);
- } else
-#ifndef QT_NO_COMBOBOX
- if (const QComboBox *combo = qobject_cast<const QComboBox *>(w)) {
- if (combo->isEditable())
- pc |= (combo->isEditable() ? PseudoClass_Editable : PseudoClass_ReadOnly);
- } else
-#endif
-#ifndef QT_NO_LINEEDIT
- if (const QLineEdit *edit = qobject_cast<const QLineEdit *>(w)) {
- pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
- } else
-#endif
- { } // required for the above ifdef'ery to work
- return pc;
-}
-
-// sets up the geometry of the widget. We set a dynamic property when
-// we modify the min/max size of the widget. The min/max size is restored
-// to their original value when a new stylesheet that does not contain
-// the CSS properties is set and when the widget has this dynamic property set.
-// This way we don't trample on users who had setup a min/max size in code and
-// don't use stylesheets at all.
-void QStyleSheetStyle::setGeometry(QWidget *w)
-{
- QRenderRule rule = renderRule(w, PseudoElement_None, PseudoClass_Enabled | extendedPseudoClass(w));
- const QStyleSheetGeometryData *geo = rule.geometry();
- if (w->property("_q_stylesheet_minw").toBool()
- && ((!rule.hasGeometry() || geo->minWidth == -1))) {
- w->setMinimumWidth(0);
- w->setProperty("_q_stylesheet_minw", QVariant());
- }
- if (w->property("_q_stylesheet_minh").toBool()
- && ((!rule.hasGeometry() || geo->minHeight == -1))) {
- w->setMinimumHeight(0);
- w->setProperty("_q_stylesheet_minh", QVariant());
- }
- if (w->property("_q_stylesheet_maxw").toBool()
- && ((!rule.hasGeometry() || geo->maxWidth == -1))) {
- w->setMaximumWidth(QWIDGETSIZE_MAX);
- w->setProperty("_q_stylesheet_maxw", QVariant());
- }
- if (w->property("_q_stylesheet_maxh").toBool()
- && ((!rule.hasGeometry() || geo->maxHeight == -1))) {
- w->setMaximumHeight(QWIDGETSIZE_MAX);
- w->setProperty("_q_stylesheet_maxh", QVariant());
- }
-
-
- if (rule.hasGeometry()) {
- if (geo->minWidth != -1) {
- w->setProperty("_q_stylesheet_minw", true);
- w->setMinimumWidth(rule.boxSize(QSize(qMax(geo->width, geo->minWidth), 0)).width());
- }
- if (geo->minHeight != -1) {
- w->setProperty("_q_stylesheet_minh", true);
- w->setMinimumHeight(rule.boxSize(QSize(0, qMax(geo->height, geo->minHeight))).height());
- }
- if (geo->maxWidth != -1) {
- w->setProperty("_q_stylesheet_maxw", true);
- w->setMaximumWidth(rule.boxSize(QSize(qMin(geo->width == -1 ? QWIDGETSIZE_MAX : geo->width,
- geo->maxWidth == -1 ? QWIDGETSIZE_MAX : geo->maxWidth), 0)).width());
- }
- if (geo->maxHeight != -1) {
- w->setProperty("_q_stylesheet_maxh", true);
- w->setMaximumHeight(rule.boxSize(QSize(0, qMin(geo->height == -1 ? QWIDGETSIZE_MAX : geo->height,
- geo->maxHeight == -1 ? QWIDGETSIZE_MAX : geo->maxHeight))).height());
- }
- }
-}
-
-void QStyleSheetStyle::setProperties(QWidget *w)
-{
- QHash<QString, QVariant> propertyHash;
- QVector<Declaration> decls = declarations(styleRules(w), QString());
-
- // run through the declarations in order
- for (int i = 0; i < decls.count(); i++) {
- const Declaration &decl = decls.at(i);
- QString property = decl.d->property;
- if (!property.startsWith(QLatin1String("qproperty-"), Qt::CaseInsensitive))
- continue;
- property.remove(0, 10); // strip "qproperty-"
- const QVariant value = w->property(property.toLatin1());
- const QMetaObject *metaObject = w->metaObject();
- int index = metaObject->indexOfProperty(property.toLatin1());
- if (index == -1) {
- qWarning() << w << " does not have a property named " << property;
- continue;
- }
- QMetaProperty metaProperty = metaObject->property(index);
- if (!metaProperty.isWritable() || !metaProperty.isDesignable()) {
- qWarning() << w << " cannot design property named " << property;
- continue;
- }
- QVariant v;
- switch (value.type()) {
- case QVariant::Icon: v = decl.iconValue(); break;
- case QVariant::Image: v = QImage(decl.uriValue()); break;
- case QVariant::Pixmap: v = QPixmap(decl.uriValue()); break;
- case QVariant::Rect: v = decl.rectValue(); break;
- case QVariant::Size: v = decl.sizeValue(); break;
- case QVariant::Color: v = decl.colorValue(); break;
- case QVariant::Brush: v = decl.brushValue(); break;
-#ifndef QT_NO_SHORTCUT
- case QVariant::KeySequence: v = QKeySequence(decl.d->values.at(0).variant.toString()); break;
-#endif
- default: v = decl.d->values.at(0).variant; break;
- }
- propertyHash[property] = v;
- }
- // apply the values
- const QList<QString> properties = propertyHash.keys();
- for (int i = 0; i < properties.count(); i++) {
- const QString &property = properties.at(i);
- w->setProperty(property.toLatin1(), propertyHash[property]);
- }
-}
-
-void QStyleSheetStyle::setPalette(QWidget *w)
-{
- struct RuleRoleMap {
- int state;
- QPalette::ColorGroup group;
- } map[3] = {
- { int(PseudoClass_Active | PseudoClass_Enabled), QPalette::Active },
- { PseudoClass_Disabled, QPalette::Disabled },
- { PseudoClass_Enabled, QPalette::Inactive }
- };
-
- QPalette p = w->palette();
- QWidget *ew = embeddedWidget(w);
-
- for (int i = 0; i < 3; i++) {
- QRenderRule rule = renderRule(w, PseudoElement_None, map[i].state | extendedPseudoClass(w));
- if (i == 0) {
- if (!w->property("_q_styleSheetWidgetFont").isValid()) {
- saveWidgetFont(w, w->font());
- }
- updateStyleSheetFont(w);
- if (ew != w)
- updateStyleSheetFont(ew);
- }
-
- rule.configurePalette(&p, map[i].group, ew, ew != w);
- }
-
- styleSheetCaches->customPaletteWidgets.insert(w, w->palette());
- w->setPalette(p);
- if (ew != w)
- ew->setPalette(p);
-}
-
-void QStyleSheetStyle::unsetPalette(QWidget *w)
-{
- if (styleSheetCaches->customPaletteWidgets.contains(w)) {
- QPalette p = styleSheetCaches->customPaletteWidgets.value(w);
- w->setPalette(p);
- QWidget *ew = embeddedWidget(w);
- if (ew != w)
- ew->setPalette(p);
- styleSheetCaches->customPaletteWidgets.remove(w);
- }
- QVariant oldFont = w->property("_q_styleSheetWidgetFont");
- if (oldFont.isValid()) {
- w->setFont(qvariant_cast<QFont>(oldFont));
- }
- if (styleSheetCaches->autoFillDisabledWidgets.contains(w)) {
- embeddedWidget(w)->setAutoFillBackground(true);
- styleSheetCaches->autoFillDisabledWidgets.remove(w);
- }
-}
-
-static void updateWidgets(const QList<const QWidget *>& widgets)
-{
- if (!styleSheetCaches->styleRulesCache.isEmpty() || !styleSheetCaches->hasStyleRuleCache.isEmpty() || !styleSheetCaches->renderRulesCache.isEmpty()) {
- for (int i = 0; i < widgets.size(); ++i) {
- const QWidget *widget = widgets.at(i);
- styleSheetCaches->styleRulesCache.remove(widget);
- styleSheetCaches->hasStyleRuleCache.remove(widget);
- styleSheetCaches->renderRulesCache.remove(widget);
- }
- }
- for (int i = 0; i < widgets.size(); ++i) {
- QWidget *widget = const_cast<QWidget *>(widgets.at(i));
- if (widget == 0)
- continue;
- widget->style()->polish(widget);
- QEvent event(QEvent::StyleChange);
- QApplication::sendEvent(widget, &event);
- widget->update();
- widget->updateGeometry();
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// The stylesheet style
-int QStyleSheetStyle::numinstances = 0;
-
-QStyleSheetStyle::QStyleSheetStyle(QStyle *base)
- : QWindowsStyle(*new QStyleSheetStylePrivate), base(base), refcount(1)
-{
- ++numinstances;
- if (numinstances == 1) {
- styleSheetCaches = new QStyleSheetStyleCaches;
- }
-}
-
-QStyleSheetStyle::~QStyleSheetStyle()
-{
- --numinstances;
- if (numinstances == 0) {
- delete styleSheetCaches;
- }
-}
-QStyle *QStyleSheetStyle::baseStyle() const
-{
- if (base)
- return base;
- if (QStyleSheetStyle *me = qobject_cast<QStyleSheetStyle *>(QApplication::style()))
- return me->base;
- return QApplication::style();
-}
-
-void QStyleSheetStyleCaches::widgetDestroyed(QObject *o)
-{
- styleRulesCache.remove((const QWidget *)o);
- hasStyleRuleCache.remove((const QWidget *)o);
- renderRulesCache.remove((const QWidget *)o);
- customPaletteWidgets.remove((const QWidget *)o);
- styleSheetCache.remove((const QWidget *)o);
- autoFillDisabledWidgets.remove((const QWidget *)o);
-}
-
-void QStyleSheetStyleCaches::styleDestroyed(QObject *o)
-{
- styleSheetCache.remove(o);
-}
-
-/*!
- * Make sure that the cache will be clean by connecting destroyed if needed.
- * return false if the widget is not stylable;
- */
-bool QStyleSheetStyle::initWidget(const QWidget *w) const
-{
- if (!w)
- return false;
- if(w->testAttribute(Qt::WA_StyleSheet))
- return true;
-
- if(unstylable(w))
- return false;
-
- const_cast<QWidget *>(w)->setAttribute(Qt::WA_StyleSheet, true);
- QObject::connect(w, SIGNAL(destroyed(QObject*)), styleSheetCaches, SLOT(widgetDestroyed(QObject*)), Qt::UniqueConnection);
- return true;
-}
-
-void QStyleSheetStyle::polish(QWidget *w)
-{
- baseStyle()->polish(w);
- RECURSION_GUARD(return)
-
- if (!initWidget(w))
- return;
-
- if (styleSheetCaches->styleRulesCache.contains(w)) {
- // the widget accessed its style pointer before polish (or repolish)
- // (exemple: the QAbstractSpinBox constructor ask for the stylehint)
- styleSheetCaches->styleRulesCache.remove(w);
- styleSheetCaches->hasStyleRuleCache.remove(w);
- styleSheetCaches->renderRulesCache.remove(w);
- }
- setGeometry(w);
- setProperties(w);
- unsetPalette(w);
- setPalette(w);
-
- //set the WA_Hover attribute if one of the selector depends of the hover state
- QVector<StyleRule> rules = styleRules(w);
- for (int i = 0; i < rules.count(); i++) {
- const Selector& selector = rules.at(i).selectors.at(0);
- quint64 negated = 0;
- quint64 cssClass = selector.pseudoClass(&negated);
- if ( cssClass & PseudoClass_Hover || negated & PseudoClass_Hover) {
- w->setAttribute(Qt::WA_Hover);
- embeddedWidget(w)->setAttribute(Qt::WA_Hover);
- }
- }
-
-
-#ifndef QT_NO_SCROLLAREA
- if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
- QRenderRule rule = renderRule(sa, PseudoElement_None, PseudoClass_Enabled);
- if ((rule.hasBorder() && rule.border()->hasBorderImage())
- || (rule.hasBackground() && !rule.background()->pixmap.isNull())) {
- QObject::connect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()), Qt::UniqueConnection);
- QObject::connect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()), Qt::UniqueConnection);
- }
- }
-#endif
-
-#ifndef QT_NO_PROGRESSBAR
- if (QProgressBar *pb = qobject_cast<QProgressBar *>(w)) {
- QWindowsStyle::polish(pb);
- }
-#endif
-
- QRenderRule rule = renderRule(w, PseudoElement_None, PseudoClass_Any);
- if (rule.hasDrawable() || rule.hasBox()) {
- if (w->metaObject() == &QWidget::staticMetaObject
-#ifndef QT_NO_ITEMVIEWS
- || qobject_cast<QHeaderView *>(w)
-#endif
-#ifndef QT_NO_TABBAR
- || qobject_cast<QTabBar *>(w)
-#endif
-#ifndef QT_NO_FRAME
- || qobject_cast<QFrame *>(w)
-#endif
-#ifndef QT_NO_MAINWINDOW
- || qobject_cast<QMainWindow *>(w)
-#endif
-#ifndef QT_NO_MDIAREA
- || qobject_cast<QMdiSubWindow *>(w)
-#endif
-#ifndef QT_NO_MENUBAR
- || qobject_cast<QMenuBar *>(w)
-#endif
- || qobject_cast<QDialog *>(w)) {
- w->setAttribute(Qt::WA_StyledBackground, true);
- }
- QWidget *ew = embeddedWidget(w);
- if (ew->autoFillBackground()) {
- ew->setAutoFillBackground(false);
- styleSheetCaches->autoFillDisabledWidgets.insert(w);
- if (ew != w) { //eg. viewport of a scrollarea
- //(in order to draw the background anyway in case we don't.)
- ew->setAttribute(Qt::WA_StyledBackground, true);
- }
- }
- if (!rule.hasBackground() || rule.background()->isTransparent() || rule.hasBox()
- || (!rule.hasNativeBorder() && !rule.border()->isOpaque()))
- w->setAttribute(Qt::WA_OpaquePaintEvent, false);
- }
-}
-
-void QStyleSheetStyle::polish(QApplication *app)
-{
- baseStyle()->polish(app);
-}
-
-void QStyleSheetStyle::polish(QPalette &pal)
-{
- baseStyle()->polish(pal);
-}
-
-void QStyleSheetStyle::repolish(QWidget *w)
-{
- QList<const QWidget *> children = w->findChildren<const QWidget *>(QString());
- children.append(w);
- styleSheetCaches->styleSheetCache.remove(w);
- updateWidgets(children);
-}
-
-void QStyleSheetStyle::repolish(QApplication *app)
-{
- Q_UNUSED(app);
- const QList<const QWidget*> allWidgets = styleSheetCaches->styleRulesCache.keys();
- styleSheetCaches->styleSheetCache.remove(qApp);
- styleSheetCaches->styleRulesCache.clear();
- styleSheetCaches->hasStyleRuleCache.clear();
- styleSheetCaches->renderRulesCache.clear();
- updateWidgets(allWidgets);
-}
-
-void QStyleSheetStyle::unpolish(QWidget *w)
-{
- if (!w || !w->testAttribute(Qt::WA_StyleSheet)) {
- baseStyle()->unpolish(w);
- return;
- }
-
- styleSheetCaches->styleRulesCache.remove(w);
- styleSheetCaches->hasStyleRuleCache.remove(w);
- styleSheetCaches->renderRulesCache.remove(w);
- styleSheetCaches->styleSheetCache.remove(w);
- unsetPalette(w);
- w->setProperty("_q_stylesheet_minw", QVariant());
- w->setProperty("_q_stylesheet_minh", QVariant());
- w->setProperty("_q_stylesheet_maxw", QVariant());
- w->setProperty("_q_stylesheet_maxh", QVariant());
- w->setAttribute(Qt::WA_StyleSheet, false);
- QObject::disconnect(w, 0, this, 0);
-#ifndef QT_NO_SCROLLAREA
- if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
- QObject::disconnect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()));
- QObject::disconnect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)),
- sa, SLOT(update()));
- }
-#endif
-#ifndef QT_NO_PROGRESSBAR
- if (QProgressBar *pb = qobject_cast<QProgressBar *>(w))
- QWindowsStyle::unpolish(pb);
-#endif
- baseStyle()->unpolish(w);
-}
-
-void QStyleSheetStyle::unpolish(QApplication *app)
-{
- baseStyle()->unpolish(app);
- RECURSION_GUARD(return)
- styleSheetCaches->styleRulesCache.clear();
- styleSheetCaches->hasStyleRuleCache.clear();
- styleSheetCaches->renderRulesCache.clear();
- styleSheetCaches->styleSheetCache.remove(qApp);
-}
-
-#ifndef QT_NO_TABBAR
-inline static bool verticalTabs(QTabBar::Shape shape)
-{
- return shape == QTabBar::RoundedWest
- || shape == QTabBar::RoundedEast
- || shape == QTabBar::TriangularWest
- || shape == QTabBar::TriangularEast;
-}
-#endif // QT_NO_TABBAR
-
-void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w) const
-{
- RECURSION_GUARD(baseStyle()->drawComplexControl(cc, opt, p, w); return)
-
- QRenderRule rule = renderRule(w, opt);
-
- switch (cc) {
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QStyleOptionComboBox cmbOpt(*cmb);
- cmbOpt.rect = rule.borderRect(opt->rect);
- if (rule.hasNativeBorder()) {
- rule.drawBackgroundImage(p, cmbOpt.rect);
- rule.configurePalette(&cmbOpt.palette, QPalette::ButtonText, QPalette::Button);
- bool customDropDown = (opt->subControls & QStyle::SC_ComboBoxArrow)
- && (hasStyleRule(w, PseudoElement_ComboBoxDropDown) || hasStyleRule(w, PseudoElement_ComboBoxArrow));
- if (customDropDown)
- cmbOpt.subControls &= ~QStyle::SC_ComboBoxArrow;
- if (rule.baseStyleCanDraw()) {
- baseStyle()->drawComplexControl(cc, &cmbOpt, p, w);
- } else {
- QWindowsStyle::drawComplexControl(cc, &cmbOpt, p, w);
- }
- if (!customDropDown)
- return;
- } else {
- rule.drawRule(p, opt->rect);
- }
-
- if (opt->subControls & QStyle::SC_ComboBoxArrow) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
- if (subRule.hasDrawable()) {
- QRect r = subControlRect(CC_ComboBox, opt, SC_ComboBoxArrow, w);
- subRule.drawRule(p, r);
- QRenderRule subRule2 = renderRule(w, opt, PseudoElement_ComboBoxArrow);
- r = positionRect(w, subRule, subRule2, PseudoElement_ComboBoxArrow, r, opt->direction);
- subRule2.drawRule(p, r);
- } else {
- cmbOpt.subControls = QStyle::SC_ComboBoxArrow;
- QWindowsStyle::drawComplexControl(cc, &cmbOpt, p, w);
- }
- }
-
- return;
- }
- break;
-
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QStyleOptionSpinBox spinOpt(*spin);
- rule.configurePalette(&spinOpt.palette, QPalette::ButtonText, QPalette::Button);
- rule.configurePalette(&spinOpt.palette, QPalette::Text, QPalette::Base);
- spinOpt.rect = rule.borderRect(opt->rect);
- bool customUp = true, customDown = true;
- QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
- QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
- bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition();
- bool downRuleMatch = downRule.hasGeometry() || downRule.hasPosition();
- if (rule.hasNativeBorder() && !upRuleMatch && !downRuleMatch) {
- rule.drawBackgroundImage(p, spinOpt.rect);
- customUp = (opt->subControls & QStyle::SC_SpinBoxUp)
- && (hasStyleRule(w, PseudoElement_SpinBoxUpButton) || hasStyleRule(w, PseudoElement_UpArrow));
- if (customUp)
- spinOpt.subControls &= ~QStyle::SC_SpinBoxUp;
- customDown = (opt->subControls & QStyle::SC_SpinBoxDown)
- && (hasStyleRule(w, PseudoElement_SpinBoxDownButton) || hasStyleRule(w, PseudoElement_DownArrow));
- if (customDown)
- spinOpt.subControls &= ~QStyle::SC_SpinBoxDown;
- if (rule.baseStyleCanDraw()) {
- baseStyle()->drawComplexControl(cc, &spinOpt, p, w);
- } else {
- QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
- }
- if (!customUp && !customDown)
- return;
- } else {
- rule.drawRule(p, opt->rect);
- }
-
- if ((opt->subControls & QStyle::SC_SpinBoxUp) && customUp) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
- if (subRule.hasDrawable()) {
- QRect r = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w);
- subRule.drawRule(p, r);
- QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SpinBoxUpArrow);
- r = positionRect(w, subRule, subRule2, PseudoElement_SpinBoxUpArrow, r, opt->direction);
- subRule2.drawRule(p, r);
- } else {
- spinOpt.subControls = QStyle::SC_SpinBoxUp;
- QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
- }
- }
-
- if ((opt->subControls & QStyle::SC_SpinBoxDown) && customDown) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
- if (subRule.hasDrawable()) {
- QRect r = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w);
- subRule.drawRule(p, r);
- QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SpinBoxDownArrow);
- r = positionRect(w, subRule, subRule2, PseudoElement_SpinBoxDownArrow, r, opt->direction);
- subRule2.drawRule(p, r);
- } else {
- spinOpt.subControls = QStyle::SC_SpinBoxDown;
- QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
- }
- }
- return;
- }
- break;
-#endif // QT_NO_SPINBOX
-
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
-
- QRect labelRect, checkBoxRect, titleRect, frameRect;
- bool hasTitle = (gb->subControls & QStyle::SC_GroupBoxCheckBox) || !gb->text.isEmpty();
-
- if (!rule.hasDrawable() && (!hasTitle || !hasStyleRule(w, PseudoElement_GroupBoxTitle))
- && !hasStyleRule(w, PseudoElement_Indicator) && !rule.hasBox() && !rule.hasFont && !rule.hasPalette()) {
- // let the native style draw the combobox if there is no style for it.
- break;
- }
- rule.drawBackground(p, opt->rect);
-
- QRenderRule titleRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
- bool clipSet = false;
-
- if (hasTitle) {
- labelRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w);
- //Some native style (such as mac) may return a too small rectangle (because they use smaller fonts), so we may need to expand it a little bit.
- labelRect.setSize(labelRect.size().expandedTo(ParentStyle::subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w).size()));
- if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
- checkBoxRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxCheckBox, w);
- titleRect = titleRule.boxRect(checkBoxRect.united(labelRect));
- } else {
- titleRect = titleRule.boxRect(labelRect);
- }
- if (!titleRule.hasBackground() || !titleRule.background()->isTransparent()) {
- clipSet = true;
- p->save();
- p->setClipRegion(QRegion(opt->rect) - titleRect);
- }
- }
-
- frameRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxFrame, w);
- QStyleOptionFrameV2 frame;
- frame.QStyleOption::operator=(*gb);
- frame.features = gb->features;
- frame.lineWidth = gb->lineWidth;
- frame.midLineWidth = gb->midLineWidth;
- frame.rect = frameRect;
- drawPrimitive(PE_FrameGroupBox, &frame, p, w);
-
- if (clipSet)
- p->restore();
-
- // draw background and frame of the title
- if (hasTitle)
- titleRule.drawRule(p, titleRect);
-
- // draw the indicator
- if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*gb);
- box.rect = checkBoxRect;
- drawPrimitive(PE_IndicatorCheckBox, &box, p, w);
- }
-
- // draw the text
- if (!gb->text.isEmpty()) {
- int alignment = int(Qt::AlignCenter | Qt::TextShowMnemonic);
- if (!styleHint(QStyle::SH_UnderlineShortcut, opt, w)) {
- alignment |= Qt::TextHideMnemonic;
- }
-
- QPalette pal = gb->palette;
- if (gb->textColor.isValid())
- pal.setColor(QPalette::WindowText, gb->textColor);
- titleRule.configurePalette(&pal, QPalette::WindowText, QPalette::Window);
- drawItemText(p, labelRect, alignment, pal, gb->state & State_Enabled,
- gb->text, QPalette::WindowText);
-
- if (gb->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*gb);
- fropt.rect = labelRect;
- drawPrimitive(PE_FrameFocusRect, &fropt, p, w);
- }
- }
-
- return;
- }
- break;
-
- case CC_ToolButton:
- if (const QStyleOptionToolButton *tool = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- QStyleOptionToolButton toolOpt(*tool);
- rule.configurePalette(&toolOpt.palette, QPalette::ButtonText, QPalette::Button);
- toolOpt.font = rule.font.resolve(toolOpt.font);
- toolOpt.rect = rule.borderRect(opt->rect);
- bool customArrow = (tool->features & (QStyleOptionToolButton::HasMenu | QStyleOptionToolButton::MenuButtonPopup));
- bool customDropDown = tool->features & QStyleOptionToolButton::MenuButtonPopup;
- if (rule.hasNativeBorder()) {
- if (tool->subControls & SC_ToolButton) {
- //in some case (eg. the button is "auto raised") the style doesn't draw the background
- //so we need to draw the background.
- // use the same condition as in QCommonStyle
- State bflags = tool->state & ~State_Sunken;
- if (bflags & State_AutoRaise && (!(bflags & State_MouseOver) || !(bflags & State_Enabled)))
- bflags &= ~State_Raised;
- if (tool->state & State_Sunken && tool->activeSubControls & SC_ToolButton)
- bflags |= State_Sunken;
- if (!(bflags & (State_Sunken | State_On | State_Raised)))
- rule.drawBackground(p, toolOpt.rect);
- }
- customArrow = customArrow && hasStyleRule(w, PseudoElement_ToolButtonDownArrow);
- if (customArrow)
- toolOpt.features &= ~QStyleOptionToolButton::HasMenu;
- customDropDown = customDropDown && hasStyleRule(w, PseudoElement_ToolButtonMenu);
- if (customDropDown)
- toolOpt.subControls &= ~QStyle::SC_ToolButtonMenu;
-
- if (rule.baseStyleCanDraw() && !(tool->features & QStyleOptionToolButton::Arrow)) {
- baseStyle()->drawComplexControl(cc, &toolOpt, p, w);
- } else {
- QWindowsStyle::drawComplexControl(cc, &toolOpt, p, w);
- }
-
- if (!customArrow && !customDropDown)
- return;
- } else {
- rule.drawRule(p, opt->rect);
- toolOpt.rect = rule.contentsRect(opt->rect);
- if (rule.hasFont)
- toolOpt.font = rule.font;
- drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
- }
-
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
- QRect r = subControlRect(CC_ToolButton, opt, QStyle::SC_ToolButtonMenu, w);
- if (customDropDown) {
- if (opt->subControls & QStyle::SC_ToolButtonMenu) {
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, r);
- } else {
- toolOpt.rect = r;
- baseStyle()->drawPrimitive(PE_IndicatorButtonDropDown, &toolOpt, p, w);
- }
- }
- }
-
- if (customArrow) {
- QRenderRule subRule2 = customDropDown ? renderRule(w, opt, PseudoElement_ToolButtonMenuArrow)
- : renderRule(w, opt, PseudoElement_ToolButtonDownArrow);
- QRect r2 = customDropDown
- ? positionRect(w, subRule, subRule2, PseudoElement_ToolButtonMenuArrow, r, opt->direction)
- : positionRect(w, rule, subRule2, PseudoElement_ToolButtonDownArrow, opt->rect, opt->direction);
- if (subRule2.hasDrawable()) {
- subRule2.drawRule(p, r2);
- } else {
- toolOpt.rect = r2;
- baseStyle()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &toolOpt, p, w);
- }
- }
-
- return;
- }
- break;
-
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QStyleOptionSlider sbOpt(*sb);
- if (!rule.hasDrawable()) {
- sbOpt.rect = rule.borderRect(opt->rect);
- rule.drawBackgroundImage(p, opt->rect);
- baseStyle()->drawComplexControl(cc, &sbOpt, p, w);
- } else {
- rule.drawRule(p, opt->rect);
- QWindowsStyle::drawComplexControl(cc, opt, p, w);
- }
- return;
- }
- break;
-#endif // QT_NO_SCROLLBAR
-
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- rule.drawRule(p, opt->rect);
-
- QRenderRule grooveSubRule = renderRule(w, opt, PseudoElement_SliderGroove);
- QRenderRule handleSubRule = renderRule(w, opt, PseudoElement_SliderHandle);
- if (!grooveSubRule.hasDrawable()) {
- QStyleOptionSlider slOpt(*slider);
- bool handleHasRule = handleSubRule.hasDrawable();
- // If the style specifies a different handler rule, draw the groove without the handler.
- if (handleHasRule)
- slOpt.subControls &= ~SC_SliderHandle;
- baseStyle()->drawComplexControl(cc, &slOpt, p, w);
- if (!handleHasRule)
- return;
- }
-
- QRect gr = subControlRect(cc, opt, SC_SliderGroove, w);
- if (slider->subControls & SC_SliderGroove) {
- grooveSubRule.drawRule(p, gr);
- }
-
- if (slider->subControls & SC_SliderHandle) {
- QRect hr = subControlRect(cc, opt, SC_SliderHandle, w);
-
- QRenderRule subRule1 = renderRule(w, opt, PseudoElement_SliderSubPage);
- if (subRule1.hasDrawable()) {
- QRect r(gr.topLeft(),
- slider->orientation == Qt::Horizontal
- ? QPoint(hr.x()+hr.width()/2, gr.y()+gr.height() - 1)
- : QPoint(gr.x()+gr.width() - 1, hr.y()+hr.height()/2));
- subRule1.drawRule(p, r);
- }
-
- QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SliderAddPage);
- if (subRule2.hasDrawable()) {
- QRect r(slider->orientation == Qt::Horizontal
- ? QPoint(hr.x()+hr.width()/2+1, gr.y())
- : QPoint(gr.x(), hr.y()+hr.height()/2+1),
- gr.bottomRight());
- subRule2.drawRule(p, r);
- }
-
- handleSubRule.drawRule(p, handleSubRule.boxRect(hr, Margin));
- }
-
- if (slider->subControls & SC_SliderTickmarks) {
- // TODO...
- }
-
- return;
- }
- break;
-#endif // QT_NO_SLIDER
-
- case CC_MdiControls:
- if (hasStyleRule(w, PseudoElement_MdiCloseButton)
- || hasStyleRule(w, PseudoElement_MdiNormalButton)
- || hasStyleRule(w, PseudoElement_MdiMinButton)) {
- QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
- if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("mNX"));
-
- QStyleOptionComplex optCopy(*opt);
- optCopy.subControls = 0;
- for (int i = 0; i < layout.count(); i++) {
- int layoutButton = layout[i].toInt();
- if (layoutButton < PseudoElement_MdiCloseButton
- || layoutButton > PseudoElement_MdiNormalButton)
- continue;
- QStyle::SubControl control = knownPseudoElements[layoutButton].subControl;
- if (!(opt->subControls & control))
- continue;
- QRenderRule subRule = renderRule(w, opt, layoutButton);
- if (subRule.hasDrawable()) {
- QRect rect = subRule.boxRect(subControlRect(CC_MdiControls, opt, control, w), Margin);
- subRule.drawRule(p, rect);
- QIcon icon = standardIcon(subControlIcon(layoutButton), opt);
- icon.paint(p, subRule.contentsRect(rect), Qt::AlignCenter);
- } else {
- optCopy.subControls |= control;
- }
- }
-
- if (optCopy.subControls)
- baseStyle()->drawComplexControl(CC_MdiControls, &optCopy, p, w);
- return;
- }
- break;
-
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
- if (!subRule.hasDrawable() && !subRule.hasBox() && !subRule.hasBorder())
- break;
- subRule.drawRule(p, opt->rect);
- QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
-
- QRect ir;
- ir = layout[SC_TitleBarLabel];
- if (ir.isValid()) {
- if (subRule.hasPalette())
- p->setPen(subRule.palette()->foreground.color());
- p->fillRect(ir, Qt::white);
- p->drawText(ir.x(), ir.y(), ir.width(), ir.height(), Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
- }
-
- QPixmap pm;
-
- ir = layout[SC_TitleBarSysMenu];
- if (ir.isValid()) {
- QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarSysMenu);
- subSubRule.drawRule(p, ir);
- ir = subSubRule.contentsRect(ir);
- if (!tb->icon.isNull()) {
- tb->icon.paint(p, ir);
- } else {
- int iconSize = pixelMetric(PM_SmallIconSize, tb, w);
- pm = standardIcon(SP_TitleBarMenuButton, 0, w).pixmap(iconSize, iconSize);
- drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- }
- }
-
- ir = layout[SC_TitleBarCloseButton];
- if (ir.isValid()) {
- QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarCloseButton);
- subSubRule.drawRule(p, ir);
-
- QSize sz = subSubRule.contentsRect(ir).size();
- if ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool)
- pm = standardIcon(SP_DockWidgetCloseButton, 0, w).pixmap(sz);
- else
- pm = standardIcon(SP_TitleBarCloseButton, 0, w).pixmap(sz);
- drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- }
-
- int pes[] = {
- PseudoElement_TitleBarMaxButton,
- PseudoElement_TitleBarMinButton,
- PseudoElement_TitleBarNormalButton,
- PseudoElement_TitleBarShadeButton,
- PseudoElement_TitleBarUnshadeButton,
- PseudoElement_TitleBarContextHelpButton
- };
-
- for (unsigned int i = 0; i < sizeof(pes)/sizeof(int); i++) {
- int pe = pes[i];
- QStyle::SubControl sc = knownPseudoElements[pe].subControl;
- ir = layout[sc];
- if (!ir.isValid())
- continue;
- QRenderRule subSubRule = renderRule(w, opt, pe);
- subSubRule.drawRule(p, ir);
- pm = standardIcon(subControlIcon(pe), 0, w).pixmap(subSubRule.contentsRect(ir).size());
- drawItemPixmap(p, ir, Qt::AlignCenter, pm);
- }
-
- return;
- }
- break;
-
-
- default:
- break;
- }
-
- baseStyle()->drawComplexControl(cc, opt, p, w);
-}
-
-void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
- const QWidget *w) const
-{
- RECURSION_GUARD(baseStyle()->drawControl(ce, opt, p, w); return)
-
- QRenderRule rule = renderRule(w, opt);
- int pe1 = PseudoElement_None, pe2 = PseudoElement_None;
- bool fallback = false;
-
- switch (ce) {
- case CE_ToolButtonLabel:
- if (const QStyleOptionToolButton *btn = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- if (rule.hasBox() || btn->features & QStyleOptionToolButton::Arrow) {
- QCommonStyle::drawControl(ce, opt, p, w);
- } else {
- QStyleOptionToolButton butOpt(*btn);
- rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
- baseStyle()->drawControl(ce, &butOpt, p, w);
- }
- return;
- }
- break;
-
- case CE_FocusFrame:
- if (!rule.hasNativeBorder()) {
- rule.drawBorder(p, opt->rect);
- return;
- }
- break;
-
- case CE_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (rule.hasDrawable() || rule.hasBox() || rule.hasPosition() || rule.hasPalette() ||
- ((btn->features & QStyleOptionButton::HasMenu) && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator))) {
- ParentStyle::drawControl(ce, opt, p, w);
- return;
- }
- }
- break;
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QStyleOptionButton btnOpt(*btn);
- btnOpt.rect = rule.borderRect(opt->rect);
- if (rule.hasNativeBorder()) {
- rule.drawBackgroundImage(p, btnOpt.rect);
- rule.configurePalette(&btnOpt.palette, QPalette::ButtonText, QPalette::Button);
- bool customMenu = (btn->features & QStyleOptionButton::HasMenu
- && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator));
- if (customMenu)
- btnOpt.features &= ~QStyleOptionButton::HasMenu;
- if (rule.baseStyleCanDraw()) {
- baseStyle()->drawControl(ce, &btnOpt, p, w);
- } else {
- QWindowsStyle::drawControl(ce, &btnOpt, p, w);
- }
- if (!customMenu)
- return;
- } else {
- rule.drawRule(p, opt->rect);
- }
-
- if (btn->features & QStyleOptionButton::HasMenu) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
- QRect ir = positionRect(w, rule, subRule, PseudoElement_PushButtonMenuIndicator, opt->rect, opt->direction);
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, ir);
- } else {
- btnOpt.rect = ir;
- baseStyle()->drawPrimitive(PE_IndicatorArrowDown, &btnOpt, p, w);
- }
- }
- }
- return;
-
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QStyleOptionButton butOpt(*button);
- rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
- if (rule.hasPosition() && rule.position()->textAlignment != 0) {
- Qt::Alignment textAlignment = rule.position()->textAlignment;
- QRect textRect = button->rect;
- uint tf = Qt::TextShowMnemonic;
- const uint verticalAlignMask = Qt::AlignVCenter | Qt::AlignTop | Qt::AlignLeft;
- tf |= (textAlignment & verticalAlignMask) ? (textAlignment & verticalAlignMask) : Qt::AlignVCenter;
- if (!styleHint(SH_UnderlineShortcut, button, w))
- tf |= Qt::TextHideMnemonic;
- if (!button->icon.isNull()) {
- //Group both icon and text
- QRect iconRect;
- QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- if (mode == QIcon::Normal && button->state & State_HasFocus)
- mode = QIcon::Active;
- QIcon::State state = QIcon::Off;
- if (button->state & State_On)
- state = QIcon::On;
-
- QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
- int labelWidth = pixmap.width();
- int labelHeight = pixmap.height();
- int iconSpacing = 4;//### 4 is currently hardcoded in QPushButton::sizeHint()
- int textWidth = button->fontMetrics.boundingRect(opt->rect, tf, button->text).width();
- if (!button->text.isEmpty())
- labelWidth += (textWidth + iconSpacing);
-
- //Determine label alignment:
- if (textAlignment & Qt::AlignLeft) { /*left*/
- iconRect = QRect(textRect.x(), textRect.y() + (textRect.height() - labelHeight) / 2,
- pixmap.width(), pixmap.height());
- } else if (textAlignment & Qt::AlignHCenter) { /* center */
- iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
- textRect.y() + (textRect.height() - labelHeight) / 2,
- pixmap.width(), pixmap.height());
- } else { /*right*/
- iconRect = QRect(textRect.x() + textRect.width() - labelWidth,
- textRect.y() + (textRect.height() - labelHeight) / 2,
- pixmap.width(), pixmap.height());
- }
-
- iconRect = visualRect(button->direction, textRect, iconRect);
-
- tf |= Qt::AlignLeft; //left align, we adjust the text-rect instead
-
- if (button->direction == Qt::RightToLeft)
- textRect.setRight(iconRect.left() - iconSpacing);
- else
- textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);
-
- if (button->state & (State_On | State_Sunken))
- iconRect.translate(pixelMetric(PM_ButtonShiftHorizontal, opt, w),
- pixelMetric(PM_ButtonShiftVertical, opt, w));
- p->drawPixmap(iconRect, pixmap);
- } else {
- tf |= textAlignment;
- }
- if (button->state & (State_On | State_Sunken))
- textRect.translate(pixelMetric(PM_ButtonShiftHorizontal, opt, w),
- pixelMetric(PM_ButtonShiftVertical, opt, w));
-
- if (button->features & QStyleOptionButton::HasMenu) {
- int indicatorSize = pixelMetric(PM_MenuButtonIndicator, button, w);
- if (button->direction == Qt::LeftToRight)
- textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
- else
- textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
- }
- drawItemText(p, textRect, tf, butOpt.palette, (button->state & State_Enabled),
- button->text, QPalette::ButtonText);
- } else {
- ParentStyle::drawControl(ce, &butOpt, p, w);
- }
- }
- return;
-
- case CE_RadioButton:
- case CE_CheckBox:
- if (rule.hasBox() || !rule.hasNativeBorder() || rule.hasDrawable() || hasStyleRule(w, PseudoElement_Indicator)) {
- rule.drawRule(p, opt->rect);
- ParentStyle::drawControl(ce, opt, p, w);
- return;
- } else if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QStyleOptionButton butOpt(*btn);
- rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
- baseStyle()->drawControl(ce, &butOpt, p, w);
- return;
- }
- break;
- case CE_RadioButtonLabel:
- case CE_CheckBoxLabel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QStyleOptionButton butOpt(*btn);
- rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
- ParentStyle::drawControl(ce, &butOpt, p, w);
- }
- return;
-
- case CE_Splitter:
- pe1 = PseudoElement_SplitterHandle;
- break;
-
- case CE_ToolBar:
- if (rule.hasBackground()) {
- rule.drawBackground(p, opt->rect);
- }
- if (rule.hasBorder()) {
- rule.drawBorder(p, rule.borderRect(opt->rect));
- } else {
-#ifndef QT_NO_TOOLBAR
- if (const QStyleOptionToolBar *tb = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
- QStyleOptionToolBar newTb(*tb);
- newTb.rect = rule.borderRect(opt->rect);
- baseStyle()->drawControl(ce, &newTb, p, w);
- }
-#endif // QT_NO_TOOLBAR
- }
- return;
-
- case CE_MenuEmptyArea:
- case CE_MenuBarEmptyArea:
- if (rule.hasDrawable()) {
- // Drawn by PE_Widget
- return;
- }
- break;
-
- case CE_MenuTearoff:
- case CE_MenuScroller:
- if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- QStyleOptionMenuItem mi(*m);
- int pe = ce == CE_MenuTearoff ? PseudoElement_MenuTearoff : PseudoElement_MenuScroller;
- QRenderRule subRule = renderRule(w, opt, pe);
- mi.rect = subRule.contentsRect(opt->rect);
- rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
- subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
-
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- } else {
- baseStyle()->drawControl(ce, &mi, p, w);
- }
- }
- return;
-
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- QStyleOptionMenuItem mi(*m);
-
- int pseudo = (mi.menuItemType == QStyleOptionMenuItem::Separator) ? PseudoElement_MenuSeparator : PseudoElement_Item;
- QRenderRule subRule = renderRule(w, opt, pseudo);
- mi.rect = subRule.contentsRect(opt->rect);
- rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
- rule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
- subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
- subRule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
- QFont oldFont = p->font();
- if (subRule.hasFont)
- p->setFont(subRule.font.resolve(p->font()));
-
- // We fall back to drawing with the style sheet code whenever at least one of the
- // items are styled in an incompatible way, such as having a background image.
- QRenderRule allRules = renderRule(w, PseudoElement_Item, PseudoClass_Any);
-
- if ((pseudo == PseudoElement_MenuSeparator) && subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- } else if ((pseudo == PseudoElement_Item)
- && (allRules.hasBox() || allRules.hasBorder()
- || (allRules.background() && !allRules.background()->pixmap.isNull()))) {
- subRule.drawRule(p, opt->rect);
- if (subRule.hasBackground()) {
- mi.palette.setBrush(QPalette::Highlight, Qt::NoBrush);
- mi.palette.setBrush(QPalette::Button, Qt::NoBrush);
- } else {
- mi.palette.setBrush(QPalette::Highlight, mi.palette.brush(QPalette::Button));
- }
- mi.palette.setBrush(QPalette::HighlightedText, mi.palette.brush(QPalette::ButtonText));
-
- bool checkable = mi.checkType != QStyleOptionMenuItem::NotCheckable;
- bool checked = checkable ? mi.checked : false;
-
- bool dis = !(opt->state & QStyle::State_Enabled),
- act = opt->state & QStyle::State_Selected;
-
- if (!mi.icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap;
- if (checked)
- pixmap = mi.icon.pixmap(pixelMetric(PM_SmallIconSize), mode, QIcon::On);
- else
- pixmap = mi.icon.pixmap(pixelMetric(PM_SmallIconSize), mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- QRenderRule iconRule = renderRule(w, opt, PseudoElement_MenuIcon);
- if (!iconRule.hasGeometry()) {
- iconRule.geo = new QStyleSheetGeometryData(pixw, pixh, pixw, pixh, -1, -1);
- } else {
- iconRule.geo->width = pixw;
- iconRule.geo->height = pixh;
- }
- QRect iconRect = positionRect(w, subRule, iconRule, PseudoElement_MenuIcon, opt->rect, opt->direction);
- iconRule.drawRule(p, iconRect);
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(iconRect.center());
- p->drawPixmap(pmr.topLeft(), pixmap);
- } else if (checkable) {
- QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
- if (subSubRule.hasDrawable() || checked) {
- QStyleOptionMenuItem newMi = mi;
- newMi.rect = positionRect(w, subRule, subSubRule, PseudoElement_MenuCheckMark, opt->rect, opt->direction);
- drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, w);
- }
- }
-
- QRect textRect = subRule.contentsRect(opt->rect);
- textRect.setWidth(textRect.width() - mi.tabWidth);
- QString s = mi.text;
- p->setPen(mi.palette.buttonText().color());
- if (!s.isEmpty()) {
- int text_flags = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, &mi, w))
- text_flags |= Qt::TextHideMnemonic;
- int t = s.indexOf(QLatin1Char('\t'));
- if (t >= 0) {
- QRect vShortcutRect = visualRect(opt->direction, mi.rect,
- QRect(textRect.topRight(), QPoint(mi.rect.right(), textRect.bottom())));
- p->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- p->drawText(textRect, text_flags, s.left(t));
- }
-
- if (mi.menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- PrimitiveElement arrow = (opt->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- QRenderRule subRule2 = renderRule(w, opt, PseudoElement_MenuRightArrow);
- mi.rect = positionRect(w, subRule, subRule2, PseudoElement_MenuRightArrow, opt->rect, mi.direction);
- drawPrimitive(arrow, &mi, p, w);
- }
- } else if (hasStyleRule(w, PseudoElement_MenuCheckMark) || hasStyleRule(w, PseudoElement_MenuRightArrow)) {
- QWindowsStyle::drawControl(ce, &mi, p, w);
- if (mi.checkType != QStyleOptionMenuItem::NotCheckable && !mi.checked) {
- // We have a style defined, but QWindowsStyle won't draw anything if not checked.
- // So we mimick what QWindowsStyle would do.
- int checkcol = qMax<int>(mi.maxIconWidth, QWindowsStylePrivate::windowsCheckMarkWidth);
- QRect vCheckRect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x(), mi.rect.y(), checkcol, mi.rect.height()));
- if (mi.state.testFlag(State_Enabled) && mi.state.testFlag(State_Selected)) {
- qDrawShadePanel(p, vCheckRect, mi.palette, true, 1, &mi.palette.brush(QPalette::Button));
- } else {
- QBrush fill(mi.palette.light().color(), Qt::Dense4Pattern);
- qDrawShadePanel(p, vCheckRect, mi.palette, true, 1, &fill);
- }
- QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
- if (subSubRule.hasDrawable()) {
- QStyleOptionMenuItem newMi(mi);
- newMi.rect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x() + QWindowsStylePrivate::windowsItemFrame,
- mi.rect.y() + QWindowsStylePrivate::windowsItemFrame,
- checkcol - 2 * QWindowsStylePrivate::windowsItemFrame,
- mi.rect.height() - 2 * QWindowsStylePrivate::windowsItemFrame));
- drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, w);
- }
- }
- } else {
- if (rule.hasDrawable() && !subRule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
- mi.palette.setColor(QPalette::Window, Qt::transparent);
- mi.palette.setColor(QPalette::Button, Qt::transparent);
- }
- if (rule.baseStyleCanDraw() && subRule.baseStyleCanDraw()) {
- baseStyle()->drawControl(ce, &mi, p, w);
- } else {
- ParentStyle::drawControl(ce, &mi, p, w);
- }
- }
-
- if (subRule.hasFont)
- p->setFont(oldFont);
-
- return;
- }
- return;
-
- case CE_MenuBarItem:
- if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- QStyleOptionMenuItem mi(*m);
- QRenderRule subRule = renderRule(w, opt, PseudoElement_Item);
- mi.rect = subRule.contentsRect(opt->rect);
- rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
- subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
-
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- QCommonStyle::drawControl(ce, &mi, p, w);
- } else {
- if (rule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
- // So that the menu bar background is not hidden by the items
- mi.palette.setColor(QPalette::Window, Qt::transparent);
- mi.palette.setColor(QPalette::Button, Qt::transparent);
- }
- baseStyle()->drawControl(ce, &mi, p, w);
- }
- }
- return;
-
-#ifndef QT_NO_COMBOBOX
- case CE_ComboBoxLabel:
- if (!rule.hasBox())
- break;
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QRect editRect = subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, w);
- p->save();
- p->setClipRect(editRect);
- if (!cb->currentIcon.isNull()) {
- int spacing = rule.hasBox() ? rule.box()->spacing : -1;
- if (spacing == -1)
- spacing = 6;
- QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
- QRect iconRect(editRect);
- iconRect.setWidth(cb->iconSize.width());
- iconRect = alignedRect(cb->direction,
- Qt::AlignLeft | Qt::AlignVCenter,
- iconRect.size(), editRect);
- drawItemPixmap(p, iconRect, Qt::AlignCenter, pixmap);
-
- if (cb->direction == Qt::RightToLeft)
- editRect.translate(-spacing - cb->iconSize.width(), 0);
- else
- editRect.translate(cb->iconSize.width() + spacing, 0);
- }
- if (!cb->currentText.isEmpty() && !cb->editable) {
- QPalette styledPalette(cb->palette);
- rule.configurePalette(&styledPalette, QPalette::Text, QPalette::Base);
- drawItemText(p, editRect.adjusted(0, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, styledPalette,
- cb->state & State_Enabled, cb->currentText, QPalette::Text);
- }
- p->restore();
- return;
- }
- break;
-#endif // QT_NO_COMBOBOX
-
- case CE_Header:
- if (hasStyleRule(w, PseudoElement_HeaderViewUpArrow)
- || hasStyleRule(w, PseudoElement_HeaderViewDownArrow)) {
- ParentStyle::drawControl(ce, opt, p, w);
- return;
- }
- if(hasStyleRule(w, PseudoElement_HeaderViewSection)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
- if (!subRule.hasNativeBorder() || !subRule.baseStyleCanDraw()
- || subRule.hasBackground() || subRule.hasPalette()) {
- ParentStyle::drawControl(ce, opt, p, w);
- return;
- }
- }
- break;
- case CE_HeaderSection:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
- if (subRule.hasNativeBorder()) {
- QStyleOptionHeader hdr(*header);
- subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
-
- if (subRule.baseStyleCanDraw()) {
- baseStyle()->drawControl(CE_HeaderSection, &hdr, p, w);
- } else {
- QWindowsStyle::drawControl(CE_HeaderSection, &hdr, p, w);
- }
- } else {
- subRule.drawRule(p, opt->rect);
- }
- return;
- }
- break;
-
- case CE_HeaderLabel:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QStyleOptionHeader hdr(*header);
- QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
- subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
- QFont oldFont = p->font();
- if (subRule.hasFont)
- p->setFont(subRule.font.resolve(p->font()));
- baseStyle()->drawControl(ce, &hdr, p, w);
- if (subRule.hasFont)
- p->setFont(oldFont);
- return;
- }
- break;
-
- case CE_HeaderEmptyArea:
- if (rule.hasDrawable()) {
- return;
- }
- break;
-
- case CE_ProgressBar:
- QWindowsStyle::drawControl(ce, opt, p, w);
- return;
-
- case CE_ProgressBarGroove:
- if (!rule.hasNativeBorder()) {
- rule.drawRule(p, rule.boxRect(opt->rect, Margin));
- return;
- }
- break;
-
- case CE_ProgressBarContents: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
- if (subRule.hasDrawable()) {
- if (const QStyleOptionProgressBarV2 *pb = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- p->save();
- p->setClipRect(pb->rect);
-
- qint64 minimum = qint64(pb->minimum);
- qint64 maximum = qint64(pb->maximum);
- qint64 progress = qint64(pb->progress);
- bool vertical = (pb->orientation == Qt::Vertical);
- bool inverted = pb->invertedAppearance;
-
- QTransform m;
- QRect rect = pb->rect;
- if (vertical) {
- rect = QRect(rect.y(), rect.x(), rect.height(), rect.width());
- m.rotate(90);
- m.translate(0, -(rect.height() + rect.y()*2));
- }
-
- bool reverse = ((!vertical && (pb->direction == Qt::RightToLeft)) || vertical);
- if (inverted)
- reverse = !reverse;
- const bool indeterminate = pb->minimum == pb->maximum;
- qreal fillRatio = indeterminate ? 0.50 : qreal(progress - minimum)/(maximum - minimum);
- int fillWidth = int(rect.width() * fillRatio);
- int chunkWidth = fillWidth;
- if (subRule.hasContentsSize()) {
- QSize sz = subRule.size();
- chunkWidth = (opt->state & QStyle::State_Horizontal) ? sz.width() : sz.height();
- }
-
- QRect r = rect;
- if (pb->minimum == 0 && pb->maximum == 0) {
- Q_D(const QWindowsStyle);
- int chunkCount = fillWidth/chunkWidth;
- int offset = (d->animateStep*8%rect.width());
- int x = reverse ? r.left() + r.width() - offset - chunkWidth : r.x() + offset;
- while (chunkCount > 0) {
- r.setRect(x, rect.y(), chunkWidth, rect.height());
- r = m.mapRect(QRectF(r)).toRect();
- subRule.drawRule(p, r);
- x += reverse ? -chunkWidth : chunkWidth;
- if (reverse ? x < rect.left() : x > rect.right())
- break;
- --chunkCount;
- }
-
- r = rect;
- x = reverse ? r.right() - (r.left() - x - chunkWidth)
- : r.left() + (x - r.right() - chunkWidth);
- while (chunkCount > 0) {
- r.setRect(x, rect.y(), chunkWidth, rect.height());
- r = m.mapRect(QRectF(r)).toRect();
- subRule.drawRule(p, r);
- x += reverse ? -chunkWidth : chunkWidth;
- --chunkCount;
- };
- } else {
- int x = reverse ? r.left() + r.width() - chunkWidth : r.x();
-
- for (int i = 0; i < ceil(qreal(fillWidth)/chunkWidth); ++i) {
- r.setRect(x, rect.y(), chunkWidth, rect.height());
- r = m.mapRect(QRectF(r)).toRect();
- subRule.drawRule(p, r);
- x += reverse ? -chunkWidth : chunkWidth;
- }
- }
-
- p->restore();
- return;
- }
- }
- }
- break;
-
- case CE_ProgressBarLabel:
- if (const QStyleOptionProgressBarV2 *pb = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_ProgressBarChunk)) {
- drawItemText(p, pb->rect, pb->textAlignment | Qt::TextSingleLine, pb->palette,
- pb->state & State_Enabled, pb->text, QPalette::Text);
- } else {
- QStyleOptionProgressBarV2 pbCopy(*pb);
- rule.configurePalette(&pbCopy.palette, QPalette::HighlightedText, QPalette::Highlight);
- baseStyle()->drawControl(ce, &pbCopy, p, w);
- }
- return;
- }
- break;
-
- case CE_SizeGrip:
- if (const QStyleOptionSizeGrip *sgOpt = qstyleoption_cast<const QStyleOptionSizeGrip *>(opt)) {
- if (rule.hasDrawable()) {
- rule.drawFrame(p, opt->rect);
- p->save();
- switch (sgOpt->corner) {
- case Qt::BottomRightCorner: break;
- case Qt::BottomLeftCorner: p->rotate(90); break;
- case Qt::TopLeftCorner: p->rotate(180); break;
- case Qt::TopRightCorner: p->rotate(270); break;
- default: break;
- }
- rule.drawImage(p, opt->rect);
- p->restore();
- } else {
- QStyleOptionSizeGrip sg(*sgOpt);
- sg.rect = rule.contentsRect(opt->rect);
- baseStyle()->drawControl(CE_SizeGrip, &sg, p, w);
- }
- return;
- }
- break;
-
- case CE_ToolBoxTab:
- QWindowsStyle::drawControl(ce, opt, p, w);
- return;
-
- case CE_ToolBoxTabShape: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolBoxTab);
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- return;
- }
- }
- break;
-
- case CE_ToolBoxTabLabel:
- if (const QStyleOptionToolBox *box = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
- QStyleOptionToolBox boxCopy(*box);
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolBoxTab);
- subRule.configurePalette(&boxCopy.palette, QPalette::ButtonText, QPalette::Button);
- QFont oldFont = p->font();
- if (subRule.hasFont)
- p->setFont(subRule.font);
- boxCopy.rect = subRule.contentsRect(opt->rect);
- QWindowsStyle::drawControl(ce, &boxCopy, p , w);
- if (subRule.hasFont)
- p->setFont(oldFont);
- return;
- }
- break;
-
- case CE_ScrollBarAddPage:
- pe1 = PseudoElement_ScrollBarAddPage;
- break;
-
- case CE_ScrollBarSubPage:
- pe1 = PseudoElement_ScrollBarSubPage;
- break;
-
- case CE_ScrollBarAddLine:
- pe1 = PseudoElement_ScrollBarAddLine;
- pe2 = (opt->state & QStyle::State_Horizontal) ? PseudoElement_ScrollBarRightArrow : PseudoElement_ScrollBarDownArrow;
- fallback = true;
- break;
-
- case CE_ScrollBarSubLine:
- pe1 = PseudoElement_ScrollBarSubLine;
- pe2 = (opt->state & QStyle::State_Horizontal) ? PseudoElement_ScrollBarLeftArrow : PseudoElement_ScrollBarUpArrow;
- fallback = true;
- break;
-
- case CE_ScrollBarFirst:
- pe1 = PseudoElement_ScrollBarFirst;
- break;
-
- case CE_ScrollBarLast:
- pe1 = PseudoElement_ScrollBarLast;
- break;
-
- case CE_ScrollBarSlider:
- pe1 = PseudoElement_ScrollBarSlider;
- fallback = true;
- break;
-
-#ifndef QT_NO_ITEMVIEWS
- case CE_ItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
- if (subRule.hasDrawable() || hasStyleRule(w, PseudoElement_Indicator)) {
- QStyleOptionViewItemV4 optCopy(*vopt);
- subRule.configurePalette(&optCopy.palette, vopt->state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text,
- vopt->state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base);
- QWindowsStyle::drawControl(ce, &optCopy, p, w);
- } else {
- QStyleOptionViewItemV4 voptCopy(*vopt);
- subRule.configurePalette(&voptCopy.palette, QPalette::Text, QPalette::NoRole);
- baseStyle()->drawControl(ce, &voptCopy, p, w);
- }
- return;
- }
- break;
-#endif // QT_NO_ITEMVIEWS
-
-#ifndef QT_NO_TABBAR
- case CE_TabBarTab:
- if (hasStyleRule(w, PseudoElement_TabBarTab)) {
- QWindowsStyle::drawControl(ce, opt, p, w);
- return;
- }
- break;
-
- case CE_TabBarTabLabel:
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- QStyleOptionTabV3 tabCopy(*tab);
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- QRect r = positionRect(w, subRule, PseudoElement_TabBarTab, opt->rect, opt->direction);
- if (ce == CE_TabBarTabShape && subRule.hasDrawable()) {
- subRule.drawRule(p, r);
- return;
- }
- subRule.configurePalette(&tabCopy.palette, QPalette::WindowText, QPalette::Window);
- QFont oldFont = p->font();
- if (subRule.hasFont)
- p->setFont(subRule.font);
- if (subRule.hasBox() || !subRule.hasNativeBorder()) {
- tabCopy.rect = ce == CE_TabBarTabShape ? subRule.borderRect(r)
- : subRule.contentsRect(r);
- QWindowsStyle::drawControl(ce, &tabCopy, p, w);
- } else {
- baseStyle()->drawControl(ce, &tabCopy, p, w);
- }
- if (subRule.hasFont)
- p->setFont(oldFont);
-
- return;
- }
- break;
-#endif // QT_NO_TABBAR
-
- case CE_ColumnViewGrip:
- if (rule.hasDrawable()) {
- rule.drawRule(p, opt->rect);
- return;
- }
- break;
-
- case CE_DockWidgetTitle:
- if (const QStyleOptionDockWidgetV2 *dwOpt = qstyleoption_cast<const QStyleOptionDockWidgetV2 *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
- if (!subRule.hasDrawable() && !subRule.hasPosition())
- break;
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- } else {
- QStyleOptionDockWidgetV2 dwCopy(*dwOpt);
- dwCopy.title = QString();
- baseStyle()->drawControl(ce, &dwCopy, p, w);
- }
-
- if (!dwOpt->title.isEmpty()) {
- QRect r = opt->rect;
- if (dwOpt->verticalTitleBar) {
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- p->save();
- p->translate(r.left(), r.top() + r.width());
- p->rotate(-90);
- p->translate(-r.left(), -r.top());
- }
-
- Qt::Alignment alignment = 0;
- if (subRule.hasPosition())
- alignment = subRule.position()->textAlignment;
- if (alignment == 0)
- alignment = Qt::AlignLeft;
- drawItemText(p, subRule.contentsRect(opt->rect),
- alignment | Qt::TextShowMnemonic, dwOpt->palette,
- dwOpt->state & State_Enabled, dwOpt->title,
- QPalette::WindowText);
-
- if (dwOpt->verticalTitleBar)
- p->restore();
- }
-
- return;
- }
- break;
- case CE_ShapedFrame:
- if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (rule.hasNativeBorder()) {
- QStyleOptionFrameV3 frmOpt(*frm);
- rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
- frmOpt.rect = rule.borderRect(frmOpt.rect);
- baseStyle()->drawControl(ce, &frmOpt, p, w);
- }
- // else, borders are already drawn in PE_Widget
- }
- return;
-
-
- default:
- break;
- }
-
- if (pe1 != PseudoElement_None) {
- QRenderRule subRule = renderRule(w, opt, pe1);
- if (subRule.bg != 0 || subRule.hasDrawable()) {
- //We test subRule.bg directly because hasBackground() would return false for background:none.
- //But we still don't want the default drawning in that case (example for QScrollBar::add-page) (task 198926)
- subRule.drawRule(p, opt->rect);
- } else if (fallback) {
- QWindowsStyle::drawControl(ce, opt, p, w);
- pe2 = PseudoElement_None;
- } else {
- baseStyle()->drawControl(ce, opt, p, w);
- }
- if (pe2 != PseudoElement_None) {
- QRenderRule subSubRule = renderRule(w, opt, pe2);
- QRect r = positionRect(w, subRule, subSubRule, pe2, opt->rect, opt->direction);
- subSubRule.drawRule(p, r);
- }
- return;
- }
-
- baseStyle()->drawControl(ce, opt, p, w);
-}
-
-void QStyleSheetStyle::drawItemPixmap(QPainter *p, const QRect &rect, int alignment, const
- QPixmap &pixmap) const
-{
- baseStyle()->drawItemPixmap(p, rect, alignment, pixmap);
-}
-
-void QStyleSheetStyle::drawItemText(QPainter *painter, const QRect& rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const
-{
- baseStyle()->drawItemText(painter, rect, alignment, pal, enabled, text, textRole);
-}
-
-void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w) const
-{
- RECURSION_GUARD(baseStyle()->drawPrimitive(pe, opt, p, w); return)
-
- int pseudoElement = PseudoElement_None;
- QRenderRule rule = renderRule(w, opt);
- QRect rect = opt->rect;
-
- switch (pe) {
-
- case PE_FrameStatusBar: {
- QRenderRule subRule = renderRule(w->parentWidget(), opt, PseudoElement_Item);
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- return;
- }
- break;
- }
-
- case PE_IndicatorArrowDown:
- pseudoElement = PseudoElement_DownArrow;
- break;
-
- case PE_IndicatorArrowUp:
- pseudoElement = PseudoElement_UpArrow;
- break;
-
- case PE_IndicatorRadioButton:
- pseudoElement = PseudoElement_ExclusiveIndicator;
- break;
-
- case PE_IndicatorViewItemCheck:
- pseudoElement = PseudoElement_ViewItemIndicator;
- break;
-
- case PE_IndicatorCheckBox:
- pseudoElement = PseudoElement_Indicator;
- break;
-
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- pseudoElement = hdr->sortIndicator == QStyleOptionHeader::SortUp
- ? PseudoElement_HeaderViewUpArrow
- : PseudoElement_HeaderViewDownArrow;
- }
- break;
-
- case PE_PanelButtonTool:
- case PE_PanelButtonCommand:
- if (qobject_cast<const QAbstractButton *>(w) && rule.hasBackground() && rule.hasNativeBorder()) {
- //the window style will draw the borders
- ParentStyle::drawPrimitive(pe, opt, p, w);
- if (!rule.background()->pixmap.isNull() || rule.hasImage()) {
- rule.drawRule(p, rule.boxRect(opt->rect, QRenderRule::Margin).adjusted(1,1,-1,-1));
- }
- return;
- }
- if (!rule.hasNativeBorder()) {
- rule.drawRule(p, rule.boxRect(opt->rect, QRenderRule::Margin));
- return;
- }
- break;
-
- case PE_IndicatorButtonDropDown: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
- if (!subRule.hasNativeBorder()) {
- rule.drawBorder(p, opt->rect);
- return;
- }
- break;
- }
-
- case PE_FrameDefaultButton:
- if (rule.hasNativeBorder()) {
- if (rule.baseStyleCanDraw())
- break;
- QWindowsStyle::drawPrimitive(pe, opt, p, w);
- }
- return;
-
- case PE_FrameWindow:
- case PE_FrameDockWidget:
- case PE_Frame:
- if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (rule.hasNativeBorder()) {
- QStyleOptionFrameV2 frmOpt(*frm);
- rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
- if (!qstyleoption_cast<const QStyleOptionFrameV3 *>(opt)) //if it comes from CE_ShapedFrame, the margins are already sustracted
- frmOpt.rect = rule.borderRect(frmOpt.rect);
- baseStyle()->drawPrimitive(pe, &frmOpt, p, w);
- } else {
- rule.drawBorder(p, rule.borderRect(opt->rect));
- }
- }
- return;
-
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
-#ifndef QT_NO_SPINBOX
- if (w && qobject_cast<const QAbstractSpinBox *>(w->parentWidget())) {
- QRenderRule spinboxRule = renderRule(w->parentWidget(), opt);
- if (!spinboxRule.hasNativeBorder() || !spinboxRule.baseStyleCanDraw())
- return;
- rule = spinboxRule;
- }
-#endif
- if (rule.hasNativeBorder()) {
- QStyleOptionFrame frmOpt(*frm);
- rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
- frmOpt.rect = rule.borderRect(frmOpt.rect);
- if (rule.baseStyleCanDraw()) {
- rule.drawBackgroundImage(p, opt->rect);
- baseStyle()->drawPrimitive(pe, &frmOpt, p, w);
- } else {
- rule.drawBackground(p, opt->rect);
- if (frmOpt.lineWidth > 0)
- baseStyle()->drawPrimitive(PE_FrameLineEdit, &frmOpt, p, w);
- }
- } else {
- rule.drawRule(p, opt->rect);
- }
- }
- return;
-
- case PE_Widget:
- if (w && !rule.hasDrawable()) {
- QWidget *container = containerWidget(w);
- if (styleSheetCaches->autoFillDisabledWidgets.contains(container)
- && (container == w || !renderRule(container, opt).hasBackground())) {
- //we do not have a background, but we disabled the autofillbackground anyway. so fill the background now.
- // (this may happen if we have rules like :focus)
- p->fillRect(opt->rect, opt->palette.brush(w->backgroundRole()));
- }
- break;
- }
-#ifndef QT_NO_SCROLLAREA
- if (const QAbstractScrollArea *sa = qobject_cast<const QAbstractScrollArea *>(w)) {
- const QAbstractScrollAreaPrivate *sap = sa->d_func();
- rule.drawBackground(p, opt->rect, sap->contentsOffset());
- if (rule.hasBorder()) {
- QRect brect = rule.borderRect(opt->rect);
- if (styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, opt, w)) {
- QRect r = brect.adjusted(0, 0, sa->verticalScrollBar()->isVisible() ? -sa->verticalScrollBar()->width() : 0,
- sa->horizontalScrollBar()->isVisible() ? -sa->horizontalScrollBar()->height() : 0);
- brect = QStyle::visualRect(opt->direction, brect, r);
- }
- rule.drawBorder(p, brect);
- }
- break;
- }
-#endif
- //fall tghought
- case PE_PanelMenu:
- case PE_PanelStatusBar:
- if(rule.hasDrawable()) {
- rule.drawRule(p, opt->rect);
- return;
- }
- break;
-
- case PE_FrameMenu:
- if (rule.hasDrawable()) {
- // Drawn by PE_PanelMenu
- return;
- }
- break;
-
- case PE_PanelMenuBar:
- if (rule.hasDrawable()) {
- // Drawn by PE_Widget
- return;
- }
- break;
-
- case PE_IndicatorToolBarSeparator:
- case PE_IndicatorToolBarHandle: {
- PseudoElement ps = pe == PE_IndicatorToolBarHandle ? PseudoElement_ToolBarHandle : PseudoElement_ToolBarSeparator;
- QRenderRule subRule = renderRule(w, opt, ps);
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, opt->rect);
- return;
- }
- }
- break;
-
- case PE_IndicatorMenuCheckMark:
- pseudoElement = PseudoElement_MenuCheckMark;
- break;
-
- case PE_IndicatorArrowLeft:
- pseudoElement = PseudoElement_LeftArrow;
- break;
-
- case PE_IndicatorArrowRight:
- pseudoElement = PseudoElement_RightArrow;
- break;
-
- case PE_IndicatorColumnViewArrow:
- if (const QStyleOptionViewItem *viewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
- bool reverse = (viewOpt->direction == Qt::RightToLeft);
- pseudoElement = reverse ? PseudoElement_LeftArrow : PseudoElement_RightArrow;
- } else {
- pseudoElement = PseudoElement_RightArrow;
- }
- break;
-
- case PE_IndicatorBranch:
- if (const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TreeViewBranch);
- if (subRule.hasDrawable()) {
- if ((v2->state & QStyle::State_Selected) && v2->showDecorationSelected)
- p->fillRect(v2->rect, v2->palette.highlight());
- else if (v2->features & QStyleOptionViewItemV2::Alternate)
- p->fillRect(v2->rect, v2->palette.alternateBase());
- subRule.drawRule(p, opt->rect);
- } else {
- baseStyle()->drawPrimitive(pe, v2, p, w);
- }
- }
- return;
-
- case PE_PanelTipLabel:
- if (!rule.hasDrawable())
- break;
-
- if (const QStyleOptionFrame *frmOpt = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (rule.hasNativeBorder()) {
- rule.drawBackground(p, opt->rect);
- QStyleOptionFrame optCopy(*frmOpt);
- optCopy.rect = rule.borderRect(opt->rect);
- optCopy.palette.setBrush(QPalette::Window, Qt::NoBrush); // oh dear
- baseStyle()->drawPrimitive(pe, &optCopy, p, w);
- } else {
- rule.drawRule(p, opt->rect);
- }
- }
- return;
-
- case PE_FrameGroupBox:
- if (rule.hasNativeBorder())
- break;
- rule.drawBorder(p, opt->rect);
- return;
-
-#ifndef QT_NO_TABWIDGET
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *frm = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TabWidgetPane);
- if (subRule.hasNativeBorder()) {
- subRule.drawBackground(p, opt->rect);
- QStyleOptionTabWidgetFrameV2 frmCopy(*frm);
- subRule.configurePalette(&frmCopy.palette, QPalette::WindowText, QPalette::Window);
- baseStyle()->drawPrimitive(pe, &frmCopy, p, w);
- } else {
- subRule.drawRule(p, opt->rect);
- }
- return;
- }
- break;
-#endif // QT_NO_TABWIDGET
-
- case PE_IndicatorProgressChunk:
- pseudoElement = PseudoElement_ProgressBarChunk;
- break;
-
- case PE_IndicatorTabTear:
- pseudoElement = PseudoElement_TabBarTear;
- break;
-
- case PE_FrameFocusRect:
- if (!rule.hasNativeOutline()) {
- rule.drawOutline(p, opt->rect);
- return;
- }
- break;
-
- case PE_IndicatorDockWidgetResizeHandle:
- pseudoElement = PseudoElement_DockWidgetSeparator;
- break;
-
- case PE_PanelItemViewItem:
- pseudoElement = PseudoElement_ViewItem;
- break;
-
- case PE_PanelScrollAreaCorner:
- pseudoElement = PseudoElement_ScrollAreaCorner;
- break;
-
- case PE_IndicatorSpinDown:
- case PE_IndicatorSpinMinus:
- pseudoElement = PseudoElement_SpinBoxDownArrow;
- break;
-
- case PE_IndicatorSpinUp:
- case PE_IndicatorSpinPlus:
- pseudoElement = PseudoElement_SpinBoxUpArrow;
- break;
-#ifndef QT_NO_TABBAR
- case PE_IndicatorTabClose:
- if (w)
- w = w->parentWidget(); //match on the QTabBar instead of the CloseButton
- pseudoElement = PseudoElement_TabBarTabCloseButton;
-#endif
-
- default:
- break;
- }
-
- if (pseudoElement != PseudoElement_None) {
- QRenderRule subRule = renderRule(w, opt, pseudoElement);
- if (subRule.hasDrawable()) {
- subRule.drawRule(p, rect);
- } else {
- baseStyle()->drawPrimitive(pe, opt, p, w);
- }
- } else {
- baseStyle()->drawPrimitive(pe, opt, p, w);
- }
-}
-
-QPixmap QStyleSheetStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap& pixmap,
- const QStyleOption *option) const
-{
- return baseStyle()->generatedIconPixmap(iconMode, pixmap, option);
-}
-
-QStyle::SubControl QStyleSheetStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->hitTestComplexControl(cc, opt, pt, w))
- switch (cc) {
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- QRenderRule rule = renderRule(w, opt, PseudoElement_TitleBar);
- if (rule.hasDrawable() || rule.hasBox() || rule.hasBorder()) {
- QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
- QRect r;
- QStyle::SubControl sc = QStyle::SC_None;
- uint ctrl = SC_TitleBarSysMenu;
- while (ctrl <= SC_TitleBarLabel) {
- r = layout[QStyle::SubControl(ctrl)];
- if (r.isValid() && r.contains(pt)) {
- sc = QStyle::SubControl(ctrl);
- break;
- }
- ctrl <<= 1;
- }
- return sc;
- }
- }
- break;
-
- case CC_MdiControls:
- if (hasStyleRule(w, PseudoElement_MdiCloseButton)
- || hasStyleRule(w, PseudoElement_MdiNormalButton)
- || hasStyleRule(w, PseudoElement_MdiMinButton))
- return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
- break;
-
- case CC_ScrollBar: {
- QRenderRule rule = renderRule(w, opt);
- if (!rule.hasDrawable() && !rule.hasBox())
- break;
- }
- // intentionally falls through
- case CC_SpinBox:
- case CC_GroupBox:
- case CC_ComboBox:
- case CC_Slider:
- case CC_ToolButton:
- return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
- default:
- break;
- }
-
- return baseStyle()->hitTestComplexControl(cc, opt, pt, w);
-}
-
-QRect QStyleSheetStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const
-{
- return baseStyle()->itemPixmapRect(rect, alignment, pixmap);
-}
-
-QRect QStyleSheetStyle::itemTextRect(const QFontMetrics &metrics, const QRect& rect, int alignment,
- bool enabled, const QString& text) const
-{
- return baseStyle()->itemTextRect(metrics, rect, alignment, enabled, text);
-}
-
-int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->pixelMetric(m, opt, w))
-
- QRenderRule rule = renderRule(w, opt);
- QRenderRule subRule;
-
- switch (m) {
- case PM_MenuButtonIndicator:
-#ifndef QT_NO_TOOLBUTTON
- // QToolButton adds this directly to the width
- if (qobject_cast<const QToolButton *>(w) && (rule.hasBox() || !rule.hasNativeBorder()))
- return 0;
-#endif
- subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
- if (subRule.hasContentsSize())
- return subRule.size().width();
- break;
-
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- case PM_ButtonMargin:
- case PM_ButtonDefaultIndicator:
- if (rule.hasBox())
- return 0;
- break;
-
- case PM_DefaultFrameWidth:
- if (!rule.hasNativeBorder())
- return rule.border()->borders[LeftEdge];
- break;
-
- case PM_ExclusiveIndicatorWidth:
- case PM_IndicatorWidth:
- case PM_ExclusiveIndicatorHeight:
- case PM_IndicatorHeight:
- subRule = renderRule(w, opt, PseudoElement_Indicator);
- if (subRule.hasContentsSize()) {
- return (m == PM_ExclusiveIndicatorWidth) || (m == PM_IndicatorWidth)
- ? subRule.size().width() : subRule.size().height();
- }
- break;
-
- case PM_DockWidgetFrameWidth:
- case PM_ToolTipLabelFrameWidth: // border + margin + padding (support only one width)
- if (!rule.hasDrawable())
- break;
-
- return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
- + (rule.hasBox() ? rule.box()->margins[LeftEdge] + rule.box()->paddings[LeftEdge]: 0);
-
- case PM_ToolBarFrameWidth:
- if (rule.hasBorder() || rule.hasBox())
- return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
- + (rule.hasBox() ? rule.box()->paddings[LeftEdge]: 0);
- break;
-
- case PM_MenuPanelWidth:
- case PM_MenuBarPanelWidth:
- if (rule.hasBorder() || rule.hasBox())
- return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
- + (rule.hasBox() ? rule.box()->margins[LeftEdge]: 0);
- break;
-
-
- case PM_MenuHMargin:
- case PM_MenuBarHMargin:
- if (rule.hasBox())
- return rule.box()->paddings[LeftEdge];
- break;
-
- case PM_MenuVMargin:
- case PM_MenuBarVMargin:
- if (rule.hasBox())
- return rule.box()->paddings[TopEdge];
- break;
-
- case PM_DockWidgetTitleBarButtonMargin:
- case PM_ToolBarItemMargin:
- if (rule.hasBox())
- return rule.box()->margins[TopEdge];
- break;
-
- case PM_ToolBarItemSpacing:
- case PM_MenuBarItemSpacing:
- if (rule.hasBox() && rule.box()->spacing != -1)
- return rule.box()->spacing;
- break;
-
- case PM_MenuTearoffHeight:
- case PM_MenuScrollerHeight: {
- PseudoElement ps = m == PM_MenuTearoffHeight ? PseudoElement_MenuTearoff : PseudoElement_MenuScroller;
- subRule = renderRule(w, opt, ps);
- if (subRule.hasContentsSize())
- return subRule.size().height();
- break;
- }
-
- case PM_ToolBarExtensionExtent:
- break;
-
- case PM_SplitterWidth:
- case PM_ToolBarSeparatorExtent:
- case PM_ToolBarHandleExtent: {
- PseudoElement ps;
- if (m == PM_ToolBarHandleExtent) ps = PseudoElement_ToolBarHandle;
- else if (m == PM_SplitterWidth) ps = PseudoElement_SplitterHandle;
- else ps = PseudoElement_ToolBarSeparator;
- subRule = renderRule(w, opt, ps);
- if (subRule.hasContentsSize()) {
- QSize sz = subRule.size();
- return (opt && opt->state & QStyle::State_Horizontal) ? sz.width() : sz.height();
- }
- break;
- }
-
- case PM_RadioButtonLabelSpacing:
- if (rule.hasBox() && rule.box()->spacing != -1)
- return rule.box()->spacing;
- break;
- case PM_CheckBoxLabelSpacing:
- if (qobject_cast<const QCheckBox *>(w)) {
- if (rule.hasBox() && rule.box()->spacing != -1)
- return rule.box()->spacing;
- }
- // assume group box
- subRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
- if (subRule.hasBox() && subRule.box()->spacing != -1)
- return subRule.box()->spacing;
- break;
-
-#ifndef QT_NO_SCROLLBAR
- case PM_ScrollBarExtent:
- if (rule.hasContentsSize()) {
- QSize sz = rule.size();
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt))
- return sb->orientation == Qt::Horizontal ? sz.height() : sz.width();
- return sz.width() == -1 ? sz.height() : sz.width();
- }
- break;
-
- case PM_ScrollBarSliderMin:
- if (hasStyleRule(w, PseudoElement_ScrollBarSlider)) {
- subRule = renderRule(w, opt, PseudoElement_ScrollBarSlider);
- QSize msz = subRule.minimumSize();
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt))
- return sb->orientation == Qt::Horizontal ? msz.width() : msz.height();
- return msz.width() == -1 ? msz.height() : msz.width();
- }
- break;
-
- case PM_ScrollView_ScrollBarSpacing:
- if(!rule.hasNativeBorder() || rule.hasBox())
- return 0;
- break;
-#endif // QT_NO_SCROLLBAR
-
- case PM_ProgressBarChunkWidth:
- subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
- if (subRule.hasContentsSize()) {
- QSize sz = subRule.size();
- return (opt->state & QStyle::State_Horizontal)
- ? sz.width() : sz.height();
- }
- break;
-
-#ifndef QT_NO_TABWIDGET
- case PM_TabBarTabHSpace:
- case PM_TabBarTabVSpace:
- subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- if (subRule.hasBox() || subRule.hasBorder())
- return 0;
- break;
-
- case PM_TabBarScrollButtonWidth: {
- subRule = renderRule(w, opt, PseudoElement_TabBarScroller);
- if (subRule.hasContentsSize()) {
- QSize sz = subRule.size();
- return sz.width() != -1 ? sz.width() : sz.height();
- }
- }
- break;
-
- case PM_TabBarTabShiftHorizontal:
- case PM_TabBarTabShiftVertical:
- subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- if (subRule.hasBox())
- return 0;
- break;
-
- case PM_TabBarBaseOverlap: {
- const QWidget *tabWidget = qobject_cast<const QTabWidget *>(w) ? w : w->parentWidget();
- if (hasStyleRule(tabWidget, PseudoElement_TabWidgetPane)) {
- return 0;
- }
- break;
- }
-#endif // QT_NO_TABWIDGET
-
- case PM_SliderThickness: // horizontal slider's height (sizeHint)
- case PM_SliderLength: // minimum length of slider
- if (rule.hasContentsSize()) {
- bool horizontal = opt->state & QStyle::State_Horizontal;
- if (m == PM_SliderThickness) {
- QSize sz = rule.size();
- return horizontal ? sz.height() : sz.width();
- } else {
- QSize msz = rule.minimumContentsSize();
- return horizontal ? msz.width() : msz.height();
- }
- }
- break;
-
- case PM_SliderControlThickness: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_SliderHandle);
- if (!subRule.hasContentsSize())
- break;
- QSize size = subRule.size();
- return (opt->state & QStyle::State_Horizontal) ? size.height() : size.width();
- }
-
- case PM_ToolBarIconSize:
- case PM_ListViewIconSize:
- case PM_IconViewIconSize:
- case PM_TabBarIconSize:
- case PM_MessageBoxIconSize:
- case PM_ButtonIconSize:
- case PM_SmallIconSize:
- if (rule.hasStyleHint(QLatin1String("icon-size"))) {
- return rule.styleHint(QLatin1String("icon-size")).toSize().width();
- }
- break;
-
- case PM_DockWidgetTitleMargin: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
- if (!subRule.hasBox())
- break;
- return (subRule.border() ? subRule.border()->borders[TopEdge] : 0)
- + (subRule.hasBox() ? subRule.box()->margins[TopEdge] + subRule.box()->paddings[TopEdge]: 0);
- }
-
- case PM_DockWidgetSeparatorExtent: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetSeparator);
- if (!subRule.hasContentsSize())
- break;
- QSize sz = subRule.size();
- return qMax(sz.width(), sz.height());
- }
-
- case PM_TitleBarHeight: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
- if (subRule.hasContentsSize())
- return subRule.size().height();
- else if (subRule.hasBox() || subRule.hasBorder()) {
- QFontMetrics fm = opt ? opt->fontMetrics : w->fontMetrics();
- return subRule.size(QSize(0, fm.height())).height();
- }
- break;
- }
-
- case PM_MdiSubWindowFrameWidth:
- if (rule.hasBox() || rule.hasBorder()) {
- return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
- + (rule.hasBox() ? rule.box()->paddings[LeftEdge]+rule.box()->margins[LeftEdge]: 0);
- }
- break;
-
- case PM_MdiSubWindowMinimizedWidth: {
- QRenderRule subRule = renderRule(w, PseudoElement_None, PseudoClass_Minimized);
- int width = subRule.size().width();
- if (width != -1)
- return width;
- break;
- }
- default:
- break;
- }
-
- return baseStyle()->pixelMetric(m, opt, w);
-}
-
-QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &csz, const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->sizeFromContents(ct, opt, csz, w))
-
- QRenderRule rule = renderRule(w, opt);
- QSize sz = rule.adjustSize(csz);
-
- switch (ct) {
- case CT_SpinBox: // ### hopelessly broken QAbstractSpinBox (part 1)
- if (rule.hasBox() || !rule.hasNativeBorder())
- return csz;
- return rule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
- : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
- case CT_ToolButton:
- if (rule.hasBox() || !rule.hasNativeBorder() || !rule.baseStyleCanDraw())
- sz += QSize(3, 3); // ### broken QToolButton
- //fall thought
- case CT_ComboBox:
- case CT_PushButton:
- if (rule.hasBox() || !rule.hasNativeBorder()) {
- if(ct == CT_ComboBox) {
- //add some space for the drop down.
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
- QRect comboRect = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
- //+2 because there is hardcoded margins in QCommonStyle::drawControl(CE_ComboBoxLabel)
- sz += QSize(comboRect.width() + 2, 0);
- }
- return rule.boxSize(sz);
- }
- sz = rule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
- : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
- return rule.boxSize(sz, Margin);
-
- case CT_HeaderSection: {
- if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
- if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder()) {
- sz = subRule.adjustSize(csz);
- if (!subRule.hasGeometry()) {
- QSize nativeContentsSize;
- bool nullIcon = hdr->icon.isNull();
- int iconSize = nullIcon ? 0 : pixelMetric(QStyle::PM_SmallIconSize, hdr, w);
- QSize txt = hdr->fontMetrics.size(0, hdr->text);
- nativeContentsSize.setHeight(qMax(iconSize, txt.height()));
- nativeContentsSize.setWidth(iconSize + txt.width());
- sz = sz.expandedTo(nativeContentsSize);
- }
- return subRule.size(sz);
- }
- return subRule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
- : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
- }
- }
- break;
- case CT_GroupBox:
- case CT_LineEdit:
-#ifndef QT_NO_SPINBOX
- // ### hopelessly broken QAbstractSpinBox (part 2)
- if (QAbstractSpinBox *spinBox = qobject_cast<QAbstractSpinBox *>(w ? w->parentWidget() : 0)) {
- QRenderRule rule = renderRule(spinBox, opt);
- if (rule.hasBox() || !rule.hasNativeBorder())
- return csz;
- return rule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
- : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
- }
-#endif
- if (rule.hasBox() || !rule.hasNativeBorder()) {
- return rule.boxSize(sz);
- }
- break;
-
- case CT_CheckBox:
- case CT_RadioButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
- bool isRadio = (ct == CT_RadioButton);
- int iw = pixelMetric(isRadio ? PM_ExclusiveIndicatorWidth
- : PM_IndicatorWidth, btn, w);
- int ih = pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
- : PM_IndicatorHeight, btn, w);
-
- int spacing = pixelMetric(isRadio ? PM_RadioButtonLabelSpacing
- : PM_CheckBoxLabelSpacing, btn, w);
- sz.setWidth(sz.width() + iw + spacing);
- sz.setHeight(qMax(sz.height(), ih));
- return rule.boxSize(sz);
- }
- }
- break;
-
- case CT_Menu:
- case CT_MenuBar: // already has everything!
- case CT_ScrollBar:
- if (rule.hasBox() || rule.hasBorder())
- return sz;
- break;
-
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- PseudoElement pe = (mi->menuItemType == QStyleOptionMenuItem::Separator)
- ? PseudoElement_MenuSeparator : PseudoElement_Item;
- QRenderRule subRule = renderRule(w, opt, pe);
- if ((pe == PseudoElement_MenuSeparator) && subRule.hasContentsSize()) {
- return QSize(sz.width(), subRule.size().height());
- } else if ((pe == PseudoElement_Item) && (subRule.hasBox() || subRule.hasBorder())) {
- int width = csz.width();
- if (mi->text.contains(QLatin1Char('\t')))
- width += 12; //as in QCommonStyle
- return subRule.boxSize(subRule.adjustSize(QSize(width, csz.height())));
- }
- }
- break;
-
- case CT_Splitter:
- case CT_MenuBarItem: {
- PseudoElement pe = (ct == CT_Splitter) ? PseudoElement_SplitterHandle : PseudoElement_Item;
- QRenderRule subRule = renderRule(w, opt, pe);
- if (subRule.hasBox() || subRule.hasBorder())
- return subRule.boxSize(sz);
- break;
- }
-
- case CT_ProgressBar:
- case CT_SizeGrip:
- return (rule.hasContentsSize())
- ? rule.size(sz)
- : rule.boxSize(baseStyle()->sizeFromContents(ct, opt, sz, w));
- break;
-
- case CT_Slider:
- if (rule.hasBorder() || rule.hasBox() || rule.hasGeometry())
- return rule.boxSize(sz);
- break;
-
-#ifndef QT_NO_TABBAR
- case CT_TabBarTab: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- if (subRule.hasBox() || !subRule.hasNativeBorder()) {
- int spaceForIcon = 0;
- bool vertical = false;
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- if (!tab->icon.isNull())
- spaceForIcon = 6 /* icon offset */ + 4 /* spacing */ + 2 /* magic */; // ###: hardcoded to match with common style
- vertical = verticalTabs(tab->shape);
- }
- sz = csz + QSize(vertical ? 0 : spaceForIcon, vertical ? spaceForIcon : 0);
- return subRule.boxSize(subRule.adjustSize(sz));
- }
-#ifdef Q_WS_MAC
- if (baseStyle()->inherits("QMacStyle")) {
- //adjust the size after the call to the style because the mac style ignore the size arguments anyway.
- //this might cause the (max-){width,height} property to include the native style border while they should not.
- return subRule.adjustSize(baseStyle()->sizeFromContents(ct, opt, csz, w));
- }
-#endif
- sz = subRule.adjustSize(csz);
- break;
- }
-#endif // QT_NO_TABBAR
-
- case CT_MdiControls:
- if (const QStyleOptionComplex *ccOpt = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
- if (!hasStyleRule(w, PseudoElement_MdiCloseButton)
- && !hasStyleRule(w, PseudoElement_MdiNormalButton)
- && !hasStyleRule(w, PseudoElement_MdiMinButton))
- break;
-
- QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
- if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("mNX"));
-
- int width = 0, height = 0;
- for (int i = 0; i < layout.count(); i++) {
- int layoutButton = layout[i].toInt();
- if (layoutButton < PseudoElement_MdiCloseButton
- || layoutButton > PseudoElement_MdiNormalButton)
- continue;
- QStyle::SubControl sc = knownPseudoElements[layoutButton].subControl;
- if (!(ccOpt->subControls & sc))
- continue;
- QRenderRule subRule = renderRule(w, opt, layoutButton);
- QSize sz = subRule.size();
- width += sz.width();
- height = qMax(height, sz.height());
- }
-
- return QSize(width, height);
- }
- break;
-
-#ifndef QT_NO_ITEMVIEWS
- case CT_ItemViewItem: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
- sz = baseStyle()->sizeFromContents(ct, opt, csz, w);
- sz = subRule.adjustSize(sz);
- if (subRule.hasBox() || subRule.hasBorder())
- sz = subRule.boxSize(sz);
- return sz;
- }
-#endif // QT_NO_ITEMVIEWS
-
- default:
- break;
- }
-
- return baseStyle()->sizeFromContents(ct, opt, sz, w);
-}
-
-/*!
- \internal
-*/
-static QLatin1String propertyNameForStandardPixmap(QStyle::StandardPixmap sp)
-{
- switch (sp) {
- case QStyle::SP_TitleBarMenuButton: return QLatin1String("titlebar-menu-icon");
- case QStyle::SP_TitleBarMinButton: return QLatin1String("titlebar-minimize-icon");
- case QStyle::SP_TitleBarMaxButton: return QLatin1String("titlebar-maximize-icon");
- case QStyle::SP_TitleBarCloseButton: return QLatin1String("titlebar-close-icon");
- case QStyle::SP_TitleBarNormalButton: return QLatin1String("titlebar-normal-icon");
- case QStyle::SP_TitleBarShadeButton: return QLatin1String("titlebar-shade-icon");
- case QStyle::SP_TitleBarUnshadeButton: return QLatin1String("titlebar-unshade-icon");
- case QStyle::SP_TitleBarContextHelpButton: return QLatin1String("titlebar-contexthelp-icon");
- case QStyle::SP_DockWidgetCloseButton: return QLatin1String("dockwidget-close-icon");
- case QStyle::SP_MessageBoxInformation: return QLatin1String("messagebox-information-icon");
- case QStyle::SP_MessageBoxWarning: return QLatin1String("messagebox-warning-icon");
- case QStyle::SP_MessageBoxCritical: return QLatin1String("messagebox-critical-icon");
- case QStyle::SP_MessageBoxQuestion: return QLatin1String("messagebox-question-icon");
- case QStyle::SP_DesktopIcon: return QLatin1String("desktop-icon");
- case QStyle::SP_TrashIcon: return QLatin1String("trash-icon");
- case QStyle::SP_ComputerIcon: return QLatin1String("computer-icon");
- case QStyle::SP_DriveFDIcon: return QLatin1String("floppy-icon");
- case QStyle::SP_DriveHDIcon: return QLatin1String("harddisk-icon");
- case QStyle::SP_DriveCDIcon: return QLatin1String("cd-icon");
- case QStyle::SP_DriveDVDIcon: return QLatin1String("dvd-icon");
- case QStyle::SP_DriveNetIcon: return QLatin1String("network-icon");
- case QStyle::SP_DirOpenIcon: return QLatin1String("directory-open-icon");
- case QStyle::SP_DirClosedIcon: return QLatin1String("directory-closed-icon");
- case QStyle::SP_DirLinkIcon: return QLatin1String("directory-link-icon");
- case QStyle::SP_FileIcon: return QLatin1String("file-icon");
- case QStyle::SP_FileLinkIcon: return QLatin1String("file-link-icon");
- case QStyle::SP_FileDialogStart: return QLatin1String("filedialog-start-icon");
- case QStyle::SP_FileDialogEnd: return QLatin1String("filedialog-end-icon");
- case QStyle::SP_FileDialogToParent: return QLatin1String("filedialog-parent-directory-icon");
- case QStyle::SP_FileDialogNewFolder: return QLatin1String("filedialog-new-directory-icon");
- case QStyle::SP_FileDialogDetailedView: return QLatin1String("filedialog-detailedview-icon");
- case QStyle::SP_FileDialogInfoView: return QLatin1String("filedialog-infoview-icon");
- case QStyle::SP_FileDialogContentsView: return QLatin1String("filedialog-contentsview-icon");
- case QStyle::SP_FileDialogListView: return QLatin1String("filedialog-listview-icon");
- case QStyle::SP_FileDialogBack: return QLatin1String("filedialog-backward-icon");
- case QStyle::SP_DirIcon: return QLatin1String("directory-icon");
- case QStyle::SP_DialogOkButton: return QLatin1String("dialog-ok-icon");
- case QStyle::SP_DialogCancelButton: return QLatin1String("dialog-cancel-icon");
- case QStyle::SP_DialogHelpButton: return QLatin1String("dialog-help-icon");
- case QStyle::SP_DialogOpenButton: return QLatin1String("dialog-open-icon");
- case QStyle::SP_DialogSaveButton: return QLatin1String("dialog-save-icon");
- case QStyle::SP_DialogCloseButton: return QLatin1String("dialog-close-icon");
- case QStyle::SP_DialogApplyButton: return QLatin1String("dialog-apply-icon");
- case QStyle::SP_DialogResetButton: return QLatin1String("dialog-reset-icon");
- case QStyle::SP_DialogDiscardButton: return QLatin1String("discard-icon");
- case QStyle::SP_DialogYesButton: return QLatin1String("dialog-yes-icon");
- case QStyle::SP_DialogNoButton: return QLatin1String("dialog-no-icon");
- case QStyle::SP_ArrowUp: return QLatin1String("uparrow-icon");
- case QStyle::SP_ArrowDown: return QLatin1String("downarrow-icon");
- case QStyle::SP_ArrowLeft: return QLatin1String("leftarrow-icon");
- case QStyle::SP_ArrowRight: return QLatin1String("rightarrow-icon");
- case QStyle::SP_ArrowBack: return QLatin1String("backward-icon");
- case QStyle::SP_ArrowForward: return QLatin1String("forward-icon");
- case QStyle::SP_DirHomeIcon: return QLatin1String("home-icon");
- default: return QLatin1String("");
- }
-}
-
-QIcon QStyleSheetStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt,
- const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->standardIcon(standardIcon, opt, w))
- QString s = propertyNameForStandardPixmap(standardIcon);
- if (!s.isEmpty()) {
- QRenderRule rule = renderRule(w, opt);
- if (rule.hasStyleHint(s))
- return qvariant_cast<QIcon>(rule.styleHint(s));
- }
- return baseStyle()->standardIcon(standardIcon, opt, w);
-}
-
-QPalette QStyleSheetStyle::standardPalette() const
-{
- return baseStyle()->standardPalette();
-}
-
-QPixmap QStyleSheetStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->standardPixmap(standardPixmap, opt, w))
- QString s = propertyNameForStandardPixmap(standardPixmap);
- if (!s.isEmpty()) {
- QRenderRule rule = renderRule(w, opt);
- if (rule.hasStyleHint(s)) {
- QIcon icon = qvariant_cast<QIcon>(rule.styleHint(s));
- return icon.pixmap(16, 16); // ###: unhard-code this if someone complains
- }
- }
- return baseStyle()->standardPixmap(standardPixmap, opt, w);
-}
-
-int QStyleSheetStyle::layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option,
- const QWidget *widget) const
-{
- return baseStyle()->layoutSpacing(control1, control2, orientation, option, widget);
-}
-
-int QStyleSheetStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1 ,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption * option ,
- const QWidget * widget) const
-{
- return baseStyle()->layoutSpacing(control1, control2, orientation, option, widget);
-}
-
-int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
- QStyleHintReturn *shret) const
-{
- RECURSION_GUARD(return baseStyle()->styleHint(sh, opt, w, shret))
- // Prevent endless loop if somebody use isActiveWindow property as selector.
- // QWidget::isActiveWindow uses this styleHint to determine if the window is active or not
- if (sh == SH_Widget_ShareActivation)
- return baseStyle()->styleHint(sh, opt, w, shret);
-
- QRenderRule rule = renderRule(w, opt);
- QString s;
- switch (sh) {
- case SH_LineEdit_PasswordCharacter: s = QLatin1String("lineedit-password-character"); break;
- case SH_DitherDisabledText: s = QLatin1String("dither-disabled-text"); break;
- case SH_EtchDisabledText: s = QLatin1String("etch-disabled-text"); break;
- case SH_ItemView_ActivateItemOnSingleClick: s = QLatin1String("activate-on-singleclick"); break;
- case SH_ItemView_ShowDecorationSelected: s = QLatin1String("show-decoration-selected"); break;
- case SH_Table_GridLineColor: s = QLatin1String("gridline-color"); break;
- case SH_DialogButtonLayout: s = QLatin1String("button-layout"); break;
- case SH_ToolTipLabel_Opacity: s = QLatin1String("opacity"); break;
- case SH_ComboBox_Popup: s = QLatin1String("combobox-popup"); break;
- case SH_ComboBox_ListMouseTracking: s = QLatin1String("combobox-list-mousetracking"); break;
- case SH_MenuBar_AltKeyNavigation: s = QLatin1String("menubar-altkey-navigation"); break;
- case SH_Menu_Scrollable: s = QLatin1String("menu-scrollable"); break;
- case SH_DrawMenuBarSeparator: s = QLatin1String("menubar-separator"); break;
- case SH_MenuBar_MouseTracking: s = QLatin1String("mouse-tracking"); break;
- case SH_SpinBox_ClickAutoRepeatRate: s = QLatin1String("spinbox-click-autorepeat-rate"); break;
- case SH_SpinControls_DisableOnBounds: s = QLatin1String("spincontrol-disable-on-bounds"); break;
- case SH_MessageBox_TextInteractionFlags: s = QLatin1String("messagebox-text-interaction-flags"); break;
- case SH_ToolButton_PopupDelay: s = QLatin1String("toolbutton-popup-delay"); break;
- case SH_ToolBox_SelectedPageTitleBold:
- if (renderRule(w, opt, PseudoElement_ToolBoxTab).hasFont)
- return 0;
- break;
- case SH_GroupBox_TextLabelColor:
- if (rule.hasPalette() && rule.palette()->foreground.style() != Qt::NoBrush)
- return rule.palette()->foreground.color().rgba();
- break;
- case SH_ScrollView_FrameOnlyAroundContents: s = QLatin1String("scrollview-frame-around-contents"); break;
- case SH_ScrollBar_ContextMenu: s = QLatin1String("scrollbar-contextmenu"); break;
- case SH_ScrollBar_LeftClickAbsolutePosition: s = QLatin1String("scrollbar-leftclick-absolute-position"); break;
- case SH_ScrollBar_MiddleClickAbsolutePosition: s = QLatin1String("scrollbar-middleclick-absolute-position"); break;
- case SH_ScrollBar_RollBetweenButtons: s = QLatin1String("scrollbar-roll-between-buttons"); break;
- case SH_ScrollBar_ScrollWhenPointerLeavesControl: s = QLatin1String("scrollbar-scroll-when-pointer-leaves-control"); break;
- case SH_TabBar_Alignment:
-#ifndef QT_NO_TABWIDGET
- if (qobject_cast<const QTabWidget *>(w)) {
- rule = renderRule(w, opt, PseudoElement_TabWidgetTabBar);
- if (rule.hasPosition())
- return rule.position()->position;
- }
-#endif // QT_NO_TABWIDGET
- s = QLatin1String("alignment");
- break;
-#ifndef QT_NO_TABBAR
- case SH_TabBar_CloseButtonPosition:
- rule = renderRule(w, opt, PseudoElement_TabBarTabCloseButton);
- if (rule.hasPosition()) {
- Qt::Alignment align = rule.position()->position;
- if (align & Qt::AlignLeft || align & Qt::AlignTop)
- return QTabBar::LeftSide;
- if (align & Qt::AlignRight || align & Qt::AlignBottom)
- return QTabBar::RightSide;
- }
- break;
-#endif
- case SH_TabBar_ElideMode: s = QLatin1String("tabbar-elide-mode"); break;
- case SH_TabBar_PreferNoArrows: s = QLatin1String("tabbar-prefer-no-arrows"); break;
- case SH_ComboBox_PopupFrameStyle:
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox *>(w)) {
- QAbstractItemView *view = w->findChild<QAbstractItemView *>();
- if (view) {
- view->ensurePolished();
- QRenderRule subRule = renderRule(view, PseudoElement_None);
- if (subRule.hasBox() || !subRule.hasNativeBorder())
- return QFrame::NoFrame;
- }
- }
-#endif // QT_NO_COMBOBOX
- break;
- case SH_DialogButtonBox_ButtonsHaveIcons: s = QLatin1String("dialogbuttonbox-buttons-have-icons"); break;
- case SH_Workspace_FillSpaceOnMaximize: s = QLatin1String("mdi-fill-space-on-maximize"); break;
- case SH_TitleBar_NoBorder:
- if (rule.hasBorder())
- return !rule.border()->borders[LeftEdge];
- break;
- case SH_TitleBar_AutoRaise: { // plain absurd
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
- if (subRule.hasDrawable())
- return 1;
- break;
- }
- case SH_ItemView_ArrowKeysNavigateIntoChildren: s = QLatin1String("arrow-keys-navigate-into-children"); break;
- case SH_ItemView_PaintAlternatingRowColorsForEmptyArea: s = QLatin1String("paint-alternating-row-colors-for-empty-area"); break;
- default: break;
- }
- if (!s.isEmpty() && rule.hasStyleHint(s)) {
- return rule.styleHint(s).toInt();
- }
-
- return baseStyle()->styleHint(sh, opt, w, shret);
-}
-
-QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->subControlRect(cc, opt, sc, w))
-
- QRenderRule rule = renderRule(w, opt);
- switch (cc) {
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- if (rule.hasBox() || !rule.hasNativeBorder()) {
- switch (sc) {
- case SC_ComboBoxFrame: return rule.borderRect(opt->rect);
- case SC_ComboBoxEditField:
- {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
- QRect r = rule.contentsRect(opt->rect);
- QRect r2 = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown,
- opt->rect, opt->direction);
- if (subRule.hasPosition() && subRule.position()->position & Qt::AlignLeft) {
- return visualRect(opt->direction, r, r.adjusted(r2.width(),0,0,0));
- } else {
- return visualRect(opt->direction, r, r.adjusted(0,0,-r2.width(),0));
- }
- }
- case SC_ComboBoxArrow: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
- return positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
- }
- case SC_ComboBoxListBoxPopup:
- default:
- return baseStyle()->subControlRect(cc, opt, sc, w);
- }
- }
-
- QStyleOptionComboBox comboBox(*cb);
- comboBox.rect = rule.borderRect(opt->rect);
- return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &comboBox, sc, w)
- : QWindowsStyle::subControlRect(cc, &comboBox, sc, w);
- }
- break;
-
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
- QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
- bool ruleMatch = rule.hasBox() || !rule.hasNativeBorder();
- bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition();
- bool downRuleMatch = downRule.hasGeometry() || upRule.hasPosition();
- if (ruleMatch || upRuleMatch || downRuleMatch) {
- switch (sc) {
- case SC_SpinBoxFrame:
- return rule.borderRect(opt->rect);
- case SC_SpinBoxEditField:
- {
- QRect r = rule.contentsRect(opt->rect);
- // Use the widest button on each side to determine edit field size.
- Qt::Alignment upAlign, downAlign;
-
- upAlign = upRule.hasPosition() ? upRule.position()->position
- : Qt::Alignment(Qt::AlignRight);
- upAlign = resolveAlignment(opt->direction, upAlign);
-
- downAlign = downRule.hasPosition() ? downRule.position()->position
- : Qt::Alignment(Qt::AlignRight);
- downAlign = resolveAlignment(opt->direction, downAlign);
-
- int upSize = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w).width();
- int downSize = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w).width();
- int widestL = qMax((upAlign & Qt::AlignLeft) ? upSize : 0,
- (downAlign & Qt::AlignLeft) ? downSize : 0);
- int widestR = qMax((upAlign & Qt::AlignRight) ? upSize : 0,
- (downAlign & Qt::AlignRight) ? downSize : 0);
- r.setRight(r.right() - widestR);
- r.setLeft(r.left() + widestL);
- return r;
- }
- case SC_SpinBoxDown:
- if (downRuleMatch)
- return positionRect(w, rule, downRule, PseudoElement_SpinBoxDownButton,
- opt->rect, opt->direction);
- break;
- case SC_SpinBoxUp:
- if (upRuleMatch)
- return positionRect(w, rule, upRule, PseudoElement_SpinBoxUpButton,
- opt->rect, opt->direction);
- break;
- default:
- break;
- }
-
- return baseStyle()->subControlRect(cc, opt, sc, w);
- }
-
- QStyleOptionSpinBox spinBox(*spin);
- spinBox.rect = rule.borderRect(opt->rect);
- return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &spinBox, sc, w)
- : QWindowsStyle::subControlRect(cc, &spinBox, sc, w);
- }
- break;
-#endif // QT_NO_SPINBOX
-
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
- switch (sc) {
- case SC_GroupBoxFrame:
- case SC_GroupBoxContents: {
- if (rule.hasBox() || !rule.hasNativeBorder()) {
- return sc == SC_GroupBoxFrame ? rule.borderRect(opt->rect)
- : rule.contentsRect(opt->rect);
- }
- QStyleOptionGroupBox groupBox(*gb);
- groupBox.rect = rule.borderRect(opt->rect);
- return baseStyle()->subControlRect(cc, &groupBox, sc, w);
- }
- default:
- case SC_GroupBoxLabel:
- case SC_GroupBoxCheckBox: {
- QRenderRule indRule = renderRule(w, opt, PseudoElement_GroupBoxIndicator);
- QRenderRule labelRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
- if (!labelRule.hasPosition() && !labelRule.hasGeometry() && !labelRule.hasBox()
- && !labelRule.hasBorder() && !indRule.hasContentsSize()) {
- QStyleOptionGroupBox groupBox(*gb);
- groupBox.rect = rule.borderRect(opt->rect);
- return baseStyle()->subControlRect(cc, &groupBox, sc, w);
- }
- int tw = opt->fontMetrics.width(gb->text);
- int th = opt->fontMetrics.height();
- int spacing = pixelMetric(QStyle::PM_CheckBoxLabelSpacing, opt, w);
- int iw = pixelMetric(QStyle::PM_IndicatorWidth, opt, w);
- int ih = pixelMetric(QStyle::PM_IndicatorHeight, opt, w);
-
- if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
- tw = tw + iw + spacing;
- th = qMax(th, ih);
- }
- if (!labelRule.hasGeometry()) {
- labelRule.geo = new QStyleSheetGeometryData(tw, th, tw, th, -1, -1);
- } else {
- labelRule.geo->width = tw;
- labelRule.geo->height = th;
- }
- if (!labelRule.hasPosition()) {
- labelRule.p = new QStyleSheetPositionData(0, 0, 0, 0, defaultOrigin(PseudoElement_GroupBoxTitle),
- gb->textAlignment, PositionMode_Static);
- }
- QRect r = positionRect(w, rule, labelRule, PseudoElement_GroupBoxTitle,
- opt->rect, opt->direction);
- if (gb->subControls & SC_GroupBoxCheckBox) {
- r = labelRule.contentsRect(r);
- if (sc == SC_GroupBoxLabel) {
- r.setLeft(r.left() + iw + spacing);
- r.setTop(r.center().y() - th/2);
- } else {
- r = QRect(r.left(), r.center().y() - ih/2, iw, ih);
- }
- return r;
- } else {
- return labelRule.contentsRect(r);
- }
- }
- } // switch
- }
- break;
-
- case CC_ToolButton:
- if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
- if (rule.hasBox() || !rule.hasNativeBorder()) {
- switch (sc) {
- case SC_ToolButton: return rule.borderRect(opt->rect);
- case SC_ToolButtonMenu: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
- return positionRect(w, rule, subRule, PseudoElement_ToolButtonMenu, opt->rect, opt->direction);
- }
- default:
- break;
- }
- }
-
- QStyleOptionToolButton tool(*tb);
- tool.rect = rule.borderRect(opt->rect);
- return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &tool, sc, w)
- : QWindowsStyle::subControlRect(cc, &tool, sc, w);
- }
- break;
-
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QStyleOptionSlider styleOptionSlider(*sb);
- styleOptionSlider.rect = rule.borderRect(opt->rect);
- if (rule.hasDrawable() || rule.hasBox()) {
- QRect grooveRect;
- if (!rule.hasBox()) {
- grooveRect = rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, sb, SC_ScrollBarGroove, w)
- : QWindowsStyle::subControlRect(cc, sb, SC_ScrollBarGroove, w);
- } else {
- grooveRect = rule.contentsRect(opt->rect);
- }
-
- PseudoElement pe = PseudoElement_None;
-
- switch (sc) {
- case SC_ScrollBarGroove:
- return grooveRect;
- case SC_ScrollBarAddPage:
- case SC_ScrollBarSubPage:
- case SC_ScrollBarSlider: {
- QRect contentRect = grooveRect;
- if (hasStyleRule(w, PseudoElement_ScrollBarSlider)) {
- QRenderRule sliderRule = renderRule(w, opt, PseudoElement_ScrollBarSlider);
- Origin origin = sliderRule.hasPosition() ? sliderRule.position()->origin : defaultOrigin(PseudoElement_ScrollBarSlider);
- contentRect = rule.originRect(opt->rect, origin);
- }
- int maxlen = (styleOptionSlider.orientation == Qt::Horizontal) ? contentRect.width() : contentRect.height();
- int sliderlen;
- if (sb->maximum != sb->minimum) {
- uint range = sb->maximum - sb->minimum;
- sliderlen = (qint64(sb->pageStep) * maxlen) / (range + sb->pageStep);
-
- int slidermin = pixelMetric(PM_ScrollBarSliderMin, sb, w);
- if (sliderlen < slidermin || range > INT_MAX / 2)
- sliderlen = slidermin;
- if (sliderlen > maxlen)
- sliderlen = maxlen;
- } else {
- sliderlen = maxlen;
- }
-
- int sliderstart = (styleOptionSlider.orientation == Qt::Horizontal ? contentRect.left() : contentRect.top())
- + sliderPositionFromValue(sb->minimum, sb->maximum, sb->sliderPosition,
- maxlen - sliderlen, sb->upsideDown);
-
- QRect sr = (sb->orientation == Qt::Horizontal)
- ? QRect(sliderstart, contentRect.top(), sliderlen, contentRect.height())
- : QRect(contentRect.left(), sliderstart, contentRect.width(), sliderlen);
- if (sc == SC_ScrollBarSlider) {
- return sr;
- } else if (sc == SC_ScrollBarSubPage) {
- return QRect(contentRect.topLeft(), sb->orientation == Qt::Horizontal ? sr.bottomLeft() : sr.topRight());
- } else { // SC_ScrollBarAddPage
- return QRect(sb->orientation == Qt::Horizontal ? sr.topRight() : sr.bottomLeft(), contentRect.bottomRight());
- }
- break;
- }
- case SC_ScrollBarAddLine: pe = PseudoElement_ScrollBarAddLine; break;
- case SC_ScrollBarSubLine: pe = PseudoElement_ScrollBarSubLine; break;
- case SC_ScrollBarFirst: pe = PseudoElement_ScrollBarFirst; break;
- case SC_ScrollBarLast: pe = PseudoElement_ScrollBarLast; break;
- default: break;
- }
- if (hasStyleRule(w,pe)) {
- QRenderRule subRule = renderRule(w, opt, pe);
- if (subRule.hasPosition() || subRule.hasGeometry() || subRule.hasBox()) {
- const QStyleSheetPositionData *pos = subRule.position();
- QRect originRect = grooveRect;
- if (rule.hasBox()) {
- Origin origin = (pos && pos->origin != Origin_Unknown) ? pos->origin : defaultOrigin(pe);
- originRect = rule.originRect(opt->rect, origin);
- }
- return positionRect(w, subRule, pe, originRect, styleOptionSlider.direction);
- }
- }
- }
- return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &styleOptionSlider, sc, w)
- : QWindowsStyle::subControlRect(cc, &styleOptionSlider, sc, w);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_SliderGroove);
- if (!subRule.hasDrawable())
- break;
- subRule.img = 0;
- QRect gr = positionRect(w, rule, subRule, PseudoElement_SliderGroove, opt->rect, opt->direction);
- switch (sc) {
- case SC_SliderGroove:
- return gr;
- case SC_SliderHandle: {
- bool horizontal = slider->orientation & Qt::Horizontal;
- QRect cr = subRule.contentsRect(gr);
- QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SliderHandle);
- int len = horizontal ? subRule2.size().width() : subRule2.size().height();
- subRule2.img = 0;
- subRule2.geo = 0;
- cr = positionRect(w, subRule2, PseudoElement_SliderHandle, cr, opt->direction);
- int thickness = horizontal ? cr.height() : cr.width();
- int sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum, slider->sliderPosition,
- (horizontal ? cr.width() : cr.height()) - len, slider->upsideDown);
- cr = horizontal ? QRect(cr.x() + sliderPos, cr.y(), len, thickness)
- : QRect(cr.x(), cr.y() + sliderPos, thickness, len);
- return subRule2.borderRect(cr);
- break; }
- case SC_SliderTickmarks:
- // TODO...
- default:
- break;
- }
- }
- break;
-#endif // QT_NO_SLIDER
-
- case CC_MdiControls:
- if (hasStyleRule(w, PseudoElement_MdiCloseButton)
- || hasStyleRule(w, PseudoElement_MdiNormalButton)
- || hasStyleRule(w, PseudoElement_MdiMinButton)) {
- QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
- if (layout.isEmpty())
- layout = subControlLayout(QLatin1String("mNX"));
-
- int x = 0, width = 0;
- QRenderRule subRule;
- for (int i = 0; i < layout.count(); i++) {
- int layoutButton = layout[i].toInt();
- if (layoutButton < PseudoElement_MdiCloseButton
- || layoutButton > PseudoElement_MdiNormalButton)
- continue;
- QStyle::SubControl control = knownPseudoElements[layoutButton].subControl;
- if (!(opt->subControls & control))
- continue;
- subRule = renderRule(w, opt, layoutButton);
- width = subRule.size().width();
- if (sc == control)
- break;
- x += width;
- }
-
- return subRule.borderRect(QRect(x, opt->rect.top(), width, opt->rect.height()));
- }
- break;
-
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
- if (!subRule.hasDrawable() && !subRule.hasBox() && !subRule.hasBorder())
- break;
- QHash<QStyle::SubControl, QRect> layoutRects = titleBarLayout(w, tb);
- return layoutRects.value(sc);
- }
- break;
-
- default:
- break;
- }
-
- return baseStyle()->subControlRect(cc, opt, sc, w);
-}
-
-QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, const QWidget *w) const
-{
- RECURSION_GUARD(return baseStyle()->subElementRect(se, opt, w))
-
- QRenderRule rule = renderRule(w, opt);
-#ifndef QT_NO_TABBAR
- int pe = PseudoElement_None;
-#endif
-
- switch (se) {
- case SE_PushButtonContents:
- case SE_PushButtonFocusRect:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QStyleOptionButton btnOpt(*btn);
- if (rule.hasBox() || !rule.hasNativeBorder())
- return visualRect(opt->direction, opt->rect, rule.contentsRect(opt->rect));
- return rule.baseStyleCanDraw() ? baseStyle()->subElementRect(se, &btnOpt, w)
- : QWindowsStyle::subElementRect(se, &btnOpt, w);
- }
- break;
-
- case SE_LineEditContents:
- case SE_FrameContents:
- case SE_ShapedFrameContents:
- if (rule.hasBox() || !rule.hasNativeBorder()) {
- return visualRect(opt->direction, opt->rect, rule.contentsRect(opt->rect));
- }
- break;
-
- case SE_CheckBoxIndicator:
- case SE_RadioButtonIndicator:
- if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
- PseudoElement pe = se == SE_CheckBoxIndicator ? PseudoElement_Indicator : PseudoElement_ExclusiveIndicator;
- QRenderRule subRule = renderRule(w, opt, pe);
- return positionRect(w, rule, subRule, pe, opt->rect, opt->direction);
- }
- break;
-
- case SE_CheckBoxContents:
- case SE_RadioButtonContents:
- if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
- bool isRadio = se == SE_RadioButtonContents;
- QRect ir = subElementRect(isRadio ? SE_RadioButtonIndicator : SE_CheckBoxIndicator,
- opt, w);
- ir = visualRect(opt->direction, opt->rect, ir);
- int spacing = pixelMetric(isRadio ? PM_RadioButtonLabelSpacing : PM_CheckBoxLabelSpacing, 0, w);
- QRect cr = rule.contentsRect(opt->rect);
- ir.setRect(ir.left() + ir.width() + spacing, cr.y(),
- cr.width() - ir.width() - spacing, cr.height());
- return visualRect(opt->direction, opt->rect, ir);
- }
- break;
-
- case SE_ToolBoxTabContents:
- if (w && hasStyleRule(w->parentWidget(), PseudoElement_ToolBoxTab)) {
- QRenderRule subRule = renderRule(w->parentWidget(), opt, PseudoElement_ToolBoxTab);
- return visualRect(opt->direction, opt->rect, subRule.contentsRect(opt->rect));
- }
- break;
-
- case SE_RadioButtonFocusRect:
- case SE_RadioButtonClickRect: // focusrect | indicator
- if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
- return opt->rect;
- }
- break;
-
- case SE_CheckBoxFocusRect:
- case SE_CheckBoxClickRect: // relies on indicator and contents
- return ParentStyle::subElementRect(se, opt, w);
-
-#ifndef QT_NO_ITEMVIEWS
- case SE_ViewItemCheckIndicator:
- if (!qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- return subElementRect(SE_CheckBoxIndicator, opt, w);
- }
- // intentionally falls through
- case SE_ItemViewItemText:
- case SE_ItemViewItemDecoration:
- case SE_ItemViewItemFocusRect:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
- PseudoElement pe = PseudoElement_None;
- if (se == SE_ItemViewItemText || se == SE_ItemViewItemFocusRect)
- pe = PseudoElement_ViewItemText;
- else if (se == SE_ItemViewItemDecoration && vopt->features & QStyleOptionViewItemV2::HasDecoration)
- pe = PseudoElement_ViewItemIcon;
- else if (se == SE_ItemViewItemCheckIndicator && vopt->features & QStyleOptionViewItemV2::HasCheckIndicator)
- pe = PseudoElement_ViewItemIndicator;
- else
- break;
- if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder() || hasStyleRule(w, pe)) {
- QRenderRule subRule2 = renderRule(w, opt, pe);
- QStyleOptionViewItemV4 optCopy(*vopt);
- optCopy.rect = subRule.contentsRect(vopt->rect);
- QRect rect = ParentStyle::subElementRect(se, &optCopy, w);
- return positionRect(w, subRule2, pe, rect, opt->direction);
- }
- }
- break;
-#endif // QT_NO_ITEMVIEWS
-
- case SE_HeaderArrow: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewUpArrow);
- if (subRule.hasPosition() || subRule.hasGeometry())
- return positionRect(w, rule, subRule, PseudoElement_HeaderViewUpArrow, opt->rect, opt->direction);
- }
- break;
-
- case SE_HeaderLabel: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
- if (subRule.hasBox() || !subRule.hasNativeBorder())
- return subRule.contentsRect(opt->rect);
- }
- break;
-
- case SE_ProgressBarGroove:
- case SE_ProgressBarContents:
- case SE_ProgressBarLabel:
- if (const QStyleOptionProgressBarV2 *pb = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- if (rule.hasBox() || !rule.hasNativeBorder() || rule.hasPosition() || hasStyleRule(w, PseudoElement_ProgressBarChunk)) {
- if (se == SE_ProgressBarGroove)
- return rule.borderRect(pb->rect);
- else if (se == SE_ProgressBarContents)
- return rule.contentsRect(pb->rect);
-
- QSize sz = pb->fontMetrics.size(0, pb->text);
- return QStyle::alignedRect(Qt::LeftToRight, rule.hasPosition() ? rule.position()->textAlignment : pb->textAlignment,
- sz, pb->rect);
- }
- }
- break;
-
-#ifndef QT_NO_TABBAR
- case SE_TabWidgetLeftCorner:
- pe = PseudoElement_TabWidgetLeftCorner;
- // intentionally falls through
- case SE_TabWidgetRightCorner:
- if (pe == PseudoElement_None)
- pe = PseudoElement_TabWidgetRightCorner;
- // intentionally falls through
- case SE_TabWidgetTabBar:
- if (pe == PseudoElement_None)
- pe = PseudoElement_TabWidgetTabBar;
- // intentionally falls through
- case SE_TabWidgetTabPane:
- case SE_TabWidgetTabContents:
- if (pe == PseudoElement_None)
- pe = PseudoElement_TabWidgetPane;
-
- if (hasStyleRule(w, pe)) {
- QRect r = QWindowsStyle::subElementRect(pe == PseudoElement_TabWidgetPane ? SE_TabWidgetTabPane : se, opt, w);
- QRenderRule subRule = renderRule(w, opt, pe);
- r = positionRect(w, subRule, pe, r, opt->direction);
- if (pe == PseudoElement_TabWidgetTabBar) {
- Q_ASSERT(opt);
- r = opt->rect.intersected(r);
- }
- if (se == SE_TabWidgetTabContents)
- r = subRule.contentsRect(r);
- return r;
- }
- break;
-
- case SE_TabBarTearIndicator: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTear);
- if (subRule.hasContentsSize()) {
- QRect r;
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- r.setRect(tab->rect.left(), tab->rect.top(), subRule.size().width(), opt->rect.height());
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- r.setRect(tab->rect.left(), tab->rect.top(), opt->rect.width(), subRule.size().height());
- break;
- default:
- break;
- }
- r = visualRect(opt->direction, opt->rect, r);
- }
- return r;
- }
- break;
- }
- case SE_TabBarTabText:
- case SE_TabBarTabLeftButton:
- case SE_TabBarTabRightButton: {
- QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
- if (subRule.hasBox() || !subRule.hasNativeBorder()) {
- return ParentStyle::subElementRect(se, opt, w);
- }
- break;
- }
-#endif // QT_NO_TABBAR
-
- case SE_DockWidgetCloseButton:
- case SE_DockWidgetFloatButton: {
- PseudoElement pe = (se == SE_DockWidgetCloseButton) ? PseudoElement_DockWidgetCloseButton : PseudoElement_DockWidgetFloatButton;
- QRenderRule subRule2 = renderRule(w, opt, pe);
- if (!subRule2.hasPosition())
- break;
- QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
- return positionRect(w, subRule, subRule2, pe, opt->rect, opt->direction);
- }
-
-#ifndef QT_NO_TOOLBAR
- case SE_ToolBarHandle:
- if (hasStyleRule(w, PseudoElement_ToolBarHandle))
- return ParentStyle::subElementRect(se, opt, w);
- break;
-#endif //QT_NO_TOOLBAR
-
- default:
- break;
- }
-
- return baseStyle()->subElementRect(se, opt, w);
-}
-
-bool QStyleSheetStyle::event(QEvent *e)
-{
- return (baseStyle()->event(e) && e->isAccepted()) || ParentStyle::event(e);
-}
-
-void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
-{
- QWidget *container = containerWidget(w);
- QRenderRule rule = renderRule(container, PseudoElement_None,
- PseudoClass_Active | PseudoClass_Enabled | extendedPseudoClass(container));
- QFont font = rule.font.resolve(w->font());
-
- if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
- && isNaturalChild(w) && qobject_cast<QWidget *>(w->parent())) {
-
- font = font.resolve(static_cast<QWidget *>(w->parent())->font());
- }
-
- if (w->data->fnt == font)
- return;
-
-#ifdef QT3_SUPPORT
- QFont old = w->data->fnt;
-#endif
- w->data->fnt = font;
-#if defined(Q_WS_X11)
- // make sure the font set on this widget is associated with the correct screen
- //w->data->fnt.x11SetScreen(w->d_func()->xinfo.screen());
-#endif
-
- QEvent e(QEvent::FontChange);
- QApplication::sendEvent(w, &e);
-#ifdef QT3_SUPPORT
- w->fontChange(old);
-#endif
-}
-
-void QStyleSheetStyle::saveWidgetFont(QWidget* w, const QFont& font) const
-{
- w->setProperty("_q_styleSheetWidgetFont", font);
-}
-
-void QStyleSheetStyle::clearWidgetFont(QWidget* w) const
-{
- w->setProperty("_q_styleSheetWidgetFont", QVariant(QVariant::Invalid));
-}
-
-// Polish palette that should be used for a particular widget, with particular states
-// (eg. :focus, :hover, ...)
-// this is called by widgets that paint themself in their paint event
-// Returns true if there is a new palette in pal.
-bool QStyleSheetStyle::styleSheetPalette(const QWidget* w, const QStyleOption* opt, QPalette* pal)
-{
- if (!w || !opt || !pal)
- return false;
-
- RECURSION_GUARD(return false)
-
- w = containerWidget(w);
-
- QRenderRule rule = renderRule(w, PseudoElement_None, pseudoClass(opt->state) | extendedPseudoClass(w));
- if (!rule.hasPalette())
- return false;
-
- rule.configurePalette(pal, QPalette::NoRole, QPalette::NoRole);
- return true;
-}
-
-Qt::Alignment QStyleSheetStyle::resolveAlignment(Qt::LayoutDirection layDir, Qt::Alignment src)
-{
- if (layDir == Qt::LeftToRight || src & Qt::AlignAbsolute)
- return src;
-
- if (src & Qt::AlignLeft) {
- src &= ~Qt::AlignLeft;
- src |= Qt::AlignRight;
- } else if (src & Qt::AlignRight) {
- src &= ~Qt::AlignRight;
- src |= Qt::AlignLeft;
- }
- src |= Qt::AlignAbsolute;
- return src;
-}
-
-// Returns whether the given QWidget has a "natural" parent, meaning that
-// the parent contains this child as part of its normal operation.
-// An example is the QTabBar inside a QTabWidget.
-// This does not mean that any QTabBar which is a child of QTabWidget will
-// match, only the one that was created by the QTabWidget initialization
-// (and hence has the correct object name).
-bool QStyleSheetStyle::isNaturalChild(const QWidget *w)
-{
- if (w->objectName().startsWith(QLatin1String("qt_")))
- return true;
-
- return false;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qstylesheetstyle_p.cpp"
-
-#endif // QT_NO_STYLE_STYLESHEET
diff --git a/src/gui/styles/qstylesheetstyle_default.cpp b/src/gui/styles/qstylesheetstyle_default.cpp
deleted file mode 100644
index 76ffac8187..0000000000
--- a/src/gui/styles/qstylesheetstyle_default.cpp
+++ /dev/null
@@ -1,512 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/* This is the default Qt style sheet.
-
- IMPORTANT: This style sheet is primarily meant for defining feature
- capablities of styles. Do NOT add default styling rules here. When in
- doubt ask the stylesheet maintainer.
-
- The stylesheet in here used to be in a CSS file, but was moved here to
- avoid parsing overhead.
-*/
-
-#include "private/qcssparser_p.h"
-#include "qstylesheetstyle_p.h"
-
-#ifndef QT_NO_STYLE_STYLESHEET
-
-QT_BEGIN_NAMESPACE
-
-using namespace QCss;
-
-// This is the class name of the selector.
-// Use an empty string where you would use '*' in CSS.
-// Ex. QHeaderView
-
-#define SET_ELEMENT_NAME(x) \
- bSelector.elementName = (x)
-
-// This acts as both pseudo state and sub control. The first parameter is the
-// string name, and the second is the PseudoClass_* constant.
-// The sub control specifier is always the first, and has the type
-// PseudoClass_Unknown.
-// If there is no PseudoClass_Unknown as the first pseudo, it is assumed to be
-// a pseudo state.
-// Ex. QComboBox::drop-down:enabled
-// ^ ^
-
-#define ADD_PSEUDO(x, y) \
- pseudo.type = (y); \
- pseudo.name = (x); \
- bSelector.pseudos << pseudo
-
-// This is attributes. The third parameter is AttributeSelector::*
-// Ex. QComboBox[style="QWindowsXPStyle"]
-// ^ ^
-
-#define ADD_ATTRIBUTE_SELECTOR(x, y, z) \
- attr.name = (x); \
- attr.value = (y); \
- attr.valueMatchCriterium = (z); \
- bSelector.attributeSelectors << attr
-
-// Adds the current basic selector to the rule.
-// Several basic selectors behave as AND (space in CSS).
-
-#define ADD_BASIC_SELECTOR \
- selector.basicSelectors << bSelector; \
- bSelector.ids.clear(); \
- bSelector.pseudos.clear(); \
- bSelector.attributeSelectors.clear()
-
-// Adds the current selector to the rule.
-// Several selectors behave as OR (comma in CSS).
-
-#define ADD_SELECTOR \
- styleRule.selectors << selector; \
- selector.basicSelectors.clear()
-
-// Sets the name of a property.
-// Ex. background: red;
-// ^
-
-#define SET_PROPERTY(x, y) \
- decl.d->property = (x); \
- decl.d->propertyId = (y)
-
-// Adds a value to the current property.
-// The first parameter should be Value::KnownIdentifier if the value can be
-// found among the Value_* constants, in which case the second should be that
-// constant. Otherwise the first parameter is Value::Identifier and the second
-// is a string.
-// Adding more values is the same as seperating by spaces in CSS.
-// Ex. border: 2px solid black;
-// ^ ^ ^
-
-#define ADD_VALUE(x, y) \
- value.type = (x); \
- value.variant = (y); \
- decl.d->values << value
-
-// Adds the current declaration to the rule.
-// Ex. border: 2px solid black;
-// \----------------------/
-
-#define ADD_DECLARATION \
- styleRule.declarations << decl; \
- decl.d.detach(); \
- decl.d->values.clear()
-
-// Adds the rule to the stylesheet.
-// Use at the end of every CSS block.
-
-#define ADD_STYLE_RULE \
- sheet.styleRules << styleRule; \
- styleRule.selectors.clear(); \
- styleRule.declarations.clear()
-
-StyleSheet QStyleSheetStyle::getDefaultStyleSheet() const
-{
- StyleSheet sheet;
- StyleRule styleRule;
- BasicSelector bSelector;
- Selector selector;
- Declaration decl;
- QCss::Value value;
- Pseudo pseudo;
- AttributeSelector attr;
-
- // pixmap based style doesn't support any features
- bool styleIsPixmapBased = baseStyle()->inherits("QMacStyle")
- || baseStyle()->inherits("QWindowsXPStyle")
- || baseStyle()->inherits("QGtkStyle")
- || baseStyle()->inherits("QS60Style");
-
-
- /*QLineEdit {
- -qt-background-role: base;
- border: native;
- -qt-style-features: background-color;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QLineEdit"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
- ADD_DECLARATION;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QLineEdit:no-frame {
- border: none;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QLineEdit"));
- ADD_PSEUDO(QLatin1String("no-frame"), PseudoClass_Frameless);
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QFrame {
- border: native;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QFrame"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QLabel, QToolBox {
- background: none;
- border-image: none;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QLabel"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_ELEMENT_NAME(QLatin1String("QToolBox"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("background"), Background);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
- ADD_DECLARATION;
-
- SET_PROPERTY(QLatin1String("border-image"), BorderImage);
- ADD_VALUE(Value::KnownIdentifier, Value_None);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QGroupBox {
- border: native;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QGroupBox"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
-
- /*QToolTip {
- -qt-background-role: window;
- border: native;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QToolTip"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
- ADD_DECLARATION;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QPushButton, QToolButton {
- border-style: native;
- -qt-style-features: background-color; //only for not pixmap based styles
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QPushButton"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_ELEMENT_NAME(QLatin1String("QToolButton"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border-style"), BorderStyles);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- if (!styleIsPixmapBased) {
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_DECLARATION;
- }
-
-
- ADD_STYLE_RULE;
- }
-
-
- /*QComboBox {
- border: native;
- -qt-style-features: background-color background-gradient; //only for not pixmap based styles
- -qt-background-role: base;
- }*/
-
- {
- SET_ELEMENT_NAME(QLatin1String("QComboBox"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- if (!styleIsPixmapBased) {
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-gradient"));
- ADD_DECLARATION;
- }
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QComboBox[style="QPlastiqueStyle"][readOnly="true"],
- QComboBox[style="QCleanlooksStyle"][readOnly="true"]
- {
- -qt-background-role: button;
- }*/
- if (baseStyle()->inherits("QPlastiqueStyle") || baseStyle()->inherits("QCleanlooksStyle"))
- {
- SET_ELEMENT_NAME(QLatin1String("QComboBox"));
- ADD_ATTRIBUTE_SELECTOR(QLatin1String("readOnly"), QLatin1String("true"), AttributeSelector::MatchEqual);
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Button);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QAbstractSpinBox {
- border: native;
- -qt-style-features: background-color;
- -qt-background-role: base;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QAbstractSpinBox"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_DECLARATION;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QMenu {
- -qt-background-role: window;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QMenu"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
- /*QMenu::item {
- -qt-style-features: background-color;
- }*/
- if (!styleIsPixmapBased) {
- SET_ELEMENT_NAME(QLatin1String("QMenu"));
- ADD_PSEUDO(QLatin1String("item"), PseudoClass_Unknown);
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QHeaderView {
- -qt-background-role: window;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QHeaderView"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QTableCornerButton::section, QHeaderView::section {
- -qt-background-role: button;
- -qt-style-features: background-color; //if style is not pixmap based
- border: native;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QTableCornerButton"));
- ADD_PSEUDO(QLatin1String("section"), PseudoClass_Unknown);
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_ELEMENT_NAME(QLatin1String("QHeaderView"));
- ADD_PSEUDO(QLatin1String("section"), PseudoClass_Unknown);
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Button);
- ADD_DECLARATION;
-
- if (!styleIsPixmapBased) {
- SET_PROPERTY(QLatin1String("-qt-style-features"), QtStyleFeatures);
- ADD_VALUE(Value::Identifier, QString::fromLatin1("background-color"));
- ADD_DECLARATION;
- }
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QProgressBar {
- -qt-background-role: base;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QProgressBar"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Base);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QScrollBar {
- -qt-background-role: window;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QScrollBar"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("-qt-background-role"), QtBackgroundRole);
- ADD_VALUE(Value::KnownIdentifier, Value_Window);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- /*QDockWidget {
- border: native;
- }*/
- {
- SET_ELEMENT_NAME(QLatin1String("QDockWidget"));
- ADD_BASIC_SELECTOR;
- ADD_SELECTOR;
-
- SET_PROPERTY(QLatin1String("border"), Border);
- ADD_VALUE(Value::KnownIdentifier, Value_Native);
- ADD_DECLARATION;
-
- ADD_STYLE_RULE;
- }
-
- sheet.origin = StyleSheetOrigin_UserAgent;
- sheet.buildIndexes();
- return sheet;
-}
-
-#endif // #ifndef QT_NO_STYLE_STYLESHEET
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qstylesheetstyle_p.h b/src/gui/styles/qstylesheetstyle_p.h
deleted file mode 100644
index 1f331b2642..0000000000
--- a/src/gui/styles/qstylesheetstyle_p.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTYLESHEETSTYLE_P_H
-#define QSTYLESHEETSTYLE_P_H
-
-#include "QtGui/qwindowsstyle.h"
-
-#ifndef QT_NO_STYLE_STYLESHEET
-
-#include "QtGui/qstyleoption.h"
-#include "QtCore/qhash.h"
-#include "QtGui/qevent.h"
-#include "QtCore/qvector.h"
-#include "QtGui/qapplication.h"
-#include "private/qcssparser_p.h"
-#include "QtGui/qbrush.h"
-
-QT_BEGIN_NAMESPACE
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-class QRenderRule;
-class QAbstractScrollArea;
-class QStyleSheetStylePrivate;
-class QStyleOptionTitleBar;
-
-class Q_AUTOTEST_EXPORT QStyleSheetStyle : public QWindowsStyle
-{
- typedef QWindowsStyle ParentStyle;
-
- Q_OBJECT
-public:
- QStyleSheetStyle(QStyle *baseStyle);
- ~QStyleSheetStyle();
-
- void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const;
- void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const;
- void drawItemText(QPainter *painter, const QRect& rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole = QPalette::NoRole) const;
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *option) const;
- SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const;
- QRect itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const;
- QRect itemTextRect(const QFontMetrics &metrics, const QRect &rect, int alignment, bool enabled,
- const QString &text) const;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
- void polish(QWidget *widget);
- void polish(QApplication *app);
- void polish(QPalette &pal);
- QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const;
- QPalette standardPalette() const;
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option = 0,
- const QWidget *w = 0 ) const;
- int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
- int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
- QStyleHintReturn *shret = 0) const;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *w = 0) const;
-
- // These functions are called from QApplication/QWidget. Be careful.
- QStyle *baseStyle() const;
- void repolish(QWidget *widget);
- void repolish(QApplication *app);
-
- void unpolish(QWidget *widget);
- void unpolish(QApplication *app);
-
- QStyle *base;
- void ref() { ++refcount; }
- void deref() { Q_ASSERT(refcount > 0); if (!--refcount) delete this; }
-
- void updateStyleSheetFont(QWidget* w) const;
- void saveWidgetFont(QWidget* w, const QFont& font) const;
- void clearWidgetFont(QWidget* w) const;
-
- bool styleSheetPalette(const QWidget* w, const QStyleOption* opt, QPalette* pal);
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const;
- int layoutSpacingImplementation(QSizePolicy::ControlType control1,
- QSizePolicy::ControlType control2,
- Qt::Orientation orientation,
- const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
-
-protected:
- bool event(QEvent *e);
-
-private:
- int refcount;
-
- friend class QRenderRule;
- int nativeFrameWidth(const QWidget *);
- QRenderRule renderRule(const QWidget *, int, quint64 = 0) const;
- QRenderRule renderRule(const QWidget *, const QStyleOption *, int = 0) const;
- QSize defaultSize(const QWidget *, QSize, const QRect&, int) const;
- QRect positionRect(const QWidget *, const QRenderRule&, const QRenderRule&, int,
- const QRect&, Qt::LayoutDirection) const;
- QRect positionRect(const QWidget *w, const QRenderRule &rule2, int pe,
- const QRect &originRect, Qt::LayoutDirection dir) const;
-
- mutable QCss::Parser parser;
-
- void setPalette(QWidget *);
- void unsetPalette(QWidget *);
- void setProperties(QWidget *);
- void setGeometry(QWidget *);
- QVector<QCss::StyleRule> styleRules(const QWidget *w) const;
- bool hasStyleRule(const QWidget *w, int part) const;
-
- QHash<QStyle::SubControl, QRect> titleBarLayout(const QWidget *w, const QStyleOptionTitleBar *tb) const;
-
- QCss::StyleSheet getDefaultStyleSheet() const;
-
- static Qt::Alignment resolveAlignment(Qt::LayoutDirection, Qt::Alignment);
- static bool isNaturalChild(const QWidget *w);
- bool initWidget(const QWidget *w) const;
-public:
- static int numinstances;
-
-private:
- Q_DISABLE_COPY(QStyleSheetStyle)
- Q_DECLARE_PRIVATE(QStyleSheetStyle)
-};
-
-class QStyleSheetStyleCaches : public QObject
-{
- Q_OBJECT
-public Q_SLOTS:
- void widgetDestroyed(QObject *);
- void styleDestroyed(QObject *);
-public:
- QHash<const QWidget *, QVector<QCss::StyleRule> > styleRulesCache;
- QHash<const QWidget *, QHash<int, bool> > hasStyleRuleCache;
- typedef QHash<int, QHash<quint64, QRenderRule> > QRenderRules;
- QHash<const QWidget *, QRenderRules> renderRulesCache;
- QHash<const QWidget *, QPalette> customPaletteWidgets; // widgets whose palette we tampered
- QHash<const void *, QCss::StyleSheet> styleSheetCache; // parsed style sheets
- QSet<const QWidget *> autoFillDisabledWidgets;
-};
-
-
-QT_END_NAMESPACE
-#endif // QT_NO_STYLE_STYLESHEET
-#endif // QSTYLESHEETSTYLE_P_H
diff --git a/src/gui/styles/qwindowscestyle.cpp b/src/gui/styles/qwindowscestyle.cpp
deleted file mode 100644
index d7947bc653..0000000000
--- a/src/gui/styles/qwindowscestyle.cpp
+++ /dev/null
@@ -1,2429 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwindowscestyle.h"
-
-#if !defined(QT_NO_STYLE_WINDOWSCE) || defined(QT_PLUGIN)
-
-#include "qpainterpath.h"
-#include "qapplication.h"
-#include "qdockwidget.h"
-#include "qtoolbar.h"
-#include "qpaintengine.h"
-#include "qpainter.h"
-#include "qstyleoption.h"
-#include "qwindowscestyle_p.h"
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-static const int windowsItemFrame = 2; // menu item frame width
-static const int windowsItemHMargin = 3; // menu item hor text margin
-static const int windowsItemVMargin = 2; // menu item ver text margin
-static const int windowsArrowHMargin = 6; // arrow horizontal margin
-static const int windowsRightBorder = 15; // right border on windows
-static const int windowsCheckMarkWidth = 14; // checkmarks width on windows
-
-static const int windowsCEitemViewCheckBoxSize = 14;
-static const int windowsCEFrameGroupBoxOffset = 9;
-static const int windowsCEIndicatorSize = 14;
-static const int windowsCEExclusiveIndicatorSize = 14;
-static const int windowsCESliderThickness = 24;
-static const int windowsCEIconSize = 16;
-
-static const QColor windowsCECheckBoxGradientColorBegin = QColor(222, 224, 214);
-static const QColor windowsCECheckBoxGradientColorEnd = QColor(255, 255, 255);
-
-enum QSliderDirection { SlUp, SlDown, SlLeft, SlRight };
-
-QWindowsCEStyle::QWindowsCEStyle() : QWindowsStyle() {
- qApp->setEffectEnabled(Qt::UI_FadeMenu, false);
- qApp->setEffectEnabled(Qt::UI_AnimateMenu, false);
-}
-
-void QWindowsCEStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const {
-
- bool doRestore = false;
- QRect rect = option->rect;
-
- switch (element) {
- case PE_PanelButtonTool: {
- if (
-#ifndef QT_NO_TOOLBAR
- (widget && qobject_cast<QToolBar*>(widget->parentWidget())) ||
-#endif
-#ifndef QT_NO_DOCKWIDGET
- (widget && widget->inherits("QDockWidgetTitleButton")) ||
-#endif
- (option->state & (State_Sunken | State_On)))
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect.adjusted(0, 0, 0, 0),
- option->palette, option->state & (State_Sunken | State_On),
- &option->palette.button());
- if (option->state & (State_On)){
- QBrush fill = QBrush(option->palette.midlight().color(), Qt::Dense4Pattern);
- painter->fillRect(option->rect.adjusted(windowsItemFrame , windowsItemFrame ,
- -windowsItemFrame , -windowsItemFrame ), fill);
- }
- break; }
- case PE_IndicatorButtonDropDown:
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect, option->palette,
- option->state & (State_Sunken | State_On),
- &option->palette.brush(QPalette::Button));
- break;
-#ifndef QT_NO_TABBAR
- case PE_IndicatorTabTear:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- bool rtl = tab->direction == Qt::RightToLeft;
- QRect rect = tab->rect;
- QPainterPath path;
- rect.setTop(rect.top() + ((tab->state & State_Selected) ? 1 : 3));
- rect.setBottom(rect.bottom() - ((tab->state & State_Selected) ? 0 : 2));
- path.moveTo(QPoint(rtl ? rect.right() : rect.left(), rect.top()));
- int count = 3;
- for(int jags = 1; jags <= count; ++jags, rtl = !rtl)
- path.lineTo(QPoint(rtl ? rect.left() : rect.right(), rect.top() + jags * rect.height()/count));
-
- painter->setPen(QPen(tab->palette.light(), qreal(.8)));
- painter->setBrush(tab->palette.background());
- painter->setRenderHint(QPainter::Antialiasing);
- painter->drawPath(path);
- }
- break;
-#endif //QT_NO_TABBAR
-#ifndef QT_NO_TOOLBAR
- case PE_IndicatorToolBarSeparator:
- //nothing to draw on WindowsCE
- break;
- case PE_IndicatorToolBarHandle:
- painter->save();
- painter->translate(option->rect.x(), option->rect.y());
- if (option->state & State_Horizontal) {
- int x = option->rect.width() / 2 - 4;
- if (QApplication::layoutDirection() == Qt::RightToLeft)
- x -= 2;
- if (option->rect.height() > 4) {
- QWindowsCEStylePrivate::drawWinCEButton(painter,x - 1, 0, 7, option->rect.height(),
- option->palette, false, 0);
- QWindowsCEStylePrivate::drawWinCEPanel(painter, x, 1, 3, option->rect.height() - 1,
- option->palette, false, 0);
- QWindowsCEStylePrivate::drawWinCEPanel(painter, x + 3, 1, 3, option->rect.height() - 1,
- option->palette, false, 0);
- painter->setPen(option->palette.button().color());
- painter->drawLine(x + 4, 2, x + 4,option->rect.height() - 2);
- }
- } else {
- if (option->rect.width() > 4) {
- int y = option->rect.height() / 2 - 4;
- QWindowsCEStylePrivate::drawWinCEPanel(painter, 2, y, option->rect.width() - 2, 3,
- option->palette, false, 0);
- QWindowsCEStylePrivate::drawWinCEPanel(painter, 2, y + 3, option->rect.width() - 2, 3,
- option->palette, false, 0);
- }
- }
- painter->restore();
- break;
-
-#endif // QT_NO_TOOLBAR
- case PE_FrameButtonTool: {
-#ifndef QT_NO_DOCKWIDGET
- if (widget && widget->inherits("QDockWidgetTitleButton")) {
- if (const QDockWidget *dw = qobject_cast<const QDockWidget *>(widget->parent()))
- if (dw->isFloating()){
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect.adjusted(1, 1, 0, 0),
- option->palette, option->state & (State_Sunken | State_On),
- &option->palette.button());
- return;
- }
- }
-#endif // QT_NO_DOCKWIDGET
- QBrush fill;
- bool stippled;
- bool panel = (element == PE_PanelButtonTool);
- if ((!(option->state & State_Sunken ))
- && (!(option->state & State_Enabled)
- || ((option->state & State_Enabled ) && !(option->state & State_MouseOver)))
- && (option->state & State_On)) {
- fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- stippled = true;
- } else {
- fill = option->palette.brush(QPalette::Button);
- stippled = false;
- }
- if (option->state & (State_Raised | State_Sunken | State_On)) {
- if (option->state & State_AutoRaise) {
- if(option->state & (State_Enabled | State_Sunken | State_On)){
- if (panel)
- QWindowsCEStylePrivate::drawWinCEPanel(painter, option->rect, option->palette,
- option->state & (State_Sunken | State_On), &fill);
- else
- qDrawShadeRect(painter, option->rect, option->palette,
- option->state & (State_Sunken | State_On), 1);
- }
- if (stippled) {
- painter->setPen(option->palette.button().color());
- painter->drawRect(option->rect.adjusted(1, 1, -2, -2));
- }
- } else {
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect, option->palette,
- option->state & (State_Sunken | State_On), panel ? &fill : 0);
- }
- } else {
- painter->fillRect(option->rect, fill);
- }
- break; }
-
- case PE_PanelButtonBevel: {
- QBrush fill;
- bool panel = element != PE_FrameButtonBevel;
- painter->setBrushOrigin(option->rect.topLeft());
- if (!(option->state & State_Sunken) && (option->state & State_On))
- fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- else
- fill = option->palette.brush(QPalette::Button);
-
- if (option->state & (State_Raised | State_On | State_Sunken)) {
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect, option->palette,
- option->state & (State_Sunken | State_On),
- panel ? &fill : 0); ;
- } else {
- if (panel)
- painter->fillRect(option->rect, fill);
- else
- painter->drawRect(option->rect);
- }
- break; }
-
- case PE_FrameGroupBox:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- QRect fr = frame->rect;
- painter->setPen(frame->palette.shadow().color());
- painter->drawRect(fr.x(), fr.y(), fr.x() + fr.width() - 1,
- fr.y() + fr.height() - windowsCEFrameGroupBoxOffset);
- }
- break;
-
- case PE_IndicatorCheckBox: {
- QBrush fill;
- if (option->state & State_NoChange)
- fill = QBrush(option->palette.base().color(), Qt::Dense4Pattern);
- else if (option->state & State_Sunken)
- fill = option->palette.button();
- else if (option->state & State_Enabled)
- fill = option->palette.base();
- else
- fill = option->palette.background();
- painter->save();
- doRestore = true;
- painter->fillRect(option->rect,fill);
- painter->setPen(option->palette.dark().color());
- painter->drawRect(option->rect);
- painter->setPen(option->palette.shadow().color());
- painter->drawLine(option->rect.x() + 1,option->rect.y() + 1,
- option->rect.x() + option->rect.width() - 1, option->rect.y() + 1);
- painter->drawLine(option->rect.x() + 1,option->rect.y() + 1,
- option->rect.x() + 1, option->rect.y() + option->rect.height() - 1);
- //fall through...
- }
- case PE_IndicatorViewItemCheck:
- case PE_Q3CheckListIndicator: {
- if (!doRestore) {
- painter->save();
- doRestore = true;
- }
- int arrowSize= 2;
- if (element == PE_Q3CheckListIndicator || element == PE_IndicatorViewItemCheck) {
- QLinearGradient linearGradient(QPoint(option->rect.x(),option->rect.y()), QPoint(option->rect.x()+option->rect.width(),
- option->rect.y()+option->rect.height()));
- linearGradient.setColorAt(0, windowsCECheckBoxGradientColorBegin);
- linearGradient.setColorAt(1, windowsCECheckBoxGradientColorEnd);
- painter->setBrush(linearGradient);
- painter->setPen(Qt::NoPen);
- if (option->state & State_NoChange)
- painter->setBrush(option->palette.brush(QPalette::Button));
- painter->setPen(option->palette.link().color());
- painter->drawRect(option->rect.x(), option->rect.y(), windowsCEitemViewCheckBoxSize, windowsCEitemViewCheckBoxSize);
- painter->setPen(option->palette.brightText().color());
- arrowSize= 3;
- }
- if (!(option->state & State_Off)) {
- QLineF lines[9];
- int i, xx, yy;
- xx = option->rect.x() + 4;
- yy = option->rect.y() + 6;
- for (i = 0; i < 4; ++i) {
- lines[i] = QLineF(xx, yy, xx, yy + arrowSize);
- ++xx;
- ++yy;
- }
- yy -= 2;
- for (i = 4; i < 9; ++i) {
- lines[i] = QLineF(xx, yy, xx, yy + arrowSize);
- ++xx;
- --yy;
- }
- painter->drawLines(lines, 9);
- }
- if (doRestore)
- painter->restore();
-
- break; }
- case PE_IndicatorRadioButton: {
- QRect ir = option->rect;
- painter->save();
- painter->setPen(Qt::NoPen);
- painter->setBrush(option->palette.light());
- painter->drawEllipse(option->rect);
- painter->setPen(option->palette.shadow().color());
- painter->setBrush(option->palette.shadow().color());
- painter->drawArc(option->rect, 0, 360 * 16);
- painter->drawArc(option->rect.x() + 1, option->rect.y() + 1, option->rect.width() - 2,
- option->rect.height() - 2, 40 * 16, 180 * 16);
- painter->setPen(option->palette.light().color());
- painter->drawPoint(option->rect.x() + 11, option->rect.y() + 3);
- painter->drawPoint(option->rect.x() + 3,option->rect.y() + 3);
- painter->setPen(option->palette.shadow().color());
- painter->drawPoint(option->rect.x() +3,option->rect.y() + 12);
- if (option->state & (State_Sunken | State_On)) {
- painter->setPen(Qt::NoPen);
- painter->setBrush(option->palette.text());
- painter->drawEllipse(option->rect.x() +3,option->rect.y()+ 2,9,10);
- }
- painter->restore();
- break; }
- case PE_PanelMenuBar:
- painter->save();
- painter->setPen(option->palette.shadow().color());
- painter->drawRect(option->rect);
- painter->restore();
- break;
- case PE_PanelButtonCommand:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- QBrush fill;
- State flags = option->state;
- QPalette pal = option->palette;
- QRect r = option->rect;
- if (! (flags & State_Sunken) && (flags & State_On))
- fill = QBrush(pal.light().color(), Qt::Dense4Pattern);
- else
- fill = pal.brush(QPalette::Button);
- if (btn->features & QStyleOptionButton::DefaultButton && flags & State_Sunken) {
- painter->setPen(pal.dark().color());
- painter->setBrush(fill);
- painter->drawRect(r.adjusted(0, 0, -1, -1));
- } else if (flags & (State_Raised | State_Sunken | State_On | State_Sunken)) {
- QWindowsCEStylePrivate::drawWinCEButton(painter, r, pal, flags & (State_Sunken | State_On),
- &fill);
- } else {
- painter->fillRect(r, fill);
- }
-
- }
- break;
- case PE_FrameDefaultButton: {
- painter->setPen(option->palette.shadow().color());
- QRect rect = option->rect;
- rect.adjust(0, 0, -1, -1);
- painter->drawRect(rect);
- break; }
- case PE_IndicatorSpinPlus:
- case PE_IndicatorSpinMinus: {
- QRect r = option->rect;
- int fw = pixelMetric(PM_DefaultFrameWidth, option, widget)+2;
- QRect br = r.adjusted(fw, fw, -fw, -fw);
- int offset = (option->state & State_Sunken) ? 1 : 0;
- int step = (br.width() + 4) / 5;
- painter->fillRect(br.x() + offset, br.y() + offset +br.height() / 2 - step / 2,
- br.width(), step,
- option->palette.buttonText());
- if (element == PE_IndicatorSpinPlus)
- painter->fillRect(br.x() + br.width() / 2 - step / 2 + offset, br.y() + offset+4,
- step, br.height()-7,
- option->palette.buttonText());
- break; }
- case PE_IndicatorSpinUp:
- case PE_IndicatorSpinDown: {
- painter->save();
- QPoint points[7];
- switch (element) {
- case PE_IndicatorSpinUp:
- points[0] = QPoint(-2, -4);
- points[1] = QPoint(-2, 2);
- points[2] = QPoint(-1, -3);
- points[3] = QPoint(-1, 1);
- points[4] = QPoint(0, -2);
- points[5] = QPoint(0, 0);
- points[6] = QPoint(1, -1);
- break;
- case PE_IndicatorSpinDown:
- points[0] = QPoint(0, -4);
- points[1] = QPoint(0, 2);
- points[2] = QPoint(-1, -3);
- points[3] = QPoint(-1, 1);
- points[4] = QPoint(-2, -2);
- points[5] = QPoint(-2, 0);
- points[6] = QPoint(-3, -1);
- break;
- default:
- break;
- }
- if (option->state & State_Sunken)
- painter->translate(pixelMetric(PM_ButtonShiftHorizontal),
- pixelMetric(PM_ButtonShiftVertical));
- if (option->state & State_Enabled) {
- painter->translate(option->rect.x() + option->rect.width() / 2,
- option->rect.y() + option->rect.height() / 2);
- painter->setPen(option->palette.buttonText().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- } else {
- painter->translate(option->rect.x() + option->rect.width() / 2 + 1,
- option->rect.y() + option->rect.height() / 2 + 1);
- painter->setPen(option->palette.light().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- painter->translate(-1, -1);
- painter->setPen(option->palette.mid().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- }
-
- painter->restore();
- break; }
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowLeft: {
- painter->save();
- QPoint points[9];
- switch (element) {
- case PE_IndicatorArrowUp:
-
- points[0] = QPoint(-4, 2);
- points[1] = QPoint(4, 2);
- points[2] = QPoint(-3, 1);
- points[3] = QPoint(3, 1);
- points[4] = QPoint(-2, 0);
- points[5] = QPoint(2, 0);
- points[6] = QPoint(-1, -1);
- points[7] = QPoint(1, -1);
- points[8] = QPoint(0, -2);
- break;
- case PE_IndicatorArrowDown:
-
- points[0] = QPoint(-4, -2);
- points[1] = QPoint(4, -2);
- points[2] = QPoint(-3, -1);
- points[3] = QPoint(3, -1);
- points[4] = QPoint(-2, 0);
- points[5] = QPoint(2, 0);
- points[6] = QPoint(-1, 1);
- points[7] = QPoint(1, 1);
- points[8] = QPoint(0, 2);
- break;
- case PE_IndicatorArrowRight:
- points[0] = QPoint(-3, -4);
- points[1] = QPoint(-3, 4);
- points[2] = QPoint(-2, -3);
- points[3] = QPoint(-2, 3);
- points[4] = QPoint(-1, -2);
- points[5] = QPoint(-1, 2);
- points[6] = QPoint(0, -1);
- points[7] = QPoint(0, 1);
- points[8] = QPoint(1, 0);
- break;
- case PE_IndicatorArrowLeft:
- points[0] = QPoint(1, -4);
- points[1] = QPoint(1, 4);
- points[2] = QPoint(0, -3);
- points[3] = QPoint(0, 3);
- points[4] = QPoint(-1, -2);
- points[5] = QPoint(-1, 2);
- points[6] = QPoint(-2, -1);
- points[7] = QPoint(-2, 1);
- points[8] = QPoint(-3, 0);
- break;
- default:
- break;
- }
- if (option->state & State_Sunken)
- painter->translate(pixelMetric(PM_ButtonShiftHorizontal),
- pixelMetric(PM_ButtonShiftVertical));
- if (option->state & State_Enabled) {
- painter->translate(option->rect.x() + option->rect.width() / 2,
- option->rect.y() + option->rect.height() / 2);
- painter->setPen(option->palette.buttonText().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawLine(points[6], points[7]);
- painter->drawPoint(points[8]);
- } else {
- painter->translate(option->rect.x() + option->rect.width() / 2 + 1,
- option->rect.y() + option->rect.height() / 2 + 1);
- painter->setPen(option->palette.light().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawLine(points[6], points[7]);
- painter->drawPoint(points[8]);
- painter->translate(-1, -1);
- painter->setPen(option->palette.mid().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawLine(points[6], points[7]);
- painter->drawPoint(points[8]);
- }
- painter->restore();
- break; }
-
- case PE_FrameWindow: {
- QPalette popupPal = option->palette;
- popupPal.setColor(QPalette::Light, option->palette.background().color());
- popupPal.setColor(QPalette::Midlight, option->palette.light().color());
- QWindowsCEStylePrivate::drawWinCEPanel(painter, option->rect, popupPal, option->state & State_Sunken);
- break; }
-
- case PE_Frame:
- case PE_FrameMenu:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- QPalette popupPal = frame->palette;
- QRect r = frame->rect;
- qDrawPlainRect(painter, r, frame->palette.shadow().color(),1);
- }
- break;
- case PE_FrameStatusBar:
- QWindowsCEStylePrivate::drawWinCEPanel(painter, option->rect, option->palette, true, 0);
- break;
-
- case PE_FrameTabWidget: {
- QRect rect = option->rect;
- QPalette pal = option->palette;
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect, option->palette, false, 0);
- break; }
- default:
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- break;
- }
-}
-
-void QWindowsCEStyle::drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const {
- switch (element) {
- #ifndef QT_NO_MENU
- case CE_MenuTearoff: {
- if(option->state & State_Selected) {
- if(pixelMetric(PM_MenuPanelWidth, option, widget) > 1)
- qDrawShadePanel(painter, option->rect.x(), option->rect.y(), option->rect.width(),
- option->rect.height(), option->palette, false, 2,
- &option->palette.brush(QPalette::Button));
- else
- qDrawShadePanel(painter, option->rect.x() + 1, option->rect.y() + 1, option->rect.width() - 2,
- option->rect.height() - 2, option->palette, true, 1, &option->palette.brush(QPalette::Button));
- } else {
- painter->fillRect(option->rect, option->palette.brush(QPalette::Button));
- }
- painter->setPen(QPen(option->palette.dark().color(), 1, Qt::DashLine));
- painter->drawLine(option->rect.x()+2, option->rect.y()+option->rect.height()/2-1, option->rect.x()+option->rect.width()-4,
- option->rect.y()+option->rect.height()/2-1);
- painter->setPen(QPen(option->palette.light().color(), 1, Qt::DashLine));
- painter->drawLine(option->rect.x()+2, option->rect.y()+option->rect.height()/2, option->rect.x()+option->rect.width()-4,
- option->rect.y()+option->rect.height()/2);
- break; }
-
-
- case CE_MenuBarItem:
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- bool active = mbi->state & State_Selected;
- bool hasFocus = mbi->state & State_HasFocus;
- bool down = mbi->state & State_Sunken;
- QStyleOptionMenuItem newMbi = *mbi;
- if (active || hasFocus) {
- QBrush b = mbi->palette.brush(QPalette::Highlight);
- if (active && down) {
- painter->fillRect(mbi->rect.adjusted(0, 1, 0, -1), b);
- }
- }
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip
- | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, mbi, widget))
- alignment |= Qt::TextHideMnemonic;
-
- painter->save();
- QFont f = painter->font();
- f.setBold(true);
- painter->setFont(f);
- QPixmap pix = mbi->icon.pixmap(pixelMetric(PM_SmallIconSize),
- (mbi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
- if (!pix.isNull())
- drawItemPixmap(painter,mbi->rect, alignment, pix);
- else
- if (active && down)
- drawItemText(painter, mbi->rect, alignment, mbi->palette, mbi->state & State_Enabled,
- mbi->text, QPalette::Light);
- else
- drawItemText(painter, mbi->rect, alignment, mbi->palette, mbi->state & State_Enabled,
- mbi->text, QPalette::ButtonText);
- painter->restore();
- }
- break;
-
- case CE_MenuBarEmptyArea:
- painter->save();
- painter->setPen(option->palette.shadow().color());
- if (widget && !widget->testAttribute(Qt::WA_NoSystemBackground)) {
- painter->eraseRect(option->rect);
- QRect r = option->rect;
- painter->drawLine(r.x() + 1, r.y() + 1, r.x()+ 1, r.y()+ r.height() - 2);
- painter->drawLine(r.x() - 2 + r.width(), r.y() + 1, r.x() - 2 + r.width(), r.y() + r.height() - 2);
- painter->drawLine(r.x() + 1, r.y() +1, r.x() - 1 + r.width(), r.y() + 1);
- painter->drawLine(r.x() + 1, r.y() + r.height()-2 , r.x() - 2 + r.width(), r.y() + r.height() - 2);
- }
- painter->restore();
- break;
-
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- int x, y, w, h;
- menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
- bool dis = !(menuitem->state & State_Enabled);
- bool checked = menuitem->checkType != QStyleOptionMenuItem::NotCheckable
- ? menuitem->checked : false;
- bool act = menuitem->state & State_Selected;
-
- // windows always has a check column, regardless whether we have an icon or not
- int checkcol = qMax(menuitem->maxIconWidth, windowsCheckMarkWidth);
- QBrush fill = menuitem->palette.brush(act ? QPalette::Highlight : QPalette::Button);
- painter->fillRect(menuitem->rect.adjusted(1, 1, 0, 0), fill);
-
- if (menuitem->menuItemType == QStyleOptionMenuItem::Separator) {
- int yoff = y-1 + h / 2;
- painter->setPen(menuitem->palette.shadow().color());
- painter->drawLine(x + 4, yoff + 1, x + w - 8, yoff + 1);
- return;
- }
-
- QRect vCheckRect = visualRect(option->direction, menuitem->rect, QRect(menuitem->rect.x(),
- menuitem->rect.y(), checkcol, menuitem->rect.height()));
- if (checked) {
- if (act && !dis) {
- qDrawPlainRect(painter, vCheckRect,
- menuitem->palette.button().color(), 1,
- &menuitem->palette.brush(QPalette::Button));
- } else {
- QBrush fill(menuitem->palette.button().color(), Qt::Dense4Pattern);
- qDrawPlainRect(painter, vCheckRect,menuitem->palette.button().color(), 1, &fill);
- }
- } else if (!act) {
- painter->fillRect(vCheckRect, menuitem->palette.brush(QPalette::Button));
- }
- // On Windows Style, if we have a checkable item and an icon we
- // draw the icon recessed to indicate an item is checked. If we
- // have no icon, we draw a checkmark instead.
- if (!menuitem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap;
- if (checked)
- pixmap = menuitem->icon.pixmap(pixelMetric(PM_SmallIconSize), mode, QIcon::On);
- else
- pixmap = menuitem->icon.pixmap(pixelMetric(PM_SmallIconSize), mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- if (act && !dis && !checked)
- qDrawPlainRect(painter, vCheckRect, menuitem->palette.button().color(), 1,
- &menuitem->palette.brush(QPalette::Button));
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vCheckRect.center());
- painter->setPen(menuitem->palette.text().color());
- painter->drawPixmap(pmr.topLeft(), pixmap);
- } else if (checked) {
- QStyleOptionMenuItem newMi = *menuitem;
- newMi.state = State_None;
- if (!dis)
- newMi.state |= State_Enabled;
- if (act)
- newMi.state |= State_On;
- newMi.rect = visualRect(option->direction, menuitem->rect, QRect(menuitem->rect.x()
- + windowsItemFrame, menuitem->rect.y() + windowsItemFrame,
- checkcol - 2 * windowsItemFrame, menuitem->rect.height() - 2*windowsItemFrame));
- drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, painter, widget);
- }
- painter->setPen(act ? menuitem->palette.highlightedText().color() : menuitem->palette.buttonText().color());
-
- QColor discol;
- if (dis) {
- discol = menuitem->palette.text().color();
- painter->setPen(discol);
- }
- int xm = windowsItemFrame + checkcol + windowsItemHMargin;
- int xpos = menuitem->rect.x() + xm;
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(option->direction, menuitem->rect, textRect);
- QString s = menuitem->text;
- if (!s.isEmpty()) { // draw text
- painter->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
- text_flags |= Qt::AlignLeft;
- if (t >= 0) {
- QRect vShortcutRect = visualRect(option->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
- if (dis && !act)
- painter->setPen(discol);
- painter->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- QFont font = menuitem->font;
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
- painter->setFont(font);
- if (dis && !act)
- painter->setPen(discol);
- painter->drawText(vTextRect, text_flags, s.left(t));
- painter->restore();
- }
- if (menuitem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- int dim = (h - 2 * windowsItemFrame) / 2;
- PrimitiveElement arrow;
- arrow = (option->direction == Qt::RightToLeft) ? PE_IndicatorSpinDown : PE_IndicatorSpinUp;
- xpos = x + w - windowsArrowHMargin - windowsItemFrame - dim;
- QRect vSubMenuRect = visualRect(option->direction, menuitem->rect, QRect(xpos, y + h / 2 - dim / 2, dim, dim));
- QStyleOptionMenuItem newMI = *menuitem;
- newMI.rect = vSubMenuRect;
- newMI.state = dis ? State_None : State_Enabled;
- if (act)
- newMI.palette.setColor(QPalette::ButtonText,
- newMI.palette.highlightedText().color());
- drawPrimitive(arrow, &newMI, painter, widget);
- }
- }
- break;
-#endif // QT_NO_MENU
- case CE_MenuVMargin:
- painter->fillRect(option->rect, Qt::white);
- break;
- case CE_MenuEmptyArea:
- QWindowsStyle::drawControl(element,option, painter, widget);
- break;
-
-#ifndef QT_NO_TABBAR
- case CE_TabBarTab:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- drawControl(CE_TabBarTabShape, tab, painter, widget);
- drawControl(CE_TabBarTabLabel, tab, painter, widget);
- }
- break;
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- bool rtlHorTabs = (tab->direction == Qt::RightToLeft
- && (tab->shape == QTabBar::RoundedNorth
- || tab->shape == QTabBar::RoundedSouth));
- bool selected = tab->state & State_Selected;
- bool lastTab = ((!rtlHorTabs && tab->position == QStyleOptionTab::End)
- || (rtlHorTabs
- && tab->position == QStyleOptionTab::Beginning));
- bool firstTab = ((!rtlHorTabs
- && tab->position == QStyleOptionTab::Beginning)
- || (rtlHorTabs
- && tab->position == QStyleOptionTab::End));
- bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
- bool previousSelected =
- ((!rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
- || (rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::NextIsSelected));
- bool nextSelected =
- ((!rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::NextIsSelected)
- || (rtlHorTabs
- && tab->selectedPosition
- == QStyleOptionTab::PreviousIsSelected));
- int tabBarAlignment = styleHint(SH_TabBar_Alignment, tab, widget);
- bool leftAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignLeft)
- || (rtlHorTabs
- && tabBarAlignment == Qt::AlignRight);
-
- bool rightAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignRight)
- || (rtlHorTabs
- && tabBarAlignment == Qt::AlignLeft);
- QColor light = tab->palette.light().color();
- QColor midlight = tab->palette.midlight().color();
- QColor dark = tab->palette.dark().color();
- QColor shadow = tab->palette.shadow().color();
- QColor background = tab->palette.background().color();
- int borderThinkness = pixelMetric(PM_TabBarBaseOverlap, tab, widget);
- if (selected)
- borderThinkness /= 2;
- QRect r2(option->rect);
- int x1 = r2.left();
- int x2 = r2.right();
- int y1 = r2.top();
- int y2 = r2.bottom();
- switch (tab->shape) {
- default:
- QCommonStyle::drawControl(element, tab, painter, widget);
- break;
- case QTabBar::RoundedNorth: {
- if (!selected) {
- y1 += 2;
- x1 += firstTab ? borderThinkness : 0;
- x2 -= lastTab ? borderThinkness : 0;
- }
-
- painter->fillRect(QRect(x1 + 1, y1 + 1, (x2 - x1) - 1, (y2 - y1) - 2), tab->palette.background());
-
- // Delete border
- if (selected) {
- painter->setPen(background);
- painter->drawLine(x1, y2 - 1, x2, y2 - 1);
- painter->drawLine(x1, y2 + 1, x2, y2 + 1);
- painter->drawLine(x1, y2, x2, y2);
- }
- // Left
- if (firstTab || selected || onlyOne || !previousSelected) {
- painter->setPen(dark);
- painter->drawLine(x1, y1 + 2, x1, y2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness));
- painter->drawPoint(x1 + 1, y1 + 1);
- painter->setPen(midlight);
- painter->drawLine(x1 + 1, y1 + 2, x1 + 1, y2 -
- ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness));
-
- }
- // Top
- {
- int beg = x1 + (previousSelected ? 0 : 2);
- int end = x2 - (nextSelected ? 0 : 2);
- painter->setPen(dark);
- painter->drawLine(beg, y1, end, y1);
-
- painter->setPen(midlight);
- painter->drawLine(beg, y1 + 1, end, y1 + 1);
-
- }
- // Right
- if (lastTab || selected || onlyOne || !nextSelected) {
- painter->setPen(shadow);
- painter->drawLine(x2, y1 + 2, x2, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- painter->drawPoint(x2 - 1, y1 + 1);
- painter->setPen(dark);
- painter->drawLine(x2 - 1, y1 + 2, x2 - 1, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- }
- break; }
- case QTabBar::RoundedSouth: {
- if (!selected) {
- y2 -= 2;
- x1 += firstTab ? borderThinkness : 0;
- x2 -= lastTab ? borderThinkness : 0;
- }
-
- painter->fillRect(QRect(x1 + 1, y1 + 2, (x2 - x1) - 1, (y2 - y1) - 1), tab->palette.background());
-
- // Delete border
- if (selected) {
- painter->setPen(background);
- painter->drawLine(x1, y1 + 1, x2 - 1, y1 + 1);
- painter->drawLine(x1, y1 - 1, x2 - 1, y1 - 1);
- painter->drawLine(x1, y1, x2 - 1, y1);
- }
- // Left
- if (firstTab || selected || onlyOne || !previousSelected) {
- painter->setPen(dark);
- painter->drawLine(x1, y2 - 2, x1, y1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness));
- painter->drawPoint(x1 + 1, y2 - 1);
- painter->setPen(midlight);
- painter->drawLine(x1 + 1, y2 - 2, x1 + 1, y1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness));
- }
- // Bottom
- {
- int beg = x1 + (previousSelected ? 0 : 2);
- int end = x2 - (nextSelected ? 0 : 2);
- painter->setPen(shadow);
- painter->drawLine(beg, y2, end, y2);
- painter->setPen(dark);
- painter->drawLine(beg, y2 - 1, end, y2 - 1);
- }
- // Right
- if (lastTab || selected || onlyOne || !nextSelected) {
- painter->setPen(shadow);
- painter->drawLine(x2, y2 - 2, x2, y1 + ((onlyOne || lastTab) && selected &&
- rightAligned ? 0 : borderThinkness));
- painter->drawPoint(x2 - 1, y2 - 1);
- painter->setPen(dark);
- painter->drawLine(x2 - 1, y2 - 2, x2 - 1, y1 + ((onlyOne || lastTab) && selected &&
- rightAligned ? 0 : borderThinkness));
- }
- break; }
- case QTabBar::RoundedWest: {
- if (!selected) {
- x1 += 2;
- y1 += firstTab ? borderThinkness : 0;
- y2 -= lastTab ? borderThinkness : 0;
- }
-
- painter->fillRect(QRect(x1 + 1, y1 + 1, (x2 - x1) - 2, (y2 - y1) - 1), tab->palette.background());
-
- // Delete border
- if (selected) {
- painter->setPen(background);
- painter->drawLine(x2 - 1, y1, x2 - 1, y2);
- painter->drawLine(x2, y1, x2, y2);
- }
- // Top
- if (firstTab || selected || onlyOne || !previousSelected) {
- painter->setPen(dark);
- painter->drawLine(x1 + 2, y1, x2 - ((onlyOne || firstTab) && selected &&
- leftAligned ? 0 : borderThinkness), y1);
- painter->drawPoint(x1 + 1, y1 + 1);
- painter->setPen(midlight);
- painter->drawLine(x1 + 2, y1 + 1, x2 - ((onlyOne || firstTab) && selected &&
- leftAligned ? 0 : borderThinkness), y1 + 1);
- }
- // Left
- {
- int beg = y1 + (previousSelected ? 0 : 2);
- int end = y2 - (nextSelected ? 0 : 2);
- painter->setPen(dark);
- painter->drawLine(x1, beg, x1, end);
- painter->setPen(midlight);
- painter->drawLine(x1 + 1, beg, x1 + 1, end);
- }
- // Bottom
- if (lastTab || selected || onlyOne || !nextSelected) {
- painter->setPen(shadow);
- painter->drawLine(x1 + 3, y2, x2 - ((onlyOne || lastTab) && selected &&
- rightAligned ? 0 : borderThinkness), y2);
- painter->drawPoint(x1 + 2, y2 - 1);
- painter->setPen(dark);
- painter->drawLine(x1 + 3, y2 - 1, x2 - ((onlyOne || lastTab) && selected &&
- rightAligned ? 0 : borderThinkness), y2 - 1);
- painter->drawPoint(x1 + 1, y2 - 1);
- painter->drawPoint(x1 + 2, y2);
- }
- break; }
- case QTabBar::RoundedEast: {
- if (!selected) {
- x2 -= 2;
- y1 += firstTab ? borderThinkness : 0;
- y2 -= lastTab ? borderThinkness : 0;
- }
-
- painter->fillRect(QRect(x1 + 2, y1 + 1, (x2 - x1) - 1, (y2 - y1) - 1), tab->palette.background());
-
- // Delete border
- if (selected) {
- painter->setPen(background);
- painter->drawLine(x1 + 1, y1, x1 + 1, y2 - 1);
- painter->drawLine(x1, y1, x1, y2 - 1);
- }
- // Top
- if (firstTab || selected || onlyOne || !previousSelected) {
- painter->setPen(dark);
- painter->drawLine(x2 - 2, y1, x1 + ((onlyOne || firstTab) && selected &&
- leftAligned ? 0 : borderThinkness), y1);
- painter->drawPoint(x2 - 1, y1 + 1);
- painter->setPen(midlight);
- painter->drawLine(x2 - 3, y1 + 1, x1 + ((onlyOne || firstTab) &&
- selected && leftAligned ? 0 : borderThinkness), y1 + 1);
- painter->drawPoint(x2 - 1, y1);
-
- }
- // Right
- {
- int beg = y1 + (previousSelected ? 0 : 2);
- int end = y2 - (nextSelected ? 0 : 2);
- painter->setPen(shadow);
- painter->drawLine(x2, beg, x2, end);
- painter->setPen(dark);
- painter->drawLine(x2 - 1, beg, x2 - 1, end);
- }
- // Bottom
- if (lastTab || selected || onlyOne || !nextSelected) {
- painter->setPen(shadow);
- painter->drawLine(x2 - 2, y2, x1 + ((onlyOne || lastTab) &&
- selected && rightAligned ? 0 : borderThinkness), y2);
- painter->drawPoint(x2 - 1, y2 - 1);
- painter->setPen(dark);
- painter->drawLine(x2 - 2, y2 - 1, x1 + ((onlyOne || lastTab) &&
- selected && rightAligned ? 0 : borderThinkness), y2 - 1);
- }
- break; }
- }
- }
- break;
-#endif // QT_NO_TABBAR
-
- case CE_ToolBar: {
- QRect rect = option->rect;
- painter->setPen(QPen(option->palette.dark().color()));
- painter->drawLine(rect.topRight().x()-1,
- rect.topRight().y(),
- rect.bottomRight().x()-1,
- rect.bottomRight().y());
- painter->drawLine(rect.bottomLeft().x(),
- rect.bottomLeft().y(),
- rect.bottomRight().x(),
- rect.bottomRight().y());
- painter->setPen(QPen(option->palette.light().color()));
- painter->drawLine(rect.topRight().x(),
- rect.topRight().y(),
- rect.bottomRight().x(),
- rect.bottomRight().y());
- painter->drawLine(rect.topLeft().x(),
- rect.topLeft().y(),
- rect.topRight().x(),
- rect.topRight().y());
-
- break; }
-#ifndef QT_NO_SCROLLBAR
- case CE_ScrollBarSubLine:
- case CE_ScrollBarAddLine: {
- if (option->state & State_Sunken) {
- QStyleOption buttonOpt = *option;
-
- drawPrimitive(PE_PanelButtonBevel, &buttonOpt, painter, widget);
- } else {
- QStyleOption buttonOpt = *option;
- if (!(buttonOpt.state & State_Sunken))
- buttonOpt.state |= State_Raised;
- drawPrimitive(PE_PanelButtonBevel, &buttonOpt, painter, widget);
- }
- PrimitiveElement arrow;
- if (option->state & State_Horizontal) {
- if (element == CE_ScrollBarAddLine)
- arrow = option->direction == Qt::LeftToRight ? PE_IndicatorArrowRight : PE_IndicatorArrowLeft;
- else
- arrow = option->direction == Qt::LeftToRight ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- } else {
- if (element == CE_ScrollBarAddLine)
- arrow = PE_IndicatorArrowDown;
- else
- arrow = PE_IndicatorArrowUp;
- }
- drawPrimitive(arrow, option, painter, widget);
- break; }
- case CE_ScrollBarAddPage:
- case CE_ScrollBarSubPage: {
- QBrush br;
- QBrush bg = painter->background();
- Qt::BGMode bg_mode = painter->backgroundMode();
- painter->setPen(Qt::NoPen);
- painter->setBackgroundMode(Qt::OpaqueMode);
-
- if (option->state & State_Sunken) {
- br = QBrush(option->palette.shadow().color(), Qt::Dense4Pattern);
- painter->setBackground(option->palette.dark().color());
- painter->setBrush(br);
- } else {
- QPixmap pm = option->palette.brush(QPalette::Light).texture();
- if (option->state & State_Enabled)
- br = !pm.isNull() ? QBrush(pm) : QBrush(option->palette.button().color(), Qt::Dense4Pattern);
- else
- br = !pm.isNull() ? QBrush(pm) : QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- painter->setBackground(option->palette.base().color());
- painter->setBrush(br);
- }
- painter->drawRect(option->rect);
- painter->setBackground(bg);
- painter->setBackgroundMode(bg_mode);
- break; }
- case CE_ScrollBarSlider:
- if (!(option->state & State_Enabled)) {
- QStyleOptionButton buttonOpt;
- buttonOpt.QStyleOption::operator=(*option);
- buttonOpt.state = State_Enabled | State_Raised;
- drawPrimitive(PE_PanelButtonBevel, &buttonOpt, painter, widget);
- QPixmap pm = option->palette.brush(QPalette::Light).texture();
- QBrush br = !pm.isNull() ? QBrush(pm) : QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- painter->setPen(Qt::NoPen);
- painter->setBrush(br);
- painter->setBackgroundMode(Qt::OpaqueMode);
- painter->drawRect(option->rect.adjusted(2, 2, -2, -2));
- } else {
- QStyleOptionButton buttonOpt;
- buttonOpt.QStyleOption::operator=(*option);
- buttonOpt.state = State_Enabled | State_Raised;
- drawPrimitive(PE_PanelButtonBevel, &buttonOpt, painter, widget);
- }
- break;
-#endif // QT_NO_SCROLLBAR
- case CE_HeaderSection: {
- QBrush fill;
- if (option->state & State_On)
- fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- else
- fill = option->palette.brush(QPalette::Button);
-
- if (option->state & (State_Raised | State_Sunken)) {
- QWindowsCEStylePrivate::drawWinCEButton(painter, option->rect, option->palette,
- option->state & State_Sunken, &fill);
- } else {
- painter->fillRect(option->rect, fill);
- }
- break; }
-
- case CE_DockWidgetTitle:
- QWindowsStyle::drawControl(element,option, painter, widget);
- break;
-
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- painter->save();
- QFont f = painter->font();
- f.setBold(true);
- painter->setFont(f);
- QRect ir = btn->rect;
- uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
- if (!styleHint(SH_UnderlineShortcut, btn, widget))
- tf |= Qt::TextHideMnemonic;
-
- if (btn->state & (State_On | State_Sunken))
- ir.translate(pixelMetric(PM_ButtonShiftHorizontal, option, widget),
- pixelMetric(PM_ButtonShiftVertical, option, widget));
- if (!btn->icon.isNull()) {
- QIcon::Mode mode = btn->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- if (mode == QIcon::Normal && btn->state & State_HasFocus)
- mode = QIcon::Active;
- QIcon::State state = QIcon::Off;
- if (btn->state & State_On)
- state = QIcon::On;
- QPixmap pixmap = btn->icon.pixmap(btn->iconSize, mode, state);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- //Center the icon if there is no text
-
- QPoint point;
- if (btn->text.isEmpty()) {
- point = QPoint(ir.x() + ir.width() / 2 - pixw / 2,
- ir.y() + ir.height() / 2 - pixh / 2);
- } else {
- point = QPoint(ir.x() + 2, ir.y() + ir.height() / 2 - pixh / 2);
- }
- if (btn->direction == Qt::RightToLeft)
- point.rx() += pixw;
-
- if ((btn->state & (State_On | State_Sunken)) && btn->direction == Qt::RightToLeft)
- point.rx() -= pixelMetric(PM_ButtonShiftHorizontal, option, widget) * 2;
-
- painter->drawPixmap(visualPos(btn->direction, btn->rect, point), pixmap);
-
- if (btn->direction == Qt::RightToLeft)
- ir.translate(-4, 0);
- else
- ir.translate(pixw + 4, 0);
- ir.setWidth(ir.width() - (pixw + 4));
- // left-align text if there is
- if (!btn->text.isEmpty())
- tf |= Qt::AlignLeft;
- } else {
- tf |= Qt::AlignHCenter;
- }
- drawItemText(painter, ir, tf, btn->palette, (btn->state & State_Enabled),
- btn->text, QPalette::ButtonText);
- painter->restore();
- }
- break;
- default:
- QWindowsStyle::drawControl(element, option, painter, widget);
- break;
- }
-}
-
-void QWindowsCEStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const {
- switch (control) {
- #ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int thickness = pixelMetric(PM_SliderControlThickness, slider, widget);
- int len = pixelMetric(PM_SliderLength, slider, widget);
- int ticks = slider->tickPosition;
- QRect groove = subControlRect(CC_Slider, slider, SC_SliderGroove, widget);
- QRect handle = subControlRect(CC_Slider, slider, SC_SliderHandle, widget);
-
- if ((slider->subControls & SC_SliderGroove) && groove.isValid()) {
- int mid = thickness / 2;
- if (ticks & QSlider::TicksAbove)
- mid += len / 8;
- if (ticks & QSlider::TicksBelow)
- mid -= len / 8;
-
- painter->setPen(slider->palette.shadow().color());
- if (slider->orientation == Qt::Horizontal) {
- QWindowsCEStylePrivate::drawWinCEPanel(painter, groove.x(), groove.y() + mid - 2,
- groove.width(), 4, option->palette, true);
- painter->drawLine(groove.x() + 1, groove.y() + mid - 1,
- groove.x() + groove.width() - 3, groove.y() + mid - 1);
- } else {
- QWindowsCEStylePrivate::drawWinCEPanel(painter, groove.x() + mid - 2, groove.y(),
- 4, groove.height(), option->palette, true);
- painter->drawLine(groove.x() + mid - 1, groove.y() + 1,
- groove.x() + mid - 1, groove.y() + groove.height() - 3);
- }
- }
- if (slider->subControls & SC_SliderTickmarks) {
- QStyleOptionSlider tmpSlider = *slider;
- tmpSlider.subControls = SC_SliderTickmarks;
- QCommonStyle::drawComplexControl(control, &tmpSlider, painter, widget);
- }
-
- if (slider->subControls & SC_SliderHandle) {
- // 4444440
- // 4333310
- // 4322210
- // 4322210
- // 4322210
- // 4322210
- // *43210*
- // **440**
- // ***0***
- const QColor c0 = slider->palette.shadow().color();
- const QColor c1 = slider->palette.dark().color();
- // const QColor c2 = g.button();
- const QColor c3 = slider->palette.midlight().color();
- const QColor c4 = slider->palette.dark().color();
- QBrush handleBrush;
-
- if (slider->state & State_Enabled) {
- handleBrush = slider->palette.color(QPalette::Button);
- } else {
- handleBrush = QBrush(slider->palette.color(QPalette::Button),
- Qt::Dense4Pattern);
- }
-
- int x = handle.x(), y = handle.y(),
- wi = handle.width(), he = handle.height();
-
- int x1 = x;
- int x2 = x + wi - 1;
- int y1 = y;
- int y2 = y + he - 1;
-
- Qt::Orientation orient = slider->orientation;
- bool tickAbove = slider->tickPosition == QSlider::TicksAbove;
- bool tickBelow = slider->tickPosition == QSlider::TicksBelow;
-
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = subElementRect(SE_SliderFocusRect, slider, widget);
- drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- if ((tickAbove && tickBelow) || (!tickAbove && !tickBelow)) {
- Qt::BGMode oldMode = painter->backgroundMode();
- painter->setBackgroundMode(Qt::OpaqueMode);
- QWindowsCEStylePrivate::drawWinCEButton(painter, QRect(x, y, wi, he), slider->palette, false,
- &handleBrush);
- painter->setBackgroundMode(oldMode);
- QBrush fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 + 2, y1 + 2, x2 - x1 - 3, y2 - y1 - 3),fill);
- return;
- }
- QSliderDirection dir;
- if (orient == Qt::Horizontal)
- if (tickAbove)
- dir = SlUp;
- else
- dir = SlDown;
- else
- if (tickAbove)
- dir = SlLeft;
- else
- dir = SlRight;
- QPolygon a;
- int d = 0;
- switch (dir) {
- case SlUp:
- x2++;
- y1 = y1 + wi / 2;
- d = (wi + 1) / 2 - 1;
- a.setPoints(5, x1, y1, x1, y2, x2, y2, x2, y1, x1 + d, y1 - d);
- break;
- case SlDown:
- x2++;
- y2 = y2 - wi / 2;
- d = (wi + 1) / 2 - 1;
- a.setPoints(5, x1, y1, x1, y2, x1 + d, y2+d, x2, y2, x2, y1);
- break;
- case SlLeft:
- d = (he + 1) / 2 - 1;
- x1 = x1 + he / 2;
- a.setPoints(5, x1, y1, x1 - d, y1 + d, x1, y2, x2, y2, x2, y1);
- y1--;
- break;
- case SlRight:
- d = (he + 1) / 2 - 1;
- x2 = x2 - he / 2;
- a.setPoints(5, x1, y1, x1, y2, x2, y2, x2 + d, y1 + d, x2, y1);
- y1--;
- break;
- }
- QBrush oldBrush = painter->brush();
- painter->setPen(Qt::NoPen);
- painter->setBrush(handleBrush);
- Qt::BGMode oldMode = painter->backgroundMode();
- painter->setBackgroundMode(Qt::OpaqueMode);
- painter->drawRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
- painter->drawPolygon(a);
- QBrush fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1, y1, x2 - x1 + 1, y2 - y1 + 1),fill);
- painter->setBrush(oldBrush);
- painter->setBackgroundMode(oldMode);
-
- if (dir != SlUp) {
- painter->setPen(c4);
- painter->drawLine(x1, y1, x2, y1);
- painter->setPen(c3);
- painter->drawLine(x1, y1 + 1, x2, y1 + 1);
- }
- if (dir != SlLeft) {
- painter->setPen(c3);
- painter->drawLine(x1 + 1, y1 + 1, x1 + 1, y2);
- painter->setPen(c4);
- painter->drawLine(x1, y1, x1, y2);
- }
- if (dir != SlRight) {
- painter->setPen(c0);
- painter->drawLine(x2, y1, x2, y2);
- painter->setPen(c1);
- painter->drawLine(x2 - 1, y1 + 1, x2 - 1, y2 - 1);
- }
- if (dir != SlDown) {
- painter->setPen(c0);
- painter->drawLine(x1, y2, x2, y2);
- painter->setPen(c1);
- painter->drawLine(x1+1, y2 - 1, x2 - 1, y2 - 1);
- }
-
- switch (dir) {
- case SlUp:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 + 3, y1 - d + 2, x2 - x1 - 4,y1), fill);
- painter->setPen(c4);
- painter->drawLine(x1, y1, x1 + d, y1 - d);
- painter->setPen(c0);
- d = wi - d - 1;
- painter->drawLine(x2, y1, x2 - d, y1 - d);
- d--;
- painter->setPen(c3);
- painter->drawLine(x1 + 1, y1, x1 + 1 + d-1, y1 - d + 1);
- painter->setPen(c1);
- painter->drawLine(x2 - 1, y1, x2-1 - d, y1 - d);
- break;
- case SlDown:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 + 3, y2 - d, x2 - x1 - 4,y2 - 8), fill);
- painter->setPen(c4);
- painter->drawLine(x1, y2, x1 + d, y2 + d);
- painter->setPen(c0);
- d = wi - d - 1;
- painter->drawLine(x2, y2, x2 - d, y2 + d);
- d--;
- painter->setPen(c3);
- painter->drawLine(x1 + 1, y2, x1 + 1 + d - 1, y2 + d - 1);
- painter->setPen(c1);
- painter->drawLine(x2 - 1, y2, x2 - 1 - d, y2 + d);
- break;
- case SlLeft:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 - d + 2, y1 + 2, x1,y2 - y1 - 3), fill);
- painter->setPen(c4);
- painter->drawLine(x1, y1, x1 - d, y1 + d);
- painter->setPen(c0);
- d = he - d - 1;
- painter->drawLine(x1, y2, x1 - d, y2 - d);
- d--;
- painter->setPen(c3);
- painter->drawLine(x1, y1 + 1, x1 - d + 1, y1 + 1 + d - 1);
- painter->setPen(c1);
- painter->drawLine(x1, y2 - 1, x1 - d, y2 - 1 - d);
- break;
- case SlRight:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x2 - d - 4, y1 + 2, x2 - 4, y2 - y1 - 3), fill);
- painter->setPen(c4);
- painter->drawLine(x2, y1, x2 + d, y1 + d);
- painter->setPen(c0);
- d = he - d - 1;
- painter->drawLine(x2, y2, x2 + d, y2 - d);
- d--;
- painter->setPen(c3);
- painter->drawLine(x2, y1 + 1, x2 + d - 1, y1 + 1 + d - 1);
- painter->setPen(c1);
- painter->drawLine(x2, y2 - 1, x2 + d, y2 - 1 - d);
- break;
- }
- }
- }
- break;
-#endif // QT_NO_SLIDER
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- QRect button, menuarea;
-
-#ifndef QT_NO_TOOLBAR
- bool flat = !(widget ? qobject_cast<QToolBar*>(widget->parentWidget()) : 0);
-#else
- bool flat = true;
-#endif
-
- button = subControlRect(control, toolbutton, SC_ToolButton, widget);
- menuarea = subControlRect(control, toolbutton, SC_ToolButtonMenu, widget);
-
- if (flat && (toolbutton->subControls & SC_ToolButtonMenu)) {
- menuarea.setLeft(menuarea.left() - 4);
- button.setRight(button.right() - 4);
- }
-
- State bflags = toolbutton->state;
-
- if (bflags & State_AutoRaise)
- if (!(bflags & State_MouseOver)) {
- bflags &= ~State_Raised;
- }
- State mflags = bflags;
-
- if (toolbutton->activeSubControls & SC_ToolButton)
- bflags |= State_Sunken;
- if (toolbutton->activeSubControls & SC_ToolButtonMenu)
- mflags |= State_Sunken;
-
- QStyleOption tool(0);
- tool.palette = toolbutton->palette;
- if (toolbutton->subControls & SC_ToolButton) {
- tool.rect = button;
- tool.state = bflags;
- drawPrimitive(PE_PanelButtonTool, &tool, painter, widget);
- }
-
- if (toolbutton->subControls & SC_ToolButtonMenu) {
- tool.rect = menuarea;
- tool.state = mflags;
- tool.state = bflags;
- drawPrimitive(PE_IndicatorButtonDropDown, &tool, painter, widget);
-
- if (!flat) {
-
- //connect buttons
- painter->save();
- painter->setPen(tool.palette.button().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y(), tool.rect.x() - 2, tool.rect.y() + tool.rect.height());
- painter->drawLine(tool.rect.x() - 1, tool.rect.y(), tool.rect.x() - 1, tool.rect.y() + tool.rect.height());
- painter->drawLine(tool.rect.x(), tool.rect.y(), tool.rect.x(), tool.rect.y() + tool.rect.height());
- painter->drawLine(tool.rect.x() + 1, tool.rect.y(), tool.rect.x() + 1, tool.rect.y() + tool.rect.height());
-
- if (tool.state & State_Sunken)
- {
- painter->setPen(tool.palette.midlight().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y() + tool.rect.height() - 2,
- tool.rect.x() + 1, tool.rect.y() + tool.rect.height() -2 );
- painter->setPen(tool.palette.shadow().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y() + 1,tool.rect.x() + 1, tool.rect.y() + 1);
- painter->drawLine(tool.rect.x() - 2, tool.rect.y(), tool.rect.x() + 1, tool.rect.y());
- painter->setPen(tool.palette.light().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y() + tool.rect.height() - 1,
- tool.rect.x() + 1, tool.rect.y() + tool.rect.height() - 1);
- }
- else
- {
- painter->setPen(tool.palette.dark().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y(),tool.rect.x() + 1, tool.rect.y());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y()+tool.rect.height() - 2,tool.rect.x() + 1,
- tool.rect.y() + tool.rect.height() - 2);
- painter->setPen(tool.palette.midlight().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y() + 1,tool.rect.x() + 1, tool.rect.y() + 1);
- painter->setPen(tool.palette.shadow().color());
- painter->drawLine(tool.rect.x() - 2, tool.rect.y() + tool.rect.height() - 1,
- tool.rect.x() + 1, tool.rect.y() + tool.rect.height() - 1);
- }
- painter->restore();
- }
-
-
- if (!flat) {
- tool.rect.adjust(-3,0,-3,0);
- painter->save();
- painter->setPen(tool.palette.button().color());
- if (tool.state & State_Sunken)
- painter->drawLine(tool.rect.x() + 2, tool.rect.y() + 10,
- tool.rect.x() + tool.rect.width(), tool.rect.y() + 10);
- else
- painter->drawLine(tool.rect.x() + 1, tool.rect.y() + 9, tool.rect.x() +
- tool.rect.width() - 1, tool.rect.y() + 9);
- painter->restore();
- } else {
- tool.rect.adjust(-1,0,-1,0);
- }
-
- drawPrimitive(PE_IndicatorArrowDown, &tool, painter, widget);
- }
-
- if (toolbutton->state & State_HasFocus) {
- QStyleOptionFocusRect fr;
- fr.QStyleOption::operator=(*toolbutton);
- fr.rect.adjust(3, 3, -3, -3);
- if (toolbutton->features & QStyleOptionToolButton::Menu)
- fr.rect.adjust(0, 0, -pixelMetric(QStyle::PM_MenuButtonIndicator,
- toolbutton, widget), 0);
- drawPrimitive(PE_FrameFocusRect, &fr, painter, widget);
- }
- QStyleOptionToolButton label = *toolbutton;
- int fw = pixelMetric(PM_DefaultFrameWidth, option, widget);
- label.rect = button.adjusted(fw, fw, -fw, -fw);
- drawControl(CE_ToolButtonLabel, &label, painter, widget);
- }
- break;
-
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- // Draw frame
- painter->save();
- QFont f = painter->font();
- f.setBold(true);
- painter->setFont(f);
- QStyleOptionGroupBox groupBoxFont = *groupBox;
- groupBoxFont.fontMetrics = QFontMetrics(f);
- QRect textRect = subControlRect(CC_GroupBox, &groupBoxFont, SC_GroupBoxLabel, widget);
- QRect checkBoxRect = subControlRect(CC_GroupBox, option, SC_GroupBoxCheckBox, widget);
- if (groupBox->subControls & QStyle::SC_GroupBoxFrame) {
- QStyleOptionFrameV2 frame;
- frame.QStyleOption::operator=(*groupBox);
- frame.features = groupBox->features;
- frame.lineWidth = groupBox->lineWidth;
- frame.midLineWidth = groupBox->midLineWidth;
- frame.rect = subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);
- painter->save();
-
- QRegion region(groupBox->rect);
- if (!groupBox->text.isEmpty()) {
- bool ltr = groupBox->direction == Qt::LeftToRight;
- QRect finalRect = checkBoxRect.united(textRect);
- if (groupBox->subControls & QStyle::SC_GroupBoxCheckBox)
- finalRect.adjust(ltr ? -4 : 0, 0, ltr ? 0 : 4, 0);
- region -= finalRect;
- }
- painter->setClipRegion(region);
- drawPrimitive(PE_FrameGroupBox, &frame, painter, widget);
- painter->restore();
- }
-
- // Draw title
- if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
- QColor textColor = groupBox->textColor;
- if (textColor.isValid())
- painter->setPen(textColor);
- int alignment = int(groupBox->textAlignment);
- if (!styleHint(QStyle::SH_UnderlineShortcut, option, widget))
- alignment |= Qt::TextHideMnemonic;
-
- drawItemText(painter, textRect, Qt::TextShowMnemonic | Qt::AlignHCenter | alignment,
- groupBox->palette, groupBox->state & State_Enabled, groupBox->text,
- textColor.isValid() ? QPalette::NoRole : QPalette::WindowText);
-
- if (groupBox->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*groupBox);
- fropt.rect = textRect;
- drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- }
- // Draw checkbox
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*groupBox);
- box.rect = checkBoxRect;
- drawPrimitive(PE_IndicatorCheckBox, &box, painter, widget);
- }
- painter->restore();
- }
- break;
-#endif //QT_NO_GROUPBOX
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- QBrush editBrush = cmb->palette.brush(QPalette::Base);
- if ((cmb->subControls & SC_ComboBoxFrame) && cmb->frame)
- QWindowsCEStylePrivate::drawWinCEPanel(painter, option->rect, option->palette, true, &editBrush);
- else
- painter->fillRect(option->rect, editBrush);
-
- if (cmb->subControls & SC_ComboBoxArrow) {
- State flags = State_None;
-
- QRect ar = subControlRect(CC_ComboBox, cmb, SC_ComboBoxArrow, widget);
- if (cmb->activeSubControls == SC_ComboBoxArrow) {
- painter->setPen(cmb->palette.dark().color());
- painter->setBrush(cmb->palette.brush(QPalette::Button));
- painter->drawRect(ar.adjusted(0, 0, -1, -1));
- QWindowsCEStylePrivate::drawWinCEButton(painter, ar.adjusted(0, 0, -1, -1), option->palette, true,
- &cmb->palette.brush(QPalette::Button));
- } else {
- // Make qDrawWinButton use the right colors for drawing the shade of the button
-
- QWindowsCEStylePrivate::drawWinCEButton(painter, ar, option->palette, false,
- &cmb->palette.brush(QPalette::Button));
- }
-
- ar.adjust(2, 2, -2, -2);
- if (option->state & State_Enabled)
- flags |= State_Enabled;
-
- if (cmb->activeSubControls == SC_ComboBoxArrow)
- flags |= State_Sunken;
- QStyleOption arrowOpt(0);
- arrowOpt.rect = ar;
- arrowOpt.palette = cmb->palette;
- arrowOpt.state = flags;
- drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, painter, widget);
- }
- if (cmb->subControls & SC_ComboBoxEditField) {
- QRect re = subControlRect(CC_ComboBox, cmb, SC_ComboBoxEditField, widget);
- if (cmb->state & State_HasFocus && !cmb->editable)
- painter->fillRect(re.x(), re.y(), re.width(), re.height(),
- cmb->palette.brush(QPalette::Highlight));
- if (cmb->state & State_HasFocus) {
- painter->setPen(cmb->palette.highlightedText().color());
- painter->setBackground(cmb->palette.highlight());
- } else {
- painter->setPen(cmb->palette.text().color());
- painter->setBackground(cmb->palette.background());
- }
- if (cmb->state & State_HasFocus && !cmb->editable) {
- QStyleOptionFocusRect focus;
- focus.QStyleOption::operator=(*cmb);
- focus.rect = subElementRect(SE_ComboBoxFocusRect, cmb, widget);
- focus.state |= State_FocusAtBorder;
- focus.backgroundColor = cmb->palette.highlight().color();
- drawPrimitive(PE_FrameFocusRect, &focus, painter, widget);
- }
- }
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QStyleOptionSpinBox copy = *sb;
- PrimitiveElement pe;
-
- if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
- QRect r = subControlRect(CC_SpinBox, sb, SC_SpinBoxFrame, widget);
- QWindowsCEStylePrivate::drawWinCEPanel(painter, r, option->palette, true);
- }
- QPalette shadePal(option->palette);
- shadePal.setColor(QPalette::Button, option->palette.light().color());
- shadePal.setColor(QPalette::Light, option->palette.button().color());
-
- bool reverse = QApplication::layoutDirection() == Qt::RightToLeft;
-
- if (sb->subControls & SC_SpinBoxUp) {
- copy.subControls = SC_SpinBoxUp;
- QPalette pal2 = sb->palette;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepUpEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
- if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- if (reverse)
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinMinus
- : PE_IndicatorSpinDown);
- else
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinPlus
- : PE_IndicatorSpinUp);
- copy.rect = subControlRect(CC_SpinBox, sb, SC_SpinBoxUp, widget);
- QWindowsCEStylePrivate::drawWinCEButton(painter, copy.rect, option->palette, copy.state & (State_Sunken | State_On),
- &copy.palette.brush(QPalette::Button));
- copy.rect.adjust(3, 0, -4, 0);
- drawPrimitive(pe, &copy, painter, widget);
- }
- if (sb->subControls & SC_SpinBoxDown) {
- copy.subControls = SC_SpinBoxDown;
- copy.state = sb->state;
- QPalette pal2 = sb->palette;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
-
- if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- if (reverse)
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinPlus
- : PE_IndicatorSpinUp);
- else
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinMinus
- : PE_IndicatorSpinDown);
- copy.rect = subControlRect(CC_SpinBox, sb, SC_SpinBoxDown, widget);
- QWindowsCEStylePrivate::drawWinCEButton(painter, copy.rect, shadePal, copy.state & (State_Sunken | State_On),
- &copy.palette.brush(QPalette::Button));
-
- copy.rect.adjust(3, 0, -4, 0);
- if (pe == PE_IndicatorArrowUp || pe == PE_IndicatorArrowDown) {
- copy.rect = copy.rect.adjusted(1, 1, -1, -1);
- drawPrimitive(pe, &copy, painter, widget);
- }
- else {
- drawPrimitive(pe, &copy, painter, widget);
- }
- if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
- QRect r = subControlRect(CC_SpinBox, sb, SC_SpinBoxEditField, widget);
- painter->save();
- painter->setPen(option->palette.light().color());
- painter->drawLine(r.x() + 1 + r.width(), r.y() - 2, r.x() + 1 + r.width(), r.y() + r.height() + 1);
- painter->setPen(option->palette.midlight().color());
- painter->drawLine(r.x() + r.width(), r.y() - 1, r.x() + r.width(), r.y() + r.height());
- painter->restore();
- }
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-
- default:
- QWindowsStyle::drawComplexControl(control, option, painter, widget);
- break;
- }
-}
-
-void QWindowsCEStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
- bool enabled, const QString& text, QPalette::ColorRole textRole) const {
- if (text.isEmpty())
- return;
- QPen savedPen;
- if (textRole != QPalette::NoRole) {
- savedPen = painter->pen();
- painter->setPen(pal.color(textRole));
- }
- if (!enabled) {
- QPen pen = painter->pen();
- painter->setPen(pal.light().color());
- //painter->drawText(rect.adjusted(1, 1, 1, 1), alignment, text);
- painter->setPen(pen);
- }
- painter->drawText(rect, alignment, text);
- if (textRole != QPalette::NoRole)
- painter->setPen(savedPen);
-}
-
-
-QSize QWindowsCEStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const {
- QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget);
- switch (type) {
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- newSize = QWindowsStyle::sizeFromContents(type, option, size, widget);
- int w = newSize.width(),
- h = newSize.height();
- int defwidth = 0;
- if (btn->features & QStyleOptionButton::AutoDefaultButton)
- defwidth = 2 * pixelMetric(PM_ButtonDefaultIndicator, btn, widget);
- if (w < 75 + defwidth && btn->icon.isNull())
- w = 75 + defwidth;
- if (h < 23 + defwidth)
- h = 23 + defwidth;
- newSize = QSize(w+14, h);
- }
- break;
-
- case CT_RadioButton:
- case CT_CheckBox:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool isRadio = (type == CT_RadioButton);
- QRect irect = visualRect(btn->direction, btn->rect,
- subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, btn, widget));
- int h = pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
- : PM_IndicatorHeight, btn, widget);
- int margins = (!btn->icon.isNull() && btn->text.isEmpty()) ? 0 : 10;
- newSize += QSize(irect.right() + margins, 4);
- newSize.setHeight(qMax(newSize.height(), h));
- }
- break;
- case CT_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int fw = cmb->frame ? pixelMetric(PM_ComboBoxFrameWidth, option, widget) * 2 : 0;
- newSize = QSize(newSize.width() + fw -1, qMax(24, newSize.height() + fw-1));
- }
- break;
-#ifndef QT_NO_SPINBOX
- case CT_SpinBox:
- if (const QStyleOptionSpinBox *spnb = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- int fw = spnb->frame ? pixelMetric(PM_SpinBoxFrameWidth, option, widget) * 2 : 0;
- newSize = QSize(newSize.width() + fw - 5, newSize.height() + fw - 6);
- }
- break;
-#endif
- case CT_LineEdit:
- newSize += QSize(0,1);
- break;
- case CT_MenuBarItem:
- newSize += QSize(5, 1);
- break;
- case CT_MenuItem:
- newSize += QSize(0, -2);
- break;
- case CT_MenuBar:
- newSize += QSize(0, -1);
- break;
- case CT_ToolButton:
- if (const QStyleOptionToolButton *b = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- if (b->toolButtonStyle != Qt::ToolButtonIconOnly)
- newSize = QSize(newSize.width() + 1, newSize.height() - 1);
- else
- newSize = QSize(newSize.width() + 1, newSize.height());
- }
- break;
-
- default:
- break;
- }
- return newSize;
-}
-
-QRect QWindowsCEStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const {
- QRect rect = QWindowsStyle::subElementRect(element, option, widget);
- switch (element) {
-#ifndef QT_NO_COMBOBOX
- case SE_ComboBoxFocusRect:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int margin = cb->frame ? 3 : 0;
- rect.setRect(margin, margin, option->rect.width() - 2*margin - 20, option->rect.height() - 2*margin);
- rect = visualRect(option->direction, option->rect, rect);
- }
- break;
-#endif // QT_NO_COMBOBOX
- default:
- break;
- }
- return rect;
-}
-
-QRect QWindowsCEStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const {
- QRect rect = QWindowsStyle::subControlRect(control, option, subControl, widget);
- switch (control) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int tickOffset = pixelMetric(PM_SliderTickmarkOffset, slider, widget);
- int thickness = pixelMetric(PM_SliderControlThickness, slider, widget);
-
- switch (subControl) {
- case SC_SliderHandle: {
- int sliderPos = 0;
- int len = pixelMetric(PM_SliderLength, slider, widget);
- bool horizontal = slider->orientation == Qt::Horizontal;
- sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum,
- slider->sliderPosition,
- (horizontal ? slider->rect.width()
- : slider->rect.height()) - len,
- slider->upsideDown);
- if (horizontal)
- rect.setRect(slider->rect.x() + sliderPos, slider->rect.y() + tickOffset, len, thickness);
- else
- rect.setRect(slider->rect.x() + tickOffset, slider->rect.y() + sliderPos, thickness, len);
- break; }
- default:
- break;
- }
- rect = visualRect(slider->direction, slider->rect, rect);
- }
- break;
-#endif //QT_NO_SLIDER
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int x = cb->rect.x(),
- y = cb->rect.y(),
- wi = cb->rect.width(),
- he = cb->rect.height();
- int xpos = x;
- int margin = cb->frame ? 3 : 0;
- int bmarg = cb->frame ? 2 : 0;
- xpos += wi - (he - 2*bmarg) - bmarg;
- switch (subControl) {
- case SC_ComboBoxArrow:
- rect.setRect(xpos, y + bmarg, he - 2*bmarg, he - 2*bmarg);
- break;
- case SC_ComboBoxEditField:
- rect.setRect(x + margin, y + margin, wi - 2 * margin - (he - 2*bmarg), he - 2 * margin);
- break;
- case SC_ComboBoxListBoxPopup:
- rect = cb->rect;
- break;
- case SC_ComboBoxFrame:
- rect = cb->rect;
- break;
- default:
- break;
- }
- rect = visualRect(cb->direction, cb->rect, rect);
- }
-#endif //QT_NO_COMBOBOX
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QSize bs;
- int fw = spinbox->frame ? pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
- bs.setWidth(qMax(18, (spinbox->rect.height() / 2 - fw + 1)));
- // 1.6 -approximate golden mean
- bs.setHeight(qMax(18, qMin((bs.height() * 8 / 5), (spinbox->rect.width() / 4))));
- bs = bs.expandedTo(QApplication::globalStrut());
- int y = fw;
- int x, lx, rx;
- x = spinbox->rect.width() - y - bs.width() * 2;
- lx = fw;
- rx = x - fw;
- switch (subControl) {
- case SC_SpinBoxUp:
- rect = QRect(x + bs.width(), y, bs.width(), bs.height());
- break;
- case SC_SpinBoxDown:
- rect = QRect(x, y , bs.width(), bs.height());
- break;
- case SC_SpinBoxEditField:
- if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons) {
- rect = QRect(lx, fw, spinbox->rect.width() - 2*fw - 2, spinbox->rect.height() - 2*fw);
- } else {
- rect = QRect(lx, fw, rx-2, spinbox->rect.height() - 2*fw);
- }
- break;
- case SC_SpinBoxFrame:
- rect = spinbox->rect;
- default:
- break;
- }
- rect = visualRect(spinbox->direction, spinbox->rect, rect);
- }
- break;
-#endif // Qt_NO_SPINBOX
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox: {
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- switch (subControl) {
- case SC_GroupBoxFrame:
- // FALL THROUGH
- case SC_GroupBoxContents: {
- int topMargin = 0;
- int topHeight = 0;
- int bottomMargin = 0;
- int noLabelMargin = 0;
- QRect frameRect = groupBox->rect;
- int verticalAlignment = styleHint(SH_GroupBox_TextLabelVerticalAlignment, groupBox, widget);
- if (groupBox->text.size()) {
- topHeight = groupBox->fontMetrics.height();
- if (verticalAlignment & Qt::AlignVCenter)
- topMargin = topHeight / 2;
- else if (verticalAlignment & Qt::AlignTop)
- topMargin = -topHeight/2;
- }
- else {
- topHeight = groupBox->fontMetrics.height();
- noLabelMargin = topHeight / 2;
- if (verticalAlignment & Qt::AlignVCenter) {
- topMargin = topHeight / 4 - 4;
- bottomMargin = topHeight / 4 - 4;
- }
- else if (verticalAlignment & Qt::AlignTop) {
- topMargin = topHeight/2 - 4;
- bottomMargin = topHeight/2 - 4;
- }
- }
-
- if (subControl == SC_GroupBoxFrame) {
- frameRect.setTop(topMargin);
- frameRect.setBottom(frameRect.height() + bottomMargin);
- rect = frameRect;
- break;
- }
-
- int frameWidth = 0;
- if ((groupBox->features & QStyleOptionFrameV2::Flat) == 0)
- frameWidth = pixelMetric(PM_DefaultFrameWidth, groupBox, widget);
- rect = frameRect.adjusted(frameWidth, frameWidth + topHeight, -frameWidth, -frameWidth - noLabelMargin);
- break;
- }
- case SC_GroupBoxCheckBox:
- // FALL THROUGH
- case SC_GroupBoxLabel: {
- QFontMetrics fontMetrics = groupBox->fontMetrics;
- int h = fontMetrics.height();
- int tw = fontMetrics.size(Qt::TextShowMnemonic, groupBox->text + QLatin1Char(' ')).width();
- int marg = (groupBox->features & QStyleOptionFrameV2::Flat) ? 0 : 8;
- rect = groupBox->rect.adjusted(marg, 0, -marg, 0);
- rect.setHeight(h);
-
- int indicatorWidth = pixelMetric(PM_IndicatorWidth, option, widget);
- int indicatorSpace = pixelMetric(PM_CheckBoxLabelSpacing, option, widget) - 1;
- bool hasCheckBox = groupBox->subControls & QStyle::SC_GroupBoxCheckBox;
- int checkBoxSize = hasCheckBox ? (indicatorWidth + indicatorSpace) : 0;
-
- // Adjusted rect for label + indicatorWidth + indicatorSpace
- QRect totalRect = alignedRect(groupBox->direction, groupBox->textAlignment,
- QSize(tw + checkBoxSize, h), rect);
-
- // Adjust totalRect if checkbox is set
- if (hasCheckBox) {
- bool ltr = groupBox->direction == Qt::LeftToRight;
- int left = 0;
- // Adjust for check box
- if (subControl == SC_GroupBoxCheckBox) {
- int indicatorHeight = pixelMetric(PM_IndicatorHeight, option, widget);
- left = ltr ? totalRect.left() : (totalRect.right() - indicatorWidth);
- int top = totalRect.top() + (fontMetrics.height() - indicatorHeight) / 2;
- totalRect.setRect(left, top, indicatorWidth, indicatorHeight);
- // Adjust for label
- } else {
- left = ltr ? (totalRect.left() + checkBoxSize - 2) : totalRect.left();
- totalRect.setRect(left, totalRect.top(),
- totalRect.width() - checkBoxSize, totalRect.height());
- }
- }
- rect = totalRect;
- break;
- }
- default:
- break;
- }
- }
- break;
- }
-#endif // QT_NO_GROUPBOX
- default:
- break;
- }
- return rect;
-}
-
-QStyle::SubControl QWindowsCEStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- const QPoint &pos, const QWidget *widget) const {
- /*switch (control) {
- default:
- break;
- }*/
- return QWindowsStyle::hitTestComplexControl(control, option, pos, widget);
-}
-
-
-QPalette QWindowsCEStyle::standardPalette() const {
- QPalette palette (Qt::black,QColor(198, 195, 198), QColor(222, 223, 222 ),
- QColor(132, 130, 132), QColor(198, 195, 198) , Qt::black, Qt::white, Qt::white, QColor(198, 195, 198));
- palette.setColor(QPalette::Window, QColor(198, 195, 198));
- palette.setColor(QPalette::Base, Qt::white);
- palette.setColor(QPalette::Button, QColor(198, 195, 198));
- palette.setColor(QPalette::Highlight, QColor(0, 0, 132));
- palette.setColor(QPalette::Light, Qt::white);
- palette.setColor(QPalette::Midlight, QColor(222, 223, 222 ));
- palette.setColor(QPalette::Dark, QColor(132, 130, 132));
- palette.setColor(QPalette::Mid, QColor(132, 130, 132));
- palette.setColor(QPalette::Shadow, QColor(0, 0, 0));
- palette.setColor(QPalette::BrightText, QColor(33, 162, 33)); //color for ItemView checked indicator (arrow)
- palette.setColor(QPalette::Link, QColor(24,81,132)); // color for the box around the ItemView indicator
-
- return palette;
-}
-
-void QWindowsCEStyle::polish(QApplication *app) {
- QWindowsStyle::polish(app);
-}
-
-void QWindowsCEStyle::polish(QWidget *widget) {
- QWindowsStyle::polish(widget);
-}
-
-void QWindowsCEStyle::polish(QPalette &palette) {
- QWindowsStyle::polish(palette);
-}
-
-int QWindowsCEStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QWidget *widget) const {
- int ret;
-
- switch (pm) {
- case PM_DefaultFrameWidth:
- ret = 1;
- break;
-
- case PM_MenuBarHMargin:
- ret = 2;
- break;
- case PM_MenuBarVMargin:
- ret = 2;
- break;
- /*case PM_MenuBarItemSpacing:
- ret = 2;
- break;*/
-
- case PM_MenuButtonIndicator:
- ret = 10;
- break;
-
- case PM_SpinBoxFrameWidth:
- ret = 2;
- break;
- case PM_ButtonDefaultIndicator:
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- ret = 1;
- break;
-#ifndef QT_NO_TABBAR
- case PM_TabBarTabShiftHorizontal:
- ret = 0;
- break;
- case PM_TabBarTabShiftVertical:
- ret = 6;
- break;
-#endif
- case PM_MaximumDragDistance:
- ret = 60;
- break;
-
- case PM_IndicatorWidth:
- ret = windowsCEIndicatorSize;
- break;
-
- case PM_IndicatorHeight:
- ret = windowsCEIndicatorSize;
- break;
-
- case PM_ExclusiveIndicatorWidth:
- ret = windowsCEExclusiveIndicatorSize;
- break;
-
- case PM_ExclusiveIndicatorHeight:
- ret = windowsCEExclusiveIndicatorSize;;
- break;
-
-#ifndef QT_NO_SLIDER
- case PM_SliderLength:
- ret = 12;
- break;
- case PM_SliderThickness:
- ret = windowsCESliderThickness;
- break;
-
- case PM_TabBarScrollButtonWidth:
- ret = 18;
- break;
-
- // Returns the number of pixels to use for the business part of the
- // slider (i.e., the non-tickmark portion). The remaining space is shared
- // equally between the tickmark regions.
- case PM_SliderControlThickness:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int space = (sl->orientation == Qt::Horizontal) ? sl->rect.height() : sl->rect.width();
- int ticks = sl->tickPosition;
- int n = 0;
- if (ticks & QSlider::TicksAbove)
- ++n;
- if (ticks & QSlider::TicksBelow)
- ++n;
- if (!n) {
- ret = space;
- break;
- }
- int thick = 12;
- if (ticks != QSlider::TicksBothSides && ticks != QSlider::NoTicks)
- thick += pixelMetric(PM_SliderLength, sl, widget) / 4;
-
- space -= thick;
- if (space > 0)
- thick += (space * 2) / (n + 2);
- ret = thick;
- } else {
- ret = 0;
- }
- break;
-#endif // QT_NO_SLIDER
-
-#ifndef QT_NO_MENU
-
- case PM_SmallIconSize:
- ret = windowsCEIconSize;
- break;
- case PM_ButtonMargin:
- ret = 6;
- break;
-
- case PM_LargeIconSize:
- ret = 32;
- break;
-
- case PM_IconViewIconSize:
- ret = pixelMetric(PM_LargeIconSize, opt, widget);
- break;
-
- case PM_ToolBarIconSize:
- ret = windowsCEIconSize;
- break;
- case PM_DockWidgetTitleMargin:
- ret = 2;
- break;
-#if defined(Q_WS_WIN)
-// case PM_DockWidgetFrameWidth:
-// ret = GetSystemMetrics(SM_CXFRAME);
-// break;
-#else
- case PM_DockWidgetFrameWidth:
- ret = 4;
- break;
-#endif // Q_WS_WIN
- break;
-
-#endif // QT_NO_MENU
-
- case PM_TitleBarHeight:
- ret = 30;
- break;
- case PM_ScrollBarExtent:
- ret = 19;
- break;
- case PM_SplitterWidth:
- ret = qMax(4, QApplication::globalStrut().width());
- break;
-
-#if defined(Q_WS_WIN)
- case PM_MDIFrameWidth:
- ret = 3;
- break;
-#endif
- case PM_ToolBarItemMargin:
- ret = 1;
- break;
- case PM_ToolBarItemSpacing:
- ret = 0;
- break;
- case PM_ToolBarHandleExtent:
- ret = 10;
- break;
- case PM_ButtonIconSize:
- ret = 22;
- break;
- default:
- ret = QWindowsStyle::pixelMetric(pm, opt, widget);
- break;
- }
- return ret;
-}
-
-QPixmap QWindowsCEStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget) const {
-#ifndef QT_NO_IMAGEFORMAT_XPM
- /*switch (standardPixmap) {
-
- default:
- break;
- }*/
-#endif //QT_NO_IMAGEFORMAT_XPM
- return QWindowsStyle::standardPixmap(standardPixmap, opt, widget);
-}
-
-int QWindowsCEStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWidget *widget,
- QStyleHintReturn *returnData) const {
- int ret;
- switch (hint) {
- case SH_TabBar_ElideMode:
- ret = Qt::ElideMiddle;
- break;
- case SH_EtchDisabledText:
- ret = false;
- break;
- case SH_RequestSoftwareInputPanel:
- ret = RSIP_OnMouseClick;
- break;
- default:
- ret = QWindowsStyle::styleHint(hint, opt, widget, returnData);
- break;
- }
- return ret;
-}
-
-void QWindowsCEStylePrivate::drawWinShades(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill) {
- if (w < 2 || h < 2) // can't do anything with that
- return;
- QPen oldPen = p->pen();
- QPoint a[3] = { QPoint(x, y+h-2), QPoint(x, y), QPoint(x+w-2, y) };
- p->setPen(c1);
- p->drawPolyline(a, 3);
- QPoint b[3] = { QPoint(x, y+h-1), QPoint(x+w-1, y+h-1), QPoint(x+w-1, y) };
- p->setPen(c2);
- p->drawPolyline(b, 3);
- if (w > 4 && h > 4) {
- QPoint c[3] = { QPoint(x+1, y+h-3), QPoint(x+1, y+1), QPoint(x+w-3, y+1) };
- p->setPen(c3);
- p->drawPolyline(c, 3);
- QPoint d[3] = { QPoint(x+1, y+h-2), QPoint(x+w-2, y+h-2), QPoint(x+w-2, y+1) };
- p->setPen(c4);
- p->drawPolyline(d, 3);
- if (fill)
- p->fillRect(QRect(x+2, y+2, w-4, h-4), *fill);
- }
- p->setPen(oldPen);
-}
-
-void QWindowsCEStylePrivate::drawWinCEShades(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill) {
- if (w < 2 || h < 2) // can't do anything with that
- return;
- QPen oldPen = p->pen();
- QPoint b[3] = { QPoint(x, y+h-1), QPoint(x+w-1, y+h-1), QPoint(x+w-1, y) };
- p->setPen(c2);
- p->drawPolyline(b, 3);
- if (w > 4 && h > 4) {
- QPoint c[3] = { QPoint(x+1, y+h-3), QPoint(x+1, y+1), QPoint(x+w-3, y+1) };
- p->setPen(c3);
- p->drawPolyline(c, 3);
- QPoint d[5] = { QPoint(x, y+h-2), QPoint(x+w-2, y+h-2), QPoint(x+w-2, y), QPoint(x, y), QPoint(x, y+h-2) };
- p->setPen(c4);
- p->drawPolyline(d, 5);
- if (fill)
- p->fillRect(QRect(x+2, y+2, w-4, h-4), *fill);
- }
- QPoint a[3] = { QPoint(x+1, y+h-3), QPoint(x+1, y+1), QPoint(x+w-3, y+1) };
- p->setPen(c1);
- p->drawPolyline(a, 3);
- p->setPen(oldPen);
-}
-
-void QWindowsCEStylePrivate::drawWinCEShadesSunken(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill) {
- if (w < 2 || h < 2) // can't do anything with that
- return;
- QPen oldPen = p->pen();
-
- QPoint b[3] = { QPoint(x, y+h-1), QPoint(x+w-1, y+h-1), QPoint(x+w-1, y) };
- p->setPen(c2);
- p->drawPolyline(b, 3);
- if (w > 4 && h > 4) {
- QPoint d[3] = { QPoint(x, y+h-2), QPoint(x+w-2, y+h-2), QPoint(x+w-2, y) };
- p->setPen(c4);
- p->drawPolyline(d, 3);
- QPoint c[3] = { QPoint(x, y+h-2), QPoint(x, y), QPoint(x+w-2, y) };
- p->setPen(c3);
- p->drawPolyline(c, 3);
- if (fill)
- p->fillRect(QRect(x+2, y+2, w-4, h-4), *fill);
- }
- QPoint a[3] = { QPoint(x+1, y+h-3), QPoint(x+1, y+1), QPoint(x+w-3, y+1) };
- p->setPen(c1);
- p->drawPolyline(a, 3);
- p->setPen(oldPen);
-}
-
-
-void QWindowsCEStylePrivate::drawWinCEButton(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken,
- const QBrush *fill) {
- if (sunken)
- drawWinCEShadesSunken(p, x, y, w, h,
- pal.shadow().color(), pal.light().color(), pal.shadow().color(),
- pal.midlight().color(), fill);
- else
- drawWinCEShades(p, x, y, w, h,
- pal.midlight().color(), pal.shadow().color(), pal.button().color(),
- pal.dark().color(), fill);
-}
-
-void QWindowsCEStylePrivate::drawWinCEPanel(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken,
- const QBrush *fill) {
- if (sunken)
- drawWinShades(p, x, y, w, h,
- pal.dark().color(), pal.light().color(), pal.shadow().color(),
- pal.midlight().color(), fill);
- else
- drawWinShades(p, x, y, w, h,
- pal.light().color(), pal.shadow().color(), pal.button().color(),
- pal.midlight().color(), fill);
-}
-
-void QWindowsCEStylePrivate::drawWinCEButton(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken, const QBrush *fill) {
- drawWinCEButton(p, r.x(), r.y(), r.width(), r.height(), pal, sunken, fill);
-}
-
-void QWindowsCEStylePrivate::drawWinCEPanel(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken, const QBrush *fill) {
- drawWinCEPanel(p, r.x(), r.y(), r.width(), r.height(), pal, sunken, fill);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSCE
diff --git a/src/gui/styles/qwindowscestyle.h b/src/gui/styles/qwindowscestyle.h
deleted file mode 100644
index 3fd83bc764..0000000000
--- a/src/gui/styles/qwindowscestyle.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSCESTYLE_H
-#define QWINDOWSCESTYLE_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_WINDOWSCE)
-
-class Q_GUI_EXPORT QWindowsCEStyle : public QWindowsStyle
-{
- Q_OBJECT
-public:
- QWindowsCEStyle();
-
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget = 0) const;
-
- void drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const;
-
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const;
-
- virtual void drawItemText(QPainter *painter, const QRect &rect,
- int flags, const QPalette &pal, bool enabled,
- const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const;
-
- QSize sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const;
-
- QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const;
-
- SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- const QPoint &pos, const QWidget *widget = 0) const;
-
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
-
- int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
-
- void polish(QWidget *widget);
- void polish(QPalette &palette);
- void polish(QApplication *app);
- QPalette standardPalette() const;
-};
-
-#endif // QT_NO_STYLE_WINDOWSCE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWINDOWSCESTYLE_H
diff --git a/src/gui/styles/qwindowscestyle_p.h b/src/gui/styles/qwindowscestyle_p.h
deleted file mode 100644
index c2d9c68ea7..0000000000
--- a/src/gui/styles/qwindowscestyle_p.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSCE_P_H
-#define QWINDOWSCE_P_H
-
-#include "qwindowscestyle.h"
-#include <private/qwindowsstyle_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_NAMESPACE
-
-class QPainter;
-class QPalette;
-class QPoint;
-class QColor;
-class QBrush;
-class QRect;
-
-// Private class
-class QWindowsCEStylePrivate : public QWindowsStylePrivate
-{
- Q_DECLARE_PUBLIC(QWindowsCEStyle)
-public:
- inline QWindowsCEStylePrivate()
- { }
-
-
-static void drawWinCEButton(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-static void drawWinCEButton(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-static void drawWinCEPanel(QPainter *p, int x, int y, int w, int h,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-static void drawWinCEPanel(QPainter *p, const QRect &r,
- const QPalette &pal, bool sunken = false,
- const QBrush *fill = 0);
-
-static void drawWinShades(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill);
-
-static void drawWinCEShades(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill);
-
-static void drawWinCEShadesSunken(QPainter *p,
- int x, int y, int w, int h,
- const QColor &c1, const QColor &c2,
- const QColor &c3, const QColor &c4,
- const QBrush *fill);
-
-
-
-
-};
-
-QT_END_NAMESPACE
-
-#endif //QWINDOWSCE_P_H
diff --git a/src/gui/styles/qwindowsmobilestyle.cpp b/src/gui/styles/qwindowsmobilestyle.cpp
deleted file mode 100644
index 32cc2e63b8..0000000000
--- a/src/gui/styles/qwindowsmobilestyle.cpp
+++ /dev/null
@@ -1,7283 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwindowsmobilestyle.h"
-#include "qwindowsmobilestyle_p.h"
-
-#if !defined(QT_NO_STYLE_WINDOWSMOBILE) || defined(QT_PLUGIN)
-
-#include "qpainterpath.h"
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qwidget.h"
-#include "qdockwidget.h"
-#include "qframe.h"
-#include "qmenu.h"
-#include "qpaintengine.h"
-#include "qpainter.h"
-#include "qgroupbox.h"
-#include "qstyleoption.h"
-#include "qlistview.h"
-#include "qdrawutil.h"
-#include "qtoolbar.h"
-#include "qabstractscrollarea.h"
-#include "qabstractbutton.h"
-#include "qcombobox.h"
-#include "qabstractscrollarea.h"
-#include "qframe.h"
-#include "qscrollbar.h"
-#include "qabstractitemview.h"
-#include "qmenubar.h"
-#include "qtoolbutton.h"
-#include "qtextedit.h"
-#include "qdialog.h"
-#include "qdebug.h"
-#include "qtabwidget.h"
-
-#ifdef Q_WS_WINCE
-#include "qt_windows.h"
-#include "qguifunctions_wince.h"
-extern bool qt_wince_is_high_dpi(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_smartphone(); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_windows_mobile_65(); //defined in qguifunctions_wince.cpp
-#endif // Q_WS_WINCE
-
-#include "qstylehelper_p.h"
-
-QT_BEGIN_NAMESPACE
-
-static const int windowsItemFrame = 1; // menu item frame width
-
-static const int windowsMobileitemViewCheckBoxSize = 13;
-static const int windowsMobileFrameGroupBoxOffset = 9;
-static const int windowsMobileIndicatorSize = 14;
-static const int windowsMobileExclusiveIndicatorSize = 14;
-static const int windowsMobileSliderThickness = 6;
-static const int windowsMobileIconSize = 16;
-static const int PE_IndicatorArrowUpBig = 0xf000101;
-static const int PE_IndicatorArrowDownBig = 0xf000102;
-static const int PE_IndicatorArrowLeftBig = 0xf000103;
-static const int PE_IndicatorArrowRightBig = 0xf000104;
-
-/* XPM */
-static const char *const radiobutton_xpm[] = {
- "30 30 2 1",
- " c None",
- ". c #000000",
- " ........ ",
- " .............. ",
- " .... .... ",
- " .... .... ",
- " ... ... ",
- " ... ... ",
- " .. .. ",
- " .. .. ",
- " ... ... ",
- " .. .. ",
- " .. .. ",
- ".. ..",
- ".. ..",
- ".. ..",
- ".. ..",
- ".. ..",
- ".. ..",
- ".. ..",
- ".. ..",
- " .. .. ",
- " .. .. ",
- " ... ... ",
- " .. .. ",
- " .. .. ",
- " ... ... ",
- " ... ... ",
- " .... .... ",
- " .... .... ",
- " .............. ",
- " ........ "};
-
-/* XPM */
-static const char * const radiobutton_low_xpm[] = {
- "15 15 2 1",
- " c None",
- ". c #000000",
- " ..... ",
- " .. .. ",
- " . . ",
- " . . ",
- " . . ",
- ". .",
- ". .",
- ". .",
- ". .",
- ". .",
- " . . ",
- " . . ",
- " . . ",
- " .. .. ",
- " ..... "};
-
-/* XPM */
- static const char * const arrowleft_big_xpm[] = {
- "9 17 2 1",
- " c None",
- ". c #000000",
- " .",
- " ..",
- " ...",
- " ....",
- " .....",
- " ......",
- " .......",
- " ........",
- ".........",
- " ........",
- " .......",
- " ......",
- " .....",
- " ....",
- " ...",
- " ..",
- " ."};
-
-/* XPM */
- static const char * const arrowleft_xpm[] = {
- "8 15 2 1",
- " c None",
- ". c #000000",
- " .",
- " ..",
- " ...",
- " ....",
- " .....",
- " ......",
- " .......",
- "........",
- " .......",
- " ......",
- " .....",
- " ....",
- " ...",
- " ..",
- " ."};
-
-
-
-/* XPM */
-static const char *const horlines_xpm[] = {
- "2 2 2 1",
- " c None",
- ". c #000000",
- " ",
- ".."};
-
-/* XPM */
-static const char *const vertlines_xpm[] = {
- "2 2 2 1",
- " c None",
- ". c #000000",
- ". ",
- ". "};
-
-/* XPM */
-static const char *const radiochecked_xpm[] = {
- "18 18 2 1",
- " c None",
- ". c #000000",
- " ...... ",
- " .......... ",
- " .............. ",
- " .............. ",
- " ................ ",
- " ................ ",
- "..................",
- "..................",
- "..................",
- "..................",
- "..................",
- "..................",
- " ................ ",
- " ................ ",
- " .............. ",
- " .............. ",
- " .......... ",
- " ...... "};
-
-/* XPM */
-static const char * const radiochecked_low_xpm[] = {
- "9 9 2 1",
- " c None",
- ". c #000000",
- " ... ",
- " ....... ",
- " ....... ",
- ".........",
- ".........",
- ".........",
- " ....... ",
- " ....... ",
- " ... "};
-
-static const char *const arrowdown_xpm[] = {
- "15 8 2 1",
- " c None",
- ". c #000000",
- "...............",
- " ............. ",
- " ........... ",
- " ......... ",
- " ....... ",
- " ..... ",
- " ... ",
- " . "};
-
-
-static const char *const arrowdown_big_xpm[] = {
- "17 9 2 1",
- " c None",
- ". c #000000",
- ".................",
- " ............... ",
- " ............. ",
- " ........... ",
- " ......... ",
- " ....... ",
- " ..... ",
- " ... ",
- " . "};
-
-
-/* XPM */
-static const char *const checkedlight_xpm[] = {
- "24 24 2 1",
- " c None",
- ". c #000000",
- " ",
- " ",
- " ",
- " ",
- " ",
- " . ",
- " .. ",
- " ... ",
- " .... ",
- " ..... ",
- " ...... ",
- " . ...... ",
- " .. ...... ",
- " ... ...... ",
- " .... ...... ",
- " .......... ",
- " ......... ",
- " ....... ",
- " ..... ",
- " ... ",
- " . ",
- " ",
- " ",
- " "};
-
-
-/* XPM */
-static const char *const checkedbold_xpm[] = {
- "26 26 2 1",
- " c None",
- ". c #000000",
- " ",
- " ",
- " ",
- " ",
- " ",
- " ",
- " .. ",
- " ... ",
- " .... ",
- " ..... ",
- " .. ...... ",
- " ... ....... ",
- " .... ....... ",
- " ..... ....... ",
- " ...... ....... ",
- " .............. ",
- " ............ ",
- " .......... ",
- " ........ ",
- " ...... ",
- " .... ",
- " .. ",
- " ",
- " ",
- " ",
- " "};
-
-/* XPM */
-static const char * const checkedbold_low_xpm[] = {
- "9 8 2 1",
- " c None",
- ". c #000000",
- " .",
- " ..",
- ". ...",
- ".. ... ",
- "... ... ",
- " ..... ",
- " ... ",
- " . "};
-
-/* XPM */
-static const char * const checkedlight_low_xpm[] = {
- "8 8 2 1",
- " c None",
- ". c #000000",
- " .",
- " ..",
- " ...",
- ". ... ",
- ".. ... ",
- "..... ",
- " ... ",
- " . "};
-
-/* XPM */
-static const char * const highlightedradiobutton_xpm[] = {
- "30 30 3 1",
- " c None",
- ". c #000000",
- "+ c #0078CC",
- " ........ ",
- " .............. ",
- " ....++++++++.... ",
- " ....++++++++++++.... ",
- " ...++++ ++++... ",
- " ...+++ +++... ",
- " ..++ ++.. ",
- " ..++ ++.. ",
- " ...++ ++... ",
- " ..++ ++.. ",
- " ..++ ++.. ",
- "..++ ++..",
- "..++ ++..",
- "..++ ++..",
- "..++ ++..",
- "..++ ++..",
- "..++ ++..",
- "..++ ++..",
- "..++ ++..",
- " ..++ ++.. ",
- " ..++ ++.. ",
- " ...++ ++... ",
- " ..++ ++.. ",
- " ..++ ++.. ",
- " ...+++ +++... ",
- " ...++++ ++++... ",
- " ....++++++++++++.... ",
- " ....++++++++.... ",
- " .............. ",
- " ........ "};
-
-/* XPM */
-static const char * const highlightedradiobutton_low_xpm[] = {
- "15 15 3 1",
- " c None",
- ". c #000000",
- "+ c #3192D6",
- " ..... ",
- " ..+++++.. ",
- " .++ ++. ",
- " .+ +. ",
- " .+ +. ",
- ".+ +.",
- ".+ +.",
- ".+ +.",
- ".+ +.",
- ".+ +.",
- " .+ +. ",
- " .+ +. ",
- " .++ ++. ",
- " ..+++++.. ",
- " ..... "};
-
-/* XPM */
-static const char * const cross_big_xpm[] = {
-"28 28 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FDFFFC",
-" ",
-" ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++..@@@..........@@@..++ ",
-" ++..@@@@........@@@@..++ ",
-" ++..@@@@@......@@@@@..++ ",
-" ++...@@@@@....@@@@@...++ ",
-" ++....@@@@@..@@@@@....++ ",
-" ++.....@@@@@@@@@@.....++ ",
-" ++......@@@@@@@@......++ ",
-" ++.......@@@@@@.......++ ",
-" ++.......@@@@@@.......++ ",
-" ++......@@@@@@@@......++ ",
-" ++.....@@@@@@@@@@.....++ ",
-" ++....@@@@@..@@@@@....++ ",
-" ++...@@@@@....@@@@@...++ ",
-" ++..@@@@@......@@@@@..++ ",
-" ++..@@@@........@@@@..++ ",
-" ++..@@@..........@@@..++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ",
-" "};
-
-/* XPM */
-static const char * const cross_small_xpm[] = {
-"14 14 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FCFFFC",
-" ",
-" ++++++++++++ ",
-" +..........+ ",
-" +.@@....@@.+ ",
-" +.@@@..@@@.+ ",
-" +..@@@@@@..+ ",
-" +...@@@@...+ ",
-" +...@@@@...+ ",
-" +..@@@@@@..+ ",
-" +.@@@..@@@.+ ",
-" +.@@....@@.+ ",
-" +..........+ ",
-" ++++++++++++ ",
-" "};
-
-/* XPM */
-static const char * const max_big_xpm[] = {
-"28 28 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FDFFFC",
-" ",
-" ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ",
-" "};
-
-/* XPM */
-static const char * const max_small_xpm[] = {
-"14 14 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FCFFFC",
-" ",
-" ++++++++++++ ",
-" +..........+ ",
-" +..........+ ",
-" +.@@@@@@@@.+ ",
-" +.@@@@@@@@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@@@@@@@@.+ ",
-" +..........+ ",
-" +..........+ ",
-" ++++++++++++ ",
-" "};
-
-/* XPM */
-static const char * const normal_big_xpm[] = {
-"28 28 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FDFFFC",
-" ",
-" ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@............@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ",
-" "};
-
-/* XPM */
-static const char * const normal_small_xpm[] = {
-"14 14 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FCFFFC",
-" ",
-" ++++++++++++ ",
-" +..........+ ",
-" +.@@@@@@@@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@......@.+ ",
-" +.@@@@@@@@.+ ",
-" +..........+ ",
-" ++++++++++++ ",
-" "};
-
-
-/* XPM */
-static const char * const min_big_xpm[] = {
-"28 28 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FDFFFC",
-" ",
-" ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++..@@@@@@@@@@@@@@@@..++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++....................++ ",
-" ++++++++++++++++++++++++ ",
-" ++++++++++++++++++++++++ ",
-" ",
-" "};
-
-/* XPM */
-static const char * const min_small_xpm[] = {
-"14 14 4 1",
-" c #09454A",
-". c #218C98",
-"+ c #47D8E5",
-"@ c #FCFFFC",
-" ",
-" ++++++++++++ ",
-" +..........+ ",
-" +..........+ ",
-" +..........+ ",
-" +..........+ ",
-" +..........+ ",
-" +..........+ ",
-" +..........+ ",
-" +.@@@@@@@@.+ ",
-" +..........+ ",
-" +..........+ ",
-" ++++++++++++ ",
-" "};
-
-#ifdef Q_WS_WINCE_WM
-
-static char * sbhandleup_xpm[] = {
-"26 41 45 1",
-" c None",
-". c #000000",
-"+ c #E7E7E7",
-"@ c #D6D7D6",
-"# c #949294",
-"$ c #737573",
-"% c #636563",
-"& c #636163",
-"* c #5A5D5A",
-"= c #5A595A",
-"- c #525552",
-"; c #525152",
-"> c #4A4D4A",
-", c #7B797B",
-"' c #CECFCE",
-") c #CED3CE",
-"! c #6B6D6B",
-"~ c #6B696B",
-"{ c #737173",
-"] c #7B7D7B",
-"^ c #848684",
-"/ c #848284",
-"( c #8C8A8C",
-"_ c #8C8E8C",
-": c #B5B2B5",
-"< c #FFFFFF",
-"[ c #949694",
-"} c #B5B6B5",
-"| c #9C9A9C",
-"1 c #ADAEAD",
-"2 c #9C9E9C",
-"3 c #BDBABD",
-"4 c #BDBEBD",
-"5 c #F7F3F7",
-"6 c #C6C3C6",
-"7 c #C6C7C6",
-"8 c #A5A2A5",
-"9 c #CECBCE",
-"0 c #FFFBFF",
-"a c #ADAAAD",
-"b c #A5A6A5",
-"c c #D6D3D6",
-"d c #B5BAB5",
-"e c #DEDFDE",
-"f c #DEDBDE",
-"..........................",
-"+@#$%%&&&**===---;;;;>=,'+",
-"+@#$%%&&&**===---;;;;>=$'+",
-")$!!~~%%&&&**===---;;;;>;'",
-"#{$]],,$${{{!!~~%%%&&&*-;]",
-"#{$]],,$${{{!!~~%%%&&&*-;]",
-",$^//]],,$${{{!!~~%%%&&*;*",
-",,(^^//]],$${!!!!!~~%%%&-*",
-",,(^^//]],$${!!!!!~~%%%&-*",
-"]]_((^^//]$!%%~!{{!!~~%%-*",
-"//#__((^^]{:<<:~!{{{!!~~=*",
-"//#__((^^]{:<<:~!{{{!!~~=&",
-"//###__(/$:<<<<:~{${{!!~*&",
-"^^[[##_^]:<<<<<<}!{$${{!*%",
-"^^[[##_^]:<<<<<<}!{$${{!*%",
-"((|[[#_/:<<<<<<<<}!$$${{&~",
-"((||[#^1<<<<1:<<<<}!$$$$&~",
-"((||[#^1<<<<1:<<<<}!$$$$&~",
-"__2|#(1<<<<}],}<<<<}{$,$%~",
-"##2|_1<<<<}^((]3<<<<}{$,~!",
-"##2|_1<<<<}^((]3<<<<}{$,~!",
-"##2#1<<<<3^###(/4<<<<}{,~{",
-"##2#1<<<<3^###(/4<<<<}{,~!",
-"[[2_5<<<4(#|[[#_/6<<<<,,!{",
-"[|2_5<<4_[||||[[_/7<<<,]{$",
-"[|2_5<<4_[||||[[_/7<<<,]{$",
-"||8_5<6#|2222|||[_/9<<,]{$",
-"228#06[28888222||[_/'<,/$,",
-"228#06[28888222||[_/'<,/$,",
-"22a|6[8bbbb88822||[(/c](,]",
-"881b8baaabbbb88222|[(^(_,]",
-"881b8baaabbbb88222|[(^(_,]",
-"88111111aaabbb88822|[###]/",
-"bb:::11111aaabbb8822||[[/^",
-"bb:::11111aaabbb8822||[[//",
-"bb:::::1111aaabbb8822||[/(",
-"3a1::::::1111aaabb8822|_^8",
-"da1::::::1111aaabb8822|_^8",
-"e1aaabbbb888822||[[##__((@",
-"+e4:aaabbbb88822||[[[#[b@+",
-"+e4:aaabbbb88822||[[[#[bf+"};
-
-static char * sbhandledown_xpm[] = {
-"26 40 46 1",
-" c None",
-". c #E7E7E7",
-"+ c #DEDFDE",
-"@ c #BDBEBD",
-"# c #B5B2B5",
-"$ c #ADAAAD",
-"% c #A5A6A5",
-"& c #A5A2A5",
-"* c #9C9E9C",
-"= c #9C9A9C",
-"- c #949694",
-"; c #949294",
-"> c #D6D7D6",
-", c #DEDBDE",
-"' c #D6DBD6",
-") c #ADAEAD",
-"! c #8C8E8C",
-"~ c #8C8A8C",
-"{ c #BDBABD",
-"] c #848684",
-"^ c #B5BAB5",
-"/ c #848284",
-"( c #848A84",
-"_ c #7B7D7B",
-": c #7B797B",
-"< c #C6C3C6",
-"[ c #D6D3D6",
-"} c #FFFBFF",
-"| c #CECFCE",
-"1 c #FFFFFF",
-"2 c #737573",
-"3 c #F7F3F7",
-"4 c #CECBCE",
-"5 c #737173",
-"6 c #C6C7C6",
-"7 c #6B6D6B",
-"8 c #B5B6B5",
-"9 c #6B696B",
-"0 c #636563",
-"a c #636163",
-"b c #5A5D5A",
-"c c #5A595A",
-"d c #525552",
-"e c #525152",
-"f c #4A4D4A",
-"g c #C6CBC6",
-".+@#$$$%%%%&&&**==---;-%>.",
-".+@#$$$%%%%&&&**==---;-%,.",
-"')$$$%%%%&&&&**==--;;!!~~>",
-"{$)######))))$$$%%&&**=!]&",
-"^$)######))))$$$%%&&**=!]&",
-"%%#####))))$$$%%%&&**==-/(",
-"%%###)))))$$$%%%&&**==--/]",
-"%%###)))))$$$%%%&&**==--//",
-"&&))))))$$$%%%&&&**=-;;;_/",
-"&&)%&%$$$%%%%&&***=-~]~!:_",
-"&&)%&%$$$%%%%&&***=-~]~!:_",
-"**$=<-&%%%%&&&**==-~/[_~:_",
-"**&;}<-*&&&&***==-!/|1:/2:",
-"**&;}<-*&&&&***==-!/|1:/2:",
-"==&!31<;=****===-!/411:_5:",
-"-=*!311@!-====--!/6111:_52",
-"-=*!311@!-====--!/6111:_52",
-"--*!3111@~;=--;!/<1111::75",
-";;*;)1111{];;;~/@111185:95",
-";;*;)1111{];;;~/@111185:97",
-";;*=!)11118]~~_{1111852:97",
-";;*=!)11118]~~_{1111852:97",
-"!!*=;~)11118_:81111852:207",
-"~~==-;])1111)#1111872222a9",
-"~~==-;])1111)#1111872222a9",
-"~~=--;!/#111111118722255a0",
-"]]--;;!]_#11111187522557b0",
-"]]--;;!]_#11111187522557b0",
-"//;;;!!~/2#1111#95255779ba",
-"//;!!~~]]_5#11#975557799cb",
-"//;!!~~]]_5#11#975557799ca",
-"__!~~]]//_27009755779900db",
-"::~]]//__:2257777799000adb",
-"::~]]//__:2257777799000adb",
-":2]//__::225557799000aabeb",
-";52__::225557799000aaabde_",
-";52__::225557799000aaabde_",
-"[2779900aaabbcccdddeeeefeg",
-".>;200aaabbcccdddeeeefc:|.",
-".>;200aaabbcccdddeeeefc2|."};
-
-static char * sbgripdown_xpm[] = {
-"26 34 39 1",
-" c None",
-". c #949294",
-"+ c #9C9E9C",
-"@ c #9C9A9C",
-"# c #949694",
-"$ c #8C8E8C",
-"% c #8C8A8C",
-"& c #848684",
-"* c #848284",
-"= c #7B7D7B",
-"- c #7B797B",
-"; c #6B696B",
-"> c #636563",
-", c #737573",
-"' c #636163",
-") c #737173",
-"! c #5A5D5A",
-"~ c #6B6D6B",
-"{ c #5A595A",
-"] c #B5B6B5",
-"^ c #BDBEBD",
-"/ c #ADAEAD",
-"( c #BDBABD",
-"_ c #525552",
-": c #313031",
-"< c #525152",
-"[ c #ADAAAD",
-"} c #BDBAB5",
-"| c #4A4D4A",
-"1 c #4A494A",
-"2 c #C6C3C6",
-"3 c #C6CBC6",
-"4 c #E7E7E7",
-"5 c #DEDFDE",
-"6 c #E7E3E7",
-"7 c #DEE3DE",
-"8 c #CECBCE",
-"9 c #8C928C",
-"0 c #CECFCE",
-"..+++@@@###...$$%&&**==-;>",
-"$.++@@@@##...$$%%&**==-->>",
-"$$+@@@@###..$$%%&&*==--,>>",
-"$$@@@@###..$$%%&&**==-,,>'",
-"%%@@@###..$$$%&&**==--,,''",
-"%%@@###..$$$%&&**==--,,)''",
-"%%@###...$$%%&&*==--,,))'!",
-"&&###...$$%%&&**==--,)))!!",
-"&&##...$$%%&&**==--,,))~!!",
-"&&#...$$%%&&**==--,,))~~!{",
-"**...$$%%&&**==--,,))~~;!{",
-"**..$$%%&&**===--,)))~~;{{",
-"**.$$%%&]^&===//,,))~~;;{{",
-"==$$%%&&]^*==-((,))~~;;>{_",
-"==$%%&&***::--,,::~~;;;>__",
-"==%%&&&**=::-,,)::~~;;>>__",
-"--%&&&**==--,,)))~~;;>>>__",
-"--&&&**==--,,)))~~;;>>>'_<",
-",-&&**==]^-,))[[~;;>>>''<<",
-",,&**==-]^-)))}};;>>>'''<<",
-",,**==--,,::)~~;::>>'''!<<",
-"))*==--,,)::~~;;::>'''!!<|",
-"))==--,,)))~~;;;>>'''!!!||",
-"))=--,,)))~~;;;>>'''!!!{||",
-"~~--,,)))~~;;;>>'''!!!{{||",
-"~~-,,)))~~;;>>>'''!!!{{{|1",
-";;,,)))~~;;>>>'''!!!{{{_1<",
-"~;,)))~~;;>>>'''!!!{{{__1'",
-"%>~))~~;;>>>'''!!!{{{__|1$",
-"2>>~~~;;>>>''!!!{{{{__<113",
-"4%'';;;>>>''!!!{{{{__<11%4",
-"45-!!'>>>''!!!{{{{_<|11)64",
-"447+!{{___<<<||||1111|+444",
-"444489~__<<<||||111>$04444"};
-
-static char * sbgripup_xpm[] = {
-"26 34 38 1",
-" c None",
-". c #E7E7E7",
-"+ c #D6DBD6",
-"@ c #C6C7C6",
-"# c #B5B6B5",
-"$ c #ADAEAD",
-"% c #ADAAAD",
-"& c #A5A6A5",
-"* c #A5A2A5",
-"= c #BDBEBD",
-"- c #DEDFDE",
-"; c #C6CBC6",
-"> c #9C9E9C",
-", c #E7E3E7",
-"' c #BDBABD",
-") c #B5B2B5",
-"! c #9C9A9C",
-"~ c #DEE3DE",
-"{ c #949694",
-"] c #D6D7D6",
-"^ c #949294",
-"/ c #DEDBDE",
-"( c #8C8E8C",
-"_ c #8C8A8C",
-": c #848684",
-"< c #D6D3CE",
-"[ c #CECBCE",
-"} c #D6D3D6",
-"| c #848284",
-"1 c #313031",
-"2 c #7B7D7B",
-"3 c #CECFCE",
-"4 c #CECBC6",
-"5 c #7B797B",
-"6 c #737573",
-"7 c #737173",
-"8 c #6B6D6B",
-"9 c #6B696B",
-"....+@#$$%%%%&&&***$=-....",
-"...;$$$$$%%%&&&&**>>>>@...",
-".,'$$)#'#####)))$$$%*!!$~.",
-".=$)#'''####))))$$$%%*!{'.",
-"]$$''''#####)))$$$%%%&*{^/",
-"=$#'''#####)))$$$$%%&&&!^#",
-"$$'''#####))))$$$%%%&&*>(!",
-"$$''#####))))$$$%%%&&&*>(^",
-"$$######))))$$$$%%&&&**>(_",
-"%$#####))))$$$$%%%&&***>__",
-"%$####))))$$$$%%%&&&**>>__",
-"%%###)))))$$$%%%&&&**>>>_:",
-"%%##))))<])$$%[[&&***>>!::",
-"%%#)))))<]$$%%}<&&**>>!!:|",
-"&%)))))$$$11%%&&11*>>>!!:|",
-"&&))))$$$$11%&&&11*>>!!{||",
-"&&)))$$$$$%%%&&&**>>!!!{|2",
-"&&))$$$$$%%%&&&**>>>!!{{|2",
-"*&)$$$$$3]%&&&4@*>>!!{{{22",
-"**$$$$$%3]%&&&<<>>!!!{{^25",
-"**$$$$%%%%11&**>11!!{{^^25",
-"**$$$%%%%&11***>11!!{{^^55",
-"**$$%%%%&&&***>>!!!{{^^(55",
-">>$%%%%&&&***>>>!!{{^^((56",
-">>%%%%&&&&***>>!!!{{^^((66",
-">>%%%&&&&***>>!!!{{^^((_67",
-"!>%%&&&&***>>>!!{{{^^(__67",
-"!!%&&&&***>>>!!!{{^^((_:77",
-"!!&&&&***>>>!!!{{^^((__:77",
-"!!&&&****>>!!!{{^^^(__::78",
-"{!&&****>>>!!{{{^^((_::|88",
-"{{&****>>>!!!{{^^((__:||88",
-"{{****>>>!!!{{^^^(__::|289",
-"{{***>>>!!!{{{^^((_::||289"};
-
-static char * sbgripmiddle_xpm[] = {
-"26 2 12 1",
-" c None",
-". c #949294",
-"+ c #A5A2A5",
-"@ c #9C9E9C",
-"# c #9C9A9C",
-"$ c #949694",
-"% c #8C8E8C",
-"& c #8C8A8C",
-"* c #848684",
-"= c #848284",
-"- c #7B7D7B",
-"; c #6B696B",
-"..++@@@###$$$..%%&&*==--;;",
-"..++@@@###$$$..%%&&*==--;;"};
-
-
-static char * listviewhighmiddle_xpm[] = {
-"8 46 197 2",
-" c None",
-". c #66759E",
-"+ c #6C789D",
-"@ c #6A789E",
-"# c #6B789E",
-"$ c #6A779D",
-"% c #6C789C",
-"& c #6F7D9B",
-"* c #6F7D9A",
-"= c #9DB6EE",
-"- c #9DB6ED",
-"; c #9CB6ED",
-"> c #A1B6EF",
-", c #A2B6F0",
-"' c #93AAE9",
-") c #95ABEA",
-"! c #94ABEA",
-"~ c #94A9E8",
-"{ c #8BA8EA",
-"] c #8BA7EA",
-"^ c #8AA7EA",
-"/ c #8EAAE8",
-"( c #8FAAE8",
-"_ c #88A2E7",
-": c #8CA3E8",
-"< c #8BA3E7",
-"[ c #8BA3E8",
-"} c #8BA2E7",
-"| c #8CA2E7",
-"1 c #8DA2E7",
-"2 c #87A1E8",
-"3 c #87A1E9",
-"4 c #86A0E8",
-"5 c #86A1E7",
-"6 c #87A2E7",
-"7 c #859EE9",
-"8 c #849DE9",
-"9 c #869EE9",
-"0 c #869FE9",
-"a c #7C9BEA",
-"b c #7C9CEA",
-"c c #7B9CEA",
-"d c #7C9BE9",
-"e c #7E9CE9",
-"f c #7B9AEA",
-"g c #7C99E9",
-"h c #7C9AEA",
-"i c #7B9AE8",
-"j c #7A9AEA",
-"k c #7996E1",
-"l c #7C96E4",
-"m c #7B96E3",
-"n c #7B95E3",
-"o c #7E95E5",
-"p c #7E95E6",
-"q c #7292E1",
-"r c #7490DF",
-"s c #7591E0",
-"t c #7590DF",
-"u c #7392E1",
-"v c #6D8CDE",
-"w c #6F8EDD",
-"x c #6E8DDD",
-"y c #6E8DDE",
-"z c #6F8EDE",
-"A c #6E8EDE",
-"B c #718EDD",
-"C c #728EDD",
-"D c #6B89E0",
-"E c #6C89DF",
-"F c #6D89E0",
-"G c #6D89DF",
-"H c #6C88DF",
-"I c #6D88DF",
-"J c #6D86DD",
-"K c #6086E0",
-"L c #6686E0",
-"M c #6586E0",
-"N c #6486E0",
-"O c #6485E0",
-"P c #6786DF",
-"Q c #5F85E0",
-"R c #6583DE",
-"S c #6683DE",
-"T c #6682DD",
-"U c #6086DF",
-"V c #5F86E0",
-"W c #567ED7",
-"X c #567ED8",
-"Y c #557DD7",
-"Z c #5A7FD8",
-"` c #6281DA",
-" . c #5379D9",
-".. c #5278D9",
-"+. c #547BD8",
-"@. c #4C73D7",
-"#. c #4B72D2",
-"$. c #4C73D4",
-"%. c #4C73D3",
-"&. c #4B72D4",
-"*. c #4F75D3",
-"=. c #5074D2",
-"-. c #4971D0",
-";. c #4871D0",
-">. c #335ECF",
-",. c #325ECB",
-"'. c #335ECD",
-"). c #335ECE",
-"!. c #325DCD",
-"~. c #2E59C9",
-"{. c #3059C9",
-"]. c #2F59C9",
-"^. c #2F59C8",
-"/. c #2B59CA",
-"(. c #3355C6",
-"_. c #3354C5",
-":. c #3156C7",
-"<. c #3056C7",
-"[. c #3355C7",
-"}. c #3355C5",
-"|. c #254EBF",
-"1. c #1F51C1",
-"2. c #234FC0",
-"3. c #234FBF",
-"4. c #2350C0",
-"5. c #1E50BE",
-"6. c #1D50C0",
-"7. c #264DBE",
-"8. c #264CBD",
-"9. c #254DBE",
-"0. c #244EBF",
-"a. c #254DBF",
-"b. c #234CBF",
-"c. c #244CC0",
-"d. c #244BC0",
-"e. c #234BC0",
-"f. c #234BBF",
-"g. c #234CBE",
-"h. c #2049B7",
-"i. c #2A49B5",
-"j. c #2749B5",
-"k. c #2749B6",
-"l. c #2D49B4",
-"m. c #2649B6",
-"n. c #2946B5",
-"o. c #2A48B6",
-"p. c #2947B5",
-"q. c #2946B6",
-"r. c #2848B6",
-"s. c #2549B5",
-"t. c #2648B6",
-"u. c #2744B5",
-"v. c #2744B4",
-"w. c #2744AF",
-"x. c #2543B4",
-"y. c #2543B2",
-"z. c #2442B2",
-"A. c #2442B3",
-"B. c #2442B5",
-"C. c #2543B3",
-"D. c #1F40B1",
-"E. c #1E40B1",
-"F. c #243EAE",
-"G. c #273BAC",
-"H. c #263DAC",
-"I. c #253CAB",
-"J. c #273CAB",
-"K. c #273CAC",
-"L. c #263BAA",
-"M. c #253CAE",
-"N. c #263BA6",
-"O. c #253BA5",
-"P. c #253AA5",
-"Q. c #253BA6",
-"R. c #253CA7",
-"S. c #263AA6",
-"T. c #243CA6",
-"U. c #253CA5",
-"V. c #273BA8",
-"W. c #2F4DA4",
-"X. c #2F4DA3",
-"Y. c #1B2F85",
-"Z. c #B5B5B6",
-"`. c #B5B5B5",
-" + c #B5B6B6",
-".+ c #B5B4B6",
-"++ c #C2C3C5",
-"@+ c #C0C3C3",
-"#+ c #C1C3C4",
-"$+ c #E3E3E3",
-"%+ c #E3E3E4",
-"&+ c #E4E3E4",
-"*+ c #E2E3E4",
-"=+ c #ECEEEB",
-"-+ c #EBEDEA",
-";+ c #EEF0ED",
-">+ c #EFF0EE",
-". + @ @ # # $ % ",
-"& & * & & & & & ",
-"= = - = = ; > , ",
-"' ) ! ! ! ) ' ~ ",
-"{ ] { { { ^ / ( ",
-"_ : < [ : } | 1 ",
-"2 2 2 3 2 4 5 6 ",
-"7 7 7 7 7 8 9 0 ",
-"a b a a a c d e ",
-"f g h h h h i j ",
-"k l m m m n o p ",
-"q q q q q q q q ",
-"r r s s s t q u ",
-"v w x y z A B C ",
-"D E F F G F H I ",
-"J K L M N O P Q ",
-"R R S S S T U V ",
-"W W X X X Y Z ` ",
-" . . . . ...+.W ",
-" . . . . ..... .",
-"@.#.$.$.%.&.*.=.",
-"-.-.;.-.-.-.-.-.",
-">.,.'.).).!.!.>.",
-"~.{.].^.].^././.",
-"(.(.(.(.(._.:.<.",
-"(.(.[.[.[.[.(.}.",
-"|.1.2.3.3.4.5.6.",
-"7.7.7.7.7.8.9.0.",
-"a.b.c.d.c.e.f.g.",
-"h.i.j.k.j.k.l.m.",
-"n.o.p.q.r.p.s.t.",
-"u.u.v.u.u.u.u.u.",
-"w.x.y.z.A.y.B.C.",
-"D.D.E.D.D.D.D.D.",
-"D.D.E.D.D.D.D.D.",
-"F.G.H.I.J.K.L.M.",
-"N.N.O.N.N.P.Q.R.",
-"N.N.S.N.N.N.N.N.",
-"T.N.T.T.T.U.N.V.",
-"W.W.X.W.W.W.W.W.",
-"W.W.W.W.W.W.W.W.",
-"Y.Y.Y.Y.Y.Y.Y.Y.",
-"Z.`. + +.+Z.`.`.",
-"++@+#+#+#+#+@+@+",
-"$+%+&+&+*+%+%+%+",
-"=+-+;+-+-+>+-+-+"};
-
-
-
-static char * listviewhighcornerleft_xpm[] = {
-"100 46 1475 2",
-" c None",
-". c #FBFBFC",
-"+ c #E8EAE7",
-"@ c #758DC3",
-"# c #42599E",
-"$ c #28418A",
-"% c #19418F",
-"& c #3F5695",
-"* c #415896",
-"= c #435A98",
-"- c #445C99",
-"; c #465E9B",
-"> c #48609B",
-", c #49629C",
-"' c #4A639D",
-") c #49639D",
-"! c #4A629D",
-"~ c #4B639D",
-"{ c #4B649D",
-"] c #4C659D",
-"^ c #4D669D",
-"/ c #4E689D",
-"( c #506A9D",
-"_ c #516A9D",
-": c #536B9C",
-"< c #546C9C",
-"[ c #566D9B",
-"} c #576D9B",
-"| c #586E9C",
-"1 c #5B6F9D",
-"2 c #61739D",
-"3 c #63749E",
-"4 c #64749E",
-"5 c #68769E",
-"6 c #6A779E",
-"7 c #6B789E",
-"8 c #66759E",
-"9 c #6C789D",
-"0 c #EEF0ED",
-"a c #D0D3DC",
-"b c #3E51A3",
-"c c #28428B",
-"d c #29428C",
-"e c #425996",
-"f c #455C99",
-"g c #485F9C",
-"h c #49619E",
-"i c #4A63A0",
-"j c #4B64A1",
-"k c #4B65A1",
-"l c #4C66A2",
-"m c #4D67A2",
-"n c #4F69A1",
-"o c #516AA1",
-"p c #536CA0",
-"q c #556DA1",
-"r c #576EA0",
-"s c #586F9F",
-"t c #586E9F",
-"u c #596F9E",
-"v c #5A6F9E",
-"w c #5C709E",
-"x c #5E719E",
-"y c #5F729F",
-"z c #62739F",
-"A c #63739E",
-"B c #64749D",
-"C c #65749E",
-"D c #69769D",
-"E c #6C799E",
-"F c #6D799F",
-"G c #707D9F",
-"H c #717F9E",
-"I c #6E7AA1",
-"J c #6C789E",
-"K c #6F7C9C",
-"L c #6F7D9B",
-"M c #2A4AA0",
-"N c #4971D0",
-"O c #4C72D8",
-"P c #5472C0",
-"Q c #5573BF",
-"R c #5774BF",
-"S c #5875BF",
-"T c #5976C1",
-"U c #5A76C1",
-"V c #5C78C2",
-"W c #5E7AC2",
-"X c #607CC3",
-"Y c #627EC3",
-"Z c #637FC4",
-"` c #6581C5",
-" . c #6682C6",
-".. c #6783C7",
-"+. c #6984C8",
-"@. c #6B85C9",
-"#. c #6D87CA",
-"$. c #6F89CB",
-"%. c #718CCD",
-"&. c #748ECF",
-"*. c #7690D0",
-"=. c #7992D2",
-"-. c #7A93D3",
-";. c #7C95D5",
-">. c #7F98D7",
-",. c #8099D8",
-"'. c #859CDB",
-"). c #8AA0DD",
-"!. c #8DA3DF",
-"~. c #8FA5E0",
-"{. c #90A5E0",
-"]. c #91A6E1",
-"^. c #91A5E1",
-"/. c #90A4E0",
-"(. c #8EA3DE",
-"_. c #92A6E2",
-":. c #8FA4DF",
-"<. c #90A5DE",
-"[. c #90A5DC",
-"}. c #90A6DB",
-"|. c #91A6E0",
-"1. c #93A7E2",
-"2. c #95AAE6",
-"3. c #99AEEA",
-"4. c #9AB2EA",
-"5. c #99B1E9",
-"6. c #99B1E7",
-"7. c #98AFE6",
-"8. c #93A8E2",
-"9. c #97ACE7",
-"0. c #9AB3EB",
-"a. c #9DB5ED",
-"b. c #9DB6EE",
-"c. c #375095",
-"d. c #4056AD",
-"e. c #506DCD",
-"f. c #4360CC",
-"g. c #345ED6",
-"h. c #335ECF",
-"i. c #355ED6",
-"j. c #355FD6",
-"k. c #365FD6",
-"l. c #355FD0",
-"m. c #3760D5",
-"n. c #3A63D4",
-"o. c #3C63D1",
-"p. c #3B63CD",
-"q. c #3B63C9",
-"r. c #3B62C9",
-"s. c #3D63C8",
-"t. c #4065C5",
-"u. c #4567C5",
-"v. c #496BC5",
-"w. c #4F70C7",
-"x. c #5273C8",
-"y. c #5475CA",
-"z. c #5777CB",
-"A. c #5879CD",
-"B. c #5A7BCE",
-"C. c #5D7DCF",
-"D. c #5F7ECF",
-"E. c #617FD0",
-"F. c #6381D1",
-"G. c #6583D2",
-"H. c #6785D2",
-"I. c #6886D3",
-"J. c #6A88D4",
-"K. c #6C89D5",
-"L. c #6E8BD6",
-"M. c #708CD7",
-"N. c #718DD8",
-"O. c #738EDA",
-"P. c #748FDB",
-"Q. c #7691DC",
-"R. c #7893DD",
-"S. c #7994DD",
-"T. c #7A96DE",
-"U. c #7B97DF",
-"V. c #7C98E0",
-"W. c #7E9AE2",
-"X. c #7F9BE3",
-"Y. c #829DE4",
-"Z. c #849FE5",
-"`. c #87A0E6",
-" + c #88A1E7",
-".+ c #89A2E6",
-"++ c #8CA3E7",
-"@+ c #8EA5E9",
-"#+ c #8EA6E9",
-"$+ c #8FA7E9",
-"%+ c #8FA8E8",
-"&+ c #8FA9E8",
-"*+ c #91A9E8",
-"=+ c #90A7E8",
-"-+ c #8FA8EA",
-";+ c #90AAEA",
-">+ c #93ABEA",
-",+ c #95ABEA",
-"'+ c #93ABE9",
-")+ c #94ABEA",
-"!+ c #90A9EA",
-"~+ c #93AAE9",
-"{+ c #273E7E",
-"]+ c #345ED5",
-"^+ c #3D60CE",
-"/+ c #3D60CF",
-"(+ c #345ECF",
-"_+ c #335ED0",
-":+ c #355FD3",
-"<+ c #3A60CE",
-"[+ c #3A5FCB",
-"}+ c #385FC9",
-"|+ c #3B60C8",
-"1+ c #3C63CB",
-"2+ c #3E64CB",
-"3+ c #4166CA",
-"4+ c #4568C9",
-"5+ c #4A6CC7",
-"6+ c #4F71C8",
-"7+ c #5172CA",
-"8+ c #5475CE",
-"9+ c #5678D3",
-"0+ c #597CD6",
-"a+ c #5C7ED7",
-"b+ c #5E7FD8",
-"c+ c #6181D9",
-"d+ c #6383DA",
-"e+ c #6585DA",
-"f+ c #6786DB",
-"g+ c #6988DC",
-"h+ c #6B8ADD",
-"i+ c #6D8BDE",
-"j+ c #6F8DDE",
-"k+ c #718EDF",
-"l+ c #728FE0",
-"m+ c #7390E1",
-"n+ c #7390E2",
-"o+ c #7491E3",
-"p+ c #7592E4",
-"q+ c #7693E4",
-"r+ c #7794E5",
-"s+ c #7894E5",
-"t+ c #7995E6",
-"u+ c #7B96E6",
-"v+ c #7C97E7",
-"w+ c #7D9AE8",
-"x+ c #7F9CE9",
-"y+ c #829DE9",
-"z+ c #849EE9",
-"A+ c #859EE9",
-"B+ c #87A0E7",
-"C+ c #8AA2E7",
-"D+ c #8BA3E8",
-"E+ c #89A2E7",
-"F+ c #8CA6EA",
-"G+ c #8BA6EA",
-"H+ c #8BA7EA",
-"I+ c #8CA3E8",
-"J+ c #8BA8EA",
-"K+ c #8CA7EA",
-"L+ c #8CA8EA",
-"M+ c #4659C7",
-"N+ c #355ECF",
-"O+ c #3660CF",
-"P+ c #3860CE",
-"Q+ c #3961CD",
-"R+ c #3B61CB",
-"S+ c #3B61CA",
-"T+ c #3D62CA",
-"U+ c #3D63CA",
-"V+ c #4165CB",
-"W+ c #456ACB",
-"X+ c #4B6FCD",
-"Y+ c #5174CE",
-"Z+ c #5275D1",
-"`+ c #5477D4",
-" @ c #5678D9",
-".@ c #587ADB",
-"+@ c #597BDB",
-"@@ c #5B7DDC",
-"#@ c #5E7FDC",
-"$@ c #6081DD",
-"%@ c #6283DE",
-"&@ c #6484DF",
-"*@ c #6787E0",
-"=@ c #6989E1",
-"-@ c #6B8BE1",
-";@ c #6D8DE2",
-">@ c #6F8EE3",
-",@ c #718FE4",
-"'@ c #7290E4",
-")@ c #7491E5",
-"!@ c #7692E6",
-"~@ c #7793E5",
-"{@ c #7894E6",
-"]@ c #7895E7",
-"^@ c #7996E8",
-"/@ c #7A97E8",
-"(@ c #7B98E9",
-"_@ c #7D99E8",
-":@ c #7F9AE8",
-"<@ c #7F9BE9",
-"[@ c #7F9CEA",
-"}@ c #859EE8",
-"|@ c #859FE8",
-"1@ c #85A0E9",
-"2@ c #869FE9",
-"3@ c #86A1E7",
-"4@ c #86A0E9",
-"5@ c #87A1E7",
-"6@ c #88A2E7",
-"7@ c #87A1E9",
-"8@ c #5A6FCA",
-"9@ c #365FCF",
-"0@ c #345ED0",
-"a@ c #385FCC",
-"b@ c #385FCE",
-"c@ c #3A61CC",
-"d@ c #3B62CD",
-"e@ c #3E64CD",
-"f@ c #4167CF",
-"g@ c #4469CF",
-"h@ c #486CD1",
-"i@ c #4D71D2",
-"j@ c #5175D4",
-"k@ c #5376D6",
-"l@ c #5578DA",
-"m@ c #5679DC",
-"n@ c #587BDD",
-"o@ c #5A7DDE",
-"p@ c #5D80DE",
-"q@ c #5F82DF",
-"r@ c #6284DF",
-"s@ c #6585E0",
-"t@ c #6787E1",
-"u@ c #6988E2",
-"v@ c #6B8AE2",
-"w@ c #6D8CE3",
-"x@ c #6E8DE3",
-"y@ c #708EE4",
-"z@ c #718FE3",
-"A@ c #7391E4",
-"B@ c #7592E5",
-"C@ c #7895E5",
-"D@ c #7996E6",
-"E@ c #7A97E6",
-"F@ c #7B98E7",
-"G@ c #7A98E8",
-"H@ c #7B99E9",
-"I@ c #7E9AE9",
-"J@ c #7D9AE9",
-"K@ c #7E9AEA",
-"L@ c #809CE9",
-"M@ c #819DE8",
-"N@ c #7F9BEA",
-"O@ c #819DE9",
-"P@ c #819CE9",
-"Q@ c #839EE9",
-"R@ c #839EE8",
-"S@ c #839DEA",
-"T@ c #859FE9",
-"U@ c #87A0E8",
-"V@ c #86A0E8",
-"W@ c #87A1E8",
-"X@ c #3760CF",
-"Y@ c #3A61CE",
-"Z@ c #3A62CD",
-"`@ c #3F66CE",
-" # c #4368D0",
-".# c #466CD2",
-"+# c #496DD5",
-"@# c #4E72D6",
-"## c #5175D8",
-"$# c #5276DA",
-"%# c #5578DC",
-"&# c #577ADC",
-"*# c #597CDD",
-"=# c #5B7DDD",
-"-# c #5D7FDE",
-";# c #5E81DE",
-"># c #6183DF",
-",# c #6386DF",
-"'# c #6687E0",
-")# c #6888E0",
-"!# c #6A89E1",
-"~# c #6C8AE1",
-"{# c #6E8CE2",
-"]# c #6F8DE2",
-"^# c #7390E4",
-"/# c #7390E3",
-"(# c #7491E4",
-"_# c #7693E5",
-":# c #7895E6",
-"<# c #7896E6",
-"[# c #7997E7",
-"}# c #7B97E7",
-"|# c #7B98E8",
-"1# c #7C98E8",
-"2# c #7E9BE9",
-"3# c #809CEA",
-"4# c #819CEA",
-"5# c #839DE9",
-"6# c #365FD0",
-"7# c #3660D0",
-"8# c #3961CF",
-"9# c #3B63CF",
-"0# c #3D64D0",
-"a# c #4067D0",
-"b# c #4469D2",
-"c# c #466BD3",
-"d# c #496ED5",
-"e# c #4C71D6",
-"f# c #4E72D8",
-"g# c #5074D9",
-"h# c #5376DB",
-"i# c #5578DB",
-"j# c #587ADC",
-"k# c #5B7CDC",
-"l# c #5D7EDD",
-"m# c #5F80DD",
-"n# c #6081DE",
-"o# c #6383DE",
-"p# c #6686DF",
-"q# c #6887E0",
-"r# c #6988E0",
-"s# c #6B89E1",
-"t# c #6C8AE0",
-"u# c #6E8CE1",
-"v# c #708EE2",
-"w# c #718FE2",
-"x# c #7290E3",
-"y# c #7391E2",
-"z# c #7492E1",
-"A# c #7592E2",
-"B# c #7691E3",
-"C# c #7591E3",
-"D# c #7692E3",
-"E# c #7693E3",
-"F# c #7793E4",
-"G# c #7893E4",
-"H# c #7994E5",
-"I# c #7D97E8",
-"J# c #7E98E8",
-"K# c #7D98E8",
-"L# c #7D99E9",
-"M# c #7D9BEA",
-"N# c #7D9CEA",
-"O# c #7E99E8",
-"P# c #7D9AEA",
-"Q# c #7C9BEA",
-"R# c #7C9CEA",
-"S# c #355FCF",
-"T# c #3860D0",
-"U# c #3A62D0",
-"V# c #3C64D1",
-"W# c #4167D1",
-"X# c #4369D3",
-"Y# c #466BD4",
-"Z# c #486DD5",
-"`# c #4A6ED7",
-" $ c #4C70D8",
-".$ c #5478D9",
-"+$ c #577BDA",
-"@$ c #597DDB",
-"#$ c #5B7EDB",
-"$$ c #5D7FDC",
-"%$ c #6182DE",
-"&$ c #6284DE",
-"*$ c #6485DF",
-"=$ c #6586DF",
-"-$ c #6787DF",
-";$ c #6888DF",
-">$ c #6A8ADF",
-",$ c #6C8BE0",
-"'$ c #6D8CE0",
-")$ c #6E8DE1",
-"!$ c #6F8DE1",
-"~$ c #708EE1",
-"{$ c #718FE0",
-"]$ c #728FE1",
-"^$ c #7390E0",
-"/$ c #738FE0",
-"($ c #7490E1",
-"_$ c #7590E1",
-":$ c #7591E1",
-"<$ c #7592E1",
-"[$ c #7692E2",
-"}$ c #7794E2",
-"|$ c #7894E3",
-"1$ c #7996E3",
-"2$ c #7A96E5",
-"3$ c #7B98E6",
-"4$ c #7B9AE8",
-"5$ c #7C99E8",
-"6$ c #7C96E5",
-"7$ c #7D97E7",
-"8$ c #7C99E9",
-"9$ c #7B9AE9",
-"0$ c #7B9AEA",
-"a$ c #5B6DCF",
-"b$ c #305EC8",
-"c$ c #335ECE",
-"d$ c #305ECA",
-"e$ c #345FCF",
-"f$ c #3761D0",
-"g$ c #3A62D1",
-"h$ c #3C64D2",
-"i$ c #4066D3",
-"j$ c #466BD5",
-"k$ c #486ED6",
-"l$ c #4A6ED6",
-"m$ c #4D71D8",
-"n$ c #4F72D9",
-"o$ c #5073D9",
-"p$ c #4F72D8",
-"q$ c #5074D8",
-"r$ c #5276D9",
-"s$ c #587ADA",
-"t$ c #5B7CDB",
-"u$ c #5D7EDC",
-"v$ c #5F7FDD",
-"w$ c #6081DC",
-"x$ c #6182DD",
-"y$ c #6283DD",
-"z$ c #6484DE",
-"A$ c #6585DD",
-"B$ c #6787DE",
-"C$ c #6988DF",
-"D$ c #6A89DE",
-"E$ c #6C8ADF",
-"F$ c #6D8BDF",
-"G$ c #6E8CE0",
-"H$ c #6F8DE0",
-"I$ c #718EE0",
-"J$ c #728FDF",
-"K$ c #728FDE",
-"L$ c #7290E0",
-"M$ c #7190E0",
-"N$ c #7291E0",
-"O$ c #7191E0",
-"P$ c #7392E1",
-"Q$ c #7493E1",
-"R$ c #7594E1",
-"S$ c #7594E2",
-"T$ c #7694E2",
-"U$ c #7695E2",
-"V$ c #7A96E4",
-"W$ c #7895E2",
-"X$ c #7A96E2",
-"Y$ c #7A96E3",
-"Z$ c #7B96E3",
-"`$ c #7996E1",
-" % c #7C96E4",
-".% c #305EC9",
-"+% c #315ECC",
-"@% c #325ECE",
-"#% c #3760D0",
-"$% c #3962D1",
-"%% c #3E66D3",
-"&% c #4268D4",
-"*% c #446BD5",
-"=% c #476CD6",
-"-% c #496ED7",
-";% c #4B6FD7",
-">% c #4C70D7",
-",% c #4E71D7",
-"'% c #5074D7",
-")% c #5276D8",
-"!% c #5376D8",
-"~% c #5779DA",
-"{% c #597ADA",
-"]% c #5A7BDB",
-"^% c #5B7CDA",
-"/% c #5D7EDB",
-"(% c #5E7FDB",
-"_% c #6182DB",
-":% c #6384DC",
-"<% c #6586DD",
-"[% c #6686DC",
-"}% c #6887DD",
-"|% c #6988DD",
-"1% c #6A8ADE",
-"2% c #6B8BDE",
-"3% c #6C8CDE",
-"4% c #6E8DDF",
-"5% c #6E8CDF",
-"6% c #6D8DDF",
-"7% c #6C8BDF",
-"8% c #6F8DDF",
-"9% c #718FDF",
-"0% c #7290DF",
-"a% c #7391E0",
-"b% c #7491E0",
-"c% c #7292E1",
-"d% c #3959C5",
-"e% c #345BC5",
-"f% c #315EC8",
-"g% c #355BC5",
-"h% c #325EC8",
-"i% c #315ECB",
-"j% c #345DCC",
-"k% c #335ECD",
-"l% c #345ECD",
-"m% c #355FCE",
-"n% c #3862D0",
-"o% c #3E66D2",
-"p% c #456BD5",
-"q% c #476CD5",
-"r% c #4B6ED7",
-"s% c #4B6FD6",
-"t% c #4B6FD5",
-"u% c #4D71D6",
-"v% c #5073D7",
-"w% c #5174D7",
-"x% c #5275D8",
-"y% c #5577D8",
-"z% c #5678D8",
-"A% c #5779D9",
-"B% c #587AD8",
-"C% c #597CD9",
-"D% c #5B7DD9",
-"E% c #5D7FDA",
-"F% c #5F80DB",
-"G% c #6182DC",
-"H% c #6484DC",
-"I% c #6585DC",
-"J% c #6787DD",
-"K% c #6988DE",
-"L% c #6B8ADE",
-"M% c #6B8ADF",
-"N% c #6989DE",
-"O% c #6B89DE",
-"P% c #6E8BDF",
-"Q% c #708CDE",
-"R% c #708DDF",
-"S% c #708FDF",
-"T% c #728EDF",
-"U% c #6F8EDD",
-"V% c #728EDD",
-"W% c #7390DF",
-"X% c #7490DF",
-"Y% c #335DC8",
-"Z% c #3759C5",
-"`% c #3859C5",
-" & c #335EC8",
-".& c #325DCA",
-"+& c #345CCB",
-"@& c #335DCC",
-"#& c #345DCD",
-"$& c #355FCD",
-"%& c #3861D0",
-"&& c #3B64D1",
-"*& c #3E65D2",
-"=& c #4168D3",
-"-& c #456AD5",
-";& c #4B6ED5",
-">& c #4C6FD4",
-",& c #4D70D5",
-"'& c #4F72D6",
-")& c #5173D6",
-"!& c #5375D7",
-"~& c #5476D8",
-"{& c #5577D7",
-"]& c #5477D8",
-"^& c #5677D8",
-"/& c #5879D9",
-"(& c #597AD9",
-"_& c #5C7DDA",
-":& c #6080DC",
-"<& c #6080DB",
-"[& c #6181DC",
-"}& c #6282DC",
-"|& c #6383DD",
-"1& c #6484DD",
-"2& c #6686DE",
-"3& c #6685DE",
-"4& c #6786DE",
-"5& c #6687DE",
-"6& c #6887DE",
-"7& c #6987DE",
-"8& c #6788DF",
-"9& c #6785DF",
-"0& c #6B89DF",
-"a& c #6C89DF",
-"b& c #6F8DDD",
-"c& c #6D8CDE",
-"d& c #445BBB",
-"e& c #3759BE",
-"f& c #375AC6",
-"g& c #355CC8",
-"h& c #345CCA",
-"i& c #355ECC",
-"j& c #365FCD",
-"k& c #3761CE",
-"l& c #3A63D0",
-"m& c #3D65D1",
-"n& c #466AD4",
-"o& c #476BD4",
-"p& c #486CD3",
-"q& c #4A6ED4",
-"r& c #4B6ED4",
-"s& c #4E71D6",
-"t& c #4F71D5",
-"u& c #5072D6",
-"v& c #5274D7",
-"w& c #5273D7",
-"x& c #5274D6",
-"y& c #5476D7",
-"z& c #5779D8",
-"A& c #587AD9",
-"B& c #5A7CDA",
-"C& c #5C7DDB",
-"D& c #5D7EDA",
-"E& c #6081DA",
-"F& c #6181DB",
-"G& c #6283DC",
-"H& c #6483DD",
-"I& c #6483DE",
-"J& c #6585DE",
-"K& c #6786DF",
-"L& c #6886DE",
-"M& c #6887DF",
-"N& c #6987DF",
-"O& c #6A88DF",
-"P& c #6786E0",
-"Q& c #6A86DE",
-"R& c #6B89E0",
-"S& c #365BC8",
-"T& c #365CC8",
-"U& c #375DCA",
-"V& c #375FCB",
-"W& c #3860CD",
-"X& c #3C63D0",
-"Y& c #4167D2",
-"Z& c #4268D2",
-"`& c #4368D2",
-" * c #4367D2",
-".* c #4568D2",
-"+* c #466AD2",
-"@* c #496CD3",
-"#* c #4A6DD3",
-"$* c #4A6DD4",
-"%* c #4D70D4",
-"&* c #4F72D5",
-"** c #4C70D4",
-"=* c #4E72D5",
-"-* c #5173D5",
-";* c #5375D6",
-">* c #597BDA",
-",* c #5B7DDA",
-"'* c #5C7EDB",
-")* c #5D7FDB",
-"!* c #5E80DB",
-"~* c #5E81DA",
-"{* c #5F81DB",
-"]* c #5F82DB",
-"^* c #6384DD",
-"/* c #6384DE",
-"(* c #6585DF",
-"_* c #6486E0",
-":* c #6583DD",
-"<* c #6386E0",
-"[* c #6686E0",
-"}* c #6B86DD",
-"|* c #6D86DD",
-"1* c #6086E0",
-"2* c #5573CD",
-"3* c #3959C3",
-"4* c #3959C4",
-"5* c #3759C0",
-"6* c #375BC7",
-"7* c #365CC7",
-"8* c #395FCC",
-"9* c #3B62CE",
-"0* c #3E64D0",
-"a* c #4066D1",
-"b* c #4166D1",
-"c* c #4064CF",
-"d* c #4065CF",
-"e* c #4266D0",
-"f* c #4468D1",
-"g* c #4569D1",
-"h* c #476BD2",
-"i* c #466AD1",
-"j* c #476AD2",
-"k* c #456AD1",
-"l* c #496DD2",
-"m* c #4A6FD3",
-"n* c #496ED2",
-"o* c #4B70D4",
-"p* c #4D71D4",
-"q* c #4E72D4",
-"r* c #5073D4",
-"s* c #5174D5",
-"t* c #5175D5",
-"u* c #5276D6",
-"v* c #5377D6",
-"w* c #5478D7",
-"x* c #5579D7",
-"y* c #567AD8",
-"z* c #577BD9",
-"A* c #597CD8",
-"B* c #5A7DD9",
-"C* c #5A7ED9",
-"D* c #5B7FDA",
-"E* c #5C80DA",
-"F* c #5D80DA",
-"G* c #5E81DB",
-"H* c #5D80DB",
-"I* c #6082DC",
-"J* c #6183DD",
-"K* c #6183DE",
-"L* c #6082DB",
-"M* c #6282DE",
-"N* c #6682DE",
-"O* c #6583DE",
-"P* c #3759BF",
-"Q* c #375AC2",
-"R* c #375AC1",
-"S* c #375AC4",
-"T* c #395DCA",
-"U* c #3A5ECA",
-"V* c #3C60CC",
-"W* c #3D61CD",
-"X* c #3D61CC",
-"Y* c #3C61CD",
-"Z* c #3E62CD",
-"`* c #3F64CE",
-" = c #4266CF",
-".= c #4468D0",
-"+= c #4267CF",
-"@= c #4166CE",
-"#= c #4065CE",
-"$= c #4166CD",
-"%= c #4267CE",
-"&= c #456AD0",
-"*= c #4368CE",
-"== c #4468CF",
-"-= c #4569D0",
-";= c #486BD1",
-">= c #4B6FD3",
-",= c #4C70D3",
-"'= c #4F73D4",
-")= c #5275D5",
-"!= c #5477D6",
-"~= c #577BD7",
-"{= c #587CD8",
-"]= c #577CD8",
-"^= c #597DD9",
-"/= c #5A7DDA",
-"(= c #597DDA",
-"_= c #587CDA",
-":= c #5A7EDA",
-"<= c #567BD8",
-"[= c #557AD9",
-"}= c #567BD9",
-"|= c #577CD9",
-"1= c #587DD9",
-"2= c #587ED9",
-"3= c #577ED8",
-"4= c #587DD8",
-"5= c #587ED8",
-"6= c #567ED7",
-"7= c #526ABD",
-"8= c #3759C1",
-"9= c #385BC7",
-"0= c #395CC8",
-"a= c #3B5DC9",
-"b= c #3B5ECA",
-"c= c #3A5FCA",
-"d= c #3B60CC",
-"e= c #3C61CC",
-"f= c #3D62CD",
-"g= c #3E63CD",
-"h= c #3C61CB",
-"i= c #3C61CA",
-"j= c #3D62CB",
-"k= c #3F64CC",
-"l= c #4065CD",
-"m= c #4669D0",
-"n= c #476AD0",
-"o= c #496BD1",
-"p= c #4A6DD2",
-"q= c #4B6ED2",
-"r= c #4D71D3",
-"s= c #4E73D4",
-"t= c #4F74D4",
-"u= c #5075D5",
-"v= c #5276D5",
-"w= c #5377D7",
-"x= c #5278D7",
-"y= c #5277D6",
-"z= c #5378D7",
-"A= c #5379D8",
-"B= c #5379D9",
-"C= c #5278D8",
-"D= c #5178D7",
-"E= c #3355C0",
-"F= c #3556C1",
-"G= c #395AC6",
-"H= c #385AC7",
-"I= c #395BC7",
-"J= c #395EC9",
-"K= c #395FCA",
-"L= c #3B60CA",
-"M= c #3B60CB",
-"N= c #375DC7",
-"O= c #385EC8",
-"P= c #395FC9",
-"Q= c #3A60CA",
-"R= c #3D63CC",
-"S= c #4367CF",
-"T= c #476BD1",
-"U= c #4A6ED2",
-"V= c #4B6FD2",
-"W= c #4C6FD2",
-"X= c #4D70D1",
-"Y= c #4E71D2",
-"Z= c #4E72D2",
-"`= c #4E74D4",
-" - c #4E75D5",
-".- c #4E75D4",
-"+- c #4F75D3",
-"@- c #5075D2",
-"#- c #5075D3",
-"$- c #5177D7",
-"%- c #5178D8",
-"&- c #4F75D5",
-"*- c #5076D5",
-"=- c #4F76D6",
-"-- c #5279D9",
-";- c #3C52B1",
-">- c #3656C3",
-",- c #3757C5",
-"'- c #3758C6",
-")- c #3759C6",
-"!- c #375BC6",
-"~- c #385CC7",
-"{- c #385DC8",
-"]- c #365CC6",
-"^- c #355BC6",
-"/- c #355CC6",
-"(- c #365DC7",
-"_- c #375EC8",
-":- c #375CC6",
-"<- c #385EC6",
-"[- c #3A5FC7",
-"}- c #3C60C8",
-"|- c #3D61C9",
-"1- c #3E62CA",
-"2- c #4063CC",
-"3- c #4165CE",
-"4- c #4268D0",
-"5- c #4269D1",
-"6- c #436AD2",
-"7- c #446AD2",
-"8- c #456BD2",
-"9- c #496CD1",
-"0- c #4C6CD0",
-"a- c #4D6CCF",
-"b- c #4E6DD0",
-"c- c #4F6ECF",
-"d- c #4E6FCF",
-"e- c #4C70CF",
-"f- c #4A71D0",
-"g- c #4F6FCF",
-"h- c #4B71D0",
-"i- c #4A72D1",
-"j- c #4B73D4",
-"k- c #4F70D0",
-"l- c #4C73D3",
-"m- c #4C73D6",
-"n- c #4B72D2",
-"o- c #4B71D1",
-"p- c #4C73D7",
-"q- c #3354C0",
-"r- c #3152BE",
-"s- c #3052BE",
-"t- c #3051BF",
-"u- c #2E4FBF",
-"v- c #2E4FBE",
-"w- c #2E50BF",
-"x- c #2F50BF",
-"y- c #3156C4",
-"z- c #2F56C5",
-"A- c #2E57C5",
-"B- c #2F57C5",
-"C- c #3057C6",
-"D- c #3258C6",
-"E- c #3459C7",
-"F- c #365AC7",
-"G- c #385BC8",
-"H- c #3B5DCA",
-"I- c #3B5DCB",
-"J- c #3C5ECC",
-"K- c #3C60CD",
-"L- c #3C62CE",
-"M- c #3D65D0",
-"N- c #3D66D1",
-"O- c #4166D2",
-"P- c #4667D2",
-"Q- c #4A67D1",
-"R- c #4C68D0",
-"S- c #4C69CF",
-"T- c #4D6BCE",
-"U- c #4E6DCD",
-"V- c #4E6ECE",
-"W- c #4E6DCE",
-"X- c #4970D0",
-"Y- c #4770D0",
-"Z- c #4B6BCE",
-"`- c #4A6CCE",
-" ; c #496DCF",
-".; c #476FD0",
-"+; c #4870D0",
-"@; c #486DCF",
-"#; c #242F79",
-"$; c #2F41AC",
-"%; c #2040B8",
-"&; c #2041B8",
-"*; c #2243B3",
-"=; c #2243B8",
-"-; c #2343B8",
-";; c #2444B8",
-">; c #2445B8",
-",; c #2445B6",
-"'; c #2445B7",
-"); c #2444B9",
-"!; c #2949BE",
-"~; c #2649BF",
-"{; c #234BBF",
-"]; c #224CBF",
-"^; c #224AC0",
-"/; c #244CC0",
-"(; c #254DC0",
-"_; c #254DC1",
-":; c #264DC2",
-"<; c #274EC3",
-"[; c #274CC3",
-"}; c #274DC4",
-"|; c #254DC5",
-"1; c #214EC5",
-"2; c #204FC6",
-"3; c #1F50C8",
-"4; c #2151C9",
-"5; c #2B53C8",
-"6; c #3154C7",
-"7; c #3255C6",
-"8; c #2F57C7",
-"9; c #2C58C9",
-"0; c #2D59CA",
-"a; c #2D58C9",
-"b; c #2E5BCC",
-"c; c #325ECC",
-"d; c #325ECB",
-"e; c #1F40B1",
-"f; c #1F40B2",
-"g; c #1F40B3",
-"h; c #2A44BD",
-"i; c #2845BE",
-"j; c #2745BE",
-"k; c #2646BF",
-"l; c #2546BE",
-"m; c #2347BF",
-"n; c #2147BF",
-"o; c #2048C0",
-"p; c #1D48C0",
-"q; c #1C48C0",
-"r; c #1B47C0",
-"s; c #1C48BF",
-"t; c #1E49BE",
-"u; c #214ABD",
-"v; c #244CBD",
-"w; c #264DBE",
-"x; c #254EC0",
-"y; c #214FC2",
-"z; c #1B51C5",
-"A; c #1C51C7",
-"B; c #2250C8",
-"C; c #2A52C8",
-"D; c #3254C6",
-"E; c #3355C5",
-"F; c #3154C8",
-"G; c #3355C6",
-"H; c #2F57C8",
-"I; c #2E58C9",
-"J; c #2E59C9",
-"K; c #3059C9",
-"L; c #2040B6",
-"M; c #2743BB",
-"N; c #2844BC",
-"O; c #2743BD",
-"P; c #2844BE",
-"Q; c #2844BD",
-"R; c #2346BE",
-"S; c #2047BF",
-"T; c #1E48C0",
-"U; c #1D47C0",
-"V; c #1D49BF",
-"W; c #1F49BF",
-"X; c #204ABE",
-"Y; c #254DBF",
-"Z; c #234EC0",
-"`; c #2050C1",
-" > c #1C51C3",
-".> c #1F51C6",
-"+> c #2651C8",
-"@> c #2D53C7",
-"#> c #3155C6",
-"$> c #3155C7",
-"%> c #3355C7",
-"&> c #3254C7",
-"*> c #1E40B1",
-"=> c #2141B8",
-"-> c #2442B9",
-";> c #2744BB",
-">> c #2945BB",
-",> c #2A45BB",
-"'> c #2944BA",
-")> c #2745BB",
-"!> c #2545BC",
-"~> c #2246BD",
-"{> c #2047BE",
-"]> c #1F47BD",
-"^> c #1D48BE",
-"/> c #1E49C0",
-"(> c #1F4AC0",
-"_> c #214BBF",
-":> c #244CBE",
-"<> c #254DBE",
-"[> c #244DBE",
-"}> c #224FBF",
-"|> c #2051C1",
-"1> c #2151C3",
-"2> c #2252C5",
-"3> c #2151C1",
-"4> c #2851C6",
-"5> c #2A50C6",
-"6> c #2E54C6",
-"7> c #1F51C2",
-"8> c #1D52C5",
-"9> c #2651C9",
-"0> c #2950C7",
-"a> c #2D40A5",
-"b> c #2040B0",
-"c> c #1F40B0",
-"d> c #223CAE",
-"e> c #233CAE",
-"f> c #253BAC",
-"g> c #253BAD",
-"h> c #233CB0",
-"i> c #213EB2",
-"j> c #1F3FB4",
-"k> c #1E40B6",
-"l> c #1F3FB7",
-"m> c #1E3EB8",
-"n> c #1F3FB8",
-"o> c #2040B7",
-"p> c #2141B6",
-"q> c #2140B7",
-"r> c #2241B6",
-"s> c #2342B5",
-"t> c #2442B6",
-"u> c #2543B5",
-"v> c #2643B4",
-"w> c #2544B6",
-"x> c #2346B8",
-"y> c #2247B9",
-"z> c #2048BC",
-"A> c #1F48BF",
-"B> c #2049C0",
-"C> c #214AC0",
-"D> c #224BBF",
-"E> c #234CBE",
-"F> c #244DBF",
-"G> c #234CBF",
-"H> c #264DC0",
-"I> c #274EBF",
-"J> c #264DBF",
-"K> c #254EBF",
-"L> c #2050C0",
-"M> c #1F51C1",
-"N> c #1E42A4",
-"O> c #263BA6",
-"P> c #253BA7",
-"Q> c #253CA7",
-"R> c #1E41A5",
-"S> c #1F40AF",
-"T> c #273AAC",
-"U> c #1E40B0",
-"V> c #1F40B5",
-"W> c #1F40B6",
-"X> c #1F40B8",
-"Y> c #1E40B8",
-"Z> c #1F3EB8",
-"`> c #203FB7",
-" , c #2240B6",
-"., c #2341B7",
-"+, c #2345B9",
-"@, c #2147BB",
-"#, c #2148BA",
-"$, c #2049BB",
-"%, c #2049BD",
-"&, c #2049BF",
-"*, c #224BBE",
-"=, c #244DBD",
-"-, c #244CBF",
-";, c #182969",
-">, c #273BAD",
-",, c #2739AB",
-"', c #263AAC",
-"), c #243CAE",
-"!, c #233DAE",
-"~, c #213EAF",
-"{, c #1F3FB0",
-"], c #2040B4",
-"^, c #1F3FB6",
-"/, c #1E3EB7",
-"(, c #2240B7",
-"_, c #2341B6",
-":, c #2543B4",
-"<, c #2644B3",
-"[, c #2544B5",
-"}, c #2545B5",
-"|, c #2547B6",
-"1, c #2548B7",
-"2, c #2349BA",
-"3, c #1F49BE",
-"4, c #2149BD",
-"5, c #2049BE",
-"6, c #214BBE",
-"7, c #2249BE",
-"8, c #234CBD",
-"9, c #2149BE",
-"0, c #1E49BF",
-"a, c #253BA9",
-"b, c #253BAB",
-"c, c #263AAB",
-"d, c #213DAF",
-"e, c #203EAF",
-"f, c #1D40AF",
-"g, c #1D40B0",
-"h, c #1E40B4",
-"i, c #2241B7",
-"j, c #2643B6",
-"k, c #2744B5",
-"l, c #2643B5",
-"m, c #2346B6",
-"n, c #2147B7",
-"o, c #2644B6",
-"p, c #2247B7",
-"q, c #2248B8",
-"r, c #2647B7",
-"s, c #2549B7",
-"t, c #2645B7",
-"u, c #2148B8",
-"v, c #2847B6",
-"w, c #2549B6",
-"x, c #2849B6",
-"y, c #2049B7",
-"z, c #2A49B5",
-"A, c #243BA4",
-"B, c #253BA5",
-"C, c #253BA6",
-"D, c #263AA7",
-"E, c #263AA8",
-"F, c #2739AA",
-"G, c #243CAD",
-"H, c #223DAE",
-"I, c #1F3EAF",
-"J, c #1E3FB0",
-"K, c #1D40B1",
-"L, c #1E3FB1",
-"M, c #1F3FB3",
-"N, c #1F3FB5",
-"O, c #2140B6",
-"P, c #2140B8",
-"Q, c #2744B4",
-"R, c #2746B6",
-"S, c #2947B6",
-"T, c #2946B5",
-"U, c #2A48B6",
-"V, c #3551A8",
-"W, c #1F399C",
-"X, c #143D9F",
-"Y, c #263BA5",
-"Z, c #273BA8",
-"`, c #273BAA",
-" ' c #263AAD",
-".' c #233CAD",
-"+' c #213DAE",
-"@' c #203FB2",
-"#' c #2342B6",
-"$' c #2443B6",
-"%' c #2543B6",
-"&' c #2644B5",
-"*' c #133D9E",
-"=' c #263BA7",
-"-' c #263BA9",
-";' c #273BA9",
-">' c #263AAA",
-",' c #2539AB",
-"'' c #2639AB",
-")' c #253AAC",
-"!' c #243BAD",
-"~' c #223DAF",
-"{' c #203FB0",
-"]' c #2040B1",
-"^' c #2140B3",
-"/' c #2543B1",
-"(' c #2744AF",
-"_' c #1A3CA0",
-":' c #1D3BA2",
-"<' c #233BA4",
-"[' c #263AA5",
-"}' c #253AA5",
-"|' c #263AA6",
-"1' c #263BA4",
-"2' c #243BA5",
-"3' c #263BA8",
-"4' c #223EAF",
-"5' c #3B4CA5",
-"6' c #1D379A",
-"7' c #1E389C",
-"8' c #1E399F",
-"9' c #1F3BA2",
-"0' c #1F3BA3",
-"a' c #213BA4",
-"b' c #233AA3",
-"c' c #243AA3",
-"d' c #2539A4",
-"e' c #253AA6",
-"f' c #243BA7",
-"g' c #253CAA",
-"h' c #253CAC",
-"i' c #253CAD",
-"j' c #253CAE",
-"k' c #243DAE",
-"l' c #213FAF",
-"m' c #223FAF",
-"n' c #2040AF",
-"o' c #253D93",
-"p' c #1D3894",
-"q' c #1F379A",
-"r' c #1E389B",
-"s' c #1D399C",
-"t' c #1C3A9D",
-"u' c #1B3A9D",
-"v' c #183B9E",
-"w' c #163C9E",
-"x' c #153C9E",
-"y' c #163B9D",
-"z' c #173B9D",
-"A' c #193A9D",
-"B' c #1C3A9E",
-"C' c #1F3AA1",
-"D' c #223AA4",
-"E' c #253BA8",
-"F' c #273BA7",
-"G' c #263CAB",
-"H' c #263CAC",
-"I' c #243EAE",
-"J' c #273BAC",
-"K' c #2A3795",
-"L' c #1F389B",
-"M' c #1D389B",
-"N' c #1C399C",
-"O' c #1B399C",
-"P' c #1A3A9D",
-"Q' c #1D399B",
-"R' c #1B399B",
-"S' c #1A3A9C",
-"T' c #1B3A9F",
-"U' c #1D3AA0",
-"V' c #203BA2",
-"W' c #203BA3",
-"X' c #2639A6",
-"Y' c #1B3692",
-"Z' c #1C3794",
-"`' c #1D3796",
-" ) c #1E3898",
-".) c #1E389A",
-"+) c #1F399B",
-"@) c #1A399C",
-"#) c #193A9E",
-"$) c #1A3BA0",
-"%) c #1C3BA2",
-"&) c #1D3CA3",
-"*) c #203CA4",
-"=) c #223BA5",
-"-) c #3C4699",
-";) c #2B4595",
-">) c #1C3793",
-",) c #1D3895",
-"') c #1E3897",
-")) c #1F3998",
-"!) c #1F3999",
-"~) c #1F399A",
-"{) c #1E399C",
-"]) c #1C3B9E",
-"^) c #1D3BA0",
-"/) c #1E3CA2",
-"() c #223CA5",
-"_) c #243CA6",
-":) c #596FA9",
-"<) c #3B4894",
-"[) c #314993",
-"}) c #29499F",
-"|) c #28489E",
-"1) c #2B4BA1",
-"2) c #2C4BA1",
-"3) c #2D4CA2",
-"4) c #2E4CA3",
-"5) c #2F4CA4",
-"6) c #2E4CA4",
-"7) c #2F4DA3",
-"8) c #2F4DA4",
-"9) c #D3D5D2",
-"0) c #3B4794",
-"a) c #314791",
-"b) c #304892",
-"c) c #304893",
-"d) c #2F4995",
-"e) c #2F4997",
-"f) c #2D4A9A",
-"g) c #2A4A9D",
-"h) c #294A9F",
-"i) c #284AA0",
-"j) c #294AA0",
-"k) c #2B4AA1",
-"l) c #2D4CA3",
-"m) c #C9CAC9",
-"n) c #455D9B",
-"o) c #242F78",
-"p) c #1B2F85",
-"q) c #C6C3C8",
-"r) c #B5B2B6",
-"s) c #B5B7B4",
-"t) c #B5B7B3",
-"u) c #B5B2B5",
-"v) c #B5B3B4",
-"w) c #B5B5B4",
-"x) c #B5B6B3",
-"y) c #B5B4B4",
-"z) c #B5B3B5",
-"A) c #B5B4B5",
-"B) c #B5B5B5",
-"C) c #B5B5B3",
-"D) c #B5B5B6",
-"E) c #BAC3BE",
-"F) c #B9C3BD",
-"G) c #C1C3C4",
-"H) c #BFC3C2",
-"I) c #B9C3BE",
-"J) c #BBC3BF",
-"K) c #BDC3C1",
-"L) c #C0C3C3",
-"M) c #BEC3C1",
-"N) c #C2C3C5",
-"O) c #E6E3E8",
-"P) c #E0E2DF",
-"Q) c #E1E1E1",
-"R) c #E2E1E3",
-"S) c #E4E1E6",
-"T) c #E4E2E7",
-"U) c #E4E2E6",
-"V) c #E3E3E4",
-"W) c #E2E3E3",
-"X) c #E1E3E2",
-"Y) c #E3E3E3",
-"Z) c #E3E3E2",
-"`) c #EBEDEA",
-" ! c #EAECE9",
-".! c #E9EBE8",
-"+! c #ECEEEB",
-". . + @ # $ $ $ $ $ $ $ % $ $ $ $ $ % $ $ $ $ $ $ % $ $ $ $ $ % $ $ $ $ $ $ $ $ $ % $ $ & * = - ; > , , ' ) ! ! ~ { ] ^ / ( _ : < [ } | | 1 2 3 3 4 4 4 4 4 4 4 5 6 4 4 4 5 6 7 8 9 4 5 6 7 8 9 6 7 8 9 ",
-"0 a b % $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c d d d d $ $ $ $ $ c d e f g h i i i i j k l m n o p q r s t u v w x y z 4 A B C D 9 9 E 9 E F G H I F J K L L L L J K L L L L L L L L ",
-"@ % M N O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O P Q R S T U V W X Y Z ` ...+.@.#.$.%.&.*.=.-.;.>.,.'.).!.~.{.].^./.(._.:.<.[.}.|.1.2.3.4.5.6.7.8.9.0.a.b.b.b.b.b.b.",
-"c.$ d.O e.f.g.g.g.h.g.g.g.g.g.h.h.g.g.g.g.g.h.h.g.g.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z.A.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z.`. +.+++@+#+$+@+$+%+&+*+=+$+-+;+>+,+'+)+!+;+>+,+~+,+>+,+~+,+",
-"$ {+N N f.f.f.f.h.h.h.g.f.f.h.h.h.h.g.f.f.h.h.h.h.]+^+/+(+h._+:+<+[+}+|+1+2+3+4+5+6+7+8+9+0+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+w+x+y+z+A+B+.+C+D+E+D+F+G+H+C+I+F+G+J+K+L+H+F+G+J+K+L+H+J+H+J+H+",
-"{+{+N N M+M+h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.N+N+h.h.(+O+P+P+Q+R+S+T+U+V+W+X+Y+Z+`+ @.@+@@@#@$@%@&@*@=@-@;@>@,@'@)@!@~@{@]@^@/@(@_@:@<@[@[@y+}@|@1@A+1@2@3@ +2@4@2@5@C+D+6@D+7@5@C+D+6@I+C+D+6@I+",
-"{+{+8@N M+M+h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.9@9@0@N+a@b@c@d@e@f@g@h@i@j@k@l@m@n@o@p@q@r@s@t@u@v@w@x@y@z@A@B@q+r+C@D@E@F@G@H@_@I@J@K@<@L@M@N@O@P@Q@R@S@T@A+A+U@V@W@W@A+2@U@V@W@W@U@V@W@W@",
-"{+{+8@N f.M+h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.(+(+(+9@9@X@Y@Z@e@`@ #.#+#@###$#%#&#*#=#-#;#>#,#'#)#!#~#{#]#z@^#/#(#p+_#r+:#s+t+<#[#}#|#|#1#_@|#_@_@2#L@3#4#y+y+5#z+z+z+5#z+z+z+z+A+A+A+A+A+",
-"{+{+8@8@f.f.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.(+6#7#8#9#0#a#b#c#d#e#f#g#h#i#j#k#l#m#n#o#&@p#q#r#s#t#u#v#w#x#x#y#y#z#A#B#C#D#E#E#F#G#H#F#H#H#u+v+I#J#K#L#J@J@M#N#O#P#M#M#M#N#M#Q#Q#R#",
-"$ {+8@e.f.f.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.h.S#l.7#T#U#V#W#X#Y#Z#`# $f#g###.$+$@$#$$$$@%$&$*$=$-$;$>$,$'$)$!$~$~${$]$^$/$($($_$_$:$<$_$<$[$}$|$|$1$2$2$3$}#4$5$6$7$8$8$9$8$8$8$0$8$",
-"$ {+a$e.f.f.h.h.h.h.h.h.h.h.h.b$h.c$c$c$c$c$d$c$c$c$c$c$c$c$c$c$c$e$e$7#f$g$h$i$X#j$k$l$m$n$o$p$q$r$l@s$t$u$v$w$x$y$z$A$B$C$D$E$F$G$G$H$I$J$J$K$K$J$L$L$L$L$L$M$N$O$P$Q$R$S$T$U$1$V$T$W$X$Y$1$V$Y$Z$`$ %",
-"$ $ a$a$f.f.b$b$b$b$b$b$b$b$b$b$b$b$b$b$b$b$b$b$.%b$b$b$.%d$+%+%@%h.e$l.#%$%h$%%&%*%=%-%;%>%,%'%)%!% @ @~%{%]%^%/%(%w$_%:%<%[%}%|%D$1%2%3%4%5%4%4%6%5%5%4%4%4%5%7%5%8%9%L$0%a%a%a%P$b%P$P$z#z#z#P$c%c%c%",
-"$ $ 8@e.f.f.d%b$b$b$b$b$d%b$b$b$b$b$b$e%f%b$b$b$b$b$g%h%b$.%i%i%j%k%l%m%X@n%h$o%&%p%q%`#r%s%t%u%v%w%x%y% @z%A%B%C%D%E%F%G%:%H%I%[%J%}%K%|%D$K%D$D$L%M%M%M%M%M%D$N%O%i+P%j+Q%R%S%T%0%U%V%W%W%W%W%X%X%X%X%",
-"$ $ 8@8@f.f.d%d%b$b$b$b$d%d%b$b$b$h%Y%Z%Z%h%f%f%h%Y%`%`% &h%h%.&+&@&#&$&X@%&&&*&=&-&j$Z#+#;&>&,&'&)&)&!&~&{&]&^&/&(&^%_&(%:&<&[&}&|&1&A$A$2&3&4&4&5&B$6&7&B$7&8&9&6&7&0&a&a&i+i+i+b&a&a&j+U%c&U%j+U%c&U%",
-"$ $ 8@8@d&e&d%d%d%d%d%d%d%d%d%d%d%`%d%d%d%d%`%`%`%d%d%d%d%`%`%f&g&h&j%i&j&k&l&m&=&X#Y#n&o&p&q&r&>&s&t&t&u&v&w&x&y&{&z&A&B&C&D&(%(%F%F%E&F&}&}&|&G&|&H&1&I%I&A$1&}&z$z$J&K&L&M&N&O&0&P&Q&0&a&R&a&a&a&R&a&",
-"{+$ 8@8@e&e&d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%`%f&S&T&U&V&W&Y@X&Y&Z&`& *.*+*@*#*@*r&$*#*r&%*&***=*-*;*y&z%A%z&A&A&>*B&,*,*'*)*!*!*~*{*F&}&{*}&{*]*G%G%y$^*/*J&(*2&_*:*<*=$[*}*<*=$<*|*1*",
-"{+{+8@2*e&e&d%d%d%d%d%d%d%d%d%e&3*4*4*4*4*4*5*4*4*4*4*4*4*4*4*4*`%f&6*6*7*8*9*0*a*b*c*d*e*f*g*h*i*j*+*k*h*l*m*n*m*o*p*q*r*s*t*u*v*w*x*y*y*z*A*B*C*D*E*F*G*E*G*F*H*G*F*~*]*{*I*x$J*K*L*G%K*M*o#o#I&N*O*O*",
-"{+{+8@2*e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&P*e&e&e&e&e&e&P*P*e&e&e&P*P*5*Q*R*S*T*U*V*W*X*Y*Z*`*d* =.=+=@=#=$=%=g@&=*===-=i*;=l*>=,=q*'=s*)=k@!=x*~={=]=^=/=(=_=:=(=<=<=]=[=}=|=]=]=1=2=3=|=4=5=2=2=2=3=6=6=6=",
-"{+{+7=e.e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&e&P*P*8=9=0=a=b=U*c=d=e=f=e@#=g=h=i=i=j=k=k=l=%===m=n=o=p=q=,=r=s=t=u=v=v*w=x=x=y=z=z=A=z=A=B=C=B=D=C=B=x=B=B=B=B=B=B=B=B=B=B=B=B=B=B=",
-"{+{+7=7=e&e&e&e&E=E=e&e&e&e&E=E=E=e&e&e&e&E=E=E=e&e&e&e&E=E=e&e&e&e&E=E=E=F=d%G=G=H=I=J=K=L=M=R+}+N=O=P=Q=j=i=h=R=e@@=S=-=T=h@l*U=V=W=X=Y=Z=`= - - -.-+-@- -#-$-%-$-&-*-$-=-%-----C=$-%---------B=B=B=B=",
-"{+{+7=7=;-;-E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=E=>-,-'-)-!-6*~-{-{-]-^-/-/-(-_-:-N=<-[-}-|-1-2-3- =4-5-6-7-8-9-0-0-a-b-c-d-e-f-g-h-h-i-j-k-h-h-i-j-l-m-n-o-i-j-l-m-n-j-l-p-n-",
-"{+{+7=7=;-;-E=E=E=E=E=E=E=E=q-r-s-t-t-u-u-v-v-v-u-w-x-u-u-u-u-u-u-u-u-v-v-u-u-u-u-u-v-v-u-u-u-u-v-v-u-y-z-A-B-C-D-E-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-U-V-W-V-e-X-Y-Z-`- ;.;Y-N N +;@;.;Y-N N N N N N N ",
-"#;#;d&d&$;$;%;%;%;%;%;%;%;%;&;*;=;-;-;-;;;>;,;>;>;>;;;>;>;>;>;>;>;>;>;>;';);>;>;>;>;>;';>;>;>;>;>;';);!;~;{;];^;/;(;_;_;:;<;[;};};|;1;2;3;4;5;6;7;8;9;9;0;a;0;0;b;h.a;0;0;b;h.c;h.d;0;b;h.c;h.d;h.c;h.d;",
-"#;#;;-;-$;$;e;e;e;e;e;e;e;e;e;e;e;f;f;f;f;e;e;e;f;f;f;f;f;f;f;f;f;f;f;f;g;%;f;f;f;f;f;g;f;f;f;f;f;g;%;h;i;j;k;l;m;n;o;p;q;r;r;s;t;u;v;w;x;y;z;A;B;C;6;D;E;F;G;G;H;I;F;G;G;H;I;J;J;K;G;H;I;J;J;K;I;J;J;K;",
-"#;#;;-;-$;$;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;L;e;e;e;e;e;e;e;e;e;e;e;e;L;M;N;O;P;Q;i;i;k;R;S;T;U;q;q;V;W;X;{;Y;Z;`; >.>+>@>#>+>$>6;#>#>+>%>&>G;G;G;G;G;&>G;G;G;G;G;G;G;G;G;",
-"#;#;d.;-$;$;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;*>e;e;e;e;e;e;e;e;e;e;e;e;*>=>->;>>>,>'>'>)>!>~>{>]>^>^>V;V;/>(>_>:><>[>}>|>1>2>3>2>4>5>6>7>8>9>0>G;G;G;G;9>0>G;G;G;G;G;G;G;G;",
-"#;#;d.d.a>a>e;e;e;e;e;e;e;e;e;e;b>b>c>c>c>c>c>b>e;e;e;e;e;e;e;e;e;e;e;e;e;e;d>e>f>g>h>i>j>k>l>l>m>m>n>n>o>o>p>q>r>r>s>t>u>v>v>u>w>';x>y>z>t;A>B>C>D>E>E>F>G>F>H>H>I>F>Y;J>w;K>L>K>M>J>w;K>L>K>M>K>L>K>M>",
-"#;#;d.d.a>a>N>e;N>O>O>O>N>e;N>O>O>P>Q>R>S>R>Q>O>O>O>N>e;N>O>O>O>N>e;N>N>O>T>e;e;e;U>U>U>U>f;V>W>o>o>o>o>X>X>Y>Y>n>n>Z>Z>`> ,.,t>t>u>u>w>+,@,#,$,%,A>&,*,=,B>[>-,w;<>C>[>-,w;w;w;w;w;-,w;w;w;w;w;w;w;w;w;",
-"#;;,;-;-a>a>N>N>N>O>O>O>N>N>N>O>O>O>O>N>N>N>O>O>O>O>N>N>N>O>O>O>N>N>N>N>O>>,,,,,,,',g>),!,~,{,{,*>U>e;f;],o>%;o>^,^,/,/,l>q>(,_,t>u>:,<,v>[,},|,1,2,%,%,3,4,5,6,7,8,9,5,6,0,G>G>Y;G>6,0,G>G>Y;G>G>G>Y;G>",
-";,;,;-;-O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>P>a,b,',',c,c,f>),e>d,e,{,{,U>U>f,f,U>U>g,g,*>g;h,^,^,`>`>q>i,t>j,k,k,l,w>m,n,o,p,q,r,s,t,p,u,v,w,x,y,z,u,v,w,x,y,z,w,x,y,z,",
-";,;,b b O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>A,A,A,B,C,D,E,F,c,',g>G,!,H,~,e,{,I,J,J,K,K,U>f,f,J,L,M,N,L;O,i,P,.,l,Q,k,k,k,k,k,k,R,v,k,k,k,R,v,S,T,U,k,R,v,S,T,U,v,S,T,U,",
-";,;,b V,W,W,X,X,O>X,X,X,X,X,O>X,X,X,X,X,X,O>X,X,X,X,X,X,O>X,X,X,X,X,O>X,X,O>O>O>O>B,B,B,B,Y,O>O>Z,`,T>T> '',g>.'+'e,{,{,e,+'+'e,e,{,J,K,e;@'N,O,#'$'%'%'j,%'j,&'k,k,%'j,&'k,k,k,k,k,&'k,k,k,k,k,k,k,k,k,",
-";,;,b V,W,W,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,*'O>O>O>O>O>O>O>O>B,B,A,A,B,C,='-'`,;'>'>',''')'!'!'e>e>~'~'~,~,{'{,*>*>e;]']']']']']'^'/']']']'^'/':,(':,]'^'/':,(':,/':,(':,",
-";,;,V,V,W,W,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_':'<'['}'|'|'O>O>O>O>O>O>O>Y,Y,1'1'B,B,2'2'C,3'-'>'c,)')'!'),4'{'e;]'e;*>*>e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;e;",
-";,;,5'5'W,W,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,W,6'6'6'7'8'9'0'a'b'c'd'd'}'}'O>O>O>O>O>O>O>O>Y,1'1'['['e'e'f'g'h'i'j'k'G,),!,l'j'm'n'b>b>),m'b>e;e;e;e;e;b>e;e;e;e;e;e;e;e;e;",
-";,;,b b o'o'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'W,q'q'q'r's't'u'v'w'x'y'z'A'B'C'D'2'2'B,B,O>O>O>O>O>O>O>O>O>O>O>Y,Y,C,C,='='='E'F'3'3'3'G'Z,='F'F'G'H'I'J'F'F'G'H'I'J'G'H'I'J'",
-";,;,b b K'K'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'W,W,W,W,W,L'L'q'r'M'N'O'P'u'N's'Q'R'S'A'T'U'C'V'9'0'W'D'}'X'|'O>O>B,B,O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>",
-";,;,b b K'K'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'p'Y'Y'Y'Z'`' ).)+)+)+)W,W,W,W,L'L'q'q'r'r's'M'N'P'@)A'#)$)%)&)*)=)B,|'|'O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>O>",
-"{+;,$ -);)K'p'p'o'p'p'p'p'p'o'p'p'p'p'p'p'o'p'p'p'p'p'p'o'p'p'p'p'p'o'o'p'p'p'p'p'p'p'p'p'p'>)>)Y'Y'>)Z',)')))!)~)+)W,W,W,W,W,W,W,W,W,W,W,L'L'{)s't'])^)/)])/)/)O>()])/)/)O>()O>_)O>/)O>()O>_)O>()O>_)O>",
-":);,;,;)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)[)M M M M M M M M M M M M M M M M M M })})|)|)})M M 1)2)3)4)5)6)6)6)7)7)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)",
-"9)#;;,;,$ -)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)<)0)a)a)a)b)c)d)e)f)g)h)i)i)j)j)M M M M M M M M M M M })})})})M k)k)M M k)l)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)8)",
-"+ 9)m)n)$ #;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;#;o)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)p)",
-"+ + 9)a m)q)r)s)r)s)r)s)r)s)r)r)s)r)s)r)s)r)r)s)r)s)r)s)r)s)r)s)r)s)r)s)r)t)u)v)w)x)x)w)y)z)A)A)B)B)B)B)w)w)C)C)w)w)B)B)B)B)B)w)w)w)w)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)B)D)B)B)B)B)B)D)B)B)B)D)B)",
-". + + 9)9)9)q)E)q)E)q)E)q)E)q)q)E)q)E)q)E)q)q)E)q)E)q)E)q)E)q)E)q)E)q)E)q)F)G)H)E)I)J)K)H)L)L)L)L)L)L)L)H)H)M)M)H)H)L)L)G)L)L)H)H)H)H)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)L)N)L)L)L)L)L)N)L)L)L)N)L)",
-". . 0 . + O)P)O)P)O)P)O)P)O)P)P)O)P)O)P)O)P)P)O)P)O)P)O)P)O)P)O)P)O)P)O)P)O)Q)R)S)T)U)V)W)X)W)W)V)V)V)V)V)V)V)V)Y)Y)Z)Z)Y)Z)Z)Y)Y)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)V)Y)V)V)V)V)V)Y)V)V)V)Y)V)",
-". . . 0 0 0 . 0 0 0 + 0 + 0 + 0 + 0 + 0 + 0 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 0 `) !+ + + .! !`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)`)+!`)`)`)`)`)+!`)`)`)+!`)"};
-
-
-static char * listviewhighcornerright_xpm[] = {
-"100 46 780 2",
-" c None",
-". c #6A779D",
-"+ c #6C789C",
-"@ c #6C789D",
-"# c #6B789D",
-"$ c #6A779E",
-"% c #66759E",
-"& c #64749E",
-"* c #63749E",
-"= c #61739D",
-"- c #576D9B",
-"; c #556C9C",
-"> c #4D679D",
-", c #4A649D",
-"' c #49629D",
-") c #465E9C",
-"! c #40579C",
-"~ c #3B5394",
-"{ c #2C4E97",
-"] c #314993",
-"^ c #2B4595",
-"/ c #1B4296",
-"( c #253D93",
-"_ c #19418F",
-": c #0F3C96",
-"< c #42599E",
-"[ c #758DC3",
-"} c #E8EAE7",
-"| c #EEF0ED",
-"1 c #FBFBFC",
-"2 c #6F7D9B",
-"3 c #6F7D9A",
-"4 c #6E7B9C",
-"5 c #67759E",
-"6 c #63739E",
-"7 c #62739D",
-"8 c #596F9C",
-"9 c #4A639D",
-"0 c #47609C",
-"a c #445B9F",
-"b c #3E5697",
-"c c #2E509A",
-"d c #2D509A",
-"e c #2D4F99",
-"f c #2D4F98",
-"g c #28418A",
-"h c #3E51A3",
-"i c #D0D3DC",
-"j c #A1B6EF",
-"k c #A2B6F0",
-"l c #A1B6F0",
-"m c #A3B6F0",
-"n c #A0B6EF",
-"o c #9DB6EE",
-"p c #9CB5EF",
-"q c #9CB2F0",
-"r c #9FB5EE",
-"s c #9CB4EB",
-"t c #9AB3EC",
-"u c #9AB0EC",
-"v c #9DB3EB",
-"w c #9BB4EC",
-"x c #9BB4EE",
-"y c #9BB1EF",
-"z c #9BB0F0",
-"A c #90ACF0",
-"B c #93ABEE",
-"C c #91A8EB",
-"D c #8BA3E8",
-"E c #88A1E7",
-"F c #809DE9",
-"G c #7A99E8",
-"H c #7491E5",
-"I c #698AE4",
-"J c #6184E3",
-"K c #507EDC",
-"L c #4E7CDB",
-"M c #4F7DDC",
-"N c #5479DA",
-"O c #567BDC",
-"P c #577CDD",
-"Q c #5074DA",
-"R c #5174DB",
-"S c #5175DC",
-"T c #5276DD",
-"U c #4D71DE",
-"V c #4C72D8",
-"W c #3A6CE0",
-"X c #2B49A6",
-"Y c #E0E2DF",
-"Z c #93AAE9",
-"` c #94A9E8",
-" . c #94AAE9",
-".. c #93A9E9",
-"+. c #92AAE9",
-"@. c #8DA9E8",
-"#. c #8CA7E9",
-"$. c #92ABE9",
-"%. c #8EAAE9",
-"&. c #8EA9E9",
-"*. c #8FAAE9",
-"=. c #8CA8E9",
-"-. c #8CA2E7",
-";. c #86A1E6",
-">. c #839EE9",
-",. c #7F9CE9",
-"'. c #7A97E8",
-"). c #7693E7",
-"!. c #6E8EE8",
-"~. c #678AE9",
-"{. c #5D84E3",
-"]. c #577CDF",
-"^. c #4E77DF",
-"/. c #4A70DB",
-"(. c #4870DB",
-"_. c #4870DC",
-":. c #4770E3",
-"<. c #496FDC",
-"[. c #486EDB",
-"}. c #466FE4",
-"|. c #466EE3",
-"1. c #4167D9",
-"2. c #4066D8",
-"3. c #3F66D8",
-"4. c #3D64D7",
-"5. c #3960DA",
-"6. c #476DD9",
-"7. c #446EE5",
-"8. c #305EC8",
-"9. c #8EAAE8",
-"0. c #8FAAE8",
-"a. c #91AAE9",
-"b. c #8FA9E8",
-"c. c #8BA8E8",
-"d. c #8AA7E9",
-"e. c #8BA5EA",
-"f. c #8AA7E8",
-"g. c #87A2E6",
-"h. c #859FE8",
-"i. c #7F9DE8",
-"j. c #7C9AE8",
-"k. c #7B95E7",
-"l. c #7090E8",
-"m. c #6B8BE9",
-"n. c #6386E6",
-"o. c #5881E1",
-"p. c #5479DE",
-"q. c #4D74DE",
-"r. c #476EDB",
-"s. c #446EE1",
-"t. c #446EE0",
-"u. c #446EDF",
-"v. c #446DE0",
-"w. c #426ADF",
-"x. c #3C64DA",
-"y. c #4360CC",
-"z. c #D3D5D2",
-"A. c #E6E3E8",
-"B. c #8DA2E7",
-"C. c #8CA6EA",
-"D. c #8DA3E9",
-"E. c #88A2E7",
-"F. c #87A1E7",
-"G. c #8AA1E7",
-"H. c #849EE9",
-"I. c #7D9AE9",
-"J. c #7B98E8",
-"K. c #7796E5",
-"L. c #7191E7",
-"M. c #688CE9",
-"N. c #6687E5",
-"O. c #5C83E1",
-"P. c #557BDE",
-"Q. c #4F76DE",
-"R. c #4C72DE",
-"S. c #456EDF",
-"T. c #426AD9",
-"U. c #4269D9",
-"V. c #4269D8",
-"W. c #3D64D9",
-"X. c #3A61DA",
-"Y. c #345ED6",
-"Z. c #335ECF",
-"`. c #C6C3C8",
-" + c #86A1E7",
-".+ c #87A2E7",
-"++ c #87A0E7",
-"@+ c #859EE8",
-"#+ c #849DE9",
-"$+ c #7E9BE9",
-"%+ c #7A99E9",
-"&+ c #7A95E5",
-"*+ c #7593E7",
-"=+ c #6F8EE9",
-"-+ c #668AE5",
-";+ c #6386E0",
-">+ c #5B82DF",
-",+ c #5379DE",
-"'+ c #5075DE",
-")+ c #4B6FDC",
-"!+ c #446AD7",
-"~+ c #4269D6",
-"{+ c #4269D5",
-"]+ c #3E65D7",
-"^+ c #C9CAC9",
-"/+ c #869EE9",
-"(+ c #859FE9",
-"_+ c #849FE9",
-":+ c #829DE8",
-"<+ c #819DE8",
-"[+ c #7B9AE9",
-"}+ c #7A96E6",
-"|+ c #7290E8",
-"1+ c #698CE6",
-"2+ c #6689E0",
-"3+ c #5D84E0",
-"4+ c #587FDF",
-"5+ c #5377DD",
-"6+ c #4B74DE",
-"7+ c #496BD8",
-"8+ c #7C9BE9",
-"9+ c #7E9CE9",
-"0+ c #7D9AEA",
-"a+ c #7D9BEA",
-"b+ c #7D98E8",
-"c+ c #7C98E8",
-"d+ c #7796E4",
-"e+ c #7592E6",
-"f+ c #7390E1",
-"g+ c #698DE0",
-"h+ c #6588DE",
-"i+ c #5E84E0",
-"j+ c #5880DF",
-"k+ c #5479DC",
-"l+ c #4F75DE",
-"m+ c #4A6FDB",
-"n+ c #436AD7",
-"o+ c #3F65D7",
-"p+ c #BAC3BE",
-"q+ c #7B9AE8",
-"r+ c #7B9AEA",
-"s+ c #7A9AEA",
-"t+ c #7B99E9",
-"u+ c #7D97E7",
-"v+ c #7D95E6",
-"w+ c #7D95E5",
-"x+ c #7C95E6",
-"y+ c #7493E3",
-"z+ c #7290DF",
-"A+ c #6C8DDE",
-"B+ c #6B89E1",
-"C+ c #6486DF",
-"D+ c #5D81DF",
-"E+ c #567DDE",
-"F+ c #4F73DE",
-"G+ c #496EDA",
-"H+ c #355ED6",
-"I+ c #345ED5",
-"J+ c #7E95E5",
-"K+ c #7C97E8",
-"L+ c #7C97E7",
-"M+ c #7B94E6",
-"N+ c #7A95E4",
-"O+ c #7695E5",
-"P+ c #7694E4",
-"Q+ c #7994E6",
-"R+ c #7995E4",
-"S+ c #7594E4",
-"T+ c #7391E2",
-"U+ c #6E8EDE",
-"V+ c #6B8ADE",
-"W+ c #6688DF",
-"X+ c #5F84E0",
-"Y+ c #5980E0",
-"Z+ c #4D72DD",
-"`+ c #456BD7",
-" @ c #4168D6",
-".@ c #3C64D7",
-"+@ c #335ED0",
-"@@ c #4659C7",
-"#@ c #7292E1",
-"$@ c #7392E1",
-"%@ c #7492E1",
-"&@ c #718FDF",
-"*@ c #6F8EDE",
-"=@ c #6D8BDE",
-"-@ c #6B88DF",
-";@ c #597FDF",
-">@ c #557ADD",
-",@ c #5176DC",
-"'@ c #4D74DD",
-")@ c #496DDA",
-"!@ c #3860D8",
-"~@ c #7391E0",
-"{@ c #7290DE",
-"]@ c #6D8EDD",
-"^@ c #6D8DDD",
-"/@ c #7190E0",
-"(@ c #6C8DDD",
-"_@ c #6B89DF",
-":@ c #6487E0",
-"<@ c #6085DF",
-"[@ c #5F81DE",
-"}@ c #567EDE",
-"|@ c #4F74D9",
-"1@ c #466BD7",
-"2@ c #4067D5",
-"3@ c #3C63D7",
-"4@ c #335ED3",
-"5@ c #335ED1",
-"6@ c #718EDD",
-"7@ c #728EDD",
-"8@ c #748EDD",
-"9@ c #708EDD",
-"0@ c #6F8DDD",
-"a@ c #6E8DDD",
-"b@ c #6C8ADE",
-"c@ c #6C89DF",
-"d@ c #6988DF",
-"e@ c #6387DF",
-"f@ c #6282DE",
-"g@ c #5681E0",
-"h@ c #577BDD",
-"i@ c #5277DB",
-"j@ c #4D73D8",
-"k@ c #4A70D8",
-"l@ c #436AD5",
-"m@ c #3F66D6",
-"n@ c #3C63D8",
-"o@ c #3960D8",
-"p@ c #3860D7",
-"q@ c #335ED2",
-"r@ c #345ED4",
-"s@ c #6C88DF",
-"t@ c #6D88DF",
-"u@ c #6B89DE",
-"v@ c #6888DF",
-"w@ c #6587E0",
-"x@ c #6989DF",
-"y@ c #6687E0",
-"z@ c #6287E0",
-"A@ c #6281DD",
-"B@ c #5881E0",
-"C@ c #557ADB",
-"D@ c #5176D9",
-"E@ c #4E75D7",
-"F@ c #4A6FD8",
-"G@ c #476BD6",
-"H@ c #4067D6",
-"I@ c #3C62D7",
-"J@ c #3C60D4",
-"K@ c #365ED1",
-"L@ c #345ED3",
-"M@ c #6786DF",
-"N@ c #5F85E0",
-"O@ c #5F86E0",
-"P@ c #6186DF",
-"Q@ c #6286E0",
-"R@ c #6284DF",
-"S@ c #6384DF",
-"T@ c #5B7FDE",
-"U@ c #577DDC",
-"V@ c #557BDA",
-"W@ c #5278D8",
-"X@ c #4E76D6",
-"Y@ c #4C72D7",
-"Z@ c #486DD8",
-"`@ c #4469D6",
-" # c #3F62D2",
-".# c #3C60CF",
-"+# c #345ECF",
-"@# c #6086DF",
-"## c #6085E0",
-"$# c #6285DF",
-"%# c #6383DD",
-"&# c #6481DC",
-"*# c #6380DD",
-"=# c #6183DE",
-"-# c #6083DD",
-";# c #6081DC",
-"># c #6080DD",
-",# c #6083DE",
-"'# c #6181DC",
-")# c #6280DD",
-"!# c #577EDB",
-"~# c #557CD7",
-"{# c #4F76D6",
-"]# c #4E74D7",
-"^# c #466CD7",
-"/# c #3B64D6",
-"(# c #4261CD",
-"_# c #375FCE",
-":# c #5A7FD8",
-"<# c #6281DA",
-"[# c #5F81D8",
-"}# c #5C80D8",
-"|# c #557DD7",
-"1# c #577ED8",
-"2# c #567ED7",
-"3# c #587DD8",
-"4# c #577DD8",
-"5# c #587ED8",
-"6# c #567DD8",
-"7# c #5379D9",
-"8# c #5177D7",
-"9# c #4D74D5",
-"0# c #486ED9",
-"a# c #4068D4",
-"b# c #3D65D2",
-"c# c #4361CC",
-"d# c #345ECE",
-"e# c #325DCF",
-"f# c #2C5AD1",
-"g# c #3959C5",
-"h# c #547BD8",
-"i# c #567DD7",
-"j# c #557BD8",
-"k# c #5279D9",
-"l# c #5278D9",
-"m# c #4D74D6",
-"n# c #4B71D8",
-"o# c #496CD8",
-"p# c #4669D7",
-"q# c #3D66D3",
-"r# c #3F62CF",
-"s# c #4260CC",
-"t# c #5379D8",
-"u# c #4E75D4",
-"v# c #4C73D7",
-"w# c #476CD7",
-"x# c #4869D0",
-"y# c #4067D2",
-"z# c #3D64D1",
-"A# c #4261CC",
-"B# c #395FCE",
-"C# c #4F75D3",
-"D# c #5074D2",
-"E# c #5174D1",
-"F# c #5175D1",
-"G# c #4F74D3",
-"H# c #4C73D5",
-"I# c #4C73D4",
-"J# c #4A72D1",
-"K# c #4B70CF",
-"L# c #506CCC",
-"M# c #4D6BCE",
-"N# c #4167D0",
-"O# c #3D65D1",
-"P# c #3F63CF",
-"Q# c #3B5FCD",
-"R# c #3159CD",
-"S# c #4971D0",
-"T# c #4870CF",
-"U# c #4C6FCF",
-"V# c #4E6CCE",
-"W# c #4E6BCE",
-"X# c #4769CF",
-"Y# c #3D66D0",
-"Z# c #3C65D1",
-"`# c #4062CE",
-" $ c #3D5FCD",
-".$ c #365FCF",
-"+$ c #325DCD",
-"@$ c #2D5AD0",
-"#$ c #3859C5",
-"$$ c #355FCF",
-"%$ c #355ECF",
-"&$ c #335ECE",
-"*$ c #305CCD",
-"=$ c #2B5ACE",
-"-$ c #3056C9",
-";$ c #2553C6",
-">$ c #2153C8",
-",$ c #1F4FC7",
-"'$ c #274CC5",
-")$ c #214AC7",
-"!$ c #1C48C8",
-"~$ c #1244C9",
-"{$ c #1043C9",
-"]$ c #1144C9",
-"^$ c #2A45BE",
-"/$ c #2744B5",
-"($ c #1D49C0",
-"_$ c #2B58DE",
-":$ c #002D94",
-"<$ c #2B59CA",
-"[$ c #2A59CA",
-"}$ c #2E57C8",
-"|$ c #3255C6",
-"1$ c #3355C5",
-"2$ c #1C52C8",
-"3$ c #1D50C7",
-"4$ c #234FC6",
-"5$ c #264CC5",
-"6$ c #1D48C7",
-"7$ c #1245C8",
-"8$ c #1F44C2",
-"9$ c #2945BE",
-"0$ c #2A45BD",
-"a$ c #2040BF",
-"b$ c #3156C7",
-"c$ c #3056C7",
-"d$ c #3354C5",
-"e$ c #3355C6",
-"f$ c #3255C5",
-"g$ c #3254C5",
-"h$ c #1952C7",
-"i$ c #1951C8",
-"j$ c #2050C7",
-"k$ c #274CC4",
-"l$ c #244CC6",
-"m$ c #1F49C7",
-"n$ c #1E47C5",
-"o$ c #2045C3",
-"p$ c #1C44BF",
-"q$ c #2045BE",
-"r$ c #2040B8",
-"s$ c #3254C6",
-"t$ c #3055C6",
-"u$ c #2A54C6",
-"v$ c #2353C7",
-"w$ c #3054C5",
-"x$ c #2F55C5",
-"y$ c #2A54C5",
-"z$ c #2553C5",
-"A$ c #2F54C5",
-"B$ c #3155C6",
-"C$ c #2A54C7",
-"D$ c #1A52C8",
-"E$ c #204FC2",
-"F$ c #264DC6",
-"G$ c #234BC5",
-"H$ c #1D48C1",
-"I$ c #1E48BF",
-"J$ c #2646BE",
-"K$ c #2B45BD",
-"L$ c #1E43BE",
-"M$ c #2643BF",
-"N$ c #2243BF",
-"O$ c #3049BC",
-"P$ c #1E50BE",
-"Q$ c #1D50C0",
-"R$ c #1D50BF",
-"S$ c #1852C1",
-"T$ c #1E51C0",
-"U$ c #214FBF",
-"V$ c #2050C0",
-"W$ c #244EBF",
-"X$ c #2151C0",
-"Y$ c #234FBF",
-"Z$ c #2350C0",
-"`$ c #2351C0",
-" % c #244FBF",
-".% c #2250C0",
-"+% c #2051C0",
-"@% c #1E50C0",
-"#% c #244DBE",
-"$% c #274DBF",
-"%% c #244CBF",
-"&% c #1C48C0",
-"*% c #2247BF",
-"=% c #2C44BD",
-"-% c #1C44BE",
-";% c #1444BF",
-">% c #1841BF",
-",% c #1F40BF",
-"'% c #254DBE",
-")% c #224FBE",
-"!% c #224FBF",
-"~% c #234EBF",
-"{% c #254CBD",
-"]% c #244DBD",
-"^% c #244CBD",
-"/% c #264DBE",
-"(% c #264DBD",
-"_% c #214BC0",
-":% c #1D48C0",
-"<% c #2347BF",
-"[% c #2B44BD",
-"}% c #2444BE",
-"|% c #0F42BF",
-"1% c #0641BF",
-"2% c #0F41BF",
-"3% c #1741BE",
-"4% c #1F40BD",
-"5% c #234BBF",
-"6% c #234CBE",
-"7% c #214BBE",
-"8% c #244CBE",
-"9% c #214ABE",
-"0% c #214ABF",
-"a% c #1F48C0",
-"b% c #2746BE",
-"c% c #1F43BE",
-"d% c #0941BE",
-"e% c #0342BA",
-"f% c #0242BC",
-"g% c #1241B8",
-"h% c #1F40B7",
-"i% c #2F41AC",
-"j% c #2644AE",
-"k% c #2D49B4",
-"l% c #2649B6",
-"m% c #2949B7",
-"n% c #2849B5",
-"o% c #2149B8",
-"p% c #1E49B9",
-"q% c #1F48B8",
-"r% c #1F49B9",
-"s% c #2545B6",
-"t% c #2744B7",
-"u% c #2844B7",
-"v% c #2043B8",
-"w% c #1241B7",
-"x% c #1340B8",
-"y% c #0D41B8",
-"z% c #1941B8",
-"A% c #1F40B8",
-"B% c #203FB8",
-"C% c #2549B5",
-"D% c #2648B6",
-"E% c #2547B7",
-"F% c #2248B7",
-"G% c #2048B7",
-"H% c #2346B6",
-"I% c #2146B6",
-"J% c #2247B7",
-"K% c #2148B7",
-"L% c #2743B4",
-"M% c #2643B5",
-"N% c #2542B6",
-"O% c #1D42B7",
-"P% c #0E42B8",
-"Q% c #0C41B8",
-"R% c #1341B8",
-"S% c #1740B8",
-"T% c #1C41B8",
-"U% c #1F40B1",
-"V% c #2644B5",
-"W% c #2544B5",
-"X% c #2544B4",
-"Y% c #2444B5",
-"Z% c #2444B4",
-"`% c #2744B4",
-" & c #2241B7",
-".& c #1D41B8",
-"+& c #0B42B8",
-"@& c #0942B8",
-"#& c #0C42B8",
-"$& c #0F41B8",
-"%& c #1641B8",
-"&& c #2442B5",
-"*& c #2543B3",
-"=& c #2342B2",
-"-& c #2341B4",
-";& c #2141B3",
-">& c #2141B5",
-",& c #2140B5",
-"'& c #2040B5",
-")& c #1C40B7",
-"!& c #1B41B3",
-"~& c #0142B6",
-"{& c #0E41B7",
-"]& c #1141B7",
-"^& c #1440B2",
-"/& c #113FB0",
-"(& c #1440B0",
-"_& c #213EAF",
-":& c #233DAE",
-"<& c #223EAF",
-"[& c #1E40B1",
-"}& c #173EAD",
-"|& c #1440AF",
-"1& c #0D40AF",
-"2& c #0941B0",
-"3& c #0D3FAE",
-"4& c #1B3CAC",
-"5& c #233CAD",
-"6& c #203FB0",
-"7& c #273BAD",
-"8& c #1D40B0",
-"9& c #2040B1",
-"0& c #1E40B0",
-"a& c #1C40B0",
-"b& c #1B3DAC",
-"c& c #143DAC",
-"d& c #193DAD",
-"e& c #1B3DAD",
-"f& c #173DAD",
-"g& c #153DAC",
-"h& c #1C3CAC",
-"i& c #243CAD",
-"j& c #213FB0",
-"k& c #263BAA",
-"l& c #253CAE",
-"m& c #273AAC",
-"n& c #273AAD",
-"o& c #253BAD",
-"p& c #1D3CAC",
-"q& c #243BAD",
-"r& c #1E3CAC",
-"s& c #263BAD",
-"t& c #1A3DAC",
-"u& c #143DAB",
-"v& c #163DAC",
-"w& c #1A3CAC",
-"x& c #1F3CAD",
-"y& c #263BAB",
-"z& c #263BA6",
-"A& c #1E42A4",
-"B& c #2D40A5",
-"C& c #253BA6",
-"D& c #253CA7",
-"E& c #263AA5",
-"F& c #253BA7",
-"G& c #1E3BA6",
-"H& c #193DA6",
-"I& c #173DA5",
-"J& c #143DA6",
-"K& c #1A3DA7",
-"L& c #133DA6",
-"M& c #123DA5",
-"N& c #1A3CA7",
-"O& c #243BA6",
-"P& c #263AA7",
-"Q& c #273BA7",
-"R& c #263AA6",
-"S& c #223BA6",
-"T& c #1D3BA6",
-"U& c #173CA6",
-"V& c #133DA5",
-"W& c #1B3DA6",
-"X& c #193DA5",
-"Y& c #123DA4",
-"Z& c #163CA5",
-"`& c #213CA6",
-" * c #273BA8",
-".* c #263BA7",
-"+* c #253BA5",
-"@* c #263BA5",
-"#* c #1C3BA6",
-"$* c #1B3BA9",
-"%* c #133BA8",
-"&* c #0A3BA7",
-"** c #083AA6",
-"=* c #123CA5",
-"-* c #0839A8",
-";* c #0239A6",
-">* c #123AA8",
-",* c #1F49C8",
-"'* c #2F4DA4",
-")* c #2E4DA3",
-"!* c #384CA4",
-"~* c #3C4DA7",
-"{* c #394EA7",
-"]* c #3B4CA5",
-"^* c #3C52B1",
-"/* c #3551A8",
-"(* c #3759BE",
-"_* c #4161C7",
-":* c #0033A8",
-"<* c #596FA9",
-"[* c #2F4DA3",
-"}* c #2D4BA5",
-"|* c #2E4CA4",
-"1* c #2C4AA5",
-"2* c #2D4BA4",
-"3* c #354DA4",
-"4* c #3A4BA4",
-"5* c #394DA6",
-"6* c #4056AD",
-"7* c #445BBB",
-"8* c #B5B7B4",
-"9* c #1B2F85",
-"0* c #242F79",
-"a* c #B5B5B5",
-"b* c #B5B2B6",
-"c* c #C0C3C3",
-"d* c #E3E3E4",
-"e* c #EBEDEA",
-". + @ + # $ % & # $ % & # $ % & # $ % & & * = - ; > , ' ) ! ~ { { { { { { { ] ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ / / / ( / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / _ _ / / : / < [ } | | | 1 1 ",
-"2 2 2 2 3 2 4 @ 3 2 4 @ 3 2 4 @ 3 2 4 @ # 5 6 7 8 ; > 9 0 a b c d e f { { { ] ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ( ( ( ( ( ( ( ( ( / / / / / / / / / / / / / / / / / _ _ _ _ _ _ _ _ _ _ _ g g _ / / : : : h i } 1 | 1 ",
-"j k l m n o p q n o p q r s t u v w x y z A B C D E F G H I J K L M N O P O O Q R S T T T T T T T T T T T T T T T T T T U U U U U U U U U U U U U U U U U U U U U U U U U U U U V V V U U W X : [ Y | | ",
-"Z ` . ...+.@.#...+.@.#.Z $.%.&.Z $.*.=.-.;.>.,.'.).!.~.{.].^./.(._.:.<.[.}.|.1.2.3.4.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.6.7.8.: h Y } 1 ",
-"9.0.a.b.c.c.d.e.f.c.d.e.f.c.d.e.f.c.d.e.g.h.i.j.k.l.m.n.o.p.q.r.s.s.t.u.u.v.w.x.4.4.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.y.5.7.6.: / z.A.} ",
-"-.B.C.D.-.E.g.F.G.E.g.F.G.E.g.F.G.E.g.F.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.V.U.U.W.X.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Z.y.Y.7.7.: : `.z.} ",
-" +.+g.;.++F.@+#+++F.@+#+++F.@+#+++F.@+#+$+%+&+*+=+-+;+>+,+'+)+!+~+{+]+{+{+4.4.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.Y.Y.5.5.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Z.Z.Z.y.y.5.7.7.: : ^+z.Y ",
-"/+(+_+#+H.H.>.:+H.H.>.:+H.H.>.:+H.H.>.<+[+}+*+|+1+2+3+4+5+6+7+{+{+4.4.4.4.4.4.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.Y.Y.Y.Y.Y.Y.Y.5.Y.Y.Y.Y.Y.Y.Y.Y.5.Y.Y.5.5.5.5.Y.Y.Y.Y.Y.Y.Z.Z.Z.Z.y.y.y.y.y.y.7.7.: : ^+i } ",
-"8+9+0+0+a+0+0+b+a+0+0+b+a+0+0+b+a+0+0+c+d+e+f+g+h+i+j+k+l+m+n+o+4.4.4.4.5.5.5.5.5.5.Y.Y.5.5.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Y.Y.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.7.7.: : p+z.Y ",
-"q+r+r+s+t+u+v+w+t+u+v+w+t+u+v+w+t+u+x+&+y+z+A+B+C+D+E+5+F+G+~+4.4.4.4.5.5.5.5.5.H+Y.Y.Y.Y.Y.Y.Y.Y.I+Y.Z.Y.Y.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.7.7.: : `.z.A.",
-"J+v+K+L+M+N+O+P+Q+R+O+P+Q+R+O+P+Q+R+O+S+T+U+V+W+X+Y+P.T Z+`+ @4.4..@5.5.5.5.5.5.Y.Y.Y.I+I+I+I+I++@+@Z.Z.Y.Y.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.@@Z.7.7.: : p+z.Y ",
-"#@$@$@%@%@$@#@&@#@#@#@&@#@#@#@&@#@#@#@*@=@-@;+i+;@>@,@'@)@ @4.X.5.5.H+Y.Y.Y.!@Y.Y.I++@+@Z.Z.+@Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.y.Z.6.6.: : `.z.A.",
-"#@$@~@~@~@{@]@^@/@{@]@^@/@{@]@^@/@{@]@(@_@:@<@[@}@k+|@V 1@2@3@5.5.5.Y.Y.I+4@I+5@+@Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.y.Z.6.6.: : p+z.Y ",
-"6@7@8@9@0@a@b@c@a@a@b@c@a@a@b@c@a@a@b@d@e@<@f@g@h@i@j@k@l@m@n@o@o@p@Y.I+q@q@r@+@Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.y.Z.6.6.: : `.z.A.",
-"s@t@u@_@_@v@w@w@x@v@w@w@x@v@y@y@x@v@:@z@A@B@P C@D@E@F@G@H@I@J@K@5@+@+@+@r@I+L@Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.@@Z.W W : : p+z.Y ",
-"M@N@O@P@C+Q@Q@R@C+;+Q@R@C+;+;+S@C+Q@Q@R@T@U@V@W@X@Y@Z@`@4. #.#+#Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.8.Z.Z.Z.Z.8.8.Z.Z.y.@@@@W W : : `.z.A.",
-"@#O@O@##$#%#&#*#=#-#;#>#,#-#;#>#,#-#'#)#!#~#W@{#]#k@^#H@/#(#_#Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.8.8.Z.Z.Z.Z.Z.Z.Z.8.8.8.8.8.8.8.8.8.8.8.Z.Z.y.y.@@W W : : p+z.Y ",
-":#<#[#}#|#1#2#3#4#5#1#4#4#1#1#4#4#1#1#6#7#8#9#V 0#`+a#b#c#d#e#Z.Z.Z.f#Z.Z.Z.f#f#f#f#f#f#f#f#f#f#g#g#g#g#g#8.8.8.8.8.8.8.8.8.g#g#g#g#8.g#8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.y.y.@@W W : : `.z.A.",
-"h#2#i#6#|#j#7#k#|#j#7#7#|#j#7#7#|#j#7#l#8#m#n#n#o#p#q#r#s#d#e#Z.Z.Z.f#f#f#f#Z.f#f#g#g#g#g#g#g#g#g#g#g#g#g#8.8.8.g#g#8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.8.y.y.y.y.8.8.8.y.y.@@W W : : p+z.Y ",
-"l#7#7#l#7#7#7#W@7#7#7#W@7#7#k#W@t#7#7#W@u#v#n#w#x#y#z#A#B#Z.e#f#f#Z.f#f#f#Z.Z.g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#8.8.8.g#g#g#g#8.8.g#g#g#g#g#g#8.8.g#8.8.y.8.8.y.y.8.y.y.y.y.@@W W : : `.z.A.",
-"C#D#E#F#G#H#I#J#G#H#I#J#G#H#I#J#G#H#I#J#K#L#M#N#O#P#s#Q#+#f#R#f#f#f#f#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#@@@@y.y.@@@@y.y.W W : : p+z.Y ",
-"S#S#S#S#S#T#S#U#S#T#S#U#S#T#S#U#S#T#S#U#V#W#X#Y#Z#`# $.$+$@$#$g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#@@@@@@@@@@@@@@@@@@y.y.W W : : `.z.A.",
-"+$Z..$$$%$+$&$*$%$+$&$*$%$+$&$*$%$+$&$*$=$-$;$>$,$'$)$!$~${$]$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$/$/$/$/$($($_$_$:$:$p+z.Y ",
-"<$<$<$<$<$[$}$|$<$[$}$|$<$[$}$|$<$[$}$|$1$2$3$4$5$)$6$7$8$9$0$a$a$a$a$a$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$/$/$/$^$^$^$/$/$/$/$/$/$/$/$/$/$/$/$/$/$($($_$_$:$:$`.z.A.",
-"b$c$c$c$d$e$e$f$g$|$|$1$d$e$e$1$d$e$e$1$h$i$j$k$l$m$n$o$p$9$q$a$a$a$a$a$a$a$a$^$a$a$^$^$^$^$^$^$a$r$r$r$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$^$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$($($_$_$:$:$p+z.Y ",
-"e$1$s$s$1$t$u$v$w$x$y$z$A$x$u$v$g$B$C$>$D$E$F$G$H$I$J$K$L$M$N$a$a$a$a$a$a$a$a$^$r$r$a$^$^$^$a$r$r$r$r$r$/$^$r$^$^$^$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$O$($_$_$:$:$`.z.A.",
-"P$Q$R$S$T$U$V$W$X$Y$Z$W$`$ %.%W$+%U$@%#%$%%%&%($*%=%-%;%>%>%,%r$r$r$r$r$a$a$a$/$/$/$r$r$r$r$r$r$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$O$($_$_$:$:$p+z.Y ",
-"'%W$)%!%~%{%'%]%~%^%'%]%~%^%'%]%~%^%/%(%_%&%:%<%[%}%|%1%2%3%4%r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$/$r$/$/$r$r$r$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$/$r$/$/$/$/$/$O$($_$_$:$:$`.z.A.",
-"5%6%'%'%6%7%8%9%6%7%8%9%6%7%8%9%6%7%8%0%&%a%<%b%[%c%d%e%f%g%h%r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$/$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$/$/$/$/$/$/$/$/$/$/$/$/$/$/$r$r$/$/$r$r$/$r$i%j%O$($_$_$:$:$p+z.Y ",
-"k%l%m%n%o%o%p%q%o%o%r%q%o%o%r%q%o%o%p%q%s%t%/$u%v%w%x%y%z%A%B%r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$/$/$/$/$/$/$/$r$r$i%i%i%r$r$i%i%i%i%i%i%i%i%i%i%i%i%r$/$/$j%j%j%j%j%j%j%j%j%O$($_$_$:$:$`.z.A.",
-"C%D%E%F%G%H%I%J%K%H%I%J%K%H%I%J%K%H%I%J%L%M%N%O%P%Q%R%S%T%A%B%r$r$r$r$r$r$r$r$r$r$r$r$r$r$r$U%U%r$r$i%i%/$/$r$r$/$/$/$/$r$r$i%i%i%i%i%i%i%i%i%i%i%i%i%i%j%i%j%j%j%j%j%j%j%j%j%j%j%j%j%O$($_$_$:$:$p+z.Y ",
-"/$/$/$/$V%V%W%X%W%Y%Y%Z%W%W%Y%Z%W%W%W%`%`% &B%.&+&@&#&$&%&A%B%r$r$r$U%U%U%U%r$U%U%U%U%U%U%U%U%U%U%i%i%i%i%i%i%i%i%/$/$/$i%i%i%i%i%i%i%i%i%j%j%j%j%i%i%i%i%i%j%j%j%i%i%j%j%j%j%j%j%j%j%O$($_$_$:$:$`.z.A.",
-"&&*&=&-&=&;&>&,&=&;&>&,&=&;&>&,&=&;&>&'&)&!&~&{&]&^&/&(&_&:&<&U%U%U%U%U%U%U%U%U%U%U%U%U%i%i%U%U%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%O$($_$_$:$:$p+z.Y ",
-"U%U%U%U%U%U%U%U%U%U%U%U%U%U%U%U%U%U%U%U%[&}&|&1&2&3&4&5&_&6&U%7&U%U%U%U%U%U%U%U%i%i%U%U%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%O$O$_$_$:$:$`.z.A.",
-"U%U%U%U%U%U%[&8&U%9&[&0&U%9&[&0&U%9&[&a&:&b&c&d&e&f&g&h&i&<&j&U%U%U%U%U%U%U%U%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%O$O$_$_$:$:$p+z.Y ",
-"k&l&m&7&7&n&o&p&7&n&q&r&s&s&q&r&s&n&o&p&t&u&u&g&v&w&x&q&n&m&y&7&7&U%U%7&z&7&z&U%A&B&i%i%B&B&i%i%B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&i%B&O$O$_$_$:$:$`.z.A.",
-"C&D&E&z&z&E&F&G&z&E&F&G&z&E&F&G&z&E&F&G&H&I&J&K&L&M&N&O&P&Q&z&z&z&z&z&z&z&z&z&z&z&z&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&O$O$_$_$:$:$p+z.Y ",
-"z&z&z&z&R&S&T&U&R&S&T&U&R&S&T&U&R&S&T&U&V&V&W&X&Y&Z&`&C&R&z&z&z&z&z&z&z&z&z&z&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&O$O$_$_$:$:$^+z.A.",
-"z& *.*+*@*#*$*%*@*#*$*%*@*#*$*%*@*#*$*%*&***=*-*;*>*k&P&+*z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&z&B&B&B&B&z&z&z&B&B&B&z&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&B&/$O$O$@@_$,*:$/ ^+z.Y ",
-"'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*'*)*'*!*~*{*]*^*^*^*/*/*/*/*/*/*/*^*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*^*/*/*/*/*/*h h ^*h h ^*^*h h ^*^*^*^*h ^*^*^*^*h ^*^*^*(*_*_*_*_*_$:*:$<*`.z.} ",
-"'*'*'*'*'*[*}*|*'*[*}*|*'*[*}*|*'*[*}*|*1*1*2*}*}*2*[*)*3*4*5*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*h h h h h h h h h h h h h h h h 6*7*_*_*_*_*^*:*:$: 8*z.Y } ",
-"9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*9*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*( <*8*^+z.Y } 1 ",
-"a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*8*b*8*b*8*b*8*b*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*b*8*8*8*8*b*8*`.z.A.Y | | ",
-"c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*c*p+`.p+`.p+`.p+`.`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+`.p+^+`.^+^+z.z.Y Y | | 1 ",
-"d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*d*A.Y A.Y A.Y A.Y Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y A.Y } } | | | | 1 1 ",
-"e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*} | } | } | } | | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | } | | | | 1 | | | 1 1 1 "};
-
-
-static char * tabmiddle_xpm[] = {
-"33 42 32 1",
-" c None",
-". c #CECFEF",
-"+ c #CECBE7",
-"@ c #C6C7E7",
-"# c #C6CBE7",
-"$ c #BDBEDE",
-"% c #BDC3DE",
-"& c #CECBEF",
-"* c #B5B6D6",
-"= c #ADAECE",
-"- c #ADB2CE",
-"; c #BDBAD6",
-"> c #B5BAD6",
-", c #C6C3DE",
-"' c #ADAAC6",
-") c #B5B2CE",
-"! c #B5B6CE",
-"~ c #A5A2BD",
-"{ c #A5A6BD",
-"] c #9C9EB5",
-"^ c #9CA2BD",
-"/ c #ADAEC6",
-"( c #C6C3E7",
-"_ c #9C9AB5",
-": c #A5A6C6",
-"< c #949AAD",
-"[ c #A5AAC6",
-"} c #9496AD",
-"| c #BDBADE",
-"1 c #BDBED6",
-"2 c #9CA2B5",
-"3 c #A5AABD",
-"..........................+@.#.#.",
-"........................$@%&#.#..",
-"......................**$$@@&#.#.",
-".....................=-;>,%+@.#..",
-"....................'')!$$@@&#.#.",
-"...................~{=)$$@@&#.#..",
-"..................]^'/;;(%&#.#...",
-"................._]:/*>,%&@.#.#..",
-".................<{[)!$%+@.#.#...",
-"................}~{=!$%@@.#......",
-"................]^/-|$@@.#.......",
-"................]'/*;@@&#........",
-"...............<~[)>,%&#.#.......",
-"...............]~=)$%+#.#........",
-"...............]'/;1@@.#.........",
-"...............~{)*,%&#..........",
-"...............2/-$$@#...........",
-"...............~[*>(@&#..........",
-"...............^=)$%+#...........",
-"...............{'*>(@.#..........",
-"...............^=)$%+#...........",
-"...............{'*>(@.#..........",
-"...............^=)$%+#...........",
-"...............{'*>(@.#..........",
-"...............^=)$%+#...........",
-"...............{'*>(@.#..........",
-"...............^=)$%+#...........",
-"...............{'*>@@.#..........",
-"...............^=!$%&#...........",
-"...............{/*;@@.#..........",
-"...............{)!$%&#...........",
-"..............]'/;1@@.#..........",
-"..............23)>,%&#...........",
-"..............~=-$$@@.#..........",
-".............]{/*;@@.#...........",
-"............<^[)>,%&#............",
-"............]{/!$%@@.#...........",
-"..........]^[-!$%@@.#............",
-".........]^3/!>$@@.#.............",
-".......<]^3/!>$@@&#..............",
-".....<]2{[/!>$%@&#.#.............",
-"}<<_]2{3/-!>$%@&#.#.............."};
-
-
-static char * tabselectedbeginn_xpm[] = {
-"33 39 28 1",
-" c None",
-". c #CECFEF",
-"+ c #EFF3EF",
-"@ c #FFFBFF",
-"# c #F7FBF7",
-"$ c #FFFFFF",
-"% c #EFEFEF",
-"& c #F7F7F7",
-"* c #DEDFDE",
-"= c #E7E7E7",
-"- c #D6D3D6",
-"; c #DEE3DE",
-"> c #EFEBEF",
-", c #F7F3F7",
-"' c #CECBCE",
-") c #CECFCE",
-"! c #D6D7D6",
-"~ c #DEDBDE",
-"{ c #E7EBE7",
-"] c #C6C7C6",
-"^ c #E7E3E7",
-"/ c #BDC3BD",
-"( c #CED3CE",
-"_ c #BDBABD",
-": c #C6C3C6",
-"< c #C6CBC6",
-"[ c #D6DBD6",
-"} c #BDBEBD",
-"..........................+@#$#$$",
-"........................%%&&@#$#$",
-"......................*==%%&&@#$$",
-"....................--*;>%,&@#$#$",
-"...................')!~={,+@#$#$$",
-"...................]-!^=%%&&@#$#$",
-"................../'(~;>%&&@#$#$$",
-"................._])!*={,&@#$#$$$",
-"................_])~*>%&&$#$$$$$$",
-"................:<![={&&@#$$$$$$$",
-"................:)!^=,+@#$$$$$$$$",
-"...............}'(*^%+@#$#$$$$$$$",
-"...............:<!*>%&&$#$$$$$$$$",
-".............../)!^{,&@#$$$$$$$$$",
-"...............](*^%+@#$$$$$$$$$$",
-"...............]!~=%&&$$$$$$$$$$$",
-"...............'(*=,+@#$$$$$$$$$$",
-"...............<!*>%&&$$$$$$$$$$$",
-"...............'-^=,+@#$$$$$$$$$$",
-"...............<!*>%&#$$$$$$$$$$$",
-"...............'-^=,+@#$$$$$$$$$$",
-"...............<!*>%&#$$$$$$$$$$$",
-"...............'-^=,+@#$$$$$$$$$$",
-"...............<!*>%&#$$$$$$$$$$$",
-"...............'-^=,+@#$$$$$$$$$$",
-"...............<!*>%&#$$$$$$$$$$$",
-"...............'!^=,&@#$$$$$$$$$$",
-"...............<~*>%&#$$$$$$$$$$$",
-"...............)!^{,&@#$$$$$$$$$$",
-"..............])~;%+@#$$$$$$$$$$$",
-"..............]-[={&&$#$$$$$$$$$$",
-".............])!^=,&@#$$$$$$$$$$$",
-"............:'-*^%+@#$$$$$$$$$$$$",
-"............])~*>%&&$#$$$$$$$$$$$",
-"...........:'!*={,&@#$$$$$$$$$$$$",
-"..........:'-~^=,+@#$$$$$$$$$$$$$",
-".......}]'-~^=%,&@#$$$$$$$$$$$$$$",
-".....}:])-~^=%,+@#$#$$$$$$$$$$$$$",
-"}}}:]')-!*^=%,&@#$#$$$$$$$$$$$$$$"};
-
-
-static char * tabselectedend_xpm[] = {
-"33 42 33 1",
-" c None",
-". c #FFFFFF",
-"+ c #CECBE7",
-"@ c #C6C7E7",
-"# c #CECFEF",
-"$ c #C6CBE7",
-"% c #BDBEDE",
-"& c #BDC3DE",
-"* c #CECBEF",
-"= c #B5B6D6",
-"- c #ADAECE",
-"; c #ADB2CE",
-"> c #BDBAD6",
-", c #B5BAD6",
-"' c #C6C3DE",
-") c #ADAAC6",
-"! c #B5B2CE",
-"~ c #B5B6CE",
-"{ c #A5A2BD",
-"] c #A5A6BD",
-"^ c #9C9EB5",
-"/ c #9CA2BD",
-"( c #ADAEC6",
-"_ c #C6C3E7",
-": c #9C9AB5",
-"< c #A5A6C6",
-"[ c #949AAD",
-"} c #A5AAC6",
-"| c #9496AD",
-"1 c #BDBADE",
-"2 c #BDBED6",
-"3 c #9CA2B5",
-"4 c #A5AABD",
-"..........................+@#$#$#",
-"........................%@&*$#$##",
-"......................==%%@@*$#$#",
-".....................-;>,'&+@#$##",
-"....................))!~%%@@*$#$#",
-"...................{]-!%%@@*$#$##",
-"..................^/)(>>_&*$#$###",
-".................:^<(=,'&*@#$#$##",
-".................[]}!~%&+@#$#$###",
-"................|{]-~%&@@#$######",
-"................^/(;1%@@#$#######",
-"................^)(=>@@*$########",
-"...............[{}!,'&*$#$#######",
-"...............^{-!%&+$#$########",
-"...............^)(>2@@#$#########",
-"...............{]!='&*$##########",
-"...............3(;%%@$###########",
-"...............{}=,_@*$##########",
-".............../-!%&+$###########",
-"...............])=,_@#$##########",
-".............../-!%&+$###########",
-"...............])=,_@#$##########",
-".............../-!%&+$###########",
-"...............])=,_@#$##########",
-".............../-!%&+$###########",
-"...............])=,_@#$##########",
-".............../-!%&+$###########",
-"...............])=,@@#$##########",
-".............../-~%&*$###########",
-"...............](=>@@#$##########",
-"...............]!~%&*$###########",
-"..............^)(>2@@#$##########",
-"..............34!,'&*$###########",
-"..............{-;%%@@#$##########",
-".............^](=>@@#$###########",
-"............[/}!,'&*$############",
-"............^](~%&@@#$###########",
-"..........^/};~%&@@#$############",
-".........^/4(~,%@@#$#############",
-".......[^/4(~,%@@*$##############",
-".....[^3]}(~,%&@*$#$#############",
-"|[[:^3]4(;~,%&@*$#$##############"};
-
-
-static char * tabend_xpm[] = {
-"33 42 3 1",
-" c None",
-". c #CECFEF",
-"+ c #FFFFFF",
-"..........................+++++++",
-"........................+++++++++",
-"......................+++++++++++",
-".....................++++++++++++",
-"....................+++++++++++++",
-"...................++++++++++++++",
-"..................+++++++++++++++",
-".................++++++++++++++++",
-".................++++++++++++++++",
-"................+++++++++++++++++",
-"................+++++++++++++++++",
-"................+++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"...............++++++++++++++++++",
-"..............+++++++++++++++++++",
-"..............+++++++++++++++++++",
-"..............+++++++++++++++++++",
-".............++++++++++++++++++++",
-"............+++++++++++++++++++++",
-"............+++++++++++++++++++++",
-"..........+++++++++++++++++++++++",
-".........++++++++++++++++++++++++",
-".......++++++++++++++++++++++++++",
-".....++++++++++++++++++++++++++++",
-"+++++++++++++++++++++++++++++++++"};
-
-
-
-
-QColor fromHsl(QColor c)
-{
- const qreal h = c.hueF();
- const qreal s = c.saturationF();
- const qreal l = c.valueF();
-
- qreal ca[3] = {0, 0, 0};
-
- if (s == 0 || h == 1) {
- // achromatic case
- ca[0] = ca[1] = ca[2] = l;
- } else {
- // chromatic case
- qreal temp2;
- if (l < qreal(0.5))
- temp2 = l * (qreal(1.0) + s);
- else
- temp2 = l + s - (l * s);
-
- const qreal temp1 = (qreal(2.0) * l) - temp2;
- qreal temp3[3] = { h + (qreal(1.0) / qreal(3.0)),
- h,
- h - (qreal(1.0) / qreal(3.0)) };
-
- for (int i = 0; i != 3; ++i) {
- if (temp3[i] < qreal(0.0))
- temp3[i] += qreal(1.0);
- else if (temp3[i] > qreal(1.0))
- temp3[i] -= qreal(1.0);
-
- const qreal sixtemp3 = temp3[i] * qreal(6.0);
-
- if (sixtemp3 < qreal(1.0))
- ca[i] = ((temp1 + (temp2 - temp1) * sixtemp3));
- else if ((temp3[i] * qreal(2.0)) < qreal(1.0))
- ca[i] = (temp2);
- else if ((temp3[i] * qreal(3.0)) < qreal(2.0))
- ca[i] = temp1 + (temp2 -temp1) * (qreal(2.0) /qreal(3.0) - temp3[i]) * qreal(6.0);
- else ca[i] = temp1;
- }
- }
-
- return QColor::fromRgbF(ca[0], ca[1], ca[2]);
-}
-
-#define Q_MAX_3(a, b, c) ( ( a > b && a > c) ? a : (b > c ? b : c) )
-#define Q_MIN_3(a, b, c) ( ( a < b && a < c) ? a : (b < c ? b : c) )
-
-QColor toHsl(QColor c)
-{
- QColor color;
- qreal h;
- qreal s;
- qreal l;
-
- const qreal r = c.redF();
- const qreal g = c.greenF();
- const qreal b = c.blueF();
- const qreal max = Q_MAX_3(r, g, b);
- const qreal min = Q_MIN_3(r, g, b);
- const qreal delta = max - min;
- const qreal delta2 = max + min;
- const qreal lightness = qreal(0.5) * delta2;
- l = (lightness);
- if (qFuzzyIsNull(delta)) {
- // achromatic case, hue is undefined
- h = 0;
- s = 0;
- } else {
- // chromatic case
- qreal hue = 0;
- if (lightness < qreal(0.5))
- s = ((delta / delta2));
- else
- s = ((delta / (qreal(2.0) - delta2)));
- if (qFuzzyCompare(r, max)) {
- hue = ((g - b) /delta);
- } else if (qFuzzyCompare(g, max)) {
- hue = (2.0 + (b - r) / delta);
- } else if (qFuzzyCompare(b, max)) {
- hue = (4.0 + (r - g) / delta);
- } else {
- Q_ASSERT_X(false, "QColor::toHsv", "internal error");
- }
- hue *= 60.0;
- if (hue < 0.0)
- hue += 360.0;
- h = (hue * 100);
- }
-
- h = h / 36000;
-
- return QColor::fromHsvF(h, s, l);
-}
-
-void tintColor(QColor &color, QColor tintColor, qreal _saturation)
-{
- tintColor = toHsl(tintColor);
- color = toHsl(color);
- qreal hue = tintColor.hueF();
-
- qreal saturation = color.saturationF();
- if (_saturation)
- saturation = _saturation;
- qreal lightness = color.valueF();
- color.setHsvF(hue, saturation, lightness);
-
- color = fromHsl(color);
- color.toRgb();
-}
-
-void tintImagePal(QImage *image, QColor color, qreal saturation)
-{
- QVector<QRgb> colorTable = image->colorTable();
- for (int i=2;i< colorTable.size();i++) {
- QColor c(toHsl(colorTable.at(i)));
- tintColor(c, color, saturation);
- colorTable[i] = c.rgb();
- }
- image->setColorTable(colorTable);
-}
-
-
-void tintImage(QImage *image, QColor color, qreal saturation)
-{
- *image = image->convertToFormat(QImage::Format_RGB32);
-
- for (int x = 0; x < image->width(); x++)
- for (int y = 0; y < image->height(); y++) {
- QColor c(image->pixel(x,y));
- tintColor(c, color, saturation);
- image->setPixel(x, y, c.rgb());
- }
-}
-
-#endif //Q_WS_WINCE_WM
-
-
-enum QSliderDirection { SliderUp, SliderDown, SliderLeft, SliderRight };
-
-#ifdef Q_WS_WINCE_WM
-
-void QWindowsMobileStylePrivate::tintImagesButton(QColor color)
-{
- if (currentTintButton == color)
- return;
- currentTintButton = color;
-
- imageTabEnd = QImage(tabend_xpm);
- imageTabSelectedEnd = QImage(tabselectedend_xpm);
- imageTabSelectedBegin = QImage(tabselectedbeginn_xpm);
- imageTabMiddle = QImage(tabmiddle_xpm);
- tintImage(&imageTabEnd, color, 0.0);
- tintImage(&imageTabSelectedEnd, color, 0.0);
- tintImage(&imageTabSelectedBegin, color, 0.0);
- tintImage(&imageTabMiddle, color, 0.0);
-
- if (!doubleControls) {
- int height = imageTabMiddle.height() / 2 + 1;
- imageTabEnd = imageTabEnd.scaledToHeight(height);
- imageTabMiddle = imageTabMiddle.scaledToHeight(height);
- imageTabSelectedEnd = imageTabSelectedEnd.scaledToHeight(height);
- imageTabSelectedBegin = imageTabSelectedBegin.scaledToHeight(height);
- }
-}
-
-void QWindowsMobileStylePrivate::tintImagesHigh(QColor color)
-{
- if (currentTintHigh == color)
- return;
- currentTintHigh = color;
- tintListViewHighlight(color);
- imageScrollbarHandleUpHigh = imageScrollbarHandleUp;
- imageScrollbarHandleDownHigh = imageScrollbarHandleDown;
- tintImagePal(&imageScrollbarHandleDownHigh, color, qreal(0.8));
- tintImagePal(&imageScrollbarHandleUpHigh, color, qreal(0.8));
-}
-
-void QWindowsMobileStylePrivate::tintListViewHighlight(QColor color)
-{
- imageListViewHighlightCornerRight = QImage(listviewhighcornerright_xpm);
- tintImage(&imageListViewHighlightCornerRight, color, qreal(0.0));
-
- imageListViewHighlightCornerLeft = QImage(listviewhighcornerleft_xpm);
- tintImage(&imageListViewHighlightCornerLeft, color, qreal(0.0));
-
- imageListViewHighlightMiddle = QImage(listviewhighmiddle_xpm);
- tintImage(&imageListViewHighlightMiddle, color, qreal(0.0));
-
- int height = imageListViewHighlightMiddle.height();
- if (!doubleControls) {
- height = height / 2;
- imageListViewHighlightCornerRight = imageListViewHighlightCornerRight.scaledToHeight(height);
- imageListViewHighlightCornerLeft = imageListViewHighlightCornerLeft.scaledToHeight(height);
- imageListViewHighlightMiddle = imageListViewHighlightMiddle.scaledToHeight(height);
- }
-}
-
-#endif //Q_WS_WINCE_WM
-
-void QWindowsMobileStylePrivate::setupWindowsMobileStyle65()
-{
-#ifdef Q_WS_WINCE_WM
- wm65 = qt_wince_is_windows_mobile_65();
- if (wm65) {
- imageScrollbarHandleUp = QImage(sbhandleup_xpm);
- imageScrollbarHandleDown = QImage(sbhandledown_xpm);
- imageScrollbarGripUp = QImage(sbgripup_xpm);
- imageScrollbarGripDown = QImage(sbgripdown_xpm);
- imageScrollbarGripMiddle = QImage(sbgripmiddle_xpm);
-
- if (!doubleControls) {
- imageScrollbarHandleUp = imageScrollbarHandleUp.scaledToHeight(imageScrollbarHandleUp.height() / 2);
- imageScrollbarHandleDown = imageScrollbarHandleDown.scaledToHeight(imageScrollbarHandleDown.height() / 2);
- imageScrollbarGripMiddle = imageScrollbarGripMiddle.scaledToHeight(imageScrollbarGripMiddle.height() / 2);
- imageScrollbarGripUp = imageScrollbarGripUp.scaledToHeight(imageScrollbarGripUp.height() / 2);
- imageScrollbarGripDown = imageScrollbarGripDown.scaledToHeight(imageScrollbarGripDown.height() / 2);
- } else {
- }
- tintImagesHigh(Qt::blue);
- }
-#endif //Q_WS_WINCE_WM
-}
-
-void QWindowsMobileStylePrivate::drawTabBarTab(QPainter *painter, const QStyleOptionTab *tab)
-{
-#ifndef QT_NO_TABBAR
-#ifdef Q_WS_WINCE_WM
- if (wm65) {
- tintImagesButton(tab->palette.button().color());
- QRect r;
- r.setTopLeft(tab->rect.topRight() - QPoint(imageTabMiddle.width(), 0));
- r.setBottomRight(tab->rect.bottomRight());
- if (tab->state & QStyle::State_Selected) {
- painter->fillRect(tab->rect, tab->palette.window());
- } else {
- painter->fillRect(tab->rect, QColor(imageTabMiddle.pixel(0,0)));
- }
- if (tab->selectedPosition == QStyleOptionTab::NextIsSelected) {
- painter->drawImage(r, imageTabSelectedBegin);
- } else if (tab->position == QStyleOptionTab::End ||
- tab->position == QStyleOptionTab::OnlyOneTab) {
- if (!(tab->state & QStyle::State_Selected)) {
- painter->drawImage(r, imageTabEnd);
- }
- } else if (tab->state & QStyle::State_Selected) {
- painter->drawImage(r, imageTabSelectedEnd);
- } else {
- painter->drawImage(r, imageTabMiddle);
- }
- if (tab->position == QStyleOptionTab::Beginning && ! (tab->state & QStyle::State_Selected)) {
- painter->drawImage(tab->rect.topLeft() - QPoint(imageTabMiddle.width() * 0.60, 0), imageTabSelectedEnd);
- }
- //imageTabBarBig
- return;
- }
-#endif //Q_WS_WINCE_WM
- painter->save();
- painter->setPen(tab->palette.shadow().color());
- if (doubleControls) {
- QPen pen = painter->pen();
- pen.setWidth(2);
- pen.setCapStyle(Qt::FlatCap);
- painter->setPen(pen);
- }
- if(tab->shape == QTabBar::RoundedNorth) {
- if (tab->state & QStyle::State_Selected) {
- painter->fillRect(tab->rect, tab->palette.light());
- painter->drawLine(tab->rect.topRight(), tab->rect.bottomRight());
- }
- else {
- painter->fillRect(tab->rect, tab->palette.button());
- painter->drawLine(tab->rect.bottomLeft() , tab->rect.bottomRight());
- painter->drawLine(tab->rect.topRight(), tab->rect.bottomRight());
- }
- }
- else if(tab->shape == QTabBar::RoundedSouth) {
- if (tab->state & QStyle::State_Selected) {
- painter->fillRect(tab->rect.adjusted(0,-2,0,0), tab->palette.light());
- painter->drawLine(tab->rect.topRight(), tab->rect.bottomRight());
- }
- else {
- painter->fillRect(tab->rect, tab->palette.button());
- if (doubleControls)
- painter->drawLine(tab->rect.topLeft() + QPoint(0,1), tab->rect.topRight() + QPoint(0,1));
- else
- painter->drawLine(tab->rect.topLeft(), tab->rect.topRight());
- painter->drawLine(tab->rect.topRight(), tab->rect.bottomRight());
- }
- }
- else if(tab->shape == QTabBar::RoundedEast) {
- if (tab->state & QStyle::State_Selected) {
- painter->fillRect(tab->rect, tab->palette.light());
- painter->drawLine(tab->rect.topLeft(), tab->rect.topRight());
- }
- else {
- painter->fillRect(tab->rect, tab->palette.button());
- painter->drawLine(tab->rect.topLeft(), tab->rect.bottomLeft());
- painter->drawLine(tab->rect.topLeft(), tab->rect.topRight());
- }
- }
- else if(tab->shape == QTabBar::RoundedWest) {
- if (tab->state & QStyle::State_Selected) {
- painter->fillRect(tab->rect, tab->palette.light());
- painter->drawLine(tab->rect.bottomLeft(), tab->rect.bottomRight());
- }
- else {
- painter->fillRect(tab->rect, tab->palette.button());
- painter->drawLine(tab->rect.topRight(), tab->rect.bottomRight());
- painter->drawLine(tab->rect.bottomLeft(), tab->rect.bottomRight());
- }
- }
- painter->restore();
-#endif //QT_NO_TABBAR
-}
-
-void QWindowsMobileStylePrivate::drawPanelItemViewSelected(QPainter *painter, const QStyleOptionViewItemV4 *option, QRect rect)
-{
-#ifdef Q_WS_WINCE_WM
- if (wm65) {
- QRect r;
- if (rect.isValid())
- r = rect;
- else
- r = option->rect;
- tintImagesHigh(option->palette.highlight().color());
-
- painter->setPen(QColor(Qt::lightGray));
-
- if (option->viewItemPosition == QStyleOptionViewItemV4::Middle) {
- painter->drawImage(r, imageListViewHighlightMiddle);
- } else if (option->viewItemPosition == QStyleOptionViewItemV4::Beginning) {
- painter->drawImage(r.adjusted(10, 0, 0, 0), imageListViewHighlightMiddle);
- } else if (option->viewItemPosition == QStyleOptionViewItemV4::End) {
- painter->drawImage(r.adjusted(0, 0, -10, 0), imageListViewHighlightMiddle);
- } else {
- painter->drawImage(r.adjusted(10, 0, -10, 0), imageListViewHighlightMiddle);
- }
-
- QImage cornerLeft = imageListViewHighlightCornerLeft;
- QImage cornerRight = imageListViewHighlightCornerRight;
-
- int width = r.width() > cornerRight.width() ? r.width() : cornerRight.width();
-
- if ((width * 2) > r.width()) {
- width = (r.width() - 5) / 2;
- }
-
- cornerLeft = cornerLeft.scaled(width, r.height());
- cornerRight = cornerRight.scaled(width, r.height());
-
- if ((option->viewItemPosition == QStyleOptionViewItemV4::Beginning) || (option->viewItemPosition == QStyleOptionViewItemV4::OnlyOne) || !option->viewItemPosition) {
- painter->drawImage(r.topLeft(), cornerLeft);
- }
- if ((option->viewItemPosition == QStyleOptionViewItemV4::End) || (option->viewItemPosition == QStyleOptionViewItemV4::OnlyOne) || !option->viewItemPosition) {
- painter->drawImage(r.topRight() - QPoint(cornerRight.width(),0), cornerRight);
- }
- return;
- }
-#endif //Q_WS_WINCE_WM
- QPalette::ColorGroup cg = option->state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
-
- if (rect.isValid())
- painter->fillRect(rect, option->palette.brush(cg, QPalette::Highlight));
- else
- painter->fillRect(option->rect, option->palette.brush(cg, QPalette::Highlight));
-}
-
-void QWindowsMobileStylePrivate::drawScrollbarGrip(QPainter *p, QStyleOptionSlider *newScrollbar, const QStyleOptionComplex *option, bool drawCompleteFrame)
-{
-#ifdef Q_WS_WINCE_WM
- if (wm65) {
- if (newScrollbar->orientation == Qt::Horizontal) {
- QTransform transform;
- transform.rotate(-90);
- QRect r = newScrollbar->rect;
- p->drawImage(r.adjusted(10, 0, -10, 0), imageScrollbarGripMiddle.transformed(transform));
- p->drawImage(r.topLeft(), imageScrollbarGripUp.transformed(transform));
- p->drawImage(r.topRight() - QPoint(imageScrollbarGripDown.height() - 1, 0), imageScrollbarGripDown.transformed(transform));
- } else {
- QRect r = newScrollbar->rect;
- p->drawImage(r.adjusted(0, 10, 0, -10), imageScrollbarGripMiddle);
- p->drawImage(r.topLeft(), imageScrollbarGripUp);
- p->drawImage(r.bottomLeft() - QPoint(0, imageScrollbarGripDown.height() - 1), imageScrollbarGripDown);
- }
- return ;
- }
-#endif
- if (newScrollbar->orientation == Qt::Horizontal) {
- p->fillRect(newScrollbar->rect,option->palette.button());
- QRect r = newScrollbar->rect;
- p->drawLine(r.topLeft(), r.bottomLeft());
- p->drawLine(r.topRight(), r.bottomRight());
- if (smartphone) {
- p->drawLine(r.topLeft(), r.topRight());
- p->drawLine(r.bottomLeft(), r.bottomRight());
- }
- }
- else {
- p->fillRect(newScrollbar->rect,option->palette.button());
- QRect r = newScrollbar->rect;
- p->drawLine(r.topLeft(), r.topRight());
- p->drawLine(r.bottomLeft(), r.bottomRight());
- if (smartphone) {
- p->drawLine(r.topLeft(), r.bottomLeft());
- p->drawLine(r.topRight(), r.bottomRight());
- }
- }
- if (newScrollbar->state & QStyle::State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*newScrollbar);
- fropt.rect.setRect(newScrollbar->rect.x() + 2, newScrollbar->rect.y() + 2,
- newScrollbar->rect.width() - 5,
- newScrollbar->rect.height() - 5);
- }
- int gripMargin = doubleControls ? 4 : 2;
- int doubleLines = doubleControls ? 2 : 1;
- //If there is a frame around the scrollbar (abstractScrollArea),
- //then the margin is different, because of the missing frame
- int gripMarginFrame = doubleControls ? 3 : 1;
- if (drawCompleteFrame)
- gripMarginFrame = 0;
- //draw grips
- if (!smartphone)
- if (newScrollbar->orientation == Qt::Horizontal) {
- for (int i = -3; i < 3; i += 2) {
- p->drawLine(
- QPoint(newScrollbar->rect.center().x() + i * doubleLines + 1,
- newScrollbar->rect.top() + gripMargin +gripMarginFrame),
- QPoint(newScrollbar->rect.center().x() + i * doubleLines + 1,
- newScrollbar->rect.bottom() - gripMargin));
- }
- } else {
- for (int i = -2; i < 4 ; i += 2) {
- p->drawLine(
- QPoint(newScrollbar->rect.left() + gripMargin + gripMarginFrame ,
- newScrollbar->rect.center().y() + 1 + i * doubleLines - 1),
- QPoint(newScrollbar->rect.right() - gripMargin,
- newScrollbar->rect.center().y() + 1 + i * doubleLines - 1));
- }
- }
- if (!smartphone) {
- QRect r;
- if (doubleControls)
- r = option->rect.adjusted(1, 1, -1, 0);
- else
- r = option->rect.adjusted(0, 0, -1, 0);
- if (drawCompleteFrame && doubleControls)
- r.adjust(0, 0, 0, -1);
- //Check if the scrollbar is part of an abstractItemView and draw the frame according
- if (drawCompleteFrame)
- p->drawRect(r);
- else
- if (newScrollbar->orientation == Qt::Horizontal)
- p->drawLine(r.topLeft(), r.topRight());
- else
- p->drawLine(r.topLeft(), r.bottomLeft());
- }
-}
-
-void QWindowsMobileStylePrivate::drawScrollbarHandleUp(QPainter *p, QStyleOptionSlider *opt, bool completeFrame, bool )
-{
-#ifdef Q_WS_WINCE_WM
- if (wm65) {
- tintImagesHigh(opt->palette.highlight().color());
- QRect r = opt->rect;
- if (opt->orientation == Qt::Horizontal) {
- QTransform transform;
- transform.rotate(-90);
- if (opt->state & QStyle::State_Sunken)
- p->drawImage(r.topLeft(), imageScrollbarHandleUpHigh.transformed(transform));
- else
- p->drawImage(r.topLeft(), imageScrollbarHandleUp.transformed(transform));
- } else {
- if (opt->state & QStyle::State_Sunken)
- p->drawImage(r.topLeft(), imageScrollbarHandleUpHigh);
- else
- p->drawImage(r.topLeft(), imageScrollbarHandleUp);
- }
- return ;
- }
-#endif //Q_WS_WINCE_WM
-
- QBrush fill = opt->palette.button();
- if (opt->state & QStyle::State_Sunken)
- fill = opt->palette.shadow();
-
- QStyleOption arrowOpt = *opt;
- if (doubleControls)
- arrowOpt.rect = opt->rect.adjusted(4, 6, -5, -3);
- else
- arrowOpt.rect = opt->rect.adjusted(5, 6, -4, -3);
-
- bool horizontal = (opt->orientation == Qt::Horizontal);
-
- if (horizontal) {
- p->fillRect(opt->rect,fill);
- QRect r = opt->rect.adjusted(0,0,1,0);
- p->drawLine(r.topRight(), r.bottomRight());
- if (doubleControls)
- arrowOpt.rect.adjust(0, -2 ,0, -2);
- q_func()->proxy()->drawPrimitive(QStyle::PE_IndicatorArrowLeft, &arrowOpt, p, 0);
- } else {
- p->fillRect(opt->rect,fill);
- QRect r = opt->rect.adjusted(0, 0, 0, 1);
- p->drawLine(r.bottomLeft(), r.bottomRight());
- if (completeFrame)
- arrowOpt.rect.adjust(-2, 0, -2, 0);
- if (doubleControls)
- arrowOpt.rect.adjust(0, -4 , 0, -4);
- if (completeFrame && doubleControls)
- arrowOpt.rect.adjust(2, 0, 2, 0);
- q_func()->proxy()->drawPrimitive(QStyle::PE_IndicatorArrowUp, &arrowOpt, p, 0);
- }
-}
-
-void QWindowsMobileStylePrivate::drawScrollbarHandleDown(QPainter *p, QStyleOptionSlider *opt, bool completeFrame, bool secondScrollBar)
-{
-#ifndef QT_NO_SCROLLBAR
-#ifdef Q_WS_WINCE_WM
- if (wm65) {
- tintImagesHigh(opt->palette.highlight().color());
- QRect r = opt->rect;
- if (opt->orientation == Qt::Horizontal) {
- QTransform transform;
- transform.rotate(-90);
- if (opt->state & QStyle::State_Sunken)
- p->drawImage(r.topLeft(), imageScrollbarHandleDownHigh.transformed(transform));
- else
- p->drawImage(r.topLeft(), imageScrollbarHandleDown.transformed(transform));
- } else {
- if (opt->state & QStyle::State_Sunken)
- p->drawImage(r.topLeft(), imageScrollbarHandleDownHigh);
- else
- p->drawImage(r.topLeft(), imageScrollbarHandleDown);
- }
- return ;
- }
-#endif //Q_WS_WINCE_WM
-
- QBrush fill = opt->palette.button();
- if (opt->state & QStyle::State_Sunken)
- fill = opt->palette.shadow();
-
- QStyleOption arrowOpt = *opt;
- if (doubleControls)
- arrowOpt.rect = opt->rect.adjusted(4, 0, -5, 3);
- else
- arrowOpt.rect = opt->rect.adjusted(5, 6, -4, -3);
-
- bool horizontal = (opt->orientation == Qt::Horizontal);
-
- if (horizontal) {
- p->fillRect(opt->rect,fill);
- QRect r = opt->rect.adjusted(0, 0, 0, 0);
- p->drawLine(r.topLeft(), r.bottomLeft());
- if (secondScrollBar)
- p->drawLine(r.topRight(), r.bottomRight());
- if (doubleControls)
- arrowOpt.rect.adjust(0, 4, 0, 4 );
- q_func()->proxy()->drawPrimitive(QStyle::PE_IndicatorArrowRight, &arrowOpt, p, 0);
- } else {
- p->fillRect(opt->rect,fill);
- QRect r = opt->rect.adjusted(0, -1, 0, -1);
- p->drawLine(r.topLeft(), r.topRight());
- if (secondScrollBar)
- p->drawLine(r.bottomLeft() + QPoint(0,1), r.bottomRight() + QPoint(0, 1));
- if (completeFrame)
- arrowOpt.rect.adjust(-2, 0, -2, 0);
- if (doubleControls)
- arrowOpt.rect.adjust(1, 0, 1, 0 );
- if (completeFrame && doubleControls)
- arrowOpt.rect.adjust(1, 0, 1, 0);
- q_func()->proxy()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &arrowOpt, p, 0);
- }
-#endif //QT_NO_SCROLLBAR
-}
-
-void QWindowsMobileStylePrivate::drawScrollbarGroove(QPainter *p,const QStyleOptionSlider *opt)
-{
-#ifndef QT_NO_SCROLLBAR
-#ifdef Q_OS_WINCE_WM
- if (wm65) {
- p->fillRect(opt->rect, QColor(231, 231, 231));
- return ;
- }
-#endif
- QBrush fill;
- if (smartphone) {
- fill = opt->palette.light();
- p->fillRect(opt->rect, fill);
- fill = opt->palette.button();
- QImage image;
-#ifndef QT_NO_IMAGEFORMAT_XPM
- if (opt->orientation == Qt::Horizontal)
- image = QImage(vertlines_xpm);
- else
- image = QImage(horlines_xpm);
-#endif
- image.setColor(1, opt->palette.button().color().rgb());
- fill.setTextureImage(image);
- }
- else {
- fill = opt->palette.light();
- }
- p->fillRect(opt->rect, fill);
-#endif //QT_NO_SCROLLBAR
-}
-
-QWindowsMobileStyle::QWindowsMobileStyle(QWindowsMobileStylePrivate &dd) : QWindowsStyle(dd) {
- qApp->setEffectEnabled(Qt::UI_FadeMenu, false);
- qApp->setEffectEnabled(Qt::UI_AnimateMenu, false);
-}
-
-QWindowsMobileStyle::QWindowsMobileStyle() : QWindowsStyle(*new QWindowsMobileStylePrivate) {
- qApp->setEffectEnabled(Qt::UI_FadeMenu, false);
- qApp->setEffectEnabled(Qt::UI_AnimateMenu, false);
-}
-
-QWindowsMobileStylePrivate::QWindowsMobileStylePrivate() :QWindowsStylePrivate() {
-
-#ifdef Q_WS_WINCE
- doubleControls = qt_wince_is_high_dpi();
- smartphone = qt_wince_is_smartphone();
-#else
- doubleControls = false;
- smartphone = false;
-#endif //Q_WS_WINCE
-
-#ifndef QT_NO_IMAGEFORMAT_XPM
-
- imageArrowDown = QImage(arrowdown_xpm);
- imageArrowUp = QImage(arrowdown_xpm).mirrored();
- imageArrowLeft = QImage(arrowleft_xpm);
- imageArrowRight = QImage(arrowleft_xpm).mirrored(true, false);
- if (doubleControls) {
- imageRadioButton = QImage(radiobutton_xpm);
- imageRadioButtonChecked = QImage(radiochecked_xpm);
- imageChecked = QImage(checkedlight_xpm);
- imageCheckedBold = QImage(checkedbold_xpm);
- imageRadioButtonHighlighted = QImage(highlightedradiobutton_xpm);
- imageClose = QImage(cross_big_xpm);
- imageMaximize = QImage(max_big_xpm);
- imageMinimize = QImage(min_big_xpm);
- imageNormalize = QImage(normal_big_xpm);
- } else {
- imageRadioButton = QImage(radiobutton_low_xpm);
- imageRadioButtonChecked = QImage(radiochecked_low_xpm);
- imageChecked = QImage(checkedlight_low_xpm);
- imageCheckedBold = QImage(checkedbold_low_xpm);
- imageRadioButtonHighlighted = QImage(highlightedradiobutton_low_xpm);
- imageClose = QImage(cross_small_xpm);
- imageMaximize = QImage(max_small_xpm);
- imageMinimize = QImage(min_small_xpm);
- imageNormalize = QImage(normal_small_xpm);
- }
-
- setupWindowsMobileStyle65();
-
-
- imageArrowDownBig = QImage(arrowdown_big_xpm);
- imageArrowUpBig = QImage(arrowdown_big_xpm).mirrored();
- imageArrowLeftBig = QImage(arrowleft_big_xpm);
- imageArrowRightBig = QImage(arrowleft_big_xpm).mirrored(true, false);
-
-#endif
-}
-
-void QWindowsMobileStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
-
- bool doRestore = false;
- QRect rect = option->rect;
- painter->setClipping(false);
-
- switch (element) {
- case PE_PanelButtonTool: {
- int penSize = 1;
- if (d->doubleControls)
- penSize = 2;
- if (widget)
- if (QWidget *parent = widget->parentWidget())
-#ifndef QT_NO_TABWIDGET
- if (qobject_cast<QTabWidget *>(parent->parentWidget())) {
-#else
- if (false) {
-#endif //QT_NO_TABBAR
- rect.adjust(0,2*penSize,0,-1*penSize);
- qDrawPlainRect(painter, rect, option->palette.shadow().color(), penSize, &option->palette.light());
- if (option->state & (State_Sunken))
- qDrawPlainRect(painter, rect, option->palette.shadow().color(), penSize, &option->palette.shadow());
- }
- else {
- if (!(option->state & State_AutoRaise) || (option->state & (State_Sunken | State_On)))
- qDrawPlainRect(painter,option->rect.adjusted(0, penSize, 0, -1 * penSize) ,
- option->palette.button().color(), 0, &option->palette.button());
- if (option->state & (State_Sunken)) {
- qDrawPlainRect(painter, rect, option->palette.shadow().color(), penSize, &option->palette.light());
- }
- if (option->state & (State_On)){
- QBrush fill = QBrush(option->palette.light().color());
- painter->fillRect(rect.adjusted(windowsItemFrame , windowsItemFrame ,
- -windowsItemFrame , -windowsItemFrame ), fill);
- qDrawPlainRect(painter, rect, option->palette.shadow().color(), penSize, &option->palette.light());
- }
- }
- break; }
- case PE_IndicatorButtonDropDown:
- if (d->doubleControls)
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(), 2, &option->palette.button());
- else
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(), 1, &option->palette.button());
- break;
-#ifndef QT_NO_TABBAR
- case PE_IndicatorTabTear:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- bool rtl = tab->direction == Qt::RightToLeft;
- QRect rect = tab->rect;
- QPainterPath path;
- rect.setTop(rect.top() + ((tab->state & State_Selected) ? 1 : 3));
- rect.setBottom(rect.bottom() - ((tab->state & State_Selected) ? 0 : 2));
- path.moveTo(QPoint(rtl ? rect.right() : rect.left(), rect.top()));
- int count = 3;
- for(int jags = 1; jags <= count; ++jags, rtl = !rtl)
- path.lineTo(QPoint(rtl ? rect.left() : rect.right(), rect.top() + jags * rect.height()/count));
- painter->setPen(QPen(tab->palette.light(), qreal(.8)));
- painter->setBrush(tab->palette.background());
- painter->setRenderHint(QPainter::Antialiasing);
- painter->drawPath(path);
- }
- break;
-#endif //QT_NO_TABBAR
-
-#ifndef QT_NO_TOOLBAR
- case PE_IndicatorToolBarSeparator: {
- painter->save();
- QPoint p1, p2;
- if (option->state & State_Horizontal) {
- p1 = QPoint(option->rect.width()/2, 0);
- p2 = QPoint(p1.x(), option->rect.height());
- } else {
- p1 = QPoint(0, option->rect.height()/2);
- p2 = QPoint(option->rect.width(), p1.y());
- }
-
-
- painter->setPen(option->palette.mid().color());
- if (d->doubleControls) {
- QPen pen = painter->pen();
- pen.setWidth(2);
- pen.setCapStyle(Qt::FlatCap);
- painter->setPen(pen);
- }
- painter->drawLine(p1, p2);
- painter->restore();
- break; }
-#endif // QT_NO_TOOLBAR
- case PE_IndicatorToolBarHandle:
- painter->save();
- painter->translate(option->rect.x(), option->rect.y());
- if (option->state & State_Horizontal) {
- int x = option->rect.width() / 2 - 4;
- if (QApplication::layoutDirection() == Qt::RightToLeft)
- x -= 2;
- if (option->rect.height() > 4) {
- qDrawWinButton(painter,x-1,0,7,option->rect.height(), option->palette, false, 0);
-
- qDrawShadePanel(painter, x, 1, 3, option->rect.height() - 1,
- option->palette, false, 0);
- qDrawShadePanel(painter, x + 3, 1, 3, option->rect.height() - 1,
- option->palette, false, 0);
- painter->setPen(option->palette.button().color());
- }
- } else {
- if (option->rect.width() > 4) {
- int y = option->rect.height() / 2 - 4;
- qDrawShadePanel(painter, 2, y, option->rect.width() - 2, 3,
- option->palette, false, 0);
- qDrawShadePanel(painter, 2, y + 3, option->rect.width() - 2, 3,
- option->palette, false, 0);
- }
- }
- painter->restore();
- break;
-
-#ifndef QT_NO_PROGRESSBAR
- case PE_IndicatorProgressChunk: {
- bool vertical = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option))
- vertical = (pb2->orientation == Qt::Vertical);
- if (!vertical) {
- painter->fillRect(option->rect.x(), option->rect.y()+2, option->rect.width(), option->rect.height()-4,
- option->palette.brush(QPalette::Highlight));
- } else {
- painter->fillRect(option->rect.x()+2, option->rect.y(), option->rect.width()-4, option->rect.height(),
- option->palette.brush(QPalette::Highlight));
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
-
- case PE_FrameButtonTool: {
-#ifndef QT_NO_DOCKWIDGET
- if (widget && widget->inherits("QDockWidgetTitleButton")) {
- if (const QDockWidget *dw = qobject_cast<const QDockWidget *>(widget->parent()))
- if (dw->isFloating()){
- qDrawPlainRect(painter,option->rect.adjusted(1, 1, 0, 0),
- option->palette.shadow().color(),1,&option->palette.button());
- return;
- }
- }
-#endif // QT_NO_DOCKWIDGET
- QBrush fill;
- bool stippled;
- bool panel = (element == PE_PanelButtonTool);
- if ((!(option->state & State_Sunken ))
- && (!(option->state & State_Enabled)
- || ((option->state & State_Enabled ) && !(option->state & State_MouseOver)))
- && (option->state & State_On)) {
- fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- stippled = true;
- } else {
- fill = option->palette.brush(QPalette::Button);
- stippled = false;
- }
- if (option->state & (State_Raised | State_Sunken | State_On)) {
- if (option->state & State_AutoRaise) {
- if(option->state & (State_Enabled | State_Sunken | State_On)){
- if (panel)
- qDrawPlainRect(painter, option->rect,option->palette.shadow().color(),d->doubleControls, &fill);
- else
- qDrawPlainRect(painter, option->rect,option->palette.shadow().color(),d->doubleControls, &fill);
- }
- if (stippled) {
- painter->setPen(option->palette.button().color());
- painter->drawRect(option->rect.adjusted(1, 1, -2, -2));
- }
- } else {
- qDrawPlainRect(painter, option->rect,option->palette.shadow().color(),d->doubleControls, &fill);
- }
- } else {
- painter->fillRect(option->rect, fill);
- }
- break; }
-
- case PE_FrameFocusRect:
- if (const QStyleOptionFocusRect *fropt = qstyleoption_cast<const QStyleOptionFocusRect *>(option)) {
- //### check for d->alt_down
- int penSize;
- d->doubleControls ? penSize = 2 : penSize = 1;
- bool alternateFocusStyle = false;
- if (!widget)
- alternateFocusStyle = true;
-#ifndef QT_NO_COMBOBOX
- if (qobject_cast<const QComboBox*>(widget))
- alternateFocusStyle = true;
-#endif
- if (!(fropt->state & State_KeyboardFocusChange) && !styleHint(SH_UnderlineShortcut, option))
- return;
- QRect r = option->rect;
- painter->save();
- painter->setBackgroundMode(Qt::TransparentMode);
- if (alternateFocusStyle) {
- QColor bg_col = fropt->backgroundColor;
- if (!bg_col.isValid())
- bg_col = painter->background().color();
- // Create an "XOR" color.
- QColor patternCol((bg_col.red() ^ 0xff) & 0xff,
- (bg_col.green() ^ 0xff) & 0xff,
- (bg_col.blue() ^ 0xff) & 0xff);
- painter->setBrush(QBrush(patternCol, Qt::Dense4Pattern));
- painter->setBrushOrigin(r.topLeft());
- }
- else {
- painter->setPen(option->palette.highlight().color());
- painter->setBrush(option->palette.highlight());
- }
- painter->setPen(Qt::NoPen);
- painter->setBrushOrigin(r.topLeft());
- painter->drawRect(r.left(), r.top(), r.width(), penSize); // Top
- painter->drawRect(r.left(), r.bottom(), r.width() + penSize - 1, penSize); // Bottom
- painter->drawRect(r.left(), r.top(), penSize, r.height()); // Left
- painter->drawRect(r.right(), r.top(), penSize, r.height()); // Right
- painter->restore();
- }
- break;
-
- case PE_PanelButtonBevel: {
- QBrush fill;
- bool panel = element != PE_FrameButtonBevel;
- painter->setBrushOrigin(option->rect.topLeft());
- if (!(option->state & State_Sunken) && (option->state & State_On))
- fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- else
- fill = option->palette.brush(QPalette::Button);
-
- if (option->state & (State_Raised | State_On | State_Sunken)) {
- if (d->doubleControls)
- qDrawPlainRect(painter, option->rect,option->palette.shadow().color(),2,&fill);
- else
- qDrawPlainRect(painter, option->rect,option->palette.shadow().color(),1,&fill);
- } else {
- if (panel)
- painter->fillRect(option->rect, fill);
- else
- painter->drawRect(option->rect);
- }
- break; }
-
- case PE_FrameGroupBox:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
-
- const QStyleOptionFrameV2 *frame2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(option);
- if (frame2 && !(frame2->features & QStyleOptionFrameV2::Flat)) {
- QPen oldPen = painter->pen();
- QRect r = frame->rect;
- painter->setPen(frame->palette.shadow().color());
- painter->fillRect(r.x(), r.y(), r.x() + r.width()-1,
- r.y() + r.height() - windowsMobileFrameGroupBoxOffset,
- frame->palette.light());
- painter ->drawLine(r.topLeft() + QPoint(-2, 1), r.topRight()+ QPoint(0, 1));
- if (d->doubleControls)
- painter ->drawLine(r.topLeft() + QPoint(-2, 2), r.topRight()+ QPoint(0, 2));
- painter->setPen(oldPen);
- }
- }
- break;
-
- case PE_IndicatorCheckBox: {
- QBrush fill;
- QRect r = d->doubleControls ? option->rect.adjusted(0,1,0,-1) : option->rect;
- if (option->state & State_NoChange)
- fill = QBrush(option->palette.shadow().color(), Qt::Dense4Pattern);
- else if (option->state & State_Sunken)
- fill = option->palette.button();
- else if (option->state & State_Enabled)
- fill = option->palette.base();
- else
- fill = option->palette.background();
- painter->save();
- doRestore = true;
- if (d->doubleControls && (option->state & State_NoChange))
- painter->fillRect(r, fill);
- else
- painter->fillRect(option->rect, fill);
- painter->setPen(option->palette.shadow().color());
- painter->drawLine(r.topLeft(), r.topRight());
- painter->drawLine(r.topRight(), r.bottomRight());
- painter->drawLine(r.bottomLeft(), r.bottomRight());
- painter->drawLine(r.bottomLeft(), r.topLeft());
- if (d->doubleControls) {
- QRect r0 = r.adjusted(1, 1, -1, -1);
- painter->drawLine(r0.topLeft(), r0.topRight());
- painter->drawLine(r0.topRight(), r0.bottomRight());
- painter->drawLine(r0.bottomLeft(), r0.bottomRight());
- painter->drawLine(r0.bottomLeft(), r0.topLeft());
- }
- if (option->state & State_HasFocus) {
- painter->setPen(option->palette.highlight().color());
- QRect r2 = d->doubleControls ? r.adjusted(2, 2, -2, -2) : r.adjusted(1, 1, -1, -1);
- painter->drawLine(r2.topLeft(), r2.topRight());
- painter->drawLine(r2.topRight(), r2.bottomRight());
- painter->drawLine(r2.bottomLeft(), r2.bottomRight());
- painter->drawLine(r2.bottomLeft(), r2.topLeft());
- if (d->doubleControls) {
- QRect r3 = r2.adjusted(1, 1, -1, -1);
- painter->drawLine(r3.topLeft(), r3.topRight());
- painter->drawLine(r3.topRight(), r3.bottomRight());
- painter->drawLine(r3.bottomLeft(), r3.bottomRight());
- painter->drawLine(r3.bottomLeft(), r3.topLeft());
- }
- painter->setPen(option->palette.shadow().color());
- }
- //fall through...
- }
- case PE_IndicatorViewItemCheck:
- case PE_Q3CheckListIndicator: {
- if (!doRestore) {
- painter->save();
- doRestore = true;
- }
- if (element == PE_Q3CheckListIndicator || element == PE_IndicatorViewItemCheck) {
- painter->setPen(option->palette.shadow().color());
- if (option->state & State_NoChange)
- painter->setBrush(option->palette.brush(QPalette::Button));
- if (d->doubleControls) {
- QRect r = QRect(option->rect.x(), option->rect.y(), windowsMobileitemViewCheckBoxSize * 2, windowsMobileitemViewCheckBoxSize * 2);
- qDrawPlainRect(painter, r, option->palette.shadow().color(), 2);
- } else {
- QRect r = QRect(option->rect.x(), option->rect.y(), windowsMobileitemViewCheckBoxSize, windowsMobileitemViewCheckBoxSize);
- qDrawPlainRect(painter, r, option->palette.shadow().color(), 1);
- }
- if (option->state & State_Enabled)
- d->imageChecked.setColor(1, option->palette.shadow().color().rgba());
- else
- d->imageChecked.setColor(1, option->palette.dark().color().rgba());
- if (!(option->state & State_Off)) {
- if (d->doubleControls)
- painter->drawImage(option->rect.x(), option->rect.y(), d->imageChecked);
- else
- painter->drawImage(option->rect.x() + 3, option->rect.y() + 3, d->imageChecked);
- }
- }
- else {
- if (option->state & State_NoChange)
- d->imageCheckedBold.setColor(1, option->palette.dark().color().rgba());
- else if (option->state & State_Enabled)
- d->imageCheckedBold.setColor(1, option->palette.shadow().color().rgba());
- else
- d->imageCheckedBold.setColor(1, option->palette.dark().color().rgba());
- if (!(option->state & State_Off)) {
- if (d->doubleControls)
- painter->drawImage(option->rect.x() + 2, option->rect.y(), d->imageCheckedBold);
- else
- painter->drawImage(option->rect.x() + 3, option->rect.y() + 3, d->imageCheckedBold);
- }
- }
- if (doRestore)
- painter->restore();
- break; }
- case PE_IndicatorRadioButton: {
- painter->save();
-
- if (option->state & State_HasFocus) {
- d->imageRadioButtonHighlighted.setColor(1, option->palette.shadow().color().rgba());
- d->imageRadioButtonHighlighted.setColor(2, option->palette.highlight().color().rgba());
- painter->drawImage(option->rect.x(), option->rect.y(), d->imageRadioButtonHighlighted);
- }
- else {
- d->imageRadioButton.setColor(1, option->palette.shadow().color().rgba());
- painter->drawImage(option->rect.x(), option->rect.y(), d->imageRadioButton);
- }
- if (option->state & (State_Sunken | State_On)) {
- if (option->state & State_Enabled)
- d->imageRadioButtonChecked.setColor(1, option->palette.shadow().color().rgba());
- else
- d->imageRadioButtonChecked.setColor(1, option->palette.dark().color().rgba());
-
- static const int offset = d->doubleControls ? 6 : 3;
- painter->drawImage(option->rect.x() + offset, option->rect.y() + offset, d->imageRadioButtonChecked);
- }
- painter->restore();
- break; }
- case PE_PanelButtonCommand:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- QBrush fill;
- State flags = option->state;
- QPalette pal = option->palette;
- QRect r = option->rect;
- if ((flags & State_Sunken || flags & State_On) )
- fill = pal.brush(QPalette::Shadow);
- else
- fill = pal.brush(QPalette::Button);
- int singleLine = 1;
- int doubleLine = 2;
- if (d->doubleControls) {
- singleLine = 2;
- doubleLine = 4;
- }
- if (button->features & QStyleOptionButton::DefaultButton && flags & State_Sunken) {
- if (d->doubleControls) {
- qDrawPlainRect(painter, r, pal.shadow().color(), 1, &fill);
- qDrawPlainRect(painter, r.adjusted(1, 1, -1, 1), pal.shadow().color(), 1, &fill);
- }
- else {
- qDrawPlainRect(painter, r, pal.shadow().color(), 1, &fill);
- }
- } else if (flags & (State_Raised | State_Sunken | State_On | State_Sunken)) {
- qDrawPlainRect(painter, r, pal.shadow().color(), singleLine, &fill);
- } else {
- painter->fillRect(r, fill);
- }
- }
- break;
- case PE_FrameDefaultButton: {
- painter->save();
- painter->setPen(option->palette.shadow().color());
- QRect rect = option->rect;
- if (d->doubleControls) {
- rect.adjust(1, 1, -2, -2);
- painter->drawRect(rect);
- painter->drawRect(rect.adjusted(1, 1, -1, -1));
- }
-
- else {
- rect.adjust(2, 2, -3, -3);
- painter->drawRect(rect);
- }
- painter->restore();
- break; }
- case PE_IndicatorSpinPlus:
- case PE_IndicatorSpinMinus: {
- QRect r = option->rect;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, option, widget)+2;
- QRect br = r.adjusted(fw, fw, -fw, -fw);
- int offset = (option->state & State_Sunken) ? 1 : 0;
- int step = (br.width() + 4) / 5;
- painter->fillRect(br.x() + offset, br.y() + offset +br.height() / 2 - step / 2,
- br.width(), step, option->palette.buttonText());
- if (element == PE_IndicatorSpinPlus)
- painter->fillRect(br.x() + br.width() / 2 - step / 2 + offset, br.y() + offset+4,
- step, br.height() - 7, option->palette.buttonText());
- break; }
- case PE_IndicatorSpinUp:
- case PE_IndicatorSpinDown: {
- painter->save();
- QPoint points[7];
- switch (element) {
- case PE_IndicatorSpinUp:
- points[0] = QPoint(-2, -4);
- points[1] = QPoint(-2, 2);
- points[2] = QPoint(-1, -3);
- points[3] = QPoint(-1, 1);
- points[4] = QPoint(0, -2);
- points[5] = QPoint(0, 0);
- points[6] = QPoint(1, -1);
- break;
- case PE_IndicatorSpinDown:
- points[0] = QPoint(0, -4);
- points[1] = QPoint(0, 2);
- points[2] = QPoint(-1, -3);
- points[3] = QPoint(-1, 1);
- points[4] = QPoint(-2, -2);
- points[5] = QPoint(-2, 0);
- points[6] = QPoint(-3, -1);
- break;
- default:
- break;
- }
- if (option->state & State_Sunken)
- painter->translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal),
- proxy()->pixelMetric(PM_ButtonShiftVertical));
- if (option->state & State_Enabled) {
- painter->translate(option->rect.x() + option->rect.width() / 2,
- option->rect.y() + option->rect.height() / 2);
- painter->setPen(option->palette.buttonText().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- } else {
- painter->translate(option->rect.x() + option->rect.width() / 2 + 1,
- option->rect.y() + option->rect.height() / 2 + 1);
- painter->setPen(option->palette.light().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- painter->translate(-1, -1);
- painter->setPen(option->palette.mid().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- }
- painter->restore();
- break; }
-
- case PE_IndicatorArrowUpBig:
- case PE_IndicatorArrowDownBig:
- case PE_IndicatorArrowLeftBig:
- case PE_IndicatorArrowRightBig:
-
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowLeft: {
- painter->save();
-
- if (d->doubleControls) {
- QColor color;
- if (option->state & State_Sunken)
- color = option->palette.light().color();
- else
- color = option->palette.buttonText().color();
- QImage image;
- int xoffset, yoffset;
- bool isTabBarArrow = widget && widget->parent()
- && widget->inherits("QToolButton")
- && widget->parent()->inherits("QTabBar");
-
- switch (element) {
- case PE_IndicatorArrowUp:
- image = d->imageArrowUp;
- xoffset = 1;
- yoffset = 12;
- break;
- case PE_IndicatorArrowDown:
- image = d->imageArrowDown;
- xoffset = 1;
- yoffset =12;
- break;
- case PE_IndicatorArrowLeft:
- image = d->imageArrowLeft;
- xoffset = 8;
- yoffset = isTabBarArrow ? 12 : 2;
- break;
- case PE_IndicatorArrowRight:
- image = d->imageArrowRight;
- xoffset = 8;
- yoffset = isTabBarArrow ? 12 : 2;
- break;
- case PE_IndicatorArrowUpBig:
- image = d->imageArrowUpBig;
- xoffset = 3;
- yoffset = 12;
- break;
- case PE_IndicatorArrowDownBig:
- image = d->imageArrowDownBig;
- xoffset = 2;
- yoffset =12;
- break;
- case PE_IndicatorArrowLeftBig:
- image = d->imageArrowLeftBig;
- xoffset = 8;
- yoffset = 2;
- break;
- case PE_IndicatorArrowRightBig:
- image = d->imageArrowRightBig;
- xoffset = 8;
- yoffset = 2;
- break;
- default:
- break;
- }
- image.setColor(1, color.rgba());
- painter->drawImage(option->rect.x() + xoffset, option->rect.y() + yoffset, image);
- }
- else {
- QPoint points[7];
- switch (element) {
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowUpBig:
- points[0] = QPoint(-3, 1);
- points[1] = QPoint(3, 1);
- points[2] = QPoint(-2, 0);
- points[3] = QPoint(2, 0);
- points[4] = QPoint(-1, -1);
- points[5] = QPoint(1, -1);
- points[6] = QPoint(0, -2);
- break;
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowDownBig:
- points[0] = QPoint(-3, -1);
- points[1] = QPoint(3, -1);
- points[2] = QPoint(-2, 0);
- points[3] = QPoint(2, 0);
- points[4] = QPoint(-1, 1);
- points[5] = QPoint(1, 1);
- points[6] = QPoint(0, 2);
- break;
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowRightBig:
- points[0] = QPoint(-2, -3);
- points[1] = QPoint(-2, 3);
- points[2] = QPoint(-1, -2);
- points[3] = QPoint(-1, 2);
- points[4] = QPoint(0, -1);
- points[5] = QPoint(0, 1);
- points[6] = QPoint(1, 0);
- break;
- case PE_IndicatorArrowLeft:
- case PE_IndicatorArrowLeftBig:
- points[0] = QPoint(0, -3);
- points[1] = QPoint(0, 3);
- points[2] = QPoint(-1, -2);
- points[3] = QPoint(-1, 2);
- points[4] = QPoint(-2, -1);
- points[5] = QPoint(-2, 1);
- points[6] = QPoint(-3, 0);
- break;
- default:
- break;
- }
- if (option->state & State_Sunken)
- painter->setPen(option->palette.light().color());
- else
- painter->setPen(option->palette.buttonText().color());
- if (option->state & State_Enabled) {
- painter->translate(option->rect.x() + option->rect.width() / 2,
- option->rect.y() + option->rect.height() / 2 - 1);
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- } else {
- painter->translate(option->rect.x() + option->rect.width() / 2,
- option->rect.y() + option->rect.height() / 2 - 1);
- painter->setPen(option->palette.mid().color());
- painter->drawLine(points[0], points[1]);
- painter->drawLine(points[2], points[3]);
- painter->drawLine(points[4], points[5]);
- painter->drawPoint(points[6]);
- }
- }
- painter->restore();
- break; }
-#ifndef QT_NO_TABWIDGET
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *tab = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option)) {
- QRect rect = option->rect;
- QPalette pal = option->palette;
- painter->save();
- QBrush fill = pal.light();
- painter->fillRect(rect, fill);
- painter->setPen(pal.shadow().color());
- if (d->doubleControls) {
- QPen pen = painter->pen();
- pen.setWidth(2);
- pen.setCapStyle(Qt::FlatCap);
- painter->setPen(pen);
- }
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
-#ifdef Q_WS_WINCE_WM
- if (!d->wm65)
-#endif
- {
- if (d->doubleControls)
- painter->drawLine(rect.topLeft() + QPoint(0, 1), rect.topRight() + QPoint(0, 1));
- else
- painter->drawLine(rect.topLeft(), rect.topRight());
- }
- break;
- case QTabBar::RoundedSouth:
-#ifdef Q_WS_WINCE_WM
- if (!d->wm65)
-#endif
- {
- if (d->doubleControls)
- painter->drawLine(rect.bottomLeft(), rect.bottomRight());
- else
- painter->drawLine(rect.bottomLeft(), rect.bottomRight());
- }
- break;
- case QTabBar::RoundedEast:
-#ifdef Q_WS_WINCE_WM
- if (!d->wm65)
-#endif
- painter->drawLine(rect.topRight(), rect.bottomRight());
- break;
- case QTabBar::RoundedWest:
-#ifdef Q_WS_WINCE_WM
- if (!d->wm65)
-#endif
- painter->drawLine(rect.topLeft(), rect.bottomLeft());
- break;
- case QTabBar::TriangularWest:
- case QTabBar::TriangularEast:
- case QTabBar::TriangularSouth:
- case QTabBar::TriangularNorth:
- if (d->doubleControls)
- qDrawPlainRect(painter, rect.adjusted(0,-2,0,0), option->palette.shadow().color(),2,&pal.light());
- else
- qDrawPlainRect(painter, rect, option->palette.shadow().color(),1,&pal.light());
- break;
- default:
- break;
- }
- painter->restore();
- }
- break;
-#endif //QT_NO_TABBAR
-#ifndef QT_NO_ITEMVIEWS
- case PE_PanelItemViewRow:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- QPalette::ColorGroup cg = vopt->state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- if ((vopt->state & QStyle::State_Selected) && proxy()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, option, widget))
- d->drawPanelItemViewSelected(painter, vopt);
- else if (vopt->features & QStyleOptionViewItemV2::Alternate)
- painter->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::AlternateBase));
- else if (!(vopt->state & QStyle::State_Enabled))
- painter->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::Base));
- }
- break;
- case PE_PanelItemViewItem:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- QPalette::ColorGroup cg = vopt->state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- if (vopt->showDecorationSelected && (vopt->state & QStyle::State_Selected)) {
- d->drawPanelItemViewSelected(painter, vopt);
- } else {
- if (vopt->backgroundBrush.style() != Qt::NoBrush) {
- QPointF oldBO = painter->brushOrigin();
- painter->setBrushOrigin(vopt->rect.topLeft());
- painter->fillRect(vopt->rect, vopt->backgroundBrush);
- painter->setBrushOrigin(oldBO);
- }
-
- if (vopt->state & QStyle::State_Selected) {
- QRect textRect = proxy()->subElementRect(QStyle::SE_ItemViewItemText, option, widget);
- d->drawPanelItemViewSelected(painter, vopt, textRect);
- }
- }
- }
- break;
-#endif //QT_NO_ITEMVIEWS
-
- case PE_FrameWindow: {
- QPalette popupPal = option->palette;
- popupPal.setColor(QPalette::Light, option->palette.background().color());
- popupPal.setColor(QPalette::Midlight, option->palette.light().color());
- if (d->doubleControls)
- qDrawPlainRect(painter, option->rect, popupPal.shadow().color(),2,0);
- else
- qDrawPlainRect(painter, option->rect, popupPal.shadow().color(),1,0);
- break; }
- case PE_FrameTabBarBase: {
- break; }
- case PE_Widget:
- break;
- case PE_IndicatorMenuCheckMark: {
- int markW = option->rect.width() > 7 ? 7 : option->rect.width();
- int markH = markW;
- if (d->doubleControls)
- markW*=2;
- markH*=2;
- int posX = option->rect.x() + (option->rect.width() - markW)/2 + 1;
- int posY = option->rect.y() + (option->rect.height() - markH)/2;
-
- QVector<QLineF> a;
- a.reserve(markH);
-
- int i, xx, yy;
- xx = posX;
- yy = 3 + posY;
- for (i = 0; i < markW/2; ++i) {
- a << QLineF(xx, yy, xx, yy + 2);
- ++xx;
- ++yy;
- }
- yy -= 2;
- for (; i < markH; ++i) {
- a << QLineF(xx, yy, xx, yy + 2);
- ++xx;
- --yy;
- }
- if (!(option->state & State_Enabled) && !(option->state & State_On)) {
- int pnt;
- painter->setPen(option->palette.highlightedText().color());
- QPoint offset(1, 1);
- for (pnt = 0; pnt < a.size(); ++pnt)
- a[pnt].translate(offset.x(), offset.y());
- painter->drawLines(a);
- for (pnt = 0; pnt < a.size(); ++pnt)
- a[pnt].translate(offset.x(), offset.y());
- }
- painter->setPen(option->palette.text().color());
- painter->drawLines(a);
- break; }
- case PE_IndicatorBranch: {
- // Copied from the Windows style.
- static const int decoration_size = d->doubleControls ? 18 : 9;
- static const int ofsA = d->doubleControls ? 4 : 2;
- static const int ofsB = d->doubleControls ? 8 : 4;
- static const int ofsC = d->doubleControls ? 12 : 6;
- static const int ofsD = d->doubleControls ? 1 : 0;
- int mid_h = option->rect.x() + option->rect.width() / 2;
- int mid_v = option->rect.y() + option->rect.height() / 2;
- int bef_h = mid_h;
- int bef_v = mid_v;
- int aft_h = mid_h;
- int aft_v = mid_v;
- if (option->state & State_Children) {
- int delta = decoration_size / 2;
- bef_h -= delta;
- bef_v -= delta;
- aft_h += delta;
- aft_v += delta;
- QPen oldPen = painter->pen();
- QPen crossPen = oldPen;
- crossPen.setWidth(2);
- painter->setPen(crossPen);
- painter->drawLine(bef_h + ofsA + ofsD, bef_v + ofsB + ofsD, bef_h + ofsC + ofsD, bef_v + ofsB + ofsD);
- if (!(option->state & State_Open))
- painter->drawLine(bef_h + ofsB + ofsD, bef_v + ofsA + ofsD, bef_h + ofsB + ofsD, bef_v + ofsC + ofsD);
- painter->setPen(option->palette.dark().color());
- painter->drawRect(bef_h, bef_v, decoration_size - 1, decoration_size - 1);
- if (d->doubleControls)
- painter->drawRect(bef_h + 1, bef_v + 1, decoration_size - 3, decoration_size - 3);
- painter->setPen(oldPen);
- }
- QBrush brush(option->palette.dark().color(), Qt::Dense4Pattern);
- if (option->state & State_Item) {
- if (option->direction == Qt::RightToLeft)
- painter->fillRect(option->rect.left(), mid_v, bef_h - option->rect.left(), 1, brush);
- else
- painter->fillRect(aft_h, mid_v, option->rect.right() - aft_h + 1, 1, brush);
- }
- if (option->state & State_Sibling)
- painter->fillRect(mid_h, aft_v, 1, option->rect.bottom() - aft_v + 1, brush);
- if (option->state & (State_Open | State_Children | State_Item | State_Sibling))
- painter->fillRect(mid_h, option->rect.y(), 1, bef_v - option->rect.y(), brush);
- break; }
- case PE_Frame:
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(),
- d->doubleControls ? 2 : 1, &option->palette.background());
- break;
- case PE_FrameLineEdit:
- case PE_FrameMenu:
- if (d->doubleControls)
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(),2);
- else
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(),1);
- break;
- case PE_FrameStatusBar:
- if (d->doubleControls)
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(),2,0);
- else
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(),1,0);
- break;
-
- default:
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- break;
- }
-}
-
-void QWindowsMobileStyle::drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const {
-
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
-
-
- painter->setClipping(false);
- switch (element) {
- case CE_MenuBarEmptyArea:
- painter->setClipping(true);
- QWindowsStyle::drawControl(element, option, painter, widget);
- break;
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- QRect br = button->rect;
- int dbi = proxy()->pixelMetric(PM_ButtonDefaultIndicator, button, widget);
-
- if (button->features & QStyleOptionButton::AutoDefaultButton)
- br.setCoords(br.left() + dbi, br.top() + dbi, br.right() - dbi, br.bottom() - dbi);
- QStyleOptionButton tmpBtn = *button;
- tmpBtn.rect = br;
- proxy()->drawPrimitive(PE_PanelButtonCommand, &tmpBtn, painter, widget);
- if (button->features & QStyleOptionButton::HasMenu) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget);
- QRect ir = button->rect;
- QStyleOptionButton newButton = *button;
- if (d->doubleControls)
- newButton.rect = QRect(ir.right() - mbi, ir.height() - 30, mbi, ir.height() - 4);
- else
- newButton.rect = QRect(ir.right() - mbi, ir.height() - 20, mbi, ir.height() - 4);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newButton, painter, widget);
- }
- if (button->features & QStyleOptionButton::DefaultButton)
- proxy()->drawPrimitive(PE_FrameDefaultButton, option, painter, widget);
- }
- break;
- case CE_RadioButton:
- case CE_CheckBox:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool isRadio = (element == CE_RadioButton);
- QStyleOptionButton subopt = *button;
- subopt.rect = proxy()->subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, button, widget);
- proxy()->drawPrimitive(isRadio ? PE_IndicatorRadioButton : PE_IndicatorCheckBox,
- &subopt, painter, widget);
- subopt.rect = proxy()->subElementRect(isRadio ? SE_RadioButtonContents
- : SE_CheckBoxContents, button, widget);
- proxy()->drawControl(isRadio ? CE_RadioButtonLabel : CE_CheckBoxLabel, &subopt, painter, widget);
- if (button->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*button);
- fropt.rect = proxy()->subElementRect(isRadio ? SE_RadioButtonFocusRect
- : SE_CheckBoxFocusRect, button, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- }
- break;
- case CE_RadioButtonLabel:
- case CE_CheckBoxLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- uint alignment = visualAlignment(button->direction, Qt::AlignLeft | Qt::AlignVCenter);
- if (!styleHint(SH_UnderlineShortcut, button, widget))
- alignment |= Qt::TextHideMnemonic;
- QPixmap pix;
- QRect textRect = button->rect;
- if (!button->icon.isNull()) {
- pix = button->icon.pixmap(button->iconSize, button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled);
- proxy()->drawItemPixmap(painter, button->rect, alignment, pix);
- if (button->direction == Qt::RightToLeft)
- textRect.setRight(textRect.right() - button->iconSize.width() - 4);
- else
- textRect.setLeft(textRect.left() + button->iconSize.width() + 4);
- }
- if (!button->text.isEmpty()){
- if (button->state & State_Enabled)
- proxy()->drawItemText(painter, textRect, alignment | Qt::TextShowMnemonic,
- button->palette, false, button->text, QPalette::WindowText);
- else
- proxy()->drawItemText(painter, textRect, alignment | Qt::TextShowMnemonic,
- button->palette, false, button->text, QPalette::Mid);
- }
- }
- break;
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBarGroove:
- if (d->doubleControls)
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(), 2, &option->palette.brush(QPalette::Window));
- else
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(), 1, &option->palette.brush(QPalette::Window));
- break;
-#endif //QT_NO_PROGRESSBAR
-#ifndef QT_NO_TABBAR
- case CE_TabBarTab:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- proxy()->drawControl(CE_TabBarTabShape, tab, painter, widget);
- proxy()->drawControl(CE_TabBarTabLabel, tab, painter, widget);
- }
- break;
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
-
- if (tab->shape == QTabBar::RoundedNorth || tab->shape == QTabBar::RoundedEast ||
- tab->shape == QTabBar::RoundedSouth || tab->shape == QTabBar::RoundedWest) {
- d->drawTabBarTab(painter, tab);
- } else {
- QCommonStyle::drawControl(element, option, painter, widget);
- }
- break; }
-
-#endif // QT_NO_TABBAR
-
-#ifndef QT_NO_TOOLBAR
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
- QRect rect = option->rect;
- painter->save();
- painter->setPen(option->palette.dark().color());
- painter->fillRect(rect,option->palette.button());
- if (d->doubleControls) {
- QPen pen = painter->pen();
- pen.setWidth(4);
- painter->setPen(pen);
- }
- if (toolBar->toolBarArea == Qt::TopToolBarArea)
- painter->drawLine(rect.bottomLeft(), rect.bottomRight());
- else
- painter->drawLine(rect.topLeft(), rect.topRight());
- painter->restore();
- break; }
-#endif //QT_NO_TOOLBAR
- case CE_Header:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- QRegion clipRegion = painter->clipRegion();
- painter->setClipRect(option->rect);
- proxy()->drawControl(CE_HeaderSection, header, painter, widget);
- QStyleOptionHeader subopt = *header;
- subopt.rect = proxy()->subElementRect(SE_HeaderLabel, header, widget);
- if (header->state & State_Sunken)
- subopt.palette.setColor(QPalette::ButtonText, header->palette.brightText().color());
- subopt.state |= QStyle::State_On;
- if (subopt.rect.isValid())
- proxy()->drawControl(CE_HeaderLabel, &subopt, painter, widget);
- if (header->sortIndicator != QStyleOptionHeader::None) {
- subopt.rect = proxy()->subElementRect(SE_HeaderArrow, option, widget);
- proxy()->drawPrimitive(PE_IndicatorHeaderArrow, &subopt, painter, widget);
- }
- painter->setClipRegion(clipRegion);
- }
- break;
-
- case CE_HeaderSection:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- QBrush fill;
- QColor color;
- QRect rect = option->rect;
- painter->setPen(option->palette.shadow().color());
-
- int penSize = 1;
-
- if (d->doubleControls) {
- penSize = 2;
- QPen pen = painter->pen();
- pen.setWidth(2);
- pen.setCapStyle(Qt::FlatCap);
- painter->setPen(pen);
- }
-
- //fix Frame
-
- if (header->position == QStyleOptionHeader::End
- || (header->position == QStyleOptionHeader::OnlyOneSection
- && !header->text.isEmpty()))
- if (Qt::Horizontal == header->orientation )
- rect.adjust(0, 0, penSize, 0);
- else
- rect.adjust(0, 0, 0, penSize);
-
- if (option->state & State_Sunken) {
- fill = option->palette.brush(QPalette::Shadow);
- color = option->palette.light().color();
- painter->drawLine(rect.bottomLeft(), rect.bottomRight());
- painter->drawLine(rect.topRight(), rect.bottomRight());
- rect.adjust(0, 0, -penSize, -penSize);
- }
- else {
- fill = option->palette.brush(QPalette::Button);
- color = option->palette.shadow().color();
- if (Qt::Horizontal == header->orientation )
- rect.adjust(-penSize, 0, 0, 0);
- else
- rect.adjust(0, -penSize, 0, 0);
- }
- if (Qt::Horizontal == header->orientation )
- rect.adjust(0,-penSize,0,0);
- else
- rect.adjust(-penSize, 0, 0, 0);
-
- if (option->state & State_Sunken) {
- qDrawPlainRect(painter, rect, color, penSize, &fill);
- } else {
- //Corner
- rect.adjust(-penSize, 0, 0, 0);
- qDrawPlainRect(painter, rect, color, penSize, &fill);
- }
-
- //Hack to get rid of some double lines... StyleOptions need a clean flag for that
- rect = option->rect;
-#ifndef QT_NO_SCROLLAREA
- if (const QAbstractScrollArea *abstractScrollArea = qobject_cast<const QAbstractScrollArea *> (widget) ) {
- QRect rectScrollArea = abstractScrollArea->geometry();
- if (Qt::Horizontal == header->orientation )
- if ((rectScrollArea.right() - rect.right() ) > 1)
- painter->drawLine(rect.topRight(), rect.bottomRight());
- else ;
- else
- if ((rectScrollArea.bottom() - rect.bottom() ) > 1)
- painter->drawLine(rect.bottomLeft(), rect.bottomRight());
- }
-#endif // QT_NO_SCROLLAREA
- break;
- }
-#ifndef QT_NO_COMBOBOX
- case CE_ComboBoxLabel:
- // This is copied from qcommonstyle.cpp with the difference, that
- // the editRect isn't adjusted when calling drawItemText.
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- QRect editRect = proxy()->subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget);
- painter->save();
- painter->setClipRect(editRect);
- if (!cb->currentIcon.isNull()) {
- QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
- QRect iconRect(editRect);
- iconRect.setWidth(cb->iconSize.width() + 4);
- iconRect = alignedRect(cb->direction,
- Qt::AlignLeft | Qt::AlignVCenter,
- iconRect.size(), editRect);
- if (cb->editable)
- painter->fillRect(iconRect, option->palette.brush(QPalette::Base));
- proxy()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap);
-
- if (cb->direction == Qt::RightToLeft)
- editRect.translate(-4 - cb->iconSize.width(), 0);
- else
- editRect.translate(cb->iconSize.width() + 4, 0);
- }
- if (!cb->currentText.isEmpty() && !cb->editable) {
- proxy()->drawItemText(painter, editRect,
- visualAlignment(cb->direction, Qt::AlignLeft | Qt::AlignVCenter),
- cb->palette, cb->state & State_Enabled, cb->currentText);
- }
- painter->restore();
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_DOCKWIDGET
- case CE_DockWidgetTitle:
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(option)) {
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(option);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- QRect rect = dwOpt->rect;
- QRect r = rect;
-
- if (verticalTitleBar) {
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- painter->save();
- painter->translate(r.left(), r.top() + r.width());
- painter->rotate(-90);
- painter->translate(-r.left(), -r.top());
- }
-
- bool floating = false;
- bool active = dwOpt->state & State_Active;
- int menuOffset = 0; //used to center text when floated
- QColor inactiveCaptionTextColor = option->palette.highlightedText().color();
- if (dwOpt->movable) {
- QColor left, right;
-
- //Titlebar gradient
- if (widget && widget->isWindow()) {
- floating = true;
- if (active) {
- right = option->palette.highlight().color();
- left = right.lighter(125);
- } else {
- left = option->palette.highlight().color().lighter(125);
- right = QColor(0xff, 0xff, 0xff);
- }
- menuOffset = 2;
- QBrush fillBrush(left);
- if (left != right) {
- QPoint p1(r.x(), r.top() + r.height()/2);
- QPoint p2(rect.right(), r.top() + r.height()/2);
- QLinearGradient lg(p1, p2);
- lg.setColorAt(0, left);
- lg.setColorAt(1, right);
- fillBrush = lg;
- }
- painter->fillRect(r.adjusted(0, 0, 0, -3), fillBrush);
- } else {
- painter->fillRect(r.adjusted(0, 0, 0, -3), option->palette.button().color());
- }
- painter->setPen(dwOpt->palette.color(QPalette::Light));
- if (!widget || !widget->isWindow()) {
- painter->drawLine(r.topLeft(), r.topRight());
- painter->setPen(dwOpt->palette.color(QPalette::Dark));
- painter->drawLine(r.bottomLeft(), r.bottomRight()); }
- }
- if (!dwOpt->title.isEmpty()) {
- QFont oldFont = painter->font();
- QFont newFont = oldFont;
- if (newFont.pointSize() > 2)
- newFont.setPointSize(newFont.pointSize() - 2);
- if (floating)
- newFont.setBold(true);
- painter->setFont(newFont);
- QPalette palette = dwOpt->palette;
- palette.setColor(QPalette::Window, inactiveCaptionTextColor);
- QRect titleRect = proxy()->subElementRect(SE_DockWidgetTitleBarText, option, widget);
- if (verticalTitleBar) {
- titleRect = QRect(r.left() + rect.bottom()
- - titleRect.bottom(),
- r.top() + titleRect.left() - rect.left(),
- titleRect.height(), titleRect.width());
- }
- proxy()->drawItemText(painter, titleRect,
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, palette,
- dwOpt->state & State_Enabled, dwOpt->title,
- floating ? (active ? QPalette::BrightText : QPalette::Window) : QPalette::WindowText);
- painter->setFont(oldFont);
- }
- if (verticalTitleBar)
- painter->restore();
- }
- return;
-#endif // QT_NO_DOCKWIDGET
-
- case CE_PushButtonLabel:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- painter->save();
- QRect ir = button->rect;
- QPalette::ColorRole colorRole;
- uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
- if (!styleHint(SH_UnderlineShortcut, button, widget))
- tf |= Qt::TextHideMnemonic;
-
- if (button->state & (State_On | State_Sunken))
- colorRole = QPalette::Light;
- else
- colorRole = QPalette::ButtonText;
-
- if (!button->icon.isNull()) {
- QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal
- : QIcon::Disabled;
- if (mode == QIcon::Normal && button->state & State_HasFocus)
- mode = QIcon::Active;
- QIcon::State state = QIcon::Off;
- if (button->state & State_On)
- state = QIcon::On;
- QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- //Center the icon if there is no text
-
- QPoint point;
- if (button->text.isEmpty()) {
- point = QPoint(ir.x() + ir.width() / 2 - pixw / 2,
- ir.y() + ir.height() / 2 - pixh / 2);
- } else {
- point = QPoint(ir.x() + 2, ir.y() + ir.height() / 2 - pixh / 2);
- }
- if (button->direction == Qt::RightToLeft)
- point.rx() += pixw;
-
- if ((button->state & (State_On | State_Sunken)) && button->direction == Qt::RightToLeft)
- point.rx() -= proxy()->pixelMetric(PM_ButtonShiftHorizontal, option, widget) * 2;
-
- painter->drawPixmap(visualPos(button->direction, button->rect, point), pixmap);
-
- if (button->direction == Qt::RightToLeft)
- ir.translate(-4, 0);
- else
- ir.translate(pixw + 4, 0);
- ir.setWidth(ir.width() - (pixw + 4));
- // left-align text if there is
- if (!button->text.isEmpty())
- tf |= Qt::AlignLeft;
- } else {
- tf |= Qt::AlignHCenter;
- }
- if (button->state & State_Enabled)
- proxy()->drawItemText(painter, ir, tf, button->palette, true, button->text, colorRole);
- else
- proxy()->drawItemText(painter, ir, tf, button->palette, true, button->text, QPalette::Mid);
- painter->restore();
- }
- break;
- default:
- QWindowsStyle::drawControl(element, option, painter, widget);
- break;
- }
-}
-
-void QWindowsMobileStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const {
-
- painter->setClipping(false);
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
-
- switch (control) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- int ticks = slider->tickPosition;
- QRect groove = proxy()->subControlRect(CC_Slider, slider, SC_SliderGroove, widget);
- QRect handle = proxy()->subControlRect(CC_Slider, slider, SC_SliderHandle, widget);
-
- if ((slider->subControls & SC_SliderGroove) && groove.isValid()) {
- int mid = thickness / 2;
- if (ticks & QSlider::TicksAbove)
- mid += len / 8;
- if (ticks & QSlider::TicksBelow)
- mid -= len / 8;
-
- painter->setPen(slider->palette.shadow().color());
- if (slider->orientation == Qt::Horizontal) {
- qDrawPlainRect(painter, groove.x(), groove.y() + mid - 2,
- groove.width(), 4, option->palette.shadow().color(),1,0);
- } else {
- qDrawPlainRect(painter, groove.x()+mid-2, groove.y(),
- 4, groove.height(), option->palette.shadow().color(),1,0);
- }
- }
- if (slider->subControls & SC_SliderTickmarks) {
- QStyleOptionSlider tmpSlider = *slider;
- tmpSlider.subControls = SC_SliderTickmarks;
- QCommonStyle::drawComplexControl(control, &tmpSlider, painter, widget);
- }
-
- if (slider->subControls & SC_SliderHandle) {
- const QColor c0 = slider->palette.shadow().color();
- const QColor c1 = slider->palette.dark().color();
- const QColor c3 = slider->palette.midlight().color();
- const QColor c4 = slider->palette.dark().color();
- QBrush handleBrush;
-
- if (slider->state & State_Enabled) {
- handleBrush = slider->palette.color(QPalette::Light);
- } else {
- handleBrush = QBrush(slider->palette.color(QPalette::Shadow),
- Qt::Dense4Pattern);
- }
- int x = handle.x(), y = handle.y(),
- wi = handle.width(), he = handle.height();
- int x1 = x;
- int x2 = x+wi-1;
- int y1 = y;
- int y2 = y+he-1;
-
- Qt::Orientation orient = slider->orientation;
- bool tickAbove = slider->tickPosition == QSlider::TicksAbove;
- bool tickBelow = slider->tickPosition == QSlider::TicksBelow;
-
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = proxy()->subElementRect(SE_SliderFocusRect, slider, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- if ((tickAbove && tickBelow) || (!tickAbove && !tickBelow)) {
- Qt::BGMode oldMode = painter->backgroundMode();
- painter->setBackgroundMode(Qt::OpaqueMode);
- qDrawPlainRect(painter, QRect(x, y, wi, he)
- ,slider->palette.shadow().color(),1,&handleBrush);
- painter->setBackgroundMode(oldMode);
- QBrush fill = QBrush(option->palette.light().color(), Qt::Dense4Pattern);
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 + 2, y1 + 2, x2 - x1 - 3, y2 - y1 - 3),fill);
- return;
- }
- QSliderDirection dir;
- if (orient == Qt::Horizontal)
- if (tickAbove)
- dir = SliderUp;
- else
- dir = SliderDown;
- else
- if (tickAbove)
- dir = SliderLeft;
- else
- dir = SliderRight;
- QPolygon polygon;
- int d = 0;
- switch (dir) {
- case SliderUp:
- x2++;
- y1 = y1 + wi / 2;
- d = (wi + 1) / 2 - 1;
- polygon.setPoints(5, x1, y1, x1, y2, x2, y2, x2, y1, x1 + d,y1 - d);
- break;
- case SliderDown:
- x2++;
- y2 = y2 - wi/2;
- d = (wi + 1) / 2 - 1;
- polygon.setPoints(5, x1, y1, x1, y2, x1 + d,y2 + d, x2, y2, x2, y1);
- break;
- case SliderLeft:
- d = (he + 1) / 2 - 1;
- x1 = x1 + he/2;
- polygon.setPoints(5, x1, y1, x1 - d, y1 + d, x1,y2, x2, y2, x2, y1);
- y1--;
- break;
- case SliderRight:
- d = (he + 1) / 2 - 1;
- x2 = x2 - he/2;
- polygon.setPoints(5, x1, y1, x1, y2, x2,y2, x2 + d, y1 + d, x2, y1);
- y1--;
- break;
- }
- QBrush oldBrush = painter->brush();
- painter->setPen(Qt::NoPen);
- painter->setBrush(handleBrush);
- Qt::BGMode oldMode = painter->backgroundMode();
- painter->setBackgroundMode(Qt::OpaqueMode);
- painter->drawRect(x1, y1, x2-x1+1, y2-y1+1);
- painter->drawPolygon(polygon);
- QBrush fill = QBrush(option->palette.button().color(), Qt::Dense4Pattern);
- painter->setBrush(oldBrush);
- painter->setBackgroundMode(oldMode);
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1, y1, x2 - x1 + 1, y2 - y1 + 1),fill);
-
- if (dir != SliderUp) {
- painter->setPen(c0);
- painter->drawLine(x1, y1, x2, y1);
- }
- if (dir != SliderLeft) {
- painter->setPen(c0);
- painter->drawLine(x1, y1, x1, y2);
- }
- if (dir != SliderRight) {
- painter->setPen(c0);
- painter->drawLine(x2, y1, x2, y2);
- }
- if (dir != SliderDown) {
- painter->setPen(c0);
- painter->drawLine(x1, y2, x2, y2);
- }
- switch (dir) {
- case SliderUp:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 + 3, y1 - d + 2, x2 - x1 - 4, y1),fill);
- painter->setPen(c0);
- painter->drawLine(x1, y1, x1 + d, y1 - d);
- d = wi - d - 1;
- painter->drawLine(x2, y1, x2 -d , y1 -d );
- d--;
- break;
- case SliderDown:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1+3, y2 - d, x2 - x1 -4,y2 - 8),fill);
- painter->setPen(c0);
- painter->drawLine(x1, y2, x1 + d, y2 + d);
- d = wi - d - 1;
- painter->drawLine(x2, y2, x2 - d, y2 + d);
- d--;
- break;
- case SliderLeft:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x1 - d + 2, y1 + 2, x1, y2 - y1 - 3),fill);
- painter->setPen(c0);
- painter->drawLine(x1, y1, x1 - d, y1 + d);
- d = he - d - 1;
- painter->drawLine(x1, y2, x1 - d, y2 - d);
- d--;
- break;
- case SliderRight:
- if (slider->state & State_Sunken)
- painter->fillRect(QRectF(x2 - d - 4, y1 + 2, x2 - 4, y2 - y1 - 3),fill);
- painter->setPen(c0);
- painter->drawLine(x2, y1, x2 + d, y1 + d);
- painter->setPen(c0);
- d = he - d - 1;
- painter->drawLine(x2, y2, x2 + d, y2 - d);
- d--;
- break;
- }
- }
- }
- break;
-#endif //QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- painter->save();
- painter->setPen(option->palette.shadow().color());
- if (d->doubleControls) {
- QPen pen = painter->pen();
- pen.setWidth(2);
- pen.setCapStyle(Qt::SquareCap);
- painter->setPen(pen);
- }
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- d->drawScrollbarGroove(painter, scrollbar);
- // Make a copy here and reset it for each primitive.
- QStyleOptionSlider newScrollbar = *scrollbar;
- State saveFlags = scrollbar->state;
- //Check if the scrollbar is part of an abstractItemView and draw the frame according
- bool drawCompleteFrame = true;
- bool secondScrollBar = false;
- if (widget)
- if (QWidget *parent = widget->parentWidget()) {
- if (QAbstractScrollArea *abstractScrollArea = qobject_cast<QAbstractScrollArea *>(parent->parentWidget())) {
- drawCompleteFrame = (abstractScrollArea->frameStyle() == QFrame::NoFrame) || (abstractScrollArea->frameStyle() == QFrame::StyledPanel);
- secondScrollBar = (abstractScrollArea->horizontalScrollBar()->isVisible()
- && abstractScrollArea->verticalScrollBar()->isVisible()) ;
- }
-#ifndef QT_NO_LISTVIEW
- if (QListView *listView = qobject_cast<QListView *>(parent->parentWidget()))
- drawCompleteFrame = false;
-#endif
- }
- if (scrollbar->minimum == scrollbar->maximum)
- saveFlags |= State_Enabled;
- if (scrollbar->subControls & SC_ScrollBarSubLine) {
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(control, &newScrollbar, SC_ScrollBarSubLine, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarSubLine))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- d->drawScrollbarHandleUp(painter, &newScrollbar, drawCompleteFrame, secondScrollBar);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarAddLine) {
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(control, &newScrollbar, SC_ScrollBarAddLine, widget);
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarAddLine))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- d->drawScrollbarHandleDown(painter, &newScrollbar, drawCompleteFrame, secondScrollBar);
- }
- }
- if (scrollbar->subControls & SC_ScrollBarSlider) {
-
- newScrollbar.rect = scrollbar->rect;
- newScrollbar.state = saveFlags;
- newScrollbar.rect = proxy()->subControlRect(control, &newScrollbar, SC_ScrollBarSlider, widget);
-
- if (newScrollbar.rect.isValid()) {
- if (!(scrollbar->activeSubControls & SC_ScrollBarSlider))
- newScrollbar.state &= ~(State_Sunken | State_MouseOver);
- d->drawScrollbarGrip(painter, &newScrollbar, option, drawCompleteFrame);
- }
- }
- }
- painter->restore();
- break;
-#endif // QT_NO_SCROLLBAR
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- QRect button, menuarea;
- bool isTabWidget = false;
-#ifndef QT_NO_TABWIDGET
- if (widget)
- if (QWidget *parent = widget->parentWidget())
- isTabWidget = (qobject_cast<QTabWidget *>(parent->parentWidget()));
-#endif //QT_NO_TABWIDGET
-
- button = proxy()->subControlRect(control, toolbutton, SC_ToolButton, widget);
- menuarea = proxy()->subControlRect(control, toolbutton, SC_ToolButtonMenu, widget);
- State buttonFlags = toolbutton->state;
- if (buttonFlags & State_AutoRaise) {
- if (!(buttonFlags & State_MouseOver)) {
- buttonFlags &= ~State_Raised;
- }
- }
- State menuFlags = buttonFlags;
- if (toolbutton->activeSubControls & SC_ToolButton)
- buttonFlags |= State_Sunken;
- if (toolbutton->activeSubControls & SC_ToolButtonMenu)
- menuFlags |= State_On;
- QStyleOption tool(0);
- tool.palette = toolbutton->palette;
- if (toolbutton->subControls & SC_ToolButton) {
- tool.rect = button;
- tool.state = buttonFlags;
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, painter, widget);
- }
- if (toolbutton->subControls & SC_ToolButtonMenu) {
- tool.rect = menuarea;
- tool.state = buttonFlags & State_Enabled;
- QStyleOption toolMenu(0);
- toolMenu = *toolbutton;
- toolMenu.state = menuFlags;
- if (buttonFlags & State_Sunken)
- proxy()->drawPrimitive(PE_PanelButtonTool, &toolMenu, painter, widget);
- QStyleOption arrowOpt(0);
- arrowOpt.rect = tool.rect;
- arrowOpt.palette = tool.palette;
- State flags = State_None;
- if (menuFlags & State_Enabled)
- flags |= State_Enabled;
- if ((menuFlags & State_On) && !(buttonFlags & State_Sunken)) {
- flags |= State_Sunken;
- painter->fillRect(menuarea, option->palette.shadow());
- }
- arrowOpt.state = flags;
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, painter, widget);
- }
- if (toolbutton->state & State_HasFocus) {
- QStyleOptionFocusRect focusRect;
- focusRect.QStyleOption::operator=(*toolbutton);
- focusRect.rect.adjust(3, 3, -3, -3);
- if (toolbutton->features & QStyleOptionToolButton::Menu)
- focusRect.rect.adjust(0, 0, -proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator,
- toolbutton, widget), 0);
- proxy()->drawPrimitive(PE_FrameFocusRect, &focusRect, painter, widget);
- }
- QStyleOptionToolButton label = *toolbutton;
- if (isTabWidget)
- label.state = toolbutton->state;
- else
- label.state = toolbutton->state & State_Enabled;
- int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, option, widget);
- label.rect = button.adjusted(fw, fw, -fw, -fw);
- proxy()->drawControl(CE_ToolButtonLabel, &label, painter, widget);
- }
- break;
-
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox:
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- // Draw frame
- painter->save();
- QFont font = painter->font();
- font.setBold(true);
- painter->setFont(font);
- QStyleOptionGroupBox groupBoxFont = *groupBox;
- groupBoxFont.fontMetrics = QFontMetrics(font);
- QRect textRect = proxy()->subControlRect(CC_GroupBox, &groupBoxFont, SC_GroupBoxLabel, widget);
- QRect checkBoxRect = proxy()->subControlRect(CC_GroupBox, option, SC_GroupBoxCheckBox, widget).adjusted(0,0,0,0);
- if (groupBox->subControls & QStyle::SC_GroupBoxFrame) {
- QStyleOptionFrameV2 frame;
- frame.QStyleOption::operator=(*groupBox);
- frame.features = groupBox->features;
- frame.lineWidth = groupBox->lineWidth;
- frame.midLineWidth = groupBox->midLineWidth;
- frame.rect = proxy()->subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);
- painter->save();
- QRegion region(groupBox->rect);
- if (!groupBox->text.isEmpty()) {
- bool ltr = groupBox->direction == Qt::LeftToRight;
- QRect finalRect = checkBoxRect.united(textRect);
- if (groupBox->subControls & QStyle::SC_GroupBoxCheckBox)
- finalRect.adjust(ltr ? -4 : 0, 0, ltr ? 0 : 4, 0);
- region -= finalRect;
- }
- proxy()->drawPrimitive(PE_FrameGroupBox, &frame, painter, widget);
- painter->restore();
- }
- // Draw checkbox
- if (groupBox->subControls & SC_GroupBoxCheckBox) {
- QStyleOptionButton box;
- box.QStyleOption::operator=(*groupBox);
- box.rect = checkBoxRect;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &box, painter, widget);
- }
- // Draw title
- if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
- QColor textColor = groupBox->textColor;
- if (textColor.isValid())
- painter->setPen(textColor);
- else
- painter->setPen(groupBox->palette.link().color());
- painter->setPen(groupBox->palette.link().color());
-
- int alignment = int(groupBox->textAlignment);
- if (!styleHint(QStyle::SH_UnderlineShortcut, option, widget))
- alignment |= Qt::TextHideMnemonic;
-
- if (groupBox->state & State_Enabled)
- proxy()->drawItemText(painter, textRect, Qt::TextShowMnemonic | Qt::AlignHCenter | alignment,
- groupBox->palette, true, groupBox->text,
- textColor.isValid() ? QPalette::NoRole : QPalette::Link);
- else
- proxy()->drawItemText(painter, textRect, Qt::TextShowMnemonic | Qt::AlignHCenter | alignment,
- groupBox->palette, true, groupBox->text, QPalette::Mid);
- if (groupBox->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*groupBox);
- fropt.rect = textRect;
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
- }
- }
- painter->restore();
- }
- break;
-#endif //QT_NO_GROUPBOX
-
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- QBrush editBrush = cmb->palette.brush(QPalette::Base);
- if ((cmb->subControls & SC_ComboBoxFrame) && cmb->frame)
- qDrawPlainRect(painter, option->rect, option->palette.shadow().color(), proxy()->pixelMetric(PM_ComboBoxFrameWidth, option, widget), &editBrush);
- else
- painter->fillRect(option->rect, editBrush);
- State flags = State_None;
- QRect ar = proxy()->subControlRect(CC_ComboBox, cmb, SC_ComboBoxArrow, widget);
- if ((option->state & State_On)) {
- painter->fillRect(ar.adjusted(0, 0, 1, 1),cmb->palette.brush(QPalette::Shadow));
- }
- if (d->doubleControls)
- ar.adjust(5, 0, 5, 0);
- else
- ar.adjust(2, 0, -2, 0);
- if (option->state & State_Enabled)
- flags |= State_Enabled;
- if (option->state & State_On)
- flags |= State_Sunken;
- QStyleOption arrowOpt(0);
- arrowOpt.rect = ar;
- arrowOpt.palette = cmb->palette;
- arrowOpt.state = flags;
- proxy()->drawPrimitive(PrimitiveElement(PE_IndicatorArrowDownBig), &arrowOpt, painter, widget);
- if (cmb->subControls & SC_ComboBoxEditField) {
- QRect re = proxy()->subControlRect(CC_ComboBox, cmb, SC_ComboBoxEditField, widget);
- if (cmb->state & State_HasFocus && !cmb->editable)
- painter->fillRect(re.x(), re.y(), re.width(), re.height(),
- cmb->palette.brush(QPalette::Highlight));
- if (cmb->state & State_HasFocus) {
- painter->setPen(cmb->palette.highlightedText().color());
- painter->setBackground(cmb->palette.highlight());
- } else {
- painter->setPen(cmb->palette.text().color());
- painter->setBackground(cmb->palette.background());
- }
- if (cmb->state & State_HasFocus && !cmb->editable) {
- QStyleOptionFocusRect focus;
- focus.QStyleOption::operator=(*cmb);
- focus.rect = proxy()->subElementRect(SE_ComboBoxFocusRect, cmb, widget);
- focus.state |= State_FocusAtBorder;
- focus.backgroundColor = cmb->palette.highlight().color();
- if ((option->state & State_On))
- proxy()->drawPrimitive(PE_FrameFocusRect, &focus, painter, widget);
- }
- }
- }
- break;
-#endif // QT_NO_COMBOBOX
-
-
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QStyleOptionSpinBox copy = *spinBox;
- //PrimitiveElement primitiveElement;
- int primitiveElement;
-
- if (spinBox->frame && (spinBox->subControls & SC_SpinBoxFrame)) {
- QRect r = proxy()->subControlRect(CC_SpinBox, spinBox, SC_SpinBoxFrame, widget);
- qDrawPlainRect(painter, r, option->palette.shadow().color(), proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget),0);
- }
- QPalette shadePal(option->palette);
- shadePal.setColor(QPalette::Button, option->palette.light().color());
- shadePal.setColor(QPalette::Light, option->palette.base().color());
- if (spinBox->subControls & SC_SpinBoxUp) {
- copy.subControls = SC_SpinBoxUp;
- QPalette pal2 = spinBox->palette;
- if (!(spinBox->stepEnabled & QAbstractSpinBox::StepUpEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
- if (spinBox->activeSubControls == SC_SpinBoxUp && (spinBox->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- primitiveElement = (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorArrowUpBig
- : PE_IndicatorArrowUpBig);
- copy.rect = proxy()->subControlRect(CC_SpinBox, spinBox, SC_SpinBoxUp, widget);
- if (copy.state & (State_Sunken | State_On))
- qDrawPlainRect(painter, copy.rect, option->palette.shadow().color(), proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), &copy.palette.brush(QPalette::Shadow));
- else
- qDrawPlainRect(painter, copy.rect, option->palette.shadow().color(), proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), &copy.palette.brush(QPalette::Base));
- copy.rect.adjust(proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), 0, -pixelMetric(PM_SpinBoxFrameWidth, option, widget), 0);
- proxy()->drawPrimitive(PrimitiveElement(primitiveElement), &copy, painter, widget);
- }
- if (spinBox->subControls & SC_SpinBoxDown) {
- copy.subControls = SC_SpinBoxDown;
- copy.state = spinBox->state;
- QPalette pal2 = spinBox->palette;
- if (!(spinBox->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
- if (spinBox->activeSubControls == SC_SpinBoxDown && (spinBox->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- primitiveElement = (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorArrowDownBig
- : PE_IndicatorArrowDownBig);
- copy.rect = proxy()->subControlRect(CC_SpinBox, spinBox, SC_SpinBoxDown, widget);
- qDrawPlainRect(painter, copy.rect, option->palette.shadow().color(), proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), &copy.palette.brush(QPalette::Base));
- if (copy.state & (State_Sunken | State_On))
- qDrawPlainRect(painter, copy.rect, option->palette.shadow().color(), proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), &copy.palette.brush(QPalette::Shadow));
- else
- qDrawPlainRect(painter, copy.rect, option->palette.shadow().color(), proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), &copy.palette.brush(QPalette::Base));
- copy.rect.adjust(3, 0, -4, 0);
- if (primitiveElement == PE_IndicatorArrowUp || primitiveElement == PE_IndicatorArrowDown) {
- int frameWidth = proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget);
- copy.rect = copy.rect.adjusted(frameWidth, frameWidth, -frameWidth, -frameWidth);
- proxy()->drawPrimitive(PrimitiveElement(primitiveElement), &copy, painter, widget);
- }
- else {
- proxy()->drawPrimitive(PrimitiveElement(primitiveElement), &copy, painter, widget);
- }
- if (spinBox->frame && (spinBox->subControls & SC_SpinBoxFrame)) {
- QRect r = proxy()->subControlRect(CC_SpinBox, spinBox, SC_SpinBoxEditField, widget);
- }
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-
- default:
- QWindowsStyle::drawComplexControl(control, option, painter, widget);
- break;
- }
-}
-
-QSize QWindowsMobileStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const {
-
- QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget);
- switch (type) {
- case CT_PushButton:
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- newSize = QCommonStyle::sizeFromContents(type, option, size, widget);
- int w = newSize.width(),
- h = newSize.height();
- int defwidth = 0;
- if (button->features & QStyleOptionButton::AutoDefaultButton)
- defwidth = 2 * proxy()->pixelMetric(PM_ButtonDefaultIndicator, button, widget);
-
- int minwidth = int(QStyleHelper::dpiScaled(55.0f));
- int minheight = int(QStyleHelper::dpiScaled(19.0f));
-
- if (w < minwidth + defwidth && button->icon.isNull())
- w = minwidth + defwidth;
- if (h < minheight + defwidth)
- h = minheight + defwidth;
- newSize = QSize(w + 4, h + 4);
- }
- break;
-
-#ifndef QT_NO_GROUPBOX
- case CT_GroupBox:
- if (const QGroupBox *grb = static_cast<const QGroupBox *>(widget)) {
- newSize = size + QSize(!grb->isFlat() ? 16 : 0, !grb->isFlat() ? 16 : 0);
- }
- break;
-#endif // QT_NO_GROUPBOX
-
- case CT_RadioButton:
- case CT_CheckBox:
- newSize = size;
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- bool isRadio = (type == CT_RadioButton);
- QRect irect = visualRect(button->direction, button->rect,
- proxy()->subElementRect(isRadio ? SE_RadioButtonIndicator
- : SE_CheckBoxIndicator, button, widget));
- int h = proxy()->pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
- : PM_IndicatorHeight, button, widget);
- int margins = (!button->icon.isNull() && button->text.isEmpty()) ? 0 : 10;
- if (d_func()->doubleControls)
- margins *= 2;
- newSize += QSize(irect.right() + margins, 1);
- newSize.setHeight(qMax(newSize.height(), h));
- }
- break;
-#ifndef QT_NO_COMBOBOX
- case CT_ComboBox:
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int fw = comboBox->frame ? proxy()->pixelMetric(PM_ComboBoxFrameWidth, option, widget) * 2 : 0;
- newSize = QSize(newSize.width() + fw + 9, newSize.height() + fw); //Nine is a magic Number - See CommonStyle for real magic (23)
- }
- break;
-#endif
-#ifndef QT_NO_SPINBOX
- case CT_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- int fw = spinBox->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget) * 2 : 0;
- newSize = QSize(newSize.width() + fw-5, newSize.height() + fw-6);
- }
- break;
-#endif
-#ifndef QT_NO_LINEEDIT
- case CT_LineEdit:
- newSize += QSize(0,1);
- break;
-#endif
- case CT_ToolButton:
- newSize = QSize(newSize.width() + 1, newSize.height());
- break;
- case CT_TabBarTab:
- if (d_func()->doubleControls)
- newSize = QSize(newSize.width(), 42);
- else
- newSize = QSize(newSize.width(), 21);
- break;
- case CT_HeaderSection:
- newSize += QSize(4, 2);
- break;
-#ifndef QT_NO_ITEMVIEWS
-#ifdef Q_WS_WINCE_WM
- case CT_ItemViewItem:
- if (d_func()->wm65)
- if (d_func()->doubleControls)
- newSize.setHeight(46);
- else
- newSize.setHeight(23);
- break;
-#endif //Q_WS_WINCE_WM
-#endif //QT_NO_ITEMVIEWS
- default:
- break;
- }
- return newSize;
-}
-
-QRect QWindowsMobileStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
- QRect rect = QWindowsStyle::subElementRect(element, option, widget);
- switch (element) {
-#ifndef QT_NO_TABWIDGET
- case SE_TabWidgetTabBar:
- if (d->doubleControls)
- rect.adjust(-2, 0, 2, 0);
- else
- rect.adjust(-2, 0, 2, 0);
- break;
-#endif //QT_NO_TABWIDGET
- case SE_CheckBoxFocusRect:
- rect.adjust(1,0,-2,-1);
- break;
- case SE_RadioButtonFocusRect:
- rect.adjust(1,1,-2,-2);
- break;
- default:
- break;
-#ifndef QT_NO_SLIDER
- case SE_SliderFocusRect:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- rect = slider->rect;
- }
- break;
- case SE_PushButtonFocusRect:
- if (d->doubleControls)
- rect.adjust(-1, -1, 0, 0);
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_ITEMVIEWS
- case SE_ItemViewItemFocusRect:
-#ifdef Q_WS_WINCE_WM
- if (d->wm65)
- rect = QRect();
-#endif
- break;
-#endif //QT_NO_ITEMVIEWS
- }
- return rect;
-}
-
-QRect QWindowsMobileStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
-
- QRect rect = QCommonStyle::subControlRect(control, option, subControl, widget);
- switch (control) {
-
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int sliderButtonExtent = proxy()->pixelMetric(PM_ScrollBarExtent, scrollbar, widget);
- float stretchFactor = 1.4f;
- int sliderButtonExtentDir = int (sliderButtonExtent * stretchFactor);
-
-#ifdef Q_WS_WINCE_WM
- if (d->wm65)
- {
- sliderButtonExtent = d->imageScrollbarHandleUp.width();
- sliderButtonExtentDir = d->imageScrollbarHandleUp.height();
- }
-#endif //Q_WS_WINCE_WM
-
- int sliderlen;
- int maxlen = ((scrollbar->orientation == Qt::Horizontal) ?
- scrollbar->rect.width() : scrollbar->rect.height()) - (sliderButtonExtentDir * 2);
- // calculate slider length
- if (scrollbar->maximum != scrollbar->minimum) {
- uint range = scrollbar->maximum - scrollbar->minimum;
- sliderlen = (qint64(scrollbar->pageStep) * maxlen) / (range + scrollbar->pageStep);
-
- int slidermin = proxy()->pixelMetric(PM_ScrollBarSliderMin, scrollbar, widget);
- if (sliderlen < slidermin || range > INT_MAX / 2)
- sliderlen = slidermin;
- if (sliderlen > maxlen)
- sliderlen = maxlen;
- } else {
- sliderlen = maxlen;
- }
- int sliderstart = sliderButtonExtentDir + sliderPositionFromValue(scrollbar->minimum,
- scrollbar->maximum,
- scrollbar->sliderPosition,
- maxlen - sliderlen,
- scrollbar->upsideDown);
- if (d->smartphone) {
- sliderstart -= sliderButtonExtentDir;
- sliderlen += 2*sliderButtonExtent;
- }
- switch (subControl) {
- case SC_ScrollBarSubLine: // top/left button
- if (scrollbar->orientation == Qt::Horizontal) {
- int buttonWidth = qMin(scrollbar->rect.width() / 2, sliderButtonExtentDir );
- rect.setRect(0, 0, buttonWidth, sliderButtonExtent);
- } else {
- int buttonHeight = qMin(scrollbar->rect.height() / 2, sliderButtonExtentDir);
- rect.setRect(0, 0, sliderButtonExtent, buttonHeight);
- }
- if (d->smartphone)
- rect.setRect(0, 0, 0, 0);
- break;
- case SC_ScrollBarAddLine: // bottom/right button
- if (scrollbar->orientation == Qt::Horizontal) {
- int buttonWidth = qMin(scrollbar->rect.width()/2, sliderButtonExtentDir);
- rect.setRect(scrollbar->rect.width() - buttonWidth, 0, buttonWidth, sliderButtonExtent);
- } else {
- int buttonHeight = qMin(scrollbar->rect.height()/2, sliderButtonExtentDir );
- rect.setRect(0, scrollbar->rect.height() - buttonHeight, sliderButtonExtent, buttonHeight);
- }
- if (d->smartphone)
- rect.setRect(0, 0, 0, 0);
- break;
- case SC_ScrollBarSubPage: // between top/left button and slider
- if (scrollbar->orientation == Qt::Horizontal)
- if (d->smartphone)
- rect.setRect(0, 0, sliderstart, sliderButtonExtent);
- else
- rect.setRect(sliderButtonExtent, 0, sliderstart - sliderButtonExtent, sliderButtonExtent);
- else
- if (d->smartphone)
- rect.setRect(0, 0, sliderButtonExtent, sliderstart);
- else
- rect.setRect(0, sliderButtonExtent, sliderButtonExtent, sliderstart - sliderButtonExtent);
- break;
- case SC_ScrollBarAddPage: // between bottom/right button and slider
- if (scrollbar->orientation == Qt::Horizontal)
- if (d->smartphone)
- rect.setRect(sliderstart + sliderlen, 0,
- maxlen - sliderstart - sliderlen + 2*sliderButtonExtent, sliderButtonExtent);
- else
- rect.setRect(sliderstart + sliderlen, 0,
- maxlen - sliderstart - sliderlen + sliderButtonExtent, sliderButtonExtent);
- else
- if (d->smartphone)
- rect.setRect(0, sliderstart + sliderlen, sliderButtonExtent,
- maxlen - sliderstart - sliderlen + 2*sliderButtonExtent);
- else
- rect.setRect(0, sliderstart + sliderlen, sliderButtonExtent,
- maxlen - sliderstart - sliderlen + sliderButtonExtent);
- break;
- case SC_ScrollBarGroove:
- if (scrollbar->orientation == Qt::Horizontal)
- rect.setRect(sliderButtonExtent, 0, scrollbar->rect.width() - sliderButtonExtent * 2,
- scrollbar->rect.height());
- else
- rect.setRect(0, sliderButtonExtent, scrollbar->rect.width(),
- scrollbar->rect.height() - sliderButtonExtent * 2);
- break;
- case SC_ScrollBarSlider:
- if (scrollbar->orientation == Qt::Horizontal)
- rect.setRect(sliderstart, 0, sliderlen, sliderButtonExtent);
- else
- rect.setRect(0, sliderstart, sliderButtonExtent, sliderlen);
- break;
- default:
- break;
- }
- rect = visualRect(scrollbar->direction, scrollbar->rect, rect);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-
-
-
-#ifndef QT_NO_TOOLBUTTON
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolButton = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolButton, widget);
- rect = toolButton->rect;
- switch (subControl) {
- case SC_ToolButton:
- if ((toolButton->features
- & (QStyleOptionToolButton::Menu | QStyleOptionToolButton::PopupDelay))
- == QStyleOptionToolButton::Menu)
- rect.adjust(0, 0, -mbi, 0);
- break;
- case SC_ToolButtonMenu:
- if ((toolButton->features
- & (QStyleOptionToolButton::Menu | QStyleOptionToolButton::PopupDelay))
- == QStyleOptionToolButton::Menu)
- rect.adjust(rect.width() - mbi, 1, 0, 1);
- break;
- default:
- break;
- }
- rect = visualRect(toolButton->direction, toolButton->rect, rect);
- }
- break;
-#endif // QT_NO_TOOLBUTTON
-
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- int tickOffset = proxy()->pixelMetric(PM_SliderTickmarkOffset, slider, widget);
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
- switch (subControl) {
- case SC_SliderHandle: {
- int sliderPos = 0;
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- bool horizontal = slider->orientation == Qt::Horizontal;
- sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum,
- slider->sliderPosition,
- (horizontal ? slider->rect.width()
- : slider->rect.height()) - len,
- slider->upsideDown);
- if (horizontal)
- rect.setRect(slider->rect.x() + sliderPos, slider->rect.y() + tickOffset, len, thickness);
- else
- rect.setRect(slider->rect.x() + tickOffset, slider->rect.y() + sliderPos, thickness, len);
- break; }
- default:
- break;
- }
- rect = visualRect(slider->direction, slider->rect, rect);
- }
- break;
-#endif //QT_NO_SLIDER
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int x = comboBox->rect.x(),
- y = comboBox->rect.y(),
- wi = comboBox->rect.width(),
- he = comboBox->rect.height();
- int xpos = x;
- int margin = comboBox->frame ? (d->doubleControls ? 2 : 1) : 0;
- int bmarg = comboBox->frame ? (d->doubleControls ? 2 : 1) : 0;
- if (subControl == SC_ComboBoxArrow)
- xpos += wi - int((he - 2*bmarg)*0.9) - bmarg;
- else
- xpos += wi - (he - 2*bmarg) - bmarg;
- switch (subControl) {
- case SC_ComboBoxArrow:
- rect.setRect(xpos, y + bmarg, he - 2*bmarg, he - 2*bmarg);
- break;
- case SC_ComboBoxEditField:
- rect.setRect(x + margin, y + margin, wi - 2 * margin - int((he - 2*bmarg) * 0.84f), he - 2 * margin);
- if (d->doubleControls) {
- if (comboBox->editable)
- rect.adjust(2, 0, 0, 0);
- else
- rect.adjust(4, 2, 0, -2);
- } else if (!comboBox->editable) {
- rect.adjust(2, 1, 0, -1);
- }
- break;
- case SC_ComboBoxFrame:
- rect = comboBox->rect;
- break;
- default:
- break;
- }
- }
-#endif //QT_NO_COMBOBOX
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
- QSize bs;
- int fw = spinBox->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, spinBox, widget) : 0;
- bs.setHeight(qMax(d->doubleControls ? 28 : 14, (spinBox->rect.height())));
- // 1.6 -approximate golden mean
- bs.setWidth(qMax(d->doubleControls ? 28 : 14, qMin((bs.height()*7/8), (spinBox->rect.width() / 8))));
- bs = bs.expandedTo(QApplication::globalStrut());
- int x, lx, rx;
- x = spinBox->rect.width() - bs.width()*2;
- lx = fw;
- rx = x - fw;
- switch (subControl) {
- case SC_SpinBoxUp:
- rect = QRect(x + proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget), 0 , bs.width(), bs.height());
- break;
- case SC_SpinBoxDown:
- rect = QRect(x + bs.width(), 0, bs.width(), bs.height());
- break;
- case SC_SpinBoxEditField:
- if (spinBox->buttonSymbols == QAbstractSpinBox::NoButtons) {
- rect = QRect(lx, fw, spinBox->rect.width() - 2*fw - 2, spinBox->rect.height() - 2*fw);
- } else {
- rect = QRect(lx, fw, rx-2, spinBox->rect.height() - 2*fw);
- }
- break;
- case SC_SpinBoxFrame:
- rect = spinBox->rect;
- default:
- break;
- }
- rect = visualRect(spinBox->direction, spinBox->rect, rect);
- }
- break;
-#endif // Qt_NO_SPINBOX
-#ifndef QT_NO_GROUPBOX
- case CC_GroupBox: {
- if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
- switch (subControl) {
- case SC_GroupBoxFrame:
- // FALL THROUGH
- case SC_GroupBoxContents: {
- int topMargin = 0;
- int topHeight = 0;
- int bottomMargin = 0;
- int labelMargin = 2;
-
- QRect frameRect = groupBox->rect;
- int verticalAlignment = styleHint(SH_GroupBox_TextLabelVerticalAlignment, groupBox, widget);
- if (groupBox->text.size()) {
- topHeight = groupBox->fontMetrics.height();
- if (verticalAlignment & Qt::AlignVCenter)
- topMargin = topHeight+5;
- else if (verticalAlignment & Qt::AlignTop)
- topMargin = -topHeight+5;
- }
- if (subControl == SC_GroupBoxFrame) {
- frameRect.setTop(topMargin);
- frameRect.setBottom(frameRect.height() + bottomMargin);
- rect = frameRect;
- break;
- }
- int frameWidth = 0;
- if (groupBox->text.size()) {
- frameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth, groupBox, widget);
- rect = frameRect.adjusted(frameWidth, frameWidth + topHeight + labelMargin, -frameWidth, -frameWidth);
- }
- else {
- rect = groupBox->rect;
- }
- break;
- }
- case SC_GroupBoxCheckBox:
- // FALL THROUGH
- case SC_GroupBoxLabel: {
- QFontMetrics fontMetrics = groupBox->fontMetrics;
- int h = fontMetrics.height();
- int textWidth = fontMetrics.size(Qt::TextShowMnemonic, groupBox->text + QLatin1Char(' ')).width();
- int margX = (groupBox->features & QStyleOptionFrameV2::Flat) ? 0 : 2;
- int margY = (groupBox->features & QStyleOptionFrameV2::Flat) ? 0 : 2;
- rect = groupBox->rect.adjusted(margX, margY, -margX, 0);
- if (groupBox->text.size())
- rect.setHeight(h);
- else
- rect.setHeight(0);
- int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, option, widget);
- int indicatorSpace = proxy()->pixelMetric(PM_CheckBoxLabelSpacing, option, widget) - 1;
- bool hasCheckBox = groupBox->subControls & QStyle::SC_GroupBoxCheckBox;
- int checkBoxSize = hasCheckBox ? (indicatorWidth + indicatorSpace) : 0;
-
- // Adjusted rect for label + indicatorWidth + indicatorSpace
- QRect totalRect = alignedRect(groupBox->direction, groupBox->textAlignment,
- QSize(textWidth + checkBoxSize, h), rect);
-
- // Adjust totalRect if checkbox is set
- if (hasCheckBox) {
- bool ltr = groupBox->direction == Qt::LeftToRight;
- int left = 2;
- // Adjust for check box
- if (subControl == SC_GroupBoxCheckBox) {
- int indicatorHeight = proxy()->pixelMetric(PM_IndicatorHeight, option, widget);
- left = ltr ? totalRect.left() : (totalRect.right() - indicatorWidth);
- int top = totalRect.top() + (fontMetrics.height() - indicatorHeight) / 2;
- totalRect.setRect(left, top, indicatorWidth, indicatorHeight);
- // Adjust for label
- } else {
- left = ltr ? (totalRect.left() + checkBoxSize - 2) : totalRect.left();
- totalRect.setRect(left, totalRect.top(),
- totalRect.width() - checkBoxSize, totalRect.height());
- }
- }
- if ((subControl== SC_GroupBoxLabel))
- totalRect.adjust(-2,0,6,0);
- rect = totalRect;
- break;
- }
- default:
- break;
- }
- }
- break;
- }
-#endif // QT_NO_GROUPBOX
- default:
- break;
- }
- return rect;
-}
-
-QPalette QWindowsMobileStyle::standardPalette() const {
- QPalette palette (Qt::black,QColor(198, 195, 198), QColor(222, 223, 222 ),
- QColor(132, 130, 132), QColor(198, 195, 198), Qt::black, Qt::white, Qt::white, QColor(198, 195, 198));
- palette.setColor(QPalette::Window, QColor(206, 223, 239));
- palette.setColor(QPalette::Link, QColor(8,77,123)); //Alternate TextColor for labels...
- palette.setColor(QPalette::Base, Qt::white);
- palette.setColor(QPalette::Button, QColor(206, 223, 239));
- palette.setColor(QPalette::Highlight, QColor(49, 146, 214));
- palette.setColor(QPalette::Light, Qt::white);
- palette.setColor(QPalette::Text, Qt::black);
- palette.setColor(QPalette::ButtonText, Qt::black);
- palette.setColor(QPalette::Midlight, QColor(222, 223, 222 ));
- palette.setColor(QPalette::Dark, QColor(132, 130, 132));
- palette.setColor(QPalette::Mid, QColor(189, 190, 189));
- palette.setColor(QPalette::Shadow, QColor(0, 0, 0));
- palette.setColor(QPalette::BrightText, QColor(33, 162, 33)); //color for ItemView checked indicator (arrow)
- return palette;
-}
-
-
-/*! \reimp */
-void QWindowsMobileStyle::polish(QApplication *application) {
- QWindowsStyle::polish(application);
-}
-
-/*! \reimp */
-void QWindowsMobileStyle::polish(QWidget *widget) {
-
-#ifndef QT_NO_TOOLBAR
- if (QToolBar *toolBar = qobject_cast<QToolBar*>(widget)) {
- QPalette pal = toolBar->palette();
- pal.setColor(QPalette::Background, pal.button().color());
- toolBar->setPalette(pal);
- }
- else
-#endif //QT_NO_TOOLBAR
-
- QWindowsStyle::polish(widget);
-}
-
-void QWindowsMobileStyle::unpolish(QWidget *widget)
-{
- QWindowsStyle::unpolish(widget);
-}
-
-void QWindowsMobileStyle::unpolish(QApplication *app)
-{
- QWindowsStyle::unpolish(app);
-}
-
-/*! \reimp */
-void QWindowsMobileStyle::polish(QPalette &palette) {
- QWindowsStyle::polish(palette);
-}
-
-int QWindowsMobileStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QWidget *widget) const {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
- int ret;
-
- switch (pm) {
- case PM_DefaultTopLevelMargin:
- ret =0;
- break;
- case PM_DefaultLayoutSpacing:
- d->doubleControls ? ret = 8 : ret = 4;
- break;
- case PM_HeaderMargin:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
- case PM_DefaultChildMargin:
- d->doubleControls ? ret = 10 : ret = 5;
- break;
- case PM_ToolBarSeparatorExtent:
- d->doubleControls ? ret = 6 : ret = 3;
- break;
- case PM_DefaultFrameWidth:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
- case PM_MenuVMargin:
- ret = 1;
- break;
- case PM_MenuHMargin:
- ret = 1;
- break;
- case PM_MenuButtonIndicator:
- ret = d->doubleControls ? 24 : 14;
- break;
- case PM_ComboBoxFrameWidth:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
- case PM_SpinBoxFrameWidth:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
- case PM_ButtonDefaultIndicator:
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
-#ifndef QT_NO_TABBAR
- case PM_TabBarTabShiftHorizontal:
- ret = 0;
- break;
- case PM_TabBarTabShiftVertical:
- ret = 0;
- break;
-#endif
- case PM_MaximumDragDistance:
- ret = 60;
- break;
- case PM_TabBarTabVSpace:
- ret = d->doubleControls ? 12 : 6;
- break;
- case PM_TabBarBaseHeight:
- ret = 0;
- break;
- case PM_IndicatorWidth:
- ret = d->doubleControls ? windowsMobileIndicatorSize * 2 : windowsMobileIndicatorSize;
- break;
- case PM_IndicatorHeight:
- ret = d->doubleControls ? windowsMobileIndicatorSize * 2 : windowsMobileIndicatorSize;
- break;
- case PM_ExclusiveIndicatorWidth:
- ret = d->doubleControls ? windowsMobileExclusiveIndicatorSize * 2 + 4: windowsMobileExclusiveIndicatorSize + 2;
- break;
- case PM_ExclusiveIndicatorHeight:
- ret = d->doubleControls ? windowsMobileExclusiveIndicatorSize * 2 + 4: windowsMobileExclusiveIndicatorSize + 2;
- break;
-#ifndef QT_NO_SLIDER
- case PM_SliderLength:
- ret = d->doubleControls ? 16 : 8;
- break;
- case PM_FocusFrameHMargin:
- ret = d->doubleControls ? 1 : 2;
- break;
- case PM_SliderThickness:
- ret = d->doubleControls ? windowsMobileSliderThickness * 2: windowsMobileSliderThickness;
- break;
- case PM_TabBarScrollButtonWidth:
- ret = d->doubleControls ? 14 * 2 : 18;
- break;
- case PM_CheckBoxLabelSpacing:
- case PM_RadioButtonLabelSpacing:
- ret = d->doubleControls ? 6 * 2 : 6;
- break;
- // Returns the number of pixels to use for the business part of the
- // slider (i.e., the non-tickmark portion). The remaining space is shared
- // equally between the tickmark regions.
- case PM_SliderControlThickness:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int space = (sl->orientation == Qt::Horizontal) ? sl->rect.height() : sl->rect.width();
- int ticks = sl->tickPosition;
- int n = 0;
- if (ticks & QSlider::TicksAbove)
- ++n;
- if (ticks & QSlider::TicksBelow)
- ++n;
- if (!n) {
- ret = space;
- break;
- }
- int thick = 8;
- if (ticks != QSlider::TicksBothSides && ticks != QSlider::NoTicks)
- thick += proxy()->pixelMetric(PM_SliderLength, sl, widget) / 4;
-
- space -= thick;
- if (space > 0)
- thick += (space * 2) / (n + 2);
- ret = thick;
- } else {
- ret = 0;
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_MENU
- case PM_SmallIconSize:
- d->doubleControls ? ret = windowsMobileIconSize * 2 : ret = windowsMobileIconSize;
- break;
- case PM_ButtonMargin:
- d->doubleControls ? ret = 8 : ret = 4;
- break;
- case PM_LargeIconSize:
- d->doubleControls ? ret = 64 : ret = 32;
- break;
- case PM_IconViewIconSize:
- ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget);
- break;
- case PM_ToolBarIconSize:
- d->doubleControls ? ret = 2 * windowsMobileIconSize : ret = windowsMobileIconSize;
- break;
- case PM_DockWidgetTitleMargin:
- ret = 2;
- break;
-#if defined(Q_WS_WIN)
-#else
- case PM_DockWidgetFrameWidth:
- ret = 4;
- break;
-#endif // Q_WS_WIN
- break;
-#endif // QT_NO_MENU
-
- case PM_TitleBarHeight:
- d->doubleControls ? ret = 42 : ret = 21;
- break;
- case PM_ScrollBarSliderMin:
-#ifdef Q_WS_WINCE_WM
- if (d->wm65)
-#else
- if (false)
-#endif
- {
- d->doubleControls ? ret = 68 : ret = 34;
- } else {
- d->doubleControls ? ret = 36 : ret = 18;
- }
- break;
- case PM_ScrollBarExtent: {
-
- if (d->smartphone)
- ret = 9;
- else
- d->doubleControls ? ret = 25 : ret = 13;
-
-#ifdef Q_WS_WINCE_WM
- if (d->wm65)
-#else
- if (false)
-#endif
- {
- d->doubleControls ? ret = 26 : ret = 13;
- break;
- }
-
-#ifndef QT_NO_SCROLLAREA
- //Check if the scrollbar is part of an abstractItemView and set size according
- if (widget)
- if (QWidget *parent = widget->parentWidget())
- if (qobject_cast<QAbstractScrollArea *>(parent->parentWidget()))
- if (d->smartphone)
- ret = 8;
- else
- d->doubleControls ? ret = 24 : ret = 12;
-#endif
- }
- break;
- case PM_SplitterWidth:
- ret = qMax(4, QApplication::globalStrut().width());
- break;
-
-#if defined(Q_WS_WIN)
- case PM_MDIFrameWidth:
- ret = 1;
- break;
-#endif
- case PM_ToolBarExtensionExtent:
- d->doubleControls ? ret = 32 : ret = 16;
- break;
- case PM_ToolBarItemMargin:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
- case PM_ToolBarItemSpacing:
- d->doubleControls ? ret = 2 : ret = 1;
- break;
- case PM_ToolBarHandleExtent:
- d->doubleControls ? ret = 16 : ret = 8;
- break;
- case PM_ButtonIconSize:
- d->doubleControls ? ret = 32 : ret = 16;
- break;
- case PM_TextCursorWidth:
- ret = 2;
- break;
- case PM_TabBar_ScrollButtonOverlap:
- ret = 0;
- break;
- default:
- ret = QWindowsStyle::pixelMetric(pm, opt, widget);
- break;
- }
- return ret;
-}
-
-int QWindowsMobileStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWidget *widget,
- QStyleHintReturn *returnData) const {
-
- int ret;
- switch (hint) {
- case SH_Menu_MouseTracking:
- case SH_ComboBox_ListMouseTracking:
- case SH_EtchDisabledText:
- ret = 0;
- break;
- case SH_DitherDisabledText:
- ret = 0;
- break;
- case SH_ItemView_ShowDecorationSelected:
- ret = 0;
- break;
-#ifndef QT_NO_TABWIDGET
- case SH_TabWidget_DefaultTabPosition:
- ret = QTabWidget::South;
- break;
-#endif
- case SH_ToolBar_Movable:
- ret = false;
- break;
- case SH_ScrollBar_ContextMenu:
- ret = false;
- break;
- case SH_MenuBar_AltKeyNavigation:
- ret = false;
- break;
- case SH_RequestSoftwareInputPanel:
- ret = RSIP_OnMouseClick;
- break;
- default:
- ret = QWindowsStyle::styleHint(hint, opt, widget, returnData);
- break;
- }
- return ret;
-}
-
-QPixmap QWindowsMobileStyle::standardPixmap(StandardPixmap sp, const QStyleOption *option,
- const QWidget *widget) const {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
- switch (sp) {
-#ifndef QT_NO_IMAGEFORMAT_XPM
- case SP_ToolBarHorizontalExtensionButton: {
- QPixmap pixmap = QCommonStyle::standardPixmap(sp, option, widget);
- if (d->doubleControls)
- return pixmap.scaledToHeight(pixmap.height() * 2);
- else
- return pixmap;
- }
- case SP_TitleBarMaxButton:
- case SP_TitleBarCloseButton:
- case SP_TitleBarNormalButton:
- case SP_TitleBarMinButton: {
- QImage image;
- switch (sp) {
- case SP_TitleBarMaxButton:
- image = d->imageMaximize;
- break;
- case SP_TitleBarCloseButton:
- image = d->imageClose;
- break;
- case SP_TitleBarNormalButton:
- image = d->imageNormalize;
- break;
- case SP_TitleBarMinButton:
- image = d->imageMinimize;
- break;
- default:
- break;
- }
- if (option) {
- image.setColor(0, option->palette.shadow().color().rgba());
- image.setColor(1, option->palette.highlight().color().rgba());
- image.setColor(2, option->palette.highlight().color().lighter(150).rgba());
- image.setColor(3, option->palette.highlightedText().color().rgba());
- }
-
- return QPixmap::fromImage(image);
- }
-
-#endif
- default:
- return QWindowsStyle::standardPixmap(sp, option, widget);
- }
-}
-
-QPixmap QWindowsMobileStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *option) const {
-
- switch (iconMode) {
- case QIcon::Selected: {
-#ifdef Q_WS_WINCE_WM
- if (d_func()->wm65)
- return pixmap;
-#endif //Q_WS_WINCE_WM
- QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
- int imgh = img.height();
- int imgw = img.width();
- for (int y = 0; y < imgh; y += 2) {
- for (int x = 0; x < imgw; x += 2) {
- QColor c = option->palette.highlight().color().rgb();
- c.setAlpha( qAlpha(img.pixel(x, y)));
- QRgb pixel = c.rgba();
- img.setPixel(x, y, pixel);
- }
- }
- return QPixmap::fromImage(img);
- }
- default:
- break;
- }
- return QWindowsStyle::generatedIconPixmap(iconMode, pixmap, option);
-}
-
-
-bool QWindowsMobileStyle::doubleControls() const {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
-
- return d->doubleControls;
-}
-
-void QWindowsMobileStyle::setDoubleControls(bool doubleControls) {
-
- QWindowsMobileStylePrivate *d = const_cast<QWindowsMobileStylePrivate*>(d_func());
-
- d->doubleControls = doubleControls;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSMOBILE
-
diff --git a/src/gui/styles/qwindowsmobilestyle.h b/src/gui/styles/qwindowsmobilestyle.h
deleted file mode 100644
index 6ac1af1c35..0000000000
--- a/src/gui/styles/qwindowsmobilestyle.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSMOBILESTYLE_H
-#define QWINDOWSMOBILESTYLE_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_WINDOWSMOBILE)
-
-class QWindowsMobileStylePrivate;
-
-class Q_GUI_EXPORT QWindowsMobileStyle : public QWindowsStyle
-{
- Q_OBJECT
-public:
- QWindowsMobileStyle();
-
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget = 0) const;
-
- void drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const;
-
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const;
-
- QSize sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const;
-
- QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const;
-
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const;
-
- QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
- const QStyleOption *option) const;
-
- QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *option,
- const QWidget *widget) const;
-
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
-
- int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
-
- void polish(QApplication*);
- void unpolish(QApplication*);
- void polish(QWidget *widget);
- void unpolish(QWidget *widget);
- void polish(QPalette &);
-
- QPalette standardPalette() const;
-
- bool doubleControls() const;
-
- void setDoubleControls(bool);
-
-protected:
- QWindowsMobileStyle(QWindowsMobileStylePrivate &dd);
-
-private:
- Q_DECLARE_PRIVATE(QWindowsMobileStyle)
-};
-
-#endif // QT_NO_STYLE_WINDOWSMOBILE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //QWINDOWSMOBILESTYLE_H
diff --git a/src/gui/styles/qwindowsmobilestyle_p.h b/src/gui/styles/qwindowsmobilestyle_p.h
deleted file mode 100644
index cfc6aea1c6..0000000000
--- a/src/gui/styles/qwindowsmobilestyle_p.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSMOBILESTYLE_P_H
-#define QWINDOWSMOBILESTYLE_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qwindowsmobilestyle.h"
-#include "qwindowsstyle_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_STYLE_WINDOWSMOBILE
-
-class QStyleOptionTab;
-class QStyleOptionSlider;
-class QStyleOptionViewItemV4;
-
-class QWindowsMobileStylePrivate : public QWindowsStylePrivate
-{
- Q_DECLARE_PUBLIC(QWindowsMobileStyle)
-public:
- QWindowsMobileStylePrivate();
- bool doubleControls;
- bool smartphone;
-#ifdef Q_WS_WINCE_WM
- bool wm65;
-#endif
-
- QImage imageRadioButton;
- QImage imageRadioButtonChecked;
- QImage imageRadioButtonHighlighted;
- QImage imageChecked;
- QImage imageCheckedBold;
- QImage imageArrowDown;
- QImage imageArrowUp;
- QImage imageArrowLeft;
- QImage imageArrowRight;
- QImage imageArrowDownBig;
- QImage imageArrowUpBig;
- QImage imageArrowLeftBig;
- QImage imageArrowRightBig;
- QImage imageClose;
- QImage imageMaximize;
- QImage imageNormalize;
- QImage imageMinimize;
-
- void setupWindowsMobileStyle65();
-
-#ifdef Q_WS_WINCE_WM
- //Windows Mobile 6.5 images
- QImage imageScrollbarHandleUp;
- QImage imageScrollbarHandleDown;
- QImage imageScrollbarHandleUpHigh;
- QImage imageScrollbarHandleDownHigh;
- QImage imageScrollbarGripUp;
- QImage imageScrollbarGripDown;
- QImage imageScrollbarGripMiddle;
- QImage imageListViewHighlightCornerLeft;
- QImage imageListViewHighlightCornerRight;
- QImage imageListViewHighlightMiddle;
- QImage imageTabEnd;
- QImage imageTabSelectedEnd;
- QImage imageTabSelectedBegin;
- QImage imageTabMiddle;
-
- QColor currentTintHigh;
- QColor currentTintButton;
-
- void tintImagesHigh(QColor color);
- void tintImagesButton(QColor color);
- void tintListViewHighlight(QColor color);
-
-#endif //Q_WS_WINCE_WM
-
- void drawScrollbarHandleUp(QPainter *p, QStyleOptionSlider *opt, bool completeFrame = false, bool secondScrollBar = false);
- void drawScrollbarHandleDown(QPainter *p, QStyleOptionSlider *opt, bool completeFrame = false, bool secondScrollBar = false);
- void drawScrollbarGroove(QPainter *p, const QStyleOptionSlider *opt);
- void drawScrollbarGrip(QPainter *p, QStyleOptionSlider *newScrollbar, const QStyleOptionComplex *option, bool drawCompleteFrame);
- void drawTabBarTab(QPainter *p, const QStyleOptionTab *tab);
- void drawPanelItemViewSelected(QPainter *painter, const QStyleOptionViewItemV4 *option, QRect rect = QRect());
-
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSMOBILE
-#endif //QWINDOWSMOBILESTYLE_P_H
diff --git a/src/gui/styles/qwindowsstyle.cpp b/src/gui/styles/qwindowsstyle.cpp
deleted file mode 100644
index 44f3f92d8b..0000000000
--- a/src/gui/styles/qwindowsstyle.cpp
+++ /dev/null
@@ -1,3392 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwindowsstyle.h"
-#include "qwindowsstyle_p.h"
-
-#if !defined(QT_NO_STYLE_WINDOWS) || defined(QT_PLUGIN)
-
-#include <private/qsystemlibrary_p.h>
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qdrawutil.h" // for now
-#include "qevent.h"
-#include "qmenu.h"
-#include "qmenubar.h"
-#include <private/qmenubar_p.h>
-#include "qpaintengine.h"
-#include "qpainter.h"
-#include "qprogressbar.h"
-#include "qrubberband.h"
-#include "qstyleoption.h"
-#include "qtabbar.h"
-#include "qwidget.h"
-#include "qdebug.h"
-#include "qmainwindow.h"
-#include "qfile.h"
-#include "qtextstream.h"
-#include "qpixmapcache.h"
-#include "qwizard.h"
-#include "qlistview.h"
-#include <private/qmath_p.h>
-#include <qmath.h>
-
-#ifdef Q_WS_X11
-#include "qfileinfo.h"
-#include "qdir.h"
-#include <private/qt_x11_p.h>
-#endif
-
-#include <private/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#if defined(Q_WS_WIN)
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qt_windows.h"
-QT_END_INCLUDE_NAMESPACE
-# ifndef COLOR_GRADIENTACTIVECAPTION
-# define COLOR_GRADIENTACTIVECAPTION 27
-# endif
-# ifndef COLOR_GRADIENTINACTIVECAPTION
-# define COLOR_GRADIENTINACTIVECAPTION 28
-# endif
-
-
-typedef struct
-{
- DWORD cbSize;
- HICON hIcon;
- int iSysImageIndex;
- int iIcon;
- WCHAR szPath[MAX_PATH];
-} QSHSTOCKICONINFO;
-
-#define _SHGFI_SMALLICON 0x000000001
-#define _SHGFI_LARGEICON 0x000000000
-#define _SHGFI_ICON 0x000000100
-#define _SIID_SHIELD 77
-
-typedef HRESULT (WINAPI *PtrSHGetStockIconInfo)(int siid, int uFlags, QSHSTOCKICONINFO *psii);
-static PtrSHGetStockIconInfo pSHGetStockIconInfo = 0;
-
-#endif //Q_WS_WIN
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <limits.h>
-QT_END_INCLUDE_NAMESPACE
-
-enum QSliderDirection { SlUp, SlDown, SlLeft, SlRight };
-
-/*
- \internal
-*/
-QWindowsStylePrivate::QWindowsStylePrivate()
- : alt_down(false), menuBarTimer(0), animationFps(10), animateTimer(0), animateStep(0)
-{
-#if defined(Q_WS_WIN) && !defined(Q_OS_WINCE)
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) {
- QSystemLibrary shellLib(QLatin1String("shell32"));
- pSHGetStockIconInfo = (PtrSHGetStockIconInfo)shellLib.resolve("SHGetStockIconInfo");
- }
-#endif
- startTime.start();
-}
-
-// Returns true if the toplevel parent of \a widget has seen the Alt-key
-bool QWindowsStylePrivate::hasSeenAlt(const QWidget *widget) const
-{
- widget = widget->window();
- return seenAlt.contains(widget);
-}
-
-/*!
- \reimp
-*/
-void QWindowsStyle::timerEvent(QTimerEvent *event)
-{
-#ifndef QT_NO_PROGRESSBAR
- Q_D(QWindowsStyle);
- if (event->timerId() == d->animateTimer) {
- Q_ASSERT(d->animationFps> 0);
- d->animateStep = d->startTime.elapsed() / (1000 / d->animationFps);
- foreach (QProgressBar *bar, d->bars) {
- if ((bar->minimum() == 0 && bar->maximum() == 0))
- bar->update();
- }
- }
-#endif // QT_NO_PROGRESSBAR
- event->ignore();
-}
-
-/*!
- \reimp
-*/
-bool QWindowsStyle::eventFilter(QObject *o, QEvent *e)
-{
- // Records Alt- and Focus events
- if (!o->isWidgetType())
- return QObject::eventFilter(o, e);
-
- QWidget *widget = qobject_cast<QWidget*>(o);
- Q_D(QWindowsStyle);
- switch(e->type()) {
- case QEvent::KeyPress:
- if (static_cast<QKeyEvent *>(e)->key() == Qt::Key_Alt) {
- widget = widget->window();
-
- // Alt has been pressed - find all widgets that care
- QList<QWidget *> l = widget->findChildren<QWidget *>();
- for (int pos=0 ; pos < l.size() ; ++pos) {
- QWidget *w = l.at(pos);
- if (w->isWindow() || !w->isVisible() ||
- w->style()->styleHint(SH_UnderlineShortcut, 0, w))
- l.removeAt(pos);
- }
- // Update states before repainting
- d->seenAlt.append(widget);
- d->alt_down = true;
-
- // Repaint all relevant widgets
- for (int pos = 0; pos < l.size(); ++pos)
- l.at(pos)->update();
- }
- break;
- case QEvent::KeyRelease:
- if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Alt) {
- widget = widget->window();
-
- // Update state and repaint the menu bars.
- d->alt_down = false;
-#ifndef QT_NO_MENUBAR
- QList<QMenuBar *> l = widget->findChildren<QMenuBar *>();
- for (int i = 0; i < l.size(); ++i)
- l.at(i)->update();
-#endif
- }
- break;
- case QEvent::Close:
- // Reset widget when closing
- d->seenAlt.removeAll(widget);
- d->seenAlt.removeAll(widget->window());
- break;
-#ifndef QT_NO_PROGRESSBAR
- case QEvent::StyleChange:
- case QEvent::Show:
- if (QProgressBar *bar = qobject_cast<QProgressBar *>(o)) {
- if (!d->bars.contains(bar)) {
- d->bars << bar;
- if (d->bars.size() == 1) {
- Q_ASSERT(d->animationFps> 0);
- d->animateTimer = startTimer(1000 / d->animationFps);
- }
- }
- }
- break;
- case QEvent::Destroy:
- case QEvent::Hide:
- // reinterpret_cast because there is no type info when getting
- // the destroy event. We know that it is a QProgressBar.
- if (QProgressBar *bar = reinterpret_cast<QProgressBar *>(o)) {
- d->bars.removeAll(bar);
- if (d->bars.isEmpty() && d->animateTimer) {
- killTimer(d->animateTimer);
- d->animateTimer = 0;
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
- default:
- break;
- }
- return QCommonStyle::eventFilter(o, e);
-}
-
-/*!
- \class QWindowsStyle
- \brief The QWindowsStyle class provides a Microsoft Windows-like look and feel.
-
- \ingroup appearance
-
- This style is Qt's default GUI style on Windows.
-
- \img qwindowsstyle.png
- \sa QWindowsXPStyle, QMacStyle, QPlastiqueStyle, QCDEStyle, QMotifStyle
-*/
-
-/*!
- Constructs a QWindowsStyle object.
-*/
-QWindowsStyle::QWindowsStyle() : QCommonStyle(*new QWindowsStylePrivate)
-{
-}
-
-/*!
- \internal
-
- Constructs a QWindowsStyle object.
-*/
-QWindowsStyle::QWindowsStyle(QWindowsStylePrivate &dd) : QCommonStyle(dd)
-{
-}
-
-
-/*! Destroys the QWindowsStyle object. */
-QWindowsStyle::~QWindowsStyle()
-{
-}
-
-#ifdef Q_WS_WIN
-static inline QRgb colorref2qrgb(COLORREF col)
-{
- return qRgb(GetRValue(col), GetGValue(col), GetBValue(col));
-}
-#endif
-
-/*! \reimp */
-void QWindowsStyle::polish(QApplication *app)
-{
- QCommonStyle::polish(app);
- QWindowsStylePrivate *d = const_cast<QWindowsStylePrivate*>(d_func());
- // We only need the overhead when shortcuts are sometimes hidden
- if (!proxy()->styleHint(SH_UnderlineShortcut, 0) && app)
- app->installEventFilter(this);
-
- d->activeCaptionColor = app->palette().highlight().color();
- d->activeGradientCaptionColor = app->palette().highlight() .color();
- d->inactiveCaptionColor = app->palette().dark().color();
- d->inactiveGradientCaptionColor = app->palette().dark().color();
- d->inactiveCaptionText = app->palette().background().color();
-
-#if defined(Q_WS_WIN) //fetch native title bar colors
- if(app->desktopSettingsAware()){
- DWORD activeCaption = GetSysColor(COLOR_ACTIVECAPTION);
- DWORD gradientActiveCaption = GetSysColor(COLOR_GRADIENTACTIVECAPTION);
- DWORD inactiveCaption = GetSysColor(COLOR_INACTIVECAPTION);
- DWORD gradientInactiveCaption = GetSysColor(COLOR_GRADIENTINACTIVECAPTION);
- DWORD inactiveCaptionText = GetSysColor(COLOR_INACTIVECAPTIONTEXT);
- d->activeCaptionColor = colorref2qrgb(activeCaption);
- d->activeGradientCaptionColor = colorref2qrgb(gradientActiveCaption);
- d->inactiveCaptionColor = colorref2qrgb(inactiveCaption);
- d->inactiveGradientCaptionColor = colorref2qrgb(gradientInactiveCaption);
- d->inactiveCaptionText = colorref2qrgb(inactiveCaptionText);
- }
-#endif
-}
-
-/*! \reimp */
-void QWindowsStyle::unpolish(QApplication *app)
-{
- QCommonStyle::unpolish(app);
- app->removeEventFilter(this);
-}
-
-/*! \reimp */
-void QWindowsStyle::polish(QWidget *widget)
-{
- QCommonStyle::polish(widget);
-#ifndef QT_NO_PROGRESSBAR
- if (qobject_cast<QProgressBar *>(widget))
- widget->installEventFilter(this);
-#endif
-}
-
-/*! \reimp */
-void QWindowsStyle::unpolish(QWidget *widget)
-{
- QCommonStyle::unpolish(widget);
-#ifndef QT_NO_PROGRESSBAR
- if (QProgressBar *bar=qobject_cast<QProgressBar *>(widget)) {
- Q_D(QWindowsStyle);
- widget->removeEventFilter(this);
- d->bars.removeAll(bar);
- }
-#endif
-}
-
-/*!
- \reimp
-*/
-void QWindowsStyle::polish(QPalette &pal)
-{
- QCommonStyle::polish(pal);
-}
-
-/*!
- \reimp
-*/
-int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QWidget *widget) const
-{
- int ret;
-
- switch (pm) {
- case PM_ButtonDefaultIndicator:
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- case PM_MenuHMargin:
- case PM_MenuVMargin:
- ret = 1;
- break;
-#ifndef QT_NO_TABBAR
- case PM_TabBarTabShiftHorizontal:
- ret = 0;
- break;
- case PM_TabBarTabShiftVertical:
- ret = 2;
- break;
-#endif
- case PM_MaximumDragDistance:
-#if defined(Q_WS_WIN)
- {
- HDC hdcScreen = GetDC(0);
- int dpi = GetDeviceCaps(hdcScreen, LOGPIXELSX);
- ReleaseDC(0, hdcScreen);
- ret = (int)(dpi * 1.375);
- }
-#else
- ret = 60;
-#endif
- break;
-
-#ifndef QT_NO_SLIDER
- case PM_SliderLength:
- ret = int(QStyleHelper::dpiScaled(11.));
- break;
-
- // Returns the number of pixels to use for the business part of the
- // slider (i.e., the non-tickmark portion). The remaining space is shared
- // equally between the tickmark regions.
- case PM_SliderControlThickness:
- if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int space = (sl->orientation == Qt::Horizontal) ? sl->rect.height() : sl->rect.width();
- int ticks = sl->tickPosition;
- int n = 0;
- if (ticks & QSlider::TicksAbove)
- ++n;
- if (ticks & QSlider::TicksBelow)
- ++n;
- if (!n) {
- ret = space;
- break;
- }
-
- int thick = 6; // Magic constant to get 5 + 16 + 5
- if (ticks != QSlider::TicksBothSides && ticks != QSlider::NoTicks)
- thick += proxy()->pixelMetric(PM_SliderLength, sl, widget) / 4;
-
- space -= thick;
- if (space > 0)
- thick += (space * 2) / (n + 2);
- ret = thick;
- } else {
- ret = 0;
- }
- break;
-#endif // QT_NO_SLIDER
-
-#ifndef QT_NO_MENU
- case PM_MenuBarHMargin:
- ret = 0;
- break;
-
- case PM_MenuBarVMargin:
- ret = 0;
- break;
-
- case PM_MenuBarPanelWidth:
- ret = 0;
- break;
-
- case PM_SmallIconSize:
- ret = int(QStyleHelper::dpiScaled(16.));
- break;
-
- case PM_LargeIconSize:
- ret = int(QStyleHelper::dpiScaled(32.));
- break;
-
- case PM_IconViewIconSize:
- ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget);
- break;
-
- case PM_DockWidgetTitleMargin:
- ret = int(QStyleHelper::dpiScaled(2.));
- break;
- case PM_DockWidgetTitleBarButtonMargin:
- ret = int(QStyleHelper::dpiScaled(4.));
- break;
-#if defined(Q_WS_WIN)
- case PM_DockWidgetFrameWidth:
-#if defined(Q_OS_WINCE)
- ret = GetSystemMetrics(SM_CXDLGFRAME);
-#else
- ret = GetSystemMetrics(SM_CXFRAME);
-#endif
- break;
-#else
- case PM_DockWidgetFrameWidth:
- ret = 4;
- break;
-#endif // Q_WS_WIN
- break;
-
-#endif // QT_NO_MENU
-
-
-#if defined(Q_WS_WIN)
- case PM_TitleBarHeight:
-#ifdef QT3_SUPPORT
- // qt3 dockwindow height should be equal to tool windows
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- ret = GetSystemMetrics(SM_CYSMCAPTION) - 1;
- } else
-#endif
- if (widget && (widget->windowType() == Qt::Tool)) {
- // MS always use one less than they say
-#if defined(Q_OS_WINCE)
- ret = GetSystemMetrics(SM_CYCAPTION) - 1;
-#else
- ret = GetSystemMetrics(SM_CYSMCAPTION) - 1;
-#endif
- } else {
- ret = GetSystemMetrics(SM_CYCAPTION) - 1;
- }
-
- break;
-
- case PM_ScrollBarExtent:
- {
-#ifndef Q_OS_WINCE
- NONCLIENTMETRICS ncm;
- ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT);
- if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0))
- ret = qMax(ncm.iScrollHeight, ncm.iScrollWidth);
- else
-#endif
- ret = QCommonStyle::pixelMetric(pm, opt, widget);
- }
- break;
-#endif // Q_WS_WIN
-
- case PM_SplitterWidth:
- ret = qMax(4, QApplication::globalStrut().width());
- break;
-
-#if defined(Q_WS_WIN)
- case PM_MdiSubWindowFrameWidth:
-#if defined(Q_OS_WINCE)
- ret = GetSystemMetrics(SM_CYDLGFRAME);
-#else
- ret = GetSystemMetrics(SM_CYFRAME);
-#endif
- break;
- case PM_TextCursorWidth: {
- DWORD caretWidth = 1;
-#if defined(SPI_GETCARETWIDTH)
- SystemParametersInfo(SPI_GETCARETWIDTH, 0, &caretWidth, 0);
-#endif
- ret = (int)caretWidth;
- break; }
-#endif
- case PM_ToolBarItemMargin:
- ret = 1;
- break;
- case PM_ToolBarItemSpacing:
- ret = 0;
- break;
- case PM_ToolBarHandleExtent:
- ret = int(QStyleHelper::dpiScaled(10.));
- break;
- default:
- ret = QCommonStyle::pixelMetric(pm, opt, widget);
- break;
- }
-
- return ret;
-}
-
-#ifndef QT_NO_IMAGEFORMAT_XPM
-
-/* XPM */
-static const char * const qt_menu_xpm[] = {
-"16 16 72 1",
-" c None",
-". c #65AF36",
-"+ c #66B036",
-"@ c #77B94C",
-"# c #A7D28C",
-"$ c #BADBA4",
-"% c #A4D088",
-"& c #72B646",
-"* c #9ACB7A",
-"= c #7FBD56",
-"- c #85C05F",
-"; c #F4F9F0",
-"> c #FFFFFF",
-", c #E5F1DC",
-"' c #ECF5E7",
-") c #7ABA50",
-"! c #83BF5C",
-"~ c #AED595",
-"{ c #D7EACA",
-"] c #A9D28D",
-"^ c #BCDDA8",
-"/ c #C4E0B1",
-"( c #81BE59",
-"_ c #D0E7C2",
-": c #D4E9C6",
-"< c #6FB542",
-"[ c #6EB440",
-"} c #88C162",
-"| c #98CA78",
-"1 c #F4F9F1",
-"2 c #8FC56C",
-"3 c #F1F8EC",
-"4 c #E8F3E1",
-"5 c #D4E9C7",
-"6 c #74B748",
-"7 c #80BE59",
-"8 c #73B747",
-"9 c #6DB43F",
-"0 c #CBE4BA",
-"a c #80BD58",
-"b c #6DB33F",
-"c c #FEFFFE",
-"d c #68B138",
-"e c #F9FCF7",
-"f c #91C66F",
-"g c #E8F3E0",
-"h c #DCEDD0",
-"i c #91C66E",
-"j c #A3CF86",
-"k c #C9E3B8",
-"l c #B0D697",
-"m c #E3F0DA",
-"n c #95C873",
-"o c #E6F2DE",
-"p c #9ECD80",
-"q c #BEDEAA",
-"r c #C7E2B6",
-"s c #79BA4F",
-"t c #6EB441",
-"u c #BCDCA7",
-"v c #FAFCF8",
-"w c #F6FAF3",
-"x c #84BF5D",
-"y c #EDF6E7",
-"z c #FAFDF9",
-"A c #88C263",
-"B c #98CA77",
-"C c #CDE5BE",
-"D c #67B037",
-"E c #D9EBCD",
-"F c #6AB23C",
-"G c #77B94D",
-" .++++++++++++++",
-".+++++++++++++++",
-"+++@#$%&+++*=+++",
-"++-;>,>')+!>~+++",
-"++{>]+^>/(_>:~<+",
-"+[>>}+|>123>456+",
-"+7>>8+->>90>~+++",
-"+a>>b+a>c[0>~+++",
-"+de>=+f>g+0>~+++",
-"++h>i+j>k+0>~+++",
-"++l>mno>p+q>rst+",
-"++duv>wl++xy>zA+",
-"++++B>Cb++++&D++",
-"+++++0zE++++++++",
-"++++++FG+++++++.",
-"++++++++++++++. "};
-
-static const char * const qt_close_xpm[] = {
-"10 10 2 1",
-"# c #000000",
-". c None",
-"..........",
-".##....##.",
-"..##..##..",
-"...####...",
-"....##....",
-"...####...",
-"..##..##..",
-".##....##.",
-"..........",
-".........."};
-
-static const char * const qt_maximize_xpm[]={
-"10 10 2 1",
-"# c #000000",
-". c None",
-"#########.",
-"#########.",
-"#.......#.",
-"#.......#.",
-"#.......#.",
-"#.......#.",
-"#.......#.",
-"#.......#.",
-"#########.",
-".........."};
-
-static const char * const qt_minimize_xpm[] = {
-"10 10 2 1",
-"# c #000000",
-". c None",
-"..........",
-"..........",
-"..........",
-"..........",
-"..........",
-"..........",
-"..........",
-".#######..",
-".#######..",
-".........."};
-
-static const char * const qt_normalizeup_xpm[] = {
-"10 10 2 1",
-"# c #000000",
-". c None",
-"...######.",
-"...######.",
-"...#....#.",
-".######.#.",
-".######.#.",
-".#....###.",
-".#....#...",
-".#....#...",
-".######...",
-".........."};
-
-static const char * const qt_help_xpm[] = {
-"10 10 2 1",
-". c None",
-"# c #000000",
-"..........",
-"..######..",
-".##....##.",
-"......##..",
-".....##...",
-"....##....",
-"....##....",
-"..........",
-"....##....",
-".........."};
-
-static const char * const qt_shade_xpm[] = {
-"10 10 2 1",
-"# c #000000",
-". c None",
-"..........",
-"..........",
-"..........",
-"..........",
-"....#.....",
-"...###....",
-"..#####...",
-".#######..",
-"..........",
-".........."};
-
-static const char * const qt_unshade_xpm[] = {
-"10 10 2 1",
-"# c #000000",
-". c None",
-"..........",
-"..........",
-"..........",
-".#######..",
-"..#####...",
-"...###....",
-"....#.....",
-"..........",
-"..........",
-".........."};
-
-static const char * dock_widget_close_xpm[] = {
-"8 8 2 1",
-"# c #000000",
-". c None",
-"........",
-".##..##.",
-"..####..",
-"...##...",
-"..####..",
-".##..##.",
-"........",
-"........"};
-
-/* XPM */
-static const char * const information_xpm[]={
-"32 32 5 1",
-". c None",
-"c c #000000",
-"* c #999999",
-"a c #ffffff",
-"b c #0000ff",
-"...........********.............",
-"........***aaaaaaaa***..........",
-"......**aaaaaaaaaaaaaa**........",
-".....*aaaaaaaaaaaaaaaaaa*.......",
-"....*aaaaaaaabbbbaaaaaaaac......",
-"...*aaaaaaaabbbbbbaaaaaaaac.....",
-"..*aaaaaaaaabbbbbbaaaaaaaaac....",
-".*aaaaaaaaaaabbbbaaaaaaaaaaac...",
-".*aaaaaaaaaaaaaaaaaaaaaaaaaac*..",
-"*aaaaaaaaaaaaaaaaaaaaaaaaaaaac*.",
-"*aaaaaaaaaabbbbbbbaaaaaaaaaaac*.",
-"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
-"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
-"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
-"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
-"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
-".*aaaaaaaaaaabbbbbaaaaaaaaaac***",
-".*aaaaaaaaaaabbbbbaaaaaaaaaac***",
-"..*aaaaaaaaaabbbbbaaaaaaaaac***.",
-"...caaaaaaabbbbbbbbbaaaaaac****.",
-"....caaaaaaaaaaaaaaaaaaaac****..",
-".....caaaaaaaaaaaaaaaaaac****...",
-"......ccaaaaaaaaaaaaaacc****....",
-".......*cccaaaaaaaaccc*****.....",
-"........***cccaaaac*******......",
-"..........****caaac*****........",
-".............*caaac**...........",
-"...............caac**...........",
-"................cac**...........",
-".................cc**...........",
-"..................***...........",
-"...................**..........."};
-/* XPM */
-static const char* const warning_xpm[]={
-"32 32 4 1",
-". c None",
-"a c #ffff00",
-"* c #000000",
-"b c #999999",
-".............***................",
-"............*aaa*...............",
-"...........*aaaaa*b.............",
-"...........*aaaaa*bb............",
-"..........*aaaaaaa*bb...........",
-"..........*aaaaaaa*bb...........",
-".........*aaaaaaaaa*bb..........",
-".........*aaaaaaaaa*bb..........",
-"........*aaaaaaaaaaa*bb.........",
-"........*aaaa***aaaa*bb.........",
-".......*aaaa*****aaaa*bb........",
-".......*aaaa*****aaaa*bb........",
-"......*aaaaa*****aaaaa*bb.......",
-"......*aaaaa*****aaaaa*bb.......",
-".....*aaaaaa*****aaaaaa*bb......",
-".....*aaaaaa*****aaaaaa*bb......",
-"....*aaaaaaaa***aaaaaaaa*bb.....",
-"....*aaaaaaaa***aaaaaaaa*bb.....",
-"...*aaaaaaaaa***aaaaaaaaa*bb....",
-"...*aaaaaaaaaa*aaaaaaaaaa*bb....",
-"..*aaaaaaaaaaa*aaaaaaaaaaa*bb...",
-"..*aaaaaaaaaaaaaaaaaaaaaaa*bb...",
-".*aaaaaaaaaaaa**aaaaaaaaaaa*bb..",
-".*aaaaaaaaaaa****aaaaaaaaaa*bb..",
-"*aaaaaaaaaaaa****aaaaaaaaaaa*bb.",
-"*aaaaaaaaaaaaa**aaaaaaaaaaaa*bb.",
-"*aaaaaaaaaaaaaaaaaaaaaaaaaaa*bbb",
-"*aaaaaaaaaaaaaaaaaaaaaaaaaaa*bbb",
-".*aaaaaaaaaaaaaaaaaaaaaaaaa*bbbb",
-"..*************************bbbbb",
-"....bbbbbbbbbbbbbbbbbbbbbbbbbbb.",
-".....bbbbbbbbbbbbbbbbbbbbbbbbb.."};
-/* XPM */
-static const char* const critical_xpm[]={
-"32 32 4 1",
-". c None",
-"a c #999999",
-"* c #ff0000",
-"b c #ffffff",
-"...........********.............",
-".........************...........",
-".......****************.........",
-"......******************........",
-".....********************a......",
-"....**********************a.....",
-"...************************a....",
-"..*******b**********b*******a...",
-"..******bbb********bbb******a...",
-".******bbbbb******bbbbb******a..",
-".*******bbbbb****bbbbb*******a..",
-"*********bbbbb**bbbbb*********a.",
-"**********bbbbbbbbbb**********a.",
-"***********bbbbbbbb***********aa",
-"************bbbbbb************aa",
-"************bbbbbb************aa",
-"***********bbbbbbbb***********aa",
-"**********bbbbbbbbbb**********aa",
-"*********bbbbb**bbbbb*********aa",
-".*******bbbbb****bbbbb*******aa.",
-".******bbbbb******bbbbb******aa.",
-"..******bbb********bbb******aaa.",
-"..*******b**********b*******aa..",
-"...************************aaa..",
-"....**********************aaa...",
-"....a********************aaa....",
-".....a******************aaa.....",
-"......a****************aaa......",
-".......aa************aaaa.......",
-".........aa********aaaaa........",
-"...........aaaaaaaaaaa..........",
-".............aaaaaaa............"};
-/* XPM */
-static const char *const question_xpm[] = {
-"32 32 5 1",
-". c None",
-"c c #000000",
-"* c #999999",
-"a c #ffffff",
-"b c #0000ff",
-"...........********.............",
-"........***aaaaaaaa***..........",
-"......**aaaaaaaaaaaaaa**........",
-".....*aaaaaaaaaaaaaaaaaa*.......",
-"....*aaaaaaaaaaaaaaaaaaaac......",
-"...*aaaaaaaabbbbbbaaaaaaaac.....",
-"..*aaaaaaaabaaabbbbaaaaaaaac....",
-".*aaaaaaaabbaaaabbbbaaaaaaaac...",
-".*aaaaaaaabbbbaabbbbaaaaaaaac*..",
-"*aaaaaaaaabbbbaabbbbaaaaaaaaac*.",
-"*aaaaaaaaaabbaabbbbaaaaaaaaaac*.",
-"*aaaaaaaaaaaaabbbbaaaaaaaaaaac**",
-"*aaaaaaaaaaaaabbbaaaaaaaaaaaac**",
-"*aaaaaaaaaaaaabbaaaaaaaaaaaaac**",
-"*aaaaaaaaaaaaabbaaaaaaaaaaaaac**",
-"*aaaaaaaaaaaaaaaaaaaaaaaaaaaac**",
-".*aaaaaaaaaaaabbaaaaaaaaaaaac***",
-".*aaaaaaaaaaabbbbaaaaaaaaaaac***",
-"..*aaaaaaaaaabbbbaaaaaaaaaac***.",
-"...caaaaaaaaaabbaaaaaaaaaac****.",
-"....caaaaaaaaaaaaaaaaaaaac****..",
-".....caaaaaaaaaaaaaaaaaac****...",
-"......ccaaaaaaaaaaaaaacc****....",
-".......*cccaaaaaaaaccc*****.....",
-"........***cccaaaac*******......",
-"..........****caaac*****........",
-".............*caaac**...........",
-"...............caac**...........",
-"................cac**...........",
-".................cc**...........",
-"..................***...........",
-"...................**..........."};
-
-#endif //QT_NO_IMAGEFORMAT_XPM
-
-#ifdef Q_OS_WIN
-static QPixmap loadIconFromShell32( int resourceId, int size )
-{
-#ifdef Q_OS_WINCE
- HMODULE hmod = LoadLibrary(L"ceshell");
-#else
- HMODULE hmod = QSystemLibrary::load(L"shell32");
-#endif
- if( hmod ) {
- HICON iconHandle = (HICON)LoadImage(hmod, MAKEINTRESOURCE(resourceId), IMAGE_ICON, size, size, 0);
- if( iconHandle ) {
- QPixmap iconpixmap = QPixmap::fromWinHICON( iconHandle );
- DestroyIcon(iconHandle);
- return iconpixmap;
- }
- }
- return QPixmap();
-}
-#endif
-
-/*!
- \reimp
- */
-QPixmap QWindowsStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget) const
-{
-#if defined(Q_WS_WIN) && !defined(Q_OS_WINCE)
- QPixmap desktopIcon;
- switch(standardPixmap) {
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- {
- desktopIcon = loadIconFromShell32(12, 16);
- break;
- }
- case SP_DriveNetIcon:
- {
- desktopIcon = loadIconFromShell32(10, 16);
- break;
- }
- case SP_DriveHDIcon:
- {
- desktopIcon = loadIconFromShell32(9, 16);
- break;
- }
- case SP_DriveFDIcon:
- {
- desktopIcon = loadIconFromShell32(7, 16);
- break;
- }
- case SP_FileIcon:
- {
- desktopIcon = loadIconFromShell32(1, 16);
- break;
- }
- case SP_FileLinkIcon:
- {
- desktopIcon = loadIconFromShell32(1, 16);
- QPainter painter(&desktopIcon);
- QPixmap link = loadIconFromShell32(30, 16);
- painter.drawPixmap(0, 0, 16, 16, link);
- break;
- }
- case SP_DirLinkIcon:
- {
- desktopIcon = loadIconFromShell32(4, 16);
- QPainter painter(&desktopIcon);
- QPixmap link = loadIconFromShell32(30, 16);
- painter.drawPixmap(0, 0, 16, 16, link);
- break;
- }
- case SP_DirClosedIcon:
- {
- desktopIcon = loadIconFromShell32(4, 16);
- break;
- }
- case SP_DesktopIcon:
- {
- desktopIcon = loadIconFromShell32(35, 16);
- break;
- }
- case SP_ComputerIcon:
- {
- desktopIcon = loadIconFromShell32(16, 16);
- break;
- }
- case SP_DirOpenIcon:
- {
- desktopIcon = loadIconFromShell32(5, 16);
- break;
- }
- case SP_FileDialogNewFolder:
- {
- desktopIcon = loadIconFromShell32(319, 16);
- break;
- }
- case SP_DirHomeIcon:
- {
- desktopIcon = loadIconFromShell32(235, 16);
- break;
- }
- case SP_TrashIcon:
- {
- desktopIcon = loadIconFromShell32(191, 16);
- break;
- }
- case SP_MessageBoxInformation:
- {
- HICON iconHandle = LoadIcon(NULL, IDI_INFORMATION);
- desktopIcon = QPixmap::fromWinHICON( iconHandle );
- DestroyIcon(iconHandle);
- break;
- }
- case SP_MessageBoxWarning:
- {
- HICON iconHandle = LoadIcon(NULL, IDI_WARNING);
- desktopIcon = QPixmap::fromWinHICON( iconHandle );
- DestroyIcon(iconHandle);
- break;
- }
- case SP_MessageBoxCritical:
- {
- HICON iconHandle = LoadIcon(NULL, IDI_ERROR);
- desktopIcon = QPixmap::fromWinHICON( iconHandle );
- DestroyIcon(iconHandle);
- break;
- }
- case SP_MessageBoxQuestion:
- {
- HICON iconHandle = LoadIcon(NULL, IDI_QUESTION);
- desktopIcon = QPixmap::fromWinHICON( iconHandle );
- DestroyIcon(iconHandle);
- break;
- }
- case SP_VistaShield:
- {
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based
- && pSHGetStockIconInfo)
- {
- QPixmap pixmap;
- QSHSTOCKICONINFO iconInfo;
- memset(&iconInfo, 0, sizeof(iconInfo));
- iconInfo.cbSize = sizeof(iconInfo);
- if (pSHGetStockIconInfo(_SIID_SHIELD, _SHGFI_ICON | _SHGFI_SMALLICON, &iconInfo) == S_OK) {
- pixmap = QPixmap::fromWinHICON(iconInfo.hIcon);
- DestroyIcon(iconInfo.hIcon);
- return pixmap;
- }
- }
- }
- break;
- default:
- break;
- }
- if (!desktopIcon.isNull()) {
- return desktopIcon;
- }
-#endif
-#ifndef QT_NO_IMAGEFORMAT_XPM
- switch (standardPixmap) {
- case SP_TitleBarMenuButton:
- return QPixmap(qt_menu_xpm);
- case SP_TitleBarShadeButton:
- return QPixmap(qt_shade_xpm);
- case SP_TitleBarUnshadeButton:
- return QPixmap(qt_unshade_xpm);
- case SP_TitleBarNormalButton:
- return QPixmap(qt_normalizeup_xpm);
- case SP_TitleBarMinButton:
- return QPixmap(qt_minimize_xpm);
- case SP_TitleBarMaxButton:
- return QPixmap(qt_maximize_xpm);
- case SP_TitleBarCloseButton:
- return QPixmap(qt_close_xpm);
- case SP_TitleBarContextHelpButton:
- return QPixmap(qt_help_xpm);
- case SP_DockWidgetCloseButton:
- return QPixmap(dock_widget_close_xpm);
- case SP_MessageBoxInformation:
- return QPixmap(information_xpm);
- case SP_MessageBoxWarning:
- return QPixmap(warning_xpm);
- case SP_MessageBoxCritical:
- return QPixmap(critical_xpm);
- case SP_MessageBoxQuestion:
- return QPixmap(question_xpm);
- default:
- break;
- }
-#endif //QT_NO_IMAGEFORMAT_XPM
- return QCommonStyle::standardPixmap(standardPixmap, opt, widget);
-}
-
-/*! \reimp */
-int QWindowsStyle::styleHint(StyleHint hint, const QStyleOption *opt, const QWidget *widget,
- QStyleHintReturn *returnData) const
-{
- int ret = 0;
-
- switch (hint) {
- case SH_EtchDisabledText:
- case SH_Slider_SnapToValue:
- case SH_PrintDialog_RightAlignButtons:
- case SH_FontDialog_SelectAssociatedText:
- case SH_Menu_AllowActiveAndDisabled:
- case SH_MenuBar_AltKeyNavigation:
- case SH_MenuBar_MouseTracking:
- case SH_Menu_MouseTracking:
- case SH_ComboBox_ListMouseTracking:
- case SH_ScrollBar_StopMouseOverSlider:
- case SH_MainWindow_SpaceBelowMenuBar:
- ret = 1;
-
- break;
- case SH_ItemView_ShowDecorationSelected:
-#ifndef QT_NO_LISTVIEW
- if (qobject_cast<const QListView*>(widget))
- ret = 1;
-#endif
- break;
- case SH_ItemView_ChangeHighlightOnFocus:
- ret = 1;
- break;
- case SH_ToolBox_SelectedPageTitleBold:
- ret = 0;
- break;
-
-#if defined(Q_WS_WIN)
- case SH_UnderlineShortcut:
- {
- ret = 1;
- BOOL cues = false;
- SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &cues, 0);
- ret = int(cues);
- // Do nothing if we always paint underlines
- Q_D(const QWindowsStyle);
- if (!ret && widget && d) {
-#ifndef QT_NO_MENUBAR
- const QMenuBar *menuBar = qobject_cast<const QMenuBar *>(widget);
- if (!menuBar && qobject_cast<const QMenu *>(widget)) {
- QWidget *w = QApplication::activeWindow();
- if (w && w != widget)
- menuBar = w->findChild<QMenuBar *>();
- }
- // If we paint a menu bar draw underlines if is in the keyboardState
- if (menuBar) {
- if (menuBar->d_func()->keyboardState || d->altDown())
- ret = 1;
- // Otherwise draw underlines if the toplevel widget has seen an alt-press
- } else
-#endif // QT_NO_MENUBAR
- if (d->hasSeenAlt(widget)) {
- ret = 1;
- }
- }
- break;
- }
-#endif
-#ifndef QT_NO_RUBBERBAND
- case SH_RubberBand_Mask:
- if (const QStyleOptionRubberBand *rbOpt = qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
- ret = 0;
- if (rbOpt->shape == QRubberBand::Rectangle) {
- ret = true;
- if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(returnData)) {
- mask->region = opt->rect;
- int size = 1;
- if (widget && widget->isWindow())
- size = 4;
- mask->region -= opt->rect.adjusted(size, size, -size, -size);
- }
- }
- }
- break;
-#endif // QT_NO_RUBBERBAND
- case SH_LineEdit_PasswordCharacter:
- {
-#ifdef Q_WS_WIN
- if (widget && (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) {
- const QFontMetrics &fm = widget->fontMetrics();
- if (fm.inFont(QChar(0x25CF)))
- ret = 0x25CF;
- else if (fm.inFont(QChar(0x2022)))
- ret = 0x2022;
- }
-#endif
- if (!ret)
- ret = '*';
- }
- break;
-#ifndef QT_NO_WIZARD
- case SH_WizardStyle:
- ret = QWizard::ModernStyle;
- break;
-#endif
- case SH_ItemView_ArrowKeysNavigateIntoChildren:
- ret = true;
- break;
- case SH_DialogButtonBox_ButtonsHaveIcons:
- ret = 0;
- break;
- default:
- ret = QCommonStyle::styleHint(hint, opt, widget, returnData);
- break;
- }
- return ret;
-}
-
-/*! \reimp */
-void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w) const
-{
- // Used to restore across fallthrough cases. Currently only used in PE_IndicatorCheckBox
- bool doRestore = false;
-
- switch (pe) {
-#ifndef QT_NO_TOOLBAR
- case PE_IndicatorToolBarSeparator:
- {
- QRect rect = opt->rect;
- const int margin = 2;
- QPen oldPen = p->pen();
- if(opt->state & State_Horizontal){
- const int offset = rect.width()/2;
- p->setPen(QPen(opt->palette.dark().color()));
- p->drawLine(rect.bottomLeft().x() + offset,
- rect.bottomLeft().y() - margin,
- rect.topLeft().x() + offset,
- rect.topLeft().y() + margin);
- p->setPen(QPen(opt->palette.light().color()));
- p->drawLine(rect.bottomLeft().x() + offset + 1,
- rect.bottomLeft().y() - margin,
- rect.topLeft().x() + offset + 1,
- rect.topLeft().y() + margin);
- }
- else{ //Draw vertical separator
- const int offset = rect.height()/2;
- p->setPen(QPen(opt->palette.dark().color()));
- p->drawLine(rect.topLeft().x() + margin ,
- rect.topLeft().y() + offset,
- rect.topRight().x() - margin,
- rect.topRight().y() + offset);
- p->setPen(QPen(opt->palette.light().color()));
- p->drawLine(rect.topLeft().x() + margin ,
- rect.topLeft().y() + offset + 1,
- rect.topRight().x() - margin,
- rect.topRight().y() + offset + 1);
- }
- p->setPen(oldPen);
- }
- break;
- case PE_IndicatorToolBarHandle:
- p->save();
- p->translate(opt->rect.x(), opt->rect.y());
- if (opt->state & State_Horizontal) {
- int x = opt->rect.width() / 2 - 4;
- if (opt->direction == Qt::RightToLeft)
- x -= 2;
- if (opt->rect.height() > 4) {
- qDrawShadePanel(p, x, 2, 3, opt->rect.height() - 4,
- opt->palette, false, 1, 0);
- qDrawShadePanel(p, x + 3, 2, 3, opt->rect.height() - 4,
- opt->palette, false, 1, 0);
- }
- } else {
- if (opt->rect.width() > 4) {
- int y = opt->rect.height() / 2 - 4;
- qDrawShadePanel(p, 2, y, opt->rect.width() - 4, 3,
- opt->palette, false, 1, 0);
- qDrawShadePanel(p, 2, y + 3, opt->rect.width() - 4, 3,
- opt->palette, false, 1, 0);
- }
- }
- p->restore();
- break;
-
-#endif // QT_NO_TOOLBAR
- case PE_FrameButtonTool:
- case PE_PanelButtonTool: {
- QPen oldPen = p->pen();
-#ifndef QT_NO_DOCKWIDGET
- if (w && w->inherits("QDockWidgetTitleButton")) {
- if (const QWidget *dw = w->parentWidget())
- if (dw->isWindow()){
- qDrawWinButton(p, opt->rect.adjusted(1, 1, 0, 0), opt->palette, opt->state & (State_Sunken | State_On),
- &opt->palette.button());
-
- return;
- }
- }
-#endif // QT_NO_DOCKWIDGET
- QBrush fill;
- bool stippled;
- bool panel = (pe == PE_PanelButtonTool);
- if ((!(opt->state & State_Sunken ))
- && (!(opt->state & State_Enabled)
- || !(opt->state & State_MouseOver && opt->state & State_AutoRaise))
- && (opt->state & State_On)) {
- fill = QBrush(opt->palette.light().color(), Qt::Dense4Pattern);
- stippled = true;
- } else {
- fill = opt->palette.brush(QPalette::Button);
- stippled = false;
- }
-
- if (opt->state & (State_Raised | State_Sunken | State_On)) {
- if (opt->state & State_AutoRaise) {
- if(opt->state & (State_Enabled | State_Sunken | State_On)){
- if (panel)
- qDrawShadePanel(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), 1, &fill);
- else
- qDrawShadeRect(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), 1);
- }
- if (stippled) {
- p->setPen(opt->palette.button().color());
- p->drawRect(opt->rect.adjusted(1,1,-2,-2));
- }
- } else {
- qDrawWinButton(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), panel ? &fill : 0);
- }
- } else {
- p->fillRect(opt->rect, fill);
- }
- p->setPen(oldPen);
- break; }
- case PE_PanelButtonCommand:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- QBrush fill;
- State flags = opt->state;
- QPalette pal = opt->palette;
- QRect r = opt->rect;
- if (! (flags & State_Sunken) && (flags & State_On))
- fill = QBrush(pal.light().color(), Qt::Dense4Pattern);
- else
- fill = pal.brush(QPalette::Button);
-
- if (btn->features & QStyleOptionButton::DefaultButton && flags & State_Sunken) {
- p->setPen(pal.dark().color());
- p->setBrush(fill);
- p->drawRect(r.adjusted(0, 0, -1, -1));
- } else if (flags & (State_Raised | State_Sunken | State_On | State_Sunken)) {
- qDrawWinButton(p, r, pal, flags & (State_Sunken | State_On),
- &fill);
- } else {
- p->fillRect(r, fill);
- }
- }
- break;
- case PE_FrameDefaultButton: {
- QPen oldPen = p->pen();
- p->setPen(opt->palette.shadow().color());
- QRect rect = opt->rect;
- rect.adjust(0, 0, -1, -1);
- p->drawRect(rect);
- p->setPen(oldPen);
- break;
- }
- case PE_IndicatorArrowUp:
- case PE_IndicatorArrowDown:
- case PE_IndicatorArrowRight:
- case PE_IndicatorArrowLeft:
- {
- if (opt->rect.width() <= 1 || opt->rect.height() <= 1)
- break;
- QRect r = opt->rect;
- int size = qMin(r.height(), r.width());
- QPixmap pixmap;
- QString pixmapName = QStyleHelper::uniqueName(QLatin1String("$qt_ia-")
- % QLatin1String(metaObject()->className()), opt, QSize(size, size))
- % HexString<uint>(pe);
- if (!QPixmapCache::find(pixmapName, pixmap)) {
- int border = size/5;
- int sqsize = 2*(size/2);
- QImage image(sqsize, sqsize, QImage::Format_ARGB32_Premultiplied);
- image.fill(0);
- QPainter imagePainter(&image);
-
- QPolygon a;
- switch (pe) {
- case PE_IndicatorArrowUp:
- a.setPoints(3, border, sqsize/2, sqsize/2, border, sqsize - border, sqsize/2);
- break;
- case PE_IndicatorArrowDown:
- a.setPoints(3, border, sqsize/2, sqsize/2, sqsize - border, sqsize - border, sqsize/2);
- break;
- case PE_IndicatorArrowRight:
- a.setPoints(3, sqsize - border, sqsize/2, sqsize/2, border, sqsize/2, sqsize - border);
- break;
- case PE_IndicatorArrowLeft:
- a.setPoints(3, border, sqsize/2, sqsize/2, border, sqsize/2, sqsize - border);
- break;
- default:
- break;
- }
-
- int bsx = 0;
- int bsy = 0;
-
- if (opt->state & State_Sunken) {
- bsx = proxy()->pixelMetric(PM_ButtonShiftHorizontal, opt, w);
- bsy = proxy()->pixelMetric(PM_ButtonShiftVertical, opt, w);
- }
-
- QRect bounds = a.boundingRect();
- int sx = sqsize / 2 - bounds.center().x() - 1;
- int sy = sqsize / 2 - bounds.center().y() - 1;
- imagePainter.translate(sx + bsx, sy + bsy);
- imagePainter.setPen(opt->palette.buttonText().color());
- imagePainter.setBrush(opt->palette.buttonText());
-
- if (!(opt->state & State_Enabled)) {
- imagePainter.translate(1, 1);
- imagePainter.setBrush(opt->palette.light().color());
- imagePainter.setPen(opt->palette.light().color());
- imagePainter.drawPolygon(a);
- imagePainter.translate(-1, -1);
- imagePainter.setBrush(opt->palette.mid().color());
- imagePainter.setPen(opt->palette.mid().color());
- }
-
- imagePainter.drawPolygon(a);
- imagePainter.end();
- pixmap = QPixmap::fromImage(image);
- QPixmapCache::insert(pixmapName, pixmap);
- }
- int xOffset = r.x() + (r.width() - size)/2;
- int yOffset = r.y() + (r.height() - size)/2;
- p->drawPixmap(xOffset, yOffset, pixmap);
- }
- break;
- case PE_IndicatorCheckBox: {
- QBrush fill;
- if (opt->state & State_NoChange)
- fill = QBrush(opt->palette.base().color(), Qt::Dense4Pattern);
- else if (opt->state & State_Sunken)
- fill = opt->palette.button();
- else if (opt->state & State_Enabled)
- fill = opt->palette.base();
- else
- fill = opt->palette.background();
- p->save();
- doRestore = true;
- qDrawWinPanel(p, opt->rect, opt->palette, true, &fill);
- if (opt->state & State_NoChange)
- p->setPen(opt->palette.dark().color());
- else
- p->setPen(opt->palette.text().color());
- } // Fall through!
- case PE_IndicatorViewItemCheck:
- case PE_Q3CheckListIndicator:
- if (!doRestore) {
- p->save();
- doRestore = true;
- }
- if (pe == PE_Q3CheckListIndicator || pe == PE_IndicatorViewItemCheck) {
- const QStyleOptionViewItem *itemViewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt);
- p->setPen(itemViewOpt
- && itemViewOpt->showDecorationSelected
- && opt->state & State_Selected
- ? opt->palette.highlightedText().color()
- : opt->palette.text().color());
- if (opt->state & State_NoChange)
- p->setBrush(opt->palette.brush(QPalette::Button));
- p->drawRect(opt->rect.x() + 1, opt->rect.y() + 1, 11, 11);
- }
- if (!(opt->state & State_Off)) {
- QLineF lines[7];
- int i, xx, yy;
- xx = opt->rect.x() + 3;
- yy = opt->rect.y() + 5;
- for (i = 0; i < 3; ++i) {
- lines[i] = QLineF(xx, yy, xx, yy + 2);
- ++xx;
- ++yy;
- }
- yy -= 2;
- for (i = 3; i < 7; ++i) {
- lines[i] = QLineF(xx, yy, xx, yy + 2);
- ++xx;
- --yy;
- }
- p->drawLines(lines, 7);
- }
- if (doRestore)
- p->restore();
- break;
- case PE_FrameFocusRect:
- if (const QStyleOptionFocusRect *fropt = qstyleoption_cast<const QStyleOptionFocusRect *>(opt)) {
- //### check for d->alt_down
- if (!(fropt->state & State_KeyboardFocusChange) && !proxy()->styleHint(SH_UnderlineShortcut, opt))
- return;
- QRect r = opt->rect;
- p->save();
- p->setBackgroundMode(Qt::TransparentMode);
- QColor bg_col = fropt->backgroundColor;
- if (!bg_col.isValid())
- bg_col = p->background().color();
- // Create an "XOR" color.
- QColor patternCol((bg_col.red() ^ 0xff) & 0xff,
- (bg_col.green() ^ 0xff) & 0xff,
- (bg_col.blue() ^ 0xff) & 0xff);
- p->setBrush(QBrush(patternCol, Qt::Dense4Pattern));
- p->setBrushOrigin(r.topLeft());
- p->setPen(Qt::NoPen);
- p->drawRect(r.left(), r.top(), r.width(), 1); // Top
- p->drawRect(r.left(), r.bottom(), r.width(), 1); // Bottom
- p->drawRect(r.left(), r.top(), 1, r.height()); // Left
- p->drawRect(r.right(), r.top(), 1, r.height()); // Right
- p->restore();
- }
- break;
- case PE_IndicatorRadioButton:
- {
-#define PTSARRLEN(x) sizeof(x)/(sizeof(QPoint))
- static const QPoint pts1[] = { // dark lines
- QPoint(1, 9), QPoint(1, 8), QPoint(0, 7), QPoint(0, 4), QPoint(1, 3), QPoint(1, 2),
- QPoint(2, 1), QPoint(3, 1), QPoint(4, 0), QPoint(7, 0), QPoint(8, 1), QPoint(9, 1)
- };
- static const QPoint pts2[] = { // black lines
- QPoint(2, 8), QPoint(1, 7), QPoint(1, 4), QPoint(2, 3), QPoint(2, 2), QPoint(3, 2),
- QPoint(4, 1), QPoint(7, 1), QPoint(8, 2), QPoint(9, 2)
- };
- static const QPoint pts3[] = { // background lines
- QPoint(2, 9), QPoint(3, 9), QPoint(4, 10), QPoint(7, 10), QPoint(8, 9), QPoint(9, 9),
- QPoint(9, 8), QPoint(10, 7), QPoint(10, 4), QPoint(9, 3)
- };
- static const QPoint pts4[] = { // white lines
- QPoint(2, 10), QPoint(3, 10), QPoint(4, 11), QPoint(7, 11), QPoint(8, 10),
- QPoint(9, 10), QPoint(10, 9), QPoint(10, 8), QPoint(11, 7), QPoint(11, 4),
- QPoint(10, 3), QPoint(10, 2)
- };
- static const QPoint pts5[] = { // inner fill
- QPoint(4, 2), QPoint(7, 2), QPoint(9, 4), QPoint(9, 7), QPoint(7, 9), QPoint(4, 9),
- QPoint(2, 7), QPoint(2, 4)
- };
-
- // make sure the indicator is square
- QRect ir = opt->rect;
-
- if (opt->rect.width() < opt->rect.height()) {
- ir.setTop(opt->rect.top() + (opt->rect.height() - opt->rect.width()) / 2);
- ir.setHeight(opt->rect.width());
- } else if (opt->rect.height() < opt->rect.width()) {
- ir.setLeft(opt->rect.left() + (opt->rect.width() - opt->rect.height()) / 2);
- ir.setWidth(opt->rect.height());
- }
-
- p->save();
- bool down = opt->state & State_Sunken;
- bool enabled = opt->state & State_Enabled;
- bool on = opt->state & State_On;
- QPolygon a;
-
- //center when rect is larger than indicator size
- int xOffset = 0;
- int yOffset = 0;
- int indicatorWidth = proxy()->pixelMetric(PM_ExclusiveIndicatorWidth);
- int indicatorHeight = proxy()->pixelMetric(PM_ExclusiveIndicatorWidth);
- if (ir.width() > indicatorWidth)
- xOffset += (ir.width() - indicatorWidth)/2;
- if (ir.height() > indicatorHeight)
- yOffset += (ir.height() - indicatorHeight)/2;
- p->translate(xOffset, yOffset);
-
- p->translate(ir.x(), ir.y());
-
- p->setPen(opt->palette.dark().color());
- p->drawPolyline(pts1, PTSARRLEN(pts1));
-
- p->setPen(opt->palette.shadow().color());
- p->drawPolyline(pts2, PTSARRLEN(pts2));
-
- p->setPen(opt->palette.midlight().color());
- p->drawPolyline(pts3, PTSARRLEN(pts3));
-
- p->setPen(opt->palette.light().color());
- p->drawPolyline(pts4, PTSARRLEN(pts4));
-
- QColor fillColor = (down || !enabled)
- ? opt->palette.button().color()
- : opt->palette.base().color();
- p->setPen(fillColor);
- p->setBrush(fillColor) ;
- p->drawPolygon(pts5, PTSARRLEN(pts5));
-
- p->translate(-ir.x(), -ir.y()); // restore translate
-
- if (on) {
- p->setPen(Qt::NoPen);
- p->setBrush(opt->palette.text());
- p->drawRect(ir.x() + 5, ir.y() + 4, 2, 4);
- p->drawRect(ir.x() + 4, ir.y() + 5, 4, 2);
- }
- p->restore();
- break;
- }
-#ifndef QT_NO_FRAME
- case PE_Frame:
- case PE_FrameMenu:
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- if (frame->lineWidth == 2 || pe == PE_Frame) {
- QPalette popupPal = frame->palette;
- if (pe == PE_FrameMenu) {
- popupPal.setColor(QPalette::Light, frame->palette.background().color());
- popupPal.setColor(QPalette::Midlight, frame->palette.light().color());
- }
- if (pe == PE_Frame && (frame->state & State_Raised))
- qDrawWinButton(p, frame->rect, popupPal, frame->state & State_Sunken);
- else if (pe == PE_Frame && (frame->state & State_Sunken))
- {
- popupPal.setColor(QPalette::Midlight, frame->palette.background().color());
- qDrawWinPanel(p, frame->rect, popupPal, frame->state & State_Sunken);
- }
- else
- qDrawWinPanel(p, frame->rect, popupPal, frame->state & State_Sunken);
- } else {
- QCommonStyle::drawPrimitive(pe, opt, p, w);
- }
- } else {
- QPalette popupPal = opt->palette;
- popupPal.setColor(QPalette::Light, opt->palette.background().color());
- popupPal.setColor(QPalette::Midlight, opt->palette.light().color());
- qDrawWinPanel(p, opt->rect, popupPal, opt->state & State_Sunken);
- }
- break;
-#endif // QT_NO_FRAME
- case PE_IndicatorBranch: {
- // This is _way_ too similar to the common style.
- static const int decoration_size = 9;
- int mid_h = opt->rect.x() + opt->rect.width() / 2;
- int mid_v = opt->rect.y() + opt->rect.height() / 2;
- int bef_h = mid_h;
- int bef_v = mid_v;
- int aft_h = mid_h;
- int aft_v = mid_v;
- if (opt->state & State_Children) {
- int delta = decoration_size / 2;
- bef_h -= delta;
- bef_v -= delta;
- aft_h += delta;
- aft_v += delta;
- p->drawLine(bef_h + 2, bef_v + 4, bef_h + 6, bef_v + 4);
- if (!(opt->state & State_Open))
- p->drawLine(bef_h + 4, bef_v + 2, bef_h + 4, bef_v + 6);
- QPen oldPen = p->pen();
- p->setPen(opt->palette.dark().color());
- p->drawRect(bef_h, bef_v, decoration_size - 1, decoration_size - 1);
- p->setPen(oldPen);
- }
- QBrush brush(opt->palette.dark().color(), Qt::Dense4Pattern);
- if (opt->state & State_Item) {
- if (opt->direction == Qt::RightToLeft)
- p->fillRect(opt->rect.left(), mid_v, bef_h - opt->rect.left(), 1, brush);
- else
- p->fillRect(aft_h, mid_v, opt->rect.right() - aft_h + 1, 1, brush);
- }
- if (opt->state & State_Sibling)
- p->fillRect(mid_h, aft_v, 1, opt->rect.bottom() - aft_v + 1, brush);
- if (opt->state & (State_Open | State_Children | State_Item | State_Sibling))
- p->fillRect(mid_h, opt->rect.y(), 1, bef_v - opt->rect.y(), brush);
- break; }
- case PE_FrameButtonBevel:
- case PE_PanelButtonBevel: {
- QBrush fill;
- bool panel = pe != PE_FrameButtonBevel;
- p->setBrushOrigin(opt->rect.topLeft());
- if (!(opt->state & State_Sunken) && (opt->state & State_On))
- fill = QBrush(opt->palette.light().color(), Qt::Dense4Pattern);
- else
- fill = opt->palette.brush(QPalette::Button);
-
- if (opt->state & (State_Raised | State_On | State_Sunken)) {
- qDrawWinButton(p, opt->rect, opt->palette, opt->state & (State_Sunken | State_On),
- panel ? &fill : 0);
- } else {
- if (panel)
- p->fillRect(opt->rect, fill);
- else
- p->drawRect(opt->rect);
- }
- break; }
- case PE_FrameWindow: {
- QPalette popupPal = opt->palette;
- popupPal.setColor(QPalette::Light, opt->palette.background().color());
- popupPal.setColor(QPalette::Midlight, opt->palette.light().color());
- qDrawWinPanel(p, opt->rect, popupPal, opt->state & State_Sunken);
- break; }
-#ifndef QT_NO_DOCKWIDGET
- case PE_IndicatorDockWidgetResizeHandle: {
- QPen oldPen = p->pen();
- p->setPen(opt->palette.light().color());
- if (opt->state & State_Horizontal) {
- p->drawLine(opt->rect.left(), opt->rect.top(),
- opt->rect.right(), opt->rect.top());
- p->setPen(opt->palette.dark().color());
- p->drawLine(opt->rect.left(), opt->rect.bottom() - 1,
- opt->rect.right(), opt->rect.bottom() - 1);
- p->setPen(opt->palette.shadow().color());
- p->drawLine(opt->rect.left(), opt->rect.bottom(),
- opt->rect.right(), opt->rect.bottom());
- } else {
- p->drawLine(opt->rect.left(), opt->rect.top(),
- opt->rect.left(), opt->rect.bottom());
- p->setPen(opt->palette.dark().color());
- p->drawLine(opt->rect.right() - 1, opt->rect.top(),
- opt->rect.right() - 1, opt->rect.bottom());
- p->setPen(opt->palette.shadow().color());
- p->drawLine(opt->rect.right(), opt->rect.top(),
- opt->rect.right(), opt->rect.bottom());
- }
- p->setPen(oldPen);
- break; }
-case PE_FrameDockWidget:
- if (qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
- proxy()->drawPrimitive(QStyle::PE_FrameWindow, opt, p, w);
- }
- break;
-#endif // QT_NO_DOCKWIDGET
-
- case PE_FrameStatusBarItem:
- qDrawShadePanel(p, opt->rect, opt->palette, true, 1, 0);
- break;
-
-#ifndef QT_NO_PROGRESSBAR
- case PE_IndicatorProgressChunk:
- {
- bool vertical = false, inverted = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
- vertical = (pb2->orientation == Qt::Vertical);
- inverted = pb2->invertedAppearance;
- }
-
- int space = 2;
- int chunksize = proxy()->pixelMetric(PM_ProgressBarChunkWidth, opt, w) - space;
- if (!vertical) {
- if (opt->rect.width() <= chunksize)
- space = 0;
-
- if (inverted)
- p->fillRect(opt->rect.x() + space, opt->rect.y(), opt->rect.width() - space, opt->rect.height(),
- opt->palette.brush(QPalette::Highlight));
- else
- p->fillRect(opt->rect.x(), opt->rect.y(), opt->rect.width() - space, opt->rect.height(),
- opt->palette.brush(QPalette::Highlight));
- } else {
- if (opt->rect.height() <= chunksize)
- space = 0;
-
- if (inverted)
- p->fillRect(opt->rect.x(), opt->rect.y(), opt->rect.width(), opt->rect.height() - space,
- opt->palette.brush(QPalette::Highlight));
- else
- p->fillRect(opt->rect.x(), opt->rect.y() + space, opt->rect.width(), opt->rect.height() - space,
- opt->palette.brush(QPalette::Highlight));
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
-
- case PE_FrameTabWidget: {
- qDrawWinButton(p, opt->rect, opt->palette, false, 0);
- break;
- }
- default:
- QCommonStyle::drawPrimitive(pe, opt, p, w);
- }
-}
-
-/*! \reimp */
-void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
- const QWidget *widget) const
-{
- switch (ce) {
-#ifndef QT_NO_RUBBERBAND
- case CE_RubberBand:
- if (qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
- // ### workaround for slow general painter path
- QPixmap tiledPixmap(16, 16);
- QPainter pixmapPainter(&tiledPixmap);
- pixmapPainter.setPen(Qt::NoPen);
- pixmapPainter.setBrush(Qt::Dense4Pattern);
- pixmapPainter.setBackground(Qt::white);
- pixmapPainter.setBackgroundMode(Qt::OpaqueMode);
- pixmapPainter.drawRect(0, 0, tiledPixmap.width(), tiledPixmap.height());
- pixmapPainter.end();
- tiledPixmap = QPixmap::fromImage(tiledPixmap.toImage());
- p->save();
- QRect r = opt->rect;
- QStyleHintReturnMask mask;
- if (proxy()->styleHint(QStyle::SH_RubberBand_Mask, opt, widget, &mask))
- p->setClipRegion(mask.region);
- p->drawTiledPixmap(r.x(), r.y(), r.width(), r.height(), tiledPixmap);
- p->restore();
- return;
- }
- break;
-#endif // QT_NO_RUBBERBAND
-
-#if !defined(QT_NO_MENU) && !defined(QT_NO_MAINWINDOW)
- case CE_MenuBarEmptyArea:
- if (widget && qobject_cast<const QMainWindow *>(widget->parentWidget())) {
- p->fillRect(opt->rect, opt->palette.button());
- QPen oldPen = p->pen();
- p->setPen(QPen(opt->palette.dark().color()));
- p->drawLine(opt->rect.bottomLeft(), opt->rect.bottomRight());
- p->setPen(oldPen);
- }
- break;
-#endif
-#ifndef QT_NO_MENU
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- int x, y, w, h;
- menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
- bool dis = !(menuitem->state & State_Enabled);
- bool checked = menuitem->checkType != QStyleOptionMenuItem::NotCheckable
- ? menuitem->checked : false;
- bool act = menuitem->state & State_Selected;
-
- // windows always has a check column, regardless whether we have an icon or not
- int checkcol = qMax<int>(menuitem->maxIconWidth, QWindowsStylePrivate::windowsCheckMarkWidth);
-
- QBrush fill = menuitem->palette.brush(act ? QPalette::Highlight : QPalette::Button);
- p->fillRect(menuitem->rect.adjusted(0, 0, -1, 0), fill);
-
- if (menuitem->menuItemType == QStyleOptionMenuItem::Separator){
- int yoff = y-1 + h / 2;
- p->setPen(menuitem->palette.dark().color());
- p->drawLine(x + 2, yoff, x + w - 4, yoff);
- p->setPen(menuitem->palette.light().color());
- p->drawLine(x + 2, yoff + 1, x + w - 4, yoff + 1);
- return;
- }
-
- QRect vCheckRect = visualRect(opt->direction, menuitem->rect, QRect(menuitem->rect.x(), menuitem->rect.y(), checkcol, menuitem->rect.height()));
- if (checked) {
- if (act && !dis) {
- qDrawShadePanel(p, vCheckRect,
- menuitem->palette, true, 1,
- &menuitem->palette.brush(QPalette::Button));
- } else {
- QBrush fill(menuitem->palette.light().color(), Qt::Dense4Pattern);
- qDrawShadePanel(p, vCheckRect, menuitem->palette, true, 1, &fill);
- }
- } else if (!act) {
- p->fillRect(vCheckRect, menuitem->palette.brush(QPalette::Button));
- }
-
- // On Windows Style, if we have a checkable item and an icon we
- // draw the icon recessed to indicate an item is checked. If we
- // have no icon, we draw a checkmark instead.
- if (!menuitem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap;
- if (checked)
- pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, opt, widget), mode, QIcon::On);
- else
- pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, opt, widget), mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- if (act && !dis && !checked)
- qDrawShadePanel(p, vCheckRect, menuitem->palette, false, 1,
- &menuitem->palette.brush(QPalette::Button));
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vCheckRect.center());
- p->setPen(menuitem->palette.text().color());
- p->drawPixmap(pmr.topLeft(), pixmap);
- } else if (checked) {
- QStyleOptionMenuItem newMi = *menuitem;
- newMi.state = State_None;
- if (!dis)
- newMi.state |= State_Enabled;
- if (act)
- newMi.state |= State_On;
- newMi.rect = visualRect(opt->direction, menuitem->rect, QRect(menuitem->rect.x() + QWindowsStylePrivate::windowsItemFrame,
- menuitem->rect.y() + QWindowsStylePrivate::windowsItemFrame,
- checkcol - 2 * QWindowsStylePrivate::windowsItemFrame,
- menuitem->rect.height() - 2 * QWindowsStylePrivate::windowsItemFrame));
- proxy()->drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, widget);
- }
- p->setPen(act ? menuitem->palette.highlightedText().color() : menuitem->palette.buttonText().color());
-
- QColor discol;
- if (dis) {
- discol = menuitem->palette.text().color();
- p->setPen(discol);
- }
-
- int xm = int(QWindowsStylePrivate::windowsItemFrame) + checkcol + int(QWindowsStylePrivate::windowsItemHMargin);
- int xpos = menuitem->rect.x() + xm;
- QRect textRect(xpos, y + QWindowsStylePrivate::windowsItemVMargin,
- w - xm - QWindowsStylePrivate::windowsRightBorder - tab + 1, h - 2 * QWindowsStylePrivate::windowsItemVMargin);
- QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
- QString s = menuitem->text;
- if (!s.isEmpty()) { // draw text
- p->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
- text_flags |= Qt::AlignLeft;
- if (t >= 0) {
- QRect vShortcutRect = visualRect(opt->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
- if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, opt, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vShortcutRect.adjusted(1,1,1,1), text_flags, s.mid(t + 1));
- p->setPen(discol);
- }
- p->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- QFont font = menuitem->font;
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
- p->setFont(font);
- if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, opt, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vTextRect.adjusted(1,1,1,1), text_flags, s.left(t));
- p->setPen(discol);
- }
- p->drawText(vTextRect, text_flags, s.left(t));
- p->restore();
- }
- if (menuitem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- int dim = (h - 2 * QWindowsStylePrivate::windowsItemFrame) / 2;
- PrimitiveElement arrow;
- arrow = (opt->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- xpos = x + w - QWindowsStylePrivate::windowsArrowHMargin - QWindowsStylePrivate::windowsItemFrame - dim;
- QRect vSubMenuRect = visualRect(opt->direction, menuitem->rect, QRect(xpos, y + h / 2 - dim / 2, dim, dim));
- QStyleOptionMenuItem newMI = *menuitem;
- newMI.rect = vSubMenuRect;
- newMI.state = dis ? State_None : State_Enabled;
- if (act)
- newMI.palette.setColor(QPalette::ButtonText,
- newMI.palette.highlightedText().color());
- proxy()->drawPrimitive(arrow, &newMI, p, widget);
- }
-
- }
- break;
-#endif // QT_NO_MENU
-#ifndef QT_NO_MENUBAR
- case CE_MenuBarItem:
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- bool active = mbi->state & State_Selected;
- bool hasFocus = mbi->state & State_HasFocus;
- bool down = mbi->state & State_Sunken;
- QStyleOptionMenuItem newMbi = *mbi;
- p->fillRect(mbi->rect, mbi->palette.brush(QPalette::Button));
- if (active || hasFocus) {
- QBrush b = mbi->palette.brush(QPalette::Button);
- if (active && down)
- p->setBrushOrigin(p->brushOrigin() + QPoint(1, 1));
- if (active && hasFocus)
- qDrawShadeRect(p, mbi->rect.x(), mbi->rect.y(), mbi->rect.width(),
- mbi->rect.height(), mbi->palette, active && down, 1, 0, &b);
- if (active && down) {
- newMbi.rect.translate(proxy()->pixelMetric(PM_ButtonShiftHorizontal, mbi, widget),
- proxy()->pixelMetric(PM_ButtonShiftVertical, mbi, widget));
- p->setBrushOrigin(p->brushOrigin() - QPoint(1, 1));
- }
- }
- QCommonStyle::drawControl(ce, &newMbi, p, widget);
- }
- break;
-#endif // QT_NO_MENUBAR
-#ifndef QT_NO_TABBAR
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
- bool rtlHorTabs = (tab->direction == Qt::RightToLeft
- && (tab->shape == QTabBar::RoundedNorth
- || tab->shape == QTabBar::RoundedSouth));
- bool selected = tab->state & State_Selected;
- bool lastTab = ((!rtlHorTabs && tab->position == QStyleOptionTab::End)
- || (rtlHorTabs
- && tab->position == QStyleOptionTab::Beginning));
- bool firstTab = ((!rtlHorTabs
- && tab->position == QStyleOptionTab::Beginning)
- || (rtlHorTabs
- && tab->position == QStyleOptionTab::End));
- bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
- bool previousSelected =
- ((!rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
- || (rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::NextIsSelected));
- bool nextSelected =
- ((!rtlHorTabs
- && tab->selectedPosition == QStyleOptionTab::NextIsSelected)
- || (rtlHorTabs
- && tab->selectedPosition
- == QStyleOptionTab::PreviousIsSelected));
- int tabBarAlignment = proxy()->styleHint(SH_TabBar_Alignment, tab, widget);
- bool leftAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignLeft)
- || (rtlHorTabs
- && tabBarAlignment == Qt::AlignRight);
-
- bool rightAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignRight)
- || (rtlHorTabs
- && tabBarAlignment == Qt::AlignLeft);
-
- QColor light = tab->palette.light().color();
- QColor midlight = tab->palette.midlight().color();
- QColor dark = tab->palette.dark().color();
- QColor shadow = tab->palette.shadow().color();
- QColor background = tab->palette.background().color();
- int borderThinkness = proxy()->pixelMetric(PM_TabBarBaseOverlap, tab, widget);
- if (selected)
- borderThinkness /= 2;
- QRect r2(opt->rect);
- int x1 = r2.left();
- int x2 = r2.right();
- int y1 = r2.top();
- int y2 = r2.bottom();
- switch (tab->shape) {
- default:
- QCommonStyle::drawControl(ce, tab, p, widget);
- break;
- case QTabBar::RoundedNorth: {
- if (!selected) {
- y1 += 2;
- x1 += onlyOne || firstTab ? borderThinkness : 0;
- x2 -= onlyOne || lastTab ? borderThinkness : 0;
- }
-
- p->fillRect(QRect(x1 + 1, y1 + 1, (x2 - x1) - 1, (y2 - y1) - 2), tab->palette.background());
-
- // Delete border
- if (selected) {
- p->fillRect(QRect(x1,y2-1,x2-x1,1), tab->palette.background());
- p->fillRect(QRect(x1,y2,x2-x1,1), tab->palette.background());
- }
- // Left
- if (firstTab || selected || onlyOne || !previousSelected) {
- p->setPen(light);
- p->drawLine(x1, y1 + 2, x1, y2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness));
- p->drawPoint(x1 + 1, y1 + 1);
- }
- // Top
- {
- int beg = x1 + (previousSelected ? 0 : 2);
- int end = x2 - (nextSelected ? 0 : 2);
- p->setPen(light);
- p->drawLine(beg, y1, end, y1);
- }
- // Right
- if (lastTab || selected || onlyOne || !nextSelected) {
- p->setPen(shadow);
- p->drawLine(x2, y1 + 2, x2, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- p->drawPoint(x2 - 1, y1 + 1);
- p->setPen(dark);
- p->drawLine(x2 - 1, y1 + 2, x2 - 1, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- }
- break; }
- case QTabBar::RoundedSouth: {
- if (!selected) {
- y2 -= 2;
- x1 += firstTab ? borderThinkness : 0;
- x2 -= lastTab ? borderThinkness : 0;
- }
-
- p->fillRect(QRect(x1 + 1, y1 + 2, (x2 - x1) - 1, (y2 - y1) - 1), tab->palette.background());
-
- // Delete border
- if (selected) {
- p->fillRect(QRect(x1, y1 + 1, (x2 - 1)-x1, 1), tab->palette.background());
- p->fillRect(QRect(x1, y1, (x2 - 1)-x1, 1), tab->palette.background());
- }
- // Left
- if (firstTab || selected || onlyOne || !previousSelected) {
- p->setPen(light);
- p->drawLine(x1, y2 - 2, x1, y1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness));
- p->drawPoint(x1 + 1, y2 - 1);
- }
- // Bottom
- {
- int beg = x1 + (previousSelected ? 0 : 2);
- int end = x2 - (nextSelected ? 0 : 2);
- p->setPen(shadow);
- p->drawLine(beg, y2, end, y2);
- p->setPen(dark);
- p->drawLine(beg, y2 - 1, end, y2 - 1);
- }
- // Right
- if (lastTab || selected || onlyOne || !nextSelected) {
- p->setPen(shadow);
- p->drawLine(x2, y2 - 2, x2, y1 + ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- p->drawPoint(x2 - 1, y2 - 1);
- p->setPen(dark);
- p->drawLine(x2 - 1, y2 - 2, x2 - 1, y1 + ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
- }
- break; }
- case QTabBar::RoundedWest: {
- if (!selected) {
- x1 += 2;
- y1 += firstTab ? borderThinkness : 0;
- y2 -= lastTab ? borderThinkness : 0;
- }
-
- p->fillRect(QRect(x1 + 1, y1 + 1, (x2 - x1) - 2, (y2 - y1) - 1), tab->palette.background());
-
- // Delete border
- if (selected) {
- p->fillRect(QRect(x2 - 1, y1, 1, y2-y1), tab->palette.background());
- p->fillRect(QRect(x2, y1, 1, y2-y1), tab->palette.background());
- }
- // Top
- if (firstTab || selected || onlyOne || !previousSelected) {
- p->setPen(light);
- p->drawLine(x1 + 2, y1, x2 - ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness), y1);
- p->drawPoint(x1 + 1, y1 + 1);
- }
- // Left
- {
- int beg = y1 + (previousSelected ? 0 : 2);
- int end = y2 - (nextSelected ? 0 : 2);
- p->setPen(light);
- p->drawLine(x1, beg, x1, end);
- }
- // Bottom
- if (lastTab || selected || onlyOne || !nextSelected) {
- p->setPen(shadow);
- p->drawLine(x1 + 3, y2, x2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness), y2);
- p->drawPoint(x1 + 2, y2 - 1);
- p->setPen(dark);
- p->drawLine(x1 + 3, y2 - 1, x2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness), y2 - 1);
- p->drawPoint(x1 + 1, y2 - 1);
- p->drawPoint(x1 + 2, y2);
- }
- break; }
- case QTabBar::RoundedEast: {
- if (!selected) {
- x2 -= 2;
- y1 += firstTab ? borderThinkness : 0;
- y2 -= lastTab ? borderThinkness : 0;
- }
-
- p->fillRect(QRect(x1 + 2, y1 + 1, (x2 - x1) - 1, (y2 - y1) - 1), tab->palette.background());
-
- // Delete border
- if (selected) {
- p->fillRect(QRect(x1 + 1, y1, 1, (y2 - 1)-y1),tab->palette.background());
- p->fillRect(QRect(x1, y1, 1, (y2-1)-y1), tab->palette.background());
- }
- // Top
- if (firstTab || selected || onlyOne || !previousSelected) {
- p->setPen(light);
- p->drawLine(x2 - 2, y1, x1 + ((onlyOne || firstTab) && selected && leftAligned ? 0 : borderThinkness), y1);
- p->drawPoint(x2 - 1, y1 + 1);
- }
- // Right
- {
- int beg = y1 + (previousSelected ? 0 : 2);
- int end = y2 - (nextSelected ? 0 : 2);
- p->setPen(shadow);
- p->drawLine(x2, beg, x2, end);
- p->setPen(dark);
- p->drawLine(x2 - 1, beg, x2 - 1, end);
- }
- // Bottom
- if (lastTab || selected || onlyOne || !nextSelected) {
- p->setPen(shadow);
- p->drawLine(x2 - 2, y2, x1 + ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness), y2);
- p->drawPoint(x2 - 1, y2 - 1);
- p->setPen(dark);
- p->drawLine(x2 - 2, y2 - 1, x1 + ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness), y2 - 1);
- }
- break; }
- }
- }
- break;
-#endif // QT_NO_TABBAR
- case CE_ToolBoxTabShape:
- qDrawShadePanel(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), 1,
- &opt->palette.brush(QPalette::Button));
- break;
-#ifndef QT_NO_SPLITTER
- case CE_Splitter:
- p->eraseRect(opt->rect);
- break;
-#endif // QT_NO_SPLITTER
-#ifndef QT_NO_SCROLLBAR
- case CE_ScrollBarSubLine:
- case CE_ScrollBarAddLine: {
- if ((opt->state & State_Sunken)) {
- p->setPen(opt->palette.dark().color());
- p->setBrush(opt->palette.brush(QPalette::Button));
- p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
- } else {
- QStyleOption buttonOpt = *opt;
- if (!(buttonOpt.state & State_Sunken))
- buttonOpt.state |= State_Raised;
- QPalette pal(opt->palette);
- pal.setColor(QPalette::Button, opt->palette.light().color());
- pal.setColor(QPalette::Light, opt->palette.button().color());
- qDrawWinButton(p, opt->rect, pal, opt->state & (State_Sunken | State_On),
- &opt->palette.brush(QPalette::Button));
- }
- PrimitiveElement arrow;
- if (opt->state & State_Horizontal) {
- if (ce == CE_ScrollBarAddLine)
- arrow = opt->direction == Qt::LeftToRight ? PE_IndicatorArrowRight : PE_IndicatorArrowLeft;
- else
- arrow = opt->direction == Qt::LeftToRight ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- } else {
- if (ce == CE_ScrollBarAddLine)
- arrow = PE_IndicatorArrowDown;
- else
- arrow = PE_IndicatorArrowUp;
- }
- QStyleOption arrowOpt = *opt;
- arrowOpt.rect = opt->rect.adjusted(4, 4, -4, -4);
- proxy()->drawPrimitive(arrow, &arrowOpt, p, widget);
- break; }
- case CE_ScrollBarAddPage:
- case CE_ScrollBarSubPage: {
- QBrush br;
- QBrush bg = p->background();
- Qt::BGMode bg_mode = p->backgroundMode();
- p->setPen(Qt::NoPen);
- p->setBackgroundMode(Qt::OpaqueMode);
-
- if (opt->state & State_Sunken) {
- br = QBrush(opt->palette.shadow().color(), Qt::Dense4Pattern);
- p->setBackground(opt->palette.dark().color());
- p->setBrush(br);
- } else {
- QPixmap pm = opt->palette.brush(QPalette::Light).texture();
- br = !pm.isNull() ? QBrush(pm) : QBrush(opt->palette.light().color(), Qt::Dense4Pattern);
- p->setBackground(opt->palette.background().color());
- p->setBrush(br);
- }
- p->drawRect(opt->rect);
- p->setBackground(bg);
- p->setBackgroundMode(bg_mode);
- break; }
- case CE_ScrollBarSlider:
- if (!(opt->state & State_Enabled)) {
- QPixmap pm = opt->palette.brush(QPalette::Light).texture();
- QBrush br = !pm.isNull() ? QBrush(pm) : QBrush(opt->palette.light().color(), Qt::Dense4Pattern);
- p->setPen(Qt::NoPen);
- p->setBrush(br);
- p->setBackgroundMode(Qt::OpaqueMode);
- p->drawRect(opt->rect);
- } else {
- QStyleOptionButton buttonOpt;
- buttonOpt.QStyleOption::operator=(*opt);
- buttonOpt.state = State_Enabled | State_Raised;
-
- QPalette pal(opt->palette);
- pal.setColor(QPalette::Button, opt->palette.light().color());
- pal.setColor(QPalette::Light, opt->palette.button().color());
- qDrawWinButton(p, opt->rect, pal, false, &opt->palette.brush(QPalette::Button));
- }
- break;
-#endif // QT_NO_SCROLLBAR
- case CE_HeaderSection: {
- QBrush fill;
- if (opt->state & State_On)
- fill = QBrush(opt->palette.light().color(), Qt::Dense4Pattern);
- else
- fill = opt->palette.brush(QPalette::Button);
-
- if (opt->state & (State_Raised | State_Sunken)) {
- qDrawWinButton(p, opt->rect, opt->palette, opt->state & State_Sunken, &fill);
- } else {
- p->fillRect(opt->rect, fill);
- }
- break; }
-#ifndef QT_NO_TOOLBAR
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolbar = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
- QRect rect = opt->rect;
-
- bool paintLeftBorder = true;
- bool paintRightBorder = true;
- bool paintBottomBorder = true;
-
- switch (toolbar->toolBarArea){
- case Qt::BottomToolBarArea :
- switch(toolbar->positionOfLine){
- case QStyleOptionToolBar::Beginning:
- case QStyleOptionToolBar::OnlyOne:
- paintBottomBorder = false;
- default:
- break;
- }
- case Qt::TopToolBarArea :
- switch(toolbar->positionWithinLine){
- case QStyleOptionToolBar::Beginning:
- paintLeftBorder = false;
- break;
- case QStyleOptionToolBar::End:
- paintRightBorder = false;
- break;
- case QStyleOptionToolBar::OnlyOne:
- paintRightBorder = false;
- paintLeftBorder = false;
- default:
- break;
- }
- if(opt->direction == Qt::RightToLeft){ //reverse layout changes the order of Beginning/end
- bool tmp = paintLeftBorder;
- paintRightBorder=paintLeftBorder;
- paintLeftBorder=tmp;
- }
- break;
- case Qt::RightToolBarArea :
- switch (toolbar->positionOfLine){
- case QStyleOptionToolBar::Beginning:
- case QStyleOptionToolBar::OnlyOne:
- paintRightBorder = false;
- break;
- default:
- break;
- }
- break;
- case Qt::LeftToolBarArea :
- switch (toolbar->positionOfLine){
- case QStyleOptionToolBar::Beginning:
- case QStyleOptionToolBar::OnlyOne:
- paintLeftBorder = false;
- break;
- default:
- break;
- }
- break;
- default:
- break;
- }
-
-
- //draw top border
- p->setPen(QPen(opt->palette.light().color()));
- p->drawLine(rect.topLeft().x(),
- rect.topLeft().y(),
- rect.topRight().x(),
- rect.topRight().y());
-
- if (paintLeftBorder){
- p->setPen(QPen(opt->palette.light().color()));
- p->drawLine(rect.topLeft().x(),
- rect.topLeft().y(),
- rect.bottomLeft().x(),
- rect.bottomLeft().y());
- }
-
- if (paintRightBorder){
- p->setPen(QPen(opt->palette.dark().color()));
- p->drawLine(rect.topRight().x(),
- rect.topRight().y(),
- rect.bottomRight().x(),
- rect.bottomRight().y());
- }
-
- if (paintBottomBorder){
- p->setPen(QPen(opt->palette.dark().color()));
- p->drawLine(rect.bottomLeft().x(),
- rect.bottomLeft().y(),
- rect.bottomRight().x(),
- rect.bottomRight().y());
- }
- }
- break;
-
-
-#endif // QT_NO_TOOLBAR
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
- QRect rect = pb->rect;
- if (!rect.isValid())
- return;
-
- bool vertical = false;
- bool inverted = false;
-
- // Get extra style options if version 2
- const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt);
- if (pb2) {
- vertical = (pb2->orientation == Qt::Vertical);
- inverted = pb2->invertedAppearance;
- }
- QMatrix m;
- if (vertical) {
- rect = QRect(rect.y(), rect.x(), rect.height(), rect.width()); // flip width and height
- m.rotate(90);
- m.translate(0, -(rect.height() + rect.y()*2));
- }
- QPalette pal2 = pb->palette;
- // Correct the highlight color if it is the same as the background
- if (pal2.highlight() == pal2.background())
- pal2.setColor(QPalette::Highlight, pb->palette.color(QPalette::Active,
- QPalette::Highlight));
- bool reverse = ((!vertical && (pb->direction == Qt::RightToLeft)) || vertical);
- if (inverted)
- reverse = !reverse;
- int w = rect.width();
- if (pb->minimum == 0 && pb->maximum == 0) {
- Q_D(const QWindowsStyle);
- const int unit_width = proxy()->pixelMetric(PM_ProgressBarChunkWidth, pb, widget);
- QStyleOptionProgressBarV2 pbBits = *pb;
- Q_ASSERT(unit_width >0);
-
- pbBits.rect = rect;
- pbBits.palette = pal2;
-
- int chunkCount = w / unit_width + 1;
- int step = d->animateStep%chunkCount;
- int chunksInRow = 5;
- int myY = pbBits.rect.y();
- int myHeight = pbBits.rect.height();
- int chunksToDraw = chunksInRow;
-
- if(step > chunkCount - 5)chunksToDraw = (chunkCount - step);
- p->save();
- p->setClipRect(m.mapRect(QRectF(rect)).toRect());
-
- int x0 = reverse ? rect.left() + rect.width() - unit_width*(step) - unit_width : rect.left() + unit_width * step;
- int x = 0;
-
- for (int i = 0; i < chunksToDraw ; ++i) {
- pbBits.rect.setRect(x0 + x, myY, unit_width, myHeight);
- pbBits.rect = m.mapRect(QRectF(pbBits.rect)).toRect();
- proxy()->drawPrimitive(PE_IndicatorProgressChunk, &pbBits, p, widget);
- x += reverse ? -unit_width : unit_width;
- }
- //Draw wrap-around chunks
- if( step > chunkCount-5){
- x0 = reverse ? rect.left() + rect.width() - unit_width : rect.left() ;
- x = 0;
- int chunksToDraw = step - (chunkCount - chunksInRow);
- for (int i = 0; i < chunksToDraw ; ++i) {
- pbBits.rect.setRect(x0 + x, myY, unit_width, myHeight);
- pbBits.rect = m.mapRect(QRectF(pbBits.rect)).toRect();
- proxy()->drawPrimitive(PE_IndicatorProgressChunk, &pbBits, p, widget);
- x += reverse ? -unit_width : unit_width;
- }
- }
- p->restore(); //restore state
- }
- else {
- QCommonStyle::drawControl(ce, opt, p, widget);
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
-
-#ifndef QT_NO_DOCKWIDGET
- case CE_DockWidgetTitle:
-
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
- Q_D(const QWindowsStyle);
-
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- QRect rect = dwOpt->rect;
- QRect r = rect;
-
- if (verticalTitleBar) {
- QSize s = r.size();
- s.transpose();
- r.setSize(s);
-
- p->save();
- p->translate(r.left(), r.top() + r.width());
- p->rotate(-90);
- p->translate(-r.left(), -r.top());
- }
-
- bool floating = false;
- bool active = dwOpt->state & State_Active;
- QColor inactiveCaptionTextColor = d->inactiveCaptionText;
- if (dwOpt->movable) {
- QColor left, right;
-
- //Titlebar gradient
- if (widget && widget->isWindow()) {
- floating = true;
- if (active) {
- left = d->activeCaptionColor;
- right = d->activeGradientCaptionColor;
- } else {
- left = d->inactiveCaptionColor;
- right = d->inactiveGradientCaptionColor;
- }
- QBrush fillBrush(left);
- if (left != right) {
- QPoint p1(r.x(), r.top() + r.height()/2);
- QPoint p2(rect.right(), r.top() + r.height()/2);
- QLinearGradient lg(p1, p2);
- lg.setColorAt(0, left);
- lg.setColorAt(1, right);
- fillBrush = lg;
- }
- p->fillRect(r.adjusted(0, 0, 0, -3), fillBrush);
- }
- p->setPen(dwOpt->palette.color(QPalette::Light));
- if (!widget || !widget->isWindow()) {
- p->drawLine(r.topLeft(), r.topRight());
- p->setPen(dwOpt->palette.color(QPalette::Dark));
- p->drawLine(r.bottomLeft(), r.bottomRight()); }
- }
- if (!dwOpt->title.isEmpty()) {
- QFont oldFont = p->font();
- if (floating) {
- QFont font = oldFont;
- font.setBold(true);
- p->setFont(font);
- }
- QPalette palette = dwOpt->palette;
- palette.setColor(QPalette::Window, inactiveCaptionTextColor);
- QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, opt, widget);
- if (verticalTitleBar) {
- titleRect = QRect(r.left() + rect.bottom()
- - titleRect.bottom(),
- r.top() + titleRect.left() - rect.left(),
- titleRect.height(), titleRect.width());
- }
- proxy()->drawItemText(p, titleRect,
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, palette,
- dwOpt->state & State_Enabled, dwOpt->title,
- floating ? (active ? QPalette::BrightText : QPalette::Window) : QPalette::WindowText);
- p->setFont(oldFont);
- }
- if (verticalTitleBar)
- p->restore();
- }
- return;
-#endif // QT_NO_DOCKWIDGET
- default:
- QCommonStyle::drawControl(ce, opt, p, widget);
- }
-}
-
-/*! \reimp */
-QRect QWindowsStyle::subElementRect(SubElement sr, const QStyleOption *opt, const QWidget *w) const
-{
- QRect r;
- switch (sr) {
- case SE_SliderFocusRect:
- case SE_ToolBoxTabContents:
- r = visualRect(opt->direction, opt->rect, opt->rect);
- break;
- case SE_DockWidgetTitleBarText: {
- r = QCommonStyle::subElementRect(sr, opt, w);
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
- int m = proxy()->pixelMetric(PM_DockWidgetTitleMargin, opt, w);
- if (verticalTitleBar) {
- r.adjust(0, 0, 0, -m);
- } else {
- if (opt->direction == Qt::LeftToRight)
- r.adjust(m, 0, 0, 0);
- else
- r.adjust(0, 0, -m, 0);
- }
- break;
- }
- case SE_ProgressBarContents:
- r = QCommonStyle::subElementRect(SE_ProgressBarGroove, opt, w);
- r.adjust(3, 3, -3, -3);
- break;
- default:
- r = QCommonStyle::subElementRect(sr, opt, w);
- }
- return r;
-}
-
-#ifdef QT3_SUPPORT
-Q_GLOBAL_STATIC_WITH_ARGS(QBitmap, globalVerticalLine, (1, 129))
-Q_GLOBAL_STATIC_WITH_ARGS(QBitmap, globalHorizontalLine, (128, 1))
-#endif
-
-/*! \reimp */
-void QWindowsStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- QPainter *p, const QWidget *widget) const
-{
- switch (cc) {
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- int ticks = slider->tickPosition;
- QRect groove = proxy()->subControlRect(CC_Slider, slider, SC_SliderGroove, widget);
- QRect handle = proxy()->subControlRect(CC_Slider, slider, SC_SliderHandle, widget);
-
- if ((slider->subControls & SC_SliderGroove) && groove.isValid()) {
- int mid = thickness / 2;
-
- if (ticks & QSlider::TicksAbove)
- mid += len / 8;
- if (ticks & QSlider::TicksBelow)
- mid -= len / 8;
-
- p->setPen(slider->palette.shadow().color());
- if (slider->orientation == Qt::Horizontal) {
- qDrawWinPanel(p, groove.x(), groove.y() + mid - 2,
- groove.width(), 4, slider->palette, true);
- p->drawLine(groove.x() + 1, groove.y() + mid - 1,
- groove.x() + groove.width() - 3, groove.y() + mid - 1);
- } else {
- qDrawWinPanel(p, groove.x() + mid - 2, groove.y(),
- 4, groove.height(), slider->palette, true);
- p->drawLine(groove.x() + mid - 1, groove.y() + 1,
- groove.x() + mid - 1, groove.y() + groove.height() - 3);
- }
- }
-
- if (slider->subControls & SC_SliderTickmarks) {
- QStyleOptionSlider tmpSlider = *slider;
- tmpSlider.subControls = SC_SliderTickmarks;
- QCommonStyle::drawComplexControl(cc, &tmpSlider, p, widget);
- }
-
- if (slider->subControls & SC_SliderHandle) {
- // 4444440
- // 4333310
- // 4322210
- // 4322210
- // 4322210
- // 4322210
- // *43210*
- // **410**
- // ***0***
- const QColor c0 = slider->palette.shadow().color();
- const QColor c1 = slider->palette.dark().color();
- // const QColor c2 = g.button();
- const QColor c3 = slider->palette.midlight().color();
- const QColor c4 = slider->palette.light().color();
- QBrush handleBrush;
-
- if (slider->state & State_Enabled) {
- handleBrush = slider->palette.color(QPalette::Button);
- } else {
- handleBrush = QBrush(slider->palette.color(QPalette::Button),
- Qt::Dense4Pattern);
- }
-
-
- int x = handle.x(), y = handle.y(),
- wi = handle.width(), he = handle.height();
-
- int x1 = x;
- int x2 = x+wi-1;
- int y1 = y;
- int y2 = y+he-1;
-
- Qt::Orientation orient = slider->orientation;
- bool tickAbove = slider->tickPosition == QSlider::TicksAbove;
- bool tickBelow = slider->tickPosition == QSlider::TicksBelow;
-
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = subElementRect(SE_SliderFocusRect, slider, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
-
- if ((tickAbove && tickBelow) || (!tickAbove && !tickBelow)) {
- Qt::BGMode oldMode = p->backgroundMode();
- p->setBackgroundMode(Qt::OpaqueMode);
- qDrawWinButton(p, QRect(x, y, wi, he), slider->palette, false,
- &handleBrush);
- p->setBackgroundMode(oldMode);
- return;
- }
-
- QSliderDirection dir;
-
- if (orient == Qt::Horizontal)
- if (tickAbove)
- dir = SlUp;
- else
- dir = SlDown;
- else
- if (tickAbove)
- dir = SlLeft;
- else
- dir = SlRight;
-
- QPolygon a;
-
- int d = 0;
- switch (dir) {
- case SlUp:
- y1 = y1 + wi/2;
- d = (wi + 1) / 2 - 1;
- a.setPoints(5, x1,y1, x1,y2, x2,y2, x2,y1, x1+d,y1-d);
- break;
- case SlDown:
- y2 = y2 - wi/2;
- d = (wi + 1) / 2 - 1;
- a.setPoints(5, x1,y1, x1,y2, x1+d,y2+d, x2,y2, x2,y1);
- break;
- case SlLeft:
- d = (he + 1) / 2 - 1;
- x1 = x1 + he/2;
- a.setPoints(5, x1,y1, x1-d,y1+d, x1,y2, x2,y2, x2,y1);
- break;
- case SlRight:
- d = (he + 1) / 2 - 1;
- x2 = x2 - he/2;
- a.setPoints(5, x1,y1, x1,y2, x2,y2, x2+d,y1+d, x2,y1);
- break;
- }
-
- QBrush oldBrush = p->brush();
- p->setPen(Qt::NoPen);
- p->setBrush(handleBrush);
- Qt::BGMode oldMode = p->backgroundMode();
- p->setBackgroundMode(Qt::OpaqueMode);
- p->drawRect(x1, y1, x2-x1+1, y2-y1+1);
- p->drawPolygon(a);
- p->setBrush(oldBrush);
- p->setBackgroundMode(oldMode);
-
- if (dir != SlUp) {
- p->setPen(c4);
- p->drawLine(x1, y1, x2, y1);
- p->setPen(c3);
- p->drawLine(x1, y1+1, x2, y1+1);
- }
- if (dir != SlLeft) {
- p->setPen(c3);
- p->drawLine(x1+1, y1+1, x1+1, y2);
- p->setPen(c4);
- p->drawLine(x1, y1, x1, y2);
- }
- if (dir != SlRight) {
- p->setPen(c0);
- p->drawLine(x2, y1, x2, y2);
- p->setPen(c1);
- p->drawLine(x2-1, y1+1, x2-1, y2-1);
- }
- if (dir != SlDown) {
- p->setPen(c0);
- p->drawLine(x1, y2, x2, y2);
- p->setPen(c1);
- p->drawLine(x1+1, y2-1, x2-1, y2-1);
- }
-
- switch (dir) {
- case SlUp:
- p->setPen(c4);
- p->drawLine(x1, y1, x1+d, y1-d);
- p->setPen(c0);
- d = wi - d - 1;
- p->drawLine(x2, y1, x2-d, y1-d);
- d--;
- p->setPen(c3);
- p->drawLine(x1+1, y1, x1+1+d, y1-d);
- p->setPen(c1);
- p->drawLine(x2-1, y1, x2-1-d, y1-d);
- break;
- case SlDown:
- p->setPen(c4);
- p->drawLine(x1, y2, x1+d, y2+d);
- p->setPen(c0);
- d = wi - d - 1;
- p->drawLine(x2, y2, x2-d, y2+d);
- d--;
- p->setPen(c3);
- p->drawLine(x1+1, y2, x1+1+d, y2+d);
- p->setPen(c1);
- p->drawLine(x2-1, y2, x2-1-d, y2+d);
- break;
- case SlLeft:
- p->setPen(c4);
- p->drawLine(x1, y1, x1-d, y1+d);
- p->setPen(c0);
- d = he - d - 1;
- p->drawLine(x1, y2, x1-d, y2-d);
- d--;
- p->setPen(c3);
- p->drawLine(x1, y1+1, x1-d, y1+1+d);
- p->setPen(c1);
- p->drawLine(x1, y2-1, x1-d, y2-1-d);
- break;
- case SlRight:
- p->setPen(c4);
- p->drawLine(x2, y1, x2+d, y1+d);
- p->setPen(c0);
- d = he - d - 1;
- p->drawLine(x2, y2, x2+d, y2-d);
- d--;
- p->setPen(c3);
- p->drawLine(x2, y1+1, x2+d, y1+1+d);
- p->setPen(c1);
- p->drawLine(x2, y2-1, x2+d, y2-1-d);
- break;
- }
- }
- }
- break;
-#endif // QT_NO_SLIDER
-#ifndef QT_NO_SCROLLBAR
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
- QStyleOptionSlider newScrollbar = *scrollbar;
- if (scrollbar->minimum == scrollbar->maximum)
- newScrollbar.state &= ~State_Enabled; //do not draw the slider.
- QCommonStyle::drawComplexControl(cc, &newScrollbar, p, widget);
- }
- break;
-#endif // QT_NO_SCROLLBAR
-#ifdef QT3_SUPPORT
- case CC_Q3ListView:
- if (const QStyleOptionQ3ListView *lv = qstyleoption_cast<const QStyleOptionQ3ListView *>(opt)) {
- int i;
- if (lv->subControls & SC_Q3ListView)
- QCommonStyle::drawComplexControl(cc, lv, p, widget);
- if (lv->subControls & (SC_Q3ListViewBranch | SC_Q3ListViewExpand)) {
- if (lv->items.isEmpty())
- break;
- QStyleOptionQ3ListViewItem item = lv->items.at(0);
- int y = lv->rect.y();
- int c;
- int dotoffset = 0;
- QPolygon dotlines;
- if ((lv->activeSubControls & SC_All) && (lv->subControls & SC_Q3ListViewExpand)) {
- c = 2;
- dotlines.resize(2);
- dotlines[0] = QPoint(lv->rect.right(), lv->rect.top());
- dotlines[1] = QPoint(lv->rect.right(), lv->rect.bottom());
- } else {
- int linetop = 0, linebot = 0;
- // each branch needs at most two lines, ie. four end points
- dotoffset = (item.itemY + item.height - y) % 2;
- dotlines.resize(item.childCount * 4);
- c = 0;
-
- // skip the stuff above the exposed rectangle
- for (i = 1; i < lv->items.size(); ++i) {
- QStyleOptionQ3ListViewItem child = lv->items.at(i);
- if (child.height + y > 0)
- break;
- y += child.totalHeight;
- }
- int bx = lv->rect.width() / 2;
-
- // paint stuff in the magical area
- while (i < lv->items.size() && y < lv->rect.height()) {
- QStyleOptionQ3ListViewItem child = lv->items.at(i);
- if (child.features & QStyleOptionQ3ListViewItem::Visible) {
- int lh;
- if (!(item.features & QStyleOptionQ3ListViewItem::MultiLine))
- lh = child.height;
- else
- lh = p->fontMetrics().height() + 2 * lv->itemMargin;
- lh = qMax(lh, QApplication::globalStrut().height());
- if (lh % 2 > 0)
- ++lh;
- linebot = y + lh / 2;
- if (child.features & QStyleOptionQ3ListViewItem::Expandable
- || (child.childCount > 0 && child.height > 0)) {
- // needs a box
- p->setPen(lv->palette.mid().color());
- p->drawRect(bx - 4, linebot - 4, 8, 8);
- // plus or minus
- p->setPen(lv->palette.text().color());
- p->drawLine(bx - 2, linebot, bx + 2, linebot);
- if (!(child.state & State_Open))
- p->drawLine(bx, linebot - 2, bx, linebot + 2);
- // dotlinery
- p->setPen(lv->palette.mid().color());
- dotlines[c++] = QPoint(bx, linetop);
- dotlines[c++] = QPoint(bx, linebot - 4);
- dotlines[c++] = QPoint(bx + 5, linebot);
- dotlines[c++] = QPoint(lv->rect.width(), linebot);
- linetop = linebot + 5;
- } else {
- // just dotlinery
- dotlines[c++] = QPoint(bx+1, linebot -1);
- dotlines[c++] = QPoint(lv->rect.width(), linebot -1);
- }
- y += child.totalHeight;
- }
- ++i;
- }
-
- // Expand line height to edge of rectangle if there's any
- // visible child below
- while (i < lv->items.size() && lv->items.at(i).height <= 0)
- ++i;
- if (i < lv->items.size())
- linebot = lv->rect.height();
-
- if (linetop < linebot) {
- dotlines[c++] = QPoint(bx, linetop);
- dotlines[c++] = QPoint(bx, linebot);
- }
- }
- p->setPen(lv->palette.text().color());
- QBitmap *verticalLine = globalVerticalLine();
- QBitmap *horizontalLine = globalHorizontalLine();
- static bool isInit = false;
- if (!isInit) {
- isInit = true;
- // make 128*1 and 1*128 bitmaps that can be used for
- // drawing the right sort of lines.
- verticalLine->clear();
- horizontalLine->clear();
- QPolygon a(64);
- QPainter p;
- p.begin(verticalLine);
- for(i = 0; i < 64; ++i)
- a.setPoint(i, 0, i * 2 + 1);
- p.setPen(Qt::color1);
- p.drawPoints(a);
- p.end();
- QApplication::flush();
- verticalLine->setMask(*verticalLine);
- p.begin(horizontalLine);
- for(i = 0; i < 64; ++i)
- a.setPoint(i, i * 2 + 1, 0);
- p.setPen(Qt::color1);
- p.drawPoints(a);
- p.end();
- QApplication::flush();
- horizontalLine->setMask(*horizontalLine);
- }
-
- int line; // index into dotlines
- if (lv->subControls & SC_Q3ListViewBranch) for(line = 0; line < c; line += 2) {
- // assumptions here: lines are horizontal or vertical.
- // lines always start with the numerically lowest
- // coordinate.
-
- // point ... relevant coordinate of current point
- // end ..... same coordinate of the end of the current line
- // other ... the other coordinate of the current point/line
- if (dotlines[line].y() == dotlines[line+1].y()) {
- int end = dotlines[line + 1].x();
- int point = dotlines[line].x();
- int other = dotlines[line].y();
- while (point < end) {
- int i = 128;
- if (i + point > end)
- i = end-point;
- p->drawPixmap(point, other, *horizontalLine, 0, 0, i, 1);
- point += i;
- }
- } else {
- int end = dotlines[line + 1].y();
- int point = dotlines[line].y();
- int other = dotlines[line].x();
- int pixmapoffset = ((point & 1) != dotoffset) ? 1 : 0;
- while(point < end) {
- int i = 128;
- if (i + point > end)
- i = end-point;
- p->drawPixmap(other, point, *verticalLine, 0, pixmapoffset, 1, i);
- point += i;
- }
- }
- }
- }
- }
- break;
-#endif // QT3_SUPPORT
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
- QBrush editBrush = cmb->palette.brush(QPalette::Base);
- if ((cmb->subControls & SC_ComboBoxFrame)) {
- if (cmb->frame) {
- QPalette shadePal = opt->palette;
- shadePal.setColor(QPalette::Midlight, shadePal.button().color());
- qDrawWinPanel(p, opt->rect, shadePal, true, &editBrush);
- }
- else {
- p->fillRect(opt->rect, editBrush);
- }
- }
- if (cmb->subControls & SC_ComboBoxArrow) {
- State flags = State_None;
-
- QRect ar = proxy()->subControlRect(CC_ComboBox, cmb, SC_ComboBoxArrow, widget);
- bool sunkenArrow = cmb->activeSubControls == SC_ComboBoxArrow
- && cmb->state & State_Sunken;
- if (sunkenArrow) {
- p->setPen(cmb->palette.dark().color());
- p->setBrush(cmb->palette.brush(QPalette::Button));
- p->drawRect(ar.adjusted(0,0,-1,-1));
- } else {
- // Make qDrawWinButton use the right colors for drawing the shade of the button
- QPalette pal(cmb->palette);
- pal.setColor(QPalette::Button, cmb->palette.light().color());
- pal.setColor(QPalette::Light, cmb->palette.button().color());
- qDrawWinButton(p, ar, pal, false,
- &cmb->palette.brush(QPalette::Button));
- }
-
- ar.adjust(2, 2, -2, -2);
- if (opt->state & State_Enabled)
- flags |= State_Enabled;
- if (opt->state & State_HasFocus)
- flags |= State_HasFocus;
-
- if (sunkenArrow)
- flags |= State_Sunken;
- QStyleOption arrowOpt(0);
- arrowOpt.rect = ar.adjusted(1, 1, -1, -1);
- arrowOpt.palette = cmb->palette;
- arrowOpt.state = flags;
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, widget);
- }
-
- if (cmb->subControls & SC_ComboBoxEditField) {
- QRect re = proxy()->subControlRect(CC_ComboBox, cmb, SC_ComboBoxEditField, widget);
- if (cmb->state & State_HasFocus && !cmb->editable)
- p->fillRect(re.x(), re.y(), re.width(), re.height(),
- cmb->palette.brush(QPalette::Highlight));
-
- if (cmb->state & State_HasFocus) {
- p->setPen(cmb->palette.highlightedText().color());
- p->setBackground(cmb->palette.highlight());
-
- } else {
- p->setPen(cmb->palette.text().color());
- p->setBackground(cmb->palette.background());
- }
-
- if (cmb->state & State_HasFocus && !cmb->editable) {
- QStyleOptionFocusRect focus;
- focus.QStyleOption::operator=(*cmb);
- focus.rect = subElementRect(SE_ComboBoxFocusRect, cmb, widget);
- focus.state |= State_FocusAtBorder;
- focus.backgroundColor = cmb->palette.highlight().color();
- proxy()->drawPrimitive(PE_FrameFocusRect, &focus, p, widget);
- }
- }
- }
- break;
-#endif // QT_NO_COMBOBOX
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
- QStyleOptionSpinBox copy = *sb;
- PrimitiveElement pe;
- bool enabled = opt->state & State_Enabled;
- if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
- QBrush editBrush = sb->palette.brush(QPalette::Base);
- QRect r = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxFrame, widget);
- QPalette shadePal = sb->palette;
- shadePal.setColor(QPalette::Midlight, shadePal.button().color());
- qDrawWinPanel(p, r, shadePal, true, &editBrush);
- }
-
- QPalette shadePal(opt->palette);
- shadePal.setColor(QPalette::Button, opt->palette.light().color());
- shadePal.setColor(QPalette::Light, opt->palette.button().color());
-
- if (sb->subControls & SC_SpinBoxUp) {
- copy.subControls = SC_SpinBoxUp;
- QPalette pal2 = sb->palette;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepUpEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
-
- copy.palette = pal2;
-
- if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinPlus
- : PE_IndicatorSpinUp);
-
- copy.rect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxUp, widget);
- qDrawWinButton(p, copy.rect, shadePal, copy.state & (State_Sunken | State_On),
- &copy.palette.brush(QPalette::Button));
- copy.rect.adjust(4, 1, -5, -1);
- if ((!enabled || !(sb->stepEnabled & QAbstractSpinBox::StepUpEnabled))
- && proxy()->styleHint(SH_EtchDisabledText, opt, widget) )
- {
- QStyleOptionSpinBox lightCopy = copy;
- lightCopy.rect.adjust(1, 1, 1, 1);
- lightCopy.palette.setBrush(QPalette::ButtonText, copy.palette.light());
- proxy()->drawPrimitive(pe, &lightCopy, p, widget);
- }
- proxy()->drawPrimitive(pe, &copy, p, widget);
- }
-
- if (sb->subControls & SC_SpinBoxDown) {
- copy.subControls = SC_SpinBoxDown;
- copy.state = sb->state;
- QPalette pal2 = sb->palette;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
- pal2.setCurrentColorGroup(QPalette::Disabled);
- copy.state &= ~State_Enabled;
- }
- copy.palette = pal2;
-
- if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_Sunken)) {
- copy.state |= State_On;
- copy.state |= State_Sunken;
- } else {
- copy.state |= State_Raised;
- copy.state &= ~State_Sunken;
- }
- pe = (sb->buttonSymbols == QAbstractSpinBox::PlusMinus ? PE_IndicatorSpinMinus
- : PE_IndicatorSpinDown);
-
- copy.rect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxDown, widget);
- qDrawWinButton(p, copy.rect, shadePal, copy.state & (State_Sunken | State_On),
- &copy.palette.brush(QPalette::Button));
- copy.rect.adjust(4, 0, -5, -1);
- if ((!enabled || !(sb->stepEnabled & QAbstractSpinBox::StepDownEnabled))
- && proxy()->styleHint(SH_EtchDisabledText, opt, widget) )
- {
- QStyleOptionSpinBox lightCopy = copy;
- lightCopy.rect.adjust(1, 1, 1, 1);
- lightCopy.palette.setBrush(QPalette::ButtonText, copy.palette.light());
- proxy()->drawPrimitive(pe, &lightCopy, p, widget);
- }
- proxy()->drawPrimitive(pe, &copy, p, widget);
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-
- default:
- QCommonStyle::drawComplexControl(cc, opt, p, widget);
- }
-}
-
-/*! \reimp */
-QSize QWindowsStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &csz, const QWidget *widget) const
-{
- QSize sz(csz);
- switch (ct) {
- case CT_PushButton:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
- sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
- int w = sz.width(),
- h = sz.height();
- int defwidth = 0;
- if (btn->features & QStyleOptionButton::AutoDefaultButton)
- defwidth = 2 * proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget);
- int minwidth = int(QStyleHelper::dpiScaled(75.));
- int minheight = int(QStyleHelper::dpiScaled(23.));
-
-#ifndef QT_QWS_SMALL_PUSHBUTTON
- if (w < minwidth + defwidth && !btn->text.isEmpty())
- w = minwidth + defwidth;
- if (h < minheight + defwidth)
- h = minheight + defwidth;
-#endif
- sz = QSize(w, h);
- }
- break;
-#ifndef QT_NO_MENU
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
- int w = sz.width();
- sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
-
- if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
- sz = QSize(10, QWindowsStylePrivate::windowsSepHeight);
- }
- else if (mi->icon.isNull()) {
- sz.setHeight(sz.height() - 2);
- w -= 6;
- }
-
- if (mi->menuItemType != QStyleOptionMenuItem::Separator && !mi->icon.isNull()) {
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
- sz.setHeight(qMax(sz.height(),
- mi->icon.actualSize(QSize(iconExtent, iconExtent)).height()
- + 2 * QWindowsStylePrivate::windowsItemFrame));
- }
- int maxpmw = mi->maxIconWidth;
- int tabSpacing = 20;
- if (mi->text.contains(QLatin1Char('\t')))
- w += tabSpacing;
- else if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
- w += 2 * QWindowsStylePrivate::windowsArrowHMargin;
- else if (mi->menuItemType == QStyleOptionMenuItem::DefaultItem) {
- // adjust the font and add the difference in size.
- // it would be better if the font could be adjusted in the initStyleOption qmenu func!!
- QFontMetrics fm(mi->font);
- QFont fontBold = mi->font;
- fontBold.setBold(true);
- QFontMetrics fmBold(fontBold);
- w += fmBold.width(mi->text) - fm.width(mi->text);
- }
-
- int checkcol = qMax<int>(maxpmw, QWindowsStylePrivate::windowsCheckMarkWidth); // Windows always shows a check column
- w += checkcol;
- w += int(QWindowsStylePrivate::windowsRightBorder) + 10;
- sz.setWidth(w);
- }
- break;
-#endif // QT_NO_MENU
-#ifndef QT_NO_MENUBAR
- case CT_MenuBarItem:
- if (!sz.isEmpty())
- sz += QSize(QWindowsStylePrivate::windowsItemHMargin * 4, QWindowsStylePrivate::windowsItemVMargin * 2);
- break;
-#endif
- // Otherwise, fall through
- case CT_ToolButton:
- if (qstyleoption_cast<const QStyleOptionToolButton *>(opt))
- return sz += QSize(7, 6);
- // Otherwise, fall through
-
- default:
- sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
- }
- return sz;
-}
-
-/*!
- \internal
-*/
-QIcon QWindowsStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget) const
-{
- QIcon icon;
- QPixmap pixmap;
-#ifdef Q_OS_WIN
- switch (standardIcon) {
- case SP_FileDialogNewFolder:
- {
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(319, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- }
- case SP_DirHomeIcon:
- {
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(235, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- }
- case SP_DirIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(4, size);
- icon.addPixmap(pixmap, QIcon::Normal, QIcon::Off);
- pixmap = loadIconFromShell32(5, size);
- icon.addPixmap(pixmap, QIcon::Normal, QIcon::On);
- }
- break;
- case SP_DirLinkIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- QPixmap link = loadIconFromShell32(30, size);
- pixmap = loadIconFromShell32(4, size);
- if (!pixmap.isNull() && !link.isNull()) {
- QPainter painter(&pixmap);
- painter.drawPixmap(0, 0, size, size, link);
- icon.addPixmap(pixmap, QIcon::Normal, QIcon::Off);
- }
- link = loadIconFromShell32(30, size);
- pixmap = loadIconFromShell32(5, size);
- if (!pixmap.isNull() && !link.isNull()) {
- QPainter painter(&pixmap);
- painter.drawPixmap(0, 0, size, size, link);
- icon.addPixmap(pixmap, QIcon::Normal, QIcon::On);
- }
- }
- break;
- case SP_FileIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(1, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- case SP_ComputerIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(16, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
-
- case SP_DesktopIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(35, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- case SP_DriveCDIcon:
- case SP_DriveDVDIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(12, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- case SP_DriveNetIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(10, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- case SP_DriveHDIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(9, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- case SP_DriveFDIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- pixmap = loadIconFromShell32(7, size);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- break;
- case SP_FileLinkIcon:
- for (int size = 16 ; size <= 32 ; size += 16) {
- QPixmap link;
- link = loadIconFromShell32(30, size);
- pixmap = loadIconFromShell32(1, size);
- if (!pixmap.isNull() && !link.isNull()) {
- QPainter painter(&pixmap);
- painter.drawPixmap(0, 0, size, size, link);
- icon.addPixmap(pixmap, QIcon::Normal);
- }
- }
- break;
- case SP_VistaShield:
- {
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA
- && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based
- && pSHGetStockIconInfo)
- {
- icon.addPixmap(proxy()->standardPixmap(SP_VistaShield, option, widget)); //fetches small icon
- QSHSTOCKICONINFO iconInfo; //append large icon
- memset(&iconInfo, 0, sizeof(iconInfo));
- iconInfo.cbSize = sizeof(iconInfo);
- if (pSHGetStockIconInfo(_SIID_SHIELD, _SHGFI_ICON | _SHGFI_LARGEICON, &iconInfo) == S_OK) {
- icon.addPixmap(QPixmap::fromWinHICON(iconInfo.hIcon));
- DestroyIcon(iconInfo.hIcon);
- }
- }
- }
- break;
- default:
- break;
- }
-#endif
-
- if (icon.isNull())
- icon = QCommonStyle::standardIconImplementation(standardIcon, option, widget);
- return icon;
-}
-
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWS
diff --git a/src/gui/styles/qwindowsstyle.h b/src/gui/styles/qwindowsstyle.h
deleted file mode 100644
index 99f64fcb05..0000000000
--- a/src/gui/styles/qwindowsstyle.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSSTYLE_H
-#define QWINDOWSSTYLE_H
-
-#include <QtGui/qcommonstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_WINDOWS)
-
-class QWindowsStylePrivate;
-
-class Q_GUI_EXPORT QWindowsStyle : public QCommonStyle
-{
- Q_OBJECT
-public:
- QWindowsStyle();
- ~QWindowsStyle();
-
- void polish(QApplication*);
- void unpolish(QApplication*);
-
- void polish(QWidget*);
- void unpolish(QWidget*);
-
- void polish(QPalette &);
-
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
- void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const;
- QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const;
-
- int pixelMetric(PixelMetric pm, const QStyleOption *option = 0, const QWidget *widget = 0) const;
-
- int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
-
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget = 0) const;
-
-protected:
- bool eventFilter(QObject *o, QEvent *e);
- void timerEvent(QTimerEvent *event);
- QWindowsStyle(QWindowsStylePrivate &dd);
-
-private:
- Q_DISABLE_COPY(QWindowsStyle)
- Q_DECLARE_PRIVATE(QWindowsStyle)
- void *reserved;
-};
-
-#endif // QT_NO_STYLE_WINDOWS
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWINDOWSSTYLE_H
diff --git a/src/gui/styles/qwindowsstyle_p.h b/src/gui/styles/qwindowsstyle_p.h
deleted file mode 100644
index a10f2baffd..0000000000
--- a/src/gui/styles/qwindowsstyle_p.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSSTYLE_P_H
-#define QWINDOWSSTYLE_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qwindowsstyle.h"
-#include "qcommonstyle_p.h"
-
-#ifndef QT_NO_STYLE_WINDOWS
-#include <qlist.h>
-#include <qhash.h>
-#include <qelapsedtimer.h>
-
-QT_BEGIN_NAMESPACE
-
-class QTime;
-class QProgressBar;
-
-class QWindowsStylePrivate : public QCommonStylePrivate
-{
- Q_DECLARE_PUBLIC(QWindowsStyle)
-public:
- QWindowsStylePrivate();
- bool hasSeenAlt(const QWidget *widget) const;
- bool altDown() const { return alt_down; }
- bool alt_down;
- QList<const QWidget *> seenAlt;
- int menuBarTimer;
-
- QList<QProgressBar *> bars;
- int animationFps;
- int animateTimer;
- QElapsedTimer startTime;
- int animateStep;
- QColor inactiveCaptionText;
- QColor activeCaptionColor;
- QColor activeGradientCaptionColor;
- QColor inactiveCaptionColor;
- QColor inactiveGradientCaptionColor;
-
- enum {
- windowsItemFrame = 2, // menu item frame width
- windowsSepHeight = 9, // separator item height
- windowsItemHMargin = 3, // menu item hor text margin
- windowsItemVMargin = 2, // menu item ver text margin
- windowsArrowHMargin = 6, // arrow horizontal margin
- windowsRightBorder = 15, // right border on windows
- windowsCheckMarkWidth = 12 // checkmarks width on windows
- };
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWS
-
-#endif //QWINDOWSSTYLE_P_H
diff --git a/src/gui/styles/qwindowsvistastyle.cpp b/src/gui/styles/qwindowsvistastyle.cpp
deleted file mode 100644
index 7f1a3ab678..0000000000
--- a/src/gui/styles/qwindowsvistastyle.cpp
+++ /dev/null
@@ -1,2670 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwindowsvistastyle.h"
-#include "qwindowsvistastyle_p.h"
-#include <private/qstylehelper_p.h>
-#include <private/qsystemlibrary_p.h>
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA) || defined(QT_PLUGIN)
-
-QT_BEGIN_NAMESPACE
-
-static const int windowsItemFrame = 2; // menu item frame width
-static const int windowsItemHMargin = 3; // menu item hor text margin
-static const int windowsItemVMargin = 4; // menu item ver text margin
-static const int windowsArrowHMargin = 6; // arrow horizontal margin
-static const int windowsRightBorder = 15; // right border on windows
-
-#ifndef TMT_CONTENTMARGINS
-# define TMT_CONTENTMARGINS 3602
-#endif
-#ifndef TMT_SIZINGMARGINS
-# define TMT_SIZINGMARGINS 3601
-#endif
-#ifndef LISS_NORMAL
-# define LISS_NORMAL 1
-# define LISS_HOT 2
-# define LISS_SELECTED 3
-# define LISS_DISABLED 4
-# define LISS_SELECTEDNOTFOCUS 5
-# define LISS_HOTSELECTED 6
-#endif
-#ifndef BP_COMMANDLINK
-# define BP_COMMANDLINK 6
-# define BP_COMMANDLINKGLYPH 7
-# define CMDLGS_NORMAL 1
-# define CMDLGS_HOT 2
-# define CMDLGS_PRESSED 3
-# define CMDLGS_DISABLED 4
-#endif
-
-// Runtime resolved theme engine function calls
-
-
-typedef HRESULT (WINAPI *PtrGetThemePartSize)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, OPTIONAL RECT *prc, enum THEMESIZE eSize, OUT SIZE *psz);
-typedef HTHEME (WINAPI *PtrOpenThemeData)(HWND hwnd, LPCWSTR pszClassList);
-typedef HTHEME (WINAPI *PtrOpenThemeData)(HWND hwnd, LPCWSTR pszClassList);
-typedef HRESULT (WINAPI *PtrCloseThemeData)(HTHEME hTheme);
-typedef HRESULT (WINAPI *PtrDrawThemeBackground)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const RECT *pClipRect);
-typedef HRESULT (WINAPI *PtrDrawThemeBackgroundEx)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const DTBGOPTS *pOptions);
-typedef HRESULT (WINAPI *PtrGetCurrentThemeName)(OUT LPWSTR pszThemeFileName, int cchMaxNameChars, OUT OPTIONAL LPWSTR pszColorBuff, int cchMaxColorChars, OUT OPTIONAL LPWSTR pszSizeBuff, int cchMaxSizeChars);
-typedef HRESULT (WINAPI *PtrGetThemeBool)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT BOOL *pfVal);
-typedef HRESULT (WINAPI *PtrGetThemeColor)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT COLORREF *pColor);
-typedef HRESULT (WINAPI *PtrGetThemeEnumValue)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT int *piVal);
-typedef HRESULT (WINAPI *PtrGetThemeFilename)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT LPWSTR pszThemeFileName, int cchMaxBuffChars);
-typedef HRESULT (WINAPI *PtrGetThemeFont)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OUT LOGFONT *pFont);
-typedef HRESULT (WINAPI *PtrGetThemeInt)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT int *piVal);
-typedef HRESULT (WINAPI *PtrGetThemeIntList)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT INTLIST *pIntList);
-typedef HRESULT (WINAPI *PtrGetThemeMargins)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OPTIONAL RECT *prc, OUT MARGINS *pMargins);
-typedef HRESULT (WINAPI *PtrGetThemeMetric)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OUT int *piVal);
-typedef HRESULT (WINAPI *PtrGetThemePartSize)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, OPTIONAL RECT *prc, enum THEMESIZE eSize, OUT SIZE *psz);
-typedef HRESULT (WINAPI *PtrGetThemePosition)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT POINT *pPoint);
-typedef HRESULT (WINAPI *PtrGetThemeRect)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT RECT *pRect);
-typedef HRESULT (WINAPI *PtrGetThemeString)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT LPWSTR pszBuff, int cchMaxBuffChars);
-typedef HRESULT (WINAPI *PtrGetThemeTransitionDuration)(HTHEME hTheme, int iPartId, int iStateFromId, int iStateToId, int iPropId, int *pDuration);
-typedef HRESULT (WINAPI *PtrIsThemePartDefined)(HTHEME hTheme, int iPartId, int iStateId);
-typedef HRESULT (WINAPI *PtrSetWindowTheme)(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList);
-typedef HRESULT (WINAPI *PtrGetThemePropertyOrigin)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT enum PROPERTYORIGIN *pOrigin);
-
-static PtrIsThemePartDefined pIsThemePartDefined = 0;
-static PtrOpenThemeData pOpenThemeData = 0;
-static PtrCloseThemeData pCloseThemeData = 0;
-static PtrDrawThemeBackground pDrawThemeBackground = 0;
-static PtrDrawThemeBackgroundEx pDrawThemeBackgroundEx = 0;
-static PtrGetCurrentThemeName pGetCurrentThemeName = 0;
-static PtrGetThemeBool pGetThemeBool = 0;
-static PtrGetThemeColor pGetThemeColor = 0;
-static PtrGetThemeEnumValue pGetThemeEnumValue = 0;
-static PtrGetThemeFilename pGetThemeFilename = 0;
-static PtrGetThemeFont pGetThemeFont = 0;
-static PtrGetThemeInt pGetThemeInt = 0;
-static PtrGetThemeIntList pGetThemeIntList = 0;
-static PtrGetThemeMargins pGetThemeMargins = 0;
-static PtrGetThemeMetric pGetThemeMetric = 0;
-static PtrGetThemePartSize pGetThemePartSize = 0;
-static PtrGetThemePosition pGetThemePosition = 0;
-static PtrGetThemeRect pGetThemeRect = 0;
-static PtrGetThemeString pGetThemeString = 0;
-static PtrGetThemeTransitionDuration pGetThemeTransitionDuration= 0;
-static PtrSetWindowTheme pSetWindowTheme = 0;
-static PtrGetThemePropertyOrigin pGetThemePropertyOrigin = 0;
-
-/* \internal
- Checks if we should use Vista style , or if we should
- fall back to Windows style.
-*/
-bool QWindowsVistaStylePrivate::useVista()
-{
- return (QWindowsVistaStylePrivate::useXP() &&
- (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA &&
- QSysInfo::WindowsVersion < QSysInfo::WV_NT_based));
-}
-
-/*!
- \class QWindowsVistaStyle
- \brief The QWindowsVistaStyle class provides a look and feel suitable for applications on Microsoft Windows Vista.
- \since 4.3
- \ingroup appearance
-
- \warning This style is only available on the Windows Vista platform
- because it makes use of Windows Vista's style engine.
-
- \sa QMacStyle, QWindowsXPStyle, QPlastiqueStyle, QCleanlooksStyle, QMotifStyle
-*/
-
-/*!
- Constructs a QWindowsVistaStyle object.
-*/
-QWindowsVistaStyle::QWindowsVistaStyle()
- : QWindowsXPStyle(*new QWindowsVistaStylePrivate)
-{
-}
-
-//convert Qt state flags to uxtheme button states
-static int buttonStateId(int flags, int partId)
-{
- int stateId = 0;
- if (partId == BP_RADIOBUTTON || partId == BP_CHECKBOX) {
- if (!(flags & QStyle::State_Enabled))
- stateId = RBS_UNCHECKEDDISABLED;
- else if (flags & QStyle::State_Sunken)
- stateId = RBS_UNCHECKEDPRESSED;
- else if (flags & QStyle::State_MouseOver)
- stateId = RBS_UNCHECKEDHOT;
- else
- stateId = RBS_UNCHECKEDNORMAL;
-
- if (flags & QStyle::State_On)
- stateId += RBS_CHECKEDNORMAL-1;
-
- } else if (partId == BP_PUSHBUTTON) {
- if (!(flags & QStyle::State_Enabled))
- stateId = PBS_DISABLED;
- else if (flags & (QStyle::State_Sunken | QStyle::State_On))
- stateId = PBS_PRESSED;
- else if (flags & QStyle::State_MouseOver)
- stateId = PBS_HOT;
- else
- stateId = PBS_NORMAL;
- } else {
- Q_ASSERT(1);
- }
- return stateId;
-}
-
-void QWindowsVistaAnimation::paint(QPainter *painter, const QStyleOption *option)
-{
- Q_UNUSED(option);
- Q_UNUSED(painter);
-}
-
-/*! \internal
-
- Helperfunction to paint the current transition state between two
- animation frames.
-
- The result is a blended image consisting of ((alpha)*_primaryImage)
- + ((1-alpha)*_secondaryImage)
-
-*/
-void QWindowsVistaAnimation::drawBlendedImage(QPainter *painter, QRect rect, float alpha) {
- if (_secondaryImage.isNull() || _primaryImage.isNull())
- return;
-
- if (_tempImage.isNull())
- _tempImage = _secondaryImage;
-
- const int a = qRound(alpha*256);
- const int ia = 256 - a;
- const int sw = _primaryImage.width();
- const int sh = _primaryImage.height();
- const int bpl = _primaryImage.bytesPerLine();
- switch(_primaryImage.depth()) {
- case 32:
- {
- uchar *mixed_data = _tempImage.bits();
- const uchar *back_data = _primaryImage.bits();
- const uchar *front_data = _secondaryImage.bits();
- for (int sy = 0; sy < sh; sy++) {
- quint32* mixed = (quint32*)mixed_data;
- const quint32* back = (const quint32*)back_data;
- const quint32* front = (const quint32*)front_data;
- for (int sx = 0; sx < sw; sx++) {
- quint32 bp = back[sx];
- quint32 fp = front[sx];
- mixed[sx] = qRgba ((qRed(bp)*ia + qRed(fp)*a)>>8,
- (qGreen(bp)*ia + qGreen(fp)*a)>>8,
- (qBlue(bp)*ia + qBlue(fp)*a)>>8,
- (qAlpha(bp)*ia + qAlpha(fp)*a)>>8);
- }
- mixed_data += bpl;
- back_data += bpl;
- front_data += bpl;
- }
- }
- default:
- break;
- }
- painter->drawImage(rect, _tempImage);
-}
-
-/*! \internal
- Paints a transition state. The result will be a mix between the
- initial and final state of the transition, depending on the time
- difference between _startTime and current time.
-*/
-void QWindowsVistaTransition::paint(QPainter *painter, const QStyleOption *option)
-{
- float alpha = 1.0;
- if (_duration > 0) {
- QTime current = QTime::currentTime();
-
- if (_startTime > current)
- _startTime = current;
-
- int timeDiff = _startTime.msecsTo(current);
- alpha = timeDiff/(float)_duration;
- if (timeDiff > _duration) {
- _running = false;
- alpha = 1.0;
- }
- }
- else {
- _running = false;
- }
- drawBlendedImage(painter, option->rect, alpha);
-}
-
-/*! \internal
- Paints a pulse. The result will be a mix between the primary and
- secondary pulse images depending on the time difference between
- _startTime and current time.
-*/
-void QWindowsVistaPulse::paint(QPainter *painter, const QStyleOption *option)
-{
- float alpha = 1.0;
- if (_duration > 0) {
- QTime current = QTime::currentTime();
-
- if (_startTime > current)
- _startTime = current;
-
- int timeDiff = _startTime.msecsTo(current) % _duration*2;
- if (timeDiff > _duration)
- timeDiff = _duration*2 - timeDiff;
- alpha = timeDiff/(float)_duration;
- } else {
- _running = false;
- }
- drawBlendedImage(painter, option->rect, alpha);
-}
-
-
-/*!
- \internal
-
- Animations are used for some state transitions on specific widgets.
-
- Only one running animation can exist for a widget at any specific
- time. Animations can be added through
- QWindowsVistaStylePrivate::startAnimation(Animation *) and any
- existing animation on a widget can be retrieved with
- QWindowsVistaStylePrivate::widgetAnimation(Widget *).
-
- Once an animation has been started,
- QWindowsVistaStylePrivate::timerEvent(QTimerEvent *) will
- continuously call update() on the widget until it is stopped,
- meaning that drawPrimitive will be called many times until the
- transition has completed. During this time, the result will be
- retrieved by the Animation::paint(...) function and not by the style
- itself.
-
- To determine if a transition should occur, the style needs to know
- the previous state of the widget as well as the current one. This is
- solved by updating dynamic properties on the widget every time the
- function is called.
-
- Transitions interrupting existing transitions should always be
- smooth, so whenever a hover-transition is started on a pulsating
- button, it uses the current frame of the pulse-animation as the
- starting image for the hover transition.
-
- */
-void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const
-{
- QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate*>(d_func());
-
- int state = option->state;
- if (!QWindowsVistaStylePrivate::useVista()) {
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- return;
- }
-
- QRect oldRect;
- QRect newRect;
-
- if (widget && d->transitionsEnabled())
- {
- /* all widgets that supports state transitions : */
- if (
-#ifndef QT_NO_LINEEDIT
- (qobject_cast<const QLineEdit*>(widget) && element == PE_FrameLineEdit) ||
-#endif // QT_NO_LINEEDIT
- (qobject_cast<const QRadioButton*>(widget)&& element == PE_IndicatorRadioButton) ||
- (qobject_cast<const QCheckBox*>(widget) && element == PE_IndicatorCheckBox) ||
- (qobject_cast<const QGroupBox *>(widget)&& element == PE_IndicatorCheckBox) ||
- (qobject_cast<const QToolButton*>(widget) && element == PE_PanelButtonBevel)
- )
- {
- // Retrieve and update the dynamic properties tracking
- // the previous state of the widget:
- QWidget *w = const_cast<QWidget *> (widget);
- int oldState = w->property("_q_stylestate").toInt();
- oldRect = w->property("_q_stylerect").toRect();
- newRect = w->rect();
- w->setProperty("_q_stylestate", (int)option->state);
- w->setProperty("_q_stylerect", w->rect());
-
- bool doTransition = oldState &&
- ((state & State_Sunken) != (oldState & State_Sunken) ||
- (state & State_On) != (oldState & State_On) ||
- (state & State_MouseOver) != (oldState & State_MouseOver));
-
- if (oldRect != newRect ||
- (state & State_Enabled) != (oldState & State_Enabled) ||
- (state & State_Active) != (oldState & State_Active))
- d->stopAnimation(widget);
-
-#ifndef QT_NO_LINEEDIT
- if (const QLineEdit *edit = qobject_cast<const QLineEdit *>(widget))
- if (edit->isReadOnly() && element == PE_FrameLineEdit) // Do not animate read only line edits
- doTransition = false;
-#endif // QT_NO_LINEEDIT
-
- if (doTransition) {
-
- // We create separate images for the initial and final transition states and store them in the
- // Transition object.
- QImage startImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- QImage endImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- QStyleOption opt = *option;
-
- opt.rect.setRect(0, 0, option->rect.width(), option->rect.height());
- opt.state = (QStyle::State)oldState;
- startImage.fill(0);
- QPainter startPainter(&startImage);
-
- QWindowsVistaAnimation *anim = d->widgetAnimation(widget);
- QWindowsVistaTransition *t = new QWindowsVistaTransition;
- t->setWidget(w);
-
- // If we have a running animation on the widget already, we will use that to paint the initial
- // state of the new transition, this ensures a smooth transition from a current animation such as a
- // pulsating default button into the intended target state.
-
- if (!anim)
- proxy()->drawPrimitive(element, &opt, &startPainter, 0); // Note that the widget pointer is intentionally 0
- else // this ensures that we do not recurse in the animation logic above
- anim->paint(&startPainter, &opt);
-
- d->startAnimation(t);
- t->setStartImage(startImage);
-
- // The end state of the transition is simply the result we would have painted
- // if the style was not animated.
-
- QPainter endPainter(&endImage);
- endImage.fill(0);
- QStyleOption opt2 = opt;
- opt2.state = option->state;
- proxy()->drawPrimitive(element, &opt2, &endPainter, 0); // Note that the widget pointer is intentionally 0
- // this ensures that we do not recurse in the animation logic above
- t->setEndImage(endImage);
-
- HTHEME theme;
- int partId;
- int duration;
- int fromState = 0;
- int toState = 0;
-
- //translate state flags to UXTHEME states :
- if (element == PE_FrameLineEdit) {
- theme = pOpenThemeData(0, L"Edit");
- partId = EP_EDITBORDER_NOSCROLL;
-
- if (oldState & State_MouseOver)
- fromState = ETS_HOT;
- else if (oldState & State_HasFocus)
- fromState = ETS_FOCUSED;
- else
- fromState = ETS_NORMAL;
-
- if (state & State_MouseOver)
- toState = ETS_HOT;
- else if (state & State_HasFocus)
- toState = ETS_FOCUSED;
- else
- toState = ETS_NORMAL;
-
- } else {
- theme = pOpenThemeData(0, L"Button");
- if (element == PE_IndicatorRadioButton)
- partId = BP_RADIOBUTTON;
- else if (element == PE_IndicatorCheckBox)
- partId = BP_CHECKBOX;
- else
- partId = BP_PUSHBUTTON;
-
- fromState = buttonStateId(oldState, partId);
- toState = buttonStateId(option->state, partId);
- }
-
- // Retrieve the transition time between the states from the system.
- if (theme && pGetThemeTransitionDuration(theme, partId, fromState, toState,
- TMT_TRANSITIONDURATIONS, &duration) == S_OK)
- {
- t->setDuration(duration);
- }
- t->setStartTime(QTime::currentTime());
- }
- }
- } // End of animation part
-
-
- QRect rect = option->rect;
-
- switch (element) {
- case PE_IndicatorHeaderArrow:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- int stateId = HSAS_SORTEDDOWN;
- if (header->sortIndicator & QStyleOptionHeader::SortDown)
- stateId = HSAS_SORTEDUP; //note that the uxtheme sort down indicator is the inverse of ours
- XPThemeData theme(widget, painter, QLatin1String("HEADER"), HP_HEADERSORTARROW, stateId, option->rect);
- d->drawBackground(theme);
- }
- break;
-
- case PE_IndicatorBranch:
- {
- XPThemeData theme(d->treeViewHelper(), painter, QLatin1String("TREEVIEW"));
- static int decoration_size = 0;
- if (theme.isValid() && !decoration_size) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, TVP_HOTGLYPH, GLPS_OPENED, 0, TS_TRUE, &size);
- decoration_size = qMax(size.cx, size.cy);
- }
- int mid_h = option->rect.x() + option->rect.width() / 2;
- int mid_v = option->rect.y() + option->rect.height() / 2;
- int bef_h = mid_h;
- int bef_v = mid_v;
- int aft_h = mid_h;
- int aft_v = mid_v;
- if (option->state & State_Children) {
- int delta = decoration_size / 2;
- theme.rect = QRect(bef_h - delta, bef_v - delta, decoration_size, decoration_size);
- theme.partId = option->state & State_MouseOver ? TVP_HOTGLYPH : TVP_GLYPH;
- theme.stateId = option->state & QStyle::State_Open ? GLPS_OPENED : GLPS_CLOSED;
- if (option->direction == Qt::RightToLeft)
- theme.mirrorHorizontally = true;
- d->drawBackground(theme);
- bef_h -= delta + 2;
- bef_v -= delta + 2;
- aft_h += delta - 2;
- aft_v += delta - 2;
- }
-#if 0
- QBrush brush(option->palette.dark().color(), Qt::Dense4Pattern);
- if (option->state & State_Item) {
- if (option->direction == Qt::RightToLeft)
- painter->fillRect(option->rect.left(), mid_v, bef_h - option->rect.left(), 1, brush);
- else
- painter->fillRect(aft_h, mid_v, option->rect.right() - aft_h + 1, 1, brush);
- }
- if (option->state & State_Sibling && option->rect.bottom() > aft_v)
- painter->fillRect(mid_h, aft_v, 1, option->rect.bottom() - aft_v + 1, brush);
- if (option->state & (State_Open | State_Children | State_Item | State_Sibling) && (bef_v > option->rect.y()))
- painter->fillRect(mid_h, option->rect.y(), 1, bef_v - option->rect.y(), brush);
-#endif
- }
- break;
-
- case PE_PanelButtonBevel:
- case PE_IndicatorCheckBox:
- case PE_IndicatorRadioButton:
- {
- if (QWindowsVistaAnimation *a = d->widgetAnimation(widget)) {
- a->paint(painter, option);
- } else {
- QWindowsXPStyle::drawPrimitive(element, option, painter, widget);
- }
- }
- break;
-
- case PE_FrameMenu:
- {
- int stateId = option->state & State_Active ? MB_ACTIVE : MB_INACTIVE;
- XPThemeData theme(widget, painter, QLatin1String("MENU"), MENU_POPUPBORDERS, stateId, option->rect);
- d->drawBackground(theme);
- }
- break;
- case PE_Frame:
-#ifndef QT_NO_TEXTEDIT
- if (const QTextEdit *edit = qobject_cast<const QTextEdit*>(widget)) {
- painter->save();
- int stateId = ETS_NORMAL;
- if (!(state & State_Enabled))
- stateId = ETS_DISABLED;
- else if (edit->isReadOnly())
- stateId = ETS_READONLY;
- else if (state & State_HasFocus)
- stateId = ETS_SELECTED;
- XPThemeData theme(widget, painter, QLatin1String("EDIT"), EP_EDITBORDER_HVSCROLL, stateId, option->rect);
- uint resolve_mask = option->palette.resolve();
- if (resolve_mask & (1 << QPalette::Base)) {
- // Since EP_EDITBORDER_HVSCROLL does not us borderfill, theme.noContent cannot be used for clipping
- int borderSize = 1;
- pGetThemeInt(theme.handle(), theme.partId, theme.stateId, TMT_BORDERSIZE, &borderSize);
- QRegion clipRegion = option->rect;
- QRegion content = option->rect.adjusted(borderSize, borderSize, -borderSize, -borderSize);
- clipRegion ^= content;
- painter->setClipRegion(clipRegion);
- }
- d->drawBackground(theme);
- painter->restore();
- } else
-#endif // QT_NO_TEXTEDIT
- QWindowsXPStyle::drawPrimitive(element, option, painter, widget);
- break;
-
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- QBrush bg;
- bool usePalette = false;
- bool isEnabled = option->state & State_Enabled;
- uint resolve_mask = panel->palette.resolve();
- if (widget) {
- //Since spin box and combo box includes a line edit we need to resolve the palette on the parent instead
-#ifndef QT_NO_SPINBOX
- if (QAbstractSpinBox *spinbox = qobject_cast<QAbstractSpinBox*>(widget->parentWidget()))
- resolve_mask = spinbox->palette().resolve();
-#endif // QT_NO_SPINBOX
- }
- if (resolve_mask & (1 << QPalette::Base)) {
- // Base color is set for this widget, so use it
- bg = panel->palette.brush(QPalette::Base);
- usePalette = true;
- }
- if (usePalette) {
- painter->fillRect(panel->rect, bg);
- } else {
- int partId = EP_BACKGROUND;
- int stateId = EBS_NORMAL;
- if (!isEnabled)
- stateId = EBS_DISABLED;
- else if (state & State_ReadOnly)
- stateId = EBS_READONLY;
- else if (state & State_MouseOver)
- stateId = EBS_HOT;
-
- XPThemeData theme(0, painter, QLatin1String("EDIT"), partId, stateId, rect);
- if (!theme.isValid()) {
- QWindowsStyle::drawPrimitive(element, option, painter, widget);
- return;
- }
- int bgType;
- pGetThemeEnumValue( theme.handle(),
- partId,
- stateId,
- TMT_BGTYPE,
- &bgType);
- if( bgType == BT_IMAGEFILE ) {
- d->drawBackground(theme);
- } else {
- QBrush fillColor = option->palette.brush(QPalette::Base);
- if (!isEnabled) {
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(theme.handle(), theme.partId, theme.stateId, TMT_FILLCOLOR, &origin);
- // Use only if the fill property comes from our part
- if ((origin == PO_PART || origin == PO_STATE)) {
- COLORREF bgRef;
- pGetThemeColor(theme.handle(), partId, stateId, TMT_FILLCOLOR, &bgRef);
- fillColor = QBrush(qRgb(GetRValue(bgRef), GetGValue(bgRef), GetBValue(bgRef)));
- }
- }
- painter->fillRect(option->rect, fillColor);
- }
- }
- if (panel->lineWidth > 0)
- proxy()->drawPrimitive(PE_FrameLineEdit, panel, painter, widget);
- return;
- }
- break;
-
- case PE_FrameLineEdit:
- if (QWindowsVistaAnimation *anim = d->widgetAnimation(widget)) {
- anim->paint(painter, option);
- } else {
- QPainter *p = painter;
- QWidget *parentWidget = 0;
- if (widget) {
- parentWidget = widget->parentWidget();
- if (parentWidget)
- parentWidget = parentWidget->parentWidget();
- }
- if (widget && widget->inherits("QLineEdit")
- && parentWidget && parentWidget->inherits("QAbstractItemView")) {
- // we try to check if this lineedit is a delegate on a QAbstractItemView-derived class.
- QPen oldPen = p->pen();
- // Inner white border
- p->setPen(QPen(option->palette.base().color(), 1));
- p->drawRect(option->rect.adjusted(1, 1, -2, -2));
- // Outer dark border
- p->setPen(QPen(option->palette.shadow().color(), 1));
- p->drawRect(option->rect.adjusted(0, 0, -1, -1));
- p->setPen(oldPen);
- return;
- } else {
- int stateId = ETS_NORMAL;
- if (!(state & State_Enabled))
- stateId = ETS_DISABLED;
- else if (state & State_ReadOnly)
- stateId = ETS_READONLY;
- else if (state & State_MouseOver)
- stateId = ETS_HOT;
- else if (state & State_HasFocus)
- stateId = ETS_SELECTED;
- XPThemeData theme(widget, painter, QLatin1String("EDIT"), EP_EDITBORDER_NOSCROLL, stateId, option->rect);
- painter->save();
- QRegion clipRegion = option->rect;
- clipRegion -= option->rect.adjusted(2, 2, -2, -2);
- painter->setClipRegion(clipRegion);
- d->drawBackground(theme);
- painter->restore();
- }
- }
- break;
-
- case PE_IndicatorToolBarHandle:
- {
- XPThemeData theme;
- QRect rect;
- if (option->state & State_Horizontal) {
- theme = XPThemeData(widget, painter, QLatin1String("REBAR"), RP_GRIPPER, ETS_NORMAL, option->rect.adjusted(0, 1, -2, -2));
- rect = option->rect.adjusted(0, 1, 0, -2);
- rect.setWidth(4);
- } else {
- theme = XPThemeData(widget, painter, QLatin1String("REBAR"), RP_GRIPPERVERT, ETS_NORMAL, option->rect.adjusted(0, 1, -2, -2));
- rect = option->rect.adjusted(1, 0, -1, 0);
- rect.setHeight(4);
- }
- theme.rect = rect;
- d->drawBackground(theme);
- }
- break;
-
- case PE_IndicatorToolBarSeparator:
- {
- QPen pen = painter->pen();
- int margin = 3;
- painter->setPen(option->palette.background().color().darker(114));
- if (option->state & State_Horizontal) {
- int x1 = option->rect.center().x();
- painter->drawLine(QPoint(x1, option->rect.top() + margin), QPoint(x1, option->rect.bottom() - margin));
- } else {
- int y1 = option->rect.center().y();
- painter->drawLine(QPoint(option->rect.left() + margin, y1), QPoint(option->rect.right() - margin, y1));
- }
- painter->setPen(pen);
- }
- break;
-
- case PE_PanelTipLabel: {
- XPThemeData theme(widget, painter, QLatin1String("TOOLTIP"), TTP_STANDARD, TTSS_NORMAL, option->rect);
- d->drawBackground(theme);
- break;
- }
-
- case PE_PanelItemViewItem:
- {
- const QStyleOptionViewItemV4 *vopt;
- const QAbstractItemView *view = qobject_cast<const QAbstractItemView *>(widget);
- bool newStyle = true;
-
- if (qobject_cast<const QTableView*>(widget))
- newStyle = false;
-
- if (newStyle && view && (vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option))) {
- bool selected = vopt->state & QStyle::State_Selected;
- bool hover = vopt->state & QStyle::State_MouseOver;
- bool active = vopt->state & QStyle::State_Active;
-
- if (vopt->features & QStyleOptionViewItemV2::Alternate)
- painter->fillRect(vopt->rect, vopt->palette.alternateBase());
-
- QPalette::ColorGroup cg = vopt->state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
- if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
- cg = QPalette::Inactive;
-
- QRect textRect = subElementRect(QStyle::SE_ItemViewItemText, option, widget);
- QRect itemRect = subElementRect(QStyle::SE_ItemViewItemFocusRect, option, widget).adjusted(-1, 0, 1, 0);
- itemRect.setTop(vopt->rect.top());
- itemRect.setBottom(vopt->rect.bottom());
-
- QSize sectionSize = itemRect.size();
- if (vopt->showDecorationSelected)
- sectionSize = vopt->rect.size();
-
- if (view->selectionBehavior() == QAbstractItemView::SelectRows)
- sectionSize.setWidth(vopt->rect.width());
- if (view->selectionMode() == QAbstractItemView::NoSelection)
- hover = false;
- QPixmap pixmap;
-
- if (vopt->backgroundBrush.style() != Qt::NoBrush) {
- QPointF oldBO = painter->brushOrigin();
- painter->setBrushOrigin(vopt->rect.topLeft());
- painter->fillRect(vopt->rect, vopt->backgroundBrush);
- }
-
- if (hover || selected) {
- QString key = QString::fromLatin1("qvdelegate-%1-%2-%3-%4-%5").arg(sectionSize.width())
- .arg(sectionSize.height()).arg(selected).arg(active).arg(hover);
- if (!QPixmapCache::find(key, pixmap)) {
- pixmap = QPixmap(sectionSize);
- pixmap.fill(Qt::transparent);
-
- int state;
- if (selected && hover)
- state = LISS_HOTSELECTED;
- else if (selected && !active)
- state = LISS_SELECTEDNOTFOCUS;
- else if (selected)
- state = LISS_SELECTED;
- else
- state = LISS_HOT;
-
- QPainter pixmapPainter(&pixmap);
- XPThemeData theme(d->treeViewHelper(), &pixmapPainter, QLatin1String("TREEVIEW"),
- LVP_LISTITEM, state, QRect(0, 0, sectionSize.width(), sectionSize.height()));
- if (theme.isValid()) {
- d->drawBackground(theme);
- } else {
- QWindowsXPStyle::drawPrimitive(PE_PanelItemViewItem, option, painter, widget);
- break;;
- }
- QPixmapCache::insert(key, pixmap);
- }
-
- if (vopt->showDecorationSelected) {
- const int frame = 2; //Assumes a 2 pixel pixmap border
- QRect srcRect = QRect(0, 0, sectionSize.width(), sectionSize.height());
- QRect pixmapRect = vopt->rect;
- bool reverse = vopt->direction == Qt::RightToLeft;
- bool leftSection = vopt->viewItemPosition == QStyleOptionViewItemV4::Beginning;
- bool rightSection = vopt->viewItemPosition == QStyleOptionViewItemV4::End;
- if (vopt->viewItemPosition == QStyleOptionViewItemV4::OnlyOne
- || vopt->viewItemPosition == QStyleOptionViewItemV4::Invalid)
- painter->drawPixmap(pixmapRect.topLeft(), pixmap);
- else if (reverse ? rightSection : leftSection){
- painter->drawPixmap(QRect(pixmapRect.topLeft(),
- QSize(frame, pixmapRect.height())), pixmap,
- QRect(QPoint(0, 0), QSize(frame, pixmapRect.height())));
- painter->drawPixmap(pixmapRect.adjusted(frame, 0, 0, 0),
- pixmap, srcRect.adjusted(frame, 0, -frame, 0));
- } else if (reverse ? leftSection : rightSection) {
- painter->drawPixmap(QRect(pixmapRect.topRight() - QPoint(frame - 1, 0),
- QSize(frame, pixmapRect.height())), pixmap,
- QRect(QPoint(pixmapRect.width() - frame, 0),
- QSize(frame, pixmapRect.height())));
- painter->drawPixmap(pixmapRect.adjusted(0, 0, -frame, 0),
- pixmap, srcRect.adjusted(frame, 0, -frame, 0));
- } else if (vopt->viewItemPosition == QStyleOptionViewItemV4::Middle)
- painter->drawPixmap(pixmapRect, pixmap,
- srcRect.adjusted(frame, 0, -frame, 0));
- } else {
- if (vopt->text.isEmpty() && vopt->icon.isNull())
- break;
- painter->drawPixmap(itemRect.topLeft(), pixmap);
- }
- }
- } else {
- QWindowsXPStyle::drawPrimitive(element, option, painter, widget);
- }
- break;
- }
- case PE_Widget:
- {
- const QDialogButtonBox *buttonBox = 0;
-
- if (qobject_cast<const QMessageBox *> (widget))
- buttonBox = widget->findChild<const QDialogButtonBox *>(QLatin1String("qt_msgbox_buttonbox"));
-#ifndef QT_NO_INPUTDIALOG
- else if (qobject_cast<const QInputDialog *> (widget))
- buttonBox = widget->findChild<const QDialogButtonBox *>(QLatin1String("qt_inputdlg_buttonbox"));
-#endif // QT_NO_INPUTDIALOG
-
- if (buttonBox) {
- //draw white panel part
- XPThemeData theme(widget, painter, QLatin1String("TASKDIALOG"), TDLG_PRIMARYPANEL, 0, option->rect);
- QRect toprect = option->rect;
- toprect.setBottom(buttonBox->geometry().top());
- theme.rect = toprect;
- d->drawBackground(theme);
-
- //draw bottom panel part
- QRect buttonRect = option->rect;
- buttonRect.setTop(buttonBox->geometry().top());
- theme.rect = buttonRect;
- theme.partId = TDLG_SECONDARYPANEL;
- d->drawBackground(theme);
- }
- }
- break;
- default:
- QWindowsXPStyle::drawPrimitive(element, option, painter, widget);
- break;
- }
-}
-
-
-/*!
- \internal
-
- see drawPrimitive for comments on the animation support
- */
-void QWindowsVistaStyle::drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const
-{
- QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate*>(d_func());
-
- if (!QWindowsVistaStylePrivate::useVista()) {
- QWindowsStyle::drawControl(element, option, painter, widget);
- return;
- }
-
- bool selected = option->state & State_Selected;
- bool pressed = option->state & State_Sunken;
- bool disabled = !(option->state & State_Enabled);
-
- int state = option->state;
- QString name;
-
- QRect rect(option->rect);
- State flags = option->state;
- int partId = 0;
- int stateId = 0;
-
- QRect oldRect;
- QRect newRect;
-
- if (d->transitionsEnabled() && widget) {
- if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- if ((qobject_cast<const QPushButton*>(widget) && element == CE_PushButtonBevel))
- {
- QWidget *w = const_cast<QWidget *> (widget);
- int oldState = w->property("_q_stylestate").toInt();
- oldRect = w->property("_q_stylerect").toRect();
- newRect = w->rect();
- w->setProperty("_q_stylestate", (int)option->state);
- w->setProperty("_q_stylerect", w->rect());
-
- bool wasDefault = w->property("_q_isdefault").toBool();
- bool isDefault = button->features & QStyleOptionButton::DefaultButton;
- w->setProperty("_q_isdefault", isDefault);
-
- bool doTransition = ((state & State_Sunken) != (oldState & State_Sunken) ||
- (state & State_On) != (oldState & State_On) ||
- (state & State_MouseOver) != (oldState & State_MouseOver));
-
- if (oldRect != newRect || (wasDefault && !isDefault))
- {
- doTransition = false;
- d->stopAnimation(widget);
- }
-
- if (doTransition) {
- QImage startImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- QImage endImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- QWindowsVistaAnimation *anim = d->widgetAnimation(widget);
-
- QStyleOptionButton opt = *button;
- opt.state = (QStyle::State)oldState;
-
- startImage.fill(0);
- QWindowsVistaTransition *t = new QWindowsVistaTransition;
- t->setWidget(w);
- QPainter startPainter(&startImage);
-
- if (!anim) {
- proxy()->drawControl(element, &opt, &startPainter, 0 /* Intentional */);
- } else {
- anim->paint(&startPainter, &opt);
- d->stopAnimation(widget);
- }
-
- t->setStartImage(startImage);
- d->startAnimation(t);
-
- endImage.fill(0);
- QPainter endPainter(&endImage);
- proxy()->drawControl(element, option, &endPainter, 0 /* Intentional */);
- t->setEndImage(endImage);
- int duration = 0;
- HTHEME theme = pOpenThemeData(0, L"Button");
-
- int fromState = buttonStateId(oldState, BP_PUSHBUTTON);
- int toState = buttonStateId(option->state, BP_PUSHBUTTON);
- if (pGetThemeTransitionDuration(theme, BP_PUSHBUTTON, fromState, toState, TMT_TRANSITIONDURATIONS, &duration) == S_OK)
- t->setDuration(duration);
- else
- t->setDuration(0);
- t->setStartTime(QTime::currentTime());
- }
- }
- }
- }
- switch (element) {
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option))
- {
-
- if (QWindowsVistaAnimation *anim = d->widgetAnimation(widget)) {
- anim->paint(painter, option);
- } else {
- name = QLatin1String("BUTTON");
- partId = BP_PUSHBUTTON;
- if (btn->features & QStyleOptionButton::CommandLinkButton)
- partId = BP_COMMANDLINK;
- bool justFlat = (btn->features & QStyleOptionButton::Flat) && !(flags & (State_On|State_Sunken));
- if (!(flags & State_Enabled) && !(btn->features & QStyleOptionButton::Flat))
- stateId = PBS_DISABLED;
- else if (justFlat)
- ;
- else if (flags & (State_Sunken | State_On))
- stateId = PBS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = PBS_HOT;
- else if (btn->features & QStyleOptionButton::DefaultButton && (state & State_Active))
- stateId = PBS_DEFAULTED;
- else
- stateId = PBS_NORMAL;
-
- if (!justFlat) {
-
- if (widget && d->transitionsEnabled() && (btn->features & QStyleOptionButton::DefaultButton) &&
- !(state & (State_Sunken | State_On)) && !(state & State_MouseOver) &&
- (state & State_Enabled) && (state & State_Active))
- {
- QWindowsVistaAnimation *anim = d->widgetAnimation(widget);
- if (!anim && widget) {
- QImage startImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- startImage.fill(0);
- QImage alternateImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- alternateImage.fill(0);
-
- QWindowsVistaPulse *pulse = new QWindowsVistaPulse;
- pulse->setWidget(const_cast<QWidget*>(widget));
-
- QPainter startPainter(&startImage);
- stateId = PBS_DEFAULTED;
- XPThemeData theme(widget, &startPainter, name, partId, stateId, rect);
- d->drawBackground(theme);
-
- QPainter alternatePainter(&alternateImage);
- theme.stateId = PBS_DEFAULTED_ANIMATING;
- theme.painter = &alternatePainter;
- d->drawBackground(theme);
- pulse->setPrimaryImage(startImage);
- pulse->setAlternateImage(alternateImage);
- pulse->setStartTime(QTime::currentTime());
- pulse->setDuration(2000);
- d->startAnimation(pulse);
- anim = pulse;
- }
-
- if (anim)
- anim->paint(painter, option);
- else {
- XPThemeData theme(widget, painter, name, partId, stateId, rect);
- d->drawBackground(theme);
- }
- }
- else {
- d->stopAnimation(widget);
- XPThemeData theme(widget, painter, name, partId, stateId, rect);
- d->drawBackground(theme);
- }
- }
- }
- if (btn->features & QStyleOptionButton::HasMenu) {
- int mbiw = 0, mbih = 0;
- XPThemeData theme(widget, 0, QLatin1String("TOOLBAR"), TP_DROPDOWNBUTTON);
- if (theme.isValid()) {
- SIZE size;
- if (pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size) == S_OK) {
- mbiw = size.cx;
- mbih = size.cy;
- }
- }
- QRect ir = subElementRect(SE_PushButtonContents, option, 0);
- QStyleOptionButton newBtn = *btn;
- newBtn.rect = QStyle::visualRect(option->direction, option->rect,
- QRect(ir.right() - mbiw - 2,
- option->rect.top() + (option->rect.height()/2) - (mbih/2),
- mbiw + 1, mbih + 1));
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, painter, widget);
- }
- return;
- }
- break;
-#ifndef QT_NO_PROGRESSBAR
- case CE_ProgressBarContents:
- if (const QStyleOptionProgressBar *bar
- = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
- int stateId = MBI_NORMAL;
- if (disabled)
- stateId = MBI_DISABLED;
- bool isIndeterminate = (bar->minimum == 0 && bar->maximum == 0);
- bool vertical = false;
- bool inverted = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- vertical = (pb2->orientation == Qt::Vertical);
- inverted = pb2->invertedAppearance;
- }
-
- if (const QProgressBar *progressbar = qobject_cast<const QProgressBar *>(widget)) {
- if (((progressbar->value() > 0 && d->transitionsEnabled()) || isIndeterminate)) {
- if (!d->widgetAnimation(progressbar) && progressbar->value() < progressbar->maximum()) {
- QWindowsVistaAnimation *a = new QWindowsVistaAnimation;
- a->setWidget(const_cast<QWidget*>(widget));
- a->setStartTime(QTime::currentTime());
- d->startAnimation(a);
- }
- } else {
- d->stopAnimation(progressbar);
- }
- }
-
- XPThemeData theme(widget, painter, QLatin1String("PROGRESS"), vertical ? PP_FILLVERT : PP_FILL);
- theme.rect = option->rect;
- bool reverse = (bar->direction == Qt::LeftToRight && inverted) || (bar->direction == Qt::RightToLeft && !inverted);
- QTime current = QTime::currentTime();
-
- if (isIndeterminate) {
- if (QWindowsVistaAnimation *a = d->widgetAnimation(widget)) {
- int glowSize = 120;
- int animationWidth = glowSize * 2 + (vertical ? theme.rect.height() : theme.rect.width());
- int animOffset = a->startTime().msecsTo(current) / 4;
- if (animOffset > animationWidth)
- a->setStartTime(QTime::currentTime());
- painter->save();
- painter->setClipRect(theme.rect);
- QRect animRect;
- QSize pixmapSize(14, 14);
- if (vertical) {
- animRect = QRect(theme.rect.left(),
- inverted ? rect.top() - glowSize + animOffset :
- rect.bottom() + glowSize - animOffset,
- rect.width(), glowSize);
- pixmapSize.setHeight(animRect.height());
- } else {
- animRect = QRect(rect.left() - glowSize + animOffset,
- rect.top(), glowSize, rect.height());
- animRect = QStyle::visualRect(reverse ? Qt::RightToLeft : Qt::LeftToRight,
- option->rect, animRect);
- pixmapSize.setWidth(animRect.width());
- }
- QString name = QString::fromLatin1("qiprogress-%1-%2").arg(pixmapSize.width()).arg(pixmapSize.height());
- QPixmap pixmap;
- if (!QPixmapCache::find(name, pixmap)) {
- QImage image(pixmapSize, QImage::Format_ARGB32);
- image.fill(Qt::transparent);
- QPainter imagePainter(&image);
- theme.painter = &imagePainter;
- theme.partId = vertical ? PP_FILLVERT : PP_FILL;
- theme.rect = QRect(QPoint(0,0), theme.rect.size());
- QLinearGradient alphaGradient(0, 0, vertical ? 0 : image.width(),
- vertical ? image.height() : 0);
- alphaGradient.setColorAt(0, QColor(0, 0, 0, 0));
- alphaGradient.setColorAt(0.5, QColor(0, 0, 0, 220));
- alphaGradient.setColorAt(1, QColor(0, 0, 0, 0));
- imagePainter.fillRect(image.rect(), alphaGradient);
- imagePainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
- d->drawBackground(theme);
- imagePainter.end();
- pixmap = QPixmap::fromImage(image);
- QPixmapCache::insert(name, pixmap);
- }
- painter->drawPixmap(animRect, pixmap);
- painter->restore();
- }
- }
- else {
- qint64 progress = qMax<qint64>(bar->progress, bar->minimum); // workaround for bug in QProgressBar
-
- if (vertical) {
- int maxHeight = option->rect.height();
- int minHeight = 0;
- double vc6_workaround = ((progress - qint64(bar->minimum)) / qMax(double(1.0), double(qint64(bar->maximum) - qint64(bar->minimum))) * maxHeight);
- int height = isIndeterminate ? maxHeight: qMax(int(vc6_workaround), minHeight);
- theme.rect.setHeight(height);
- if (!inverted)
- theme.rect.moveTop(rect.height() - theme.rect.height());
- } else {
- int maxWidth = option->rect.width();
- int minWidth = 0;
- double vc6_workaround = ((progress - qint64(bar->minimum)) / qMax(double(1.0), double(qint64(bar->maximum) - qint64(bar->minimum))) * maxWidth);
- int width = isIndeterminate ? maxWidth : qMax(int(vc6_workaround), minWidth);
- theme.rect.setWidth(width);
- theme.rect = QStyle::visualRect(reverse ? Qt::RightToLeft : Qt::LeftToRight,
- option->rect, theme.rect);
- }
- d->drawBackground(theme);
-
- if (QWindowsVistaAnimation *a = d->widgetAnimation(widget)) {
- int glowSize = 140;
- int animationWidth = glowSize * 2 + (vertical ? theme.rect.height() : theme.rect.width());
- int animOffset = a->startTime().msecsTo(current) / 4;
- theme.partId = vertical ? PP_MOVEOVERLAYVERT : PP_MOVEOVERLAY;
- if (animOffset > animationWidth) {
- if (bar->progress < bar->maximum)
- a->setStartTime(QTime::currentTime());
- else
- d->stopAnimation(widget); //we stop the glow motion only after it has
- //moved out of view
- }
- painter->save();
- painter->setClipRect(theme.rect);
- if (vertical) {
- theme.rect = QRect(theme.rect.left(),
- inverted ? rect.top() - glowSize + animOffset :
- rect.bottom() + glowSize - animOffset,
- rect.width(), glowSize);
- } else {
- theme.rect = QRect(rect.left() - glowSize + animOffset,rect.top(), glowSize, rect.height());
- theme.rect = QStyle::visualRect(reverse ? Qt::RightToLeft : Qt::LeftToRight, option->rect, theme.rect);
- }
- d->drawBackground(theme);
- painter->restore();
- }
- }
- }
- break;
-#endif // QT_NO_PROGRESSBAR
- case CE_MenuBarItem:
- {
-
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option))
- {
- if (mbi->menuItemType == QStyleOptionMenuItem::DefaultItem)
- break;
-
- QPalette::ColorRole textRole = disabled ? QPalette::Text : QPalette::ButtonText;
- QPixmap pix = mbi->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), QIcon::Normal);
-
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!proxy()->styleHint(SH_UnderlineShortcut, mbi, widget))
- alignment |= Qt::TextHideMnemonic;
-
- //The rect adjustment is a workaround for the menu not really filling its background.
- XPThemeData theme(widget, painter, QLatin1String("MENU"), MENU_BARBACKGROUND, 0, option->rect.adjusted(-1, 0, 2, 1));
- d->drawBackground(theme);
-
- int stateId = MBI_NORMAL;
- if (disabled)
- stateId = MBI_DISABLED;
- else if (pressed)
- stateId = MBI_PUSHED;
- else if (selected)
- stateId = MBI_HOT;
-
- XPThemeData theme2(widget, painter, QLatin1String("MENU"), MENU_BARITEM, stateId, option->rect);
- d->drawBackground(theme2);
-
- if (!pix.isNull())
- drawItemPixmap(painter, mbi->rect, alignment, pix);
- else
- drawItemText(painter, mbi->rect, alignment, mbi->palette, mbi->state & State_Enabled, mbi->text, textRole);
- }
- }
- break;
-#ifndef QT_NO_MENU
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- // windows always has a check column, regardless whether we have an icon or not
- int checkcol = 28;
- {
- SIZE size;
- MARGINS margins;
- XPThemeData theme(widget, 0, QLatin1String("MENU"), MENU_POPUPCHECKBACKGROUND, MBI_HOT);
- pGetThemePartSize(theme.handle(), NULL, MENU_POPUPCHECK, 0, NULL,TS_TRUE, &size);
- pGetThemeMargins(theme.handle(), NULL, MENU_POPUPCHECK, 0, TMT_CONTENTMARGINS, NULL, &margins);
- checkcol = qMax(menuitem->maxIconWidth, int(6 + size.cx + margins.cxLeftWidth + margins.cxRightWidth));
- }
- QColor darkLine = option->palette.background().color().darker(108);
- QColor lightLine = option->palette.background().color().lighter(107);
- QRect rect = option->rect;
- QStyleOptionMenuItem mbiCopy = *menuitem;
-
- //draw vertical menu line
- QPoint p1 = QStyle::visualPos(option->direction, menuitem->rect, QPoint(checkcol, rect.top()));
- QPoint p2 = QStyle::visualPos(option->direction, menuitem->rect, QPoint(checkcol, rect.bottom()));
- QRect gutterRect(p1.x(), p1.y(), 3, p2.y() - p1.y() + 1);
- XPThemeData theme2(widget, painter, QLatin1String("MENU"), MENU_POPUPGUTTER, stateId, gutterRect);
- d->drawBackground(theme2);
-
- int x, y, w, h;
- menuitem->rect.getRect(&x, &y, &w, &h);
- int tab = menuitem->tabWidth;
- bool dis = !(menuitem->state & State_Enabled);
- bool checked = menuitem->checkType != QStyleOptionMenuItem::NotCheckable
- ? menuitem->checked : false;
- bool act = menuitem->state & State_Selected;
-
- if (menuitem->menuItemType == QStyleOptionMenuItem::Separator) {
- int yoff = y-2 + h / 2;
- QPoint p1 = QPoint(x + checkcol, yoff);
- QPoint p2 = QPoint(x + w + 6 , yoff);
- stateId = MBI_HOT;
- QRect subRect(p1.x(), p1.y(), p2.x() - p1.x(), 6);
- subRect = QStyle::visualRect(option->direction, option->rect, subRect );
- XPThemeData theme2(widget, painter, QLatin1String("MENU"), MENU_POPUPSEPARATOR, stateId, subRect);
- d->drawBackground(theme2);
- return;
- }
-
- QRect vCheckRect = visualRect(option->direction, menuitem->rect, QRect(menuitem->rect.x(),
- menuitem->rect.y(), checkcol - 6, menuitem->rect.height()));
-
- if (act) {
- stateId = MBI_HOT;
- XPThemeData theme2(widget, painter, QLatin1String("MENU"), MENU_POPUPITEM, stateId, option->rect);
- d->drawBackground(theme2);
- }
-
- if (checked) {
- XPThemeData theme(widget, painter, QLatin1String("MENU"), MENU_POPUPCHECKBACKGROUND,
- menuitem->icon.isNull() ? MBI_HOT : MBI_PUSHED, vCheckRect);
- SIZE size;
- MARGINS margins;
- pGetThemePartSize(theme.handle(), NULL, MENU_POPUPCHECK, 0, NULL,TS_TRUE, &size);
- pGetThemeMargins(theme.handle(), NULL, MENU_POPUPCHECK, 0,
- TMT_CONTENTMARGINS, NULL, &margins);
- QRect checkRect(0, 0, size.cx + margins.cxLeftWidth + margins.cxRightWidth ,
- size.cy + margins.cyBottomHeight + margins.cyTopHeight);
- checkRect.moveCenter(vCheckRect.center());
- theme.rect = checkRect;
-
- d->drawBackground(theme);
-
- if (menuitem->icon.isNull()) {
- checkRect = QRect(0, 0, size.cx, size.cy);
- checkRect.moveCenter(theme.rect.center());
- theme.rect = checkRect;
-
- theme.partId = MENU_POPUPCHECK;
- bool bullet = menuitem->checkType & QStyleOptionMenuItem::Exclusive;
- if (dis)
- theme.stateId = bullet ? MC_BULLETDISABLED: MC_CHECKMARKDISABLED;
- else
- theme.stateId = bullet ? MC_BULLETNORMAL: MC_CHECKMARKNORMAL;
- d->drawBackground(theme);
- }
- }
-
- if (!menuitem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap;
- if (checked)
- pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), mode, QIcon::On);
- else
- pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- QRect pmr(0, 0, pixw, pixh);
- pmr.moveCenter(vCheckRect.center());
- painter->setPen(menuitem->palette.text().color());
- painter->drawPixmap(pmr.topLeft(), pixmap);
- }
-
- painter->setPen(menuitem->palette.buttonText().color());
-
- QColor discol;
- if (dis) {
- discol = menuitem->palette.text().color();
- painter->setPen(discol);
- }
-
- int xm = windowsItemFrame + checkcol + windowsItemHMargin;
- int xpos = menuitem->rect.x() + xm;
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(option->direction, menuitem->rect, textRect);
- QString s = menuitem->text;
- if (!s.isEmpty()) { // draw text
- painter->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
- text_flags |= Qt::AlignLeft;
- if (t >= 0) {
- QRect vShortcutRect = visualRect(option->direction, menuitem->rect,
- QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
- painter->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- QFont font = menuitem->font;
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
- painter->setFont(font);
- painter->setPen(discol);
- painter->drawText(vTextRect, text_flags, s.left(t));
- painter->restore();
- }
- if (menuitem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
- int dim = (h - 2 * windowsItemFrame) / 2;
- PrimitiveElement arrow;
- arrow = (option->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- xpos = x + w - windowsArrowHMargin - windowsItemFrame - dim;
- QRect vSubMenuRect = visualRect(option->direction, menuitem->rect, QRect(xpos, y + h / 2 - dim / 2, dim, dim));
- QStyleOptionMenuItem newMI = *menuitem;
- newMI.rect = vSubMenuRect;
- newMI.state = dis ? State_None : State_Enabled;
- proxy()->drawPrimitive(arrow, &newMI, painter, widget);
- }
- }
- break;
-#endif // QT_NO_MENU
- case CE_HeaderSection:
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- name = QLatin1String("HEADER");
- partId = HP_HEADERITEM;
- if (flags & State_Sunken)
- stateId = HIS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = HIS_HOT;
- else
- stateId = HIS_NORMAL;
-
- if (header->sortIndicator != QStyleOptionHeader::None)
- stateId += 3;
-
- XPThemeData theme(widget, painter, name, partId, stateId, option->rect);
- d->drawBackground(theme);
- }
- break;
- case CE_MenuBarEmptyArea:
- {
- stateId = MBI_NORMAL;
- if (!(state & State_Enabled))
- stateId = MBI_DISABLED;
- XPThemeData theme(widget, painter, QLatin1String("MENU"), MENU_BARBACKGROUND, stateId, option->rect);
- d->drawBackground(theme);
- }
- break;
- case CE_ToolBar:
- if (const QStyleOptionToolBar *toolbar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
- QPalette pal = option->palette;
- pal.setColor(QPalette::Dark, option->palette.background().color().darker(130));
- QStyleOptionToolBar copyOpt = *toolbar;
- copyOpt.palette = pal;
- QWindowsStyle::drawControl(element, &copyOpt, painter, widget);
- }
- break;
- case CE_DockWidgetTitle:
- if (const QDockWidget *dockWidget = qobject_cast<const QDockWidget *>(widget)) {
- QRect rect = option->rect;
- if (dockWidget->isFloating()) {
- QWindowsXPStyle::drawControl(element, option, painter, widget);
- break; //otherwise fall through
- }
-
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(option)) {
-
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- if (verticalTitleBar) {
- QSize s = rect.size();
- s.transpose();
- rect.setSize(s);
-
- painter->translate(rect.left() - 1, rect.top() + rect.width());
- painter->rotate(-90);
- painter->translate(-rect.left() + 1, -rect.top());
- }
-
- painter->setBrush(option->palette.background().color().darker(110));
- painter->setPen(option->palette.background().color().darker(130));
- painter->drawRect(rect.adjusted(0, 1, -1, -3));
-
- int buttonMargin = 4;
- int mw = proxy()->pixelMetric(QStyle::PM_DockWidgetTitleMargin, dwOpt, widget);
- int fw = proxy()->pixelMetric(PM_DockWidgetFrameWidth, dwOpt, widget);
- const QDockWidget *dw = qobject_cast<const QDockWidget *>(widget);
- bool isFloating = dw != 0 && dw->isFloating();
-
- QRect r = option->rect.adjusted(0, 2, -1, -3);
- QRect titleRect = r;
-
- if (dwOpt->closable) {
- QSize sz = standardIcon(QStyle::SP_TitleBarCloseButton, dwOpt, widget).actualSize(QSize(10, 10));
- titleRect.adjust(0, 0, -sz.width() - mw - buttonMargin, 0);
- }
-
- if (dwOpt->floatable) {
- QSize sz = standardIcon(QStyle::SP_TitleBarMaxButton, dwOpt, widget).actualSize(QSize(10, 10));
- titleRect.adjust(0, 0, -sz.width() - mw - buttonMargin, 0);
- }
-
- if (isFloating) {
- titleRect.adjust(0, -fw, 0, 0);
- if (widget != 0 && widget->windowIcon().cacheKey() != QApplication::windowIcon().cacheKey())
- titleRect.adjust(titleRect.height() + mw, 0, 0, 0);
- } else {
- titleRect.adjust(mw, 0, 0, 0);
- if (!dwOpt->floatable && !dwOpt->closable)
- titleRect.adjust(0, 0, -mw, 0);
- }
- if (!verticalTitleBar)
- titleRect = visualRect(dwOpt->direction, r, titleRect);
-
- if (!dwOpt->title.isEmpty()) {
- QString titleText = painter->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight,
- verticalTitleBar ? titleRect.height() : titleRect.width());
- const int indent = painter->fontMetrics().descent();
- drawItemText(painter, rect.adjusted(indent + 1, 1, -indent - 1, -1),
- Qt::AlignLeft | Qt::AlignVCenter, dwOpt->palette,
- dwOpt->state & State_Enabled, titleText,
- QPalette::WindowText);
- }
- }
- break;
- }
-#ifndef QT_NO_ITEMVIEWS
- case CE_ItemViewItem:
- {
- const QStyleOptionViewItemV4 *vopt;
- const QAbstractItemView *view = qobject_cast<const QAbstractItemView *>(widget);
- bool newStyle = true;
-
- if (qobject_cast<const QTableView*>(widget))
- newStyle = false;
-
- if (newStyle && view && (vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option))) {
- /*
- // We cannot currently get the correct selection color for "explorer style" views
- COLORREF cref = 0;
- XPThemeData theme(d->treeViewHelper(), 0, QLatin1String("LISTVIEW"), 0, 0);
- unsigned int res = pGetThemeColor(theme.handle(), LVP_LISTITEM, LISS_SELECTED, TMT_TEXTCOLOR, &cref);
- QColor textColor(GetRValue(cref), GetGValue(cref), GetBValue(cref));
- */
- QPalette palette = vopt->palette;
- palette.setColor(QPalette::All, QPalette::HighlightedText, palette.color(QPalette::Active, QPalette::Text));
- // Note that setting a saturated color here results in ugly XOR colors in the focus rect
- palette.setColor(QPalette::All, QPalette::Highlight, palette.base().color().darker(108));
- QStyleOptionViewItemV4 adjustedOption = *vopt;
- adjustedOption.palette = palette;
- // We hide the focusrect in singleselection as it is not required
- if ((view->selectionMode() == QAbstractItemView::SingleSelection)
- && !(vopt->state & State_KeyboardFocusChange))
- adjustedOption.state &= ~State_HasFocus;
- QWindowsXPStyle::drawControl(element, &adjustedOption, painter, widget);
- } else {
- QWindowsXPStyle::drawControl(element, option, painter, widget);
- }
- break;
- }
-#endif // QT_NO_ITEMVIEWS
-
- default:
- QWindowsXPStyle::drawControl(element, option, painter, widget);
- break;
- }
-}
-
-/*!
- \internal
-
- see drawPrimitive for comments on the animation support
-
- */
-void QWindowsVistaStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const
-{
- QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate*>(d_func());
- if (!QWindowsVistaStylePrivate::useVista()) {
- QWindowsStyle::drawComplexControl(control, option, painter, widget);
- return;
- }
-
- State state = option->state;
- SubControls sub = option->subControls;
- QRect r = option->rect;
-
- int partId = 0;
- int stateId = 0;
-
- State flags = option->state;
- if (widget && widget->testAttribute(Qt::WA_UnderMouse) && widget->isActiveWindow())
- flags |= State_MouseOver;
-
- if (d->transitionsEnabled() && widget) {
- if ((qobject_cast<const QScrollBar *>(widget) && control == CC_ScrollBar)
-#ifndef QT_NO_SPINBOX
- || (qobject_cast<const QAbstractSpinBox*>(widget) && control == CC_SpinBox)
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_COMBOBOX
- || (qobject_cast<const QComboBox*>(widget) && control == CC_ComboBox)
-#endif // QT_NO_COMBOBOX
- )
- {
- QWidget *w = const_cast<QWidget *> (widget);
-
- int oldState = w->property("_q_stylestate").toInt();
- int oldActiveControls = w->property("_q_stylecontrols").toInt();
- QRect oldRect = w->property("_q_stylerect").toRect();
- w->setProperty("_q_stylestate", (int)option->state);
- w->setProperty("_q_stylecontrols", (int)option->activeSubControls);
- w->setProperty("_q_stylerect", w->rect());
-
- bool doTransition = ((state & State_Sunken) != (oldState & State_Sunken) ||
- (state & State_On) != (oldState & State_On) ||
- (state & State_MouseOver) != (oldState & State_MouseOver) ||
- oldActiveControls != option->activeSubControls);
-
-
- if (qstyleoption_cast<const QStyleOptionSlider *>(option)) {
- QRect oldSliderPos = w->property("_q_stylesliderpos").toRect();
- QRect currentPos = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- w->setProperty("_q_stylesliderpos", currentPos);
- if (oldSliderPos != currentPos) {
- doTransition = false;
- d->stopAnimation(widget);
- }
- } else if (control == CC_SpinBox) {
- //spinboxes have a transition when focus changes
- if (!doTransition)
- doTransition = (state & State_HasFocus) != (oldState & State_HasFocus);
- }
-
- if (oldRect != option->rect) {
- doTransition = false;
- d->stopAnimation(widget);
- }
-
- if (doTransition) {
- QImage startImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- QImage endImage(option->rect.size(), QImage::Format_ARGB32_Premultiplied);
- QWindowsVistaAnimation *anim = d->widgetAnimation(widget);
- QWindowsVistaTransition *t = new QWindowsVistaTransition;
- t->setWidget(w);
- if (!anim) {
- if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox*>(option)) {
- //Combo boxes are special cased to avoid cleartype issues
- startImage.fill(0);
- QPainter startPainter(&startImage);
- QStyleOptionComboBox startCombo = *combo;
- startCombo.state = (QStyle::State)oldState;
- startCombo.activeSubControls = (QStyle::SubControl)oldActiveControls;
- proxy()->drawComplexControl(control, &startCombo, &startPainter, 0 /* Intentional */);
- t->setStartImage(startImage);
- } else if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider*>(option)) {
- //This is a workaround for the direct3d engine as it currently has some issues with grabWindow
- startImage.fill(0);
- QPainter startPainter(&startImage);
- QStyleOptionSlider startSlider = *slider;
- startSlider.state = (QStyle::State)oldState;
- startSlider.activeSubControls = (QStyle::SubControl)oldActiveControls;
- proxy()->drawComplexControl(control, &startSlider, &startPainter, 0 /* Intentional */);
- t->setStartImage(startImage);
- } else {
- QPoint offset(0, 0);
- if (!widget->internalWinId())
- offset = widget->mapTo(widget->nativeParentWidget(), offset);
- t->setStartImage(QPixmap::grabWindow(widget->effectiveWinId(), offset.x(), offset.y(),
- option->rect.width(), option->rect.height()).toImage());
- }
- } else {
- startImage.fill(0);
- QPainter startPainter(&startImage);
- anim->paint(&startPainter, option);
- t->setStartImage(startImage);
- }
- d->startAnimation(t);
- endImage.fill(0);
- QPainter endPainter(&endImage);
- proxy()->drawComplexControl(control, option, &endPainter, 0 /* Intentional */);
- t->setEndImage(endImage);
- t->setStartTime(QTime::currentTime());
-
- if (option->state & State_MouseOver || option->state & State_Sunken)
- t->setDuration(150);
- else
- t->setDuration(500);
- }
-
- if (QWindowsVistaAnimation *anim = d->widgetAnimation(widget)) {
- anim->paint(painter, option);
- return;
- }
-
- }
- }
-
- switch (control) {
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option))
- {
- if (cmb->editable) {
- if (sub & SC_ComboBoxEditField) {
- partId = EP_EDITBORDER_NOSCROLL;
- if (!(flags & State_Enabled))
- stateId = ETS_DISABLED;
- else if (flags & State_MouseOver)
- stateId = ETS_HOT;
- else if (flags & State_HasFocus)
- stateId = ETS_FOCUSED;
- else
- stateId = ETS_NORMAL;
-
- XPThemeData theme(widget, painter, QLatin1String("EDIT"), partId, stateId, r);
-
- d->drawBackground(theme);
- }
- if (sub & SC_ComboBoxArrow) {
- QRect subRect = proxy()->subControlRect(CC_ComboBox, option, SC_ComboBoxArrow, widget);
- XPThemeData theme(widget, painter, QLatin1String("COMBOBOX"));
- theme.rect = subRect;
- partId = option->direction == Qt::RightToLeft ? CP_DROPDOWNBUTTONLEFT : CP_DROPDOWNBUTTONRIGHT;
-
- if (!(cmb->state & State_Enabled))
- stateId = CBXS_DISABLED;
- else if (cmb->state & State_Sunken || cmb->state & State_On)
- stateId = CBXS_PRESSED;
- else if (cmb->state & State_MouseOver && option->activeSubControls & SC_ComboBoxArrow)
- stateId = CBXS_HOT;
- else
- stateId = CBXS_NORMAL;
-
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
-
- } else {
- if (sub & SC_ComboBoxFrame) {
- QStyleOptionButton btn;
- btn.QStyleOption::operator=(*option);
- btn.rect = option->rect.adjusted(-1, -1, 1, 1);
- if (sub & SC_ComboBoxArrow)
- btn.features = QStyleOptionButton::HasMenu;
- proxy()->drawControl(QStyle::CE_PushButton, &btn, painter, widget);
- }
- }
- }
- break;
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(option))
- {
- XPThemeData theme(widget, painter, QLatin1String("SCROLLBAR"));
-
- bool maxedOut = (scrollbar->maximum == scrollbar->minimum);
- if (maxedOut)
- flags &= ~State_Enabled;
-
- bool isHorz = flags & State_Horizontal;
- bool isRTL = option->direction == Qt::RightToLeft;
- if (sub & SC_ScrollBarAddLine) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarAddLine, widget);
- partId = SBP_ARROWBTN;
- if (!(flags & State_Enabled))
- stateId = (isHorz ? (isRTL ? ABS_LEFTDISABLED : ABS_RIGHTDISABLED) : ABS_DOWNDISABLED);
- else if (scrollbar->activeSubControls & SC_ScrollBarAddLine && (scrollbar->state & State_Sunken))
- stateId = (isHorz ? (isRTL ? ABS_LEFTPRESSED : ABS_RIGHTPRESSED) : ABS_DOWNPRESSED);
- else if (scrollbar->activeSubControls & SC_ScrollBarAddLine && (scrollbar->state & State_MouseOver))
- stateId = (isHorz ? (isRTL ? ABS_LEFTHOT : ABS_RIGHTHOT) : ABS_DOWNHOT);
- else if (scrollbar->state & State_MouseOver)
- stateId = (isHorz ? (isRTL ? ABS_LEFTHOVER : ABS_RIGHTHOVER) : ABS_DOWNHOVER);
- else
- stateId = (isHorz ? (isRTL ? ABS_LEFTNORMAL : ABS_RIGHTNORMAL) : ABS_DOWNNORMAL);
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_ScrollBarSubLine) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSubLine, widget);
- partId = SBP_ARROWBTN;
- if (!(flags & State_Enabled))
- stateId = (isHorz ? (isRTL ? ABS_RIGHTDISABLED : ABS_LEFTDISABLED) : ABS_UPDISABLED);
- else if (scrollbar->activeSubControls & SC_ScrollBarSubLine && (scrollbar->state & State_Sunken))
- stateId = (isHorz ? (isRTL ? ABS_RIGHTPRESSED : ABS_LEFTPRESSED) : ABS_UPPRESSED);
- else if (scrollbar->activeSubControls & SC_ScrollBarSubLine && (scrollbar->state & State_MouseOver))
- stateId = (isHorz ? (isRTL ? ABS_RIGHTHOT : ABS_LEFTHOT) : ABS_UPHOT);
- else if (scrollbar->state & State_MouseOver)
- stateId = (isHorz ? (isRTL ? ABS_RIGHTHOVER : ABS_LEFTHOVER) : ABS_UPHOVER);
- else
- stateId = (isHorz ? (isRTL ? ABS_RIGHTNORMAL : ABS_LEFTNORMAL) : ABS_UPNORMAL);
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (maxedOut) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- theme.rect = theme.rect.united(proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSubPage, widget));
- theme.rect = theme.rect.united(proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarAddPage, widget));
- partId = flags & State_Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT;
- stateId = SCRBS_DISABLED;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- } else {
- if (sub & SC_ScrollBarSubPage) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSubPage, widget);
- partId = flags & State_Horizontal ? SBP_UPPERTRACKHORZ : SBP_UPPERTRACKVERT;
- if (!(flags & State_Enabled))
- stateId = SCRBS_DISABLED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSubPage && (scrollbar->state & State_Sunken))
- stateId = SCRBS_PRESSED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSubPage && (scrollbar->state & State_MouseOver))
- stateId = SCRBS_HOT;
- else
- stateId = SCRBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_ScrollBarAddPage) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarAddPage, widget);
- partId = flags & State_Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT;
- if (!(flags & State_Enabled))
- stateId = SCRBS_DISABLED;
- else if (scrollbar->activeSubControls & SC_ScrollBarAddPage && (scrollbar->state & State_Sunken))
- stateId = SCRBS_PRESSED;
- else if (scrollbar->activeSubControls & SC_ScrollBarAddPage && (scrollbar->state & State_MouseOver))
- stateId = SCRBS_HOT;
- else
- stateId = SCRBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_ScrollBarSlider) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- if (!(flags & State_Enabled))
- stateId = SCRBS_DISABLED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSlider && (scrollbar->state & State_Sunken))
- stateId = SCRBS_PRESSED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSlider && (scrollbar->state & State_MouseOver))
- stateId = SCRBS_HOT;
- else if (option->state & State_MouseOver)
- stateId = SCRBS_HOVER;
- else
- stateId = SCRBS_NORMAL;
-
- // Draw handle
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- theme.partId = flags & State_Horizontal ? SBP_THUMBBTNHORZ : SBP_THUMBBTNVERT;
- theme.stateId = stateId;
- d->drawBackground(theme);
-
- // Calculate rect of gripper
- const int swidth = theme.rect.width();
- const int sheight = theme.rect.height();
-
- MARGINS contentsMargin;
- RECT rect = theme.toRECT(theme.rect);
- pGetThemeMargins(theme.handle(), 0, theme.partId, theme.stateId, TMT_SIZINGMARGINS, &rect, &contentsMargin);
-
- SIZE size;
- theme.partId = flags & State_Horizontal ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- int gw = size.cx, gh = size.cy;
-
-
- QRect gripperBounds;
- if (flags & State_Horizontal && ((swidth - contentsMargin.cxLeftWidth - contentsMargin.cxRightWidth) > gw)) {
- gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2);
- gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2);
- gripperBounds.setWidth(gw);
- gripperBounds.setHeight(gh);
- } else if ((sheight - contentsMargin.cyTopHeight - contentsMargin.cyBottomHeight) > gh) {
- gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2);
- gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2);
- gripperBounds.setWidth(gw);
- gripperBounds.setHeight(gh);
- }
-
- // Draw gripper if there is enough space
- if (!gripperBounds.isEmpty() && flags & State_Enabled) {
- painter->save();
- XPThemeData grippBackground = theme;
- grippBackground.partId = flags & State_Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT;
- theme.rect = gripperBounds;
- painter->setClipRegion(d->region(theme));// Only change inside the region of the gripper
- d->drawBackground(grippBackground);// The gutter is the grippers background
- d->drawBackground(theme); // Transparent gripper ontop of background
- painter->restore();
- }
- }
- }
- }
- break;
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(option))
- {
- XPThemeData theme(widget, painter, QLatin1String("SPIN"));
- if (sb->frame && (sub & SC_SpinBoxFrame)) {
- partId = EP_EDITBORDER_NOSCROLL;
- if (!(flags & State_Enabled))
- stateId = ETS_DISABLED;
- else if (flags & State_MouseOver)
- stateId = ETS_HOT;
- else if (flags & State_HasFocus)
- stateId = ETS_SELECTED;
- else
- stateId = ETS_NORMAL;
-
- XPThemeData ftheme(widget, painter, QLatin1String("EDIT"), partId, stateId, r);
- ftheme.noContent = true;
- d->drawBackground(ftheme);
- }
- if (sub & SC_SpinBoxUp) {
- theme.rect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxUp, widget).adjusted(0, 0, 0, 1);
- partId = SPNP_UP;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepUpEnabled) || !(flags & State_Enabled))
- stateId = UPS_DISABLED;
- else if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_Sunken))
- stateId = UPS_PRESSED;
- else if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_MouseOver))
- stateId = UPS_HOT;
- else
- stateId = UPS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_SpinBoxDown) {
- theme.rect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxDown, widget);
- partId = SPNP_DOWN;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepDownEnabled) || !(flags & State_Enabled))
- stateId = DNS_DISABLED;
- else if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_Sunken))
- stateId = DNS_PRESSED;
- else if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_MouseOver))
- stateId = DNS_HOT;
- else
- stateId = DNS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- }
- break;
-#endif // QT_NO_SPINBOX
- default:
- QWindowsXPStyle::drawComplexControl(control, option, painter, widget);
- break;
- }
-}
-
-/*!
- \internal
- */
-QSize QWindowsVistaStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista())
- return QWindowsStyle::sizeFromContents(type, option, size, widget);
-
- QSize sz(size);
- switch (type) {
- case CT_MenuItem:
- sz = QWindowsXPStyle::sizeFromContents(type, option, size, widget);
- int minimumHeight;
- {
- SIZE size;
- MARGINS margins;
- XPThemeData theme(widget, 0, QLatin1String("MENU"), MENU_POPUPCHECKBACKGROUND, MBI_HOT);
- pGetThemePartSize(theme.handle(), NULL, MENU_POPUPCHECK, 0, NULL,TS_TRUE, &size);
- pGetThemeMargins(theme.handle(), NULL, MENU_POPUPCHECK, 0, TMT_CONTENTMARGINS, NULL, &margins);
- minimumHeight = qMax<qint32>(size.cy + margins.cyBottomHeight+ margins.cyTopHeight, sz.height());
- sz.rwidth() += size.cx + margins.cxLeftWidth + margins.cxRightWidth;
- }
-
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- if (menuitem->menuItemType != QStyleOptionMenuItem::Separator)
- sz.setHeight(minimumHeight);
- }
- return sz;
-#ifndef QT_NO_MENUBAR
- case CT_MenuBarItem:
- if (!sz.isEmpty())
- sz += QSize(windowsItemHMargin * 5 + 1, 5);
- return sz;
- break;
-#endif
- case CT_ItemViewItem:
- sz = QWindowsXPStyle::sizeFromContents(type, option, size, widget);
- sz.rheight() += 2;
- return sz;
- case CT_SpinBox:
- {
- //Spinbox adds frame twice
- sz = QWindowsStyle::sizeFromContents(type, option, size, widget);
- int border = proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget);
- sz -= QSize(2*border, 2*border);
- }
- return sz;
- default:
- break;
- }
- return QWindowsXPStyle::sizeFromContents(type, option, size, widget);
-}
-
-/*!
- \internal
- */
-QRect QWindowsVistaStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista())
- return QWindowsStyle::subElementRect(element, option, widget);
-
- QRect rect = QWindowsXPStyle::subElementRect(element, option, widget);
- switch (element) {
-
- case SE_PushButtonContents:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- MARGINS borderSize;
- HTHEME theme = pOpenThemeData(widget ? QWindowsVistaStylePrivate::winId(widget) : 0, L"Button");
- if (theme) {
- int stateId = PBS_NORMAL;
- if (!(option->state & State_Enabled))
- stateId = PBS_DISABLED;
- else if (option->state & State_Sunken)
- stateId = PBS_PRESSED;
- else if (option->state & State_MouseOver)
- stateId = PBS_HOT;
- else if (btn->features & QStyleOptionButton::DefaultButton)
- stateId = PBS_DEFAULTED;
-
- int border = proxy()->pixelMetric(PM_DefaultFrameWidth, btn, widget);
- rect = option->rect.adjusted(border, border, -border, -border);
-
- int result = pGetThemeMargins(theme,
- NULL,
- BP_PUSHBUTTON,
- stateId,
- TMT_CONTENTMARGINS,
- NULL,
- &borderSize);
-
- if (result == S_OK) {
- rect.adjust(borderSize.cxLeftWidth, borderSize.cyTopHeight,
- -borderSize.cxRightWidth, -borderSize.cyBottomHeight);
- rect = visualRect(option->direction, option->rect, rect);
- }
- }
- }
- break;
-
- case SE_HeaderArrow:
- {
- QRect r = rect;
- int h = option->rect.height();
- int w = option->rect.width();
- int x = option->rect.x();
- int y = option->rect.y();
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, option, widget);
-
- XPThemeData theme(widget, 0, QLatin1String("HEADER"), HP_HEADERSORTARROW, HSAS_SORTEDDOWN, option->rect);
-
- int arrowWidth = 13;
- int arrowHeight = 5;
- if (theme.isValid()) {
- SIZE size;
- if (pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size) == S_OK) {
- arrowWidth = size.cx;
- arrowHeight = size.cy;
- }
- }
- if (option->state & State_Horizontal) {
- r.setRect(x + w/2 - arrowWidth/2, y , arrowWidth, arrowHeight);
- } else {
- int vert_size = w / 2;
- r.setRect(x + 5, y + h - margin * 2 - vert_size,
- w - margin * 2 - 5, vert_size);
- }
- rect = visualRect(option->direction, option->rect, r);
- }
- break;
-
- case SE_HeaderLabel:
- {
- int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, option, widget);
- QRect r = option->rect;
- r.setRect(option->rect.x() + margin, option->rect.y() + margin,
- option->rect.width() - margin * 2, option->rect.height() - margin * 2);
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- // Subtract width needed for arrow, if there is one
- if (header->sortIndicator != QStyleOptionHeader::None) {
- if (!(option->state & State_Horizontal)) //horizontal arrows are positioned on top
- r.setHeight(r.height() - (option->rect.width() / 2) - (margin * 2));
- }
- }
- rect = visualRect(option->direction, option->rect, r);
- }
- break;
- case SE_ProgressBarContents:
- rect = QCommonStyle::subElementRect(SE_ProgressBarGroove, option, widget);
- break;
- case SE_ItemViewItemDecoration:
- if (qstyleoption_cast<const QStyleOptionViewItemV4 *>(option))
- rect.adjust(-2, 0, 2, 0);
- break;
- case SE_ItemViewItemFocusRect:
- if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(option)) {
- QRect textRect = subElementRect(QStyle::SE_ItemViewItemText, option, widget);
- QRect displayRect = subElementRect(QStyle::SE_ItemViewItemDecoration, option, widget);
- if (!vopt->icon.isNull())
- rect = textRect.united(displayRect);
- else
- rect = textRect;
- rect = rect.adjusted(1, 0, -1, 0);
- }
- break;
- default:
- break;
- }
- return rect;
-}
-
-
-/*
- This function is used by subControlRect to check if a button
- should be drawn for the given subControl given a set of window flags.
-*/
-static bool buttonVisible(const QStyle::SubControl sc, const QStyleOptionTitleBar *tb){
-
- bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
- const uint flags = tb->titleBarFlags;
- bool retVal = false;
- switch (sc) {
- case QStyle::SC_TitleBarContextHelpButton:
- if (flags & Qt::WindowContextHelpButtonHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarMinButton:
- if (!isMinimized && (flags & Qt::WindowMinimizeButtonHint))
- retVal = true;
- break;
- case QStyle::SC_TitleBarNormalButton:
- if (isMinimized && (flags & Qt::WindowMinimizeButtonHint))
- retVal = true;
- else if (isMaximized && (flags & Qt::WindowMaximizeButtonHint))
- retVal = true;
- break;
- case QStyle::SC_TitleBarMaxButton:
- if (!isMaximized && (flags & Qt::WindowMaximizeButtonHint))
- retVal = true;
- break;
- case QStyle::SC_TitleBarShadeButton:
- if (!isMinimized && flags & Qt::WindowShadeButtonHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarUnshadeButton:
- if (isMinimized && flags & Qt::WindowShadeButtonHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarCloseButton:
- if (flags & Qt::WindowSystemMenuHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarSysMenu:
- if (flags & Qt::WindowSystemMenuHint)
- retVal = true;
- break;
- default :
- retVal = true;
- }
- return retVal;
-}
-
-
-/*! \internal */
-int QWindowsVistaStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget,
- QStyleHintReturn *returnData) const
-{
- QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate*>(d_func());
- int ret = 0;
- switch (hint) {
- case SH_MessageBox_CenterButtons:
- ret = false;
- break;
- case SH_ToolTip_Mask:
- if (option) {
- if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(returnData)) {
- ret = true;
- XPThemeData themeData(widget, 0, QLatin1String("TOOLTIP"), TTP_STANDARD, TTSS_NORMAL, option->rect);
- mask->region = d->region(themeData);
- }
- }
- break;
- case SH_Table_GridLineColor:
- if (option)
- ret = option->palette.color(QPalette::Base).darker(118).rgb();
- else
- ret = -1;
- break;
- default:
- ret = QWindowsXPStyle::styleHint(hint, option, widget, returnData);
- break;
- }
- return ret;
-}
-
-
-/*!
- \internal
- */
-QRect QWindowsVistaStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista())
- return QWindowsStyle::subControlRect(control, option, subControl, widget);
-
- QRect rect = QWindowsXPStyle::subControlRect(control, option, subControl, widget);
- switch (control) {
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int x = cb->rect.x(),
- y = cb->rect.y(),
- wi = cb->rect.width(),
- he = cb->rect.height();
- int xpos = x;
- int margin = cb->frame ? 3 : 0;
- int bmarg = cb->frame ? 2 : 0;
- int arrowButtonWidth = bmarg + 16;
- xpos += wi - arrowButtonWidth;
-
- switch (subControl) {
- case SC_ComboBoxFrame:
- rect = cb->rect;
- break;
- case SC_ComboBoxArrow:
- rect.setRect(xpos, y , arrowButtonWidth, he);
- break;
- case SC_ComboBoxEditField:
- rect.setRect(x + margin, y + margin, wi - 2 * margin - 16, he - 2 * margin);
- break;
- case SC_ComboBoxListBoxPopup:
- rect = cb->rect;
- break;
- default:
- break;
- }
- rect = visualRect(cb->direction, cb->rect, rect);
- return rect;
- }
-#endif // QT_NO_COMBOBOX
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- if (!buttonVisible(subControl, tb))
- return rect;
- const bool isToolTitle = false;
- const int height = tb->rect.height();
- const int width = tb->rect.width();
- int buttonWidth = GetSystemMetrics(SM_CXSIZE) - 4;
-
- const int frameWidth = proxy()->pixelMetric(PM_MdiSubWindowFrameWidth, option, widget);
- const bool sysmenuHint = (tb->titleBarFlags & Qt::WindowSystemMenuHint) != 0;
- const bool minimizeHint = (tb->titleBarFlags & Qt::WindowMinimizeButtonHint) != 0;
- const bool maximizeHint = (tb->titleBarFlags & Qt::WindowMaximizeButtonHint) != 0;
- const bool contextHint = (tb->titleBarFlags & Qt::WindowContextHelpButtonHint) != 0;
- const bool shadeHint = (tb->titleBarFlags & Qt::WindowShadeButtonHint) != 0;
-
- switch (subControl) {
- case SC_TitleBarLabel:
- rect = QRect(frameWidth, 0, width - (buttonWidth + frameWidth + 10), height);
- if (isToolTitle) {
- if (sysmenuHint) {
- rect.adjust(0, 0, -buttonWidth - 3, 0);
- }
- if (minimizeHint || maximizeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- } else {
- if (sysmenuHint) {
- const int leftOffset = height - 8;
- rect.adjust(leftOffset, 0, 0, 4);
- }
- if (minimizeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- if (maximizeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- if (contextHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- if (shadeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- }
- rect.translate(0, 2);
- rect = visualRect(option->direction, option->rect, rect);
- break;
- case SC_TitleBarSysMenu:
- {
- const int controlTop = 6;
- const int controlHeight = height - controlTop - 3;
- int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
- QSize iconSize = tb->icon.actualSize(QSize(iconExtent, iconExtent));
- if (tb->icon.isNull())
- iconSize = QSize(controlHeight, controlHeight);
- int hPad = (controlHeight - iconSize.height())/2;
- int vPad = (controlHeight - iconSize.width())/2;
- rect = QRect(frameWidth + hPad, controlTop + vPad, iconSize.width(), iconSize.height());
- rect.translate(0, 3);
- rect = visualRect(option->direction, option->rect, rect);
- }
- break;
- default:
- break;
- }
- }
- break;
- default:
- break;
- }
- return rect;
-}
-
-/*!
- \internal
- */
-bool QWindowsVistaStyle::event(QEvent *e)
-{
- Q_D(QWindowsVistaStyle);
- switch (e->type()) {
- case QEvent::Timer:
- {
- QTimerEvent *timerEvent = (QTimerEvent *)e;
- if (d->animationTimer.timerId() == timerEvent->timerId()) {
- d->timerEvent();
- e->accept();
- return true;
- }
- }
- break;
- default:
- break;
- }
- return QWindowsXPStyle::event(e);
-}
-
-/*!
- \internal
- */
-QStyle::SubControl QWindowsVistaStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- const QPoint &pos, const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista()) {
- return QWindowsStyle::hitTestComplexControl(control, option, pos, widget);
- }
- return QWindowsXPStyle::hitTestComplexControl(control, option, pos, widget);
-}
-
-/*!
- \internal
- */
-int QWindowsVistaStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista()) {
- return QWindowsStyle::pixelMetric(metric, option, widget);
- }
- switch (metric) {
-
- case PM_DockWidgetTitleBarButtonMargin:
- return int(QStyleHelper::dpiScaled(5.));
- case PM_ScrollBarSliderMin:
- return int(QStyleHelper::dpiScaled(18.));
- case PM_MenuHMargin:
- case PM_MenuVMargin:
- return 0;
- case PM_MenuPanelWidth:
- return 3;
- default:
- break;
- }
- return QWindowsXPStyle::pixelMetric(metric, option, widget);
-}
-
-/*!
- \internal
- */
-QPalette QWindowsVistaStyle::standardPalette() const
-{
- return QWindowsXPStyle::standardPalette();
-}
-
-/*!
- \internal
- */
-void QWindowsVistaStyle::polish(QApplication *app)
-{
- QWindowsXPStyle::polish(app);
-}
-
-/*!
- \internal
- */
-void QWindowsVistaStyle::polish(QWidget *widget)
-{
- QWindowsXPStyle::polish(widget);
-#ifndef QT_NO_LINEEDIT
- if (qobject_cast<QLineEdit*>(widget))
- widget->setAttribute(Qt::WA_Hover);
- else
-#endif // QT_NO_LINEEDIT
- if (qobject_cast<QGroupBox*>(widget))
- widget->setAttribute(Qt::WA_Hover);
- else if (qobject_cast<QCommandLinkButton*>(widget)) {
- QFont buttonFont = widget->font();
- buttonFont.setFamily(QLatin1String("Segoe UI"));
- widget->setFont(buttonFont);
- }
- else if (widget->inherits("QTipLabel")){
- //note that since tooltips are not reused
- //we do not have to care about unpolishing
- widget->setContentsMargins(3, 0, 4, 0);
- COLORREF bgRef;
- HTHEME theme = pOpenThemeData(widget ? QWindowsVistaStylePrivate::winId(widget) : 0, L"TOOLTIP");
- if (theme) {
- if (pGetThemeColor(theme, TTP_STANDARD, TTSS_NORMAL, TMT_TEXTCOLOR, &bgRef) == S_OK) {
- QColor textColor = QColor::fromRgb(bgRef);
- QPalette pal;
- pal.setColor(QPalette::All, QPalette::ToolTipText, textColor);
- widget->setPalette(pal);
- }
- }
- } else if (qobject_cast<QMessageBox *> (widget)) {
- widget->setAttribute(Qt::WA_StyledBackground);
- QDialogButtonBox *buttonBox = widget->findChild<QDialogButtonBox *>(QLatin1String("qt_msgbox_buttonbox"));
- if (buttonBox)
- buttonBox->setContentsMargins(0, 9, 0, 0);
- }
-#ifndef QT_NO_INPUTDIALOG
- else if (qobject_cast<QInputDialog *> (widget)) {
- widget->setAttribute(Qt::WA_StyledBackground);
- QDialogButtonBox *buttonBox = widget->findChild<QDialogButtonBox *>(QLatin1String("qt_inputdlg_buttonbox"));
- if (buttonBox)
- buttonBox->setContentsMargins(0, 9, 0, 0);
- }
-#endif // QT_NO_INPUTDIALOG
- else if (QTreeView *tree = qobject_cast<QTreeView *> (widget)) {
- tree->viewport()->setAttribute(Qt::WA_Hover);
- }
- else if (QListView *list = qobject_cast<QListView *> (widget)) {
- list->viewport()->setAttribute(Qt::WA_Hover);
- }
-}
-
-/*!
- \internal
- */
-void QWindowsVistaStyle::unpolish(QWidget *widget)
-{
- QWindowsXPStyle::unpolish(widget);
-
- QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate*>(d_func());
- d->stopAnimation(widget);
-
-#ifndef QT_NO_LINEEDIT
- if (qobject_cast<QLineEdit*>(widget))
- widget->setAttribute(Qt::WA_Hover, false);
- else
-#endif // QT_NO_LINEEDIT
- if (qobject_cast<QGroupBox*>(widget))
- widget->setAttribute(Qt::WA_Hover, false);
- else if (qobject_cast<QMessageBox *> (widget)) {
- widget->setAttribute(Qt::WA_StyledBackground, false);
- QDialogButtonBox *buttonBox = widget->findChild<QDialogButtonBox *>(QLatin1String("qt_msgbox_buttonbox"));
- if (buttonBox)
- buttonBox->setContentsMargins(0, 0, 0, 0);
- }
-#ifndef QT_NO_INPUTDIALOG
- else if (qobject_cast<QInputDialog *> (widget)) {
- widget->setAttribute(Qt::WA_StyledBackground, false);
- QDialogButtonBox *buttonBox = widget->findChild<QDialogButtonBox *>(QLatin1String("qt_inputdlg_buttonbox"));
- if (buttonBox)
- buttonBox->setContentsMargins(0, 0, 0, 0);
- }
-#endif // QT_NO_INPUTDIALOG
- else if (QTreeView *tree = qobject_cast<QTreeView *> (widget)) {
- tree->viewport()->setAttribute(Qt::WA_Hover, false);
- } else if (qobject_cast<QCommandLinkButton*>(widget)) {
- QFont font = QApplication::font("QCommandLinkButton");
- QFont widgetFont = widget->font();
- widgetFont.setFamily(font.family()); //Only family set by polish
- widget->setFont(widgetFont);
- }
-}
-
-
-/*!
- \internal
- */
-void QWindowsVistaStyle::unpolish(QApplication *app)
-{
- QWindowsXPStyle::unpolish(app);
-}
-
-/*!
- \internal
- */
-void QWindowsVistaStyle::polish(QPalette &pal)
-{
- QWindowsStyle::polish(pal);
- pal.setBrush(QPalette::AlternateBase, pal.base().color().darker(104));
-}
-
-/*!
- \internal
- */
-QPixmap QWindowsVistaStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option,
- const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista()) {
- return QWindowsStyle::standardPixmap(standardPixmap, option, widget);
- }
- return QWindowsXPStyle::standardPixmap(standardPixmap, option, widget);
-}
-
-QWindowsVistaStylePrivate::QWindowsVistaStylePrivate() :
- QWindowsXPStylePrivate(), m_treeViewHelper(0)
-{
- resolveSymbols();
-}
-
-QWindowsVistaStylePrivate::~QWindowsVistaStylePrivate()
-{
- delete m_treeViewHelper;
-}
-
-void QWindowsVistaStylePrivate::timerEvent()
-{
- for (int i = animations.size() - 1 ; i >= 0 ; --i) {
-
- if (animations[i]->widget())
- animations[i]->widget()->update();
-
- if (!animations[i]->widget() ||
- !animations[i]->widget()->isEnabled() ||
- !animations[i]->widget()->isVisible() ||
- animations[i]->widget()->window()->isMinimized() ||
- !animations[i]->running() ||
- !QWindowsVistaStylePrivate::useVista())
- {
- QWindowsVistaAnimation *a = animations.takeAt(i);
- delete a;
- }
- }
- if (animations.size() == 0 && animationTimer.isActive()) {
- animationTimer.stop();
- }
-}
-
-void QWindowsVistaStylePrivate::stopAnimation(const QWidget *w)
-{
- for (int i = animations.size() - 1 ; i >= 0 ; --i) {
- if (animations[i]->widget() == w) {
- QWindowsVistaAnimation *a = animations.takeAt(i);
- delete a;
- break;
- }
- }
-}
-
-void QWindowsVistaStylePrivate::startAnimation(QWindowsVistaAnimation *t)
-{
- Q_Q(QWindowsVistaStyle);
- stopAnimation(t->widget());
- animations.append(t);
- if (animations.size() > 0 && !animationTimer.isActive()) {
- animationTimer.start(45, q);
- }
-}
-
-bool QWindowsVistaStylePrivate::transitionsEnabled() const
-{
- BOOL animEnabled = false;
- if (SystemParametersInfo(SPI_GETCLIENTAREAANIMATION, 0, &animEnabled, 0))
- {
- if (animEnabled)
- return true;
- }
- return false;
-}
-
-
-QWindowsVistaAnimation * QWindowsVistaStylePrivate::widgetAnimation(const QWidget *widget) const
-{
- if (!widget)
- return 0;
- foreach (QWindowsVistaAnimation *a, animations) {
- if (a->widget() == widget)
- return a;
- }
- return 0;
-}
-
-
-/*! \internal
- Returns true if all the necessary theme engine symbols were
- resolved.
-*/
-bool QWindowsVistaStylePrivate::resolveSymbols()
-{
- static bool tried = false;
- if (!tried) {
- tried = true;
- QSystemLibrary themeLib(QLatin1String("uxtheme"));
- pSetWindowTheme = (PtrSetWindowTheme )themeLib.resolve("SetWindowTheme");
- pIsThemePartDefined = (PtrIsThemePartDefined )themeLib.resolve("IsThemePartDefined");
- pGetThemePartSize = (PtrGetThemePartSize )themeLib.resolve("GetThemePartSize");
- pOpenThemeData = (PtrOpenThemeData )themeLib.resolve("OpenThemeData");
- pCloseThemeData = (PtrCloseThemeData )themeLib.resolve("CloseThemeData");
- pDrawThemeBackground = (PtrDrawThemeBackground )themeLib.resolve("DrawThemeBackground");
- pDrawThemeBackgroundEx = (PtrDrawThemeBackgroundEx )themeLib.resolve("DrawThemeBackgroundEx");
- pGetCurrentThemeName = (PtrGetCurrentThemeName )themeLib.resolve("GetCurrentThemeName");
- pGetThemeBool = (PtrGetThemeBool )themeLib.resolve("GetThemeBool");
- pGetThemeColor = (PtrGetThemeColor )themeLib.resolve("GetThemeColor");
- pGetThemeEnumValue = (PtrGetThemeEnumValue )themeLib.resolve("GetThemeEnumValue");
- pGetThemeFilename = (PtrGetThemeFilename )themeLib.resolve("GetThemeFilename");
- pGetThemeFont = (PtrGetThemeFont )themeLib.resolve("GetThemeFont");
- pGetThemeInt = (PtrGetThemeInt )themeLib.resolve("GetThemeInt");
- pGetThemeIntList = (PtrGetThemeIntList )themeLib.resolve("GetThemeIntList");
- pGetThemeMargins = (PtrGetThemeMargins )themeLib.resolve("GetThemeMargins");
- pGetThemeMetric = (PtrGetThemeMetric )themeLib.resolve("GetThemeMetric");
- pGetThemePartSize = (PtrGetThemePartSize )themeLib.resolve("GetThemePartSize");
- pGetThemePosition = (PtrGetThemePosition )themeLib.resolve("GetThemePosition");
- pGetThemeRect = (PtrGetThemeRect )themeLib.resolve("GetThemeRect");
- pGetThemeString = (PtrGetThemeString )themeLib.resolve("GetThemeString");
- pGetThemeTransitionDuration = (PtrGetThemeTransitionDuration)themeLib.resolve("GetThemeTransitionDuration");
- pGetThemePropertyOrigin = (PtrGetThemePropertyOrigin)themeLib.resolve("GetThemePropertyOrigin");
- }
- return pGetThemeTransitionDuration != 0;
-}
-
-/*
- * We need to set the windows explorer theme explicitly on a native widget
- * in order to get Vista-style item view themes
- */
-QWidget *QWindowsVistaStylePrivate::treeViewHelper()
-{
- if (!m_treeViewHelper) {
- m_treeViewHelper = new QWidget(0);
- pSetWindowTheme(m_treeViewHelper->winId(), L"explorer", NULL);
- }
- return m_treeViewHelper;
-}
-
-
-/*!
-\internal
-*/
-QIcon QWindowsVistaStyle::standardIconImplementation(StandardPixmap standardIcon,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- if (!QWindowsVistaStylePrivate::useVista()) {
- return QWindowsStyle::standardIconImplementation(standardIcon, option, widget);
- }
-
- QWindowsVistaStylePrivate *d = const_cast<QWindowsVistaStylePrivate *>(d_func());
- switch(standardIcon) {
- case SP_CommandLink:
- {
- XPThemeData theme(0, 0, QLatin1String("BUTTON"), BP_COMMANDLINKGLYPH, CMDLGS_NORMAL);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- QIcon linkGlyph;
- QPixmap pm = QPixmap(size.cx, size.cy);
- pm.fill(Qt::transparent);
- QPainter p(&pm);
- theme.painter = &p;
- theme.rect = QRect(0, 0, size.cx, size.cy);
- d->drawBackground(theme);
- linkGlyph.addPixmap(pm, QIcon::Normal, QIcon::Off); // Normal
- pm.fill(Qt::transparent);
-
- theme.stateId = CMDLGS_PRESSED;
- d->drawBackground(theme);
- linkGlyph.addPixmap(pm, QIcon::Normal, QIcon::On); // Pressed
- pm.fill(Qt::transparent);
-
- theme.stateId = CMDLGS_HOT;
- d->drawBackground(theme);
- linkGlyph.addPixmap(pm, QIcon::Active, QIcon::Off); // Hover
- pm.fill(Qt::transparent);
-
- theme.stateId = CMDLGS_DISABLED;
- d->drawBackground(theme);
- linkGlyph.addPixmap(pm, QIcon::Disabled, QIcon::Off); // Disabled
- return linkGlyph;
- }
- }
- break;
- default:
- break;
- }
- return QWindowsXPStyle::standardIconImplementation(standardIcon, option, widget);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_WINDOWSVISTA
diff --git a/src/gui/styles/qwindowsvistastyle.h b/src/gui/styles/qwindowsvistastyle.h
deleted file mode 100644
index c13dccf28b..0000000000
--- a/src/gui/styles/qwindowsvistastyle.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSVISTASTYLE_H
-#define QWINDOWSVISTASTYLE_H
-
-#include <QtGui/qwindowsxpstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-
-class QWindowsVistaStylePrivate;
-class Q_GUI_EXPORT QWindowsVistaStyle : public QWindowsXPStyle
-{
- Q_OBJECT
-public:
- QWindowsVistaStyle();
-
- void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget = 0) const;
- void drawControl(ControlElement element, const QStyleOption *option,
- QPainter *painter, const QWidget *widget) const;
- void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget) const;
- QSize sizeFromContents(ContentsType type, const QStyleOption *option,
- const QSize &size, const QWidget *widget) const;
-
- QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
- SubControl sc, const QWidget *widget) const;
-
- SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option,
- const QPoint &pos, const QWidget *widget = 0) const;
-
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
- int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
-
-
- void polish(QWidget *widget);
- void unpolish(QWidget *widget);
- void polish(QPalette &pal);
- void polish(QApplication *app);
- void unpolish(QApplication *app);
- bool event(QEvent *event);
- QPalette standardPalette() const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget = 0) const;
-
-private:
- Q_DISABLE_COPY(QWindowsVistaStyle)
- Q_DECLARE_PRIVATE(QWindowsVistaStyle)
- friend class QStyleFactory;
-};
-#endif //QT_NO_STYLE_WINDOWSVISTA
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif //QWINDOWSVISTASTYLE_H
diff --git a/src/gui/styles/qwindowsvistastyle_p.h b/src/gui/styles/qwindowsvistastyle_p.h
deleted file mode 100644
index ba653880c9..0000000000
--- a/src/gui/styles/qwindowsvistastyle_p.h
+++ /dev/null
@@ -1,220 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSVISTASTYLE_P_H
-#define QWINDOWSVISTASTYLE_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qwindowsvistastyle.h"
-
-#if !defined(QT_NO_STYLE_WINDOWSVISTA)
-#include <private/qwindowsxpstyle_p.h>
-#include <private/qpaintengine_raster_p.h>
-#include <qlibrary.h>
-#include <qpaintengine.h>
-#include <qwidget.h>
-#include <qapplication.h>
-#include <qpixmapcache.h>
-#include <qstyleoption.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qcheckbox.h>
-#include <qlineedit.h>
-#include <qgroupbox.h>
-#include <qtoolbutton.h>
-#include <qspinbox.h>
-#include <qtoolbar.h>
-#include <qcombobox.h>
-#include <qscrollbar.h>
-#include <qprogressbar.h>
-#include <qdockwidget.h>
-#include <qlistview.h>
-#include <qtreeview.h>
-#include <qtextedit.h>
-#include <qmessagebox.h>
-#include <qdialogbuttonbox.h>
-#include <qinputdialog.h>
-#include <qtreeview.h>
-#include <qlistview.h>
-#include <qtableview.h>
-#include <qbasictimer.h>
-#include <qdatetime.h>
-#include <qcommandlinkbutton.h>
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(SCHEMA_VERIFY_VSSYM32)
-#define TMT_ANIMATIONDURATION 5006
-#define TMT_TRANSITIONDURATIONS 6000
-#define EP_EDITBORDER_NOSCROLL 6
-#define EP_EDITBORDER_HVSCROLL 9
-#define EP_BACKGROUND 3
-#define EBS_NORMAL 1
-#define EBS_HOT 2
-#define EBS_DISABLED 3
-#define EBS_READONLY 5
-#define PBS_DEFAULTED_ANIMATING 6
-#define MBI_NORMAL 1
-#define MBI_HOT 2
-#define MBI_PUSHED 3
-#define MBI_DISABLED 4
-#define MB_ACTIVE 1
-#define MB_INACTIVE 2
-#define PP_FILL 5
-#define PP_FILLVERT 6
-#define PP_MOVEOVERLAY 8
-#define PP_MOVEOVERLAYVERT 10
-#define MENU_BARBACKGROUND 7
-#define MENU_BARITEM 8
-#define MENU_POPUPCHECK 11
-#define MENU_POPUPCHECKBACKGROUND 12
-#define MENU_POPUPGUTTER 13
-#define MENU_POPUPITEM 14
-#define MENU_POPUPBORDERS 10
-#define MENU_POPUPSEPARATOR 15
-#define MC_CHECKMARKNORMAL 1
-#define MC_CHECKMARKDISABLED 2
-#define MC_BULLETNORMAL 3
-#define MC_BULLETDISABLED 4
-#define ABS_UPHOVER 17
-#define ABS_DOWNHOVER 18
-#define ABS_LEFTHOVER 19
-#define ABS_RIGHTHOVER 20
-#define CP_DROPDOWNBUTTONRIGHT 6
-#define CP_DROPDOWNBUTTONLEFT 7
-#define SCRBS_HOVER 5
-#define TVP_HOTGLYPH 4
-#define SPI_GETCLIENTAREAANIMATION 0x1042
-#define TDLG_PRIMARYPANEL 1
-#define TDLG_SECONDARYPANEL 8
-#endif
-
-class QWindowsVistaAnimation
-{
-public :
- QWindowsVistaAnimation() : _running(true) { }
- virtual ~QWindowsVistaAnimation() { }
- QWidget * widget() const { return _widget; }
- bool running() const { return _running; }
- const QTime &startTime() const { return _startTime; }
- void setRunning(bool val) { _running = val; }
- void setWidget(QWidget *widget) { _widget = widget; }
- void setStartTime(const QTime &startTime) { _startTime = startTime; }
- virtual void paint(QPainter *painter, const QStyleOption *option);
-
-protected:
- void drawBlendedImage(QPainter *painter, QRect rect, float value);
- QTime _startTime;
- QPointer<QWidget> _widget;
- QImage _primaryImage;
- QImage _secondaryImage;
- QImage _tempImage;
- bool _running;
-};
-
-
-// Handles state transition animations
-class QWindowsVistaTransition : public QWindowsVistaAnimation
-{
-public :
- QWindowsVistaTransition() : QWindowsVistaAnimation() {}
- virtual ~QWindowsVistaTransition() { }
- void setDuration(int duration) { _duration = duration; }
- void setStartImage(const QImage &image) { _primaryImage = image; }
- void setEndImage(const QImage &image) { _secondaryImage = image; }
- virtual void paint(QPainter *painter, const QStyleOption *option);
- int duration() const { return _duration; }
- int _duration; //set time in ms to complete a state transition
-};
-
-
-// Handles pulse animations (default buttons)
-class QWindowsVistaPulse: public QWindowsVistaAnimation
-{
-public :
- QWindowsVistaPulse() : QWindowsVistaAnimation() {}
- virtual ~QWindowsVistaPulse() { }
- void setDuration(int duration) { _duration = duration; }
- void setPrimaryImage(const QImage &image) { _primaryImage = image; }
- void setAlternateImage(const QImage &image) { _secondaryImage = image; }
- virtual void paint(QPainter *painter, const QStyleOption *option);
- int duration() const { return _duration; }
- int _duration; //time in ms to complete a pulse cycle
-};
-
-
-class QWindowsVistaStylePrivate : public QWindowsXPStylePrivate
-{
- Q_DECLARE_PUBLIC(QWindowsVistaStyle)
-
-public:
- QWindowsVistaStylePrivate();
- ~QWindowsVistaStylePrivate();
- static bool resolveSymbols();
- static inline bool useVista();
- void startAnimation(QWindowsVistaAnimation *);
- void stopAnimation(const QWidget *);
- QWindowsVistaAnimation* widgetAnimation(const QWidget *) const;
- void timerEvent();
- bool transitionsEnabled() const;
- QWidget *treeViewHelper();
-
-private:
- QList <QWindowsVistaAnimation*> animations;
- QBasicTimer animationTimer;
- QWidget *m_treeViewHelper;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSVISTA
-
-#endif // QWINDOWSVISTASTYLE_P_H
diff --git a/src/gui/styles/qwindowsxpstyle.cpp b/src/gui/styles/qwindowsxpstyle.cpp
deleted file mode 100644
index 74a20fce29..0000000000
--- a/src/gui/styles/qwindowsxpstyle.cpp
+++ /dev/null
@@ -1,4271 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwindowsxpstyle.h"
-#include "qwindowsxpstyle_p.h"
-
-#if !defined(QT_NO_STYLE_WINDOWSXP) || defined(QT_PLUGIN)
-
-#include <private/qobject_p.h>
-#include <private/qpaintengine_raster_p.h>
-#include <private/qapplication_p.h>
-#include <private/qstylehelper_p.h>
-#include <private/qwidget_p.h>
-#include <private/qsystemlibrary_p.h>
-#include <qpainter.h>
-#include <qpaintengine.h>
-#include <qwidget.h>
-#include <qapplication.h>
-#include <qpixmapcache.h>
-
-#include <qdesktopwidget.h>
-#include <qtoolbutton.h>
-#include <qtabbar.h>
-#include <qcombobox.h>
-#include <qscrollbar.h>
-#include <qheaderview.h>
-#include <qspinbox.h>
-#include <qlistview.h>
-#include <qstackedwidget.h>
-#include <qpushbutton.h>
-#include <qtoolbar.h>
-#include <qlabel.h>
-#include <qvarlengtharray.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-// Runtime resolved theme engine function calls
-typedef bool (WINAPI *PtrIsAppThemed)();
-typedef bool (WINAPI *PtrIsThemeActive)();
-typedef HRESULT (WINAPI *PtrGetThemePartSize)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, OPTIONAL RECT *prc, enum THEMESIZE eSize, OUT SIZE *psz);
-typedef HTHEME (WINAPI *PtrOpenThemeData)(HWND hwnd, LPCWSTR pszClassList);
-typedef HRESULT (WINAPI *PtrCloseThemeData)(HTHEME hTheme);
-typedef HRESULT (WINAPI *PtrDrawThemeBackground)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const RECT *pClipRect);
-typedef HRESULT (WINAPI *PtrDrawThemeBackgroundEx)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const DTBGOPTS *pOptions);
-typedef HRESULT (WINAPI *PtrGetCurrentThemeName)(OUT LPWSTR pszThemeFileName, int cchMaxNameChars, OUT OPTIONAL LPWSTR pszColorBuff, int cchMaxColorChars, OUT OPTIONAL LPWSTR pszSizeBuff, int cchMaxSizeChars);
-typedef HRESULT (WINAPI *PtrGetThemeDocumentationProperty)(LPCWSTR pszThemeName, LPCWSTR pszPropertyName, OUT LPWSTR pszValueBuff, int cchMaxValChars);
-typedef HRESULT (WINAPI *PtrGetThemeBool)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT BOOL *pfVal);
-typedef HRESULT (WINAPI *PtrGetThemeColor)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT COLORREF *pColor);
-typedef HRESULT (WINAPI *PtrGetThemeEnumValue)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT int *piVal);
-typedef HRESULT (WINAPI *PtrGetThemeFilename)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT LPWSTR pszThemeFileName, int cchMaxBuffChars);
-typedef HRESULT (WINAPI *PtrGetThemeFont)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OUT LOGFONT *pFont);
-typedef HRESULT (WINAPI *PtrGetThemeInt)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT int *piVal);
-typedef HRESULT (WINAPI *PtrGetThemeIntList)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT INTLIST *pIntList);
-typedef HRESULT (WINAPI *PtrGetThemeMargins)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OPTIONAL RECT *prc, OUT MARGINS *pMargins);
-typedef HRESULT (WINAPI *PtrGetThemeMetric)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OUT int *piVal);
-typedef HRESULT (WINAPI *PtrGetThemePartSize)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, OPTIONAL RECT *prc, enum THEMESIZE eSize, OUT SIZE *psz);
-typedef HRESULT (WINAPI *PtrGetThemePosition)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT POINT *pPoint);
-typedef HRESULT (WINAPI *PtrGetThemePropertyOrigin)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT enum PROPERTYORIGIN *pOrigin);
-typedef HRESULT (WINAPI *PtrGetThemeRect)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT RECT *pRect);
-typedef HRESULT (WINAPI *PtrGetThemeString)(HTHEME hTheme, int iPartId, int iStateId, int iPropId, OUT LPWSTR pszBuff, int cchMaxBuffChars);
-typedef HRESULT (WINAPI *PtrGetThemeBackgroundRegion)(HTHEME hTheme, OPTIONAL HDC hdc, int iPartId, int iStateId, const RECT *pRect, OUT HRGN *pRegion);
-typedef BOOL (WINAPI *PtrIsThemeBackgroundPartiallyTransparent)(HTHEME hTheme, int iPartId, int iStateId);
-
-static PtrIsAppThemed pIsAppThemed = 0;
-static PtrIsThemeActive pIsThemeActive = 0;
-static PtrOpenThemeData pOpenThemeData = 0;
-static PtrCloseThemeData pCloseThemeData = 0;
-static PtrDrawThemeBackground pDrawThemeBackground = 0;
-static PtrDrawThemeBackgroundEx pDrawThemeBackgroundEx = 0;
-static PtrGetCurrentThemeName pGetCurrentThemeName = 0;
-static PtrGetThemeBool pGetThemeBool = 0;
-static PtrGetThemeColor pGetThemeColor = 0;
-static PtrGetThemeEnumValue pGetThemeEnumValue = 0;
-static PtrGetThemeFilename pGetThemeFilename = 0;
-static PtrGetThemeFont pGetThemeFont = 0;
-static PtrGetThemeInt pGetThemeInt = 0;
-static PtrGetThemeIntList pGetThemeIntList = 0;
-static PtrGetThemeMargins pGetThemeMargins = 0;
-static PtrGetThemeMetric pGetThemeMetric = 0;
-static PtrGetThemePartSize pGetThemePartSize = 0;
-static PtrGetThemePosition pGetThemePosition = 0;
-static PtrGetThemePropertyOrigin pGetThemePropertyOrigin = 0;
-static PtrGetThemeRect pGetThemeRect = 0;
-static PtrGetThemeString pGetThemeString = 0;
-static PtrGetThemeBackgroundRegion pGetThemeBackgroundRegion = 0;
-static PtrGetThemeDocumentationProperty pGetThemeDocumentationProperty = 0;
-static PtrIsThemeBackgroundPartiallyTransparent pIsThemeBackgroundPartiallyTransparent = 0;
-
-// General const values
-static const int windowsItemFrame = 2; // menu item frame width
-static const int windowsItemHMargin = 3; // menu item hor text margin
-static const int windowsItemVMargin = 0; // menu item ver text margin
-static const int windowsArrowHMargin = 6; // arrow horizontal margin
-static const int windowsRightBorder = 12; // right border on windows
-
-// External function calls
-extern Q_GUI_EXPORT HDC qt_win_display_dc();
-extern QRegion qt_region_from_HRGN(HRGN rgn);
-
-
-
-// Theme data helper ------------------------------------------------------------------------------
-/* \internal
- Returns true if the themedata is valid for use.
-*/
-bool XPThemeData::isValid()
-{
- return QWindowsXPStylePrivate::useXP() && name.size() && handle();
-}
-
-
-/* \internal
- Returns the theme engine handle to the specific class.
- If the handle hasn't been opened before, it opens the data, and
- adds it to a static map, for caching.
-*/
-HTHEME XPThemeData::handle()
-{
- if (!QWindowsXPStylePrivate::useXP())
- return 0;
-
- if (!htheme && QWindowsXPStylePrivate::handleMap)
- htheme = QWindowsXPStylePrivate::handleMap->operator[](name);
-
- if (!htheme) {
- htheme = pOpenThemeData(QWindowsXPStylePrivate::winId(widget), (wchar_t*)name.utf16());
- if (htheme) {
- if (!QWindowsXPStylePrivate::handleMap)
- QWindowsXPStylePrivate::handleMap = new QMap<QString, HTHEME>;
- QWindowsXPStylePrivate::handleMap->operator[](name) = htheme;
- }
- }
-
- return htheme;
-}
-
-/* \internal
- Converts a QRect to the native RECT structure.
-*/
-RECT XPThemeData::toRECT(const QRect &qr)
-{
- RECT r;
- r.left = qr.x();
- r.right = qr.x() + qr.width();
- r.top = qr.y();
- r.bottom = qr.y() + qr.height();
- return r;
-}
-
-/* \internal
- Returns the native region of a part, if the part is considered
- transparent. The region is scaled to the parts size (rect).
-*/
-HRGN XPThemeData::mask()
-{
- if (!pIsThemeBackgroundPartiallyTransparent(handle(), partId, stateId))
- return 0;
-
- HRGN hrgn;
- HDC dc = painter == 0 ? 0 : painter->paintEngine()->getDC();
- RECT nativeRect = toRECT(rect);
- pGetThemeBackgroundRegion(handle(), dc, partId, stateId, &nativeRect, &hrgn);
- if (dc)
- painter->paintEngine()->releaseDC(dc);
- return hrgn;
-}
-
-// QWindowsXPStylePrivate -------------------------------------------------------------------------
-// Static initializations
-QWidget *QWindowsXPStylePrivate::limboWidget = 0;
-QPixmap *QWindowsXPStylePrivate::tabbody = 0;
-QMap<QString,HTHEME> *QWindowsXPStylePrivate::handleMap = 0;
-bool QWindowsXPStylePrivate::use_xp = false;
-QBasicAtomicInt QWindowsXPStylePrivate::ref = Q_BASIC_ATOMIC_INITIALIZER(-1); // -1 based refcounting
-
-/* \internal
- Checks if the theme engine can/should be used, or if we should
- fall back to Windows style.
-*/
-bool QWindowsXPStylePrivate::useXP(bool update)
-{
- if (!update)
- return use_xp;
- return (use_xp = resolveSymbols() && pIsThemeActive()
- && (pIsAppThemed() || !QApplication::instance()));
-}
-
-/* \internal
- Handles refcounting, and queries the theme engine for usage.
-*/
-void QWindowsXPStylePrivate::init(bool force)
-{
- if (ref.ref() && !force)
- return;
- if (!force) // -1 based atomic refcounting
- ref.ref();
-
- useXP(true);
-}
-
-/* \internal
- Cleans up all static data.
-*/
-void QWindowsXPStylePrivate::cleanup(bool force)
-{
- if(bufferBitmap) {
- if (bufferDC && nullBitmap)
- SelectObject(bufferDC, nullBitmap);
- DeleteObject(bufferBitmap);
- bufferBitmap = 0;
- }
-
- if(bufferDC)
- DeleteDC(bufferDC);
- bufferDC = 0;
-
- if (ref.deref() && !force)
- return;
- if (!force) // -1 based atomic refcounting
- ref.deref();
-
- use_xp = false;
- cleanupHandleMap();
- if (limboWidget) {
- if (QApplication::closingDown())
- delete limboWidget;
- else
- limboWidget->deleteLater();
- }
- delete tabbody;
- limboWidget = 0;
- tabbody = 0;
-}
-
-/* \internal
- Closes all open theme data handles to ensure that we don't leak
- resources, and that we don't refere to old handles when for
- example the user changes the theme style.
-*/
-void QWindowsXPStylePrivate::cleanupHandleMap()
-{
- if (!handleMap)
- return;
-
- QMap<QString, HTHEME>::Iterator it;
- for (it = handleMap->begin(); it != handleMap->end(); ++it)
- pCloseThemeData(it.value());
- delete handleMap;
- handleMap = 0;
-}
-
-/*! \internal
- This function will always return a valid window handle, and might
- create a limbo widget to do so.
- We often need a window handle to for example open theme data, so
- this function ensures that we get one.
-*/
-HWND QWindowsXPStylePrivate::winId(const QWidget *widget)
-{
- if (widget && widget->internalWinId())
- return widget->internalWinId();
-
- if (!limboWidget) {
- limboWidget = new QWidget(0);
- limboWidget->createWinId();
- limboWidget->setObjectName(QLatin1String("xp_limbo_widget"));
- // We don't need this internal widget to appear in QApplication::topLevelWidgets()
- if (QWidgetPrivate::allWidgets)
- QWidgetPrivate::allWidgets->remove(limboWidget);
- }
-
- return limboWidget->winId();
-}
-
-/*! \internal
- Returns the pointer to a tab widgets body pixmap, scaled to the
- height of the screen. This way the theme engine doesn't need to
- scale the body for every time we ask for it. (Speed optimization)
-*/
-const QPixmap *QWindowsXPStylePrivate::tabBody(QWidget *)
-{
- if (!tabbody) {
- SIZE sz;
- XPThemeData theme(0, 0, QLatin1String("TAB"), TABP_BODY);
- pGetThemePartSize(theme.handle(), qt_win_display_dc(), TABP_BODY, 0, 0, TS_TRUE, &sz);
-
- tabbody = new QPixmap(sz.cx, QApplication::desktop()->screenGeometry().height());
- QPainter painter(tabbody);
- theme.rect = QRect(0, 0, sz.cx, sz.cy);
- drawBackground(theme);
- // We fill with the last line of the themedata, that
- // way we don't get a tiled pixmap inside big tabs
- QPixmap temp(sz.cx, 1);
- painter.drawPixmap(0, 0, temp, 0, sz.cy-1, -1, -1);
- painter.drawTiledPixmap(0, sz.cy, sz.cx, tabbody->height()-sz.cy, temp);
- }
- return tabbody;
-}
-
-/*! \internal
- Returns true if all the necessary theme engine symbols were
- resolved.
-*/
-bool QWindowsXPStylePrivate::resolveSymbols()
-{
- static bool tried = false;
- if (!tried) {
- tried = true;
- QSystemLibrary themeLib(QLatin1String("uxtheme"));
- pIsAppThemed = (PtrIsAppThemed)themeLib.resolve("IsAppThemed");
- if (pIsAppThemed) {
- pIsThemeActive = (PtrIsThemeActive )themeLib.resolve("IsThemeActive");
- pGetThemePartSize = (PtrGetThemePartSize )themeLib.resolve("GetThemePartSize");
- pOpenThemeData = (PtrOpenThemeData )themeLib.resolve("OpenThemeData");
- pCloseThemeData = (PtrCloseThemeData )themeLib.resolve("CloseThemeData");
- pDrawThemeBackground = (PtrDrawThemeBackground )themeLib.resolve("DrawThemeBackground");
- pDrawThemeBackgroundEx = (PtrDrawThemeBackgroundEx )themeLib.resolve("DrawThemeBackgroundEx");
- pGetCurrentThemeName = (PtrGetCurrentThemeName )themeLib.resolve("GetCurrentThemeName");
- pGetThemeBool = (PtrGetThemeBool )themeLib.resolve("GetThemeBool");
- pGetThemeColor = (PtrGetThemeColor )themeLib.resolve("GetThemeColor");
- pGetThemeEnumValue = (PtrGetThemeEnumValue )themeLib.resolve("GetThemeEnumValue");
- pGetThemeFilename = (PtrGetThemeFilename )themeLib.resolve("GetThemeFilename");
- pGetThemeFont = (PtrGetThemeFont )themeLib.resolve("GetThemeFont");
- pGetThemeInt = (PtrGetThemeInt )themeLib.resolve("GetThemeInt");
- pGetThemeIntList = (PtrGetThemeIntList )themeLib.resolve("GetThemeIntList");
- pGetThemeMargins = (PtrGetThemeMargins )themeLib.resolve("GetThemeMargins");
- pGetThemeMetric = (PtrGetThemeMetric )themeLib.resolve("GetThemeMetric");
- pGetThemePartSize = (PtrGetThemePartSize )themeLib.resolve("GetThemePartSize");
- pGetThemePosition = (PtrGetThemePosition )themeLib.resolve("GetThemePosition");
- pGetThemePropertyOrigin = (PtrGetThemePropertyOrigin)themeLib.resolve("GetThemePropertyOrigin");
- pGetThemeRect = (PtrGetThemeRect )themeLib.resolve("GetThemeRect");
- pGetThemeString = (PtrGetThemeString )themeLib.resolve("GetThemeString");
- pGetThemeBackgroundRegion = (PtrGetThemeBackgroundRegion )themeLib.resolve("GetThemeBackgroundRegion");
- pGetThemeDocumentationProperty = (PtrGetThemeDocumentationProperty )themeLib.resolve("GetThemeDocumentationProperty");
- pIsThemeBackgroundPartiallyTransparent = (PtrIsThemeBackgroundPartiallyTransparent)themeLib.resolve("IsThemeBackgroundPartiallyTransparent");
- }
- }
-
- return pIsAppThemed != 0;
-}
-
-/*! \internal
- Returns a native buffer (DIB section) of at least the size of
- ( \a x , \a y ). The buffer has a 32 bit depth, to not lose
- the alpha values on proper alpha-pixmaps.
-*/
-HBITMAP QWindowsXPStylePrivate::buffer(int w, int h)
-{
- // If we already have a HBITMAP which is of adequate size, just return that
- if (bufferBitmap) {
- if (bufferW >= w && bufferH >= h)
- return bufferBitmap;
- // Not big enough, discard the old one
- if (bufferDC && nullBitmap)
- SelectObject(bufferDC, nullBitmap);
- DeleteObject(bufferBitmap);
- bufferBitmap = 0;
- }
-
- w = qMax(bufferW, w);
- h = qMax(bufferH, h);
-
- if (!bufferDC)
- bufferDC = CreateCompatibleDC(qt_win_display_dc());
-
- // Define the header
- BITMAPINFO bmi;
- memset(&bmi, 0, sizeof(bmi));
- bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmi.bmiHeader.biWidth = w;
- bmi.bmiHeader.biHeight = -h;
- bmi.bmiHeader.biPlanes = 1;
- bmi.bmiHeader.biBitCount = 32;
- bmi.bmiHeader.biCompression = BI_RGB;
-
- // Create the pixmap
- bufferPixels = 0;
- bufferBitmap = CreateDIBSection(bufferDC, &bmi, DIB_RGB_COLORS, (void **) &bufferPixels, 0, 0);
- GdiFlush();
- nullBitmap = (HBITMAP)SelectObject(bufferDC, bufferBitmap);
-
- if (!bufferBitmap) {
- qErrnoWarning("QWindowsXPStylePrivate::buffer(w,h), failed to create dibsection");
- bufferW = 0;
- bufferH = 0;
- return 0;
- }
- if (!bufferPixels) {
- qErrnoWarning("QWindowsXPStylePrivate::buffer(w,h), did not allocate pixel data");
- bufferW = 0;
- bufferH = 0;
- return 0;
- }
- bufferW = w;
- bufferH = h;
-#ifdef DEBUG_XP_STYLE
- qDebug("Creating new dib section (%d, %d)", w, h);
-#endif
- return bufferBitmap;
-}
-
-/*! \internal
- Returns true if the part contains any transparency at all. This does
- not indicate what kind of transparency we're dealing with. It can be
- - Alpha transparency
- - Masked transparency
-*/
-bool QWindowsXPStylePrivate::isTransparent(XPThemeData &themeData)
-{
- return pIsThemeBackgroundPartiallyTransparent(themeData.handle(), themeData.partId,
- themeData.stateId);
-}
-
-
-/*! \internal
- Returns a QRegion of the region of the part
-*/
-QRegion QWindowsXPStylePrivate::region(XPThemeData &themeData)
-{
- HRGN hRgn = 0;
- RECT rect = themeData.toRECT(themeData.rect);
- if (!SUCCEEDED(pGetThemeBackgroundRegion(themeData.handle(), bufferHDC(), themeData.partId,
- themeData.stateId, &rect, &hRgn)))
- return QRegion();
-
- HRGN dest = CreateRectRgn(0, 0, 0, 0);
- const bool success = CombineRgn(dest, hRgn, 0, RGN_COPY) != ERROR;
-
- QRegion region;
-
- if (success)
- region = qt_region_from_HRGN(dest);
-
- DeleteObject(hRgn);
- DeleteObject(dest);
-
- return region;
-}
-
-/*! \internal
- Sets the parts region on a window.
-*/
-void QWindowsXPStylePrivate::setTransparency(QWidget *widget, XPThemeData &themeData)
-{
- HRGN hrgn = themeData.mask();
- if (hrgn && widget)
- SetWindowRgn(winId(widget), hrgn, true);
-}
-
-/*! \internal
- Returns true if the native doublebuffer contains a pixel which
- has a non-0xFF alpha value. Should only be use when its
- guaranteed that data painted into the buffer wasn't a proper
- alpha pixmap.
-*/
-bool QWindowsXPStylePrivate::hasAnyData(const QRect &rect)
-{
- const int startX = rect.left();
- const int startY = rect.top();
- const int w = rect.width();
- const int h = rect.height();
-
- for (int y = startY; y < h; ++y) {
- register DWORD *buffer = (DWORD*)bufferPixels + (y * bufferW);
- for (int x = startX; x < w; ++x, ++buffer) {
- int alpha = (*buffer) >> 24;
- if (alpha != 0xFF) // buffer has been touched
- return true;
- }
- }
- return false;
-}
-
-/*! \internal
- Returns true if the native doublebuffer contains pixels with
- varying alpha value.
-*/
-bool QWindowsXPStylePrivate::hasAlphaChannel(const QRect &rect)
-{
- const int startX = rect.left();
- const int startY = rect.top();
- const int w = rect.width();
- const int h = rect.height();
-
- int firstAlpha = -1;
- for (int y = startY; y < h/2; ++y) {
- register DWORD *buffer = (DWORD*)bufferPixels + (y * bufferW);
- for (int x = startX; x < w; ++x, ++buffer) {
- int alpha = (*buffer) >> 24;
- if (firstAlpha == -1)
- firstAlpha = alpha;
- else if (alpha != firstAlpha)
- return true;
- }
- }
- return false;
-}
-
-/*! \internal
- When the theme engine paints both a true alpha pixmap and a glyph
- into our buffer, the glyph might not contain a proper alpha value.
- The rule of thumb for premultiplied pixmaps is that the color
- values of a pixel can never be higher than the alpha values, so
- we use this to our advantage here, and fix all instances where
- this occures.
-*/
-bool QWindowsXPStylePrivate::fixAlphaChannel(const QRect &rect)
-{
- const int startX = rect.left();
- const int startY = rect.top();
- const int w = rect.width();
- const int h = rect.height();
- bool hasFixedAlphaValue = false;
-
- for (int y = startY; y < h; ++y) {
- register DWORD *buffer = (DWORD*)bufferPixels + (y * bufferW);
- for (register int x = startX; x < w; ++x, ++buffer) {
- uint pixel = *buffer;
- int alpha = qAlpha(pixel);
- if (qRed(pixel) > alpha || qGreen(pixel) > alpha || qBlue(pixel) > alpha) {
- *buffer |= 0xff000000;
- hasFixedAlphaValue = true;
- }
- }
- }
- return hasFixedAlphaValue;
-}
-
-/*! \internal
- Swaps the alpha values on certain pixels:
- 0xFF?????? -> 0x00??????
- 0x00?????? -> 0xFF??????
- Used to determin the mask of a non-alpha transparent pixmap in
- the native doublebuffer, and swap the alphas so we may paint
- the image as a Premultiplied QImage with drawImage(), and obtain
- the mask transparency.
-*/
-bool QWindowsXPStylePrivate::swapAlphaChannel(const QRect &rect, bool allPixels)
-{
- const int startX = rect.left();
- const int startY = rect.top();
- const int w = rect.width();
- const int h = rect.height();
- bool valueChange = false;
-
- // Flip the alphas, so that 255-alpha pixels are 0, and 0-alpha are 255.
- for (int y = startY; y < h; ++y) {
- register DWORD *buffer = (DWORD*)bufferPixels + (y * bufferW);
- for (register int x = startX; x < w; ++x, ++buffer) {
- if (allPixels) {
- *buffer |= 0xFF000000;
- continue;
- }
- register unsigned int alphaValue = (*buffer) & 0xFF000000;
- if (alphaValue == 0xFF000000) {
- *buffer = 0;
- valueChange = true;
- } else if (alphaValue == 0) {
- *buffer |= 0xFF000000;
- valueChange = true;
- }
- }
- }
- return valueChange;
-}
-
-/*! \internal
- Main theme drawing function.
- Determines the correct lowlevel drawing method depending on several
- factors.
- Use drawBackgroundThruNativeBuffer() if:
- - Painter does not have an HDC
- - Theme part is flipped (mirrored horizontally)
- else use drawBackgroundDirectly().
-*/
-void QWindowsXPStylePrivate::drawBackground(XPThemeData &themeData)
-{
- if (themeData.rect.isEmpty())
- return;
-
- QPainter *painter = themeData.painter;
- Q_ASSERT_X(painter != 0, "QWindowsXPStylePrivate::drawBackground()", "Trying to draw a theme part without a painter");
- if (!painter || !painter->isActive())
- return;
-
- painter->save();
-
- bool complexXForm = painter->deviceTransform().type() > QTransform::TxTranslate;
-
- bool translucentToplevel = false;
- QPaintDevice *pdev = painter->device();
- if (pdev->devType() == QInternal::Widget) {
- QWidget *win = ((QWidget *) pdev)->window();
- translucentToplevel = win->testAttribute(Qt::WA_TranslucentBackground);
- }
-
- bool useFallback = painter->paintEngine()->getDC() == 0
- || painter->opacity() != 1.0
- || themeData.rotate
- || complexXForm
- || themeData.mirrorVertically
- || (themeData.mirrorHorizontally && pDrawThemeBackgroundEx == 0)
- || translucentToplevel;
-
- if (!useFallback)
- drawBackgroundDirectly(themeData);
- else
- drawBackgroundThruNativeBuffer(themeData);
-
- painter->restore();
-}
-
-/*! \internal
- This function draws the theme parts directly to the paintengines HDC.
- Do not use this if you need to perform other transformations on the
- resulting data.
-*/
-void QWindowsXPStylePrivate::drawBackgroundDirectly(XPThemeData &themeData)
-{
- QPainter *painter = themeData.painter;
- HDC dc = painter->paintEngine()->getDC();
-
- QPoint redirectionDelta(int(painter->deviceMatrix().dx()),
- int(painter->deviceMatrix().dy()));
- QRect area = themeData.rect.translated(redirectionDelta);
-
- QRegion sysRgn = painter->paintEngine()->systemClip();
- if (sysRgn.isEmpty())
- sysRgn = area;
- else
- sysRgn &= area;
- if (painter->hasClipping())
- sysRgn &= painter->clipRegion().translated(redirectionDelta);
- SelectClipRgn(dc, sysRgn.handle());
-
-#ifdef DEBUG_XP_STYLE
- printf("---[ DIRECT PAINTING ]------------------> Name(%-10s) Part(%d) State(%d)\n",
- qPrintable(themeData.name), themeData.partId, themeData.stateId);
- showProperties(themeData);
-#endif
-
- RECT drawRECT = themeData.toRECT(area);
- DTBGOPTS drawOptions;
- drawOptions.dwSize = sizeof(drawOptions);
- drawOptions.rcClip = themeData.toRECT(sysRgn.boundingRect());
- drawOptions.dwFlags = DTBG_CLIPRECT
- | (themeData.noBorder ? DTBG_OMITBORDER : 0)
- | (themeData.noContent ? DTBG_OMITCONTENT : 0)
- | (themeData.mirrorHorizontally ? DTBG_MIRRORDC : 0);
-
- if (pDrawThemeBackgroundEx != 0) {
- pDrawThemeBackgroundEx(themeData.handle(), dc, themeData.partId, themeData.stateId, &(drawRECT), &drawOptions);
- } else {
- // We are running on a system where the uxtheme.dll does not have
- // the DrawThemeBackgroundEx function, so we need to clip away
- // borders or contents manually. All flips and mirrors uses the
- // fallback implementation
-
- int borderSize = 0;
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, TMT_BORDERSIZE, &origin);
- pGetThemeInt(themeData.handle(), themeData.partId, themeData.stateId, TMT_BORDERSIZE, &borderSize);
-
- // Clip away border region
- QRegion extraClip = sysRgn;
- if ((origin == PO_CLASS || origin == PO_PART || origin == PO_STATE) && borderSize > 0) {
- if (themeData.noBorder) {
- // extraClip &= area is already done
- drawRECT = themeData.toRECT(area.adjusted(-borderSize, -borderSize, borderSize, borderSize));
- }
-
- // Clip away content region
- if (themeData.noContent) {
- QRegion content = area.adjusted(borderSize, borderSize, -borderSize, -borderSize);
- extraClip ^= content;
- }
-
- // Set the clip region, if used..
- if (themeData.noBorder || themeData.noContent)
- SelectClipRgn(dc, extraClip.handle());
- }
-
- pDrawThemeBackground(themeData.handle(), dc, themeData.partId, themeData.stateId, &(drawRECT), &(drawOptions.rcClip));
- }
- SelectClipRgn(dc, 0);
-}
-
-/*! \internal
- This function uses a secondary Native doublebuffer for painting parts.
- It should only be used when the painteengine doesn't provide a proper
- HDC for direct painting (e.g. when doing a grabWidget(), painting to
- other pixmaps etc), or when special transformations are needed (e.g.
- flips (horizonal mirroring only, vertical are handled by the theme
- engine).
-*/
-void QWindowsXPStylePrivate::drawBackgroundThruNativeBuffer(XPThemeData &themeData)
-{
- QPainter *painter = themeData.painter;
- QRect rect = themeData.rect;
-
- if ((themeData.rotate + 90) % 180 == 0) { // Catch 90,270,etc.. degree flips.
- rect = QRect(0, 0, rect.height(), rect.width());
- }
- rect.moveTo(0,0);
- int partId = themeData.partId;
- int stateId = themeData.stateId;
- int w = rect.width();
- int h = rect.height();
-
- // Values initialized later, either from cached values, or from function calls
- AlphaChannelType alphaType = UnknownAlpha;
- bool stateHasData = true; // We assume so;
- bool hasAlpha = false;
- bool partIsTransparent;
- bool inspectData;
- bool potentialInvalidAlpha;
-
- QString pixmapCacheKey = QString::fromLatin1("$qt_xp_%1p%2s%3s%4b%5c%6w%7h").arg(themeData.name)
- .arg(partId).arg(stateId).arg(!themeData.noBorder).arg(!themeData.noContent)
- .arg(w).arg(h);
- QPixmap cachedPixmap;
- ThemeMapKey key(themeData);
- ThemeMapData data = alphaCache.value(key);
-
- bool haveCachedPixmap = false;
- bool isCached = data.dataValid;
- if (isCached) {
- if (!(stateHasData = data.hasAnyData))
- return; // Cached NOOP
- inspectData = data.wasAlphaSwapped;
- partIsTransparent = data.partIsTransparent;
- hasAlpha = data.hasAlphaChannel;
- alphaType = data.alphaType;
- potentialInvalidAlpha = data.hadInvalidAlpha;
-
- haveCachedPixmap = QPixmapCache::find(pixmapCacheKey, cachedPixmap);
-
-#ifdef DEBUG_XP_STYLE
- char buf[25];
- ::sprintf(buf, "+ Pixmap(%3d, %3d) ]", w, h);
- printf("---[ CACHED %s--------> Name(%-10s) Part(%d) State(%d)\n",
- haveCachedPixmap ? buf : "]-------------------",
- qPrintable(themeData.name), themeData.partId, themeData.stateId);
-#endif
- } else {
- // Not cached, so get values from Theme Engine
- BOOL tmt_borderonly = false;
- COLORREF tmt_transparentcolor = 0x0;
- PROPERTYORIGIN proporigin = PO_NOTFOUND;
- pGetThemeBool(themeData.handle(), themeData.partId, themeData.stateId, TMT_BORDERONLY, &tmt_borderonly);
- pGetThemeColor(themeData.handle(), themeData.partId, themeData.stateId, TMT_TRANSPARENTCOLOR, &tmt_transparentcolor);
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, TMT_CAPTIONMARGINS, &proporigin);
- inspectData = (tmt_transparentcolor != 0 || tmt_borderonly || proporigin == PO_PART || proporigin == PO_STATE);
-
- // ### This is a vista-specific workaround for broken alpha in titlebar pixmaps
- if ((QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) {
- if (themeData.partId == WP_CAPTION || themeData.partId == WP_SMALLCAPTION)
- inspectData = false;
- }
-
- partIsTransparent = isTransparent(themeData);
-
- potentialInvalidAlpha = false;
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, TMT_GLYPHTYPE, &proporigin);
- if (proporigin == PO_PART || proporigin == PO_STATE) {
- int tmt_glyphtype = GT_NONE;
- pGetThemeEnumValue(themeData.handle(), themeData.partId, themeData.stateId, TMT_GLYPHTYPE, &tmt_glyphtype);
- potentialInvalidAlpha = partIsTransparent && !inspectData && tmt_glyphtype == GT_IMAGEGLYPH;
- }
-
-#ifdef DEBUG_XP_STYLE
- printf("---[ NOT CACHED ]-----------------------> Name(%-10s) Part(%d) State(%d)\n",
- qPrintable(themeData.name), themeData.partId, themeData.stateId);
- printf("-->partIsTransparen = %d\n", partIsTransparent);
- printf("-->inspectData = %d\n", inspectData);
- printf("-->potentialInvalidAlpha = %d\n", potentialInvalidAlpha);
- showProperties(themeData);
-#endif
- }
- bool wasAlphaSwapped = false;
- bool wasAlphaFixed = false;
-
- // OLD PSDK Workaround ------------------------------------------------------------------------
- // See if we need extra clipping for the older PSDK, which does
- // not have a DrawThemeBackgroundEx function for DTGB_OMITBORDER
- // and DTGB_OMITCONTENT
- bool addBorderContentClipping = false;
- QRegion extraClip;
- QRect area = rect;
- if (themeData.noBorder || themeData.noContent) {
- extraClip = area;
- // We are running on a system where the uxtheme.dll does not have
- // the DrawThemeBackgroundEx function, so we need to clip away
- // borders or contents manually.
-
- int borderSize = 0;
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, TMT_BORDERSIZE, &origin);
- pGetThemeInt(themeData.handle(), themeData.partId, themeData.stateId, TMT_BORDERSIZE, &borderSize);
-
- // Clip away border region
- if ((origin == PO_CLASS || origin == PO_PART || origin == PO_STATE) && borderSize > 0) {
- if (themeData.noBorder) {
- extraClip &= area;
- area = area.adjusted(-borderSize, -borderSize, borderSize, borderSize);
- }
-
- // Clip away content region
- if (themeData.noContent) {
- QRegion content = area.adjusted(borderSize, borderSize, -borderSize, -borderSize);
- extraClip ^= content;
- }
- }
- addBorderContentClipping = (themeData.noBorder | themeData.noContent);
- }
-
- QImage img;
- if (!haveCachedPixmap) { // If the pixmap is not cached, generate it! -------------------------
- buffer(w, h); // Ensure a buffer of at least (w, h) in size
- HDC dc = bufferHDC();
-
- // Clear the buffer
- if (alphaType != NoAlpha) {
- // Consider have separate "memset" function for small chunks for more speedup
- memset(bufferPixels, inspectData ? 0xFF : 0x00, bufferW * h * 4);
- }
-
- // Difference between area and rect
- int dx = area.x() - rect.x();
- int dy = area.y() - rect.y();
- int dr = area.right() - rect.right();
- int db = area.bottom() - rect.bottom();
-
- // Adjust so painting rect starts from Origo
- rect.moveTo(0,0);
- area.moveTo(dx,dy);
- DTBGOPTS drawOptions;
- drawOptions.dwSize = sizeof(drawOptions);
- drawOptions.rcClip = themeData.toRECT(rect);
- drawOptions.dwFlags = DTBG_CLIPRECT
- | (themeData.noBorder ? DTBG_OMITBORDER : 0)
- | (themeData.noContent ? DTBG_OMITCONTENT : 0);
-
- // Drawing the part into the backing store
- if (pDrawThemeBackgroundEx != 0) {
- RECT rect(themeData.toRECT(area));
- pDrawThemeBackgroundEx(themeData.handle(), dc, themeData.partId, themeData.stateId, &rect, &drawOptions);
- } else {
- // Set the clip region, if used..
- if (addBorderContentClipping) {
- SelectClipRgn(dc, extraClip.handle());
- // Compensate for the noBorder area difference (noContent has the same area)
- drawOptions.rcClip = themeData.toRECT(rect.adjusted(dx, dy, dr, db));
- }
-
- pDrawThemeBackground(themeData.handle(), dc, themeData.partId, themeData.stateId, &(drawOptions.rcClip), 0);
-
- if (addBorderContentClipping)
- SelectClipRgn(dc, 0);
- }
-
- // If not cached, analyze the buffer data to figure
- // out alpha type, and if it contains data
- if (!isCached) {
- if (inspectData)
- stateHasData = hasAnyData(rect);
- // SHORTCUT: If the part's state has no data, cache it for NOOP later
- if (!stateHasData) {
- memset(&data, 0, sizeof(data));
- data.dataValid = true;
- alphaCache.insert(key, data);
- return;
- }
- hasAlpha = hasAlphaChannel(rect);
- if (!hasAlpha && partIsTransparent)
- potentialInvalidAlpha = true;
-#if defined(DEBUG_XP_STYLE) && 1
- dumpNativeDIB(w, h);
-#endif
- }
-
- // Swap alpha values, if needed
- if (inspectData)
- wasAlphaSwapped = swapAlphaChannel(rect);
-
- // Fix alpha values, if needed
- if (potentialInvalidAlpha)
- wasAlphaFixed = fixAlphaChannel(rect);
-
- QImage::Format format;
- if ((partIsTransparent && !wasAlphaSwapped) || (!partIsTransparent && hasAlpha)) {
- format = QImage::Format_ARGB32_Premultiplied;
- alphaType = RealAlpha;
- } else if (wasAlphaSwapped) {
- format = QImage::Format_ARGB32_Premultiplied;
- alphaType = MaskAlpha;
- } else {
- format = QImage::Format_RGB32;
- // The image data we got from the theme engine does not have any transparency,
- // thus the alpha channel is set to 0.
- // However, Format_RGB32 requires the alpha part to be set to 0xff, thus
- // we must flip it from 0x00 to 0xff
- swapAlphaChannel(rect, true);
- alphaType = NoAlpha;
- }
-#if defined(DEBUG_XP_STYLE) && 1
- printf("Image format is: %s\n", alphaType == RealAlpha ? "Real Alpha" : alphaType == MaskAlpha ? "Masked Alpha" : "No Alpha");
-#endif
- img = QImage(bufferPixels, bufferW, bufferH, format);
- }
-
- // Blitting backing store
- bool useRegion = partIsTransparent && !hasAlpha && !wasAlphaSwapped;
-
- QRegion newRegion;
- QRegion oldRegion;
- if (useRegion) {
- newRegion = region(themeData);
- oldRegion = painter->clipRegion();
- painter->setClipRegion(newRegion);
-#if defined(DEBUG_XP_STYLE) && 0
- printf("Using region:\n");
- QVector<QRect> rects = newRegion.rects();
- for (int i = 0; i < rects.count(); ++i) {
- const QRect &r = rects.at(i);
- printf(" (%d, %d, %d, %d)\n", r.x(), r.y(), r.right(), r.bottom());
- }
-#endif
- }
-
- if (addBorderContentClipping)
- painter->setClipRegion(extraClip, Qt::IntersectClip);
-
- if (!themeData.mirrorHorizontally && !themeData.mirrorVertically && !themeData.rotate) {
- if (!haveCachedPixmap)
- painter->drawImage(themeData.rect, img, rect);
- else
- painter->drawPixmap(themeData.rect, cachedPixmap);
- } else {
- // This is _slow_!
- // Make a copy containing only the necessary data, and mirror
- // on all wanted axes. Then draw the copy.
- // If cached, the normal pixmap is cached, instead of caching
- // all possible orientations for each part and state.
- QImage imgCopy;
- if (!haveCachedPixmap)
- imgCopy = img.copy(rect);
- else
- imgCopy = cachedPixmap.toImage();
-
- if (themeData.rotate) {
- QMatrix rotMatrix;
- rotMatrix.rotate(themeData.rotate);
- imgCopy = imgCopy.transformed(rotMatrix);
- }
- if (themeData.mirrorHorizontally || themeData.mirrorVertically) {
- imgCopy = imgCopy.mirrored(themeData.mirrorHorizontally, themeData.mirrorVertically);
- }
- painter->drawImage(themeData.rect,
- imgCopy);
- }
-
- if (useRegion || addBorderContentClipping) {
- if (oldRegion.isEmpty())
- painter->setClipping(false);
- else
- painter->setClipRegion(oldRegion);
- }
-
- // Cache the pixmap to avoid expensive swapAlphaChannel() calls
- if (!haveCachedPixmap && w && h) {
- QPixmap pix = QPixmap::fromImage(img).copy(rect);
- QPixmapCache::insert(pixmapCacheKey, pix);
-#ifdef DEBUG_XP_STYLE
- printf("+++Adding pixmap to cache, size(%d, %d), wasAlphaSwapped(%d), wasAlphaFixed(%d), name(%s)\n",
- w, h, wasAlphaSwapped, wasAlphaFixed, qPrintable(pixmapCacheKey));
-#endif
- }
-
- // Add to theme part cache
- if (!isCached) {
- memset(&data, 0, sizeof(data));
- data.dataValid = true;
- data.partIsTransparent = partIsTransparent;
- data.alphaType = alphaType;
- data.hasAlphaChannel = hasAlpha;
- data.hasAnyData = stateHasData;
- data.wasAlphaSwapped = wasAlphaSwapped;
- data.hadInvalidAlpha = wasAlphaFixed;
- alphaCache.insert(key, data);
- }
-}
-
-
-// ------------------------------------------------------------------------------------------------
-
-/*!
- \class QWindowsXPStyle
- \brief The QWindowsXPStyle class provides a Microsoft Windows XP-like look and feel.
-
- \ingroup appearance
-
- \warning This style is only available on the Windows XP platform
- because it makes use of Windows XP's style engine.
-
- Most of the functions are documented in the base classes
- QWindowsStyle, QCommonStyle, and QStyle, but the
- QWindowsXPStyle overloads of drawComplexControl(), drawControl(),
- drawControlMask(), drawPrimitive(), proxy()->subControlRect(), and
- sizeFromContents(), are documented here.
-
- \img qwindowsxpstyle.png
- \sa QMacStyle, QWindowsStyle, QPlastiqueStyle, QCDEStyle, QMotifStyle
-*/
-
-/*!
- Constructs a QWindowsStyle
-*/
-QWindowsXPStyle::QWindowsXPStyle()
- : QWindowsStyle(*new QWindowsXPStylePrivate)
-{
-}
-
-/*!
- Destroys the style.
-*/
-QWindowsXPStyle::~QWindowsXPStyle()
-{
-}
-
-/*! \reimp */
-void QWindowsXPStyle::unpolish(QApplication *app)
-{
- QWindowsStyle::unpolish(app);
-}
-
-/*! \reimp */
-void QWindowsXPStyle::polish(QApplication *app)
-{
- QWindowsStyle::polish(app);
- if (!QWindowsXPStylePrivate::useXP())
- return;
-}
-
-/*! \reimp */
-void QWindowsXPStyle::polish(QWidget *widget)
-{
- QWindowsStyle::polish(widget);
- if (!QWindowsXPStylePrivate::useXP())
- return;
-
- if (qobject_cast<QAbstractButton*>(widget)
- || qobject_cast<QToolButton*>(widget)
- || qobject_cast<QTabBar*>(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<QComboBox*>(widget)
-#endif // QT_NO_COMBOBOX
- || qobject_cast<QScrollBar*>(widget)
- || qobject_cast<QSlider*>(widget)
- || qobject_cast<QHeaderView*>(widget)
-#ifndef QT_NO_SPINBOX
- || qobject_cast<QAbstractSpinBox*>(widget)
- || qobject_cast<QSpinBox*>(widget)
-#endif // QT_NO_SPINBOX
- || widget->inherits("QWorkspaceChild")
- || widget->inherits("Q3TitleBar"))
- widget->setAttribute(Qt::WA_Hover);
-
-#ifndef QT_NO_RUBBERBAND
- if (qobject_cast<QRubberBand*>(widget)) {
- widget->setWindowOpacity(0.6);
- }
-#endif
- if (qobject_cast<QStackedWidget*>(widget) &&
- qobject_cast<QTabWidget*>(widget->parent()))
- widget->parentWidget()->setAttribute(Qt::WA_ContentsPropagated);
-
- Q_D(QWindowsXPStyle);
- if (!d->hasInitColors) {
- // Get text color for group box labels
- COLORREF cref;
- XPThemeData theme(0, 0, QLatin1String("BUTTON"), 0, 0);
- pGetThemeColor(theme.handle(), BP_GROUPBOX, GBS_NORMAL, TMT_TEXTCOLOR, &cref);
- d->groupBoxTextColor = qRgb(GetRValue(cref), GetGValue(cref), GetBValue(cref));
- pGetThemeColor(theme.handle(), BP_GROUPBOX, GBS_DISABLED, TMT_TEXTCOLOR, &cref);
- d->groupBoxTextColorDisabled = qRgb(GetRValue(cref), GetGValue(cref), GetBValue(cref));
- // Where does this color come from?
- //pGetThemeColor(theme.handle(), TKP_TICS, TSS_NORMAL, TMT_COLOR, &cref);
- d->sliderTickColor = qRgb(165, 162, 148);
- d->hasInitColors = true;
- }
-}
-
-/*! \reimp */
-void QWindowsXPStyle::polish(QPalette &pal)
-{
- QWindowsStyle::polish(pal);
- pal.setBrush(QPalette::AlternateBase, pal.base().color().darker(110));
-}
-
-/*! \reimp */
-void QWindowsXPStyle::unpolish(QWidget *widget)
-{
-#ifndef QT_NO_RUBBERBAND
- if (qobject_cast<QRubberBand*>(widget)) {
- widget->setWindowOpacity(1.0);
- }
-#endif
- Q_D(QWindowsXPStyle);
- // Unpolish of widgets is the first thing that
- // happens when a theme changes, or the theme
- // engine is turned off. So we detect it here.
- bool oldState = QWindowsXPStylePrivate::useXP();
- bool newState = QWindowsXPStylePrivate::useXP(true);
- if ((oldState != newState) && newState) {
- d->cleanup(true);
- d->init(true);
- } else {
- // Cleanup handle map, if just changing style,
- // or turning it on. In both cases the values
- // already in the map might be old (other style).
- d->cleanupHandleMap();
- }
- if (qobject_cast<QAbstractButton*>(widget)
- || qobject_cast<QToolButton*>(widget)
- || qobject_cast<QTabBar*>(widget)
-#ifndef QT_NO_COMBOBOX
- || qobject_cast<QComboBox*>(widget)
-#endif // QT_NO_COMBOBOX
- || qobject_cast<QScrollBar*>(widget)
- || qobject_cast<QSlider*>(widget)
- || qobject_cast<QHeaderView*>(widget)
-#ifndef QT_NO_SPINBOX
- || qobject_cast<QAbstractSpinBox*>(widget)
- || qobject_cast<QSpinBox*>(widget)
-#endif // QT_NO_SPINBOX
- || widget->inherits("QWorkspaceChild")
- || widget->inherits("Q3TitleBar"))
- widget->setAttribute(Qt::WA_Hover, false);
- QWindowsStyle::unpolish(widget);
-}
-
-/*! \reimp */
-QRect QWindowsXPStyle::subElementRect(SubElement sr, const QStyleOption *option, const QWidget *widget) const
-{
- if (!QWindowsXPStylePrivate::useXP()) {
- return QWindowsStyle::subElementRect(sr, option, widget);
- }
-
- QRect rect(option->rect);
- switch(sr) {
- case SE_DockWidgetCloseButton:
- case SE_DockWidgetFloatButton:
- rect = QWindowsStyle::subElementRect(sr, option, widget);
- return rect.translated(0, 1);
- break;
- case SE_TabWidgetTabContents:
- if (qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option))
- {
- rect = QWindowsStyle::subElementRect(sr, option, widget);
- if (sr == SE_TabWidgetTabContents)
- rect.adjust(0, 0, -2, -2);
- }
- break;
- case SE_TabWidgetTabBar: {
- rect = QWindowsStyle::subElementRect(sr, option, widget);
- const QStyleOptionTabWidgetFrame *twfOption =
- qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option);
- if (twfOption && twfOption->direction == Qt::RightToLeft
- && (twfOption->shape == QTabBar::RoundedNorth
- || twfOption->shape == QTabBar::RoundedSouth))
- {
- QStyleOptionTab otherOption;
- otherOption.shape = (twfOption->shape == QTabBar::RoundedNorth
- ? QTabBar::RoundedEast : QTabBar::RoundedSouth);
- int overlap = proxy()->pixelMetric(PM_TabBarBaseOverlap, &otherOption, widget);
- int borderThickness = proxy()->pixelMetric(PM_DefaultFrameWidth, option, widget);
- rect.adjust(-overlap + borderThickness, 0, -overlap + borderThickness, 0);
- }
- break;}
-
- case SE_PushButtonContents:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
- MARGINS borderSize;
- if (widget) {
- XPThemeData buttontheme(widget, 0, QLatin1String("Button"));
- HTHEME theme = buttontheme.handle();
- if (theme) {
- int stateId;
- if (!(option->state & State_Enabled))
- stateId = PBS_DISABLED;
- else if (option->state & State_Sunken)
- stateId = PBS_PRESSED;
- else if (option->state & State_MouseOver)
- stateId = PBS_HOT;
- else if (btn->features & QStyleOptionButton::DefaultButton)
- stateId = PBS_DEFAULTED;
- else
- stateId = PBS_NORMAL;
-
- int border = proxy()->pixelMetric(PM_DefaultFrameWidth, btn, widget);
- rect = option->rect.adjusted(border, border, -border, -border);
-
- int result = pGetThemeMargins(theme,
- NULL,
- BP_PUSHBUTTON,
- stateId,
- TMT_CONTENTMARGINS,
- NULL,
- &borderSize);
-
- if (result == S_OK) {
- rect.adjust(borderSize.cxLeftWidth, borderSize.cyTopHeight,
- -borderSize.cxRightWidth, -borderSize.cyBottomHeight);
- rect = visualRect(option->direction, option->rect, rect);
- }
- }
- }
- }
- break;
- case SE_ProgressBarContents:
- rect = QCommonStyle::subElementRect(SE_ProgressBarGroove, option, widget);
- if (option->state & QStyle::State_Horizontal)
- rect.adjust(4, 3, -4, -3);
- else
- rect.adjust(3, 2, -3, -2);
- break;
- default:
- rect = QWindowsStyle::subElementRect(sr, option, widget);
- }
- return rect;
-}
-
-/*!
- \reimp
-*/
-void QWindowsXPStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *option, QPainter *p,
- const QWidget *widget) const
-{
- QWindowsXPStylePrivate *d = const_cast<QWindowsXPStylePrivate*>(d_func());
-
- if (!QWindowsXPStylePrivate::useXP()) {
- QWindowsStyle::drawPrimitive(pe, option, p, widget);
- return;
- }
-
- QString name;
- int partId = 0;
- int stateId = 0;
- QRect rect = option->rect;
- State flags = option->state;
- bool hMirrored = false;
- bool vMirrored = false;
- bool noBorder = false;
- bool noContent = false;
- int rotate = 0;
-
- switch (pe) {
- case PE_FrameTabBarBase:
- if (const QStyleOptionTabBarBase *tbb
- = qstyleoption_cast<const QStyleOptionTabBarBase *>(option)) {
- p->save();
- switch (tbb->shape) {
- case QTabBar::RoundedNorth:
- p->setPen(QPen(tbb->palette.dark(), 0));
- p->drawLine(tbb->rect.topLeft(), tbb->rect.topRight());
- break;
- case QTabBar::RoundedWest:
- p->setPen(QPen(tbb->palette.dark(), 0));
- p->drawLine(tbb->rect.left(), tbb->rect.top(), tbb->rect.left(), tbb->rect.bottom());
- break;
- case QTabBar::RoundedSouth:
- p->setPen(QPen(tbb->palette.dark(), 0));
- p->drawLine(tbb->rect.left(), tbb->rect.top(),
- tbb->rect.right(), tbb->rect.top());
- break;
- case QTabBar::RoundedEast:
- p->setPen(QPen(tbb->palette.dark(), 0));
- p->drawLine(tbb->rect.topLeft(), tbb->rect.bottomLeft());
- break;
- case QTabBar::TriangularNorth:
- case QTabBar::TriangularEast:
- case QTabBar::TriangularWest:
- case QTabBar::TriangularSouth:
- p->restore();
- QWindowsStyle::drawPrimitive(pe, option, p, widget);
- return;
- }
- p->restore();
- }
- return;
- case PE_PanelButtonBevel:
- name = QLatin1String("BUTTON");
- partId = BP_PUSHBUTTON;
- if (!(flags & State_Enabled))
- stateId = PBS_DISABLED;
- else if ((flags & State_Sunken) || (flags & State_On))
- stateId = PBS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = PBS_HOT;
- //else if (flags & State_ButtonDefault)
- // stateId = PBS_DEFAULTED;
- else
- stateId = PBS_NORMAL;
- break;
-
- case PE_PanelButtonTool:
- if (widget && widget->inherits("QDockWidgetTitleButton")) {
- if (const QWidget *dw = widget->parentWidget())
- if (dw->isWindow())
- return;
- }
- name = QLatin1String("TOOLBAR");
- partId = TP_BUTTON;
- if (!(flags & State_Enabled))
- stateId = TS_DISABLED;
- else if (flags & State_Sunken)
- stateId = TS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = flags & State_On ? TS_HOTCHECKED : TS_HOT;
- else if (flags & State_On)
- stateId = TS_CHECKED;
- else if (!(flags & State_AutoRaise))
- stateId = TS_HOT;
- else
- stateId = TS_NORMAL;
- break;
-
- case PE_IndicatorButtonDropDown:
- name = QLatin1String("TOOLBAR");
- partId = TP_SPLITBUTTONDROPDOWN;
- if (!(flags & State_Enabled))
- stateId = TS_DISABLED;
- else if (flags & State_Sunken)
- stateId = TS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = flags & State_On ? TS_HOTCHECKED : TS_HOT;
- else if (flags & State_On)
- stateId = TS_CHECKED;
- else if (!(flags & State_AutoRaise))
- stateId = TS_HOT;
- else
- stateId = TS_NORMAL;
- if (option->direction == Qt::RightToLeft)
- hMirrored = true;
- break;
-
- case PE_IndicatorCheckBox:
- name = QLatin1String("BUTTON");
- partId = BP_CHECKBOX;
- if (!(flags & State_Enabled))
- stateId = CBS_UNCHECKEDDISABLED;
- else if (flags & State_Sunken)
- stateId = CBS_UNCHECKEDPRESSED;
- else if (flags & State_MouseOver)
- stateId = CBS_UNCHECKEDHOT;
- else
- stateId = CBS_UNCHECKEDNORMAL;
-
- if (flags & State_On)
- stateId += CBS_CHECKEDNORMAL-1;
- else if (flags & State_NoChange)
- stateId += CBS_MIXEDNORMAL-1;
-
- break;
-
- case PE_IndicatorRadioButton:
- name = QLatin1String("BUTTON");
- partId = BP_RADIOBUTTON;
- if (!(flags & State_Enabled))
- stateId = RBS_UNCHECKEDDISABLED;
- else if (flags & State_Sunken)
- stateId = RBS_UNCHECKEDPRESSED;
- else if (flags & State_MouseOver)
- stateId = RBS_UNCHECKEDHOT;
- else
- stateId = RBS_UNCHECKEDNORMAL;
-
- if (flags & State_On)
- stateId += RBS_CHECKEDNORMAL-1;
- break;
-
- case PE_IndicatorDockWidgetResizeHandle:
- return;
-
-case PE_Frame:
- {
- if (flags & State_Raised)
- return;
- name = QLatin1String("LISTVIEW");
- partId = LVP_LISTGROUP;
- XPThemeData theme(0, 0, name, partId, 0);
-
- if (!(flags & State_Enabled))
- stateId = ETS_DISABLED;
- else
- stateId = ETS_NORMAL;
- int fillType;
- if (pGetThemeEnumValue(theme.handle(), partId, stateId, TMT_BGTYPE, &fillType) == S_OK) {
- if (fillType == BT_BORDERFILL) {
- COLORREF bcRef;
- pGetThemeColor(theme.handle(), partId, stateId, TMT_BORDERCOLOR, &bcRef);
- QColor bordercolor(qRgb(GetRValue(bcRef), GetGValue(bcRef), GetBValue(bcRef)));
- QPen oldPen = p->pen();
- // int borderSize = 1;
- // pGetThemeInt(theme.handle(), partId, stateId, TMT_BORDERCOLOR, &borderSize);
-
- // Inner white border
- p->setPen(QPen(option->palette.base().color(), 1));
- p->drawRect(option->rect.adjusted(1, 1, -2, -2));
- // Outer dark border
- p->setPen(QPen(bordercolor, 1));
- p->drawRect(option->rect.adjusted(0, 0, -1, -1));
- p->setPen(oldPen);
- return;
- } else if (fillType == BT_NONE) {
- return;
- } else {
- break;
- }
- }
- }
- case PE_FrameLineEdit: {
- // we try to check if this lineedit is a delegate on a QAbstractItemView-derived class.
- QWidget *parentWidget = 0;
- if (widget)
- parentWidget = widget->parentWidget();
- if (parentWidget)
- parentWidget = parentWidget->parentWidget();
- if (widget && widget->inherits("QLineEdit")
- && parentWidget && parentWidget->inherits("QAbstractItemView")) {
- QPen oldPen = p->pen();
- // Inner white border
- p->setPen(QPen(option->palette.base().color(), 1));
- p->drawRect(option->rect.adjusted(1, 1, -2, -2));
- // Outer dark border
- p->setPen(QPen(option->palette.shadow().color(), 1));
- p->drawRect(option->rect.adjusted(0, 0, -1, -1));
- p->setPen(oldPen);
- return;
- } else if (qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- name = QLatin1String("EDIT");
- partId = EP_EDITTEXT;
- noContent = true;
- if (!(flags & State_Enabled))
- stateId = ETS_DISABLED;
- else
- stateId = ETS_NORMAL;
- }
- break;
- }
-
- case PE_PanelLineEdit:
- if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- name = QLatin1String("EDIT");
- partId = EP_EDITTEXT;
- noBorder = true;
- QBrush bg;
- bool usePalette = false;
- bool isEnabled = flags & State_Enabled;
- uint resolve_mask = panel->palette.resolve();
-
-#ifndef QT_NO_SPINBOX
- //Since spin box includes a line edit we need to resolve the palette on the spin box instead
- if (widget) {
- if (QAbstractSpinBox *spinbox = qobject_cast<QAbstractSpinBox*>(widget->parentWidget()))
- resolve_mask = spinbox->palette().resolve();
- }
-#endif // QT_NO_SPINBOX
- if (resolve_mask & (1 << QPalette::Base)) {
- // Base color is set for this widget, so use it
- bg = panel->palette.brush(QPalette::Base);
- usePalette = true;
- }
-
- stateId = isEnabled ? ETS_NORMAL : ETS_DISABLED;
-
- if (usePalette) {
- p->fillRect(panel->rect, bg);
- } else {
- XPThemeData theme(0, p, name, partId, stateId, rect);
- if (!theme.isValid()) {
- QWindowsStyle::drawPrimitive(pe, option, p, widget);
- return;
- }
- int bgType;
- pGetThemeEnumValue( theme.handle(),
- partId,
- stateId,
- TMT_BGTYPE,
- &bgType);
- if( bgType == BT_IMAGEFILE ) {
- theme.mirrorHorizontally = hMirrored;
- theme.mirrorVertically = vMirrored;
- theme.noBorder = noBorder;
- theme.noContent = noContent;
- theme.rotate = rotate;
- d->drawBackground(theme);
- } else {
- QBrush fillColor = option->palette.brush(QPalette::Base);
-
- if (!isEnabled) {
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(theme.handle(), theme.partId, theme.stateId, TMT_FILLCOLOR, &origin);
- // Use only if the fill property comes from our part
- if ((origin == PO_PART || origin == PO_STATE)) {
- COLORREF bgRef;
- pGetThemeColor(theme.handle(), partId, stateId, TMT_FILLCOLOR, &bgRef);
- fillColor = QBrush(qRgb(GetRValue(bgRef), GetGValue(bgRef), GetBValue(bgRef)));
- }
- }
- p->fillRect(option->rect, fillColor);
- }
- }
-
- if (panel->lineWidth > 0)
- proxy()->drawPrimitive(PE_FrameLineEdit, panel, p, widget);
- return;
- }
- break;
-
- case PE_FrameTabWidget:
- if (const QStyleOptionTabWidgetFrame *tab = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option))
- {
- name = QLatin1String("TAB");
- partId = TABP_PANE;
-
- if (widget) {
- bool useGradient = true;
- const int maxlength = 256;
- wchar_t themeFileName[maxlength];
- wchar_t themeColor[maxlength];
- // Due to a a scaling issue with the XP Silver theme, tab gradients are not used with it
- if (pGetCurrentThemeName(themeFileName, maxlength, themeColor, maxlength, NULL, 0) == S_OK) {
- wchar_t *offset = 0;
- if ((offset = wcsrchr(themeFileName, QChar(QLatin1Char('\\')).unicode())) != NULL) {
- offset++;
- if (!lstrcmp(offset, L"Luna.msstyles") && !lstrcmp(offset, L"Metallic")) {
- useGradient = false;
- }
- }
- }
- // This should work, but currently there's an error in the ::drawBackgroundDirectly()
- // code, when using the HDC directly..
- if (useGradient) {
- QStyleOptionTabWidgetFrameV2 frameOpt = *tab;
- frameOpt.rect = widget->rect();
- QRect contentsRect = subElementRect(SE_TabWidgetTabContents, &frameOpt, widget);
- QRegion reg = option->rect;
- reg -= contentsRect;
- p->setClipRegion(reg);
- XPThemeData theme(widget, p, name, partId, stateId, rect);
- theme.mirrorHorizontally = hMirrored;
- theme.mirrorVertically = vMirrored;
- d->drawBackground(theme);
- p->setClipRect(contentsRect);
- partId = TABP_BODY;
- }
- }
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- vMirrored = true;
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- rotate = 90;
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- rotate = 90;
- hMirrored = true;
- break;
- default:
- break;
- }
- }
- break;
-
- case PE_FrameMenu:
- p->save();
- p->setPen(option->palette.dark().color());
- p->drawRect(rect.adjusted(0, 0, -1, -1));
- p->restore();
- return;
-
- case PE_PanelMenuBar:
- break;
-
- case PE_FrameDockWidget:
- if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(option))
- {
- name = QLatin1String("WINDOW");
- if (flags & State_Active)
- stateId = FS_ACTIVE;
- else
- stateId = FS_INACTIVE;
-
- int fwidth = proxy()->pixelMetric(PM_DockWidgetFrameWidth, frm, widget);
-
- XPThemeData theme(widget, p, name, 0, stateId);
- if (!theme.isValid())
- break;
- theme.rect = QRect(frm->rect.x(), frm->rect.y(), frm->rect.x()+fwidth, frm->rect.height()-fwidth); theme.partId = WP_SMALLFRAMELEFT;
- d->drawBackground(theme);
- theme.rect = QRect(frm->rect.width()-fwidth, frm->rect.y(), fwidth, frm->rect.height()-fwidth);
- theme.partId = WP_SMALLFRAMERIGHT;
- d->drawBackground(theme);
- theme.rect = QRect(frm->rect.x(), frm->rect.bottom()-fwidth+1, frm->rect.width(), fwidth);
- theme.partId = WP_SMALLFRAMEBOTTOM;
- d->drawBackground(theme);
- return;
- }
- break;
-
- case PE_IndicatorHeaderArrow:
- {
-#if 0 // XP theme engine doesn't know about this :(
- name = QLatin1String("HEADER");
- partId = HP_HEADERSORTARROW;
- if (flags & State_Down)
- stateId = HSAS_SORTEDDOWN;
- else
- stateId = HSAS_SORTEDUP;
-#else
- if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
- p->save();
- p->setPen(option->palette.dark().color());
- p->translate(0, option->rect.height()/2 - 4);
- if (header->sortIndicator & QStyleOptionHeader::SortUp) { // invert logic to follow Windows style guide
- p->drawLine(option->rect.x(), option->rect.y(), option->rect.x()+8, option->rect.y());
- p->drawLine(option->rect.x()+1, option->rect.y()+1, option->rect.x()+7, option->rect.y()+1);
- p->drawLine(option->rect.x()+2, option->rect.y()+2, option->rect.x()+6, option->rect.y()+2);
- p->drawLine(option->rect.x()+3, option->rect.y()+3, option->rect.x()+5, option->rect.y()+3);
- p->drawPoint(option->rect.x()+4, option->rect.y()+4);
- } else if(header->sortIndicator & QStyleOptionHeader::SortDown) {
- p->drawLine(option->rect.x(), option->rect.y()+4, option->rect.x()+8, option->rect.y()+4);
- p->drawLine(option->rect.x()+1, option->rect.y()+3, option->rect.x()+7, option->rect.y()+3);
- p->drawLine(option->rect.x()+2, option->rect.y()+2, option->rect.x()+6, option->rect.y()+2);
- p->drawLine(option->rect.x()+3, option->rect.y()+1, option->rect.x()+5, option->rect.y()+1);
- p->drawPoint(option->rect.x()+4, option->rect.y());
- }
- p->restore();
- return;
- }
-#endif
- }
- break;
-
- case PE_FrameStatusBarItem:
- name = QLatin1String("STATUS");
- partId = SP_PANE;
- break;
-
- case PE_FrameGroupBox:
- name = QLatin1String("BUTTON");
- partId = BP_GROUPBOX;
- if (!(flags & State_Enabled))
- stateId = GBS_DISABLED;
- else
- stateId = GBS_NORMAL;
- if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(option)) {
- const QStyleOptionFrameV2 *frame2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(option);
- if (frame2->features & QStyleOptionFrameV2::Flat) {
- // Windows XP does not have a theme part for a flat GroupBox, paint it with the windows style
- QRect fr = frame->rect;
- QPoint p1(fr.x(), fr.y() + 1);
- QPoint p2(fr.x() + fr.width(), p1.y() + 1);
- rect = QRect(p1, p2);
- name = QLatin1String("");
- }
- }
- break;
-
- case PE_IndicatorProgressChunk:
- {
- Qt::Orientation orient = Qt::Horizontal;
- bool inverted = false;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
- orient = pb2->orientation;
- if (pb2->invertedAppearance)
- inverted = true;
- }
- if (orient == Qt::Horizontal) {
- partId = PP_CHUNK;
- rect = QRect(option->rect.x(), option->rect.y(), option->rect.width(), option->rect.height() );
- if (inverted && option->direction == Qt::LeftToRight)
- hMirrored = true;
- } else {
- partId = PP_CHUNKVERT;
- rect = QRect(option->rect.x(), option->rect.y(), option->rect.width(), option->rect.height());
- }
- name = QLatin1String("PROGRESS");
- stateId = 1;
- }
- break;
-
- case PE_Q3DockWindowSeparator:
- name = QLatin1String("TOOLBAR");
- if (flags & State_Horizontal)
- partId = TP_SEPARATOR;
- else
- partId = TP_SEPARATORVERT;
- break;
-
- case PE_FrameWindow:
- if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(option))
- {
- name = QLatin1String("WINDOW");
- if (flags & State_Active)
- stateId = FS_ACTIVE;
- else
- stateId = FS_INACTIVE;
-
- int fwidth = frm->lineWidth + frm->midLineWidth;
-
- XPThemeData theme(0, p, name, 0, stateId);
- if (!theme.isValid())
- break;
-
- theme.rect = QRect(option->rect.x(), option->rect.y()+fwidth, option->rect.x()+fwidth, option->rect.height()-fwidth);
- theme.partId = WP_FRAMELEFT;
- d->drawBackground(theme);
- theme.rect = QRect(option->rect.width()-fwidth, option->rect.y()+fwidth, fwidth, option->rect.height()-fwidth);
- theme.partId = WP_FRAMERIGHT;
- d->drawBackground(theme);
- theme.rect = QRect(option->rect.x(), option->rect.height()-fwidth, option->rect.width(), fwidth);
- theme.partId = WP_FRAMEBOTTOM;
- d->drawBackground(theme);
- theme.rect = QRect(option->rect.x(), option->rect.y(), option->rect.width(), option->rect.y()+fwidth);
- theme.partId = WP_CAPTION;
- d->drawBackground(theme);
- return;
- }
- break;
-
- case PE_IndicatorBranch:
- {
- static const int decoration_size = 9;
- int mid_h = option->rect.x() + option->rect.width() / 2;
- int mid_v = option->rect.y() + option->rect.height() / 2;
- int bef_h = mid_h;
- int bef_v = mid_v;
- int aft_h = mid_h;
- int aft_v = mid_v;
- QBrush brush(option->palette.dark().color(), Qt::Dense4Pattern);
- if (option->state & State_Item) {
- if (option->direction == Qt::RightToLeft)
- p->fillRect(option->rect.left(), mid_v, bef_h - option->rect.left(), 1, brush);
- else
- p->fillRect(aft_h, mid_v, option->rect.right() - aft_h + 1, 1, brush);
- }
- if (option->state & State_Sibling)
- p->fillRect(mid_h, aft_v, 1, option->rect.bottom() - aft_v + 1, brush);
- if (option->state & (State_Open | State_Children | State_Item | State_Sibling))
- p->fillRect(mid_h, option->rect.y(), 1, bef_v - option->rect.y(), brush);
- if (option->state & State_Children) {
- int delta = decoration_size / 2;
- bef_h -= delta;
- bef_v -= delta;
- aft_h += delta;
- aft_v += delta;
- XPThemeData theme(0, p, QLatin1String("TREEVIEW"));
- theme.rect = QRect(bef_h, bef_v, decoration_size, decoration_size);
- theme.partId = TVP_GLYPH;
- theme.stateId = flags & QStyle::State_Open ? GLPS_OPENED : GLPS_CLOSED;
- d->drawBackground(theme);
- }
- }
- return;
-
- case PE_IndicatorToolBarSeparator:
- if (option->rect.height() < 3) {
- // XP style requires a few pixels for the separator
- // to be visible.
- QWindowsStyle::drawPrimitive(pe, option, p, widget);
- return;
- }
- name = QLatin1String("TOOLBAR");
- partId = TP_SEPARATOR;
-
- if (option->state & State_Horizontal)
- partId = TP_SEPARATOR;
- else
- partId = TP_SEPARATORVERT;
-
- break;
-
- case PE_IndicatorToolBarHandle:
-
- name = QLatin1String("REBAR");
- partId = RP_GRIPPER;
- if (option->state & State_Horizontal) {
- partId = RP_GRIPPER;
- rect.adjust(0, 0, -2, 0);
- }
- else {
- partId = RP_GRIPPERVERT;
- rect.adjust(0, 0, 0, -2);
- }
- break;
-
- case PE_IndicatorItemViewItemCheck: {
- QStyleOptionButton button;
- button.QStyleOption::operator=(*option);
- button.state &= ~State_MouseOver;
- proxy()->drawPrimitive(PE_IndicatorCheckBox, &button, p, widget);
- return;
- }
-
- default:
- break;
- }
-
- XPThemeData theme(0, p, name, partId, stateId, rect);
- if (!theme.isValid()) {
- QWindowsStyle::drawPrimitive(pe, option, p, widget);
- return;
- }
- theme.mirrorHorizontally = hMirrored;
- theme.mirrorVertically = vMirrored;
- theme.noBorder = noBorder;
- theme.noContent = noContent;
- theme.rotate = rotate;
- d->drawBackground(theme);
-}
-
-/*!
- \reimp
-*/
-void QWindowsXPStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *p,
- const QWidget *widget) const
-{
- QWindowsXPStylePrivate *d = const_cast<QWindowsXPStylePrivate*>(d_func());
- if (!QWindowsXPStylePrivate::useXP()) {
- QWindowsStyle::drawControl(element, option, p, widget);
- return;
- }
-
- QRect rect(option->rect);
- State flags = option->state;
-
- int rotate = 0;
- bool hMirrored = false;
- bool vMirrored = false;
-
- QString name;
- int partId = 0;
- int stateId = 0;
- switch (element) {
- case CE_SizeGrip:
- {
- name = QLatin1String("STATUS");
- partId = SP_GRIPPER;
- SIZE sz;
- XPThemeData theme(0, p, name, partId, 0);
- pGetThemePartSize(theme.handle(), 0, partId, 0, 0, TS_TRUE, &sz);
- --sz.cy;
- if (const QStyleOptionSizeGrip *sg = qstyleoption_cast<const QStyleOptionSizeGrip *>(option)) {
- switch (sg->corner) {
- case Qt::BottomRightCorner:
- rect = QRect(rect.right() - sz.cx, rect.bottom() - sz.cy, sz.cx, sz.cy);
- break;
- case Qt::BottomLeftCorner:
- rect = QRect(rect.left() + 1, rect.bottom() - sz.cy, sz.cx, sz.cy);
- hMirrored = true;
- break;
- case Qt::TopRightCorner:
- rect = QRect(rect.right() - sz.cx, rect.top() + 1, sz.cx, sz.cy);
- vMirrored = true;
- break;
- case Qt::TopLeftCorner:
- rect = QRect(rect.left() + 1, rect.top() + 1, sz.cx, sz.cy);
- hMirrored = vMirrored = true;
- }
- }
- }
- break;
-
- case CE_HeaderSection:
- name = QLatin1String("HEADER");
- partId = HP_HEADERITEM;
- if (flags & State_Sunken)
- stateId = HIS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = HIS_HOT;
- else
- stateId = HIS_NORMAL;
- break;
-
- case CE_Splitter:
- p->eraseRect(option->rect);
- return;
-
- case CE_PushButtonBevel:
- if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option))
- {
- name = QLatin1String("BUTTON");
- partId = BP_PUSHBUTTON;
- bool justFlat = ((btn->features & QStyleOptionButton::Flat) && !(flags & (State_On|State_Sunken)))
- || ((btn->features & QStyleOptionButton::CommandLinkButton)
- && !(flags & State_MouseOver)
- && !(btn->features & QStyleOptionButton::DefaultButton));
- if (!(flags & State_Enabled) && !(btn->features & QStyleOptionButton::Flat))
- stateId = PBS_DISABLED;
- else if (justFlat)
- ;
- else if (flags & (State_Sunken | State_On))
- stateId = PBS_PRESSED;
- else if (flags & State_MouseOver)
- stateId = PBS_HOT;
- else if (btn->features & QStyleOptionButton::DefaultButton)
- stateId = PBS_DEFAULTED;
- else
- stateId = PBS_NORMAL;
-
- if (!justFlat) {
- XPThemeData theme(widget, p, name, partId, stateId, rect);
- d->drawBackground(theme);
- }
-
- if (btn->features & QStyleOptionButton::HasMenu) {
- int mbiw = 0, mbih = 0;
- XPThemeData theme(widget, 0, QLatin1String("TOOLBAR"), TP_SPLITBUTTONDROPDOWN);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- mbiw = size.cx;
- mbih = size.cy;
- }
-
- QRect ir = btn->rect;
- QStyleOptionButton newBtn = *btn;
- newBtn.rect = QRect(ir.right() - mbiw - 1, 1 + (ir.height()/2) - (mbih/2), mbiw, mbih);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
- }
- return;
- }
- break;
- case CE_TabBarTab:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option))
- {
- stateId = tab->state & State_Enabled ? TIS_NORMAL : TIS_DISABLED;
- }
- break;
-
- case CE_TabBarTabShape:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option))
- {
- name = QLatin1String("TAB");
- bool isDisabled = !(tab->state & State_Enabled);
- bool hasFocus = tab->state & State_HasFocus;
- bool isHot = tab->state & State_MouseOver;
- bool selected = tab->state & State_Selected;
- bool lastTab = tab->position == QStyleOptionTab::End;
- bool firstTab = tab->position == QStyleOptionTab::Beginning;
- bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
- bool leftAligned = proxy()->styleHint(SH_TabBar_Alignment, tab, widget) == Qt::AlignLeft;
- bool centerAligned = proxy()->styleHint(SH_TabBar_Alignment, tab, widget) == Qt::AlignCenter;
- int borderThickness = proxy()->pixelMetric(PM_DefaultFrameWidth, option, widget);
- int tabOverlap = proxy()->pixelMetric(PM_TabBarTabOverlap, option, widget);
-
- if (isDisabled)
- stateId = TIS_DISABLED;
- else if (selected)
- stateId = TIS_SELECTED;
- else if (hasFocus)
- stateId = TIS_FOCUSED;
- else if (isHot)
- stateId = TIS_HOT;
- else
- stateId = TIS_NORMAL;
-
- // Selecting proper part depending on position
- if (firstTab || onlyOne) {
- if (leftAligned) {
- partId = TABP_TABITEMLEFTEDGE;
- } else if (centerAligned) {
- partId = TABP_TABITEM;
- } else { // rightAligned
- partId = TABP_TABITEMRIGHTEDGE;
- }
- } else {
- partId = TABP_TABITEM;
- }
-
- if (tab->direction == Qt::RightToLeft
- && (tab->shape == QTabBar::RoundedNorth
- || tab->shape == QTabBar::RoundedSouth)) {
- bool temp = firstTab;
- firstTab = lastTab;
- lastTab = temp;
- }
- bool begin = firstTab || onlyOne;
- bool end = lastTab || onlyOne;
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- if (selected)
- rect.adjust(begin ? 0 : -tabOverlap, 0, end ? 0 : tabOverlap, borderThickness);
- else
- rect.adjust(begin? tabOverlap : 0, tabOverlap, end ? -tabOverlap : 0, 0);
- break;
- case QTabBar::RoundedSouth:
- //vMirrored = true;
- rotate = 180; // Not 100% correct, but works
- if (selected)
- rect.adjust(begin ? 0 : -tabOverlap , -borderThickness, end ? 0 : tabOverlap, 0);
- else
- rect.adjust(begin ? tabOverlap : 0, 0, end ? -tabOverlap : 0 , -tabOverlap);
- break;
- case QTabBar::RoundedEast:
- rotate = 90;
- if (selected) {
- rect.adjust(-borderThickness, begin ? 0 : -tabOverlap, 0, end ? 0 : tabOverlap);
- }else{
- rect.adjust(0, begin ? tabOverlap : 0, -tabOverlap, end ? -tabOverlap : 0);
- }
- break;
- case QTabBar::RoundedWest:
- hMirrored = true;
- rotate = 90;
- if (selected) {
- rect.adjust(0, begin ? 0 : -tabOverlap, borderThickness, end ? 0 : tabOverlap);
- }else{
- rect.adjust(tabOverlap, begin ? tabOverlap : 0, 0, end ? -tabOverlap : 0);
- }
- break;
- default:
- name = QLatin1String(""); // Do our own painting for triangular
- break;
- }
-
- if (!selected) {
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- rect.adjust(0,0, 0,-1);
- break;
- case QTabBar::RoundedSouth:
- rect.adjust(0,1, 0,0);
- break;
- case QTabBar::RoundedEast:
- rect.adjust( 1,0, 0,0);
- break;
- case QTabBar::RoundedWest:
- rect.adjust(0,0, -1,0);
- break;
- default:
- break;
- }
- }
- }
- break;
-
- case CE_ProgressBarGroove:
- {
- Qt::Orientation orient = Qt::Horizontal;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option))
- orient = pb2->orientation;
- partId = (orient == Qt::Horizontal) ? PP_BAR : PP_BARVERT;
- name = QLatin1String("PROGRESS");
- stateId = 1;
- }
- break;
-
- case CE_MenuEmptyArea:
- case CE_MenuItem:
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option))
- {
- int tab = menuitem->tabWidth;
- bool dis = !(menuitem->state & State_Enabled);
- bool act = menuitem->state & State_Selected;
- bool checkable = menuitem->menuHasCheckableItems;
- bool checked = checkable ? menuitem->checked : false;
-
- // windows always has a check column, regardless whether we have an icon or not
- int checkcol = qMax(menuitem->maxIconWidth, 12);
-
- int x, y, w, h;
- rect.getRect(&x, &y, &w, &h);
-
- QBrush fill = menuitem->palette.brush(act ? QPalette::Highlight : QPalette::Button);
- p->fillRect(rect, fill);
-
- if (element == CE_MenuEmptyArea)
- break;
-
- // draw separator -------------------------------------------------
- if (menuitem->menuItemType == QStyleOptionMenuItem::Separator) {
- int yoff = y-1 + h / 2;
- p->setPen(menuitem->palette.dark().color());
- p->drawLine(x, yoff, x+w, yoff);
- ++yoff;
- p->setPen(menuitem->palette.light().color());
- p->drawLine(x, yoff, x+w, yoff);
- return;
- }
-
- int xpos = x;
-
- // draw icon ------------------------------------------------------
- if (!menuitem->icon.isNull()) {
- QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
- if (act && !dis)
- mode = QIcon::Active;
- QPixmap pixmap = checked ?
- menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), mode, QIcon::On) :
- menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), mode);
- int pixw = pixmap.width();
- int pixh = pixmap.height();
- QRect iconRect(0, 0, pixw, pixh);
- iconRect.moveCenter(QRect(xpos, y, checkcol, h).center());
- QRect vIconRect = visualRect(option->direction, option->rect, iconRect);
- p->setPen(menuitem->palette.text().color());
- p->setBrush(Qt::NoBrush);
- if (checked)
- p->drawRect(vIconRect.adjusted(-1, -1, 0, 0));
- p->drawPixmap(vIconRect.topLeft(), pixmap);
-
- // draw checkmark -------------------------------------------------
- } else if (checked) {
- QStyleOptionMenuItem newMi = *menuitem;
- newMi.state = State_None;
- if (!dis)
- newMi.state |= State_Enabled;
- if (act)
- newMi.state |= State_On;
-
- QRect checkMarkRect = QRect(menuitem->rect.x() + windowsItemFrame,
- menuitem->rect.y() + windowsItemFrame,
- checkcol - 2 * windowsItemFrame,
- menuitem->rect.height() - 2*windowsItemFrame);
- newMi.rect = visualRect(option->direction, option->rect, checkMarkRect);
- proxy()->drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, widget);
- }
-
- QColor textColor = dis ? menuitem->palette.text().color() :
- act ? menuitem->palette.highlightedText().color() : menuitem->palette.buttonText().color();
- p->setPen(textColor);
-
- // draw text ------------------------------------------------------
- int xm = windowsItemFrame + checkcol + windowsItemHMargin;
- xpos = menuitem->rect.x() + xm;
- QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
- QRect vTextRect = visualRect(option->direction, option->rect, textRect);
- QString s = menuitem->text;
- if (!s.isEmpty()) {
- p->save();
- int t = s.indexOf(QLatin1Char('\t'));
- int text_flags = Qt::AlignVCenter|Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine | Qt::AlignLeft;
- if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget))
- text_flags |= Qt::TextHideMnemonic;
- // draw tab text ----------------
- if (t >= 0) {
- QRect vShortcutRect = visualRect(option->direction, option->rect, QRect(textRect.topRight(), menuitem->rect.bottomRight()));
- if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vShortcutRect.adjusted(1,1,1,1), text_flags, s.mid(t + 1));
- p->setPen(textColor);
- }
- p->drawText(vShortcutRect, text_flags, s.mid(t + 1));
- s = s.left(t);
- }
- QFont font = menuitem->font;
- if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
- font.setBold(true);
- p->setFont(font);
- if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
- p->setPen(menuitem->palette.light().color());
- p->drawText(vTextRect.adjusted(1,1,1,1), text_flags, s.left(t));
- p->setPen(textColor);
- }
- p->drawText(vTextRect, text_flags, s);
- p->restore();
- }
-
- // draw sub menu arrow --------------------------------------------
- if (menuitem->menuItemType == QStyleOptionMenuItem::SubMenu) {
- int dim = (h - 2) / 2;
- PrimitiveElement arrow;
- arrow = (option->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
- xpos = x + w - windowsArrowHMargin - windowsItemFrame - dim;
- QRect vSubMenuRect = visualRect(option->direction, option->rect, QRect(xpos, y + h / 2 - dim / 2, dim, dim));
- QStyleOptionMenuItem newMI = *menuitem;
- newMI.rect = vSubMenuRect;
- newMI.state = dis ? State_None : State_Enabled;
- if (act)
- newMI.palette.setColor(QPalette::ButtonText, newMI.palette.highlightedText().color());
- proxy()->drawPrimitive(arrow, &newMI, p, widget);
- }
- }
- return;
-
- case CE_MenuBarItem:
- if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option))
- {
- if (mbi->menuItemType == QStyleOptionMenuItem::DefaultItem)
- break;
-
- bool act = mbi->state & State_Selected;
- bool dis = !(mbi->state & State_Enabled);
-
- QBrush fill = mbi->palette.brush(act ? QPalette::Highlight : QPalette::Button);
- QPalette::ColorRole textRole = dis ? QPalette::Text:
- act ? QPalette::HighlightedText : QPalette::ButtonText;
- QPixmap pix = mbi->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), QIcon::Normal);
-
- uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
- if (!proxy()->styleHint(SH_UnderlineShortcut, mbi, widget))
- alignment |= Qt::TextHideMnemonic;
-
- p->fillRect(rect, fill);
- if (!pix.isNull())
- drawItemPixmap(p, mbi->rect, alignment, pix);
- else
- drawItemText(p, mbi->rect, alignment, mbi->palette, mbi->state & State_Enabled, mbi->text, textRole);
- }
- return;
-#ifndef QT_NO_DOCKWIDGET
- case CE_DockWidgetTitle:
- if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(option))
- {
- int buttonMargin = 4;
- int mw = proxy()->pixelMetric(QStyle::PM_DockWidgetTitleMargin, dwOpt, widget);
- int fw = proxy()->pixelMetric(PM_DockWidgetFrameWidth, dwOpt, widget);
- bool isFloating = widget && widget->isWindow();
- bool isActive = dwOpt->state & State_Active;
-
- const QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
- bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
- if (verticalTitleBar) {
- QSize s = rect.size();
- s.transpose();
- rect.setSize(s);
-
- p->translate(rect.left() - 1, rect.top() + rect.width());
- p->rotate(-90);
- p->translate(-rect.left() + 1, -rect.top());
- }
- QRect r = rect.adjusted(0, 2, -1, -3);
- QRect titleRect = r;
-
- if (dwOpt->closable) {
- QSize sz = proxy()->standardIcon(QStyle::SP_TitleBarCloseButton, dwOpt, widget).actualSize(QSize(10, 10));
- titleRect.adjust(0, 0, -sz.width() - mw - buttonMargin, 0);
- }
-
- if (dwOpt->floatable) {
- QSize sz = proxy()->standardIcon(QStyle::SP_TitleBarMaxButton, dwOpt, widget).actualSize(QSize(10, 10));
- titleRect.adjust(0, 0, -sz.width() - mw - buttonMargin, 0);
- }
-
- if (isFloating) {
- titleRect.adjust(0, -fw, 0, 0);
- if (widget != 0 && widget->windowIcon().cacheKey() != QApplication::windowIcon().cacheKey())
- titleRect.adjust(titleRect.height() + mw, 0, 0, 0);
- } else {
- titleRect.adjust(mw, 0, 0, 0);
- if (!dwOpt->floatable && !dwOpt->closable)
- titleRect.adjust(0, 0, -mw, 0);
- }
-
- if (!verticalTitleBar)
- titleRect = visualRect(dwOpt->direction, r, titleRect);
-
- if (!isFloating) {
- QPen oldPen = p->pen();
- QString titleText = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight, titleRect.width());
- p->setPen(dwOpt->palette.color(QPalette::Dark));
- p->drawRect(r);
-
- if (!titleText.isEmpty()) {
- drawItemText(p, titleRect,
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, dwOpt->palette,
- dwOpt->state & State_Enabled, titleText,
- QPalette::WindowText);
- }
-
- p->setPen(oldPen);
- } else {
- name = QLatin1String("WINDOW");
- if (isActive)
- stateId = CS_ACTIVE;
- else
- stateId = CS_INACTIVE;
-
- int titleHeight = rect.height() - 2;
- rect = rect.adjusted(-fw, -fw, fw, 0);
-
- XPThemeData theme(widget, p, name, 0, stateId);
- if (!theme.isValid())
- break;
-
- // Draw small type title bar
- theme.rect = rect;
- theme.partId = WP_SMALLCAPTION;
- d->drawBackground(theme);
-
- // Figure out maximal button space on title bar
-
- QIcon ico = widget->windowIcon();
- bool hasIcon = (ico.cacheKey() != QApplication::windowIcon().cacheKey());
- if (hasIcon) {
- QPixmap pxIco = ico.pixmap(titleHeight);
- if (!verticalTitleBar && dwOpt->direction == Qt::RightToLeft)
- p->drawPixmap(rect.width() - titleHeight - pxIco.width(), rect.bottom() - titleHeight - 2, pxIco);
- else
- p->drawPixmap(fw, rect.bottom() - titleHeight - 2, pxIco);
- }
- if (!dwOpt->title.isEmpty()) {
- QPen oldPen = p->pen();
- QFont oldFont = p->font();
- QFont titleFont = oldFont;
- titleFont.setBold(true);
- p->setFont(titleFont);
- QString titleText
- = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight, titleRect.width());
-
- int result = TST_NONE;
- pGetThemeEnumValue(theme.handle(), WP_SMALLCAPTION, isActive ? CS_ACTIVE : CS_INACTIVE, TMT_TEXTSHADOWTYPE, &result);
- if (result != TST_NONE) {
- COLORREF textShadowRef;
- pGetThemeColor(theme.handle(), WP_SMALLCAPTION, isActive ? CS_ACTIVE : CS_INACTIVE, TMT_TEXTSHADOWCOLOR, &textShadowRef);
- QColor textShadow = qRgb(GetRValue(textShadowRef), GetGValue(textShadowRef), GetBValue(textShadowRef));
- p->setPen(textShadow);
- drawItemText(p, titleRect.adjusted(1, 1, 1, 1),
- Qt::AlignLeft | Qt::AlignBottom, dwOpt->palette,
- dwOpt->state & State_Enabled, titleText);
- }
-
- COLORREF captionText = GetSysColor(isActive ? COLOR_CAPTIONTEXT : COLOR_INACTIVECAPTIONTEXT);
- QColor textColor = qRgb(GetRValue(captionText), GetGValue(captionText), GetBValue(captionText));
- p->setPen(textColor);
- drawItemText(p, titleRect,
- Qt::AlignLeft | Qt::AlignBottom, dwOpt->palette,
- dwOpt->state & State_Enabled, titleText);
- p->setFont(oldFont);
- p->setPen(oldPen);
- }
-
- }
-
- return;
- }
- break;
-#endif // QT_NO_DOCKWIDGET
-#ifndef QT_NO_RUBBERBAND
- case CE_RubberBand:
- if (qstyleoption_cast<const QStyleOptionRubberBand *>(option)) {
- QColor highlight = option->palette.color(QPalette::Active, QPalette::Highlight);
- p->save();
- QRect r = option->rect;
- p->setPen(highlight.darker(120));
- QColor dimHighlight(qMin(highlight.red()/2 + 110, 255),
- qMin(highlight.green()/2 + 110, 255),
- qMin(highlight.blue()/2 + 110, 255),
- (widget && widget->isTopLevel())? 255 : 127);
- p->setBrush(dimHighlight);
- p->drawRect(option->rect.adjusted(0, 0, -1, -1));
- p->restore();
- return;
- }
-#endif // QT_NO_RUBBERBAND
- case CE_HeaderEmptyArea:
- if (option->state & State_Horizontal)
- {
- name = QLatin1String("HEADER");
- stateId = HIS_NORMAL;
- }
- else {
- QWindowsStyle::drawControl(CE_HeaderEmptyArea, option, p, widget);
- return;
- }
- break;
- default:
- break;
- }
-
- XPThemeData theme(widget, p, name, partId, stateId, rect);
- if (!theme.isValid()) {
- QWindowsStyle::drawControl(element, option, p, widget);
- return;
- }
-
- theme.rotate = rotate;
- theme.mirrorHorizontally = hMirrored;
- theme.mirrorVertically = vMirrored;
- d->drawBackground(theme);
-}
-
-
-/*!
- \reimp
-*/
-void QWindowsXPStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *option,
- QPainter *p, const QWidget *widget) const
-{
- QWindowsXPStylePrivate *d = const_cast<QWindowsXPStylePrivate*>(d_func());
-
- if (!QWindowsXPStylePrivate::useXP()) {
- QWindowsStyle::drawComplexControl(cc, option, p, widget);
- return;
- }
-
- State flags = option->state;
- SubControls sub = option->subControls;
- QRect r = option->rect;
-
- int partId = 0;
- int stateId = 0;
- if (widget && widget->testAttribute(Qt::WA_UnderMouse) && widget->isActiveWindow())
- flags |= State_MouseOver;
-
- switch (cc) {
-#ifndef QT_NO_SPINBOX
- case CC_SpinBox:
- if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(option))
- {
- XPThemeData theme(widget, p, QLatin1String("SPIN"));
-
- if (sb->frame && (sub & SC_SpinBoxFrame)) {
- partId = EP_EDITTEXT;
- if (!(flags & State_Enabled))
- stateId = ETS_DISABLED;
- else if (flags & State_HasFocus)
- stateId = ETS_FOCUSED;
- else
- stateId = ETS_NORMAL;
-
- XPThemeData ftheme(widget, p, QLatin1String("EDIT"), partId, stateId, r);
- ftheme.noContent = true;
- d->drawBackground(ftheme);
- }
- if (sub & SC_SpinBoxUp) {
- theme.rect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxUp, widget);
- partId = SPNP_UP;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepUpEnabled) || !(flags & State_Enabled))
- stateId = UPS_DISABLED;
- else if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_Sunken))
- stateId = UPS_PRESSED;
- else if (sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_MouseOver))
- stateId = UPS_HOT;
- else
- stateId = UPS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_SpinBoxDown) {
- theme.rect = proxy()->subControlRect(CC_SpinBox, option, SC_SpinBoxDown, widget);
- partId = SPNP_DOWN;
- if (!(sb->stepEnabled & QAbstractSpinBox::StepDownEnabled) || !(flags & State_Enabled))
- stateId = DNS_DISABLED;
- else if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_Sunken))
- stateId = DNS_PRESSED;
- else if (sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_MouseOver))
- stateId = DNS_HOT;
- else
- stateId = DNS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- }
- break;
-#endif // QT_NO_SPINBOX
-#ifndef QT_NO_COMBOBOX
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option))
- {
- if (sub & SC_ComboBoxEditField) {
- if (cmb->frame) {
- partId = EP_EDITTEXT;
- if (!(flags & State_Enabled))
- stateId = ETS_DISABLED;
- else if (flags & State_HasFocus)
- stateId = ETS_FOCUSED;
- else
- stateId = ETS_NORMAL;
- XPThemeData theme(widget, p, QLatin1String("EDIT"), partId, stateId, r);
- d->drawBackground(theme);
- } else {
- QBrush editBrush = cmb->palette.brush(QPalette::Base);
- p->fillRect(option->rect, editBrush);
- }
- if (!cmb->editable) {
- QRect re = proxy()->subControlRect(CC_ComboBox, option, SC_ComboBoxEditField, widget);
- if (option->state & State_HasFocus) {
- p->fillRect(re, option->palette.highlight());
- p->setPen(option->palette.highlightedText().color());
- p->setBackground(option->palette.highlight());
- } else {
- p->fillRect(re, option->palette.base());
- p->setPen(option->palette.text().color());
- p->setBackground(option->palette.base());
- }
- }
- }
-
- if (sub & SC_ComboBoxArrow) {
- XPThemeData theme(widget, p, QLatin1String("COMBOBOX"));
- theme.rect = proxy()->subControlRect(CC_ComboBox, option, SC_ComboBoxArrow, widget);
- partId = CP_DROPDOWNBUTTON;
- if (!(flags & State_Enabled))
- stateId = CBXS_DISABLED;
- else if (cmb->activeSubControls == SC_ComboBoxArrow && (cmb->state & State_Sunken))
- stateId = CBXS_PRESSED;
- else if (cmb->activeSubControls == SC_ComboBoxArrow && (cmb->state & State_MouseOver))
- stateId = CBXS_HOT;
- else
- stateId = CBXS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- }
- break;
-#endif // QT_NO_COMBOBOX
- case CC_ScrollBar:
- if (const QStyleOptionSlider *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(option))
- {
- XPThemeData theme(widget, p, QLatin1String("SCROLLBAR"));
- bool maxedOut = (scrollbar->maximum == scrollbar->minimum);
- if (maxedOut)
- flags &= ~State_Enabled;
-
- bool isHorz = flags & State_Horizontal;
- bool isRTL = option->direction == Qt::RightToLeft;
- if (sub & SC_ScrollBarAddLine) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarAddLine, widget);
- partId = SBP_ARROWBTN;
- if (!(flags & State_Enabled))
- stateId = (isHorz ? (isRTL ? ABS_LEFTDISABLED : ABS_RIGHTDISABLED) : ABS_DOWNDISABLED);
- else if (scrollbar->activeSubControls & SC_ScrollBarAddLine && (scrollbar->state & State_Sunken))
- stateId = (isHorz ? (isRTL ? ABS_LEFTPRESSED : ABS_RIGHTPRESSED) : ABS_DOWNPRESSED);
- else if (scrollbar->activeSubControls & SC_ScrollBarAddLine && (scrollbar->state & State_MouseOver))
- stateId = (isHorz ? (isRTL ? ABS_LEFTHOT : ABS_RIGHTHOT) : ABS_DOWNHOT);
- else
- stateId = (isHorz ? (isRTL ? ABS_LEFTNORMAL : ABS_RIGHTNORMAL) : ABS_DOWNNORMAL);
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_ScrollBarSubLine) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSubLine, widget);
- partId = SBP_ARROWBTN;
- if (!(flags & State_Enabled))
- stateId = (isHorz ? (isRTL ? ABS_RIGHTDISABLED : ABS_LEFTDISABLED) : ABS_UPDISABLED);
- else if (scrollbar->activeSubControls & SC_ScrollBarSubLine && (scrollbar->state & State_Sunken))
- stateId = (isHorz ? (isRTL ? ABS_RIGHTPRESSED : ABS_LEFTPRESSED) : ABS_UPPRESSED);
- else if (scrollbar->activeSubControls & SC_ScrollBarSubLine && (scrollbar->state & State_MouseOver))
- stateId = (isHorz ? (isRTL ? ABS_RIGHTHOT : ABS_LEFTHOT) : ABS_UPHOT);
- else
- stateId = (isHorz ? (isRTL ? ABS_RIGHTNORMAL : ABS_LEFTNORMAL) : ABS_UPNORMAL);
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (maxedOut) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- theme.rect = theme.rect.united(proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSubPage, widget));
- theme.rect = theme.rect.united(proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarAddPage, widget));
- partId = scrollbar->orientation == Qt::Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT;
- stateId = SCRBS_DISABLED;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- } else {
- if (sub & SC_ScrollBarSubPage) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSubPage, widget);
- partId = flags & State_Horizontal ? SBP_UPPERTRACKHORZ : SBP_UPPERTRACKVERT;
- if (!(flags & State_Enabled))
- stateId = SCRBS_DISABLED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSubPage && (scrollbar->state & State_Sunken))
- stateId = SCRBS_PRESSED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSubPage && (scrollbar->state & State_MouseOver))
- stateId = SCRBS_HOT;
- else
- stateId = SCRBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_ScrollBarAddPage) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarAddPage, widget);
- partId = flags & State_Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT;
- if (!(flags & State_Enabled))
- stateId = SCRBS_DISABLED;
- else if (scrollbar->activeSubControls & SC_ScrollBarAddPage && (scrollbar->state & State_Sunken))
- stateId = SCRBS_PRESSED;
- else if (scrollbar->activeSubControls & SC_ScrollBarAddPage && (scrollbar->state & State_MouseOver))
- stateId = SCRBS_HOT;
- else
- stateId = SCRBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_ScrollBarSlider) {
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- if (!(flags & State_Enabled))
- stateId = SCRBS_DISABLED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSlider && (scrollbar->state & State_Sunken))
- stateId = SCRBS_PRESSED;
- else if (scrollbar->activeSubControls & SC_ScrollBarSlider && (scrollbar->state & State_MouseOver))
- stateId = SCRBS_HOT;
- else
- stateId = SCRBS_NORMAL;
-
- // Draw handle
- theme.rect = proxy()->subControlRect(CC_ScrollBar, option, SC_ScrollBarSlider, widget);
- theme.partId = flags & State_Horizontal ? SBP_THUMBBTNHORZ : SBP_THUMBBTNVERT;
- theme.stateId = stateId;
- d->drawBackground(theme);
-
- // Calculate rect of gripper
- const int swidth = theme.rect.width();
- const int sheight = theme.rect.height();
-
- MARGINS contentsMargin;
- RECT rect = theme.toRECT(theme.rect);
- pGetThemeMargins(theme.handle(), 0, theme.partId, theme.stateId, TMT_SIZINGMARGINS, &rect, &contentsMargin);
-
- SIZE size;
- theme.partId = flags & State_Horizontal ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- int gw = size.cx, gh = size.cy;
-
-
- QRect gripperBounds;
- if (flags & State_Horizontal && ((swidth - contentsMargin.cxLeftWidth - contentsMargin.cxRightWidth) > gw)) {
- gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2);
- gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2);
- gripperBounds.setWidth(gw);
- gripperBounds.setHeight(gh);
- } else if ((sheight - contentsMargin.cyTopHeight - contentsMargin.cyBottomHeight) > gh) {
- gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2);
- gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2);
- gripperBounds.setWidth(gw);
- gripperBounds.setHeight(gh);
- }
-
- // Draw gripper if there is enough space
- if (!gripperBounds.isEmpty()) {
- p->save();
- theme.rect = gripperBounds;
- p->setClipRegion(d->region(theme));// Only change inside the region of the gripper
- d->drawBackground(theme); // Transparent gripper ontop of background
- p->restore();
- }
- }
- }
- }
- break;
-
-#ifndef QT_NO_SLIDER
- case CC_Slider:
- if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option))
- {
- XPThemeData theme(widget, p, QLatin1String("TRACKBAR"));
- QRect slrect = slider->rect;
- QRegion tickreg = slrect;
- if (sub & SC_SliderGroove) {
- theme.rect = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget);
- if (slider->orientation == Qt::Horizontal) {
- partId = TKP_TRACK;
- stateId = TRS_NORMAL;
- theme.rect = QRect(slrect.left(), theme.rect.center().y() - 2, slrect.width(), 4);
- } else {
- partId = TKP_TRACKVERT;
- stateId = TRVS_NORMAL;
- theme.rect = QRect(theme.rect.center().x() - 2, slrect.top(), 4, slrect.height());
- }
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- tickreg -= theme.rect;
- }
- if (sub & SC_SliderTickmarks) {
- int tickOffset = proxy()->pixelMetric(PM_SliderTickmarkOffset, slider, widget);
- int ticks = slider->tickPosition;
- int thickness = proxy()->pixelMetric(PM_SliderControlThickness, slider, widget);
- int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
- int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
- int interval = slider->tickInterval;
- if (interval <= 0) {
- interval = slider->singleStep;
- if (QStyle::sliderPositionFromValue(slider->minimum, slider->maximum, interval,
- available)
- - QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- 0, available) < 3)
- interval = slider->pageStep;
- }
- if (!interval)
- interval = 1;
- int fudge = len / 2;
- int pos;
- int bothOffset = (ticks & QSlider::TicksAbove && ticks & QSlider::TicksBelow) ? 1 : 0;
- p->setPen(d->sliderTickColor);
- QVarLengthArray<QLine, 32> lines;
- int v = slider->minimum;
- while (v <= slider->maximum + 1) {
- if (v == slider->maximum + 1 && interval == 1)
- break;
- const int v_ = qMin(v, slider->maximum);
- int tickLength = (v_ == slider->minimum || v_ >= slider->maximum) ? 4 : 3;
- pos = QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
- v_, available) + fudge;
- if (slider->orientation == Qt::Horizontal) {
- if (ticks & QSlider::TicksAbove)
- lines.append(QLine(pos, tickOffset - 1 - bothOffset,
- pos, tickOffset - 1 - bothOffset - tickLength));
-
- if (ticks & QSlider::TicksBelow)
- lines.append(QLine(pos, tickOffset + thickness + bothOffset,
- pos, tickOffset + thickness + bothOffset + tickLength));
- } else {
- if (ticks & QSlider::TicksAbove)
- lines.append(QLine(tickOffset - 1 - bothOffset, pos,
- tickOffset - 1 - bothOffset - tickLength, pos));
-
- if (ticks & QSlider::TicksBelow)
- lines.append(QLine(tickOffset + thickness + bothOffset, pos,
- tickOffset + thickness + bothOffset + tickLength, pos));
- }
- // in the case where maximum is max int
- int nextInterval = v + interval;
- if (nextInterval < v)
- break;
- v = nextInterval;
- }
- if (lines.size() > 0) {
- p->save();
- p->translate(slrect.topLeft());
- p->drawLines(lines.constData(), lines.size());
- p->restore();
- }
- }
- if (sub & SC_SliderHandle) {
- theme.rect = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget);
- if (slider->orientation == Qt::Horizontal) {
- if (slider->tickPosition == QSlider::TicksAbove)
- partId = TKP_THUMBTOP;
- else if (slider->tickPosition == QSlider::TicksBelow)
- partId = TKP_THUMBBOTTOM;
- else
- partId = TKP_THUMB;
-
- if (!(slider->state & State_Enabled))
- stateId = TUS_DISABLED;
- else if (slider->activeSubControls & SC_SliderHandle && (slider->state & State_Sunken))
- stateId = TUS_PRESSED;
- else if (slider->activeSubControls & SC_SliderHandle && (slider->state & State_MouseOver))
- stateId = TUS_HOT;
- else if (flags & State_HasFocus)
- stateId = TUS_FOCUSED;
- else
- stateId = TUS_NORMAL;
- } else {
- if (slider->tickPosition == QSlider::TicksLeft)
- partId = TKP_THUMBLEFT;
- else if (slider->tickPosition == QSlider::TicksRight)
- partId = TKP_THUMBRIGHT;
- else
- partId = TKP_THUMBVERT;
-
- if (!(slider->state & State_Enabled))
- stateId = TUVS_DISABLED;
- else if (slider->activeSubControls & SC_SliderHandle && (slider->state & State_Sunken))
- stateId = TUVS_PRESSED;
- else if (slider->activeSubControls & SC_SliderHandle && (slider->state & State_MouseOver))
- stateId = TUVS_HOT;
- else if (flags & State_HasFocus)
- stateId = TUVS_FOCUSED;
- else
- stateId = TUVS_NORMAL;
- }
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (slider->state & State_HasFocus) {
- QStyleOptionFocusRect fropt;
- fropt.QStyleOption::operator=(*slider);
- fropt.rect = subElementRect(SE_SliderFocusRect, slider, widget);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, p, widget);
- }
- }
- break;
-#endif
-#ifndef QT_NO_TOOLBUTTON
- case CC_ToolButton:
- if (const QStyleOptionToolButton *toolbutton
- = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
- QRect button, menuarea;
- button = proxy()->subControlRect(cc, toolbutton, SC_ToolButton, widget);
- menuarea = proxy()->subControlRect(cc, toolbutton, SC_ToolButtonMenu, widget);
-
- State bflags = toolbutton->state & ~State_Sunken;
- State mflags = bflags;
- bool autoRaise = flags & State_AutoRaise;
- if (autoRaise) {
- if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) {
- bflags &= ~State_Raised;
- }
- }
-
- if (toolbutton->state & State_Sunken) {
- if (toolbutton->activeSubControls & SC_ToolButton) {
- bflags |= State_Sunken;
- mflags |= State_MouseOver | State_Sunken;
- } else if (toolbutton->activeSubControls & SC_ToolButtonMenu) {
- mflags |= State_Sunken;
- bflags |= State_MouseOver;
- }
- }
-
- QStyleOption tool(0);
- tool.palette = toolbutton->palette;
- if (toolbutton->subControls & SC_ToolButton) {
- if (flags & (State_Sunken | State_On | State_Raised) || !autoRaise) {
- if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup && autoRaise) {
- XPThemeData theme(widget, p, QLatin1String("TOOLBAR"));
- theme.partId = TP_SPLITBUTTON;
- theme.rect = button;
- if (!(bflags & State_Enabled))
- stateId = TS_DISABLED;
- else if (bflags & State_Sunken)
- stateId = TS_PRESSED;
- else if (bflags & State_MouseOver || !(flags & State_AutoRaise))
- stateId = flags & State_On ? TS_HOTCHECKED : TS_HOT;
- else if (bflags & State_On)
- stateId = TS_CHECKED;
- else
- stateId = TS_NORMAL;
- if (option->direction == Qt::RightToLeft)
- theme.mirrorHorizontally = true;
- theme.stateId = stateId;
- d->drawBackground(theme);
- } else {
- tool.rect = option->rect;
- tool.state = bflags;
- if (autoRaise) // for tool bars
- proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget);
- else
- proxy()->drawPrimitive(PE_PanelButtonBevel, &tool, p, widget);
- }
- }
- }
-
- if (toolbutton->state & State_HasFocus) {
- QStyleOptionFocusRect fr;
- fr.QStyleOption::operator=(*toolbutton);
- fr.rect.adjust(3, 3, -3, -3);
- if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup)
- fr.rect.adjust(0, 0, -proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator,
- toolbutton, widget), 0);
- proxy()->drawPrimitive(PE_FrameFocusRect, &fr, p, widget);
- }
- QStyleOptionToolButton label = *toolbutton;
- label.state = bflags;
- int fw = 2;
- if (!autoRaise)
- label.state &= ~State_Sunken;
- label.rect = button.adjusted(fw, fw, -fw, -fw);
- proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget);
-
- if (toolbutton->subControls & SC_ToolButtonMenu) {
- tool.rect = menuarea;
- tool.state = mflags;
- if (autoRaise) {
- proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, p, widget);
- } else {
- tool.state = mflags;
- menuarea.adjust(-2, 0, 0, 0);
- // Draw menu button
- if ((bflags & State_Sunken) != (mflags & State_Sunken)){
- p->save();
- p->setClipRect(menuarea);
- tool.rect = option->rect;
- proxy()->drawPrimitive(PE_PanelButtonBevel, &tool, p, 0);
- p->restore();
- }
- // Draw arrow
- p->save();
- p->setPen(option->palette.dark().color());
- p->drawLine(menuarea.left(), menuarea.top() + 3,
- menuarea.left(), menuarea.bottom() - 3);
- p->setPen(option->palette.light().color());
- p->drawLine(menuarea.left() - 1, menuarea.top() + 3,
- menuarea.left() - 1, menuarea.bottom() - 3);
-
- tool.rect = menuarea.adjusted(2, 3, -2, -1);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, p, widget);
- p->restore();
- }
- } else if (toolbutton->features & QStyleOptionToolButton::HasMenu) {
- int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolbutton, widget);
- QRect ir = toolbutton->rect;
- QStyleOptionToolButton newBtn = *toolbutton;
- newBtn.rect = QRect(ir.right() + 4 - mbi, ir.height() - mbi + 4, mbi - 5, mbi - 5);
- proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget);
- }
- }
- break;
-#endif // QT_NO_TOOLBUTTON
-
- case CC_TitleBar:
- {
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option))
- {
- bool isActive = tb->titleBarState & QStyle::State_Active;
- XPThemeData theme(widget, p, QLatin1String("WINDOW"));
- if (sub & SC_TitleBarLabel) {
-
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- partId = WP_SMALLCAPTION;
- } else
-#endif
- partId = (tb->titleBarState & Qt::WindowMinimized) ? WP_MINCAPTION : WP_CAPTION;
- theme.rect = option->rect;
- if (widget && !widget->isEnabled())
- stateId = CS_DISABLED;
- else if (isActive)
- stateId = CS_ACTIVE;
- else
- stateId = CS_INACTIVE;
-
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
-
- QRect ir = proxy()->subControlRect(CC_TitleBar, tb, SC_TitleBarLabel, widget);
-
- int result = TST_NONE;
- pGetThemeEnumValue(theme.handle(), WP_CAPTION, isActive ? CS_ACTIVE : CS_INACTIVE, TMT_TEXTSHADOWTYPE, &result);
- if (result != TST_NONE) {
- COLORREF textShadowRef;
- pGetThemeColor(theme.handle(), WP_CAPTION, isActive ? CS_ACTIVE : CS_INACTIVE, TMT_TEXTSHADOWCOLOR, &textShadowRef);
- QColor textShadow = qRgb(GetRValue(textShadowRef), GetGValue(textShadowRef), GetBValue(textShadowRef));
- p->setPen(textShadow);
- p->drawText(ir.x() + 3, ir.y() + 2, ir.width() - 1, ir.height(),
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
- }
- COLORREF captionText = GetSysColor(isActive ? COLOR_CAPTIONTEXT : COLOR_INACTIVECAPTIONTEXT);
- QColor textColor = qRgb(GetRValue(captionText), GetGValue(captionText), GetBValue(captionText));
- p->setPen(textColor);
- p->drawText(ir.x() + 2, ir.y() + 1, ir.width() - 2, ir.height(),
- Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
- }
- if (sub & SC_TitleBarSysMenu && tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarSysMenu, widget);
- partId = WP_SYSBUTTON;
- if ((widget && !widget->isEnabled()) || !isActive)
- stateId = SBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarSysMenu && (option->state & State_Sunken))
- stateId = SBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarSysMenu && (option->state & State_MouseOver))
- stateId = SBS_HOT;
- else
- stateId = SBS_NORMAL;
- if (!tb->icon.isNull()) {
- tb->icon.paint(p, theme.rect);
- } else {
- theme.partId = partId;
- theme.stateId = stateId;
- SIZE sz;
- pGetThemePartSize(theme.handle(), qt_win_display_dc(), theme.partId, theme.stateId, 0, TS_TRUE, &sz);
- if (sz.cx == 0 || sz.cy == 0) {
- int iconSize = proxy()->pixelMetric(PM_SmallIconSize, tb, widget);
- QPixmap pm = proxy()->standardIcon(SP_TitleBarMenuButton, tb, widget).pixmap(iconSize, iconSize);
- p->save();
- drawItemPixmap(p, theme.rect, Qt::AlignCenter, pm);
- p->restore();
- } else {
- d->drawBackground(theme);
- }
- }
- }
-
- if (sub & SC_TitleBarMinButton && tb->titleBarFlags & Qt::WindowMinimizeButtonHint
- && !(tb->titleBarState & Qt::WindowMinimized)) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarMinButton, widget);
- partId = WP_MINBUTTON;
- if (widget && !widget->isEnabled())
- stateId = MINBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarMinButton && (option->state & State_Sunken))
- stateId = MINBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarMinButton && (option->state & State_MouseOver))
- stateId = MINBS_HOT;
- else if (!isActive)
- stateId = MINBS_INACTIVE;
- else
- stateId = MINBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_TitleBarMaxButton && tb->titleBarFlags & Qt::WindowMaximizeButtonHint
- && !(tb->titleBarState & Qt::WindowMaximized)) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarMaxButton, widget);
- partId = WP_MAXBUTTON;
- if (widget && !widget->isEnabled())
- stateId = MAXBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarMaxButton && (option->state & State_Sunken))
- stateId = MAXBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarMaxButton && (option->state & State_MouseOver))
- stateId = MAXBS_HOT;
- else if (!isActive)
- stateId = MAXBS_INACTIVE;
- else
- stateId = MAXBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_TitleBarContextHelpButton
- && tb->titleBarFlags & Qt::WindowContextHelpButtonHint) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarContextHelpButton, widget);
- partId = WP_HELPBUTTON;
- if (widget && !widget->isEnabled())
- stateId = MINBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarContextHelpButton && (option->state & State_Sunken))
- stateId = MINBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarContextHelpButton && (option->state & State_MouseOver))
- stateId = MINBS_HOT;
- else if (!isActive)
- stateId = MINBS_INACTIVE;
- else
- stateId = MINBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- bool drawNormalButton = (sub & SC_TitleBarNormalButton)
- && (((tb->titleBarFlags & Qt::WindowMinimizeButtonHint)
- && (tb->titleBarState & Qt::WindowMinimized))
- || ((tb->titleBarFlags & Qt::WindowMaximizeButtonHint)
- && (tb->titleBarState & Qt::WindowMaximized)));
- if (drawNormalButton) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarNormalButton, widget);
- partId = WP_RESTOREBUTTON;
- if (widget && !widget->isEnabled())
- stateId = RBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarNormalButton && (option->state & State_Sunken))
- stateId = RBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarNormalButton && (option->state & State_MouseOver))
- stateId = RBS_HOT;
- else if (!isActive)
- stateId = RBS_INACTIVE;
- else
- stateId = RBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_TitleBarShadeButton && tb->titleBarFlags & Qt::WindowShadeButtonHint
- && !(tb->titleBarState & Qt::WindowMinimized)) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarShadeButton, widget);
- partId = WP_MINBUTTON;
- if (widget && !widget->isEnabled())
- stateId = MINBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarShadeButton && (option->state & State_Sunken))
- stateId = MINBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarShadeButton && (option->state & State_MouseOver))
- stateId = MINBS_HOT;
- else if (!isActive)
- stateId = MINBS_INACTIVE;
- else
- stateId = MINBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_TitleBarUnshadeButton && tb->titleBarFlags & Qt::WindowShadeButtonHint
- && tb->titleBarState & Qt::WindowMinimized) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarUnshadeButton, widget);
- partId = WP_RESTOREBUTTON;
- if (widget && !widget->isEnabled())
- stateId = RBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarUnshadeButton && (option->state & State_Sunken))
- stateId = RBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarUnshadeButton && (option->state & State_MouseOver))
- stateId = RBS_HOT;
- else if (!isActive)
- stateId = RBS_INACTIVE;
- else
- stateId = RBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- if (sub & SC_TitleBarCloseButton && tb->titleBarFlags & Qt::WindowSystemMenuHint) {
- theme.rect = proxy()->subControlRect(CC_TitleBar, option, SC_TitleBarCloseButton, widget);
- //partId = titlebar->testWFlags(Qt::WA_WState_Tool) ? WP_SMALLCLOSEBUTTON : WP_CLOSEBUTTON;
- partId = WP_CLOSEBUTTON;
- if (widget && !widget->isEnabled())
- stateId = CBS_DISABLED;
- else if (option->activeSubControls == SC_TitleBarCloseButton && (option->state & State_Sunken))
- stateId = CBS_PUSHED;
- else if (option->activeSubControls == SC_TitleBarCloseButton && (option->state & State_MouseOver))
- stateId = CBS_HOT;
- else if (!isActive)
- stateId = CBS_INACTIVE;
- else
- stateId = CBS_NORMAL;
- theme.partId = partId;
- theme.stateId = stateId;
- d->drawBackground(theme);
- }
- }
- }
- break;
-
-#ifndef QT_NO_WORKSPACE
- case CC_MdiControls:
- {
- QRect buttonRect;
- XPThemeData theme(widget, p, QLatin1String("WINDOW"), WP_MDICLOSEBUTTON, CBS_NORMAL);
-
- if (option->subControls & SC_MdiCloseButton) {
- buttonRect = proxy()->subControlRect(CC_MdiControls, option, SC_MdiCloseButton, widget);
- if (theme.isValid()) {
- theme.partId = WP_MDICLOSEBUTTON;
- theme.rect = buttonRect;
- if (!(flags & State_Enabled))
- theme.stateId = CBS_INACTIVE;
- else if (flags & State_Sunken && (option->activeSubControls & SC_MdiCloseButton))
- theme.stateId = CBS_PUSHED;
- else if (flags & State_MouseOver && (option->activeSubControls & SC_MdiCloseButton))
- theme.stateId = CBS_HOT;
- else
- theme.stateId = CBS_NORMAL;
- d->drawBackground(theme);
- }
- }
- if (option->subControls & SC_MdiNormalButton) {
- buttonRect = proxy()->subControlRect(CC_MdiControls, option, SC_MdiNormalButton, widget);
- if (theme.isValid()) {
- theme.partId = WP_MDIRESTOREBUTTON;
- theme.rect = buttonRect;
- if (!(flags & State_Enabled))
- theme.stateId = CBS_INACTIVE;
- else if (flags & State_Sunken && (option->activeSubControls & SC_MdiNormalButton))
- theme.stateId = CBS_PUSHED;
- else if (flags & State_MouseOver && (option->activeSubControls & SC_MdiNormalButton))
- theme.stateId = CBS_HOT;
- else
- theme.stateId = CBS_NORMAL;
- d->drawBackground(theme);
- }
- }
- if (option->subControls & QStyle::SC_MdiMinButton) {
- buttonRect = proxy()->subControlRect(CC_MdiControls, option, SC_MdiMinButton, widget);
- if (theme.isValid()) {
- theme.partId = WP_MDIMINBUTTON;
- theme.rect = buttonRect;
- if (!(flags & State_Enabled))
- theme.stateId = CBS_INACTIVE;
- else if (flags & State_Sunken && (option->activeSubControls & SC_MdiMinButton))
- theme.stateId = CBS_PUSHED;
- else if (flags & State_MouseOver && (option->activeSubControls & SC_MdiMinButton))
- theme.stateId = CBS_HOT;
- else
- theme.stateId = CBS_NORMAL;
- d->drawBackground(theme);
- }
- }
- }
- break;
-#endif //QT_NO_WORKSPACE
-#ifndef QT_NO_DIAL
- case CC_Dial:
- if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(option))
- QStyleHelper::drawDial(dial, p);
- break;
-#endif // QT_NO_DIAL
- default:
- QWindowsStyle::drawComplexControl(cc, option, p, widget);
- break;
- }
-}
-
-/*! \reimp */
-int QWindowsXPStyle::pixelMetric(PixelMetric pm, const QStyleOption *option, const QWidget *widget) const
-{
- if (!QWindowsXPStylePrivate::useXP())
- return QWindowsStyle::pixelMetric(pm, option, widget);
-
- int res = 0;
- switch (pm) {
- case PM_MenuBarPanelWidth:
- res = 0;
- break;
-
- case PM_DefaultFrameWidth:
- if (qobject_cast<const QListView*>(widget))
- res = 2;
- else
- res = 1;
- break;
- case PM_MenuPanelWidth:
- case PM_SpinBoxFrameWidth:
- res = 1;
- break;
-
- case PM_TabBarTabOverlap:
- case PM_MenuHMargin:
- case PM_MenuVMargin:
- res = 2;
- break;
-
- case PM_TabBarBaseOverlap:
- if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {
- switch (tab->shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- res = 1;
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- res = 2;
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- res = 3;
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- res = 1;
- break;
- }
- }
- break;
-
- case PM_SplitterWidth:
- res = qMax(int(QStyleHelper::dpiScaled(5.)), QApplication::globalStrut().width());
- break;
-
- case PM_IndicatorWidth:
- case PM_IndicatorHeight:
- {
- XPThemeData theme(widget, 0, QLatin1String("BUTTON"), BP_CHECKBOX, CBS_UNCHECKEDNORMAL);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- res = (pm == PM_IndicatorWidth) ? size.cx : size.cy;
- }
- }
- break;
-
- case PM_ExclusiveIndicatorWidth:
- case PM_ExclusiveIndicatorHeight:
- {
- XPThemeData theme(widget, 0, QLatin1String("BUTTON"), BP_RADIOBUTTON, RBS_UNCHECKEDNORMAL);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- res = (pm == PM_ExclusiveIndicatorWidth) ? size.cx : size.cy;
- }
- }
- break;
-
- case PM_ProgressBarChunkWidth:
- {
- Qt::Orientation orient = Qt::Horizontal;
- if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option))
- orient = pb2->orientation;
- XPThemeData theme(widget, 0, QLatin1String("PROGRESS"), (orient == Qt::Horizontal) ? PP_CHUNK : PP_CHUNKVERT);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- res = (orient == Qt::Horizontal) ? size.cx : size.cy;
- }
- }
- break;
-
- case PM_SliderThickness:
- {
- XPThemeData theme(widget, 0, QLatin1String("TRACKBAR"), TKP_THUMB);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- res = size.cy;
- }
- }
- break;
-
- case PM_TitleBarHeight:
- {
-#ifdef QT3_SUPPORT
- if (widget && widget->inherits("Q3DockWindowTitleBar")) {
- res = GetSystemMetrics(SM_CYSMCAPTION) + GetSystemMetrics(SM_CXSIZEFRAME);
- } else
-#endif
- if (widget && (widget->windowType() == Qt::Tool))
- res = GetSystemMetrics(SM_CYSMCAPTION) + GetSystemMetrics(SM_CXSIZEFRAME);
- else
- res = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CXSIZEFRAME);
- }
- break;
-
- case PM_MdiSubWindowFrameWidth:
- {
- XPThemeData theme(widget, 0, QLatin1String("WINDOW"), WP_FRAMELEFT, FS_ACTIVE);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, WP_FRAMELEFT, FS_ACTIVE, 0, TS_TRUE, &size);
- res = size.cx-1;
- }
- }
- break;
-
- case PM_MdiSubWindowMinimizedWidth:
- res = 160;
- break;
-
-#ifndef QT_NO_TOOLBAR
- case PM_ToolBarHandleExtent:
- res = int(QStyleHelper::dpiScaled(8.));
- break;
-
-#endif // QT_NO_TOOLBAR
- case PM_DockWidgetFrameWidth:
- {
- XPThemeData theme(widget, 0, QLatin1String("WINDOW"), WP_SMALLFRAMERIGHT, FS_ACTIVE);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- res = size.cx;
- }
- }
- break;
- case PM_DockWidgetSeparatorExtent:
- res = int(QStyleHelper::dpiScaled(4.));
- break;
- case PM_DockWidgetTitleMargin:
- res = int(QStyleHelper::dpiScaled(4.));
- break;
-
- case PM_ButtonShiftHorizontal:
- case PM_ButtonShiftVertical:
- if (qstyleoption_cast<const QStyleOptionToolButton *>(option))
- res = 1;
- else
- res = 0;
- break;
-
- case PM_ButtonDefaultIndicator:
- res = 0;
- break;
-
- default:
- res = QWindowsStyle::pixelMetric(pm, option, widget);
- }
-
- return res;
-}
-
-/*
- This function is used by subControlRect to check if a button
- should be drawn for the given subControl given a set of window flags.
-*/
-static bool buttonVisible(const QStyle::SubControl sc, const QStyleOptionTitleBar *tb){
-
- bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
- const uint flags = tb->titleBarFlags;
- bool retVal = false;
- switch (sc) {
- case QStyle::SC_TitleBarContextHelpButton:
- if (flags & Qt::WindowContextHelpButtonHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarMinButton:
- if (!isMinimized && (flags & Qt::WindowMinimizeButtonHint))
- retVal = true;
- break;
- case QStyle::SC_TitleBarNormalButton:
- if (isMinimized && (flags & Qt::WindowMinimizeButtonHint))
- retVal = true;
- else if (isMaximized && (flags & Qt::WindowMaximizeButtonHint))
- retVal = true;
- break;
- case QStyle::SC_TitleBarMaxButton:
- if (!isMaximized && (flags & Qt::WindowMaximizeButtonHint))
- retVal = true;
- break;
- case QStyle::SC_TitleBarShadeButton:
- if (!isMinimized && flags & Qt::WindowShadeButtonHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarUnshadeButton:
- if (isMinimized && flags & Qt::WindowShadeButtonHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarCloseButton:
- if (flags & Qt::WindowSystemMenuHint)
- retVal = true;
- break;
- case QStyle::SC_TitleBarSysMenu:
- if (flags & Qt::WindowSystemMenuHint)
- retVal = true;
- break;
- default :
- retVal = true;
- }
- return retVal;
-}
-
-/*!
- \reimp
-*/
-QRect QWindowsXPStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *option,
- SubControl subControl, const QWidget *widget) const
-{
- if (!QWindowsXPStylePrivate::useXP())
- return QWindowsStyle::subControlRect(cc, option, subControl, widget);
-
- QRect rect;
-
- switch (cc) {
- case CC_TitleBar:
- if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
- if (!buttonVisible(subControl, tb))
- return rect;
- const bool isToolTitle = false;
- const int height = tb->rect.height();
- const int width = tb->rect.width();
- int buttonHeight = GetSystemMetrics(SM_CYSIZE) - 4;
- int buttonWidth = GetSystemMetrics(SM_CXSIZE) - 4;
- const int delta = buttonWidth + 2;
- int controlTop = option->rect.bottom() - buttonHeight - 2;
- const int frameWidth = proxy()->pixelMetric(PM_MdiSubWindowFrameWidth, option, widget);
- const bool sysmenuHint = (tb->titleBarFlags & Qt::WindowSystemMenuHint) != 0;
- const bool minimizeHint = (tb->titleBarFlags & Qt::WindowMinimizeButtonHint) != 0;
- const bool maximizeHint = (tb->titleBarFlags & Qt::WindowMaximizeButtonHint) != 0;
- const bool contextHint = (tb->titleBarFlags & Qt::WindowContextHelpButtonHint) != 0;
- const bool shadeHint = (tb->titleBarFlags & Qt::WindowShadeButtonHint) != 0;
- bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
- bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
- int offset = 0;
-
- switch (subControl) {
- case SC_TitleBarLabel:
- rect = QRect(frameWidth, 0, width - (buttonWidth + frameWidth + 10), height);
- if (isToolTitle) {
- if (sysmenuHint) {
- rect.adjust(0, 0, -buttonWidth - 3, 0);
- }
- if (minimizeHint || maximizeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- } else {
- if (sysmenuHint) {
- const int leftOffset = height - 8;
- rect.adjust(leftOffset, 0, 0, 0);
- }
- if (minimizeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- if (maximizeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- if (contextHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- if (shadeHint)
- rect.adjust(0, 0, -buttonWidth - 2, 0);
- }
- break;
-
- case SC_TitleBarContextHelpButton:
- if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
- offset += delta;
- //fall through
- case SC_TitleBarMinButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (subControl == SC_TitleBarMinButton)
- break;
- //fall through
- case SC_TitleBarNormalButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
- offset += delta;
- else if (isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (subControl == SC_TitleBarNormalButton)
- break;
- //fall through
- case SC_TitleBarMaxButton:
- if (!isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
- offset += delta;
- else if (subControl == SC_TitleBarMaxButton)
- break;
- //fall through
- case SC_TitleBarShadeButton:
- if (!isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (subControl == SC_TitleBarShadeButton)
- break;
- //fall through
- case SC_TitleBarUnshadeButton:
- if (isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
- offset += delta;
- else if (subControl == SC_TitleBarUnshadeButton)
- break;
- //fall through
- case SC_TitleBarCloseButton:
- if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
- offset += delta;
- else if (subControl == SC_TitleBarCloseButton)
- break;
-
- rect.setRect(width - offset - controlTop + 1, controlTop,
- buttonWidth, buttonHeight);
- break;
-
- case SC_TitleBarSysMenu:
- {
- const int controlTop = 6;
- const int controlHeight = height - controlTop - 3;
- const int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
- QSize iconSize = tb->icon.actualSize(QSize(iconExtent, iconExtent));
- if (tb->icon.isNull())
- iconSize = QSize(controlHeight, controlHeight);
- int hPad = (controlHeight - iconSize.height())/2;
- int vPad = (controlHeight - iconSize.width())/2;
- rect = QRect(frameWidth + hPad, controlTop + vPad, iconSize.width(), iconSize.height());
- }
- break;
- default:
- break;
- }
- }
- break;
-
- case CC_ComboBox:
- if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
- int x = cmb->rect.x(), y = cmb->rect.y(), wi = cmb->rect.width(), he = cmb->rect.height();
- int xpos = x;
- xpos += wi - 1 - 16;
-
- switch (subControl) {
- case SC_ComboBoxFrame:
- rect = cmb->rect;
- break;
-
- case SC_ComboBoxArrow:
- rect = QRect(xpos, y+1, 16, he-2);
- break;
-
- case SC_ComboBoxEditField:
- rect = QRect(x+2, y+2, wi-3-16, he-4);
- break;
-
- case SC_ComboBoxListBoxPopup:
- rect = cmb->rect;
- break;
-
- default:
- break;
- }
- }
- break;
-#ifndef QT_NO_WORKSPACE
- case CC_MdiControls:
- {
- int numSubControls = 0;
- if (option->subControls & SC_MdiCloseButton)
- ++numSubControls;
- if (option->subControls & SC_MdiMinButton)
- ++numSubControls;
- if (option->subControls & SC_MdiNormalButton)
- ++numSubControls;
- if (numSubControls == 0)
- break;
-
- int buttonWidth = option->rect.width()/ numSubControls;
- int offset = 0;
- switch (subControl) {
- case SC_MdiCloseButton:
- // Only one sub control, no offset needed.
- if (numSubControls == 1)
- break;
- offset += buttonWidth;
- //FALL THROUGH
- case SC_MdiNormalButton:
- // No offset needed if
- // 1) There's only one sub control
- // 2) We have a close button and a normal button (offset already added in SC_MdiClose)
- if (numSubControls == 1 || (numSubControls == 2 && !(option->subControls & SC_MdiMinButton)))
- break;
- if (option->subControls & SC_MdiNormalButton)
- offset += buttonWidth;
- break;
- default:
- break;
- }
- rect = QRect(offset, 0, buttonWidth, option->rect.height());
- break;
- }
-#endif // QT_NO_WORKSPACE
-
- default:
- rect = visualRect(option->direction, option->rect,
- QWindowsStyle::subControlRect(cc, option, subControl, widget));
- break;
- }
- return visualRect(option->direction, option->rect, rect);
-}
-
-/*!
- \reimp
-*/
-QSize QWindowsXPStyle::sizeFromContents(ContentsType ct, const QStyleOption *option,
- const QSize &contentsSize, const QWidget *widget) const
-{
- if (!QWindowsXPStylePrivate::useXP())
- return QWindowsStyle::sizeFromContents(ct, option, contentsSize, widget);
-
- QSize sz(contentsSize);
- switch (ct) {
- case CT_LineEdit:
- case CT_ComboBox:
- {
- XPThemeData buttontheme(widget, 0, QLatin1String("Button"));
- HTHEME theme = buttontheme.handle();
- MARGINS borderSize;
- if (theme) {
- int result = pGetThemeMargins(theme,
- NULL,
- BP_PUSHBUTTON,
- PBS_NORMAL,
- TMT_CONTENTMARGINS,
- NULL,
- &borderSize);
- if (result == S_OK) {
- sz += QSize(borderSize.cxLeftWidth + borderSize.cxRightWidth - 2,
- borderSize.cyBottomHeight + borderSize.cyTopHeight - 2);
- }
- const int textMargins = 2*(proxy()->pixelMetric(PM_FocusFrameHMargin) + 1);
- sz += QSize(qMax(pixelMetric(QStyle::PM_ScrollBarExtent, option, widget)
- + textMargins, 23), 0); //arrow button
- }
- }
- break;
- case CT_SpinBox:
- {
- //Spinbox adds frame twice
- sz = QWindowsStyle::sizeFromContents(ct, option, contentsSize, widget);
- int border = proxy()->pixelMetric(PM_SpinBoxFrameWidth, option, widget);
- sz -= QSize(2*border, 2*border);
- }
- break;
- case CT_TabWidget:
- sz += QSize(6, 6);
- break;
- case CT_Menu:
- sz += QSize(1, 0);
- break;
-#ifndef QT_NO_MENUBAR
- case CT_MenuBarItem:
- if (!sz.isEmpty())
- sz += QSize(windowsItemHMargin * 5 + 1, 6);
- break;
-#endif
- case CT_MenuItem:
- if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option))
- {
- if (menuitem->menuItemType != QStyleOptionMenuItem::Separator) {
- sz = QWindowsStyle::sizeFromContents(ct, option, sz, widget);
- sz.setHeight(sz.height() - 2);
- return sz;
- }
- }
- sz = QWindowsStyle::sizeFromContents(ct, option, sz, widget);
- break;
-
- case CT_MdiControls:
- if (const QStyleOptionComplex *styleOpt = qstyleoption_cast<const QStyleOptionComplex *>(option)) {
- int width = 0;
- if (styleOpt->subControls & SC_MdiMinButton)
- width += 17 + 1;
- if (styleOpt->subControls & SC_MdiNormalButton)
- width += 17 + 1;
- if (styleOpt->subControls & SC_MdiCloseButton)
- width += 17 + 1;
- sz = QSize(width, 19);
- } else {
- sz = QSize(54, 19);
- }
- break;
-
- default:
- sz = QWindowsStyle::sizeFromContents(ct, option, sz, widget);
- break;
- }
-
- return sz;
-}
-
-
-/*! \reimp */
-int QWindowsXPStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget,
- QStyleHintReturn *returnData) const
-{
- QWindowsXPStylePrivate *d = const_cast<QWindowsXPStylePrivate*>(d_func());
- if (!QWindowsXPStylePrivate::useXP())
- return QWindowsStyle::styleHint(hint, option, widget, returnData);
-
- int res = 0;
- switch (hint) {
-
- case SH_EtchDisabledText:
- res = (qobject_cast<const QLabel*>(widget) != 0);
- break;
-
- case SH_SpinControls_DisableOnBounds:
- res = 0;
- break;
-
- case SH_TitleBar_AutoRaise:
- case SH_TitleBar_NoBorder:
- res = 1;
- break;
-
- case SH_GroupBox_TextLabelColor:
- if (!widget || (widget && widget->isEnabled()))
- res = d->groupBoxTextColor;
- else
- res = d->groupBoxTextColorDisabled;
- break;
-
- case SH_Table_GridLineColor:
- res = 0xC0C0C0;
- break;
-
- case SH_WindowFrame_Mask:
- {
- res = 1;
- QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask *>(returnData);
- const QStyleOptionTitleBar *titlebar = qstyleoption_cast<const QStyleOptionTitleBar *>(option);
- if (mask && titlebar) {
- // Note certain themes will not return the whole window frame but only the titlebar part when
- // queried This function needs to return the entire window mask, hence we will only fetch the mask for the
- // titlebar itself and add the remaining part of the window rect at the bottom.
- int tbHeight = proxy()->pixelMetric(PM_TitleBarHeight, option, widget);
- QRect titleBarRect = option->rect;
- titleBarRect.setHeight(tbHeight);
- XPThemeData themeData;
- if (titlebar->titleBarState & Qt::WindowMinimized) {
- themeData = XPThemeData(widget, 0, QLatin1String("WINDOW"), WP_MINCAPTION, CS_ACTIVE, titleBarRect);
- } else
- themeData = XPThemeData(widget, 0, QLatin1String("WINDOW"), WP_CAPTION, CS_ACTIVE, titleBarRect);
- mask->region = d->region(themeData) +
- QRect(0, tbHeight, option->rect.width(), option->rect.height() - tbHeight);
- }
- }
- break;
-#ifndef QT_NO_RUBBERBAND
- case SH_RubberBand_Mask:
- if (qstyleoption_cast<const QStyleOptionRubberBand *>(option)) {
- res = 0;
- break;
- }
-#endif // QT_NO_RUBBERBAND
-
- case SH_ItemView_DrawDelegateFrame:
- res = 1;
- break;
-
- default:
- res =QWindowsStyle::styleHint(hint, option, widget, returnData);
- }
-
- return res;
-}
-
-/*! \reimp */
-QPalette QWindowsXPStyle::standardPalette() const
-{
- if (QWindowsXPStylePrivate::useXP() && QApplicationPrivate::sys_pal)
- return *QApplicationPrivate::sys_pal;
- else
- return QWindowsStyle::standardPalette();
-}
-
-/*!
- \reimp
-*/
-QPixmap QWindowsXPStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option,
- const QWidget *widget) const
-{
- if (!QWindowsXPStylePrivate::useXP())
- return QWindowsStyle::standardPixmap(standardPixmap, option, widget);
-
- switch(standardPixmap) {
- case SP_TitleBarMaxButton:
- case SP_TitleBarCloseButton:
- if (qstyleoption_cast<const QStyleOptionDockWidget *>(option))
- {
- if (widget && widget->isWindow()) {
- XPThemeData theme(widget, 0, QLatin1String("WINDOW"), WP_SMALLCLOSEBUTTON, CBS_NORMAL);
- if (theme.isValid()) {
- SIZE sz;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &sz);
- return QIcon(QWindowsStyle::standardPixmap(standardPixmap, option, widget)).pixmap(QSize(sz.cx, sz.cy));
- }
- }
- }
- break;
- default:
- break;
- }
- return QWindowsStyle::standardPixmap(standardPixmap, option, widget);
-}
-
-/*!
- \internal
-*/
-QIcon QWindowsXPStyle::standardIconImplementation(StandardPixmap standardIcon,
- const QStyleOption *option,
- const QWidget *widget) const
-{
- if (!QWindowsXPStylePrivate::useXP()) {
- return QWindowsStyle::standardIconImplementation(standardIcon, option, widget);
- }
-
- QWindowsXPStylePrivate *d = const_cast<QWindowsXPStylePrivate*>(d_func());
- switch(standardIcon) {
- case SP_TitleBarMaxButton:
- if (qstyleoption_cast<const QStyleOptionDockWidget *>(option))
- {
- if (d->dockFloat.isNull()) {
- XPThemeData themeSize(0, 0, QLatin1String("WINDOW"), WP_SMALLCLOSEBUTTON, CBS_NORMAL);
- XPThemeData theme(0, 0, QLatin1String("WINDOW"), WP_MAXBUTTON, MAXBS_NORMAL);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(themeSize.handle(), 0, themeSize.partId, themeSize.stateId, 0, TS_TRUE, &size);
- QPixmap pm = QPixmap(size.cx, size.cy);
- pm.fill(Qt::transparent);
- QPainter p(&pm);
- theme.painter = &p;
- theme.rect = QRect(0, 0, size.cx, size.cy);
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Normal, QIcon::Off); // Normal
- pm.fill(Qt::transparent);
- theme.stateId = MAXBS_PUSHED;
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Normal, QIcon::On); // Pressed
- pm.fill(Qt::transparent);
- theme.stateId = MAXBS_HOT;
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Active, QIcon::Off); // Hover
- pm.fill(Qt::transparent);
- theme.stateId = MAXBS_INACTIVE;
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Disabled, QIcon::Off); // Disabled
- }
- }
- if (widget && widget->isWindow())
- return d->dockFloat;
-
- }
- break;
- case SP_TitleBarCloseButton:
- if (qstyleoption_cast<const QStyleOptionDockWidget *>(option))
- {
- if (d->dockClose.isNull()) {
- XPThemeData theme(0, 0, QLatin1String("WINDOW"), WP_SMALLCLOSEBUTTON, CBS_NORMAL);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(theme.handle(), 0, theme.partId, theme.stateId, 0, TS_TRUE, &size);
- QPixmap pm = QPixmap(size.cx, size.cy);
- pm.fill(Qt::transparent);
- QPainter p(&pm);
- theme.painter = &p;
- theme.partId = WP_CLOSEBUTTON; // ####
- theme.rect = QRect(0, 0, size.cx, size.cy);
- d->drawBackground(theme);
- d->dockClose.addPixmap(pm, QIcon::Normal, QIcon::Off); // Normal
- pm.fill(Qt::transparent);
- theme.stateId = CBS_PUSHED;
- d->drawBackground(theme);
- d->dockClose.addPixmap(pm, QIcon::Normal, QIcon::On); // Pressed
- pm.fill(Qt::transparent);
- theme.stateId = CBS_HOT;
- d->drawBackground(theme);
- d->dockClose.addPixmap(pm, QIcon::Active, QIcon::Off); // Hover
- pm.fill(Qt::transparent);
- theme.stateId = CBS_INACTIVE;
- d->drawBackground(theme);
- d->dockClose.addPixmap(pm, QIcon::Disabled, QIcon::Off); // Disabled
- }
- }
- if (widget && widget->isWindow())
- return d->dockClose;
- }
- break;
- case SP_TitleBarNormalButton:
- if (qstyleoption_cast<const QStyleOptionDockWidget *>(option))
- {
- if (d->dockFloat.isNull()) {
- XPThemeData themeSize(0, 0, QLatin1String("WINDOW"), WP_SMALLCLOSEBUTTON, CBS_NORMAL);
- XPThemeData theme(0, 0, QLatin1String("WINDOW"), WP_RESTOREBUTTON, RBS_NORMAL);
- if (theme.isValid()) {
- SIZE size;
- pGetThemePartSize(themeSize.handle(), 0, themeSize.partId, themeSize.stateId, 0, TS_TRUE, &size);
- QPixmap pm = QPixmap(size.cx, size.cy);
- pm.fill(Qt::transparent);
- QPainter p(&pm);
- theme.painter = &p;
- theme.rect = QRect(0, 0, size.cx, size.cy);
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Normal, QIcon::Off); // Normal
- pm.fill(Qt::transparent);
- theme.stateId = RBS_PUSHED;
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Normal, QIcon::On); // Pressed
- pm.fill(Qt::transparent);
- theme.stateId = RBS_HOT;
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Active, QIcon::Off); // Hover
- pm.fill(Qt::transparent);
- theme.stateId = RBS_INACTIVE;
- d->drawBackground(theme);
- d->dockFloat.addPixmap(pm, QIcon::Disabled, QIcon::Off); // Disabled
- }
- }
- if (widget && widget->isWindow())
- return d->dockFloat;
-
- }
- break;
- default:
- break;
- }
-
- return QWindowsStyle::standardIconImplementation(standardIcon, option, widget);
-}
-
-/*!
- \internal
-
- Constructs a QWindowsXPStyle object.
-*/
-QWindowsXPStyle::QWindowsXPStyle(QWindowsXPStylePrivate &dd) : QWindowsStyle(dd)
-{
-}
-
-
-// Debugging code ---------------------------------------------------------------------[ START ]---
-// The code for this point on is not compiled by default, but only used as assisting
-// debugging code when you uncomment the DEBUG_XP_STYLE define at the top of the file.
-
-#ifdef DEBUG_XP_STYLE
-// The schema file expects these to be defined by the user.
-#define TMT_ENUMDEF 8
-#define TMT_ENUMVAL TEXT('A')
-#define TMT_ENUM TEXT('B')
-#define SCHEMA_STRINGS // For 2nd pass on schema file
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <tmschema.h>
-QT_END_INCLUDE_NAMESPACE
-
-// A property's value, type and name combo
-struct PropPair {
- int propValue;
- int propType;
- LPCWSTR propName;
-};
-
-// Operator for sorting of PropPairs
-bool operator<(PropPair a, PropPair b) {
- return wcscmp(a.propName, b.propName) < 0;
-}
-
-// Our list of all possible properties
-static QList<PropPair> all_props;
-
-
-/*! \internal
- Dumps a portion of the full native DIB section double buffer.
- The DIB section double buffer is only used when doing special
- transformations to the theme part, or when the real double
- buffer in the paintengine does not have an HDC we may use
- directly.
- Since we cannot rely on the pixel data we get from Microsoft
- when drawing into the DIB section, we use this function to
- see the actual data we got, and can determin the appropriate
- action.
-*/
-void QWindowsXPStylePrivate::dumpNativeDIB(int w, int h)
-{
- if (w && h) {
- static int pCount = 0;
- DWORD *bufPix = (DWORD*)bufferPixels;
-
- char *bufferDump = new char[bufferH * bufferW * 16];
- char *bufferPos = bufferDump;
-
- memset(bufferDump, 0, sizeof(bufferDump));
- bufferPos += sprintf(bufferPos, "const int pixelBufferW%d = %d;\n", pCount, w);
- bufferPos += sprintf(bufferPos, "const int pixelBufferH%d = %d;\n", pCount, h);
- bufferPos += sprintf(bufferPos, "const unsigned DWORD pixelBuffer%d[] = {", pCount);
- for (int iy = 0; iy < h; ++iy) {
- bufferPos += sprintf(bufferPos, "\n ");
- bufPix = (DWORD*)(bufferPixels + (iy * bufferW * 4));
- for (int ix = 0; ix < w; ++ix) {
- bufferPos += sprintf(bufferPos, "0x%08x, ", *bufPix);
- ++bufPix;
- }
- }
- bufferPos += sprintf(bufferPos, "\n};\n\n");
- printf(bufferDump);
-
- delete[] bufferDump;
- ++pCount;
- }
-}
-
-/*! \internal
- Shows the value of a given property for a part.
-*/
-static void showProperty(XPThemeData &themeData, const PropPair &prop)
-{
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &origin);
- const char *originStr;
- switch(origin) {
- case PO_STATE:
- originStr = "State ";
- break;
- case PO_PART:
- originStr = "Part ";
- break;
- case PO_CLASS:
- originStr = "Class ";
- break;
- case PO_GLOBAL:
- originStr = "Globl ";
- break;
- case PO_NOTFOUND:
- default:
- originStr = "Unkwn ";
- break;
- }
-
- switch(prop.propType) {
- case TMT_STRING:
- {
- wchar_t buffer[512];
- pGetThemeString(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, buffer, 512);
- printf(" (%sString) %-20S: %S\n", originStr, prop.propName, buffer);
- }
- break;
- case TMT_ENUM:
- {
- int result = -1;
- pGetThemeEnumValue(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sEnum) %-20S: %d\n", originStr, prop.propName, result);
- }
- break;
- case TMT_INT:
- {
- int result = -1;
- pGetThemeInt(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sint) %-20S: %d\n", originStr, prop.propName, result);
- }
- break;
- case TMT_BOOL:
- {
- BOOL result = false;
- pGetThemeBool(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sbool) %-20S: %d\n", originStr, prop.propName, result);
- }
- break;
- case TMT_COLOR:
- {
- COLORREF result = 0;
- pGetThemeColor(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%scolor) %-20S: 0x%08X\n", originStr, prop.propName, result);
- }
- break;
- case TMT_MARGINS:
- {
- MARGINS result;
- memset(&result, 0, sizeof(result));
- pGetThemeMargins(themeData.handle(), 0, themeData.partId, themeData.stateId, prop.propValue, 0, &result);
- printf(" (%smargins) %-20S: (%d, %d, %d, %d)\n", originStr,
- prop.propName, result.cxLeftWidth, result.cyTopHeight, result.cxRightWidth, result.cyBottomHeight);
- }
- break;
- case TMT_FILENAME:
- {
- wchar_t buffer[512];
- pGetThemeFilename(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, buffer, 512);
- printf(" (%sfilename)%-20S: %S\n", originStr, prop.propName, buffer);
- }
- break;
- case TMT_SIZE:
- {
- SIZE result1;
- SIZE result2;
- SIZE result3;
- memset(&result1, 0, sizeof(result1));
- memset(&result2, 0, sizeof(result2));
- memset(&result3, 0, sizeof(result3));
- pGetThemePartSize(themeData.handle(), 0, themeData.partId, themeData.stateId, 0, TS_MIN, &result1);
- pGetThemePartSize(themeData.handle(), 0, themeData.partId, themeData.stateId, 0, TS_TRUE, &result2);
- pGetThemePartSize(themeData.handle(), 0, themeData.partId, themeData.stateId, 0, TS_DRAW, &result3);
- printf(" (%ssize) %-20S: Min (%d, %d), True(%d, %d), Draw(%d, %d)\n", originStr, prop.propName,
- result1.cx, result1.cy, result2.cx, result2.cy, result3.cx, result3.cy);
- }
- break;
- case TMT_POSITION:
- {
- POINT result;
- memset(&result, 0, sizeof(result));
- pGetThemePosition(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sPosition)%-20S: (%d, %d)\n", originStr, prop.propName, result.x, result.y);
- }
- break;
- case TMT_RECT:
- {
- RECT result;
- memset(&result, 0, sizeof(result));
- pGetThemeRect(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sRect) %-20S: (%d, %d, %d, %d)\n", originStr, prop.propName, result.left, result.top, result.right, result.bottom);
- }
- break;
- case TMT_FONT:
- {
- LOGFONT result;
- memset(&result, 0, sizeof(result));
- pGetThemeFont(themeData.handle(), 0, themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sFont) %-20S: %S height(%d) width(%d) weight(%d)\n", originStr, prop.propName,
- result.lfFaceName, result.lfHeight, result.lfWidth, result.lfWeight);
- }
- break;
- case TMT_INTLIST:
- {
- INTLIST result;
- memset(&result, 0, sizeof(result));
- pGetThemeIntList(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &result);
- printf(" (%sInt list)%-20S: { ", originStr, prop.propName);
- for (int i = 0; i < result.iValueCount; ++i)
- printf("%d ", result.iValues[i]);
- printf("}\n");
- }
- break;
- default:
- printf(" %s%S : Unknown property type (%d)!\n", originStr, prop.propName, prop.propType);
- }
-}
-
-/*! \internal
- Dump all valid properties for a part.
- If it's the first time this function is called, then the name,
- enum value and documentation of all properties are shown, as
- well as all global properties.
-*/
-void QWindowsXPStylePrivate::showProperties(XPThemeData &themeData)
-{
- if (!all_props.count()) {
- const TMSCHEMAINFO *infoTable = GetSchemaInfo();
- for (int i = 0; i < infoTable->iPropCount; ++i) {
- int propType = infoTable->pPropTable[i].bPrimVal;
- int propValue = infoTable->pPropTable[i].sEnumVal;
- LPCWSTR propName = infoTable->pPropTable[i].pszName;
-
- switch(propType) {
- case TMT_ENUMDEF:
- case TMT_ENUMVAL:
- continue;
- default:
- if (propType != propValue) {
- PropPair prop;
- prop.propValue = propValue;
- prop.propName = propName;
- prop.propType = propType;
- all_props.append(prop);
- }
- }
- }
- qSort(all_props);
-
- {// List all properties
- printf("part properties count = %d:\n", all_props.count());
- printf(" Enum Property Name Description\n");
- printf("-----------------------------------------------------------\n");
- wchar_t themeName[256];
- pGetCurrentThemeName(themeName, 256, 0, 0, 0, 0);
- for (int j = 0; j < all_props.count(); ++j) {
- PropPair prop = all_props.at(j);
- wchar_t buf[500];
- pGetThemeDocumentationProperty(themeName, prop.propName, buf, 500);
- printf("%3d: (%4d) %-20S %S\n", j, prop.propValue, prop.propName, buf);
- }
- }
-
- {// Show Global values
- printf("Global Properties:\n");
- for (int j = 0; j < all_props.count(); ++j) {
- PropPair prop = all_props.at(j);
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &origin);
- if (origin == PO_GLOBAL) {
- showProperty(themeData, prop);
- }
- }
- }
- }
-
- for (int j = 0; j < all_props.count(); ++j) {
- PropPair prop = all_props.at(j);
- PROPERTYORIGIN origin = PO_NOTFOUND;
- pGetThemePropertyOrigin(themeData.handle(), themeData.partId, themeData.stateId, prop.propValue, &origin);
- if (origin != PO_NOTFOUND)
- {
- showProperty(themeData, prop);
- }
- }
-}
-#endif
-// Debugging code -----------------------------------------------------------------------[ END ]---
-
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_WINDOWSXP
diff --git a/src/gui/styles/qwindowsxpstyle.h b/src/gui/styles/qwindowsxpstyle.h
deleted file mode 100644
index 08582d13a1..0000000000
--- a/src/gui/styles/qwindowsxpstyle.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSXPSTYLE_H
-#define QWINDOWSXPSTYLE_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#if !defined(QT_NO_STYLE_WINDOWSXP)
-
-class QWindowsXPStylePrivate;
-class Q_GUI_EXPORT QWindowsXPStyle : public QWindowsStyle
-{
- Q_OBJECT
-public:
- QWindowsXPStyle();
- QWindowsXPStyle(QWindowsXPStylePrivate &dd);
- ~QWindowsXPStyle();
-
- void unpolish(QApplication*);
- void polish(QApplication*);
- void polish(QWidget*);
- void polish(QPalette&);
- void unpolish(QWidget*);
-
- void drawPrimitive(PrimitiveElement pe, const QStyleOption *option, QPainter *p,
- const QWidget *widget = 0) const;
- void drawControl(ControlElement element, const QStyleOption *option, QPainter *p,
- const QWidget *wwidget = 0) const;
- QRect subElementRect(SubElement r, const QStyleOption *option, const QWidget *widget = 0) const;
- QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *option, SubControl sc,
- const QWidget *widget = 0) const;
- void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *option, QPainter *p,
- const QWidget *widget = 0) const;
- QSize sizeFromContents(ContentsType ct, const QStyleOption *option, const QSize &contentsSize,
- const QWidget *widget = 0) const;
- int pixelMetric(PixelMetric pm, const QStyleOption *option = 0,
- const QWidget *widget = 0) const;
- int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const;
-
- QPalette standardPalette() const;
- QPixmap standardPixmap(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget = 0) const;
-
-protected Q_SLOTS:
- QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *option,
- const QWidget *widget = 0) const;
-
-private:
- Q_DISABLE_COPY(QWindowsXPStyle)
- Q_DECLARE_PRIVATE(QWindowsXPStyle)
- friend class QStyleFactory;
- void *reserved;
-};
-
-#endif // QT_NO_STYLE_WINDOWSXP
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWINDOWSXPSTYLE_H
diff --git a/src/gui/styles/qwindowsxpstyle_p.h b/src/gui/styles/qwindowsxpstyle_p.h
deleted file mode 100644
index 5509cba512..0000000000
--- a/src/gui/styles/qwindowsxpstyle_p.h
+++ /dev/null
@@ -1,356 +0,0 @@
-/****************************************************************************
-**
-** 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 QWINDOWSXPSTYLE_P_H
-#define QWINDOWSXPSTYLE_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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qwindowsxpstyle.h"
-#include "qwindowsstyle_p.h"
-#include <qmap.h>
-#include <qt_windows.h>
-
-// Note, these tests are duplicated in qwizard_win.cpp.
-#ifdef Q_CC_GNU
-# include <w32api.h>
-# if (__W32API_MAJOR_VERSION >= 3 || (__W32API_MAJOR_VERSION == 2 && __W32API_MINOR_VERSION >= 5))
-# ifdef _WIN32_WINNT
-# undef _WIN32_WINNT
-# endif
-# define _WIN32_WINNT 0x0501
-# include <commctrl.h>
-# endif
-#endif
-
-#include <uxtheme.h>
-
-#if WINVER >= 0x0600
-#include <vssym32.h>
-#else
-#include <tmschema.h>
-#endif
-
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-// Older Platform SDKs do not have the extended DrawThemeBackgroundEx
-// function. We add the needed parts here, and use the extended
-// function dynamically, if available in uxtheme.dll. Else, we revert
-// back to using the DrawThemeBackground function.
-#ifndef DTBG_OMITBORDER
-# ifndef DTBG_CLIPRECT
-# define DTBG_CLIPRECT 0x00000001
-# endif
-# ifndef DTBG_DRAWSOLID
-# define DTBG_DRAWSOLID 0x00000002
-# endif
-# ifndef DTBG_OMITBORDER
-# define DTBG_OMITBORDER 0x00000004
-# endif
-# ifndef DTBG_OMITCONTENT
-# define DTBG_OMITCONTENT 0x00000008
-# endif
-# ifndef DTBG_COMPUTINGREGION
-# define DTBG_COMPUTINGREGION 0x00000010
-# endif
-# ifndef DTBG_MIRRORDC
-# define DTBG_MIRRORDC 0x00000020
-# endif
- typedef struct _DTBGOPTS
- {
- DWORD dwSize;
- DWORD dwFlags;
- RECT rcClip;
- } DTBGOPTS, *PDTBGOPTS;
-#endif // _DTBGOPTS
-
-// Undefined for some compile environments
-#ifndef TMT_TEXTCOLOR
-# define TMT_TEXTCOLOR 3803
-#endif
-#ifndef TMT_BORDERCOLORHINT
-# define TMT_BORDERCOLORHINT 3822
-#endif
-#ifndef TMT_BORDERSIZE
-# define TMT_BORDERSIZE 2403
-#endif
-#ifndef TMT_BORDERONLY
-# define TMT_BORDERONLY 2203
-#endif
-#ifndef TMT_TRANSPARENTCOLOR
-# define TMT_TRANSPARENTCOLOR 3809
-#endif
-#ifndef TMT_CAPTIONMARGINS
-# define TMT_CAPTIONMARGINS 3603
-#endif
-#ifndef TMT_CONTENTMARGINS
-# define TMT_CONTENTMARGINS 3602
-#endif
-#ifndef TMT_SIZINGMARGINS
-# define TMT_SIZINGMARGINS 3601
-#endif
-#ifndef TMT_GLYPHTYPE
-# define TMT_GLYPHTYPE 4012
-#endif
-#ifndef TMT_BGTYPE
-# define TMT_BGTYPE 4001
-#endif
-#ifndef TMT_TEXTSHADOWTYPE
-# define TMT_TEXTSHADOWTYPE 4010
-#endif
-#ifndef TMT_BORDERCOLOR
-# define TMT_BORDERCOLOR 3801
-#endif
-#ifndef BT_IMAGEFILE
-# define BT_IMAGEFILE 0
-#endif
-#ifndef BT_BORDERFILL
-# define BT_BORDERFILL 1
-#endif
-#ifndef BT_NONE
-# define BT_NONE 2
-#endif
-#ifndef TMT_FILLCOLOR
-# define TMT_FILLCOLOR 3802
-#endif
-#ifndef TMT_PROGRESSCHUNKSIZE
-# define TMT_PROGRESSCHUNKSIZE 2411
-#endif
-
-// TMT_TEXTSHADOWCOLOR is wrongly defined in mingw
-#if TMT_TEXTSHADOWCOLOR != 3818
-#undef TMT_TEXTSHADOWCOLOR
-#define TMT_TEXTSHADOWCOLOR 3818
-#endif
-#ifndef TST_NONE
-# define TST_NONE 0
-#endif
-
-#ifndef GT_NONE
-# define GT_NONE 0
-#endif
-#ifndef GT_IMAGEGLYPH
-# define GT_IMAGEGLYPH 1
-#endif
-
-// These defines are missing from the tmschema, but still exist as
-// states for their parts
-#ifndef MINBS_INACTIVE
-#define MINBS_INACTIVE 5
-#endif
-#ifndef MAXBS_INACTIVE
-#define MAXBS_INACTIVE 5
-#endif
-#ifndef RBS_INACTIVE
-#define RBS_INACTIVE 5
-#endif
-#ifndef HBS_INACTIVE
-#define HBS_INACTIVE 5
-#endif
-#ifndef CBS_INACTIVE
-#define CBS_INACTIVE 5
-#endif
-
-// Uncomment define below to build debug assisting code, and output
-// #define DEBUG_XP_STYLE
-
-#if !defined(QT_NO_STYLE_WINDOWSXP)
-
-// Declarations -----------------------------------------------------------------------------------
-class XPThemeData
-{
-public:
- XPThemeData(const QWidget *w = 0, QPainter *p = 0, const QString &theme = QString(),
- int part = 0, int state = 0, const QRect &r = QRect())
- : widget(w), painter(p), name(theme), htheme(0), partId(part), stateId(state),
- mirrorHorizontally(false), mirrorVertically(false), noBorder(false),
- noContent(false), rotate(0), rect(r)
- {}
-
- HRGN mask();
- HTHEME handle();
-
- RECT toRECT(const QRect &qr);
- bool isValid();
-
- const QWidget *widget;
- QPainter *painter;
- QString name;
- HTHEME htheme;
- int partId;
- int stateId;
-
- uint mirrorHorizontally : 1;
- uint mirrorVertically : 1;
- uint noBorder : 1;
- uint noContent : 1;
- uint rotate;
- QRect rect;
-};
-
-struct ThemeMapKey {
- QString name;
- int partId;
- int stateId;
- bool noBorder;
- bool noContent;
-
- ThemeMapKey() : partId(-1), stateId(-1) {}
- ThemeMapKey(const XPThemeData &data)
- : name(data.name), partId(data.partId), stateId(data.stateId),
- noBorder(data.noBorder), noContent(data.noContent) {}
-
-};
-
-inline uint qHash(const ThemeMapKey &key)
-{ return qHash(key.name) ^ key.partId ^ key.stateId; }
-
-inline bool operator==(const ThemeMapKey &k1, const ThemeMapKey &k2)
-{
- return k1.name == k2.name
- && k1.partId == k2.partId
- && k1.stateId == k2.stateId;
-}
-
-enum AlphaChannelType {
- UnknownAlpha = -1, // Alpha of part & state not yet known
- NoAlpha, // Totally opaque, no need to touch alpha (RGB)
- MaskAlpha, // Alpha channel must be fixed (ARGB)
- RealAlpha // Proper alpha values from Windows (ARGB_Premultiplied)
-};
-
-struct ThemeMapData {
- AlphaChannelType alphaType; // Which type of alpha on part & state
-
- bool dataValid : 1; // Only used to detect if hash value is ok
- bool partIsTransparent : 1;
- bool hasAnyData : 1; // False = part & state has not data, NOP
- bool hasAlphaChannel : 1; // True = part & state has real Alpha
- bool wasAlphaSwapped : 1; // True = alpha channel needs to be swapped
- bool hadInvalidAlpha : 1; // True = alpha channel contained invalid alpha values
-
- ThemeMapData() : dataValid(false), partIsTransparent(false), hasAnyData(false),
- hasAlphaChannel(false), wasAlphaSwapped(false), hadInvalidAlpha(false) {}
-};
-
-class QWindowsXPStylePrivate : public QWindowsStylePrivate
-{
- Q_DECLARE_PUBLIC(QWindowsXPStyle)
-public:
- QWindowsXPStylePrivate()
- : QWindowsStylePrivate(), hasInitColors(false), bufferDC(0), bufferBitmap(0), nullBitmap(0),
- bufferPixels(0), bufferW(0), bufferH(0)
- { init(); }
-
- ~QWindowsXPStylePrivate()
- { cleanup(); }
-
- static HWND winId(const QWidget *widget);
-
- void init(bool force = false);
- void cleanup(bool force = false);
- void cleanupHandleMap();
- const QPixmap *tabBody(QWidget *widget);
-
- HBITMAP buffer(int w = 0, int h = 0);
- HDC bufferHDC()
- { return bufferDC;}
-
- static bool resolveSymbols();
- static bool useXP(bool update = false);
-
- bool isTransparent(XPThemeData &themeData);
- QRegion region(XPThemeData &themeData);
-
- void setTransparency(QWidget *widget, XPThemeData &themeData);
- void drawBackground(XPThemeData &themeData);
- void drawBackgroundThruNativeBuffer(XPThemeData &themeData);
- void drawBackgroundDirectly(XPThemeData &themeData);
-
- bool hasAnyData(const QRect &rect);
- bool hasAlphaChannel(const QRect &rect);
- bool fixAlphaChannel(const QRect &rect);
- bool swapAlphaChannel(const QRect &rect, bool allPixels = false);
-
- QRgb groupBoxTextColor;
- QRgb groupBoxTextColorDisabled;
- QRgb sliderTickColor;
- bool hasInitColors;
-
- static QMap<QString,HTHEME> *handleMap;
-
- QIcon dockFloat, dockClose;
-
-private:
-#ifdef DEBUG_XP_STYLE
- void dumpNativeDIB(int w, int h);
- void showProperties(XPThemeData &themeData);
-#endif
-
- static QBasicAtomicInt ref;
- static bool use_xp;
- static QWidget *limboWidget;
- static QPixmap *tabbody;
-
- QHash<ThemeMapKey, ThemeMapData> alphaCache;
- HDC bufferDC;
- HBITMAP bufferBitmap;
- HBITMAP nullBitmap;
- uchar *bufferPixels;
- int bufferW, bufferH;
-};
-
-#endif // QT_NO_STYLE_WINDOWS
-
-QT_END_NAMESPACE
-
-#endif //QWINDOWSXPSTYLE_P_H
diff --git a/src/gui/styles/styles.pri b/src/gui/styles/styles.pri
deleted file mode 100644
index b20caf726e..0000000000
--- a/src/gui/styles/styles.pri
+++ /dev/null
@@ -1,194 +0,0 @@
-# Qt styles module
-
-HEADERS += \
- styles/qdrawutil.h \
- styles/qstyle.h \
- styles/qstylefactory.h \
- styles/qstyleoption.h \
- styles/qstyleplugin.h \
- styles/qcommonstylepixmaps_p.h \
- styles/qcommonstyle.h \
- styles/qstylehelper_p.h \
- styles/qproxystyle.h \
- styles/qproxystyle_p.h \
- styles/qstylepainter.h \
- styles/qstylesheetstyle_p.h
-
-SOURCES += \
- styles/qdrawutil.cpp \
- styles/qstyle.cpp \
- styles/qstylefactory.cpp \
- styles/qstyleoption.cpp \
- styles/qstyleplugin.cpp \
- styles/qstylehelper.cpp \
- styles/qcommonstyle.cpp \
- styles/qproxystyle.cpp \
- styles/qstylepainter.cpp \
- styles/qstylesheetstyle.cpp \
- styles/qstylesheetstyle_default.cpp
-
-wince* {
- RESOURCES += styles/qstyle_wince.qrc
-} else:symbian {
- RESOURCES += styles/qstyle_s60.qrc
-} else {
- RESOURCES += styles/qstyle.qrc
-}
-
-contains( styles, all ) {
- styles = mac windows windowsxp windowsvista
-}
-
-x11|qpa|!macx-*:styles -= mac
-
-x11{
- QMAKE_CXXFLAGS += $$QT_CFLAGS_QGTKSTYLE
- LIBS_PRIVATE += $$QT_LIBS_QGTKSTYLE
- styles += gtk
-}
-
-contains( styles, mac ) {
- HEADERS += \
- styles/qmacstyle_mac.h \
- styles/qmacstylepixmaps_mac_p.h \
- styles/qmacstyle_mac_p.h
- OBJECTIVE_SOURCES += styles/qmacstyle_mac.mm
-
- !contains( styles, windows ) {
- message( mac requires windows )
- styles += windows
- DEFINES+= QT_STYLE_WINDOWS
- }
-} else {
- DEFINES += QT_NO_STYLE_MAC
-}
-
-contains( styles, cde ) {
- HEADERS += styles/qcdestyle.h
- SOURCES += styles/qcdestyle.cpp
-
- !contains( styles, motif ) {
- message( cde requires motif )
- styles += motif
- DEFINES+= QT_STYLE_MOTIF
- }
-} else {
- DEFINES += QT_NO_STYLE_CDE
-}
-
-contains( styles, windowsvista ) {
- HEADERS += styles/qwindowsvistastyle.h
- HEADERS += styles/qwindowsvistastyle_p.h
- SOURCES += styles/qwindowsvistastyle.cpp
- !contains( styles, windowsxp ) {
- message( windowsvista requires windowsxp )
- styles += windowsxp
- DEFINES+= QT_STYLE_WINDOWSXP
- }
-} else {
- DEFINES += QT_NO_STYLE_WINDOWSVISTA
-}
-
-contains( styles, windowsxp ) {
- HEADERS += styles/qwindowsxpstyle.h
- SOURCES += styles/qwindowsxpstyle.cpp
- !contains( styles, windows ) {
- message( windowsxp requires windows )
- styles += windows
- DEFINES+= QT_STYLE_WINDOWS
- }
-} else {
- DEFINES += QT_NO_STYLE_WINDOWSXP
-}
-
-contains( styles, plastique ) {
- HEADERS += styles/qplastiquestyle.h
- SOURCES += styles/qplastiquestyle.cpp
- !contains( styles, windows ) {
- message( plastique requires windows )
- styles += windows
- DEFINES+= QT_STYLE_WINDOWS
- }
-} else {
- DEFINES += QT_NO_STYLE_PLASTIQUE
-}
-
-contains( styles, gtk ) {
- HEADERS += styles/qgtkstyle.h
- HEADERS += styles/qgtkpainter_p.h
- HEADERS += styles/qgtkstyle_p.h
- SOURCES += styles/qgtkstyle.cpp
- SOURCES += styles/qgtkpainter.cpp
- SOURCES += styles/qgtkstyle_p.cpp
- !contains( styles, cleanlooks ) {
- styles += cleanlooks
- DEFINES+= QT_STYLE_CLEANLOOKS
- }
-} else {
- DEFINES += QT_NO_STYLE_GTK
-}
-
-contains( styles, cleanlooks ) {
- HEADERS += styles/qcleanlooksstyle.h
- HEADERS += styles/qcleanlooksstyle_p.h
- SOURCES += styles/qcleanlooksstyle.cpp
- !contains( styles, windows ) {
- styles += windows
- DEFINES+= QT_STYLE_WINDOWS
- }
-} else {
- DEFINES += QT_NO_STYLE_CLEANLOOKS
-}
-
-contains( styles, windows ) {
- HEADERS += styles/qwindowsstyle.h
- SOURCES += styles/qwindowsstyle.cpp
-} else {
- DEFINES += QT_NO_STYLE_WINDOWS
-}
-
-contains( styles, motif ) {
- HEADERS += styles/qmotifstyle.h
- SOURCES += styles/qmotifstyle.cpp
-} else {
- DEFINES += QT_NO_STYLE_MOTIF
-}
-
-contains( styles, windowsce ) {
- HEADERS += styles/qwindowscestyle.h
- SOURCES += styles/qwindowscestyle.cpp
-} else {
- DEFINES += QT_NO_STYLE_WINDOWSCE
-}
-
-contains( styles, windowsmobile ) {
- HEADERS += styles/qwindowsmobilestyle.h
- SOURCES += styles/qwindowsmobilestyle.cpp
-} else {
- DEFINES += QT_NO_STYLE_WINDOWSMOBILE
-}
-
-contains( styles, s60 ):contains(QT_CONFIG, s60) {
- HEADERS += \
- styles/qs60style.h \
- styles/qs60style_p.h
- SOURCES += styles/qs60style.cpp
- symbian {
- SOURCES += styles/qs60style_s60.cpp
- LIBS += -legul -lbmpanim
- contains(CONFIG, is_using_gnupoc) {
- LIBS += -laknicon -laknskins -laknskinsrv -lfontutils
- } else {
- LIBS += -lAknIcon -lAKNSKINS -lAKNSKINSRV -lFontUtils
- }
- } else {
- SOURCES += styles/qs60style_simulated.cpp
- RESOURCES += styles/qstyle_s60_simulated.qrc
- }
-} else {
- symbian {
- HEADERS += styles/qs60style.h
- SOURCES += styles/qs60style_stub.cpp
- }
- DEFINES += QT_NO_STYLE_S60
-}
diff --git a/src/gui/symbian/images/blank.png b/src/gui/symbian/images/blank.png
deleted file mode 100644
index bd396de62e..0000000000
--- a/src/gui/symbian/images/blank.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/busy12.png b/src/gui/symbian/images/busy12.png
deleted file mode 100644
index 909e70fa4f..0000000000
--- a/src/gui/symbian/images/busy12.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/busy3.png b/src/gui/symbian/images/busy3.png
deleted file mode 100644
index 983f5d8b8f..0000000000
--- a/src/gui/symbian/images/busy3.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/busy6.png b/src/gui/symbian/images/busy6.png
deleted file mode 100644
index b2e878074f..0000000000
--- a/src/gui/symbian/images/busy6.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/busy9.png b/src/gui/symbian/images/busy9.png
deleted file mode 100644
index e093d015c5..0000000000
--- a/src/gui/symbian/images/busy9.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/closehand.png b/src/gui/symbian/images/closehand.png
deleted file mode 100644
index 05534f580d..0000000000
--- a/src/gui/symbian/images/closehand.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/cross.png b/src/gui/symbian/images/cross.png
deleted file mode 100644
index 50da7aafc3..0000000000
--- a/src/gui/symbian/images/cross.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/forbidden.png b/src/gui/symbian/images/forbidden.png
deleted file mode 100644
index a3a0fd61e1..0000000000
--- a/src/gui/symbian/images/forbidden.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/handpoint.png b/src/gui/symbian/images/handpoint.png
deleted file mode 100644
index a221548d22..0000000000
--- a/src/gui/symbian/images/handpoint.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/ibeam.png b/src/gui/symbian/images/ibeam.png
deleted file mode 100644
index ace2fada1c..0000000000
--- a/src/gui/symbian/images/ibeam.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/openhand.png b/src/gui/symbian/images/openhand.png
deleted file mode 100644
index 6f232f0d8f..0000000000
--- a/src/gui/symbian/images/openhand.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/pointer.png b/src/gui/symbian/images/pointer.png
deleted file mode 100644
index 677404e250..0000000000
--- a/src/gui/symbian/images/pointer.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/sizeall.png b/src/gui/symbian/images/sizeall.png
deleted file mode 100644
index 29500677eb..0000000000
--- a/src/gui/symbian/images/sizeall.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/sizebdiag.png b/src/gui/symbian/images/sizebdiag.png
deleted file mode 100644
index f565a3a7a1..0000000000
--- a/src/gui/symbian/images/sizebdiag.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/sizefdiag.png b/src/gui/symbian/images/sizefdiag.png
deleted file mode 100644
index 9493f12723..0000000000
--- a/src/gui/symbian/images/sizefdiag.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/sizehor.png b/src/gui/symbian/images/sizehor.png
deleted file mode 100644
index 217bf39fe2..0000000000
--- a/src/gui/symbian/images/sizehor.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/sizever.png b/src/gui/symbian/images/sizever.png
deleted file mode 100644
index 2c99038c3f..0000000000
--- a/src/gui/symbian/images/sizever.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/splith.png b/src/gui/symbian/images/splith.png
deleted file mode 100644
index 343bed529a..0000000000
--- a/src/gui/symbian/images/splith.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/splitv.png b/src/gui/symbian/images/splitv.png
deleted file mode 100644
index 69ee4163e8..0000000000
--- a/src/gui/symbian/images/splitv.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/uparrow.png b/src/gui/symbian/images/uparrow.png
deleted file mode 100644
index 92dd933856..0000000000
--- a/src/gui/symbian/images/uparrow.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait1.png b/src/gui/symbian/images/wait1.png
deleted file mode 100644
index 5aebaab1f9..0000000000
--- a/src/gui/symbian/images/wait1.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait10.png b/src/gui/symbian/images/wait10.png
deleted file mode 100644
index 3b549b08ed..0000000000
--- a/src/gui/symbian/images/wait10.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait11.png b/src/gui/symbian/images/wait11.png
deleted file mode 100644
index 24a943fa68..0000000000
--- a/src/gui/symbian/images/wait11.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait12.png b/src/gui/symbian/images/wait12.png
deleted file mode 100644
index 15afd4daa2..0000000000
--- a/src/gui/symbian/images/wait12.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait2.png b/src/gui/symbian/images/wait2.png
deleted file mode 100644
index f2022b2853..0000000000
--- a/src/gui/symbian/images/wait2.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait3.png b/src/gui/symbian/images/wait3.png
deleted file mode 100644
index 5b73e57124..0000000000
--- a/src/gui/symbian/images/wait3.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait4.png b/src/gui/symbian/images/wait4.png
deleted file mode 100644
index 17a03396e0..0000000000
--- a/src/gui/symbian/images/wait4.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait5.png b/src/gui/symbian/images/wait5.png
deleted file mode 100644
index 16a5c231f2..0000000000
--- a/src/gui/symbian/images/wait5.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait6.png b/src/gui/symbian/images/wait6.png
deleted file mode 100644
index 2870093a30..0000000000
--- a/src/gui/symbian/images/wait6.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait7.png b/src/gui/symbian/images/wait7.png
deleted file mode 100644
index 54f75a1db0..0000000000
--- a/src/gui/symbian/images/wait7.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait8.png b/src/gui/symbian/images/wait8.png
deleted file mode 100644
index 1d370c752e..0000000000
--- a/src/gui/symbian/images/wait8.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/wait9.png b/src/gui/symbian/images/wait9.png
deleted file mode 100644
index c28096fe63..0000000000
--- a/src/gui/symbian/images/wait9.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/images/whatsthis.png b/src/gui/symbian/images/whatsthis.png
deleted file mode 100644
index 3386ef0c50..0000000000
--- a/src/gui/symbian/images/whatsthis.png
+++ /dev/null
Binary files differ
diff --git a/src/gui/symbian/qsymbianevent.cpp b/src/gui/symbian/qsymbianevent.cpp
deleted file mode 100644
index e177d1702b..0000000000
--- a/src/gui/symbian/qsymbianevent.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsymbianevent.h"
-#include <qdebug.h>
-
-#include <w32std.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QSymbianEvent
- \brief The QSymbianEvent class contains a Symbian event of any type.
- \since 4.6
-
- The class is used as a generic container type for all types of Symbian
- events.
-
- \note This class is only available on Symbian.
-
- \sa QApplication::symbianEventFilter()
-*/
-
-/*!
- \enum QSymbianEvent::Type
-
- \value InvalidEvent The event is not valid.
- \value WindowServerEvent Indicates an event of type \c TWsEvent.
- \value CommandEvent Indicates that the event is a Symbian command.
- \value ResourceChangeEvent Indicates that the event is a Symbian resource change type.
-*/
-
-/*!
- \fn QSymbianEvent::type() const
-
- Returns the event type contained in the QSymbianEvent instance.
-*/
-
-/*!
- \fn QSymbianEvent::isValid() const
-
- Returns whether this QSymbianEvent instance contains a valid event.
-*/
-
-/*!
- Constructs a QSymbianEvent containing the given window server event
- \a windowServerEvent.
-*/
-QSymbianEvent::QSymbianEvent(const TWsEvent *windowServerEvent)
- : m_type(WindowServerEvent)
- , m_eventPtr(windowServerEvent)
-{
-}
-
-/*!
- Constructs a QSymbianEvent containing the given event value
- \a value. The type of event is controlled by the \a eventType parameter.
-*/
-QSymbianEvent::QSymbianEvent(QSymbianEvent::Type eventType, int value)
-{
- switch (eventType) {
- case CommandEvent:
- case ResourceChangeEvent:
- m_type = eventType;
- m_eventValue = value;
- break;
- default:
- m_type = InvalidEvent;
- m_eventValue = 0;
- break;
- }
-}
-
-/*!
- Destroys the QSymbianEvent.
-*/
-QSymbianEvent::~QSymbianEvent()
-{
-}
-
-/*!
- Returns the window server event contained in the class instance, or 0 if the event type
- is not \c WindowServerEvent.
-*/
-const TWsEvent *QSymbianEvent::windowServerEvent() const
-{
- return (m_type == WindowServerEvent) ? static_cast<const TWsEvent *>(m_eventPtr) : 0;
-}
-
-/*!
- Returns the command contained in the class instance, or 0 if the event type
- is not \c CommandEvent.
-*/
-int QSymbianEvent::command() const
-{
- return (m_type == CommandEvent) ? m_eventValue : 0;
-}
-
-/*!
- Returns the resource change type contained in the class instance, or 0 if the event type
- is not \c ResourceChangeEvent.
-*/
-int QSymbianEvent::resourceChangeType() const
-{
- return (m_type == ResourceChangeEvent) ? m_eventValue : 0;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug dbg, const QSymbianEvent *o)
-{
- if (!o) {
- dbg << "QSymbianEvent(0x0)";
- return dbg;
- }
- dbg.nospace() << "QSymbianEvent(";
- switch (o->type()) {
- case QSymbianEvent::InvalidEvent:
- dbg << "InvalidEvent";
- break;
- case QSymbianEvent::WindowServerEvent:
- dbg << "WindowServerEvent, Type = " << o->windowServerEvent()->Type();
- break;
- case QSymbianEvent::CommandEvent:
- dbg << "CommandEvent, command = " << o->command();
- break;
- case QSymbianEvent::ResourceChangeEvent:
- dbg << "ResourceChangeEvent, resourceChangeType = " << o->resourceChangeType();
- break;
- default:
- dbg << "Unknown event type";
- break;
- }
- dbg << ")";
- return dbg.space();
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/symbian/qsymbianevent.h b/src/gui/symbian/qsymbianevent.h
deleted file mode 100644
index cf05f63176..0000000000
--- a/src/gui/symbian/qsymbianevent.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** 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 QSYMBIANEVENT_H
-#define QSYMBIANEVENT_H
-
-#include <QtCore/qglobal.h>
-
-#ifdef Q_OS_SYMBIAN
-
-class TWsEvent;
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QSymbianEvent
-{
-public:
- enum Type {
- InvalidEvent,
- WindowServerEvent,
- CommandEvent,
- ResourceChangeEvent
- };
-
- QSymbianEvent(const TWsEvent *windowServerEvent);
- QSymbianEvent(Type eventType, int value);
- ~QSymbianEvent();
-
- Type type() const;
- bool isValid() const;
-
- const TWsEvent *windowServerEvent() const;
- int command() const;
- int resourceChangeType() const;
-
-private:
- Type m_type;
- union {
- const void *m_eventPtr;
- int m_eventValue;
-
- qint64 m_reserved;
- };
-};
-
-inline QSymbianEvent::Type QSymbianEvent::type() const
-{
- return m_type;
-}
-
-inline bool QSymbianEvent::isValid() const
-{
- return m_type != InvalidEvent;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-Q_GUI_EXPORT QDebug operator<<(QDebug dbg, const QSymbianEvent *o);
-#endif
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // Q_OS_SYMBIAN
-
-#endif // QSYMBIANEVENT_H
diff --git a/src/gui/symbian/symbianresources.qrc b/src/gui/symbian/symbianresources.qrc
deleted file mode 100644
index 0a4fc36c9a..0000000000
--- a/src/gui/symbian/symbianresources.qrc
+++ /dev/null
@@ -1,37 +0,0 @@
-<RCC>
- <qresource prefix="/trolltech/symbian/cursors" >
- <file>images/blank.png</file>
- <file>images/busy3.png</file>
- <file>images/busy6.png</file>
- <file>images/busy9.png</file>
- <file>images/busy12.png</file>
- <file>images/closehand.png</file>
- <file>images/cross.png</file>
- <file>images/forbidden.png</file>
- <file>images/handpoint.png</file>
- <file>images/ibeam.png</file>
- <file>images/openhand.png</file>
- <file>images/pointer.png</file>
- <file>images/sizeall.png</file>
- <file>images/sizebdiag.png</file>
- <file>images/sizefdiag.png</file>
- <file>images/sizehor.png</file>
- <file>images/sizever.png</file>
- <file>images/splith.png</file>
- <file>images/splitv.png</file>
- <file>images/uparrow.png</file>
- <file>images/wait1.png</file>
- <file>images/wait2.png</file>
- <file>images/wait3.png</file>
- <file>images/wait4.png</file>
- <file>images/wait5.png</file>
- <file>images/wait6.png</file>
- <file>images/wait7.png</file>
- <file>images/wait8.png</file>
- <file>images/wait9.png</file>
- <file>images/wait10.png</file>
- <file>images/wait11.png</file>
- <file>images/wait12.png</file>
- <file>images/whatsthis.png</file>
- </qresource>
-</RCC>
diff --git a/src/gui/to_be_moved/qdnd.cpp b/src/gui/to_be_moved/qdnd.cpp
deleted file mode 100644
index db79b9042d..0000000000
--- a/src/gui/to_be_moved/qdnd.cpp
+++ /dev/null
@@ -1,491 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbitmap.h"
-#include "qdrag.h"
-#include "qpixmap.h"
-#include "qevent.h"
-#include "qfile.h"
-#include "qtextcodec.h"
-#include "qguiapplication.h"
-#include "qpoint.h"
-#include "qwidget.h"
-#include "qbuffer.h"
-#include "qimage.h"
-#include "qregexp.h"
-#include "qdir.h"
-#include "qdnd_p.h"
-#include "qimagereader.h"
-#include "qimagewriter.h"
-#include "qdebug.h"
-#include <ctype.h>
-
-#include <private/qguiapplication_p.h>
-
-#ifndef QT_NO_DRAGANDDROP
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_DRAGANDDROP
-
-//#define QDND_DEBUG
-
-#ifdef QDND_DEBUG
-QString dragActionsToString(Qt::DropActions actions)
-{
- QString str;
- if (actions == Qt::IgnoreAction) {
- if (!str.isEmpty())
- str += " | ";
- str += "IgnoreAction";
- }
- if (actions & Qt::LinkAction) {
- if (!str.isEmpty())
- str += " | ";
- str += "LinkAction";
- }
- if (actions & Qt::CopyAction) {
- if (!str.isEmpty())
- str += " | ";
- str += "CopyAction";
- }
- if (actions & Qt::MoveAction) {
- if (!str.isEmpty())
- str += " | ";
- str += "MoveAction";
- }
- if ((actions & Qt::TargetMoveAction) == Qt::TargetMoveAction ) {
- if (!str.isEmpty())
- str += " | ";
- str += "TargetMoveAction";
- }
- return str;
-}
-
-QString KeyboardModifiersToString(Qt::KeyboardModifiers moderfies)
-{
- QString str;
- if (moderfies & Qt::ControlModifier) {
- if (!str.isEmpty())
- str += " | ";
- str += Qt::ControlModifier;
- }
- if (moderfies & Qt::AltModifier) {
- if (!str.isEmpty())
- str += " | ";
- str += Qt::AltModifier;
- }
- if (moderfies & Qt::ShiftModifier) {
- if (!str.isEmpty())
- str += " | ";
- str += Qt::ShiftModifier;
- }
- return str;
-}
-#endif
-
-
-// the universe's only drag manager
-QDragManager *QDragManager::instance = 0;
-
-
-QDragManager::QDragManager()
- : QObject(qApp)
-{
- Q_ASSERT(!instance);
-
-#ifdef Q_WS_QWS
- currentActionForOverrideCursor = Qt::IgnoreAction;
-#endif
- object = 0;
- beingCancelled = false;
- restoreCursor = false;
- willDrop = false;
- eventLoop = 0;
- dropData = new QDropData();
- currentDropTarget = 0;
-#ifdef Q_WS_X11
- xdndMimeTransferedPixmapIndex = 0;
-#endif
-}
-
-
-QDragManager::~QDragManager()
-{
-#ifndef QT_NO_CURSOR
- if (restoreCursor)
- QGuiApplication::restoreOverrideCursor();
-#endif
- instance = 0;
- delete dropData;
-}
-
-QDragManager *QDragManager::self()
-{
- if (!instance && !QApplication::closingDown())
- instance = new QDragManager;
- return instance;
-}
-
-QPixmap QDragManager::dragCursor(Qt::DropAction action) const
-{
- QDragPrivate * d = dragPrivate();
- if (d && d->customCursors.contains(action))
- return d->customCursors[action];
- else if (action == Qt::MoveAction)
- return QGuiApplicationPrivate::instance()->getPixmapCursor(Qt::DragMoveCursor);
- else if (action == Qt::CopyAction)
- return QGuiApplicationPrivate::instance()->getPixmapCursor(Qt::DragCopyCursor);
- else if (action == Qt::LinkAction)
- return QGuiApplicationPrivate::instance()->getPixmapCursor(Qt::DragLinkCursor);
-#ifdef Q_WS_WIN
- else if (action == Qt::IgnoreAction)
- return QGuiApplicationPrivate::instance()->getPixmapCursor(Qt::ForbiddenCursor);
-#endif
- return QPixmap();
-}
-
-bool QDragManager::hasCustomDragCursors() const
-{
- QDragPrivate * d = dragPrivate();
- return d && !d->customCursors.isEmpty();
-}
-
-Qt::DropAction QDragManager::defaultAction(Qt::DropActions possibleActions,
- Qt::KeyboardModifiers modifiers) const
-{
-#ifdef QDND_DEBUG
- qDebug("QDragManager::defaultAction(Qt::DropActions possibleActions)");
- qDebug("keyboard modifiers : %s", KeyboardModifiersToString(modifiers).latin1());
-#endif
-
- QDragPrivate *d = dragPrivate();
- Qt::DropAction defaultAction = d ? d->defaultDropAction : Qt::IgnoreAction;
-
- if (defaultAction == Qt::IgnoreAction) {
- //This means that the drag was initiated by QDrag::start and we need to
- //preserve the old behavior
-#ifdef Q_WS_MAC
- defaultAction = Qt::MoveAction;
-#else
- defaultAction = Qt::CopyAction;
-#endif
- }
-
-#ifdef Q_WS_MAC
- if (modifiers & Qt::ControlModifier && modifiers & Qt::AltModifier)
- defaultAction = Qt::LinkAction;
- else if (modifiers & Qt::AltModifier)
- defaultAction = Qt::CopyAction;
- else if (modifiers & Qt::ControlModifier)
- defaultAction = Qt::MoveAction;
-#else
- if (modifiers & Qt::ControlModifier && modifiers & Qt::ShiftModifier)
- defaultAction = Qt::LinkAction;
- else if (modifiers & Qt::ControlModifier)
- defaultAction = Qt::CopyAction;
- else if (modifiers & Qt::ShiftModifier)
- defaultAction = Qt::MoveAction;
- else if (modifiers & Qt::AltModifier)
- defaultAction = Qt::LinkAction;
-#endif
-
- // if the object is set take the list of possibles from it
- if (object)
- possibleActions = object->d_func()->possible_actions;
-
-#ifdef QDND_DEBUG
- qDebug("possible actions : %s", dragActionsToString(possibleActions).latin1());
-#endif
-
- // Check if the action determined is allowed
- if (!(possibleActions & defaultAction)) {
- if (possibleActions & Qt::CopyAction)
- defaultAction = Qt::CopyAction;
- else if (possibleActions & Qt::MoveAction)
- defaultAction = Qt::MoveAction;
- else if (possibleActions & Qt::LinkAction)
- defaultAction = Qt::LinkAction;
- else
- defaultAction = Qt::IgnoreAction;
- }
-
-#ifdef QDND_DEBUG
- qDebug("default action : %s", dragActionsToString(defaultAction).latin1());
-#endif
-
- return defaultAction;
-}
-
-void QDragManager::setCurrentTarget(QWidget *target, bool dropped)
-{
- if (currentDropTarget == target)
- return;
-
- currentDropTarget = target;
- if (!dropped && object) {
- object->d_func()->target = target;
- emit object->targetChanged(target);
- }
-
-}
-
-QWidget *QDragManager::currentTarget()
-{
- return currentDropTarget;
-}
-
-#endif
-
-QDropData::QDropData()
- : QInternalMimeData()
-{
-}
-
-QDropData::~QDropData()
-{
-}
-#endif // QT_NO_DRAGANDDROP
-
-#if !(defined(QT_NO_DRAGANDDROP) && defined(QT_NO_CLIPBOARD))
-
-static QStringList imageReadMimeFormats()
-{
- QStringList formats;
- QList<QByteArray> imageFormats = QImageReader::supportedImageFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- QString format = QLatin1String("image/");
- format += QString::fromLatin1(imageFormats.at(i).toLower());
- formats.append(format);
- }
-
- //put png at the front because it is best
- int pngIndex = formats.indexOf(QLatin1String("image/png"));
- if (pngIndex != -1 && pngIndex != 0)
- formats.move(pngIndex, 0);
-
- return formats;
-}
-
-
-static QStringList imageWriteMimeFormats()
-{
- QStringList formats;
- QList<QByteArray> imageFormats = QImageWriter::supportedImageFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- QString format = QLatin1String("image/");
- format += QString::fromLatin1(imageFormats.at(i).toLower());
- formats.append(format);
- }
-
- //put png at the front because it is best
- int pngIndex = formats.indexOf(QLatin1String("image/png"));
- if (pngIndex != -1 && pngIndex != 0)
- formats.move(pngIndex, 0);
-
- return formats;
-}
-
-QInternalMimeData::QInternalMimeData()
- : QMimeData()
-{
-}
-
-QInternalMimeData::~QInternalMimeData()
-{
-}
-
-bool QInternalMimeData::hasFormat(const QString &mimeType) const
-{
- bool foundFormat = hasFormat_sys(mimeType);
- if (!foundFormat && mimeType == QLatin1String("application/x-qt-image")) {
- QStringList imageFormats = imageReadMimeFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- if ((foundFormat = hasFormat_sys(imageFormats.at(i))))
- break;
- }
- }
- return foundFormat;
-}
-
-QStringList QInternalMimeData::formats() const
-{
- QStringList realFormats = formats_sys();
- if (!realFormats.contains(QLatin1String("application/x-qt-image"))) {
- QStringList imageFormats = imageReadMimeFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- if (realFormats.contains(imageFormats.at(i))) {
- realFormats += QLatin1String("application/x-qt-image");
- break;
- }
- }
- }
- return realFormats;
-}
-
-QVariant QInternalMimeData::retrieveData(const QString &mimeType, QVariant::Type type) const
-{
- QVariant data = retrieveData_sys(mimeType, type);
- if (mimeType == QLatin1String("application/x-qt-image")) {
- if (data.isNull() || (data.type() == QVariant::ByteArray && data.toByteArray().isEmpty())) {
- // try to find an image
- QStringList imageFormats = imageReadMimeFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- data = retrieveData_sys(imageFormats.at(i), type);
- if (data.isNull() || (data.type() == QVariant::ByteArray && data.toByteArray().isEmpty()))
- continue;
- break;
- }
- }
- // we wanted some image type, but all we got was a byte array. Convert it to an image.
- if (data.type() == QVariant::ByteArray
- && (type == QVariant::Image || type == QVariant::Pixmap || type == QVariant::Bitmap))
- data = QImage::fromData(data.toByteArray());
-
- } else if (mimeType == QLatin1String("application/x-color") && data.type() == QVariant::ByteArray) {
- QColor c;
- QByteArray ba = data.toByteArray();
- if (ba.size() == 8) {
- ushort * colBuf = (ushort *)ba.data();
- c.setRgbF(qreal(colBuf[0]) / qreal(0xFFFF),
- qreal(colBuf[1]) / qreal(0xFFFF),
- qreal(colBuf[2]) / qreal(0xFFFF),
- qreal(colBuf[3]) / qreal(0xFFFF));
- data = c;
- } else {
- qWarning("Qt: Invalid color format");
- }
- } else if (data.type() != type && data.type() == QVariant::ByteArray) {
- // try to use mime data's internal conversion stuf.
- QInternalMimeData *that = const_cast<QInternalMimeData *>(this);
- that->setData(mimeType, data.toByteArray());
- data = QMimeData::retrieveData(mimeType, type);
- that->clear();
- }
- return data;
-}
-
-bool QInternalMimeData::canReadData(const QString &mimeType)
-{
- return imageReadMimeFormats().contains(mimeType);
-}
-
-// helper functions for rendering mimedata to the system, this is needed because QMimeData is in core.
-QStringList QInternalMimeData::formatsHelper(const QMimeData *data)
-{
- QStringList realFormats = data->formats();
- if (realFormats.contains(QLatin1String("application/x-qt-image"))) {
- // add all supported image formats
- QStringList imageFormats = imageWriteMimeFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- if (!realFormats.contains(imageFormats.at(i)))
- realFormats.append(imageFormats.at(i));
- }
- }
- return realFormats;
-}
-
-bool QInternalMimeData::hasFormatHelper(const QString &mimeType, const QMimeData *data)
-{
-
- bool foundFormat = data->hasFormat(mimeType);
- if (!foundFormat) {
- if (mimeType == QLatin1String("application/x-qt-image")) {
- // check all supported image formats
- QStringList imageFormats = imageWriteMimeFormats();
- for (int i = 0; i < imageFormats.size(); ++i) {
- if ((foundFormat = data->hasFormat(imageFormats.at(i))))
- break;
- }
- } else if (mimeType.startsWith(QLatin1String("image/"))) {
- return data->hasImage() && imageWriteMimeFormats().contains(mimeType);
- }
- }
- return foundFormat;
-}
-
-QByteArray QInternalMimeData::renderDataHelper(const QString &mimeType, const QMimeData *data)
-{
- QByteArray ba;
- if (mimeType == QLatin1String("application/x-color")) {
- /* QMimeData can only provide colors as QColor or the name
- of a color as a QByteArray or a QString. So we need to do
- the conversion to application/x-color here.
- The application/x-color format is :
- type: application/x-color
- format: 16
- data[0]: red
- data[1]: green
- data[2]: blue
- data[3]: opacity
- */
- ba.resize(8);
- ushort * colBuf = (ushort *)ba.data();
- QColor c = qvariant_cast<QColor>(data->colorData());
- colBuf[0] = ushort(c.redF() * 0xFFFF);
- colBuf[1] = ushort(c.greenF() * 0xFFFF);
- colBuf[2] = ushort(c.blueF() * 0xFFFF);
- colBuf[3] = ushort(c.alphaF() * 0xFFFF);
- } else {
- ba = data->data(mimeType);
- if (ba.isEmpty()) {
- if (mimeType == QLatin1String("application/x-qt-image") && data->hasImage()) {
- QImage image = qvariant_cast<QImage>(data->imageData());
- QBuffer buf(&ba);
- buf.open(QBuffer::WriteOnly);
- // would there not be PNG ??
- image.save(&buf, "PNG");
- } else if (mimeType.startsWith(QLatin1String("image/")) && data->hasImage()) {
- QImage image = qvariant_cast<QImage>(data->imageData());
- QBuffer buf(&ba);
- buf.open(QBuffer::WriteOnly);
- image.save(&buf, mimeType.mid(mimeType.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper());
- }
- }
- }
- return ba;
-}
-
-#endif // QT_NO_DRAGANDDROP && QT_NO_CLIPBOARD
-
-QT_END_NAMESPACE
diff --git a/src/gui/to_be_moved/qdnd_p.h b/src/gui/to_be_moved/qdnd_p.h
deleted file mode 100644
index 754366637c..0000000000
--- a/src/gui/to_be_moved/qdnd_p.h
+++ /dev/null
@@ -1,336 +0,0 @@
-/****************************************************************************
-**
-** 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 QDND_P_H
-#define QDND_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 "QtCore/qobject.h"
-#include "QtCore/qmap.h"
-#include "QtGui/qmime.h"
-#include "QtGui/qdrag.h"
-#include "QtGui/qpixmap.h"
-#include "QtGui/qcursor.h"
-#include "QtCore/qpoint.h"
-#include "private/qobject_p.h"
-#ifdef Q_WS_MAC
-# include "private/qt_mac_p.h"
-#endif
-
-#if defined(Q_WS_WIN)
-# include <qt_windows.h>
-# include <objidl.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QEventLoop;
-
-#if !(defined(QT_NO_DRAGANDDROP) && defined(QT_NO_CLIPBOARD))
-
-class Q_GUI_EXPORT QInternalMimeData : public QMimeData
-{
- Q_OBJECT
-public:
- QInternalMimeData();
- ~QInternalMimeData();
-
- bool hasFormat(const QString &mimeType) const;
- QStringList formats() const;
- static bool canReadData(const QString &mimeType);
-
-
- static QStringList formatsHelper(const QMimeData *data);
- static bool hasFormatHelper(const QString &mimeType, const QMimeData *data);
- static QByteArray renderDataHelper(const QString &mimeType, const QMimeData *data);
-
-protected:
- QVariant retrieveData(const QString &mimeType, QVariant::Type type) const;
-
- virtual bool hasFormat_sys(const QString &mimeType) const = 0;
- virtual QStringList formats_sys() const = 0;
- virtual QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const = 0;
-};
-
-#ifdef Q_WS_WIN
-class QOleDataObject : public IDataObject
-{
-public:
- explicit QOleDataObject(QMimeData *mimeData);
- virtual ~QOleDataObject();
-
- void releaseQt();
- const QMimeData *mimeData() const;
- DWORD reportedPerformedEffect() const;
-
- // IUnknown methods
- STDMETHOD(QueryInterface)(REFIID riid, void FAR* FAR* ppvObj);
- STDMETHOD_(ULONG,AddRef)(void);
- STDMETHOD_(ULONG,Release)(void);
-
- // IDataObject methods
- STDMETHOD(GetData)(LPFORMATETC pformatetcIn, LPSTGMEDIUM pmedium);
- STDMETHOD(GetDataHere)(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium);
- STDMETHOD(QueryGetData)(LPFORMATETC pformatetc);
- STDMETHOD(GetCanonicalFormatEtc)(LPFORMATETC pformatetc, LPFORMATETC pformatetcOut);
- STDMETHOD(SetData)(LPFORMATETC pformatetc, STGMEDIUM FAR * pmedium,
- BOOL fRelease);
- STDMETHOD(EnumFormatEtc)(DWORD dwDirection, LPENUMFORMATETC FAR* ppenumFormatEtc);
- STDMETHOD(DAdvise)(FORMATETC FAR* pFormatetc, DWORD advf,
- LPADVISESINK pAdvSink, DWORD FAR* pdwConnection);
- STDMETHOD(DUnadvise)(DWORD dwConnection);
- STDMETHOD(EnumDAdvise)(LPENUMSTATDATA FAR* ppenumAdvise);
-
-private:
- ULONG m_refs;
- QPointer<QMimeData> data;
- int CF_PERFORMEDDROPEFFECT;
- DWORD performedEffect;
-};
-
-class QOleEnumFmtEtc : public IEnumFORMATETC
-{
-public:
- explicit QOleEnumFmtEtc(const QVector<FORMATETC> &fmtetcs);
- explicit QOleEnumFmtEtc(const QVector<LPFORMATETC> &lpfmtetcs);
- virtual ~QOleEnumFmtEtc();
-
- bool isNull() const;
-
- // IUnknown methods
- STDMETHOD(QueryInterface)(REFIID riid, void FAR* FAR* ppvObj);
- STDMETHOD_(ULONG,AddRef)(void);
- STDMETHOD_(ULONG,Release)(void);
-
- // IEnumFORMATETC methods
- STDMETHOD(Next)(ULONG celt, LPFORMATETC rgelt, ULONG FAR* pceltFetched);
- STDMETHOD(Skip)(ULONG celt);
- STDMETHOD(Reset)(void);
- STDMETHOD(Clone)(LPENUMFORMATETC FAR* newEnum);
-
-private:
- bool copyFormatEtc(LPFORMATETC dest, LPFORMATETC src) const;
-
- ULONG m_dwRefs;
- ULONG m_nIndex;
- QVector<LPFORMATETC> m_lpfmtetcs;
- bool m_isNull;
-};
-
-#endif
-
-#endif //QT_NO_DRAGANDDROP && QT_NO_CLIPBOARD
-
-#ifndef QT_NO_DRAGANDDROP
-
-class QDragPrivate : public QObjectPrivate
-{
-public:
- QWidget *source;
- QWidget *target;
- QMimeData *data;
- QPixmap pixmap;
- QPoint hotspot;
- Qt::DropActions possible_actions;
- Qt::DropAction executed_action;
- QMap<Qt::DropAction, QPixmap> customCursors;
- Qt::DropAction defaultDropAction;
-};
-
-class QDropData : public QInternalMimeData
-{
- Q_OBJECT
-public:
- QDropData();
- ~QDropData();
-
-protected:
- bool hasFormat_sys(const QString &mimeType) const;
- QStringList formats_sys() const;
- QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const;
-
-#if defined(Q_WS_WIN)
-public:
- LPDATAOBJECT currentDataObject;
-#endif
-};
-
-class QDragManager: public QObject {
- Q_OBJECT
-
- QDragManager();
- ~QDragManager();
- // only friend classes can use QDragManager.
- friend class QDrag;
- friend class QDragMoveEvent;
- friend class QDropEvent;
- friend class QApplication;
-#ifdef Q_WS_MAC
- friend class QWidgetPrivate; //dnd is implemented here
-#endif
-
- bool eventFilter(QObject *, QEvent *);
- void timerEvent(QTimerEvent*);
-
-public:
- Qt::DropAction drag(QDrag *);
-
- void cancel(bool deleteSource = true);
- void move(const QPoint &);
- void drop();
- void updatePixmap();
- QWidget *source() const { return object ? object->d_func()->source : 0; }
- QDragPrivate *dragPrivate() const { return object ? object->d_func() : 0; }
- static QDragPrivate *dragPrivate(QDrag *drag) { return drag ? drag->d_func() : 0; }
-
- static QDragManager *self();
- Qt::DropAction defaultAction(Qt::DropActions possibleActions,
- Qt::KeyboardModifiers modifiers) const;
-
- QDrag *object;
-
- void updateCursor();
-
- bool beingCancelled;
- bool restoreCursor;
- bool willDrop;
- QEventLoop *eventLoop;
-
- QPixmap dragCursor(Qt::DropAction action) const;
-
- bool hasCustomDragCursors() const;
-
- QDropData *dropData;
-
- void emitActionChanged(Qt::DropAction newAction) { if (object) emit object->actionChanged(newAction); }
-
- void setCurrentTarget(QWidget *target, bool dropped = false);
- QWidget *currentTarget();
-
-#ifdef Q_WS_X11
- QPixmap xdndMimeTransferedPixmap[2];
- int xdndMimeTransferedPixmapIndex;
-#endif
-
-private:
-#if defined(Q_WS_QWS) || defined(Q_WS_QPA)
- Qt::DropAction currentActionForOverrideCursor;
-#endif
-#ifdef Q_OS_SYMBIAN
-#ifndef QT_NO_CURSOR
- QCursor overrideCursor;
-#endif
-#endif
- QWidget *currentDropTarget;
-
- static QDragManager *instance;
- Q_DISABLE_COPY(QDragManager)
-};
-
-
-#if defined(Q_WS_WIN)
-
-class QOleDropTarget : public IDropTarget
-{
-public:
- QOleDropTarget(QWidget* w);
- virtual ~QOleDropTarget() {}
-
- void releaseQt();
-
- // IUnknown methods
- STDMETHOD(QueryInterface)(REFIID riid, void FAR* FAR* ppvObj);
- STDMETHOD_(ULONG, AddRef)(void);
- STDMETHOD_(ULONG, Release)(void);
-
- // IDropTarget methods
- STDMETHOD(DragEnter)(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect);
- STDMETHOD(DragOver)(DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect);
- STDMETHOD(DragLeave)();
- STDMETHOD(Drop)(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect);
-
-private:
- ULONG m_refs;
- QWidget* widget;
- QPointer<QWidget> currentWidget;
- QRect answerRect;
- QPoint lastPoint;
- DWORD chosenEffect;
- DWORD lastKeyState;
-
- void sendDragEnterEvent(QWidget *to, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect);
-};
-
-#endif
-
-#if defined (Q_WS_MAC)
-class QCocoaDropData : public QInternalMimeData
-{
- Q_OBJECT
-public:
- QCocoaDropData(CFStringRef pasteboard);
- ~QCocoaDropData();
-
-protected:
- bool hasFormat_sys(const QString &mimeType) const;
- QStringList formats_sys() const;
- QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const;
-public:
- CFStringRef dropPasteboard;
-};
-#endif
-
-#endif // !QT_NO_DRAGANDDROP
-
-
-QT_END_NAMESPACE
-
-#endif // QDND_P_H
diff --git a/src/gui/to_be_moved/qdnd_qpa.cpp b/src/gui/to_be_moved/qdnd_qpa.cpp
deleted file mode 100644
index 82e8d580ae..0000000000
--- a/src/gui/to_be_moved/qdnd_qpa.cpp
+++ /dev/null
@@ -1,426 +0,0 @@
-/****************************************************************************
-**
-** 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 "qguiapplication.h"
-
-#ifndef QT_NO_DRAGANDDROP
-
-#include "qwidget.h"
-#include "qdatetime.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qdnd_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-static QPixmap *defaultPm = 0;
-static const int default_pm_hotx = -2;
-static const int default_pm_hoty = -16;
-static const char *const default_pm[] = {
-"13 9 3 1",
-". c None",
-" c #000000",
-"X c #FFFFFF",
-"X X X X X X X",
-" X X X X X X ",
-"X ......... X",
-" X.........X ",
-"X ......... X",
-" X.........X ",
-"X ......... X",
-" X X X X X X ",
-"X X X X X X X",
-};
-
-// Shift/Ctrl handling, and final drop status
-static Qt::DropAction global_accepted_action = Qt::CopyAction;
-static Qt::DropActions possible_actions = Qt::IgnoreAction;
-
-
-// static variables in place of a proper cross-process solution
-static QDrag *drag_object;
-static bool qt_qws_dnd_dragging = false;
-
-
-static Qt::KeyboardModifiers oldstate;
-
-class QShapedPixmapWidget : public QWidget {
- QPixmap pixmap;
-public:
- QShapedPixmapWidget() :
- QWidget(0, Qt::Tool | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint)
- {
- // ### Temporary workaround for 4.2-rc1!!! To prevent flickering when
- // using drag'n drop in a client application. (task 126956)
- // setAttribute() should be done unconditionally!
- // if (QApplication::type() == QApplication::GuiServer)
- setAttribute(Qt::WA_TransparentForMouseEvents);
- }
-
- void setPixmap(QPixmap pm)
- {
- pixmap = pm;
- if (!pixmap.mask().isNull()) {
- setMask(pixmap.mask());
- } else {
- clearMask();
- }
- resize(pm.width(),pm.height());
- }
-
- void paintEvent(QPaintEvent*)
- {
- QPainter p(this);
- p.drawPixmap(0,0,pixmap);
- }
-};
-
-
-static QShapedPixmapWidget *qt_qws_dnd_deco = 0;
-
-
-void QDragManager::updatePixmap()
-{
- if (qt_qws_dnd_deco) {
- QPixmap pm;
- QPoint pm_hot(default_pm_hotx,default_pm_hoty);
- if (drag_object) {
- pm = drag_object->pixmap();
- if (!pm.isNull())
- pm_hot = drag_object->hotSpot();
- }
- if (pm.isNull()) {
- if (!defaultPm)
- defaultPm = new QPixmap(default_pm);
- pm = *defaultPm;
- }
- qt_qws_dnd_deco->setPixmap(pm);
- qt_qws_dnd_deco->move(QCursor::pos()-pm_hot);
- if (willDrop) {
- qt_qws_dnd_deco->show();
- } else {
- qt_qws_dnd_deco->hide();
- }
- }
-}
-
-void QDragManager::timerEvent(QTimerEvent *) { }
-
-void QDragManager::move(const QPoint &) { }
-
-void QDragManager::updateCursor()
-{
-#ifndef QT_NO_CURSOR
- if (willDrop) {
- if (qt_qws_dnd_deco)
- qt_qws_dnd_deco->show();
- if (currentActionForOverrideCursor != global_accepted_action) {
- QGuiApplication::changeOverrideCursor(QCursor(dragCursor(global_accepted_action), 0, 0));
- currentActionForOverrideCursor = global_accepted_action;
- }
- } else {
- QCursor *overrideCursor = QGuiApplication::overrideCursor();
- if (!overrideCursor || overrideCursor->shape() != Qt::ForbiddenCursor) {
- QGuiApplication::changeOverrideCursor(QCursor(Qt::ForbiddenCursor));
- currentActionForOverrideCursor = Qt::IgnoreAction;
- }
- if (qt_qws_dnd_deco)
- qt_qws_dnd_deco->hide();
- }
-#endif
-}
-
-
-bool QDragManager::eventFilter(QObject *o, QEvent *e)
-{
- if (beingCancelled) {
- if (e->type() == QEvent::KeyRelease && static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
- qApp->removeEventFilter(this);
- Q_ASSERT(object == 0);
- beingCancelled = false;
- eventLoop->exit();
- return true; // block the key release
- }
- return false;
- }
-
-
-
- if (!o->isWidgetType())
- return false;
-
- switch(e->type()) {
- case QEvent::ShortcutOverride:
- // prevent accelerators from firing while dragging
- e->accept();
- return true;
-
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- {
- QKeyEvent *ke = ((QKeyEvent*)e);
- if (ke->key() == Qt::Key_Escape && e->type() == QEvent::KeyPress) {
- cancel();
- qApp->removeEventFilter(this);
- beingCancelled = false;
- eventLoop->exit();
- } else {
- updateCursor();
- }
- return true; // Eat all key events
- }
-
- case QEvent::MouseButtonPress:
- case QEvent::MouseMove:
- {
- if (!object) { //#### this should not happen
- qWarning("QDragManager::eventFilter: No object");
- return true;
- }
-
- QDragManager *manager = QDragManager::self();
- QMimeData *dropData = manager->object ? manager->dragPrivate()->data : manager->dropData;
- if (manager->object)
- possible_actions = manager->dragPrivate()->possible_actions;
- else
- possible_actions = Qt::IgnoreAction;
-
- QMouseEvent *me = (QMouseEvent *)e;
- if (me->buttons()) {
- Qt::DropAction prevAction = global_accepted_action;
- QWidget *cw = QApplication::widgetAt(me->globalPos());
-
- // Fix for when we move mouse on to the deco widget
- if (qt_qws_dnd_deco && cw == qt_qws_dnd_deco)
- cw = object->target();
-
- while (cw && !cw->acceptDrops() && !cw->isWindow())
- cw = cw->parentWidget();
-
- if (object->target() != cw) {
- if (object->target()) {
- QDragLeaveEvent dle;
- QCoreApplication::sendEvent(object->target(), &dle);
- willDrop = false;
- global_accepted_action = Qt::IgnoreAction;
- updateCursor();
- restoreCursor = true;
- object->d_func()->target = 0;
- }
- if (cw && cw->acceptDrops()) {
- object->d_func()->target = cw;
- QDragEnterEvent dee(cw->mapFromGlobal(me->globalPos()), possible_actions, dropData,
- me->buttons(), me->modifiers());
- QCoreApplication::sendEvent(object->target(), &dee);
- willDrop = dee.isAccepted() && dee.dropAction() != Qt::IgnoreAction;
- global_accepted_action = willDrop ? dee.dropAction() : Qt::IgnoreAction;
- updateCursor();
- restoreCursor = true;
- }
- } else if (cw) {
- QDragMoveEvent dme(cw->mapFromGlobal(me->globalPos()), possible_actions, dropData,
- me->buttons(), me->modifiers());
- if (global_accepted_action != Qt::IgnoreAction) {
- dme.setDropAction(global_accepted_action);
- dme.accept();
- }
- QCoreApplication::sendEvent(cw, &dme);
- willDrop = dme.isAccepted();
- global_accepted_action = willDrop ? dme.dropAction() : Qt::IgnoreAction;
- updatePixmap();
- updateCursor();
- }
- if (global_accepted_action != prevAction)
- emitActionChanged(global_accepted_action);
- }
- return true; // Eat all mouse events
- }
-
- case QEvent::MouseButtonRelease:
- {
- qApp->removeEventFilter(this);
- if (restoreCursor) {
- willDrop = false;
-#ifndef QT_NO_CURSOR
- QGuiApplication::restoreOverrideCursor();
-#endif
- restoreCursor = false;
- }
- if (object && object->target()) {
- QMouseEvent *me = (QMouseEvent *)e;
-
- QDragManager *manager = QDragManager::self();
- QMimeData *dropData = manager->object ? manager->dragPrivate()->data : manager->dropData;
-
- QDropEvent de(object->target()->mapFromGlobal(me->globalPos()), possible_actions, dropData,
- me->buttons(), me->modifiers());
- QCoreApplication::sendEvent(object->target(), &de);
- if (de.isAccepted())
- global_accepted_action = de.dropAction();
- else
- global_accepted_action = Qt::IgnoreAction;
-
- if (object)
- object->deleteLater();
- drag_object = object = 0;
- }
- eventLoop->exit();
- return true; // Eat all mouse events
- }
-
- default:
- break;
- }
-
- return false;
-}
-
-Qt::DropAction QDragManager::drag(QDrag *o)
-{
- if (object == o || !o || !o->source())
- return Qt::IgnoreAction;
-
- if (object) {
- cancel();
- qApp->removeEventFilter(this);
- beingCancelled = false;
- }
-
- object = drag_object = o;
- qt_qws_dnd_deco = new QShapedPixmapWidget();
- oldstate = Qt::NoModifier; // #### Should use state that caused the drag
-// drag_mode = mode;
-
- willDrop = false;
- updatePixmap();
- updateCursor();
- restoreCursor = true;
- object->d_func()->target = 0;
- qApp->installEventFilter(this);
-
- global_accepted_action = Qt::CopyAction;
-#ifndef QT_NO_CURSOR
- qApp->setOverrideCursor(Qt::ArrowCursor);
- restoreCursor = true;
- updateCursor();
-#endif
-
- qt_qws_dnd_dragging = true;
-
- eventLoop = new QEventLoop;
- (void) eventLoop->exec();
- delete eventLoop;
- eventLoop = 0;
-
- delete qt_qws_dnd_deco;
- qt_qws_dnd_deco = 0;
- qt_qws_dnd_dragging = false;
-
-
- return global_accepted_action;
-}
-
-
-void QDragManager::cancel(bool deleteSource)
-{
-// qDebug("QDragManager::cancel");
- beingCancelled = true;
-
- if (object->target()) {
- QDragLeaveEvent dle;
- QCoreApplication::sendEvent(object->target(), &dle);
- }
-
-#ifndef QT_NO_CURSOR
- if (restoreCursor) {
- QGuiApplication::restoreOverrideCursor();
- restoreCursor = false;
- }
-#endif
-
- if (drag_object) {
- if (deleteSource)
- object->deleteLater();
- drag_object = object = 0;
- }
-
- delete qt_qws_dnd_deco;
- qt_qws_dnd_deco = 0;
-
- global_accepted_action = Qt::IgnoreAction;
-}
-
-
-void QDragManager::drop()
-{
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mimetype, QVariant::Type type) const
-{
- if (!drag_object)
- return QVariant();
- QByteArray data = drag_object->mimeData()->data(mimetype);
- if (type == QVariant::String)
- return QString::fromUtf8(data);
- return data;
-}
-
-bool QDropData::hasFormat_sys(const QString &format) const
-{
- return formats().contains(format);
-}
-
-QStringList QDropData::formats_sys() const
-{
- if (drag_object)
- return drag_object->mimeData()->formats();
- return QStringList();
-}
-
-
-#endif // QT_NO_DRAGANDDROP
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/to_be_moved/qdrag.cpp b/src/gui/to_be_moved/qdrag.cpp
deleted file mode 100644
index d8d14cb45c..0000000000
--- a/src/gui/to_be_moved/qdrag.cpp
+++ /dev/null
@@ -1,359 +0,0 @@
-/****************************************************************************
-**
-** 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 <qwidget.h>
-#include <qdrag.h>
-#include <qpixmap.h>
-#include <qpoint.h>
-#include "qdnd_p.h"
-
-#ifndef QT_NO_DRAGANDDROP
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QDrag
- \brief The QDrag class provides support for MIME-based drag and drop data
- transfer.
-
- Drag and drop is an intuitive way for users to copy or move data around in an
- application, and is used in many desktop environments as a mechanism for copying
- data between applications. Drag and drop support in Qt is centered around the
- QDrag class that handles most of the details of a drag and drop operation.
-
- The data to be transferred by the drag and drop operation is contained in a
- QMimeData object. This is specified with the setMimeData() function in the
- following way:
-
- \snippet doc/src/snippets/dragging/mainwindow.cpp 1
-
- Note that setMimeData() assigns ownership of the QMimeData object to the
- QDrag object. The QDrag must be constructed on the heap with a parent QWidget
- to ensure that Qt can clean up after the drag and drop operation has been
- completed.
-
- A pixmap can be used to represent the data while the drag is in
- progress, and will move with the cursor to the drop target. This
- pixmap typically shows an icon that represents the MIME type of
- the data being transferred, but any pixmap can be set with
- setPixmap(). The cursor's hot spot can be given a position
- relative to the top-left corner of the pixmap with the
- setHotSpot() function. The following code positions the pixmap so
- that the cursor's hot spot points to the center of its bottom
- edge:
-
- \snippet doc/src/snippets/separations/finalwidget.cpp 2
-
- \note On X11, the pixmap may not be able to keep up with the mouse
- movements if the hot spot causes the pixmap to be displayed
- directly under the cursor.
-
- The source and target widgets can be found with source() and target().
- These functions are often used to determine whether drag and drop operations
- started and finished at the same widget, so that special behavior can be
- implemented.
-
- QDrag only deals with the drag and drop operation itself. It is up to the
- developer to decide when a drag operation begins, and how a QDrag object should
- be constructed and used. For a given widget, it is often necessary to
- reimplement \l{QWidget::mousePressEvent()}{mousePressEvent()} to determine
- whether the user has pressed a mouse button, and reimplement
- \l{QWidget::mouseMoveEvent()}{mouseMoveEvent()} to check whether a QDrag is
- required.
-
- \sa {Drag and Drop}, QClipboard, QMimeData, QWindowsMime, QMacPasteboardMime,
- {Draggable Icons Example}, {Draggable Text Example}, {Drop Site Example},
- {Fridge Magnets Example}
-*/
-
-/*!
- Constructs a new drag object for the widget specified by \a dragSource.
-*/
-QDrag::QDrag(QWidget *dragSource)
- : QObject(*new QDragPrivate, dragSource)
-{
- Q_D(QDrag);
- d->source = dragSource;
- d->target = 0;
- d->data = 0;
- d->hotspot = QPoint(-10, -10);
- d->possible_actions = Qt::CopyAction;
- d->executed_action = Qt::IgnoreAction;
- d->defaultDropAction = Qt::IgnoreAction;
-}
-
-/*!
- Destroys the drag object.
-*/
-QDrag::~QDrag()
-{
- Q_D(QDrag);
- delete d->data;
- QDragManager *manager = QDragManager::self();
- if (manager && manager->object == this)
- manager->cancel(false);
-}
-
-/*!
- Sets the data to be sent to the given MIME \a data. Ownership of the data is
- transferred to the QDrag object.
-*/
-void QDrag::setMimeData(QMimeData *data)
-{
- Q_D(QDrag);
- if (d->data == data)
- return;
- if (d->data != 0)
- delete d->data;
- d->data = data;
-}
-
-/*!
- Returns the MIME data that is encapsulated by the drag object.
-*/
-QMimeData *QDrag::mimeData() const
-{
- Q_D(const QDrag);
- return d->data;
-}
-
-/*!
- Sets \a pixmap as the pixmap used to represent the data in a drag
- and drop operation. You can only set a pixmap before the drag is
- started.
-*/
-void QDrag::setPixmap(const QPixmap &pixmap)
-{
- Q_D(QDrag);
- d->pixmap = pixmap;
-}
-
-/*!
- Returns the pixmap used to represent the data in a drag and drop operation.
-*/
-QPixmap QDrag::pixmap() const
-{
- Q_D(const QDrag);
- return d->pixmap;
-}
-
-/*!
- Sets the position of the hot spot relative to the top-left corner of the
- pixmap used to the point specified by \a hotspot.
-
- \bold{Note:} on X11, the pixmap may not be able to keep up with the mouse
- movements if the hot spot causes the pixmap to be displayed
- directly under the cursor.
-*/
-void QDrag::setHotSpot(const QPoint& hotspot)
-{
- Q_D(QDrag);
- d->hotspot = hotspot;
-}
-
-/*!
- Returns the position of the hot spot relative to the top-left corner of the
- cursor.
-*/
-QPoint QDrag::hotSpot() const
-{
- Q_D(const QDrag);
- return d->hotspot;
-}
-
-/*!
- Returns the source of the drag object. This is the widget where the drag
- and drop operation originated.
-*/
-QWidget *QDrag::source() const
-{
- Q_D(const QDrag);
- return d->source;
-}
-
-/*!
- Returns the target of the drag and drop operation. This is the widget where
- the drag object was dropped.
-*/
-QWidget *QDrag::target() const
-{
- Q_D(const QDrag);
- return d->target;
-}
-
-/*!
- \since 4.3
-
- Starts the drag and drop operation and returns a value indicating the requested
- drop action when it is completed. The drop actions that the user can choose
- from are specified in \a supportedActions. The default proposed action will be selected
- among the allowed actions in the following order: Move, Copy and Link.
-
- \bold{Note:} On Linux and Mac OS X, the drag and drop operation
- can take some time, but this function does not block the event
- loop. Other events are still delivered to the application while
- the operation is performed. On Windows, the Qt event loop is
- blocked while during the operation.
-*/
-
-Qt::DropAction QDrag::exec(Qt::DropActions supportedActions)
-{
- return exec(supportedActions, Qt::IgnoreAction);
-}
-
-/*!
- \since 4.3
-
- Starts the drag and drop operation and returns a value indicating the requested
- drop action when it is completed. The drop actions that the user can choose
- from are specified in \a supportedActions.
-
- The \a defaultDropAction determines which action will be proposed when the user performs a
- drag without using modifier keys.
-
- \bold{Note:} On Linux and Mac OS X, the drag and drop operation
- can take some time, but this function does not block the event
- loop. Other events are still delivered to the application while
- the operation is performed. On Windows, the Qt event loop is
- blocked during the operation. However, QDrag::exec() on
- Windows causes processEvents() to be called frequently to keep the GUI responsive.
- If any loops or operations are called while a drag operation is active, it will block the drag operation.
-*/
-
-Qt::DropAction QDrag::exec(Qt::DropActions supportedActions, Qt::DropAction defaultDropAction)
-{
- Q_D(QDrag);
- if (!d->data) {
- qWarning("QDrag: No mimedata set before starting the drag");
- return d->executed_action;
- }
- QDragManager *manager = QDragManager::self();
- d->defaultDropAction = Qt::IgnoreAction;
- d->possible_actions = supportedActions;
-
- if (manager) {
- if (defaultDropAction == Qt::IgnoreAction) {
- if (supportedActions & Qt::MoveAction) {
- d->defaultDropAction = Qt::MoveAction;
- } else if (supportedActions & Qt::CopyAction) {
- d->defaultDropAction = Qt::CopyAction;
- } else if (supportedActions & Qt::LinkAction) {
- d->defaultDropAction = Qt::LinkAction;
- }
- } else {
- d->defaultDropAction = defaultDropAction;
- }
- d->executed_action = manager->drag(this);
- }
-
- return d->executed_action;
-}
-
-/*!
- \obsolete
-
- \bold{Note:} It is recommended to use exec() instead of this function.
-
- Starts the drag and drop operation and returns a value indicating the requested
- drop action when it is completed. The drop actions that the user can choose
- from are specified in \a request. Qt::CopyAction is always allowed.
-
- \bold{Note:} Although the drag and drop operation can take some time, this function
- does not block the event loop. Other events are still delivered to the application
- while the operation is performed.
-
- \sa exec()
-*/
-Qt::DropAction QDrag::start(Qt::DropActions request)
-{
- Q_D(QDrag);
- if (!d->data) {
- qWarning("QDrag: No mimedata set before starting the drag");
- return d->executed_action;
- }
- QDragManager *manager = QDragManager::self();
- d->defaultDropAction = Qt::IgnoreAction;
- d->possible_actions = request | Qt::CopyAction;
- if (manager)
- d->executed_action = manager->drag(this);
- return d->executed_action;
-}
-
-/*!
- Sets the drag \a cursor for the \a action. This allows you
- to override the default native cursors. To revert to using the
- native cursor for \a action pass in a null QPixmap as \a cursor.
-
- The \a action can only be CopyAction, MoveAction or LinkAction.
- All other values of DropAction are ignored.
-*/
-void QDrag::setDragCursor(const QPixmap &cursor, Qt::DropAction action)
-{
- Q_D(QDrag);
- if (action != Qt::CopyAction && action != Qt::MoveAction && action != Qt::LinkAction)
- return;
- if (cursor.isNull())
- d->customCursors.remove(action);
- else
- d->customCursors[action] = cursor;
-}
-
-/*!
- \fn void QDrag::actionChanged(Qt::DropAction action)
-
- This signal is emitted when the \a action associated with the
- drag changes.
-
- \sa targetChanged()
-*/
-
-/*!
- \fn void QDrag::targetChanged(QWidget *newTarget)
-
- This signal is emitted when the target of the drag and drop
- operation changes, with \a newTarget the new target.
-
- \sa target(), actionChanged()
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DRAGANDDROP
diff --git a/src/gui/to_be_moved/qdrag.h b/src/gui/to_be_moved/qdrag.h
deleted file mode 100644
index da847898b2..0000000000
--- a/src/gui/to_be_moved/qdrag.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/****************************************************************************
-**
-** 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 QDRAG_H
-#define QDRAG_H
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_DRAGANDDROP
-class QMimeData;
-class QDragPrivate;
-class QWidget;
-class QPixmap;
-class QPoint;
-class QDragManager;
-
-class Q_GUI_EXPORT QDrag : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QDrag)
-public:
- explicit QDrag(QWidget *dragSource);
- ~QDrag();
-
- void setMimeData(QMimeData *data);
- QMimeData *mimeData() const;
-
- void setPixmap(const QPixmap &);
- QPixmap pixmap() const;
-
- void setHotSpot(const QPoint &hotspot);
- QPoint hotSpot() const;
-
- QWidget *source() const;
- QWidget *target() const;
-
- Qt::DropAction start(Qt::DropActions supportedActions = Qt::CopyAction);
- Qt::DropAction exec(Qt::DropActions supportedActions = Qt::MoveAction);
- Qt::DropAction exec(Qt::DropActions supportedActions, Qt::DropAction defaultAction);
-
- void setDragCursor(const QPixmap &cursor, Qt::DropAction action);
-
-Q_SIGNALS:
- void actionChanged(Qt::DropAction action);
- void targetChanged(QWidget *newTarget);
-
-private:
-#ifdef Q_WS_MAC
- friend class QWidgetPrivate;
-#endif
- friend class QDragManager;
- Q_DISABLE_COPY(QDrag)
-};
-
-#endif // QT_NO_DRAGANDDROP
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDRAG_H
diff --git a/src/gui/to_be_moved/qlinecontrol.cpp b/src/gui/to_be_moved/qlinecontrol.cpp
deleted file mode 100644
index eb4e142328..0000000000
--- a/src/gui/to_be_moved/qlinecontrol.cpp
+++ /dev/null
@@ -1,1833 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlinecontrol_p.h"
-
-#ifndef QT_NO_LINEEDIT
-
-#include "qabstractitemview.h"
-#include "qclipboard.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#ifndef QT_NO_IM
-#include "qinputcontext.h"
-#include "qlist.h"
-#endif
-#include "qapplication.h"
-#ifndef QT_NO_GRAPHICSVIEW
-#include "qgraphicssceneevent.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \internal
-
- Updates the display text based of the current edit text
- If the text has changed will emit displayTextChanged()
-*/
-void QLineControl::updateDisplayText(bool forceUpdate)
-{
- QString orig = m_textLayout.text();
- QString str;
- if (m_echoMode == QLineEdit::NoEcho)
- str = QString::fromLatin1("");
- else
- str = m_text;
-
- if (m_echoMode == QLineEdit::Password || (m_echoMode == QLineEdit::PasswordEchoOnEdit
- && !m_passwordEchoEditing))
- str.fill(m_passwordCharacter);
-
- // replace certain non-printable characters with spaces (to avoid
- // drawing boxes when using fonts that don't have glyphs for such
- // characters)
- QChar* uc = str.data();
- for (int i = 0; i < (int)str.length(); ++i) {
- if ((uc[i] < 0x20 && uc[i] != 0x09)
- || uc[i] == QChar::LineSeparator
- || uc[i] == QChar::ParagraphSeparator
- || uc[i] == QChar::ObjectReplacementCharacter)
- uc[i] = QChar(0x0020);
- }
-
- m_textLayout.setText(str);
-
- QTextOption option;
- option.setTextDirection(m_layoutDirection);
- option.setFlags(QTextOption::IncludeTrailingSpaces);
- m_textLayout.setTextOption(option);
-
- m_textLayout.beginLayout();
- QTextLine l = m_textLayout.createLine();
- m_textLayout.endLayout();
- m_ascent = qRound(l.ascent());
-
- if (str != orig || forceUpdate)
- emit displayTextChanged(str);
-}
-
-#ifndef QT_NO_CLIPBOARD
-/*!
- \internal
-
- Copies the currently selected text into the clipboard using the given
- \a mode.
-
- \note If the echo mode is set to a mode other than Normal then copy
- will not work. This is to prevent using copy as a method of bypassing
- password features of the line control.
-*/
-void QLineControl::copy(QClipboard::Mode mode) const
-{
- QString t = selectedText();
- if (!t.isEmpty() && m_echoMode == QLineEdit::Normal) {
- disconnect(QApplication::clipboard(), SIGNAL(selectionChanged()), this, 0);
- QApplication::clipboard()->setText(t, mode);
- connect(QApplication::clipboard(), SIGNAL(selectionChanged()),
- this, SLOT(_q_clipboardChanged()));
- }
-}
-
-/*!
- \internal
-
- Inserts the text stored in the application clipboard into the line
- control.
-
- \sa insert()
-*/
-void QLineControl::paste(QClipboard::Mode clipboardMode)
-{
- QString clip = QApplication::clipboard()->text(clipboardMode);
- if (!clip.isEmpty() || hasSelectedText()) {
- separate(); //make it a separate undo/redo command
- insert(clip);
- separate();
- }
-}
-
-#endif // !QT_NO_CLIPBOARD
-
-/*!
- \internal
-
- Handles the behavior for the backspace key or function.
- Removes the current selection if there is a selection, otherwise
- removes the character prior to the cursor position.
-
- \sa del()
-*/
-void QLineControl::backspace()
-{
- int priorState = m_undoState;
- if (hasSelectedText()) {
- removeSelectedText();
- } else if (m_cursor) {
- --m_cursor;
- if (m_maskData)
- m_cursor = prevMaskBlank(m_cursor);
- QChar uc = m_text.at(m_cursor);
- if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) {
- // second half of a surrogate, check if we have the first half as well,
- // if yes delete both at once
- uc = m_text.at(m_cursor - 1);
- if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) {
- internalDelete(true);
- --m_cursor;
- }
- }
- internalDelete(true);
- }
- finishChange(priorState);
-}
-
-/*!
- \internal
-
- Handles the behavior for the delete key or function.
- Removes the current selection if there is a selection, otherwise
- removes the character after the cursor position.
-
- \sa del()
-*/
-void QLineControl::del()
-{
- int priorState = m_undoState;
- if (hasSelectedText()) {
- removeSelectedText();
- } else {
- int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor;
- while (n--)
- internalDelete();
- }
- finishChange(priorState);
-}
-
-/*!
- \internal
-
- Inserts the given \a newText at the current cursor position.
- If there is any selected text it is removed prior to insertion of
- the new text.
-*/
-void QLineControl::insert(const QString &newText)
-{
- int priorState = m_undoState;
- removeSelectedText();
- internalInsert(newText);
- finishChange(priorState);
-}
-
-/*!
- \internal
-
- Clears the line control text.
-*/
-void QLineControl::clear()
-{
- int priorState = m_undoState;
- m_selstart = 0;
- m_selend = m_text.length();
- removeSelectedText();
- separate();
- finishChange(priorState, /*update*/false, /*edited*/false);
-}
-
-/*!
- \internal
-
- Sets \a length characters from the given \a start position as selected.
- The given \a start position must be within the current text for
- the line control. If \a length characters cannot be selected, then
- the selection will extend to the end of the current text.
-*/
-void QLineControl::setSelection(int start, int length)
-{
- if(start < 0 || start > (int)m_text.length()){
- qWarning("QLineControl::setSelection: Invalid start position");
- return;
- }
-
- if (length > 0) {
- if (start == m_selstart && start + length == m_selend)
- return;
- m_selstart = start;
- m_selend = qMin(start + length, (int)m_text.length());
- m_cursor = m_selend;
- } else if (length < 0){
- if (start == m_selend && start + length == m_selstart)
- return;
- m_selstart = qMax(start + length, 0);
- m_selend = start;
- m_cursor = m_selstart;
- } else if (m_selstart != m_selend) {
- m_selstart = 0;
- m_selend = 0;
- m_cursor = start;
- } else {
- m_cursor = start;
- emitCursorPositionChanged();
- return;
- }
- emit selectionChanged();
- emitCursorPositionChanged();
-}
-
-void QLineControl::_q_clipboardChanged()
-{
-}
-
-void QLineControl::_q_deleteSelected()
-{
- if (!hasSelectedText())
- return;
-
- int priorState = m_undoState;
- emit resetInputContext();
- removeSelectedText();
- separate();
- finishChange(priorState);
-}
-
-/*!
- \internal
-
- Initializes the line control with a starting text value of \a txt.
-*/
-void QLineControl::init(const QString &txt)
-{
- m_text = txt;
- updateDisplayText();
- m_cursor = m_text.length();
-}
-
-/*!
- \internal
-
- Sets the password echo editing to \a editing. If password echo editing
- is true, then the text of the password is displayed even if the echo
- mode is set to QLineEdit::PasswordEchoOnEdit. Password echoing editing
- does not affect other echo modes.
-*/
-void QLineControl::updatePasswordEchoEditing(bool editing)
-{
- m_passwordEchoEditing = editing;
- updateDisplayText();
-}
-
-/*!
- \internal
-
- Returns the cursor position of the given \a x pixel value in relation
- to the displayed text. The given \a betweenOrOn specified what kind
- of cursor position is requested.
-*/
-int QLineControl::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const
-{
- return m_textLayout.lineAt(0).xToCursor(x, betweenOrOn);
-}
-
-/*!
- \internal
-
- Returns the bounds of the current cursor, as defined as a
- between characters cursor.
-*/
-QRect QLineControl::cursorRect() const
-{
- QTextLine l = m_textLayout.lineAt(0);
- int c = m_cursor;
- if (m_preeditCursor != -1)
- c += m_preeditCursor;
- int cix = qRound(l.cursorToX(c));
- int w = m_cursorWidth;
- int ch = l.height() + 1;
-
- return QRect(cix-5, 0, w+9, ch);
-}
-
-/*!
- \internal
-
- Fixes the current text so that it is valid given any set validators.
-
- Returns true if the text was changed. Otherwise returns false.
-*/
-bool QLineControl::fixup() // this function assumes that validate currently returns != Acceptable
-{
-#ifndef QT_NO_VALIDATOR
- if (m_validator) {
- QString textCopy = m_text;
- int cursorCopy = m_cursor;
- m_validator->fixup(textCopy);
- if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) {
- if (textCopy != m_text || cursorCopy != m_cursor)
- internalSetText(textCopy, cursorCopy);
- return true;
- }
- }
-#endif
- return false;
-}
-
-/*!
- \internal
-
- Moves the cursor to the given position \a pos. If \a mark is true will
- adjust the currently selected text.
-*/
-void QLineControl::moveCursor(int pos, bool mark)
-{
- if (pos != m_cursor) {
- separate();
- if (m_maskData)
- pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos);
- }
- if (mark) {
- int anchor;
- if (m_selend > m_selstart && m_cursor == m_selstart)
- anchor = m_selend;
- else if (m_selend > m_selstart && m_cursor == m_selend)
- anchor = m_selstart;
- else
- anchor = m_cursor;
- m_selstart = qMin(anchor, pos);
- m_selend = qMax(anchor, pos);
- updateDisplayText();
- } else {
- internalDeselect();
- }
- m_cursor = pos;
- if (mark || m_selDirty) {
- m_selDirty = false;
- emit selectionChanged();
- }
- emitCursorPositionChanged();
-}
-
-/*!
- \internal
-
- Applies the given input method event \a event to the text of the line
- control
-*/
-void QLineControl::processInputMethodEvent(QInputMethodEvent *event)
-{
- int priorState = 0;
- bool isGettingInput = !event->commitString().isEmpty()
- || event->preeditString() != preeditAreaText()
- || event->replacementLength() > 0;
- bool cursorPositionChanged = false;
-
- if (isGettingInput) {
- // If any text is being input, remove selected text.
- priorState = m_undoState;
- if (echoMode() == QLineEdit::PasswordEchoOnEdit && !passwordEchoEditing()) {
- updatePasswordEchoEditing(true);
- m_selstart = 0;
- m_selend = m_text.length();
- }
- removeSelectedText();
- }
-
- int c = m_cursor; // cursor position after insertion of commit string
- if (event->replacementStart() <= 0)
- c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength());
-
- m_cursor += event->replacementStart();
-
- // insert commit string
- if (event->replacementLength()) {
- m_selstart = m_cursor;
- m_selend = m_selstart + event->replacementLength();
- removeSelectedText();
- }
- if (!event->commitString().isEmpty()) {
- internalInsert(event->commitString());
- cursorPositionChanged = true;
- }
-
- m_cursor = qMin(c, m_text.length());
-
- for (int i = 0; i < event->attributes().size(); ++i) {
- const QInputMethodEvent::Attribute &a = event->attributes().at(i);
- if (a.type == QInputMethodEvent::Selection) {
- m_cursor = qBound(0, a.start + a.length, m_text.length());
- if (a.length) {
- m_selstart = qMax(0, qMin(a.start, m_text.length()));
- m_selend = m_cursor;
- if (m_selend < m_selstart) {
- qSwap(m_selstart, m_selend);
- }
- } else {
- m_selstart = m_selend = 0;
- }
- cursorPositionChanged = true;
- }
- }
-#ifndef QT_NO_IM
- setPreeditArea(m_cursor, event->preeditString());
-#endif //QT_NO_IM
- const int oldPreeditCursor = m_preeditCursor;
- m_preeditCursor = event->preeditString().length();
- m_hideCursor = false;
- QList<QTextLayout::FormatRange> formats;
- for (int i = 0; i < event->attributes().size(); ++i) {
- const QInputMethodEvent::Attribute &a = event->attributes().at(i);
- if (a.type == QInputMethodEvent::Cursor) {
- m_preeditCursor = a.start;
- m_hideCursor = !a.length;
- } else if (a.type == QInputMethodEvent::TextFormat) {
- QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat();
- if (f.isValid()) {
- QTextLayout::FormatRange o;
- o.start = a.start + m_cursor;
- o.length = a.length;
- o.format = f;
- formats.append(o);
- }
- }
- }
- m_textLayout.setAdditionalFormats(formats);
- updateDisplayText(/*force*/ true);
- if (cursorPositionChanged)
- emitCursorPositionChanged();
- else if (m_preeditCursor != oldPreeditCursor)
- emit updateMicroFocus();
- if (isGettingInput)
- finishChange(priorState);
-}
-
-/*!
- \internal
-
- Draws the display text for the line control using the given
- \a painter, \a clip, and \a offset. Which aspects of the display text
- are drawn is specified by the given \a flags.
-
- If the flags contain DrawSelections, then the selection or input mask
- backgrounds and foregrounds will be applied before drawing the text.
-
- If the flags contain DrawCursor a cursor of the current cursorWidth()
- will be drawn after drawing the text.
-
- The display text will only be drawn if the flags contain DrawText
-*/
-void QLineControl::draw(QPainter *painter, const QPoint &offset, const QRect &clip, int flags)
-{
- QVector<QTextLayout::FormatRange> selections;
- if (flags & DrawSelections) {
- QTextLayout::FormatRange o;
- if (m_selstart < m_selend) {
- o.start = m_selstart;
- o.length = m_selend - m_selstart;
- o.format.setBackground(m_palette.brush(QPalette::Highlight));
- o.format.setForeground(m_palette.brush(QPalette::HighlightedText));
- } else {
- // mask selection
- if(!m_blinkPeriod || m_blinkStatus){
- o.start = m_cursor;
- o.length = 1;
- o.format.setBackground(m_palette.brush(QPalette::Text));
- o.format.setForeground(m_palette.brush(QPalette::Window));
- }
- }
- selections.append(o);
- }
-
- if (flags & DrawText)
- m_textLayout.draw(painter, offset, selections, clip);
-
- if (flags & DrawCursor){
- int cursor = m_cursor;
- if (m_preeditCursor != -1)
- cursor += m_preeditCursor;
- if (!m_hideCursor && (!m_blinkPeriod || m_blinkStatus))
- m_textLayout.drawCursor(painter, offset, cursor, m_cursorWidth);
- }
-}
-
-/*!
- \internal
-
- Sets the selection to cover the word at the given cursor position.
- The word boundaries are defined by the behavior of QTextLayout::SkipWords
- cursor mode.
-*/
-void QLineControl::selectWordAtPos(int cursor)
-{
- int next = cursor + 1;
- if(next > end())
- --next;
- int c = m_textLayout.previousCursorPosition(next, QTextLayout::SkipWords);
- moveCursor(c, false);
- // ## text layout should support end of words.
- int end = m_textLayout.nextCursorPosition(c, QTextLayout::SkipWords);
- while (end > cursor && m_text[end-1].isSpace())
- --end;
- moveCursor(end, true);
-}
-
-/*!
- \internal
-
- Completes a change to the line control text. If the change is not valid
- will undo the line control state back to the given \a validateFromState.
-
- If \a edited is true and the change is valid, will emit textEdited() in
- addition to textChanged(). Otherwise only emits textChanged() on a valid
- change.
-
- The \a update value is currently unused.
-*/
-bool QLineControl::finishChange(int validateFromState, bool update, bool edited)
-{
- Q_UNUSED(update)
- bool lineDirty = m_selDirty;
- if (m_textDirty) {
- // do validation
- bool wasValidInput = m_validInput;
- m_validInput = true;
-#ifndef QT_NO_VALIDATOR
- if (m_validator) {
- m_validInput = false;
- QString textCopy = m_text;
- int cursorCopy = m_cursor;
- m_validInput = (m_validator->validate(textCopy, cursorCopy) != QValidator::Invalid);
- if (m_validInput) {
- if (m_text != textCopy) {
- internalSetText(textCopy, cursorCopy);
- return true;
- }
- m_cursor = cursorCopy;
- }
- }
-#endif
- if (validateFromState >= 0 && wasValidInput && !m_validInput) {
- if (m_transactions.count())
- return false;
- internalUndo(validateFromState);
- m_history.resize(m_undoState);
- if (m_modifiedState > m_undoState)
- m_modifiedState = -1;
- m_validInput = true;
- m_textDirty = false;
- }
- updateDisplayText();
- lineDirty |= m_textDirty;
- if (m_textDirty) {
- m_textDirty = false;
- QString actualText = text();
- if (edited)
- emit textEdited(actualText);
- emit textChanged(actualText);
- }
- }
- if (m_selDirty) {
- m_selDirty = false;
- emit selectionChanged();
- }
- emitCursorPositionChanged();
- return true;
-}
-
-/*!
- \internal
-
- An internal function for setting the text of the line control.
-*/
-void QLineControl::internalSetText(const QString &txt, int pos, bool edited)
-{
- internalDeselect();
- emit resetInputContext();
- QString oldText = m_text;
- if (m_maskData) {
- m_text = maskString(0, txt, true);
- m_text += clearString(m_text.length(), m_maxLength - m_text.length());
- } else {
- m_text = txt.isEmpty() ? txt : txt.left(m_maxLength);
- }
- m_history.clear();
- m_modifiedState = m_undoState = 0;
- m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos;
- m_textDirty = (oldText != m_text);
- finishChange(-1, true, edited);
-}
-
-
-/*!
- \internal
-
- Adds the given \a command to the undo history
- of the line control. Does not apply the command.
-*/
-void QLineControl::addCommand(const Command &cmd)
-{
- if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) {
- m_history.resize(m_undoState + 2);
- m_history[m_undoState++] = Command(Separator, m_cursor, 0, m_selstart, m_selend);
- } else {
- m_history.resize(m_undoState + 1);
- }
- m_separator = false;
- m_history[m_undoState++] = cmd;
-}
-
-/*!
- \internal
-
- Inserts the given string \a s into the line
- control.
-
- Also adds the appropriate commands into the undo history.
- This function does not call finishChange(), and may leave the text
- in an invalid state.
-*/
-void QLineControl::internalInsert(const QString &s)
-{
- if (hasSelectedText())
- addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
- if (m_maskData) {
- QString ms = maskString(m_cursor, s);
- for (int i = 0; i < (int) ms.length(); ++i) {
- addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1));
- addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1));
- }
- m_text.replace(m_cursor, ms.length(), ms);
- m_cursor += ms.length();
- m_cursor = nextMaskBlank(m_cursor);
- m_textDirty = true;
- } else {
- int remaining = m_maxLength - m_text.length();
- if (remaining != 0) {
- m_text.insert(m_cursor, s.left(remaining));
- for (int i = 0; i < (int) s.left(remaining).length(); ++i)
- addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1));
- m_textDirty = true;
- }
- }
-}
-
-/*!
- \internal
-
- deletes a single character from the current text. If \a wasBackspace,
- the character prior to the cursor is removed. Otherwise the character
- after the cursor is removed.
-
- Also adds the appropriate commands into the undo history.
- This function does not call finishChange(), and may leave the text
- in an invalid state.
-*/
-void QLineControl::internalDelete(bool wasBackspace)
-{
- if (m_cursor < (int) m_text.length()) {
- if (hasSelectedText())
- addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
- addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)),
- m_cursor, m_text.at(m_cursor), -1, -1));
- if (m_maskData) {
- m_text.replace(m_cursor, 1, clearString(m_cursor, 1));
- addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1));
- } else {
- m_text.remove(m_cursor, 1);
- }
- m_textDirty = true;
- }
-}
-
-/*!
- \internal
-
- removes the currently selected text from the line control.
-
- Also adds the appropriate commands into the undo history.
- This function does not call finishChange(), and may leave the text
- in an invalid state.
-*/
-void QLineControl::removeSelectedText()
-{
- if (m_selstart < m_selend && m_selend <= (int) m_text.length()) {
- separate();
- int i ;
- addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend));
- if (m_selstart <= m_cursor && m_cursor < m_selend) {
- // cursor is within the selection. Split up the commands
- // to be able to restore the correct cursor position
- for (i = m_cursor; i >= m_selstart; --i)
- addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1));
- for (i = m_selend - 1; i > m_cursor; --i)
- addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1));
- } else {
- for (i = m_selend-1; i >= m_selstart; --i)
- addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1));
- }
- if (m_maskData) {
- m_text.replace(m_selstart, m_selend - m_selstart, clearString(m_selstart, m_selend - m_selstart));
- for (int i = 0; i < m_selend - m_selstart; ++i)
- addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1));
- } else {
- m_text.remove(m_selstart, m_selend - m_selstart);
- }
- if (m_cursor > m_selstart)
- m_cursor -= qMin(m_cursor, m_selend) - m_selstart;
- internalDeselect();
- m_textDirty = true;
- }
-}
-
-/*!
- \internal
-
- Parses the input mask specified by \a maskFields to generate
- the mask data used to handle input masks.
-*/
-void QLineControl::parseInputMask(const QString &maskFields)
-{
- int delimiter = maskFields.indexOf(QLatin1Char(';'));
- if (maskFields.isEmpty() || delimiter == 0) {
- if (m_maskData) {
- delete [] m_maskData;
- m_maskData = 0;
- m_maxLength = 32767;
- internalSetText(QString());
- }
- return;
- }
-
- if (delimiter == -1) {
- m_blank = QLatin1Char(' ');
- m_inputMask = maskFields;
- } else {
- m_inputMask = maskFields.left(delimiter);
- m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' ');
- }
-
- // calculate m_maxLength / m_maskData length
- m_maxLength = 0;
- QChar c = 0;
- for (int i=0; i<m_inputMask.length(); i++) {
- c = m_inputMask.at(i);
- if (i > 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) {
- m_maxLength++;
- continue;
- }
- if (c != QLatin1Char('\\') && c != QLatin1Char('!') &&
- c != QLatin1Char('<') && c != QLatin1Char('>') &&
- c != QLatin1Char('{') && c != QLatin1Char('}') &&
- c != QLatin1Char('[') && c != QLatin1Char(']'))
- m_maxLength++;
- }
-
- delete [] m_maskData;
- m_maskData = new MaskInputData[m_maxLength];
-
- MaskInputData::Casemode m = MaskInputData::NoCaseMode;
- c = 0;
- bool s;
- bool escape = false;
- int index = 0;
- for (int i = 0; i < m_inputMask.length(); i++) {
- c = m_inputMask.at(i);
- if (escape) {
- s = true;
- m_maskData[index].maskChar = c;
- m_maskData[index].separator = s;
- m_maskData[index].caseMode = m;
- index++;
- escape = false;
- } else if (c == QLatin1Char('<')) {
- m = MaskInputData::Lower;
- } else if (c == QLatin1Char('>')) {
- m = MaskInputData::Upper;
- } else if (c == QLatin1Char('!')) {
- m = MaskInputData::NoCaseMode;
- } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) {
- switch (c.unicode()) {
- case 'A':
- case 'a':
- case 'N':
- case 'n':
- case 'X':
- case 'x':
- case '9':
- case '0':
- case 'D':
- case 'd':
- case '#':
- case 'H':
- case 'h':
- case 'B':
- case 'b':
- s = false;
- break;
- case '\\':
- escape = true;
- default:
- s = true;
- break;
- }
-
- if (!escape) {
- m_maskData[index].maskChar = c;
- m_maskData[index].separator = s;
- m_maskData[index].caseMode = m;
- index++;
- }
- }
- }
- internalSetText(m_text);
-}
-
-
-/*!
- \internal
-
- checks if the key is valid compared to the inputMask
-*/
-bool QLineControl::isValidInput(QChar key, QChar mask) const
-{
- switch (mask.unicode()) {
- case 'A':
- if (key.isLetter())
- return true;
- break;
- case 'a':
- if (key.isLetter() || key == m_blank)
- return true;
- break;
- case 'N':
- if (key.isLetterOrNumber())
- return true;
- break;
- case 'n':
- if (key.isLetterOrNumber() || key == m_blank)
- return true;
- break;
- case 'X':
- if (key.isPrint())
- return true;
- break;
- case 'x':
- if (key.isPrint() || key == m_blank)
- return true;
- break;
- case '9':
- if (key.isNumber())
- return true;
- break;
- case '0':
- if (key.isNumber() || key == m_blank)
- return true;
- break;
- case 'D':
- if (key.isNumber() && key.digitValue() > 0)
- return true;
- break;
- case 'd':
- if ((key.isNumber() && key.digitValue() > 0) || key == m_blank)
- return true;
- break;
- case '#':
- if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank)
- return true;
- break;
- case 'B':
- if (key == QLatin1Char('0') || key == QLatin1Char('1'))
- return true;
- break;
- case 'b':
- if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank)
- return true;
- break;
- case 'H':
- if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')))
- return true;
- break;
- case 'h':
- if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank)
- return true;
- break;
- default:
- break;
- }
- return false;
-}
-
-/*!
- \internal
-
- Returns true if the given text \a str is valid for any
- validator or input mask set for the line control.
-
- Otherwise returns false
-*/
-bool QLineControl::hasAcceptableInput(const QString &str) const
-{
-#ifndef QT_NO_VALIDATOR
- QString textCopy = str;
- int cursorCopy = m_cursor;
- if (m_validator && m_validator->validate(textCopy, cursorCopy)
- != QValidator::Acceptable)
- return false;
-#endif
-
- if (!m_maskData)
- return true;
-
- if (str.length() != m_maxLength)
- return false;
-
- for (int i=0; i < m_maxLength; ++i) {
- if (m_maskData[i].separator) {
- if (str.at(i) != m_maskData[i].maskChar)
- return false;
- } else {
- if (!isValidInput(str.at(i), m_maskData[i].maskChar))
- return false;
- }
- }
- return true;
-}
-
-/*!
- \internal
-
- Applies the inputMask on \a str starting from position \a pos in the mask. \a clear
- specifies from where characters should be gotten when a separator is met in \a str - true means
- that blanks will be used, false that previous input is used.
- Calling this when no inputMask is set is undefined.
-*/
-QString QLineControl::maskString(uint pos, const QString &str, bool clear) const
-{
- if (pos >= (uint)m_maxLength)
- return QString::fromLatin1("");
-
- QString fill;
- fill = clear ? clearString(0, m_maxLength) : m_text;
-
- int strIndex = 0;
- QString s = QString::fromLatin1("");
- int i = pos;
- while (i < m_maxLength) {
- if (strIndex < str.length()) {
- if (m_maskData[i].separator) {
- s += m_maskData[i].maskChar;
- if (str[(int)strIndex] == m_maskData[i].maskChar)
- strIndex++;
- ++i;
- } else {
- if (isValidInput(str[(int)strIndex], m_maskData[i].maskChar)) {
- switch (m_maskData[i].caseMode) {
- case MaskInputData::Upper:
- s += str[(int)strIndex].toUpper();
- break;
- case MaskInputData::Lower:
- s += str[(int)strIndex].toLower();
- break;
- default:
- s += str[(int)strIndex];
- }
- ++i;
- } else {
- // search for separator first
- int n = findInMask(i, true, true, str[(int)strIndex]);
- if (n != -1) {
- if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[(int)strIndex]))) {
- s += fill.mid(i, n-i+1);
- i = n + 1; // update i to find + 1
- }
- } else {
- // search for valid m_blank if not
- n = findInMask(i, true, false, str[(int)strIndex]);
- if (n != -1) {
- s += fill.mid(i, n-i);
- switch (m_maskData[n].caseMode) {
- case MaskInputData::Upper:
- s += str[(int)strIndex].toUpper();
- break;
- case MaskInputData::Lower:
- s += str[(int)strIndex].toLower();
- break;
- default:
- s += str[(int)strIndex];
- }
- i = n + 1; // updates i to find + 1
- }
- }
- }
- ++strIndex;
- }
- } else
- break;
- }
-
- return s;
-}
-
-
-
-/*!
- \internal
-
- Returns a "cleared" string with only separators and blank chars.
- Calling this when no inputMask is set is undefined.
-*/
-QString QLineControl::clearString(uint pos, uint len) const
-{
- if (pos >= (uint)m_maxLength)
- return QString();
-
- QString s;
- int end = qMin((uint)m_maxLength, pos + len);
- for (int i = pos; i < end; ++i)
- if (m_maskData[i].separator)
- s += m_maskData[i].maskChar;
- else
- s += m_blank;
-
- return s;
-}
-
-/*!
- \internal
-
- Strips blank parts of the input in a QLineControl when an inputMask is set,
- separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1".
-*/
-QString QLineControl::stripString(const QString &str) const
-{
- if (!m_maskData)
- return str;
-
- QString s;
- int end = qMin(m_maxLength, (int)str.length());
- for (int i = 0; i < end; ++i)
- if (m_maskData[i].separator)
- s += m_maskData[i].maskChar;
- else
- if (str[i] != m_blank)
- s += str[i];
-
- return s;
-}
-
-/*!
- \internal
- searches forward/backward in m_maskData for either a separator or a m_blank
-*/
-int QLineControl::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const
-{
- if (pos >= m_maxLength || pos < 0)
- return -1;
-
- int end = forward ? m_maxLength : -1;
- int step = forward ? 1 : -1;
- int i = pos;
-
- while (i != end) {
- if (findSeparator) {
- if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar)
- return i;
- } else {
- if (!m_maskData[i].separator) {
- if (searchChar.isNull())
- return i;
- else if (isValidInput(searchChar, m_maskData[i].maskChar))
- return i;
- }
- }
- i += step;
- }
- return -1;
-}
-
-void QLineControl::internalUndo(int until)
-{
- if (!isUndoAvailable())
- return;
- internalDeselect();
- while (m_undoState && m_undoState > until) {
- Command& cmd = m_history[--m_undoState];
- switch (cmd.type) {
- case Insert:
- m_text.remove(cmd.pos, 1);
- m_cursor = cmd.pos;
- break;
- case SetSelection:
- m_selstart = cmd.selStart;
- m_selend = cmd.selEnd;
- m_cursor = cmd.pos;
- break;
- case Remove:
- case RemoveSelection:
- m_text.insert(cmd.pos, cmd.uc);
- m_cursor = cmd.pos + 1;
- break;
- case Delete:
- case DeleteSelection:
- m_text.insert(cmd.pos, cmd.uc);
- m_cursor = cmd.pos;
- break;
- case Separator:
- continue;
- }
- if (until < 0 && m_undoState) {
- Command& next = m_history[m_undoState-1];
- if (next.type != cmd.type && next.type < RemoveSelection
- && (cmd.type < RemoveSelection || next.type == Separator))
- break;
- }
- }
- m_textDirty = true;
- emitCursorPositionChanged();
-}
-
-void QLineControl::internalRedo()
-{
- if (!isRedoAvailable())
- return;
- internalDeselect();
- while (m_undoState < (int)m_history.size()) {
- Command& cmd = m_history[m_undoState++];
- switch (cmd.type) {
- case Insert:
- m_text.insert(cmd.pos, cmd.uc);
- m_cursor = cmd.pos + 1;
- break;
- case SetSelection:
- m_selstart = cmd.selStart;
- m_selend = cmd.selEnd;
- m_cursor = cmd.pos;
- break;
- case Remove:
- case Delete:
- case RemoveSelection:
- case DeleteSelection:
- m_text.remove(cmd.pos, 1);
- m_selstart = cmd.selStart;
- m_selend = cmd.selEnd;
- m_cursor = cmd.pos;
- break;
- case Separator:
- m_selstart = cmd.selStart;
- m_selend = cmd.selEnd;
- m_cursor = cmd.pos;
- break;
- }
- if (m_undoState < (int)m_history.size()) {
- Command& next = m_history[m_undoState];
- if (next.type != cmd.type && cmd.type < RemoveSelection && next.type != Separator
- && (next.type < RemoveSelection || cmd.type == Separator))
- break;
- }
- }
- m_textDirty = true;
- emitCursorPositionChanged();
-}
-
-/*!
- \internal
-
- If the current cursor position differs from the last emitted cursor
- position, emits cursorPositionChanged().
-*/
-void QLineControl::emitCursorPositionChanged()
-{
- if (m_cursor != m_lastCursorPos) {
- const int oldLast = m_lastCursorPos;
- m_lastCursorPos = m_cursor;
- cursorPositionChanged(oldLast, m_cursor);
- }
-}
-
-#ifndef QT_NO_COMPLETER
-// iterating forward(dir=1)/backward(dir=-1) from the
-// current row based. dir=0 indicates a new completion prefix was set.
-bool QLineControl::advanceToEnabledItem(int dir)
-{
- int start = m_completer->currentRow();
- if (start == -1)
- return false;
- int i = start + dir;
- if (dir == 0) dir = 1;
- do {
- if (!m_completer->setCurrentRow(i)) {
- if (!m_completer->wrapAround())
- break;
- i = i > 0 ? 0 : m_completer->completionCount() - 1;
- } else {
- QModelIndex currentIndex = m_completer->currentIndex();
- if (m_completer->completionModel()->flags(currentIndex) & Qt::ItemIsEnabled)
- return true;
- i += dir;
- }
- } while (i != start);
-
- m_completer->setCurrentRow(start); // restore
- return false;
-}
-
-void QLineControl::complete(int key)
-{
- if (!m_completer || isReadOnly() || echoMode() != QLineEdit::Normal)
- return;
-
- QString text = this->text();
- if (m_completer->completionMode() == QCompleter::InlineCompletion) {
- if (key == Qt::Key_Backspace)
- return;
- int n = 0;
- if (key == Qt::Key_Up || key == Qt::Key_Down) {
- if (textAfterSelection().length())
- return;
- QString prefix = hasSelectedText() ? textBeforeSelection()
- : text;
- if (text.compare(m_completer->currentCompletion(), m_completer->caseSensitivity()) != 0
- || prefix.compare(m_completer->completionPrefix(), m_completer->caseSensitivity()) != 0) {
- m_completer->setCompletionPrefix(prefix);
- } else {
- n = (key == Qt::Key_Up) ? -1 : +1;
- }
- } else {
- m_completer->setCompletionPrefix(text);
- }
- if (!advanceToEnabledItem(n))
- return;
- } else {
-#ifndef QT_KEYPAD_NAVIGATION
- if (text.isEmpty()) {
- m_completer->popup()->hide();
- return;
- }
-#endif
- m_completer->setCompletionPrefix(text);
- }
-
- m_completer->complete();
-}
-#endif
-
-void QLineControl::setCursorBlinkPeriod(int msec)
-{
- if (msec == m_blinkPeriod)
- return;
- if (m_blinkTimer) {
- killTimer(m_blinkTimer);
- }
- if (msec) {
- m_blinkTimer = startTimer(msec / 2);
- m_blinkStatus = 1;
- } else {
- m_blinkTimer = 0;
- if (m_blinkStatus == 1)
- emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect());
- }
- m_blinkPeriod = msec;
-}
-
-void QLineControl::resetCursorBlinkTimer()
-{
- if (m_blinkPeriod == 0 || m_blinkTimer == 0)
- return;
- killTimer(m_blinkTimer);
- m_blinkTimer = startTimer(m_blinkPeriod / 2);
- m_blinkStatus = 1;
-}
-
-void QLineControl::timerEvent(QTimerEvent *event)
-{
- if (event->timerId() == m_blinkTimer) {
- m_blinkStatus = !m_blinkStatus;
- emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect());
- } else if (event->timerId() == m_deleteAllTimer) {
- killTimer(m_deleteAllTimer);
- m_deleteAllTimer = 0;
- clear();
- } else if (event->timerId() == m_tripleClickTimer) {
- killTimer(m_tripleClickTimer);
- m_tripleClickTimer = 0;
- }
-}
-
-bool QLineControl::processEvent(QEvent* ev)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- if ((ev->type() == QEvent::KeyPress) || (ev->type() == QEvent::KeyRelease)) {
- QKeyEvent *ke = (QKeyEvent *)ev;
- if (ke->key() == Qt::Key_Back) {
- if (ke->isAutoRepeat()) {
- // Swallow it. We don't want back keys running amok.
- ke->accept();
- return true;
- }
- if ((ev->type() == QEvent::KeyRelease)
- && !isReadOnly()
- && m_deleteAllTimer) {
- killTimer(m_deleteAllTimer);
- m_deleteAllTimer = 0;
- backspace();
- ke->accept();
- return true;
- }
- }
- }
- }
-#endif
- switch(ev->type()){
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseDoubleClick:
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMousePress:{
- QGraphicsSceneMouseEvent *gvEv = static_cast<QGraphicsSceneMouseEvent*>(ev);
- QMouseEvent* mouse = new QMouseEvent(ev->type(),
- gvEv->pos().toPoint(), gvEv->button(), gvEv->buttons(), gvEv->modifiers());
- processMouseEvent(mouse); break;
- }
-#endif
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- processMouseEvent(static_cast<QMouseEvent*>(ev)); break;
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- processKeyEvent(static_cast<QKeyEvent*>(ev)); break;
- case QEvent::InputMethod:
- processInputMethodEvent(static_cast<QInputMethodEvent*>(ev)); break;
-#ifndef QT_NO_SHORTCUT
- case QEvent::ShortcutOverride:{
- if (isReadOnly())
- return false;
- QKeyEvent* ke = static_cast<QKeyEvent*>(ev);
- if (ke == QKeySequence::Copy
- || ke == QKeySequence::Paste
- || ke == QKeySequence::Cut
- || ke == QKeySequence::Redo
- || ke == QKeySequence::Undo
- || ke == QKeySequence::MoveToNextWord
- || ke == QKeySequence::MoveToPreviousWord
- || ke == QKeySequence::MoveToStartOfDocument
- || ke == QKeySequence::MoveToEndOfDocument
- || ke == QKeySequence::SelectNextWord
- || ke == QKeySequence::SelectPreviousWord
- || ke == QKeySequence::SelectStartOfLine
- || ke == QKeySequence::SelectEndOfLine
- || ke == QKeySequence::SelectStartOfBlock
- || ke == QKeySequence::SelectEndOfBlock
- || ke == QKeySequence::SelectStartOfDocument
- || ke == QKeySequence::SelectAll
- || ke == QKeySequence::SelectEndOfDocument) {
- ke->accept();
- } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier
- || ke->modifiers() == Qt::KeypadModifier) {
- if (ke->key() < Qt::Key_Escape) {
- ke->accept();
- } else {
- switch (ke->key()) {
- case Qt::Key_Delete:
- case Qt::Key_Home:
- case Qt::Key_End:
- case Qt::Key_Backspace:
- case Qt::Key_Left:
- case Qt::Key_Right:
- ke->accept();
- default:
- break;
- }
- }
- }
- }
-#endif
- default:
- return false;
- }
- return true;
-}
-
-void QLineControl::processMouseEvent(QMouseEvent* ev)
-{
-
- switch (ev->type()) {
- case QEvent::GraphicsSceneMousePress:
- case QEvent::MouseButtonPress:{
- if (m_tripleClickTimer
- && (ev->pos() - m_tripleClick).manhattanLength()
- < QApplication::startDragDistance()) {
- selectAll();
- return;
- }
- if (ev->button() == Qt::RightButton)
- return;
-
- bool mark = ev->modifiers() & Qt::ShiftModifier;
- int cursor = xToPos(ev->pos().x());
- moveCursor(cursor, mark);
- break;
- }
- case QEvent::GraphicsSceneMouseDoubleClick:
- case QEvent::MouseButtonDblClick:
- if (ev->button() == Qt::LeftButton) {
- selectWordAtPos(xToPos(ev->pos().x()));
- if (m_tripleClickTimer)
- killTimer(m_tripleClickTimer);
- m_tripleClickTimer = startTimer(QApplication::doubleClickInterval());
- m_tripleClick = ev->pos();
- }
- break;
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::MouseButtonRelease:
-#ifndef QT_NO_CLIPBOARD
- if (QApplication::clipboard()->supportsSelection()) {
- if (ev->button() == Qt::LeftButton) {
- copy(QClipboard::Selection);
- } else if (!isReadOnly() && ev->button() == Qt::MidButton) {
- deselect();
- insert(QApplication::clipboard()->text(QClipboard::Selection));
- }
- }
-#endif
- break;
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::MouseMove:
- if (ev->buttons() & Qt::LeftButton) {
- moveCursor(xToPos(ev->pos().x()), true);
- }
- break;
- default:
- break;
- }
-}
-
-void QLineControl::processKeyEvent(QKeyEvent* event)
-{
- bool inlineCompletionAccepted = false;
-
-#ifndef QT_NO_COMPLETER
- if (m_completer) {
- QCompleter::CompletionMode completionMode = m_completer->completionMode();
- if ((completionMode == QCompleter::PopupCompletion
- || completionMode == QCompleter::UnfilteredPopupCompletion)
- && m_completer->popup()
- && m_completer->popup()->isVisible()) {
- // The following keys are forwarded by the completer to the widget
- // Ignoring the events lets the completer provide suitable default behavior
- switch (event->key()) {
- case Qt::Key_Escape:
- event->ignore();
- return;
- case Qt::Key_Enter:
- case Qt::Key_Return:
- case Qt::Key_F4:
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (!QApplication::keypadNavigationEnabled())
- break;
-#endif
- m_completer->popup()->hide(); // just hide. will end up propagating to parent
- default:
- break; // normal key processing
- }
- } else if (completionMode == QCompleter::InlineCompletion) {
- switch (event->key()) {
- case Qt::Key_Enter:
- case Qt::Key_Return:
- case Qt::Key_F4:
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (!QApplication::keypadNavigationEnabled())
- break;
-#endif
- if (!m_completer->currentCompletion().isEmpty() && hasSelectedText()
- && textAfterSelection().isEmpty()) {
- setText(m_completer->currentCompletion());
- inlineCompletionAccepted = true;
- }
- default:
- break; // normal key processing
- }
- }
- }
-#endif // QT_NO_COMPLETER
-
- if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
- if (hasAcceptableInput() || fixup()) {
- emit accepted();
- emit editingFinished();
- }
- if (inlineCompletionAccepted)
- event->accept();
- else
- event->ignore();
- return;
- }
-
- if (echoMode() == QLineEdit::PasswordEchoOnEdit
- && !passwordEchoEditing()
- && !isReadOnly()
- && !event->text().isEmpty()
-#ifdef QT_KEYPAD_NAVIGATION
- && event->key() != Qt::Key_Select
- && event->key() != Qt::Key_Up
- && event->key() != Qt::Key_Down
- && event->key() != Qt::Key_Back
-#endif
- && !(event->modifiers() & Qt::ControlModifier)) {
- // Clear the edit and reset to normal echo mode while editing; the
- // echo mode switches back when the edit loses focus
- // ### resets current content. dubious code; you can
- // navigate with keys up, down, back, and select(?), but if you press
- // "left" or "right" it clears?
- updatePasswordEchoEditing(true);
- clear();
- }
-
- bool unknown = false;
- bool visual = cursorMoveStyle() == QTextCursor::Visual;
-
- if (false) {
- }
-#ifndef QT_NO_SHORTCUT
- else if (event == QKeySequence::Undo) {
- if (!isReadOnly())
- undo();
- }
- else if (event == QKeySequence::Redo) {
- if (!isReadOnly())
- redo();
- }
- else if (event == QKeySequence::SelectAll) {
- selectAll();
- }
-#ifndef QT_NO_CLIPBOARD
- else if (event == QKeySequence::Copy) {
- copy();
- }
- else if (event == QKeySequence::Paste) {
- if (!isReadOnly()) {
- QClipboard::Mode mode = QClipboard::Clipboard;
-#ifdef Q_WS_X11
- if (event->modifiers() == (Qt::CTRL | Qt::SHIFT) && event->key() == Qt::Key_Insert)
- mode = QClipboard::Selection;
-#endif
- paste(mode);
- }
- }
- else if (event == QKeySequence::Cut) {
- if (!isReadOnly()) {
- copy();
- del();
- }
- }
- else if (event == QKeySequence::DeleteEndOfLine) {
- if (!isReadOnly()) {
- setSelection(cursor(), end());
- copy();
- del();
- }
- }
-#endif //QT_NO_CLIPBOARD
- else if (event == QKeySequence::MoveToStartOfLine || event == QKeySequence::MoveToStartOfBlock) {
- home(0);
- }
- else if (event == QKeySequence::MoveToEndOfLine || event == QKeySequence::MoveToEndOfBlock) {
- end(0);
- }
- else if (event == QKeySequence::SelectStartOfLine || event == QKeySequence::SelectStartOfBlock) {
- home(1);
- }
- else if (event == QKeySequence::SelectEndOfLine || event == QKeySequence::SelectEndOfBlock) {
- end(1);
- }
- else if (event == QKeySequence::MoveToNextChar) {
-#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER)
- if (hasSelectedText()) {
-#else
- if (hasSelectedText() && m_completer
- && m_completer->completionMode() == QCompleter::InlineCompletion) {
-#endif
- moveCursor(selectionEnd(), false);
- } else {
- cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1));
- }
- }
- else if (event == QKeySequence::SelectNextChar) {
- cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1));
- }
- else if (event == QKeySequence::MoveToPreviousChar) {
-#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER)
- if (hasSelectedText()) {
-#else
- if (hasSelectedText() && m_completer
- && m_completer->completionMode() == QCompleter::InlineCompletion) {
-#endif
- moveCursor(selectionStart(), false);
- } else {
- cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1));
- }
- }
- else if (event == QKeySequence::SelectPreviousChar) {
- cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1));
- }
- else if (event == QKeySequence::MoveToNextWord) {
- if (echoMode() == QLineEdit::Normal)
- layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0);
- else
- layoutDirection() == Qt::LeftToRight ? end(0) : home(0);
- }
- else if (event == QKeySequence::MoveToPreviousWord) {
- if (echoMode() == QLineEdit::Normal)
- layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0);
- else if (!isReadOnly()) {
- layoutDirection() == Qt::LeftToRight ? home(0) : end(0);
- }
- }
- else if (event == QKeySequence::SelectNextWord) {
- if (echoMode() == QLineEdit::Normal)
- layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1);
- else
- layoutDirection() == Qt::LeftToRight ? end(1) : home(1);
- }
- else if (event == QKeySequence::SelectPreviousWord) {
- if (echoMode() == QLineEdit::Normal)
- layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1);
- else
- layoutDirection() == Qt::LeftToRight ? home(1) : end(1);
- }
- else if (event == QKeySequence::Delete) {
- if (!isReadOnly())
- del();
- }
- else if (event == QKeySequence::DeleteEndOfWord) {
- if (!isReadOnly()) {
- cursorWordForward(true);
- del();
- }
- }
- else if (event == QKeySequence::DeleteStartOfWord) {
- if (!isReadOnly()) {
- cursorWordBackward(true);
- del();
- }
- }
-#endif // QT_NO_SHORTCUT
- else {
- bool handled = false;
-#ifdef Q_WS_MAC
- if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) {
- Qt::KeyboardModifiers myModifiers = (event->modifiers() & ~Qt::KeypadModifier);
- if (myModifiers & Qt::ShiftModifier) {
- if (myModifiers == (Qt::ControlModifier|Qt::ShiftModifier)
- || myModifiers == (Qt::AltModifier|Qt::ShiftModifier)
- || myModifiers == Qt::ShiftModifier) {
-
- event->key() == Qt::Key_Up ? home(1) : end(1);
- }
- } else {
- if ((myModifiers == Qt::ControlModifier
- || myModifiers == Qt::AltModifier
- || myModifiers == Qt::NoModifier)) {
- event->key() == Qt::Key_Up ? home(0) : end(0);
- }
- }
- handled = true;
- }
-#endif
- if (event->modifiers() & Qt::ControlModifier) {
- switch (event->key()) {
- case Qt::Key_Backspace:
- if (!isReadOnly()) {
- cursorWordBackward(true);
- del();
- }
- break;
-#ifndef QT_NO_COMPLETER
- case Qt::Key_Up:
- case Qt::Key_Down:
- complete(event->key());
- break;
-#endif
-#if defined(Q_WS_X11)
- case Qt::Key_E:
- end(0);
- break;
-
- case Qt::Key_U:
- if (!isReadOnly()) {
- setSelection(0, text().size());
-#ifndef QT_NO_CLIPBOARD
- copy();
-#endif
- del();
- }
- break;
-#endif
- default:
- if (!handled)
- unknown = true;
- }
- } else { // ### check for *no* modifier
- switch (event->key()) {
- case Qt::Key_Backspace:
- if (!isReadOnly()) {
- backspace();
-#ifndef QT_NO_COMPLETER
- complete(Qt::Key_Backspace);
-#endif
- }
- break;
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && !event->isAutoRepeat()
- && !isReadOnly()) {
- if (text().length() == 0) {
- setText(m_cancelText);
-
- if (passwordEchoEditing())
- updatePasswordEchoEditing(false);
-
- emit editFocusChange(false);
- } else if (!m_deleteAllTimer) {
- m_deleteAllTimer = startTimer(750);
- }
- } else {
- unknown = true;
- }
- break;
-#endif
- default:
- if (!handled)
- unknown = true;
- }
- }
- }
-
- if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) {
- setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft);
- unknown = false;
- }
-
- if (unknown && !isReadOnly()) {
- QString t = event->text();
- if (!t.isEmpty() && t.at(0).isPrint()) {
- insert(t);
-#ifndef QT_NO_COMPLETER
- complete(event->key());
-#endif
- event->accept();
- return;
- }
- }
-
- if (unknown)
- event->ignore();
- else
- event->accept();
-}
-
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/to_be_moved/qlinecontrol_p.h b/src/gui/to_be_moved/qlinecontrol_p.h
deleted file mode 100644
index 0042f17261..0000000000
--- a/src/gui/to_be_moved/qlinecontrol_p.h
+++ /dev/null
@@ -1,456 +0,0 @@
-/****************************************************************************
-**
-** 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 QLINECONTROL_P_H
-#define QLINECONTROL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qglobal.h"
-
-#ifndef QT_NO_LINEEDIT
-#include "private/qwidget_p.h"
-#include "QtGui/qlineedit.h"
-#include "QtGui/qtextlayout.h"
-#include "QtGui/qstyleoption.h"
-#include "QtCore/qpointer.h"
-#include "QtGui/qlineedit.h"
-#include "QtGui/qclipboard.h"
-#include "QtCore/qpoint.h"
-#include "QtGui/qcompleter.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QLineControl : public QObject
-{
- Q_OBJECT
-
-public:
- QLineControl(const QString &txt = QString())
- : m_cursor(0), m_preeditCursor(0), m_cursorWidth(0), m_layoutDirection(Qt::LayoutDirectionAuto),
- m_hideCursor(false), m_separator(0), m_readOnly(0),
- m_dragEnabled(0), m_echoMode(0), m_textDirty(0), m_selDirty(0),
- m_validInput(1), m_blinkStatus(0), m_blinkPeriod(0), m_blinkTimer(0), m_deleteAllTimer(0),
- m_ascent(0), m_maxLength(32767), m_lastCursorPos(-1),
- m_tripleClickTimer(0), m_maskData(0), m_modifiedState(0), m_undoState(0),
- m_selstart(0), m_selend(0), m_passwordEchoEditing(false)
- {
- init(txt);
- }
-
- ~QLineControl()
- {
- delete [] m_maskData;
- }
-
- int nextMaskBlank(int pos)
- {
- int c = findInMask(pos, true, false);
- m_separator |= (c != pos);
- return (c != -1 ? c : m_maxLength);
- }
-
- int prevMaskBlank(int pos)
- {
- int c = findInMask(pos, false, false);
- m_separator |= (c != pos);
- return (c != -1 ? c : 0);
- }
-
- bool isUndoAvailable() const { return !m_readOnly && m_undoState; }
- bool isRedoAvailable() const { return !m_readOnly && m_undoState < (int)m_history.size(); }
- void clearUndo() { m_history.clear(); m_modifiedState = m_undoState = 0; }
-
- bool isModified() const { return m_modifiedState != m_undoState; }
- void setModified(bool modified) { m_modifiedState = modified ? -1 : m_undoState; }
-
- bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.length(); }
- bool hasSelectedText() const { return !m_text.isEmpty() && m_selend > m_selstart; }
-
- int width() const { return qRound(m_textLayout.lineAt(0).width()) + 1; }
- int height() const { return qRound(m_textLayout.lineAt(0).height()) + 1; }
- int ascent() const { return m_ascent; }
- qreal naturalTextWidth() const { return m_textLayout.lineAt(0).naturalTextWidth(); }
-
- void setSelection(int start, int length);
-
- inline QString selectedText() const { return hasSelectedText() ? m_text.mid(m_selstart, m_selend - m_selstart) : QString(); }
- QString textBeforeSelection() const { return hasSelectedText() ? m_text.left(m_selstart) : QString(); }
- QString textAfterSelection() const { return hasSelectedText() ? m_text.mid(m_selend) : QString(); }
-
- int selectionStart() const { return hasSelectedText() ? m_selstart : -1; }
- int selectionEnd() const { return hasSelectedText() ? m_selend : -1; }
- bool inSelection(int x) const
- {
- if (m_selstart >= m_selend)
- return false;
- int pos = xToPos(x, QTextLine::CursorOnCharacter);
- return pos >= m_selstart && pos < m_selend;
- }
-
- void removeSelection()
- {
- int priorState = m_undoState;
- removeSelectedText();
- finishChange(priorState);
- }
-
- int start() const { return 0; }
- int end() const { return m_text.length(); }
-
-#ifndef QT_NO_CLIPBOARD
- void copy(QClipboard::Mode mode = QClipboard::Clipboard) const;
- void paste(QClipboard::Mode mode = QClipboard::Clipboard);
-#endif
-
- int cursor() const{ return m_cursor; }
- int preeditCursor() const { return m_preeditCursor; }
-
- int cursorWidth() const { return m_cursorWidth; }
- void setCursorWidth(int value) { m_cursorWidth = value; }
-
- QTextCursor::MoveStyle cursorMoveStyle() const { return m_textLayout.cursorMoveStyle(); }
- void setCursorMoveStyle(QTextCursor::MoveStyle style) { m_textLayout.setCursorMoveStyle(style); }
-
- void moveCursor(int pos, bool mark = false);
- void cursorForward(bool mark, int steps)
- {
- int c = m_cursor;
- if (steps > 0) {
- while (steps--)
- c = cursorMoveStyle() == QTextCursor::Visual ? m_textLayout.rightCursorPosition(c)
- : m_textLayout.nextCursorPosition(c);
- } else if (steps < 0) {
- while (steps++)
- c = cursorMoveStyle() == QTextCursor::Visual ? m_textLayout.leftCursorPosition(c)
- : m_textLayout.previousCursorPosition(c);
- }
- moveCursor(c, mark);
- }
-
- void cursorWordForward(bool mark) { moveCursor(m_textLayout.nextCursorPosition(m_cursor, QTextLayout::SkipWords), mark); }
- void cursorWordBackward(bool mark) { moveCursor(m_textLayout.previousCursorPosition(m_cursor, QTextLayout::SkipWords), mark); }
-
- void home(bool mark) { moveCursor(0, mark); }
- void end(bool mark) { moveCursor(text().length(), mark); }
-
- int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const;
- QRect cursorRect() const;
-
- qreal cursorToX(int cursor) const { return m_textLayout.lineAt(0).cursorToX(cursor); }
- qreal cursorToX() const
- {
- int cursor = m_cursor;
- if (m_preeditCursor != -1)
- cursor += m_preeditCursor;
- return cursorToX(cursor);
- }
-
- bool isReadOnly() const { return m_readOnly; }
- void setReadOnly(bool enable) { m_readOnly = enable; }
-
- QString text() const
- {
- QString res = m_maskData ? stripString(m_text) : m_text;
- return (res.isNull() ? QString::fromLatin1("") : res);
- }
- void setText(const QString &txt) { internalSetText(txt, -1, false); }
- QString displayText() const { return m_textLayout.text(); }
-
- void backspace();
- void del();
- void deselect() { internalDeselect(); finishChange(); }
- void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.length(), true); }
-
- void insert(const QString &);
- void clear();
- void undo() { internalUndo(); finishChange(-1, true); }
- void redo() { internalRedo(); finishChange(); }
- void selectWordAtPos(int);
-
- uint echoMode() const { return m_echoMode; }
- void setEchoMode(uint mode)
- {
- m_echoMode = mode;
- m_passwordEchoEditing = false;
- updateDisplayText();
- }
-
- int maxLength() const { return m_maxLength; }
- void setMaxLength(int maxLength)
- {
- if (m_maskData)
- return;
- m_maxLength = maxLength;
- setText(m_text);
- }
-
-#ifndef QT_NO_VALIDATOR
- const QValidator *validator() const { return m_validator; }
- void setValidator(const QValidator *v) { m_validator = const_cast<QValidator*>(v); }
-#endif
-
-#ifndef QT_NO_COMPLETER
- QCompleter *completer() const { return m_completer; }
- /* Note that you must set the widget for the completer separately */
- void setCompleter(const QCompleter *c) { m_completer = const_cast<QCompleter*>(c); }
- void complete(int key);
-#endif
-
- int cursorPosition() const { return m_cursor; }
- void setCursorPosition(int pos) { if (pos <= m_text.length()) moveCursor(qMax(0, pos)); }
-
- bool hasAcceptableInput() const { return hasAcceptableInput(m_text); }
- bool fixup();
-
- QString inputMask() const { return m_maskData ? m_inputMask + QLatin1Char(';') + m_blank : QString(); }
- void setInputMask(const QString &mask)
- {
- parseInputMask(mask);
- if (m_maskData)
- moveCursor(nextMaskBlank(0));
- }
-
- // input methods
-#ifndef QT_NO_IM
- bool composeMode() const { return !m_textLayout.preeditAreaText().isEmpty(); }
- void setPreeditArea(int cursor, const QString &text) { m_textLayout.setPreeditArea(cursor, text); }
-#endif
-
- QString preeditAreaText() const { return m_textLayout.preeditAreaText(); }
-
- void updatePasswordEchoEditing(bool editing);
- bool passwordEchoEditing() const { return m_passwordEchoEditing; }
-
- QChar passwordCharacter() const { return m_passwordCharacter; }
- void setPasswordCharacter(const QChar &character) { m_passwordCharacter = character; updateDisplayText(); }
-
- Qt::LayoutDirection layoutDirection() const {
- if (m_layoutDirection == Qt::LayoutDirectionAuto) {
- if (m_text.isEmpty())
- return QApplication::keyboardInputDirection();
- return m_text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
- }
- return m_layoutDirection;
- }
- void setLayoutDirection(Qt::LayoutDirection direction)
- {
- if (direction != m_layoutDirection) {
- m_layoutDirection = direction;
- updateDisplayText();
- }
- }
-
- void setFont(const QFont &font) { m_textLayout.setFont(font); updateDisplayText(); }
-
- void processInputMethodEvent(QInputMethodEvent *event);
- void processMouseEvent(QMouseEvent* ev);
- void processKeyEvent(QKeyEvent* ev);
-
- int cursorBlinkPeriod() const { return m_blinkPeriod; }
- void setCursorBlinkPeriod(int msec);
- void resetCursorBlinkTimer();
-
- QString cancelText() const { return m_cancelText; }
- void setCancelText(const QString &text) { m_cancelText = text; }
-
- const QPalette &palette() const { return m_palette; }
- void setPalette(const QPalette &p) { m_palette = p; }
-
- enum DrawFlags {
- DrawText = 0x01,
- DrawSelections = 0x02,
- DrawCursor = 0x04,
- DrawAll = DrawText | DrawSelections | DrawCursor
- };
- void draw(QPainter *, const QPoint &, const QRect &, int flags = DrawAll);
-
- bool processEvent(QEvent *ev);
-
-private:
- void init(const QString &txt);
- void removeSelectedText();
- void internalSetText(const QString &txt, int pos = -1, bool edited = true);
- void updateDisplayText(bool forceUpdate = false);
-
- void internalInsert(const QString &s);
- void internalDelete(bool wasBackspace = false);
- void internalRemove(int pos);
-
- inline void internalDeselect()
- {
- m_selDirty |= (m_selend > m_selstart);
- m_selstart = m_selend = 0;
- }
-
- void internalUndo(int until = -1);
- void internalRedo();
-
- QString m_text;
- QPalette m_palette;
- int m_cursor;
- int m_preeditCursor;
- int m_cursorWidth;
- Qt::LayoutDirection m_layoutDirection;
- uint m_hideCursor : 1; // used to hide the m_cursor inside preedit areas
- uint m_separator : 1;
- uint m_readOnly : 1;
- uint m_dragEnabled : 1;
- uint m_echoMode : 2;
- uint m_textDirty : 1;
- uint m_selDirty : 1;
- uint m_validInput : 1;
- uint m_blinkStatus : 1;
- int m_blinkPeriod; // 0 for non-blinking cursor
- int m_blinkTimer;
- int m_deleteAllTimer;
- int m_ascent;
- int m_maxLength;
- int m_lastCursorPos;
- QList<int> m_transactions;
- QPoint m_tripleClick;
- int m_tripleClickTimer;
- QString m_cancelText;
-
- void emitCursorPositionChanged();
-
- bool finishChange(int validateFromState = -1, bool update = false, bool edited = true);
-
-#ifndef QT_NO_VALIDATOR
- QPointer<QValidator> m_validator;
-#endif
- QPointer<QCompleter> m_completer;
-#ifndef QT_NO_COMPLETER
- bool advanceToEnabledItem(int dir);
-#endif
-
- struct MaskInputData {
- enum Casemode { NoCaseMode, Upper, Lower };
- QChar maskChar; // either the separator char or the inputmask
- bool separator;
- Casemode caseMode;
- };
- QString m_inputMask;
- QChar m_blank;
- MaskInputData *m_maskData;
-
- // undo/redo handling
- enum CommandType { Separator, Insert, Remove, Delete, RemoveSelection, DeleteSelection, SetSelection };
- struct Command {
- inline Command() {}
- inline Command(CommandType t, int p, QChar c, int ss, int se) : type(t),uc(c),pos(p),selStart(ss),selEnd(se) {}
- uint type : 4;
- QChar uc;
- int pos, selStart, selEnd;
- };
- int m_modifiedState;
- int m_undoState;
- QVector<Command> m_history;
- void addCommand(const Command& cmd);
-
- inline void separate() { m_separator = true; }
-
- // selection
- int m_selstart;
- int m_selend;
-
- // masking
- void parseInputMask(const QString &maskFields);
- bool isValidInput(QChar key, QChar mask) const;
- bool hasAcceptableInput(const QString &text) const;
- QString maskString(uint pos, const QString &str, bool clear = false) const;
- QString clearString(uint pos, uint len) const;
- QString stripString(const QString &str) const;
- int findInMask(int pos, bool forward, bool findSeparator, QChar searchChar = QChar()) const;
-
- // complex text layout
- QTextLayout m_textLayout;
-
- bool m_passwordEchoEditing;
- QChar m_passwordCharacter;
-
-Q_SIGNALS:
- void cursorPositionChanged(int, int);
- void selectionChanged();
-
- void displayTextChanged(const QString &);
- void textChanged(const QString &);
- void textEdited(const QString &);
-
- void resetInputContext();
- void updateMicroFocus();
-
- void accepted();
- void editingFinished();
- void updateNeeded(const QRect &);
-
-#ifdef QT_KEYPAD_NAVIGATION
- void editFocusChange(bool);
-#endif
-protected:
- virtual void timerEvent(QTimerEvent *event);
-
-private Q_SLOTS:
- void _q_clipboardChanged();
- void _q_deleteSelected();
-
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_LINEEDIT
-
-#endif // QLINECONTROL_P_H
diff --git a/src/gui/to_be_moved/qshortcut.cpp b/src/gui/to_be_moved/qshortcut.cpp
deleted file mode 100644
index 978ef0c240..0000000000
--- a/src/gui/to_be_moved/qshortcut.cpp
+++ /dev/null
@@ -1,407 +0,0 @@
-/****************************************************************************
-**
-** 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 "qshortcut.h"
-#include "private/qwidget_p.h"
-
-#ifndef QT_NO_SHORTCUT
-#include <qevent.h>
-#include <qwhatsthis.h>
-#include <qmenu.h>
-#include <qapplication.h>
-#include <private/qapplication_p.h>
-#include <private/qshortcutmap_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#define QAPP_CHECK(functionName) \
- if (!qApp) { \
- qWarning("QShortcut: Initialize QApplication before calling '" functionName "'."); \
- return; \
- }
-
-/*!
- \class QShortcut
- \brief The QShortcut class is used to create keyboard shortcuts.
-
- \ingroup events
-
-
- The QShortcut class provides a way of connecting keyboard
- shortcuts to Qt's \l{signals and slots} mechanism, so that
- objects can be informed when a shortcut is executed. The shortcut
- can be set up to contain all the key presses necessary to
- describe a keyboard shortcut, including the states of modifier
- keys such as \gui Shift, \gui Ctrl, and \gui Alt.
-
- \target mnemonic
-
- On certain widgets, using '&' in front of a character will
- automatically create a mnemonic (a shortcut) for that character,
- e.g. "E&xit" will create the shortcut \gui Alt+X (use '&&' to
- display an actual ampersand). The widget might consume and perform
- an action on a given shortcut. On X11 the ampersand will not be
- shown and the character will be underlined. On Windows, shortcuts
- are normally not displayed until the user presses the \gui Alt
- key, but this is a setting the user can change. On Mac, shortcuts
- are disabled by default. Call qt_set_sequence_auto_mnemonic() to
- enable them. However, because mnemonic shortcuts do not fit in
- with Aqua's guidelines, Qt will not show the shortcut character
- underlined.
-
- For applications that use menus, it may be more convenient to
- use the convenience functions provided in the QMenu class to
- assign keyboard shortcuts to menu items as they are created.
- Alternatively, shortcuts may be associated with other types of
- actions in the QAction class.
-
- The simplest way to create a shortcut for a particular widget is
- to construct the shortcut with a key sequence. For example:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qshortcut.cpp 0
-
- When the user types the \l{QKeySequence}{key sequence}
- for a given shortcut, the shortcut's activated() signal is
- emitted. (In the case of ambiguity, the activatedAmbiguously()
- signal is emitted.) A shortcut is "listened for" by Qt's event
- loop when the shortcut's parent widget is receiving events.
-
- A shortcut's key sequence can be set with setKey() and retrieved
- with key(). A shortcut can be enabled or disabled with
- setEnabled(), and can have "What's This?" help text set with
- setWhatsThis().
-
- \sa QShortcutEvent, QKeySequence, QAction
-*/
-
-/*!
- \fn QWidget *QShortcut::parentWidget() const
-
- Returns the shortcut's parent widget.
-*/
-
-/*!
- \fn void QShortcut::activated()
-
- This signal is emitted when the user types the shortcut's key
- sequence.
-
- \sa activatedAmbiguously()
-*/
-
-/*!
- \fn void QShortcut::activatedAmbiguously()
-
- When a key sequence is being typed at the keyboard, it is said to
- be ambiguous as long as it matches the start of more than one
- shortcut.
-
- When a shortcut's key sequence is completed,
- activatedAmbiguously() is emitted if the key sequence is still
- ambiguous (i.e., it is the start of one or more other shortcuts).
- The activated() signal is not emitted in this case.
-
- \sa activated()
-*/
-
-/*
- \internal
- Private data accessed through d-pointer.
-*/
-class QShortcutPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QShortcut)
-public:
- QShortcutPrivate() : sc_context(Qt::WindowShortcut), sc_enabled(true), sc_autorepeat(true), sc_id(0) {}
- QKeySequence sc_sequence;
- Qt::ShortcutContext sc_context;
- bool sc_enabled;
- bool sc_autorepeat;
- int sc_id;
- QString sc_whatsthis;
- void redoGrab(QShortcutMap &map);
-};
-
-void QShortcutPrivate::redoGrab(QShortcutMap &map)
-{
- Q_Q(QShortcut);
- if (!parent) {
- qWarning("QShortcut: No widget parent defined");
- return;
- }
-
- if (sc_id)
- map.removeShortcut(sc_id, q);
- if (sc_sequence.isEmpty())
- return;
- sc_id = map.addShortcut(q, sc_sequence, sc_context);
- if (!sc_enabled)
- map.setShortcutEnabled(false, sc_id, q);
- if (!sc_autorepeat)
- map.setShortcutAutoRepeat(false, sc_id, q);
-}
-
-/*!
- Constructs a QShortcut object for the \a parent widget. Since no
- shortcut key sequence is specified, the shortcut will not emit any
- signals.
-
- \sa setKey()
-*/
-QShortcut::QShortcut(QWidget *parent)
- : QObject(*new QShortcutPrivate, parent)
-{
- Q_ASSERT(parent != 0);
-}
-
-/*!
- Constructs a QShortcut object for the \a parent widget. The shortcut
- operates on its parent, listening for \l{QShortcutEvent}s that
- match the \a key sequence. Depending on the ambiguity of the
- event, the shortcut will call the \a member function, or the \a
- ambiguousMember function, if the key press was in the shortcut's
- \a context.
-*/
-QShortcut::QShortcut(const QKeySequence &key, QWidget *parent,
- const char *member, const char *ambiguousMember,
- Qt::ShortcutContext context)
- : QObject(*new QShortcutPrivate, parent)
-{
- QAPP_CHECK("QShortcut");
-
- Q_D(QShortcut);
- Q_ASSERT(parent != 0);
- d->sc_context = context;
- d->sc_sequence = key;
- d->redoGrab(qApp->d_func()->shortcutMap);
- if (member)
- connect(this, SIGNAL(activated()), parent, member);
- if (ambiguousMember)
- connect(this, SIGNAL(activatedAmbiguously()), parent, ambiguousMember);
-}
-
-/*!
- Destroys the shortcut.
-*/
-QShortcut::~QShortcut()
-{
- Q_D(QShortcut);
- if (qApp)
- qApp->d_func()->shortcutMap.removeShortcut(d->sc_id, this);
-}
-
-/*!
- \property QShortcut::key
- \brief the shortcut's key sequence
-
- This is a key sequence with an optional combination of Shift, Ctrl,
- and Alt. The key sequence may be supplied in a number of ways:
-
- \snippet doc/src/snippets/code/src_gui_kernel_qshortcut.cpp 1
-
- By default, this property contains an empty key sequence.
-*/
-void QShortcut::setKey(const QKeySequence &key)
-{
- Q_D(QShortcut);
- if (d->sc_sequence == key)
- return;
- QAPP_CHECK("setKey");
- d->sc_sequence = key;
- d->redoGrab(qApp->d_func()->shortcutMap);
-}
-
-QKeySequence QShortcut::key() const
-{
- Q_D(const QShortcut);
- return d->sc_sequence;
-}
-
-/*!
- \property QShortcut::enabled
- \brief whether the shortcut is enabled
-
- An enabled shortcut emits the activated() or activatedAmbiguously()
- signal when a QShortcutEvent occurs that matches the shortcut's
- key() sequence.
-
- If the application is in \c WhatsThis mode the shortcut will not emit
- the signals, but will show the "What's This?" text instead.
-
- By default, this property is true.
-
- \sa whatsThis
-*/
-void QShortcut::setEnabled(bool enable)
-{
- Q_D(QShortcut);
- if (d->sc_enabled == enable)
- return;
- QAPP_CHECK("setEnabled");
- d->sc_enabled = enable;
- qApp->d_func()->shortcutMap.setShortcutEnabled(enable, d->sc_id, this);
-}
-
-bool QShortcut::isEnabled() const
-{
- Q_D(const QShortcut);
- return d->sc_enabled;
-}
-
-/*!
- \property QShortcut::context
- \brief the context in which the shortcut is valid
-
- A shortcut's context decides in which circumstances a shortcut is
- allowed to be triggered. The normal context is Qt::WindowShortcut,
- which allows the shortcut to trigger if the parent (the widget
- containing the shortcut) is a subwidget of the active top-level
- window.
-
- By default, this property is set to Qt::WindowShortcut.
-*/
-void QShortcut::setContext(Qt::ShortcutContext context)
-{
- Q_D(QShortcut);
- if(d->sc_context == context)
- return;
- QAPP_CHECK("setContext");
- d->sc_context = context;
- d->redoGrab(qApp->d_func()->shortcutMap);
-}
-
-Qt::ShortcutContext QShortcut::context()
-{
- Q_D(QShortcut);
- return d->sc_context;
-}
-
-/*!
- \property QShortcut::whatsThis
- \brief the shortcut's "What's This?" help text
-
- The text will be shown when the application is in "What's
- This?" mode and the user types the shortcut key() sequence.
-
- To set "What's This?" help on a menu item (with or without a
- shortcut key), set the help on the item's action.
-
- By default, this property contains an empty string.
-
- \sa QWhatsThis::inWhatsThisMode(), QAction::setWhatsThis()
-*/
-void QShortcut::setWhatsThis(const QString &text)
-{
- Q_D(QShortcut);
- d->sc_whatsthis = text;
-}
-
-QString QShortcut::whatsThis() const
-{
- Q_D(const QShortcut);
- return d->sc_whatsthis;
-}
-
-/*!
- \property QShortcut::autoRepeat
- \brief whether the shortcut can auto repeat
- \since 4.2
-
- If true, the shortcut 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 QShortcut::setAutoRepeat(bool on)
-{
- Q_D(QShortcut);
- if (d->sc_autorepeat == on)
- return;
- QAPP_CHECK("setAutoRepeat");
- d->sc_autorepeat = on;
- qApp->d_func()->shortcutMap.setShortcutAutoRepeat(on, d->sc_id, this);
-}
-
-bool QShortcut::autoRepeat() const
-{
- Q_D(const QShortcut);
- return d->sc_autorepeat;
-}
-
-/*!
- Returns the shortcut's ID.
-
- \sa QShortcutEvent::shortcutId()
-*/
-int QShortcut::id() const
-{
- Q_D(const QShortcut);
- return d->sc_id;
-}
-
-/*!
- \internal
-*/
-bool QShortcut::event(QEvent *e)
-{
- Q_D(QShortcut);
- bool handled = false;
- if (d->sc_enabled && e->type() == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- if (se->shortcutId() == d->sc_id && se->key() == d->sc_sequence){
-#ifndef QT_NO_WHATSTHIS
- if (QWhatsThis::inWhatsThisMode()) {
- QWhatsThis::showText(QCursor::pos(), d->sc_whatsthis);
- handled = true;
- } else
-#endif
- if (se->isAmbiguous())
- emit activatedAmbiguously();
- else
- emit activated();
- handled = true;
- }
- }
- return handled;
-}
-#endif // QT_NO_SHORTCUT
-
-QT_END_NAMESPACE
diff --git a/src/gui/to_be_moved/qshortcut.h b/src/gui/to_be_moved/qshortcut.h
deleted file mode 100644
index f432d9ad97..0000000000
--- a/src/gui/to_be_moved/qshortcut.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** 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 QSHORTCUT_H
-#define QSHORTCUT_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qkeysequence.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SHORTCUT
-
-class QShortcutPrivate;
-class Q_GUI_EXPORT QShortcut : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QShortcut)
- Q_PROPERTY(QKeySequence key READ key WRITE setKey)
- Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis)
- Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
- Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat)
- Q_PROPERTY(Qt::ShortcutContext context READ context WRITE setContext)
-public:
- explicit QShortcut(QWidget *parent);
- QShortcut(const QKeySequence& key, QWidget *parent,
- const char *member = 0, const char *ambiguousMember = 0,
- Qt::ShortcutContext context = Qt::WindowShortcut);
- ~QShortcut();
-
- void setKey(const QKeySequence& key);
- QKeySequence key() const;
-
- void setEnabled(bool enable);
- bool isEnabled() const;
-
- void setContext(Qt::ShortcutContext context);
- Qt::ShortcutContext context();
-
- void setWhatsThis(const QString &text);
- QString whatsThis() const;
-
- void setAutoRepeat(bool on);
- bool autoRepeat() const;
-
- int id() const;
-
- inline QWidget *parentWidget() const
- { return static_cast<QWidget *>(QObject::parent()); }
-
-Q_SIGNALS:
- void activated();
- void activatedAmbiguously();
-
-protected:
- bool event(QEvent *e);
-};
-
-#endif // QT_NO_SHORTCUT
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSHORTCUT_H
diff --git a/src/gui/to_be_moved/qshortcutmap.cpp b/src/gui/to_be_moved/qshortcutmap.cpp
deleted file mode 100644
index d6baa1331e..0000000000
--- a/src/gui/to_be_moved/qshortcutmap.cpp
+++ /dev/null
@@ -1,897 +0,0 @@
-/****************************************************************************
-**
-** 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 "qshortcutmap_p.h"
-#include "private/qobject_p.h"
-#include "qkeysequence.h"
-#include "qgraphicsscene.h"
-#include "qgraphicsview.h"
-#include "qdebug.h"
-#include "qevent.h"
-#include "qwidget.h"
-#include "qapplication.h"
-#include "qvector.h"
-#include "qmenu.h"
-#include "qmenubar.h"
-#include "qshortcut.h"
-#include "private/qapplication_p.h"
-#include <private/qaction_p.h>
-#include <private/qkeymapper_p.h>
-#include <private/qwidget_p.h>
-
-#ifndef QT_NO_SHORTCUT
-
-QT_BEGIN_NAMESPACE
-
-// To enable verbose output uncomment below
-//#define DEBUG_QSHORTCUTMAP
-
-/* \internal
- Entry data for QShortcutMap
- Contains:
- Keysequence for entry
- Pointer to parent owning the sequence
-*/
-struct QShortcutEntry
-{
- QShortcutEntry()
- : keyseq(0), context(Qt::WindowShortcut), enabled(false), autorepeat(1), id(0), owner(0)
- {}
-
- QShortcutEntry(const QKeySequence &k)
- : keyseq(k), context(Qt::WindowShortcut), enabled(false), autorepeat(1), id(0), owner(0)
- {}
-
- QShortcutEntry(QObject *o, const QKeySequence &k, Qt::ShortcutContext c, int i)
- : keyseq(k), context(c), enabled(true), autorepeat(1), id(i), owner(o)
- {}
-
- QShortcutEntry(QObject *o, const QKeySequence &k, Qt::ShortcutContext c, int i, bool a)
- : keyseq(k), context(c), enabled(true), autorepeat(a), id(i), owner(o)
- {}
-
- bool operator<(const QShortcutEntry &f) const
- { return keyseq < f.keyseq; }
-
- QKeySequence keyseq;
- Qt::ShortcutContext context;
- bool enabled : 1;
- bool autorepeat : 1;
- signed int id;
- QObject *owner;
-};
-
-#if 0 //ndef QT_NO_DEBUG_STREAM
-/*! \internal
- QDebug operator<< for easy debug output of the shortcut entries.
-*/
-static QDebug &operator<<(QDebug &dbg, const QShortcutEntry *se) {
- if (!se)
- return dbg << "QShortcutEntry(0x0)";
- dbg.nospace()
- << "QShortcutEntry(" << se->keyseq
- << "), id(" << se->id << "), enabled(" << se->enabled << "), autorepeat(" << se->autorepeat
- << "), owner(" << se->owner << ')';
- return dbg.space();
-}
-#endif // QT_NO_DEBUGSTREAM
-
-/* \internal
- Private data for QShortcutMap
-*/
-class QShortcutMapPrivate
-{
- Q_DECLARE_PUBLIC(QShortcutMap)
-
-public:
- QShortcutMapPrivate(QShortcutMap* parent)
- : q_ptr(parent), currentId(0), ambigCount(0), currentState(QKeySequence::NoMatch)
- {
- identicals.reserve(10);
- currentSequences.reserve(10);
- }
- QShortcutMap *q_ptr; // Private's parent
-
- QList<QShortcutEntry> sequences; // All sequences!
-
- int currentId; // Global shortcut ID number
- int ambigCount; // Index of last enabled ambiguous dispatch
- QKeySequence::SequenceMatch currentState;
- QVector<QKeySequence> currentSequences; // Sequence for the current state
- QVector<QKeySequence> newEntries;
- QKeySequence prevSequence; // Sequence for the previous identical match
- QVector<const QShortcutEntry*> identicals; // Last identical matches
-};
-
-
-/*! \internal
- QShortcutMap constructor.
-*/
-QShortcutMap::QShortcutMap()
- : d_ptr(new QShortcutMapPrivate(this))
-{
- resetState();
-}
-
-/*! \internal
- QShortcutMap destructor.
-*/
-QShortcutMap::~QShortcutMap()
-{
-}
-
-/*! \internal
- Adds a shortcut to the global map.
- Returns the id of the newly added shortcut.
-*/
-int QShortcutMap::addShortcut(QObject *owner, const QKeySequence &key, Qt::ShortcutContext context)
-{
- Q_ASSERT_X(owner, "QShortcutMap::addShortcut", "All shortcuts need an owner");
- Q_ASSERT_X(!key.isEmpty(), "QShortcutMap::addShortcut", "Cannot add keyless shortcuts to map");
- Q_D(QShortcutMap);
-
- QShortcutEntry newEntry(owner, key, context, --(d->currentId), true);
- QList<QShortcutEntry>::iterator it = qUpperBound(d->sequences.begin(), d->sequences.end(), newEntry);
- d->sequences.insert(it, newEntry); // Insert sorted
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace()
- << "QShortcutMap::addShortcut(" << owner << ", "
- << key << ", " << context << ") = " << d->currentId;
-#endif
- return d->currentId;
-}
-
-/*! \internal
- Removes a shortcut from the global map.
- If \a owner is 0, all entries in the map with the key sequence specified
- is removed. If \a key is null, all sequences for \a owner is removed from
- the map. If \a id is 0, any identical \a key sequences owned by \a owner
- are removed.
- Returns the number of sequences removed from the map.
-*/
-
-int QShortcutMap::removeShortcut(int id, QObject *owner, const QKeySequence &key)
-{
- Q_D(QShortcutMap);
- int itemsRemoved = 0;
- bool allOwners = (owner == 0);
- bool allKeys = key.isEmpty();
- bool allIds = id == 0;
-
- // Special case, remove everything
- if (allOwners && allKeys && id == 0) {
- itemsRemoved = d->sequences.size();
- d->sequences.clear();
- return itemsRemoved;
- }
-
- int i = d->sequences.size()-1;
- while (i>=0)
- {
- const QShortcutEntry &entry = d->sequences.at(i);
- int entryId = entry.id;
- if ((allOwners || entry.owner == owner)
- && (allIds || entry.id == id)
- && (allKeys || entry.keyseq == key)) {
- d->sequences.removeAt(i);
- ++itemsRemoved;
- }
- if (id == entryId)
- return itemsRemoved;
- --i;
- }
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace()
- << "QShortcutMap::removeShortcut(" << id << ", " << owner << ", "
- << key << ") = " << itemsRemoved;
-#endif
- return itemsRemoved;
-}
-
-/*! \internal
- Changes the enable state of a shortcut to \a enable.
- If \a owner is 0, all entries in the map with the key sequence specified
- is removed. If \a key is null, all sequences for \a owner is removed from
- the map. If \a id is 0, any identical \a key sequences owned by \a owner
- are changed.
- Returns the number of sequences which are matched in the map.
-*/
-int QShortcutMap::setShortcutEnabled(bool enable, int id, QObject *owner, const QKeySequence &key)
-{
- Q_D(QShortcutMap);
- int itemsChanged = 0;
- bool allOwners = (owner == 0);
- bool allKeys = key.isEmpty();
- bool allIds = id == 0;
-
- int i = d->sequences.size()-1;
- while (i>=0)
- {
- QShortcutEntry entry = d->sequences.at(i);
- if ((allOwners || entry.owner == owner)
- && (allIds || entry.id == id)
- && (allKeys || entry.keyseq == key)) {
- d->sequences[i].enabled = enable;
- ++itemsChanged;
- }
- if (id == entry.id)
- return itemsChanged;
- --i;
- }
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace()
- << "QShortcutMap::setShortcutEnabled(" << enable << ", " << id << ", "
- << owner << ", " << key << ") = " << itemsChanged;
-#endif
- return itemsChanged;
-}
-
-/*! \internal
- Changes the auto repeat state of a shortcut to \a enable.
- If \a owner is 0, all entries in the map with the key sequence specified
- is removed. If \a key is null, all sequences for \a owner is removed from
- the map. If \a id is 0, any identical \a key sequences owned by \a owner
- are changed.
- Returns the number of sequences which are matched in the map.
-*/
-int QShortcutMap::setShortcutAutoRepeat(bool on, int id, QObject *owner, const QKeySequence &key)
-{
- Q_D(QShortcutMap);
- int itemsChanged = 0;
- bool allOwners = (owner == 0);
- bool allKeys = key.isEmpty();
- bool allIds = id == 0;
-
- int i = d->sequences.size()-1;
- while (i>=0)
- {
- QShortcutEntry entry = d->sequences.at(i);
- if ((allOwners || entry.owner == owner)
- && (allIds || entry.id == id)
- && (allKeys || entry.keyseq == key)) {
- d->sequences[i].autorepeat = on;
- ++itemsChanged;
- }
- if (id == entry.id)
- return itemsChanged;
- --i;
- }
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace()
- << "QShortcutMap::setShortcutAutoRepeat(" << on << ", " << id << ", "
- << owner << ", " << key << ") = " << itemsChanged;
-#endif
- return itemsChanged;
-}
-
-/*! \internal
- Resets the state of the statemachine to NoMatch
-*/
-void QShortcutMap::resetState()
-{
- Q_D(QShortcutMap);
- d->currentState = QKeySequence::NoMatch;
- clearSequence(d->currentSequences);
-}
-
-/*! \internal
- Returns the current state of the statemachine
-*/
-QKeySequence::SequenceMatch QShortcutMap::state()
-{
- Q_D(QShortcutMap);
- return d->currentState;
-}
-
-/*! \internal
- Uses ShortcutOverride event to see if any widgets want to override
- the event. If not, uses nextState(QKeyEvent) to check for a grabbed
- Shortcut, and dispatchEvent() is found an identical.
- \sa nextState dispatchEvent
-*/
-bool QShortcutMap::tryShortcutEvent(QObject *o, QKeyEvent *e)
-{
- Q_D(QShortcutMap);
-
- bool wasAccepted = e->isAccepted();
- bool wasSpontaneous = e->spont;
- if (d->currentState == QKeySequence::NoMatch) {
- ushort orgType = e->t;
- e->t = QEvent::ShortcutOverride;
- e->ignore();
- QCoreApplication::sendEvent(o, e);
- e->t = orgType;
- e->spont = wasSpontaneous;
- if (e->isAccepted()) {
- if (!wasAccepted)
- e->ignore();
- return false;
- }
- }
-
- QKeySequence::SequenceMatch result = nextState(e);
- bool stateWasAccepted = e->isAccepted();
- if (wasAccepted)
- e->accept();
- else
- e->ignore();
-
- int identicalMatches = d->identicals.count();
-
- switch(result) {
- case QKeySequence::NoMatch:
- return stateWasAccepted;
- case QKeySequence::ExactMatch:
- resetState();
- dispatchEvent(e);
- default:
- break;
- }
- // If nextState is QKeySequence::ExactMatch && identicals.count == 0
- // we've only found disabled shortcuts
- return identicalMatches > 0 || result == QKeySequence::PartialMatch;
-}
-
-/*! \internal
- Returns the next state of the statemachine
- If return value is SequenceMatch::ExactMatch, then a call to matches()
- will return a QObjects* list of all matching objects for the last matching
- sequence.
-*/
-QKeySequence::SequenceMatch QShortcutMap::nextState(QKeyEvent *e)
-{
- Q_D(QShortcutMap);
- // Modifiers can NOT be shortcuts...
- if (e->key() >= Qt::Key_Shift &&
- e->key() <= Qt::Key_Alt)
- return d->currentState;
-
- QKeySequence::SequenceMatch result = QKeySequence::NoMatch;
-
- // We start fresh each time..
- d->identicals.resize(0);
-
- result = find(e);
- if (result == QKeySequence::NoMatch && e->modifiers() & Qt::ShiftModifier) {
- // If Shift + Key_Backtab, also try Shift + Qt::Key_Tab
- if (e->key() == Qt::Key_Backtab) {
- QKeyEvent pe = QKeyEvent(e->type(), Qt::Key_Tab, e->modifiers(), e->text());
- result = find(&pe);
- }
- }
-
- // Should we eat this key press?
- if (d->currentState == QKeySequence::PartialMatch
- || (d->currentState == QKeySequence::ExactMatch && d->identicals.count()))
- e->accept();
- // Does the new state require us to clean up?
- if (result == QKeySequence::NoMatch)
- clearSequence(d->currentSequences);
- d->currentState = result;
-
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace() << "QShortcutMap::nextState(" << e << ") = " << result;
-#endif
- return result;
-}
-
-
-/*! \internal
- Determines if an enabled shortcut has a matcing key sequence.
-*/
-bool QShortcutMap::hasShortcutForKeySequence(const QKeySequence &seq) const
-{
- Q_D(const QShortcutMap);
- QShortcutEntry entry(seq); // needed for searching
- QList<QShortcutEntry>::ConstIterator itEnd = d->sequences.constEnd();
- QList<QShortcutEntry>::ConstIterator it = qLowerBound(d->sequences.constBegin(), itEnd, entry);
-
- for (;it != itEnd; ++it) {
- if (matches(entry.keyseq, (*it).keyseq) == QKeySequence::ExactMatch && correctContext(*it) && (*it).enabled) {
- return true;
- }
- }
-
- //end of the loop: we didn't find anything
- return false;
-}
-
-/*! \internal
- Returns the next state of the statemachine, based
- on the new key event \a e.
- Matches are appended to the vector of identicals,
- which can be access through matches().
- \sa matches
-*/
-QKeySequence::SequenceMatch QShortcutMap::find(QKeyEvent *e)
-{
- Q_D(QShortcutMap);
- if (!d->sequences.count())
- return QKeySequence::NoMatch;
-
- createNewSequences(e, d->newEntries);
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug() << "Possible shortcut key sequences:" << d->newEntries;
-#endif
-
- // Should never happen
- if (d->newEntries == d->currentSequences) {
- Q_ASSERT_X(e->key() != Qt::Key_unknown || e->text().length(),
- "QShortcutMap::find", "New sequence to find identical to previous");
- return QKeySequence::NoMatch;
- }
-
- // Looking for new identicals, scrap old
- d->identicals.resize(0);
-
- bool partialFound = false;
- bool identicalDisabledFound = false;
- QVector<QKeySequence> okEntries;
- int result = QKeySequence::NoMatch;
- for (int i = d->newEntries.count()-1; i >= 0 ; --i) {
- QShortcutEntry entry(d->newEntries.at(i)); // needed for searching
- QList<QShortcutEntry>::ConstIterator itEnd = d->sequences.constEnd();
- QList<QShortcutEntry>::ConstIterator it =
- qLowerBound(d->sequences.constBegin(), itEnd, entry);
-
- int oneKSResult = QKeySequence::NoMatch;
- int tempRes = QKeySequence::NoMatch;
- do {
- if (it == itEnd)
- break;
- tempRes = matches(entry.keyseq, (*it).keyseq);
- oneKSResult = qMax(oneKSResult, tempRes);
- if (tempRes != QKeySequence::NoMatch && correctContext(*it)) {
- if (tempRes == QKeySequence::ExactMatch) {
- if ((*it).enabled)
- d->identicals.append(&*it);
- else
- identicalDisabledFound = true;
- } else if (tempRes == QKeySequence::PartialMatch) {
- // We don't need partials, if we have identicals
- if (d->identicals.size())
- break;
- // We only care about enabled partials, so we don't consume
- // key events when all partials are disabled!
- partialFound |= (*it).enabled;
- }
- }
- ++it;
- // If we got a valid match on this run, there might still be more keys to check against,
- // so we'll loop once more. If we get NoMatch, there's guaranteed no more possible
- // matches in the shortcutmap.
- } while (tempRes != QKeySequence::NoMatch);
-
- // If the type of match improves (ergo, NoMatch->Partial, or Partial->Exact), clear the
- // previous list. If this match is equal or better than the last match, append to the list
- if (oneKSResult > result) {
- okEntries.clear();
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug() << "Found better match (" << d->newEntries << "), clearing key sequence list";
-#endif
- }
- if (oneKSResult && oneKSResult >= result) {
- okEntries << d->newEntries.at(i);
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug() << "Added ok key sequence" << d->newEntries;
-#endif
- }
- }
-
- if (d->identicals.size()) {
- result = QKeySequence::ExactMatch;
- } else if (partialFound) {
- result = QKeySequence::PartialMatch;
- } else if (identicalDisabledFound) {
- result = QKeySequence::ExactMatch;
- } else {
- clearSequence(d->currentSequences);
- result = QKeySequence::NoMatch;
- }
- if (result != QKeySequence::NoMatch)
- d->currentSequences = okEntries;
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug() << "Returning shortcut match == " << result;
-#endif
- return QKeySequence::SequenceMatch(result);
-}
-
-/*! \internal
- Clears \a seq to an empty QKeySequence.
- Same as doing (the slower)
- \snippet doc/src/snippets/code/src_gui_kernel_qshortcutmap.cpp 0
-*/
-void QShortcutMap::clearSequence(QVector<QKeySequence> &ksl)
-{
- ksl.clear();
- d_func()->newEntries.clear();
-}
-
-/*! \internal
- Alters \a seq to the new sequence state, based on the
- current sequence state, and the new key event \a e.
-*/
-void QShortcutMap::createNewSequences(QKeyEvent *e, QVector<QKeySequence> &ksl)
-{
- Q_D(QShortcutMap);
- QList<int> possibleKeys = QKeyMapper::possibleKeys(e);
- int pkTotal = possibleKeys.count();
- if (!pkTotal)
- return;
-
- int ssActual = d->currentSequences.count();
- int ssTotal = qMax(1, ssActual);
- // Resize to possible permutations of the current sequence(s).
- ksl.resize(pkTotal * ssTotal);
-
- int index = ssActual ? d->currentSequences.at(0).count() : 0;
- for (int pkNum = 0; pkNum < pkTotal; ++pkNum) {
- for (int ssNum = 0; ssNum < ssTotal; ++ssNum) {
- int i = (pkNum * ssTotal) + ssNum;
- QKeySequence &curKsl = ksl[i];
- if (ssActual) {
- const QKeySequence &curSeq = d->currentSequences.at(ssNum);
- curKsl.setKey(curSeq[0], 0);
- curKsl.setKey(curSeq[1], 1);
- curKsl.setKey(curSeq[2], 2);
- curKsl.setKey(curSeq[3], 3);
- } else {
- curKsl.setKey(0, 0);
- curKsl.setKey(0, 1);
- curKsl.setKey(0, 2);
- curKsl.setKey(0, 3);
- }
- // Filtering keycode here with 0xdfffffff to ignore the Keypad modifier
- curKsl.setKey(possibleKeys.at(pkNum) & 0xdfffffff, index);
- }
- }
-}
-
-/*! \internal
- Basically the same function as QKeySequence::matches(const QKeySequence &seq) const
- only that is specially handles Key_hyphen as Key_Minus, as people mix these up all the time and
- they conceptually the same.
-*/
-QKeySequence::SequenceMatch QShortcutMap::matches(const QKeySequence &seq1,
- const QKeySequence &seq2) const
-{
- uint userN = seq1.count(),
- seqN = seq2.count();
-
- if (userN > seqN)
- return QKeySequence::NoMatch;
-
- // If equal in length, we have a potential ExactMatch sequence,
- // else we already know it can only be partial.
- QKeySequence::SequenceMatch match = (userN == seqN
- ? QKeySequence::ExactMatch
- : QKeySequence::PartialMatch);
-
- for (uint i = 0; i < userN; ++i) {
- int userKey = seq1[i],
- sequenceKey = seq2[i];
- if ((userKey & Qt::Key_unknown) == Qt::Key_hyphen)
- userKey = (userKey & Qt::KeyboardModifierMask) | Qt::Key_Minus;
- if ((sequenceKey & Qt::Key_unknown) == Qt::Key_hyphen)
- sequenceKey = (sequenceKey & Qt::KeyboardModifierMask) | Qt::Key_Minus;
- if (userKey != sequenceKey)
- return QKeySequence::NoMatch;
- }
- return match;
-}
-
-/*! \internal
- Returns true if the widget \a w is a logical sub window of the current
- top-level widget.
-*/
-bool QShortcutMap::correctContext(const QShortcutEntry &item) const {
- Q_ASSERT_X(item.owner, "QShortcutMap", "Shortcut has no owner. Illegal map state!");
-
- QWidget *active_window = QApplication::activeWindow();
-
- // popups do not become the active window,
- // so we fake it here to get the correct context
- // for the shortcut system.
- if (QApplication::activePopupWidget())
- active_window = QApplication::activePopupWidget();
-
- if (!active_window)
- return false;
-#ifndef QT_NO_ACTION
- if (QAction *a = qobject_cast<QAction *>(item.owner))
- return correctContext(item.context, a, active_window);
-#endif
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsWidget *gw = qobject_cast<QGraphicsWidget *>(item.owner))
- return correctGraphicsWidgetContext(item.context, gw, active_window);
-#endif
- QWidget *w = qobject_cast<QWidget *>(item.owner);
- if (!w) {
- QShortcut *s = qobject_cast<QShortcut *>(item.owner);
- w = s->parentWidget();
- }
- return correctWidgetContext(item.context, w, active_window);
-}
-
-bool QShortcutMap::correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window) const
-{
- bool visible = w->isVisible();
-#ifdef Q_WS_MAC
- if (!qApp->testAttribute(Qt::AA_DontUseNativeMenuBar) && qobject_cast<QMenuBar *>(w))
- visible = true;
-#endif
-
- if (!visible || !w->isEnabled())
- return false;
-
- if (context == Qt::ApplicationShortcut)
- return QApplicationPrivate::tryModalHelper(w, 0); // true, unless w is shadowed by a modal dialog
-
- if (context == Qt::WidgetShortcut)
- return w == QApplication::focusWidget();
-
- if (context == Qt::WidgetWithChildrenShortcut) {
- const QWidget *tw = QApplication::focusWidget();
- while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup))
- tw = tw->parentWidget();
- return tw == w;
- }
-
- // Below is Qt::WindowShortcut context
- QWidget *tlw = w->window();
-#ifndef QT_NO_GRAPHICSVIEW
- if (QWExtra *topData = tlw->d_func()->extra) {
- if (topData->proxyWidget) {
- bool res = correctGraphicsWidgetContext(context, (QGraphicsWidget *)topData->proxyWidget, active_window);
- return res;
- }
- }
-#endif
-
- /* if a floating tool window is active, keep shortcuts on the
- * parent working */
- if (active_window != tlw && active_window && active_window->windowType() == Qt::Tool && active_window->parentWidget()) {
- active_window = active_window->parentWidget()->window();
- }
-
- if (active_window != tlw)
- return false;
-
- /* if we live in a MDI subwindow, ignore the event if we are
- not the active document window */
- const QWidget* sw = w;
- while (sw && !(sw->windowType() == Qt::SubWindow) && !sw->isWindow())
- sw = sw->parentWidget();
- if (sw && (sw->windowType() == Qt::SubWindow)) {
- QWidget *focus_widget = QApplication::focusWidget();
- while (focus_widget && focus_widget != sw)
- focus_widget = focus_widget->parentWidget();
- return sw == focus_widget;
- }
-
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace() << "..true [Pass-through]";
-#endif
- return true;
-}
-
-#ifndef QT_NO_GRAPHICSVIEW
-bool QShortcutMap::correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window) const
-{
- bool visible = w->isVisible();
-#ifdef Q_WS_MAC
- if (!qApp->testAttribute(Qt::AA_DontUseNativeMenuBar) && qobject_cast<QMenuBar *>(w))
- visible = true;
-#endif
-
- if (!visible || !w->isEnabled() || !w->scene())
- return false;
-
- if (context == Qt::ApplicationShortcut) {
- // Applicationwide shortcuts are always reachable unless their owner
- // is shadowed by modality. In QGV there's no modality concept, but we
- // must still check if all views are shadowed.
- QList<QGraphicsView *> views = w->scene()->views();
- for (int i = 0; i < views.size(); ++i) {
- if (QApplicationPrivate::tryModalHelper(views.at(i), 0))
- return true;
- }
- return false;
- }
-
- if (context == Qt::WidgetShortcut)
- return static_cast<QGraphicsItem *>(w) == w->scene()->focusItem();
-
- if (context == Qt::WidgetWithChildrenShortcut) {
- const QGraphicsItem *ti = w->scene()->focusItem();
- if (ti && ti->isWidget()) {
- const QGraphicsWidget *tw = static_cast<const QGraphicsWidget *>(ti);
- while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup))
- tw = tw->parentWidget();
- return tw == w;
- }
- return false;
- }
-
- // Below is Qt::WindowShortcut context
-
- // Find the active view (if any).
- QList<QGraphicsView *> views = w->scene()->views();
- QGraphicsView *activeView = 0;
- for (int i = 0; i < views.size(); ++i) {
- QGraphicsView *view = views.at(i);
- if (view->window() == active_window) {
- activeView = view;
- break;
- }
- }
- if (!activeView)
- return false;
-
- // The shortcut is reachable if owned by a windowless widget, or if the
- // widget's window is the same as the focus item's window.
- QGraphicsWidget *a = w->scene()->activeWindow();
- return !w->window() || a == w->window();
-}
-#endif
-
-#ifndef QT_NO_ACTION
-bool QShortcutMap::correctContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window) const
-{
- const QList<QWidget *> &widgets = a->d_func()->widgets;
-#if defined(DEBUG_QSHORTCUTMAP)
- if (widgets.isEmpty())
- qDebug() << a << "not connected to any widgets; won't trigger";
-#endif
- for (int i = 0; i < widgets.size(); ++i) {
- QWidget *w = widgets.at(i);
-#ifndef QT_NO_MENU
- if (QMenu *menu = qobject_cast<QMenu *>(w)) {
- QAction *a = menu->menuAction();
- if (correctContext(context, a, active_window))
- return true;
- } else
-#endif
- if (correctWidgetContext(context, w, active_window))
- return true;
- }
-
-#ifndef QT_NO_GRAPHICSVIEW
- const QList<QGraphicsWidget *> &graphicsWidgets = a->d_func()->graphicsWidgets;
-#if defined(DEBUG_QSHORTCUTMAP)
- if (graphicsWidgets.isEmpty())
- qDebug() << a << "not connected to any widgets; won't trigger";
-#endif
- for (int i = 0; i < graphicsWidgets.size(); ++i) {
- QGraphicsWidget *w = graphicsWidgets.at(i);
- if (correctGraphicsWidgetContext(context, w, active_window))
- return true;
- }
-#endif
- return false;
-}
-#endif // QT_NO_ACTION
-
-/*! \internal
- Converts keyboard button states into modifier states
-*/
-int QShortcutMap::translateModifiers(Qt::KeyboardModifiers modifiers)
-{
- int result = 0;
- if (modifiers & Qt::ShiftModifier)
- result |= Qt::SHIFT;
- if (modifiers & Qt::ControlModifier)
- result |= Qt::CTRL;
- if (modifiers & Qt::MetaModifier)
- result |= Qt::META;
- if (modifiers & Qt::AltModifier)
- result |= Qt::ALT;
- return result;
-}
-
-/*! \internal
- Returns the vector of QShortcutEntry's matching the last Identical state.
-*/
-QVector<const QShortcutEntry*> QShortcutMap::matches() const
-{
- Q_D(const QShortcutMap);
- return d->identicals;
-}
-
-/*! \internal
- Dispatches QShortcutEvents to widgets who grabbed the matched key sequence.
-*/
-void QShortcutMap::dispatchEvent(QKeyEvent *e)
-{
- Q_D(QShortcutMap);
- if (!d->identicals.size())
- return;
-
- const QKeySequence &curKey = d->identicals.at(0)->keyseq;
- if (d->prevSequence != curKey) {
- d->ambigCount = 0;
- d->prevSequence = curKey;
- }
- // Find next
- const QShortcutEntry *current = 0, *next = 0;
- int i = 0, enabledShortcuts = 0;
- while(i < d->identicals.size()) {
- current = d->identicals.at(i);
- if (current->enabled || !next){
- ++enabledShortcuts;
- if (enabledShortcuts > d->ambigCount + 1)
- break;
- next = current;
- }
- ++i;
- }
- d->ambigCount = (d->identicals.size() == i ? 0 : d->ambigCount + 1);
- // Don't trigger shortcut if we're autorepeating and the shortcut is
- // grabbed with not accepting autorepeats.
- if (!next || (e->isAutoRepeat() && !next->autorepeat))
- return;
- // Dispatch next enabled
-#if defined(DEBUG_QSHORTCUTMAP)
- qDebug().nospace()
- << "QShortcutMap::dispatchEvent(): Sending QShortcutEvent(\""
- << (QString)next->keyseq << "\", " << next->id << ", "
- << (bool)(enabledShortcuts>1) << ") to object(" << next->owner << ')';
-#endif
- QShortcutEvent se(next->keyseq, next->id, enabledShortcuts>1);
- QCoreApplication::sendEvent(const_cast<QObject *>(next->owner), &se);
-}
-
-/* \internal
- QShortcutMap dump function, only available when DEBUG_QSHORTCUTMAP is
- defined.
-*/
-#if defined(Dump_QShortcutMap)
-void QShortcutMap::dumpMap() const
-{
- Q_D(const QShortcutMap);
- for (int i = 0; i < d->sequences.size(); ++i)
- qDebug().nospace() << &(d->sequences.at(i));
-}
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SHORTCUT
diff --git a/src/gui/to_be_moved/qshortcutmap_p.h b/src/gui/to_be_moved/qshortcutmap_p.h
deleted file mode 100644
index bc530b00b4..0000000000
--- a/src/gui/to_be_moved/qshortcutmap_p.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/****************************************************************************
-**
-** 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 QSHORTCUTMAP_P_H
-#define QSHORTCUTMAP_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qkeysequence.h"
-#include "QtCore/qvector.h"
-#include "QtCore/qscopedpointer.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_SHORTCUT
-
-// To enable dump output uncomment below
-//#define Dump_QShortcutMap
-
-class QKeyEvent;
-struct QShortcutEntry;
-class QShortcutMapPrivate;
-class QGraphicsWidget;
-class QWidget;
-class QAction;
-class QObject;
-
-class QShortcutMap
-{
- Q_DECLARE_PRIVATE(QShortcutMap)
-public:
- QShortcutMap();
- ~QShortcutMap();
-
- int addShortcut(QObject *owner, const QKeySequence &key, Qt::ShortcutContext context);
- int removeShortcut(int id, QObject *owner, const QKeySequence &key = QKeySequence());
- int setShortcutEnabled(bool enable, int id, QObject *owner, const QKeySequence &key = QKeySequence());
- int setShortcutAutoRepeat(bool on, int id, QObject *owner, const QKeySequence &key = QKeySequence());
-
- void resetState();
- QKeySequence::SequenceMatch nextState(QKeyEvent *e);
- QKeySequence::SequenceMatch state();
- void dispatchEvent(QKeyEvent *e);
- bool tryShortcutEvent(QObject *o, QKeyEvent *e);
-
-#ifdef Dump_QShortcutMap
- void dumpMap() const;
-#endif
-
- bool hasShortcutForKeySequence(const QKeySequence &seq) const;
-
-
-private:
- bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidget *active_window) const;
-#ifndef QT_NO_GRAPHICSVIEW
- bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsWidget *w, QWidget *active_window) const;
-#endif
-#ifndef QT_NO_ACTION
- bool correctContext(Qt::ShortcutContext context,QAction *a, QWidget *active_window) const;
-#endif
- QScopedPointer<QShortcutMapPrivate> d_ptr;
-
- QKeySequence::SequenceMatch find(QKeyEvent *e);
- QKeySequence::SequenceMatch matches(const QKeySequence &seq1, const QKeySequence &seq2) const;
- QVector<const QShortcutEntry *> matches() const;
- void createNewSequences(QKeyEvent *e, QVector<QKeySequence> &ksl);
- void clearSequence(QVector<QKeySequence> &ksl);
- bool correctContext(const QShortcutEntry &item) const;
- int translateModifiers(Qt::KeyboardModifiers modifiers);
-};
-
-#endif // QT_NO_SHORTCUT
-
-QT_END_NAMESPACE
-
-#endif // QSHORTCUTMAP_P_H
diff --git a/src/gui/to_be_moved/qtextcontrol.cpp b/src/gui/to_be_moved/qtextcontrol.cpp
deleted file mode 100644
index 43967307bc..0000000000
--- a/src/gui/to_be_moved/qtextcontrol.cpp
+++ /dev/null
@@ -1,3148 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtextcontrol_p.h"
-#include "qtextcontrol_p_p.h"
-
-#ifndef QT_NO_TEXTCONTROL
-
-#include <qfont.h>
-#include <qpainter.h>
-#include <qevent.h>
-#include <qdebug.h>
-#include <qmime.h>
-#include <qdrag.h>
-#include <qclipboard.h>
-#include <qmenu.h>
-#include <qstyle.h>
-#include <qtimer.h>
-#include "private/qtextdocumentlayout_p.h"
-#include "private/qabstracttextdocumentlayout_p.h"
-#include "private/qtextedit_p.h"
-#include "qtextdocument.h"
-#include "private/qtextdocument_p.h"
-#include "qtextlist.h"
-#include "private/qtextcontrol_p.h"
-#include "qgraphicssceneevent.h"
-#include "qprinter.h"
-#include "qtextdocumentwriter.h"
-#include "private/qtextcursor_p.h"
-
-#include <qtextformat.h>
-#include <qdatetime.h>
-#include <qbuffer.h>
-#include <qapplication.h>
-#include <limits.h>
-#include <qtexttable.h>
-#include <qvariant.h>
-#include <qurl.h>
-#include <qdesktopservices.h>
-#include <qinputcontext.h>
-#include <qtooltip.h>
-#include <qstyleoption.h>
-#include <QtGui/qlineedit.h>
-
-#ifndef QT_NO_SHORTCUT
-#include "private/qapplication_p.h"
-#include "private/qshortcutmap_p.h"
-#include <qkeysequence.h>
-#define ACCEL_KEY(k) (!qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? QLatin1Char('\t') + QString(QKeySequence(k)) : QString())
-#else
-#define ACCEL_KEY(k) QString()
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_CONTEXTMENU
-#if defined(Q_WS_WIN) || defined(Q_WS_X11)
-extern bool qt_use_rtl_extensions;
-#endif
-#endif
-
-// could go into QTextCursor...
-static QTextLine currentTextLine(const QTextCursor &cursor)
-{
- const QTextBlock block = cursor.block();
- if (!block.isValid())
- return QTextLine();
-
- const QTextLayout *layout = block.layout();
- if (!layout)
- return QTextLine();
-
- const int relativePos = cursor.position() - block.position();
- return layout->lineForTextPosition(relativePos);
-}
-
-QTextControlPrivate::QTextControlPrivate()
- : doc(0), cursorOn(false), cursorIsFocusIndicator(false),
- interactionFlags(Qt::TextEditorInteraction),
- dragEnabled(true),
-#ifndef QT_NO_DRAGANDDROP
- mousePressed(false), mightStartDrag(false),
-#endif
- lastSelectionState(false), ignoreAutomaticScrollbarAdjustement(false),
- overwriteMode(false),
- acceptRichText(true),
- preeditCursor(0), hideCursor(false),
- hasFocus(false),
-#ifdef QT_KEYPAD_NAVIGATION
- hasEditFocus(false),
-#endif
- isEnabled(true),
- hadSelectionOnMousePress(false),
- ignoreUnusedNavigationEvents(false),
- openExternalLinks(false),
- wordSelectionEnabled(false)
-{}
-
-bool QTextControlPrivate::cursorMoveKeyEvent(QKeyEvent *e)
-{
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(e);
-#endif
-
- Q_Q(QTextControl);
- if (cursor.isNull())
- return false;
-
- const QTextCursor oldSelection = cursor;
- const int oldCursorPos = cursor.position();
-
- QTextCursor::MoveMode mode = QTextCursor::MoveAnchor;
- QTextCursor::MoveOperation op = QTextCursor::NoMove;
-
- if (false) {
- }
-#ifndef QT_NO_SHORTCUT
- if (e == QKeySequence::MoveToNextChar) {
- op = QTextCursor::Right;
- }
- else if (e == QKeySequence::MoveToPreviousChar) {
- op = QTextCursor::Left;
- }
- else if (e == QKeySequence::SelectNextChar) {
- op = QTextCursor::Right;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectPreviousChar) {
- op = QTextCursor::Left;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectNextWord) {
- op = QTextCursor::WordRight;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectPreviousWord) {
- op = QTextCursor::WordLeft;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectStartOfLine) {
- op = QTextCursor::StartOfLine;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectEndOfLine) {
- op = QTextCursor::EndOfLine;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectStartOfBlock) {
- op = QTextCursor::StartOfBlock;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectEndOfBlock) {
- op = QTextCursor::EndOfBlock;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectStartOfDocument) {
- op = QTextCursor::Start;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectEndOfDocument) {
- op = QTextCursor::End;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectPreviousLine) {
- op = QTextCursor::Up;
- mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectNextLine) {
- op = QTextCursor::Down;
- mode = QTextCursor::KeepAnchor;
- {
- QTextBlock block = cursor.block();
- QTextLine line = currentTextLine(cursor);
- if (!block.next().isValid()
- && line.isValid()
- && line.lineNumber() == block.layout()->lineCount() - 1)
- op = QTextCursor::End;
- }
- }
- else if (e == QKeySequence::MoveToNextWord) {
- op = QTextCursor::WordRight;
- }
- else if (e == QKeySequence::MoveToPreviousWord) {
- op = QTextCursor::WordLeft;
- }
- else if (e == QKeySequence::MoveToEndOfBlock) {
- op = QTextCursor::EndOfBlock;
- }
- else if (e == QKeySequence::MoveToStartOfBlock) {
- op = QTextCursor::StartOfBlock;
- }
- else if (e == QKeySequence::MoveToNextLine) {
- op = QTextCursor::Down;
- }
- else if (e == QKeySequence::MoveToPreviousLine) {
- op = QTextCursor::Up;
- }
- else if (e == QKeySequence::MoveToPreviousLine) {
- op = QTextCursor::Up;
- }
- else if (e == QKeySequence::MoveToStartOfLine) {
- op = QTextCursor::StartOfLine;
- }
- else if (e == QKeySequence::MoveToEndOfLine) {
- op = QTextCursor::EndOfLine;
- }
- else if (e == QKeySequence::MoveToStartOfDocument) {
- op = QTextCursor::Start;
- }
- else if (e == QKeySequence::MoveToEndOfDocument) {
- op = QTextCursor::End;
- }
-#endif // QT_NO_SHORTCUT
- else {
- return false;
- }
-
-// Except for pageup and pagedown, Mac OS X has very different behavior, we don't do it all, but
-// here's the breakdown:
-// Shift still works as an anchor, but only one of the other keys can be down Ctrl (Command),
-// Alt (Option), or Meta (Control).
-// Command/Control + Left/Right -- Move to left or right of the line
-// + Up/Down -- Move to top bottom of the file. (Control doesn't move the cursor)
-// Option + Left/Right -- Move one word Left/right.
-// + Up/Down -- Begin/End of Paragraph.
-// Home/End Top/Bottom of file. (usually don't move the cursor, but will select)
-
- bool visualNavigation = cursor.visualNavigation();
- cursor.setVisualNavigation(true);
- const bool moved = cursor.movePosition(op, mode);
- cursor.setVisualNavigation(visualNavigation);
- q->ensureCursorVisible();
-
- bool ignoreNavigationEvents = ignoreUnusedNavigationEvents;
- bool isNavigationEvent = e->key() == Qt::Key_Up || e->key() == Qt::Key_Down;
-
-#ifdef QT_KEYPAD_NAVIGATION
- ignoreNavigationEvents = ignoreNavigationEvents || QApplication::keypadNavigationEnabled();
- isNavigationEvent = isNavigationEvent ||
- (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
- && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right));
-#else
- isNavigationEvent = isNavigationEvent || e->key() == Qt::Key_Left || e->key() == Qt::Key_Right;
-#endif
-
- if (moved) {
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
- emit q->microFocusChanged();
- } else if (ignoreNavigationEvents && isNavigationEvent && oldSelection.anchor() == cursor.anchor()) {
- return false;
- }
-
- selectionChanged(/*forceEmitSelectionChanged =*/(mode == QTextCursor::KeepAnchor));
-
- repaintOldAndNewSelection(oldSelection);
-
- return true;
-}
-
-void QTextControlPrivate::updateCurrentCharFormat()
-{
- Q_Q(QTextControl);
-
- QTextCharFormat fmt = cursor.charFormat();
- if (fmt == lastCharFormat)
- return;
- lastCharFormat = fmt;
-
- emit q->currentCharFormatChanged(fmt);
- emit q->microFocusChanged();
-}
-
-void QTextControlPrivate::indent()
-{
- QTextBlockFormat blockFmt = cursor.blockFormat();
-
- QTextList *list = cursor.currentList();
- if (!list) {
- QTextBlockFormat modifier;
- modifier.setIndent(blockFmt.indent() + 1);
- cursor.mergeBlockFormat(modifier);
- } else {
- QTextListFormat format = list->format();
- format.setIndent(format.indent() + 1);
-
- if (list->itemNumber(cursor.block()) == 1)
- list->setFormat(format);
- else
- cursor.createList(format);
- }
-}
-
-void QTextControlPrivate::outdent()
-{
- QTextBlockFormat blockFmt = cursor.blockFormat();
-
- QTextList *list = cursor.currentList();
-
- if (!list) {
- QTextBlockFormat modifier;
- modifier.setIndent(blockFmt.indent() - 1);
- cursor.mergeBlockFormat(modifier);
- } else {
- QTextListFormat listFmt = list->format();
- listFmt.setIndent(listFmt.indent() - 1);
- list->setFormat(listFmt);
- }
-}
-
-void QTextControlPrivate::gotoNextTableCell()
-{
- QTextTable *table = cursor.currentTable();
- QTextTableCell cell = table->cellAt(cursor);
-
- int newColumn = cell.column() + cell.columnSpan();
- int newRow = cell.row();
-
- if (newColumn >= table->columns()) {
- newColumn = 0;
- ++newRow;
- if (newRow >= table->rows())
- table->insertRows(table->rows(), 1);
- }
-
- cell = table->cellAt(newRow, newColumn);
- cursor = cell.firstCursorPosition();
-}
-
-void QTextControlPrivate::gotoPreviousTableCell()
-{
- QTextTable *table = cursor.currentTable();
- QTextTableCell cell = table->cellAt(cursor);
-
- int newColumn = cell.column() - 1;
- int newRow = cell.row();
-
- if (newColumn < 0) {
- newColumn = table->columns() - 1;
- --newRow;
- if (newRow < 0)
- return;
- }
-
- cell = table->cellAt(newRow, newColumn);
- cursor = cell.firstCursorPosition();
-}
-
-void QTextControlPrivate::createAutoBulletList()
-{
- cursor.beginEditBlock();
-
- QTextBlockFormat blockFmt = cursor.blockFormat();
-
- QTextListFormat listFmt;
- listFmt.setStyle(QTextListFormat::ListDisc);
- listFmt.setIndent(blockFmt.indent() + 1);
-
- blockFmt.setIndent(0);
- cursor.setBlockFormat(blockFmt);
-
- cursor.createList(listFmt);
-
- cursor.endEditBlock();
-}
-
-void QTextControlPrivate::init(Qt::TextFormat format, const QString &text, QTextDocument *document)
-{
- Q_Q(QTextControl);
- setContent(format, text, document);
-
- doc->setUndoRedoEnabled(interactionFlags & Qt::TextEditable);
- q->setCursorWidth(-1);
-}
-
-void QTextControlPrivate::setContent(Qt::TextFormat format, const QString &text, QTextDocument *document)
-{
- Q_Q(QTextControl);
-
- // for use when called from setPlainText. we may want to re-use the currently
- // set char format then.
- const QTextCharFormat charFormatForInsertion = cursor.charFormat();
-
- bool clearDocument = true;
- if (!doc) {
- if (document) {
- doc = document;
- clearDocument = false;
- } else {
- palette = QApplication::palette("QTextControl");
- doc = new QTextDocument(q);
- }
- _q_documentLayoutChanged();
- cursor = QTextCursor(doc);
-
-// #### doc->documentLayout()->setPaintDevice(viewport);
-
- QObject::connect(doc, SIGNAL(contentsChanged()), q, SLOT(_q_updateCurrentCharFormatAndSelection()));
- QObject::connect(doc, SIGNAL(cursorPositionChanged(QTextCursor)), q, SLOT(_q_emitCursorPosChanged(QTextCursor)));
- QObject::connect(doc, SIGNAL(documentLayoutChanged()), q, SLOT(_q_documentLayoutChanged()));
-
- // convenience signal forwards
- QObject::connect(doc, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
- QObject::connect(doc, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
- QObject::connect(doc, SIGNAL(modificationChanged(bool)), q, SIGNAL(modificationChanged(bool)));
- QObject::connect(doc, SIGNAL(blockCountChanged(int)), q, SIGNAL(blockCountChanged(int)));
- }
-
- bool previousUndoRedoState = doc->isUndoRedoEnabled();
- if (!document)
- doc->setUndoRedoEnabled(false);
-
- //Saving the index save some time.
- static int contentsChangedIndex = QTextDocument::staticMetaObject.indexOfSignal("contentsChanged()");
- static int textChangedIndex = QTextControl::staticMetaObject.indexOfSignal("textChanged()");
- // avoid multiple textChanged() signals being emitted
- QMetaObject::disconnect(doc, contentsChangedIndex, q, textChangedIndex);
-
- if (!text.isEmpty()) {
- // clear 'our' cursor for insertion to prevent
- // the emission of the cursorPositionChanged() signal.
- // instead we emit it only once at the end instead of
- // at the end of the document after loading and when
- // positioning the cursor again to the start of the
- // document.
- cursor = QTextCursor();
- if (format == Qt::PlainText) {
- QTextCursor formatCursor(doc);
- // put the setPlainText and the setCharFormat into one edit block,
- // so that the syntax highlight triggers only /once/ for the entire
- // document, not twice.
- formatCursor.beginEditBlock();
- doc->setPlainText(text);
- doc->setUndoRedoEnabled(false);
- formatCursor.select(QTextCursor::Document);
- formatCursor.setCharFormat(charFormatForInsertion);
- formatCursor.endEditBlock();
- } else {
-#ifndef QT_NO_TEXTHTMLPARSER
- doc->setHtml(text);
-#else
- doc->setPlainText(text);
-#endif
- doc->setUndoRedoEnabled(false);
- }
- cursor = QTextCursor(doc);
- } else if (clearDocument) {
- doc->clear();
- }
- cursor.setCharFormat(charFormatForInsertion);
-
- QMetaObject::connect(doc, contentsChangedIndex, q, textChangedIndex);
- emit q->textChanged();
- if (!document)
- doc->setUndoRedoEnabled(previousUndoRedoState);
- _q_updateCurrentCharFormatAndSelection();
- if (!document)
- doc->setModified(false);
-
- q->ensureCursorVisible();
- emit q->cursorPositionChanged();
-}
-
-void QTextControlPrivate::startDrag()
-{
-#ifndef QT_NO_DRAGANDDROP
- Q_Q(QTextControl);
- mousePressed = false;
- if (!contextWidget)
- return;
- QMimeData *data = q->createMimeDataFromSelection();
-
- QDrag *drag = new QDrag(contextWidget);
- drag->setMimeData(data);
-
- Qt::DropActions actions = Qt::CopyAction;
- Qt::DropAction action;
- if (interactionFlags & Qt::TextEditable) {
- actions |= Qt::MoveAction;
- action = drag->exec(actions, Qt::MoveAction);
- } else {
- action = drag->exec(actions, Qt::CopyAction);
- }
-
- if (action == Qt::MoveAction && drag->target() != contextWidget)
- cursor.removeSelectedText();
-#endif
-}
-
-void QTextControlPrivate::setCursorPosition(const QPointF &pos)
-{
- Q_Q(QTextControl);
- const int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
- if (cursorPos == -1)
- return;
- cursor.setPosition(cursorPos);
-}
-
-void QTextControlPrivate::setCursorPosition(int pos, QTextCursor::MoveMode mode)
-{
- cursor.setPosition(pos, mode);
-
- if (mode != QTextCursor::KeepAnchor) {
- selectedWordOnDoubleClick = QTextCursor();
- selectedBlockOnTrippleClick = QTextCursor();
- }
-}
-
-void QTextControlPrivate::repaintCursor()
-{
- Q_Q(QTextControl);
- emit q->updateRequest(cursorRectPlusUnicodeDirectionMarkers(cursor));
-}
-
-void QTextControlPrivate::repaintOldAndNewSelection(const QTextCursor &oldSelection)
-{
- Q_Q(QTextControl);
- if (cursor.hasSelection()
- && oldSelection.hasSelection()
- && cursor.currentFrame() == oldSelection.currentFrame()
- && !cursor.hasComplexSelection()
- && !oldSelection.hasComplexSelection()
- && cursor.anchor() == oldSelection.anchor()
- ) {
- QTextCursor differenceSelection(doc);
- differenceSelection.setPosition(oldSelection.position());
- differenceSelection.setPosition(cursor.position(), QTextCursor::KeepAnchor);
- emit q->updateRequest(q->selectionRect(differenceSelection));
- } else {
- if (!oldSelection.isNull())
- emit q->updateRequest(q->selectionRect(oldSelection) | cursorRectPlusUnicodeDirectionMarkers(oldSelection));
- emit q->updateRequest(q->selectionRect() | cursorRectPlusUnicodeDirectionMarkers(cursor));
- }
-}
-
-void QTextControlPrivate::selectionChanged(bool forceEmitSelectionChanged /*=false*/)
-{
- Q_Q(QTextControl);
- if (forceEmitSelectionChanged)
- emit q->selectionChanged();
-
- bool current = cursor.hasSelection();
- if (current == lastSelectionState)
- return;
-
- lastSelectionState = current;
- emit q->copyAvailable(current);
- if (!forceEmitSelectionChanged)
- emit q->selectionChanged();
- emit q->microFocusChanged();
-}
-
-void QTextControlPrivate::_q_updateCurrentCharFormatAndSelection()
-{
- updateCurrentCharFormat();
- selectionChanged();
-}
-
-#ifndef QT_NO_CLIPBOARD
-void QTextControlPrivate::setClipboardSelection()
-{
- QClipboard *clipboard = QApplication::clipboard();
- if (!cursor.hasSelection() || !clipboard->supportsSelection())
- return;
- Q_Q(QTextControl);
- QMimeData *data = q->createMimeDataFromSelection();
- clipboard->setMimeData(data, QClipboard::Selection);
-}
-#endif
-
-void QTextControlPrivate::_q_emitCursorPosChanged(const QTextCursor &someCursor)
-{
- Q_Q(QTextControl);
- if (someCursor.isCopyOf(cursor)) {
- emit q->cursorPositionChanged();
- emit q->microFocusChanged();
- }
-}
-
-void QTextControlPrivate::_q_documentLayoutChanged()
-{
- Q_Q(QTextControl);
- QAbstractTextDocumentLayout *layout = doc->documentLayout();
- QObject::connect(layout, SIGNAL(update(QRectF)), q, SIGNAL(updateRequest(QRectF)));
- QObject::connect(layout, SIGNAL(updateBlock(QTextBlock)), q, SLOT(_q_updateBlock(QTextBlock)));
- QObject::connect(layout, SIGNAL(documentSizeChanged(QSizeF)), q, SIGNAL(documentSizeChanged(QSizeF)));
-
-}
-
-void QTextControlPrivate::setBlinkingCursorEnabled(bool enable)
-{
- Q_Q(QTextControl);
-
- if (enable && QApplication::cursorFlashTime() > 0)
- cursorBlinkTimer.start(QApplication::cursorFlashTime() / 2, q);
- else
- cursorBlinkTimer.stop();
-
- cursorOn = enable;
-
- repaintCursor();
-}
-
-void QTextControlPrivate::extendWordwiseSelection(int suggestedNewPosition, qreal mouseXPosition)
-{
- Q_Q(QTextControl);
-
- // if inside the initial selected word keep that
- if (suggestedNewPosition >= selectedWordOnDoubleClick.selectionStart()
- && suggestedNewPosition <= selectedWordOnDoubleClick.selectionEnd()) {
- q->setTextCursor(selectedWordOnDoubleClick);
- return;
- }
-
- QTextCursor curs = selectedWordOnDoubleClick;
- curs.setPosition(suggestedNewPosition, QTextCursor::KeepAnchor);
-
- if (!curs.movePosition(QTextCursor::StartOfWord))
- return;
- const int wordStartPos = curs.position();
-
- const int blockPos = curs.block().position();
- const QPointF blockCoordinates = q->blockBoundingRect(curs.block()).topLeft();
-
- QTextLine line = currentTextLine(curs);
- if (!line.isValid())
- return;
-
- const qreal wordStartX = line.cursorToX(curs.position() - blockPos) + blockCoordinates.x();
-
- if (!curs.movePosition(QTextCursor::EndOfWord))
- return;
- const int wordEndPos = curs.position();
-
- const QTextLine otherLine = currentTextLine(curs);
- if (otherLine.textStart() != line.textStart()
- || wordEndPos == wordStartPos)
- return;
-
- const qreal wordEndX = line.cursorToX(curs.position() - blockPos) + blockCoordinates.x();
-
- if (mouseXPosition < wordStartX || mouseXPosition > wordEndX)
- return;
-
- // keep the already selected word even when moving to the left
- // (#39164)
- if (suggestedNewPosition < selectedWordOnDoubleClick.position())
- cursor.setPosition(selectedWordOnDoubleClick.selectionEnd());
- else
- cursor.setPosition(selectedWordOnDoubleClick.selectionStart());
-
- const qreal differenceToStart = mouseXPosition - wordStartX;
- const qreal differenceToEnd = wordEndX - mouseXPosition;
-
- if (differenceToStart < differenceToEnd)
- setCursorPosition(wordStartPos, QTextCursor::KeepAnchor);
- else
- setCursorPosition(wordEndPos, QTextCursor::KeepAnchor);
-
- if (interactionFlags & Qt::TextSelectableByMouse) {
-#ifndef QT_NO_CLIPBOARD
- setClipboardSelection();
-#endif
- selectionChanged(true);
- }
-}
-
-void QTextControlPrivate::extendBlockwiseSelection(int suggestedNewPosition)
-{
- Q_Q(QTextControl);
-
- // if inside the initial selected line keep that
- if (suggestedNewPosition >= selectedBlockOnTrippleClick.selectionStart()
- && suggestedNewPosition <= selectedBlockOnTrippleClick.selectionEnd()) {
- q->setTextCursor(selectedBlockOnTrippleClick);
- return;
- }
-
- if (suggestedNewPosition < selectedBlockOnTrippleClick.position()) {
- cursor.setPosition(selectedBlockOnTrippleClick.selectionEnd());
- cursor.setPosition(suggestedNewPosition, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
- } else {
- cursor.setPosition(selectedBlockOnTrippleClick.selectionStart());
- cursor.setPosition(suggestedNewPosition, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
- }
-
- if (interactionFlags & Qt::TextSelectableByMouse) {
-#ifndef QT_NO_CLIPBOARD
- setClipboardSelection();
-#endif
- selectionChanged(true);
- }
-}
-
-void QTextControlPrivate::_q_deleteSelected()
-{
- if (!(interactionFlags & Qt::TextEditable) || !cursor.hasSelection())
- return;
- cursor.removeSelectedText();
-}
-
-void QTextControl::undo()
-{
- Q_D(QTextControl);
- d->repaintSelection();
- const int oldCursorPos = d->cursor.position();
- d->doc->undo(&d->cursor);
- if (d->cursor.position() != oldCursorPos)
- emit cursorPositionChanged();
- emit microFocusChanged();
- ensureCursorVisible();
-}
-
-void QTextControl::redo()
-{
- Q_D(QTextControl);
- d->repaintSelection();
- const int oldCursorPos = d->cursor.position();
- d->doc->redo(&d->cursor);
- if (d->cursor.position() != oldCursorPos)
- emit cursorPositionChanged();
- emit microFocusChanged();
- ensureCursorVisible();
-}
-
-QTextControl::QTextControl(QObject *parent)
- : QObject(*new QTextControlPrivate, parent)
-{
- Q_D(QTextControl);
- d->init();
-}
-
-QTextControl::QTextControl(const QString &text, QObject *parent)
- : QObject(*new QTextControlPrivate, parent)
-{
- Q_D(QTextControl);
- d->init(Qt::RichText, text);
-}
-
-QTextControl::QTextControl(QTextDocument *doc, QObject *parent)
- : QObject(*new QTextControlPrivate, parent)
-{
- Q_D(QTextControl);
- d->init(Qt::RichText, QString(), doc);
-}
-
-QTextControl::~QTextControl()
-{
-}
-
-void QTextControl::setDocument(QTextDocument *document)
-{
- Q_D(QTextControl);
- if (d->doc == document)
- return;
-
- d->doc->disconnect(this);
- d->doc->documentLayout()->disconnect(this);
- d->doc->documentLayout()->setPaintDevice(0);
-
- if (d->doc->parent() == this)
- delete d->doc;
-
- d->doc = 0;
- d->setContent(Qt::RichText, QString(), document);
-}
-
-QTextDocument *QTextControl::document() const
-{
- Q_D(const QTextControl);
- return d->doc;
-}
-
-void QTextControl::setTextCursor(const QTextCursor &cursor)
-{
- Q_D(QTextControl);
- d->cursorIsFocusIndicator = false;
- const bool posChanged = cursor.position() != d->cursor.position();
- const QTextCursor oldSelection = d->cursor;
- d->cursor = cursor;
- d->cursorOn = d->hasFocus && (d->interactionFlags & Qt::TextEditable);
- d->_q_updateCurrentCharFormatAndSelection();
- ensureCursorVisible();
- d->repaintOldAndNewSelection(oldSelection);
- if (posChanged)
- emit cursorPositionChanged();
-}
-
-QTextCursor QTextControl::textCursor() const
-{
- Q_D(const QTextControl);
- return d->cursor;
-}
-
-#ifndef QT_NO_CLIPBOARD
-
-void QTextControl::cut()
-{
- Q_D(QTextControl);
- if (!(d->interactionFlags & Qt::TextEditable) || !d->cursor.hasSelection())
- return;
- copy();
- d->cursor.removeSelectedText();
-}
-
-void QTextControl::copy()
-{
- Q_D(QTextControl);
- if (!d->cursor.hasSelection())
- return;
- QMimeData *data = createMimeDataFromSelection();
- QApplication::clipboard()->setMimeData(data);
-}
-
-void QTextControl::paste(QClipboard::Mode mode)
-{
- const QMimeData *md = QApplication::clipboard()->mimeData(mode);
- if (md)
- insertFromMimeData(md);
-}
-#endif
-
-void QTextControl::clear()
-{
- Q_D(QTextControl);
- // clears and sets empty content
- d->extraSelections.clear();
- d->setContent();
-}
-
-
-void QTextControl::selectAll()
-{
- Q_D(QTextControl);
- const int selectionLength = qAbs(d->cursor.position() - d->cursor.anchor());
- d->cursor.select(QTextCursor::Document);
- d->selectionChanged(selectionLength != qAbs(d->cursor.position() - d->cursor.anchor()));
- d->cursorIsFocusIndicator = false;
- emit updateRequest();
-}
-
-void QTextControl::processEvent(QEvent *e, const QPointF &coordinateOffset, QWidget *contextWidget)
-{
- QMatrix m;
- m.translate(coordinateOffset.x(), coordinateOffset.y());
- processEvent(e, m, contextWidget);
-}
-
-void QTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget *contextWidget)
-{
- Q_D(QTextControl);
- if (d->interactionFlags == Qt::NoTextInteraction) {
- e->ignore();
- return;
- }
-
- d->contextWidget = contextWidget;
-
- if (!d->contextWidget) {
- switch (e->type()) {
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseMove:
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseDoubleClick:
- case QEvent::GraphicsSceneContextMenu:
- case QEvent::GraphicsSceneHoverEnter:
- case QEvent::GraphicsSceneHoverMove:
- case QEvent::GraphicsSceneHoverLeave:
- case QEvent::GraphicsSceneHelp:
- case QEvent::GraphicsSceneDragEnter:
- case QEvent::GraphicsSceneDragMove:
- case QEvent::GraphicsSceneDragLeave:
- case QEvent::GraphicsSceneDrop: {
- QGraphicsSceneEvent *ev = static_cast<QGraphicsSceneEvent *>(e);
- d->contextWidget = ev->widget();
- break;
- }
-#endif // QT_NO_GRAPHICSVIEW
- default: break;
- };
- }
-
- switch (e->type()) {
- case QEvent::KeyPress:
- d->keyPressEvent(static_cast<QKeyEvent *>(e));
- break;
- case QEvent::MouseButtonPress: {
- QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mousePressEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
- break; }
- case QEvent::MouseMove: {
- QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mouseMoveEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
- break; }
- case QEvent::MouseButtonRelease: {
- QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mouseReleaseEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
- break; }
- case QEvent::MouseButtonDblClick: {
- QMouseEvent *ev = static_cast<QMouseEvent *>(e);
- d->mouseDoubleClickEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(),
- ev->buttons(), ev->globalPos());
- break; }
- case QEvent::InputMethod:
- d->inputMethodEvent(static_cast<QInputMethodEvent *>(e));
- break;
-#ifndef QT_NO_CONTEXTMENU
- case QEvent::ContextMenu: {
- QContextMenuEvent *ev = static_cast<QContextMenuEvent *>(e);
- d->contextMenuEvent(ev->globalPos(), matrix.map(ev->pos()), contextWidget);
- break; }
-#endif // QT_NO_CONTEXTMENU
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- d->focusEvent(static_cast<QFocusEvent *>(e));
- break;
-
- case QEvent::EnabledChange:
- d->isEnabled = e->isAccepted();
- break;
-
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTip: {
- QHelpEvent *ev = static_cast<QHelpEvent *>(e);
- d->showToolTip(ev->globalPos(), matrix.map(ev->pos()), contextWidget);
- break;
- }
-#endif // QT_NO_TOOLTIP
-
-#ifndef QT_NO_DRAGANDDROP
- case QEvent::DragEnter: {
- QDragEnterEvent *ev = static_cast<QDragEnterEvent *>(e);
- if (d->dragEnterEvent(e, ev->mimeData()))
- ev->acceptProposedAction();
- break;
- }
- case QEvent::DragLeave:
- d->dragLeaveEvent();
- break;
- case QEvent::DragMove: {
- QDragMoveEvent *ev = static_cast<QDragMoveEvent *>(e);
- if (d->dragMoveEvent(e, ev->mimeData(), matrix.map(ev->pos())))
- ev->acceptProposedAction();
- break;
- }
- case QEvent::Drop: {
- QDropEvent *ev = static_cast<QDropEvent *>(e);
- if (d->dropEvent(ev->mimeData(), matrix.map(ev->pos()), ev->dropAction(), ev->source()))
- ev->acceptProposedAction();
- break;
- }
-#endif
-
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMousePress: {
- QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mousePressEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
- ev->screenPos());
- break; }
- case QEvent::GraphicsSceneMouseMove: {
- QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mouseMoveEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
- ev->screenPos());
- break; }
- case QEvent::GraphicsSceneMouseRelease: {
- QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mouseReleaseEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
- ev->screenPos());
- break; }
- case QEvent::GraphicsSceneMouseDoubleClick: {
- QGraphicsSceneMouseEvent *ev = static_cast<QGraphicsSceneMouseEvent *>(e);
- d->mouseDoubleClickEvent(ev, ev->button(), matrix.map(ev->pos()), ev->modifiers(), ev->buttons(),
- ev->screenPos());
- break; }
- case QEvent::GraphicsSceneContextMenu: {
- QGraphicsSceneContextMenuEvent *ev = static_cast<QGraphicsSceneContextMenuEvent *>(e);
- d->contextMenuEvent(ev->screenPos(), matrix.map(ev->pos()), contextWidget);
- break; }
-
- case QEvent::GraphicsSceneHoverMove: {
- QGraphicsSceneHoverEvent *ev = static_cast<QGraphicsSceneHoverEvent *>(e);
- d->mouseMoveEvent(ev, Qt::NoButton, matrix.map(ev->pos()), ev->modifiers(),Qt::NoButton,
- ev->screenPos());
- break; }
-
- case QEvent::GraphicsSceneDragEnter: {
- QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
- if (d->dragEnterEvent(e, ev->mimeData()))
- ev->acceptProposedAction();
- break; }
- case QEvent::GraphicsSceneDragLeave:
- d->dragLeaveEvent();
- break;
- case QEvent::GraphicsSceneDragMove: {
- QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
- if (d->dragMoveEvent(e, ev->mimeData(), matrix.map(ev->pos())))
- ev->acceptProposedAction();
- break; }
- case QEvent::GraphicsSceneDrop: {
- QGraphicsSceneDragDropEvent *ev = static_cast<QGraphicsSceneDragDropEvent *>(e);
- if (d->dropEvent(ev->mimeData(), matrix.map(ev->pos()), ev->dropAction(), ev->source()))
- ev->accept();
- break; }
-#endif // QT_NO_GRAPHICSVIEW
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::EnterEditFocus:
- case QEvent::LeaveEditFocus:
- if (QApplication::keypadNavigationEnabled())
- d->editFocusEvent(e);
- break;
-#endif
- case QEvent::ShortcutOverride:
- if (d->interactionFlags & Qt::TextEditable) {
- QKeyEvent* ke = static_cast<QKeyEvent *>(e);
- if (ke->modifiers() == Qt::NoModifier
- || ke->modifiers() == Qt::ShiftModifier
- || ke->modifiers() == Qt::KeypadModifier) {
- if (ke->key() < Qt::Key_Escape) {
- ke->accept();
- } else {
- switch (ke->key()) {
- case Qt::Key_Return:
- case Qt::Key_Enter:
- case Qt::Key_Delete:
- case Qt::Key_Home:
- case Qt::Key_End:
- case Qt::Key_Backspace:
- case Qt::Key_Left:
- case Qt::Key_Right:
- case Qt::Key_Up:
- case Qt::Key_Down:
- case Qt::Key_Tab:
- ke->accept();
- default:
- break;
- }
- }
-#ifndef QT_NO_SHORTCUT
- } else if (ke == QKeySequence::Copy
- || ke == QKeySequence::Paste
- || ke == QKeySequence::Cut
- || ke == QKeySequence::Redo
- || ke == QKeySequence::Undo
- || ke == QKeySequence::MoveToNextWord
- || ke == QKeySequence::MoveToPreviousWord
- || ke == QKeySequence::MoveToStartOfDocument
- || ke == QKeySequence::MoveToEndOfDocument
- || ke == QKeySequence::SelectNextWord
- || ke == QKeySequence::SelectPreviousWord
- || ke == QKeySequence::SelectStartOfLine
- || ke == QKeySequence::SelectEndOfLine
- || ke == QKeySequence::SelectStartOfBlock
- || ke == QKeySequence::SelectEndOfBlock
- || ke == QKeySequence::SelectStartOfDocument
- || ke == QKeySequence::SelectEndOfDocument
- || ke == QKeySequence::SelectAll
- ) {
- ke->accept();
-#endif
- }
- }
- break;
- default:
- break;
- }
-}
-
-bool QTextControl::event(QEvent *e)
-{
- return QObject::event(e);
-}
-
-void QTextControl::timerEvent(QTimerEvent *e)
-{
- Q_D(QTextControl);
- if (e->timerId() == d->cursorBlinkTimer.timerId()) {
- d->cursorOn = !d->cursorOn;
-
- if (d->cursor.hasSelection())
- d->cursorOn &= (QApplication::style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected)
- != 0);
-
- d->repaintCursor();
- } else if (e->timerId() == d->trippleClickTimer.timerId()) {
- d->trippleClickTimer.stop();
- }
-}
-
-void QTextControl::setPlainText(const QString &text)
-{
- Q_D(QTextControl);
- d->setContent(Qt::PlainText, text);
-}
-
-void QTextControl::setHtml(const QString &text)
-{
- Q_D(QTextControl);
- d->setContent(Qt::RichText, text);
-}
-
-void QTextControlPrivate::keyPressEvent(QKeyEvent *e)
-{
- Q_Q(QTextControl);
-#ifndef QT_NO_SHORTCUT
- if (e == QKeySequence::SelectAll) {
- e->accept();
- q->selectAll();
- return;
- }
-#ifndef QT_NO_CLIPBOARD
- else if (e == QKeySequence::Copy) {
- e->accept();
- q->copy();
- return;
- }
-#endif
-#endif // QT_NO_SHORTCUT
-
- if (interactionFlags & Qt::TextSelectableByKeyboard
- && cursorMoveKeyEvent(e))
- goto accept;
-
- if (interactionFlags & Qt::LinksAccessibleByKeyboard) {
- if ((e->key() == Qt::Key_Return
- || e->key() == Qt::Key_Enter
-#ifdef QT_KEYPAD_NAVIGATION
- || e->key() == Qt::Key_Select
-#endif
- )
- && cursor.hasSelection()) {
-
- e->accept();
- activateLinkUnderCursor();
- return;
- }
- }
-
- if (!(interactionFlags & Qt::TextEditable)) {
- e->ignore();
- return;
- }
-
- if (e->key() == Qt::Key_Direction_L || e->key() == Qt::Key_Direction_R) {
- QTextBlockFormat fmt;
- fmt.setLayoutDirection((e->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft);
- cursor.mergeBlockFormat(fmt);
- goto accept;
- }
-
- // schedule a repaint of the region of the cursor, as when we move it we
- // want to make sure the old cursor disappears (not noticeable when moving
- // only a few pixels but noticeable when jumping between cells in tables for
- // example)
- repaintSelection();
-
- if (e->key() == Qt::Key_Backspace && !(e->modifiers() & ~Qt::ShiftModifier)) {
- QTextBlockFormat blockFmt = cursor.blockFormat();
- QTextList *list = cursor.currentList();
- if (list && cursor.atBlockStart() && !cursor.hasSelection()) {
- list->remove(cursor.block());
- } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
- blockFmt.setIndent(blockFmt.indent() - 1);
- cursor.setBlockFormat(blockFmt);
- } else {
- QTextCursor localCursor = cursor;
- localCursor.deletePreviousChar();
- }
- goto accept;
- }
-#ifndef QT_NO_SHORTCUT
- else if (e == QKeySequence::InsertParagraphSeparator) {
- cursor.insertBlock();
- e->accept();
- goto accept;
- } else if (e == QKeySequence::InsertLineSeparator) {
- cursor.insertText(QString(QChar::LineSeparator));
- e->accept();
- goto accept;
- }
-#endif
- if (false) {
- }
-#ifndef QT_NO_SHORTCUT
- else if (e == QKeySequence::Undo) {
- q->undo();
- }
- else if (e == QKeySequence::Redo) {
- q->redo();
- }
-#ifndef QT_NO_CLIPBOARD
- else if (e == QKeySequence::Cut) {
- q->cut();
- }
- else if (e == QKeySequence::Paste) {
- QClipboard::Mode mode = QClipboard::Clipboard;
-#ifdef Q_WS_X11
- if (e->modifiers() == (Qt::CTRL | Qt::SHIFT) && e->key() == Qt::Key_Insert)
- mode = QClipboard::Selection;
-#endif
- q->paste(mode);
- }
-#endif
- else if (e == QKeySequence::Delete) {
- QTextCursor localCursor = cursor;
- localCursor.deleteChar();
- }
- else if (e == QKeySequence::DeleteEndOfWord) {
- if (!cursor.hasSelection())
- cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
- }
- else if (e == QKeySequence::DeleteStartOfWord) {
- if (!cursor.hasSelection())
- cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
- }
- else if (e == QKeySequence::DeleteEndOfLine) {
- QTextBlock block = cursor.block();
- if (cursor.position() == block.position() + block.length() - 2)
- cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
- else
- cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
- }
-#endif // QT_NO_SHORTCUT
- else {
- goto process;
- }
- goto accept;
-
-process:
- {
- QString text = e->text();
- if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t'))) {
- if (overwriteMode
- // no need to call deleteChar() if we have a selection, insertText
- // does it already
- && !cursor.hasSelection()
- && !cursor.atBlockEnd())
- cursor.deleteChar();
-
- cursor.insertText(text);
- selectionChanged();
- } else {
- e->ignore();
- return;
- }
- }
-
- accept:
-
- e->accept();
- cursorOn = true;
-
- q->ensureCursorVisible();
-
- updateCurrentCharFormat();
-}
-
-QVariant QTextControl::loadResource(int type, const QUrl &name)
-{
-#ifdef QT_NO_TEXTEDIT
- Q_UNUSED(type);
- Q_UNUSED(name);
-#else
- if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(parent())) {
- QUrl resolvedName = textEdit->d_func()->resolveUrl(name);
- return textEdit->loadResource(type, resolvedName);
- }
-#endif
- return QVariant();
-}
-
-void QTextControlPrivate::_q_updateBlock(const QTextBlock &block)
-{
- Q_Q(QTextControl);
- QRectF br = q->blockBoundingRect(block);
- br.setRight(qreal(INT_MAX)); // the block might have shrunk
- emit q->updateRequest(br);
-}
-
-QRectF QTextControlPrivate::rectForPosition(int position) const
-{
- Q_Q(const QTextControl);
- const QTextBlock block = doc->findBlock(position);
- if (!block.isValid())
- return QRectF();
- const QAbstractTextDocumentLayout *docLayout = doc->documentLayout();
- const QTextLayout *layout = block.layout();
- const QPointF layoutPos = q->blockBoundingRect(block).topLeft();
- int relativePos = position - block.position();
- if (preeditCursor != 0) {
- int preeditPos = layout->preeditAreaPosition();
- if (relativePos == preeditPos)
- relativePos += preeditCursor;
- else if (relativePos > preeditPos)
- relativePos += layout->preeditAreaText().length();
- }
- QTextLine line = layout->lineForTextPosition(relativePos);
-
- int cursorWidth;
- {
- bool ok = false;
-#ifndef QT_NO_PROPERTIES
- cursorWidth = docLayout->property("cursorWidth").toInt(&ok);
-#endif
- if (!ok)
- cursorWidth = 1;
- }
-
- QRectF r;
-
- if (line.isValid()) {
- qreal x = line.cursorToX(relativePos);
- qreal w = 0;
- if (overwriteMode) {
- if (relativePos < line.textLength() - line.textStart())
- w = line.cursorToX(relativePos + 1) - x;
- else
- w = QFontMetrics(block.layout()->font()).width(QLatin1Char(' ')); // in sync with QTextLine::draw()
- }
- r = QRectF(layoutPos.x() + x, layoutPos.y() + line.y(),
- cursorWidth + w, line.height());
- } else {
- r = QRectF(layoutPos.x(), layoutPos.y(), cursorWidth, 10); // #### correct height
- }
-
- return r;
-}
-
-static inline bool firstFramePosLessThanCursorPos(QTextFrame *frame, int position)
-{
- return frame->firstPosition() < position;
-}
-
-static inline bool cursorPosLessThanLastFramePos(int position, QTextFrame *frame)
-{
- return position < frame->lastPosition();
-}
-
-static QRectF boundingRectOfFloatsInSelection(const QTextCursor &cursor)
-{
- QRectF r;
- QTextFrame *frame = cursor.currentFrame();
- const QList<QTextFrame *> children = frame->childFrames();
-
- const QList<QTextFrame *>::ConstIterator firstFrame = qLowerBound(children.constBegin(), children.constEnd(),
- cursor.selectionStart(), firstFramePosLessThanCursorPos);
- const QList<QTextFrame *>::ConstIterator lastFrame = qUpperBound(children.constBegin(), children.constEnd(),
- cursor.selectionEnd(), cursorPosLessThanLastFramePos);
- for (QList<QTextFrame *>::ConstIterator it = firstFrame; it != lastFrame; ++it) {
- if ((*it)->frameFormat().position() != QTextFrameFormat::InFlow)
- r |= frame->document()->documentLayout()->frameBoundingRect(*it);
- }
- return r;
-}
-
-QRectF QTextControl::selectionRect(const QTextCursor &cursor) const
-{
- Q_D(const QTextControl);
-
- QRectF r = d->rectForPosition(cursor.selectionStart());
-
- if (cursor.hasComplexSelection() && cursor.currentTable()) {
- QTextTable *table = cursor.currentTable();
-
- r = d->doc->documentLayout()->frameBoundingRect(table);
- /*
- int firstRow, numRows, firstColumn, numColumns;
- cursor.selectedTableCells(&firstRow, &numRows, &firstColumn, &numColumns);
-
- const QTextTableCell firstCell = table->cellAt(firstRow, firstColumn);
- const QTextTableCell lastCell = table->cellAt(firstRow + numRows - 1, firstColumn + numColumns - 1);
-
- const QAbstractTextDocumentLayout * const layout = doc->documentLayout();
-
- QRectF tableSelRect = layout->blockBoundingRect(firstCell.firstCursorPosition().block());
-
- for (int col = firstColumn; col < firstColumn + numColumns; ++col) {
- const QTextTableCell cell = table->cellAt(firstRow, col);
- const qreal y = layout->blockBoundingRect(cell.firstCursorPosition().block()).top();
-
- tableSelRect.setTop(qMin(tableSelRect.top(), y));
- }
-
- for (int row = firstRow; row < firstRow + numRows; ++row) {
- const QTextTableCell cell = table->cellAt(row, firstColumn);
- const qreal x = layout->blockBoundingRect(cell.firstCursorPosition().block()).left();
-
- tableSelRect.setLeft(qMin(tableSelRect.left(), x));
- }
-
- for (int col = firstColumn; col < firstColumn + numColumns; ++col) {
- const QTextTableCell cell = table->cellAt(firstRow + numRows - 1, col);
- const qreal y = layout->blockBoundingRect(cell.lastCursorPosition().block()).bottom();
-
- tableSelRect.setBottom(qMax(tableSelRect.bottom(), y));
- }
-
- for (int row = firstRow; row < firstRow + numRows; ++row) {
- const QTextTableCell cell = table->cellAt(row, firstColumn + numColumns - 1);
- const qreal x = layout->blockBoundingRect(cell.lastCursorPosition().block()).right();
-
- tableSelRect.setRight(qMax(tableSelRect.right(), x));
- }
-
- r = tableSelRect.toRect();
- */
- } else if (cursor.hasSelection()) {
- const int position = cursor.selectionStart();
- const int anchor = cursor.selectionEnd();
- const QTextBlock posBlock = d->doc->findBlock(position);
- const QTextBlock anchorBlock = d->doc->findBlock(anchor);
- if (posBlock == anchorBlock && posBlock.isValid() && posBlock.layout()->lineCount()) {
- const QTextLine posLine = posBlock.layout()->lineForTextPosition(position - posBlock.position());
- const QTextLine anchorLine = anchorBlock.layout()->lineForTextPosition(anchor - anchorBlock.position());
-
- const int firstLine = qMin(posLine.lineNumber(), anchorLine.lineNumber());
- const int lastLine = qMax(posLine.lineNumber(), anchorLine.lineNumber());
- const QTextLayout *layout = posBlock.layout();
- r = QRectF();
- for (int i = firstLine; i <= lastLine; ++i) {
- r |= layout->lineAt(i).rect();
- r |= layout->lineAt(i).naturalTextRect(); // might be bigger in the case of wrap not enabled
- }
- r.translate(blockBoundingRect(posBlock).topLeft());
- } else {
- QRectF anchorRect = d->rectForPosition(cursor.selectionEnd());
- r |= anchorRect;
- r |= boundingRectOfFloatsInSelection(cursor);
- QRectF frameRect(d->doc->documentLayout()->frameBoundingRect(cursor.currentFrame()));
- r.setLeft(frameRect.left());
- r.setRight(frameRect.right());
- }
- if (r.isValid())
- r.adjust(-1, -1, 1, 1);
- }
-
- return r;
-}
-
-QRectF QTextControl::selectionRect() const
-{
- Q_D(const QTextControl);
- return selectionRect(d->cursor);
-}
-
-void QTextControlPrivate::mousePressEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons, const QPoint &globalPos)
-{
- Q_Q(QTextControl);
-
- if (sendMouseEventToInputContext(
- e, QEvent::MouseButtonPress, button, pos, modifiers, buttons, globalPos)) {
- return;
- }
-
- if (interactionFlags & Qt::LinksAccessibleByMouse) {
- anchorOnMousePress = q->anchorAt(pos);
-
- if (cursorIsFocusIndicator) {
- cursorIsFocusIndicator = false;
- repaintSelection();
- cursor.clearSelection();
- }
- }
- if (!(button & Qt::LeftButton) ||
- !((interactionFlags & Qt::TextSelectableByMouse) || (interactionFlags & Qt::TextEditable))) {
- e->ignore();
- return;
- }
-
- cursorIsFocusIndicator = false;
- const QTextCursor oldSelection = cursor;
- const int oldCursorPos = cursor.position();
-
- mousePressed = (interactionFlags & Qt::TextSelectableByMouse);
-#ifndef QT_NO_DRAGANDDROP
- mightStartDrag = false;
-#endif
-
- if (trippleClickTimer.isActive()
- && ((pos - trippleClickPoint).toPoint().manhattanLength() < QApplication::startDragDistance())) {
-
- cursor.movePosition(QTextCursor::StartOfBlock);
- cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
- cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
- selectedBlockOnTrippleClick = cursor;
-
- anchorOnMousePress = QString();
-
- trippleClickTimer.stop();
- } else {
- int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
- if (cursorPos == -1) {
- e->ignore();
- return;
- }
-
- if (modifiers == Qt::ShiftModifier && (interactionFlags & Qt::TextSelectableByMouse)) {
- if (wordSelectionEnabled && !selectedWordOnDoubleClick.hasSelection()) {
- selectedWordOnDoubleClick = cursor;
- selectedWordOnDoubleClick.select(QTextCursor::WordUnderCursor);
- }
-
- if (selectedBlockOnTrippleClick.hasSelection())
- extendBlockwiseSelection(cursorPos);
- else if (selectedWordOnDoubleClick.hasSelection())
- extendWordwiseSelection(cursorPos, pos.x());
- else if (!wordSelectionEnabled)
- setCursorPosition(cursorPos, QTextCursor::KeepAnchor);
- } else {
-
- if (dragEnabled
- && cursor.hasSelection()
- && !cursorIsFocusIndicator
- && cursorPos >= cursor.selectionStart()
- && cursorPos <= cursor.selectionEnd()
- && q->hitTest(pos, Qt::ExactHit) != -1) {
-#ifndef QT_NO_DRAGANDDROP
- mightStartDrag = true;
- dragStartPos = pos.toPoint();
-#endif
- return;
- }
-
- setCursorPosition(cursorPos);
- }
- }
-
- if (interactionFlags & Qt::TextEditable) {
- q->ensureCursorVisible();
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
- _q_updateCurrentCharFormatAndSelection();
- } else {
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
- selectionChanged();
- }
- repaintOldAndNewSelection(oldSelection);
- hadSelectionOnMousePress = cursor.hasSelection();
-}
-
-void QTextControlPrivate::mouseMoveEvent(QEvent *e, Qt::MouseButton button, const QPointF &mousePos, Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons, const QPoint &globalPos)
-{
- Q_Q(QTextControl);
-
- if (sendMouseEventToInputContext(
- e, QEvent::MouseMove, button, mousePos, modifiers, buttons, globalPos)) {
- return;
- }
-
- if (interactionFlags & Qt::LinksAccessibleByMouse) {
- QString anchor = q->anchorAt(mousePos);
- if (anchor != highlightedAnchor) {
- highlightedAnchor = anchor;
- emit q->linkHovered(anchor);
- }
- }
-
- if (!(buttons & Qt::LeftButton))
- return;
-
- const bool editable = interactionFlags & Qt::TextEditable;
-
- if (!(mousePressed
- || editable
- || mightStartDrag
- || selectedWordOnDoubleClick.hasSelection()
- || selectedBlockOnTrippleClick.hasSelection()))
- return;
-
- const QTextCursor oldSelection = cursor;
- const int oldCursorPos = cursor.position();
-
- if (mightStartDrag) {
- if ((mousePos.toPoint() - dragStartPos).manhattanLength() > QApplication::startDragDistance())
- startDrag();
- return;
- }
-
- if (!mousePressed)
- return;
-
- const qreal mouseX = qreal(mousePos.x());
-
- int newCursorPos = q->hitTest(mousePos, Qt::FuzzyHit);
- if (newCursorPos == -1)
- return;
-
- if (wordSelectionEnabled && !selectedWordOnDoubleClick.hasSelection()) {
- selectedWordOnDoubleClick = cursor;
- selectedWordOnDoubleClick.select(QTextCursor::WordUnderCursor);
- }
-
- if (selectedBlockOnTrippleClick.hasSelection())
- extendBlockwiseSelection(newCursorPos);
- else if (selectedWordOnDoubleClick.hasSelection())
- extendWordwiseSelection(newCursorPos, mouseX);
- else
- setCursorPosition(newCursorPos, QTextCursor::KeepAnchor);
-
- if (interactionFlags & Qt::TextEditable) {
- // don't call ensureVisible for the visible cursor to avoid jumping
- // scrollbars. the autoscrolling ensures smooth scrolling if necessary.
- //q->ensureCursorVisible();
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
- _q_updateCurrentCharFormatAndSelection();
-#ifndef QT_NO_IM
- if (contextWidget) {
- if (QInputContext *ic = inputContext()) {
- ic->update();
- }
- }
-#endif //QT_NO_IM
- } else {
- //emit q->visibilityRequest(QRectF(mousePos, QSizeF(1, 1)));
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
- }
- selectionChanged(true);
- repaintOldAndNewSelection(oldSelection);
-}
-
-void QTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons, const QPoint &globalPos)
-{
- Q_Q(QTextControl);
-
- if (sendMouseEventToInputContext(
- e, QEvent::MouseButtonRelease, button, pos, modifiers, buttons, globalPos)) {
- return;
- }
-
- const QTextCursor oldSelection = cursor;
- const int oldCursorPos = cursor.position();
-
-#ifndef QT_NO_DRAGANDDROP
- if (mightStartDrag && (button & Qt::LeftButton)) {
- mousePressed = false;
- setCursorPosition(pos);
- cursor.clearSelection();
- selectionChanged();
- }
-#endif
- if (mousePressed) {
- mousePressed = false;
-#ifndef QT_NO_CLIPBOARD
- setClipboardSelection();
- selectionChanged(true);
- } else if (button == Qt::MidButton
- && (interactionFlags & Qt::TextEditable)
- && QApplication::clipboard()->supportsSelection()) {
- setCursorPosition(pos);
- const QMimeData *md = QApplication::clipboard()->mimeData(QClipboard::Selection);
- if (md)
- q->insertFromMimeData(md);
-#endif
- }
-
- repaintOldAndNewSelection(oldSelection);
-
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
-
- if (interactionFlags & Qt::LinksAccessibleByMouse) {
- if (!(button & Qt::LeftButton))
- return;
-
- const QString anchor = q->anchorAt(pos);
-
- if (anchor.isEmpty())
- return;
-
- if (!cursor.hasSelection()
- || (anchor == anchorOnMousePress && hadSelectionOnMousePress)) {
-
- const int anchorPos = q->hitTest(pos, Qt::ExactHit);
- if (anchorPos != -1) {
- cursor.setPosition(anchorPos);
-
- QString anchor = anchorOnMousePress;
- anchorOnMousePress = QString();
- activateLinkUnderCursor(anchor);
- }
- }
- }
-}
-
-void QTextControlPrivate::mouseDoubleClickEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos, Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons, const QPoint &globalPos)
-{
- Q_Q(QTextControl);
-
- if (sendMouseEventToInputContext(
- e, QEvent::MouseButtonDblClick, button, pos, modifiers, buttons, globalPos)) {
- return;
- }
-
- if (button != Qt::LeftButton
- || !(interactionFlags & Qt::TextSelectableByMouse)) {
- e->ignore();
- return;
- }
-
-#ifndef QT_NO_DRAGANDDROP
- mightStartDrag = false;
-#endif
- const QTextCursor oldSelection = cursor;
- setCursorPosition(pos);
- QTextLine line = currentTextLine(cursor);
- bool doEmit = false;
- if (line.isValid() && line.textLength()) {
- cursor.select(QTextCursor::WordUnderCursor);
- doEmit = true;
- }
- repaintOldAndNewSelection(oldSelection);
-
- cursorIsFocusIndicator = false;
- selectedWordOnDoubleClick = cursor;
-
- trippleClickPoint = pos;
- trippleClickTimer.start(QApplication::doubleClickInterval(), q);
- if (doEmit) {
- selectionChanged();
-#ifndef QT_NO_CLIPBOARD
- setClipboardSelection();
-#endif
- emit q->cursorPositionChanged();
- }
-}
-
-bool QTextControlPrivate::sendMouseEventToInputContext(
- QEvent *e, QEvent::Type eventType, Qt::MouseButton button, const QPointF &pos,
- Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPoint &globalPos)
-{
-#if !defined(QT_NO_IM)
- Q_Q(QTextControl);
-
- QTextLayout *layout = cursor.block().layout();
- if (contextWidget && layout && !layout->preeditAreaText().isEmpty()) {
- QInputContext *ctx = inputContext();
- int cursorPos = q->hitTest(pos, Qt::FuzzyHit) - cursor.position();
-
- if (cursorPos < 0 || cursorPos > layout->preeditAreaText().length()) {
- cursorPos = -1;
- // don't send move events outside the preedit area
- if (eventType == QEvent::MouseMove)
- return true;
- }
- if (ctx) {
- QMouseEvent ev(eventType, contextWidget->mapFromGlobal(globalPos), globalPos,
- button, buttons, modifiers);
- ctx->mouseHandler(cursorPos, &ev);
- e->setAccepted(ev.isAccepted());
- }
- if (!layout->preeditAreaText().isEmpty())
- return true;
- }
-#else
- Q_UNUSED(e);
- Q_UNUSED(eventType);
- Q_UNUSED(button);
- Q_UNUSED(pos);
- Q_UNUSED(modifiers);
- Q_UNUSED(buttons);
- Q_UNUSED(globalPos);
-#endif
- return false;
-}
-
-void QTextControlPrivate::contextMenuEvent(const QPoint &screenPos, const QPointF &docPos, QWidget *contextWidget)
-{
-#ifdef QT_NO_CONTEXTMENU
- Q_UNUSED(screenPos);
- Q_UNUSED(docPos);
- Q_UNUSED(contextWidget);
-#else
- Q_Q(QTextControl);
- if (!hasFocus)
- return;
- QMenu *menu = q->createStandardContextMenu(docPos, contextWidget);
- if (!menu)
- return;
- menu->setAttribute(Qt::WA_DeleteOnClose);
- menu->popup(screenPos);
-#endif
-}
-
-bool QTextControlPrivate::dragEnterEvent(QEvent *e, const QMimeData *mimeData)
-{
- Q_Q(QTextControl);
- if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData)) {
- e->ignore();
- return false;
- }
-
- dndFeedbackCursor = QTextCursor();
-
- return true; // accept proposed action
-}
-
-void QTextControlPrivate::dragLeaveEvent()
-{
- Q_Q(QTextControl);
-
- const QRectF crect = q->cursorRect(dndFeedbackCursor);
- dndFeedbackCursor = QTextCursor();
-
- if (crect.isValid())
- emit q->updateRequest(crect);
-}
-
-bool QTextControlPrivate::dragMoveEvent(QEvent *e, const QMimeData *mimeData, const QPointF &pos)
-{
- Q_Q(QTextControl);
- if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData)) {
- e->ignore();
- return false;
- }
-
- const int cursorPos = q->hitTest(pos, Qt::FuzzyHit);
- if (cursorPos != -1) {
- QRectF crect = q->cursorRect(dndFeedbackCursor);
- if (crect.isValid())
- emit q->updateRequest(crect);
-
- dndFeedbackCursor = cursor;
- dndFeedbackCursor.setPosition(cursorPos);
-
- crect = q->cursorRect(dndFeedbackCursor);
- emit q->updateRequest(crect);
- }
-
- return true; // accept proposed action
-}
-
-bool QTextControlPrivate::dropEvent(const QMimeData *mimeData, const QPointF &pos, Qt::DropAction dropAction, QWidget *source)
-{
- Q_Q(QTextControl);
- dndFeedbackCursor = QTextCursor();
-
- if (!(interactionFlags & Qt::TextEditable) || !q->canInsertFromMimeData(mimeData))
- return false;
-
- repaintSelection();
-
- QTextCursor insertionCursor = q->cursorForPosition(pos);
- insertionCursor.beginEditBlock();
-
- if (dropAction == Qt::MoveAction && source == contextWidget)
- cursor.removeSelectedText();
-
- cursor = insertionCursor;
- q->insertFromMimeData(mimeData);
- insertionCursor.endEditBlock();
- q->ensureCursorVisible();
- return true; // accept proposed action
-}
-
-void QTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
-{
- Q_Q(QTextControl);
- if (!(interactionFlags & Qt::TextEditable) || cursor.isNull()) {
- e->ignore();
- return;
- }
- bool isGettingInput = !e->commitString().isEmpty()
- || e->preeditString() != cursor.block().layout()->preeditAreaText()
- || e->replacementLength() > 0;
-
- cursor.beginEditBlock();
- if (isGettingInput) {
- cursor.removeSelectedText();
- }
-
- // insert commit string
- if (!e->commitString().isEmpty() || e->replacementLength()) {
- QTextCursor c = cursor;
- c.setPosition(c.position() + e->replacementStart());
- c.setPosition(c.position() + e->replacementLength(), QTextCursor::KeepAnchor);
- c.insertText(e->commitString());
- }
-
- for (int i = 0; i < e->attributes().size(); ++i) {
- const QInputMethodEvent::Attribute &a = e->attributes().at(i);
- if (a.type == QInputMethodEvent::Selection) {
- QTextCursor oldCursor = cursor;
- int blockStart = a.start + cursor.block().position();
- cursor.setPosition(blockStart, QTextCursor::MoveAnchor);
- cursor.setPosition(blockStart + a.length, QTextCursor::KeepAnchor);
- q->ensureCursorVisible();
- repaintOldAndNewSelection(oldCursor);
- }
- }
-
- QTextBlock block = cursor.block();
- QTextLayout *layout = block.layout();
- if (isGettingInput)
- layout->setPreeditArea(cursor.position() - block.position(), e->preeditString());
- QList<QTextLayout::FormatRange> overrides;
- const int oldPreeditCursor = preeditCursor;
- preeditCursor = e->preeditString().length();
- hideCursor = false;
- for (int i = 0; i < e->attributes().size(); ++i) {
- const QInputMethodEvent::Attribute &a = e->attributes().at(i);
- if (a.type == QInputMethodEvent::Cursor) {
- preeditCursor = a.start;
- hideCursor = !a.length;
- } else if (a.type == QInputMethodEvent::TextFormat) {
- QTextCharFormat f = qvariant_cast<QTextFormat>(a.value).toCharFormat();
- if (f.isValid()) {
- QTextLayout::FormatRange o;
- o.start = a.start + cursor.position() - block.position();
- o.length = a.length;
- o.format = f;
- overrides.append(o);
- }
- }
- }
- layout->setAdditionalFormats(overrides);
- cursor.endEditBlock();
- if (cursor.d)
- cursor.d->setX();
- if (oldPreeditCursor != preeditCursor)
- emit q->microFocusChanged();
-}
-
-QVariant QTextControl::inputMethodQuery(Qt::InputMethodQuery property) const
-{
- Q_D(const QTextControl);
- QTextBlock block = d->cursor.block();
- switch(property) {
- case Qt::ImMicroFocus:
- return cursorRect();
- case Qt::ImFont:
- return QVariant(d->cursor.charFormat().font());
- case Qt::ImCursorPosition:
- return QVariant(d->cursor.position() - block.position());
- case Qt::ImSurroundingText:
- return QVariant(block.text());
- case Qt::ImCurrentSelection:
- return QVariant(d->cursor.selectedText());
- case Qt::ImMaximumTextLength:
- return QVariant(); // No limit.
- case Qt::ImAnchorPosition:
- return QVariant(qBound(0, d->cursor.anchor() - block.position(), block.length()));
- default:
- return QVariant();
- }
-}
-
-void QTextControl::setFocus(bool focus, Qt::FocusReason reason)
-{
- QFocusEvent ev(focus ? QEvent::FocusIn : QEvent::FocusOut,
- reason);
- processEvent(&ev);
-}
-
-void QTextControlPrivate::focusEvent(QFocusEvent *e)
-{
- Q_Q(QTextControl);
- emit q->updateRequest(q->selectionRect());
- if (e->gotFocus()) {
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || (hasEditFocus && (e->reason() == Qt::PopupFocusReason
-#ifdef Q_OS_SYMBIAN
- || e->reason() == Qt::ActiveWindowFocusReason
-#endif
- ))) {
-#endif
- cursorOn = (interactionFlags & Qt::TextSelectableByKeyboard);
- if (interactionFlags & Qt::TextEditable) {
- setBlinkingCursorEnabled(true);
- }
-#ifdef QT_KEYPAD_NAVIGATION
- }
-#endif
- } else {
- setBlinkingCursorEnabled(false);
-
- if (cursorIsFocusIndicator
- && e->reason() != Qt::ActiveWindowFocusReason
- && e->reason() != Qt::PopupFocusReason
- && cursor.hasSelection()) {
- cursor.clearSelection();
- }
- }
- hasFocus = e->gotFocus();
-}
-
-QString QTextControlPrivate::anchorForCursor(const QTextCursor &anchorCursor) const
-{
- if (anchorCursor.hasSelection()) {
- QTextCursor cursor = anchorCursor;
- if (cursor.selectionStart() != cursor.position())
- cursor.setPosition(cursor.selectionStart());
- cursor.movePosition(QTextCursor::NextCharacter);
- QTextCharFormat fmt = cursor.charFormat();
- if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref))
- return fmt.stringProperty(QTextFormat::AnchorHref);
- }
- return QString();
-}
-
-#ifdef QT_KEYPAD_NAVIGATION
-void QTextControlPrivate::editFocusEvent(QEvent *e)
-{
- Q_Q(QTextControl);
-
- if (QApplication::keypadNavigationEnabled()) {
- if (e->type() == QEvent::EnterEditFocus && interactionFlags & Qt::TextEditable) {
- const QTextCursor oldSelection = cursor;
- const int oldCursorPos = cursor.position();
- const bool moved = cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
- q->ensureCursorVisible();
- if (moved) {
- if (cursor.position() != oldCursorPos)
- emit q->cursorPositionChanged();
- emit q->microFocusChanged();
- }
- selectionChanged();
- repaintOldAndNewSelection(oldSelection);
-
- setBlinkingCursorEnabled(true);
- } else
- setBlinkingCursorEnabled(false);
- }
-
- hasEditFocus = e->type() == QEvent::EnterEditFocus ? true : false;
-}
-#endif
-
-#ifndef QT_NO_CONTEXTMENU
-QMenu *QTextControl::createStandardContextMenu(const QPointF &pos, QWidget *parent)
-{
- Q_D(QTextControl);
-
- const bool showTextSelectionActions = d->interactionFlags & (Qt::TextEditable | Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
-
- d->linkToCopy = QString();
- if (!pos.isNull())
- d->linkToCopy = anchorAt(pos);
-
- if (d->linkToCopy.isEmpty() && !showTextSelectionActions)
- return 0;
-
- QMenu *menu = new QMenu(parent);
- QAction *a;
-
- if (d->interactionFlags & Qt::TextEditable) {
- a = menu->addAction(tr("&Undo") + ACCEL_KEY(QKeySequence::Undo), this, SLOT(undo()));
- a->setEnabled(d->doc->isUndoAvailable());
- a = menu->addAction(tr("&Redo") + ACCEL_KEY(QKeySequence::Redo), this, SLOT(redo()));
- a->setEnabled(d->doc->isRedoAvailable());
- menu->addSeparator();
-
- a = menu->addAction(tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut), this, SLOT(cut()));
- a->setEnabled(d->cursor.hasSelection());
- }
-
- if (showTextSelectionActions) {
- a = menu->addAction(tr("&Copy") + ACCEL_KEY(QKeySequence::Copy), this, SLOT(copy()));
- a->setEnabled(d->cursor.hasSelection());
- }
-
- if ((d->interactionFlags & Qt::LinksAccessibleByKeyboard)
- || (d->interactionFlags & Qt::LinksAccessibleByMouse)) {
-
- a = menu->addAction(tr("Copy &Link Location"), this, SLOT(_q_copyLink()));
- a->setEnabled(!d->linkToCopy.isEmpty());
- }
-
- if (d->interactionFlags & Qt::TextEditable) {
-#if !defined(QT_NO_CLIPBOARD)
- a = menu->addAction(tr("&Paste") + ACCEL_KEY(QKeySequence::Paste), this, SLOT(paste()));
- a->setEnabled(canPaste());
-#endif
- a = menu->addAction(tr("Delete"), this, SLOT(_q_deleteSelected()));
- a->setEnabled(d->cursor.hasSelection());
- }
-
-
- if (showTextSelectionActions) {
- menu->addSeparator();
- a = menu->addAction(tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll), this, SLOT(selectAll()));
- a->setEnabled(!d->doc->isEmpty());
- }
-
-#if !defined(QT_NO_IM)
- if (d->contextWidget) {
- QInputContext *qic = d->inputContext();
- if (qic) {
- QList<QAction *> imActions = qic->actions();
- for (int i = 0; i < imActions.size(); ++i)
- menu->addAction(imActions.at(i));
- }
- }
-#endif
-
-#if defined(Q_WS_WIN) || defined(Q_WS_X11)
- if ((d->interactionFlags & Qt::TextEditable) && qt_use_rtl_extensions) {
-#else
- if (d->interactionFlags & Qt::TextEditable) {
-#endif
- menu->addSeparator();
- QUnicodeControlCharacterMenu *ctrlCharacterMenu = new QUnicodeControlCharacterMenu(this, menu);
- menu->addMenu(ctrlCharacterMenu);
- }
-
- return menu;
-}
-#endif // QT_NO_CONTEXTMENU
-
-QTextCursor QTextControl::cursorForPosition(const QPointF &pos) const
-{
- Q_D(const QTextControl);
- int cursorPos = hitTest(pos, Qt::FuzzyHit);
- if (cursorPos == -1)
- cursorPos = 0;
- QTextCursor c(d->doc);
- c.setPosition(cursorPos);
- return c;
-}
-
-QRectF QTextControl::cursorRect(const QTextCursor &cursor) const
-{
- Q_D(const QTextControl);
- if (cursor.isNull())
- return QRectF();
-
- return d->rectForPosition(cursor.position());
-}
-
-QRectF QTextControl::cursorRect() const
-{
- Q_D(const QTextControl);
- return cursorRect(d->cursor);
-}
-
-QRectF QTextControlPrivate::cursorRectPlusUnicodeDirectionMarkers(const QTextCursor &cursor) const
-{
- if (cursor.isNull())
- return QRectF();
-
- return rectForPosition(cursor.position()).adjusted(-4, 0, 4, 0);
-}
-
-QString QTextControl::anchorAt(const QPointF &pos) const
-{
- Q_D(const QTextControl);
- return d->doc->documentLayout()->anchorAt(pos);
-}
-
-QString QTextControl::anchorAtCursor() const
-{
- Q_D(const QTextControl);
-
- return d->anchorForCursor(d->cursor);
-}
-
-bool QTextControl::overwriteMode() const
-{
- Q_D(const QTextControl);
- return d->overwriteMode;
-}
-
-void QTextControl::setOverwriteMode(bool overwrite)
-{
- Q_D(QTextControl);
- d->overwriteMode = overwrite;
-}
-
-int QTextControl::cursorWidth() const
-{
-#ifndef QT_NO_PROPERTIES
- Q_D(const QTextControl);
- return d->doc->documentLayout()->property("cursorWidth").toInt();
-#else
- return 1;
-#endif
-}
-
-void QTextControl::setCursorWidth(int width)
-{
- Q_D(QTextControl);
-#ifdef QT_NO_PROPERTIES
- Q_UNUSED(width);
-#else
- if (width == -1)
- width = QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth);
- d->doc->documentLayout()->setProperty("cursorWidth", width);
-#endif
- d->repaintCursor();
-}
-
-bool QTextControl::acceptRichText() const
-{
- Q_D(const QTextControl);
- return d->acceptRichText;
-}
-
-void QTextControl::setAcceptRichText(bool accept)
-{
- Q_D(QTextControl);
- d->acceptRichText = accept;
-}
-
-#ifndef QT_NO_TEXTEDIT
-
-void QTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections)
-{
- Q_D(QTextControl);
-
- QHash<int, int> hash;
- for (int i = 0; i < d->extraSelections.count(); ++i) {
- const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(i);
- hash.insertMulti(esel.cursor.anchor(), i);
- }
-
- for (int i = 0; i < selections.count(); ++i) {
- const QTextEdit::ExtraSelection &sel = selections.at(i);
- QHash<int, int>::iterator it = hash.find(sel.cursor.anchor());
- if (it != hash.end()) {
- const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
- if (esel.cursor.position() == sel.cursor.position()
- && esel.format == sel.format) {
- hash.erase(it);
- continue;
- }
- }
- QRectF r = selectionRect(sel.cursor);
- if (sel.format.boolProperty(QTextFormat::FullWidthSelection)) {
- r.setLeft(0);
- r.setWidth(qreal(INT_MAX));
- }
- emit updateRequest(r);
- }
-
- for (QHash<int, int>::iterator it = hash.begin(); it != hash.end(); ++it) {
- const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(it.value());
- QRectF r = selectionRect(esel.cursor);
- if (esel.format.boolProperty(QTextFormat::FullWidthSelection)) {
- r.setLeft(0);
- r.setWidth(qreal(INT_MAX));
- }
- emit updateRequest(r);
- }
-
- d->extraSelections.resize(selections.count());
- for (int i = 0; i < selections.count(); ++i) {
- d->extraSelections[i].cursor = selections.at(i).cursor;
- d->extraSelections[i].format = selections.at(i).format;
- }
-}
-
-QList<QTextEdit::ExtraSelection> QTextControl::extraSelections() const
-{
- Q_D(const QTextControl);
- QList<QTextEdit::ExtraSelection> selections;
- for (int i = 0; i < d->extraSelections.count(); ++i) {
- QTextEdit::ExtraSelection sel;
- sel.cursor = d->extraSelections.at(i).cursor;
- sel.format = d->extraSelections.at(i).format;
- selections.append(sel);
- }
- return selections;
-}
-
-#endif // QT_NO_TEXTEDIT
-
-void QTextControl::setTextWidth(qreal width)
-{
- Q_D(QTextControl);
- d->doc->setTextWidth(width);
-}
-
-qreal QTextControl::textWidth() const
-{
- Q_D(const QTextControl);
- return d->doc->textWidth();
-}
-
-QSizeF QTextControl::size() const
-{
- Q_D(const QTextControl);
- return d->doc->size();
-}
-
-void QTextControl::setOpenExternalLinks(bool open)
-{
- Q_D(QTextControl);
- d->openExternalLinks = open;
-}
-
-bool QTextControl::openExternalLinks() const
-{
- Q_D(const QTextControl);
- return d->openExternalLinks;
-}
-
-bool QTextControl::ignoreUnusedNavigationEvents() const
-{
- Q_D(const QTextControl);
- return d->ignoreUnusedNavigationEvents;
-}
-
-void QTextControl::setIgnoreUnusedNavigationEvents(bool ignore)
-{
- Q_D(QTextControl);
- d->ignoreUnusedNavigationEvents = ignore;
-}
-
-void QTextControl::moveCursor(QTextCursor::MoveOperation op, QTextCursor::MoveMode mode)
-{
- Q_D(QTextControl);
- const QTextCursor oldSelection = d->cursor;
- const bool moved = d->cursor.movePosition(op, mode);
- d->_q_updateCurrentCharFormatAndSelection();
- ensureCursorVisible();
- d->repaintOldAndNewSelection(oldSelection);
- if (moved)
- emit cursorPositionChanged();
-}
-
-bool QTextControl::canPaste() const
-{
-#ifndef QT_NO_CLIPBOARD
- Q_D(const QTextControl);
- if (d->interactionFlags & Qt::TextEditable) {
- const QMimeData *md = QApplication::clipboard()->mimeData();
- return md && canInsertFromMimeData(md);
- }
-#endif
- return false;
-}
-
-void QTextControl::setCursorIsFocusIndicator(bool b)
-{
- Q_D(QTextControl);
- d->cursorIsFocusIndicator = b;
- d->repaintCursor();
-}
-
-bool QTextControl::cursorIsFocusIndicator() const
-{
- Q_D(const QTextControl);
- return d->cursorIsFocusIndicator;
-}
-
-
-void QTextControl::setDragEnabled(bool enabled)
-{
- Q_D(QTextControl);
- d->dragEnabled = enabled;
-}
-
-bool QTextControl::isDragEnabled() const
-{
- Q_D(const QTextControl);
- return d->dragEnabled;
-}
-
-void QTextControl::setWordSelectionEnabled(bool enabled)
-{
- Q_D(QTextControl);
- d->wordSelectionEnabled = enabled;
-}
-
-bool QTextControl::isWordSelectionEnabled() const
-{
- Q_D(const QTextControl);
- return d->wordSelectionEnabled;
-}
-
-#ifndef QT_NO_PRINTER
-void QTextControl::print(QPrinter *printer) const
-{
-#ifndef QT_NO_PRINTER
- Q_D(const QTextControl);
- if (!printer || !printer->isValid())
- return;
- QTextDocument *tempDoc = 0;
- const QTextDocument *doc = d->doc;
- if (printer->printRange() == QPrinter::Selection) {
- if (!d->cursor.hasSelection())
- return;
- tempDoc = new QTextDocument(const_cast<QTextDocument *>(doc));
- tempDoc->setMetaInformation(QTextDocument::DocumentTitle, doc->metaInformation(QTextDocument::DocumentTitle));
- tempDoc->setPageSize(doc->pageSize());
- tempDoc->setDefaultFont(doc->defaultFont());
- tempDoc->setUseDesignMetrics(doc->useDesignMetrics());
- QTextCursor(tempDoc).insertFragment(d->cursor.selection());
- doc = tempDoc;
-
- // copy the custom object handlers
- doc->documentLayout()->d_func()->handlers = d->doc->documentLayout()->d_func()->handlers;
- }
- doc->print(printer);
- delete tempDoc;
-#endif
-}
-#endif // QT_NO_PRINTER
-
-QMimeData *QTextControl::createMimeDataFromSelection() const
-{
- Q_D(const QTextControl);
- const QTextDocumentFragment fragment(d->cursor);
- return new QTextEditMimeData(fragment);
-}
-
-bool QTextControl::canInsertFromMimeData(const QMimeData *source) const
-{
- Q_D(const QTextControl);
- if (d->acceptRichText)
- return (source->hasText() && !source->text().isEmpty())
- || source->hasHtml()
- || source->hasFormat(QLatin1String("application/x-qrichtext"))
- || source->hasFormat(QLatin1String("application/x-qt-richtext"));
- else
- return source->hasText() && !source->text().isEmpty();
-}
-
-void QTextControl::insertFromMimeData(const QMimeData *source)
-{
- Q_D(QTextControl);
- if (!(d->interactionFlags & Qt::TextEditable) || !source)
- return;
-
- bool hasData = false;
- QTextDocumentFragment fragment;
-#ifndef QT_NO_TEXTHTMLPARSER
- if (source->hasFormat(QLatin1String("application/x-qrichtext")) && d->acceptRichText) {
- // x-qrichtext is always UTF-8 (taken from Qt3 since we don't use it anymore).
- QString richtext = QString::fromUtf8(source->data(QLatin1String("application/x-qrichtext")));
- richtext.prepend(QLatin1String("<meta name=\"qrichtext\" content=\"1\" />"));
- fragment = QTextDocumentFragment::fromHtml(richtext, d->doc);
- hasData = true;
- } else if (source->hasHtml() && d->acceptRichText) {
- fragment = QTextDocumentFragment::fromHtml(source->html(), d->doc);
- hasData = true;
- } else {
- QString text = source->text();
- if (!text.isNull()) {
- fragment = QTextDocumentFragment::fromPlainText(text);
- hasData = true;
- }
- }
-#else
- fragment = QTextDocumentFragment::fromPlainText(source->text());
-#endif // QT_NO_TEXTHTMLPARSER
-
- if (hasData)
- d->cursor.insertFragment(fragment);
- ensureCursorVisible();
-}
-
-bool QTextControl::findNextPrevAnchor(const QTextCursor &startCursor, bool next, QTextCursor &newAnchor)
-{
- Q_D(QTextControl);
-
- int anchorStart = -1;
- QString anchorHref;
- int anchorEnd = -1;
-
- if (next) {
- const int startPos = startCursor.selectionEnd();
-
- QTextBlock block = d->doc->findBlock(startPos);
- QTextBlock::Iterator it = block.begin();
-
- while (!it.atEnd() && it.fragment().position() < startPos)
- ++it;
-
- while (block.isValid()) {
- anchorStart = -1;
-
- // find next anchor
- for (; !it.atEnd(); ++it) {
- const QTextFragment fragment = it.fragment();
- const QTextCharFormat fmt = fragment.charFormat();
-
- if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref)) {
- anchorStart = fragment.position();
- anchorHref = fmt.anchorHref();
- break;
- }
- }
-
- if (anchorStart != -1) {
- anchorEnd = -1;
-
- // find next non-anchor fragment
- for (; !it.atEnd(); ++it) {
- const QTextFragment fragment = it.fragment();
- const QTextCharFormat fmt = fragment.charFormat();
-
- if (!fmt.isAnchor() || fmt.anchorHref() != anchorHref) {
- anchorEnd = fragment.position();
- break;
- }
- }
-
- if (anchorEnd == -1)
- anchorEnd = block.position() + block.length() - 1;
-
- // make found selection
- break;
- }
-
- block = block.next();
- it = block.begin();
- }
- } else {
- int startPos = startCursor.selectionStart();
- if (startPos > 0)
- --startPos;
-
- QTextBlock block = d->doc->findBlock(startPos);
- QTextBlock::Iterator blockStart = block.begin();
- QTextBlock::Iterator it = block.end();
-
- if (startPos == block.position()) {
- it = block.begin();
- } else {
- do {
- if (it == blockStart) {
- it = QTextBlock::Iterator();
- block = QTextBlock();
- } else {
- --it;
- }
- } while (!it.atEnd() && it.fragment().position() + it.fragment().length() - 1 > startPos);
- }
-
- while (block.isValid()) {
- anchorStart = -1;
-
- if (!it.atEnd()) {
- do {
- const QTextFragment fragment = it.fragment();
- const QTextCharFormat fmt = fragment.charFormat();
-
- if (fmt.isAnchor() && fmt.hasProperty(QTextFormat::AnchorHref)) {
- anchorStart = fragment.position() + fragment.length();
- anchorHref = fmt.anchorHref();
- break;
- }
-
- if (it == blockStart)
- it = QTextBlock::Iterator();
- else
- --it;
- } while (!it.atEnd());
- }
-
- if (anchorStart != -1 && !it.atEnd()) {
- anchorEnd = -1;
-
- do {
- const QTextFragment fragment = it.fragment();
- const QTextCharFormat fmt = fragment.charFormat();
-
- if (!fmt.isAnchor() || fmt.anchorHref() != anchorHref) {
- anchorEnd = fragment.position() + fragment.length();
- break;
- }
-
- if (it == blockStart)
- it = QTextBlock::Iterator();
- else
- --it;
- } while (!it.atEnd());
-
- if (anchorEnd == -1)
- anchorEnd = qMax(0, block.position());
-
- break;
- }
-
- block = block.previous();
- it = block.end();
- if (it != block.begin())
- --it;
- blockStart = block.begin();
- }
-
- }
-
- if (anchorStart != -1 && anchorEnd != -1) {
- newAnchor = d->cursor;
- newAnchor.setPosition(anchorStart);
- newAnchor.setPosition(anchorEnd, QTextCursor::KeepAnchor);
- return true;
- }
-
- return false;
-}
-
-void QTextControlPrivate::activateLinkUnderCursor(QString href)
-{
- QTextCursor oldCursor = cursor;
-
- if (href.isEmpty()) {
- QTextCursor tmp = cursor;
- if (tmp.selectionStart() != tmp.position())
- tmp.setPosition(tmp.selectionStart());
- tmp.movePosition(QTextCursor::NextCharacter);
- href = tmp.charFormat().anchorHref();
- }
- if (href.isEmpty())
- return;
-
- if (!cursor.hasSelection()) {
- QTextBlock block = cursor.block();
- const int cursorPos = cursor.position();
-
- QTextBlock::Iterator it = block.begin();
- QTextBlock::Iterator linkFragment;
-
- for (; !it.atEnd(); ++it) {
- QTextFragment fragment = it.fragment();
- const int fragmentPos = fragment.position();
- if (fragmentPos <= cursorPos &&
- fragmentPos + fragment.length() > cursorPos) {
- linkFragment = it;
- break;
- }
- }
-
- if (!linkFragment.atEnd()) {
- it = linkFragment;
- cursor.setPosition(it.fragment().position());
- if (it != block.begin()) {
- do {
- --it;
- QTextFragment fragment = it.fragment();
- if (fragment.charFormat().anchorHref() != href)
- break;
- cursor.setPosition(fragment.position());
- } while (it != block.begin());
- }
-
- for (it = linkFragment; !it.atEnd(); ++it) {
- QTextFragment fragment = it.fragment();
- if (fragment.charFormat().anchorHref() != href)
- break;
- cursor.setPosition(fragment.position() + fragment.length(), QTextCursor::KeepAnchor);
- }
- }
- }
-
- if (hasFocus) {
- cursorIsFocusIndicator = true;
- } else {
- cursorIsFocusIndicator = false;
- cursor.clearSelection();
- }
- repaintOldAndNewSelection(oldCursor);
-
-#ifndef QT_NO_DESKTOPSERVICES
- if (openExternalLinks)
- QDesktopServices::openUrl(href);
- else
-#endif
- emit q_func()->linkActivated(href);
-}
-
-#ifndef QT_NO_TOOLTIP
-void QTextControlPrivate::showToolTip(const QPoint &globalPos, const QPointF &pos, QWidget *contextWidget)
-{
- const QString toolTip = q_func()->cursorForPosition(pos).charFormat().toolTip();
- if (toolTip.isEmpty())
- return;
- QToolTip::showText(globalPos, toolTip, contextWidget);
-}
-#endif // QT_NO_TOOLTIP
-
-bool QTextControl::setFocusToNextOrPreviousAnchor(bool next)
-{
- Q_D(QTextControl);
-
- if (!(d->interactionFlags & Qt::LinksAccessibleByKeyboard))
- return false;
-
- QRectF crect = selectionRect();
- emit updateRequest(crect);
-
- // If we don't have a current anchor, we start from the start/end
- if (!d->cursor.hasSelection()) {
- d->cursor = QTextCursor(d->doc);
- if (next)
- d->cursor.movePosition(QTextCursor::Start);
- else
- d->cursor.movePosition(QTextCursor::End);
- }
-
- QTextCursor newAnchor;
- if (findNextPrevAnchor(d->cursor, next, newAnchor)) {
- d->cursor = newAnchor;
- d->cursorIsFocusIndicator = true;
- } else {
- d->cursor.clearSelection();
- }
-
- if (d->cursor.hasSelection()) {
- crect = selectionRect();
- emit updateRequest(crect);
- emit visibilityRequest(crect);
- return true;
- } else {
- return false;
- }
-}
-
-bool QTextControl::setFocusToAnchor(const QTextCursor &newCursor)
-{
- Q_D(QTextControl);
-
- if (!(d->interactionFlags & Qt::LinksAccessibleByKeyboard))
- return false;
-
- // Verify that this is an anchor.
- const QString anchorHref = d->anchorForCursor(newCursor);
- if (anchorHref.isEmpty())
- return false;
-
- // and process it
- QRectF crect = selectionRect();
- emit updateRequest(crect);
-
- d->cursor.setPosition(newCursor.selectionStart());
- d->cursor.setPosition(newCursor.selectionEnd(), QTextCursor::KeepAnchor);
- d->cursorIsFocusIndicator = true;
-
- crect = selectionRect();
- emit updateRequest(crect);
- emit visibilityRequest(crect);
- return true;
-}
-
-void QTextControl::setTextInteractionFlags(Qt::TextInteractionFlags flags)
-{
- Q_D(QTextControl);
- if (flags == d->interactionFlags)
- return;
- d->interactionFlags = flags;
-
- if (d->hasFocus)
- d->setBlinkingCursorEnabled(flags & Qt::TextEditable);
-}
-
-Qt::TextInteractionFlags QTextControl::textInteractionFlags() const
-{
- Q_D(const QTextControl);
- return d->interactionFlags;
-}
-
-void QTextControl::mergeCurrentCharFormat(const QTextCharFormat &modifier)
-{
- Q_D(QTextControl);
- d->cursor.mergeCharFormat(modifier);
- d->updateCurrentCharFormat();
-}
-
-void QTextControl::setCurrentCharFormat(const QTextCharFormat &format)
-{
- Q_D(QTextControl);
- d->cursor.setCharFormat(format);
- d->updateCurrentCharFormat();
-}
-
-QTextCharFormat QTextControl::currentCharFormat() const
-{
- Q_D(const QTextControl);
- return d->cursor.charFormat();
-}
-
-void QTextControl::insertPlainText(const QString &text)
-{
- Q_D(QTextControl);
- d->cursor.insertText(text);
-}
-
-#ifndef QT_NO_TEXTHTMLPARSER
-void QTextControl::insertHtml(const QString &text)
-{
- Q_D(QTextControl);
- d->cursor.insertHtml(text);
-}
-#endif // QT_NO_TEXTHTMLPARSER
-
-QPointF QTextControl::anchorPosition(const QString &name) const
-{
- Q_D(const QTextControl);
- if (name.isEmpty())
- return QPointF();
-
- QRectF r;
- for (QTextBlock block = d->doc->begin(); block.isValid(); block = block.next()) {
- QTextCharFormat format = block.charFormat();
- if (format.isAnchor() && format.anchorNames().contains(name)) {
- r = d->rectForPosition(block.position());
- break;
- }
-
- for (QTextBlock::Iterator it = block.begin(); !it.atEnd(); ++it) {
- QTextFragment fragment = it.fragment();
- format = fragment.charFormat();
- if (format.isAnchor() && format.anchorNames().contains(name)) {
- r = d->rectForPosition(fragment.position());
- block = QTextBlock();
- break;
- }
- }
- }
- if (!r.isValid())
- return QPointF();
- return QPointF(0, r.top());
-}
-
-void QTextControl::adjustSize()
-{
- Q_D(QTextControl);
- d->doc->adjustSize();
-}
-
-bool QTextControl::find(const QString &exp, QTextDocument::FindFlags options)
-{
- Q_D(QTextControl);
- QTextCursor search = d->doc->find(exp, d->cursor, options);
- if (search.isNull())
- return false;
-
- setTextCursor(search);
- return true;
-}
-
-
-
-void QTextControlPrivate::append(const QString &text, Qt::TextFormat format)
-{
- QTextCursor tmp(doc);
- tmp.beginEditBlock();
- tmp.movePosition(QTextCursor::End);
-
- if (!doc->isEmpty())
- tmp.insertBlock(cursor.blockFormat(), cursor.charFormat());
- else
- tmp.setCharFormat(cursor.charFormat());
-
- // preserve the char format
- QTextCharFormat oldCharFormat = cursor.charFormat();
-
-#ifndef QT_NO_TEXTHTMLPARSER
- if (format == Qt::RichText || (format == Qt::AutoText && Qt::mightBeRichText(text))) {
- tmp.insertHtml(text);
- } else {
- tmp.insertText(text);
- }
-#else
- tmp.insertText(text);
-#endif // QT_NO_TEXTHTMLPARSER
- if (!cursor.hasSelection())
- cursor.setCharFormat(oldCharFormat);
-
- tmp.endEditBlock();
-}
-
-void QTextControl::append(const QString &text)
-{
- Q_D(QTextControl);
- d->append(text, Qt::AutoText);
-}
-
-void QTextControl::appendHtml(const QString &html)
-{
- Q_D(QTextControl);
- d->append(html, Qt::RichText);
-}
-
-void QTextControl::appendPlainText(const QString &text)
-{
- Q_D(QTextControl);
- d->append(text, Qt::PlainText);
-}
-
-
-void QTextControl::ensureCursorVisible()
-{
- Q_D(QTextControl);
- QRectF crect = d->rectForPosition(d->cursor.position()).adjusted(-5, 0, 5, 0);
- emit visibilityRequest(crect);
- emit microFocusChanged();
-}
-
-QPalette QTextControl::palette() const
-{
- Q_D(const QTextControl);
- return d->palette;
-}
-
-void QTextControl::setPalette(const QPalette &pal)
-{
- Q_D(QTextControl);
- d->palette = pal;
-}
-
-QAbstractTextDocumentLayout::PaintContext QTextControl::getPaintContext(QWidget *widget) const
-{
- Q_D(const QTextControl);
-
- QAbstractTextDocumentLayout::PaintContext ctx;
-
- ctx.selections = d->extraSelections;
- ctx.palette = d->palette;
- if (d->cursorOn && d->isEnabled) {
- if (d->hideCursor)
- ctx.cursorPosition = -1;
- else if (d->preeditCursor != 0)
- ctx.cursorPosition = - (d->preeditCursor + 2);
- else
- ctx.cursorPosition = d->cursor.position();
- }
-
- if (!d->dndFeedbackCursor.isNull())
- ctx.cursorPosition = d->dndFeedbackCursor.position();
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || d->hasEditFocus)
-#endif
- if (d->cursor.hasSelection()) {
- QAbstractTextDocumentLayout::Selection selection;
- selection.cursor = d->cursor;
- if (d->cursorIsFocusIndicator) {
- QStyleOption opt;
- opt.palette = ctx.palette;
- QStyleHintReturnVariant ret;
- QStyle *style = QApplication::style();
- if (widget)
- style = widget->style();
- style->styleHint(QStyle::SH_TextControl_FocusIndicatorTextCharFormat, &opt, widget, &ret);
- selection.format = qvariant_cast<QTextFormat>(ret.variant).toCharFormat();
- } else {
- QPalette::ColorGroup cg = d->hasFocus ? QPalette::Active : QPalette::Inactive;
- selection.format.setBackground(ctx.palette.brush(cg, QPalette::Highlight));
- selection.format.setForeground(ctx.palette.brush(cg, QPalette::HighlightedText));
- QStyleOption opt;
- QStyle *style = QApplication::style();
- if (widget) {
- opt.initFrom(widget);
- style = widget->style();
- }
- if (style->styleHint(QStyle::SH_RichText_FullWidthSelection, &opt, widget))
- selection.format.setProperty(QTextFormat::FullWidthSelection, true);
- }
- ctx.selections.append(selection);
- }
-
- return ctx;
-}
-
-void QTextControl::drawContents(QPainter *p, const QRectF &rect, QWidget *widget)
-{
- Q_D(QTextControl);
- p->save();
- QAbstractTextDocumentLayout::PaintContext ctx = getPaintContext(widget);
- if (rect.isValid())
- p->setClipRect(rect, Qt::IntersectClip);
- ctx.clip = rect;
-
- d->doc->documentLayout()->draw(p, ctx);
- p->restore();
-}
-
-void QTextControlPrivate::_q_copyLink()
-{
-#ifndef QT_NO_CLIPBOARD
- QMimeData *md = new QMimeData;
- md->setText(linkToCopy);
- QApplication::clipboard()->setMimeData(md);
-#endif
-}
-
-QInputContext *QTextControlPrivate::inputContext()
-{
- QInputContext *ctx = contextWidget->inputContext();
- if (!ctx && contextWidget->parentWidget())
- ctx = contextWidget->parentWidget()->inputContext();
- return ctx;
-}
-
-int QTextControl::hitTest(const QPointF &point, Qt::HitTestAccuracy accuracy) const
-{
- Q_D(const QTextControl);
- return d->doc->documentLayout()->hitTest(point, accuracy);
-}
-
-QRectF QTextControl::blockBoundingRect(const QTextBlock &block) const
-{
- Q_D(const QTextControl);
- return d->doc->documentLayout()->blockBoundingRect(block);
-}
-
-#ifndef QT_NO_CONTEXTMENU
-#define NUM_CONTROL_CHARACTERS 10
-const struct QUnicodeControlCharacter {
- const char *text;
- ushort character;
-} qt_controlCharacters[NUM_CONTROL_CHARACTERS] = {
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRM Left-to-right mark"), 0x200e },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLM Right-to-left mark"), 0x200f },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWJ Zero width joiner"), 0x200d },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWNJ Zero width non-joiner"), 0x200c },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "ZWSP Zero width space"), 0x200b },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRE Start of left-to-right embedding"), 0x202a },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLE Start of right-to-left embedding"), 0x202b },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "LRO Start of left-to-right override"), 0x202d },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "RLO Start of right-to-left override"), 0x202e },
- { QT_TRANSLATE_NOOP("QUnicodeControlCharacterMenu", "PDF Pop directional formatting"), 0x202c },
-};
-
-QUnicodeControlCharacterMenu::QUnicodeControlCharacterMenu(QObject *_editWidget, QWidget *parent)
- : QMenu(parent), editWidget(_editWidget)
-{
- setTitle(tr("Insert Unicode control character"));
- for (int i = 0; i < NUM_CONTROL_CHARACTERS; ++i) {
- addAction(tr(qt_controlCharacters[i].text), this, SLOT(menuActionTriggered()));
- }
-}
-
-void QUnicodeControlCharacterMenu::menuActionTriggered()
-{
- QAction *a = qobject_cast<QAction *>(sender());
- int idx = actions().indexOf(a);
- if (idx < 0 || idx >= NUM_CONTROL_CHARACTERS)
- return;
- QChar c(qt_controlCharacters[idx].character);
- QString str(c);
-
-#ifndef QT_NO_TEXTEDIT
- if (QTextEdit *edit = qobject_cast<QTextEdit *>(editWidget)) {
- edit->insertPlainText(str);
- return;
- }
-#endif
- if (QTextControl *control = qobject_cast<QTextControl *>(editWidget)) {
- control->insertPlainText(str);
- }
-#ifndef QT_NO_LINEEDIT
- if (QLineEdit *edit = qobject_cast<QLineEdit *>(editWidget)) {
- edit->insert(str);
- return;
- }
-#endif
-}
-#endif // QT_NO_CONTEXTMENU
-
-QStringList QTextEditMimeData::formats() const
-{
- if (!fragment.isEmpty())
- return QStringList() << QString::fromLatin1("text/plain") << QString::fromLatin1("text/html")
-#ifndef QT_NO_TEXTODFWRITER
- << QString::fromLatin1("application/vnd.oasis.opendocument.text")
-#endif
- ;
- else
- return QMimeData::formats();
-}
-
-QVariant QTextEditMimeData::retrieveData(const QString &mimeType, QVariant::Type type) const
-{
- if (!fragment.isEmpty())
- setup();
- return QMimeData::retrieveData(mimeType, type);
-}
-
-void QTextEditMimeData::setup() const
-{
- QTextEditMimeData *that = const_cast<QTextEditMimeData *>(this);
-#ifndef QT_NO_TEXTHTMLPARSER
- that->setData(QLatin1String("text/html"), fragment.toHtml("utf-8").toUtf8());
-#endif
-#ifndef QT_NO_TEXTODFWRITER
- {
- QBuffer buffer;
- QTextDocumentWriter writer(&buffer, "ODF");
- writer.write(fragment);
- buffer.close();
- that->setData(QLatin1String("application/vnd.oasis.opendocument.text"), buffer.data());
- }
-#endif
- that->setText(fragment.toPlainText());
- fragment = QTextDocumentFragment();
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtextcontrol_p.cpp"
-
-#endif // QT_NO_TEXTCONTROL
diff --git a/src/gui/to_be_moved/qtextcontrol_p.h b/src/gui/to_be_moved/qtextcontrol_p.h
deleted file mode 100644
index dce0ca90a5..0000000000
--- a/src/gui/to_be_moved/qtextcontrol_p.h
+++ /dev/null
@@ -1,307 +0,0 @@
-/****************************************************************************
-**
-** 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 QTEXTCONTROL_P_H
-#define QTEXTCONTROL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/qtextdocument.h>
-#include <QtGui/qtextoption.h>
-#include <QtGui/qtextcursor.h>
-#include <QtGui/qtextformat.h>
-#include <QtGui/qtextedit.h>
-#include <QtGui/qmenu.h>
-#include <QtCore/qrect.h>
-#include <QtGui/qabstracttextdocumentlayout.h>
-#include <QtGui/qtextdocumentfragment.h>
-#include <QtGui/qclipboard.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStyleSheet;
-class QTextDocument;
-class QMenu;
-class QTextControlPrivate;
-class QMimeData;
-class QAbstractScrollArea;
-class QEvent;
-class QTimerEvent;
-
-class Q_GUI_EXPORT QTextControl : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QTextControl)
-#ifndef QT_NO_TEXTHTMLPARSER
- Q_PROPERTY(QString html READ toHtml WRITE setHtml NOTIFY textChanged USER true)
-#endif
- Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
- Q_PROPERTY(bool acceptRichText READ acceptRichText WRITE setAcceptRichText)
- Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
- Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
- Q_PROPERTY(bool ignoreUnusedNavigationEvents READ ignoreUnusedNavigationEvents WRITE setIgnoreUnusedNavigationEvents)
-public:
- explicit QTextControl(QObject *parent = 0);
- explicit QTextControl(const QString &text, QObject *parent = 0);
- explicit QTextControl(QTextDocument *doc, QObject *parent = 0);
- virtual ~QTextControl();
-
- void setDocument(QTextDocument *document);
- QTextDocument *document() const;
-
- void setTextCursor(const QTextCursor &cursor);
- QTextCursor textCursor() const;
-
- void setTextInteractionFlags(Qt::TextInteractionFlags flags);
- Qt::TextInteractionFlags textInteractionFlags() const;
-
- void mergeCurrentCharFormat(const QTextCharFormat &modifier);
-
- void setCurrentCharFormat(const QTextCharFormat &format);
- QTextCharFormat currentCharFormat() const;
-
- bool find(const QString &exp, QTextDocument::FindFlags options = 0);
-
- inline QString toPlainText() const
- { return document()->toPlainText(); }
-#ifndef QT_NO_TEXTHTMLPARSER
- inline QString toHtml() const
- { return document()->toHtml(); }
-#endif
-
- virtual void ensureCursorVisible();
-
- virtual QVariant loadResource(int type, const QUrl &name);
-#ifndef QT_NO_CONTEXTMENU
- QMenu *createStandardContextMenu(const QPointF &pos, QWidget *parent);
-#endif
-
- QTextCursor cursorForPosition(const QPointF &pos) const;
- QRectF cursorRect(const QTextCursor &cursor) const;
- QRectF cursorRect() const;
- QRectF selectionRect(const QTextCursor &cursor) const;
- QRectF selectionRect() const;
-
- QString anchorAt(const QPointF &pos) const;
- QPointF anchorPosition(const QString &name) const;
-
- QString anchorAtCursor() const;
-
- bool overwriteMode() const;
- void setOverwriteMode(bool overwrite);
-
- int cursorWidth() const;
- void setCursorWidth(int width);
-
- bool acceptRichText() const;
- void setAcceptRichText(bool accept);
-
-#ifndef QT_NO_TEXTEDIT
- void setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections);
- QList<QTextEdit::ExtraSelection> extraSelections() const;
-#endif
-
- void setTextWidth(qreal width);
- qreal textWidth() const;
- QSizeF size() const;
-
- void setOpenExternalLinks(bool open);
- bool openExternalLinks() const;
-
- void setIgnoreUnusedNavigationEvents(bool ignore);
- bool ignoreUnusedNavigationEvents() const;
-
- void moveCursor(QTextCursor::MoveOperation op, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor);
-
- bool canPaste() const;
-
- void setCursorIsFocusIndicator(bool b);
- bool cursorIsFocusIndicator() const;
-
- void setDragEnabled(bool enabled);
- bool isDragEnabled() const;
-
- bool isWordSelectionEnabled() const;
- void setWordSelectionEnabled(bool enabled);
-
-#ifndef QT_NO_PRINTER
- void print(QPrinter *printer) const;
-#endif
-
- virtual int hitTest(const QPointF &point, Qt::HitTestAccuracy accuracy) const;
- virtual QRectF blockBoundingRect(const QTextBlock &block) const;
- QAbstractTextDocumentLayout::PaintContext getPaintContext(QWidget *widget) const;
-
-public Q_SLOTS:
- void setPlainText(const QString &text);
- void setHtml(const QString &text);
-
-#ifndef QT_NO_CLIPBOARD
- void cut();
- void copy();
- void paste(QClipboard::Mode mode = QClipboard::Clipboard);
-#endif
-
- void undo();
- void redo();
-
- void clear();
- void selectAll();
-
- void insertPlainText(const QString &text);
-#ifndef QT_NO_TEXTHTMLPARSER
- void insertHtml(const QString &text);
-#endif
-
- void append(const QString &text);
- void appendHtml(const QString &html);
- void appendPlainText(const QString &text);
-
- void adjustSize();
-
-Q_SIGNALS:
- void textChanged();
- void undoAvailable(bool b);
- void redoAvailable(bool b);
- void currentCharFormatChanged(const QTextCharFormat &format);
- void copyAvailable(bool b);
- void selectionChanged();
- void cursorPositionChanged();
-
- // control signals
- void updateRequest(const QRectF &rect = QRectF());
- void documentSizeChanged(const QSizeF &);
- void blockCountChanged(int newBlockCount);
- void visibilityRequest(const QRectF &rect);
- void microFocusChanged();
- void linkActivated(const QString &link);
- void linkHovered(const QString &);
- void modificationChanged(bool m);
-
-public:
- // control properties
- QPalette palette() const;
- void setPalette(const QPalette &pal);
-
- virtual void processEvent(QEvent *e, const QMatrix &matrix, QWidget *contextWidget = 0);
- void processEvent(QEvent *e, const QPointF &coordinateOffset = QPointF(), QWidget *contextWidget = 0);
-
- // control methods
- void drawContents(QPainter *painter, const QRectF &rect = QRectF(), QWidget *widget = 0);
-
- void setFocus(bool focus, Qt::FocusReason = Qt::OtherFocusReason);
-
- virtual QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
-
- virtual QMimeData *createMimeDataFromSelection() const;
- virtual bool canInsertFromMimeData(const QMimeData *source) const;
- virtual void insertFromMimeData(const QMimeData *source);
-
- bool setFocusToAnchor(const QTextCursor &newCursor);
- bool setFocusToNextOrPreviousAnchor(bool next);
- bool findNextPrevAnchor(const QTextCursor& from, bool next, QTextCursor& newAnchor);
-
-protected:
- virtual void timerEvent(QTimerEvent *e);
-
- virtual bool event(QEvent *e);
-
-private:
- Q_DISABLE_COPY(QTextControl)
- Q_PRIVATE_SLOT(d_func(), void _q_updateCurrentCharFormatAndSelection())
- Q_PRIVATE_SLOT(d_func(), void _q_emitCursorPosChanged(const QTextCursor &))
- Q_PRIVATE_SLOT(d_func(), void _q_deleteSelected())
- Q_PRIVATE_SLOT(d_func(), void _q_copyLink())
- Q_PRIVATE_SLOT(d_func(), void _q_updateBlock(const QTextBlock &))
- Q_PRIVATE_SLOT(d_func(), void _q_documentLayoutChanged())
-};
-
-
-#ifndef QT_NO_CONTEXTMENU
-class QUnicodeControlCharacterMenu : public QMenu
-{
- Q_OBJECT
-public:
- QUnicodeControlCharacterMenu(QObject *editWidget, QWidget *parent);
-
-private Q_SLOTS:
- void menuActionTriggered();
-
-private:
- QObject *editWidget;
-};
-#endif // QT_NO_CONTEXTMENU
-
-
-// also used by QLabel
-class QTextEditMimeData : public QMimeData
-{
-public:
- inline QTextEditMimeData(const QTextDocumentFragment &aFragment) : fragment(aFragment) {}
-
- virtual QStringList formats() const;
-protected:
- virtual QVariant retrieveData(const QString &mimeType, QVariant::Type type) const;
-private:
- void setup() const;
-
- mutable QTextDocumentFragment fragment;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTEXTCONTROL_H
diff --git a/src/gui/to_be_moved/qtextcontrol_p_p.h b/src/gui/to_be_moved/qtextcontrol_p_p.h
deleted file mode 100644
index 94670e225e..0000000000
--- a/src/gui/to_be_moved/qtextcontrol_p_p.h
+++ /dev/null
@@ -1,238 +0,0 @@
-/****************************************************************************
-**
-** 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 QTEXTCONTROL_P_P_H
-#define QTEXTCONTROL_P_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qtextdocumentfragment.h"
-#include "QtGui/qscrollbar.h"
-#include "QtGui/qtextcursor.h"
-#include "QtGui/qtextformat.h"
-#include "QtGui/qmenu.h"
-#include "QtGui/qabstracttextdocumentlayout.h"
-#include "QtCore/qbasictimer.h"
-#include "QtCore/qpointer.h"
-#include "private/qobject_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QMimeData;
-class QAbstractScrollArea;
-class QInputContext;
-
-class QTextControlPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QTextControl)
-public:
- QTextControlPrivate();
-
- bool cursorMoveKeyEvent(QKeyEvent *e);
-
- void updateCurrentCharFormat();
-
- void indent();
- void outdent();
-
- void gotoNextTableCell();
- void gotoPreviousTableCell();
-
- void createAutoBulletList();
-
- void init(Qt::TextFormat format = Qt::RichText, const QString &text = QString(),
- QTextDocument *document = 0);
- void setContent(Qt::TextFormat format = Qt::RichText, const QString &text = QString(),
- QTextDocument *document = 0);
- void startDrag();
-
- void paste(const QMimeData *source);
-
- void setCursorPosition(const QPointF &pos);
- void setCursorPosition(int pos, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor);
-
- void repaintCursor();
- inline void repaintSelection()
- { repaintOldAndNewSelection(QTextCursor()); }
- void repaintOldAndNewSelection(const QTextCursor &oldSelection);
-
- void selectionChanged(bool forceEmitSelectionChanged = false);
-
- void _q_updateCurrentCharFormatAndSelection();
-
-#ifndef QT_NO_CLIPBOARD
- void setClipboardSelection();
-#endif
-
- void _q_emitCursorPosChanged(const QTextCursor &someCursor);
-
- void setBlinkingCursorEnabled(bool enable);
-
- void extendWordwiseSelection(int suggestedNewPosition, qreal mouseXPosition);
- void extendBlockwiseSelection(int suggestedNewPosition);
-
- void _q_deleteSelected();
-
- void _q_setCursorAfterUndoRedo(int undoPosition, int charsAdded, int charsRemoved);
-
- QRectF cursorRectPlusUnicodeDirectionMarkers(const QTextCursor &cursor) const;
- QRectF rectForPosition(int position) const;
- QRectF selectionRect(const QTextCursor &cursor) const;
- inline QRectF selectionRect() const
- { return selectionRect(this->cursor); }
-
- QString anchorForCursor(const QTextCursor &anchor) const;
-
- void keyPressEvent(QKeyEvent *e);
- void mousePressEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos,
- Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons,
- const QPoint &globalPos);
- void mouseMoveEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos,
- Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons,
- const QPoint &globalPos);
- void mouseReleaseEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos,
- Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons,
- const QPoint &globalPos);
- void mouseDoubleClickEvent(QEvent *e, Qt::MouseButton button, const QPointF &pos,
- Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons,
- const QPoint &globalPos);
- bool sendMouseEventToInputContext(QEvent *e, QEvent::Type eventType, Qt::MouseButton button,
- const QPointF &pos,
- Qt::KeyboardModifiers modifiers,
- Qt::MouseButtons buttons,
- const QPoint &globalPos);
- void contextMenuEvent(const QPoint &screenPos, const QPointF &docPos, QWidget *contextWidget);
- void focusEvent(QFocusEvent *e);
-#ifdef QT_KEYPAD_NAVIGATION
- void editFocusEvent(QEvent *e);
-#endif
- bool dragEnterEvent(QEvent *e, const QMimeData *mimeData);
- void dragLeaveEvent();
- bool dragMoveEvent(QEvent *e, const QMimeData *mimeData, const QPointF &pos);
- bool dropEvent(const QMimeData *mimeData, const QPointF &pos, Qt::DropAction dropAction, QWidget *source);
-
- void inputMethodEvent(QInputMethodEvent *);
-
- void activateLinkUnderCursor(QString href = QString());
-
-#ifndef QT_NO_TOOLTIP
- void showToolTip(const QPoint &globalPos, const QPointF &pos, QWidget *contextWidget);
-#endif
-
- void append(const QString &text, Qt::TextFormat format = Qt::AutoText);
-
- QInputContext *inputContext();
-
- QTextDocument *doc;
- bool cursorOn;
- QTextCursor cursor;
- bool cursorIsFocusIndicator;
- QTextCharFormat lastCharFormat;
-
- QTextCursor dndFeedbackCursor;
-
- Qt::TextInteractionFlags interactionFlags;
-
- QBasicTimer cursorBlinkTimer;
- QBasicTimer trippleClickTimer;
- QPointF trippleClickPoint;
-
- bool dragEnabled;
-
- bool mousePressed;
-
- bool mightStartDrag;
- QPoint dragStartPos;
- QPointer<QWidget> contextWidget;
-
- bool lastSelectionState;
-
- bool ignoreAutomaticScrollbarAdjustement;
-
- QTextCursor selectedWordOnDoubleClick;
- QTextCursor selectedBlockOnTrippleClick;
-
- bool overwriteMode;
- bool acceptRichText;
-
- int preeditCursor;
- bool hideCursor; // used to hide the cursor in the preedit area
-
- QVector<QAbstractTextDocumentLayout::Selection> extraSelections;
-
- QPalette palette;
- bool hasFocus;
-#ifdef QT_KEYPAD_NAVIGATION
- bool hasEditFocus;
-#endif
- bool isEnabled;
-
- QString highlightedAnchor; // Anchor below cursor
- QString anchorOnMousePress;
- bool hadSelectionOnMousePress;
-
- bool ignoreUnusedNavigationEvents;
- bool openExternalLinks;
-
- bool wordSelectionEnabled;
-
- QString linkToCopy;
- void _q_copyLink();
- void _q_updateBlock(const QTextBlock &);
- void _q_documentLayoutChanged();
-};
-
-QT_END_NAMESPACE
-
-#endif // QTEXTCONTROL_P_H
diff --git a/src/gui/to_be_moved/to_be_moved.pri b/src/gui/to_be_moved/to_be_moved.pri
deleted file mode 100644
index d09c568c69..0000000000
--- a/src/gui/to_be_moved/to_be_moved.pri
+++ /dev/null
@@ -1,17 +0,0 @@
-HEADERS += \
- to_be_moved/qlinecontrol_p.h \
- to_be_moved/qtextcontrol_p.h \
- to_be_moved/qtextcontrol_p_p.h \
- to_be_moved/qshortcut.h \
- to_be_moved/qshortcutmap_p.h \
- to_be_moved/qdrag.h \
- to_be_moved/qdnd_p.h \
-
-SOURCES += \
- to_be_moved/qlinecontrol.cpp \
- to_be_moved/qtextcontrol.cpp \
- to_be_moved/qshortcut.cpp \
- to_be_moved/qshortcutmap.cpp \
- to_be_moved/qdrag.cpp \
- to_be_moved/qdnd.cpp \
- to_be_moved/qdnd_qpa.cpp \
diff --git a/src/gui/util/qcompleter.cpp b/src/gui/util/qcompleter.cpp
deleted file mode 100644
index 0cb3bbdf8c..0000000000
--- a/src/gui/util/qcompleter.cpp
+++ /dev/null
@@ -1,1833 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QCompleter
- \brief The QCompleter class provides completions based on an item model.
- \since 4.2
-
- You can use QCompleter to provide auto completions in any Qt
- widget, such as QLineEdit and QComboBox.
- When the user starts typing a word, QCompleter suggests possible ways of
- completing the word, based on a word list. The word list is
- provided as a QAbstractItemModel. (For simple applications, where
- the word list is static, you can pass a QStringList to
- QCompleter's constructor.)
-
- \tableofcontents
-
- \section1 Basic Usage
-
- A QCompleter is used typically with a QLineEdit or QComboBox.
- For example, here's how to provide auto completions from a simple
- word list in a QLineEdit:
-
- \snippet doc/src/snippets/code/src_gui_util_qcompleter.cpp 0
-
- A QFileSystemModel can be used to provide auto completion of file names.
- For example:
-
- \snippet doc/src/snippets/code/src_gui_util_qcompleter.cpp 1
-
- To set the model on which QCompleter should operate, call
- setModel(). By default, QCompleter will attempt to match the \l
- {completionPrefix}{completion prefix} (i.e., the word that the
- user has started typing) against the Qt::EditRole data stored in
- column 0 in the model case sensitively. This can be changed
- using setCompletionRole(), setCompletionColumn(), and
- setCaseSensitivity().
-
- If the model is sorted on the column and role that are used for completion,
- you can call setModelSorting() with either
- QCompleter::CaseSensitivelySortedModel or
- QCompleter::CaseInsensitivelySortedModel as the argument. On large models,
- this can lead to significant performance improvements, because QCompleter
- can then use binary search instead of linear search.
-
- The model can be a \l{QAbstractListModel}{list model},
- a \l{QAbstractTableModel}{table model}, or a
- \l{QAbstractItemModel}{tree model}. Completion on tree models
- is slightly more involved and is covered in the \l{Handling
- Tree Models} section below.
-
- The completionMode() determines the mode used to provide completions to
- the user.
-
- \section1 Iterating Through Completions
-
- To retrieve a single candidate string, call setCompletionPrefix()
- with the text that needs to be completed and call
- currentCompletion(). You can iterate through the list of
- completions as below:
-
- \snippet doc/src/snippets/code/src_gui_util_qcompleter.cpp 2
-
- completionCount() returns the total number of completions for the
- current prefix. completionCount() should be avoided when possible,
- since it requires a scan of the entire model.
-
- \section1 The Completion Model
-
- completionModel() return a list model that contains all possible
- completions for the current completion prefix, in the order in which
- they appear in the model. This model can be used to display the current
- completions in a custom view. Calling setCompletionPrefix() automatically
- refreshes the completion model.
-
- \section1 Handling Tree Models
-
- QCompleter can look for completions in tree models, assuming
- that any item (or sub-item or sub-sub-item) can be unambiguously
- represented as a string by specifying the path to the item. The
- completion is then performed one level at a time.
-
- Let's take the example of a user typing in a file system path.
- The model is a (hierarchical) QFileSystemModel. The completion
- occurs for every element in the path. For example, if the current
- text is \c C:\Wind, QCompleter might suggest \c Windows to
- complete the current path element. Similarly, if the current text
- is \c C:\Windows\Sy, QCompleter might suggest \c System.
-
- For this kind of completion to work, QCompleter needs to be able to
- split the path into a list of strings that are matched at each level.
- For \c C:\Windows\Sy, it needs to be split as "C:", "Windows" and "Sy".
- The default implementation of splitPath(), splits the completionPrefix
- using QDir::separator() if the model is a QFileSystemModel.
-
- To provide completions, QCompleter needs to know the path from an index.
- This is provided by pathFromIndex(). The default implementation of
- pathFromIndex(), returns the data for the \l{Qt::EditRole}{edit role}
- for list models and the absolute file path if the mode is a QFileSystemModel.
-
- \sa QAbstractItemModel, QLineEdit, QComboBox, {Completer Example}
-*/
-
-#include "qcompleter_p.h"
-
-#ifndef QT_NO_COMPLETER
-
-#include "QtGui/qscrollbar.h"
-#include "QtGui/qstringlistmodel.h"
-#include "QtGui/qdirmodel.h"
-#include "QtGui/qfilesystemmodel.h"
-#include "QtGui/qheaderview.h"
-#include "QtGui/qlistview.h"
-#include "QtGui/qapplication.h"
-#include "QtGui/qevent.h"
-#include "QtGui/qheaderview.h"
-#include "QtGui/qdesktopwidget.h"
-#include "QtGui/qlineedit.h"
-
-QT_BEGIN_NAMESPACE
-
-QCompletionModel::QCompletionModel(QCompleterPrivate *c, QObject *parent)
- : QAbstractProxyModel(*new QCompletionModelPrivate, parent),
- c(c), showAll(false)
-{
- createEngine();
-}
-
-int QCompletionModel::columnCount(const QModelIndex &) const
-{
- Q_D(const QCompletionModel);
- return d->model->columnCount();
-}
-
-void QCompletionModel::setSourceModel(QAbstractItemModel *source)
-{
- bool hadModel = (sourceModel() != 0);
-
- if (hadModel)
- QObject::disconnect(sourceModel(), 0, this, 0);
-
- QAbstractProxyModel::setSourceModel(source);
-
- if (source) {
- // TODO: Optimize updates in the source model
- connect(source, SIGNAL(modelReset()), this, SLOT(invalidate()));
- connect(source, SIGNAL(destroyed()), this, SLOT(modelDestroyed()));
- connect(source, SIGNAL(layoutChanged()), this, SLOT(invalidate()));
- connect(source, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInserted()));
- connect(source, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(invalidate()));
- connect(source, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(invalidate()));
- connect(source, SIGNAL(columnsRemoved(QModelIndex,int,int)), this, SLOT(invalidate()));
- connect(source, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(invalidate()));
- }
-
- invalidate();
-}
-
-void QCompletionModel::createEngine()
-{
- bool sortedEngine = false;
- switch (c->sorting) {
- case QCompleter::UnsortedModel:
- sortedEngine = false;
- break;
- case QCompleter::CaseSensitivelySortedModel:
- sortedEngine = c->cs == Qt::CaseSensitive;
- break;
- case QCompleter::CaseInsensitivelySortedModel:
- sortedEngine = c->cs == Qt::CaseInsensitive;
- break;
- }
-
- if (sortedEngine)
- engine.reset(new QSortedModelEngine(c));
- else
- engine.reset(new QUnsortedModelEngine(c));
-}
-
-QModelIndex QCompletionModel::mapToSource(const QModelIndex& index) const
-{
- Q_D(const QCompletionModel);
- if (!index.isValid())
- return engine->curParent;
-
- int row;
- QModelIndex parent = engine->curParent;
- if (!showAll) {
- if (!engine->matchCount())
- return QModelIndex();
- Q_ASSERT(index.row() < engine->matchCount());
- QIndexMapper& rootIndices = engine->historyMatch.indices;
- if (index.row() < rootIndices.count()) {
- row = rootIndices[index.row()];
- parent = QModelIndex();
- } else {
- row = engine->curMatch.indices[index.row() - rootIndices.count()];
- }
- } else {
- row = index.row();
- }
-
- return d->model->index(row, index.column(), parent);
-}
-
-QModelIndex QCompletionModel::mapFromSource(const QModelIndex& idx) const
-{
- if (!idx.isValid())
- return QModelIndex();
-
- int row = -1;
- if (!showAll) {
- if (!engine->matchCount())
- return QModelIndex();
-
- QIndexMapper& rootIndices = engine->historyMatch.indices;
- if (idx.parent().isValid()) {
- if (idx.parent() != engine->curParent)
- return QModelIndex();
- } else {
- row = rootIndices.indexOf(idx.row());
- if (row == -1 && engine->curParent.isValid())
- return QModelIndex(); // source parent and our parent don't match
- }
-
- if (row == -1) {
- QIndexMapper& indices = engine->curMatch.indices;
- engine->filterOnDemand(idx.row() - indices.last());
- row = indices.indexOf(idx.row()) + rootIndices.count();
- }
-
- if (row == -1)
- return QModelIndex();
- } else {
- if (idx.parent() != engine->curParent)
- return QModelIndex();
- row = idx.row();
- }
-
- return createIndex(row, idx.column());
-}
-
-bool QCompletionModel::setCurrentRow(int row)
-{
- if (row < 0 || !engine->matchCount())
- return false;
-
- if (row >= engine->matchCount())
- engine->filterOnDemand(row + 1 - engine->matchCount());
-
- if (row >= engine->matchCount()) // invalid row
- return false;
-
- engine->curRow = row;
- return true;
-}
-
-QModelIndex QCompletionModel::currentIndex(bool sourceIndex) const
-{
- if (!engine->matchCount())
- return QModelIndex();
-
- int row = engine->curRow;
- if (showAll)
- row = engine->curMatch.indices[engine->curRow];
-
- QModelIndex idx = createIndex(row, c->column);
- if (!sourceIndex)
- return idx;
- return mapToSource(idx);
-}
-
-QModelIndex QCompletionModel::index(int row, int column, const QModelIndex& parent) const
-{
- Q_D(const QCompletionModel);
- if (row < 0 || column < 0 || column >= columnCount(parent) || parent.isValid())
- return QModelIndex();
-
- if (!showAll) {
- if (!engine->matchCount())
- return QModelIndex();
- if (row >= engine->historyMatch.indices.count()) {
- int want = row + 1 - engine->matchCount();
- if (want > 0)
- engine->filterOnDemand(want);
- if (row >= engine->matchCount())
- return QModelIndex();
- }
- } else {
- if (row >= d->model->rowCount(engine->curParent))
- return QModelIndex();
- }
-
- return createIndex(row, column);
-}
-
-int QCompletionModel::completionCount() const
-{
- if (!engine->matchCount())
- return 0;
-
- engine->filterOnDemand(INT_MAX);
- return engine->matchCount();
-}
-
-int QCompletionModel::rowCount(const QModelIndex &parent) const
-{
- Q_D(const QCompletionModel);
- if (parent.isValid())
- return 0;
-
- if (showAll) {
- // Show all items below current parent, even if we have no valid matches
- if (engine->curParts.count() != 1 && !engine->matchCount()
- && !engine->curParent.isValid())
- return 0;
- return d->model->rowCount(engine->curParent);
- }
-
- return completionCount();
-}
-
-void QCompletionModel::setFiltered(bool filtered)
-{
- if (showAll == !filtered)
- return;
- showAll = !filtered;
- resetModel();
-}
-
-bool QCompletionModel::hasChildren(const QModelIndex &parent) const
-{
- Q_D(const QCompletionModel);
- if (parent.isValid())
- return false;
-
- if (showAll)
- return d->model->hasChildren(mapToSource(parent));
-
- if (!engine->matchCount())
- return false;
-
- return true;
-}
-
-QVariant QCompletionModel::data(const QModelIndex& index, int role) const
-{
- Q_D(const QCompletionModel);
- return d->model->data(mapToSource(index), role);
-}
-
-void QCompletionModel::modelDestroyed()
-{
- QAbstractProxyModel::setSourceModel(0); // switch to static empty model
- invalidate();
-}
-
-void QCompletionModel::rowsInserted()
-{
- invalidate();
- emit rowsAdded();
-}
-
-void QCompletionModel::invalidate()
-{
- engine->cache.clear();
- filter(engine->curParts);
-}
-
-void QCompletionModel::filter(const QStringList& parts)
-{
- Q_D(QCompletionModel);
- engine->filter(parts);
- resetModel();
-
- if (d->model->canFetchMore(engine->curParent))
- d->model->fetchMore(engine->curParent);
-}
-
-void QCompletionModel::resetModel()
-{
- if (rowCount() == 0) {
- reset();
- return;
- }
-
- emit layoutAboutToBeChanged();
- QModelIndexList piList = persistentIndexList();
- QModelIndexList empty;
- for (int i = 0; i < piList.size(); i++)
- empty.append(QModelIndex());
- changePersistentIndexList(piList, empty);
- emit layoutChanged();
-}
-
-//////////////////////////////////////////////////////////////////////////////
-void QCompletionEngine::filter(const QStringList& parts)
-{
- const QAbstractItemModel *model = c->proxy->sourceModel();
- curParts = parts;
- if (curParts.isEmpty())
- curParts.append(QString());
-
- curRow = -1;
- curParent = QModelIndex();
- curMatch = QMatchData();
- historyMatch = filterHistory();
-
- if (!model)
- return;
-
- QModelIndex parent;
- for (int i = 0; i < curParts.count() - 1; i++) {
- QString part = curParts[i];
- int emi = filter(part, parent, -1).exactMatchIndex;
- if (emi == -1)
- return;
- parent = model->index(emi, c->column, parent);
- }
-
- // Note that we set the curParent to a valid parent, even if we have no matches
- // When filtering is disabled, we show all the items under this parent
- curParent = parent;
- if (curParts.last().isEmpty())
- curMatch = QMatchData(QIndexMapper(0, model->rowCount(curParent) - 1), -1, false);
- else
- curMatch = filter(curParts.last(), curParent, 1); // build at least one
- curRow = curMatch.isValid() ? 0 : -1;
-}
-
-QMatchData QCompletionEngine::filterHistory()
-{
- QAbstractItemModel *source = c->proxy->sourceModel();
- if (curParts.count() <= 1 || c->proxy->showAll || !source)
- return QMatchData();
- bool isDirModel = false;
- bool isFsModel = false;
-#ifndef QT_NO_DIRMODEL
- isDirModel = (qobject_cast<QDirModel *>(source) != 0);
-#endif
-#ifndef QT_NO_FILESYSTEMMODEL
- isFsModel = (qobject_cast<QFileSystemModel *>(source) != 0);
-#endif
- QVector<int> v;
- QIndexMapper im(v);
- QMatchData m(im, -1, true);
-
- for (int i = 0; i < source->rowCount(); i++) {
- QString str = source->index(i, c->column).data().toString();
- if (str.startsWith(c->prefix, c->cs)
-#if (!defined(Q_OS_WIN) || defined(Q_OS_WINCE)) && !defined(Q_OS_SYMBIAN)
- && ((!isFsModel && !isDirModel) || QDir::toNativeSeparators(str) != QDir::separator())
-#endif
- )
- m.indices.append(i);
- }
- return m;
-}
-
-// Returns a match hint from the cache by chopping the search string
-bool QCompletionEngine::matchHint(QString part, const QModelIndex& parent, QMatchData *hint)
-{
- if (c->cs == Qt::CaseInsensitive)
- part = part.toLower();
-
- const CacheItem& map = cache[parent];
-
- QString key = part;
- while (!key.isEmpty()) {
- key.chop(1);
- if (map.contains(key)) {
- *hint = map[key];
- return true;
- }
- }
-
- return false;
-}
-
-bool QCompletionEngine::lookupCache(QString part, const QModelIndex& parent, QMatchData *m)
-{
- if (c->cs == Qt::CaseInsensitive)
- part = part.toLower();
- const CacheItem& map = cache[parent];
- if (!map.contains(part))
- return false;
- *m = map[part];
- return true;
-}
-
-// When the cache size exceeds 1MB, it clears out about 1/2 of the cache.
-void QCompletionEngine::saveInCache(QString part, const QModelIndex& parent, const QMatchData& m)
-{
- QMatchData old = cache[parent].take(part);
- cost = cost + m.indices.cost() - old.indices.cost();
- if (cost * sizeof(int) > 1024 * 1024) {
- QMap<QModelIndex, CacheItem>::iterator it1 = cache.begin();
- while (it1 != cache.end()) {
- CacheItem& ci = it1.value();
- int sz = ci.count()/2;
- QMap<QString, QMatchData>::iterator it2 = ci.begin();
- int i = 0;
- while (it2 != ci.end() && i < sz) {
- cost -= it2.value().indices.cost();
- it2 = ci.erase(it2);
- i++;
- }
- if (ci.count() == 0) {
- it1 = cache.erase(it1);
- } else {
- ++it1;
- }
- }
- }
-
- if (c->cs == Qt::CaseInsensitive)
- part = part.toLower();
- cache[parent][part] = m;
-}
-
-///////////////////////////////////////////////////////////////////////////////////
-QIndexMapper QSortedModelEngine::indexHint(QString part, const QModelIndex& parent, Qt::SortOrder order)
-{
- const QAbstractItemModel *model = c->proxy->sourceModel();
-
- if (c->cs == Qt::CaseInsensitive)
- part = part.toLower();
-
- const CacheItem& map = cache[parent];
-
- // Try to find a lower and upper bound for the search from previous results
- int to = model->rowCount(parent) - 1;
- int from = 0;
- const CacheItem::const_iterator it = map.lowerBound(part);
-
- // look backward for first valid hint
- for(CacheItem::const_iterator it1 = it; it1-- != map.constBegin();) {
- const QMatchData& value = it1.value();
- if (value.isValid()) {
- if (order == Qt::AscendingOrder) {
- from = value.indices.last() + 1;
- } else {
- to = value.indices.first() - 1;
- }
- break;
- }
- }
-
- // look forward for first valid hint
- for(CacheItem::const_iterator it2 = it; it2 != map.constEnd(); ++it2) {
- const QMatchData& value = it2.value();
- if (value.isValid() && !it2.key().startsWith(part)) {
- if (order == Qt::AscendingOrder) {
- to = value.indices.first() - 1;
- } else {
- from = value.indices.first() + 1;
- }
- break;
- }
- }
-
- return QIndexMapper(from, to);
-}
-
-Qt::SortOrder QSortedModelEngine::sortOrder(const QModelIndex &parent) const
-{
- const QAbstractItemModel *model = c->proxy->sourceModel();
-
- int rowCount = model->rowCount(parent);
- if (rowCount < 2)
- return Qt::AscendingOrder;
- QString first = model->data(model->index(0, c->column, parent), c->role).toString();
- QString last = model->data(model->index(rowCount - 1, c->column, parent), c->role).toString();
- return QString::compare(first, last, c->cs) <= 0 ? Qt::AscendingOrder : Qt::DescendingOrder;
-}
-
-QMatchData QSortedModelEngine::filter(const QString& part, const QModelIndex& parent, int)
-{
- const QAbstractItemModel *model = c->proxy->sourceModel();
-
- QMatchData hint;
- if (lookupCache(part, parent, &hint))
- return hint;
-
- QIndexMapper indices;
- Qt::SortOrder order = sortOrder(parent);
-
- if (matchHint(part, parent, &hint)) {
- if (!hint.isValid())
- return QMatchData();
- indices = hint.indices;
- } else {
- indices = indexHint(part, parent, order);
- }
-
- // binary search the model within 'indices' for 'part' under 'parent'
- int high = indices.to() + 1;
- int low = indices.from() - 1;
- int probe;
- QModelIndex probeIndex;
- QString probeData;
-
- while (high - low > 1)
- {
- probe = (high + low) / 2;
- probeIndex = model->index(probe, c->column, parent);
- probeData = model->data(probeIndex, c->role).toString();
- const int cmp = QString::compare(probeData, part, c->cs);
- if ((order == Qt::AscendingOrder && cmp >= 0)
- || (order == Qt::DescendingOrder && cmp < 0)) {
- high = probe;
- } else {
- low = probe;
- }
- }
-
- if ((order == Qt::AscendingOrder && low == indices.to())
- || (order == Qt::DescendingOrder && high == indices.from())) { // not found
- saveInCache(part, parent, QMatchData());
- return QMatchData();
- }
-
- probeIndex = model->index(order == Qt::AscendingOrder ? low+1 : high-1, c->column, parent);
- probeData = model->data(probeIndex, c->role).toString();
- if (!probeData.startsWith(part, c->cs)) {
- saveInCache(part, parent, QMatchData());
- return QMatchData();
- }
-
- const bool exactMatch = QString::compare(probeData, part, c->cs) == 0;
- int emi = exactMatch ? (order == Qt::AscendingOrder ? low+1 : high-1) : -1;
-
- int from = 0;
- int to = 0;
- if (order == Qt::AscendingOrder) {
- from = low + 1;
- high = indices.to() + 1;
- low = from;
- } else {
- to = high - 1;
- low = indices.from() - 1;
- high = to;
- }
-
- while (high - low > 1)
- {
- probe = (high + low) / 2;
- probeIndex = model->index(probe, c->column, parent);
- probeData = model->data(probeIndex, c->role).toString();
- const bool startsWith = probeData.startsWith(part, c->cs);
- if ((order == Qt::AscendingOrder && startsWith)
- || (order == Qt::DescendingOrder && !startsWith)) {
- low = probe;
- } else {
- high = probe;
- }
- }
-
- QMatchData m(order == Qt::AscendingOrder ? QIndexMapper(from, high - 1) : QIndexMapper(low+1, to), emi, false);
- saveInCache(part, parent, m);
- return m;
-}
-
-////////////////////////////////////////////////////////////////////////////////////////
-int QUnsortedModelEngine::buildIndices(const QString& str, const QModelIndex& parent, int n,
- const QIndexMapper& indices, QMatchData* m)
-{
- Q_ASSERT(m->partial);
- Q_ASSERT(n != -1 || m->exactMatchIndex == -1);
- const QAbstractItemModel *model = c->proxy->sourceModel();
- int i, count = 0;
-
- for (i = 0; i < indices.count() && count != n; ++i) {
- QModelIndex idx = model->index(indices[i], c->column, parent);
- QString data = model->data(idx, c->role).toString();
- if (!data.startsWith(str, c->cs) || !(model->flags(idx) & Qt::ItemIsSelectable))
- continue;
- m->indices.append(indices[i]);
- ++count;
- if (m->exactMatchIndex == -1 && QString::compare(data, str, c->cs) == 0) {
- m->exactMatchIndex = indices[i];
- if (n == -1)
- return indices[i];
- }
- }
- return indices[i-1];
-}
-
-void QUnsortedModelEngine::filterOnDemand(int n)
-{
- Q_ASSERT(matchCount());
- if (!curMatch.partial)
- return;
- Q_ASSERT(n >= -1);
- const QAbstractItemModel *model = c->proxy->sourceModel();
- int lastRow = model->rowCount(curParent) - 1;
- QIndexMapper im(curMatch.indices.last() + 1, lastRow);
- int lastIndex = buildIndices(curParts.last(), curParent, n, im, &curMatch);
- curMatch.partial = (lastRow != lastIndex);
- saveInCache(curParts.last(), curParent, curMatch);
-}
-
-QMatchData QUnsortedModelEngine::filter(const QString& part, const QModelIndex& parent, int n)
-{
- QMatchData hint;
-
- QVector<int> v;
- QIndexMapper im(v);
- QMatchData m(im, -1, true);
-
- const QAbstractItemModel *model = c->proxy->sourceModel();
- bool foundInCache = lookupCache(part, parent, &m);
-
- if (!foundInCache) {
- if (matchHint(part, parent, &hint) && !hint.isValid())
- return QMatchData();
- }
-
- if (!foundInCache && !hint.isValid()) {
- const int lastRow = model->rowCount(parent) - 1;
- QIndexMapper all(0, lastRow);
- int lastIndex = buildIndices(part, parent, n, all, &m);
- m.partial = (lastIndex != lastRow);
- } else {
- if (!foundInCache) { // build from hint as much as we can
- buildIndices(part, parent, INT_MAX, hint.indices, &m);
- m.partial = hint.partial;
- }
- if (m.partial && ((n == -1 && m.exactMatchIndex == -1) || (m.indices.count() < n))) {
- // need more and have more
- const int lastRow = model->rowCount(parent) - 1;
- QIndexMapper rest(hint.indices.last() + 1, lastRow);
- int want = n == -1 ? -1 : n - m.indices.count();
- int lastIndex = buildIndices(part, parent, want, rest, &m);
- m.partial = (lastRow != lastIndex);
- }
- }
-
- saveInCache(part, parent, m);
- return m;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-QCompleterPrivate::QCompleterPrivate()
-: widget(0), proxy(0), popup(0), cs(Qt::CaseSensitive), role(Qt::EditRole), column(0),
- maxVisibleItems(7), sorting(QCompleter::UnsortedModel), wrap(true), eatFocusOut(true),
- hiddenBecauseNoMatch(false)
-{
-}
-
-void QCompleterPrivate::init(QAbstractItemModel *m)
-{
- Q_Q(QCompleter);
- proxy = new QCompletionModel(this, q);
- QObject::connect(proxy, SIGNAL(rowsAdded()), q, SLOT(_q_autoResizePopup()));
- q->setModel(m);
-#ifdef QT_NO_LISTVIEW
- q->setCompletionMode(QCompleter::InlineCompletion);
-#else
- q->setCompletionMode(QCompleter::PopupCompletion);
-#endif // QT_NO_LISTVIEW
-}
-
-void QCompleterPrivate::setCurrentIndex(QModelIndex index, bool select)
-{
- Q_Q(QCompleter);
- if (!q->popup())
- return;
- if (!select) {
- popup->selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
- } else {
- if (!index.isValid())
- popup->selectionModel()->clear();
- else
- popup->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select
- | QItemSelectionModel::Rows);
- }
- index = popup->selectionModel()->currentIndex();
- if (!index.isValid())
- popup->scrollToTop();
- else
- popup->scrollTo(index, QAbstractItemView::PositionAtTop);
-}
-
-void QCompleterPrivate::_q_completionSelected(const QItemSelection& selection)
-{
- QModelIndex index;
- if (!selection.indexes().isEmpty())
- index = selection.indexes().first();
-
- _q_complete(index, true);
-}
-
-void QCompleterPrivate::_q_complete(QModelIndex index, bool highlighted)
-{
- Q_Q(QCompleter);
- QString completion;
-
- if (!index.isValid() || (!proxy->showAll && (index.row() >= proxy->engine->matchCount()))) {
- completion = prefix;
- } else {
- if (!(index.flags() & Qt::ItemIsEnabled))
- return;
- QModelIndex si = proxy->mapToSource(index);
- si = si.sibling(si.row(), column); // for clicked()
- completion = q->pathFromIndex(si);
-#ifndef QT_NO_DIRMODEL
- // add a trailing separator in inline
- if (mode == QCompleter::InlineCompletion) {
- if (qobject_cast<QDirModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
- completion += QDir::separator();
- }
-#endif
-#ifndef QT_NO_FILESYSTEMMODEL
- // add a trailing separator in inline
- if (mode == QCompleter::InlineCompletion) {
- if (qobject_cast<QFileSystemModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
- completion += QDir::separator();
- }
-#endif
- }
-
- if (highlighted) {
- emit q->highlighted(index);
- emit q->highlighted(completion);
- } else {
- emit q->activated(index);
- emit q->activated(completion);
- }
-}
-
-void QCompleterPrivate::_q_autoResizePopup()
-{
- if (!popup || !popup->isVisible())
- return;
- showPopup(popupRect);
-}
-
-void QCompleterPrivate::showPopup(const QRect& rect)
-{
- const QRect screen = QApplication::desktop()->availableGeometry(widget);
- Qt::LayoutDirection dir = widget->layoutDirection();
- QPoint pos;
- int rh, w;
- int h = (popup->sizeHintForRow(0) * qMin(maxVisibleItems, popup->model()->rowCount()) + 3) + 3;
- QScrollBar *hsb = popup->horizontalScrollBar();
- if (hsb && hsb->isVisible())
- h += popup->horizontalScrollBar()->sizeHint().height();
-
- if (rect.isValid()) {
- rh = rect.height();
- w = rect.width();
- pos = widget->mapToGlobal(dir == Qt::RightToLeft ? rect.bottomRight() : rect.bottomLeft());
- } else {
- rh = widget->height();
- pos = widget->mapToGlobal(QPoint(0, widget->height() - 2));
- w = widget->width();
- }
-
- if (w > screen.width())
- w = screen.width();
- if ((pos.x() + w) > (screen.x() + screen.width()))
- pos.setX(screen.x() + screen.width() - w);
- if (pos.x() < screen.x())
- pos.setX(screen.x());
-
- int top = pos.y() - rh - screen.top() + 2;
- int bottom = screen.bottom() - pos.y();
- h = qMax(h, popup->minimumHeight());
- if (h > bottom) {
- h = qMin(qMax(top, bottom), h);
-
- if (top > bottom)
- pos.setY(pos.y() - h - rh + 2);
- }
-
- popup->setGeometry(pos.x(), pos.y(), w, h);
-
- if (!popup->isVisible())
- popup->show();
-}
-
-void QCompleterPrivate::_q_fileSystemModelDirectoryLoaded(const QString &path)
-{
- Q_Q(QCompleter);
- // Slot called when QFileSystemModel has finished loading.
- // If we hide the popup because there was no match because the model was not loaded yet,
- // we re-start the completion when we get the results
- if (hiddenBecauseNoMatch
- && prefix.startsWith(path) && prefix != (path + QLatin1Char('/'))
- && widget) {
- q->complete();
- }
-}
-
-/*!
- Constructs a completer object with the given \a parent.
-*/
-QCompleter::QCompleter(QObject *parent)
-: QObject(*new QCompleterPrivate(), parent)
-{
- Q_D(QCompleter);
- d->init();
-}
-
-/*!
- Constructs a completer object with the given \a parent that provides completions
- from the specified \a model.
-*/
-QCompleter::QCompleter(QAbstractItemModel *model, QObject *parent)
- : QObject(*new QCompleterPrivate(), parent)
-{
- Q_D(QCompleter);
- d->init(model);
-}
-
-#ifndef QT_NO_STRINGLISTMODEL
-/*!
- Constructs a QCompleter object with the given \a parent that uses the specified
- \a list as a source of possible completions.
-*/
-QCompleter::QCompleter(const QStringList& list, QObject *parent)
-: QObject(*new QCompleterPrivate(), parent)
-{
- Q_D(QCompleter);
- d->init(new QStringListModel(list, this));
-}
-#endif // QT_NO_STRINGLISTMODEL
-
-/*!
- Destroys the completer object.
-*/
-QCompleter::~QCompleter()
-{
-}
-
-/*!
- Sets the widget for which completion are provided for to \a widget. This
- function is automatically called when a QCompleter is set on a QLineEdit
- using QLineEdit::setCompleter() or on a QComboBox using
- QComboBox::setCompleter(). The widget needs to be set explicitly when
- providing completions for custom widgets.
-
- \sa widget(), setModel(), setPopup()
- */
-void QCompleter::setWidget(QWidget *widget)
-{
- Q_D(QCompleter);
- if (d->widget)
- d->widget->removeEventFilter(this);
- d->widget = widget;
- if (d->widget)
- d->widget->installEventFilter(this);
- if (d->popup) {
- d->popup->hide();
- d->popup->setFocusProxy(d->widget);
- }
-}
-
-/*!
- Returns the widget for which the completer object is providing completions.
-
- \sa setWidget()
- */
-QWidget *QCompleter::widget() const
-{
- Q_D(const QCompleter);
- return d->widget;
-}
-
-/*!
- Sets the model which provides completions to \a model. The \a model can
- be list model or a tree model. If a model has been already previously set
- and it has the QCompleter as its parent, it is deleted.
-
- For convenience, if \a model is a QFileSystemModel, QCompleter switches its
- caseSensitivity to Qt::CaseInsensitive on Windows and Qt::CaseSensitive
- on other platforms.
-
- \sa completionModel(), modelSorting, {Handling Tree Models}
-*/
-void QCompleter::setModel(QAbstractItemModel *model)
-{
- Q_D(QCompleter);
- QAbstractItemModel *oldModel = d->proxy->sourceModel();
- d->proxy->setSourceModel(model);
- if (d->popup)
- setPopup(d->popup); // set the model and make new connections
- if (oldModel && oldModel->QObject::parent() == this)
- delete oldModel;
-#ifndef QT_NO_DIRMODEL
- if (qobject_cast<QDirModel *>(model)) {
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- setCaseSensitivity(Qt::CaseInsensitive);
-#else
- setCaseSensitivity(Qt::CaseSensitive);
-#endif
- }
-#endif // QT_NO_DIRMODEL
-#ifndef QT_NO_FILESYSTEMMODEL
- QFileSystemModel *fsModel = qobject_cast<QFileSystemModel *>(model);
- if (fsModel) {
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) || defined(Q_OS_SYMBIAN)
- setCaseSensitivity(Qt::CaseInsensitive);
-#else
- setCaseSensitivity(Qt::CaseSensitive);
-#endif
- setCompletionRole(QFileSystemModel::FileNameRole);
- connect(fsModel, SIGNAL(directoryLoaded(QString)), this, SLOT(_q_fileSystemModelDirectoryLoaded(QString)));
- }
-#endif // QT_NO_FILESYSTEMMODEL
-}
-
-/*!
- Returns the model that provides completion strings.
-
- \sa completionModel()
-*/
-QAbstractItemModel *QCompleter::model() const
-{
- Q_D(const QCompleter);
- return d->proxy->sourceModel();
-}
-
-/*!
- \enum QCompleter::CompletionMode
-
- This enum specifies how completions are provided to the user.
-
- \value PopupCompletion Current completions are displayed in a popup window.
- \value InlineCompletion Completions appear inline (as selected text).
- \value UnfilteredPopupCompletion All possible completions are displayed in a popup window with the most likely suggestion indicated as current.
-
- \sa setCompletionMode()
-*/
-
-/*!
- \property QCompleter::completionMode
- \brief how the completions are provided to the user
-
- The default value is QCompleter::PopupCompletion.
-*/
-void QCompleter::setCompletionMode(QCompleter::CompletionMode mode)
-{
- Q_D(QCompleter);
- d->mode = mode;
- d->proxy->setFiltered(mode != QCompleter::UnfilteredPopupCompletion);
-
- if (mode == QCompleter::InlineCompletion) {
- if (d->widget)
- d->widget->removeEventFilter(this);
- if (d->popup) {
- d->popup->deleteLater();
- d->popup = 0;
- }
- } else {
- if (d->widget)
- d->widget->installEventFilter(this);
- }
-}
-
-QCompleter::CompletionMode QCompleter::completionMode() const
-{
- Q_D(const QCompleter);
- return d->mode;
-}
-
-/*!
- Sets the popup used to display completions to \a popup. QCompleter takes
- ownership of the view.
-
- A QListView is automatically created when the completionMode() is set to
- QCompleter::PopupCompletion or QCompleter::UnfilteredPopupCompletion. The
- default popup displays the completionColumn().
-
- Ensure that this function is called before the view settings are modified.
- This is required since view's properties may require that a model has been
- set on the view (for example, hiding columns in the view requires a model
- to be set on the view).
-
- \sa popup()
-*/
-void QCompleter::setPopup(QAbstractItemView *popup)
-{
- Q_D(QCompleter);
- Q_ASSERT(popup != 0);
- if (d->popup) {
- QObject::disconnect(d->popup->selectionModel(), 0, this, 0);
- QObject::disconnect(d->popup, 0, this, 0);
- }
- if (d->popup != popup)
- delete d->popup;
- if (popup->model() != d->proxy)
- popup->setModel(d->proxy);
-#if defined(Q_OS_MAC) && !defined(QT_MAC_USE_COCOA)
- popup->show();
-#else
- popup->hide();
-#endif
-
- Qt::FocusPolicy origPolicy = Qt::NoFocus;
- if (d->widget)
- origPolicy = d->widget->focusPolicy();
- popup->setParent(0, Qt::Popup);
- popup->setFocusPolicy(Qt::NoFocus);
- if (d->widget)
- d->widget->setFocusPolicy(origPolicy);
-
- popup->setFocusProxy(d->widget);
- popup->installEventFilter(this);
- popup->setItemDelegate(new QCompleterItemDelegate(popup));
-#ifndef QT_NO_LISTVIEW
- if (QListView *listView = qobject_cast<QListView *>(popup)) {
- listView->setModelColumn(d->column);
- }
-#endif
-
- QObject::connect(popup, SIGNAL(clicked(QModelIndex)),
- this, SLOT(_q_complete(QModelIndex)));
- QObject::connect(this, SIGNAL(activated(QModelIndex)),
- popup, SLOT(hide()));
-
- QObject::connect(popup->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(_q_completionSelected(QItemSelection)));
- d->popup = popup;
-}
-
-/*!
- Returns the popup used to display completions.
-
- \sa setPopup()
-*/
-QAbstractItemView *QCompleter::popup() const
-{
- Q_D(const QCompleter);
-#ifndef QT_NO_LISTVIEW
- if (!d->popup && completionMode() != QCompleter::InlineCompletion) {
- QListView *listView = new QListView;
- listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
- listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- listView->setSelectionBehavior(QAbstractItemView::SelectRows);
- listView->setSelectionMode(QAbstractItemView::SingleSelection);
- listView->setModelColumn(d->column);
- QCompleter *that = const_cast<QCompleter*>(this);
- that->setPopup(listView);
- }
-#endif // QT_NO_LISTVIEW
- return d->popup;
-}
-
-/*!
- \reimp
-*/
-bool QCompleter::event(QEvent *ev)
-{
- return QObject::event(ev);
-}
-
-/*!
- \reimp
-*/
-bool QCompleter::eventFilter(QObject *o, QEvent *e)
-{
- Q_D(QCompleter);
-
- if (d->eatFocusOut && o == d->widget && e->type() == QEvent::FocusOut) {
- d->hiddenBecauseNoMatch = false;
- if (d->popup && d->popup->isVisible())
- return true;
- }
-
- if (o != d->popup)
- return QObject::eventFilter(o, e);
-
- switch (e->type()) {
- case QEvent::KeyPress: {
- QKeyEvent *ke = static_cast<QKeyEvent *>(e);
-
- QModelIndex curIndex = d->popup->currentIndex();
- QModelIndexList selList = d->popup->selectionModel()->selectedIndexes();
-
- const int key = ke->key();
- // In UnFilteredPopup mode, select the current item
- if ((key == Qt::Key_Up || key == Qt::Key_Down) && selList.isEmpty() && curIndex.isValid()
- && d->mode == QCompleter::UnfilteredPopupCompletion) {
- d->setCurrentIndex(curIndex);
- return true;
- }
-
- // Handle popup navigation keys. These are hardcoded because up/down might make the
- // widget do something else (lineedit cursor moves to home/end on mac, for instance)
- switch (key) {
- case Qt::Key_End:
- case Qt::Key_Home:
- if (ke->modifiers() & Qt::ControlModifier)
- return false;
- break;
-
- case Qt::Key_Up:
- if (!curIndex.isValid()) {
- int rowCount = d->proxy->rowCount();
- QModelIndex lastIndex = d->proxy->index(rowCount - 1, d->column);
- d->setCurrentIndex(lastIndex);
- return true;
- } else if (curIndex.row() == 0) {
- if (d->wrap)
- d->setCurrentIndex(QModelIndex());
- return true;
- }
- return false;
-
- case Qt::Key_Down:
- if (!curIndex.isValid()) {
- QModelIndex firstIndex = d->proxy->index(0, d->column);
- d->setCurrentIndex(firstIndex);
- return true;
- } else if (curIndex.row() == d->proxy->rowCount() - 1) {
- if (d->wrap)
- d->setCurrentIndex(QModelIndex());
- return true;
- }
- return false;
-
- case Qt::Key_PageUp:
- case Qt::Key_PageDown:
- return false;
- }
-
- // Send the event to the widget. If the widget accepted the event, do nothing
- // If the widget did not accept the event, provide a default implementation
- d->eatFocusOut = false;
- (static_cast<QObject *>(d->widget))->event(ke);
- d->eatFocusOut = true;
- if (!d->widget || e->isAccepted() || !d->popup->isVisible()) {
- // widget lost focus, hide the popup
- if (d->widget && (!d->widget->hasFocus()
-#ifdef QT_KEYPAD_NAVIGATION
- || (QApplication::keypadNavigationEnabled() && !d->widget->hasEditFocus())
-#endif
- ))
- d->popup->hide();
- if (e->isAccepted())
- return true;
- }
-
- // default implementation for keys not handled by the widget when popup is open
- switch (key) {
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (!QApplication::keypadNavigationEnabled())
- break;
-#endif
- case Qt::Key_Return:
- case Qt::Key_Enter:
- case Qt::Key_Tab:
- d->popup->hide();
- if (curIndex.isValid())
- d->_q_complete(curIndex);
- break;
-
- case Qt::Key_F4:
- if (ke->modifiers() & Qt::AltModifier)
- d->popup->hide();
- break;
-
- case Qt::Key_Backtab:
- case Qt::Key_Escape:
- d->popup->hide();
- break;
-
- default:
- break;
- }
-
- return true;
- }
-
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::KeyRelease: {
- QKeyEvent *ke = static_cast<QKeyEvent *>(e);
- if (QApplication::keypadNavigationEnabled() && ke->key() == Qt::Key_Back) {
- // Send the event to the 'widget'. This is what we did for KeyPress, so we need
- // to do the same for KeyRelease, in case the widget's KeyPress event set
- // up something (such as a timer) that is relying on also receiving the
- // key release. I see this as a bug in Qt, and should really set it up for all
- // the affected keys. However, it is difficult to tell how this will affect
- // existing code, and I can't test for every combination!
- d->eatFocusOut = false;
- static_cast<QObject *>(d->widget)->event(ke);
- d->eatFocusOut = true;
- }
- break;
- }
-#endif
-
- case QEvent::MouseButtonPress: {
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- // if we've clicked in the widget (or its descendant), let it handle the click
- QWidget *source = qobject_cast<QWidget *>(o);
- if (source) {
- QPoint pos = source->mapToGlobal((static_cast<QMouseEvent *>(e))->pos());
- QWidget *target = QApplication::widgetAt(pos);
- if (target && (d->widget->isAncestorOf(target) ||
- target == d->widget)) {
- d->eatFocusOut = false;
- static_cast<QObject *>(target)->event(e);
- d->eatFocusOut = true;
- return true;
- }
- }
- }
-#endif
- if (!d->popup->underMouse()) {
- d->popup->hide();
- return true;
- }
- }
- return false;
-
- case QEvent::InputMethod:
- case QEvent::ShortcutOverride:
- QApplication::sendEvent(d->widget, e);
- break;
-
- default:
- return false;
- }
- return false;
-}
-
-/*!
- For QCompleter::PopupCompletion and QCompletion::UnfilteredPopupCompletion
- modes, calling this function displays the popup displaying the current
- completions. By default, if \a rect is not specified, the popup is displayed
- on the bottom of the widget(). If \a rect is specified the popup is
- displayed on the left edge of the rectangle.
-
- For QCompleter::InlineCompletion mode, the highlighted() signal is fired
- with the current completion.
-*/
-void QCompleter::complete(const QRect& rect)
-{
- Q_D(QCompleter);
- QModelIndex idx = d->proxy->currentIndex(false);
- d->hiddenBecauseNoMatch = false;
- if (d->mode == QCompleter::InlineCompletion) {
- if (idx.isValid())
- d->_q_complete(idx, true);
- return;
- }
-
- Q_ASSERT(d->widget != 0);
- if ((d->mode == QCompleter::PopupCompletion && !idx.isValid())
- || (d->mode == QCompleter::UnfilteredPopupCompletion && d->proxy->rowCount() == 0)) {
- if (d->popup)
- d->popup->hide(); // no suggestion, hide
- d->hiddenBecauseNoMatch = true;
- return;
- }
-
- popup();
- if (d->mode == QCompleter::UnfilteredPopupCompletion)
- d->setCurrentIndex(idx, false);
-
- d->showPopup(rect);
- d->popupRect = rect;
-}
-
-/*!
- Sets the current row to the \a row specified. Returns true if successful;
- otherwise returns false.
-
- This function may be used along with currentCompletion() to iterate
- through all the possible completions.
-
- \sa currentCompletion(), completionCount()
-*/
-bool QCompleter::setCurrentRow(int row)
-{
- Q_D(QCompleter);
- return d->proxy->setCurrentRow(row);
-}
-
-/*!
- Returns the current row.
-
- \sa setCurrentRow()
-*/
-int QCompleter::currentRow() const
-{
- Q_D(const QCompleter);
- return d->proxy->currentRow();
-}
-
-/*!
- Returns the number of completions for the current prefix. For an unsorted
- model with a large number of items this can be expensive. Use setCurrentRow()
- and currentCompletion() to iterate through all the completions.
-*/
-int QCompleter::completionCount() const
-{
- Q_D(const QCompleter);
- return d->proxy->completionCount();
-}
-
-/*!
- \enum QCompleter::ModelSorting
-
- This enum specifies how the items in the model are sorted.
-
- \value UnsortedModel The model is unsorted.
- \value CaseSensitivelySortedModel The model is sorted case sensitively.
- \value CaseInsensitivelySortedModel The model is sorted case insensitively.
-
- \sa setModelSorting()
-*/
-
-/*!
- \property QCompleter::modelSorting
- \brief the way the model is sorted
-
- By default, no assumptions are made about the order of the items
- in the model that provides the completions.
-
- If the model's data for the completionColumn() and completionRole() is sorted in
- ascending order, you can set this property to \l CaseSensitivelySortedModel
- or \l CaseInsensitivelySortedModel. On large models, this can lead to
- significant performance improvements because the completer object can
- then use a binary search algorithm instead of linear search algorithm.
-
- The sort order (i.e ascending or descending order) of the model is determined
- dynamically by inspecting the contents of the model.
-
- \bold{Note:} The performance improvements described above cannot take place
- when the completer's \l caseSensitivity is different to the case sensitivity
- used by the model's when sorting.
-
- \sa setCaseSensitivity(), QCompleter::ModelSorting
-*/
-void QCompleter::setModelSorting(QCompleter::ModelSorting sorting)
-{
- Q_D(QCompleter);
- if (d->sorting == sorting)
- return;
- d->sorting = sorting;
- d->proxy->createEngine();
- d->proxy->invalidate();
-}
-
-QCompleter::ModelSorting QCompleter::modelSorting() const
-{
- Q_D(const QCompleter);
- return d->sorting;
-}
-
-/*!
- \property QCompleter::completionColumn
- \brief the column in the model in which completions are searched for.
-
- If the popup() is a QListView, it is automatically setup to display
- this column.
-
- By default, the match column is 0.
-
- \sa completionRole, caseSensitivity
-*/
-void QCompleter::setCompletionColumn(int column)
-{
- Q_D(QCompleter);
- if (d->column == column)
- return;
-#ifndef QT_NO_LISTVIEW
- if (QListView *listView = qobject_cast<QListView *>(d->popup))
- listView->setModelColumn(column);
-#endif
- d->column = column;
- d->proxy->invalidate();
-}
-
-int QCompleter::completionColumn() const
-{
- Q_D(const QCompleter);
- return d->column;
-}
-
-/*!
- \property QCompleter::completionRole
- \brief the item role to be used to query the contents of items for matching.
-
- The default role is Qt::EditRole.
-
- \sa completionColumn, caseSensitivity
-*/
-void QCompleter::setCompletionRole(int role)
-{
- Q_D(QCompleter);
- if (d->role == role)
- return;
- d->role = role;
- d->proxy->invalidate();
-}
-
-int QCompleter::completionRole() const
-{
- Q_D(const QCompleter);
- return d->role;
-}
-
-/*!
- \property QCompleter::wrapAround
- \brief the completions wrap around when navigating through items
- \since 4.3
-
- The default is true.
-*/
-void QCompleter::setWrapAround(bool wrap)
-{
- Q_D(QCompleter);
- if (d->wrap == wrap)
- return;
- d->wrap = wrap;
-}
-
-bool QCompleter::wrapAround() const
-{
- Q_D(const QCompleter);
- return d->wrap;
-}
-
-/*!
- \property QCompleter::maxVisibleItems
- \brief the maximum allowed size on screen of the completer, measured in items
- \since 4.6
-
- By default, this property has a value of 7.
-*/
-int QCompleter::maxVisibleItems() const
-{
- Q_D(const QCompleter);
- return d->maxVisibleItems;
-}
-
-void QCompleter::setMaxVisibleItems(int maxItems)
-{
- Q_D(QCompleter);
- if (maxItems < 0) {
- qWarning("QCompleter::setMaxVisibleItems: "
- "Invalid max visible items (%d) must be >= 0", maxItems);
- return;
- }
- d->maxVisibleItems = maxItems;
-}
-
-/*!
- \property QCompleter::caseSensitivity
- \brief the case sensitivity of the matching
-
- The default is Qt::CaseSensitive.
-
- \sa completionColumn, completionRole, modelSorting
-*/
-void QCompleter::setCaseSensitivity(Qt::CaseSensitivity cs)
-{
- Q_D(QCompleter);
- if (d->cs == cs)
- return;
- d->cs = cs;
- d->proxy->createEngine();
- d->proxy->invalidate();
-}
-
-Qt::CaseSensitivity QCompleter::caseSensitivity() const
-{
- Q_D(const QCompleter);
- return d->cs;
-}
-
-/*!
- \property QCompleter::completionPrefix
- \brief the completion prefix used to provide completions.
-
- The completionModel() is updated to reflect the list of possible
- matches for \a prefix.
-*/
-void QCompleter::setCompletionPrefix(const QString &prefix)
-{
- Q_D(QCompleter);
- d->prefix = prefix;
- d->proxy->filter(splitPath(prefix));
-}
-
-QString QCompleter::completionPrefix() const
-{
- Q_D(const QCompleter);
- return d->prefix;
-}
-
-/*!
- Returns the model index of the current completion in the completionModel().
-
- \sa setCurrentRow(), currentCompletion(), model()
-*/
-QModelIndex QCompleter::currentIndex() const
-{
- Q_D(const QCompleter);
- return d->proxy->currentIndex(false);
-}
-
-/*!
- Returns the current completion string. This includes the \l completionPrefix.
- When used alongside setCurrentRow(), it can be used to iterate through
- all the matches.
-
- \sa setCurrentRow(), currentIndex()
-*/
-QString QCompleter::currentCompletion() const
-{
- Q_D(const QCompleter);
- return pathFromIndex(d->proxy->currentIndex(true));
-}
-
-/*!
- Returns the completion model. The completion model is a read-only list model
- that contains all the possible matches for the current completion prefix.
- The completion model is auto-updated to reflect the current completions.
-
- \note The return value of this function is defined to be an QAbstractItemModel
- purely for generality. This actual kind of model returned is an instance of an
- QAbstractProxyModel subclass.
-
- \sa completionPrefix, model()
-*/
-QAbstractItemModel *QCompleter::completionModel() const
-{
- Q_D(const QCompleter);
- return d->proxy;
-}
-
-/*!
- Returns the path for the given \a index. The completer object uses this to
- obtain the completion text from the underlying model.
-
- The default implementation returns the \l{Qt::EditRole}{edit role} of the
- item for list models. It returns the absolute file path if the model is a
- QFileSystemModel.
-
- \sa splitPath()
-*/
-
-QString QCompleter::pathFromIndex(const QModelIndex& index) const
-{
- Q_D(const QCompleter);
- if (!index.isValid())
- return QString();
-
- QAbstractItemModel *sourceModel = d->proxy->sourceModel();
- if (!sourceModel)
- return QString();
- bool isDirModel = false;
- bool isFsModel = false;
-#ifndef QT_NO_DIRMODEL
- isDirModel = qobject_cast<QDirModel *>(d->proxy->sourceModel()) != 0;
-#endif
-#ifndef QT_NO_FILESYSTEMMODEL
- isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != 0;
-#endif
- if (!isDirModel && !isFsModel)
- return sourceModel->data(index, d->role).toString();
-
- QModelIndex idx = index;
- QStringList list;
- do {
- QString t;
- if (isDirModel)
- t = sourceModel->data(idx, Qt::EditRole).toString();
-#ifndef QT_NO_FILESYSTEMMODEL
- else
- t = sourceModel->data(idx, QFileSystemModel::FileNameRole).toString();
-#endif
- list.prepend(t);
- QModelIndex parent = idx.parent();
- idx = parent.sibling(parent.row(), index.column());
- } while (idx.isValid());
-
-#if (!defined(Q_OS_WIN) || defined(Q_OS_WINCE)) && !defined(Q_OS_SYMBIAN)
- if (list.count() == 1) // only the separator or some other text
- return list[0];
- list[0].clear() ; // the join below will provide the separator
-#endif
-
- return list.join(QDir::separator());
-}
-
-/*!
- Splits the given \a path into strings that are used to match at each level
- in the model().
-
- The default implementation of splitPath() splits a file system path based on
- QDir::separator() when the sourceModel() is a QFileSystemModel.
-
- When used with list models, the first item in the returned list is used for
- matching.
-
- \sa pathFromIndex(), {Handling Tree Models}
-*/
-QStringList QCompleter::splitPath(const QString& path) const
-{
- bool isDirModel = false;
- bool isFsModel = false;
-#ifndef QT_NO_DIRMODEL
- Q_D(const QCompleter);
- isDirModel = qobject_cast<QDirModel *>(d->proxy->sourceModel()) != 0;
-#endif
-#ifndef QT_NO_FILESYSTEMMODEL
-#ifdef QT_NO_DIRMODEL
- Q_D(const QCompleter);
-#endif
- isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != 0;
-#endif
-
- if ((!isDirModel && !isFsModel) || path.isEmpty())
- return QStringList(completionPrefix());
-
- QString pathCopy = QDir::toNativeSeparators(path);
- QString sep = QDir::separator();
-#if defined(Q_OS_SYMBIAN)
- if (pathCopy == QLatin1String("\\"))
- return QStringList(pathCopy);
-#elif defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (pathCopy == QLatin1String("\\") || pathCopy == QLatin1String("\\\\"))
- return QStringList(pathCopy);
- QString doubleSlash(QLatin1String("\\\\"));
- if (pathCopy.startsWith(doubleSlash))
- pathCopy = pathCopy.mid(2);
- else
- doubleSlash.clear();
-#endif
-
- QRegExp re(QLatin1Char('[') + QRegExp::escape(sep) + QLatin1Char(']'));
- QStringList parts = pathCopy.split(re);
-
-#if defined(Q_OS_SYMBIAN)
- // Do nothing
-#elif defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (!doubleSlash.isEmpty())
- parts[0].prepend(doubleSlash);
-#else
- if (pathCopy[0] == sep[0]) // readd the "/" at the beginning as the split removed it
- parts[0] = QDir::fromNativeSeparators(QString(sep[0]));
-#endif
-
- return parts;
-}
-
-/*!
- \fn void QCompleter::activated(const QModelIndex& index)
-
- This signal is sent when an item in the popup() is activated by the user.
- (by clicking or pressing return). The item's \a index in the completionModel()
- is given.
-
-*/
-
-/*!
- \fn void QCompleter::activated(const QString &text)
-
- This signal is sent when an item in the popup() is activated by the user (by
- clicking or pressing return). The item's \a text is given.
-
-*/
-
-/*!
- \fn void QCompleter::highlighted(const QModelIndex& index)
-
- This signal is sent when an item in the popup() is highlighted by
- the user. It is also sent if complete() is called with the completionMode()
- set to QCompleter::InlineCompletion. The item's \a index in the completionModel()
- is given.
-*/
-
-/*!
- \fn void QCompleter::highlighted(const QString &text)
-
- This signal is sent when an item in the popup() is highlighted by
- the user. It is also sent if complete() is called with the completionMode()
- set to QCompleter::InlineCompletion. The item's \a text is given.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qcompleter.cpp"
-
-#endif // QT_NO_COMPLETER
diff --git a/src/gui/util/qcompleter.h b/src/gui/util/qcompleter.h
deleted file mode 100644
index ace2f0afb6..0000000000
--- a/src/gui/util/qcompleter.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMPLETER_H
-#define QCOMPLETER_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qpoint.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qrect.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_COMPLETER
-
-class QCompleterPrivate;
-class QAbstractItemView;
-class QAbstractProxyModel;
-class QWidget;
-
-class Q_GUI_EXPORT QCompleter : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QString completionPrefix READ completionPrefix WRITE setCompletionPrefix)
- Q_PROPERTY(ModelSorting modelSorting READ modelSorting WRITE setModelSorting)
- Q_PROPERTY(CompletionMode completionMode READ completionMode WRITE setCompletionMode)
- Q_PROPERTY(int completionColumn READ completionColumn WRITE setCompletionColumn)
- Q_PROPERTY(int completionRole READ completionRole WRITE setCompletionRole)
- Q_PROPERTY(int maxVisibleItems READ maxVisibleItems WRITE setMaxVisibleItems)
- Q_PROPERTY(Qt::CaseSensitivity caseSensitivity READ caseSensitivity WRITE setCaseSensitivity)
- Q_PROPERTY(bool wrapAround READ wrapAround WRITE setWrapAround)
-
-public:
- enum CompletionMode {
- PopupCompletion,
- UnfilteredPopupCompletion,
- InlineCompletion
- };
-
- enum ModelSorting {
- UnsortedModel = 0,
- CaseSensitivelySortedModel,
- CaseInsensitivelySortedModel
- };
-
- QCompleter(QObject *parent = 0);
- QCompleter(QAbstractItemModel *model, QObject *parent = 0);
-#ifndef QT_NO_STRINGLISTMODEL
- QCompleter(const QStringList& completions, QObject *parent = 0);
-#endif
- ~QCompleter();
-
- void setWidget(QWidget *widget);
- QWidget *widget() const;
-
- void setModel(QAbstractItemModel *c);
- QAbstractItemModel *model() const;
-
- void setCompletionMode(CompletionMode mode);
- CompletionMode completionMode() const;
-
- QAbstractItemView *popup() const;
- void setPopup(QAbstractItemView *popup);
-
- void setCaseSensitivity(Qt::CaseSensitivity caseSensitivity);
- Qt::CaseSensitivity caseSensitivity() const;
-
- void setModelSorting(ModelSorting sorting);
- ModelSorting modelSorting() const;
-
- void setCompletionColumn(int column);
- int completionColumn() const;
-
- void setCompletionRole(int role);
- int completionRole() const;
-
- bool wrapAround() const;
-
- int maxVisibleItems() const;
- void setMaxVisibleItems(int maxItems);
-
- int completionCount() const;
- bool setCurrentRow(int row);
- int currentRow() const;
-
- QModelIndex currentIndex() const;
- QString currentCompletion() const;
-
- QAbstractItemModel *completionModel() const;
-
- QString completionPrefix() const;
-
-public Q_SLOTS:
- void setCompletionPrefix(const QString &prefix);
- void complete(const QRect& rect = QRect());
- void setWrapAround(bool wrap);
-
-public:
- virtual QString pathFromIndex(const QModelIndex &index) const;
- virtual QStringList splitPath(const QString &path) const;
-
-protected:
- bool eventFilter(QObject *o, QEvent *e);
- bool event(QEvent *);
-
-Q_SIGNALS:
- void activated(const QString &text);
- void activated(const QModelIndex &index);
- void highlighted(const QString &text);
- void highlighted(const QModelIndex &index);
-
-private:
- Q_DISABLE_COPY(QCompleter)
- Q_DECLARE_PRIVATE(QCompleter)
-
- Q_PRIVATE_SLOT(d_func(), void _q_complete(QModelIndex))
- Q_PRIVATE_SLOT(d_func(), void _q_completionSelected(const QItemSelection&))
- Q_PRIVATE_SLOT(d_func(), void _q_autoResizePopup())
- Q_PRIVATE_SLOT(d_func(), void _q_fileSystemModelDirectoryLoaded(const QString&))
-};
-
-#endif // QT_NO_COMPLETER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOMPLETER_H
diff --git a/src/gui/util/qcompleter_p.h b/src/gui/util/qcompleter_p.h
deleted file mode 100644
index 83e7a27636..0000000000
--- a/src/gui/util/qcompleter_p.h
+++ /dev/null
@@ -1,264 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMPLETER_P_H
-#define QCOMPLETER_P_H
-
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qobject_p.h"
-
-#ifndef QT_NO_COMPLETER
-
-#include "QtGui/qtreeview.h"
-#include "QtGui/qabstractproxymodel.h"
-#include "qcompleter.h"
-#include "QtGui/qitemdelegate.h"
-#include "QtGui/qpainter.h"
-#include "private/qabstractproxymodel_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QCompletionModel;
-
-class QCompleterPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QCompleter)
-
-public:
- QCompleterPrivate();
- ~QCompleterPrivate() { delete popup; }
- void init(QAbstractItemModel *model = 0);
-
- QPointer<QWidget> widget;
- QCompletionModel *proxy;
- QAbstractItemView *popup;
- QCompleter::CompletionMode mode;
-
- QString prefix;
- Qt::CaseSensitivity cs;
- int role;
- int column;
- int maxVisibleItems;
- QCompleter::ModelSorting sorting;
- bool wrap;
-
- bool eatFocusOut;
- QRect popupRect;
- bool hiddenBecauseNoMatch;
-
- void showPopup(const QRect&);
- void _q_complete(QModelIndex, bool = false);
- void _q_completionSelected(const QItemSelection&);
- void _q_autoResizePopup();
- void _q_fileSystemModelDirectoryLoaded(const QString &path);
- void setCurrentIndex(QModelIndex, bool = true);
-};
-
-class QIndexMapper
-{
-public:
- QIndexMapper() : v(false), f(0), t(-1) { }
- QIndexMapper(int f, int t) : v(false), f(f), t(t) { }
- QIndexMapper(QVector<int> vec) : v(true), vector(vec), f(-1), t(-1) { }
-
- inline int count() const { return v ? vector.count() : t - f + 1; }
- inline int operator[] (int index) const { return v ? vector[index] : f + index; }
- inline int indexOf(int x) const { return v ? vector.indexOf(x) : ((t < f) ? -1 : x - f); }
- inline bool isValid() const { return !isEmpty(); }
- inline bool isEmpty() const { return v ? vector.isEmpty() : (t < f); }
- inline void append(int x) { Q_ASSERT(v); vector.append(x); }
- inline int first() const { return v ? vector.first() : f; }
- inline int last() const { return v ? vector.last() : t; }
- inline int from() const { Q_ASSERT(!v); return f; }
- inline int to() const { Q_ASSERT(!v); return t; }
- inline int cost() const { return vector.count()+2; }
-
-private:
- bool v;
- QVector<int> vector;
- int f, t;
-};
-
-struct QMatchData {
- QMatchData() : exactMatchIndex(-1) { }
- QMatchData(const QIndexMapper& indices, int em, bool p) :
- indices(indices), exactMatchIndex(em), partial(p) { }
- QIndexMapper indices;
- inline bool isValid() const { return indices.isValid(); }
- int exactMatchIndex;
- bool partial;
-};
-
-class QCompletionEngine
-{
-public:
- typedef QMap<QString, QMatchData> CacheItem;
- typedef QMap<QModelIndex, CacheItem> Cache;
-
- QCompletionEngine(QCompleterPrivate *c) : c(c), curRow(-1), cost(0) { }
- virtual ~QCompletionEngine() { }
-
- void filter(const QStringList &parts);
-
- QMatchData filterHistory();
- bool matchHint(QString, const QModelIndex&, QMatchData*);
-
- void saveInCache(QString, const QModelIndex&, const QMatchData&);
- bool lookupCache(QString part, const QModelIndex& parent, QMatchData *m);
-
- virtual void filterOnDemand(int) { }
- virtual QMatchData filter(const QString&, const QModelIndex&, int) = 0;
-
- int matchCount() const { return curMatch.indices.count() + historyMatch.indices.count(); }
-
- QMatchData curMatch, historyMatch;
- QCompleterPrivate *c;
- QStringList curParts;
- QModelIndex curParent;
- int curRow;
-
- Cache cache;
- int cost;
-};
-
-class QSortedModelEngine : public QCompletionEngine
-{
-public:
- QSortedModelEngine(QCompleterPrivate *c) : QCompletionEngine(c) { }
- QMatchData filter(const QString&, const QModelIndex&, int);
- QIndexMapper indexHint(QString, const QModelIndex&, Qt::SortOrder);
- Qt::SortOrder sortOrder(const QModelIndex&) const;
-};
-
-class QUnsortedModelEngine : public QCompletionEngine
-{
-public:
- QUnsortedModelEngine(QCompleterPrivate *c) : QCompletionEngine(c) { }
-
- void filterOnDemand(int);
- QMatchData filter(const QString&, const QModelIndex&, int);
-private:
- int buildIndices(const QString& str, const QModelIndex& parent, int n,
- const QIndexMapper& iv, QMatchData* m);
-};
-
-class QCompleterItemDelegate : public QItemDelegate
-{
-public:
- QCompleterItemDelegate(QAbstractItemView *view)
- : QItemDelegate(view), view(view) { }
- void paint(QPainter *p, const QStyleOptionViewItem& opt, const QModelIndex& idx) const {
- QStyleOptionViewItem optCopy = opt;
- optCopy.showDecorationSelected = true;
- if (view->currentIndex() == idx)
- optCopy.state |= QStyle::State_HasFocus;
- QItemDelegate::paint(p, optCopy, idx);
- }
-
-private:
- QAbstractItemView *view;
-};
-
-class QCompletionModelPrivate;
-
-class QCompletionModel : public QAbstractProxyModel
-{
- Q_OBJECT
-
-public:
- QCompletionModel(QCompleterPrivate *c, QObject *parent);
-
- void createEngine();
- void setFiltered(bool);
- void filter(const QStringList& parts);
- int completionCount() const;
- int currentRow() const { return engine->curRow; }
- bool setCurrentRow(int row);
- QModelIndex currentIndex(bool) const;
- void resetModel();
-
- QModelIndex index(int row, int column, const QModelIndex & = QModelIndex()) const;
- int rowCount(const QModelIndex &index = QModelIndex()) const;
- int columnCount(const QModelIndex &index = QModelIndex()) const;
- bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex & = QModelIndex()) const { return QModelIndex(); }
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
-
- void setSourceModel(QAbstractItemModel *sourceModel);
- QModelIndex mapToSource(const QModelIndex& proxyIndex) const;
- QModelIndex mapFromSource(const QModelIndex& sourceIndex) const;
-
- QCompleterPrivate *c;
- QScopedPointer<QCompletionEngine> engine;
- bool showAll;
-
- Q_DECLARE_PRIVATE(QCompletionModel)
-
-signals:
- void rowsAdded();
-
-public Q_SLOTS:
- void invalidate();
- void rowsInserted();
- void modelDestroyed();
-};
-
-class QCompletionModelPrivate : public QAbstractProxyModelPrivate
-{
- Q_DECLARE_PUBLIC(QCompletionModel)
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_COMPLETER
-
-#endif // QCOMPLETER_P_H
diff --git a/src/gui/util/qflickgesture.cpp b/src/gui/util/qflickgesture.cpp
deleted file mode 100644
index fdd2a95333..0000000000
--- a/src/gui/util/qflickgesture.cpp
+++ /dev/null
@@ -1,715 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgesture.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qwidget.h"
-#include "qgraphicsitem.h"
-#include "qgraphicsscene.h"
-#include "qgraphicssceneevent.h"
-#include "qgraphicsview.h"
-#include "qscroller.h"
-#include "private/qevent_p.h"
-#include "private/qflickgesture_p.h"
-#include "qdebug.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-//#define QFLICKGESTURE_DEBUG
-
-#ifdef QFLICKGESTURE_DEBUG
-# define qFGDebug qDebug
-#else
-# define qFGDebug while (false) qDebug
-#endif
-
-extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
-
-static QMouseEvent *copyMouseEvent(QEvent *e)
-{
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseMove: {
- QMouseEvent *me = static_cast<QMouseEvent *>(e);
- return new QMouseEvent(me->type(), QPoint(0, 0), me->globalPos(), me->button(), me->buttons(), me->modifiers());
- }
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseMove: {
- QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(e);
-#if 1
- QEvent::Type met = me->type() == QEvent::GraphicsSceneMousePress ? QEvent::MouseButtonPress :
- (me->type() == QEvent::GraphicsSceneMouseRelease ? QEvent::MouseButtonRelease : QEvent::MouseMove);
- return new QMouseEvent(met, QPoint(0, 0), me->screenPos(), me->button(), me->buttons(), me->modifiers());
-#else
- QGraphicsSceneMouseEvent *copy = new QGraphicsSceneMouseEvent(me->type());
- copy->setPos(me->pos());
- copy->setScenePos(me->scenePos());
- copy->setScreenPos(me->screenPos());
- for (int i = 0x1; i <= 0x10; i <<= 1) {
- Qt::MouseButton button = Qt::MouseButton(i);
- copy->setButtonDownPos(button, me->buttonDownPos(button));
- copy->setButtonDownScenePos(button, me->buttonDownScenePos(button));
- copy->setButtonDownScreenPos(button, me->buttonDownScreenPos(button));
- }
- copy->setLastPos(me->lastPos());
- copy->setLastScenePos(me->lastScenePos());
- copy->setLastScreenPos(me->lastScreenPos());
- copy->setButtons(me->buttons());
- copy->setButton(me->button());
- copy->setModifiers(me->modifiers());
- return copy;
-#endif
- }
-#endif // QT_NO_GRAPHICSVIEW
- default:
- return 0;
- }
-}
-
-class PressDelayHandler : public QObject
-{
-private:
- PressDelayHandler(QObject *parent = 0)
- : QObject(parent)
- , pressDelayTimer(0)
- , sendingEvent(false)
- , mouseButton(Qt::NoButton)
- , mouseTarget(0)
- { }
-
- static PressDelayHandler *inst;
-
-public:
- enum {
- UngrabMouseBefore = 1,
- RegrabMouseAfterwards = 2
- };
-
- static PressDelayHandler *instance()
- {
- static PressDelayHandler *inst = 0;
- if (!inst)
- inst = new PressDelayHandler(QCoreApplication::instance());
- return inst;
- }
-
- bool shouldEventBeIgnored(QEvent *) const
- {
- return sendingEvent;
- }
-
- bool isDelaying() const
- {
- return !pressDelayEvent.isNull();
- }
-
- void pressed(QEvent *e, int delay)
- {
- if (!pressDelayEvent) {
- pressDelayEvent.reset(copyMouseEvent(e));
- pressDelayTimer = startTimer(delay);
- mouseTarget = QApplication::widgetAt(pressDelayEvent->globalPos());
- mouseButton = pressDelayEvent->button();
- qFGDebug() << "QFG: consuming/delaying mouse press";
- } else {
- qFGDebug() << "QFG: NOT consuming/delaying mouse press";
- }
- e->setAccepted(true);
- }
-
- bool released(QEvent *e, bool scrollerWasActive, bool scrollerIsActive)
- {
- // consume this event if the scroller was or is active
- bool result = scrollerWasActive || scrollerIsActive;
-
- // stop the timer
- if (pressDelayTimer) {
- killTimer(pressDelayTimer);
- pressDelayTimer = 0;
- }
- // we still haven't even sent the press, so do it now
- if (pressDelayEvent && mouseTarget && !scrollerIsActive) {
- QScopedPointer<QMouseEvent> releaseEvent(copyMouseEvent(e));
-
- qFGDebug() << "QFG: re-sending mouse press (due to release) for " << mouseTarget;
- sendMouseEvent(pressDelayEvent.data(), UngrabMouseBefore);
-
- qFGDebug() << "QFG: faking mouse release (due to release) for " << mouseTarget;
- sendMouseEvent(releaseEvent.data());
-
- result = true; // consume this event
- } else if (mouseTarget && scrollerIsActive) {
- // we grabbed the mouse expicitly when the scroller became active, so undo that now
- sendMouseEvent(0, UngrabMouseBefore);
- }
- pressDelayEvent.reset(0);
- mouseTarget = 0;
- return result;
- }
-
- void scrollerWasIntercepted()
- {
- qFGDebug() << "QFG: deleting delayed mouse press, since scroller was only intercepted";
- if (pressDelayEvent) {
- // we still haven't even sent the press, so just throw it away now
- if (pressDelayTimer) {
- killTimer(pressDelayTimer);
- pressDelayTimer = 0;
- }
- pressDelayEvent.reset(0);
- }
- mouseTarget = 0;
- }
-
- void scrollerBecameActive()
- {
- if (pressDelayEvent) {
- // we still haven't even sent the press, so just throw it away now
- qFGDebug() << "QFG: deleting delayed mouse press, since scroller is active now";
- if (pressDelayTimer) {
- killTimer(pressDelayTimer);
- pressDelayTimer = 0;
- }
- pressDelayEvent.reset(0);
- mouseTarget = 0;
- } else if (mouseTarget) {
- // we did send a press, so we need to fake a release now
- Qt::MouseButtons mouseButtons = QApplication::mouseButtons();
-
- // release all pressed mouse buttons
- /*for (int i = 0; i < 32; ++i) {
- if (mouseButtons & (1 << i)) {
- Qt::MouseButton b = static_cast<Qt::MouseButton>(1 << i);
- mouseButtons &= ~b;
- QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
-
- qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
- QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway,
- b, mouseButtons, QApplication::keyboardModifiers());
- sendMouseEvent(&re);
- }
- }*/
-
- QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
-
- qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
- QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway,
- mouseButton, QApplication::mouseButtons() & ~mouseButton,
- QApplication::keyboardModifiers());
- sendMouseEvent(&re, RegrabMouseAfterwards);
- // don't clear the mouseTarget just yet, since we need to explicitly ungrab the mouse on release!
- }
- }
-
-protected:
- void timerEvent(QTimerEvent *e)
- {
- if (e->timerId() == pressDelayTimer) {
- if (pressDelayEvent && mouseTarget) {
- qFGDebug() << "QFG: timer event: re-sending mouse press to " << mouseTarget;
- sendMouseEvent(pressDelayEvent.data(), UngrabMouseBefore);
- }
- pressDelayEvent.reset(0);
-
- if (pressDelayTimer) {
- killTimer(pressDelayTimer);
- pressDelayTimer = 0;
- }
- }
- }
-
- void sendMouseEvent(QMouseEvent *me, int flags = 0)
- {
- if (mouseTarget) {
- sendingEvent = true;
-
-#ifndef QT_NO_GRAPHICSVIEW
- QGraphicsItem *grabber = 0;
- if (mouseTarget->parentWidget()) {
- if (QGraphicsView *gv = qobject_cast<QGraphicsView *>(mouseTarget->parentWidget())) {
- if (gv->scene())
- grabber = gv->scene()->mouseGrabberItem();
- }
- }
-
- if (grabber && (flags & UngrabMouseBefore)) {
- // GraphicsView Mouse Handling Workaround #1:
- // we need to ungrab the mouse before re-sending the press,
- // since the scene had already set the mouse grabber to the
- // original (and consumed) event's receiver
- qFGDebug() << "QFG: ungrabbing" << grabber;
- grabber->ungrabMouse();
- }
-#endif // QT_NO_GRAPHICSVIEW
-
- if (me) {
- QMouseEvent copy(me->type(), mouseTarget->mapFromGlobal(me->globalPos()), me->globalPos(), me->button(), me->buttons(), me->modifiers());
- qt_sendSpontaneousEvent(mouseTarget, &copy);
- }
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (grabber && (flags & RegrabMouseAfterwards)) {
- // GraphicsView Mouse Handling Workaround #2:
- // we need to re-grab the mouse after sending a faked mouse
- // release, since we still need the mouse moves for the gesture
- // (the scene will clear the item's mouse grabber status on
- // release).
- qFGDebug() << "QFG: re-grabbing" << grabber;
- grabber->grabMouse();
- }
-#endif
- sendingEvent = false;
- }
- }
-
-
-private:
- int pressDelayTimer;
- QScopedPointer<QMouseEvent> pressDelayEvent;
- bool sendingEvent;
- Qt::MouseButton mouseButton;
- QPointer<QWidget> mouseTarget;
-};
-
-
-/*!
- \internal
- \class QFlickGesture
- \since 4.8
- \brief The QFlickGesture class describes a flicking gesture made by the user.
- \ingroup gestures
- The QFlickGesture is more complex than the QPanGesture that uses QScroller and QScrollerProperties
- to decide if it is triggered.
- This gesture is reacting on touch event as compared to the QMouseFlickGesture.
-
- \sa {Gestures Programming}, QScroller, QScrollerProperties, QMouseFlickGesture
-*/
-
-/*!
- \internal
-*/
-QFlickGesture::QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent)
- : QGesture(*new QFlickGesturePrivate, parent)
-{
- d_func()->q_ptr = this;
- d_func()->receiver = receiver;
- d_func()->receiverScroller = (receiver && QScroller::hasScroller(receiver)) ? QScroller::scroller(receiver) : 0;
- d_func()->button = button;
-}
-
-QFlickGesture::~QFlickGesture()
-{ }
-
-QFlickGesturePrivate::QFlickGesturePrivate()
- : receiverScroller(0), button(Qt::NoButton), macIgnoreWheel(false)
-{ }
-
-
-//
-// QFlickGestureRecognizer
-//
-
-
-QFlickGestureRecognizer::QFlickGestureRecognizer(Qt::MouseButton button)
-{
- this->button = button;
-}
-
-/*! \reimp
- */
-QGesture *QFlickGestureRecognizer::create(QObject *target)
-{
-#ifndef QT_NO_GRAPHICSVIEW
- QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target);
- if (go && button == Qt::NoButton) {
- go->setAcceptTouchEvents(true);
- }
-#endif
- return new QFlickGesture(target, button);
-}
-
-/*! \internal
- The recognize function detects a touch event suitable to start the attached QScroller.
- The QFlickGesture will be triggered as soon as the scroller is no longer in the state
- QScroller::Inactive or QScroller::Pressed. It will be finished or canceled
- at the next QEvent::TouchEnd.
- Note that the QScroller might continue scrolling (kinetically) at this point.
- */
-QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
- QObject *watched,
- QEvent *event)
-{
- Q_UNUSED(watched);
-
- static QElapsedTimer monotonicTimer;
- if (!monotonicTimer.isValid())
- monotonicTimer.start();
-
- QFlickGesture *q = static_cast<QFlickGesture *>(state);
- QFlickGesturePrivate *d = q->d_func();
-
- QScroller *scroller = d->receiverScroller;
- if (!scroller)
- return Ignore; // nothing to do without a scroller?
-
- QWidget *receiverWidget = qobject_cast<QWidget *>(d->receiver);
-#ifndef QT_NO_GRAPHICSVIEW
- QGraphicsObject *receiverGraphicsObject = qobject_cast<QGraphicsObject *>(d->receiver);
-#endif
-
- // this is only set for events that we inject into the event loop via sendEvent()
- if (PressDelayHandler::instance()->shouldEventBeIgnored(event)) {
- //qFGDebug() << state << "QFG: ignored event: " << event->type();
- return Ignore;
- }
-
- const QMouseEvent *me = 0;
-#ifndef QT_NO_GRAPHICSVIEW
- const QGraphicsSceneMouseEvent *gsme = 0;
-#endif
- const QTouchEvent *te = 0;
- QPoint globalPos;
-
- // qFGDebug() << "FlickGesture "<<state<<"watched:"<<watched<<"receiver"<<d->receiver<<"event"<<event->type()<<"button"<<button;
-
- switch (event->type()) {
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseMove:
- if (!receiverWidget)
- return Ignore;
- if (button != Qt::NoButton) {
- me = static_cast<const QMouseEvent *>(event);
- globalPos = me->globalPos();
- }
- break;
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMousePress:
- case QEvent::GraphicsSceneMouseRelease:
- case QEvent::GraphicsSceneMouseMove:
- if (!receiverGraphicsObject)
- return Ignore;
- if (button != Qt::NoButton) {
- gsme = static_cast<const QGraphicsSceneMouseEvent *>(event);
- globalPos = gsme->screenPos();
- }
- break;
-#endif
- case QEvent::TouchBegin:
- case QEvent::TouchEnd:
- case QEvent::TouchUpdate:
- if (button == Qt::NoButton) {
- te = static_cast<const QTouchEvent *>(event);
- if (!te->touchPoints().isEmpty())
- globalPos = te->touchPoints().at(0).screenPos().toPoint();
- }
- break;
-
-#if defined(Q_WS_MAC)
- // the only way to distinguish between real mouse wheels and wheel
- // events generated by the native 2 finger swipe gesture is to listen
- // for these events (according to Apple's Cocoa Event-Handling Guide)
-
- case QEvent::NativeGesture: {
- QNativeGestureEvent *nge = static_cast<QNativeGestureEvent *>(event);
- if (nge->gestureType == QNativeGestureEvent::GestureBegin)
- d->macIgnoreWheel = true;
- else if (nge->gestureType == QNativeGestureEvent::GestureEnd)
- d->macIgnoreWheel = false;
- break;
- }
-#endif
-
- // consume all wheel events if the scroller is active
- case QEvent::Wheel:
- if (d->macIgnoreWheel || (scroller->state() != QScroller::Inactive))
- return Ignore | ConsumeEventHint;
- break;
-
- // consume all dbl click events if the scroller is active
- case QEvent::MouseButtonDblClick:
- if (scroller->state() != QScroller::Inactive)
- return Ignore | ConsumeEventHint;
- break;
-
- default:
- break;
- }
-
- if (!me
-#ifndef QT_NO_GRAPHICSVIEW
- && !gsme
-#endif
- && !te) // Neither mouse nor touch
- return Ignore;
-
- // get the current pointer position in local coordinates.
- QPointF point;
- QScroller::Input inputType = (QScroller::Input) 0;
-
- switch (event->type()) {
- case QEvent::MouseButtonPress:
- if (me && me->button() == button && me->buttons() == button) {
- point = me->globalPos();
- inputType = QScroller::InputPress;
- } else if (me) {
- scroller->stop();
- return CancelGesture;
- }
- break;
- case QEvent::MouseButtonRelease:
- if (me && me->button() == button) {
- point = me->globalPos();
- inputType = QScroller::InputRelease;
- }
- break;
- case QEvent::MouseMove:
-#ifdef Q_OS_SYMBIAN
- // Qt on Symbian tracks the button state internally, while Qt on Win/Mac/Unix
- // relies on the windowing system to report the current buttons state.
- if (me && (me->buttons() == button || !me->buttons())) {
-#else
- if (me && me->buttons() == button) {
-#endif
- point = me->globalPos();
- inputType = QScroller::InputMove;
- }
- break;
-
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMousePress:
- if (gsme && gsme->button() == button && gsme->buttons() == button) {
- point = gsme->scenePos();
- inputType = QScroller::InputPress;
- } else if (gsme) {
- scroller->stop();
- return CancelGesture;
- }
- break;
- case QEvent::GraphicsSceneMouseRelease:
- if (gsme && gsme->button() == button) {
- point = gsme->scenePos();
- inputType = QScroller::InputRelease;
- }
- break;
- case QEvent::GraphicsSceneMouseMove:
-#ifdef Q_OS_SYMBIAN
- // Qt on Symbian tracks the button state internally, while Qt on Win/Mac/Unix
- // relies on the windowing system to report the current buttons state.
- if (gsme && (gsme->buttons() == button || !me->buttons())) {
-#else
- if (gsme && gsme->buttons() == button) {
-#endif
- point = gsme->scenePos();
- inputType = QScroller::InputMove;
- }
- break;
-#endif
-
- case QEvent::TouchBegin:
- inputType = QScroller::InputPress;
- // fall through
- case QEvent::TouchEnd:
- if (!inputType)
- inputType = QScroller::InputRelease;
- // fallthrough
- case QEvent::TouchUpdate:
- if (!inputType)
- inputType = QScroller::InputMove;
-
- if (te->deviceType() == QTouchEvent::TouchPad) {
- if (te->touchPoints().count() != 2) // 2 fingers on pad
- return Ignore;
-
- point = te->touchPoints().at(0).startScenePos() +
- ((te->touchPoints().at(0).scenePos() - te->touchPoints().at(0).startScenePos()) +
- (te->touchPoints().at(1).scenePos() - te->touchPoints().at(1).startScenePos())) / 2;
- } else { // TouchScreen
- if (te->touchPoints().count() != 1) // 1 finger on screen
- return Ignore;
-
- point = te->touchPoints().at(0).scenePos();
- }
- break;
-
- default:
- break;
- }
-
- // Check for an active scroller at globalPos
- if (inputType == QScroller::InputPress) {
- foreach (QScroller *as, QScroller::activeScrollers()) {
- if (as != scroller) {
- QRegion scrollerRegion;
-
- if (QWidget *w = qobject_cast<QWidget *>(as->target())) {
- scrollerRegion = QRect(w->mapToGlobal(QPoint(0, 0)), w->size());
-#ifndef QT_NO_GRAPHICSVIEW
- } else if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(as->target())) {
- if (go->scene() && !go->scene()->views().isEmpty()) {
- foreach (QGraphicsView *gv, go->scene()->views())
- scrollerRegion |= gv->mapFromScene(go->mapToScene(go->boundingRect()))
- .translated(gv->mapToGlobal(QPoint(0, 0)));
- }
-#endif
- }
- // active scrollers always have priority
- if (scrollerRegion.contains(globalPos))
- return Ignore;
- }
- }
- }
-
- bool scrollerWasDragging = (scroller->state() == QScroller::Dragging);
- bool scrollerWasScrolling = (scroller->state() == QScroller::Scrolling);
-
- if (inputType) {
- if (QWidget *w = qobject_cast<QWidget *>(d->receiver))
- point = w->mapFromGlobal(point.toPoint());
-#ifndef QT_NO_GRAPHICSVIEW
- else if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(d->receiver))
- point = go->mapFromScene(point);
-#endif
-
- // inform the scroller about the new event
- scroller->handleInput(inputType, point, monotonicTimer.elapsed());
- }
-
- // depending on the scroller state return the gesture state
- Result result(0);
- bool scrollerIsActive = (scroller->state() == QScroller::Dragging ||
- scroller->state() == QScroller::Scrolling);
-
- // Consume all mouse events while dragging or scrolling to avoid nasty
- // side effects with Qt's standard widgets.
- if ((me
-#ifndef QT_NO_GRAPHICSVIEW
- || gsme
-#endif
- ) && scrollerIsActive)
- result |= ConsumeEventHint;
-
- // The only problem with this approach is that we consume the
- // MouseRelease when we start the scrolling with a flick gesture, so we
- // have to fake a MouseRelease "somewhere" to not mess with the internal
- // states of Qt's widgets (a QPushButton would stay in 'pressed' state
- // forever, if it doesn't receive a MouseRelease).
- if (me
-#ifndef QT_NO_GRAPHICSVIEW
- || gsme
-#endif
- ) {
- if (!scrollerWasDragging && !scrollerWasScrolling && scrollerIsActive)
- PressDelayHandler::instance()->scrollerBecameActive();
- else if (scrollerWasScrolling && (scroller->state() == QScroller::Dragging || scroller->state() == QScroller::Inactive))
- PressDelayHandler::instance()->scrollerWasIntercepted();
- }
-
- if (!inputType) {
- result |= Ignore;
- } else {
- switch (event->type()) {
- case QEvent::MouseButtonPress:
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMousePress:
-#endif
- if (scroller->state() == QScroller::Pressed) {
- int pressDelay = int(1000 * scroller->scrollerProperties().scrollMetric(QScrollerProperties::MousePressEventDelay).toReal());
- if (pressDelay > 0) {
- result |= ConsumeEventHint;
-
- PressDelayHandler::instance()->pressed(event, pressDelay);
- event->accept();
- }
- }
- // fall through
- case QEvent::TouchBegin:
- q->setHotSpot(globalPos);
- result |= scrollerIsActive ? TriggerGesture : MayBeGesture;
- break;
-
- case QEvent::MouseMove:
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseMove:
-#endif
- if (PressDelayHandler::instance()->isDelaying())
- result |= ConsumeEventHint;
- // fall through
- case QEvent::TouchUpdate:
- result |= scrollerIsActive ? TriggerGesture : Ignore;
- break;
-
-#ifndef QT_NO_GRAPHICSVIEW
- case QEvent::GraphicsSceneMouseRelease:
-#endif
- case QEvent::MouseButtonRelease:
- if (PressDelayHandler::instance()->released(event, scrollerWasDragging || scrollerWasScrolling, scrollerIsActive))
- result |= ConsumeEventHint;
- // fall through
- case QEvent::TouchEnd:
- result |= scrollerIsActive ? FinishGesture : CancelGesture;
- break;
-
- default:
- result |= Ignore;
- break;
- }
- }
- return result;
-}
-
-
-/*! \reimp
- */
-void QFlickGestureRecognizer::reset(QGesture *state)
-{
- QGestureRecognizer::reset(state);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/util/qflickgesture_p.h b/src/gui/util/qflickgesture_p.h
deleted file mode 100644
index 451b579edd..0000000000
--- a/src/gui/util/qflickgesture_p.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** 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 QFLICKGESTURE_P_H
-#define QFLICKGESTURE_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 "qevent.h"
-#include "qgesturerecognizer.h"
-#include "private/qgesture_p.h"
-#include "qscroller.h"
-#include "qscopedpointer.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-class QFlickGesturePrivate;
-class QGraphicsItem;
-
-class Q_GUI_EXPORT QFlickGesture : public QGesture
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QFlickGesture)
-
-public:
- QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent = 0);
- ~QFlickGesture();
-
- friend class QFlickGestureRecognizer;
-};
-
-class PressDelayHandler;
-
-class QFlickGesturePrivate : public QGesturePrivate
-{
- Q_DECLARE_PUBLIC(QFlickGesture)
-public:
- QFlickGesturePrivate();
-
- QPointer<QObject> receiver;
- QScroller *receiverScroller;
- Qt::MouseButton button; // NoButton == Touch
- bool macIgnoreWheel;
- static PressDelayHandler *pressDelayHandler;
-};
-
-class QFlickGestureRecognizer : public QGestureRecognizer
-{
-public:
- QFlickGestureRecognizer(Qt::MouseButton button);
-
- QGesture *create(QObject *target);
- QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
- void reset(QGesture *state);
-
-private:
- Qt::MouseButton button; // NoButton == Touch
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QFLICKGESTURE_P_H
diff --git a/src/gui/util/qscroller.cpp b/src/gui/util/qscroller.cpp
deleted file mode 100644
index db128c136a..0000000000
--- a/src/gui/util/qscroller.cpp
+++ /dev/null
@@ -1,2059 +0,0 @@
-/****************************************************************************
-**
-** 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 "qevent.h"
-#include "qwidget.h"
-#include "qscroller.h"
-#include "private/qflickgesture_p.h"
-#include "private/qscroller_p.h"
-#include "qscrollerproperties.h"
-#include "private/qscrollerproperties_p.h"
-#include "qnumeric.h"
-#include "math.h"
-
-#include <QTime>
-#include <QElapsedTimer>
-#include <QMap>
-#include <QApplication>
-#include <QAbstractScrollArea>
-#include <QGraphicsObject>
-#include <QGraphicsScene>
-#include <QGraphicsView>
-#include <QDesktopWidget>
-#include <QtCore/qmath.h>
-#include <QtGui/qevent.h>
-#include <qnumeric.h>
-
-#include <QtDebug>
-
-#if defined(Q_WS_X11)
-# include "private/qt_x11_p.h"
-#endif
-
-
-QT_BEGIN_NAMESPACE
-
-bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
-
-//#define QSCROLLER_DEBUG
-
-#ifdef QSCROLLER_DEBUG
-# define qScrollerDebug qDebug
-#else
-# define qScrollerDebug while (false) qDebug
-#endif
-
-QDebug &operator<<(QDebug &dbg, const QScrollerPrivate::ScrollSegment &s)
-{
- dbg << "\n Time: start:" << s.startTime << " duration:" << s.deltaTime << " stop progress:" << s.stopProgress;
- dbg << "\n Pos: start:" << s.startPos << " delta:" << s.deltaPos << " stop:" << s.stopPos;
- dbg << "\n Curve: type:" << s.curve.type() << "\n";
- return dbg;
-}
-
-
-// a few helper operators to make the code below a lot more readable:
-// otherwise a lot of ifs would have to be multi-line to check both the x
-// and y coordinate separately.
-
-// returns true only if the abs. value of BOTH x and y are <= f
-inline bool operator<=(const QPointF &p, qreal f)
-{
- return (qAbs(p.x()) <= f) && (qAbs(p.y()) <= f);
-}
-
-// returns true only if the abs. value of BOTH x and y are < f
-inline bool operator<(const QPointF &p, qreal f)
-{
- return (qAbs(p.x()) < f) && (qAbs(p.y()) < f);
-}
-
-// returns true if the abs. value of EITHER x or y are >= f
-inline bool operator>=(const QPointF &p, qreal f)
-{
- return (qAbs(p.x()) >= f) || (qAbs(p.y()) >= f);
-}
-
-// returns true if the abs. value of EITHER x or y are > f
-inline bool operator>(const QPointF &p, qreal f)
-{
- return (qAbs(p.x()) > f) || (qAbs(p.y()) > f);
-}
-
-// returns a new point with both coordinates having the abs. value of the original one
-inline QPointF qAbs(const QPointF &p)
-{
- return QPointF(qAbs(p.x()), qAbs(p.y()));
-}
-
-// returns a new point with all components of p1 multiplied by the corresponding components of p2
-inline QPointF operator*(const QPointF &p1, const QPointF &p2)
-{
- return QPointF(p1.x() * p2.x(), p1.y() * p2.y());
-}
-
-// returns a new point with all components of p1 divided by the corresponding components of p2
-inline QPointF operator/(const QPointF &p1, const QPointF &p2)
-{
- return QPointF(p1.x() / p2.x(), p1.y() / p2.y());
-}
-
-inline QPointF clampToRect(const QPointF &p, const QRectF &rect)
-{
- qreal x = qBound(rect.left(), p.x(), rect.right());
- qreal y = qBound(rect.top(), p.y(), rect.bottom());
- return QPointF(x, y);
-}
-
-// returns -1, 0 or +1 according to r being <0, ==0 or >0
-inline int qSign(qreal r)
-{
- return (r < 0) ? -1 : ((r > 0) ? 1 : 0);
-}
-
-// this version is not mathematically exact, but it just works for every
-// easing curve type (even custom ones)
-
-static qreal differentialForProgress(const QEasingCurve &curve, qreal pos)
-{
- const qreal dx = 0.01;
- qreal left = (pos < qreal(0.5)) ? pos : pos - qreal(dx);
- qreal right = (pos >= qreal(0.5)) ? pos : pos + qreal(dx);
- qreal d = (curve.valueForProgress(right) - curve.valueForProgress(left)) / qreal(dx);
-
- //qScrollerDebug() << "differentialForProgress(type: " << curve.type() << ", pos: " << pos << ") = " << d;
-
- return d;
-}
-
-// this version is not mathematically exact, but it just works for every
-// easing curve type (even custom ones)
-
-static qreal progressForValue(const QEasingCurve &curve, qreal value)
-{
- if (curve.type() >= QEasingCurve::InElastic &&
- curve.type() < QEasingCurve::Custom) {
- qWarning("progressForValue(): QEasingCurves of type %d do not have an inverse, since they are not injective.", curve.type());
- return value;
- }
- if (value < qreal(0) || value > qreal(1))
- return value;
-
- qreal progress = value, left(0), right(1);
- for (int iterations = 6; iterations; --iterations) {
- qreal v = curve.valueForProgress(progress);
- if (v < value)
- left = progress;
- else if (v > value)
- right = progress;
- else
- break;
- progress = (left + right) / qreal(2);
- }
- return progress;
-}
-
-
-#ifndef QT_NO_ANIMATION
-class QScrollTimer : public QAbstractAnimation
-{
-public:
- QScrollTimer(QScrollerPrivate *_d)
- : d(_d), ignoreUpdate(false), skip(0)
- { }
-
- int duration() const
- {
- return -1;
- }
-
- void start()
- {
- // QAbstractAnimation::start() will immediately call
- // updateCurrentTime(), but our state is not set correctly yet
- ignoreUpdate = true;
- QAbstractAnimation::start();
- ignoreUpdate = false;
- skip = 0;
- }
-
-protected:
- void updateCurrentTime(int /*currentTime*/)
- {
- if (!ignoreUpdate) {
- if (++skip >= d->frameRateSkip()) {
- skip = 0;
- d->timerTick();
- }
- }
- }
-
-private:
- QScrollerPrivate *d;
- bool ignoreUpdate;
- int skip;
-};
-#endif // QT_NO_ANIMATION
-
-/*!
- \class QScroller
- \brief The QScroller class enables kinetic scrolling for any scrolling widget or graphics item.
- \since 4.8
-
- With kinetic scrolling, the user can push the widget in a given
- direction and it will continue to scroll in this direction until it is
- stopped either by the user or by friction. Aspects of inertia, friction
- and other physical concepts can be changed in order to fine-tune an
- intuitive user experience.
-
- The QScroller object is the object that stores the current position and
- scrolling speed and takes care of updates.
- QScroller can be triggered by a flick gesture
-
- \code
- QWidget *w = ...;
- QScroller::grabGesture(w, QScroller::LeftMouseButtonGesture);
- \endcode
-
- or directly like this:
-
- \code
- QWidget *w = ...;
- QScroller *scroller = QScroller::scroller(w);
- scroller->scrollTo(QPointF(100, 100));
- \endcode
-
- The scrolled QObjects receive a QScrollPrepareEvent whenever the scroller needs to
- update its geometry information and a QScrollEvent whenever the content of the object should
- actually be scrolled.
-
- The scroller uses the global QAbstractAnimation timer to generate its QScrollEvents. This
- can be changed with QScrollerProperties::FrameRate on a per-QScroller basis.
-
- Several examples in the \c scroller examples directory show how QScroller,
- QScrollEvent and the scroller gesture can be used.
-
- Even though this kinetic scroller has a large number of settings available via
- QScrollerProperties, we recommend that you leave them all at their default, platform optimized
- values. Before changing them you can experiment with the \c plot example in
- the \c scroller examples directory.
-
- \sa QScrollEvent, QScrollPrepareEvent, QScrollerProperties
-*/
-
-typedef QMap<QObject *, QScroller *> ScrollerHash;
-typedef QSet<QScroller *> ScrollerSet;
-
-Q_GLOBAL_STATIC(ScrollerHash, qt_allScrollers)
-Q_GLOBAL_STATIC(ScrollerSet, qt_activeScrollers)
-
-/*!
- Returns \c true if a QScroller object was already created for \a target; \c false otherwise.
-
- \sa scroller()
-*/
-bool QScroller::hasScroller(QObject *target)
-{
- return (qt_allScrollers()->value(target));
-}
-
-/*!
- Returns the scroller for the given \a target.
- As long as the object exists this function will always return the same QScroller instance.
- If no QScroller exists for the \a target, one will implicitly be created.
- At no point more than one QScroller will be active on an object.
-
- \sa hasScroller(), target()
-*/
-QScroller *QScroller::scroller(QObject *target)
-{
- if (!target) {
- qWarning("QScroller::scroller() was called with a null target.");
- return 0;
- }
-
- if (qt_allScrollers()->contains(target))
- return qt_allScrollers()->value(target);
-
- QScroller *s = new QScroller(target);
- qt_allScrollers()->insert(target, s);
- return s;
-}
-
-/*!
- \overload
- This is the const version of scroller().
-*/
-const QScroller *QScroller::scroller(const QObject *target)
-{
- return scroller(const_cast<QObject*>(target));
-}
-
-/*!
- Returns an application wide list of currently active QScroller objects.
- Active QScroller objects are in a state() that is not QScroller::Inactive.
- This function is useful when writing your own gesture recognizer.
-*/
-QList<QScroller *> QScroller::activeScrollers()
-{
- return qt_activeScrollers()->toList();
-}
-
-/*!
- Returns the target object of this scroller.
- \sa hasScroller(), scroller()
- */
-QObject *QScroller::target() const
-{
- Q_D(const QScroller);
- return d->target;
-}
-
-/*!
- \fn QScroller::scrollerPropertiesChanged(const QScrollerProperties &newProperties);
-
- QScroller emits this signal whenever its scroller properties change.
- \a newProperties are the new scroller properties.
-
- \sa scrollerProperties
-*/
-
-
-/*! \property QScroller::scrollerProperties
- \brief The scroller properties of this scroller.
- The properties are used by the QScroller to determine its scrolling behavior.
-*/
-QScrollerProperties QScroller::scrollerProperties() const
-{
- Q_D(const QScroller);
- return d->properties;
-}
-
-void QScroller::setScrollerProperties(const QScrollerProperties &sp)
-{
- Q_D(QScroller);
- if (d->properties != sp) {
- d->properties = sp;
- emit scrollerPropertiesChanged(sp);
-
- // we need to force the recalculation here, since the overshootPolicy may have changed and
- // existing segments may include an overshoot animation.
- d->recalcScrollingSegments(true);
- }
-}
-
-#ifndef QT_NO_GESTURES
-
-/*!
- Registers a custom scroll gesture recognizer, grabs it for the \a
- target and returns the resulting gesture type. If \a scrollGestureType is
- set to TouchGesture the gesture triggers on touch events. If it is set to
- one of LeftMouseButtonGesture, RightMouseButtonGesture or
- MiddleMouseButtonGesture it triggers on mouse events of the
- corresponding button.
-
- Only one scroll gesture can be active on a single object at the same
- time. If you call this function twice on the same object, it will
- ungrab the existing gesture before grabbing the new one.
-
- \note To avoid unwanted side-effects, mouse events are consumed while
- the gesture is triggered. Since the initial mouse press event is
- not consumed, the gesture sends a fake mouse release event
- at the global position \c{(INT_MIN, INT_MIN)}. This ensures that
- internal states of the widget that received the original mouse press
- are consistent.
-
- \sa ungrabGesture, grabbedGesture
-*/
-Qt::GestureType QScroller::grabGesture(QObject *target, ScrollerGestureType scrollGestureType)
-{
- // ensure that a scroller for target is created
- QScroller *s = scroller(target);
- if (!s)
- return Qt::GestureType(0);
-
- QScrollerPrivate *sp = s->d_ptr;
- if (sp->recognizer)
- ungrabGesture(target); // ungrab the old gesture
-
- Qt::MouseButton button;
- switch (scrollGestureType) {
- case LeftMouseButtonGesture : button = Qt::LeftButton; break;
- case RightMouseButtonGesture : button = Qt::RightButton; break;
- case MiddleMouseButtonGesture: button = Qt::MiddleButton; break;
- default :
- case TouchGesture : button = Qt::NoButton; break; // NoButton == Touch
- }
-
- sp->recognizer = new QFlickGestureRecognizer(button);
- sp->recognizerType = QGestureRecognizer::registerRecognizer(sp->recognizer);
-
- if (target->isWidgetType()) {
- QWidget *widget = static_cast<QWidget *>(target);
- widget->grabGesture(sp->recognizerType);
- if (scrollGestureType == TouchGesture)
- widget->setAttribute(Qt::WA_AcceptTouchEvents);
-#ifndef QT_NO_GRAPHICSVIEW
- } else if (QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target)) {
- if (scrollGestureType == TouchGesture)
- go->setAcceptTouchEvents(true);
- go->grabGesture(sp->recognizerType);
-#endif // QT_NO_GRAPHICSVIEW
- }
- return sp->recognizerType;
-}
-
-/*!
- Returns the gesture type currently grabbed for the \a target or 0 if no
- gesture is grabbed.
-
- \sa grabGesture, ungrabGesture
-*/
-Qt::GestureType QScroller::grabbedGesture(QObject *target)
-{
- QScroller *s = scroller(target);
- if (s && s->d_ptr)
- return s->d_ptr->recognizerType;
- else
- return Qt::GestureType(0);
-}
-
-/*!
- Ungrabs the gesture for the \a target.
- Does nothing if no gesture is grabbed.
-
- \sa grabGesture, grabbedGesture
-*/
-void QScroller::ungrabGesture(QObject *target)
-{
- QScroller *s = scroller(target);
- if (!s)
- return;
-
- QScrollerPrivate *sp = s->d_ptr;
- if (!sp->recognizer)
- return; // nothing to do
-
- if (target->isWidgetType()) {
- QWidget *widget = static_cast<QWidget *>(target);
- widget->ungrabGesture(sp->recognizerType);
-#ifndef QT_NO_GRAPHICSVIEW
- } else if (QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target)) {
- go->ungrabGesture(sp->recognizerType);
-#endif
- }
-
- QGestureRecognizer::unregisterRecognizer(sp->recognizerType);
- // do not delete the recognizer. The QGestureManager is doing this.
- sp->recognizer = 0;
-}
-
-#endif // QT_NO_GESTURES
-
-/*!
- \internal
-*/
-QScroller::QScroller(QObject *target)
- : d_ptr(new QScrollerPrivate(this, target))
-{
- Q_ASSERT(target); // you can't create a scroller without a target in any normal way
- Q_D(QScroller);
- d->init();
-}
-
-/*!
- \internal
-*/
-QScroller::~QScroller()
-{
- Q_D(QScroller);
-#ifndef QT_NO_GESTURES
- QGestureRecognizer::unregisterRecognizer(d->recognizerType);
- // do not delete the recognizer. The QGestureManager is doing this.
- d->recognizer = 0;
-#endif
- qt_allScrollers()->remove(d->target);
- qt_activeScrollers()->remove(this);
-
- delete d_ptr;
-}
-
-
-/*!
- \fn QScroller::stateChanged(QScroller::State newState);
-
- QScroller emits this signal whenever the state changes. \a newState is the new State.
-
- \sa state
-*/
-
-/*!
- \property QScroller::state
- \brief the state of the scroller
-
- \sa QScroller::State
-*/
-QScroller::State QScroller::state() const
-{
- Q_D(const QScroller);
- return d->state;
-}
-
-/*!
- Stops the scroller and resets its state back to Inactive.
-*/
-void QScroller::stop()
-{
- Q_D(QScroller);
- if (d->state != Inactive) {
- QPointF here = clampToRect(d->contentPosition, d->contentPosRange);
- qreal snapX = d->nextSnapPos(here.x(), 0, Qt::Horizontal);
- qreal snapY = d->nextSnapPos(here.y(), 0, Qt::Vertical);
- QPointF snap = here;
- if (!qIsNaN(snapX))
- snap.setX(snapX);
- if (!qIsNaN(snapY))
- snap.setY(snapY);
- d->contentPosition = snap;
- d->overshootPosition = QPointF(0, 0);
-
- d->setState(Inactive);
- }
-}
-
-/*!
- Returns the pixel per meter metric for the scrolled widget.
-
- The value is reported for both the x and y axis separately by using a QPointF.
-
- \note Please note that this value should be physically correct. The actual DPI settings
- that Qt returns for the display may be reported wrongly on purpose by the underlying
- windowing system, for example on Mac OS X or Maemo 5.
-*/
-QPointF QScroller::pixelPerMeter() const
-{
- Q_D(const QScroller);
- QPointF ppm = d->pixelPerMeter;
-
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(d->target)) {
- QTransform viewtr;
- //TODO: the first view isn't really correct - maybe use an additional field in the prepare event?
- if (go->scene() && !go->scene()->views().isEmpty())
- viewtr = go->scene()->views().first()->viewportTransform();
- QTransform tr = go->deviceTransform(viewtr);
- if (tr.isScaling()) {
- QPointF p0 = tr.map(QPointF(0, 0));
- QPointF px = tr.map(QPointF(1, 0));
- QPointF py = tr.map(QPointF(0, 1));
- ppm.rx() /= QLineF(p0, px).length();
- ppm.ry() /= QLineF(p0, py).length();
- }
- }
-#endif // QT_NO_GRAPHICSVIEW
- return ppm;
-}
-
-/*!
- Returns the current scrolling velocity in meter per second when the state is Scrolling or Dragging.
- Returns a zero velocity otherwise.
-
- The velocity is reported for both the x and y axis separately by using a QPointF.
-
- \sa pixelPerMeter()
-*/
-QPointF QScroller::velocity() const
-{
- Q_D(const QScroller);
- const QScrollerPropertiesPrivate *sp = d->properties.d.data();
-
- switch (state()) {
- case Dragging:
- return d->releaseVelocity;
- case Scrolling: {
- QPointF vel;
- qint64 now = d->monotonicTimer.elapsed();
-
- if (!d->xSegments.isEmpty()) {
- const QScrollerPrivate::ScrollSegment &s = d->xSegments.head();
- qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime);
- qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress);
- vel.setX(v);
- }
-
- if (!d->ySegments.isEmpty()) {
- const QScrollerPrivate::ScrollSegment &s = d->ySegments.head();
- qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime);
- qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress);
- vel.setY(v);
- }
- return vel;
- }
- default:
- return QPointF(0, 0);
- }
-}
-
-/*!
- Returns the estimated final position for the current scroll movement.
- Returns the current position if the scroller state is not Scrolling.
- The result is undefined when the scroller state is Inactive.
-
- The target position is in pixel.
-
- \sa pixelPerMeter(), scrollTo()
-*/
-QPointF QScroller::finalPosition() const
-{
- Q_D(const QScroller);
- return QPointF(d->scrollingSegmentsEndPos(Qt::Horizontal),
- d->scrollingSegmentsEndPos(Qt::Vertical));
-}
-
-/*!
- Starts scrolling the widget so that point \a pos is at the top-left position in
- the viewport.
-
- The behaviour when scrolling outside the valid scroll area is undefined.
- In this case the scroller might or might not overshoot.
-
- The scrolling speed will be calculated so that the given position will
- be reached after a platform-defined time span.
-
- \a pos is given in viewport coordinates.
-
- \sa ensureVisible()
-*/
-void QScroller::scrollTo(const QPointF &pos)
-{
- // we could make this adjustable via QScrollerProperties
- scrollTo(pos, 300);
-}
-
-/*! \overload
-
- This version will reach its destination position in \a scrollTime milliseconds.
-*/
-void QScroller::scrollTo(const QPointF &pos, int scrollTime)
-{
- Q_D(QScroller);
-
- if (d->state == Pressed || d->state == Dragging )
- return;
-
- // no need to resend a prepare event if we are already scrolling
- if (d->state == Inactive && !d->prepareScrolling(QPointF()))
- return;
-
- QPointF newpos = clampToRect(pos, d->contentPosRange);
- qreal snapX = d->nextSnapPos(newpos.x(), 0, Qt::Horizontal);
- qreal snapY = d->nextSnapPos(newpos.y(), 0, Qt::Vertical);
- if (!qIsNaN(snapX))
- newpos.setX(snapX);
- if (!qIsNaN(snapY))
- newpos.setY(snapY);
-
- qScrollerDebug() << "QScroller::scrollTo(req:" << pos << " [pix] / snap:" << newpos << ", " << scrollTime << " [ms])";
-
- if (newpos == d->contentPosition + d->overshootPosition)
- return;
-
- QPointF vel = velocity();
-
- if (scrollTime < 0)
- scrollTime = 0;
- qreal time = qreal(scrollTime) / 1000;
-
- d->createScrollToSegments(vel.x(), time, newpos.x(), Qt::Horizontal, QScrollerPrivate::ScrollTypeScrollTo);
- d->createScrollToSegments(vel.y(), time, newpos.y(), Qt::Vertical, QScrollerPrivate::ScrollTypeScrollTo);
-
- if (!scrollTime)
- d->setContentPositionHelperScrolling();
- d->setState(scrollTime ? Scrolling : Inactive);
-}
-
-/*!
- Starts scrolling so that the rectangle \a rect is visible inside the
- viewport with additional margins specified in pixels by \a xmargin and \a ymargin around
- the rect.
-
- In cases where it is not possible to fit the rect plus margins inside the viewport the contents
- are scrolled so that as much as possible is visible from \a rect.
-
- The scrolling speed is calculated so that the given position is reached after a platform-defined
- time span.
-
- This function performs the actual scrolling by calling scrollTo().
-
- \sa scrollTo
-*/
-void QScroller::ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin)
-{
- // we could make this adjustable via QScrollerProperties
- ensureVisible(rect, xmargin, ymargin, 1000);
-}
-
-/*! \overload
-
- This version will reach its destination position in \a scrollTime milliseconds.
-*/
-void QScroller::ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin, int scrollTime)
-{
- Q_D(QScroller);
-
- if (d->state == Pressed || d->state == Dragging )
- return;
-
- if (d->state == Inactive && !d->prepareScrolling(QPointF()))
- return;
-
- // -- calculate the current pos (or the position after the current scroll)
- QPointF startPos = d->contentPosition + d->overshootPosition;
- startPos = QPointF(d->scrollingSegmentsEndPos(Qt::Horizontal),
- d->scrollingSegmentsEndPos(Qt::Vertical));
-
- QRectF marginRect(rect.x() - xmargin, rect.y() - ymargin,
- rect.width() + 2 * xmargin, rect.height() + 2 * ymargin);
-
- QSizeF visible = d->viewportSize;
- QRectF visibleRect(startPos, visible);
-
- qScrollerDebug() << "QScroller::ensureVisible(" << rect << " [pix], " << xmargin << " [pix], " << ymargin << " [pix], " << scrollTime << "[ms])";
- qScrollerDebug() << " --> content position:" << d->contentPosition;
-
- if (visibleRect.contains(marginRect))
- return;
-
- QPointF newPos = startPos;
-
- if (visibleRect.width() < rect.width()) {
- // at least try to move the rect into view
- if (rect.left() > visibleRect.left())
- newPos.setX(rect.left());
- else if (rect.right() < visibleRect.right())
- newPos.setX(rect.right() - visible.width());
-
- } else if (visibleRect.width() < marginRect.width()) {
- newPos.setX(rect.center().x() - visibleRect.width() / 2);
- } else if (marginRect.left() > visibleRect.left()) {
- newPos.setX(marginRect.left());
- } else if (marginRect.right() < visibleRect.right()) {
- newPos.setX(marginRect.right() - visible.width());
- }
-
- if (visibleRect.height() < rect.height()) {
- // at least try to move the rect into view
- if (rect.top() > visibleRect.top())
- newPos.setX(rect.top());
- else if (rect.bottom() < visibleRect.bottom())
- newPos.setX(rect.bottom() - visible.height());
-
- } else if (visibleRect.height() < marginRect.height()) {
- newPos.setY(rect.center().y() - visibleRect.height() / 2);
- } else if (marginRect.top() > visibleRect.top()) {
- newPos.setY(marginRect.top());
- } else if (marginRect.bottom() < visibleRect.bottom()) {
- newPos.setY(marginRect.bottom() - visible.height());
- }
-
- // clamp to maximum content position
- newPos = clampToRect(newPos, d->contentPosRange);
- if (newPos == startPos)
- return;
-
- scrollTo(newPos, scrollTime);
-}
-
-/*! This function resends the QScrollPrepareEvent.
- Calling resendPrepareEvent triggers a QScrollPrepareEvent from the scroller.
- This allows the receiver to re-set content position and content size while
- scrolling.
- Calling this function while in the Inactive state is useless as the prepare event
- is sent again before scrolling starts.
- */
-void QScroller::resendPrepareEvent()
-{
- Q_D(QScroller);
- d->prepareScrolling(d->pressPosition);
-}
-
-/*! Set the snap positions for the horizontal axis to a list of \a positions.
- This overwrites all previously set snap positions and also a previously
- set snapping interval.
- Snapping can be deactivated by setting an empty list of positions.
- */
-void QScroller::setSnapPositionsX(const QList<qreal> &positions)
-{
- Q_D(QScroller);
- d->snapPositionsX = positions;
- d->snapIntervalX = 0.0;
-
- d->recalcScrollingSegments();
-}
-
-/*! Set the snap positions for the horizontal axis to regular spaced intervals.
- The first snap position is at \a first. The next at \a first + \a interval.
- This can be used to implement a list header.
- This overwrites all previously set snap positions and also a previously
- set snapping interval.
- Snapping can be deactivated by setting an interval of 0.0
- */
-void QScroller::setSnapPositionsX(qreal first, qreal interval)
-{
- Q_D(QScroller);
- d->snapFirstX = first;
- d->snapIntervalX = interval;
- d->snapPositionsX.clear();
-
- d->recalcScrollingSegments();
-}
-
-/*! Set the snap positions for the vertical axis to a list of \a positions.
- This overwrites all previously set snap positions and also a previously
- set snapping interval.
- Snapping can be deactivated by setting an empty list of positions.
- */
-void QScroller::setSnapPositionsY(const QList<qreal> &positions)
-{
- Q_D(QScroller);
- d->snapPositionsY = positions;
- d->snapIntervalY = 0.0;
-
- d->recalcScrollingSegments();
-}
-
-/*! Set the snap positions for the vertical axis to regular spaced intervals.
- The first snap position is at \a first. The next at \a first + \a interval.
- This overwrites all previously set snap positions and also a previously
- set snapping interval.
- Snapping can be deactivated by setting an interval of 0.0
- */
-void QScroller::setSnapPositionsY(qreal first, qreal interval)
-{
- Q_D(QScroller);
- d->snapFirstY = first;
- d->snapIntervalY = interval;
- d->snapPositionsY.clear();
-
- d->recalcScrollingSegments();
-}
-
-
-
-// -------------- private ------------
-
-QScrollerPrivate::QScrollerPrivate(QScroller *q, QObject *_target)
- : target(_target)
-#ifndef QT_NO_GESTURES
- , recognizer(0)
- , recognizerType(Qt::CustomGesture)
-#endif
- , state(QScroller::Inactive)
- , firstScroll(true)
- , pressTimestamp(0)
- , lastTimestamp(0)
- , snapFirstX(-1.0)
- , snapIntervalX(0.0)
- , snapFirstY(-1.0)
- , snapIntervalY(0.0)
-#ifndef QT_NO_ANIMATION
- , scrollTimer(new QScrollTimer(this))
-#endif
- , q_ptr(q)
-{
- connect(target, SIGNAL(destroyed(QObject*)), this, SLOT(targetDestroyed()));
-}
-
-void QScrollerPrivate::init()
-{
- setDpiFromWidget(0);
- monotonicTimer.start();
-}
-
-void QScrollerPrivate::sendEvent(QObject *o, QEvent *e)
-{
- qt_sendSpontaneousEvent(o, e);
-}
-
-const char *QScrollerPrivate::stateName(QScroller::State state)
-{
- switch (state) {
- case QScroller::Inactive: return "inactive";
- case QScroller::Pressed: return "pressed";
- case QScroller::Dragging: return "dragging";
- case QScroller::Scrolling: return "scrolling";
- default: return "(invalid)";
- }
-}
-
-const char *QScrollerPrivate::inputName(QScroller::Input input)
-{
- switch (input) {
- case QScroller::InputPress: return "press";
- case QScroller::InputMove: return "move";
- case QScroller::InputRelease: return "release";
- default: return "(invalid)";
- }
-}
-
-void QScrollerPrivate::targetDestroyed()
-{
-#ifndef QT_NO_ANIMATION
- scrollTimer->stop();
-#endif
- delete q_ptr;
-}
-
-void QScrollerPrivate::timerTick()
-{
- struct timerevent {
- QScroller::State state;
- typedef void (QScrollerPrivate::*timerhandler_t)();
- timerhandler_t handler;
- };
-
- timerevent timerevents[] = {
- { QScroller::Dragging, &QScrollerPrivate::timerEventWhileDragging },
- { QScroller::Scrolling, &QScrollerPrivate::timerEventWhileScrolling },
- };
-
- for (int i = 0; i < int(sizeof(timerevents) / sizeof(*timerevents)); ++i) {
- timerevent *te = timerevents + i;
-
- if (state == te->state) {
- (this->*te->handler)();
- return;
- }
- }
-
-#ifndef QT_NO_ANIMATION
- scrollTimer->stop();
-#endif
-}
-
-/*!
- This function is used by gesture recognizers to inform the scroller about a new input event.
- The scroller changes its internal state() according to the input event and its attached
- scroller properties. The scroller doesn't distinguish between the kind of input device the
- event came from. Therefore the event needs to be split into the \a input type, a \a position and a
- milli-second \a timestamp. The \a position needs to be in the target's coordinate system.
-
- The return value is \c true if the event should be consumed by the calling filter or \c false
- if the event should be forwarded to the control.
-
- \note Using grabGesture() should be sufficient for most use cases.
-*/
-bool QScroller::handleInput(Input input, const QPointF &position, qint64 timestamp)
-{
- Q_D(QScroller);
-
- qScrollerDebug() << "QScroller::handleInput(" << input << ", " << d->stateName(d->state) << ", " << position << ", " << timestamp << ")";
- struct statechange {
- State state;
- Input input;
- typedef bool (QScrollerPrivate::*inputhandler_t)(const QPointF &position, qint64 timestamp);
- inputhandler_t handler;
- };
-
- statechange statechanges[] = {
- { QScroller::Inactive, InputPress, &QScrollerPrivate::pressWhileInactive },
- { QScroller::Pressed, InputMove, &QScrollerPrivate::moveWhilePressed },
- { QScroller::Pressed, InputRelease, &QScrollerPrivate::releaseWhilePressed },
- { QScroller::Dragging, InputMove, &QScrollerPrivate::moveWhileDragging },
- { QScroller::Dragging, InputRelease, &QScrollerPrivate::releaseWhileDragging },
- { QScroller::Scrolling, InputPress, &QScrollerPrivate::pressWhileScrolling }
- };
-
- for (int i = 0; i < int(sizeof(statechanges) / sizeof(*statechanges)); ++i) {
- statechange *sc = statechanges + i;
-
- if (d->state == sc->state && input == sc->input)
- return (d->*sc->handler)(position - d->overshootPosition, timestamp);
- }
- return false;
-}
-
-#if !defined(Q_WS_MAC)
-// the Mac version is implemented in qscroller_mac.mm
-
-QPointF QScrollerPrivate::realDpi(int screen)
-{
-# ifdef Q_WS_MAEMO_5
- Q_UNUSED(screen);
-
- // The DPI value is hardcoded to 96 on Maemo5:
- // https://projects.maemo.org/bugzilla/show_bug.cgi?id=152525
- // This value (260) is only correct for the N900 though, but
- // there's no way to get the real DPI at run time.
- return QPointF(260, 260);
-
-# elif defined(Q_WS_X11) && !defined(QT_NO_XRANDR)
- if (X11 && X11->use_xrandr && X11->ptrXRRSizes && X11->ptrXRRRootToScreen) {
- int nsizes = 0;
- // QDesktopWidget is based on Xinerama screens, which do not always
- // correspond to RandR screens: NVidia's TwinView e.g. will show up
- // as 2 screens in QDesktopWidget, but libXRandR will only see 1 screen.
- // (although with the combined size of the Xinerama screens).
- // Additionally, libXrandr will simply crash when calling XRRSizes
- // for (the non-existent) screen 1 in this scenario.
- Window root = RootWindow(X11->display, screen == -1 ? X11->defaultScreen : screen);
- int randrscreen = (root != XNone) ? X11->ptrXRRRootToScreen(X11->display, root) : -1;
-
- XRRScreenSize *sizes = X11->ptrXRRSizes(X11->display, randrscreen == -1 ? 0 : randrscreen, &nsizes);
- if (nsizes > 0 && sizes && sizes->width && sizes->height && sizes->mwidth && sizes->mheight) {
- qScrollerDebug() << "XRandR DPI:" << QPointF(qreal(25.4) * qreal(sizes->width) / qreal(sizes->mwidth),
- qreal(25.4) * qreal(sizes->height) / qreal(sizes->mheight));
- return QPointF(qreal(25.4) * qreal(sizes->width) / qreal(sizes->mwidth),
- qreal(25.4) * qreal(sizes->height) / qreal(sizes->mheight));
- }
- }
-# endif
-
- QWidget *w = QApplication::desktop()->screen(screen);
- return QPointF(w->physicalDpiX(), w->physicalDpiY());
-}
-
-#endif // !Q_WS_MAC
-
-
-/*! \internal
- Returns the resolution of the used screen.
-*/
-QPointF QScrollerPrivate::dpi() const
-{
- return pixelPerMeter * qreal(0.0254);
-}
-
-/*! \internal
- Sets the resolution used for scrolling.
- This resolution is only used by the kinetic scroller. If you change this
- then the scroller will behave quite different as a lot of the values are
- given in physical distances (millimeter).
-*/
-void QScrollerPrivate::setDpi(const QPointF &dpi)
-{
- pixelPerMeter = dpi / qreal(0.0254);
-}
-
-/*! \internal
- Sets the dpi used for scrolling to the value of the widget.
-*/
-void QScrollerPrivate::setDpiFromWidget(QWidget *widget)
-{
- QDesktopWidget *dw = QApplication::desktop();
- setDpi(realDpi(widget ? dw->screenNumber(widget) : dw->primaryScreen()));
-}
-
-/*! \internal
- Updates the velocity during dragging.
- Sets releaseVelocity.
-*/
-void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 deltaTime)
-{
- if (deltaTime <= 0)
- return;
-
- Q_Q(QScroller);
- QPointF ppm = q->pixelPerMeter();
- const QScrollerPropertiesPrivate *sp = properties.d.data();
- QPointF deltaPixel = deltaPixelRaw;
-
- qScrollerDebug() << "QScroller::updateVelocity(" << deltaPixelRaw << " [delta pix], " << deltaTime << " [delta ms])";
-
- // faster than 2.5mm/ms seems bogus (that would be a screen height in ~20 ms)
- if (((deltaPixelRaw / qreal(deltaTime)).manhattanLength() / ((ppm.x() + ppm.y()) / 2) * 1000) > qreal(2.5))
- deltaPixel = deltaPixelRaw * qreal(2.5) * ppm / 1000 / (deltaPixelRaw / qreal(deltaTime)).manhattanLength();
-
- QPointF newv = -deltaPixel / qreal(deltaTime) * qreal(1000) / ppm;
- // around 95% of all updates are in the [1..50] ms range, so make sure
- // to scale the smoothing factor over that range: this way a 50ms update
- // will have full impact, while 5ms update will only have a 10% impact.
- qreal smoothing = sp->dragVelocitySmoothingFactor * qMin(qreal(deltaTime), qreal(50)) / qreal(50);
-
- // only smooth if we already have a release velocity and only if the
- // user hasn't stopped to move his finger for more than 100ms
- if ((releaseVelocity != QPointF(0, 0)) && (deltaTime < 100)) {
- qScrollerDebug() << "SMOOTHED from " << newv << " to " << newv * smoothing + releaseVelocity * (qreal(1) - smoothing);
- // smooth x or y only if the new velocity is either 0 or at least in
- // the same direction of the release velocity
- if (!newv.x() || (qSign(releaseVelocity.x()) == qSign(newv.x())))
- newv.setX(newv.x() * smoothing + releaseVelocity.x() * (qreal(1) - smoothing));
- if (!newv.y() || (qSign(releaseVelocity.y()) == qSign(newv.y())))
- newv.setY(newv.y() * smoothing + releaseVelocity.y() * (qreal(1) - smoothing));
- } else
- qScrollerDebug() << "NO SMOOTHING to " << newv;
-
- releaseVelocity.setX(qBound(-sp->maximumVelocity, newv.x(), sp->maximumVelocity));
- releaseVelocity.setY(qBound(-sp->maximumVelocity, newv.y(), sp->maximumVelocity));
-
- qScrollerDebug() << " --> new velocity:" << releaseVelocity;
-}
-
-void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, qreal startPos, qreal deltaPos, qreal stopPos, QEasingCurve::Type curve, Qt::Orientation orientation)
-{
- if (startPos == stopPos || deltaPos == 0)
- return;
-
- ScrollSegment s;
- if (orientation == Qt::Horizontal && !xSegments.isEmpty())
- s.startTime = xSegments.last().startTime + xSegments.last().deltaTime * xSegments.last().stopProgress;
- else if (orientation == Qt::Vertical && !ySegments.isEmpty())
- s.startTime = ySegments.last().startTime + ySegments.last().deltaTime * ySegments.last().stopProgress;
- else
- s.startTime = monotonicTimer.elapsed();
-
- s.startPos = startPos;
- s.deltaPos = deltaPos;
- s.stopPos = stopPos;
- s.deltaTime = deltaTime * 1000;
- s.stopProgress = stopProgress;
- s.curve.setType(curve);
- s.type = type;
-
- if (orientation == Qt::Horizontal)
- xSegments.enqueue(s);
- else
- ySegments.enqueue(s);
-
- qScrollerDebug() << "+++ Added a new ScrollSegment: " << s;
-}
-
-
-/*! \internal
- Clears the old segments and recalculates them if the current segments are not longer valid
-*/
-void QScrollerPrivate::recalcScrollingSegments(bool forceRecalc)
-{
- Q_Q(QScroller);
- QPointF ppm = q->pixelPerMeter();
-
- releaseVelocity = q->velocity();
-
- if (forceRecalc || !scrollingSegmentsValid(Qt::Horizontal))
- createScrollingSegments(releaseVelocity.x(), contentPosition.x() + overshootPosition.x(), ppm.x(), Qt::Horizontal);
-
- if (forceRecalc || !scrollingSegmentsValid(Qt::Vertical))
- createScrollingSegments(releaseVelocity.y(), contentPosition.y() + overshootPosition.y(), ppm.y(), Qt::Vertical);
-}
-
-/*! \internal
- Returns the end position after the current scroll has finished.
-*/
-qreal QScrollerPrivate::scrollingSegmentsEndPos(Qt::Orientation orientation) const
-{
- if (orientation == Qt::Horizontal) {
- if (xSegments.isEmpty())
- return contentPosition.x() + overshootPosition.x();
- else
- return xSegments.last().stopPos;
- } else {
- if (ySegments.isEmpty())
- return contentPosition.y() + overshootPosition.y();
- else
- return ySegments.last().stopPos;
- }
-}
-
-/*! \internal
- Checks if the scroller segment end in a valid position.
-*/
-bool QScrollerPrivate::scrollingSegmentsValid(Qt::Orientation orientation)
-{
- QQueue<ScrollSegment> *segments;
- qreal minPos;
- qreal maxPos;
-
- if (orientation == Qt::Horizontal) {
- segments = &xSegments;
- minPos = contentPosRange.left();
- maxPos = contentPosRange.right();
- } else {
- segments = &ySegments;
- minPos = contentPosRange.top();
- maxPos = contentPosRange.bottom();
- }
-
- if (segments->isEmpty())
- return true;
-
- const ScrollSegment &last = segments->last();
- qreal stopPos = last.stopPos;
-
- if (last.type == ScrollTypeScrollTo)
- return true; // scrollTo is always valid
-
- if (last.type == ScrollTypeOvershoot &&
- (stopPos != minPos && stopPos != maxPos))
- return false;
-
- if (stopPos < minPos || stopPos > maxPos)
- return false;
-
- if (stopPos == minPos || stopPos == maxPos) // the begin and the end of the list are always ok
- return true;
-
- qreal nextSnap = nextSnapPos(stopPos, 0, orientation);
- if (!qIsNaN(nextSnap) && stopPos != nextSnap)
- return false;
-
- return true;
-}
-
-/*! \internal
- Creates the sections needed to scroll to the specific \a endPos to the segments queue.
-*/
-void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, Qt::Orientation orientation, ScrollType type)
-{
- Q_UNUSED(v);
-
- if (orientation == Qt::Horizontal)
- xSegments.clear();
- else
- ySegments.clear();
-
- qScrollerDebug() << "+++ createScrollToSegments: t:" << deltaTime << "ep:" << endPos << "o:" << int(orientation);
-
- const QScrollerPropertiesPrivate *sp = properties.d.data();
-
- qreal startPos = (orientation == Qt::Horizontal) ? contentPosition.x() + overshootPosition.x()
- : contentPosition.y() + overshootPosition.y();
- qreal deltaPos = (endPos - startPos) / 2;
-
- pushSegment(type, deltaTime * qreal(0.3), qreal(1.0), startPos, deltaPos, startPos + deltaPos, QEasingCurve::InQuad, orientation);
- pushSegment(type, deltaTime * qreal(0.7), qreal(1.0), startPos + deltaPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation);
-}
-
-/*! \internal
-*/
-void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, qreal ppm, Qt::Orientation orientation)
-{
- const QScrollerPropertiesPrivate *sp = properties.d.data();
-
- QScrollerProperties::OvershootPolicy policy;
- qreal minPos;
- qreal maxPos;
- qreal viewSize;
-
- if (orientation == Qt::Horizontal) {
- xSegments.clear();
- policy = sp->hOvershootPolicy;
- minPos = contentPosRange.left();
- maxPos = contentPosRange.right();
- viewSize = viewportSize.width();
- } else {
- ySegments.clear();
- policy = sp->vOvershootPolicy;
- minPos = contentPosRange.top();
- maxPos = contentPosRange.bottom();
- viewSize = viewportSize.height();
- }
-
- bool alwaysOvershoot = (policy == QScrollerProperties::OvershootAlwaysOn);
- bool noOvershoot = (policy == QScrollerProperties::OvershootAlwaysOff) || !sp->overshootScrollDistanceFactor;
- bool canOvershoot = !noOvershoot && (alwaysOvershoot || maxPos);
-
- qScrollerDebug() << "+++ createScrollingSegments: s:" << startPos << "maxPos:" << maxPos << "o:" << int(orientation);
-
- qScrollerDebug() << "v = " << v << ", decelerationFactor = " << sp->decelerationFactor << ", curveType = " << sp->scrollingCurve.type();
-
- // This is only correct for QEasingCurve::OutQuad (linear velocity,
- // constant deceleration), but the results look and feel ok for OutExpo
- // and OutSine as well
-
- // v(t) = deltaTime * a * 0.5 * differentialForProgress(t / deltaTime)
- // v(0) = vrelease
- // v(deltaTime) = 0
- // deltaTime = (2 * vrelease) / (a * differntial(0))
-
- // pos(t) = integrate(v(t)dt)
- // pos(t) = vrelease * t - 0.5 * a * t * t
- // pos(t) = deltaTime * a * 0.5 * progress(t / deltaTime) * deltaTime
- // deltaPos = pos(deltaTime)
-
- qreal deltaTime = (qreal(2) * qAbs(v)) / (sp->decelerationFactor * differentialForProgress(sp->scrollingCurve, 0));
- qreal deltaPos = qSign(v) * deltaTime * deltaTime * qreal(0.5) * sp->decelerationFactor * ppm;
- qreal endPos = startPos + deltaPos;
-
- qScrollerDebug() << " Real Delta:" << deltaPos;
-
- // -- determine snap points
- qreal nextSnap = nextSnapPos(endPos, 0, orientation);
- qreal lowerSnapPos = nextSnapPos(startPos, -1, orientation);
- qreal higherSnapPos = nextSnapPos(startPos, 1, orientation);
-
- qScrollerDebug() << " Real Delta:" << lowerSnapPos <<"-"<<nextSnap <<"-"<<higherSnapPos;
-
- // - check if we can reach another snap point
- if (nextSnap > higherSnapPos || qIsNaN(higherSnapPos))
- higherSnapPos = nextSnap;
- if (nextSnap < lowerSnapPos || qIsNaN(lowerSnapPos))
- lowerSnapPos = nextSnap;
-
- // -- check if are in overshoot and end in overshoot
- if ((startPos < minPos && endPos < minPos) ||
- (startPos > maxPos && endPos > maxPos)) {
- qreal stopPos = endPos < minPos ? minPos : maxPos;
- qreal oDeltaTime = sp->overshootScrollTime;
-
- pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), startPos, stopPos - startPos, stopPos, sp->scrollingCurve.type(), orientation);
- return;
- }
-
- if (qAbs(v) < sp->minimumVelocity) {
-
- qScrollerDebug() << "### below minimum Vel" << orientation;
-
- // - no snap points or already at one
- if (qIsNaN(nextSnap) || nextSnap == startPos)
- return; // nothing to do, no scrolling needed.
-
- // - decide which point to use
-
- qreal snapDistance = higherSnapPos - lowerSnapPos;
-
- qreal pressDistance = (orientation == Qt::Horizontal) ?
- lastPosition.x() - pressPosition.x() :
- lastPosition.y() - pressPosition.y();
-
- // if not dragged far enough, pick the next snap point.
- if (sp->snapPositionRatio == 0.0 || qAbs(pressDistance / sp->snapPositionRatio) > snapDistance)
- endPos = nextSnap;
- else if (pressDistance < 0.0)
- endPos = lowerSnapPos;
- else
- endPos = higherSnapPos;
-
- deltaPos = endPos - startPos;
- qreal midPos = startPos + deltaPos * qreal(0.3);
- pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.3), qreal(1.0), startPos, midPos - startPos, midPos, QEasingCurve::InQuad, orientation);
- pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.7), qreal(1.0), midPos, endPos - midPos, endPos, sp->scrollingCurve.type(), orientation);
- return;
- }
-
- // - go to the next snappoint if there is one
- if (v > 0 && !qIsNaN(higherSnapPos)) {
- // change the time in relation to the changed end position
- if (endPos - startPos)
- deltaTime *= qAbs((higherSnapPos - startPos) / (endPos - startPos));
- if (deltaTime > sp->snapTime)
- deltaTime = sp->snapTime;
- endPos = higherSnapPos;
-
- } else if (v < 0 && !qIsNaN(lowerSnapPos)) {
- // change the time in relation to the changed end position
- if (endPos - startPos)
- deltaTime *= qAbs((lowerSnapPos - startPos) / (endPos - startPos));
- if (deltaTime > sp->snapTime)
- deltaTime = sp->snapTime;
- endPos = lowerSnapPos;
-
- // -- check if we are overshooting
- } else if (endPos < minPos || endPos > maxPos) {
- qreal stopPos = endPos < minPos ? minPos : maxPos;
-
- qScrollerDebug() << "Overshoot: delta:" << (stopPos - startPos);
-
- qreal stopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos - startPos) / deltaPos));
-
- if (!canOvershoot) {
- qScrollerDebug() << "Overshoot stopp:" << stopProgress;
-
- pushSegment(ScrollTypeFlick, deltaTime, stopProgress, startPos, endPos, stopPos, sp->scrollingCurve.type(), orientation);
- } else {
- qreal oDeltaTime = sp->overshootScrollTime;
- qreal oStopProgress = qMin(stopProgress + oDeltaTime * qreal(0.3) / deltaTime, qreal(1));
- qreal oDistance = startPos + deltaPos * sp->scrollingCurve.valueForProgress(oStopProgress) - stopPos;
- qreal oMaxDistance = qSign(oDistance) * (viewSize * sp->overshootScrollDistanceFactor);
-
- qScrollerDebug() << "1 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress;
-
- if (qAbs(oDistance) > qAbs(oMaxDistance)) {
- oStopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos + oMaxDistance - startPos) / deltaPos));
- oDistance = oMaxDistance;
- qScrollerDebug() << "2 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress;
- }
-
- pushSegment(ScrollTypeFlick, deltaTime, oStopProgress, startPos, deltaPos, stopPos + oDistance, sp->scrollingCurve.type(), orientation);
- pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), stopPos + oDistance, -oDistance, stopPos, sp->scrollingCurve.type(), orientation);
- }
- return;
- }
-
- pushSegment(ScrollTypeFlick, deltaTime, qreal(1.0), startPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation);
-}
-
-
-/*! \internal
- Prepares scrolling by sending a QScrollPrepareEvent to the receiver widget.
- Returns true if the scrolling was accepted and a target was returned.
-*/
-bool QScrollerPrivate::prepareScrolling(const QPointF &position)
-{
- QScrollPrepareEvent spe(position);
- spe.ignore();
- sendEvent(target, &spe);
-
- qScrollerDebug() << "QScrollPrepareEvent returned from" << target << "with" << spe.isAccepted() << "mcp:" << spe.contentPosRange() << "cp:" << spe.contentPos();
- if (spe.isAccepted()) {
- QPointF oldContentPos = contentPosition + overshootPosition;
- QPointF contentDelta = spe.contentPos() - oldContentPos;
-
- viewportSize = spe.viewportSize();
- contentPosRange = spe.contentPosRange();
- if (contentPosRange.width() < 0)
- contentPosRange.setWidth(0);
- if (contentPosRange.height() < 0)
- contentPosRange.setHeight(0);
- contentPosition = clampToRect(spe.contentPos(), contentPosRange);
- overshootPosition = spe.contentPos() - contentPosition;
-
- // - check if the content position was moved
- if (contentDelta != QPointF(0, 0)) {
- // need to correct all segments
- for (int i = 0; i < xSegments.count(); i++)
- xSegments[i].startPos -= contentDelta.x();
-
- for (int i = 0; i < ySegments.count(); i++)
- ySegments[i].startPos -= contentDelta.y();
- }
-
- if (QWidget *w = qobject_cast<QWidget *>(target))
- setDpiFromWidget(w);
-#ifndef QT_NO_GRAPHICSVIEW
- if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(target)) {
- //TODO: the first view isn't really correct - maybe use an additional field in the prepare event?
- if (go->scene() && !go->scene()->views().isEmpty())
- setDpiFromWidget(go->scene()->views().first());
- }
-#endif
-
- if (state == QScroller::Scrolling) {
- recalcScrollingSegments();
- }
- return true;
- }
-
- return false;
-}
-
-void QScrollerPrivate::handleDrag(const QPointF &position, qint64 timestamp)
-{
- const QScrollerPropertiesPrivate *sp = properties.d.data();
-
- QPointF deltaPixel = position - lastPosition;
- qint64 deltaTime = timestamp - lastTimestamp;
-
- if (sp->axisLockThreshold) {
- int dx = qAbs(deltaPixel.x());
- int dy = qAbs(deltaPixel.y());
- if (dx || dy) {
- bool vertical = (dy > dx);
- qreal alpha = qreal(vertical ? dx : dy) / qreal(vertical ? dy : dx);
- //qScrollerDebug() << "QScroller::handleDrag() -- axis lock:" << alpha << " / " << axisLockThreshold << "- isvertical:" << vertical << "- dx:" << dx << "- dy:" << dy;
- if (alpha <= sp->axisLockThreshold) {
- if (vertical)
- deltaPixel.setX(0);
- else
- deltaPixel.setY(0);
- }
- }
- }
-
- // calculate velocity (if the user would release the mouse NOW)
- updateVelocity(deltaPixel, deltaTime);
-
- // restrict velocity, if content is not scrollable
- QRectF max = contentPosRange;
- bool canScrollX = (max.width() > 0) || (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn);
- bool canScrollY = (max.height() > 0) || (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn);
-
- if (!canScrollX) {
- deltaPixel.setX(0);
- releaseVelocity.setX(0);
- }
- if (!canScrollY) {
- deltaPixel.setY(0);
- releaseVelocity.setY(0);
- }
-
-// if (firstDrag) {
-// // Do not delay the first drag
-// setContentPositionHelper(q->contentPosition() - overshootDistance - deltaPixel);
-// dragDistance = QPointF(0, 0);
-// } else {
- dragDistance += deltaPixel;
-// }
-//qScrollerDebug() << "######################" << deltaPixel << position.y() << lastPosition.y();
- if (canScrollX)
- lastPosition.setX(position.x());
- if (canScrollY)
- lastPosition.setY(position.y());
- lastTimestamp = timestamp;
-}
-
-bool QScrollerPrivate::pressWhileInactive(const QPointF &position, qint64 timestamp)
-{
- if (prepareScrolling(position)) {
- const QScrollerPropertiesPrivate *sp = properties.d.data();
-
- if (!contentPosRange.isNull() ||
- (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn) ||
- (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn)) {
-
- lastPosition = pressPosition = position;
- lastTimestamp = pressTimestamp = timestamp;
- setState(QScroller::Pressed);
- }
- }
- return false;
-}
-
-bool QScrollerPrivate::releaseWhilePressed(const QPointF &, qint64)
-{
- if (overshootPosition != QPointF(0.0, 0.0)) {
- setState(QScroller::Scrolling);
- return true;
- } else {
- setState(QScroller::Inactive);
- return false;
- }
-}
-
-bool QScrollerPrivate::moveWhilePressed(const QPointF &position, qint64 timestamp)
-{
- Q_Q(QScroller);
- const QScrollerPropertiesPrivate *sp = properties.d.data();
- QPointF ppm = q->pixelPerMeter();
-
- QPointF deltaPixel = position - pressPosition;
-
- bool moveAborted = false;
- bool moveStarted = (((deltaPixel / ppm).manhattanLength()) > sp->dragStartDistance);
-
- // check the direction of the mouse drag and abort if it's too much in the wrong direction.
- if (moveStarted) {
- QRectF max = contentPosRange;
- bool canScrollX = (max.width() > 0);
- bool canScrollY = (max.height() > 0);
-
- if (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn)
- canScrollX = true;
- if (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn)
- canScrollY = true;
-
- if (qAbs(deltaPixel.x() / ppm.x()) < qAbs(deltaPixel.y() / ppm.y())) {
- if (!canScrollY)
- moveAborted = true;
- } else {
- if (!canScrollX)
- moveAborted = true;
- }
- }
-
- if (moveAborted) {
- setState(QScroller::Inactive);
- moveStarted = false;
-
- } else if (moveStarted) {
- setState(QScroller::Dragging);
-
- // subtract the dragStartDistance
- deltaPixel = deltaPixel - deltaPixel * (sp->dragStartDistance / deltaPixel.manhattanLength());
-
- if (deltaPixel != QPointF(0, 0)) {
- // handleDrag updates lastPosition, lastTimestamp and velocity
- handleDrag(pressPosition + deltaPixel, timestamp);
- }
- }
- return moveStarted;
-}
-
-bool QScrollerPrivate::moveWhileDragging(const QPointF &position, qint64 timestamp)
-{
- // handleDrag updates lastPosition, lastTimestamp and velocity
- handleDrag(position, timestamp);
- return true;
-}
-
-void QScrollerPrivate::timerEventWhileDragging()
-{
- if (dragDistance != QPointF(0, 0)) {
- qScrollerDebug() << "QScroller::timerEventWhileDragging() -- dragDistance:" << dragDistance;
-
- setContentPositionHelperDragging(-dragDistance);
- dragDistance = QPointF(0, 0);
- }
-}
-
-bool QScrollerPrivate::releaseWhileDragging(const QPointF &position, qint64 timestamp)
-{
- Q_Q(QScroller);
- const QScrollerPropertiesPrivate *sp = properties.d.data();
-
- // handleDrag updates lastPosition, lastTimestamp and velocity
- handleDrag(position, timestamp);
-
- // check if we moved at all - this can happen if you stop a running
- // scroller with a press and release shortly afterwards
- QPointF deltaPixel = position - pressPosition;
- if (((deltaPixel / q->pixelPerMeter()).manhattanLength()) > sp->dragStartDistance) {
-
- // handle accelerating flicks
- if ((oldVelocity != QPointF(0, 0)) && sp->acceleratingFlickMaximumTime &&
- ((timestamp - pressTimestamp) < qint64(sp->acceleratingFlickMaximumTime * 1000))) {
-
- // - determine if the direction was changed
- int signX = 0, signY = 0;
- if (releaseVelocity.x())
- signX = (releaseVelocity.x() > 0) == (oldVelocity.x() > 0) ? 1 : -1;
- if (releaseVelocity.y())
- signY = (releaseVelocity.y() > 0) == (oldVelocity.y() > 0) ? 1 : -1;
-
- if (signX > 0)
- releaseVelocity.setX(qBound(-sp->maximumVelocity,
- oldVelocity.x() * sp->acceleratingFlickSpeedupFactor,
- sp->maximumVelocity));
- if (signY > 0)
- releaseVelocity.setY(qBound(-sp->maximumVelocity,
- oldVelocity.y() * sp->acceleratingFlickSpeedupFactor,
- sp->maximumVelocity));
- }
- }
-
- QPointF ppm = q->pixelPerMeter();
- createScrollingSegments(releaseVelocity.x(), contentPosition.x() + overshootPosition.x(), ppm.x(), Qt::Horizontal);
- createScrollingSegments(releaseVelocity.y(), contentPosition.y() + overshootPosition.y(), ppm.y(), Qt::Vertical);
-
- qScrollerDebug() << "QScroller::releaseWhileDragging() -- velocity:" << releaseVelocity << "-- minimum velocity:" << sp->minimumVelocity << "overshoot" << overshootPosition;
-
- if (xSegments.isEmpty() && ySegments.isEmpty())
- setState(QScroller::Inactive);
- else
- setState(QScroller::Scrolling);
-
- return true;
-}
-
-void QScrollerPrivate::timerEventWhileScrolling()
-{
- qScrollerDebug() << "QScroller::timerEventWhileScrolling()";
-
- setContentPositionHelperScrolling();
- if (xSegments.isEmpty() && ySegments.isEmpty())
- setState(QScroller::Inactive);
-}
-
-bool QScrollerPrivate::pressWhileScrolling(const QPointF &position, qint64 timestamp)
-{
- Q_Q(QScroller);
-
- if ((q->velocity() <= properties.d->maximumClickThroughVelocity) &&
- (overshootPosition == QPointF(0.0, 0.0))) {
- setState(QScroller::Inactive);
- return false;
- } else {
- lastPosition = pressPosition = position;
- lastTimestamp = pressTimestamp = timestamp;
- setState(QScroller::Pressed);
- setState(QScroller::Dragging);
- return true;
- }
-}
-
-/*! \internal
- This function handles all state changes of the scroller.
-*/
-void QScrollerPrivate::setState(QScroller::State newstate)
-{
- Q_Q(QScroller);
- bool sendLastScroll = false;
-
- if (state == newstate)
- return;
-
- qScrollerDebug() << q << "QScroller::setState(" << stateName(newstate) << ")";
-
- switch (newstate) {
- case QScroller::Inactive:
-#ifndef QT_NO_ANIMATION
- scrollTimer->stop();
-#endif
-
- // send the last scroll event (but only after the current state change was finished)
- if (!firstScroll)
- sendLastScroll = true;
-
- releaseVelocity = QPointF(0, 0);
- break;
-
- case QScroller::Pressed:
-#ifndef QT_NO_ANIMATION
- scrollTimer->stop();
-#endif
-
- oldVelocity = releaseVelocity;
- releaseVelocity = QPointF(0, 0);
- break;
-
- case QScroller::Dragging:
- dragDistance = QPointF(0, 0);
-#ifndef QT_NO_ANIMATION
- if (state == QScroller::Pressed)
- scrollTimer->start();
-#endif
- break;
-
- case QScroller::Scrolling:
-#ifndef QT_NO_ANIMATION
- scrollTimer->start();
-#endif
- break;
- }
-
- qSwap(state, newstate);
-
- if (sendLastScroll) {
- QScrollEvent se(contentPosition, overshootPosition, QScrollEvent::ScrollFinished);
- sendEvent(target, &se);
- firstScroll = true;
- }
- if (state == QScroller::Dragging || state == QScroller::Scrolling)
- qt_activeScrollers()->insert(q);
- else
- qt_activeScrollers()->remove(q);
- emit q->stateChanged(state);
-}
-
-
-/*! \internal
- Helps when setting the content position.
- It will try to move the content by the requested delta but stop in case
- when we are coming back from an overshoot or a scrollTo.
- It will also indicate a new overshooting condition by the overshootX and oversthootY flags.
-
- In this cases it will reset the velocity variables and other flags.
-
- Also keeps track of the current over-shooting value in overshootPosition.
-
- \a deltaPos is the amount of pixels the current content position should be moved
-*/
-void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos)
-{
- Q_Q(QScroller);
- QPointF ppm = q->pixelPerMeter();
- const QScrollerPropertiesPrivate *sp = properties.d.data();
- QPointF v = q->velocity();
-
- if (sp->overshootDragResistanceFactor)
- overshootPosition /= sp->overshootDragResistanceFactor;
-
- QPointF oldPos = contentPosition + overshootPosition;
- QPointF newPos = oldPos + deltaPos;
-
- qScrollerDebug() << "QScroller::setContentPositionHelperDragging(" << deltaPos << " [pix])";
- qScrollerDebug() << " --> overshoot:" << overshootPosition << "- old pos:" << oldPos << "- new pos:" << newPos;
-
- QPointF oldClampedPos = clampToRect(oldPos, contentPosRange);
- QPointF newClampedPos = clampToRect(newPos, contentPosRange);
-
- // --- handle overshooting and stop if the coordinate is going back inside the normal area
- bool alwaysOvershootX = (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn);
- bool alwaysOvershootY = (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn);
- bool noOvershootX = (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOff) ||
- ((state == QScroller::Dragging) && !sp->overshootDragResistanceFactor) ||
- !sp->overshootDragDistanceFactor;
- bool noOvershootY = (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOff) ||
- ((state == QScroller::Dragging) && !sp->overshootDragResistanceFactor) ||
- !sp->overshootDragDistanceFactor;
- bool canOvershootX = !noOvershootX && (alwaysOvershootX || contentPosRange.width());
- bool canOvershootY = !noOvershootY && (alwaysOvershootY || contentPosRange.height());
-
- qreal oldOvershootX = (canOvershootX) ? oldPos.x() - oldClampedPos.x() : 0;
- qreal oldOvershootY = (canOvershootY) ? oldPos.y() - oldClampedPos.y() : 0;
-
- qreal newOvershootX = (canOvershootX) ? newPos.x() - newClampedPos.x() : 0;
- qreal newOvershootY = (canOvershootY) ? newPos.y() - newClampedPos.y() : 0;
-
- qreal maxOvershootX = viewportSize.width() * sp->overshootDragDistanceFactor;
- qreal maxOvershootY = viewportSize.height() * sp->overshootDragDistanceFactor;
-
- qScrollerDebug() << " --> noOs:" << noOvershootX << "drf:" << sp->overshootDragResistanceFactor << "mdf:" << sp->overshootScrollDistanceFactor << "ossP:"<<sp->hOvershootPolicy;
- qScrollerDebug() << " --> canOS:" << canOvershootX << "newOS:" << newOvershootX << "maxOS:" << maxOvershootX;
-
- if (sp->overshootDragResistanceFactor) {
- oldOvershootX *= sp->overshootDragResistanceFactor;
- oldOvershootY *= sp->overshootDragResistanceFactor;
- newOvershootX *= sp->overshootDragResistanceFactor;
- newOvershootY *= sp->overshootDragResistanceFactor;
- }
-
- // -- stop at the maximum overshoot distance
-
- newOvershootX = qBound(-maxOvershootX, newOvershootX, maxOvershootX);
- newOvershootY = qBound(-maxOvershootY, newOvershootY, maxOvershootY);
-
- overshootPosition.setX(newOvershootX);
- overshootPosition.setY(newOvershootY);
- contentPosition = newClampedPos;
-
- QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted : QScrollEvent::ScrollUpdated);
- sendEvent(target, &se);
- firstScroll = false;
-
- qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition <<
- "- overshoot x/y?:" << overshootPosition;
-}
-
-
-qreal QScrollerPrivate::nextSegmentPosition(QQueue<ScrollSegment> &segments, qint64 now, qreal oldPos)
-{
- qreal pos = oldPos;
-
- // check the X segments for new positions
- while (!segments.isEmpty()) {
- const ScrollSegment s = segments.head();
-
- if ((s.startTime + s.deltaTime * s.stopProgress) <= now) {
- segments.dequeue();
- pos = s.stopPos;
- } else if (s.startTime <= now) {
- qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime);
- pos = s.startPos + s.deltaPos * s.curve.valueForProgress(progress);
- if (s.deltaPos > 0 ? pos > s.stopPos : pos < s.stopPos) {
- segments.dequeue();
- pos = s.stopPos;
- } else {
- break;
- }
- } else {
- break;
- }
- }
- return pos;
-}
-
-void QScrollerPrivate::setContentPositionHelperScrolling()
-{
- qint64 now = monotonicTimer.elapsed();
- QPointF newPos = contentPosition + overshootPosition;
-
- newPos.setX(nextSegmentPosition(xSegments, now, newPos.x()));
- newPos.setY(nextSegmentPosition(ySegments, now, newPos.y()));
-
- // -- set the position and handle overshoot
- qScrollerDebug() << "QScroller::setContentPositionHelperScrolling()";
- qScrollerDebug() << " --> overshoot:" << overshootPosition << "- new pos:" << newPos;
-
- QPointF newClampedPos = clampToRect(newPos, contentPosRange);
-
- overshootPosition = newPos - newClampedPos;
- contentPosition = newClampedPos;
-
- QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted : QScrollEvent::ScrollUpdated);
- sendEvent(target, &se);
- firstScroll = false;
-
- qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition;
-}
-
-/*! \internal
- Returns the next snap point in direction.
- If \a direction >0 it will return the next snap point that is larger than the current position.
- If \a direction <0 it will return the next snap point that is smaller than the current position.
- If \a direction ==0 it will return the nearest snap point (or the current position if we are already
- on a snap point.
- Returns the nearest snap position or NaN if no such point could be found.
- */
-qreal QScrollerPrivate::nextSnapPos(qreal p, int dir, Qt::Orientation orientation)
-{
- qreal bestSnapPos = Q_QNAN;
- qreal bestSnapPosDist = Q_INFINITY;
-
- qreal minPos;
- qreal maxPos;
-
- if (orientation == Qt::Horizontal) {
- minPos = contentPosRange.left();
- maxPos = contentPosRange.right();
- } else {
- minPos = contentPosRange.top();
- maxPos = contentPosRange.bottom();
- }
-
- if (orientation == Qt::Horizontal) {
- // the snap points in the list
- foreach (qreal snapPos, snapPositionsX) {
- qreal snapPosDist = snapPos - p;
- if ((dir > 0 && snapPosDist < 0) ||
- (dir < 0 && snapPosDist > 0))
- continue; // wrong direction
- if (snapPos < minPos || snapPos > maxPos )
- continue; // invalid
-
- if (qIsNaN(bestSnapPos) ||
- qAbs(snapPosDist) < bestSnapPosDist ) {
- bestSnapPos = snapPos;
- bestSnapPosDist = qAbs(snapPosDist);
- }
- }
-
- // the snap point interval
- if (snapIntervalX > 0.0) {
- qreal first = minPos + snapFirstX;
- qreal snapPos;
- if (dir > 0)
- snapPos = qCeil((p - first) / snapIntervalX) * snapIntervalX + first;
- else if (dir < 0)
- snapPos = qFloor((p - first) / snapIntervalX) * snapIntervalX + first;
- else if (p <= first)
- snapPos = first;
- else
- {
- qreal last = qFloor((maxPos - first) / snapIntervalX) * snapIntervalX + first;
- if (p >= last)
- snapPos = last;
- else
- snapPos = qRound((p - first) / snapIntervalX) * snapIntervalX + first;
- }
-
- if (snapPos >= first && snapPos <= maxPos ) {
- qreal snapPosDist = snapPos - p;
-
- if (qIsNaN(bestSnapPos) ||
- qAbs(snapPosDist) < bestSnapPosDist ) {
- bestSnapPos = snapPos;
- bestSnapPosDist = qAbs(snapPosDist);
- }
- }
- }
-
- } else { // (orientation == Qt::Vertical)
- // the snap points in the list
- foreach (qreal snapPos, snapPositionsY) {
- qreal snapPosDist = snapPos - p;
- if ((dir > 0 && snapPosDist < 0) ||
- (dir < 0 && snapPosDist > 0))
- continue; // wrong direction
- if (snapPos < minPos || snapPos > maxPos )
- continue; // invalid
-
- if (qIsNaN(bestSnapPos) ||
- qAbs(snapPosDist) < bestSnapPosDist) {
- bestSnapPos = snapPos;
- bestSnapPosDist = qAbs(snapPosDist);
- }
- }
-
- // the snap point interval
- if (snapIntervalY > 0.0) {
- qreal first = minPos + snapFirstY;
- qreal snapPos;
- if (dir > 0)
- snapPos = qCeil((p - first) / snapIntervalY) * snapIntervalY + first;
- else if (dir < 0)
- snapPos = qFloor((p - first) / snapIntervalY) * snapIntervalY + first;
- else if (p <= first)
- snapPos = first;
- else
- {
- qreal last = qFloor((maxPos - first) / snapIntervalY) * snapIntervalY + first;
- if (p >= last)
- snapPos = last;
- else
- snapPos = qRound((p - first) / snapIntervalY) * snapIntervalY + first;
- }
-
- if (snapPos >= first && snapPos <= maxPos ) {
- qreal snapPosDist = snapPos - p;
-
- if (qIsNaN(bestSnapPos) ||
- qAbs(snapPosDist) < bestSnapPosDist) {
- bestSnapPos = snapPos;
- bestSnapPosDist = qAbs(snapPosDist);
- }
- }
- }
- }
-
- return bestSnapPos;
-}
-
-/*!
- \enum QScroller::State
-
- This enum contains the different QScroller states.
-
- \value Inactive The scroller is not scrolling and nothing is pressed.
- \value Pressed A touch event was received or the mouse button was pressed but the scroll area is currently not dragged.
- \value Dragging The scroll area is currently following the touch point or mouse.
- \value Scrolling The scroll area is moving on it's own.
-*/
-
-/*!
- \enum QScroller::ScrollerGestureType
-
- This enum contains the different gesture types that are supported by the QScroller gesture recognizer.
-
- \value TouchGesture The gesture recognizer will only trigger on touch
- events. Specifically it will react on single touch points when using a
- touch screen and dual touch points when using a touchpad.
- \value LeftMouseButtonGesture The gesture recognizer will only trigger on left mouse button events.
- \value MiddleMouseButtonGesture The gesture recognizer will only trigger on middle mouse button events.
- \value RightMouseButtonGesture The gesture recognizer will only trigger on right mouse button events.
-*/
-
-/*!
- \enum QScroller::Input
-
- This enum contains an input device agnostic view of input events that are relevant for QScroller.
-
- \value InputPress The user pressed the input device (e.g. QEvent::MouseButtonPress,
- QEvent::GraphicsSceneMousePress, QEvent::TouchBegin)
-
- \value InputMove The user moved the input device (e.g. QEvent::MouseMove,
- QEvent::GraphicsSceneMouseMove, QEvent::TouchUpdate)
-
- \value InputRelease The user released the input device (e.g. QEvent::MouseButtonRelease,
- QEvent::GraphicsSceneMouseRelease, QEvent::TouchEnd)
-
-*/
-
-QT_END_NAMESPACE
diff --git a/src/gui/util/qscroller.h b/src/gui/util/qscroller.h
deleted file mode 100644
index 1599c7dcdf..0000000000
--- a/src/gui/util/qscroller.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLER_H
-#define QSCROLLER_H
-
-#include <QtCore/QObject>
-#include <QtCore/QPointF>
-#include <QtGui/QScrollerProperties>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QWidget;
-class QScrollerPrivate;
-class QScrollerProperties;
-#ifndef QT_NO_GESTURES
-class QFlickGestureRecognizer;
-class QMouseFlickGestureRecognizer;
-#endif
-
-class Q_GUI_EXPORT QScroller : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(State state READ state NOTIFY stateChanged)
- Q_PROPERTY(QScrollerProperties scrollerProperties READ scrollerProperties WRITE setScrollerProperties NOTIFY scrollerPropertiesChanged)
- Q_ENUMS(State)
-
-public:
- enum State
- {
- Inactive,
- Pressed,
- Dragging,
- Scrolling
- };
-
- enum ScrollerGestureType
- {
- TouchGesture,
- LeftMouseButtonGesture,
- RightMouseButtonGesture,
- MiddleMouseButtonGesture
- };
-
- enum Input
- {
- InputPress = 1,
- InputMove,
- InputRelease
- };
-
- static bool hasScroller(QObject *target);
-
- static QScroller *scroller(QObject *target);
- static const QScroller *scroller(const QObject *target);
-
-#ifndef QT_NO_GESTURES
- static Qt::GestureType grabGesture(QObject *target, ScrollerGestureType gestureType = TouchGesture);
- static Qt::GestureType grabbedGesture(QObject *target);
- static void ungrabGesture(QObject *target);
-#endif
-
- static QList<QScroller *> activeScrollers();
-
- QObject *target() const;
-
- State state() const;
-
- bool handleInput(Input input, const QPointF &position, qint64 timestamp = 0);
-
- void stop();
- QPointF velocity() const;
- QPointF finalPosition() const;
- QPointF pixelPerMeter() const;
-
- QScrollerProperties scrollerProperties() const;
-
- void setSnapPositionsX( const QList<qreal> &positions );
- void setSnapPositionsX( qreal first, qreal interval );
- void setSnapPositionsY( const QList<qreal> &positions );
- void setSnapPositionsY( qreal first, qreal interval );
-
-public Q_SLOTS:
- void setScrollerProperties(const QScrollerProperties &prop);
- void scrollTo(const QPointF &pos);
- void scrollTo(const QPointF &pos, int scrollTime);
- void ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin);
- void ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin, int scrollTime);
- void resendPrepareEvent();
-
-Q_SIGNALS:
- void stateChanged(QScroller::State newstate);
- void scrollerPropertiesChanged(const QScrollerProperties &);
-
-private:
- QScrollerPrivate *d_ptr;
-
- QScroller(QObject *target);
- virtual ~QScroller();
-
- Q_DISABLE_COPY(QScroller)
- Q_DECLARE_PRIVATE(QScroller)
-
-#ifndef QT_NO_GESTURES
- friend class QFlickGestureRecognizer;
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSCROLLER_H
diff --git a/src/gui/util/qscroller_mac.mm b/src/gui/util/qscroller_mac.mm
deleted file mode 100644
index 4bf69c17c0..0000000000
--- a/src/gui/util/qscroller_mac.mm
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qglobal.h>
-
-#ifdef Q_WS_MAC
-
-#import <Cocoa/Cocoa.h>
-
-#include "qscroller_p.h"
-
-QPointF QScrollerPrivate::realDpi(int screen)
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSArray *nsscreens = [NSScreen screens];
-
- if (screen < 0 || screen >= int([nsscreens count]))
- screen = 0;
-
- NSScreen *nsscreen = [nsscreens objectAtIndex:screen];
- CGDirectDisplayID display = [[[nsscreen deviceDescription] objectForKey:@"NSScreenNumber"] intValue];
-
- CGSize mmsize = CGDisplayScreenSize(display);
- if (mmsize.width > 0 && mmsize.height > 0) {
- return QPointF(CGDisplayPixelsWide(display) / mmsize.width,
- CGDisplayPixelsHigh(display) / mmsize.height) * qreal(25.4);
- } else {
- return QPointF();
- }
- [pool release];
-}
-
-#endif
diff --git a/src/gui/util/qscroller_p.h b/src/gui/util/qscroller_p.h
deleted file mode 100644
index c1196152df..0000000000
--- a/src/gui/util/qscroller_p.h
+++ /dev/null
@@ -1,209 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLER_P_H
-#define QSCROLLER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QObject>
-#include <QPointer>
-#include <QQueue>
-#include <QSet>
-#include <QEasingCurve>
-#include <QElapsedTimer>
-#include <QSizeF>
-#include <QPointF>
-#include <QRectF>
-#include <qscroller.h>
-#include <qscrollerproperties.h>
-#include <private/qscrollerproperties_p.h>
-#include <QAbstractAnimation>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_GESTURES
-class QFlickGestureRecognizer;
-#endif
-
-#ifndef QT_NO_ANIMATION
-class QScrollTimer;
-#endif
-class QScrollerPrivate : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PUBLIC(QScroller)
-
-public:
- QScrollerPrivate(QScroller *q, QObject *target);
- void init();
-
- void sendEvent(QObject *o, QEvent *e);
-
- void setState(QScroller::State s);
-
- enum ScrollType {
- ScrollTypeFlick = 0,
- ScrollTypeScrollTo,
- ScrollTypeOvershoot
- };
-
- struct ScrollSegment {
- qint64 startTime;
- qint64 deltaTime;
- qreal startPos;
- qreal deltaPos;
- QEasingCurve curve;
- qreal stopProgress; // whatever is..
- qreal stopPos; // ..reached first
- ScrollType type;
- };
-
- bool pressWhileInactive(const QPointF &position, qint64 timestamp);
- bool moveWhilePressed(const QPointF &position, qint64 timestamp);
- bool releaseWhilePressed(const QPointF &position, qint64 timestamp);
- bool moveWhileDragging(const QPointF &position, qint64 timestamp);
- bool releaseWhileDragging(const QPointF &position, qint64 timestamp);
- bool pressWhileScrolling(const QPointF &position, qint64 timestamp);
-
- void timerTick();
- void timerEventWhileDragging();
- void timerEventWhileScrolling();
-
- bool prepareScrolling(const QPointF &position);
- void handleDrag(const QPointF &position, qint64 timestamp);
-
- QPointF realDpi(int screen);
- QPointF dpi() const;
- void setDpi(const QPointF &dpi);
- void setDpiFromWidget(QWidget *widget);
-
- void updateVelocity(const QPointF &deltaPixelRaw, qint64 deltaTime);
- void pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, qreal startPos, qreal deltaPos, qreal stopPos, QEasingCurve::Type curve, Qt::Orientation orientation);
- void recalcScrollingSegments(bool forceRecalc = false);
- qreal scrollingSegmentsEndPos(Qt::Orientation orientation) const;
- bool scrollingSegmentsValid(Qt::Orientation orientation);
- void createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, Qt::Orientation orientation, ScrollType type);
- void createScrollingSegments(qreal v, qreal startPos, qreal ppm, Qt::Orientation orientation);
-
- void setContentPositionHelperDragging(const QPointF &deltaPos);
- void setContentPositionHelperScrolling();
-
- qreal nextSnapPos(qreal p, int dir, Qt::Orientation orientation);
- static qreal nextSegmentPosition(QQueue<ScrollSegment> &segments, qint64 now, qreal oldPos);
-
- inline int frameRateSkip() const { return properties.d.data()->frameRate; }
-
- static const char *stateName(QScroller::State state);
- static const char *inputName(QScroller::Input input);
-
-public slots:
- void targetDestroyed();
-
-public:
- // non static
- QObject *target;
- QScrollerProperties properties;
-#ifndef QT_NO_GESTURES
- QFlickGestureRecognizer *recognizer;
- Qt::GestureType recognizerType;
-#endif
-
- // scroller state:
-
- // QPointer<QObject> scrollTarget;
- QSizeF viewportSize;
- QRectF contentPosRange;
- QPointF contentPosition;
- QPointF overshootPosition; // the number of pixels we are overshooting (before overshootDragResistanceFactor)
-
- // state
-
- bool enabled;
- QScroller::State state;
- bool firstScroll; // true if we haven't already send a scroll event
-
- QPointF oldVelocity; // the release velocity of the last drag
-
- QPointF pressPosition;
- QPointF lastPosition;
- qint64 pressTimestamp;
- qint64 lastTimestamp;
-
- QPointF dragDistance; // the distance we should move during the next drag timer event
-
- QQueue<ScrollSegment> xSegments;
- QQueue<ScrollSegment> ySegments;
-
- // snap positions
- QList<qreal> snapPositionsX;
- qreal snapFirstX;
- qreal snapIntervalX;
- QList<qreal> snapPositionsY;
- qreal snapFirstY;
- qreal snapIntervalY;
-
- QPointF pixelPerMeter;
-
- QElapsedTimer monotonicTimer;
-
- QPointF releaseVelocity; // the starting velocity of the scrolling state
-#ifndef QT_NO_ANIMATION
- QScrollTimer *scrollTimer;
-#endif
-
- QScroller *q_ptr;
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QSCROLLER_P_H
-
diff --git a/src/gui/util/qscrollerproperties.cpp b/src/gui/util/qscrollerproperties.cpp
deleted file mode 100644
index 85e2e82af1..0000000000
--- a/src/gui/util/qscrollerproperties.cpp
+++ /dev/null
@@ -1,393 +0,0 @@
-/****************************************************************************
-**
-** 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 <QPointer>
-#include <QObject>
-#include <QtCore/qmath.h>
-#ifdef Q_WS_WIN
-# include <QLibrary>
-#endif
-
-#include "qscrollerproperties.h"
-#include "private/qscrollerproperties_p.h"
-
-QT_BEGIN_NAMESPACE
-
-static QScrollerPropertiesPrivate *userDefaults = 0;
-static QScrollerPropertiesPrivate *systemDefaults = 0;
-
-QScrollerPropertiesPrivate *QScrollerPropertiesPrivate::defaults()
-{
- if (!systemDefaults) {
- QScrollerPropertiesPrivate spp;
- spp.mousePressEventDelay = qreal(0.25);
- spp.dragStartDistance = qreal(5.0 / 1000);
- spp.dragVelocitySmoothingFactor = qreal(0.8);
- spp.axisLockThreshold = qreal(0);
- spp.scrollingCurve.setType(QEasingCurve::OutQuad);
- spp.decelerationFactor = qreal(0.125);
- spp.minimumVelocity = qreal(50.0 / 1000);
- spp.maximumVelocity = qreal(500.0 / 1000);
- spp.maximumClickThroughVelocity = qreal(66.5 / 1000);
- spp.acceleratingFlickMaximumTime = qreal(1.25);
- spp.acceleratingFlickSpeedupFactor = qreal(3.0);
- spp.snapPositionRatio = qreal(0.5);
- spp.snapTime = qreal(0.3);
- spp.overshootDragResistanceFactor = qreal(0.5);
- spp.overshootDragDistanceFactor = qreal(1);
- spp.overshootScrollDistanceFactor = qreal(0.5);
- spp.overshootScrollTime = qreal(0.7);
-# ifdef Q_WS_WIN
- if (QLibrary::resolve(QLatin1String("UxTheme"), "BeginPanningFeedback"))
- spp.overshootScrollTime = qreal(0.35);
-# endif
- spp.hOvershootPolicy = QScrollerProperties::OvershootWhenScrollable;
- spp.vOvershootPolicy = QScrollerProperties::OvershootWhenScrollable;
- spp.frameRate = QScrollerProperties::Standard;
-
- systemDefaults = new QScrollerPropertiesPrivate(spp);
- }
- return new QScrollerPropertiesPrivate(userDefaults ? *userDefaults : *systemDefaults);
-}
-
-/*!
- \class QScrollerProperties
- \brief The QScrollerProperties class stores the settings for a QScroller.
- \since 4.8
-
- The QScrollerProperties class stores the parameters used by QScroller.
-
- The default settings are platform dependent so that Qt emulates the
- platform behaviour for kinetic scrolling.
-
- As a convention the QScrollerProperties are in physical units (meter,
- seconds) and are converted by QScroller using the current DPI.
-
- \sa QScroller
-*/
-
-/*!
- Constructs new scroller properties.
-*/
-QScrollerProperties::QScrollerProperties()
- : d(QScrollerPropertiesPrivate::defaults())
-{
-}
-
-/*!
- Constructs a copy of \a sp.
-*/
-QScrollerProperties::QScrollerProperties(const QScrollerProperties &sp)
- : d(new QScrollerPropertiesPrivate(*sp.d))
-{
-}
-
-/*!
- Assigns \a sp to these scroller properties and returns a reference to these scroller properties.
-*/
-QScrollerProperties &QScrollerProperties::operator=(const QScrollerProperties &sp)
-{
- *d.data() = *sp.d.data();
- return *this;
-}
-
-/*!
- Destroys the scroller properties.
-*/
-QScrollerProperties::~QScrollerProperties()
-{
-}
-
-/*!
- Returns true if these scroller properties are equal to \a sp; otherwise returns false.
-*/
-bool QScrollerProperties::operator==(const QScrollerProperties &sp) const
-{
- return *d.data() == *sp.d.data();
-}
-
-/*!
- Returns true if these scroller properties are different from \a sp; otherwise returns false.
-*/
-bool QScrollerProperties::operator!=(const QScrollerProperties &sp) const
-{
- return !(*d.data() == *sp.d.data());
-}
-
-bool QScrollerPropertiesPrivate::operator==(const QScrollerPropertiesPrivate &p) const
-{
- bool same = true;
- same &= (mousePressEventDelay == p.mousePressEventDelay);
- same &= (dragStartDistance == p.dragStartDistance);
- same &= (dragVelocitySmoothingFactor == p.dragVelocitySmoothingFactor);
- same &= (axisLockThreshold == p.axisLockThreshold);
- same &= (scrollingCurve == p.scrollingCurve);
- same &= (decelerationFactor == p.decelerationFactor);
- same &= (minimumVelocity == p.minimumVelocity);
- same &= (maximumVelocity == p.maximumVelocity);
- same &= (maximumClickThroughVelocity == p.maximumClickThroughVelocity);
- same &= (acceleratingFlickMaximumTime == p.acceleratingFlickMaximumTime);
- same &= (acceleratingFlickSpeedupFactor == p.acceleratingFlickSpeedupFactor);
- same &= (snapPositionRatio == p.snapPositionRatio);
- same &= (snapTime == p.snapTime);
- same &= (overshootDragResistanceFactor == p.overshootDragResistanceFactor);
- same &= (overshootDragDistanceFactor == p.overshootDragDistanceFactor);
- same &= (overshootScrollDistanceFactor == p.overshootScrollDistanceFactor);
- same &= (overshootScrollTime == p.overshootScrollTime);
- same &= (hOvershootPolicy == p.hOvershootPolicy);
- same &= (vOvershootPolicy == p.vOvershootPolicy);
- same &= (frameRate == p.frameRate);
- return same;
-}
-
-/*!
- Sets the scroller properties for all new QScrollerProperties objects to \a sp.
-
- Use this function to override the platform default properties returned by the default
- constructor. If you only want to change the scroller properties of a single scroller, use
- QScroller::setScrollerProperties()
-
- \note Calling this function will not change the content of already existing
- QScrollerProperties objects.
-
- \sa unsetDefaultScrollerProperties()
-*/
-void QScrollerProperties::setDefaultScrollerProperties(const QScrollerProperties &sp)
-{
- if (!userDefaults)
- userDefaults = new QScrollerPropertiesPrivate(*sp.d);
- else
- *userDefaults = *sp.d;
-}
-
-/*!
- Sets the scroller properties returned by the default constructor back to the platform default
- properties.
-
- \sa setDefaultScrollerProperties()
-*/
-void QScrollerProperties::unsetDefaultScrollerProperties()
-{
- delete userDefaults;
- userDefaults = 0;
-}
-
-/*!
- Query the \a metric value of the scroller properties.
-
- \sa setScrollMetric(), ScrollMetric
-*/
-QVariant QScrollerProperties::scrollMetric(ScrollMetric metric) const
-{
- switch (metric) {
- case MousePressEventDelay: return d->mousePressEventDelay;
- case DragStartDistance: return d->dragStartDistance;
- case DragVelocitySmoothingFactor: return d->dragVelocitySmoothingFactor;
- case AxisLockThreshold: return d->axisLockThreshold;
- case ScrollingCurve: return d->scrollingCurve;
- case DecelerationFactor: return d->decelerationFactor;
- case MinimumVelocity: return d->minimumVelocity;
- case MaximumVelocity: return d->maximumVelocity;
- case MaximumClickThroughVelocity: return d->maximumClickThroughVelocity;
- case AcceleratingFlickMaximumTime: return d->acceleratingFlickMaximumTime;
- case AcceleratingFlickSpeedupFactor:return d->acceleratingFlickSpeedupFactor;
- case SnapPositionRatio: return d->snapPositionRatio;
- case SnapTime: return d->snapTime;
- case OvershootDragResistanceFactor: return d->overshootDragResistanceFactor;
- case OvershootDragDistanceFactor: return d->overshootDragDistanceFactor;
- case OvershootScrollDistanceFactor: return d->overshootScrollDistanceFactor;
- case OvershootScrollTime: return d->overshootScrollTime;
- case HorizontalOvershootPolicy: return QVariant::fromValue(d->hOvershootPolicy);
- case VerticalOvershootPolicy: return QVariant::fromValue(d->vOvershootPolicy);
- case FrameRate: return QVariant::fromValue(d->frameRate);
- case ScrollMetricCount: break;
- }
- return QVariant();
-}
-
-/*!
- Set a specific value of the \a metric ScrollerMetric to \a value.
-
- \sa scrollMetric(), ScrollMetric
-*/
-void QScrollerProperties::setScrollMetric(ScrollMetric metric, const QVariant &value)
-{
- switch (metric) {
- case MousePressEventDelay: d->mousePressEventDelay = value.toReal(); break;
- case DragStartDistance: d->dragStartDistance = value.toReal(); break;
- case DragVelocitySmoothingFactor: d->dragVelocitySmoothingFactor = qBound(qreal(0), value.toReal(), qreal(1)); break;
- case AxisLockThreshold: d->axisLockThreshold = qBound(qreal(0), value.toReal(), qreal(1)); break;
- case ScrollingCurve: d->scrollingCurve = value.toEasingCurve(); break;
- case DecelerationFactor: d->decelerationFactor = value.toReal(); break;
- case MinimumVelocity: d->minimumVelocity = value.toReal(); break;
- case MaximumVelocity: d->maximumVelocity = value.toReal(); break;
- case MaximumClickThroughVelocity: d->maximumClickThroughVelocity = value.toReal(); break;
- case AcceleratingFlickMaximumTime: d->acceleratingFlickMaximumTime = value.toReal(); break;
- case AcceleratingFlickSpeedupFactor:d->acceleratingFlickSpeedupFactor = value.toReal(); break;
- case SnapPositionRatio: d->snapPositionRatio = qBound(qreal(0), value.toReal(), qreal(1)); break;
- case SnapTime: d->snapTime = value.toReal(); break;
- case OvershootDragResistanceFactor: d->overshootDragResistanceFactor = value.toReal(); break;
- case OvershootDragDistanceFactor: d->overshootDragDistanceFactor = qBound(qreal(0), value.toReal(), qreal(1)); break;
- case OvershootScrollDistanceFactor: d->overshootScrollDistanceFactor = qBound(qreal(0), value.toReal(), qreal(1)); break;
- case OvershootScrollTime: d->overshootScrollTime = value.toReal(); break;
- case HorizontalOvershootPolicy: d->hOvershootPolicy = value.value<QScrollerProperties::OvershootPolicy>(); break;
- case VerticalOvershootPolicy: d->vOvershootPolicy = value.value<QScrollerProperties::OvershootPolicy>(); break;
- case FrameRate: d->frameRate = value.value<QScrollerProperties::FrameRates>(); break;
- case ScrollMetricCount: break;
- }
-}
-
-/*!
- \enum QScrollerProperties::FrameRates
-
- This enum describes the available frame rates used while dragging or scrolling.
-
- \value Fps60 60 frames per second
- \value Fps30 30 frames per second
- \value Fps20 20 frames per second
- \value Standard the default value is 60 frames per second (which corresponds to QAbstractAnimation).
-*/
-
-/*!
- \enum QScrollerProperties::OvershootPolicy
-
- This enum describes the various modes of overshooting.
-
- \value OvershootWhenScrollable Overshooting is possible when the content is scrollable. This is the
- default.
-
- \value OvershootAlwaysOff Overshooting is never enabled, even when the content is scrollable.
-
- \value OvershootAlwaysOn Overshooting is always enabled, even when the content is not
- scrollable.
-*/
-
-/*!
- \enum QScrollerProperties::ScrollMetric
-
- This enum contains the different scroll metric types. When not indicated otherwise the
- setScrollMetric function expects a QVariant of type qreal.
-
- See the QScroller documentation for further details of the concepts behind the different
- values.
-
- \value MousePressEventDelay This is the time a mouse press event is delayed when starting
- a flick gesture in \c{[s]}. If the gesture is triggered within that time, no mouse press or
- release is sent to the scrolled object. If it triggers after that delay the delayed
- mouse press plus a faked release event at global postion \c{QPoint(-QWIDGETSIZE_MAX,
- -QWIDGETSIZE_MAX)} is sent. If the gesture is canceled, then both the delayed mouse
- press plus the real release event are delivered.
-
- \value DragStartDistance This is the minimum distance the touch or mouse point needs to be
- moved before the flick gesture is triggered in \c m.
-
- \value DragVelocitySmoothingFactor A value that describes to which extent new drag velocities are
- included in the final scrolling velocity. This value should be in the range between \c 0 and
- \c 1. The lower the value, the more smoothing is applied to the dragging velocity.
-
- \value AxisLockThreshold Restricts the movement to one axis if the movement is inside an angle
- around the axis. The threshold must be in the range \c 0 to \c 1.
-
- \value ScrollingCurve The QEasingCurve used when decelerating the scrolling velocity after an
- user initiated flick. Please note that this is the easing curve for the positions, \bold{not}
- the velocity: the default is QEasingCurve::OutQuad, which results in a linear decrease in
- velocity (1st derivative) and a constant deceleration (2nd derivative).
-
- \value DecelerationFactor This factor influences how long it takes the scroller to decelerate
- to 0 velocity. The actual value depends on the chosen ScrollingCurve. For most
- types the value should be in the range from \c 0.1 to \c 2.0
-
- \value MinimumVelocity The minimum velocity that is needed after ending the touch or releasing
- the mouse to start scrolling in \c{m/s}.
-
- \value MaximumVelocity This is the maximum velocity that can be reached in \c{m/s}.
-
- \value MaximumClickThroughVelocity This is the maximum allowed scroll speed for a click-through
- in \c{m/s}. This means that a click on a currently (slowly) scrolling object will not only stop
- the scrolling but the click event will also be delivered to the UI control. This is
- useful when using exponential-type scrolling curves.
-
- \value AcceleratingFlickMaximumTime This is the maximum time in \c seconds that a flick gesture
- can take to be recognized as an accelerating flick. If set to zero no such gesture is
- detected. An "accelerating flick" is a flick gesture executed on an already scrolling object.
- In such cases the scrolling speed is multiplied by AcceleratingFlickSpeedupFactor in order to
- accelerate it.
-
- \value AcceleratingFlickSpeedupFactor The current speed is multiplied by this number if an
- accelerating flick is detected. Should be \c{>= 1}.
-
- \value SnapPositionRatio This is the distance that the user must drag the area beween two snap
- points in order to snap it to the next position. \c{0.33} means that the scroll must only
- reach one third of the distance between two snap points to snap to the next one. The ratio must
- be between \c 0 and \c 1.
-
- \value SnapTime This is the time factor for the scrolling curve. A lower value means that the
- scrolling will take longer. The scrolling distance is independet of this value.
-
- \value OvershootDragResistanceFactor This value is the factor between the mouse dragging and
- the actual scroll area movement (during overshoot). The factor must be between \c 0 and \c 1.
-
- \value OvershootDragDistanceFactor This is the maximum distance for overshoot movements while
- dragging. The actual overshoot distance is calculated by multiplying this value with the
- viewport size of the scrolled object. The factor must be between \c 0 and \c 1.
-
- \value OvershootScrollDistanceFactor This is the maximum distance for overshoot movements while
- scrolling. The actual overshoot distance is calculated by multiplying this value with the
- viewport size of the scrolled object. The factor must be between \c 0 and \c 1.
-
- \value OvershootScrollTime This is the time in \c seconds that is used to play the
- complete overshoot animation.
-
- \value HorizontalOvershootPolicy This is the horizontal overshooting policy (see OvershootPolicy).
-
- \value VerticalOvershootPolicy This is the horizontal overshooting policy (see OvershootPolicy).
-
- \value FrameRate This is the frame rate which should be used while dragging or scrolling.
- QScroller uses a QAbstractAnimation timer internally to sync all scrolling operations to other
- animations that might be active at the same time. If the standard value of 60 frames per
- second is too fast, it can be lowered with this setting,
- while still being in-sync with QAbstractAnimation. Please note that only the values of the
- FrameRates enum are allowed here.
-
- \value ScrollMetricCount This is always the last entry.
-*/
-
-QT_END_NAMESPACE
diff --git a/src/gui/util/qscrollerproperties.h b/src/gui/util/qscrollerproperties.h
deleted file mode 100644
index 75d8932f81..0000000000
--- a/src/gui/util/qscrollerproperties.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLERPROPERTIES_H
-#define QSCROLLERPROPERTIES_H
-
-#include <QtCore/QScopedPointer>
-#include <QtCore/QMetaType>
-#include <QtCore/QVariant>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QScroller;
-class QScrollerPrivate;
-class QScrollerPropertiesPrivate;
-
-class Q_GUI_EXPORT QScrollerProperties
-{
-public:
- QScrollerProperties();
- QScrollerProperties(const QScrollerProperties &sp);
- QScrollerProperties &operator=(const QScrollerProperties &sp);
- virtual ~QScrollerProperties();
-
- bool operator==(const QScrollerProperties &sp) const;
- bool operator!=(const QScrollerProperties &sp) const;
-
- static void setDefaultScrollerProperties(const QScrollerProperties &sp);
- static void unsetDefaultScrollerProperties();
-
- enum OvershootPolicy
- {
- OvershootWhenScrollable,
- OvershootAlwaysOff,
- OvershootAlwaysOn
- };
-
- enum FrameRates {
- Standard,
- Fps60,
- Fps30,
- Fps20
- };
-
- enum ScrollMetric
- {
- MousePressEventDelay, // qreal [s]
- DragStartDistance, // qreal [m]
- DragVelocitySmoothingFactor, // qreal [0..1/s] (complex calculation involving time) v = v_new* DASF + v_old * (1-DASF)
- AxisLockThreshold, // qreal [0..1] atan(|min(dx,dy)|/|max(dx,dy)|)
-
- ScrollingCurve, // QEasingCurve
- DecelerationFactor, // slope of the curve
-
- MinimumVelocity, // qreal [m/s]
- MaximumVelocity, // qreal [m/s]
- MaximumClickThroughVelocity, // qreal [m/s]
-
- AcceleratingFlickMaximumTime, // qreal [s]
- AcceleratingFlickSpeedupFactor, // qreal [1..]
-
- SnapPositionRatio, // qreal [0..1]
- SnapTime, // qreal [s]
-
- OvershootDragResistanceFactor, // qreal [0..1]
- OvershootDragDistanceFactor, // qreal [0..1]
- OvershootScrollDistanceFactor, // qreal [0..1]
- OvershootScrollTime, // qreal [s]
-
- HorizontalOvershootPolicy, // enum OvershootPolicy
- VerticalOvershootPolicy, // enum OvershootPolicy
- FrameRate, // enum FrameRates
-
- ScrollMetricCount
- };
-
- QVariant scrollMetric(ScrollMetric metric) const;
- void setScrollMetric(ScrollMetric metric, const QVariant &value);
-
-protected:
- QScopedPointer<QScrollerPropertiesPrivate> d;
-
-private:
- QScrollerProperties(QScrollerPropertiesPrivate &dd);
-
- friend class QScrollerPropertiesPrivate;
- friend class QScroller;
- friend class QScrollerPrivate;
-};
-
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(QScrollerProperties::OvershootPolicy)
-Q_DECLARE_METATYPE(QScrollerProperties::FrameRates)
-
-QT_END_HEADER
-
-#endif // QSCROLLERPROPERTIES_H
diff --git a/src/gui/util/qscrollerproperties_p.h b/src/gui/util/qscrollerproperties_p.h
deleted file mode 100644
index 76d8b0a79b..0000000000
--- a/src/gui/util/qscrollerproperties_p.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLERPROPERTIES_P_H
-#define QSCROLLERPROPERTIES_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QPointF>
-#include <QEasingCurve>
-#include <qscrollerproperties.h>
-
-QT_BEGIN_NAMESPACE
-
-class QScrollerPropertiesPrivate
-{
-public:
- static QScrollerPropertiesPrivate *defaults();
-
- bool operator==(const QScrollerPropertiesPrivate &) const;
-
- qreal mousePressEventDelay;
- qreal dragStartDistance;
- qreal dragVelocitySmoothingFactor;
- qreal axisLockThreshold;
- QEasingCurve scrollingCurve;
- qreal decelerationFactor;
- qreal minimumVelocity;
- qreal maximumVelocity;
- qreal maximumClickThroughVelocity;
- qreal acceleratingFlickMaximumTime;
- qreal acceleratingFlickSpeedupFactor;
- qreal snapPositionRatio;
- qreal snapTime;
- qreal overshootDragResistanceFactor;
- qreal overshootDragDistanceFactor;
- qreal overshootScrollDistanceFactor;
- qreal overshootScrollTime;
- QScrollerProperties::OvershootPolicy hOvershootPolicy;
- QScrollerProperties::OvershootPolicy vOvershootPolicy;
- QScrollerProperties::FrameRates frameRate;
-};
-
-QT_END_NAMESPACE
-
-#endif // QSCROLLERPROPERTIES_P_H
-
diff --git a/src/gui/util/qsystemtrayicon.cpp b/src/gui/util/qsystemtrayicon.cpp
deleted file mode 100644
index 33cc61ee97..0000000000
--- a/src/gui/util/qsystemtrayicon.cpp
+++ /dev/null
@@ -1,674 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsystemtrayicon.h"
-#include "qsystemtrayicon_p.h"
-
-#ifndef QT_NO_SYSTEMTRAYICON
-
-#include "qmenu.h"
-#include "qevent.h"
-#include "qpoint.h"
-#include "qlabel.h"
-#include "qpushbutton.h"
-#include "qpainterpath.h"
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qgridlayout.h"
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qbitmap.h"
-#include "private/qlabel_p.h"
-#include "qapplication.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QSystemTrayIcon
- \brief The QSystemTrayIcon class provides an icon for an application in the system tray.
- \since 4.2
- \ingroup desktop
-
- Modern operating systems usually provide a special area on the desktop,
- called the \e{system tray} or \e{notification area}, where long-running
- applications can display icons and short messages.
-
- \image system-tray.png The system tray on Windows XP.
-
- The QSystemTrayIcon class can be used on the following platforms:
-
- \list
- \o All supported versions of Windows.
- \o All window managers for X11 that implement the \l{freedesktop.org} system
- tray specification, including recent versions of KDE and GNOME.
- \o All supported versions of Mac OS X. Note that the Growl
- notification system must be installed for
- QSystemTrayIcon::showMessage() to display messages.
- \endlist
-
- To check whether a system tray is present on the user's desktop,
- call the QSystemTrayIcon::isSystemTrayAvailable() static function.
-
- To add a system tray entry, create a QSystemTrayIcon object, call setContextMenu()
- to provide a context menu for the icon, and call show() to make it visible in the
- system tray. Status notification messages ("balloon messages") can be displayed at
- any time using showMessage().
-
- If the system tray is unavailable when a system tray icon is constructed, but
- becomes available later, QSystemTrayIcon will automatically add an entry for the
- application in the system tray if the icon is \l visible.
-
- The activated() signal is emitted when the user activates the icon.
-
- Only on X11, when a tooltip is requested, the QSystemTrayIcon receives a QHelpEvent
- of type QEvent::ToolTip. Additionally, the QSystemTrayIcon receives wheel events of
- type QEvent::Wheel. These are not supported on any other platform.
-
- \sa QDesktopServices, QDesktopWidget, {Desktop Integration}, {System Tray Icon Example}
-*/
-
-/*!
- \enum QSystemTrayIcon::MessageIcon
-
- This enum describes the icon that is shown when a balloon message is displayed.
-
- \value NoIcon No icon is shown.
- \value Information An information icon is shown.
- \value Warning A standard warning icon is shown.
- \value Critical A critical warning icon is shown.
-
- \sa QMessageBox
-*/
-
-/*!
- Constructs a QSystemTrayIcon object with the given \a parent.
-
- The icon is initially invisible.
-
- \sa visible
-*/
-QSystemTrayIcon::QSystemTrayIcon(QObject *parent)
-: QObject(*new QSystemTrayIconPrivate(), parent)
-{
-}
-
-/*!
- Constructs a QSystemTrayIcon object with the given \a icon and \a parent.
-
- The icon is initially invisible.
-
- \sa visible
-*/
-QSystemTrayIcon::QSystemTrayIcon(const QIcon &icon, QObject *parent)
-: QObject(*new QSystemTrayIconPrivate(), parent)
-{
- setIcon(icon);
-}
-
-/*!
- Removes the icon from the system tray and frees all allocated resources.
-*/
-QSystemTrayIcon::~QSystemTrayIcon()
-{
- Q_D(QSystemTrayIcon);
- d->remove_sys();
-}
-
-#ifndef QT_NO_MENU
-
-/*!
- Sets the specified \a menu to be the context menu for the system tray icon.
-
- The menu will pop up when the user requests the context menu for the system
- tray icon by clicking the mouse button.
-
- On Mac OS X, this is currenly converted to a NSMenu, so the
- aboutToHide() signal is not emitted.
-
- \note The system tray icon does not take ownership of the menu. You must
- ensure that it is deleted at the appropriate time by, for example, creating
- the menu with a suitable parent object.
-*/
-void QSystemTrayIcon::setContextMenu(QMenu *menu)
-{
- Q_D(QSystemTrayIcon);
- d->menu = menu;
- d->updateMenu_sys();
-}
-
-/*!
- Returns the current context menu for the system tray entry.
-*/
-QMenu* QSystemTrayIcon::contextMenu() const
-{
- Q_D(const QSystemTrayIcon);
- return d->menu;
-}
-
-#endif // QT_NO_MENU
-
-/*!
- \property QSystemTrayIcon::icon
- \brief the system tray icon
-
- On Windows, the system tray icon size is 16x16; on X11, the preferred size is
- 22x22. The icon will be scaled to the appropriate size as necessary.
-*/
-void QSystemTrayIcon::setIcon(const QIcon &icon)
-{
- Q_D(QSystemTrayIcon);
- d->icon = icon;
- d->updateIcon_sys();
-}
-
-QIcon QSystemTrayIcon::icon() const
-{
- Q_D(const QSystemTrayIcon);
- return d->icon;
-}
-
-/*!
- \property QSystemTrayIcon::toolTip
- \brief the tooltip for the system tray entry
-
- On some systems, the tooltip's length is limited. The tooltip will be truncated
- if necessary.
-*/
-void QSystemTrayIcon::setToolTip(const QString &tooltip)
-{
- Q_D(QSystemTrayIcon);
- d->toolTip = tooltip;
- d->updateToolTip_sys();
-}
-
-QString QSystemTrayIcon::toolTip() const
-{
- Q_D(const QSystemTrayIcon);
- return d->toolTip;
-}
-
-/*!
- \fn void QSystemTrayIcon::show()
-
- Shows the icon in the system tray.
-
- \sa hide(), visible
-*/
-
-/*!
- \fn void QSystemTrayIcon::hide()
-
- Hides the system tray entry.
-
- \sa show(), visible
-*/
-
-/*!
- \since 4.3
- Returns the geometry of the system tray icon in screen coordinates.
-
- \sa visible
-*/
-QRect QSystemTrayIcon::geometry() const
-{
- Q_D(const QSystemTrayIcon);
- if (!d->visible)
- return QRect();
- return d->geometry_sys();
-}
-
-/*!
- \property QSystemTrayIcon::visible
- \brief whether the system tray entry is visible
-
- Setting this property to true or calling show() makes the system tray icon
- visible; setting this property to false or calling hide() hides it.
-*/
-void QSystemTrayIcon::setVisible(bool visible)
-{
- Q_D(QSystemTrayIcon);
- if (visible == d->visible)
- return;
- if (d->icon.isNull() && visible)
- qWarning("QSystemTrayIcon::setVisible: No Icon set");
- d->visible = visible;
- if (d->visible)
- d->install_sys();
- else
- d->remove_sys();
-}
-
-bool QSystemTrayIcon::isVisible() const
-{
- Q_D(const QSystemTrayIcon);
- return d->visible;
-}
-
-/*!
- \reimp
-*/
-bool QSystemTrayIcon::event(QEvent *e)
-{
-#if defined(Q_WS_X11)
- if (e->type() == QEvent::ToolTip) {
- Q_D(QSystemTrayIcon);
- return d->sys->deliverToolTipEvent(e);
- }
-#endif
- return QObject::event(e);
-}
-
-/*!
- \enum QSystemTrayIcon::ActivationReason
-
- This enum describes the reason the system tray was activated.
-
- \value Unknown Unknown reason
- \value Context The context menu for the system tray entry was requested
- \value DoubleClick The system tray entry was double clicked
- \value Trigger The system tray entry was clicked
- \value MiddleClick The system tray entry was clicked with the middle mouse button
-
- \sa activated()
-*/
-
-/*!
- \fn void QSystemTrayIcon::activated(QSystemTrayIcon::ActivationReason reason)
-
- This signal is emitted when the user activates the system tray icon. \a reason
- specifies the reason for activation. QSystemTrayIcon::ActivationReason enumerates
- the various reasons.
-
- \sa QSystemTrayIcon::ActivationReason
-*/
-
-/*!
- \fn void QSystemTrayIcon::messageClicked()
-
- This signal is emitted when the message displayed using showMessage()
- was clicked by the user.
-
- Currently this signal is not sent on Mac OS X.
-
- \note We follow Microsoft Windows XP/Vista behavior, so the
- signal is also emitted when the user clicks on a tray icon with
- a balloon message displayed.
-
- \sa activated()
-*/
-
-
-/*!
- Returns true if the system tray is available; otherwise returns false.
-
- If the system tray is currently unavailable but becomes available later,
- QSystemTrayIcon will automatically add an entry in the system tray if it
- is \l visible.
-*/
-
-bool QSystemTrayIcon::isSystemTrayAvailable()
-{
- return QSystemTrayIconPrivate::isSystemTrayAvailable_sys();
-}
-
-/*!
- Returns true if the system tray supports balloon messages; otherwise returns false.
-
- \sa showMessage()
-*/
-bool QSystemTrayIcon::supportsMessages()
-{
- return QSystemTrayIconPrivate::supportsMessages_sys();
-}
-
-/*!
- \fn void QSystemTrayIcon::showMessage(const QString &title, const QString &message, MessageIcon icon, int millisecondsTimeoutHint)
- \since 4.3
-
- Shows a balloon message for the entry with the given \a title, \a message and
- \a icon for the time specified in \a millisecondsTimeoutHint. \a title and \a message
- must be plain text strings.
-
- Message can be clicked by the user; the messageClicked() signal will emitted when
- this occurs.
-
- Note that display of messages are dependent on the system configuration and user
- preferences, and that messages may not appear at all. Hence, it should not be
- relied upon as the sole means for providing critical information.
-
- On Windows, the \a millisecondsTimeoutHint is usually ignored by the system
- when the application has focus.
-
- On Mac OS X, the Growl notification system must be installed for this function to
- display messages.
-
- \sa show() supportsMessages()
- */
-void QSystemTrayIcon::showMessage(const QString& title, const QString& msg,
- QSystemTrayIcon::MessageIcon icon, int msecs)
-{
- Q_D(QSystemTrayIcon);
- if (d->visible)
- d->showMessage_sys(title, msg, icon, msecs);
-}
-
-//////////////////////////////////////////////////////////////////////
-static QBalloonTip *theSolitaryBalloonTip = 0;
-
-void QBalloonTip::showBalloon(QSystemTrayIcon::MessageIcon icon, const QString& title,
- const QString& message, QSystemTrayIcon *trayIcon,
- const QPoint& pos, int timeout, bool showArrow)
-{
- hideBalloon();
- if (message.isEmpty() && title.isEmpty())
- return;
-
- theSolitaryBalloonTip = new QBalloonTip(icon, title, message, trayIcon);
- if (timeout < 0)
- timeout = 10000; //10 s default
- theSolitaryBalloonTip->balloon(pos, timeout, showArrow);
-}
-
-void QBalloonTip::hideBalloon()
-{
- if (!theSolitaryBalloonTip)
- return;
- theSolitaryBalloonTip->hide();
- delete theSolitaryBalloonTip;
- theSolitaryBalloonTip = 0;
-}
-
-bool QBalloonTip::isBalloonVisible()
-{
- return theSolitaryBalloonTip;
-}
-
-QBalloonTip::QBalloonTip(QSystemTrayIcon::MessageIcon icon, const QString& title,
- const QString& message, QSystemTrayIcon *ti)
- : QWidget(0, Qt::ToolTip), trayIcon(ti), timerId(-1)
-{
- setAttribute(Qt::WA_DeleteOnClose);
- QObject::connect(ti, SIGNAL(destroyed()), this, SLOT(close()));
-
- QLabel *titleLabel = new QLabel;
- titleLabel->installEventFilter(this);
- titleLabel->setText(title);
- QFont f = titleLabel->font();
- f.setBold(true);
-#ifdef Q_WS_WINCE
- f.setPointSize(f.pointSize() - 2);
-#endif
- titleLabel->setFont(f);
- titleLabel->setTextFormat(Qt::PlainText); // to maintain compat with windows
-
-#ifdef Q_WS_WINCE
- const int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize);
- const int closeButtonSize = style()->pixelMetric(QStyle::PM_SmallIconSize) - 2;
-#else
- const int iconSize = 18;
- const int closeButtonSize = 15;
-#endif
-
- QPushButton *closeButton = new QPushButton;
- closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
- closeButton->setIconSize(QSize(closeButtonSize, closeButtonSize));
- closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- closeButton->setFixedSize(closeButtonSize, closeButtonSize);
- QObject::connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
-
- QLabel *msgLabel = new QLabel;
-#ifdef Q_WS_WINCE
- f.setBold(false);
- msgLabel->setFont(f);
-#endif
- msgLabel->installEventFilter(this);
- msgLabel->setText(message);
- msgLabel->setTextFormat(Qt::PlainText);
- msgLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);
-
- // smart size for the message label
-#ifdef Q_WS_WINCE
- int limit = QApplication::desktop()->availableGeometry(msgLabel).size().width() / 2;
-#else
- int limit = QApplication::desktop()->availableGeometry(msgLabel).size().width() / 3;
-#endif
- if (msgLabel->sizeHint().width() > limit) {
- msgLabel->setWordWrap(true);
- if (msgLabel->sizeHint().width() > limit) {
- msgLabel->d_func()->ensureTextControl();
- if (QTextControl *control = msgLabel->d_func()->control) {
- QTextOption opt = control->document()->defaultTextOption();
- opt.setWrapMode(QTextOption::WrapAnywhere);
- control->document()->setDefaultTextOption(opt);
- }
- }
-#ifdef Q_WS_WINCE
- // Make sure that the text isn't wrapped "somewhere" in the balloon widget
- // in the case that we have a long title label.
- setMaximumWidth(limit);
-#else
- // Here we allow the text being much smaller than the balloon widget
- // to emulate the weird standard windows behavior.
- msgLabel->setFixedSize(limit, msgLabel->heightForWidth(limit));
-#endif
- }
-
- QIcon si;
- switch (icon) {
- case QSystemTrayIcon::Warning:
- si = style()->standardIcon(QStyle::SP_MessageBoxWarning);
- break;
- case QSystemTrayIcon::Critical:
- si = style()->standardIcon(QStyle::SP_MessageBoxCritical);
- break;
- case QSystemTrayIcon::Information:
- si = style()->standardIcon(QStyle::SP_MessageBoxInformation);
- break;
- case QSystemTrayIcon::NoIcon:
- default:
- break;
- }
-
- QGridLayout *layout = new QGridLayout;
- if (!si.isNull()) {
- QLabel *iconLabel = new QLabel;
- iconLabel->setPixmap(si.pixmap(iconSize, iconSize));
- iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- iconLabel->setMargin(2);
- layout->addWidget(iconLabel, 0, 0);
- layout->addWidget(titleLabel, 0, 1);
- } else {
- layout->addWidget(titleLabel, 0, 0, 1, 2);
- }
-
- layout->addWidget(closeButton, 0, 2);
- layout->addWidget(msgLabel, 1, 0, 1, 3);
- layout->setSizeConstraint(QLayout::SetFixedSize);
- layout->setMargin(3);
- setLayout(layout);
-
- QPalette pal = palette();
- pal.setColor(QPalette::Window, QColor(0xff, 0xff, 0xe1));
- pal.setColor(QPalette::WindowText, Qt::black);
- setPalette(pal);
-}
-
-QBalloonTip::~QBalloonTip()
-{
- theSolitaryBalloonTip = 0;
-}
-
-void QBalloonTip::paintEvent(QPaintEvent *)
-{
- QPainter painter(this);
- painter.drawPixmap(rect(), pixmap);
-}
-
-void QBalloonTip::resizeEvent(QResizeEvent *ev)
-{
- QWidget::resizeEvent(ev);
-}
-
-void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
-{
- QRect scr = QApplication::desktop()->screenGeometry(pos);
- QSize sh = sizeHint();
- const int border = 1;
- const int ah = 18, ao = 18, aw = 18, rc = 7;
- bool arrowAtTop = (pos.y() + sh.height() + ah < scr.height());
- bool arrowAtLeft = (pos.x() + sh.width() - ao < scr.width());
- setContentsMargins(border + 3, border + (arrowAtTop ? ah : 0) + 2, border + 3, border + (arrowAtTop ? 0 : ah) + 2);
- updateGeometry();
- sh = sizeHint();
-
- int ml, mr, mt, mb;
- QSize sz = sizeHint();
- if (!arrowAtTop) {
- ml = mt = 0;
- mr = sz.width() - 1;
- mb = sz.height() - ah - 1;
- } else {
- ml = 0;
- mt = ah;
- mr = sz.width() - 1;
- mb = sz.height() - 1;
- }
-
- QPainterPath path;
-#if defined(QT_NO_XSHAPE) && defined(Q_WS_X11)
- // XShape is required for setting the mask, so we just
- // draw an ugly square when its not available
- path.moveTo(0, 0);
- path.lineTo(sz.width() - 1, 0);
- path.lineTo(sz.width() - 1, sz.height() - 1);
- path.lineTo(0, sz.height() - 1);
- path.lineTo(0, 0);
- move(qMax(pos.x() - sz.width(), scr.left()), pos.y());
-#else
- path.moveTo(ml + rc, mt);
- if (arrowAtTop && arrowAtLeft) {
- if (showArrow) {
- path.lineTo(ml + ao, mt);
- path.lineTo(ml + ao, mt - ah);
- path.lineTo(ml + ao + aw, mt);
- }
- move(qMax(pos.x() - ao, scr.left() + 2), pos.y());
- } else if (arrowAtTop && !arrowAtLeft) {
- if (showArrow) {
- path.lineTo(mr - ao - aw, mt);
- path.lineTo(mr - ao, mt - ah);
- path.lineTo(mr - ao, mt);
- }
- move(qMin(pos.x() - sh.width() + ao, scr.right() - sh.width() - 2), pos.y());
- }
- path.lineTo(mr - rc, mt);
- path.arcTo(QRect(mr - rc*2, mt, rc*2, rc*2), 90, -90);
- path.lineTo(mr, mb - rc);
- path.arcTo(QRect(mr - rc*2, mb - rc*2, rc*2, rc*2), 0, -90);
- if (!arrowAtTop && !arrowAtLeft) {
- if (showArrow) {
- path.lineTo(mr - ao, mb);
- path.lineTo(mr - ao, mb + ah);
- path.lineTo(mr - ao - aw, mb);
- }
- move(qMin(pos.x() - sh.width() + ao, scr.right() - sh.width() - 2),
- pos.y() - sh.height());
- } else if (!arrowAtTop && arrowAtLeft) {
- if (showArrow) {
- path.lineTo(ao + aw, mb);
- path.lineTo(ao, mb + ah);
- path.lineTo(ao, mb);
- }
- move(qMax(pos.x() - ao, scr.x() + 2), pos.y() - sh.height());
- }
- path.lineTo(ml + rc, mb);
- path.arcTo(QRect(ml, mb - rc*2, rc*2, rc*2), -90, -90);
- path.lineTo(ml, mt + rc);
- path.arcTo(QRect(ml, mt, rc*2, rc*2), 180, -90);
-
- // Set the mask
- QBitmap bitmap = QBitmap(sizeHint());
- bitmap.fill(Qt::color0);
- QPainter painter1(&bitmap);
- painter1.setPen(QPen(Qt::color1, border));
- painter1.setBrush(QBrush(Qt::color1));
- painter1.drawPath(path);
- setMask(bitmap);
-#endif
-
- // Draw the border
- pixmap = QPixmap(sz);
- QPainter painter2(&pixmap);
- painter2.setPen(QPen(palette().color(QPalette::Window).darker(160), border));
- painter2.setBrush(palette().color(QPalette::Window));
- painter2.drawPath(path);
-
- if (msecs > 0)
- timerId = startTimer(msecs);
- show();
-}
-
-void QBalloonTip::mousePressEvent(QMouseEvent *e)
-{
- close();
- if(e->button() == Qt::LeftButton)
- emit trayIcon->messageClicked();
-}
-
-void QBalloonTip::timerEvent(QTimerEvent *e)
-{
- if (e->timerId() == timerId) {
- killTimer(timerId);
- if (!underMouse())
- close();
- return;
- }
- QWidget::timerEvent(e);
-}
-
-void qtsystray_sendActivated(QSystemTrayIcon *i, int r)
-{
- emit i->activated((QSystemTrayIcon::ActivationReason)r);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SYSTEMTRAYICON
diff --git a/src/gui/util/qsystemtrayicon.h b/src/gui/util/qsystemtrayicon.h
deleted file mode 100644
index 1f0dab5393..0000000000
--- a/src/gui/util/qsystemtrayicon.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** 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 QSYSTEMTRAYICON_H
-#define QSYSTEMTRAYICON_H
-
-#include <QtCore/qobject.h>
-
-#ifndef QT_NO_SYSTEMTRAYICON
-
-#include <QtGui/qicon.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QSystemTrayIconPrivate;
-
-class QMenu;
-class QEvent;
-class QWheelEvent;
-class QMouseEvent;
-class QPoint;
-
-class Q_GUI_EXPORT QSystemTrayIcon : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip)
- Q_PROPERTY(QIcon icon READ icon WRITE setIcon)
- Q_PROPERTY(bool visible READ isVisible WRITE setVisible DESIGNABLE false)
-
-public:
- QSystemTrayIcon(QObject *parent = 0);
- QSystemTrayIcon(const QIcon &icon, QObject *parent = 0);
- ~QSystemTrayIcon();
-
- enum ActivationReason {
- Unknown,
- Context,
- DoubleClick,
- Trigger,
- MiddleClick
- };
-
-#ifndef QT_NO_MENU
- void setContextMenu(QMenu *menu);
- QMenu *contextMenu() const;
-#endif
-
- QIcon icon() const;
- void setIcon(const QIcon &icon);
-
- QString toolTip() const;
- void setToolTip(const QString &tip);
-
- static bool isSystemTrayAvailable();
- static bool supportsMessages();
-
- enum MessageIcon { NoIcon, Information, Warning, Critical };
- void showMessage(const QString &title, const QString &msg,
- MessageIcon icon = Information, int msecs = 10000);
-
- QRect geometry() const;
- bool isVisible() const;
-
-public Q_SLOTS:
- void setVisible(bool visible);
- inline void show() { setVisible(true); }
- inline void hide() { setVisible(false); }
-
-Q_SIGNALS:
- void activated(QSystemTrayIcon::ActivationReason reason);
- void messageClicked();
-
-protected:
- bool event(QEvent *event);
-
-private:
- Q_DISABLE_COPY(QSystemTrayIcon)
- Q_DECLARE_PRIVATE(QSystemTrayIcon)
-
- friend class QSystemTrayIconSys;
- friend class QBalloonTip;
- friend void qtsystray_sendActivated(QSystemTrayIcon *, int);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_SYSTEMTRAYICON
-#endif // QSYSTEMTRAYICON_H
diff --git a/src/gui/util/qsystemtrayicon_mac.mm b/src/gui/util/qsystemtrayicon_mac.mm
deleted file mode 100644
index 0ec0b07040..0000000000
--- a/src/gui/util/qsystemtrayicon_mac.mm
+++ /dev/null
@@ -1,578 +0,0 @@
-/****************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-#define QT_MAC_SYSTEMTRAY_USE_GROWL
-
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qsystemtrayicon_p.h>
-#include <qtemporaryfile.h>
-#include <qimagewriter.h>
-#include <qapplication.h>
-#include <qdebug.h>
-#include <qstyle.h>
-
-#include <private/qt_mac_p.h>
-#import <AppKit/AppKit.h>
-
-QT_BEGIN_NAMESPACE
-extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret); //qapplication_mac.cpp
-extern void qtsystray_sendActivated(QSystemTrayIcon *i, int r); //qsystemtrayicon.cpp
-extern NSString *keySequenceToKeyEqivalent(const QKeySequence &accel); // qmenu_mac.mm
-extern NSUInteger keySequenceModifierMask(const QKeySequence &accel); // qmenu_mac.mm
-extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum);
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QNSMenu);
-@class QT_MANGLE_NAMESPACE(QNSImageView);
-
-@interface QT_MANGLE_NAMESPACE(QNSStatusItem) : NSObject {
- NSStatusItem *item;
- QSystemTrayIcon *icon;
- QSystemTrayIconPrivate *iconPrivate;
- QT_MANGLE_NAMESPACE(QNSImageView) *imageCell;
-}
--(id)initWithIcon:(QSystemTrayIcon*)icon iconPrivate:(QSystemTrayIconPrivate *)iprivate;
--(void)dealloc;
--(QSystemTrayIcon*)icon;
--(NSStatusItem*)item;
--(QRectF)geometry;
-- (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton;
-- (void)doubleClickSelector:(id)sender;
-@end
-
-@interface QT_MANGLE_NAMESPACE(QNSImageView) : NSImageView {
- BOOL down;
- QT_MANGLE_NAMESPACE(QNSStatusItem) *parent;
-}
--(id)initWithParent:(QT_MANGLE_NAMESPACE(QNSStatusItem)*)myParent;
--(QSystemTrayIcon*)icon;
--(void)menuTrackingDone:(NSNotification*)notification;
--(void)mousePressed:(NSEvent *)mouseEvent button:(Qt::MouseButton)mouseButton;
-@end
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSMenuDelegate <NSObject>
--(void)menuNeedsUpdate:(NSMenu*)menu;
-@end
-#endif
-
-
-@interface QT_MANGLE_NAMESPACE(QNSMenu) : NSMenu <NSMenuDelegate> {
- QMenu *qmenu;
-}
--(QMenu*)menu;
--(id)initWithQMenu:(QMenu*)qmenu;
--(void)selectedAction:(id)item;
-@end
-
-QT_BEGIN_NAMESPACE
-class QSystemTrayIconSys
-{
-public:
- QSystemTrayIconSys(QSystemTrayIcon *icon, QSystemTrayIconPrivate *d) {
- QMacCocoaAutoReleasePool pool;
- item = [[QT_MANGLE_NAMESPACE(QNSStatusItem) alloc] initWithIcon:icon iconPrivate:d];
- }
- ~QSystemTrayIconSys() {
- QMacCocoaAutoReleasePool pool;
- [[[item item] view] setHidden: YES];
- [item release];
- }
- QT_MANGLE_NAMESPACE(QNSStatusItem) *item;
-};
-
-void QSystemTrayIconPrivate::install_sys()
-{
- Q_Q(QSystemTrayIcon);
- if (!sys) {
- sys = new QSystemTrayIconSys(q, this);
- updateIcon_sys();
- updateMenu_sys();
- updateToolTip_sys();
- }
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
- if(sys) {
- const QRectF geom = [sys->item geometry];
- if(!geom.isNull())
- return geom.toRect();
- }
- return QRect();
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
- delete sys;
- sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
- if(sys && !icon.isNull()) {
- QMacCocoaAutoReleasePool pool;
-#ifndef QT_MAC_USE_COCOA
- const short scale = GetMBarHeight()-4;
-#else
- CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
- const short scale = hgt - 4;
-#endif
- NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(icon.pixmap(QSize(scale, scale))));
- [(NSImageView*)[[sys->item item] view] setImage: nsimage];
- [nsimage release];
- }
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
- if(sys) {
- QMacCocoaAutoReleasePool pool;
- if(menu && !menu->isEmpty()) {
- [[sys->item item] setHighlightMode:YES];
- } else {
- [[sys->item item] setHighlightMode:NO];
- }
- }
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
- if(sys) {
- QMacCocoaAutoReleasePool pool;
- QCFString string(toolTip);
- [[[sys->item item] view] setToolTip:(NSString*)static_cast<CFStringRef>(string)];
- }
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
- return true;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
- return true;
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon, int)
-{
-
- if(sys) {
-#ifdef QT_MAC_SYSTEMTRAY_USE_GROWL
- // Make sure that we have Growl installed on the machine we are running on.
- QCFType<CFURLRef> cfurl;
- OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator,
- CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
- if (status == kLSApplicationNotFoundErr)
- return;
- QCFType<CFBundleRef> bundle = CFBundleCreate(0, cfurl);
-
- if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"),
- kCFCompareCaseInsensitive | kCFCompareBackwards) != kCFCompareEqualTo)
- return;
- QPixmap notificationIconPixmap;
- if(icon == QSystemTrayIcon::Information)
- notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxInformation);
- else if(icon == QSystemTrayIcon::Warning)
- notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxWarning);
- else if(icon == QSystemTrayIcon::Critical)
- notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxCritical);
- QTemporaryFile notificationIconFile;
- QString notificationType(QLatin1String("Notification")), notificationIcon, notificationApp(QApplication::applicationName());
- if(notificationApp.isEmpty())
- notificationApp = QLatin1String("Application");
- if(!notificationIconPixmap.isNull() && notificationIconFile.open()) {
- QImageWriter writer(&notificationIconFile, "PNG");
- if(writer.write(notificationIconPixmap.toImage()))
- notificationIcon = QLatin1String("image from location \"file://") + notificationIconFile.fileName() + QLatin1String("\"");
- }
- const QString script(QLatin1String(
- "tell application \"GrowlHelperApp\"\n"
- "-- Make a list of all the notification types (all)\n"
- "set the allNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
-
- "-- Make a list of the notifications (enabled)\n"
- "set the enabledNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
-
- "-- Register our script with growl.\n"
- "register as application \"") + notificationApp + QLatin1String("\" all notifications allNotificationsList default notifications enabledNotificationsList\n"
-
- "-- Send a Notification...\n") +
- QLatin1String("notify with name \"") + notificationType +
- QLatin1String("\" title \"") + title +
- QLatin1String("\" description \"") + message +
- QLatin1String("\" application name \"") + notificationApp +
- QLatin1String("\" ") + notificationIcon +
- QLatin1String("\nend tell"));
- qt_mac_execute_apple_script(script, 0);
-#elif 0
- Q_Q(QSystemTrayIcon);
- NSView *v = [[sys->item item] view];
- NSWindow *w = [v window];
- w = [[sys->item item] window];
- qDebug() << w << v;
- QPoint p(qRound([w frame].origin.x), qRound([w frame].origin.y));
- qDebug() << p;
- QBalloonTip::showBalloon(icon, message, title, q, QPoint(0, 0), msecs);
-#else
- Q_UNUSED(icon);
- Q_UNUSED(title);
- Q_UNUSED(message);
-#endif
- }
-}
-QT_END_NAMESPACE
-
-@implementation NSStatusItem (Qt)
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSImageView)
--(id)initWithParent:(QT_MANGLE_NAMESPACE(QNSStatusItem)*)myParent {
- self = [super init];
- parent = myParent;
- down = NO;
- return self;
-}
-
--(QSystemTrayIcon*)icon {
- return [parent icon];
-}
-
--(void)menuTrackingDone:(NSNotification*)notification
-{
- Q_UNUSED(notification);
- down = NO;
-
- if( ![self icon]->icon().isNull() ) {
-#ifndef QT_MAC_USE_COCOA
- const short scale = GetMBarHeight()-4;
-#else
- CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
- const short scale = hgt - 4;
-#endif
- NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage([self icon]->icon().pixmap(QSize(scale, scale))));
- [self setImage: nsimage];
- [nsimage release];
- }
-
- if([self icon]->contextMenu())
- [self icon]->contextMenu()->hide();
-
- [self setNeedsDisplay:YES];
-}
-
--(void)mousePressed:(NSEvent *)mouseEvent button:(Qt::MouseButton)mouseButton
-{
- down = YES;
- int clickCount = [mouseEvent clickCount];
- [self setNeedsDisplay:YES];
-
-#ifndef QT_MAC_USE_COCOA
- const short scale = GetMBarHeight()-4;
-#else
- CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
- const short scale = hgt - 4;
-#endif
-
- if (![self icon]->icon().isNull() ) {
- NSImage *nsaltimage = static_cast<NSImage *>(qt_mac_create_nsimage([self icon]->icon().pixmap(QSize(scale, scale), QIcon::Selected)));
- [self setImage: nsaltimage];
- [nsaltimage release];
- }
-
- if ((clickCount == 2)) {
- [self menuTrackingDone:nil];
- [parent doubleClickSelector:self];
- } else {
- [parent triggerSelector:self button:mouseButton];
- }
-}
-
--(void)mouseDown:(NSEvent *)mouseEvent
-{
- [self mousePressed:mouseEvent button:Qt::LeftButton];
-}
-
--(void)mouseUp:(NSEvent *)mouseEvent
-{
- Q_UNUSED(mouseEvent);
- [self menuTrackingDone:nil];
-}
-
-- (void)rightMouseDown:(NSEvent *)mouseEvent
-{
- [self mousePressed:mouseEvent button:Qt::RightButton];
-}
-
--(void)rightMouseUp:(NSEvent *)mouseEvent
-{
- Q_UNUSED(mouseEvent);
- [self menuTrackingDone:nil];
-}
-
-- (void)otherMouseDown:(NSEvent *)mouseEvent
-{
- [self mousePressed:mouseEvent button:cocoaButton2QtButton([mouseEvent buttonNumber])];
-}
-
--(void)otherMouseUp:(NSEvent *)mouseEvent
-{
- Q_UNUSED(mouseEvent);
- [self menuTrackingDone:nil];
-}
-
--(void)drawRect:(NSRect)rect {
- [[parent item] drawStatusBarBackgroundInRect:rect withHighlight:down];
- [super drawRect:rect];
-}
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSStatusItem)
-
--(id)initWithIcon:(QSystemTrayIcon*)i iconPrivate:(QSystemTrayIconPrivate *)iPrivate
-{
- self = [super init];
- if(self) {
- icon = i;
- iconPrivate = iPrivate;
- item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
- imageCell = [[QT_MANGLE_NAMESPACE(QNSImageView) alloc] initWithParent:self];
- [item setView: imageCell];
- }
- return self;
-}
--(void)dealloc {
- [[NSStatusBar systemStatusBar] removeStatusItem:item];
- [imageCell release];
- [item release];
- [super dealloc];
-
-}
-
--(QSystemTrayIcon*)icon {
- return icon;
-}
-
--(NSStatusItem*)item {
- return item;
-}
--(QRectF)geometry {
- if(NSWindow *window = [[item view] window]) {
- NSRect screenRect = [[window screen] frame];
- NSRect windowRect = [window frame];
- return QRectF(windowRect.origin.x, screenRect.size.height-windowRect.origin.y-windowRect.size.height, windowRect.size.width, windowRect.size.height);
- }
- return QRectF();
-}
-
-- (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton {
- Q_UNUSED(sender);
- if (!icon)
- return;
-
- if (mouseButton == Qt::MidButton)
- qtsystray_sendActivated(icon, QSystemTrayIcon::MiddleClick);
- else
- qtsystray_sendActivated(icon, QSystemTrayIcon::Trigger);
-
- if (icon->contextMenu()) {
-#ifndef QT_MAC_USE_COCOA
- [[[self item] view] removeAllToolTips];
- iconPrivate->updateToolTip_sys();
-#endif
- NSMenu *m = [[QT_MANGLE_NAMESPACE(QNSMenu) alloc] initWithQMenu:icon->contextMenu()];
- [m setAutoenablesItems: NO];
- [[NSNotificationCenter defaultCenter] addObserver:imageCell
- selector:@selector(menuTrackingDone:)
- name:NSMenuDidEndTrackingNotification
- object:m];
- [item popUpStatusItemMenu: m];
- [m release];
- }
-}
-
-- (void)doubleClickSelector:(id)sender {
- Q_UNUSED(sender);
- if(!icon)
- return;
- qtsystray_sendActivated(icon, QSystemTrayIcon::DoubleClick);
-}
-
-@end
-
-class QSystemTrayIconQMenu : public QMenu
-{
-public:
- void doAboutToShow() { emit aboutToShow(); }
-private:
- QSystemTrayIconQMenu();
-};
-
-@implementation QT_MANGLE_NAMESPACE(QNSMenu)
--(id)initWithQMenu:(QMenu*)qm {
- self = [super init];
- if(self) {
- self->qmenu = qm;
- [self setDelegate:self];
- }
- return self;
-}
--(QMenu*)menu {
- return qmenu;
-}
--(void)menuNeedsUpdate:(NSMenu*)nsmenu {
- QT_MANGLE_NAMESPACE(QNSMenu) *menu = static_cast<QT_MANGLE_NAMESPACE(QNSMenu) *>(nsmenu);
- emit static_cast<QSystemTrayIconQMenu*>(menu->qmenu)->doAboutToShow();
- for(int i = [menu numberOfItems]-1; i >= 0; --i)
- [menu removeItemAtIndex:i];
- QList<QAction*> actions = menu->qmenu->actions();;
- for(int i = 0; i < actions.size(); ++i) {
- const QAction *action = actions[i];
- if(!action->isVisible())
- continue;
-
- NSMenuItem *item = 0;
- bool needRelease = false;
- if(action->isSeparator()) {
- item = [NSMenuItem separatorItem];
- } else {
- item = [[NSMenuItem alloc] init];
- needRelease = true;
- QString text = action->text();
- QKeySequence accel = action->shortcut();
- {
- int st = text.lastIndexOf(QLatin1Char('\t'));
- if(st != -1) {
- accel = QKeySequence(text.right(text.length()-(st+1)));
- text.remove(st, text.length()-st);
- }
- }
- if(accel.count() > 1)
- text += QLatin1String(" (****)"); //just to denote a multi stroke shortcut
-
- [item setTitle:(NSString*)QCFString::toCFStringRef(qt_mac_removeMnemonics(text))];
- [item setEnabled:menu->qmenu->isEnabled() && action->isEnabled()];
- [item setState:action->isChecked() ? NSOnState : NSOffState];
- [item setToolTip:(NSString*)QCFString::toCFStringRef(action->toolTip())];
- const QIcon icon = action->icon();
- if(!icon.isNull()) {
-#ifndef QT_MAC_USE_COCOA
- const short scale = GetMBarHeight();
-#else
- const short scale = [[NSApp mainMenu] menuBarHeight];
-#endif
- NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(icon.pixmap(QSize(scale, scale))));
- [item setImage: nsimage];
- [nsimage release];
- }
- if(action->menu()) {
- QT_MANGLE_NAMESPACE(QNSMenu) *sub = [[QT_MANGLE_NAMESPACE(QNSMenu) alloc] initWithQMenu:action->menu()];
- [item setSubmenu:sub];
- } else {
- [item setAction:@selector(selectedAction:)];
- [item setTarget:self];
- }
- if(!accel.isEmpty()) {
- [item setKeyEquivalent:keySequenceToKeyEqivalent(accel)];
- [item setKeyEquivalentModifierMask:keySequenceModifierMask(accel)];
- }
- }
- if(item)
- [menu addItem:item];
- if (needRelease)
- [item release];
- }
-}
--(void)selectedAction:(id)a {
- const int activated = [self indexOfItem:a];
- QAction *action = 0;
- QList<QAction*> actions = qmenu->actions();
- for(int i = 0, cnt = 0; i < actions.size(); ++i) {
- if(actions.at(i)->isVisible() && (cnt++) == activated) {
- action = actions.at(i);
- break;
- }
- }
- if(action) {
- action->activate(QAction::Trigger);
- }
-}
-@end
-
diff --git a/src/gui/util/qsystemtrayicon_p.h b/src/gui/util/qsystemtrayicon_p.h
deleted file mode 100644
index cc7bd47092..0000000000
--- a/src/gui/util/qsystemtrayicon_p.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/****************************************************************************
-**
-** 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 QSYSTEMTRAYICON_P_H
-#define QSYSTEMTRAYICON_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of a number of Qt sources files. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qsystemtrayicon.h"
-#include "private/qobject_p.h"
-
-#ifndef QT_NO_SYSTEMTRAYICON
-
-#include "QtGui/qmenu.h"
-#include "QtGui/qpixmap.h"
-#include "QtCore/qstring.h"
-#include "QtCore/qpointer.h"
-
-QT_BEGIN_NAMESPACE
-
-class QSystemTrayIconSys;
-class QToolButton;
-class QLabel;
-
-class QSystemTrayIconPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QSystemTrayIcon)
-
-public:
- QSystemTrayIconPrivate() : sys(0), visible(false) { }
-
- void install_sys();
- void remove_sys();
- void updateIcon_sys();
- void updateToolTip_sys();
- void updateMenu_sys();
- QRect geometry_sys() const;
- void showMessage_sys(const QString &msg, const QString &title, QSystemTrayIcon::MessageIcon icon, int secs);
-
- static bool isSystemTrayAvailable_sys();
- static bool supportsMessages_sys();
-
- QPointer<QMenu> menu;
- QIcon icon;
- QString toolTip;
- QSystemTrayIconSys *sys;
- bool visible;
-};
-
-class QBalloonTip : public QWidget
-{
- Q_OBJECT
-public:
- static void showBalloon(QSystemTrayIcon::MessageIcon icon, const QString& title,
- const QString& msg, QSystemTrayIcon *trayIcon,
- const QPoint& pos, int timeout, bool showArrow = true);
- static void hideBalloon();
- static bool isBalloonVisible();
-
-private:
- QBalloonTip(QSystemTrayIcon::MessageIcon icon, const QString& title,
- const QString& msg, QSystemTrayIcon *trayIcon);
- ~QBalloonTip();
- void balloon(const QPoint&, int, bool);
-
-protected:
- void paintEvent(QPaintEvent *);
- void resizeEvent(QResizeEvent *);
- void mousePressEvent(QMouseEvent *e);
- void timerEvent(QTimerEvent *e);
-
-private:
- QSystemTrayIcon *trayIcon;
- QPixmap pixmap;
- int timerId;
-};
-
-#if defined(Q_WS_X11)
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <QtCore/qcoreapplication.h>
-#include <X11/Xlib.h>
-#include <X11/Xatom.h>
-#include <X11/Xutil.h>
-QT_END_INCLUDE_NAMESPACE
-
-class QSystemTrayIconSys : public QWidget
-{
- friend class QSystemTrayIconPrivate;
-
-public:
- QSystemTrayIconSys(QSystemTrayIcon *q);
- ~QSystemTrayIconSys();
- enum {
- SYSTEM_TRAY_REQUEST_DOCK = 0,
- SYSTEM_TRAY_BEGIN_MESSAGE = 1,
- SYSTEM_TRAY_CANCEL_MESSAGE =2
- };
-
- void addToTray();
- void updateIcon();
- XVisualInfo* getSysTrayVisualInfo();
-
- // QObject::event is public but QWidget's ::event() re-implementation
- // is protected ;(
- inline bool deliverToolTipEvent(QEvent *e)
- { return QWidget::event(e); }
-
- static Window sysTrayWindow;
- static QList<QSystemTrayIconSys *> trayIcons;
- static QCoreApplication::EventFilter oldEventFilter;
- static bool sysTrayTracker(void *message, long *result);
- static Window locateSystemTray();
- static Atom sysTraySelection;
- static XVisualInfo sysTrayVisual;
-
-protected:
- void paintEvent(QPaintEvent *pe);
- void resizeEvent(QResizeEvent *re);
- bool x11Event(XEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseDoubleClickEvent(QMouseEvent *event);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *event);
-#endif
- bool event(QEvent *e);
-
-private:
- QPixmap background;
- QSystemTrayIcon *q;
- Colormap colormap;
-};
-#endif // Q_WS_X11
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SYSTEMTRAYICON
-
-#endif // QSYSTEMTRAYICON_P_H
-
diff --git a/src/gui/util/qsystemtrayicon_qpa.cpp b/src/gui/util/qsystemtrayicon_qpa.cpp
deleted file mode 100644
index 48f8fe8922..0000000000
--- a/src/gui/util/qsystemtrayicon_qpa.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsystemtrayicon_p.h"
-
-#ifndef QT_NO_SYSTEMTRAYICON
-
-QT_BEGIN_NAMESPACE
-
-void QSystemTrayIconPrivate::install_sys()
-{
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
- return QRect();
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
- return false;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
- return false;
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &message,
- const QString &title,
- QSystemTrayIcon::MessageIcon icon,
- int msecs)
-{
- Q_UNUSED(message);
- Q_UNUSED(title);
- Q_UNUSED(icon);
- Q_UNUSED(msecs);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SYSTEMTRAYICON
diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp
deleted file mode 100644
index 5a0e179e6d..0000000000
--- a/src/gui/util/qsystemtrayicon_win.cpp
+++ /dev/null
@@ -1,524 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsystemtrayicon_p.h"
-#ifndef QT_NO_SYSTEMTRAYICON
-
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0600
-#endif
-
-#ifndef _WIN32_IE
-#define _WIN32_IE 0x600
-#endif
-
-#include <qt_windows.h>
-#include <windowsx.h>
-#include <commctrl.h>
-
-#include <private/qsystemlibrary_p.h>
-#include <QApplication>
-#include <QSettings>
-
-QT_BEGIN_NAMESPACE
-
-static const UINT q_uNOTIFYICONID = 0;
-
-static uint MYWM_TASKBARCREATED = 0;
-#define MYWM_NOTIFYICON (WM_APP+101)
-
-struct Q_NOTIFYICONIDENTIFIER {
- DWORD cbSize;
- HWND hWnd;
- UINT uID;
- GUID guidItem;
-};
-
-#ifndef NOTIFYICON_VERSION_4
-#define NOTIFYICON_VERSION_4 4
-#endif
-
-#ifndef NIN_SELECT
-#define NIN_SELECT (WM_USER + 0)
-#endif
-
-#ifndef NIN_KEYSELECT
-#define NIN_KEYSELECT (WM_USER + 1)
-#endif
-
-#ifndef NIN_BALLOONTIMEOUT
-#define NIN_BALLOONTIMEOUT (WM_USER + 4)
-#endif
-
-#ifndef NIN_BALLOONUSERCLICK
-#define NIN_BALLOONUSERCLICK (WM_USER + 5)
-#endif
-
-#ifndef NIF_SHOWTIP
-#define NIF_SHOWTIP 0x00000080
-#endif
-
-#define Q_MSGFLT_ALLOW 1
-
-typedef HRESULT (WINAPI *PtrShell_NotifyIconGetRect)(const Q_NOTIFYICONIDENTIFIER* identifier, RECT* iconLocation);
-typedef BOOL (WINAPI *PtrChangeWindowMessageFilter)(UINT message, DWORD dwFlag);
-typedef BOOL (WINAPI *PtrChangeWindowMessageFilterEx)(HWND hWnd, UINT message, DWORD action, void* pChangeFilterStruct);
-
-class QSystemTrayIconSys : QWidget
-{
-public:
- QSystemTrayIconSys(QSystemTrayIcon *object);
- ~QSystemTrayIconSys();
- bool winEvent( MSG *m, long *result );
- bool trayMessage(DWORD msg);
- void setIconContents(NOTIFYICONDATA &data);
- bool showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs);
- QRect findIconGeometry(const int a_iButtonID);
- void createIcon();
- HICON hIcon;
- QPoint globalPos;
- QSystemTrayIcon *q;
-private:
- uint notifyIconSize;
- int maxTipLength;
- int version;
- bool ignoreNextMouseRelease;
-};
-
-static bool allowsMessages()
-{
-#ifndef QT_NO_SETTINGS
- QSettings settings(QLatin1String("HKEY_CURRENT_USER\\Software\\Microsoft"
- "\\Windows\\CurrentVersion\\Explorer\\Advanced"), QSettings::NativeFormat);
- return settings.value(QLatin1String("EnableBalloonTips"), true).toBool();
-#else
- return false;
-#endif
-}
-
-QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object)
- : hIcon(0), q(object), ignoreNextMouseRelease(false)
-
-{
- if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) {
- notifyIconSize = sizeof(NOTIFYICONDATA);
- version = NOTIFYICON_VERSION_4;
- } else {
- notifyIconSize = NOTIFYICONDATA_V2_SIZE;
- version = NOTIFYICON_VERSION;
- }
-
- maxTipLength = 128;
-
- // For restoring the tray icon after explorer crashes
- if (!MYWM_TASKBARCREATED) {
- MYWM_TASKBARCREATED = RegisterWindowMessage(L"TaskbarCreated");
- }
-
- // Allow the WM_TASKBARCREATED message through the UIPI filter on Windows Vista and higher
- static PtrChangeWindowMessageFilterEx pChangeWindowMessageFilterEx =
- (PtrChangeWindowMessageFilterEx)QSystemLibrary::resolve(QLatin1String("user32"), "ChangeWindowMessageFilterEx");
-
- if (pChangeWindowMessageFilterEx) {
- // Call the safer ChangeWindowMessageFilterEx API if available
- pChangeWindowMessageFilterEx(winId(), MYWM_TASKBARCREATED, Q_MSGFLT_ALLOW, 0);
- } else {
- static PtrChangeWindowMessageFilter pChangeWindowMessageFilter =
- (PtrChangeWindowMessageFilter)QSystemLibrary::resolve(QLatin1String("user32"), "ChangeWindowMessageFilter");
-
- if (pChangeWindowMessageFilter) {
- // Call the deprecated ChangeWindowMessageFilter API otherwise
- pChangeWindowMessageFilter(MYWM_TASKBARCREATED, Q_MSGFLT_ALLOW);
- }
- }
-}
-
-QSystemTrayIconSys::~QSystemTrayIconSys()
-{
- if (hIcon)
- DestroyIcon(hIcon);
-}
-
-void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd)
-{
- tnd.uFlags |= NIF_MESSAGE | NIF_ICON | NIF_TIP;
- tnd.uCallbackMessage = MYWM_NOTIFYICON;
- tnd.hIcon = hIcon;
- QString tip = q->toolTip();
-
- if (!tip.isNull()) {
- tip = tip.left(maxTipLength - 1) + QChar();
- memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t));
- }
-}
-
-static int iconFlag( QSystemTrayIcon::MessageIcon icon )
-{
- switch (icon) {
- case QSystemTrayIcon::Information:
- return NIIF_INFO;
- case QSystemTrayIcon::Warning:
- return NIIF_WARNING;
- case QSystemTrayIcon::Critical:
- return NIIF_ERROR;
- case QSystemTrayIcon::NoIcon:
- return NIIF_NONE;
- default:
- Q_ASSERT_X(false, "QSystemTrayIconSys::showMessage", "Invalid QSystemTrayIcon::MessageIcon value");
- return NIIF_NONE;
- }
-}
-
-bool QSystemTrayIconSys::showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs)
-{
- NOTIFYICONDATA tnd;
- memset(&tnd, 0, notifyIconSize);
-
- memcpy(tnd.szInfo, message.utf16(), qMin(message.length() + 1, 256) * sizeof(wchar_t));
- memcpy(tnd.szInfoTitle, title.utf16(), qMin(title.length() + 1, 64) * sizeof(wchar_t));
-
- tnd.uID = q_uNOTIFYICONID;
- tnd.dwInfoFlags = iconFlag(type);
- tnd.cbSize = notifyIconSize;
- tnd.hWnd = winId();
- tnd.uTimeout = uSecs;
- tnd.uFlags = NIF_INFO | NIF_SHOWTIP;
-
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
- return Shell_NotifyIcon(NIM_MODIFY, &tnd);
-}
-
-bool QSystemTrayIconSys::trayMessage(DWORD msg)
-{
- NOTIFYICONDATA tnd;
- memset(&tnd, 0, notifyIconSize);
-
- tnd.uID = q_uNOTIFYICONID;
- tnd.cbSize = notifyIconSize;
- tnd.hWnd = winId();
- tnd.uFlags = NIF_SHOWTIP;
- tnd.uVersion = version;
-
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
- if (msg == NIM_ADD || msg == NIM_MODIFY) {
- setIconContents(tnd);
- }
-
- bool success = Shell_NotifyIcon(msg, &tnd);
-
- if (msg == NIM_ADD)
- return success && Shell_NotifyIcon(NIM_SETVERSION, &tnd);
- else
- return success;
-}
-
-void QSystemTrayIconSys::createIcon()
-{
- hIcon = 0;
- QIcon icon = q->icon();
- if (icon.isNull())
- return;
-
- const int iconSizeX = GetSystemMetrics(SM_CXSMICON);
- const int iconSizeY = GetSystemMetrics(SM_CYSMICON);
- QSize size = icon.actualSize(QSize(iconSizeX, iconSizeY));
- QPixmap pm = icon.pixmap(size);
- if (pm.isNull())
- return;
-
- hIcon = pm.toWinHICON();
-}
-
-bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
-{
- switch(m->message) {
- case MYWM_NOTIFYICON:
- {
- int message = 0;
- QPoint gpos;
-
- if (version == NOTIFYICON_VERSION_4) {
- Q_ASSERT(q_uNOTIFYICONID == HIWORD(m->lParam));
- message = LOWORD(m->lParam);
- gpos = QPoint(GET_X_LPARAM(m->wParam), GET_Y_LPARAM(m->wParam));
- } else {
- Q_ASSERT(q_uNOTIFYICONID == m->wParam);
- message = m->lParam;
- gpos = QCursor::pos();
- }
-
- switch (message) {
- case NIN_SELECT:
- case NIN_KEYSELECT:
- if (ignoreNextMouseRelease)
- ignoreNextMouseRelease = false;
- else
- emit q->activated(QSystemTrayIcon::Trigger);
- break;
-
- case WM_LBUTTONDBLCLK:
- ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse
- // release we must ignore it
- emit q->activated(QSystemTrayIcon::DoubleClick);
- break;
-
- case WM_CONTEXTMENU:
- if (q->contextMenu()) {
- q->contextMenu()->popup(gpos);
- q->contextMenu()->activateWindow();
- }
- emit q->activated(QSystemTrayIcon::Context);
- break;
-
- case NIN_BALLOONUSERCLICK:
- emit q->messageClicked();
- break;
-
- case WM_MBUTTONUP:
- emit q->activated(QSystemTrayIcon::MiddleClick);
- break;
-
- default:
- break;
- }
- break;
- }
- default:
- if (m->message == MYWM_TASKBARCREATED)
- trayMessage(NIM_ADD);
- else
- return QWidget::winEvent(m, result);
- break;
- }
- return 0;
-}
-
-void QSystemTrayIconPrivate::install_sys()
-{
- Q_Q(QSystemTrayIcon);
- if (!sys) {
- sys = new QSystemTrayIconSys(q);
- sys->createIcon();
- sys->trayMessage(NIM_ADD);
- }
-}
-
-/*
-* This function tries to determine the icon geometry from the tray
-*
-* If it fails an invalid rect is returned.
-*/
-QRect QSystemTrayIconSys::findIconGeometry(const int iconId)
-{
- static PtrShell_NotifyIconGetRect Shell_NotifyIconGetRect =
- (PtrShell_NotifyIconGetRect)QSystemLibrary::resolve(QLatin1String("shell32"), "Shell_NotifyIconGetRect");
-
- if (Shell_NotifyIconGetRect) {
- Q_NOTIFYICONIDENTIFIER nid;
- memset(&nid, 0, sizeof(nid));
- nid.cbSize = sizeof(nid);
- nid.hWnd = winId();
- nid.uID = iconId;
-
- RECT rect;
- HRESULT hr = Shell_NotifyIconGetRect(&nid, &rect);
- if (SUCCEEDED(hr)) {
- return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
- }
- }
-
- QRect ret;
-
- TBBUTTON buttonData;
- DWORD processID = 0;
- HWND trayHandle = FindWindow(L"Shell_TrayWnd", NULL);
-
- //find the toolbar used in the notification area
- if (trayHandle) {
- trayHandle = FindWindowEx(trayHandle, NULL, L"TrayNotifyWnd", NULL);
- if (trayHandle) {
- HWND hwnd = FindWindowEx(trayHandle, NULL, L"SysPager", NULL);
- if (hwnd) {
- hwnd = FindWindowEx(hwnd, NULL, L"ToolbarWindow32", NULL);
- if (hwnd)
- trayHandle = hwnd;
- }
- }
- }
-
- if (!trayHandle)
- return ret;
-
- GetWindowThreadProcessId(trayHandle, &processID);
- if (processID <= 0)
- return ret;
-
- HANDLE trayProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, 0, processID);
- if (!trayProcess)
- return ret;
-
- int buttonCount = SendMessage(trayHandle, TB_BUTTONCOUNT, 0, 0);
- LPVOID data = VirtualAllocEx(trayProcess, NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE);
-
- if ( buttonCount < 1 || !data ) {
- CloseHandle(trayProcess);
- return ret;
- }
-
- //search for our icon among all toolbar buttons
- for (int toolbarButton = 0; toolbarButton < buttonCount; ++toolbarButton ) {
- SIZE_T numBytes = 0;
- DWORD appData[2] = { 0, 0 };
- SendMessage(trayHandle, TB_GETBUTTON, toolbarButton , (LPARAM)data);
-
- if (!ReadProcessMemory(trayProcess, data, &buttonData, sizeof(TBBUTTON), &numBytes))
- continue;
-
- if (!ReadProcessMemory(trayProcess, (LPVOID) buttonData.dwData, appData, sizeof(appData), &numBytes))
- continue;
-
- int currentIconId = appData[1];
- HWND currentIconHandle = (HWND) appData[0];
- bool isHidden = buttonData.fsState & TBSTATE_HIDDEN;
-
- if (currentIconHandle == winId() &&
- currentIconId == iconId && !isHidden) {
- SendMessage(trayHandle, TB_GETITEMRECT, toolbarButton , (LPARAM)data);
- RECT iconRect = {0, 0};
- if(ReadProcessMemory(trayProcess, data, &iconRect, sizeof(RECT), &numBytes)) {
- MapWindowPoints(trayHandle, NULL, (LPPOINT)&iconRect, 2);
- QRect geometry(iconRect.left + 1, iconRect.top + 1,
- iconRect.right - iconRect.left - 2,
- iconRect.bottom - iconRect.top - 2);
- if (geometry.isValid())
- ret = geometry;
- break;
- }
- }
- }
- VirtualFreeEx(trayProcess, data, 0, MEM_RELEASE);
- CloseHandle(trayProcess);
- return ret;
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut)
-{
- if (!sys || !allowsMessages())
- return;
-
- uint uSecs = 0;
- if ( timeOut < 0)
- uSecs = 10000; //10 sec default
- else uSecs = (int)timeOut;
-
- //message is limited to 255 chars + NULL
- QString messageString;
- if (message.isEmpty() && !title.isEmpty())
- messageString = QLatin1Char(' '); //ensures that the message shows when only title is set
- else
- messageString = message.left(255) + QChar();
-
- //title is limited to 63 chars + NULL
- QString titleString = title.left(63) + QChar();
-
- sys->showMessage(titleString, messageString, type, uSecs);
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
- if (!sys)
- return QRect();
-
- return sys->findIconGeometry(q_uNOTIFYICONID);
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
- if (!sys)
- return;
-
- sys->trayMessage(NIM_DELETE);
- delete sys;
- sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
- if (!sys)
- return;
-
- HICON hIconToDestroy = sys->hIcon;
-
- sys->createIcon();
- sys->trayMessage(NIM_MODIFY);
-
- if (hIconToDestroy)
- DestroyIcon(hIconToDestroy);
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
- if (!sys)
- return;
-
- sys->trayMessage(NIM_MODIFY);
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
- return true;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
- return allowsMessages();
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/util/qsystemtrayicon_wince.cpp b/src/gui/util/qsystemtrayicon_wince.cpp
deleted file mode 100644
index 85a34bbe25..0000000000
--- a/src/gui/util/qsystemtrayicon_wince.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsystemtrayicon_p.h"
-#ifndef QT_NO_SYSTEMTRAYICON
-#define _WIN32_IE 0x0600 //required for NOTIFYICONDATA_V2_SIZE
-
-#include <qt_windows.h>
-#include <shlwapi.h>
-#include <QApplication>
-
-QT_BEGIN_NAMESPACE
-
-static const UINT q_uNOTIFYICONID = 13; // IDs from 0 to 12 are reserved on WinCE.
-#define MYWM_NOTIFYICON (WM_APP+101)
-
-struct Q_NOTIFYICONIDENTIFIER {
- DWORD cbSize;
- HWND hWnd;
- UINT uID;
- GUID guidItem;
-};
-
-class QSystemTrayIconSys : QWidget
-{
-public:
- QSystemTrayIconSys(QSystemTrayIcon *object);
- ~QSystemTrayIconSys();
- bool winEvent( MSG *m, long *result );
- bool trayMessage(DWORD msg);
- void setIconContents(NOTIFYICONDATA &data);
- void createIcon();
- QRect findTrayGeometry();
- HICON hIcon;
- QPoint globalPos;
- QSystemTrayIcon *q;
-private:
- uint notifyIconSize;
- int maxTipLength;
- bool ignoreNextMouseRelease;
-};
-
-QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object)
- : hIcon(0), q(object), ignoreNextMouseRelease(false)
-
-{
- notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, szTip[64]); // NOTIFYICONDATAW_V1_SIZE;
- maxTipLength = 64;
-}
-
-QSystemTrayIconSys::~QSystemTrayIconSys()
-{
- if (hIcon)
- DestroyIcon(hIcon);
-}
-
-QRect QSystemTrayIconSys::findTrayGeometry()
-{
- // Use lower right corner as fallback
- QPoint brCorner = qApp->desktop()->screenGeometry().bottomRight();
- QRect ret(brCorner.x() - 10, brCorner.y() - 10, 10, 10);
- return ret;
-}
-
-void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd)
-{
- tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
- tnd.uCallbackMessage = MYWM_NOTIFYICON;
- tnd.hIcon = hIcon;
- QString tip = q->toolTip();
-
- if (!tip.isNull()) {
- tip = tip.left(maxTipLength - 1) + QChar();
- memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t));
- }
-}
-
-bool QSystemTrayIconSys::trayMessage(DWORD msg)
-{
- NOTIFYICONDATA tnd;
- memset(&tnd, 0, notifyIconSize);
- tnd.uID = q_uNOTIFYICONID;
- tnd.cbSize = notifyIconSize;
- tnd.hWnd = winId();
-
- Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
- if (msg != NIM_DELETE) {
- setIconContents(tnd);
- }
-
- return Shell_NotifyIcon(msg, &tnd);
-}
-
-void QSystemTrayIconSys::createIcon()
-{
- hIcon = 0;
- QIcon icon = q->icon();
- if (icon.isNull())
- return;
-
- //const QSize preferredSize(GetSystemMetrics(SM_CXSMICON) * 2, GetSystemMetrics(SM_CYSMICON) * 2);
- const QSize preferredSize(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
- QPixmap pm = icon.pixmap(preferredSize);
- if (pm.isNull())
- return;
-
- hIcon = pm.toWinHICON();
-}
-
-bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
-{
- switch(m->message) {
- case WM_CREATE:
- SetWindowLong(winId(), GWL_USERDATA, (LONG)((CREATESTRUCTW*)m->lParam)->lpCreateParams);
- break;
-
- case MYWM_NOTIFYICON:
- {
- QPoint gpos = QCursor::pos();
-
- switch (m->lParam) {
- case WM_LBUTTONUP:
- if (ignoreNextMouseRelease)
- ignoreNextMouseRelease = false;
- else
- emit q->activated(QSystemTrayIcon::Trigger);
- break;
-
- case WM_LBUTTONDBLCLK:
- ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse
- // release we must ignore it
- emit q->activated(QSystemTrayIcon::DoubleClick);
- break;
-
- case WM_RBUTTONUP:
- if (q->contextMenu()) {
- q->contextMenu()->popup(gpos);
-
- // We must ensure that the popup menu doesn't show up behind the task bar.
- QRect desktopRect = qApp->desktop()->availableGeometry();
- int maxY = desktopRect.y() + desktopRect.height() - q->contextMenu()->height();
- if (gpos.y() > maxY) {
- gpos.ry() = maxY;
- q->contextMenu()->move(gpos);
- }
- }
- emit q->activated(QSystemTrayIcon::Context);
- break;
-
- case WM_MBUTTONUP:
- emit q->activated(QSystemTrayIcon::MiddleClick);
- break;
-
- default:
- break;
- }
- break;
- }
- default:
- return QWidget::winEvent(m, result);
- }
- return 0;
-}
-
-void QSystemTrayIconPrivate::install_sys()
-{
- Q_Q(QSystemTrayIcon);
- if (!sys) {
- sys = new QSystemTrayIconSys(q);
- sys->createIcon();
- sys->trayMessage(NIM_ADD);
- }
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut)
-{
- if (!sys)
- return;
-
- uint uSecs = 0;
- if ( timeOut < 0)
- uSecs = 10000; //10 sec default
- else uSecs = (int)timeOut;
-
- //message is limited to 255 chars + NULL
- QString messageString;
- if (message.isEmpty() && !title.isEmpty())
- messageString = QLatin1Char(' '); //ensures that the message shows when only title is set
- else
- messageString = message.left(255) + QChar();
-
- //title is limited to 63 chars + NULL
- QString titleString = title.left(63) + QChar();
-
- //show QBalloonTip
- QRect trayRect = sys->findTrayGeometry();
- QBalloonTip::showBalloon(type, title, message, sys->q, QPoint(trayRect.left(),
- trayRect.center().y()), uSecs, false);
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
- return QRect();
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
- if (!sys)
- return;
-
- sys->trayMessage(NIM_DELETE);
- delete sys;
- sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
- if (!sys)
- return;
-
- HICON hIconToDestroy = sys->hIcon;
-
- sys->createIcon();
- sys->trayMessage(NIM_MODIFY);
-
- if (hIconToDestroy)
- DestroyIcon(hIconToDestroy);
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
- // Calling sys->trayMessage(NIM_MODIFY) on an existing icon is broken on Windows CE.
- // So we need to call updateIcon_sys() which creates a new icon handle.
- updateIcon_sys();
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
- return true;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
- return true;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/util/qsystemtrayicon_x11.cpp b/src/gui/util/qsystemtrayicon_x11.cpp
deleted file mode 100644
index 694746c834..0000000000
--- a/src/gui/util/qsystemtrayicon_x11.cpp
+++ /dev/null
@@ -1,401 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qt_x11_p.h"
-#include "qlabel.h"
-#include "qx11info_x11.h"
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qbitmap.h"
-#include "qevent.h"
-#include "qapplication.h"
-#include "qlist.h"
-#include "qmenu.h"
-#include "qtimer.h"
-#include "qsystemtrayicon_p.h"
-#include "qpaintengine.h"
-
-#ifndef QT_NO_SYSTEMTRAYICON
-QT_BEGIN_NAMESPACE
-
-Window QSystemTrayIconSys::sysTrayWindow = XNone;
-QList<QSystemTrayIconSys *> QSystemTrayIconSys::trayIcons;
-QCoreApplication::EventFilter QSystemTrayIconSys::oldEventFilter = 0;
-Atom QSystemTrayIconSys::sysTraySelection = XNone;
-XVisualInfo QSystemTrayIconSys::sysTrayVisual = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-
-// Locate the system tray
-Window QSystemTrayIconSys::locateSystemTray()
-{
- Display *display = QX11Info::display();
- if (sysTraySelection == XNone) {
- int screen = QX11Info::appScreen();
- QString net_sys_tray = QString::fromLatin1("_NET_SYSTEM_TRAY_S%1").arg(screen);
- sysTraySelection = XInternAtom(display, net_sys_tray.toLatin1(), False);
- }
-
- return XGetSelectionOwner(QX11Info::display(), sysTraySelection);
-}
-
-XVisualInfo* QSystemTrayIconSys::getSysTrayVisualInfo()
-{
- Display *display = QX11Info::display();
-
- if (!sysTrayVisual.visual) {
- Window win = locateSystemTray();
- if (win != XNone) {
- Atom actual_type;
- int actual_format;
- ulong nitems, bytes_remaining;
- uchar *data = 0;
- int result = XGetWindowProperty(display, win, ATOM(_NET_SYSTEM_TRAY_VISUAL), 0, 1,
- False, XA_VISUALID, &actual_type,
- &actual_format, &nitems, &bytes_remaining, &data);
- VisualID vid = 0;
- if (result == Success && data && actual_type == XA_VISUALID && actual_format == 32 &&
- nitems == 1 && bytes_remaining == 0)
- vid = *(VisualID*)data;
- if (data)
- XFree(data);
- if (vid == 0)
- return 0;
-
- uint mask = VisualIDMask;
- XVisualInfo *vi, rvi;
- int count;
- rvi.visualid = vid;
- vi = XGetVisualInfo(display, mask, &rvi, &count);
- if (vi) {
- sysTrayVisual = vi[0];
- XFree((char*)vi);
- }
- if (sysTrayVisual.depth != 32)
- memset(&sysTrayVisual, 0, sizeof(sysTrayVisual));
- }
- }
-
- return sysTrayVisual.visual ? &sysTrayVisual : 0;
-}
-
-bool QSystemTrayIconSys::sysTrayTracker(void *message, long *result)
-{
- bool retval = false;
- if (QSystemTrayIconSys::oldEventFilter)
- retval = QSystemTrayIconSys::oldEventFilter(message, result);
-
- if (trayIcons.isEmpty())
- return retval;
-
- Display *display = QX11Info::display();
- XEvent *ev = (XEvent *)message;
- if (ev->type == DestroyNotify && ev->xany.window == sysTrayWindow) {
- sysTrayWindow = locateSystemTray();
- memset(&sysTrayVisual, 0, sizeof(sysTrayVisual));
- for (int i = 0; i < trayIcons.count(); i++) {
- if (sysTrayWindow == XNone) {
- QBalloonTip::hideBalloon();
- trayIcons[i]->hide(); // still no luck
- trayIcons[i]->destroy();
- trayIcons[i]->create();
- } else
- trayIcons[i]->addToTray(); // add it to the new tray
- }
- retval = true;
- } else if (ev->type == ClientMessage && sysTrayWindow == XNone) {
- static Atom manager_atom = XInternAtom(display, "MANAGER", False);
- XClientMessageEvent *cm = (XClientMessageEvent *)message;
- if ((cm->message_type == manager_atom) && ((Atom)cm->data.l[1] == sysTraySelection)) {
- sysTrayWindow = cm->data.l[2];
- memset(&sysTrayVisual, 0, sizeof(sysTrayVisual));
- XSelectInput(display, sysTrayWindow, StructureNotifyMask);
- for (int i = 0; i < trayIcons.count(); i++) {
- trayIcons[i]->addToTray();
- }
- retval = true;
- }
- } else if (ev->type == PropertyNotify && ev->xproperty.atom == ATOM(_NET_SYSTEM_TRAY_VISUAL) &&
- ev->xproperty.window == sysTrayWindow) {
- memset(&sysTrayVisual, 0, sizeof(sysTrayVisual));
- for (int i = 0; i < trayIcons.count(); i++) {
- trayIcons[i]->addToTray();
- }
- }
-
- return retval;
-}
-
-QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *q)
- : QWidget(0, Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint),
- q(q), colormap(0)
-{
- setAttribute(Qt::WA_AlwaysShowToolTips);
- setAttribute(Qt::WA_QuitOnClose, false);
- setAttribute(Qt::WA_NoSystemBackground, true);
- setAttribute(Qt::WA_PaintOnScreen);
-
- static bool eventFilterAdded = false;
- Display *display = QX11Info::display();
- if (!eventFilterAdded) {
- oldEventFilter = qApp->setEventFilter(sysTrayTracker);
- eventFilterAdded = true;
- Window root = QX11Info::appRootWindow();
- XWindowAttributes attr;
- XGetWindowAttributes(display, root, &attr);
- if ((attr.your_event_mask & StructureNotifyMask) != StructureNotifyMask) {
- (void) QApplication::desktop(); // lame trick to ensure our event mask is not overridden
- XSelectInput(display, root, attr.your_event_mask | StructureNotifyMask); // for MANAGER selection
- }
- }
- if (trayIcons.isEmpty()) {
- sysTrayWindow = locateSystemTray();
- if (sysTrayWindow != XNone)
- XSelectInput(display, sysTrayWindow, StructureNotifyMask); // track tray events
- }
- trayIcons.append(this);
- setMouseTracking(true);
-#ifndef QT_NO_TOOLTIP
- setToolTip(q->toolTip());
-#endif
- if (sysTrayWindow != XNone)
- addToTray();
-}
-
-QSystemTrayIconSys::~QSystemTrayIconSys()
-{
- trayIcons.removeAt(trayIcons.indexOf(this));
- Display *display = QX11Info::display();
- if (trayIcons.isEmpty()) {
- if (sysTrayWindow == XNone)
- return;
- if (display)
- XSelectInput(display, sysTrayWindow, 0); // stop tracking the tray
- sysTrayWindow = XNone;
- }
- if (colormap)
- XFreeColormap(display, colormap);
-}
-
-void QSystemTrayIconSys::addToTray()
-{
- Q_ASSERT(sysTrayWindow != XNone);
- Display *display = QX11Info::display();
-
- XVisualInfo *vi = getSysTrayVisualInfo();
- if (vi && vi->visual) {
- Window root = RootWindow(display, vi->screen);
- Window p = root;
- if (QWidget *pw = parentWidget())
- p = pw->effectiveWinId();
- colormap = XCreateColormap(display, root, vi->visual, AllocNone);
- XSetWindowAttributes wsa;
- wsa.background_pixmap = 0;
- wsa.colormap = colormap;
- wsa.background_pixel = 0;
- wsa.border_pixel = 0;
- Window wid = XCreateWindow(display, p, -1, -1, 1, 1,
- 0, vi->depth, InputOutput, vi->visual,
- CWBackPixmap|CWBackPixel|CWBorderPixel|CWColormap, &wsa);
- create(wid);
- } else {
- XSetWindowBackgroundPixmap(display, winId(), ParentRelative);
- }
-
- // GNOME, NET WM Specification
- static Atom netwm_tray_atom = XInternAtom(display, "_NET_SYSTEM_TRAY_OPCODE", False);
- long l[5] = { CurrentTime, SYSTEM_TRAY_REQUEST_DOCK, winId(), 0, 0 };
- XEvent ev;
- memset(&ev, 0, sizeof(ev));
- ev.xclient.type = ClientMessage;
- ev.xclient.window = sysTrayWindow;
- ev.xclient.message_type = netwm_tray_atom;
- ev.xclient.format = 32;
- memcpy((char *)&ev.xclient.data, (const char *) l, sizeof(l));
- XSendEvent(display, sysTrayWindow, False, 0, &ev);
- setMinimumSize(22, 22); // required at least on GNOME
-}
-
-void QSystemTrayIconSys::updateIcon()
-{
- update();
-}
-
-void QSystemTrayIconSys::resizeEvent(QResizeEvent *re)
-{
- QWidget::resizeEvent(re);
- updateIcon();
-}
-
-void QSystemTrayIconSys::paintEvent(QPaintEvent*)
-{
- QPainter p(this);
- if (!getSysTrayVisualInfo()) {
- const QRegion oldSystemClip = p.paintEngine()->systemClip();
- const QRect clearedRect = oldSystemClip.boundingRect();
- XClearArea(QX11Info::display(), winId(), clearedRect.x(), clearedRect.y(),
- clearedRect.width(), clearedRect.height(), False);
- QPaintEngine *pe = p.paintEngine();
- pe->setSystemClip(clearedRect);
- q->icon().paint(&p, rect());
- pe->setSystemClip(oldSystemClip);
- } else {
- p.setCompositionMode(QPainter::CompositionMode_Source);
- p.fillRect(rect(), Qt::transparent);
- p.setCompositionMode(QPainter::CompositionMode_SourceOver);
- q->icon().paint(&p, rect());
- }
-}
-
-void QSystemTrayIconSys::mousePressEvent(QMouseEvent *ev)
-{
- QPoint globalPos = ev->globalPos();
- if (ev->button() == Qt::RightButton && q->contextMenu())
- q->contextMenu()->popup(globalPos);
-
- if (QBalloonTip::isBalloonVisible()) {
- emit q->messageClicked();
- QBalloonTip::hideBalloon();
- }
-
- if (ev->button() == Qt::LeftButton)
- emit q->activated(QSystemTrayIcon::Trigger);
- else if (ev->button() == Qt::RightButton)
- emit q->activated(QSystemTrayIcon::Context);
- else if (ev->button() == Qt::MidButton)
- emit q->activated(QSystemTrayIcon::MiddleClick);
-}
-
-void QSystemTrayIconSys::mouseDoubleClickEvent(QMouseEvent *ev)
-{
- if (ev->button() == Qt::LeftButton)
- emit q->activated(QSystemTrayIcon::DoubleClick);
-}
-
-#ifndef QT_NO_WHEELEVENT
-void QSystemTrayIconSys::wheelEvent(QWheelEvent *e)
-{
- QApplication::sendEvent(q, e);
-}
-#endif
-
-bool QSystemTrayIconSys::event(QEvent *e)
-{
- if (e->type() == QEvent::ToolTip) {
- return QApplication::sendEvent(q, e);
- }
- return QWidget::event(e);
-}
-
-bool QSystemTrayIconSys::x11Event(XEvent *event)
-{
- if (event->type == ReparentNotify)
- show();
- return QWidget::x11Event(event);
-}
-
-////////////////////////////////////////////////////////////////////////////
-void QSystemTrayIconPrivate::install_sys()
-{
- Q_Q(QSystemTrayIcon);
- if (!sys)
- sys = new QSystemTrayIconSys(q);
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
- if (!sys)
- return QRect();
- return QRect(sys->mapToGlobal(QPoint(0, 0)), sys->size());
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
- if (!sys)
- return;
- QBalloonTip::hideBalloon();
- sys->hide(); // this should do the trick, but...
- delete sys; // wm may resize system tray only for DestroyEvents
- sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
- if (!sys)
- return;
- sys->updateIcon();
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
- if (!sys)
- return;
-#ifndef QT_NO_TOOLTIP
- sys->setToolTip(toolTip);
-#endif
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
- return QSystemTrayIconSys::locateSystemTray() != XNone;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
- return true;
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &message, const QString &title,
- QSystemTrayIcon::MessageIcon icon, int msecs)
-{
- if (!sys)
- return;
- QPoint g = sys->mapToGlobal(QPoint(0, 0));
- QBalloonTip::showBalloon(icon, message, title, sys->q,
- QPoint(g.x() + sys->width()/2, g.y() + sys->height()/2),
- msecs);
-}
-
-QT_END_NAMESPACE
-#endif //QT_NO_SYSTEMTRAYICON
diff --git a/src/gui/util/qundogroup.cpp b/src/gui/util/qundogroup.cpp
deleted file mode 100644
index 42cda7462a..0000000000
--- a/src/gui/util/qundogroup.cpp
+++ /dev/null
@@ -1,499 +0,0 @@
-/****************************************************************************
-**
-** 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 "qundogroup.h"
-#include "qundostack.h"
-#include "qundostack_p.h"
-
-#ifndef QT_NO_UNDOGROUP
-
-QT_BEGIN_NAMESPACE
-
-class QUndoGroupPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QUndoGroup)
-public:
- QUndoGroupPrivate() : active(0) {}
-
- QUndoStack *active;
- QList<QUndoStack*> stack_list;
-};
-
-/*!
- \class QUndoGroup
- \brief The QUndoGroup class is a group of QUndoStack objects.
- \since 4.2
-
- For an overview of the Qt's undo framework, see the
- \link qundo.html overview\endlink.
-
- An application often has multiple undo stacks, one for each opened document. At the
- same time, an application usually has one undo action and one redo action, which
- triggers undo or redo in the active document.
-
- QUndoGroup is a group of QUndoStack objects, one of which may be active. It has
- an undo() and redo() slot, which calls QUndoStack::undo() and QUndoStack::redo()
- for the active stack. It also has the functions createUndoAction() and createRedoAction().
- The actions returned by these functions behave in the same way as those returned by
- QUndoStack::createUndoAction() and QUndoStack::createRedoAction() of the active
- stack.
-
- Stacks are added to a group with addStack() and removed with removeStack(). A stack
- is implicitly added to a group when it is created with the group as its parent
- QObject.
-
- It is the programmer's responsibility to specify which stack is active by
- calling QUndoStack::setActive(), usually when the associated document window receives focus.
- The active stack may also be set with setActiveStack(), and is returned by activeStack().
-
- When a stack is added to a group using addStack(), the group does not take ownership
- of the stack. This means the stack has to be deleted separately from the group. When
- a stack is deleted, it is automatically removed from a group. A stack may belong to
- only one group. Adding it to another group will cause it to be removed from the previous
- group.
-
- A QUndoGroup is also useful in conjunction with QUndoView. If a QUndoView is
- set to watch a group using QUndoView::setGroup(), it will update itself to display
- the active stack.
-*/
-
-/*!
- Creates an empty QUndoGroup object with parent \a parent.
-
- \sa addStack()
-*/
-
-QUndoGroup::QUndoGroup(QObject *parent)
- : QObject(*new QUndoGroupPrivate(), parent)
-{
-}
-
-/*!
- Destroys the QUndoGroup.
-*/
-QUndoGroup::~QUndoGroup()
-{
- // Ensure all QUndoStacks no longer refer to this group.
- Q_D(QUndoGroup);
- QList<QUndoStack *>::iterator it = d->stack_list.begin();
- QList<QUndoStack *>::iterator end = d->stack_list.end();
- while (it != end) {
- (*it)->d_func()->group = 0;
- ++it;
- }
-}
-
-/*!
- Adds \a stack to this group. The group does not take ownership of the stack. Another
- way of adding a stack to a group is by specifying the group as the stack's parent
- QObject in QUndoStack::QUndoStack(). In this case, the stack is deleted when the
- group is deleted, in the usual manner of QObjects.
-
- \sa removeStack() stacks() QUndoStack::QUndoStack()
-*/
-
-void QUndoGroup::addStack(QUndoStack *stack)
-{
- Q_D(QUndoGroup);
-
- if (d->stack_list.contains(stack))
- return;
- d->stack_list.append(stack);
-
- if (QUndoGroup *other = stack->d_func()->group)
- other->removeStack(stack);
- stack->d_func()->group = this;
-}
-
-/*!
- Removes \a stack from this group. If the stack was the active stack in the group,
- the active stack becomes 0.
-
- \sa addStack() stacks() QUndoStack::~QUndoStack()
-*/
-
-void QUndoGroup::removeStack(QUndoStack *stack)
-{
- Q_D(QUndoGroup);
-
- if (d->stack_list.removeAll(stack) == 0)
- return;
- if (stack == d->active)
- setActiveStack(0);
- stack->d_func()->group = 0;
-}
-
-/*!
- Returns a list of stacks in this group.
-
- \sa addStack() removeStack()
-*/
-
-QList<QUndoStack*> QUndoGroup::stacks() const
-{
- Q_D(const QUndoGroup);
- return d->stack_list;
-}
-
-/*!
- Sets the active stack of this group to \a stack.
-
- If the stack is not a member of this group, this function does nothing.
-
- Synonymous with calling QUndoStack::setActive() on \a stack.
-
- The actions returned by createUndoAction() and createRedoAction() will now behave
- in the same way as those returned by \a stack's QUndoStack::createUndoAction()
- and QUndoStack::createRedoAction().
-
- \sa QUndoStack::setActive() activeStack()
-*/
-
-void QUndoGroup::setActiveStack(QUndoStack *stack)
-{
- Q_D(QUndoGroup);
- if (d->active == stack)
- return;
-
- if (d->active != 0) {
- disconnect(d->active, SIGNAL(canUndoChanged(bool)),
- this, SIGNAL(canUndoChanged(bool)));
- disconnect(d->active, SIGNAL(undoTextChanged(QString)),
- this, SIGNAL(undoTextChanged(QString)));
- disconnect(d->active, SIGNAL(canRedoChanged(bool)),
- this, SIGNAL(canRedoChanged(bool)));
- disconnect(d->active, SIGNAL(redoTextChanged(QString)),
- this, SIGNAL(redoTextChanged(QString)));
- disconnect(d->active, SIGNAL(indexChanged(int)),
- this, SIGNAL(indexChanged(int)));
- disconnect(d->active, SIGNAL(cleanChanged(bool)),
- this, SIGNAL(cleanChanged(bool)));
- }
-
- d->active = stack;
-
- if (d->active == 0) {
- emit canUndoChanged(false);
- emit undoTextChanged(QString());
- emit canRedoChanged(false);
- emit redoTextChanged(QString());
- emit cleanChanged(true);
- emit indexChanged(0);
- } else {
- connect(d->active, SIGNAL(canUndoChanged(bool)),
- this, SIGNAL(canUndoChanged(bool)));
- connect(d->active, SIGNAL(undoTextChanged(QString)),
- this, SIGNAL(undoTextChanged(QString)));
- connect(d->active, SIGNAL(canRedoChanged(bool)),
- this, SIGNAL(canRedoChanged(bool)));
- connect(d->active, SIGNAL(redoTextChanged(QString)),
- this, SIGNAL(redoTextChanged(QString)));
- connect(d->active, SIGNAL(indexChanged(int)),
- this, SIGNAL(indexChanged(int)));
- connect(d->active, SIGNAL(cleanChanged(bool)),
- this, SIGNAL(cleanChanged(bool)));
- emit canUndoChanged(d->active->canUndo());
- emit undoTextChanged(d->active->undoText());
- emit canRedoChanged(d->active->canRedo());
- emit redoTextChanged(d->active->redoText());
- emit cleanChanged(d->active->isClean());
- emit indexChanged(d->active->index());
- }
-
- emit activeStackChanged(d->active);
-}
-
-/*!
- Returns the active stack of this group.
-
- If none of the stacks are active, or if the group is empty, this function
- returns 0.
-
- \sa setActiveStack() QUndoStack::setActive()
-*/
-
-QUndoStack *QUndoGroup::activeStack() const
-{
- Q_D(const QUndoGroup);
- return d->active;
-}
-
-/*!
- Calls QUndoStack::undo() on the active stack.
-
- If none of the stacks are active, or if the group is empty, this function
- does nothing.
-
- \sa redo() canUndo() setActiveStack()
-*/
-
-void QUndoGroup::undo()
-{
- Q_D(QUndoGroup);
- if (d->active != 0)
- d->active->undo();
-}
-
-/*!
- Calls QUndoStack::redo() on the active stack.
-
- If none of the stacks are active, or if the group is empty, this function
- does nothing.
-
- \sa undo() canRedo() setActiveStack()
-*/
-
-
-void QUndoGroup::redo()
-{
- Q_D(QUndoGroup);
- if (d->active != 0)
- d->active->redo();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::canUndo().
-
- If none of the stacks are active, or if the group is empty, this function
- returns false.
-
- \sa canRedo() setActiveStack()
-*/
-
-bool QUndoGroup::canUndo() const
-{
- Q_D(const QUndoGroup);
- return d->active != 0 && d->active->canUndo();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::canRedo().
-
- If none of the stacks are active, or if the group is empty, this function
- returns false.
-
- \sa canUndo() setActiveStack()
-*/
-
-bool QUndoGroup::canRedo() const
-{
- Q_D(const QUndoGroup);
- return d->active != 0 && d->active->canRedo();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::undoText().
-
- If none of the stacks are active, or if the group is empty, this function
- returns an empty string.
-
- \sa redoText() setActiveStack()
-*/
-
-QString QUndoGroup::undoText() const
-{
- Q_D(const QUndoGroup);
- return d->active == 0 ? QString() : d->active->undoText();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::redoText().
-
- If none of the stacks are active, or if the group is empty, this function
- returns an empty string.
-
- \sa undoText() setActiveStack()
-*/
-
-QString QUndoGroup::redoText() const
-{
- Q_D(const QUndoGroup);
- return d->active == 0 ? QString() : d->active->redoText();
-}
-
-/*!
- Returns the value of the active stack's QUndoStack::isClean().
-
- If none of the stacks are active, or if the group is empty, this function
- returns true.
-
- \sa setActiveStack()
-*/
-
-bool QUndoGroup::isClean() const
-{
- Q_D(const QUndoGroup);
- return d->active == 0 || d->active->isClean();
-}
-
-#ifndef QT_NO_ACTION
-
-/*!
- Creates an undo QAction object with parent \a parent.
-
- Triggering this action will cause a call to QUndoStack::undo() on the active stack.
- The text of this action will always be the text of the command which will be undone
- in the next call to undo(), prefixed by \a prefix. If there is no command available
- for undo, if the group is empty or if none of the stacks are active, this action will
- be disabled.
-
- If \a prefix is empty, the default prefix "Undo" is used.
-
- \sa createRedoAction() canUndo() QUndoCommand::text()
-*/
-
-QAction *QUndoGroup::createUndoAction(QObject *parent, const QString &prefix) const
-{
- QString pref = prefix.isEmpty() ? tr("Undo") : prefix;
- QUndoAction *result = new QUndoAction(pref, parent);
- result->setEnabled(canUndo());
- result->setPrefixedText(undoText());
- connect(this, SIGNAL(canUndoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(undoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(undo()));
- return result;
-}
-
-/*!
- Creates an redo QAction object with parent \a parent.
-
- Triggering this action will cause a call to QUndoStack::redo() on the active stack.
- The text of this action will always be the text of the command which will be redone
- in the next call to redo(), prefixed by \a prefix. If there is no command available
- for redo, if the group is empty or if none of the stacks are active, this action will
- be disabled.
-
- If \a prefix is empty, the default prefix "Undo" is used.
-
- \sa createUndoAction() canRedo() QUndoCommand::text()
-*/
-
-QAction *QUndoGroup::createRedoAction(QObject *parent, const QString &prefix) const
-{
- QString pref = prefix.isEmpty() ? tr("Redo") : prefix;
- QUndoAction *result = new QUndoAction(pref, parent);
- result->setEnabled(canRedo());
- result->setPrefixedText(redoText());
- connect(this, SIGNAL(canRedoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(redoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(redo()));
- return result;
-}
-
-#endif // QT_NO_ACTION
-
-/*! \fn void QUndoGroup::activeStackChanged(QUndoStack *stack)
-
- This signal is emitted whenever the active stack of the group changes. This can happen
- when setActiveStack() or QUndoStack::setActive() is called, or when the active stack
- is removed form the group. \a stack is the new active stack. If no stack is active,
- \a stack is 0.
-
- \sa setActiveStack() QUndoStack::setActive()
-*/
-
-/*! \fn void QUndoGroup::indexChanged(int idx)
-
- This signal is emitted whenever the active stack emits QUndoStack::indexChanged()
- or the active stack changes.
-
- \a idx is the new current index, or 0 if the active stack is 0.
-
- \sa QUndoStack::indexChanged() setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::cleanChanged(bool clean)
-
- This signal is emitted whenever the active stack emits QUndoStack::cleanChanged()
- or the active stack changes.
-
- \a clean is the new state, or true if the active stack is 0.
-
- \sa QUndoStack::cleanChanged() setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::canUndoChanged(bool canUndo)
-
- This signal is emitted whenever the active stack emits QUndoStack::canUndoChanged()
- or the active stack changes.
-
- \a canUndo is the new state, or false if the active stack is 0.
-
- \sa QUndoStack::canUndoChanged() setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::canRedoChanged(bool canRedo)
-
- This signal is emitted whenever the active stack emits QUndoStack::canRedoChanged()
- or the active stack changes.
-
- \a canRedo is the new state, or false if the active stack is 0.
-
- \sa QUndoStack::canRedoChanged() setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::undoTextChanged(const QString &undoText)
-
- This signal is emitted whenever the active stack emits QUndoStack::undoTextChanged()
- or the active stack changes.
-
- \a undoText is the new state, or an empty string if the active stack is 0.
-
- \sa QUndoStack::undoTextChanged() setActiveStack()
-*/
-
-/*! \fn void QUndoGroup::redoTextChanged(const QString &redoText)
-
- This signal is emitted whenever the active stack emits QUndoStack::redoTextChanged()
- or the active stack changes.
-
- \a redoText is the new state, or an empty string if the active stack is 0.
-
- \sa QUndoStack::redoTextChanged() setActiveStack()
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_UNDOGROUP
diff --git a/src/gui/util/qundogroup.h b/src/gui/util/qundogroup.h
deleted file mode 100644
index 4ed79a9c81..0000000000
--- a/src/gui/util/qundogroup.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** 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 QUNDOGROUP_H
-#define QUNDOGROUP_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QUndoGroupPrivate;
-class QUndoStack;
-class QAction;
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_UNDOGROUP
-
-class Q_GUI_EXPORT QUndoGroup : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QUndoGroup)
-
-public:
- explicit QUndoGroup(QObject *parent = 0);
- ~QUndoGroup();
-
- void addStack(QUndoStack *stack);
- void removeStack(QUndoStack *stack);
- QList<QUndoStack*> stacks() const;
- QUndoStack *activeStack() const;
-
-#ifndef QT_NO_ACTION
- QAction *createUndoAction(QObject *parent,
- const QString &prefix = QString()) const;
- QAction *createRedoAction(QObject *parent,
- const QString &prefix = QString()) const;
-#endif // QT_NO_ACTION
- bool canUndo() const;
- bool canRedo() const;
- QString undoText() const;
- QString redoText() const;
- bool isClean() const;
-
-public Q_SLOTS:
- void undo();
- void redo();
- void setActiveStack(QUndoStack *stack);
-
-Q_SIGNALS:
- void activeStackChanged(QUndoStack *stack);
- void indexChanged(int idx);
- void cleanChanged(bool clean);
- void canUndoChanged(bool canUndo);
- void canRedoChanged(bool canRedo);
- void undoTextChanged(const QString &undoText);
- void redoTextChanged(const QString &redoText);
-
-private:
- Q_DISABLE_COPY(QUndoGroup)
-};
-
-#endif // QT_NO_UNDOGROUP
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QUNDOGROUP_H
diff --git a/src/gui/util/qundostack.cpp b/src/gui/util/qundostack.cpp
deleted file mode 100644
index 6b038ee52e..0000000000
--- a/src/gui/util/qundostack.cpp
+++ /dev/null
@@ -1,1127 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qdebug.h>
-#include "qundostack.h"
-#include "qundogroup.h"
-#include "qundostack_p.h"
-
-#ifndef QT_NO_UNDOCOMMAND
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QUndoCommand
- \brief The QUndoCommand class is the base class of all commands stored on a QUndoStack.
- \since 4.2
-
- For an overview of Qt's Undo Framework, see the
- \l{Overview of Qt's Undo Framework}{overview document}.
-
- A QUndoCommand represents a single editing action on a document; for example,
- inserting or deleting a block of text in a text editor. QUndoCommand can apply
- a change to the document with redo() and undo the change with undo(). The
- implementations for these functions must be provided in a derived class.
-
- \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 0
-
- A QUndoCommand has an associated text(). This is a short string
- describing what the command does. It is used to update the text
- properties of the stack's undo and redo actions; see
- QUndoStack::createUndoAction() and QUndoStack::createRedoAction().
-
- QUndoCommand objects are owned by the stack they were pushed on.
- QUndoStack deletes a command if it has been undone and a new command is pushed. For example:
-
-\snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 1
-
- In effect, when a command is pushed, it becomes the top-most command
- on the stack.
-
- To support command compression, QUndoCommand has an id() and the virtual function
- mergeWith(). These functions are used by QUndoStack::push().
-
- To support command macros, a QUndoCommand object can have any number of child
- commands. Undoing or redoing the parent command will cause the child
- commands to be undone or redone. A command can be assigned
- to a parent explicitly in the constructor. In this case, the command
- will be owned by the parent.
-
- The parent in this case is usually an empty command, in that it doesn't
- provide its own implementation of undo() and redo(). Instead, it uses
- the base implementations of these functions, which simply call undo() or
- redo() on all its children. The parent should, however, have a meaningful
- text().
-
- \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 2
-
- Another way to create macros is to use the convenience functions
- QUndoStack::beginMacro() and QUndoStack::endMacro().
-
- \sa QUndoStack
-*/
-
-/*!
- Constructs a QUndoCommand object with the given \a parent and \a text.
-
- If \a parent is not 0, this command is appended to parent's child list.
- The parent command then owns this command and will delete it in its
- destructor.
-
- \sa ~QUndoCommand()
-*/
-
-QUndoCommand::QUndoCommand(const QString &text, QUndoCommand *parent)
-{
- d = new QUndoCommandPrivate;
- if (parent != 0)
- parent->d->child_list.append(this);
- d->text = text;
-}
-
-/*!
- Constructs a QUndoCommand object with parent \a parent.
-
- If \a parent is not 0, this command is appended to parent's child list.
- The parent command then owns this command and will delete it in its
- destructor.
-
- \sa ~QUndoCommand()
-*/
-
-QUndoCommand::QUndoCommand(QUndoCommand *parent)
-{
- d = new QUndoCommandPrivate;
- if (parent != 0)
- parent->d->child_list.append(this);
-}
-
-/*!
- Destroys the QUndoCommand object and all child commands.
-
- \sa QUndoCommand()
-*/
-
-QUndoCommand::~QUndoCommand()
-{
- qDeleteAll(d->child_list);
- delete d;
-}
-
-/*!
- Returns the ID of this command.
-
- A command ID is used in command compression. It must be an integer unique to
- this command's class, or -1 if the command doesn't support compression.
-
- If the command supports compression this function must be overridden in the
- derived class to return the correct ID. The base implementation returns -1.
-
- QUndoStack::push() will only try to merge two commands if they have the
- same ID, and the ID is not -1.
-
- \sa mergeWith(), QUndoStack::push()
-*/
-
-int QUndoCommand::id() const
-{
- return -1;
-}
-
-/*!
- Attempts to merge this command with \a command. Returns true on
- success; otherwise returns false.
-
- If this function returns true, calling this command's redo() must have the same
- effect as redoing both this command and \a command.
- Similarly, calling this command's undo() must have the same effect as undoing
- \a command and this command.
-
- QUndoStack will only try to merge two commands if they have the same id, and
- the id is not -1.
-
- The default implementation returns false.
-
- \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 3
-
- \sa id() QUndoStack::push()
-*/
-
-bool QUndoCommand::mergeWith(const QUndoCommand *command)
-{
- Q_UNUSED(command);
- return false;
-}
-
-/*!
- Applies a change to the document. This function must be implemented in
- the derived class. Calling QUndoStack::push(),
- QUndoStack::undo() or QUndoStack::redo() from this function leads to
- undefined beahavior.
-
- The default implementation calls redo() on all child commands.
-
- \sa undo()
-*/
-
-void QUndoCommand::redo()
-{
- for (int i = 0; i < d->child_list.size(); ++i)
- d->child_list.at(i)->redo();
-}
-
-/*!
- Reverts a change to the document. After undo() is called, the state of
- the document should be the same as before redo() was called. This function must
- be implemented in the derived class. Calling QUndoStack::push(),
- QUndoStack::undo() or QUndoStack::redo() from this function leads to
- undefined beahavior.
-
- The default implementation calls undo() on all child commands in reverse order.
-
- \sa redo()
-*/
-
-void QUndoCommand::undo()
-{
- for (int i = d->child_list.size() - 1; i >= 0; --i)
- d->child_list.at(i)->undo();
-}
-
-/*!
- Returns a short text string describing what this command does; for example,
- "insert text".
-
- The text is used when the text properties of the stack's undo and redo
- actions are updated.
-
- \sa setText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction()
-*/
-
-QString QUndoCommand::text() const
-{
- return d->text;
-}
-
-/*!
- Sets the command's text to be the \a text specified.
-
- The specified text should be a short user-readable string describing what this
- command does.
-
- \sa text() QUndoStack::createUndoAction() QUndoStack::createRedoAction()
-*/
-
-void QUndoCommand::setText(const QString &text)
-{
- d->text = text;
-}
-
-/*!
- \since 4.4
-
- Returns the number of child commands in this command.
-
- \sa child()
-*/
-
-int QUndoCommand::childCount() const
-{
- return d->child_list.count();
-}
-
-/*!
- \since 4.4
-
- Returns the child command at \a index.
-
- \sa childCount(), QUndoStack::command()
-*/
-
-const QUndoCommand *QUndoCommand::child(int index) const
-{
- if (index < 0 || index >= d->child_list.count())
- return 0;
- return d->child_list.at(index);
-}
-
-#endif // QT_NO_UNDOCOMMAND
-
-#ifndef QT_NO_UNDOSTACK
-
-/*!
- \class QUndoStack
- \brief The QUndoStack class is a stack of QUndoCommand objects.
- \since 4.2
-
- For an overview of Qt's Undo Framework, see the
- \l{Overview of Qt's Undo Framework}{overview document}.
-
- An undo stack maintains a stack of commands that have been applied to a
- document.
-
- New commands are pushed on the stack using push(). Commands can be
- undone and redone using undo() and redo(), or by triggering the
- actions returned by createUndoAction() and createRedoAction().
-
- QUndoStack keeps track of the \a current command. This is the command
- which will be executed by the next call to redo(). The index of this
- command is returned by index(). The state of the edited object can be
- rolled forward or back using setIndex(). If the top-most command on the
- stack has already been redone, index() is equal to count().
-
- QUndoStack provides support for undo and redo actions, command
- compression, command macros, and supports the concept of a
- \e{clean state}.
-
- \section1 Undo and Redo Actions
-
- QUndoStack provides convenient undo and redo QAction objects, which
- can be inserted into a menu or a toolbar. When commands are undone or
- redone, QUndoStack updates the text properties of these actions
- to reflect what change they will trigger. The actions are also disabled
- when no command is available for undo or redo. These actions
- are returned by QUndoStack::createUndoAction() and QUndoStack::createRedoAction().
-
- \section1 Command Compression and Macros
-
- Command compression is useful when several commands can be compressed
- into a single command that can be undone and redone in a single operation.
- For example, when a user types a character in a text editor, a new command
- is created. This command inserts the character into the document at the
- cursor position. However, it is more convenient for the user to be able
- to undo or redo typing of whole words, sentences, or paragraphs.
- Command compression allows these single-character commands to be merged
- into a single command which inserts or deletes sections of text.
- For more information, see QUndoCommand::mergeWith() and push().
-
- A command macro is a sequence of commands, all of which are undone and
- redone in one go. Command macros are created by giving a command a list
- of child commands.
- Undoing or redoing the parent command will cause the child commands to
- be undone or redone. Command macros may be created explicitly
- by specifying a parent in the QUndoCommand constructor, or by using the
- convenience functions beginMacro() and endMacro().
-
- Although command compression and macros appear to have the same effect to the
- user, they often have different uses in an application. Commands that
- perform small changes to a document may be usefully compressed if there is
- no need to individually record them, and if only larger changes are relevant
- to the user.
- However, for commands that need to be recorded individually, or those that
- cannot be compressed, it is useful to use macros to provide a more convenient
- user experience while maintaining a record of each command.
-
- \section1 Clean State
-
- QUndoStack supports the concept of a clean state. When the
- document is saved to disk, the stack can be marked as clean using
- setClean(). Whenever the stack returns to this state through undoing and
- redoing commands, it emits the signal cleanChanged(). This signal
- is also emitted when the stack leaves the clean state. This signal is
- usually used to enable and disable the save actions in the application,
- and to update the document's title to reflect that it contains unsaved
- changes.
-
- \sa QUndoCommand, QUndoView
-*/
-
-#ifndef QT_NO_ACTION
-
-QUndoAction::QUndoAction(const QString &prefix, QObject *parent)
- : QAction(parent)
-{
- m_prefix = prefix;
-}
-
-void QUndoAction::setPrefixedText(const QString &text)
-{
- QString s = m_prefix;
- if (!m_prefix.isEmpty() && !text.isEmpty())
- s.append(QLatin1Char(' '));
- s.append(text);
- setText(s);
-}
-
-#endif // QT_NO_ACTION
-
-/*! \internal
- Sets the current index to \a idx, emitting appropriate signals. If \a clean is true,
- makes \a idx the clean index as well.
-*/
-
-void QUndoStackPrivate::setIndex(int idx, bool clean)
-{
- Q_Q(QUndoStack);
-
- bool was_clean = index == clean_index;
-
- if (idx != index) {
- index = idx;
- emit q->indexChanged(index);
- emit q->canUndoChanged(q->canUndo());
- emit q->undoTextChanged(q->undoText());
- emit q->canRedoChanged(q->canRedo());
- emit q->redoTextChanged(q->redoText());
- }
-
- if (clean)
- clean_index = index;
-
- bool is_clean = index == clean_index;
- if (is_clean != was_clean)
- emit q->cleanChanged(is_clean);
-}
-
-/*! \internal
- If the number of commands on the stack exceedes the undo limit, deletes commands from
- the bottom of the stack.
-
- Returns true if commands were deleted.
-*/
-
-bool QUndoStackPrivate::checkUndoLimit()
-{
- if (undo_limit <= 0 || !macro_stack.isEmpty() || undo_limit >= command_list.count())
- return false;
-
- int del_count = command_list.count() - undo_limit;
-
- for (int i = 0; i < del_count; ++i)
- delete command_list.takeFirst();
-
- index -= del_count;
- if (clean_index != -1) {
- if (clean_index < del_count)
- clean_index = -1; // we've deleted the clean command
- else
- clean_index -= del_count;
- }
-
- return true;
-}
-
-/*!
- Constructs an empty undo stack with the parent \a parent. The
- stack will initially be in the clean state. If \a parent is a
- QUndoGroup object, the stack is automatically added to the group.
-
- \sa push()
-*/
-
-QUndoStack::QUndoStack(QObject *parent)
- : QObject(*(new QUndoStackPrivate), parent)
-{
-#ifndef QT_NO_UNDOGROUP
- if (QUndoGroup *group = qobject_cast<QUndoGroup*>(parent))
- group->addStack(this);
-#endif
-}
-
-/*!
- Destroys the undo stack, deleting any commands that are on it. If the
- stack is in a QUndoGroup, the stack is automatically removed from the group.
-
- \sa QUndoStack()
-*/
-
-QUndoStack::~QUndoStack()
-{
-#ifndef QT_NO_UNDOGROUP
- Q_D(QUndoStack);
- if (d->group != 0)
- d->group->removeStack(this);
-#endif
- clear();
-}
-
-/*!
- Clears the command stack by deleting all commands on it, and returns the stack
- to the clean state.
-
- Commands are not undone or redone; the state of the edited object remains
- unchanged.
-
- This function is usually used when the contents of the document are
- abandoned.
-
- \sa QUndoStack()
-*/
-
-void QUndoStack::clear()
-{
- Q_D(QUndoStack);
-
- if (d->command_list.isEmpty())
- return;
-
- bool was_clean = isClean();
-
- d->macro_stack.clear();
- qDeleteAll(d->command_list);
- d->command_list.clear();
-
- d->index = 0;
- d->clean_index = 0;
-
- emit indexChanged(0);
- emit canUndoChanged(false);
- emit undoTextChanged(QString());
- emit canRedoChanged(false);
- emit redoTextChanged(QString());
-
- if (!was_clean)
- emit cleanChanged(true);
-}
-
-/*!
- Pushes \a cmd on the stack or merges it with the most recently executed command.
- In either case, executes \a cmd by calling its redo() function.
-
- If \a cmd's id is not -1, and if the id is the same as that of the
- most recently executed command, QUndoStack will attempt to merge the two
- commands by calling QUndoCommand::mergeWith() on the most recently executed
- command. If QUndoCommand::mergeWith() returns true, \a cmd is deleted.
-
- In all other cases \a cmd is simply pushed on the stack.
-
- If commands were undone before \a cmd was pushed, the current command and
- all commands above it are deleted. Hence \a cmd always ends up being the
- top-most on the stack.
-
- Once a command is pushed, the stack takes ownership of it. There
- are no getters to return the command, since modifying it after it has
- been executed will almost always lead to corruption of the document's
- state.
-
- \sa QUndoCommand::id() QUndoCommand::mergeWith()
-*/
-
-void QUndoStack::push(QUndoCommand *cmd)
-{
- Q_D(QUndoStack);
- cmd->redo();
-
- bool macro = !d->macro_stack.isEmpty();
-
- QUndoCommand *cur = 0;
- if (macro) {
- QUndoCommand *macro_cmd = d->macro_stack.last();
- if (!macro_cmd->d->child_list.isEmpty())
- cur = macro_cmd->d->child_list.last();
- } else {
- if (d->index > 0)
- cur = d->command_list.at(d->index - 1);
- while (d->index < d->command_list.size())
- delete d->command_list.takeLast();
- if (d->clean_index > d->index)
- d->clean_index = -1; // we've deleted the clean state
- }
-
- bool try_merge = cur != 0
- && cur->id() != -1
- && cur->id() == cmd->id()
- && (macro || d->index != d->clean_index);
-
- if (try_merge && cur->mergeWith(cmd)) {
- delete cmd;
- if (!macro) {
- emit indexChanged(d->index);
- emit canUndoChanged(canUndo());
- emit undoTextChanged(undoText());
- emit canRedoChanged(canRedo());
- emit redoTextChanged(redoText());
- }
- } else {
- if (macro) {
- d->macro_stack.last()->d->child_list.append(cmd);
- } else {
- d->command_list.append(cmd);
- d->checkUndoLimit();
- d->setIndex(d->index + 1, false);
- }
- }
-}
-
-/*!
- Marks the stack as clean and emits cleanChanged() if the stack was
- not already clean.
-
- Whenever the stack returns to this state through the use of undo/redo
- commands, it emits the signal cleanChanged(). This signal is also
- emitted when the stack leaves the clean state.
-
- \sa isClean(), cleanIndex()
-*/
-
-void QUndoStack::setClean()
-{
- Q_D(QUndoStack);
- if (!d->macro_stack.isEmpty()) {
- qWarning("QUndoStack::setClean(): cannot set clean in the middle of a macro");
- return;
- }
-
- d->setIndex(d->index, true);
-}
-
-/*!
- If the stack is in the clean state, returns true; otherwise returns false.
-
- \sa setClean() cleanIndex()
-*/
-
-bool QUndoStack::isClean() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return false;
- return d->clean_index == d->index;
-}
-
-/*!
- Returns the clean index. This is the index at which setClean() was called.
-
- A stack may not have a clean index. This happens if a document is saved,
- some commands are undone, then a new command is pushed. Since
- push() deletes all the undone commands before pushing the new command, the stack
- can't return to the clean state again. In this case, this function returns -1.
-
- \sa isClean() setClean()
-*/
-
-int QUndoStack::cleanIndex() const
-{
- Q_D(const QUndoStack);
- return d->clean_index;
-}
-
-/*!
- Undoes the command below the current command by calling QUndoCommand::undo().
- Decrements the current command index.
-
- If the stack is empty, or if the bottom command on the stack has already been
- undone, this function does nothing.
-
- \sa redo() index()
-*/
-
-void QUndoStack::undo()
-{
- Q_D(QUndoStack);
- if (d->index == 0)
- return;
-
- if (!d->macro_stack.isEmpty()) {
- qWarning("QUndoStack::undo(): cannot undo in the middle of a macro");
- return;
- }
-
- int idx = d->index - 1;
- d->command_list.at(idx)->undo();
- d->setIndex(idx, false);
-}
-
-/*!
- Redoes the current command by calling QUndoCommand::redo(). Increments the current
- command index.
-
- If the stack is empty, or if the top command on the stack has already been
- redone, this function does nothing.
-
- \sa undo() index()
-*/
-
-void QUndoStack::redo()
-{
- Q_D(QUndoStack);
- if (d->index == d->command_list.size())
- return;
-
- if (!d->macro_stack.isEmpty()) {
- qWarning("QUndoStack::redo(): cannot redo in the middle of a macro");
- return;
- }
-
- d->command_list.at(d->index)->redo();
- d->setIndex(d->index + 1, false);
-}
-
-/*!
- Returns the number of commands on the stack. Macro commands are counted as
- one command.
-
- \sa index() setIndex() command()
-*/
-
-int QUndoStack::count() const
-{
- Q_D(const QUndoStack);
- return d->command_list.size();
-}
-
-/*!
- Returns the index of the current command. This is the command that will be
- executed on the next call to redo(). It is not always the top-most command
- on the stack, since a number of commands may have been undone.
-
- \sa undo() redo() count()
-*/
-
-int QUndoStack::index() const
-{
- Q_D(const QUndoStack);
- return d->index;
-}
-
-/*!
- Repeatedly calls undo() or redo() until the current command index reaches
- \a idx. This function can be used to roll the state of the document forwards
- of backwards. indexChanged() is emitted only once.
-
- \sa index() count() undo() redo()
-*/
-
-void QUndoStack::setIndex(int idx)
-{
- Q_D(QUndoStack);
- if (!d->macro_stack.isEmpty()) {
- qWarning("QUndoStack::setIndex(): cannot set index in the middle of a macro");
- return;
- }
-
- if (idx < 0)
- idx = 0;
- else if (idx > d->command_list.size())
- idx = d->command_list.size();
-
- int i = d->index;
- while (i < idx)
- d->command_list.at(i++)->redo();
- while (i > idx)
- d->command_list.at(--i)->undo();
-
- d->setIndex(idx, false);
-}
-
-/*!
- Returns true if there is a command available for undo; otherwise returns false.
-
- This function returns false if the stack is empty, or if the bottom command
- on the stack has already been undone.
-
- Synonymous with index() == 0.
-
- \sa index() canRedo()
-*/
-
-bool QUndoStack::canUndo() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return false;
- return d->index > 0;
-}
-
-/*!
- Returns true if there is a command available for redo; otherwise returns false.
-
- This function returns false if the stack is empty or if the top command
- on the stack has already been redone.
-
- Synonymous with index() == count().
-
- \sa index() canUndo()
-*/
-
-bool QUndoStack::canRedo() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return false;
- return d->index < d->command_list.size();
-}
-
-/*!
- Returns the text of the command which will be undone in the next call to undo().
-
- \sa QUndoCommand::text() redoText()
-*/
-
-QString QUndoStack::undoText() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return QString();
- if (d->index > 0)
- return d->command_list.at(d->index - 1)->text();
- return QString();
-}
-
-/*!
- Returns the text of the command which will be redone in the next call to redo().
-
- \sa QUndoCommand::text() undoText()
-*/
-
-QString QUndoStack::redoText() const
-{
- Q_D(const QUndoStack);
- if (!d->macro_stack.isEmpty())
- return QString();
- if (d->index < d->command_list.size())
- return d->command_list.at(d->index)->text();
- return QString();
-}
-
-#ifndef QT_NO_ACTION
-
-/*!
- Creates an undo QAction object with the given \a parent.
-
- Triggering this action will cause a call to undo(). The text of this action
- is the text of the command which will be undone in the next call to undo(),
- prefixed by the specified \a prefix. If there is no command available for undo,
- this action will be disabled.
-
- If \a prefix is empty, the default prefix "Undo" is used.
-
- \sa createRedoAction(), canUndo(), QUndoCommand::text()
-*/
-
-QAction *QUndoStack::createUndoAction(QObject *parent, const QString &prefix) const
-{
- QString pref = prefix.isEmpty() ? tr("Undo") : prefix;
- QUndoAction *result = new QUndoAction(pref, parent);
- result->setEnabled(canUndo());
- result->setPrefixedText(undoText());
- connect(this, SIGNAL(canUndoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(undoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(undo()));
- return result;
-}
-
-/*!
- Creates an redo QAction object with the given \a parent.
-
- Triggering this action will cause a call to redo(). The text of this action
- is the text of the command which will be redone in the next call to redo(),
- prefixed by the specified \a prefix. If there is no command available for redo,
- this action will be disabled.
-
- If \a prefix is empty, the default prefix "Redo" is used.
-
- \sa createUndoAction(), canRedo(), QUndoCommand::text()
-*/
-
-QAction *QUndoStack::createRedoAction(QObject *parent, const QString &prefix) const
-{
- QString pref = prefix.isEmpty() ? tr("Redo") : prefix;
- QUndoAction *result = new QUndoAction(pref, parent);
- result->setEnabled(canRedo());
- result->setPrefixedText(redoText());
- connect(this, SIGNAL(canRedoChanged(bool)),
- result, SLOT(setEnabled(bool)));
- connect(this, SIGNAL(redoTextChanged(QString)),
- result, SLOT(setPrefixedText(QString)));
- connect(result, SIGNAL(triggered()), this, SLOT(redo()));
- return result;
-}
-
-#endif // QT_NO_ACTION
-
-/*!
- Begins composition of a macro command with the given \a text description.
-
- An empty command described by the specified \a text is pushed on the stack.
- Any subsequent commands pushed on the stack will be appended to the empty
- command's children until endMacro() is called.
-
- Calls to beginMacro() and endMacro() may be nested, but every call to
- beginMacro() must have a matching call to endMacro().
-
- While a macro is composed, the stack is disabled. This means that:
- \list
- \i indexChanged() and cleanChanged() are not emitted,
- \i canUndo() and canRedo() return false,
- \i calling undo() or redo() has no effect,
- \i the undo/redo actions are disabled.
- \endlist
-
- The stack becomes enabled and appropriate signals are emitted when endMacro()
- is called for the outermost macro.
-
- \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 4
-
- This code is equivalent to:
-
- \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 5
-
- \sa endMacro()
-*/
-
-void QUndoStack::beginMacro(const QString &text)
-{
- Q_D(QUndoStack);
- QUndoCommand *cmd = new QUndoCommand();
- cmd->setText(text);
-
- if (d->macro_stack.isEmpty()) {
- while (d->index < d->command_list.size())
- delete d->command_list.takeLast();
- if (d->clean_index > d->index)
- d->clean_index = -1; // we've deleted the clean state
- d->command_list.append(cmd);
- } else {
- d->macro_stack.last()->d->child_list.append(cmd);
- }
- d->macro_stack.append(cmd);
-
- if (d->macro_stack.count() == 1) {
- emit canUndoChanged(false);
- emit undoTextChanged(QString());
- emit canRedoChanged(false);
- emit redoTextChanged(QString());
- }
-}
-
-/*!
- Ends composition of a macro command.
-
- If this is the outermost macro in a set nested macros, this function emits
- indexChanged() once for the entire macro command.
-
- \sa beginMacro()
-*/
-
-void QUndoStack::endMacro()
-{
- Q_D(QUndoStack);
- if (d->macro_stack.isEmpty()) {
- qWarning("QUndoStack::endMacro(): no matching beginMacro()");
- return;
- }
-
- d->macro_stack.removeLast();
-
- if (d->macro_stack.isEmpty()) {
- d->checkUndoLimit();
- d->setIndex(d->index + 1, false);
- }
-}
-
-/*!
- \since 4.4
-
- Returns a const pointer to the command at \a index.
-
- This function returns a const pointer, because modifying a command,
- once it has been pushed onto the stack and executed, almost always
- causes corruption of the state of the document, if the command is
- later undone or redone.
-
- \sa QUndoCommand::child()
-*/
-const QUndoCommand *QUndoStack::command(int index) const
-{
- Q_D(const QUndoStack);
-
- if (index < 0 || index >= d->command_list.count())
- return 0;
- return d->command_list.at(index);
-}
-
-/*!
- Returns the text of the command at index \a idx.
-
- \sa beginMacro()
-*/
-
-QString QUndoStack::text(int idx) const
-{
- Q_D(const QUndoStack);
-
- if (idx < 0 || idx >= d->command_list.size())
- return QString();
- return d->command_list.at(idx)->text();
-}
-
-/*!
- \property QUndoStack::undoLimit
- \brief the maximum number of commands on this stack.
- \since 4.3
-
- When the number of commands on a stack exceedes the stack's undoLimit, commands are
- deleted from the bottom of the stack. Macro commands (commands with child commands)
- are treated as one command. The default value is 0, which means that there is no
- limit.
-
- This property may only be set when the undo stack is empty, since setting it on a
- non-empty stack might delete the command at the current index. Calling setUndoLimit()
- on a non-empty stack prints a warning and does nothing.
-*/
-
-void QUndoStack::setUndoLimit(int limit)
-{
- Q_D(QUndoStack);
-
- if (!d->command_list.isEmpty()) {
- qWarning("QUndoStack::setUndoLimit(): an undo limit can only be set when the stack is empty");
- return;
- }
-
- if (limit == d->undo_limit)
- return;
- d->undo_limit = limit;
- d->checkUndoLimit();
-}
-
-int QUndoStack::undoLimit() const
-{
- Q_D(const QUndoStack);
-
- return d->undo_limit;
-}
-
-/*!
- \property QUndoStack::active
- \brief the active status of this stack.
-
- An application often has multiple undo stacks, one for each opened document. The active
- stack is the one associated with the currently active document. If the stack belongs
- to a QUndoGroup, calls to QUndoGroup::undo() or QUndoGroup::redo() will be forwarded
- to this stack when it is active. If the QUndoGroup is watched by a QUndoView, the view
- will display the contents of this stack when it is active. If the stack does not belong to
- a QUndoGroup, making it active has no effect.
-
- It is the programmer's responsibility to specify which stack is active by
- calling setActive(), usually when the associated document window receives focus.
-
- \sa QUndoGroup
-*/
-
-void QUndoStack::setActive(bool active)
-{
-#ifdef QT_NO_UNDOGROUP
- Q_UNUSED(active);
-#else
- Q_D(QUndoStack);
-
- if (d->group != 0) {
- if (active)
- d->group->setActiveStack(this);
- else if (d->group->activeStack() == this)
- d->group->setActiveStack(0);
- }
-#endif
-}
-
-bool QUndoStack::isActive() const
-{
-#ifdef QT_NO_UNDOGROUP
- return true;
-#else
- Q_D(const QUndoStack);
- return d->group == 0 || d->group->activeStack() == this;
-#endif
-}
-
-/*!
- \fn void QUndoStack::indexChanged(int idx)
-
- This signal is emitted whenever a command modifies the state of the document.
- This happens when a command is undone or redone. When a macro
- command is undone or redone, or setIndex() is called, this signal
- is emitted only once.
-
- \a idx specifies the index of the current command, ie. the command which will be
- executed on the next call to redo().
-
- \sa index() setIndex()
-*/
-
-/*!
- \fn void QUndoStack::cleanChanged(bool clean)
-
- This signal is emitted whenever the stack enters or leaves the clean state.
- If \a clean is true, the stack is in a clean state; otherwise this signal
- indicates that it has left the clean state.
-
- \sa isClean() setClean()
-*/
-
-/*!
- \fn void QUndoStack::undoTextChanged(const QString &undoText)
-
- This signal is emitted whenever the value of undoText() changes. It is
- used to update the text property of the undo action returned by createUndoAction().
- \a undoText specifies the new text.
-*/
-
-/*!
- \fn void QUndoStack::canUndoChanged(bool canUndo)
-
- This signal is emitted whenever the value of canUndo() changes. It is
- used to enable or disable the undo action returned by createUndoAction().
- \a canUndo specifies the new value.
-*/
-
-/*!
- \fn void QUndoStack::redoTextChanged(const QString &redoText)
-
- This signal is emitted whenever the value of redoText() changes. It is
- used to update the text property of the redo action returned by createRedoAction().
- \a redoText specifies the new text.
-*/
-
-/*!
- \fn void QUndoStack::canRedoChanged(bool canRedo)
-
- This signal is emitted whenever the value of canRedo() changes. It is
- used to enable or disable the redo action returned by createRedoAction().
- \a canRedo specifies the new value.
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_UNDOSTACK
diff --git a/src/gui/util/qundostack.h b/src/gui/util/qundostack.h
deleted file mode 100644
index 65941b53c3..0000000000
--- a/src/gui/util/qundostack.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************************
-**
-** 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 QUNDOSTACK_H
-#define QUNDOSTACK_H
-
-#include <QtCore/qobject.h>
-#include <QtCore/qstring.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QAction;
-class QUndoCommandPrivate;
-class QUndoStackPrivate;
-
-#ifndef QT_NO_UNDOCOMMAND
-
-class Q_GUI_EXPORT QUndoCommand
-{
- QUndoCommandPrivate *d;
-
-public:
- explicit QUndoCommand(QUndoCommand *parent = 0);
- explicit QUndoCommand(const QString &text, QUndoCommand *parent = 0);
- virtual ~QUndoCommand();
-
- virtual void undo();
- virtual void redo();
-
- QString text() const;
- void setText(const QString &text);
-
- virtual int id() const;
- virtual bool mergeWith(const QUndoCommand *other);
-
- int childCount() const;
- const QUndoCommand *child(int index) const;
-
-private:
- Q_DISABLE_COPY(QUndoCommand)
- friend class QUndoStack;
-};
-
-#endif // QT_NO_UNDOCOMMAND
-
-#ifndef QT_NO_UNDOSTACK
-
-class Q_GUI_EXPORT QUndoStack : public QObject
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QUndoStack)
- Q_PROPERTY(bool active READ isActive WRITE setActive)
- Q_PROPERTY(int undoLimit READ undoLimit WRITE setUndoLimit)
-
-public:
- explicit QUndoStack(QObject *parent = 0);
- ~QUndoStack();
- void clear();
-
- void push(QUndoCommand *cmd);
-
- bool canUndo() const;
- bool canRedo() const;
- QString undoText() const;
- QString redoText() const;
-
- int count() const;
- int index() const;
- QString text(int idx) const;
-
-#ifndef QT_NO_ACTION
- QAction *createUndoAction(QObject *parent,
- const QString &prefix = QString()) const;
- QAction *createRedoAction(QObject *parent,
- const QString &prefix = QString()) const;
-#endif // QT_NO_ACTION
-
- bool isActive() const;
- bool isClean() const;
- int cleanIndex() const;
-
- void beginMacro(const QString &text);
- void endMacro();
-
- void setUndoLimit(int limit);
- int undoLimit() const;
-
- const QUndoCommand *command(int index) const;
-
-public Q_SLOTS:
- void setClean();
- void setIndex(int idx);
- void undo();
- void redo();
- void setActive(bool active = true);
-
-Q_SIGNALS:
- void indexChanged(int idx);
- void cleanChanged(bool clean);
- void canUndoChanged(bool canUndo);
- void canRedoChanged(bool canRedo);
- void undoTextChanged(const QString &undoText);
- void redoTextChanged(const QString &redoText);
-
-private:
- Q_DISABLE_COPY(QUndoStack)
- friend class QUndoGroup;
-};
-
-#endif // QT_NO_UNDOSTACK
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QUNDOSTACK_H
diff --git a/src/gui/util/qundostack_p.h b/src/gui/util/qundostack_p.h
deleted file mode 100644
index 3c7d0e7d85..0000000000
--- a/src/gui/util/qundostack_p.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** 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 QUNDOSTACK_P_H
-#define QUNDOSTACK_P_H
-
-#include <private/qobject_p.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qaction.h>
-
-#include "qundostack.h"
-
-QT_BEGIN_NAMESPACE
-class QUndoCommand;
-class QUndoGroup;
-
-//
-// 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 and qfiledialog.cpp. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-class QUndoCommandPrivate
-{
-public:
- QUndoCommandPrivate() : id(-1) {}
- QList<QUndoCommand*> child_list;
- QString text;
- int id;
-};
-
-#ifndef QT_NO_UNDOSTACK
-
-class QUndoStackPrivate : public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QUndoStack)
-public:
- QUndoStackPrivate() : index(0), clean_index(0), group(0), undo_limit(0) {}
-
- QList<QUndoCommand*> command_list;
- QList<QUndoCommand*> macro_stack;
- int index;
- int clean_index;
- QUndoGroup *group;
- int undo_limit;
-
- void setIndex(int idx, bool clean);
- bool checkUndoLimit();
-};
-
-#ifndef QT_NO_ACTION
-class QUndoAction : public QAction
-{
- Q_OBJECT
-public:
- QUndoAction(const QString &prefix, QObject *parent = 0);
-public Q_SLOTS:
- void setPrefixedText(const QString &text);
-private:
- QString m_prefix;
-};
-#endif // QT_NO_ACTION
-
-
-QT_END_NAMESPACE
-#endif // QT_NO_UNDOSTACK
-#endif // QUNDOSTACK_P_H
diff --git a/src/gui/util/qundoview.cpp b/src/gui/util/qundoview.cpp
deleted file mode 100644
index 43c1774b25..0000000000
--- a/src/gui/util/qundoview.cpp
+++ /dev/null
@@ -1,476 +0,0 @@
-/****************************************************************************
-**
-** 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 "qundostack.h"
-#include "qundoview.h"
-
-#ifndef QT_NO_UNDOVIEW
-
-#include "qundogroup.h"
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qpointer.h>
-#include <QtGui/qicon.h>
-#include <private/qlistview_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QUndoModel : public QAbstractItemModel
-{
- Q_OBJECT
-public:
- QUndoModel(QObject *parent = 0);
-
- QUndoStack *stack() const;
-
- virtual QModelIndex index(int row, int column,
- const QModelIndex &parent = QModelIndex()) const;
- virtual QModelIndex parent(const QModelIndex &child) const;
- virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
- virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
- virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
-
- QModelIndex selectedIndex() const;
- QItemSelectionModel *selectionModel() const;
-
- QString emptyLabel() const;
- void setEmptyLabel(const QString &label);
-
- void setCleanIcon(const QIcon &icon);
- QIcon cleanIcon() const;
-
-public slots:
- void setStack(QUndoStack *stack);
-
-private slots:
- void stackChanged();
- void stackDestroyed(QObject *obj);
- void setStackCurrentIndex(const QModelIndex &index);
-
-private:
- QUndoStack *m_stack;
- QItemSelectionModel *m_sel_model;
- QString m_emty_label;
- QIcon m_clean_icon;
-};
-
-QUndoModel::QUndoModel(QObject *parent)
- : QAbstractItemModel(parent)
-{
- m_stack = 0;
- m_sel_model = new QItemSelectionModel(this, this);
- connect(m_sel_model, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(setStackCurrentIndex(QModelIndex)));
- m_emty_label = tr("<empty>");
-}
-
-QItemSelectionModel *QUndoModel::selectionModel() const
-{
- return m_sel_model;
-}
-
-QUndoStack *QUndoModel::stack() const
-{
- return m_stack;
-}
-
-void QUndoModel::setStack(QUndoStack *stack)
-{
- if (m_stack == stack)
- return;
-
- if (m_stack != 0) {
- disconnect(m_stack, SIGNAL(cleanChanged(bool)), this, SLOT(stackChanged()));
- disconnect(m_stack, SIGNAL(indexChanged(int)), this, SLOT(stackChanged()));
- disconnect(m_stack, SIGNAL(destroyed(QObject*)), this, SLOT(stackDestroyed(QObject*)));
- }
- m_stack = stack;
- if (m_stack != 0) {
- connect(m_stack, SIGNAL(cleanChanged(bool)), this, SLOT(stackChanged()));
- connect(m_stack, SIGNAL(indexChanged(int)), this, SLOT(stackChanged()));
- connect(m_stack, SIGNAL(destroyed(QObject*)), this, SLOT(stackDestroyed(QObject*)));
- }
-
- stackChanged();
-}
-
-void QUndoModel::stackDestroyed(QObject *obj)
-{
- if (obj != m_stack)
- return;
- m_stack = 0;
-
- stackChanged();
-}
-
-void QUndoModel::stackChanged()
-{
- reset();
- m_sel_model->setCurrentIndex(selectedIndex(), QItemSelectionModel::ClearAndSelect);
-}
-
-void QUndoModel::setStackCurrentIndex(const QModelIndex &index)
-{
- if (m_stack == 0)
- return;
-
- if (index == selectedIndex())
- return;
-
- if (index.column() != 0)
- return;
-
- m_stack->setIndex(index.row());
-}
-
-QModelIndex QUndoModel::selectedIndex() const
-{
- return m_stack == 0 ? QModelIndex() : createIndex(m_stack->index(), 0);
-}
-
-QModelIndex QUndoModel::index(int row, int column, const QModelIndex &parent) const
-{
- if (m_stack == 0)
- return QModelIndex();
-
- if (parent.isValid())
- return QModelIndex();
-
- if (column != 0)
- return QModelIndex();
-
- if (row < 0 || row > m_stack->count())
- return QModelIndex();
-
- return createIndex(row, column);
-}
-
-QModelIndex QUndoModel::parent(const QModelIndex&) const
-{
- return QModelIndex();
-}
-
-int QUndoModel::rowCount(const QModelIndex &parent) const
-{
- if (m_stack == 0)
- return 0;
-
- if (parent.isValid())
- return 0;
-
- return m_stack->count() + 1;
-}
-
-int QUndoModel::columnCount(const QModelIndex&) const
-{
- return 1;
-}
-
-QVariant QUndoModel::data(const QModelIndex &index, int role) const
-{
- if (m_stack == 0)
- return QVariant();
-
- if (index.column() != 0)
- return QVariant();
-
- if (index.row() < 0 || index.row() > m_stack->count())
- return QVariant();
-
- if (role == Qt::DisplayRole) {
- if (index.row() == 0)
- return m_emty_label;
- return m_stack->text(index.row() - 1);
- } else if (role == Qt::DecorationRole) {
- if (index.row() == m_stack->cleanIndex() && !m_clean_icon.isNull())
- return m_clean_icon;
- return QVariant();
- }
-
- return QVariant();
-}
-
-QString QUndoModel::emptyLabel() const
-{
- return m_emty_label;
-}
-
-void QUndoModel::setEmptyLabel(const QString &label)
-{
- m_emty_label = label;
- stackChanged();
-}
-
-void QUndoModel::setCleanIcon(const QIcon &icon)
-{
- m_clean_icon = icon;
- stackChanged();
-}
-
-QIcon QUndoModel::cleanIcon() const
-{
- return m_clean_icon;
-}
-
-/*!
- \class QUndoView
- \brief The QUndoView class displays the contents of a QUndoStack.
- \since 4.2
-
- \ingroup advanced
-
- QUndoView is a QListView which displays the list of commands pushed on an undo stack.
- The most recently executed command is always selected. Selecting a different command
- results in a call to QUndoStack::setIndex(), rolling the state of the document
- backwards or forward to the new command.
-
- The stack can be set explicitly with setStack(). Alternatively, a QUndoGroup object can
- be set with setGroup(). The view will then update itself automatically whenever the
- active stack of the group changes.
-
- \image qundoview.png
-*/
-
-class QUndoViewPrivate : public QListViewPrivate
-{
- Q_DECLARE_PUBLIC(QUndoView)
-public:
- QUndoViewPrivate() :
-#ifndef QT_NO_UNDOGROUP
- group(0),
-#endif
- model(0) {}
-
-#ifndef QT_NO_UNDOGROUP
- QPointer<QUndoGroup> group;
-#endif
- QUndoModel *model;
-
- void init();
-};
-
-void QUndoViewPrivate::init()
-{
- Q_Q(QUndoView);
-
- model = new QUndoModel(q);
- q->setModel(model);
- q->setSelectionModel(model->selectionModel());
-}
-
-/*!
- Constructs a new view with parent \a parent.
-*/
-
-QUndoView::QUndoView(QWidget *parent)
- : QListView(*new QUndoViewPrivate(), parent)
-{
- Q_D(QUndoView);
- d->init();
-}
-
-/*!
- Constructs a new view with parent \a parent and sets the observed stack to \a stack.
-*/
-
-QUndoView::QUndoView(QUndoStack *stack, QWidget *parent)
- : QListView(*new QUndoViewPrivate(), parent)
-{
- Q_D(QUndoView);
- d->init();
- setStack(stack);
-}
-
-#ifndef QT_NO_UNDOGROUP
-
-/*!
- Constructs a new view with parent \a parent and sets the observed group to \a group.
-
- The view will update itself autmiatically whenever the active stack of the group changes.
-*/
-
-QUndoView::QUndoView(QUndoGroup *group, QWidget *parent)
- : QListView(*new QUndoViewPrivate(), parent)
-{
- Q_D(QUndoView);
- d->init();
- setGroup(group);
-}
-
-#endif // QT_NO_UNDOGROUP
-
-/*!
- Destroys this view.
-*/
-
-QUndoView::~QUndoView()
-{
-}
-
-/*!
- Returns the stack currently displayed by this view. If the view is looking at a
- QUndoGroup, this the group's active stack.
-
- \sa setStack() setGroup()
-*/
-
-QUndoStack *QUndoView::stack() const
-{
- Q_D(const QUndoView);
- return d->model->stack();
-}
-
-/*!
- Sets the stack displayed by this view to \a stack. If \a stack is 0, the view
- will be empty.
-
- If the view was previously looking at a QUndoGroup, the group is set to 0.
-
- \sa stack() setGroup()
-*/
-
-void QUndoView::setStack(QUndoStack *stack)
-{
- Q_D(QUndoView);
-#ifndef QT_NO_UNDOGROUP
- setGroup(0);
-#endif
- d->model->setStack(stack);
-}
-
-#ifndef QT_NO_UNDOGROUP
-
-/*!
- Sets the group displayed by this view to \a group. If \a group is 0, the view will
- be empty.
-
- The view will update itself autmiatically whenever the active stack of the group changes.
-
- \sa group() setStack()
-*/
-
-void QUndoView::setGroup(QUndoGroup *group)
-{
- Q_D(QUndoView);
-
- if (d->group == group)
- return;
-
- if (d->group != 0) {
- disconnect(d->group, SIGNAL(activeStackChanged(QUndoStack*)),
- d->model, SLOT(setStack(QUndoStack*)));
- }
-
- d->group = group;
-
- if (d->group != 0) {
- connect(d->group, SIGNAL(activeStackChanged(QUndoStack*)),
- d->model, SLOT(setStack(QUndoStack*)));
- d->model->setStack(d->group->activeStack());
- } else {
- d->model->setStack(0);
- }
-}
-
-/*!
- Returns the group displayed by this view.
-
- If the view is not looking at group, this function returns 0.
-
- \sa setGroup() setStack()
-*/
-
-QUndoGroup *QUndoView::group() const
-{
- Q_D(const QUndoView);
- return d->group;
-}
-
-#endif // QT_NO_UNDOGROUP
-
-/*!
- \property QUndoView::emptyLabel
- \brief the label used for the empty state.
-
- The empty label is the topmost element in the list of commands, which represents
- the state of the document before any commands were pushed on the stack. The default
- is the string "<empty>".
-*/
-
-void QUndoView::setEmptyLabel(const QString &label)
-{
- Q_D(QUndoView);
- d->model->setEmptyLabel(label);
-}
-
-QString QUndoView::emptyLabel() const
-{
- Q_D(const QUndoView);
- return d->model->emptyLabel();
-}
-
-/*!
- \property QUndoView::cleanIcon
- \brief the icon used to represent the clean state.
-
- A stack may have a clean state set with QUndoStack::setClean(). This is usually
- the state of the document at the point it was saved. QUndoView can display an
- icon in the list of commands to show the clean state. If this property is
- a null icon, no icon is shown. The default value is the null icon.
-*/
-
-void QUndoView::setCleanIcon(const QIcon &icon)
-{
- Q_D(const QUndoView);
- d->model->setCleanIcon(icon);
-
-}
-
-QIcon QUndoView::cleanIcon() const
-{
- Q_D(const QUndoView);
- return d->model->cleanIcon();
-}
-
-QT_END_NAMESPACE
-
-#include "qundoview.moc"
-
-#endif // QT_NO_UNDOVIEW
diff --git a/src/gui/util/qundoview.h b/src/gui/util/qundoview.h
deleted file mode 100644
index de32a39c54..0000000000
--- a/src/gui/util/qundoview.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** 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 QUNDOVIEW_H
-#define QUNDOVIEW_H
-
-#include <QtGui/qlistview.h>
-#include <QtCore/qstring.h>
-
-#ifndef QT_NO_UNDOVIEW
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QUndoViewPrivate;
-class QUndoStack;
-class QUndoGroup;
-class QIcon;
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QUndoView : public QListView
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QUndoView)
- Q_PROPERTY(QString emptyLabel READ emptyLabel WRITE setEmptyLabel)
- Q_PROPERTY(QIcon cleanIcon READ cleanIcon WRITE setCleanIcon)
-
-public:
- explicit QUndoView(QWidget *parent = 0);
- explicit QUndoView(QUndoStack *stack, QWidget *parent = 0);
-#ifndef QT_NO_UNDOGROUP
- explicit QUndoView(QUndoGroup *group, QWidget *parent = 0);
-#endif
- ~QUndoView();
-
- QUndoStack *stack() const;
-#ifndef QT_NO_UNDOGROUP
- QUndoGroup *group() const;
-#endif
-
- void setEmptyLabel(const QString &label);
- QString emptyLabel() const;
-
- void setCleanIcon(const QIcon &icon);
- QIcon cleanIcon() const;
-
-public Q_SLOTS:
- void setStack(QUndoStack *stack);
-#ifndef QT_NO_UNDOGROUP
- void setGroup(QUndoGroup *group);
-#endif
-
-private:
- Q_DISABLE_COPY(QUndoView)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_UNDOVIEW
-#endif // QUNDOVIEW_H
diff --git a/src/gui/util/util.pri b/src/gui/util/util.pri
deleted file mode 100644
index 854964b784..0000000000
--- a/src/gui/util/util.pri
+++ /dev/null
@@ -1,69 +0,0 @@
-# Qt util module
-
-HEADERS += \
- util/qsystemtrayicon.h \
- util/qcompleter.h \
- util/qcompleter_p.h \
- util/qsystemtrayicon_p.h \
- util/qscroller.h \
- util/qscroller_p.h \
- util/qscrollerproperties.h \
- util/qscrollerproperties_p.h \
- util/qflickgesture_p.h \
- util/qundogroup.h \
- util/qundostack.h \
- util/qundostack_p.h \
- util/qundoview.h
-
-SOURCES += \
- util/qsystemtrayicon.cpp \
- util/qcompleter.cpp \
- util/qscroller.cpp \
- util/qscrollerproperties.cpp \
- util/qflickgesture.cpp \
- util/qundogroup.cpp \
- util/qundostack.cpp \
- util/qundoview.cpp
-
-
-wince* {
- SOURCES += \
- util/qsystemtrayicon_wince.cpp
-} else:win32 {
- SOURCES += \
- util/qsystemtrayicon_win.cpp
-}
-
-unix:x11 {
- SOURCES += \
- util/qsystemtrayicon_x11.cpp
-}
-
-qpa {
- SOURCES += \
- util/qsystemtrayicon_qpa.cpp
-}
-
-!qpa:!x11:mac {
- OBJECTIVE_SOURCES += util/qsystemtrayicon_mac.mm
-}
-
-symbian {
- LIBS += -letext -lplatformenv
- contains(S60_VERSION, 3.1)|contains(S60_VERSION, 3.2)|contains(S60_VERSION, 5.0) {
- LIBS += -lsendas2 -lapmime
- contains(QT_CONFIG, s60) {
- contains(CONFIG, is_using_gnupoc) {
- LIBS += -lcommonui
- } else {
- LIBS += -lCommonUI
- }
- }
- } else {
- DEFINES += USE_SCHEMEHANDLER
- }
-}
-
-macx {
- OBJECTIVE_SOURCES += util/qscroller_mac.mm
-}
diff --git a/src/gui/widgets/qabstractbutton.cpp b/src/gui/widgets/qabstractbutton.cpp
deleted file mode 100644
index d45c56b72d..0000000000
--- a/src/gui/widgets/qabstractbutton.cpp
+++ /dev/null
@@ -1,1470 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractbutton.h"
-#include "qabstractitemview.h"
-#include "qbuttongroup.h"
-#include "qabstractbutton_p.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qapplication.h"
-#include "qstyle.h"
-#include "qaction.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#define AUTO_REPEAT_DELAY 300
-#define AUTO_REPEAT_INTERVAL 100
-
-Q_GUI_EXPORT extern bool qt_tab_all_widgets;
-
-/*!
- \class QAbstractButton
-
- \brief The QAbstractButton class is the abstract base class of
- button widgets, providing functionality common to buttons.
-
- \ingroup abstractwidgets
-
- This class implements an \e abstract button.
- Subclasses of this class handle user actions, and specify how the button
- is drawn.
-
- QAbstractButton provides support for both push buttons and checkable
- (toggle) buttons. Checkable buttons are implemented in the QRadioButton
- and QCheckBox classes. Push buttons are implemented in the
- QPushButton and QToolButton classes; these also provide toggle
- behavior if required.
-
- Any button can display a label containing text and an icon. setText()
- sets the text; setIcon() sets the icon. If a button is disabled, its label
- is changed to give the button a "disabled" appearance.
-
- If the button is a text button with a string containing an
- ampersand ('&'), QAbstractButton automatically creates a shortcut
- key. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp 0
-
- The \key Alt+C shortcut is assigned to the button, i.e., when the
- user presses \key Alt+C the button will call animateClick(). See
- the \l {QShortcut#mnemonic}{QShortcut} documentation for details
- (to display an actual ampersand, use '&&').
-
- You can also set a custom shortcut key using the setShortcut()
- function. This is useful mostly for buttons that do not have any
- text, because they have no automatic shortcut.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp 1
-
- All of the buttons provided by Qt (QPushButton, QToolButton,
- QCheckBox, and QRadioButton) can display both \l text and \l{icon}{icons}.
-
- A button can be made the default button in a dialog are provided by
- QPushButton::setDefault() and QPushButton::setAutoDefault().
-
- QAbstractButton provides most of the states used for buttons:
-
- \list
-
- \o isDown() indicates whether the button is \e pressed down.
-
- \o isChecked() indicates whether the button is \e checked. Only
- checkable buttons can be checked and unchecked (see below).
-
- \o isEnabled() indicates whether the button can be pressed by the
- user.
-
- \o setAutoRepeat() sets whether the button will auto-repeat if the
- user holds it down. \l autoRepeatDelay and \l autoRepeatInterval
- define how auto-repetition is done.
-
- \o setCheckable() sets whether the button is a toggle button or not.
-
- \endlist
-
- The difference between isDown() and isChecked() is as follows.
- When the user clicks a toggle button to check it, the button is first
- \e pressed then released into the \e checked state. When the user
- clicks it again (to uncheck it), the button moves first to the
- \e pressed state, then to the \e unchecked state (isChecked() and
- isDown() are both false).
-
- QAbstractButton provides four signals:
-
- \list 1
-
- \o pressed() is emitted when the left mouse button is pressed while
- the mouse cursor is inside the button.
-
- \o released() is emitted when the left mouse button is released.
-
- \o clicked() is emitted when the button is first pressed and then
- released, when the shortcut key is typed, or when click() or
- animateClick() is called.
-
- \o toggled() is emitted when the state of a toggle button changes.
-
- \endlist
-
- To subclass QAbstractButton, you must reimplement at least
- paintEvent() to draw the button's outline and its text or pixmap. It
- is generally advisable to reimplement sizeHint() as well, and
- sometimes hitButton() (to determine whether a button press is within
- the button). For buttons with more than two states (like tri-state
- buttons), you will also have to reimplement checkStateSet() and
- nextCheckState().
-
- \sa QButtonGroup
-*/
-
-QAbstractButtonPrivate::QAbstractButtonPrivate(QSizePolicy::ControlType type)
- :
-#ifndef QT_NO_SHORTCUT
- shortcutId(0),
-#endif
- checkable(false), checked(false), autoRepeat(false), autoExclusive(false),
- down(false), blockRefresh(false), pressed(false),
-#ifndef QT_NO_BUTTONGROUP
- group(0),
-#endif
- autoRepeatDelay(AUTO_REPEAT_DELAY),
- autoRepeatInterval(AUTO_REPEAT_INTERVAL),
- controlType(type)
-{}
-
-#ifndef QT_NO_BUTTONGROUP
-
-class QButtonGroupPrivate: public QObjectPrivate
-{
- Q_DECLARE_PUBLIC(QButtonGroup)
-
-public:
- QButtonGroupPrivate():exclusive(true){}
- QList<QAbstractButton *> buttonList;
- QPointer<QAbstractButton> checkedButton;
- void detectCheckedButton();
- void notifyChecked(QAbstractButton *button);
- bool exclusive;
- QMap<QAbstractButton*, int> mapping;
-};
-
-QButtonGroup::QButtonGroup(QObject *parent)
- : QObject(*new QButtonGroupPrivate, parent)
-{
-}
-
-QButtonGroup::~QButtonGroup()
-{
- Q_D(QButtonGroup);
- for (int i = 0; i < d->buttonList.count(); ++i)
- d->buttonList.at(i)->d_func()->group = 0;
-}
-
-
-bool QButtonGroup::exclusive() const
-{
- Q_D(const QButtonGroup);
- return d->exclusive;
-}
-
-void QButtonGroup::setExclusive(bool exclusive)
-{
- Q_D(QButtonGroup);
- d->exclusive = exclusive;
-}
-
-
-// TODO: Qt 5: Merge with addButton(QAbstractButton *button, int id)
-void QButtonGroup::addButton(QAbstractButton *button)
-{
- addButton(button, -1);
-}
-
-void QButtonGroup::addButton(QAbstractButton *button, int id)
-{
- Q_D(QButtonGroup);
- if (QButtonGroup *previous = button->d_func()->group)
- previous->removeButton(button);
- button->d_func()->group = this;
- d->buttonList.append(button);
- if (id == -1) {
- QList<int> ids = d->mapping.values();
- if (ids.isEmpty())
- d->mapping[button] = -2;
- else {
- qSort(ids);
- d->mapping[button] = ids.first()-1;
- }
- } else {
- d->mapping[button] = id;
- }
-
- if (d->exclusive && button->isChecked())
- button->d_func()->notifyChecked();
-}
-
-void QButtonGroup::removeButton(QAbstractButton *button)
-{
- Q_D(QButtonGroup);
- if (d->checkedButton == button) {
- d->detectCheckedButton();
- }
- if (button->d_func()->group == this) {
- button->d_func()->group = 0;
- d->buttonList.removeAll(button);
- d->mapping.remove(button);
- }
-}
-
-QList<QAbstractButton*> QButtonGroup::buttons() const
-{
- Q_D(const QButtonGroup);
- return d->buttonList;
-}
-
-QAbstractButton *QButtonGroup::checkedButton() const
-{
- Q_D(const QButtonGroup);
- return d->checkedButton;
-}
-
-QAbstractButton *QButtonGroup::button(int id) const
-{
- Q_D(const QButtonGroup);
- return d->mapping.key(id);
-}
-
-void QButtonGroup::setId(QAbstractButton *button, int id)
-{
- Q_D(QButtonGroup);
- if (button && id != -1)
- d->mapping[button] = id;
-}
-
-int QButtonGroup::id(QAbstractButton *button) const
-{
- Q_D(const QButtonGroup);
- return d->mapping.value(button, -1);
-}
-
-int QButtonGroup::checkedId() const
-{
- Q_D(const QButtonGroup);
- return d->mapping.value(d->checkedButton, -1);
-}
-
-// detect a checked button other than the current one
-void QButtonGroupPrivate::detectCheckedButton()
-{
- QAbstractButton *previous = checkedButton;
- checkedButton = 0;
- if (exclusive)
- return;
- for (int i = 0; i < buttonList.count(); i++) {
- if (buttonList.at(i) != previous && buttonList.at(i)->isChecked()) {
- checkedButton = buttonList.at(i);
- return;
- }
- }
-}
-
-#endif // QT_NO_BUTTONGROUP
-
-QList<QAbstractButton *>QAbstractButtonPrivate::queryButtonList() const
-{
-#ifndef QT_NO_BUTTONGROUP
- if (group)
- return group->d_func()->buttonList;
-#endif
-
- QList<QAbstractButton*>candidates = parent->findChildren<QAbstractButton *>();
- if (autoExclusive) {
- for (int i = candidates.count() - 1; i >= 0; --i) {
- QAbstractButton *candidate = candidates.at(i);
- if (!candidate->autoExclusive()
-#ifndef QT_NO_BUTTONGROUP
- || candidate->group()
-#endif
- )
- candidates.removeAt(i);
- }
- }
- return candidates;
-}
-
-QAbstractButton *QAbstractButtonPrivate::queryCheckedButton() const
-{
-#ifndef QT_NO_BUTTONGROUP
- if (group)
- return group->d_func()->checkedButton;
-#endif
-
- Q_Q(const QAbstractButton);
- QList<QAbstractButton *> buttonList = queryButtonList();
- if (!autoExclusive || buttonList.count() == 1) // no group
- return 0;
-
- for (int i = 0; i < buttonList.count(); ++i) {
- QAbstractButton *b = buttonList.at(i);
- if (b->d_func()->checked && b != q)
- return b;
- }
- return checked ? const_cast<QAbstractButton *>(q) : 0;
-}
-
-void QAbstractButtonPrivate::notifyChecked()
-{
-#ifndef QT_NO_BUTTONGROUP
- Q_Q(QAbstractButton);
- if (group) {
- QAbstractButton *previous = group->d_func()->checkedButton;
- group->d_func()->checkedButton = q;
- if (group->d_func()->exclusive && previous && previous != q)
- previous->nextCheckState();
- } else
-#endif
- if (autoExclusive) {
- if (QAbstractButton *b = queryCheckedButton())
- b->setChecked(false);
- }
-}
-
-void QAbstractButtonPrivate::moveFocus(int key)
-{
- QList<QAbstractButton *> buttonList = queryButtonList();;
-#ifndef QT_NO_BUTTONGROUP
- bool exclusive = group ? group->d_func()->exclusive : autoExclusive;
-#else
- bool exclusive = autoExclusive;
-#endif
- QWidget *f = QApplication::focusWidget();
- QAbstractButton *fb = qobject_cast<QAbstractButton *>(f);
- if (!fb || !buttonList.contains(fb))
- return;
-
- QAbstractButton *candidate = 0;
- int bestScore = -1;
- QRect target = f->rect().translated(f->mapToGlobal(QPoint(0,0)));
- QPoint goal = target.center();
- uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
-
- for (int i = 0; i < buttonList.count(); ++i) {
- QAbstractButton *button = buttonList.at(i);
- if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() &&
- (autoExclusive || (button->focusPolicy() & focus_flag) == focus_flag)) {
- QRect buttonRect = button->rect().translated(button->mapToGlobal(QPoint(0,0)));
- QPoint p = buttonRect.center();
-
- //Priority to widgets that overlap on the same coordinate.
- //In that case, the distance in the direction will be used as significant score,
- //take also in account orthogonal distance in case two widget are in the same distance.
- int score;
- if ((buttonRect.x() < target.right() && target.x() < buttonRect.right())
- && (key == Qt::Key_Up || key == Qt::Key_Down)) {
- //one item's is at the vertical of the other
- score = (qAbs(p.y() - goal.y()) << 16) + qAbs(p.x() - goal.x());
- } else if ((buttonRect.y() < target.bottom() && target.y() < buttonRect.bottom())
- && (key == Qt::Key_Left || key == Qt::Key_Right) ) {
- //one item's is at the horizontal of the other
- score = (qAbs(p.x() - goal.x()) << 16) + qAbs(p.y() - goal.y());
- } else {
- score = (1 << 30) + (p.y() - goal.y()) * (p.y() - goal.y()) + (p.x() - goal.x()) * (p.x() - goal.x());
- }
-
- if (score > bestScore && candidate)
- continue;
-
- switch(key) {
- case Qt::Key_Up:
- if (p.y() < goal.y()) {
- candidate = button;
- bestScore = score;
- }
- break;
- case Qt::Key_Down:
- if (p.y() > goal.y()) {
- candidate = button;
- bestScore = score;
- }
- break;
- case Qt::Key_Left:
- if (p.x() < goal.x()) {
- candidate = button;
- bestScore = score;
- }
- break;
- case Qt::Key_Right:
- if (p.x() > goal.x()) {
- candidate = button;
- bestScore = score;
- }
- break;
- }
- }
- }
-
- if (exclusive
-#ifdef QT_KEYPAD_NAVIGATION
- && !QApplication::keypadNavigationEnabled()
-#endif
- && candidate
- && fb->d_func()->checked
- && candidate->d_func()->checkable)
- candidate->click();
-
- if (candidate) {
- if (key == Qt::Key_Up || key == Qt::Key_Left)
- candidate->setFocus(Qt::BacktabFocusReason);
- else
- candidate->setFocus(Qt::TabFocusReason);
- }
-}
-
-void QAbstractButtonPrivate::fixFocusPolicy()
-{
- Q_Q(QAbstractButton);
-#ifndef QT_NO_BUTTONGROUP
- if (!group && !autoExclusive)
-#else
- if (!autoExclusive)
-#endif
- return;
-
- QList<QAbstractButton *> buttonList = queryButtonList();
- for (int i = 0; i < buttonList.count(); ++i) {
- QAbstractButton *b = buttonList.at(i);
- if (!b->isCheckable())
- continue;
- b->setFocusPolicy((Qt::FocusPolicy) ((b == q || !q->isCheckable())
- ? (b->focusPolicy() | Qt::TabFocus)
- : (b->focusPolicy() & ~Qt::TabFocus)));
- }
-}
-
-void QAbstractButtonPrivate::init()
-{
- Q_Q(QAbstractButton);
-
- q->setFocusPolicy(Qt::FocusPolicy(q->style()->styleHint(QStyle::SH_Button_FocusPolicy)));
- q->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, controlType));
- q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- q->setForegroundRole(QPalette::ButtonText);
- q->setBackgroundRole(QPalette::Button);
-}
-
-void QAbstractButtonPrivate::refresh()
-{
- Q_Q(QAbstractButton);
-
- if (blockRefresh)
- return;
- q->update();
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(q, 0, QAccessible::StateChanged);
-#endif
-}
-
-void QAbstractButtonPrivate::click()
-{
- Q_Q(QAbstractButton);
-
- down = false;
- blockRefresh = true;
- bool changeState = true;
- if (checked && queryCheckedButton() == q) {
- // the checked button of an exclusive or autoexclusive group cannot be unchecked
-#ifndef QT_NO_BUTTONGROUP
- if (group ? group->d_func()->exclusive : autoExclusive)
-#else
- if (autoExclusive)
-#endif
- changeState = false;
- }
-
- QPointer<QAbstractButton> guard(q);
- if (changeState) {
- q->nextCheckState();
- if (!guard)
- return;
- }
- blockRefresh = false;
- refresh();
- q->repaint(); //flush paint event before invoking potentially expensive operation
- QApplication::flush();
- if (guard)
- emitReleased();
- if (guard)
- emitClicked();
-}
-
-void QAbstractButtonPrivate::emitClicked()
-{
- Q_Q(QAbstractButton);
- QPointer<QAbstractButton> guard(q);
- emit q->clicked(checked);
-#ifndef QT_NO_BUTTONGROUP
- if (guard && group) {
- emit group->buttonClicked(group->id(q));
- if (guard && group)
- emit group->buttonClicked(q);
- }
-#endif
-}
-
-void QAbstractButtonPrivate::emitPressed()
-{
- Q_Q(QAbstractButton);
- QPointer<QAbstractButton> guard(q);
- emit q->pressed();
-#ifndef QT_NO_BUTTONGROUP
- if (guard && group) {
- emit group->buttonPressed(group->id(q));
- if (guard && group)
- emit group->buttonPressed(q);
- }
-#endif
-}
-
-void QAbstractButtonPrivate::emitReleased()
-{
- Q_Q(QAbstractButton);
- QPointer<QAbstractButton> guard(q);
- emit q->released();
-#ifndef QT_NO_BUTTONGROUP
- if (guard && group) {
- emit group->buttonReleased(group->id(q));
- if (guard && group)
- emit group->buttonReleased(q);
- }
-#endif
-}
-
-/*!
- Constructs an abstract button with a \a parent.
-*/
-QAbstractButton::QAbstractButton(QWidget *parent)
- : QWidget(*new QAbstractButtonPrivate, parent, 0)
-{
- Q_D(QAbstractButton);
- d->init();
-}
-
-/*!
- Destroys the button.
- */
- QAbstractButton::~QAbstractButton()
-{
-#ifndef QT_NO_BUTTONGROUP
- Q_D(QAbstractButton);
- if (d->group)
- d->group->removeButton(this);
-#endif
-}
-
-
-/*! \internal
- */
-QAbstractButton::QAbstractButton(QAbstractButtonPrivate &dd, QWidget *parent)
- : QWidget(dd, parent, 0)
-{
- Q_D(QAbstractButton);
- d->init();
-}
-
-/*!
-\property QAbstractButton::text
-\brief the text shown on the button
-
-If the button has no text, the text() function will return a an empty
-string.
-
-If the text contains an ampersand character ('&'), a shortcut is
-automatically created for it. The character that follows the '&' will
-be used as the shortcut key. Any previous shortcut will be
-overwritten, or cleared if no shortcut is defined by the text. See the
-\l {QShortcut#mnemonic}{QShortcut} documentation for details (to
-display an actual ampersand, use '&&').
-
-There is no default text.
-*/
-
-void QAbstractButton::setText(const QString &text)
-{
- Q_D(QAbstractButton);
- if (d->text == text)
- return;
- d->text = text;
-#ifndef QT_NO_SHORTCUT
- QKeySequence newMnemonic = QKeySequence::mnemonic(text);
- setShortcut(newMnemonic);
-#endif
- d->sizeHint = QSize();
- update();
- updateGeometry();
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
-#endif
-}
-
-QString QAbstractButton::text() const
-{
- Q_D(const QAbstractButton);
- return d->text;
-}
-
-
-/*!
- \property QAbstractButton::icon
- \brief the icon shown on the button
-
- The icon's default size is defined by the GUI style, but can be
- adjusted by setting the \l iconSize property.
-*/
-void QAbstractButton::setIcon(const QIcon &icon)
-{
- Q_D(QAbstractButton);
- d->icon = icon;
- d->sizeHint = QSize();
- update();
- updateGeometry();
-}
-
-QIcon QAbstractButton::icon() const
-{
- Q_D(const QAbstractButton);
- return d->icon;
-}
-
-#ifndef QT_NO_SHORTCUT
-/*!
-\property QAbstractButton::shortcut
-\brief the mnemonic associated with the button
-*/
-
-void QAbstractButton::setShortcut(const QKeySequence &key)
-{
- Q_D(QAbstractButton);
- if (d->shortcutId != 0)
- releaseShortcut(d->shortcutId);
- d->shortcut = key;
- d->shortcutId = grabShortcut(key);
-}
-
-QKeySequence QAbstractButton::shortcut() const
-{
- Q_D(const QAbstractButton);
- return d->shortcut;
-}
-#endif // QT_NO_SHORTCUT
-
-/*!
-\property QAbstractButton::checkable
-\brief whether the button is checkable
-
-By default, the button is not checkable.
-
-\sa checked
-*/
-void QAbstractButton::setCheckable(bool checkable)
-{
- Q_D(QAbstractButton);
- if (d->checkable == checkable)
- return;
-
- d->checkable = checkable;
- d->checked = false;
-}
-
-bool QAbstractButton::isCheckable() const
-{
- Q_D(const QAbstractButton);
- return d->checkable;
-}
-
-/*!
-\property QAbstractButton::checked
-\brief whether the button is checked
-
-Only checkable buttons can be checked. By default, the button is unchecked.
-
-\sa checkable
-*/
-void QAbstractButton::setChecked(bool checked)
-{
- Q_D(QAbstractButton);
- if (!d->checkable || d->checked == checked) {
- if (!d->blockRefresh)
- checkStateSet();
- return;
- }
-
- if (!checked && d->queryCheckedButton() == this) {
- // the checked button of an exclusive or autoexclusive group cannot be unchecked
-#ifndef QT_NO_BUTTONGROUP
- if (d->group ? d->group->d_func()->exclusive : d->autoExclusive)
- return;
- if (d->group)
- d->group->d_func()->detectCheckedButton();
-#else
- if (d->autoExclusive)
- return;
-#endif
- }
-
- QPointer<QAbstractButton> guard(this);
-
- d->checked = checked;
- if (!d->blockRefresh)
- checkStateSet();
- d->refresh();
-
- if (guard && checked)
- d->notifyChecked();
- if (guard)
- emit toggled(checked);
-}
-
-bool QAbstractButton::isChecked() const
-{
- Q_D(const QAbstractButton);
- return d->checked;
-}
-
-/*!
- \property QAbstractButton::down
- \brief whether the button is pressed down
-
- If this property is true, the button is pressed down. The signals
- pressed() and clicked() are not emitted if you set this property
- to true. The default is false.
-*/
-
-void QAbstractButton::setDown(bool down)
-{
- Q_D(QAbstractButton);
- if (d->down == down)
- return;
- d->down = down;
- d->refresh();
- if (d->autoRepeat && d->down)
- d->repeatTimer.start(d->autoRepeatDelay, this);
- else
- d->repeatTimer.stop();
-}
-
-bool QAbstractButton::isDown() const
-{
- Q_D(const QAbstractButton);
- return d->down;
-}
-
-/*!
-\property QAbstractButton::autoRepeat
-\brief whether autoRepeat is enabled
-
-If autoRepeat is enabled, then the pressed(), released(), and clicked() signals are emitted at
-regular intervals when the button is down. autoRepeat is off by default.
-The initial delay and the repetition interval are defined in milliseconds by \l
-autoRepeatDelay and \l autoRepeatInterval.
-
-Note: If a button is pressed down by a shortcut key, then auto-repeat is enabled and timed by the
-system and not by this class. The pressed(), released(), and clicked() signals will be emitted
-like in the normal case.
-*/
-
-void QAbstractButton::setAutoRepeat(bool autoRepeat)
-{
- Q_D(QAbstractButton);
- if (d->autoRepeat == autoRepeat)
- return;
- d->autoRepeat = autoRepeat;
- if (d->autoRepeat && d->down)
- d->repeatTimer.start(d->autoRepeatDelay, this);
- else
- d->repeatTimer.stop();
-}
-
-bool QAbstractButton::autoRepeat() const
-{
- Q_D(const QAbstractButton);
- return d->autoRepeat;
-}
-
-/*!
- \property QAbstractButton::autoRepeatDelay
- \brief the initial delay of auto-repetition
- \since 4.2
-
- If \l autoRepeat is enabled, then autoRepeatDelay defines the initial
- delay in milliseconds before auto-repetition kicks in.
-
- \sa autoRepeat, autoRepeatInterval
-*/
-
-void QAbstractButton::setAutoRepeatDelay(int autoRepeatDelay)
-{
- Q_D(QAbstractButton);
- d->autoRepeatDelay = autoRepeatDelay;
-}
-
-int QAbstractButton::autoRepeatDelay() const
-{
- Q_D(const QAbstractButton);
- return d->autoRepeatDelay;
-}
-
-/*!
- \property QAbstractButton::autoRepeatInterval
- \brief the interval of auto-repetition
- \since 4.2
-
- If \l autoRepeat is enabled, then autoRepeatInterval defines the
- length of the auto-repetition interval in millisecons.
-
- \sa autoRepeat, autoRepeatDelay
-*/
-
-void QAbstractButton::setAutoRepeatInterval(int autoRepeatInterval)
-{
- Q_D(QAbstractButton);
- d->autoRepeatInterval = autoRepeatInterval;
-}
-
-int QAbstractButton::autoRepeatInterval() const
-{
- Q_D(const QAbstractButton);
- return d->autoRepeatInterval;
-}
-
-
-
-/*!
-\property QAbstractButton::autoExclusive
-\brief whether auto-exclusivity is enabled
-
-If auto-exclusivity is enabled, checkable buttons that belong to the
-same parent widget behave as if they were part of the same
-exclusive button group. In an exclusive button group, only one button
-can be checked at any time; checking another button automatically
-unchecks the previously checked one.
-
-The property has no effect on buttons that belong to a button
-group.
-
-autoExclusive is off by default, except for radio buttons.
-
-\sa QRadioButton
-*/
-void QAbstractButton::setAutoExclusive(bool autoExclusive)
-{
- Q_D(QAbstractButton);
- d->autoExclusive = autoExclusive;
-}
-
-bool QAbstractButton::autoExclusive() const
-{
- Q_D(const QAbstractButton);
- return d->autoExclusive;
-}
-
-#ifndef QT_NO_BUTTONGROUP
-/*!
- Returns the group that this button belongs to.
-
- If the button is not a member of any QButtonGroup, this function
- returns 0.
-
- \sa QButtonGroup
-*/
-QButtonGroup *QAbstractButton::group() const
-{
- Q_D(const QAbstractButton);
- return d->group;
-}
-#endif // QT_NO_BUTTONGROUP
-
-/*!
-Performs an animated click: the button is pressed immediately, and
-released \a msec milliseconds later (the default is 100 ms).
-
-Calling this function again before the button was released will reset
-the release timer.
-
-All signals associated with a click are emitted as appropriate.
-
-This function does nothing if the button is \link setEnabled()
-disabled. \endlink
-
-\sa click()
-*/
-void QAbstractButton::animateClick(int msec)
-{
- if (!isEnabled())
- return;
- Q_D(QAbstractButton);
- if (d->checkable && focusPolicy() & Qt::ClickFocus)
- setFocus();
- setDown(true);
- repaint(); //flush paint event before invoking potentially expensive operation
- QApplication::flush();
- if (!d->animateTimer.isActive())
- d->emitPressed();
- d->animateTimer.start(msec, this);
-}
-
-/*!
-Performs a click.
-
-All the usual signals associated with a click are emitted as
-appropriate. If the button is checkable, the state of the button is
-toggled.
-
-This function does nothing if the button is \link setEnabled()
-disabled. \endlink
-
-\sa animateClick()
- */
-void QAbstractButton::click()
-{
- if (!isEnabled())
- return;
- Q_D(QAbstractButton);
- QPointer<QAbstractButton> guard(this);
- d->down = true;
- d->emitPressed();
- if (guard) {
- d->down = false;
- nextCheckState();
- if (guard)
- d->emitReleased();
- if (guard)
- d->emitClicked();
- }
-}
-
-/*! \fn void QAbstractButton::toggle()
-
- Toggles the state of a checkable button.
-
- \sa checked
-*/
-void QAbstractButton::toggle()
-{
- Q_D(QAbstractButton);
- setChecked(!d->checked);
-}
-
-
-/*! This virtual handler is called when setChecked() was called,
-unless it was called from within nextCheckState(). It allows
-subclasses to reset their intermediate button states.
-
-\sa nextCheckState()
- */
-void QAbstractButton::checkStateSet()
-{
-}
-
-/*! This virtual handler is called when a button is clicked. The
-default implementation calls setChecked(!isChecked()) if the button
-isCheckable(). It allows subclasses to implement intermediate button
-states.
-
-\sa checkStateSet()
-*/
-void QAbstractButton::nextCheckState()
-{
- if (isCheckable())
- setChecked(!isChecked());
-}
-
-/*!
-Returns true if \a pos is inside the clickable button rectangle;
-otherwise returns false.
-
-By default, the clickable area is the entire widget. Subclasses
-may reimplement this function to provide support for clickable
-areas of different shapes and sizes.
-*/
-bool QAbstractButton::hitButton(const QPoint &pos) const
-{
- return rect().contains(pos);
-}
-
-/*! \reimp */
-bool QAbstractButton::event(QEvent *e)
-{
- // as opposed to other widgets, disabled buttons accept mouse
- // events. This avoids surprising click-through scenarios
- if (!isEnabled()) {
- switch(e->type()) {
- case QEvent::TabletPress:
- case QEvent::TabletRelease:
- case QEvent::TabletMove:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- case QEvent::HoverMove:
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::ContextMenu:
-#ifndef QT_NO_WHEELEVENT
- case QEvent::Wheel:
-#endif
- return true;
- default:
- break;
- }
- }
-
-#ifndef QT_NO_SHORTCUT
- if (e->type() == QEvent::Shortcut) {
- Q_D(QAbstractButton);
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- if (d->shortcutId != se->shortcutId())
- return false;
- if (!se->isAmbiguous()) {
- if (!d->animateTimer.isActive())
- animateClick();
- } else {
- if (focusPolicy() != Qt::NoFocus)
- setFocus(Qt::ShortcutFocusReason);
- window()->setAttribute(Qt::WA_KeyboardFocusChange);
- }
- return true;
- }
-#endif
- return QWidget::event(e);
-}
-
-/*! \reimp */
-void QAbstractButton::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QAbstractButton);
- if (e->button() != Qt::LeftButton) {
- e->ignore();
- return;
- }
- if (hitButton(e->pos())) {
- setDown(true);
- d->pressed = true;
- repaint(); //flush paint event before invoking potentially expensive operation
- QApplication::flush();
- d->emitPressed();
- e->accept();
- } else {
- e->ignore();
- }
-}
-
-/*! \reimp */
-void QAbstractButton::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QAbstractButton);
- d->pressed = false;
-
- if (e->button() != Qt::LeftButton) {
- e->ignore();
- return;
- }
-
- if (!d->down) {
- e->ignore();
- return;
- }
-
- if (hitButton(e->pos())) {
- d->repeatTimer.stop();
- d->click();
- e->accept();
- } else {
- setDown(false);
- e->ignore();
- }
-}
-
-/*! \reimp */
-void QAbstractButton::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QAbstractButton);
- if (!(e->buttons() & Qt::LeftButton) || !d->pressed) {
- e->ignore();
- return;
- }
-
- if (hitButton(e->pos()) != d->down) {
- setDown(!d->down);
- repaint(); //flush paint event before invoking potentially expensive operation
- QApplication::flush();
- if (d->down)
- d->emitPressed();
- else
- d->emitReleased();
- e->accept();
- } else if (!hitButton(e->pos())) {
- e->ignore();
- }
-}
-
-/*! \reimp */
-void QAbstractButton::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QAbstractButton);
- bool next = true;
- switch (e->key()) {
- case Qt::Key_Enter:
- case Qt::Key_Return:
- e->ignore();
- break;
- case Qt::Key_Select:
- case Qt::Key_Space:
- if (!e->isAutoRepeat()) {
- setDown(true);
- repaint(); //flush paint event before invoking potentially expensive operation
- QApplication::flush();
- d->emitPressed();
- }
- break;
- case Qt::Key_Up:
- case Qt::Key_Left:
- next = false;
- // fall through
- case Qt::Key_Right:
- case Qt::Key_Down:
-#ifdef QT_KEYPAD_NAVIGATION
- if ((QApplication::keypadNavigationEnabled()
- && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right))
- || (!QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
- || (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down))) {
- e->ignore();
- return;
- }
-#endif
- QWidget *pw;
- if (d->autoExclusive
-#ifndef QT_NO_BUTTONGROUP
- || d->group
-#endif
-#ifndef QT_NO_ITEMVIEWS
- || ((pw = parentWidget()) && qobject_cast<QAbstractItemView *>(pw->parentWidget()))
-#endif
- ) {
- // ### Using qobject_cast to check if the parent is a viewport of
- // QAbstractItemView is a crude hack, and should be revisited and
- // cleaned up when fixing task 194373. It's here to ensure that we
- // keep compatibility outside QAbstractItemView.
- d->moveFocus(e->key());
- if (hasFocus()) // nothing happend, propagate
- e->ignore();
- } else {
- focusNextPrevChild(next);
- }
- break;
- case Qt::Key_Escape:
- if (d->down) {
- setDown(false);
- repaint(); //flush paint event before invoking potentially expensive operation
- QApplication::flush();
- d->emitReleased();
- break;
- }
- // fall through
- default:
- e->ignore();
- }
-}
-
-/*! \reimp */
-void QAbstractButton::keyReleaseEvent(QKeyEvent *e)
-{
- Q_D(QAbstractButton);
-
- if (!e->isAutoRepeat())
- d->repeatTimer.stop();
-
- switch (e->key()) {
- case Qt::Key_Select:
- case Qt::Key_Space:
- if (!e->isAutoRepeat() && d->down)
- d->click();
- break;
- default:
- e->ignore();
- }
-}
-
-/*!\reimp
- */
-void QAbstractButton::timerEvent(QTimerEvent *e)
-{
- Q_D(QAbstractButton);
- if (e->timerId() == d->repeatTimer.timerId()) {
- d->repeatTimer.start(d->autoRepeatInterval, this);
- if (d->down) {
- QPointer<QAbstractButton> guard(this);
- nextCheckState();
- if (guard)
- d->emitReleased();
- if (guard)
- d->emitClicked();
- if (guard)
- d->emitPressed();
- }
- } else if (e->timerId() == d->animateTimer.timerId()) {
- d->animateTimer.stop();
- d->click();
- }
-}
-
-/*! \reimp */
-void QAbstractButton::focusInEvent(QFocusEvent *e)
-{
- Q_D(QAbstractButton);
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled())
-#endif
- d->fixFocusPolicy();
- QWidget::focusInEvent(e);
-}
-
-/*! \reimp */
-void QAbstractButton::focusOutEvent(QFocusEvent *e)
-{
- Q_D(QAbstractButton);
- if (e->reason() != Qt::PopupFocusReason)
- d->down = false;
- QWidget::focusOutEvent(e);
-}
-
-/*! \reimp */
-void QAbstractButton::changeEvent(QEvent *e)
-{
- Q_D(QAbstractButton);
- switch (e->type()) {
- case QEvent::EnabledChange:
- if (!isEnabled())
- setDown(false);
- break;
- default:
- d->sizeHint = QSize();
- break;
- }
- QWidget::changeEvent(e);
-}
-
-/*!
- \fn void QAbstractButton::paintEvent(QPaintEvent *e)
- \reimp
-*/
-
-/*!
- \fn void QAbstractButton::pressed()
-
- This signal is emitted when the button is pressed down.
-
- \sa released(), clicked()
-*/
-
-/*!
- \fn void QAbstractButton::released()
-
- This signal is emitted when the button is released.
-
- \sa pressed(), clicked(), toggled()
-*/
-
-/*!
-\fn void QAbstractButton::clicked(bool checked)
-
-This signal is emitted when the button is activated (i.e. pressed down
-then released while the mouse cursor is inside the button), when the
-shortcut key is typed, or when click() or animateClick() is called.
-Notably, this signal is \e not emitted if you call setDown(),
-setChecked() or toggle().
-
-If the button is checkable, \a checked is true if the button is
-checked, or false if the button is unchecked.
-
-\sa pressed(), released(), toggled()
-*/
-
-/*!
-\fn void QAbstractButton::toggled(bool checked)
-
-This signal is emitted whenever a checkable button changes its state.
-\a checked is true if the button is checked, or false if the button is
-unchecked.
-
-This may be the result of a user action, click() slot activation,
-or because setChecked() was called.
-
-The states of buttons in exclusive button groups are updated before this
-signal is emitted. This means that slots can act on either the "off"
-signal or the "on" signal emitted by the buttons in the group whose
-states have changed.
-
-For example, a slot that reacts to signals emitted by newly checked
-buttons but which ignores signals from buttons that have been unchecked
-can be implemented using the following pattern:
-
-\snippet doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp 2
-
-Button groups can be created using the QButtonGroup class, and
-updates to the button states monitored with the
-\l{QButtonGroup::buttonClicked()} signal.
-
-\sa checked, clicked()
-*/
-
-/*!
- \property QAbstractButton::iconSize
- \brief the icon size used for this button.
-
- The default size is defined by the GUI style. This is a maximum
- size for the icons. Smaller icons will not be scaled up.
-*/
-
-QSize QAbstractButton::iconSize() const
-{
- Q_D(const QAbstractButton);
- if (d->iconSize.isValid())
- return d->iconSize;
- int e = style()->pixelMetric(QStyle::PM_ButtonIconSize, 0, this);
- return QSize(e, e);
-}
-
-void QAbstractButton::setIconSize(const QSize &size)
-{
- Q_D(QAbstractButton);
- if (d->iconSize == size)
- return;
-
- d->iconSize = size;
- d->sizeHint = QSize();
- updateGeometry();
- if (isVisible()) {
- update();
- }
-}
-
-
-#ifdef QT3_SUPPORT
-/*!
- Use icon() instead.
-*/
-QIcon *QAbstractButton::iconSet() const
-{
- Q_D(const QAbstractButton);
- if (!d->icon.isNull())
- return const_cast<QIcon *>(&d->icon);
- return 0;
-}
-
-/*!
- Use QAbstractButton(QWidget *) instead.
-
- Call setObjectName() if you want to specify an object name, and
- setParent() if you want to set the window flags.
-*/
-QAbstractButton::QAbstractButton(QWidget *parent, const char *name, Qt::WindowFlags f)
- : QWidget(*new QAbstractButtonPrivate, parent, f)
-{
- Q_D(QAbstractButton);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*! \fn bool QAbstractButton::isOn() const
-
- Use isChecked() instead.
-*/
-
-/*!
- \fn QPixmap *QAbstractButton::pixmap() const
-
- This compatibility function always returns 0.
-
- Use icon() instead.
-*/
-
-/*! \fn void QAbstractButton::setPixmap(const QPixmap &p)
-
- Use setIcon() instead.
-*/
-
-/*! \fn void QAbstractButton::setIconSet(const QIcon &icon)
-
- Use setIcon() instead.
-*/
-
-/*! \fn void QAbstractButton::setOn(bool b)
-
- Use setChecked() instead.
-*/
-
-/*! \fn bool QAbstractButton::isToggleButton() const
-
- Use isCheckable() instead.
-*/
-
-/*!
- \fn void QAbstractButton::setToggleButton(bool b)
-
- Use setCheckable() instead.
-*/
-
-/*! \fn void QAbstractButton::setAccel(const QKeySequence &key)
-
- Use setShortcut() instead.
-*/
-
-/*! \fn QKeySequence QAbstractButton::accel() const
-
- Use shortcut() instead.
-*/
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qabstractbutton.h b/src/gui/widgets/qabstractbutton.h
deleted file mode 100644
index abdc11012c..0000000000
--- a/src/gui/widgets/qabstractbutton.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTBUTTON_H
-#define QABSTRACTBUTTON_H
-
-#include <QtGui/qicon.h>
-#include <QtGui/qkeysequence.h>
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QButtonGroup;
-class QAbstractButtonPrivate;
-
-class Q_GUI_EXPORT QAbstractButton : public QWidget
-{
- Q_OBJECT
-
- Q_PROPERTY(QString text READ text WRITE setText)
- Q_PROPERTY(QIcon icon READ icon WRITE setIcon)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
-#ifndef QT_NO_SHORTCUT
- Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut)
-#endif
- Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable)
- Q_PROPERTY(bool checked READ isChecked WRITE setChecked DESIGNABLE isCheckable NOTIFY toggled USER true)
- Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat)
- Q_PROPERTY(bool autoExclusive READ autoExclusive WRITE setAutoExclusive)
- Q_PROPERTY(int autoRepeatDelay READ autoRepeatDelay WRITE setAutoRepeatDelay)
- Q_PROPERTY(int autoRepeatInterval READ autoRepeatInterval WRITE setAutoRepeatInterval)
- Q_PROPERTY(bool down READ isDown WRITE setDown DESIGNABLE false)
-
-public:
- explicit QAbstractButton(QWidget* parent=0);
- ~QAbstractButton();
-
- void setText(const QString &text);
- QString text() const;
-
- void setIcon(const QIcon &icon);
- QIcon icon() const;
-
- QSize iconSize() const;
-
-#ifndef QT_NO_SHORTCUT
- void setShortcut(const QKeySequence &key);
- QKeySequence shortcut() const;
-#endif
-
- void setCheckable(bool);
- bool isCheckable() const;
-
- bool isChecked() const;
-
- void setDown(bool);
- bool isDown() const;
-
- void setAutoRepeat(bool);
- bool autoRepeat() const;
-
- void setAutoRepeatDelay(int);
- int autoRepeatDelay() const;
-
- void setAutoRepeatInterval(int);
- int autoRepeatInterval() const;
-
- void setAutoExclusive(bool);
- bool autoExclusive() const;
-
-#ifndef QT_NO_BUTTONGROUP
- QButtonGroup *group() const;
-#endif
-
-public Q_SLOTS:
- void setIconSize(const QSize &size);
- void animateClick(int msec = 100);
- void click();
- void toggle();
- void setChecked(bool);
-
-Q_SIGNALS:
- void pressed();
- void released();
- void clicked(bool checked = false);
- void toggled(bool checked);
-
-protected:
- virtual void paintEvent(QPaintEvent *e) = 0;
- virtual bool hitButton(const QPoint &pos) const;
- virtual void checkStateSet();
- virtual void nextCheckState();
-
- bool event(QEvent *e);
- void keyPressEvent(QKeyEvent *e);
- void keyReleaseEvent(QKeyEvent *e);
- void mousePressEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
- void mouseMoveEvent(QMouseEvent *e);
- void focusInEvent(QFocusEvent *e);
- void focusOutEvent(QFocusEvent *e);
- void changeEvent(QEvent *e);
- void timerEvent(QTimerEvent *e);
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QAbstractButton(QWidget *parent, const char *name, Qt::WindowFlags f=0);
- inline QT3_SUPPORT bool isOn() const { return isChecked(); }
- inline QT3_SUPPORT const QPixmap *pixmap() const { return 0; } // help styles compile
- inline QT3_SUPPORT void setPixmap( const QPixmap &p ) {
- setIcon(QIcon(p));
- setIconSize(p.size());
- }
- QT3_SUPPORT QIcon *iconSet() const;
- inline QT3_SUPPORT void setIconSet(const QIcon &icon) { setIcon(icon); }
- inline QT3_SUPPORT bool isToggleButton() const { return isCheckable(); }
- inline QT3_SUPPORT void setToggleButton(bool b) { setCheckable(b); }
- inline QT3_SUPPORT void setAccel(const QKeySequence &key) { setShortcut(key); }
- inline QT3_SUPPORT QKeySequence accel() const { return shortcut(); }
-
-public Q_SLOTS:
- inline QT_MOC_COMPAT void setOn(bool b) { setChecked(b); }
-#endif
-
-protected:
- QAbstractButton(QAbstractButtonPrivate &dd, QWidget* parent = 0);
-
-private:
- Q_DECLARE_PRIVATE(QAbstractButton)
- Q_DISABLE_COPY(QAbstractButton)
- friend class QButtonGroup;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTBUTTON_H
diff --git a/src/gui/widgets/qabstractbutton_p.h b/src/gui/widgets/qabstractbutton_p.h
deleted file mode 100644
index e3f71e409a..0000000000
--- a/src/gui/widgets/qabstractbutton_p.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTBUTTON_P_H
-#define QABSTRACTBUTTON_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qbasictimer.h"
-#include "private/qwidget_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QAbstractButtonPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractButton)
-public:
- QAbstractButtonPrivate(QSizePolicy::ControlType type = QSizePolicy::DefaultType);
-
- QString text;
- QIcon icon;
- QSize iconSize;
-#ifndef QT_NO_SHORTCUT
- QKeySequence shortcut;
- int shortcutId;
-#endif
- uint checkable :1;
- uint checked :1;
- uint autoRepeat :1;
- uint autoExclusive :1;
- uint down :1;
- uint blockRefresh :1;
- uint pressed : 1;
-
-#ifndef QT_NO_BUTTONGROUP
- QButtonGroup* group;
-#endif
- QBasicTimer repeatTimer;
- QBasicTimer animateTimer;
-
- int autoRepeatDelay, autoRepeatInterval;
-
- QSizePolicy::ControlType controlType;
- mutable QSize sizeHint;
-
- void init();
- void click();
- void refresh();
-
- QList<QAbstractButton *>queryButtonList() const;
- QAbstractButton *queryCheckedButton() const;
- void notifyChecked();
- void moveFocus(int key);
- void fixFocusPolicy();
-
- void emitPressed();
- void emitReleased();
- void emitClicked();
-};
-
-QT_END_NAMESPACE
-
-#endif // QABSTRACTBUTTON_P_H
diff --git a/src/gui/widgets/qabstractscrollarea.cpp b/src/gui/widgets/qabstractscrollarea.cpp
deleted file mode 100644
index dabfec0225..0000000000
--- a/src/gui/widgets/qabstractscrollarea.cpp
+++ /dev/null
@@ -1,1506 +0,0 @@
-/****************************************************************************
-**
-** 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 "qabstractscrollarea.h"
-
-#ifndef QT_NO_SCROLLAREA
-
-#include "qscrollbar.h"
-#include "qapplication.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qevent.h"
-#include "qdebug.h"
-#include "qboxlayout.h"
-#include "qpainter.h"
-#include "qmargins.h"
-
-#include <QDebug>
-
-#include "qabstractscrollarea_p.h"
-#include <qwidget.h>
-
-#include <private/qapplication_p.h>
-
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-#ifdef Q_WS_WIN
-# include <qlibrary.h>
-# include <windows.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAbstractScrollArea
- \brief The QAbstractScrollArea widget provides a scrolling area with
- on-demand scroll bars.
-
- \ingroup abstractwidgets
-
- QAbstractScrollArea is a low-level abstraction of a scrolling
- area. The area provides a central widget called the viewport, in
- which the contents of the area is to be scrolled (i.e, the
- visible parts of the contents are rendered in the viewport).
-
- Next to the viewport is a vertical scroll bar, and below is a
- horizontal scroll bar. When all of the area contents fits in the
- viewport, each scroll bar can be either visible or hidden
- depending on the scroll bar's Qt::ScrollBarPolicy. When a scroll
- bar is hidden, the viewport expands in order to cover all
- available space. When a scroll bar becomes visible again, the
- viewport shrinks in order to make room for the scroll bar.
-
- It is possible to reserve a margin area around the viewport, see
- setViewportMargins(). The feature is mostly used to place a
- QHeaderView widget above or beside the scrolling area. Subclasses
- of QAbstractScrollArea should implement margins.
-
- When inheriting QAbstractScrollArea, you need to do the
- following:
-
- \list
- \o Control the scroll bars by setting their
- range, value, page step, and tracking their
- movements.
- \o Draw the contents of the area in the viewport according
- to the values of the scroll bars.
- \o Handle events received by the viewport in
- viewportEvent() - notably resize events.
- \o Use \c{viewport->update()} to update the contents of the
- viewport instead of \l{QWidget::update()}{update()}
- as all painting operations take place on the viewport.
- \endlist
-
- With a scroll bar policy of Qt::ScrollBarAsNeeded (the default),
- QAbstractScrollArea shows scroll bars when they provide a non-zero
- scrolling range, and hides them otherwise.
-
- The scroll bars and viewport should be updated whenever the viewport
- receives a resize event or the size of the contents changes.
- The viewport also needs to be updated when the scroll bars
- values change. The initial values of the scroll bars are often
- set when the area receives new contents.
-
- We give a simple example, in which we have implemented a scroll area
- that can scroll any QWidget. We make the widget a child of the
- viewport; this way, we do not have to calculate which part of
- the widget to draw but can simply move the widget with
- QWidget::move(). When the area contents or the viewport size
- changes, we do the following:
-
- \snippet doc/src/snippets/myscrollarea.cpp 1
-
- When the scroll bars change value, we need to update the widget
- position, i.e., find the part of the widget that is to be drawn in
- the viewport:
-
- \snippet doc/src/snippets/myscrollarea.cpp 0
-
- In order to track scroll bar movements, reimplement the virtual
- function scrollContentsBy(). In order to fine-tune scrolling
- behavior, connect to a scroll bar's
- QAbstractSlider::actionTriggered() signal and adjust the \l
- QAbstractSlider::sliderPosition as you wish.
-
- For convenience, QAbstractScrollArea makes all viewport events
- available in the virtual viewportEvent() handler. QWidget's
- specialized handlers are remapped to viewport events in the cases
- where this makes sense. The remapped specialized handlers are:
- paintEvent(), mousePressEvent(), mouseReleaseEvent(),
- mouseDoubleClickEvent(), mouseMoveEvent(), wheelEvent(),
- dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(), dropEvent(),
- contextMenuEvent(), and resizeEvent().
-
- QScrollArea, which inherits QAbstractScrollArea, provides smooth
- scrolling for any QWidget (i.e., the widget is scrolled pixel by
- pixel). You only need to subclass QAbstractScrollArea if you need
- more specialized behavior. This is, for instance, true if the
- entire contents of the area is not suitable for being drawn on a
- QWidget or if you do not want smooth scrolling.
-
- \sa QScrollArea
-*/
-
-QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate()
- :hbar(0), vbar(0), vbarpolicy(Qt::ScrollBarAsNeeded), hbarpolicy(Qt::ScrollBarAsNeeded),
- viewport(0), cornerWidget(0), left(0), top(0), right(0), bottom(0),
- xoffset(0), yoffset(0), viewportFilter(0)
-#ifdef Q_WS_WIN
- , singleFingerPanEnabled(false)
-#endif
-{
-}
-
-QAbstractScrollAreaScrollBarContainer::QAbstractScrollAreaScrollBarContainer(Qt::Orientation orientation, QWidget *parent)
- :QWidget(parent), scrollBar(new QScrollBar(orientation, this)),
- layout(new QBoxLayout(orientation == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom)),
- orientation(orientation)
-{
- setLayout(layout);
- layout->setMargin(0);
- layout->setSpacing(0);
- layout->addWidget(scrollBar);
-}
-
-/*! \internal
- Adds a widget to the scroll bar container.
-*/
-void QAbstractScrollAreaScrollBarContainer::addWidget(QWidget *widget, LogicalPosition position)
-{
- QSizePolicy policy = widget->sizePolicy();
- if (orientation == Qt::Vertical)
- policy.setHorizontalPolicy(QSizePolicy::Ignored);
- else
- policy.setVerticalPolicy(QSizePolicy::Ignored);
- widget->setSizePolicy(policy);
- widget->setParent(this);
-
- const int insertIndex = (position & LogicalLeft) ? 0 : scrollBarLayoutIndex() + 1;
- layout->insertWidget(insertIndex, widget);
-}
-
-/*! \internal
- Retuns a list of scroll bar widgets for the given position. The scroll bar
- itself is not returned.
-*/
-QWidgetList QAbstractScrollAreaScrollBarContainer::widgets(LogicalPosition position)
-{
- QWidgetList list;
- const int scrollBarIndex = scrollBarLayoutIndex();
- if (position == LogicalLeft) {
- for (int i = 0; i < scrollBarIndex; ++i)
- list.append(layout->itemAt(i)->widget());
- } else if (position == LogicalRight) {
- const int layoutItemCount = layout->count();
- for (int i = scrollBarIndex + 1; i < layoutItemCount; ++i)
- list.append(layout->itemAt(i)->widget());
- }
- return list;
-}
-
-/*! \internal
- Returns the layout index for the scroll bar. This needs to be
- recalculated by a linear search for each use, since items in
- the layout can be removed at any time (i.e. when a widget is
- deleted or re-parented).
-*/
-int QAbstractScrollAreaScrollBarContainer::scrollBarLayoutIndex() const
-{
- const int layoutItemCount = layout->count();
- for (int i = 0; i < layoutItemCount; ++i) {
- if (qobject_cast<QScrollBar *>(layout->itemAt(i)->widget()))
- return i;
- }
- return -1;
-}
-
-/*! \internal
-*/
-void QAbstractScrollAreaPrivate::replaceScrollBar(QScrollBar *scrollBar,
- Qt::Orientation orientation)
-{
- Q_Q(QAbstractScrollArea);
-
- QAbstractScrollAreaScrollBarContainer *container = scrollBarContainers[orientation];
- bool horizontal = (orientation == Qt::Horizontal);
- QScrollBar *oldBar = horizontal ? hbar : vbar;
- if (horizontal)
- hbar = scrollBar;
- else
- vbar = scrollBar;
- scrollBar->setParent(container);
- container->scrollBar = scrollBar;
- container->layout->removeWidget(oldBar);
- container->layout->insertWidget(0, scrollBar);
- scrollBar->setVisible(oldBar->isVisibleTo(container));
- scrollBar->setInvertedAppearance(oldBar->invertedAppearance());
- scrollBar->setInvertedControls(oldBar->invertedControls());
- scrollBar->setRange(oldBar->minimum(), oldBar->maximum());
- scrollBar->setOrientation(oldBar->orientation());
- scrollBar->setPageStep(oldBar->pageStep());
- scrollBar->setSingleStep(oldBar->singleStep());
- scrollBar->setSliderDown(oldBar->isSliderDown());
- scrollBar->setSliderPosition(oldBar->sliderPosition());
- scrollBar->setTracking(oldBar->hasTracking());
- scrollBar->setValue(oldBar->value());
- delete oldBar;
-
- QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
- q, horizontal ? SLOT(_q_hslide(int)) : SLOT(_q_vslide(int)));
- QObject::connect(scrollBar, SIGNAL(rangeChanged(int,int)),
- q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
-}
-
-void QAbstractScrollAreaPrivate::init()
-{
- Q_Q(QAbstractScrollArea);
- viewport = new QWidget(q);
- viewport->setObjectName(QLatin1String("qt_scrollarea_viewport"));
- viewport->setBackgroundRole(QPalette::Base);
- viewport->setAutoFillBackground(true);
- scrollBarContainers[Qt::Horizontal] = new QAbstractScrollAreaScrollBarContainer(Qt::Horizontal, q);
- scrollBarContainers[Qt::Horizontal]->setObjectName(QLatin1String("qt_scrollarea_hcontainer"));
- hbar = scrollBarContainers[Qt::Horizontal]->scrollBar;
- hbar->setRange(0,0);
- scrollBarContainers[Qt::Horizontal]->setVisible(false);
- QObject::connect(hbar, SIGNAL(valueChanged(int)), q, SLOT(_q_hslide(int)));
- QObject::connect(hbar, SIGNAL(rangeChanged(int,int)), q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
- scrollBarContainers[Qt::Vertical] = new QAbstractScrollAreaScrollBarContainer(Qt::Vertical, q);
- scrollBarContainers[Qt::Vertical]->setObjectName(QLatin1String("qt_scrollarea_vcontainer"));
- vbar = scrollBarContainers[Qt::Vertical]->scrollBar;
- vbar->setRange(0,0);
- scrollBarContainers[Qt::Vertical]->setVisible(false);
- QObject::connect(vbar, SIGNAL(valueChanged(int)), q, SLOT(_q_vslide(int)));
- QObject::connect(vbar, SIGNAL(rangeChanged(int,int)), q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
- viewportFilter.reset(new QAbstractScrollAreaFilter(this));
- viewport->installEventFilter(viewportFilter.data());
- viewport->setFocusProxy(q);
- q->setFocusPolicy(Qt::WheelFocus);
- q->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
- q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- layoutChildren();
-#ifndef Q_WS_MAC
-# ifndef QT_NO_GESTURES
- viewport->grabGesture(Qt::PanGesture);
-# endif
-#endif
-#ifdef Q_WS_MAEMO_5
-# ifndef QT_NO_GESTURES
- // viewport->grabGesture(Qt::TouchFlickGesture);
-# endif
-#endif
-}
-
-#ifdef Q_WS_WIN
-void QAbstractScrollAreaPrivate::setSingleFingerPanEnabled(bool on)
-{
- singleFingerPanEnabled = on;
- QWidgetPrivate *dd = static_cast<QWidgetPrivate *>(QObjectPrivate::get(viewport));
- if (dd)
- dd->winSetupGestures();
-}
-#endif // Q_WS_WIN
-
-void QAbstractScrollAreaPrivate::layoutChildren()
-{
- Q_Q(QAbstractScrollArea);
- bool needh = (hbarpolicy == Qt::ScrollBarAlwaysOn
- || (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum()));
-
- bool needv = (vbarpolicy == Qt::ScrollBarAlwaysOn
- || (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum()));
-
-#ifdef Q_WS_MAC
- QWidget * const window = q->window();
-
- // Use small scroll bars for tool windows, to match the native size grip.
- bool hbarIsSmall = hbar->testAttribute(Qt::WA_MacSmallSize);
- bool vbarIsSmall = vbar->testAttribute(Qt::WA_MacSmallSize);
- const Qt::WindowType windowType = window->windowType();
- if (windowType == Qt::Tool) {
- if (!hbarIsSmall) {
- hbar->setAttribute(Qt::WA_MacMiniSize, false);
- hbar->setAttribute(Qt::WA_MacNormalSize, false);
- hbar->setAttribute(Qt::WA_MacSmallSize, true);
- }
- if (!vbarIsSmall) {
- vbar->setAttribute(Qt::WA_MacMiniSize, false);
- vbar->setAttribute(Qt::WA_MacNormalSize, false);
- vbar->setAttribute(Qt::WA_MacSmallSize, true);
- }
- } else {
- if (hbarIsSmall) {
- hbar->setAttribute(Qt::WA_MacMiniSize, false);
- hbar->setAttribute(Qt::WA_MacNormalSize, false);
- hbar->setAttribute(Qt::WA_MacSmallSize, false);
- }
- if (vbarIsSmall) {
- vbar->setAttribute(Qt::WA_MacMiniSize, false);
- vbar->setAttribute(Qt::WA_MacNormalSize, false);
- vbar->setAttribute(Qt::WA_MacSmallSize, false);
- }
- }
-#endif
-
- const int hsbExt = hbar->sizeHint().height();
- const int vsbExt = vbar->sizeHint().width();
- const QPoint extPoint(vsbExt, hsbExt);
- const QSize extSize(vsbExt, hsbExt);
-
- const QRect widgetRect = q->rect();
- QStyleOption opt(0);
- opt.init(q);
-
- const bool hasCornerWidget = (cornerWidget != 0);
-
-// If the scroll bars are at the very right and bottom of the window we
-// move their positions to be aligned with the size grip.
-#ifdef Q_WS_MAC
- // Check if a native sizegrip is present.
- bool hasMacReverseSizeGrip = false;
- bool hasMacSizeGrip = false;
- bool nativeGripPresent = false;
- if (q->testAttribute(Qt::WA_WState_Created))
- nativeGripPresent = qt_mac_checkForNativeSizeGrip(q);
-
- if (nativeGripPresent) {
- // Look for a native size grip at the visual window bottom right and at the
- // absolute window bottom right. In reverse mode, the native size grip does not
- // swich side, so we need to check if it is on the "wrong side".
- const QPoint scrollAreaBottomRight = q->mapTo(window, widgetRect.bottomRight() - QPoint(frameWidth, frameWidth));
- const QPoint windowBottomRight = window->rect().bottomRight();
- const QPoint visualWindowBottomRight = QStyle::visualPos(opt.direction, opt.rect, windowBottomRight);
- const QPoint offset = windowBottomRight - scrollAreaBottomRight;
- const QPoint visualOffset = visualWindowBottomRight - scrollAreaBottomRight;
- hasMacSizeGrip = (visualOffset.manhattanLength() < vsbExt);
- hasMacReverseSizeGrip = (hasMacSizeGrip == false && (offset.manhattanLength() < hsbExt));
- }
-#endif
-
- QPoint cornerOffset(needv ? vsbExt : 0, needh ? hsbExt : 0);
- QRect controlsRect;
- QRect viewportRect;
-
- // In FrameOnlyAroundContents mode the frame is drawn between the controls and
- // the viewport, else the frame rect is equal to the widget rect.
- if ((frameStyle != QFrame::NoFrame) &&
- q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, q)) {
- controlsRect = widgetRect;
- const int extra = q->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, q);
- const QPoint cornerExtra(needv ? extra : 0, needh ? extra : 0);
- QRect frameRect = widgetRect;
- frameRect.adjust(0, 0, -cornerOffset.x() - cornerExtra.x(), -cornerOffset.y() - cornerExtra.y());
- q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, frameRect));
- // The frame rect needs to be in logical coords, however we need to flip
- // the contentsRect back before passing it on to the viewportRect
- // since the viewportRect has its logical coords calculated later.
- viewportRect = QStyle::visualRect(opt.direction, opt.rect, q->contentsRect());
- } else {
- q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, widgetRect));
- controlsRect = q->contentsRect();
- viewportRect = QRect(controlsRect.topLeft(), controlsRect.bottomRight() - cornerOffset);
- }
-
- // If we have a corner widget and are only showing one scroll bar, we need to move it
- // to make room for the corner widget.
- if (hasCornerWidget && (needv || needh))
- cornerOffset = extPoint;
-
-#ifdef Q_WS_MAC
- // Also move the scroll bars if they are covered by the native Mac size grip.
- if (hasMacSizeGrip)
- cornerOffset = extPoint;
-#endif
-
- // The corner point is where the scroll bar rects, the corner widget rect and the
- // viewport rect meets.
- const QPoint cornerPoint(controlsRect.bottomRight() + QPoint(1, 1) - cornerOffset);
-
- // Some styles paints the corner if both scorllbars are showing and there is
- // no corner widget. Also, on the Mac we paint if there is a native
- // (transparent) sizegrip in the area where a corner widget would be.
- if ((needv && needh && hasCornerWidget == false)
- || ((needv || needh)
-#ifdef Q_WS_MAC
- && hasMacSizeGrip
-#endif
- )
- ) {
- cornerPaintingRect = QStyle::visualRect(opt.direction, opt.rect, QRect(cornerPoint, extSize));
- } else {
- cornerPaintingRect = QRect();
- }
-
-#ifdef Q_WS_MAC
- if (hasMacReverseSizeGrip)
- reverseCornerPaintingRect = QRect(controlsRect.bottomRight() + QPoint(1, 1) - extPoint, extSize);
- else
- reverseCornerPaintingRect = QRect();
-#endif
-
- if (needh) {
- QRect horizontalScrollBarRect(QPoint(controlsRect.left(), cornerPoint.y()), QPoint(cornerPoint.x() - 1, controlsRect.bottom()));
-#ifdef Q_WS_MAC
- if (hasMacReverseSizeGrip)
- horizontalScrollBarRect.adjust(vsbExt, 0, 0, 0);
-#endif
- scrollBarContainers[Qt::Horizontal]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, horizontalScrollBarRect));
- scrollBarContainers[Qt::Horizontal]->raise();
- }
-
- if (needv) {
- const QRect verticalScrollBarRect (QPoint(cornerPoint.x(), controlsRect.top()), QPoint(controlsRect.right(), cornerPoint.y() - 1));
- scrollBarContainers[Qt::Vertical]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, verticalScrollBarRect));
- scrollBarContainers[Qt::Vertical]->raise();
- }
-
- if (cornerWidget) {
- const QRect cornerWidgetRect(cornerPoint, controlsRect.bottomRight());
- cornerWidget->setGeometry(QStyle::visualRect(opt.direction, opt.rect, cornerWidgetRect));
- }
-
- scrollBarContainers[Qt::Horizontal]->setVisible(needh);
- scrollBarContainers[Qt::Vertical]->setVisible(needv);
-
- if (q->isRightToLeft())
- viewportRect.adjust(right, top, -left, -bottom);
- else
- viewportRect.adjust(left, top, -right, -bottom);
-
- viewport->setGeometry(QStyle::visualRect(opt.direction, opt.rect, viewportRect)); // resize the viewport last
-}
-
-/*!
- \internal
-
- Creates a new QAbstractScrollAreaPrivate, \a dd with the given \a parent.
-*/
-QAbstractScrollArea::QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent)
- :QFrame(dd, parent)
-{
- Q_D(QAbstractScrollArea);
- QT_TRY {
- d->init();
- } QT_CATCH(...) {
- d->viewportFilter.reset();
- QT_RETHROW;
- }
-}
-
-/*!
- Constructs a viewport.
-
- The \a parent argument is sent to the QWidget constructor.
-*/
-QAbstractScrollArea::QAbstractScrollArea(QWidget *parent)
- :QFrame(*new QAbstractScrollAreaPrivate, parent)
-{
- Q_D(QAbstractScrollArea);
- QT_TRY {
- d->init();
- } QT_CATCH(...) {
- d->viewportFilter.reset();
- QT_RETHROW;
- }
-}
-
-
-/*!
- Destroys the viewport.
- */
-QAbstractScrollArea::~QAbstractScrollArea()
-{
- Q_D(QAbstractScrollArea);
- // reset it here, otherwise we'll have a dangling pointer in ~QWidget
- d->viewportFilter.reset();
-}
-
-
-/*!
- \since 4.2
- Sets the viewport to be the given \a widget.
- The QAbstractScrollArea will take ownership of the given \a widget.
-
- If \a widget is 0, QAbstractScrollArea will assign a new QWidget instance
- for the viewport.
-
- \sa viewport()
-*/
-void QAbstractScrollArea::setViewport(QWidget *widget)
-{
- Q_D(QAbstractScrollArea);
- if (widget != d->viewport) {
- QWidget *oldViewport = d->viewport;
- if (!widget)
- widget = new QWidget;
- d->viewport = widget;
- d->viewport->setParent(this);
- d->viewport->setFocusProxy(this);
- d->viewport->installEventFilter(d->viewportFilter.data());
-#ifndef Q_WS_MAC
-#ifndef QT_NO_GESTURES
- d->viewport->grabGesture(Qt::PanGesture);
-#endif
-#endif
-#ifdef Q_WS_MAEMO_5
-#ifndef QT_NO_GESTURES
-// d->viewport->grabGesture(Qt::TouchFlickGesture);
-#endif
-#endif
- d->layoutChildren();
- if (isVisible())
- d->viewport->show();
- QMetaObject::invokeMethod(this, "setupViewport", Q_ARG(QWidget *, widget));
- delete oldViewport;
- }
-}
-
-/*!
- Returns the viewport widget.
-
- Use the QScrollArea::widget() function to retrieve the contents of
- the viewport widget.
-
- \sa QScrollArea::widget()
-*/
-QWidget *QAbstractScrollArea::viewport() const
-{
- Q_D(const QAbstractScrollArea);
- return d->viewport;
-}
-
-
-/*!
-Returns the size of the viewport as if the scroll bars had no valid
-scrolling range.
-*/
-// ### still thinking about the name
-QSize QAbstractScrollArea::maximumViewportSize() const
-{
- Q_D(const QAbstractScrollArea);
- int hsbExt = d->hbar->sizeHint().height();
- int vsbExt = d->vbar->sizeHint().width();
-
- int f = 2 * d->frameWidth;
- QSize max = size() - QSize(f + d->left + d->right, f + d->top + d->bottom);
- if (d->vbarpolicy == Qt::ScrollBarAlwaysOn)
- max.rwidth() -= vsbExt;
- if (d->hbarpolicy == Qt::ScrollBarAlwaysOn)
- max.rheight() -= hsbExt;
- return max;
-}
-
-/*!
- \property QAbstractScrollArea::verticalScrollBarPolicy
- \brief the policy for the vertical scroll bar
-
- The default policy is Qt::ScrollBarAsNeeded.
-
- \sa horizontalScrollBarPolicy
-*/
-
-Qt::ScrollBarPolicy QAbstractScrollArea::verticalScrollBarPolicy() const
-{
- Q_D(const QAbstractScrollArea);
- return d->vbarpolicy;
-}
-
-void QAbstractScrollArea::setVerticalScrollBarPolicy(Qt::ScrollBarPolicy policy)
-{
- Q_D(QAbstractScrollArea);
- const Qt::ScrollBarPolicy oldPolicy = d->vbarpolicy;
- d->vbarpolicy = policy;
- if (isVisible())
- d->layoutChildren();
- if (oldPolicy != d->vbarpolicy)
- d->scrollBarPolicyChanged(Qt::Vertical, d->vbarpolicy);
-}
-
-
-/*!
- Returns the vertical scroll bar.
-
- \sa verticalScrollBarPolicy, horizontalScrollBar()
- */
-QScrollBar *QAbstractScrollArea::verticalScrollBar() const
-{
- Q_D(const QAbstractScrollArea);
- return d->vbar;
-}
-
-/*!
- \since 4.2
- Replaces the existing vertical scroll bar with \a scrollBar, and sets all
- the former scroll bar's slider properties on the new scroll bar. The former
- scroll bar is then deleted.
-
- QAbstractScrollArea already provides vertical and horizontal scroll bars by
- default. You can call this function to replace the default vertical
- scroll bar with your own custom scroll bar.
-
- \sa verticalScrollBar(), setHorizontalScrollBar()
-*/
-void QAbstractScrollArea::setVerticalScrollBar(QScrollBar *scrollBar)
-{
- Q_D(QAbstractScrollArea);
- if (!scrollBar) {
- qWarning("QAbstractScrollArea::setVerticalScrollBar: Cannot set a null scroll bar");
- return;
- }
-
- d->replaceScrollBar(scrollBar, Qt::Vertical);
-}
-
-/*!
- \property QAbstractScrollArea::horizontalScrollBarPolicy
- \brief the policy for the horizontal scroll bar
-
- The default policy is Qt::ScrollBarAsNeeded.
-
- \sa verticalScrollBarPolicy
-*/
-
-Qt::ScrollBarPolicy QAbstractScrollArea::horizontalScrollBarPolicy() const
-{
- Q_D(const QAbstractScrollArea);
- return d->hbarpolicy;
-}
-
-void QAbstractScrollArea::setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy policy)
-{
- Q_D(QAbstractScrollArea);
- const Qt::ScrollBarPolicy oldPolicy = d->hbarpolicy;
- d->hbarpolicy = policy;
- if (isVisible())
- d->layoutChildren();
- if (oldPolicy != d->hbarpolicy)
- d->scrollBarPolicyChanged(Qt::Horizontal, d->hbarpolicy);
-}
-
-/*!
- Returns the horizontal scroll bar.
-
- \sa horizontalScrollBarPolicy, verticalScrollBar()
- */
-QScrollBar *QAbstractScrollArea::horizontalScrollBar() const
-{
- Q_D(const QAbstractScrollArea);
- return d->hbar;
-}
-
-/*!
- \since 4.2
-
- Replaces the existing horizontal scroll bar with \a scrollBar, and sets all
- the former scroll bar's slider properties on the new scroll bar. The former
- scroll bar is then deleted.
-
- QAbstractScrollArea already provides horizontal and vertical scroll bars by
- default. You can call this function to replace the default horizontal
- scroll bar with your own custom scroll bar.
-
- \sa horizontalScrollBar(), setVerticalScrollBar()
-*/
-void QAbstractScrollArea::setHorizontalScrollBar(QScrollBar *scrollBar)
-{
- Q_D(QAbstractScrollArea);
- if (!scrollBar) {
- qWarning("QAbstractScrollArea::setHorizontalScrollBar: Cannot set a null scroll bar");
- return;
- }
-
- d->replaceScrollBar(scrollBar, Qt::Horizontal);
-}
-
-/*!
- \since 4.2
-
- Returns the widget in the corner between the two scroll bars.
-
- By default, no corner widget is present.
-*/
-QWidget *QAbstractScrollArea::cornerWidget() const
-{
- Q_D(const QAbstractScrollArea);
- return d->cornerWidget;
-}
-
-/*!
- \since 4.2
-
- Sets the widget in the corner between the two scroll bars to be
- \a widget.
-
- You will probably also want to set at least one of the scroll bar
- modes to \c AlwaysOn.
-
- Passing 0 shows no widget in the corner.
-
- Any previous corner widget is hidden.
-
- You may call setCornerWidget() with the same widget at different
- times.
-
- All widgets set here will be deleted by the scroll area when it is
- destroyed unless you separately reparent the widget after setting
- some other corner widget (or 0).
-
- Any \e newly set widget should have no current parent.
-
- By default, no corner widget is present.
-
- \sa horizontalScrollBarPolicy, horizontalScrollBarPolicy
-*/
-void QAbstractScrollArea::setCornerWidget(QWidget *widget)
-{
- Q_D(QAbstractScrollArea);
- QWidget* oldWidget = d->cornerWidget;
- if (oldWidget != widget) {
- if (oldWidget)
- oldWidget->hide();
- d->cornerWidget = widget;
-
- if (widget && widget->parentWidget() != this)
- widget->setParent(this);
-
- d->layoutChildren();
- if (widget)
- widget->show();
- } else {
- d->cornerWidget = widget;
- d->layoutChildren();
- }
-}
-
-/*!
- \since 4.2
- Adds \a widget as a scroll bar widget in the location specified
- by \a alignment.
-
- Scroll bar widgets are shown next to the horizontal or vertical
- scroll bar, and can be placed on either side of it. If you want
- the scroll bar widgets to be always visible, set the
- scrollBarPolicy for the corresponding scroll bar to \c AlwaysOn.
-
- \a alignment must be one of Qt::Alignleft and Qt::AlignRight,
- which maps to the horizontal scroll bar, or Qt::AlignTop and
- Qt::AlignBottom, which maps to the vertical scroll bar.
-
- A scroll bar widget can be removed by either re-parenting the
- widget or deleting it. It's also possible to hide a widget with
- QWidget::hide()
-
- The scroll bar widget will be resized to fit the scroll bar
- geometry for the current style. The following describes the case
- for scroll bar widgets on the horizontal scroll bar:
-
- The height of the widget will be set to match the height of the
- scroll bar. To control the width of the widget, use
- QWidget::setMinimumWidth and QWidget::setMaximumWidth, or
- implement QWidget::sizeHint() and set a horizontal size policy.
- If you want a square widget, call
- QStyle::pixelMetric(QStyle::PM_ScrollBarExtent) and set the
- width to this value.
-
- \sa scrollBarWidgets()
-*/
-void QAbstractScrollArea::addScrollBarWidget(QWidget *widget, Qt::Alignment alignment)
-{
- Q_D(QAbstractScrollArea);
-
- if (widget == 0)
- return;
-
- const Qt::Orientation scrollBarOrientation
- = ((alignment & Qt::AlignLeft) || (alignment & Qt::AlignRight)) ? Qt::Horizontal : Qt::Vertical;
- const QAbstractScrollAreaScrollBarContainer::LogicalPosition position
- = ((alignment & Qt::AlignRight) || (alignment & Qt::AlignBottom))
- ? QAbstractScrollAreaScrollBarContainer::LogicalRight : QAbstractScrollAreaScrollBarContainer::LogicalLeft;
- d->scrollBarContainers[scrollBarOrientation]->addWidget(widget, position);
- d->layoutChildren();
- if (isHidden() == false)
- widget->show();
-}
-
-/*!
- \since 4.2
- Returns a list of the currently set scroll bar widgets. \a alignment
- can be any combination of the four location flags.
-
- \sa addScrollBarWidget()
-*/
-QWidgetList QAbstractScrollArea::scrollBarWidgets(Qt::Alignment alignment)
-{
- Q_D(QAbstractScrollArea);
-
- QWidgetList list;
-
- if (alignment & Qt::AlignLeft)
- list += d->scrollBarContainers[Qt::Horizontal]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalLeft);
- if (alignment & Qt::AlignRight)
- list += d->scrollBarContainers[Qt::Horizontal]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalRight);
- if (alignment & Qt::AlignTop)
- list += d->scrollBarContainers[Qt::Vertical]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalLeft);
- if (alignment & Qt::AlignBottom)
- list += d->scrollBarContainers[Qt::Vertical]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalRight);
-
- return list;
-}
-
-/*!
- Sets the margins around the scrolling area to \a left, \a top, \a
- right and \a bottom. This is useful for applications such as
- spreadsheets with "locked" rows and columns. The marginal space is
- is left blank; put widgets in the unused area.
-
- Note that this function is frequently called by QTreeView and
- QTableView, so margins must be implemented by QAbstractScrollArea
- subclasses. Also, if the subclasses are to be used in item views,
- they should not call this function.
-
- By default all margins are zero.
-
-*/
-void QAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
-{
- Q_D(QAbstractScrollArea);
- d->left = left;
- d->top = top;
- d->right = right;
- d->bottom = bottom;
- d->layoutChildren();
-}
-
-/*!
- \since 4.6
- Sets \a margins around the scrolling area. This is useful for
- applications such as spreadsheets with "locked" rows and columns.
- The marginal space is is left blank; put widgets in the unused
- area.
-
- By default all margins are zero.
-
-*/
-void QAbstractScrollArea::setViewportMargins(const QMargins &margins)
-{
- setViewportMargins(margins.left(), margins.top(),
- margins.right(), margins.bottom());
-}
-
-/*!
- \fn bool QAbstractScrollArea::event(QEvent *event)
-
- \reimp
-
- This is the main event handler for the QAbstractScrollArea widget (\e not
- the scrolling area viewport()). The specified \a event is a general event
- object that may need to be cast to the appropriate class depending on its
- type.
-
- \sa QEvent::type()
-*/
-bool QAbstractScrollArea::event(QEvent *e)
-{
- Q_D(QAbstractScrollArea);
- switch (e->type()) {
- case QEvent::AcceptDropsChange:
- // There was a chance that with accessibility client we get an
- // event before the viewport was created.
- // Also, in some cases we might get here from QWidget::event() virtual function which is (indirectly) called
- // from the viewport constructor at the time when the d->viewport is not yet initialized even without any
- // accessibility client. See qabstractscrollarea autotest for a test case.
- if (d->viewport)
- d->viewport->setAcceptDrops(acceptDrops());
- break;
- case QEvent::MouseTrackingChange:
- d->viewport->setMouseTracking(hasMouseTracking());
- break;
- case QEvent::Resize:
- d->layoutChildren();
- break;
- case QEvent::Paint: {
- QStyleOption option;
- option.initFrom(this);
- if (d->cornerPaintingRect.isValid()) {
- option.rect = d->cornerPaintingRect;
- QPainter p(this);
- style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
- }
-#ifdef Q_WS_MAC
- if (d->reverseCornerPaintingRect.isValid()) {
- option.rect = d->reverseCornerPaintingRect;
- QPainter p(this);
- style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
- }
-#endif
- }
- QFrame::paintEvent((QPaintEvent*)e);
- break;
-#ifndef QT_NO_CONTEXTMENU
- case QEvent::ContextMenu:
- if (static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard)
- return QFrame::event(e);
- e->ignore();
- break;
-#endif // QT_NO_CONTEXTMENU
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- case QEvent::Wheel:
-#ifndef QT_NO_DRAGANDDROP
- case QEvent::Drop:
- case QEvent::DragEnter:
- case QEvent::DragMove:
- case QEvent::DragLeave:
-#endif
- // ignore touch events in case they have been propagated from the viewport
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- return false;
-#ifndef QT_NO_GESTURES
- case QEvent::Gesture:
- {
- QGestureEvent *ge = static_cast<QGestureEvent *>(e);
- QPanGesture *g = static_cast<QPanGesture *>(ge->gesture(Qt::PanGesture));
- if (g) {
- QScrollBar *hBar = horizontalScrollBar();
- QScrollBar *vBar = verticalScrollBar();
- QPointF delta = g->delta();
- if (!delta.isNull()) {
- if (QApplication::isRightToLeft())
- delta.rx() *= -1;
- int newX = hBar->value() - delta.x();
- int newY = vBar->value() - delta.y();
- hBar->setValue(newX);
- vBar->setValue(newY);
- }
- return true;
- }
- return false;
- }
-#endif // QT_NO_GESTURES
- case QEvent::ScrollPrepare:
- {
- QScrollPrepareEvent *se = static_cast<QScrollPrepareEvent *>(e);
- if (d->canStartScrollingAt(se->startPos().toPoint())) {
- QScrollBar *hBar = horizontalScrollBar();
- QScrollBar *vBar = verticalScrollBar();
-
- se->setViewportSize(QSizeF(viewport()->size()));
- se->setContentPosRange(QRectF(0, 0, hBar->maximum(), vBar->maximum()));
- se->setContentPos(QPointF(hBar->value(), vBar->value()));
- se->accept();
- return true;
- }
- return false;
- }
- case QEvent::Scroll:
- {
- QScrollEvent *se = static_cast<QScrollEvent *>(e);
-
- QScrollBar *hBar = horizontalScrollBar();
- QScrollBar *vBar = verticalScrollBar();
- hBar->setValue(se->contentPos().x());
- vBar->setValue(se->contentPos().y());
-
-#ifdef Q_WS_WIN
- typedef BOOL (*PtrBeginPanningFeedback)(HWND);
- typedef BOOL (*PtrUpdatePanningFeedback)(HWND, LONG, LONG, BOOL);
- typedef BOOL (*PtrEndPanningFeedback)(HWND, BOOL);
-
- static PtrBeginPanningFeedback ptrBeginPanningFeedback = 0;
- static PtrUpdatePanningFeedback ptrUpdatePanningFeedback = 0;
- static PtrEndPanningFeedback ptrEndPanningFeedback = 0;
-
- if (!ptrBeginPanningFeedback)
- ptrBeginPanningFeedback = (PtrBeginPanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "BeginPanningFeedback");
- if (!ptrUpdatePanningFeedback)
- ptrUpdatePanningFeedback = (PtrUpdatePanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "UpdatePanningFeedback");
- if (!ptrEndPanningFeedback)
- ptrEndPanningFeedback = (PtrEndPanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "EndPanningFeedback");
-
- if (ptrBeginPanningFeedback && ptrUpdatePanningFeedback && ptrEndPanningFeedback) {
- WId wid = window()->winId();
-
- if (!se->overshootDistance().isNull() && d->overshoot.isNull())
- ptrBeginPanningFeedback(wid);
- if (!se->overshootDistance().isNull())
- ptrUpdatePanningFeedback(wid, -se->overshootDistance().x(), -se->overshootDistance().y(), false);
- if (se->overshootDistance().isNull() && !d->overshoot.isNull())
- ptrEndPanningFeedback(wid, true);
- } else
-#endif
- {
- QPoint delta = d->overshoot - se->overshootDistance().toPoint();
- if (!delta.isNull())
- viewport()->move(viewport()->pos() + delta);
- }
- d->overshoot = se->overshootDistance().toPoint();
-
- return true;
- }
- case QEvent::StyleChange:
- case QEvent::LayoutDirectionChange:
- case QEvent::ApplicationLayoutDirectionChange:
- case QEvent::LayoutRequest:
- d->layoutChildren();
- // fall through
- default:
- return QFrame::event(e);
- }
- return true;
-}
-
-/*!
- \fn bool QAbstractScrollArea::viewportEvent(QEvent *event)
-
- The main event handler for the scrolling area (the viewport() widget).
- It handles the \a event specified, and can be called by subclasses to
- provide reasonable default behavior.
-
- Returns true to indicate to the event system that the event has been
- handled, and needs no further processing; otherwise returns false to
- indicate that the event should be propagated further.
-
- You can reimplement this function in a subclass, but we recommend
- using one of the specialized event handlers instead.
-
- Specialized handlers for viewport events are: paintEvent(),
- mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(),
- mouseMoveEvent(), wheelEvent(), dragEnterEvent(), dragMoveEvent(),
- dragLeaveEvent(), dropEvent(), contextMenuEvent(), and
- resizeEvent().
-*/
-bool QAbstractScrollArea::viewportEvent(QEvent *e)
-{
- switch (e->type()) {
- case QEvent::Resize:
- case QEvent::Paint:
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::TouchBegin:
- case QEvent::TouchUpdate:
- case QEvent::TouchEnd:
- case QEvent::MouseMove:
- case QEvent::ContextMenu:
-#ifndef QT_NO_WHEELEVENT
- case QEvent::Wheel:
-#endif
-#ifndef QT_NO_DRAGANDDROP
- case QEvent::Drop:
- case QEvent::DragEnter:
- case QEvent::DragMove:
- case QEvent::DragLeave:
-#endif
- return QFrame::event(e);
- case QEvent::LayoutRequest:
-#ifndef QT_NO_GESTURES
- case QEvent::Gesture:
- case QEvent::GestureOverride:
- return event(e);
-#endif
- case QEvent::ScrollPrepare:
- case QEvent::Scroll:
- return event(e);
- default:
- break;
- }
- return false; // let the viewport widget handle the event
-}
-
-/*!
- \fn void QAbstractScrollArea::resizeEvent(QResizeEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- resize events (passed in \a event), for the viewport() widget.
-
- When resizeEvent() is called, the viewport already has its new
- geometry: Its new size is accessible through the
- QResizeEvent::size() function, and the old size through
- QResizeEvent::oldSize().
-
- \sa QWidget::resizeEvent()
- */
-void QAbstractScrollArea::resizeEvent(QResizeEvent *)
-{
-}
-
-/*!
- \fn void QAbstractScrollArea::paintEvent(QPaintEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- paint events (passed in \a event), for the viewport() widget.
-
- \note If you open a painter, make sure to open it on the viewport().
-
- \sa QWidget::paintEvent()
-*/
-void QAbstractScrollArea::paintEvent(QPaintEvent*)
-{
-}
-
-/*!
- This event handler can be reimplemented in a subclass to receive
- mouse press events for the viewport() widget. The event is passed
- in \a e.
-
- \sa QWidget::mousePressEvent()
-*/
-void QAbstractScrollArea::mousePressEvent(QMouseEvent *e)
-{
- e->ignore();
-}
-
-/*!
- This event handler can be reimplemented in a subclass to receive
- mouse release events for the viewport() widget. The event is
- passed in \a e.
-
- \sa QWidget::mouseReleaseEvent()
-*/
-void QAbstractScrollArea::mouseReleaseEvent(QMouseEvent *e)
-{
- e->ignore();
-}
-
-/*!
- This event handler can be reimplemented in a subclass to receive
- mouse double click events for the viewport() widget. The event is
- passed in \a e.
-
- \sa QWidget::mouseDoubleClickEvent()
-*/
-void QAbstractScrollArea::mouseDoubleClickEvent(QMouseEvent *e)
-{
- e->ignore();
-}
-
-/*!
- This event handler can be reimplemented in a subclass to receive
- mouse move events for the viewport() widget. The event is passed
- in \a e.
-
- \sa QWidget::mouseMoveEvent()
-*/
-void QAbstractScrollArea::mouseMoveEvent(QMouseEvent *e)
-{
- e->ignore();
-}
-
-/*!
- This event handler can be reimplemented in a subclass to receive
- wheel events for the viewport() widget. The event is passed in \a
- e.
-
- \sa QWidget::wheelEvent()
-*/
-#ifndef QT_NO_WHEELEVENT
-void QAbstractScrollArea::wheelEvent(QWheelEvent *e)
-{
- Q_D(QAbstractScrollArea);
- if (static_cast<QWheelEvent*>(e)->orientation() == Qt::Horizontal)
- QApplication::sendEvent(d->hbar, e);
- else
- QApplication::sendEvent(d->vbar, e);
-}
-#endif
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- This event handler can be reimplemented in a subclass to receive
- context menu events for the viewport() widget. The event is passed
- in \a e.
-
- \sa QWidget::contextMenuEvent()
-*/
-void QAbstractScrollArea::contextMenuEvent(QContextMenuEvent *e)
-{
- e->ignore();
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*!
- This function is called with key event \a e when key presses
- occur. It handles PageUp, PageDown, Up, Down, Left, and Right, and
- ignores all other key presses.
-*/
-void QAbstractScrollArea::keyPressEvent(QKeyEvent * e)
-{
- Q_D(QAbstractScrollArea);
- if (false){
-#ifndef QT_NO_SHORTCUT
- } else if (e == QKeySequence::MoveToPreviousPage) {
- d->vbar->triggerAction(QScrollBar::SliderPageStepSub);
- } else if (e == QKeySequence::MoveToNextPage) {
- d->vbar->triggerAction(QScrollBar::SliderPageStepAdd);
-#endif
- } else {
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- e->ignore();
- return;
- }
-#endif
- switch (e->key()) {
- case Qt::Key_Up:
- d->vbar->triggerAction(QScrollBar::SliderSingleStepSub);
- break;
- case Qt::Key_Down:
- d->vbar->triggerAction(QScrollBar::SliderSingleStepAdd);
- break;
- case Qt::Key_Left:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()
- && (!d->hbar->isVisible() || d->hbar->value() == d->hbar->minimum())) {
- //if we aren't using the hbar or we are already at the leftmost point ignore
- e->ignore();
- return;
- }
-#endif
- d->hbar->triggerAction(
- layoutDirection() == Qt::LeftToRight
- ? QScrollBar::SliderSingleStepSub : QScrollBar::SliderSingleStepAdd);
- break;
- case Qt::Key_Right:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()
- && (!d->hbar->isVisible() || d->hbar->value() == d->hbar->maximum())) {
- //if we aren't using the hbar or we are already at the rightmost point ignore
- e->ignore();
- return;
- }
-#endif
- d->hbar->triggerAction(
- layoutDirection() == Qt::LeftToRight
- ? QScrollBar::SliderSingleStepAdd : QScrollBar::SliderSingleStepSub);
- break;
- default:
- e->ignore();
- return;
- }
- }
- e->accept();
-}
-
-
-#ifndef QT_NO_DRAGANDDROP
-/*!
- \fn void QAbstractScrollArea::dragEnterEvent(QDragEnterEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- drag enter events (passed in \a event), for the viewport() widget.
-
- \sa QWidget::dragEnterEvent()
-*/
-void QAbstractScrollArea::dragEnterEvent(QDragEnterEvent *)
-{
-}
-
-/*!
- \fn void QAbstractScrollArea::dragMoveEvent(QDragMoveEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- drag move events (passed in \a event), for the viewport() widget.
-
- \sa QWidget::dragMoveEvent()
-*/
-void QAbstractScrollArea::dragMoveEvent(QDragMoveEvent *)
-{
-}
-
-/*!
- \fn void QAbstractScrollArea::dragLeaveEvent(QDragLeaveEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- drag leave events (passed in \a event), for the viewport() widget.
-
- \sa QWidget::dragLeaveEvent()
-*/
-void QAbstractScrollArea::dragLeaveEvent(QDragLeaveEvent *)
-{
-}
-
-/*!
- \fn void QAbstractScrollArea::dropEvent(QDropEvent *event)
-
- This event handler can be reimplemented in a subclass to receive
- drop events (passed in \a event), for the viewport() widget.
-
- \sa QWidget::dropEvent()
-*/
-void QAbstractScrollArea::dropEvent(QDropEvent *)
-{
-}
-
-
-#endif
-
-/*!
- This virtual handler is called when the scroll bars are moved by
- \a dx, \a dy, and consequently the viewport's contents should be
- scrolled accordingly.
-
- The default implementation simply calls update() on the entire
- viewport(), subclasses can reimplement this handler for
- optimization purposes, or - like QScrollArea - to move a contents
- widget. The parameters \a dx and \a dy are there for convenience,
- so that the class knows how much should be scrolled (useful
- e.g. when doing pixel-shifts). You may just as well ignore these
- values and scroll directly to the position the scroll bars
- indicate.
-
- Calling this function in order to scroll programmatically is an
- error, use the scroll bars instead (e.g. by calling
- QScrollBar::setValue() directly).
-*/
-void QAbstractScrollArea::scrollContentsBy(int, int)
-{
- viewport()->update();
-}
-
-bool QAbstractScrollAreaPrivate::canStartScrollingAt( const QPoint &startPos )
-{
- Q_Q(QAbstractScrollArea);
-
-#ifndef QT_NO_GRAPHICSVIEW
- // don't start scrolling when a drag mode has been set.
- // don't start scrolling on a movable item.
- if (QGraphicsView *view = qobject_cast<QGraphicsView *>(q)) {
- if (view->dragMode() != QGraphicsView::NoDrag)
- return false;
-
- QGraphicsItem *childItem = view->itemAt(startPos);
-
- if (childItem && (childItem->flags() & QGraphicsItem::ItemIsMovable))
- return false;
- }
-#endif
-
- // don't start scrolling on a QAbstractSlider
- if (qobject_cast<QAbstractSlider *>(q->viewport()->childAt(startPos))) {
- return false;
- }
-
- return true;
-}
-
-void QAbstractScrollAreaPrivate::_q_hslide(int x)
-{
- Q_Q(QAbstractScrollArea);
- int dx = xoffset - x;
- xoffset = x;
- q->scrollContentsBy(dx, 0);
-}
-
-void QAbstractScrollAreaPrivate::_q_vslide(int y)
-{
- Q_Q(QAbstractScrollArea);
- int dy = yoffset - y;
- yoffset = y;
- q->scrollContentsBy(0, dy);
-}
-
-void QAbstractScrollAreaPrivate::_q_showOrHideScrollBars()
-{
- layoutChildren();
-#ifdef Q_WS_WIN
- // Need to re-subscribe to gestures as the content changes to make sure we
- // enable/disable panning when needed.
- QWidgetPrivate *dd = static_cast<QWidgetPrivate *>(QObjectPrivate::get(viewport));
- if (dd)
- dd->winSetupGestures();
-#endif // Q_WS_WIN
-}
-
-QPoint QAbstractScrollAreaPrivate::contentsOffset() const
-{
- Q_Q(const QAbstractScrollArea);
- QPoint offset;
- if (vbar->isVisible())
- offset.setY(vbar->value());
- if (hbar->isVisible()) {
- if (q->isRightToLeft())
- offset.setX(hbar->maximum() - hbar->value());
- else
- offset.setX(hbar->value());
- }
- return offset;
-}
-
-/*!
- \reimp
-
-*/
-QSize QAbstractScrollArea::minimumSizeHint() const
-{
- Q_D(const QAbstractScrollArea);
- int hsbExt = d->hbar->sizeHint().height();
- int vsbExt = d->vbar->sizeHint().width();
- int extra = 2 * d->frameWidth;
- QStyleOption opt;
- opt.initFrom(this);
- if ((d->frameStyle != QFrame::NoFrame)
- && style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, this)) {
- extra += style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, this);
- }
- return QSize(d->scrollBarContainers[Qt::Horizontal]->sizeHint().width() + vsbExt + extra,
- d->scrollBarContainers[Qt::Vertical]->sizeHint().height() + hsbExt + extra);
-}
-
-/*!
- \reimp
-*/
-QSize QAbstractScrollArea::sizeHint() const
-{
- return QSize(256, 192);
-#if 0
- Q_D(const QAbstractScrollArea);
- int h = qMax(10, fontMetrics().height());
- int f = 2 * d->frameWidth;
- return QSize((6 * h) + f, (4 * h) + f);
-#endif
-}
-
-/*!
- This slot is called by QAbstractScrollArea after setViewport(\a
- viewport) has been called. Reimplement this function in a
- subclass of QAbstractScrollArea to initialize the new \a viewport
- before it is used.
-
- \sa setViewport()
-*/
-void QAbstractScrollArea::setupViewport(QWidget *viewport)
-{
- Q_UNUSED(viewport);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qabstractscrollarea.cpp"
-#include "moc_qabstractscrollarea_p.cpp"
-
-#endif // QT_NO_SCROLLAREA
diff --git a/src/gui/widgets/qabstractscrollarea.h b/src/gui/widgets/qabstractscrollarea.h
deleted file mode 100644
index 34b7837284..0000000000
--- a/src/gui/widgets/qabstractscrollarea.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTSCROLLAREA_H
-#define QABSTRACTSCROLLAREA_H
-
-#include <QtGui/qframe.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SCROLLAREA
-
-class QMargins;
-class QScrollBar;
-class QAbstractScrollAreaPrivate;
-
-class Q_GUI_EXPORT QAbstractScrollArea : public QFrame
-{
- Q_OBJECT
- Q_PROPERTY(Qt::ScrollBarPolicy verticalScrollBarPolicy READ verticalScrollBarPolicy WRITE setVerticalScrollBarPolicy)
- Q_PROPERTY(Qt::ScrollBarPolicy horizontalScrollBarPolicy READ horizontalScrollBarPolicy WRITE setHorizontalScrollBarPolicy)
-
-public:
- explicit QAbstractScrollArea(QWidget* parent=0);
- ~QAbstractScrollArea();
-
- Qt::ScrollBarPolicy verticalScrollBarPolicy() const;
- void setVerticalScrollBarPolicy(Qt::ScrollBarPolicy);
- QScrollBar *verticalScrollBar() const;
- void setVerticalScrollBar(QScrollBar *scrollbar);
-
- Qt::ScrollBarPolicy horizontalScrollBarPolicy() const;
- void setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy);
- QScrollBar *horizontalScrollBar() const;
- void setHorizontalScrollBar(QScrollBar *scrollbar);
-
- QWidget *cornerWidget() const;
- void setCornerWidget(QWidget *widget);
-
- void addScrollBarWidget(QWidget *widget, Qt::Alignment alignment);
- QWidgetList scrollBarWidgets(Qt::Alignment alignment);
-
- QWidget *viewport() const;
- void setViewport(QWidget *widget);
- QSize maximumViewportSize() const;
-
- QSize minimumSizeHint() const;
-
- QSize sizeHint() const;
-
-protected Q_SLOTS:
- void setupViewport(QWidget *viewport);
-
-protected:
- QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent = 0);
- void setViewportMargins(int left, int top, int right, int bottom);
- void setViewportMargins(const QMargins &margins);
-
- bool event(QEvent *);
- virtual bool viewportEvent(QEvent *);
-
- void resizeEvent(QResizeEvent *);
- void paintEvent(QPaintEvent *);
- void mousePressEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void mouseDoubleClickEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *);
-#endif
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *);
-#endif
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QDragEnterEvent *);
- void dragMoveEvent(QDragMoveEvent *);
- void dragLeaveEvent(QDragLeaveEvent *);
- void dropEvent(QDropEvent *);
-#endif
-
- void keyPressEvent(QKeyEvent *);
-
- virtual void scrollContentsBy(int dx, int dy);
-
-private:
- Q_DECLARE_PRIVATE(QAbstractScrollArea)
- Q_DISABLE_COPY(QAbstractScrollArea)
- Q_PRIVATE_SLOT(d_func(), void _q_hslide(int))
- Q_PRIVATE_SLOT(d_func(), void _q_vslide(int))
- Q_PRIVATE_SLOT(d_func(), void _q_showOrHideScrollBars())
-
- friend class QStyleSheetStyle;
- friend class QWidgetPrivate;
-};
-
-#endif // QT_NO_SCROLLAREA
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTSCROLLAREA_H
diff --git a/src/gui/widgets/qabstractscrollarea_p.h b/src/gui/widgets/qabstractscrollarea_p.h
deleted file mode 100644
index 76e1c34868..0000000000
--- a/src/gui/widgets/qabstractscrollarea_p.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTSCROLLAREA_P_H
-#define QABSTRACTSCROLLAREA_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qframe_p.h"
-#include "qabstractscrollarea.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_SCROLLAREA
-
-class QScrollBar;
-class QAbstractScrollAreaScrollBarContainer;
-class Q_GUI_EXPORT QAbstractScrollAreaPrivate: public QFramePrivate
-{
- Q_DECLARE_PUBLIC(QAbstractScrollArea)
-
-public:
- QAbstractScrollAreaPrivate();
-
- void replaceScrollBar(QScrollBar *scrollBar, Qt::Orientation orientation);
-
- QAbstractScrollAreaScrollBarContainer *scrollBarContainers[Qt::Vertical + 1];
- QScrollBar *hbar, *vbar;
- Qt::ScrollBarPolicy vbarpolicy, hbarpolicy;
-
- QWidget *viewport;
- QWidget *cornerWidget;
- QRect cornerPaintingRect;
-#ifdef Q_WS_MAC
- QRect reverseCornerPaintingRect;
-#endif
- int left, top, right, bottom; // viewport margin
-
- int xoffset, yoffset;
- QPoint overshoot;
-
- void init();
- void layoutChildren();
- // ### Fix for 4.4, talk to Bjoern E or Girish.
- virtual void scrollBarPolicyChanged(Qt::Orientation, Qt::ScrollBarPolicy) {}
- bool canStartScrollingAt( const QPoint &startPos );
-
- void _q_hslide(int);
- void _q_vslide(int);
- void _q_showOrHideScrollBars();
-
- virtual QPoint contentsOffset() const;
-
- inline bool viewportEvent(QEvent *event)
- { return q_func()->viewportEvent(event); }
- QScopedPointer<QObject> viewportFilter;
-
-#ifdef Q_WS_WIN
- bool singleFingerPanEnabled;
- void setSingleFingerPanEnabled(bool on = true);
-#endif
-};
-
-class QAbstractScrollAreaFilter : public QObject
-{
- Q_OBJECT
-public:
- QAbstractScrollAreaFilter(QAbstractScrollAreaPrivate *p) : d(p)
- { setObjectName(QLatin1String("qt_abstractscrollarea_filter")); }
- bool eventFilter(QObject *o, QEvent *e)
- { return (o == d->viewport ? d->viewportEvent(e) : false); }
-private:
- QAbstractScrollAreaPrivate *d;
-};
-
-class QBoxLayout;
-class QAbstractScrollAreaScrollBarContainer : public QWidget
-{
-public:
- enum LogicalPosition { LogicalLeft = 1, LogicalRight = 2 };
-
- QAbstractScrollAreaScrollBarContainer(Qt::Orientation orientation, QWidget *parent);
- void addWidget(QWidget *widget, LogicalPosition position);
- QWidgetList widgets(LogicalPosition position);
- void removeWidget(QWidget *widget);
-
- QScrollBar *scrollBar;
- QBoxLayout *layout;
-private:
- int scrollBarLayoutIndex() const;
-
- Qt::Orientation orientation;
-};
-
-#endif // QT_NO_SCROLLAREA
-
-QT_END_NAMESPACE
-
-#endif // QABSTRACTSCROLLAREA_P_H
diff --git a/src/gui/widgets/qabstractslider.cpp b/src/gui/widgets/qabstractslider.cpp
deleted file mode 100644
index 2570496262..0000000000
--- a/src/gui/widgets/qabstractslider.cpp
+++ /dev/null
@@ -1,1001 +0,0 @@
-/****************************************************************************
-**
-** 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 <qapplication.h>
-#include "qabstractslider.h"
-#include "qevent.h"
-#include "qabstractslider_p.h"
-#include "qdebug.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAbstractSlider
- \brief The QAbstractSlider class provides an integer value within a range.
-
- \ingroup abstractwidgets
-
- The class is designed as a common super class for widgets like
- QScrollBar, QSlider and QDial.
-
- Here are the main properties of the class:
-
- \list 1
-
- \i \l value: The bounded integer that QAbstractSlider maintains.
-
- \i \l minimum: The lowest possible value.
-
- \i \l maximum: The highest possible value.
-
- \i \l singleStep: The smaller of two natural steps that an
- abstract sliders provides and typically corresponds to the user
- pressing an arrow key.
-
- \i \l pageStep: The larger of two natural steps that an abstract
- slider provides and typically corresponds to the user pressing
- PageUp or PageDown.
-
- \i \l tracking: Whether slider tracking is enabled.
-
- \i \l sliderPosition: The current position of the slider. If \l
- tracking is enabled (the default), this is identical to \l value.
-
- \endlist
-
- Unity (1) may be viewed as a third step size. setValue() lets you
- set the current value to any integer in the allowed range, not
- just minimum() + \e n * singleStep() for integer values of \e n.
- Some widgets may allow the user to set any value at all; others
- may just provide multiples of singleStep() or pageStep().
-
- QAbstractSlider emits a comprehensive set of signals:
-
- \table
- \header \i Signal \i Emitted when
- \row \i \l valueChanged()
- \i the value has changed. The \l tracking
- determines whether this signal is emitted during user
- interaction.
- \row \i \l sliderPressed()
- \i the user starts to drag the slider.
- \row \i \l sliderMoved()
- \i the user drags the slider.
- \row \i \l sliderReleased()
- \i the user releases the slider.
- \row \i \l actionTriggered()
- \i a slider action was triggerd.
- \row \i \l rangeChanged()
- \i a the range has changed.
- \endtable
-
- QAbstractSlider provides a virtual sliderChange() function that is
- well suited for updating the on-screen representation of
- sliders. By calling triggerAction(), subclasses trigger slider
- actions. Two helper functions QStyle::sliderPositionFromValue() and
- QStyle::sliderValueFromPosition() help subclasses and styles to map
- screen coordinates to logical range values.
-
- \sa QAbstractSpinBox, QSlider, QDial, QScrollBar, {Sliders Example}
-*/
-
-/*!
- \enum QAbstractSlider::SliderAction
-
- \value SliderNoAction
- \value SliderSingleStepAdd
- \value SliderSingleStepSub
- \value SliderPageStepAdd
- \value SliderPageStepSub
- \value SliderToMinimum
- \value SliderToMaximum
- \value SliderMove
-
-*/
-
-/*!
- \fn void QAbstractSlider::valueChanged(int value)
-
- This signal is emitted when the slider value has changed, with the
- new slider \a value as argument.
-*/
-
-/*!
- \fn void QAbstractSlider::sliderPressed()
-
- This signal is emitted when the user presses the slider with the
- mouse, or programmatically when setSliderDown(true) is called.
-
- \sa sliderReleased(), sliderMoved(), isSliderDown()
-*/
-
-/*!
- \fn void QAbstractSlider::sliderMoved(int value)
-
- This signal is emitted when sliderDown is true and the slider moves. This
- usually happens when the user is dragging the slider. The \a value
- is the new slider position.
-
- This signal is emitted even when tracking is turned off.
-
- \sa setTracking(), valueChanged(), isSliderDown(),
- sliderPressed(), sliderReleased()
-*/
-
-/*!
- \fn void QAbstractSlider::sliderReleased()
-
- This signal is emitted when the user releases the slider with the
- mouse, or programmatically when setSliderDown(false) is called.
-
- \sa sliderPressed() sliderMoved() sliderDown
-*/
-
-/*!
- \fn void QAbstractSlider::rangeChanged(int min, int max)
-
- This signal is emitted when the slider range has changed, with \a
- min being the new minimum, and \a max being the new maximum.
-
- \sa minimum, maximum
-*/
-
-/*!
- \fn void QAbstractSlider::actionTriggered(int action)
-
- This signal is emitted when the slider action \a action is
- triggered. Actions are \l SliderSingleStepAdd, \l
- SliderSingleStepSub, \l SliderPageStepAdd, \l SliderPageStepSub,
- \l SliderToMinimum, \l SliderToMaximum, and \l SliderMove.
-
- When the signal is emitted, the \l sliderPosition has been
- adjusted according to the action, but the \l value has not yet
- been propagated (meaning the valueChanged() signal was not yet
- emitted), and the visual display has not been updated. In slots
- connected to this signal you can thus safely adjust any action by
- calling setSliderPosition() yourself, based on both the action and
- the slider's value.
-
- \sa triggerAction()
-*/
-
-/*!
- \enum QAbstractSlider::SliderChange
-
- \value SliderRangeChange
- \value SliderOrientationChange
- \value SliderStepsChange
- \value SliderValueChange
-*/
-
-QAbstractSliderPrivate::QAbstractSliderPrivate()
- : minimum(0), maximum(99), pageStep(10), value(0), position(0), pressValue(-1),
- singleStep(1), offset_accumulated(0), tracking(true),
- blocktracking(false), pressed(false),
- invertedAppearance(false), invertedControls(false),
- orientation(Qt::Horizontal), repeatAction(QAbstractSlider::SliderNoAction)
-#ifdef QT_KEYPAD_NAVIGATION
- , isAutoRepeating(false)
- , repeatMultiplier(1)
-{
- firstRepeat.invalidate();
-#else
-{
-#endif
-
-}
-
-QAbstractSliderPrivate::~QAbstractSliderPrivate()
-{
-}
-
-/*!
- Sets the slider's minimum to \a min and its maximum to \a max.
-
- If \a max is smaller than \a min, \a min becomes the only legal
- value.
-
- \sa minimum maximum
-*/
-void QAbstractSlider::setRange(int min, int max)
-{
- Q_D(QAbstractSlider);
- int oldMin = d->minimum;
- int oldMax = d->maximum;
- d->minimum = min;
- d->maximum = qMax(min, max);
- if (oldMin != d->minimum || oldMax != d->maximum) {
- sliderChange(SliderRangeChange);
- emit rangeChanged(d->minimum, d->maximum);
- setValue(d->value); // re-bound
- }
-}
-
-
-void QAbstractSliderPrivate::setSteps(int single, int page)
-{
- Q_Q(QAbstractSlider);
- singleStep = qAbs(single);
- pageStep = qAbs(page);
- q->sliderChange(QAbstractSlider::SliderStepsChange);
-}
-
-/*!
- Constructs an abstract slider.
-
- The \a parent argument is sent to the QWidget constructor.
-
- The \l minimum defaults to 0, the \l maximum to 99, with a \l
- singleStep size of 1 and a \l pageStep size of 10, and an initial
- \l value of 0.
-*/
-QAbstractSlider::QAbstractSlider(QWidget *parent)
- :QWidget(*new QAbstractSliderPrivate, parent, 0)
-{
-}
-
-/*! \internal */
-QAbstractSlider::QAbstractSlider(QAbstractSliderPrivate &dd, QWidget *parent)
- :QWidget(dd, parent, 0)
-{
-}
-
-/*!
- Destroys the slider.
-*/
-QAbstractSlider::~QAbstractSlider()
-{
-}
-
-/*!
- \property QAbstractSlider::orientation
- \brief the orientation of the slider
-
- The orientation must be \l Qt::Vertical (the default) or \l
- Qt::Horizontal.
-*/
-void QAbstractSlider::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QAbstractSlider);
- if (d->orientation == orientation)
- return;
-
- d->orientation = orientation;
- if (!testAttribute(Qt::WA_WState_OwnSizePolicy)) {
- QSizePolicy sp = sizePolicy();
- sp.transpose();
- setSizePolicy(sp);
- setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- }
- update();
- updateGeometry();
-}
-
-Qt::Orientation QAbstractSlider::orientation() const
-{
- Q_D(const QAbstractSlider);
- return d->orientation;
-}
-
-
-/*!
- \property QAbstractSlider::minimum
- \brief the sliders's minimum value
-
- When setting this property, the \l maximum is adjusted if
- necessary to ensure that the range remains valid. Also the
- slider's current value is adjusted to be within the new range.
-
-*/
-
-void QAbstractSlider::setMinimum(int min)
-{
- Q_D(QAbstractSlider);
- setRange(min, qMax(d->maximum, min));
-}
-
-int QAbstractSlider::minimum() const
-{
- Q_D(const QAbstractSlider);
- return d->minimum;
-}
-
-
-/*!
- \property QAbstractSlider::maximum
- \brief the slider's maximum value
-
- When setting this property, the \l minimum is adjusted if
- necessary to ensure that the range remains valid. Also the
- slider's current value is adjusted to be within the new range.
-
-
-*/
-
-void QAbstractSlider::setMaximum(int max)
-{
- Q_D(QAbstractSlider);
- setRange(qMin(d->minimum, max), max);
-}
-
-int QAbstractSlider::maximum() const
-{
- Q_D(const QAbstractSlider);
- return d->maximum;
-}
-
-
-
-/*!
- \property QAbstractSlider::singleStep
- \brief the single step.
-
- The smaller of two natural steps that an
- abstract sliders provides and typically corresponds to the user
- pressing an arrow key.
-
- If the property is modified during an auto repeating key event, behavior
- is undefined.
-
- \sa pageStep
-*/
-
-void QAbstractSlider::setSingleStep(int step)
-{
- Q_D(QAbstractSlider);
- if (step != d->singleStep)
- d->setSteps(step, d->pageStep);
-}
-
-int QAbstractSlider::singleStep() const
-{
- Q_D(const QAbstractSlider);
- return d->singleStep;
-}
-
-
-/*!
- \property QAbstractSlider::pageStep
- \brief the page step.
-
- The larger of two natural steps that an abstract slider provides
- and typically corresponds to the user pressing PageUp or PageDown.
-
- \sa singleStep
-*/
-
-void QAbstractSlider::setPageStep(int step)
-{
- Q_D(QAbstractSlider);
- if (step != d->pageStep)
- d->setSteps(d->singleStep, step);
-}
-
-int QAbstractSlider::pageStep() const
-{
- Q_D(const QAbstractSlider);
- return d->pageStep;
-}
-
-/*!
- \property QAbstractSlider::tracking
- \brief whether slider tracking is enabled
-
- If tracking is enabled (the default), the slider emits the
- valueChanged() signal while the slider is being dragged. If
- tracking is disabled, the slider emits the valueChanged() signal
- only when the user releases the slider.
-
- \sa sliderDown
-*/
-void QAbstractSlider::setTracking(bool enable)
-{
- Q_D(QAbstractSlider);
- d->tracking = enable;
-}
-
-bool QAbstractSlider::hasTracking() const
-{
- Q_D(const QAbstractSlider);
- return d->tracking;
-}
-
-
-/*!
- \property QAbstractSlider::sliderDown
- \brief whether the slider is pressed down.
-
- The property is set by subclasses in order to let the abstract
- slider know whether or not \l tracking has any effect.
-
- Changing the slider down property emits the sliderPressed() and
- sliderReleased() signals.
-
-*/
-void QAbstractSlider::setSliderDown(bool down)
-{
- Q_D(QAbstractSlider);
- bool doEmit = d->pressed != down;
-
- d->pressed = down;
-
- if (doEmit) {
- if (down)
- emit sliderPressed();
- else
- emit sliderReleased();
- }
-
- if (!down && d->position != d->value)
- triggerAction(SliderMove);
-}
-
-bool QAbstractSlider::isSliderDown() const
-{
- Q_D(const QAbstractSlider);
- return d->pressed;
-}
-
-
-/*!
- \property QAbstractSlider::sliderPosition
- \brief the current slider position
-
- If \l tracking is enabled (the default), this is identical to \l value.
-*/
-void QAbstractSlider::setSliderPosition(int position)
-{
- Q_D(QAbstractSlider);
- position = d->bound(position);
- if (position == d->position)
- return;
- d->position = position;
- if (!d->tracking)
- update();
- if (d->pressed)
- emit sliderMoved(position);
- if (d->tracking && !d->blocktracking)
- triggerAction(SliderMove);
-}
-
-int QAbstractSlider::sliderPosition() const
-{
- Q_D(const QAbstractSlider);
- return d->position;
-}
-
-
-/*!
- \property QAbstractSlider::value
- \brief the slider's current value
-
- The slider forces the value to be within the legal range: \l
- minimum <= \c value <= \l maximum.
-
- Changing the value also changes the \l sliderPosition.
-*/
-
-
-int QAbstractSlider::value() const
-{
- Q_D(const QAbstractSlider);
- return d->value;
-}
-
-void QAbstractSlider::setValue(int value)
-{
- Q_D(QAbstractSlider);
- value = d->bound(value);
- if (d->value == value && d->position == value)
- return;
- d->value = value;
- if (d->position != value) {
- d->position = value;
- if (d->pressed)
- emit sliderMoved((d->position = value));
- }
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::ValueChanged);
-#endif
- sliderChange(SliderValueChange);
- emit valueChanged(value);
-}
-
-/*!
- \property QAbstractSlider::invertedAppearance
- \brief whether or not a slider shows its values inverted.
-
- If this property is false (the default), the minimum and maximum will
- be shown in its classic position for the inherited widget. If the
- value is true, the minimum and maximum appear at their opposite location.
-
- Note: This property makes most sense for sliders and dials. For
- scroll bars, the visual effect of the scroll bar subcontrols depends on
- whether or not the styles understand inverted appearance; most styles
- ignore this property for scroll bars.
-*/
-
-bool QAbstractSlider::invertedAppearance() const
-{
- Q_D(const QAbstractSlider);
- return d->invertedAppearance;
-}
-
-void QAbstractSlider::setInvertedAppearance(bool invert)
-{
- Q_D(QAbstractSlider);
- d->invertedAppearance = invert;
- update();
-}
-
-
-/*!
- \property QAbstractSlider::invertedControls
- \brief whether or not the slider inverts its wheel and key events.
-
- If this property is false, scrolling the mouse wheel "up" and using keys
- like page up will increase the slider's value towards its maximum. Otherwise
- pressing page up will move value towards the slider's minimum.
-*/
-
-
-bool QAbstractSlider::invertedControls() const
-{
- Q_D(const QAbstractSlider);
- return d->invertedControls;
-}
-
-void QAbstractSlider::setInvertedControls(bool invert)
-{
- Q_D(QAbstractSlider);
- d->invertedControls = invert;
-}
-
-/*! Triggers a slider \a action. Possible actions are \l
- SliderSingleStepAdd, \l SliderSingleStepSub, \l SliderPageStepAdd,
- \l SliderPageStepSub, \l SliderToMinimum, \l SliderToMaximum, and \l
- SliderMove.
-
- \sa actionTriggered()
- */
-void QAbstractSlider::triggerAction(SliderAction action)
-{
- Q_D(QAbstractSlider);
- d->blocktracking = true;
- switch (action) {
- case SliderSingleStepAdd:
- setSliderPosition(d->overflowSafeAdd(d->effectiveSingleStep()));
- break;
- case SliderSingleStepSub:
- setSliderPosition(d->overflowSafeAdd(-d->effectiveSingleStep()));
- break;
- case SliderPageStepAdd:
- setSliderPosition(d->overflowSafeAdd(d->pageStep));
- break;
- case SliderPageStepSub:
- setSliderPosition(d->overflowSafeAdd(-d->pageStep));
- break;
- case SliderToMinimum:
- setSliderPosition(d->minimum);
- break;
- case SliderToMaximum:
- setSliderPosition(d->maximum);
- break;
- case SliderMove:
- case SliderNoAction:
- break;
- };
- emit actionTriggered(action);
- d->blocktracking = false;
- setValue(d->position);
-}
-
-/*! Sets action \a action to be triggered repetitively in intervals
-of \a repeatTime, after an initial delay of \a thresholdTime.
-
-\sa triggerAction() repeatAction()
- */
-void QAbstractSlider::setRepeatAction(SliderAction action, int thresholdTime, int repeatTime)
-{
- Q_D(QAbstractSlider);
- if ((d->repeatAction = action) == SliderNoAction) {
- d->repeatActionTimer.stop();
- } else {
- d->repeatActionTime = repeatTime;
- d->repeatActionTimer.start(thresholdTime, this);
- }
-}
-
-/*!
- Returns the current repeat action.
- \sa setRepeatAction()
- */
-QAbstractSlider::SliderAction QAbstractSlider::repeatAction() const
-{
- Q_D(const QAbstractSlider);
- return d->repeatAction;
-}
-
-/*!\reimp
- */
-void QAbstractSlider::timerEvent(QTimerEvent *e)
-{
- Q_D(QAbstractSlider);
- if (e->timerId() == d->repeatActionTimer.timerId()) {
- if (d->repeatActionTime) { // was threshold time, use repeat time next time
- d->repeatActionTimer.start(d->repeatActionTime, this);
- d->repeatActionTime = 0;
- }
- if (d->repeatAction == SliderPageStepAdd)
- d->setAdjustedSliderPosition(d->overflowSafeAdd(d->pageStep));
- else if (d->repeatAction == SliderPageStepSub)
- d->setAdjustedSliderPosition(d->overflowSafeAdd(-d->pageStep));
- else
- triggerAction(d->repeatAction);
- }
-}
-
-/*!
- Reimplement this virtual function to track slider changes such as
- \l SliderRangeChange, \l SliderOrientationChange, \l
- SliderStepsChange, or \l SliderValueChange. The default
- implementation only updates the display and ignores the \a change
- parameter.
- */
-void QAbstractSlider::sliderChange(SliderChange)
-{
- update();
-}
-
-bool QAbstractSliderPrivate::scrollByDelta(Qt::Orientation orientation, Qt::KeyboardModifiers modifiers, int delta)
-{
- Q_Q(QAbstractSlider);
- int stepsToScroll = 0;
- // in Qt scrolling to the right gives negative values.
- if (orientation == Qt::Horizontal)
- delta = -delta;
- qreal offset = qreal(delta) / 120;
-
- if ((modifiers & Qt::ControlModifier) || (modifiers & Qt::ShiftModifier)) {
- // Scroll one page regardless of delta:
- stepsToScroll = qBound(-pageStep, int(offset * pageStep), pageStep);
- offset_accumulated = 0;
- } else {
- // Calculate how many lines to scroll. Depending on what delta is (and
- // offset), we might end up with a fraction (e.g. scroll 1.3 lines). We can
- // only scroll whole lines, so we keep the reminder until next event.
- qreal stepsToScrollF =
-#ifndef QT_NO_WHEELEVENT
- QApplication::wheelScrollLines() *
-#endif
- offset * effectiveSingleStep();
- // Check if wheel changed direction since last event:
- if (offset_accumulated != 0 && (offset / offset_accumulated) < 0)
- offset_accumulated = 0;
-
- offset_accumulated += stepsToScrollF;
-#ifndef Q_WS_MAC
- // Don't scroll more than one page in any case:
- stepsToScroll = qBound(-pageStep, int(offset_accumulated), pageStep);
-#else
- // Native UI-elements on Mac can scroll hundreds of lines at a time as
- // a result of acceleration. So keep the same behaviour in Qt, and
- // don't restrict stepsToScroll to certain maximum (pageStep):
- stepsToScroll = int(offset_accumulated);
-#endif
- offset_accumulated -= int(offset_accumulated);
- if (stepsToScroll == 0)
- return false;
- }
-
- if (invertedControls)
- stepsToScroll = -stepsToScroll;
-
- int prevValue = value;
- position = overflowSafeAdd(stepsToScroll); // value will be updated by triggerAction()
- q->triggerAction(QAbstractSlider::SliderMove);
-
- if (prevValue == value) {
- offset_accumulated = 0;
- return false;
- }
- return true;
-}
-
-/*!
- \reimp
-*/
-#ifndef QT_NO_WHEELEVENT
-void QAbstractSlider::wheelEvent(QWheelEvent * e)
-{
- Q_D(QAbstractSlider);
- e->ignore();
- int delta = e->delta();
- if (d->scrollByDelta(e->orientation(), e->modifiers(), delta))
- e->accept();
-}
-
-#endif
-
-/*!
- \reimp
-*/
-void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
-{
- Q_D(QAbstractSlider);
- SliderAction action = SliderNoAction;
-#ifdef QT_KEYPAD_NAVIGATION
- if (ev->isAutoRepeat()) {
- if (!d->firstRepeat.isValid())
- d->firstRepeat.start();
- else if (1 == d->repeatMultiplier) {
- // This is the interval in milli seconds which one key repetition
- // takes.
- const int repeatMSecs = d->firstRepeat.elapsed();
-
- /**
- * The time it takes to currently navigate the whole slider.
- */
- const qreal currentTimeElapse = (qreal(maximum()) / singleStep()) * repeatMSecs;
-
- /**
- * This is an arbitrarily determined constant in msecs that
- * specifies how long time it should take to navigate from the
- * start to the end(excluding starting key auto repeat).
- */
- const int SliderRepeatElapse = 2500;
-
- d->repeatMultiplier = currentTimeElapse / SliderRepeatElapse;
- }
-
- }
- else if (d->firstRepeat.isValid()) {
- d->firstRepeat.invalidate();
- d->repeatMultiplier = 1;
- }
-
-#endif
-
- switch (ev->key()) {
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled())
- setEditFocus(!hasEditFocus());
- else
- ev->ignore();
- break;
- case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
- setValue(d->origValue);
- setEditFocus(false);
- } else
- ev->ignore();
- break;
-#endif
-
- // It seems we need to use invertedAppearance for Left and right, otherwise, things look weird.
- case Qt::Key_Left:
-#ifdef QT_KEYPAD_NAVIGATION
- // In QApplication::KeypadNavigationDirectional, we want to change the slider
- // value if there is no left/right navigation possible and if this slider is not
- // inside a tab widget.
- if (QApplication::keypadNavigationEnabled()
- && (!hasEditFocus() && QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
- || d->orientation == Qt::Vertical
- || !hasEditFocus()
- && (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal) || QWidgetPrivate::inTabWidget(this)))) {
- ev->ignore();
- return;
- }
- if (QApplication::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
- action = d->invertedControls ? SliderSingleStepSub : SliderSingleStepAdd;
- else
-#endif
- if (isRightToLeft())
- action = d->invertedAppearance ? SliderSingleStepSub : SliderSingleStepAdd;
- else
- action = !d->invertedAppearance ? SliderSingleStepSub : SliderSingleStepAdd;
- break;
- case Qt::Key_Right:
-#ifdef QT_KEYPAD_NAVIGATION
- // Same logic as in Qt::Key_Left
- if (QApplication::keypadNavigationEnabled()
- && (!hasEditFocus() && QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
- || d->orientation == Qt::Vertical
- || !hasEditFocus()
- && (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal) || QWidgetPrivate::inTabWidget(this)))) {
- ev->ignore();
- return;
- }
- if (QApplication::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
- action = d->invertedControls ? SliderSingleStepAdd : SliderSingleStepSub;
- else
-#endif
- if (isRightToLeft())
- action = d->invertedAppearance ? SliderSingleStepAdd : SliderSingleStepSub;
- else
- action = !d->invertedAppearance ? SliderSingleStepAdd : SliderSingleStepSub;
- break;
- case Qt::Key_Up:
-#ifdef QT_KEYPAD_NAVIGATION
- // In QApplication::KeypadNavigationDirectional, we want to change the slider
- // value if there is no up/down navigation possible.
- if (QApplication::keypadNavigationEnabled()
- && (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
- || d->orientation == Qt::Horizontal
- || !hasEditFocus() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical))) {
- ev->ignore();
- break;
- }
-#endif
- action = d->invertedControls ? SliderSingleStepSub : SliderSingleStepAdd;
- break;
- case Qt::Key_Down:
-#ifdef QT_KEYPAD_NAVIGATION
- // Same logic as in Qt::Key_Up
- if (QApplication::keypadNavigationEnabled()
- && (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
- || d->orientation == Qt::Horizontal
- || !hasEditFocus() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical))) {
- ev->ignore();
- break;
- }
-#endif
- action = d->invertedControls ? SliderSingleStepAdd : SliderSingleStepSub;
- break;
- case Qt::Key_PageUp:
- action = d->invertedControls ? SliderPageStepSub : SliderPageStepAdd;
- break;
- case Qt::Key_PageDown:
- action = d->invertedControls ? SliderPageStepAdd : SliderPageStepSub;
- break;
- case Qt::Key_Home:
- action = SliderToMinimum;
- break;
- case Qt::Key_End:
- action = SliderToMaximum;
- break;
- default:
- ev->ignore();
- break;
- }
- if (action)
- triggerAction(action);
-}
-
-/*!
- \reimp
-*/
-void QAbstractSlider::changeEvent(QEvent *ev)
-{
- Q_D(QAbstractSlider);
- switch (ev->type()) {
- case QEvent::EnabledChange:
- if (!isEnabled()) {
- d->repeatActionTimer.stop();
- setSliderDown(false);
- }
- // fall through...
- default:
- QWidget::changeEvent(ev);
- }
-}
-
-/*!
- \reimp
-*/
-bool QAbstractSlider::event(QEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- Q_D(QAbstractSlider);
- switch (e->type()) {
- case QEvent::FocusIn:
- d->origValue = d->value;
- break;
- default:
- break;
- }
-#endif
-
- return QWidget::event(e);
-}
-
-/*! \fn int QAbstractSlider::minValue() const
-
- Use minimum() instead.
-*/
-
-/*! \fn int QAbstractSlider::maxValue() const
-
- Use maximum() instead.
-*/
-
-/*! \fn int QAbstractSlider::lineStep() const
-
- Use singleStep() instead.
-*/
-
-/*! \fn void QAbstractSlider::setMinValue(int v)
-
- Use setMinimum() instead.
-*/
-
-/*! \fn void QAbstractSlider::setMaxValue(int v)
-
- Use setMaximum() instead.
-*/
-
-/*! \fn void QAbstractSlider::setLineStep(int v)
-
- Use setSingleStep() instead.
-*/
-
-/*! \fn void QAbstractSlider::addPage()
-
- Use triggerAction(QAbstractSlider::SliderPageStepAdd) instead.
-*/
-
-/*! \fn void QAbstractSlider::subtractPage()
-
- Use triggerAction(QAbstractSlider::SliderPageStepSub) instead.
-*/
-
-/*! \fn void QAbstractSlider::addLine()
-
- Use triggerAction(QAbstractSlider::SliderSingleStepAdd) instead.
-*/
-
-/*! \fn void QAbstractSlider::subtractLine()
-
- Use triggerAction(QAbstractSlider::SliderSingleStepSub) instead.
-*/
-
-/*! \fn void QAbstractSlider::setSteps(int single, int page)
-
- Use setSingleStep(\a single) followed by setPageStep(\a page)
- instead.
-*/
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qabstractslider.h b/src/gui/widgets/qabstractslider.h
deleted file mode 100644
index bdcfe0ecc9..0000000000
--- a/src/gui/widgets/qabstractslider.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTSLIDER_H
-#define QABSTRACTSLIDER_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QAbstractSliderPrivate;
-
-class Q_GUI_EXPORT QAbstractSlider : public QWidget
-{
- Q_OBJECT
-
- Q_PROPERTY(int minimum READ minimum WRITE setMinimum)
- Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
- Q_PROPERTY(int singleStep READ singleStep WRITE setSingleStep)
- Q_PROPERTY(int pageStep READ pageStep WRITE setPageStep)
- Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged USER true)
- Q_PROPERTY(int sliderPosition READ sliderPosition WRITE setSliderPosition NOTIFY sliderMoved)
- Q_PROPERTY(bool tracking READ hasTracking WRITE setTracking)
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
- Q_PROPERTY(bool invertedAppearance READ invertedAppearance WRITE setInvertedAppearance)
- Q_PROPERTY(bool invertedControls READ invertedControls WRITE setInvertedControls)
- Q_PROPERTY(bool sliderDown READ isSliderDown WRITE setSliderDown DESIGNABLE false)
-
-public:
- explicit QAbstractSlider(QWidget *parent=0);
- ~QAbstractSlider();
-
- Qt::Orientation orientation() const;
-
- void setMinimum(int);
- int minimum() const;
-
- void setMaximum(int);
- int maximum() const;
-
- void setRange(int min, int max);
-
- void setSingleStep(int);
- int singleStep() const;
-
- void setPageStep(int);
- int pageStep() const;
-
- void setTracking(bool enable);
- bool hasTracking() const;
-
- void setSliderDown(bool);
- bool isSliderDown() const;
-
- void setSliderPosition(int);
- int sliderPosition() const;
-
- void setInvertedAppearance(bool);
- bool invertedAppearance() const;
-
- void setInvertedControls(bool);
- bool invertedControls() const;
-
- enum SliderAction {
- SliderNoAction,
- SliderSingleStepAdd,
- SliderSingleStepSub,
- SliderPageStepAdd,
- SliderPageStepSub,
- SliderToMinimum,
- SliderToMaximum,
- SliderMove
- };
-
- int value() const;
-
- void triggerAction(SliderAction action);
-
-public Q_SLOTS:
- void setValue(int);
- void setOrientation(Qt::Orientation);
-
-Q_SIGNALS:
- void valueChanged(int value);
-
- void sliderPressed();
- void sliderMoved(int position);
- void sliderReleased();
-
- void rangeChanged(int min, int max);
-
- void actionTriggered(int action);
-
-protected:
- bool event(QEvent *e);
-
- void setRepeatAction(SliderAction action, int thresholdTime = 500, int repeatTime = 50);
- SliderAction repeatAction() const;
-
- enum SliderChange {
- SliderRangeChange,
- SliderOrientationChange,
- SliderStepsChange,
- SliderValueChange
- };
- virtual void sliderChange(SliderChange change);
-
- void keyPressEvent(QKeyEvent *ev);
- void timerEvent(QTimerEvent *);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *e);
-#endif
- void changeEvent(QEvent *e);
-
-#ifdef QT3_SUPPORT
-public:
- inline QT3_SUPPORT int minValue() const { return minimum(); }
- inline QT3_SUPPORT int maxValue() const { return maximum(); }
- inline QT3_SUPPORT int lineStep() const { return singleStep(); }
- inline QT3_SUPPORT void setMinValue(int v) { setMinimum(v); }
- inline QT3_SUPPORT void setMaxValue(int v) { setMaximum(v); }
- inline QT3_SUPPORT void setLineStep(int v) { setSingleStep(v); }
- inline QT3_SUPPORT void setSteps(int single, int page) { setSingleStep(single); setPageStep(page); }
- inline QT3_SUPPORT void addPage() { triggerAction(SliderPageStepAdd); }
- inline QT3_SUPPORT void subtractPage() { triggerAction(SliderPageStepSub); }
- inline QT3_SUPPORT void addLine() { triggerAction(SliderSingleStepAdd); }
- inline QT3_SUPPORT void subtractLine() { triggerAction(SliderSingleStepSub); }
-#endif
-
-protected:
- QAbstractSlider(QAbstractSliderPrivate &dd, QWidget *parent=0);
-
-private:
- Q_DISABLE_COPY(QAbstractSlider)
- Q_DECLARE_PRIVATE(QAbstractSlider)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTSLIDER_H
diff --git a/src/gui/widgets/qabstractslider_p.h b/src/gui/widgets/qabstractslider_p.h
deleted file mode 100644
index 8887b47b47..0000000000
--- a/src/gui/widgets/qabstractslider_p.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTSLIDER_P_H
-#define QABSTRACTSLIDER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qbasictimer.h"
-#include "QtCore/qelapsedtimer.h"
-#include "private/qwidget_p.h"
-#include "qstyle.h"
-
-QT_BEGIN_NAMESPACE
-
-class QAbstractSliderPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractSlider)
-public:
- QAbstractSliderPrivate();
- ~QAbstractSliderPrivate();
-
- void setSteps(int single, int page);
-
- int minimum, maximum, pageStep, value, position, pressValue;
-
- /**
- * Call effectiveSingleStep() when changing the slider value.
- */
- int singleStep;
-
- float offset_accumulated;
- uint tracking : 1;
- uint blocktracking :1;
- uint pressed : 1;
- uint invertedAppearance : 1;
- uint invertedControls : 1;
- Qt::Orientation orientation;
-
- QBasicTimer repeatActionTimer;
- int repeatActionTime;
- QAbstractSlider::SliderAction repeatAction;
-
-#ifdef QT_KEYPAD_NAVIGATION
- int origValue;
-
- /**
- */
- bool isAutoRepeating;
-
- /**
- * When we're auto repeating, we multiply singleStep with this value to
- * get our effective step.
- */
- qreal repeatMultiplier;
-
- /**
- * The time of when the first auto repeating key press event occurs.
- */
- QElapsedTimer firstRepeat;
-
-#endif
-
- inline int effectiveSingleStep() const
- {
- return singleStep
-#ifdef QT_KEYPAD_NAVIGATION
- * repeatMultiplier
-#endif
- ;
- }
-
- virtual int bound(int val) const { return qMax(minimum, qMin(maximum, val)); }
- inline int overflowSafeAdd(int add) const
- {
- int newValue = value + add;
- if (add > 0 && newValue < value)
- newValue = maximum;
- else if (add < 0 && newValue > value)
- newValue = minimum;
- return newValue;
- }
- inline void setAdjustedSliderPosition(int position)
- {
- Q_Q(QAbstractSlider);
- if (q->style()->styleHint(QStyle::SH_Slider_StopMouseOverSlider, 0, q)) {
- if ((position > pressValue - 2 * pageStep) && (position < pressValue + 2 * pageStep)) {
- repeatAction = QAbstractSlider::SliderNoAction;
- q->setSliderPosition(pressValue);
- return;
- }
- }
- q->triggerAction(repeatAction);
- }
- bool scrollByDelta(Qt::Orientation orientation, Qt::KeyboardModifiers modifiers, int delta);
-};
-
-QT_END_NAMESPACE
-
-#endif // QABSTRACTSLIDER_P_H
diff --git a/src/gui/widgets/qabstractspinbox.cpp b/src/gui/widgets/qabstractspinbox.cpp
deleted file mode 100644
index 34991ab236..0000000000
--- a/src/gui/widgets/qabstractspinbox.cpp
+++ /dev/null
@@ -1,2122 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qabstractspinbox_p.h>
-#include <private/qdatetime_p.h>
-#include <private/qlineedit_p.h>
-#include <qabstractspinbox.h>
-
-#ifndef QT_NO_SPINBOX
-
-#include <qapplication.h>
-#include <qclipboard.h>
-#include <qdatetime.h>
-#include <qdatetimeedit.h>
-#include <qevent.h>
-#include <qmenu.h>
-#include <qpainter.h>
-#include <qpalette.h>
-#include <qstylepainter.h>
-#include <qdebug.h>
-#ifndef QT_NO_ACCESSIBILITY
-# include <qaccessible.h>
-#endif
-
-#if defined(Q_WS_X11)
-#include <limits.h>
-#endif
-
-#if defined(Q_OS_SYMBIAN)
-#include <w32std.h>
-#include <private/qt_s60_p.h>
-#endif
-
-//#define QABSTRACTSPINBOX_QSBDEBUG
-#ifdef QABSTRACTSPINBOX_QSBDEBUG
-# define QASBDEBUG qDebug
-#else
-# define QASBDEBUG if (false) qDebug
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QAbstractSpinBox
- \brief The QAbstractSpinBox class provides a spinbox and a line edit to
- display values.
-
- \ingroup abstractwidgets
-
- The class is designed as a common super class for widgets like
- QSpinBox, QDoubleSpinBox and QDateTimeEdit
-
- Here are the main properties of the class:
-
- \list 1
-
- \i \l text: The text that is displayed in the QAbstractSpinBox.
-
- \i \l alignment: The alignment of the text in the QAbstractSpinBox.
-
- \i \l wrapping: Whether the QAbstractSpinBox wraps from the
- minimum value to the maximum value and vica versa.
-
- \endlist
-
- QAbstractSpinBox provides a virtual stepBy() function that is
- called whenever the user triggers a step. This function takes an
- integer value to signify how many steps were taken. E.g. Pressing
- Qt::Key_Down will trigger a call to stepBy(-1).
-
- QAbstractSpinBox also provide a virtual function stepEnabled() to
- determine whether stepping up/down is allowed at any point. This
- function returns a bitset of StepEnabled.
-
- \sa QAbstractSlider, QSpinBox, QDoubleSpinBox, QDateTimeEdit,
- {Spin Boxes Example}
-*/
-
-/*!
- \enum QAbstractSpinBox::StepEnabledFlag
-
- \value StepNone
- \value StepUpEnabled
- \value StepDownEnabled
-*/
-
-/*!
- \fn void QAbstractSpinBox::editingFinished()
-
- This signal is emitted editing is finished. This happens when the
- spinbox loses focus and when enter is pressed.
-*/
-
-/*!
- Constructs an abstract spinbox with the given \a parent with default
- \l wrapping, and \l alignment properties.
-*/
-
-QAbstractSpinBox::QAbstractSpinBox(QWidget *parent)
- : QWidget(*new QAbstractSpinBoxPrivate, parent, 0)
-{
- Q_D(QAbstractSpinBox);
- d->init();
-}
-
-/*!
- \internal
-*/
-QAbstractSpinBox::QAbstractSpinBox(QAbstractSpinBoxPrivate &dd, QWidget *parent)
- : QWidget(dd, parent, 0)
-{
- Q_D(QAbstractSpinBox);
- d->init();
-}
-
-/*!
- Called when the QAbstractSpinBox is destroyed.
-*/
-
-QAbstractSpinBox::~QAbstractSpinBox()
-{
-}
-
-/*!
- \enum QAbstractSpinBox::ButtonSymbols
-
- This enum type describes the symbols that can be displayed on the buttons
- in a spin box.
-
- \inlineimage qspinbox-updown.png
- \inlineimage qspinbox-plusminus.png
-
- \value UpDownArrows Little arrows in the classic style.
- \value PlusMinus \bold{+} and \bold{-} symbols.
- \value NoButtons Don't display buttons.
-
- \sa QAbstractSpinBox::buttonSymbols
-*/
-
-/*!
- \property QAbstractSpinBox::buttonSymbols
-
- \brief the current button symbol mode
-
- The possible values can be either \c UpDownArrows or \c PlusMinus.
- The default is \c UpDownArrows.
-
- Note that some styles might render PlusMinus and UpDownArrows
- identically.
-
- \sa ButtonSymbols
-*/
-
-QAbstractSpinBox::ButtonSymbols QAbstractSpinBox::buttonSymbols() const
-{
- Q_D(const QAbstractSpinBox);
- return d->buttonSymbols;
-}
-
-void QAbstractSpinBox::setButtonSymbols(ButtonSymbols buttonSymbols)
-{
- Q_D(QAbstractSpinBox);
- if (d->buttonSymbols != buttonSymbols) {
- d->buttonSymbols = buttonSymbols;
- d->updateEditFieldGeometry();
- update();
- }
-}
-
-/*!
- \property QAbstractSpinBox::text
-
- \brief the spin box's text, including any prefix and suffix
-
- There is no default text.
-*/
-
-QString QAbstractSpinBox::text() const
-{
- return lineEdit()->displayText();
-}
-
-
-/*!
- \property QAbstractSpinBox::specialValueText
- \brief the special-value text
-
- If set, the spin box will display this text instead of a numeric
- value whenever the current value is equal to minimum(). Typical use
- is to indicate that this choice has a special (default) meaning.
-
- For example, if your spin box allows the user to choose a scale factor
- (or zoom level) for displaying an image, and your application is able
- to automatically choose one that will enable the image to fit completely
- within the display window, you can set up the spin box like this:
-
- \snippet examples/widgets/spinboxes/window.cpp 3
-
- The user will then be able to choose a scale from 1% to 1000%
- or select "Auto" to leave it up to the application to choose. Your code
- must then interpret the spin box value of 0 as a request from the user
- to scale the image to fit inside the window.
-
- All values are displayed with the prefix and suffix (if set), \e
- except for the special value, which only shows the special value
- text. This special text is passed in the QSpinBox::valueChanged()
- signal that passes a QString.
-
- To turn off the special-value text display, call this function
- with an empty string. The default is no special-value text, i.e.
- the numeric value is shown as usual.
-
- If no special-value text is set, specialValueText() returns an
- empty string.
-*/
-
-QString QAbstractSpinBox::specialValueText() const
-{
- Q_D(const QAbstractSpinBox);
- return d->specialValueText;
-}
-
-void QAbstractSpinBox::setSpecialValueText(const QString &specialValueText)
-{
- Q_D(QAbstractSpinBox);
-
- d->specialValueText = specialValueText;
- d->cachedSizeHint = QSize(); // minimumSizeHint doesn't care about specialValueText
- d->clearCache();
- d->updateEdit();
-}
-
-/*!
- \property QAbstractSpinBox::wrapping
-
- \brief whether the spin box is circular.
-
- If wrapping is true stepping up from maximum() value will take you
- to the minimum() value and vica versa. Wrapping only make sense if
- you have minimum() and maximum() values set.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qabstractspinbox.cpp 0
-
- \sa QSpinBox::minimum(), QSpinBox::maximum()
-*/
-
-bool QAbstractSpinBox::wrapping() const
-{
- Q_D(const QAbstractSpinBox);
- return d->wrapping;
-}
-
-void QAbstractSpinBox::setWrapping(bool wrapping)
-{
- Q_D(QAbstractSpinBox);
- d->wrapping = wrapping;
-}
-
-
-/*!
- \property QAbstractSpinBox::readOnly
- \brief whether the spin box is read only.
-
- In read-only mode, the user can still copy the text to the
- clipboard, or drag and drop the text;
- but cannot edit it.
-
- The QLineEdit in the QAbstractSpinBox does not show a cursor in
- read-only mode.
-
- \sa QLineEdit::readOnly
-*/
-
-bool QAbstractSpinBox::isReadOnly() const
-{
- Q_D(const QAbstractSpinBox);
- return d->readOnly;
-}
-
-void QAbstractSpinBox::setReadOnly(bool enable)
-{
- Q_D(QAbstractSpinBox);
- d->readOnly = enable;
- d->edit->setReadOnly(enable);
- update();
-}
-
-/*!
- \property QAbstractSpinBox::keyboardTracking
- \brief whether keyboard tracking is enabled for the spinbox.
- \since 4.3
-
- If keyboard tracking is enabled (the default), the spinbox
- emits the valueChanged() signal while the new value is being
- entered from the keyboard.
-
- E.g. when the user enters the value 600 by typing 6, 0, and 0,
- the spinbox emits 3 signals with the values 6, 60, and 600
- respectively.
-
- If keyboard tracking is disabled, the spinbox doesn't emit the
- valueChanged() signal while typing. It emits the signal later,
- when the return key is pressed, when keyboard focus is lost, or
- when other spinbox functionality is used, e.g. pressing an arrow
- key.
-*/
-
-bool QAbstractSpinBox::keyboardTracking() const
-{
- Q_D(const QAbstractSpinBox);
- return d->keyboardTracking;
-}
-
-void QAbstractSpinBox::setKeyboardTracking(bool enable)
-{
- Q_D(QAbstractSpinBox);
- d->keyboardTracking = enable;
-}
-
-/*!
- \property QAbstractSpinBox::frame
- \brief whether the spin box draws itself with a frame
-
- If enabled (the default) the spin box draws itself inside a frame,
- otherwise the spin box draws itself without any frame.
-*/
-
-bool QAbstractSpinBox::hasFrame() const
-{
- Q_D(const QAbstractSpinBox);
- return d->frame;
-}
-
-
-void QAbstractSpinBox::setFrame(bool enable)
-{
- Q_D(QAbstractSpinBox);
- d->frame = enable;
- update();
- d->updateEditFieldGeometry();
-}
-
-/*!
- \property QAbstractSpinBox::accelerated
- \brief whether the spin box will accelerate the frequency of the steps when
- pressing the step Up/Down buttons.
- \since 4.2
-
- If enabled the spin box will increase/decrease the value faster
- the longer you hold the button down.
-*/
-
-void QAbstractSpinBox::setAccelerated(bool accelerate)
-{
- Q_D(QAbstractSpinBox);
- d->accelerate = accelerate;
-
-}
-bool QAbstractSpinBox::isAccelerated() const
-{
- Q_D(const QAbstractSpinBox);
- return d->accelerate;
-}
-
-/*!
- \enum QAbstractSpinBox::CorrectionMode
-
- This enum type describes the mode the spinbox will use to correct
- an \l{QValidator::}{Intermediate} value if editing finishes.
-
- \value CorrectToPreviousValue The spinbox will revert to the last
- valid value.
-
- \value CorrectToNearestValue The spinbox will revert to the nearest
- valid value.
-
- \sa correctionMode
-*/
-
-/*!
- \property QAbstractSpinBox::correctionMode
- \brief the mode to correct an \l{QValidator::}{Intermediate}
- value if editing finishes
- \since 4.2
-
- The default mode is QAbstractSpinBox::CorrectToPreviousValue.
-
- \sa acceptableInput, validate(), fixup()
-*/
-void QAbstractSpinBox::setCorrectionMode(CorrectionMode correctionMode)
-{
- Q_D(QAbstractSpinBox);
- d->correctionMode = correctionMode;
-
-}
-QAbstractSpinBox::CorrectionMode QAbstractSpinBox::correctionMode() const
-{
- Q_D(const QAbstractSpinBox);
- return d->correctionMode;
-}
-
-
-/*!
- \property QAbstractSpinBox::acceptableInput
- \brief whether the input satisfies the current validation
- \since 4.2
-
- \sa validate(), fixup(), correctionMode
-*/
-
-bool QAbstractSpinBox::hasAcceptableInput() const
-{
- Q_D(const QAbstractSpinBox);
- return d->edit->hasAcceptableInput();
-}
-
-/*!
- \property QAbstractSpinBox::alignment
- \brief the alignment of the spin box
-
- Possible Values are Qt::AlignLeft, Qt::AlignRight, and Qt::AlignHCenter.
-
- By default, the alignment is Qt::AlignLeft
-
- Attempting to set the alignment to an illegal flag combination
- does nothing.
-
- \sa Qt::Alignment
-*/
-
-Qt::Alignment QAbstractSpinBox::alignment() const
-{
- Q_D(const QAbstractSpinBox);
-
- return (Qt::Alignment)d->edit->alignment();
-}
-
-void QAbstractSpinBox::setAlignment(Qt::Alignment flag)
-{
- Q_D(QAbstractSpinBox);
-
- d->edit->setAlignment(flag);
-}
-
-/*!
- Selects all the text in the spinbox except the prefix and suffix.
-*/
-
-void QAbstractSpinBox::selectAll()
-{
- Q_D(QAbstractSpinBox);
-
-
- if (!d->specialValue()) {
- const int tmp = d->edit->displayText().size() - d->suffix.size();
- d->edit->setSelection(tmp, -(tmp - d->prefix.size()));
- } else {
- d->edit->selectAll();
- }
-}
-
-/*!
- Clears the lineedit of all text but prefix and suffix.
-*/
-
-void QAbstractSpinBox::clear()
-{
- Q_D(QAbstractSpinBox);
-
- d->edit->setText(d->prefix + d->suffix);
- d->edit->setCursorPosition(d->prefix.size());
- d->cleared = true;
-}
-
-/*!
- Virtual function that determines whether stepping up and down is
- legal at any given time.
-
- The up arrow will be painted as disabled unless (stepEnabled() &
- StepUpEnabled) != 0.
-
- The default implementation will return (StepUpEnabled|
- StepDownEnabled) if wrapping is turned on. Else it will return
- StepDownEnabled if value is > minimum() or'ed with StepUpEnabled if
- value < maximum().
-
- If you subclass QAbstractSpinBox you will need to reimplement this function.
-
- \sa QSpinBox::minimum(), QSpinBox::maximum(), wrapping()
-*/
-
-
-QAbstractSpinBox::StepEnabled QAbstractSpinBox::stepEnabled() const
-{
- Q_D(const QAbstractSpinBox);
- if (d->readOnly || d->type == QVariant::Invalid)
- return StepNone;
- if (d->wrapping)
- return StepEnabled(StepUpEnabled | StepDownEnabled);
- StepEnabled ret = StepNone;
- if (d->variantCompare(d->value, d->maximum) < 0) {
- ret |= StepUpEnabled;
- }
- if (d->variantCompare(d->value, d->minimum) > 0) {
- ret |= StepDownEnabled;
- }
- return ret;
-}
-
-/*!
- This virtual function is called by the QAbstractSpinBox to
- determine whether \a input is valid. The \a pos parameter indicates
- the position in the string. Reimplemented in the various
- subclasses.
-*/
-
-QValidator::State QAbstractSpinBox::validate(QString & /* input */, int & /* pos */) const
-{
- return QValidator::Acceptable;
-}
-
-/*!
- This virtual function is called by the QAbstractSpinBox if the
- \a input is not validated to QValidator::Acceptable when Return is
- pressed or interpretText() is called. It will try to change the
- text so it is valid. Reimplemented in the various subclasses.
-*/
-
-void QAbstractSpinBox::fixup(QString & /* input */) const
-{
-}
-
-/*!
- Steps up by one linestep
- Calling this slot is analogous to calling stepBy(1);
- \sa stepBy(), stepDown()
-*/
-
-void QAbstractSpinBox::stepUp()
-{
- stepBy(1);
-}
-
-/*!
- Steps down by one linestep
- Calling this slot is analogous to calling stepBy(-1);
- \sa stepBy(), stepUp()
-*/
-
-void QAbstractSpinBox::stepDown()
-{
- stepBy(-1);
-}
-/*!
- Virtual function that is called whenever the user triggers a step.
- The \a steps parameter indicates how many steps were taken, e.g.
- Pressing Qt::Key_Down will trigger a call to stepBy(-1),
- whereas pressing Qt::Key_Prior will trigger a call to
- stepBy(10).
-
- If you subclass QAbstractSpinBox you must reimplement this
- function. Note that this function is called even if the resulting
- value will be outside the bounds of minimum and maximum. It's this
- function's job to handle these situations.
-*/
-
-void QAbstractSpinBox::stepBy(int steps)
-{
- Q_D(QAbstractSpinBox);
-
- const QVariant old = d->value;
- QString tmp = d->edit->displayText();
- int cursorPos = d->edit->cursorPosition();
- bool dontstep = false;
- EmitPolicy e = EmitIfChanged;
- if (d->pendingEmit) {
- dontstep = validate(tmp, cursorPos) != QValidator::Acceptable;
- d->cleared = false;
- d->interpret(NeverEmit);
- if (d->value != old)
- e = AlwaysEmit;
- }
- if (!dontstep) {
- d->setValue(d->bound(d->value + (d->singleStep * steps), old, steps), e);
- } else if (e == AlwaysEmit) {
- d->emitSignals(e, old);
- }
- selectAll();
-}
-
-/*!
- This function returns a pointer to the line edit of the spin box.
-*/
-
-QLineEdit *QAbstractSpinBox::lineEdit() const
-{
- Q_D(const QAbstractSpinBox);
-
- return d->edit;
-}
-
-
-/*!
- \fn void QAbstractSpinBox::setLineEdit(QLineEdit *lineEdit)
-
- Sets the line edit of the spinbox to be \a lineEdit instead of the
- current line edit widget. \a lineEdit can not be 0.
-
- QAbstractSpinBox takes ownership of the new lineEdit
-
- If QLineEdit::validator() for the \a lineEdit returns 0, the internal
- validator of the spinbox will be set on the line edit.
-*/
-
-void QAbstractSpinBox::setLineEdit(QLineEdit *lineEdit)
-{
- Q_D(QAbstractSpinBox);
-
- if (!lineEdit) {
- Q_ASSERT(lineEdit);
- return;
- }
- delete d->edit;
- d->edit = lineEdit;
- if (!d->edit->validator())
- d->edit->setValidator(d->validator);
-
- if (d->edit->parent() != this)
- d->edit->setParent(this);
-
- d->edit->setFrame(false);
- d->edit->setFocusProxy(this);
- d->edit->setAcceptDrops(false);
-
- if (d->type != QVariant::Invalid) {
- connect(d->edit, SIGNAL(textChanged(QString)),
- this, SLOT(_q_editorTextChanged(QString)));
- connect(d->edit, SIGNAL(cursorPositionChanged(int,int)),
- this, SLOT(_q_editorCursorPositionChanged(int,int)));
- }
- d->updateEditFieldGeometry();
- d->edit->setContextMenuPolicy(Qt::NoContextMenu);
-
- if (isVisible())
- d->edit->show();
- if (isVisible())
- d->updateEdit();
-}
-
-
-/*!
- This function interprets the text of the spin box. If the value
- has changed since last interpretation it will emit signals.
-*/
-
-void QAbstractSpinBox::interpretText()
-{
- Q_D(QAbstractSpinBox);
- d->interpret(EmitIfChanged);
-}
-
-/*
- Reimplemented in 4.6, so be careful.
- */
-/*!
- \reimp
-*/
-QVariant QAbstractSpinBox::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- Q_D(const QAbstractSpinBox);
- return d->edit->inputMethodQuery(query);
-}
-
-/*!
- \reimp
-*/
-
-bool QAbstractSpinBox::event(QEvent *event)
-{
- Q_D(QAbstractSpinBox);
- switch (event->type()) {
- case QEvent::FontChange:
- case QEvent::StyleChange:
- d->cachedSizeHint = d->cachedMinimumSizeHint = QSize();
- break;
- case QEvent::ApplicationLayoutDirectionChange:
- case QEvent::LayoutDirectionChange:
- d->updateEditFieldGeometry();
- break;
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d->updateHoverControl(he->pos());
- break;
- case QEvent::ShortcutOverride:
- if (d->edit->event(event))
- return true;
- break;
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::EnterEditFocus:
- case QEvent::LeaveEditFocus:
- if (QApplication::keypadNavigationEnabled()) {
- const bool b = d->edit->event(event);
- d->edit->setSelection(d->edit->displayText().size() - d->suffix.size(),0);
- if (event->type() == QEvent::LeaveEditFocus)
- emit editingFinished();
- if (b)
- return true;
- }
- break;
-#endif
- case QEvent::InputMethod:
- return d->edit->event(event);
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::showEvent(QShowEvent *)
-{
- Q_D(QAbstractSpinBox);
- d->reset();
-
- if (d->ignoreUpdateEdit) {
- d->ignoreUpdateEdit = false;
- } else {
- d->updateEdit();
- }
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::changeEvent(QEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- switch (event->type()) {
- case QEvent::StyleChange:
- d->spinClickTimerInterval = style()->styleHint(QStyle::SH_SpinBox_ClickAutoRepeatRate, 0, this);
- d->spinClickThresholdTimerInterval =
- style()->styleHint(QStyle::SH_SpinBox_ClickAutoRepeatThreshold, 0, this);
- d->reset();
- d->updateEditFieldGeometry();
- break;
- case QEvent::EnabledChange:
- if (!isEnabled()) {
- d->reset();
- }
- break;
- case QEvent::ActivationChange:
- if (!isActiveWindow()){
- d->reset();
- if (d->pendingEmit) // pendingEmit can be true even if it hasn't changed.
- d->interpret(EmitIfChanged); // E.g. 10 to 10.0
- }
- break;
- default:
- break;
- }
- QWidget::changeEvent(event);
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::resizeEvent(QResizeEvent *event)
-{
- Q_D(QAbstractSpinBox);
- QWidget::resizeEvent(event);
-
- d->updateEditFieldGeometry();
- update();
-}
-
-/*!
- \reimp
-*/
-
-QSize QAbstractSpinBox::sizeHint() const
-{
- Q_D(const QAbstractSpinBox);
- if (d->cachedSizeHint.isEmpty()) {
- ensurePolished();
-
- const QFontMetrics fm(fontMetrics());
- int h = d->edit->sizeHint().height();
- int w = 0;
- QString s;
- s = d->prefix + d->textFromValue(d->minimum) + d->suffix + QLatin1Char(' ');
- s.truncate(18);
- w = qMax(w, fm.width(s));
- s = d->prefix + d->textFromValue(d->maximum) + d->suffix + QLatin1Char(' ');
- s.truncate(18);
- w = qMax(w, fm.width(s));
- if (d->specialValueText.size()) {
- s = d->specialValueText;
- w = qMax(w, fm.width(s));
- }
- w += 2; // cursor blinking space
-
- QStyleOptionSpinBox opt;
- initStyleOption(&opt);
- QSize hint(w, h);
- QSize extra(35, 6);
- opt.rect.setSize(hint + extra);
- extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, this).size();
- // get closer to final result by repeating the calculation
- opt.rect.setSize(hint + extra);
- extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, this).size();
- hint += extra;
-
- opt.rect = rect();
- d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
- .expandedTo(QApplication::globalStrut());
- }
- return d->cachedSizeHint;
-}
-
-/*!
- \reimp
-*/
-
-QSize QAbstractSpinBox::minimumSizeHint() const
-{
- Q_D(const QAbstractSpinBox);
- if (d->cachedMinimumSizeHint.isEmpty()) {
- ensurePolished();
-
- const QFontMetrics fm(fontMetrics());
- int h = d->edit->minimumSizeHint().height();
- int w = fm.width(QLatin1String("1000"));
- w += 2; // cursor blinking space
-
- QStyleOptionSpinBox opt;
- initStyleOption(&opt);
- QSize hint(w, h);
- QSize extra(35, 6);
- opt.rect.setSize(hint + extra);
- extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, this).size();
- // get closer to final result by repeating the calculation
- opt.rect.setSize(hint + extra);
- extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, this).size();
- hint += extra;
-
- opt.rect = rect();
-
- d->cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
- .expandedTo(QApplication::globalStrut());
- }
- return d->cachedMinimumSizeHint;
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::paintEvent(QPaintEvent *)
-{
- QStyleOptionSpinBox opt;
- initStyleOption(&opt);
- QStylePainter p(this);
- p.drawComplexControl(QStyle::CC_SpinBox, opt);
-}
-
-/*!
- \reimp
-
- This function handles keyboard input.
-
- The following keys are handled specifically:
- \table
- \row \i Enter/Return
- \i This will reinterpret the text and emit a signal even if the value has not changed
- since last time a signal was emitted.
- \row \i Up
- \i This will invoke stepBy(1)
- \row \i Down
- \i This will invoke stepBy(-1)
- \row \i Page up
- \i This will invoke stepBy(10)
- \row \i Page down
- \i This will invoke stepBy(-10)
- \endtable
-*/
-
-
-void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- if (!event->text().isEmpty() && d->edit->cursorPosition() < d->prefix.size())
- d->edit->setCursorPosition(d->prefix.size());
-
- int steps = 1;
- bool isPgUpOrDown = false;
- switch (event->key()) {
- case Qt::Key_PageUp:
- case Qt::Key_PageDown:
- steps *= 10;
- isPgUpOrDown = true;
- case Qt::Key_Up:
- case Qt::Key_Down: {
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- // Reserve up/down for nav - use left/right for edit.
- if (!hasEditFocus() && (event->key() == Qt::Key_Up
- || event->key() == Qt::Key_Down)) {
- event->ignore();
- return;
- }
- }
-#endif
- event->accept();
- const bool up = (event->key() == Qt::Key_PageUp || event->key() == Qt::Key_Up);
- if (!(stepEnabled() & (up ? StepUpEnabled : StepDownEnabled)))
- return;
- if (!up)
- steps *= -1;
- if (style()->styleHint(QStyle::SH_SpinBox_AnimateButton, 0, this)) {
- d->buttonState = (Keyboard | (up ? Up : Down));
- }
- if (d->spinClickTimerId == -1)
- stepBy(steps);
- if(event->isAutoRepeat() && !isPgUpOrDown) {
- if(d->spinClickThresholdTimerId == -1 && d->spinClickTimerId == -1) {
- d->updateState(up, true);
- }
- }
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::ValueChanged);
-#endif
- return;
- }
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Left:
- case Qt::Key_Right:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- event->ignore();
- return;
- }
- break;
- case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- event->ignore();
- return;
- }
- break;
-#endif
- case Qt::Key_Enter:
- case Qt::Key_Return:
- d->edit->d_func()->control->clearUndo();
- d->interpret(d->keyboardTracking ? AlwaysEmit : EmitIfChanged);
- selectAll();
- event->ignore();
- emit editingFinished();
- return;
-
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- // Toggles between left/right moving cursor and inc/dec.
- setEditFocus(!hasEditFocus());
- }
- return;
-#endif
-
-#ifdef Q_WS_X11 // only X11
- case Qt::Key_U:
- if (event->modifiers() & Qt::ControlModifier) {
- event->accept();
- if (!isReadOnly())
- clear();
- return;
- }
- break;
-#endif
-
- case Qt::Key_End:
- case Qt::Key_Home:
- if (event->modifiers() & Qt::ShiftModifier) {
- int currentPos = d->edit->cursorPosition();
- const QString text = d->edit->displayText();
- if (event->key() == Qt::Key_End) {
- if ((currentPos == 0 && !d->prefix.isEmpty()) || text.size() - d->suffix.size() <= currentPos) {
- break; // let lineedit handle this
- } else {
- d->edit->setSelection(currentPos, text.size() - d->suffix.size() - currentPos);
- }
- } else {
- if ((currentPos == text.size() && !d->suffix.isEmpty()) || currentPos <= d->prefix.size()) {
- break; // let lineedit handle this
- } else {
- d->edit->setSelection(currentPos, d->prefix.size() - currentPos);
- }
- }
- event->accept();
- return;
- }
- break;
-
- default:
-#ifndef QT_NO_SHORTCUT
- if (event == QKeySequence::SelectAll) {
- selectAll();
- event->accept();
- return;
- }
-#endif
- break;
- }
-
- d->edit->event(event);
- if (!isVisible())
- d->ignoreUpdateEdit = true;
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::keyReleaseEvent(QKeyEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- if (d->buttonState & Keyboard && !event->isAutoRepeat()) {
- d->reset();
- } else {
- d->edit->event(event);
- }
-}
-
-/*!
- \reimp
-*/
-
-#ifndef QT_NO_WHEELEVENT
-void QAbstractSpinBox::wheelEvent(QWheelEvent *event)
-{
- const int steps = (event->delta() > 0 ? 1 : -1);
- if (stepEnabled() & (steps > 0 ? StepUpEnabled : StepDownEnabled))
- stepBy(event->modifiers() & Qt::ControlModifier ? steps * 10 : steps);
- event->accept();
-}
-#endif
-
-
-/*!
- \reimp
-*/
-void QAbstractSpinBox::focusInEvent(QFocusEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- d->edit->event(event);
- if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason) {
- selectAll();
- }
- QWidget::focusInEvent(event);
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::focusOutEvent(QFocusEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- if (d->pendingEmit)
- d->interpret(EmitIfChanged);
-
- d->reset();
- d->edit->event(event);
- d->updateEdit();
- QWidget::focusOutEvent(event);
-
-#ifdef QT_KEYPAD_NAVIGATION
- // editingFinished() is already emitted on LeaveEditFocus
- if (!QApplication::keypadNavigationEnabled())
-#endif
- emit editingFinished();
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::closeEvent(QCloseEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- d->reset();
- if (d->pendingEmit)
- d->interpret(EmitIfChanged);
- QWidget::closeEvent(event);
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::hideEvent(QHideEvent *event)
-{
- Q_D(QAbstractSpinBox);
- d->reset();
- if (d->pendingEmit)
- d->interpret(EmitIfChanged);
- QWidget::hideEvent(event);
-}
-
-
-/*!
- \internal
-
- Used when acceleration is turned on. We need to get the
- keyboard auto repeat rate from OS. This value is used as
- argument when starting acceleration related timers.
-
- Every platform should, either, use native calls to obtain
- the value or hard code some reasonable rate.
-
- Remember that time value should be given in msecs.
-*/
-static int getKeyboardAutoRepeatRate() {
- int ret = 30;
-#if defined(Q_OS_SYMBIAN)
- TTimeIntervalMicroSeconds32 initialTime;
- TTimeIntervalMicroSeconds32 time;
- S60->wsSession().GetKeyboardRepeatRate(initialTime, time);
- ret = time.Int() / 1000; // msecs
-#elif defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- DWORD time;
- if (SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &time, 0) != FALSE)
- ret = static_cast<int>(1000 / static_cast<int>(time)); // msecs
-#endif
- return ret; // msecs
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::timerEvent(QTimerEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- bool doStep = false;
- if (event->timerId() == d->spinClickThresholdTimerId) {
- killTimer(d->spinClickThresholdTimerId);
- d->spinClickThresholdTimerId = -1;
- d->effectiveSpinRepeatRate = d->buttonState & Keyboard
- ? getKeyboardAutoRepeatRate()
- : d->spinClickTimerInterval;
- d->spinClickTimerId = startTimer(d->effectiveSpinRepeatRate);
- doStep = true;
- } else if (event->timerId() == d->spinClickTimerId) {
- if (d->accelerate) {
- d->acceleration = d->acceleration + (int)(d->effectiveSpinRepeatRate * 0.05);
- if (d->effectiveSpinRepeatRate - d->acceleration >= 10) {
- killTimer(d->spinClickTimerId);
- d->spinClickTimerId = startTimer(d->effectiveSpinRepeatRate - d->acceleration);
- }
- }
- doStep = true;
- }
-
- if (doStep) {
- const StepEnabled st = stepEnabled();
- if (d->buttonState & Up) {
- if (!(st & StepUpEnabled)) {
- d->reset();
- } else {
- stepBy(1);
- }
- } else if (d->buttonState & Down) {
- if (!(st & StepDownEnabled)) {
- d->reset();
- } else {
- stepBy(-1);
- }
- }
- return;
- }
- QWidget::timerEvent(event);
- return;
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::contextMenuEvent(QContextMenuEvent *event)
-{
-#ifdef QT_NO_CONTEXTMENU
- Q_UNUSED(event);
-#else
- Q_D(QAbstractSpinBox);
-
- QPointer<QMenu> menu = d->edit->createStandardContextMenu();
- if (!menu)
- return;
-
- d->reset();
-
- QAction *selAll = new QAction(tr("&Select All"), menu);
- menu->insertAction(d->edit->d_func()->selectAllAction,
- selAll);
- menu->removeAction(d->edit->d_func()->selectAllAction);
- menu->addSeparator();
- const uint se = stepEnabled();
- QAction *up = menu->addAction(tr("&Step up"));
- up->setEnabled(se & StepUpEnabled);
- QAction *down = menu->addAction(tr("Step &down"));
- down->setEnabled(se & StepDownEnabled);
- menu->addSeparator();
-
- const QPointer<QAbstractSpinBox> that = this;
- const QPoint pos = (event->reason() == QContextMenuEvent::Mouse)
- ? event->globalPos() : mapToGlobal(QPoint(event->pos().x(), 0)) + QPoint(width() / 2, height() / 2);
- const QAction *action = menu->exec(pos);
- delete static_cast<QMenu *>(menu);
- if (that && action) {
- if (action == up) {
- stepBy(1);
- } else if (action == down) {
- stepBy(-1);
- } else if (action == selAll) {
- selectAll();
- }
- }
- event->accept();
-#endif // QT_NO_CONTEXTMENU
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- d->updateHoverControl(event->pos());
-
- // If we have a timer ID, update the state
- if (d->spinClickTimerId != -1 && d->buttonSymbols != NoButtons) {
- const StepEnabled se = stepEnabled();
- if ((se & StepUpEnabled) && d->hoverControl == QStyle::SC_SpinBoxUp)
- d->updateState(true);
- else if ((se & StepDownEnabled) && d->hoverControl == QStyle::SC_SpinBoxDown)
- d->updateState(false);
- else
- d->reset();
- event->accept();
- }
-}
-
-/*!
- \reimp
-*/
-
-void QAbstractSpinBox::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- if (event->button() != Qt::LeftButton || d->buttonState != None) {
- return;
- }
-
- d->updateHoverControl(event->pos());
- event->accept();
-
- const StepEnabled se = (d->buttonSymbols == NoButtons) ? StepEnabled(StepNone) : stepEnabled();
- if ((se & StepUpEnabled) && d->hoverControl == QStyle::SC_SpinBoxUp) {
- d->updateState(true);
- } else if ((se & StepDownEnabled) && d->hoverControl == QStyle::SC_SpinBoxDown) {
- d->updateState(false);
- } else {
- event->ignore();
- }
-}
-
-/*!
- \reimp
-*/
-void QAbstractSpinBox::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QAbstractSpinBox);
-
- if ((d->buttonState & Mouse) != 0)
- d->reset();
- event->accept();
-}
-
-// --- QAbstractSpinBoxPrivate ---
-
-/*!
- \internal
- Constructs a QAbstractSpinBoxPrivate object
-*/
-
-QAbstractSpinBoxPrivate::QAbstractSpinBoxPrivate()
- : edit(0), type(QVariant::Invalid), spinClickTimerId(-1),
- spinClickTimerInterval(100), spinClickThresholdTimerId(-1), spinClickThresholdTimerInterval(-1),
- effectiveSpinRepeatRate(1), buttonState(None), cachedText(QLatin1String("\x01")),
- cachedState(QValidator::Invalid), pendingEmit(false), readOnly(false), wrapping(false),
- ignoreCursorPositionChanged(false), frame(true), accelerate(false), keyboardTracking(true),
- cleared(false), ignoreUpdateEdit(false), correctionMode(QAbstractSpinBox::CorrectToPreviousValue),
- acceleration(0), hoverControl(QStyle::SC_None), buttonSymbols(QAbstractSpinBox::UpDownArrows), validator(0)
-{
-}
-
-/*
- \internal
- Called when the QAbstractSpinBoxPrivate is destroyed
-*/
-QAbstractSpinBoxPrivate::~QAbstractSpinBoxPrivate()
-{
-}
-
-/*!
- \internal
- Updates the old and new hover control. Does nothing if the hover
- control has not changed.
-*/
-bool QAbstractSpinBoxPrivate::updateHoverControl(const QPoint &pos)
-{
- Q_Q(QAbstractSpinBox);
- QRect lastHoverRect = hoverRect;
- QStyle::SubControl lastHoverControl = hoverControl;
- bool doesHover = q->testAttribute(Qt::WA_Hover);
- if (lastHoverControl != newHoverControl(pos) && doesHover) {
- q->update(lastHoverRect);
- q->update(hoverRect);
- return true;
- }
- return !doesHover;
-}
-
-/*!
- \internal
- Returns the hover control at \a pos.
- This will update the hoverRect and hoverControl.
-*/
-QStyle::SubControl QAbstractSpinBoxPrivate::newHoverControl(const QPoint &pos)
-{
- Q_Q(QAbstractSpinBox);
-
- QStyleOptionSpinBox opt;
- q->initStyleOption(&opt);
- opt.subControls = QStyle::SC_All;
- hoverControl = q->style()->hitTestComplexControl(QStyle::CC_SpinBox, &opt, pos, q);
- hoverRect = q->style()->subControlRect(QStyle::CC_SpinBox, &opt, hoverControl, q);
- return hoverControl;
-}
-
-/*!
- \internal
- Strips any prefix/suffix from \a text.
-*/
-
-QString QAbstractSpinBoxPrivate::stripped(const QString &t, int *pos) const
-{
- QString text = t;
- if (specialValueText.size() == 0 || text != specialValueText) {
- int from = 0;
- int size = text.size();
- bool changed = false;
- if (prefix.size() && text.startsWith(prefix)) {
- from += prefix.size();
- size -= from;
- changed = true;
- }
- if (suffix.size() && text.endsWith(suffix)) {
- size -= suffix.size();
- changed = true;
- }
- if (changed)
- text = text.mid(from, size);
- }
-
- const int s = text.size();
- text = text.trimmed();
- if (pos)
- (*pos) -= (s - text.size());
- return text;
-
-}
-
-void QAbstractSpinBoxPrivate::updateEditFieldGeometry()
-{
- Q_Q(QAbstractSpinBox);
- QStyleOptionSpinBox opt;
- q->initStyleOption(&opt);
- opt.subControls = QStyle::SC_SpinBoxEditField;
- edit->setGeometry(q->style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, q));
-}
-/*!
- \internal
- Returns true if a specialValueText has been set and the current value is minimum.
-*/
-
-bool QAbstractSpinBoxPrivate::specialValue() const
-{
- return (value == minimum && !specialValueText.isEmpty());
-}
-
-/*!
- \internal Virtual function that emits signals when the value
- changes. Reimplemented in the different subclasses.
-*/
-
-void QAbstractSpinBoxPrivate::emitSignals(EmitPolicy, const QVariant &)
-{
-}
-
-/*!
- \internal
-
- Slot connected to the line edit's textChanged(const QString &)
- signal.
-*/
-
-void QAbstractSpinBoxPrivate::_q_editorTextChanged(const QString &t)
-{
- Q_Q(QAbstractSpinBox);
-
- if (keyboardTracking) {
- QString tmp = t;
- int pos = edit->cursorPosition();
- QValidator::State state = q->validate(tmp, pos);
- if (state == QValidator::Acceptable) {
- const QVariant v = valueFromText(tmp);
- setValue(v, EmitIfChanged, tmp != t);
- pendingEmit = false;
- } else {
- pendingEmit = true;
- }
- } else {
- pendingEmit = true;
- }
-}
-
-/*!
- \internal
-
- Virtual slot connected to the line edit's
- cursorPositionChanged(int, int) signal. Will move the cursor to a
- valid position if the new one is invalid. E.g. inside the prefix.
- Reimplemented in Q[Date|Time|DateTime]EditPrivate to account for
- the different sections etc.
-*/
-
-void QAbstractSpinBoxPrivate::_q_editorCursorPositionChanged(int oldpos, int newpos)
-{
- if (!edit->hasSelectedText() && !ignoreCursorPositionChanged && !specialValue()) {
- ignoreCursorPositionChanged = true;
-
- bool allowSelection = true;
- int pos = -1;
- if (newpos < prefix.size() && newpos != 0) {
- if (oldpos == 0) {
- allowSelection = false;
- pos = prefix.size();
- } else {
- pos = oldpos;
- }
- } else if (newpos > edit->text().size() - suffix.size()
- && newpos != edit->text().size()) {
- if (oldpos == edit->text().size()) {
- pos = edit->text().size() - suffix.size();
- allowSelection = false;
- } else {
- pos = edit->text().size();
- }
- }
- if (pos != -1) {
- const int selSize = edit->selectionStart() >= 0 && allowSelection
- ? (edit->selectedText().size()
- * (newpos < pos ? -1 : 1)) - newpos + pos
- : 0;
-
- const bool wasBlocked = edit->blockSignals(true);
- if (selSize != 0) {
- edit->setSelection(pos - selSize, selSize);
- } else {
- edit->setCursorPosition(pos);
- }
- edit->blockSignals(wasBlocked);
- }
- ignoreCursorPositionChanged = false;
- }
-}
-
-/*!
- \internal
-
- Initialises the QAbstractSpinBoxPrivate object.
-*/
-
-void QAbstractSpinBoxPrivate::init()
-{
- Q_Q(QAbstractSpinBox);
-
- q->setLineEdit(new QLineEdit(q));
- edit->setObjectName(QLatin1String("qt_spinbox_lineedit"));
- validator = new QSpinBoxValidator(q, this);
- edit->setValidator(validator);
-
- QStyleOptionSpinBox opt;
- q->initStyleOption(&opt);
- spinClickTimerInterval = q->style()->styleHint(QStyle::SH_SpinBox_ClickAutoRepeatRate, &opt, q);
- spinClickThresholdTimerInterval = q->style()->styleHint(QStyle::SH_SpinBox_ClickAutoRepeatThreshold, &opt, q);
- q->setFocusPolicy(Qt::WheelFocus);
- q->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, QSizePolicy::SpinBox));
- q->setAttribute(Qt::WA_InputMethodEnabled);
-
- q->setAttribute(Qt::WA_MacShowFocusRect);
-}
-
-/*!
- \internal
-
- Resets the state of the spinbox. E.g. the state is set to
- (Keyboard|Up) if Key up is currently pressed.
-*/
-
-void QAbstractSpinBoxPrivate::reset()
-{
- Q_Q(QAbstractSpinBox);
-
- buttonState = None;
- if (q) {
- if (spinClickTimerId != -1)
- q->killTimer(spinClickTimerId);
- if (spinClickThresholdTimerId != -1)
- q->killTimer(spinClickThresholdTimerId);
- spinClickTimerId = spinClickThresholdTimerId = -1;
- acceleration = 0;
- q->update();
- }
-}
-
-/*!
- \internal
-
- Updates the state of the spinbox.
-*/
-
-void QAbstractSpinBoxPrivate::updateState(bool up, bool fromKeyboard /* = false */)
-{
- Q_Q(QAbstractSpinBox);
- if ((up && (buttonState & Up)) || (!up && (buttonState & Down)))
- return;
- reset();
- if (q && (q->stepEnabled() & (up ? QAbstractSpinBox::StepUpEnabled
- : QAbstractSpinBox::StepDownEnabled))) {
- spinClickThresholdTimerId = q->startTimer(spinClickThresholdTimerInterval);
- buttonState = (up ? Up : Down) | (fromKeyboard ? Keyboard : Mouse);
- q->stepBy(up ? 1 : -1);
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(q, 0, QAccessible::ValueChanged);
-#endif
- }
-}
-
-
-/*!
- Initialize \a option with the values from this QSpinBox. This method
- is useful for subclasses when they need a QStyleOptionSpinBox, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QAbstractSpinBox::initStyleOption(QStyleOptionSpinBox *option) const
-{
- if (!option)
- return;
-
- Q_D(const QAbstractSpinBox);
- option->initFrom(this);
- option->activeSubControls = QStyle::SC_None;
- option->buttonSymbols = d->buttonSymbols;
- option->subControls = QStyle::SC_SpinBoxFrame | QStyle::SC_SpinBoxEditField;
- if (d->buttonSymbols != QAbstractSpinBox::NoButtons) {
- option->subControls |= QStyle::SC_SpinBoxUp | QStyle::SC_SpinBoxDown;
- if (d->buttonState & Up) {
- option->activeSubControls = QStyle::SC_SpinBoxUp;
- } else if (d->buttonState & Down) {
- option->activeSubControls = QStyle::SC_SpinBoxDown;
- }
- }
-
- if (d->buttonState) {
- option->state |= QStyle::State_Sunken;
- } else {
- option->activeSubControls = d->hoverControl;
- }
-
- option->stepEnabled = style()->styleHint(QStyle::SH_SpinControls_DisableOnBounds)
- ? stepEnabled()
- : (QAbstractSpinBox::StepDownEnabled|QAbstractSpinBox::StepUpEnabled);
-
- option->frame = d->frame;
-}
-
-/*!
- \internal
-
- Bounds \a val to be within minimum and maximum. Also tries to be
- clever about setting it at min and max depending on what it was
- and what direction it was changed etc.
-*/
-
-QVariant QAbstractSpinBoxPrivate::bound(const QVariant &val, const QVariant &old, int steps) const
-{
- QVariant v = val;
- if (!wrapping || steps == 0 || old.isNull()) {
- if (variantCompare(v, minimum) < 0) {
- v = wrapping ? maximum : minimum;
- }
- if (variantCompare(v, maximum) > 0) {
- v = wrapping ? minimum : maximum;
- }
- } else {
- const bool wasMin = old == minimum;
- const bool wasMax = old == maximum;
- const int oldcmp = variantCompare(v, old);
- const int maxcmp = variantCompare(v, maximum);
- const int mincmp = variantCompare(v, minimum);
- const bool wrapped = (oldcmp > 0 && steps < 0) || (oldcmp < 0 && steps > 0);
- if (maxcmp > 0) {
- v = ((wasMax && !wrapped && steps > 0) || (steps < 0 && !wasMin && wrapped))
- ? minimum : maximum;
- } else if (wrapped && (maxcmp > 0 || mincmp < 0)) {
- v = ((wasMax && steps > 0) || (!wasMin && steps < 0)) ? minimum : maximum;
- } else if (mincmp < 0) {
- v = (!wasMax && !wasMin ? minimum : maximum);
- }
- }
-
- return v;
-}
-
-/*!
- \internal
-
- Sets the value of the spin box to \a val. Depending on the value
- of \a ep it will also emit signals.
-*/
-
-void QAbstractSpinBoxPrivate::setValue(const QVariant &val, EmitPolicy ep,
- bool doUpdate)
-{
- Q_Q(QAbstractSpinBox);
- const QVariant old = value;
- value = bound(val);
- pendingEmit = false;
- cleared = false;
- if (doUpdate) {
- updateEdit();
- }
- q->update();
-
- if (ep == AlwaysEmit || (ep == EmitIfChanged && old != value)) {
- emitSignals(ep, old);
- }
-}
-
-/*!
- \internal
-
- Updates the line edit to reflect the current value of the spin box.
-*/
-
-void QAbstractSpinBoxPrivate::updateEdit()
-{
- Q_Q(QAbstractSpinBox);
- if (type == QVariant::Invalid)
- return;
- const QString newText = specialValue() ? specialValueText : prefix + textFromValue(value) + suffix;
- if (newText == edit->displayText() || cleared)
- return;
-
- const bool empty = edit->text().isEmpty();
- int cursor = edit->cursorPosition();
- int selsize = edit->selectedText().size();
- const bool sb = edit->blockSignals(true);
- edit->setText(newText);
-
- if (!specialValue()) {
- cursor = qBound(prefix.size(), cursor, edit->displayText().size() - suffix.size());
-
- if (selsize > 0) {
- edit->setSelection(cursor, selsize);
- } else {
- edit->setCursorPosition(empty ? prefix.size() : cursor);
- }
- }
- edit->blockSignals(sb);
- q->update();
-}
-
-/*!
- \internal
-
- Convenience function to set min/max values.
-*/
-
-void QAbstractSpinBoxPrivate::setRange(const QVariant &min, const QVariant &max)
-{
- Q_Q(QAbstractSpinBox);
-
- clearCache();
- minimum = min;
- maximum = (variantCompare(min, max) < 0 ? max : min);
- cachedSizeHint = QSize(); // minimumSizeHint doesn't care about min/max
-
- reset();
- if (!(bound(value) == value)) {
- setValue(bound(value), EmitIfChanged);
- } else if (value == minimum && !specialValueText.isEmpty()) {
- updateEdit();
- }
-
- q->updateGeometry();
-}
-
-/*!
- \internal
-
- Convenience function to get a variant of the right type.
-*/
-
-QVariant QAbstractSpinBoxPrivate::getZeroVariant() const
-{
- QVariant ret;
- switch (type) {
- case QVariant::Int: ret = QVariant((int)0); break;
- case QVariant::Double: ret = QVariant((double)0.0); break;
- default: break;
- }
- return ret;
-}
-
-/*!
- \internal
-
- Virtual method called that calls the public textFromValue()
- functions in the subclasses. Needed to change signature from
- QVariant to int/double/QDateTime etc. Used when needing to display
- a value textually.
-
- This method is reimeplemented in the various subclasses.
-*/
-
-QString QAbstractSpinBoxPrivate::textFromValue(const QVariant &) const
-{
- return QString();
-}
-
-/*!
- \internal
-
- Virtual method called that calls the public valueFromText()
- functions in the subclasses. Needed to change signature from
- QVariant to int/double/QDateTime etc. Used when needing to
- interpret a string as another type.
-
- This method is reimeplemented in the various subclasses.
-*/
-
-QVariant QAbstractSpinBoxPrivate::valueFromText(const QString &) const
-{
- return QVariant();
-}
-/*!
- \internal
-
- Interprets text and emits signals. Called when the spinbox needs
- to interpret the text on the lineedit.
-*/
-
-void QAbstractSpinBoxPrivate::interpret(EmitPolicy ep)
-{
- Q_Q(QAbstractSpinBox);
- if (type == QVariant::Invalid || cleared)
- return;
-
- QVariant v = getZeroVariant();
- bool doInterpret = true;
- QString tmp = edit->displayText();
- int pos = edit->cursorPosition();
- const int oldpos = pos;
-
- if (q->validate(tmp, pos) != QValidator::Acceptable) {
- const QString copy = tmp;
- q->fixup(tmp);
- QASBDEBUG() << "QAbstractSpinBoxPrivate::interpret() text '"
- << edit->displayText()
- << "' >> '" << copy << '\''
- << "' >> '" << tmp << '\'';
-
- doInterpret = tmp != copy && (q->validate(tmp, pos) == QValidator::Acceptable);
- if (!doInterpret) {
- v = (correctionMode == QAbstractSpinBox::CorrectToNearestValue
- ? variantBound(minimum, v, maximum) : value);
- }
- }
- if (doInterpret) {
- v = valueFromText(tmp);
- }
- clearCache();
- setValue(v, ep, true);
- if (oldpos != pos)
- edit->setCursorPosition(pos);
-}
-
-void QAbstractSpinBoxPrivate::clearCache() const
-{
- cachedText.clear();
- cachedValue.clear();
- cachedState = QValidator::Acceptable;
-}
-
-
-// --- QSpinBoxValidator ---
-
-/*!
- \internal
- Constructs a QSpinBoxValidator object
-*/
-
-QSpinBoxValidator::QSpinBoxValidator(QAbstractSpinBox *qp, QAbstractSpinBoxPrivate *dp)
- : QValidator(qp), qptr(qp), dptr(dp)
-{
- setObjectName(QLatin1String("qt_spinboxvalidator"));
-}
-
-/*!
- \internal
-
- Checks for specialValueText, prefix, suffix and calls
- the virtual QAbstractSpinBox::validate function.
-*/
-
-QValidator::State QSpinBoxValidator::validate(QString &input, int &pos) const
-{
- if (dptr->specialValueText.size() > 0 && input == dptr->specialValueText)
- return QValidator::Acceptable;
-
- if (!dptr->prefix.isEmpty() && !input.startsWith(dptr->prefix)) {
- input.prepend(dptr->prefix);
- pos += dptr->prefix.length();
- }
-
- if (!dptr->suffix.isEmpty() && !input.endsWith(dptr->suffix))
- input.append(dptr->suffix);
-
- return qptr->validate(input, pos);
-}
-/*!
- \internal
- Calls the virtual QAbstractSpinBox::fixup function.
-*/
-
-void QSpinBoxValidator::fixup(QString &input) const
-{
- qptr->fixup(input);
-}
-
-// --- global ---
-
-/*!
- \internal
- Adds two variants together and returns the result.
-*/
-
-QVariant operator+(const QVariant &arg1, const QVariant &arg2)
-{
- QVariant ret;
- if (arg1.type() != arg2.type())
- qWarning("QAbstractSpinBox: Internal error: Different types (%s vs %s) (%s:%d)",
- arg1.typeName(), arg2.typeName(), __FILE__, __LINE__);
- switch (arg1.type()) {
- case QVariant::Int: ret = QVariant(arg1.toInt() + arg2.toInt()); break;
- case QVariant::Double: ret = QVariant(arg1.toDouble() + arg2.toDouble()); break;
- case QVariant::DateTime: {
- QDateTime a2 = arg2.toDateTime();
- QDateTime a1 = arg1.toDateTime().addDays(QDATETIMEEDIT_DATETIME_MIN.daysTo(a2));
- a1.setTime(a1.time().addMSecs(QTime().msecsTo(a2.time())));
- ret = QVariant(a1);
- }
- default: break;
- }
- return ret;
-}
-
-
-/*!
- \internal
- Subtracts two variants and returns the result.
-*/
-
-QVariant operator-(const QVariant &arg1, const QVariant &arg2)
-{
- QVariant ret;
- if (arg1.type() != arg2.type())
- qWarning("QAbstractSpinBox: Internal error: Different types (%s vs %s) (%s:%d)",
- arg1.typeName(), arg2.typeName(), __FILE__, __LINE__);
- switch (arg1.type()) {
- case QVariant::Int: ret = QVariant(arg1.toInt() - arg2.toInt()); break;
- case QVariant::Double: ret = QVariant(arg1.toDouble() - arg2.toDouble()); break;
- case QVariant::DateTime: {
- QDateTime a1 = arg1.toDateTime();
- QDateTime a2 = arg2.toDateTime();
- int days = a2.daysTo(a1);
- int secs = a2.secsTo(a1);
- int msecs = qMax(0, a1.time().msec() - a2.time().msec());
- if (days < 0 || secs < 0 || msecs < 0) {
- ret = arg1;
- } else {
- QDateTime dt = a2.addDays(days).addSecs(secs);
- if (msecs > 0)
- dt.setTime(dt.time().addMSecs(msecs));
- ret = QVariant(dt);
- }
- }
- default: break;
- }
- return ret;
-}
-
-/*!
- \internal
- Multiplies \a arg1 by \a multiplier and returns the result.
-*/
-
-QVariant operator*(const QVariant &arg1, double multiplier)
-{
- QVariant ret;
-
- switch (arg1.type()) {
- case QVariant::Int: ret = QVariant((int)(arg1.toInt() * multiplier)); break;
- case QVariant::Double: ret = QVariant(arg1.toDouble() * multiplier); break;
- case QVariant::DateTime: {
- double days = QDATETIMEEDIT_DATE_MIN.daysTo(arg1.toDateTime().date()) * multiplier;
- int daysInt = (int)days;
- days -= daysInt;
- long msecs = (long)((QDATETIMEEDIT_TIME_MIN.msecsTo(arg1.toDateTime().time()) * multiplier)
- + (days * (24 * 3600 * 1000)));
- ret = QDateTime(QDate().addDays(int(days)), QTime().addMSecs(msecs));
- break;
- }
- default: ret = arg1; break;
- }
-
- return ret;
-}
-
-
-
-double operator/(const QVariant &arg1, const QVariant &arg2)
-{
- double a1 = 0;
- double a2 = 0;
-
- switch (arg1.type()) {
- case QVariant::Int:
- a1 = (double)arg1.toInt();
- a2 = (double)arg2.toInt();
- break;
- case QVariant::Double:
- a1 = arg1.toDouble();
- a2 = arg2.toDouble();
- break;
- case QVariant::DateTime:
- a1 = QDATETIMEEDIT_DATE_MIN.daysTo(arg1.toDate());
- a2 = QDATETIMEEDIT_DATE_MIN.daysTo(arg2.toDate());
- a1 += (double)QDATETIMEEDIT_TIME_MIN.msecsTo(arg1.toDateTime().time()) / (long)(3600 * 24 * 1000);
- a2 += (double)QDATETIMEEDIT_TIME_MIN.msecsTo(arg2.toDateTime().time()) / (long)(3600 * 24 * 1000);
- default: break;
- }
-
- return (a1 != 0 && a2 != 0) ? (a1 / a2) : 0.0;
-}
-
-int QAbstractSpinBoxPrivate::variantCompare(const QVariant &arg1, const QVariant &arg2)
-{
- switch (arg2.type()) {
- case QVariant::Date:
- Q_ASSERT_X(arg1.type() == QVariant::Date, "QAbstractSpinBoxPrivate::variantCompare",
- qPrintable(QString::fromAscii("Internal error 1 (%1)").
- arg(QString::fromAscii(arg1.typeName()))));
- if (arg1.toDate() == arg2.toDate()) {
- return 0;
- } else if (arg1.toDate() < arg2.toDate()) {
- return -1;
- } else {
- return 1;
- }
- case QVariant::Time:
- Q_ASSERT_X(arg1.type() == QVariant::Time, "QAbstractSpinBoxPrivate::variantCompare",
- qPrintable(QString::fromAscii("Internal error 2 (%1)").
- arg(QString::fromAscii(arg1.typeName()))));
- if (arg1.toTime() == arg2.toTime()) {
- return 0;
- } else if (arg1.toTime() < arg2.toTime()) {
- return -1;
- } else {
- return 1;
- }
-
-
- case QVariant::DateTime:
- if (arg1.toDateTime() == arg2.toDateTime()) {
- return 0;
- } else if (arg1.toDateTime() < arg2.toDateTime()) {
- return -1;
- } else {
- return 1;
- }
- case QVariant::Int:
- if (arg1.toInt() == arg2.toInt()) {
- return 0;
- } else if (arg1.toInt() < arg2.toInt()) {
- return -1;
- } else {
- return 1;
- }
- case QVariant::Double:
- if (arg1.toDouble() == arg2.toDouble()) {
- return 0;
- } else if (arg1.toDouble() < arg2.toDouble()) {
- return -1;
- } else {
- return 1;
- }
- case QVariant::Invalid:
- if (arg2.type() == QVariant::Invalid)
- return 0;
- default:
- Q_ASSERT_X(0, "QAbstractSpinBoxPrivate::variantCompare",
- qPrintable(QString::fromAscii("Internal error 3 (%1 %2)").
- arg(QString::fromAscii(arg1.typeName())).
- arg(QString::fromAscii(arg2.typeName()))));
- }
- return -2;
-}
-
-QVariant QAbstractSpinBoxPrivate::variantBound(const QVariant &min,
- const QVariant &value,
- const QVariant &max)
-{
- Q_ASSERT(variantCompare(min, max) <= 0);
- if (variantCompare(min, value) < 0) {
- const int compMax = variantCompare(value, max);
- return (compMax < 0 ? value : max);
- } else {
- return min;
- }
-}
-
-
-QT_END_NAMESPACE
-
-#include "moc_qabstractspinbox.cpp"
-
-#endif // QT_NO_SPINBOX
diff --git a/src/gui/widgets/qabstractspinbox.h b/src/gui/widgets/qabstractspinbox.h
deleted file mode 100644
index bb1307cca5..0000000000
--- a/src/gui/widgets/qabstractspinbox.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTSPINBOX_H
-#define QABSTRACTSPINBOX_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qvalidator.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SPINBOX
-
-class QLineEdit;
-
-class QAbstractSpinBoxPrivate;
-class QStyleOptionSpinBox;
-
-class Q_GUI_EXPORT QAbstractSpinBox : public QWidget
-{
- Q_OBJECT
-
- Q_ENUMS(ButtonSymbols)
- Q_ENUMS(CorrectionMode)
- Q_PROPERTY(bool wrapping READ wrapping WRITE setWrapping)
- Q_PROPERTY(bool frame READ hasFrame WRITE setFrame)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(ButtonSymbols buttonSymbols READ buttonSymbols WRITE setButtonSymbols)
- Q_PROPERTY(QString specialValueText READ specialValueText WRITE setSpecialValueText)
- Q_PROPERTY(QString text READ text)
- Q_PROPERTY(bool accelerated READ isAccelerated WRITE setAccelerated)
- Q_PROPERTY(CorrectionMode correctionMode READ correctionMode WRITE setCorrectionMode)
- Q_PROPERTY(bool acceptableInput READ hasAcceptableInput)
- Q_PROPERTY(bool keyboardTracking READ keyboardTracking WRITE setKeyboardTracking)
-public:
- explicit QAbstractSpinBox(QWidget *parent = 0);
- ~QAbstractSpinBox();
-
- enum StepEnabledFlag { StepNone = 0x00, StepUpEnabled = 0x01,
- StepDownEnabled = 0x02 };
- Q_DECLARE_FLAGS(StepEnabled, StepEnabledFlag)
-
- enum ButtonSymbols { UpDownArrows, PlusMinus, NoButtons };
-
- ButtonSymbols buttonSymbols() const;
- void setButtonSymbols(ButtonSymbols bs);
-
- enum CorrectionMode { CorrectToPreviousValue, CorrectToNearestValue };
-
- void setCorrectionMode(CorrectionMode cm);
- CorrectionMode correctionMode() const;
-
- bool hasAcceptableInput() const;
- QString text() const;
-
- QString specialValueText() const;
- void setSpecialValueText(const QString &txt);
-
- bool wrapping() const;
- void setWrapping(bool w);
-
- void setReadOnly(bool r);
- bool isReadOnly() const;
-
- void setKeyboardTracking(bool kt);
- bool keyboardTracking() const;
-
- void setAlignment(Qt::Alignment flag);
- Qt::Alignment alignment() const;
-
- void setFrame(bool);
- bool hasFrame() const;
-
- void setAccelerated(bool on);
- bool isAccelerated() const;
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
- void interpretText();
- bool event(QEvent *event);
-
- QVariant inputMethodQuery(Qt::InputMethodQuery) const;
-
- virtual QValidator::State validate(QString &input, int &pos) const;
- virtual void fixup(QString &input) const;
-
- virtual void stepBy(int steps);
-public Q_SLOTS:
- void stepUp();
- void stepDown();
- void selectAll();
- virtual void clear();
-protected:
- void resizeEvent(QResizeEvent *event);
- void keyPressEvent(QKeyEvent *event);
- void keyReleaseEvent(QKeyEvent *event);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *event);
-#endif
- void focusInEvent(QFocusEvent *event);
- void focusOutEvent(QFocusEvent *event);
- void contextMenuEvent(QContextMenuEvent *event);
- void changeEvent(QEvent *event);
- void closeEvent(QCloseEvent *event);
- void hideEvent(QHideEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void timerEvent(QTimerEvent *event);
- void paintEvent(QPaintEvent *event);
- void showEvent(QShowEvent *event);
- void initStyleOption(QStyleOptionSpinBox *option) const;
-
- QLineEdit *lineEdit() const;
- void setLineEdit(QLineEdit *edit);
-
- virtual StepEnabled stepEnabled() const;
-Q_SIGNALS:
- void editingFinished();
-protected:
- QAbstractSpinBox(QAbstractSpinBoxPrivate &dd, QWidget *parent = 0);
-
-private:
- Q_PRIVATE_SLOT(d_func(), void _q_editorTextChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_editorCursorPositionChanged(int, int))
-
- Q_DECLARE_PRIVATE(QAbstractSpinBox)
- Q_DISABLE_COPY(QAbstractSpinBox)
-};
-Q_DECLARE_OPERATORS_FOR_FLAGS(QAbstractSpinBox::StepEnabled)
-
-#endif // QT_NO_SPINBOX
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QABSTRACTSPINBOX_H
diff --git a/src/gui/widgets/qabstractspinbox_p.h b/src/gui/widgets/qabstractspinbox_p.h
deleted file mode 100644
index 38270c4e95..0000000000
--- a/src/gui/widgets/qabstractspinbox_p.h
+++ /dev/null
@@ -1,170 +0,0 @@
-/****************************************************************************
-**
-** 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 QABSTRACTSPINBOX_P_H
-#define QABSTRACTSPINBOX_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qabstractspinbox.h"
-
-#ifndef QT_NO_SPINBOX
-
-#include "QtGui/qlineedit.h"
-#include "QtGui/qstyleoption.h"
-#include "QtGui/qvalidator.h"
-#include "QtCore/qdatetime.h"
-#include "QtCore/qvariant.h"
-#include "private/qwidget_p.h"
-#include "private/qdatetime_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QVariant operator+(const QVariant &arg1, const QVariant &arg2);
-QVariant operator-(const QVariant &arg1, const QVariant &arg2);
-QVariant operator*(const QVariant &arg1, double multiplier);
-double operator/(const QVariant &arg1, const QVariant &arg2);
-
-enum EmitPolicy {
- EmitIfChanged,
- AlwaysEmit,
- NeverEmit
-};
-
-enum Button {
- None = 0x000,
- Keyboard = 0x001,
- Mouse = 0x002,
- Wheel = 0x004,
- ButtonMask = 0x008,
- Up = 0x010,
- Down = 0x020,
- DirectionMask = 0x040
-};
-class QSpinBoxValidator;
-class QAbstractSpinBoxPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QAbstractSpinBox)
-public:
- QAbstractSpinBoxPrivate();
- ~QAbstractSpinBoxPrivate();
-
- void init();
- void reset();
- void updateState(bool up, bool fromKeyboard = false);
- QString stripped(const QString &text, int *pos = 0) const;
- bool specialValue() const;
- virtual QVariant getZeroVariant() const;
- virtual void setRange(const QVariant &min, const QVariant &max);
- void setValue(const QVariant &val, EmitPolicy ep, bool updateEdit = true);
- virtual QVariant bound(const QVariant &val, const QVariant &old = QVariant(), int steps = 0) const;
- virtual void updateEdit();
-
- virtual void emitSignals(EmitPolicy ep, const QVariant &old);
- virtual void interpret(EmitPolicy ep);
- virtual QString textFromValue(const QVariant &n) const;
- virtual QVariant valueFromText(const QString &input) const;
-
- void _q_editorTextChanged(const QString &);
- virtual void _q_editorCursorPositionChanged(int oldpos, int newpos);
-
- virtual QStyle::SubControl newHoverControl(const QPoint &pos);
- bool updateHoverControl(const QPoint &pos);
-
- virtual void clearCache() const;
- virtual void updateEditFieldGeometry();
-
- static int variantCompare(const QVariant &arg1, const QVariant &arg2);
- static QVariant variantBound(const QVariant &min, const QVariant &value, const QVariant &max);
-
- QLineEdit *edit;
- QString prefix, suffix, specialValueText;
- QVariant value, minimum, maximum, singleStep;
- QVariant::Type type;
- int spinClickTimerId, spinClickTimerInterval, spinClickThresholdTimerId, spinClickThresholdTimerInterval;
- int effectiveSpinRepeatRate;
- uint buttonState;
- mutable QString cachedText;
- mutable QVariant cachedValue;
- mutable QValidator::State cachedState;
- mutable QSize cachedSizeHint, cachedMinimumSizeHint;
- uint pendingEmit : 1;
- uint readOnly : 1;
- uint wrapping : 1;
- uint ignoreCursorPositionChanged : 1;
- uint frame : 1;
- uint accelerate : 1;
- uint keyboardTracking : 1;
- uint cleared : 1;
- uint ignoreUpdateEdit : 1;
- QAbstractSpinBox::CorrectionMode correctionMode;
- int acceleration;
- QStyle::SubControl hoverControl;
- QRect hoverRect;
- QAbstractSpinBox::ButtonSymbols buttonSymbols;
- QSpinBoxValidator *validator;
-};
-
-class QSpinBoxValidator : public QValidator
-{
-public:
- QSpinBoxValidator(QAbstractSpinBox *qptr, QAbstractSpinBoxPrivate *dptr);
- QValidator::State validate(QString &input, int &) const;
- void fixup(QString &) const;
-private:
- QAbstractSpinBox *qptr;
- QAbstractSpinBoxPrivate *dptr;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SPINBOX
-
-#endif // QABSTRACTSPINBOX_P_H
diff --git a/src/gui/widgets/qbuttongroup.cpp b/src/gui/widgets/qbuttongroup.cpp
deleted file mode 100644
index c4a37153a6..0000000000
--- a/src/gui/widgets/qbuttongroup.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-
-
-/*!
- \class QButtonGroup
- \brief The QButtonGroup class provides a container to organize groups of
- button widgets.
-
- \ingroup organizers
- \ingroup geomanagement
-
- QButtonGroup provides an abstract container into which button widgets can
- be placed. It does not provide a visual representation of this container
- (see QGroupBox for a container widget), but instead manages the states of
- each of the buttons in the group.
-
- An \l {QButtonGroup::exclusive} {exclusive} button group switches
- off all checkable (toggle) buttons except the one that was
- clicked. By default, a button group is exclusive. The buttons in a
- button group are usually checkable QPushButton's, \l{QCheckBox}es
- (normally for non-exclusive button groups), or \l{QRadioButton}s.
- If you create an exclusive button group, you should ensure that
- one of the buttons in the group is initially checked; otherwise,
- the group will initially be in a state where no buttons are
- checked.
-
- A button is added to the group with addButton(). It can be removed
- from the group with removeButton(). If the group is exclusive, the
- currently checked button is available as checkedButton(). If a
- button is clicked the buttonClicked() signal is emitted. For a
- checkable button in an exclusive group this means that the button
- was checked. The list of buttons in the group is returned by
- buttons().
-
- In addition, QButtonGroup can map between integers and buttons.
- You can assign an integer id to a button with setId(), and
- retrieve it with id(). The id of the currently checked button is
- available with checkedId(), and there is an overloaded signal
- buttonClicked() which emits the id of the button. The id \c {-1}
- is reserved by QButtonGroup to mean "no such button". The purpose
- of the mapping mechanism is to simplify the representation of enum
- values in a user interface.
-
- \sa QGroupBox QPushButton, QCheckBox, QRadioButton
-*/
-
-/*!
- \fn QButtonGroup::QButtonGroup(QObject *parent)
-
- Constructs a new, empty button group with the given \a parent.
-
- \sa addButton() setExclusive()
-*/
-
-/*!
- \fn QButtonGroup::~QButtonGroup()
-
- Destroys the button group.
-*/
-
-/*!
- \property QButtonGroup::exclusive
- \brief whether the button group is exclusive
-
- If this property is true then only one button in the group can be checked
- at any given time. The user can click on any button to check it, and that
- button will replace the existing one as the checked button in the group.
-
- In an exclusive group, the user cannot uncheck the currently checked button
- by clicking on it; instead, another button in the group must be clicked
- to set the new checked button for that group.
-
- By default, this property is true.
-*/
-
-/*!
- \fn void QButtonGroup::buttonClicked(QAbstractButton *button)
-
- This signal is emitted when the given \a button is clicked. A
- button is clicked when it is first pressed and then released, when
- its shortcut key is typed, or programmatically when
- QAbstractButton::click() or QAbstractButton::animateClick() is
- called.
-
-
- \sa checkedButton(), QAbstractButton::clicked()
-*/
-
-/*!
- \fn void QButtonGroup::buttonClicked(int id)
-
- This signal is emitted when a button with the given \a id is
- clicked.
-
- \sa checkedButton(), QAbstractButton::clicked()
-*/
-
-/*!
- \fn void QButtonGroup::buttonPressed(QAbstractButton *button)
- \since 4.2
-
- This signal is emitted when the given \a button is pressed down.
-
- \sa QAbstractButton::pressed()
-*/
-
-/*!
- \fn void QButtonGroup::buttonPressed(int id)
- \since 4.2
-
- This signal is emitted when a button with the given \a id is
- pressed down.
-
- \sa QAbstractButton::pressed()
-*/
-
-/*!
- \fn void QButtonGroup::buttonReleased(QAbstractButton *button)
- \since 4.2
-
- This signal is emitted when the given \a button is released.
-
- \sa QAbstractButton::released()
-*/
-
-/*!
- \fn void QButtonGroup::buttonReleased(int id)
- \since 4.2
-
- This signal is emitted when a button with the given \a id is
- released.
-
- \sa QAbstractButton::released()
-*/
-
-/*!
- \fn void QButtonGroup::addButton(QAbstractButton *button);
-
- Adds the given \a button to the end of the group's internal list
- of buttons. An id will be assigned to the button by this
- QButtonGroup. Automatically assigned ids are guaranteed to be
- negative, starting with -2. If you are also assigning your own
- ids, use positive values to avoid conflicts.
-
- \sa removeButton() buttons()
-*/
-
-/*!
- \fn void QButtonGroup::addButton(QAbstractButton *button, int id);
-
- Adds the given \a button to the button group, with the given \a
- id. It is recommended to assign only positive ids.
-
- \sa removeButton() buttons()
-*/
-
-/*!
- \fn void QButtonGroup::removeButton(QAbstractButton *button);
-
- Removes the given \a button from the button group.
-
- \sa addButton() buttons()
-*/
-
-/*!
- \fn QList<QAbstractButton*> QButtonGroup::buttons() const
-
- Returns the list of this groups's buttons. This may be empty.
-
- \sa addButton(), removeButton()
-*/
-
-/*!
- \fn QAbstractButton *QButtonGroup::checkedButton() const;
-
- Returns the button group's checked button, or 0 if no buttons are
- checked.
-
- \sa buttonClicked()
-*/
-
-/*!
- \fn QAbstractButton *QButtonGroup::button(int id) const;
- \since 4.1
-
- Returns the button with the specified \a id, or 0 if no such button
- exists.
-*/
-
-/*!
- \fn void QButtonGroup::setId(QAbstractButton *button, int id)
- \since 4.1
-
- Sets the \a id for the specified \a button. Note that \a id can
- not be -1.
-
- \sa id()
-*/
-
-/*!
- \fn int QButtonGroup::id(QAbstractButton *button) const;
- \since 4.1
-
- Returns the id for the specified \a button, or -1 if no such button
- exists.
-
-
- \sa setId()
-*/
-
-/*!
- \fn int QButtonGroup::checkedId() const;
- \since 4.1
-
- Returns the id of the checkedButton(), or -1 if no button is checked.
-
- \sa setId()
-*/
-
-
-/*! \fn void QButtonGroup::insert(QAbstractButton *b)
-
- Use addButton() instead.
-*/
-
-/*! \fn void QButtonGroup::remove(QAbstractButton *b)
-
- Use removeButton() instead.
-*/
diff --git a/src/gui/widgets/qbuttongroup.h b/src/gui/widgets/qbuttongroup.h
deleted file mode 100644
index 5c5522f229..0000000000
--- a/src/gui/widgets/qbuttongroup.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** 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 QBUTTONGROUP_H
-#define QBUTTONGROUP_H
-
-#include <QtCore/qobject.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_BUTTONGROUP
-
-class QAbstractButton;
-class QAbstractButtonPrivate;
-class QButtonGroupPrivate;
-
-class Q_GUI_EXPORT QButtonGroup : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(bool exclusive READ exclusive WRITE setExclusive)
-public:
- explicit QButtonGroup(QObject *parent = 0);
- ~QButtonGroup();
-
- void setExclusive(bool);
- bool exclusive() const;
-
- void addButton(QAbstractButton *);
- void addButton(QAbstractButton *, int id);
- void removeButton(QAbstractButton *);
-
- QList<QAbstractButton*> buttons() const;
-
- QAbstractButton * checkedButton() const;
- // no setter on purpose!
-
- QAbstractButton *button(int id) const;
- void setId(QAbstractButton *button, int id);
- int id(QAbstractButton *button) const;
- int checkedId() const;
-
-Q_SIGNALS:
- void buttonClicked(QAbstractButton *);
- void buttonClicked(int);
- void buttonPressed(QAbstractButton *);
- void buttonPressed(int);
- void buttonReleased(QAbstractButton *);
- void buttonReleased(int);
-
-#ifdef QT3_SUPPORT
-public:
- inline QT3_SUPPORT void insert(QAbstractButton *b) { addButton(b); }
- inline QT3_SUPPORT void remove(QAbstractButton *b) { removeButton(b); }
-#endif
-
-private:
- Q_DISABLE_COPY(QButtonGroup)
- Q_DECLARE_PRIVATE(QButtonGroup)
- friend class QAbstractButton;
- friend class QAbstractButtonPrivate;
-};
-
-#endif // QT_NO_BUTTONGROUP
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QBUTTONGROUP_H
diff --git a/src/gui/widgets/qcalendartextnavigator_p.h b/src/gui/widgets/qcalendartextnavigator_p.h
deleted file mode 100644
index 0aaad4689f..0000000000
--- a/src/gui/widgets/qcalendartextnavigator_p.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** 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 QCALENDARTEXTNAVIGATOR_P_H
-#define QCALENDARTEXTNAVIGATOR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtCore/qobject.h>
-#include <QtCore/qdatetime.h>
-#include <QtCore/qbasictimer.h>
-
-#ifndef QT_NO_CALENDARWIDGET
-
-QT_BEGIN_NAMESPACE
-
-class QLabel;
-class QCalendarDateValidator;
-class QFrame;
-
-class QCalendarTextNavigator: public QObject
-{
- Q_OBJECT
-public:
- QCalendarTextNavigator(QObject *parent = 0)
- : QObject(parent), m_dateText(0), m_dateFrame(0), m_dateValidator(0), m_widget(0), m_editDelay(1500), m_date(QDate::currentDate()) { }
-
- QWidget *widget() const;
- void setWidget(QWidget *widget);
-
- int dateEditAcceptDelay() const;
- void setDateEditAcceptDelay(int delay);
-
- QDate date() const;
- void setDate(const QDate &date);
-
- bool eventFilter(QObject *o, QEvent *e);
- void timerEvent(QTimerEvent *e);
-
-signals:
- void dateChanged(const QDate &date);
- void editingFinished();
-
-private:
- void applyDate();
- void updateDateLabel();
- void createDateLabel();
- void removeDateLabel();
-
- QLabel *m_dateText;
- QFrame *m_dateFrame;
- QBasicTimer m_acceptTimer;
- QCalendarDateValidator *m_dateValidator;
- QWidget *m_widget;
- int m_editDelay;
-
- QDate m_date;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_CALENDARWIDGET
-
-#endif
-
diff --git a/src/gui/widgets/qcalendarwidget.cpp b/src/gui/widgets/qcalendarwidget.cpp
deleted file mode 100644
index d6a6f14e3f..0000000000
--- a/src/gui/widgets/qcalendarwidget.cpp
+++ /dev/null
@@ -1,3104 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcalendarwidget.h"
-
-#ifndef QT_NO_CALENDARWIDGET
-
-#include <qabstractitemmodel.h>
-#include <qitemdelegate.h>
-#include <qdatetime.h>
-#include <qtableview.h>
-#include <qlayout.h>
-#include <qevent.h>
-#include <qtextformat.h>
-#include <qheaderview.h>
-#include <private/qwidget_p.h>
-#include <qpushbutton.h>
-#include <qtoolbutton.h>
-#include <qlabel.h>
-#include <qspinbox.h>
-#include <qmenu.h>
-#include <qapplication.h>
-#include <qbasictimer.h>
-#include <qstylepainter.h>
-#include <private/qcalendartextnavigator_p.h>
-
-QT_BEGIN_NAMESPACE
-
-enum {
- RowCount = 6,
- ColumnCount = 7,
- HeaderColumn = 0,
- HeaderRow = 0,
- MinimumDayOffset = 1
-};
-
-class QCalendarDateSectionValidator
-{
-public:
-
- enum Section {
- NextSection,
- ThisSection,
- PrevSection
- };
-
- QCalendarDateSectionValidator() {}
- virtual ~QCalendarDateSectionValidator() {}
- virtual Section handleKey(int key) = 0;
- virtual QDate applyToDate(const QDate &date) const = 0;
- virtual void setDate(const QDate &date) = 0;
- virtual QString text() const = 0;
- virtual QString text(const QDate &date, int repeat) const = 0;
-
- QLocale m_locale;
-
-protected:
- QString highlightString(const QString &str, int pos) const;
-private:
-};
-
-QString QCalendarDateSectionValidator::highlightString(const QString &str, int pos) const
-{
- if (pos == 0)
- return QLatin1String("<b>") + str + QLatin1String("</b>");
- int startPos = str.length() - pos;
- return str.mid(0, startPos) + QLatin1String("<b>") + str.mid(startPos, pos) + QLatin1String("</b>");
-
-}
-
-class QCalendarDayValidator : public QCalendarDateSectionValidator
-{
-
-public:
- QCalendarDayValidator();
- virtual Section handleKey(int key);
- virtual QDate applyToDate(const QDate &date) const;
- virtual void setDate(const QDate &date);
- virtual QString text() const;
- virtual QString text(const QDate &date, int repeat) const;
-private:
- int m_pos;
- int m_day;
- int m_oldDay;
-};
-
-QCalendarDayValidator::QCalendarDayValidator()
- : QCalendarDateSectionValidator(), m_pos(0), m_day(1), m_oldDay(1)
-{
-}
-
-QCalendarDateSectionValidator::Section QCalendarDayValidator::handleKey(int key)
-{
- if (key == Qt::Key_Right || key == Qt::Key_Left) {
- m_pos = 0;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Up) {
- m_pos = 0;
- ++m_day;
- if (m_day > 31)
- m_day = 1;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Down) {
- m_pos = 0;
- --m_day;
- if (m_day < 1)
- m_day = 31;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Back || key == Qt::Key_Backspace) {
- --m_pos;
- if (m_pos < 0)
- m_pos = 1;
-
- if (m_pos == 0)
- m_day = m_oldDay;
- else
- m_day = m_day / 10;
- //m_day = m_oldDay / 10 * 10 + m_day / 10;
-
- if (m_pos == 0)
- return QCalendarDateSectionValidator::PrevSection;
- return QCalendarDateSectionValidator::ThisSection;
- }
- if (key < Qt::Key_0 || key > Qt::Key_9)
- return QCalendarDateSectionValidator::ThisSection;
- int pressedKey = key - Qt::Key_0;
- if (m_pos == 0)
- m_day = pressedKey;
- else
- m_day = m_day % 10 * 10 + pressedKey;
- if (m_day > 31)
- m_day = 31;
- ++m_pos;
- if (m_pos > 1) {
- m_pos = 0;
- return QCalendarDateSectionValidator::NextSection;
- }
- return QCalendarDateSectionValidator::ThisSection;
-}
-
-QDate QCalendarDayValidator::applyToDate(const QDate &date) const
-{
- int day = m_day;
- if (day < 1)
- day = 1;
- else if (day > 31)
- day = 31;
- if (day > date.daysInMonth())
- day = date.daysInMonth();
- return QDate(date.year(), date.month(), day);
-}
-
-void QCalendarDayValidator::setDate(const QDate &date)
-{
- m_day = m_oldDay = date.day();
- m_pos = 0;
-}
-
-QString QCalendarDayValidator::text() const
-{
- QString str;
- if (m_day / 10 == 0)
- str += QLatin1Char('0');
- str += QString::number(m_day);
- return highlightString(str, m_pos);
-}
-
-QString QCalendarDayValidator::text(const QDate &date, int repeat) const
-{
- if (repeat <= 1) {
- return QString::number(date.day());
- } else if (repeat == 2) {
- QString str;
- if (date.day() / 10 == 0)
- str += QLatin1Char('0');
- return str + QString::number(date.day());
- } else if (repeat == 3) {
- return m_locale.dayName(date.dayOfWeek(), QLocale::ShortFormat);
- } else if (repeat >= 4) {
- return m_locale.dayName(date.dayOfWeek(), QLocale::LongFormat);
- }
- return QString();
-}
-
-//////////////////////////////////
-
-class QCalendarMonthValidator : public QCalendarDateSectionValidator
-{
-
-public:
- QCalendarMonthValidator();
- virtual Section handleKey(int key);
- virtual QDate applyToDate(const QDate &date) const;
- virtual void setDate(const QDate &date);
- virtual QString text() const;
- virtual QString text(const QDate &date, int repeat) const;
-private:
- int m_pos;
- int m_month;
- int m_oldMonth;
-};
-
-QCalendarMonthValidator::QCalendarMonthValidator()
- : QCalendarDateSectionValidator(), m_pos(0), m_month(1), m_oldMonth(1)
-{
-}
-
-QCalendarDateSectionValidator::Section QCalendarMonthValidator::handleKey(int key)
-{
- if (key == Qt::Key_Right || key == Qt::Key_Left) {
- m_pos = 0;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Up) {
- m_pos = 0;
- ++m_month;
- if (m_month > 12)
- m_month = 1;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Down) {
- m_pos = 0;
- --m_month;
- if (m_month < 1)
- m_month = 12;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Back || key == Qt::Key_Backspace) {
- --m_pos;
- if (m_pos < 0)
- m_pos = 1;
-
- if (m_pos == 0)
- m_month = m_oldMonth;
- else
- m_month = m_month / 10;
- //m_month = m_oldMonth / 10 * 10 + m_month / 10;
-
- if (m_pos == 0)
- return QCalendarDateSectionValidator::PrevSection;
- return QCalendarDateSectionValidator::ThisSection;
- }
- if (key < Qt::Key_0 || key > Qt::Key_9)
- return QCalendarDateSectionValidator::ThisSection;
- int pressedKey = key - Qt::Key_0;
- if (m_pos == 0)
- m_month = pressedKey;
- else
- m_month = m_month % 10 * 10 + pressedKey;
- if (m_month > 12)
- m_month = 12;
- ++m_pos;
- if (m_pos > 1) {
- m_pos = 0;
- return QCalendarDateSectionValidator::NextSection;
- }
- return QCalendarDateSectionValidator::ThisSection;
-}
-
-QDate QCalendarMonthValidator::applyToDate(const QDate &date) const
-{
- int month = m_month;
- if (month < 1)
- month = 1;
- else if (month > 12)
- month = 12;
- QDate newDate(date.year(), m_month, 1);
- int day = date.day();
- if (day > newDate.daysInMonth())
- day = newDate.daysInMonth();
- return QDate(date.year(), month, day);
-}
-
-void QCalendarMonthValidator::setDate(const QDate &date)
-{
- m_month = m_oldMonth = date.month();
- m_pos = 0;
-}
-
-QString QCalendarMonthValidator::text() const
-{
- QString str;
- if (m_month / 10 == 0)
- str += QLatin1Char('0');
- str += QString::number(m_month);
- return highlightString(str, m_pos);
-}
-
-QString QCalendarMonthValidator::text(const QDate &date, int repeat) const
-{
- if (repeat <= 1) {
- return QString::number(date.month());
- } else if (repeat == 2) {
- QString str;
- if (date.month() / 10 == 0)
- str += QLatin1Char('0');
- return str + QString::number(date.month());
- } else if (repeat == 3) {
- return m_locale.standaloneMonthName(date.month(), QLocale::ShortFormat);
- } else /*if (repeat >= 4)*/ {
- return m_locale.standaloneMonthName(date.month(), QLocale::LongFormat);
- }
-}
-
-//////////////////////////////////
-
-class QCalendarYearValidator : public QCalendarDateSectionValidator
-{
-
-public:
- QCalendarYearValidator();
- virtual Section handleKey(int key);
- virtual QDate applyToDate(const QDate &date) const;
- virtual void setDate(const QDate &date);
- virtual QString text() const;
- virtual QString text(const QDate &date, int repeat) const;
-private:
- int pow10(int n);
- int m_pos;
- int m_year;
- int m_oldYear;
-};
-
-QCalendarYearValidator::QCalendarYearValidator()
- : QCalendarDateSectionValidator(), m_pos(0), m_year(2000), m_oldYear(2000)
-{
-}
-
-int QCalendarYearValidator::pow10(int n)
-{
- int power = 1;
- for (int i = 0; i < n; i++)
- power *= 10;
- return power;
-}
-
-QCalendarDateSectionValidator::Section QCalendarYearValidator::handleKey(int key)
-{
- if (key == Qt::Key_Right || key == Qt::Key_Left) {
- m_pos = 0;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Up) {
- m_pos = 0;
- ++m_year;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Down) {
- m_pos = 0;
- --m_year;
- return QCalendarDateSectionValidator::ThisSection;
- } else if (key == Qt::Key_Back || key == Qt::Key_Backspace) {
- --m_pos;
- if (m_pos < 0)
- m_pos = 3;
-
- int pow = pow10(m_pos);
- m_year = m_oldYear / pow * pow + m_year % (pow * 10) / 10;
-
- if (m_pos == 0)
- return QCalendarDateSectionValidator::PrevSection;
- return QCalendarDateSectionValidator::ThisSection;
- }
- if (key < Qt::Key_0 || key > Qt::Key_9)
- return QCalendarDateSectionValidator::ThisSection;
- int pressedKey = key - Qt::Key_0;
- int pow = pow10(m_pos);
- m_year = m_year / (pow * 10) * (pow * 10) + m_year % pow * 10 + pressedKey;
- ++m_pos;
- if (m_pos > 3) {
- m_pos = 0;
- return QCalendarDateSectionValidator::NextSection;
- }
- return QCalendarDateSectionValidator::ThisSection;
-}
-
-QDate QCalendarYearValidator::applyToDate(const QDate &date) const
-{
- int year = m_year;
- if (year < 1)
- year = 1;
- QDate newDate(year, date.month(), 1);
- int day = date.day();
- if (day > newDate.daysInMonth())
- day = newDate.daysInMonth();
- return QDate(year, date.month(), day);
-}
-
-void QCalendarYearValidator::setDate(const QDate &date)
-{
- m_year = m_oldYear = date.year();
- m_pos = 0;
-}
-
-QString QCalendarYearValidator::text() const
-{
- QString str;
- int pow = 10;
- for (int i = 0; i < 3; i++) {
- if (m_year / pow == 0)
- str += QLatin1Char('0');
- pow *= 10;
- }
- str += QString::number(m_year);
- return highlightString(str, m_pos);
-}
-
-QString QCalendarYearValidator::text(const QDate &date, int repeat) const
-{
- if (repeat < 4) {
- QString str;
- int year = date.year() % 100;
- if (year / 10 == 0)
- str = QLatin1Char('0');
- return str + QString::number(year);
- }
- return QString::number(date.year());
-}
-
-///////////////////////////////////
-
-class QCalendarDateValidator
-{
-public:
- QCalendarDateValidator();
- ~QCalendarDateValidator();
-
- void handleKeyEvent(QKeyEvent *keyEvent);
- QString currentText() const;
- QDate currentDate() const { return m_currentDate; }
- void setFormat(const QString &format);
- void setInitialDate(const QDate &date);
-
- void setLocale(const QLocale &locale);
-
-private:
-
- struct SectionToken {
- SectionToken(QCalendarDateSectionValidator *val, int rep) : validator(val), repeat(rep) {}
- QCalendarDateSectionValidator *validator;
- int repeat;
- };
-
- void toNextToken();
- void toPreviousToken();
- void applyToDate();
-
- int countRepeat(const QString &str, int index) const;
- void clear();
-
- QStringList m_separators;
- QList<SectionToken *> m_tokens;
- QCalendarDateSectionValidator *m_yearValidator;
- QCalendarDateSectionValidator *m_monthValidator;
- QCalendarDateSectionValidator *m_dayValidator;
-
- SectionToken *m_currentToken;
-
- QDate m_initialDate;
- QDate m_currentDate;
-
- QCalendarDateSectionValidator::Section m_lastSectionMove;
-};
-
-QCalendarDateValidator::QCalendarDateValidator()
- : m_currentToken(0), m_lastSectionMove(QCalendarDateSectionValidator::ThisSection)
-{
- m_initialDate = m_currentDate = QDate::currentDate();
- m_yearValidator = new QCalendarYearValidator();
- m_monthValidator = new QCalendarMonthValidator();
- m_dayValidator = new QCalendarDayValidator();
-}
-
-void QCalendarDateValidator::setLocale(const QLocale &locale)
-{
- m_yearValidator->m_locale = locale;
- m_monthValidator->m_locale = locale;
- m_dayValidator->m_locale = locale;
-}
-
-QCalendarDateValidator::~QCalendarDateValidator()
-{
- delete m_yearValidator;
- delete m_monthValidator;
- delete m_dayValidator;
- clear();
-}
-
-// from qdatetime.cpp
-int QCalendarDateValidator::countRepeat(const QString &str, int index) const
-{
- Q_ASSERT(index >= 0 && index < str.size());
- int count = 1;
- const QChar ch = str.at(index);
- while (index + count < str.size() && str.at(index + count) == ch)
- ++count;
- return count;
-}
-
-void QCalendarDateValidator::setInitialDate(const QDate &date)
-{
- m_yearValidator->setDate(date);
- m_monthValidator->setDate(date);
- m_dayValidator->setDate(date);
- m_initialDate = date;
- m_currentDate = date;
- m_lastSectionMove = QCalendarDateSectionValidator::ThisSection;
-}
-
-QString QCalendarDateValidator::currentText() const
-{
- QString str;
- QStringListIterator itSep(m_separators);
- QListIterator<SectionToken *> itTok(m_tokens);
- while (itSep.hasNext()) {
- str += itSep.next();
- if (itTok.hasNext()) {
- SectionToken *token = itTok.next();
- QCalendarDateSectionValidator *validator = token->validator;
- if (m_currentToken == token)
- str += validator->text();
- else
- str += validator->text(m_currentDate, token->repeat);
- }
- }
- return str;
-}
-
-void QCalendarDateValidator::clear()
-{
- QListIterator<SectionToken *> it(m_tokens);
- while (it.hasNext())
- delete it.next();
-
- m_tokens.clear();
- m_separators.clear();
-
- m_currentToken = 0;
-}
-
-void QCalendarDateValidator::setFormat(const QString &format)
-{
- clear();
-
- int pos = 0;
- const QLatin1Char quote('\'');
- bool quoting = false;
- QString separator;
- while (pos < format.size()) {
- QString mid = format.mid(pos);
- int offset = 1;
-
- if (mid.startsWith(quote)) {
- quoting = !quoting;
- } else {
- const QChar nextChar = format.at(pos);
- if (quoting) {
- separator += nextChar;
- } else {
- SectionToken *token = 0;
- if (nextChar == QLatin1Char('d')) {
- offset = qMin(4, countRepeat(format, pos));
- token = new SectionToken(m_dayValidator, offset);
- } else if (nextChar == QLatin1Char('M')) {
- offset = qMin(4, countRepeat(format, pos));
- token = new SectionToken(m_monthValidator, offset);
- } else if (nextChar == QLatin1Char('y')) {
- offset = qMin(4, countRepeat(format, pos));
- token = new SectionToken(m_yearValidator, offset);
- } else {
- separator += nextChar;
- }
- if (token) {
- m_tokens.append(token);
- m_separators.append(separator);
- separator = QString();
- if (!m_currentToken)
- m_currentToken = token;
-
- }
- }
- }
- pos += offset;
- }
- m_separators += separator;
-}
-
-void QCalendarDateValidator::applyToDate()
-{
- m_currentDate = m_yearValidator->applyToDate(m_currentDate);
- m_currentDate = m_monthValidator->applyToDate(m_currentDate);
- m_currentDate = m_dayValidator->applyToDate(m_currentDate);
-}
-
-void QCalendarDateValidator::toNextToken()
-{
- const int idx = m_tokens.indexOf(m_currentToken);
- if (idx == -1)
- return;
- if (idx + 1 >= m_tokens.count())
- m_currentToken = m_tokens.first();
- else
- m_currentToken = m_tokens.at(idx + 1);
-}
-
-void QCalendarDateValidator::toPreviousToken()
-{
- const int idx = m_tokens.indexOf(m_currentToken);
- if (idx == -1)
- return;
- if (idx - 1 < 0)
- m_currentToken = m_tokens.last();
- else
- m_currentToken = m_tokens.at(idx - 1);
-}
-
-void QCalendarDateValidator::handleKeyEvent(QKeyEvent *keyEvent)
-{
- if (!m_currentToken)
- return;
-
- int key = keyEvent->key();
- if (m_lastSectionMove == QCalendarDateSectionValidator::NextSection) {
- if (key == Qt::Key_Back || key == Qt::Key_Backspace)
- toPreviousToken();
- }
- if (key == Qt::Key_Right)
- toNextToken();
- else if (key == Qt::Key_Left)
- toPreviousToken();
-
- m_lastSectionMove = m_currentToken->validator->handleKey(key);
-
- applyToDate();
- if (m_lastSectionMove == QCalendarDateSectionValidator::NextSection)
- toNextToken();
- else if (m_lastSectionMove == QCalendarDateSectionValidator::PrevSection)
- toPreviousToken();
-}
-
-QWidget *QCalendarTextNavigator::widget() const
-{
- return m_widget;
-}
-
-void QCalendarTextNavigator::setWidget(QWidget *widget)
-{
- m_widget = widget;
-}
-
-QDate QCalendarTextNavigator::date() const
-{
- return m_date;
-}
-
-void QCalendarTextNavigator::setDate(const QDate &date)
-{
- m_date = date;
-}
-
-void QCalendarTextNavigator::updateDateLabel()
-{
- if (!m_widget)
- return;
-
- m_acceptTimer.start(m_editDelay, this);
-
- m_dateText->setText(m_dateValidator->currentText());
-
- QSize s = m_dateFrame->sizeHint();
- QRect r = m_widget->geometry(); // later, just the table section
- QRect newRect((r.width() - s.width()) / 2, (r.height() - s.height()) / 2, s.width(), s.height());
- m_dateFrame->setGeometry(newRect);
- // need to set palette after geometry update as phonestyle sets transparency
- // effect in move event.
- QPalette p = m_dateFrame->palette();
- p.setBrush(QPalette::Window, m_dateFrame->window()->palette().brush(QPalette::Window));
- m_dateFrame->setPalette(p);
-
- m_dateFrame->raise();
- m_dateFrame->show();
-}
-
-void QCalendarTextNavigator::applyDate()
-{
- QDate date = m_dateValidator->currentDate();
- if (m_date == date)
- return;
-
- m_date = date;
- emit dateChanged(date);
-}
-
-void QCalendarTextNavigator::createDateLabel()
-{
- if (m_dateFrame)
- return;
- m_dateFrame = new QFrame(m_widget);
- QVBoxLayout *vl = new QVBoxLayout;
- m_dateText = new QLabel;
- vl->addWidget(m_dateText);
- m_dateFrame->setLayout(vl);
- m_dateFrame->setFrameShadow(QFrame::Plain);
- m_dateFrame->setFrameShape(QFrame::Box);
- m_dateValidator = new QCalendarDateValidator();
- m_dateValidator->setLocale(m_widget->locale());
- m_dateValidator->setFormat(m_widget->locale().dateFormat(QLocale::ShortFormat));
- m_dateValidator->setInitialDate(m_date);
-
- m_dateFrame->setAutoFillBackground(true);
- m_dateFrame->setBackgroundRole(QPalette::Window);
-}
-
-void QCalendarTextNavigator::removeDateLabel()
-{
- if (!m_dateFrame)
- return;
- m_acceptTimer.stop();
- m_dateFrame->hide();
- m_dateFrame->deleteLater();
- delete m_dateValidator;
- m_dateFrame = 0;
- m_dateText = 0;
- m_dateValidator = 0;
-}
-
-bool QCalendarTextNavigator::eventFilter(QObject *o, QEvent *e)
-{
- if (m_widget) {
- if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) {
- QKeyEvent* ke = (QKeyEvent*)e;
- if ((ke->text().length() > 0 && ke->text()[0].isPrint()) || m_dateFrame) {
- if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Select) {
- applyDate();
- emit editingFinished();
- removeDateLabel();
- } else if (ke->key() == Qt::Key_Escape) {
- removeDateLabel();
- } else if (e->type() == QEvent::KeyPress) {
- createDateLabel();
- m_dateValidator->handleKeyEvent(ke);
- updateDateLabel();
- }
- ke->accept();
- return true;
- }
- // If we are navigating let the user finish his date in old locate.
- // If we change our mind and want it to update immediately simply uncomment below
- /*
- } else if (e->type() == QEvent::LocaleChange) {
- if (m_dateValidator) {
- m_dateValidator->setLocale(m_widget->locale());
- m_dateValidator->setFormat(m_widget->locale().dateFormat(QLocale::ShortFormat));
- updateDateLabel();
- }
- */
- }
- }
- return QObject::eventFilter(o,e);
-}
-
-void QCalendarTextNavigator::timerEvent(QTimerEvent *e)
-{
- if (e->timerId() == m_acceptTimer.timerId()) {
- applyDate();
- removeDateLabel();
- }
-}
-
-int QCalendarTextNavigator::dateEditAcceptDelay() const
-{
- return m_editDelay;
-}
-
-void QCalendarTextNavigator::setDateEditAcceptDelay(int delay)
-{
- m_editDelay = delay;
-}
-
-class QCalendarView;
-
-class QCalendarModel : public QAbstractTableModel
-{
- Q_OBJECT
-public:
- QCalendarModel(QObject *parent = 0);
-
- int rowCount(const QModelIndex &) const
- { return RowCount + m_firstRow; }
- int columnCount(const QModelIndex &) const
- { return ColumnCount + m_firstColumn; }
- QVariant data(const QModelIndex &index, int role) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex())
- {
- beginInsertRows(parent, row, row + count - 1);
- endInsertRows();
- return true;
- }
- bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex())
- {
- beginInsertColumns(parent, column, column + count - 1);
- endInsertColumns();
- return true;
- }
- bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex())
- {
- beginRemoveRows(parent, row, row + count - 1);
- endRemoveRows();
- return true;
- }
- bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex())
- {
- beginRemoveColumns(parent, column, column + count - 1);
- endRemoveColumns();
- return true;
- }
-
- void showMonth(int year, int month);
- void setDate(const QDate &d);
-
- void setMinimumDate(const QDate &date);
- void setMaximumDate(const QDate &date);
-
- void setRange(const QDate &min, const QDate &max);
-
- void setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat format);
-
- void setFirstColumnDay(Qt::DayOfWeek dayOfWeek);
- Qt::DayOfWeek firstColumnDay() const;
-
- bool weekNumbersShown() const;
- void setWeekNumbersShown(bool show);
-
- QTextCharFormat formatForCell(int row, int col) const;
- Qt::DayOfWeek dayOfWeekForColumn(int section) const;
- int columnForDayOfWeek(Qt::DayOfWeek day) const;
- QDate dateForCell(int row, int column) const;
- void cellForDate(const QDate &date, int *row, int *column) const;
- QString dayName(Qt::DayOfWeek day) const;
-
- void setView(QCalendarView *view)
- { m_view = view; }
-
- void internalUpdate();
- QDate referenceDate() const;
- int columnForFirstOfMonth(const QDate &date) const;
-
- int m_firstColumn;
- int m_firstRow;
- QDate m_date;
- QDate m_minimumDate;
- QDate m_maximumDate;
- int m_shownYear;
- int m_shownMonth;
- Qt::DayOfWeek m_firstDay;
- QCalendarWidget::HorizontalHeaderFormat m_horizontalHeaderFormat;
- bool m_weekNumbersShown;
- QMap<Qt::DayOfWeek, QTextCharFormat> m_dayFormats;
- QMap<QDate, QTextCharFormat> m_dateFormats;
- QTextCharFormat m_headerFormat;
- QCalendarView *m_view;
-};
-
-class QCalendarView : public QTableView
-{
- Q_OBJECT
-public:
- QCalendarView(QWidget *parent = 0);
-
- void internalUpdate() { updateGeometries(); }
- void setReadOnly(bool enable);
- virtual void keyboardSearch(const QString & search) { Q_UNUSED(search) }
-
-signals:
- void showDate(const QDate &date);
- void changeDate(const QDate &date, bool changeMonth);
- void clicked(const QDate &date);
- void editingFinished();
-protected:
- QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
- void mouseDoubleClickEvent(QMouseEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *event);
-#endif
- void keyPressEvent(QKeyEvent *event);
- bool event(QEvent *event);
-
- QDate handleMouseEvent(QMouseEvent *event);
-public:
- bool readOnly;
-private:
- bool validDateClicked;
-#ifdef QT_KEYPAD_NAVIGATION
- QDate origDate;
-#endif
-};
-
-QCalendarModel::QCalendarModel(QObject *parent)
- : QAbstractTableModel(parent)
-{
- m_date = QDate::currentDate();
- m_minimumDate = QDate::fromJulianDay(1);
- m_maximumDate = QDate(7999, 12, 31);
- m_shownYear = m_date.year();
- m_shownMonth = m_date.month();
- m_firstDay = Qt::Sunday;
- m_horizontalHeaderFormat = QCalendarWidget::ShortDayNames;
- m_weekNumbersShown = true;
- m_firstColumn = 1;
- m_firstRow = 1;
- m_view = 0;
-}
-
-Qt::DayOfWeek QCalendarModel::dayOfWeekForColumn(int column) const
-{
- int col = column - m_firstColumn;
- if (col < 0 || col > 6)
- return Qt::Sunday;
- int day = m_firstDay + col;
- if (day > 7)
- day -= 7;
- return Qt::DayOfWeek(day);
-}
-
-int QCalendarModel::columnForDayOfWeek(Qt::DayOfWeek day) const
-{
- if (day < 1 || day > 7)
- return -1;
- int column = (int)day - (int)m_firstDay;
- if (column < 0)
- column += 7;
- return column + m_firstColumn;
-}
-
-/*
-This simple algorithm tries to generate a valid date from the month shown.
-Some months don't contain a first day (e.g. Jan of -4713 year,
-so QDate (-4713, 1, 1) would be invalid). In that case we try to generate
-another valid date for that month. Later, returned date's day is the number of cells
-calendar widget will reserve for days before referenceDate. (E.g. if returned date's
-day is 16, that day will be placed in 3rd or 4th row, not in the 1st or 2nd row).
-Depending on referenceData we can change behaviour of Oct 1582. If referenceDate is 1st
-of Oct we render 1 Oct in 1st or 2nd row. If referenceDate is 17 of Oct we show always 16
-dates before 17 of Oct, and since this month contains the hole 5-14 Oct, the first of Oct
-will be rendered in 2nd or 3rd row, showing more dates from previous month.
-*/
-QDate QCalendarModel::referenceDate() const
-{
- int refDay = 1;
- while (refDay <= 31) {
- QDate refDate(m_shownYear, m_shownMonth, refDay);
- if (refDate.isValid())
- return refDate;
- refDay += 1;
- }
- return QDate();
-}
-
-int QCalendarModel::columnForFirstOfMonth(const QDate &date) const
-{
- return (columnForDayOfWeek(static_cast<Qt::DayOfWeek>(date.dayOfWeek())) - (date.day() % 7) + 8) % 7;
-}
-
-QDate QCalendarModel::dateForCell(int row, int column) const
-{
- if (row < m_firstRow || row > m_firstRow + RowCount - 1 ||
- column < m_firstColumn || column > m_firstColumn + ColumnCount - 1)
- return QDate();
- const QDate refDate = referenceDate();
- if (!refDate.isValid())
- return QDate();
-
- const int columnForFirstOfShownMonth = columnForFirstOfMonth(refDate);
- if (columnForFirstOfShownMonth - m_firstColumn < MinimumDayOffset)
- row -= 1;
-
- const int requestedDay = 7 * (row - m_firstRow) + column - columnForFirstOfShownMonth - refDate.day() + 1;
- return refDate.addDays(requestedDay);
-}
-
-void QCalendarModel::cellForDate(const QDate &date, int *row, int *column) const
-{
- if (!row && !column)
- return;
-
- if (row)
- *row = -1;
- if (column)
- *column = -1;
-
- const QDate refDate = referenceDate();
- if (!refDate.isValid())
- return;
-
- const int columnForFirstOfShownMonth = columnForFirstOfMonth(refDate);
- const int requestedPosition = refDate.daysTo(date) - m_firstColumn + columnForFirstOfShownMonth + refDate.day() - 1;
-
- int c = requestedPosition % 7;
- int r = requestedPosition / 7;
- if (c < 0) {
- c += 7;
- r -= 1;
- }
-
- if (columnForFirstOfShownMonth - m_firstColumn < MinimumDayOffset)
- r += 1;
-
- if (r < 0 || r > RowCount - 1 || c < 0 || c > ColumnCount - 1)
- return;
-
- if (row)
- *row = r + m_firstRow;
- if (column)
- *column = c + m_firstColumn;
-}
-
-QString QCalendarModel::dayName(Qt::DayOfWeek day) const
-{
- switch (m_horizontalHeaderFormat) {
- case QCalendarWidget::SingleLetterDayNames: {
- QString standaloneDayName = m_view->locale().standaloneDayName(day, QLocale::NarrowFormat);
- if (standaloneDayName == m_view->locale().dayName(day, QLocale::NarrowFormat))
- return standaloneDayName.left(1);
- return standaloneDayName;
- }
- case QCalendarWidget::ShortDayNames:
- return m_view->locale().dayName(day, QLocale::ShortFormat);
- case QCalendarWidget::LongDayNames:
- return m_view->locale().dayName(day, QLocale::LongFormat);
- default:
- break;
- }
- return QString();
-}
-
-QTextCharFormat QCalendarModel::formatForCell(int row, int col) const
-{
- QPalette pal;
- QPalette::ColorGroup cg = QPalette::Active;
- if (m_view) {
- pal = m_view->palette();
- if (!m_view->isEnabled())
- cg = QPalette::Disabled;
- else if (!m_view->isActiveWindow())
- cg = QPalette::Inactive;
- }
-
- QTextCharFormat format;
- format.setFont(m_view->font());
- bool header = (m_weekNumbersShown && col == HeaderColumn)
- || (m_horizontalHeaderFormat != QCalendarWidget::NoHorizontalHeader && row == HeaderRow);
- format.setBackground(pal.brush(cg, header ? QPalette::AlternateBase : QPalette::Base));
- format.setForeground(pal.brush(cg, QPalette::Text));
- if (header) {
- format.merge(m_headerFormat);
- }
-
- if (col >= m_firstColumn && col < m_firstColumn + ColumnCount) {
- Qt::DayOfWeek dayOfWeek = dayOfWeekForColumn(col);
- if (m_dayFormats.contains(dayOfWeek))
- format.merge(m_dayFormats.value(dayOfWeek));
- }
-
- if (!header) {
- QDate date = dateForCell(row, col);
- format.merge(m_dateFormats.value(date));
- if(date < m_minimumDate || date > m_maximumDate)
- format.setBackground(pal.brush(cg, QPalette::Window));
- if (m_shownMonth != date.month())
- format.setForeground(pal.brush(QPalette::Disabled, QPalette::Text));
- }
- return format;
-}
-
-QVariant QCalendarModel::data(const QModelIndex &index, int role) const
-{
- if (role == Qt::TextAlignmentRole)
- return (int) Qt::AlignCenter;
-
- int row = index.row();
- int column = index.column();
-
- if(role == Qt::DisplayRole) {
- if (m_weekNumbersShown && column == HeaderColumn
- && row >= m_firstRow && row < m_firstRow + RowCount) {
- QDate date = dateForCell(row, columnForDayOfWeek(Qt::Monday));
- if (date.isValid())
- return date.weekNumber();
- }
- if (m_horizontalHeaderFormat != QCalendarWidget::NoHorizontalHeader && row == HeaderRow
- && column >= m_firstColumn && column < m_firstColumn + ColumnCount)
- return dayName(dayOfWeekForColumn(column));
- QDate date = dateForCell(row, column);
- if (date.isValid())
- return date.day();
- return QString();
- }
-
- QTextCharFormat fmt = formatForCell(row, column);
- if (role == Qt::BackgroundColorRole)
- return fmt.background().color();
- if (role == Qt::TextColorRole)
- return fmt.foreground().color();
- if (role == Qt::FontRole)
- return fmt.font();
- if (role == Qt::ToolTipRole)
- return fmt.toolTip();
- return QVariant();
-}
-
-Qt::ItemFlags QCalendarModel::flags(const QModelIndex &index) const
-{
- QDate date = dateForCell(index.row(), index.column());
- if (!date.isValid())
- return QAbstractTableModel::flags(index);
- if (date < m_minimumDate)
- return 0;
- if (date > m_maximumDate)
- return 0;
- return QAbstractTableModel::flags(index);
-}
-
-void QCalendarModel::setDate(const QDate &d)
-{
- m_date = d;
- if (m_date < m_minimumDate)
- m_date = m_minimumDate;
- else if (m_date > m_maximumDate)
- m_date = m_maximumDate;
-}
-
-void QCalendarModel::showMonth(int year, int month)
-{
- if (m_shownYear == year && m_shownMonth == month)
- return;
-
- m_shownYear = year;
- m_shownMonth = month;
-
- internalUpdate();
-}
-
-void QCalendarModel::setMinimumDate(const QDate &d)
-{
- if (!d.isValid() || d == m_minimumDate)
- return;
-
- m_minimumDate = d;
- if (m_maximumDate < m_minimumDate)
- m_maximumDate = m_minimumDate;
- if (m_date < m_minimumDate)
- m_date = m_minimumDate;
- internalUpdate();
-}
-
-void QCalendarModel::setMaximumDate(const QDate &d)
-{
- if (!d.isValid() || d == m_maximumDate)
- return;
-
- m_maximumDate = d;
- if (m_minimumDate > m_maximumDate)
- m_minimumDate = m_maximumDate;
- if (m_date > m_maximumDate)
- m_date = m_maximumDate;
- internalUpdate();
-}
-
-void QCalendarModel::setRange(const QDate &min, const QDate &max)
-{
- m_minimumDate = min;
- m_maximumDate = max;
- if (m_minimumDate > m_maximumDate)
- qSwap(m_minimumDate, m_maximumDate);
- if (m_date < m_minimumDate)
- m_date = m_minimumDate;
- if (m_date > m_maximumDate)
- m_date = m_maximumDate;
- internalUpdate();
-}
-
-void QCalendarModel::internalUpdate()
-{
- QModelIndex begin = index(0, 0);
- QModelIndex end = index(m_firstRow + RowCount - 1, m_firstColumn + ColumnCount - 1);
- emit dataChanged(begin, end);
- emit headerDataChanged(Qt::Vertical, 0, m_firstRow + RowCount - 1);
- emit headerDataChanged(Qt::Horizontal, 0, m_firstColumn + ColumnCount - 1);
-}
-
-void QCalendarModel::setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat format)
-{
- if (m_horizontalHeaderFormat == format)
- return;
-
- int oldFormat = m_horizontalHeaderFormat;
- m_horizontalHeaderFormat = format;
- if (oldFormat == QCalendarWidget::NoHorizontalHeader) {
- m_firstRow = 1;
- insertRow(0);
- } else if (m_horizontalHeaderFormat == QCalendarWidget::NoHorizontalHeader) {
- m_firstRow = 0;
- removeRow(0);
- }
- internalUpdate();
-}
-
-void QCalendarModel::setFirstColumnDay(Qt::DayOfWeek dayOfWeek)
-{
- if (m_firstDay == dayOfWeek)
- return;
-
- m_firstDay = dayOfWeek;
- internalUpdate();
-}
-
-Qt::DayOfWeek QCalendarModel::firstColumnDay() const
-{
- return m_firstDay;
-}
-
-bool QCalendarModel::weekNumbersShown() const
-{
- return m_weekNumbersShown;
-}
-
-void QCalendarModel::setWeekNumbersShown(bool show)
-{
- if (m_weekNumbersShown == show)
- return;
-
- m_weekNumbersShown = show;
- if (show) {
- m_firstColumn = 1;
- insertColumn(0);
- } else {
- m_firstColumn = 0;
- removeColumn(0);
- }
- internalUpdate();
-}
-
-QCalendarView::QCalendarView(QWidget *parent)
- : QTableView(parent),
- readOnly(false),
- validDateClicked(false)
-{
- setTabKeyNavigation(false);
- setShowGrid(false);
- verticalHeader()->setVisible(false);
- horizontalHeader()->setVisible(false);
- setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
-}
-
-QModelIndex QCalendarView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
-{
- QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model());
- if (!calendarModel)
- return QTableView::moveCursor(cursorAction, modifiers);
-
- if (readOnly)
- return currentIndex();
-
- QModelIndex index = currentIndex();
- QDate currentDate = static_cast<QCalendarModel*>(model())->dateForCell(index.row(), index.column());
- switch (cursorAction) {
- case QAbstractItemView::MoveUp:
- currentDate = currentDate.addDays(-7);
- break;
- case QAbstractItemView::MoveDown:
- currentDate = currentDate.addDays(7);
- break;
- case QAbstractItemView::MoveLeft:
- currentDate = currentDate.addDays(isRightToLeft() ? 1 : -1);
- break;
- case QAbstractItemView::MoveRight:
- currentDate = currentDate.addDays(isRightToLeft() ? -1 : 1);
- break;
- case QAbstractItemView::MoveHome:
- currentDate = QDate(currentDate.year(), currentDate.month(), 1);
- break;
- case QAbstractItemView::MoveEnd:
- currentDate = QDate(currentDate.year(), currentDate.month(), currentDate.daysInMonth());
- break;
- case QAbstractItemView::MovePageUp:
- currentDate = currentDate.addMonths(-1);
- break;
- case QAbstractItemView::MovePageDown:
- currentDate = currentDate.addMonths(1);
- break;
- case QAbstractItemView::MoveNext:
- case QAbstractItemView::MovePrevious:
- return currentIndex();
- default:
- break;
- }
- emit changeDate(currentDate, true);
- return currentIndex();
-}
-
-void QCalendarView::keyPressEvent(QKeyEvent *event)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- if (event->key() == Qt::Key_Select) {
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus()) {
- setEditFocus(true);
- return;
- }
- }
- } else if (event->key() == Qt::Key_Back) {
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
- if (qobject_cast<QCalendarModel *>(model())) {
- emit changeDate(origDate, true); //changes selection back to origDate, but doesn't activate
- setEditFocus(false);
- return;
- }
- }
- }
-#endif
-
- if (!readOnly) {
- switch (event->key()) {
- case Qt::Key_Return:
- case Qt::Key_Enter:
- case Qt::Key_Select:
- emit editingFinished();
- return;
- default:
- break;
- }
- }
- QTableView::keyPressEvent(event);
-}
-
-#ifndef QT_NO_WHEELEVENT
-void QCalendarView::wheelEvent(QWheelEvent *event)
-{
- const int numDegrees = event->delta() / 8;
- const int numSteps = numDegrees / 15;
- const QModelIndex index = currentIndex();
- QDate currentDate = static_cast<QCalendarModel*>(model())->dateForCell(index.row(), index.column());
- currentDate = currentDate.addMonths(-numSteps);
- emit showDate(currentDate);
-}
-#endif
-
-bool QCalendarView::event(QEvent *event)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- if (event->type() == QEvent::FocusIn) {
- if (QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model())) {
- origDate = calendarModel->m_date;
- }
- }
-#endif
-
- return QTableView::event(event);
-}
-
-QDate QCalendarView::handleMouseEvent(QMouseEvent *event)
-{
- QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model());
- if (!calendarModel)
- return QDate();
-
- QPoint pos = event->pos();
- QModelIndex index = indexAt(pos);
- QDate date = calendarModel->dateForCell(index.row(), index.column());
- if (date.isValid() && date >= calendarModel->m_minimumDate
- && date <= calendarModel->m_maximumDate) {
- return date;
- }
- return QDate();
-}
-
-void QCalendarView::mouseDoubleClickEvent(QMouseEvent *event)
-{
- QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model());
- if (!calendarModel) {
- QTableView::mouseDoubleClickEvent(event);
- return;
- }
-
- if (readOnly)
- return;
-
- QDate date = handleMouseEvent(event);
- validDateClicked = false;
- if (date == calendarModel->m_date && !style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
- emit editingFinished();
- }
-}
-
-void QCalendarView::mousePressEvent(QMouseEvent *event)
-{
- QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model());
- if (!calendarModel) {
- QTableView::mousePressEvent(event);
- return;
- }
-
- if (readOnly)
- return;
-
- if (event->button() != Qt::LeftButton)
- return;
-
- QDate date = handleMouseEvent(event);
- if (date.isValid()) {
- validDateClicked = true;
- int row = -1, col = -1;
- static_cast<QCalendarModel *>(model())->cellForDate(date, &row, &col);
- if (row != -1 && col != -1) {
- selectionModel()->setCurrentIndex(model()->index(row, col), QItemSelectionModel::NoUpdate);
- }
- } else {
- validDateClicked = false;
- event->ignore();
- }
-}
-
-void QCalendarView::mouseMoveEvent(QMouseEvent *event)
-{
- QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model());
- if (!calendarModel) {
- QTableView::mouseMoveEvent(event);
- return;
- }
-
- if (readOnly)
- return;
-
- if (validDateClicked) {
- QDate date = handleMouseEvent(event);
- if (date.isValid()) {
- int row = -1, col = -1;
- static_cast<QCalendarModel *>(model())->cellForDate(date, &row, &col);
- if (row != -1 && col != -1) {
- selectionModel()->setCurrentIndex(model()->index(row, col), QItemSelectionModel::NoUpdate);
- }
- }
- } else {
- event->ignore();
- }
-}
-
-void QCalendarView::mouseReleaseEvent(QMouseEvent *event)
-{
- QCalendarModel *calendarModel = qobject_cast<QCalendarModel *>(model());
- if (!calendarModel) {
- QTableView::mouseReleaseEvent(event);
- return;
- }
-
- if (event->button() != Qt::LeftButton)
- return;
-
- if (readOnly)
- return;
-
- if (validDateClicked) {
- QDate date = handleMouseEvent(event);
- if (date.isValid()) {
- emit changeDate(date, true);
- emit clicked(date);
- if (style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick))
- emit editingFinished();
- }
- validDateClicked = false;
- } else {
- event->ignore();
- }
-}
-
-class QCalendarDelegate : public QItemDelegate
-{
- Q_OBJECT
-public:
- QCalendarDelegate(QCalendarWidgetPrivate *w, QObject *parent = 0)
- : QItemDelegate(parent), calendarWidgetPrivate(w)
- { }
- virtual void paint(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
- void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
-
-private:
- QCalendarWidgetPrivate *calendarWidgetPrivate;
- mutable QStyleOptionViewItemV4 storedOption;
-};
-
-//Private tool button class
-class QCalToolButton: public QToolButton
-{
-public:
- QCalToolButton(QWidget * parent)
- : QToolButton(parent)
- { }
-protected:
- void paintEvent(QPaintEvent *e)
- {
- Q_UNUSED(e)
-
-#ifndef Q_WS_MAC
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
-
- if (opt.state & QStyle::State_MouseOver || isDown()) {
- //act as normal button
- setPalette(QPalette());
- } else {
- //set the highlight color for button text
- QPalette toolPalette = palette();
- toolPalette.setColor(QPalette::ButtonText, toolPalette.color(QPalette::HighlightedText));
- setPalette(toolPalette);
- }
-#endif
- QToolButton::paintEvent(e);
- }
-};
-
-class QPrevNextCalButton : public QToolButton
-{
- Q_OBJECT
-public:
- QPrevNextCalButton(QWidget *parent) : QToolButton(parent) {}
-protected:
- void paintEvent(QPaintEvent *) {
- QStylePainter painter(this);
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
- opt.state &= ~QStyle::State_HasFocus;
- painter.drawComplexControl(QStyle::CC_ToolButton, opt);
- }
-};
-
-class QCalendarWidgetPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QCalendarWidget)
-public:
- QCalendarWidgetPrivate();
-
- void showMonth(int year, int month);
- void update();
- void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
-
- void _q_slotShowDate(const QDate &date);
- void _q_slotChangeDate(const QDate &date);
- void _q_slotChangeDate(const QDate &date, bool changeMonth);
- void _q_editingFinished();
- void _q_monthChanged(QAction*);
- void _q_prevMonthClicked();
- void _q_nextMonthClicked();
- void _q_yearEditingFinished();
- void _q_yearClicked();
-
- void createNavigationBar(QWidget *widget);
- void updateButtonIcons();
- void updateMonthMenu();
- void updateMonthMenuNames();
- void updateNavigationBar();
- void updateCurrentPage(const QDate &newDate);
- inline QDate getCurrentDate();
- void setNavigatorEnabled(bool enable);
-
- QCalendarModel *m_model;
- QCalendarView *m_view;
- QCalendarDelegate *m_delegate;
- QItemSelectionModel *m_selection;
- QCalendarTextNavigator *m_navigator;
- bool m_dateEditEnabled;
-
- QToolButton *nextMonth;
- QToolButton *prevMonth;
- QCalToolButton *monthButton;
- QMenu *monthMenu;
- QMap<int, QAction *> monthToAction;
- QCalToolButton *yearButton;
- QSpinBox *yearEdit;
- QWidget *navBarBackground;
- QSpacerItem *spaceHolder;
-
- bool navBarVisible;
- mutable QSize cachedSizeHint;
- Qt::FocusPolicy oldFocusPolicy;
-};
-
-void QCalendarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- QDate date = calendarWidgetPrivate->m_model->dateForCell(index.row(), index.column());
- if (date.isValid()) {
- storedOption = option;
- QRect rect = option.rect;
- calendarWidgetPrivate->paintCell(painter, rect, date);
- } else {
- QItemDelegate::paint(painter, option, index);
- }
-}
-
-void QCalendarDelegate::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
-{
- storedOption.rect = rect;
- int row = -1;
- int col = -1;
- calendarWidgetPrivate->m_model->cellForDate(date, &row, &col);
- QModelIndex idx = calendarWidgetPrivate->m_model->index(row, col);
- QItemDelegate::paint(painter, storedOption, idx);
-}
-
-QCalendarWidgetPrivate::QCalendarWidgetPrivate()
- : QWidgetPrivate()
-{
- m_model = 0;
- m_view = 0;
- m_delegate = 0;
- m_selection = 0;
- m_navigator = 0;
- m_dateEditEnabled = false;
- navBarVisible = true;
- oldFocusPolicy = Qt::StrongFocus;
-}
-
-void QCalendarWidgetPrivate::setNavigatorEnabled(bool enable)
-{
- Q_Q(QCalendarWidget);
-
- bool navigatorEnabled = (m_navigator->widget() != 0);
- if (enable == navigatorEnabled)
- return;
-
- if (enable) {
- m_navigator->setWidget(q);
- q->connect(m_navigator, SIGNAL(dateChanged(QDate)),
- q, SLOT(_q_slotChangeDate(QDate)));
- q->connect(m_navigator, SIGNAL(editingFinished()),
- q, SLOT(_q_editingFinished()));
- m_view->installEventFilter(m_navigator);
- } else {
- m_navigator->setWidget(0);
- q->disconnect(m_navigator, SIGNAL(dateChanged(QDate)),
- q, SLOT(_q_slotChangeDate(QDate)));
- q->disconnect(m_navigator, SIGNAL(editingFinished()),
- q, SLOT(_q_editingFinished()));
- m_view->removeEventFilter(m_navigator);
- }
-}
-
-void QCalendarWidgetPrivate::createNavigationBar(QWidget *widget)
-{
- Q_Q(QCalendarWidget);
- navBarBackground = new QWidget(widget);
- navBarBackground->setObjectName(QLatin1String("qt_calendar_navigationbar"));
- navBarBackground->setAutoFillBackground(true);
- navBarBackground->setBackgroundRole(QPalette::Highlight);
-
- prevMonth = new QPrevNextCalButton(navBarBackground);
- nextMonth = new QPrevNextCalButton(navBarBackground);
- prevMonth->setAutoRaise(true);
- nextMonth->setAutoRaise(true);
- prevMonth->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
- nextMonth->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
- nextMonth->setAutoRaise(true);
- updateButtonIcons();
- prevMonth->setAutoRepeat(true);
- nextMonth->setAutoRepeat(true);
-
- monthButton = new QCalToolButton(navBarBackground);
- monthButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
- monthButton->setAutoRaise(true);
- monthButton->setPopupMode(QToolButton::InstantPopup);
- monthMenu = new QMenu(monthButton);
- for (int i = 1; i <= 12; i++) {
- QString monthName(q->locale().standaloneMonthName(i, QLocale::LongFormat));
- QAction *act = monthMenu->addAction(monthName);
- act->setData(i);
- monthToAction[i] = act;
- }
- monthButton->setMenu(monthMenu);
- yearButton = new QCalToolButton(navBarBackground);
- yearButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
- yearButton->setAutoRaise(true);
- yearEdit = new QSpinBox(navBarBackground);
-
- QFont font = q->font();
- font.setBold(true);
- monthButton->setFont(font);
- yearButton->setFont(font);
- yearEdit->setFrame(false);
- yearEdit->setMinimum(m_model->m_minimumDate.year());
- yearEdit->setMaximum(m_model->m_maximumDate.year());
- yearEdit->hide();
- spaceHolder = new QSpacerItem(0,0);
-
- QHBoxLayout *headerLayout = new QHBoxLayout;
- headerLayout->setMargin(0);
- headerLayout->setSpacing(0);
- headerLayout->addWidget(prevMonth);
- headerLayout->insertStretch(headerLayout->count());
- headerLayout->addWidget(monthButton);
- headerLayout->addItem(spaceHolder);
- headerLayout->addWidget(yearButton);
- headerLayout->insertStretch(headerLayout->count());
- headerLayout->addWidget(nextMonth);
- navBarBackground->setLayout(headerLayout);
-
- yearEdit->setFocusPolicy(Qt::StrongFocus);
- prevMonth->setFocusPolicy(Qt::NoFocus);
- nextMonth->setFocusPolicy(Qt::NoFocus);
- yearButton->setFocusPolicy(Qt::NoFocus);
- monthButton->setFocusPolicy(Qt::NoFocus);
-
- //set names for the header controls.
- prevMonth->setObjectName(QLatin1String("qt_calendar_prevmonth"));
- nextMonth->setObjectName(QLatin1String("qt_calendar_nextmonth"));
- monthButton->setObjectName(QLatin1String("qt_calendar_monthbutton"));
- yearButton->setObjectName(QLatin1String("qt_calendar_yearbutton"));
- yearEdit->setObjectName(QLatin1String("qt_calendar_yearedit"));
-
- updateMonthMenu();
- showMonth(m_model->m_date.year(), m_model->m_date.month());
-}
-
-void QCalendarWidgetPrivate::updateButtonIcons()
-{
- Q_Q(QCalendarWidget);
- prevMonth->setIcon(q->style()->standardIcon(q->isRightToLeft() ? QStyle::SP_ArrowRight : QStyle::SP_ArrowLeft, 0, q));
- nextMonth->setIcon(q->style()->standardIcon(q->isRightToLeft() ? QStyle::SP_ArrowLeft : QStyle::SP_ArrowRight, 0, q));
-}
-
-void QCalendarWidgetPrivate::updateMonthMenu()
-{
- int beg = 1, end = 12;
- bool prevEnabled = true;
- bool nextEnabled = true;
- if (m_model->m_shownYear == m_model->m_minimumDate.year()) {
- beg = m_model->m_minimumDate.month();
- if (m_model->m_shownMonth == m_model->m_minimumDate.month())
- prevEnabled = false;
- }
- if (m_model->m_shownYear == m_model->m_maximumDate.year()) {
- end = m_model->m_maximumDate.month();
- if (m_model->m_shownMonth == m_model->m_maximumDate.month())
- nextEnabled = false;
- }
- prevMonth->setEnabled(prevEnabled);
- nextMonth->setEnabled(nextEnabled);
- for (int i = 1; i <= 12; i++) {
- bool monthEnabled = true;
- if (i < beg || i > end)
- monthEnabled = false;
- monthToAction[i]->setEnabled(monthEnabled);
- }
-}
-
-void QCalendarWidgetPrivate::updateMonthMenuNames()
-{
- Q_Q(QCalendarWidget);
-
- for (int i = 1; i <= 12; i++) {
- QString monthName(q->locale().standaloneMonthName(i, QLocale::LongFormat));
- monthToAction[i]->setText(monthName);
- }
-}
-
-void QCalendarWidgetPrivate::updateCurrentPage(const QDate &date)
-{
- Q_Q(QCalendarWidget);
-
- QDate newDate = date;
- QDate minDate = q->minimumDate();
- QDate maxDate = q->maximumDate();
- if (minDate.isValid()&& minDate.daysTo(newDate) < 0)
- newDate = minDate;
- if (maxDate.isValid()&& maxDate.daysTo(newDate) > 0)
- newDate = maxDate;
- showMonth(newDate.year(), newDate.month());
- int row = -1, col = -1;
- m_model->cellForDate(newDate, &row, &col);
- if (row != -1 && col != -1)
- {
- m_view->selectionModel()->setCurrentIndex(m_model->index(row, col),
- QItemSelectionModel::NoUpdate);
- }
-}
-
-void QCalendarWidgetPrivate::_q_monthChanged(QAction *act)
-{
- monthButton->setText(act->text());
- QDate currentDate = getCurrentDate();
- QDate newDate = currentDate.addMonths(act->data().toInt()-currentDate.month());
- updateCurrentPage(newDate);
-}
-
-QDate QCalendarWidgetPrivate::getCurrentDate()
-{
- QModelIndex index = m_view->currentIndex();
- return m_model->dateForCell(index.row(), index.column());
-}
-
-void QCalendarWidgetPrivate::_q_prevMonthClicked()
-{
- QDate currentDate = getCurrentDate().addMonths(-1);
- updateCurrentPage(currentDate);
-}
-
-void QCalendarWidgetPrivate::_q_nextMonthClicked()
-{
- QDate currentDate = getCurrentDate().addMonths(1);
- updateCurrentPage(currentDate);
-}
-
-void QCalendarWidgetPrivate::_q_yearEditingFinished()
-{
- Q_Q(QCalendarWidget);
- yearButton->setText(yearEdit->text());
- yearEdit->hide();
- q->setFocusPolicy(oldFocusPolicy);
- qApp->removeEventFilter(q);
- spaceHolder->changeSize(0, 0);
- yearButton->show();
- QDate currentDate = getCurrentDate();
- currentDate = currentDate.addYears(yearEdit->text().toInt() - currentDate.year());
- updateCurrentPage(currentDate);
-}
-
-void QCalendarWidgetPrivate::_q_yearClicked()
-{
- Q_Q(QCalendarWidget);
- //show the spinbox on top of the button
- yearEdit->setGeometry(yearButton->x(), yearButton->y(),
- yearEdit->sizeHint().width(), yearButton->height());
- spaceHolder->changeSize(yearButton->width(), 0);
- yearButton->hide();
- oldFocusPolicy = q->focusPolicy();
- q->setFocusPolicy(Qt::NoFocus);
- yearEdit->show();
- qApp->installEventFilter(q);
- yearEdit->raise();
- yearEdit->selectAll();
- yearEdit->setFocus(Qt::MouseFocusReason);
-}
-
-void QCalendarWidgetPrivate::showMonth(int year, int month)
-{
- if (m_model->m_shownYear == year && m_model->m_shownMonth == month)
- return;
- Q_Q(QCalendarWidget);
- m_model->showMonth(year, month);
- updateNavigationBar();
- emit q->currentPageChanged(year, month);
- m_view->internalUpdate();
- cachedSizeHint = QSize();
- update();
- updateMonthMenu();
-}
-
-void QCalendarWidgetPrivate::updateNavigationBar()
-{
- Q_Q(QCalendarWidget);
-
- QString monthName = q->locale().standaloneMonthName(m_model->m_shownMonth, QLocale::LongFormat);
-
- monthButton->setText(monthName);
- yearButton->setText(QString::number(m_model->m_shownYear));
- yearEdit->setValue(m_model->m_shownYear);
-}
-
-void QCalendarWidgetPrivate::update()
-{
- QDate currentDate = m_model->m_date;
- int row, column;
- m_model->cellForDate(currentDate, &row, &column);
- QModelIndex idx;
- m_selection->clear();
- if (row != -1 && column != -1) {
- idx = m_model->index(row, column);
- m_selection->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent);
- }
-}
-
-void QCalendarWidgetPrivate::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
-{
- Q_Q(const QCalendarWidget);
- q->paintCell(painter, rect, date);
-}
-
-void QCalendarWidgetPrivate::_q_slotShowDate(const QDate &date)
-{
- updateCurrentPage(date);
-}
-
-void QCalendarWidgetPrivate::_q_slotChangeDate(const QDate &date)
-{
- _q_slotChangeDate(date, true);
-}
-
-void QCalendarWidgetPrivate::_q_slotChangeDate(const QDate &date, bool changeMonth)
-{
- QDate oldDate = m_model->m_date;
- m_model->setDate(date);
- QDate newDate = m_model->m_date;
- if (changeMonth)
- showMonth(newDate.year(), newDate.month());
- if (oldDate != newDate) {
- update();
- Q_Q(QCalendarWidget);
- m_navigator->setDate(newDate);
- emit q->selectionChanged();
- }
-}
-
-void QCalendarWidgetPrivate::_q_editingFinished()
-{
- Q_Q(QCalendarWidget);
- emit q->activated(m_model->m_date);
-}
-
-/*!
- \class QCalendarWidget
- \brief The QCalendarWidget class provides a monthly based
- calendar widget allowing the user to select a date.
- \since 4.2
-
- \ingroup advanced
-
- \image cleanlooks-calendarwidget.png
-
- The widget is initialized with the current month and year, but
- QCalendarWidget provides several public slots to change the year
- and month that is shown.
-
- By default, today's date is selected, and the user can select a
- date using both mouse and keyboard. The currently selected date
- can be retrieved using the selectedDate() function. It is
- possible to constrain the user selection to a given date range by
- setting the minimumDate and maximumDate properties.
- Alternatively, both properties can be set in one go using the
- setDateRange() convenience slot. Set the \l selectionMode
- property to NoSelection to prohibit the user from selecting at
- all. Note that a date also can be selected programmatically using
- the setSelectedDate() slot.
-
- The currently displayed month and year can be retrieved using the
- monthShown() and yearShown() functions, respectively.
-
- A newly created calendar widget uses abbreviated day names, and
- both Saturdays and Sundays are marked in red. The calendar grid is
- not visible. The week numbers are displayed, and the first column
- day is Sunday.
-
- The notation of the days can be altered to a single letter
- abbreviations ("M" for "Monday") by setting the
- horizontalHeaderFormat property to
- QCalendarWidget::SingleLetterDayNames. Setting the same property
- to QCalendarWidget::LongDayNames makes the header display the
- complete day names. The week numbers can be removed by setting
- the verticalHeaderFormat property to
- QCalendarWidget::NoVerticalHeader. The calendar grid can be
- turned on by setting the gridVisible property to true using the
- setGridVisible() function:
-
- \table
- \row \o
- \image qcalendarwidget-grid.png
- \row \o
- \snippet doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp 0
- \endtable
-
- Finally, the day in the first column can be altered using the
- setFirstDayOfWeek() function.
-
- The QCalendarWidget class also provides three signals,
- selectionChanged(), activated() and currentPageChanged() making it
- possible to respond to user interaction.
-
- The rendering of the headers, weekdays or single days can be
- largely customized by setting QTextCharFormat's for some special
- weekday, a special date or for the rendering of the headers.
-
- Only a subset of the properties in QTextCharFormat are used by the
- calendar widget. Currently, the foreground, background and font
- properties are used to determine the rendering of individual cells
- in the widget.
-
- \sa QDate, QDateEdit, QTextCharFormat
-*/
-
-/*!
- \enum QCalendarWidget::SelectionMode
-
- This enum describes the types of selection offered to the user for
- selecting dates in the calendar.
-
- \value NoSelection Dates cannot be selected.
- \value SingleSelection Single dates can be selected.
-
- \sa selectionMode
-*/
-
-/*!
- Constructs a calendar widget with the given \a parent.
-
- The widget is initialized with the current month and year, and the
- currently selected date is today.
-
- \sa setCurrentPage()
-*/
-QCalendarWidget::QCalendarWidget(QWidget *parent)
- : QWidget(*new QCalendarWidgetPrivate, parent, 0)
-{
- Q_D(QCalendarWidget);
-
- setAutoFillBackground(true);
- setBackgroundRole(QPalette::Window);
-
- QVBoxLayout *layoutV = new QVBoxLayout(this);
- layoutV->setMargin(0);
- d->m_model = new QCalendarModel(this);
- QTextCharFormat fmt;
- fmt.setForeground(QBrush(Qt::red));
- d->m_model->m_dayFormats.insert(Qt::Saturday, fmt);
- d->m_model->m_dayFormats.insert(Qt::Sunday, fmt);
- d->m_view = new QCalendarView(this);
- d->m_view->setObjectName(QLatin1String("qt_calendar_calendarview"));
- d->m_view->setModel(d->m_model);
- d->m_model->setView(d->m_view);
- d->m_view->setSelectionBehavior(QAbstractItemView::SelectItems);
- d->m_view->setSelectionMode(QAbstractItemView::SingleSelection);
- d->m_view->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
- d->m_view->horizontalHeader()->setClickable(false);
- d->m_view->verticalHeader()->setResizeMode(QHeaderView::Stretch);
- d->m_view->verticalHeader()->setClickable(false);
- d->m_selection = d->m_view->selectionModel();
- d->createNavigationBar(this);
- d->m_view->setFrameStyle(QFrame::NoFrame);
- d->m_delegate = new QCalendarDelegate(d, this);
- d->m_view->setItemDelegate(d->m_delegate);
- d->update();
- d->updateNavigationBar();
- setFocusPolicy(Qt::StrongFocus);
- setFocusProxy(d->m_view);
- setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
-
- connect(d->m_view, SIGNAL(showDate(QDate)),
- this, SLOT(_q_slotShowDate(QDate)));
- connect(d->m_view, SIGNAL(changeDate(QDate,bool)),
- this, SLOT(_q_slotChangeDate(QDate,bool)));
- connect(d->m_view, SIGNAL(clicked(QDate)),
- this, SIGNAL(clicked(QDate)));
- connect(d->m_view, SIGNAL(editingFinished()),
- this, SLOT(_q_editingFinished()));
-
- connect(d->prevMonth, SIGNAL(clicked(bool)),
- this, SLOT(_q_prevMonthClicked()));
- connect(d->nextMonth, SIGNAL(clicked(bool)),
- this, SLOT(_q_nextMonthClicked()));
- connect(d->yearButton, SIGNAL(clicked(bool)),
- this, SLOT(_q_yearClicked()));
- connect(d->monthMenu, SIGNAL(triggered(QAction*)),
- this, SLOT(_q_monthChanged(QAction*)));
- connect(d->yearEdit, SIGNAL(editingFinished()),
- this, SLOT(_q_yearEditingFinished()));
-
- layoutV->setMargin(0);
- layoutV->setSpacing(0);
- layoutV->addWidget(d->navBarBackground);
- layoutV->addWidget(d->m_view);
-
- d->m_navigator = new QCalendarTextNavigator(this);
- setDateEditEnabled(true);
-}
-
-/*!
- Destroys the calendar widget.
-*/
-QCalendarWidget::~QCalendarWidget()
-{
-}
-
-/*!
- \reimp
-*/
-QSize QCalendarWidget::sizeHint() const
-{
- return minimumSizeHint();
-}
-
-/*!
- \reimp
-*/
-QSize QCalendarWidget::minimumSizeHint() const
-{
- Q_D(const QCalendarWidget);
- if (d->cachedSizeHint.isValid())
- return d->cachedSizeHint;
-
- ensurePolished();
-
- int w = 0;
- int h = 0;
-
- int end = 53;
- int rows = 7;
- int cols = 8;
-
- const int marginH = (style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1) * 2;
-
- if (horizontalHeaderFormat() == QCalendarWidget::NoHorizontalHeader) {
- rows = 6;
- } else {
- for (int i = 1; i <= 7; i++) {
- QFontMetrics fm(d->m_model->formatForCell(0, i).font());
- w = qMax(w, fm.width(d->m_model->dayName(d->m_model->dayOfWeekForColumn(i))) + marginH);
- h = qMax(h, fm.height());
- }
- }
-
- if (verticalHeaderFormat() == QCalendarWidget::NoVerticalHeader) {
- cols = 7;
- } else {
- for (int i = 1; i <= 6; i++) {
- QFontMetrics fm(d->m_model->formatForCell(i, 0).font());
- for (int j = 1; j < end; j++)
- w = qMax(w, fm.width(QString::number(j)) + marginH);
- h = qMax(h, fm.height());
- }
- }
-
- QFontMetrics fm(d->m_model->formatForCell(1, 1).font());
- for (int i = 1; i <= end; i++) {
- w = qMax(w, fm.width(QString::number(i)) + marginH);
- h = qMax(h, fm.height());
- }
-
- if (d->m_view->showGrid()) {
- // hardcoded in tableview
- w += 1;
- h += 1;
- }
-
- w += 1; // default column span
-
- h = qMax(h, d->m_view->verticalHeader()->minimumSectionSize());
- w = qMax(w, d->m_view->horizontalHeader()->minimumSectionSize());
-
- //add the size of the header.
- QSize headerSize(0, 0);
- if (d->navBarVisible) {
- int headerH = d->navBarBackground->sizeHint().height();
- int headerW = 0;
-
- headerW += d->prevMonth->sizeHint().width();
- headerW += d->nextMonth->sizeHint().width();
-
- QFontMetrics fm = d->monthButton->fontMetrics();
- int monthW = 0;
- for (int i = 1; i < 12; i++) {
- QString monthName = locale().standaloneMonthName(i, QLocale::LongFormat);
- monthW = qMax(monthW, fm.boundingRect(monthName).width());
- }
- const int buttonDecoMargin = d->monthButton->sizeHint().width() - fm.boundingRect(d->monthButton->text()).width();
- headerW += monthW + buttonDecoMargin;
-
- fm = d->yearButton->fontMetrics();
- headerW += fm.boundingRect(QLatin1String("5555")).width() + buttonDecoMargin;
-
- headerSize = QSize(headerW, headerH);
- }
- w *= cols;
- w = qMax(headerSize.width(), w);
- h = (h * rows) + headerSize.height();
- d->cachedSizeHint = QSize(w, h);
- return d->cachedSizeHint;
-}
-
-/*!
- Paints the cell specified by the given \a date, using the given \a painter and \a rect.
-*/
-
-void QCalendarWidget::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
-{
- Q_D(const QCalendarWidget);
- d->m_delegate->paintCell(painter, rect, date);
-}
-
-/*!
- \property QCalendarWidget::selectedDate
- \brief the currently selected date.
-
- The selected date must be within the date range specified by the
- minimumDate and maximumDate properties. By default, the selected
- date is the current date.
-
- \sa setDateRange()
-*/
-
-QDate QCalendarWidget::selectedDate() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_date;
-}
-
-void QCalendarWidget::setSelectedDate(const QDate &date)
-{
- Q_D(QCalendarWidget);
- if (d->m_model->m_date == date && date == d->getCurrentDate())
- return;
-
- if (!date.isValid())
- return;
-
- d->m_model->setDate(date);
- d->update();
- QDate newDate = d->m_model->m_date;
- d->showMonth(newDate.year(), newDate.month());
- emit selectionChanged();
-}
-
-/*!
- Returns the year of the currently displayed month. Months are
- numbered from 1 to 12.
-
- \sa monthShown(), setCurrentPage()
-*/
-
-int QCalendarWidget::yearShown() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_shownYear;
-}
-
-/*!
- Returns the currently displayed month. Months are numbered from 1 to
- 12.
-
- \sa yearShown(), setCurrentPage()
-*/
-
-int QCalendarWidget::monthShown() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_shownMonth;
-}
-
-/*!
- Displays the given \a month of the given \a year without changing
- the selected date. Use the setSelectedDate() function to alter the
- selected date.
-
- The currently displayed month and year can be retrieved using the
- monthShown() and yearShown() functions respectively.
-
- \sa yearShown(), monthShown(), showPreviousMonth(), showNextMonth(),
- showPreviousYear(), showNextYear()
-*/
-
-void QCalendarWidget::setCurrentPage(int year, int month)
-{
- Q_D(QCalendarWidget);
- QDate currentDate = d->getCurrentDate();
- int day = currentDate.day();
- int daysInMonths = QDate(year, month, 1).daysInMonth();
- if (day > daysInMonths)
- day = daysInMonths;
-
- d->showMonth(year, month);
-
- QDate newDate(year, month, day);
- int row = -1, col = -1;
- d->m_model->cellForDate(newDate, &row, &col);
- if (row != -1 && col != -1) {
- d->m_view->selectionModel()->setCurrentIndex(d->m_model->index(row, col),
- QItemSelectionModel::NoUpdate);
- }
-}
-
-/*!
- Shows the next month relative to the currently displayed
- month. Note that the selected date is not changed.
-
- \sa showPreviousMonth(), setCurrentPage(), setSelectedDate()
-*/
-
-void QCalendarWidget::showNextMonth()
-{
- int year = yearShown();
- int month = monthShown();
- if (month == 12) {
- ++year;
- month = 1;
- } else {
- ++month;
- }
- setCurrentPage(year, month);
-}
-
-/*!
- Shows the previous month relative to the currently displayed
- month. Note that the selected date is not changed.
-
- \sa showNextMonth(), setCurrentPage(), setSelectedDate()
-*/
-
-void QCalendarWidget::showPreviousMonth()
-{
- int year = yearShown();
- int month = monthShown();
- if (month == 1) {
- --year;
- month = 12;
- } else {
- --month;
- }
- setCurrentPage(year, month);
-}
-
-/*!
- Shows the currently displayed month in the \e next year relative
- to the currently displayed year. Note that the selected date is
- not changed.
-
- \sa showPreviousYear(), setCurrentPage(), setSelectedDate()
-*/
-
-void QCalendarWidget::showNextYear()
-{
- int year = yearShown();
- int month = monthShown();
- ++year;
- setCurrentPage(year, month);
-}
-
-/*!
- Shows the currently displayed month in the \e previous year
- relative to the currently displayed year. Note that the selected
- date is not changed.
-
- \sa showNextYear(), setCurrentPage(), setSelectedDate()
-*/
-
-void QCalendarWidget::showPreviousYear()
-{
- int year = yearShown();
- int month = monthShown();
- --year;
- setCurrentPage(year, month);
-}
-
-/*!
- Shows the month of the selected date.
-
- \sa selectedDate(), setCurrentPage()
-*/
-void QCalendarWidget::showSelectedDate()
-{
- QDate currentDate = selectedDate();
- setCurrentPage(currentDate.year(), currentDate.month());
-}
-
-/*!
- Shows the month of the today's date.
-
- \sa selectedDate(), setCurrentPage()
-*/
-void QCalendarWidget::showToday()
-{
- QDate currentDate = QDate::currentDate();
- setCurrentPage(currentDate.year(), currentDate.month());
-}
-
-/*!
- \property QCalendarWidget::minimumDate
- \brief the minimum date of the currently specified date range.
-
- The user will not be able to select a date that is before the
- currently set minimum date.
-
- \table
- \row
- \o \image qcalendarwidget-minimum.png
- \row
- \o
- \snippet doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp 1
- \endtable
-
- By default, the minimum date is the earliest date that the QDate
- class can handle.
-
- When setting a minimum date, the maximumDate and selectedDate
- properties are adjusted if the selection range becomes invalid. If
- the provided date is not a valid QDate object, the
- setMinimumDate() function does nothing.
-
- \sa setDateRange()
-*/
-
-QDate QCalendarWidget::minimumDate() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_minimumDate;
-}
-
-void QCalendarWidget::setMinimumDate(const QDate &date)
-{
- Q_D(QCalendarWidget);
- if (!date.isValid() || d->m_model->m_minimumDate == date)
- return;
-
- QDate oldDate = d->m_model->m_date;
- d->m_model->setMinimumDate(date);
- d->yearEdit->setMinimum(d->m_model->m_minimumDate.year());
- d->updateMonthMenu();
- QDate newDate = d->m_model->m_date;
- if (oldDate != newDate) {
- d->update();
- d->showMonth(newDate.year(), newDate.month());
- d->m_navigator->setDate(newDate);
- emit selectionChanged();
- }
-}
-
-/*!
- \property QCalendarWidget::maximumDate
- \brief the maximum date of the currently specified date range.
-
- The user will not be able to select a date which is after the
- currently set maximum date.
-
- \table
- \row
- \o \image qcalendarwidget-maximum.png
- \row
- \o
- \snippet doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp 2
- \endtable
-
- By default, the maximum date is the last day the QDate class can
- handle.
-
- When setting a maximum date, the minimumDate and selectedDate
- properties are adjusted if the selection range becomes invalid. If
- the provided date is not a valid QDate object, the
- setMaximumDate() function does nothing.
-
- \sa setDateRange()
-*/
-
-QDate QCalendarWidget::maximumDate() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_maximumDate;
-}
-
-void QCalendarWidget::setMaximumDate(const QDate &date)
-{
- Q_D(QCalendarWidget);
- if (!date.isValid() || d->m_model->m_maximumDate == date)
- return;
-
- QDate oldDate = d->m_model->m_date;
- d->m_model->setMaximumDate(date);
- d->yearEdit->setMaximum(d->m_model->m_maximumDate.year());
- d->updateMonthMenu();
- QDate newDate = d->m_model->m_date;
- if (oldDate != newDate) {
- d->update();
- d->showMonth(newDate.year(), newDate.month());
- d->m_navigator->setDate(newDate);
- emit selectionChanged();
- }
-}
-
-/*!
- Defines a date range by setting the minimumDate and maximumDate
- properties.
-
- The date range restricts the user selection, i.e. the user can
- only select dates within the specified date range. Note that
-
- \snippet doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp 3
-
- is analogous to
-
- \snippet doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp 4
-
- If either the \a min or \a max parameters are not valid QDate
- objects, this function does nothing.
-
- \sa setMinimumDate(), setMaximumDate()
-*/
-
-void QCalendarWidget::setDateRange(const QDate &min, const QDate &max)
-{
- Q_D(QCalendarWidget);
- if (d->m_model->m_minimumDate == min && d->m_model->m_maximumDate == max)
- return;
- if (!min.isValid() || !max.isValid())
- return;
-
- QDate oldDate = d->m_model->m_date;
- d->m_model->setRange(min, max);
- d->yearEdit->setMinimum(d->m_model->m_minimumDate.year());
- d->yearEdit->setMaximum(d->m_model->m_maximumDate.year());
- d->updateMonthMenu();
- QDate newDate = d->m_model->m_date;
- if (oldDate != newDate) {
- d->update();
- d->showMonth(newDate.year(), newDate.month());
- d->m_navigator->setDate(newDate);
- emit selectionChanged();
- }
-}
-
-
-/*! \enum QCalendarWidget::HorizontalHeaderFormat
-
- This enum type defines the various formats the horizontal header can display.
-
- \value SingleLetterDayNames The header displays a single letter abbreviation for day names (e.g. M for Monday).
- \value ShortDayNames The header displays a short abbreviation for day names (e.g. Mon for Monday).
- \value LongDayNames The header displays complete day names (e.g. Monday).
- \value NoHorizontalHeader The header is hidden.
-
- \sa horizontalHeaderFormat(), VerticalHeaderFormat
-*/
-
-/*!
- \property QCalendarWidget::horizontalHeaderFormat
- \brief the format of the horizontal header.
-
- The default value is QCalendarWidget::ShortDayNames.
-*/
-
-void QCalendarWidget::setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat format)
-{
- Q_D(QCalendarWidget);
- if (d->m_model->m_horizontalHeaderFormat == format)
- return;
-
- d->m_model->setHorizontalHeaderFormat(format);
- d->cachedSizeHint = QSize();
- d->m_view->viewport()->update();
- d->m_view->updateGeometry();
-}
-
-QCalendarWidget::HorizontalHeaderFormat QCalendarWidget::horizontalHeaderFormat() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_horizontalHeaderFormat;
-}
-
-
-/*!
- \enum QCalendarWidget::VerticalHeaderFormat
-
- This enum type defines the various formats the vertical header can display.
-
- \value ISOWeekNumbers The header displays ISO week numbers as described by \l QDate::weekNumber().
- \value NoVerticalHeader The header is hidden.
-
- \sa verticalHeaderFormat(), HorizontalHeaderFormat
-*/
-
-/*!
- \property QCalendarWidget::verticalHeaderFormat
- \brief the format of the vertical header.
-
- The default value is QCalendarWidget::ISOWeekNumber.
-*/
-
-QCalendarWidget::VerticalHeaderFormat QCalendarWidget::verticalHeaderFormat() const
-{
- Q_D(const QCalendarWidget);
- bool shown = d->m_model->weekNumbersShown();
- if (shown)
- return QCalendarWidget::ISOWeekNumbers;
- return QCalendarWidget::NoVerticalHeader;
-}
-
-void QCalendarWidget::setVerticalHeaderFormat(QCalendarWidget::VerticalHeaderFormat format)
-{
- Q_D(QCalendarWidget);
- bool show = false;
- if (format == QCalendarWidget::ISOWeekNumbers)
- show = true;
- if (d->m_model->weekNumbersShown() == show)
- return;
- d->m_model->setWeekNumbersShown(show);
- d->cachedSizeHint = QSize();
- d->m_view->viewport()->update();
- d->m_view->updateGeometry();
-}
-
-/*!
- \property QCalendarWidget::gridVisible
- \brief whether the table grid is displayed.
-
- \table
- \row
- \o \inlineimage qcalendarwidget-grid.png
- \row
- \o
- \snippet doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp 5
- \endtable
-
- The default value is false.
-*/
-
-bool QCalendarWidget::isGridVisible() const
-{
- Q_D(const QCalendarWidget);
- return d->m_view->showGrid();
-}
-
-void QCalendarWidget::setGridVisible(bool show)
-{
- Q_D(QCalendarWidget);
- d->m_view->setShowGrid(show);
- d->cachedSizeHint = QSize();
- d->m_view->viewport()->update();
- d->m_view->updateGeometry();
-}
-
-/*!
- \property QCalendarWidget::selectionMode
- \brief the type of selection the user can make in the calendar
-
- When this property is set to SingleSelection, the user can select a date
- within the minimum and maximum allowed dates, using either the mouse or
- the keyboard.
-
- When the property is set to NoSelection, the user will be unable to select
- dates, but they can still be selected programmatically. Note that the date
- that is selected when the property is set to NoSelection will still be
- the selected date of the calendar.
-
- The default value is SingleSelection.
-*/
-
-QCalendarWidget::SelectionMode QCalendarWidget::selectionMode() const
-{
- Q_D(const QCalendarWidget);
- return d->m_view->readOnly ? QCalendarWidget::NoSelection : QCalendarWidget::SingleSelection;
-}
-
-void QCalendarWidget::setSelectionMode(SelectionMode mode)
-{
- Q_D(QCalendarWidget);
- d->m_view->readOnly = (mode == QCalendarWidget::NoSelection);
- d->setNavigatorEnabled(isDateEditEnabled() && (selectionMode() != QCalendarWidget::NoSelection));
- d->update();
-}
-
-/*!
- \property QCalendarWidget::firstDayOfWeek
- \brief a value identifying the day displayed in the first column.
-
- By default, the day displayed in the first column is Sunday
-*/
-
-void QCalendarWidget::setFirstDayOfWeek(Qt::DayOfWeek dayOfWeek)
-{
- Q_D(QCalendarWidget);
- if ((Qt::DayOfWeek)d->m_model->firstColumnDay() == dayOfWeek)
- return;
-
- d->m_model->setFirstColumnDay(dayOfWeek);
- d->update();
-}
-
-Qt::DayOfWeek QCalendarWidget::firstDayOfWeek() const
-{
- Q_D(const QCalendarWidget);
- return (Qt::DayOfWeek)d->m_model->firstColumnDay();
-}
-
-/*!
- Returns the text char format for rendering the header.
-*/
-QTextCharFormat QCalendarWidget::headerTextFormat() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_headerFormat;
-}
-
-/*!
- Sets the text char format for rendering the header to \a format.
- If you also set a weekday text format, this format's foreground and
- background color will take precedence over the header's format.
- The other formatting information will still be decided by
- the header's format.
-*/
-void QCalendarWidget::setHeaderTextFormat(const QTextCharFormat &format)
-{
- Q_D(QCalendarWidget);
- d->m_model->m_headerFormat = format;
- d->cachedSizeHint = QSize();
- d->m_view->viewport()->update();
- d->m_view->updateGeometry();
-}
-
-/*!
- Returns the text char format for rendering of day in the week \a dayOfWeek.
-
- \sa headerTextFormat()
-*/
-QTextCharFormat QCalendarWidget::weekdayTextFormat(Qt::DayOfWeek dayOfWeek) const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_dayFormats.value(dayOfWeek);
-}
-
-/*!
- Sets the text char format for rendering of day in the week \a dayOfWeek to \a format.
- The format will take precedence over the header format in case of foreground
- and background color. Other text formatting information is taken from the headers format.
-
- \sa setHeaderTextFormat()
-*/
-void QCalendarWidget::setWeekdayTextFormat(Qt::DayOfWeek dayOfWeek, const QTextCharFormat &format)
-{
- Q_D(QCalendarWidget);
- d->m_model->m_dayFormats[dayOfWeek] = format;
- d->cachedSizeHint = QSize();
- d->m_view->viewport()->update();
- d->m_view->updateGeometry();
-}
-
-/*!
- Returns a QMap from QDate to QTextCharFormat showing all dates
- that use a special format that alters their rendering.
-*/
-QMap<QDate, QTextCharFormat> QCalendarWidget::dateTextFormat() const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_dateFormats;
-}
-
-/*!
- Returns a QTextCharFormat for \a date. The char format can be be
- empty if the date is not renderd specially.
-*/
-QTextCharFormat QCalendarWidget::dateTextFormat(const QDate &date) const
-{
- Q_D(const QCalendarWidget);
- return d->m_model->m_dateFormats.value(date);
-}
-
-/*!
- Sets the format used to render the given \a date to that specified by \a format.
-
- If \a date is null, all date formats are cleared.
-*/
-void QCalendarWidget::setDateTextFormat(const QDate &date, const QTextCharFormat &format)
-{
- Q_D(QCalendarWidget);
- if (date.isNull())
- d->m_model->m_dateFormats.clear();
- else
- d->m_model->m_dateFormats[date] = format;
- d->m_view->viewport()->update();
- d->m_view->updateGeometry();
-}
-
-/*!
- \property QCalendarWidget::dateEditEnabled
- \brief whether the date edit popup is enabled
- \since 4.3
-
- If this property is enabled, pressing a non-modifier key will cause a
- date edit to popup if the calendar widget has focus, allowing the user
- to specify a date in the form specified by the current locale.
-
- By default, this property is enabled.
-
- The date edit is simpler in appearance than QDateEdit, but allows the
- user to navigate between fields using the left and right cursor keys,
- increment and decrement individual fields using the up and down cursor
- keys, and enter values directly using the number keys.
-
- \sa QCalendarWidget::dateEditAcceptDelay
-*/
-bool QCalendarWidget::isDateEditEnabled() const
-{
- Q_D(const QCalendarWidget);
- return d->m_dateEditEnabled;
-}
-
-void QCalendarWidget::setDateEditEnabled(bool enable)
-{
- Q_D(QCalendarWidget);
- if (isDateEditEnabled() == enable)
- return;
-
- d->m_dateEditEnabled = enable;
-
- d->setNavigatorEnabled(enable && (selectionMode() != QCalendarWidget::NoSelection));
-}
-
-/*!
- \property QCalendarWidget::dateEditAcceptDelay
- \brief the time an inactive date edit is shown before its contents are accepted
- \since 4.3
-
- If the calendar widget's \l{dateEditEnabled}{date edit is enabled}, this
- property specifies the amount of time (in millseconds) that the date edit
- remains open after the most recent user input. Once this time has elapsed,
- the date specified in the date edit is accepted and the popup is closed.
-
- By default, the delay is defined to be 1500 milliseconds (1.5 seconds).
-*/
-int QCalendarWidget::dateEditAcceptDelay() const
-{
- Q_D(const QCalendarWidget);
- return d->m_navigator->dateEditAcceptDelay();
-}
-
-void QCalendarWidget::setDateEditAcceptDelay(int delay)
-{
- Q_D(QCalendarWidget);
- d->m_navigator->setDateEditAcceptDelay(delay);
-}
-
-/*!
- \since 4.4
-
- Updates the cell specified by the given \a date unless updates
- are disabled or the cell is hidden.
-
- \sa updateCells(), yearShown(), monthShown()
-*/
-void QCalendarWidget::updateCell(const QDate &date)
-{
- if (!date.isValid()) {
- qWarning("QCalendarWidget::updateCell: Invalid date");
- return;
- }
-
- if (!isVisible())
- return;
-
- Q_D(QCalendarWidget);
- int row, column;
- d->m_model->cellForDate(date, &row, &column);
- if (row == -1 || column == -1)
- return;
-
- QModelIndex modelIndex = d->m_model->index(row, column);
- if (!modelIndex.isValid())
- return;
-
- d->m_view->viewport()->update(d->m_view->visualRect(modelIndex));
-}
-
-/*!
- \since 4.4
-
- Updates all visible cells unless updates are disabled.
-
- \sa updateCell()
-*/
-void QCalendarWidget::updateCells()
-{
- Q_D(QCalendarWidget);
- if (isVisible())
- d->m_view->viewport()->update();
-}
-
-/*!
- \fn void QCalendarWidget::selectionChanged()
-
- This signal is emitted when the currently selected date is
- changed.
-
- The currently selected date can be changed by the user using the
- mouse or keyboard, or by the programmer using setSelectedDate().
-
- \sa selectedDate()
-*/
-
-/*!
- \fn void QCalendarWidget::currentPageChanged(int year, int month)
-
- This signal is emitted when the currently shown month is changed.
- The new \a year and \a month are passed as parameters.
-
- \sa setCurrentPage()
-*/
-
-/*!
- \fn void QCalendarWidget::activated(const QDate &date)
-
- This signal is emitted whenever the user presses the Return or
- Enter key or double-clicks a \a date in the calendar
- widget.
-*/
-
-/*!
- \fn void QCalendarWidget::clicked(const QDate &date)
-
- This signal is emitted when a mouse button is clicked. The date
- the mouse was clicked on is specified by \a date. The signal is
- only emitted when clicked on a valid date, e.g., dates are not
- outside the minimumDate() and maximumDate(). If the selection mode
- is NoSelection, this signal will not be emitted.
-
-*/
-
-/*!
- \property QCalendarWidget::headerVisible
- \brief whether the navigation bar is shown or not
-
- \obsolete
-
- Use navigationBarVisible() instead.
-
- By default, this property is true.
-*/
-
-/*!
- \obsolete
-
- Use setNavigationBarVisible() instead.
-*/
-bool QCalendarWidget::isHeaderVisible() const
-{
- Q_D(const QCalendarWidget);
- return d->navBarVisible;
-}
-
-/*!
- \obsolete
-
- Use setNavigationBarVisible() instead.
-
-*/
-void QCalendarWidget::setHeaderVisible(bool visible)
-{
- setNavigationBarVisible(visible);
-}
-
-/*!
- \property QCalendarWidget::navigationBarVisible
- \brief whether the navigation bar is shown or not
-
- \since 4.3
-
- When this property is true (the default), the next month,
- previous month, month selection, year selection controls are
- shown on top.
-
- When the property is set to false, these controls are hidden.
-*/
-
-void QCalendarWidget::setNavigationBarVisible(bool visible)
-{
- Q_D(QCalendarWidget);
- d->navBarVisible = visible;
- d->cachedSizeHint = QSize();
- d->navBarBackground->setVisible(visible);
- updateGeometry();
-}
-
-/*!
- \reimp
-*/
-bool QCalendarWidget::event(QEvent *event)
-{
- Q_D(QCalendarWidget);
- switch (event->type()) {
- case QEvent::LayoutDirectionChange:
- d->updateButtonIcons();
- case QEvent::LocaleChange:
- d->cachedSizeHint = QSize();
- d->updateMonthMenuNames();
- d->updateNavigationBar();
- d->m_view->updateGeometry();
- break;
- case QEvent::FontChange:
- case QEvent::ApplicationFontChange:
- d->cachedSizeHint = QSize();
- d->m_view->updateGeometry();
- break;
- case QEvent::StyleChange:
- d->cachedSizeHint = QSize();
- d->m_view->updateGeometry();
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-bool QCalendarWidget::eventFilter(QObject *watched, QEvent *event)
-{
- Q_D(QCalendarWidget);
- if (event->type() == QEvent::MouseButtonPress && d->yearEdit->hasFocus()) {
- QWidget *tlw = window();
- QWidget *widget = static_cast<QWidget*>(watched);
- //as we have a event filter on the whole application we first make sure that the top level widget
- //of both this and the watched widget are the same to decide if we should finish the year edition.
- if (widget->window() == tlw) {
- QPoint mousePos = widget->mapTo(tlw, static_cast<QMouseEvent *>(event)->pos());
- QRect geom = QRect(d->yearEdit->mapTo(tlw, QPoint(0, 0)), d->yearEdit->size());
- if (!geom.contains(mousePos)) {
- event->accept();
- d->_q_yearEditingFinished();
- setFocus();
- return true;
- }
- }
- }
- return QWidget::eventFilter(watched, event);
-}
-
-/*!
- \reimp
-*/
-void QCalendarWidget::mousePressEvent(QMouseEvent *event)
-{
- setAttribute(Qt::WA_NoMouseReplay);
- QWidget::mousePressEvent(event);
- setFocus();
-}
-
-/*!
- \reimp
-*/
-void QCalendarWidget::resizeEvent(QResizeEvent * event)
-{
- Q_D(QCalendarWidget);
-
- // XXX Should really use a QWidgetStack for yearEdit and yearButton,
- // XXX here we hide the year edit when the layout is likely to break
- // XXX the manual positioning of the yearEdit over the yearButton.
- if(d->yearEdit->isVisible() && event->size().width() != event->oldSize().width())
- d->_q_yearEditingFinished();
-
- QWidget::resizeEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QCalendarWidget::keyPressEvent(QKeyEvent * event)
-{
- Q_D(QCalendarWidget);
- if(d->yearEdit->isVisible()&& event->key() == Qt::Key_Escape)
- {
- d->yearEdit->setValue(yearShown());
- d->_q_yearEditingFinished();
- return;
- }
- QWidget::keyPressEvent(event);
-}
-
-QT_END_NAMESPACE
-
-#include "qcalendarwidget.moc"
-#include "moc_qcalendarwidget.cpp"
-
-#endif //QT_NO_CALENDARWIDGET
diff --git a/src/gui/widgets/qcalendarwidget.h b/src/gui/widgets/qcalendarwidget.h
deleted file mode 100644
index 08d2ca0a21..0000000000
--- a/src/gui/widgets/qcalendarwidget.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** 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 QCALENDARWIDGET_H
-#define QCALENDARWIDGET_H
-
-#include <QtGui/qwidget.h>
-#include <QtCore/qdatetime.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_CALENDARWIDGET
-
-class QDate;
-class QTextCharFormat;
-class QCalendarWidgetPrivate;
-
-class Q_GUI_EXPORT QCalendarWidget : public QWidget
-{
- Q_OBJECT
- Q_ENUMS(Qt::DayOfWeek)
- Q_ENUMS(HorizontalHeaderFormat)
- Q_ENUMS(VerticalHeaderFormat)
- Q_ENUMS(SelectionMode)
- Q_PROPERTY(QDate selectedDate READ selectedDate WRITE setSelectedDate)
- Q_PROPERTY(QDate minimumDate READ minimumDate WRITE setMinimumDate)
- Q_PROPERTY(QDate maximumDate READ maximumDate WRITE setMaximumDate)
- Q_PROPERTY(Qt::DayOfWeek firstDayOfWeek READ firstDayOfWeek WRITE setFirstDayOfWeek)
- Q_PROPERTY(bool gridVisible READ isGridVisible WRITE setGridVisible)
- Q_PROPERTY(SelectionMode selectionMode READ selectionMode WRITE setSelectionMode)
- Q_PROPERTY(HorizontalHeaderFormat horizontalHeaderFormat READ horizontalHeaderFormat WRITE setHorizontalHeaderFormat)
- Q_PROPERTY(VerticalHeaderFormat verticalHeaderFormat READ verticalHeaderFormat WRITE setVerticalHeaderFormat)
- Q_PROPERTY(bool headerVisible READ isHeaderVisible WRITE setHeaderVisible STORED false DESIGNABLE false) // obsolete
- Q_PROPERTY(bool navigationBarVisible READ isNavigationBarVisible WRITE setNavigationBarVisible)
- Q_PROPERTY(bool dateEditEnabled READ isDateEditEnabled WRITE setDateEditEnabled)
- Q_PROPERTY(int dateEditAcceptDelay READ dateEditAcceptDelay WRITE setDateEditAcceptDelay)
-
-public:
- enum HorizontalHeaderFormat {
- NoHorizontalHeader,
- SingleLetterDayNames,
- ShortDayNames,
- LongDayNames
- };
-
- enum VerticalHeaderFormat {
- NoVerticalHeader,
- ISOWeekNumbers
- };
-
- enum SelectionMode {
- NoSelection,
- SingleSelection
- };
-
- explicit QCalendarWidget(QWidget *parent = 0);
- ~QCalendarWidget();
-
- virtual QSize sizeHint() const;
- virtual QSize minimumSizeHint() const;
-
- QDate selectedDate() const;
-
- int yearShown() const;
- int monthShown() const;
-
- QDate minimumDate() const;
- void setMinimumDate(const QDate &date);
-
- QDate maximumDate() const;
- void setMaximumDate(const QDate &date);
-
- Qt::DayOfWeek firstDayOfWeek() const;
- void setFirstDayOfWeek(Qt::DayOfWeek dayOfWeek);
-
- // ### Qt 5: eliminate these two
- bool isHeaderVisible() const;
- void setHeaderVisible(bool show);
-
- inline bool isNavigationBarVisible() const { return isHeaderVisible(); }
-
- bool isGridVisible() const;
-
- SelectionMode selectionMode() const;
- void setSelectionMode(SelectionMode mode);
-
- HorizontalHeaderFormat horizontalHeaderFormat() const;
- void setHorizontalHeaderFormat(HorizontalHeaderFormat format);
-
- VerticalHeaderFormat verticalHeaderFormat() const;
- void setVerticalHeaderFormat(VerticalHeaderFormat format);
-
- QTextCharFormat headerTextFormat() const;
- void setHeaderTextFormat(const QTextCharFormat &format);
-
- QTextCharFormat weekdayTextFormat(Qt::DayOfWeek dayOfWeek) const;
- void setWeekdayTextFormat(Qt::DayOfWeek dayOfWeek, const QTextCharFormat &format);
-
- QMap<QDate, QTextCharFormat> dateTextFormat() const;
- QTextCharFormat dateTextFormat(const QDate &date) const;
- void setDateTextFormat(const QDate &date, const QTextCharFormat &format);
-
- bool isDateEditEnabled() const;
- void setDateEditEnabled(bool enable);
-
- int dateEditAcceptDelay() const;
- void setDateEditAcceptDelay(int delay);
-
-protected:
- bool event(QEvent *event);
- bool eventFilter(QObject *watched, QEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void resizeEvent(QResizeEvent * event);
- void keyPressEvent(QKeyEvent * event);
-
- virtual void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
- void updateCell(const QDate &date);
- void updateCells();
-
-public Q_SLOTS:
- void setSelectedDate(const QDate &date);
- void setDateRange(const QDate &min, const QDate &max);
- void setCurrentPage(int year, int month);
- void setGridVisible(bool show);
- void setNavigationBarVisible(bool visible);
- void showNextMonth();
- void showPreviousMonth();
- void showNextYear();
- void showPreviousYear();
- void showSelectedDate();
- void showToday();
-
-Q_SIGNALS:
- void selectionChanged();
- void clicked(const QDate &date);
- void activated(const QDate &date);
- void currentPageChanged(int year, int month);
-
-private:
- Q_DECLARE_PRIVATE(QCalendarWidget)
- Q_DISABLE_COPY(QCalendarWidget)
-
- Q_PRIVATE_SLOT(d_func(), void _q_slotShowDate(const QDate &date))
- Q_PRIVATE_SLOT(d_func(), void _q_slotChangeDate(const QDate &date))
- Q_PRIVATE_SLOT(d_func(), void _q_slotChangeDate(const QDate &date, bool changeMonth))
- Q_PRIVATE_SLOT(d_func(), void _q_editingFinished())
- Q_PRIVATE_SLOT(d_func(), void _q_prevMonthClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_nextMonthClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_yearEditingFinished())
- Q_PRIVATE_SLOT(d_func(), void _q_yearClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_monthChanged(QAction *act))
-
-};
-
-#endif // QT_NO_CALENDARWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCALENDARWIDGET_H
-
diff --git a/src/gui/widgets/qcheckbox.cpp b/src/gui/widgets/qcheckbox.cpp
deleted file mode 100644
index df2512c1c8..0000000000
--- a/src/gui/widgets/qcheckbox.cpp
+++ /dev/null
@@ -1,447 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcheckbox.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qicon.h"
-#include "qstylepainter.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qevent.h"
-
-#include "private/qabstractbutton_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QCheckBoxPrivate : public QAbstractButtonPrivate
-{
- Q_DECLARE_PUBLIC(QCheckBox)
-public:
- QCheckBoxPrivate()
- : QAbstractButtonPrivate(QSizePolicy::CheckBox), tristate(false), noChange(false),
- hovering(true), publishedState(Qt::Unchecked) {}
-
- uint tristate : 1;
- uint noChange : 1;
- uint hovering : 1;
- uint publishedState : 2;
-
- void init();
-};
-
-/*!
- \class QCheckBox
- \brief The QCheckBox widget provides a checkbox with a text label.
-
- \ingroup basicwidgets
-
-
- A QCheckBox is an option button that can be switched on (checked) or off
- (unchecked). Checkboxes are typically used to represent features in an
- application that can be enabled or disabled without affecting others, but
- different types of behavior can be implemented. For example, a
- QButtonGroup can be used to group check buttons logically, allowing
- exclusive checkboxes. However, QButtonGroup does not provide any visual
- representation.
-
- The image below further illustrates the differences between exclusive and
- non-exclusive checkboxes.
-
- \table
- \row \o \inlineimage checkboxes-exclusive.png
- \o \inlineimage checkboxes-non-exclusive.png
- \endtable
-
- Whenever a checkbox is checked or cleared it emits the signal
- stateChanged(). Connect to this signal if you want to trigger an action
- each time the checkbox changes state. You can use isChecked() to query
- whether or not a checkbox is checked.
-
- In addition to the usual checked and unchecked states, QCheckBox optionally
- provides a third state to indicate "no change". This is useful whenever you
- need to give the user the option of neither checking nor unchecking a
- checkbox. If you need this third state, enable it with setTristate(), and
- use checkState() to query the current toggle state.
-
- Just like QPushButton, a checkbox displays text, and optionally a small
- icon. The icon is set with setIcon(). The text can be set in the
- constructor or with setText(). A shortcut key can be specified by preceding
- the preferred character with an ampersand. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qcheckbox.cpp 0
-
- In this example the shortcut is \e{Alt+A}. See the \l{QShortcut#mnemonic}
- {QShortcut} documentation for details (to display an actual ampersand,
- use '&&').
-
- Important inherited functions: text(), setText(), text(), pixmap(),
- setPixmap(), accel(), setAccel(), isToggleButton(), setDown(), isDown(),
- isOn(), checkState(), autoRepeat(), isExclusiveToggle(), group(),
- setAutoRepeat(), toggle(), pressed(), released(), clicked(), toggled(),
- checkState(), and stateChanged().
-
- \table 100%
- \row
- \o \inlineimage macintosh-checkbox.png Screenshot of a Macintosh style checkbox
- \o A checkbox shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row
- \o \inlineimage windows-checkbox.png Screenshot of a Windows XP style checkbox
- \o A checkbox shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row
- \o \inlineimage plastique-checkbox.png Screenshot of a Plastique style checkbox
- \o A checkbox shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QAbstractButton, QRadioButton, {fowler}{GUI Design Handbook: Check Box}
-*/
-
-/*!
- \enum QCheckBox::ToggleState
- \compat
-
- \value Off Use Qt::Unchecked instead.
- \value NoChange Use Qt::PartiallyChecked instead.
- \value On Use Qt::Checked instead.
-*/
-
-/*!
- \fn void QCheckBox::stateChanged(int state)
-
- This signal is emitted whenever the check box's state changes, i.e.
- whenever the user checks or unchecks it.
-
- \a state contains the check box's new Qt::CheckState.
-*/
-
-/*!
- \property QCheckBox::tristate
- \brief whether the checkbox is a tri-state checkbox
-
- The default is false; i.e. the checkbox has only two states.
-*/
-
-void QCheckBoxPrivate::init()
-{
- Q_Q(QCheckBox);
- q->setCheckable(true);
- q->setMouseTracking(true);
- q->setForegroundRole(QPalette::WindowText);
- setLayoutItemMargins(QStyle::SE_CheckBoxLayoutItem);
-}
-
-/*!
- Initializes \a option with the values from this QCheckBox. This method is
- useful for subclasses that require a QStyleOptionButton, but do not want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QCheckBox::initStyleOption(QStyleOptionButton *option) const
-{
- if (!option)
- return;
- Q_D(const QCheckBox);
- option->initFrom(this);
- if (d->down)
- option->state |= QStyle::State_Sunken;
- if (d->tristate && d->noChange)
- option->state |= QStyle::State_NoChange;
- else
- option->state |= d->checked ? QStyle::State_On : QStyle::State_Off;
- if (testAttribute(Qt::WA_Hover) && underMouse()) {
- if (d->hovering)
- option->state |= QStyle::State_MouseOver;
- else
- option->state &= ~QStyle::State_MouseOver;
- }
- option->text = d->text;
- option->icon = d->icon;
- option->iconSize = iconSize();
-}
-
-/*!
- Constructs a checkbox with the given \a parent, but with no text.
-
- \a parent is passed on to the QAbstractButton constructor.
-*/
-
-QCheckBox::QCheckBox(QWidget *parent)
- : QAbstractButton (*new QCheckBoxPrivate, parent)
-{
- Q_D(QCheckBox);
- d->init();
-}
-
-/*!
- Constructs a checkbox with the given \a parent and \a text.
-
- \a parent is passed on to the QAbstractButton constructor.
-*/
-
-QCheckBox::QCheckBox(const QString &text, QWidget *parent)
- : QAbstractButton (*new QCheckBoxPrivate, parent)
-{
- Q_D(QCheckBox);
- d->init();
- setText(text);
-}
-
-void QCheckBox::setTristate(bool y)
-{
- Q_D(QCheckBox);
- d->tristate = y;
-}
-
-bool QCheckBox::isTristate() const
-{
- Q_D(const QCheckBox);
- return d->tristate;
-}
-
-
-/*!
- Returns the check box's check state. If you do not need tristate support,
- you can also use \l QAbstractButton::isChecked() which returns a boolean.
-
- \sa setCheckState() Qt::CheckState
-*/
-Qt::CheckState QCheckBox::checkState() const
-{
- Q_D(const QCheckBox);
- if (d->tristate && d->noChange)
- return Qt::PartiallyChecked;
- return d->checked ? Qt::Checked : Qt::Unchecked;
-}
-
-/*!
- Sets the check box's check state to \a state. If you do not need tristate
- support, you can also use \l QAbstractButton::setChecked() which takes a
- boolean.
-
- \sa checkState() Qt::CheckState
-*/
-void QCheckBox::setCheckState(Qt::CheckState state)
-{
- Q_D(QCheckBox);
- if (state == Qt::PartiallyChecked) {
- d->tristate = true;
- d->noChange = true;
- } else {
- d->noChange = false;
- }
- d->blockRefresh = true;
- setChecked(state != Qt::Unchecked);
- d->blockRefresh = false;
- d->refresh();
- if ((uint)state != d->publishedState) {
- d->publishedState = state;
- emit stateChanged(state);
- }
-}
-
-
-/*!
- \reimp
-*/
-QSize QCheckBox::sizeHint() const
-{
- Q_D(const QCheckBox);
- if (d->sizeHint.isValid())
- return d->sizeHint;
- ensurePolished();
- QFontMetrics fm = fontMetrics();
- QStyleOptionButton opt;
- initStyleOption(&opt);
- QSize sz = style()->itemTextRect(fm, QRect(), Qt::TextShowMnemonic, false,
- text()).size();
- if (!opt.icon.isNull())
- sz = QSize(sz.width() + opt.iconSize.width() + 4, qMax(sz.height(), opt.iconSize.height()));
- d->sizeHint = (style()->sizeFromContents(QStyle::CT_CheckBox, &opt, sz, this)
- .expandedTo(QApplication::globalStrut()));
- return d->sizeHint;
-}
-
-
-/*!
- \reimp
-*/
-QSize QCheckBox::minimumSizeHint() const
-{
- return sizeHint();
-}
-
-/*!
- \reimp
-*/
-void QCheckBox::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionButton opt;
- initStyleOption(&opt);
- p.drawControl(QStyle::CE_CheckBox, opt);
-}
-
-/*!
- \reimp
-*/
-void QCheckBox::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QCheckBox);
- if (testAttribute(Qt::WA_Hover)) {
- bool hit = false;
- if (underMouse())
- hit = hitButton(e->pos());
-
- if (hit != d->hovering) {
- update(rect());
- d->hovering = hit;
- }
- }
-
- QAbstractButton::mouseMoveEvent(e);
-}
-
-
-/*!
- \reimp
-*/
-bool QCheckBox::hitButton(const QPoint &pos) const
-{
- QStyleOptionButton opt;
- initStyleOption(&opt);
- return style()->subElementRect(QStyle::SE_CheckBoxClickRect, &opt, this).contains(pos);
-}
-
-/*!
- \reimp
-*/
-void QCheckBox::checkStateSet()
-{
- Q_D(QCheckBox);
- d->noChange = false;
- Qt::CheckState state = checkState();
- if ((uint)state != d->publishedState) {
- d->publishedState = state;
- emit stateChanged(state);
- }
-}
-
-/*!
- \reimp
-*/
-void QCheckBox::nextCheckState()
-{
- Q_D(QCheckBox);
- if (d->tristate)
- setCheckState((Qt::CheckState)((checkState() + 1) % 3));
- else {
- QAbstractButton::nextCheckState();
- QCheckBox::checkStateSet();
- }
-}
-
-/*!
- \reimp
-*/
-bool QCheckBox::event(QEvent *e)
-{
- Q_D(QCheckBox);
- if (e->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || e->type() == QEvent::MacSizeChange
-#endif
- )
- d->setLayoutItemMargins(QStyle::SE_CheckBoxLayoutItem);
- return QAbstractButton::event(e);
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QCheckBox::QCheckBox(QWidget *parent, const char* name)
- : QAbstractButton (*new QCheckBoxPrivate, parent)
-{
- Q_D(QCheckBox);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QCheckBox::QCheckBox(const QString &text, QWidget *parent, const char* name)
- : QAbstractButton (*new QCheckBoxPrivate, parent)
-{
- Q_D(QCheckBox);
- setObjectName(QString::fromAscii(name));
- d->init();
- setText(text);
-}
-
-#endif
-
-
-/*!
- \fn void QCheckBox::setNoChange()
- \compat
-
- Use setCheckState() instead.
-*/
-
-/*!
- \fn void QCheckBox::setState(ToggleState state)
- \compat
-
- Use setCheckState() instead.
-*/
-
-/*!
- \fn QCheckBox::ToggleState QCheckBox::state() const
- \compat
-
- Use checkState() instead.
-*/
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qcheckbox.h b/src/gui/widgets/qcheckbox.h
deleted file mode 100644
index ae2e93291f..0000000000
--- a/src/gui/widgets/qcheckbox.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/****************************************************************************
-**
-** 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 QCHECKBOX_H
-#define QCHECKBOX_H
-
-#include <QtGui/qabstractbutton.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QCheckBoxPrivate;
-class QStyleOptionButton;
-
-class Q_GUI_EXPORT QCheckBox : public QAbstractButton
-{
- Q_OBJECT
-
- Q_PROPERTY(bool tristate READ isTristate WRITE setTristate)
-
-public:
- explicit QCheckBox(QWidget *parent=0);
- explicit QCheckBox(const QString &text, QWidget *parent=0);
-
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- void setTristate(bool y = true);
- bool isTristate() const;
-
- Qt::CheckState checkState() const;
- void setCheckState(Qt::CheckState state);
-
-Q_SIGNALS:
- void stateChanged(int);
-
-protected:
- bool event(QEvent *e);
- bool hitButton(const QPoint &pos) const;
- void checkStateSet();
- void nextCheckState();
- void paintEvent(QPaintEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void initStyleOption(QStyleOptionButton *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- enum ToggleState {
- Off = Qt::Unchecked,
- NoChange = Qt::PartiallyChecked,
- On = Qt::Checked
- };
- inline QT3_SUPPORT ToggleState state() const
- { return static_cast<QCheckBox::ToggleState>(static_cast<int>(checkState())); }
- inline QT3_SUPPORT void setState(ToggleState state)
- { setCheckState(static_cast<Qt::CheckState>(static_cast<int>(state))); }
- inline QT3_SUPPORT void setNoChange()
- { setCheckState(Qt::PartiallyChecked); }
- QT3_SUPPORT_CONSTRUCTOR QCheckBox(QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QCheckBox(const QString &text, QWidget *parent, const char* name);
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QCheckBox)
- Q_DISABLE_COPY(QCheckBox)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCHECKBOX_H
diff --git a/src/gui/widgets/qcocoamenu_mac.mm b/src/gui/widgets/qcocoamenu_mac.mm
deleted file mode 100644
index dff37b49ad..0000000000
--- a/src/gui/widgets/qcocoamenu_mac.mm
+++ /dev/null
@@ -1,244 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmacdefines_mac.h"
-#include "qapplication.h"
-#ifdef QT_MAC_USE_COCOA
-#import <private/qcocoamenu_mac_p.h>
-#import <private/qcocoamenuloader_mac_p.h>
-#import <private/qcocoaapplication_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qapplication_p.h>
-#include <private/qaction_p.h>
-#include <private/qcocoaapplication_mac_p.h>
-
-#include <QtGui/QMenu>
-
-QT_FORWARD_DECLARE_CLASS(QAction)
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QApplication)
-QT_FORWARD_DECLARE_CLASS(QCoreApplication)
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
-QT_FORWARD_DECLARE_CLASS(QKeyEvent)
-QT_FORWARD_DECLARE_CLASS(QEvent)
-
-QT_BEGIN_NAMESPACE
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); //qapplication.cpp
-extern NSString *qt_mac_removePrivateUnicode(NSString* string);
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaMenu)
-
-- (id)initWithQMenu:(QMenu*)menu
-{
- self = [super init];
- if (self) {
- qmenu = menu;
- previousAction = 0;
- [self setAutoenablesItems:NO];
- [self setDelegate:self];
- }
- return self;
-}
-
-- (void)menu:(NSMenu*)menu willHighlightItem:(NSMenuItem*)item
-{
- Q_UNUSED(menu);
-
- if (!item) {
- if (previousAction) {
- qt_mac_clear_status_text(previousAction);
- previousAction = 0;
- }
- return;
- }
-
- if (QAction *action = reinterpret_cast<QAction *>([item tag])) {
- QMenu *qtmenu = static_cast<QT_MANGLE_NAMESPACE(QCocoaMenu) *>(menu)->qmenu;
- previousAction = action;
- action->activate(QAction::Hover);
- qt_mac_menu_emit_hovered(qtmenu, action);
- action->showStatusText(0); // 0 widget -> action's parent
- }
-}
-
-- (void)menuWillOpen:(NSMenu*)menu
-{
- while (QWidget *popup
- = QApplication::activePopupWidget())
- popup->close();
- QMenu *qtmenu = static_cast<QT_MANGLE_NAMESPACE(QCocoaMenu) *>(menu)->qmenu;
- qt_mac_emit_menuSignals(qtmenu, true);
- qt_mac_menu_collapseSeparators(menu, qtmenu->separatorsCollapsible());
-}
-
-- (void)menuDidClose:(NSMenu*)menu
-{
- qt_mac_emit_menuSignals(((QT_MANGLE_NAMESPACE(QCocoaMenu) *)menu)->qmenu, false);
- if (previousAction) {
- qt_mac_clear_status_text(previousAction);
- previousAction = 0;
- }
-}
-
-- (BOOL)hasShortcut:(NSMenu *)menu forKey:(NSString *)key forModifiers:(NSUInteger)modifier
- whichItem:(NSMenuItem**)outItem
-{
- for (NSMenuItem *item in [menu itemArray]) {
- if (![item isEnabled] || [item isHidden] || [item isSeparatorItem])
- continue;
- if ([item hasSubmenu]) {
- if ([self hasShortcut:[item submenu]
- forKey:key
- forModifiers:modifier whichItem:outItem]) {
- if (outItem)
- *outItem = item;
- return YES;
- }
- }
- NSString *menuKey = [item keyEquivalent];
- if (menuKey && NSOrderedSame == [menuKey compare:key]
- && (modifier == [item keyEquivalentModifierMask])) {
- if (outItem)
- *outItem = item;
- return YES;
- }
- }
- if (outItem)
- *outItem = 0;
- return NO;
-}
-
-- (BOOL)menuHasKeyEquivalent:(NSMenu *)menu forEvent:(NSEvent *)event target:(id *)target action:(SEL *)action
-{
- // Check if the menu actually has a keysequence defined for this key event.
- // If it does, then we will first send the key sequence to the QWidget that has focus
- // since (in Qt's eyes) it needs to a chance at the key event first. If the widget
- // accepts the key event, we then return YES, but set the target and action to be nil,
- // which means that the action should not be triggered, and instead dispatch the event ourselves.
- // In every other case we return NO, which means that Cocoa can do as it pleases
- // (i.e., fire the menu action).
- NSMenuItem *whichItem;
- // Change the private unicode keys to the ones used in setting the "Key Equivalents"
- NSString *characters = qt_mac_removePrivateUnicode([event characters]);
- if ([self hasShortcut:menu
- forKey:characters
- // Interested only in Shift, Cmd, Ctrl & Alt Keys, so ignoring masks like, Caps lock, Num Lock ...
- forModifiers:([event modifierFlags] & (NSShiftKeyMask | NSControlKeyMask | NSCommandKeyMask | NSAlternateKeyMask))
- whichItem:&whichItem]) {
- QWidget *widget = 0;
- QAction *qaction = 0;
- if (whichItem && [whichItem tag]) {
- qaction = reinterpret_cast<QAction *>([whichItem tag]);
- }
- if (qApp->activePopupWidget())
- widget = (qApp->activePopupWidget()->focusWidget() ?
- qApp->activePopupWidget()->focusWidget() : qApp->activePopupWidget());
- else if (QApplicationPrivate::focus_widget)
- widget = QApplicationPrivate::focus_widget;
- // If we could not find any receivers, pass it to the active window
- if (!widget)
- widget = qApp->activeWindow();
- if (qaction && widget) {
- int key = qaction->shortcut();
- QKeyEvent accel_ev(QEvent::ShortcutOverride, (key & (~Qt::KeyboardModifierMask)),
- Qt::KeyboardModifiers(key & Qt::KeyboardModifierMask));
- accel_ev.ignore();
- qt_sendSpontaneousEvent(widget, &accel_ev);
- if (accel_ev.isAccepted()) {
- qt_dispatchKeyEvent(event, widget);
- *target = nil;
- *action = nil;
- return YES;
- }
- }
- }
- return NO;
-}
-
-- (NSInteger)indexOfItemWithTarget:(id)anObject andAction:(SEL)actionSelector
-{
- NSInteger index = [super indexOfItemWithTarget:anObject andAction:actionSelector];
- static SEL selForOFCP = NSSelectorFromString(@"orderFrontCharacterPalette:");
- if (index == -1 && selForOFCP == actionSelector) {
- // Check if the 'orderFrontCharacterPalette' SEL exists for QCocoaMenuLoader object
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = [NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
- return [super indexOfItemWithTarget:loader andAction:actionSelector];
- }
- return index;
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-extern int qt_mac_menus_open_count; // qmenu_mac.mm
-
-void qt_mac_emit_menuSignals(QMenu *menu, bool show)
-{
- if (!menu)
- return;
- int delta;
- if (show) {
- emit menu->aboutToShow();
- delta = 1;
- } else {
- emit menu->aboutToHide();
- delta = -1;
- }
- qt_mac_menus_open_count += delta;
-}
-
-void qt_mac_clear_status_text(QAction *action)
-{
- action->d_func()->showStatusText(0, QString());
-}
-
-void qt_mac_menu_emit_hovered(QMenu *menu, QAction *action)
-{
- emit menu->hovered(action);
-}
-
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qcocoamenu_mac_p.h b/src/gui/widgets/qcocoamenu_mac_p.h
deleted file mode 100644
index 42a43f7a51..0000000000
--- a/src/gui/widgets/qcocoamenu_mac_p.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_FORWARD_DECLARE_CLASS(QMenu)
-QT_FORWARD_DECLARE_CLASS(QAction)
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSMenuDelegate <NSObject>
-- (void)menu:(NSMenu*)menu willHighlightItem:(NSMenuItem*)item;
-- (void)menuWillOpen:(NSMenu*)menu;
-- (void)menuDidClose:(NSMenu*)menu;
-- (BOOL)hasShortcut:(NSMenu *)menu forKey:(NSString *)key forModifiers:(NSUInteger)modifier
- whichItem:(NSMenuItem**)outItem;
-@end
-
-#endif
-
-@interface QT_MANGLE_NAMESPACE(QCocoaMenu) : NSMenu <NSMenuDelegate>
-{
- QMenu *qmenu;
- QAction *previousAction;
-}
-- (id)initWithQMenu:(QMenu*)menu;
-- (BOOL)menuHasKeyEquivalent:(NSMenu *)menu forEvent:(NSEvent *)event target:(id *)target action:(SEL *)action;
-- (NSInteger)indexOfItemWithTarget:(id)anObject andAction:(SEL)actionSelector;
-@end
-#endif
-
diff --git a/src/gui/widgets/qcocoatoolbardelegate_mac.mm b/src/gui/widgets/qcocoatoolbardelegate_mac.mm
deleted file mode 100644
index a5ce0d3459..0000000000
--- a/src/gui/widgets/qcocoatoolbardelegate_mac.mm
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#import <private/qcocoatoolbardelegate_mac_p.h>
-#ifdef QT_MAC_USE_COCOA
-#include <private/qmainwindowlayout_p.h>
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qcocoaview_mac_p.h>
-#include <private/qwidget_p.h>
-#include <qtoolbar.h>
-#include <qlayout.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-extern QWidgetPrivate *qt_widget_private(QWidget *widget);
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QMainWindowLayout);
-QT_FORWARD_DECLARE_CLASS(QToolBar);
-QT_FORWARD_DECLARE_CLASS(QCFString);
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaToolBarDelegate)
-
-- (id)initWithMainWindowLayout:(QMainWindowLayout *)layout
-{
- self = [super init];
- if (self) {
- mainWindowLayout = layout;
- }
- return self;
-}
-
-- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
-{
- Q_UNUSED(toolbar);
- return [NSArray arrayWithObject:@"com.trolltech.qt.nstoolbar-qtoolbar"];
-}
-
-- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
-{
- return [self toolbarAllowedItemIdentifiers:toolbar];
-}
-
-- (void)toolbarDidRemoveItem:(NSNotification *)notification
-{
- NSToolbarItem *item = [[notification userInfo] valueForKey:@"item"];
- mainWindowLayout->unifiedToolbarHash.remove(item);
- for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
- if (mainWindowLayout->toolbarItemsCopy.at(i) == item) {
- // I know about it, so release it.
- mainWindowLayout->toolbarItemsCopy.removeAt(i);
- mainWindowLayout->qtoolbarsInUnifiedToolbarList.removeAt(i);
- [item release];
- break;
- }
- }
-}
-
-- (NSToolbarItem *)toolbar:(NSToolbar *)nstoolbar itemForItemIdentifier:(NSString *)itemIdentifier
- willBeInsertedIntoToolbar:(BOOL)flag
-{
- Q_UNUSED(flag);
- Q_UNUSED(nstoolbar);
- QToolBar *tb = mainWindowLayout->cocoaItemIDToToolbarHash.value(
- QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)(itemIdentifier));
- NSToolbarItem *item = nil;
- if (tb) {
- item = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
- mainWindowLayout->unifiedToolbarHash.insert(item, tb);
- }
- return item;
-}
-
-- (void)toolbarWillAddItem:(NSNotification *)notification
-{
- NSToolbarItem *item = [[notification userInfo] valueForKey:@"item"];
- QToolBar *tb = mainWindowLayout->cocoaItemIDToToolbarHash.value(
- QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)([item itemIdentifier]));
- if (!tb)
- return; // I can't really do anything about this.
- [item retain];
- [item setView:QT_PREPEND_NAMESPACE(qt_mac_nativeview_for)(tb)];
-
- NSArray *items = [[qt_mac_window_for(mainWindowLayout->layoutState.mainWindow->window()) toolbar] items];
- int someIndex = 0;
- for (NSToolbarItem *i in items) {
- if (i == item)
- break;
- ++someIndex;
- }
- mainWindowLayout->toolbarItemsCopy.insert(someIndex, item);
-
- // This is synchronization code that was needed in Carbon, but may not be needed anymore here.
- QToolBar *toolbar = mainWindowLayout->unifiedToolbarHash.value(item);
- if (toolbar) {
- int toolbarIndex = mainWindowLayout->qtoolbarsInUnifiedToolbarList.indexOf(toolbar);
- if (someIndex != toolbarIndex) {
- // Dang, we must be out of sync, rebuild it from the "toolbarItemsCopy"
- mainWindowLayout->qtoolbarsInUnifiedToolbarList.clear();
- for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
- // This will either append the correct toolbar or an
- // null toolbar. This is fine because this list
- // is really only kept to make sure that things are but in the right order.
- mainWindowLayout->qtoolbarsInUnifiedToolbarList.append(
- mainWindowLayout->unifiedToolbarHash.value(mainWindowLayout->
- toolbarItemsCopy.at(i)));
- }
- }
- toolbar->update();
- }
-}
-
-@end
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/widgets/qcocoatoolbardelegate_mac_p.h b/src/gui/widgets/qcocoatoolbardelegate_mac_p.h
deleted file mode 100644
index 1542dcf2fa..0000000000
--- a/src/gui/widgets/qcocoatoolbardelegate_mac_p.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_BEGIN_NAMESPACE
-class QMainWindowLayout;
-class QToolBar;
-QT_END_NAMESPACE
-
-@class NSToolbarItem;
-
-@interface QT_MANGLE_NAMESPACE(QCocoaToolBarDelegate) : NSObject {
- QT_PREPEND_NAMESPACE(QMainWindowLayout) *mainWindowLayout;
- NSToolbarItem *toolbarItem;
-}
-
-- (id)initWithMainWindowLayout:(QT_PREPEND_NAMESPACE(QMainWindowLayout) *)layout;
-@end
-#endif
diff --git a/src/gui/widgets/qcombobox.cpp b/src/gui/widgets/qcombobox.cpp
deleted file mode 100644
index dd1ad9cd28..0000000000
--- a/src/gui/widgets/qcombobox.cpp
+++ /dev/null
@@ -1,3365 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcombobox.h"
-
-#ifndef QT_NO_COMBOBOX
-#include <qstylepainter.h>
-#include <qlineedit.h>
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <qlistview.h>
-#include <qtableview.h>
-#include <qitemdelegate.h>
-#include <qmap.h>
-#include <qmenu.h>
-#include <qevent.h>
-#include <qlayout.h>
-#include <qscrollbar.h>
-#include <qtreeview.h>
-#include <qheaderview.h>
-#include <qmath.h>
-#ifndef QT_NO_IM
-#include "qinputcontext.h"
-#endif
-#include <private/qapplication_p.h>
-#include <private/qcombobox_p.h>
-#include <private/qabstractitemmodel_p.h>
-#include <private/qabstractscrollarea_p.h>
-#include <private/qsoftkeymanager_p.h>
-#include <qdebug.h>
-#ifdef Q_WS_X11
-#include <private/qt_x11_p.h>
-#endif
-#if defined(Q_WS_MAC) && !defined(QT_NO_EFFECTS) && !defined(QT_NO_STYLE_MAC)
-#include <private/qcore_mac_p.h>
-#include <QMacStyle>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-#ifndef QT_NO_EFFECTS
-# include <private/qeffects_p.h>
-#endif
-#if defined(Q_WS_S60)
-#include "private/qt_s60_p.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QComboBoxPrivate::QComboBoxPrivate()
- : QWidgetPrivate(),
- model(0),
- lineEdit(0),
- container(0),
- insertPolicy(QComboBox::InsertAtBottom),
- sizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow),
- minimumContentsLength(0),
- shownOnce(false),
- autoCompletion(true),
- duplicatesEnabled(false),
- frame(true),
- maxVisibleItems(10),
- maxCount(INT_MAX),
- modelColumn(0),
- inserting(false),
- arrowState(QStyle::State_None),
- hoverControl(QStyle::SC_None),
- autoCompletionCaseSensitivity(Qt::CaseInsensitive),
- indexBeforeChange(-1)
-#ifndef QT_NO_COMPLETER
- , completer(0)
-#endif
-{
-}
-
-QStyleOptionMenuItem QComboMenuDelegate::getStyleOption(const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- QStyleOptionMenuItem menuOption;
-
- QPalette resolvedpalette = option.palette.resolve(QApplication::palette("QMenu"));
- QVariant value = index.data(Qt::ForegroundRole);
- if (value.canConvert<QBrush>()) {
- resolvedpalette.setBrush(QPalette::WindowText, qvariant_cast<QBrush>(value));
- resolvedpalette.setBrush(QPalette::ButtonText, qvariant_cast<QBrush>(value));
- resolvedpalette.setBrush(QPalette::Text, qvariant_cast<QBrush>(value));
- }
- menuOption.palette = resolvedpalette;
- menuOption.state = QStyle::State_None;
- if (mCombo->window()->isActiveWindow())
- menuOption.state = QStyle::State_Active;
- if ((option.state & QStyle::State_Enabled) && (index.model()->flags(index) & Qt::ItemIsEnabled))
- menuOption.state |= QStyle::State_Enabled;
- else
- menuOption.palette.setCurrentColorGroup(QPalette::Disabled);
- if (option.state & QStyle::State_Selected)
- menuOption.state |= QStyle::State_Selected;
- menuOption.checkType = QStyleOptionMenuItem::NonExclusive;
- menuOption.checked = mCombo->currentIndex() == index.row();
- if (QComboBoxDelegate::isSeparator(index))
- menuOption.menuItemType = QStyleOptionMenuItem::Separator;
- else
- menuOption.menuItemType = QStyleOptionMenuItem::Normal;
-
- QVariant variant = index.model()->data(index, Qt::DecorationRole);
- switch (variant.type()) {
- case QVariant::Icon:
- menuOption.icon = qvariant_cast<QIcon>(variant);
- break;
- case QVariant::Color: {
- static QPixmap pixmap(option.decorationSize);
- pixmap.fill(qvariant_cast<QColor>(variant));
- menuOption.icon = pixmap;
- break; }
- default:
- menuOption.icon = qvariant_cast<QPixmap>(variant);
- break;
- }
- if (index.data(Qt::BackgroundRole).canConvert<QBrush>()) {
- menuOption.palette.setBrush(QPalette::All, QPalette::Background,
- qvariant_cast<QBrush>(index.data(Qt::BackgroundRole)));
- }
- menuOption.text = index.model()->data(index, Qt::DisplayRole).toString()
- .replace(QLatin1Char('&'), QLatin1String("&&"));
- menuOption.tabWidth = 0;
- menuOption.maxIconWidth = option.decorationSize.width() + 4;
- menuOption.menuRect = option.rect;
- menuOption.rect = option.rect;
-
- // Make sure fonts set on the combo box also overrides the font for the popup menu.
- if (mCombo->testAttribute(Qt::WA_SetFont)
- || mCombo->testAttribute(Qt::WA_MacSmallSize)
- || mCombo->testAttribute(Qt::WA_MacMiniSize)
- || mCombo->font() != qt_app_fonts_hash()->value("QComboBox", QFont()))
- menuOption.font = mCombo->font();
- else
- menuOption.font = qt_app_fonts_hash()->value("QComboMenuItem", mCombo->font());
-
- menuOption.fontMetrics = QFontMetrics(menuOption.font);
-
- return menuOption;
-}
-
-#ifdef QT_KEYPAD_NAVIGATION
-void QComboBoxPrivate::_q_completerActivated()
-{
- Q_Q(QComboBox);
- if ( QApplication::keypadNavigationEnabled()
- && q->isEditable()
- && q->completer()
- && q->completer()->completionMode() == QCompleter::UnfilteredPopupCompletion ) {
- q->setEditFocus(false);
- }
-}
-#endif
-
-void QComboBoxPrivate::updateArrow(QStyle::StateFlag state)
-{
- Q_Q(QComboBox);
- if (arrowState == state)
- return;
- arrowState = state;
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- q->update(q->style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxArrow, q));
-}
-
-void QComboBoxPrivate::_q_modelReset()
-{
- Q_Q(QComboBox);
- if (lineEdit) {
- lineEdit->setText(QString());
- updateLineEditGeometry();
- }
- if (currentIndex.row() != indexBeforeChange)
- _q_emitCurrentIndexChanged(currentIndex);
- q->update();
-}
-
-void QComboBoxPrivate::_q_modelDestroyed()
-{
- model = QAbstractItemModelPrivate::staticEmptyModel();
-}
-
-
-//Windows and KDE allows menus to cover the taskbar, while GNOME and Mac don't
-QRect QComboBoxPrivate::popupGeometry(int screen) const
-{
-#ifdef Q_WS_WIN
- return QApplication::desktop()->screenGeometry(screen);
-#elif defined Q_WS_X11
- if (X11->desktopEnvironment == DE_KDE)
- return QApplication::desktop()->screenGeometry(screen);
- else
- return QApplication::desktop()->availableGeometry(screen);
-#else
- return QApplication::desktop()->availableGeometry(screen);
-#endif
-}
-
-bool QComboBoxPrivate::updateHoverControl(const QPoint &pos)
-{
-
- Q_Q(QComboBox);
- QRect lastHoverRect = hoverRect;
- QStyle::SubControl lastHoverControl = hoverControl;
- bool doesHover = q->testAttribute(Qt::WA_Hover);
- if (lastHoverControl != newHoverControl(pos) && doesHover) {
- q->update(lastHoverRect);
- q->update(hoverRect);
- return true;
- }
- return !doesHover;
-}
-
-QStyle::SubControl QComboBoxPrivate::newHoverControl(const QPoint &pos)
-{
- Q_Q(QComboBox);
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- opt.subControls = QStyle::SC_All;
- hoverControl = q->style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt, pos, q);
- hoverRect = (hoverControl != QStyle::SC_None)
- ? q->style()->subControlRect(QStyle::CC_ComboBox, &opt, hoverControl, q)
- : QRect();
- return hoverControl;
-}
-
-/*
- Computes a size hint based on the maximum width
- for the items in the combobox.
-*/
-int QComboBoxPrivate::computeWidthHint() const
-{
- Q_Q(const QComboBox);
-
- int width = 0;
- const int count = q->count();
- const int iconWidth = q->iconSize().width() + 4;
- const QFontMetrics &fontMetrics = q->fontMetrics();
-
- for (int i = 0; i < count; ++i) {
- const int textWidth = fontMetrics.width(q->itemText(i));
- if (q->itemIcon(i).isNull())
- width = (qMax(width, textWidth));
- else
- width = (qMax(width, textWidth + iconWidth));
- }
-
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- QSize tmp(width, 0);
- tmp = q->style()->sizeFromContents(QStyle::CT_ComboBox, &opt, tmp, q);
- return tmp.width();
-}
-
-QSize QComboBoxPrivate::recomputeSizeHint(QSize &sh) const
-{
- Q_Q(const QComboBox);
- if (!sh.isValid()) {
- bool hasIcon = sizeAdjustPolicy == QComboBox::AdjustToMinimumContentsLengthWithIcon ? true : false;
- int count = q->count();
- QSize iconSize = q->iconSize();
- const QFontMetrics &fm = q->fontMetrics();
-
- // text width
- if (&sh == &sizeHint || minimumContentsLength == 0) {
- switch (sizeAdjustPolicy) {
- case QComboBox::AdjustToContents:
- case QComboBox::AdjustToContentsOnFirstShow:
- if (count == 0) {
- sh.rwidth() = 7 * fm.width(QLatin1Char('x'));
- } else {
- for (int i = 0; i < count; ++i) {
- if (!q->itemIcon(i).isNull()) {
- hasIcon = true;
- sh.setWidth(qMax(sh.width(), fm.boundingRect(q->itemText(i)).width() + iconSize.width() + 4));
- } else {
- sh.setWidth(qMax(sh.width(), fm.boundingRect(q->itemText(i)).width()));
- }
- }
- }
- break;
- case QComboBox::AdjustToMinimumContentsLength:
- for (int i = 0; i < count && !hasIcon; ++i)
- hasIcon = !q->itemIcon(i).isNull();
- default:
- ;
- }
- } else {
- for (int i = 0; i < count && !hasIcon; ++i)
- hasIcon = !q->itemIcon(i).isNull();
- }
- if (minimumContentsLength > 0)
- sh.setWidth(qMax(sh.width(), minimumContentsLength * fm.width(QLatin1Char('X')) + (hasIcon ? iconSize.width() + 4 : 0)));
-
-
- // height
- sh.setHeight(qMax(qCeil(QFontMetricsF(fm).height()), 14) + 2);
- if (hasIcon) {
- sh.setHeight(qMax(sh.height(), iconSize.height() + 2));
- }
-
- // add style and strut values
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- sh = q->style()->sizeFromContents(QStyle::CT_ComboBox, &opt, sh, q);
- }
- return sh.expandedTo(QApplication::globalStrut());
-}
-
-void QComboBoxPrivate::adjustComboBoxSize()
-{
- viewContainer()->adjustSizeTimer.start(20, container);
-}
-
-void QComboBoxPrivate::updateLayoutDirection()
-{
- Q_Q(const QComboBox);
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- Qt::LayoutDirection dir = Qt::LayoutDirection(
- q->style()->styleHint(QStyle::SH_ComboBox_LayoutDirection, &opt, q));
- if (lineEdit)
- lineEdit->setLayoutDirection(dir);
- if (container)
- container->setLayoutDirection(dir);
-}
-
-
-void QComboBoxPrivateContainer::timerEvent(QTimerEvent *timerEvent)
-{
- if (timerEvent->timerId() == adjustSizeTimer.timerId()) {
- adjustSizeTimer.stop();
- if (combo->sizeAdjustPolicy() == QComboBox::AdjustToContents) {
- combo->updateGeometry();
- combo->adjustSize();
- combo->update();
- }
- }
-}
-
-void QComboBoxPrivateContainer::resizeEvent(QResizeEvent *e)
-{
- QStyleOptionComboBox opt = comboStyleOption();
- if (combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo)) {
- QStyleOption myOpt;
- myOpt.initFrom(this);
- QStyleHintReturnMask mask;
- if (combo->style()->styleHint(QStyle::SH_Menu_Mask, &myOpt, this, &mask)) {
- setMask(mask.region);
- }
- } else {
- clearMask();
- }
- QFrame::resizeEvent(e);
-}
-
-void QComboBoxPrivateContainer::leaveEvent(QEvent *)
-{
-// On Mac using the Mac style we want to clear the selection
-// when the mouse moves outside the popup.
-#ifdef Q_WS_MAC
- QStyleOptionComboBox opt = comboStyleOption();
- if (combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo))
- view->clearSelection();
-#endif
-}
-
-QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView, QComboBox *parent)
- : QFrame(parent, Qt::Popup), combo(parent), view(0), top(0), bottom(0)
-{
- // we need the combobox and itemview
- Q_ASSERT(parent);
- Q_ASSERT(itemView);
-
- setAttribute(Qt::WA_WindowPropagation);
- setAttribute(Qt::WA_X11NetWmWindowTypeCombo);
-
- // setup container
- blockMouseReleaseTimer.setSingleShot(true);
-
- // we need a vertical layout
- QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setSpacing(0);
- layout->setMargin(0);
-
- // set item view
- setItemView(itemView);
-
- // add scroller arrows if style needs them
- QStyleOptionComboBox opt = comboStyleOption();
- const bool usePopup = combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo);
- if (usePopup) {
- top = new QComboBoxPrivateScroller(QAbstractSlider::SliderSingleStepSub, this);
- bottom = new QComboBoxPrivateScroller(QAbstractSlider::SliderSingleStepAdd, this);
- top->hide();
- bottom->hide();
- } else {
- setLineWidth(1);
- }
-
- setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));
-
- if (top) {
- layout->insertWidget(0, top);
- connect(top, SIGNAL(doScroll(int)), this, SLOT(scrollItemView(int)));
- }
- if (bottom) {
- layout->addWidget(bottom);
- connect(bottom, SIGNAL(doScroll(int)), this, SLOT(scrollItemView(int)));
- }
-
- // Some styles (Mac) have a margin at the top and bottom of the popup.
- layout->insertSpacing(0, 0);
- layout->addSpacing(0);
- updateTopBottomMargin();
-}
-
-void QComboBoxPrivateContainer::scrollItemView(int action)
-{
-#ifndef QT_NO_SCROLLBAR
- if (view->verticalScrollBar())
- view->verticalScrollBar()->triggerAction(static_cast<QAbstractSlider::SliderAction>(action));
-#endif
-}
-
-/*
- Hides or shows the scrollers when we emulate a popupmenu
-*/
-void QComboBoxPrivateContainer::updateScrollers()
-{
-#ifndef QT_NO_SCROLLBAR
- if (!top || !bottom)
- return;
-
- if (isVisible() == false)
- return;
-
- QStyleOptionComboBox opt = comboStyleOption();
- if (combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo) &&
- view->verticalScrollBar()->minimum() < view->verticalScrollBar()->maximum()) {
-
- bool needTop = view->verticalScrollBar()->value()
- > (view->verticalScrollBar()->minimum() + spacing());
- bool needBottom = view->verticalScrollBar()->value()
- < (view->verticalScrollBar()->maximum() - spacing()*2);
- if (needTop)
- top->show();
- else
- top->hide();
- if (needBottom)
- bottom->show();
- else
- bottom->hide();
- } else {
- top->hide();
- bottom->hide();
- }
-#endif // QT_NO_SCROLLBAR
-}
-
-/*
- Cleans up when the view is destroyed.
-*/
-void QComboBoxPrivateContainer::viewDestroyed()
-{
- view = 0;
- setItemView(new QComboBoxListView());
-}
-
-/*
- Returns the item view used for the combobox popup.
-*/
-QAbstractItemView *QComboBoxPrivateContainer::itemView() const
-{
- return view;
-}
-
-/*!
- Sets the item view to be used for the combobox popup.
-*/
-void QComboBoxPrivateContainer::setItemView(QAbstractItemView *itemView)
-{
- Q_ASSERT(itemView);
-
- // clean up old one
- if (view) {
- view->removeEventFilter(this);
- view->viewport()->removeEventFilter(this);
-#ifndef QT_NO_SCROLLBAR
- disconnect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(updateScrollers()));
- disconnect(view->verticalScrollBar(), SIGNAL(rangeChanged(int,int)),
- this, SLOT(updateScrollers()));
-#endif
- disconnect(view, SIGNAL(destroyed()),
- this, SLOT(viewDestroyed()));
-
- delete view;
- view = 0;
- }
-
- // setup the item view
- view = itemView;
- view->setParent(this);
- view->setAttribute(Qt::WA_MacShowFocusRect, false);
- qobject_cast<QBoxLayout*>(layout())->insertWidget(top ? 2 : 0, view);
- view->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
- view->installEventFilter(this);
- view->viewport()->installEventFilter(this);
- view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- QStyleOptionComboBox opt = comboStyleOption();
- const bool usePopup = combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo);
-#ifndef QT_NO_SCROLLBAR
-#ifndef Q_WS_S60
- if (usePopup)
- view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
-#endif
-#endif
- if (combo->style()->styleHint(QStyle::SH_ComboBox_ListMouseTracking, &opt, combo) ||
- usePopup) {
- view->setMouseTracking(true);
- }
- view->setSelectionMode(QAbstractItemView::SingleSelection);
- view->setFrameStyle(QFrame::NoFrame);
- view->setLineWidth(0);
- view->setEditTriggers(QAbstractItemView::NoEditTriggers);
-#ifndef QT_NO_SCROLLBAR
- connect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(updateScrollers()));
- connect(view->verticalScrollBar(), SIGNAL(rangeChanged(int,int)),
- this, SLOT(updateScrollers()));
-#endif
- connect(view, SIGNAL(destroyed()),
- this, SLOT(viewDestroyed()));
-
-#ifdef QT_SOFTKEYS_ENABLED
- selectAction = QSoftKeyManager::createKeyedAction(QSoftKeyManager::SelectSoftKey, Qt::Key_Select, itemView);
- cancelAction = QSoftKeyManager::createKeyedAction(QSoftKeyManager::CancelSoftKey, Qt::Key_Escape, itemView);
- addAction(selectAction);
- addAction(cancelAction);
-#endif
-}
-
-/*!
- Returns the spacing between the items in the view.
-*/
-int QComboBoxPrivateContainer::spacing() const
-{
- QListView *lview = qobject_cast<QListView*>(view);
- if (lview)
- return lview->spacing();
-#ifndef QT_NO_TABLEVIEW
- QTableView *tview = qobject_cast<QTableView*>(view);
- if (tview)
- return tview->showGrid() ? 1 : 0;
-#endif
- return 0;
-}
-
-void QComboBoxPrivateContainer::updateTopBottomMargin()
-{
- if (!layout() || layout()->count() < 1)
- return;
-
- QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(layout());
- if (!boxLayout)
- return;
-
- const QStyleOptionComboBox opt = comboStyleOption();
- const bool usePopup = combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo);
- const int margin = usePopup ? combo->style()->pixelMetric(QStyle::PM_MenuVMargin, &opt, combo) : 0;
-
- QSpacerItem *topSpacer = boxLayout->itemAt(0)->spacerItem();
- if (topSpacer)
- topSpacer->changeSize(0, margin, QSizePolicy::Minimum, QSizePolicy::Fixed);
-
- QSpacerItem *bottomSpacer = boxLayout->itemAt(boxLayout->count() - 1)->spacerItem();
- if (bottomSpacer && bottomSpacer != topSpacer)
- bottomSpacer->changeSize(0, margin, QSizePolicy::Minimum, QSizePolicy::Fixed);
-
- boxLayout->invalidate();
-}
-
-void QComboBoxPrivateContainer::changeEvent(QEvent *e)
-{
- if (e->type() == QEvent::StyleChange) {
- QStyleOptionComboBox opt = comboStyleOption();
- view->setMouseTracking(combo->style()->styleHint(QStyle::SH_ComboBox_ListMouseTracking, &opt, combo) ||
- combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo));
- setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));
-#ifdef QT_SOFTKEYS_ENABLED
- } else if (e->type() == QEvent::LanguageChange) {
- selectAction->setText(QSoftKeyManager::standardSoftKeyText(QSoftKeyManager::SelectSoftKey));
- cancelAction->setText(QSoftKeyManager::standardSoftKeyText(QSoftKeyManager::CancelSoftKey));
-#endif
- }
-
- QWidget::changeEvent(e);
-}
-
-
-bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
-{
- switch (e->type()) {
- case QEvent::ShortcutOverride:
- switch (static_cast<QKeyEvent*>(e)->key()) {
- case Qt::Key_Enter:
- case Qt::Key_Return:
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
-#endif
- if (view->currentIndex().isValid() && (view->currentIndex().flags() & Qt::ItemIsEnabled) ) {
- combo->hidePopup();
- emit itemSelected(view->currentIndex());
- }
- return true;
- case Qt::Key_Down:
- if (!(static_cast<QKeyEvent*>(e)->modifiers() & Qt::AltModifier))
- break;
- // fall through
- case Qt::Key_F4:
- case Qt::Key_Escape:
- combo->hidePopup();
- return true;
- default:
- break;
- }
- break;
- case QEvent::MouseMove:
- if (isVisible()) {
- QMouseEvent *m = static_cast<QMouseEvent *>(e);
- QWidget *widget = static_cast<QWidget *>(o);
- QPoint vector = widget->mapToGlobal(m->pos()) - initialClickPosition;
- if (vector.manhattanLength() > 9 && blockMouseReleaseTimer.isActive())
- blockMouseReleaseTimer.stop();
- QModelIndex indexUnderMouse = view->indexAt(m->pos());
- if (indexUnderMouse.isValid()
- && !QComboBoxDelegate::isSeparator(indexUnderMouse)) {
- view->setCurrentIndex(indexUnderMouse);
- }
- }
- break;
- case QEvent::MouseButtonRelease: {
- QMouseEvent *m = static_cast<QMouseEvent *>(e);
- if (isVisible() && view->rect().contains(m->pos()) && view->currentIndex().isValid()
- && !blockMouseReleaseTimer.isActive()
- && (view->currentIndex().flags() & Qt::ItemIsEnabled)
- && (view->currentIndex().flags() & Qt::ItemIsSelectable)) {
- combo->hidePopup();
- emit itemSelected(view->currentIndex());
- return true;
- }
- break;
- }
- default:
- break;
- }
- return QFrame::eventFilter(o, e);
-}
-
-void QComboBoxPrivateContainer::showEvent(QShowEvent *)
-{
- combo->update();
-}
-
-void QComboBoxPrivateContainer::hideEvent(QHideEvent *)
-{
- emit resetButton();
- combo->update();
-#ifndef QT_NO_GRAPHICSVIEW
- // QGraphicsScenePrivate::removePopup closes the combo box popup, it hides it non-explicitly.
- // Hiding/showing the QComboBox after this will unexpectedly show the popup as well.
- // Re-hiding the popup container makes sure it is explicitly hidden.
- if (QGraphicsProxyWidget *proxy = graphicsProxyWidget())
- proxy->hide();
-#endif
-}
-
-void QComboBoxPrivateContainer::mousePressEvent(QMouseEvent *e)
-{
-
- QStyleOptionComboBox opt = comboStyleOption();
- opt.subControls = QStyle::SC_All;
- opt.activeSubControls = QStyle::SC_ComboBoxArrow;
- QStyle::SubControl sc = combo->style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt,
- combo->mapFromGlobal(e->globalPos()),
- combo);
- if ((combo->isEditable() && sc == QStyle::SC_ComboBoxArrow)
- || (!combo->isEditable() && sc != QStyle::SC_None))
- setAttribute(Qt::WA_NoMouseReplay);
- combo->hidePopup();
-}
-
-void QComboBoxPrivateContainer::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_UNUSED(e);
- if (!blockMouseReleaseTimer.isActive()){
- combo->hidePopup();
- emit resetButton();
- }
-}
-
-QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
-{
- // ### This should use QComboBox's initStyleOption(), but it's protected
- // perhaps, we could cheat by having the QCombo private instead?
- QStyleOptionComboBox opt;
- opt.initFrom(combo);
- opt.subControls = QStyle::SC_All;
- opt.activeSubControls = QStyle::SC_None;
- opt.editable = combo->isEditable();
- return opt;
-}
-
-/*!
- \enum QComboBox::InsertPolicy
-
- This enum specifies what the QComboBox should do when a new string is
- entered by the user.
-
- \value NoInsert The string will not be inserted into the combobox.
- \value InsertAtTop The string will be inserted as the first item in the combobox.
- \value InsertAtCurrent The current item will be \e replaced by the string.
- \value InsertAtBottom The string will be inserted after the last item in the combobox.
- \value InsertAfterCurrent The string is inserted after the current item in the combobox.
- \value InsertBeforeCurrent The string is inserted before the current item in the combobox.
- \value InsertAlphabetically The string is inserted in the alphabetic order in the combobox.
- \omitvalue NoInsertion
- \omitvalue AtTop
- \omitvalue AtCurrent
- \omitvalue AtBottom
- \omitvalue AfterCurrent
- \omitvalue BeforeCurrent
-*/
-
-/*!
- \enum QComboBox::SizeAdjustPolicy
-
- This enum specifies how the size hint of the QComboBox should
- adjust when new content is added or content changes.
-
- \value AdjustToContents The combobox will always adjust to the contents
- \value AdjustToContentsOnFirstShow The combobox will adjust to its contents the first time it is shown.
- \value AdjustToMinimumContentsLength Use AdjustToContents or AdjustToContentsOnFirstShow instead.
- \value AdjustToMinimumContentsLengthWithIcon The combobox will adjust to \l minimumContentsLength plus space for an icon. For performance reasons use this policy on large models.
-*/
-
-/*!
- \fn void QComboBox::activated(int index)
-
- This signal is sent when the user chooses an item in the combobox.
- The item's \a index is passed. Note that this signal is sent even
- when the choice is not changed. If you need to know when the
- choice actually changes, use signal currentIndexChanged().
-
-*/
-
-/*!
- \fn void QComboBox::activated(const QString &text)
-
- This signal is sent when the user chooses an item in the combobox.
- The item's \a text is passed. Note that this signal is sent even
- when the choice is not changed. If you need to know when the
- choice actually changes, use signal currentIndexChanged().
-
-*/
-
-/*!
- \fn void QComboBox::highlighted(int index)
-
- This signal is sent when an item in the combobox popup list is
- highlighted by the user. The item's \a index is passed.
-*/
-
-/*!
- \fn void QComboBox::highlighted(const QString &text)
-
- This signal is sent when an item in the combobox popup list is
- highlighted by the user. The item's \a text is passed.
-*/
-
-/*!
- \fn void QComboBox::currentIndexChanged(int index)
- \since 4.1
-
- This signal is sent whenever the currentIndex in the combobox
- changes either through user interaction or programmatically. The
- item's \a index is passed or -1 if the combobox becomes empty or the
- currentIndex was reset.
-*/
-
-/*!
- \fn void QComboBox::currentIndexChanged(const QString &text)
- \since 4.1
-
- This signal is sent whenever the currentIndex in the combobox
- changes either through user interaction or programmatically. The
- item's \a text is passed.
-*/
-
-/*!
- Constructs a combobox with the given \a parent, using the default
- model QStandardItemModel.
-*/
-QComboBox::QComboBox(QWidget *parent)
- : QWidget(*new QComboBoxPrivate(), parent, 0)
-{
- Q_D(QComboBox);
- d->init();
-}
-
-/*!
- \internal
-*/
-QComboBox::QComboBox(QComboBoxPrivate &dd, QWidget *parent)
- : QWidget(dd, parent, 0)
-{
- Q_D(QComboBox);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QComboBox::QComboBox(QWidget *parent, const char *name)
- : QWidget(*new QComboBoxPrivate(), parent, 0)
-{
- Q_D(QComboBox);
- d->init();
- setObjectName(QString::fromAscii(name));
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QComboBox::QComboBox(bool rw, QWidget *parent, const char *name)
- : QWidget(*new QComboBoxPrivate(), parent, 0)
-{
- Q_D(QComboBox);
- d->init();
- setEditable(rw);
- setObjectName(QString::fromAscii(name));
-}
-
-#endif //QT3_SUPPORT
-
-/*!
- \class QComboBox
- \brief The QComboBox widget is a combined button and popup list.
-
- \ingroup basicwidgets
-
-
- A QComboBox provides a means of presenting a list of options to the user
- in a way that takes up the minimum amount of screen space.
-
- A combobox is a selection widget that displays the current item,
- and can pop up a list of selectable items. A combobox may be editable,
- allowing the user to modify each item in the list.
-
- Comboboxes can contain pixmaps as well as strings; the
- insertItem() and setItemText() functions are suitably overloaded.
- For editable comboboxes, the function clearEditText() is provided,
- to clear the displayed string without changing the combobox's
- contents.
-
- There are two signals emitted if the current item of a combobox
- changes, currentIndexChanged() and activated().
- currentIndexChanged() is always emitted regardless if the change
- was done programmatically or by user interaction, while
- activated() is only emitted when the change is caused by user
- interaction. The highlighted() signal is emitted when the user
- highlights an item in the combobox popup list. All three signals
- exist in two versions, one with a QString argument and one with an
- \c int argument. If the user selects or highlights a pixmap, only
- the \c int signals are emitted. Whenever the text of an editable
- combobox is changed the editTextChanged() signal is emitted.
-
- When the user enters a new string in an editable combobox, the
- widget may or may not insert it, and it can insert it in several
- locations. The default policy is is \l AtBottom but you can change
- this using setInsertPolicy().
-
- It is possible to constrain the input to an editable combobox
- using QValidator; see setValidator(). By default, any input is
- accepted.
-
- A combobox can be populated using the insert functions,
- insertItem() and insertItems() for example. Items can be
- changed with setItemText(). An item can be removed with
- removeItem() and all items can be removed with clear(). The text
- of the current item is returned by currentText(), and the text of
- a numbered item is returned with text(). The current item can be
- set with setCurrentIndex(). The number of items in the combobox is
- returned by count(); the maximum number of items can be set with
- setMaxCount(). You can allow editing using setEditable(). For
- editable comboboxes you can set auto-completion using
- setCompleter() and whether or not the user can add duplicates
- is set with setDuplicatesEnabled().
-
- QComboBox uses the \l{Model/View Programming}{model/view
- framework} for its popup list and to store its items. By default
- a QStandardItemModel stores the items and a QListView subclass
- displays the popuplist. You can access the model and view directly
- (with model() and view()), but QComboBox also provides functions
- to set and get item data (e.g., setItemData() and itemText()). You
- can also set a new model and view (with setModel() and setView()).
- For the text and icon in the combobox label, the data in the model
- that has the Qt::DisplayRole and Qt::DecorationRole is used. Note
- that you cannot alter the \l{QAbstractItemView::}{SelectionMode}
- of the view(), e.g., by using
- \l{QAbstractItemView::}{setSelectionMode()}.
-
- \image qstyle-comboboxes.png Comboboxes in the different built-in styles.
-
- \sa QLineEdit, QSpinBox, QRadioButton, QButtonGroup,
- {fowler}{GUI Design Handbook: Combo Box, Drop-Down List Box}
-*/
-
-void QComboBoxPrivate::init()
-{
- Q_Q(QComboBox);
- q->setFocusPolicy(Qt::WheelFocus);
- q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed,
- QSizePolicy::ComboBox));
- setLayoutItemMargins(QStyle::SE_ComboBoxLayoutItem);
- q->setModel(new QStandardItemModel(0, 1, q));
- if (!q->isEditable())
- q->setAttribute(Qt::WA_InputMethodEnabled, false);
- else
- q->setAttribute(Qt::WA_InputMethodEnabled);
-}
-
-QComboBoxPrivateContainer* QComboBoxPrivate::viewContainer()
-{
- if (container)
- return container;
-
- Q_Q(QComboBox);
- container = new QComboBoxPrivateContainer(new QComboBoxListView(q), q);
- container->itemView()->setModel(model);
- container->itemView()->setTextElideMode(Qt::ElideMiddle);
- updateDelegate(true);
- updateLayoutDirection();
- updateViewContainerPaletteAndOpacity();
- QObject::connect(container, SIGNAL(itemSelected(QModelIndex)),
- q, SLOT(_q_itemSelected(QModelIndex)));
- QObject::connect(container->itemView()->selectionModel(),
- SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitHighlighted(QModelIndex)));
- QObject::connect(container, SIGNAL(resetButton()), q, SLOT(_q_resetButton()));
- return container;
-}
-
-
-void QComboBoxPrivate::_q_resetButton()
-{
- updateArrow(QStyle::State_None);
-}
-
-void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
-{
- Q_Q(QComboBox);
- if (inserting || topLeft.parent() != root)
- return;
-
- if (sizeAdjustPolicy == QComboBox::AdjustToContents) {
- sizeHint = QSize();
- adjustComboBoxSize();
- q->updateGeometry();
- }
-
- if (currentIndex.row() >= topLeft.row() && currentIndex.row() <= bottomRight.row()) {
- if (lineEdit) {
- lineEdit->setText(q->itemText(currentIndex.row()));
- updateLineEditGeometry();
- }
- q->update();
- }
-}
-
-void QComboBoxPrivate::_q_rowsInserted(const QModelIndex &parent, int start, int end)
-{
- Q_Q(QComboBox);
- if (inserting || parent != root)
- return;
-
- if (sizeAdjustPolicy == QComboBox::AdjustToContents) {
- sizeHint = QSize();
- adjustComboBoxSize();
- q->updateGeometry();
- }
-
- // set current index if combo was previously empty
- if (start == 0 && (end - start + 1) == q->count() && !currentIndex.isValid()) {
- q->setCurrentIndex(0);
- // need to emit changed if model updated index "silently"
- } else if (currentIndex.row() != indexBeforeChange) {
- q->update();
- _q_emitCurrentIndexChanged(currentIndex);
- }
-}
-
-void QComboBoxPrivate::_q_updateIndexBeforeChange()
-{
- indexBeforeChange = currentIndex.row();
-}
-
-void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/, int /*end*/)
-{
- Q_Q(QComboBox);
- if (parent != root)
- return;
-
- if (sizeAdjustPolicy == QComboBox::AdjustToContents) {
- sizeHint = QSize();
- adjustComboBoxSize();
- q->updateGeometry();
- }
-
- // model has changed the currentIndex
- if (currentIndex.row() != indexBeforeChange) {
- if (!currentIndex.isValid() && q->count()) {
- q->setCurrentIndex(qMin(q->count() - 1, qMax(indexBeforeChange, 0)));
- return;
- }
- if (lineEdit) {
- lineEdit->setText(q->itemText(currentIndex.row()));
- updateLineEditGeometry();
- }
- q->update();
- _q_emitCurrentIndexChanged(currentIndex);
- }
-}
-
-
-void QComboBoxPrivate::updateViewContainerPaletteAndOpacity()
-{
- if (!container)
- return;
- Q_Q(QComboBox);
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
-#ifndef QT_NO_MENU
- if (q->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, q)) {
- QMenu menu;
- menu.ensurePolished();
- container->setPalette(menu.palette());
- container->setWindowOpacity(menu.windowOpacity());
- } else
-#endif
- {
- container->setPalette(q->palette());
- container->setWindowOpacity(1.0);
- }
- if (lineEdit)
- lineEdit->setPalette(q->palette());
-}
-
-/*!
- Initialize \a option with the values from this QComboBox. This method
- is useful for subclasses when they need a QStyleOptionComboBox, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QComboBox::initStyleOption(QStyleOptionComboBox *option) const
-{
- if (!option)
- return;
-
- Q_D(const QComboBox);
- option->initFrom(this);
- option->editable = isEditable();
- option->frame = d->frame;
- if (hasFocus() && !option->editable)
- option->state |= QStyle::State_Selected;
- option->subControls = QStyle::SC_All;
- if (d->arrowState == QStyle::State_Sunken) {
- option->activeSubControls = QStyle::SC_ComboBoxArrow;
- option->state |= d->arrowState;
- } else {
- option->activeSubControls = d->hoverControl;
- }
- if (d->currentIndex.isValid()) {
- option->currentText = currentText();
- option->currentIcon = d->itemIcon(d->currentIndex);
- }
- option->iconSize = iconSize();
- if (d->container && d->container->isVisible())
- option->state |= QStyle::State_On;
-}
-
-void QComboBoxPrivate::updateLineEditGeometry()
-{
- if (!lineEdit)
- return;
-
- Q_Q(QComboBox);
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- QRect editRect = q->style()->subControlRect(QStyle::CC_ComboBox, &opt,
- QStyle::SC_ComboBoxEditField, q);
- if (!q->itemIcon(q->currentIndex()).isNull()) {
- QRect comboRect(editRect);
- editRect.setWidth(editRect.width() - q->iconSize().width() - 4);
- editRect = QStyle::alignedRect(q->layoutDirection(), Qt::AlignRight,
- editRect.size(), comboRect);
- }
- lineEdit->setGeometry(editRect);
-}
-
-Qt::MatchFlags QComboBoxPrivate::matchFlags() const
-{
- // Base how duplicates are determined on the autocompletion case sensitivity
- Qt::MatchFlags flags = Qt::MatchFixedString;
-#ifndef QT_NO_COMPLETER
- if (!lineEdit->completer() || lineEdit->completer()->caseSensitivity() == Qt::CaseSensitive)
-#endif
- flags |= Qt::MatchCaseSensitive;
- return flags;
-}
-
-
-void QComboBoxPrivate::_q_editingFinished()
-{
- Q_Q(QComboBox);
- if (lineEdit && !lineEdit->text().isEmpty()) {
- //here we just check if the current item was entered
- const int index = q_func()->findText(lineEdit->text(), matchFlags());
- if (index != -1 && itemText(currentIndex) != lineEdit->text()) {
- q->setCurrentIndex(index);
- emitActivated(currentIndex);
- }
- }
-
-}
-
-void QComboBoxPrivate::_q_returnPressed()
-{
- Q_Q(QComboBox);
- if (lineEdit && !lineEdit->text().isEmpty()) {
- if (q->count() >= maxCount && !(this->insertPolicy == QComboBox::InsertAtCurrent))
- return;
- lineEdit->deselect();
- lineEdit->end(false);
- QString text = lineEdit->text();
- // check for duplicates (if not enabled) and quit
- int index = -1;
- if (!duplicatesEnabled) {
- index = q->findText(text, matchFlags());
- if (index != -1) {
- q->setCurrentIndex(index);
- emitActivated(currentIndex);
- return;
- }
- }
- switch (insertPolicy) {
- case QComboBox::InsertAtTop:
- index = 0;
- break;
- case QComboBox::InsertAtBottom:
- index = q->count();
- break;
- case QComboBox::InsertAtCurrent:
- case QComboBox::InsertAfterCurrent:
- case QComboBox::InsertBeforeCurrent:
- if (!q->count() || !currentIndex.isValid())
- index = 0;
- else if (insertPolicy == QComboBox::InsertAtCurrent)
- q->setItemText(q->currentIndex(), text);
- else if (insertPolicy == QComboBox::InsertAfterCurrent)
- index = q->currentIndex() + 1;
- else if (insertPolicy == QComboBox::InsertBeforeCurrent)
- index = q->currentIndex();
- break;
- case QComboBox::InsertAlphabetically:
- index = 0;
- for (int i=0; i< q->count(); i++, index++ ) {
- if (text.toLower() < q->itemText(i).toLower())
- break;
- }
- break;
- case QComboBox::NoInsert:
- default:
- break;
- }
- if (index >= 0) {
- q->insertItem(index, text);
- q->setCurrentIndex(index);
- emitActivated(currentIndex);
- }
- }
-}
-
-void QComboBoxPrivate::_q_itemSelected(const QModelIndex &item)
-{
- Q_Q(QComboBox);
- if (item != currentIndex) {
- setCurrentIndex(item);
- } else if (lineEdit) {
- lineEdit->selectAll();
- lineEdit->setText(q->itemText(currentIndex.row()));
- }
- emitActivated(currentIndex);
-}
-
-void QComboBoxPrivate::emitActivated(const QModelIndex &index)
-{
- Q_Q(QComboBox);
- if (!index.isValid())
- return;
- QString text(itemText(index));
- emit q->activated(index.row());
- emit q->activated(text);
-}
-
-void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
-{
- Q_Q(QComboBox);
- if (!index.isValid())
- return;
- QString text(itemText(index));
- emit q->highlighted(index.row());
- emit q->highlighted(text);
-}
-
-void QComboBoxPrivate::_q_emitCurrentIndexChanged(const QModelIndex &index)
-{
- Q_Q(QComboBox);
- emit q->currentIndexChanged(index.row());
- emit q->currentIndexChanged(itemText(index));
-}
-
-QString QComboBoxPrivate::itemText(const QModelIndex &index) const
-{
- return index.isValid() ? model->data(index, itemRole()).toString() : QString();
-}
-
-int QComboBoxPrivate::itemRole() const
-{
- return q_func()->isEditable() ? Qt::EditRole : Qt::DisplayRole;
-}
-
-/*!
- Destroys the combobox.
-*/
-QComboBox::~QComboBox()
-{
- // ### check delegateparent and delete delegate if us?
- Q_D(QComboBox);
-
- QT_TRY {
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- } QT_CATCH(...) {
- ; // objects can't throw in destructor
- }
-}
-
-/*!
- \property QComboBox::maxVisibleItems
- \brief the maximum allowed size on screen of the combo box, measured in items
-
- By default, this property has a value of 10.
-
- \note This property is ignored for non-editable comboboxes in styles that returns
- true for QStyle::SH_ComboBox_Popup such as the Mac style or the Gtk+ Style.
-*/
-int QComboBox::maxVisibleItems() const
-{
- Q_D(const QComboBox);
- return d->maxVisibleItems;
-}
-
-void QComboBox::setMaxVisibleItems(int maxItems)
-{
- Q_D(QComboBox);
- if (maxItems < 0) {
- qWarning("QComboBox::setMaxVisibleItems: "
- "Invalid max visible items (%d) must be >= 0", maxItems);
- return;
- }
- d->maxVisibleItems = maxItems;
-}
-
-/*!
- \property QComboBox::count
- \brief the number of items in the combobox
-
- By default, for an empty combo box, this property has a value of 0.
-*/
-int QComboBox::count() const
-{
- Q_D(const QComboBox);
- return d->model->rowCount(d->root);
-}
-
-/*!
- \property QComboBox::maxCount
- \brief the maximum number of items allowed in the combobox
-
- \note If you set the maximum number to be less then the current
- amount of items in the combobox, the extra items will be
- truncated. This also applies if you have set an external model on
- the combobox.
-
- By default, this property's value is derived from the highest
- signed integer available (typically 2147483647).
-*/
-void QComboBox::setMaxCount(int max)
-{
- Q_D(QComboBox);
- if (max < 0) {
- qWarning("QComboBox::setMaxCount: Invalid count (%d) must be >= 0", max);
- return;
- }
-
- if (max < count())
- d->model->removeRows(max, count() - max, d->root);
-
- d->maxCount = max;
-}
-
-int QComboBox::maxCount() const
-{
- Q_D(const QComboBox);
- return d->maxCount;
-}
-
-#ifndef QT_NO_COMPLETER
-
-/*!
- \property QComboBox::autoCompletion
- \brief whether the combobox provides auto-completion for editable items
- \since 4.1
- \obsolete
-
- Use setCompleter() instead.
-
- By default, this property is true.
-
- \sa editable
-*/
-
-/*!
- \obsolete
-
- Use setCompleter() instead.
-*/
-bool QComboBox::autoCompletion() const
-{
- Q_D(const QComboBox);
- return d->autoCompletion;
-}
-
-/*!
- \obsolete
-
- Use setCompleter() instead.
-*/
-void QComboBox::setAutoCompletion(bool enable)
-{
- Q_D(QComboBox);
-
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !enable && isEditable())
- qWarning("QComboBox::setAutoCompletion: auto completion is mandatory when combo box editable");
-#endif
-
- d->autoCompletion = enable;
- if (!d->lineEdit)
- return;
- if (enable) {
- if (d->lineEdit->completer())
- return;
- d->completer = new QCompleter(d->model, d->lineEdit);
- d->completer->setCaseSensitivity(d->autoCompletionCaseSensitivity);
- d->completer->setCompletionMode(QCompleter::InlineCompletion);
- d->completer->setCompletionColumn(d->modelColumn);
- d->lineEdit->setCompleter(d->completer);
- d->completer->setWidget(this);
- } else {
- d->lineEdit->setCompleter(0);
- }
-}
-
-/*!
- \property QComboBox::autoCompletionCaseSensitivity
- \brief whether string comparisons are case-sensitive or case-insensitive for auto-completion
- \obsolete
-
- By default, this property is Qt::CaseInsensitive.
-
- Use setCompleter() instead. Case sensitivity of the auto completion can be
- changed using QCompleter::setCaseSensitivity().
-
- \sa autoCompletion
-*/
-
-/*!
- \obsolete
-
- Use setCompleter() and QCompleter::setCaseSensitivity() instead.
-*/
-Qt::CaseSensitivity QComboBox::autoCompletionCaseSensitivity() const
-{
- Q_D(const QComboBox);
- return d->autoCompletionCaseSensitivity;
-}
-
-/*!
- \obsolete
-
- Use setCompleter() and QCompleter::setCaseSensitivity() instead.
-*/
-void QComboBox::setAutoCompletionCaseSensitivity(Qt::CaseSensitivity sensitivity)
-{
- Q_D(QComboBox);
- d->autoCompletionCaseSensitivity = sensitivity;
- if (d->lineEdit && d->lineEdit->completer())
- d->lineEdit->completer()->setCaseSensitivity(sensitivity);
-}
-
-#endif // QT_NO_COMPLETER
-
-/*!
- \property QComboBox::duplicatesEnabled
- \brief whether the user can enter duplicate items into the combobox
-
- Note that it is always possible to programmatically insert duplicate items into the
- combobox.
-
- By default, this property is false (duplicates are not allowed).
-*/
-bool QComboBox::duplicatesEnabled() const
-{
- Q_D(const QComboBox);
- return d->duplicatesEnabled;
-}
-
-void QComboBox::setDuplicatesEnabled(bool enable)
-{
- Q_D(QComboBox);
- d->duplicatesEnabled = enable;
-}
-
-/*! \fn int QComboBox::findText(const QString &text, Qt::MatchFlags flags = Qt::MatchExactly|Qt::MatchCaseSensitive) const
-
- Returns the index of the item containing the given \a text; otherwise
- returns -1.
-
- The \a flags specify how the items in the combobox are searched.
-*/
-
-/*!
- Returns the index of the item containing the given \a data for the
- given \a role; otherwise returns -1.
-
- The \a flags specify how the items in the combobox are searched.
-*/
-int QComboBox::findData(const QVariant &data, int role, Qt::MatchFlags flags) const
-{
- Q_D(const QComboBox);
- QModelIndexList result;
- QModelIndex start = d->model->index(0, d->modelColumn, d->root);
- result = d->model->match(start, role, data, 1, flags);
- if (result.isEmpty())
- return -1;
- return result.first().row();
-}
-
-/*!
- \property QComboBox::insertPolicy
- \brief the policy used to determine where user-inserted items should
- appear in the combobox
-
- The default value is \l AtBottom, indicating that new items will appear
- at the bottom of the list of items.
-
- \sa InsertPolicy
-*/
-
-QComboBox::InsertPolicy QComboBox::insertPolicy() const
-{
- Q_D(const QComboBox);
- return d->insertPolicy;
-}
-
-void QComboBox::setInsertPolicy(InsertPolicy policy)
-{
- Q_D(QComboBox);
- d->insertPolicy = policy;
-}
-
-/*!
- \property QComboBox::sizeAdjustPolicy
- \brief the policy describing how the size of the combobox changes
- when the content changes
-
- The default value is \l AdjustToContentsOnFirstShow.
-
- \sa SizeAdjustPolicy
-*/
-
-QComboBox::SizeAdjustPolicy QComboBox::sizeAdjustPolicy() const
-{
- Q_D(const QComboBox);
- return d->sizeAdjustPolicy;
-}
-
-void QComboBox::setSizeAdjustPolicy(QComboBox::SizeAdjustPolicy policy)
-{
- Q_D(QComboBox);
- if (policy == d->sizeAdjustPolicy)
- return;
-
- d->sizeAdjustPolicy = policy;
- d->sizeHint = QSize();
- d->adjustComboBoxSize();
- updateGeometry();
-}
-
-/*!
- \property QComboBox::minimumContentsLength
- \brief the minimum number of characters that should fit into the combobox.
-
- The default value is 0.
-
- If this property is set to a positive value, the
- minimumSizeHint() and sizeHint() take it into account.
-
- \sa sizeAdjustPolicy
-*/
-int QComboBox::minimumContentsLength() const
-{
- Q_D(const QComboBox);
- return d->minimumContentsLength;
-}
-
-void QComboBox::setMinimumContentsLength(int characters)
-{
- Q_D(QComboBox);
- if (characters == d->minimumContentsLength || characters < 0)
- return;
-
- d->minimumContentsLength = characters;
-
- if (d->sizeAdjustPolicy == AdjustToContents
- || d->sizeAdjustPolicy == AdjustToMinimumContentsLength
- || d->sizeAdjustPolicy == AdjustToMinimumContentsLengthWithIcon) {
- d->sizeHint = QSize();
- d->adjustComboBoxSize();
- updateGeometry();
- }
-}
-
-/*!
- \property QComboBox::iconSize
- \brief the size of the icons shown in the combobox.
-
- Unless explicitly set this returns the default value of the
- current style. This size is the maximum size that icons can have;
- icons of smaller size are not scaled up.
-*/
-
-QSize QComboBox::iconSize() const
-{
- Q_D(const QComboBox);
- if (d->iconSize.isValid())
- return d->iconSize;
-
- int iconWidth = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this);
- return QSize(iconWidth, iconWidth);
-}
-
-void QComboBox::setIconSize(const QSize &size)
-{
- Q_D(QComboBox);
- if (size == d->iconSize)
- return;
-
- view()->setIconSize(size);
- d->iconSize = size;
- d->sizeHint = QSize();
- updateGeometry();
-}
-
-/*!
- \property QComboBox::editable
- \brief whether the combo box can be edited by the user
-
- By default, this property is false.
-*/
-bool QComboBox::isEditable() const
-{
- Q_D(const QComboBox);
- return d->lineEdit != 0;
-}
-
-/*! \internal
- update the default delegate
- depending on the style's SH_ComboBox_Popup hint, we use a different default delegate.
-
- but we do not change the delegate is the combobox use a custom delegate,
- unless \a force is set to true.
- */
-void QComboBoxPrivate::updateDelegate(bool force)
-{
- Q_Q(QComboBox);
- QStyleOptionComboBox opt;
- q->initStyleOption(&opt);
- if (q->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, q)) {
- if (force || qobject_cast<QComboBoxDelegate *>(q->itemDelegate()))
- q->setItemDelegate(new QComboMenuDelegate(q->view(), q));
- } else {
- if (force || qobject_cast<QComboMenuDelegate *>(q->itemDelegate()))
- q->setItemDelegate(new QComboBoxDelegate(q->view(), q));
- }
-}
-
-QIcon QComboBoxPrivate::itemIcon(const QModelIndex &index) const
-{
- QVariant decoration = model->data(index, Qt::DecorationRole);
- if (decoration.type() == QVariant::Pixmap)
- return QIcon(qvariant_cast<QPixmap>(decoration));
- else
- return qvariant_cast<QIcon>(decoration);
-}
-
-void QComboBox::setEditable(bool editable)
-{
- Q_D(QComboBox);
- if (isEditable() == editable)
- return;
-
- d->updateDelegate();
-
- QStyleOptionComboBox opt;
- initStyleOption(&opt);
- if (editable) {
- if (style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, this)) {
- d->viewContainer()->updateScrollers();
- view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- }
- QLineEdit *le = new QLineEdit(this);
- setLineEdit(le);
- } else {
- if (style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, this)) {
- d->viewContainer()->updateScrollers();
- view()->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- }
- setAttribute(Qt::WA_InputMethodEnabled, false);
- d->lineEdit->hide();
- d->lineEdit->deleteLater();
- d->lineEdit = 0;
- }
-
- d->viewContainer()->updateTopBottomMargin();
- if (!testAttribute(Qt::WA_Resized))
- adjustSize();
-}
-
-/*!
- Sets the line \a edit to use instead of the current line edit widget.
-
- The combo box takes ownership of the line edit.
-*/
-void QComboBox::setLineEdit(QLineEdit *edit)
-{
- Q_D(QComboBox);
- if (!edit) {
- qWarning("QComboBox::setLineEdit: cannot set a 0 line edit");
- return;
- }
-
- if (edit == d->lineEdit)
- return;
-
- edit->setText(currentText());
- delete d->lineEdit;
-
- d->lineEdit = edit;
- if (d->lineEdit->parent() != this)
- d->lineEdit->setParent(this);
- connect(d->lineEdit, SIGNAL(returnPressed()), this, SLOT(_q_returnPressed()));
- connect(d->lineEdit, SIGNAL(editingFinished()), this, SLOT(_q_editingFinished()));
- connect(d->lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(editTextChanged(QString)));
-#ifdef QT3_SUPPORT
- connect(d->lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(textChanged(QString)));
-#endif
- d->lineEdit->setFrame(false);
- d->lineEdit->setContextMenuPolicy(Qt::NoContextMenu);
- d->lineEdit->setFocusProxy(this);
- d->lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
-#ifndef QT_NO_COMPLETER
- setAutoCompletion(d->autoCompletion);
-#endif
-
-#ifdef QT_KEYPAD_NAVIGATION
-#ifndef QT_NO_COMPLETER
- if (QApplication::keypadNavigationEnabled()) {
- // Editable combo boxes will have a completer that is set to UnfilteredPopupCompletion.
- // This means that when the user enters edit mode they are immediately presented with a
- // list of possible completions.
- setAutoCompletion(true);
- if (d->completer) {
- d->completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
- connect(d->completer, SIGNAL(activated(QModelIndex)), this, SLOT(_q_completerActivated()));
- }
- }
-#endif
-#endif
-
- setAttribute(Qt::WA_InputMethodEnabled);
- d->updateLayoutDirection();
- d->updateLineEditGeometry();
- if (isVisible())
- d->lineEdit->show();
-
- update();
-}
-
-/*!
- Returns the line edit used to edit items in the combobox, or 0 if there
- is no line edit.
-
- Only editable combo boxes have a line edit.
-*/
-QLineEdit *QComboBox::lineEdit() const
-{
- Q_D(const QComboBox);
- return d->lineEdit;
-}
-
-#ifndef QT_NO_VALIDATOR
-/*!
- \fn void QComboBox::setValidator(const QValidator *validator)
-
- Sets the \a validator to use instead of the current validator.
-*/
-
-void QComboBox::setValidator(const QValidator *v)
-{
- Q_D(QComboBox);
- if (d->lineEdit)
- d->lineEdit->setValidator(v);
-}
-
-/*!
- Returns the validator that is used to constrain text input for the
- combobox.
-
- \sa editable
-*/
-const QValidator *QComboBox::validator() const
-{
- Q_D(const QComboBox);
- return d->lineEdit ? d->lineEdit->validator() : 0;
-}
-#endif // QT_NO_VALIDATOR
-
-#ifndef QT_NO_COMPLETER
-
-/*!
- \fn void QComboBox::setCompleter(QCompleter *completer)
- \since 4.2
-
- Sets the \a completer to use instead of the current completer.
- If \a completer is 0, auto completion is disabled.
-
- By default, for an editable combo box, a QCompleter that
- performs case insensitive inline completion is automatically created.
-*/
-void QComboBox::setCompleter(QCompleter *c)
-{
- Q_D(QComboBox);
- if (!d->lineEdit)
- return;
- d->lineEdit->setCompleter(c);
- if (c)
- c->setWidget(this);
-}
-
-/*!
- \since 4.2
-
- Returns the completer that is used to auto complete text input for the
- combobox.
-
- \sa editable
-*/
-QCompleter *QComboBox::completer() const
-{
- Q_D(const QComboBox);
- return d->lineEdit ? d->lineEdit->completer() : 0;
-}
-
-#endif // QT_NO_COMPLETER
-
-/*!
- Returns the item delegate used by the popup list view.
-
- \sa setItemDelegate()
-*/
-QAbstractItemDelegate *QComboBox::itemDelegate() const
-{
- return view()->itemDelegate();
-}
-
-/*!
- Sets the item \a delegate for the popup list view.
- The combobox takes ownership of the delegate.
-
- \warning You should not share the same instance of a delegate between comboboxes,
- widget mappers or views. Doing so can cause incorrect or unintuitive editing behavior
- since each view connected to a given delegate may receive the
- \l{QAbstractItemDelegate::}{closeEditor()} signal, and attempt to access, modify or
- close an editor that has already been closed.
-
- \sa itemDelegate()
-*/
-void QComboBox::setItemDelegate(QAbstractItemDelegate *delegate)
-{
- if (!delegate) {
- qWarning("QComboBox::setItemDelegate: cannot set a 0 delegate");
- return;
- }
- delete view()->itemDelegate();
- view()->setItemDelegate(delegate);
-}
-
-/*!
- Returns the model used by the combobox.
-*/
-
-QAbstractItemModel *QComboBox::model() const
-{
- Q_D(const QComboBox);
- if (d->model == QAbstractItemModelPrivate::staticEmptyModel()) {
- QComboBox *that = const_cast<QComboBox*>(this);
- that->setModel(new QStandardItemModel(0, 1, that));
- }
- return d->model;
-}
-
-/*!
- Sets the model to be \a model. \a model must not be 0.
- If you want to clear the contents of a model, call clear().
-
- \sa clear()
-*/
-void QComboBox::setModel(QAbstractItemModel *model)
-{
- Q_D(QComboBox);
-
- if (!model) {
- qWarning("QComboBox::setModel: cannot set a 0 model");
- return;
- }
-
-#ifndef QT_NO_COMPLETER
- if (d->lineEdit && d->lineEdit->completer()
- && d->lineEdit->completer() == d->completer)
- d->lineEdit->completer()->setModel(model);
-#endif
- if (d->model) {
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- disconnect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- disconnect(d->model, SIGNAL(modelAboutToBeReset()),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(modelReset()),
- this, SLOT(_q_modelReset()));
- if (d->model->QObject::parent() == this)
- delete d->model;
- }
-
- d->model = model;
-
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- connect(model, SIGNAL(modelAboutToBeReset()),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(modelReset()),
- this, SLOT(_q_modelReset()));
-
- if (d->container)
- d->container->itemView()->setModel(model);
-
- bool currentReset = false;
-
- if (count()) {
- for (int pos=0; pos < count(); pos++) {
- if (d->model->index(pos, d->modelColumn, d->root).flags() & Qt::ItemIsEnabled) {
- setCurrentIndex(pos);
- currentReset = true;
- break;
- }
- }
- }
-
- if (!currentReset)
- setCurrentIndex(-1);
-
- d->modelChanged();
-}
-
-/*!
- Returns the root model item index for the items in the combobox.
-
- \sa setRootModelIndex()
-*/
-
-QModelIndex QComboBox::rootModelIndex() const
-{
- Q_D(const QComboBox);
- return QModelIndex(d->root);
-}
-
-/*!
- Sets the root model item \a index for the items in the combobox.
-
- \sa rootModelIndex()
-*/
-void QComboBox::setRootModelIndex(const QModelIndex &index)
-{
- Q_D(QComboBox);
- d->root = QPersistentModelIndex(index);
- view()->setRootIndex(index);
- update();
-}
-
-/*!
- \property QComboBox::currentIndex
- \brief the index of the current item in the combobox.
-
- The current index can change when inserting or removing items.
-
- By default, for an empty combo box or a combo box in which no current
- item is set, this property has a value of -1.
-*/
-int QComboBox::currentIndex() const
-{
- Q_D(const QComboBox);
- return d->currentIndex.row();
-}
-
-void QComboBox::setCurrentIndex(int index)
-{
- Q_D(QComboBox);
- QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
- d->setCurrentIndex(mi);
-}
-
-void QComboBoxPrivate::setCurrentIndex(const QModelIndex &mi)
-{
- Q_Q(QComboBox);
-
- QModelIndex normalized;
- if (mi.column() != modelColumn)
- normalized = model->index(mi.row(), modelColumn, mi.parent());
- if (!normalized.isValid())
- normalized = mi; // Fallback to passed index.
-
- bool indexChanged = (normalized != currentIndex);
- if (indexChanged)
- currentIndex = QPersistentModelIndex(normalized);
- if (lineEdit) {
- QString newText = q->itemText(normalized.row());
- if (lineEdit->text() != newText)
- lineEdit->setText(newText);
- updateLineEditGeometry();
- }
- if (indexChanged) {
- q->update();
- _q_emitCurrentIndexChanged(currentIndex);
- }
-}
-
-/*!
- \property QComboBox::currentText
- \brief the text of the current item
-
- By default, for an empty combo box or a combo box in which no current
- item is set, this property contains an empty string.
-*/
-QString QComboBox::currentText() const
-{
- Q_D(const QComboBox);
- if (d->lineEdit)
- return d->lineEdit->text();
- else if (d->currentIndex.isValid())
- return d->itemText(d->currentIndex);
- else
- return QString();
-}
-
-/*!
- Returns the text for the given \a index in the combobox.
-*/
-QString QComboBox::itemText(int index) const
-{
- Q_D(const QComboBox);
- QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
- return d->itemText(mi);
-}
-
-/*!
- Returns the icon for the given \a index in the combobox.
-*/
-QIcon QComboBox::itemIcon(int index) const
-{
- Q_D(const QComboBox);
- QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
- return d->itemIcon(mi);
-}
-
-/*!
- Returns the data for the given \a role in the given \a index in the
- combobox, or QVariant::Invalid if there is no data for this role.
-*/
-QVariant QComboBox::itemData(int index, int role) const
-{
- Q_D(const QComboBox);
- QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
- return d->model->data(mi, role);
-}
-
-/*!
- \fn void QComboBox::insertItem(int index, const QString &text, const QVariant &userData)
-
- Inserts the \a text and \a userData (stored in the Qt::UserRole)
- into the combobox at the given \a index.
-
- If the index is equal to or higher than the total number of items,
- the new item is appended to the list of existing items. If the
- index is zero or negative, the new item is prepended to the list
- of existing items.
-
- \sa insertItems()
-*/
-
-/*!
-
- Inserts the \a icon, \a text and \a userData (stored in the
- Qt::UserRole) into the combobox at the given \a index.
-
- If the index is equal to or higher than the total number of items,
- the new item is appended to the list of existing items. If the
- index is zero or negative, the new item is prepended to the list
- of existing items.
-
- \sa insertItems()
-*/
-void QComboBox::insertItem(int index, const QIcon &icon, const QString &text, const QVariant &userData)
-{
- Q_D(QComboBox);
- int itemCount = count();
- index = qBound(0, index, itemCount);
- if (index >= d->maxCount)
- return;
-
- // For the common case where we are using the built in QStandardItemModel
- // construct a QStandardItem, reducing the number of expensive signals from the model
- if (QStandardItemModel *m = qobject_cast<QStandardItemModel*>(d->model)) {
- QStandardItem *item = new QStandardItem(text);
- if (!icon.isNull()) item->setData(icon, Qt::DecorationRole);
- if (userData.isValid()) item->setData(userData, Qt::UserRole);
- m->insertRow(index, item);
- ++itemCount;
- } else {
- d->inserting = true;
- if (d->model->insertRows(index, 1, d->root)) {
- QModelIndex item = d->model->index(index, d->modelColumn, d->root);
- if (icon.isNull() && !userData.isValid()) {
- d->model->setData(item, text, Qt::EditRole);
- } else {
- QMap<int, QVariant> values;
- if (!text.isNull()) values.insert(Qt::EditRole, text);
- if (!icon.isNull()) values.insert(Qt::DecorationRole, icon);
- if (userData.isValid()) values.insert(Qt::UserRole, userData);
- if (!values.isEmpty()) d->model->setItemData(item, values);
- }
- d->inserting = false;
- d->_q_rowsInserted(d->root, index, index);
- ++itemCount;
- } else {
- d->inserting = false;
- }
- }
-
- if (itemCount > d->maxCount)
- d->model->removeRows(itemCount - 1, itemCount - d->maxCount, d->root);
-}
-
-/*!
- Inserts the strings from the \a list into the combobox as separate items,
- starting at the \a index specified.
-
- If the index is equal to or higher than the total number of items, the new items
- are appended to the list of existing items. If the index is zero or negative, the
- new items are prepended to the list of existing items.
-
- \sa insertItem()
- */
-void QComboBox::insertItems(int index, const QStringList &list)
-{
- Q_D(QComboBox);
- if (list.isEmpty())
- return;
- index = qBound(0, index, count());
- int insertCount = qMin(d->maxCount - index, list.count());
- if (insertCount <= 0)
- return;
- // For the common case where we are using the built in QStandardItemModel
- // construct a QStandardItem, reducing the number of expensive signals from the model
- if (QStandardItemModel *m = qobject_cast<QStandardItemModel*>(d->model)) {
- QList<QStandardItem *> items;
- QStandardItem *hiddenRoot = m->invisibleRootItem();
- for (int i = 0; i < insertCount; ++i)
- items.append(new QStandardItem(list.at(i)));
- hiddenRoot->insertRows(index, items);
- } else {
- d->inserting = true;
- if (d->model->insertRows(index, insertCount, d->root)) {
- QModelIndex item;
- for (int i = 0; i < insertCount; ++i) {
- item = d->model->index(i+index, d->modelColumn, d->root);
- d->model->setData(item, list.at(i), Qt::EditRole);
- }
- d->inserting = false;
- d->_q_rowsInserted(d->root, index, index + insertCount - 1);
- } else {
- d->inserting = false;
- }
- }
-
- int mc = count();
- if (mc > d->maxCount)
- d->model->removeRows(d->maxCount, mc - d->maxCount, d->root);
-}
-
-/*!
- \since 4.4
-
- Inserts a separator item into the combobox at the given \a index.
-
- If the index is equal to or higher than the total number of items, the new item
- is appended to the list of existing items. If the index is zero or negative, the
- new item is prepended to the list of existing items.
-
- \sa insertItem()
-*/
-void QComboBox::insertSeparator(int index)
-{
- Q_D(QComboBox);
- int itemCount = count();
- index = qBound(0, index, itemCount);
- if (index >= d->maxCount)
- return;
- insertItem(index, QIcon(), QString());
- QComboBoxDelegate::setSeparator(d->model, d->model->index(index, 0, d->root));
-}
-
-/*!
- Removes the item at the given \a index from the combobox.
- This will update the current index if the index is removed.
-
- This function does nothing if \a index is out of range.
-*/
-void QComboBox::removeItem(int index)
-{
- Q_D(QComboBox);
- if (index < 0 || index >= count())
- return;
- d->model->removeRows(index, 1, d->root);
-}
-
-/*!
- Sets the \a text for the item on the given \a index in the combobox.
-*/
-void QComboBox::setItemText(int index, const QString &text)
-{
- Q_D(const QComboBox);
- QModelIndex item = d->model->index(index, d->modelColumn, d->root);
- if (item.isValid()) {
- d->model->setData(item, text, Qt::EditRole);
- }
-}
-
-/*!
- Sets the \a icon for the item on the given \a index in the combobox.
-*/
-void QComboBox::setItemIcon(int index, const QIcon &icon)
-{
- Q_D(const QComboBox);
- QModelIndex item = d->model->index(index, d->modelColumn, d->root);
- if (item.isValid()) {
- d->model->setData(item, icon, Qt::DecorationRole);
- }
-}
-
-/*!
- Sets the data \a role for the item on the given \a index in the combobox
- to the specified \a value.
-*/
-void QComboBox::setItemData(int index, const QVariant &value, int role)
-{
- Q_D(const QComboBox);
- QModelIndex item = d->model->index(index, d->modelColumn, d->root);
- if (item.isValid()) {
- d->model->setData(item, value, role);
- }
-}
-
-/*!
- Returns the list view used for the combobox popup.
-*/
-QAbstractItemView *QComboBox::view() const
-{
- Q_D(const QComboBox);
- return const_cast<QComboBoxPrivate*>(d)->viewContainer()->itemView();
-}
-
-/*!
- Sets the view to be used in the combobox popup to the given \a
- itemView. The combobox takes ownership of the view.
-
- Note: If you want to use the convenience views (like QListWidget,
- QTableWidget or QTreeWidget), make sure to call setModel() on the
- combobox with the convenience widgets model before calling this
- function.
-*/
-void QComboBox::setView(QAbstractItemView *itemView)
-{
- Q_D(QComboBox);
- if (!itemView) {
- qWarning("QComboBox::setView: cannot set a 0 view");
- return;
- }
-
- if (itemView->model() != d->model)
- itemView->setModel(d->model);
- d->viewContainer()->setItemView(itemView);
-}
-
-/*!
- \reimp
-*/
-QSize QComboBox::minimumSizeHint() const
-{
- Q_D(const QComboBox);
- return d->recomputeSizeHint(d->minimumSizeHint);
-}
-
-/*!
- \reimp
-
- This implementation caches the size hint to avoid resizing when
- the contents change dynamically. To invalidate the cached value
- change the \l sizeAdjustPolicy.
-*/
-QSize QComboBox::sizeHint() const
-{
- Q_D(const QComboBox);
- return d->recomputeSizeHint(d->sizeHint);
-}
-
-/*!
- Displays the list of items in the combobox. If the list is empty
- then the no items will be shown.
-
- If you reimplement this function to show a custom pop-up, make
- sure you call hidePopup() to reset the internal state.
-
- \sa hidePopup()
-*/
-void QComboBox::showPopup()
-{
- Q_D(QComboBox);
- if (count() <= 0)
- return;
-
-#ifdef QT_KEYPAD_NAVIGATION
-#ifndef QT_NO_COMPLETER
- if (QApplication::keypadNavigationEnabled() && d->completer) {
- // editable combo box is line edit plus completer
- setEditFocus(true);
- d->completer->complete(); // show popup
- return;
- }
-#endif
-#endif
-
- QStyle * const style = this->style();
-
- // set current item and select it
- view()->selectionModel()->setCurrentIndex(d->currentIndex,
- QItemSelectionModel::ClearAndSelect);
- QComboBoxPrivateContainer* container = d->viewContainer();
- QStyleOptionComboBox opt;
- initStyleOption(&opt);
- QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
- QStyle::SC_ComboBoxListBoxPopup, this));
-#ifndef Q_WS_S60
- QRect screen = d->popupGeometry(QApplication::desktop()->screenNumber(this));
-#else
- QRect screen = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect());
-#endif
-
- QPoint below = mapToGlobal(listRect.bottomLeft());
- int belowHeight = screen.bottom() - below.y();
- QPoint above = mapToGlobal(listRect.topLeft());
- int aboveHeight = above.y() - screen.y();
- bool boundToScreen = !window()->testAttribute(Qt::WA_DontShowOnScreen);
-
- const bool usePopup = style->styleHint(QStyle::SH_ComboBox_Popup, &opt, this);
- {
- int listHeight = 0;
- int count = 0;
- QStack<QModelIndex> toCheck;
- toCheck.push(view()->rootIndex());
-#ifndef QT_NO_TREEVIEW
- QTreeView *treeView = qobject_cast<QTreeView*>(view());
- if (treeView && treeView->header() && !treeView->header()->isHidden())
- listHeight += treeView->header()->height();
-#endif
- while (!toCheck.isEmpty()) {
- QModelIndex parent = toCheck.pop();
- for (int i = 0; i < d->model->rowCount(parent); ++i) {
- QModelIndex idx = d->model->index(i, d->modelColumn, parent);
- if (!idx.isValid())
- continue;
- listHeight += view()->visualRect(idx).height() + container->spacing();
-#ifndef QT_NO_TREEVIEW
- if (d->model->hasChildren(idx) && treeView && treeView->isExpanded(idx))
- toCheck.push(idx);
-#endif
- ++count;
- if (!usePopup && count >= d->maxVisibleItems) {
- toCheck.clear();
- break;
- }
- }
- }
- listRect.setHeight(listHeight);
- }
-
- {
- // add the spacing for the grid on the top and the bottom;
- int heightMargin = 2*container->spacing();
-
- // add the frame of the container
- int marginTop, marginBottom;
- container->getContentsMargins(0, &marginTop, 0, &marginBottom);
- heightMargin += marginTop + marginBottom;
-
- //add the frame of the view
- view()->getContentsMargins(0, &marginTop, 0, &marginBottom);
- marginTop += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top;
- marginBottom += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom;
- heightMargin += marginTop + marginBottom;
-
- listRect.setHeight(listRect.height() + heightMargin);
- }
-
- // Add space for margin at top and bottom if the style wants it.
- if (usePopup)
- listRect.setHeight(listRect.height() + style->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) * 2);
-
- // Make sure the popup is wide enough to display its contents.
- if (usePopup) {
- const int diff = d->computeWidthHint() - width();
- if (diff > 0)
- listRect.setWidth(listRect.width() + diff);
- }
-
- //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
- container->layout()->activate();
- //takes account of the minimum/maximum size of the container
- listRect.setSize( listRect.size().expandedTo(container->minimumSize())
- .boundedTo(container->maximumSize()));
-
- // make sure the widget fits on screen
- if (boundToScreen) {
- if (listRect.width() > screen.width() )
- listRect.setWidth(screen.width());
- if (mapToGlobal(listRect.bottomRight()).x() > screen.right()) {
- below.setX(screen.x() + screen.width() - listRect.width());
- above.setX(screen.x() + screen.width() - listRect.width());
- }
- if (mapToGlobal(listRect.topLeft()).x() < screen.x() ) {
- below.setX(screen.x());
- above.setX(screen.x());
- }
- }
-
- if (usePopup) {
- // Position horizontally.
- listRect.moveLeft(above.x());
-
-#ifndef Q_WS_S60
- // Position vertically so the curently selected item lines up
- // with the combo box.
- const QRect currentItemRect = view()->visualRect(view()->currentIndex());
- const int offset = listRect.top() - currentItemRect.top();
- listRect.moveTop(above.y() + offset - listRect.top());
-#endif
-
-
- // Clamp the listRect height and vertical position so we don't expand outside the
- // available screen geometry.This may override the vertical position, but it is more
- // important to show as much as possible of the popup.
- const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
- listRect.setHeight(height);
-
- if (boundToScreen) {
- if (listRect.top() < screen.top())
- listRect.moveTop(screen.top());
- if (listRect.bottom() > screen.bottom())
- listRect.moveBottom(screen.bottom());
- }
-#ifdef Q_WS_S60
- if (screen.width() < screen.height()) {
- // in portait, menu should be positioned above softkeys
- listRect.moveBottom(screen.bottom());
- } else {
- TRect staConTopRect = TRect();
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, staConTopRect);
- listRect.setWidth(listRect.height());
- //by default popup is centered on screen in landscape
- listRect.moveCenter(screen.center());
- if (staConTopRect.IsEmpty() && AknLayoutUtils::CbaLocation() != AknLayoutUtils::EAknCbaLocationBottom) {
- // landscape without stacon, menu should be at the right
- (opt.direction == Qt::LeftToRight) ? listRect.setRight(screen.right()) :
- listRect.setLeft(screen.left());
- }
- }
-#endif
- } else if (!boundToScreen || listRect.height() <= belowHeight) {
- listRect.moveTopLeft(below);
- } else if (listRect.height() <= aboveHeight) {
- listRect.moveBottomLeft(above);
- } else if (belowHeight >= aboveHeight) {
- listRect.setHeight(belowHeight);
- listRect.moveTopLeft(below);
- } else {
- listRect.setHeight(aboveHeight);
- listRect.moveBottomLeft(above);
- }
-
-#ifndef QT_NO_IM
- if (QInputContext *qic = inputContext())
- qic->reset();
-#endif
- QScrollBar *sb = view()->horizontalScrollBar();
- Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy();
- bool needHorizontalScrollBar = (policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn)
- && sb->minimum() < sb->maximum();
- if (needHorizontalScrollBar) {
- listRect.adjust(0, 0, 0, sb->height());
- }
- container->setGeometry(listRect);
-
-#ifndef Q_WS_MAC
- const bool updatesEnabled = container->updatesEnabled();
-#endif
-
-#if defined(Q_WS_WIN) && !defined(QT_NO_EFFECTS)
- bool scrollDown = (listRect.topLeft() == below);
- if (QApplication::isEffectEnabled(Qt::UI_AnimateCombo)
- && !style->styleHint(QStyle::SH_ComboBox_Popup, &opt, this) && !window()->testAttribute(Qt::WA_DontShowOnScreen))
- qScrollEffect(container, scrollDown ? QEffects::DownScroll : QEffects::UpScroll, 150);
-#endif
-
-// Don't disable updates on Mac OS X. Windows are displayed immediately on this platform,
-// which means that the window will be visible before the call to container->show() returns.
-// If updates are disabled at this point we'll miss our chance at painting the popup
-// menu before it's shown, causing flicker since the window then displays the standard gray
-// background.
-#ifndef Q_WS_MAC
- container->setUpdatesEnabled(false);
-#endif
-
- container->raise();
- container->show();
- container->updateScrollers();
- view()->setFocus();
-
- view()->scrollTo(view()->currentIndex(),
- style->styleHint(QStyle::SH_ComboBox_Popup, &opt, this)
- ? QAbstractItemView::PositionAtCenter
- : QAbstractItemView::EnsureVisible);
-
-#ifndef Q_WS_MAC
- container->setUpdatesEnabled(updatesEnabled);
-#endif
-
- container->update();
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- view()->setEditFocus(true);
-#endif
-}
-
-/*!
- Hides the list of items in the combobox if it is currently visible
- and resets the internal state, so that if the custom pop-up was
- shown inside the reimplemented showPopup(), then you also need to
- reimplement the hidePopup() function to hide your custom pop-up
- and call the base class implementation to reset the internal state
- whenever your custom pop-up widget is hidden.
-
- \sa showPopup()
-*/
-void QComboBox::hidePopup()
-{
- Q_D(QComboBox);
- if (d->container && d->container->isVisible()) {
-#if !defined(QT_NO_EFFECTS)
- d->model->blockSignals(true);
- d->container->itemView()->blockSignals(true);
- d->container->blockSignals(true);
- // Flash selected/triggered item (if any).
- if (style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)) {
- QItemSelectionModel *selectionModel = view() ? view()->selectionModel() : 0;
- if (selectionModel && selectionModel->hasSelection()) {
- QEventLoop eventLoop;
- const QItemSelection selection = selectionModel->selection();
-
- // Deselect item and wait 60 ms.
- selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(60, &eventLoop, SLOT(quit()));
- eventLoop.exec();
-
- // Select item and wait 20 ms.
- selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(20, &eventLoop, SLOT(quit()));
- eventLoop.exec();
- }
- }
-
- // Fade out.
- bool needFade = style()->styleHint(QStyle::SH_Menu_FadeOutOnHide);
- if (needFade) {
-#if defined(Q_WS_MAC)
- macWindowFade(qt_mac_window_for(d->container));
-#endif // Q_WS_MAC
- // Other platform implementations welcome :-)
- }
- d->model->blockSignals(false);
- d->container->itemView()->blockSignals(false);
- d->container->blockSignals(false);
-
- if (!needFade)
-#endif // QT_NO_EFFECTS
- // Fade should implicitly hide as well ;-)
- d->container->hide();
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && isEditable() && hasFocus())
- setEditFocus(true);
-#endif
- d->_q_resetButton();
-}
-
-/*!
- Clears the combobox, removing all items.
-
- Note: If you have set an external model on the combobox this model
- will still be cleared when calling this function.
-*/
-void QComboBox::clear()
-{
- Q_D(QComboBox);
- d->model->removeRows(0, d->model->rowCount(d->root), d->root);
-}
-
-/*!
- \fn void QComboBox::clearValidator()
-
- Use setValidator(0) instead.
-*/
-
-/*!
- Clears the contents of the line edit used for editing in the combobox.
-*/
-void QComboBox::clearEditText()
-{
- Q_D(QComboBox);
- if (d->lineEdit)
- d->lineEdit->clear();
-}
-
-/*!
- Sets the \a text in the combobox's text edit.
-*/
-void QComboBox::setEditText(const QString &text)
-{
- Q_D(QComboBox);
- if (d->lineEdit)
- d->lineEdit->setText(text);
-}
-
-/*!
- \reimp
-*/
-void QComboBox::focusInEvent(QFocusEvent *e)
-{
- Q_D(QComboBox);
- update();
- if (d->lineEdit) {
- d->lineEdit->event(e);
-#ifndef QT_NO_COMPLETER
- if (d->lineEdit->completer())
- d->lineEdit->completer()->setWidget(this);
-#endif
- }
-}
-
-/*!
- \reimp
-*/
-void QComboBox::focusOutEvent(QFocusEvent *e)
-{
- Q_D(QComboBox);
- update();
- if (d->lineEdit)
- d->lineEdit->event(e);
-}
-
-/*! \reimp */
-void QComboBox::changeEvent(QEvent *e)
-{
- Q_D(QComboBox);
- switch (e->type()) {
- case QEvent::StyleChange:
- d->updateDelegate();
-#ifdef Q_WS_MAC
- case QEvent::MacSizeChange:
-#endif
- d->sizeHint = QSize(); // invalidate size hint
- d->minimumSizeHint = QSize();
- d->updateLayoutDirection();
- if (d->lineEdit)
- d->updateLineEditGeometry();
- d->setLayoutItemMargins(QStyle::SE_ComboBoxLayoutItem);
-
-#ifdef Q_WS_S60
- if (d->container) {
- QStyleOptionComboBox opt;
- initStyleOption(&opt);
-
- if (style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, this)) {
- QRect screen = qt_TRect2QRect(static_cast<CEikAppUi*>(S60->appUi())->ClientRect());
-
- QRect listRect(style()->subControlRect(QStyle::CC_ComboBox, &opt,
- QStyle::SC_ComboBoxListBoxPopup, this));
- listRect.setHeight(qMin(screen.height(), screen.width()));
-
- if (screen.width() < screen.height()) {
- // in portait, menu should be positioned above softkeys
- listRect.moveBottom(screen.bottom());
- } else {
- TRect staConTopRect = TRect();
- AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, staConTopRect);
- listRect.setWidth(listRect.height());
- //by default popup is centered on screen in landscape
- listRect.moveCenter(screen.center());
- if (staConTopRect.IsEmpty() && AknLayoutUtils::CbaLocation() != AknLayoutUtils::EAknCbaLocationBottom) {
- // landscape without stacon, menu should be at the right
- (opt.direction == Qt::LeftToRight) ? listRect.setRight(screen.right()) :
- listRect.setLeft(screen.left());
- }
- }
-
- d->container->setGeometry(listRect);
- }
- }
-#endif
-
- // ### need to update scrollers etc. as well here
- break;
- case QEvent::EnabledChange:
- if (!isEnabled())
- hidePopup();
- break;
- case QEvent::PaletteChange: {
- d->updateViewContainerPaletteAndOpacity();
- break;
- }
- case QEvent::FontChange:
- d->sizeHint = QSize(); // invalidate size hint
- d->viewContainer()->setFont(font());
- if (d->lineEdit)
- d->updateLineEditGeometry();
- break;
- default:
- break;
- }
- QWidget::changeEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QComboBox::resizeEvent(QResizeEvent *)
-{
- Q_D(QComboBox);
-#ifdef Q_WS_S60
- if (d->viewContainer() && d->viewContainer()->isVisible())
- showPopup();
-#endif
- d->updateLineEditGeometry();
-}
-
-/*!
- \reimp
-*/
-void QComboBox::paintEvent(QPaintEvent *)
-{
- QStylePainter painter(this);
- painter.setPen(palette().color(QPalette::Text));
-
- // draw the combobox frame, focusrect and selected etc.
- QStyleOptionComboBox opt;
- initStyleOption(&opt);
- painter.drawComplexControl(QStyle::CC_ComboBox, opt);
-
- // draw the icon and text
- painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
-}
-
-/*!
- \reimp
-*/
-void QComboBox::showEvent(QShowEvent *e)
-{
- Q_D(QComboBox);
- if (!d->shownOnce && d->sizeAdjustPolicy == QComboBox::AdjustToContentsOnFirstShow) {
- d->sizeHint = QSize();
- updateGeometry();
- }
- d->shownOnce = true;
- QWidget::showEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QComboBox::hideEvent(QHideEvent *)
-{
- hidePopup();
-}
-
-/*!
- \reimp
-*/
-bool QComboBox::event(QEvent *event)
-{
- Q_D(QComboBox);
- switch(event->type()) {
- case QEvent::LayoutDirectionChange:
- case QEvent::ApplicationLayoutDirectionChange:
- d->updateLayoutDirection();
- d->updateLineEditGeometry();
- break;
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d->updateHoverControl(he->pos());
- break;
- case QEvent::ShortcutOverride:
- if (d->lineEdit)
- return d->lineEdit->event(event);
- break;
-#ifdef QT_KEYPAD_NAVIGATION
- case QEvent::EnterEditFocus:
- if (!d->lineEdit)
- setEditFocus(false); // We never want edit focus if we are not editable
- else
- d->lineEdit->event(event); //so cursor starts
- break;
- case QEvent::LeaveEditFocus:
- if (d->lineEdit)
- d->lineEdit->event(event); //so cursor stops
- break;
-#endif
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-void QComboBox::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QComboBox);
- QStyleOptionComboBox opt;
- initStyleOption(&opt);
- QStyle::SubControl sc = style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt, e->pos(),
- this);
- if (e->button() == Qt::LeftButton && (sc == QStyle::SC_ComboBoxArrow || !isEditable())
- && !d->viewContainer()->isVisible()) {
- if (sc == QStyle::SC_ComboBoxArrow)
- d->updateArrow(QStyle::State_Sunken);
-#ifdef QT_KEYPAD_NAVIGATION
- //if the container already exists, then d->viewContainer() is safe to call
- if (d->container) {
-#endif
- // We've restricted the next couple of lines, because by not calling
- // viewContainer(), we avoid creating the QComboBoxPrivateContainer.
- d->viewContainer()->blockMouseReleaseTimer.start(QApplication::doubleClickInterval());
- d->viewContainer()->initialClickPosition = mapToGlobal(e->pos());
-#ifdef QT_KEYPAD_NAVIGATION
- }
-#endif
- showPopup();
- } else {
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && sc == QStyle::SC_ComboBoxEditField && d->lineEdit) {
- d->lineEdit->event(e); //so lineedit can move cursor, etc
- return;
- }
-#endif
- QWidget::mousePressEvent(e);
- }
-}
-
-/*!
- \reimp
-*/
-void QComboBox::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QComboBox);
- Q_UNUSED(e);
- d->updateArrow(QStyle::State_None);
-}
-
-/*!
- \reimp
-*/
-void QComboBox::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QComboBox);
-
-#ifndef QT_NO_COMPLETER
- if (d->lineEdit
- && d->lineEdit->completer()
- && d->lineEdit->completer()->popup()
- && d->lineEdit->completer()->popup()->isVisible()) {
- // provide same autocompletion support as line edit
- d->lineEdit->event(e);
- return;
- }
-#endif
-
- enum Move { NoMove=0 , MoveUp , MoveDown , MoveFirst , MoveLast};
-
- Move move = NoMove;
- int newIndex = currentIndex();
- switch (e->key()) {
- case Qt::Key_Up:
- if (e->modifiers() & Qt::ControlModifier)
- break; // pass to line edit for auto completion
- case Qt::Key_PageUp:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- e->ignore();
- else
-#endif
- move = MoveUp;
- break;
- case Qt::Key_Down:
- if (e->modifiers() & Qt::AltModifier) {
- showPopup();
- return;
- } else if (e->modifiers() & Qt::ControlModifier)
- break; // pass to line edit for auto completion
- // fall through
- case Qt::Key_PageDown:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- e->ignore();
- else
-#endif
- move = MoveDown;
- break;
- case Qt::Key_Home:
- if (!d->lineEdit)
- move = MoveFirst;
- break;
- case Qt::Key_End:
- if (!d->lineEdit)
- move = MoveLast;
- break;
- case Qt::Key_F4:
- if (!e->modifiers()) {
- showPopup();
- return;
- }
- break;
- case Qt::Key_Space:
- if (!d->lineEdit) {
- showPopup();
- return;
- }
- case Qt::Key_Enter:
- case Qt::Key_Return:
- case Qt::Key_Escape:
- if (!d->lineEdit)
- e->ignore();
- break;
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()
- && (!hasEditFocus() || !d->lineEdit)) {
- showPopup();
- return;
- }
- break;
- case Qt::Key_Left:
- case Qt::Key_Right:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
- e->ignore();
- break;
- case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus() || !d->lineEdit)
- e->ignore();
- } else {
- e->ignore(); // let the surounding dialog have it
- }
- break;
-#endif
- default:
- if (!d->lineEdit) {
- if (!e->text().isEmpty())
- d->keyboardSearchString(e->text());
- else
- e->ignore();
- }
- }
-
- if (move != NoMove) {
- e->accept();
- switch (move) {
- case MoveFirst:
- newIndex = -1;
- case MoveDown:
- newIndex++;
- while ((newIndex < count()) && !(d->model->flags(d->model->index(newIndex,d->modelColumn,d->root)) & Qt::ItemIsEnabled))
- newIndex++;
- break;
- case MoveLast:
- newIndex = count();
- case MoveUp:
- newIndex--;
- while ((newIndex >= 0) && !(d->model->flags(d->model->index(newIndex,d->modelColumn,d->root)) & Qt::ItemIsEnabled))
- newIndex--;
- break;
- default:
- e->ignore();
- break;
- }
-
- if (newIndex >= 0 && newIndex < count() && newIndex != currentIndex()) {
- setCurrentIndex(newIndex);
- d->emitActivated(d->currentIndex);
- }
- } else if (d->lineEdit) {
- d->lineEdit->event(e);
- }
-}
-
-
-/*!
- \reimp
-*/
-void QComboBox::keyReleaseEvent(QKeyEvent *e)
-{
- Q_D(QComboBox);
- if (d->lineEdit)
- d->lineEdit->event(e);
-}
-
-/*!
- \reimp
-*/
-#ifndef QT_NO_WHEELEVENT
-void QComboBox::wheelEvent(QWheelEvent *e)
-{
- Q_D(QComboBox);
- if (!d->viewContainer()->isVisible()) {
- int newIndex = currentIndex();
-
- if (e->delta() > 0) {
- newIndex--;
- while ((newIndex >= 0) && !(d->model->flags(d->model->index(newIndex,d->modelColumn,d->root)) & Qt::ItemIsEnabled))
- newIndex--;
- } else {
- newIndex++;
- while ((newIndex < count()) && !(d->model->flags(d->model->index(newIndex,d->modelColumn,d->root)) & Qt::ItemIsEnabled))
- newIndex++;
- }
-
- if (newIndex >= 0 && newIndex < count() && newIndex != currentIndex()) {
- setCurrentIndex(newIndex);
- d->emitActivated(d->currentIndex);
- }
- e->accept();
- }
-}
-#endif
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \reimp
-*/
-void QComboBox::contextMenuEvent(QContextMenuEvent *e)
-{
- Q_D(QComboBox);
- if (d->lineEdit) {
- Qt::ContextMenuPolicy p = d->lineEdit->contextMenuPolicy();
- d->lineEdit->setContextMenuPolicy(Qt::DefaultContextMenu);
- d->lineEdit->event(e);
- d->lineEdit->setContextMenuPolicy(p);
- }
-}
-#endif // QT_NO_CONTEXTMENU
-
-void QComboBoxPrivate::keyboardSearchString(const QString &text)
-{
- // use keyboardSearch from the listView so we do not duplicate code
- QAbstractItemView *view = viewContainer()->itemView();
- view->setCurrentIndex(currentIndex);
- int currentRow = view->currentIndex().row();
- view->keyboardSearch(text);
- if (currentRow != view->currentIndex().row()) {
- setCurrentIndex(view->currentIndex());
- emitActivated(currentIndex);
- }
-}
-
-void QComboBoxPrivate::modelChanged()
-{
- Q_Q(QComboBox);
-
- if (sizeAdjustPolicy == QComboBox::AdjustToContents) {
- sizeHint = QSize();
- adjustComboBoxSize();
- q->updateGeometry();
- }
-}
-
-/*!
- \reimp
-*/
-void QComboBox::inputMethodEvent(QInputMethodEvent *e)
-{
- Q_D(QComboBox);
- if (d->lineEdit) {
- d->lineEdit->event(e);
- } else {
- if (!e->commitString().isEmpty())
- d->keyboardSearchString(e->commitString());
- else
- e->ignore();
- }
-}
-
-/*!
- \reimp
-*/
-QVariant QComboBox::inputMethodQuery(Qt::InputMethodQuery query) const
-{
- Q_D(const QComboBox);
- if (d->lineEdit)
- return d->lineEdit->inputMethodQuery(query);
- return QWidget::inputMethodQuery(query);
-}
-
-/*!
- \fn bool QComboBox::editable() const
-
- Use isEditable() instead.
-*/
-
-/*!
- \fn void QComboBox::insertItem(const QPixmap &pixmap, int index)
-
- Use an insertItem() function that takes a QIcon instead, for
- example, insertItem(index, QIcon(pixmap)).
-*/
-
-/*!
- \fn void QComboBox::insertItem(const QPixmap &pixmap, const QString &text, int index)
-
- Use an insertItem() function that takes a QIcon instead, for
- example, insertItem(index, QIcon(pixmap), text).
-
- \sa insertItems()
-*/
-
-/*!
- \fn void QComboBox::changeItem(const QString &text, int index)
-
- Use setItemText() instead.
-*/
-
-/*!
- \fn void QComboBox::changeItem(const QPixmap &pixmap, int index)
-
- Use setItemIcon() instead, for example,
- setItemIcon(index, QIcon(pixmap)).
-*/
-
-/*!
- \fn void QComboBox::changeItem(const QPixmap &pixmap, const QString &text, int index)
-
- Use setItem() instead, for example, setItem(index, QIcon(pixmap),text).
-*/
-
-/*!
- \fn void QComboBox::addItem(const QString &text, const QVariant &userData)
-
- Adds an item to the combobox with the given \a text, and
- containing the specified \a userData (stored in the Qt::UserRole).
- The item is appended to the list of existing items.
-*/
-
-/*!
- \fn void QComboBox::addItem(const QIcon &icon, const QString &text,
- const QVariant &userData)
-
- Adds an item to the combobox with the given \a icon and \a text,
- and containing the specified \a userData (stored in the
- Qt::UserRole). The item is appended to the list of existing items.
-*/
-
-/*!
- \fn void QComboBox::addItems(const QStringList &texts)
-
- Adds each of the strings in the given \a texts to the combobox. Each item
- is appended to the list of existing items in turn.
-*/
-
-/*!
- \fn void QComboBox::editTextChanged(const QString &text)
-
- This signal is emitted when the text in the combobox's line edit
- widget is changed. The new text is specified by \a text.
-*/
-
-/*!
- \fn QComboBox::InsertPolicy QComboBox::insertionPolicy() const
- \compat
-
- Use QComboBox::insertPolicy instead.
-*/
-
-/*!
- \fn void QComboBox::setInsertionPolicy(InsertPolicy policy)
- \compat
-
- Use QComboBox::insertPolicy instead.
-*/
-
-/*!
- \fn void QComboBox::setCurrentText(const QString &text)
- \compat
-
- Use setItemText() instead.
-
- \sa currentIndex()
-*/
-
-/*!
- \fn QString QComboBox::text(int index) const
- \compat
-
- Use itemText() instead.
-*/
-
-/*!
- \fn QPixmap QComboBox::pixmap(int index) const
- \compat
-
- Use itemIcon() instead.
-*/
-
-/*!
- \fn void QComboBox::insertStringList(const QStringList &list, int index)
- \compat
-
- Use insertItems() instead.
-*/
-
-/*!
- \fn void QComboBox::insertItem(const QString &text, int index)
- \compat
-*/
-
-/*!
- \fn void QComboBox::clearEdit()
- \compat
-
- Use clearEditText() instead.
-*/
-
-
-/*!
- \property QComboBox::frame
- \brief whether the combo box draws itself with a frame
-
-
- If enabled (the default) the combo box draws itself inside a
- frame, otherwise the combo box draws itself without any frame.
-*/
-bool QComboBox::hasFrame() const
-{
- Q_D(const QComboBox);
- return d->frame;
-}
-
-
-void QComboBox::setFrame(bool enable)
-{
- Q_D(QComboBox);
- d->frame = enable;
- update();
- updateGeometry();
-}
-
-/*!
- \property QComboBox::modelColumn
- \brief the column in the model that is visible.
-
- If set prior to populating the combo box, the pop-up view will
- not be affected and will show the first column (using this property's
- default value).
-
- By default, this property has a value of 0.
-*/
-int QComboBox::modelColumn() const
-{
- Q_D(const QComboBox);
- return d->modelColumn;
-}
-
-void QComboBox::setModelColumn(int visibleColumn)
-{
- Q_D(QComboBox);
- d->modelColumn = visibleColumn;
- QListView *lv = qobject_cast<QListView *>(d->viewContainer()->itemView());
- if (lv)
- lv->setModelColumn(visibleColumn);
-#ifndef QT_NO_COMPLETER
- if (d->lineEdit && d->lineEdit->completer()
- && d->lineEdit->completer() == d->completer)
- d->lineEdit->completer()->setCompletionColumn(visibleColumn);
-#endif
- setCurrentIndex(currentIndex()); //update the text to the text of the new column;
-}
-
-/*!
- \fn int QComboBox::currentItem() const
-
- Use currentIndex() instead.
-*/
-
-/*!
- \fn void QComboBox::setCurrentItem(int)
-
- Use setCurrentIndex(int) instead.
-*/
-
-/*!
- \fn void QComboBox::popup()
-
- Use showPopup() instead.
-*/
-
-/*!
- \fn void QComboBox::textChanged(const QString &text)
-
- Use the editTextChanged(const QString &text) signal instead.
-*/
-
-/*!
- \typedef QComboBox::Policy
- \compat
-
- Use QComboBox::InsertPolicy instead.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qcombobox.cpp"
-
-#endif // QT_NO_COMBOBOX
diff --git a/src/gui/widgets/qcombobox.h b/src/gui/widgets/qcombobox.h
deleted file mode 100644
index fd6f68af2d..0000000000
--- a/src/gui/widgets/qcombobox.h
+++ /dev/null
@@ -1,339 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMBOBOX_H
-#define QCOMBOBOX_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qabstractitemdelegate.h>
-#include <QtCore/qabstractitemmodel.h>
-#include <QtCore/qvariant.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-#ifndef QT_NO_COMBOBOX
-
-class QAbstractItemView;
-class QLineEdit;
-class QComboBoxPrivate;
-class QCompleter;
-
-class Q_GUI_EXPORT QComboBox : public QWidget
-{
- Q_OBJECT
-
- Q_ENUMS(InsertPolicy)
- Q_ENUMS(SizeAdjustPolicy)
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- Q_PROPERTY(int count READ count)
- Q_PROPERTY(QString currentText READ currentText)
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged USER true)
- Q_PROPERTY(int maxVisibleItems READ maxVisibleItems WRITE setMaxVisibleItems)
- Q_PROPERTY(int maxCount READ maxCount WRITE setMaxCount)
- Q_PROPERTY(InsertPolicy insertPolicy READ insertPolicy WRITE setInsertPolicy)
- Q_PROPERTY(SizeAdjustPolicy sizeAdjustPolicy READ sizeAdjustPolicy WRITE setSizeAdjustPolicy)
- Q_PROPERTY(int minimumContentsLength READ minimumContentsLength WRITE setMinimumContentsLength)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
-
-#ifndef QT_NO_COMPLETER
- Q_PROPERTY(bool autoCompletion READ autoCompletion WRITE setAutoCompletion DESIGNABLE false)
- Q_PROPERTY(Qt::CaseSensitivity autoCompletionCaseSensitivity READ autoCompletionCaseSensitivity WRITE setAutoCompletionCaseSensitivity DESIGNABLE false)
-#endif // QT_NO_COMPLETER
-
- Q_PROPERTY(bool duplicatesEnabled READ duplicatesEnabled WRITE setDuplicatesEnabled)
- Q_PROPERTY(bool frame READ hasFrame WRITE setFrame)
- Q_PROPERTY(int modelColumn READ modelColumn WRITE setModelColumn)
-
-public:
- explicit QComboBox(QWidget *parent = 0);
- ~QComboBox();
-
- int maxVisibleItems() const;
- void setMaxVisibleItems(int maxItems);
-
- int count() const;
- void setMaxCount(int max);
- int maxCount() const;
-
-#ifndef QT_NO_COMPLETER
- bool autoCompletion() const;
- void setAutoCompletion(bool enable);
-
- Qt::CaseSensitivity autoCompletionCaseSensitivity() const;
- void setAutoCompletionCaseSensitivity(Qt::CaseSensitivity sensitivity);
-#endif
-
- bool duplicatesEnabled() const;
- void setDuplicatesEnabled(bool enable);
-
- void setFrame(bool);
- bool hasFrame() const;
-
- inline int findText(const QString &text,
- Qt::MatchFlags flags = static_cast<Qt::MatchFlags>(Qt::MatchExactly|Qt::MatchCaseSensitive)) const
- { return findData(text, Qt::DisplayRole, flags); }
- int findData(const QVariant &data, int role = Qt::UserRole,
- Qt::MatchFlags flags = static_cast<Qt::MatchFlags>(Qt::MatchExactly|Qt::MatchCaseSensitive)) const;
-
- enum InsertPolicy {
- NoInsert,
- InsertAtTop,
- InsertAtCurrent,
- InsertAtBottom,
- InsertAfterCurrent,
- InsertBeforeCurrent,
- InsertAlphabetically
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- ,
- NoInsertion = NoInsert,
- AtTop = InsertAtTop,
- AtCurrent = InsertAtCurrent,
- AtBottom = InsertAtBottom,
- AfterCurrent = InsertAfterCurrent,
- BeforeCurrent = InsertBeforeCurrent
-#endif
- };
-#ifdef QT3_SUPPORT
- typedef InsertPolicy Policy;
-#endif
-
- InsertPolicy insertPolicy() const;
- void setInsertPolicy(InsertPolicy policy);
-
- enum SizeAdjustPolicy {
- AdjustToContents,
- AdjustToContentsOnFirstShow,
- AdjustToMinimumContentsLength, // ### Qt 5: remove
- AdjustToMinimumContentsLengthWithIcon
- };
-
- SizeAdjustPolicy sizeAdjustPolicy() const;
- void setSizeAdjustPolicy(SizeAdjustPolicy policy);
- int minimumContentsLength() const;
- void setMinimumContentsLength(int characters);
- QSize iconSize() const;
- void setIconSize(const QSize &size);
-
- bool isEditable() const;
- void setEditable(bool editable);
- void setLineEdit(QLineEdit *edit);
- QLineEdit *lineEdit() const;
-#ifndef QT_NO_VALIDATOR
- void setValidator(const QValidator *v);
- const QValidator *validator() const;
-#endif
-
-#ifndef QT_NO_COMPLETER
- void setCompleter(QCompleter *c);
- QCompleter *completer() const;
-#endif
-
- QAbstractItemDelegate *itemDelegate() const;
- void setItemDelegate(QAbstractItemDelegate *delegate);
-
- QAbstractItemModel *model() const;
- void setModel(QAbstractItemModel *model);
-
- QModelIndex rootModelIndex() const;
- void setRootModelIndex(const QModelIndex &index);
-
- int modelColumn() const;
- void setModelColumn(int visibleColumn);
-
- int currentIndex() const;
-
- QString currentText() const;
-
- QString itemText(int index) const;
- QIcon itemIcon(int index) const;
- QVariant itemData(int index, int role = Qt::UserRole) const;
-
- inline void addItem(const QString &text, const QVariant &userData = QVariant());
- inline void addItem(const QIcon &icon, const QString &text,
- const QVariant &userData = QVariant());
- inline void addItems(const QStringList &texts)
- { insertItems(count(), texts); }
-
- inline void insertItem(int index, const QString &text, const QVariant &userData = QVariant());
- void insertItem(int index, const QIcon &icon, const QString &text,
- const QVariant &userData = QVariant());
- void insertItems(int index, const QStringList &texts);
- void insertSeparator(int index);
-
- void removeItem(int index);
-
- void setItemText(int index, const QString &text);
- void setItemIcon(int index, const QIcon &icon);
- void setItemData(int index, const QVariant &value, int role = Qt::UserRole);
-
- QAbstractItemView *view() const;
- void setView(QAbstractItemView *itemView);
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- virtual void showPopup();
- virtual void hidePopup();
-
- bool event(QEvent *event);
-
-public Q_SLOTS:
- void clear();
- void clearEditText();
- void setEditText(const QString &text);
- void setCurrentIndex(int index);
-
-Q_SIGNALS:
- void editTextChanged(const QString &);
- void activated(int index);
- void activated(const QString &);
- void highlighted(int index);
- void highlighted(const QString &);
- void currentIndexChanged(int index);
- void currentIndexChanged(const QString &);
-
-protected:
- void focusInEvent(QFocusEvent *e);
- void focusOutEvent(QFocusEvent *e);
- void changeEvent(QEvent *e);
- void resizeEvent(QResizeEvent *e);
- void paintEvent(QPaintEvent *e);
- void showEvent(QShowEvent *e);
- void hideEvent(QHideEvent *e);
- void mousePressEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
- void keyPressEvent(QKeyEvent *e);
- void keyReleaseEvent(QKeyEvent *e);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *e);
-#endif
- void contextMenuEvent(QContextMenuEvent *e);
- void inputMethodEvent(QInputMethodEvent *);
- QVariant inputMethodQuery(Qt::InputMethodQuery) const;
- void initStyleOption(QStyleOptionComboBox *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QComboBox(QWidget *parent, const char *name);
- QT3_SUPPORT_CONSTRUCTOR QComboBox(bool rw, QWidget *parent, const char *name = 0);
- inline QT3_SUPPORT int currentItem() const { return currentIndex(); }
- inline QT3_SUPPORT void setCurrentItem(int index) { setCurrentIndex(index); }
- inline QT3_SUPPORT InsertPolicy insertionPolicy() const { return insertPolicy(); }
- inline QT3_SUPPORT void setInsertionPolicy(InsertPolicy policy) { setInsertPolicy(policy); }
- inline QT3_SUPPORT bool editable() const { return isEditable(); }
- inline QT3_SUPPORT void popup() { showPopup(); }
- inline QT3_SUPPORT void setCurrentText(const QString& text) {
- int i = findText(text);
- if (i != -1)
- setCurrentIndex(i);
- else if (isEditable())
- setEditText(text);
- else
- setItemText(currentIndex(), text);
- }
- inline QT3_SUPPORT QString text(int index) const { return itemText(index); }
-
- inline QT3_SUPPORT QPixmap pixmap(int index) const
- { return itemIcon(index).pixmap(iconSize(), isEnabled() ? QIcon::Normal : QIcon::Disabled); }
- inline QT3_SUPPORT void insertStringList(const QStringList &list, int index = -1)
- { insertItems((index < 0 ? count() : index), list); }
- inline QT3_SUPPORT void insertItem(const QString &text, int index = -1)
- { insertItem((index < 0 ? count() : index), text); }
- inline QT3_SUPPORT void insertItem(const QPixmap &pix, int index = -1)
- { insertItem((index < 0 ? count() : index), QIcon(pix), QString()); }
- inline QT3_SUPPORT void insertItem(const QPixmap &pix, const QString &text, int index = -1)
- { insertItem((index < 0 ? count() : index), QIcon(pix), text); }
- inline QT3_SUPPORT void changeItem(const QString &text, int index)
- { setItemText(index, text); }
- inline QT3_SUPPORT void changeItem(const QPixmap &pix, int index)
- { setItemIcon(index, QIcon(pix)); }
- inline QT3_SUPPORT void changeItem(const QPixmap &pix, const QString &text, int index)
- { setItemIcon(index, QIcon(pix)); setItemText(index, text); }
- inline QT3_SUPPORT void clearValidator() { setValidator(0); }
- inline QT3_SUPPORT void clearEdit() { clearEditText(); }
-
-Q_SIGNALS:
- QT_MOC_COMPAT void textChanged(const QString &);
-#endif
-
-protected:
- QComboBox(QComboBoxPrivate &, QWidget *);
-
-private:
- Q_DECLARE_PRIVATE(QComboBox)
- Q_DISABLE_COPY(QComboBox)
- Q_PRIVATE_SLOT(d_func(), void _q_itemSelected(const QModelIndex &item))
- Q_PRIVATE_SLOT(d_func(), void _q_emitHighlighted(const QModelIndex &))
- Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentIndexChanged(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_editingFinished())
- Q_PRIVATE_SLOT(d_func(), void _q_returnPressed())
- Q_PRIVATE_SLOT(d_func(), void _q_resetButton())
- Q_PRIVATE_SLOT(d_func(), void _q_dataChanged(const QModelIndex &, const QModelIndex &))
- Q_PRIVATE_SLOT(d_func(), void _q_updateIndexBeforeChange())
- Q_PRIVATE_SLOT(d_func(), void _q_rowsInserted(const QModelIndex & parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_rowsRemoved(const QModelIndex & parent, int start, int end))
- Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed())
- Q_PRIVATE_SLOT(d_func(), void _q_modelReset())
-#ifdef QT_KEYPAD_NAVIGATION
- Q_PRIVATE_SLOT(d_func(), void _q_completerActivated())
-#endif
-};
-
-inline void QComboBox::addItem(const QString &atext, const QVariant &auserData)
-{ insertItem(count(), atext, auserData); }
-inline void QComboBox::addItem(const QIcon &aicon, const QString &atext,
- const QVariant &auserData)
-{ insertItem(count(), aicon, atext, auserData); }
-
-inline void QComboBox::insertItem(int aindex, const QString &atext,
- const QVariant &auserData)
-{ insertItem(aindex, QIcon(), atext, auserData); }
-
-#endif // QT_NO_COMBOBOX
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOMBOBOX_H
diff --git a/src/gui/widgets/qcombobox_p.h b/src/gui/widgets/qcombobox_p.h
deleted file mode 100644
index cd84b87564..0000000000
--- a/src/gui/widgets/qcombobox_p.h
+++ /dev/null
@@ -1,421 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMBOBOX_P_H
-#define QCOMBOBOX_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qcombobox.h"
-
-#ifndef QT_NO_COMBOBOX
-#include "QtGui/qabstractslider.h"
-#include "QtGui/qapplication.h"
-#include "QtGui/qitemdelegate.h"
-#include "QtGui/qstandarditemmodel.h"
-#include "QtGui/qlineedit.h"
-#include "QtGui/qlistview.h"
-#include "QtGui/qpainter.h"
-#include "QtGui/qstyle.h"
-#include "QtGui/qstyleoption.h"
-#include "QtCore/qhash.h"
-#include "QtCore/qpair.h"
-#include "QtCore/qtimer.h"
-#include "private/qwidget_p.h"
-#include "QtCore/qpointer.h"
-#include "QtGui/qcompleter.h"
-#include "QtGui/qevent.h"
-#include "QtCore/qdebug.h"
-
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-class QAction;
-
-class QComboBoxListView : public QListView
-{
- Q_OBJECT
-public:
- QComboBoxListView(QComboBox *cmb = 0) : combo(cmb) {}
-
-protected:
- void resizeEvent(QResizeEvent *event)
- {
- resizeContents(viewport()->width(), contentsSize().height());
- QListView::resizeEvent(event);
- }
-
- QStyleOptionViewItem viewOptions() const
- {
- QStyleOptionViewItem option = QListView::viewOptions();
- option.showDecorationSelected = true;
- if (combo)
- option.font = combo->font();
- return option;
- }
-
- void paintEvent(QPaintEvent *e)
- {
- if (combo) {
- QStyleOptionComboBox opt;
- opt.initFrom(combo);
- opt.editable = combo->isEditable();
- if (combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo)) {
- //we paint the empty menu area to avoid having blank space that can happen when scrolling
- QStyleOptionMenuItem menuOpt;
- menuOpt.initFrom(this);
- menuOpt.palette = palette();
- menuOpt.state = QStyle::State_None;
- menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
- menuOpt.menuRect = e->rect();
- menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
- QPainter p(viewport());
- combo->style()->drawControl(QStyle::CE_MenuEmptyArea, &menuOpt, &p, this);
- }
- }
- QListView::paintEvent(e);
- }
-
-private:
- QComboBox *combo;
-};
-
-
-class QStandardItemModel;
-
-class Q_AUTOTEST_EXPORT QComboBoxPrivateScroller : public QWidget
-{
- Q_OBJECT
-
-public:
- QComboBoxPrivateScroller(QAbstractSlider::SliderAction action, QWidget *parent)
- : QWidget(parent), sliderAction(action)
- {
- setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
- setAttribute(Qt::WA_NoMousePropagation);
- }
- QSize sizeHint() const {
- return QSize(20, style()->pixelMetric(QStyle::PM_MenuScrollerHeight));
- }
-
-protected:
- inline void stopTimer() {
- timer.stop();
- }
-
- inline void startTimer() {
- timer.start(100, this);
- fast = false;
- }
-
- void enterEvent(QEvent *) {
- startTimer();
- }
-
- void leaveEvent(QEvent *) {
- stopTimer();
- }
- void timerEvent(QTimerEvent *e) {
- if (e->timerId() == timer.timerId()) {
- emit doScroll(sliderAction);
- if (fast) {
- emit doScroll(sliderAction);
- emit doScroll(sliderAction);
- }
- }
- }
- void hideEvent(QHideEvent *) {
- stopTimer();
- }
-
- void mouseMoveEvent(QMouseEvent *e)
- {
- // Enable fast scrolling if the cursor is directly above or below the popup.
- const int mouseX = e->pos().x();
- const int mouseY = e->pos().y();
- const bool horizontallyInside = pos().x() < mouseX && mouseX < rect().right() + 1;
- const bool verticallyOutside = (sliderAction == QAbstractSlider::SliderSingleStepAdd) ?
- rect().bottom() + 1 < mouseY : mouseY < pos().y();
-
- fast = horizontallyInside && verticallyOutside;
- }
-
- void paintEvent(QPaintEvent *) {
- QPainter p(this);
- QStyleOptionMenuItem menuOpt;
- menuOpt.init(this);
- menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
- menuOpt.menuRect = rect();
- menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
- menuOpt.menuItemType = QStyleOptionMenuItem::Scroller;
- if (sliderAction == QAbstractSlider::SliderSingleStepAdd)
- menuOpt.state |= QStyle::State_DownArrow;
-#ifndef Q_WS_S60
- p.eraseRect(rect());
-#endif
- style()->drawControl(QStyle::CE_MenuScroller, &menuOpt, &p);
- }
-
-Q_SIGNALS:
- void doScroll(int action);
-
-private:
- QAbstractSlider::SliderAction sliderAction;
- QBasicTimer timer;
- bool fast;
-};
-
-class Q_AUTOTEST_EXPORT QComboBoxPrivateContainer : public QFrame
-{
- Q_OBJECT
-
-public:
- QComboBoxPrivateContainer(QAbstractItemView *itemView, QComboBox *parent);
- QAbstractItemView *itemView() const;
- void setItemView(QAbstractItemView *itemView);
- int spacing() const;
- void updateTopBottomMargin();
-
- QTimer blockMouseReleaseTimer;
- QBasicTimer adjustSizeTimer;
- QPoint initialClickPosition;
-
-public Q_SLOTS:
- void scrollItemView(int action);
- void updateScrollers();
- void viewDestroyed();
-
-protected:
- void changeEvent(QEvent *e);
- bool eventFilter(QObject *o, QEvent *e);
- void mousePressEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *e);
- void showEvent(QShowEvent *e);
- void hideEvent(QHideEvent *e);
- void timerEvent(QTimerEvent *timerEvent);
- void leaveEvent(QEvent *e);
- void resizeEvent(QResizeEvent *e);
- QStyleOptionComboBox comboStyleOption() const;
-
-Q_SIGNALS:
- void itemSelected(const QModelIndex &);
- void resetButton();
-
-private:
- QComboBox *combo;
- QAbstractItemView *view;
- QComboBoxPrivateScroller *top;
- QComboBoxPrivateScroller *bottom;
-#ifdef QT_SOFTKEYS_ENABLED
- QAction *selectAction;
- QAction *cancelAction;
-#endif
-};
-
-class QComboMenuDelegate : public QAbstractItemDelegate
-{ Q_OBJECT
-public:
- QComboMenuDelegate(QObject *parent, QComboBox *cmb) : QAbstractItemDelegate(parent), mCombo(cmb) {}
-
-protected:
- void paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const {
- QStyleOptionMenuItem opt = getStyleOption(option, index);
-#ifndef Q_WS_S60
- painter->fillRect(option.rect, opt.palette.background());
-#endif
- mCombo->style()->drawControl(QStyle::CE_MenuItem, &opt, painter, mCombo);
- }
- QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const {
- QStyleOptionMenuItem opt = getStyleOption(option, index);
- return mCombo->style()->sizeFromContents(
- QStyle::CT_MenuItem, &opt, option.rect.size(), mCombo);
- }
-
-private:
- QStyleOptionMenuItem getStyleOption(const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
- QComboBox *mCombo;
-};
-
-// Note that this class is intentionally not using QStyledItemDelegate
-// Vista does not use the new theme for combo boxes and there might
-// be other side effects from using the new class
-class QComboBoxDelegate : public QItemDelegate
-{ Q_OBJECT
-public:
- QComboBoxDelegate(QObject *parent, QComboBox *cmb) : QItemDelegate(parent), mCombo(cmb) {}
-
- static bool isSeparator(const QModelIndex &index) {
- return index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator");
- }
- static void setSeparator(QAbstractItemModel *model, const QModelIndex &index) {
- model->setData(index, QString::fromLatin1("separator"), Qt::AccessibleDescriptionRole);
- if (QStandardItemModel *m = qobject_cast<QStandardItemModel*>(model))
- if (QStandardItem *item = m->itemFromIndex(index))
- item->setFlags(item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled));
- }
-
-protected:
- void paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const {
- if (isSeparator(index)) {
- QRect rect = option.rect;
- if (const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3*>(&option))
- if (const QAbstractItemView *view = qobject_cast<const QAbstractItemView*>(v3->widget))
- rect.setWidth(view->viewport()->width());
- QStyleOption opt;
- opt.rect = rect;
- mCombo->style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &opt, painter, mCombo);
- } else {
- QItemDelegate::paint(painter, option, index);
- }
- }
-
- QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const {
- if (isSeparator(index)) {
- int pm = mCombo->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, mCombo);
- return QSize(pm, pm);
- }
- return QItemDelegate::sizeHint(option, index);
- }
-private:
- QComboBox *mCombo;
-};
-
-class Q_AUTOTEST_EXPORT QComboBoxPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QComboBox)
-public:
- QComboBoxPrivate();
- ~QComboBoxPrivate() {}
- void init();
- QComboBoxPrivateContainer* viewContainer();
- void updateLineEditGeometry();
- Qt::MatchFlags matchFlags() const;
- void _q_editingFinished();
- void _q_returnPressed();
- void _q_complete();
- void _q_itemSelected(const QModelIndex &item);
- bool contains(const QString &text, int role);
- void emitActivated(const QModelIndex&);
- void _q_emitHighlighted(const QModelIndex&);
- void _q_emitCurrentIndexChanged(const QModelIndex &index);
- void _q_modelDestroyed();
- void _q_modelReset();
-#ifdef QT_KEYPAD_NAVIGATION
- void _q_completerActivated();
-#endif
- void _q_resetButton();
- void _q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
- void _q_updateIndexBeforeChange();
- void _q_rowsInserted(const QModelIndex & parent, int start, int end);
- void _q_rowsRemoved(const QModelIndex & parent, int start, int end);
- void updateArrow(QStyle::StateFlag state);
- bool updateHoverControl(const QPoint &pos);
- QRect popupGeometry(int screen = -1) const;
- QStyle::SubControl newHoverControl(const QPoint &pos);
- int computeWidthHint() const;
- QSize recomputeSizeHint(QSize &sh) const;
- void adjustComboBoxSize();
- QString itemText(const QModelIndex &index) const;
- QIcon itemIcon(const QModelIndex &index) const;
- int itemRole() const;
- void updateLayoutDirection();
- void setCurrentIndex(const QModelIndex &index);
- void updateDelegate(bool force = false);
- void keyboardSearchString(const QString &text);
- void modelChanged();
- void updateViewContainerPaletteAndOpacity();
-
- QAbstractItemModel *model;
- QLineEdit *lineEdit;
- QComboBoxPrivateContainer *container;
- QComboBox::InsertPolicy insertPolicy;
- QComboBox::SizeAdjustPolicy sizeAdjustPolicy;
- int minimumContentsLength;
- QSize iconSize;
- uint shownOnce : 1;
- uint autoCompletion : 1;
- uint duplicatesEnabled : 1;
- uint frame : 1;
- uint padding : 26;
- int maxVisibleItems;
- int maxCount;
- int modelColumn;
- bool inserting;
- mutable QSize minimumSizeHint;
- mutable QSize sizeHint;
- QStyle::StateFlag arrowState;
- QStyle::SubControl hoverControl;
- QRect hoverRect;
- QPersistentModelIndex currentIndex;
- QPersistentModelIndex root;
- Qt::CaseSensitivity autoCompletionCaseSensitivity;
- int indexBeforeChange;
-#ifndef QT_NO_COMPLETER
- QPointer<QCompleter> completer;
-#endif
- static QPalette viewContainerPalette(QComboBox *cmb)
- { return cmb->d_func()->viewContainer()->palette(); }
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_COMBOBOX
-
-#endif // QCOMBOBOX_P_H
diff --git a/src/gui/widgets/qcommandlinkbutton.cpp b/src/gui/widgets/qcommandlinkbutton.cpp
deleted file mode 100644
index f1734a009e..0000000000
--- a/src/gui/widgets/qcommandlinkbutton.cpp
+++ /dev/null
@@ -1,410 +0,0 @@
-/****************************************************************************
-**
-** 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 "qcommandlinkbutton.h"
-#include "qstylepainter.h"
-#include "qstyleoption.h"
-#include "qtextdocument.h"
-#include "qtextlayout.h"
-#include "qcolor.h"
-#include "qfont.h"
-#include <qmath.h>
-
-#include "private/qpushbutton_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QCommandLinkButton
- \since 4.4
- \brief The QCommandLinkButton widget provides a Vista style command link button.
-
- \ingroup basicwidgets
-
-
- The command link is a new control that was introduced by Windows Vista. It's
- intended use is similar to that of a radio button in that it is used to choose
- between a set of mutually exclusive options. Command link buttons should not
- be used by themselves but rather as an alternative to radio buttons in
- Wizards and dialogs and makes pressing the "next" button redundant.
- The appearance is generally similar to that of a flat pushbutton, but
- it allows for a descriptive text in addition to the normal button text.
- By default it will also carry an arrow icon, indicating that pressing the
- control will open another window or page.
-
- \sa QPushButton QRadioButton
-*/
-
-/*!
- \property QCommandLinkButton::description
- \brief A descriptive label to complement the button text
-
- Setting this property will set a descriptive text on the
- button, complementing the text label. This will usually
- be displayed in a smaller font than the primary text.
-*/
-
-/*!
- \property QCommandLinkButton::flat
- \brief This property determines whether the button is displayed as a flat
- panel or with a border.
-
- By default, this property is set to false.
-
- \sa QPushButton::flat
-*/
-
-class QCommandLinkButtonPrivate : public QPushButtonPrivate
-{
- Q_DECLARE_PUBLIC(QCommandLinkButton)
-
-public:
- QCommandLinkButtonPrivate()
- : QPushButtonPrivate(){}
-
- void init();
- qreal titleSize() const;
- bool usingVistaStyle() const;
-
- QFont titleFont() const;
- QFont descriptionFont() const;
-
- QRect titleRect() const;
- QRect descriptionRect() const;
-
- int textOffset() const;
- int descriptionOffset() const;
- int descriptionHeight(int width) const;
- QColor mergedColors(const QColor &a, const QColor &b, int value) const;
-
- int topMargin() const { return 10; }
- int leftMargin() const { return 7; }
- int rightMargin() const { return 4; }
- int bottomMargin() const { return 10; }
-
- QString description;
- QColor currentColor;
-};
-
-// Mix colors a and b with a ratio in the range [0-255]
-QColor QCommandLinkButtonPrivate::mergedColors(const QColor &a, const QColor &b, int value = 50) const
-{
- Q_ASSERT(value >= 0);
- Q_ASSERT(value <= 255);
- QColor tmp = a;
- tmp.setRed((tmp.red() * value) / 255 + (b.red() * (255 - value)) / 255);
- tmp.setGreen((tmp.green() * value) / 255 + (b.green() * (255 - value)) / 255);
- tmp.setBlue((tmp.blue() * value) / 255 + (b.blue() * (255 - value)) / 255);
- return tmp;
-}
-
-QFont QCommandLinkButtonPrivate::titleFont() const
-{
- Q_Q(const QCommandLinkButton);
- QFont font = q->font();
- if (usingVistaStyle()) {
- font.setPointSizeF(12.0);
- } else {
- font.setBold(true);
- font.setPointSizeF(9.0);
- }
-
- // Note the font will be resolved against
- // QPainters font, so we need to restore the mask
- int resolve_mask = font.resolve_mask;
- QFont modifiedFont = q->font().resolve(font);
- modifiedFont.detach();
- modifiedFont.resolve_mask = resolve_mask;
- return modifiedFont;
-}
-
-QFont QCommandLinkButtonPrivate::descriptionFont() const
-{
- Q_Q(const QCommandLinkButton);
- QFont font = q->font();
- font.setPointSizeF(9.0);
-
- // Note the font will be resolved against
- // QPainters font, so we need to restore the mask
- int resolve_mask = font.resolve_mask;
- QFont modifiedFont = q->font().resolve(font);
- modifiedFont.detach();
- modifiedFont.resolve_mask = resolve_mask;
- return modifiedFont;
-}
-
-QRect QCommandLinkButtonPrivate::titleRect() const
-{
- Q_Q(const QCommandLinkButton);
- QRect r = q->rect().adjusted(textOffset(), topMargin(), -rightMargin(), 0);
- if (description.isEmpty())
- {
- QFontMetrics fm(titleFont());
- r.setTop(r.top() + qMax(0, (q->icon().actualSize(q->iconSize()).height()
- - fm.height()) / 2));
- }
-
- return r;
-}
-
-QRect QCommandLinkButtonPrivate::descriptionRect() const
-{
- Q_Q(const QCommandLinkButton);
- return q->rect().adjusted(textOffset(), descriptionOffset(),
- -rightMargin(), -bottomMargin());
-}
-
-int QCommandLinkButtonPrivate::textOffset() const
-{
- Q_Q(const QCommandLinkButton);
- return q->icon().actualSize(q->iconSize()).width() + leftMargin() + 6;
-}
-
-int QCommandLinkButtonPrivate::descriptionOffset() const
-{
- QFontMetrics fm(titleFont());
- return topMargin() + fm.height();
-}
-
-bool QCommandLinkButtonPrivate::usingVistaStyle() const
-{
- Q_Q(const QCommandLinkButton);
- //### This is a hack to detect if we are indeed running Vista style themed and not in classic
- // When we add api to query for this, we should change this implementation to use it.
- return q->style()->inherits("QWindowsVistaStyle")
- && !q->style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal);
-}
-
-void QCommandLinkButtonPrivate::init()
-{
- Q_Q(QCommandLinkButton);
- QPushButtonPrivate::init();
- q->setAttribute(Qt::WA_Hover);
-
- QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::PushButton);
- policy.setHeightForWidth(true);
- q->setSizePolicy(policy);
-
- q->setIconSize(QSize(20, 20));
- QStyleOptionButton opt;
- q->initStyleOption(&opt);
- q->setIcon(q->style()->standardIcon(QStyle::SP_CommandLink, &opt));
-}
-
-// Calculates the height of the description text based on widget width
-int QCommandLinkButtonPrivate::descriptionHeight(int widgetWidth) const
-{
- // Calc width of actual paragraph
- int lineWidth = widgetWidth - textOffset() - rightMargin();
-
- qreal descriptionheight = 0;
- if (!description.isEmpty()) {
- QTextLayout layout(description);
- layout.setFont(descriptionFont());
- layout.beginLayout();
- while (true) {
- QTextLine line = layout.createLine();
- if (!line.isValid())
- break;
- line.setLineWidth(lineWidth);
- line.setPosition(QPointF(0, descriptionheight));
- descriptionheight += line.height();
- }
- layout.endLayout();
- }
- return qCeil(descriptionheight);
-}
-
-/*!
- \reimp
- */
-QSize QCommandLinkButton::minimumSizeHint() const
-{
- Q_D(const QCommandLinkButton);
- QSize size = sizeHint();
- int minimumHeight = qMax(d->descriptionOffset() + d->bottomMargin(),
- icon().actualSize(iconSize()).height() + d->topMargin());
- size.setHeight(minimumHeight);
- return size;
-}
-
-/*!
- Constructs a command link with no text and a \a parent.
-*/
-
-QCommandLinkButton::QCommandLinkButton(QWidget *parent)
-: QPushButton(*new QCommandLinkButtonPrivate, parent)
-{
- Q_D(QCommandLinkButton);
- d->init();
-}
-
-/*!
- Constructs a command link with the parent \a parent and the text \a
- text.
-*/
-
-QCommandLinkButton::QCommandLinkButton(const QString &text, QWidget *parent)
- : QPushButton(*new QCommandLinkButtonPrivate, parent)
-{
- Q_D(QCommandLinkButton);
- setText(text);
- d->init();
-}
-
-/*!
- Constructs a command link with a \a text, a \a description, and a \a parent.
-*/
-QCommandLinkButton::QCommandLinkButton(const QString &text, const QString &description, QWidget *parent)
- : QPushButton(*new QCommandLinkButtonPrivate, parent)
-{
- Q_D(QCommandLinkButton);
- setText(text);
- setDescription(description);
- d->init();
-}
-
-/*! \reimp */
-bool QCommandLinkButton::event(QEvent *e)
-{
- return QPushButton::event(e);
-}
-
-/*! \reimp */
-QSize QCommandLinkButton::sizeHint() const
-{
-// Standard size hints from UI specs
-// Without note: 135, 41
-// With note: 135, 60
- Q_D(const QCommandLinkButton);
-
- QSize size = QPushButton::sizeHint();
- QFontMetrics fm(d->titleFont());
- int textWidth = qMax(fm.width(text()), 135);
- int buttonWidth = textWidth + d->textOffset() + d->rightMargin();
- int heightWithoutDescription = d->descriptionOffset() + d->bottomMargin();
-
- size.setWidth(qMax(size.width(), buttonWidth));
- size.setHeight(qMax(d->description.isEmpty() ? 41 : 60,
- heightWithoutDescription + d->descriptionHeight(buttonWidth)));
- return size;
-}
-
-/*! \reimp */
-int QCommandLinkButton::heightForWidth(int width) const
-{
- Q_D(const QCommandLinkButton);
- int heightWithoutDescription = d->descriptionOffset() + d->bottomMargin();
- // find the width available for the description area
- return qMax(heightWithoutDescription + d->descriptionHeight(width),
- icon().actualSize(iconSize()).height() + d->topMargin() +
- d->bottomMargin());
-}
-
-/*! \reimp */
-void QCommandLinkButton::paintEvent(QPaintEvent *)
-{
- Q_D(QCommandLinkButton);
- QStylePainter p(this);
- p.save();
-
- QStyleOptionButton option;
- initStyleOption(&option);
-
- //Enable command link appearance on Vista
- option.features |= QStyleOptionButton::CommandLinkButton;
- option.text = QString();
- option.icon = QIcon(); //we draw this ourselves
- QSize pixmapSize = icon().actualSize(iconSize());
-
- int vOffset = isDown() ? style()->pixelMetric(QStyle::PM_ButtonShiftVertical) : 0;
- int hOffset = isDown() ? style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal) : 0;
-
- //Draw icon
- p.drawControl(QStyle::CE_PushButton, option);
- if (!icon().isNull())
- p.drawPixmap(d->leftMargin() + hOffset, d->topMargin() + vOffset,
- icon().pixmap(pixmapSize, isEnabled() ? QIcon::Normal : QIcon::Disabled,
- isChecked() ? QIcon::On : QIcon::Off));
-
- //Draw title
- QColor textColor = palette().buttonText().color();
- if (isEnabled() && d->usingVistaStyle()) {
- textColor = QColor(21, 28, 85);
- if (underMouse() && !isDown())
- textColor = QColor(7, 64, 229);
- //A simple text color transition
- d->currentColor = d->mergedColors(textColor, d->currentColor, 60);
- option.palette.setColor(QPalette::ButtonText, d->currentColor);
- }
-
- int textflags = Qt::TextShowMnemonic;
- if (!style()->styleHint(QStyle::SH_UnderlineShortcut, &option, this))
- textflags |= Qt::TextHideMnemonic;
-
- p.setFont(d->titleFont());
- p.drawItemText(d->titleRect().translated(hOffset, vOffset),
- textflags, option.palette, isEnabled(), text(), QPalette::ButtonText);
-
- //Draw description
- textflags |= Qt::TextWordWrap | Qt::ElideRight;
- p.setFont(d->descriptionFont());
- p.drawItemText(d->descriptionRect().translated(hOffset, vOffset), textflags,
- option.palette, isEnabled(), description(), QPalette::ButtonText);
- p.restore();
-}
-
-void QCommandLinkButton::setDescription(const QString &description)
-{
- Q_D(QCommandLinkButton);
- d->description = description;
- updateGeometry();
- update();
-}
-
-QString QCommandLinkButton::description() const
-{
- Q_D(const QCommandLinkButton);
- return d->description;
-}
-
-QT_END_NAMESPACE
-
diff --git a/src/gui/widgets/qcommandlinkbutton.h b/src/gui/widgets/qcommandlinkbutton.h
deleted file mode 100644
index 0dc5dfc58d..0000000000
--- a/src/gui/widgets/qcommandlinkbutton.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOMMANDLINKBUTTON_H
-#define QCOMMANDLINKBUTTON_H
-
-#include <QtGui/qpushbutton.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QCommandLinkButtonPrivate;
-
-class Q_GUI_EXPORT QCommandLinkButton: public QPushButton
-{
- Q_OBJECT
-
- Q_PROPERTY(QString description READ description WRITE setDescription)
- Q_PROPERTY(bool flat READ isFlat WRITE setFlat DESIGNABLE false)
-
-public:
- explicit QCommandLinkButton(QWidget *parent=0);
- explicit QCommandLinkButton(const QString &text, QWidget *parent=0);
- QCommandLinkButton(const QString &text, const QString &description, QWidget *parent=0);
- QString description() const;
- void setDescription(const QString &description);
-
-protected:
- QSize sizeHint() const;
- int heightForWidth(int) const;
- QSize minimumSizeHint() const;
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *);
-
-private:
- Q_DISABLE_COPY(QCommandLinkButton)
- Q_DECLARE_PRIVATE(QCommandLinkButton)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOMMANDLINKBUTTON
diff --git a/src/gui/widgets/qdatetimeedit.cpp b/src/gui/widgets/qdatetimeedit.cpp
deleted file mode 100644
index 63371138c7..0000000000
--- a/src/gui/widgets/qdatetimeedit.cpp
+++ /dev/null
@@ -1,2642 +0,0 @@
-/****************************************************************************
-**
-** 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 <math.h>
-#include <private/qdatetimeedit_p.h>
-#include <qabstractspinbox.h>
-#include <qapplication.h>
-#include <qdatetimeedit.h>
-#include <qdesktopwidget.h>
-#include <qdebug.h>
-#include <qevent.h>
-#include <qlineedit.h>
-#include <private/qlineedit_p.h>
-#include <qlocale.h>
-#include <qpainter.h>
-#include <qlayout.h>
-#include <qset.h>
-#include <qstyle.h>
-
-#ifndef QT_NO_DATETIMEEDIT
-
-//#define QDATETIMEEDIT_QDTEDEBUG
-#ifdef QDATETIMEEDIT_QDTEDEBUG
-# define QDTEDEBUG qDebug() << QString::fromLatin1("%1:%2").arg(__FILE__).arg(__LINE__)
-# define QDTEDEBUGN qDebug
-#else
-# define QDTEDEBUG if (false) qDebug()
-# define QDTEDEBUGN if (false) qDebug
-#endif
-
-QT_BEGIN_NAMESPACE
-
-// --- QDateTimeEdit ---
-
-/*!
- \class QDateTimeEdit
- \brief The QDateTimeEdit class provides a widget for editing dates and times.
-
- \ingroup basicwidgets
-
-
- QDateTimeEdit allows the user to edit dates by using the keyboard or
- the arrow keys to increase and decrease date and time values. The
- arrow keys can be used to move from section to section within the
- QDateTimeEdit box. Dates and times appear in accordance with the
- format set; see setDisplayFormat().
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 0
-
- Here we've created a new QDateTimeEdit object initialized with
- today's date, and restricted the valid date range to today plus or
- minus 365 days. We've set the order to month, day, year.
-
- The minimum value for QDateTimeEdit is 14 September 1752,
- and 2 January 4713BC for QDate. You can change this by calling
- setMinimumDate(), setMaximumDate(), setMinimumTime(),
- and setMaximumTime().
-
- \section1 Using a Pop-up Calendar Widget
-
- QDateTimeEdit can be configured to allow a QCalendarWidget to be used
- to select dates. This is enabled by setting the calendarPopup property.
- Additionally, you can supply a custom calendar widget for use as the
- calendar pop-up by calling the setCalendarWidget() function. The existing
- calendar widget can be retrieved with calendarWidget().
-
- \table 100%
- \row \o \inlineimage windowsxp-datetimeedit.png Screenshot of a Windows XP style date time editing widget
- \o A date time editing widget shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage macintosh-datetimeedit.png Screenshot of a Macintosh style date time editing widget
- \o A date time editing widget shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row \o \inlineimage plastique-datetimeedit.png Screenshot of a Plastique style date time editing widget
- \o A date time editing widget shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QDateEdit, QTimeEdit, QDate, QTime
-*/
-
-/*!
- \enum QDateTimeEdit::Section
-
- \value NoSection
- \value AmPmSection
- \value MSecSection
- \value SecondSection
- \value MinuteSection
- \value HourSection
- \value DaySection
- \value MonthSection
- \value YearSection
- \omitvalue DateSections_Mask
- \omitvalue TimeSections_Mask
-*/
-
-/*!
- \fn void QDateTimeEdit::dateTimeChanged(const QDateTime &datetime)
-
- This signal is emitted whenever the date or time is changed. The
- new date and time is passed in \a datetime.
-*/
-
-/*!
- \fn void QDateTimeEdit::timeChanged(const QTime &time)
-
- This signal is emitted whenever the time is changed. The new time
- is passed in \a time.
-*/
-
-/*!
- \fn void QDateTimeEdit::dateChanged(const QDate &date)
-
- This signal is emitted whenever the date is changed. The new date
- is passed in \a date.
-*/
-
-
-/*!
- Constructs an empty date time editor with a \a parent.
-*/
-
-QDateTimeEdit::QDateTimeEdit(QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
-{
- Q_D(QDateTimeEdit);
- d->init(QDateTime(QDATETIMEEDIT_DATE_INITIAL, QDATETIMEEDIT_TIME_MIN));
-}
-
-/*!
- Constructs an empty date time editor with a \a parent. The value
- is set to \a datetime.
-*/
-
-QDateTimeEdit::QDateTimeEdit(const QDateTime &datetime, QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
-{
- Q_D(QDateTimeEdit);
- d->init(datetime.isValid() ? datetime : QDateTime(QDATETIMEEDIT_DATE_INITIAL,
- QDATETIMEEDIT_TIME_MIN));
-}
-
-/*!
- \fn QDateTimeEdit::QDateTimeEdit(const QDate &date, QWidget *parent)
-
- Constructs an empty date time editor with a \a parent.
- The value is set to \a date.
-*/
-
-QDateTimeEdit::QDateTimeEdit(const QDate &date, QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
-{
- Q_D(QDateTimeEdit);
- d->init(date.isValid() ? date : QDATETIMEEDIT_DATE_INITIAL);
-}
-
-/*!
- \fn QDateTimeEdit::QDateTimeEdit(const QTime &time, QWidget *parent)
-
- Constructs an empty date time editor with a \a parent.
- The value is set to \a time.
-*/
-
-QDateTimeEdit::QDateTimeEdit(const QTime &time, QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
-{
- Q_D(QDateTimeEdit);
- d->init(time.isValid() ? time : QDATETIMEEDIT_TIME_MIN);
-}
-
-/*!
- \internal
-*/
-
-QDateTimeEdit::QDateTimeEdit(const QVariant &var, QVariant::Type parserType, QWidget *parent)
- : QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
-{
- Q_D(QDateTimeEdit);
- d->parserType = parserType;
- d->init(var);
-}
-
-/*!
- \property QDateTimeEdit::dateTime
- \brief the QDateTime that is set in the QDateTimeEdit
-
- When setting this property the timespec of the QDateTimeEdit remains the same
- and the timespec of the new QDateTime is ignored.
-
- By default, this property contains a date that refers to January 1,
- 2000 and a time of 00:00:00 and 0 milliseconds.
-
- \sa date, time
-*/
-
-QDateTime QDateTimeEdit::dateTime() const
-{
- Q_D(const QDateTimeEdit);
- return d->value.toDateTime();
-}
-
-void QDateTimeEdit::setDateTime(const QDateTime &datetime)
-{
- Q_D(QDateTimeEdit);
- if (datetime.isValid()) {
- d->clearCache();
- if (!(d->sections & DateSections_Mask))
- setDateRange(datetime.date(), datetime.date());
- d->setValue(QDateTime(datetime.date(), datetime.time(), d->spec), EmitIfChanged);
- }
-}
-
-/*!
- \property QDateTimeEdit::date
- \brief the QDate that is set in the widget
-
- By default, this property contains a date that refers to January 1, 2000.
-
- \sa time, dateTime
-*/
-
-/*!
- Returns the date of the date time edit.
-*/
-QDate QDateTimeEdit::date() const
-{
- Q_D(const QDateTimeEdit);
- return d->value.toDate();
-}
-
-void QDateTimeEdit::setDate(const QDate &date)
-{
- Q_D(QDateTimeEdit);
- if (date.isValid()) {
- if (!(d->sections & DateSections_Mask))
- setDateRange(date, date);
-
- d->clearCache();
- d->setValue(QDateTime(date, d->value.toTime(), d->spec), EmitIfChanged);
- d->updateTimeSpec();
- }
-}
-
-/*!
- \property QDateTimeEdit::time
- \brief the QTime that is set in the widget
-
- By default, this property contains a time of 00:00:00 and 0 milliseconds.
-
- \sa date, dateTime
-*/
-
-/*!
- Returns the time of the date time edit.
-*/
-QTime QDateTimeEdit::time() const
-{
- Q_D(const QDateTimeEdit);
- return d->value.toTime();
-}
-
-void QDateTimeEdit::setTime(const QTime &time)
-{
- Q_D(QDateTimeEdit);
- if (time.isValid()) {
- d->clearCache();
- d->setValue(QDateTime(d->value.toDate(), time, d->spec), EmitIfChanged);
- }
-}
-
-
-/*!
- \property QDateTimeEdit::minimumDateTime
- \since 4.4
-
- \brief the minimum datetime of the date time edit
-
- When setting this property the \l maximumDateTime() is adjusted if
- necessary to ensure that the range remains valid. If the datetime is
- not a valid QDateTime object, this function does nothing.
-
- The default minimumDateTime can be restored with
- clearMinimumDateTime()
-
- By default, this property contains a date that refers to September 14,
- 1752 and a time of 00:00:00 and 0 milliseconds.
-
- \sa maximumDateTime(), minimumTime(), maximumTime(), minimumDate(),
- maximumDate(), setDateTimeRange(), setDateRange(), setTimeRange(),
- clearMaximumDateTime(), clearMinimumDate(),
- clearMaximumDate(), clearMinimumTime(), clearMaximumTime()
-*/
-
-QDateTime QDateTimeEdit::minimumDateTime() const
-{
- Q_D(const QDateTimeEdit);
- return d->minimum.toDateTime();
-}
-
-void QDateTimeEdit::clearMinimumDateTime()
-{
- setMinimumDateTime(QDateTime(QDATETIMEEDIT_COMPAT_DATE_MIN, QDATETIMEEDIT_TIME_MIN));
-}
-
-void QDateTimeEdit::setMinimumDateTime(const QDateTime &dt)
-{
- Q_D(QDateTimeEdit);
- if (dt.isValid() && dt.date() >= QDATETIMEEDIT_DATE_MIN) {
- const QDateTime m = dt.toTimeSpec(d->spec);
- const QDateTime max = d->maximum.toDateTime();
- d->setRange(m, (max > m ? max : m));
- }
-}
-
-/*!
- \property QDateTimeEdit::maximumDateTime
- \since 4.4
-
- \brief the maximum datetime of the date time edit
-
- When setting this property the \l minimumDateTime() is adjusted if
- necessary to ensure that the range remains valid. If the datetime is
- not a valid QDateTime object, this function does nothing.
-
- The default maximumDateTime can be restored with
- clearMaximumDateTime().
-
- By default, this property contains a date that refers to 31 December,
- 7999 and a time of 23:59:59 and 999 milliseconds.
-
- \sa minimumDateTime(), minimumTime(), maximumTime(), minimumDate(),
- maximumDate(), setDateTimeRange(), setDateRange(), setTimeRange(),
- clearMinimumDateTime(), clearMinimumDate(),
- clearMaximumDate(), clearMinimumTime(), clearMaximumTime()
-*/
-
-QDateTime QDateTimeEdit::maximumDateTime() const
-{
- Q_D(const QDateTimeEdit);
- return d->maximum.toDateTime();
-}
-
-void QDateTimeEdit::clearMaximumDateTime()
-{
- setMaximumDateTime(QDATETIMEEDIT_DATETIME_MAX);
-}
-
-void QDateTimeEdit::setMaximumDateTime(const QDateTime &dt)
-{
- Q_D(QDateTimeEdit);
- if (dt.isValid() && dt.date() <= QDATETIMEEDIT_DATE_MAX) {
- const QDateTime m = dt.toTimeSpec(d->spec);
- const QDateTime min = d->minimum.toDateTime();
- d->setRange((min < m ? min : m), m);
- }
-}
-
-
-/*!
- Convenience function to set minimum and maximum date time with one
- function call.
- \since 4.4
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 1
-
- is analogous to:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 2
-
- If either \a min or \a max are not valid, this function does
- nothing.
-
- \sa setMinimumDate(), maximumDate(), setMaximumDate(),
- clearMinimumDate(), setMinimumTime(), maximumTime(),
- setMaximumTime(), clearMinimumTime(), QDateTime::isValid()
-*/
-
-void QDateTimeEdit::setDateTimeRange(const QDateTime &min, const QDateTime &max)
-{
- Q_D(QDateTimeEdit);
- const QDateTime minimum = min.toTimeSpec(d->spec);
- QDateTime maximum = max.toTimeSpec(d->spec);
- if (min > max)
- maximum = minimum;
- d->setRange(minimum, maximum);
-}
-
-/*!
- \property QDateTimeEdit::minimumDate
-
- \brief the minimum date of the date time edit
-
- When setting this property the \l maximumDate is adjusted if
- necessary, to ensure that the range remains valid. If the date is
- not a valid QDate object, this function does nothing.
-
- By default, this property contains a date that refers to September 14, 1752.
- The minimum date must be at least the first day in year 100, otherwise
- setMinimumDate() has no effect.
-
- \sa minimumTime(), maximumTime(), setDateRange()
-*/
-
-QDate QDateTimeEdit::minimumDate() const
-{
- Q_D(const QDateTimeEdit);
- return d->minimum.toDate();
-}
-
-void QDateTimeEdit::setMinimumDate(const QDate &min)
-{
- Q_D(QDateTimeEdit);
- if (min.isValid() && min >= QDATETIMEEDIT_DATE_MIN) {
- setMinimumDateTime(QDateTime(min, d->minimum.toTime(), d->spec));
- }
-}
-
-void QDateTimeEdit::clearMinimumDate()
-{
- setMinimumDate(QDATETIMEEDIT_COMPAT_DATE_MIN);
-}
-
-/*!
- \property QDateTimeEdit::maximumDate
-
- \brief the maximum date of the date time edit
-
- When setting this property the \l minimumDate is adjusted if
- necessary to ensure that the range remains valid. If the date is
- not a valid QDate object, this function does nothing.
-
- By default, this property contains a date that refers to December 31, 7999.
-
- \sa minimumDate, minimumTime, maximumTime, setDateRange()
-*/
-
-QDate QDateTimeEdit::maximumDate() const
-{
- Q_D(const QDateTimeEdit);
- return d->maximum.toDate();
-}
-
-void QDateTimeEdit::setMaximumDate(const QDate &max)
-{
- Q_D(QDateTimeEdit);
- if (max.isValid()) {
- setMaximumDateTime(QDateTime(max, d->maximum.toTime(), d->spec));
- }
-}
-
-void QDateTimeEdit::clearMaximumDate()
-{
- setMaximumDate(QDATETIMEEDIT_DATE_MAX);
-}
-
-/*!
- \property QDateTimeEdit::minimumTime
-
- \brief the minimum time of the date time edit
-
- When setting this property the \l maximumTime is adjusted if
- necessary, to ensure that the range remains valid. If the time is
- not a valid QTime object, this function does nothing.
-
- By default, this property contains a time of 00:00:00 and 0 milliseconds.
-
- \sa maximumTime, minimumDate, maximumDate, setTimeRange()
-*/
-
-QTime QDateTimeEdit::minimumTime() const
-{
- Q_D(const QDateTimeEdit);
- return d->minimum.toTime();
-}
-
-void QDateTimeEdit::setMinimumTime(const QTime &min)
-{
- Q_D(QDateTimeEdit);
- if (min.isValid()) {
- const QDateTime m(d->minimum.toDate(), min, d->spec);
- setMinimumDateTime(m);
- }
-}
-
-void QDateTimeEdit::clearMinimumTime()
-{
- setMinimumTime(QDATETIMEEDIT_TIME_MIN);
-}
-
-/*!
- \property QDateTimeEdit::maximumTime
-
- \brief the maximum time of the date time edit
-
- When setting this property, the \l minimumTime is adjusted if
- necessary to ensure that the range remains valid. If the time is
- not a valid QTime object, this function does nothing.
-
- By default, this property contains a time of 23:59:59 and 999 milliseconds.
-
- \sa minimumTime, minimumDate, maximumDate, setTimeRange()
-*/
-QTime QDateTimeEdit::maximumTime() const
-{
- Q_D(const QDateTimeEdit);
- return d->maximum.toTime();
-}
-
-void QDateTimeEdit::setMaximumTime(const QTime &max)
-{
- Q_D(QDateTimeEdit);
- if (max.isValid()) {
- const QDateTime m(d->maximum.toDate(), max);
- setMaximumDateTime(m);
- }
-}
-
-void QDateTimeEdit::clearMaximumTime()
-{
- setMaximumTime(QDATETIMEEDIT_TIME_MAX);
-}
-
-/*!
- Convenience function to set minimum and maximum date with one
- function call.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 3
-
- is analogous to:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 4
-
- If either \a min or \a max are not valid, this function does
- nothing.
-
- \sa setMinimumDate(), maximumDate(), setMaximumDate(),
- clearMinimumDate(), setMinimumTime(), maximumTime(),
- setMaximumTime(), clearMinimumTime(), QDate::isValid()
-*/
-
-void QDateTimeEdit::setDateRange(const QDate &min, const QDate &max)
-{
- Q_D(QDateTimeEdit);
- if (min.isValid() && max.isValid()) {
- setDateTimeRange(QDateTime(min, d->minimum.toTime(), d->spec),
- QDateTime(max, d->maximum.toTime(), d->spec));
- }
-}
-
-/*!
- Convenience function to set minimum and maximum time with one
- function call.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 5
-
- is analogous to:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp 6
-
- If either \a min or \a max are not valid, this function does
- nothing.
-
- \sa setMinimumDate(), maximumDate(), setMaximumDate(),
- clearMinimumDate(), setMinimumTime(), maximumTime(),
- setMaximumTime(), clearMinimumTime(), QTime::isValid()
-*/
-
-void QDateTimeEdit::setTimeRange(const QTime &min, const QTime &max)
-{
- Q_D(QDateTimeEdit);
- if (min.isValid() && max.isValid()) {
- setDateTimeRange(QDateTime(d->minimum.toDate(), min, d->spec),
- QDateTime(d->maximum.toDate(), max, d->spec));
- }
-}
-
-/*!
- \property QDateTimeEdit::displayedSections
-
- \brief the currently displayed fields of the date time edit
-
- Returns a bit set of the displayed sections for this format.
- \a setDisplayFormat(), displayFormat()
-*/
-
-QDateTimeEdit::Sections QDateTimeEdit::displayedSections() const
-{
- Q_D(const QDateTimeEdit);
- return d->sections;
-}
-
-/*!
- \property QDateTimeEdit::currentSection
-
- \brief the current section of the spinbox
- \a setCurrentSection()
-*/
-
-QDateTimeEdit::Section QDateTimeEdit::currentSection() const
-{
- Q_D(const QDateTimeEdit);
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && d->focusOnButton)
- return NoSection;
-#endif
- return d->convertToPublic(d->sectionType(d->currentSectionIndex));
-}
-
-void QDateTimeEdit::setCurrentSection(Section section)
-{
- Q_D(QDateTimeEdit);
- if (section == NoSection || !(section & d->sections))
- return;
-
- d->updateCache(d->value, d->displayText());
- const int size = d->sectionNodes.size();
- int index = d->currentSectionIndex + 1;
- for (int i=0; i<2; ++i) {
- while (index < size) {
- if (d->convertToPublic(d->sectionType(index)) == section) {
- d->edit->setCursorPosition(d->sectionPos(index));
- QDTEDEBUG << d->sectionPos(index);
- return;
- }
- ++index;
- }
- index = 0;
- }
-}
-
-/*!
- \since 4.3
-
- Returns the Section at \a index.
-
- If the format is 'yyyy/MM/dd', sectionAt(0) returns YearSection,
- sectionAt(1) returns MonthSection, and sectionAt(2) returns
- YearSection,
-*/
-
-QDateTimeEdit::Section QDateTimeEdit::sectionAt(int index) const
-{
- Q_D(const QDateTimeEdit);
- if (index < 0 || index >= d->sectionNodes.size())
- return NoSection;
- return d->convertToPublic(d->sectionType(index));
-}
-
-/*!
- \since 4.3
-
- \property QDateTimeEdit::sectionCount
-
- \brief the number of sections displayed.
- If the format is 'yyyy/yy/yyyy', sectionCount returns 3
-*/
-
-int QDateTimeEdit::sectionCount() const
-{
- Q_D(const QDateTimeEdit);
- return d->sectionNodes.size();
-}
-
-
-/*!
- \since 4.3
-
- \property QDateTimeEdit::currentSectionIndex
-
- \brief the current section index of the spinbox
-
- If the format is 'yyyy/MM/dd', the displayText is '2001/05/21' and
- the cursorPosition is 5 currentSectionIndex returns 1. If the
- cursorPosition is 3 currentSectionIndex is 0 etc.
-
- \a setCurrentSection()
- \sa currentSection()
-*/
-
-int QDateTimeEdit::currentSectionIndex() const
-{
- Q_D(const QDateTimeEdit);
- return d->currentSectionIndex;
-}
-
-void QDateTimeEdit::setCurrentSectionIndex(int index)
-{
- Q_D(QDateTimeEdit);
- if (index < 0 || index >= d->sectionNodes.size())
- return;
- d->edit->setCursorPosition(d->sectionPos(index));
-}
-
-/*!
- \since 4.4
-
- \brief Returns the calendar widget for the editor if calendarPopup is
- set to true and (sections() & DateSections_Mask) != 0.
-
- This function creates and returns a calendar widget if none has been set.
-*/
-
-
-QCalendarWidget *QDateTimeEdit::calendarWidget() const
-{
- Q_D(const QDateTimeEdit);
- if (!d->calendarPopup || !(d->sections & QDateTimeParser::DateSectionMask))
- return 0;
- if (!d->monthCalendar) {
- const_cast<QDateTimeEditPrivate*>(d)->initCalendarPopup();
- }
- return d->monthCalendar->calendarWidget();
-}
-
-/*!
- \since 4.4
-
- Sets the given \a calendarWidget as the widget to be used for the calendar
- pop-up. The editor does not automatically take ownership of the calendar widget.
-
- \note calendarPopup must be set to true before setting the calendar widget.
- \sa calendarPopup
-*/
-void QDateTimeEdit::setCalendarWidget(QCalendarWidget *calendarWidget)
-{
- Q_D(QDateTimeEdit);
- if (!calendarWidget) {
- qWarning("QDateTimeEdit::setCalendarWidget: Cannot set a null calendar widget");
- return;
- }
-
- if (!d->calendarPopup) {
- qWarning("QDateTimeEdit::setCalendarWidget: calendarPopup is set to false");
- return;
- }
-
- if (!(d->display & QDateTimeParser::DateSectionMask)) {
- qWarning("QDateTimeEdit::setCalendarWidget: no date sections specified");
- return;
- }
- d->initCalendarPopup(calendarWidget);
-}
-
-
-/*!
- \since 4.2
-
- Selects \a section. If \a section doesn't exist in the currently
- displayed sections this function does nothing. If \a section is
- NoSection this function will unselect all text in the editor.
- Otherwise this function will move the cursor and the current section
- to the selected section.
-
- \sa currentSection()
-*/
-
-void QDateTimeEdit::setSelectedSection(Section section)
-{
- Q_D(QDateTimeEdit);
- if (section == NoSection) {
- d->edit->setSelection(d->edit->cursorPosition(), 0);
- } else if (section & d->sections) {
- if (currentSection() != section)
- setCurrentSection(section);
- d->setSelected(d->currentSectionIndex);
- }
-}
-
-
-
-/*!
- \fn QString QDateTimeEdit::sectionText(Section section) const
-
- Returns the text from the given \a section.
-
- \sa currentSection()
-*/
-
-QString QDateTimeEdit::sectionText(Section section) const
-{
- Q_D(const QDateTimeEdit);
- if (section == QDateTimeEdit::NoSection || !(section & d->sections)) {
- return QString();
- }
-
- d->updateCache(d->value, d->displayText());
- const int sectionIndex = d->absoluteIndex(section, 0);
- return d->sectionText(sectionIndex);
-}
-
-/*!
- \property QDateTimeEdit::displayFormat
-
- \brief the format used to display the time/date of the date time edit
-
- This format is the same as the one used described in QDateTime::toString()
- and QDateTime::fromString()
-
- Example format strings (assuming that the date is 2nd of July 1969):
-
- \table
- \header \i Format \i Result
- \row \i dd.MM.yyyy \i 02.07.1969
- \row \i MMM d yy \i Jul 2 69
- \row \i MMMM d yy \i July 2 69
- \endtable
-
- Note that if you specify a two digit year, it will be interpreted
- to be in the century in which the date time edit was initialized.
- The default century is the 21 (2000-2099).
-
- If you specify an invalid format the format will not be set.
-
- \sa QDateTime::toString(), displayedSections()
-*/
-
-QString QDateTimeEdit::displayFormat() const
-{
- Q_D(const QDateTimeEdit);
- return isRightToLeft() ? d->unreversedFormat : d->displayFormat;
-}
-
-template<typename C> static inline C reverse(const C &l)
-{
- C ret;
- for (int i=l.size() - 1; i>=0; --i)
- ret.append(l.at(i));
- return ret;
-}
-
-void QDateTimeEdit::setDisplayFormat(const QString &format)
-{
- Q_D(QDateTimeEdit);
- if (d->parseFormat(format)) {
- d->unreversedFormat.clear();
- if (isRightToLeft()) {
- d->unreversedFormat = format;
- d->displayFormat.clear();
- for (int i=d->sectionNodes.size() - 1; i>=0; --i) {
- d->displayFormat += d->separators.at(i + 1);
- d->displayFormat += d->sectionFormat(i);
- }
- d->displayFormat += d->separators.at(0);
- d->separators = reverse(d->separators);
- d->sectionNodes = reverse(d->sectionNodes);
- }
-
- d->formatExplicitlySet = true;
- d->sections = d->convertSections(d->display);
- d->clearCache();
-
- d->currentSectionIndex = qMin(d->currentSectionIndex, d->sectionNodes.size() - 1);
- const bool timeShown = (d->sections & TimeSections_Mask);
- const bool dateShown = (d->sections & DateSections_Mask);
- Q_ASSERT(dateShown || timeShown);
- if (timeShown && !dateShown) {
- QTime time = d->value.toTime();
- setDateRange(d->value.toDate(), d->value.toDate());
- if (d->minimum.toTime() >= d->maximum.toTime()) {
- setTimeRange(QDATETIMEEDIT_TIME_MIN, QDATETIMEEDIT_TIME_MAX);
- // if the time range became invalid during the adjustment, the time would have been reset
- setTime(time);
- }
- } else if (dateShown && !timeShown) {
- setTimeRange(QDATETIMEEDIT_TIME_MIN, QDATETIMEEDIT_TIME_MAX);
- d->value = QDateTime(d->value.toDate(), QTime(), d->spec);
- }
- d->updateEdit();
- d->_q_editorCursorPositionChanged(-1, 0);
- }
-}
-
-/*!
- \property QDateTimeEdit::calendarPopup
- \brief the current calendar pop-up showing mode.
- \since 4.2
-
- The calendar pop-up will be shown upon clicking the arrow button.
- This property is valid only if there is a valid date display format.
-
- \sa setDisplayFormat()
-*/
-
-bool QDateTimeEdit::calendarPopup() const
-{
- Q_D(const QDateTimeEdit);
- return d->calendarPopup;
-}
-
-void QDateTimeEdit::setCalendarPopup(bool enable)
-{
- Q_D(QDateTimeEdit);
- if (enable == d->calendarPopup)
- return;
- setAttribute(Qt::WA_MacShowFocusRect, !enable);
- d->calendarPopup = enable;
-#ifdef QT_KEYPAD_NAVIGATION
- if (!enable)
- d->focusOnButton = false;
-#endif
- d->updateEditFieldGeometry();
- update();
-}
-
-/*!
- \property QDateTimeEdit::timeSpec
- \brief the current timespec used by the date time edit.
- \since 4.4
-*/
-
-Qt::TimeSpec QDateTimeEdit::timeSpec() const
-{
- Q_D(const QDateTimeEdit);
- return d->spec;
-}
-
-void QDateTimeEdit::setTimeSpec(Qt::TimeSpec spec)
-{
- Q_D(QDateTimeEdit);
- if (spec != d->spec) {
- d->spec = spec;
- d->updateTimeSpec();
- }
-}
-
-/*!
- \reimp
-*/
-
-QSize QDateTimeEdit::sizeHint() const
-{
- Q_D(const QDateTimeEdit);
- if (d->cachedSizeHint.isEmpty()) {
- ensurePolished();
-
- const QFontMetrics fm(fontMetrics());
- int h = d->edit->sizeHint().height();
- int w = 0;
- QString s;
- s = d->textFromValue(d->minimum) + QLatin1String(" ");
- w = qMax<int>(w, fm.width(s));
- s = d->textFromValue(d->maximum) + QLatin1String(" ");
- w = qMax<int>(w, fm.width(s));
- if (d->specialValueText.size()) {
- s = d->specialValueText;
- w = qMax<int>(w, fm.width(s));
- }
- w += 2; // cursor blinking space
-
- QSize hint(w, h);
-
-#ifdef Q_WS_MAC
- if (d->calendarPopupEnabled()) {
- QStyleOptionComboBox opt;
- d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_ComboBox, &opt, hint, this);
- } else {
-#else
- {
-#endif
- QSize extra(35, 6);
- QStyleOptionSpinBox opt;
- initStyleOption(&opt);
- opt.rect.setSize(hint + extra);
- extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, this).size();
- // get closer to final result by repeating the calculation
- opt.rect.setSize(hint + extra);
- extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt,
- QStyle::SC_SpinBoxEditField, this).size();
- hint += extra;
-
- opt.rect = rect();
- d->cachedSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
- .expandedTo(QApplication::globalStrut());
- }
-
- d->cachedMinimumSizeHint = d->cachedSizeHint;
- // essentially make minimumSizeHint return the same as sizeHint for datetimeedits
- }
- return d->cachedSizeHint;
-}
-
-/*!
- \reimp
-*/
-
-bool QDateTimeEdit::event(QEvent *event)
-{
- Q_D(QDateTimeEdit);
- switch (event->type()) {
- case QEvent::ApplicationLayoutDirectionChange: {
- const bool was = d->formatExplicitlySet;
- const QString oldFormat = d->displayFormat;
- d->displayFormat.clear();
- setDisplayFormat(oldFormat);
- d->formatExplicitlySet = was;
- break; }
- case QEvent::LocaleChange:
- d->updateEdit();
- break;
- case QEvent::StyleChange:
-#ifdef Q_WS_MAC
- case QEvent::MacSizeChange:
-#endif
- d->setLayoutItemMargins(QStyle::SE_DateTimeEditLayoutItem);
- break;
- default:
- break;
- }
- return QAbstractSpinBox::event(event);
-}
-
-/*!
- \reimp
-*/
-
-void QDateTimeEdit::clear()
-{
- Q_D(QDateTimeEdit);
- d->clearSection(d->currentSectionIndex);
-}
-/*!
- \reimp
-*/
-
-void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QDateTimeEdit);
- int oldCurrent = d->currentSectionIndex;
- bool select = true;
- bool inserted = false;
-
- switch (event->key()) {
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_NumberSign: //shortcut to popup calendar
- if (QApplication::keypadNavigationEnabled() && d->calendarPopupEnabled()) {
- d->initCalendarPopup();
- d->positionCalendarPopup();
- d->monthCalendar->show();
- return;
- }
- break;
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- if (hasEditFocus()) {
- if (d->focusOnButton) {
- d->initCalendarPopup();
- d->positionCalendarPopup();
- d->monthCalendar->show();
- d->focusOnButton = false;
- return;
- }
- setEditFocus(false);
- selectAll();
- } else {
- setEditFocus(true);
-
- //hide cursor
- d->edit->d_func()->setCursorVisible(false);
- d->edit->d_func()->control->setCursorBlinkPeriod(0);
- d->setSelected(0);
- }
- }
- return;
-#endif
- case Qt::Key_Enter:
- case Qt::Key_Return:
- d->interpret(AlwaysEmit);
- d->setSelected(d->currentSectionIndex, true);
- event->ignore();
- emit editingFinished();
- return;
- default:
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()
- && !event->text().isEmpty() && event->text().at(0).isLetterOrNumber()) {
- setEditFocus(true);
-
- //hide cursor
- d->edit->d_func()->setCursorVisible(false);
- d->edit->d_func()->control->setCursorBlinkPeriod(0);
- d->setSelected(0);
- oldCurrent = 0;
- }
-#endif
- if (!d->isSeparatorKey(event)) {
- inserted = select = !event->text().isEmpty() && event->text().at(0).isPrint()
- && !(event->modifiers() & ~(Qt::ShiftModifier|Qt::KeypadModifier));
- break;
- }
- case Qt::Key_Left:
- case Qt::Key_Right:
- if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
- if (
-#ifdef QT_KEYPAD_NAVIGATION
- QApplication::keypadNavigationEnabled() && !hasEditFocus()
- || !QApplication::keypadNavigationEnabled() &&
-#endif
- !(event->modifiers() & Qt::ControlModifier)) {
- select = false;
- break;
- }
-#ifdef Q_WS_MAC
- else
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled())
-#endif
- {
- select = (event->modifiers() & Qt::ShiftModifier);
- break;
- }
-#endif
- }
- // else fall through
- case Qt::Key_Backtab:
- case Qt::Key_Tab: {
- event->accept();
- if (d->specialValue()) {
- d->edit->setSelection(d->edit->cursorPosition(), 0);
- return;
- }
- const bool forward = event->key() != Qt::Key_Left && event->key() != Qt::Key_Backtab
- && (event->key() != Qt::Key_Tab || !(event->modifiers() & Qt::ShiftModifier));
-#ifdef QT_KEYPAD_NAVIGATION
- int newSection = d->nextPrevSection(d->currentSectionIndex, forward);
- if (QApplication::keypadNavigationEnabled()) {
- if (d->focusOnButton) {
- newSection = forward ? 0 : d->sectionNodes.size() - 1;
- d->focusOnButton = false;
- update();
- } else if (newSection < 0 && select && d->calendarPopupEnabled()) {
- setSelectedSection(NoSection);
- d->focusOnButton = true;
- update();
- return;
- }
- }
- // only allow date/time sections to be selected.
- if (newSection & ~(QDateTimeParser::TimeSectionMask | QDateTimeParser::DateSectionMask))
- return;
-#endif
- //key tab and backtab will be managed thrgout QWidget::event
- if (event->key() != Qt::Key_Backtab && event->key() != Qt::Key_Tab)
- focusNextPrevChild(forward);
-
- return; }
- }
- QAbstractSpinBox::keyPressEvent(event);
- if (select && !d->edit->hasSelectedText()) {
- if (inserted && d->sectionAt(d->edit->cursorPosition()) == QDateTimeParser::NoSectionIndex) {
- QString str = d->displayText();
- int pos = d->edit->cursorPosition();
- if (validate(str, pos) == QValidator::Acceptable
- && (d->sectionNodes.at(oldCurrent).count != 1
- || d->sectionMaxSize(oldCurrent) == d->sectionSize(oldCurrent)
- || d->skipToNextSection(oldCurrent, d->value.toDateTime(), d->sectionText(oldCurrent)))) {
- QDTEDEBUG << "Setting currentsection to"
- << d->closestSection(d->edit->cursorPosition(), true) << event->key()
- << oldCurrent << str;
- const int tmp = d->closestSection(d->edit->cursorPosition(), true);
- if (tmp >= 0)
- d->currentSectionIndex = tmp;
- }
- }
- if (d->currentSectionIndex != oldCurrent) {
- d->setSelected(d->currentSectionIndex);
- }
- }
- if (d->specialValue()) {
- d->edit->setSelection(d->edit->cursorPosition(), 0);
- }
-}
-
-/*!
- \reimp
-*/
-
-#ifndef QT_NO_WHEELEVENT
-void QDateTimeEdit::wheelEvent(QWheelEvent *event)
-{
- QAbstractSpinBox::wheelEvent(event);
-}
-#endif
-
-/*!
- \reimp
-*/
-
-void QDateTimeEdit::focusInEvent(QFocusEvent *event)
-{
- Q_D(QDateTimeEdit);
- QAbstractSpinBox::focusInEvent(event);
- QString *frm = 0;
- const int oldPos = d->edit->cursorPosition();
- if (!d->formatExplicitlySet) {
- if (d->displayFormat == d->defaultTimeFormat) {
- frm = &d->defaultTimeFormat;
- } else if (d->displayFormat == d->defaultDateFormat) {
- frm = &d->defaultDateFormat;
- } else if (d->displayFormat == d->defaultDateTimeFormat) {
- frm = &d->defaultDateTimeFormat;
- }
-
- if (frm) {
- d->readLocaleSettings();
- if (d->displayFormat != *frm) {
- setDisplayFormat(*frm);
- d->formatExplicitlySet = false;
- d->edit->setCursorPosition(oldPos);
- }
- }
- }
- const bool oldHasHadFocus = d->hasHadFocus;
- d->hasHadFocus = true;
- bool first = true;
- switch (event->reason()) {
- case Qt::BacktabFocusReason:
- first = false;
- break;
- case Qt::MouseFocusReason:
- case Qt::PopupFocusReason:
- return;
- case Qt::ActiveWindowFocusReason:
- if (oldHasHadFocus)
- return;
- case Qt::ShortcutFocusReason:
- case Qt::TabFocusReason:
- default:
- break;
- }
- if (isRightToLeft())
- first = !first;
- d->updateEdit(); // needed to make it update specialValueText
-
- d->setSelected(first ? 0 : d->sectionNodes.size() - 1);
-}
-
-/*!
- \reimp
-*/
-
-bool QDateTimeEdit::focusNextPrevChild(bool next)
-{
- Q_D(QDateTimeEdit);
- const int newSection = d->nextPrevSection(d->currentSectionIndex, next);
- switch (d->sectionType(newSection)) {
- case QDateTimeParser::NoSection:
- case QDateTimeParser::FirstSection:
- case QDateTimeParser::LastSection:
- return QAbstractSpinBox::focusNextPrevChild(next);
- default:
- d->edit->deselect();
- d->edit->setCursorPosition(d->sectionPos(newSection));
- QDTEDEBUG << d->sectionPos(newSection);
- d->setSelected(newSection, true);
- return false;
- }
-}
-
-/*!
- \reimp
-*/
-
-void QDateTimeEdit::stepBy(int steps)
-{
- Q_D(QDateTimeEdit);
-#ifdef QT_KEYPAD_NAVIGATION
- // with keypad navigation and not editFocus, left right change the date/time by a fixed amount.
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- // if date based, shift by day. else shift by 15min
- if (d->sections & DateSections_Mask) {
- setDateTime(dateTime().addDays(steps));
- } else {
- int minutes = time().hour()*60 + time().minute();
- int blocks = minutes/15;
- blocks += steps;
- /* rounding involved */
- if (minutes % 15) {
- if (steps < 0) {
- blocks += 1; // do one less step;
- }
- }
-
- minutes = blocks * 15;
-
- /* need to take wrapping into account */
- if (!d->wrapping) {
- int max_minutes = d->maximum.toTime().hour()*60 + d->maximum.toTime().minute();
- int min_minutes = d->minimum.toTime().hour()*60 + d->minimum.toTime().minute();
-
- if (minutes >= max_minutes) {
- setTime(maximumTime());
- return;
- } else if (minutes <= min_minutes) {
- setTime(minimumTime());
- return;
- }
- }
- setTime(QTime(minutes/60, minutes%60));
- }
- return;
- }
-#endif
- // don't optimize away steps == 0. This is the only way to select
- // the currentSection in Qt 4.1.x
- if (d->specialValue() && displayedSections() != AmPmSection) {
- for (int i=0; i<d->sectionNodes.size(); ++i) {
- if (d->sectionType(i) != QDateTimeParser::AmPmSection) {
- d->currentSectionIndex = i;
- break;
- }
- }
- }
- d->setValue(d->stepBy(d->currentSectionIndex, steps, false), EmitIfChanged);
- d->updateCache(d->value, d->displayText());
-
- d->setSelected(d->currentSectionIndex);
- d->updateTimeSpec();
-}
-
-/*!
- This virtual function is used by the date time edit whenever it
- needs to display \a dateTime.
-
- If you reimplement this, you may also need to reimplement validate().
-
- \sa dateTimeFromText(), validate()
-*/
-QString QDateTimeEdit::textFromDateTime(const QDateTime &dateTime) const
-{
- Q_D(const QDateTimeEdit);
- return locale().toString(dateTime, d->displayFormat);
-}
-
-
-/*!
- Returns an appropriate datetime for the given \a text.
-
- This virtual function is used by the datetime edit whenever it
- needs to interpret text entered by the user as a value.
-
- \sa textFromDateTime(), validate()
-*/
-QDateTime QDateTimeEdit::dateTimeFromText(const QString &text) const
-{
- Q_D(const QDateTimeEdit);
- QString copy = text;
- int pos = d->edit->cursorPosition();
- QValidator::State state = QValidator::Acceptable;
- return d->validateAndInterpret(copy, pos, state);
-}
-
-/*!
- \reimp
-*/
-
-QValidator::State QDateTimeEdit::validate(QString &text, int &pos) const
-{
- Q_D(const QDateTimeEdit);
- QValidator::State state;
- d->validateAndInterpret(text, pos, state);
- return state;
-}
-
-/*!
- \reimp
-*/
-
-
-void QDateTimeEdit::fixup(QString &input) const
-{
- Q_D(const QDateTimeEdit);
- QValidator::State state;
- int copy = d->edit->cursorPosition();
-
- d->validateAndInterpret(input, copy, state, true);
-}
-
-
-/*!
- \reimp
-*/
-
-QDateTimeEdit::StepEnabled QDateTimeEdit::stepEnabled() const
-{
- Q_D(const QDateTimeEdit);
- if (d->readOnly)
- return StepEnabled(0);
- if (d->specialValue()) {
- return (d->minimum == d->maximum ? StepEnabled(0) : StepEnabled(StepUpEnabled));
- }
-
- QAbstractSpinBox::StepEnabled ret = 0;
-
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- if (d->wrapping)
- return StepEnabled(StepUpEnabled | StepDownEnabled);
- // 3 cases. date, time, datetime. each case look
- // at just the relavant component.
- QVariant max, min, val;
- if (!(d->sections & DateSections_Mask)) {
- // time only, no date
- max = d->maximum.toTime();
- min = d->minimum.toTime();
- val = d->value.toTime();
- } else if (!(d->sections & TimeSections_Mask)) {
- // date only, no time
- max = d->maximum.toDate();
- min = d->minimum.toDate();
- val = d->value.toDate();
- } else {
- // both
- max = d->maximum;
- min = d->minimum;
- val = d->value;
- }
- if (val != min)
- ret |= QAbstractSpinBox::StepDownEnabled;
- if (val != max)
- ret |= QAbstractSpinBox::StepUpEnabled;
- return ret;
- }
-#endif
- switch (d->sectionType(d->currentSectionIndex)) {
- case QDateTimeParser::NoSection:
- case QDateTimeParser::FirstSection:
- case QDateTimeParser::LastSection: return 0;
- default: break;
- }
- if (d->wrapping)
- return StepEnabled(StepDownEnabled|StepUpEnabled);
-
- QVariant v = d->stepBy(d->currentSectionIndex, 1, true);
- if (v != d->value) {
- ret |= QAbstractSpinBox::StepUpEnabled;
- }
- v = d->stepBy(d->currentSectionIndex, -1, true);
- if (v != d->value) {
- ret |= QAbstractSpinBox::StepDownEnabled;
- }
-
- return ret;
-}
-
-
-/*!
- \reimp
-*/
-
-void QDateTimeEdit::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QDateTimeEdit);
- if (!d->calendarPopupEnabled()) {
- QAbstractSpinBox::mousePressEvent(event);
- return;
- }
- d->updateHoverControl(event->pos());
- if (d->hoverControl == QStyle::SC_ComboBoxArrow) {
- event->accept();
- if (d->readOnly) {
- return;
- }
- d->updateArrow(QStyle::State_Sunken);
- d->initCalendarPopup();
- d->positionCalendarPopup();
- //Show the calendar
- d->monthCalendar->show();
- } else {
- QAbstractSpinBox::mousePressEvent(event);
- }
-}
-
-/*!
- \class QTimeEdit
- \brief The QTimeEdit class provides a widget for editing times based on
- the QDateTimeEdit widget.
-
- \ingroup basicwidgets
-
-
- Many of the properties and functions provided by QTimeEdit are implemented in
- QDateTimeEdit. The following properties are most relevant to users of this
- class:
-
- \list
- \o \l{QDateTimeEdit::time}{time} holds the date displayed by the widget.
- \o \l{QDateTimeEdit::minimumTime}{minimumTime} defines the minimum (earliest) time
- that can be set by the user.
- \o \l{QDateTimeEdit::maximumTime}{maximumTime} defines the maximum (latest) time
- that can be set by the user.
- \o \l{QDateTimeEdit::displayFormat}{displayFormat} contains a string that is used
- to format the time displayed in the widget.
- \endlist
-
- \table 100%
- \row \o \inlineimage windowsxp-timeedit.png Screenshot of a Windows XP style time editing widget
- \o A time editing widget shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage macintosh-timeedit.png Screenshot of a Macintosh style time editing widget
- \o A time editing widget shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row \o \inlineimage plastique-timeedit.png Screenshot of a Plastique style time editing widget
- \o A time editing widget shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QDateEdit, QDateTimeEdit
-*/
-
-/*!
- Constructs an empty time editor with a \a parent.
-*/
-
-
-QTimeEdit::QTimeEdit(QWidget *parent)
- : QDateTimeEdit(QDATETIMEEDIT_TIME_MIN, QVariant::Time, parent)
-{
-}
-
-/*!
- Constructs an empty time editor with a \a parent. The time is set
- to \a time.
-*/
-
-QTimeEdit::QTimeEdit(const QTime &time, QWidget *parent)
- : QDateTimeEdit(time, QVariant::Time, parent)
-{
-}
-
-
-/*!
- \class QDateEdit
- \brief The QDateEdit class provides a widget for editing dates based on
- the QDateTimeEdit widget.
-
- \ingroup basicwidgets
-
-
- Many of the properties and functions provided by QDateEdit are implemented in
- QDateTimeEdit. The following properties are most relevant to users of this
- class:
-
- \list
- \o \l{QDateTimeEdit::date}{date} holds the date displayed by the widget.
- \o \l{QDateTimeEdit::minimumDate}{minimumDate} defines the minimum (earliest)
- date that can be set by the user.
- \o \l{QDateTimeEdit::maximumDate}{maximumDate} defines the maximum (latest) date
- that can be set by the user.
- \o \l{QDateTimeEdit::displayFormat}{displayFormat} contains a string that is used
- to format the date displayed in the widget.
- \endlist
-
- \table 100%
- \row \o \inlineimage windowsxp-dateedit.png Screenshot of a Windows XP style date editing widget
- \o A date editing widget shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage macintosh-dateedit.png Screenshot of a Macintosh style date editing widget
- \o A date editing widget shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row \o \inlineimage plastique-dateedit.png Screenshot of a Plastique style date editing widget
- \o A date editing widget shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QTimeEdit, QDateTimeEdit
-*/
-
-/*!
- Constructs an empty date editor with a \a parent.
-*/
-
-QDateEdit::QDateEdit(QWidget *parent)
- : QDateTimeEdit(QDATETIMEEDIT_DATE_INITIAL, QVariant::Date, parent)
-{
-}
-
-/*!
- Constructs an empty date editor with a \a parent. The date is set
- to \a date.
-*/
-
-QDateEdit::QDateEdit(const QDate &date, QWidget *parent)
- : QDateTimeEdit(date, QVariant::Date, parent)
-{
-}
-
-
-// --- QDateTimeEditPrivate ---
-
-/*!
- \internal
- Constructs a QDateTimeEditPrivate object
-*/
-
-
-QDateTimeEditPrivate::QDateTimeEditPrivate()
- : QDateTimeParser(QVariant::DateTime, QDateTimeParser::DateTimeEdit)
-{
- hasHadFocus = false;
- formatExplicitlySet = false;
- cacheGuard = false;
- fixday = true;
- type = QVariant::DateTime;
- sections = 0;
- cachedDay = -1;
- currentSectionIndex = FirstSectionIndex;
-
- first.type = FirstSection;
- last.type = LastSection;
- none.type = NoSection;
- first.pos = 0;
- last.pos = -1;
- none.pos = -1;
- sections = 0;
- calendarPopup = false;
- minimum = QDATETIMEEDIT_COMPAT_DATETIME_MIN;
- maximum = QDATETIMEEDIT_DATETIME_MAX;
- arrowState = QStyle::State_None;
- monthCalendar = 0;
- readLocaleSettings();
-
-#ifdef QT_KEYPAD_NAVIGATION
- focusOnButton = false;
-#endif
-}
-
-void QDateTimeEditPrivate::updateTimeSpec()
-{
- minimum = minimum.toDateTime().toTimeSpec(spec);
- maximum = maximum.toDateTime().toTimeSpec(spec);
- value = value.toDateTime().toTimeSpec(spec);
-
- // time zone changes can lead to 00:00:00 becomes 01:00:00 and 23:59:59 becomes 00:59:59 (invalid range)
- const bool dateShown = (sections & QDateTimeEdit::DateSections_Mask);
- if (!dateShown) {
- if (minimum.toTime() >= maximum.toTime()){
- minimum = QDateTime(value.toDate(), QDATETIMEEDIT_TIME_MIN, spec);
- maximum = QDateTime(value.toDate(), QDATETIMEEDIT_TIME_MAX, spec);
- }
- }
-}
-
-void QDateTimeEditPrivate::updateEdit()
-{
- const QString newText = (specialValue() ? specialValueText : textFromValue(value));
- if (newText == displayText())
- return;
- int selsize = edit->selectedText().size();
- const bool sb = edit->blockSignals(true);
-
- edit->setText(newText);
-
- if (!specialValue()
-#ifdef QT_KEYPAD_NAVIGATION
- && !(QApplication::keypadNavigationEnabled() && !edit->hasEditFocus())
-#endif
- ) {
- int cursor = sectionPos(currentSectionIndex);
- QDTEDEBUG << "cursor is " << cursor << currentSectionIndex;
- cursor = qBound(0, cursor, displayText().size());
- QDTEDEBUG << cursor;
- if (selsize > 0) {
- edit->setSelection(cursor, selsize);
- QDTEDEBUG << cursor << selsize;
- } else {
- edit->setCursorPosition(cursor);
- QDTEDEBUG << cursor;
-
- }
- }
- edit->blockSignals(sb);
-}
-
-
-/*!
- \internal
-
- Selects the section \a s. If \a forward is false selects backwards.
-*/
-
-void QDateTimeEditPrivate::setSelected(int sectionIndex, bool forward)
-{
- if (specialValue()
-#ifdef QT_KEYPAD_NAVIGATION
- || (QApplication::keypadNavigationEnabled() && !edit->hasEditFocus())
-#endif
- ) {
- edit->selectAll();
- } else {
- const SectionNode &node = sectionNode(sectionIndex);
- if (node.type == NoSection || node.type == LastSection || node.type == FirstSection)
- return;
-
- updateCache(value, displayText());
- const int size = sectionSize(sectionIndex);
- if (forward) {
- edit->setSelection(sectionPos(node), size);
- } else {
- edit->setSelection(sectionPos(node) + size, -size);
- }
- }
-}
-
-/*!
- \internal
-
- Returns the section at index \a index or NoSection if there are no sections there.
-*/
-
-int QDateTimeEditPrivate::sectionAt(int pos) const
-{
- if (pos < separators.first().size()) {
- return (pos == 0 ? FirstSectionIndex : NoSectionIndex);
- } else if (displayText().size() - pos < separators.last().size() + 1) {
- if (separators.last().size() == 0) {
- return sectionNodes.count() - 1;
- }
- return (pos == displayText().size() ? LastSectionIndex : NoSectionIndex);
- }
- updateCache(value, displayText());
-
- for (int i=0; i<sectionNodes.size(); ++i) {
- const int tmp = sectionPos(i);
- if (pos < tmp + sectionSize(i)) {
- return (pos < tmp ? -1 : i);
- }
- }
- return -1;
-}
-
-/*!
- \internal
-
- Returns the closest section of index \a index. Searches forward
- for a section if \a forward is true. Otherwise searches backwards.
-*/
-
-int QDateTimeEditPrivate::closestSection(int pos, bool forward) const
-{
- Q_ASSERT(pos >= 0);
- if (pos < separators.first().size()) {
- return forward ? 0 : FirstSectionIndex;
- } else if (displayText().size() - pos < separators.last().size() + 1) {
- return forward ? LastSectionIndex : sectionNodes.size() - 1;
- }
- updateCache(value, displayText());
- for (int i=0; i<sectionNodes.size(); ++i) {
- const int tmp = sectionPos(sectionNodes.at(i));
- if (pos < tmp + sectionSize(i)) {
- if (pos < tmp && !forward) {
- return i-1;
- }
- return i;
- } else if (i == sectionNodes.size() - 1 && pos > tmp) {
- return i;
- }
- }
- qWarning("QDateTimeEdit: Internal Error: closestSection returned NoSection");
- return NoSectionIndex;
-}
-
-/*!
- \internal
-
- Returns a copy of the section that is before or after \a current, depending on \a forward.
-*/
-
-int QDateTimeEditPrivate::nextPrevSection(int current, bool forward) const
-{
- Q_Q(const QDateTimeEdit);
- if (q->isRightToLeft())
- forward = !forward;
-
- switch (current) {
- case FirstSectionIndex: return forward ? 0 : FirstSectionIndex;
- case LastSectionIndex: return (forward ? LastSectionIndex : sectionNodes.size() - 1);
- case NoSectionIndex: return FirstSectionIndex;
- default: break;
- }
- Q_ASSERT(current >= 0 && current < sectionNodes.size());
-
- current += (forward ? 1 : -1);
- if (current >= sectionNodes.size()) {
- return LastSectionIndex;
- } else if (current < 0) {
- return FirstSectionIndex;
- }
-
- return current;
-}
-
-/*!
- \internal
-
- Clears the text of section \a s.
-*/
-
-void QDateTimeEditPrivate::clearSection(int index)
-{
- const QLatin1Char space(' ');
- int cursorPos = edit->cursorPosition();
- bool blocked = edit->blockSignals(true);
- QString t = edit->text();
- const int pos = sectionPos(index);
- if (pos == -1) {
- qWarning("QDateTimeEdit: Internal error (%s:%d)", __FILE__, __LINE__);
- return;
- }
- const int size = sectionSize(index);
- t.replace(pos, size, QString().fill(space, size));
- edit->setText(t);
- edit->setCursorPosition(cursorPos);
- QDTEDEBUG << cursorPos;
-
- edit->blockSignals(blocked);
-}
-
-
-/*!
- \internal
-
- updates the cached values
-*/
-
-void QDateTimeEditPrivate::updateCache(const QVariant &val, const QString &str) const
-{
- if (val != cachedValue || str != cachedText || cacheGuard) {
- cacheGuard = true;
- QString copy = str;
- int unused = edit->cursorPosition();
- QValidator::State unusedState;
- validateAndInterpret(copy, unused, unusedState);
- cacheGuard = false;
- }
-}
-
-/*!
- \internal
-
- parses and validates \a input
-*/
-
-QDateTime QDateTimeEditPrivate::validateAndInterpret(QString &input, int &position,
- QValidator::State &state, bool fixup) const
-{
- if (input.isEmpty()) {
- if (sectionNodes.size() == 1 || !specialValueText.isEmpty()) {
- state = QValidator::Intermediate;
- } else {
- state = QValidator::Invalid;
- }
- return getZeroVariant().toDateTime();
- } else if (cachedText == input && !fixup) {
- state = cachedState;
- return cachedValue.toDateTime();
- } else if (!specialValueText.isEmpty()) {
- bool changeCase = false;
- const int max = qMin(specialValueText.size(), input.size());
- int i;
- for (i=0; i<max; ++i) {
- const QChar ic = input.at(i);
- const QChar sc = specialValueText.at(i);
- if (ic != sc) {
- if (sc.toLower() == ic.toLower()) {
- changeCase = true;
- } else {
- break;
- }
- }
- }
- if (i == max) {
- state = specialValueText.size() == input.size() ? QValidator::Acceptable : QValidator::Intermediate;
- if (changeCase) {
- input = specialValueText.left(max);
- }
- return minimum.toDateTime();
- }
- }
- StateNode tmp = parse(input, position, value.toDateTime(), fixup);
- input = tmp.input;
- state = QValidator::State(int(tmp.state));
- if (state == QValidator::Acceptable) {
- if (tmp.conflicts && conflictGuard != tmp.value) {
- conflictGuard = tmp.value;
- clearCache();
- input = textFromValue(tmp.value);
- updateCache(tmp.value, input);
- conflictGuard.clear();
- } else {
- cachedText = input;
- cachedState = state;
- cachedValue = tmp.value;
- }
- } else {
- clearCache();
- }
- return (tmp.value.isNull() ? getZeroVariant().toDateTime() : tmp.value);
-}
-
-
-/*!
- \internal
-*/
-
-QString QDateTimeEditPrivate::textFromValue(const QVariant &f) const
-{
- Q_Q(const QDateTimeEdit);
- return q->textFromDateTime(f.toDateTime());
-}
-
-/*!
- \internal
-
- This function's name is slightly confusing; it is not to be confused
- with QAbstractSpinBox::valueFromText().
-*/
-
-QVariant QDateTimeEditPrivate::valueFromText(const QString &f) const
-{
- Q_Q(const QDateTimeEdit);
- return q->dateTimeFromText(f).toTimeSpec(spec);
-}
-
-
-/*!
- \internal
-
- Internal function called by QDateTimeEdit::stepBy(). Also takes a
- Section for which section to step on and a bool \a test for
- whether or not to modify the internal cachedDay variable. This is
- necessary because the function is called from the const function
- QDateTimeEdit::stepEnabled() as well as QDateTimeEdit::stepBy().
-*/
-
-QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) const
-{
- Q_Q(const QDateTimeEdit);
- QDateTime v = value.toDateTime();
- QString str = displayText();
- int pos = edit->cursorPosition();
- const SectionNode sn = sectionNode(sectionIndex);
-
- int val;
- // to make sure it behaves reasonably when typing something and then stepping in non-tracking mode
- if (!test && pendingEmit) {
- if (q->validate(str, pos) != QValidator::Acceptable) {
- v = value.toDateTime();
- } else {
- v = q->dateTimeFromText(str);
- }
- val = getDigit(v, sectionIndex);
- } else {
- val = getDigit(v, sectionIndex);
- }
-
- val += steps;
-
- const int min = absoluteMin(sectionIndex);
- const int max = absoluteMax(sectionIndex, value.toDateTime());
-
- if (val < min) {
- val = (wrapping ? max - (min - val) + 1 : min);
- } else if (val > max) {
- val = (wrapping ? min + val - max - 1 : max);
- }
-
-
- const int oldDay = v.date().day();
-
- setDigit(v, sectionIndex, val);
- // if this sets year or month it will make
- // sure that days are lowered if needed.
-
- const QDateTime minimumDateTime = minimum.toDateTime();
- const QDateTime maximumDateTime = maximum.toDateTime();
- // changing one section should only modify that section, if possible
- if (sn.type != AmPmSection && (v < minimumDateTime || v > maximumDateTime)) {
- const int localmin = getDigit(minimumDateTime, sectionIndex);
- const int localmax = getDigit(maximumDateTime, sectionIndex);
-
- if (wrapping) {
- // just because we hit the roof in one direction, it
- // doesn't mean that we hit the floor in the other
- if (steps > 0) {
- setDigit(v, sectionIndex, min);
- if (!(sn.type & (DaySection|DayOfWeekSection)) && sections & DateSectionMask) {
- const int daysInMonth = v.date().daysInMonth();
- if (v.date().day() < oldDay && v.date().day() < daysInMonth) {
- const int adds = qMin(oldDay, daysInMonth);
- v = v.addDays(adds - v.date().day());
- }
- }
-
- if (v < minimumDateTime) {
- setDigit(v, sectionIndex, localmin);
- if (v < minimumDateTime)
- setDigit(v, sectionIndex, localmin + 1);
- }
- } else {
- setDigit(v, sectionIndex, max);
- if (!(sn.type & (DaySection|DayOfWeekSection)) && sections & DateSectionMask) {
- const int daysInMonth = v.date().daysInMonth();
- if (v.date().day() < oldDay && v.date().day() < daysInMonth) {
- const int adds = qMin(oldDay, daysInMonth);
- v = v.addDays(adds - v.date().day());
- }
- }
-
- if (v > maximumDateTime) {
- setDigit(v, sectionIndex, localmax);
- if (v > maximumDateTime)
- setDigit(v, sectionIndex, localmax - 1);
- }
- }
- } else {
- setDigit(v, sectionIndex, (steps > 0 ? localmax : localmin));
- }
- }
- if (!test && oldDay != v.date().day() && !(sn.type & (DaySection|DayOfWeekSection))) {
- // this should not happen when called from stepEnabled
- cachedDay = qMax<int>(oldDay, cachedDay);
- }
-
- if (v < minimumDateTime) {
- if (wrapping) {
- QDateTime t = v;
- setDigit(t, sectionIndex, steps < 0 ? max : min);
- bool mincmp = (t >= minimumDateTime);
- bool maxcmp = (t <= maximumDateTime);
- if (!mincmp || !maxcmp) {
- setDigit(t, sectionIndex, getDigit(steps < 0
- ? maximumDateTime
- : minimumDateTime, sectionIndex));
- mincmp = (t >= minimumDateTime);
- maxcmp = (t <= maximumDateTime);
- }
- if (mincmp && maxcmp) {
- v = t;
- }
- } else {
- v = value.toDateTime();
- }
- } else if (v > maximumDateTime) {
- if (wrapping) {
- QDateTime t = v;
- setDigit(t, sectionIndex, steps > 0 ? min : max);
- bool mincmp = (t >= minimumDateTime);
- bool maxcmp = (t <= maximumDateTime);
- if (!mincmp || !maxcmp) {
- setDigit(t, sectionIndex, getDigit(steps > 0 ?
- minimumDateTime :
- maximumDateTime, sectionIndex));
- mincmp = (t >= minimumDateTime);
- maxcmp = (t <= maximumDateTime);
- }
- if (mincmp && maxcmp) {
- v = t;
- }
- } else {
- v = value.toDateTime();
- }
- }
-
- const QDateTime ret = bound(v, value, steps).toDateTime().toTimeSpec(spec);
- return ret;
-}
-
-/*!
- \internal
-*/
-
-void QDateTimeEditPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
-{
- Q_Q(QDateTimeEdit);
- if (ep == NeverEmit) {
- return;
- }
- pendingEmit = false;
-
- const bool dodate = value.toDate().isValid() && (sections & DateSectionMask);
- const bool datechanged = (ep == AlwaysEmit || old.toDate() != value.toDate());
- const bool dotime = value.toTime().isValid() && (sections & TimeSectionMask);
- const bool timechanged = (ep == AlwaysEmit || old.toTime() != value.toTime());
-
- updateCache(value, displayText());
-
- syncCalendarWidget();
- if (datechanged || timechanged)
- emit q->dateTimeChanged(value.toDateTime());
- if (dodate && datechanged)
- emit q->dateChanged(value.toDate());
- if (dotime && timechanged)
- emit q->timeChanged(value.toTime());
-
-}
-
-/*!
- \internal
-*/
-
-void QDateTimeEditPrivate::_q_editorCursorPositionChanged(int oldpos, int newpos)
-{
- if (ignoreCursorPositionChanged || specialValue())
- return;
- const QString oldText = displayText();
- updateCache(value, oldText);
-
- const bool allowChange = !edit->hasSelectedText();
- const bool forward = oldpos <= newpos;
- ignoreCursorPositionChanged = true;
- int s = sectionAt(newpos);
- if (s == NoSectionIndex && forward && newpos > 0) {
- s = sectionAt(newpos - 1);
- }
-
- int c = newpos;
-
- const int selstart = edit->selectionStart();
- const int selSection = sectionAt(selstart);
- const int l = selSection != -1 ? sectionSize(selSection) : 0;
-
- if (s == NoSectionIndex) {
- if (l > 0 && selstart == sectionPos(selSection) && edit->selectedText().size() == l) {
- s = selSection;
- if (allowChange)
- setSelected(selSection, true);
- c = -1;
- } else {
- int closest = closestSection(newpos, forward);
- c = sectionPos(closest) + (forward ? 0 : qMax<int>(0, sectionSize(closest)));
-
- if (allowChange) {
- edit->setCursorPosition(c);
- QDTEDEBUG << c;
- }
- s = closest;
- }
- }
-
- if (allowChange && currentSectionIndex != s) {
- interpret(EmitIfChanged);
- }
- if (c == -1) {
- setSelected(s, true);
- } else if (!edit->hasSelectedText()) {
- if (oldpos < newpos) {
- edit->setCursorPosition(displayText().size() - (oldText.size() - c));
- } else {
- edit->setCursorPosition(c);
- }
- }
-
- QDTEDEBUG << "currentSectionIndex is set to" << sectionName(sectionType(s))
- << oldpos << newpos
- << "was" << sectionName(sectionType(currentSectionIndex));
-
- currentSectionIndex = s;
- Q_ASSERT_X(currentSectionIndex < sectionNodes.size(),
- "QDateTimeEditPrivate::_q_editorCursorPositionChanged()",
- qPrintable(QString::fromAscii("Internal error (%1 %2)").
- arg(currentSectionIndex).
- arg(sectionNodes.size())));
-
- ignoreCursorPositionChanged = false;
-}
-
-/*!
- \internal
-
- Try to get the format from the local settings
-*/
-void QDateTimeEditPrivate::readLocaleSettings()
-{
- const QLocale loc;
- defaultTimeFormat = loc.timeFormat(QLocale::ShortFormat);
- defaultDateFormat = loc.dateFormat(QLocale::ShortFormat);
- defaultDateTimeFormat = loc.dateTimeFormat(QLocale::ShortFormat);
-}
-
-QDateTimeEdit::Section QDateTimeEditPrivate::convertToPublic(QDateTimeParser::Section s)
-{
- switch (s & ~Internal) {
- case AmPmSection: return QDateTimeEdit::AmPmSection;
- case MSecSection: return QDateTimeEdit::MSecSection;
- case SecondSection: return QDateTimeEdit::SecondSection;
- case MinuteSection: return QDateTimeEdit::MinuteSection;
- case DayOfWeekSection:
- case DaySection: return QDateTimeEdit::DaySection;
- case MonthSection: return QDateTimeEdit::MonthSection;
- case YearSection2Digits:
- case YearSection: return QDateTimeEdit::YearSection;
- case Hour12Section:
- case Hour24Section: return QDateTimeEdit::HourSection;
- case FirstSection:
- case NoSection:
- case LastSection: break;
- }
- return QDateTimeEdit::NoSection;
-}
-
-QDateTimeEdit::Sections QDateTimeEditPrivate::convertSections(QDateTimeParser::Sections s)
-{
- QDateTimeEdit::Sections ret = 0;
- if (s & QDateTimeParser::MSecSection)
- ret |= QDateTimeEdit::MSecSection;
- if (s & QDateTimeParser::SecondSection)
- ret |= QDateTimeEdit::SecondSection;
- if (s & QDateTimeParser::MinuteSection)
- ret |= QDateTimeEdit::MinuteSection;
- if (s & (QDateTimeParser::Hour24Section|QDateTimeParser::Hour12Section))
- ret |= QDateTimeEdit::HourSection;
- if (s & QDateTimeParser::AmPmSection)
- ret |= QDateTimeEdit::AmPmSection;
- if (s & (QDateTimeParser::DaySection|QDateTimeParser::DayOfWeekSection))
- ret |= QDateTimeEdit::DaySection;
- if (s & QDateTimeParser::MonthSection)
- ret |= QDateTimeEdit::MonthSection;
- if (s & (QDateTimeParser::YearSection|QDateTimeParser::YearSection2Digits))
- ret |= QDateTimeEdit::YearSection;
-
- return ret;
-}
-
-/*!
- \reimp
-*/
-
-void QDateTimeEdit::paintEvent(QPaintEvent *event)
-{
- Q_D(QDateTimeEdit);
- if (!d->calendarPopupEnabled()) {
- QAbstractSpinBox::paintEvent(event);
- return;
- }
-
- QStyleOptionSpinBox opt;
- initStyleOption(&opt);
-
- QStyleOptionComboBox optCombo;
-
- optCombo.init(this);
- optCombo.editable = true;
- optCombo.frame = opt.frame;
- optCombo.subControls = opt.subControls;
- optCombo.activeSubControls = opt.activeSubControls;
- optCombo.state = opt.state;
- if (d->readOnly) {
- optCombo.state &= ~QStyle::State_Enabled;
- }
-
- QPainter p(this);
- style()->drawComplexControl(QStyle::CC_ComboBox, &optCombo, &p, this);
-}
-
-QString QDateTimeEditPrivate::getAmPmText(AmPm ap, Case cs) const
-{
- if (ap == AmText) {
- return (cs == UpperCase ? QDateTimeEdit::tr("AM") : QDateTimeEdit::tr("am"));
- } else {
- return (cs == UpperCase ? QDateTimeEdit::tr("PM") : QDateTimeEdit::tr("pm"));
- }
-}
-
-int QDateTimeEditPrivate::absoluteIndex(QDateTimeEdit::Section s, int index) const
-{
- for (int i=0; i<sectionNodes.size(); ++i) {
- if (convertToPublic(sectionNodes.at(i).type) == s && index-- == 0) {
- return i;
- }
- }
- return NoSectionIndex;
-}
-
-int QDateTimeEditPrivate::absoluteIndex(const SectionNode &s) const
-{
- return sectionNodes.indexOf(s);
-}
-
-void QDateTimeEditPrivate::interpret(EmitPolicy ep)
-{
- Q_Q(QDateTimeEdit);
- QString tmp = displayText();
- int pos = edit->cursorPosition();
- const QValidator::State state = q->validate(tmp, pos);
- if (state != QValidator::Acceptable
- && correctionMode == QAbstractSpinBox::CorrectToPreviousValue
- && (state == QValidator::Invalid || !(fieldInfo(currentSectionIndex) & AllowPartial))) {
- setValue(value, ep);
- updateTimeSpec();
- } else {
- QAbstractSpinBoxPrivate::interpret(ep);
- }
-}
-
-void QDateTimeEditPrivate::clearCache() const
-{
- QAbstractSpinBoxPrivate::clearCache();
- cachedDay = -1;
-}
-
-/*!
- Initialize \a option with the values from this QDataTimeEdit. This method
- is useful for subclasses when they need a QStyleOptionSpinBox, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QDateTimeEdit::initStyleOption(QStyleOptionSpinBox *option) const
-{
- if (!option)
- return;
-
- Q_D(const QDateTimeEdit);
- QAbstractSpinBox::initStyleOption(option);
- if (d->calendarPopupEnabled()) {
- option->subControls = QStyle::SC_ComboBoxFrame | QStyle::SC_ComboBoxEditField
- | QStyle::SC_ComboBoxArrow;
- if (d->arrowState == QStyle::State_Sunken)
- option->state |= QStyle::State_Sunken;
- else
- option->state &= ~QStyle::State_Sunken;
- }
-}
-
-void QDateTimeEditPrivate::init(const QVariant &var)
-{
- Q_Q(QDateTimeEdit);
- switch (var.type()) {
- case QVariant::Date:
- value = QDateTime(var.toDate(), QDATETIMEEDIT_TIME_MIN);
- q->setDisplayFormat(defaultDateFormat);
- if (sectionNodes.isEmpty()) // ### safeguard for broken locale
- q->setDisplayFormat(QLatin1String("dd/MM/yyyy"));
- break;
- case QVariant::DateTime:
- value = var;
- q->setDisplayFormat(defaultDateTimeFormat);
- if (sectionNodes.isEmpty()) // ### safeguard for broken locale
- q->setDisplayFormat(QLatin1String("dd/MM/yyyy hh:mm:ss"));
- break;
- case QVariant::Time:
- value = QDateTime(QDATETIMEEDIT_DATE_INITIAL, var.toTime());
- q->setDisplayFormat(defaultTimeFormat);
- if (sectionNodes.isEmpty()) // ### safeguard for broken locale
- q->setDisplayFormat(QLatin1String("hh:mm:ss"));
- break;
- default:
- Q_ASSERT_X(0, "QDateTimeEditPrivate::init", "Internal error");
- break;
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- q->setCalendarPopup(true);
-#endif
- updateTimeSpec();
- q->setInputMethodHints(Qt::ImhPreferNumbers);
- setLayoutItemMargins(QStyle::SE_DateTimeEditLayoutItem);
-}
-
-void QDateTimeEditPrivate::_q_resetButton()
-{
- updateArrow(QStyle::State_None);
-}
-
-void QDateTimeEditPrivate::updateArrow(QStyle::StateFlag state)
-{
- Q_Q(QDateTimeEdit);
-
- if (arrowState == state)
- return;
- arrowState = state;
- if (arrowState != QStyle::State_None)
- buttonState |= Mouse;
- else {
- buttonState = 0;
- hoverControl = QStyle::SC_ComboBoxFrame;
- }
- q->update();
-}
-
-/*!
- \internal
- Returns the hover control at \a pos.
- This will update the hoverRect and hoverControl.
-*/
-QStyle::SubControl QDateTimeEditPrivate::newHoverControl(const QPoint &pos)
-{
- if (!calendarPopupEnabled())
- return QAbstractSpinBoxPrivate::newHoverControl(pos);
-
- Q_Q(QDateTimeEdit);
-
- QStyleOptionComboBox optCombo;
- optCombo.init(q);
- optCombo.editable = true;
- optCombo.subControls = QStyle::SC_All;
- hoverControl = q->style()->hitTestComplexControl(QStyle::CC_ComboBox, &optCombo, pos, q);
- return hoverControl;
-}
-
-void QDateTimeEditPrivate::updateEditFieldGeometry()
-{
- if (!calendarPopupEnabled()) {
- QAbstractSpinBoxPrivate::updateEditFieldGeometry();
- return;
- }
-
- Q_Q(QDateTimeEdit);
-
- QStyleOptionComboBox optCombo;
- optCombo.init(q);
- optCombo.editable = true;
- optCombo.subControls = QStyle::SC_ComboBoxEditField;
- edit->setGeometry(q->style()->subControlRect(QStyle::CC_ComboBox, &optCombo,
- QStyle::SC_ComboBoxEditField, q));
-}
-
-QVariant QDateTimeEditPrivate::getZeroVariant() const
-{
- Q_ASSERT(type == QVariant::DateTime);
- return QDateTime(QDATETIMEEDIT_DATE_INITIAL, QTime(), spec);
-}
-
-void QDateTimeEditPrivate::setRange(const QVariant &min, const QVariant &max)
-{
- QAbstractSpinBoxPrivate::setRange(min, max);
- syncCalendarWidget();
-}
-
-
-bool QDateTimeEditPrivate::isSeparatorKey(const QKeyEvent *ke) const
-{
- if (!ke->text().isEmpty() && currentSectionIndex + 1 < sectionNodes.size() && currentSectionIndex >= 0) {
- if (fieldInfo(currentSectionIndex) & Numeric) {
- if (ke->text().at(0).isNumber())
- return false;
- } else if (ke->text().at(0).isLetterOrNumber()) {
- return false;
- }
- return separators.at(currentSectionIndex + 1).contains(ke->text());
- }
- return false;
-}
-
-void QDateTimeEditPrivate::initCalendarPopup(QCalendarWidget *cw)
-{
- Q_Q(QDateTimeEdit);
- if (!monthCalendar) {
- monthCalendar = new QCalendarPopup(q, cw);
- monthCalendar->setObjectName(QLatin1String("qt_datetimedit_calendar"));
- QObject::connect(monthCalendar, SIGNAL(newDateSelected(QDate)), q, SLOT(setDate(QDate)));
- QObject::connect(monthCalendar, SIGNAL(hidingCalendar(QDate)), q, SLOT(setDate(QDate)));
- QObject::connect(monthCalendar, SIGNAL(activated(QDate)), q, SLOT(setDate(QDate)));
- QObject::connect(monthCalendar, SIGNAL(activated(QDate)), monthCalendar, SLOT(close()));
- QObject::connect(monthCalendar, SIGNAL(resetButton()), q, SLOT(_q_resetButton()));
- } else if (cw) {
- monthCalendar->setCalendarWidget(cw);
- }
- syncCalendarWidget();
-}
-
-void QDateTimeEditPrivate::positionCalendarPopup()
-{
- Q_Q(QDateTimeEdit);
- QPoint pos = (q->layoutDirection() == Qt::RightToLeft) ? q->rect().bottomRight() : q->rect().bottomLeft();
- QPoint pos2 = (q->layoutDirection() == Qt::RightToLeft) ? q->rect().topRight() : q->rect().topLeft();
- pos = q->mapToGlobal(pos);
- pos2 = q->mapToGlobal(pos2);
- QSize size = monthCalendar->sizeHint();
- QRect screen = QApplication::desktop()->availableGeometry(pos);
- //handle popup falling "off screen"
- if (q->layoutDirection() == Qt::RightToLeft) {
- pos.setX(pos.x()-size.width());
- pos2.setX(pos2.x()-size.width());
- if (pos.x() < screen.left())
- pos.setX(qMax(pos.x(), screen.left()));
- else if (pos.x()+size.width() > screen.right())
- pos.setX(qMax(pos.x()-size.width(), screen.right()-size.width()));
- } else {
- if (pos.x()+size.width() > screen.right())
- pos.setX(screen.right()-size.width());
- pos.setX(qMax(pos.x(), screen.left()));
- }
- if (pos.y() + size.height() > screen.bottom())
- pos.setY(pos2.y() - size.height());
- else if (pos.y() < screen.top())
- pos.setY(screen.top());
- if (pos.y() < screen.top())
- pos.setY(screen.top());
- if (pos.y()+size.height() > screen.bottom())
- pos.setY(screen.bottom()-size.height());
- monthCalendar->move(pos);
-}
-
-bool QDateTimeEditPrivate::calendarPopupEnabled() const
-{
- return (calendarPopup && (sections & (DateSectionMask)));
-}
-
-void QDateTimeEditPrivate::syncCalendarWidget()
-{
- Q_Q(QDateTimeEdit);
- if (monthCalendar) {
- monthCalendar->setDateRange(q->minimumDate(), q->maximumDate());
- monthCalendar->setDate(q->date());
- }
-}
-
-QCalendarPopup::QCalendarPopup(QWidget * parent, QCalendarWidget *cw)
- : QWidget(parent, Qt::Popup), calendar(0)
-{
- setAttribute(Qt::WA_WindowPropagation);
-
- dateChanged = false;
- if (!cw) {
- cw = new QCalendarWidget(this);
- cw->setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader);
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- cw->setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames);
-#endif
- }
- setCalendarWidget(cw);
-}
-
-void QCalendarPopup::setCalendarWidget(QCalendarWidget *cw)
-{
- Q_ASSERT(cw);
- QVBoxLayout *widgetLayout = qobject_cast<QVBoxLayout*>(layout());
- if (!widgetLayout) {
- widgetLayout = new QVBoxLayout(this);
- widgetLayout->setMargin(0);
- widgetLayout->setSpacing(0);
- }
- delete calendar;
- calendar = cw;
- widgetLayout->addWidget(calendar);
-
- connect(calendar, SIGNAL(activated(QDate)), this, SLOT(dateSelected(QDate)));
- connect(calendar, SIGNAL(clicked(QDate)), this, SLOT(dateSelected(QDate)));
- connect(calendar, SIGNAL(selectionChanged()), this, SLOT(dateSelectionChanged()));
-
- calendar->setFocus();
-}
-
-
-void QCalendarPopup::setDate(const QDate &date)
-{
- oldDate = date;
- calendar->setSelectedDate(date);
-}
-
-void QCalendarPopup::setDateRange(const QDate &min, const QDate &max)
-{
- calendar->setMinimumDate(min);
- calendar->setMaximumDate(max);
-}
-
-void QCalendarPopup::mousePressEvent(QMouseEvent *event)
-{
- QDateTimeEdit *dateTime = qobject_cast<QDateTimeEdit *>(parentWidget());
- if (dateTime) {
- QStyleOptionComboBox opt;
- opt.init(dateTime);
- QRect arrowRect = dateTime->style()->subControlRect(QStyle::CC_ComboBox, &opt,
- QStyle::SC_ComboBoxArrow, dateTime);
- arrowRect.moveTo(dateTime->mapToGlobal(arrowRect .topLeft()));
- if (arrowRect.contains(event->globalPos()) || rect().contains(event->pos()))
- setAttribute(Qt::WA_NoMouseReplay);
- }
- QWidget::mousePressEvent(event);
-}
-
-void QCalendarPopup::mouseReleaseEvent(QMouseEvent*)
-{
- emit resetButton();
-}
-
-bool QCalendarPopup::event(QEvent *event)
-{
- if (event->type() == QEvent::KeyPress) {
- QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
- if (keyEvent->key()== Qt::Key_Escape)
- dateChanged = false;
- }
- return QWidget::event(event);
-}
-
-void QCalendarPopup::dateSelectionChanged()
-{
- dateChanged = true;
- emit newDateSelected(calendar->selectedDate());
-}
-void QCalendarPopup::dateSelected(const QDate &date)
-{
- dateChanged = true;
- emit activated(date);
- close();
-}
-
-void QCalendarPopup::hideEvent(QHideEvent *)
-{
- emit resetButton();
- if (!dateChanged)
- emit hidingCalendar(oldDate);
-}
-
-QT_END_NAMESPACE
-#include "moc_qdatetimeedit.cpp"
-
-#endif // QT_NO_DATETIMEEDIT
diff --git a/src/gui/widgets/qdatetimeedit.h b/src/gui/widgets/qdatetimeedit.h
deleted file mode 100644
index d174a41fc7..0000000000
--- a/src/gui/widgets/qdatetimeedit.h
+++ /dev/null
@@ -1,230 +0,0 @@
-/****************************************************************************
-**
-** 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 QDATETIMEEDIT_H
-#define QDATETIMEEDIT_H
-
-#include <QtCore/qdatetime.h>
-#include <QtCore/qvariant.h>
-#include <QtGui/qabstractspinbox.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_DATETIMEEDIT
-
-class QDateTimeEditPrivate;
-class QStyleOptionSpinBox;
-class QCalendarWidget;
-
-class Q_GUI_EXPORT QDateTimeEdit : public QAbstractSpinBox
-{
- Q_OBJECT
-
- Q_ENUMS(Section)
- Q_FLAGS(Sections)
- Q_PROPERTY(QDateTime dateTime READ dateTime WRITE setDateTime NOTIFY dateTimeChanged USER true)
- Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY dateChanged)
- Q_PROPERTY(QTime time READ time WRITE setTime NOTIFY timeChanged)
- Q_PROPERTY(QDateTime maximumDateTime READ maximumDateTime WRITE setMaximumDateTime RESET clearMaximumDateTime)
- Q_PROPERTY(QDateTime minimumDateTime READ minimumDateTime WRITE setMinimumDateTime RESET clearMinimumDateTime)
- Q_PROPERTY(QDate maximumDate READ maximumDate WRITE setMaximumDate RESET clearMaximumDate)
- Q_PROPERTY(QDate minimumDate READ minimumDate WRITE setMinimumDate RESET clearMinimumDate)
- Q_PROPERTY(QTime maximumTime READ maximumTime WRITE setMaximumTime RESET clearMaximumTime)
- Q_PROPERTY(QTime minimumTime READ minimumTime WRITE setMinimumTime RESET clearMinimumTime)
- Q_PROPERTY(Section currentSection READ currentSection WRITE setCurrentSection)
- Q_PROPERTY(Sections displayedSections READ displayedSections)
- Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)
- Q_PROPERTY(bool calendarPopup READ calendarPopup WRITE setCalendarPopup)
- Q_PROPERTY(int currentSectionIndex READ currentSectionIndex WRITE setCurrentSectionIndex)
- Q_PROPERTY(int sectionCount READ sectionCount)
- Q_PROPERTY(Qt::TimeSpec timeSpec READ timeSpec WRITE setTimeSpec)
-public:
- enum Section {
- NoSection = 0x0000,
- AmPmSection = 0x0001,
- MSecSection = 0x0002,
- SecondSection = 0x0004,
- MinuteSection = 0x0008,
- HourSection = 0x0010,
- DaySection = 0x0100,
- MonthSection = 0x0200,
- YearSection = 0x0400,
- TimeSections_Mask = AmPmSection|MSecSection|SecondSection|MinuteSection|HourSection,
- DateSections_Mask = DaySection|MonthSection|YearSection
- };
-
- Q_DECLARE_FLAGS(Sections, Section)
-
- explicit QDateTimeEdit(QWidget *parent = 0);
- explicit QDateTimeEdit(const QDateTime &dt, QWidget *parent = 0);
- explicit QDateTimeEdit(const QDate &d, QWidget *parent = 0);
- explicit QDateTimeEdit(const QTime &t, QWidget *parent = 0);
-
- QDateTime dateTime() const;
- QDate date() const;
- QTime time() const;
-
- QDateTime minimumDateTime() const;
- void clearMinimumDateTime();
- void setMinimumDateTime(const QDateTime &dt);
-
- QDateTime maximumDateTime() const;
- void clearMaximumDateTime();
- void setMaximumDateTime(const QDateTime &dt);
-
- void setDateTimeRange(const QDateTime &min, const QDateTime &max);
-
- QDate minimumDate() const;
- void setMinimumDate(const QDate &min);
- void clearMinimumDate();
-
- QDate maximumDate() const;
- void setMaximumDate(const QDate &max);
- void clearMaximumDate();
-
- void setDateRange(const QDate &min, const QDate &max);
-
- QTime minimumTime() const;
- void setMinimumTime(const QTime &min);
- void clearMinimumTime();
-
- QTime maximumTime() const;
- void setMaximumTime(const QTime &max);
- void clearMaximumTime();
-
- void setTimeRange(const QTime &min, const QTime &max);
-
- Sections displayedSections() const;
- Section currentSection() const;
- Section sectionAt(int index) const;
- void setCurrentSection(Section section);
-
- int currentSectionIndex() const;
- void setCurrentSectionIndex(int index);
-
- QCalendarWidget *calendarWidget() const;
- void setCalendarWidget(QCalendarWidget *calendarWidget);
-
- int sectionCount() const;
-
- void setSelectedSection(Section section);
-
- QString sectionText(Section section) const;
-
- QString displayFormat() const;
- void setDisplayFormat(const QString &format);
-
- bool calendarPopup() const;
- void setCalendarPopup(bool enable);
-
- Qt::TimeSpec timeSpec() const;
- void setTimeSpec(Qt::TimeSpec spec);
-
- QSize sizeHint() const;
-
- virtual void clear();
- virtual void stepBy(int steps);
-
- bool event(QEvent *event);
-Q_SIGNALS:
- void dateTimeChanged(const QDateTime &date);
- void timeChanged(const QTime &date);
- void dateChanged(const QDate &date);
-
-public Q_SLOTS:
- void setDateTime(const QDateTime &dateTime);
- void setDate(const QDate &date);
- void setTime(const QTime &time);
-
-protected:
- virtual void keyPressEvent(QKeyEvent *event);
-#ifndef QT_NO_WHEELEVENT
- virtual void wheelEvent(QWheelEvent *event);
-#endif
- virtual void focusInEvent(QFocusEvent *event);
- virtual bool focusNextPrevChild(bool next);
- virtual QValidator::State validate(QString &input, int &pos) const;
- virtual void fixup(QString &input) const;
-
- virtual QDateTime dateTimeFromText(const QString &text) const;
- virtual QString textFromDateTime(const QDateTime &dt) const;
- virtual StepEnabled stepEnabled() const;
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void paintEvent(QPaintEvent *event);
- void initStyleOption(QStyleOptionSpinBox *option) const;
-
- QDateTimeEdit(const QVariant &val, QVariant::Type parserType, QWidget *parent = 0);
-private:
- Q_DECLARE_PRIVATE(QDateTimeEdit)
- Q_DISABLE_COPY(QDateTimeEdit)
-
- Q_PRIVATE_SLOT(d_func(), void _q_resetButton())
-};
-
-class Q_GUI_EXPORT QTimeEdit : public QDateTimeEdit
-{
- Q_OBJECT
-public:
- QTimeEdit(QWidget *parent = 0);
- QTimeEdit(const QTime &time, QWidget *parent = 0);
-};
-
-class Q_GUI_EXPORT QDateEdit : public QDateTimeEdit
-{
- Q_OBJECT
-public:
- QDateEdit(QWidget *parent = 0);
- QDateEdit(const QDate &date, QWidget *parent = 0);
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QDateTimeEdit::Sections)
-
-#endif // QT_NO_DATETIMEEDIT
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDATETIMEEDIT_H
diff --git a/src/gui/widgets/qdatetimeedit_p.h b/src/gui/widgets/qdatetimeedit_p.h
deleted file mode 100644
index acdc87826d..0000000000
--- a/src/gui/widgets/qdatetimeedit_p.h
+++ /dev/null
@@ -1,183 +0,0 @@
-/****************************************************************************
-**
-** 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 QDATETIMEEDIT_P_H
-#define QDATETIMEEDIT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qcombobox.h"
-#include "QtGui/qcalendarwidget.h"
-#include "QtGui/qspinbox.h"
-#include "QtGui/qtoolbutton.h"
-#include "QtGui/qmenu.h"
-#include "QtGui/qlabel.h"
-#include "QtGui/qdatetimeedit.h"
-#include "QtGui/private/qabstractspinbox_p.h"
-#include "QtCore/private/qdatetime_p.h"
-
-#include "qdebug.h"
-
-#ifndef QT_NO_DATETIMEEDIT
-
-QT_BEGIN_NAMESPACE
-
-class QCalendarPopup;
-class QDateTimeEditPrivate : public QAbstractSpinBoxPrivate, public QDateTimeParser
-{
- Q_DECLARE_PUBLIC(QDateTimeEdit)
-public:
- QDateTimeEditPrivate();
-
- void init(const QVariant &var);
- void readLocaleSettings();
-
- void emitSignals(EmitPolicy ep, const QVariant &old);
- QString textFromValue(const QVariant &f) const;
- QVariant valueFromText(const QString &f) const;
- virtual void _q_editorCursorPositionChanged(int oldpos, int newpos);
- virtual void interpret(EmitPolicy ep);
- virtual void clearCache() const;
-
- QDateTime validateAndInterpret(QString &input, int &, QValidator::State &state,
- bool fixup = false) const;
- void clearSection(int index);
- virtual QString displayText() const { return edit->text(); } // this is from QDateTimeParser
-
- int absoluteIndex(QDateTimeEdit::Section s, int index) const;
- int absoluteIndex(const SectionNode &s) const;
- void updateEdit();
- QDateTime stepBy(int index, int steps, bool test = false) const;
- int sectionAt(int pos) const;
- int closestSection(int index, bool forward) const;
- int nextPrevSection(int index, bool forward) const;
- void setSelected(int index, bool forward = false);
-
- void updateCache(const QVariant &val, const QString &str) const;
-
- void updateTimeSpec();
- virtual QDateTime getMinimum() const { return minimum.toDateTime(); }
- virtual QDateTime getMaximum() const { return maximum.toDateTime(); }
- virtual QLocale locale() const { return q_func()->locale(); }
- QString valueToText(const QVariant &var) const { return textFromValue(var); }
- QString getAmPmText(AmPm ap, Case cs) const;
- int cursorPosition() const { return edit ? edit->cursorPosition() : -1; }
-
- virtual QStyle::SubControl newHoverControl(const QPoint &pos);
- virtual void updateEditFieldGeometry();
- virtual QVariant getZeroVariant() const;
- virtual void setRange(const QVariant &min, const QVariant &max);
-
- void _q_resetButton();
- void updateArrow(QStyle::StateFlag state);
- bool calendarPopupEnabled() const;
- void syncCalendarWidget();
-
- bool isSeparatorKey(const QKeyEvent *k) const;
-
- static QDateTimeEdit::Sections convertSections(QDateTimeParser::Sections s);
- static QDateTimeEdit::Section convertToPublic(QDateTimeParser::Section s);
-
- void initCalendarPopup(QCalendarWidget *cw = 0);
- void positionCalendarPopup();
-
- QDateTimeEdit::Sections sections;
- mutable bool cacheGuard;
-
- QString defaultDateFormat, defaultTimeFormat, defaultDateTimeFormat, unreversedFormat;
- mutable QVariant conflictGuard;
- bool hasHadFocus, formatExplicitlySet, calendarPopup;
- QStyle::StateFlag arrowState;
- QCalendarPopup *monthCalendar;
-
-#ifdef QT_KEYPAD_NAVIGATION
- bool focusOnButton;
-#endif
-};
-
-
-class QCalendarPopup : public QWidget
-{
- Q_OBJECT
-public:
- QCalendarPopup(QWidget *parent = 0, QCalendarWidget *cw = 0);
- QDate selectedDate() { return calendar->selectedDate(); }
- void setDate(const QDate &date);
- void setDateRange(const QDate &min, const QDate &max);
- void setFirstDayOfWeek(Qt::DayOfWeek dow) { calendar->setFirstDayOfWeek(dow); }
- QCalendarWidget *calendarWidget() const { return calendar; }
- void setCalendarWidget(QCalendarWidget *cw);
-Q_SIGNALS:
- void activated(const QDate &date);
- void newDateSelected(const QDate &newDate);
- void hidingCalendar(const QDate &oldDate);
- void resetButton();
-
-private Q_SLOTS:
- void dateSelected(const QDate &date);
- void dateSelectionChanged();
-
-protected:
- void hideEvent(QHideEvent *);
- void mousePressEvent(QMouseEvent *e);
- void mouseReleaseEvent(QMouseEvent *);
- bool event(QEvent *e);
-
-private:
- QCalendarWidget *calendar;
- QDate oldDate;
- bool dateChanged;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DATETIMEEDIT
-
-#endif // QDATETIMEEDIT_P_H
diff --git a/src/gui/widgets/qdial.cpp b/src/gui/widgets/qdial.cpp
deleted file mode 100644
index 19e8d231ca..0000000000
--- a/src/gui/widgets/qdial.cpp
+++ /dev/null
@@ -1,546 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdial.h"
-
-#ifndef QT_NO_DIAL
-
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcolor.h>
-#include <qevent.h>
-#include <qpainter.h>
-#include <qpolygon.h>
-#include <qregion.h>
-#include <qstyle.h>
-#include <qstylepainter.h>
-#include <qstyleoption.h>
-#include <qslider.h>
-#include <private/qabstractslider_p.h>
-#include <private/qmath_p.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include <qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDialPrivate : public QAbstractSliderPrivate
-{
- Q_DECLARE_PUBLIC(QDial)
-public:
- QDialPrivate()
- {
- wrapping = false;
- tracking = true;
- doNotEmit = false;
- target = qreal(3.7);
- }
-
- qreal target;
- uint showNotches : 1;
- uint wrapping : 1;
- uint doNotEmit : 1;
-
- int valueFromPoint(const QPoint &) const;
- double angle(const QPoint &, const QPoint &) const;
- void init();
- virtual int bound(int val) const;
-};
-
-void QDialPrivate::init()
-{
- Q_Q(QDial);
- showNotches = false;
- q->setFocusPolicy(Qt::WheelFocus);
-#ifdef QT3_SUPPORT
- QObject::connect(q, SIGNAL(sliderPressed()), q, SIGNAL(dialPressed()));
- QObject::connect(q, SIGNAL(sliderMoved(int)), q, SIGNAL(dialMoved(int)));
- QObject::connect(q, SIGNAL(sliderReleased()), q, SIGNAL(dialReleased()));
-#endif
-}
-
-int QDialPrivate::bound(int val) const
-{
- if (wrapping) {
- if ((val >= minimum) && (val <= maximum))
- return val;
- val = minimum + ((val - minimum) % (maximum - minimum));
- if (val < minimum)
- val += maximum - minimum;
- return val;
- } else {
- return QAbstractSliderPrivate::bound(val);
- }
-}
-
-/*!
- Initialize \a option with the values from this QDial. This method
- is useful for subclasses when they need a QStyleOptionSlider, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QDial::initStyleOption(QStyleOptionSlider *option) const
-{
- if (!option)
- return;
-
- Q_D(const QDial);
- option->initFrom(this);
- option->minimum = d->minimum;
- option->maximum = d->maximum;
- option->sliderPosition = d->position;
- option->sliderValue = d->value;
- option->singleStep = d->singleStep;
- option->pageStep = d->pageStep;
- option->upsideDown = !d->invertedAppearance;
- option->notchTarget = d->target;
- option->dialWrapping = d->wrapping;
- option->subControls = QStyle::SC_All;
- option->activeSubControls = QStyle::SC_None;
- if (!d->showNotches) {
- option->subControls &= ~QStyle::SC_DialTickmarks;
- option->tickPosition = QSlider::TicksAbove;
- } else {
- option->tickPosition = QSlider::NoTicks;
- }
- option->tickInterval = notchSize();
-}
-
-int QDialPrivate::valueFromPoint(const QPoint &p) const
-{
- Q_Q(const QDial);
- double yy = (double)q->height()/2.0 - p.y();
- double xx = (double)p.x() - q->width()/2.0;
- double a = (xx || yy) ? qAtan2(yy, xx) : 0;
-
- if (a < Q_PI / -2)
- a = a + Q_PI * 2;
-
- int dist = 0;
- int minv = minimum, maxv = maximum;
-
- if (minimum < 0) {
- dist = -minimum;
- minv = 0;
- maxv = maximum + dist;
- }
-
- int r = maxv - minv;
- int v;
- if (wrapping)
- v = (int)(0.5 + minv + r * (Q_PI * 3 / 2 - a) / (2 * Q_PI));
- else
- v = (int)(0.5 + minv + r* (Q_PI * 4 / 3 - a) / (Q_PI * 10 / 6));
-
- if (dist > 0)
- v -= dist;
-
- return !invertedAppearance ? bound(v) : maximum - bound(v);
-}
-
-/*!
- \class QDial
-
- \brief The QDial class provides a rounded range control (like a speedometer or potentiometer).
-
- \ingroup basicwidgets
-
-
- QDial is used when the user needs to control a value within a
- program-definable range, and the range either wraps around
- (for example, with angles measured from 0 to 359 degrees) or the
- dialog layout needs a square widget.
-
- Since QDial inherits from QAbstractSlider, the dial behaves in
- a similar way to a \l{QSlider}{slider}. When wrapping() is false
- (the default setting) there is no real difference between a slider
- and a dial. They both share the same signals, slots and member
- functions. Which one you use depends on the expectations of
- your users and on the type of application.
-
- The dial initially emits valueChanged() signals continuously while
- the slider is being moved; you can make it emit the signal less
- often by disabling the \l{QAbstractSlider::tracking} {tracking}
- property. The sliderMoved() signal is emitted continuously even
- when tracking is disabled.
-
- The dial also emits sliderPressed() and sliderReleased() signals
- when the mouse button is pressed and released. Note that the
- dial's value can change without these signals being emitted since
- the keyboard and wheel can also be used to change the value.
-
- Unlike the slider, QDial attempts to draw a "nice" number of
- notches rather than one per line step. If possible, the number of
- notches drawn is one per line step, but if there aren't enough pixels
- to draw every one, QDial will skip notches to try and draw a uniform
- set (e.g. by drawing every second or third notch).
-
- Like the slider, the dial makes the QAbstractSlider functions
- setValue(), addLine(), subtractLine(), addPage() and
- subtractPage() available as slots.
-
- The dial's keyboard interface is fairly simple: The
- \key{left}/\key{up} and \key{right}/\key{down} arrow keys adjust
- the dial's \l {QAbstractSlider::value} {value} by the defined
- \l {QAbstractSlider::singleStep} {singleStep}, \key{Page Up} and
- \key{Page Down} by the defined \l {QAbstractSlider::pageStep}
- {pageStep}, and the \key Home and \key End keys set the value to
- the defined \l {QAbstractSlider::minimum} {minimum} and
- \l {QAbstractSlider::maximum} {maximum} values.
-
- If you are using the mouse wheel to adjust the dial, the increment
- value is determined by the lesser value of
- \l{QApplication::wheelScrollLines()} {wheelScrollLines} multipled
- by \l {QAbstractSlider::singleStep} {singleStep}, and
- \l {QAbstractSlider::pageStep} {pageStep}.
-
- \table
- \row \o \inlineimage plastique-dial.png Screenshot of a dial in the Plastique widget style
- \o \inlineimage windowsxp-dial.png Screenshot of a dial in the Windows XP widget style
- \o \inlineimage macintosh-dial.png Screenshot of a dial in the Macintosh widget style
- \row \o {3,1} Dials shown in various widget styles (from left to right):
- \l{Plastique Style Widget Gallery}{Plastique},
- \l{Windows XP Style Widget Gallery}{Windows XP},
- \l{Macintosh Style Widget Gallery}{Macintosh}.
- \endtable
-
- \sa QScrollBar, QSpinBox, QSlider, {fowler}{GUI Design Handbook: Slider}, {Sliders Example}
-*/
-
-/*!
- Constructs a dial.
-
- The \a parent argument is sent to the QAbstractSlider constructor.
-*/
-QDial::QDial(QWidget *parent)
- : QAbstractSlider(*new QDialPrivate, parent)
-{
- Q_D(QDial);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QDial::QDial(QWidget *parent, const char *name)
- : QAbstractSlider(*new QDialPrivate, parent)
-{
- Q_D(QDial);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QDial::QDial(int minValue, int maxValue, int pageStep, int value,
- QWidget *parent, const char *name)
- : QAbstractSlider(*new QDialPrivate, parent)
-{
- Q_D(QDial);
- setObjectName(QString::fromAscii(name));
- d->minimum = minValue;
- d->maximum = maxValue;
- d->pageStep = pageStep;
- d->position = d->value = value;
- d->init();
-}
-#endif
-/*!
- Destroys the dial.
-*/
-QDial::~QDial()
-{
-}
-
-/*! \reimp */
-void QDial::resizeEvent(QResizeEvent *e)
-{
- QWidget::resizeEvent(e);
-}
-
-/*!
- \reimp
-*/
-
-void QDial::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionSlider option;
- initStyleOption(&option);
- p.drawComplexControl(QStyle::CC_Dial, option);
-}
-
-/*!
- \reimp
-*/
-
-void QDial::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QDial);
- if (d->maximum == d->minimum ||
- (e->button() != Qt::LeftButton) ||
- (e->buttons() ^ e->button())) {
- e->ignore();
- return;
- }
- e->accept();
- setSliderPosition(d->valueFromPoint(e->pos()));
- // ### This isn't quite right,
- // we should be doing a hit test and only setting this if it's
- // the actual dial thingie (similar to what QSlider does), but we have no
- // subControls for QDial.
- setSliderDown(true);
-}
-
-
-/*!
- \reimp
-*/
-
-void QDial::mouseReleaseEvent(QMouseEvent * e)
-{
- Q_D(QDial);
- if (e->buttons() & (~e->button()) ||
- (e->button() != Qt::LeftButton)) {
- e->ignore();
- return;
- }
- e->accept();
- setValue(d->valueFromPoint(e->pos()));
- setSliderDown(false);
-}
-
-
-/*!
- \reimp
-*/
-
-void QDial::mouseMoveEvent(QMouseEvent * e)
-{
- Q_D(QDial);
- if (!(e->buttons() & Qt::LeftButton)) {
- e->ignore();
- return;
- }
- e->accept();
- d->doNotEmit = true;
- setSliderPosition(d->valueFromPoint(e->pos()));
- d->doNotEmit = false;
-}
-
-
-/*!
- \reimp
-*/
-
-void QDial::sliderChange(SliderChange change)
-{
- QAbstractSlider::sliderChange(change);
-}
-
-void QDial::setWrapping(bool enable)
-{
- Q_D(QDial);
- if (d->wrapping == enable)
- return;
- d->wrapping = enable;
- update();
-}
-
-
-/*!
- \property QDial::wrapping
- \brief whether wrapping is enabled
-
- If true, wrapping is enabled; otherwise some space is inserted at the bottom
- of the dial to separate the ends of the range of valid values.
-
- If enabled, the arrow can be oriented at any angle on the dial. If disabled,
- the arrow will be restricted to the upper part of the dial; if it is rotated
- into the space at the bottom of the dial, it will be clamped to the closest
- end of the valid range of values.
-
- By default this property is false.
-*/
-
-bool QDial::wrapping() const
-{
- Q_D(const QDial);
- return d->wrapping;
-}
-
-
-/*!
- \property QDial::notchSize
- \brief the current notch size
-
- The notch size is in range control units, not pixels, and if
- possible it is a multiple of singleStep() that results in an
- on-screen notch size near notchTarget().
-
- By default, this property has a value of 1.
-
- \sa notchTarget(), singleStep()
-*/
-
-int QDial::notchSize() const
-{
- Q_D(const QDial);
- // radius of the arc
- int r = qMin(width(), height())/2;
- // length of the whole arc
- int l = (int)(r * (d->wrapping ? 6 : 5) * Q_PI / 6);
- // length of the arc from minValue() to minValue()+pageStep()
- if (d->maximum > d->minimum + d->pageStep)
- l = (int)(0.5 + l * d->pageStep / (d->maximum - d->minimum));
- // length of a singleStep arc
- l = l * d->singleStep / (d->pageStep ? d->pageStep : 1);
- if (l < 1)
- l = 1;
- // how many times singleStep can be draw in d->target pixels
- l = (int)(0.5 + d->target / l);
- // we want notchSize() to be a non-zero multiple of lineStep()
- if (!l)
- l = 1;
- return d->singleStep * l;
-}
-
-void QDial::setNotchTarget(double target)
-{
- Q_D(QDial);
- d->target = target;
- update();
-}
-
-/*!
- \property QDial::notchTarget
- \brief the target number of pixels between notches
-
- The notch target is the number of pixels QDial attempts to put
- between each notch.
-
- The actual size may differ from the target size.
-
- The default notch target is 3.7 pixels.
-*/
-qreal QDial::notchTarget() const
-{
- Q_D(const QDial);
- return d->target;
-}
-
-
-void QDial::setNotchesVisible(bool visible)
-{
- Q_D(QDial);
- d->showNotches = visible;
- update();
-}
-
-/*!
- \property QDial::notchesVisible
- \brief whether the notches are shown
-
- If the property is true, a series of notches are drawn around the dial
- to indicate the range of values available; otherwise no notches are
- shown.
-
- By default, this property is disabled.
-*/
-bool QDial::notchesVisible() const
-{
- Q_D(const QDial);
- return d->showNotches;
-}
-
-/*!
- \reimp
-*/
-
-QSize QDial::minimumSizeHint() const
-{
- return QSize(50, 50);
-}
-
-/*!
- \reimp
-*/
-
-QSize QDial::sizeHint() const
-{
- return QSize(100, 100).expandedTo(QApplication::globalStrut());
-}
-
-/*!
- \reimp
-*/
-bool QDial::event(QEvent *e)
-{
- return QAbstractSlider::event(e);
-}
-
-/*!
- \fn void QDial::dialPressed();
-
- Use QAbstractSlider::sliderPressed() instead.
-*/
-
-/*!
- \fn void QDial::dialMoved(int value);
-
- Use QAbstractSlider::sliderMoved() instead.
-*/
-
-/*!
- \fn void QDial::dialReleased();
-
- Use QAbstractSlider::sliderReleased() instead.
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DIAL
diff --git a/src/gui/widgets/qdial.h b/src/gui/widgets/qdial.h
deleted file mode 100644
index 6786358969..0000000000
--- a/src/gui/widgets/qdial.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** 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 QDIAL_H
-#define QDIAL_H
-
-#include <QtGui/qabstractslider.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_DIAL
-
-class QDialPrivate;
-class QStyleOptionSlider;
-
-class Q_GUI_EXPORT QDial: public QAbstractSlider
-{
- Q_OBJECT
-
- Q_PROPERTY(bool wrapping READ wrapping WRITE setWrapping)
- Q_PROPERTY(int notchSize READ notchSize)
- Q_PROPERTY(qreal notchTarget READ notchTarget WRITE setNotchTarget)
- Q_PROPERTY(bool notchesVisible READ notchesVisible WRITE setNotchesVisible)
-public:
- explicit QDial(QWidget *parent = 0);
-
- ~QDial();
-
- bool wrapping() const;
-
- int notchSize() const;
-
- void setNotchTarget(double target);
- qreal notchTarget() const;
- bool notchesVisible() const;
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
-public Q_SLOTS:
- void setNotchesVisible(bool visible);
- void setWrapping(bool on);
-
-protected:
- bool event(QEvent *e);
- void resizeEvent(QResizeEvent *re);
- void paintEvent(QPaintEvent *pe);
-
- void mousePressEvent(QMouseEvent *me);
- void mouseReleaseEvent(QMouseEvent *me);
- void mouseMoveEvent(QMouseEvent *me);
-
- void sliderChange(SliderChange change);
- void initStyleOption(QStyleOptionSlider *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QDial(int minValue, int maxValue, int pageStep, int value,
- QWidget* parent = 0, const char* name = 0);
- QT3_SUPPORT_CONSTRUCTOR QDial(QWidget *parent, const char *name);
-
-Q_SIGNALS:
- QT_MOC_COMPAT void dialPressed();
- QT_MOC_COMPAT void dialMoved(int value);
- QT_MOC_COMPAT void dialReleased();
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QDial)
- Q_DISABLE_COPY(QDial)
-};
-
-#endif // QT_NO_DIAL
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDIAL_H
diff --git a/src/gui/widgets/qdialogbuttonbox.cpp b/src/gui/widgets/qdialogbuttonbox.cpp
deleted file mode 100644
index 6fe87b6ac8..0000000000
--- a/src/gui/widgets/qdialogbuttonbox.cpp
+++ /dev/null
@@ -1,1285 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qhash.h>
-#include <QtGui/qpushbutton.h>
-#include <QtGui/qstyle.h>
-#include <QtGui/qlayout.h>
-#include <QtGui/qdialog.h>
-#include <QtGui/qapplication.h>
-#include <QtGui/private/qwidget_p.h>
-#include <QtGui/qaction.h>
-
-#include "qdialogbuttonbox.h"
-
-#ifdef QT_SOFTKEYS_ENABLED
-#include <QtGui/qaction.h>
-#endif
-
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QDialogButtonBox
- \since 4.2
- \brief The QDialogButtonBox class is a widget that presents buttons in a
- layout that is appropriate to the current widget style.
-
- \ingroup dialog-classes
-
-
- Dialogs and message boxes typically present buttons in a layout that
- conforms to the interface guidelines for that platform. Invariably,
- different platforms have different layouts for their dialogs.
- QDialogButtonBox allows a developer to add buttons to it and will
- automatically use the appropriate layout for the user's desktop
- environment.
-
- Most buttons for a dialog follow certain roles. Such roles include:
-
- \list
- \o Accepting or rejecting the dialog.
- \o Asking for help.
- \o Performing actions on the dialog itself (such as resetting fields or
- applying changes).
- \endlist
-
- There can also be alternate ways of dismissing the dialog which may cause
- destructive results.
-
- Most dialogs have buttons that can almost be considered standard (e.g.
- \gui OK and \gui Cancel buttons). It is sometimes convenient to create these
- buttons in a standard way.
-
- There are a couple ways of using QDialogButtonBox. One ways is to create
- the buttons (or button texts) yourself and add them to the button box,
- specifying their role.
-
- \snippet examples/dialogs/extension/finddialog.cpp 1
-
- Alternatively, QDialogButtonBox provides several standard buttons (e.g. OK, Cancel, Save)
- that you can use. They exist as flags so you can OR them together in the constructor.
-
- \snippet examples/dialogs/tabdialog/tabdialog.cpp 2
-
- You can mix and match normal buttons and standard buttons.
-
- Currently the buttons are laid out in the following way if the button box is horizontal:
- \table
- \row \o \inlineimage buttonbox-gnomelayout-horizontal.png GnomeLayout Horizontal
- \o Button box laid out in horizontal GnomeLayout
- \row \o \inlineimage buttonbox-kdelayout-horizontal.png KdeLayout Horizontal
- \o Button box laid out in horizontal KdeLayout
- \row \o \inlineimage buttonbox-maclayout-horizontal.png MacLayout Horizontal
- \o Button box laid out in horizontal MacLayout
- \row \o \inlineimage buttonbox-winlayout-horizontal.png WinLayout Horizontal
- \o Button box laid out in horizontal WinLayout
- \endtable
-
- The buttons are laid out the following way if the button box is vertical:
-
- \table
- \row \o GnomeLayout
- \o KdeLayout
- \o MacLayout
- \o WinLayout
- \row \o \inlineimage buttonbox-gnomelayout-vertical.png GnomeLayout Vertical
- \o \inlineimage buttonbox-kdelayout-vertical.png KdeLayout Vertical
- \o \inlineimage buttonbox-maclayout-vertical.png MacLayout Vertical
- \o \inlineimage buttonbox-winlayout-vertical.png WinLayout Vertical
- \endtable
-
- Additionally, button boxes that contain only buttons with ActionRole or
- HelpRole can be considered modeless and have an alternate look on Mac OS X:
-
- \table
- \row \o modeless horizontal MacLayout
- \o \inlineimage buttonbox-mac-modeless-horizontal.png Screenshot of modeless horizontal MacLayout
- \endtable
-
- When a button is clicked in the button box, the clicked() signal is emitted
- for the actual button is that is pressed. For convenience, if the button
- has an AcceptRole, RejectRole, or HelpRole, the accepted(), rejected(), or
- helpRequested() signals are emitted respectively.
-
- If you want a specific button to be default you need to call
- QPushButton::setDefault() on it yourself. However, if there is no default
- button set and to preserve which button is the default button across
- platforms when using the QPushButton::autoDefault property, the first push
- button with the accept role is made the default button when the
- QDialogButtonBox is shown,
-
- \sa QMessageBox, QPushButton, QDialog
-*/
-
-enum {
- AcceptRole = QDialogButtonBox::AcceptRole,
- RejectRole = QDialogButtonBox::RejectRole,
- DestructiveRole = QDialogButtonBox::DestructiveRole,
- ActionRole = QDialogButtonBox::ActionRole,
- HelpRole = QDialogButtonBox::HelpRole,
- YesRole = QDialogButtonBox::YesRole,
- NoRole = QDialogButtonBox::NoRole,
- ApplyRole = QDialogButtonBox::ApplyRole,
- ResetRole = QDialogButtonBox::ResetRole,
-
- AlternateRole = 0x10000000,
- Stretch = 0x20000000,
- EOL = 0x40000000,
- Reverse = 0x80000000
-};
-
-static QDialogButtonBox::ButtonRole roleFor(QDialogButtonBox::StandardButton button)
-{
- switch (button) {
- case QDialogButtonBox::Ok:
- case QDialogButtonBox::Save:
- case QDialogButtonBox::Open:
- case QDialogButtonBox::SaveAll:
- case QDialogButtonBox::Retry:
- case QDialogButtonBox::Ignore:
- return QDialogButtonBox::AcceptRole;
-
- case QDialogButtonBox::Cancel:
- case QDialogButtonBox::Close:
- case QDialogButtonBox::Abort:
- return QDialogButtonBox::RejectRole;
-
- case QDialogButtonBox::Discard:
- return QDialogButtonBox::DestructiveRole;
-
- case QDialogButtonBox::Help:
- return QDialogButtonBox::HelpRole;
-
- case QDialogButtonBox::Apply:
- return QDialogButtonBox::ApplyRole;
-
- case QDialogButtonBox::Yes:
- case QDialogButtonBox::YesToAll:
- return QDialogButtonBox::YesRole;
-
- case QDialogButtonBox::No:
- case QDialogButtonBox::NoToAll:
- return QDialogButtonBox::NoRole;
-
- case QDialogButtonBox::RestoreDefaults:
- case QDialogButtonBox::Reset:
- return QDialogButtonBox::ResetRole;
-
- case QDialogButtonBox::NoButton: // NoButton means zero buttons, not "No" button
- ;
- }
-
- return QDialogButtonBox::InvalidRole;
-}
-
-static const int layouts[2][5][14] =
-{
- // Qt::Horizontal
- {
- // WinLayout
- { ResetRole, Stretch, YesRole, AcceptRole, AlternateRole, DestructiveRole, NoRole, ActionRole, RejectRole, ApplyRole,
- HelpRole, EOL, EOL, EOL },
-
- // MacLayout
- { HelpRole, ResetRole, ApplyRole, ActionRole, Stretch, DestructiveRole | Reverse,
- AlternateRole | Reverse, RejectRole | Reverse, AcceptRole | Reverse, NoRole | Reverse, YesRole | Reverse, EOL, EOL },
-
- // KdeLayout
- { HelpRole, ResetRole, Stretch, YesRole, NoRole, ActionRole, AcceptRole, AlternateRole,
- ApplyRole, DestructiveRole, RejectRole, EOL },
-
- // GnomeLayout
- { HelpRole, ResetRole, Stretch, ActionRole, ApplyRole | Reverse, DestructiveRole | Reverse,
- AlternateRole | Reverse, RejectRole | Reverse, AcceptRole | Reverse, NoRole | Reverse, YesRole | Reverse, EOL },
-
- // Mac modeless
- { ResetRole, ApplyRole, ActionRole, Stretch, HelpRole, EOL, EOL, EOL, EOL, EOL, EOL, EOL, EOL, EOL }
- },
-
- // Qt::Vertical
- {
- // WinLayout
- { ActionRole, YesRole, AcceptRole, AlternateRole, DestructiveRole, NoRole, RejectRole, ApplyRole, ResetRole,
- HelpRole, Stretch, EOL, EOL, EOL },
-
- // MacLayout
- { YesRole, NoRole, AcceptRole, RejectRole, AlternateRole, DestructiveRole, Stretch, ActionRole, ApplyRole,
- ResetRole, HelpRole, EOL, EOL },
-
- // KdeLayout
- { AcceptRole, AlternateRole, ApplyRole, ActionRole, YesRole, NoRole, Stretch, ResetRole,
- DestructiveRole, RejectRole, HelpRole, EOL },
-
- // GnomeLayout
- { YesRole, NoRole, AcceptRole, RejectRole, AlternateRole, DestructiveRole, ApplyRole, ActionRole, Stretch,
- ResetRole, HelpRole, EOL, EOL, EOL },
-
- // Mac modeless
- { ActionRole, ApplyRole, ResetRole, Stretch, HelpRole, EOL, EOL, EOL, EOL, EOL, EOL, EOL, EOL, EOL }
- }
-};
-
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
-class QDialogButtonEnabledProxy : public QObject
-{
-public:
- QDialogButtonEnabledProxy(QObject *parent, QWidget *src, QAction *trg) : QObject(parent), source(src), target(trg)
- {
- source->installEventFilter(this);
- target->setEnabled(source->isEnabled());
- }
- ~QDialogButtonEnabledProxy()
- {
- source->removeEventFilter(this);
- }
- bool eventFilter(QObject *object, QEvent *event)
- {
- if (object == source && event->type() == QEvent::EnabledChange) {
- target->setEnabled(source->isEnabled());
- }
- return false;
- };
-private:
- QWidget *source;
- QAction *target;
-};
-#endif
-
-class QDialogButtonBoxPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QDialogButtonBox)
-
-public:
- QDialogButtonBoxPrivate(Qt::Orientation orient);
-
- QList<QAbstractButton *> buttonLists[QDialogButtonBox::NRoles];
- QHash<QPushButton *, QDialogButtonBox::StandardButton> standardButtonHash;
-#ifdef QT_SOFTKEYS_ENABLED
- QHash<QAbstractButton *, QAction *> softKeyActions;
-#endif
-
- Qt::Orientation orientation;
- QDialogButtonBox::ButtonLayout layoutPolicy;
- QBoxLayout *buttonLayout;
- bool internalRemove;
- bool center;
-
- void createStandardButtons(QDialogButtonBox::StandardButtons buttons);
-
- void layoutButtons();
- void initLayout();
- void resetLayout();
- QPushButton *createButton(QDialogButtonBox::StandardButton button, bool doLayout = true);
- void addButton(QAbstractButton *button, QDialogButtonBox::ButtonRole role, bool doLayout = true);
- void _q_handleButtonDestroyed();
- void _q_handleButtonClicked();
- void addButtonsToLayout(const QList<QAbstractButton *> &buttonList, bool reverse);
- void retranslateStrings();
- const char *standardButtonText(QDialogButtonBox::StandardButton sbutton) const;
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
- QAction *createSoftKey(QAbstractButton *button, QDialogButtonBox::ButtonRole role);
-#endif
-};
-
-QDialogButtonBoxPrivate::QDialogButtonBoxPrivate(Qt::Orientation orient)
- : orientation(orient), buttonLayout(0), internalRemove(false), center(false)
-{
-}
-
-void QDialogButtonBoxPrivate::initLayout()
-{
- Q_Q(QDialogButtonBox);
- layoutPolicy = QDialogButtonBox::ButtonLayout(q->style()->styleHint(QStyle::SH_DialogButtonLayout, 0, q));
- bool createNewLayout = buttonLayout == 0
- || (orientation == Qt::Horizontal && qobject_cast<QVBoxLayout *>(buttonLayout) != 0)
- || (orientation == Qt::Vertical && qobject_cast<QHBoxLayout *>(buttonLayout) != 0);
- if (createNewLayout) {
- delete buttonLayout;
- if (orientation == Qt::Horizontal)
- buttonLayout = new QHBoxLayout(q);
- else
- buttonLayout = new QVBoxLayout(q);
- }
-
- int left, top, right, bottom;
- setLayoutItemMargins(QStyle::SE_PushButtonLayoutItem);
- getLayoutItemMargins(&left, &top, &right, &bottom);
- buttonLayout->setContentsMargins(-left, -top, -right, -bottom);
-
- if (!q->testAttribute(Qt::WA_WState_OwnSizePolicy)) {
- QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Fixed, QSizePolicy::ButtonBox);
- if (orientation == Qt::Vertical)
- sp.transpose();
- q->setSizePolicy(sp);
- q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- }
-
- // ### move to a real init() function
- q->setFocusPolicy(Qt::TabFocus);
-}
-
-void QDialogButtonBoxPrivate::resetLayout()
-{
- //delete buttonLayout;
- initLayout();
- layoutButtons();
-}
-
-void QDialogButtonBoxPrivate::addButtonsToLayout(const QList<QAbstractButton *> &buttonList,
- bool reverse)
-{
- int start = reverse ? buttonList.count() - 1 : 0;
- int end = reverse ? -1 : buttonList.count();
- int step = reverse ? -1 : 1;
-
- for (int i = start; i != end; i += step) {
- QAbstractButton *button = buttonList.at(i);
- buttonLayout->addWidget(button);
- button->show();
- }
-}
-
-void QDialogButtonBoxPrivate::layoutButtons()
-{
- Q_Q(QDialogButtonBox);
- const int MacGap = 36 - 8; // 8 is the default gap between a widget and a spacer item
-
- for (int i = buttonLayout->count() - 1; i >= 0; --i) {
- QLayoutItem *item = buttonLayout->takeAt(i);
- if (QWidget *widget = item->widget())
- widget->hide();
- delete item;
- }
-
- int tmpPolicy = layoutPolicy;
-
- static const int M = 5;
- static const int ModalRoles[M] = { AcceptRole, RejectRole, DestructiveRole, YesRole, NoRole };
- if (tmpPolicy == QDialogButtonBox::MacLayout) {
- bool hasModalButton = false;
- for (int i = 0; i < M; ++i) {
- if (!buttonLists[ModalRoles[i]].isEmpty()) {
- hasModalButton = true;
- break;
- }
- }
- if (!hasModalButton)
- tmpPolicy = 4; // Mac modeless
- }
-
- const int *currentLayout = layouts[orientation == Qt::Vertical][tmpPolicy];
-
- if (center)
- buttonLayout->addStretch();
-
- QList<QAbstractButton *> acceptRoleList = buttonLists[AcceptRole];
-
- while (*currentLayout != EOL) {
- int role = (*currentLayout & ~Reverse);
- bool reverse = (*currentLayout & Reverse);
-
- switch (role) {
- case Stretch:
- if (!center)
- buttonLayout->addStretch();
- break;
- case AcceptRole: {
- if (acceptRoleList.isEmpty())
- break;
- // Only the first one
- QAbstractButton *button = acceptRoleList.first();
- buttonLayout->addWidget(button);
- button->show();
- }
- break;
- case AlternateRole:
- {
- if (acceptRoleList.size() < 2)
- break;
- QList<QAbstractButton *> list = acceptRoleList;
- list.removeFirst();
- addButtonsToLayout(list, reverse);
- }
- break;
- case DestructiveRole:
- {
- const QList<QAbstractButton *> &list = buttonLists[role];
-
- /*
- Mac: Insert a gap on the left of the destructive
- buttons to ensure that they don't get too close to
- the help and action buttons (but only if there are
- some buttons to the left of the destructive buttons
- (and the stretch, whence buttonLayout->count() > 1
- and not 0)).
- */
- if (tmpPolicy == QDialogButtonBox::MacLayout
- && !list.isEmpty() && buttonLayout->count() > 1)
- buttonLayout->addSpacing(MacGap);
-
- addButtonsToLayout(list, reverse);
-
- /*
- Insert a gap between the destructive buttons and the
- accept and reject buttons.
- */
- if (tmpPolicy == QDialogButtonBox::MacLayout && !list.isEmpty())
- buttonLayout->addSpacing(MacGap);
- }
- break;
- case RejectRole:
- case ActionRole:
- case HelpRole:
- case YesRole:
- case NoRole:
- case ApplyRole:
- case ResetRole:
- addButtonsToLayout(buttonLists[role], reverse);
- }
- ++currentLayout;
- }
-
- QWidget *lastWidget = 0;
- q->setFocusProxy(0);
- for (int i = 0; i < buttonLayout->count(); ++i) {
- QLayoutItem *item = buttonLayout->itemAt(i);
- if (QWidget *widget = item->widget()) {
- if (lastWidget)
- QWidget::setTabOrder(lastWidget, widget);
- else
- q->setFocusProxy(widget);
- lastWidget = widget;
- }
- }
-
- if (center)
- buttonLayout->addStretch();
-}
-
-QPushButton *QDialogButtonBoxPrivate::createButton(QDialogButtonBox::StandardButton sbutton,
- bool doLayout)
-{
- Q_Q(QDialogButtonBox);
- const char *buttonText = 0;
- int icon = 0;
-
- switch (sbutton) {
- case QDialogButtonBox::Ok:
- icon = QStyle::SP_DialogOkButton;
- break;
- case QDialogButtonBox::Save:
- icon = QStyle::SP_DialogSaveButton;
- break;
- case QDialogButtonBox::Open:
- icon = QStyle::SP_DialogOpenButton;
- break;
- case QDialogButtonBox::Cancel:
- icon = QStyle::SP_DialogCancelButton;
- break;
- case QDialogButtonBox::Close:
- icon = QStyle::SP_DialogCloseButton;
- break;
- case QDialogButtonBox::Apply:
- icon = QStyle::SP_DialogApplyButton;
- break;
- case QDialogButtonBox::Reset:
- icon = QStyle::SP_DialogResetButton;
- break;
- case QDialogButtonBox::Help:
- icon = QStyle::SP_DialogHelpButton;
- break;
- case QDialogButtonBox::Discard:
- icon = QStyle::SP_DialogDiscardButton;
- break;
- case QDialogButtonBox::Yes:
- icon = QStyle::SP_DialogYesButton;
- break;
- case QDialogButtonBox::No:
- icon = QStyle::SP_DialogNoButton;
- break;
- case QDialogButtonBox::YesToAll:
- case QDialogButtonBox::NoToAll:
- case QDialogButtonBox::SaveAll:
- case QDialogButtonBox::Abort:
- case QDialogButtonBox::Retry:
- case QDialogButtonBox::Ignore:
- case QDialogButtonBox::RestoreDefaults:
- break;
- case QDialogButtonBox::NoButton:
- return 0;
- ;
- }
- buttonText = standardButtonText(sbutton);
-
- QPushButton *button = new QPushButton(QDialogButtonBox::tr(buttonText), q);
- QStyle *style = q->style();
- if (style->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons, 0, q) && icon != 0)
- button->setIcon(style->standardIcon(QStyle::StandardPixmap(icon), 0, q));
- if (style != QApplication::style()) // Propagate style
- button->setStyle(style);
- standardButtonHash.insert(button, sbutton);
- if (roleFor(sbutton) != QDialogButtonBox::InvalidRole) {
- addButton(button, roleFor(sbutton), doLayout);
- } else {
- qWarning("QDialogButtonBox::createButton: Invalid ButtonRole, button not added");
- }
-
-#ifdef Q_WS_MAC
- // Since mnemonics is off by default on Mac, we add a Cmd-D
- // shortcut here to e.g. make the "Don't Save" button work nativly:
- if (sbutton == QDialogButtonBox::Discard)
- button->setShortcut(QKeySequence(QLatin1String("Ctrl+D")));
-#endif
-
- return button;
-}
-
-void QDialogButtonBoxPrivate::addButton(QAbstractButton *button, QDialogButtonBox::ButtonRole role,
- bool doLayout)
-{
- Q_Q(QDialogButtonBox);
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_handleButtonClicked()));
- QObject::connect(button, SIGNAL(destroyed()), q, SLOT(_q_handleButtonDestroyed()));
- buttonLists[role].append(button);
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
- QAction *action = createSoftKey(button, role);
- softKeyActions.insert(button, action);
- new QDialogButtonEnabledProxy(action, button, action);
-#endif
- if (doLayout)
- layoutButtons();
-}
-
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
-QAction* QDialogButtonBoxPrivate::createSoftKey(QAbstractButton *button, QDialogButtonBox::ButtonRole role)
-{
- Q_Q(QDialogButtonBox);
- QAction::SoftKeyRole softkeyRole;
-
- QAction *action = new QAction(button->text(), button);
-
- switch (role) {
- case ApplyRole:
- case AcceptRole:
- case YesRole:
- case ActionRole:
- case HelpRole:
- softkeyRole = QAction::PositiveSoftKey;
- break;
- case RejectRole:
- case DestructiveRole:
- case NoRole:
- case ResetRole:
- softkeyRole = QAction::NegativeSoftKey;
- break;
- default:
- break;
- }
- QObject::connect(action, SIGNAL(triggered()), button, SIGNAL(clicked()));
- action->setSoftKeyRole(softkeyRole);
-
-
- QWidget *dialog = 0;
- QWidget *p = q;
- while (p && !p->isWindow()) {
- p = p->parentWidget();
- if ((dialog = qobject_cast<QDialog *>(p)))
- break;
- }
-
- if (dialog) {
- dialog->addAction(action);
- } else {
- q->addAction(action);
- }
-
- return action;
-}
-#endif
-
-void QDialogButtonBoxPrivate::createStandardButtons(QDialogButtonBox::StandardButtons buttons)
-{
- uint i = QDialogButtonBox::FirstButton;
- while (i <= QDialogButtonBox::LastButton) {
- if (i & buttons) {
- createButton(QDialogButtonBox::StandardButton(i), false);
- }
- i = i << 1;
- }
- layoutButtons();
-}
-
-const char *QDialogButtonBoxPrivate::standardButtonText(QDialogButtonBox::StandardButton sbutton) const
-{
- const char *buttonText = 0;
- bool gnomeLayout = (layoutPolicy == QDialogButtonBox::GnomeLayout);
- switch (sbutton) {
- case QDialogButtonBox::Ok:
- buttonText = gnomeLayout ? QT_TRANSLATE_NOOP("QDialogButtonBox", "&OK") : QT_TRANSLATE_NOOP("QDialogButtonBox", "OK");
- break;
- case QDialogButtonBox::Save:
- buttonText = gnomeLayout ? QT_TRANSLATE_NOOP("QDialogButtonBox", "&Save") : QT_TRANSLATE_NOOP("QDialogButtonBox", "Save");
- break;
- case QDialogButtonBox::Open:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Open");
- break;
- case QDialogButtonBox::Cancel:
- buttonText = gnomeLayout ? QT_TRANSLATE_NOOP("QDialogButtonBox", "&Cancel") : QT_TRANSLATE_NOOP("QDialogButtonBox", "Cancel");
- break;
- case QDialogButtonBox::Close:
- buttonText = gnomeLayout ? QT_TRANSLATE_NOOP("QDialogButtonBox", "&Close") : QT_TRANSLATE_NOOP("QDialogButtonBox", "Close");
- break;
- case QDialogButtonBox::Apply:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Apply");
- break;
- case QDialogButtonBox::Reset:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Reset");
- break;
- case QDialogButtonBox::Help:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Help");
- break;
- case QDialogButtonBox::Discard:
- if (layoutPolicy == QDialogButtonBox::MacLayout)
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Don't Save");
- else if (layoutPolicy == QDialogButtonBox::GnomeLayout)
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Close without Saving");
- else
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Discard");
- break;
- case QDialogButtonBox::Yes:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "&Yes");
- break;
- case QDialogButtonBox::YesToAll:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Yes to &All");
- break;
- case QDialogButtonBox::No:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "&No");
- break;
- case QDialogButtonBox::NoToAll:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "N&o to All");
- break;
- case QDialogButtonBox::SaveAll:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Save All");
- break;
- case QDialogButtonBox::Abort:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Abort");
- break;
- case QDialogButtonBox::Retry:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Retry");
- break;
- case QDialogButtonBox::Ignore:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Ignore");
- break;
- case QDialogButtonBox::RestoreDefaults:
- buttonText = QT_TRANSLATE_NOOP("QDialogButtonBox", "Restore Defaults");
- break;
- case QDialogButtonBox::NoButton:
- ;
- } // switch
- return buttonText;
-}
-
-void QDialogButtonBoxPrivate::retranslateStrings()
-{
- const char *buttonText = 0;
- QHash<QPushButton *, QDialogButtonBox::StandardButton>::iterator it = standardButtonHash.begin();
- while (it != standardButtonHash.end()) {
- buttonText = standardButtonText(it.value());
- if (buttonText) {
- QPushButton *button = it.key();
- button->setText(QDialogButtonBox::tr(buttonText));
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
- QAction *action = softKeyActions.value(button, 0);
- if (action)
- action->setText(button->text());
-#endif
- }
- ++it;
- }
-}
-
-/*!
- Constructs an empty, horizontal button box with the given \a parent.
-
- \sa orientation, addButton()
-*/
-QDialogButtonBox::QDialogButtonBox(QWidget *parent)
- : QWidget(*new QDialogButtonBoxPrivate(Qt::Horizontal), parent, 0)
-{
- d_func()->initLayout();
-}
-
-/*!
- Constructs an empty button box with the given \a orientation and \a parent.
-
- \sa orientation, addButton()
-*/
-QDialogButtonBox::QDialogButtonBox(Qt::Orientation orientation, QWidget *parent)
- : QWidget(*new QDialogButtonBoxPrivate(orientation), parent, 0)
-{
- d_func()->initLayout();
-}
-
-/*!
- Constructs a button box with the given \a orientation and \a parent, containing
- the standard buttons specified by \a buttons.
-
- \sa orientation, addButton()
-*/
-QDialogButtonBox::QDialogButtonBox(StandardButtons buttons, Qt::Orientation orientation,
- QWidget *parent)
- : QWidget(*new QDialogButtonBoxPrivate(orientation), parent, 0)
-{
- d_func()->initLayout();
- d_func()->createStandardButtons(buttons);
-}
-
-/*!
- Destroys the button box.
-*/
-QDialogButtonBox::~QDialogButtonBox()
-{
-}
-
-/*!
- \enum QDialogButtonBox::ButtonRole
- \enum QMessageBox::ButtonRole
-
- This enum describes the roles that can be used to describe buttons in
- the button box. Combinations of these roles are as flags used to
- describe different aspects of their behavior.
-
- \value InvalidRole The button is invalid.
- \value AcceptRole Clicking the button causes the dialog to be accepted
- (e.g. OK).
- \value RejectRole Clicking the button causes the dialog to be rejected
- (e.g. Cancel).
- \value DestructiveRole Clicking the button causes a destructive change
- (e.g. for Discarding Changes) and closes the dialog.
- \value ActionRole Clicking the button causes changes to the elements within
- the dialog.
- \value HelpRole The button can be clicked to request help.
- \value YesRole The button is a "Yes"-like button.
- \value NoRole The button is a "No"-like button.
- \value ApplyRole The button applies current changes.
- \value ResetRole The button resets the dialog's fields to default values.
-
- \omitvalue NRoles
-
- \sa StandardButton
-*/
-
-/*!
- \enum QDialogButtonBox::StandardButton
-
- These enums describe flags for standard buttons. Each button has a
- defined \l ButtonRole.
-
- \value Ok An "OK" button defined with the \l AcceptRole.
- \value Open A "Open" button defined with the \l AcceptRole.
- \value Save A "Save" button defined with the \l AcceptRole.
- \value Cancel A "Cancel" button defined with the \l RejectRole.
- \value Close A "Close" button defined with the \l RejectRole.
- \value Discard A "Discard" or "Don't Save" button, depending on the platform,
- defined with the \l DestructiveRole.
- \value Apply An "Apply" button defined with the \l ApplyRole.
- \value Reset A "Reset" button defined with the \l ResetRole.
- \value RestoreDefaults A "Restore Defaults" button defined with the \l ResetRole.
- \value Help A "Help" button defined with the \l HelpRole.
- \value SaveAll A "Save All" button defined with the \l AcceptRole.
- \value Yes A "Yes" button defined with the \l YesRole.
- \value YesToAll A "Yes to All" button defined with the \l YesRole.
- \value No A "No" button defined with the \l NoRole.
- \value NoToAll A "No to All" button defined with the \l NoRole.
- \value Abort An "Abort" button defined with the \l RejectRole.
- \value Retry A "Retry" button defined with the \l AcceptRole.
- \value Ignore An "Ignore" button defined with the \l AcceptRole.
-
- \value NoButton An invalid button.
-
- \omitvalue FirstButton
- \omitvalue LastButton
-
- \sa ButtonRole, standardButtons
-*/
-
-/*!
- \enum QDialogButtonBox::ButtonLayout
-
- This enum describes the layout policy to be used when arranging the buttons
- contained in the button box.
-
- \value WinLayout Use a policy appropriate for applications on Windows.
- \value MacLayout Use a policy appropriate for applications on Mac OS X.
- \value KdeLayout Use a policy appropriate for applications on KDE.
- \value GnomeLayout Use a policy appropriate for applications on GNOME.
-
- The button layout is specified by the \l{style()}{current style}. However,
- on the X11 platform, it may be influenced by the desktop environment.
-*/
-
-/*!
- \fn void QDialogButtonBox::clicked(QAbstractButton *button)
-
- This signal is emitted when a button inside the button box is clicked. The
- specific button that was pressed is specified by \a button.
-
- \sa accepted(), rejected(), helpRequested()
-*/
-
-/*!
- \fn void QDialogButtonBox::accepted()
-
- This signal is emitted when a button inside the button box is clicked, as long
- as it was defined with the \l AcceptRole or \l YesRole.
-
- \sa rejected(), clicked() helpRequested()
-*/
-
-/*!
- \fn void QDialogButtonBox::rejected()
-
- This signal is emitted when a button inside the button box is clicked, as long
- as it was defined with the \l RejectRole or \l NoRole.
-
- \sa accepted() helpRequested() clicked()
-*/
-
-/*!
- \fn void QDialogButtonBox::helpRequested()
-
- This signal is emitted when a button inside the button box is clicked, as long
- as it was defined with the \l HelpRole.
-
- \sa accepted() rejected() clicked()
-*/
-
-/*!
- \property QDialogButtonBox::orientation
- \brief the orientation of the button box
-
- By default, the orientation is horizontal (i.e. the buttons are laid out
- side by side). The possible orientations are Qt::Horizontal and
- Qt::Vertical.
-*/
-Qt::Orientation QDialogButtonBox::orientation() const
-{
- return d_func()->orientation;
-}
-
-void QDialogButtonBox::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QDialogButtonBox);
- if (orientation == d->orientation)
- return;
-
- d->orientation = orientation;
- d->resetLayout();
-}
-
-/*!
- Clears the button box, deleting all buttons within it.
-
- \sa removeButton(), addButton()
-*/
-void QDialogButtonBox::clear()
-{
- Q_D(QDialogButtonBox);
-#ifdef QT_SOFTKEYS_ENABLED
- // Delete softkey actions as they have the buttons as parents
- qDeleteAll(d->softKeyActions.values());
- d->softKeyActions.clear();
-#endif
- // Remove the created standard buttons, they should be in the other lists, which will
- // do the deletion
- d->standardButtonHash.clear();
- for (int i = 0; i < NRoles; ++i) {
- QList<QAbstractButton *> &list = d->buttonLists[i];
- while (list.count()) {
- QAbstractButton *button = list.takeAt(0);
- QObject::disconnect(button, SIGNAL(destroyed()), this, SLOT(_q_handleButtonDestroyed()));
- delete button;
- }
- }
-}
-
-/*!
- Returns a list of all the buttons that have been added to the button box.
-
- \sa buttonRole(), addButton(), removeButton()
-*/
-QList<QAbstractButton *> QDialogButtonBox::buttons() const
-{
- Q_D(const QDialogButtonBox);
- QList<QAbstractButton *> finalList;
- for (int i = 0; i < NRoles; ++i) {
- const QList<QAbstractButton *> &list = d->buttonLists[i];
- for (int j = 0; j < list.count(); ++j)
- finalList.append(list.at(j));
- }
- return finalList;
-}
-
-/*!
- Returns the button role for the specified \a button. This function returns
- \l InvalidRole if \a button is 0 or has not been added to the button box.
-
- \sa buttons(), addButton()
-*/
-QDialogButtonBox::ButtonRole QDialogButtonBox::buttonRole(QAbstractButton *button) const
-{
- Q_D(const QDialogButtonBox);
- for (int i = 0; i < NRoles; ++i) {
- const QList<QAbstractButton *> &list = d->buttonLists[i];
- for (int j = 0; j < list.count(); ++j) {
- if (list.at(j) == button)
- return ButtonRole(i);
- }
- }
- return InvalidRole;
-}
-
-/*!
- Removes \a button from the button box without deleting it and sets its parent to zero.
-
- \sa clear(), buttons(), addButton()
-*/
-void QDialogButtonBox::removeButton(QAbstractButton *button)
-{
- Q_D(QDialogButtonBox);
-
- if (!button)
- return;
-
- // Remove it from the standard button hash first and then from the roles
- if (QPushButton *pushButton = qobject_cast<QPushButton *>(button))
- d->standardButtonHash.remove(pushButton);
- for (int i = 0; i < NRoles; ++i) {
- QList<QAbstractButton *> &list = d->buttonLists[i];
- for (int j = 0; j < list.count(); ++j) {
- if (list.at(j) == button) {
- list.takeAt(j);
- if (!d->internalRemove) {
- disconnect(button, SIGNAL(clicked()), this, SLOT(_q_handleButtonClicked()));
- disconnect(button, SIGNAL(destroyed()), this, SLOT(_q_handleButtonDestroyed()));
- }
- break;
- }
- }
- }
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
- QAction *action = d->softKeyActions.value(button, 0);
- if (action) {
- d->softKeyActions.remove(button);
- delete action;
- }
-#endif
- if (!d->internalRemove)
- button->setParent(0);
-}
-
-/*!
- Adds the given \a button to the button box with the specified \a role.
- If the role is invalid, the button is not added.
-
- If the button has already been added, it is removed and added again with the
- new role.
-
- \note The button box takes ownership of the button.
-
- \sa removeButton(), clear()
-*/
-void QDialogButtonBox::addButton(QAbstractButton *button, ButtonRole role)
-{
- Q_D(QDialogButtonBox);
- if (role <= InvalidRole || role >= NRoles) {
- qWarning("QDialogButtonBox::addButton: Invalid ButtonRole, button not added");
- return;
- }
- removeButton(button);
- button->setParent(this);
- d->addButton(button, role);
-}
-
-/*!
- Creates a push button with the given \a text, adds it to the button box for the
- specified \a role, and returns the corresponding push button. If \a role is
- invalid, no button is created, and zero is returned.
-
- \sa removeButton(), clear()
-*/
-QPushButton *QDialogButtonBox::addButton(const QString &text, ButtonRole role)
-{
- Q_D(QDialogButtonBox);
- if (role <= InvalidRole || role >= NRoles) {
- qWarning("QDialogButtonBox::addButton: Invalid ButtonRole, button not added");
- return 0;
- }
- QPushButton *button = new QPushButton(text, this);
- d->addButton(button, role);
- return button;
-}
-
-/*!
- Adds a standard \a button to the button box if it is valid to do so, and returns
- a push button. If \a button is invalid, it is not added to the button box, and
- zero is returned.
-
- \sa removeButton(), clear()
-*/
-QPushButton *QDialogButtonBox::addButton(StandardButton button)
-{
- Q_D(QDialogButtonBox);
- return d->createButton(button);
-}
-
-/*!
- \property QDialogButtonBox::standardButtons
- \brief collection of standard buttons in the button box
-
- This property controls which standard buttons are used by the button box.
-
- \sa addButton()
-*/
-void QDialogButtonBox::setStandardButtons(StandardButtons buttons)
-{
- Q_D(QDialogButtonBox);
-#ifdef QT_SOFTKEYS_ENABLED
- // Delete softkey actions since they have the buttons as parents
- qDeleteAll(d->softKeyActions.values());
- d->softKeyActions.clear();
-#endif
- // Clear out all the old standard buttons, then recreate them.
- qDeleteAll(d->standardButtonHash.keys());
- d->standardButtonHash.clear();
-
- d->createStandardButtons(buttons);
-}
-
-QDialogButtonBox::StandardButtons QDialogButtonBox::standardButtons() const
-{
- Q_D(const QDialogButtonBox);
- StandardButtons standardButtons = NoButton;
- QHash<QPushButton *, StandardButton>::const_iterator it = d->standardButtonHash.constBegin();
- while (it != d->standardButtonHash.constEnd()) {
- standardButtons |= it.value();
- ++it;
- }
- return standardButtons;
-}
-
-/*!
- Returns the QPushButton corresponding to the standard button \a which,
- or 0 if the standard button doesn't exist in this button box.
-
- \sa standardButton(), standardButtons(), buttons()
-*/
-QPushButton *QDialogButtonBox::button(StandardButton which) const
-{
- Q_D(const QDialogButtonBox);
- return d->standardButtonHash.key(which);
-}
-
-/*!
- Returns the standard button enum value corresponding to the given \a button,
- or NoButton if the given \a button isn't a standard button.
-
- \sa button(), buttons(), standardButtons()
-*/
-QDialogButtonBox::StandardButton QDialogButtonBox::standardButton(QAbstractButton *button) const
-{
- Q_D(const QDialogButtonBox);
- return d->standardButtonHash.value(static_cast<QPushButton *>(button));
-}
-
-void QDialogButtonBoxPrivate::_q_handleButtonClicked()
-{
- Q_Q(QDialogButtonBox);
- if (QAbstractButton *button = qobject_cast<QAbstractButton *>(q->sender())) {
- emit q->clicked(button);
-
- switch (q->buttonRole(button)) {
- case AcceptRole:
- case YesRole:
- emit q->accepted();
- break;
- case RejectRole:
- case NoRole:
- emit q->rejected();
- break;
- case HelpRole:
- emit q->helpRequested();
- break;
- default:
- break;
- }
- }
-}
-
-void QDialogButtonBoxPrivate::_q_handleButtonDestroyed()
-{
- Q_Q(QDialogButtonBox);
- if (QObject *object = q->sender()) {
- QBoolBlocker skippy(internalRemove);
- q->removeButton(static_cast<QAbstractButton *>(object));
- }
-}
-
-/*!
- \property QDialogButtonBox::centerButtons
- \brief whether the buttons in the button box are centered
-
- By default, this property is false. This behavior is appopriate
- for most types of dialogs. A notable exception is message boxes
- on most platforms (e.g. Windows), where the button box is
- centered horizontally.
-
- \sa QMessageBox
-*/
-void QDialogButtonBox::setCenterButtons(bool center)
-{
- Q_D(QDialogButtonBox);
- if (d->center != center) {
- d->center = center;
- d->resetLayout();
- }
-}
-
-bool QDialogButtonBox::centerButtons() const
-{
- Q_D(const QDialogButtonBox);
- return d->center;
-}
-
-/*!
- \reimp
-*/
-void QDialogButtonBox::changeEvent(QEvent *event)
-{
- typedef QHash<QPushButton *, QDialogButtonBox::StandardButton> StandardButtonHash;
-
- Q_D(QDialogButtonBox);
- switch (event->type()) {
- case QEvent::StyleChange: // Propagate style
- if (!d->standardButtonHash.empty()) {
- QStyle *newStyle = style();
- const StandardButtonHash::iterator end = d->standardButtonHash.end();
- for (StandardButtonHash::iterator it = d->standardButtonHash.begin(); it != end; ++it)
- it.key()->setStyle(newStyle);
- }
- // fallthrough intended
-#ifdef Q_WS_MAC
- case QEvent::MacSizeChange:
-#endif
- d->resetLayout();
- QWidget::changeEvent(event);
- break;
- default:
- QWidget::changeEvent(event);
- break;
- }
-}
-
-/*!
- \reimp
-*/
-bool QDialogButtonBox::event(QEvent *event)
-{
- Q_D(QDialogButtonBox);
- if (event->type() == QEvent::Show) {
- QList<QAbstractButton *> acceptRoleList = d->buttonLists[AcceptRole];
- QPushButton *firstAcceptButton = acceptRoleList.isEmpty() ? 0 : qobject_cast<QPushButton *>(acceptRoleList.at(0));
- bool hasDefault = false;
- QWidget *dialog = 0;
- QWidget *p = this;
- while (p && !p->isWindow()) {
- p = p->parentWidget();
- if ((dialog = qobject_cast<QDialog *>(p)))
- break;
- }
-
- foreach (QPushButton *pb, (dialog ? dialog : this)->findChildren<QPushButton *>()) {
- if (pb->isDefault() && pb != firstAcceptButton) {
- hasDefault = true;
- break;
- }
- }
- if (!hasDefault && firstAcceptButton)
- firstAcceptButton->setDefault(true);
-#ifdef QT_SOFTKEYS_ENABLED
- if (dialog)
- setFixedSize(0,0);
-#endif
- }else if (event->type() == QEvent::LanguageChange) {
- d->retranslateStrings();
- }
-#if defined(QT_SOFTKEYS_ENABLED) && !defined(QT_NO_ACTION)
- else if (event->type() == QEvent::ParentChange) {
- QWidget *dialog = 0;
- QWidget *p = this;
- while (p && !p->isWindow()) {
- p = p->parentWidget();
- if ((dialog = qobject_cast<QDialog *>(p)))
- break;
- }
-
- // If the parent changes, then move the softkeys
- for (QHash<QAbstractButton *, QAction *>::const_iterator it = d->softKeyActions.constBegin();
- it != d->softKeyActions.constEnd(); ++it) {
- QAction *current = it.value();
- QList<QWidget *> widgets = current->associatedWidgets();
- foreach (QWidget *w, widgets)
- w->removeAction(current);
- if (dialog)
- dialog->addAction(current);
- else
- addAction(current);
- }
- }
-#endif
-
- return QWidget::event(event);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qdialogbuttonbox.cpp"
diff --git a/src/gui/widgets/qdialogbuttonbox.h b/src/gui/widgets/qdialogbuttonbox.h
deleted file mode 100644
index 4e390134c4..0000000000
--- a/src/gui/widgets/qdialogbuttonbox.h
+++ /dev/null
@@ -1,168 +0,0 @@
-/****************************************************************************
-**
-** 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 QDIALOGBUTTONBOX_H
-#define QDIALOGBUTTONBOX_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QAbstractButton;
-class QPushButton;
-class QDialogButtonBoxPrivate;
-
-class Q_GUI_EXPORT QDialogButtonBox : public QWidget
-{
- Q_OBJECT
- Q_FLAGS(StandardButtons)
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
- Q_PROPERTY(StandardButtons standardButtons READ standardButtons WRITE setStandardButtons)
- Q_PROPERTY(bool centerButtons READ centerButtons WRITE setCenterButtons)
-
-public:
- enum ButtonRole {
- // keep this in sync with QMessageBox::ButtonRole
- InvalidRole = -1,
- AcceptRole,
- RejectRole,
- DestructiveRole,
- ActionRole,
- HelpRole,
- YesRole,
- NoRole,
- ResetRole,
- ApplyRole,
-
- NRoles
- };
-
- enum StandardButton {
- // keep this in sync with QMessageBox::StandardButton
- NoButton = 0x00000000,
- Ok = 0x00000400,
- Save = 0x00000800,
- SaveAll = 0x00001000,
- Open = 0x00002000,
- Yes = 0x00004000,
- YesToAll = 0x00008000,
- No = 0x00010000,
- NoToAll = 0x00020000,
- Abort = 0x00040000,
- Retry = 0x00080000,
- Ignore = 0x00100000,
- Close = 0x00200000,
- Cancel = 0x00400000,
- Discard = 0x00800000,
- Help = 0x01000000,
- Apply = 0x02000000,
- Reset = 0x04000000,
- RestoreDefaults = 0x08000000,
-
-#ifndef Q_MOC_RUN
- FirstButton = Ok,
- LastButton = RestoreDefaults
-#endif
- };
-
- Q_DECLARE_FLAGS(StandardButtons, StandardButton)
-
- enum ButtonLayout {
- WinLayout,
- MacLayout,
- KdeLayout,
- GnomeLayout
- };
-
- QDialogButtonBox(QWidget *parent = 0);
- QDialogButtonBox(Qt::Orientation orientation, QWidget *parent = 0);
- QDialogButtonBox(StandardButtons buttons, Qt::Orientation orientation = Qt::Horizontal,
- QWidget *parent = 0);
- ~QDialogButtonBox();
-
- void setOrientation(Qt::Orientation orientation);
- Qt::Orientation orientation() const;
-
- void addButton(QAbstractButton *button, ButtonRole role);
- QPushButton *addButton(const QString &text, ButtonRole role);
- QPushButton *addButton(StandardButton button);
- void removeButton(QAbstractButton *button);
- void clear();
-
- QList<QAbstractButton *> buttons() const;
- ButtonRole buttonRole(QAbstractButton *button) const;
-
- void setStandardButtons(StandardButtons buttons);
- StandardButtons standardButtons() const;
- StandardButton standardButton(QAbstractButton *button) const;
- QPushButton *button(StandardButton which) const;
-
- void setCenterButtons(bool center);
- bool centerButtons() const;
-
-Q_SIGNALS:
- void clicked(QAbstractButton *button);
- void accepted();
- void helpRequested();
- void rejected();
-
-protected:
- void changeEvent(QEvent *event);
- bool event(QEvent *event);
-
-private:
- Q_DISABLE_COPY(QDialogButtonBox)
- Q_DECLARE_PRIVATE(QDialogButtonBox)
- Q_PRIVATE_SLOT(d_func(), void _q_handleButtonClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_handleButtonDestroyed())
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QDialogButtonBox::StandardButtons)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDIALOGBUTTONBOX_H
diff --git a/src/gui/widgets/qdockarealayout.cpp b/src/gui/widgets/qdockarealayout.cpp
deleted file mode 100644
index 223421dfb2..0000000000
--- a/src/gui/widgets/qdockarealayout.cpp
+++ /dev/null
@@ -1,3334 +0,0 @@
-/****************************************************************************
-**
-** 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 "QtGui/qapplication.h"
-#include "QtGui/qwidget.h"
-#include "QtGui/qtabbar.h"
-#include "QtGui/qstyle.h"
-#include "QtGui/qdesktopwidget.h"
-#include "QtCore/qvariant.h"
-#include "qdockarealayout_p.h"
-#include "qdockwidget.h"
-#include "qmainwindow.h"
-#include "qwidgetanimator_p.h"
-#include "qmainwindowlayout_p.h"
-#include "qdockwidget_p.h"
-#include <private/qlayoutengine_p.h>
-
-#include <qpainter.h>
-#include <qstyleoption.h>
-
-#ifndef QT_NO_DOCKWIDGET
-
-QT_BEGIN_NAMESPACE
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-enum { StateFlagVisible = 1, StateFlagFloating = 2 };
-
-/******************************************************************************
-** QPlaceHolderItem
-*/
-
-QPlaceHolderItem::QPlaceHolderItem(QWidget *w)
-{
- objectName = w->objectName();
- hidden = w->isHidden();
- window = w->isWindow();
- if (window)
- topLevelRect = w->geometry();
-}
-
-/******************************************************************************
-** QDockAreaLayoutItem
-*/
-
-QDockAreaLayoutItem::QDockAreaLayoutItem(QLayoutItem *_widgetItem)
- : widgetItem(_widgetItem), subinfo(0), placeHolderItem(0), pos(0), size(-1), flags(NoFlags)
-{
-}
-
-QDockAreaLayoutItem::QDockAreaLayoutItem(QDockAreaLayoutInfo *_subinfo)
- : widgetItem(0), subinfo(_subinfo), placeHolderItem(0), pos(0), size(-1), flags(NoFlags)
-{
-}
-
-QDockAreaLayoutItem::QDockAreaLayoutItem(QPlaceHolderItem *_placeHolderItem)
- : widgetItem(0), subinfo(0), placeHolderItem(_placeHolderItem), pos(0), size(-1), flags(NoFlags)
-{
-}
-
-QDockAreaLayoutItem::QDockAreaLayoutItem(const QDockAreaLayoutItem &other)
- : widgetItem(other.widgetItem), subinfo(0), placeHolderItem(0), pos(other.pos),
- size(other.size), flags(other.flags)
-{
- if (other.subinfo != 0)
- subinfo = new QDockAreaLayoutInfo(*other.subinfo);
- else if (other.placeHolderItem != 0)
- placeHolderItem = new QPlaceHolderItem(*other.placeHolderItem);
-}
-
-QDockAreaLayoutItem::~QDockAreaLayoutItem()
-{
- delete subinfo;
- delete placeHolderItem;
-}
-
-bool QDockAreaLayoutItem::skip() const
-{
- if (placeHolderItem != 0)
- return true;
-
- if (flags & GapItem)
- return false;
-
- if (widgetItem != 0)
- return widgetItem->isEmpty();
-
- if (subinfo != 0) {
- for (int i = 0; i < subinfo->item_list.count(); ++i) {
- if (!subinfo->item_list.at(i).skip())
- return false;
- }
- }
-
- return true;
-}
-
-QSize QDockAreaLayoutItem::minimumSize() const
-{
- if (widgetItem != 0) {
- int left, top, right, bottom;
- widgetItem->widget()->getContentsMargins(&left, &top, &right, &bottom);
- return widgetItem->minimumSize() + QSize(left+right, top+bottom);
- }
- if (subinfo != 0)
- return subinfo->minimumSize();
- return QSize(0, 0);
-}
-
-QSize QDockAreaLayoutItem::maximumSize() const
-{
- if (widgetItem != 0) {
- int left, top, right, bottom;
- widgetItem->widget()->getContentsMargins(&left, &top, &right, &bottom);
- return widgetItem->maximumSize()+ QSize(left+right, top+bottom);
- }
- if (subinfo != 0)
- return subinfo->maximumSize();
- return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
-}
-
-bool QDockAreaLayoutItem::hasFixedSize(Qt::Orientation o) const
-{
- return perp(o, minimumSize()) == perp(o, maximumSize());
-}
-
-bool QDockAreaLayoutItem::expansive(Qt::Orientation o) const
-{
- if ((flags & GapItem) || placeHolderItem != 0)
- return false;
- if (widgetItem != 0)
- return ((widgetItem->expandingDirections() & o) == o);
- if (subinfo != 0)
- return subinfo->expansive(o);
- return false;
-}
-
-QSize QDockAreaLayoutItem::sizeHint() const
-{
- if (placeHolderItem != 0)
- return QSize(0, 0);
- if (widgetItem != 0) {
- int left, top, right, bottom;
- widgetItem->widget()->getContentsMargins(&left, &top, &right, &bottom);
- return widgetItem->sizeHint() + QSize(left+right, top+bottom);
- }
- if (subinfo != 0)
- return subinfo->sizeHint();
- return QSize(-1, -1);
-}
-
-QDockAreaLayoutItem
- &QDockAreaLayoutItem::operator = (const QDockAreaLayoutItem &other)
-{
- widgetItem = other.widgetItem;
- if (other.subinfo == 0)
- subinfo = 0;
- else
- subinfo = new QDockAreaLayoutInfo(*other.subinfo);
-
- delete placeHolderItem;
- if (other.placeHolderItem == 0)
- placeHolderItem = 0;
- else
- placeHolderItem = new QPlaceHolderItem(*other.placeHolderItem);
-
- pos = other.pos;
- size = other.size;
- flags = other.flags;
-
- return *this;
-}
-
-/******************************************************************************
-** QDockAreaLayoutInfo
-*/
-
-#ifndef QT_NO_TABBAR
-static quintptr tabId(const QDockAreaLayoutItem &item)
-{
- if (item.widgetItem == 0)
- return 0;
- return reinterpret_cast<quintptr>(item.widgetItem->widget());
-}
-#endif
-
-static const int zero = 0;
-
-QDockAreaLayoutInfo::QDockAreaLayoutInfo()
- : sep(&zero), dockPos(QInternal::LeftDock), o(Qt::Horizontal), mainWindow(0)
-#ifndef QT_NO_TABBAR
- , tabbed(false), tabBar(0), tabBarShape(QTabBar::RoundedSouth)
-#endif
-{
-}
-
-QDockAreaLayoutInfo::QDockAreaLayoutInfo(const int *_sep, QInternal::DockPosition _dockPos,
- Qt::Orientation _o, int tbshape,
- QMainWindow *window)
- : sep(_sep), dockPos(_dockPos), o(_o), mainWindow(window)
-#ifndef QT_NO_TABBAR
- , tabbed(false), tabBar(0), tabBarShape(static_cast<QTabBar::Shape>(tbshape))
-#endif
-{
-#ifdef QT_NO_TABBAR
- Q_UNUSED(tbshape);
-#endif
-}
-
-QSize QDockAreaLayoutInfo::size() const
-{
- return isEmpty() ? QSize(0, 0) : rect.size();
-}
-
-void QDockAreaLayoutInfo::clear()
-{
- item_list.clear();
- rect = QRect();
-#ifndef QT_NO_TABBAR
- tabbed = false;
- tabBar = 0;
-#endif
-}
-
-bool QDockAreaLayoutInfo::isEmpty() const
-{
- return next(-1) == -1;
-}
-
-QSize QDockAreaLayoutInfo::minimumSize() const
-{
- if (isEmpty())
- return QSize(0, 0);
-
- int a = 0, b = 0;
- bool first = true;
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
-
- QSize min_size = item.minimumSize();
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- a = qMax(a, pick(o, min_size));
- } else
-#endif
- {
- if (!first)
- a += *sep;
- a += pick(o, min_size);
- }
- b = qMax(b, perp(o, min_size));
-
- first = false;
- }
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
-#ifndef QT_NO_TABBAR
- QSize tbm = tabBarMinimumSize();
- if (!tbm.isNull()) {
- switch (tabBarShape) {
- case QTabBar::RoundedNorth:
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularNorth:
- case QTabBar::TriangularSouth:
- result.rheight() += tbm.height();
- result.rwidth() = qMax(tbm.width(), result.width());
- break;
- case QTabBar::RoundedEast:
- case QTabBar::RoundedWest:
- case QTabBar::TriangularEast:
- case QTabBar::TriangularWest:
- result.rheight() = qMax(tbm.height(), result.height());
- result.rwidth() += tbm.width();
- break;
- default:
- break;
- }
- }
-#endif // QT_NO_TABBAR
-
- return result;
-}
-
-QSize QDockAreaLayoutInfo::maximumSize() const
-{
- if (isEmpty())
- return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
-
- int a = 0, b = QWIDGETSIZE_MAX;
-#ifndef QT_NO_TABBAR
- if (tabbed)
- a = QWIDGETSIZE_MAX;
-#endif
-
- int min_perp = 0;
-
- bool first = true;
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
-
- QSize max_size = item.maximumSize();
- min_perp = qMax(min_perp, perp(o, item.minimumSize()));
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- a = qMin(a, pick(o, max_size));
- } else
-#endif
- {
- if (!first)
- a += *sep;
- a += pick(o, max_size);
- }
- b = qMin(b, perp(o, max_size));
-
- a = qMin(a, int(QWIDGETSIZE_MAX));
- b = qMin(b, int(QWIDGETSIZE_MAX));
-
- first = false;
- }
-
- b = qMax(b, min_perp);
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
-#ifndef QT_NO_TABBAR
- QSize tbh = tabBarSizeHint();
- if (!tbh.isNull()) {
- switch (tabBarShape) {
- case QTabBar::RoundedNorth:
- case QTabBar::RoundedSouth:
- result.rheight() += tbh.height();
- break;
- case QTabBar::RoundedEast:
- case QTabBar::RoundedWest:
- result.rwidth() += tbh.width();
- break;
- default:
- break;
- }
- }
-#endif // QT_NO_TABBAR
-
- return result;
-}
-
-QSize QDockAreaLayoutInfo::sizeHint() const
-{
- if (isEmpty())
- return QSize(0, 0);
-
- int a = 0, b = 0;
- int min_perp = 0;
- int max_perp = QWIDGETSIZE_MAX;
- const QDockAreaLayoutItem *previous = 0;
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
-
- bool gap = item.flags & QDockAreaLayoutItem::GapItem;
-
- QSize size_hint = item.sizeHint();
- min_perp = qMax(min_perp, perp(o, item.minimumSize()));
- max_perp = qMin(max_perp, perp(o, item.maximumSize()));
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- a = qMax(a, gap ? item.size : pick(o, size_hint));
- } else
-#endif
- {
- if (previous && !gap && !(previous->flags & QDockAreaLayoutItem::GapItem)
- && !previous->hasFixedSize(o)) {
- a += *sep;
- }
- a += gap ? item.size : pick(o, size_hint);
- }
- b = qMax(b, perp(o, size_hint));
-
- previous = &item;
- }
-
- max_perp = qMax(max_perp, min_perp);
- b = qMax(b, min_perp);
- b = qMin(b, max_perp);
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- QSize tbh = tabBarSizeHint();
- switch (tabBarShape) {
- case QTabBar::RoundedNorth:
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularNorth:
- case QTabBar::TriangularSouth:
- result.rheight() += tbh.height();
- result.rwidth() = qMax(tbh.width(), result.width());
- break;
- case QTabBar::RoundedEast:
- case QTabBar::RoundedWest:
- case QTabBar::TriangularEast:
- case QTabBar::TriangularWest:
- result.rheight() = qMax(tbh.height(), result.height());
- result.rwidth() += tbh.width();
- break;
- default:
- break;
- }
- }
-#endif // QT_NO_TABBAR
-
- return result;
-}
-
-bool QDockAreaLayoutInfo::expansive(Qt::Orientation o) const
-{
- for (int i = 0; i < item_list.size(); ++i) {
- if (item_list.at(i).expansive(o))
- return true;
- }
- return false;
-}
-
-/* QDockAreaLayoutInfo::maximumSize() doesn't return the real max size. For example,
- if the layout is empty, it returns QWIDGETSIZE_MAX. This is so that empty dock areas
- don't constrain the size of the QMainWindow, but sometimes we really need to know the
- maximum size. Also, these functions take into account widgets that want to keep their
- size (f.ex. when they are hidden and then shown, they should not change size).
-*/
-
-static int realMinSize(const QDockAreaLayoutInfo &info)
-{
- int result = 0;
- bool first = true;
- for (int i = 0; i < info.item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = info.item_list.at(i);
- if (item.skip())
- continue;
-
- int min = 0;
- if ((item.flags & QDockAreaLayoutItem::KeepSize) && item.size != -1)
- min = item.size;
- else
- min = pick(info.o, item.minimumSize());
-
- if (!first)
- result += *info.sep;
- result += min;
-
- first = false;
- }
-
- return result;
-}
-
-static int realMaxSize(const QDockAreaLayoutInfo &info)
-{
- int result = 0;
- bool first = true;
- for (int i = 0; i < info.item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = info.item_list.at(i);
- if (item.skip())
- continue;
-
- int max = 0;
- if ((item.flags & QDockAreaLayoutItem::KeepSize) && item.size != -1)
- max = item.size;
- else
- max = pick(info.o, item.maximumSize());
-
- if (!first)
- result += *info.sep;
- result += max;
-
- if (result >= QWIDGETSIZE_MAX)
- return QWIDGETSIZE_MAX;
-
- first = false;
- }
-
- return result;
-}
-
-void QDockAreaLayoutInfo::fitItems()
-{
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- return;
- }
-#endif
-
- QVector<QLayoutStruct> layout_struct_list(item_list.size()*2);
- int j = 0;
-
- int size = pick(o, rect.size());
- int min_size = realMinSize(*this);
- int max_size = realMaxSize(*this);
- int last_index = -1;
-
- const QDockAreaLayoutItem *previous = 0;
- for (int i = 0; i < item_list.size(); ++i) {
- QDockAreaLayoutItem &item = item_list[i];
- if (item.skip())
- continue;
-
- bool gap = item.flags & QDockAreaLayoutItem::GapItem;
- if (previous && !gap) {
- if (!(previous->flags & QDockAreaLayoutItem::GapItem)) {
- QLayoutStruct &ls = layout_struct_list[j++];
- ls.init();
- ls.minimumSize = ls.maximumSize = ls.sizeHint = previous->hasFixedSize(o) ? 0 : *sep;
- ls.empty = false;
- }
- }
-
- if (item.flags & QDockAreaLayoutItem::KeepSize) {
- // Check if the item can keep its size, without violating size constraints
- // of other items.
-
- if (size < min_size) {
- // There is too little space to keep this widget's size
- item.flags &= ~QDockAreaLayoutItem::KeepSize;
- min_size -= item.size;
- min_size += pick(o, item.minimumSize());
- min_size = qMax(0, min_size);
- } else if (size > max_size) {
- // There is too much space to keep this widget's size
- item.flags &= ~QDockAreaLayoutItem::KeepSize;
- max_size -= item.size;
- max_size += pick(o, item.maximumSize());
- max_size = qMin<int>(QWIDGETSIZE_MAX, max_size);
- }
- }
-
- last_index = j;
- QLayoutStruct &ls = layout_struct_list[j++];
- ls.init();
- ls.empty = false;
- if (item.flags & QDockAreaLayoutItem::KeepSize) {
- ls.minimumSize = ls.maximumSize = ls.sizeHint = item.size;
- ls.expansive = false;
- ls.stretch = 0;
- } else {
- ls.maximumSize = pick(o, item.maximumSize());
- ls.expansive = item.expansive(o);
- ls.minimumSize = pick(o, item.minimumSize());
- ls.sizeHint = item.size == -1 ? pick(o, item.sizeHint()) : item.size;
- ls.stretch = ls.expansive ? ls.sizeHint : 0;
- }
-
- item.flags &= ~QDockAreaLayoutItem::KeepSize;
- previous = &item;
- }
- layout_struct_list.resize(j);
-
- // If there is more space than the widgets can take (due to maximum size constraints),
- // we detect it here and stretch the last widget to take up the rest of the space.
- if (size > max_size && last_index != -1) {
- layout_struct_list[last_index].maximumSize = QWIDGETSIZE_MAX;
- layout_struct_list[last_index].expansive = true;
- }
-
- qGeomCalc(layout_struct_list, 0, j, pick(o, rect.topLeft()), size, 0);
-
- j = 0;
- bool prev_gap = false;
- bool first = true;
- for (int i = 0; i < item_list.size(); ++i) {
- QDockAreaLayoutItem &item = item_list[i];
- if (item.skip())
- continue;
-
- bool gap = item.flags & QDockAreaLayoutItem::GapItem;
- if (!first && !gap && !prev_gap)
- ++j;
-
- const QLayoutStruct &ls = layout_struct_list.at(j++);
- item.size = ls.size;
- item.pos = ls.pos;
-
- if (item.subinfo != 0) {
- item.subinfo->rect = itemRect(i);
- item.subinfo->fitItems();
- }
-
- prev_gap = gap;
- first = false;
- }
-}
-
-static QInternal::DockPosition dockPosHelper(const QRect &rect, const QPoint &_pos,
- Qt::Orientation o,
- bool nestingEnabled,
- QDockAreaLayoutInfo::TabMode tabMode)
-{
- if (tabMode == QDockAreaLayoutInfo::ForceTabs)
- return QInternal::DockCount;
-
- QPoint pos = _pos - rect.topLeft();
-
- int x = pos.x();
- int y = pos.y();
- int w = rect.width();
- int h = rect.height();
-
- if (tabMode != QDockAreaLayoutInfo::NoTabs) {
- // is it in the center?
- if (nestingEnabled) {
- /* 2/3
- +--------------+
- | |
- | CCCCCCCC |
- 2/3 | CCCCCCCC |
- | CCCCCCCC |
- | |
- +--------------+ */
-
- QRect center(w/6, h/6, 2*w/3, 2*h/3);
- if (center.contains(pos))
- return QInternal::DockCount;
- } else if (o == Qt::Horizontal) {
- /* 2/3
- +--------------+
- | CCCCCCCC |
- | CCCCCCCC |
- | CCCCCCCC |
- | CCCCCCCC |
- | CCCCCCCC |
- +--------------+ */
-
- if (x > w/6 && x < w*5/6)
- return QInternal::DockCount;
- } else {
- /*
- +--------------+
- | |
- 2/3 |CCCCCCCCCCCCCC|
- |CCCCCCCCCCCCCC|
- | |
- +--------------+ */
- if (y > h/6 && y < 5*h/6)
- return QInternal::DockCount;
- }
- }
-
- // not in the center. which edge?
- if (nestingEnabled) {
- if (o == Qt::Horizontal) {
- /* 1/3 1/3 1/3
- +------------+ (we've already ruled out the center)
- |LLLLTTTTRRRR|
- |LLLLTTTTRRRR|
- |LLLLBBBBRRRR|
- |LLLLBBBBRRRR|
- +------------+ */
-
- if (x < w/3)
- return QInternal::LeftDock;
- if (x > 2*w/3)
- return QInternal::RightDock;
- if (y < h/2)
- return QInternal::TopDock;
- return QInternal::BottomDock;
- } else {
- /* +------------+ (we've already ruled out the center)
- 1/3 |TTTTTTTTTTTT|
- |LLLLLLRRRRRR|
- 1/3 |LLLLLLRRRRRR|
- 1/3 |BBBBBBBBBBBB|
- +------------+ */
-
- if (y < h/3)
- return QInternal::TopDock;
- if (y > 2*h/3)
- return QInternal::BottomDock;
- if (x < w/2)
- return QInternal::LeftDock;
- return QInternal::RightDock;
- }
- } else {
- if (o == Qt::Horizontal) {
- return x < w/2
- ? QInternal::LeftDock
- : QInternal::RightDock;
- } else {
- return y < h/2
- ? QInternal::TopDock
- : QInternal::BottomDock;
- }
- }
-}
-
-QList<int> QDockAreaLayoutInfo::gapIndex(const QPoint& _pos,
- bool nestingEnabled, TabMode tabMode) const
-{
- QList<int> result;
- QRect item_rect;
- int item_index = 0;
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- item_rect = tabContentRect();
- } else
-#endif
- {
- int pos = pick(o, _pos);
-
- int last = -1;
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
-
- last = i;
-
- if (item.pos + item.size < pos)
- continue;
-
- if (item.subinfo != 0
-#ifndef QT_NO_TABBAR
- && !item.subinfo->tabbed
-#endif
- ) {
- result = item.subinfo->gapIndex(_pos, nestingEnabled,
- tabMode);
- result.prepend(i);
- return result;
- }
-
- item_rect = itemRect(i);
- item_index = i;
- break;
- }
-
- if (item_rect.isNull()) {
- result.append(last + 1);
- return result;
- }
- }
-
- Q_ASSERT(!item_rect.isNull());
-
- QInternal::DockPosition dock_pos
- = dockPosHelper(item_rect, _pos, o, nestingEnabled, tabMode);
-
- switch (dock_pos) {
- case QInternal::LeftDock:
- if (o == Qt::Horizontal)
- result << item_index;
- else
- result << item_index << 0; // this subinfo doesn't exist yet, but insertGap()
- // handles this by inserting it
- break;
- case QInternal::RightDock:
- if (o == Qt::Horizontal)
- result << item_index + 1;
- else
- result << item_index << 1;
- break;
- case QInternal::TopDock:
- if (o == Qt::Horizontal)
- result << item_index << 0;
- else
- result << item_index;
- break;
- case QInternal::BottomDock:
- if (o == Qt::Horizontal)
- result << item_index << 1;
- else
- result << item_index + 1;
- break;
- case QInternal::DockCount:
- result << (-item_index - 1) << 0; // negative item_index means "on top of"
- // -item_index - 1, insertGap()
- // will insert a tabbed subinfo
- break;
- default:
- break;
- }
-
- return result;
-}
-
-static inline int shrink(QLayoutStruct &ls, int delta)
-{
- if (ls.empty)
- return 0;
- int old_size = ls.size;
- ls.size = qMax(ls.size - delta, ls.minimumSize);
- return old_size - ls.size;
-}
-
-static inline int grow(QLayoutStruct &ls, int delta)
-{
- if (ls.empty)
- return 0;
- int old_size = ls.size;
- ls.size = qMin(ls.size + delta, ls.maximumSize);
- return ls.size - old_size;
-}
-
-static int separatorMoveHelper(QVector<QLayoutStruct> &list, int index, int delta, int sep)
-{
- // adjust sizes
- int pos = -1;
- for (int i = 0; i < list.size(); ++i) {
- const QLayoutStruct &ls = list.at(i);
- if (!ls.empty) {
- pos = ls.pos;
- break;
- }
- }
- if (pos == -1)
- return 0;
-
- if (delta > 0) {
- int growlimit = 0;
- for (int i = 0; i<=index; ++i) {
- const QLayoutStruct &ls = list.at(i);
- if (ls.empty)
- continue;
- if (ls.maximumSize == QLAYOUTSIZE_MAX) {
- growlimit = QLAYOUTSIZE_MAX;
- break;
- }
- growlimit += ls.maximumSize - ls.size;
- }
- if (delta > growlimit)
- delta = growlimit;
-
- int d = 0;
- for (int i = index + 1; d < delta && i < list.count(); ++i)
- d += shrink(list[i], delta - d);
- delta = d;
- d = 0;
- for (int i = index; d < delta && i >= 0; --i)
- d += grow(list[i], delta - d);
- } else if (delta < 0) {
- int growlimit = 0;
- for (int i = index + 1; i < list.count(); ++i) {
- const QLayoutStruct &ls = list.at(i);
- if (ls.empty)
- continue;
- if (ls.maximumSize == QLAYOUTSIZE_MAX) {
- growlimit = QLAYOUTSIZE_MAX;
- break;
- }
- growlimit += ls.maximumSize - ls.size;
- }
- if (-delta > growlimit)
- delta = -growlimit;
-
- int d = 0;
- for (int i = index; d < -delta && i >= 0; --i)
- d += shrink(list[i], -delta - d);
- delta = -d;
- d = 0;
- for (int i = index + 1; d < -delta && i < list.count(); ++i)
- d += grow(list[i], -delta - d);
- }
-
- // adjust positions
- bool first = true;
- for (int i = 0; i < list.size(); ++i) {
- QLayoutStruct &ls = list[i];
- if (ls.empty) {
- ls.pos = pos + (first ? 0 : sep);
- continue;
- }
- if (!first)
- pos += sep;
- ls.pos = pos;
- pos += ls.size;
- first = false;
- }
-
- return delta;
-}
-
-int QDockAreaLayoutInfo::separatorMove(int index, int delta)
-{
-#ifndef QT_NO_TABBAR
- Q_ASSERT(!tabbed);
-#endif
-
- QVector<QLayoutStruct> list(item_list.size());
- for (int i = 0; i < list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- QLayoutStruct &ls = list[i];
- Q_ASSERT(!(item.flags & QDockAreaLayoutItem::GapItem));
- if (item.skip()) {
- ls.empty = true;
- } else {
- const int separatorSpace = item.hasFixedSize(o) ? 0 : *sep;
- ls.empty = false;
- ls.pos = item.pos;
- ls.size = item.size + separatorSpace;
- ls.minimumSize = pick(o, item.minimumSize()) + separatorSpace;
- ls.maximumSize = pick(o, item.maximumSize()) + separatorSpace;
-
- }
- }
-
- //the separator space has been added to the size, so we pass 0 as a parameter
- delta = separatorMoveHelper(list, index, delta, 0 /*separator*/);
-
- for (int i = 0; i < list.size(); ++i) {
- QDockAreaLayoutItem &item = item_list[i];
- if (item.skip())
- continue;
- QLayoutStruct &ls = list[i];
- const int separatorSpace = item.hasFixedSize(o) ? 0 : *sep;
- item.size = ls.size - separatorSpace;
- item.pos = ls.pos;
- if (item.subinfo != 0) {
- item.subinfo->rect = itemRect(i);
- item.subinfo->fitItems();
- }
- }
-
- return delta;
-}
-
-void QDockAreaLayoutInfo::unnest(int index)
-{
- QDockAreaLayoutItem &item = item_list[index];
- if (item.subinfo == 0)
- return;
- if (item.subinfo->item_list.count() > 1)
- return;
-
- if (item.subinfo->item_list.count() == 0) {
- item_list.removeAt(index);
- } else if (item.subinfo->item_list.count() == 1) {
- QDockAreaLayoutItem &child = item.subinfo->item_list.first();
- if (child.widgetItem != 0) {
- item.widgetItem = child.widgetItem;
- delete item.subinfo;
- item.subinfo = 0;
- } else if (child.subinfo != 0) {
- QDockAreaLayoutInfo *tmp = item.subinfo;
- item.subinfo = child.subinfo;
- child.subinfo = 0;
- tmp->item_list.clear();
- delete tmp;
- }
- }
-}
-
-void QDockAreaLayoutInfo::remove(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
-
- if (path.count() > 1) {
- const int index = path.first();
- QDockAreaLayoutItem &item = item_list[index];
- Q_ASSERT(item.subinfo != 0);
- item.subinfo->remove(path.mid(1));
- unnest(index);
- } else {
- int index = path.first();
- item_list.removeAt(index);
- }
-}
-
-QLayoutItem *QDockAreaLayoutInfo::plug(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
-
- int index = path.first();
- if (index < 0)
- index = -index - 1;
-
- if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list.at(index);
- Q_ASSERT(item.subinfo != 0);
- return item.subinfo->plug(path.mid(1));
- }
-
- QDockAreaLayoutItem &item = item_list[index];
-
- Q_ASSERT(item.widgetItem != 0);
- Q_ASSERT(item.flags & QDockAreaLayoutItem::GapItem);
- item.flags &= ~QDockAreaLayoutItem::GapItem;
-
- QRect result;
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- } else
-#endif
- {
- int prev = this->prev(index);
- int next = this->next(index);
-
- if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem)) {
- item.pos += *sep;
- item.size -= *sep;
- }
- if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- item.size -= *sep;
-
- QPoint pos;
- rpick(o, pos) = item.pos;
- rperp(o, pos) = perp(o, rect.topLeft());
- QSize s;
- rpick(o, s) = item.size;
- rperp(o, s) = perp(o, rect.size());
- result = QRect(pos, s);
- }
-
- return item.widgetItem;
-}
-
-QLayoutItem *QDockAreaLayoutInfo::unplug(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
-
- const int index = path.first();
- if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list.at(index);
- Q_ASSERT(item.subinfo != 0);
- return item.subinfo->unplug(path.mid(1));
- }
-
- QDockAreaLayoutItem &item = item_list[index];
- int prev = this->prev(index);
- int next = this->next(index);
-
- Q_ASSERT(!(item.flags & QDockAreaLayoutItem::GapItem));
- item.flags |= QDockAreaLayoutItem::GapItem;
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- } else
-#endif
- {
- if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem)) {
- item.pos -= *sep;
- item.size += *sep;
- }
- if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- item.size += *sep;
- }
-
- return item.widgetItem;
-}
-
-#ifndef QT_NO_TABBAR
-
-quintptr QDockAreaLayoutInfo::currentTabId() const
-{
- if (!tabbed || tabBar == 0)
- return 0;
-
- int index = tabBar->currentIndex();
- if (index == -1)
- return 0;
-
- return qvariant_cast<quintptr>(tabBar->tabData(index));
-}
-
-void QDockAreaLayoutInfo::setCurrentTab(QWidget *widget)
-{
- setCurrentTabId(reinterpret_cast<quintptr>(widget));
-}
-
-void QDockAreaLayoutInfo::setCurrentTabId(quintptr id)
-{
- if (!tabbed || tabBar == 0)
- return;
-
- for (int i = 0; i < tabBar->count(); ++i) {
- if (qvariant_cast<quintptr>(tabBar->tabData(i)) == id) {
- tabBar->setCurrentIndex(i);
- return;
- }
- }
-}
-
-#endif // QT_NO_TABBAR
-
-static QRect dockedGeometry(QWidget *widget)
-{
- int titleHeight = 0;
-
- QDockWidgetLayout *layout
- = qobject_cast<QDockWidgetLayout*>(widget->layout());
- if(layout != 0 && layout->nativeWindowDeco())
- titleHeight = layout->titleHeight();
-
- QRect result = widget->geometry();
- result.adjust(0, -titleHeight, 0, 0);
- return result;
-}
-
-bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWidgetItem)
-{
- Q_ASSERT(!path.isEmpty());
-
- bool insert_tabbed = false;
- int index = path.first();
- if (index < 0) {
- insert_tabbed = true;
- index = -index - 1;
- }
-
-// dump(qDebug() << "insertGap() before:" << index << tabIndex, *this, QString());
-
- if (path.count() > 1) {
- QDockAreaLayoutItem &item = item_list[index];
-
- if (item.subinfo == 0
-#ifndef QT_NO_TABBAR
- || (item.subinfo->tabbed && !insert_tabbed)
-#endif
- ) {
-
- // this is not yet a nested layout - make it
-
- QDockAreaLayoutInfo *subinfo = item.subinfo;
- QLayoutItem *widgetItem = item.widgetItem;
- QPlaceHolderItem *placeHolderItem = item.placeHolderItem;
- QRect r = subinfo == 0 ? widgetItem ? dockedGeometry(widgetItem->widget()) : placeHolderItem->topLevelRect : subinfo->rect;
-
- Qt::Orientation opposite = o == Qt::Horizontal ? Qt::Vertical : Qt::Horizontal;
-#ifdef QT_NO_TABBAR
- const int tabBarShape = 0;
-#endif
- QDockAreaLayoutInfo *new_info
- = new QDockAreaLayoutInfo(sep, dockPos, opposite, tabBarShape, mainWindow);
-
- //item become a new top-level
- item.subinfo = new_info;
- item.widgetItem = 0;
- item.placeHolderItem = 0;
-
- QDockAreaLayoutItem new_item
- = widgetItem == 0
- ? QDockAreaLayoutItem(subinfo)
- : widgetItem ? QDockAreaLayoutItem(widgetItem) : QDockAreaLayoutItem(placeHolderItem);
- new_item.size = pick(opposite, r.size());
- new_item.pos = pick(opposite, r.topLeft());
- new_info->item_list.append(new_item);
-#ifndef QT_NO_TABBAR
- if (insert_tabbed) {
- new_info->tabbed = true;
- }
-#endif
- }
-
- return item.subinfo->insertGap(path.mid(1), dockWidgetItem);
- }
-
- // create the gap item
- QDockAreaLayoutItem gap_item;
- gap_item.flags |= QDockAreaLayoutItem::GapItem;
- gap_item.widgetItem = dockWidgetItem; // so minimumSize(), maximumSize() and
- // sizeHint() will work
-#ifndef QT_NO_TABBAR
- if (!tabbed)
-#endif
- {
- int prev = this->prev(index);
- int next = this->next(index - 1);
- // find out how much space we have in the layout
- int space = 0;
- if (isEmpty()) {
- // I am an empty dock area, therefore I am a top-level dock area.
- switch (dockPos) {
- case QInternal::LeftDock:
- case QInternal::RightDock:
- if (o == Qt::Vertical) {
- // the "size" is the height of the dock area (remember we are empty)
- space = pick(Qt::Vertical, rect.size());
- } else {
- space = pick(Qt::Horizontal, dockWidgetItem->widget()->size());
- }
- break;
- case QInternal::TopDock:
- case QInternal::BottomDock:
- default:
- if (o == Qt::Horizontal) {
- // the "size" is width of the dock area
- space = pick(Qt::Horizontal, rect.size());
- } else {
- space = pick(Qt::Vertical, dockWidgetItem->widget()->size());
- }
- break;
- }
- } else {
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
- Q_ASSERT(!(item.flags & QDockAreaLayoutItem::GapItem));
- space += item.size - pick(o, item.minimumSize());
- }
- }
-
- // find the actual size of the gap
- int gap_size = 0;
- int sep_size = 0;
- if (isEmpty()) {
- gap_size = space;
- sep_size = 0;
- } else {
- QRect r = dockedGeometry(dockWidgetItem->widget());
- gap_size = pick(o, r.size());
- if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem))
- sep_size += *sep;
- if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- sep_size += *sep;
- }
- if (gap_size + sep_size > space)
- gap_size = pick(o, gap_item.minimumSize());
- gap_item.size = gap_size + sep_size;
- }
-
- // finally, insert the gap
- item_list.insert(index, gap_item);
-
-// dump(qDebug() << "insertGap() after:" << index << tabIndex, *this, QString());
-
- return true;
-}
-
-QDockAreaLayoutInfo *QDockAreaLayoutInfo::info(QWidget *widget)
-{
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
-
-#ifndef QT_NO_TABBAR
- if (tabbed && widget == tabBar)
- return this;
-#endif
-
- if (item.widgetItem != 0 && item.widgetItem->widget() == widget)
- return this;
-
- if (item.subinfo != 0) {
- if (QDockAreaLayoutInfo *result = item.subinfo->info(widget))
- return result;
- }
- }
-
- return 0;
-}
-
-QDockAreaLayoutInfo *QDockAreaLayoutInfo::info(const QList<int> &path)
-{
- int index = path.first();
- if (index < 0)
- index = -index - 1;
- if (index >= item_list.count())
- return this;
- if (path.count() == 1 || item_list[index].subinfo == 0)
- return this;
- return item_list[index].subinfo->info(path.mid(1));
-}
-
-QRect QDockAreaLayoutInfo::itemRect(int index) const
-{
- const QDockAreaLayoutItem &item = item_list.at(index);
-
- if (item.skip())
- return QRect();
-
- QRect result;
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- if (tabId(item) == currentTabId())
- result = tabContentRect();
- } else
-#endif
- {
- QPoint pos;
- rpick(o, pos) = item.pos;
- rperp(o, pos) = perp(o, rect.topLeft());
- QSize s;
- rpick(o, s) = item.size;
- rperp(o, s) = perp(o, rect.size());
- result = QRect(pos, s);
- }
-
- return result;
-}
-
-QRect QDockAreaLayoutInfo::itemRect(const QList<int> &path) const
-{
- Q_ASSERT(!path.isEmpty());
-
- const int index = path.first();
- if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list.at(index);
- Q_ASSERT(item.subinfo != 0);
- return item.subinfo->itemRect(path.mid(1));
- }
-
- return itemRect(index);
-}
-
-QRect QDockAreaLayoutInfo::separatorRect(int index) const
-{
-#ifndef QT_NO_TABBAR
- if (tabbed)
- return QRect();
-#endif
-
- const QDockAreaLayoutItem &item = item_list.at(index);
- if (item.skip())
- return QRect();
-
- QPoint pos = rect.topLeft();
- rpick(o, pos) = item.pos + item.size;
- QSize s = rect.size();
- rpick(o, s) = *sep;
-
- return QRect(pos, s);
-}
-
-QRect QDockAreaLayoutInfo::separatorRect(const QList<int> &path) const
-{
- Q_ASSERT(!path.isEmpty());
-
- const int index = path.first();
- if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list.at(index);
- Q_ASSERT(item.subinfo != 0);
- return item.subinfo->separatorRect(path.mid(1));
- }
- return separatorRect(index);
-}
-
-QList<int> QDockAreaLayoutInfo::findSeparator(const QPoint &_pos) const
-{
-#ifndef QT_NO_TABBAR
- if (tabbed)
- return QList<int>();
-#endif
-
- int pos = pick(o, _pos);
-
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip() || (item.flags & QDockAreaLayoutItem::GapItem))
- continue;
-
- if (item.pos + item.size > pos) {
- if (item.subinfo != 0) {
- QList<int> result = item.subinfo->findSeparator(_pos);
- if (!result.isEmpty()) {
- result.prepend(i);
- return result;
- } else {
- return QList<int>();
- }
- }
- }
-
- int next = this->next(i);
- if (next == -1 || (item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- continue;
-
- QRect sepRect = separatorRect(i);
- if (!sepRect.isNull() && *sep == 1)
- sepRect.adjust(-2, -2, 2, 2);
- //we also make sure we don't find a separator that's not there
- if (sepRect.contains(_pos) && !item.hasFixedSize(o)) {
- return QList<int>() << i;
- }
-
- }
-
- return QList<int>();
-}
-
-QList<int> QDockAreaLayoutInfo::indexOfPlaceHolder(const QString &objectName) const
-{
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
-
- if (item.subinfo != 0) {
- QList<int> result = item.subinfo->indexOfPlaceHolder(objectName);
- if (!result.isEmpty()) {
- result.prepend(i);
- return result;
- }
- continue;
- }
-
- if (item.placeHolderItem != 0 && item.placeHolderItem->objectName == objectName) {
- QList<int> result;
- result << i;
- return result;
- }
- }
-
- return QList<int>();
-}
-
-QList<int> QDockAreaLayoutInfo::indexOf(QWidget *widget) const
-{
- for (int i = 0; i < item_list.size(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
-
- if (item.placeHolderItem != 0)
- continue;
-
- if (item.subinfo != 0) {
- QList<int> result = item.subinfo->indexOf(widget);
- if (!result.isEmpty()) {
- result.prepend(i);
- return result;
- }
- continue;
- }
-
- if (!(item.flags & QDockAreaLayoutItem::GapItem) && item.widgetItem->widget() == widget) {
- QList<int> result;
- result << i;
- return result;
- }
- }
-
- return QList<int>();
-}
-
-QMainWindowLayout *QDockAreaLayoutInfo::mainWindowLayout() const
-{
- QMainWindowLayout *result = qt_mainwindow_layout(mainWindow);
- Q_ASSERT(result != 0);
- return result;
-}
-
-bool QDockAreaLayoutInfo::hasFixedSize() const
-{
- return perp(o, minimumSize()) == perp(o, maximumSize());
-}
-
-
-void QDockAreaLayoutInfo::apply(bool animate)
-{
- QWidgetAnimator &widgetAnimator = mainWindowLayout()->widgetAnimator;
-
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- QRect tab_rect;
- QSize tbh = tabBarSizeHint();
-
- if (!tbh.isNull()) {
- switch (tabBarShape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- tab_rect = QRect(rect.left(), rect.top(), rect.width(), tbh.height());
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- tab_rect = QRect(rect.left(), rect.bottom() - tbh.height() + 1,
- rect.width(), tbh.height());
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- tab_rect = QRect(rect.right() - tbh.width() + 1, rect.top(),
- tbh.width(), rect.height());
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- tab_rect = QRect(rect.left(), rect.top(),
- tbh.width(), rect.height());
- break;
- default:
- break;
- }
- }
-
- widgetAnimator.animate(tabBar, tab_rect, animate);
- }
-#endif // QT_NO_TABBAR
-
- for (int i = 0; i < item_list.size(); ++i) {
- QDockAreaLayoutItem &item = item_list[i];
-
- if (item.flags & QDockAreaLayoutItem::GapItem)
- continue;
-
- if (item.subinfo != 0) {
- item.subinfo->apply(animate);
- continue;
- }
-
- if (item.skip())
- continue;
-
- Q_ASSERT(item.widgetItem);
- QRect r = itemRect(i);
- QWidget *w = item.widgetItem->widget();
-
- QRect geo = w->geometry();
- widgetAnimator.animate(w, r, animate);
- if (!w->isHidden() && w->window()->isVisible()) {
- QDockWidget *dw = qobject_cast<QDockWidget*>(w);
- if (!r.isValid() && geo.right() >= 0 && geo.bottom() >= 0) {
- dw->lower();
- emit dw->visibilityChanged(false);
- } else if (r.isValid()
- && (geo.right() < 0 || geo.bottom() < 0)) {
- emit dw->visibilityChanged(true);
- }
- }
- }
-#ifndef QT_NO_TABBAR
- if (*sep == 1)
- updateSeparatorWidgets();
-#endif //QT_NO_TABBAR
-}
-
-static void paintSep(QPainter *p, QWidget *w, const QRect &r, Qt::Orientation o, bool mouse_over)
-{
- QStyleOption opt(0);
- opt.state = QStyle::State_None;
- if (w->isEnabled())
- opt.state |= QStyle::State_Enabled;
- if (o != Qt::Horizontal)
- opt.state |= QStyle::State_Horizontal;
- if (mouse_over)
- opt.state |= QStyle::State_MouseOver;
- opt.rect = r;
- opt.palette = w->palette();
-
- w->style()->drawPrimitive(QStyle::PE_IndicatorDockWidgetResizeHandle, &opt, p, w);
-}
-
-QRegion QDockAreaLayoutInfo::separatorRegion() const
-{
- QRegion result;
-
- if (isEmpty())
- return result;
-#ifndef QT_NO_TABBAR
- if (tabbed)
- return result;
-#endif
-
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
-
- if (item.skip())
- continue;
-
- int next = this->next(i);
-
- if (item.subinfo)
- result |= item.subinfo->separatorRegion();
-
- if (next == -1)
- break;
- result |= separatorRect(i);
- }
-
- return result;
-}
-
-void QDockAreaLayoutInfo::paintSeparators(QPainter *p, QWidget *widget,
- const QRegion &clip,
- const QPoint &mouse) const
-{
- if (isEmpty())
- return;
-#ifndef QT_NO_TABBAR
- if (tabbed)
- return;
-#endif
-
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
-
- if (item.skip())
- continue;
-
- int next = this->next(i);
- if ((item.flags & QDockAreaLayoutItem::GapItem)
- || (next != -1 && (item_list.at(next).flags & QDockAreaLayoutItem::GapItem)))
- continue;
-
- if (item.subinfo) {
- if (clip.contains(item.subinfo->rect))
- item.subinfo->paintSeparators(p, widget, clip, mouse);
- }
-
- if (next == -1)
- break;
- QRect r = separatorRect(i);
- if (clip.contains(r) && !item.hasFixedSize(o))
- paintSep(p, widget, r, o, r.contains(mouse));
- }
-}
-
-int QDockAreaLayoutInfo::next(int index) const
-{
- for (int i = index + 1; i < item_list.size(); ++i) {
- if (!item_list.at(i).skip())
- return i;
- }
- return -1;
-}
-
-int QDockAreaLayoutInfo::prev(int index) const
-{
- for (int i = index - 1; i >= 0; --i) {
- if (!item_list.at(i).skip())
- return i;
- }
- return -1;
-}
-
-void QDockAreaLayoutInfo::tab(int index, QLayoutItem *dockWidgetItem)
-{
-#ifdef QT_NO_TABBAR
- Q_UNUSED(index);
- Q_UNUSED(dockWidgetItem);
-#else
- if (tabbed) {
- item_list.append(QDockAreaLayoutItem(dockWidgetItem));
- updateTabBar();
- setCurrentTab(dockWidgetItem->widget());
- } else {
- QDockAreaLayoutInfo *new_info
- = new QDockAreaLayoutInfo(sep, dockPos, o, tabBarShape, mainWindow);
- item_list[index].subinfo = new_info;
- new_info->item_list.append(item_list.at(index).widgetItem);
- item_list[index].widgetItem = 0;
- new_info->item_list.append(dockWidgetItem);
- new_info->tabbed = true;
- new_info->updateTabBar();
- new_info->setCurrentTab(dockWidgetItem->widget());
- }
-#endif // QT_NO_TABBAR
-}
-
-void QDockAreaLayoutInfo::split(int index, Qt::Orientation orientation,
- QLayoutItem *dockWidgetItem)
-{
- if (orientation == o) {
- item_list.insert(index + 1, QDockAreaLayoutItem(dockWidgetItem));
- } else {
-#ifdef QT_NO_TABBAR
- const int tabBarShape = 0;
-#endif
- QDockAreaLayoutInfo *new_info
- = new QDockAreaLayoutInfo(sep, dockPos, orientation, tabBarShape, mainWindow);
- item_list[index].subinfo = new_info;
- new_info->item_list.append(item_list.at(index).widgetItem);
- item_list[index].widgetItem = 0;
- new_info->item_list.append(dockWidgetItem);
- }
-}
-
-QDockAreaLayoutItem &QDockAreaLayoutInfo::item(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- if (path.count() > 1) {
- const QDockAreaLayoutItem &item = item_list[index];
- Q_ASSERT(item.subinfo != 0);
- return item.subinfo->item(path.mid(1));
- }
- return item_list[index];
-}
-
-QLayoutItem *QDockAreaLayoutInfo::itemAt(int *x, int index) const
-{
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.placeHolderItem != 0)
- continue;
- if (item.subinfo) {
- if (QLayoutItem *ret = item.subinfo->itemAt(x, index))
- return ret;
- } else if (item.widgetItem) {
- if ((*x)++ == index)
- return item.widgetItem;
- }
- }
- return 0;
-}
-
-QLayoutItem *QDockAreaLayoutInfo::takeAt(int *x, int index)
-{
- for (int i = 0; i < item_list.count(); ++i) {
- QDockAreaLayoutItem &item = item_list[i];
- if (item.placeHolderItem != 0)
- continue;
- else if (item.subinfo) {
- if (QLayoutItem *ret = item.subinfo->takeAt(x, index)) {
- unnest(i);
- return ret;
- }
- } else if (item.widgetItem) {
- if ((*x)++ == index) {
- item.placeHolderItem = new QPlaceHolderItem(item.widgetItem->widget());
- QLayoutItem *ret = item.widgetItem;
- item.widgetItem = 0;
- if (item.size != -1)
- item.flags |= QDockAreaLayoutItem::KeepSize;
- return ret;
- }
- }
- }
- return 0;
-}
-
-void QDockAreaLayoutInfo::deleteAllLayoutItems()
-{
- for (int i = 0; i < item_list.count(); ++i) {
- QDockAreaLayoutItem &item= item_list[i];
- if (item.subinfo) {
- item.subinfo->deleteAllLayoutItems();
- } else {
- delete item.widgetItem;
- item.widgetItem = 0;
- }
- }
-}
-
-void QDockAreaLayoutInfo::saveState(QDataStream &stream) const
-{
-#ifndef QT_NO_TABBAR
- if (tabbed) {
- stream << (uchar) TabMarker;
-
- // write the index in item_list of the widget that's currently on top.
- quintptr id = currentTabId();
- int index = -1;
- for (int i = 0; i < item_list.count(); ++i) {
- if (tabId(item_list.at(i)) == id) {
- index = i;
- break;
- }
- }
- stream << index;
- } else
-#endif // QT_NO_TABBAR
- {
- stream << (uchar) SequenceMarker;
- }
-
- stream << (uchar) o << item_list.count();
-
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.widgetItem != 0) {
- stream << (uchar) WidgetMarker;
- QWidget *w = item.widgetItem->widget();
- QString name = w->objectName();
- if (name.isEmpty()) {
- qWarning("QMainWindow::saveState(): 'objectName' not set for QDockWidget %p '%s;",
- w, qPrintable(w->windowTitle()));
- }
- stream << name;
-
- uchar flags = 0;
- if (!w->isHidden())
- flags |= StateFlagVisible;
- if (w->isWindow())
- flags |= StateFlagFloating;
- stream << flags;
-
- if (w->isWindow()) {
- stream << w->x() << w->y() << w->width() << w->height();
- } else {
- stream << item.pos << item.size << pick(o, item.minimumSize())
- << pick(o, item.maximumSize());
- }
- } else if (item.placeHolderItem != 0) {
- stream << (uchar) WidgetMarker;
- stream << item.placeHolderItem->objectName;
- uchar flags = 0;
- if (!item.placeHolderItem->hidden)
- flags |= StateFlagVisible;
- if (item.placeHolderItem->window)
- flags |= StateFlagFloating;
- stream << flags;
- if (item.placeHolderItem->window) {
- QRect r = item.placeHolderItem->topLevelRect;
- stream << r.x() << r.y() << r.width() << r.height();
- } else {
- stream << item.pos << item.size << (int)0 << (int)0;
- }
- } else if (item.subinfo != 0) {
- stream << (uchar) SequenceMarker << item.pos << item.size << pick(o, item.minimumSize()) << pick(o, item.maximumSize());
- item.subinfo->saveState(stream);
- }
- }
-}
-
-static Qt::DockWidgetArea toDockWidgetArea(QInternal::DockPosition pos)
-{
- switch (pos) {
- case QInternal::LeftDock: return Qt::LeftDockWidgetArea;
- case QInternal::RightDock: return Qt::RightDockWidgetArea;
- case QInternal::TopDock: return Qt::TopDockWidgetArea;
- case QInternal::BottomDock: return Qt::BottomDockWidgetArea;
- default: break;
- }
- return Qt::NoDockWidgetArea;
-}
-
-static QRect constrainedRect(QRect rect, const QRect &desktop)
-{
- if (desktop.isValid()) {
- rect.setWidth(qMin(rect.width(), desktop.width()));
- rect.setHeight(qMin(rect.height(), desktop.height()));
- rect.moveLeft(qMax(rect.left(), desktop.left()));
- rect.moveTop(qMax(rect.top(), desktop.top()));
- rect.moveRight(qMin(rect.right(), desktop.right()));
- rect.moveBottom(qMin(rect.bottom(), desktop.bottom()));
- }
-
- return rect;
-}
-
-bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*> &widgets, bool testing)
-{
- uchar marker;
- stream >> marker;
- if (marker != TabMarker && marker != SequenceMarker)
- return false;
-
-#ifndef QT_NO_TABBAR
- tabbed = marker == TabMarker;
-
- int index = -1;
- if (tabbed)
- stream >> index;
-#endif
-
- uchar orientation;
- stream >> orientation;
- o = static_cast<Qt::Orientation>(orientation);
-
- int cnt;
- stream >> cnt;
-
- for (int i = 0; i < cnt; ++i) {
- uchar nextMarker;
- stream >> nextMarker;
- if (nextMarker == WidgetMarker) {
- QString name;
- uchar flags;
- stream >> name >> flags;
- if (name.isEmpty()) {
- int dummy;
- stream >> dummy >> dummy >> dummy >> dummy;
- continue;
- }
-
- QDockWidget *widget = 0;
- for (int j = 0; j < widgets.count(); ++j) {
- if (widgets.at(j)->objectName() == name) {
- widget = widgets.takeAt(j);
- break;
- }
- }
-
- if (widget == 0) {
- QPlaceHolderItem *placeHolder = new QPlaceHolderItem;
- QDockAreaLayoutItem item(placeHolder);
-
- placeHolder->objectName = name;
- placeHolder->window = flags & StateFlagFloating;
- placeHolder->hidden = !(flags & StateFlagVisible);
- if (placeHolder->window) {
- int x, y, w, h;
- stream >> x >> y >> w >> h;
- placeHolder->topLevelRect = QRect(x, y, w, h);
- } else {
- int dummy;
- stream >> item.pos >> item.size >> dummy >> dummy;
- }
- if (item.size != -1)
- item.flags |= QDockAreaLayoutItem::KeepSize;
- if (!testing)
- item_list.append(item);
- } else {
- QDockAreaLayoutItem item(new QDockWidgetItem(widget));
- if (flags & StateFlagFloating) {
- bool drawer = false;
-#ifdef Q_WS_MAC // drawer support
- extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
- extern bool qt_mac_set_drawer_preferred_edge(QWidget *, Qt::DockWidgetArea); //qwidget_mac.cpp
- drawer = qt_mac_is_macdrawer(widget);
-#endif
-
- if (!testing) {
- widget->hide();
- if (!drawer)
- widget->setFloating(true);
- }
-
- int x, y, w, h;
- stream >> x >> y >> w >> h;
-
-#ifdef Q_WS_MAC // drawer support
- if (drawer) {
- mainWindow->window()->createWinId();
- widget->window()->createWinId();
- qt_mac_set_drawer_preferred_edge(widget, toDockWidgetArea(dockPos));
- } else
-#endif
- if (!testing) {
- QRect r(x, y, w, h);
- QDesktopWidget *desktop = QApplication::desktop();
- if (desktop->isVirtualDesktop())
- r = constrainedRect(r, desktop->screenGeometry(desktop->screenNumber(r.topLeft())));
- else
- r = constrainedRect(r, desktop->screenGeometry(widget));
- widget->move(r.topLeft());
- widget->resize(r.size());
- }
-
- if (!testing) {
- widget->setVisible(flags & StateFlagVisible);
- item_list.append(item);
- }
- } else {
- int dummy;
- stream >> item.pos >> item.size >> dummy >> dummy;
- if (!testing) {
- item_list.append(item);
- widget->setFloating(false);
- widget->setVisible(flags & StateFlagVisible);
- emit widget->dockLocationChanged(toDockWidgetArea(dockPos));
- }
- }
- if (testing) {
- //was it is not really added to the layout, we need to delete the object here
- delete item.widgetItem;
- }
- }
- } else if (nextMarker == SequenceMarker) {
- int dummy;
-#ifdef QT_NO_TABBAR
- const int tabBarShape = 0;
-#endif
- QDockAreaLayoutItem item(new QDockAreaLayoutInfo(sep, dockPos, o,
- tabBarShape, mainWindow));
- stream >> item.pos >> item.size >> dummy >> dummy;
- //we need to make sure the element is in the list so the dock widget can eventually be docked correctly
- if (!testing)
- item_list.append(item);
-
- //here we need to make sure we change the item in the item_list
- QDockAreaLayoutItem &lastItem = testing ? item : item_list.last();
-
- if (!lastItem.subinfo->restoreState(stream, widgets, testing))
- return false;
-
- } else {
- return false;
- }
- }
-
-#ifndef QT_NO_TABBAR
- if (!testing && tabbed && index >= 0 && index < item_list.count()) {
- updateTabBar();
- setCurrentTabId(tabId(item_list.at(index)));
- }
- if (!testing && *sep == 1)
- updateSeparatorWidgets();
-#endif
-
- return true;
-}
-
-#ifndef QT_NO_TABBAR
-void QDockAreaLayoutInfo::updateSeparatorWidgets() const
-{
- if (tabbed) {
- separatorWidgets.clear();
- return;
- }
-
- int j = 0;
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
-
- if (item.skip())
- continue;
-
- int next = this->next(i);
- if ((item.flags & QDockAreaLayoutItem::GapItem)
- || (next != -1 && (item_list.at(next).flags & QDockAreaLayoutItem::GapItem)))
- continue;
-
- if (item.subinfo) {
- item.subinfo->updateSeparatorWidgets();
- }
-
- if (next == -1)
- break;
-
- QWidget *sepWidget;
- if (j < separatorWidgets.size() && separatorWidgets.at(j)) {
- sepWidget = separatorWidgets.at(j);
- } else {
- sepWidget = mainWindowLayout()->getSeparatorWidget();
- separatorWidgets.append(sepWidget);
- }
- j++;
-
-#ifndef QT_MAC_USE_COCOA
- sepWidget->raise();
-#endif
- QRect sepRect = separatorRect(i).adjusted(-2, -2, 2, 2);
- sepWidget->setGeometry(sepRect);
- sepWidget->setMask( QRegion(separatorRect(i).translated( - sepRect.topLeft())));
- sepWidget->show();
- }
-
- for (int k = j; k < separatorWidgets.size(); ++k) {
- separatorWidgets[k]->hide();
- }
- separatorWidgets.resize(j);
- Q_ASSERT(separatorWidgets.size() == j);
-}
-#endif //QT_NO_TABBAR
-
-#ifndef QT_NO_TABBAR
-//returns whether the tabbar is visible or not
-bool QDockAreaLayoutInfo::updateTabBar() const
-{
- if (!tabbed)
- return false;
-
- QDockAreaLayoutInfo *that = const_cast<QDockAreaLayoutInfo*>(this);
-
- if (that->tabBar == 0) {
- that->tabBar = mainWindowLayout()->getTabBar();
- that->tabBar->setShape(static_cast<QTabBar::Shape>(tabBarShape));
- that->tabBar->setDrawBase(true);
- }
-
- bool blocked = tabBar->blockSignals(true);
- bool gap = false;
-
- int tab_idx = 0;
- bool changed = false;
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.skip())
- continue;
- if (item.flags & QDockAreaLayoutItem::GapItem) {
- gap = true;
- continue;
- }
- if (item.widgetItem == 0)
- continue;
-
- QDockWidget *dw = qobject_cast<QDockWidget*>(item.widgetItem->widget());
- QString title = dw->d_func()->fixedWindowTitle;
- quintptr id = tabId(item);
- if (tab_idx == tabBar->count()) {
- tabBar->insertTab(tab_idx, title);
-#ifndef QT_NO_TOOLTIP
- tabBar->setTabToolTip(tab_idx, title);
-#endif
- tabBar->setTabData(tab_idx, id);
- changed = true;
- } else if (qvariant_cast<quintptr>(tabBar->tabData(tab_idx)) != id) {
- if (tab_idx + 1 < tabBar->count()
- && qvariant_cast<quintptr>(tabBar->tabData(tab_idx + 1)) == id)
- tabBar->removeTab(tab_idx);
- else {
- tabBar->insertTab(tab_idx, title);
-#ifndef QT_NO_TOOLTIP
- tabBar->setTabToolTip(tab_idx, title);
-#endif
- tabBar->setTabData(tab_idx, id);
- }
- changed = true;
- }
-
- if (title != tabBar->tabText(tab_idx)) {
- tabBar->setTabText(tab_idx, title);
-#ifndef QT_NO_TOOLTIP
- tabBar->setTabToolTip(tab_idx, title);
-#endif
- changed = true;
- }
-
- ++tab_idx;
- }
-
- while (tab_idx < tabBar->count()) {
- tabBar->removeTab(tab_idx);
- changed = true;
- }
-
- tabBar->blockSignals(blocked);
-
- //returns if the tabbar is visible or not
- return ( (gap ? 1 : 0) + tabBar->count()) > 1;
-}
-
-void QDockAreaLayoutInfo::setTabBarShape(int shape)
-{
- if (shape == tabBarShape)
- return;
- tabBarShape = shape;
- if (tabBar != 0)
- tabBar->setShape(static_cast<QTabBar::Shape>(shape));
-
- for (int i = 0; i < item_list.count(); ++i) {
- QDockAreaLayoutItem &item = item_list[i];
- if (item.subinfo != 0)
- item.subinfo->setTabBarShape(shape);
- }
-}
-
-QSize QDockAreaLayoutInfo::tabBarMinimumSize() const
-{
- if (!updateTabBar())
- return QSize(0, 0);
-
- return tabBar->minimumSizeHint();
-}
-
-QSize QDockAreaLayoutInfo::tabBarSizeHint() const
-{
- if (!updateTabBar())
- return QSize(0, 0);
-
- return tabBar->sizeHint();
-}
-
-QSet<QTabBar*> QDockAreaLayoutInfo::usedTabBars() const
-{
- QSet<QTabBar*> result;
-
- if (tabbed) {
- updateTabBar();
- result.insert(tabBar);
- }
-
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.subinfo != 0)
- result += item.subinfo->usedTabBars();
- }
-
- return result;
-}
-
-// returns a set of all used separator widgets for this dockarelayout info
-// and all subinfos
-QSet<QWidget*> QDockAreaLayoutInfo::usedSeparatorWidgets() const
-{
- QSet<QWidget*> result;
-
- for (int i = 0; i < separatorWidgets.count(); ++i)
- result << separatorWidgets.at(i);
-
- for (int i = 0; i < item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = item_list.at(i);
- if (item.subinfo != 0)
- result += item.subinfo->usedSeparatorWidgets();
- }
-
- return result;
-}
-
-QRect QDockAreaLayoutInfo::tabContentRect() const
-{
- if (!tabbed)
- return QRect();
-
- QRect result = rect;
- QSize tbh = tabBarSizeHint();
-
- if (!tbh.isNull()) {
- switch (tabBarShape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- result.adjust(0, tbh.height(), 0, 0);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- result.adjust(0, 0, 0, -tbh.height());
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- result.adjust(0, 0, -tbh.width(), 0);
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- result.adjust(tbh.width(), 0, 0, 0);
- break;
- default:
- break;
- }
- }
-
- return result;
-}
-#endif // QT_NO_TABBAR
-
-/******************************************************************************
-** QDockAreaLayout
-*/
-
-QDockAreaLayout::QDockAreaLayout(QMainWindow *win) : fallbackToSizeHints(true)
-{
- mainWindow = win;
- sep = win->style()->pixelMetric(QStyle::PM_DockWidgetSeparatorExtent, 0, win);
-#ifndef QT_NO_TABBAR
- const int tabShape = QTabBar::RoundedSouth;
-#else
- const int tabShape = 0;
-#endif
- docks[QInternal::LeftDock]
- = QDockAreaLayoutInfo(&sep, QInternal::LeftDock, Qt::Vertical, tabShape, win);
- docks[QInternal::RightDock]
- = QDockAreaLayoutInfo(&sep, QInternal::RightDock, Qt::Vertical, tabShape, win);
- docks[QInternal::TopDock]
- = QDockAreaLayoutInfo(&sep, QInternal::TopDock, Qt::Horizontal, tabShape, win);
- docks[QInternal::BottomDock]
- = QDockAreaLayoutInfo(&sep, QInternal::BottomDock, Qt::Horizontal, tabShape, win);
- centralWidgetItem = 0;
-
-
- corners[Qt::TopLeftCorner] = Qt::TopDockWidgetArea;
- corners[Qt::TopRightCorner] = Qt::TopDockWidgetArea;
- corners[Qt::BottomLeftCorner] = Qt::BottomDockWidgetArea;
- corners[Qt::BottomRightCorner] = Qt::BottomDockWidgetArea;
-}
-
-bool QDockAreaLayout::isValid() const
-{
- return rect.isValid();
-}
-
-void QDockAreaLayout::saveState(QDataStream &stream) const
-{
- stream << (uchar) DockWidgetStateMarker;
- int cnt = 0;
- for (int i = 0; i < QInternal::DockCount; ++i) {
- if (!docks[i].item_list.isEmpty())
- ++cnt;
- }
- stream << cnt;
- for (int i = 0; i < QInternal::DockCount; ++i) {
- if (docks[i].item_list.isEmpty())
- continue;
- stream << i << docks[i].rect.size();
- docks[i].saveState(stream);
- }
-
- stream << centralWidgetRect.size();
-
- for (int i = 0; i < 4; ++i)
- stream << static_cast<int>(corners[i]);
-}
-
-bool QDockAreaLayout::restoreState(QDataStream &stream, const QList<QDockWidget*> &_dockwidgets, bool testing)
-{
- QList<QDockWidget*> dockwidgets = _dockwidgets;
-
- int cnt;
- stream >> cnt;
- for (int i = 0; i < cnt; ++i) {
- int pos;
- stream >> pos;
- QSize size;
- stream >> size;
- if (!testing) {
- docks[pos].rect = QRect(QPoint(0, 0), size);
- }
- if (!docks[pos].restoreState(stream, dockwidgets, testing)) {
- stream.setStatus(QDataStream::ReadCorruptData);
- return false;
- }
- }
-
- QSize size;
- stream >> size;
- centralWidgetRect = QRect(QPoint(0, 0), size);
-
- bool ok = stream.status() == QDataStream::Ok;
-
- if (ok) {
- int cornerData[4];
- for (int i = 0; i < 4; ++i)
- stream >> cornerData[i];
- if (stream.status() == QDataStream::Ok) {
- for (int i = 0; i < 4; ++i)
- corners[i] = static_cast<Qt::DockWidgetArea>(cornerData[i]);
- }
-
- if (!testing)
- fallbackToSizeHints = false;
- }
-
- return ok;
-}
-
-QList<int> QDockAreaLayout::indexOfPlaceHolder(const QString &objectName) const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QList<int> result = docks[i].indexOfPlaceHolder(objectName);
- if (!result.isEmpty()) {
- result.prepend(i);
- return result;
- }
- }
- return QList<int>();
-}
-
-QList<int> QDockAreaLayout::indexOf(QWidget *dockWidget) const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QList<int> result = docks[i].indexOf(dockWidget);
- if (!result.isEmpty()) {
- result.prepend(i);
- return result;
- }
- }
- return QList<int>();
-}
-
-QList<int> QDockAreaLayout::gapIndex(const QPoint &pos) const
-{
- QMainWindow::DockOptions opts = mainWindow->dockOptions();
- bool nestingEnabled = opts & QMainWindow::AllowNestedDocks;
- QDockAreaLayoutInfo::TabMode tabMode = QDockAreaLayoutInfo::NoTabs;
-#ifndef QT_NO_TABBAR
- if (opts & QMainWindow::AllowTabbedDocks
- || opts & QMainWindow::VerticalTabs)
- tabMode = QDockAreaLayoutInfo::AllowTabs;
- if (opts & QMainWindow::ForceTabbedDocks)
- tabMode = QDockAreaLayoutInfo::ForceTabs;
-
- if (tabMode == QDockAreaLayoutInfo::ForceTabs)
- nestingEnabled = false;
-#endif
-
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &info = docks[i];
-
- if (!info.isEmpty() && info.rect.contains(pos)) {
- QList<int> result
- = docks[i].gapIndex(pos, nestingEnabled, tabMode);
- if (!result.isEmpty())
- result.prepend(i);
- return result;
- }
- }
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &info = docks[i];
-
- if (info.isEmpty()) {
- QRect r;
- switch (i) {
- case QInternal::LeftDock:
- r = QRect(rect.left(), rect.top(), EmptyDropAreaSize, rect.height());
- break;
- case QInternal::RightDock:
- r = QRect(rect.right() - EmptyDropAreaSize, rect.top(),
- EmptyDropAreaSize, rect.height());
- break;
- case QInternal::TopDock:
- r = QRect(rect.left(), rect.top(), rect.width(), EmptyDropAreaSize);
- break;
- case QInternal::BottomDock:
- r = QRect(rect.left(), rect.bottom() - EmptyDropAreaSize,
- rect.width(), EmptyDropAreaSize);
- break;
- }
- if (r.contains(pos)) {
- if (opts & QMainWindow::ForceTabbedDocks && !info.item_list.isEmpty()) {
- //in case of ForceTabbedDocks, we pass -1 in order to force the gap to be tabbed
- //it mustn't be completely empty otherwise it won't work
- return QList<int>() << i << -1 << 0;
- } else {
- return QList<int>() << i << 0;
- }
- }
- }
- }
-
- return QList<int>();
-}
-
-QList<int> QDockAreaLayout::findSeparator(const QPoint &pos) const
-{
- QList<int> result;
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &info = docks[i];
- if (info.isEmpty())
- continue;
- QRect rect = separatorRect(i);
- if (!rect.isNull() && sep == 1)
- rect.adjust(-2, -2, 2, 2);
- if (rect.contains(pos) && !info.hasFixedSize()) {
- result << i;
- break;
- } else if (info.rect.contains(pos)) {
- result = docks[i].findSeparator(pos);
- if (!result.isEmpty()) {
- result.prepend(i);
- break;
- }
- }
- }
-
- return result;
-}
-
-QDockAreaLayoutInfo *QDockAreaLayout::info(QWidget *widget)
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- if (QDockAreaLayoutInfo *result = docks[i].info(widget))
- return result;
- }
-
- return 0;
-}
-
-QDockAreaLayoutInfo *QDockAreaLayout::info(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
-
- if (path.count() == 1)
- return &docks[index];
-
- return docks[index].info(path.mid(1));
-}
-
-const QDockAreaLayoutInfo *QDockAreaLayout::info(const QList<int> &path) const
-{
- return const_cast<QDockAreaLayout*>(this)->info(path);
-}
-
-QDockAreaLayoutItem &QDockAreaLayout::item(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- return docks[index].item(path.mid(1));
-}
-
-QRect QDockAreaLayout::itemRect(const QList<int> &path) const
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- return docks[index].itemRect(path.mid(1));
-}
-
-QRect QDockAreaLayout::separatorRect(int index) const
-{
- const QDockAreaLayoutInfo &dock = docks[index];
- if (dock.isEmpty())
- return QRect();
- QRect r = dock.rect;
- switch (index) {
- case QInternal::LeftDock:
- return QRect(r.right() + 1, r.top(), sep, r.height());
- case QInternal::RightDock:
- return QRect(r.left() - sep, r.top(), sep, r.height());
- case QInternal::TopDock:
- return QRect(r.left(), r.bottom() + 1, r.width(), sep);
- case QInternal::BottomDock:
- return QRect(r.left(), r.top() - sep, r.width(), sep);
- default:
- break;
- }
- return QRect();
-}
-
-QRect QDockAreaLayout::separatorRect(const QList<int> &path) const
-{
- Q_ASSERT(!path.isEmpty());
-
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
-
- if (path.count() == 1)
- return separatorRect(index);
- else
- return docks[index].separatorRect(path.mid(1));
-}
-
-bool QDockAreaLayout::insertGap(const QList<int> &path, QLayoutItem *dockWidgetItem)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- return docks[index].insertGap(path.mid(1), dockWidgetItem);
-}
-
-QLayoutItem *QDockAreaLayout::plug(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- return docks[index].plug(path.mid(1));
-}
-
-QLayoutItem *QDockAreaLayout::unplug(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- return docks[index].unplug(path.mid(1));
-}
-
-void QDockAreaLayout::remove(const QList<int> &path)
-{
- Q_ASSERT(!path.isEmpty());
- const int index = path.first();
- Q_ASSERT(index >= 0 && index < QInternal::DockCount);
- docks[index].remove(path.mid(1));
-}
-
-static inline int qMin(int i1, int i2, int i3) { return qMin(i1, qMin(i2, i3)); }
-static inline int qMax(int i1, int i2, int i3) { return qMax(i1, qMax(i2, i3)); }
-
-void QDockAreaLayout::getGrid(QVector<QLayoutStruct> *_ver_struct_list,
- QVector<QLayoutStruct> *_hor_struct_list)
-{
- QSize center_hint(0, 0);
- QSize center_min(0, 0);
- const bool have_central = centralWidgetItem != 0 && !centralWidgetItem->isEmpty();
- if (have_central) {
- center_hint = centralWidgetRect.size();
- if (!center_hint.isValid())
- center_hint = centralWidgetItem->sizeHint();
- center_min = centralWidgetItem->minimumSize();
- }
-
- QRect center_rect = rect;
- if (!docks[QInternal::LeftDock].isEmpty())
- center_rect.setLeft(rect.left() + docks[QInternal::LeftDock].rect.width() + sep);
- if (!docks[QInternal::TopDock].isEmpty())
- center_rect.setTop(rect.top() + docks[QInternal::TopDock].rect.height() + sep);
- if (!docks[QInternal::RightDock].isEmpty())
- center_rect.setRight(rect.right() - docks[QInternal::RightDock].rect.width() - sep);
- if (!docks[QInternal::BottomDock].isEmpty())
- center_rect.setBottom(rect.bottom() - docks[QInternal::BottomDock].rect.height() - sep);
-
- QSize left_hint = docks[QInternal::LeftDock].size();
- if (left_hint.isNull() || fallbackToSizeHints)
- left_hint = docks[QInternal::LeftDock].sizeHint();
- QSize left_min = docks[QInternal::LeftDock].minimumSize();
- QSize left_max = docks[QInternal::LeftDock].maximumSize();
- left_hint = left_hint.boundedTo(left_max).expandedTo(left_min);
-
- QSize right_hint = docks[QInternal::RightDock].size();
- if (right_hint.isNull() || fallbackToSizeHints)
- right_hint = docks[QInternal::RightDock].sizeHint();
- QSize right_min = docks[QInternal::RightDock].minimumSize();
- QSize right_max = docks[QInternal::RightDock].maximumSize();
- right_hint = right_hint.boundedTo(right_max).expandedTo(right_min);
-
- QSize top_hint = docks[QInternal::TopDock].size();
- if (top_hint.isNull() || fallbackToSizeHints)
- top_hint = docks[QInternal::TopDock].sizeHint();
- QSize top_min = docks[QInternal::TopDock].minimumSize();
- QSize top_max = docks[QInternal::TopDock].maximumSize();
- top_hint = top_hint.boundedTo(top_max).expandedTo(top_min);
-
- QSize bottom_hint = docks[QInternal::BottomDock].size();
- if (bottom_hint.isNull() || fallbackToSizeHints)
- bottom_hint = docks[QInternal::BottomDock].sizeHint();
- QSize bottom_min = docks[QInternal::BottomDock].minimumSize();
- QSize bottom_max = docks[QInternal::BottomDock].maximumSize();
- bottom_hint = bottom_hint.boundedTo(bottom_max).expandedTo(bottom_min);
-
- fallbackToSizeHints = false;
-
- if (_ver_struct_list != 0) {
- QVector<QLayoutStruct> &ver_struct_list = *_ver_struct_list;
- ver_struct_list.resize(3);
-
- // top --------------------------------------------------
- ver_struct_list[0].init();
- ver_struct_list[0].stretch = 0;
- ver_struct_list[0].sizeHint = top_hint.height();
- ver_struct_list[0].minimumSize = top_min.height();
- ver_struct_list[0].maximumSize = top_max.height();
- ver_struct_list[0].expansive = false;
- ver_struct_list[0].empty = docks[QInternal::TopDock].isEmpty();
- ver_struct_list[0].pos = docks[QInternal::TopDock].rect.top();
- ver_struct_list[0].size = docks[QInternal::TopDock].rect.height();
-
- // center --------------------------------------------------
- ver_struct_list[1].init();
- ver_struct_list[1].stretch = center_hint.height();
-
- bool tl_significant = corners[Qt::TopLeftCorner] == Qt::TopDockWidgetArea
- || docks[QInternal::TopDock].isEmpty();
- bool bl_significant = corners[Qt::BottomLeftCorner] == Qt::BottomDockWidgetArea
- || docks[QInternal::BottomDock].isEmpty();
- bool tr_significant = corners[Qt::TopRightCorner] == Qt::TopDockWidgetArea
- || docks[QInternal::TopDock].isEmpty();
- bool br_significant = corners[Qt::BottomRightCorner] == Qt::BottomDockWidgetArea
- || docks[QInternal::BottomDock].isEmpty();
-
- int left = (tl_significant && bl_significant) ? left_hint.height() : 0;
- int right = (tr_significant && br_significant) ? right_hint.height() : 0;
- ver_struct_list[1].sizeHint = qMax(left, center_hint.height(), right);
-
- left = (tl_significant && bl_significant) ? left_min.height() : 0;
- right = (tr_significant && br_significant) ? right_min.height() : 0;
- ver_struct_list[1].minimumSize = qMax(left, center_min.height(), right);
- ver_struct_list[1].maximumSize = have_central ? QWIDGETSIZE_MAX : 0;
- ver_struct_list[1].expansive = have_central;
- ver_struct_list[1].empty = docks[QInternal::LeftDock].isEmpty()
- && !have_central
- && docks[QInternal::RightDock].isEmpty();
- ver_struct_list[1].pos = center_rect.top();
- ver_struct_list[1].size = center_rect.height();
-
- // bottom --------------------------------------------------
- ver_struct_list[2].init();
- ver_struct_list[2].stretch = 0;
- ver_struct_list[2].sizeHint = bottom_hint.height();
- ver_struct_list[2].minimumSize = bottom_min.height();
- ver_struct_list[2].maximumSize = bottom_max.height();
- ver_struct_list[2].expansive = false;
- ver_struct_list[2].empty = docks[QInternal::BottomDock].isEmpty();
- ver_struct_list[2].pos = docks[QInternal::BottomDock].rect.top();
- ver_struct_list[2].size = docks[QInternal::BottomDock].rect.height();
-
- for (int i = 0; i < 3; ++i) {
- ver_struct_list[i].sizeHint
- = qMax(ver_struct_list[i].sizeHint, ver_struct_list[i].minimumSize);
- }
- }
-
- if (_hor_struct_list != 0) {
- QVector<QLayoutStruct> &hor_struct_list = *_hor_struct_list;
- hor_struct_list.resize(3);
-
- // left --------------------------------------------------
- hor_struct_list[0].init();
- hor_struct_list[0].stretch = 0;
- hor_struct_list[0].sizeHint = left_hint.width();
- hor_struct_list[0].minimumSize = left_min.width();
- hor_struct_list[0].maximumSize = left_max.width();
- hor_struct_list[0].expansive = false;
- hor_struct_list[0].empty = docks[QInternal::LeftDock].isEmpty();
- hor_struct_list[0].pos = docks[QInternal::LeftDock].rect.left();
- hor_struct_list[0].size = docks[QInternal::LeftDock].rect.width();
-
- // center --------------------------------------------------
- hor_struct_list[1].init();
- hor_struct_list[1].stretch = center_hint.width();
-
- bool tl_significant = corners[Qt::TopLeftCorner] == Qt::LeftDockWidgetArea
- || docks[QInternal::LeftDock].isEmpty();
- bool tr_significant = corners[Qt::TopRightCorner] == Qt::RightDockWidgetArea
- || docks[QInternal::RightDock].isEmpty();
- bool bl_significant = corners[Qt::BottomLeftCorner] == Qt::LeftDockWidgetArea
- || docks[QInternal::LeftDock].isEmpty();
- bool br_significant = corners[Qt::BottomRightCorner] == Qt::RightDockWidgetArea
- || docks[QInternal::RightDock].isEmpty();
-
- int top = (tl_significant && tr_significant) ? top_hint.width() : 0;
- int bottom = (bl_significant && br_significant) ? bottom_hint.width() : 0;
- hor_struct_list[1].sizeHint = qMax(top, center_hint.width(), bottom);
-
- top = (tl_significant && tr_significant) ? top_min.width() : 0;
- bottom = (bl_significant && br_significant) ? bottom_min.width() : 0;
- hor_struct_list[1].minimumSize = qMax(top, center_min.width(), bottom);
-
- hor_struct_list[1].maximumSize = have_central ? QWIDGETSIZE_MAX : 0;
- hor_struct_list[1].expansive = have_central;
- hor_struct_list[1].empty = !have_central;
- hor_struct_list[1].pos = center_rect.left();
- hor_struct_list[1].size = center_rect.width();
-
- // right --------------------------------------------------
- hor_struct_list[2].init();
- hor_struct_list[2].stretch = 0;
- hor_struct_list[2].sizeHint = right_hint.width();
- hor_struct_list[2].minimumSize = right_min.width();
- hor_struct_list[2].maximumSize = right_max.width();
- hor_struct_list[2].expansive = false;
- hor_struct_list[2].empty = docks[QInternal::RightDock].isEmpty();
- hor_struct_list[2].pos = docks[QInternal::RightDock].rect.left();
- hor_struct_list[2].size = docks[QInternal::RightDock].rect.width();
-
- for (int i = 0; i < 3; ++i) {
- hor_struct_list[i].sizeHint
- = qMax(hor_struct_list[i].sizeHint, hor_struct_list[i].minimumSize);
- }
- }
-}
-
-void QDockAreaLayout::setGrid(QVector<QLayoutStruct> *ver_struct_list,
- QVector<QLayoutStruct> *hor_struct_list)
-{
-
- // top ---------------------------------------------------
-
- if (!docks[QInternal::TopDock].isEmpty()) {
- QRect r = docks[QInternal::TopDock].rect;
- if (hor_struct_list != 0) {
- r.setLeft(corners[Qt::TopLeftCorner] == Qt::TopDockWidgetArea
- || docks[QInternal::LeftDock].isEmpty()
- ? rect.left() : hor_struct_list->at(1).pos);
- r.setRight(corners[Qt::TopRightCorner] == Qt::TopDockWidgetArea
- || docks[QInternal::RightDock].isEmpty()
- ? rect.right() : hor_struct_list->at(2).pos - sep - 1);
- }
- if (ver_struct_list != 0) {
- r.setTop(rect.top());
- r.setBottom(ver_struct_list->at(1).pos - sep - 1);
- }
- docks[QInternal::TopDock].rect = r;
- docks[QInternal::TopDock].fitItems();
- }
-
- // bottom ---------------------------------------------------
-
- if (!docks[QInternal::BottomDock].isEmpty()) {
- QRect r = docks[QInternal::BottomDock].rect;
- if (hor_struct_list != 0) {
- r.setLeft(corners[Qt::BottomLeftCorner] == Qt::BottomDockWidgetArea
- || docks[QInternal::LeftDock].isEmpty()
- ? rect.left() : hor_struct_list->at(1).pos);
- r.setRight(corners[Qt::BottomRightCorner] == Qt::BottomDockWidgetArea
- || docks[QInternal::RightDock].isEmpty()
- ? rect.right() : hor_struct_list->at(2).pos - sep - 1);
- }
- if (ver_struct_list != 0) {
- r.setTop(ver_struct_list->at(2).pos);
- r.setBottom(rect.bottom());
- }
- docks[QInternal::BottomDock].rect = r;
- docks[QInternal::BottomDock].fitItems();
- }
-
- // left ---------------------------------------------------
-
- if (!docks[QInternal::LeftDock].isEmpty()) {
- QRect r = docks[QInternal::LeftDock].rect;
- if (hor_struct_list != 0) {
- r.setLeft(rect.left());
- r.setRight(hor_struct_list->at(1).pos - sep - 1);
- }
- if (ver_struct_list != 0) {
- r.setTop(corners[Qt::TopLeftCorner] == Qt::LeftDockWidgetArea
- || docks[QInternal::TopDock].isEmpty()
- ? rect.top() : ver_struct_list->at(1).pos);
- r.setBottom(corners[Qt::BottomLeftCorner] == Qt::LeftDockWidgetArea
- || docks[QInternal::BottomDock].isEmpty()
- ? rect.bottom() : ver_struct_list->at(2).pos - sep - 1);
- }
- docks[QInternal::LeftDock].rect = r;
- docks[QInternal::LeftDock].fitItems();
- }
-
- // right ---------------------------------------------------
-
- if (!docks[QInternal::RightDock].isEmpty()) {
- QRect r = docks[QInternal::RightDock].rect;
- if (hor_struct_list != 0) {
- r.setLeft(hor_struct_list->at(2).pos);
- r.setRight(rect.right());
- }
- if (ver_struct_list != 0) {
- r.setTop(corners[Qt::TopRightCorner] == Qt::RightDockWidgetArea
- || docks[QInternal::TopDock].isEmpty()
- ? rect.top() : ver_struct_list->at(1).pos);
- r.setBottom(corners[Qt::BottomRightCorner] == Qt::RightDockWidgetArea
- || docks[QInternal::BottomDock].isEmpty()
- ? rect.bottom() : ver_struct_list->at(2).pos - sep - 1);
- }
- docks[QInternal::RightDock].rect = r;
- docks[QInternal::RightDock].fitItems();
- }
-
- // center ---------------------------------------------------
-
- if (hor_struct_list != 0) {
- centralWidgetRect.setLeft(hor_struct_list->at(1).pos);
- centralWidgetRect.setWidth(hor_struct_list->at(1).size);
- }
- if (ver_struct_list != 0) {
- centralWidgetRect.setTop(ver_struct_list->at(1).pos);
- centralWidgetRect.setHeight(ver_struct_list->at(1).size);
- }
-}
-
-void QDockAreaLayout::fitLayout()
-{
- QVector<QLayoutStruct> ver_struct_list(3);
- QVector<QLayoutStruct> hor_struct_list(3);
- getGrid(&ver_struct_list, &hor_struct_list);
-
- qGeomCalc(ver_struct_list, 0, 3, rect.top(), rect.height(), sep);
- qGeomCalc(hor_struct_list, 0, 3, rect.left(), rect.width(), sep);
-
- setGrid(&ver_struct_list, &hor_struct_list);
-}
-
-void QDockAreaLayout::clear()
-{
- for (int i = 0; i < QInternal::DockCount; ++i)
- docks[i].clear();
-
- rect = QRect();
- centralWidgetRect = QRect();
-}
-
-QSize QDockAreaLayout::sizeHint() const
-{
- int left_sep = 0;
- int right_sep = 0;
- int top_sep = 0;
- int bottom_sep = 0;
-
- if (centralWidgetItem != 0) {
- left_sep = docks[QInternal::LeftDock].isEmpty() ? 0 : sep;
- right_sep = docks[QInternal::RightDock].isEmpty() ? 0 : sep;
- top_sep = docks[QInternal::TopDock].isEmpty() ? 0 : sep;
- bottom_sep = docks[QInternal::BottomDock].isEmpty() ? 0 : sep;
- }
-
- QSize left = docks[QInternal::LeftDock].sizeHint() + QSize(left_sep, 0);
- QSize right = docks[QInternal::RightDock].sizeHint() + QSize(right_sep, 0);
- QSize top = docks[QInternal::TopDock].sizeHint() + QSize(0, top_sep);
- QSize bottom = docks[QInternal::BottomDock].sizeHint() + QSize(0, bottom_sep);
- QSize center = centralWidgetItem == 0 ? QSize(0, 0) : centralWidgetItem->sizeHint();
-
- int row1 = top.width();
- int row2 = left.width() + center.width() + right.width();
- int row3 = bottom.width();
- int col1 = left.height();
- int col2 = top.height() + center.height() + bottom.height();
- int col3 = right.height();
-
- if (corners[Qt::TopLeftCorner] == Qt::LeftDockWidgetArea)
- row1 += left.width();
- else
- col1 += top.height();
-
- if (corners[Qt::TopRightCorner] == Qt::RightDockWidgetArea)
- row1 += right.width();
- else
- col3 += top.height();
-
- if (corners[Qt::BottomLeftCorner] == Qt::LeftDockWidgetArea)
- row3 += left.width();
- else
- col1 += bottom.height();
-
- if (corners[Qt::BottomRightCorner] == Qt::RightDockWidgetArea)
- row3 += right.width();
- else
- col3 += bottom.height();
-
- return QSize(qMax(row1, row2, row3), qMax(col1, col2, col3));
-}
-
-QSize QDockAreaLayout::minimumSize() const
-{
- int left_sep = 0;
- int right_sep = 0;
- int top_sep = 0;
- int bottom_sep = 0;
-
- if (centralWidgetItem != 0) {
- left_sep = docks[QInternal::LeftDock].isEmpty() ? 0 : sep;
- right_sep = docks[QInternal::RightDock].isEmpty() ? 0 : sep;
- top_sep = docks[QInternal::TopDock].isEmpty() ? 0 : sep;
- bottom_sep = docks[QInternal::BottomDock].isEmpty() ? 0 : sep;
- }
-
- QSize left = docks[QInternal::LeftDock].minimumSize() + QSize(left_sep, 0);
- QSize right = docks[QInternal::RightDock].minimumSize() + QSize(right_sep, 0);
- QSize top = docks[QInternal::TopDock].minimumSize() + QSize(0, top_sep);
- QSize bottom = docks[QInternal::BottomDock].minimumSize() + QSize(0, bottom_sep);
- QSize center = centralWidgetItem == 0 ? QSize(0, 0) : centralWidgetItem->minimumSize();
-
- int row1 = top.width();
- int row2 = left.width() + center.width() + right.width();
- int row3 = bottom.width();
- int col1 = left.height();
- int col2 = top.height() + center.height() + bottom.height();
- int col3 = right.height();
-
- if (corners[Qt::TopLeftCorner] == Qt::LeftDockWidgetArea)
- row1 += left.width();
- else
- col1 += top.height();
-
- if (corners[Qt::TopRightCorner] == Qt::RightDockWidgetArea)
- row1 += right.width();
- else
- col3 += top.height();
-
- if (corners[Qt::BottomLeftCorner] == Qt::LeftDockWidgetArea)
- row3 += left.width();
- else
- col1 += bottom.height();
-
- if (corners[Qt::BottomRightCorner] == Qt::RightDockWidgetArea)
- row3 += right.width();
- else
- col3 += bottom.height();
-
- return QSize(qMax(row1, row2, row3), qMax(col1, col2, col3));
-}
-
-bool QDockAreaLayout::restoreDockWidget(QDockWidget *dockWidget)
-{
- QList<int> index = indexOfPlaceHolder(dockWidget->objectName());
- if (index.isEmpty())
- return false;
-
- QDockAreaLayoutItem &item = this->item(index);
- QPlaceHolderItem *placeHolder = item.placeHolderItem;
- Q_ASSERT(placeHolder != 0);
-
- item.widgetItem = new QDockWidgetItem(dockWidget);
-
- if (placeHolder->window) {
- QDesktopWidget desktop;
- QRect r = constrainedRect(placeHolder->topLevelRect, desktop.screenGeometry(dockWidget));
- dockWidget->d_func()->setWindowState(true, true, r);
- }
- dockWidget->setVisible(!placeHolder->hidden);
-#ifdef Q_WS_X11
- if (placeHolder->window) // gets rid of the X11BypassWindowManager window flag
- dockWidget->d_func()->setWindowState(true);
-#endif
-
- item.placeHolderItem = 0;
- delete placeHolder;
-
- return true;
-}
-
-void QDockAreaLayout::addDockWidget(QInternal::DockPosition pos, QDockWidget *dockWidget,
- Qt::Orientation orientation)
-{
- QLayoutItem *dockWidgetItem = new QDockWidgetItem(dockWidget);
- QDockAreaLayoutInfo &info = docks[pos];
- if (orientation == info.o || info.item_list.count() <= 1) {
- // empty dock areas, or dock areas containing exactly one widget can have their orientation
- // switched.
- info.o = orientation;
-
- QDockAreaLayoutItem new_item(dockWidgetItem);
- info.item_list.append(new_item);
-#ifndef QT_NO_TABBAR
- if (info.tabbed && !new_item.skip()) {
- info.updateTabBar();
- info.setCurrentTabId(tabId(new_item));
- }
-#endif
- } else {
-#ifndef QT_NO_TABBAR
- int tbshape = info.tabBarShape;
-#else
- int tbshape = 0;
-#endif
- QDockAreaLayoutInfo new_info(&sep, pos, orientation, tbshape, mainWindow);
- new_info.item_list.append(new QDockAreaLayoutInfo(info));
- new_info.item_list.append(dockWidgetItem);
- info = new_info;
- }
-
- QList<int> index = indexOfPlaceHolder(dockWidget->objectName());
- if (!index.isEmpty())
- remove(index);
-}
-
-void QDockAreaLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
-{
- QList<int> path = indexOf(first);
- if (path.isEmpty())
- return;
-
- QDockAreaLayoutInfo *info = this->info(path);
- Q_ASSERT(info != 0);
- info->tab(path.last(), new QDockWidgetItem(second));
-
- QList<int> index = indexOfPlaceHolder(second->objectName());
- if (!index.isEmpty())
- remove(index);
-}
-
-void QDockAreaLayout::splitDockWidget(QDockWidget *after,
- QDockWidget *dockWidget,
- Qt::Orientation orientation)
-{
- QList<int> path = indexOf(after);
- if (path.isEmpty())
- return;
-
- QDockAreaLayoutInfo *info = this->info(path);
- Q_ASSERT(info != 0);
- info->split(path.last(), orientation, new QDockWidgetItem(dockWidget));
-
- QList<int> index = indexOfPlaceHolder(dockWidget->objectName());
- if (!index.isEmpty())
- remove(index);
-}
-
-void QDockAreaLayout::apply(bool animate)
-{
- QWidgetAnimator &widgetAnimator = qt_mainwindow_layout(mainWindow)->widgetAnimator;
-
- for (int i = 0; i < QInternal::DockCount; ++i)
- docks[i].apply(animate);
- if (centralWidgetItem != 0 && !centralWidgetItem->isEmpty()) {
- widgetAnimator.animate(centralWidgetItem->widget(), centralWidgetRect,
- animate);
- }
-#ifndef QT_NO_TABBAR
- if (sep == 1)
- updateSeparatorWidgets();
-#endif //QT_NO_TABBAR
-}
-
-void QDockAreaLayout::paintSeparators(QPainter *p, QWidget *widget,
- const QRegion &clip,
- const QPoint &mouse) const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &dock = docks[i];
- if (dock.isEmpty())
- continue;
- QRect r = separatorRect(i);
- if (clip.contains(r) && !dock.hasFixedSize()) {
- Qt::Orientation opposite = dock.o == Qt::Horizontal
- ? Qt::Vertical : Qt::Horizontal;
- paintSep(p, widget, r, opposite, r.contains(mouse));
- }
- if (clip.contains(dock.rect))
- dock.paintSeparators(p, widget, clip, mouse);
- }
-}
-
-QRegion QDockAreaLayout::separatorRegion() const
-{
- QRegion result;
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &dock = docks[i];
- if (dock.isEmpty())
- continue;
- result |= separatorRect(i);
- result |= dock.separatorRegion();
- }
-
- return result;
-}
-
-int QDockAreaLayout::separatorMove(const QList<int> &separator, const QPoint &origin,
- const QPoint &dest)
-{
- int delta = 0;
- int index = separator.last();
-
- if (separator.count() > 1) {
- QDockAreaLayoutInfo *info = this->info(separator);
- delta = pick(info->o, dest - origin);
- if (delta != 0)
- delta = info->separatorMove(index, delta);
- info->apply(false);
- return delta;
- }
-
- QVector<QLayoutStruct> list;
-
- if (index == QInternal::LeftDock || index == QInternal::RightDock)
- getGrid(0, &list);
- else
- getGrid(&list, 0);
-
- int sep_index = index == QInternal::LeftDock || index == QInternal::TopDock
- ? 0 : 1;
- Qt::Orientation o = index == QInternal::LeftDock || index == QInternal::RightDock
- ? Qt::Horizontal
- : Qt::Vertical;
-
- delta = pick(o, dest - origin);
- delta = separatorMoveHelper(list, sep_index, delta, sep);
-
- if (index == QInternal::LeftDock || index == QInternal::RightDock)
- setGrid(0, &list);
- else
- setGrid(&list, 0);
-
- apply(false);
-
- return delta;
-}
-
-#ifndef QT_NO_TABBAR
-// Sets the correct positions for the separator widgets
-// Allocates new sepearator widgets with getSeparatorWidget
-void QDockAreaLayout::updateSeparatorWidgets() const
-{
- int j = 0;
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &dock = docks[i];
- if (dock.isEmpty())
- continue;
-
- QWidget *sepWidget;
- if (j < separatorWidgets.size()) {
- sepWidget = separatorWidgets.at(j);
- } else {
- sepWidget = qt_mainwindow_layout(mainWindow)->getSeparatorWidget();
- separatorWidgets.append(sepWidget);
- }
- j++;
-
-#ifndef QT_MAC_USE_COCOA
- sepWidget->raise();
-#endif
- QRect sepRect = separatorRect(i).adjusted(-2, -2, 2, 2);
- sepWidget->setGeometry(sepRect);
- sepWidget->setMask( QRegion(separatorRect(i).translated( - sepRect.topLeft())));
- sepWidget->show();
- }
- for (int i = j; i < separatorWidgets.size(); ++i)
- separatorWidgets.at(i)->hide();
-
- separatorWidgets.resize(j);
-}
-#endif //QT_NO_TABBAR
-
-QLayoutItem *QDockAreaLayout::itemAt(int *x, int index) const
-{
- Q_ASSERT(x != 0);
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &dock = docks[i];
- if (QLayoutItem *ret = dock.itemAt(x, index))
- return ret;
- }
-
- if (centralWidgetItem && (*x)++ == index)
- return centralWidgetItem;
-
- return 0;
-}
-
-QLayoutItem *QDockAreaLayout::takeAt(int *x, int index)
-{
- Q_ASSERT(x != 0);
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QDockAreaLayoutInfo &dock = docks[i];
- if (QLayoutItem *ret = dock.takeAt(x, index))
- return ret;
- }
-
- if (centralWidgetItem && (*x)++ == index) {
- QLayoutItem *ret = centralWidgetItem;
- centralWidgetItem = 0;
- return ret;
- }
-
- return 0;
-}
-
-void QDockAreaLayout::deleteAllLayoutItems()
-{
- for (int i = 0; i < QInternal::DockCount; ++i)
- docks[i].deleteAllLayoutItems();
-}
-
-#ifndef QT_NO_TABBAR
-QSet<QTabBar*> QDockAreaLayout::usedTabBars() const
-{
- QSet<QTabBar*> result;
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &dock = docks[i];
- result += dock.usedTabBars();
- }
- return result;
-}
-
-// Returns the set of all used separator widgets
-QSet<QWidget*> QDockAreaLayout::usedSeparatorWidgets() const
-{
- QSet<QWidget*> result;
-
- for (int i = 0; i < separatorWidgets.count(); ++i)
- result << separatorWidgets.at(i);
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QDockAreaLayoutInfo &dock = docks[i];
- result += dock.usedSeparatorWidgets();
- }
- return result;
-}
-#endif
-
-QRect QDockAreaLayout::gapRect(const QList<int> &path) const
-{
- const QDockAreaLayoutInfo *info = this->info(path);
- if (info == 0)
- return QRect();
- const QList<QDockAreaLayoutItem> &item_list = info->item_list;
- Qt::Orientation o = info->o;
- int index = path.last();
- if (index < 0 || index >= item_list.count())
- return QRect();
- const QDockAreaLayoutItem &item = item_list.at(index);
- if (!(item.flags & QDockAreaLayoutItem::GapItem))
- return QRect();
-
- QRect result;
-
-#ifndef QT_NO_TABBAR
- if (info->tabbed) {
- result = info->tabContentRect();
- } else
-#endif
- {
- int pos = item.pos;
- int size = item.size;
-
- int prev = info->prev(index);
- int next = info->next(index);
-
- if (prev != -1 && !(item_list.at(prev).flags & QDockAreaLayoutItem::GapItem)) {
- pos += sep;
- size -= sep;
- }
- if (next != -1 && !(item_list.at(next).flags & QDockAreaLayoutItem::GapItem))
- size -= sep;
-
- QPoint p;
- rpick(o, p) = pos;
- rperp(o, p) = perp(o, info->rect.topLeft());
- QSize s;
- rpick(o, s) = size;
- rperp(o, s) = perp(o, info->rect.size());
-
- result = QRect(p, s);
- }
-
- return result;
-}
-
-void QDockAreaLayout::keepSize(QDockWidget *w)
-{
- QList<int> path = indexOf(w);
- if (path.isEmpty())
- return;
- QDockAreaLayoutItem &item = this->item(path);
- if (item.size != -1)
- item.flags |= QDockAreaLayoutItem::KeepSize;
-}
-
-void QDockAreaLayout::styleChangedEvent()
-{
- sep = mainWindow->style()->pixelMetric(QStyle::PM_DockWidgetSeparatorExtent, 0, mainWindow);
- fitLayout();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DOCKWIDGET
diff --git a/src/gui/widgets/qdockarealayout_p.h b/src/gui/widgets/qdockarealayout_p.h
deleted file mode 100644
index c1c8445b3d..0000000000
--- a/src/gui/widgets/qdockarealayout_p.h
+++ /dev/null
@@ -1,308 +0,0 @@
-/****************************************************************************
-**
-** 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 QDOCKAREALAYOUT_P_H
-#define QDOCKAREALAYOUT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qrect.h"
-#include "QtCore/qpair.h"
-#include "QtCore/qlist.h"
-#include "QtCore/qvector.h"
-#include "QtGui/qlayout.h"
-
-#ifndef QT_NO_DOCKWIDGET
-
-QT_BEGIN_NAMESPACE
-
-class QLayoutItem;
-class QWidget;
-class QLayoutItem;
-class QDockAreaLayoutInfo;
-class QPlaceHolderItem;
-class QDockWidget;
-class QMainWindow;
-class QWidgetAnimator;
-class QMainWindowLayout;
-struct QLayoutStruct;
-class QTabBar;
-
-// The classes in this file represent the tree structure that represents all the docks
-// Also see the wiki internal documentation
-// At the root of the tree is: QDockAreaLayout, which handles all 4 sides, so there is only one.
-// For each side it has one QDockAreaLayoutInfo child. (See QDockAreaLayout::docks.)
-// The QDockAreaLayoutInfo have QDockAreaLayoutItems as children (See QDockAreaLayoutInfo::item_list),
-// which then has one QDockAreaLayoutInfo as a child. (QDockAreaLayoutItem::subInfo) or
-// a widgetItem if this is a node of the tree (QDockAreaLayoutItem::widgetItem)
-//
-// A path indetifies uniquely one object in this tree, the first number being the side and all the following
-// indexes into the QDockAreaLayoutInfo::item_list.
-
-struct QDockAreaLayoutItem
-{
- enum ItemFlags { NoFlags = 0, GapItem = 1, KeepSize = 2 };
-
- QDockAreaLayoutItem(QLayoutItem *_widgetItem = 0);
- QDockAreaLayoutItem(QDockAreaLayoutInfo *_subinfo);
- QDockAreaLayoutItem(QPlaceHolderItem *_placeHolderItem);
- QDockAreaLayoutItem(const QDockAreaLayoutItem &other);
- ~QDockAreaLayoutItem();
-
- QDockAreaLayoutItem &operator = (const QDockAreaLayoutItem &other);
-
- bool skip() const;
- QSize minimumSize() const;
- QSize maximumSize() const;
- QSize sizeHint() const;
- bool expansive(Qt::Orientation o) const;
- bool hasFixedSize(Qt::Orientation o) const;
-
- QLayoutItem *widgetItem;
- QDockAreaLayoutInfo *subinfo;
- QPlaceHolderItem *placeHolderItem;
- int pos;
- int size;
- uint flags;
-};
-
-class Q_AUTOTEST_EXPORT QPlaceHolderItem
-{
-public:
- QPlaceHolderItem() : hidden(false), window(false) {}
- QPlaceHolderItem(QWidget *w);
-
- QString objectName;
- bool hidden, window;
- QRect topLevelRect;
-};
-
-class Q_AUTOTEST_EXPORT QDockAreaLayoutInfo
-{
-public:
- QDockAreaLayoutInfo();
- QDockAreaLayoutInfo(const int *_sep, QInternal::DockPosition _dockPos, Qt::Orientation _o,
- int tbhape, QMainWindow *window);
-
- QSize minimumSize() const;
- QSize maximumSize() const;
- QSize sizeHint() const;
- QSize size() const;
-
- bool insertGap(const QList<int> &path, QLayoutItem *dockWidgetItem);
- QLayoutItem *plug(const QList<int> &path);
- QLayoutItem *unplug(const QList<int> &path);
- enum TabMode { NoTabs, AllowTabs, ForceTabs };
- QList<int> gapIndex(const QPoint &pos, bool nestingEnabled,
- TabMode tabMode) const;
- void remove(const QList<int> &path);
- void unnest(int index);
- void split(int index, Qt::Orientation orientation, QLayoutItem *dockWidgetItem);
- void tab(int index, QLayoutItem *dockWidgetItem);
- QDockAreaLayoutItem &item(const QList<int> &path);
- QDockAreaLayoutInfo *info(const QList<int> &path);
- QDockAreaLayoutInfo *info(QWidget *widget);
-
- enum { // sentinel values used to validate state data
- SequenceMarker = 0xfc,
- TabMarker = 0xfa,
- WidgetMarker = 0xfb
- };
- void saveState(QDataStream &stream) const;
- bool restoreState(QDataStream &stream, QList<QDockWidget*> &widgets, bool testing);
-
- void fitItems();
- bool expansive(Qt::Orientation o) const;
- int changeSize(int index, int size, bool below);
- QRect itemRect(int index) const;
- QRect itemRect(const QList<int> &path) const;
- QRect separatorRect(int index) const;
- QRect separatorRect(const QList<int> &path) const;
-
- void clear();
- bool isEmpty() const;
- bool hasFixedSize() const;
- QList<int> findSeparator(const QPoint &pos) const;
- int next(int idx) const;
- int prev(int idx) const;
-
- QList<int> indexOf(QWidget *widget) const;
- QList<int> indexOfPlaceHolder(const QString &objectName) const;
-
- void apply(bool animate);
-
- void paintSeparators(QPainter *p, QWidget *widget, const QRegion &clip,
- const QPoint &mouse) const;
- QRegion separatorRegion() const;
- int separatorMove(int index, int delta);
-
- QLayoutItem *itemAt(int *x, int index) const;
- QLayoutItem *takeAt(int *x, int index);
- void deleteAllLayoutItems();
-
- QMainWindowLayout *mainWindowLayout() const;
-
- const int *sep;
- mutable QVector<QWidget*> separatorWidgets;
- QInternal::DockPosition dockPos;
- Qt::Orientation o;
- QRect rect;
- QMainWindow *mainWindow;
- QList<QDockAreaLayoutItem> item_list;
-#ifndef QT_NO_TABBAR
- void updateSeparatorWidgets() const;
- QSet<QWidget*> usedSeparatorWidgets() const;
-#endif //QT_NO_TABBAR
-
-#ifndef QT_NO_TABBAR
- quintptr currentTabId() const;
- void setCurrentTab(QWidget *widget);
- void setCurrentTabId(quintptr id);
- QRect tabContentRect() const;
- bool tabbed;
- QTabBar *tabBar;
- int tabBarShape;
-
- bool updateTabBar() const;
- void setTabBarShape(int shape);
- QSize tabBarMinimumSize() const;
- QSize tabBarSizeHint() const;
-
- QSet<QTabBar*> usedTabBars() const;
-#endif // QT_NO_TABBAR
-};
-
-class Q_AUTOTEST_EXPORT QDockAreaLayout
-{
-public:
- enum { EmptyDropAreaSize = 80 }; // when a dock area is empty, how "wide" is it?
-
- Qt::DockWidgetArea corners[4]; // use a Qt::Corner for indexing
- QRect rect;
- QLayoutItem *centralWidgetItem;
- QMainWindow *mainWindow;
- QRect centralWidgetRect;
- QDockAreaLayout(QMainWindow *win);
- QDockAreaLayoutInfo docks[4];
- int sep; // separator extent
- bool fallbackToSizeHints; //determines if we should use the sizehint for the dock areas (true until the layout is restored or the central widget is set)
- mutable QVector<QWidget*> separatorWidgets;
-
- bool isValid() const;
-
- enum { DockWidgetStateMarker = 0xfd };
- void saveState(QDataStream &stream) const;
- bool restoreState(QDataStream &stream, const QList<QDockWidget*> &widgets, bool testing = false);
-
- QList<int> indexOfPlaceHolder(const QString &objectName) const;
- QList<int> indexOf(QWidget *dockWidget) const;
- QList<int> gapIndex(const QPoint &pos) const;
- QList<int> findSeparator(const QPoint &pos) const;
-
- QDockAreaLayoutItem &item(const QList<int> &path);
- QDockAreaLayoutInfo *info(const QList<int> &path);
- const QDockAreaLayoutInfo *info(const QList<int> &path) const;
- QDockAreaLayoutInfo *info(QWidget *widget);
- QRect itemRect(const QList<int> &path) const;
- QRect separatorRect(int index) const;
- QRect separatorRect(const QList<int> &path) const;
-
- bool insertGap(const QList<int> &path, QLayoutItem *dockWidgetItem);
- QLayoutItem *plug(const QList<int> &path);
- QLayoutItem *unplug(const QList<int> &path);
- void remove(const QList<int> &path);
-
- void fitLayout();
-
- void clear();
-
- QSize sizeHint() const;
- QSize minimumSize() const;
-
- void addDockWidget(QInternal::DockPosition pos, QDockWidget *dockWidget, Qt::Orientation orientation);
- bool restoreDockWidget(QDockWidget *dockWidget);
- void splitDockWidget(QDockWidget *after, QDockWidget *dockWidget,
- Qt::Orientation orientation);
- void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
-
- void apply(bool animate);
-
- void paintSeparators(QPainter *p, QWidget *widget, const QRegion &clip,
- const QPoint &mouse) const;
- QRegion separatorRegion() const;
- int separatorMove(const QList<int> &separator, const QPoint &origin, const QPoint &dest);
-#ifndef QT_NO_TABBAR
- void updateSeparatorWidgets() const;
-#endif //QT_NO_TABBAR
-
- QLayoutItem *itemAt(int *x, int index) const;
- QLayoutItem *takeAt(int *x, int index);
- void deleteAllLayoutItems();
-
- void getGrid(QVector<QLayoutStruct> *ver_struct_list,
- QVector<QLayoutStruct> *hor_struct_list);
- void setGrid(QVector<QLayoutStruct> *ver_struct_list,
- QVector<QLayoutStruct> *hor_struct_list);
-
- QRect gapRect(const QList<int> &path) const;
-
- void keepSize(QDockWidget *w);
-#ifndef QT_NO_TABBAR
- QSet<QTabBar*> usedTabBars() const;
- QSet<QWidget*> usedSeparatorWidgets() const;
-#endif //QT_NO_TABBAR
- void styleChangedEvent();
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_QDOCKWIDGET
-
-#endif // QDOCKAREALAYOUT_P_H
diff --git a/src/gui/widgets/qdockwidget.cpp b/src/gui/widgets/qdockwidget.cpp
deleted file mode 100644
index 9d1a737cf1..0000000000
--- a/src/gui/widgets/qdockwidget.cpp
+++ /dev/null
@@ -1,1606 +0,0 @@
-/****************************************************************************
-**
-** 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 "qdockwidget.h"
-
-#ifndef QT_NO_DOCKWIDGET
-#include <qaction.h>
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <qdrawutil.h>
-#include <qevent.h>
-#include <qfontmetrics.h>
-#include <qmainwindow.h>
-#include <qrubberband.h>
-#include <qstylepainter.h>
-#include <qtoolbutton.h>
-#include <qdebug.h>
-
-#include <private/qwidgetresizehandler_p.h>
-
-#include "qdockwidget_p.h"
-#include "qmainwindowlayout_p.h"
-#ifdef Q_WS_MAC
-#include <private/qapplication_p.h>
-#include <private/qt_mac_p.h>
-#include <qmacstyle_mac.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*); // qwidget.cpp
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-static inline bool hasFeature(const QDockWidgetPrivate *priv, QDockWidget::DockWidgetFeature feature)
-{ return (priv->features & feature) == feature; }
-
-static inline bool hasFeature(const QDockWidget *dockwidget, QDockWidget::DockWidgetFeature feature)
-{ return (dockwidget->features() & feature) == feature; }
-
-
-/*
- A Dock Window:
-
- [+] is the float button
- [X] is the close button
-
- +-------------------------------+
- | Dock Window Title [+][X]|
- +-------------------------------+
- | |
- | place to put the single |
- | QDockWidget child (this space |
- | does not yet have a name) |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- +-------------------------------+
-
-*/
-
-/******************************************************************************
-** QDockWidgetTitleButton
-*/
-
-class QDockWidgetTitleButton : public QAbstractButton
-{
- Q_OBJECT
-
-public:
- QDockWidgetTitleButton(QDockWidget *dockWidget);
-
- QSize sizeHint() const;
- inline QSize minimumSizeHint() const
- { return sizeHint(); }
-
- void enterEvent(QEvent *event);
- void leaveEvent(QEvent *event);
- void paintEvent(QPaintEvent *event);
-};
-
-
-QDockWidgetTitleButton::QDockWidgetTitleButton(QDockWidget *dockWidget)
- : QAbstractButton(dockWidget)
-{
- setFocusPolicy(Qt::NoFocus);
-}
-
-QSize QDockWidgetTitleButton::sizeHint() const
-{
- ensurePolished();
-
- int size = 2*style()->pixelMetric(QStyle::PM_DockWidgetTitleBarButtonMargin, 0, this);
- if (!icon().isNull()) {
- int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this);
- QSize sz = icon().actualSize(QSize(iconSize, iconSize));
- size += qMax(sz.width(), sz.height());
- }
-
- return QSize(size, size);
-}
-
-void QDockWidgetTitleButton::enterEvent(QEvent *event)
-{
- if (isEnabled()) update();
- QAbstractButton::enterEvent(event);
-}
-
-void QDockWidgetTitleButton::leaveEvent(QEvent *event)
-{
- if (isEnabled()) update();
- QAbstractButton::leaveEvent(event);
-}
-
-void QDockWidgetTitleButton::paintEvent(QPaintEvent *)
-{
- QPainter p(this);
-
- QRect r = rect();
- QStyleOptionToolButton opt;
- opt.init(this);
- opt.state |= QStyle::State_AutoRaise;
-
- if (style()->styleHint(QStyle::SH_DockWidget_ButtonsHaveFrame, 0, this))
- {
- if (isEnabled() && underMouse() && !isChecked() && !isDown())
- opt.state |= QStyle::State_Raised;
- if (isChecked())
- opt.state |= QStyle::State_On;
- if (isDown())
- opt.state |= QStyle::State_Sunken;
- style()->drawPrimitive(QStyle::PE_PanelButtonTool, &opt, &p, this);
- }
-
- opt.icon = icon();
- opt.subControls = 0;
- opt.activeSubControls = 0;
- opt.features = QStyleOptionToolButton::None;
- opt.arrowType = Qt::NoArrow;
- int size = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this);
- opt.iconSize = QSize(size, size);
- style()->drawComplexControl(QStyle::CC_ToolButton, &opt, &p, this);
-}
-
-/******************************************************************************
-** QDockWidgetLayout
-*/
-
-QDockWidgetLayout::QDockWidgetLayout(QWidget *parent)
- : QLayout(parent), verticalTitleBar(false), item_list(RoleCount, 0)
-{
-}
-
-QDockWidgetLayout::~QDockWidgetLayout()
-{
- qDeleteAll(item_list);
-}
-
-bool QDockWidgetLayout::nativeWindowDeco() const
-{
- return nativeWindowDeco(parentWidget()->isWindow());
-}
-
-bool QDockWidgetLayout::nativeWindowDeco(bool floating) const
-{
-#if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_WINCE)
- Q_UNUSED(floating);
- return false;
-#else
- return floating && item_list[QDockWidgetLayout::TitleBar] == 0;
-#endif
-}
-
-
-void QDockWidgetLayout::addItem(QLayoutItem*)
-{
- qWarning() << "QDockWidgetLayout::addItem(): please use QDockWidgetLayout::setWidget()";
- return;
-}
-
-QLayoutItem *QDockWidgetLayout::itemAt(int index) const
-{
- int cnt = 0;
- for (int i = 0; i < item_list.count(); ++i) {
- QLayoutItem *item = item_list.at(i);
- if (item == 0)
- continue;
- if (index == cnt++)
- return item;
- }
- return 0;
-}
-
-QLayoutItem *QDockWidgetLayout::takeAt(int index)
-{
- int j = 0;
- for (int i = 0; i < item_list.count(); ++i) {
- QLayoutItem *item = item_list.at(i);
- if (item == 0)
- continue;
- if (index == j) {
- item_list[i] = 0;
- invalidate();
- return item;
- }
- ++j;
- }
- return 0;
-}
-
-int QDockWidgetLayout::count() const
-{
- int result = 0;
- for (int i = 0; i < item_list.count(); ++i) {
- if (item_list.at(i))
- ++result;
- }
- return result;
-}
-
-QSize QDockWidgetLayout::sizeFromContent(const QSize &content, bool floating) const
-{
- QSize result = content;
-
- if (verticalTitleBar) {
- result.setHeight(qMax(result.height(), minimumTitleWidth()));
- result.setWidth(qMax(content.width(), 0));
- } else {
- result.setHeight(qMax(result.height(), 0));
- result.setWidth(qMax(content.width(), minimumTitleWidth()));
- }
-
- QDockWidget *w = qobject_cast<QDockWidget*>(parentWidget());
- const bool nativeDeco = nativeWindowDeco(floating);
-
- int fw = floating && !nativeDeco
- ? w->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, w)
- : 0;
-
- const int th = titleHeight();
- if (!nativeDeco) {
- if (verticalTitleBar)
- result += QSize(th + 2*fw, 2*fw);
- else
- result += QSize(2*fw, th + 2*fw);
- }
-
- result.setHeight(qMin(result.height(), (int) QWIDGETSIZE_MAX));
- result.setWidth(qMin(result.width(), (int) QWIDGETSIZE_MAX));
-
- if (content.width() < 0)
- result.setWidth(-1);
- if (content.height() < 0)
- result.setHeight(-1);
-
- int left, top, right, bottom;
- w->getContentsMargins(&left, &top, &right, &bottom);
- //we need to substract the contents margin (it will be added by the caller)
- QSize min = w->minimumSize() - QSize(left + right, top + bottom);
- QSize max = w->maximumSize() - QSize(left + right, top + bottom);
-
- /* A floating dockwidget will automatically get its minimumSize set to the layout's
- minimum size + deco. We're *not* interested in this, we only take minimumSize()
- into account if the user set it herself. Otherwise we end up expanding the result
- of a calculation for a non-floating dock widget to a floating dock widget's
- minimum size + window decorations. */
-
- uint explicitMin = 0;
- uint explicitMax = 0;
- if (w->d_func()->extra != 0) {
- explicitMin = w->d_func()->extra->explicitMinSize;
- explicitMax = w->d_func()->extra->explicitMaxSize;
- }
-
- if (!(explicitMin & Qt::Horizontal) || min.width() == 0)
- min.setWidth(-1);
- if (!(explicitMin & Qt::Vertical) || min.height() == 0)
- min.setHeight(-1);
-
- if (!(explicitMax & Qt::Horizontal))
- max.setWidth(QWIDGETSIZE_MAX);
- if (!(explicitMax & Qt::Vertical))
- max.setHeight(QWIDGETSIZE_MAX);
-
- return result.boundedTo(max).expandedTo(min);
-}
-
-QSize QDockWidgetLayout::sizeHint() const
-{
- QDockWidget *w = qobject_cast<QDockWidget*>(parentWidget());
-
- QSize content(-1, -1);
- if (item_list[Content] != 0)
- content = item_list[Content]->sizeHint();
-
- return sizeFromContent(content, w->isFloating());
-}
-
-QSize QDockWidgetLayout::maximumSize() const
-{
- if (item_list[Content] != 0) {
- const QSize content = item_list[Content]->maximumSize();
- return sizeFromContent(content, parentWidget()->isWindow());
- } else {
- return parentWidget()->maximumSize();
- }
-
-}
-
-QSize QDockWidgetLayout::minimumSize() const
-{
- QDockWidget *w = qobject_cast<QDockWidget*>(parentWidget());
-
- QSize content(0, 0);
- if (item_list[Content] != 0)
- content = item_list[Content]->minimumSize();
-
- return sizeFromContent(content, w->isFloating());
-}
-
-QWidget *QDockWidgetLayout::widgetForRole(Role r) const
-{
- QLayoutItem *item = item_list.at(r);
- return item == 0 ? 0 : item->widget();
-}
-
-QLayoutItem *QDockWidgetLayout::itemForRole(Role r) const
-{
- return item_list.at(r);
-}
-
-void QDockWidgetLayout::setWidgetForRole(Role r, QWidget *w)
-{
- QWidget *old = widgetForRole(r);
- if (old != 0) {
- old->hide();
- removeWidget(old);
- }
-
- if (w != 0) {
- addChildWidget(w);
- item_list[r] = new QWidgetItemV2(w);
- w->show();
- } else {
- item_list[r] = 0;
- }
-
- invalidate();
-}
-
-static inline int pick(bool vertical, const QSize &size)
-{
- return vertical ? size.height() : size.width();
-}
-
-static inline int perp(bool vertical, const QSize &size)
-{
- return vertical ? size.width() : size.height();
-}
-
-int QDockWidgetLayout::minimumTitleWidth() const
-{
- QDockWidget *q = qobject_cast<QDockWidget*>(parentWidget());
-
- if (QWidget *title = widgetForRole(TitleBar))
- return pick(verticalTitleBar, title->minimumSizeHint());
-
- QSize closeSize(0, 0);
- QSize floatSize(0, 0);
- if (hasFeature(q, QDockWidget::DockWidgetClosable)) {
- if (QLayoutItem *item = item_list[CloseButton])
- closeSize = item->widget()->sizeHint();
- }
- if (hasFeature(q, QDockWidget::DockWidgetFloatable)) {
- if (QLayoutItem *item = item_list[FloatButton])
- floatSize = item->widget()->sizeHint();
- }
-
- int titleHeight = this->titleHeight();
-
- int mw = q->style()->pixelMetric(QStyle::PM_DockWidgetTitleMargin, 0, q);
- int fw = q->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, q);
-
- return pick(verticalTitleBar, closeSize)
- + pick(verticalTitleBar, floatSize)
- + titleHeight + 2*fw + 3*mw;
-}
-
-int QDockWidgetLayout::titleHeight() const
-{
- QDockWidget *q = qobject_cast<QDockWidget*>(parentWidget());
-
- if (QWidget *title = widgetForRole(TitleBar))
- return perp(verticalTitleBar, title->sizeHint());
-
- QSize closeSize(0, 0);
- QSize floatSize(0, 0);
- if (QLayoutItem *item = item_list[CloseButton])
- closeSize = item->widget()->sizeHint();
- if (QLayoutItem *item = item_list[FloatButton])
- floatSize = item->widget()->sizeHint();
-
- int buttonHeight = qMax(perp(verticalTitleBar, closeSize),
- perp(verticalTitleBar, floatSize));
-
- QFontMetrics titleFontMetrics = q->fontMetrics();
-#ifdef Q_WS_MAC
- if (qobject_cast<QMacStyle *>(q->style())) {
- //### this breaks on proxy styles. (But is this code still called?)
- QFont font = qt_app_fonts_hash()->value("QToolButton", q->font());
- titleFontMetrics = QFontMetrics(font);
- }
-#endif
-
- int mw = q->style()->pixelMetric(QStyle::PM_DockWidgetTitleMargin, 0, q);
-
- return qMax(buttonHeight + 2, titleFontMetrics.height() + 2*mw);
-}
-
-void QDockWidgetLayout::setGeometry(const QRect &geometry)
-{
- QDockWidget *q = qobject_cast<QDockWidget*>(parentWidget());
-
- bool nativeDeco = nativeWindowDeco();
-
- int fw = q->isFloating() && !nativeDeco
- ? q->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, q)
- : 0;
-
- if (nativeDeco) {
- if (QLayoutItem *item = item_list[Content])
- item->setGeometry(geometry);
- } else {
- int titleHeight = this->titleHeight();
-
- if (verticalTitleBar) {
- _titleArea = QRect(QPoint(fw, fw),
- QSize(titleHeight, geometry.height() - (fw * 2)));
- } else {
- _titleArea = QRect(QPoint(fw, fw),
- QSize(geometry.width() - (fw * 2), titleHeight));
- }
-
- if (QLayoutItem *item = item_list[TitleBar]) {
- item->setGeometry(_titleArea);
- } else {
- QStyleOptionDockWidgetV2 opt;
- q->initStyleOption(&opt);
-
- if (QLayoutItem *item = item_list[CloseButton]) {
- if (!item->isEmpty()) {
- QRect r = q->style()
- ->subElementRect(QStyle::SE_DockWidgetCloseButton,
- &opt, q);
- if (!r.isNull())
- item->setGeometry(r);
- }
- }
-
- if (QLayoutItem *item = item_list[FloatButton]) {
- if (!item->isEmpty()) {
- QRect r = q->style()
- ->subElementRect(QStyle::SE_DockWidgetFloatButton,
- &opt, q);
- if (!r.isNull())
- item->setGeometry(r);
- }
- }
- }
-
- if (QLayoutItem *item = item_list[Content]) {
- QRect r = geometry;
- if (verticalTitleBar) {
- r.setLeft(_titleArea.right() + 1);
- r.adjust(0, fw, -fw, -fw);
- } else {
- r.setTop(_titleArea.bottom() + 1);
- r.adjust(fw, 0, -fw, -fw);
- }
- item->setGeometry(r);
- }
- }
-}
-
-void QDockWidgetLayout::setVerticalTitleBar(bool b)
-{
- if (b == verticalTitleBar)
- return;
- verticalTitleBar = b;
- invalidate();
- parentWidget()->update();
-}
-
-/******************************************************************************
-** QDockWidgetItem
-*/
-
-QDockWidgetItem::QDockWidgetItem(QDockWidget *dockWidget)
- : QWidgetItem(dockWidget)
-{
-}
-
-QSize QDockWidgetItem::minimumSize() const
-{
- QSize widgetMin(0, 0);
- if (QLayoutItem *item = dockWidgetChildItem())
- widgetMin = item->minimumSize();
- return dockWidgetLayout()->sizeFromContent(widgetMin, false);
-}
-
-QSize QDockWidgetItem::maximumSize() const
-{
- if (QLayoutItem *item = dockWidgetChildItem()) {
- return dockWidgetLayout()->sizeFromContent(item->maximumSize(), false);
- } else {
- return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
- }
-}
-
-
-QSize QDockWidgetItem::sizeHint() const
-{
- if (QLayoutItem *item = dockWidgetChildItem()) {
- return dockWidgetLayout()->sizeFromContent(item->sizeHint(), false);
- } else {
- return QWidgetItem::sizeHint();
- }
-}
-
-/******************************************************************************
-** QDockWidgetPrivate
-*/
-
-void QDockWidgetPrivate::init()
-{
- Q_Q(QDockWidget);
-
- QDockWidgetLayout *layout = new QDockWidgetLayout(q);
- layout->setSizeConstraint(QLayout::SetMinAndMaxSize);
-
- QAbstractButton *button = new QDockWidgetTitleButton(q);
- button->setObjectName(QLatin1String("qt_dockwidget_floatbutton"));
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_toggleTopLevel()));
- layout->setWidgetForRole(QDockWidgetLayout::FloatButton, button);
-
- button = new QDockWidgetTitleButton(q);
- button->setObjectName(QLatin1String("qt_dockwidget_closebutton"));
- QObject::connect(button, SIGNAL(clicked()), q, SLOT(close()));
- layout->setWidgetForRole(QDockWidgetLayout::CloseButton, button);
-
- resizer = new QWidgetResizeHandler(q);
- resizer->setMovingEnabled(false);
- resizer->setActive(false);
-
-#ifndef QT_NO_ACTION
- toggleViewAction = new QAction(q);
- toggleViewAction->setCheckable(true);
- fixedWindowTitle = qt_setWindowTitle_helperHelper(q->windowTitle(), q);
- toggleViewAction->setText(fixedWindowTitle);
- QObject::connect(toggleViewAction, SIGNAL(triggered(bool)),
- q, SLOT(_q_toggleView(bool)));
-#endif
-
- updateButtons();
-}
-
-/*!
- Initialize \a option with the values from this QDockWidget. This method
- is useful for subclasses when they need a QStyleOptionDockWidget, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QDockWidget::initStyleOption(QStyleOptionDockWidget *option) const
-{
- Q_D(const QDockWidget);
-
- if (!option)
- return;
- QDockWidgetLayout *dwlayout = qobject_cast<QDockWidgetLayout*>(layout());
-
- option->initFrom(this);
- option->rect = dwlayout->titleArea();
- option->title = d->fixedWindowTitle;
- option->closable = hasFeature(this, QDockWidget::DockWidgetClosable);
- option->movable = hasFeature(this, QDockWidget::DockWidgetMovable);
- option->floatable = hasFeature(this, QDockWidget::DockWidgetFloatable);
-
- QDockWidgetLayout *l = qobject_cast<QDockWidgetLayout*>(layout());
- QStyleOptionDockWidgetV2 *v2
- = qstyleoption_cast<QStyleOptionDockWidgetV2*>(option);
- if (v2 != 0)
- v2->verticalTitleBar = l->verticalTitleBar;
-}
-
-void QDockWidgetPrivate::_q_toggleView(bool b)
-{
- Q_Q(QDockWidget);
- if (b == q->isHidden()) {
- if (b)
- q->show();
- else
- q->close();
- }
-}
-
-void QDockWidgetPrivate::updateButtons()
-{
- Q_Q(QDockWidget);
- QDockWidgetLayout *dwLayout = qobject_cast<QDockWidgetLayout*>(layout);
-
- QStyleOptionDockWidget opt;
- q->initStyleOption(&opt);
-
- bool customTitleBar = dwLayout->widgetForRole(QDockWidgetLayout::TitleBar) != 0;
- bool nativeDeco = dwLayout->nativeWindowDeco();
- bool hideButtons = nativeDeco || customTitleBar;
-
- bool canClose = hasFeature(this, QDockWidget::DockWidgetClosable);
- bool canFloat = hasFeature(this, QDockWidget::DockWidgetFloatable);
-
- QAbstractButton *button
- = qobject_cast<QAbstractButton*>(dwLayout->widgetForRole(QDockWidgetLayout::FloatButton));
- button->setIcon(q->style()->standardIcon(QStyle::SP_TitleBarNormalButton, &opt, q));
- button->setVisible(canFloat && !hideButtons);
-
- button
- = qobject_cast <QAbstractButton*>(dwLayout->widgetForRole(QDockWidgetLayout::CloseButton));
- button->setIcon(q->style()->standardIcon(QStyle::SP_TitleBarCloseButton, &opt, q));
- button->setVisible(canClose && !hideButtons);
-
- q->setAttribute(Qt::WA_ContentsPropagated,
- (canFloat || canClose) && !hideButtons);
-
- layout->invalidate();
-}
-
-void QDockWidgetPrivate::_q_toggleTopLevel()
-{
- Q_Q(QDockWidget);
- q->setFloating(!q->isFloating());
-}
-
-void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca)
-{
- if (state != 0)
- return;
-
- QMainWindow *win = qobject_cast<QMainWindow*>(parent);
- Q_ASSERT(win != 0);
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
- Q_ASSERT(layout != 0);
- if (layout->pluggingWidget != 0) // the main window is animating a docking operation
- return;
-
- state = new QDockWidgetPrivate::DragState;
- state->pressPos = pos;
- state->dragging = false;
- state->widgetItem = 0;
- state->ownWidgetItem = false;
- state->nca = nca;
- state->ctrlDrag = false;
-}
-
-void QDockWidgetPrivate::startDrag()
-{
- Q_Q(QDockWidget);
-
- if (state == 0 || state->dragging)
- return;
-
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- Q_ASSERT(layout != 0);
-
- state->widgetItem = layout->unplug(q);
- if (state->widgetItem == 0) {
- /* I have a QMainWindow parent, but I was never inserted with
- QMainWindow::addDockWidget, so the QMainWindowLayout has no
- widget item for me. :( I have to create it myself, and then
- delete it if I don't get dropped into a dock area. */
- state->widgetItem = new QDockWidgetItem(q);
- state->ownWidgetItem = true;
- }
-
- if (state->ctrlDrag)
- layout->restore();
-
- state->dragging = true;
-}
-
-void QDockWidgetPrivate::endDrag(bool abort)
-{
- Q_Q(QDockWidget);
- Q_ASSERT(state != 0);
-
- q->releaseMouse();
-
- if (state->dragging) {
- QMainWindowLayout *mwLayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- Q_ASSERT(mwLayout != 0);
-
- if (abort || !mwLayout->plug(state->widgetItem)) {
- if (hasFeature(this, QDockWidget::DockWidgetFloatable)) {
- if (state->ownWidgetItem)
- delete state->widgetItem;
- mwLayout->restore();
-#ifdef Q_WS_X11
- // get rid of the X11BypassWindowManager window flag and activate the resizer
- Qt::WindowFlags flags = q->windowFlags();
- flags &= ~Qt::X11BypassWindowManagerHint;
- q->setWindowFlags(flags);
- resizer->setActive(QWidgetResizeHandler::Resize, true);
- q->show();
-#else
- QDockWidgetLayout *myLayout
- = qobject_cast<QDockWidgetLayout*>(layout);
- resizer->setActive(QWidgetResizeHandler::Resize,
- myLayout->widgetForRole(QDockWidgetLayout::TitleBar) != 0);
-#endif
- undockedGeometry = q->geometry();
- q->activateWindow();
- } else {
- mwLayout->revert(state->widgetItem);
- }
- }
- }
- delete state;
- state = 0;
-}
-
-bool QDockWidgetPrivate::isAnimating() const
-{
- Q_Q(const QDockWidget);
-
- QMainWindow *mainWin = qobject_cast<QMainWindow*>(parent);
- if (mainWin == 0)
- return false;
-
- QMainWindowLayout *mainWinLayout = qt_mainwindow_layout(mainWin);
- if (mainWinLayout == 0)
- return false;
-
- return (void*)mainWinLayout->pluggingWidget == (void*)q;
-}
-
-bool QDockWidgetPrivate::mousePressEvent(QMouseEvent *event)
-{
-#if !defined(QT_NO_MAINWINDOW)
- Q_Q(QDockWidget);
-
- QDockWidgetLayout *dwLayout
- = qobject_cast<QDockWidgetLayout*>(layout);
-
- if (!dwLayout->nativeWindowDeco()) {
- QRect titleArea = dwLayout->titleArea();
-
- if (event->button() != Qt::LeftButton ||
- !titleArea.contains(event->pos()) ||
- // check if the tool window is movable... do nothing if it
- // is not (but allow moving if the window is floating)
- (!hasFeature(this, QDockWidget::DockWidgetMovable) && !q->isFloating()) ||
- qobject_cast<QMainWindow*>(parent) == 0 ||
- isAnimating() || state != 0) {
- return false;
- }
-
- initDrag(event->pos(), false);
-
- if (state)
- state->ctrlDrag = hasFeature(this, QDockWidget::DockWidgetFloatable) && event->modifiers() & Qt::ControlModifier;
-
- return true;
- }
-
-#endif // !defined(QT_NO_MAINWINDOW)
- return false;
-}
-
-bool QDockWidgetPrivate::mouseDoubleClickEvent(QMouseEvent *event)
-{
- QDockWidgetLayout *dwLayout = qobject_cast<QDockWidgetLayout*>(layout);
-
- if (!dwLayout->nativeWindowDeco()) {
- QRect titleArea = dwLayout->titleArea();
-
- if (event->button() == Qt::LeftButton && titleArea.contains(event->pos()) &&
- hasFeature(this, QDockWidget::DockWidgetFloatable)) {
- _q_toggleTopLevel();
- return true;
- }
- }
- return false;
-}
-
-bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
-{
- bool ret = false;
-#if !defined(QT_NO_MAINWINDOW)
- Q_Q(QDockWidget);
-
- if (!state)
- return ret;
-
- QDockWidgetLayout *dwlayout
- = qobject_cast<QDockWidgetLayout *>(layout);
- QMainWindowLayout *mwlayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- if (!dwlayout->nativeWindowDeco()) {
- if (!state->dragging
- && mwlayout->pluggingWidget == 0
- && (event->pos() - state->pressPos).manhattanLength()
- > QApplication::startDragDistance()) {
- startDrag();
-#ifdef Q_OS_WIN
- grabMouseWhileInWindow();
-#else
- q->grabMouse();
-#endif
- ret = true;
- }
- }
-
- if (state->dragging && !state->nca) {
- QPoint pos = event->globalPos() - state->pressPos;
- q->move(pos);
-
- if (!state->ctrlDrag)
- mwlayout->hover(state->widgetItem, event->globalPos());
-
- ret = true;
- }
-
-#endif // !defined(QT_NO_MAINWINDOW)
- return ret;
-}
-
-bool QDockWidgetPrivate::mouseReleaseEvent(QMouseEvent *event)
-{
-#if !defined(QT_NO_MAINWINDOW)
-
- if (event->button() == Qt::LeftButton && state && !state->nca) {
- endDrag();
- return true; //filter out the event
- }
-
-#endif // !defined(QT_NO_MAINWINDOW)
- return false;
-}
-
-void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
-{
- Q_Q(QDockWidget);
-
- int fw = q->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, q);
-
- QRect geo = q->geometry();
- QRect titleRect = q->frameGeometry();
-#ifdef Q_WS_MAC
- if ((features & QDockWidget::DockWidgetVerticalTitleBar)) {
- titleRect.setTop(geo.top());
- titleRect.setBottom(geo.bottom());
- titleRect.setRight(geo.left() - 1);
- } else
-#endif
- {
- titleRect.setLeft(geo.left());
- titleRect.setRight(geo.right());
- titleRect.setBottom(geo.top() - 1);
- titleRect.adjust(0, fw, 0, 0);
- }
-
- switch (event->type()) {
- case QEvent::NonClientAreaMouseButtonPress:
- if (!titleRect.contains(event->globalPos()))
- break;
- if (state != 0)
- break;
- if (qobject_cast<QMainWindow*>(parent) == 0)
- break;
- if (isAnimating())
- break;
- initDrag(event->pos(), true);
- if (state == 0)
- break;
-#ifdef Q_OS_WIN
- // On Windows, NCA mouse events don't contain modifier info
- state->ctrlDrag = GetKeyState(VK_CONTROL) & 0x8000;
-#else
- state->ctrlDrag = event->modifiers() & Qt::ControlModifier;
-#endif
- startDrag();
- break;
- case QEvent::NonClientAreaMouseMove:
- if (state == 0 || !state->dragging)
- break;
- if (state->nca) {
- endDrag();
- }
-#ifdef Q_OS_MAC
- else { // workaround for lack of mouse-grab on Mac
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- Q_ASSERT(layout != 0);
-
- q->move(event->globalPos() - state->pressPos);
- if (!state->ctrlDrag)
- layout->hover(state->widgetItem, event->globalPos());
- }
-#endif
- break;
- case QEvent::NonClientAreaMouseButtonRelease:
-#ifdef Q_OS_MAC
- if (state)
- endDrag();
-#endif
- break;
- case QEvent::NonClientAreaMouseButtonDblClick:
- _q_toggleTopLevel();
- break;
- default:
- break;
- }
-}
-
-void QDockWidgetPrivate::moveEvent(QMoveEvent *event)
-{
- Q_Q(QDockWidget);
-
- if (state == 0 || !state->dragging || !state->nca || !q->isWindow())
- return;
-
- // When the native window frame is being dragged, all we get is these mouse
- // move events.
-
- if (state->ctrlDrag)
- return;
-
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- Q_ASSERT(layout != 0);
-
- QPoint globalMousePos = event->pos() + state->pressPos;
- layout->hover(state->widgetItem, globalMousePos);
-}
-
-void QDockWidgetPrivate::unplug(const QRect &rect)
-{
- Q_Q(QDockWidget);
- QRect r = rect;
- r.moveTopLeft(q->mapToGlobal(QPoint(0, 0)));
- QDockWidgetLayout *dwLayout = qobject_cast<QDockWidgetLayout*>(layout);
- if (dwLayout->nativeWindowDeco(true))
- r.adjust(0, dwLayout->titleHeight(), 0, 0);
- setWindowState(true, true, r);
-}
-
-void QDockWidgetPrivate::plug(const QRect &rect)
-{
- setWindowState(false, false, rect);
-}
-
-void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect &rect)
-{
- Q_Q(QDockWidget);
-
- if (!floating && parent) {
- QMainWindowLayout *mwlayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- if (mwlayout && mwlayout->dockWidgetArea(q) == Qt::NoDockWidgetArea)
- return; // this dockwidget can't be redocked
- }
-
- bool wasFloating = q->isFloating();
- bool hidden = q->isHidden();
-
- if (q->isVisible())
- q->hide();
-
- Qt::WindowFlags flags = floating ? Qt::Tool : Qt::Widget;
-
- QDockWidgetLayout *dwLayout = qobject_cast<QDockWidgetLayout*>(layout);
- const bool nativeDeco = dwLayout->nativeWindowDeco(floating);
-
- if (nativeDeco) {
- flags |= Qt::CustomizeWindowHint | Qt::WindowTitleHint;
- if (hasFeature(this, QDockWidget::DockWidgetClosable))
- flags |= Qt::WindowCloseButtonHint;
- } else {
- flags |= Qt::FramelessWindowHint;
- }
-
- if (unplug)
- flags |= Qt::X11BypassWindowManagerHint;
-
- q->setWindowFlags(flags);
-
-#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
- if (floating && nativeDeco && (q->features() & QDockWidget::DockWidgetVerticalTitleBar)) {
- ChangeWindowAttributes(HIViewGetWindow(HIViewRef(q->winId())), kWindowSideTitlebarAttribute, 0);
- }
-#endif
-
- if (!rect.isNull())
- q->setGeometry(rect);
-
- updateButtons();
-
- if (!hidden)
- q->show();
-
- if (floating != wasFloating) {
- emit q->topLevelChanged(floating);
- if (!floating && parent) {
- QMainWindowLayout *mwlayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- if (mwlayout)
- emit q->dockLocationChanged(mwlayout->dockWidgetArea(q));
- }
- }
-
- resizer->setActive(QWidgetResizeHandler::Resize, !unplug && floating && !nativeDeco);
-}
-
-/*!
- \class QDockWidget
-
- \brief The QDockWidget class provides a widget that can be docked
- inside a QMainWindow or floated as a top-level window on the
- desktop.
-
- \ingroup mainwindow-classes
-
- QDockWidget provides the concept of dock widgets, also know as
- tool palettes or utility windows. Dock windows are secondary
- windows placed in the \e {dock widget area} around the
- \l{QMainWindow::centralWidget()}{central widget} in a
- QMainWindow.
-
- \image mainwindow-docks.png
-
- Dock windows can be moved inside their current area, moved into
- new areas and floated (e.g., undocked) by the end-user. The
- QDockWidget API allows the programmer to restrict the dock widgets
- ability to move, float and close, as well as the areas in which
- they can be placed.
-
- \section1 Appearance
-
- A QDockWidget consists of a title bar and the content area. The
- title bar displays the dock widgets \link QWidget::windowTitle()
- window title\endlink, a \e float button and a \e close button.
- Depending on the state of the QDockWidget, the \e float and \e
- close buttons may be either disabled or not shown at all.
-
- The visual appearance of the title bar and buttons is dependent
- on the \l{QStyle}{style} in use.
-
- A QDockWidget acts as a wrapper for its child widget, set with setWidget().
- Custom size hints, minimum and maximum sizes and size policies should be
- implemented in the child widget. QDockWidget will respect them, adjusting
- its own constraints to include the frame and title. Size constraints
- should not be set on the QDockWidget itself, because they change depending
- on whether it is docked; a docked QDockWidget has no frame and a smaller title
- bar.
-
- \sa QMainWindow, {Dock Widgets Example}
-*/
-
-/*!
- \enum QDockWidget::DockWidgetFeature
-
- \value DockWidgetClosable The dock widget can be closed. On some systems the dock
- widget always has a close button when it's floating
- (for example on MacOS 10.5).
- \value DockWidgetMovable The dock widget can be moved between docks
- by the user.
- \value DockWidgetFloatable The dock widget can be detached from the
- main window, and floated as an independent
- window.
- \value DockWidgetVerticalTitleBar The dock widget displays a vertical title
- bar on its left side. This can be used to
- increase the amount of vertical space in
- a QMainWindow.
- \value AllDockWidgetFeatures (Deprecated) The dock widget can be closed, moved,
- and floated. Since new features might be added in future
- releases, the look and behavior of dock widgets might
- change if you use this flag. Please specify individual
- flags instead.
- \value NoDockWidgetFeatures The dock widget cannot be closed, moved,
- or floated.
-
- \omitvalue DockWidgetFeatureMask
- \omitvalue Reserved
-*/
-
-/*!
- \property QDockWidget::windowTitle
- \brief the dock widget title (caption)
-
- By default, this property contains an empty string.
-*/
-
-/*!
- Constructs a QDockWidget with parent \a parent and window flags \a
- flags. The dock widget will be placed in the left dock widget
- area.
-*/
-QDockWidget::QDockWidget(QWidget *parent, Qt::WindowFlags flags)
- : QWidget(*new QDockWidgetPrivate, parent, flags)
-{
- Q_D(QDockWidget);
- d->init();
-}
-
-/*!
- Constructs a QDockWidget with parent \a parent and window flags \a
- flags. The dock widget will be placed in the left dock widget
- area.
-
- The window title is set to \a title. This title is used when the
- QDockWidget is docked and undocked. It is also used in the context
- menu provided by QMainWindow.
-
- \sa setWindowTitle()
-*/
-QDockWidget::QDockWidget(const QString &title, QWidget *parent, Qt::WindowFlags flags)
- : QWidget(*new QDockWidgetPrivate, parent, flags)
-{
- Q_D(QDockWidget);
- d->init();
- setWindowTitle(title);
-}
-
-/*!
- Destroys the dock widget.
-*/
-QDockWidget::~QDockWidget()
-{ }
-
-/*!
- Returns the widget for the dock widget. This function returns zero
- if the widget has not been set.
-
- \sa setWidget()
-*/
-QWidget *QDockWidget::widget() const
-{
- QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(this->layout());
- return layout->widgetForRole(QDockWidgetLayout::Content);
-}
-
-/*!
- Sets the widget for the dock widget to \a widget.
-
- If the dock widget is visible when \a widget is added, you must
- \l{QWidget::}{show()} it explicitly.
-
- Note that you must add the layout of the \a widget before you call
- this function; if not, the \a widget will not be visible.
-
- \sa widget()
-*/
-void QDockWidget::setWidget(QWidget *widget)
-{
- QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(this->layout());
- layout->setWidgetForRole(QDockWidgetLayout::Content, widget);
-}
-
-/*!
- \property QDockWidget::features
- \brief whether the dock widget is movable, closable, and floatable
-
- By default, this property is set to a combination of DockWidgetClosable,
- DockWidgetMovable and DockWidgetFloatable.
-
- \sa DockWidgetFeature
-*/
-
-void QDockWidget::setFeatures(QDockWidget::DockWidgetFeatures features)
-{
- Q_D(QDockWidget);
- features &= DockWidgetFeatureMask;
- if (d->features == features)
- return;
- const bool closableChanged = (d->features ^ features) & DockWidgetClosable;
- d->features = features;
- QDockWidgetLayout *layout
- = qobject_cast<QDockWidgetLayout*>(this->layout());
- layout->setVerticalTitleBar(features & DockWidgetVerticalTitleBar);
- d->updateButtons();
- d->toggleViewAction->setEnabled((d->features & DockWidgetClosable) == DockWidgetClosable);
- emit featuresChanged(d->features);
- update();
- if (closableChanged && layout->nativeWindowDeco()) {
- //this ensures the native decoration is drawn
- d->setWindowState(true /*floating*/, true /*unplug*/);
- }
-}
-
-QDockWidget::DockWidgetFeatures QDockWidget::features() const
-{
- Q_D(const QDockWidget);
- return d->features;
-}
-
-/*!
- \property QDockWidget::floating
- \brief whether the dock widget is floating
-
- A floating dock widget is presented to the user as an independent
- window "on top" of its parent QMainWindow, instead of being
- docked in the QMainWindow.
-
- By default, this property is true.
-
- \sa isWindow()
-*/
-void QDockWidget::setFloating(bool floating)
-{
- Q_D(QDockWidget);
-
- // the initial click of a double-click may have started a drag...
- if (d->state != 0)
- d->endDrag(true);
-
- QRect r = d->undockedGeometry;
-
- d->setWindowState(floating, false, floating ? r : QRect());
-
- if (floating && r.isNull()) {
- if (x() < 0 || y() < 0) //may happen if we have been hidden
- move(QPoint());
- setAttribute(Qt::WA_Moved, false); //we want it at the default position
- }
-}
-
-/*!
- \property QDockWidget::allowedAreas
- \brief areas where the dock widget may be placed
-
- The default is Qt::AllDockWidgetAreas.
-
- \sa Qt::DockWidgetArea
-*/
-
-void QDockWidget::setAllowedAreas(Qt::DockWidgetAreas areas)
-{
- Q_D(QDockWidget);
- areas &= Qt::DockWidgetArea_Mask;
- if (areas == d->allowedAreas)
- return;
- d->allowedAreas = areas;
- emit allowedAreasChanged(d->allowedAreas);
-}
-
-Qt::DockWidgetAreas QDockWidget::allowedAreas() const
-{
- Q_D(const QDockWidget);
- return d->allowedAreas;
-}
-
-/*!
- \fn bool QDockWidget::isAreaAllowed(Qt::DockWidgetArea area) const
-
- Returns true if this dock widget can be placed in the given \a area;
- otherwise returns false.
-*/
-
-/*! \reimp */
-void QDockWidget::changeEvent(QEvent *event)
-{
- Q_D(QDockWidget);
- QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(this->layout());
-
- switch (event->type()) {
- case QEvent::ModifiedChange:
- case QEvent::WindowTitleChange:
- update(layout->titleArea());
-#ifndef QT_NO_ACTION
- d->fixedWindowTitle = qt_setWindowTitle_helperHelper(windowTitle(), this);
- d->toggleViewAction->setText(d->fixedWindowTitle);
-#endif
-#ifndef QT_NO_TABBAR
- {
- QMainWindow *win = qobject_cast<QMainWindow*>(parentWidget());
- if (QMainWindowLayout *winLayout = qt_mainwindow_layout(win)) {
- if (QDockAreaLayoutInfo *info = winLayout->layoutState.dockAreaLayout.info(this))
- info->updateTabBar();
- }
- }
-#endif // QT_NO_TABBAR
- break;
- default:
- break;
- }
- QWidget::changeEvent(event);
-}
-
-/*! \reimp */
-void QDockWidget::closeEvent(QCloseEvent *event)
-{
- Q_D(QDockWidget);
- if (d->state)
- d->endDrag(true);
- QWidget::closeEvent(event);
-}
-
-/*! \reimp */
-void QDockWidget::paintEvent(QPaintEvent *event)
-{
- Q_UNUSED(event)
-
- QDockWidgetLayout *layout
- = qobject_cast<QDockWidgetLayout*>(this->layout());
- bool customTitleBar = layout->widgetForRole(QDockWidgetLayout::TitleBar) != 0;
- bool nativeDeco = layout->nativeWindowDeco();
-
- if (!nativeDeco && !customTitleBar) {
- QStylePainter p(this);
- // ### Add PixelMetric to change spacers, so style may show border
- // when not floating.
- if (isFloating()) {
- QStyleOptionFrame framOpt;
- framOpt.init(this);
- p.drawPrimitive(QStyle::PE_FrameDockWidget, framOpt);
- }
-
- // Title must be painted after the frame, since the areas overlap, and
- // the title may wish to extend out to all sides (eg. XP style)
- QStyleOptionDockWidgetV2 titleOpt;
- initStyleOption(&titleOpt);
- p.drawControl(QStyle::CE_DockWidgetTitle, titleOpt);
- }
-}
-
-/*! \reimp */
-bool QDockWidget::event(QEvent *event)
-{
- Q_D(QDockWidget);
-
- QMainWindow *win = qobject_cast<QMainWindow*>(parentWidget());
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
-
- switch (event->type()) {
-#ifndef QT_NO_ACTION
- case QEvent::Hide:
- if (layout != 0)
- layout->keepSize(this);
- d->toggleViewAction->setChecked(false);
- emit visibilityChanged(false);
- break;
- case QEvent::Show:
- d->toggleViewAction->setChecked(true);
- emit visibilityChanged(geometry().right() >= 0 && geometry().bottom() >= 0);
- break;
-#endif
- case QEvent::ApplicationLayoutDirectionChange:
- case QEvent::LayoutDirectionChange:
- case QEvent::StyleChange:
- case QEvent::ParentChange:
- d->updateButtons();
- break;
- case QEvent::ZOrderChange: {
- bool onTop = false;
- if (win != 0) {
- const QObjectList &siblings = win->children();
- onTop = siblings.count() > 0 && siblings.last() == (QObject*)this;
- }
- if (!isFloating() && layout != 0 && onTop)
- layout->raise(this);
- break;
- }
- case QEvent::WindowActivate:
- case QEvent::WindowDeactivate:
- update(qobject_cast<QDockWidgetLayout *>(this->layout())->titleArea());
- break;
- case QEvent::ContextMenu:
- if (d->state) {
- event->accept();
- return true;
- }
- break;
- // return true after calling the handler since we don't want
- // them to be passed onto the default handlers
- case QEvent::MouseButtonPress:
- if (d->mousePressEvent(static_cast<QMouseEvent *>(event)))
- return true;
- break;
- case QEvent::MouseButtonDblClick:
- if (d->mouseDoubleClickEvent(static_cast<QMouseEvent *>(event)))
- return true;
- break;
- case QEvent::MouseMove:
- if (d->mouseMoveEvent(static_cast<QMouseEvent *>(event)))
- return true;
- break;
-#ifdef Q_OS_WIN
- case QEvent::Leave:
- if (d->state != 0 && d->state->dragging && !d->state->nca) {
- // This is a workaround for loosing the mouse on Vista.
- QPoint pos = QCursor::pos();
- QMouseEvent fake(QEvent::MouseMove, mapFromGlobal(pos), pos, Qt::NoButton,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- d->mouseMoveEvent(&fake);
- }
- break;
-#endif
- case QEvent::MouseButtonRelease:
- if (d->mouseReleaseEvent(static_cast<QMouseEvent *>(event)))
- return true;
- break;
- case QEvent::NonClientAreaMouseMove:
- case QEvent::NonClientAreaMouseButtonPress:
- case QEvent::NonClientAreaMouseButtonRelease:
- case QEvent::NonClientAreaMouseButtonDblClick:
- d->nonClientAreaMouseEvent(static_cast<QMouseEvent*>(event));
- return true;
- case QEvent::Move:
- d->moveEvent(static_cast<QMoveEvent*>(event));
- break;
- case QEvent::Resize:
- // if the mainwindow is plugging us, we don't want to update undocked geometry
- if (isFloating() && layout != 0 && layout->pluggingWidget != this)
- d->undockedGeometry = geometry();
- break;
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-#ifndef QT_NO_ACTION
-/*!
- Returns a checkable action that can be used to show or close this
- dock widget.
-
- The action's text is set to the dock widget's window title.
-
- \sa QAction::text QWidget::windowTitle
- */
-QAction * QDockWidget::toggleViewAction() const
-{
- Q_D(const QDockWidget);
- return d->toggleViewAction;
-}
-#endif // QT_NO_ACTION
-
-/*!
- \fn void QDockWidget::featuresChanged(QDockWidget::DockWidgetFeatures features)
-
- This signal is emitted when the \l features property changes. The
- \a features parameter gives the new value of the property.
-*/
-
-/*!
- \fn void QDockWidget::topLevelChanged(bool topLevel)
-
- This signal is emitted when the \l floating property changes.
- The \a topLevel parameter is true if the dock widget is now floating;
- otherwise it is false.
-
- \sa isWindow()
-*/
-
-/*!
- \fn void QDockWidget::allowedAreasChanged(Qt::DockWidgetAreas allowedAreas)
-
- This signal is emitted when the \l allowedAreas property changes. The
- \a allowedAreas parameter gives the new value of the property.
-*/
-
-/*!
- \fn void QDockWidget::visibilityChanged(bool visible)
- \since 4.3
-
- This signal is emitted when the dock widget becomes \a visible (or
- invisible). This happens when the widget is hidden or shown, as
- well as when it is docked in a tabbed dock area and its tab
- becomes selected or unselected.
-*/
-
-/*!
- \fn void QDockWidget::dockLocationChanged(Qt::DockWidgetArea area)
- \since 4.3
-
- This signal is emitted when the dock widget is moved to another
- dock \a area, or is moved to a different location in its current
- dock area. This happens when the dock widget is moved
- programmatically or is dragged to a new location by the user.
-*/
-
-/*!
- \since 4.3
-
- Sets an arbitrary \a widget as the dock widget's title bar. If \a widget
- is 0, any custom title bar widget previously set on the dock widget is
- removed, but not deleted, and the default title bar will be used
- instead.
-
- If a title bar widget is set, QDockWidget will not use native window
- decorations when it is floated.
-
- Here are some tips for implementing custom title bars:
-
- \list
- \o Mouse events that are not explicitly handled by the title bar widget
- must be ignored by calling QMouseEvent::ignore(). These events then
- propagate to the QDockWidget parent, which handles them in the usual
- manner, moving when the title bar is dragged, docking and undocking
- when it is double-clicked, etc.
-
- \o When DockWidgetVerticalTitleBar is set on QDockWidget, the title
- bar widget is repositioned accordingly. In resizeEvent(), the title
- bar should check what orientation it should assume:
- \snippet doc/src/snippets/code/src_gui_widgets_qdockwidget.cpp 0
-
- \o The title bar widget must have a valid QWidget::sizeHint() and
- QWidget::minimumSizeHint(). These functions should take into account
- the current orientation of the title bar.
-
- \o It is not possible to remove a title bar from a dock widget. However,
- a similar effect can be achieved by setting a default constructed
- QWidget as the title bar widget.
- \endlist
-
- Using qobject_cast() as shown above, the title bar widget has full access
- to its parent QDockWidget. Hence it can perform such operations as docking
- and hiding in response to user actions.
-
- \sa titleBarWidget() DockWidgetVerticalTitleBar
-*/
-
-void QDockWidget::setTitleBarWidget(QWidget *widget)
-{
- Q_D(QDockWidget);
- QDockWidgetLayout *layout
- = qobject_cast<QDockWidgetLayout*>(this->layout());
- layout->setWidgetForRole(QDockWidgetLayout::TitleBar, widget);
- d->updateButtons();
- if (isWindow()) {
- //this ensures the native decoration is drawn
- d->setWindowState(true /*floating*/, true /*unplug*/);
- }
-}
-
-/*!
- \since 4.3
- Returns the custom title bar widget set on the QDockWidget, or 0 if no
- custom title bar has been set.
-
- \sa setTitleBarWidget()
-*/
-
-QWidget *QDockWidget::titleBarWidget() const
-{
- QDockWidgetLayout *layout
- = qobject_cast<QDockWidgetLayout*>(this->layout());
- return layout->widgetForRole(QDockWidgetLayout::TitleBar);
-}
-
-QT_END_NAMESPACE
-
-#include "qdockwidget.moc"
-#include "moc_qdockwidget.cpp"
-
-#endif // QT_NO_DOCKWIDGET
diff --git a/src/gui/widgets/qdockwidget.h b/src/gui/widgets/qdockwidget.h
deleted file mode 100644
index d26528bcb1..0000000000
--- a/src/gui/widgets/qdockwidget.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICDOCKWIDGET_H
-#define QDYNAMICDOCKWIDGET_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_DOCKWIDGET
-
-class QDockAreaLayout;
-class QDockWidgetPrivate;
-class QMainWindow;
-class QStyleOptionDockWidget;
-
-class Q_GUI_EXPORT QDockWidget : public QWidget
-{
- Q_OBJECT
-
- Q_FLAGS(DockWidgetFeatures)
- Q_PROPERTY(bool floating READ isFloating WRITE setFloating)
- Q_PROPERTY(DockWidgetFeatures features READ features WRITE setFeatures NOTIFY featuresChanged)
- Q_PROPERTY(Qt::DockWidgetAreas allowedAreas READ allowedAreas
- WRITE setAllowedAreas NOTIFY allowedAreasChanged)
- Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle DESIGNABLE true)
-
-public:
- explicit QDockWidget(const QString &title, QWidget *parent = 0, Qt::WindowFlags flags = 0);
- explicit QDockWidget(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QDockWidget();
-
- QWidget *widget() const;
- void setWidget(QWidget *widget);
-
- enum DockWidgetFeature {
- DockWidgetClosable = 0x01,
- DockWidgetMovable = 0x02,
- DockWidgetFloatable = 0x04,
- DockWidgetVerticalTitleBar = 0x08,
-
- DockWidgetFeatureMask = 0x0f,
- AllDockWidgetFeatures = DockWidgetClosable|DockWidgetMovable|DockWidgetFloatable, // ### remove in 5.0
- NoDockWidgetFeatures = 0x00,
-
- Reserved = 0xff
- };
- Q_DECLARE_FLAGS(DockWidgetFeatures, DockWidgetFeature)
-
- void setFeatures(DockWidgetFeatures features);
- DockWidgetFeatures features() const;
-
- void setFloating(bool floating);
- inline bool isFloating() const { return isWindow(); }
-
- void setAllowedAreas(Qt::DockWidgetAreas areas);
- Qt::DockWidgetAreas allowedAreas() const;
-
- void setTitleBarWidget(QWidget *widget);
- QWidget *titleBarWidget() const;
-
- inline bool isAreaAllowed(Qt::DockWidgetArea area) const
- { return (allowedAreas() & area) == area; }
-
-#ifndef QT_NO_ACTION
- QAction *toggleViewAction() const;
-#endif
-
-Q_SIGNALS:
- void featuresChanged(QDockWidget::DockWidgetFeatures features);
- void topLevelChanged(bool topLevel);
- void allowedAreasChanged(Qt::DockWidgetAreas allowedAreas);
- void visibilityChanged(bool visible);
- void dockLocationChanged(Qt::DockWidgetArea area);
-
-protected:
- void changeEvent(QEvent *event);
- void closeEvent(QCloseEvent *event);
- void paintEvent(QPaintEvent *event);
- bool event(QEvent *event);
- void initStyleOption(QStyleOptionDockWidget *option) const;
-
-private:
- Q_DECLARE_PRIVATE(QDockWidget)
- Q_DISABLE_COPY(QDockWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_toggleView(bool))
- Q_PRIVATE_SLOT(d_func(), void _q_toggleTopLevel())
- friend class QDockAreaLayout;
- friend class QDockWidgetItem;
- friend class QMainWindowLayout;
- friend class QDockWidgetLayout;
- friend class QDockAreaLayoutInfo;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QDockWidget::DockWidgetFeatures)
-
-#endif // QT_NO_DOCKWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDYNAMICDOCKWIDGET_H
diff --git a/src/gui/widgets/qdockwidget_p.h b/src/gui/widgets/qdockwidget_p.h
deleted file mode 100644
index f71a276003..0000000000
--- a/src/gui/widgets/qdockwidget_p.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICDOCKWIDGET_P_H
-#define QDYNAMICDOCKWIDGET_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qstyleoption.h"
-#include "private/qwidget_p.h"
-#include "QtGui/qboxlayout.h"
-#include "QtGui/qdockwidget.h"
-
-#ifndef QT_NO_DOCKWIDGET
-
-QT_BEGIN_NAMESPACE
-
-class QGridLayout;
-class QWidgetResizeHandler;
-class QRubberBand;
-class QDockWidgetTitleButton;
-class QSpacerItem;
-class QDockWidgetItem;
-
-class QDockWidgetPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QDockWidget)
-
- struct DragState {
- QPoint pressPos;
- bool dragging;
- QLayoutItem *widgetItem;
- bool ownWidgetItem;
- bool nca;
- bool ctrlDrag;
- };
-
-public:
- inline QDockWidgetPrivate()
- : QWidgetPrivate(), state(0),
- features(QDockWidget::DockWidgetClosable
- | QDockWidget::DockWidgetMovable
- | QDockWidget::DockWidgetFloatable),
- allowedAreas(Qt::AllDockWidgetAreas)
- { }
-
- void init();
- void _q_toggleView(bool); // private slot
- void _q_toggleTopLevel(); // private slot
-
- void updateButtons();
- DragState *state;
-
- QDockWidget::DockWidgetFeatures features;
- Qt::DockWidgetAreas allowedAreas;
-
- QWidgetResizeHandler *resizer;
-
-#ifndef QT_NO_ACTION
- QAction *toggleViewAction;
-#endif
-
-// QMainWindow *findMainWindow(QWidget *widget) const;
- QRect undockedGeometry;
- QString fixedWindowTitle;
-
- bool mousePressEvent(QMouseEvent *event);
- bool mouseDoubleClickEvent(QMouseEvent *event);
- bool mouseMoveEvent(QMouseEvent *event);
- bool mouseReleaseEvent(QMouseEvent *event);
- void setWindowState(bool floating, bool unplug = false, const QRect &rect = QRect());
- void nonClientAreaMouseEvent(QMouseEvent *event);
- void initDrag(const QPoint &pos, bool nca);
- void startDrag();
- void endDrag(bool abort = false);
- void moveEvent(QMoveEvent *event);
-
- void unplug(const QRect &rect);
- void plug(const QRect &rect);
-
- bool isAnimating() const;
-};
-
-class Q_GUI_EXPORT QDockWidgetLayout : public QLayout
-{
- Q_OBJECT
-public:
- QDockWidgetLayout(QWidget *parent = 0);
- ~QDockWidgetLayout();
- void addItem(QLayoutItem *item);
- QLayoutItem *itemAt(int index) const;
- QLayoutItem *takeAt(int index);
- int count() const;
-
- QSize maximumSize() const;
- QSize minimumSize() const;
- QSize sizeHint() const;
-
- QSize sizeFromContent(const QSize &content, bool floating) const;
-
- void setGeometry(const QRect &r);
-
- enum Role { Content, CloseButton, FloatButton, TitleBar, RoleCount };
- QWidget *widgetForRole(Role r) const;
- void setWidgetForRole(Role r, QWidget *w);
- QLayoutItem *itemForRole(Role r) const;
-
- QRect titleArea() const { return _titleArea; }
-
- int minimumTitleWidth() const;
- int titleHeight() const;
- void updateMaxSize();
- bool nativeWindowDeco() const;
- bool nativeWindowDeco(bool floating) const;
-
- void setVerticalTitleBar(bool b);
-
- bool verticalTitleBar;
-
-private:
- QVector<QLayoutItem*> item_list;
- QRect _titleArea;
-};
-
-/* The size hints of a QDockWidget will depend on whether it is docked or not.
- This layout item always returns the size hints as if the dock widget was docked. */
-
-class QDockWidgetItem : public QWidgetItem
-{
-public:
- QDockWidgetItem(QDockWidget *dockWidget);
- QSize minimumSize() const;
- QSize maximumSize() const;
- QSize sizeHint() const;
-
-private:
- inline QLayoutItem *dockWidgetChildItem() const;
- inline QDockWidgetLayout *dockWidgetLayout() const;
-};
-
-inline QLayoutItem *QDockWidgetItem::dockWidgetChildItem() const
-{
- if (QDockWidgetLayout *layout = dockWidgetLayout())
- return layout->itemForRole(QDockWidgetLayout::Content);
- return 0;
-}
-
-inline QDockWidgetLayout *QDockWidgetItem::dockWidgetLayout() const
-{
- QWidget *w = const_cast<QDockWidgetItem*>(this)->widget();
- if (w != 0)
- return qobject_cast<QDockWidgetLayout*>(w->layout());
- return 0;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DOCKWIDGET
-
-#endif // QDYNAMICDOCKWIDGET_P_H
diff --git a/src/gui/widgets/qeffects.cpp b/src/gui/widgets/qeffects.cpp
deleted file mode 100644
index 6b64d48654..0000000000
--- a/src/gui/widgets/qeffects.cpp
+++ /dev/null
@@ -1,613 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#ifndef QT_NO_EFFECTS
-#include "qdesktopwidget.h"
-#include "qeffects_p.h"
-#include "qevent.h"
-#include "qimage.h"
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qpointer.h"
-#include "qtimer.h"
-#include "qelapsedtimer.h"
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-/*
- Internal class QAlphaWidget.
-
- The QAlphaWidget is shown while the animation lasts
- and displays the pixmap resulting from the alpha blending.
-*/
-
-class QAlphaWidget: public QWidget, private QEffects
-{
- Q_OBJECT
-public:
- QAlphaWidget(QWidget* w, Qt::WindowFlags f = 0);
- ~QAlphaWidget();
-
- void run(int time);
-
-protected:
- void paintEvent(QPaintEvent* e);
- void closeEvent(QCloseEvent*);
- void alphaBlend();
- bool eventFilter(QObject *, QEvent *);
-
-protected slots:
- void render();
-
-private:
- QPixmap pm;
- double alpha;
- QImage backImage;
- QImage frontImage;
- QImage mixedImage;
- QPointer<QWidget> widget;
- int duration;
- int elapsed;
- bool showWidget;
- QTimer anim;
- QElapsedTimer checkTime;
-};
-
-static QAlphaWidget* q_blend = 0;
-
-/*
- Constructs a QAlphaWidget.
-*/
-QAlphaWidget::QAlphaWidget(QWidget* w, Qt::WindowFlags f)
- : QWidget(QApplication::desktop()->screen(QApplication::desktop()->screenNumber(w)), f)
-{
-#ifndef Q_WS_WIN
- setEnabled(false);
-#endif
- setAttribute(Qt::WA_NoSystemBackground, true);
- widget = w;
- alpha = 0;
-}
-
-QAlphaWidget::~QAlphaWidget()
-{
-#if defined(Q_WS_WIN) && !defined(Q_WS_WINCE)
- // Restore user-defined opacity value
- if (widget)
- widget->setWindowOpacity(1);
-#endif
-}
-
-/*
- \reimp
-*/
-void QAlphaWidget::paintEvent(QPaintEvent*)
-{
- QPainter p(this);
- p.drawPixmap(0, 0, pm);
-}
-
-/*
- Starts the alphablending animation.
- The animation will take about \a time ms
-*/
-void QAlphaWidget::run(int time)
-{
- duration = time;
-
- if (duration < 0)
- duration = 150;
-
- if (!widget)
- return;
-
- elapsed = 0;
- checkTime.start();
-
- showWidget = true;
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- qApp->installEventFilter(this);
- widget->setWindowOpacity(0.0);
- widget->show();
- connect(&anim, SIGNAL(timeout()), this, SLOT(render()));
- anim.start(1);
-#else
- //This is roughly equivalent to calling setVisible(true) without actually showing the widget
- widget->setAttribute(Qt::WA_WState_ExplicitShowHide, true);
- widget->setAttribute(Qt::WA_WState_Hidden, false);
-
- qApp->installEventFilter(this);
-
- move(widget->geometry().x(),widget->geometry().y());
- resize(widget->size().width(), widget->size().height());
-
- frontImage = QPixmap::grabWidget(widget).toImage();
- backImage = QPixmap::grabWindow(QApplication::desktop()->winId(),
- widget->geometry().x(), widget->geometry().y(),
- widget->geometry().width(), widget->geometry().height()).toImage();
-
- if (!backImage.isNull() && checkTime.elapsed() < duration / 2) {
- mixedImage = backImage.copy();
- pm = QPixmap::fromImage(mixedImage);
- show();
- setEnabled(false);
-
- connect(&anim, SIGNAL(timeout()), this, SLOT(render()));
- anim.start(1);
- } else {
- duration = 0;
- render();
- }
-#endif
-}
-
-/*
- \reimp
-*/
-bool QAlphaWidget::eventFilter(QObject *o, QEvent *e)
-{
- switch (e->type()) {
- case QEvent::Move:
- if (o != widget)
- break;
- move(widget->geometry().x(),widget->geometry().y());
- update();
- break;
- case QEvent::Hide:
- case QEvent::Close:
- if (o != widget)
- break;
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonDblClick:
- showWidget = false;
- render();
- break;
- case QEvent::KeyPress: {
- QKeyEvent *ke = (QKeyEvent*)e;
- if (ke->key() == Qt::Key_Escape) {
- showWidget = false;
- } else {
- duration = 0;
- }
- render();
- break;
- }
- default:
- break;
- }
- return QWidget::eventFilter(o, e);
-}
-
-/*
- \reimp
-*/
-void QAlphaWidget::closeEvent(QCloseEvent *e)
-{
- e->accept();
- if (!q_blend)
- return;
-
- showWidget = false;
- render();
-
- QWidget::closeEvent(e);
-}
-
-/*
- Render alphablending for the time elapsed.
-
- Show the blended widget and free all allocated source
- if the blending is finished.
-*/
-void QAlphaWidget::render()
-{
- int tempel = checkTime.elapsed();
- if (elapsed >= tempel)
- elapsed++;
- else
- elapsed = tempel;
-
- if (duration != 0)
- alpha = tempel / double(duration);
- else
- alpha = 1;
-
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
- if (alpha >= 1 || !showWidget) {
- anim.stop();
- qApp->removeEventFilter(this);
- widget->setWindowOpacity(1);
- q_blend = 0;
- deleteLater();
- } else {
- widget->setWindowOpacity(alpha);
- }
-#else
- if (alpha >= 1 || !showWidget) {
- anim.stop();
- qApp->removeEventFilter(this);
-
- if (widget) {
- if (!showWidget) {
-#ifdef Q_WS_WIN
- setEnabled(true);
- setFocus();
-#endif // Q_WS_WIN
- widget->hide();
- } else {
- //Since we are faking the visibility of the widget
- //we need to unset the hidden state on it before calling show
- widget->setAttribute(Qt::WA_WState_Hidden, true);
- widget->show();
- lower();
- }
- }
- q_blend = 0;
- deleteLater();
- } else {
- alphaBlend();
- pm = QPixmap::fromImage(mixedImage);
- repaint();
- }
-#endif // defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
-}
-
-/*
- Calculate an alphablended image.
-*/
-void QAlphaWidget::alphaBlend()
-{
- const int a = qRound(alpha*256);
- const int ia = 256 - a;
-
- const int sw = frontImage.width();
- const int sh = frontImage.height();
- const int bpl = frontImage.bytesPerLine();
- switch(frontImage.depth()) {
- case 32:
- {
- uchar *mixed_data = mixedImage.bits();
- const uchar *back_data = backImage.bits();
- const uchar *front_data = frontImage.bits();
-
- for (int sy = 0; sy < sh; sy++) {
- quint32* mixed = (quint32*)mixed_data;
- const quint32* back = (const quint32*)back_data;
- const quint32* front = (const quint32*)front_data;
- for (int sx = 0; sx < sw; sx++) {
- quint32 bp = back[sx];
- quint32 fp = front[sx];
-
- mixed[sx] = qRgb((qRed(bp)*ia + qRed(fp)*a)>>8,
- (qGreen(bp)*ia + qGreen(fp)*a)>>8,
- (qBlue(bp)*ia + qBlue(fp)*a)>>8);
- }
- mixed_data += bpl;
- back_data += bpl;
- front_data += bpl;
- }
- }
- default:
- break;
- }
-}
-
-/*
- Internal class QRollEffect
-
- The QRollEffect widget is shown while the animation lasts
- and displays a scrolling pixmap.
-*/
-
-class QRollEffect : public QWidget, private QEffects
-{
- Q_OBJECT
-public:
- QRollEffect(QWidget* w, Qt::WindowFlags f, DirFlags orient);
-
- void run(int time);
-
-protected:
- void paintEvent(QPaintEvent*);
- void closeEvent(QCloseEvent*);
-
-private slots:
- void scroll();
-
-private:
- QPointer<QWidget> widget;
-
- int currentHeight;
- int currentWidth;
- int totalHeight;
- int totalWidth;
-
- int duration;
- int elapsed;
- bool done;
- bool showWidget;
- int orientation;
-
- QTimer anim;
- QElapsedTimer checkTime;
-
- QPixmap pm;
-};
-
-static QRollEffect* q_roll = 0;
-
-/*
- Construct a QRollEffect widget.
-*/
-QRollEffect::QRollEffect(QWidget* w, Qt::WindowFlags f, DirFlags orient)
- : QWidget(0, f), orientation(orient)
-{
-#ifndef Q_WS_WIN
- setEnabled(false);
-#endif
-
- widget = w;
- Q_ASSERT(widget);
-
- setAttribute(Qt::WA_NoSystemBackground, true);
-
- if (widget->testAttribute(Qt::WA_Resized)) {
- totalWidth = widget->width();
- totalHeight = widget->height();
- } else {
- totalWidth = widget->sizeHint().width();
- totalHeight = widget->sizeHint().height();
- }
-
- currentHeight = totalHeight;
- currentWidth = totalWidth;
-
- if (orientation & (RightScroll|LeftScroll))
- currentWidth = 0;
- if (orientation & (DownScroll|UpScroll))
- currentHeight = 0;
-
- pm = QPixmap::grabWidget(widget);
-}
-
-/*
- \reimp
-*/
-void QRollEffect::paintEvent(QPaintEvent*)
-{
- int x = orientation & RightScroll ? qMin(0, currentWidth - totalWidth) : 0;
- int y = orientation & DownScroll ? qMin(0, currentHeight - totalHeight) : 0;
-
- QPainter p(this);
- p.drawPixmap(x, y, pm);
-}
-
-/*
- \reimp
-*/
-void QRollEffect::closeEvent(QCloseEvent *e)
-{
- e->accept();
- if (done)
- return;
-
- showWidget = false;
- done = true;
- scroll();
-
- QWidget::closeEvent(e);
-}
-
-/*
- Start the animation.
-
- The animation will take about \a time ms, or is
- calculated if \a time is negative
-*/
-void QRollEffect::run(int time)
-{
- if (!widget)
- return;
-
- duration = time;
- elapsed = 0;
-
- if (duration < 0) {
- int dist = 0;
- if (orientation & (RightScroll|LeftScroll))
- dist += totalWidth - currentWidth;
- if (orientation & (DownScroll|UpScroll))
- dist += totalHeight - currentHeight;
- duration = qMin(qMax(dist/3, 50), 120);
- }
-
- connect(&anim, SIGNAL(timeout()), this, SLOT(scroll()));
-
- move(widget->geometry().x(),widget->geometry().y());
- resize(qMin(currentWidth, totalWidth), qMin(currentHeight, totalHeight));
-
- //This is roughly equivalent to calling setVisible(true) without actually showing the widget
- widget->setAttribute(Qt::WA_WState_ExplicitShowHide, true);
- widget->setAttribute(Qt::WA_WState_Hidden, false);
-
- show();
- setEnabled(false);
-
- qApp->installEventFilter(this);
-
- showWidget = true;
- done = false;
- anim.start(1);
- checkTime.start();
-}
-
-/*
- Roll according to the time elapsed.
-*/
-void QRollEffect::scroll()
-{
- if (!done && widget) {
- int tempel = checkTime.elapsed();
- if (elapsed >= tempel)
- elapsed++;
- else
- elapsed = tempel;
-
- if (currentWidth != totalWidth) {
- currentWidth = totalWidth * (elapsed/duration)
- + (2 * totalWidth * (elapsed%duration) + duration)
- / (2 * duration);
- // equiv. to int((totalWidth*elapsed) / duration + 0.5)
- done = (currentWidth >= totalWidth);
- }
- if (currentHeight != totalHeight) {
- currentHeight = totalHeight * (elapsed/duration)
- + (2 * totalHeight * (elapsed%duration) + duration)
- / (2 * duration);
- // equiv. to int((totalHeight*elapsed) / duration + 0.5)
- done = (currentHeight >= totalHeight);
- }
- done = (currentHeight >= totalHeight) &&
- (currentWidth >= totalWidth);
-
- int w = totalWidth;
- int h = totalHeight;
- int x = widget->geometry().x();
- int y = widget->geometry().y();
-
- if (orientation & RightScroll || orientation & LeftScroll)
- w = qMin(currentWidth, totalWidth);
- if (orientation & DownScroll || orientation & UpScroll)
- h = qMin(currentHeight, totalHeight);
-
- setUpdatesEnabled(false);
- if (orientation & UpScroll)
- y = widget->geometry().y() + qMax(0, totalHeight - currentHeight);
- if (orientation & LeftScroll)
- x = widget->geometry().x() + qMax(0, totalWidth - currentWidth);
- if (orientation & UpScroll || orientation & LeftScroll)
- move(x, y);
-
- resize(w, h);
- setUpdatesEnabled(true);
- repaint();
- }
- if (done) {
- anim.stop();
- qApp->removeEventFilter(this);
- if (widget) {
- if (!showWidget) {
-#ifdef Q_WS_WIN
- setEnabled(true);
- setFocus();
-#endif
- widget->hide();
- } else {
- //Since we are faking the visibility of the widget
- //we need to unset the hidden state on it before calling show
- widget->setAttribute(Qt::WA_WState_Hidden, true);
- widget->show();
- lower();
- }
- }
- q_roll = 0;
- deleteLater();
- }
-}
-
-/*!
- Scroll widget \a w in \a time ms. \a orient may be 1 (vertical), 2
- (horizontal) or 3 (diagonal).
-*/
-void qScrollEffect(QWidget* w, QEffects::DirFlags orient, int time)
-{
- if (q_roll) {
- q_roll->deleteLater();
- q_roll = 0;
- }
-
- if (!w)
- return;
-
- QApplication::sendPostedEvents(w, QEvent::Move);
- QApplication::sendPostedEvents(w, QEvent::Resize);
- Qt::WindowFlags flags = Qt::ToolTip;
-
- // those can be popups - they would steal the focus, but are disabled
- q_roll = new QRollEffect(w, flags, orient);
- q_roll->run(time);
-}
-
-/*!
- Fade in widget \a w in \a time ms.
-*/
-void qFadeEffect(QWidget* w, int time)
-{
- if (q_blend) {
- q_blend->deleteLater();
- q_blend = 0;
- }
-
- if (!w)
- return;
-
- QApplication::sendPostedEvents(w, QEvent::Move);
- QApplication::sendPostedEvents(w, QEvent::Resize);
-
- Qt::WindowFlags flags = Qt::ToolTip;
-
- // those can be popups - they would steal the focus, but are disabled
- q_blend = new QAlphaWidget(w, flags);
-
- q_blend->run(time);
-}
-
-QT_END_NAMESPACE
-
-/*
- Delete this after timeout
-*/
-
-#include "qeffects.moc"
-
-#endif //QT_NO_EFFECTS
diff --git a/src/gui/widgets/qeffects_p.h b/src/gui/widgets/qeffects_p.h
deleted file mode 100644
index feaf9be9e6..0000000000
--- a/src/gui/widgets/qeffects_p.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** 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 QEFFECTS_P_H
-#define QEFFECTS_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of qeffects.cpp, qcombobox.cpp, qpopupmenu.cpp and qtooltip.cpp.
-// This header file may change from version to version without notice,
-// or even be removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qnamespace.h"
-
-#ifndef QT_NO_EFFECTS
-
-QT_BEGIN_NAMESPACE
-
-class QWidget;
-
-struct QEffects
-{
- enum Direction {
- LeftScroll = 0x0001,
- RightScroll = 0x0002,
- UpScroll = 0x0004,
- DownScroll = 0x0008
- };
-
- typedef uint DirFlags;
-};
-
-extern void Q_GUI_EXPORT qScrollEffect(QWidget*, QEffects::DirFlags dir = QEffects::DownScroll, int time = -1);
-extern void Q_GUI_EXPORT qFadeEffect(QWidget*, int time = -1);
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_EFFECTS
-
-#endif // QEFFECTS_P_H
diff --git a/src/gui/widgets/qfocusframe.cpp b/src/gui/widgets/qfocusframe.cpp
deleted file mode 100644
index 6508c31b50..0000000000
--- a/src/gui/widgets/qfocusframe.cpp
+++ /dev/null
@@ -1,339 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfocusframe.h"
-#include "qstyle.h"
-#include "qbitmap.h"
-#include "qstylepainter.h"
-#include "qstyleoption.h"
-#include "qdebug.h"
-#include <private/qwidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QFocusFramePrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QFocusFrame)
- QWidget *widget;
- QWidget *frameParent;
- bool showFrameAboveWidget;
-public:
- QFocusFramePrivate() {
- widget = 0;
- frameParent = 0;
- sendChildEvents = false;
- showFrameAboveWidget = false;
- }
- void updateSize();
- void update();
-};
-
-void QFocusFramePrivate::update()
-{
- Q_Q(QFocusFrame);
- q->setParent(frameParent);
- updateSize();
- if (q->parentWidget()->rect().intersects(q->geometry())) {
- if (showFrameAboveWidget)
- q->raise();
- else
- q->stackUnder(widget);
- q->show();
- } else {
- q->hide();
- }
-}
-
-void QFocusFramePrivate::updateSize()
-{
- Q_Q(QFocusFrame);
- if (!widget)
- return;
-
- int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin),
- hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin);
- QPoint pos(widget->x(), widget->y());
- if (q->parentWidget() != widget->parentWidget())
- pos = widget->parentWidget()->mapTo(q->parentWidget(), pos);
- QRect geom(pos.x()-hmargin, pos.y()-vmargin,
- widget->width()+(hmargin*2), widget->height()+(vmargin*2));
- if(q->geometry() == geom)
- return;
-
- q->setGeometry(geom);
- QStyleHintReturnMask mask;
- QStyleOption opt;
- q->initStyleOption(&opt);
- if (q->style()->styleHint(QStyle::SH_FocusFrame_Mask, &opt, q, &mask))
- q->setMask(mask.region);
-}
-
-/*!
- Initialize \a option with the values from this QFocusFrame. This method is useful
- for subclasses when they need a QStyleOption, but don't want to fill
- in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QFocusFrame::initStyleOption(QStyleOption *option) const
-{
- if (!option)
- return;
-
- option->initFrom(this);
-}
-
-/*!
- \class QFocusFrame
- \brief The QFocusFrame widget provides a focus frame which can be
- outside of a widget's normal paintable area.
-
- \ingroup basicwidgets
-
-
- Normally an application will not need to create its own
- QFocusFrame as QStyle will handle this detail for
- you. A style writer can optionally use a QFocusFrame to have a
- focus area outside of the widget's paintable geometry. In this way
- space need not be reserved for the widget to have focus but only
- set on a QWidget with QFocusFrame::setWidget. It is, however,
- legal to create your own QFocusFrame on a custom widget and set
- its geometry manually via QWidget::setGeometry however you will
- not get auto-placement when the focused widget changes size or
- placement.
-*/
-
-/*!
- Constructs a QFocusFrame.
-
- The focus frame will not monitor \a parent for updates but rather
- can be placed manually or by using QFocusFrame::setWidget. A
- QFocusFrame sets Qt::WA_NoChildEventsForParent attribute; as a
- result the parent will not receive a QEvent::ChildInserted event,
- this will make it possible to manually set the geometry of the
- QFocusFrame inside of a QSplitter or other child event monitoring
- widget.
-
- \sa QFocusFrame::setWidget()
-*/
-
-QFocusFrame::QFocusFrame(QWidget *parent)
- : QWidget(*new QFocusFramePrivate, parent, 0)
-{
- setAttribute(Qt::WA_TransparentForMouseEvents);
- setFocusPolicy(Qt::NoFocus);
- setAttribute(Qt::WA_NoChildEventsForParent, true);
- setAttribute(Qt::WA_AcceptDrops, style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this));
-}
-
-/*!
- Destructor.
-*/
-
-QFocusFrame::~QFocusFrame()
-{
-}
-
-/*!
- QFocusFrame will track changes to \a widget and resize itself automatically.
- If the monitored widget's parent changes, QFocusFrame will follow the widget
- and place itself around the widget automatically. If the monitored widget is deleted,
- QFocusFrame will set it to zero.
-
- \sa QFocusFrame::widget()
-*/
-
-void
-QFocusFrame::setWidget(QWidget *widget)
-{
- Q_D(QFocusFrame);
-
- if (style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this))
- d->showFrameAboveWidget = true;
- else
- d->showFrameAboveWidget = false;
-
- if (widget == d->widget)
- return;
- if (d->widget) {
- // Remove event filters from the widget hierarchy.
- QWidget *p = d->widget;
- do {
- p->removeEventFilter(this);
- if (!d->showFrameAboveWidget || p == d->frameParent)
- break;
- p = p->parentWidget();
- }while (p);
- }
- if (widget && !widget->isWindow() && widget->parentWidget()->windowType() != Qt::SubWindow) {
- d->widget = widget;
- d->widget->installEventFilter(this);
- QWidget *p = widget->parentWidget();
- QWidget *prev = 0;
- if (d->showFrameAboveWidget) {
- // Find the right parent for the focus frame.
- while (p) {
- // Traverse the hirerarchy of the 'widget' for setting event filter.
- // During this if come across toolbar or a top level, use that
- // as the parent for the focus frame. If we find a scroll area
- // use its viewport as the parent.
- bool isScrollArea = false;
- if (p->isWindow() || p->inherits("QToolBar") || (isScrollArea = p->inherits("QAbstractScrollArea"))) {
- d->frameParent = p;
- // The previous one in the hierarchy will be the viewport.
- if (prev && isScrollArea)
- d->frameParent = prev;
- break;
- } else {
- p->installEventFilter(this);
- prev = p;
- p = p->parentWidget();
- }
- }
- } else {
- d->frameParent = p;
- }
- d->update();
- } else {
- d->widget = 0;
- hide();
- }
-}
-
-/*!
- Returns the currently monitored widget for automatically resize and
- update.
-
- \sa QFocusFrame::setWidget()
-*/
-
-QWidget *
-QFocusFrame::widget() const
-{
- Q_D(const QFocusFrame);
- return d->widget;
-}
-
-
-/*! \reimp */
-void
-QFocusFrame::paintEvent(QPaintEvent *)
-{
- Q_D(QFocusFrame);
- QStylePainter p(this);
- QStyleOption option;
- initStyleOption(&option);
- int vmargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin);
- int hmargin = style()->pixelMetric(QStyle::PM_FocusFrameHMargin);
- QWidgetPrivate *wd = qt_widget_private(d->widget);
- QRect rect = wd->clipRect().adjusted(0, 0, hmargin*2, vmargin*2);
- p.setClipRect(rect);
- p.drawControl(QStyle::CE_FocusFrame, option);
-}
-
-
-/*! \reimp */
-bool
-QFocusFrame::eventFilter(QObject *o, QEvent *e)
-{
- Q_D(QFocusFrame);
- if(o == d->widget) {
- switch(e->type()) {
- case QEvent::Move:
- case QEvent::Resize:
- d->updateSize();
- break;
- case QEvent::Hide:
- case QEvent::StyleChange:
- hide();
- break;
- case QEvent::ParentChange:
- if (d->showFrameAboveWidget) {
- QWidget *w = d->widget;
- setWidget(0);
- setWidget(w);
- } else {
- d->update();
- }
- break;
- case QEvent::Show:
- d->update();
- show();
- break;
- case QEvent::PaletteChange:
- setPalette(d->widget->palette());
- break;
- case QEvent::ZOrderChange:
- if (style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this))
- raise();
- else
- stackUnder(d->widget);
- break;
- case QEvent::Destroy:
- setWidget(0);
- break;
- default:
- break;
- }
- } else if (d->showFrameAboveWidget) {
- // Handle changes in the parent widgets we are monitoring.
- switch(e->type()) {
- case QEvent::Move:
- case QEvent::Resize:
- d->updateSize();
- break;
- case QEvent::ZOrderChange:
- raise();
- break;
- default:
- break;
- }
- }
- return false;
-}
-
-/*! \reimp */
-bool QFocusFrame::event(QEvent *e)
-{
- return QWidget::event(e);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qfocusframe.h b/src/gui/widgets/qfocusframe.h
deleted file mode 100644
index 3ed411d558..0000000000
--- a/src/gui/widgets/qfocusframe.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** 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 QFOCUSFRAME_H
-#define QFOCUSFRAME_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QFocusFramePrivate;
-class QStyleOption;
-
-class Q_GUI_EXPORT QFocusFrame : public QWidget
-{
- Q_OBJECT
-public:
- QFocusFrame(QWidget *parent=0);
- ~QFocusFrame();
-
- void setWidget(QWidget *widget);
- QWidget *widget() const;
-
-protected:
- bool event(QEvent *e);
-
- bool eventFilter(QObject *, QEvent *);
- void paintEvent(QPaintEvent *);
- void initStyleOption(QStyleOption *option) const;
-
-private:
- Q_DECLARE_PRIVATE(QFocusFrame)
- Q_DISABLE_COPY(QFocusFrame)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QFOCUSFRAME_H
diff --git a/src/gui/widgets/qfontcombobox.cpp b/src/gui/widgets/qfontcombobox.cpp
deleted file mode 100644
index d27f9dc339..0000000000
--- a/src/gui/widgets/qfontcombobox.cpp
+++ /dev/null
@@ -1,474 +0,0 @@
-/****************************************************************************
-**
-** 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 "qfontcombobox.h"
-
-#ifndef QT_NO_FONTCOMBOBOX
-
-#include <qstringlistmodel.h>
-#include <qitemdelegate.h>
-#include <qlistview.h>
-#include <qpainter.h>
-#include <qevent.h>
-#include <qapplication.h>
-#include <private/qcombobox_p.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool *hasLatin)
-{
- *hasLatin = true;
-
- QList<QFontDatabase::WritingSystem> writingSystems = QFontDatabase().writingSystems(font.family());
-// qDebug() << font.family() << writingSystems;
-
- // this just confuses the algorithm below. Vietnamese is Latin with lots of special chars
- writingSystems.removeAll(QFontDatabase::Vietnamese);
-
- QFontDatabase::WritingSystem system = QFontDatabase::Any;
-
- if (!writingSystems.contains(QFontDatabase::Latin)) {
- *hasLatin = false;
- // we need to show something
- if (writingSystems.count())
- system = writingSystems.last();
- } else {
- writingSystems.removeAll(QFontDatabase::Latin);
- }
-
- if (writingSystems.isEmpty())
- return system;
-
- if (writingSystems.count() == 1 && writingSystems.at(0) > QFontDatabase::Cyrillic) {
- system = writingSystems.at(0);
- return system;
- }
-
- if (writingSystems.count() <= 2
- && writingSystems.last() > QFontDatabase::Armenian
- && writingSystems.last() < QFontDatabase::Vietnamese) {
- system = writingSystems.last();
- return system;
- }
-
- if (writingSystems.count() <= 5
- && writingSystems.last() >= QFontDatabase::SimplifiedChinese
- && writingSystems.last() <= QFontDatabase::Korean)
- system = writingSystems.last();
-
- return system;
-}
-
-class QFontFamilyDelegate : public QAbstractItemDelegate
-{
- Q_OBJECT
-public:
- explicit QFontFamilyDelegate(QObject *parent);
-
- // painting
- void paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const;
-
- QIcon truetype;
- QIcon bitmap;
- QFontDatabase::WritingSystem writingSystem;
-};
-
-QFontFamilyDelegate::QFontFamilyDelegate(QObject *parent)
- : QAbstractItemDelegate(parent)
-{
- truetype = QIcon(QLatin1String(":/trolltech/styles/commonstyle/images/fonttruetype-16.png"));
- bitmap = QIcon(QLatin1String(":/trolltech/styles/commonstyle/images/fontbitmap-16.png"));
- writingSystem = QFontDatabase::Any;
-}
-
-void QFontFamilyDelegate::paint(QPainter *painter,
- const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- QString text = index.data(Qt::DisplayRole).toString();
- QFont font(option.font);
- font.setPointSize(QFontInfo(font).pointSize() * 3 / 2);
- QFont font2 = font;
- font2.setFamily(text);
-
- bool hasLatin;
- QFontDatabase::WritingSystem system = writingSystemForFont(font2, &hasLatin);
- if (hasLatin)
- font = font2;
-
- QRect r = option.rect;
-
- if (option.state & QStyle::State_Selected) {
- painter->save();
- painter->setBrush(option.palette.highlight());
- painter->setPen(Qt::NoPen);
- painter->drawRect(option.rect);
- painter->setPen(QPen(option.palette.highlightedText(), 0));
- }
-
- const QIcon *icon = &bitmap;
- if (QFontDatabase().isSmoothlyScalable(text)) {
- icon = &truetype;
- }
- QSize actualSize = icon->actualSize(r.size());
-
- icon->paint(painter, r, Qt::AlignLeft|Qt::AlignVCenter);
- if (option.direction == Qt::RightToLeft)
- r.setRight(r.right() - actualSize.width() - 4);
- else
- r.setLeft(r.left() + actualSize.width() + 4);
-
- QFont old = painter->font();
- painter->setFont(font);
- painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, text);
-
- if (writingSystem != QFontDatabase::Any)
- system = writingSystem;
-
- if (system != QFontDatabase::Any) {
- int w = painter->fontMetrics().width(text + QLatin1String(" "));
- painter->setFont(font2);
- QString sample = QFontDatabase().writingSystemSample(system);
- if (option.direction == Qt::RightToLeft)
- r.setRight(r.right() - w);
- else
- r.setLeft(r.left() + w);
- painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, sample);
- }
- painter->setFont(old);
-
- if (option.state & QStyle::State_Selected)
- painter->restore();
-
-}
-
-QSize QFontFamilyDelegate::sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- QString text = index.data(Qt::DisplayRole).toString();
- QFont font(option.font);
-// font.setFamily(text);
- font.setPointSize(QFontInfo(font).pointSize() * 3/2);
- QFontMetrics fontMetrics(font);
- return QSize(fontMetrics.width(text), fontMetrics.height());
-}
-
-
-class QFontComboBoxPrivate : public QComboBoxPrivate
-{
-public:
- inline QFontComboBoxPrivate() { filters = QFontComboBox::AllFonts; }
-
- QFontComboBox::FontFilters filters;
- QFont currentFont;
-
- void _q_updateModel();
- void _q_currentChanged(const QString &);
-
- Q_DECLARE_PUBLIC(QFontComboBox)
-};
-
-
-void QFontComboBoxPrivate::_q_updateModel()
-{
- Q_Q(QFontComboBox);
- const int scalableMask = (QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
- const int spacingMask = (QFontComboBox::ProportionalFonts | QFontComboBox::MonospacedFonts);
-
- QStringListModel *m = qobject_cast<QStringListModel *>(q->model());
- if (!m)
- return;
- QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(q->view()->itemDelegate());
- QFontDatabase::WritingSystem system = delegate ? delegate->writingSystem : QFontDatabase::Any;
-
- QFontDatabase fdb;
- QStringList list = fdb.families(system);
- QStringList result;
-
- int offset = 0;
- QFontInfo fi(currentFont);
-
- for (int i = 0; i < list.size(); ++i) {
- if ((filters & scalableMask) && (filters & scalableMask) != scalableMask) {
- if (bool(filters & QFontComboBox::ScalableFonts) != fdb.isSmoothlyScalable(list.at(i)))
- continue;
- }
- if ((filters & spacingMask) && (filters & spacingMask) != spacingMask) {
- if (bool(filters & QFontComboBox::MonospacedFonts) != fdb.isFixedPitch(list.at(i)))
- continue;
- }
- result += list.at(i);
- if (list.at(i) == fi.family() || list.at(i).startsWith(fi.family() + QLatin1String(" [")))
- offset = result.count() - 1;
- }
- list = result;
-
- //we need to block the signals so that the model doesn't emit reset
- //this prevents the current index from changing
- //it will be updated just after this
- ///TODO: we should finda way to avoid blocking signals and have a real update of the model
- const bool old = m->blockSignals(true);
- m->setStringList(list);
- m->blockSignals(old);
-
- if (list.isEmpty()) {
- if (currentFont != QFont()) {
- currentFont = QFont();
- emit q->currentFontChanged(currentFont);
- }
- } else {
- q->setCurrentIndex(offset);
- }
-}
-
-
-void QFontComboBoxPrivate::_q_currentChanged(const QString &text)
-{
- Q_Q(QFontComboBox);
- if (currentFont.family() != text) {
- currentFont.setFamily(text);
- emit q->currentFontChanged(currentFont);
- }
-}
-
-/*!
- \class QFontComboBox
- \brief The QFontComboBox widget is a combobox that lets the user
- select a font family.
-
- \since 4.2
- \ingroup basicwidgets
-
- The combobox is populated with an alphabetized list of font
- family names, such as Arial, Helvetica, and Times New Roman.
- Family names are displayed using the actual font when possible.
- For fonts such as Symbol, where the name is not representable in
- the font itself, a sample of the font is displayed next to the
- family name.
-
- QFontComboBox is often used in toolbars, in conjunction with a
- QComboBox for controlling the font size and two \l{QToolButton}s
- for bold and italic.
-
- When the user selects a new font, the currentFontChanged() signal
- is emitted in addition to currentIndexChanged().
-
- Call setWritingSystem() to tell QFontComboBox to show only fonts
- that support a given writing system, and setFontFilters() to
- filter out certain types of fonts as e.g. non scalable fonts or
- monospaced fonts.
-
- \image windowsxp-fontcombobox.png Screenshot of QFontComboBox on Windows XP
-
- \sa QComboBox, QFont, QFontInfo, QFontMetrics, QFontDatabase, {Character Map Example}
-*/
-
-/*!
- \fn void QFontComboBox::setWritingSystem(QFontDatabase::WritingSystem script)
-*/
-
-/*!
- \fn void QFontComboBox::setCurrentFont(const QFont &font);
-*/
-
-/*!
- Constructs a font combobox with the given \a parent.
-*/
-QFontComboBox::QFontComboBox(QWidget *parent)
- : QComboBox(*new QFontComboBoxPrivate, parent)
-{
- Q_D(QFontComboBox);
- d->currentFont = font();
- setEditable(true);
-
- QStringListModel *m = new QStringListModel(this);
- setModel(m);
- setItemDelegate(new QFontFamilyDelegate(this));
- QListView *lview = qobject_cast<QListView*>(view());
- if (lview)
- lview->setUniformItemSizes(true);
- setWritingSystem(QFontDatabase::Any);
-
- connect(this, SIGNAL(currentIndexChanged(QString)),
- this, SLOT(_q_currentChanged(QString)));
-
- connect(qApp, SIGNAL(fontDatabaseChanged()),
- this, SLOT(_q_updateModel()));
-}
-
-
-/*!
- Destroys the combobox.
-*/
-QFontComboBox::~QFontComboBox()
-{
-}
-
-/*!
- \property QFontComboBox::writingSystem
- \brief the writing system that serves as a filter for the combobox
-
- If \a script is QFontDatabase::Any (the default), all fonts are
- listed.
-
- \sa fontFilters
-*/
-
-void QFontComboBox::setWritingSystem(QFontDatabase::WritingSystem script)
-{
- Q_D(QFontComboBox);
- QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(view()->itemDelegate());
- if (delegate)
- delegate->writingSystem = script;
- d->_q_updateModel();
-}
-
-QFontDatabase::WritingSystem QFontComboBox::writingSystem() const
-{
- QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(view()->itemDelegate());
- if (delegate)
- return delegate->writingSystem;
- return QFontDatabase::Any;
-}
-
-
-/*!
- \enum QFontComboBox::FontFilter
-
- This enum can be used to only show certain types of fonts in the font combo box.
-
- \value AllFonts Show all fonts
- \value ScalableFonts Show scalable fonts
- \value NonScalableFonts Show non scalable fonts
- \value MonospacedFonts Show monospaced fonts
- \value ProportionalFonts Show proportional fonts
-*/
-
-/*!
- \property QFontComboBox::fontFilters
- \brief the filter for the combobox
-
- By default, all fonts are listed.
-
- \sa writingSystem
-*/
-void QFontComboBox::setFontFilters(FontFilters filters)
-{
- Q_D(QFontComboBox);
- d->filters = filters;
- d->_q_updateModel();
-}
-
-QFontComboBox::FontFilters QFontComboBox::fontFilters() const
-{
- Q_D(const QFontComboBox);
- return d->filters;
-}
-
-/*!
- \property QFontComboBox::currentFont
- \brief the currently selected font
-
- \sa currentFontChanged(), currentIndex, currentText
-*/
-QFont QFontComboBox::currentFont() const
-{
- Q_D(const QFontComboBox);
- return d->currentFont;
-}
-
-void QFontComboBox::setCurrentFont(const QFont &font)
-{
- Q_D(QFontComboBox);
- if (font != d->currentFont) {
- d->currentFont = font;
- d->_q_updateModel();
- if (d->currentFont == font) { //else the signal has already be emitted by _q_updateModel
- emit currentFontChanged(d->currentFont);
- }
- }
-}
-
-/*!
- \fn QFontComboBox::currentFontChanged(const QFont &font)
-
- This signal is emitted whenever the current font changes, with
- the new \a font.
-
- \sa currentFont
-*/
-
-/*!
- \reimp
-*/
-bool QFontComboBox::event(QEvent *e)
-{
- if (e->type() == QEvent::Resize) {
- QListView *lview = qobject_cast<QListView*>(view());
- if (lview)
- lview->window()->setFixedWidth(width() * 5 / 3);
- }
- return QComboBox::event(e);
-}
-
-/*!
- \reimp
-*/
-QSize QFontComboBox::sizeHint() const
-{
- QSize sz = QComboBox::sizeHint();
- QFontMetrics fm(font());
- sz.setWidth(fm.width(QLatin1Char('m'))*14);
- return sz;
-}
-
-QT_END_NAMESPACE
-
-#include "qfontcombobox.moc"
-#include "moc_qfontcombobox.cpp"
-
-#endif // QT_NO_FONTCOMBOBOX
diff --git a/src/gui/widgets/qfontcombobox.h b/src/gui/widgets/qfontcombobox.h
deleted file mode 100644
index 1eb647a855..0000000000
--- a/src/gui/widgets/qfontcombobox.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** 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 QFONTCOMBOBOX_H
-#define QFONTCOMBOBOX_H
-
-#include <QtGui/qcombobox.h>
-#include <QtGui/qfontdatabase.h>
-
-#ifndef QT_NO_FONTCOMBOBOX
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QFontComboBoxPrivate;
-
-class Q_GUI_EXPORT QFontComboBox : public QComboBox
-{
- Q_OBJECT
- Q_FLAGS(FontFilters)
- Q_PROPERTY(QFontDatabase::WritingSystem writingSystem READ writingSystem WRITE setWritingSystem)
- Q_PROPERTY(FontFilters fontFilters READ fontFilters WRITE setFontFilters)
- Q_PROPERTY(QFont currentFont READ currentFont WRITE setCurrentFont NOTIFY currentFontChanged)
- Q_ENUMS(FontSelection)
-
-public:
- explicit QFontComboBox(QWidget *parent = 0);
- ~QFontComboBox();
-
- void setWritingSystem(QFontDatabase::WritingSystem);
- QFontDatabase::WritingSystem writingSystem() const;
-
- enum FontFilter {
- AllFonts = 0,
- ScalableFonts = 0x1,
- NonScalableFonts = 0x2,
- MonospacedFonts = 0x4,
- ProportionalFonts = 0x8
- };
- Q_DECLARE_FLAGS(FontFilters, FontFilter)
-
- void setFontFilters(FontFilters filters);
- FontFilters fontFilters() const;
-
- QFont currentFont() const;
- QSize sizeHint() const;
-
-public Q_SLOTS:
- void setCurrentFont(const QFont &f);
-
-Q_SIGNALS:
- void currentFontChanged(const QFont &f);
-
-protected:
- bool event(QEvent *e);
-
-private:
- Q_DISABLE_COPY(QFontComboBox)
- Q_DECLARE_PRIVATE(QFontComboBox)
- Q_PRIVATE_SLOT(d_func(), void _q_currentChanged(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_updateModel())
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QFontComboBox::FontFilters)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_FONTCOMBOBOX
-#endif
diff --git a/src/gui/widgets/qframe.cpp b/src/gui/widgets/qframe.cpp
deleted file mode 100644
index 1a61b3831f..0000000000
--- a/src/gui/widgets/qframe.cpp
+++ /dev/null
@@ -1,564 +0,0 @@
-/****************************************************************************
-**
-** 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 "qframe.h"
-#include "qbitmap.h"
-#include "qdrawutil.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qapplication.h"
-
-#include "qframe_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QFramePrivate::QFramePrivate()
- : frect(QRect(0, 0, 0, 0)),
- frameStyle(QFrame::NoFrame | QFrame::Plain),
- lineWidth(1),
- midLineWidth(0),
- frameWidth(0),
- leftFrameWidth(0), rightFrameWidth(0),
- topFrameWidth(0), bottomFrameWidth(0)
-{
-}
-
-inline void QFramePrivate::init()
-{
- setLayoutItemMargins(QStyle::SE_FrameLayoutItem);
-}
-
-/*!
- \class QFrame
- \brief The QFrame class is the base class of widgets that can have a frame.
-
- \ingroup abstractwidgets
-
-
- QMenu uses this to "raise" the menu above the surrounding
- screen. QProgressBar has a "sunken" look. QLabel has a flat look.
- The frames of widgets like these can be changed.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qframe.cpp 0
-
- The QFrame class can also be used directly for creating simple
- placeholder frames without any contents.
-
- The frame style is specified by a \l{QFrame::Shape}{frame shape} and
- a \l{QFrame::Shadow}{shadow style} that is used to visually separate
- the frame from surrounding widgets. These properties can be set
- together using the setFrameStyle() function and read with frameStyle().
-
- The frame shapes are \l NoFrame, \l Box, \l Panel, \l StyledPanel,
- HLine and \l VLine; the shadow styles are \l Plain, \l Raised and
- \l Sunken.
-
- A frame widget has three attributes that describe the thickness of the
- border: \l lineWidth, \l midLineWidth, and \l frameWidth.
-
- \list
- \o The line width is the width of the frame border. It can be modified
- to customize the frame's appearance.
-
- \o The mid-line width specifies the width of an extra line in the
- middle of the frame, which uses a third color to obtain a special
- 3D effect. Notice that a mid-line is only drawn for \l Box, \l
- HLine and \l VLine frames that are raised or sunken.
-
- \o The frame width is determined by the frame style, and the frameWidth()
- function is used to obtain the value defined for the style used.
- \endlist
-
- The margin between the frame and the contents of the frame can be
- customized with the QWidget::setContentsMargins() function.
-
- \target picture
- This table shows some of the combinations of styles and line widths:
-
- \image frames.png Table of frame styles
-*/
-
-
-/*!
- \enum QFrame::Shape
-
- This enum type defines the shapes of frame available.
-
- \value NoFrame QFrame draws nothing
- \value Box QFrame draws a box around its contents
- \value Panel QFrame draws a panel to make the contents appear
- raised or sunken
- \value StyledPanel draws a rectangular panel with a look that
- depends on the current GUI style. It can be raised or sunken.
- \value HLine QFrame draws a horizontal line that frames nothing
- (useful as separator)
- \value VLine QFrame draws a vertical line that frames nothing
- (useful as separator)
- \value WinPanel draws a rectangular panel that can be raised or
- sunken like those in Windows 2000. Specifying this shape sets
- the line width to 2 pixels. WinPanel is provided for compatibility.
- For GUI style independence we recommend using StyledPanel instead.
-
- \omitvalue GroupBoxPanel
- \omitvalue ToolBarPanel
- \omitvalue MenuBarPanel
- \omitvalue PopupPanel
- \omitvalue LineEditPanel
- \omitvalue TabWidgetPanel
-
- When it does not call QStyle, Shape interacts with QFrame::Shadow,
- the lineWidth() and the midLineWidth() to create the total result.
- See the picture of the frames in the main class documentation.
-
- \sa QFrame::Shadow QFrame::style() QStyle::drawPrimitive()
-*/
-
-
-/*!
- \enum QFrame::Shadow
-
- This enum type defines the types of shadow that are used to give
- a 3D effect to frames.
-
- \value Plain the frame and contents appear level with the
- surroundings; draws using the palette QPalette::WindowText color
- (without any 3D effect)
-
- \value Raised the frame and contents appear raised; draws a 3D
- raised line using the light and dark colors of the current color
- group
- \value Sunken the frame and contents appear sunken; draws a 3D
- sunken line using the light and dark colors of the current color
- group
-
- Shadow interacts with QFrame::Shape, the lineWidth() and the
- midLineWidth(). See the picture of the frames in the main class
- documentation.
-
- \sa QFrame::Shape lineWidth() midLineWidth()
-*/
-
-/*!
- \enum QFrame::StyleMask
-
- This enum defines two constants that can be used to extract the
- two components of frameStyle():
-
- \value Shadow_Mask The \l Shadow part of frameStyle()
- \value Shape_Mask The \l Shape part of frameStyle()
-
- \omitvalue MShadow
- \omitvalue MShape
-
- Normally, you don't need to use these, since frameShadow() and
- frameShape() already extract the \l Shadow and the \l Shape parts
- of frameStyle().
-
- \sa frameStyle(), setFrameStyle()
-*/
-
-/*!
- Constructs a frame widget with frame style \l NoFrame and a
- 1-pixel frame width.
-
- The \a parent and \a f arguments are passed to the QWidget
- constructor.
-*/
-
-QFrame::QFrame(QWidget* parent, Qt::WindowFlags f)
- : QWidget(*new QFramePrivate, parent, f)
-{
- Q_D(QFrame);
- d->init();
-}
-
-/*! \internal */
-QFrame::QFrame(QFramePrivate &dd, QWidget* parent, Qt::WindowFlags f)
- : QWidget(dd, parent, f)
-{
- Q_D(QFrame);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QFrame::QFrame(QWidget *parent, const char *name, Qt::WindowFlags f)
- : QWidget(*new QFramePrivate, parent, f)
-{
- Q_D(QFrame);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-#endif
-
-/*!
- Destroys the frame.
- */
-QFrame::~QFrame()
-{
-}
-
-/*!
- Returns the frame style.
-
- The default value is QFrame::Plain.
-
- \sa setFrameStyle(), frameShape(), frameShadow()
-*/
-int QFrame::frameStyle() const
-{
- Q_D(const QFrame);
- return d->frameStyle;
-}
-
-/*!
- \property QFrame::frameShape
- \brief the frame shape value from the frame style
-
- \sa frameStyle(), frameShadow()
-*/
-
-QFrame::Shape QFrame::frameShape() const
-{
- Q_D(const QFrame);
- return (Shape) (d->frameStyle & Shape_Mask);
-}
-
-void QFrame::setFrameShape(QFrame::Shape s)
-{
- Q_D(QFrame);
- setFrameStyle((d->frameStyle & Shadow_Mask) | s);
-}
-
-
-/*!
- \property QFrame::frameShadow
- \brief the frame shadow value from the frame style
-
- \sa frameStyle(), frameShape()
-*/
-QFrame::Shadow QFrame::frameShadow() const
-{
- Q_D(const QFrame);
- return (Shadow) (d->frameStyle & Shadow_Mask);
-}
-
-void QFrame::setFrameShadow(QFrame::Shadow s)
-{
- Q_D(QFrame);
- setFrameStyle((d->frameStyle & Shape_Mask) | s);
-}
-
-/*!
- Sets the frame style to \a style.
-
- The \a style is the bitwise OR between a frame shape and a frame
- shadow style. See the picture of the frames in the main class
- documentation.
-
- The frame shapes are given in \l{QFrame::Shape} and the shadow
- styles in \l{QFrame::Shadow}.
-
- If a mid-line width greater than 0 is specified, an additional
- line is drawn for \l Raised or \l Sunken \l Box, \l HLine, and \l
- VLine frames. The mid-color of the current color group is used for
- drawing middle lines.
-
- \sa frameStyle()
-*/
-
-void QFrame::setFrameStyle(int style)
-{
- Q_D(QFrame);
- if (!testAttribute(Qt::WA_WState_OwnSizePolicy)) {
- QSizePolicy sp;
-
- switch (style & Shape_Mask) {
- case HLine:
- sp = QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, QSizePolicy::Line);
- break;
- case VLine:
- sp = QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum, QSizePolicy::Line);
- break;
- default:
- sp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::Frame);
- }
- setSizePolicy(sp);
- setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- }
- d->frameStyle = (short)style;
- update();
- d->updateFrameWidth();
-}
-
-/*!
- \property QFrame::lineWidth
- \brief the line width
-
- Note that the \e total line width for frames used as separators
- (\l HLine and \l VLine) is specified by \l frameWidth.
-
- The default value is 1.
-
- \sa midLineWidth, frameWidth
-*/
-
-void QFrame::setLineWidth(int w)
-{
- Q_D(QFrame);
- if (short(w) == d->lineWidth)
- return;
- d->lineWidth = short(w);
- d->updateFrameWidth();
-}
-
-int QFrame::lineWidth() const
-{
- Q_D(const QFrame);
- return d->lineWidth;
-}
-
-/*!
- \property QFrame::midLineWidth
- \brief the width of the mid-line
-
- The default value is 0.
-
- \sa lineWidth, frameWidth
-*/
-
-void QFrame::setMidLineWidth(int w)
-{
- Q_D(QFrame);
- if (short(w) == d->midLineWidth)
- return;
- d->midLineWidth = short(w);
- d->updateFrameWidth();
-}
-
-int QFrame::midLineWidth() const
-{
- Q_D(const QFrame);
- return d->midLineWidth;
-}
-
-/*!
- \internal
- Updates the frame widths from the style.
-*/
-void QFramePrivate::updateStyledFrameWidths()
-{
- Q_Q(const QFrame);
- QStyleOptionFrameV3 opt;
- opt.initFrom(q);
- opt.lineWidth = lineWidth;
- opt.midLineWidth = midLineWidth;
- opt.frameShape = QFrame::Shape(frameStyle & QFrame::Shape_Mask);
-
- QRect cr = q->style()->subElementRect(QStyle::SE_ShapedFrameContents, &opt, q);
- leftFrameWidth = cr.left() - opt.rect.left();
- topFrameWidth = cr.top() - opt.rect.top();
- rightFrameWidth = opt.rect.right() - cr.right(),
- bottomFrameWidth = opt.rect.bottom() - cr.bottom();
- frameWidth = qMax(qMax(leftFrameWidth, rightFrameWidth),
- qMax(topFrameWidth, bottomFrameWidth));
-}
-
-/*!
- \internal
- Updated the frameWidth parameter.
-*/
-
-void QFramePrivate::updateFrameWidth()
-{
- Q_Q(QFrame);
- QRect fr = q->frameRect();
- updateStyledFrameWidths();
- q->setFrameRect(fr);
- setLayoutItemMargins(QStyle::SE_FrameLayoutItem);
-}
-
-/*!
- \property QFrame::frameWidth
- \brief the width of the frame that is drawn.
-
- Note that the frame width depends on the \l{QFrame::setFrameStyle()}{frame style},
- not only the line width and the mid-line width. For example, the style specified
- by \l NoFrame always has a frame width of 0, whereas the style \l Panel has a
- frame width equivalent to the line width.
-
- \sa lineWidth(), midLineWidth(), frameStyle()
-*/
-int QFrame::frameWidth() const
-{
- Q_D(const QFrame);
- return d->frameWidth;
-}
-
-
-/*!
- \property QFrame::frameRect
- \brief the frame's rectangle
-
- The frame's rectangle is the rectangle the frame is drawn in. By
- default, this is the entire widget. Setting the rectangle does
- does \e not cause a widget update. The frame rectangle is
- automatically adjusted when the widget changes size.
-
- If you set the rectangle to a null rectangle (for example,
- QRect(0, 0, 0, 0)), then the resulting frame rectangle is
- equivalent to the \link QWidget::rect() widget rectangle\endlink.
-*/
-
-QRect QFrame::frameRect() const
-{
- Q_D(const QFrame);
- QRect fr = contentsRect();
- fr.adjust(-d->leftFrameWidth, -d->topFrameWidth, d->rightFrameWidth, d->bottomFrameWidth);
- return fr;
-}
-
-void QFrame::setFrameRect(const QRect &r)
-{
- Q_D(QFrame);
- QRect cr = r.isValid() ? r : rect();
- cr.adjust(d->leftFrameWidth, d->topFrameWidth, -d->rightFrameWidth, -d->bottomFrameWidth);
- setContentsMargins(cr.left(), cr.top(), rect().right() - cr.right(), rect().bottom() - cr.bottom());
-}
-
-/*!\reimp
-*/
-QSize QFrame::sizeHint() const
-{
- Q_D(const QFrame);
- // Returns a size hint for the frame - for HLine and VLine
- // shapes, this is stretchable one way and 3 pixels wide the
- // other. For other shapes, QWidget::sizeHint() is used.
- switch (d->frameStyle & Shape_Mask) {
- case HLine:
- return QSize(-1,3);
- case VLine:
- return QSize(3,-1);
- default:
- return QWidget::sizeHint();
- }
-}
-
-/*!\reimp
-*/
-
-void QFrame::paintEvent(QPaintEvent *)
-{
- QPainter paint(this);
- drawFrame(&paint);
-}
-
-/*!
- \internal
-
- Mostly for the sake of Q3Frame
- */
-void QFrame::drawFrame(QPainter *p)
-{
- Q_D(QFrame);
- QStyleOptionFrameV3 opt;
- opt.init(this);
- int frameShape = d->frameStyle & QFrame::Shape_Mask;
- int frameShadow = d->frameStyle & QFrame::Shadow_Mask;
- opt.frameShape = Shape(int(opt.frameShape) | frameShape);
- opt.rect = frameRect();
- switch (frameShape) {
- case QFrame::Box:
- case QFrame::HLine:
- case QFrame::VLine:
- case QFrame::StyledPanel:
- case QFrame::Panel:
- opt.lineWidth = d->lineWidth;
- opt.midLineWidth = d->midLineWidth;
- break;
- default:
- // most frame styles do not handle customized line and midline widths
- // (see updateFrameWidth()).
- opt.lineWidth = d->frameWidth;
- break;
- }
-
- if (frameShadow == Sunken)
- opt.state |= QStyle::State_Sunken;
- else if (frameShadow == Raised)
- opt.state |= QStyle::State_Raised;
-
- style()->drawControl(QStyle::CE_ShapedFrame, &opt, p, this);
-}
-
-
-/*!\reimp
- */
-void QFrame::changeEvent(QEvent *ev)
-{
- Q_D(QFrame);
- if (ev->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || ev->type() == QEvent::MacSizeChange
-#endif
- )
- d->updateFrameWidth();
- QWidget::changeEvent(ev);
-}
-
-/*! \reimp */
-bool QFrame::event(QEvent *e)
-{
- if (e->type() == QEvent::ParentChange)
- d_func()->updateFrameWidth();
- bool result = QWidget::event(e);
- //this has to be done after the widget has been polished
- if (e->type() == QEvent::Polish)
- d_func()->updateFrameWidth();
- return result;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qframe.h b/src/gui/widgets/qframe.h
deleted file mode 100644
index 8596961e62..0000000000
--- a/src/gui/widgets/qframe.h
+++ /dev/null
@@ -1,148 +0,0 @@
-/****************************************************************************
-**
-** 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 QFRAME_H
-#define QFRAME_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QFramePrivate;
-
-class Q_GUI_EXPORT QFrame : public QWidget
-{
- Q_OBJECT
-
- Q_ENUMS(Shape Shadow)
- Q_PROPERTY(Shape frameShape READ frameShape WRITE setFrameShape)
- Q_PROPERTY(Shadow frameShadow READ frameShadow WRITE setFrameShadow)
- Q_PROPERTY(int lineWidth READ lineWidth WRITE setLineWidth)
- Q_PROPERTY(int midLineWidth READ midLineWidth WRITE setMidLineWidth)
- Q_PROPERTY(int frameWidth READ frameWidth)
- Q_PROPERTY(QRect frameRect READ frameRect WRITE setFrameRect DESIGNABLE false)
-
-public:
- explicit QFrame(QWidget* parent = 0, Qt::WindowFlags f = 0);
- ~QFrame();
-
- int frameStyle() const;
- void setFrameStyle(int);
-
- int frameWidth() const;
-
- QSize sizeHint() const;
-
- enum Shape {
- NoFrame = 0, // no frame
- Box = 0x0001, // rectangular box
- Panel = 0x0002, // rectangular panel
- WinPanel = 0x0003, // rectangular panel (Windows)
- HLine = 0x0004, // horizontal line
- VLine = 0x0005, // vertical line
- StyledPanel = 0x0006 // rectangular panel depending on the GUI style
-
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- ,PopupPanel = StyledPanel, // rectangular panel depending on the GUI style
- MenuBarPanel = StyledPanel,
- ToolBarPanel = StyledPanel,
- LineEditPanel = StyledPanel,
- TabWidgetPanel = StyledPanel,
- GroupBoxPanel = StyledPanel
-#endif
- };
- enum Shadow {
- Plain = 0x0010, // plain line
- Raised = 0x0020, // raised shadow effect
- Sunken = 0x0030 // sunken shadow effect
- };
-
- enum StyleMask {
- Shadow_Mask = 0x00f0, // mask for the shadow
- Shape_Mask = 0x000f // mask for the shape
-#if defined(QT3_SUPPORT)
- ,MShadow = Shadow_Mask,
- MShape = Shape_Mask
-#endif
- };
-
- Shape frameShape() const;
- void setFrameShape(Shape);
- Shadow frameShadow() const;
- void setFrameShadow(Shadow);
-
- int lineWidth() const;
- void setLineWidth(int);
-
- int midLineWidth() const;
- void setMidLineWidth(int);
-
- QRect frameRect() const;
- void setFrameRect(const QRect &);
-
-protected:
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *);
- void changeEvent(QEvent *);
- void drawFrame(QPainter *);
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QFrame(QWidget* parent, const char* name, Qt::WindowFlags f = 0);
-#endif
-
-protected:
- QFrame(QFramePrivate &dd, QWidget* parent = 0, Qt::WindowFlags f = 0);
-
-private:
- Q_DISABLE_COPY(QFrame)
- Q_DECLARE_PRIVATE(QFrame)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QFRAME_H
diff --git a/src/gui/widgets/qframe_p.h b/src/gui/widgets/qframe_p.h
deleted file mode 100644
index 173dfdc6fa..0000000000
--- a/src/gui/widgets/qframe_p.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** 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 QFRAME_P_H
-#define QFRAME_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qwidget_p.h"
-#include "qframe.h"
-
-QT_BEGIN_NAMESPACE
-
-class QFramePrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QFrame)
-public:
- QFramePrivate();
-
- void updateFrameWidth();
- void updateStyledFrameWidths();
-
- QRect frect;
- int frameStyle;
- short lineWidth;
- short midLineWidth;
- short frameWidth;
- short leftFrameWidth, rightFrameWidth;
- short topFrameWidth, bottomFrameWidth;
-
- inline void init();
-
-};
-
-QT_END_NAMESPACE
-
-#endif // QFRAME_P_H
diff --git a/src/gui/widgets/qgroupbox.cpp b/src/gui/widgets/qgroupbox.cpp
deleted file mode 100644
index 560ccd08c3..0000000000
--- a/src/gui/widgets/qgroupbox.cpp
+++ /dev/null
@@ -1,781 +0,0 @@
-/****************************************************************************
-**
-** 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 "qgroupbox.h"
-#ifndef QT_NO_GROUPBOX
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qdrawutil.h"
-#include "qevent.h"
-#include "qlayout.h"
-#include "qradiobutton.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qstylepainter.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include <private/qwidget_p.h>
-
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-class QGroupBoxPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QGroupBox)
-
-public:
- void skip();
- void init();
- void calculateFrame();
- QString title;
- int align;
-#ifndef QT_NO_SHORTCUT
- int shortcutId;
-#endif
-
- void _q_fixFocus(Qt::FocusReason reason);
- void _q_setChildrenEnabled(bool b);
- void click();
- bool flat;
- bool checkable;
- bool checked;
- bool hover;
- bool overCheckBox;
- QStyle::SubControl pressedControl;
-};
-
-/*!
- Initialize \a option with the values from this QGroupBox. This method
- is useful for subclasses when they need a QStyleOptionGroupBox, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QGroupBox::initStyleOption(QStyleOptionGroupBox *option) const
-{
- if (!option)
- return;
-
- Q_D(const QGroupBox);
- option->initFrom(this);
- option->text = d->title;
- option->lineWidth = 1;
- option->midLineWidth = 0;
- option->textAlignment = Qt::Alignment(d->align);
- option->activeSubControls |= d->pressedControl;
- option->subControls = QStyle::SC_GroupBoxFrame;
-
- if (d->hover)
- option->state |= QStyle::State_MouseOver;
- else
- option->state &= ~QStyle::State_MouseOver;
-
- if (d->flat)
- option->features |= QStyleOptionFrameV2::Flat;
-
- if (d->checkable) {
- option->subControls |= QStyle::SC_GroupBoxCheckBox;
- option->state |= (d->checked ? QStyle::State_On : QStyle::State_Off);
- if ((d->pressedControl == QStyle::SC_GroupBoxCheckBox
- || d->pressedControl == QStyle::SC_GroupBoxLabel) && (d->hover || d->overCheckBox))
- option->state |= QStyle::State_Sunken;
- }
-
- if (!option->palette.isBrushSet(isEnabled() ? QPalette::Active :
- QPalette::Disabled, QPalette::WindowText))
- option->textColor = QColor(style()->styleHint(QStyle::SH_GroupBox_TextLabelColor,
- option, this));
-
- if (!d->title.isEmpty())
- option->subControls |= QStyle::SC_GroupBoxLabel;
-}
-
-void QGroupBoxPrivate::click()
-{
- Q_Q(QGroupBox);
-
- QPointer<QGroupBox> guard(q);
- q->setChecked(!checked);
- if (!guard)
- return;
- emit q->clicked(checked);
-}
-
-/*!
- \class QGroupBox
- \brief The QGroupBox widget provides a group box frame with a title.
-
- \ingroup organizers
- \ingroup geomanagement
-
- A group box provides a frame, a title and a keyboard shortcut, and
- displays various other widgets inside itself. The title is on top,
- the keyboard shortcut moves keyboard focus to one of the group
- box's child widgets.
-
- QGroupBox also lets you set the \l title (normally set in the
- constructor) and the title's \l alignment. Group boxes can be
- \l checkable; child widgets in checkable group boxes are enabled or
- disabled depending on whether or not the group box is \l checked.
-
- You can minimize the space consumption of a group box by enabling
- the \l flat property. In most \l{QStyle}{styles}, enabling this
- property results in the removal of the left, right and bottom
- edges of the frame.
-
- QGroupBox doesn't automatically lay out the child widgets (which
- are often \l{QCheckBox}es or \l{QRadioButton}s but can be any
- widgets). The following example shows how we can set up a
- QGroupBox with a layout:
-
- \snippet examples/widgets/groupbox/window.cpp 2
-
- \table 100%
- \row \o \inlineimage windowsxp-groupbox.png Screenshot of a Windows XP style group box
- \o \inlineimage macintosh-groupbox.png Screenshot of a Macintosh style group box
- \o \inlineimage plastique-groupbox.png Screenshot of a Plastique style group box
- \row \o A \l{Windows XP Style Widget Gallery}{Windows XP style} group box.
- \o A \l{Macintosh Style Widget Gallery}{Macintosh style} group box.
- \o A \l{Plastique Style Widget Gallery}{Plastique style} group box.
- \endtable
-
- \sa QButtonGroup, {Group Box Example}
-*/
-
-
-
-/*!
- Constructs a group box widget with the given \a parent but with no title.
-*/
-
-QGroupBox::QGroupBox(QWidget *parent)
- : QWidget(*new QGroupBoxPrivate, parent, 0)
-{
- Q_D(QGroupBox);
- d->init();
-}
-
-/*!
- Constructs a group box with the given \a title and \a parent.
-*/
-
-QGroupBox::QGroupBox(const QString &title, QWidget *parent)
- : QWidget(*new QGroupBoxPrivate, parent, 0)
-{
- Q_D(QGroupBox);
- d->init();
- setTitle(title);
-}
-
-
-/*!
- Destroys the group box.
-*/
-QGroupBox::~QGroupBox()
-{
-}
-
-void QGroupBoxPrivate::init()
-{
- Q_Q(QGroupBox);
- align = Qt::AlignLeft;
-#ifndef QT_NO_SHORTCUT
- shortcutId = 0;
-#endif
- flat = false;
- checkable = false;
- checked = true;
- hover = false;
- overCheckBox = false;
- pressedControl = QStyle::SC_None;
- calculateFrame();
- q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred,
- QSizePolicy::GroupBox));
-}
-
-void QGroupBox::setTitle(const QString &title)
-{
- Q_D(QGroupBox);
- if (d->title == title) // no change
- return;
- d->title = title;
-#ifndef QT_NO_SHORTCUT
- releaseShortcut(d->shortcutId);
- d->shortcutId = grabShortcut(QKeySequence::mnemonic(title));
-#endif
- d->calculateFrame();
-
- update();
- updateGeometry();
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
-#endif
-}
-
-/*!
- \property QGroupBox::title
- \brief the group box title text
-
- The group box title text will have a keyboard shortcut if the title
- contains an ampersand ('&') followed by a letter.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qgroupbox.cpp 0
-
- In the example above, \key Alt+U moves the keyboard focus to the
- group box. See the \l {QShortcut#mnemonic}{QShortcut}
- documentation for details (to display an actual ampersand, use
- '&&').
-
- There is no default title text.
-
- \sa alignment
-*/
-
-QString QGroupBox::title() const
-{
- Q_D(const QGroupBox);
- return d->title;
-}
-
-/*!
- \property QGroupBox::alignment
- \brief the alignment of the group box title.
-
- Most styles place the title at the top of the frame. The horizontal
- alignment of the title can be specified using single values from
- the following list:
-
- \list
- \i Qt::AlignLeft aligns the title text with the left-hand side of the group box.
- \i Qt::AlignRight aligns the title text with the right-hand side of the group box.
- \i Qt::AlignHCenter aligns the title text with the horizontal center of the group box.
- \endlist
-
- The default alignment is Qt::AlignLeft.
-
- \sa Qt::Alignment
-*/
-Qt::Alignment QGroupBox::alignment() const
-{
- Q_D(const QGroupBox);
- return QFlag(d->align);
-}
-
-void QGroupBox::setAlignment(int alignment)
-{
- Q_D(QGroupBox);
- d->align = alignment;
- updateGeometry();
- update();
-}
-
-/*! \reimp
-*/
-void QGroupBox::resizeEvent(QResizeEvent *e)
-{
- QWidget::resizeEvent(e);
-}
-
-/*! \reimp
-*/
-
-void QGroupBox::paintEvent(QPaintEvent *)
-{
- QStylePainter paint(this);
- QStyleOptionGroupBox option;
- initStyleOption(&option);
- paint.drawComplexControl(QStyle::CC_GroupBox, option);
-}
-
-/*! \reimp */
-bool QGroupBox::event(QEvent *e)
-{
- Q_D(QGroupBox);
-#ifndef QT_NO_SHORTCUT
- if (e->type() == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- if (se->shortcutId() == d->shortcutId) {
- if (!isCheckable()) {
- d->_q_fixFocus(Qt::ShortcutFocusReason);
- } else {
- d->click();
- setFocus(Qt::ShortcutFocusReason);
- }
- return true;
- }
- }
-#endif
- QStyleOptionGroupBox box;
- initStyleOption(&box);
- switch (e->type()) {
- case QEvent::HoverEnter:
- case QEvent::HoverMove: {
- QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- static_cast<QHoverEvent *>(e)->pos(),
- this);
- bool oldHover = d->hover;
- d->hover = d->checkable && (control == QStyle::SC_GroupBoxLabel || control == QStyle::SC_GroupBoxCheckBox);
- if (oldHover != d->hover) {
- QRect rect = style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this)
- | style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxLabel, this);
- update(rect);
- }
- return true;
- }
- case QEvent::HoverLeave:
- d->hover = false;
- if (d->checkable) {
- QRect rect = style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this)
- | style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxLabel, this);
- update(rect);
- }
- return true;
- case QEvent::KeyPress: {
- QKeyEvent *k = static_cast<QKeyEvent*>(e);
- if (!k->isAutoRepeat() && (k->key() == Qt::Key_Select || k->key() == Qt::Key_Space)) {
- d->pressedControl = QStyle::SC_GroupBoxCheckBox;
- update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this));
- return true;
- }
- break;
- }
- case QEvent::KeyRelease: {
- QKeyEvent *k = static_cast<QKeyEvent*>(e);
- if (!k->isAutoRepeat() && (k->key() == Qt::Key_Select || k->key() == Qt::Key_Space)) {
- bool toggle = (d->pressedControl == QStyle::SC_GroupBoxLabel
- || d->pressedControl == QStyle::SC_GroupBoxCheckBox);
- d->pressedControl = QStyle::SC_None;
- if (toggle)
- d->click();
- return true;
- }
- break;
- }
- default:
- break;
- }
- return QWidget::event(e);
-}
-
-/*!\reimp */
-void QGroupBox::childEvent(QChildEvent *c)
-{
- Q_D(QGroupBox);
- if (c->type() != QEvent::ChildAdded || !c->child()->isWidgetType())
- return;
- QWidget *w = (QWidget*)c->child();
- if (d->checkable) {
- if (d->checked) {
- if (!w->testAttribute(Qt::WA_ForceDisabled))
- w->setEnabled(true);
- } else {
- if (w->isEnabled()) {
- w->setEnabled(false);
- w->setAttribute(Qt::WA_ForceDisabled, false);
- }
- }
- }
-}
-
-
-/*!
- \internal
-
- This private slot finds a widget in this group box that can accept
- focus, and gives the focus to that widget.
-*/
-
-void QGroupBoxPrivate::_q_fixFocus(Qt::FocusReason reason)
-{
- Q_Q(QGroupBox);
- QWidget *fw = q->focusWidget();
- if (!fw || fw == q) {
- QWidget * best = 0;
- QWidget * candidate = 0;
- QWidget * w = q;
- while ((w = w->nextInFocusChain()) != q) {
- if (q->isAncestorOf(w) && (w->focusPolicy() & Qt::TabFocus) == Qt::TabFocus && w->isVisibleTo(q)) {
- if (!best && qobject_cast<QRadioButton*>(w) && ((QRadioButton*)w)->isChecked())
- // we prefer a checked radio button or a widget that
- // already has focus, if there is one
- best = w;
- else
- if (!candidate)
- // but we'll accept anything that takes focus
- candidate = w;
- }
- }
- if (best)
- fw = best;
- else if (candidate)
- fw = candidate;
- }
- if (fw)
- fw->setFocus(reason);
-}
-
-/*
- Sets the right frame rect depending on the title.
-*/
-void QGroupBoxPrivate::calculateFrame()
-{
- Q_Q(QGroupBox);
- QStyleOptionGroupBox box;
- q->initStyleOption(&box);
- QRect contentsRect = q->style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxContents, q);
- q->setContentsMargins(contentsRect.left() - box.rect.left(), contentsRect.top() - box.rect.top(),
- box.rect.right() - contentsRect.right(), box.rect.bottom() - contentsRect.bottom());
- setLayoutItemMargins(QStyle::SE_GroupBoxLayoutItem, &box);
-}
-
-/*! \reimp
- */
-void QGroupBox::focusInEvent(QFocusEvent *fe)
-{ // note no call to super
- Q_D(QGroupBox);
- if (focusPolicy() == Qt::NoFocus) {
- d->_q_fixFocus(fe->reason());
- } else {
- QWidget::focusInEvent(fe);
- }
-}
-
-
-/*!
- \reimp
-*/
-QSize QGroupBox::minimumSizeHint() const
-{
- Q_D(const QGroupBox);
- QStyleOptionGroupBox option;
- initStyleOption(&option);
-
- QFontMetrics metrics(fontMetrics());
-
- int baseWidth = metrics.width(d->title) + metrics.width(QLatin1Char(' '));
- int baseHeight = metrics.height();
- if (d->checkable) {
- baseWidth += style()->pixelMetric(QStyle::PM_IndicatorWidth);
- baseWidth += style()->pixelMetric(QStyle::PM_CheckBoxLabelSpacing);
- baseHeight = qMax(baseHeight, style()->pixelMetric(QStyle::PM_IndicatorHeight));
- }
-
- QSize size = style()->sizeFromContents(QStyle::CT_GroupBox, &option, QSize(baseWidth, baseHeight), this);
- return size.expandedTo(QWidget::minimumSizeHint());
-}
-
-/*!
- \property QGroupBox::flat
- \brief whether the group box is painted flat or has a frame
-
- A group box usually consists of a surrounding frame with a title
- at the top. If this property is enabled, only the top part of the frame is
- drawn in most styles; otherwise the whole frame is drawn.
-
- By default, this property is disabled; i.e. group boxes are not flat unless
- explicitly specified.
-
- \bold{Note:} In some styles, flat and non-flat group boxes have similar
- representations and may not be as distinguishable as they are in other
- styles.
-
- \sa title
-*/
-bool QGroupBox::isFlat() const
-{
- Q_D(const QGroupBox);
- return d->flat;
-}
-
-void QGroupBox::setFlat(bool b)
-{
- Q_D(QGroupBox);
- if (d->flat == b)
- return;
- d->flat = b;
- updateGeometry();
- update();
-}
-
-
-/*!
- \property QGroupBox::checkable
- \brief whether the group box has a checkbox in its title
-
- If this property is true, the group box displays its title using
- a checkbox in place of an ordinary label. If the checkbox is checked,
- the group box's children are enabled; otherwise they are disabled and
- inaccessible.
-
- By default, group boxes are not checkable.
-
- If this property is enabled for a group box, it will also be initially
- checked to ensure that its contents are enabled.
-
- \sa checked
-*/
-void QGroupBox::setCheckable(bool checkable)
-{
- Q_D(QGroupBox);
-
- bool wasCheckable = d->checkable;
- d->checkable = checkable;
-
- if (checkable) {
- setChecked(true);
- if (!wasCheckable) {
- setFocusPolicy(Qt::StrongFocus);
- d->_q_setChildrenEnabled(true);
- updateGeometry();
- }
- } else {
- if (wasCheckable) {
- setFocusPolicy(Qt::NoFocus);
- d->_q_setChildrenEnabled(true);
- updateGeometry();
- }
- d->_q_setChildrenEnabled(true);
- }
-
- if (wasCheckable != checkable) {
- d->calculateFrame();
- update();
- }
-}
-
-bool QGroupBox::isCheckable() const
-{
- Q_D(const QGroupBox);
- return d->checkable;
-}
-
-
-bool QGroupBox::isChecked() const
-{
- Q_D(const QGroupBox);
- return d->checkable && d->checked;
-}
-
-
-/*!
- \fn void QGroupBox::toggled(bool on)
-
- If the group box is checkable, this signal is emitted when the check box
- is toggled. \a on is true if the check box is checked; otherwise it is false.
-
- \sa checkable
-*/
-
-
-/*!
- \fn void QGroupBox::clicked(bool checked)
- \since 4.2
-
- This signal is emitted when the check box is activated (i.e. pressed down
- then released while the mouse cursor is inside the button), or when the
- shortcut key is typed, Notably, this signal is \e not emitted if you call
- setChecked().
-
- If the check box is checked \a checked is true; it is false if the check
- box is unchecked.
-
- \sa checkable, toggled(), checked
-*/
-
-/*!
- \property QGroupBox::checked
- \brief whether the group box is checked
-
- If the group box is checkable, it is displayed with a check box.
- If the check box is checked, the group box's children are enabled;
- otherwise the children are disabled and are inaccessible to the user.
-
- By default, checkable group boxes are also checked.
-
- \sa checkable
-*/
-void QGroupBox::setChecked(bool b)
-{
- Q_D(QGroupBox);
- if (d->checkable && b != d->checked) {
- update();
- d->checked = b;
- d->_q_setChildrenEnabled(b);
- emit toggled(b);
- }
-}
-
-/*
- sets all children of the group box except the qt_groupbox_checkbox
- to either disabled/enabled
-*/
-void QGroupBoxPrivate::_q_setChildrenEnabled(bool b)
-{
- Q_Q(QGroupBox);
- QObjectList childList = q->children();
- for (int i = 0; i < childList.size(); ++i) {
- QObject *o = childList.at(i);
- if (o->isWidgetType()) {
- QWidget *w = static_cast<QWidget *>(o);
- if (b) {
- if (!w->testAttribute(Qt::WA_ForceDisabled))
- w->setEnabled(true);
- } else {
- if (w->isEnabled()) {
- w->setEnabled(false);
- w->setAttribute(Qt::WA_ForceDisabled, false);
- }
- }
- }
- }
-}
-
-/*! \reimp */
-void QGroupBox::changeEvent(QEvent *ev)
-{
- Q_D(QGroupBox);
- if (ev->type() == QEvent::EnabledChange) {
- if (d->checkable && isEnabled()) {
- // we are being enabled - disable children
- if (!d->checked)
- d->_q_setChildrenEnabled(false);
- }
- } else if (ev->type() == QEvent::FontChange
-#ifdef Q_WS_MAC
- || ev->type() == QEvent::MacSizeChange
-#endif
- || ev->type() == QEvent::StyleChange) {
- d->calculateFrame();
- }
- QWidget::changeEvent(ev);
-}
-
-/*! \reimp */
-void QGroupBox::mousePressEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
-
- Q_D(QGroupBox);
- QStyleOptionGroupBox box;
- initStyleOption(&box);
- d->pressedControl = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- event->pos(), this);
- if (d->checkable && (d->pressedControl & (QStyle::SC_GroupBoxCheckBox | QStyle::SC_GroupBoxLabel))) {
- d->overCheckBox = true;
- update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this));
- }
-}
-
-/*! \reimp */
-void QGroupBox::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QGroupBox);
- QStyleOptionGroupBox box;
- initStyleOption(&box);
- QStyle::SubControl pressed = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- event->pos(), this);
- bool oldOverCheckBox = d->overCheckBox;
- d->overCheckBox = (pressed == QStyle::SC_GroupBoxCheckBox || pressed == QStyle::SC_GroupBoxLabel);
- if (d->checkable && (d->pressedControl == QStyle::SC_GroupBoxCheckBox || d->pressedControl == QStyle::SC_GroupBoxLabel)
- && (d->overCheckBox != oldOverCheckBox))
- update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this));
-}
-
-/*! \reimp */
-void QGroupBox::mouseReleaseEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
-
- Q_D(QGroupBox);
- QStyleOptionGroupBox box;
- initStyleOption(&box);
- QStyle::SubControl released = style()->hitTestComplexControl(QStyle::CC_GroupBox, &box,
- event->pos(), this);
- bool toggle = d->checkable && (released == QStyle::SC_GroupBoxLabel
- || released == QStyle::SC_GroupBoxCheckBox);
- d->pressedControl = QStyle::SC_None;
- d->overCheckBox = false;
- if (toggle)
- d->click();
- else if (d->checkable)
- update(style()->subControlRect(QStyle::CC_GroupBox, &box, QStyle::SC_GroupBoxCheckBox, this));
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QGroupBox::QGroupBox(QWidget *parent, const char *name)
- : QWidget(*new QGroupBoxPrivate, parent, 0)
-{
- Q_D(QGroupBox);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QGroupBox::QGroupBox(const QString &title, QWidget *parent, const char *name)
- : QWidget(*new QGroupBoxPrivate, parent, 0)
-{
- Q_D(QGroupBox);
- setObjectName(QString::fromAscii(name));
- d->init();
- setTitle(title);
-}
-#endif // QT3_SUPPORT
-
-QT_END_NAMESPACE
-
-#include "moc_qgroupbox.cpp"
-
-#endif //QT_NO_GROUPBOX
diff --git a/src/gui/widgets/qgroupbox.h b/src/gui/widgets/qgroupbox.h
deleted file mode 100644
index 84dc886bb9..0000000000
--- a/src/gui/widgets/qgroupbox.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** 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 QGROUPBOX_H
-#define QGROUPBOX_H
-
-#include <QtGui/qframe.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_GROUPBOX
-
-class QGroupBoxPrivate;
-class QStyleOptionGroupBox;
-class Q_GUI_EXPORT QGroupBox : public QWidget
-{
- Q_OBJECT
-
- Q_PROPERTY(QString title READ title WRITE setTitle)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
- Q_PROPERTY(bool flat READ isFlat WRITE setFlat)
- Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable)
- Q_PROPERTY(bool checked READ isChecked WRITE setChecked DESIGNABLE isCheckable NOTIFY toggled USER true)
-public:
- explicit QGroupBox(QWidget* parent=0);
- explicit QGroupBox(const QString &title, QWidget* parent=0);
- ~QGroupBox();
-
- QString title() const;
- void setTitle(const QString &title);
-
- Qt::Alignment alignment() const;
- void setAlignment(int alignment);
-
- QSize minimumSizeHint() const;
-
- bool isFlat() const;
- void setFlat(bool flat);
- bool isCheckable() const;
- void setCheckable(bool checkable);
- bool isChecked() const;
-
-public Q_SLOTS:
- void setChecked(bool checked);
-
-Q_SIGNALS:
- void clicked(bool checked = false);
- void toggled(bool);
-
-protected:
- bool event(QEvent *event);
- void childEvent(QChildEvent *event);
- void resizeEvent(QResizeEvent *event);
- void paintEvent(QPaintEvent *event);
- void focusInEvent(QFocusEvent *event);
- void changeEvent(QEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void initStyleOption(QStyleOptionGroupBox *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QGroupBox(QWidget* parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QGroupBox(const QString &title, QWidget* parent, const char* name);
-#endif
-
-private:
- Q_DISABLE_COPY(QGroupBox)
- Q_DECLARE_PRIVATE(QGroupBox)
- Q_PRIVATE_SLOT(d_func(), void _q_setChildrenEnabled(bool b))
-};
-
-#endif // QT_NO_GROUPBOX
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QGROUPBOX_H
diff --git a/src/gui/widgets/qlabel.cpp b/src/gui/widgets/qlabel.cpp
deleted file mode 100644
index 4714d2f2c9..0000000000
--- a/src/gui/widgets/qlabel.cpp
+++ /dev/null
@@ -1,1718 +0,0 @@
-/****************************************************************************
-**
-** 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 "qpainter.h"
-#include "qevent.h"
-#include "qdrawutil.h"
-#include "qapplication.h"
-#include "qabstractbutton.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include <limits.h>
-#include "qaction.h"
-#include "qclipboard.h"
-#include <qdebug.h>
-#include <qurl.h>
-#include "qlabel_p.h"
-#include "private/qstylesheetstyle_p.h"
-#include <qmath.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QLabel
- \brief The QLabel widget provides a text or image display.
-
- \ingroup basicwidgets
-
- QLabel is used for displaying text or an image. No user
- interaction functionality is provided. The visual appearance of
- the label can be configured in various ways, and it can be used
- for specifying a focus mnemonic key for another widget.
-
- A QLabel can contain any of the following content types:
-
- \table
- \header \o Content \o Setting
- \row \o Plain text
- \o Pass a QString to setText().
- \row \o Rich text
- \o Pass a QString that contains rich text to setText().
- \row \o A pixmap
- \o Pass a QPixmap to setPixmap().
- \row \o A movie
- \o Pass a QMovie to setMovie().
- \row \o A number
- \o Pass an \e int or a \e double to setNum(), which converts
- the number to plain text.
- \row \o Nothing
- \o The same as an empty plain text. This is the default. Set
- by clear().
- \endtable
-
- When the content is changed using any of these functions, any
- previous content is cleared.
-
- By default, labels display \l{alignment}{left-aligned, vertically-centered}
- text and images, where any tabs in the text to be displayed are
- \l{Qt::TextExpandTabs}{automatically expanded}. However, the look
- of a QLabel can be adjusted and fine-tuned in several ways.
-
- The positioning of the content within the QLabel widget area can
- be tuned with setAlignment() and setIndent(). Text content can
- also wrap lines along word boundaries with setWordWrap(). For
- example, this code sets up a sunken panel with a two-line text in
- the bottom right corner (both lines being flush with the right
- side of the label):
-
- \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 0
-
- The properties and functions QLabel inherits from QFrame can also
- be used to specify the widget frame to be used for any given label.
-
- A QLabel is often used as a label for an interactive widget. For
- this use QLabel provides a useful mechanism for adding an
- mnemonic (see QKeySequence) that will set the keyboard focus to
- the other widget (called the QLabel's "buddy"). For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 1
-
- In this example, keyboard focus is transferred to the label's
- buddy (the QLineEdit) when the user presses Alt+P. If the buddy
- was a button (inheriting from QAbstractButton), triggering the
- mnemonic would emulate a button click.
-
- \table 100%
- \row
- \o \inlineimage macintosh-label.png Screenshot of a Macintosh style label
- \o A label shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row
- \o \inlineimage plastique-label.png Screenshot of a Plastique style label
- \o A label shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \row
- \o \inlineimage windowsxp-label.png Screenshot of a Windows XP style label
- \o A label shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \endtable
-
- \sa QLineEdit, QTextEdit, QPixmap, QMovie,
- {fowler}{GUI Design Handbook: Label}
-*/
-
-#ifndef QT_NO_PICTURE
-/*!
- Returns the label's picture or 0 if the label doesn't have a
- picture.
-*/
-
-const QPicture *QLabel::picture() const
-{
- Q_D(const QLabel);
- return d->picture;
-}
-#endif
-
-
-/*!
- Constructs an empty label.
-
- The \a parent and widget flag \a f, arguments are passed
- to the QFrame constructor.
-
- \sa setAlignment(), setFrameStyle(), setIndent()
-*/
-QLabel::QLabel(QWidget *parent, Qt::WindowFlags f)
- : QFrame(*new QLabelPrivate(), parent, f)
-{
- Q_D(QLabel);
- d->init();
-}
-
-/*!
- Constructs a label that displays the text, \a text.
-
- The \a parent and widget flag \a f, arguments are passed
- to the QFrame constructor.
-
- \sa setText(), setAlignment(), setFrameStyle(), setIndent()
-*/
-QLabel::QLabel(const QString &text, QWidget *parent, Qt::WindowFlags f)
- : QFrame(*new QLabelPrivate(), parent, f)
-{
- Q_D(QLabel);
- d->init();
- setText(text);
-}
-
-
-#ifdef QT3_SUPPORT
-/*! \obsolete
- Constructs an empty label.
-
- The \a parent, \a name and widget flag \a f, arguments are passed
- to the QFrame constructor.
-
- \sa setAlignment(), setFrameStyle(), setIndent()
-*/
-
-QLabel::QLabel(QWidget *parent, const char *name, Qt::WindowFlags f)
- : QFrame(*new QLabelPrivate(), parent, f)
-{
- Q_D(QLabel);
- if (name)
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-
-/*! \obsolete
- Constructs a label that displays the text, \a text.
-
- The \a parent, \a name and widget flag \a f, arguments are passed
- to the QFrame constructor.
-
- \sa setText(), setAlignment(), setFrameStyle(), setIndent()
-*/
-
-QLabel::QLabel(const QString &text, QWidget *parent, const char *name,
- Qt::WindowFlags f)
- : QFrame(*new QLabelPrivate(), parent, f)
-{
- Q_D(QLabel);
- if (name)
- setObjectName(QString::fromAscii(name));
- d->init();
- setText(text);
-}
-
-
-/*! \obsolete
- Constructs a label that displays the text \a text. The label has a
- buddy widget, \a buddy.
-
- If the \a text contains an underlined letter (a letter preceded by
- an ampersand, \&), when the user presses Alt+ the underlined letter,
- focus is passed to the buddy widget.
-
- The \a parent, \a name and widget flag, \a f, arguments are passed
- to the QFrame constructor.
-
- \sa setText(), setBuddy(), setAlignment(), setFrameStyle(),
- setIndent()
-*/
-QLabel::QLabel(QWidget *buddy, const QString &text,
- QWidget *parent, const char *name, Qt::WindowFlags f)
- : QFrame(*new QLabelPrivate(), parent, f)
-{
- Q_D(QLabel);
- if (name)
- setObjectName(QString::fromAscii(name));
- d->init();
-#ifndef QT_NO_SHORTCUT
- setBuddy(buddy);
-#endif
- setText(text);
-}
-#endif //QT3_SUPPORT
-
-/*!
- Destroys the label.
-*/
-
-QLabel::~QLabel()
-{
- Q_D(QLabel);
- d->clearContents();
-}
-
-void QLabelPrivate::init()
-{
- Q_Q(QLabel);
-
- valid_hints = false;
- margin = 0;
-#ifndef QT_NO_MOVIE
- movie = 0;
-#endif
-#ifndef QT_NO_SHORTCUT
- shortcutId = 0;
-#endif
- pixmap = 0;
- scaledpixmap = 0;
- cachedimage = 0;
-#ifndef QT_NO_PICTURE
- picture = 0;
-#endif
- align = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextExpandTabs;
- indent = -1;
- scaledcontents = false;
- textLayoutDirty = false;
- textDirty = false;
- textformat = Qt::AutoText;
- control = 0;
- textInteractionFlags = Qt::LinksAccessibleByMouse;
- isRichText = false;
- isTextLabel = false;
-
- q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred,
- QSizePolicy::Label));
-
-#ifndef QT_NO_CURSOR
- validCursor = false;
- onAnchor = false;
-#endif
-
- openExternalLinks = false;
-
- setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
-}
-
-
-/*!
- \property QLabel::text
- \brief the label's text
-
- If no text has been set this will return an empty string. Setting
- the text clears any previous content.
-
- The text will be interpreted either as plain text or as rich
- text, depending on the text format setting; see setTextFormat().
- The default setting is Qt::AutoText; i.e. QLabel will try to
- auto-detect the format of the text set.
-
- If a buddy has been set, the buddy mnemonic key is updated
- from the new text.
-
- Note that QLabel is well-suited to display small rich text
- documents, such as small documents that get their document
- specific settings (font, text color, link color) from the label's
- palette and font properties. For large documents, use QTextEdit
- in read-only mode instead. QTextEdit can also provide a scroll bar
- when necessary.
-
- \note This function enables mouse tracking if \a text contains rich
- text.
-
- \sa setTextFormat(), setBuddy(), alignment
-*/
-
-void QLabel::setText(const QString &text)
-{
- Q_D(QLabel);
- if (d->text == text)
- return;
-
- QTextControl *oldControl = d->control;
- d->control = 0;
-
- d->clearContents();
- d->text = text;
- d->isTextLabel = true;
- d->textDirty = true;
- d->isRichText = d->textformat == Qt::RichText
- || (d->textformat == Qt::AutoText && Qt::mightBeRichText(d->text));
-
- d->control = oldControl;
-
- if (d->needTextControl()) {
- d->ensureTextControl();
- } else {
- delete d->control;
- d->control = 0;
- }
-
- if (d->isRichText) {
- setMouseTracking(true);
- } else {
- // Note: mouse tracking not disabled intentionally
- }
-
-#ifndef QT_NO_SHORTCUT
- if (d->buddy)
- d->updateShortcut();
-#endif
-
- d->updateLabel();
-}
-
-QString QLabel::text() const
-{
- Q_D(const QLabel);
- return d->text;
-}
-
-/*!
- Clears any label contents.
-*/
-
-void QLabel::clear()
-{
- Q_D(QLabel);
- d->clearContents();
- d->updateLabel();
-}
-
-/*!
- \property QLabel::pixmap
- \brief the label's pixmap
-
- If no pixmap has been set this will return 0.
-
- Setting the pixmap clears any previous content. The buddy
- shortcut, if any, is disabled.
-*/
-void QLabel::setPixmap(const QPixmap &pixmap)
-{
- Q_D(QLabel);
- if (!d->pixmap || d->pixmap->cacheKey() != pixmap.cacheKey()) {
- d->clearContents();
- d->pixmap = new QPixmap(pixmap);
- }
-
- if (d->pixmap->depth() == 1 && !d->pixmap->mask())
- d->pixmap->setMask(*((QBitmap *)d->pixmap));
-
- d->updateLabel();
-}
-
-const QPixmap *QLabel::pixmap() const
-{
- Q_D(const QLabel);
- return d->pixmap;
-}
-
-#ifndef QT_NO_PICTURE
-/*!
- Sets the label contents to \a picture. Any previous content is
- cleared.
-
- The buddy shortcut, if any, is disabled.
-
- \sa picture(), setBuddy()
-*/
-
-void QLabel::setPicture(const QPicture &picture)
-{
- Q_D(QLabel);
- d->clearContents();
- d->picture = new QPicture(picture);
-
- d->updateLabel();
-}
-#endif // QT_NO_PICTURE
-
-/*!
- Sets the label contents to plain text containing the textual
- representation of integer \a num. Any previous content is cleared.
- Does nothing if the integer's string representation is the same as
- the current contents of the label.
-
- The buddy shortcut, if any, is disabled.
-
- \sa setText(), QString::setNum(), setBuddy()
-*/
-
-void QLabel::setNum(int num)
-{
- QString str;
- str.setNum(num);
- setText(str);
-}
-
-/*!
- \overload
-
- Sets the label contents to plain text containing the textual
- representation of double \a num. Any previous content is cleared.
- Does nothing if the double's string representation is the same as
- the current contents of the label.
-
- The buddy shortcut, if any, is disabled.
-
- \sa setText(), QString::setNum(), setBuddy()
-*/
-
-void QLabel::setNum(double num)
-{
- QString str;
- str.setNum(num);
- setText(str);
-}
-
-/*!
- \property QLabel::alignment
- \brief the alignment of the label's contents
-
- By default, the contents of the label are left-aligned and vertically-centered.
-
- \sa text
-*/
-
-void QLabel::setAlignment(Qt::Alignment alignment)
-{
- Q_D(QLabel);
- if (alignment == (d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)))
- return;
- d->align = (d->align & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask))
- | (alignment & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
-
- d->updateLabel();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use setAlignment(Qt::Alignment) instead.
-
- If \a alignment specifies text flags as well, use setTextFormat()
- to set those.
-*/
-void QLabel::setAlignment(int alignment)
-{
- Q_D(QLabel);
- d->align = alignment & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask|Qt::TextWordWrap);
- setAlignment(Qt::Alignment(QFlag(alignment)));
-}
-#endif
-
-Qt::Alignment QLabel::alignment() const
-{
- Q_D(const QLabel);
- return QFlag(d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
-}
-
-
-/*!
- \property QLabel::wordWrap
- \brief the label's word-wrapping policy
-
- If this property is true then label text is wrapped where
- necessary at word-breaks; otherwise it is not wrapped at all.
-
- By default, word wrap is disabled.
-
- \sa text
-*/
-void QLabel::setWordWrap(bool on)
-{
- Q_D(QLabel);
- if (on)
- d->align |= Qt::TextWordWrap;
- else
- d->align &= ~Qt::TextWordWrap;
-
- d->updateLabel();
-}
-
-bool QLabel::wordWrap() const
-{
- Q_D(const QLabel);
- return d->align & Qt::TextWordWrap;
-}
-
-/*!
- \property QLabel::indent
- \brief the label's text indent in pixels
-
- If a label displays text, the indent applies to the left edge if
- alignment() is Qt::AlignLeft, to the right edge if alignment() is
- Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and
- to to the bottom edge if alignment() is Qt::AlignBottom.
-
- If indent is negative, or if no indent has been set, the label
- computes the effective indent as follows: If frameWidth() is 0,
- the effective indent becomes 0. If frameWidth() is greater than 0,
- the effective indent becomes half the width of the "x" character
- of the widget's current font().
-
- By default, the indent is -1, meaning that an effective indent is
- calculating in the manner described above.
-
- \sa alignment, margin, frameWidth(), font()
-*/
-
-void QLabel::setIndent(int indent)
-{
- Q_D(QLabel);
- d->indent = indent;
- d->updateLabel();
-}
-
-int QLabel::indent() const
-{
- Q_D(const QLabel);
- return d->indent;
-}
-
-
-/*!
- \property QLabel::margin
- \brief the width of the margin
-
- The margin is the distance between the innermost pixel of the
- frame and the outermost pixel of contents.
-
- The default margin is 0.
-
- \sa indent
-*/
-int QLabel::margin() const
-{
- Q_D(const QLabel);
- return d->margin;
-}
-
-void QLabel::setMargin(int margin)
-{
- Q_D(QLabel);
- if (d->margin == margin)
- return;
- d->margin = margin;
- d->updateLabel();
-}
-
-/*!
- Returns the size that will be used if the width of the label is \a
- w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned
-*/
-QSize QLabelPrivate::sizeForWidth(int w) const
-{
- Q_Q(const QLabel);
- if(q->minimumWidth() > 0)
- w = qMax(w, q->minimumWidth());
- QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin);
-
- QRect br;
-
- int hextra = 2 * margin;
- int vextra = hextra;
- QFontMetrics fm = q->fontMetrics();
-
- if (pixmap && !pixmap->isNull())
- br = pixmap->rect();
-#ifndef QT_NO_PICTURE
- else if (picture && !picture->isNull())
- br = picture->boundingRect();
-#endif
-#ifndef QT_NO_MOVIE
- else if (movie && !movie->currentPixmap().isNull())
- br = movie->currentPixmap().rect();
-#endif
- else if (isTextLabel) {
- int align = QStyle::visualAlignment(textDirection(), QFlag(this->align));
- // Add indentation
- int m = indent;
-
- if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
- m = fm.width(QLatin1Char('x')) - margin*2;
- if (m > 0) {
- if ((align & Qt::AlignLeft) || (align & Qt::AlignRight))
- hextra += m;
- if ((align & Qt::AlignTop) || (align & Qt::AlignBottom))
- vextra += m;
- }
-
- if (control) {
- ensureTextLayouted();
- const qreal oldTextWidth = control->textWidth();
- // Calculate the length of document if w is the width
- if (align & Qt::TextWordWrap) {
- if (w >= 0) {
- w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent
- control->setTextWidth(w);
- } else {
- control->adjustSize();
- }
- } else {
- control->setTextWidth(-1);
- }
-
- QSizeF controlSize = control->size();
- br = QRect(QPoint(0, 0), QSize(qCeil(controlSize.width()), qCeil(controlSize.height())));
-
- // restore state
- control->setTextWidth(oldTextWidth);
- } else {
- // Turn off center alignment in order to avoid rounding errors for centering,
- // since centering involves a division by 2. At the end, all we want is the size.
- int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter);
- if (hasShortcut) {
- flags |= Qt::TextShowMnemonic;
- QStyleOption opt;
- opt.initFrom(q);
- if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q))
- flags |= Qt::TextHideMnemonic;
- }
-
- bool tryWidth = (w < 0) && (align & Qt::TextWordWrap);
- if (tryWidth)
- w = qMin(fm.averageCharWidth() * 80, q->maximumSize().width());
- else if (w < 0)
- w = 2000;
- w -= (hextra + contentsMargin.width());
- br = fm.boundingRect(0, 0, w ,2000, flags, text);
- if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2)
- br = fm.boundingRect(0, 0, w/2, 2000, flags, text);
- if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4)
- br = fm.boundingRect(0, 0, w/4, 2000, flags, text);
- }
- } else {
- br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing()));
- }
-
- const QSize contentsSize(br.width() + hextra, br.height() + vextra);
- return (contentsSize + contentsMargin).expandedTo(q->minimumSize());
-}
-
-
-/*!
- \reimp
-*/
-
-int QLabel::heightForWidth(int w) const
-{
- Q_D(const QLabel);
- if (d->isTextLabel)
- return d->sizeForWidth(w).height();
- return QWidget::heightForWidth(w);
-}
-
-/*!
- \property QLabel::openExternalLinks
- \since 4.2
-
- Specifies whether QLabel should automatically open links using
- QDesktopServices::openUrl() instead of emitting the
- linkActivated() signal.
-
- \bold{Note:} The textInteractionFlags set on the label need to include
- either LinksAccessibleByMouse or LinksAccessibleByKeyboard.
-
- The default value is false.
-
- \sa textInteractionFlags()
-*/
-bool QLabel::openExternalLinks() const
-{
- Q_D(const QLabel);
- return d->openExternalLinks;
-}
-
-void QLabel::setOpenExternalLinks(bool open)
-{
- Q_D(QLabel);
- d->openExternalLinks = open;
- if (d->control)
- d->control->setOpenExternalLinks(open);
-}
-
-/*!
- \property QLabel::textInteractionFlags
- \since 4.2
-
- Specifies how the label should interact with user input if it displays text.
-
- If the flags contain Qt::LinksAccessibleByKeyboard the focus policy is also
- automatically set to Qt::StrongFocus. If Qt::TextSelectableByKeyboard is set
- then the focus policy is set to Qt::ClickFocus.
-
- The default value is Qt::LinksAccessibleByMouse.
-*/
-void QLabel::setTextInteractionFlags(Qt::TextInteractionFlags flags)
-{
- Q_D(QLabel);
- if (d->textInteractionFlags == flags)
- return;
- d->textInteractionFlags = flags;
- if (flags & Qt::LinksAccessibleByKeyboard)
- setFocusPolicy(Qt::StrongFocus);
- else if (flags & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse))
- setFocusPolicy(Qt::ClickFocus);
- else
- setFocusPolicy(Qt::NoFocus);
-
- if (d->needTextControl()) {
- d->ensureTextControl();
- } else {
- delete d->control;
- d->control = 0;
- }
-
- if (d->control)
- d->control->setTextInteractionFlags(d->textInteractionFlags);
-}
-
-Qt::TextInteractionFlags QLabel::textInteractionFlags() const
-{
- Q_D(const QLabel);
- return d->textInteractionFlags;
-}
-
-/*!
- Selects text from position \a start and for \a length characters.
-
- \sa selectedText()
-
- \bold{Note:} The textInteractionFlags set on the label need to include
- either TextSelectableByMouse or TextSelectableByKeyboard.
-
- \since 4.7
-*/
-void QLabel::setSelection(int start, int length)
-{
- Q_D(QLabel);
- if (d->control) {
- d->ensureTextPopulated();
- QTextCursor cursor = d->control->textCursor();
- cursor.setPosition(start);
- cursor.setPosition(start + length, QTextCursor::KeepAnchor);
- d->control->setTextCursor(cursor);
- }
-}
-
-/*!
- \property QLabel::hasSelectedText
- \brief whether there is any text selected
-
- hasSelectedText() returns true if some or all of the text has been
- selected by the user; otherwise returns false.
-
- By default, this property is false.
-
- \sa selectedText()
-
- \bold{Note:} The textInteractionFlags set on the label need to include
- either TextSelectableByMouse or TextSelectableByKeyboard.
-
- \since 4.7
-*/
-bool QLabel::hasSelectedText() const
-{
- Q_D(const QLabel);
- if (d->control)
- return d->control->textCursor().hasSelection();
- return false;
-}
-
-/*!
- \property QLabel::selectedText
- \brief the selected text
-
- If there is no selected text this property's value is
- an empty string.
-
- By default, this property contains an empty string.
-
- \sa hasSelectedText()
-
- \bold{Note:} The textInteractionFlags set on the label need to include
- either TextSelectableByMouse or TextSelectableByKeyboard.
-
- \since 4.7
-*/
-QString QLabel::selectedText() const
-{
- Q_D(const QLabel);
- if (d->control)
- return d->control->textCursor().selectedText();
- return QString();
-}
-
-/*!
- selectionStart() returns the index of the first selected character in the
- label or -1 if no text is selected.
-
- \sa selectedText()
-
- \bold{Note:} The textInteractionFlags set on the label need to include
- either TextSelectableByMouse or TextSelectableByKeyboard.
-
- \since 4.7
-*/
-int QLabel::selectionStart() const
-{
- Q_D(const QLabel);
- if (d->control && d->control->textCursor().hasSelection())
- return d->control->textCursor().selectionStart();
- return -1;
-}
-
-/*!\reimp
-*/
-QSize QLabel::sizeHint() const
-{
- Q_D(const QLabel);
- if (!d->valid_hints)
- (void) QLabel::minimumSizeHint();
- return d->sh;
-}
-
-/*!
- \reimp
-*/
-QSize QLabel::minimumSizeHint() const
-{
- Q_D(const QLabel);
- if (d->valid_hints) {
- if (d->sizePolicy == sizePolicy())
- return d->msh;
- }
-
- ensurePolished();
- d->valid_hints = true;
- d->sh = d->sizeForWidth(-1); // wrap ? golden ratio : min doc size
- QSize msh(-1, -1);
-
- if (!d->isTextLabel) {
- msh = d->sh;
- } else {
- msh.rheight() = d->sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line
- msh.rwidth() = d->sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size
- if (d->sh.height() < msh.height())
- msh.rheight() = d->sh.height();
- }
- d->msh = msh;
- d->sizePolicy = sizePolicy();
- return msh;
-}
-
-/*!\reimp
-*/
-void QLabel::mousePressEvent(QMouseEvent *ev)
-{
- Q_D(QLabel);
- d->sendControlEvent(ev);
-}
-
-/*!\reimp
-*/
-void QLabel::mouseMoveEvent(QMouseEvent *ev)
-{
- Q_D(QLabel);
- d->sendControlEvent(ev);
-}
-
-/*!\reimp
-*/
-void QLabel::mouseReleaseEvent(QMouseEvent *ev)
-{
- Q_D(QLabel);
- d->sendControlEvent(ev);
-}
-
-/*!\reimp
-*/
-void QLabel::contextMenuEvent(QContextMenuEvent *ev)
-{
-#ifdef QT_NO_CONTEXTMENU
- Q_UNUSED(ev);
-#else
- Q_D(QLabel);
- if (!d->isTextLabel) {
- ev->ignore();
- return;
- }
- QMenu *menu = d->createStandardContextMenu(ev->pos());
- if (!menu) {
- ev->ignore();
- return;
- }
- ev->accept();
- menu->setAttribute(Qt::WA_DeleteOnClose);
- menu->popup(ev->globalPos());
-#endif
-}
-
-/*!
- \reimp
-*/
-void QLabel::focusInEvent(QFocusEvent *ev)
-{
- Q_D(QLabel);
- if (d->isTextLabel) {
- d->ensureTextControl();
- d->sendControlEvent(ev);
- }
- QFrame::focusInEvent(ev);
-}
-
-/*!
- \reimp
-*/
-void QLabel::focusOutEvent(QFocusEvent *ev)
-{
- Q_D(QLabel);
- if (d->control) {
- d->sendControlEvent(ev);
- QTextCursor cursor = d->control->textCursor();
- Qt::FocusReason reason = ev->reason();
- if (reason != Qt::ActiveWindowFocusReason
- && reason != Qt::PopupFocusReason
- && cursor.hasSelection()) {
- cursor.clearSelection();
- d->control->setTextCursor(cursor);
- }
- }
-
- QFrame::focusOutEvent(ev);
-}
-
-/*!\reimp
-*/
-bool QLabel::focusNextPrevChild(bool next)
-{
- Q_D(QLabel);
- if (d->control && d->control->setFocusToNextOrPreviousAnchor(next))
- return true;
- return QFrame::focusNextPrevChild(next);
-}
-
-/*!\reimp
-*/
-void QLabel::keyPressEvent(QKeyEvent *ev)
-{
- Q_D(QLabel);
- d->sendControlEvent(ev);
-}
-
-/*!\reimp
-*/
-bool QLabel::event(QEvent *e)
-{
- Q_D(QLabel);
- QEvent::Type type = e->type();
-
-#ifndef QT_NO_SHORTCUT
- if (type == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- if (se->shortcutId() == d->shortcutId) {
- QWidget * w = d->buddy;
- QAbstractButton *button = qobject_cast<QAbstractButton *>(w);
- if (w->focusPolicy() != Qt::NoFocus)
- w->setFocus(Qt::ShortcutFocusReason);
- if (button && !se->isAmbiguous())
- button->animateClick();
- else
- window()->setAttribute(Qt::WA_KeyboardFocusChange);
- return true;
- }
- } else
-#endif
- if (type == QEvent::Resize) {
- if (d->control)
- d->textLayoutDirty = true;
- } else if (e->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || e->type() == QEvent::MacSizeChange
-#endif
- ) {
- d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
- d->updateLabel();
- }
-
- return QFrame::event(e);
-}
-
-/*!\reimp
-*/
-void QLabel::paintEvent(QPaintEvent *)
-{
- Q_D(QLabel);
- QStyle *style = QWidget::style();
- QPainter painter(this);
- drawFrame(&painter);
- QRect cr = contentsRect();
- cr.adjust(d->margin, d->margin, -d->margin, -d->margin);
- int align = QStyle::visualAlignment(d->isTextLabel ? d->textDirection()
- : layoutDirection(), QFlag(d->align));
-
-#ifndef QT_NO_MOVIE
- if (d->movie) {
- if (d->scaledcontents)
- style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));
- else
- style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());
- }
- else
-#endif
- if (d->isTextLabel) {
- QRectF lr = d->layoutRect().toAlignedRect();
- QStyleOption opt;
- opt.initFrom(this);
-#ifndef QT_NO_STYLE_STYLESHEET
- if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) {
- cssStyle->styleSheetPalette(this, &opt, &opt.palette);
- }
-#endif
- if (d->control) {
-#ifndef QT_NO_SHORTCUT
- const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0);
- if (d->shortcutId != 0
- && underline != d->shortcutCursor.charFormat().fontUnderline()) {
- QTextCharFormat fmt;
- fmt.setFontUnderline(underline);
- d->shortcutCursor.mergeCharFormat(fmt);
- }
-#endif
- d->ensureTextLayouted();
-
- QAbstractTextDocumentLayout::PaintContext context;
- if (!isEnabled() && !d->control &&
- // We cannot support etched for rich text controls because custom
- // colors and links will override the light palette
- style->styleHint(QStyle::SH_EtchDisabledText, &opt, this)) {
- context.palette = opt.palette;
- context.palette.setColor(QPalette::Text, context.palette.light().color());
- painter.save();
- painter.translate(lr.x() + 1, lr.y() + 1);
- painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1));
- QAbstractTextDocumentLayout *layout = d->control->document()->documentLayout();
- layout->draw(&painter, context);
- painter.restore();
- }
-
- // Adjust the palette
- context.palette = opt.palette;
-
- if (foregroundRole() != QPalette::Text && isEnabled())
- context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole()));
-
- painter.save();
- painter.translate(lr.topLeft());
- painter.setClipRect(lr.translated(-lr.x(), -lr.y()));
- d->control->setPalette(context.palette);
- d->control->drawContents(&painter, QRectF(), this);
- painter.restore();
- } else {
- int flags = align | (d->textDirection() == Qt::LeftToRight ? Qt::TextForceLeftToRight
- : Qt::TextForceRightToLeft);
- if (d->hasShortcut) {
- flags |= Qt::TextShowMnemonic;
- if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this))
- flags |= Qt::TextHideMnemonic;
- }
- style->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), d->text, foregroundRole());
- }
- } else
-#ifndef QT_NO_PICTURE
- if (d->picture) {
- QRect br = d->picture->boundingRect();
- int rw = br.width();
- int rh = br.height();
- if (d->scaledcontents) {
- painter.save();
- painter.translate(cr.x(), cr.y());
- painter.scale((double)cr.width()/rw, (double)cr.height()/rh);
- painter.drawPicture(-br.x(), -br.y(), *d->picture);
- painter.restore();
- } else {
- int xo = 0;
- int yo = 0;
- if (align & Qt::AlignVCenter)
- yo = (cr.height()-rh)/2;
- else if (align & Qt::AlignBottom)
- yo = cr.height()-rh;
- if (align & Qt::AlignRight)
- xo = cr.width()-rw;
- else if (align & Qt::AlignHCenter)
- xo = (cr.width()-rw)/2;
- painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);
- }
- } else
-#endif
- if (d->pixmap && !d->pixmap->isNull()) {
- QPixmap pix;
- if (d->scaledcontents) {
- if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) {
- if (!d->cachedimage)
- d->cachedimage = new QImage(d->pixmap->toImage());
- delete d->scaledpixmap;
- d->scaledpixmap = new QPixmap(QPixmap::fromImage(d->cachedimage->scaled(cr.size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation)));
- }
- pix = *d->scaledpixmap;
- } else
- pix = *d->pixmap;
- QStyleOption opt;
- opt.initFrom(this);
- if (!isEnabled())
- pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt);
- style->drawItemPixmap(&painter, cr, align, pix);
- }
-}
-
-
-/*!
- Updates the label, but not the frame.
-*/
-
-void QLabelPrivate::updateLabel()
-{
- Q_Q(QLabel);
- valid_hints = false;
-
- if (isTextLabel) {
- QSizePolicy policy = q->sizePolicy();
- const bool wrap = align & Qt::TextWordWrap;
- policy.setHeightForWidth(wrap);
- if (policy != q->sizePolicy()) // ### should be replaced by WA_WState_OwnSizePolicy idiom
- q->setSizePolicy(policy);
- textLayoutDirty = true;
- }
- q->updateGeometry();
- q->update(q->contentsRect());
-}
-
-#ifndef QT_NO_SHORTCUT
-/*!
- Sets this label's buddy to \a buddy.
-
- When the user presses the shortcut key indicated by this label,
- the keyboard focus is transferred to the label's buddy widget.
-
- The buddy mechanism is only available for QLabels that contain
- text in which one character is prefixed with an ampersand, '&'.
- This character is set as the shortcut key. See the \l
- QKeySequence::mnemonic() documentation for details (to display an
- actual ampersand, use '&&').
-
- In a dialog, you might create two data entry widgets and a label
- for each, and set up the geometry layout so each label is just to
- the left of its data entry widget (its "buddy"), for example:
- \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 2
-
- With the code above, the focus jumps to the Name field when the
- user presses Alt+N, and to the Phone field when the user presses
- Alt+P.
-
- To unset a previously set buddy, call this function with \a buddy
- set to 0.
-
- \sa buddy(), setText(), QShortcut, setAlignment()
-*/
-
-void QLabel::setBuddy(QWidget *buddy)
-{
- Q_D(QLabel);
- d->buddy = buddy;
- if (d->isTextLabel) {
- if (d->shortcutId)
- releaseShortcut(d->shortcutId);
- d->shortcutId = 0;
- d->textDirty = true;
- if (buddy)
- d->updateShortcut(); // grab new shortcut
- d->updateLabel();
- }
-}
-
-
-/*!
- Returns this label's buddy, or 0 if no buddy is currently set.
-
- \sa setBuddy()
-*/
-
-QWidget * QLabel::buddy() const
-{
- Q_D(const QLabel);
- return d->buddy;
-}
-
-void QLabelPrivate::updateShortcut()
-{
- Q_Q(QLabel);
- Q_ASSERT(shortcutId == 0);
- // Introduce an extra boolean to indicate the presence of a shortcut in the
- // text. We cannot use the shortcutId itself because on the mac mnemonics are
- // off by default, so QKeySequence::mnemonic always returns an empty sequence.
- // But then we do want to hide the ampersands, so we can't use shortcutId.
- hasShortcut = false;
-
- if (!text.contains(QLatin1Char('&')))
- return;
- hasShortcut = true;
- shortcutId = q->grabShortcut(QKeySequence::mnemonic(text));
-}
-
-#endif // QT_NO_SHORTCUT
-
-#ifndef QT_NO_MOVIE
-void QLabelPrivate::_q_movieUpdated(const QRect& rect)
-{
- Q_Q(QLabel);
- if (movie && movie->isValid()) {
- QRect r;
- if (scaledcontents) {
- QRect cr = q->contentsRect();
- QRect pixmapRect(cr.topLeft(), movie->currentPixmap().size());
- if (pixmapRect.isEmpty())
- return;
- r.setRect(cr.left(), cr.top(),
- (rect.width() * cr.width()) / pixmapRect.width(),
- (rect.height() * cr.height()) / pixmapRect.height());
- } else {
- r = q->style()->itemPixmapRect(q->contentsRect(), align, movie->currentPixmap());
- r.translate(rect.x(), rect.y());
- r.setWidth(qMin(r.width(), rect.width()));
- r.setHeight(qMin(r.height(), rect.height()));
- }
- q->update(r);
- }
-}
-
-void QLabelPrivate::_q_movieResized(const QSize& size)
-{
- Q_Q(QLabel);
- q->update(); //we need to refresh the whole background in case the new size is smaler
- valid_hints = false;
- _q_movieUpdated(QRect(QPoint(0,0), size));
- q->updateGeometry();
-}
-
-/*!
- Sets the label contents to \a movie. Any previous content is
- cleared. The label does NOT take ownership of the movie.
-
- The buddy shortcut, if any, is disabled.
-
- \sa movie(), setBuddy()
-*/
-
-void QLabel::setMovie(QMovie *movie)
-{
- Q_D(QLabel);
- d->clearContents();
-
- if (!movie)
- return;
-
- d->movie = movie;
- connect(movie, SIGNAL(resized(QSize)), this, SLOT(_q_movieResized(QSize)));
- connect(movie, SIGNAL(updated(QRect)), this, SLOT(_q_movieUpdated(QRect)));
-
- // Assume that if the movie is running,
- // resize/update signals will come soon enough
- if (movie->state() != QMovie::Running)
- d->updateLabel();
-}
-
-#endif // QT_NO_MOVIE
-
-/*!
- \internal
-
- Clears any contents, without updating/repainting the label.
-*/
-
-void QLabelPrivate::clearContents()
-{
- delete control;
- control = 0;
- isTextLabel = false;
- hasShortcut = false;
-
-#ifndef QT_NO_PICTURE
- delete picture;
- picture = 0;
-#endif
- delete scaledpixmap;
- scaledpixmap = 0;
- delete cachedimage;
- cachedimage = 0;
- delete pixmap;
- pixmap = 0;
-
- text.clear();
- Q_Q(QLabel);
-#ifndef QT_NO_SHORTCUT
- if (shortcutId)
- q->releaseShortcut(shortcutId);
- shortcutId = 0;
-#endif
-#ifndef QT_NO_MOVIE
- if (movie) {
- QObject::disconnect(movie, SIGNAL(resized(QSize)), q, SLOT(_q_movieResized(QSize)));
- QObject::disconnect(movie, SIGNAL(updated(QRect)), q, SLOT(_q_movieUpdated(QRect)));
- }
- movie = 0;
-#endif
-#ifndef QT_NO_CURSOR
- if (onAnchor) {
- if (validCursor)
- q->setCursor(cursor);
- else
- q->unsetCursor();
- }
- validCursor = false;
- onAnchor = false;
-#endif
-}
-
-
-#ifndef QT_NO_MOVIE
-
-/*!
- Returns a pointer to the label's movie, or 0 if no movie has been
- set.
-
- \sa setMovie()
-*/
-
-QMovie *QLabel::movie() const
-{
- Q_D(const QLabel);
- return d->movie;
-}
-
-#endif // QT_NO_MOVIE
-
-/*!
- \property QLabel::textFormat
- \brief the label's text format
-
- See the Qt::TextFormat enum for an explanation of the possible
- options.
-
- The default format is Qt::AutoText.
-
- \sa text()
-*/
-
-Qt::TextFormat QLabel::textFormat() const
-{
- Q_D(const QLabel);
- return d->textformat;
-}
-
-void QLabel::setTextFormat(Qt::TextFormat format)
-{
- Q_D(QLabel);
- if (format != d->textformat) {
- d->textformat = format;
- QString t = d->text;
- if (!t.isNull()) {
- d->text.clear();
- setText(t);
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QLabel::changeEvent(QEvent *ev)
-{
- Q_D(QLabel);
- if(ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) {
- if (d->isTextLabel) {
- if (d->control)
- d->control->document()->setDefaultFont(font());
- d->updateLabel();
- }
- } else if (ev->type() == QEvent::PaletteChange && d->control) {
- d->control->setPalette(palette());
- } else if (ev->type() == QEvent::ContentsRectChange) {
- d->updateLabel();
- }
- QFrame::changeEvent(ev);
-}
-
-/*!
- \property QLabel::scaledContents
- \brief whether the label will scale its contents to fill all
- available space.
-
- When enabled and the label shows a pixmap, it will scale the
- pixmap to fill the available space.
-
- This property's default is false.
-*/
-bool QLabel::hasScaledContents() const
-{
- Q_D(const QLabel);
- return d->scaledcontents;
-}
-
-void QLabel::setScaledContents(bool enable)
-{
- Q_D(QLabel);
- if ((bool)d->scaledcontents == enable)
- return;
- d->scaledcontents = enable;
- if (!enable) {
- delete d->scaledpixmap;
- d->scaledpixmap = 0;
- delete d->cachedimage;
- d->cachedimage = 0;
- }
- update(contentsRect());
-}
-
-Qt::LayoutDirection QLabelPrivate::textDirection() const
-{
- if (control) {
- QTextOption opt = control->document()->defaultTextOption();
- return opt.textDirection();
- }
-
- return text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
-}
-
-/*!
- \fn void QLabel::setAlignment(Qt::AlignmentFlag flag)
- \internal
-
- Without this function, a call to e.g. setAlignment(Qt::AlignTop)
- results in the \c QT3_SUPPORT function setAlignment(int) being called,
- rather than setAlignment(Qt::Alignment).
-*/
-
-// Returns the rect that is available for us to draw the document
-QRect QLabelPrivate::documentRect() const
-{
- Q_Q(const QLabel);
- Q_ASSERT_X(isTextLabel, "documentRect", "document rect called for label that is not a text label!");
- QRect cr = q->contentsRect();
- cr.adjust(margin, margin, -margin, -margin);
- const int align = QStyle::visualAlignment(isTextLabel ? textDirection()
- : q->layoutDirection(), QFlag(this->align));
- int m = indent;
- if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
- m = q->fontMetrics().width(QLatin1Char('x')) / 2 - margin;
- if (m > 0) {
- if (align & Qt::AlignLeft)
- cr.setLeft(cr.left() + m);
- if (align & Qt::AlignRight)
- cr.setRight(cr.right() - m);
- if (align & Qt::AlignTop)
- cr.setTop(cr.top() + m);
- if (align & Qt::AlignBottom)
- cr.setBottom(cr.bottom() - m);
- }
- return cr;
-}
-
-void QLabelPrivate::ensureTextPopulated() const
-{
- if (!textDirty)
- return;
- if (control) {
- QTextDocument *doc = control->document();
- if (textDirty) {
-#ifndef QT_NO_TEXTHTMLPARSER
- if (isRichText)
- doc->setHtml(text);
- else
- doc->setPlainText(text);
-#else
- doc->setPlainText(text);
-#endif
- doc->setUndoRedoEnabled(false);
-
-#ifndef QT_NO_SHORTCUT
- if (hasShortcut) {
- // Underline the first character that follows an ampersand (and remove the others ampersands)
- int from = 0;
- bool found = false;
- QTextCursor cursor;
- while (!(cursor = control->document()->find((QLatin1String("&")), from)).isNull()) {
- cursor.deleteChar(); // remove the ampersand
- cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
- from = cursor.position();
- if (!found && cursor.selectedText() != QLatin1String("&")) { //not a second &
- found = true;
- shortcutCursor = cursor;
- }
- }
- }
-#endif
- }
- }
- textDirty = false;
-}
-
-void QLabelPrivate::ensureTextLayouted() const
-{
- if (!textLayoutDirty)
- return;
- ensureTextPopulated();
- if (control) {
- QTextDocument *doc = control->document();
- QTextOption opt = doc->defaultTextOption();
-
- opt.setAlignment(QFlag(this->align));
-
- if (this->align & Qt::TextWordWrap)
- opt.setWrapMode(QTextOption::WordWrap);
- else
- opt.setWrapMode(QTextOption::ManualWrap);
-
- doc->setDefaultTextOption(opt);
-
- QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
- fmt.setMargin(0);
- doc->rootFrame()->setFrameFormat(fmt);
- doc->setTextWidth(documentRect().width());
- }
- textLayoutDirty = false;
-}
-
-void QLabelPrivate::ensureTextControl() const
-{
- Q_Q(const QLabel);
- if (!isTextLabel)
- return;
- if (!control) {
- control = new QTextControl(const_cast<QLabel *>(q));
- control->document()->setUndoRedoEnabled(false);
- control->document()->setDefaultFont(q->font());
- control->setTextInteractionFlags(textInteractionFlags);
- control->setOpenExternalLinks(openExternalLinks);
- control->setPalette(q->palette());
- control->setFocus(q->hasFocus());
- QObject::connect(control, SIGNAL(updateRequest(QRectF)),
- q, SLOT(update()));
- QObject::connect(control, SIGNAL(linkHovered(QString)),
- q, SLOT(_q_linkHovered(QString)));
- QObject::connect(control, SIGNAL(linkActivated(QString)),
- q, SIGNAL(linkActivated(QString)));
- textLayoutDirty = true;
- textDirty = true;
- }
-}
-
-void QLabelPrivate::sendControlEvent(QEvent *e)
-{
- Q_Q(QLabel);
- if (!isTextLabel || !control || textInteractionFlags == Qt::NoTextInteraction) {
- e->ignore();
- return;
- }
- control->processEvent(e, -layoutRect().topLeft(), q);
-}
-
-void QLabelPrivate::_q_linkHovered(const QString &anchor)
-{
- Q_Q(QLabel);
-#ifndef QT_NO_CURSOR
- if (anchor.isEmpty()) { // restore cursor
- if (validCursor)
- q->setCursor(cursor);
- else
- q->unsetCursor();
- onAnchor = false;
- } else if (!onAnchor) {
- validCursor = q->testAttribute(Qt::WA_SetCursor);
- if (validCursor) {
- cursor = q->cursor();
- }
- q->setCursor(Qt::PointingHandCursor);
- onAnchor = true;
- }
-#endif
- emit q->linkHovered(anchor);
-}
-
-// Return the layout rect - this is the rect that is given to the layout painting code
-// This may be different from the document rect since vertical alignment is not
-// done by the text layout code
-QRectF QLabelPrivate::layoutRect() const
-{
- QRectF cr = documentRect();
- if (!control)
- return cr;
- ensureTextLayouted();
- // Caculate y position manually
- qreal rh = control->document()->documentLayout()->documentSize().height();
- qreal yo = 0;
- if (align & Qt::AlignVCenter)
- yo = qMax((cr.height()-rh)/2, qreal(0));
- else if (align & Qt::AlignBottom)
- yo = qMax(cr.height()-rh, qreal(0));
- return QRectF(cr.x(), yo + cr.y(), cr.width(), cr.height());
-}
-
-// Returns the point in the document rect adjusted with p
-QPoint QLabelPrivate::layoutPoint(const QPoint& p) const
-{
- QRect lr = layoutRect().toRect();
- return p - lr.topLeft();
-}
-
-#ifndef QT_NO_CONTEXTMENU
-QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos)
-{
- QString linkToCopy;
- QPoint p;
- if (control && isRichText) {
- p = layoutPoint(pos);
- linkToCopy = control->document()->documentLayout()->anchorAt(p);
- }
-
- if (linkToCopy.isEmpty() && !control)
- return 0;
-
- return control->createStandardContextMenu(p, q_func());
-}
-#endif
-
-/*!
- \fn void QLabel::linkHovered(const QString &link)
- \since 4.2
-
- This signal is emitted when the user hovers over a link. The URL
- referred to by the anchor is passed in \a link.
-
- \sa linkActivated()
-*/
-
-
-/*!
- \fn void QLabel::linkActivated(const QString &link)
- \since 4.2
-
- This signal is emitted when the user clicks a link. The URL
- referred to by the anchor is passed in \a link.
-
- \sa linkHovered()
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qlabel.cpp"
diff --git a/src/gui/widgets/qlabel.h b/src/gui/widgets/qlabel.h
deleted file mode 100644
index 27ab164dc6..0000000000
--- a/src/gui/widgets/qlabel.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/****************************************************************************
-**
-** 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 QLABEL_H
-#define QLABEL_H
-
-#include <QtGui/qframe.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QLabelPrivate;
-
-class Q_GUI_EXPORT QLabel : public QFrame
-{
- Q_OBJECT
- Q_PROPERTY(QString text READ text WRITE setText)
- Q_PROPERTY(Qt::TextFormat textFormat READ textFormat WRITE setTextFormat)
- Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap)
- Q_PROPERTY(bool scaledContents READ hasScaledContents WRITE setScaledContents)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
- Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap)
- Q_PROPERTY(int margin READ margin WRITE setMargin)
- Q_PROPERTY(int indent READ indent WRITE setIndent)
- Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
- Q_PROPERTY(bool hasSelectedText READ hasSelectedText)
- Q_PROPERTY(QString selectedText READ selectedText)
-
-public:
- explicit QLabel(QWidget *parent=0, Qt::WindowFlags f=0);
- explicit QLabel(const QString &text, QWidget *parent=0, Qt::WindowFlags f=0);
- ~QLabel();
-
- QString text() const;
- const QPixmap *pixmap() const;
-#ifndef QT_NO_PICTURE
- const QPicture *picture() const;
-#endif
-#ifndef QT_NO_MOVIE
- QMovie *movie() const;
-#endif
-
- Qt::TextFormat textFormat() const;
- void setTextFormat(Qt::TextFormat);
-
- Qt::Alignment alignment() const;
- void setAlignment(Qt::Alignment);
-
- void setWordWrap(bool on);
- bool wordWrap() const;
-
- int indent() const;
- void setIndent(int);
-
- int margin() const;
- void setMargin(int);
-
- bool hasScaledContents() const;
- void setScaledContents(bool);
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-#ifndef QT_NO_SHORTCUT
- void setBuddy(QWidget *);
- QWidget *buddy() const;
-#endif
- int heightForWidth(int) const;
-
- bool openExternalLinks() const;
- void setOpenExternalLinks(bool open);
-
- void setTextInteractionFlags(Qt::TextInteractionFlags flags);
- Qt::TextInteractionFlags textInteractionFlags() const;
-
- void setSelection(int, int);
- bool hasSelectedText() const;
- QString selectedText() const;
- int selectionStart() const;
-
-public Q_SLOTS:
- void setText(const QString &);
- void setPixmap(const QPixmap &);
-#ifndef QT_NO_PICTURE
- void setPicture(const QPicture &);
-#endif
-#ifndef QT_NO_MOVIE
- void setMovie(QMovie *movie);
-#endif
- void setNum(int);
- void setNum(double);
- void clear();
-
-Q_SIGNALS:
- void linkActivated(const QString& link);
- void linkHovered(const QString& link);
-
-protected:
- bool event(QEvent *e);
- void keyPressEvent(QKeyEvent *ev);
- void paintEvent(QPaintEvent *);
- void changeEvent(QEvent *);
- void mousePressEvent(QMouseEvent *ev);
- void mouseMoveEvent(QMouseEvent *ev);
- void mouseReleaseEvent(QMouseEvent *ev);
- void contextMenuEvent(QContextMenuEvent *ev);
- void focusInEvent(QFocusEvent *ev);
- void focusOutEvent(QFocusEvent *ev);
- bool focusNextPrevChild(bool next);
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QLabel(QWidget *parent, const char* name, Qt::WindowFlags f=0);
- QT3_SUPPORT_CONSTRUCTOR QLabel(const QString &text, QWidget *parent, const char* name,
- Qt::WindowFlags f=0);
- QT3_SUPPORT_CONSTRUCTOR QLabel(QWidget *buddy, const QString &,
- QWidget *parent=0, const char* name=0, Qt::WindowFlags f=0);
- QT3_SUPPORT void setAlignment(int alignment);
-
- // don't mark the next function with QT3_SUPPORT
- inline void setAlignment(Qt::AlignmentFlag flag) { setAlignment((Qt::Alignment)flag); }
-#endif
-
-private:
- Q_DISABLE_COPY(QLabel)
- Q_DECLARE_PRIVATE(QLabel)
-#ifndef QT_NO_MOVIE
- Q_PRIVATE_SLOT(d_func(), void _q_movieUpdated(const QRect&))
- Q_PRIVATE_SLOT(d_func(), void _q_movieResized(const QSize&))
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_linkHovered(const QString &))
-
- friend class QTipLabel;
- friend class QMessageBoxPrivate;
- friend class QBalloonTip;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLABEL_H
diff --git a/src/gui/widgets/qlabel_p.h b/src/gui/widgets/qlabel_p.h
deleted file mode 100644
index ea79c8d205..0000000000
--- a/src/gui/widgets/qlabel_p.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** 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 QLABEL_P_H
-#define QLABEL_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qlabel.h"
-
-#include "private/qtextdocumentlayout_p.h"
-#include "private/qtextcontrol_p.h"
-#include "qtextdocumentfragment.h"
-#include "qframe_p.h"
-#include "qtextdocument.h"
-#include "qmovie.h"
-#include "qimage.h"
-#include "qbitmap.h"
-#include "qpicture.h"
-#include "qmenu.h"
-
-QT_BEGIN_NAMESPACE
-
-class QLabelPrivate : public QFramePrivate
-{
- Q_DECLARE_PUBLIC(QLabel)
-public:
- QLabelPrivate() {}
-
- void init();
- void clearContents();
- void updateLabel();
- QSize sizeForWidth(int w) const;
-
- mutable QSize sh;
- mutable QSize msh;
- mutable bool valid_hints;
- mutable QSizePolicy sizePolicy;
- int margin;
- QString text;
- QPixmap *pixmap;
- QPixmap *scaledpixmap;
- QImage *cachedimage;
-#ifndef QT_NO_PICTURE
- QPicture *picture;
-#endif
-#ifndef QT_NO_MOVIE
- QPointer<QMovie> movie;
- void _q_movieUpdated(const QRect&);
- void _q_movieResized(const QSize&);
-#endif
-#ifndef QT_NO_SHORTCUT
- void updateShortcut();
-#endif
-#ifndef QT_NO_SHORTCUT
- QPointer<QWidget> buddy;
- int shortcutId;
-#endif
- ushort align;
- short indent;
- uint scaledcontents :1;
- mutable uint textLayoutDirty : 1;
- mutable uint textDirty : 1;
- mutable uint isRichText : 1;
- mutable uint isTextLabel : 1;
- mutable uint hasShortcut : 1;
- Qt::TextFormat textformat;
- mutable QTextControl *control;
- mutable QTextCursor shortcutCursor;
- Qt::TextInteractionFlags textInteractionFlags;
-
- inline bool needTextControl() const {
- return isTextLabel
- && (isRichText
- || (!isRichText && (textInteractionFlags & (Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard))));
- }
-
- void ensureTextPopulated() const;
- void ensureTextLayouted() const;
- void ensureTextControl() const;
- void sendControlEvent(QEvent *e);
-
- void _q_linkHovered(const QString &link);
-
- QRectF layoutRect() const;
- QRect documentRect() const;
- QPoint layoutPoint(const QPoint& p) const;
- Qt::LayoutDirection textDirection() const;
-#ifndef QT_NO_CONTEXTMENU
- QMenu *createStandardContextMenu(const QPoint &pos);
-#endif
-
- bool openExternalLinks;
-
-#ifndef QT_NO_CURSOR
- uint validCursor : 1;
- uint onAnchor : 1;
- QCursor cursor;
-#endif
-
- friend class QMessageBoxPrivate;
-};
-
-QT_END_NAMESPACE
-
-#endif // QLABEL_P_H
diff --git a/src/gui/widgets/qlcdnumber.cpp b/src/gui/widgets/qlcdnumber.cpp
deleted file mode 100644
index 2513718d8b..0000000000
--- a/src/gui/widgets/qlcdnumber.cpp
+++ /dev/null
@@ -1,1312 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlcdnumber.h"
-#ifndef QT_NO_LCDNUMBER
-#include "qbitarray.h"
-#include "qpainter.h"
-#include "private/qframe_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QLCDNumberPrivate : public QFramePrivate
-{
- Q_DECLARE_PUBLIC(QLCDNumber)
-public:
- void init();
- void internalSetString(const QString& s);
- void drawString(const QString& s, QPainter &, QBitArray * = 0, bool = true);
- //void drawString(const QString &, QPainter &, QBitArray * = 0) const;
- void drawDigit(const QPoint &, QPainter &, int, char, char = ' ');
- void drawSegment(const QPoint &, char, QPainter &, int, bool = false);
-
- int ndigits;
- double val;
- uint base : 2;
- uint smallPoint : 1;
- uint fill : 1;
- uint shadow : 1;
- QString digitStr;
- QBitArray points;
-};
-
-/*!
- \class QLCDNumber
-
- \brief The QLCDNumber widget displays a number with LCD-like digits.
-
- \ingroup basicwidgets
-
-
- It can display a number in just about any size. It can display
- decimal, hexadecimal, octal or binary numbers. It is easy to
- connect to data sources using the display() slot, which is
- overloaded to take any of five argument types.
-
- There are also slots to change the base with setMode() and the
- decimal point with setSmallDecimalPoint().
-
- QLCDNumber emits the overflow() signal when it is asked to display
- something beyond its range. The range is set by setDigitCount(),
- but setSmallDecimalPoint() also influences it. If the display is
- set to hexadecimal, octal or binary, the integer equivalent of the
- value is displayed.
-
- These digits and other symbols can be shown: 0/O, 1, 2, 3, 4, 5/S,
- 6, 7, 8, 9/g, minus, decimal point, A, B, C, D, E, F, h, H, L, o,
- P, r, u, U, Y, colon, degree sign (which is specified as single
- quote in the string) and space. QLCDNumber substitutes spaces for
- illegal characters.
-
- It is not possible to retrieve the contents of a QLCDNumber
- object, although you can retrieve the numeric value with value().
- If you really need the text, we recommend that you connect the
- signals that feed the display() slot to another slot as well and
- store the value there.
-
- Incidentally, QLCDNumber is the very oldest part of Qt, tracing
- its roots back to a BASIC program on the \link
- http://www.nvg.ntnu.no/sinclair/computers/zxspectrum/zxspectrum.htm
- Sinclair Spectrum\endlink.
-
- \table
- \row \o \inlineimage motif-lcdnumber.png Screenshot of a Motif style LCD number widget
- \inlineimage cde-lcdnumber.png Screenshot of a CDE style LCD number widget
- \inlineimage windows-lcdnumber.png Screenshot of a Windows style LCD number widget
- \inlineimage windowsxp-lcdnumber.png Screenshot of a Windows XP style LCD number widget
- \inlineimage macintosh-lcdnumber.png Screenshot of a Macintosh style LCD number widget
- \inlineimage plastique-lcdnumber.png Screenshot of a Plastique style LCD number widget
- \row \o LCD number widgets shown in various widget styles (from left to right):
- \l{Motif Style Widget Gallery}{Motif}, \l{CDE Style Widget Gallery}{CDE},
- \l{Windows Style Widget Gallery}{Windows}, \l{Windows XP Style Widget Gallery}{Windows XP},
- \l{Macintosh Style Widget Gallery}{Macintosh}, \l{Plastique Style Widget Gallery}{Plastique}.
- \endtable
-
- \sa QLabel, QFrame, {Digital Clock Example}, {Tetrix Example}
-*/
-
-/*!
- \enum QLCDNumber::Mode
-
- This type determines how numbers are shown.
-
- \value Hex Hexadecimal
- \value Dec Decimal
- \value Oct Octal
- \value Bin Binary
- \omitvalue HEX
- \omitvalue DEC
- \omitvalue OCT
- \omitvalue BIN
-
- If the display is set to hexadecimal, octal or binary, the integer
- equivalent of the value is displayed.
-*/
-
-/*!
- \enum QLCDNumber::SegmentStyle
-
- This type determines the visual appearance of the QLCDNumber
- widget.
-
- \value Outline gives raised segments filled with the background color.
- \value Filled gives raised segments filled with the windowText color.
- \value Flat gives flat segments filled with the windowText color.
-*/
-
-
-
-/*!
- \fn void QLCDNumber::overflow()
-
- This signal is emitted whenever the QLCDNumber is asked to display
- a too-large number or a too-long string.
-
- It is never emitted by setDigitCount().
-*/
-
-
-static QString int2string(int num, int base, int ndigits, bool *oflow)
-{
- QString s;
- bool negative;
- if (num < 0) {
- negative = true;
- num = -num;
- } else {
- negative = false;
- }
- switch(base) {
- case QLCDNumber::Hex:
- s.sprintf("%*x", ndigits, num);
- break;
- case QLCDNumber::Dec:
- s.sprintf("%*i", ndigits, num);
- break;
- case QLCDNumber::Oct:
- s.sprintf("%*o", ndigits, num);
- break;
- case QLCDNumber::Bin:
- {
- char buf[42];
- char *p = &buf[41];
- uint n = num;
- int len = 0;
- *p = '\0';
- do {
- *--p = (char)((n&1)+'0');
- n >>= 1;
- len++;
- } while (n != 0);
- len = ndigits - len;
- if (len > 0)
- s.fill(QLatin1Char(' '), len);
- s += QString::fromLatin1(p);
- }
- break;
- }
- if (negative) {
- for (int i=0; i<(int)s.length(); i++) {
- if (s[i] != QLatin1Char(' ')) {
- if (i != 0) {
- s[i-1] = QLatin1Char('-');
- } else {
- s.insert(0, QLatin1Char('-'));
- }
- break;
- }
- }
- }
- if (oflow)
- *oflow = (int)s.length() > ndigits;
- return s;
-}
-
-
-static QString double2string(double num, int base, int ndigits, bool *oflow)
-{
- QString s;
- if (base != QLCDNumber::Dec) {
- bool of = num >= 2147483648.0 || num < -2147483648.0;
- if (of) { // oops, integer overflow
- if (oflow)
- *oflow = true;
- return s;
- }
- s = int2string((int)num, base, ndigits, 0);
- } else { // decimal base
- int nd = ndigits;
- do {
- s.sprintf("%*.*g", ndigits, nd, num);
- int i = s.indexOf(QLatin1Char('e'));
- if (i > 0 && s[i+1]==QLatin1Char('+')) {
- s[i] = QLatin1Char(' ');
- s[i+1] = QLatin1Char('e');
- }
- } while (nd-- && (int)s.length() > ndigits);
- }
- if (oflow)
- *oflow = (int)s.length() > ndigits;
- return s;
-}
-
-
-static const char *getSegments(char ch) // gets list of segments for ch
-{
- static const char segments[30][8] =
- { { 0, 1, 2, 4, 5, 6,99, 0}, // 0 0 / O
- { 2, 5,99, 0, 0, 0, 0, 0}, // 1 1
- { 0, 2, 3, 4, 6,99, 0, 0}, // 2 2
- { 0, 2, 3, 5, 6,99, 0, 0}, // 3 3
- { 1, 2, 3, 5,99, 0, 0, 0}, // 4 4
- { 0, 1, 3, 5, 6,99, 0, 0}, // 5 5 / S
- { 0, 1, 3, 4, 5, 6,99, 0}, // 6 6
- { 0, 2, 5,99, 0, 0, 0, 0}, // 7 7
- { 0, 1, 2, 3, 4, 5, 6,99}, // 8 8
- { 0, 1, 2, 3, 5, 6,99, 0}, // 9 9 / g
- { 3,99, 0, 0, 0, 0, 0, 0}, // 10 -
- { 7,99, 0, 0, 0, 0, 0, 0}, // 11 .
- { 0, 1, 2, 3, 4, 5,99, 0}, // 12 A
- { 1, 3, 4, 5, 6,99, 0, 0}, // 13 B
- { 0, 1, 4, 6,99, 0, 0, 0}, // 14 C
- { 2, 3, 4, 5, 6,99, 0, 0}, // 15 D
- { 0, 1, 3, 4, 6,99, 0, 0}, // 16 E
- { 0, 1, 3, 4,99, 0, 0, 0}, // 17 F
- { 1, 3, 4, 5,99, 0, 0, 0}, // 18 h
- { 1, 2, 3, 4, 5,99, 0, 0}, // 19 H
- { 1, 4, 6,99, 0, 0, 0, 0}, // 20 L
- { 3, 4, 5, 6,99, 0, 0, 0}, // 21 o
- { 0, 1, 2, 3, 4,99, 0, 0}, // 22 P
- { 3, 4,99, 0, 0, 0, 0, 0}, // 23 r
- { 4, 5, 6,99, 0, 0, 0, 0}, // 24 u
- { 1, 2, 4, 5, 6,99, 0, 0}, // 25 U
- { 1, 2, 3, 5, 6,99, 0, 0}, // 26 Y
- { 8, 9,99, 0, 0, 0, 0, 0}, // 27 :
- { 0, 1, 2, 3,99, 0, 0, 0}, // 28 '
- {99, 0, 0, 0, 0, 0, 0, 0} }; // 29 empty
-
- if (ch >= '0' && ch <= '9')
- return segments[ch - '0'];
- if (ch >= 'A' && ch <= 'F')
- return segments[ch - 'A' + 12];
- if (ch >= 'a' && ch <= 'f')
- return segments[ch - 'a' + 12];
-
- int n;
- switch (ch) {
- case '-':
- n = 10; break;
- case 'O':
- n = 0; break;
- case 'g':
- n = 9; break;
- case '.':
- n = 11; break;
- case 'h':
- n = 18; break;
- case 'H':
- n = 19; break;
- case 'l':
- case 'L':
- n = 20; break;
- case 'o':
- n = 21; break;
- case 'p':
- case 'P':
- n = 22; break;
- case 'r':
- case 'R':
- n = 23; break;
- case 's':
- case 'S':
- n = 5; break;
- case 'u':
- n = 24; break;
- case 'U':
- n = 25; break;
- case 'y':
- case 'Y':
- n = 26; break;
- case ':':
- n = 27; break;
- case '\'':
- n = 28; break;
- default:
- n = 29; break;
- }
- return segments[n];
-}
-
-
-#ifdef QT3_SUPPORT
-/*! \obsolete
- Constructs an LCD number, sets the number of digits to 5, the base
- to decimal, the decimal point mode to 'small' and the frame style
- to a raised box. The segmentStyle() is set to \c Outline.
-
- The \a parent and \a name arguments are passed to the QFrame
- constructor.
-
- \sa setDigitCount(), setSmallDecimalPoint()
-*/
-
-QLCDNumber::QLCDNumber(QWidget *parent, const char *name)
- : QFrame(*new QLCDNumberPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- Q_D(QLCDNumber);
- d->ndigits = 5;
- d->init();
-}
-
-
-/*! \obsolete
- Constructs an LCD number, sets the number of digits to \a
- numDigits, the base to decimal, the decimal point mode to 'small'
- and the frame style to a raised box. The segmentStyle() is set to
- \c Outline.
-
- The \a parent and \a name arguments are passed to the QFrame
- constructor.
-
- \sa setDigitCount(), setSmallDecimalPoint()
-*/
-
-QLCDNumber::QLCDNumber(uint numDigits, QWidget *parent, const char *name)
- : QFrame(*new QLCDNumberPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- Q_D(QLCDNumber);
- d->ndigits = numDigits;
- d->init();
-}
-#endif //QT3_SUPPORT
-
-/*!
- Constructs an LCD number, sets the number of digits to 5, the base
- to decimal, the decimal point mode to 'small' and the frame style
- to a raised box. The segmentStyle() is set to \c Outline.
-
- The \a parent argument is passed to the QFrame constructor.
-
- \sa setDigitCount(), setSmallDecimalPoint()
-*/
-
-QLCDNumber::QLCDNumber(QWidget *parent)
- : QFrame(*new QLCDNumberPrivate, parent)
-{
- Q_D(QLCDNumber);
- d->ndigits = 5;
- d->init();
-}
-
-
-/*!
- Constructs an LCD number, sets the number of digits to \a
- numDigits, the base to decimal, the decimal point mode to 'small'
- and the frame style to a raised box. The segmentStyle() is set to
- \c Filled.
-
- The \a parent argument is passed to the QFrame constructor.
-
- \sa setDigitCount(), setSmallDecimalPoint()
-*/
-
-QLCDNumber::QLCDNumber(uint numDigits, QWidget *parent)
- : QFrame(*new QLCDNumberPrivate, parent)
-{
- Q_D(QLCDNumber);
- d->ndigits = numDigits;
- d->init();
-}
-
-void QLCDNumberPrivate::init()
-{
- Q_Q(QLCDNumber);
-
- q->setFrameStyle(QFrame::Box | QFrame::Raised);
- val = 0;
- base = QLCDNumber::Dec;
- smallPoint = false;
- q->setDigitCount(ndigits);
- q->setSegmentStyle(QLCDNumber::Filled);
- q->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));
-}
-
-/*!
- Destroys the LCD number.
-*/
-
-QLCDNumber::~QLCDNumber()
-{
-}
-
-
-/*!
- \deprecated
- \property QLCDNumber::numDigits
- \brief the current number of digits displayed
- \sa digitCount
-*/
-
-void QLCDNumber::setNumDigits(int numDigits)
-{
- setDigitCount(numDigits);
-}
-
-/*!
- \since 4.6
- \property QLCDNumber::digitCount
- \brief the current number of digits displayed
-
- Corresponds to the current number of digits. If \l
- QLCDNumber::smallDecimalPoint is false, the decimal point occupies
- one digit position.
-
- By default, this property contains a value of 5.
-
- \sa smallDecimalPoint
-*/
-
-/*!
- Sets the current number of digits to \a numDigits. Must
- be in the range 0..99.
- */
-void QLCDNumber::setDigitCount(int numDigits)
-{
- Q_D(QLCDNumber);
- if (numDigits > 99) {
- qWarning("QLCDNumber::setNumDigits: (%s) Max 99 digits allowed",
- objectName().toLocal8Bit().constData());
- numDigits = 99;
- }
- if (numDigits < 0) {
- qWarning("QLCDNumber::setNumDigits: (%s) Min 0 digits allowed",
- objectName().toLocal8Bit().constData());
- numDigits = 0;
- }
- if (d->digitStr.isNull()) { // from constructor
- d->ndigits = numDigits;
- d->digitStr.fill(QLatin1Char(' '), d->ndigits);
- d->points.fill(0, d->ndigits);
- d->digitStr[d->ndigits - 1] = QLatin1Char('0'); // "0" is the default number
- } else {
- bool doDisplay = d->ndigits == 0;
- if (numDigits == d->ndigits) // no change
- return;
- register int i;
- int dif;
- if (numDigits > d->ndigits) { // expand
- dif = numDigits - d->ndigits;
- QString buf;
- buf.fill(QLatin1Char(' '), dif);
- d->digitStr.insert(0, buf);
- d->points.resize(numDigits);
- for (i=numDigits-1; i>=dif; i--)
- d->points.setBit(i, d->points.testBit(i-dif));
- for (i=0; i<dif; i++)
- d->points.clearBit(i);
- } else { // shrink
- dif = d->ndigits - numDigits;
- d->digitStr = d->digitStr.right(numDigits);
- QBitArray tmpPoints = d->points;
- d->points.resize(numDigits);
- for (i=0; i<(int)numDigits; i++)
- d->points.setBit(i, tmpPoints.testBit(i+dif));
- }
- d->ndigits = numDigits;
- if (doDisplay)
- display(value());
- update();
- }
-}
-
-int QLCDNumber::numDigits() const
-{
- Q_D(const QLCDNumber);
- return d->ndigits;
-}
-
-/*!
- Returns the current number of digits.
- */
-int QLCDNumber::digitCount() const
-{
- Q_D(const QLCDNumber);
- return d->ndigits;
-}
-
-/*!
- \overload
-
- Returns true if \a num is too big to be displayed in its entirety;
- otherwise returns false.
-
- \sa display(), digitCount(), smallDecimalPoint()
-*/
-
-bool QLCDNumber::checkOverflow(int num) const
-{
- Q_D(const QLCDNumber);
- bool of;
- int2string(num, d->base, d->ndigits, &of);
- return of;
-}
-
-
-/*!
- Returns true if \a num is too big to be displayed in its entirety;
- otherwise returns false.
-
- \sa display(), digitCount(), smallDecimalPoint()
-*/
-
-bool QLCDNumber::checkOverflow(double num) const
-{
- Q_D(const QLCDNumber);
- bool of;
- double2string(num, d->base, d->ndigits, &of);
- return of;
-}
-
-
-/*!
- \property QLCDNumber::mode
- \brief the current display mode (number base)
-
- Corresponds to the current display mode, which is one of \c Bin,
- \c Oct, \c Dec (the default) and \c Hex. \c Dec mode can display
- floating point values, the other modes display the integer
- equivalent.
-
- \sa smallDecimalPoint(), setHexMode(), setDecMode(), setOctMode(), setBinMode()
-*/
-
-QLCDNumber::Mode QLCDNumber::mode() const
-{
- Q_D(const QLCDNumber);
- return (QLCDNumber::Mode) d->base;
-}
-
-void QLCDNumber::setMode(Mode m)
-{
- Q_D(QLCDNumber);
- d->base = m;
- display(d->val);
-}
-
-
-/*!
- \property QLCDNumber::value
- \brief the displayed value
-
- This property corresponds to the current value displayed by the
- LCDNumber.
-
- If the displayed value is not a number, the property has a value
- of 0.
-
- By default, this property contains a value of 0.
-*/
-
-double QLCDNumber::value() const
-{
- Q_D(const QLCDNumber);
- return d->val;
-}
-
-/*!
- \overload
-
- Displays the number \a num.
-*/
-void QLCDNumber::display(double num)
-{
- Q_D(QLCDNumber);
- d->val = num;
- bool of;
- QString s = double2string(d->val, d->base, d->ndigits, &of);
- if (of)
- emit overflow();
- else
- d->internalSetString(s);
-}
-
-/*!
- \property QLCDNumber::intValue
- \brief the displayed value rounded to the nearest integer
-
- This property corresponds to the nearest integer to the current
- value displayed by the LCDNumber. This is the value used for
- hexadecimal, octal and binary modes.
-
- If the displayed value is not a number, the property has a value
- of 0.
-
- By default, this property contains a value of 0.
-*/
-int QLCDNumber::intValue() const
-{
- Q_D(const QLCDNumber);
- return qRound(d->val);
-}
-
-
-/*!
- \overload
-
- Displays the number \a num.
-*/
-void QLCDNumber::display(int num)
-{
- Q_D(QLCDNumber);
- d->val = (double)num;
- bool of;
- QString s = int2string(num, d->base, d->ndigits, &of);
- if (of)
- emit overflow();
- else
- d->internalSetString(s);
-}
-
-
-/*!
- Displays the number represented by the string \a s.
-
- This version of the function disregards mode() and
- smallDecimalPoint().
-
- These digits and other symbols can be shown: 0/O, 1, 2, 3, 4, 5/S,
- 6, 7, 8, 9/g, minus, decimal point, A, B, C, D, E, F, h, H, L, o,
- P, r, u, U, Y, colon, degree sign (which is specified as single
- quote in the string) and space. QLCDNumber substitutes spaces for
- illegal characters.
-*/
-
-void QLCDNumber::display(const QString &s)
-{
- Q_D(QLCDNumber);
- d->val = 0;
- bool ok = false;
- double v = s.toDouble(&ok);
- if (ok)
- d->val = v;
- d->internalSetString(s);
-}
-
-/*!
- Calls setMode(Hex). Provided for convenience (e.g. for
- connecting buttons to it).
-
- \sa setMode(), setDecMode(), setOctMode(), setBinMode(), mode()
-*/
-
-void QLCDNumber::setHexMode()
-{
- setMode(Hex);
-}
-
-
-/*!
- Calls setMode(Dec). Provided for convenience (e.g. for
- connecting buttons to it).
-
- \sa setMode(), setHexMode(), setOctMode(), setBinMode(), mode()
-*/
-
-void QLCDNumber::setDecMode()
-{
- setMode(Dec);
-}
-
-
-/*!
- Calls setMode(Oct). Provided for convenience (e.g. for
- connecting buttons to it).
-
- \sa setMode(), setHexMode(), setDecMode(), setBinMode(), mode()
-*/
-
-void QLCDNumber::setOctMode()
-{
- setMode(Oct);
-}
-
-
-/*!
- Calls setMode(Bin). Provided for convenience (e.g. for
- connecting buttons to it).
-
- \sa setMode(), setHexMode(), setDecMode(), setOctMode(), mode()
-*/
-
-void QLCDNumber::setBinMode()
-{
- setMode(Bin);
-}
-
-
-/*!
- \property QLCDNumber::smallDecimalPoint
- \brief the style of the decimal point
-
- If true the decimal point is drawn between two digit positions.
- Otherwise it occupies a digit position of its own, i.e. is drawn
- in a digit position. The default is false.
-
- The inter-digit space is made slightly wider when the decimal
- point is drawn between the digits.
-
- \sa mode
-*/
-
-void QLCDNumber::setSmallDecimalPoint(bool b)
-{
- Q_D(QLCDNumber);
- d->smallPoint = b;
- update();
-}
-
-bool QLCDNumber::smallDecimalPoint() const
-{
- Q_D(const QLCDNumber);
- return d->smallPoint;
-}
-
-
-
-/*!\reimp
-*/
-
-
-void QLCDNumber::paintEvent(QPaintEvent *)
-{
- Q_D(QLCDNumber);
- QPainter p(this);
- drawFrame(&p);
- p.setRenderHint(QPainter::Antialiasing);
- if (d->shadow)
- p.translate(0.5, 0.5);
-
- if (d->smallPoint)
- d->drawString(d->digitStr, p, &d->points, false);
- else
- d->drawString(d->digitStr, p, 0, false);
-}
-
-
-void QLCDNumberPrivate::internalSetString(const QString& s)
-{
- Q_Q(QLCDNumber);
- QString buffer;
- int i;
- int len = s.length();
- QBitArray newPoints(ndigits);
-
- if (!smallPoint) {
- if (len == ndigits)
- buffer = s;
- else
- buffer = s.right(ndigits).rightJustified(ndigits, QLatin1Char(' '));
- } else {
- int index = -1;
- bool lastWasPoint = true;
- newPoints.clearBit(0);
- for (i=0; i<len; i++) {
- if (s[i] == QLatin1Char('.')) {
- if (lastWasPoint) { // point already set for digit?
- if (index == ndigits - 1) // no more digits
- break;
- index++;
- buffer[index] = QLatin1Char(' '); // 2 points in a row, add space
- }
- newPoints.setBit(index); // set decimal point
- lastWasPoint = true;
- } else {
- if (index == ndigits - 1)
- break;
- index++;
- buffer[index] = s[i];
- newPoints.clearBit(index); // decimal point default off
- lastWasPoint = false;
- }
- }
- if (index < ((int) ndigits) - 1) {
- for(i=index; i>=0; i--) {
- buffer[ndigits - 1 - index + i] = buffer[i];
- newPoints.setBit(ndigits - 1 - index + i,
- newPoints.testBit(i));
- }
- for(i=0; i<ndigits-index-1; i++) {
- buffer[i] = QLatin1Char(' ');
- newPoints.clearBit(i);
- }
- }
- }
-
- if (buffer == digitStr)
- return;
-
- digitStr = buffer;
- if (smallPoint)
- points = newPoints;
- q->update();
-}
-
-/*!
- \internal
-*/
-
-void QLCDNumberPrivate::drawString(const QString &s, QPainter &p,
- QBitArray *newPoints, bool newString)
-{
- Q_Q(QLCDNumber);
- QPoint pos;
-
- int digitSpace = smallPoint ? 2 : 1;
- int xSegLen = q->width()*5/(ndigits*(5 + digitSpace) + digitSpace);
- int ySegLen = q->height()*5/12;
- int segLen = ySegLen > xSegLen ? xSegLen : ySegLen;
- int xAdvance = segLen*(5 + digitSpace)/5;
- int xOffset = (q->width() - ndigits*xAdvance + segLen/5)/2;
- int yOffset = (q->height() - segLen*2)/2;
-
- for (int i=0; i<ndigits; i++) {
- pos = QPoint(xOffset + xAdvance*i, yOffset);
- if (newString)
- drawDigit(pos, p, segLen, s[i].toLatin1(), digitStr[i].toLatin1());
- else
- drawDigit(pos, p, segLen, s[i].toLatin1());
- if (newPoints) {
- char newPoint = newPoints->testBit(i) ? '.' : ' ';
- if (newString) {
- char oldPoint = points.testBit(i) ? '.' : ' ';
- drawDigit(pos, p, segLen, newPoint, oldPoint);
- } else {
- drawDigit(pos, p, segLen, newPoint);
- }
- }
- }
- if (newString) {
- digitStr = s;
- digitStr.truncate(ndigits);
- if (newPoints)
- points = *newPoints;
- }
-}
-
-
-/*!
- \internal
-*/
-
-void QLCDNumberPrivate::drawDigit(const QPoint &pos, QPainter &p, int segLen,
- char newCh, char oldCh)
-{
-// Draws and/or erases segments to change display of a single digit
-// from oldCh to newCh
-
- char updates[18][2]; // can hold 2 times number of segments, only
- // first 9 used if segment table is correct
- int nErases;
- int nUpdates;
- const char *segs;
- int i,j;
-
- const char erase = 0;
- const char draw = 1;
- const char leaveAlone = 2;
-
- segs = getSegments(oldCh);
- for (nErases=0; segs[nErases] != 99; nErases++) {
- updates[nErases][0] = erase; // get segments to erase to
- updates[nErases][1] = segs[nErases]; // remove old char
- }
- nUpdates = nErases;
- segs = getSegments(newCh);
- for(i = 0 ; segs[i] != 99 ; i++) {
- for (j=0; j<nErases; j++)
- if (segs[i] == updates[j][1]) { // same segment ?
- updates[j][0] = leaveAlone; // yes, already on screen
- break;
- }
- if (j == nErases) { // if not already on screen
- updates[nUpdates][0] = draw;
- updates[nUpdates][1] = segs[i];
- nUpdates++;
- }
- }
- for (i=0; i<nUpdates; i++) {
- if (updates[i][0] == draw)
- drawSegment(pos, updates[i][1], p, segLen);
- if (updates[i][0] == erase)
- drawSegment(pos, updates[i][1], p, segLen, true);
- }
-}
-
-
-static void addPoint(QPolygon &a, const QPoint &p)
-{
- uint n = a.size();
- a.resize(n + 1);
- a.setPoint(n, p);
-}
-
-/*!
- \internal
-*/
-
-void QLCDNumberPrivate::drawSegment(const QPoint &pos, char segmentNo, QPainter &p,
- int segLen, bool erase)
-{
- Q_Q(QLCDNumber);
- QPoint ppt;
- QPoint pt = pos;
- int width = segLen/5;
-
- const QPalette &pal = q->palette();
- QColor lightColor,darkColor,fgColor;
- if (erase){
- lightColor = pal.color(q->backgroundRole());
- darkColor = lightColor;
- fgColor = lightColor;
- } else {
- lightColor = pal.light().color();
- darkColor = pal.dark().color();
- fgColor = pal.color(q->foregroundRole());
- }
-
-
-#define LINETO(X,Y) addPoint(a, QPoint(pt.x() + (X),pt.y() + (Y)))
-#define LIGHT
-#define DARK
-
- if (fill) {
- QPolygon a(0);
- //The following is an exact copy of the switch below.
- //don't make any changes here
- switch (segmentNo) {
- case 0 :
- ppt = pt;
- LIGHT;
- LINETO(segLen - 1,0);
- DARK;
- LINETO(segLen - width - 1,width);
- LINETO(width,width);
- LINETO(0,0);
- break;
- case 1 :
- pt += QPoint(0 , 1);
- ppt = pt;
- LIGHT;
- LINETO(width,width);
- DARK;
- LINETO(width,segLen - width/2 - 2);
- LINETO(0,segLen - 2);
- LIGHT;
- LINETO(0,0);
- break;
- case 2 :
- pt += QPoint(segLen - 1 , 1);
- ppt = pt;
- DARK;
- LINETO(0,segLen - 2);
- LINETO(-width,segLen - width/2 - 2);
- LIGHT;
- LINETO(-width,width);
- LINETO(0,0);
- break;
- case 3 :
- pt += QPoint(0 , segLen);
- ppt = pt;
- LIGHT;
- LINETO(width,-width/2);
- LINETO(segLen - width - 1,-width/2);
- LINETO(segLen - 1,0);
- DARK;
- if (width & 1) { // adjust for integer division error
- LINETO(segLen - width - 3,width/2 + 1);
- LINETO(width + 2,width/2 + 1);
- } else {
- LINETO(segLen - width - 1,width/2);
- LINETO(width,width/2);
- }
- LINETO(0,0);
- break;
- case 4 :
- pt += QPoint(0 , segLen + 1);
- ppt = pt;
- LIGHT;
- LINETO(width,width/2);
- DARK;
- LINETO(width,segLen - width - 2);
- LINETO(0,segLen - 2);
- LIGHT;
- LINETO(0,0);
- break;
- case 5 :
- pt += QPoint(segLen - 1 , segLen + 1);
- ppt = pt;
- DARK;
- LINETO(0,segLen - 2);
- LINETO(-width,segLen - width - 2);
- LIGHT;
- LINETO(-width,width/2);
- LINETO(0,0);
- break;
- case 6 :
- pt += QPoint(0 , segLen*2);
- ppt = pt;
- LIGHT;
- LINETO(width,-width);
- LINETO(segLen - width - 1,-width);
- LINETO(segLen - 1,0);
- DARK;
- LINETO(0,0);
- break;
- case 7 :
- if (smallPoint) // if smallpoint place'.' between other digits
- pt += QPoint(segLen + width/2 , segLen*2);
- else
- pt += QPoint(segLen/2 , segLen*2);
- ppt = pt;
- DARK;
- LINETO(width,0);
- LINETO(width,-width);
- LIGHT;
- LINETO(0,-width);
- LINETO(0,0);
- break;
- case 8 :
- pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
- ppt = pt;
- DARK;
- LINETO(width,0);
- LINETO(width,-width);
- LIGHT;
- LINETO(0,-width);
- LINETO(0,0);
- break;
- case 9 :
- pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
- ppt = pt;
- DARK;
- LINETO(width,0);
- LINETO(width,-width);
- LIGHT;
- LINETO(0,-width);
- LINETO(0,0);
- break;
- default :
- qWarning("QLCDNumber::drawSegment: (%s) Illegal segment id: %d\n",
- q->objectName().toLocal8Bit().constData(), segmentNo);
- }
- // End exact copy
- p.setPen(Qt::NoPen);
- p.setBrush(fgColor);
- p.drawPolygon(a);
- p.setBrush(Qt::NoBrush);
-
- pt = pos;
- }
-#undef LINETO
-#undef LIGHT
-#undef DARK
-
-#define LINETO(X,Y) p.drawLine(ppt.x(), ppt.y(), pt.x()+(X), pt.y()+(Y)); \
- ppt = QPoint(pt.x()+(X), pt.y()+(Y))
-#define LIGHT p.setPen(lightColor)
-#define DARK p.setPen(darkColor)
- if (shadow)
- switch (segmentNo) {
- case 0 :
- ppt = pt;
- LIGHT;
- LINETO(segLen - 1,0);
- DARK;
- LINETO(segLen - width - 1,width);
- LINETO(width,width);
- LINETO(0,0);
- break;
- case 1 :
- pt += QPoint(0,1);
- ppt = pt;
- LIGHT;
- LINETO(width,width);
- DARK;
- LINETO(width,segLen - width/2 - 2);
- LINETO(0,segLen - 2);
- LIGHT;
- LINETO(0,0);
- break;
- case 2 :
- pt += QPoint(segLen - 1 , 1);
- ppt = pt;
- DARK;
- LINETO(0,segLen - 2);
- LINETO(-width,segLen - width/2 - 2);
- LIGHT;
- LINETO(-width,width);
- LINETO(0,0);
- break;
- case 3 :
- pt += QPoint(0 , segLen);
- ppt = pt;
- LIGHT;
- LINETO(width,-width/2);
- LINETO(segLen - width - 1,-width/2);
- LINETO(segLen - 1,0);
- DARK;
- if (width & 1) { // adjust for integer division error
- LINETO(segLen - width - 3,width/2 + 1);
- LINETO(width + 2,width/2 + 1);
- } else {
- LINETO(segLen - width - 1,width/2);
- LINETO(width,width/2);
- }
- LINETO(0,0);
- break;
- case 4 :
- pt += QPoint(0 , segLen + 1);
- ppt = pt;
- LIGHT;
- LINETO(width,width/2);
- DARK;
- LINETO(width,segLen - width - 2);
- LINETO(0,segLen - 2);
- LIGHT;
- LINETO(0,0);
- break;
- case 5 :
- pt += QPoint(segLen - 1 , segLen + 1);
- ppt = pt;
- DARK;
- LINETO(0,segLen - 2);
- LINETO(-width,segLen - width - 2);
- LIGHT;
- LINETO(-width,width/2);
- LINETO(0,0);
- break;
- case 6 :
- pt += QPoint(0 , segLen*2);
- ppt = pt;
- LIGHT;
- LINETO(width,-width);
- LINETO(segLen - width - 1,-width);
- LINETO(segLen - 1,0);
- DARK;
- LINETO(0,0);
- break;
- case 7 :
- if (smallPoint) // if smallpoint place'.' between other digits
- pt += QPoint(segLen + width/2 , segLen*2);
- else
- pt += QPoint(segLen/2 , segLen*2);
- ppt = pt;
- DARK;
- LINETO(width,0);
- LINETO(width,-width);
- LIGHT;
- LINETO(0,-width);
- LINETO(0,0);
- break;
- case 8 :
- pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
- ppt = pt;
- DARK;
- LINETO(width,0);
- LINETO(width,-width);
- LIGHT;
- LINETO(0,-width);
- LINETO(0,0);
- break;
- case 9 :
- pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
- ppt = pt;
- DARK;
- LINETO(width,0);
- LINETO(width,-width);
- LIGHT;
- LINETO(0,-width);
- LINETO(0,0);
- break;
- default :
- qWarning("QLCDNumber::drawSegment: (%s) Illegal segment id: %d\n",
- q->objectName().toLocal8Bit().constData(), segmentNo);
- }
-
-#undef LINETO
-#undef LIGHT
-#undef DARK
-}
-
-
-
-/*!
- \property QLCDNumber::segmentStyle
- \brief the style of the LCDNumber
-
- \table
- \header \i Style \i Result
- \row \i \c Outline
- \i Produces raised segments filled with the background color
- \row \i \c Filled
- (this is the default).
- \i Produces raised segments filled with the foreground color.
- \row \i \c Flat
- \i Produces flat segments filled with the foreground color.
- \endtable
-
- \c Outline and \c Filled will additionally use
- QPalette::light() and QPalette::dark() for shadow effects.
-*/
-void QLCDNumber::setSegmentStyle(SegmentStyle s)
-{
- Q_D(QLCDNumber);
- d->fill = (s == Flat || s == Filled);
- d->shadow = (s == Outline || s == Filled);
- update();
-}
-
-QLCDNumber::SegmentStyle QLCDNumber::segmentStyle() const
-{
- Q_D(const QLCDNumber);
- Q_ASSERT(d->fill || d->shadow);
- if (!d->fill && d->shadow)
- return Outline;
- if (d->fill && d->shadow)
- return Filled;
- return Flat;
-}
-
-
-/*!\reimp
-*/
-QSize QLCDNumber::sizeHint() const
-{
- return QSize(10 + 9 * (digitCount() + (smallDecimalPoint() ? 0 : 1)), 23);
-}
-
-/*! \reimp */
-bool QLCDNumber::event(QEvent *e)
-{
- return QFrame::event(e);
-}
-
-/*!
- \fn void QLCDNumber::setMargin(int margin)
- Sets the width of the margin around the contents of the widget to \a margin.
-
- Use QWidget::setContentsMargins() instead.
- \sa margin(), QWidget::setContentsMargins()
-*/
-
-/*!
- \fn int QLCDNumber::margin() const
- Returns the width of the margin around the contents of the widget.
-
- Use QWidget::getContentsMargins() instead.
- \sa setMargin(), QWidget::getContentsMargins()
-*/
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_LCDNUMBER
diff --git a/src/gui/widgets/qlcdnumber.h b/src/gui/widgets/qlcdnumber.h
deleted file mode 100644
index b1719881bd..0000000000
--- a/src/gui/widgets/qlcdnumber.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** 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 QLCDNUMBER_H
-#define QLCDNUMBER_H
-
-#include <QtGui/qframe.h>
-#include <QtCore/qbitarray.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_LCDNUMBER
-
-class QLCDNumberPrivate;
-class Q_GUI_EXPORT QLCDNumber : public QFrame // LCD number widget
-{
- Q_OBJECT
- Q_ENUMS(Mode SegmentStyle)
- Q_PROPERTY(bool smallDecimalPoint READ smallDecimalPoint WRITE setSmallDecimalPoint)
- Q_PROPERTY(int numDigits READ numDigits WRITE setNumDigits)
- Q_PROPERTY(int digitCount READ digitCount WRITE setDigitCount)
- Q_PROPERTY(Mode mode READ mode WRITE setMode)
- Q_PROPERTY(SegmentStyle segmentStyle READ segmentStyle WRITE setSegmentStyle)
- Q_PROPERTY(double value READ value WRITE display)
- Q_PROPERTY(int intValue READ intValue WRITE display)
-
-public:
- explicit QLCDNumber(QWidget* parent = 0);
- explicit QLCDNumber(uint numDigits, QWidget* parent = 0);
- ~QLCDNumber();
-
- enum Mode {
- Hex, Dec, Oct, Bin
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- , HEX = Hex, DEC = Dec, OCT = Oct, BIN = Bin
-#endif
- };
- enum SegmentStyle {
- Outline, Filled, Flat
- };
-
- bool smallDecimalPoint() const;
-#ifdef QT_DEPRECATED
- QT_DEPRECATED int numDigits() const;
- QT_DEPRECATED void setNumDigits(int nDigits);
-#endif
- int digitCount() const;
- void setDigitCount(int nDigits);
-
- bool checkOverflow(double num) const;
- bool checkOverflow(int num) const;
-
- Mode mode() const;
- void setMode(Mode);
-
- SegmentStyle segmentStyle() const;
- void setSegmentStyle(SegmentStyle);
-
- double value() const;
- int intValue() const;
-
- QSize sizeHint() const;
-
-public Q_SLOTS:
- void display(const QString &str);
- void display(int num);
- void display(double num);
- void setHexMode();
- void setDecMode();
- void setOctMode();
- void setBinMode();
- void setSmallDecimalPoint(bool);
-
-Q_SIGNALS:
- void overflow();
-
-protected:
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *);
-
-public:
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QLCDNumber(QWidget* parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QLCDNumber(uint numDigits, QWidget* parent, const char* name);
-
- QT3_SUPPORT void setMargin(int margin) { setContentsMargins(margin, margin, margin, margin); }
- QT3_SUPPORT int margin() const
- { int margin; int dummy; getContentsMargins(&margin, &dummy, &dummy, &dummy); return margin; }
-#endif
-
-private:
- Q_DISABLE_COPY(QLCDNumber)
- Q_DECLARE_PRIVATE(QLCDNumber)
-};
-
-#endif // QT_NO_LCDNUMBER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLCDNUMBER_H
diff --git a/src/gui/widgets/qlineedit.cpp b/src/gui/widgets/qlineedit.cpp
deleted file mode 100644
index 43c3f52d2b..0000000000
--- a/src/gui/widgets/qlineedit.cpp
+++ /dev/null
@@ -1,2360 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlineedit.h"
-#include "qlineedit_p.h"
-
-#ifndef QT_NO_LINEEDIT
-#include "qaction.h"
-#include "qapplication.h"
-#include "qclipboard.h"
-#include "qdrag.h"
-#include "qdrawutil.h"
-#include "qevent.h"
-#include "qfontmetrics.h"
-#include "qmenu.h"
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qpointer.h"
-#include "qstringlist.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qtimer.h"
-#include "qvalidator.h"
-#include "qvariant.h"
-#include "qvector.h"
-#include "qwhatsthis.h"
-#include "qdebug.h"
-#include "qtextedit.h"
-#include <private/qtextedit_p.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#ifndef QT_NO_IM
-#include "qinputcontext.h"
-#include "qlist.h"
-#endif
-#include "qabstractitemview.h"
-#include "private/qstylesheetstyle_p.h"
-
-#ifndef QT_NO_SHORTCUT
-#include "private/qapplication_p.h"
-#include "private/qshortcutmap_p.h"
-#include "qkeysequence.h"
-#define ACCEL_KEY(k) (!qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? QLatin1Char('\t') + QString(QKeySequence(k)) : QString())
-#else
-#define ACCEL_KEY(k) QString()
-#endif
-
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifdef Q_WS_MAC
-extern void qt_mac_secure_keyboard(bool); //qapplication_mac.cpp
-#endif
-
-/*!
- Initialize \a option with the values from this QLineEdit. This method
- is useful for subclasses when they need a QStyleOptionFrame or QStyleOptionFrameV2, but don't want
- to fill in all the information themselves. This function will check the version
- of the QStyleOptionFrame and fill in the additional values for a
- QStyleOptionFrameV2.
-
- \sa QStyleOption::initFrom()
-*/
-void QLineEdit::initStyleOption(QStyleOptionFrame *option) const
-{
- if (!option)
- return;
-
- Q_D(const QLineEdit);
- option->initFrom(this);
- option->rect = contentsRect();
- option->lineWidth = d->frame ? style()->pixelMetric(QStyle::PM_DefaultFrameWidth, option, this)
- : 0;
- option->midLineWidth = 0;
- option->state |= QStyle::State_Sunken;
- if (d->control->isReadOnly())
- option->state |= QStyle::State_ReadOnly;
-#ifdef QT_KEYPAD_NAVIGATION
- if (hasEditFocus())
- option->state |= QStyle::State_HasEditFocus;
-#endif
- if (QStyleOptionFrameV2 *optionV2 = qstyleoption_cast<QStyleOptionFrameV2 *>(option))
- optionV2->features = QStyleOptionFrameV2::None;
-}
-
-/*!
- \class QLineEdit
- \brief The QLineEdit widget is a one-line text editor.
-
- \ingroup basicwidgets
-
-
- A line edit allows the user to enter and edit a single line of
- plain text with a useful collection of editing functions,
- including undo and redo, cut and paste, and drag and drop.
-
- By changing the echoMode() of a line edit, it can also be used as
- a "write-only" field, for inputs such as passwords.
-
- The length of the text can be constrained to maxLength(). The text
- can be arbitrarily constrained using a validator() or an
- inputMask(), or both. When switching between a validator and an input mask
- on the same line edit, it is best to clear the validator or input mask to
- prevent undefined behavior.
-
-
- A related class is QTextEdit which allows multi-line, rich text
- editing.
-
- You can change the text with setText() or insert(). The text is
- retrieved with text(); the displayed text (which may be different,
- see \l{EchoMode}) is retrieved with displayText(). Text can be
- selected with setSelection() or selectAll(), and the selection can
- be cut(), copy()ied and paste()d. The text can be aligned with
- setAlignment().
-
- When the text changes the textChanged() signal is emitted; when
- the text changes other than by calling setText() the textEdited()
- signal is emitted; when the cursor is moved the
- cursorPositionChanged() signal is emitted; and when the Return or
- Enter key is pressed the returnPressed() signal is emitted.
-
- When editing is finished, either because the line edit lost focus
- or Return/Enter is pressed the editingFinished() signal is
- emitted.
-
- Note that if there is a validator set on the line edit, the
- returnPressed()/editingFinished() signals will only be emitted if
- the validator returns QValidator::Acceptable.
-
- By default, QLineEdits have a frame as specified by the Windows
- and Motif style guides; you can turn it off by calling
- setFrame(false).
-
- The default key bindings are described below. The line edit also
- provides a context menu (usually invoked by a right mouse click)
- that presents some of these editing options.
- \target desc
- \table
- \header \i Keypress \i Action
- \row \i Left Arrow \i Moves the cursor one character to the left.
- \row \i Shift+Left Arrow \i Moves and selects text one character to the left.
- \row \i Right Arrow \i Moves the cursor one character to the right.
- \row \i Shift+Right Arrow \i Moves and selects text one character to the right.
- \row \i Home \i Moves the cursor to the beginning of the line.
- \row \i End \i Moves the cursor to the end of the line.
- \row \i Backspace \i Deletes the character to the left of the cursor.
- \row \i Ctrl+Backspace \i Deletes the word to the left of the cursor.
- \row \i Delete \i Deletes the character to the right of the cursor.
- \row \i Ctrl+Delete \i Deletes the word to the right of the cursor.
- \row \i Ctrl+A \i Select all.
- \row \i Ctrl+C \i Copies the selected text to the clipboard.
- \row \i Ctrl+Insert \i Copies the selected text to the clipboard.
- \row \i Ctrl+K \i Deletes to the end of the line.
- \row \i Ctrl+V \i Pastes the clipboard text into line edit.
- \row \i Shift+Insert \i Pastes the clipboard text into line edit.
- \row \i Ctrl+X \i Deletes the selected text and copies it to the clipboard.
- \row \i Shift+Delete \i Deletes the selected text and copies it to the clipboard.
- \row \i Ctrl+Z \i Undoes the last operation.
- \row \i Ctrl+Y \i Redoes the last undone operation.
- \endtable
-
- Any other key sequence that represents a valid character, will
- cause the character to be inserted into the line edit.
-
- \table 100%
- \row \o \inlineimage macintosh-lineedit.png Screenshot of a Macintosh style line edit
- \o A line edit shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row \o \inlineimage windows-lineedit.png Screenshot of a Windows XP style line edit
- \o A line edit shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage plastique-lineedit.png Screenshot of a Plastique style line edit
- \o A line edit shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QTextEdit, QLabel, QComboBox, {fowler}{GUI Design Handbook: Field, Entry}, {Line Edits Example}
-*/
-
-
-/*!
- \fn void QLineEdit::textChanged(const QString &text)
-
- This signal is emitted whenever the text changes. The \a text
- argument is the new text.
-
- Unlike textEdited(), this signal is also emitted when the text is
- changed programmatically, for example, by calling setText().
-*/
-
-/*!
- \fn void QLineEdit::textEdited(const QString &text)
-
- This signal is emitted whenever the text is edited. The \a text
- argument is the next text.
-
- Unlike textChanged(), this signal is not emitted when the text is
- changed programmatically, for example, by calling setText().
-*/
-
-/*!
- \fn void QLineEdit::cursorPositionChanged(int old, int new)
-
- This signal is emitted whenever the cursor moves. The previous
- position is given by \a old, and the new position by \a new.
-
- \sa setCursorPosition(), cursorPosition()
-*/
-
-/*!
- \fn void QLineEdit::selectionChanged()
-
- This signal is emitted whenever the selection changes.
-
- \sa hasSelectedText(), selectedText()
-*/
-
-/*!
- Constructs a line edit with no text.
-
- The maximum text length is set to 32767 characters.
-
- The \a parent argument is sent to the QWidget constructor.
-
- \sa setText(), setMaxLength()
-*/
-QLineEdit::QLineEdit(QWidget* parent)
- : QWidget(*new QLineEditPrivate, parent,0)
-{
- Q_D(QLineEdit);
- d->init(QString());
-}
-
-/*!
- Constructs a line edit containing the text \a contents.
-
- The cursor position is set to the end of the line and the maximum
- text length to 32767 characters.
-
- The \a parent and argument is sent to the QWidget
- constructor.
-
- \sa text(), setMaxLength()
-*/
-QLineEdit::QLineEdit(const QString& contents, QWidget* parent)
- : QWidget(*new QLineEditPrivate, parent, 0)
-{
- Q_D(QLineEdit);
- d->init(contents);
-}
-
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a line edit with no text.
-
- The maximum text length is set to 32767 characters.
-
- The \a parent and \a name arguments are sent to the QWidget constructor.
-
- \sa setText(), setMaxLength()
-*/
-QLineEdit::QLineEdit(QWidget* parent, const char* name)
- : QWidget(*new QLineEditPrivate, parent,0)
-{
- Q_D(QLineEdit);
- setObjectName(QString::fromAscii(name));
- d->init(QString());
-}
-
-/*!
- Constructs a line edit containing the text \a contents.
-
- The cursor position is set to the end of the line and the maximum
- text length to 32767 characters.
-
- The \a parent and \a name arguments are sent to the QWidget
- constructor.
-
- \sa text(), setMaxLength()
-*/
-
-QLineEdit::QLineEdit(const QString& contents, QWidget* parent, const char* name)
- : QWidget(*new QLineEditPrivate, parent, 0)
-{
- Q_D(QLineEdit);
- setObjectName(QString::fromAscii(name));
- d->init(contents);
-}
-
-/*!
- Constructs a line edit with an input \a inputMask and the text \a
- contents.
-
- The cursor position is set to the end of the line and the maximum
- text length is set to the length of the mask (the number of mask
- characters and separators).
-
- The \a parent and \a name arguments are sent to the QWidget
- constructor.
-
- \sa setMask() text()
-*/
-QLineEdit::QLineEdit(const QString& contents, const QString &inputMask, QWidget* parent, const char* name)
- : QWidget(*new QLineEditPrivate, parent, 0)
-{
- Q_D(QLineEdit);
- setObjectName(QString::fromAscii(name));
- d->init(contents);
- d->control->setInputMask(inputMask);
- d->control->moveCursor(d->control->nextMaskBlank(contents.length()));
-}
-#endif
-
-/*!
- Destroys the line edit.
-*/
-
-QLineEdit::~QLineEdit()
-{
-}
-
-
-/*!
- \property QLineEdit::text
- \brief the line edit's text
-
- Setting this property clears the selection, clears the undo/redo
- history, moves the cursor to the end of the line and resets the
- \l modified property to false. The text is not validated when
- inserted with setText().
-
- The text is truncated to maxLength() length.
-
- By default, this property contains an empty string.
-
- \sa insert(), clear()
-*/
-QString QLineEdit::text() const
-{
- Q_D(const QLineEdit);
- return d->control->text();
-}
-
-void QLineEdit::setText(const QString& text)
-{
- Q_D(QLineEdit);
- d->control->setText(text);
-}
-
-/*!
- \since 4.7
-
- \property QLineEdit::placeholderText
- \brief the line edit's placeholder text
-
- Setting this property makes the line edit display a grayed-out
- placeholder text as long as the text() is empty and the widget doesn't
- have focus.
-
- By default, this property contains an empty string.
-
- \sa text()
-*/
-QString QLineEdit::placeholderText() const
-{
- Q_D(const QLineEdit);
- return d->placeholderText;
-}
-
-void QLineEdit::setPlaceholderText(const QString& placeholderText)
-{
- Q_D(QLineEdit);
- if (d->placeholderText != placeholderText) {
- d->placeholderText = placeholderText;
- if (!hasFocus())
- update();
- }
-}
-
-/*!
- \property QLineEdit::displayText
- \brief the displayed text
-
- If \l echoMode is \l Normal this returns the same as text(); if
- \l EchoMode is \l Password or \l PasswordEchoOnEdit it returns a string of asterisks
- text().length() characters long, e.g. "******"; if \l EchoMode is
- \l NoEcho returns an empty string, "".
-
- By default, this property contains an empty string.
-
- \sa setEchoMode() text() EchoMode
-*/
-
-QString QLineEdit::displayText() const
-{
- Q_D(const QLineEdit);
- return d->control->displayText();
-}
-
-
-/*!
- \property QLineEdit::maxLength
- \brief the maximum permitted length of the text
-
- If the text is too long, it is truncated at the limit.
-
- If truncation occurs any selected text will be unselected, the
- cursor position is set to 0 and the first part of the string is
- shown.
-
- If the line edit has an input mask, the mask defines the maximum
- string length.
-
- By default, this property contains a value of 32767.
-
- \sa inputMask
-*/
-
-int QLineEdit::maxLength() const
-{
- Q_D(const QLineEdit);
- return d->control->maxLength();
-}
-
-void QLineEdit::setMaxLength(int maxLength)
-{
- Q_D(QLineEdit);
- d->control->setMaxLength(maxLength);
-}
-
-/*!
- \property QLineEdit::frame
- \brief whether the line edit draws itself with a frame
-
- If enabled (the default) the line edit draws itself inside a
- frame, otherwise the line edit draws itself without any frame.
-*/
-bool QLineEdit::hasFrame() const
-{
- Q_D(const QLineEdit);
- return d->frame;
-}
-
-
-void QLineEdit::setFrame(bool enable)
-{
- Q_D(QLineEdit);
- d->frame = enable;
- update();
- updateGeometry();
-}
-
-
-/*!
- \enum QLineEdit::EchoMode
-
- This enum type describes how a line edit should display its
- contents.
-
- \value Normal Display characters as they are entered. This is the
- default.
- \value NoEcho Do not display anything. This may be appropriate
- for passwords where even the length of the
- password should be kept secret.
- \value Password Display asterisks instead of the characters
- actually entered.
- \value PasswordEchoOnEdit Display characters as they are entered
- while editing otherwise display asterisks.
-
- \sa setEchoMode() echoMode()
-*/
-
-
-/*!
- \property QLineEdit::echoMode
- \brief the line edit's echo mode
-
- The echo mode determines how the text entered in the line edit is
- displayed (or echoed) to the user.
-
- The most common setting is \l Normal, in which the text entered by the
- user is displayed verbatim, but QLineEdit also supports modes that allow
- the entered text to be suppressed or obscured: these include \l NoEcho,
- \l Password and \l PasswordEchoOnEdit.
-
- The widget's display and the ability to copy or drag the text is
- affected by this setting.
-
- By default, this property is set to \l Normal.
-
- \sa EchoMode displayText()
-*/
-
-QLineEdit::EchoMode QLineEdit::echoMode() const
-{
- Q_D(const QLineEdit);
- return (EchoMode) d->control->echoMode();
-}
-
-void QLineEdit::setEchoMode(EchoMode mode)
-{
- Q_D(QLineEdit);
- if (mode == (EchoMode)d->control->echoMode())
- return;
- Qt::InputMethodHints imHints = inputMethodHints();
- if (mode == Password || mode == NoEcho) {
- imHints |= Qt::ImhHiddenText;
- } else {
- imHints &= ~Qt::ImhHiddenText;
- }
- if (mode != Normal) {
- imHints |= (Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
- } else {
- imHints &= ~(Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText);
- }
- setInputMethodHints(imHints);
- d->control->setEchoMode(mode);
- update();
-#ifdef Q_WS_MAC
- if (hasFocus())
- qt_mac_secure_keyboard(mode == Password || mode == NoEcho);
-#endif
-}
-
-
-#ifndef QT_NO_VALIDATOR
-/*!
- Returns a pointer to the current input validator, or 0 if no
- validator has been set.
-
- \sa setValidator()
-*/
-
-const QValidator * QLineEdit::validator() const
-{
- Q_D(const QLineEdit);
- return d->control->validator();
-}
-
-/*!
- Sets this line edit to only accept input that the validator, \a v,
- will accept. This allows you to place any arbitrary constraints on
- the text which may be entered.
-
- If \a v == 0, setValidator() removes the current input validator.
- The initial setting is to have no input validator (i.e. any input
- is accepted up to maxLength()).
-
- \sa validator() QIntValidator QDoubleValidator QRegExpValidator
-*/
-
-void QLineEdit::setValidator(const QValidator *v)
-{
- Q_D(QLineEdit);
- d->control->setValidator(v);
-}
-#endif // QT_NO_VALIDATOR
-
-#ifndef QT_NO_COMPLETER
-/*!
- \since 4.2
-
- Sets this line edit to provide auto completions from the completer, \a c.
- The completion mode is set using QCompleter::setCompletionMode().
-
- To use a QCompleter with a QValidator or QLineEdit::inputMask, you need to
- ensure that the model provided to QCompleter contains valid entries. You can
- use the QSortFilterProxyModel to ensure that the QCompleter's model contains
- only valid entries.
-
- If \a c == 0, setCompleter() removes the current completer, effectively
- disabling auto completion.
-
- \sa QCompleter
-*/
-void QLineEdit::setCompleter(QCompleter *c)
-{
- Q_D(QLineEdit);
- if (c == d->control->completer())
- return;
- if (d->control->completer()) {
- disconnect(d->control->completer(), 0, this, 0);
- d->control->completer()->setWidget(0);
- if (d->control->completer()->parent() == this)
- delete d->control->completer();
- }
- d->control->setCompleter(c);
- if (!c)
- return;
- if (c->widget() == 0)
- c->setWidget(this);
- if (hasFocus()) {
- QObject::connect(d->control->completer(), SIGNAL(activated(QString)),
- this, SLOT(setText(QString)));
- QObject::connect(d->control->completer(), SIGNAL(highlighted(QString)),
- this, SLOT(_q_completionHighlighted(QString)));
- }
-}
-
-/*!
- \since 4.2
-
- Returns the current QCompleter that provides completions.
-*/
-QCompleter *QLineEdit::completer() const
-{
- Q_D(const QLineEdit);
- return d->control->completer();
-}
-
-#endif // QT_NO_COMPLETER
-
-/*!
- Returns a recommended size for the widget.
-
- The width returned, in pixels, is usually enough for about 15 to
- 20 characters.
-*/
-
-QSize QLineEdit::sizeHint() const
-{
- Q_D(const QLineEdit);
- ensurePolished();
- QFontMetrics fm(font());
- int h = qMax(fm.height(), 14) + 2*d->verticalMargin
- + d->topTextMargin + d->bottomTextMargin
- + d->topmargin + d->bottommargin;
- int w = fm.width(QLatin1Char('x')) * 17 + 2*d->horizontalMargin
- + d->leftTextMargin + d->rightTextMargin
- + d->leftmargin + d->rightmargin; // "some"
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
- return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
- expandedTo(QApplication::globalStrut()), this));
-}
-
-
-/*!
- Returns a minimum size for the line edit.
-
- The width returned is enough for at least one character.
-*/
-
-QSize QLineEdit::minimumSizeHint() const
-{
- Q_D(const QLineEdit);
- ensurePolished();
- QFontMetrics fm = fontMetrics();
- int h = fm.height() + qMax(2*d->verticalMargin, fm.leading())
- + d->topmargin + d->bottommargin;
- int w = fm.maxWidth() + d->leftmargin + d->rightmargin;
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
- return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
- expandedTo(QApplication::globalStrut()), this));
-}
-
-
-/*!
- \property QLineEdit::cursorPosition
- \brief the current cursor position for this line edit
-
- Setting the cursor position causes a repaint when appropriate.
-
- By default, this property contains a value of 0.
-*/
-
-int QLineEdit::cursorPosition() const
-{
- Q_D(const QLineEdit);
- return d->control->cursorPosition();
-}
-
-void QLineEdit::setCursorPosition(int pos)
-{
- Q_D(QLineEdit);
- d->control->setCursorPosition(pos);
-}
-
-/*!
- Returns the cursor position under the point \a pos.
-*/
-// ### What should this do if the point is outside of contentsRect? Currently returns 0.
-int QLineEdit::cursorPositionAt(const QPoint &pos)
-{
- Q_D(QLineEdit);
- return d->xToPos(pos.x());
-}
-
-
-#ifdef QT3_SUPPORT
-/*! \obsolete
-
- Use setText(), setCursorPosition() and setSelection() instead.
-*/
-bool QLineEdit::validateAndSet(const QString &newText, int newPos,
- int newMarkAnchor, int newMarkDrag)
-{
- // The suggested functions above in the docs don't seem to validate,
- // below code tries to mimic previous behaviour.
- QString oldText = text();
- setText(newText);
- if(!hasAcceptableInput()){
- setText(oldText);
- return false;
- }
- int selstart = qMin(newMarkAnchor, newMarkDrag);
- int sellength = qAbs(newMarkAnchor - newMarkDrag);
- if (selstart == newPos) {
- selstart = qMax(newMarkAnchor, newMarkDrag);
- sellength = -sellength;
- }
- //setSelection also set the position
- setSelection(selstart, sellength);
- return true;
-}
-#endif //QT3_SUPPORT
-
-/*!
- \property QLineEdit::alignment
- \brief the alignment of the line edit
-
- Both horizontal and vertical alignment is allowed here, Qt::AlignJustify
- will map to Qt::AlignLeft.
-
- By default, this property contains a combination of Qt::AlignLeft and Qt::AlignVCenter.
-
- \sa Qt::Alignment
-*/
-
-Qt::Alignment QLineEdit::alignment() const
-{
- Q_D(const QLineEdit);
- return QFlag(d->alignment);
-}
-
-void QLineEdit::setAlignment(Qt::Alignment alignment)
-{
- Q_D(QLineEdit);
- d->alignment = alignment;
- update();
-}
-
-
-/*!
- Moves the cursor forward \a steps characters. If \a mark is true
- each character moved over is added to the selection; if \a mark is
- false the selection is cleared.
-
- \sa cursorBackward()
-*/
-
-void QLineEdit::cursorForward(bool mark, int steps)
-{
- Q_D(QLineEdit);
- d->control->cursorForward(mark, steps);
-}
-
-
-/*!
- Moves the cursor back \a steps characters. If \a mark is true each
- character moved over is added to the selection; if \a mark is
- false the selection is cleared.
-
- \sa cursorForward()
-*/
-void QLineEdit::cursorBackward(bool mark, int steps)
-{
- cursorForward(mark, -steps);
-}
-
-/*!
- Moves the cursor one word forward. If \a mark is true, the word is
- also selected.
-
- \sa cursorWordBackward()
-*/
-void QLineEdit::cursorWordForward(bool mark)
-{
- Q_D(QLineEdit);
- d->control->cursorWordForward(mark);
-}
-
-/*!
- Moves the cursor one word backward. If \a mark is true, the word
- is also selected.
-
- \sa cursorWordForward()
-*/
-
-void QLineEdit::cursorWordBackward(bool mark)
-{
- Q_D(QLineEdit);
- d->control->cursorWordBackward(mark);
-}
-
-
-/*!
- If no text is selected, deletes the character to the left of the
- text cursor and moves the cursor one position to the left. If any
- text is selected, the cursor is moved to the beginning of the
- selected text and the selected text is deleted.
-
- \sa del()
-*/
-void QLineEdit::backspace()
-{
- Q_D(QLineEdit);
- d->control->backspace();
-}
-
-/*!
- If no text is selected, deletes the character to the right of the
- text cursor. If any text is selected, the cursor is moved to the
- beginning of the selected text and the selected text is deleted.
-
- \sa backspace()
-*/
-
-void QLineEdit::del()
-{
- Q_D(QLineEdit);
- d->control->del();
-}
-
-/*!
- Moves the text cursor to the beginning of the line unless it is
- already there. If \a mark is true, text is selected towards the
- first position; otherwise, any selected text is unselected if the
- cursor is moved.
-
- \sa end()
-*/
-
-void QLineEdit::home(bool mark)
-{
- Q_D(QLineEdit);
- d->control->home(mark);
-}
-
-/*!
- Moves the text cursor to the end of the line unless it is already
- there. If \a mark is true, text is selected towards the last
- position; otherwise, any selected text is unselected if the cursor
- is moved.
-
- \sa home()
-*/
-
-void QLineEdit::end(bool mark)
-{
- Q_D(QLineEdit);
- d->control->end(mark);
-}
-
-
-/*!
- \property QLineEdit::modified
- \brief whether the line edit's contents has been modified by the user
-
- The modified flag is never read by QLineEdit; it has a default value
- of false and is changed to true whenever the user changes the line
- edit's contents.
-
- This is useful for things that need to provide a default value but
- do not start out knowing what the default should be (perhaps it
- depends on other fields on the form). Start the line edit without
- the best default, and when the default is known, if modified()
- returns false (the user hasn't entered any text), insert the
- default value.
-
- Calling setText() resets the modified flag to false.
-*/
-
-bool QLineEdit::isModified() const
-{
- Q_D(const QLineEdit);
- return d->control->isModified();
-}
-
-void QLineEdit::setModified(bool modified)
-{
- Q_D(QLineEdit);
- d->control->setModified(modified);
-}
-
-
-/*!\fn QLineEdit::clearModified()
-
-Use setModified(false) instead.
-
- \sa isModified()
-*/
-
-
-/*!
- \property QLineEdit::hasSelectedText
- \brief whether there is any text selected
-
- hasSelectedText() returns true if some or all of the text has been
- selected by the user; otherwise returns false.
-
- By default, this property is false.
-
- \sa selectedText()
-*/
-
-
-bool QLineEdit::hasSelectedText() const
-{
- Q_D(const QLineEdit);
- return d->control->hasSelectedText();
-}
-
-/*!
- \property QLineEdit::selectedText
- \brief the selected text
-
- If there is no selected text this property's value is
- an empty string.
-
- By default, this property contains an empty string.
-
- \sa hasSelectedText()
-*/
-
-QString QLineEdit::selectedText() const
-{
- Q_D(const QLineEdit);
- return d->control->selectedText();
-}
-
-/*!
- selectionStart() returns the index of the first selected character in the
- line edit or -1 if no text is selected.
-
- \sa selectedText()
-*/
-
-int QLineEdit::selectionStart() const
-{
- Q_D(const QLineEdit);
- return d->control->selectionStart();
-}
-
-
-#ifdef QT3_SUPPORT
-
-/*!
- \fn void QLineEdit::lostFocus()
-
- This signal is emitted when the line edit has lost focus.
-
- Use editingFinished() instead
- \sa editingFinished(), returnPressed()
-*/
-
-/*!
- Use isModified() instead.
-*/
-bool QLineEdit::edited() const { return isModified(); }
-/*!
- Use setModified() or setText().
-*/
-void QLineEdit::setEdited(bool on) { setModified(on); }
-
-/*!
- There exists no equivalent functionality in Qt 4.
-*/
-int QLineEdit::characterAt(int xpos, QChar *chr) const
-{
- Q_D(const QLineEdit);
- int pos = d->xToPos(xpos + contentsRect().x() - d->hscroll + d->horizontalMargin);
- QString txt = d->control->text();
- if (chr && pos < (int) txt.length())
- *chr = txt.at(pos);
- return pos;
-
-}
-
-/*!
- Use selectedText() and selectionStart() instead.
-*/
-bool QLineEdit::getSelection(int *start, int *end)
-{
- Q_D(QLineEdit);
- if (d->control->hasSelectedText() && start && end) {
- *start = selectionStart();
- *end = *start + selectedText().length();
- return true;
- }
- return false;
-}
-#endif
-
-
-/*!
- Selects text from position \a start and for \a length characters.
- Negative lengths are allowed.
-
- \sa deselect() selectAll() selectedText()
-*/
-
-void QLineEdit::setSelection(int start, int length)
-{
- Q_D(QLineEdit);
- if (start < 0 || start > (int)d->control->text().length()) {
- qWarning("QLineEdit::setSelection: Invalid start position (%d)", start);
- return;
- }
-
- d->control->setSelection(start, length);
-
- if (d->control->hasSelectedText()){
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
- if (!style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
- d->setCursorVisible(false);
- }
-}
-
-
-/*!
- \property QLineEdit::undoAvailable
- \brief whether undo is available
-
- Undo becomes available once the user has modified the text in the line edit.
-
- By default, this property is false.
-*/
-
-bool QLineEdit::isUndoAvailable() const
-{
- Q_D(const QLineEdit);
- return d->control->isUndoAvailable();
-}
-
-/*!
- \property QLineEdit::redoAvailable
- \brief whether redo is available
-
- Redo becomes available once the user has performed one or more undo operations
- on text in the line edit.
-
- By default, this property is false.
-*/
-
-bool QLineEdit::isRedoAvailable() const
-{
- Q_D(const QLineEdit);
- return d->control->isRedoAvailable();
-}
-
-/*!
- \property QLineEdit::dragEnabled
- \brief whether the lineedit starts a drag if the user presses and
- moves the mouse on some selected text
-
- Dragging is disabled by default.
-*/
-
-bool QLineEdit::dragEnabled() const
-{
- Q_D(const QLineEdit);
- return d->dragEnabled;
-}
-
-void QLineEdit::setDragEnabled(bool b)
-{
- Q_D(QLineEdit);
- d->dragEnabled = b;
-}
-
-
-/*!
- \property QLineEdit::cursorMoveStyle
- \brief the movement style of cursor in this line edit
- \since 4.8
-
- When this property is set to QTextCursor::Visual, the line edit will use visual
- movement style. Pressing the left arrow key will always cause the cursor to move
- left, regardless of the text's writing direction. The same behavior applies to
- right arrow key.
-
- When the property is QTextCursor::Logical (the default), within a LTR text block,
- increase cursor position when pressing left arrow key, decrease cursor position
- when pressing the right arrow key. If the text block is right to left, the opposite
- behavior applies.
-*/
-
-QTextCursor::MoveStyle QLineEdit::cursorMoveStyle() const
-{
- Q_D(const QLineEdit);
- return d->control->cursorMoveStyle();
-}
-
-void QLineEdit::setCursorMoveStyle(QTextCursor::MoveStyle style)
-{
- Q_D(QLineEdit);
- d->control->setCursorMoveStyle(style);
-}
-
-/*!
- \property QLineEdit::acceptableInput
- \brief whether the input satisfies the inputMask and the
- validator.
-
- By default, this property is true.
-
- \sa setInputMask(), setValidator()
-*/
-bool QLineEdit::hasAcceptableInput() const
-{
- Q_D(const QLineEdit);
- return d->control->hasAcceptableInput();
-}
-
-/*!
- Sets the margins around the text inside the frame to have the
- sizes \a left, \a top, \a right, and \a bottom.
- \since 4.5
-
- See also getTextMargins().
-*/
-void QLineEdit::setTextMargins(int left, int top, int right, int bottom)
-{
- Q_D(QLineEdit);
- d->leftTextMargin = left;
- d->topTextMargin = top;
- d->rightTextMargin = right;
- d->bottomTextMargin = bottom;
- updateGeometry();
- update();
-}
-
-/*!
- \since 4.6
- Sets the \a margins around the text inside the frame.
-
- See also textMargins().
-*/
-void QLineEdit::setTextMargins(const QMargins &margins)
-{
- setTextMargins(margins.left(), margins.top(), margins.right(), margins.bottom());
-}
-
-/*!
- Returns the widget's text margins for \a left, \a top, \a right, and \a bottom.
- \since 4.5
-
- \sa setTextMargins()
-*/
-void QLineEdit::getTextMargins(int *left, int *top, int *right, int *bottom) const
-{
- Q_D(const QLineEdit);
- if (left)
- *left = d->leftTextMargin;
- if (top)
- *top = d->topTextMargin;
- if (right)
- *right = d->rightTextMargin;
- if (bottom)
- *bottom = d->bottomTextMargin;
-}
-
-/*!
- \since 4.6
- Returns the widget's text margins.
-
- \sa setTextMargins()
-*/
-QMargins QLineEdit::textMargins() const
-{
- Q_D(const QLineEdit);
- return QMargins(d->leftTextMargin, d->topTextMargin, d->rightTextMargin, d->bottomTextMargin);
-}
-
-/*!
- \property QLineEdit::inputMask
- \brief The validation input mask
-
- If no mask is set, inputMask() returns an empty string.
-
- Sets the QLineEdit's validation mask. Validators can be used
- instead of, or in conjunction with masks; see setValidator().
-
- Unset the mask and return to normal QLineEdit operation by passing
- an empty string ("") or just calling setInputMask() with no
- arguments.
-
- The table below shows the characters that can be used in an input mask.
- A space character, the default character for a blank, is needed for cases
- where a character is \e{permitted but not required}.
-
- \table
- \header \i Character \i Meaning
- \row \i \c A \i ASCII alphabetic character required. A-Z, a-z.
- \row \i \c a \i ASCII alphabetic character permitted but not required.
- \row \i \c N \i ASCII alphanumeric character required. A-Z, a-z, 0-9.
- \row \i \c n \i ASCII alphanumeric character permitted but not required.
- \row \i \c X \i Any character required.
- \row \i \c x \i Any character permitted but not required.
- \row \i \c 9 \i ASCII digit required. 0-9.
- \row \i \c 0 \i ASCII digit permitted but not required.
- \row \i \c D \i ASCII digit required. 1-9.
- \row \i \c d \i ASCII digit permitted but not required (1-9).
- \row \i \c # \i ASCII digit or plus/minus sign permitted but not required.
- \row \i \c H \i Hexadecimal character required. A-F, a-f, 0-9.
- \row \i \c h \i Hexadecimal character permitted but not required.
- \row \i \c B \i Binary character required. 0-1.
- \row \i \c b \i Binary character permitted but not required.
- \row \i \c > \i All following alphabetic characters are uppercased.
- \row \i \c < \i All following alphabetic characters are lowercased.
- \row \i \c ! \i Switch off case conversion.
- \row \i \tt{\\} \i Use \tt{\\} to escape the special
- characters listed above to use them as
- separators.
- \endtable
-
- The mask consists of a string of mask characters and separators,
- optionally followed by a semicolon and the character used for
- blanks. The blank characters are always removed from the text
- after editing.
-
- Examples:
- \table
- \header \i Mask \i Notes
- \row \i \c 000.000.000.000;_ \i IP address; blanks are \c{_}.
- \row \i \c HH:HH:HH:HH:HH:HH;_ \i MAC address
- \row \i \c 0000-00-00 \i ISO Date; blanks are \c space
- \row \i \c >AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;# \i License number;
- blanks are \c - and all (alphabetic) characters are converted to
- uppercase.
- \endtable
-
- To get range control (e.g., for an IP address) use masks together
- with \link setValidator() validators\endlink.
-
- \sa maxLength
-*/
-QString QLineEdit::inputMask() const
-{
- Q_D(const QLineEdit);
- return d->control->inputMask();
-}
-
-void QLineEdit::setInputMask(const QString &inputMask)
-{
- Q_D(QLineEdit);
- d->control->setInputMask(inputMask);
-}
-
-/*!
- Selects all the text (i.e. highlights it) and moves the cursor to
- the end. This is useful when a default value has been inserted
- because if the user types before clicking on the widget, the
- selected text will be deleted.
-
- \sa setSelection() deselect()
-*/
-
-void QLineEdit::selectAll()
-{
- Q_D(QLineEdit);
- d->control->selectAll();
-}
-
-/*!
- Deselects any selected text.
-
- \sa setSelection() selectAll()
-*/
-
-void QLineEdit::deselect()
-{
- Q_D(QLineEdit);
- d->control->deselect();
-}
-
-
-/*!
- Deletes any selected text, inserts \a newText, and validates the
- result. If it is valid, it sets it as the new contents of the line
- edit.
-
- \sa setText(), clear()
-*/
-void QLineEdit::insert(const QString &newText)
-{
-// q->resetInputContext(); //#### FIX ME IN QT
- Q_D(QLineEdit);
- d->control->insert(newText);
-}
-
-/*!
- Clears the contents of the line edit.
-
- \sa setText(), insert()
-*/
-void QLineEdit::clear()
-{
- Q_D(QLineEdit);
- resetInputContext();
- d->control->clear();
-}
-
-/*!
- Undoes the last operation if undo is \link
- QLineEdit::undoAvailable available\endlink. Deselects any current
- selection, and updates the selection start to the current cursor
- position.
-*/
-void QLineEdit::undo()
-{
- Q_D(QLineEdit);
- resetInputContext();
- d->control->undo();
-}
-
-/*!
- Redoes the last operation if redo is \link
- QLineEdit::redoAvailable available\endlink.
-*/
-void QLineEdit::redo()
-{
- Q_D(QLineEdit);
- resetInputContext();
- d->control->redo();
-}
-
-
-/*!
- \property QLineEdit::readOnly
- \brief whether the line edit is read only.
-
- In read-only mode, the user can still copy the text to the
- clipboard, or drag and drop the text (if echoMode() is \l Normal),
- but cannot edit it.
-
- QLineEdit does not show a cursor in read-only mode.
-
- By default, this property is false.
-
- \sa setEnabled()
-*/
-
-bool QLineEdit::isReadOnly() const
-{
- Q_D(const QLineEdit);
- return d->control->isReadOnly();
-}
-
-void QLineEdit::setReadOnly(bool enable)
-{
- Q_D(QLineEdit);
- if (d->control->isReadOnly() != enable) {
- d->control->setReadOnly(enable);
- setAttribute(Qt::WA_MacShowFocusRect, !enable);
- setAttribute(Qt::WA_InputMethodEnabled, d->shouldEnableInputMethod());
-#ifndef QT_NO_CURSOR
- setCursor(enable ? Qt::ArrowCursor : Qt::IBeamCursor);
-#endif
- update();
- }
-}
-
-
-#ifndef QT_NO_CLIPBOARD
-/*!
- Copies the selected text to the clipboard and deletes it, if there
- is any, and if echoMode() is \l Normal.
-
- If the current validator disallows deleting the selected text,
- cut() will copy without deleting.
-
- \sa copy() paste() setValidator()
-*/
-
-void QLineEdit::cut()
-{
- if (hasSelectedText()) {
- copy();
- del();
- }
-}
-
-
-/*!
- Copies the selected text to the clipboard, if there is any, and if
- echoMode() is \l Normal.
-
- \sa cut() paste()
-*/
-
-void QLineEdit::copy() const
-{
- Q_D(const QLineEdit);
- d->control->copy();
-}
-
-/*!
- Inserts the clipboard's text at the cursor position, deleting any
- selected text, providing the line edit is not \link
- QLineEdit::readOnly read-only\endlink.
-
- If the end result would not be acceptable to the current
- \link setValidator() validator\endlink, nothing happens.
-
- \sa copy() cut()
-*/
-
-void QLineEdit::paste()
-{
- Q_D(QLineEdit);
- d->control->paste();
-}
-
-#endif // !QT_NO_CLIPBOARD
-
-/*! \reimp
-*/
-bool QLineEdit::event(QEvent * e)
-{
- Q_D(QLineEdit);
- if (e->type() == QEvent::Timer) {
- // should be timerEvent, is here for binary compatibility
- int timerId = ((QTimerEvent*)e)->timerId();
- if (false) {
-#ifndef QT_NO_DRAGANDDROP
- } else if (timerId == d->dndTimer.timerId()) {
- d->drag();
-#endif
- }
- else if (timerId == d->tripleClickTimer.timerId())
- d->tripleClickTimer.stop();
- } else if (e->type() == QEvent::ContextMenu) {
-#ifndef QT_NO_IM
- if (d->control->composeMode())
- return true;
-#endif
- //d->separate();
- } else if (e->type() == QEvent::WindowActivate) {
- QTimer::singleShot(0, this, SLOT(_q_handleWindowActivate()));
- }else if(e->type() == QEvent::ShortcutOverride){
- d->control->processEvent(e);
- } else if (e->type() == QEvent::KeyRelease) {
- d->control->setCursorBlinkPeriod(QApplication::cursorFlashTime());
- } else if (e->type() == QEvent::Show) {
- //In order to get the cursor blinking if QComboBox::setEditable is called when the combobox has focus
- if (hasFocus()) {
- d->control->setCursorBlinkPeriod(QApplication::cursorFlashTime());
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
- if ((!hasSelectedText() && d->control->preeditAreaText().isEmpty())
- || style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
- d->setCursorVisible(true);
- }
- }
-
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- if (e->type() == QEvent::EnterEditFocus) {
- end(false);
- d->setCursorVisible(true);
- d->control->setCursorBlinkPeriod(QApplication::cursorFlashTime());
- } else if (e->type() == QEvent::LeaveEditFocus) {
- d->setCursorVisible(false);
- d->control->setCursorBlinkPeriod(0);
- if (d->control->hasAcceptableInput() || d->control->fixup())
- emit editingFinished();
- }
- }
-#endif
- return QWidget::event(e);
-}
-
-/*! \reimp
-*/
-void QLineEdit::mousePressEvent(QMouseEvent* e)
-{
- Q_D(QLineEdit);
- if (d->sendMouseEventToInputContext(e))
- return;
- if (e->button() == Qt::RightButton)
- return;
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- setEditFocus(true);
- // Get the completion list to pop up.
- if (d->control->completer())
- d->control->completer()->complete();
- }
-#endif
- if (d->tripleClickTimer.isActive() && (e->pos() - d->tripleClick).manhattanLength() <
- QApplication::startDragDistance()) {
- selectAll();
- return;
- }
- bool mark = e->modifiers() & Qt::ShiftModifier;
- int cursor = d->xToPos(e->pos().x());
-#ifndef QT_NO_DRAGANDDROP
- if (!mark && d->dragEnabled && d->control->echoMode() == Normal &&
- e->button() == Qt::LeftButton && d->control->inSelection(e->pos().x())) {
- d->dndPos = e->pos();
- if (!d->dndTimer.isActive())
- d->dndTimer.start(QApplication::startDragTime(), this);
- } else
-#endif
- {
- d->control->moveCursor(cursor, mark);
- }
-}
-
-/*! \reimp
-*/
-void QLineEdit::mouseMoveEvent(QMouseEvent * e)
-{
- Q_D(QLineEdit);
- if (d->sendMouseEventToInputContext(e))
- return;
-
- if (e->buttons() & Qt::LeftButton) {
-#ifndef QT_NO_DRAGANDDROP
- if (d->dndTimer.isActive()) {
- if ((d->dndPos - e->pos()).manhattanLength() > QApplication::startDragDistance())
- d->drag();
- } else
-#endif
- {
- d->control->moveCursor(d->xToPos(e->pos().x()), true);
- }
- }
-}
-
-/*! \reimp
-*/
-void QLineEdit::mouseReleaseEvent(QMouseEvent* e)
-{
- Q_D(QLineEdit);
- if (d->sendMouseEventToInputContext(e))
- return;
-#ifndef QT_NO_DRAGANDDROP
- if (e->button() == Qt::LeftButton) {
- if (d->dndTimer.isActive()) {
- d->dndTimer.stop();
- deselect();
- return;
- }
- }
-#endif
-#ifndef QT_NO_CLIPBOARD
- if (QApplication::clipboard()->supportsSelection()) {
- if (e->button() == Qt::LeftButton) {
- d->control->copy(QClipboard::Selection);
- } else if (!d->control->isReadOnly() && e->button() == Qt::MidButton) {
- deselect();
- insert(QApplication::clipboard()->text(QClipboard::Selection));
- }
- }
-#endif
-
- if (!isReadOnly() && rect().contains(e->pos()))
- d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
- d->clickCausedFocus = 0;
-}
-
-/*! \reimp
-*/
-void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
-{
- Q_D(QLineEdit);
- if (d->sendMouseEventToInputContext(e))
- return;
- if (e->button() == Qt::LeftButton) {
- d->control->selectWordAtPos(d->xToPos(e->pos().x()));
- d->tripleClickTimer.start(QApplication::doubleClickInterval(), this);
- d->tripleClick = e->pos();
- }
-}
-
-/*!
- \fn void QLineEdit::returnPressed()
-
- This signal is emitted when the Return or Enter key is pressed.
- Note that if there is a validator() or inputMask() set on the line
- edit, the returnPressed() signal will only be emitted if the input
- follows the inputMask() and the validator() returns
- QValidator::Acceptable.
-*/
-
-/*!
- \fn void QLineEdit::editingFinished()
-
- This signal is emitted when the Return or Enter key is pressed or
- the line edit loses focus. Note that if there is a validator() or
- inputMask() set on the line edit and enter/return is pressed, the
- editingFinished() signal will only be emitted if the input follows
- the inputMask() and the validator() returns QValidator::Acceptable.
-*/
-
-/*!
- Converts the given key press \a event into a line edit action.
-
- If Return or Enter is pressed and the current text is valid (or
- can be \link QValidator::fixup() made valid\endlink by the
- validator), the signal returnPressed() is emitted.
-
- The default key bindings are listed in the class's detailed
- description.
-*/
-
-void QLineEdit::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QLineEdit);
- #ifdef QT_KEYPAD_NAVIGATION
- bool select = false;
- switch (event->key()) {
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- if (hasEditFocus()) {
- setEditFocus(false);
- if (d->control->completer() && d->control->completer()->popup()->isVisible())
- d->control->completer()->popup()->hide();
- select = true;
- }
- }
- break;
- case Qt::Key_Back:
- case Qt::Key_No:
- if (!QApplication::keypadNavigationEnabled() || !hasEditFocus()) {
- event->ignore();
- return;
- }
- break;
- default:
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus() && !(event->modifiers() & Qt::ControlModifier)) {
- if (!event->text().isEmpty() && event->text().at(0).isPrint()
- && !isReadOnly())
- setEditFocus(true);
- else {
- event->ignore();
- return;
- }
- }
- }
- }
-
-
-
- if (QApplication::keypadNavigationEnabled() && !select && !hasEditFocus()) {
- setEditFocus(true);
- if (event->key() == Qt::Key_Select)
- return; // Just start. No action.
- }
-#endif
- d->control->processKeyEvent(event);
- if (event->isAccepted()) {
- if (layoutDirection() != d->control->layoutDirection())
- setLayoutDirection(d->control->layoutDirection());
- d->control->setCursorBlinkPeriod(0);
- }
-}
-
-/*!
- \since 4.4
-
- Returns a rectangle that includes the lineedit cursor.
-*/
-QRect QLineEdit::cursorRect() const
-{
- Q_D(const QLineEdit);
- return d->cursorRect();
-}
-
-/*! \reimp
- */
-void QLineEdit::inputMethodEvent(QInputMethodEvent *e)
-{
- Q_D(QLineEdit);
- if (d->control->isReadOnly()) {
- e->ignore();
- return;
- }
-
- if (echoMode() == PasswordEchoOnEdit && !d->control->passwordEchoEditing()) {
- // Clear the edit and reset to normal echo mode while entering input
- // method data; the echo mode switches back when the edit loses focus.
- // ### changes a public property, resets current content.
- d->updatePasswordEchoEditing(true);
- clear();
- }
-
-#ifdef QT_KEYPAD_NAVIGATION
- // Focus in if currently in navigation focus on the widget
- // Only focus in on preedits, to allow input methods to
- // commit text as they focus out without interfering with focus
- if (QApplication::keypadNavigationEnabled()
- && hasFocus() && !hasEditFocus()
- && !e->preeditString().isEmpty())
- setEditFocus(true);
-#endif
-
- d->control->processInputMethodEvent(e);
-
-#ifndef QT_NO_COMPLETER
- if (!e->commitString().isEmpty())
- d->control->complete(Qt::Key_unknown);
-#endif
-}
-
-/*!\reimp
-*/
-QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property) const
-{
- Q_D(const QLineEdit);
- switch(property) {
- case Qt::ImMicroFocus:
- return d->cursorRect();
- case Qt::ImFont:
- return font();
- case Qt::ImCursorPosition:
- return QVariant(d->control->cursor());
- case Qt::ImSurroundingText:
- return QVariant(text());
- case Qt::ImCurrentSelection:
- return QVariant(selectedText());
- case Qt::ImMaximumTextLength:
- return QVariant(maxLength());
- case Qt::ImAnchorPosition:
- if (d->control->selectionStart() == d->control->selectionEnd())
- return QVariant(d->control->cursor());
- else if (d->control->selectionStart() == d->control->cursor())
- return QVariant(d->control->selectionEnd());
- else
- return QVariant(d->control->selectionStart());
- default:
- return QVariant();
- }
-}
-
-/*!\reimp
-*/
-
-void QLineEdit::focusInEvent(QFocusEvent *e)
-{
- Q_D(QLineEdit);
- if (e->reason() == Qt::TabFocusReason ||
- e->reason() == Qt::BacktabFocusReason ||
- e->reason() == Qt::ShortcutFocusReason) {
- if (!d->control->inputMask().isEmpty())
- d->control->moveCursor(d->control->nextMaskBlank(0));
- else if (!d->control->hasSelectedText())
- selectAll();
- } else if (e->reason() == Qt::MouseFocusReason) {
- d->clickCausedFocus = 1;
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || (hasEditFocus() && ( e->reason() == Qt::PopupFocusReason
-#ifdef Q_OS_SYMBIAN
- || e->reason() == Qt::ActiveWindowFocusReason
-#endif
- ))) {
-#endif
- d->control->setCursorBlinkPeriod(QApplication::cursorFlashTime());
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
- if((!hasSelectedText() && d->control->preeditAreaText().isEmpty())
- || style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
- d->setCursorVisible(true);
-#ifdef Q_WS_MAC
- if (d->control->echoMode() == Password || d->control->echoMode() == NoEcho)
- qt_mac_secure_keyboard(true);
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- d->control->setCancelText(d->control->text());
- }
-#endif
-#ifndef QT_NO_COMPLETER
- if (d->control->completer()) {
- d->control->completer()->setWidget(this);
- QObject::connect(d->control->completer(), SIGNAL(activated(QString)),
- this, SLOT(setText(QString)));
- QObject::connect(d->control->completer(), SIGNAL(highlighted(QString)),
- this, SLOT(_q_completionHighlighted(QString)));
- }
-#endif
- update();
-}
-
-/*!\reimp
-*/
-
-void QLineEdit::focusOutEvent(QFocusEvent *e)
-{
- Q_D(QLineEdit);
- if (d->control->passwordEchoEditing()) {
- // Reset the echomode back to PasswordEchoOnEdit when the widget loses
- // focus.
- d->updatePasswordEchoEditing(false);
- }
-
- Qt::FocusReason reason = e->reason();
- if (reason != Qt::ActiveWindowFocusReason &&
- reason != Qt::PopupFocusReason)
- deselect();
-
- d->setCursorVisible(false);
- d->control->setCursorBlinkPeriod(0);
-#ifdef QT_KEYPAD_NAVIGATION
- // editingFinished() is already emitted on LeaveEditFocus
- if (!QApplication::keypadNavigationEnabled())
-#endif
- if (reason != Qt::PopupFocusReason
- || !(QApplication::activePopupWidget() && QApplication::activePopupWidget()->parentWidget() == this)) {
- if (hasAcceptableInput() || d->control->fixup())
- emit editingFinished();
-#ifdef QT3_SUPPORT
- emit lostFocus();
-#endif
- }
-#ifdef Q_WS_MAC
- if (d->control->echoMode() == Password || d->control->echoMode() == NoEcho)
- qt_mac_secure_keyboard(false);
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- d->control->setCancelText(QString());
-#endif
-#ifndef QT_NO_COMPLETER
- if (d->control->completer()) {
- QObject::disconnect(d->control->completer(), 0, this, 0);
- }
-#endif
- update();
-}
-
-/*!\reimp
-*/
-void QLineEdit::paintEvent(QPaintEvent *)
-{
- Q_D(QLineEdit);
- QPainter p(this);
-
- QRect r = rect();
- QPalette pal = palette();
-
- QStyleOptionFrameV2 panel;
- initStyleOption(&panel);
- style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panel, &p, this);
- r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
- r.setX(r.x() + d->leftTextMargin);
- r.setY(r.y() + d->topTextMargin);
- r.setRight(r.right() - d->rightTextMargin);
- r.setBottom(r.bottom() - d->bottomTextMargin);
- p.setClipRect(r);
-
- QFontMetrics fm = fontMetrics();
- Qt::Alignment va = QStyle::visualAlignment(d->control->layoutDirection(), QFlag(d->alignment));
- switch (va & Qt::AlignVertical_Mask) {
- case Qt::AlignBottom:
- d->vscroll = r.y() + r.height() - fm.height() - d->verticalMargin;
- break;
- case Qt::AlignTop:
- d->vscroll = r.y() + d->verticalMargin;
- break;
- default:
- //center
- d->vscroll = r.y() + (r.height() - fm.height() + 1) / 2;
- break;
- }
- QRect lineRect(r.x() + d->horizontalMargin, d->vscroll, r.width() - 2*d->horizontalMargin, fm.height());
-
- int minLB = qMax(0, -fm.minLeftBearing());
- int minRB = qMax(0, -fm.minRightBearing());
-
- if (d->control->text().isEmpty()) {
- if (!hasFocus() && !d->placeholderText.isEmpty()) {
- QColor col = pal.text().color();
- col.setAlpha(128);
- QPen oldpen = p.pen();
- p.setPen(col);
- lineRect.adjust(minLB, 0, 0, 0);
- QString elidedText = fm.elidedText(d->placeholderText, Qt::ElideRight, lineRect.width());
- p.drawText(lineRect, va, elidedText);
- p.setPen(oldpen);
- return;
- }
- }
-
- int cix = qRound(d->control->cursorToX());
-
- // horizontal scrolling. d->hscroll is the left indent from the beginning
- // of the text line to the left edge of lineRect. we update this value
- // depending on the delta from the last paint event; in effect this means
- // the below code handles all scrolling based on the textline (widthUsed,
- // minLB, minRB), the line edit rect (lineRect) and the cursor position
- // (cix).
- int widthUsed = qRound(d->control->naturalTextWidth()) + 1 + minRB;
- if ((minLB + widthUsed) <= lineRect.width()) {
- // text fits in lineRect; use hscroll for alignment
- switch (va & ~(Qt::AlignAbsolute|Qt::AlignVertical_Mask)) {
- case Qt::AlignRight:
- d->hscroll = widthUsed - lineRect.width() + 1;
- break;
- case Qt::AlignHCenter:
- d->hscroll = (widthUsed - lineRect.width()) / 2;
- break;
- default:
- // Left
- d->hscroll = 0;
- break;
- }
- d->hscroll -= minLB;
- } else if (cix - d->hscroll >= lineRect.width()) {
- // text doesn't fit, cursor is to the right of lineRect (scroll right)
- d->hscroll = cix - lineRect.width() + 1;
- } else if (cix - d->hscroll < 0 && d->hscroll < widthUsed) {
- // text doesn't fit, cursor is to the left of lineRect (scroll left)
- d->hscroll = cix;
- } else if (widthUsed - d->hscroll < lineRect.width()) {
- // text doesn't fit, text document is to the left of lineRect; align
- // right
- d->hscroll = widthUsed - lineRect.width() + 1;
- } else {
- //in case the text is bigger than the lineedit, the hscroll can never be negative
- d->hscroll = qMax(0, d->hscroll);
- }
-
- // the y offset is there to keep the baseline constant in case we have script changes in the text.
- QPoint topLeft = lineRect.topLeft() - QPoint(d->hscroll, d->control->ascent() - fm.ascent());
-
- // draw text, selections and cursors
-#ifndef QT_NO_STYLE_STYLESHEET
- if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style())) {
- cssStyle->styleSheetPalette(this, &panel, &pal);
- }
-#endif
- p.setPen(pal.text().color());
-
- int flags = QLineControl::DrawText;
-
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || hasEditFocus())
-#endif
- if (d->control->hasSelectedText() || (d->cursorVisible && !d->control->inputMask().isEmpty() && !d->control->isReadOnly())){
- flags |= QLineControl::DrawSelections;
- // Palette only used for selections/mask and may not be in sync
- if (d->control->palette() != pal
- || d->control->palette().currentColorGroup() != pal.currentColorGroup())
- d->control->setPalette(pal);
- }
-
- // Asian users see an IM selection text as cursor on candidate
- // selection phase of input method, so the ordinary cursor should be
- // invisible if we have a preedit string.
- if (d->cursorVisible && !d->control->isReadOnly())
- flags |= QLineControl::DrawCursor;
-
- d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth));
- d->control->draw(&p, topLeft, r, flags);
-
-}
-
-
-#ifndef QT_NO_DRAGANDDROP
-/*!\reimp
-*/
-void QLineEdit::dragMoveEvent(QDragMoveEvent *e)
-{
- Q_D(QLineEdit);
- if (!d->control->isReadOnly() && e->mimeData()->hasFormat(QLatin1String("text/plain"))) {
- e->acceptProposedAction();
- d->control->moveCursor(d->xToPos(e->pos().x()), false);
- d->cursorVisible = true;
- update();
- }
-}
-
-/*!\reimp */
-void QLineEdit::dragEnterEvent(QDragEnterEvent * e)
-{
- QLineEdit::dragMoveEvent(e);
-}
-
-/*!\reimp */
-void QLineEdit::dragLeaveEvent(QDragLeaveEvent *)
-{
- Q_D(QLineEdit);
- if (d->cursorVisible) {
- d->cursorVisible = false;
- update();
- }
-}
-
-/*!\reimp */
-void QLineEdit::dropEvent(QDropEvent* e)
-{
- Q_D(QLineEdit);
- QString str = e->mimeData()->text();
-
- if (!str.isNull() && !d->control->isReadOnly()) {
- if (e->source() == this && e->dropAction() == Qt::CopyAction)
- deselect();
- int cursorPos = d->xToPos(e->pos().x());
- int selStart = cursorPos;
- int oldSelStart = d->control->selectionStart();
- int oldSelEnd = d->control->selectionEnd();
- d->control->moveCursor(cursorPos, false);
- d->cursorVisible = false;
- e->acceptProposedAction();
- insert(str);
- if (e->source() == this) {
- if (e->dropAction() == Qt::MoveAction) {
- if (selStart > oldSelStart && selStart <= oldSelEnd)
- setSelection(oldSelStart, str.length());
- else if (selStart > oldSelEnd)
- setSelection(selStart - str.length(), str.length());
- else
- setSelection(selStart, str.length());
- } else {
- setSelection(selStart, str.length());
- }
- }
- } else {
- e->ignore();
- update();
- }
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- Shows the standard context menu created with
- createStandardContextMenu().
-
- If you do not want the line edit to have a context menu, you can set
- its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
- customize the context menu, reimplement this function. If you want
- to extend the standard context menu, reimplement this function, call
- createStandardContextMenu() and extend the menu returned.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qlineedit.cpp 0
-
- The \a event parameter is used to obtain the position where
- the mouse cursor was when the event was generated.
-
- \sa setContextMenuPolicy()
-*/
-void QLineEdit::contextMenuEvent(QContextMenuEvent *event)
-{
- if (QMenu *menu = createStandardContextMenu()) {
- menu->setAttribute(Qt::WA_DeleteOnClose);
- menu->popup(event->globalPos());
- }
-}
-
-#if defined(Q_WS_WIN) || defined(Q_WS_X11)
- extern bool qt_use_rtl_extensions;
-#endif
-
-/*! This function creates the standard context menu which is shown
- when the user clicks on the line edit with the right mouse
- button. It is called from the default contextMenuEvent() handler.
- The popup menu's ownership is transferred to the caller.
-*/
-
-QMenu *QLineEdit::createStandardContextMenu()
-{
- Q_D(QLineEdit);
- QMenu *popup = new QMenu(this);
- popup->setObjectName(QLatin1String("qt_edit_menu"));
- QAction *action = 0;
-
- if (!isReadOnly()) {
- action = popup->addAction(QLineEdit::tr("&Undo") + ACCEL_KEY(QKeySequence::Undo));
- action->setEnabled(d->control->isUndoAvailable());
- connect(action, SIGNAL(triggered()), SLOT(undo()));
-
- action = popup->addAction(QLineEdit::tr("&Redo") + ACCEL_KEY(QKeySequence::Redo));
- action->setEnabled(d->control->isRedoAvailable());
- connect(action, SIGNAL(triggered()), SLOT(redo()));
-
- popup->addSeparator();
- }
-
-#ifndef QT_NO_CLIPBOARD
- if (!isReadOnly()) {
- action = popup->addAction(QLineEdit::tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut));
- action->setEnabled(!d->control->isReadOnly() && d->control->hasSelectedText()
- && d->control->echoMode() == QLineEdit::Normal);
- connect(action, SIGNAL(triggered()), SLOT(cut()));
- }
-
- action = popup->addAction(QLineEdit::tr("&Copy") + ACCEL_KEY(QKeySequence::Copy));
- action->setEnabled(d->control->hasSelectedText()
- && d->control->echoMode() == QLineEdit::Normal);
- connect(action, SIGNAL(triggered()), SLOT(copy()));
-
- if (!isReadOnly()) {
- action = popup->addAction(QLineEdit::tr("&Paste") + ACCEL_KEY(QKeySequence::Paste));
- action->setEnabled(!d->control->isReadOnly() && !QApplication::clipboard()->text().isEmpty());
- connect(action, SIGNAL(triggered()), SLOT(paste()));
- }
-#endif
-
- if (!isReadOnly()) {
- action = popup->addAction(QLineEdit::tr("Delete"));
- action->setEnabled(!d->control->isReadOnly() && !d->control->text().isEmpty() && d->control->hasSelectedText());
- connect(action, SIGNAL(triggered()), d->control, SLOT(_q_deleteSelected()));
- }
-
- if (!popup->isEmpty())
- popup->addSeparator();
-
- action = popup->addAction(QLineEdit::tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll));
- action->setEnabled(!d->control->text().isEmpty() && !d->control->allSelected());
- d->selectAllAction = action;
- connect(action, SIGNAL(triggered()), SLOT(selectAll()));
-
-#if !defined(QT_NO_IM)
- QInputContext *qic = inputContext();
- if (qic) {
- QList<QAction *> imActions = qic->actions();
- for (int i = 0; i < imActions.size(); ++i)
- popup->addAction(imActions.at(i));
- }
-#endif
-
-#if defined(Q_WS_WIN) || defined(Q_WS_X11)
- if (!d->control->isReadOnly() && qt_use_rtl_extensions) {
-#else
- if (!d->control->isReadOnly()) {
-#endif
- popup->addSeparator();
- QUnicodeControlCharacterMenu *ctrlCharacterMenu = new QUnicodeControlCharacterMenu(this, popup);
- popup->addMenu(ctrlCharacterMenu);
- }
- return popup;
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*! \reimp */
-void QLineEdit::changeEvent(QEvent *ev)
-{
- Q_D(QLineEdit);
- switch(ev->type())
- {
- case QEvent::ActivationChange:
- if (!palette().isEqual(QPalette::Active, QPalette::Inactive))
- update();
- break;
- case QEvent::FontChange:
- d->control->setFont(font());
- break;
- case QEvent::StyleChange:
- {
- QStyleOptionFrameV2 opt;
- initStyleOption(&opt);
- d->control->setPasswordCharacter(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, this));
- }
- update();
- break;
- default:
- break;
- }
- QWidget::changeEvent(ev);
-}
-
-/*!
- \fn void QLineEdit::repaintArea(int a, int b)
-
- Use update() instead.
-*/
-
-/*!
- \fn void QLineEdit::cursorLeft(bool mark, int steps)
-
- Use cursorForward() with a negative number of steps instead. For
- example, cursorForward(mark, -steps).
-*/
-
-/*!
- \fn void QLineEdit::cursorRight(bool mark, int steps)
-
- Use cursorForward() instead.
-*/
-
-/*!
- \fn bool QLineEdit::frame() const
-
- Use hasFrame() instead.
-*/
-
-/*!
- \fn void QLineEdit::clearValidator()
-
- Use setValidator(0) instead.
-*/
-
-/*!
- \fn bool QLineEdit::hasMarkedText() const
-
- Use hasSelectedText() instead.
-*/
-
-/*!
- \fn QString QLineEdit::markedText() const
-
- Use selectedText() instead.
-*/
-
-/*!
- \fn void QLineEdit::setFrameRect(QRect)
- \internal
-*/
-
-/*!
- \fn QRect QLineEdit::frameRect() const
- \internal
-*/
-/*!
- \enum QLineEdit::DummyFrame
- \internal
-
- \value Box
- \value Sunken
- \value Plain
- \value Raised
- \value MShadow
- \value NoFrame
- \value Panel
- \value StyledPanel
- \value HLine
- \value VLine
- \value GroupBoxPanel
- \value WinPanel
- \value ToolBarPanel
- \value MenuBarPanel
- \value PopupPanel
- \value LineEditPanel
- \value TabWidgetPanel
- \value MShape
-*/
-
-/*!
- \fn void QLineEdit::setFrameShadow(DummyFrame)
- \internal
-*/
-
-/*!
- \fn DummyFrame QLineEdit::frameShadow() const
- \internal
-*/
-
-/*!
- \fn void QLineEdit::setFrameShape(DummyFrame)
- \internal
-*/
-
-/*!
- \fn DummyFrame QLineEdit::frameShape() const
- \internal
-*/
-
-/*!
- \fn void QLineEdit::setFrameStyle(int)
- \internal
-*/
-
-/*!
- \fn int QLineEdit::frameStyle() const
- \internal
-*/
-
-/*!
- \fn int QLineEdit::frameWidth() const
- \internal
-*/
-
-/*!
- \fn void QLineEdit::setLineWidth(int)
- \internal
-*/
-
-/*!
- \fn int QLineEdit::lineWidth() const
- \internal
-*/
-
-/*!
- \fn void QLineEdit::setMargin(int margin)
- Sets the width of the margin around the contents of the widget to \a margin.
-
- Use QWidget::setContentsMargins() instead.
- \sa margin(), QWidget::setContentsMargins()
-*/
-
-/*!
- \fn int QLineEdit::margin() const
- Returns the width of the margin around the contents of the widget.
-
- Use QWidget::getContentsMargins() instead.
- \sa setMargin(), QWidget::getContentsMargins()
-*/
-
-/*!
- \fn void QLineEdit::setMidLineWidth(int)
- \internal
-*/
-
-/*!
- \fn int QLineEdit::midLineWidth() const
- \internal
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qlineedit.cpp"
-
-#endif // QT_NO_LINEEDIT
diff --git a/src/gui/widgets/qlineedit.h b/src/gui/widgets/qlineedit.h
deleted file mode 100644
index 73a736c690..0000000000
--- a/src/gui/widgets/qlineedit.h
+++ /dev/null
@@ -1,299 +0,0 @@
-/****************************************************************************
-**
-** 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 QLINEEDIT_H
-#define QLINEEDIT_H
-
-#include <QtGui/qframe.h>
-#include <QtGui/qtextcursor.h>
-#include <QtCore/qstring.h>
-#include <QtCore/qmargins.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_LINEEDIT
-
-class QValidator;
-class QMenu;
-class QLineEditPrivate;
-class QCompleter;
-class QStyleOptionFrame;
-class QAbstractSpinBox;
-class QDateTimeEdit;
-
-class Q_GUI_EXPORT QLineEdit : public QWidget
-{
- Q_OBJECT
-
- Q_ENUMS(EchoMode)
- Q_PROPERTY(QString inputMask READ inputMask WRITE setInputMask)
- Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged USER true)
- Q_PROPERTY(int maxLength READ maxLength WRITE setMaxLength)
- Q_PROPERTY(bool frame READ hasFrame WRITE setFrame)
- Q_PROPERTY(EchoMode echoMode READ echoMode WRITE setEchoMode)
- Q_PROPERTY(QString displayText READ displayText)
- Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
- Q_PROPERTY(bool modified READ isModified WRITE setModified DESIGNABLE false)
- Q_PROPERTY(bool hasSelectedText READ hasSelectedText)
- Q_PROPERTY(QString selectedText READ selectedText)
- Q_PROPERTY(bool dragEnabled READ dragEnabled WRITE setDragEnabled)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(bool undoAvailable READ isUndoAvailable)
- Q_PROPERTY(bool redoAvailable READ isRedoAvailable)
- Q_PROPERTY(bool acceptableInput READ hasAcceptableInput)
- Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText)
-
-public:
- explicit QLineEdit(QWidget* parent=0);
- explicit QLineEdit(const QString &, QWidget* parent=0);
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QLineEdit(QWidget* parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QLineEdit(const QString &, QWidget* parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QLineEdit(const QString &, const QString &, QWidget* parent=0, const char* name=0);
-#endif
- ~QLineEdit();
-
- QString text() const;
-
- QString displayText() const;
-
- QString placeholderText() const;
- void setPlaceholderText(const QString &);
-
- int maxLength() const;
- void setMaxLength(int);
-
- void setFrame(bool);
- bool hasFrame() const;
-
- enum EchoMode { Normal, NoEcho, Password, PasswordEchoOnEdit };
- EchoMode echoMode() const;
- void setEchoMode(EchoMode);
-
- bool isReadOnly() const;
- void setReadOnly(bool);
-
-#ifndef QT_NO_VALIDATOR
- void setValidator(const QValidator *);
- const QValidator * validator() const;
-#endif
-
-#ifndef QT_NO_COMPLETER
- void setCompleter(QCompleter *completer);
- QCompleter *completer() const;
-#endif
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- int cursorPosition() const;
- void setCursorPosition(int);
- int cursorPositionAt(const QPoint &pos);
-
- void setAlignment(Qt::Alignment flag);
- Qt::Alignment alignment() const;
-
- void cursorForward(bool mark, int steps = 1);
- void cursorBackward(bool mark, int steps = 1);
- void cursorWordForward(bool mark);
- void cursorWordBackward(bool mark);
- void backspace();
- void del();
- void home(bool mark);
- void end(bool mark);
-
- bool isModified() const;
- void setModified(bool);
-
- void setSelection(int, int);
- bool hasSelectedText() const;
- QString selectedText() const;
- int selectionStart() const;
-
- bool isUndoAvailable() const;
- bool isRedoAvailable() const;
-
- void setDragEnabled(bool b);
- bool dragEnabled() const;
-
- void setCursorMoveStyle(QTextCursor::MoveStyle style);
- QTextCursor::MoveStyle cursorMoveStyle() const;
-
- QString inputMask() const;
- void setInputMask(const QString &inputMask);
- bool hasAcceptableInput() const;
-
- void setTextMargins(int left, int top, int right, int bottom);
- void setTextMargins(const QMargins &margins);
- void getTextMargins(int *left, int *top, int *right, int *bottom) const;
- QMargins textMargins() const;
-
-public Q_SLOTS:
- void setText(const QString &);
- void clear();
- void selectAll();
- void undo();
- void redo();
-#ifndef QT_NO_CLIPBOARD
- void cut();
- void copy() const;
- void paste();
-#endif
-
-public:
- void deselect();
- void insert(const QString &);
-#ifndef QT_NO_CONTEXTMENU
- QMenu *createStandardContextMenu();
-#endif
-
-Q_SIGNALS:
- void textChanged(const QString &);
- void textEdited(const QString &);
- void cursorPositionChanged(int, int);
- void returnPressed();
- void editingFinished();
- void selectionChanged();
-
-protected:
- void mousePressEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void mouseDoubleClickEvent(QMouseEvent *);
- void keyPressEvent(QKeyEvent *);
- void focusInEvent(QFocusEvent *);
- void focusOutEvent(QFocusEvent *);
- void paintEvent(QPaintEvent *);
-#ifndef QT_NO_DRAGANDDROP
- void dragEnterEvent(QDragEnterEvent *);
- void dragMoveEvent(QDragMoveEvent *e);
- void dragLeaveEvent(QDragLeaveEvent *e);
- void dropEvent(QDropEvent *);
-#endif
- void changeEvent(QEvent *);
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *);
-#endif
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT void repaintArea(int, int) { update(); }
-#endif
-
- void inputMethodEvent(QInputMethodEvent *);
- void initStyleOption(QStyleOptionFrame *option) const;
-public:
- QVariant inputMethodQuery(Qt::InputMethodQuery) const;
- bool event(QEvent *);
-protected:
- QRect cursorRect() const;
-
-public:
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT void clearModified() { setModified(false); }
- inline QT3_SUPPORT void cursorLeft(bool mark, int steps = 1) { cursorForward(mark, -steps); }
- inline QT3_SUPPORT void cursorRight(bool mark, int steps = 1) { cursorForward(mark, steps); }
- QT3_SUPPORT bool validateAndSet(const QString &, int, int, int);
- inline QT3_SUPPORT bool frame() const { return hasFrame(); }
-#ifndef QT_NO_VALIDATOR
- inline QT3_SUPPORT void clearValidator() { setValidator(0); }
-#endif
- inline QT3_SUPPORT bool hasMarkedText() const { return hasSelectedText(); }
- inline QT3_SUPPORT QString markedText() const { return selectedText(); }
- QT3_SUPPORT bool edited() const;
- QT3_SUPPORT void setEdited(bool);
- QT3_SUPPORT int characterAt(int, QChar*) const;
- QT3_SUPPORT bool getSelection(int *, int *);
-
- QT3_SUPPORT void setFrameRect(QRect) {}
- QT3_SUPPORT QRect frameRect() const { return QRect(); }
- enum DummyFrame { Box, Sunken, Plain, Raised, MShadow, NoFrame, Panel, StyledPanel,
- HLine, VLine, GroupBoxPanel, WinPanel, ToolBarPanel, MenuBarPanel,
- PopupPanel, LineEditPanel, TabWidgetPanel, MShape };
- QT3_SUPPORT void setFrameShadow(DummyFrame) {}
- QT3_SUPPORT DummyFrame frameShadow() const { return Plain; }
- QT3_SUPPORT void setFrameShape(DummyFrame) {}
- QT3_SUPPORT DummyFrame frameShape() const { return NoFrame; }
- QT3_SUPPORT void setFrameStyle(int) {}
- QT3_SUPPORT int frameStyle() const { return 0; }
- QT3_SUPPORT int frameWidth() const { return 0; }
- QT3_SUPPORT void setLineWidth(int) {}
- QT3_SUPPORT int lineWidth() const { return 0; }
- QT3_SUPPORT void setMargin(int margin) { setContentsMargins(margin, margin, margin, margin); }
- QT3_SUPPORT int margin() const
- { int margin; int dummy; getContentsMargins(&margin, &dummy, &dummy, &dummy); return margin; }
- QT3_SUPPORT void setMidLineWidth(int) {}
- QT3_SUPPORT int midLineWidth() const { return 0; }
-
-Q_SIGNALS:
- QT_MOC_COMPAT void lostFocus();
-#endif
-
-private:
- friend class QAbstractSpinBox;
-#ifdef QT_KEYPAD_NAVIGATION
- friend class QDateTimeEdit;
-#endif
- Q_DISABLE_COPY(QLineEdit)
- Q_DECLARE_PRIVATE(QLineEdit)
- Q_PRIVATE_SLOT(d_func(), void _q_handleWindowActivate())
- Q_PRIVATE_SLOT(d_func(), void _q_textEdited(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged(int, int))
-#ifndef QT_NO_COMPLETER
- Q_PRIVATE_SLOT(d_func(), void _q_completionHighlighted(QString))
-#endif
-#ifdef QT_KEYPAD_NAVIGATION
- Q_PRIVATE_SLOT(d_func(), void _q_editFocusChange(bool))
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged())
- Q_PRIVATE_SLOT(d_func(), void _q_updateNeeded(const QRect &))
-};
-
-#endif // QT_NO_LINEEDIT
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLINEEDIT_H
diff --git a/src/gui/widgets/qlineedit_p.cpp b/src/gui/widgets/qlineedit_p.cpp
deleted file mode 100644
index 816689019d..0000000000
--- a/src/gui/widgets/qlineedit_p.cpp
+++ /dev/null
@@ -1,292 +0,0 @@
-/****************************************************************************
-**
-** 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 "qlineedit.h"
-#include "qlineedit_p.h"
-
-#ifndef QT_NO_LINEEDIT
-
-#include "qabstractitemview.h"
-#include "qdrag.h"
-#include "qclipboard.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#ifndef QT_NO_IM
-#include "qinputcontext.h"
-#include "qlist.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-const int QLineEditPrivate::verticalMargin(1);
-const int QLineEditPrivate::horizontalMargin(2);
-
-QRect QLineEditPrivate::adjustedControlRect(const QRect &rect) const
-{
- QRect cr = adjustedContentsRect();
- int cix = cr.x() - hscroll + horizontalMargin;
- return rect.translated(QPoint(cix, vscroll));
-}
-
-int QLineEditPrivate::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const
-{
- QRect cr = adjustedContentsRect();
- x-= cr.x() - hscroll + horizontalMargin;
- return control->xToPos(x, betweenOrOn);
-}
-
-QRect QLineEditPrivate::cursorRect() const
-{
- return adjustedControlRect(control->cursorRect());
-}
-
-#ifndef QT_NO_COMPLETER
-
-void QLineEditPrivate::_q_completionHighlighted(QString newText)
-{
- Q_Q(QLineEdit);
- if (control->completer()->completionMode() != QCompleter::InlineCompletion) {
- q->setText(newText);
- } else {
- int c = control->cursor();
- QString text = control->text();
- q->setText(text.left(c) + newText.mid(c));
- control->moveCursor(control->end(), false);
- control->moveCursor(c, true);
- }
-}
-
-#endif // QT_NO_COMPLETER
-
-void QLineEditPrivate::_q_handleWindowActivate()
-{
- Q_Q(QLineEdit);
- if (!q->hasFocus() && control->hasSelectedText())
- control->deselect();
-}
-
-void QLineEditPrivate::_q_textEdited(const QString &text)
-{
- Q_Q(QLineEdit);
- emit q->textEdited(text);
-#ifndef QT_NO_COMPLETER
- if (control->completer()
- && control->completer()->completionMode() != QCompleter::InlineCompletion)
- control->complete(-1); // update the popup on cut/paste/del
-#endif
-}
-
-void QLineEditPrivate::_q_cursorPositionChanged(int from, int to)
-{
- Q_Q(QLineEdit);
- q->update();
- emit q->cursorPositionChanged(from, to);
-}
-
-#ifdef QT_KEYPAD_NAVIGATION
-void QLineEditPrivate::_q_editFocusChange(bool e)
-{
- Q_Q(QLineEdit);
- q->setEditFocus(e);
-}
-#endif
-
-void QLineEditPrivate::_q_selectionChanged()
-{
- Q_Q(QLineEdit);
- if (!control->text().isEmpty() && control->preeditAreaText().isEmpty()) {
- QStyleOptionFrameV2 opt;
- q->initStyleOption(&opt);
- bool showCursor = control->hasSelectedText() ?
- q->style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, q):
- q->hasFocus();
- setCursorVisible(showCursor);
- }
-
- emit q->selectionChanged();
-}
-
-void QLineEditPrivate::_q_updateNeeded(const QRect &rect)
-{
- q_func()->update(adjustedControlRect(rect));
-}
-
-void QLineEditPrivate::init(const QString& txt)
-{
- Q_Q(QLineEdit);
- control = new QLineControl(txt);
- control->setFont(q->font());
- QObject::connect(control, SIGNAL(textChanged(QString)),
- q, SIGNAL(textChanged(QString)));
- QObject::connect(control, SIGNAL(textEdited(QString)),
- q, SLOT(_q_textEdited(QString)));
- QObject::connect(control, SIGNAL(cursorPositionChanged(int,int)),
- q, SLOT(_q_cursorPositionChanged(int,int)));
- QObject::connect(control, SIGNAL(selectionChanged()),
- q, SLOT(_q_selectionChanged()));
- QObject::connect(control, SIGNAL(accepted()),
- q, SIGNAL(returnPressed()));
- QObject::connect(control, SIGNAL(editingFinished()),
- q, SIGNAL(editingFinished()));
-#ifdef QT_KEYPAD_NAVIGATION
- QObject::connect(control, SIGNAL(editFocusChange(bool)),
- q, SLOT(_q_editFocusChange(bool)));
-#endif
- QObject::connect(control, SIGNAL(cursorPositionChanged(int,int)),
- q, SLOT(updateMicroFocus()));
-
- QObject::connect(control, SIGNAL(textChanged(const QString &)),
- q, SLOT(updateMicroFocus()));
-
- // for now, going completely overboard with updates.
- QObject::connect(control, SIGNAL(selectionChanged()),
- q, SLOT(update()));
-
- QObject::connect(control, SIGNAL(displayTextChanged(QString)),
- q, SLOT(update()));
-
- QObject::connect(control, SIGNAL(updateNeeded(QRect)),
- q, SLOT(_q_updateNeeded(QRect)));
-
- QStyleOptionFrameV2 opt;
- q->initStyleOption(&opt);
- control->setPasswordCharacter(q->style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, q));
-#ifndef QT_NO_CURSOR
- q->setCursor(Qt::IBeamCursor);
-#endif
- q->setFocusPolicy(Qt::StrongFocus);
- q->setAttribute(Qt::WA_InputMethodEnabled);
- // Specifies that this widget can use more, but is able to survive on
- // less, horizontal space; and is fixed vertically.
- q->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, QSizePolicy::LineEdit));
- q->setBackgroundRole(QPalette::Base);
- q->setAttribute(Qt::WA_KeyCompression);
- q->setMouseTracking(true);
- q->setAcceptDrops(true);
-
- q->setAttribute(Qt::WA_MacShowFocusRect);
-}
-
-QRect QLineEditPrivate::adjustedContentsRect() const
-{
- Q_Q(const QLineEdit);
- QStyleOptionFrameV2 opt;
- q->initStyleOption(&opt);
- QRect r = q->style()->subElementRect(QStyle::SE_LineEditContents, &opt, q);
- r.setX(r.x() + leftTextMargin);
- r.setY(r.y() + topTextMargin);
- r.setRight(r.right() - rightTextMargin);
- r.setBottom(r.bottom() - bottomTextMargin);
- return r;
-}
-
-void QLineEditPrivate::setCursorVisible(bool visible)
-{
- Q_Q(QLineEdit);
- if ((bool)cursorVisible == visible)
- return;
- cursorVisible = visible;
- if (control->inputMask().isEmpty())
- q->update(cursorRect());
- else
- q->update();
-}
-
-void QLineEditPrivate::updatePasswordEchoEditing(bool editing)
-{
- Q_Q(QLineEdit);
- control->updatePasswordEchoEditing(editing);
- q->setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod());
-}
-
-/*!
- This function is not intended as polymorphic usage. Just a shared code
- fragment that calls QInputContext::mouseHandler for this
- class.
-*/
-bool QLineEditPrivate::sendMouseEventToInputContext( QMouseEvent *e )
-{
-#if !defined QT_NO_IM
- Q_Q(QLineEdit);
- if ( control->composeMode() ) {
- int tmp_cursor = xToPos(e->pos().x());
- int mousePos = tmp_cursor - control->cursor();
- if ( mousePos < 0 || mousePos > control->preeditAreaText().length() ) {
- mousePos = -1;
- // don't send move events outside the preedit area
- if ( e->type() == QEvent::MouseMove )
- return true;
- }
-
- QInputContext *qic = q->inputContext();
- if ( qic )
- // may be causing reset() in some input methods
- qic->mouseHandler(mousePos, e);
- if (!control->preeditAreaText().isEmpty())
- return true;
- }
-#else
- Q_UNUSED(e);
-#endif
-
- return false;
-}
-
-#ifndef QT_NO_DRAGANDDROP
-void QLineEditPrivate::drag()
-{
- Q_Q(QLineEdit);
- dndTimer.stop();
- QMimeData *data = new QMimeData;
- data->setText(control->selectedText());
- QDrag *drag = new QDrag(q);
- drag->setMimeData(data);
- Qt::DropAction action = drag->start();
- if (action == Qt::MoveAction && !control->isReadOnly() && drag->target() != q)
- control->removeSelection();
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qlineedit_p.h b/src/gui/widgets/qlineedit_p.h
deleted file mode 100644
index 32f6077438..0000000000
--- a/src/gui/widgets/qlineedit_p.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/****************************************************************************
-**
-** 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 QLINEEDIT_P_H
-#define QLINEEDIT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qglobal.h"
-
-#ifndef QT_NO_LINEEDIT
-#include "private/qwidget_p.h"
-#include "QtGui/qlineedit.h"
-#include "QtGui/qtextlayout.h"
-#include "QtGui/qstyleoption.h"
-#include "QtCore/qbasictimer.h"
-#include "QtGui/qcompleter.h"
-#include "QtCore/qpointer.h"
-#include "QtGui/qlineedit.h"
-
-#include "private/qlinecontrol_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QLineEditPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QLineEdit)
-public:
-
- QLineEditPrivate()
- : control(0), frame(1), contextMenuEnabled(1), cursorVisible(0),
- dragEnabled(0), clickCausedFocus(0), hscroll(0), vscroll(0),
- alignment(Qt::AlignLeading | Qt::AlignVCenter),
- leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0)
- {
- }
-
- ~QLineEditPrivate()
- {
- delete control;
- }
-
- QLineControl *control;
-
-#ifndef QT_NO_CONTEXTMENU
- QPointer<QAction> selectAllAction;
-#endif
- void init(const QString&);
-
- QRect adjustedControlRect(const QRect &) const;
-
- int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const;
- QRect cursorRect() const;
- void setCursorVisible(bool visible);
-
- void updatePasswordEchoEditing(bool);
-
- inline bool shouldEnableInputMethod() const
- {
- return !control->isReadOnly();
- }
-
- QPoint tripleClick;
- QBasicTimer tripleClickTimer;
- uint frame : 1;
- uint contextMenuEnabled : 1;
- uint cursorVisible : 1;
- uint dragEnabled : 1;
- uint clickCausedFocus : 1;
- int hscroll;
- int vscroll;
- uint alignment;
- static const int verticalMargin;
- static const int horizontalMargin;
-
- bool sendMouseEventToInputContext(QMouseEvent *e);
-
- QRect adjustedContentsRect() const;
-
- void _q_handleWindowActivate();
- void _q_textEdited(const QString &);
- void _q_cursorPositionChanged(int, int);
-#ifdef QT_KEYPAD_NAVIGATION
- void _q_editFocusChange(bool);
-#endif
- void _q_selectionChanged();
- void _q_updateNeeded(const QRect &);
-#ifndef QT_NO_COMPLETER
- void _q_completionHighlighted(QString);
-#endif
-#ifndef QT_NO_DRAGANDDROP
- QPoint dndPos;
- QBasicTimer dndTimer;
- void drag();
-#endif
-
- int leftTextMargin;
- int topTextMargin;
- int rightTextMargin;
- int bottomTextMargin;
-
- QString placeholderText;
-};
-
-#endif // QT_NO_LINEEDIT
-
-QT_END_NAMESPACE
-
-#endif // QLINEEDIT_P_H
diff --git a/src/gui/widgets/qmaccocoaviewcontainer_mac.h b/src/gui/widgets/qmaccocoaviewcontainer_mac.h
deleted file mode 100644
index 9b5befb40f..0000000000
--- a/src/gui/widgets/qmaccocoaviewcontainer_mac.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** 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 QCOCOAVIEWCONTAINER_H
-#define QCOCOAVIEWCONTAINER_H
-
-#include <QtGui/QWidget>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QMacCocoaViewContainerPrivate;
-
-class Q_GUI_EXPORT QMacCocoaViewContainer : public QWidget
-{
- Q_OBJECT
-public:
- QMacCocoaViewContainer(void *cocoaViewToWrap, QWidget *parent = 0);
- virtual ~QMacCocoaViewContainer();
-
- void setCocoaView(void *cocoaViewToWrap);
- void *cocoaView() const;
-
-private:
- Q_DECLARE_PRIVATE(QMacCocoaViewContainer)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOCOAVIEWCONTAINER_H
diff --git a/src/gui/widgets/qmaccocoaviewcontainer_mac.mm b/src/gui/widgets/qmaccocoaviewcontainer_mac.mm
deleted file mode 100644
index cefc93f734..0000000000
--- a/src/gui/widgets/qmaccocoaviewcontainer_mac.mm
+++ /dev/null
@@ -1,187 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#import <Cocoa/Cocoa.h>
-#include <private/qwidget_p.h>
-#include "qmaccocoaviewcontainer_mac.h"
-#include <private/qt_mac_p.h>
-
-/*!
- \class QMacCocoaViewContainer
- \since 4.5
-
- \brief The QMacCocoaViewContainer class provides a widget for Mac OS X that can be used to wrap arbitrary
- Cocoa views (i.e., NSView subclasses) and insert them into Qt hierarchies.
-
- \ingroup advanced
-
- While Qt offers a lot of classes for writing your application, Apple's
- Cocoa framework offers lots of functionality that is not currently in Qt or
- may never end up in Qt. Using QMacCocoaViewContainer, it is possible to put an
- arbitrary NSView-derived class from Cocoa and put it in a Qt hierarchy.
- Depending on how comfortable you are with using objective-C, you can use
- QMacCocoaViewContainer directly, or subclass it to wrap further functionality
- of the underlying NSView.
-
- QMacCocoaViewContainer works regardless if Qt is built against Carbon or
- Cocoa. However, QCocoaContainerView requires Mac OS X 10.5 or better to be
- used with Carbon.
-
- It should be also noted that at the low level on Mac OS X, there is a
- difference between windows (top-levels) and view (widgets that are inside a
- window). For this reason, make sure that the NSView that you are wrapping
- doesn't end up as a top-level. The best way to ensure this is to make sure
- you always have a parent and not set the parent to 0.
-
- If you are using QMacCocoaViewContainer as a sub-class and are mixing and
- matching objective-C with C++ (a.k.a. objective-C++). It is probably
- simpler to have your file end with \tt{.mm} than \tt{.cpp}. Most Apple tools will
- correctly identify the source as objective-C++.
-
- QMacCocoaViewContainer requires knowledge of how Cocoa works, especially in
- regard to its reference counting (retain/release) nature. It is noted in
- the functions below if there is any change in the reference count. Cocoa
- views often generate temporary objects that are released by an autorelease
- pool. If this is done outside of a running event loop, it is up to the
- developer to provide the autorelease pool.
-
- The following is a snippet of subclassing QMacCocoaViewContainer to wrap a NSSearchField.
- \snippet demos/macmainwindow/macmainwindow.mm 0
-
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QMacCocoaViewContainerPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QMacCocoaViewContainer)
-public:
- NSView *nsview;
-#ifndef QT_MAC_USE_COCOA
- HIViewRef wrapperView;
-#endif
- QMacCocoaViewContainerPrivate();
- ~QMacCocoaViewContainerPrivate();
-};
-
-QMacCocoaViewContainerPrivate::QMacCocoaViewContainerPrivate()
- : nsview(0)
-#ifndef QT_MAC_USE_COCOA
- , wrapperView(0)
-#endif
-{
-}
-
-QMacCocoaViewContainerPrivate::~QMacCocoaViewContainerPrivate()
-{
- [nsview release];
-#ifndef QT_MAC_USE_COCOA
- if (wrapperView)
- CFRelease(wrapperView);
-#endif
-}
-
-/*!
- \fn QMacCocoaViewContainer::QMacCocoaViewContainer(void *cocoaViewToWrap, QWidget *parent)
-
- Create a new QMacCocoaViewContainer using the NSView pointer in \a
- cocoaViewToWrap with parent, \a parent. QMacCocoaViewContainer will
- retain \a cocoaViewToWrap.
-
- \a cocoaViewToWrap is a void pointer that allows the header to be included
- with C++ source.
-*/
-QMacCocoaViewContainer::QMacCocoaViewContainer(void *cocoaViewToWrap, QWidget *parent)
- : QWidget(*new QMacCocoaViewContainerPrivate, parent, 0)
-{
- if (cocoaViewToWrap)
- setCocoaView(cocoaViewToWrap);
-}
-
-/*!
- Destroy the QMacCocoaViewContainer and release the wrapped view.
-*/
-QMacCocoaViewContainer::~QMacCocoaViewContainer()
-{
-}
-
-/*!
- Returns the NSView that has been set on this container. The returned view
- has been autoreleased, so you will need to retain it if you want to make
- use of it.
-*/
-void *QMacCocoaViewContainer::cocoaView() const
-{
- Q_D(const QMacCocoaViewContainer);
- return [[d->nsview retain] autorelease];
-}
-
-/*!
- Sets the NSView to contain to be \a cocoaViewToWrap and retains it. If this
- container already had a view set, it will release the previously set view.
-*/
-void QMacCocoaViewContainer::setCocoaView(void *cocoaViewToWrap)
-{
- Q_D(QMacCocoaViewContainer);
- QMacCocoaAutoReleasePool pool;
- NSView *view = static_cast<NSView *>(cocoaViewToWrap);
- NSView *oldView = d->nsview;
- destroy(true, true);
- [view retain];
- d->nsview = view;
-#ifndef QT_MAC_USE_COCOA
- if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5) {
- qWarning("QMacCocoaViewContainer::setCocoaView: You cannot use this class with Carbon on versions of Mac OS X less than 10.5.");
- return;
- }
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
- if (d->wrapperView)
- CFRelease(d->wrapperView);
- HICocoaViewCreate(d->nsview, 0, &d->wrapperView);
- create(WId(d->wrapperView), false, true);
-#endif
-#else
- create(WId(d->nsview), false, true);
-#endif
- [oldView release];
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qmacnativewidget_mac.h b/src/gui/widgets/qmacnativewidget_mac.h
deleted file mode 100644
index 98c618d1ad..0000000000
--- a/src/gui/widgets/qmacnativewidget_mac.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** 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 QMACNATIVEWIDGET_H
-#define QMACNATIVEWIDGET_H
-
-#include <QtGui/QWidget>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QMacNativeWidgetPrivate;
-class Q_GUI_EXPORT QMacNativeWidget : public QWidget
-{
- Q_OBJECT
-public:
- QMacNativeWidget(void *parentRef = 0);
- ~QMacNativeWidget();
-
- QSize sizeHint() const;
-
-protected:
- bool event(QEvent *ev);
-
-private:
- Q_DECLARE_PRIVATE(QMacNativeWidget)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMACNATIVEWIDGET_H
diff --git a/src/gui/widgets/qmacnativewidget_mac.mm b/src/gui/widgets/qmacnativewidget_mac.mm
deleted file mode 100644
index d71fedd2a8..0000000000
--- a/src/gui/widgets/qmacnativewidget_mac.mm
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-#import <Cocoa/Cocoa.h>
-#import <private/qcocoaview_mac_p.h>
-#include "qmacnativewidget_mac.h"
-#include <private/qwidget_p.h>
-
-/*!
- \class QMacNativeWidget
- \since 4.5
- \brief The QMacNativeWidget class provides a widget for Mac OS X that provides a way to put Qt widgets into Carbon
- or Cocoa hierarchies depending on how Qt was configured.
-
- \ingroup advanced
-
- On Mac OS X, there is a difference between a window and view;
- normally expressed as widgets in Qt. Qt makes assumptions about its
- parent-child hierarchy that make it complex to put an arbitrary Qt widget
- into a hierarchy of "normal" views from Apple frameworks. QMacNativeWidget
- bridges the gap between views and windows and makes it possible to put a
- hierarchy of Qt widgets into a non-Qt window or view.
-
- QMacNativeWidget pretends it is a window (i.e. isWindow() will return true),
- but it cannot be shown on its own. It needs to be put into a window
- when it is created or later through a native call.
-
- QMacNativeWidget works for either Carbon or Cocoa depending on how Qt was configured. If Qt is
- using Carbon, QMacNativeWidget will embed into Carbon hierarchies. If Qt is
- using Cocoa, QMacNativeWidget embeds into Cocoa hierarchies.
-
- Here is an example of putting a QPushButton into a NSWindow:
-
- \snippet doc/src/snippets/qmacnativewidget/main.mm 0
-
- On Carbon, this would do the equivalent:
-
- \snippet doc/src/snippets/qmacnativewidget/main.mm 1
-
- Note that QMacNativeWidget requires knowledge of Carbon or Cocoa. All it
- does is get the Qt hierarchy into a window not owned by Qt. It is then up
- to the programmer to ensure it is placed correctly in the window and
- responds correctly to events.
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QMacNativeWidgetPrivate : public QWidgetPrivate
-{
-};
-
-extern OSViewRef qt_mac_create_widget(QWidget *widget, QWidgetPrivate *widgetPrivate, OSViewRef parent);
-
-
-/*!
- Create a QMacNativeWidget with \a parentView as its "superview" (i.e.,
- parent). The \a parentView is either an HIViewRef if Qt is using Carbon or
- a NSView pointer if Qt is using Cocoa.
-*/
-QMacNativeWidget::QMacNativeWidget(void *parentView)
- : QWidget(*new QMacNativeWidgetPrivate, 0, Qt::Window)
-{
- Q_D(QMacNativeWidget);
- OSViewRef myView = qt_mac_create_widget(this, d, OSViewRef(parentView));
-
- d->topData()->embedded = true;
- create(WId(myView), false, false);
- setPalette(QPalette(Qt::transparent));
- setAttribute(Qt::WA_SetPalette, false);
- setAttribute(Qt::WA_LayoutUsesWidgetRect);
-}
-
-/*!
- Destroy the QMacNativeWidget.
-*/
-QMacNativeWidget::~QMacNativeWidget()
-{
-}
-
-/*!
- \reimp
-*/
-QSize QMacNativeWidget::sizeHint() const
-{
- return QSize(200, 200);
-}
-/*!
- \reimp
-*/
-bool QMacNativeWidget::event(QEvent *ev)
-{
- return QWidget::event(ev);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qmainwindow.cpp b/src/gui/widgets/qmainwindow.cpp
deleted file mode 100644
index 43d67962e8..0000000000
--- a/src/gui/widgets/qmainwindow.cpp
+++ /dev/null
@@ -1,1686 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//#define QT_EXPERIMENTAL_CLIENT_DECORATIONS
-
-#include "qmainwindow.h"
-#include "qmainwindowlayout_p.h"
-
-#ifndef QT_NO_MAINWINDOW
-
-#include "qdockwidget.h"
-#include "qtoolbar.h"
-
-#include <qapplication.h>
-#include <qmenubar.h>
-#include <qstatusbar.h>
-#include <qevent.h>
-#include <qstyle.h>
-#include <qdebug.h>
-#include <qpainter.h>
-
-#include <private/qwidget_p.h>
-#include "qtoolbar_p.h"
-#include "qwidgetanimator_p.h"
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-QT_BEGIN_NAMESPACE
-extern OSWindowRef qt_mac_window_for(const QWidget *); // qwidget_mac.cpp
-QT_END_NAMESPACE
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QMainWindowPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QMainWindow)
-public:
- inline QMainWindowPrivate()
- : layout(0), explicitIconSize(false), toolButtonStyle(Qt::ToolButtonIconOnly)
-#ifdef Q_WS_MAC
- , useHIToolBar(false)
- , activateUnifiedToolbarAfterFullScreen(false)
-#endif
-#if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_CURSOR)
- , hasOldCursor(false) , cursorAdjusted(false)
-#endif
- { }
- QMainWindowLayout *layout;
- QSize iconSize;
- bool explicitIconSize;
- Qt::ToolButtonStyle toolButtonStyle;
-#ifdef Q_WS_MAC
- bool useHIToolBar;
- bool activateUnifiedToolbarAfterFullScreen;
-#endif
- void init();
- QList<int> hoverSeparator;
- QPoint hoverPos;
-
-#if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_CURSOR)
- QCursor separatorCursor(const QList<int> &path) const;
- void adjustCursor(const QPoint &pos);
- QCursor oldCursor;
- uint hasOldCursor : 1;
- uint cursorAdjusted : 1;
-#endif
-
- static inline QMainWindowLayout *mainWindowLayout(const QMainWindow *mainWindow)
- {
- return mainWindow ? mainWindow->d_func()->layout : static_cast<QMainWindowLayout *>(0);
- }
-};
-
-QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *mainWindow)
-{
- return QMainWindowPrivate::mainWindowLayout(mainWindow);
-}
-
-#ifdef QT_EXPERIMENTAL_CLIENT_DECORATIONS
-Q_GUI_EXPORT void qt_setMainWindowTitleWidget(QMainWindow *mainWindow, Qt::DockWidgetArea area, QWidget *widget)
-{
- QGridLayout *topLayout = qobject_cast<QGridLayout *>(mainWindow->layout());
- Q_ASSERT(topLayout);
-
- int row = 0;
- int column = 0;
-
- switch (area) {
- case Qt::LeftDockWidgetArea:
- row = 1;
- column = 0;
- break;
- case Qt::TopDockWidgetArea:
- row = 0;
- column = 1;
- break;
- case Qt::BottomDockWidgetArea:
- row = 2;
- column = 1;
- break;
- case Qt::RightDockWidgetArea:
- row = 1;
- column = 2;
- break;
- default:
- Q_ASSERT_X(false, "qt_setMainWindowTitleWidget", "Unknown area");
- return;
- }
-
- if (QLayoutItem *oldItem = topLayout->itemAtPosition(row, column))
- delete oldItem->widget();
- topLayout->addWidget(widget, row, column);
-}
-#endif
-
-void QMainWindowPrivate::init()
-{
- Q_Q(QMainWindow);
-
-#ifdef QT_EXPERIMENTAL_CLIENT_DECORATIONS
- QGridLayout *topLayout = new QGridLayout(q);
- topLayout->setContentsMargins(0, 0, 0, 0);
-
- layout = new QMainWindowLayout(q, topLayout);
-
- topLayout->addItem(layout, 1, 1);
-#else
- layout = new QMainWindowLayout(q, 0);
-#endif
-
- const int metric = q->style()->pixelMetric(QStyle::PM_ToolBarIconSize, 0, q);
- iconSize = QSize(metric, metric);
- q->setAttribute(Qt::WA_Hover);
-}
-
-/*
- The Main Window:
-
- +----------------------------------------------------------+
- | Menu Bar |
- +----------------------------------------------------------+
- | Tool Bar Area |
- | +--------------------------------------------------+ |
- | | Dock Window Area | |
- | | +------------------------------------------+ | |
- | | | | | |
- | | | Central Widget | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | | | | |
- | | +------------------------------------------+ | |
- | | | |
- | +--------------------------------------------------+ |
- | |
- +----------------------------------------------------------+
- | Status Bar |
- +----------------------------------------------------------+
-
-*/
-
-/*!
- \class QMainWindow
- \brief The QMainWindow class provides a main application
- window.
- \ingroup mainwindow-classes
-
-
- \tableofcontents
-
- \section1 Qt Main Window Framework
-
- A main window provides a framework for building an
- application's user interface. Qt has QMainWindow and its \l{Main
- Window and Related Classes}{related classes} for main window
- management. QMainWindow has its own layout to which you can add
- \l{QToolBar}s, \l{QDockWidget}s, a
- QMenuBar, and a QStatusBar. The layout has a center area that can
- be occupied by any kind of widget. You can see an image of the
- layout below.
-
- \image mainwindowlayout.png
-
- \note Creating a main window without a central widget is not supported.
- You must have a central widget even if it is just a placeholder.
-
- \section1 Creating Main Window Components
-
- A central widget will typically be a standard Qt widget such
- as a QTextEdit or a QGraphicsView. Custom widgets can also be
- used for advanced applications. You set the central widget with \c
- setCentralWidget().
-
- Main windows have either a single (SDI) or multiple (MDI)
- document interface. You create MDI applications in Qt by using a
- QMdiArea as the central widget.
-
- We will now examine each of the other widgets that can be
- added to a main window. We give examples on how to create and add
- them.
-
- \section2 Creating Menus
-
- Qt implements menus in QMenu and QMainWindow keeps them in a
- QMenuBar. \l{QAction}{QAction}s are added to the menus, which
- display them as menu items.
-
- You can add new menus to the main window's menu bar by calling
- \c menuBar(), which returns the QMenuBar for the window, and then
- add a menu with QMenuBar::addMenu().
-
- QMainWindow comes with a default menu bar, but you can also
- set one yourself with \c setMenuBar(). If you wish to implement a
- custom menu bar (i.e., not use the QMenuBar widget), you can set it
- with \c setMenuWidget().
-
- An example of how to create menus follows:
-
- \snippet examples/mainwindows/application/mainwindow.cpp 26
-
- The \c createPopupMenu() function creates popup menus when the
- main window receives context menu events. The default
- implementation generates a menu with the checkable actions from
- the dock widgets and toolbars. You can reimplement \c
- createPopupMenu() for a custom menu.
-
- \section2 Creating Toolbars
-
- Toolbars are implemented in the QToolBar class. You add a
- toolbar to a main window with \c addToolBar().
-
- You control the initial position of toolbars by assigning them
- to a specific Qt::ToolBarArea. You can split an area by inserting
- a toolbar break - think of this as a line break in text editing -
- with \c addToolBarBreak() or \c insertToolBarBreak(). You can also
- restrict placement by the user with QToolBar::setAllowedAreas()
- and QToolBar::setMovable().
-
- The size of toolbar icons can be retrieved with \c iconSize().
- The sizes are platform dependent; you can set a fixed size with \c
- setIconSize(). You can alter the appearance of all tool buttons in
- the toolbars with \c setToolButtonStyle().
-
- An example of toolbar creation follows:
-
- \snippet examples/mainwindows/application/mainwindow.cpp 29
-
- \section2 Creating Dock Widgets
-
- Dock widgets are implemented in the QDockWidget class. A dock
- widget is a window that can be docked into the main window. You
- add dock widgets to a main window with \c addDockWidget().
-
- There are four dock widget areas as given by the
- Qt::DockWidgetArea enum: left, right, top, and bottom. You can
- specify which dock widget area that should occupy the corners
- where the areas overlap with \c setCorner(). By default
- each area can only contain one row (vertical or horizontal) of
- dock widgets, but if you enable nesting with \c
- setDockNestingEnabled(), dock widgets can be added in either
- direction.
-
- Two dock widgets may also be stacked on top of each other. A
- QTabBar is then used to select which of the widgets that should be
- displayed.
-
- We give an example of how to create and add dock widgets to a
- main window:
-
- \snippet doc/src/snippets/mainwindowsnippet.cpp 0
-
- \section2 The Status Bar
-
- You can set a status bar with \c setStatusBar(), but one is
- created the first time \c statusBar() (which returns the main
- window's status bar) is called. See QStatusBar for information on
- how to use it.
-
- \section1 Storing State
-
- QMainWindow can store the state of its layout with \c
- saveState(); it can later be retrieved with \c restoreState(). It
- is the position and size (relative to the size of the main window)
- of the toolbars and dock widgets that are stored.
-
- \sa QMenuBar, QToolBar, QStatusBar, QDockWidget, {Application
- Example}, {Dock Widgets Example}, {MDI Example}, {SDI Example},
- {Menus Example}
-*/
-
-/*!
- \fn void QMainWindow::iconSizeChanged(const QSize &iconSize)
-
- This signal is emitted when the size of the icons used in the
- window is changed. The new icon size is passed in \a iconSize.
-
- You can connect this signal to other components to help maintain
- a consistent appearance for your application.
-
- \sa setIconSize()
-*/
-
-/*!
- \fn void QMainWindow::toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle)
-
- This signal is emitted when the style used for tool buttons in the
- window is changed. The new style is passed in \a toolButtonStyle.
-
- You can connect this signal to other components to help maintain
- a consistent appearance for your application.
-
- \sa setToolButtonStyle()
-*/
-
-/*!
- Constructs a QMainWindow with the given \a parent and the specified
- widget \a flags.
-
- QMainWindow sets the Qt::Window flag itself, and will hence
- always be created as a top-level widget.
- */
-QMainWindow::QMainWindow(QWidget *parent, Qt::WindowFlags flags)
- : QWidget(*(new QMainWindowPrivate()), parent, flags | Qt::Window)
-{
- d_func()->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \obsolete
- Constructs a QMainWindow with the given \a parent, \a name, and
- with the specified widget \a flags.
- */
-QMainWindow::QMainWindow(QWidget *parent, const char *name, Qt::WindowFlags flags)
- : QWidget(*(new QMainWindowPrivate()), parent, flags | Qt::WType_TopLevel)
-{
- setObjectName(QString::fromAscii(name));
- d_func()->init();
-}
-#endif
-
-/*!
- Destroys the main window.
- */
-QMainWindow::~QMainWindow()
-{ }
-
-/*! \property QMainWindow::iconSize
- \brief size of toolbar icons in this mainwindow.
-
- The default is the default tool bar icon size of the GUI style.
- Note that the icons used must be at least of this size as the
- icons are only scaled down.
-*/
-
-/*!
- \property QMainWindow::dockOptions
- \brief the docking behavior of QMainWindow
- \since 4.3
-
- The default value is AnimatedDocks | AllowTabbedDocks.
-*/
-
-/*!
- \enum QMainWindow::DockOption
- \since 4.3
-
- This enum contains flags that specify the docking behavior of QMainWindow.
-
- \value AnimatedDocks Identical to the \l animated property.
-
- \value AllowNestedDocks Identical to the \l dockNestingEnabled property.
-
- \value AllowTabbedDocks The user can drop one dock widget "on top" of
- another. The two widgets are stacked and a tab
- bar appears for selecting which one is visible.
-
- \value ForceTabbedDocks Each dock area contains a single stack of tabbed
- dock widgets. In other words, dock widgets cannot
- be placed next to each other in a dock area. If
- this option is set, AllowNestedDocks has no effect.
-
- \value VerticalTabs The two vertical dock areas on the sides of the
- main window show their tabs vertically. If this
- option is not set, all dock areas show their tabs
- at the bottom. Implies AllowTabbedDocks. See also
- \l setTabPosition().
-
- These options only control how dock widgets may be dropped in a QMainWindow.
- They do not re-arrange the dock widgets to conform with the specified
- options. For this reason they should be set before any dock widgets
- are added to the main window. Exceptions to this are the AnimatedDocks and
- VerticalTabs options, which may be set at any time.
-*/
-
-void QMainWindow::setDockOptions(DockOptions opt)
-{
- Q_D(QMainWindow);
- d->layout->setDockOptions(opt);
-}
-
-QMainWindow::DockOptions QMainWindow::dockOptions() const
-{
- Q_D(const QMainWindow);
- return d->layout->dockOptions;
-}
-
-QSize QMainWindow::iconSize() const
-{ return d_func()->iconSize; }
-
-void QMainWindow::setIconSize(const QSize &iconSize)
-{
- Q_D(QMainWindow);
- QSize sz = iconSize;
- if (!sz.isValid()) {
- const int metric = style()->pixelMetric(QStyle::PM_ToolBarIconSize, 0, this);
- sz = QSize(metric, metric);
- }
- if (d->iconSize != sz) {
- d->iconSize = sz;
- emit iconSizeChanged(d->iconSize);
- }
- d->explicitIconSize = iconSize.isValid();
-}
-
-/*! \property QMainWindow::toolButtonStyle
- \brief style of toolbar buttons in this mainwindow.
-
- The default is Qt::ToolButtonIconOnly.
-*/
-
-Qt::ToolButtonStyle QMainWindow::toolButtonStyle() const
-{ return d_func()->toolButtonStyle; }
-
-void QMainWindow::setToolButtonStyle(Qt::ToolButtonStyle toolButtonStyle)
-{
- Q_D(QMainWindow);
- if (d->toolButtonStyle == toolButtonStyle)
- return;
- d->toolButtonStyle = toolButtonStyle;
- emit toolButtonStyleChanged(d->toolButtonStyle);
-}
-
-#ifndef QT_NO_MENUBAR
-/*!
- Returns the menu bar for the main window. This function creates
- and returns an empty menu bar if the menu bar does not exist.
-
- If you want all windows in a Mac application to share one menu
- bar, don't use this function to create it, because the menu bar
- created here will have this QMainWindow as its parent. Instead,
- you must create a menu bar that does not have a parent, which you
- can then share among all the Mac windows. Create a parent-less
- menu bar this way:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qmenubar.cpp 1
-
- \sa setMenuBar()
-*/
-QMenuBar *QMainWindow::menuBar() const
-{
- QMenuBar *menuBar = qobject_cast<QMenuBar *>(layout()->menuBar());
- if (!menuBar) {
- QMainWindow *self = const_cast<QMainWindow *>(this);
- menuBar = new QMenuBar(self);
- self->setMenuBar(menuBar);
- }
- return menuBar;
-}
-
-/*!
- Sets the menu bar for the main window to \a menuBar.
-
- Note: QMainWindow takes ownership of the \a menuBar pointer and
- deletes it at the appropriate time.
-
- \sa menuBar()
-*/
-void QMainWindow::setMenuBar(QMenuBar *menuBar)
-{
- QLayout *topLayout = layout();
-
- if (topLayout->menuBar() && topLayout->menuBar() != menuBar) {
- // Reparent corner widgets before we delete the old menu bar.
- QMenuBar *oldMenuBar = qobject_cast<QMenuBar *>(topLayout->menuBar());
- if (menuBar) {
- // TopLeftCorner widget.
- QWidget *cornerWidget = oldMenuBar->cornerWidget(Qt::TopLeftCorner);
- if (cornerWidget)
- menuBar->setCornerWidget(cornerWidget, Qt::TopLeftCorner);
- // TopRightCorner widget.
- cornerWidget = oldMenuBar->cornerWidget(Qt::TopRightCorner);
- if (cornerWidget)
- menuBar->setCornerWidget(cornerWidget, Qt::TopRightCorner);
- }
- oldMenuBar->hide();
- oldMenuBar->deleteLater();
- }
- topLayout->setMenuBar(menuBar);
-}
-
-/*!
- \since 4.2
-
- Returns the menu bar for the main window. This function returns
- null if a menu bar hasn't been constructed yet.
-*/
-QWidget *QMainWindow::menuWidget() const
-{
- QWidget *menuBar = d_func()->layout->menuBar();
- return menuBar;
-}
-
-/*!
- \since 4.2
-
- Sets the menu bar for the main window to \a menuBar.
-
- QMainWindow takes ownership of the \a menuBar pointer and
- deletes it at the appropriate time.
-*/
-void QMainWindow::setMenuWidget(QWidget *menuBar)
-{
- Q_D(QMainWindow);
- if (d->layout->menuBar() && d->layout->menuBar() != menuBar) {
- d->layout->menuBar()->hide();
- d->layout->menuBar()->deleteLater();
- }
- d->layout->setMenuBar(menuBar);
-}
-#endif // QT_NO_MENUBAR
-
-#ifndef QT_NO_STATUSBAR
-/*!
- Returns the status bar for the main window. This function creates
- and returns an empty status bar if the status bar does not exist.
-
- \sa setStatusBar()
-*/
-QStatusBar *QMainWindow::statusBar() const
-{
- QStatusBar *statusbar = d_func()->layout->statusBar();
- if (!statusbar) {
- QMainWindow *self = const_cast<QMainWindow *>(this);
- statusbar = new QStatusBar(self);
- statusbar->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
- self->setStatusBar(statusbar);
- }
- return statusbar;
-}
-
-/*!
- Sets the status bar for the main window to \a statusbar.
-
- Setting the status bar to 0 will remove it from the main window.
- Note that QMainWindow takes ownership of the \a statusbar pointer
- and deletes it at the appropriate time.
-
- \sa statusBar()
-*/
-void QMainWindow::setStatusBar(QStatusBar *statusbar)
-{
- Q_D(QMainWindow);
- if (d->layout->statusBar() && d->layout->statusBar() != statusbar) {
- d->layout->statusBar()->hide();
- d->layout->statusBar()->deleteLater();
- }
- d->layout->setStatusBar(statusbar);
-}
-#endif // QT_NO_STATUSBAR
-
-/*!
- Returns the central widget for the main window. This function
- returns zero if the central widget has not been set.
-
- \sa setCentralWidget()
-*/
-QWidget *QMainWindow::centralWidget() const
-{ return d_func()->layout->centralWidget(); }
-
-/*!
- Sets the given \a widget to be the main window's central widget.
-
- Note: QMainWindow takes ownership of the \a widget pointer and
- deletes it at the appropriate time.
-
- \sa centralWidget()
-*/
-void QMainWindow::setCentralWidget(QWidget *widget)
-{
- Q_D(QMainWindow);
- if (d->layout->centralWidget() && d->layout->centralWidget() != widget) {
- d->layout->centralWidget()->hide();
- d->layout->centralWidget()->deleteLater();
- }
- d->layout->setCentralWidget(widget);
-}
-
-#ifndef QT_NO_DOCKWIDGET
-/*!
- Sets the given dock widget \a area to occupy the specified \a
- corner.
-
- \sa corner()
-*/
-void QMainWindow::setCorner(Qt::Corner corner, Qt::DockWidgetArea area)
-{
- bool valid = false;
- switch (corner) {
- case Qt::TopLeftCorner:
- valid = (area == Qt::TopDockWidgetArea || area == Qt::LeftDockWidgetArea);
- break;
- case Qt::TopRightCorner:
- valid = (area == Qt::TopDockWidgetArea || area == Qt::RightDockWidgetArea);
- break;
- case Qt::BottomLeftCorner:
- valid = (area == Qt::BottomDockWidgetArea || area == Qt::LeftDockWidgetArea);
- break;
- case Qt::BottomRightCorner:
- valid = (area == Qt::BottomDockWidgetArea || area == Qt::RightDockWidgetArea);
- break;
- }
- if (!valid)
- qWarning("QMainWindow::setCorner(): 'area' is not valid for 'corner'");
- else
- d_func()->layout->setCorner(corner, area);
-}
-
-/*!
- Returns the dock widget area that occupies the specified \a
- corner.
-
- \sa setCorner()
-*/
-Qt::DockWidgetArea QMainWindow::corner(Qt::Corner corner) const
-{ return d_func()->layout->corner(corner); }
-#endif
-
-#ifndef QT_NO_TOOLBAR
-
-static bool checkToolBarArea(Qt::ToolBarArea area, const char *where)
-{
- switch (area) {
- case Qt::LeftToolBarArea:
- case Qt::RightToolBarArea:
- case Qt::TopToolBarArea:
- case Qt::BottomToolBarArea:
- return true;
- default:
- break;
- }
- qWarning("%s: invalid 'area' argument", where);
- return false;
-}
-
-/*!
- Adds a toolbar break to the given \a area after all the other
- objects that are present.
-*/
-void QMainWindow::addToolBarBreak(Qt::ToolBarArea area)
-{
- if (!checkToolBarArea(area, "QMainWindow::addToolBarBreak"))
- return;
- d_func()->layout->addToolBarBreak(area);
-}
-
-/*!
- Inserts a toolbar break before the toolbar specified by \a before.
-*/
-void QMainWindow::insertToolBarBreak(QToolBar *before)
-{ d_func()->layout->insertToolBarBreak(before); }
-
-/*!
- Removes a toolbar break previously inserted before the toolbar specified by \a before.
-*/
-
-void QMainWindow::removeToolBarBreak(QToolBar *before)
-{
- Q_D(QMainWindow);
- d->layout->removeToolBarBreak(before);
-}
-
-/*!
- Adds the \a toolbar into the specified \a area in this main
- window. The \a toolbar is placed at the end of the current tool
- bar block (i.e. line). If the main window already manages \a toolbar
- then it will only move the toolbar to \a area.
-
- \sa insertToolBar() addToolBarBreak() insertToolBarBreak()
-*/
-void QMainWindow::addToolBar(Qt::ToolBarArea area, QToolBar *toolbar)
-{
- if (!checkToolBarArea(area, "QMainWindow::addToolBar"))
- return;
-
- Q_D(QMainWindow);
-
- disconnect(this, SIGNAL(iconSizeChanged(QSize)),
- toolbar, SLOT(_q_updateIconSize(QSize)));
- disconnect(this, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
- toolbar, SLOT(_q_updateToolButtonStyle(Qt::ToolButtonStyle)));
-
- if(toolbar->d_func()->state && toolbar->d_func()->state->dragging) {
- //removing a toolbar which is dragging will cause crash
-#ifndef QT_NO_DOCKWIDGET
- bool animated = isAnimated();
- setAnimated(false);
-#endif
- toolbar->d_func()->endDrag();
-#ifndef QT_NO_DOCKWIDGET
- setAnimated(animated);
-#endif
- }
-
- if (!d->layout->usesHIToolBar(toolbar)) {
- d->layout->removeWidget(toolbar);
- } else {
- d->layout->removeToolBar(toolbar);
- }
-
- toolbar->d_func()->_q_updateIconSize(d->iconSize);
- toolbar->d_func()->_q_updateToolButtonStyle(d->toolButtonStyle);
- connect(this, SIGNAL(iconSizeChanged(QSize)),
- toolbar, SLOT(_q_updateIconSize(QSize)));
- connect(this, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
- toolbar, SLOT(_q_updateToolButtonStyle(Qt::ToolButtonStyle)));
-
- d->layout->addToolBar(area, toolbar);
-}
-
-/*! \overload
- Equivalent of calling addToolBar(Qt::TopToolBarArea, \a toolbar)
-*/
-void QMainWindow::addToolBar(QToolBar *toolbar)
-{ addToolBar(Qt::TopToolBarArea, toolbar); }
-
-/*!
- \overload
-
- Creates a QToolBar object, setting its window title to \a title,
- and inserts it into the top toolbar area.
-
- \sa setWindowTitle()
-*/
-QToolBar *QMainWindow::addToolBar(const QString &title)
-{
- QToolBar *toolBar = new QToolBar(this);
- toolBar->setWindowTitle(title);
- addToolBar(toolBar);
- return toolBar;
-}
-
-/*!
- Inserts the \a toolbar into the area occupied by the \a before toolbar
- so that it appears before it. For example, in normal left-to-right
- layout operation, this means that \a toolbar will appear to the left
- of the toolbar specified by \a before in a horizontal toolbar area.
-
- \sa insertToolBarBreak() addToolBar() addToolBarBreak()
-*/
-void QMainWindow::insertToolBar(QToolBar *before, QToolBar *toolbar)
-{
- Q_D(QMainWindow);
-
- d->layout->removeToolBar(toolbar);
-
- toolbar->d_func()->_q_updateIconSize(d->iconSize);
- toolbar->d_func()->_q_updateToolButtonStyle(d->toolButtonStyle);
- connect(this, SIGNAL(iconSizeChanged(QSize)),
- toolbar, SLOT(_q_updateIconSize(QSize)));
- connect(this, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
- toolbar, SLOT(_q_updateToolButtonStyle(Qt::ToolButtonStyle)));
-
- d->layout->insertToolBar(before, toolbar);
-}
-
-/*!
- Removes the \a toolbar from the main window layout and hides
- it. Note that the \a toolbar is \e not deleted.
-*/
-void QMainWindow::removeToolBar(QToolBar *toolbar)
-{
- if (toolbar) {
- d_func()->layout->removeToolBar(toolbar);
- toolbar->hide();
- }
-}
-
-/*!
- Returns the Qt::ToolBarArea for \a toolbar. If \a toolbar has not
- been added to the main window, this function returns \c
- Qt::NoToolBarArea.
-
- \sa addToolBar() addToolBarBreak() Qt::ToolBarArea
-*/
-Qt::ToolBarArea QMainWindow::toolBarArea(QToolBar *toolbar) const
-{ return d_func()->layout->toolBarArea(toolbar); }
-
-/*!
-
- Returns whether there is a toolbar
- break before the \a toolbar.
-
- \sa addToolBarBreak(), insertToolBarBreak()
-*/
-bool QMainWindow::toolBarBreak(QToolBar *toolbar) const
-{
- return d_func()->layout->toolBarBreak(toolbar);
-}
-
-#endif // QT_NO_TOOLBAR
-
-#ifndef QT_NO_DOCKWIDGET
-
-/*! \property QMainWindow::animated
- \brief whether manipulating dock widgets and tool bars is animated
- \since 4.2
-
- When a dock widget or tool bar is dragged over the
- main window, the main window adjusts its contents
- to indicate where the dock widget or tool bar will
- be docked if it is dropped. Setting this property
- causes QMainWindow to move its contents in a smooth
- animation. Clearing this property causes the contents
- to snap into their new positions.
-
- By default, this property is set. It may be cleared if
- the main window contains widgets which are slow at resizing
- or repainting themselves.
-
- Setting this property is identical to setting the AnimatedDocks
- option using setDockOptions().
-*/
-
-bool QMainWindow::isAnimated() const
-{
- Q_D(const QMainWindow);
- return d->layout->dockOptions & AnimatedDocks;
-}
-
-void QMainWindow::setAnimated(bool enabled)
-{
- Q_D(QMainWindow);
-
- DockOptions opts = d->layout->dockOptions;
- if (enabled)
- opts |= AnimatedDocks;
- else
- opts &= ~AnimatedDocks;
-
- d->layout->setDockOptions(opts);
-}
-
-/*! \property QMainWindow::dockNestingEnabled
- \brief whether docks can be nested
- \since 4.2
-
- If this property is false, dock areas can only contain a single row
- (horizontal or vertical) of dock widgets. If this property is true,
- the area occupied by a dock widget can be split in either direction to contain
- more dock widgets.
-
- Dock nesting is only necessary in applications that contain a lot of
- dock widgets. It gives the user greater freedom in organizing their
- main window. However, dock nesting leads to more complex
- (and less intuitive) behavior when a dock widget is dragged over the
- main window, since there are more ways in which a dropped dock widget
- may be placed in the dock area.
-
- Setting this property is identical to setting the AllowNestedDocks option
- using setDockOptions().
-*/
-
-bool QMainWindow::isDockNestingEnabled() const
-{
- Q_D(const QMainWindow);
- return d->layout->dockOptions & AllowNestedDocks;
-}
-
-void QMainWindow::setDockNestingEnabled(bool enabled)
-{
- Q_D(QMainWindow);
-
- DockOptions opts = d->layout->dockOptions;
- if (enabled)
- opts |= AllowNestedDocks;
- else
- opts &= ~AllowNestedDocks;
-
- d->layout->setDockOptions(opts);
-}
-
-#if 0
-/*! \property QMainWindow::verticalTabsEnabled
- \brief whether left and right dock areas use vertical tabs
- \since 4.2
-
- If this property is set to false, dock areas containing tabbed dock widgets
- display horizontal tabs, simmilar to Visual Studio.
-
- If this property is set to true, then the right and left dock areas display vertical
- tabs, simmilar to KDevelop.
-
- This property should be set before any dock widgets are added to the main window.
-*/
-
-bool QMainWindow::verticalTabsEnabled() const
-{
- return d_func()->layout->verticalTabsEnabled();
-}
-
-void QMainWindow::setVerticalTabsEnabled(bool enabled)
-{
- d_func()->layout->setVerticalTabsEnabled(enabled);
-}
-#endif
-
-static bool checkDockWidgetArea(Qt::DockWidgetArea area, const char *where)
-{
- switch (area) {
- case Qt::LeftDockWidgetArea:
- case Qt::RightDockWidgetArea:
- case Qt::TopDockWidgetArea:
- case Qt::BottomDockWidgetArea:
- return true;
- default:
- break;
- }
- qWarning("%s: invalid 'area' argument", where);
- return false;
-}
-
-#ifndef QT_NO_TABBAR
-/*!
- \property QMainWindow::documentMode
- \brief whether the tab bar for tabbed dockwidgets is set to document mode.
- \since 4.5
-
- The default is false.
-
- \sa QTabBar::documentMode
-*/
-bool QMainWindow::documentMode() const
-{
- return d_func()->layout->documentMode();
-}
-
-void QMainWindow::setDocumentMode(bool enabled)
-{
- d_func()->layout->setDocumentMode(enabled);
-}
-#endif // QT_NO_TABBAR
-
-#ifndef QT_NO_TABWIDGET
-/*!
- \property QMainWindow::tabShape
- \brief the tab shape used for tabbed dock widgets.
- \since 4.5
-
- The default is \l QTabWidget::Rounded.
-
- \sa setTabPosition()
-*/
-QTabWidget::TabShape QMainWindow::tabShape() const
-{
- return d_func()->layout->tabShape();
-}
-
-void QMainWindow::setTabShape(QTabWidget::TabShape tabShape)
-{
- d_func()->layout->setTabShape(tabShape);
-}
-
-/*!
- \since 4.5
-
- Returns the tab position for \a area.
-
- \note The \l VerticalTabs dock option overrides the tab positions returned
- by this function.
-
- \sa setTabPosition(), tabShape()
-*/
-QTabWidget::TabPosition QMainWindow::tabPosition(Qt::DockWidgetArea area) const
-{
- if (!checkDockWidgetArea(area, "QMainWindow::tabPosition"))
- return QTabWidget::South;
- return d_func()->layout->tabPosition(area);
-}
-
-/*!
- \since 4.5
-
- Sets the tab position for the given dock widget \a areas to the specified
- \a tabPosition. By default, all dock areas show their tabs at the bottom.
-
- \note The \l VerticalTabs dock option overrides the tab positions set by
- this method.
-
- \sa tabPosition(), setTabShape()
-*/
-void QMainWindow::setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition)
-{
- d_func()->layout->setTabPosition(areas, tabPosition);
-}
-#endif // QT_NO_TABWIDGET
-
-/*!
- Adds the given \a dockwidget to the specified \a area.
-*/
-void QMainWindow::addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget)
-{
- if (!checkDockWidgetArea(area, "QMainWindow::addDockWidget"))
- return;
-
- Qt::Orientation orientation = Qt::Vertical;
- switch (area) {
- case Qt::TopDockWidgetArea:
- case Qt::BottomDockWidgetArea:
- orientation = Qt::Horizontal;
- break;
- default:
- break;
- }
- d_func()->layout->removeWidget(dockwidget); // in case it was already in here
- addDockWidget(area, dockwidget, orientation);
-
-#ifdef Q_WS_MAC //drawer support
- QMacCocoaAutoReleasePool pool;
- extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
- if (qt_mac_is_macdrawer(dockwidget)) {
- extern bool qt_mac_set_drawer_preferred_edge(QWidget *, Qt::DockWidgetArea); //qwidget_mac.cpp
- window()->createWinId();
- dockwidget->window()->createWinId();
- qt_mac_set_drawer_preferred_edge(dockwidget, area);
- if (dockwidget->isVisible()) {
- dockwidget->hide();
- dockwidget->show();
- }
- }
-#endif
-}
-
-/*!
- Restores the state of \a dockwidget if it is created after the call
- to restoreState(). Returns true if the state was restored; otherwise
- returns false.
-
- \sa restoreState(), saveState()
-*/
-
-bool QMainWindow::restoreDockWidget(QDockWidget *dockwidget)
-{
- return d_func()->layout->restoreDockWidget(dockwidget);
-}
-
-/*!
- Adds \a dockwidget into the given \a area in the direction
- specified by the \a orientation.
-*/
-void QMainWindow::addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget,
- Qt::Orientation orientation)
-{
- if (!checkDockWidgetArea(area, "QMainWindow::addDockWidget"))
- return;
-
- // add a window to an area, placing done relative to the previous
- d_func()->layout->addDockWidget(area, dockwidget, orientation);
-}
-
-/*!
- \fn void QMainWindow::splitDockWidget(QDockWidget *first, QDockWidget *second, Qt::Orientation orientation)
-
- Splits the space covered by the \a first dock widget into two parts,
- moves the \a first dock widget into the first part, and moves the
- \a second dock widget into the second part.
-
- The \a orientation specifies how the space is divided: A Qt::Horizontal
- split places the second dock widget to the right of the first; a
- Qt::Vertical split places the second dock widget below the first.
-
- \e Note: if \a first is currently in a tabbed docked area, \a second will
- be added as a new tab, not as a neighbor of \a first. This is because a
- single tab can contain only one dock widget.
-
- \e Note: The Qt::LayoutDirection influences the order of the dock widgets
- in the two parts of the divided area. When right-to-left layout direction
- is enabled, the placing of the dock widgets will be reversed.
-
- \sa tabifyDockWidget(), addDockWidget(), removeDockWidget()
-*/
-void QMainWindow::splitDockWidget(QDockWidget *after, QDockWidget *dockwidget,
- Qt::Orientation orientation)
-{
- d_func()->layout->splitDockWidget(after, dockwidget, orientation);
-}
-
-/*!
- \fn void QMainWindow::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
-
- Moves \a second dock widget on top of \a first dock widget, creating a tabbed
- docked area in the main window.
-
- \sa tabifiedDockWidgets()
-*/
-void QMainWindow::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
-{
- d_func()->layout->tabifyDockWidget(first, second);
-}
-
-
-/*!
- \fn QList<QDockWidget*> QMainWindow::tabifiedDockWidgets(QDockWidget *dockwidget) const
-
- Returns the dock widgets that are tabified together with \a dockwidget.
-
- \since 4.5
- \sa tabifyDockWidget()
-*/
-
-QList<QDockWidget*> QMainWindow::tabifiedDockWidgets(QDockWidget *dockwidget) const
-{
- QList<QDockWidget*> ret;
-#if defined(QT_NO_TABBAR)
- Q_UNUSED(dockwidget);
-#else
- const QDockAreaLayoutInfo *info = d_func()->layout->layoutState.dockAreaLayout.info(dockwidget);
- if (info && info->tabbed && info->tabBar) {
- for(int i = 0; i < info->item_list.count(); ++i) {
- const QDockAreaLayoutItem &item = info->item_list.at(i);
- if (item.widgetItem) {
- if (QDockWidget *dock = qobject_cast<QDockWidget*>(item.widgetItem->widget())) {
- if (dock != dockwidget) {
- ret += dock;
- }
- }
- }
- }
- }
-#endif
- return ret;
-}
-
-
-/*!
- Removes the \a dockwidget from the main window layout and hides
- it. Note that the \a dockwidget is \e not deleted.
-*/
-void QMainWindow::removeDockWidget(QDockWidget *dockwidget)
-{
- if (dockwidget) {
- d_func()->layout->removeWidget(dockwidget);
- dockwidget->hide();
- }
-}
-
-/*!
- Returns the Qt::DockWidgetArea for \a dockwidget. If \a dockwidget
- has not been added to the main window, this function returns \c
- Qt::NoDockWidgetArea.
-
- \sa addDockWidget() splitDockWidget() Qt::DockWidgetArea
-*/
-Qt::DockWidgetArea QMainWindow::dockWidgetArea(QDockWidget *dockwidget) const
-{ return d_func()->layout->dockWidgetArea(dockwidget); }
-
-#endif // QT_NO_DOCKWIDGET
-
-/*!
- Saves the current state of this mainwindow's toolbars and
- dockwidgets. The \a version number is stored as part of the data.
-
- The \link QObject::objectName objectName\endlink property is used
- to identify each QToolBar and QDockWidget. You should make sure
- that this property is unique for each QToolBar and QDockWidget you
- add to the QMainWindow
-
- To restore the saved state, pass the return value and \a version
- number to restoreState().
-
- To save the geometry when the window closes, you can
- implement a close event like this:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qmainwindow.cpp 0
-
- \sa restoreState(), QWidget::saveGeometry(), QWidget::restoreGeometry()
-*/
-QByteArray QMainWindow::saveState(int version) const
-{
- QByteArray data;
- QDataStream stream(&data, QIODevice::WriteOnly);
- stream << QMainWindowLayout::VersionMarker;
- stream << version;
- d_func()->layout->saveState(stream);
- return data;
-}
-
-/*!
- Restores the \a state of this mainwindow's toolbars and
- dockwidgets. The \a version number is compared with that stored
- in \a state. If they do not match, the mainwindow's state is left
- unchanged, and this function returns \c false; otherwise, the state
- is restored, and this function returns \c true.
-
- To restore geometry saved using QSettings, you can use code like
- this:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qmainwindow.cpp 1
-
- \sa saveState(), QWidget::saveGeometry(),
- QWidget::restoreGeometry(), restoreDockWidget()
-*/
-bool QMainWindow::restoreState(const QByteArray &state, int version)
-{
- if (state.isEmpty())
- return false;
- QByteArray sd = state;
- QDataStream stream(&sd, QIODevice::ReadOnly);
- int marker, v;
- stream >> marker;
- stream >> v;
- if (stream.status() != QDataStream::Ok || marker != QMainWindowLayout::VersionMarker || v != version)
- return false;
- bool restored = d_func()->layout->restoreState(stream);
- return restored;
-}
-
-#if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_CURSOR)
-QCursor QMainWindowPrivate::separatorCursor(const QList<int> &path) const
-{
- QDockAreaLayoutInfo *info = layout->layoutState.dockAreaLayout.info(path);
- Q_ASSERT(info != 0);
- if (path.size() == 1) { // is this the "top-level" separator which separates a dock area
- // from the central widget?
- switch (path.first()) {
- case QInternal::LeftDock:
- case QInternal::RightDock:
- return Qt::SplitHCursor;
- case QInternal::TopDock:
- case QInternal::BottomDock:
- return Qt::SplitVCursor;
- default:
- break;
- }
- }
-
- // no, it's a splitter inside a dock area, separating two dock widgets
-
- return info->o == Qt::Horizontal
- ? Qt::SplitHCursor : Qt::SplitVCursor;
-}
-
-void QMainWindowPrivate::adjustCursor(const QPoint &pos)
-{
- Q_Q(QMainWindow);
-
- hoverPos = pos;
-
- if (pos == QPoint(0, 0)) {
- if (!hoverSeparator.isEmpty())
- q->update(layout->layoutState.dockAreaLayout.separatorRect(hoverSeparator));
- hoverSeparator.clear();
-
- if (cursorAdjusted) {
- cursorAdjusted = false;
- if (hasOldCursor)
- q->setCursor(oldCursor);
- else
- q->unsetCursor();
- }
- } else {
- QList<int> pathToSeparator
- = layout->layoutState.dockAreaLayout.findSeparator(pos);
-
- if (pathToSeparator != hoverSeparator) {
- if (!hoverSeparator.isEmpty())
- q->update(layout->layoutState.dockAreaLayout.separatorRect(hoverSeparator));
-
- hoverSeparator = pathToSeparator;
-
- if (hoverSeparator.isEmpty()) {
- if (cursorAdjusted) {
- cursorAdjusted = false;
- if (hasOldCursor)
- q->setCursor(oldCursor);
- else
- q->unsetCursor();
- }
- } else {
- q->update(layout->layoutState.dockAreaLayout.separatorRect(hoverSeparator));
- if (!cursorAdjusted) {
- oldCursor = q->cursor();
- hasOldCursor = q->testAttribute(Qt::WA_SetCursor);
- }
- QCursor cursor = separatorCursor(hoverSeparator);
- cursorAdjusted = false; //to not reset the oldCursor in event(CursorChange)
- q->setCursor(cursor);
- cursorAdjusted = true;
- }
- }
- }
-}
-#endif
-
-/*! \reimp */
-bool QMainWindow::event(QEvent *event)
-{
- Q_D(QMainWindow);
- switch (event->type()) {
-
-#ifndef QT_NO_DOCKWIDGET
- case QEvent::Paint: {
- QPainter p(this);
- QRegion r = static_cast<QPaintEvent*>(event)->region();
- d->layout->layoutState.dockAreaLayout.paintSeparators(&p, this, r, d->hoverPos);
- break;
- }
-
-#ifndef QT_NO_CURSOR
- case QEvent::HoverMove: {
- d->adjustCursor(static_cast<QHoverEvent*>(event)->pos());
- break;
- }
-
- // We don't want QWidget to call update() on the entire QMainWindow
- // on HoverEnter and HoverLeave, hence accept the event (return true).
- case QEvent::HoverEnter:
- return true;
- case QEvent::HoverLeave:
- d->adjustCursor(QPoint(0, 0));
- return true;
- case QEvent::ShortcutOverride: // when a menu pops up
- d->adjustCursor(QPoint(0, 0));
- break;
-#endif // QT_NO_CURSOR
-
- case QEvent::MouseButtonPress: {
- QMouseEvent *e = static_cast<QMouseEvent*>(event);
- if (e->button() == Qt::LeftButton && d->layout->startSeparatorMove(e->pos())) {
- // The click was on a separator, eat this event
- e->accept();
- return true;
- }
- break;
- }
-
- case QEvent::MouseMove: {
- QMouseEvent *e = static_cast<QMouseEvent*>(event);
-
-#ifndef QT_NO_CURSOR
- d->adjustCursor(e->pos());
-#endif
- if (e->buttons() & Qt::LeftButton) {
- if (d->layout->separatorMove(e->pos())) {
- // We're moving a separator, eat this event
- e->accept();
- return true;
- }
- }
-
- break;
- }
-
- case QEvent::MouseButtonRelease: {
- QMouseEvent *e = static_cast<QMouseEvent*>(event);
- if (d->layout->endSeparatorMove(e->pos())) {
- // We've released a separator, eat this event
- e->accept();
- return true;
- }
- break;
- }
-
-#endif
-
-#ifndef QT_NO_TOOLBAR
- case QEvent::ToolBarChange: {
- d->layout->toggleToolBarsVisible();
- return true;
- }
-#endif
-
-#ifndef QT_NO_STATUSTIP
- case QEvent::StatusTip:
-#ifndef QT_NO_STATUSBAR
- if (QStatusBar *sb = d->layout->statusBar())
- sb->showMessage(static_cast<QStatusTipEvent*>(event)->tip());
- else
-#endif
- static_cast<QStatusTipEvent*>(event)->ignore();
- return true;
-#endif // QT_NO_STATUSTIP
-
- case QEvent::StyleChange:
-#ifndef QT_NO_DOCKWIDGET
- d->layout->layoutState.dockAreaLayout.styleChangedEvent();
-#endif
- if (!d->explicitIconSize)
- setIconSize(QSize());
- break;
-#ifdef Q_WS_MAC
- case QEvent::Show:
- if (unifiedTitleAndToolBarOnMac())
- d->layout->syncUnifiedToolbarVisibility();
- d->layout->blockVisiblityCheck = false;
- break;
- case QEvent::WindowStateChange:
- {
- if (isHidden()) {
- // We are coming out of a minimize, leave things as is.
- d->layout->blockVisiblityCheck = true;
- }
-# ifdef QT_MAC_USE_COCOA
- // We need to update the HIToolbar status when we go out of or into fullscreen.
- QWindowStateChangeEvent *wce = static_cast<QWindowStateChangeEvent *>(event);
- if ((windowState() & Qt::WindowFullScreen) || (wce->oldState() & Qt::WindowFullScreen)) {
- d->layout->updateHIToolBarStatus();
- }
-# endif // Cocoa
- }
- break;
-#endif // Q_WS_MAC
-#if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_CURSOR)
- case QEvent::CursorChange:
- if (d->cursorAdjusted) {
- d->oldCursor = cursor();
- d->hasOldCursor = testAttribute(Qt::WA_SetCursor);
- }
- break;
-#endif
- default:
- break;
- }
-
- return QWidget::event(event);
-}
-
-#ifndef QT_NO_TOOLBAR
-
-/*!
- \property QMainWindow::unifiedTitleAndToolBarOnMac
- \brief whether the window uses the unified title and toolbar look on Mac OS X
- \since 4.3
-
- This property is false by default and only has any effect on Mac OS X 10.4 or higher.
-
- If set to true, then the top toolbar area is replaced with a Carbon HIToolbar
- or a Cocoa NSToolbar (depending on whether Qt was built with Carbon or Cocoa).
- All toolbars in the top toolbar area and any toolbars added afterwards are
- moved to that. This means a couple of things.
-
- \list
- \i QToolBars in this toolbar area are not movable and you cannot drag other
- toolbars to it
- \i Toolbar breaks are not respected or preserved
- \i Any custom widgets in the toolbar will not be shown if the toolbar
- becomes too small (only actions will be shown)
- \i Before Qt 4.5, if you called showFullScreen() on the main window, the QToolbar would
- disappear since it is considered to be part of the title bar. Qt 4.5 and up will now work around this by pulling
- the toolbars out and back into the regular toolbar and vice versa when you swap out.
- \endlist
-
- Setting this back to false will remove these restrictions.
-
- The Qt::WA_MacBrushedMetal attribute takes precedence over this property.
-*/
-void QMainWindow::setUnifiedTitleAndToolBarOnMac(bool set)
-{
-#ifdef Q_WS_MAC
- Q_D(QMainWindow);
- if (!isWindow() || d->useHIToolBar == set || QSysInfo::MacintoshVersion < QSysInfo::MV_10_3)
- return;
-
- d->useHIToolBar = set;
- createWinId(); // We need the hiview for down below.
-
-#ifdef QT_MAC_USE_COCOA
- // Activate the unified toolbar with the raster engine.
- if (windowSurface() && set) {
- d->layout->unifiedSurface = new QUnifiedToolbarSurface(this);
- }
-#endif // QT_MAC_USE_COCOA
-
- d->layout->updateHIToolBarStatus();
-
-#ifdef QT_MAC_USE_COCOA
- // Deactivate the unified toolbar with the raster engine.
- if (windowSurface() && !set) {
- if (d->layout->unifiedSurface) {
- delete d->layout->unifiedSurface;
- d->layout->unifiedSurface = 0;
- }
- }
-#endif // QT_MAC_USE_COCOA
-
- // Enabling the unified toolbar clears the opaque size grip setting, update it.
- d->macUpdateOpaqueSizeGrip();
-#else
- Q_UNUSED(set)
-#endif
-}
-
-bool QMainWindow::unifiedTitleAndToolBarOnMac() const
-{
-#ifdef Q_WS_MAC
- return d_func()->useHIToolBar && !testAttribute(Qt::WA_MacBrushedMetal) && !(windowFlags() & Qt::FramelessWindowHint);
-#endif
- return false;
-}
-
-#endif // QT_NO_TOOLBAR
-
-/*!
- \internal
-*/
-bool QMainWindow::isSeparator(const QPoint &pos) const
-{
-#ifndef QT_NO_DOCKWIDGET
- Q_D(const QMainWindow);
- return !d->layout->layoutState.dockAreaLayout.findSeparator(pos).isEmpty();
-#else
- Q_UNUSED(pos);
- return false;
-#endif
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \reimp
-*/
-void QMainWindow::contextMenuEvent(QContextMenuEvent *event)
-{
- event->ignore();
- // only show the context menu for direct QDockWidget and QToolBar
- // children and for the menu bar as well
- QWidget *child = childAt(event->pos());
- while (child && child != this) {
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar *>(child)) {
- if (mb->parentWidget() != this)
- return;
- break;
- }
-#endif
-#ifndef QT_NO_DOCKWIDGET
- if (QDockWidget *dw = qobject_cast<QDockWidget *>(child)) {
- if (dw->parentWidget() != this)
- return;
- if (dw->widget()
- && dw->widget()->geometry().contains(child->mapFrom(this, event->pos()))) {
- // ignore the event if the mouse is over the QDockWidget contents
- return;
- }
- break;
- }
-#endif // QT_NO_DOCKWIDGET
-#ifndef QT_NO_TOOLBAR
- if (QToolBar *tb = qobject_cast<QToolBar *>(child)) {
- if (tb->parentWidget() != this)
- return;
- break;
- }
-#endif
- child = child->parentWidget();
- }
- if (child == this)
- return;
-
-#ifndef QT_NO_MENU
- QMenu *popup = createPopupMenu();
- if (popup) {
- if (!popup->isEmpty()) {
- popup->setAttribute(Qt::WA_DeleteOnClose);
- popup->popup(event->globalPos());
- event->accept();
- } else {
- delete popup;
- }
- }
-#endif
-}
-#endif // QT_NO_CONTEXTMENU
-
-#ifndef QT_NO_MENU
-/*!
- Returns a popup menu containing checkable entries for the toolbars and
- dock widgets present in the main window. If there are no toolbars and
- dock widgets present, this function returns a null pointer.
-
- By default, this function is called by the main window when the user
- activates a context menu, typically by right-clicking on a toolbar or a dock
- widget.
-
- If you want to create a custom popup menu, reimplement this function and
- return a newly-created popup menu. Ownership of the popup menu is transferred
- to the caller.
-
- \sa addDockWidget(), addToolBar(), menuBar()
-*/
-QMenu *QMainWindow::createPopupMenu()
-{
- Q_D(QMainWindow);
- QMenu *menu = 0;
-#ifndef QT_NO_DOCKWIDGET
- QList<QDockWidget *> dockwidgets = findChildren<QDockWidget *>();
- if (dockwidgets.size()) {
- menu = new QMenu(this);
- for (int i = 0; i < dockwidgets.size(); ++i) {
- QDockWidget *dockWidget = dockwidgets.at(i);
- if (dockWidget->parentWidget() == this
- && !d->layout->layoutState.dockAreaLayout.indexOf(dockWidget).isEmpty()) {
- menu->addAction(dockwidgets.at(i)->toggleViewAction());
- }
- }
- menu->addSeparator();
- }
-#endif // QT_NO_DOCKWIDGET
-#ifndef QT_NO_TOOLBAR
- QList<QToolBar *> toolbars = findChildren<QToolBar *>();
- if (toolbars.size()) {
- if (!menu)
- menu = new QMenu(this);
- for (int i = 0; i < toolbars.size(); ++i) {
- QToolBar *toolBar = toolbars.at(i);
- if (toolBar->parentWidget() == this
- && (!d->layout->layoutState.toolBarAreaLayout.indexOf(toolBar).isEmpty()
- || (unifiedTitleAndToolBarOnMac()
- && toolBarArea(toolBar) == Qt::TopToolBarArea))) {
- menu->addAction(toolbars.at(i)->toggleViewAction());
- }
- }
- }
-#endif
- Q_UNUSED(d);
- return menu;
-}
-#endif // QT_NO_MENU
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_MAINWINDOW
diff --git a/src/gui/widgets/qmainwindow.h b/src/gui/widgets/qmainwindow.h
deleted file mode 100644
index 051ee57cf2..0000000000
--- a/src/gui/widgets/qmainwindow.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICMAINWINDOW_H
-#define QDYNAMICMAINWINDOW_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qtabwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_MAINWINDOW
-
-class QDockWidget;
-class QMainWindowPrivate;
-class QMenuBar;
-class QStatusBar;
-class QToolBar;
-class QMenu;
-
-class Q_GUI_EXPORT QMainWindow : public QWidget
-{
- Q_OBJECT
-
- Q_ENUMS(DockOption)
- Q_FLAGS(DockOptions)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
- Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle)
-#ifndef QT_NO_DOCKWIDGET
- Q_PROPERTY(bool animated READ isAnimated WRITE setAnimated)
-#ifndef QT_NO_TABBAR
- Q_PROPERTY(bool documentMode READ documentMode WRITE setDocumentMode)
-#endif // QT_NO_TABBAR
-#ifndef QT_NO_TABWIDGET
- Q_PROPERTY(QTabWidget::TabShape tabShape READ tabShape WRITE setTabShape)
-#endif // QT_NO_TABWIDGET
- Q_PROPERTY(bool dockNestingEnabled READ isDockNestingEnabled WRITE setDockNestingEnabled)
-#endif // QT_NO_DOCKWIDGET
- Q_PROPERTY(DockOptions dockOptions READ dockOptions WRITE setDockOptions)
-#ifndef QT_NO_TOOLBAR
- Q_PROPERTY(bool unifiedTitleAndToolBarOnMac READ unifiedTitleAndToolBarOnMac WRITE setUnifiedTitleAndToolBarOnMac)
-#endif
-
-public:
- enum DockOption {
- AnimatedDocks = 0x01,
- AllowNestedDocks = 0x02,
- AllowTabbedDocks = 0x04,
- ForceTabbedDocks = 0x08, // implies AllowTabbedDocks, !AllowNestedDocks
- VerticalTabs = 0x10 // implies AllowTabbedDocks
- };
- Q_DECLARE_FLAGS(DockOptions, DockOption)
-
- explicit QMainWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QMainWindow();
-
- QSize iconSize() const;
- void setIconSize(const QSize &iconSize);
-
- Qt::ToolButtonStyle toolButtonStyle() const;
- void setToolButtonStyle(Qt::ToolButtonStyle toolButtonStyle);
-
-#ifndef QT_NO_DOCKWIDGET
- bool isAnimated() const;
- bool isDockNestingEnabled() const;
-#endif
-
-#ifndef QT_NO_TABBAR
- bool documentMode() const;
- void setDocumentMode(bool enabled);
-#endif
-
-#ifndef QT_NO_TABWIDGET
- QTabWidget::TabShape tabShape() const;
- void setTabShape(QTabWidget::TabShape tabShape);
- QTabWidget::TabPosition tabPosition(Qt::DockWidgetArea area) const;
- void setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition);
-#endif // QT_NO_TABWIDGET
-
- void setDockOptions(DockOptions options);
- DockOptions dockOptions() const;
-
- bool isSeparator(const QPoint &pos) const;
-
-#ifndef QT_NO_MENUBAR
- QMenuBar *menuBar() const;
- void setMenuBar(QMenuBar *menubar);
-
- QWidget *menuWidget() const;
- void setMenuWidget(QWidget *menubar);
-#endif
-
-#ifndef QT_NO_STATUSBAR
- QStatusBar *statusBar() const;
- void setStatusBar(QStatusBar *statusbar);
-#endif
-
- QWidget *centralWidget() const;
- void setCentralWidget(QWidget *widget);
-
-#ifndef QT_NO_DOCKWIDGET
- void setCorner(Qt::Corner corner, Qt::DockWidgetArea area);
- Qt::DockWidgetArea corner(Qt::Corner corner) const;
-#endif
-
-#ifndef QT_NO_TOOLBAR
- void addToolBarBreak(Qt::ToolBarArea area = Qt::TopToolBarArea);
- void insertToolBarBreak(QToolBar *before);
-
- void addToolBar(Qt::ToolBarArea area, QToolBar *toolbar);
- void addToolBar(QToolBar *toolbar);
- QToolBar *addToolBar(const QString &title);
- void insertToolBar(QToolBar *before, QToolBar *toolbar);
- void removeToolBar(QToolBar *toolbar);
- void removeToolBarBreak(QToolBar *before);
-
- void setUnifiedTitleAndToolBarOnMac(bool set);
- bool unifiedTitleAndToolBarOnMac() const;
-
- Qt::ToolBarArea toolBarArea(QToolBar *toolbar) const;
- bool toolBarBreak(QToolBar *toolbar) const;
-#endif
-#ifndef QT_NO_DOCKWIDGET
- void addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget);
- void addDockWidget(Qt::DockWidgetArea area, QDockWidget *dockwidget,
- Qt::Orientation orientation);
- void splitDockWidget(QDockWidget *after, QDockWidget *dockwidget,
- Qt::Orientation orientation);
- void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
- QList<QDockWidget*> tabifiedDockWidgets(QDockWidget *dockwidget) const;
- void removeDockWidget(QDockWidget *dockwidget);
- bool restoreDockWidget(QDockWidget *dockwidget);
-
- Qt::DockWidgetArea dockWidgetArea(QDockWidget *dockwidget) const;
-#endif // QT_NO_DOCKWIDGET
-
- QByteArray saveState(int version = 0) const;
- bool restoreState(const QByteArray &state, int version = 0);
-
-#ifndef QT_NO_MENU
- virtual QMenu *createPopupMenu();
-#endif
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QMainWindow(QWidget *parent, const char *name, Qt::WindowFlags flags = 0);
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
-public Q_SLOTS:
- void setAnimated(bool enabled);
- void setDockNestingEnabled(bool enabled);
-#endif
-
-Q_SIGNALS:
- void iconSizeChanged(const QSize &iconSize);
- void toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle);
-
-protected:
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *event);
-#endif
- bool event(QEvent *event);
-
-private:
- Q_DECLARE_PRIVATE(QMainWindow)
- Q_DISABLE_COPY(QMainWindow)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QMainWindow::DockOptions)
-
-#endif // QT_NO_MAINWINDOW
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDYNAMICMAINWINDOW_H
diff --git a/src/gui/widgets/qmainwindowlayout.cpp b/src/gui/widgets/qmainwindowlayout.cpp
deleted file mode 100644
index d4afe075be..0000000000
--- a/src/gui/widgets/qmainwindowlayout.cpp
+++ /dev/null
@@ -1,2017 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmainwindowlayout_p.h"
-#include "qdockarealayout_p.h"
-
-#ifndef QT_NO_MAINWINDOW
-#include "qdockwidget.h"
-#include "qdockwidget_p.h"
-#include "qtoolbar_p.h"
-#include "qmainwindow.h"
-#include "qmainwindowlayout_p.h"
-#include "qtoolbar.h"
-#include "qtoolbarlayout_p.h"
-#include "qwidgetanimator_p.h"
-#include "qrubberband.h"
-#include "qdockwidget_p.h"
-#include "qtabbar_p.h"
-
-#include <qapplication.h>
-#include <qstatusbar.h>
-#include <qstring.h>
-#include <qstyle.h>
-#include <qvarlengtharray.h>
-#include <qstack.h>
-#include <qmap.h>
-#include <qtimer.h>
-
-#include <qdebug.h>
-
-#include <private/qapplication_p.h>
-#include <private/qlayoutengine_p.h>
-#ifdef Q_WS_MAC
-# include <private/qcore_mac_p.h>
-# include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#ifdef QT_NO_DOCKWIDGET
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-#endif
-
-#ifdef Q_DEBUG_MAINWINDOW_LAYOUT
-# include <QTextStream>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/******************************************************************************
-** debug
-*/
-
-#if defined(Q_DEBUG_MAINWINDOW_LAYOUT) && !defined(QT_NO_DOCKWIDGET)
-
-static QTextStream qout(stderr, QIODevice::WriteOnly);
-
-static void dumpLayout(QTextStream &qout, const QDockAreaLayoutInfo &layout, QString indent);
-
-static void dumpLayout(QTextStream &qout, const QDockAreaLayoutItem &item, QString indent)
-{
- qout << indent << "QDockAreaLayoutItem: "
- << "pos: " << item.pos << " size:" << item.size
- << " gap:" << (item.flags & QDockAreaLayoutItem::GapItem)
- << " keepSize:" << (item.flags & QDockAreaLayoutItem::KeepSize) << '\n';
- indent += QLatin1String(" ");
- if (item.widgetItem != 0) {
- qout << indent << "widget: "
- << item.widgetItem->widget()->metaObject()->className()
- << ' ' << item.widgetItem->widget()->windowTitle() << '\n';
- } else if (item.subinfo != 0) {
- qout << indent << "subinfo:\n";
- dumpLayout(qout, *item.subinfo, indent + QLatin1String(" "));
- } else if (item.placeHolderItem != 0) {
- QRect r = item.placeHolderItem->topLevelRect;
- qout << indent << "placeHolder: "
- << "pos: " << item.pos << " size:" << item.size
- << " gap:" << (item.flags & QDockAreaLayoutItem::GapItem)
- << " keepSize:" << (item.flags & QDockAreaLayoutItem::KeepSize)
- << " objectName:" << item.placeHolderItem->objectName
- << " hidden:" << item.placeHolderItem->hidden
- << " window:" << item.placeHolderItem->window
- << " rect:" << r.x() << ',' << r.y() << ' '
- << r.width() << 'x' << r.height() << '\n';
- }
- qout.flush();
-}
-
-static void dumpLayout(QTextStream &qout, const QDockAreaLayoutInfo &layout, QString indent)
-{
- qout << indent << "QDockAreaLayoutInfo: "
- << layout.rect.left() << ','
- << layout.rect.top() << ' '
- << layout.rect.width() << 'x'
- << layout.rect.height()
- << " orient:" << layout.o
- << " tabbed:" << layout.tabbed
- << " tbshape:" << layout.tabBarShape << '\n';
-
- indent += QLatin1String(" ");
-
- for (int i = 0; i < layout.item_list.count(); ++i) {
- qout << indent << "Item: " << i << '\n';
- dumpLayout(qout, layout.item_list.at(i), indent + QLatin1String(" "));
- }
- qout.flush();
-};
-
-static void dumpLayout(QTextStream &qout, const QDockAreaLayout &layout, QString indent)
-{
- qout << indent << "QDockAreaLayout: "
- << layout.rect.left() << ','
- << layout.rect.top() << ' '
- << layout.rect.width() << 'x'
- << layout.rect.height() << '\n';
-
- qout << indent << "TopDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::TopDock], indent + QLatin1String(" "));
- qout << indent << "LeftDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::LeftDock], indent + QLatin1String(" "));
- qout << indent << "RightDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::RightDock], indent + QLatin1String(" "));
- qout << indent << "BottomDockArea:\n";
- dumpLayout(qout, layout.docks[QInternal::BottomDock], indent + QLatin1String(" "));
-
- qout.flush();
-};
-
-void qt_dumpLayout(QTextStream &qout, QMainWindow *window)
-{
- QMainWindowLayout *layout = qt_mainwindow_layout(window);
- dumpLayout(qout, layout->layoutState.dockAreaLayout, QString());
-}
-
-#endif // Q_DEBUG_MAINWINDOW_LAYOUT && !QT_NO_DOCKWIDGET
-
-/******************************************************************************
-** QMainWindowLayoutState
-*/
-
-// we deal with all the #ifndefferry here so QMainWindowLayout code is clean
-
-QMainWindowLayoutState::QMainWindowLayoutState(QMainWindow *win)
- :
-#ifndef QT_NO_TOOLBAR
- toolBarAreaLayout(win),
-#endif
-#ifndef QT_NO_DOCKWIDGET
- dockAreaLayout(win)
-#else
- centralWidgetItem(0)
-#endif
-
-{
- mainWindow = win;
-}
-
-QSize QMainWindowLayoutState::sizeHint() const
-{
-
- QSize result(0, 0);
-
-#ifndef QT_NO_DOCKWIDGET
- result = dockAreaLayout.sizeHint();
-#else
- if (centralWidgetItem != 0)
- result = centralWidgetItem->sizeHint();
-#endif
-
-#ifndef QT_NO_TOOLBAR
- result = toolBarAreaLayout.sizeHint(result);
-#endif // QT_NO_TOOLBAR
-
- return result;
-}
-
-QSize QMainWindowLayoutState::minimumSize() const
-{
- QSize result(0, 0);
-
-#ifndef QT_NO_DOCKWIDGET
- result = dockAreaLayout.minimumSize();
-#else
- if (centralWidgetItem != 0)
- result = centralWidgetItem->minimumSize();
-#endif
-
-#ifndef QT_NO_TOOLBAR
- result = toolBarAreaLayout.minimumSize(result);
-#endif // QT_NO_TOOLBAR
-
- return result;
-}
-
-void QMainWindowLayoutState::apply(bool animated)
-{
-#ifndef QT_NO_TOOLBAR
- toolBarAreaLayout.apply(animated);
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
-// dumpLayout(dockAreaLayout, QString());
- dockAreaLayout.apply(animated);
-#else
- if (centralWidgetItem != 0) {
- QMainWindowLayout *layout = qt_mainwindow_layout(mainWindow);
- Q_ASSERT(layout != 0);
- layout->widgetAnimator.animate(centralWidgetItem->widget(), centralWidgetRect, animated);
- }
-#endif
-}
-
-void QMainWindowLayoutState::fitLayout()
-{
- QRect r;
-#ifdef QT_NO_TOOLBAR
- r = rect;
-#else
- toolBarAreaLayout.rect = rect;
- r = toolBarAreaLayout.fitLayout();
-#endif // QT_NO_TOOLBAR
-
-#ifndef QT_NO_DOCKWIDGET
- dockAreaLayout.rect = r;
- dockAreaLayout.fitLayout();
-#else
- centralWidgetRect = r;
-#endif
-}
-
-void QMainWindowLayoutState::deleteAllLayoutItems()
-{
-#ifndef QT_NO_TOOLBAR
- toolBarAreaLayout.deleteAllLayoutItems();
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- dockAreaLayout.deleteAllLayoutItems();
-#endif
-}
-
-void QMainWindowLayoutState::deleteCentralWidgetItem()
-{
-#ifndef QT_NO_DOCKWIDGET
- delete dockAreaLayout.centralWidgetItem;
- dockAreaLayout.centralWidgetItem = 0;
-#else
- delete centralWidgetItem;
- centralWidgetItem = 0;
-#endif
-}
-
-QLayoutItem *QMainWindowLayoutState::itemAt(int index, int *x) const
-{
-#ifndef QT_NO_TOOLBAR
- if (QLayoutItem *ret = toolBarAreaLayout.itemAt(x, index))
- return ret;
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (QLayoutItem *ret = dockAreaLayout.itemAt(x, index))
- return ret;
-#else
- if (centralWidgetItem != 0 && (*x)++ == index)
- return centralWidgetItem;
-#endif
-
- return 0;
-}
-
-QLayoutItem *QMainWindowLayoutState::takeAt(int index, int *x)
-{
-#ifndef QT_NO_TOOLBAR
- if (QLayoutItem *ret = toolBarAreaLayout.takeAt(x, index))
- return ret;
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (QLayoutItem *ret = dockAreaLayout.takeAt(x, index))
- return ret;
-#else
- if (centralWidgetItem != 0 && (*x)++ == index) {
- QLayoutItem *ret = centralWidgetItem;
- centralWidgetItem = 0;
- return ret;
- }
-#endif
-
- return 0;
-}
-
-QList<int> QMainWindowLayoutState::indexOf(QWidget *widget) const
-{
- QList<int> result;
-
-#ifndef QT_NO_TOOLBAR
- // is it a toolbar?
- if (QToolBar *toolBar = qobject_cast<QToolBar*>(widget)) {
- result = toolBarAreaLayout.indexOf(toolBar);
- if (!result.isEmpty())
- result.prepend(0);
- return result;
- }
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- // is it a dock widget?
- if (QDockWidget *dockWidget = qobject_cast<QDockWidget *>(widget)) {
- result = dockAreaLayout.indexOf(dockWidget);
- if (!result.isEmpty())
- result.prepend(1);
- return result;
- }
-#endif //QT_NO_DOCKWIDGET
-
- return result;
-}
-
-bool QMainWindowLayoutState::contains(QWidget *widget) const
-{
-#ifndef QT_NO_DOCKWIDGET
- if (dockAreaLayout.centralWidgetItem != 0 && dockAreaLayout.centralWidgetItem->widget() == widget)
- return true;
- if (!dockAreaLayout.indexOf(widget).isEmpty())
- return true;
-#else
- if (centralWidgetItem != 0 && centralWidgetItem->widget() == widget)
- return true;
-#endif
-
-#ifndef QT_NO_TOOLBAR
- if (!toolBarAreaLayout.indexOf(widget).isEmpty())
- return true;
-#endif
- return false;
-}
-
-void QMainWindowLayoutState::setCentralWidget(QWidget *widget)
-{
- QLayoutItem *item = 0;
- //make sure we remove the widget
- deleteCentralWidgetItem();
-
- if (widget != 0)
- item = new QWidgetItemV2(widget);
-
-#ifndef QT_NO_DOCKWIDGET
- dockAreaLayout.centralWidgetItem = item;
-#else
- centralWidgetItem = item;
-#endif
-}
-
-QWidget *QMainWindowLayoutState::centralWidget() const
-{
- QLayoutItem *item = 0;
-
-#ifndef QT_NO_DOCKWIDGET
- item = dockAreaLayout.centralWidgetItem;
-#else
- item = centralWidgetItem;
-#endif
-
- if (item != 0)
- return item->widget();
- return 0;
-}
-
-QList<int> QMainWindowLayoutState::gapIndex(QWidget *widget,
- const QPoint &pos) const
-{
- QList<int> result;
-
-#ifndef QT_NO_TOOLBAR
- // is it a toolbar?
- if (qobject_cast<QToolBar*>(widget) != 0) {
- result = toolBarAreaLayout.gapIndex(pos);
- if (!result.isEmpty())
- result.prepend(0);
- return result;
- }
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- // is it a dock widget?
- if (qobject_cast<QDockWidget *>(widget) != 0) {
- result = dockAreaLayout.gapIndex(pos);
- if (!result.isEmpty())
- result.prepend(1);
- return result;
- }
-#endif //QT_NO_DOCKWIDGET
-
- return result;
-}
-
-bool QMainWindowLayoutState::insertGap(const QList<int> &path, QLayoutItem *item)
-{
- if (path.isEmpty())
- return false;
-
- int i = path.first();
-
-#ifndef QT_NO_TOOLBAR
- if (i == 0) {
- Q_ASSERT(qobject_cast<QToolBar*>(item->widget()) != 0);
- return toolBarAreaLayout.insertGap(path.mid(1), item);
- }
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1) {
- Q_ASSERT(qobject_cast<QDockWidget*>(item->widget()) != 0);
- return dockAreaLayout.insertGap(path.mid(1), item);
- }
-#endif //QT_NO_DOCKWIDGET
-
- return false;
-}
-
-void QMainWindowLayoutState::remove(const QList<int> &path)
-{
- int i = path.first();
-
-#ifndef QT_NO_TOOLBAR
- if (i == 0)
- toolBarAreaLayout.remove(path.mid(1));
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1)
- dockAreaLayout.remove(path.mid(1));
-#endif //QT_NO_DOCKWIDGET
-}
-
-void QMainWindowLayoutState::remove(QLayoutItem *item)
-{
-#ifndef QT_NO_TOOLBAR
- toolBarAreaLayout.remove(item);
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- // is it a dock widget?
- if (QDockWidget *dockWidget = qobject_cast<QDockWidget *>(item->widget())) {
- QList<int> path = dockAreaLayout.indexOf(dockWidget);
- if (!path.isEmpty())
- dockAreaLayout.remove(path);
- }
-#endif //QT_NO_DOCKWIDGET
-}
-
-void QMainWindowLayoutState::clear()
-{
-#ifndef QT_NO_TOOLBAR
- toolBarAreaLayout.clear();
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- dockAreaLayout.clear();
-#else
- centralWidgetRect = QRect();
-#endif
-
- rect = QRect();
-}
-
-bool QMainWindowLayoutState::isValid() const
-{
- return rect.isValid();
-}
-
-QLayoutItem *QMainWindowLayoutState::item(const QList<int> &path)
-{
- int i = path.first();
-
-#ifndef QT_NO_TOOLBAR
- if (i == 0)
- return toolBarAreaLayout.item(path.mid(1)).widgetItem;
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1)
- return dockAreaLayout.item(path.mid(1)).widgetItem;
-#endif //QT_NO_DOCKWIDGET
-
- return 0;
-}
-
-QRect QMainWindowLayoutState::itemRect(const QList<int> &path) const
-{
- int i = path.first();
-
-#ifndef QT_NO_TOOLBAR
- if (i == 0)
- return toolBarAreaLayout.itemRect(path.mid(1));
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1)
- return dockAreaLayout.itemRect(path.mid(1));
-#endif //QT_NO_DOCKWIDGET
-
- return QRect();
-}
-
-QRect QMainWindowLayoutState::gapRect(const QList<int> &path) const
-{
- int i = path.first();
-
-#ifndef QT_NO_TOOLBAR
- if (i == 0)
- return toolBarAreaLayout.itemRect(path.mid(1));
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1)
- return dockAreaLayout.gapRect(path.mid(1));
-#endif //QT_NO_DOCKWIDGET
-
- return QRect();
-}
-
-QLayoutItem *QMainWindowLayoutState::plug(const QList<int> &path)
-{
- int i = path.first();
-
-#ifndef QT_NO_TOOLBAR
- if (i == 0)
- return toolBarAreaLayout.plug(path.mid(1));
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1)
- return dockAreaLayout.plug(path.mid(1));
-#endif //QT_NO_DOCKWIDGET
-
- return 0;
-}
-
-QLayoutItem *QMainWindowLayoutState::unplug(const QList<int> &path, QMainWindowLayoutState *other)
-{
- int i = path.first();
-
-#ifdef QT_NO_TOOLBAR
- Q_UNUSED(other);
-#else
- if (i == 0)
- return toolBarAreaLayout.unplug(path.mid(1), other ? &other->toolBarAreaLayout : 0);
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- if (i == 1)
- return dockAreaLayout.unplug(path.mid(1));
-#endif //QT_NO_DOCKWIDGET
-
- return 0;
-}
-
-void QMainWindowLayoutState::saveState(QDataStream &stream) const
-{
-#ifndef QT_NO_DOCKWIDGET
- dockAreaLayout.saveState(stream);
-#endif
-#ifndef QT_NO_TOOLBAR
- toolBarAreaLayout.saveState(stream);
-#endif
-}
-
-template <typename T>
-static QList<T> findChildrenHelper(const QObject *o)
-{
- const QObjectList &list = o->children();
- QList<T> result;
-
- for (int i=0; i < list.size(); ++i) {
- if (T t = qobject_cast<T>(list[i])) {
- result.append(t);
- }
- }
-
- return result;
-}
-
-//pre4.3 tests the format that was used before 4.3
-bool QMainWindowLayoutState::checkFormat(QDataStream &stream, bool pre43)
-{
-#ifdef QT_NO_TOOLBAR
- Q_UNUSED(pre43);
-#endif
- while (!stream.atEnd()) {
- uchar marker;
- stream >> marker;
- switch(marker)
- {
-#ifndef QT_NO_TOOLBAR
- case QToolBarAreaLayout::ToolBarStateMarker:
- case QToolBarAreaLayout::ToolBarStateMarkerEx:
- {
- QList<QToolBar *> toolBars = findChildrenHelper<QToolBar*>(mainWindow);
- if (!toolBarAreaLayout.restoreState(stream, toolBars, marker,
- pre43 /*testing 4.3 format*/, true /*testing*/)) {
- return false;
- }
- }
- break;
-#endif // QT_NO_TOOLBAR
-
-#ifndef QT_NO_DOCKWIDGET
- case QDockAreaLayout::DockWidgetStateMarker:
- {
- QList<QDockWidget *> dockWidgets = findChildrenHelper<QDockWidget*>(mainWindow);
- if (!dockAreaLayout.restoreState(stream, dockWidgets, true /*testing*/)) {
- return false;
- }
- }
- break;
-#endif
- default:
- //there was an error during the parsing
- return false;
- }// switch
- } //while
-
- //everything went fine: it must be a pre-4.3 saved state
- return true;
-}
-
-bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
- const QMainWindowLayoutState &oldState)
-{
- //make a copy of the data so that we can read it more than once
- QByteArray copy;
- while(!_stream.atEnd()) {
- int length = 1024;
- QByteArray ba(length, '\0');
- length = _stream.readRawData(ba.data(), ba.size());
- ba.resize(length);
- copy += ba;
- }
-
- QDataStream ds(copy);
- const bool oldFormat = !checkFormat(ds, false);
- if (oldFormat) {
- //we should try with the old format
- QDataStream ds2(copy);
- if (!checkFormat(ds2, true)) {
- return false; //format unknown
- }
- }
-
- QDataStream stream(copy);
-
- while (!stream.atEnd()) {
- uchar marker;
- stream >> marker;
- switch(marker)
- {
-#ifndef QT_NO_DOCKWIDGET
- case QDockAreaLayout::DockWidgetStateMarker:
- {
- QList<QDockWidget *> dockWidgets = findChildrenHelper<QDockWidget*>(mainWindow);
- if (!dockAreaLayout.restoreState(stream, dockWidgets))
- return false;
-
- for (int i = 0; i < dockWidgets.size(); ++i) {
- QDockWidget *w = dockWidgets.at(i);
- QList<int> path = dockAreaLayout.indexOf(w);
- if (path.isEmpty()) {
- QList<int> oldPath = oldState.dockAreaLayout.indexOf(w);
- if (oldPath.isEmpty()) {
- continue;
- }
- QDockAreaLayoutInfo *info = dockAreaLayout.info(oldPath);
- if (info == 0) {
- continue;
- }
- info->item_list.append(QDockAreaLayoutItem(new QDockWidgetItem(w)));
- }
- }
- }
- break;
-#endif // QT_NO_DOCKWIDGET
-
-#ifndef QT_NO_TOOLBAR
- case QToolBarAreaLayout::ToolBarStateMarker:
- case QToolBarAreaLayout::ToolBarStateMarkerEx:
- {
- QList<QToolBar *> toolBars = findChildrenHelper<QToolBar*>(mainWindow);
- if (!toolBarAreaLayout.restoreState(stream, toolBars, marker, oldFormat))
- return false;
-
- for (int i = 0; i < toolBars.size(); ++i) {
- QToolBar *w = toolBars.at(i);
- QList<int> path = toolBarAreaLayout.indexOf(w);
- if (path.isEmpty()) {
- QList<int> oldPath = oldState.toolBarAreaLayout.indexOf(w);
- if (oldPath.isEmpty()) {
- continue;
- }
- toolBarAreaLayout.docks[oldPath.at(0)].insertToolBar(0, w);
- }
- }
- }
- break;
-#endif //QT_NO_TOOLBAR
- default:
- return false;
- }// switch
- } //while
-
-
- return true;
-}
-
-/******************************************************************************
-** QMainWindowLayoutState - toolbars
-*/
-
-#ifndef QT_NO_TOOLBAR
-
-static inline void validateToolBarArea(Qt::ToolBarArea &area)
-{
- switch (area) {
- case Qt::LeftToolBarArea:
- case Qt::RightToolBarArea:
- case Qt::TopToolBarArea:
- case Qt::BottomToolBarArea:
- break;
- default:
- area = Qt::TopToolBarArea;
- }
-}
-
-static QInternal::DockPosition toDockPos(Qt::ToolBarArea area)
-{
- switch (area) {
- case Qt::LeftToolBarArea: return QInternal::LeftDock;
- case Qt::RightToolBarArea: return QInternal::RightDock;
- case Qt::TopToolBarArea: return QInternal::TopDock;
- case Qt::BottomToolBarArea: return QInternal::BottomDock;
- default:
- break;
- }
-
- return QInternal::DockCount;
-}
-
-static Qt::ToolBarArea toToolBarArea(QInternal::DockPosition pos)
-{
- switch (pos) {
- case QInternal::LeftDock: return Qt::LeftToolBarArea;
- case QInternal::RightDock: return Qt::RightToolBarArea;
- case QInternal::TopDock: return Qt::TopToolBarArea;
- case QInternal::BottomDock: return Qt::BottomToolBarArea;
- default: break;
- }
- return Qt::NoToolBarArea;
-}
-
-static inline Qt::ToolBarArea toToolBarArea(int pos)
-{
- return toToolBarArea(static_cast<QInternal::DockPosition>(pos));
-}
-
-void QMainWindowLayout::addToolBarBreak(Qt::ToolBarArea area)
-{
- validateToolBarArea(area);
-
- layoutState.toolBarAreaLayout.addToolBarBreak(toDockPos(area));
- if (savedState.isValid())
- savedState.toolBarAreaLayout.addToolBarBreak(toDockPos(area));
-
- invalidate();
-}
-
-void QMainWindowLayout::insertToolBarBreak(QToolBar *before)
-{
- layoutState.toolBarAreaLayout.insertToolBarBreak(before);
- if (savedState.isValid())
- savedState.toolBarAreaLayout.insertToolBarBreak(before);
- invalidate();
-}
-
-void QMainWindowLayout::removeToolBarBreak(QToolBar *before)
-{
- layoutState.toolBarAreaLayout.removeToolBarBreak(before);
- if (savedState.isValid())
- savedState.toolBarAreaLayout.removeToolBarBreak(before);
- invalidate();
-}
-
-void QMainWindowLayout::moveToolBar(QToolBar *toolbar, int pos)
-{
- layoutState.toolBarAreaLayout.moveToolBar(toolbar, pos);
- if (savedState.isValid())
- savedState.toolBarAreaLayout.moveToolBar(toolbar, pos);
- invalidate();
-}
-
-/* Removes the toolbar from the mainwindow so that it can be added again. Does not
- explicitly hide the toolbar. */
-void QMainWindowLayout::removeToolBar(QToolBar *toolbar)
-{
- if (toolbar) {
- QObject::disconnect(parentWidget(), SIGNAL(iconSizeChanged(QSize)),
- toolbar, SLOT(_q_updateIconSize(QSize)));
- QObject::disconnect(parentWidget(), SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
- toolbar, SLOT(_q_updateToolButtonStyle(Qt::ToolButtonStyle)));
-
-#ifdef Q_WS_MAC
- if (usesHIToolBar(toolbar)) {
- removeFromMacToolbar(toolbar);
- } else
-#endif // Q_WS_MAC
- {
- removeWidget(toolbar);
- }
- }
-}
-
-/*!
- Adds \a toolbar to \a area, continuing the current line.
-*/
-void QMainWindowLayout::addToolBar(Qt::ToolBarArea area,
- QToolBar *toolbar,
- bool)
-{
- validateToolBarArea(area);
-#ifdef Q_WS_MAC
- if ((area == Qt::TopToolBarArea)
- && layoutState.mainWindow->unifiedTitleAndToolBarOnMac()) {
- insertIntoMacToolbar(0, toolbar);
- } else
-#endif
- {
- //let's add the toolbar to the layout
- addChildWidget(toolbar);
- QLayoutItem * item = layoutState.toolBarAreaLayout.addToolBar(toDockPos(area), toolbar);
- if (savedState.isValid() && item) {
- // copy the toolbar also in the saved state
- savedState.toolBarAreaLayout.insertItem(toDockPos(area), item);
- }
- invalidate();
-
- //this ensures that the toolbar has the right window flags (not floating any more)
- toolbar->d_func()->updateWindowFlags(false /*floating*/);
- }
-}
-
-/*!
- Adds \a toolbar before \a before
-*/
-void QMainWindowLayout::insertToolBar(QToolBar *before, QToolBar *toolbar)
-{
-#ifdef Q_WS_MAC
- if (usesHIToolBar(before)) {
- insertIntoMacToolbar(before, toolbar);
- } else
-#endif // Q_WS_MAC
- {
- addChildWidget(toolbar);
- QLayoutItem * item = layoutState.toolBarAreaLayout.insertToolBar(before, toolbar);
- if (savedState.isValid() && item) {
- // copy the toolbar also in the saved state
- savedState.toolBarAreaLayout.insertItem(before, item);
- }
- if (!currentGapPos.isEmpty() && currentGapPos.first() == 0) {
- currentGapPos = layoutState.toolBarAreaLayout.currentGapIndex();
- if (!currentGapPos.isEmpty()) {
- currentGapPos.prepend(0);
- currentGapRect = layoutState.itemRect(currentGapPos);
- }
- }
- invalidate();
- }
-}
-
-Qt::ToolBarArea QMainWindowLayout::toolBarArea(QToolBar *toolbar) const
-{
- QInternal::DockPosition pos = layoutState.toolBarAreaLayout.findToolBar(toolbar);
- switch (pos) {
- case QInternal::LeftDock: return Qt::LeftToolBarArea;
- case QInternal::RightDock: return Qt::RightToolBarArea;
- case QInternal::TopDock: return Qt::TopToolBarArea;
- case QInternal::BottomDock: return Qt::BottomToolBarArea;
- default: break;
- }
-#ifdef Q_WS_MAC
- if (pos == QInternal::DockCount) {
- if (qtoolbarsInUnifiedToolbarList.contains(toolbar))
- return Qt::TopToolBarArea;
- }
-#endif
- return Qt::NoToolBarArea;
-}
-
-bool QMainWindowLayout::toolBarBreak(QToolBar *toolBar) const
-{
- return layoutState.toolBarAreaLayout.toolBarBreak(toolBar);
-}
-
-void QMainWindowLayout::getStyleOptionInfo(QStyleOptionToolBar *option, QToolBar *toolBar) const
-{
- option->toolBarArea = toolBarArea(toolBar);
- layoutState.toolBarAreaLayout.getStyleOptionInfo(option, toolBar);
-}
-
-void QMainWindowLayout::toggleToolBarsVisible()
-{
- bool updateNonUnifiedParts = true;
-#ifdef Q_WS_MAC
- if (layoutState.mainWindow->unifiedTitleAndToolBarOnMac()) {
- // If we hit this case, someone has pressed the "toolbar button" which will
- // toggle the unified toolbar visibility, because that's what the user wants.
- // We might be in a situation where someone has hidden all the toolbars
- // beforehand (maybe in construction), but now they've hit this button and
- // and are expecting the items to show. What do we do?
- // 1) Check the visibility of all the toolbars, if one is visible, do nothing, this
- // preserves what people would expect (these toolbars were visible when I clicked last time).
- // 2) If NONE are visible, then show them all. Again, this preserves the user expectation
- // of, "I want to see the toolbars." The user may get more toolbars than expected, but this
- // is better seeing nothing.
- // Don't worry about any of this if we are going invisible. This does mean we may get
- // into issues when switching into and out of fullscreen mode, but this is probably minor.
- // If we ever need to do hiding, that would have to be taken care of after the unified toolbar
- // has finished hiding.
- // People can of course handle the QEvent::ToolBarChange event themselves and do
- // WHATEVER they want if they don't like what we are doing (though the unified toolbar
- // will fire regardless).
-
- // Check if we REALLY need to update the geometry below. If we only have items in the
- // unified toolbar, all the docks will be empty, so there's very little point
- // in doing the geometry as Apple will do it (we also avoid flicker in Cocoa as well).
- // FWIW, layoutState.toolBarAreaLayout.visible and the state of the unified toolbar
- // visibility can get out of sync. I really don't think it's a big issue. It is kept
- // to a minimum because we only change the visibility if we absolutely must.
- // update the "non unified parts."
- updateNonUnifiedParts = !layoutState.toolBarAreaLayout.isEmpty();
-
- // We get this function before the unified toolbar does its thing.
- // So, the value will be opposite of what we expect.
- bool goingVisible = !macWindowToolbarIsVisible(qt_mac_window_for(layoutState.mainWindow));
- if (goingVisible) {
- const int ToolBarCount = qtoolbarsInUnifiedToolbarList.size();
- bool needAllVisible = true;
- for (int i = 0; i < ToolBarCount; ++i) {
- if (!qtoolbarsInUnifiedToolbarList.at(i)->isHidden()) {
- needAllVisible = false;
- break;
- }
- }
- if (needAllVisible) {
- QBoolBlocker blocker(blockVisiblityCheck); // Disable the visibilty check because
- // the toggle has already happened.
- for (int i = 0; i < ToolBarCount; ++i)
- qtoolbarsInUnifiedToolbarList.at(i)->setVisible(true);
- }
- }
- if (!updateNonUnifiedParts)
- layoutState.toolBarAreaLayout.visible = goingVisible;
- }
-#endif
- if (updateNonUnifiedParts) {
- layoutState.toolBarAreaLayout.visible = !layoutState.toolBarAreaLayout.visible;
- if (!layoutState.mainWindow->isMaximized()) {
- QPoint topLeft = parentWidget()->geometry().topLeft();
- QRect r = parentWidget()->geometry();
- r = layoutState.toolBarAreaLayout.rectHint(r);
- r.moveTo(topLeft);
- parentWidget()->setGeometry(r);
- } else {
- update();
- }
- }
-}
-
-#endif // QT_NO_TOOLBAR
-
-/******************************************************************************
-** QMainWindowLayoutState - dock areas
-*/
-
-#ifndef QT_NO_DOCKWIDGET
-
-static inline void validateDockWidgetArea(Qt::DockWidgetArea &area)
-{
- switch (area) {
- case Qt::LeftDockWidgetArea:
- case Qt::RightDockWidgetArea:
- case Qt::TopDockWidgetArea:
- case Qt::BottomDockWidgetArea:
- break;
- default:
- area = Qt::LeftDockWidgetArea;
- }
-}
-
-static QInternal::DockPosition toDockPos(Qt::DockWidgetArea area)
-{
- switch (area) {
- case Qt::LeftDockWidgetArea: return QInternal::LeftDock;
- case Qt::RightDockWidgetArea: return QInternal::RightDock;
- case Qt::TopDockWidgetArea: return QInternal::TopDock;
- case Qt::BottomDockWidgetArea: return QInternal::BottomDock;
- default:
- break;
- }
-
- return QInternal::DockCount;
-}
-
-static Qt::DockWidgetArea toDockWidgetArea(QInternal::DockPosition pos)
-{
- switch (pos) {
- case QInternal::LeftDock : return Qt::LeftDockWidgetArea;
- case QInternal::RightDock : return Qt::RightDockWidgetArea;
- case QInternal::TopDock : return Qt::TopDockWidgetArea;
- case QInternal::BottomDock : return Qt::BottomDockWidgetArea;
- default:
- break;
- }
-
- return Qt::NoDockWidgetArea;
-}
-
-inline static Qt::DockWidgetArea toDockWidgetArea(int pos)
-{
- return toDockWidgetArea(static_cast<QInternal::DockPosition>(pos));
-}
-
-void QMainWindowLayout::setCorner(Qt::Corner corner, Qt::DockWidgetArea area)
-{
- if (layoutState.dockAreaLayout.corners[corner] == area)
- return;
- layoutState.dockAreaLayout.corners[corner] = area;
- if (savedState.isValid())
- savedState.dockAreaLayout.corners[corner] = area;
- invalidate();
-}
-
-Qt::DockWidgetArea QMainWindowLayout::corner(Qt::Corner corner) const
-{
- return layoutState.dockAreaLayout.corners[corner];
-}
-
-void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
- QDockWidget *dockwidget,
- Qt::Orientation orientation)
-{
- addChildWidget(dockwidget);
-
- // If we are currently moving a separator, then we need to abort the move, since each
- // time we move the mouse layoutState is replaced by savedState modified by the move.
- if (!movingSeparator.isEmpty())
- endSeparatorMove(movingSeparatorPos);
-
- layoutState.dockAreaLayout.addDockWidget(toDockPos(area), dockwidget, orientation);
- emit dockwidget->dockLocationChanged(area);
- invalidate();
-}
-
-void QMainWindowLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
-{
- addChildWidget(second);
- layoutState.dockAreaLayout.tabifyDockWidget(first, second);
- emit second->dockLocationChanged(dockWidgetArea(first));
- invalidate();
-}
-
-bool QMainWindowLayout::restoreDockWidget(QDockWidget *dockwidget)
-{
- addChildWidget(dockwidget);
- if (!layoutState.dockAreaLayout.restoreDockWidget(dockwidget))
- return false;
- emit dockwidget->dockLocationChanged(dockWidgetArea(dockwidget));
- invalidate();
- return true;
-}
-
-#ifndef QT_NO_TABBAR
-bool QMainWindowLayout::documentMode() const
-{
- return _documentMode;
-}
-
-void QMainWindowLayout::setDocumentMode(bool enabled)
-{
- if (_documentMode == enabled)
- return;
-
- _documentMode = enabled;
-
- // Update the document mode for all tab bars
- foreach (QTabBar *bar, usedTabBars)
- bar->setDocumentMode(_documentMode);
- foreach (QTabBar *bar, unusedTabBars)
- bar->setDocumentMode(_documentMode);
-}
-#endif // QT_NO_TABBAR
-
-void QMainWindowLayout::setVerticalTabsEnabled(bool enabled)
-{
-#ifdef QT_NO_TABBAR
- Q_UNUSED(enabled);
-#else
- if (verticalTabsEnabled == enabled)
- return;
-
- verticalTabsEnabled = enabled;
-
- updateTabBarShapes();
-#endif // QT_NO_TABBAR
-}
-
-#ifndef QT_NO_TABWIDGET
-QTabWidget::TabShape QMainWindowLayout::tabShape() const
-{
- return _tabShape;
-}
-
-void QMainWindowLayout::setTabShape(QTabWidget::TabShape tabShape)
-{
- if (_tabShape == tabShape)
- return;
-
- _tabShape = tabShape;
-
- updateTabBarShapes();
-}
-
-QTabWidget::TabPosition QMainWindowLayout::tabPosition(Qt::DockWidgetArea area) const
-{
- return tabPositions[toDockPos(area)];
-}
-
-void QMainWindowLayout::setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition)
-{
- const Qt::DockWidgetArea dockWidgetAreas[] = {
- Qt::TopDockWidgetArea,
- Qt::LeftDockWidgetArea,
- Qt::BottomDockWidgetArea,
- Qt::RightDockWidgetArea
- };
- const QInternal::DockPosition dockPositions[] = {
- QInternal::TopDock,
- QInternal::LeftDock,
- QInternal::BottomDock,
- QInternal::RightDock
- };
-
- for (int i = 0; i < QInternal::DockCount; ++i)
- if (areas & dockWidgetAreas[i])
- tabPositions[dockPositions[i]] = tabPosition;
-
- updateTabBarShapes();
-}
-
-static inline QTabBar::Shape tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position)
-{
- const bool rounded = (shape == QTabWidget::Rounded);
- if (position == QTabWidget::North)
- return rounded ? QTabBar::RoundedNorth : QTabBar::TriangularNorth;
- if (position == QTabWidget::South)
- return rounded ? QTabBar::RoundedSouth : QTabBar::TriangularSouth;
- if (position == QTabWidget::East)
- return rounded ? QTabBar::RoundedEast : QTabBar::TriangularEast;
- if (position == QTabWidget::West)
- return rounded ? QTabBar::RoundedWest : QTabBar::TriangularWest;
- return QTabBar::RoundedNorth;
-}
-#endif // QT_NO_TABWIDGET
-
-#ifndef QT_NO_TABBAR
-void QMainWindowLayout::updateTabBarShapes()
-{
-#ifndef QT_NO_TABWIDGET
- const QTabWidget::TabPosition vertical[] = {
- QTabWidget::West,
- QTabWidget::East,
- QTabWidget::North,
- QTabWidget::South
- };
-#else
- const QTabBar::Shape vertical[] = {
- QTabBar::RoundedWest,
- QTabBar::RoundedEast,
- QTabBar::RoundedNorth,
- QTabBar::RoundedSouth
- };
-#endif
-
- QDockAreaLayout &layout = layoutState.dockAreaLayout;
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
-#ifndef QT_NO_TABWIDGET
- QTabWidget::TabPosition pos = verticalTabsEnabled ? vertical[i] : tabPositions[i];
- QTabBar::Shape shape = tabBarShapeFrom(_tabShape, pos);
-#else
- QTabBar::Shape shape = verticalTabsEnabled ? vertical[i] : QTabBar::RoundedSouth;
-#endif
- layout.docks[i].setTabBarShape(shape);
- }
-}
-#endif // QT_NO_TABBAR
-
-void QMainWindowLayout::splitDockWidget(QDockWidget *after,
- QDockWidget *dockwidget,
- Qt::Orientation orientation)
-{
- addChildWidget(dockwidget);
- layoutState.dockAreaLayout.splitDockWidget(after, dockwidget, orientation);
- emit dockwidget->dockLocationChanged(dockWidgetArea(after));
- invalidate();
-}
-
-Qt::DockWidgetArea QMainWindowLayout::dockWidgetArea(QDockWidget *widget) const
-{
- QList<int> pathToWidget = layoutState.dockAreaLayout.indexOf(widget);
- if (pathToWidget.isEmpty())
- return Qt::NoDockWidgetArea;
- return toDockWidgetArea(pathToWidget.first());
-}
-
-void QMainWindowLayout::keepSize(QDockWidget *w)
-{
- layoutState.dockAreaLayout.keepSize(w);
-}
-
-#ifndef QT_NO_TABBAR
-
-class QMainWindowTabBar : public QTabBar
-{
-public:
- QMainWindowTabBar(QWidget *parent);
-protected:
- bool event(QEvent *e);
-};
-
-QMainWindowTabBar::QMainWindowTabBar(QWidget *parent)
- : QTabBar(parent)
-{
- setExpanding(false);
-}
-
-bool QMainWindowTabBar::event(QEvent *e)
-{
- // show the tooltip if tab is too small to fit label
-
- if (e->type() != QEvent::ToolTip)
- return QTabBar::event(e);
- QSize size = this->size();
- QSize hint = sizeHint();
- if (shape() == QTabBar::RoundedWest || shape() == QTabBar::RoundedEast) {
- size.transpose();
- hint.transpose();
- }
- if (size.width() < hint.width())
- return QTabBar::event(e);
- e->accept();
- return true;
-}
-
-QTabBar *QMainWindowLayout::getTabBar()
-{
- QTabBar *result = 0;
- if (!unusedTabBars.isEmpty()) {
- result = unusedTabBars.takeLast();
- } else {
- result = new QMainWindowTabBar(parentWidget());
- result->setDrawBase(true);
- result->setElideMode(Qt::ElideRight);
- result->setDocumentMode(_documentMode);
- connect(result, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()));
- }
-
- usedTabBars.insert(result);
- return result;
-}
-
-// Allocates a new separator widget if needed
-QWidget *QMainWindowLayout::getSeparatorWidget()
-{
- QWidget *result = 0;
- if (!unusedSeparatorWidgets.isEmpty()) {
- result = unusedSeparatorWidgets.takeLast();
- } else {
- result = new QWidget(parentWidget());
- result->setAttribute(Qt::WA_MouseNoMask, true);
- result->setAutoFillBackground(false);
- result->setObjectName(QLatin1String("qt_qmainwindow_extended_splitter"));
- }
- usedSeparatorWidgets.insert(result);
- return result;
-}
-
-void QMainWindowLayout::tabChanged()
-{
- QTabBar *tb = qobject_cast<QTabBar*>(sender());
- if (tb == 0)
- return;
- QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(tb);
- if (info == 0)
- return;
- info->apply(false);
-
- if (QWidget *w = centralWidget())
- w->raise();
-}
-#endif // QT_NO_TABBAR
-
-bool QMainWindowLayout::startSeparatorMove(const QPoint &pos)
-{
- movingSeparator = layoutState.dockAreaLayout.findSeparator(pos);
-
- if (movingSeparator.isEmpty())
- return false;
-
- savedState = layoutState;
- movingSeparatorPos = movingSeparatorOrigin = pos;
-
- return true;
-}
-
-bool QMainWindowLayout::separatorMove(const QPoint &pos)
-{
- if (movingSeparator.isEmpty())
- return false;
- movingSeparatorPos = pos;
- separatorMoveTimer.start(0, this);
- return true;
-}
-
-bool QMainWindowLayout::endSeparatorMove(const QPoint&)
-{
- bool result = !movingSeparator.isEmpty();
- movingSeparator.clear();
- savedState.clear();
- return result;
-}
-
-void QMainWindowLayout::raise(QDockWidget *widget)
-{
- QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(widget);
- if (info == 0)
- return;
-#ifndef QT_NO_TABBAR
- if (!info->tabbed)
- return;
- info->setCurrentTab(widget);
-#endif
-}
-
-#endif // QT_NO_DOCKWIDGET
-
-
-/******************************************************************************
-** QMainWindowLayoutState - layout interface
-*/
-
-int QMainWindowLayout::count() const
-{
- qWarning("QMainWindowLayout::count: ?");
- return 0; //#################################################
-}
-
-QLayoutItem *QMainWindowLayout::itemAt(int index) const
-{
- int x = 0;
-
- if (QLayoutItem *ret = layoutState.itemAt(index, &x))
- return ret;
-
- if (statusbar && x++ == index)
- return statusbar;
-
- return 0;
-}
-
-QLayoutItem *QMainWindowLayout::takeAt(int index)
-{
- int x = 0;
-
- if (QLayoutItem *ret = layoutState.takeAt(index, &x)) {
- // the widget might in fact have been destroyed by now
- if (QWidget *w = ret->widget()) {
- widgetAnimator.abort(w);
- if (w == pluggingWidget)
- pluggingWidget = 0;
- }
-
- if (savedState.isValid() ) {
- //we need to remove the item also from the saved state to prevent crash
- savedState.remove(ret);
- //Also, the item may be contained several times as a gap item.
- layoutState.remove(ret);
- }
-
-#ifndef QT_NO_TOOLBAR
- if (!currentGapPos.isEmpty() && currentGapPos.first() == 0) {
- currentGapPos = layoutState.toolBarAreaLayout.currentGapIndex();
- if (!currentGapPos.isEmpty()) {
- currentGapPos.prepend(0);
- currentGapRect = layoutState.itemRect(currentGapPos);
- }
- }
-#endif
-
- return ret;
- }
-
- if (statusbar && x++ == index) {
- QLayoutItem *ret = statusbar;
- statusbar = 0;
- return ret;
- }
-
- return 0;
-}
-
-void QMainWindowLayout::setGeometry(const QRect &_r)
-{
- if (savedState.isValid())
- return;
-
- QRect r = _r;
-
- QLayout::setGeometry(r);
-
- if (statusbar) {
- QRect sbr(QPoint(0, 0),
- QSize(r.width(), statusbar->heightForWidth(r.width()))
- .expandedTo(statusbar->minimumSize()));
- sbr.moveBottom(r.bottom());
- QRect vr = QStyle::visualRect(parentWidget()->layoutDirection(), _r, sbr);
- statusbar->setGeometry(vr);
- r.setBottom(sbr.top() - 1);
- }
-
- layoutState.rect = r;
- layoutState.fitLayout();
- applyState(layoutState, false);
-}
-
-void QMainWindowLayout::addItem(QLayoutItem *)
-{ qWarning("QMainWindowLayout::addItem: Please use the public QMainWindow API instead"); }
-
-QSize QMainWindowLayout::sizeHint() const
-{
- if (!szHint.isValid()) {
- szHint = layoutState.sizeHint();
- const QSize sbHint = statusbar ? statusbar->sizeHint() : QSize(0, 0);
- szHint = QSize(qMax(sbHint.width(), szHint.width()),
- sbHint.height() + szHint.height());
- }
- return szHint;
-}
-
-QSize QMainWindowLayout::minimumSize() const
-{
- if (!minSize.isValid()) {
- minSize = layoutState.minimumSize();
- const QSize sbMin = statusbar ? statusbar->minimumSize() : QSize(0, 0);
- minSize = QSize(qMax(sbMin.width(), minSize.width()),
- sbMin.height() + minSize.height());
-#ifdef Q_WS_MAC
- const QSize storedSize = minSize;
- int minWidth = 0;
- foreach (QToolBar *toolbar, qtoolbarsInUnifiedToolbarList) {
- minWidth += toolbar->sizeHint().width() + 20;
- }
- minSize = QSize(qMax(minWidth, storedSize.width()), storedSize.height());
-#endif
- }
- return minSize;
-}
-
-void QMainWindowLayout::invalidate()
-{
- QLayout::invalidate();
- minSize = szHint = QSize();
-}
-
-/******************************************************************************
-** QMainWindowLayout - remaining stuff
-*/
-
-static void fixToolBarOrientation(QLayoutItem *item, int dockPos)
-{
-#ifndef QT_NO_TOOLBAR
- QToolBar *toolBar = qobject_cast<QToolBar*>(item->widget());
- if (toolBar == 0)
- return;
-
- QRect oldGeo = toolBar->geometry();
-
- QInternal::DockPosition pos
- = static_cast<QInternal::DockPosition>(dockPos);
- Qt::Orientation o = pos == QInternal::TopDock || pos == QInternal::BottomDock
- ? Qt::Horizontal : Qt::Vertical;
- if (o != toolBar->orientation())
- toolBar->setOrientation(o);
-
- QSize hint = toolBar->sizeHint().boundedTo(toolBar->maximumSize())
- .expandedTo(toolBar->minimumSize());
-
- if (toolBar->size() != hint) {
- QRect newGeo(oldGeo.topLeft(), hint);
- if (toolBar->layoutDirection() == Qt::RightToLeft)
- newGeo.moveRight(oldGeo.right());
- toolBar->setGeometry(newGeo);
- }
-
-#else
- Q_UNUSED(item);
- Q_UNUSED(dockPos);
-#endif
-}
-
-void QMainWindowLayout::revert(QLayoutItem *widgetItem)
-{
- if (!savedState.isValid())
- return;
-
- QWidget *widget = widgetItem->widget();
- layoutState = savedState;
- currentGapPos = layoutState.indexOf(widget);
- fixToolBarOrientation(widgetItem, currentGapPos.at(1));
- layoutState.unplug(currentGapPos);
- layoutState.fitLayout();
- currentGapRect = layoutState.itemRect(currentGapPos);
-
- plug(widgetItem);
-}
-
-bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
-{
- if (!parentWidget()->isVisible() || parentWidget()->isMinimized() || currentGapPos.isEmpty())
- return false;
-
- fixToolBarOrientation(widgetItem, currentGapPos.at(1));
-
- QWidget *widget = widgetItem->widget();
-
- QList<int> previousPath = layoutState.indexOf(widget);
-
- QLayoutItem *it = layoutState.plug(currentGapPos);
- Q_ASSERT(it == widgetItem);
- Q_UNUSED(it);
- if (!previousPath.isEmpty())
- layoutState.remove(previousPath);
-
- pluggingWidget = widget;
- QRect globalRect = currentGapRect;
- globalRect.moveTopLeft(parentWidget()->mapToGlobal(globalRect.topLeft()));
-#ifndef QT_NO_DOCKWIDGET
- if (qobject_cast<QDockWidget*>(widget) != 0) {
- QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(widget->layout());
- if (layout->nativeWindowDeco()) {
- globalRect.adjust(0, layout->titleHeight(), 0, 0);
- } else {
- int fw = widget->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, widget);
- globalRect.adjust(-fw, -fw, fw, fw);
- }
- }
-#endif
- widgetAnimator.animate(widget, globalRect, dockOptions & QMainWindow::AnimatedDocks);
-
- return true;
-}
-
-void QMainWindowLayout::animationFinished(QWidget *widget)
-{
- //this function is called from within the Widget Animator whenever an animation is finished
- //on a certain widget
-#ifndef QT_NO_TOOLBAR
- if (QToolBar *tb = qobject_cast<QToolBar*>(widget)) {
- QToolBarLayout *tbl = qobject_cast<QToolBarLayout*>(tb->layout());
- if (tbl->animating) {
- tbl->animating = false;
- if (tbl->expanded)
- tbl->layoutActions(tb->size());
- tb->update();
- }
- }
-#endif
-
- if (widget == pluggingWidget) {
-
-#ifndef QT_NO_DOCKWIDGET
- if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget))
- dw->d_func()->plug(currentGapRect);
-#endif
-#ifndef QT_NO_TOOLBAR
- if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
- tb->d_func()->plug(currentGapRect);
-#endif
-
- savedState.clear();
- currentGapPos.clear();
- pluggingWidget = 0;
- //applying the state will make sure that the currentGap is updated correctly
- //and all the geometries (especially the one from the central widget) is correct
- layoutState.apply(false);
-
-#ifndef QT_NO_DOCKWIDGET
-#ifndef QT_NO_TABBAR
- if (qobject_cast<QDockWidget*>(widget) != 0) {
- // info() might return null if the widget is destroyed while
- // animating but before the animationFinished signal is received.
- if (QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(widget))
- info->setCurrentTab(widget);
- }
-#endif
-#endif
- }
-
- if (!widgetAnimator.animating()) {
- //all animations are finished
-#ifndef QT_NO_DOCKWIDGET
- parentWidget()->update(layoutState.dockAreaLayout.separatorRegion());
-#ifndef QT_NO_TABBAR
- foreach (QTabBar *tab_bar, usedTabBars)
- tab_bar->show();
-#endif // QT_NO_TABBAR
-#endif // QT_NO_DOCKWIDGET
- }
-
- updateGapIndicator();
-}
-
-void QMainWindowLayout::restore(bool keepSavedState)
-{
- if (!savedState.isValid())
- return;
-
- layoutState = savedState;
- applyState(layoutState);
- if (!keepSavedState)
- savedState.clear();
- currentGapPos.clear();
- pluggingWidget = 0;
- updateGapIndicator();
-}
-
-QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLayout)
- : QLayout(parentLayout ? static_cast<QWidget *>(0) : mainwindow)
- , layoutState(mainwindow)
- , savedState(mainwindow)
- , dockOptions(QMainWindow::AnimatedDocks | QMainWindow::AllowTabbedDocks)
- , statusbar(0)
-#ifndef QT_NO_DOCKWIDGET
-#ifndef QT_NO_TABBAR
- , _documentMode(false)
- , verticalTabsEnabled(false)
-#ifndef QT_NO_TABWIDGET
- , _tabShape(QTabWidget::Rounded)
-#endif
-#endif
-#endif // QT_NO_DOCKWIDGET
- , widgetAnimator(this)
- , pluggingWidget(0)
-#ifndef QT_NO_RUBBERBAND
- , gapIndicator(new QRubberBand(QRubberBand::Rectangle, mainwindow))
-#endif //QT_NO_RUBBERBAND
-#ifdef Q_WS_MAC
- , blockVisiblityCheck(false)
-#endif
-{
- if (parentLayout)
- setParent(parentLayout);
-
-#ifndef QT_NO_DOCKWIDGET
-#ifndef QT_NO_TABBAR
- sep = mainwindow->style()->pixelMetric(QStyle::PM_DockWidgetSeparatorExtent, 0, mainwindow);
-#endif
-
-#ifndef QT_NO_TABWIDGET
- for (int i = 0; i < QInternal::DockCount; ++i)
- tabPositions[i] = QTabWidget::South;
-#endif
-#endif // QT_NO_DOCKWIDGET
-
-#ifndef QT_NO_RUBBERBAND
- // For accessibility to identify this special widget.
- gapIndicator->setObjectName(QLatin1String("qt_rubberband"));
- gapIndicator->hide();
-#endif
- pluggingWidget = 0;
-
- setObjectName(mainwindow->objectName() + QLatin1String("_layout"));
-}
-
-QMainWindowLayout::~QMainWindowLayout()
-{
- layoutState.deleteAllLayoutItems();
- layoutState.deleteCentralWidgetItem();
-
-#ifdef Q_WS_MAC
- cleanUpMacToolbarItems();
-#endif
-
- delete statusbar;
-}
-
-void QMainWindowLayout::setDockOptions(QMainWindow::DockOptions opts)
-{
- if (opts == dockOptions)
- return;
-
- dockOptions = opts;
-
-#ifndef QT_NO_DOCKWIDGET
- setVerticalTabsEnabled(opts & QMainWindow::VerticalTabs);
-#endif
-
- invalidate();
-}
-
-#ifndef QT_NO_STATUSBAR
-QStatusBar *QMainWindowLayout::statusBar() const
-{ return statusbar ? qobject_cast<QStatusBar *>(statusbar->widget()) : 0; }
-
-void QMainWindowLayout::setStatusBar(QStatusBar *sb)
-{
- if (sb)
- addChildWidget(sb);
- delete statusbar;
- statusbar = sb ? new QWidgetItemV2(sb) : 0;
- invalidate();
-}
-#endif // QT_NO_STATUSBAR
-
-QWidget *QMainWindowLayout::centralWidget() const
-{
- return layoutState.centralWidget();
-}
-
-void QMainWindowLayout::setCentralWidget(QWidget *widget)
-{
- if (widget != 0)
- addChildWidget(widget);
- layoutState.setCentralWidget(widget);
- if (savedState.isValid()) {
-#ifndef QT_NO_DOCKWIDGET
- savedState.dockAreaLayout.centralWidgetItem = layoutState.dockAreaLayout.centralWidgetItem;
- savedState.dockAreaLayout.fallbackToSizeHints = true;
-#else
- savedState.centralWidgetItem = layoutState.centralWidgetItem;
-#endif
- }
- invalidate();
-}
-
-QLayoutItem *QMainWindowLayout::unplug(QWidget *widget)
-{
- QList<int> path = layoutState.indexOf(widget);
- if (path.isEmpty())
- return 0;
-
- QLayoutItem *item = layoutState.item(path);
- if (widget->isWindow())
- return item;
-
- QRect r = layoutState.itemRect(path);
- savedState = layoutState;
-
-#ifndef QT_NO_DOCKWIDGET
- if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
- dw->d_func()->unplug(r);
- }
-#endif
-#ifndef QT_NO_TOOLBAR
- if (QToolBar *tb = qobject_cast<QToolBar*>(widget)) {
- tb->d_func()->unplug(r);
- }
-#endif
-
-
- layoutState.unplug(path ,&savedState);
- savedState.fitLayout();
- currentGapPos = path;
- currentGapRect = r;
- updateGapIndicator();
-
- fixToolBarOrientation(item, currentGapPos.at(1));
-
- return item;
-}
-
-void QMainWindowLayout::updateGapIndicator()
-{
-#ifndef QT_NO_RUBBERBAND
- gapIndicator->setVisible(!widgetAnimator.animating() && !currentGapPos.isEmpty());
- gapIndicator->setGeometry(currentGapRect);
-#endif
-}
-
-QList<int> QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
-{
- if (!parentWidget()->isVisible() || parentWidget()->isMinimized()
- || pluggingWidget != 0 || widgetItem == 0)
- return QList<int>();
-
- QWidget *widget = widgetItem->widget();
- QPoint pos = parentWidget()->mapFromGlobal(mousePos);
-
- if (!savedState.isValid())
- savedState = layoutState;
-
- QList<int> path = savedState.gapIndex(widget, pos);
-
- if (!path.isEmpty()) {
- bool allowed = false;
-
-#ifndef QT_NO_DOCKWIDGET
- if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget))
- allowed = dw->isAreaAllowed(toDockWidgetArea(path.at(1)));
-#endif
-#ifndef QT_NO_TOOLBAR
- if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
- allowed = tb->isAreaAllowed(toToolBarArea(path.at(1)));
-#endif
-
- if (!allowed)
- path.clear();
- }
-
- if (path == currentGapPos)
- return currentGapPos; // the gap is already there
-
- currentGapPos = path;
- if (path.isEmpty()) {
- fixToolBarOrientation(widgetItem, 2); // 2 = top dock, ie. horizontal
- restore(true);
- return QList<int>();
- }
-
- fixToolBarOrientation(widgetItem, currentGapPos.at(1));
-
- QMainWindowLayoutState newState = savedState;
-
- if (!newState.insertGap(path, widgetItem)) {
- restore(true); // not enough space
- return QList<int>();
- }
-
- QSize min = newState.minimumSize();
- QSize size = newState.rect.size();
-
- if (min.width() > size.width() || min.height() > size.height()) {
- restore(true);
- return QList<int>();
- }
-
- newState.fitLayout();
-
- currentGapRect = newState.gapRect(currentGapPos);
-
-#ifndef QT_NO_DOCKWIDGET
- parentWidget()->update(layoutState.dockAreaLayout.separatorRegion());
-#endif
- layoutState = newState;
- applyState(layoutState);
-
- updateGapIndicator();
-
- return path;
-}
-
-void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animate)
-{
-#ifndef QT_NO_DOCKWIDGET
-#ifndef QT_NO_TABBAR
- QSet<QTabBar*> used = newState.dockAreaLayout.usedTabBars();
- QSet<QTabBar*> retired = usedTabBars - used;
- usedTabBars = used;
- foreach (QTabBar *tab_bar, retired) {
- tab_bar->hide();
- while (tab_bar->count() > 0)
- tab_bar->removeTab(0);
- unusedTabBars.append(tab_bar);
- }
-
- if (sep == 1) {
- QSet<QWidget*> usedSeps = newState.dockAreaLayout.usedSeparatorWidgets();
- QSet<QWidget*> retiredSeps = usedSeparatorWidgets - usedSeps;
- usedSeparatorWidgets = usedSeps;
- foreach (QWidget *sepWidget, retiredSeps) {
- unusedSeparatorWidgets.append(sepWidget);
- }
- }
-
-
-#endif // QT_NO_TABBAR
-#endif // QT_NO_DOCKWIDGET
- newState.apply(dockOptions & QMainWindow::AnimatedDocks && animate);
-}
-
-void QMainWindowLayout::saveState(QDataStream &stream) const
-{
- layoutState.saveState(stream);
-}
-
-bool QMainWindowLayout::restoreState(QDataStream &stream)
-{
- savedState = layoutState;
- layoutState.clear();
- layoutState.rect = savedState.rect;
-
- if (!layoutState.restoreState(stream, savedState)) {
- layoutState.deleteAllLayoutItems();
- layoutState = savedState;
- if (parentWidget()->isVisible())
- applyState(layoutState, false); // hides tabBars allocated by newState
- return false;
- }
-
- if (parentWidget()->isVisible()) {
- layoutState.fitLayout();
- applyState(layoutState, false);
- }
-
- savedState.deleteAllLayoutItems();
- savedState.clear();
-
-#ifndef QT_NO_DOCKWIDGET
- if (parentWidget()->isVisible()) {
-#ifndef QT_NO_TABBAR
- foreach (QTabBar *tab_bar, usedTabBars)
- tab_bar->show();
-
-#endif
- }
-#endif // QT_NO_DOCKWIDGET
-
- return true;
-}
-
-
-// Returns if this toolbar *should* be using HIToolbar. Won't work for all in between cases
-// for example, you have a toolbar in the top area and then you suddenly turn on
-// HIToolbar.
-bool QMainWindowLayout::usesHIToolBar(QToolBar *toolbar) const
-{
-#ifndef Q_WS_MAC
- Q_UNUSED(toolbar);
- return false;
-#else
- return qtoolbarsInUnifiedToolbarList.contains(toolbar)
- || ((toolBarArea(toolbar) == Qt::TopToolBarArea)
- && layoutState.mainWindow->unifiedTitleAndToolBarOnMac());
-#endif
-}
-
-void QMainWindowLayout::timerEvent(QTimerEvent *e)
-{
-#ifndef QT_NO_DOCKWIDGET
- if (e->timerId() == separatorMoveTimer.timerId()) {
- //let's move the separators
- separatorMoveTimer.stop();
- if (movingSeparator.isEmpty())
- return;
- if (movingSeparatorOrigin == movingSeparatorPos)
- return;
-
- //when moving the separator, we need to update the previous position
- parentWidget()->update(layoutState.dockAreaLayout.separatorRegion());
-
- layoutState = savedState;
- layoutState.dockAreaLayout.separatorMove(movingSeparator, movingSeparatorOrigin,
- movingSeparatorPos);
- movingSeparatorPos = movingSeparatorOrigin;
- }
-#endif
- QLayout::timerEvent(e);
-}
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_MAINWINDOW
diff --git a/src/gui/widgets/qmainwindowlayout_mac.mm b/src/gui/widgets/qmainwindowlayout_mac.mm
deleted file mode 100644
index 761a4337e1..0000000000
--- a/src/gui/widgets/qmainwindowlayout_mac.mm
+++ /dev/null
@@ -1,607 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qmainwindowlayout_p.h>
-#include <qtoolbar.h>
-#include <private/qtoolbarlayout_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <private/qtoolbar_p.h>
-
-#ifndef QT_MAC_USE_COCOA
-#include <Carbon/Carbon.h>
-#else
-#include <private/qcocoatoolbardelegate_mac_p.h>
-#import <private/qcocoawindowdelegate_mac_p.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-#ifdef QT_NAMESPACE
-
-// namespace up the stuff
-#define SS(x) #x
-#define S0(x) SS(x)
-#define S "com.trolltech.qt-" S0(QT_NAMESPACE) ".qmainwindow.qtoolbarInHIToolbar"
-#define SToolbar "com.trolltech.qt-" S0(QT_NAMESPACE) ".hitoolbar-qtoolbar"
-#define SNSToolbar "com.trolltech.qt-" S0(QT_NAMESPACE) ".qtoolbarInNSToolbar"
-#define MacToolbar "com.trolltech.qt-" S0(QT_NAMESPACE) ".qmainwindow.mactoolbar"
-
-#ifndef QT_MAC_USE_COCOA
-static CFStringRef kQToolBarHIToolbarItemClassID = CFSTR(S);
-static CFStringRef kQToolBarHIToolbarIdentifier = CFSTR(SToolbar);
-#else
-static NSString *kQToolBarNSToolbarIdentifier = @SNSToolbar;
-#endif
-static CFStringRef kQMainWindowMacToolbarID = CFSTR(MacToolbar);
-#undef SS
-#undef S0
-#undef S
-#undef SToolbar
-#undef SNSToolbar
-#undef MacToolbar
-
-#else
-#ifndef QT_MAC_USE_COCOA
-static CFStringRef kQToolBarHIToolbarItemClassID = CFSTR("com.trolltech.qt.qmainwindow.qtoolbarInHIToolbar");
-static CFStringRef kQToolBarHIToolbarIdentifier = CFSTR("com.trolltech.qt.hitoolbar-qtoolbar");
-#else
-static NSString *kQToolBarNSToolbarIdentifier = @"com.trolltech.qt.qmainwindow.qtoolbarInNSToolbar";
-#endif
-static CFStringRef kQMainWindowMacToolbarID = CFSTR("com.trolltech.qt.qmainwindow.mactoolbar");
-#endif // QT_NAMESPACE
-
-#ifndef QT_MAC_USE_COCOA
-
-static const int kEventParamQToolBar = 'QTBR';
-static const int kEventParamQMainWindowLayout = 'QMWL';
-
-const EventTypeSpec qtoolbarEvents[] =
-{
- { kEventClassHIObject, kEventHIObjectConstruct },
- { kEventClassHIObject, kEventHIObjectDestruct },
- { kEventClassHIObject, kEventHIObjectInitialize },
- { kEventClassToolbarItem, kEventToolbarItemCreateCustomView }
-};
-
-struct QToolBarInHIToolbarInfo
-{
- QToolBarInHIToolbarInfo(HIToolbarItemRef item)
- : toolbarItem(item), mainWindowLayout(0)
- {}
- HIToolbarItemRef toolbarItem;
- QMainWindowLayout *mainWindowLayout;
-};
-
-OSStatus QMainWindowLayout::qtoolbarInHIToolbarHandler(EventHandlerCallRef inCallRef,
- EventRef event, void *data)
-{
- OSStatus result = eventNotHandledErr;
- QToolBarInHIToolbarInfo *object = static_cast<QToolBarInHIToolbarInfo *>(data);
-
- switch (GetEventClass(event)) {
- case kEventClassHIObject:
- switch (GetEventKind(event)) {
- case kEventHIObjectConstruct:
- {
- HIObjectRef toolbarItem;
- GetEventParameter(event, kEventParamHIObjectInstance, typeHIObjectRef,
- 0, sizeof( HIObjectRef ), 0, &toolbarItem);
-
- QToolBarInHIToolbarInfo *item = new QToolBarInHIToolbarInfo(toolbarItem);
- SetEventParameter(event, kEventParamHIObjectInstance, typeVoidPtr,
- sizeof(void *), &item);
- result = noErr;
- }
- break;
- case kEventHIObjectInitialize:
- result = CallNextEventHandler(inCallRef, event);
- if (result == noErr) {
- QToolBar *toolbar = 0;
- QMainWindowLayout *layout = 0;
- GetEventParameter(event, kEventParamQToolBar, typeVoidPtr,
- 0, sizeof(void *), 0, &toolbar);
- GetEventParameter(event, kEventParamQMainWindowLayout, typeVoidPtr,
- 0, sizeof(void *), 0, &layout);
- object->mainWindowLayout = layout;
- object->mainWindowLayout->unifiedToolbarHash.insert(object->toolbarItem, toolbar);
- HIToolbarItemChangeAttributes(object->toolbarItem,
- kHIToolbarItemLabelDisabled, 0);
- }
- break;
-
- case kEventHIObjectDestruct:
- delete object;
- result = noErr;
- break;
- }
- break;
-
- case kEventClassToolbarItem:
- switch (GetEventKind(event))
- {
- case kEventToolbarItemCreateCustomView:
- {
- QToolBar *toolbar
- = object->mainWindowLayout->unifiedToolbarHash.value(object->toolbarItem);
- if (toolbar) {
- HIViewRef hiview = HIViewRef(toolbar->winId());
- SetEventParameter(event, kEventParamControlRef, typeControlRef,
- sizeof(HIViewRef), &hiview);
- result = noErr;
- }
- }
- break;
- }
- break;
- }
- return result;
-}
-
-void QMainWindowLayout::qtMacHIToolbarRegisterQToolBarInHIToolborItemClass()
-{
- static bool registered = false;
-
- if (!registered) {
- HIObjectRegisterSubclass( kQToolBarHIToolbarItemClassID,
- kHIToolbarItemClassID, 0, QMainWindowLayout::qtoolbarInHIToolbarHandler,
- GetEventTypeCount(qtoolbarEvents), qtoolbarEvents, 0, 0 );
- registered = true;
- }
-}
-
-static void GetToolbarAllowedItems(CFMutableArrayRef array)
-{
- CFArrayAppendValue(array, kQToolBarHIToolbarIdentifier);
-}
-
-HIToolbarItemRef QMainWindowLayout::createQToolBarInHIToolbarItem(QToolBar *toolbar,
- QMainWindowLayout *layout)
-{
- QMainWindowLayout::qtMacHIToolbarRegisterQToolBarInHIToolborItemClass();
-
- EventRef event;
- HIToolbarItemRef result = 0;
-
- CFStringRef identifier = kQToolBarHIToolbarIdentifier;
- UInt32 options = kHIToolbarItemAllowDuplicates;
-
- CreateEvent(0, kEventClassHIObject, kEventHIObjectInitialize,
- GetCurrentEventTime(), 0, &event);
- SetEventParameter(event, kEventParamToolbarItemIdentifier, typeCFStringRef,
- sizeof(CFStringRef), &identifier);
- SetEventParameter(event, kEventParamAttributes, typeUInt32, sizeof(UInt32), &options);
- SetEventParameter(event, kEventParamQToolBar, typeVoidPtr, sizeof(void *), &toolbar);
- SetEventParameter(event, kEventParamQMainWindowLayout, typeVoidPtr, sizeof(void *), &layout);
-
- HIObjectCreate(kQToolBarHIToolbarItemClassID, event,
- static_cast<HIObjectRef *>(&result));
-
- ReleaseEvent(event);
- return result;
-
-}
-
-HIToolbarItemRef QMainWindowLayout::CreateToolbarItemForIdentifier(CFStringRef identifier,
- CFTypeRef data)
-{
- HIToolbarItemRef item = 0;
- if (CFStringCompare(kQToolBarHIToolbarIdentifier, identifier,
- kCFCompareBackwards) == kCFCompareEqualTo) {
- if (data && CFGetTypeID(data) == CFArrayGetTypeID()) {
- CFArrayRef array = static_cast<CFArrayRef>(data);
- QToolBar *toolbar = static_cast<QToolBar *>(const_cast<void *>(CFArrayGetValueAtIndex(array, 0)));
- QMainWindowLayout *layout = static_cast<QMainWindowLayout *>(const_cast<void *>(CFArrayGetValueAtIndex(array, 1)));
- item = createQToolBarInHIToolbarItem(toolbar, layout);
- }
- }
- return item;
-}
-
-static const EventTypeSpec kToolbarEvents[] = {
-{ kEventClassToolbar, kEventToolbarGetDefaultIdentifiers },
-{ kEventClassToolbar, kEventToolbarGetAllowedIdentifiers },
-{ kEventClassToolbar, kEventToolbarCreateItemWithIdentifier },
-{ kEventClassToolbar, kEventToolbarItemAdded },
-{ kEventClassToolbar, kEventToolbarItemRemoved }
-};
-
-OSStatus QMainWindowLayout::qtmacToolbarDelegate(EventHandlerCallRef, EventRef event, void *data)
-{
- QMainWindowLayout *mainWindowLayout = static_cast<QMainWindowLayout *>(data);
- OSStatus result = eventNotHandledErr;
- CFMutableArrayRef array;
- CFStringRef identifier;
- switch (GetEventKind(event)) {
- case kEventToolbarGetDefaultIdentifiers:
- case kEventToolbarGetAllowedIdentifiers:
- GetEventParameter(event, kEventParamMutableArray, typeCFMutableArrayRef, 0,
- sizeof(CFMutableArrayRef), 0, &array);
- GetToolbarAllowedItems(array);
- result = noErr;
- break;
- case kEventToolbarCreateItemWithIdentifier: {
- HIToolbarItemRef item;
- CFTypeRef data = 0;
- OSStatus err = GetEventParameter(event, kEventParamToolbarItemIdentifier, typeCFStringRef,
- 0, sizeof(CFStringRef), 0, &identifier);
- err = GetEventParameter(event, kEventParamToolbarItemConfigData, typeCFTypeRef,
- 0, sizeof(CFTypeRef), 0, &data);
- item = CreateToolbarItemForIdentifier(identifier, data);
- if (item) {
- result = SetEventParameter(event, kEventParamToolbarItem, typeHIToolbarItemRef,
- sizeof(HIToolbarItemRef), &item );
- }
- break;
- }
- case kEventToolbarItemAdded: {
- // Double check that our "view" of the toolbar is similar.
- HIToolbarItemRef item;
- CFIndex index;
- if (GetEventParameter(event, kEventParamToolbarItem, typeHIToolbarItemRef,
- 0, sizeof(HIToolbarItemRef), 0, &item) == noErr
- && GetEventParameter(event, kEventParamIndex, typeCFIndex, 0,
- sizeof(CFIndex), 0, &index) == noErr) {
- CFRetain(item); // We will watch this until it's removed from the list (or bust).
- mainWindowLayout->toolbarItemsCopy.insert(index, item);
- QToolBar *toolbar = mainWindowLayout->unifiedToolbarHash.value(item);
- if (toolbar) {
- int toolbarIndex = mainWindowLayout->qtoolbarsInUnifiedToolbarList.indexOf(toolbar);
- if (index != toolbarIndex) {
- // Dang, we must be out of sync, rebuild it from the "toolbarItemsCopy"
- mainWindowLayout->qtoolbarsInUnifiedToolbarList.clear();
- for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
- // This will either append the correct toolbar or an
- // null toolbar. This is fine because this list
- // is really only kept to make sure that things are but in the right order.
- mainWindowLayout->qtoolbarsInUnifiedToolbarList.append(
- mainWindowLayout->unifiedToolbarHash.value(mainWindowLayout->
- toolbarItemsCopy.at(i)));
- }
- }
- }
- }
- break;
- }
- case kEventToolbarItemRemoved: {
- HIToolbarItemRef item;
- if (GetEventParameter(event, kEventParamToolbarItem, typeHIToolbarItemRef,
- 0, sizeof(HIToolbarItemRef), 0, &item) == noErr) {
- mainWindowLayout->unifiedToolbarHash.remove(item);
- for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
- if (mainWindowLayout->toolbarItemsCopy.at(i) == item) {
- // I know about it, so release it.
- mainWindowLayout->toolbarItemsCopy.removeAt(i);
- mainWindowLayout->qtoolbarsInUnifiedToolbarList.removeAt(i);
- CFRelease(item);
- break;
- }
- }
- }
- break;
- }
- }
- return result;
-}
-#endif // ! QT_MAC_USE_COCOA
-
-#ifndef kWindowUnifiedTitleAndToolbarAttribute
-#define kWindowUnifiedTitleAndToolbarAttribute (1 << 7)
-#endif
-
-void QMainWindowLayout::updateHIToolBarStatus()
-{
- bool useMacToolbar = layoutState.mainWindow->unifiedTitleAndToolBarOnMac();
-#ifndef QT_MAC_USE_COCOA
- if (useMacToolbar) {
- ChangeWindowAttributes(qt_mac_window_for(layoutState.mainWindow),
- kWindowUnifiedTitleAndToolbarAttribute, 0);
- } else {
- ChangeWindowAttributes(qt_mac_window_for(layoutState.mainWindow),
- 0, kWindowUnifiedTitleAndToolbarAttribute);
- }
-#endif
-
- layoutState.mainWindow->setUpdatesEnabled(false); // reduces a little bit of flicker, not all though
-#if defined(QT_MAC_USE_COCOA)
- QMacCocoaAutoReleasePool pool;
- NSView *cView = [qt_mac_window_for(layoutState.mainWindow) contentView];
- if (useMacToolbar) {
- [cView setPostsFrameChangedNotifications:YES];
- [[NSNotificationCenter defaultCenter] addObserver: [QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate]
- selector: @selector(syncContentViewFrame:)
- name: NSViewFrameDidChangeNotification
- object: cView];
- }
-#endif
- if (!useMacToolbar) {
- macWindowToolbarShow(layoutState.mainWindow, false);
- // Move everything out of the HIToolbar into the main toolbar.
- while (!qtoolbarsInUnifiedToolbarList.isEmpty()) {
- // Should shrink the list by one every time.
- QToolBar *toolbar = qtoolbarsInUnifiedToolbarList.first();
-#if defined(QT_MAC_USE_COCOA)
- unifiedSurface->removeToolbar(toolbar);
-#endif
- layoutState.mainWindow->addToolBar(Qt::TopToolBarArea, toolbar);
- }
- macWindowToolbarSet(qt_mac_window_for(layoutState.mainWindow), 0);
- } else {
- QList<QToolBar *> toolbars = layoutState.mainWindow->findChildren<QToolBar *>();
- for (int i = 0; i < toolbars.size(); ++i) {
- QToolBar *toolbar = toolbars.at(i);
- if (toolBarArea(toolbar) == Qt::TopToolBarArea) {
- // Do this here, because we are in an in-between state.
- removeWidget(toolbar);
- layoutState.mainWindow->addToolBar(Qt::TopToolBarArea, toolbar);
- }
- }
- syncUnifiedToolbarVisibility();
- }
-#if defined(QT_MAC_USE_COCOA)
- if (!useMacToolbar) {
- [cView setPostsFrameChangedNotifications:NO];
- [[NSNotificationCenter defaultCenter] removeObserver: [QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate]
- name: NSViewFrameDidChangeNotification
- object: cView];
- }
-#endif
- layoutState.mainWindow->setUpdatesEnabled(true);
-}
-
-void QMainWindowLayout::insertIntoMacToolbar(QToolBar *before, QToolBar *toolbar)
-{
- // This layering could go on to one more level, but I decided to stop here.
- // The HIToolbar and NSToolbar APIs are fairly similar as you will see.
- if (toolbar == 0)
- return;
-
-#if defined(QT_MAC_USE_COCOA)
- // toolbar will now become native (if not already) since we need
- // an nsview for it inside the corresponding NSToolbarItem.
- // Setting isInUnifiedToolbar will (among other things) stop alien
- // siblings from becoming native when this happends since the toolbar
- // will not overlap with other children of the QMainWindow. NB: Switching
- // unified toolbar off after this stage is not supported, as this means
- // that either the menubar must be alien again, or the sibling must
- // be backed by an nsview to protect from overlapping issues:
- toolbar->d_func()->isInUnifiedToolbar = true;
-#endif
-
- QToolBarLayout *toolbarLayout = static_cast<QToolBarLayout *>(toolbar->layout());
- toolbarSaveState.insert(toolbar, ToolBarSaveState(toolbar->isMovable(), toolbar->maximumSize()));
-
- if (toolbarLayout->hasExpandFlag() == false)
- toolbar->setMaximumSize(toolbar->sizeHint());
-
- toolbar->setMovable(false);
- toolbarLayout->setUsePopupMenu(true);
- // Make the toolbar a child of the mainwindow to avoid creating a window.
- toolbar->setParent(layoutState.mainWindow);
-
- toolbar->winId(); // Now create the OSViewRef.
- layoutState.mainWindow->createWinId();
-
- OSWindowRef window = qt_mac_window_for(layoutState.mainWindow);
- int beforeIndex = qtoolbarsInUnifiedToolbarList.indexOf(before);
- if (beforeIndex == -1)
- beforeIndex = qtoolbarsInUnifiedToolbarList.size();
-
- int toolbarIndex = qtoolbarsInUnifiedToolbarList.indexOf(toolbar);
-
-#ifndef QT_MAC_USE_COCOA
- HIToolbarRef macToolbar = NULL;
- if ((GetWindowToolbar(window, &macToolbar) == noErr) && !macToolbar) {
- HIToolbarCreate(kQMainWindowMacToolbarID,
- kHIToolbarItemAllowDuplicates, &macToolbar);
- InstallEventHandler(HIObjectGetEventTarget(static_cast<HIToolbarRef>(macToolbar)),
- QMainWindowLayout::qtmacToolbarDelegate, GetEventTypeCount(kToolbarEvents),
- kToolbarEvents, this, 0);
- HIToolbarSetDisplaySize(macToolbar, kHIToolbarDisplaySizeNormal);
- HIToolbarSetDisplayMode(macToolbar, kHIToolbarDisplayModeIconOnly);
- macWindowToolbarSet(window, macToolbar);
- if (layoutState.mainWindow->isVisible())
- macWindowToolbarShow(layoutState.mainWindow, true);
- CFRelease(macToolbar);
- }
-#else
- QMacCocoaAutoReleasePool pool;
- NSToolbar *macToolbar = [window toolbar];
- if (macToolbar == nil) {
- macToolbar = [[NSToolbar alloc] initWithIdentifier:(NSString *)kQMainWindowMacToolbarID];
- [macToolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
- [macToolbar setSizeMode:NSToolbarSizeModeRegular];
- [macToolbar setDelegate:[[QT_MANGLE_NAMESPACE(QCocoaToolBarDelegate) alloc] initWithMainWindowLayout:this]];
- [window setToolbar:macToolbar];
- [macToolbar release];
- }
-#endif
- if (toolbarIndex != -1) {
- qtoolbarsInUnifiedToolbarList.removeAt(toolbarIndex);
-#ifndef QT_MAC_USE_COCOA
- HIToolbarRemoveItemAtIndex(macToolbar, toolbarIndex);
-#else
- [macToolbar removeItemAtIndex:toolbarIndex];
-#endif
- }
- qtoolbarsInUnifiedToolbarList.insert(beforeIndex, toolbar);
-
- // Adding to the unified toolbar surface for the raster engine.
- if (layoutState.mainWindow->windowSurface()) {
- QPoint offset(0, 0);
- for (int i = 0; i < beforeIndex; ++i) {
- offset.setX(offset.x() + qtoolbarsInUnifiedToolbarList.at(i)->size().width());
- }
-#ifdef QT_MAC_USE_COCOA
- unifiedSurface->insertToolbar(toolbar, offset);
-#endif // QT_MAC_USE_COCOA
- }
-
-#ifndef QT_MAC_USE_COCOA
- QCFType<HIToolbarItemRef> outItem;
- const QObject *stupidArray[] = { toolbar, this };
- QCFType<CFArrayRef> array = CFArrayCreate(0, reinterpret_cast<const void **>(&stupidArray),
- 2, 0);
- HIToolbarCreateItemWithIdentifier(macToolbar, kQToolBarHIToolbarIdentifier,
- array, &outItem);
- HIToolbarInsertItemAtIndex(macToolbar, outItem, beforeIndex);
-#else
- NSString *toolbarID = kQToolBarNSToolbarIdentifier;
- toolbarID = [toolbarID stringByAppendingFormat:@"%p", toolbar];
- cocoaItemIDToToolbarHash.insert(qt_mac_NSStringToQString(toolbarID), toolbar);
- [macToolbar insertItemWithItemIdentifier:toolbarID atIndex:beforeIndex];
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QMainWindowLayout::updateUnifiedToolbarOffset()
-{
- QPoint offset(0, 0);
-
- for (int i = 1; i < qtoolbarsInUnifiedToolbarList.length(); ++i) {
- offset.setX(offset.x() + qtoolbarsInUnifiedToolbarList.at(i - 1)->size().width());
- qtoolbarsInUnifiedToolbarList.at(i)->d_func()->toolbar_offset = offset;
- }
-}
-#endif // QT_MAC_USE_COCOA
-
-
-void QMainWindowLayout::removeFromMacToolbar(QToolBar *toolbar)
-{
- QHash<void *, QToolBar *>::iterator it = unifiedToolbarHash.begin();
- while (it != unifiedToolbarHash.end()) {
- if (it.value() == toolbar) {
- // Rescue our HIView and set it on the mainWindow again.
- bool saveVisible = !toolbar->isHidden();
- toolbar->setParent(0);
- toolbar->setParent(parentWidget());
- toolbar->setVisible(saveVisible);
- ToolBarSaveState saveState = toolbarSaveState.value(toolbar);
- static_cast<QToolBarLayout *>(toolbar->layout())->setUsePopupMenu(false);
- toolbar->setMovable(saveState.movable);
- toolbar->setMaximumSize(saveState.maximumSize);
- toolbarSaveState.remove(toolbar);
-#ifndef QT_MAC_USE_COCOA
- HIToolbarItemRef item = static_cast<HIToolbarItemRef>(it.key());
- HIToolbarRemoveItemAtIndex(HIToolbarItemGetToolbar(item),
- toolbarItemsCopy.indexOf(item));
-#else
- NSToolbarItem *item = static_cast<NSToolbarItem *>(it.key());
- [[qt_mac_window_for(layoutState.mainWindow->window()) toolbar]
- removeItemAtIndex:toolbarItemsCopy.indexOf(item)];
- unifiedToolbarHash.remove(item);
- qtoolbarsInUnifiedToolbarList.removeAll(toolbar);
-#endif
- break;
- }
- ++it;
- }
-}
-
-void QMainWindowLayout::cleanUpMacToolbarItems()
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
-#endif
- for (int i = 0; i < toolbarItemsCopy.size(); ++i) {
-#ifdef QT_MAC_USE_COCOA
- NSToolbarItem *item = static_cast<NSToolbarItem *>(toolbarItemsCopy.at(i));
- [item setView:0];
-#endif
- CFRelease(toolbarItemsCopy.at(i));
- }
- toolbarItemsCopy.clear();
- unifiedToolbarHash.clear();
-
-#ifdef QT_MAC_USE_COCOA
- OSWindowRef window = qt_mac_window_for(layoutState.mainWindow);
- NSToolbar *macToolbar = [window toolbar];
- if (macToolbar) {
- [[macToolbar delegate] release];
- [macToolbar setDelegate:nil];
- }
-#endif
-}
-
-void QMainWindowLayout::fixSizeInUnifiedToolbar(QToolBar *tb) const
-{
-#ifdef QT_MAC_USE_COCOA
- QHash<void *, QToolBar *>::const_iterator it = unifiedToolbarHash.constBegin();
- NSToolbarItem *item = nil;
- while (it != unifiedToolbarHash.constEnd()) {
- if (tb == it.value()) {
- item = static_cast<NSToolbarItem *>(it.key());
- break;
- }
- ++it;
- }
- if (item) {
- QMacCocoaAutoReleasePool pool;
- QWidgetItem layoutItem(tb);
- QSize size = layoutItem.maximumSize();
- NSSize nssize = NSMakeSize(size.width(), size.height());
- [item setMaxSize:nssize];
- size = layoutItem.minimumSize();
- nssize.width = size.width();
- nssize.height = size.height();
- [item setMinSize:nssize];
- }
-#else
- Q_UNUSED(tb);
-#endif
-}
-
-void QMainWindowLayout::syncUnifiedToolbarVisibility()
-{
- if (blockVisiblityCheck)
- return;
-
- Q_ASSERT(layoutState.mainWindow->unifiedTitleAndToolBarOnMac());
- bool show = false;
- const int ToolBarCount = qtoolbarsInUnifiedToolbarList.count();
- for (int i = 0; i < ToolBarCount; ++i) {
- if (qtoolbarsInUnifiedToolbarList.at(i)->isVisible()) {
- show = true;
- break;
- }
- }
- macWindowToolbarShow(layoutState.mainWindow, show);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qmainwindowlayout_p.h b/src/gui/widgets/qmainwindowlayout_p.h
deleted file mode 100644
index 20aca61deb..0000000000
--- a/src/gui/widgets/qmainwindowlayout_p.h
+++ /dev/null
@@ -1,357 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICMAINWINDOWLAYOUT_P_H
-#define QDYNAMICMAINWINDOWLAYOUT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmainwindow.h"
-
-#ifndef QT_NO_MAINWINDOW
-
-#include "QtGui/qlayout.h"
-#include "QtGui/qtabbar.h"
-#include "QtCore/qvector.h"
-#include "QtCore/qset.h"
-#include "QtCore/qbasictimer.h"
-#include "private/qlayoutengine_p.h"
-#include "private/qwidgetanimator_p.h"
-
-#include "qdockarealayout_p.h"
-#include "qtoolbararealayout_p.h"
-
-//#define Q_DEBUG_MAINWINDOW_LAYOUT
-
-#if defined(Q_DEBUG_MAINWINDOW_LAYOUT) && !defined(QT_NO_DOCKWIDGET)
-QT_BEGIN_NAMESPACE
-class QTextStream;
-Q_GUI_EXPORT void qt_dumpLayout(QTextStream &qout, QMainWindow *window);
-QT_END_NAMESPACE
-#endif // Q_DEBUG_MAINWINDOW_LAYOUT && !QT_NO_DOCKWIDGET
-
-#ifdef Q_WS_MAC
-// Forward defs to make avoid including Carbon.h (faster compile you know ;).
-struct OpaqueHIObjectRef;
-typedef struct OpaqueHIObjectRef* HIObjectRef;
-typedef HIObjectRef HIToolbarItemRef;
-typedef const void * CFTypeRef;
-typedef const struct __CFString * CFStringRef;
-
-# ifdef QT_MAC_USE_COCOA
-#include <private/qunifiedtoolbarsurface_mac_p.h>
-# endif // QT_MAC_USE_COCOA
-
-#endif // Q_WS_MAC
-
-QT_BEGIN_NAMESPACE
-
-class QToolBar;
-class QRubberBand;
-
-/* This data structure represents the state of all the tool-bars and dock-widgets. It's value based
- so it can be easilly copied into a temporary variable. All operations are performed without moving
- any widgets. Only when we are sure we have the desired state, we call apply(), which moves the
- widgets.
-*/
-
-class QMainWindowLayoutState
-{
-public:
- QRect rect;
- QMainWindow *mainWindow;
-
- QMainWindowLayoutState(QMainWindow *win);
-
-#ifndef QT_NO_TOOLBAR
- QToolBarAreaLayout toolBarAreaLayout;
-#endif
-
-#ifndef QT_NO_DOCKWIDGET
- QDockAreaLayout dockAreaLayout;
-#else
- QLayoutItem *centralWidgetItem;
- QRect centralWidgetRect;
-#endif
-
- void apply(bool animated);
- void deleteAllLayoutItems();
- void deleteCentralWidgetItem();
-
- QSize sizeHint() const;
- QSize minimumSize() const;
- void fitLayout();
-
- QLayoutItem *itemAt(int index, int *x) const;
- QLayoutItem *takeAt(int index, int *x);
- QList<int> indexOf(QWidget *widget) const;
- QLayoutItem *item(const QList<int> &path);
- QRect itemRect(const QList<int> &path) const;
- QRect gapRect(const QList<int> &path) const; // ### get rid of this, use itemRect() instead
-
- bool contains(QWidget *widget) const;
-
- void setCentralWidget(QWidget *widget);
- QWidget *centralWidget() const;
-
- QList<int> gapIndex(QWidget *widget, const QPoint &pos) const;
- bool insertGap(const QList<int> &path, QLayoutItem *item);
- void remove(const QList<int> &path);
- void remove(QLayoutItem *item);
- void clear();
- bool isValid() const;
-
- QLayoutItem *plug(const QList<int> &path);
- QLayoutItem *unplug(const QList<int> &path, QMainWindowLayoutState *savedState = 0);
-
- void saveState(QDataStream &stream) const;
- bool checkFormat(QDataStream &stream, bool pre43);
- bool restoreState(QDataStream &stream, const QMainWindowLayoutState &oldState);
-};
-
-class Q_AUTOTEST_EXPORT QMainWindowLayout : public QLayout
-{
- Q_OBJECT
-
-public:
- QMainWindowLayoutState layoutState, savedState;
-
- QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLayout);
- ~QMainWindowLayout();
-
- QMainWindow::DockOptions dockOptions;
- void setDockOptions(QMainWindow::DockOptions opts);
- bool usesHIToolBar(QToolBar *toolbar) const;
-
- void timerEvent(QTimerEvent *e);
-
- // status bar
-
- QLayoutItem *statusbar;
-
-#ifndef QT_NO_STATUSBAR
- QStatusBar *statusBar() const;
- void setStatusBar(QStatusBar *sb);
-#endif
-
- // central widget
-
- QWidget *centralWidget() const;
- void setCentralWidget(QWidget *cw);
-
- // toolbars
-
-#ifndef QT_NO_TOOLBAR
- void addToolBarBreak(Qt::ToolBarArea area);
- void insertToolBarBreak(QToolBar *before);
- void removeToolBarBreak(QToolBar *before);
-
- void addToolBar(Qt::ToolBarArea area, QToolBar *toolbar, bool needAddChildWidget = true);
- void insertToolBar(QToolBar *before, QToolBar *toolbar);
- Qt::ToolBarArea toolBarArea(QToolBar *toolbar) const;
- bool toolBarBreak(QToolBar *toolBar) const;
- void getStyleOptionInfo(QStyleOptionToolBar *option, QToolBar *toolBar) const;
- void removeToolBar(QToolBar *toolbar);
- void toggleToolBarsVisible();
- void moveToolBar(QToolBar *toolbar, int pos);
-#endif
-
- // dock widgets
-
-#ifndef QT_NO_DOCKWIDGET
- void setCorner(Qt::Corner corner, Qt::DockWidgetArea area);
- Qt::DockWidgetArea corner(Qt::Corner corner) const;
- void addDockWidget(Qt::DockWidgetArea area,
- QDockWidget *dockwidget,
- Qt::Orientation orientation);
- void splitDockWidget(QDockWidget *after,
- QDockWidget *dockwidget,
- Qt::Orientation orientation);
- void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
- Qt::DockWidgetArea dockWidgetArea(QDockWidget *dockwidget) const;
- void raise(QDockWidget *widget);
- void setVerticalTabsEnabled(bool enabled);
- bool restoreDockWidget(QDockWidget *dockwidget);
-
-#ifndef QT_NO_TABBAR
- bool _documentMode;
- bool documentMode() const;
- void setDocumentMode(bool enabled);
-
- QTabBar *getTabBar();
- QSet<QTabBar*> usedTabBars;
- QList<QTabBar*> unusedTabBars;
- bool verticalTabsEnabled;
-
- QWidget *getSeparatorWidget();
- QSet<QWidget*> usedSeparatorWidgets;
- QList<QWidget*> unusedSeparatorWidgets;
- int sep; // separator extent
-
-#ifndef QT_NO_TABWIDGET
- QTabWidget::TabPosition tabPositions[4];
- QTabWidget::TabShape _tabShape;
-
- QTabWidget::TabShape tabShape() const;
- void setTabShape(QTabWidget::TabShape tabShape);
- QTabWidget::TabPosition tabPosition(Qt::DockWidgetArea area) const;
- void setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition);
-#endif // QT_NO_TABWIDGET
-#endif // QT_NO_TABBAR
-
- // separators
-
- QList<int> movingSeparator;
- QPoint movingSeparatorOrigin, movingSeparatorPos;
- QBasicTimer separatorMoveTimer;
-
- bool startSeparatorMove(const QPoint &pos);
- bool separatorMove(const QPoint &pos);
- bool endSeparatorMove(const QPoint &pos);
- void keepSize(QDockWidget *w);
-#endif // QT_NO_DOCKWIDGET
-
- // save/restore
-
- enum { // sentinel values used to validate state data
- VersionMarker = 0xff
- };
- void saveState(QDataStream &stream) const;
- bool restoreState(QDataStream &stream);
-
- // QLayout interface
-
- void addItem(QLayoutItem *item);
- void setGeometry(const QRect &r);
- QLayoutItem *itemAt(int index) const;
- QLayoutItem *takeAt(int index);
- int count() const;
-
- QSize sizeHint() const;
- QSize minimumSize() const;
- mutable QSize szHint;
- mutable QSize minSize;
- void invalidate();
-
- // animations
-
- QWidgetAnimator widgetAnimator;
- QList<int> currentGapPos;
- QRect currentGapRect;
- QWidget *pluggingWidget;
-#ifndef QT_NO_RUBBERBAND
- QRubberBand *gapIndicator;
-#endif
-
- QList<int> hover(QLayoutItem *widgetItem, const QPoint &mousePos);
- bool plug(QLayoutItem *widgetItem);
- QLayoutItem *unplug(QWidget *widget);
- void revert(QLayoutItem *widgetItem);
- void updateGapIndicator();
- void paintDropIndicator(QPainter *p, QWidget *widget, const QRegion &clip);
- void applyState(QMainWindowLayoutState &newState, bool animate = true);
- void restore(bool keepSavedState = false);
- void updateHIToolBarStatus();
- void animationFinished(QWidget *widget);
-
-private Q_SLOTS:
-#ifndef QT_NO_DOCKWIDGET
-#ifndef QT_NO_TABBAR
- void tabChanged();
-#endif
-#endif
-private:
-#ifndef QT_NO_TABBAR
- void updateTabBarShapes();
-#endif
-#ifdef Q_WS_MAC
-# ifndef QT_MAC_USE_COCOA
- static OSStatus qtmacToolbarDelegate(EventHandlerCallRef, EventRef , void *);
- static OSStatus qtoolbarInHIToolbarHandler(EventHandlerCallRef inCallRef, EventRef event,
- void *data);
- static void qtMacHIToolbarRegisterQToolBarInHIToolborItemClass();
- static HIToolbarItemRef CreateToolbarItemForIdentifier(CFStringRef identifier, CFTypeRef data);
- static HIToolbarItemRef createQToolBarInHIToolbarItem(QToolBar *toolbar,
- QMainWindowLayout *layout);
-# endif
-public:
- struct ToolBarSaveState {
- ToolBarSaveState() : movable(false) { }
- ToolBarSaveState(bool newMovable, const QSize &newMax)
- : movable(newMovable), maximumSize(newMax) { }
- bool movable;
- QSize maximumSize;
- };
- QList<QToolBar *> qtoolbarsInUnifiedToolbarList;
- QList<void *> toolbarItemsCopy;
- QHash<void *, QToolBar *> unifiedToolbarHash;
- QHash<QToolBar *, ToolBarSaveState> toolbarSaveState;
- QHash<QString, QToolBar *> cocoaItemIDToToolbarHash;
- void insertIntoMacToolbar(QToolBar *before, QToolBar *after);
- void removeFromMacToolbar(QToolBar *toolbar);
- void cleanUpMacToolbarItems();
- void fixSizeInUnifiedToolbar(QToolBar *tb) const;
- bool useHIToolBar;
- bool activateUnifiedToolbarAfterFullScreen;
- void syncUnifiedToolbarVisibility();
- bool blockVisiblityCheck;
-
-#ifdef QT_MAC_USE_COCOA
- QUnifiedToolbarSurface *unifiedSurface;
- void updateUnifiedToolbarOffset();
-#endif // QT_MAC_USE_COCOA
-
-#endif // Q_WS_MAC
-};
-QT_END_NAMESPACE
-
-#endif // QT_NO_MAINWINDOW
-
-#endif // QDYNAMICMAINWINDOWLAYOUT_P_H
diff --git a/src/gui/widgets/qmdiarea.cpp b/src/gui/widgets/qmdiarea.cpp
deleted file mode 100644
index 2a486bba18..0000000000
--- a/src/gui/widgets/qmdiarea.cpp
+++ /dev/null
@@ -1,2678 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QMdiArea
- \brief The QMdiArea widget provides an area in which MDI windows are displayed.
- \since 4.3
- \ingroup mainwindow-classes
-
-
- QMdiArea functions, essentially, like a window manager for MDI
- windows. For instance, it draws the windows it manages on itself
- and arranges them in a cascading or tile pattern. QMdiArea is
- commonly used as the center widget in a QMainWindow to create MDI
- applications, but can also be placed in any layout. The following
- code adds an area to a main window:
-
- \snippet doc/src/snippets/mdiareasnippets.cpp 0
-
- Unlike the window managers for top-level windows, all window flags
- (Qt::WindowFlags) are supported by QMdiArea as long as the flags
- are supported by the current widget style. If a specific flag is
- not supported by the style (e.g., the
- \l{Qt::}{WindowShadeButtonHint}), you can still shade the window
- with showShaded().
-
- Subwindows in QMdiArea are instances of QMdiSubWindow. They
- are added to an MDI area with addSubWindow(). It is common to pass
- a QWidget, which is set as the internal widget, to this function,
- but it is also possible to pass a QMdiSubWindow directly.The class
- inherits QWidget, and you can use the same API as with a normal
- top-level window when programming. QMdiSubWindow also has behavior
- that is specific to MDI windows. See the QMdiSubWindow class
- description for more details.
-
- A subwindow becomes active when it gets the keyboard focus, or
- when setFocus() is called. The user activates a window by moving
- focus in the usual ways. The MDI area emits the
- subWindowActivated() signal when the active window changes, and
- the activeSubWindow() function returns the active subwindow.
-
- The convenience function subWindowList() returns a list of all
- subwindows. This information could be used in a popup menu
- containing a list of windows, for example.
-
- The subwindows are sorted by the current
- \l{QMdiArea::}{WindowOrder}. This is used for the subWindowList()
- and for activateNextSubWindow() and acivatePreviousSubWindow().
- Also, it is used when cascading or tiling the windows with
- cascadeSubWindows() and tileSubWindows().
-
- QMdiArea provides two built-in layout strategies for
- subwindows: cascadeSubWindows() and tileSubWindows(). Both are
- slots and are easily connected to menu entries.
-
- \table
- \row \o \inlineimage mdi-cascade.png
- \o \inlineimage mdi-tile.png
- \endtable
-
- \note The default scroll bar property for QMdiArea is Qt::ScrollBarAlwaysOff.
-
- \sa QMdiSubWindow
-*/
-
-/*!
- \fn QMdiArea::subWindowActivated(QMdiSubWindow *window)
-
- QMdiArea emits this signal after \a window has been activated. When \a
- window is 0, QMdiArea has just deactivated its last active window, and
- there are no active windows on the workspace.
-
- \sa QMdiArea::activeSubWindow()
-*/
-
-/*!
- \enum QMdiArea::AreaOption
-
- This enum describes options that customize the behavior of the
- QMdiArea.
-
- \value DontMaximizeSubWindowOnActivation When the active subwindow
- is maximized, the default behavior is to maximize the next
- subwindow that is activated. Set this option if you do not want
- this behavior.
-*/
-
-/*!
- \enum QMdiArea::WindowOrder
-
- Specifies the criteria to use for ordering the list of child windows
- returned by subWindowList(). The functions cascadeSubWindows() and
- tileSubWindows() follow this order when arranging the windows.
-
- \value CreationOrder The windows are returned in the order of
- their creation.
-
- \value StackingOrder The windows are returned in the order in
- which they are stacked, with the top-most window being last in
- the list.
-
- \value ActivationHistoryOrder The windows are returned in the order in
- which they were activated.
-
- \sa subWindowList()
-*/
-
-/*!
- \enum QMdiArea::ViewMode
- \since 4.4
-
- This enum describes the view mode of the area; i.e. how sub-windows
- will be displayed.
-
- \value SubWindowView Display sub-windows with window frames (default).
- \value TabbedView Display sub-windows with tabs in a tab bar.
-
- \sa setViewMode()
-*/
-
-#include "qmdiarea_p.h"
-
-#ifndef QT_NO_MDIAREA
-
-#include <QApplication>
-#include <QStyle>
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-#include <QMacStyle>
-#endif
-#include <QChildEvent>
-#include <QResizeEvent>
-#include <QScrollBar>
-#include <QtAlgorithms>
-#include <QMutableListIterator>
-#include <QPainter>
-#include <QFontMetrics>
-#include <QStyleOption>
-#include <QDesktopWidget>
-#include <QDebug>
-#include <qmath.h>
-#include <private/qlayoutengine_p.h>
-
-QT_BEGIN_NAMESPACE
-
-using namespace QMdi;
-
-// Asserts in debug mode, gives warning otherwise.
-static bool sanityCheck(const QMdiSubWindow * const child, const char *where)
-{
- if (!child) {
- const char error[] = "null pointer";
- Q_ASSERT_X(false, where, error);
- qWarning("%s:%s", where, error);
- return false;
- }
- return true;
-}
-
-static bool sanityCheck(const QList<QWidget *> &widgets, const int index, const char *where)
-{
- if (index < 0 || index >= widgets.size()) {
- const char error[] = "index out of range";
- Q_ASSERT_X(false, where, error);
- qWarning("%s:%s", where, error);
- return false;
- }
- if (!widgets.at(index)) {
- const char error[] = "null pointer";
- Q_ASSERT_X(false, where, error);
- qWarning("%s:%s", where, error);
- return false;
- }
- return true;
-}
-
-static void setIndex(int *index, int candidate, int min, int max, bool isIncreasing)
-{
- if (!index)
- return;
-
- if (isIncreasing) {
- if (candidate > max)
- *index = min;
- else
- *index = qMax(candidate, min);
- } else {
- if (candidate < min)
- *index = max;
- else
- *index = qMin(candidate, max);
- }
- Q_ASSERT(*index >= min && *index <= max);
-}
-
-static inline bool useScrollBar(const QRect &childrenRect, const QSize &maxViewportSize,
- Qt::Orientation orientation)
-{
- if (orientation == Qt::Horizontal)
- return childrenRect.width() > maxViewportSize.width()
- || childrenRect.left() < 0
- || childrenRect.right() >= maxViewportSize.width();
- else
- return childrenRect.height() > maxViewportSize.height()
- || childrenRect.top() < 0
- || childrenRect.bottom() >= maxViewportSize.height();
-}
-
-// Returns the closest mdi area containing the widget (if any).
-static inline QMdiArea *mdiAreaParent(QWidget *widget)
-{
- if (!widget)
- return 0;
-
- QWidget *parent = widget->parentWidget();
- while (parent) {
- if (QMdiArea *area = qobject_cast<QMdiArea *>(parent))
- return area;
- parent = parent->parentWidget();
- }
- return 0;
-}
-
-#ifndef QT_NO_TABWIDGET
-static inline QTabBar::Shape tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position)
-{
- const bool rounded = (shape == QTabWidget::Rounded);
- if (position == QTabWidget::North)
- return rounded ? QTabBar::RoundedNorth : QTabBar::TriangularNorth;
- if (position == QTabWidget::South)
- return rounded ? QTabBar::RoundedSouth : QTabBar::TriangularSouth;
- if (position == QTabWidget::East)
- return rounded ? QTabBar::RoundedEast : QTabBar::TriangularEast;
- if (position == QTabWidget::West)
- return rounded ? QTabBar::RoundedWest : QTabBar::TriangularWest;
- return QTabBar::RoundedNorth;
-}
-#endif // QT_NO_TABWIDGET
-
-static inline QString tabTextFor(QMdiSubWindow *subWindow)
-{
- if (!subWindow)
- return QString();
-
- QString title = subWindow->windowTitle();
- if (subWindow->isWindowModified()) {
- title.replace(QLatin1String("[*]"), QLatin1String("*"));
- } else {
- extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*);
- title = qt_setWindowTitle_helperHelper(title, subWindow);
- }
-
- return title.isEmpty() ? QMdiArea::tr("(Untitled)") : title;
-}
-
-/*!
- \internal
-*/
-void RegularTiler::rearrange(QList<QWidget *> &widgets, const QRect &domain) const
-{
- if (widgets.isEmpty())
- return;
-
- const int n = widgets.size();
- const int ncols = qMax(qCeil(qSqrt(qreal(n))), 1);
- const int nrows = qMax((n % ncols) ? (n / ncols + 1) : (n / ncols), 1);
- const int nspecial = (n % ncols) ? (ncols - n % ncols) : 0;
- const int dx = domain.width() / ncols;
- const int dy = domain.height() / nrows;
-
- int i = 0;
- for (int row = 0; row < nrows; ++row) {
- const int y1 = int(row * (dy + 1));
- for (int col = 0; col < ncols; ++col) {
- if (row == 1 && col < nspecial)
- continue;
- const int x1 = int(col * (dx + 1));
- int x2 = int(x1 + dx);
- int y2 = int(y1 + dy);
- if (row == 0 && col < nspecial) {
- y2 *= 2;
- if (nrows != 2)
- y2 += 1;
- else
- y2 = domain.bottom();
- }
- if (col == ncols - 1 && x2 != domain.right())
- x2 = domain.right();
- if (row == nrows - 1 && y2 != domain.bottom())
- y2 = domain.bottom();
- if (!sanityCheck(widgets, i, "RegularTiler"))
- continue;
- QWidget *widget = widgets.at(i++);
- QRect newGeometry = QRect(QPoint(x1, y1), QPoint(x2, y2));
- widget->setGeometry(QStyle::visualRect(widget->layoutDirection(), domain, newGeometry));
- }
- }
-}
-
-/*!
- \internal
-*/
-void SimpleCascader::rearrange(QList<QWidget *> &widgets, const QRect &domain) const
-{
- if (widgets.isEmpty())
- return;
-
- // Tunables:
- const int topOffset = 0;
- const int bottomOffset = 50;
- const int leftOffset = 0;
- const int rightOffset = 100;
- const int dx = 10;
-
- QStyleOptionTitleBar options;
- options.initFrom(widgets.at(0));
- int titleBarHeight = widgets.at(0)->style()->pixelMetric(QStyle::PM_TitleBarHeight, &options, widgets.at(0));
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- // ### Remove this after the mac style has been fixed
- if (qobject_cast<QMacStyle *>(widgets.at(0)->style()))
- titleBarHeight -= 4;
-#endif
- const QFontMetrics fontMetrics = QFontMetrics(QApplication::font("QWorkspaceTitleBar"));
- const int dy = qMax(titleBarHeight - (titleBarHeight - fontMetrics.height()) / 2, 1);
-
- const int n = widgets.size();
- const int nrows = qMax((domain.height() - (topOffset + bottomOffset)) / dy, 1);
- const int ncols = qMax(n / nrows + ((n % nrows) ? 1 : 0), 1);
- const int dcol = (domain.width() - (leftOffset + rightOffset)) / ncols;
-
- int i = 0;
- for (int row = 0; row < nrows; ++row) {
- for (int col = 0; col < ncols; ++col) {
- const int x = leftOffset + row * dx + col * dcol;
- const int y = topOffset + row * dy;
- if (!sanityCheck(widgets, i, "SimpleCascader"))
- continue;
- QWidget *widget = widgets.at(i++);
- QRect newGeometry = QRect(QPoint(x, y), widget->sizeHint());
- widget->setGeometry(QStyle::visualRect(widget->layoutDirection(), domain, newGeometry));
- if (i == n)
- return;
- }
- }
-}
-
-/*!
- \internal
-*/
-void IconTiler::rearrange(QList<QWidget *> &widgets, const QRect &domain) const
-{
- if (widgets.isEmpty() || !sanityCheck(widgets, 0, "IconTiler"))
- return;
-
- const int n = widgets.size();
- const int width = widgets.at(0)->width();
- const int height = widgets.at(0)->height();
- const int ncols = qMax(domain.width() / width, 1);
- const int nrows = n / ncols + ((n % ncols) ? 1 : 0);
-
- int i = 0;
- for (int row = 0; row < nrows; ++row) {
- for (int col = 0; col < ncols; ++col) {
- const int x = col * width;
- const int y = domain.height() - height - row * height;
- if (!sanityCheck(widgets, i, "IconTiler"))
- continue;
- QWidget *widget = widgets.at(i++);
- QPoint newPos(x, y);
- QRect newGeometry = QRect(newPos.x(), newPos.y(), widget->width(), widget->height());
- widget->setGeometry(QStyle::visualRect(widget->layoutDirection(), domain, newGeometry));
- if (i == n)
- return;
- }
- }
-}
-
-/*!
- \internal
- Calculates the accumulated overlap (intersection area) between 'source' and 'rects'.
-*/
-int MinOverlapPlacer::accumulatedOverlap(const QRect &source, const QList<QRect> &rects)
-{
- int accOverlap = 0;
- foreach (const QRect &rect, rects) {
- QRect intersection = source.intersected(rect);
- accOverlap += intersection.width() * intersection.height();
- }
- return accOverlap;
-}
-
-
-/*!
- \internal
- Finds among 'source' the rectangle with the minimum accumulated overlap with the
- rectangles in 'rects'.
-*/
-QRect MinOverlapPlacer::findMinOverlapRect(const QList<QRect> &source, const QList<QRect> &rects)
-{
- int minAccOverlap = -1;
- QRect minAccOverlapRect;
- foreach (const QRect &srcRect, source) {
- const int accOverlap = accumulatedOverlap(srcRect, rects);
- if (accOverlap < minAccOverlap || minAccOverlap == -1) {
- minAccOverlap = accOverlap;
- minAccOverlapRect = srcRect;
- }
- }
- return minAccOverlapRect;
-}
-
-/*!
- \internal
- Gets candidates for the final placement.
-*/
-void MinOverlapPlacer::getCandidatePlacements(const QSize &size, const QList<QRect> &rects,
- const QRect &domain,QList<QRect> &candidates)
-{
- QSet<int> xset;
- QSet<int> yset;
- xset << domain.left() << domain.right() - size.width() + 1;
- yset << domain.top();
- if (domain.bottom() - size.height() + 1 >= 0)
- yset << domain.bottom() - size.height() + 1;
- foreach (const QRect &rect, rects) {
- xset << rect.right() + 1;
- yset << rect.bottom() + 1;
- }
-
- QList<int> xlist = xset.values();
- qSort(xlist.begin(), xlist.end());
- QList<int> ylist = yset.values();
- qSort(ylist.begin(), ylist.end());
-
- foreach (int y, ylist)
- foreach (int x, xlist)
- candidates << QRect(QPoint(x, y), size);
-}
-
-/*!
- \internal
- Finds all rectangles in 'source' not completely inside 'domain'. The result is stored
- in 'result' and also removed from 'source'.
-*/
-void MinOverlapPlacer::findNonInsiders(const QRect &domain, QList<QRect> &source,
- QList<QRect> &result)
-{
- QMutableListIterator<QRect> it(source);
- while (it.hasNext()) {
- const QRect srcRect = it.next();
- if (!domain.contains(srcRect)) {
- result << srcRect;
- it.remove();
- }
- }
-}
-
-/*!
- \internal
- Finds all rectangles in 'source' that overlaps 'domain' by the maximum overlap area
- between 'domain' and any rectangle in 'source'. The result is stored in 'result'.
-*/
-void MinOverlapPlacer::findMaxOverlappers(const QRect &domain, const QList<QRect> &source,
- QList<QRect> &result)
-{
- int maxOverlap = -1;
- foreach (const QRect &srcRect, source) {
- QRect intersection = domain.intersected(srcRect);
- const int overlap = intersection.width() * intersection.height();
- if (overlap >= maxOverlap || maxOverlap == -1) {
- if (overlap > maxOverlap) {
- maxOverlap = overlap;
- result.clear();
- }
- result << srcRect;
- }
- }
-}
-
-/*!
- \internal
- Finds among the rectangles in 'source' the best placement. Here, 'best' means the
- placement that overlaps the rectangles in 'rects' as little as possible while at the
- same time being as much as possible inside 'domain'.
-*/
-QPoint MinOverlapPlacer::findBestPlacement(const QRect &domain, const QList<QRect> &rects,
- QList<QRect> &source)
-{
- QList<QRect> nonInsiders;
- findNonInsiders(domain, source, nonInsiders);
-
- if (!source.empty())
- return findMinOverlapRect(source, rects).topLeft();
-
- QList<QRect> maxOverlappers;
- findMaxOverlappers(domain, nonInsiders, maxOverlappers);
- return findMinOverlapRect(maxOverlappers, rects).topLeft();
-}
-
-
-/*!
- \internal
- Places the rectangle defined by 'size' relative to 'rects' and 'domain' so that it
- overlaps 'rects' as little as possible and 'domain' as much as possible.
- Returns the position of the resulting rectangle.
-*/
-QPoint MinOverlapPlacer::place(const QSize &size, const QList<QRect> &rects,
- const QRect &domain) const
-{
- if (size.isEmpty() || !domain.isValid())
- return QPoint();
- foreach (const QRect &rect, rects) {
- if (!rect.isValid())
- return QPoint();
- }
-
- QList<QRect> candidates;
- getCandidatePlacements(size, rects, domain, candidates);
- return findBestPlacement(domain, rects, candidates);
-}
-
-#ifndef QT_NO_TABBAR
-class QMdiAreaTabBar : public QTabBar
-{
-public:
- QMdiAreaTabBar(QWidget *parent) : QTabBar(parent) {}
-
-protected:
- void mousePressEvent(QMouseEvent *event);
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *event);
-#endif
-
-private:
- QMdiSubWindow *subWindowFromIndex(int index) const;
-};
-
-/*!
- \internal
-*/
-void QMdiAreaTabBar::mousePressEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::MidButton) {
- QTabBar::mousePressEvent(event);
- return;
- }
-
- QMdiSubWindow *subWindow = subWindowFromIndex(tabAt(event->pos()));
- if (!subWindow) {
- event->ignore();
- return;
- }
-
- subWindow->close();
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \internal
-*/
-void QMdiAreaTabBar::contextMenuEvent(QContextMenuEvent *event)
-{
- QPointer<QMdiSubWindow> subWindow = subWindowFromIndex(tabAt(event->pos()));
- if (!subWindow || subWindow->isHidden()) {
- event->ignore();
- return;
- }
-
-#ifndef QT_NO_MENU
- QMdiSubWindowPrivate *subWindowPrivate = subWindow->d_func();
- if (!subWindowPrivate->systemMenu) {
- event->ignore();
- return;
- }
-
- QMdiSubWindow *currentSubWindow = subWindowFromIndex(currentIndex());
- Q_ASSERT(currentSubWindow);
-
- // We don't want these actions to show up in the system menu when the
- // current sub-window is maximized, i.e. covers the entire viewport.
- if (currentSubWindow->isMaximized()) {
- subWindowPrivate->setVisible(QMdiSubWindowPrivate::MoveAction, false);
- subWindowPrivate->setVisible(QMdiSubWindowPrivate::ResizeAction, false);
- subWindowPrivate->setVisible(QMdiSubWindowPrivate::MinimizeAction, false);
- subWindowPrivate->setVisible(QMdiSubWindowPrivate::MaximizeAction, false);
- subWindowPrivate->setVisible(QMdiSubWindowPrivate::MaximizeAction, false);
- subWindowPrivate->setVisible(QMdiSubWindowPrivate::StayOnTopAction, false);
- }
-
- // Show system menu.
- subWindowPrivate->systemMenu->exec(event->globalPos());
- if (!subWindow)
- return;
-
- // Restore action visibility.
- subWindowPrivate->updateActions();
-#endif // QT_NO_MENU
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*!
- \internal
-*/
-QMdiSubWindow *QMdiAreaTabBar::subWindowFromIndex(int index) const
-{
- if (index < 0 || index >= count())
- return 0;
-
- QMdiArea *mdiArea = qobject_cast<QMdiArea *>(parentWidget());
- Q_ASSERT(mdiArea);
-
- const QList<QMdiSubWindow *> subWindows = mdiArea->subWindowList();
- Q_ASSERT(index < subWindows.size());
-
- QMdiSubWindow *subWindow = mdiArea->subWindowList().at(index);
- Q_ASSERT(subWindow);
-
- return subWindow;
-}
-#endif // QT_NO_TABBAR
-
-/*!
- \internal
-*/
-QMdiAreaPrivate::QMdiAreaPrivate()
- : cascader(0),
- regularTiler(0),
- iconTiler(0),
- placer(0),
-#ifndef QT_NO_RUBBERBAND
- rubberBand(0),
-#endif
-#ifndef QT_NO_TABBAR
- tabBar(0),
-#endif
- activationOrder(QMdiArea::CreationOrder),
- viewMode(QMdiArea::SubWindowView),
-#ifndef QT_NO_TABBAR
- documentMode(false),
- tabsClosable(false),
- tabsMovable(false),
-#endif
-#ifndef QT_NO_TABWIDGET
- tabShape(QTabWidget::Rounded),
- tabPosition(QTabWidget::North),
-#endif
- ignoreGeometryChange(false),
- ignoreWindowStateChange(false),
- isActivated(false),
- isSubWindowsTiled(false),
- showActiveWindowMaximized(false),
- tileCalledFromResizeEvent(false),
- updatesDisabledByUs(false),
- inViewModeChange(false),
- indexToNextWindow(-1),
- indexToPreviousWindow(-1),
- indexToHighlighted(-1),
- indexToLastActiveTab(-1),
- resizeTimerId(-1),
- tabToPreviousTimerId(-1)
-{
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::_q_deactivateAllWindows(QMdiSubWindow *aboutToActivate)
-{
- if (ignoreWindowStateChange)
- return;
-
- Q_Q(QMdiArea);
- if (!aboutToActivate)
- aboutToBecomeActive = qobject_cast<QMdiSubWindow *>(q->sender());
- else
- aboutToBecomeActive = aboutToActivate;
- Q_ASSERT(aboutToBecomeActive);
-
- foreach (QMdiSubWindow *child, childWindows) {
- if (!sanityCheck(child, "QMdiArea::deactivateAllWindows") || aboutToBecomeActive == child)
- continue;
- // We don't want to handle signals caused by child->showNormal().
- ignoreWindowStateChange = true;
- if(!(options & QMdiArea::DontMaximizeSubWindowOnActivation) && !showActiveWindowMaximized)
- showActiveWindowMaximized = child->isMaximized() && child->isVisible();
- if (showActiveWindowMaximized && child->isMaximized()) {
- if (q->updatesEnabled()) {
- updatesDisabledByUs = true;
- q->setUpdatesEnabled(false);
- }
- child->showNormal();
- }
- if (child->isMinimized() && !child->isShaded() && !windowStaysOnTop(child))
- child->lower();
- ignoreWindowStateChange = false;
- child->d_func()->setActive(false);
- }
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::_q_processWindowStateChanged(Qt::WindowStates oldState,
- Qt::WindowStates newState)
-{
- if (ignoreWindowStateChange)
- return;
-
- Q_Q(QMdiArea);
- QMdiSubWindow *child = qobject_cast<QMdiSubWindow *>(q->sender());
- if (!child)
- return;
-
- // windowActivated
- if (!(oldState & Qt::WindowActive) && (newState & Qt::WindowActive))
- emitWindowActivated(child);
- // windowDeactivated
- else if ((oldState & Qt::WindowActive) && !(newState & Qt::WindowActive))
- resetActiveWindow(child);
-
- // windowMinimized
- if (!(oldState & Qt::WindowMinimized) && (newState & Qt::WindowMinimized)) {
- isSubWindowsTiled = false;
- arrangeMinimizedSubWindows();
- // windowMaximized
- } else if (!(oldState & Qt::WindowMaximized) && (newState & Qt::WindowMaximized)) {
- internalRaise(child);
- // windowRestored
- } else if (!(newState & (Qt::WindowMaximized | Qt::WindowMinimized))) {
- internalRaise(child);
- if (oldState & Qt::WindowMinimized)
- arrangeMinimizedSubWindows();
- }
-}
-
-void QMdiAreaPrivate::_q_currentTabChanged(int index)
-{
-#ifdef QT_NO_TABBAR
- Q_UNUSED(index);
-#else
- if (!tabBar || index < 0)
- return;
-
- // If the previous active sub-window was hidden, disable the tab.
- if (indexToLastActiveTab >= 0 && indexToLastActiveTab < tabBar->count()
- && indexToLastActiveTab < childWindows.count()) {
- QMdiSubWindow *lastActive = childWindows.at(indexToLastActiveTab);
- if (lastActive && lastActive->isHidden())
- tabBar->setTabEnabled(indexToLastActiveTab, false);
- }
-
- indexToLastActiveTab = index;
- Q_ASSERT(childWindows.size() > index);
- QMdiSubWindow *subWindow = childWindows.at(index);
- Q_ASSERT(subWindow);
- activateWindow(subWindow);
-#endif // QT_NO_TABBAR
-}
-
-void QMdiAreaPrivate::_q_closeTab(int index)
-{
-#ifdef QT_NO_TABBAR
- Q_UNUSED(index);
-#else
- QMdiSubWindow *subWindow = childWindows.at(index);
- Q_ASSERT(subWindow);
- subWindow->close();
-#endif // QT_NO_TABBAR
-}
-
-void QMdiAreaPrivate::_q_moveTab(int from, int to)
-{
-#ifdef QT_NO_TABBAR
- Q_UNUSED(from);
- Q_UNUSED(to);
-#else
- childWindows.move(from, to);
-#endif // QT_NO_TABBAR
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::appendChild(QMdiSubWindow *child)
-{
- Q_Q(QMdiArea);
- Q_ASSERT(child && childWindows.indexOf(child) == -1);
-
- if (child->parent() != viewport)
- child->setParent(viewport, child->windowFlags());
- childWindows.append(QPointer<QMdiSubWindow>(child));
-
- if (!child->testAttribute(Qt::WA_Resized) && q->isVisible()) {
- QSize newSize(child->sizeHint().boundedTo(viewport->size()));
- child->resize(newSize.expandedTo(qSmartMinSize(child)));
- }
-
- if (!placer)
- placer = new MinOverlapPlacer;
- place(placer, child);
-
- if (hbarpolicy != Qt::ScrollBarAlwaysOff)
- child->setOption(QMdiSubWindow::AllowOutsideAreaHorizontally, true);
- else
- child->setOption(QMdiSubWindow::AllowOutsideAreaHorizontally, false);
-
- if (vbarpolicy != Qt::ScrollBarAlwaysOff)
- child->setOption(QMdiSubWindow::AllowOutsideAreaVertically, true);
- else
- child->setOption(QMdiSubWindow::AllowOutsideAreaVertically, false);
-
- internalRaise(child);
- indicesToActivatedChildren.prepend(childWindows.size() - 1);
- Q_ASSERT(indicesToActivatedChildren.size() == childWindows.size());
-
-#ifndef QT_NO_TABBAR
- if (tabBar) {
- tabBar->addTab(child->windowIcon(), tabTextFor(child));
- updateTabBarGeometry();
- if (childWindows.count() == 1 && !(options & QMdiArea::DontMaximizeSubWindowOnActivation))
- showActiveWindowMaximized = true;
- }
-#endif
-
- if (!(child->windowFlags() & Qt::SubWindow))
- child->setWindowFlags(Qt::SubWindow);
- child->installEventFilter(q);
-
- QObject::connect(child, SIGNAL(aboutToActivate()), q, SLOT(_q_deactivateAllWindows()));
- QObject::connect(child, SIGNAL(windowStateChanged(Qt::WindowStates,Qt::WindowStates)),
- q, SLOT(_q_processWindowStateChanged(Qt::WindowStates,Qt::WindowStates)));
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::place(Placer *placer, QMdiSubWindow *child)
-{
- if (!placer || !child)
- return;
-
- Q_Q(QMdiArea);
- if (!q->isVisible()) {
- // The window is only laid out when it's added to QMdiArea,
- // so there's no need to check that we don't have it in the
- // list already. appendChild() ensures that.
- pendingPlacements.append(child);
- return;
- }
-
- QList<QRect> rects;
- QRect parentRect = q->rect();
- foreach (QMdiSubWindow *window, childWindows) {
- if (!sanityCheck(window, "QMdiArea::place") || window == child || !window->isVisibleTo(q)
- || !window->testAttribute(Qt::WA_Moved)) {
- continue;
- }
- QRect occupiedGeometry;
- if (window->isMaximized()) {
- occupiedGeometry = QRect(window->d_func()->oldGeometry.topLeft(),
- window->d_func()->restoreSize);
- } else {
- occupiedGeometry = window->geometry();
- }
- rects.append(QStyle::visualRect(child->layoutDirection(), parentRect, occupiedGeometry));
- }
- QPoint newPos = placer->place(child->size(), rects, parentRect);
- QRect newGeometry = QRect(newPos.x(), newPos.y(), child->width(), child->height());
- child->setGeometry(QStyle::visualRect(child->layoutDirection(), parentRect, newGeometry));
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::rearrange(Rearranger *rearranger)
-{
- if (!rearranger)
- return;
-
- Q_Q(QMdiArea);
- if (!q->isVisible()) {
- // Compress if we already have the rearranger in the list.
- int index = pendingRearrangements.indexOf(rearranger);
- if (index != -1)
- pendingRearrangements.move(index, pendingRearrangements.size() - 1);
- else
- pendingRearrangements.append(rearranger);
- return;
- }
-
- QList<QWidget *> widgets;
- const bool reverseList = rearranger->type() == Rearranger::RegularTiler;
- const QList<QMdiSubWindow *> subWindows = subWindowList(activationOrder, reverseList);
- QSize minSubWindowSize;
- foreach (QMdiSubWindow *child, subWindows) {
- if (!sanityCheck(child, "QMdiArea::rearrange") || !child->isVisible())
- continue;
- if (rearranger->type() == Rearranger::IconTiler) {
- if (child->isMinimized() && !child->isShaded() && !(child->windowFlags() & Qt::FramelessWindowHint))
- widgets.append(child);
- } else {
- if (child->isMinimized() && !child->isShaded())
- continue;
- if (child->isMaximized() || child->isShaded())
- child->showNormal();
- minSubWindowSize = minSubWindowSize.expandedTo(child->minimumSize())
- .expandedTo(child->d_func()->internalMinimumSize);
- widgets.append(child);
- }
- }
-
- if (active && rearranger->type() == Rearranger::RegularTiler) {
- // Move active window in front if necessary. That's the case if we
- // have any windows with staysOnTopHint set.
- int indexToActive = widgets.indexOf((QWidget *)active);
- if (indexToActive > 0)
- widgets.move(indexToActive, 0);
- }
-
- QRect domain = viewport->rect();
- if (rearranger->type() == Rearranger::RegularTiler && !widgets.isEmpty())
- domain = resizeToMinimumTileSize(minSubWindowSize, widgets.count());
-
- rearranger->rearrange(widgets, domain);
-
- if (rearranger->type() == Rearranger::RegularTiler && !widgets.isEmpty()) {
- isSubWindowsTiled = true;
- updateScrollBars();
- } else if (rearranger->type() == Rearranger::SimpleCascader) {
- isSubWindowsTiled = false;
- }
-}
-
-/*!
- \internal
-
- Arranges all minimized windows at the bottom of the workspace.
-*/
-void QMdiAreaPrivate::arrangeMinimizedSubWindows()
-{
- if (!iconTiler)
- iconTiler = new IconTiler;
- rearrange(iconTiler);
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::activateWindow(QMdiSubWindow *child)
-{
- if (childWindows.isEmpty()) {
- Q_ASSERT(!child);
- Q_ASSERT(!active);
- return;
- }
-
- if (!child) {
- if (active) {
- Q_ASSERT(active->d_func()->isActive);
- active->d_func()->setActive(false);
- resetActiveWindow();
- }
- return;
- }
-
- if (child->isHidden() || child == active)
- return;
- child->d_func()->setActive(true);
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::activateCurrentWindow()
-{
- QMdiSubWindow *current = q_func()->currentSubWindow();
- if (current && !isExplicitlyDeactivated(current)) {
- current->d_func()->activationEnabled = true;
- current->d_func()->setActive(true, /*changeFocus=*/false);
- }
-}
-
-void QMdiAreaPrivate::activateHighlightedWindow()
-{
- if (indexToHighlighted < 0)
- return;
-
- Q_ASSERT(indexToHighlighted < childWindows.size());
- if (tabToPreviousTimerId != -1)
- activateWindow(nextVisibleSubWindow(-1, QMdiArea::ActivationHistoryOrder));
- else
- activateWindow(childWindows.at(indexToHighlighted));
-#ifndef QT_NO_RUBBERBAND
- hideRubberBand();
-#endif
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::emitWindowActivated(QMdiSubWindow *activeWindow)
-{
- Q_Q(QMdiArea);
- Q_ASSERT(activeWindow);
- if (activeWindow == active)
- return;
- Q_ASSERT(activeWindow->d_func()->isActive);
-
- if (!aboutToBecomeActive)
- _q_deactivateAllWindows(activeWindow);
- Q_ASSERT(aboutToBecomeActive);
-
- // This is true only if 'DontMaximizeSubWindowOnActivation' is disabled
- // and the previous active window was maximized.
- if (showActiveWindowMaximized) {
- if (!activeWindow->isMaximized())
- activeWindow->showMaximized();
- showActiveWindowMaximized = false;
- }
-
- // Put in front to update activation order.
- const int indexToActiveWindow = childWindows.indexOf(activeWindow);
- Q_ASSERT(indexToActiveWindow != -1);
- const int index = indicesToActivatedChildren.indexOf(indexToActiveWindow);
- Q_ASSERT(index != -1);
- indicesToActivatedChildren.move(index, 0);
- internalRaise(activeWindow);
-
- if (updatesDisabledByUs) {
- q->setUpdatesEnabled(true);
- updatesDisabledByUs = false;
- }
-
- Q_ASSERT(aboutToBecomeActive == activeWindow);
- active = activeWindow;
- aboutToBecomeActive = 0;
- Q_ASSERT(active->d_func()->isActive);
-
-#ifndef QT_NO_TABBAR
- if (tabBar && tabBar->currentIndex() != indexToActiveWindow)
- tabBar->setCurrentIndex(indexToActiveWindow);
-#endif
-
- if (active->isMaximized() && scrollBarsEnabled())
- updateScrollBars();
-
- emit q->subWindowActivated(active);
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::resetActiveWindow(QMdiSubWindow *deactivatedWindow)
-{
- Q_Q(QMdiArea);
- if (deactivatedWindow) {
- if (deactivatedWindow != active)
- return;
- active = 0;
- if ((aboutToBecomeActive || isActivated || lastWindowAboutToBeDestroyed())
- && !isExplicitlyDeactivated(deactivatedWindow) && !q->window()->isMinimized()) {
- return;
- }
- emit q->subWindowActivated(0);
- return;
- }
-
- if (aboutToBecomeActive)
- return;
-
- active = 0;
- emit q->subWindowActivated(0);
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::updateActiveWindow(int removedIndex, bool activeRemoved)
-{
- Q_ASSERT(indicesToActivatedChildren.size() == childWindows.size());
-
-#ifndef QT_NO_TABBAR
- if (tabBar && removedIndex >= 0) {
- tabBar->blockSignals(true);
- tabBar->removeTab(removedIndex);
- updateTabBarGeometry();
- tabBar->blockSignals(false);
- }
-#endif
-
- if (childWindows.isEmpty()) {
- showActiveWindowMaximized = false;
- resetActiveWindow();
- return;
- }
-
- if (indexToHighlighted >= 0) {
-#ifndef QT_NO_RUBBERBAND
- // Hide rubber band if highlighted window is removed.
- if (indexToHighlighted == removedIndex)
- hideRubberBand();
- else
-#endif
- // or update index if necessary.
- if (indexToHighlighted > removedIndex)
- --indexToHighlighted;
- }
-
- // Update indices list
- for (int i = 0; i < indicesToActivatedChildren.size(); ++i) {
- int *index = &indicesToActivatedChildren[i];
- if (*index > removedIndex)
- --*index;
- }
-
- if (!activeRemoved)
- return;
-
- // Activate next window.
- QMdiSubWindow *next = nextVisibleSubWindow(0, activationOrder, removedIndex);
- if (next)
- activateWindow(next);
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::updateScrollBars()
-{
- if (ignoreGeometryChange || !scrollBarsEnabled())
- return;
-
- Q_Q(QMdiArea);
- QSize maxSize = q->maximumViewportSize();
- QSize hbarExtent = hbar->sizeHint();
- QSize vbarExtent = vbar->sizeHint();
-
- if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, 0, q)) {
- const int doubleFrameWidth = frameWidth * 2;
- if (hbarpolicy == Qt::ScrollBarAlwaysOn)
- maxSize.rheight() -= doubleFrameWidth;
- if (vbarpolicy == Qt::ScrollBarAlwaysOn)
- maxSize.rwidth() -= doubleFrameWidth;
- hbarExtent.rheight() += doubleFrameWidth;
- vbarExtent.rwidth() += doubleFrameWidth;
- }
-
- const QRect childrenRect = active && active->isMaximized()
- ? active->geometry() : viewport->childrenRect();
- bool useHorizontalScrollBar = useScrollBar(childrenRect, maxSize, Qt::Horizontal);
- bool useVerticalScrollBar = useScrollBar(childrenRect, maxSize, Qt::Vertical);
-
- if (useHorizontalScrollBar && !useVerticalScrollBar) {
- const QSize max = maxSize - QSize(0, hbarExtent.height());
- useVerticalScrollBar = useScrollBar(childrenRect, max, Qt::Vertical);
- }
-
- if (useVerticalScrollBar && !useHorizontalScrollBar) {
- const QSize max = maxSize - QSize(vbarExtent.width(), 0);
- useHorizontalScrollBar = useScrollBar(childrenRect, max, Qt::Horizontal);
- }
-
- if (useHorizontalScrollBar && hbarpolicy != Qt::ScrollBarAlwaysOn)
- maxSize.rheight() -= hbarExtent.height();
- if (useVerticalScrollBar && vbarpolicy != Qt::ScrollBarAlwaysOn)
- maxSize.rwidth() -= vbarExtent.width();
-
- QRect viewportRect(QPoint(0, 0), maxSize);
- const int startX = q->isLeftToRight() ? childrenRect.left() : viewportRect.right()
- - childrenRect.right();
-
- // Horizontal scroll bar.
- if (isSubWindowsTiled && hbar->value() != 0)
- hbar->setValue(0);
- const int xOffset = startX + hbar->value();
- hbar->setRange(qMin(0, xOffset),
- qMax(0, xOffset + childrenRect.width() - viewportRect.width()));
- hbar->setPageStep(childrenRect.width());
- hbar->setSingleStep(childrenRect.width() / 20);
-
- // Vertical scroll bar.
- if (isSubWindowsTiled && vbar->value() != 0)
- vbar->setValue(0);
- const int yOffset = childrenRect.top() + vbar->value();
- vbar->setRange(qMin(0, yOffset),
- qMax(0, yOffset + childrenRect.height() - viewportRect.height()));
- vbar->setPageStep(childrenRect.height());
- vbar->setSingleStep(childrenRect.height() / 20);
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::internalRaise(QMdiSubWindow *mdiChild) const
-{
- if (!sanityCheck(mdiChild, "QMdiArea::internalRaise") || childWindows.size() < 2)
- return;
-
- QMdiSubWindow *stackUnderChild = 0;
- if (!windowStaysOnTop(mdiChild)) {
- foreach (QObject *object, viewport->children()) {
- QMdiSubWindow *child = qobject_cast<QMdiSubWindow *>(object);
- if (!child || !childWindows.contains(child))
- continue;
- if (!child->isHidden() && windowStaysOnTop(child)) {
- if (stackUnderChild)
- child->stackUnder(stackUnderChild);
- else
- child->raise();
- stackUnderChild = child;
- }
- }
- }
-
- if (stackUnderChild)
- mdiChild->stackUnder(stackUnderChild);
- else
- mdiChild->raise();
-}
-
-QRect QMdiAreaPrivate::resizeToMinimumTileSize(const QSize &minSubWindowSize, int subWindowCount)
-{
- Q_Q(QMdiArea);
- if (!minSubWindowSize.isValid() || subWindowCount <= 0)
- return viewport->rect();
-
- // Calculate minimum size.
- const int columns = qMax(qCeil(qSqrt(qreal(subWindowCount))), 1);
- const int rows = qMax((subWindowCount % columns) ? (subWindowCount / columns + 1)
- : (subWindowCount / columns), 1);
- const int minWidth = minSubWindowSize.width() * columns;
- const int minHeight = minSubWindowSize.height() * rows;
-
- // Increase area size if necessary. Scroll bars are provided if we're not able
- // to resize to the minimum size.
- if (!tileCalledFromResizeEvent) {
- QWidget *topLevel = q;
- // Find the topLevel for this area, either a real top-level or a sub-window.
- while (topLevel && !topLevel->isWindow() && topLevel->windowType() != Qt::SubWindow)
- topLevel = topLevel->parentWidget();
- // We don't want sub-subwindows to be placed at the edge, thus add 2 pixels.
- int minAreaWidth = minWidth + left + right + 2;
- int minAreaHeight = minHeight + top + bottom + 2;
- if (hbar->isVisible())
- minAreaHeight += hbar->height();
- if (vbar->isVisible())
- minAreaWidth += vbar->width();
- if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, 0, q)) {
- const int frame = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, q);
- minAreaWidth += 2 * frame;
- minAreaHeight += 2 * frame;
- }
- const QSize diff = QSize(minAreaWidth, minAreaHeight).expandedTo(q->size()) - q->size();
- topLevel->resize(topLevel->size() + diff);
- }
-
- QRect domain = viewport->rect();
-
- // Adjust domain width and provide horizontal scroll bar.
- if (domain.width() < minWidth) {
- domain.setWidth(minWidth);
- if (hbarpolicy == Qt::ScrollBarAlwaysOff)
- q->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- else
- hbar->setValue(0);
- }
- // Adjust domain height and provide vertical scroll bar.
- if (domain.height() < minHeight) {
- domain.setHeight(minHeight);
- if (vbarpolicy == Qt::ScrollBarAlwaysOff)
- q->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- else
- vbar->setValue(0);
- }
- return domain;
-}
-
-/*!
- \internal
-*/
-bool QMdiAreaPrivate::scrollBarsEnabled() const
-{
- return hbarpolicy != Qt::ScrollBarAlwaysOff || vbarpolicy != Qt::ScrollBarAlwaysOff;
-}
-
-/*!
- \internal
-*/
-bool QMdiAreaPrivate::lastWindowAboutToBeDestroyed() const
-{
- if (childWindows.count() != 1)
- return false;
-
- QMdiSubWindow *last = childWindows.at(0);
- if (!last)
- return true;
-
- if (!last->testAttribute(Qt::WA_DeleteOnClose))
- return false;
-
- return last->d_func()->data.is_closing;
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::setChildActivationEnabled(bool enable, bool onlyNextActivationEvent) const
-{
- foreach (QMdiSubWindow *subWindow, childWindows) {
- if (!subWindow || !subWindow->isVisible())
- continue;
- if (onlyNextActivationEvent)
- subWindow->d_func()->ignoreNextActivationEvent = !enable;
- else
- subWindow->d_func()->activationEnabled = enable;
- }
-}
-
-/*!
- \internal
- \reimp
-*/
-void QMdiAreaPrivate::scrollBarPolicyChanged(Qt::Orientation orientation, Qt::ScrollBarPolicy policy)
-{
- if (childWindows.isEmpty())
- return;
-
- const QMdiSubWindow::SubWindowOption option = orientation == Qt::Horizontal ?
- QMdiSubWindow::AllowOutsideAreaHorizontally : QMdiSubWindow::AllowOutsideAreaVertically;
- const bool enable = policy != Qt::ScrollBarAlwaysOff;
- foreach (QMdiSubWindow *child, childWindows) {
- if (!sanityCheck(child, "QMdiArea::scrollBarPolicyChanged"))
- continue;
- child->setOption(option, enable);
- }
- updateScrollBars();
-}
-
-QList<QMdiSubWindow*>
-QMdiAreaPrivate::subWindowList(QMdiArea::WindowOrder order, bool reversed) const
-{
- QList<QMdiSubWindow *> list;
- if (childWindows.isEmpty())
- return list;
-
- if (order == QMdiArea::CreationOrder) {
- foreach (QMdiSubWindow *child, childWindows) {
- if (!child)
- continue;
- if (!reversed)
- list.append(child);
- else
- list.prepend(child);
- }
- } else if (order == QMdiArea::StackingOrder) {
- foreach (QObject *object, viewport->children()) {
- QMdiSubWindow *child = qobject_cast<QMdiSubWindow *>(object);
- if (!child || !childWindows.contains(child))
- continue;
- if (!reversed)
- list.append(child);
- else
- list.prepend(child);
- }
- } else { // ActivationHistoryOrder
- Q_ASSERT(indicesToActivatedChildren.size() == childWindows.size());
- for (int i = indicesToActivatedChildren.count() - 1; i >= 0; --i) {
- QMdiSubWindow *child = childWindows.at(indicesToActivatedChildren.at(i));
- if (!child)
- continue;
- if (!reversed)
- list.append(child);
- else
- list.prepend(child);
- }
- }
- return list;
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::disconnectSubWindow(QObject *subWindow)
-{
- if (!subWindow)
- return;
-
- Q_Q(QMdiArea);
- QObject::disconnect(subWindow, 0, q, 0);
- subWindow->removeEventFilter(q);
-}
-
-/*!
- \internal
-*/
-QMdiSubWindow *QMdiAreaPrivate::nextVisibleSubWindow(int increaseFactor, QMdiArea::WindowOrder order,
- int removedIndex, int fromIndex) const
-{
- if (childWindows.isEmpty())
- return 0;
-
- Q_Q(const QMdiArea);
- const QList<QMdiSubWindow *> subWindows = q->subWindowList(order);
- QMdiSubWindow *current = 0;
-
- if (removedIndex < 0) {
- if (fromIndex >= 0 && fromIndex < subWindows.size())
- current = childWindows.at(fromIndex);
- else
- current = q->currentSubWindow();
- }
-
- // There's no current sub-window (removed or deactivated),
- // so we have to pick the last active or the next in creation order.
- if (!current) {
- if (removedIndex >= 0 && order == QMdiArea::CreationOrder) {
- int candidateIndex = -1;
- setIndex(&candidateIndex, removedIndex, 0, subWindows.size() - 1, true);
- current = childWindows.at(candidateIndex);
- } else {
- current = subWindows.back();
- }
- }
- Q_ASSERT(current);
-
- // Find the index for the current sub-window in the given activation order
- const int indexToCurrent = subWindows.indexOf(current);
- const bool increasing = increaseFactor > 0 ? true : false;
-
- // and use that index + increseFactor as a candidate.
- int index = -1;
- setIndex(&index, indexToCurrent + increaseFactor, 0, subWindows.size() - 1, increasing);
- Q_ASSERT(index != -1);
-
- // Try to find another window if the candidate is hidden.
- while (subWindows.at(index)->isHidden()) {
- setIndex(&index, index + increaseFactor, 0, subWindows.size() - 1, increasing);
- if (index == indexToCurrent)
- break;
- }
-
- if (!subWindows.at(index)->isHidden())
- return subWindows.at(index);
- return 0;
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::highlightNextSubWindow(int increaseFactor)
-{
- if (childWindows.size() == 1)
- return;
-
- Q_Q(QMdiArea);
- // There's no highlighted sub-window atm, use current.
- if (indexToHighlighted < 0) {
- QMdiSubWindow *current = q->currentSubWindow();
- if (!current)
- return;
- indexToHighlighted = childWindows.indexOf(current);
- }
-
- Q_ASSERT(indexToHighlighted >= 0);
- Q_ASSERT(indexToHighlighted < childWindows.size());
-
- QMdiSubWindow *highlight = nextVisibleSubWindow(increaseFactor, activationOrder, -1, indexToHighlighted);
- if (!highlight)
- return;
-
-#ifndef QT_NO_RUBBERBAND
- if (!rubberBand) {
- rubberBand = new QRubberBand(QRubberBand::Rectangle, viewport);
- // For accessibility to identify this special widget.
- rubberBand->setObjectName(QLatin1String("qt_rubberband"));
- rubberBand->setWindowFlags(rubberBand->windowFlags() | Qt::WindowStaysOnTopHint);
- }
-#endif
-
- // Only highlight if we're not switching back to the previously active window (Ctrl-Tab once).
-#ifndef QT_NO_RUBBERBAND
- if (tabToPreviousTimerId == -1)
- showRubberBandFor(highlight);
-#endif
-
- indexToHighlighted = childWindows.indexOf(highlight);
- Q_ASSERT(indexToHighlighted >= 0);
-}
-
-/*!
- \internal
- \since 4.4
-*/
-void QMdiAreaPrivate::setViewMode(QMdiArea::ViewMode mode)
-{
- Q_Q(QMdiArea);
- if (viewMode == mode || inViewModeChange)
- return;
-
- // Just a guard since we cannot set viewMode = mode here.
- inViewModeChange = true;
-
-#ifndef QT_NO_TABBAR
- if (mode == QMdiArea::TabbedView) {
- Q_ASSERT(!tabBar);
- tabBar = new QMdiAreaTabBar(q);
- tabBar->setDocumentMode(documentMode);
- tabBar->setTabsClosable(tabsClosable);
- tabBar->setMovable(tabsMovable);
-#ifndef QT_NO_TABWIDGET
- tabBar->setShape(tabBarShapeFrom(tabShape, tabPosition));
-#endif
-
- isSubWindowsTiled = false;
-
- foreach (QMdiSubWindow *subWindow, childWindows)
- tabBar->addTab(subWindow->windowIcon(), tabTextFor(subWindow));
-
- QMdiSubWindow *current = q->currentSubWindow();
- if (current) {
- tabBar->setCurrentIndex(childWindows.indexOf(current));
- // Restore sub-window (i.e. cleanup buttons in menu bar and window title).
- if (current->isMaximized())
- current->showNormal();
-
- viewMode = mode;
-
- // Now, maximize it.
- if (!q->testOption(QMdiArea::DontMaximizeSubWindowOnActivation)) {
- current->showMaximized();
- }
- } else {
- viewMode = mode;
- }
-
- if (q->isVisible())
- tabBar->show();
- updateTabBarGeometry();
-
- QObject::connect(tabBar, SIGNAL(currentChanged(int)), q, SLOT(_q_currentTabChanged(int)));
- QObject::connect(tabBar, SIGNAL(tabCloseRequested(int)), q, SLOT(_q_closeTab(int)));
- QObject::connect(tabBar, SIGNAL(tabMoved(int,int)), q, SLOT(_q_moveTab(int,int)));
- } else
-#endif // QT_NO_TABBAR
- { // SubWindowView
-#ifndef QT_NO_TABBAR
- delete tabBar;
- tabBar = 0;
-#endif // QT_NO_TABBAR
-
- viewMode = mode;
- q->setViewportMargins(0, 0, 0, 0);
- indexToLastActiveTab = -1;
-
- QMdiSubWindow *current = q->currentSubWindow();
- if (current && current->isMaximized())
- current->showNormal();
- }
-
- Q_ASSERT(viewMode == mode);
- inViewModeChange = false;
-}
-
-#ifndef QT_NO_TABBAR
-/*!
- \internal
-*/
-void QMdiAreaPrivate::updateTabBarGeometry()
-{
- if (!tabBar)
- return;
-
- Q_Q(QMdiArea);
-#ifndef QT_NO_TABWIDGET
- Q_ASSERT(tabBarShapeFrom(tabShape, tabPosition) == tabBar->shape());
-#endif
- const QSize tabBarSizeHint = tabBar->sizeHint();
-
- int areaHeight = q->height();
- if (hbar && hbar->isVisible())
- areaHeight -= hbar->height();
-
- int areaWidth = q->width();
- if (vbar && vbar->isVisible())
- areaWidth -= vbar->width();
-
- QRect tabBarRect;
-#ifndef QT_NO_TABWIDGET
- switch (tabPosition) {
- case QTabWidget::North:
- q->setViewportMargins(0, tabBarSizeHint.height(), 0, 0);
- tabBarRect = QRect(0, 0, areaWidth, tabBarSizeHint.height());
- break;
- case QTabWidget::South:
- q->setViewportMargins(0, 0, 0, tabBarSizeHint.height());
- tabBarRect = QRect(0, areaHeight - tabBarSizeHint.height(), areaWidth, tabBarSizeHint.height());
- break;
- case QTabWidget::East:
- if (q->layoutDirection() == Qt::LeftToRight)
- q->setViewportMargins(0, 0, tabBarSizeHint.width(), 0);
- else
- q->setViewportMargins(tabBarSizeHint.width(), 0, 0, 0);
- tabBarRect = QRect(areaWidth - tabBarSizeHint.width(), 0, tabBarSizeHint.width(), areaHeight);
- break;
- case QTabWidget::West:
- if (q->layoutDirection() == Qt::LeftToRight)
- q->setViewportMargins(tabBarSizeHint.width(), 0, 0, 0);
- else
- q->setViewportMargins(0, 0, tabBarSizeHint.width(), 0);
- tabBarRect = QRect(0, 0, tabBarSizeHint.width(), areaHeight);
- break;
- default:
- break;
- }
-#endif // QT_NO_TABWIDGET
-
- tabBar->setGeometry(QStyle::visualRect(q->layoutDirection(), q->contentsRect(), tabBarRect));
-}
-
-/*!
- \internal
-*/
-void QMdiAreaPrivate::refreshTabBar()
-{
- if (!tabBar)
- return;
-
- tabBar->setDocumentMode(documentMode);
- tabBar->setTabsClosable(tabsClosable);
- tabBar->setMovable(tabsMovable);
-#ifndef QT_NO_TABWIDGET
- tabBar->setShape(tabBarShapeFrom(tabShape, tabPosition));
-#endif
- updateTabBarGeometry();
-}
-#endif // QT_NO_TABBAR
-
-/*!
- Constructs an empty mdi area. \a parent is passed to QWidget's
- constructor.
-*/
-QMdiArea::QMdiArea(QWidget *parent)
- : QAbstractScrollArea(*new QMdiAreaPrivate, parent)
-{
- setBackground(palette().brush(QPalette::Dark));
- setFrameStyle(QFrame::NoFrame);
- setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- setViewport(0);
- setFocusPolicy(Qt::NoFocus);
- QApplication::instance()->installEventFilter(this);
-}
-
-/*!
- Destroys the MDI area.
-*/
-QMdiArea::~QMdiArea()
-{
- Q_D(QMdiArea);
- delete d->cascader;
- d->cascader = 0;
-
- delete d->regularTiler;
- d->regularTiler = 0;
-
- delete d->iconTiler;
- d->iconTiler = 0;
-
- delete d->placer;
- d->placer = 0;
-}
-
-/*!
- \reimp
-*/
-QSize QMdiArea::sizeHint() const
-{
- // Calculate a proper scale factor for QDesktopWidget::size().
- // This also takes into account that we can have nested workspaces.
- int nestedCount = 0;
- QWidget *widget = this->parentWidget();
- while (widget) {
- if (qobject_cast<QMdiArea *>(widget))
- ++nestedCount;
- widget = widget->parentWidget();
- }
- const int scaleFactor = 3 * (nestedCount + 1);
-
- QSize desktopSize = QApplication::desktop()->size();
- QSize size(desktopSize.width() * 2 / scaleFactor, desktopSize.height() * 2 / scaleFactor);
- foreach (QMdiSubWindow *child, d_func()->childWindows) {
- if (!sanityCheck(child, "QMdiArea::sizeHint"))
- continue;
- size = size.expandedTo(child->sizeHint());
- }
- return size.expandedTo(QApplication::globalStrut());
-}
-
-/*!
- \reimp
-*/
-QSize QMdiArea::minimumSizeHint() const
-{
- Q_D(const QMdiArea);
- QSize size(style()->pixelMetric(QStyle::PM_MdiSubWindowMinimizedWidth, 0, this),
- style()->pixelMetric(QStyle::PM_TitleBarHeight, 0, this));
- size = size.expandedTo(QAbstractScrollArea::minimumSizeHint());
- if (!d->scrollBarsEnabled()) {
- foreach (QMdiSubWindow *child, d->childWindows) {
- if (!sanityCheck(child, "QMdiArea::sizeHint"))
- continue;
- size = size.expandedTo(child->minimumSizeHint());
- }
- }
- return size.expandedTo(QApplication::globalStrut());
-}
-
-/*!
- Returns a pointer to the current subwindow, or 0 if there is
- no current subwindow.
-
- This function will return the same as activeSubWindow() if
- the QApplication containing QMdiArea is active.
-
- \sa activeSubWindow(), QApplication::activeWindow()
-*/
-QMdiSubWindow *QMdiArea::currentSubWindow() const
-{
- Q_D(const QMdiArea);
- if (d->childWindows.isEmpty())
- return 0;
-
- if (d->active)
- return d->active;
-
- if (d->isActivated && !window()->isMinimized())
- return 0;
-
- Q_ASSERT(d->indicesToActivatedChildren.count() > 0);
- int index = d->indicesToActivatedChildren.at(0);
- Q_ASSERT(index >= 0 && index < d->childWindows.size());
- QMdiSubWindow *current = d->childWindows.at(index);
- Q_ASSERT(current);
- return current;
-}
-
-/*!
- Returns a pointer to the current active subwindow. If no
- window is currently active, 0 is returned.
-
- Subwindows are treated as top-level windows with respect to
- window state, i.e., if a widget outside the MDI area is the active
- window, no subwindow will be active. Note that if a widget in the
- window in which the MDI area lives gains focus, the window will be
- activated.
-
- \sa setActiveSubWindow(), Qt::WindowState
-*/
-QMdiSubWindow *QMdiArea::activeSubWindow() const
-{
- Q_D(const QMdiArea);
- return d->active;
-}
-
-/*!
- Activates the subwindow \a window. If \a window is 0, any
- current active window is deactivated.
-
- \sa activeSubWindow()
-*/
-void QMdiArea::setActiveSubWindow(QMdiSubWindow *window)
-{
- Q_D(QMdiArea);
- if (!window) {
- d->activateWindow(0);
- return;
- }
-
- if (d->childWindows.isEmpty()) {
- qWarning("QMdiArea::setActiveSubWindow: workspace is empty");
- return;
- }
-
- if (d->childWindows.indexOf(window) == -1) {
- qWarning("QMdiArea::setActiveSubWindow: window is not inside workspace");
- return;
- }
-
- d->activateWindow(window);
-}
-
-/*!
- Closes the active subwindow.
-
- \sa closeAllSubWindows()
-*/
-void QMdiArea::closeActiveSubWindow()
-{
- Q_D(QMdiArea);
- if (d->active)
- d->active->close();
-}
-
-/*!
- Returns a list of all subwindows in the MDI area. If \a order is
- CreationOrder (the default), the windows are sorted in the order
- in which they were inserted into the workspace. If \a order is
- StackingOrder, the windows are listed in their stacking order,
- with the topmost window as the last item in the list. If \a order
- is ActivationHistoryOrder, the windows are listed according to
- their recent activation history.
-
- \sa WindowOrder
-*/
-QList<QMdiSubWindow *> QMdiArea::subWindowList(WindowOrder order) const
-{
- Q_D(const QMdiArea);
- return d->subWindowList(order, false);
-}
-
-/*!
- Closes all subwindows by sending a QCloseEvent to each window.
- You may receive subWindowActivated() signals from subwindows
- before they are closed (if the MDI area activates the subwindow
- when another is closing).
-
- Subwindows that ignore the close event will remain open.
-
- \sa closeActiveSubWindow()
-*/
-void QMdiArea::closeAllSubWindows()
-{
- Q_D(QMdiArea);
- if (d->childWindows.isEmpty())
- return;
-
- d->isSubWindowsTiled = false;
- foreach (QMdiSubWindow *child, d->childWindows) {
- if (!sanityCheck(child, "QMdiArea::closeAllSubWindows"))
- continue;
- child->close();
- }
-
- d->updateScrollBars();
-}
-
-/*!
- Gives the keyboard focus to another window in the list of child
- windows. The window activated will be the next one determined
- by the current \l{QMdiArea::WindowOrder} {activation order}.
-
- \sa activatePreviousSubWindow(), QMdiArea::WindowOrder
-*/
-void QMdiArea::activateNextSubWindow()
-{
- Q_D(QMdiArea);
- if (d->childWindows.isEmpty())
- return;
-
- QMdiSubWindow *next = d->nextVisibleSubWindow(1, d->activationOrder);
- if (next)
- d->activateWindow(next);
-}
-
-/*!
- Gives the keyboard focus to another window in the list of child
- windows. The window activated will be the previous one determined
- by the current \l{QMdiArea::WindowOrder} {activation order}.
-
- \sa activateNextSubWindow(), QMdiArea::WindowOrder
-*/
-void QMdiArea::activatePreviousSubWindow()
-{
- Q_D(QMdiArea);
- if (d->childWindows.isEmpty())
- return;
-
- QMdiSubWindow *previous = d->nextVisibleSubWindow(-1, d->activationOrder);
- if (previous)
- d->activateWindow(previous);
-}
-
-/*!
- Adds \a widget as a new subwindow to the MDI area. If \a
- windowFlags are non-zero, they will override the flags set on the
- widget.
-
- The \a widget can be either a QMdiSubWindow or another QWidget
- (in which case the MDI area will create a subwindow and set the \a
- widget as the internal widget).
-
- \note Once the subwindow has been added, its parent will be the
- \e{viewport widget} of the QMdiArea.
-
- \snippet doc/src/snippets/mdiareasnippets.cpp 1
-
- When you create your own subwindow, you must set the
- Qt::WA_DeleteOnClose widget attribute if you want the window to be
- deleted when closed in the MDI area. If not, the window will be
- hidden and the MDI area will not activate the next subwindow.
-
- Returns the QMdiSubWindow that is added to the MDI area.
-
- \sa removeSubWindow()
-*/
-QMdiSubWindow *QMdiArea::addSubWindow(QWidget *widget, Qt::WindowFlags windowFlags)
-{
- if (!widget) {
- qWarning("QMdiArea::addSubWindow: null pointer to widget");
- return 0;
- }
-
- Q_D(QMdiArea);
- // QWidget::setParent clears focusWidget so store it
- QWidget *childFocus = widget->focusWidget();
- QMdiSubWindow *child = qobject_cast<QMdiSubWindow *>(widget);
-
- // Widget is already a QMdiSubWindow
- if (child) {
- if (d->childWindows.indexOf(child) != -1) {
- qWarning("QMdiArea::addSubWindow: window is already added");
- return child;
- }
- child->setParent(viewport(), windowFlags ? windowFlags : child->windowFlags());
- // Create a QMdiSubWindow
- } else {
- child = new QMdiSubWindow(viewport(), windowFlags);
- child->setAttribute(Qt::WA_DeleteOnClose);
- child->setWidget(widget);
- Q_ASSERT(child->testAttribute(Qt::WA_DeleteOnClose));
- }
-
- if (childFocus)
- childFocus->setFocus();
- d->appendChild(child);
- return child;
-}
-
-/*!
- Removes \a widget from the MDI area. The \a widget must be
- either a QMdiSubWindow or a widget that is the internal widget of
- a subwindow. Note \a widget is never actually deleted by QMdiArea.
- If a QMdiSubWindow is passed in its parent is set to 0 and it is
- removed, but if an internal widget is passed in the child widget
- is set to 0 but the QMdiSubWindow is not removed.
-
- \sa addSubWindow()
-*/
-void QMdiArea::removeSubWindow(QWidget *widget)
-{
- if (!widget) {
- qWarning("QMdiArea::removeSubWindow: null pointer to widget");
- return;
- }
-
- Q_D(QMdiArea);
- if (d->childWindows.isEmpty())
- return;
-
- if (QMdiSubWindow *child = qobject_cast<QMdiSubWindow *>(widget)) {
- int index = d->childWindows.indexOf(child);
- if (index == -1) {
- qWarning("QMdiArea::removeSubWindow: window is not inside workspace");
- return;
- }
- d->disconnectSubWindow(child);
- d->childWindows.removeAll(child);
- d->indicesToActivatedChildren.removeAll(index);
- d->updateActiveWindow(index, d->active == child);
- child->setParent(0);
- return;
- }
-
- bool found = false;
- foreach (QMdiSubWindow *child, d->childWindows) {
- if (!sanityCheck(child, "QMdiArea::removeSubWindow"))
- continue;
- if (child->widget() == widget) {
- child->setWidget(0);
- Q_ASSERT(!child->widget());
- found = true;
- break;
- }
- }
-
- if (!found)
- qWarning("QMdiArea::removeSubWindow: widget is not child of any window inside QMdiArea");
-}
-
-/*!
- \property QMdiArea::background
- \brief the background brush for the workspace
-
- This property sets the background brush for the workspace area
- itself. By default, it is a gray color, but can be any brush
- (e.g., colors, gradients or pixmaps).
-*/
-QBrush QMdiArea::background() const
-{
- return d_func()->background;
-}
-
-void QMdiArea::setBackground(const QBrush &brush)
-{
- Q_D(QMdiArea);
- if (d->background != brush) {
- d->background = brush;
- d->viewport->setAttribute(Qt::WA_OpaquePaintEvent, brush.isOpaque());
- update();
- }
-}
-
-
-/*!
- \property QMdiArea::activationOrder
- \brief the ordering criteria for subwindow lists
- \since 4.4
-
- This property specifies the ordering criteria for the list of
- subwindows returned by subWindowList(). By default, it is the window
- creation order.
-
- \sa subWindowList()
-*/
-QMdiArea::WindowOrder QMdiArea::activationOrder() const
-{
- Q_D(const QMdiArea);
- return d->activationOrder;
-}
-
-void QMdiArea::setActivationOrder(WindowOrder order)
-{
- Q_D(QMdiArea);
- if (order != d->activationOrder)
- d->activationOrder = order;
-}
-
-/*!
- If \a on is true, \a option is enabled on the MDI area; otherwise
- it is disabled. See AreaOption for the effect of each option.
-
- \sa AreaOption, testOption()
-*/
-void QMdiArea::setOption(AreaOption option, bool on)
-{
- Q_D(QMdiArea);
- if (on && !(d->options & option))
- d->options |= option;
- else if (!on && (d->options & option))
- d->options &= ~option;
-}
-
-/*!
- Returns true if \a option is enabled; otherwise returns false.
-
- \sa AreaOption, setOption()
-*/
-bool QMdiArea::testOption(AreaOption option) const
-{
- return d_func()->options & option;
-}
-
-/*!
- \property QMdiArea::viewMode
- \brief the way sub-windows are displayed in the QMdiArea.
- \since 4.4
-
- By default, the SubWindowView is used to display sub-windows.
-
- \sa ViewMode, setTabShape(), setTabPosition()
-*/
-QMdiArea::ViewMode QMdiArea::viewMode() const
-{
- Q_D(const QMdiArea);
- return d->viewMode;
-}
-
-void QMdiArea::setViewMode(ViewMode mode)
-{
- Q_D(QMdiArea);
- d->setViewMode(mode);
-}
-
-#ifndef QT_NO_TABBAR
-/*!
- \property QMdiArea::documentMode
- \brief whether the tab bar is set to document mode in tabbed view mode.
- \since 4.5
-
- Document mode is disabled by default.
-
- \sa QTabBar::documentMode, setViewMode()
-*/
-bool QMdiArea::documentMode() const
-{
- Q_D(const QMdiArea);
- return d->documentMode;
-}
-
-void QMdiArea::setDocumentMode(bool enabled)
-{
- Q_D(QMdiArea);
- if (d->documentMode == enabled)
- return;
-
- d->documentMode = enabled;
- d->refreshTabBar();
-}
-
-/*!
- \property QMdiArea::tabsClosable
- \brief whether the tab bar should place close buttons on each tab in tabbed view mode.
- \since 4.8
-
- Tabs are not closable by default.
-
- \sa QTabBar::tabsClosable, setViewMode()
-*/
-bool QMdiArea::tabsClosable() const
-{
- Q_D(const QMdiArea);
- return d->tabsClosable;
-}
-
-void QMdiArea::setTabsClosable(bool closable)
-{
- Q_D(QMdiArea);
- if (d->tabsClosable == closable)
- return;
-
- d->tabsClosable = closable;
- d->refreshTabBar();
-}
-
-/*!
- \property QMdiArea::tabsMovable
- \brief whether the user can move the tabs within the tabbar area in tabbed view mode.
- \since 4.8
-
- Tabs are not movable by default.
-
- \sa QTabBar::tabsMovable, setViewMode()
-*/
-bool QMdiArea::tabsMovable() const
-{
- Q_D(const QMdiArea);
- return d->tabsMovable;
-}
-
-void QMdiArea::setTabsMovable(bool movable)
-{
- Q_D(QMdiArea);
- if (d->tabsMovable == movable)
- return;
-
- d->tabsMovable = movable;
- d->refreshTabBar();
-}
-#endif // QT_NO_TABBAR
-
-#ifndef QT_NO_TABWIDGET
-/*!
- \property QMdiArea::tabShape
- \brief the shape of the tabs in tabbed view mode.
- \since 4.4
-
- Possible values for this property are QTabWidget::Rounded
- (default) or QTabWidget::Triangular.
-
- \sa QTabWidget::TabShape, setViewMode()
-*/
-QTabWidget::TabShape QMdiArea::tabShape() const
-{
- Q_D(const QMdiArea);
- return d->tabShape;
-}
-
-void QMdiArea::setTabShape(QTabWidget::TabShape shape)
-{
- Q_D(QMdiArea);
- if (d->tabShape == shape)
- return;
-
- d->tabShape = shape;
- d->refreshTabBar();
-}
-
-/*!
- \property QMdiArea::tabPosition
- \brief the position of the tabs in tabbed view mode.
- \since 4.4
-
- Possible values for this property are described by the
- QTabWidget::TabPosition enum.
-
- \sa QTabWidget::TabPosition, setViewMode()
-*/
-QTabWidget::TabPosition QMdiArea::tabPosition() const
-{
- Q_D(const QMdiArea);
- return d->tabPosition;
-}
-
-void QMdiArea::setTabPosition(QTabWidget::TabPosition position)
-{
- Q_D(QMdiArea);
- if (d->tabPosition == position)
- return;
-
- d->tabPosition = position;
- d->refreshTabBar();
-}
-#endif // QT_NO_TABWIDGET
-
-/*!
- \reimp
-*/
-void QMdiArea::childEvent(QChildEvent *childEvent)
-{
- Q_D(QMdiArea);
- if (childEvent->type() == QEvent::ChildPolished) {
- if (QMdiSubWindow *mdiChild = qobject_cast<QMdiSubWindow *>(childEvent->child())) {
- if (d->childWindows.indexOf(mdiChild) == -1)
- d->appendChild(mdiChild);
- }
- }
-}
-
-/*!
- \reimp
-*/
-void QMdiArea::resizeEvent(QResizeEvent *resizeEvent)
-{
- Q_D(QMdiArea);
- if (d->childWindows.isEmpty()) {
- resizeEvent->ignore();
- return;
- }
-
-#ifndef QT_NO_TABBAR
- d->updateTabBarGeometry();
-#endif
-
- // Re-tile the views if we're in tiled mode. Re-tile means we will change
- // the geometry of the children, which in turn means 'isSubWindowsTiled'
- // is set to false, so we have to update the state at the end.
- if (d->isSubWindowsTiled) {
- d->tileCalledFromResizeEvent = true;
- tileSubWindows();
- d->tileCalledFromResizeEvent = false;
- d->isSubWindowsTiled = true;
- d->startResizeTimer();
- // We don't have scroll bars or any maximized views.
- return;
- }
-
- // Resize maximized views.
- bool hasMaximizedSubWindow = false;
- foreach (QMdiSubWindow *child, d->childWindows) {
- if (sanityCheck(child, "QMdiArea::resizeEvent") && child->isMaximized()
- && child->size() != resizeEvent->size()) {
- child->resize(resizeEvent->size());
- if (!hasMaximizedSubWindow)
- hasMaximizedSubWindow = true;
- }
- }
-
- d->updateScrollBars();
-
- // Minimized views are stacked under maximized views so there's
- // no need to re-arrange minimized views on-demand. Start a timer
- // just to make things faster with subsequent resize events.
- if (hasMaximizedSubWindow)
- d->startResizeTimer();
- else
- d->arrangeMinimizedSubWindows();
-}
-
-/*!
- \reimp
-*/
-void QMdiArea::timerEvent(QTimerEvent *timerEvent)
-{
- Q_D(QMdiArea);
- if (timerEvent->timerId() == d->resizeTimerId) {
- killTimer(d->resizeTimerId);
- d->resizeTimerId = -1;
- d->arrangeMinimizedSubWindows();
- } else if (timerEvent->timerId() == d->tabToPreviousTimerId) {
- killTimer(d->tabToPreviousTimerId);
- d->tabToPreviousTimerId = -1;
- if (d->indexToHighlighted < 0)
- return;
-#ifndef QT_NO_RUBBERBAND
- // We're not doing a "quick switch" ... show rubber band.
- Q_ASSERT(d->indexToHighlighted < d->childWindows.size());
- Q_ASSERT(d->rubberBand);
- d->showRubberBandFor(d->childWindows.at(d->indexToHighlighted));
-#endif
- }
-}
-
-/*!
- \reimp
-*/
-void QMdiArea::showEvent(QShowEvent *showEvent)
-{
- Q_D(QMdiArea);
- if (!d->pendingRearrangements.isEmpty()) {
- bool skipPlacement = false;
- foreach (Rearranger *rearranger, d->pendingRearrangements) {
- // If this is the case, we don't have to lay out pending child windows
- // since the rearranger will find a placement for them.
- if (rearranger->type() != Rearranger::IconTiler && !skipPlacement)
- skipPlacement = true;
- d->rearrange(rearranger);
- }
- d->pendingRearrangements.clear();
-
- if (skipPlacement && !d->pendingPlacements.isEmpty())
- d->pendingPlacements.clear();
- }
-
- if (!d->pendingPlacements.isEmpty()) {
- foreach (QMdiSubWindow *window, d->pendingPlacements) {
- if (!window)
- continue;
- if (!window->testAttribute(Qt::WA_Resized)) {
- QSize newSize(window->sizeHint().boundedTo(viewport()->size()));
- window->resize(newSize.expandedTo(qSmartMinSize(window)));
- }
- if (!window->testAttribute(Qt::WA_Moved) && !window->isMinimized()
- && !window->isMaximized()) {
- d->place(d->placer, window);
- }
- }
- d->pendingPlacements.clear();
- }
-
- d->setChildActivationEnabled(true);
- d->activateCurrentWindow();
-
- QAbstractScrollArea::showEvent(showEvent);
-}
-
-/*!
- \reimp
-*/
-bool QMdiArea::viewportEvent(QEvent *event)
-{
- Q_D(QMdiArea);
- switch (event->type()) {
- case QEvent::ChildRemoved: {
- d->isSubWindowsTiled = false;
- QObject *removedChild = static_cast<QChildEvent *>(event)->child();
- for (int i = 0; i < d->childWindows.size(); ++i) {
- QObject *child = d->childWindows.at(i);
- if (!child || child == removedChild || !child->parent()
- || child->parent() != viewport()) {
- if (!testOption(DontMaximizeSubWindowOnActivation)) {
- // In this case we can only rely on the child being a QObject
- // (or 0), but let's try and see if we can get more information.
- QWidget *mdiChild = qobject_cast<QWidget *>(removedChild);
- if (mdiChild && mdiChild->isMaximized())
- d->showActiveWindowMaximized = true;
- }
- d->disconnectSubWindow(child);
- const bool activeRemoved = i == d->indicesToActivatedChildren.at(0);
- d->childWindows.removeAt(i);
- d->indicesToActivatedChildren.removeAll(i);
- d->updateActiveWindow(i, activeRemoved);
- d->arrangeMinimizedSubWindows();
- break;
- }
- }
- d->updateScrollBars();
- break;
- }
- case QEvent::Destroy:
- d->isSubWindowsTiled = false;
- d->resetActiveWindow();
- d->childWindows.clear();
- qWarning("QMdiArea: Deleting the view port is undefined, use setViewport instead.");
- break;
- default:
- break;
- }
- return QAbstractScrollArea::viewportEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QMdiArea::scrollContentsBy(int dx, int dy)
-{
- Q_D(QMdiArea);
- const bool wasSubWindowsTiled = d->isSubWindowsTiled;
- d->ignoreGeometryChange = true;
- viewport()->scroll(isLeftToRight() ? dx : -dx, dy);
- d->arrangeMinimizedSubWindows();
- d->ignoreGeometryChange = false;
- if (wasSubWindowsTiled)
- d->isSubWindowsTiled = true;
-}
-
-/*!
- Arranges all child windows in a tile pattern.
-
- \sa cascadeSubWindows()
-*/
-void QMdiArea::tileSubWindows()
-{
- Q_D(QMdiArea);
- if (!d->regularTiler)
- d->regularTiler = new RegularTiler;
- d->rearrange(d->regularTiler);
-}
-
-/*!
- Arranges all the child windows in a cascade pattern.
-
- \sa tileSubWindows()
-*/
-void QMdiArea::cascadeSubWindows()
-{
- Q_D(QMdiArea);
- if (!d->cascader)
- d->cascader = new SimpleCascader;
- d->rearrange(d->cascader);
-}
-
-/*!
- \reimp
-*/
-bool QMdiArea::event(QEvent *event)
-{
- Q_D(QMdiArea);
- switch (event->type()) {
-#ifdef Q_WS_WIN
- // QWidgetPrivate::hide_helper activates another sub-window when closing a
- // modal dialog on Windows (see activateWindow() inside the the ifdef).
- case QEvent::WindowUnblocked:
- d->activateCurrentWindow();
- break;
-#endif
- case QEvent::WindowActivate: {
- d->isActivated = true;
- if (d->childWindows.isEmpty())
- break;
- if (!d->active)
- d->activateCurrentWindow();
- d->setChildActivationEnabled(false, true);
- break;
- }
- case QEvent::WindowDeactivate:
- d->isActivated = false;
- d->setChildActivationEnabled(false, true);
- break;
- case QEvent::StyleChange:
- // Re-tile the views if we're in tiled mode. Re-tile means we will change
- // the geometry of the children, which in turn means 'isSubWindowsTiled'
- // is set to false, so we have to update the state at the end.
- if (d->isSubWindowsTiled) {
- tileSubWindows();
- d->isSubWindowsTiled = true;
- }
- break;
- case QEvent::WindowIconChange:
- foreach (QMdiSubWindow *window, d->childWindows) {
- if (sanityCheck(window, "QMdiArea::WindowIconChange"))
- QApplication::sendEvent(window, event);
- }
- break;
- case QEvent::Hide:
- d->setActive(d->active, false, false);
- d->setChildActivationEnabled(false);
- break;
-#ifndef QT_NO_TABBAR
- case QEvent::LayoutDirectionChange:
- d->updateTabBarGeometry();
- break;
-#endif
- default:
- break;
- }
- return QAbstractScrollArea::event(event);
-}
-
-/*!
- \reimp
-*/
-bool QMdiArea::eventFilter(QObject *object, QEvent *event)
-{
- if (!object)
- return QAbstractScrollArea::eventFilter(object, event);
-
- Q_D(QMdiArea);
- // Global key events with Ctrl modifier.
- if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
-
- QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
- // Ingore key events without a Ctrl modifier (except for press/release on the modifier itself).
-#ifdef Q_WS_MAC
- if (!(keyEvent->modifiers() & Qt::MetaModifier) && keyEvent->key() != Qt::Key_Meta)
-#else
- if (!(keyEvent->modifiers() & Qt::ControlModifier) && keyEvent->key() != Qt::Key_Control)
-#endif
- return QAbstractScrollArea::eventFilter(object, event);
-
- // Find closest mdi area (in case we have a nested workspace).
- QMdiArea *area = mdiAreaParent(static_cast<QWidget *>(object));
- if (!area)
- return QAbstractScrollArea::eventFilter(object, event);
-
- const bool keyPress = (event->type() == QEvent::KeyPress) ? true : false;
-
- // 1) Ctrl-Tab once -> activate the previously active window.
- // 2) Ctrl-Tab (Tab, Tab, ...) -> iterate through all windows (activateNextSubWindow()).
- // 3) Ctrl-Shift-Tab (Tab, Tab, ...) -> iterate through all windows in the opposite
- // direction (activatePreviousSubWindow())
- switch (keyEvent->key()) {
-#ifdef Q_WS_MAC
- case Qt::Key_Meta:
-#else
- case Qt::Key_Control:
-#endif
- if (keyPress)
- area->d_func()->startTabToPreviousTimer();
- else
- area->d_func()->activateHighlightedWindow();
- break;
- case Qt::Key_Tab:
- case Qt::Key_Backtab:
- if (keyPress)
- area->d_func()->highlightNextSubWindow(keyEvent->key() == Qt::Key_Tab ? 1 : -1);
- return true;
-#ifndef QT_NO_RUBBERBAND
- case Qt::Key_Escape:
- area->d_func()->hideRubberBand();
- break;
-#endif
- default:
- break;
- }
- return QAbstractScrollArea::eventFilter(object, event);
- }
-
- QMdiSubWindow *subWindow = qobject_cast<QMdiSubWindow *>(object);
-
- if (!subWindow) {
- // QApplication events:
- if (event->type() == QEvent::ApplicationActivate && !d->active
- && isVisible() && !window()->isMinimized()) {
- d->activateCurrentWindow();
- } else if (event->type() == QEvent::ApplicationDeactivate && d->active) {
- d->setActive(d->active, false, false);
- }
- return QAbstractScrollArea::eventFilter(object, event);
- }
-
- // QMdiSubWindow events:
- switch (event->type()) {
- case QEvent::Move:
- case QEvent::Resize:
- if (d->tileCalledFromResizeEvent)
- break;
- d->updateScrollBars();
- if (!subWindow->isMinimized())
- d->isSubWindowsTiled = false;
- break;
- case QEvent::Show:
-#ifndef QT_NO_TABBAR
- if (d->tabBar) {
- const int tabIndex = d->childWindows.indexOf(subWindow);
- if (!d->tabBar->isTabEnabled(tabIndex))
- d->tabBar->setTabEnabled(tabIndex, true);
- }
-#endif // QT_NO_TABBAR
- // fall through
- case QEvent::Hide:
- d->isSubWindowsTiled = false;
- break;
-#ifndef QT_NO_RUBBERBAND
- case QEvent::Close:
- if (d->childWindows.indexOf(subWindow) == d->indexToHighlighted)
- d->hideRubberBand();
- break;
-#endif
-#ifndef QT_NO_TABBAR
- case QEvent::WindowTitleChange:
- case QEvent::ModifiedChange:
- if (d->tabBar)
- d->tabBar->setTabText(d->childWindows.indexOf(subWindow), tabTextFor(subWindow));
- break;
- case QEvent::WindowIconChange:
- if (d->tabBar)
- d->tabBar->setTabIcon(d->childWindows.indexOf(subWindow), subWindow->windowIcon());
- break;
-#endif // QT_NO_TABBAR
- default:
- break;
- }
- return QAbstractScrollArea::eventFilter(object, event);
-}
-
-/*!
- \reimp
-*/
-void QMdiArea::paintEvent(QPaintEvent *paintEvent)
-{
- Q_D(QMdiArea);
- QPainter painter(d->viewport);
- const QVector<QRect> &exposedRects = paintEvent->region().rects();
- for (int i = 0; i < exposedRects.size(); ++i)
- painter.fillRect(exposedRects.at(i), d->background);
-}
-
-/*!
- This slot is called by QAbstractScrollArea after setViewport() has been
- called. Reimplement this function in a subclass of QMdiArea to
- initialize the new \a viewport before it is used.
-
- \sa setViewport()
-*/
-void QMdiArea::setupViewport(QWidget *viewport)
-{
- Q_D(QMdiArea);
- if (viewport)
- viewport->setAttribute(Qt::WA_OpaquePaintEvent, d->background.isOpaque());
- foreach (QMdiSubWindow *child, d->childWindows) {
- if (!sanityCheck(child, "QMdiArea::setupViewport"))
- continue;
- child->setParent(viewport, child->windowFlags());
- }
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qmdiarea.cpp"
-
-#endif // QT_NO_MDIAREA
diff --git a/src/gui/widgets/qmdiarea.h b/src/gui/widgets/qmdiarea.h
deleted file mode 100644
index a4b357c667..0000000000
--- a/src/gui/widgets/qmdiarea.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/****************************************************************************
-**
-** 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 QMDIAREA_H
-#define QMDIAREA_H
-
-#include <QtGui/qabstractscrollarea.h>
-#include <QtGui/qtabwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_MDIAREA
-
-class QMdiSubWindow;
-
-class QMdiAreaPrivate;
-class Q_GUI_EXPORT QMdiArea : public QAbstractScrollArea
-{
- Q_OBJECT
- Q_ENUMS(ViewMode)
- Q_PROPERTY(QBrush background READ background WRITE setBackground)
- Q_PROPERTY(WindowOrder activationOrder READ activationOrder WRITE setActivationOrder)
- Q_PROPERTY(ViewMode viewMode READ viewMode WRITE setViewMode)
-#ifndef QT_NO_TABBAR
- Q_PROPERTY(bool documentMode READ documentMode WRITE setDocumentMode)
- Q_PROPERTY(bool tabsClosable READ tabsClosable WRITE setTabsClosable)
- Q_PROPERTY(bool tabsMovable READ tabsMovable WRITE setTabsMovable)
-#endif
-#ifndef QT_NO_TABWIDGET
- Q_PROPERTY(QTabWidget::TabShape tabShape READ tabShape WRITE setTabShape)
- Q_PROPERTY(QTabWidget::TabPosition tabPosition READ tabPosition WRITE setTabPosition)
-#endif
- Q_ENUMS(WindowOrder)
-public:
- enum AreaOption {
- DontMaximizeSubWindowOnActivation = 0x1
- };
- Q_DECLARE_FLAGS(AreaOptions, AreaOption)
-
- enum WindowOrder {
- CreationOrder,
- StackingOrder,
- ActivationHistoryOrder
- };
-
- enum ViewMode {
- SubWindowView,
- TabbedView
- };
-
- QMdiArea(QWidget *parent = 0);
- ~QMdiArea();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- QMdiSubWindow *currentSubWindow() const;
- QMdiSubWindow *activeSubWindow() const;
- QList<QMdiSubWindow *> subWindowList(WindowOrder order = CreationOrder) const;
-
- QMdiSubWindow *addSubWindow(QWidget *widget, Qt::WindowFlags flags = 0);
- void removeSubWindow(QWidget *widget);
-
- QBrush background() const;
- void setBackground(const QBrush &background);
-
- WindowOrder activationOrder() const;
- void setActivationOrder(WindowOrder order);
-
- void setOption(AreaOption option, bool on = true);
- bool testOption(AreaOption opton) const;
-
- void setViewMode(ViewMode mode);
- ViewMode viewMode() const;
-
-#ifndef QT_NO_TABBAR
- bool documentMode() const;
- void setDocumentMode(bool enabled);
-
- void setTabsClosable(bool closable);
- bool tabsClosable() const;
-
- void setTabsMovable(bool movable);
- bool tabsMovable() const;
-#endif
-#ifndef QT_NO_TABWIDGET
- void setTabShape(QTabWidget::TabShape shape);
- QTabWidget::TabShape tabShape() const;
-
- void setTabPosition(QTabWidget::TabPosition position);
- QTabWidget::TabPosition tabPosition() const;
-#endif
-
-Q_SIGNALS:
- void subWindowActivated(QMdiSubWindow *);
-
-public Q_SLOTS:
- void setActiveSubWindow(QMdiSubWindow *window);
- void tileSubWindows();
- void cascadeSubWindows();
- void closeActiveSubWindow();
- void closeAllSubWindows();
- void activateNextSubWindow();
- void activatePreviousSubWindow();
-
-protected Q_SLOTS:
- void setupViewport(QWidget *viewport);
-
-protected:
- bool event(QEvent *event);
- bool eventFilter(QObject *object, QEvent *event);
- void paintEvent(QPaintEvent *paintEvent);
- void childEvent(QChildEvent *childEvent);
- void resizeEvent(QResizeEvent *resizeEvent);
- void timerEvent(QTimerEvent *timerEvent);
- void showEvent(QShowEvent *showEvent);
- bool viewportEvent(QEvent *event);
- void scrollContentsBy(int dx, int dy);
-
-private:
- Q_DISABLE_COPY(QMdiArea)
- Q_DECLARE_PRIVATE(QMdiArea)
- Q_PRIVATE_SLOT(d_func(), void _q_deactivateAllWindows())
- Q_PRIVATE_SLOT(d_func(), void _q_processWindowStateChanged(Qt::WindowStates, Qt::WindowStates))
- Q_PRIVATE_SLOT(d_func(), void _q_currentTabChanged(int))
- Q_PRIVATE_SLOT(d_func(), void _q_closeTab(int))
- Q_PRIVATE_SLOT(d_func(), void _q_moveTab(int, int))
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QMdiArea::AreaOptions)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_MDIAREA
-#endif // QMDIAREA_H
diff --git a/src/gui/widgets/qmdiarea_p.h b/src/gui/widgets/qmdiarea_p.h
deleted file mode 100644
index e5e20570d1..0000000000
--- a/src/gui/widgets/qmdiarea_p.h
+++ /dev/null
@@ -1,285 +0,0 @@
-/****************************************************************************
-**
-** 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 QMDIAREA_P_H
-#define QMDIAREA_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmdiarea.h"
-#include "qmdisubwindow.h"
-
-#ifndef QT_NO_MDIAREA
-
-#include <QList>
-#include <QRect>
-#include <QPoint>
-#include <QtGui/qapplication.h>
-#include <private/qmdisubwindow_p.h>
-#include <private/qabstractscrollarea_p.h>
-
-QT_BEGIN_NAMESPACE
-
-namespace QMdi {
-class Rearranger
-{
-public:
- enum Type {
- RegularTiler,
- SimpleCascader,
- IconTiler
- };
-
- // Rearranges widgets relative to domain.
- virtual void rearrange(QList<QWidget *> &widgets, const QRect &domain) const = 0;
- virtual Type type() const = 0;
- virtual ~Rearranger() {}
-};
-
-class RegularTiler : public Rearranger
-{
- // Rearranges widgets according to a regular tiling pattern
- // covering the entire domain.
- // Both positions and sizes may change.
- void rearrange(QList<QWidget *> &widgets, const QRect &domain) const;
- inline Type type() const { return Rearranger::RegularTiler; }
-};
-
-class SimpleCascader : public Rearranger
-{
- // Rearranges widgets according to a simple, regular cascading pattern.
- // Widgets are resized to minimumSize.
- // Both positions and sizes may change.
- void rearrange(QList<QWidget *> &widgets, const QRect &domain) const;
- inline Type type() const { return Rearranger::SimpleCascader; }
-};
-
-class IconTiler : public Rearranger
-{
- // Rearranges icons (assumed to be the same size) according to a regular
- // tiling pattern filling up the domain from the bottom.
- // Only positions may change.
- void rearrange(QList<QWidget *> &widgets, const QRect &domain) const;
- inline Type type() const { return Rearranger::IconTiler; }
-};
-
-class Placer
-{
-public:
- // Places the rectangle defined by 'size' relative to 'rects' and 'domain'.
- // Returns the position of the resulting rectangle.
- virtual QPoint place(
- const QSize &size, const QList<QRect> &rects, const QRect &domain) const = 0;
- virtual ~Placer() {}
-};
-
-class MinOverlapPlacer : public Placer
-{
- QPoint place(const QSize &size, const QList<QRect> &rects, const QRect &domain) const;
- static int accumulatedOverlap(const QRect &source, const QList<QRect> &rects);
- static QRect findMinOverlapRect(const QList<QRect> &source, const QList<QRect> &rects);
- static void getCandidatePlacements(
- const QSize &size, const QList<QRect> &rects, const QRect &domain,
- QList<QRect> &candidates);
- static QPoint findBestPlacement(
- const QRect &domain, const QList<QRect> &rects, QList<QRect> &source);
- static void findNonInsiders(
- const QRect &domain, QList<QRect> &source, QList<QRect> &result);
- static void findMaxOverlappers(
- const QRect &domain, const QList<QRect> &source, QList<QRect> &result);
-};
-} // namespace QMdi
-
-class QMdiAreaTabBar;
-class QMdiAreaPrivate : public QAbstractScrollAreaPrivate
-{
- Q_DECLARE_PUBLIC(QMdiArea)
-public:
- QMdiAreaPrivate();
-
- // Variables.
- QMdi::Rearranger *cascader;
- QMdi::Rearranger *regularTiler;
- QMdi::Rearranger *iconTiler;
- QMdi::Placer *placer;
-#ifndef QT_NO_RUBBERBAND
- QRubberBand *rubberBand;
-#endif
- QMdiAreaTabBar *tabBar;
- QList<QMdi::Rearranger *> pendingRearrangements;
- QList< QPointer<QMdiSubWindow> > pendingPlacements;
- QList< QPointer<QMdiSubWindow> > childWindows;
- QList<int> indicesToActivatedChildren;
- QPointer<QMdiSubWindow> active;
- QPointer<QMdiSubWindow> aboutToBecomeActive;
- QBrush background;
- QMdiArea::WindowOrder activationOrder;
- QMdiArea::AreaOptions options;
- QMdiArea::ViewMode viewMode;
-#ifndef QT_NO_TABBAR
- bool documentMode;
- bool tabsClosable;
- bool tabsMovable;
-#endif
-#ifndef QT_NO_TABWIDGET
- QTabWidget::TabShape tabShape;
- QTabWidget::TabPosition tabPosition;
-#endif
- bool ignoreGeometryChange;
- bool ignoreWindowStateChange;
- bool isActivated;
- bool isSubWindowsTiled;
- bool showActiveWindowMaximized;
- bool tileCalledFromResizeEvent;
- bool updatesDisabledByUs;
- bool inViewModeChange;
- int indexToNextWindow;
- int indexToPreviousWindow;
- int indexToHighlighted;
- int indexToLastActiveTab;
- int resizeTimerId;
- int tabToPreviousTimerId;
-
- // Slots.
- void _q_deactivateAllWindows(QMdiSubWindow *aboutToActivate = 0);
- void _q_processWindowStateChanged(Qt::WindowStates oldState, Qt::WindowStates newState);
- void _q_currentTabChanged(int index);
- void _q_closeTab(int index);
- void _q_moveTab(int from, int to);
-
- // Functions.
- void appendChild(QMdiSubWindow *child);
- void place(QMdi::Placer *placer, QMdiSubWindow *child);
- void rearrange(QMdi::Rearranger *rearranger);
- void arrangeMinimizedSubWindows();
- void activateWindow(QMdiSubWindow *child);
- void activateCurrentWindow();
- void activateHighlightedWindow();
- void emitWindowActivated(QMdiSubWindow *child);
- void resetActiveWindow(QMdiSubWindow *child = 0);
- void updateActiveWindow(int removedIndex, bool activeRemoved);
- void updateScrollBars();
- void internalRaise(QMdiSubWindow *child) const;
- bool scrollBarsEnabled() const;
- bool lastWindowAboutToBeDestroyed() const;
- void setChildActivationEnabled(bool enable = true, bool onlyNextActivationEvent = false) const;
- QRect resizeToMinimumTileSize(const QSize &minSubWindowSize, int subWindowCount);
- void scrollBarPolicyChanged(Qt::Orientation, Qt::ScrollBarPolicy); // reimp
- QMdiSubWindow *nextVisibleSubWindow(int increaseFactor, QMdiArea::WindowOrder,
- int removed = -1, int fromIndex = -1) const;
- void highlightNextSubWindow(int increaseFactor);
- QList<QMdiSubWindow *> subWindowList(QMdiArea::WindowOrder, bool reversed = false) const;
- void disconnectSubWindow(QObject *subWindow);
- void setViewMode(QMdiArea::ViewMode mode);
-#ifndef QT_NO_TABBAR
- void updateTabBarGeometry();
- void refreshTabBar();
-#endif
-
- inline void startResizeTimer()
- {
- Q_Q(QMdiArea);
- if (resizeTimerId > 0)
- q->killTimer(resizeTimerId);
- resizeTimerId = q->startTimer(200);
- }
-
- inline void startTabToPreviousTimer()
- {
- Q_Q(QMdiArea);
- if (tabToPreviousTimerId > 0)
- q->killTimer(tabToPreviousTimerId);
- tabToPreviousTimerId = q->startTimer(QApplication::keyboardInputInterval());
- }
-
- inline bool windowStaysOnTop(QMdiSubWindow *subWindow) const
- {
- if (!subWindow)
- return false;
- return subWindow->windowFlags() & Qt::WindowStaysOnTopHint;
- }
-
- inline bool isExplicitlyDeactivated(QMdiSubWindow *subWindow) const
- {
- if (!subWindow)
- return true;
- return subWindow->d_func()->isExplicitlyDeactivated;
- }
-
- inline void setActive(QMdiSubWindow *subWindow, bool active = true, bool changeFocus = true) const
- {
- if (subWindow)
- subWindow->d_func()->setActive(active, changeFocus);
- }
-
-#ifndef QT_NO_RUBBERBAND
- inline void showRubberBandFor(QMdiSubWindow *subWindow)
- {
- if (!subWindow || !rubberBand)
- return;
- rubberBand->setGeometry(subWindow->geometry());
- rubberBand->raise();
- rubberBand->show();
- }
-
- inline void hideRubberBand()
- {
- if (rubberBand && rubberBand->isVisible())
- rubberBand->hide();
- indexToHighlighted = -1;
- }
-#endif // QT_NO_RUBBERBAND
-};
-
-#endif // QT_NO_MDIAREA
-
-QT_END_NAMESPACE
-
-#endif // QMDIAREA_P_H
diff --git a/src/gui/widgets/qmdisubwindow.cpp b/src/gui/widgets/qmdisubwindow.cpp
deleted file mode 100644
index 6f2b67608c..0000000000
--- a/src/gui/widgets/qmdisubwindow.cpp
+++ /dev/null
@@ -1,3547 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-/*!
- \class QMdiSubWindow
- \brief The QMdiSubWindow class provides a subwindow class for
- QMdiArea.
- \since 4.3
- \ingroup mainwindow-classes
-
-
- QMdiSubWindow represents a top-level window in a QMdiArea, and consists
- of a title bar with window decorations, an internal widget, and
- (depending on the current style) a window frame and a size
- grip. QMdiSubWindow has its own layout, which consists of the
- title bar and a center area for the internal widget.
-
- \image qmdisubwindowlayout.png
-
- The most common way to construct a QMdiSubWindow is to call
- QMdiArea::addSubWindow() with the internal widget as the argument.
- You can also create a subwindow yourself, and set an internal
- widget by calling setWidget().
-
- You use the same API when programming with subwindows as with
- regular top-level windows (e.g., you can call functions such as
- show(), hide(), showMaximized(), and setWindowTitle()).
-
- \section1 Subwindow Handling
-
- QMdiSubWindow also supports behavior specific to subwindows in
- an MDI area.
-
- By default, each QMdiSubWindow is visible inside the MDI area
- viewport when moved around, but it is also possible to specify
- transparent window movement and resizing behavior, where only
- the outline of a subwindow is updated during these operations.
- The setOption() function is used to enable this behavior.
-
- The isShaded() function detects whether the subwindow is
- currently shaded (i.e., the window is collapsed so that only the
- title bar is visible). To enter shaded mode, call showShaded().
- QMdiSubWindow emits the windowStateChanged() signal whenever the
- window state has changed (e.g., when the window becomes minimized,
- or is restored). It also emits aboutToActivate() before it is
- activated.
-
- In keyboard-interactive mode, the windows are moved and resized
- with the keyboard. You can enter this mode through the system menu
- of the window. The keyboardSingleStep and keyboardPageStep
- properties control the distance the widget is moved or resized for
- each keypress event. When shift is pressed down page step is used;
- otherwise single step is used.
-
- You can also change the active window with the keyboard. By
- pressing the control and tab keys at the same time, the next
- (using the current \l{QMdiArea::}{WindowOrder}) subwindow will be
- activated. By pressing control, shift, and tab, you will activate
- the previous window. This is equivalent to calling
- \l{QMdiArea::}{activateNextSubWindow()} and
- \l{QMdiArea::}{activatePreviousSubWindow()}. Note that these
- shortcuts overrides global shortcuts, but not the \l{QMdiArea}s
- shortcuts.
-
- \sa QMdiArea
-*/
-
-/*!
- \enum QMdiSubWindow::SubWindowOption
-
- This enum describes options that customize the behavior
- of QMdiSubWindow.
-
- \omitvalue AllowOutsideAreaHorizontally
- \omitvalue AllowOutsideAreaVertically
-
- \value RubberBandResize If you enable this option, a rubber band
- control is used to represent the subwindow's outline, and the user
- resizes this instead of the subwindow itself.
- As a result, the subwindow maintains its original position and size
- until the resize operation has been completed, at which time it will
- receive a single QResizeEvent.
- By default, this option is disabled.
-
- \value RubberBandMove If you enable this option, a rubber band
- control is used to represent the subwindow's outline, and the user
- moves this instead of the subwindow itself.
- As a result, the subwindow remains in its original position until
- the move operation has completed, at which time a QMoveEvent is
- sent to the window. By default, this option is disabled.
-*/
-
-/*!
- \fn QMdiSubWindow::windowStateChanged(Qt::WindowStates oldState, Qt::WindowStates newState)
-
- QMdiSubWindow emits this signal after the window state changes. \a
- oldState is the window state before it changed, and \a newState is the
- new, current state.
-*/
-
-/*!
- \fn QMdiSubWindow::aboutToActivate()
-
- QMdiSubWindow emits this signal immediately before it is
- activated. After the subwindow has been activated, the QMdiArea that
- manages the subwindow will also emit the
- \l{QMdiArea::}{subWindowActivated()} signal.
-
- \sa QMdiArea::subWindowActivated()
-*/
-
-#include "qmdisubwindow_p.h"
-
-#ifndef QT_NO_MDIAREA
-
-#include <QApplication>
-#include <QStylePainter>
-#include <QVBoxLayout>
-#include <QMouseEvent>
-#include <QWhatsThis>
-#include <QToolTip>
-#include <QMainWindow>
-#include <QScrollBar>
-#include <QDebug>
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-#include <QMacStyle>
-#endif
-#include <QMdiArea>
-
-QT_BEGIN_NAMESPACE
-
-using namespace QMdi;
-
-static const QStyle::SubControl SubControls[] =
-{
- QStyle::SC_TitleBarLabel, // 1
- QStyle::SC_TitleBarSysMenu, // 2
- QStyle::SC_TitleBarMinButton, // 3
- QStyle::SC_TitleBarMaxButton, // 4
- QStyle::SC_TitleBarShadeButton, // 5
- QStyle::SC_TitleBarCloseButton, // 6
- QStyle::SC_TitleBarNormalButton, // 7
- QStyle::SC_TitleBarUnshadeButton, // 8
- QStyle::SC_TitleBarContextHelpButton // 9
-};
-static const int NumSubControls = sizeof(SubControls) / sizeof(SubControls[0]);
-
-static const QStyle::StandardPixmap ButtonPixmaps[] =
-{
- QStyle::SP_TitleBarMinButton,
- QStyle::SP_TitleBarNormalButton,
- QStyle::SP_TitleBarCloseButton
-};
-static const int NumButtonPixmaps = sizeof(ButtonPixmaps) / sizeof(ButtonPixmaps[0]);
-
-static const Qt::WindowFlags CustomizeWindowFlags =
- Qt::FramelessWindowHint
- | Qt::CustomizeWindowHint
- | Qt::WindowTitleHint
- | Qt::WindowSystemMenuHint
- | Qt::WindowMinimizeButtonHint
- | Qt::WindowMaximizeButtonHint
- | Qt::WindowMinMaxButtonsHint;
-
-
-static const int BoundaryMargin = 5;
-
-static inline int getMoveDeltaComponent(uint cflags, uint moveFlag, uint resizeFlag,
- int delta, int maxDelta, int minDelta)
-{
- if (cflags & moveFlag) {
- if (delta > 0)
- return (cflags & resizeFlag) ? qMin(delta, maxDelta) : delta;
- return (cflags & resizeFlag) ? qMax(delta, minDelta) : delta;
- }
- return 0;
-}
-
-static inline int getResizeDeltaComponent(uint cflags, uint resizeFlag,
- uint resizeReverseFlag, int delta)
-{
- if (cflags & resizeFlag) {
- if (cflags & resizeReverseFlag)
- return -delta;
- return delta;
- }
- return 0;
-}
-
-static inline bool isChildOfQMdiSubWindow(const QWidget *child)
-{
- Q_ASSERT(child);
- QWidget *parent = child->parentWidget();
- while (parent) {
- if (qobject_cast<QMdiSubWindow *>(parent))
- return true;
- parent = parent->parentWidget();
- }
- return false;
-}
-
-static inline bool isChildOfTabbedQMdiArea(const QMdiSubWindow *child)
-{
- Q_ASSERT(child);
- if (QMdiArea *mdiArea = child->mdiArea()) {
- if (mdiArea->viewMode() == QMdiArea::TabbedView)
- return true;
- }
- return false;
-}
-
-template<typename T>
-static inline ControlElement<T> *ptr(QWidget *widget)
-{
- if (widget && widget->qt_metacast("ControlElement")
- && strcmp(widget->metaObject()->className(), T::staticMetaObject.className()) == 0) {
- return static_cast<ControlElement<T> *>(widget);
- }
- return 0;
-}
-
-QString QMdiSubWindowPrivate::originalWindowTitle()
-{
- Q_Q(QMdiSubWindow);
- if (originalTitle.isNull()) {
- originalTitle = q->window()->windowTitle();
- if (originalTitle.isNull())
- originalTitle = QLatin1String("");
- }
- return originalTitle;
-}
-
-void QMdiSubWindowPrivate::setNewWindowTitle()
-{
- Q_Q(QMdiSubWindow);
- QString childTitle = q->windowTitle();
- if (childTitle.isEmpty())
- return;
- QString original = originalWindowTitle();
- if (!original.isEmpty()) {
- if (!original.contains(QMdiSubWindow::tr("- [%1]").arg(childTitle)))
- q->window()->setWindowTitle(QMdiSubWindow::tr("%1 - [%2]").arg(original, childTitle));
-
- } else {
- q->window()->setWindowTitle(childTitle);
- }
-}
-
-static inline bool isHoverControl(QStyle::SubControl control)
-{
- return control != QStyle::SC_None && control != QStyle::SC_TitleBarLabel;
-}
-
-#if defined(Q_WS_WIN)
-static inline QRgb colorref2qrgb(COLORREF col)
-{
- return qRgb(GetRValue(col),GetGValue(col),GetBValue(col));
-}
-#endif
-
-#ifndef QT_NO_TOOLTIP
-static void showToolTip(QHelpEvent *helpEvent, QWidget *widget, const QStyleOptionComplex &opt,
- QStyle::ComplexControl complexControl, QStyle::SubControl subControl)
-{
- Q_ASSERT(helpEvent);
- Q_ASSERT(helpEvent->type() == QEvent::ToolTip);
- Q_ASSERT(widget);
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- // Native Mac windows don't show tool tip.
- if (qobject_cast<QMacStyle *>(widget->style()))
- return;
-#endif
-
- // Convert CC_MdiControls to CC_TitleBar. Sub controls of different complex
- // controls cannot be in the same switch as they might have the same value.
- if (complexControl == QStyle::CC_MdiControls) {
- if (subControl == QStyle::SC_MdiMinButton)
- subControl = QStyle::SC_TitleBarMinButton;
- else if (subControl == QStyle::SC_MdiCloseButton)
- subControl = QStyle::SC_TitleBarCloseButton;
- else if (subControl == QStyle::SC_MdiNormalButton)
- subControl = QStyle::SC_TitleBarNormalButton;
- else
- subControl = QStyle::SC_None;
- }
-
- // Don't change the tooltip for the base widget itself.
- if (subControl == QStyle::SC_None)
- return;
-
- QString toolTip;
-
- switch (subControl) {
- case QStyle::SC_TitleBarMinButton:
- toolTip = QMdiSubWindow::tr("Minimize");
- break;
- case QStyle::SC_TitleBarMaxButton:
- toolTip = QMdiSubWindow::tr("Maximize");
- break;
- case QStyle::SC_TitleBarUnshadeButton:
- toolTip = QMdiSubWindow::tr("Unshade");
- break;
- case QStyle::SC_TitleBarShadeButton:
- toolTip = QMdiSubWindow::tr("Shade");
- break;
- case QStyle::SC_TitleBarNormalButton:
- if (widget->isMaximized() || !qobject_cast<QMdiSubWindow *>(widget))
- toolTip = QMdiSubWindow::tr("Restore Down");
- else
- toolTip = QMdiSubWindow::tr("Restore");
- break;
- case QStyle::SC_TitleBarCloseButton:
- toolTip = QMdiSubWindow::tr("Close");
- break;
- case QStyle::SC_TitleBarContextHelpButton:
- toolTip = QMdiSubWindow::tr("Help");
- break;
- case QStyle::SC_TitleBarSysMenu:
- toolTip = QMdiSubWindow::tr("Menu");
- break;
- default:
- break;
- }
-
- const QRect rect = widget->style()->subControlRect(complexControl, &opt, subControl, widget);
- QToolTip::showText(helpEvent->globalPos(), toolTip, widget, rect);
-}
-#endif // QT_NO_TOOLTIP
-
-namespace QMdi {
-/*
- \class ControlLabel
- \internal
-*/
-class ControlLabel : public QWidget
-{
- Q_OBJECT
-public:
- ControlLabel(QMdiSubWindow *subWindow, QWidget *parent = 0);
-
- QSize sizeHint() const;
-
-signals:
- void _q_clicked();
- void _q_doubleClicked();
-
-protected:
- bool event(QEvent *event);
- void paintEvent(QPaintEvent *paintEvent);
- void mousePressEvent(QMouseEvent *mouseEvent);
- void mouseDoubleClickEvent(QMouseEvent *mouseEvent);
- void mouseReleaseEvent(QMouseEvent *mouseEvent);
-
-private:
- QPixmap label;
- bool isPressed;
- void updateWindowIcon();
-};
-} // namespace QMdi
-
-ControlLabel::ControlLabel(QMdiSubWindow *subWindow, QWidget *parent)
- : QWidget(parent), isPressed(false)
-{
- Q_UNUSED(subWindow);
- setFocusPolicy(Qt::NoFocus);
- updateWindowIcon();
- setFixedSize(label.size());
-}
-
-/*
- \internal
-*/
-QSize ControlLabel::sizeHint() const
-{
- return label.size();
-}
-
-/*
- \internal
-*/
-bool ControlLabel::event(QEvent *event)
-{
- if (event->type() == QEvent::WindowIconChange)
- updateWindowIcon();
-#ifndef QT_NO_TOOLTIP
- else if (event->type() == QEvent::ToolTip) {
- QStyleOptionTitleBar options;
- options.initFrom(this);
- showToolTip(static_cast<QHelpEvent *>(event), this, options,
- QStyle::CC_TitleBar, QStyle::SC_TitleBarSysMenu);
- }
-#endif
- return QWidget::event(event);
-}
-
-/*
- \internal
-*/
-void ControlLabel::paintEvent(QPaintEvent * /*paintEvent*/)
-{
- QPainter painter(this);
- painter.drawPixmap(0, 0, label);
-}
-
-/*
- \internal
-*/
-void ControlLabel::mousePressEvent(QMouseEvent *mouseEvent)
-{
- if (mouseEvent->button() != Qt::LeftButton) {
- mouseEvent->ignore();
- return;
- }
- isPressed = true;
-}
-
-/*
- \internal
-*/
-void ControlLabel::mouseDoubleClickEvent(QMouseEvent *mouseEvent)
-{
- if (mouseEvent->button() != Qt::LeftButton) {
- mouseEvent->ignore();
- return;
- }
- isPressed = false;
- emit _q_doubleClicked();
-}
-
-/*
- \internal
-*/
-void ControlLabel::mouseReleaseEvent(QMouseEvent *mouseEvent)
-{
- if (mouseEvent->button() != Qt::LeftButton) {
- mouseEvent->ignore();
- return;
- }
- if (isPressed) {
- isPressed = false;
- emit _q_clicked();
- }
-}
-
-/*
- \internal
-*/
-void ControlLabel::updateWindowIcon()
-{
- QIcon menuIcon = windowIcon();
- if (menuIcon.isNull())
- menuIcon = style()->standardIcon(QStyle::SP_TitleBarMenuButton, 0, parentWidget());
- label = menuIcon.pixmap(16, 16);
- update();
-}
-
-namespace QMdi {
-/*
- \class ControllerWidget
- \internal
-*/
-class ControllerWidget : public QWidget
-{
- Q_OBJECT
-public:
- ControllerWidget(QMdiSubWindow *subWindow, QWidget *parent = 0);
- QSize sizeHint() const;
- void setControlVisible(QMdiSubWindowPrivate::WindowStateAction action, bool visible);
- inline bool hasVisibleControls() const
- {
- return (visibleControls & QStyle::SC_MdiMinButton)
- || (visibleControls & QStyle::SC_MdiNormalButton)
- || (visibleControls & QStyle::SC_MdiCloseButton);
- }
-
-signals:
- void _q_minimize();
- void _q_restore();
- void _q_close();
-
-protected:
- void paintEvent(QPaintEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void leaveEvent(QEvent *event);
- bool event(QEvent *event);
-
-private:
- QStyle::SubControl activeControl;
- QStyle::SubControl hoverControl;
- QStyle::SubControls visibleControls;
- void initStyleOption(QStyleOptionComplex *option) const;
- QMdiArea *mdiArea;
- inline QStyle::SubControl getSubControl(const QPoint &pos) const
- {
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- return style()->hitTestComplexControl(QStyle::CC_MdiControls, &opt, pos, mdiArea);
- }
-};
-} // namespace QMdi
-
-/*
- \internal
-*/
-ControllerWidget::ControllerWidget(QMdiSubWindow *subWindow, QWidget *parent)
- : QWidget(parent),
- activeControl(QStyle::SC_None),
- hoverControl(QStyle::SC_None),
- visibleControls(QStyle::SC_None),
- mdiArea(0)
-{
- if (subWindow->parentWidget())
- mdiArea = qobject_cast<QMdiArea *>(subWindow->parentWidget()->parentWidget());
- setFocusPolicy(Qt::NoFocus);
- setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
- setMouseTracking(true);
-}
-
-/*
- \internal
-*/
-QSize ControllerWidget::sizeHint() const
-{
- ensurePolished();
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- QSize size(48, 16);
- return style()->sizeFromContents(QStyle::CT_MdiControls, &opt, size, mdiArea);
-}
-
-void ControllerWidget::setControlVisible(QMdiSubWindowPrivate::WindowStateAction action, bool visible)
-{
- QStyle::SubControl subControl = QStyle::SC_None;
-
- // Map action from QMdiSubWindowPrivate::WindowStateAction to QStyle::SubControl.
- if (action == QMdiSubWindowPrivate::MaximizeAction)
- subControl = QStyle::SC_MdiNormalButton;
- else if (action == QMdiSubWindowPrivate::CloseAction)
- subControl = QStyle::SC_MdiCloseButton;
- else if (action == QMdiSubWindowPrivate::MinimizeAction)
- subControl = QStyle::SC_MdiMinButton;
-
- if (subControl == QStyle::SC_None)
- return;
-
- if (visible && !(visibleControls & subControl))
- visibleControls |= subControl;
- else if (!visible && (visibleControls & subControl))
- visibleControls &= ~subControl;
-}
-
-/*
- \internal
-*/
-void ControllerWidget::paintEvent(QPaintEvent * /*paintEvent*/)
-{
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- if (activeControl == hoverControl) {
- opt.activeSubControls = activeControl;
- opt.state |= QStyle::State_Sunken;
- } else if (hoverControl != QStyle::SC_None && (activeControl == QStyle::SC_None)) {
- opt.activeSubControls = hoverControl;
- opt.state |= QStyle::State_MouseOver;
- }
- QPainter painter(this);
- style()->drawComplexControl(QStyle::CC_MdiControls, &opt, &painter, mdiArea);
-}
-
-/*
- \internal
-*/
-void ControllerWidget::mousePressEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
- activeControl = getSubControl(event->pos());
- update();
-}
-
-/*
- \internal
-*/
-void ControllerWidget::mouseReleaseEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
-
- QStyle::SubControl under_mouse = getSubControl(event->pos());
- if (under_mouse == activeControl) {
- switch (activeControl) {
- case QStyle::SC_MdiCloseButton:
- emit _q_close();
- break;
- case QStyle::SC_MdiNormalButton:
- emit _q_restore();
- break;
- case QStyle::SC_MdiMinButton:
- emit _q_minimize();
- break;
- default:
- break;
- }
- }
-
- activeControl = QStyle::SC_None;
- update();
-}
-
-/*
- \internal
-*/
-void ControllerWidget::mouseMoveEvent(QMouseEvent *event)
-{
- QStyle::SubControl under_mouse = getSubControl(event->pos());
- //test if hover state changes
- if (hoverControl != under_mouse) {
- hoverControl = under_mouse;
- update();
- }
-}
-
-/*
- \internal
-*/
-void ControllerWidget::leaveEvent(QEvent * /*event*/)
-{
- hoverControl = QStyle::SC_None;
- update();
-}
-
-/*
- \internal
-*/
-bool ControllerWidget::event(QEvent *event)
-{
-#ifndef QT_NO_TOOLTIP
- if (event->type() == QEvent::ToolTip) {
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
- showToolTip(helpEvent, this, opt, QStyle::CC_MdiControls, getSubControl(helpEvent->pos()));
- }
-#endif // QT_NO_TOOLTIP
- return QWidget::event(event);
-}
-
-/*
- \internal
-*/
-void ControllerWidget::initStyleOption(QStyleOptionComplex *option) const
-{
- option->initFrom(this);
- option->subControls = visibleControls;
- option->activeSubControls = QStyle::SC_None;
-}
-
-/*
- \internal
-*/
-ControlContainer::ControlContainer(QMdiSubWindow *mdiChild)
- : QObject(mdiChild),
- previousLeft(0),
- previousRight(0),
-#ifndef QT_NO_MENUBAR
- m_menuBar(0),
-#endif
- mdiChild(mdiChild)
-{
- Q_ASSERT(mdiChild);
-
- m_controllerWidget = new ControlElement<ControllerWidget>(mdiChild);
- connect(m_controllerWidget, SIGNAL(_q_close()), mdiChild, SLOT(close()));
- connect(m_controllerWidget, SIGNAL(_q_restore()), mdiChild, SLOT(showNormal()));
- connect(m_controllerWidget, SIGNAL(_q_minimize()), mdiChild, SLOT(showMinimized()));
-
- m_menuLabel = new ControlElement<ControlLabel>(mdiChild);
- m_menuLabel->setWindowIcon(mdiChild->windowIcon());
-#ifndef QT_NO_MENU
- connect(m_menuLabel, SIGNAL(_q_clicked()), mdiChild, SLOT(showSystemMenu()));
-#endif
- connect(m_menuLabel, SIGNAL(_q_doubleClicked()), mdiChild, SLOT(close()));
-}
-
-ControlContainer::~ControlContainer()
-{
-#ifndef QT_NO_MENUBAR
- removeButtonsFromMenuBar();
-#endif
- delete m_menuLabel;
- m_menuLabel = 0;
- delete m_controllerWidget;
- m_controllerWidget = 0;
-}
-
-#ifndef QT_NO_MENUBAR
-/*
- \internal
-*/
-QMenuBar *QMdiSubWindowPrivate::menuBar() const
-{
-#if defined(QT_NO_MAINWINDOW)
- return 0;
-#else
- Q_Q(const QMdiSubWindow);
- if (!q->isMaximized() || drawTitleBarWhenMaximized() || isChildOfTabbedQMdiArea(q))
- return 0;
-
- if (QMainWindow *mainWindow = qobject_cast<QMainWindow *>(q->window()))
- return mainWindow->menuBar();
-
- return 0;
-#endif
-}
-
-/*
- \internal
-*/
-void ControlContainer::showButtonsInMenuBar(QMenuBar *menuBar)
-{
- if (!menuBar || !mdiChild || mdiChild->windowFlags() & Qt::FramelessWindowHint)
- return;
- m_menuBar = menuBar;
-
- if (m_menuLabel && mdiChild->windowFlags() & Qt::WindowSystemMenuHint) {
- QWidget *currentLeft = menuBar->cornerWidget(Qt::TopLeftCorner);
- if (currentLeft)
- currentLeft->hide();
- if (currentLeft != m_menuLabel) {
- menuBar->setCornerWidget(m_menuLabel, Qt::TopLeftCorner);
- previousLeft = currentLeft;
- }
- m_menuLabel->show();
- }
- ControllerWidget *controllerWidget = qobject_cast<ControllerWidget *>(m_controllerWidget);
- if (controllerWidget && controllerWidget->hasVisibleControls()) {
- QWidget *currentRight = menuBar->cornerWidget(Qt::TopRightCorner);
- if (currentRight)
- currentRight->hide();
- if (currentRight != m_controllerWidget) {
- menuBar->setCornerWidget(m_controllerWidget, Qt::TopRightCorner);
- previousRight = currentRight;
- }
- m_controllerWidget->show();
- }
- mdiChild->d_func()->setNewWindowTitle();
-}
-
-/*
- \internal
-*/
-void ControlContainer::removeButtonsFromMenuBar(QMenuBar *menuBar)
-{
- if (menuBar && menuBar != m_menuBar) {
- // m_menubar was deleted while sub-window was maximized
- previousRight = 0;
- previousLeft = 0;
- m_menuBar = menuBar;
- }
-
- if (!m_menuBar || !mdiChild || qt_widget_private(mdiChild->window())->data.in_destructor)
- return;
-
- QMdiSubWindow *child = 0;
- if (m_controllerWidget) {
- QWidget *currentRight = m_menuBar->cornerWidget(Qt::TopRightCorner);
- if (currentRight == m_controllerWidget) {
- if (ControlElement<ControllerWidget> *ce = ptr<ControllerWidget>(previousRight)) {
- if (!ce->mdiChild || !ce->mdiChild->isMaximized())
- previousRight = 0;
- else
- child = ce->mdiChild;
- }
- m_menuBar->setCornerWidget(previousRight, Qt::TopRightCorner);
- if (previousRight) {
- previousRight->show();
- previousRight = 0;
- }
- }
- m_controllerWidget->hide();
- m_controllerWidget->setParent(0);
- }
- if (m_menuLabel) {
- QWidget *currentLeft = m_menuBar->cornerWidget(Qt::TopLeftCorner);
- if (currentLeft == m_menuLabel) {
- if (ControlElement<ControlLabel> *ce = ptr<ControlLabel>(previousLeft)) {
- if (!ce->mdiChild || !ce->mdiChild->isMaximized())
- previousLeft = 0;
- else if (!child)
- child = mdiChild;
- }
- m_menuBar->setCornerWidget(previousLeft, Qt::TopLeftCorner);
- if (previousLeft) {
- previousLeft->show();
- previousLeft = 0;
- }
- }
- m_menuLabel->hide();
- m_menuLabel->setParent(0);
- }
- m_menuBar->update();
- if (child)
- child->d_func()->setNewWindowTitle();
- else if (mdiChild)
- mdiChild->window()->setWindowTitle(mdiChild->d_func()->originalWindowTitle());
-}
-
-#endif // QT_NO_MENUBAR
-
-void ControlContainer::updateWindowIcon(const QIcon &windowIcon)
-{
- if (m_menuLabel)
- m_menuLabel->setWindowIcon(windowIcon);
-}
-
-/*!
- \internal
-*/
-QMdiSubWindowPrivate::QMdiSubWindowPrivate()
- : baseWidget(0),
- restoreFocusWidget(0),
- controlContainer(0),
-#ifndef QT_NO_SIZEGRIP
- sizeGrip(0),
-#endif
-#ifndef QT_NO_RUBBERBAND
- rubberBand(0),
-#endif
- userMinimumSize(0,0),
- resizeEnabled(true),
- moveEnabled(true),
- isInInteractiveMode(false),
-#ifndef QT_NO_RUBBERBAND
- isInRubberBandMode(false),
-#endif
- isShadeMode(false),
- ignoreWindowTitleChange(false),
- ignoreNextActivationEvent(false),
- activationEnabled(true),
- isShadeRequestFromMinimizeMode(false),
- isMaximizeMode(false),
- isWidgetHiddenByUs(false),
- isActive(false),
- isExplicitlyDeactivated(false),
- keyboardSingleStep(5),
- keyboardPageStep(20),
- resizeTimerId(-1),
- currentOperation(None),
- hoveredSubControl(QStyle::SC_None),
- activeSubControl(QStyle::SC_None),
- focusInReason(Qt::ActiveWindowFocusReason)
-{
- initOperationMap();
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::_q_updateStaysOnTopHint()
-{
-#ifndef QT_NO_ACTION
- Q_Q(QMdiSubWindow);
- if (QAction *senderAction = qobject_cast<QAction *>(q->sender())) {
- if (senderAction->isChecked()) {
- q->setWindowFlags(q->windowFlags() | Qt::WindowStaysOnTopHint);
- q->raise();
- } else {
- q->setWindowFlags(q->windowFlags() & ~Qt::WindowStaysOnTopHint);
- q->lower();
- }
- }
-#endif // QT_NO_ACTION
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::_q_enterInteractiveMode()
-{
-#ifndef QT_NO_ACTION
- Q_Q(QMdiSubWindow);
- QAction *action = qobject_cast<QAction *>(q->sender());
- if (!action)
- return;
-
- QPoint pressPos;
- if (actions[MoveAction] && actions[MoveAction] == action) {
- currentOperation = Move;
- pressPos = QPoint(q->width() / 2, titleBarHeight() - 1);
- } else if (actions[ResizeAction] && actions[ResizeAction] == action) {
- currentOperation = q->isLeftToRight() ? BottomRightResize : BottomLeftResize;
- int offset = q->style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, q) / 2;
- int x = q->isLeftToRight() ? q->width() - offset : offset;
- pressPos = QPoint(x, q->height() - offset);
- } else {
- return;
- }
-
- updateCursor();
-#ifndef QT_NO_CURSOR
- q->cursor().setPos(q->mapToGlobal(pressPos));
-#endif
- mousePressPosition = q->mapToParent(pressPos);
- oldGeometry = q->geometry();
- isInInteractiveMode = true;
- q->setFocus();
-#ifndef QT_NO_RUBBERBAND
- if ((q->testOption(QMdiSubWindow::RubberBandResize)
- && (currentOperation == BottomRightResize || currentOperation == BottomLeftResize))
- || (q->testOption(QMdiSubWindow::RubberBandMove) && currentOperation == Move)) {
- enterRubberBandMode();
- } else
-#endif // QT_NO_RUBBERBAND
- {
- q->grabMouse();
- }
-#endif // QT_NO_ACTION
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::_q_processFocusChanged(QWidget *old, QWidget *now)
-{
- Q_UNUSED(old);
- Q_Q(QMdiSubWindow);
- if (now && (now == q || q->isAncestorOf(now))) {
- if (now == q && !isInInteractiveMode)
- setFocusWidget();
- setActive(true);
- }
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::leaveInteractiveMode()
-{
- Q_Q(QMdiSubWindow);
-#ifndef QT_NO_RUBBERBAND
- if (isInRubberBandMode)
- leaveRubberBandMode();
- else
-#endif
- q->releaseMouse();
- isInInteractiveMode = false;
- currentOperation = None;
- updateDirtyRegions();
- updateCursor();
- if (baseWidget && baseWidget->focusWidget())
- baseWidget->focusWidget()->setFocus();
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::removeBaseWidget()
-{
- if (!baseWidget)
- return;
-
- Q_Q(QMdiSubWindow);
- baseWidget->removeEventFilter(q);
- if (layout)
- layout->removeWidget(baseWidget);
- if (baseWidget->windowTitle() == q->windowTitle()) {
- ignoreWindowTitleChange = true;
- q->setWindowTitle(QString());
- ignoreWindowTitleChange = false;
- q->setWindowModified(false);
- }
- lastChildWindowTitle.clear();
- baseWidget->setParent(0);
- baseWidget = 0;
- isWidgetHiddenByUs = false;
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::initOperationMap()
-{
- operationMap.insert(Move, OperationInfo(HMove | VMove, Qt::ArrowCursor, false));
- operationMap.insert(TopResize, OperationInfo(VMove | VResize | VResizeReverse, Qt::SizeVerCursor));
- operationMap.insert(BottomResize, OperationInfo(VResize, Qt::SizeVerCursor));
- operationMap.insert(LeftResize, OperationInfo(HMove | HResize | HResizeReverse, Qt::SizeHorCursor));
- operationMap.insert(RightResize, OperationInfo(HResize, Qt::SizeHorCursor));
- operationMap.insert(TopLeftResize, OperationInfo(HMove | VMove | HResize | VResize | VResizeReverse
- | HResizeReverse, Qt::SizeFDiagCursor));
- operationMap.insert(TopRightResize, OperationInfo(VMove | HResize | VResize
- | VResizeReverse, Qt::SizeBDiagCursor));
- operationMap.insert(BottomLeftResize, OperationInfo(HMove | HResize | VResize | HResizeReverse,
- Qt::SizeBDiagCursor));
- operationMap.insert(BottomRightResize, OperationInfo(HResize | VResize, Qt::SizeFDiagCursor));
-}
-
-#ifndef QT_NO_MENU
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::createSystemMenu()
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT_X(q, "QMdiSubWindowPrivate::createSystemMenu",
- "You can NOT call this function before QMdiSubWindow's ctor");
- systemMenu = new QMenu(q);
- const QStyle *style = q->style();
- addToSystemMenu(RestoreAction, QMdiSubWindow::tr("&Restore"), SLOT(showNormal()));
- actions[RestoreAction]->setIcon(style->standardIcon(QStyle::SP_TitleBarNormalButton, 0, q));
- actions[RestoreAction]->setEnabled(false);
- addToSystemMenu(MoveAction, QMdiSubWindow::tr("&Move"), SLOT(_q_enterInteractiveMode()));
- addToSystemMenu(ResizeAction, QMdiSubWindow::tr("&Size"), SLOT(_q_enterInteractiveMode()));
- addToSystemMenu(MinimizeAction, QMdiSubWindow::tr("Mi&nimize"), SLOT(showMinimized()));
- actions[MinimizeAction]->setIcon(style->standardIcon(QStyle::SP_TitleBarMinButton, 0, q));
- addToSystemMenu(MaximizeAction, QMdiSubWindow::tr("Ma&ximize"), SLOT(showMaximized()));
- actions[MaximizeAction]->setIcon(style->standardIcon(QStyle::SP_TitleBarMaxButton, 0, q));
- addToSystemMenu(StayOnTopAction, QMdiSubWindow::tr("Stay on &Top"), SLOT(_q_updateStaysOnTopHint()));
- actions[StayOnTopAction]->setCheckable(true);
- systemMenu->addSeparator();
- addToSystemMenu(CloseAction, QMdiSubWindow::tr("&Close"), SLOT(close()));
- actions[CloseAction]->setIcon(style->standardIcon(QStyle::SP_TitleBarCloseButton, 0, q));
-#if !defined(QT_NO_SHORTCUT)
- actions[CloseAction]->setShortcuts(QKeySequence::Close);
-#endif
- updateActions();
-}
-#endif
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::updateCursor()
-{
-#ifndef QT_NO_CURSOR
- Q_Q(QMdiSubWindow);
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(q->style()))
- return;
-#endif
-
- if (currentOperation == None) {
- q->unsetCursor();
- return;
- }
-
- if (currentOperation == Move || operationMap.find(currentOperation).value().hover) {
- q->setCursor(operationMap.find(currentOperation).value().cursorShape);
- return;
- }
-#endif
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::updateDirtyRegions()
-{
- // No update necessary
- if (!parent)
- return;
-
- foreach (Operation operation, operationMap.keys())
- operationMap.find(operation).value().region = getRegion(operation);
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::updateGeometryConstraints()
-{
- Q_Q(QMdiSubWindow);
- if (!parent)
- return;
-
- internalMinimumSize = (!q->isMinimized() && !q->minimumSize().isNull())
- ? q->minimumSize() : q->minimumSizeHint();
- int margin, minWidth;
- sizeParameters(&margin, &minWidth);
- q->setContentsMargins(margin, titleBarHeight(), margin, margin);
- if (q->isMaximized() || (q->isMinimized() && !q->isShaded())) {
- moveEnabled = false;
- resizeEnabled = false;
- } else {
- moveEnabled = true;
- if ((q->windowFlags() & Qt::MSWindowsFixedSizeDialogHint) || q->isShaded())
- resizeEnabled = false;
- else
- resizeEnabled = true;
- }
- updateDirtyRegions();
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::updateMask()
-{
- Q_Q(QMdiSubWindow);
- if (!q->mask().isEmpty())
- q->clearMask();
-
- if (!parent)
- return;
-
- if ((q->isMaximized() && !drawTitleBarWhenMaximized())
- || q->windowFlags() & Qt::FramelessWindowHint)
- return;
-
- if (resizeTimerId == -1)
- cachedStyleOptions = titleBarOptions();
- cachedStyleOptions.rect = q->rect();
- QStyleHintReturnMask frameMask;
- q->style()->styleHint(QStyle::SH_WindowFrame_Mask, &cachedStyleOptions, q, &frameMask);
- if (!frameMask.region.isEmpty())
- q->setMask(frameMask.region);
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setNewGeometry(const QPoint &pos)
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT(currentOperation != None);
- Q_ASSERT(parent);
-
- uint cflags = operationMap.find(currentOperation).value().changeFlags;
- int posX = pos.x();
- int posY = pos.y();
-
- const bool restrictHorizontal = !q->testOption(QMdiSubWindow::AllowOutsideAreaHorizontally);
- const bool restrictVertical = !q->testOption(QMdiSubWindow::AllowOutsideAreaVertically);
-
- if (restrictHorizontal || restrictVertical) {
- QRect parentRect = q->parentWidget()->rect();
- if (restrictVertical && (cflags & VResizeReverse || currentOperation == Move)) {
- posY = qMin(qMax(mousePressPosition.y() - oldGeometry.y(), posY),
- parentRect.height() - BoundaryMargin);
- }
- if (currentOperation == Move) {
- if (restrictHorizontal)
- posX = qMin(qMax(BoundaryMargin, posX), parentRect.width() - BoundaryMargin);
- if (restrictVertical)
- posY = qMin(posY, parentRect.height() - BoundaryMargin);
- } else {
- if (restrictHorizontal) {
- if (cflags & HResizeReverse)
- posX = qMax(mousePressPosition.x() - oldGeometry.x(), posX);
- else
- posX = qMin(parentRect.width() - (oldGeometry.x() + oldGeometry.width()
- - mousePressPosition.x()), posX);
- }
- if (restrictVertical && !(cflags & VResizeReverse)) {
- posY = qMin(parentRect.height() - (oldGeometry.y() + oldGeometry.height()
- - mousePressPosition.y()), posY);
- }
- }
- }
-
- QRect geometry;
- if (cflags & (HMove | VMove)) {
- int dx = getMoveDeltaComponent(cflags, HMove, HResize, posX - mousePressPosition.x(),
- oldGeometry.width() - internalMinimumSize.width(),
- oldGeometry.width() - q->maximumWidth());
- int dy = getMoveDeltaComponent(cflags, VMove, VResize, posY - mousePressPosition.y(),
- oldGeometry.height() - internalMinimumSize.height(),
- oldGeometry.height() - q->maximumHeight());
- geometry.setTopLeft(oldGeometry.topLeft() + QPoint(dx, dy));
- } else {
- geometry.setTopLeft(q->geometry().topLeft());
- }
-
- if (cflags & (HResize | VResize)) {
- int dx = getResizeDeltaComponent(cflags, HResize, HResizeReverse,
- posX - mousePressPosition.x());
- int dy = getResizeDeltaComponent(cflags, VResize, VResizeReverse,
- posY - mousePressPosition.y());
- geometry.setSize(oldGeometry.size() + QSize(dx, dy));
- } else {
- geometry.setSize(q->geometry().size());
- }
-
- setNewGeometry(&geometry);
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setMinimizeMode()
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT(parent);
-
- ensureWindowState(Qt::WindowMinimized);
- isShadeRequestFromMinimizeMode = true;
- q->showShaded();
- isShadeRequestFromMinimizeMode = false;
-
- moveEnabled = false;
-#ifndef QT_NO_ACTION
- setEnabled(MoveAction, moveEnabled);
-#endif
-
- Q_ASSERT(q->windowState() & Qt::WindowMinimized);
- Q_ASSERT(!(q->windowState() & Qt::WindowMaximized));
- // This should be a valid assert, but people can actually re-implement
- // setVisible and do crazy stuff, so we're not guaranteed that
- // the widget is hidden after calling hide().
- // Q_ASSERT(baseWidget ? baseWidget->isHidden() : true);
-
- setActive(true);
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setNormalMode()
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT(parent);
-
- isShadeMode = false;
- isMaximizeMode = false;
-
- ensureWindowState(Qt::WindowNoState);
-#ifndef QT_NO_MENUBAR
- removeButtonsFromMenuBar();
-#endif
-
- // Hide the window before we change the geometry to avoid multiple resize
- // events and wrong window state.
- const bool wasVisible = q->isVisible();
- if (wasVisible)
- q->setVisible(false);
-
- // Restore minimum size if set by user.
- if (!userMinimumSize.isNull()) {
- q->setMinimumSize(userMinimumSize);
- userMinimumSize = QSize(0, 0);
- }
-
- // Show the internal widget if it was hidden by us,
- if (baseWidget && isWidgetHiddenByUs) {
- baseWidget->show();
- isWidgetHiddenByUs = false;
- }
-
- updateGeometryConstraints();
- QRect newGeometry = oldGeometry;
- newGeometry.setSize(restoreSize.expandedTo(internalMinimumSize));
- q->setGeometry(newGeometry);
-
- if (wasVisible)
- q->setVisible(true);
-
- // Invalidate the restore size.
- restoreSize.setWidth(-1);
- restoreSize.setHeight(-1);
-
-#ifndef QT_NO_SIZEGRIP
- setSizeGripVisible(true);
-#endif
-
-#ifndef QT_NO_ACTION
- setEnabled(MoveAction, true);
- setEnabled(MaximizeAction, true);
- setEnabled(MinimizeAction, true);
- setEnabled(RestoreAction, false);
- setEnabled(ResizeAction, resizeEnabled);
-#endif // QT_NO_ACTION
-
- Q_ASSERT(!(q_func()->windowState() & Qt::WindowMinimized));
- // This sub-window can be maximized when shown above if not the
- // QMdiArea::DontMaximizeSubWindowOnActionvation is set. Make sure
- // the Qt::WindowMaximized flag is set accordingly.
- Q_ASSERT((isMaximizeMode && q_func()->windowState() & Qt::WindowMaximized)
- || (!isMaximizeMode && !(q_func()->windowState() & Qt::WindowMaximized)));
- Q_ASSERT(!isShadeMode);
-
- setActive(true);
- restoreFocus();
- updateMask();
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setMaximizeMode()
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT(parent);
-
- ensureWindowState(Qt::WindowMaximized);
- isShadeMode = false;
- isMaximizeMode = true;
-
- if (!restoreFocusWidget && q->isAncestorOf(QApplication::focusWidget()))
- restoreFocusWidget = QApplication::focusWidget();
-
-#ifndef QT_NO_SIZEGRIP
- setSizeGripVisible(false);
-#endif
-
- // Store old geometry and set restore size if not already set.
- if (!restoreSize.isValid()) {
- oldGeometry = q->geometry();
- restoreSize.setWidth(oldGeometry.width());
- restoreSize.setHeight(oldGeometry.height());
- }
-
- // Hide the window before we change the geometry to avoid multiple resize
- // events and wrong window state.
- const bool wasVisible = q->isVisible();
- if (wasVisible)
- q->setVisible(false);
-
- // Show the internal widget if it was hidden by us.
- if (baseWidget && isWidgetHiddenByUs) {
- baseWidget->show();
- isWidgetHiddenByUs = false;
- }
-
- updateGeometryConstraints();
-
- if (wasVisible) {
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mBar = menuBar())
- showButtonsInMenuBar(mBar);
- else
-#endif
- if (!controlContainer)
- controlContainer = new ControlContainer(q);
- }
-
- QWidget *parent = q->parentWidget();
- QRect availableRect = parent->contentsRect();
-
- // Adjust geometry if the sub-window is inside a scroll area.
- QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent->parentWidget());
- if (scrollArea && scrollArea->viewport() == parent) {
- QScrollBar *hbar = scrollArea->horizontalScrollBar();
- QScrollBar *vbar = scrollArea->verticalScrollBar();
- const int xOffset = hbar ? hbar->value() : 0;
- const int yOffset = vbar ? vbar->value() : 0;
- availableRect.adjust(-xOffset, -yOffset, -xOffset, -yOffset);
- oldGeometry.adjust(xOffset, yOffset, xOffset, yOffset);
- }
-
- setNewGeometry(&availableRect);
- // QWidget::setGeometry will reset Qt::WindowMaximized so we have to update it here.
- ensureWindowState(Qt::WindowMaximized);
-
- if (wasVisible)
- q->setVisible(true);
-
- resizeEnabled = false;
- moveEnabled = false;
-
-#ifndef QT_NO_ACTION
- setEnabled(MoveAction, moveEnabled);
- setEnabled(MaximizeAction, false);
- setEnabled(MinimizeAction, true);
- setEnabled(RestoreAction, true);
- setEnabled(ResizeAction, resizeEnabled);
-#endif // QT_NO_ACTION
-
- Q_ASSERT(q->windowState() & Qt::WindowMaximized);
- Q_ASSERT(!(q->windowState() & Qt::WindowMinimized));
-
- restoreFocus();
- updateMask();
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setActive(bool activate, bool changeFocus)
-{
- Q_Q(QMdiSubWindow);
- if (!parent || !activationEnabled)
- return;
-
- if (activate && !isActive && q->isEnabled()) {
- isActive = true;
- isExplicitlyDeactivated = false;
- Qt::WindowStates oldWindowState = q->windowState();
- ensureWindowState(Qt::WindowActive);
- emit q->aboutToActivate();
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mBar = menuBar())
- showButtonsInMenuBar(mBar);
-#endif
- Q_ASSERT(isActive);
- emit q->windowStateChanged(oldWindowState, q->windowState());
- } else if (!activate && isActive) {
- isActive = false;
- Qt::WindowStates oldWindowState = q->windowState();
- q->overrideWindowState(q->windowState() & ~Qt::WindowActive);
- if (changeFocus) {
- QWidget *focusWidget = QApplication::focusWidget();
- if (focusWidget && (focusWidget == q || q->isAncestorOf(focusWidget)))
- focusWidget->clearFocus();
- }
- if (baseWidget)
- baseWidget->overrideWindowState(baseWidget->windowState() & ~Qt::WindowActive);
- Q_ASSERT(!isActive);
- emit q->windowStateChanged(oldWindowState, q->windowState());
- }
-
- if (activate && isActive && q->isEnabled() && !q->hasFocus()
- && !q->isAncestorOf(QApplication::focusWidget())) {
- if (changeFocus)
- setFocusWidget();
- ensureWindowState(Qt::WindowActive);
- }
-
- int frameWidth = q->style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, q);
- int titleBarHeight = this->titleBarHeight();
- QRegion windowDecoration = QRegion(0, 0, q->width(), q->height());
- windowDecoration -= QRegion(frameWidth, titleBarHeight, q->width() - 2 * frameWidth,
- q->height() - titleBarHeight - frameWidth);
-
- // Make sure we don't use cached style options if we get
- // resize events right before activation/deactivation.
- if (resizeTimerId != -1) {
- q->killTimer(resizeTimerId);
- resizeTimerId = -1;
- updateDirtyRegions();
- }
-
- q->update(windowDecoration);
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::processClickedSubControl()
-{
- Q_Q(QMdiSubWindow);
- switch (activeSubControl) {
- case QStyle::SC_TitleBarContextHelpButton:
-#ifndef QT_NO_WHATSTHIS
- QWhatsThis::enterWhatsThisMode();
-#endif
- break;
- case QStyle::SC_TitleBarShadeButton:
- q->showShaded();
- hoveredSubControl = QStyle::SC_TitleBarUnshadeButton;
- break;
- case QStyle::SC_TitleBarUnshadeButton:
- if (q->isShaded())
- hoveredSubControl = QStyle::SC_TitleBarShadeButton;
- q->showNormal();
- break;
- case QStyle::SC_TitleBarMinButton:
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(q->style())) {
- if (q->isMinimized())
- q->showNormal();
- else
- q->showMinimized();
- break;
- }
-#endif
- q->showMinimized();
- break;
- case QStyle::SC_TitleBarNormalButton:
- if (q->isShaded())
- hoveredSubControl = QStyle::SC_TitleBarMinButton;
- q->showNormal();
- break;
- case QStyle::SC_TitleBarMaxButton:
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(q->style())) {
- if (q->isMaximized())
- q->showNormal();
- else
- q->showMaximized();
- break;
- }
-#endif
- q->showMaximized();
- break;
- case QStyle::SC_TitleBarCloseButton:
- q->close();
- break;
- default:
- break;
- }
-}
-
-/*!
- \internal
-*/
-QRegion QMdiSubWindowPrivate::getRegion(Operation operation) const
-{
- Q_Q(const QMdiSubWindow);
- int width = q->width();
- int height = q->height();
- int titleBarHeight = this->titleBarHeight();
- int frameWidth = q->style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, q);
- int cornerConst = titleBarHeight - frameWidth;
- int titleBarConst = 2 * titleBarHeight;
-
- if (operation == Move) {
- QStyleOptionTitleBar titleBarOptions = this->titleBarOptions();
- QRegion move(frameWidth, frameWidth, width - 2 * frameWidth, cornerConst);
- // Depending on which window flags are set, activated sub controllers will
- // be subtracted from the 'move' region.
- for (int i = 0; i < NumSubControls; ++i) {
- if (SubControls[i] == QStyle::SC_TitleBarLabel)
- continue;
- move -= QRegion(q->style()->subControlRect(QStyle::CC_TitleBar, &titleBarOptions,
- SubControls[i]));
- }
- return move;
- }
-
- QRegion region;
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(q->style()))
- return region;
-#endif
-
- switch (operation) {
- case TopResize:
- region = QRegion(titleBarHeight, 0, width - titleBarConst, frameWidth);
- break;
- case BottomResize:
- region = QRegion(titleBarHeight, height - frameWidth, width - titleBarConst, frameWidth);
- break;
- case LeftResize:
- region = QRegion(0, titleBarHeight, frameWidth, height - titleBarConst);
- break;
- case RightResize:
- region = QRegion(width - frameWidth, titleBarHeight, frameWidth, height - titleBarConst);
- break;
- case TopLeftResize:
- region = QRegion(0, 0, titleBarHeight, titleBarHeight)
- - QRegion(frameWidth, frameWidth, cornerConst, cornerConst);
- break;
- case TopRightResize:
- region = QRegion(width - titleBarHeight, 0, titleBarHeight, titleBarHeight)
- - QRegion(width - titleBarHeight, frameWidth, cornerConst, cornerConst);
- break;
- case BottomLeftResize:
- region = QRegion(0, height - titleBarHeight, titleBarHeight, titleBarHeight)
- - QRegion(frameWidth, height - titleBarHeight, cornerConst, cornerConst);
- break;
- case BottomRightResize:
- region = QRegion(width - titleBarHeight, height - titleBarHeight, titleBarHeight, titleBarHeight)
- - QRegion(width - titleBarHeight, height - titleBarHeight, cornerConst, cornerConst);
- break;
- default:
- break;
- }
-
- return region;
-}
-
-/*!
- \internal
-*/
-QMdiSubWindowPrivate::Operation QMdiSubWindowPrivate::getOperation(const QPoint &pos) const
-{
- OperationInfoMap::const_iterator it;
- for (it = operationMap.constBegin(); it != operationMap.constEnd(); ++it)
- if (it.value().region.contains(pos))
- return it.key();
- return None;
-}
-
-extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*);
-
-/*!
- \internal
-*/
-QStyleOptionTitleBar QMdiSubWindowPrivate::titleBarOptions() const
-{
- Q_Q(const QMdiSubWindow);
- QStyleOptionTitleBar titleBarOptions;
- titleBarOptions.initFrom(q);
- if (activeSubControl != QStyle::SC_None) {
- if (hoveredSubControl == activeSubControl) {
- titleBarOptions.state |= QStyle::State_Sunken;
- titleBarOptions.activeSubControls = activeSubControl;
- }
- } else if (autoRaise() && hoveredSubControl != QStyle::SC_None
- && hoveredSubControl != QStyle::SC_TitleBarLabel) {
- titleBarOptions.state |= QStyle::State_MouseOver;
- titleBarOptions.activeSubControls = hoveredSubControl;
- } else {
- titleBarOptions.state &= ~QStyle::State_MouseOver;
- titleBarOptions.activeSubControls = QStyle::SC_None;
- }
-
- titleBarOptions.subControls = QStyle::SC_All;
- titleBarOptions.titleBarFlags = q->windowFlags();
- titleBarOptions.titleBarState = q->windowState();
- titleBarOptions.palette = titleBarPalette;
- titleBarOptions.icon = menuIcon;
-
- if (isActive) {
- titleBarOptions.state |= QStyle::State_Active;
- titleBarOptions.titleBarState |= QStyle::State_Active;
- titleBarOptions.palette.setCurrentColorGroup(QPalette::Active);
- } else {
- titleBarOptions.state &= ~QStyle::State_Active;
- titleBarOptions.palette.setCurrentColorGroup(QPalette::Inactive);
- }
-
- int border = hasBorder(titleBarOptions) ? 4 : 0;
- int paintHeight = titleBarHeight(titleBarOptions);
- paintHeight -= q->isMinimized() ? 2 * border : border;
- titleBarOptions.rect = QRect(border, border, q->width() - 2 * border, paintHeight);
-
- if (!windowTitle.isEmpty()) {
- // Set the text here before asking for the width of the title bar label
- // in case people uses the actual text to calculate the width.
- titleBarOptions.text = windowTitle;
- titleBarOptions.fontMetrics = QFontMetrics(font);
- int width = q->style()->subControlRect(QStyle::CC_TitleBar, &titleBarOptions,
- QStyle::SC_TitleBarLabel, q).width();
- // Set elided text if we don't have enough space for the entire title.
- titleBarOptions.text = titleBarOptions.fontMetrics.elidedText(windowTitle, Qt::ElideRight, width);
- }
- return titleBarOptions;
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::ensureWindowState(Qt::WindowState state)
-{
- Q_Q(QMdiSubWindow);
- Qt::WindowStates windowStates = q->windowState() | state;
- switch (state) {
- case Qt::WindowMinimized:
- windowStates &= ~Qt::WindowMaximized;
- windowStates &= ~Qt::WindowNoState;
- break;
- case Qt::WindowMaximized:
- windowStates &= ~Qt::WindowMinimized;
- windowStates &= ~Qt::WindowNoState;
- break;
- case Qt::WindowNoState:
- windowStates &= ~Qt::WindowMinimized;
- windowStates &= ~Qt::WindowMaximized;
- break;
- default:
- break;
- }
- if (baseWidget) {
- if (!(baseWidget->windowState() & Qt::WindowActive) && windowStates & Qt::WindowActive)
- baseWidget->overrideWindowState(windowStates & ~Qt::WindowActive);
- else
- baseWidget->overrideWindowState(windowStates);
- }
- q->overrideWindowState(windowStates);
-}
-
-/*!
- \internal
-*/
-int QMdiSubWindowPrivate::titleBarHeight(const QStyleOptionTitleBar &options) const
-{
- Q_Q(const QMdiSubWindow);
- if (!parent || q->windowFlags() & Qt::FramelessWindowHint
- || (q->isMaximized() && !drawTitleBarWhenMaximized())) {
- return 0;
- }
-
- int height = q->style()->pixelMetric(QStyle::PM_TitleBarHeight, &options, q);
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- // ### Fix mac style, the +4 pixels hack is not necessary anymore
- if (qobject_cast<QMacStyle *>(q->style()))
- height -= 4;
-#endif
- if (hasBorder(options))
- height += q->isMinimized() ? 8 : 4;
- return height;
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::sizeParameters(int *margin, int *minWidth) const
-{
- Q_Q(const QMdiSubWindow);
- Qt::WindowFlags flags = q->windowFlags();
- if (!parent || flags & Qt::FramelessWindowHint) {
- *margin = 0;
- *minWidth = 0;
- return;
- }
-
- if (q->isMaximized() && !drawTitleBarWhenMaximized())
- *margin = 0;
- else
- *margin = q->style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, q);
-
- QStyleOptionTitleBar opt = this->titleBarOptions();
- int tempWidth = 0;
- for (int i = 0; i < NumSubControls; ++i) {
- if (SubControls[i] == QStyle::SC_TitleBarLabel) {
- tempWidth += 30;
- continue;
- }
- QRect rect = q->style()->subControlRect(QStyle::CC_TitleBar, &opt, SubControls[i], q);
- if (!rect.isValid())
- continue;
- tempWidth += rect.width();
- }
- *minWidth = tempWidth;
-}
-
-/*!
- \internal
-*/
-bool QMdiSubWindowPrivate::drawTitleBarWhenMaximized() const
-{
- Q_Q(const QMdiSubWindow);
- if (q->window()->testAttribute(Qt::WA_CanHostQMdiSubWindowTitleBar))
- return false;
-
- if (isChildOfTabbedQMdiArea(q))
- return false;
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC) || defined(Q_WS_WINCE_WM)
- return true;
-#else
- if (q->style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, q))
- return true;
-#if defined(QT_NO_MENUBAR) || defined(QT_NO_MAINWINDOW)
- return true;
-#else
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(q->window());
- if (!mainWindow || !qobject_cast<QMenuBar *>(mainWindow->menuWidget())
- || mainWindow->menuWidget()->isHidden())
- return true;
-
- return isChildOfQMdiSubWindow(q);
-#endif
-#endif
-}
-
-#ifndef QT_NO_MENUBAR
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::showButtonsInMenuBar(QMenuBar *menuBar)
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT(q->isMaximized() && !drawTitleBarWhenMaximized());
-
- if (isChildOfTabbedQMdiArea(q))
- return;
-
- removeButtonsFromMenuBar();
- if (!controlContainer)
- controlContainer = new ControlContainer(q);
-
- ignoreWindowTitleChange = true;
- controlContainer->showButtonsInMenuBar(menuBar);
- ignoreWindowTitleChange = false;
-
- QWidget *topLevelWindow = q->window();
- topLevelWindow->setWindowModified(q->isWindowModified());
- topLevelWindow->installEventFilter(q);
-
- int buttonHeight = 0;
- if (controlContainer->controllerWidget())
- buttonHeight = controlContainer->controllerWidget()->height();
- else if (controlContainer->systemMenuLabel())
- buttonHeight = controlContainer->systemMenuLabel()->height();
-
- // This will rarely happen.
- if (menuBar && menuBar->height() < buttonHeight
- && topLevelWindow->layout()) {
- // Make sure topLevelWindow->contentsRect returns correct geometry.
- // topLevelWidget->updateGeoemtry will not do the trick here since it will post the event.
- QEvent event(QEvent::LayoutRequest);
- QApplication::sendEvent(topLevelWindow, &event);
- }
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::removeButtonsFromMenuBar()
-{
- Q_Q(QMdiSubWindow);
-
- if (!controlContainer || isChildOfTabbedQMdiArea(q))
- return;
-
- QMenuBar *currentMenuBar = 0;
-#ifndef QT_NO_MAINWINDOW
- if (QMainWindow *mainWindow = qobject_cast<QMainWindow *>(q->window())) {
- // NB! We can't use menuBar() here because that one will actually create
- // a menubar for us if not set. That's not what we want :-)
- currentMenuBar = qobject_cast<QMenuBar *>(mainWindow->menuWidget());
- }
-#endif
-
- ignoreWindowTitleChange = true;
- controlContainer->removeButtonsFromMenuBar(currentMenuBar);
- ignoreWindowTitleChange = false;
-
- QWidget *topLevelWindow = q->window();
- topLevelWindow->removeEventFilter(q);
- if (baseWidget && !drawTitleBarWhenMaximized())
- topLevelWindow->setWindowModified(false);
- originalTitle = QString::null;
-}
-
-#endif // QT_NO_MENUBAR
-
-void QMdiSubWindowPrivate::updateWindowTitle(bool isRequestFromChild)
-{
- Q_Q(QMdiSubWindow);
- if (isRequestFromChild && !q->windowTitle().isEmpty() && !lastChildWindowTitle.isEmpty()
- && lastChildWindowTitle != q->windowTitle()) {
- return;
- }
-
- QWidget *titleWidget = 0;
- if (isRequestFromChild)
- titleWidget = baseWidget;
- else
- titleWidget = q;
- if (!titleWidget || titleWidget->windowTitle().isEmpty())
- return;
-
- ignoreWindowTitleChange = true;
- q->setWindowTitle(titleWidget->windowTitle());
- if (q->maximizedButtonsWidget())
- setNewWindowTitle();
- ignoreWindowTitleChange = false;
-}
-
-#ifndef QT_NO_RUBBERBAND
-void QMdiSubWindowPrivate::enterRubberBandMode()
-{
- Q_Q(QMdiSubWindow);
- if (q->isMaximized())
- return;
- Q_ASSERT(oldGeometry.isValid());
- Q_ASSERT(parent);
- if (!rubberBand) {
- rubberBand = new QRubberBand(QRubberBand::Rectangle, q->parentWidget());
- // For accessibility to identify this special widget.
- rubberBand->setObjectName(QLatin1String("qt_rubberband"));
- }
- QPoint rubberBandPos = q->mapToParent(QPoint(0, 0));
- rubberBand->setGeometry(rubberBandPos.x(), rubberBandPos.y(),
- oldGeometry.width(), oldGeometry.height());
- rubberBand->show();
- isInRubberBandMode = true;
- q->grabMouse();
-}
-
-void QMdiSubWindowPrivate::leaveRubberBandMode()
-{
- Q_Q(QMdiSubWindow);
- Q_ASSERT(rubberBand);
- Q_ASSERT(isInRubberBandMode);
- q->releaseMouse();
- isInRubberBandMode = false;
- q->setGeometry(rubberBand->geometry());
- rubberBand->hide();
- currentOperation = None;
-}
-#endif // QT_NO_RUBBERBAND
-
-// Taken from the old QWorkspace (::readColors())
-QPalette QMdiSubWindowPrivate::desktopPalette() const
-{
- Q_Q(const QMdiSubWindow);
- QPalette newPalette = q->palette();
-
- bool colorsInitialized = false;
-#ifdef Q_WS_WIN // ask system properties on windows
-#ifndef SPI_GETGRADIENTCAPTIONS
-#define SPI_GETGRADIENTCAPTIONS 0x1008
-#endif
-#ifndef COLOR_GRADIENTACTIVECAPTION
-#define COLOR_GRADIENTACTIVECAPTION 27
-#endif
-#ifndef COLOR_GRADIENTINACTIVECAPTION
-#define COLOR_GRADIENTINACTIVECAPTION 28
-#endif
- if (QApplication::desktopSettingsAware()) {
- newPalette.setColor(QPalette::Active, QPalette::Highlight,
- colorref2qrgb(GetSysColor(COLOR_ACTIVECAPTION)));
- newPalette.setColor(QPalette::Inactive, QPalette::Highlight,
- colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTION)));
- newPalette.setColor(QPalette::Active, QPalette::HighlightedText,
- colorref2qrgb(GetSysColor(COLOR_CAPTIONTEXT)));
- newPalette.setColor(QPalette::Inactive, QPalette::HighlightedText,
- colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTIONTEXT)));
-
- colorsInitialized = true;
- BOOL hasGradient = false;
- SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &hasGradient, 0);
-
- if (hasGradient) {
- newPalette.setColor(QPalette::Active, QPalette::Base,
- colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION)));
- newPalette.setColor(QPalette::Inactive, QPalette::Base,
- colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION)));
- } else {
- newPalette.setColor(QPalette::Active, QPalette::Base,
- newPalette.color(QPalette::Active, QPalette::Highlight));
- newPalette.setColor(QPalette::Inactive, QPalette::Base,
- newPalette.color(QPalette::Inactive, QPalette::Highlight));
- }
- }
-#endif // Q_WS_WIN
- if (!colorsInitialized) {
- newPalette.setColor(QPalette::Active, QPalette::Highlight,
- newPalette.color(QPalette::Active, QPalette::Highlight));
- newPalette.setColor(QPalette::Active, QPalette::Base,
- newPalette.color(QPalette::Active, QPalette::Highlight));
- newPalette.setColor(QPalette::Inactive, QPalette::Highlight,
- newPalette.color(QPalette::Inactive, QPalette::Dark));
- newPalette.setColor(QPalette::Inactive, QPalette::Base,
- newPalette.color(QPalette::Inactive, QPalette::Dark));
- newPalette.setColor(QPalette::Inactive, QPalette::HighlightedText,
- newPalette.color(QPalette::Inactive, QPalette::Window));
- }
-
- return newPalette;
-}
-
-void QMdiSubWindowPrivate::updateActions()
-{
- Qt::WindowFlags windowFlags = q_func()->windowFlags();
- // Hide all
- for (int i = 0; i < NumWindowStateActions; ++i)
- setVisible(WindowStateAction(i), false);
-
- if (windowFlags & Qt::FramelessWindowHint)
- return;
-
- setVisible(StayOnTopAction, true);
- setVisible(MoveAction, moveEnabled);
- setVisible(ResizeAction, resizeEnabled);
-
- // CloseAction
- if (windowFlags & Qt::WindowSystemMenuHint)
- setVisible(CloseAction, true);
-
- // RestoreAction
- if (windowFlags & (Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint))
- setVisible(RestoreAction, true);
-
- // MinimizeAction
- if (windowFlags & Qt::WindowMinimizeButtonHint)
- setVisible(MinimizeAction, true);
-
- // MaximizeAction
- if (windowFlags & Qt::WindowMaximizeButtonHint)
- setVisible(MaximizeAction, true);
-}
-
-void QMdiSubWindowPrivate::setFocusWidget()
-{
- Q_Q(QMdiSubWindow);
- if (!baseWidget) {
- q->setFocus();
- return;
- }
-
- // This will give focus to the next child if possible, otherwise
- // do nothing, hence it's not possible to tab between windows with
- // just hitting tab (unless Qt::TabFocus is removed from the focus policy).
- if (focusInReason == Qt::TabFocusReason) {
- q->focusNextChild();
- return;
- }
-
- // Same as above, but gives focus to the previous child.
- if (focusInReason == Qt::BacktabFocusReason) {
- q->focusPreviousChild();
- return;
- }
-
- if (QWidget *focusWidget = baseWidget->focusWidget()) {
- if (!focusWidget->hasFocus() && q->isAncestorOf(focusWidget)
- && focusWidget->isVisible() && !q->isMinimized()
- && focusWidget->focusPolicy() != Qt::NoFocus) {
- focusWidget->setFocus();
- } else {
- q->setFocus();
- }
- return;
- }
-
- QWidget *focusWidget = q->nextInFocusChain();
- while (focusWidget && focusWidget != q && focusWidget->focusPolicy() == Qt::NoFocus)
- focusWidget = focusWidget->nextInFocusChain();
- if (focusWidget && q->isAncestorOf(focusWidget))
- focusWidget->setFocus();
- else if (baseWidget->focusPolicy() != Qt::NoFocus)
- baseWidget->setFocus();
- else if (!q->hasFocus())
- q->setFocus();
-}
-
-void QMdiSubWindowPrivate::restoreFocus()
-{
- if (!restoreFocusWidget)
- return;
- if (!restoreFocusWidget->hasFocus() && q_func()->isAncestorOf(restoreFocusWidget)
- && restoreFocusWidget->isVisible()
- && restoreFocusWidget->focusPolicy() != Qt::NoFocus) {
- restoreFocusWidget->setFocus();
- }
- restoreFocusWidget = 0;
-}
-
-/*!
- \internal
- ### Please add QEvent::WindowFlagsChange event
-*/
-void QMdiSubWindowPrivate::setWindowFlags(Qt::WindowFlags windowFlags)
-{
- Q_Q(QMdiSubWindow);
- if (!parent) {
- q->setWindowFlags(windowFlags);
- return;
- }
-
- Qt::WindowFlags windowType = windowFlags & Qt::WindowType_Mask;
- if (windowType == Qt::Dialog || windowFlags & Qt::MSWindowsFixedSizeDialogHint)
- windowFlags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint;
-
- // Set standard flags if none of the customize flags are set
- if (!(windowFlags & CustomizeWindowFlags))
- windowFlags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint;
- else if (windowFlags & Qt::FramelessWindowHint && windowFlags & Qt::WindowStaysOnTopHint)
- windowFlags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint;
- else if (windowFlags & Qt::FramelessWindowHint)
- windowFlags = Qt::FramelessWindowHint;
-
- windowFlags &= ~windowType;
- windowFlags |= Qt::SubWindow;
-
-#ifndef QT_NO_ACTION
- if (QAction *stayOnTopAction = actions[QMdiSubWindowPrivate::StayOnTopAction]) {
- if (windowFlags & Qt::WindowStaysOnTopHint)
- stayOnTopAction->setChecked(true);
- else
- stayOnTopAction->setChecked(false);
- }
-#endif
-
-#ifndef QT_NO_SIZEGRIP
- if ((windowFlags & Qt::FramelessWindowHint) && sizeGrip)
- delete sizeGrip;
-#endif
-
- q->setWindowFlags(windowFlags);
- updateGeometryConstraints();
- updateActions();
- QSize currentSize = q->size();
- if (q->isVisible() && (currentSize.width() < internalMinimumSize.width()
- || currentSize.height() < internalMinimumSize.height())) {
- q->resize(currentSize.expandedTo(internalMinimumSize));
- }
-}
-
-void QMdiSubWindowPrivate::setVisible(WindowStateAction action, bool visible)
-{
-#ifndef QT_NO_ACTION
- if (actions[action])
- actions[action]->setVisible(visible);
-#endif
-
- Q_Q(QMdiSubWindow);
- if (!controlContainer)
- controlContainer = new ControlContainer(q);
-
- if (ControllerWidget *ctrlWidget = qobject_cast<ControllerWidget *>
- (controlContainer->controllerWidget())) {
- ctrlWidget->setControlVisible(action, visible);
- }
-}
-
-#ifndef QT_NO_ACTION
-void QMdiSubWindowPrivate::setEnabled(WindowStateAction action, bool enable)
-{
- if (actions[action])
- actions[action]->setEnabled(enable);
-}
-
-#ifndef QT_NO_MENU
-void QMdiSubWindowPrivate::addToSystemMenu(WindowStateAction action, const QString &text,
- const char *slot)
-{
- if (!systemMenu)
- return;
- actions[action] = systemMenu->addAction(text, q_func(), slot);
-}
-#endif
-#endif // QT_NO_ACTION
-
-/*!
- \internal
-*/
-QSize QMdiSubWindowPrivate::iconSize() const
-{
- Q_Q(const QMdiSubWindow);
- if (!parent || q->windowFlags() & Qt::FramelessWindowHint)
- return QSize(-1, -1);
- return QSize(q->style()->pixelMetric(QStyle::PM_MdiSubWindowMinimizedWidth, 0, q), titleBarHeight());
-}
-
-#ifndef QT_NO_SIZEGRIP
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setSizeGrip(QSizeGrip *newSizeGrip)
-{
- Q_Q(QMdiSubWindow);
- if (!newSizeGrip || sizeGrip || q->windowFlags() & Qt::FramelessWindowHint)
- return;
-
- if (layout && layout->indexOf(newSizeGrip) != -1)
- return;
- newSizeGrip->setFixedSize(newSizeGrip->sizeHint());
- bool putSizeGripInLayout = layout ? true : false;
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(q->style()))
- putSizeGripInLayout = false;
-#endif
- if (putSizeGripInLayout) {
- layout->addWidget(newSizeGrip);
- layout->setAlignment(newSizeGrip, Qt::AlignBottom | Qt::AlignRight);
- } else {
- newSizeGrip->setParent(q);
- newSizeGrip->move(q->isLeftToRight() ? q->width() - newSizeGrip->width() : 0,
- q->height() - newSizeGrip->height());
- sizeGrip = newSizeGrip;
- }
- newSizeGrip->raise();
- updateGeometryConstraints();
- newSizeGrip->installEventFilter(q);
-}
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::setSizeGripVisible(bool visible) const
-{
- // See if we can find any size grips
- QList<QSizeGrip *> sizeGrips = q_func()->findChildren<QSizeGrip *>();
- foreach (QSizeGrip *grip, sizeGrips)
- grip->setVisible(visible);
-}
-
-#endif // QT_NO_SIZEGRIP
-
-/*!
- \internal
-*/
-void QMdiSubWindowPrivate::updateInternalWindowTitle()
-{
- Q_Q(QMdiSubWindow);
- if (q->isWindowModified()) {
- windowTitle = q->windowTitle();
- windowTitle.replace(QLatin1String("[*]"), QLatin1String("*"));
- } else {
- windowTitle = qt_setWindowTitle_helperHelper(q->windowTitle(), q);
- }
- q->update(0, 0, q->width(), titleBarHeight());
-}
-
-/*!
- Constructs a new QMdiSubWindow widget. The \a parent and \a
- flags arguments are passed to QWidget's constructor.
-
- Instead of using addSubWindow(), it is also simply possible to
- use setParent() when you add the subwindow to a QMdiArea.
-
- Note that only \l{QMdiSubWindow}s can be set as children of
- QMdiArea; you cannot, for instance, write:
-
- \badcode
- QMdiArea mdiArea;
- QTextEdit editor(&mdiArea); // invalid child widget
- \endcode
-
- \sa QMdiArea::addSubWindow()
-*/
-QMdiSubWindow::QMdiSubWindow(QWidget *parent, Qt::WindowFlags flags)
- : QWidget(*new QMdiSubWindowPrivate, parent, 0)
-{
- Q_D(QMdiSubWindow);
-#ifndef QT_NO_MENU
- d->createSystemMenu();
- addActions(d->systemMenu->actions());
-#endif
- d->setWindowFlags(flags);
- setBackgroundRole(QPalette::Window);
- setAutoFillBackground(true);
- setMouseTracking(true);
- setLayout(new QVBoxLayout);
- setFocusPolicy(Qt::StrongFocus);
- layout()->setMargin(0);
- d->updateGeometryConstraints();
- setAttribute(Qt::WA_Resized, false);
- d->titleBarPalette = d->desktopPalette();
- d->font = QApplication::font("QWorkspaceTitleBar");
- // We don't want the menu icon by default on mac.
-#ifndef Q_WS_MAC
- if (windowIcon().isNull())
- d->menuIcon = style()->standardIcon(QStyle::SP_TitleBarMenuButton, 0, this);
- else
- d->menuIcon = windowIcon();
-#endif
- connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
- this, SLOT(_q_processFocusChanged(QWidget*,QWidget*)));
-}
-
-/*!
- Destroys the subwindow.
-
- \sa QMdiArea::removeSubWindow()
-*/
-QMdiSubWindow::~QMdiSubWindow()
-{
- Q_D(QMdiSubWindow);
-#ifndef QT_NO_MENUBAR
- d->removeButtonsFromMenuBar();
-#endif
- d->setActive(false);
-}
-
-/*!
- Sets \a widget as the internal widget of this subwindow. The
- internal widget is displayed in the center of the subwindow
- beneath the title bar.
-
- QMdiSubWindow takes temporary ownership of \a widget; you do
- not have to delete it. Any existing internal widget will be
- removed and reparented to the root window.
-
- \sa widget()
-*/
-void QMdiSubWindow::setWidget(QWidget *widget)
-{
- Q_D(QMdiSubWindow);
- if (!widget) {
- d->removeBaseWidget();
- return;
- }
-
- if (widget == d->baseWidget) {
- qWarning("QMdiSubWindow::setWidget: widget is already set");
- return;
- }
-
- bool wasResized = testAttribute(Qt::WA_Resized);
- d->removeBaseWidget();
-
- if (QLayout *layout = this->layout())
- layout->addWidget(widget);
- else
- widget->setParent(this);
-
-#ifndef QT_NO_SIZEGRIP
- QSizeGrip *sizeGrip = widget->findChild<QSizeGrip *>();
- if (sizeGrip)
- sizeGrip->installEventFilter(this);
- if (d->sizeGrip)
- d->sizeGrip->raise();
-#endif
-
- d->baseWidget = widget;
- d->baseWidget->installEventFilter(this);
-
- d->ignoreWindowTitleChange = true;
- bool isWindowModified = this->isWindowModified();
- if (windowTitle().isEmpty()) {
- d->updateWindowTitle(true);
- isWindowModified = d->baseWidget->isWindowModified();
- }
- if (!this->isWindowModified() && isWindowModified
- && windowTitle().contains(QLatin1String("[*]"))) {
- setWindowModified(isWindowModified);
- }
- d->lastChildWindowTitle = d->baseWidget->windowTitle();
- d->ignoreWindowTitleChange = false;
-
- if (windowIcon().isNull() && !d->baseWidget->windowIcon().isNull())
- setWindowIcon(d->baseWidget->windowIcon());
-
- d->updateGeometryConstraints();
- if (!wasResized && testAttribute(Qt::WA_Resized))
- setAttribute(Qt::WA_Resized, false);
-}
-
-/*!
- Returns the current internal widget.
-
- \sa setWidget()
-*/
-QWidget *QMdiSubWindow::widget() const
-{
- return d_func()->baseWidget;
-}
-
-
-/*!
- \internal
-*/
-QWidget *QMdiSubWindow::maximizedButtonsWidget() const
-{
- Q_D(const QMdiSubWindow);
- if (isVisible() && d->controlContainer && isMaximized() && !d->drawTitleBarWhenMaximized()
- && !isChildOfTabbedQMdiArea(this)) {
- return d->controlContainer->controllerWidget();
- }
- return 0;
-}
-
-/*!
- \internal
-*/
-QWidget *QMdiSubWindow::maximizedSystemMenuIconWidget() const
-{
- Q_D(const QMdiSubWindow);
- if (isVisible() && d->controlContainer && isMaximized() && !d->drawTitleBarWhenMaximized()
- && !isChildOfTabbedQMdiArea(this)) {
- return d->controlContainer->systemMenuLabel();
- }
- return 0;
-}
-
-/*!
- Returns true if this window is shaded; otherwise returns false.
-
- A window is shaded if it is collapsed so that only the title bar is
- visible.
-*/
-bool QMdiSubWindow::isShaded() const
-{
- return d_func()->isShadeMode;
-}
-
-/*!
- If \a on is true, \a option is enabled on the subwindow; otherwise it is
- disabled. See SubWindowOption for the effect of each option.
-
- \sa SubWindowOption, testOption()
-*/
-void QMdiSubWindow::setOption(SubWindowOption option, bool on)
-{
- Q_D(QMdiSubWindow);
- if (on && !(d->options & option))
- d->options |= option;
- else if (!on && (d->options & option))
- d->options &= ~option;
-
-#ifndef QT_NO_RUBBERBAND
- if ((option & (RubberBandResize | RubberBandMove)) && !on && d->isInRubberBandMode)
- d->leaveRubberBandMode();
-#endif
-}
-
-/*!
- Returns true if \a option is enabled; otherwise returns false.
-
- \sa SubWindowOption, setOption()
-*/
-bool QMdiSubWindow::testOption(SubWindowOption option) const
-{
- return d_func()->options & option;
-}
-
-/*!
- \property QMdiSubWindow::keyboardSingleStep
- \brief sets how far a widget should move or resize when using the
- keyboard arrow keys.
-
- When in keyboard-interactive mode, you can use the arrow and page keys to
- either move or resize the window. This property controls the arrow keys.
- The common way to enter keyboard interactive mode is to enter the
- subwindow menu, and select either "resize" or "move".
-
- The default keyboard single step value is 5 pixels.
-
- \sa keyboardPageStep
-*/
-int QMdiSubWindow::keyboardSingleStep() const
-{
- return d_func()->keyboardSingleStep;
-}
-
-void QMdiSubWindow::setKeyboardSingleStep(int step)
-{
- // Haven't done any boundary check here since negative step only
- // means inverted behavior, which is OK if the user want it.
- // A step equal to zero means "do nothing".
- d_func()->keyboardSingleStep = step;
-}
-
-/*!
- \property QMdiSubWindow::keyboardPageStep
- \brief sets how far a widget should move or resize when using the
- keyboard page keys.
-
- When in keyboard-interactive mode, you can use the arrow and page keys to
- either move or resize the window. This property controls the page
- keys. The common way to enter keyboard interactive mode is to enter the
- subwindow menu, and select either "resize" or "move".
-
- The default keyboard page step value is 20 pixels.
-
- \sa keyboardSingleStep
-*/
-int QMdiSubWindow::keyboardPageStep() const
-{
- return d_func()->keyboardPageStep;
-}
-
-void QMdiSubWindow::setKeyboardPageStep(int step)
-{
- // Haven't done any boundary check here since negative step only
- // means inverted behavior, which is OK if the user want it.
- // A step equal to zero means "do nothing".
- d_func()->keyboardPageStep = step;
-}
-
-#ifndef QT_NO_MENU
-/*!
- Sets \a systemMenu as the current system menu for this subwindow.
-
- By default, each QMdiSubWindow has a standard system menu.
-
- QActions for the system menu created by QMdiSubWindow will
- automatically be updated depending on the current window state;
- e.g., the minimize action will be disabled after the window is
- minimized.
-
- QActions added by the user are not updated by QMdiSubWindow.
-
- QMdiSubWindow takes ownership of \a systemMenu; you do not have to
- delete it. Any existing menus will be deleted.
-
- \sa systemMenu(), showSystemMenu()
-*/
-void QMdiSubWindow::setSystemMenu(QMenu *systemMenu)
-{
- Q_D(QMdiSubWindow);
- if (systemMenu && systemMenu == d->systemMenu) {
- qWarning("QMdiSubWindow::setSystemMenu: system menu is already set");
- return;
- }
-
- if (d->systemMenu) {
- delete d->systemMenu;
- d->systemMenu = 0;
- }
-
- if (!systemMenu)
- return;
-
- if (systemMenu->parent() != this)
- systemMenu->setParent(this);
- d->systemMenu = systemMenu;
-}
-
-/*!
- Returns a pointer to the current system menu, or zero if no system
- menu is set. QMdiSubWindow provides a default system menu, but you can
- also set the menu with setSystemMenu().
-
- \sa setSystemMenu(), showSystemMenu()
-*/
-QMenu *QMdiSubWindow::systemMenu() const
-{
- return d_func()->systemMenu;
-}
-
-/*!
- Shows the system menu below the system menu icon in the title bar.
-
- \sa setSystemMenu(), systemMenu()
-*/
-void QMdiSubWindow::showSystemMenu()
-{
- Q_D(QMdiSubWindow);
- if (!d->systemMenu)
- return;
-
- QPoint globalPopupPos;
- if (QWidget *icon = maximizedSystemMenuIconWidget()) {
- if (isLeftToRight())
- globalPopupPos = icon->mapToGlobal(QPoint(0, icon->y() + icon->height()));
- else
- globalPopupPos = icon->mapToGlobal(QPoint(icon->width(), icon->y() + icon->height()));
- } else {
- if (isLeftToRight())
- globalPopupPos = mapToGlobal(contentsRect().topLeft());
- else // + QPoint(1, 0) because topRight() == QPoint(left() + width() -1, top())
- globalPopupPos = mapToGlobal(contentsRect().topRight()) + QPoint(1, 0);
- }
-
- // Adjust x() with -menuwidth in reverse mode.
- if (isRightToLeft())
- globalPopupPos -= QPoint(d->systemMenu->sizeHint().width(), 0);
- d->systemMenu->installEventFilter(this);
- d->systemMenu->popup(globalPopupPos);
-}
-#endif // QT_NO_MENU
-
-/*!
- \since 4.4
-
- Returns the area containing this sub-window, or 0 if there is none.
-
- \sa QMdiArea::addSubWindow()
-*/
-QMdiArea *QMdiSubWindow::mdiArea() const
-{
- QWidget *parent = parentWidget();
- while (parent) {
- if (QMdiArea *area = qobject_cast<QMdiArea *>(parent)) {
- if (area->viewport() == parentWidget())
- return area;
- }
- parent = parent->parentWidget();
- }
- return 0;
-}
-
-/*!
- Calling this function makes the subwindow enter the shaded mode.
- When the subwindow is shaded, only the title bar is visible.
-
- Although shading is not supported by all styles, this function will
- still show the subwindow as shaded, regardless of whether support
- for shading is available. However, when used with styles without
- shading support, the user will be unable to return from shaded mode
- through the user interface (e.g., through a shade button in the title
- bar).
-
- \sa isShaded()
-*/
-void QMdiSubWindow::showShaded()
-{
- if (!parent())
- return;
-
- Q_D(QMdiSubWindow);
- // setMinimizeMode uses this function.
- if (!d->isShadeRequestFromMinimizeMode && isShaded())
- return;
-
- d->isMaximizeMode = false;
-
- QWidget *currentFocusWidget = QApplication::focusWidget();
- if (!d->restoreFocusWidget && isAncestorOf(currentFocusWidget))
- d->restoreFocusWidget = currentFocusWidget;
-
- if (!d->isShadeRequestFromMinimizeMode) {
- d->isShadeMode = true;
- d->ensureWindowState(Qt::WindowMinimized);
- }
-
-#ifndef QT_NO_MENUBAR
- d->removeButtonsFromMenuBar();
-#endif
-
- // showMinimized() will reset Qt::WindowActive, which makes sense
- // for top level widgets, but in MDI it makes sense to have an
- // active window which is minimized.
- if (hasFocus() || isAncestorOf(currentFocusWidget))
- d->ensureWindowState(Qt::WindowActive);
-
-#ifndef QT_NO_SIZEGRIP
- d->setSizeGripVisible(false);
-#endif
-
- if (!d->restoreSize.isValid() || d->isShadeMode) {
- d->oldGeometry = geometry();
- d->restoreSize.setWidth(d->oldGeometry.width());
- d->restoreSize.setHeight(d->oldGeometry.height());
- }
-
- // Hide the window before we change the geometry to avoid multiple resize
- // events and wrong window state.
- const bool wasVisible = isVisible();
- if (wasVisible)
- setVisible(false);
-
- d->updateGeometryConstraints();
- // Update minimum size to internalMinimumSize if set by user.
- if (!minimumSize().isNull()) {
- d->userMinimumSize = minimumSize();
- setMinimumSize(d->internalMinimumSize);
- }
- resize(d->internalMinimumSize);
-
- // Hide the internal widget if not already hidden by the user.
- if (d->baseWidget && !d->baseWidget->isHidden()) {
- d->baseWidget->hide();
- d->isWidgetHiddenByUs = true;
- }
-
- if (wasVisible)
- setVisible(true);
-
- d->setFocusWidget();
- d->resizeEnabled = false;
- d->moveEnabled = true;
- d->updateDirtyRegions();
- d->updateMask();
-
-#ifndef QT_NO_ACTION
- d->setEnabled(QMdiSubWindowPrivate::MinimizeAction, false);
- d->setEnabled(QMdiSubWindowPrivate::ResizeAction, d->resizeEnabled);
- d->setEnabled(QMdiSubWindowPrivate::MaximizeAction, true);
- d->setEnabled(QMdiSubWindowPrivate::RestoreAction, true);
- d->setEnabled(QMdiSubWindowPrivate::MoveAction, d->moveEnabled);
-#endif
-}
-
-/*!
- \reimp
-*/
-bool QMdiSubWindow::eventFilter(QObject *object, QEvent *event)
-{
- Q_D(QMdiSubWindow);
- if (!object)
- return QWidget::eventFilter(object, event);
-
-#ifndef QT_NO_MENU
- // System menu events.
- if (d->systemMenu && d->systemMenu == object) {
- if (event->type() == QEvent::MouseButtonDblClick) {
- close();
- } else if (event->type() == QEvent::MouseMove) {
- QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
- d->hoveredSubControl = d->getSubControl(mapFromGlobal(mouseEvent->globalPos()));
- } else if (event->type() == QEvent::Hide) {
- d->systemMenu->removeEventFilter(this);
- d->activeSubControl = QStyle::SC_None;
- update(QRegion(0, 0, width(), d->titleBarHeight()));
- }
- return QWidget::eventFilter(object, event);
- }
-#endif
-
-#ifndef QT_NO_SIZEGRIP
- if (object != d->baseWidget && parent() && qobject_cast<QSizeGrip *>(object)) {
- if (event->type() != QEvent::MouseButtonPress || !testOption(QMdiSubWindow::RubberBandResize))
- return QWidget::eventFilter(object, event);
- const QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
- d->mousePressPosition = parentWidget()->mapFromGlobal(mouseEvent->globalPos());
- d->oldGeometry = geometry();
- d->currentOperation = isLeftToRight() ? QMdiSubWindowPrivate::BottomRightResize
- : QMdiSubWindowPrivate::BottomLeftResize;
-#ifndef QT_NO_RUBBERBAND
- d->enterRubberBandMode();
-#endif
- return true;
- }
-#endif
-
- if (object != d->baseWidget && event->type() != QEvent::WindowTitleChange)
- return QWidget::eventFilter(object, event);
-
- switch (event->type()) {
- case QEvent::Show:
- d->setActive(true);
- break;
- case QEvent::ShowToParent:
- if (!d->isWidgetHiddenByUs)
- show();
- break;
- case QEvent::WindowStateChange: {
- QWindowStateChangeEvent *changeEvent = static_cast<QWindowStateChangeEvent*>(event);
- if (changeEvent->isOverride())
- break;
- Qt::WindowStates oldState = changeEvent->oldState();
- Qt::WindowStates newState = d->baseWidget->windowState();
- if (!(oldState & Qt::WindowMinimized) && (newState & Qt::WindowMinimized))
- showMinimized();
- else if (!(oldState & Qt::WindowMaximized) && (newState & Qt::WindowMaximized))
- showMaximized();
- else if (!(newState & (Qt::WindowMaximized | Qt::WindowMinimized)))
- showNormal();
- break;
- }
- case QEvent::Enter:
- d->currentOperation = QMdiSubWindowPrivate::None;
- d->updateCursor();
- break;
- case QEvent::LayoutRequest:
- d->updateGeometryConstraints();
- break;
- case QEvent::WindowTitleChange:
- if (d->ignoreWindowTitleChange)
- break;
- if (object == d->baseWidget) {
- d->updateWindowTitle(true);
- d->lastChildWindowTitle = d->baseWidget->windowTitle();
-#ifndef QT_NO_MENUBAR
- } else if (maximizedButtonsWidget() && d->controlContainer->menuBar() && d->controlContainer->menuBar()
- ->cornerWidget(Qt::TopRightCorner) == maximizedButtonsWidget()) {
- d->originalTitle = QString::null;
- if (d->baseWidget && d->baseWidget->windowTitle() == windowTitle())
- d->updateWindowTitle(true);
- else
- d->updateWindowTitle(false);
-#endif
- }
- break;
- case QEvent::ModifiedChange: {
- if (object != d->baseWidget)
- break;
- bool windowModified = d->baseWidget->isWindowModified();
- if (!windowModified && d->baseWidget->windowTitle() != windowTitle())
- break;
- if (windowTitle().contains(QLatin1String("[*]")))
- setWindowModified(windowModified);
- break;
- }
- default:
- break;
- }
- return QWidget::eventFilter(object, event);
-}
-
-/*!
- \reimp
-*/
-bool QMdiSubWindow::event(QEvent *event)
-{
- Q_D(QMdiSubWindow);
- switch (event->type()) {
- case QEvent::StyleChange: {
- bool wasShaded = isShaded();
- bool wasMinimized = isMinimized();
- bool wasMaximized = isMaximized();
- ensurePolished();
- setContentsMargins(0, 0, 0, 0);
- if (wasMinimized || wasMaximized || wasShaded)
- showNormal();
- d->updateGeometryConstraints();
- resize(d->internalMinimumSize.expandedTo(size()));
- d->updateMask();
- d->updateDirtyRegions();
- if (wasShaded)
- showShaded();
- else if (wasMinimized)
- showMinimized();
- else if (wasMaximized)
- showMaximized();
- break;
- }
- case QEvent::ParentAboutToChange:
- d->setActive(false);
- break;
- case QEvent::ParentChange: {
- bool wasResized = testAttribute(Qt::WA_Resized);
-#ifndef QT_NO_MENUBAR
- d->removeButtonsFromMenuBar();
-#endif
- d->currentOperation = QMdiSubWindowPrivate::None;
- d->activeSubControl = QStyle::SC_None;
- d->hoveredSubControl = QStyle::SC_None;
-#ifndef QT_NO_RUBBERBAND
- if (d->isInRubberBandMode)
- d->leaveRubberBandMode();
-#endif
- d->isShadeMode = false;
- d->isMaximizeMode = false;
- d->isWidgetHiddenByUs = false;
- if (!parent()) {
-#if !defined(QT_NO_SIZEGRIP) && defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(style()))
- delete d->sizeGrip;
-#endif
- setOption(RubberBandResize, false);
- setOption(RubberBandMove, false);
- } else {
- d->setWindowFlags(windowFlags());
- }
- setContentsMargins(0, 0, 0, 0);
- d->updateGeometryConstraints();
- d->updateCursor();
- d->updateMask();
- d->updateDirtyRegions();
- d->updateActions();
- if (!wasResized && testAttribute(Qt::WA_Resized))
- setAttribute(Qt::WA_Resized, false);
- break;
- }
- case QEvent::WindowActivate:
- if (d->ignoreNextActivationEvent) {
- d->ignoreNextActivationEvent = false;
- break;
- }
- d->isExplicitlyDeactivated = false;
- d->setActive(true);
- break;
- case QEvent::WindowDeactivate:
- if (d->ignoreNextActivationEvent) {
- d->ignoreNextActivationEvent = false;
- break;
- }
- d->isExplicitlyDeactivated = true;
- d->setActive(false);
- break;
- case QEvent::WindowTitleChange:
- if (!d->ignoreWindowTitleChange)
- d->updateWindowTitle(false);
- d->updateInternalWindowTitle();
- break;
- case QEvent::ModifiedChange:
- if (!windowTitle().contains(QLatin1String("[*]")))
- break;
-#ifndef QT_NO_MENUBAR
- if (maximizedButtonsWidget() && d->controlContainer->menuBar() && d->controlContainer->menuBar()
- ->cornerWidget(Qt::TopRightCorner) == maximizedButtonsWidget()) {
- window()->setWindowModified(isWindowModified());
- }
-#endif // QT_NO_MENUBAR
- d->updateInternalWindowTitle();
- break;
- case QEvent::LayoutDirectionChange:
- d->updateDirtyRegions();
- break;
- case QEvent::LayoutRequest:
- d->updateGeometryConstraints();
- break;
- case QEvent::WindowIconChange:
- d->menuIcon = windowIcon();
- if (d->menuIcon.isNull())
- d->menuIcon = style()->standardIcon(QStyle::SP_TitleBarMenuButton, 0, this);
- if (d->controlContainer)
- d->controlContainer->updateWindowIcon(d->menuIcon);
- if (!maximizedSystemMenuIconWidget())
- update(0, 0, width(), d->titleBarHeight());
- break;
- case QEvent::PaletteChange:
- d->titleBarPalette = d->desktopPalette();
- break;
- case QEvent::FontChange:
- d->font = font();
- break;
-#ifndef QT_NO_TOOLTIP
- case QEvent::ToolTip:
- showToolTip(static_cast<QHelpEvent *>(event), this, d->titleBarOptions(),
- QStyle::CC_TitleBar, d->hoveredSubControl);
- break;
-#endif
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::showEvent(QShowEvent *showEvent)
-{
- Q_D(QMdiSubWindow);
- if (!parent()) {
- QWidget::showEvent(showEvent);
- return;
- }
-
-#if !defined(QT_NO_SIZEGRIP) && defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(style()) && !d->sizeGrip
- && !(windowFlags() & Qt::FramelessWindowHint)) {
- d->setSizeGrip(new QSizeGrip(0));
- Q_ASSERT(d->sizeGrip);
- if (isMinimized())
- d->setSizeGripVisible(false);
- else
- d->setSizeGripVisible(true);
- resize(size().expandedTo(d->internalMinimumSize));
- }
-#endif
-
- d->updateDirtyRegions();
- // Show buttons in the menu bar if they're already not there.
- // We want to do this when QMdiSubWindow becomes visible after being hidden.
-#ifndef QT_NO_MENUBAR
- if (d->controlContainer) {
- if (QMenuBar *menuBar = d->menuBar()) {
- if (menuBar->cornerWidget(Qt::TopRightCorner) != maximizedButtonsWidget())
- d->showButtonsInMenuBar(menuBar);
- }
- }
-#endif
- d->setActive(true);
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::hideEvent(QHideEvent * /*hideEvent*/)
-{
-#ifndef QT_NO_MENUBAR
- d_func()->removeButtonsFromMenuBar();
-#endif
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::changeEvent(QEvent *changeEvent)
-{
- if (!parent()) {
- QWidget::changeEvent(changeEvent);
- return;
- }
-
- if (changeEvent->type() != QEvent::WindowStateChange) {
- QWidget::changeEvent(changeEvent);
- return;
- }
-
- QWindowStateChangeEvent *event = static_cast<QWindowStateChangeEvent *>(changeEvent);
- if (event->isOverride()) {
- event->ignore();
- return;
- }
-
- Qt::WindowStates oldState = event->oldState();
- Qt::WindowStates newState = windowState();
- if (oldState == newState) {
- changeEvent->ignore();
- return;
- }
-
- // QWidget ensures that the widget is visible _after_ setWindowState(),
- // but we need to ensure that the widget is visible _before_
- // setWindowState() returns.
- Q_D(QMdiSubWindow);
- if (!isVisible()) {
- d->ensureWindowState(Qt::WindowNoState);
- setVisible(true);
- }
-
- if (!d->oldGeometry.isValid())
- d->oldGeometry = geometry();
-
- if ((oldState & Qt::WindowActive) && (newState & Qt::WindowActive))
- d->currentOperation = QMdiSubWindowPrivate::None;
-
- if (!(oldState & Qt::WindowMinimized) && (newState & Qt::WindowMinimized))
- d->setMinimizeMode();
- else if (!(oldState & Qt::WindowMaximized) && (newState & Qt::WindowMaximized))
- d->setMaximizeMode();
- else if (!(newState & (Qt::WindowMaximized | Qt::WindowMinimized)))
- d->setNormalMode();
-
- if (d->isActive)
- d->ensureWindowState(Qt::WindowActive);
- emit windowStateChanged(oldState, windowState());
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::closeEvent(QCloseEvent *closeEvent)
-{
- Q_D(QMdiSubWindow);
- bool acceptClose = true;
- if (d->baseWidget)
- acceptClose = d->baseWidget->close();
- if (!acceptClose) {
- closeEvent->ignore();
- return;
- }
-#ifndef QT_NO_MENUBAR
- d->removeButtonsFromMenuBar();
-#endif
- d->setActive(false);
- if (parentWidget() && testAttribute(Qt::WA_DeleteOnClose)) {
- QChildEvent childRemoved(QEvent::ChildRemoved, this);
- QApplication::sendEvent(parentWidget(), &childRemoved);
- }
- closeEvent->accept();
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::leaveEvent(QEvent * /*leaveEvent*/)
-{
- Q_D(QMdiSubWindow);
- if (d->hoveredSubControl != QStyle::SC_None) {
- d->hoveredSubControl = QStyle::SC_None;
- update(QRegion(0, 0, width(), d->titleBarHeight()));
- }
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::resizeEvent(QResizeEvent *resizeEvent)
-{
- Q_D(QMdiSubWindow);
-#ifndef QT_NO_SIZEGRIP
- if (d->sizeGrip) {
- d->sizeGrip->move(isLeftToRight() ? width() - d->sizeGrip->width() : 0,
- height() - d->sizeGrip->height());
- }
-#endif
-
- if (!parent()) {
- QWidget::resizeEvent(resizeEvent);
- return;
- }
-
- if (d->isMaximizeMode)
- d->ensureWindowState(Qt::WindowMaximized);
-
- d->updateMask();
- if (!isVisible())
- return;
-
- if (d->resizeTimerId <= 0)
- d->cachedStyleOptions = d->titleBarOptions();
- else
- killTimer(d->resizeTimerId);
- d->resizeTimerId = startTimer(200);
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::timerEvent(QTimerEvent *timerEvent)
-{
- Q_D(QMdiSubWindow);
- if (timerEvent->timerId() == d->resizeTimerId) {
- killTimer(d->resizeTimerId);
- d->resizeTimerId = -1;
- d->updateDirtyRegions();
- }
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::moveEvent(QMoveEvent *moveEvent)
-{
- if (!parent()) {
- QWidget::moveEvent(moveEvent);
- return;
- }
-
- Q_D(QMdiSubWindow);
- if (d->isMaximizeMode)
- d->ensureWindowState(Qt::WindowMaximized);
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::paintEvent(QPaintEvent *paintEvent)
-{
- if (!parent() || (windowFlags() & Qt::FramelessWindowHint)) {
- QWidget::paintEvent(paintEvent);
- return;
- }
-
- Q_D(QMdiSubWindow);
- if (isMaximized() && !d->drawTitleBarWhenMaximized())
- return;
-
- if (d->resizeTimerId != -1) {
- // Only update the style option rect and the window title.
- int border = d->hasBorder(d->cachedStyleOptions) ? 4 : 0;
- int titleBarHeight = d->titleBarHeight(d->cachedStyleOptions);
- titleBarHeight -= isMinimized() ? 2 * border : border;
- d->cachedStyleOptions.rect = QRect(border, border, width() - 2 * border, titleBarHeight);
- if (!d->windowTitle.isEmpty()) {
- int width = style()->subControlRect(QStyle::CC_TitleBar, &d->cachedStyleOptions,
- QStyle::SC_TitleBarLabel, this).width();
- d->cachedStyleOptions.text = d->cachedStyleOptions.fontMetrics
- .elidedText(d->windowTitle, Qt::ElideRight, width);
- }
- } else {
- // Force full update.
- d->cachedStyleOptions = d->titleBarOptions();
- }
-
- QStylePainter painter(this);
- if (!d->windowTitle.isEmpty())
- painter.setFont(d->font);
- painter.drawComplexControl(QStyle::CC_TitleBar, d->cachedStyleOptions);
-
- if (isMinimized() && !d->hasBorder(d->cachedStyleOptions))
- return;
-
- QStyleOptionFrame frameOptions;
- frameOptions.initFrom(this);
- frameOptions.lineWidth = style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, this);
- if (d->isActive)
- frameOptions.state |= QStyle::State_Active;
- else
- frameOptions.state &= ~QStyle::State_Active;
-
- // ### Ensure that we do not require setting the cliprect for 4.4
- if (!isMinimized() && !d->hasBorder(d->cachedStyleOptions))
- painter.setClipRect(rect().adjusted(0, d->titleBarHeight(d->cachedStyleOptions), 0, 0));
- if (!isMinimized() || d->hasBorder(d->cachedStyleOptions))
- painter.drawPrimitive(QStyle::PE_FrameWindow, frameOptions);
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::mousePressEvent(QMouseEvent *mouseEvent)
-{
- if (!parent()) {
- QWidget::mousePressEvent(mouseEvent);
- return;
- }
-
- Q_D(QMdiSubWindow);
- if (d->isInInteractiveMode)
- d->leaveInteractiveMode();
-#ifndef QT_NO_RUBBERBAND
- if (d->isInRubberBandMode)
- d->leaveRubberBandMode();
-#endif
-
- if (mouseEvent->button() != Qt::LeftButton) {
- mouseEvent->ignore();
- return;
- }
-
- if (d->currentOperation != QMdiSubWindowPrivate::None) {
- d->updateCursor();
- d->mousePressPosition = mapToParent(mouseEvent->pos());
- if (d->resizeEnabled || d->moveEnabled)
- d->oldGeometry = geometry();
-#ifndef QT_NO_RUBBERBAND
- if ((testOption(QMdiSubWindow::RubberBandResize) && d->isResizeOperation())
- || (testOption(QMdiSubWindow::RubberBandMove) && d->isMoveOperation())) {
- d->enterRubberBandMode();
- }
-#endif
- return;
- }
-
- d->activeSubControl = d->hoveredSubControl;
-#ifndef QT_NO_MENU
- if (d->activeSubControl == QStyle::SC_TitleBarSysMenu)
- showSystemMenu();
- else
-#endif
- update(QRegion(0, 0, width(), d->titleBarHeight()));
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::mouseDoubleClickEvent(QMouseEvent *mouseEvent)
-{
- if (!parent()) {
- QWidget::mouseDoubleClickEvent(mouseEvent);
- return;
- }
-
- if (mouseEvent->button() != Qt::LeftButton) {
- mouseEvent->ignore();
- return;
- }
-
- Q_D(QMdiSubWindow);
- if (!d->isMoveOperation()) {
-#ifndef QT_NO_MENU
- if (d->hoveredSubControl == QStyle::SC_TitleBarSysMenu)
- close();
-#endif
- return;
- }
-
- Qt::WindowFlags flags = windowFlags();
- if (isMinimized()) {
- if ((isShaded() && (flags & Qt::WindowShadeButtonHint))
- || (flags & Qt::WindowMinimizeButtonHint)) {
- showNormal();
- }
- return;
- }
-
- if (isMaximized()) {
- if (flags & Qt::WindowMaximizeButtonHint)
- showNormal();
- return;
- }
-
- if (flags & Qt::WindowShadeButtonHint)
- showShaded();
- else if (flags & Qt::WindowMaximizeButtonHint)
- showMaximized();
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::mouseReleaseEvent(QMouseEvent *mouseEvent)
-{
- if (!parent()) {
- QWidget::mouseReleaseEvent(mouseEvent);
- return;
- }
-
- if (mouseEvent->button() != Qt::LeftButton) {
- mouseEvent->ignore();
- return;
- }
-
- Q_D(QMdiSubWindow);
- if (d->currentOperation != QMdiSubWindowPrivate::None) {
-#ifndef QT_NO_RUBBERBAND
- if (d->isInRubberBandMode && !d->isInInteractiveMode)
- d->leaveRubberBandMode();
-#endif
- if (d->resizeEnabled || d->moveEnabled)
- d->oldGeometry = geometry();
- }
-
- d->currentOperation = d->getOperation(mouseEvent->pos());
- d->updateCursor();
-
- d->hoveredSubControl = d->getSubControl(mouseEvent->pos());
- if (d->activeSubControl != QStyle::SC_None
- && d->activeSubControl == d->hoveredSubControl) {
- d->processClickedSubControl();
- }
- d->activeSubControl = QStyle::SC_None;
- update(QRegion(0, 0, width(), d->titleBarHeight()));
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::mouseMoveEvent(QMouseEvent *mouseEvent)
-{
- if (!parent()) {
- QWidget::mouseMoveEvent(mouseEvent);
- return;
- }
-
- Q_D(QMdiSubWindow);
- // No update needed if we're in a move/resize operation.
- if (!d->isMoveOperation() && !d->isResizeOperation()) {
- // Find previous and current hover region.
- const QStyleOptionTitleBar options = d->titleBarOptions();
- QStyle::SubControl oldHover = d->hoveredSubControl;
- d->hoveredSubControl = d->getSubControl(mouseEvent->pos());
- QRegion hoverRegion;
- if (isHoverControl(oldHover) && oldHover != d->hoveredSubControl)
- hoverRegion += style()->subControlRect(QStyle::CC_TitleBar, &options, oldHover, this);
- if (isHoverControl(d->hoveredSubControl) && d->hoveredSubControl != oldHover) {
- hoverRegion += style()->subControlRect(QStyle::CC_TitleBar, &options,
- d->hoveredSubControl, this);
- }
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- if (qobject_cast<QMacStyle *>(style()) && !hoverRegion.isEmpty())
- hoverRegion += QRegion(0, 0, width(), d->titleBarHeight(options));
-#endif
- if (!hoverRegion.isEmpty())
- update(hoverRegion);
- }
-
- if ((mouseEvent->buttons() & Qt::LeftButton) || d->isInInteractiveMode) {
- if ((d->isResizeOperation() && d->resizeEnabled) || (d->isMoveOperation() && d->moveEnabled))
- d->setNewGeometry(mapToParent(mouseEvent->pos()));
- return;
- }
-
- // Do not resize/move if not allowed.
- d->currentOperation = d->getOperation(mouseEvent->pos());
- if ((d->isResizeOperation() && !d->resizeEnabled) || (d->isMoveOperation() && !d->moveEnabled))
- d->currentOperation = QMdiSubWindowPrivate::None;
- d->updateCursor();
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::keyPressEvent(QKeyEvent *keyEvent)
-{
- Q_D(QMdiSubWindow);
- if (!d->isInInteractiveMode || !parent()) {
- keyEvent->ignore();
- return;
- }
-
- QPoint delta;
- switch (keyEvent->key()) {
- case Qt::Key_Right:
- if (keyEvent->modifiers() & Qt::ShiftModifier)
- delta = QPoint(d->keyboardPageStep, 0);
- else
- delta = QPoint(d->keyboardSingleStep, 0);
- break;
- case Qt::Key_Up:
- if (keyEvent->modifiers() & Qt::ShiftModifier)
- delta = QPoint(0, -d->keyboardPageStep);
- else
- delta = QPoint(0, -d->keyboardSingleStep);
- break;
- case Qt::Key_Left:
- if (keyEvent->modifiers() & Qt::ShiftModifier)
- delta = QPoint(-d->keyboardPageStep, 0);
- else
- delta = QPoint(-d->keyboardSingleStep, 0);
- break;
- case Qt::Key_Down:
- if (keyEvent->modifiers() & Qt::ShiftModifier)
- delta = QPoint(0, d->keyboardPageStep);
- else
- delta = QPoint(0, d->keyboardSingleStep);
- break;
- case Qt::Key_Escape:
- case Qt::Key_Return:
- case Qt::Key_Enter:
- d->leaveInteractiveMode();
- return;
- default:
- keyEvent->ignore();
- return;
- }
-
-#ifndef QT_NO_CURSOR
- QPoint newPosition = parentWidget()->mapFromGlobal(cursor().pos() + delta);
- QRect oldGeometry =
-#ifndef QT_NO_RUBBERBAND
- d->isInRubberBandMode ? d->rubberBand->geometry() :
-#endif
- geometry();
- d->setNewGeometry(newPosition);
- QRect currentGeometry =
-#ifndef QT_NO_RUBBERBAND
- d->isInRubberBandMode ? d->rubberBand->geometry() :
-#endif
- geometry();
- if (currentGeometry == oldGeometry)
- return;
-
- // Update cursor position
-
- QPoint actualDelta;
- if (d->isMoveOperation()) {
- actualDelta = QPoint(currentGeometry.x() - oldGeometry.x(),
- currentGeometry.y() - oldGeometry.y());
- } else {
- int dx = isLeftToRight() ? currentGeometry.width() - oldGeometry.width()
- : currentGeometry.x() - oldGeometry.x();
- actualDelta = QPoint(dx, currentGeometry.height() - oldGeometry.height());
- }
-
- // Adjust in case we weren't able to move as long as wanted.
- if (actualDelta != delta)
- newPosition += (actualDelta - delta);
- cursor().setPos(parentWidget()->mapToGlobal(newPosition));
-#endif
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \reimp
-*/
-void QMdiSubWindow::contextMenuEvent(QContextMenuEvent *contextMenuEvent)
-{
- Q_D(QMdiSubWindow);
- if (!d->systemMenu) {
- contextMenuEvent->ignore();
- return;
- }
-
- if (d->hoveredSubControl == QStyle::SC_TitleBarSysMenu
- || d->getRegion(QMdiSubWindowPrivate::Move).contains(contextMenuEvent->pos())) {
- d->systemMenu->exec(contextMenuEvent->globalPos());
- } else {
- contextMenuEvent->ignore();
- }
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::focusInEvent(QFocusEvent *focusInEvent)
-{
- d_func()->focusInReason = focusInEvent->reason();
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::focusOutEvent(QFocusEvent * /*focusOutEvent*/)
-{
- // To avoid update() in QWidget::focusOutEvent.
-}
-
-/*!
- \reimp
-*/
-void QMdiSubWindow::childEvent(QChildEvent *childEvent)
-{
- if (childEvent->type() != QEvent::ChildPolished)
- return;
-#ifndef QT_NO_SIZEGRIP
- if (QSizeGrip *sizeGrip = qobject_cast<QSizeGrip *>(childEvent->child()))
- d_func()->setSizeGrip(sizeGrip);
-#endif
-}
-
-/*!
- \reimp
-*/
-QSize QMdiSubWindow::sizeHint() const
-{
- Q_D(const QMdiSubWindow);
- int margin, minWidth;
- d->sizeParameters(&margin, &minWidth);
- QSize size(2 * margin, d->titleBarHeight() + margin);
- if (d->baseWidget && d->baseWidget->sizeHint().isValid())
- size += d->baseWidget->sizeHint();
- return size.expandedTo(minimumSizeHint());
-}
-
-/*!
- \reimp
-*/
-QSize QMdiSubWindow::minimumSizeHint() const
-{
- Q_D(const QMdiSubWindow);
- if (isVisible())
- ensurePolished();
-
- // Minimized window.
- if (parent() && isMinimized() && !isShaded())
- return d->iconSize();
-
- // Calculate window decoration.
- int margin, minWidth;
- d->sizeParameters(&margin, &minWidth);
- int decorationHeight = margin + d->titleBarHeight();
- int minHeight = decorationHeight;
-
- // Shaded window.
- if (parent() && isShaded())
- return QSize(qMax(minWidth, width()), d->titleBarHeight());
-
- // Content
- if (layout()) {
- QSize minLayoutSize = layout()->minimumSize();
- if (minLayoutSize.isValid()) {
- minWidth = qMax(minWidth, minLayoutSize.width() + 2 * margin);
- minHeight += minLayoutSize.height();
- }
- } else if (d->baseWidget && d->baseWidget->isVisible()) {
- QSize minBaseWidgetSize = d->baseWidget->minimumSizeHint();
- if (minBaseWidgetSize.isValid()) {
- minWidth = qMax(minWidth, minBaseWidgetSize.width() + 2 * margin);
- minHeight += minBaseWidgetSize.height();
- }
- }
-
-#ifndef QT_NO_SIZEGRIP
- // SizeGrip
- int sizeGripHeight = 0;
- if (d->sizeGrip && d->sizeGrip->isVisibleTo(const_cast<QMdiSubWindow *>(this)))
- sizeGripHeight = d->sizeGrip->height();
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
- else if (parent() && qobject_cast<QMacStyle *>(style()) && !d->sizeGrip)
- sizeGripHeight = style()->pixelMetric(QStyle::PM_SizeGripSize, 0, this);
-#endif
- minHeight = qMax(minHeight, decorationHeight + sizeGripHeight);
-#endif
-
- return QSize(minWidth, minHeight).expandedTo(QApplication::globalStrut());
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qmdisubwindow.cpp"
-#include "qmdisubwindow.moc"
-
-#endif //QT_NO_MDIAREA
diff --git a/src/gui/widgets/qmdisubwindow.h b/src/gui/widgets/qmdisubwindow.h
deleted file mode 100644
index 98c7b4c9c4..0000000000
--- a/src/gui/widgets/qmdisubwindow.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/****************************************************************************
-**
-** 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 QMDISUBWINDOW_H
-#define QMDISUBWINDOW_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_MDIAREA
-
-class QMenu;
-class QMdiArea;
-
-namespace QMdi { class ControlContainer; }
-class QMdiSubWindowPrivate;
-class Q_GUI_EXPORT QMdiSubWindow : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(int keyboardSingleStep READ keyboardSingleStep WRITE setKeyboardSingleStep)
- Q_PROPERTY(int keyboardPageStep READ keyboardPageStep WRITE setKeyboardPageStep)
-public:
- enum SubWindowOption {
- AllowOutsideAreaHorizontally = 0x1, // internal
- AllowOutsideAreaVertically = 0x2, // internal
- RubberBandResize = 0x4,
- RubberBandMove = 0x8
- };
- Q_DECLARE_FLAGS(SubWindowOptions, SubWindowOption)
-
- QMdiSubWindow(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QMdiSubWindow();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- void setWidget(QWidget *widget);
- QWidget *widget() const;
-
- QWidget *maximizedButtonsWidget() const; // internal
- QWidget *maximizedSystemMenuIconWidget() const; // internal
-
- bool isShaded() const;
-
- void setOption(SubWindowOption option, bool on = true);
- bool testOption(SubWindowOption) const;
-
- void setKeyboardSingleStep(int step);
- int keyboardSingleStep() const;
-
- void setKeyboardPageStep(int step);
- int keyboardPageStep() const;
-
-#ifndef QT_NO_MENU
- void setSystemMenu(QMenu *systemMenu);
- QMenu *systemMenu() const;
-#endif
-
- QMdiArea *mdiArea() const;
-
-Q_SIGNALS:
- void windowStateChanged(Qt::WindowStates oldState, Qt::WindowStates newState);
- void aboutToActivate();
-
-public Q_SLOTS:
-#ifndef QT_NO_MENU
- void showSystemMenu();
-#endif
- void showShaded();
-
-protected:
- bool eventFilter(QObject *object, QEvent *event);
- bool event(QEvent *event);
- void showEvent(QShowEvent *showEvent);
- void hideEvent(QHideEvent *hideEvent);
- void changeEvent(QEvent *changeEvent);
- void closeEvent(QCloseEvent *closeEvent);
- void leaveEvent(QEvent *leaveEvent);
- void resizeEvent(QResizeEvent *resizeEvent);
- void timerEvent(QTimerEvent *timerEvent);
- void moveEvent(QMoveEvent *moveEvent);
- void paintEvent(QPaintEvent *paintEvent);
- void mousePressEvent(QMouseEvent *mouseEvent);
- void mouseDoubleClickEvent(QMouseEvent *mouseEvent);
- void mouseReleaseEvent(QMouseEvent *mouseEvent);
- void mouseMoveEvent(QMouseEvent *mouseEvent);
- void keyPressEvent(QKeyEvent *keyEvent);
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *contextMenuEvent);
-#endif
- void focusInEvent(QFocusEvent *focusInEvent);
- void focusOutEvent(QFocusEvent *focusOutEvent);
- void childEvent(QChildEvent *childEvent);
-
-private:
- Q_DISABLE_COPY(QMdiSubWindow)
- Q_DECLARE_PRIVATE(QMdiSubWindow)
- Q_PRIVATE_SLOT(d_func(), void _q_updateStaysOnTopHint())
- Q_PRIVATE_SLOT(d_func(), void _q_enterInteractiveMode())
- Q_PRIVATE_SLOT(d_func(), void _q_processFocusChanged(QWidget *, QWidget *))
- friend class QMdiAreaPrivate;
-#ifndef QT_NO_TABBAR
- friend class QMdiAreaTabBar;
-#endif
- friend class QMdi::ControlContainer;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QMdiSubWindow::SubWindowOptions)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_MDIAREA
-
-#endif // QMDISUBWINDOW_H
diff --git a/src/gui/widgets/qmdisubwindow_p.h b/src/gui/widgets/qmdisubwindow_p.h
deleted file mode 100644
index e5b9d8091f..0000000000
--- a/src/gui/widgets/qmdisubwindow_p.h
+++ /dev/null
@@ -1,348 +0,0 @@
-/****************************************************************************
-**
-** 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 QMDISUBWINDOW_P_H
-#define QMDISUBWINDOW_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmdisubwindow.h"
-
-#ifndef QT_NO_MDIAREA
-
-#include <QStyle>
-#include <QStyleOptionTitleBar>
-#include <QMenuBar>
-#include <QSizeGrip>
-#include <QPointer>
-#include <QDebug>
-#include <private/qwidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QVBoxLayout;
-class QMouseEvent;
-
-namespace QMdi {
-template<typename T>
-class ControlElement : public T
-{
-public:
- ControlElement(QMdiSubWindow *child) : T(child, 0)
- {
- Q_ASSERT(child);
- mdiChild = child;
- }
-
- void *qt_metacast(const char *classname)
- {
- if (classname && strcmp(classname, "ControlElement") == 0)
- return this;
- return 0;
- }
-
- QPointer<QMdiSubWindow> mdiChild;
-};
-
-class ControlContainer : public QObject
-{
-public:
- ControlContainer(QMdiSubWindow *mdiChild);
- ~ControlContainer();
-
-#ifndef QT_NO_MENUBAR
- void showButtonsInMenuBar(QMenuBar *menuBar);
- void removeButtonsFromMenuBar(QMenuBar *menuBar = 0);
- QMenuBar *menuBar() const { return m_menuBar; }
-#endif
- void updateWindowIcon(const QIcon &windowIcon);
- QWidget *controllerWidget() const { return m_controllerWidget; }
- QWidget *systemMenuLabel() const { return m_menuLabel; }
-
-private:
- QPointer<QWidget> previousLeft;
- QPointer<QWidget> previousRight;
-#ifndef QT_NO_MENUBAR
- QPointer<QMenuBar> m_menuBar;
-#endif
- QPointer<QWidget> m_controllerWidget;
- QPointer<QWidget> m_menuLabel;
- QPointer<QMdiSubWindow> mdiChild;
-};
-} // namespace QMdi
-
-class QMdiSubWindowPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QMdiSubWindow)
-public:
- // Enums and typedefs.
- enum Operation {
- None,
- Move,
- TopResize,
- BottomResize,
- LeftResize,
- RightResize,
- TopLeftResize,
- TopRightResize,
- BottomLeftResize,
- BottomRightResize
- };
-
- enum ChangeFlag {
- HMove = 0x01,
- VMove = 0x02,
- HResize = 0x04,
- VResize = 0x08,
- HResizeReverse = 0x10,
- VResizeReverse = 0x20
- };
-
- enum WindowStateAction {
- RestoreAction,
- MoveAction,
- ResizeAction,
- MinimizeAction,
- MaximizeAction,
- StayOnTopAction,
- CloseAction,
- /* Add new states _above_ this line! */
- NumWindowStateActions
- };
-
- struct OperationInfo {
- uint changeFlags;
- Qt::CursorShape cursorShape;
- QRegion region;
- bool hover;
- OperationInfo(uint changeFlags, Qt::CursorShape cursorShape, bool hover = true)
- : changeFlags(changeFlags),
- cursorShape(cursorShape),
- hover(hover)
- {}
- };
-
- typedef QMap<Operation, OperationInfo> OperationInfoMap;
-
- QMdiSubWindowPrivate();
-
- // Variables.
- QPointer<QWidget> baseWidget;
- QPointer<QWidget> restoreFocusWidget;
- QPointer<QMdi::ControlContainer> controlContainer;
-#ifndef QT_NO_SIZEGRIP
- QPointer<QSizeGrip> sizeGrip;
-#endif
-#ifndef QT_NO_RUBBERBAND
- QRubberBand *rubberBand;
-#endif
- QPoint mousePressPosition;
- QRect oldGeometry;
- QSize internalMinimumSize;
- QSize userMinimumSize;
- QSize restoreSize;
- bool resizeEnabled;
- bool moveEnabled;
- bool isInInteractiveMode;
-#ifndef QT_NO_RUBBERBAND
- bool isInRubberBandMode;
-#endif
- bool isShadeMode;
- bool ignoreWindowTitleChange;
- bool ignoreNextActivationEvent;
- bool activationEnabled;
- bool isShadeRequestFromMinimizeMode;
- bool isMaximizeMode;
- bool isWidgetHiddenByUs;
- bool isActive;
- bool isExplicitlyDeactivated;
- int keyboardSingleStep;
- int keyboardPageStep;
- int resizeTimerId;
- Operation currentOperation;
- QStyle::SubControl hoveredSubControl;
- QStyle::SubControl activeSubControl;
- Qt::FocusReason focusInReason;
- OperationInfoMap operationMap;
- QPointer<QMenu> systemMenu;
-#ifndef QT_NO_ACTIONS
- QPointer<QAction> actions[NumWindowStateActions];
-#endif
- QMdiSubWindow::SubWindowOptions options;
- QString lastChildWindowTitle;
- QPalette titleBarPalette;
- QString windowTitle;
- QFont font;
- QIcon menuIcon;
- QStyleOptionTitleBar cachedStyleOptions;
- QString originalTitle;
-
- // Slots.
- void _q_updateStaysOnTopHint();
- void _q_enterInteractiveMode();
- void _q_processFocusChanged(QWidget *old, QWidget *now);
-
- // Functions.
- void leaveInteractiveMode();
- void removeBaseWidget();
- void initOperationMap();
-#ifndef QT_NO_MENU
- void createSystemMenu();
-#endif
- void updateCursor();
- void updateDirtyRegions();
- void updateGeometryConstraints();
- void updateMask();
- void setNewGeometry(const QPoint &pos);
- void setMinimizeMode();
- void setNormalMode();
- void setMaximizeMode();
- void setActive(bool activate, bool changeFocus = true);
- void processClickedSubControl();
- QRegion getRegion(Operation operation) const;
- Operation getOperation(const QPoint &pos) const;
- QStyleOptionTitleBar titleBarOptions() const;
- void ensureWindowState(Qt::WindowState state);
- int titleBarHeight(const QStyleOptionTitleBar &options) const;
- void sizeParameters(int *margin, int *minWidth) const;
- bool drawTitleBarWhenMaximized() const;
-#ifndef QT_NO_MENUBAR
- QMenuBar *menuBar() const;
- void showButtonsInMenuBar(QMenuBar *menuBar);
- void removeButtonsFromMenuBar();
-#endif
- void updateWindowTitle(bool requestFromChild);
-#ifndef QT_NO_RUBBERBAND
- void enterRubberBandMode();
- void leaveRubberBandMode();
-#endif
- QPalette desktopPalette() const;
- void updateActions();
- void setFocusWidget();
- void restoreFocus();
- void setWindowFlags(Qt::WindowFlags windowFlags);
- void setVisible(WindowStateAction, bool visible = true);
-#ifndef QT_NO_ACTION
- void setEnabled(WindowStateAction, bool enable = true);
-#ifndef QT_NO_MENU
- void addToSystemMenu(WindowStateAction, const QString &text, const char *slot);
-#endif
-#endif // QT_NO_ACTION
- QSize iconSize() const;
-#ifndef QT_NO_SIZEGRIP
- void setSizeGrip(QSizeGrip *sizeGrip);
- void setSizeGripVisible(bool visible = true) const;
-#endif
- void updateInternalWindowTitle();
- QString originalWindowTitle();
- void setNewWindowTitle();
-
- inline int titleBarHeight() const
- {
- Q_Q(const QMdiSubWindow);
- if (!parent || q->windowFlags() & Qt::FramelessWindowHint
- || (q->isMaximized() && !drawTitleBarWhenMaximized())) {
- return 0;
- }
- QStyleOptionTitleBar options = titleBarOptions();
- int height = options.rect.height();
- if (hasBorder(options))
- height += q->isMinimized() ? 8 : 4;
- return height;
- }
-
- inline QStyle::SubControl getSubControl(const QPoint &pos) const
- {
- Q_Q(const QMdiSubWindow);
- QStyleOptionTitleBar titleBarOptions = this->titleBarOptions();
- return q->style()->hitTestComplexControl(QStyle::CC_TitleBar, &titleBarOptions, pos, q);
- }
-
- inline void setNewGeometry(QRect *geometry)
- {
- Q_Q(QMdiSubWindow);
- Q_ASSERT(parent);
- geometry->setSize(geometry->size().expandedTo(internalMinimumSize));
-#ifndef QT_NO_RUBBERBAND
- if (isInRubberBandMode)
- rubberBand->setGeometry(*geometry);
- else
-#endif
- q->setGeometry(*geometry);
- }
-
- inline bool hasBorder(const QStyleOptionTitleBar &options) const
- {
- Q_Q(const QMdiSubWindow);
- return !q->style()->styleHint(QStyle::SH_TitleBar_NoBorder, &options, q);
- }
-
- inline bool autoRaise() const
- {
- Q_Q(const QMdiSubWindow);
- return q->style()->styleHint(QStyle::SH_TitleBar_AutoRaise, 0, q);
- }
-
- inline bool isResizeOperation() const
- {
- return currentOperation != None && currentOperation != Move;
- }
-
- inline bool isMoveOperation() const
- {
- return currentOperation == Move;
- }
-};
-
-#endif // QT_NO_MDIAREA
-
-QT_END_NAMESPACE
-
-#endif // QMDISUBWINDOW_P_H
diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp
deleted file mode 100644
index b12e5c5528..0000000000
--- a/src/gui/widgets/qmenu.cpp
+++ /dev/null
@@ -1,3525 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmenu.h"
-
-#ifndef QT_NO_MENU
-
-#include "qdebug.h"
-#include "qstyle.h"
-#include "qevent.h"
-#include "qtimer.h"
-#include "qlayout.h"
-#include "qpainter.h"
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#ifndef QT_NO_ACCESSIBILITY
-# include "qaccessible.h"
-#endif
-#ifndef QT_NO_EFFECTS
-# include <private/qeffects_p.h>
-#endif
-#ifndef QT_NO_WHATSTHIS
-# include <qwhatsthis.h>
-#endif
-
-#include "qmenu_p.h"
-#include "qmenubar_p.h"
-#include "qwidgetaction.h"
-#include "qtoolbutton.h"
-#include "qpushbutton.h"
-#include <private/qpushbutton_p.h>
-#include <private/qaction_p.h>
-#include <private/qsoftkeymanager_p.h>
-#ifdef QT3_SUPPORT
-#include <qmenudata.h>
-#endif // QT3_SUPPORT
-
-#ifdef Q_WS_X11
-# include <private/qt_x11_p.h>
-#endif
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_EFFECTS)
-# include <private/qcore_mac_p.h>
-# include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-
-QT_BEGIN_NAMESPACE
-
-QMenu *QMenuPrivate::mouseDown = 0;
-int QMenuPrivate::sloppyDelayTimer = 0;
-
-/* QMenu code */
-// internal class used for the torn off popup
-class QTornOffMenu : public QMenu
-{
- Q_OBJECT
- class QTornOffMenuPrivate : public QMenuPrivate
- {
- Q_DECLARE_PUBLIC(QMenu)
- public:
- QTornOffMenuPrivate(QMenu *p) : causedMenu(p) {
- tornoff = 1;
- causedPopup.widget = 0;
- causedPopup.action = ((QTornOffMenu*)p)->d_func()->causedPopup.action;
- causedStack = ((QTornOffMenu*)p)->d_func()->calcCausedStack();
- }
- QList<QPointer<QWidget> > calcCausedStack() const { return causedStack; }
- QPointer<QMenu> causedMenu;
- QList<QPointer<QWidget> > causedStack;
- };
-public:
- QTornOffMenu(QMenu *p) : QMenu(*(new QTornOffMenuPrivate(p)))
- {
- Q_D(QTornOffMenu);
- // make the torn-off menu a sibling of p (instead of a child)
- QWidget *parentWidget = d->causedStack.isEmpty() ? p : d->causedStack.last();
- if (parentWidget->parentWidget())
- parentWidget = parentWidget->parentWidget();
- setParent(parentWidget, Qt::Window | Qt::Tool);
- setAttribute(Qt::WA_DeleteOnClose, true);
- setAttribute(Qt::WA_X11NetWmWindowTypeMenu, true);
- setWindowTitle(p->windowTitle());
- setEnabled(p->isEnabled());
- //QObject::connect(this, SIGNAL(triggered(QAction*)), this, SLOT(onTrigger(QAction*)));
- //QObject::connect(this, SIGNAL(hovered(QAction*)), this, SLOT(onHovered(QAction*)));
- QList<QAction*> items = p->actions();
- for(int i = 0; i < items.count(); i++)
- addAction(items.at(i));
- }
- void syncWithMenu(QMenu *menu, QActionEvent *act)
- {
- Q_D(QTornOffMenu);
- if(menu != d->causedMenu)
- return;
- if (act->type() == QEvent::ActionAdded) {
- insertAction(act->before(), act->action());
- } else if (act->type() == QEvent::ActionRemoved)
- removeAction(act->action());
- }
- void actionEvent(QActionEvent *e)
- {
- QMenu::actionEvent(e);
- setFixedSize(sizeHint());
- }
-public slots:
- void onTrigger(QAction *action) { d_func()->activateAction(action, QAction::Trigger, false); }
- void onHovered(QAction *action) { d_func()->activateAction(action, QAction::Hover, false); }
-private:
- Q_DECLARE_PRIVATE(QTornOffMenu)
- friend class QMenuPrivate;
-};
-
-void QMenuPrivate::init()
-{
- Q_Q(QMenu);
-#ifndef QT_NO_WHATSTHIS
- q->setAttribute(Qt::WA_CustomWhatsThis);
-#endif
- q->setAttribute(Qt::WA_X11NetWmWindowTypePopupMenu);
- defaultMenuAction = menuAction = new QAction(q);
- menuAction->d_func()->menu = q;
- q->setMouseTracking(q->style()->styleHint(QStyle::SH_Menu_MouseTracking, 0, q));
- if (q->style()->styleHint(QStyle::SH_Menu_Scrollable, 0, q)) {
- scroll = new QMenuPrivate::QMenuScroller;
- scroll->scrollFlags = QMenuPrivate::QMenuScroller::ScrollNone;
- }
-
-#ifdef QT_SOFTKEYS_ENABLED
- selectAction = QSoftKeyManager::createKeyedAction(QSoftKeyManager::SelectSoftKey, Qt::Key_Select, q);
- cancelAction = QSoftKeyManager::createKeyedAction(QSoftKeyManager::CancelSoftKey, Qt::Key_Back, q);
- selectAction->setPriority(QAction::HighPriority);
- cancelAction->setPriority(QAction::HighPriority);
- q->addAction(selectAction);
- q->addAction(cancelAction);
-#endif
-}
-
-int QMenuPrivate::scrollerHeight() const
-{
- Q_Q(const QMenu);
- return qMax(QApplication::globalStrut().height(), q->style()->pixelMetric(QStyle::PM_MenuScrollerHeight, 0, q));
-}
-
-//Windows and KDE allows menus to cover the taskbar, while GNOME and Mac don't
-QRect QMenuPrivate::popupGeometry(const QWidget *widget) const
-{
-#ifdef Q_WS_WIN
- return QApplication::desktop()->screenGeometry(widget);
-#elif defined Q_WS_X11
- if (X11->desktopEnvironment == DE_KDE)
- return QApplication::desktop()->screenGeometry(widget);
- else
- return QApplication::desktop()->availableGeometry(widget);
-#else
- return QApplication::desktop()->availableGeometry(widget);
-#endif
-}
-
-//Windows and KDE allows menus to cover the taskbar, while GNOME and Mac don't
-QRect QMenuPrivate::popupGeometry(int screen) const
-{
-#ifdef Q_WS_WIN
- return QApplication::desktop()->screenGeometry(screen);
-#elif defined Q_WS_X11
- if (X11->desktopEnvironment == DE_KDE)
- return QApplication::desktop()->screenGeometry(screen);
- else
- return QApplication::desktop()->availableGeometry(screen);
-#else
- return QApplication::desktop()->availableGeometry(screen);
-#endif
-}
-
-QList<QPointer<QWidget> > QMenuPrivate::calcCausedStack() const
-{
- QList<QPointer<QWidget> > ret;
- for(QWidget *widget = causedPopup.widget; widget; ) {
- ret.append(widget);
- if (QTornOffMenu *qtmenu = qobject_cast<QTornOffMenu*>(widget))
- ret += qtmenu->d_func()->causedStack;
- if (QMenu *qmenu = qobject_cast<QMenu*>(widget))
- widget = qmenu->d_func()->causedPopup.widget;
- else
- break;
- }
- return ret;
-}
-
-void QMenuPrivate::updateActionRects() const
-{
- Q_Q(const QMenu);
- if (!itemsDirty)
- return;
-
- q->ensurePolished();
-
- //let's reinitialize the buffer
- actionRects.resize(actions.count());
- actionRects.fill(QRect());
-
- //let's try to get the last visible action
- int lastVisibleAction = actions.count() - 1;
- for(;lastVisibleAction >= 0; --lastVisibleAction) {
- const QAction *action = actions.at(lastVisibleAction);
- if (action->isVisible()) {
- //removing trailing separators
- if (action->isSeparator() && collapsibleSeparators)
- continue;
- break;
- }
- }
-
- int max_column_width = 0,
- dh = popupGeometry(q).height(),
- y = 0;
- QStyle *style = q->style();
- QStyleOption opt;
- opt.init(q);
- const int hmargin = style->pixelMetric(QStyle::PM_MenuHMargin, &opt, q),
- vmargin = style->pixelMetric(QStyle::PM_MenuVMargin, &opt, q),
- icone = style->pixelMetric(QStyle::PM_SmallIconSize, &opt, q);
- const int fw = style->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, q);
- const int deskFw = style->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, &opt, q);
- const int tearoffHeight = tearoff ? style->pixelMetric(QStyle::PM_MenuTearoffHeight, &opt, q) : 0;
-
- //for compatibility now - will have to refactor this away
- tabWidth = 0;
- maxIconWidth = 0;
- hasCheckableItems = false;
- ncols = 1;
- sloppyAction = 0;
-
- for (int i = 0; i < actions.count(); ++i) {
- QAction *action = actions.at(i);
- if (action->isSeparator() || !action->isVisible() || widgetItems.contains(action))
- continue;
- //..and some members
- hasCheckableItems |= action->isCheckable();
- QIcon is = action->icon();
- if (!is.isNull()) {
- maxIconWidth = qMax<uint>(maxIconWidth, icone + 4);
- }
- }
-
- //calculate size
- QFontMetrics qfm = q->fontMetrics();
- bool previousWasSeparator = true; // this is true to allow removing the leading separators
- for(int i = 0; i <= lastVisibleAction; i++) {
- QAction *action = actions.at(i);
-
- if (!action->isVisible() ||
- (collapsibleSeparators && previousWasSeparator && action->isSeparator()))
- continue; // we continue, this action will get an empty QRect
-
- previousWasSeparator = action->isSeparator();
-
- //let the style modify the above size..
- QStyleOptionMenuItem opt;
- q->initStyleOption(&opt, action);
- const QFontMetrics &fm = opt.fontMetrics;
-
- QSize sz;
- if (QWidget *w = widgetItems.value(action)) {
- sz = w->sizeHint().expandedTo(w->minimumSize()).expandedTo(w->minimumSizeHint()).boundedTo(w->maximumSize());
- } else {
- //calc what I think the size is..
- if (action->isSeparator()) {
- sz = QSize(2, 2);
- } else {
- QString s = action->text();
- int t = s.indexOf(QLatin1Char('\t'));
- if (t != -1) {
- tabWidth = qMax(int(tabWidth), qfm.width(s.mid(t+1)));
- s = s.left(t);
- #ifndef QT_NO_SHORTCUT
- } else {
- QKeySequence seq = action->shortcut();
- if (!seq.isEmpty())
- tabWidth = qMax(int(tabWidth), qfm.width(seq));
- #endif
- }
- sz.setWidth(fm.boundingRect(QRect(), Qt::TextSingleLine | Qt::TextShowMnemonic, s).width());
- sz.setHeight(qMax(fm.height(), qfm.height()));
-
- QIcon is = action->icon();
- if (!is.isNull()) {
- QSize is_sz = QSize(icone, icone);
- if (is_sz.height() > sz.height())
- sz.setHeight(is_sz.height());
- }
- }
- sz = style->sizeFromContents(QStyle::CT_MenuItem, &opt, sz, q);
- }
-
-
- if (!sz.isEmpty()) {
- max_column_width = qMax(max_column_width, sz.width());
- //wrapping
- if (!scroll &&
- y+sz.height()+vmargin > dh - (deskFw * 2)) {
- ncols++;
- y = vmargin;
- }
- y += sz.height();
- //update the item
- actionRects[i] = QRect(0, 0, sz.width(), sz.height());
- }
- }
-
- max_column_width += tabWidth; //finally add in the tab width
- const int sfcMargin = style->sizeFromContents(QStyle::CT_Menu, &opt, QApplication::globalStrut(), q).width() - QApplication::globalStrut().width();
- const int min_column_width = q->minimumWidth() - (sfcMargin + leftmargin + rightmargin + 2 * (fw + hmargin));
- max_column_width = qMax(min_column_width, max_column_width);
-
-
- //calculate position
- const int base_y = vmargin + fw + topmargin +
- (scroll ? scroll->scrollOffset : 0) +
- tearoffHeight;
- int x = hmargin + fw + leftmargin;
- y = base_y;
-
- for(int i = 0; i < actions.count(); i++) {
- QRect &rect = actionRects[i];
- if (rect.isNull())
- continue;
- if (!scroll &&
- y+rect.height() > dh - deskFw * 2) {
- x += max_column_width + hmargin;
- y = base_y;
- }
- rect.translate(x, y); //move
- rect.setWidth(max_column_width); //uniform width
-
- //we need to update the widgets geometry
- if (QWidget *widget = widgetItems.value(actions.at(i))) {
- widget->setGeometry(rect);
- widget->setVisible(actions.at(i)->isVisible());
- }
-
- y += rect.height();
- }
- itemsDirty = 0;
-}
-
-QRect QMenuPrivate::actionRect(QAction *act) const
-{
- int index = actions.indexOf(act);
- if (index == -1)
- return QRect();
-
- updateActionRects();
-
- //we found the action
- return actionRects.at(index);
-}
-
-#if defined(Q_WS_MAC)
-static const qreal MenuFadeTimeInSec = 0.150;
-#endif
-
-void QMenuPrivate::hideUpToMenuBar()
-{
- Q_Q(QMenu);
- bool fadeMenus = q->style()->styleHint(QStyle::SH_Menu_FadeOutOnHide);
- if (!tornoff) {
- QWidget *caused = causedPopup.widget;
- hideMenu(q); //hide after getting causedPopup
- while(caused) {
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(caused)) {
- mb->d_func()->setCurrentAction(0);
- mb->d_func()->setKeyboardMode(false);
- caused = 0;
- } else
-#endif
- if (QMenu *m = qobject_cast<QMenu*>(caused)) {
- caused = m->d_func()->causedPopup.widget;
- if (!m->d_func()->tornoff)
- hideMenu(m, fadeMenus);
- if (!fadeMenus) // Mac doesn't clear the action until after hidden.
- m->d_func()->setCurrentAction(0);
- } else { caused = 0;
- }
- }
-#if defined(Q_WS_MAC)
- if (fadeMenus) {
- QEventLoop eventLoop;
- QTimer::singleShot(int(MenuFadeTimeInSec * 1000), &eventLoop, SLOT(quit()));
- QMacWindowFader::currentFader()->performFade();
- eventLoop.exec();
- }
-#endif
- }
- setCurrentAction(0);
-}
-
-void QMenuPrivate::hideMenu(QMenu *menu, bool justRegister)
-{
- if (!menu)
- return;
-#if !defined(QT_NO_EFFECTS)
- menu->blockSignals(true);
- aboutToHide = true;
- // Flash item which is about to trigger (if any).
- if (menu->style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)
- && currentAction && currentAction == actionAboutToTrigger
- && menu->actions().contains(currentAction)) {
- QEventLoop eventLoop;
- QAction *activeAction = currentAction;
-
- menu->setActiveAction(0);
- QTimer::singleShot(60, &eventLoop, SLOT(quit()));
- eventLoop.exec();
-
- // Select and wait 20 ms.
- menu->setActiveAction(activeAction);
- QTimer::singleShot(20, &eventLoop, SLOT(quit()));
- eventLoop.exec();
- }
-
- // Fade out.
- if (menu->style()->styleHint(QStyle::SH_Menu_FadeOutOnHide)) {
- // ### Qt 4.4:
- // Should be something like: q->transitionWindow(Qt::FadeOutTransition, MenuFadeTimeInSec);
- // Hopefully we'll integrate qt/research/windowtransitions into main before 4.4.
- // Talk to Richard, Trenton or Bjoern.
-#if defined(Q_WS_MAC)
- if (justRegister) {
- QMacWindowFader::currentFader()->setFadeDuration(MenuFadeTimeInSec);
- QMacWindowFader::currentFader()->registerWindowToFade(menu);
- } else {
- macWindowFade(qt_mac_window_for(menu), MenuFadeTimeInSec);
- }
-
-#endif // Q_WS_MAC
- }
- aboutToHide = false;
- menu->blockSignals(false);
-#endif // QT_NO_EFFECTS
- if (!justRegister)
- menu->hide();
-}
-
-void QMenuPrivate::popupAction(QAction *action, int delay, bool activateFirst)
-{
- Q_Q(QMenu);
- if (action && action->isEnabled()) {
- if (!delay)
- q->internalDelayedPopup();
- else if (!menuDelayTimer.isActive() && (!action->menu() || !action->menu()->isVisible()))
- menuDelayTimer.start(delay, q);
- if (activateFirst && action->menu())
- action->menu()->d_func()->setFirstActionActive();
- } else if (QMenu *menu = activeMenu) { //hide the current item
- activeMenu = 0;
- hideMenu(menu);
- }
-}
-
-void QMenuPrivate::setSyncAction()
-{
- Q_Q(QMenu);
- QAction *current = currentAction;
- if(current && (!current->isEnabled() || current->menu() || current->isSeparator()))
- current = 0;
- for(QWidget *caused = q; caused;) {
- if (QMenu *m = qobject_cast<QMenu*>(caused)) {
- caused = m->d_func()->causedPopup.widget;
- if (m->d_func()->eventLoop)
- m->d_func()->syncAction = current; // synchronous operation
- } else {
- break;
- }
- }
-}
-
-
-void QMenuPrivate::setFirstActionActive()
-{
- Q_Q(QMenu);
- updateActionRects();
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
- const QRect &rect = actionRects.at(i);
- if (rect.isNull())
- continue;
- if (scroll && scroll->scrollFlags & QMenuScroller::ScrollUp) {
- saccum -= rect.height();
- if (saccum > scroll->scrollOffset - scrollerHeight())
- continue;
- }
- QAction *act = actions.at(i);
- if (!act->isSeparator() &&
- (q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q)
- || act->isEnabled())) {
- setCurrentAction(act);
- break;
- }
- }
-}
-
-// popup == -1 means do not popup, 0 means immediately, others mean use a timer
-void QMenuPrivate::setCurrentAction(QAction *action, int popup, SelectionReason reason, bool activateFirst)
-{
- Q_Q(QMenu);
- tearoffHighlighted = 0;
- if (currentAction)
- q->update(actionRect(currentAction));
-
- sloppyAction = 0;
- if (!sloppyRegion.isEmpty())
- sloppyRegion = QRegion();
- QMenu *hideActiveMenu = activeMenu;
-#ifndef QT_NO_STATUSTIP
- QAction *previousAction = currentAction;
-#endif
-#ifdef QT3_SUPPORT
- emitHighlighted = action;
-#endif
-
- currentAction = action;
- if (action) {
- if (!action->isSeparator()) {
- activateAction(action, QAction::Hover);
- if (popup != -1) {
- hideActiveMenu = 0; //will be done "later"
- // if the menu is visible then activate the required action,
- // otherwise we just mark the action as currentAction
- // and activate it when the menu will be popuped.
- if (q->isVisible())
- popupAction(currentAction, popup, activateFirst);
- }
- q->update(actionRect(action));
-
- if (reason == SelectedFromKeyboard) {
- QWidget *widget = widgetItems.value(action);
- if (widget) {
- if (widget->focusPolicy() != Qt::NoFocus)
- widget->setFocus(Qt::TabFocusReason);
- } else {
- //when the action has no QWidget, the QMenu itself should
- // get the focus
- // Since the menu is a pop-up, it uses the popup reason.
- if (!q->hasFocus()) {
- q->setFocus(Qt::PopupFocusReason);
- }
- }
- }
- } else { //action is a separator
- if (popup != -1)
- hideActiveMenu = 0; //will be done "later"
- }
-#ifndef QT_NO_STATUSTIP
- } else if (previousAction) {
- previousAction->d_func()->showStatusText(topCausedWidget(), QString());
-#endif
- }
- if (hideActiveMenu) {
- activeMenu = 0;
-#ifndef QT_NO_EFFECTS
- // kill any running effect
- qFadeEffect(0);
- qScrollEffect(0);
-#endif
- hideMenu(hideActiveMenu);
- }
-}
-
-//return the top causedPopup.widget that is not a QMenu
-QWidget *QMenuPrivate::topCausedWidget() const
-{
- QWidget* top = causedPopup.widget;
- while (QMenu* m = qobject_cast<QMenu *>(top))
- top = m->d_func()->causedPopup.widget;
- return top;
-}
-
-QAction *QMenuPrivate::actionAt(QPoint p) const
-{
- if (!q_func()->rect().contains(p)) //sanity check
- return 0;
-
- for(int i = 0; i < actionRects.count(); i++) {
- if (actionRects.at(i).contains(p))
- return actions.at(i);
- }
- return 0;
-}
-
-void QMenuPrivate::setOverrideMenuAction(QAction *a)
-{
- Q_Q(QMenu);
- QObject::disconnect(menuAction, SIGNAL(destroyed()), q, SLOT(_q_overrideMenuActionDestroyed()));
- if (a) {
- menuAction = a;
- QObject::connect(a, SIGNAL(destroyed()), q, SLOT(_q_overrideMenuActionDestroyed()));
- } else { //we revert back to the default action created by the QMenu itself
- menuAction = defaultMenuAction;
- }
-}
-
-void QMenuPrivate::_q_overrideMenuActionDestroyed()
-{
- menuAction=defaultMenuAction;
-}
-
-
-void QMenuPrivate::updateLayoutDirection()
-{
- Q_Q(QMenu);
- //we need to mimic the cause of the popup's layout direction
- //to allow setting it on a mainwindow for example
- //we call setLayoutDirection_helper to not overwrite a user-defined value
- if (!q->testAttribute(Qt::WA_SetLayoutDirection)) {
- if (QWidget *w = causedPopup.widget)
- setLayoutDirection_helper(w->layoutDirection());
- else if (QWidget *w = q->parentWidget())
- setLayoutDirection_helper(w->layoutDirection());
- else
- setLayoutDirection_helper(QApplication::layoutDirection());
- }
-}
-
-
-/*!
- Returns the action associated with this menu.
-*/
-QAction *QMenu::menuAction() const
-{
- return d_func()->menuAction;
-}
-
-/*!
- \property QMenu::title
- \brief The title of the menu
-
- This is equivalent to the QAction::text property of the menuAction().
-
- By default, this property contains an empty string.
-*/
-QString QMenu::title() const
-{
- return d_func()->menuAction->text();
-}
-
-void QMenu::setTitle(const QString &text)
-{
- d_func()->menuAction->setText(text);
-}
-
-/*!
- \property QMenu::icon
-
- \brief The icon of the menu
-
- This is equivalent to the QAction::icon property of the menuAction().
-
- By default, if no icon is explicitly set, this property contains a null icon.
-*/
-QIcon QMenu::icon() const
-{
- return d_func()->menuAction->icon();
-}
-
-void QMenu::setIcon(const QIcon &icon)
-{
- d_func()->menuAction->setIcon(icon);
-}
-
-
-//actually performs the scrolling
-void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation location, bool active)
-{
- Q_Q(QMenu);
- if (!scroll || !scroll->scrollFlags)
- return;
- updateActionRects();
- int newOffset = 0;
- const int topScroll = (scroll->scrollFlags & QMenuScroller::ScrollUp) ? scrollerHeight() : 0;
- const int botScroll = (scroll->scrollFlags & QMenuScroller::ScrollDown) ? scrollerHeight() : 0;
- const int vmargin = q->style()->pixelMetric(QStyle::PM_MenuVMargin, 0, q);
- const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, q);
-
- if (location == QMenuScroller::ScrollTop) {
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
- if (actions.at(i) == action) {
- newOffset = topScroll - saccum;
- break;
- }
- saccum += actionRects.at(i).height();
- }
- } else {
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
- saccum += actionRects.at(i).height();
- if (actions.at(i) == action) {
- if (location == QMenuScroller::ScrollCenter)
- newOffset = ((q->height() / 2) - botScroll) - (saccum - topScroll);
- else
- newOffset = (q->height() - botScroll) - saccum;
- break;
- }
- }
- if(newOffset)
- newOffset -= fw * 2;
- }
-
- //figure out which scroll flags
- uint newScrollFlags = QMenuScroller::ScrollNone;
- if (newOffset < 0) //easy and cheap one
- newScrollFlags |= QMenuScroller::ScrollUp;
- int saccum = newOffset;
- for(int i = 0; i < actionRects.count(); i++) {
- saccum += actionRects.at(i).height();
- if (saccum > q->height()) {
- newScrollFlags |= QMenuScroller::ScrollDown;
- break;
- }
- }
-
- if (!(newScrollFlags & QMenuScroller::ScrollDown) && (scroll->scrollFlags & QMenuScroller::ScrollDown)) {
- newOffset = q->height() - (saccum - newOffset) - fw*2 - vmargin; //last item at bottom
- }
-
- if (!(newScrollFlags & QMenuScroller::ScrollUp) && (scroll->scrollFlags & QMenuScroller::ScrollUp)) {
- newOffset = 0; //first item at top
- }
-
- if (newScrollFlags & QMenuScroller::ScrollUp)
- newOffset -= vmargin;
-
- QRect screen = popupGeometry(q);
- const int desktopFrame = q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q);
- if (q->height() < screen.height()-(desktopFrame*2)-1) {
- QRect geom = q->geometry();
- if (newOffset > scroll->scrollOffset && (scroll->scrollFlags & newScrollFlags & QMenuScroller::ScrollUp)) { //scroll up
- const int newHeight = geom.height()-(newOffset-scroll->scrollOffset);
- if(newHeight > geom.height())
- geom.setHeight(newHeight);
- } else if(scroll->scrollFlags & newScrollFlags & QMenuScroller::ScrollDown) {
- int newTop = geom.top() + (newOffset-scroll->scrollOffset);
- if (newTop < desktopFrame+screen.top())
- newTop = desktopFrame+screen.top();
- if (newTop < geom.top()) {
- geom.setTop(newTop);
- newOffset = 0;
- newScrollFlags &= ~QMenuScroller::ScrollUp;
- }
- }
- if (geom.bottom() > screen.bottom() - desktopFrame)
- geom.setBottom(screen.bottom() - desktopFrame);
- if (geom.top() < desktopFrame+screen.top())
- geom.setTop(desktopFrame+screen.top());
- if (geom != q->geometry()) {
-#if 0
- if (newScrollFlags & QMenuScroller::ScrollDown &&
- q->geometry().top() - geom.top() >= -newOffset)
- newScrollFlags &= ~QMenuScroller::ScrollDown;
-#endif
- q->setGeometry(geom);
- }
- }
-
- //actually update flags
- const int delta = qMin(0, newOffset) - scroll->scrollOffset; //make sure the new offset is always negative
- if (!itemsDirty && delta) {
- //we've scrolled so we need to update the action rects
- for (int i = 0; i < actionRects.count(); ++i) {
- QRect &current = actionRects[i];
- current.moveTop(current.top() + delta);
-
- //we need to update the widgets geometry
- if (QWidget *w = widgetItems.value(actions.at(i)))
- w->setGeometry(current);
- }
- }
- scroll->scrollOffset += delta;
- scroll->scrollFlags = newScrollFlags;
- if (active)
- setCurrentAction(action);
-
- q->update(); //issue an update so we see all the new state..
-}
-
-void QMenuPrivate::scrollMenu(QMenuScroller::ScrollLocation location, bool active)
-{
- Q_Q(QMenu);
- updateActionRects();
- if(location == QMenuScroller::ScrollBottom) {
- for(int i = actions.size()-1; i >= 0; --i) {
- QAction *act = actions.at(i);
- if (actionRects.at(i).isNull())
- continue;
- if (!act->isSeparator() &&
- (q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q)
- || act->isEnabled())) {
- if(scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)
- scrollMenu(act, QMenuPrivate::QMenuScroller::ScrollBottom, active);
- else if(active)
- setCurrentAction(act, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard);
- break;
- }
- }
- } else if(location == QMenuScroller::ScrollTop) {
- for(int i = 0; i < actions.size(); ++i) {
- QAction *act = actions.at(i);
- if (actionRects.at(i).isNull())
- continue;
- if (!act->isSeparator() &&
- (q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q)
- || act->isEnabled())) {
- if(scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
- scrollMenu(act, QMenuPrivate::QMenuScroller::ScrollTop, active);
- else if(active)
- setCurrentAction(act, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard);
- break;
- }
- }
- }
-}
-
-//only directional
-void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool page, bool active)
-{
- Q_Q(QMenu);
- if (!scroll || !(scroll->scrollFlags & direction)) //not really possible...
- return;
- updateActionRects();
- const int topScroll = (scroll->scrollFlags & QMenuScroller::ScrollUp) ? scrollerHeight() : 0;
- const int botScroll = (scroll->scrollFlags & QMenuScroller::ScrollDown) ? scrollerHeight() : 0;
- const int vmargin = q->style()->pixelMetric(QStyle::PM_MenuVMargin, 0, q);
- const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, q);
- const int offset = topScroll ? topScroll-vmargin : 0;
- if (direction == QMenuScroller::ScrollUp) {
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
- saccum -= actionRects.at(i).height();
- if (saccum <= scroll->scrollOffset-offset) {
- scrollMenu(actions.at(i), page ? QMenuScroller::ScrollBottom : QMenuScroller::ScrollTop, active);
- break;
- }
- }
- } else if (direction == QMenuScroller::ScrollDown) {
- bool scrolled = false;
- for(int i = 0, saccum = 0; i < actions.count(); i++) {
- const int iHeight = actionRects.at(i).height();
- saccum -= iHeight;
- if (saccum <= scroll->scrollOffset-offset) {
- const int scrollerArea = q->height() - botScroll - fw*2;
- int visible = (scroll->scrollOffset-offset) - saccum;
- for(i++ ; i < actions.count(); i++) {
- visible += actionRects.at(i).height();
- if (visible > scrollerArea - topScroll) {
- scrolled = true;
- scrollMenu(actions.at(i), page ? QMenuScroller::ScrollTop : QMenuScroller::ScrollBottom, active);
- break;
- }
- }
- break;
- }
- }
- if(!scrolled) {
- scroll->scrollFlags &= ~QMenuScroller::ScrollDown;
- q->update();
- }
- }
-}
-
-/* This is poor-mans eventfilters. This avoids the use of
- eventFilter (which can be nasty for users of QMenuBar's). */
-bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
-{
- Q_Q(QMenu);
- QPoint pos = q->mapFromGlobal(e->globalPos());
- if (scroll && !activeMenu) { //let the scroller "steal" the event
- bool isScroll = false;
- if (pos.x() >= 0 && pos.x() < q->width()) {
- for(int dir = QMenuScroller::ScrollUp; dir <= QMenuScroller::ScrollDown; dir = dir << 1) {
- if (scroll->scrollFlags & dir) {
- if (dir == QMenuScroller::ScrollUp)
- isScroll = (pos.y() <= scrollerHeight());
- else if (dir == QMenuScroller::ScrollDown)
- isScroll = (pos.y() >= q->height() - scrollerHeight());
- if (isScroll) {
- scroll->scrollDirection = dir;
- break;
- }
- }
- }
- }
- if (isScroll) {
- scroll->scrollTimer.start(50, q);
- return true;
- } else {
- scroll->scrollTimer.stop();
- }
- }
-
- if (tearoff) { //let the tear off thingie "steal" the event..
- QRect tearRect(0, 0, q->width(), q->style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, q));
- if (scroll && scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
- tearRect.translate(0, scrollerHeight());
- q->update(tearRect);
- if (tearRect.contains(pos) && hasMouseMoved(e->globalPos())) {
- setCurrentAction(0);
- tearoffHighlighted = 1;
- if (e->type() == QEvent::MouseButtonRelease) {
- if (!tornPopup)
- tornPopup = new QTornOffMenu(q);
- tornPopup->setGeometry(q->geometry());
- tornPopup->show();
- hideUpToMenuBar();
- }
- return true;
- }
- tearoffHighlighted = 0;
- }
-
- if (q->frameGeometry().contains(e->globalPos())) //otherwise if the event is in our rect we want it..
- return false;
-
- for(QWidget *caused = causedPopup.widget; caused;) {
- bool passOnEvent = false;
- QWidget *next_widget = 0;
- QPoint cpos = caused->mapFromGlobal(e->globalPos());
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(caused)) {
- passOnEvent = mb->rect().contains(cpos);
- } else
-#endif
- if (QMenu *m = qobject_cast<QMenu*>(caused)) {
- passOnEvent = m->rect().contains(cpos);
- next_widget = m->d_func()->causedPopup.widget;
- }
- if (passOnEvent) {
- if(e->type() != QEvent::MouseButtonRelease || mouseDown == caused) {
- QMouseEvent new_e(e->type(), cpos, e->button(), e->buttons(), e->modifiers());
- QApplication::sendEvent(caused, &new_e);
- return true;
- }
- }
- if (!next_widget)
- break;
- caused = next_widget;
- }
- return false;
-}
-
-void QMenuPrivate::activateCausedStack(const QList<QPointer<QWidget> > &causedStack, QAction *action, QAction::ActionEvent action_e, bool self)
-{
- QBoolBlocker guard(activationRecursionGuard);
-#ifdef QT3_SUPPORT
- const int actionId = q_func()->findIdForAction(action);
-#endif
- if(self)
- action->activate(action_e);
-
- for(int i = 0; i < causedStack.size(); ++i) {
- QPointer<QWidget> widget = causedStack.at(i);
- if (!widget)
- continue;
- //fire
- if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
- widget = qmenu->d_func()->causedPopup.widget;
- if (action_e == QAction::Trigger) {
- emit qmenu->triggered(action);
- } else if (action_e == QAction::Hover) {
- emit qmenu->hovered(action);
-#ifdef QT3_SUPPORT
- if (emitHighlighted) {
- emit qmenu->highlighted(actionId);
- emitHighlighted = false;
- }
-#endif
- }
-#ifndef QT_NO_MENUBAR
- } else if (QMenuBar *qmenubar = qobject_cast<QMenuBar*>(widget)) {
- if (action_e == QAction::Trigger) {
- emit qmenubar->triggered(action);
-#ifdef QT3_SUPPORT
- emit qmenubar->activated(actionId);
-#endif
- } else if (action_e == QAction::Hover) {
- emit qmenubar->hovered(action);
-#ifdef QT3_SUPPORT
- if (emitHighlighted) {
- emit qmenubar->highlighted(actionId);
- emitHighlighted = false;
- }
-#endif
- }
- break; //nothing more..
-#endif
- }
- }
-}
-
-void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e, bool self)
-{
- Q_Q(QMenu);
-#ifndef QT_NO_WHATSTHIS
- bool inWhatsThisMode = QWhatsThis::inWhatsThisMode();
-#endif
- if (!action || !q->isEnabled()
- || (action_e == QAction::Trigger
-#ifndef QT_NO_WHATSTHIS
- && !inWhatsThisMode
-#endif
- && (action->isSeparator() ||!action->isEnabled())))
- return;
-
- /* I have to save the caused stack here because it will be undone after popup execution (ie in the hide).
- Then I iterate over the list to actually send the events. --Sam
- */
- const QList<QPointer<QWidget> > causedStack = calcCausedStack();
- if (action_e == QAction::Trigger) {
-#ifndef QT_NO_WHATSTHIS
- if (!inWhatsThisMode)
- actionAboutToTrigger = action;
-#endif
-
- if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
- hideUpToMenuBar();
- } else {
- for(QWidget *widget = QApplication::activePopupWidget(); widget; ) {
- if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
- if(qmenu == q)
- hideUpToMenuBar();
- widget = qmenu->d_func()->causedPopup.widget;
- } else {
- break;
- }
- }
- }
-
-#ifndef QT_NO_WHATSTHIS
- if (inWhatsThisMode) {
- QString s = action->whatsThis();
- if (s.isEmpty())
- s = whatsThis;
- QWhatsThis::showText(q->mapToGlobal(actionRect(action).center()), s, q);
- return;
- }
-#endif
- }
-
-
- activateCausedStack(causedStack, action, action_e, self);
-
-
- if (action_e == QAction::Hover) {
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- int actionIndex = indexOf(action) + 1;
- QAccessible::updateAccessibility(q, actionIndex, QAccessible::Focus);
- QAccessible::updateAccessibility(q, actionIndex, QAccessible::Selection);
- }
-#endif
- action->showStatusText(topCausedWidget());
- } else {
- actionAboutToTrigger = 0;
- }
-}
-
-void QMenuPrivate::_q_actionTriggered()
-{
- Q_Q(QMenu);
- if (QAction *action = qobject_cast<QAction *>(q->sender())) {
- QWeakPointer<QAction> actionGuard = action;
-#ifdef QT3_SUPPORT
- //we store it here because the action might be deleted/changed by connected slots
- const int id = q->findIdForAction(action);
-#endif
- emit q->triggered(action);
-#ifdef QT3_SUPPORT
- emit q->activated(id);
-#endif
-
- if (!activationRecursionGuard && actionGuard) {
- //in case the action has not been activated by the mouse
- //we check the parent hierarchy
- QList< QPointer<QWidget> > list;
- for(QWidget *widget = q->parentWidget(); widget; ) {
- if (qobject_cast<QMenu*>(widget)
-#ifndef QT_NO_MENUBAR
- || qobject_cast<QMenuBar*>(widget)
-#endif
- ) {
- list.append(widget);
- widget = widget->parentWidget();
- } else {
- break;
- }
- }
- activateCausedStack(list, action, QAction::Trigger, false);
- }
- }
-}
-
-void QMenuPrivate::_q_actionHovered()
-{
- Q_Q(QMenu);
- if (QAction * action = qobject_cast<QAction *>(q->sender())) {
-#ifdef QT3_SUPPORT
- //we store it here because the action might be deleted/changed by connected slots
- const int id = q->findIdForAction(action);
-#endif
- emit q->hovered(action);
-#ifdef QT3_SUPPORT
- if (emitHighlighted) {
- emit q->highlighted(id);
- emitHighlighted = false;
- }
-#endif
- }
-}
-
-bool QMenuPrivate::hasMouseMoved(const QPoint &globalPos)
-{
- //determines if the mouse has moved (ie its initial position has
- //changed by more than QApplication::startDragDistance()
- //or if there were at least 6 mouse motions)
- return motions > 6 ||
- QApplication::startDragDistance() < (mousePopupPos - globalPos).manhattanLength();
-}
-
-
-/*!
- Initialize \a option with the values from this menu and information from \a action. This method
- is useful for subclasses when they need a QStyleOptionMenuItem, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom() QMenuBar::initStyleOption()
-*/
-void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const
-{
- if (!option || !action)
- return;
-
- Q_D(const QMenu);
- option->initFrom(this);
- option->palette = palette();
- option->state = QStyle::State_None;
-
- if (window()->isActiveWindow())
- option->state |= QStyle::State_Active;
- if (isEnabled() && action->isEnabled()
- && (!action->menu() || action->menu()->isEnabled()))
- option->state |= QStyle::State_Enabled;
- else
- option->palette.setCurrentColorGroup(QPalette::Disabled);
-
- option->font = action->font().resolve(font());
- option->fontMetrics = QFontMetrics(option->font);
-
- if (d->currentAction && d->currentAction == action && !d->currentAction->isSeparator()) {
- option->state |= QStyle::State_Selected
- | (d->mouseDown ? QStyle::State_Sunken : QStyle::State_None);
- }
-
- option->menuHasCheckableItems = d->hasCheckableItems;
- if (!action->isCheckable()) {
- option->checkType = QStyleOptionMenuItem::NotCheckable;
- } else {
- option->checkType = (action->actionGroup() && action->actionGroup()->isExclusive())
- ? QStyleOptionMenuItem::Exclusive : QStyleOptionMenuItem::NonExclusive;
- option->checked = action->isChecked();
- }
- if (action->menu())
- option->menuItemType = QStyleOptionMenuItem::SubMenu;
- else if (action->isSeparator())
- option->menuItemType = QStyleOptionMenuItem::Separator;
- else if (d->defaultAction == action)
- option->menuItemType = QStyleOptionMenuItem::DefaultItem;
- else
- option->menuItemType = QStyleOptionMenuItem::Normal;
- if (action->isIconVisibleInMenu())
- option->icon = action->icon();
- QString textAndAccel = action->text();
-#ifndef QT_NO_SHORTCUT
- if (textAndAccel.indexOf(QLatin1Char('\t')) == -1) {
- QKeySequence seq = action->shortcut();
- if (!seq.isEmpty())
- textAndAccel += QLatin1Char('\t') + QString(seq);
- }
-#endif
- option->text = textAndAccel;
- option->tabWidth = d->tabWidth;
- option->maxIconWidth = d->maxIconWidth;
- option->menuRect = rect();
-}
-
-/*!
- \class QMenu
- \brief The QMenu class provides a menu widget for use in menu
- bars, context menus, and other popup menus.
-
- \ingroup mainwindow-classes
- \ingroup basicwidgets
-
-
- A menu widget is a selection menu. It can be either a pull-down
- menu in a menu bar or a standalone context menu. Pull-down menus
- are shown by the menu bar when the user clicks on the respective
- item or presses the specified shortcut key. Use
- QMenuBar::addMenu() to insert a menu into a menu bar. Context
- menus are usually invoked by some special keyboard key or by
- right-clicking. They can be executed either asynchronously with
- popup() or synchronously with exec(). Menus can also be invoked in
- response to button presses; these are just like context menus
- except for how they are invoked.
-
- \table 100%
- \row
- \o \inlineimage plastique-menu.png
- \o \inlineimage windowsxp-menu.png
- \o \inlineimage macintosh-menu.png
- \endtable
- \caption Fig. A menu shown in \l{Plastique Style Widget Gallery}{Plastique widget style},
- \l{Windows XP Style Widget Gallery}{Windows XP widget style},
- and \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
-
- \section1 Actions
-
- A menu consists of a list of action items. Actions are added with
- the addAction(), addActions() and insertAction() functions. An action
- is represented vertically and rendered by QStyle. In addition, actions
- can have a text label, an optional icon drawn on the very left side,
- and shortcut key sequence such as "Ctrl+X".
-
- The existing actions held by a menu can be found with actions().
-
- There are four kinds of action items: separators, actions that
- show a submenu, widgets, and actions that perform an action.
- Separators are inserted with addSeparator(), submenus with addMenu(),
- and all other items are considered action items.
-
- When inserting action items you usually specify a receiver and a
- slot. The receiver will be notifed whenever the item is
- \l{QAction::triggered()}{triggered()}. In addition, QMenu provides
- two signals, activated() and highlighted(), which signal the
- QAction that was triggered from the menu.
-
- You clear a menu with clear() and remove individual action items
- with removeAction().
-
- A QMenu can also provide a tear-off menu. A tear-off menu is a
- top-level window that contains a copy of the menu. This makes it
- possible for the user to "tear off" frequently used menus and
- position them in a convenient place on the screen. If you want
- this functionality for a particular menu, insert a tear-off handle
- with setTearOffEnabled(). When using tear-off menus, bear in mind
- that the concept isn't typically used on Microsoft Windows so
- some users may not be familiar with it. Consider using a QToolBar
- instead.
-
- Widgets can be inserted into menus with the QWidgetAction class.
- Instances of this class are used to hold widgets, and are inserted
- into menus with the addAction() overload that takes a QAction.
-
- Conversely, actions can be added to widgets with the addAction(),
- addActions() and insertAction() functions.
-
- \warning To make QMenu visible on the screen, exec() or popup() should be
- used instead of show().
-
- \section1 QMenu on Qt for Windows CE
-
- If a menu is integrated into the native menubar on Windows Mobile we
- do not support the signals: aboutToHide (), aboutToShow () and hovered ().
- It is not possible to display an icon in a native menu on Windows Mobile.
-
- \section1 QMenu on Mac OS X with Qt build against Cocoa
-
- QMenu can be inserted only once in a menu/menubar. Subsequent insertions will
- have no effect or will result in a disabled menu item.
-
- See the \l{mainwindows/menus}{Menus} example for an example of how
- to use QMenuBar and QMenu in your application.
-
- \bold{Important inherited functions:} addAction(), removeAction(), clear(),
- addSeparator(), and addMenu().
-
- \sa QMenuBar, {fowler}{GUI Design Handbook: Menu, Drop-Down and Pop-Up},
- {Application Example}, {Menus Example}, {Recent Files Example}
-*/
-
-
-/*!
- Constructs a menu with parent \a parent.
-
- Although a popup menu is always a top-level widget, if a parent is
- passed the popup menu will be deleted when that parent is
- destroyed (as with any other QObject).
-*/
-QMenu::QMenu(QWidget *parent)
- : QWidget(*new QMenuPrivate, parent, Qt::Popup)
-{
- Q_D(QMenu);
- d->init();
-}
-
-/*!
- Constructs a menu with a \a title and a \a parent.
-
- Although a popup menu is always a top-level widget, if a parent is
- passed the popup menu will be deleted when that parent is
- destroyed (as with any other QObject).
-
- \sa title
-*/
-QMenu::QMenu(const QString &title, QWidget *parent)
- : QWidget(*new QMenuPrivate, parent, Qt::Popup)
-{
- Q_D(QMenu);
- d->init();
- d->menuAction->setText(title);
-}
-
-/*! \internal
- */
-QMenu::QMenu(QMenuPrivate &dd, QWidget *parent)
- : QWidget(dd, parent, Qt::Popup)
-{
- Q_D(QMenu);
- d->init();
-}
-
-/*!
- Destroys the menu.
-*/
-QMenu::~QMenu()
-{
- Q_D(QMenu);
- if (!d->widgetItems.isEmpty()) { // avoid detach on shared null hash
- QHash<QAction *, QWidget *>::iterator it = d->widgetItems.begin();
- for (; it != d->widgetItems.end(); ++it) {
- if (QWidget *widget = it.value()) {
- QWidgetAction *action = static_cast<QWidgetAction *>(it.key());
- action->releaseWidget(widget);
- *it = 0;
- }
- }
- }
-
- if (d->eventLoop)
- d->eventLoop->exit();
- hideTearOffMenu();
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with \a text.
- The function adds the newly created action to the menu's
- list of actions, and returns it.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addAction(const QString &text)
-{
- QAction *ret = new QAction(text, this);
- addAction(ret);
- return ret;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with an \a icon
- and some \a text. The function adds the newly created action to
- the menu's list of actions, and returns it.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addAction(const QIcon &icon, const QString &text)
-{
- QAction *ret = new QAction(icon, text, this);
- addAction(ret);
- return ret;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with the text \a
- text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a receiver's \a member slot. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut)
-{
- QAction *action = new QAction(text, this);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut);
-#else
- action->setShortcut(shortcut);
-#endif
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with an \a icon and
- some \a text and an optional shortcut \a shortcut. The action's
- \l{QAction::triggered()}{triggered()} signal is connected to the
- \a member slot of the \a receiver object. The function adds the
- newly created action to the menu's list of actions, and returns it.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver,
- const char* member, const QKeySequence &shortcut)
-{
- QAction *action = new QAction(icon, text, this);
-#ifdef QT_NO_SHORTCUT
- Q_UNUSED(shortcut);
-#else
- action->setShortcut(shortcut);
-#endif
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
-}
-
-/*!
- This convenience function adds \a menu as a submenu to this menu.
- It returns \a menu's menuAction(). This menu does not take
- ownership of \a menu.
-
- \sa QWidget::addAction() QMenu::menuAction()
-*/
-QAction *QMenu::addMenu(QMenu *menu)
-{
- QAction *action = menu->menuAction();
- addAction(action);
- return action;
-}
-
-/*!
- Appends a new QMenu with \a title to the menu. The menu
- takes ownership of the menu. Returns the new menu.
-
- \sa QWidget::addAction() QMenu::menuAction()
-*/
-QMenu *QMenu::addMenu(const QString &title)
-{
- QMenu *menu = new QMenu(title, this);
- addAction(menu->menuAction());
- return menu;
-}
-
-/*!
- Appends a new QMenu with \a icon and \a title to the menu. The menu
- takes ownership of the menu. Returns the new menu.
-
- \sa QWidget::addAction() QMenu::menuAction()
-*/
-QMenu *QMenu::addMenu(const QIcon &icon, const QString &title)
-{
- QMenu *menu = new QMenu(title, this);
- menu->setIcon(icon);
- addAction(menu->menuAction());
- return menu;
-}
-
-/*!
- This convenience function creates a new separator action, i.e. an
- action with QAction::isSeparator() returning true, and adds the new
- action to this menu's list of actions. It returns the newly
- created action.
-
- \sa QWidget::addAction()
-*/
-QAction *QMenu::addSeparator()
-{
- QAction *action = new QAction(this);
- action->setSeparator(true);
- addAction(action);
- return action;
-}
-
-/*!
- This convenience function inserts \a menu before action \a before
- and returns the menus menuAction().
-
- \sa QWidget::insertAction(), addMenu()
-*/
-QAction *QMenu::insertMenu(QAction *before, QMenu *menu)
-{
- QAction *action = menu->menuAction();
- insertAction(before, action);
- return action;
-}
-
-/*!
- This convenience function creates a new separator action, i.e. an
- action with QAction::isSeparator() returning true. The function inserts
- the newly created action into this menu's list of actions before
- action \a before and returns it.
-
- \sa QWidget::insertAction(), addSeparator()
-*/
-QAction *QMenu::insertSeparator(QAction *before)
-{
- QAction *action = new QAction(this);
- action->setSeparator(true);
- insertAction(before, action);
- return action;
-}
-
-/*!
- This sets the default action to \a act. The default action may have
- a visual cue, depending on the current QStyle. A default action
- usually indicates what will happen by default when a drop occurs.
-
- \sa defaultAction()
-*/
-void QMenu::setDefaultAction(QAction *act)
-{
- d_func()->defaultAction = act;
-}
-
-/*!
- Returns the current default action.
-
- \sa setDefaultAction()
-*/
-QAction *QMenu::defaultAction() const
-{
- return d_func()->defaultAction;
-}
-
-/*!
- \property QMenu::tearOffEnabled
- \brief whether the menu supports being torn off
-
- When true, the menu contains a special tear-off item (often shown as a dashed
- line at the top of the menu) that creates a copy of the menu when it is
- triggered.
-
- This "torn-off" copy lives in a separate window. It contains the same menu
- items as the original menu, with the exception of the tear-off handle.
-
- By default, this property is false.
-*/
-void QMenu::setTearOffEnabled(bool b)
-{
- Q_D(QMenu);
- if (d->tearoff == b)
- return;
- if (!b)
- hideTearOffMenu();
- d->tearoff = b;
-
- d->itemsDirty = true;
- if (isVisible())
- resize(sizeHint());
-}
-
-bool QMenu::isTearOffEnabled() const
-{
- return d_func()->tearoff;
-}
-
-/*!
- When a menu is torn off a second menu is shown to display the menu
- contents in a new window. When the menu is in this mode and the menu
- is visible returns true; otherwise false.
-
- \sa hideTearOffMenu() isTearOffEnabled()
-*/
-bool QMenu::isTearOffMenuVisible() const
-{
- if (d_func()->tornPopup)
- return d_func()->tornPopup->isVisible();
- return false;
-}
-
-/*!
- This function will forcibly hide the torn off menu making it
- disappear from the users desktop.
-
- \sa isTearOffMenuVisible() isTearOffEnabled()
-*/
-void QMenu::hideTearOffMenu()
-{
- if (QWidget *w = d_func()->tornPopup)
- w->close();
-}
-
-
-/*!
- Sets the currently highlighted action to \a act.
-*/
-void QMenu::setActiveAction(QAction *act)
-{
- Q_D(QMenu);
- d->setCurrentAction(act, 0);
- if (d->scroll)
- d->scrollMenu(act, QMenuPrivate::QMenuScroller::ScrollCenter);
-}
-
-
-/*!
- Returns the currently highlighted action, or 0 if no
- action is currently highlighted.
-*/
-QAction *QMenu::activeAction() const
-{
- return d_func()->currentAction;
-}
-
-/*!
- \since 4.2
-
- Returns true if there are no visible actions inserted into the menu, false
- otherwise.
-
- \sa QWidget::actions()
-*/
-
-bool QMenu::isEmpty() const
-{
- bool ret = true;
- for(int i = 0; ret && i < actions().count(); ++i) {
- const QAction *action = actions().at(i);
- if (!action->isSeparator() && action->isVisible()) {
- ret = false;
- }
- }
- return ret;
-}
-
-/*!
- Removes all the menu's actions. Actions owned by the menu and not
- shown in any other widget are deleted.
-
- \sa removeAction()
-*/
-void QMenu::clear()
-{
- QList<QAction*> acts = actions();
-
- for(int i = 0; i < acts.size(); i++) {
-#ifdef QT_SOFTKEYS_ENABLED
- Q_D(QMenu);
- // Lets not touch to our internal softkey actions
- if(acts[i] == d->selectAction || acts[i] == d->cancelAction)
- continue;
-#endif
- removeAction(acts[i]);
- if (acts[i]->parent() == this && acts[i]->d_func()->widgets.isEmpty())
- delete acts[i];
- }
-}
-
-/*!
- If a menu does not fit on the screen it lays itself out so that it
- does fit. It is style dependent what layout means (for example, on
- Windows it will use multiple columns).
-
- This functions returns the number of columns necessary.
-*/
-int QMenu::columnCount() const
-{
- return d_func()->ncols;
-}
-
-/*!
- Returns the item at \a pt; returns 0 if there is no item there.
-*/
-QAction *QMenu::actionAt(const QPoint &pt) const
-{
- if (QAction *ret = d_func()->actionAt(pt))
- return ret;
- return 0;
-}
-
-/*!
- Returns the geometry of action \a act.
-*/
-QRect QMenu::actionGeometry(QAction *act) const
-{
- return d_func()->actionRect(act);
-}
-
-/*!
- \reimp
-*/
-QSize QMenu::sizeHint() const
-{
- Q_D(const QMenu);
- d->updateActionRects();
-
- QSize s;
- for (int i = 0; i < d->actionRects.count(); ++i) {
- const QRect &rect = d->actionRects.at(i);
- if (rect.isNull())
- continue;
- if (rect.bottom() >= s.height())
- s.setHeight(rect.y() + rect.height());
- if (rect.right() >= s.width())
- s.setWidth(rect.x() + rect.width());
- }
- // Note that the action rects calculated above already include
- // the top and left margins, so we only need to add margins for
- // the bottom and right.
- QStyleOption opt(0);
- opt.init(this);
- const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, &opt, this);
- s.rwidth() += style()->pixelMetric(QStyle::PM_MenuHMargin, &opt, this) + fw + d->rightmargin;
- s.rheight() += style()->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) + fw + d->bottommargin;
-
- return style()->sizeFromContents(QStyle::CT_Menu, &opt,
- s.expandedTo(QApplication::globalStrut()), this);
-}
-
-/*!
- Displays the menu so that the action \a atAction will be at the
- specified \e global position \a p. To translate a widget's local
- coordinates into global coordinates, use QWidget::mapToGlobal().
-
- When positioning a menu with exec() or popup(), bear in mind that
- you cannot rely on the menu's current size(). For performance
- reasons, the menu adapts its size only when necessary, so in many
- cases, the size before and after the show is different. Instead,
- use sizeHint() which calculates the proper size depending on the
- menu's current contents.
-
- \sa QWidget::mapToGlobal(), exec()
-*/
-void QMenu::popup(const QPoint &p, QAction *atAction)
-{
- Q_D(QMenu);
-#ifndef Q_OS_SYMBIAN
- if (d->scroll) { // reset scroll state from last popup
- d->scroll->scrollOffset = 0;
- d->scroll->scrollFlags = QMenuPrivate::QMenuScroller::ScrollNone;
- }
-#endif
- d->tearoffHighlighted = 0;
- d->motions = 0;
- d->doChildEffects = true;
- d->updateLayoutDirection();
-
-#ifndef QT_NO_MENUBAR
- // if this menu is part of a chain attached to a QMenuBar, set the
- // _NET_WM_WINDOW_TYPE_DROPDOWN_MENU X11 window type
- setAttribute(Qt::WA_X11NetWmWindowTypeDropDownMenu, qobject_cast<QMenuBar *>(d->topCausedWidget()) != 0);
-#endif
-
- ensurePolished(); // Get the right font
- emit aboutToShow();
- const bool actionListChanged = d->itemsDirty;
- d->updateActionRects();
- QPoint pos;
- QPushButton *causedButton = qobject_cast<QPushButton*>(d->causedPopup.widget);
- if (actionListChanged && causedButton)
- pos = QPushButtonPrivate::get(causedButton)->adjustedMenuPosition();
- else
- pos = p;
-
- QSize size = sizeHint();
- QRect screen;
-#ifndef QT_NO_GRAPHICSVIEW
- bool isEmbedded = !bypassGraphicsProxyWidget(this) && d->nearestGraphicsProxyWidget(this);
- if (isEmbedded)
- screen = d->popupGeometry(this);
- else
-#endif
- screen = d->popupGeometry(QApplication::desktop()->screenNumber(p));
-
- const int desktopFrame = style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, this);
- bool adjustToDesktop = !window()->testAttribute(Qt::WA_DontShowOnScreen);
-#ifdef QT_KEYPAD_NAVIGATION
- if (!atAction && QApplication::keypadNavigationEnabled()) {
- // Try to have one item activated
- if (d->defaultAction && d->defaultAction->isEnabled()) {
- atAction = d->defaultAction;
- // TODO: This works for first level menus, not yet sub menus
- } else {
- foreach (QAction *action, d->actions)
- if (action->isEnabled()) {
- atAction = action;
- break;
- }
- }
- d->currentAction = atAction;
- }
-#endif
- if (d->ncols > 1) {
- pos.setY(screen.top() + desktopFrame);
- } else if (atAction) {
- for (int i = 0, above_height = 0; i < d->actions.count(); i++) {
- QAction *action = d->actions.at(i);
- if (action == atAction) {
- int newY = pos.y() - above_height;
- if (d->scroll && newY < desktopFrame) {
- d->scroll->scrollFlags = d->scroll->scrollFlags
- | QMenuPrivate::QMenuScroller::ScrollUp;
- d->scroll->scrollOffset = newY;
- newY = desktopFrame;
- }
- pos.setY(newY);
-
- if (d->scroll && d->scroll->scrollFlags != QMenuPrivate::QMenuScroller::ScrollNone
- && !style()->styleHint(QStyle::SH_Menu_FillScreenWithScroll, 0, this)) {
- int below_height = above_height + d->scroll->scrollOffset;
- for (int i2 = i; i2 < d->actionRects.count(); i2++)
- below_height += d->actionRects.at(i2).height();
- size.setHeight(below_height);
- }
- break;
- } else {
- above_height += d->actionRects.at(i).height();
- }
- }
- }
-
- QPoint mouse = QCursor::pos();
- d->mousePopupPos = mouse;
- const bool snapToMouse = (QRect(p.x() - 3, p.y() - 3, 6, 6).contains(mouse));
-
- if (adjustToDesktop) {
- // handle popup falling "off screen"
- if (isRightToLeft()) {
- if (snapToMouse) // position flowing left from the mouse
- pos.setX(mouse.x() - size.width());
-
-#ifndef QT_NO_MENUBAR
- // if in a menubar, it should be right-aligned
- if (qobject_cast<QMenuBar*>(d->causedPopup.widget))
- pos.rx() -= size.width();
-#endif //QT_NO_MENUBAR
-
- if (pos.x() < screen.left() + desktopFrame)
- pos.setX(qMax(p.x(), screen.left() + desktopFrame));
- if (pos.x() + size.width() - 1 > screen.right() - desktopFrame)
- pos.setX(qMax(p.x() - size.width(), screen.right() - desktopFrame - size.width() + 1));
- } else {
- if (pos.x() + size.width() - 1 > screen.right() - desktopFrame)
- pos.setX(screen.right() - desktopFrame - size.width() + 1);
- if (pos.x() < screen.left() + desktopFrame)
- pos.setX(screen.left() + desktopFrame);
- }
- if (pos.y() + size.height() - 1 > screen.bottom() - desktopFrame) {
- if(snapToMouse)
- pos.setY(qMin(mouse.y() - (size.height() + desktopFrame), screen.bottom()-desktopFrame-size.height()+1));
- else
- pos.setY(qMax(p.y() - (size.height() + desktopFrame), screen.bottom()-desktopFrame-size.height()+1));
- } else if (pos.y() < screen.top() + desktopFrame) {
- pos.setY(screen.top() + desktopFrame);
- }
-
- if (pos.y() < screen.top() + desktopFrame)
- pos.setY(screen.top() + desktopFrame);
- if (pos.y() + size.height() - 1 > screen.bottom() - desktopFrame) {
- if (d->scroll) {
- d->scroll->scrollFlags |= uint(QMenuPrivate::QMenuScroller::ScrollDown);
- int y = qMax(screen.y(),pos.y());
- size.setHeight(screen.bottom() - (desktopFrame * 2) - y);
- } else {
- // Too big for screen, bias to see bottom of menu (for some reason)
- pos.setY(screen.bottom() - size.height() + 1);
- }
- }
- }
- setGeometry(QRect(pos, size));
-#ifndef QT_NO_EFFECTS
- int hGuess = isRightToLeft() ? QEffects::LeftScroll : QEffects::RightScroll;
- int vGuess = QEffects::DownScroll;
- if (isRightToLeft()) {
- if ((snapToMouse && (pos.x() + size.width() / 2 > mouse.x())) ||
- (qobject_cast<QMenu*>(d->causedPopup.widget) && pos.x() + size.width() / 2 > d->causedPopup.widget->x()))
- hGuess = QEffects::RightScroll;
- } else {
- if ((snapToMouse && (pos.x() + size.width() / 2 < mouse.x())) ||
- (qobject_cast<QMenu*>(d->causedPopup.widget) && pos.x() + size.width() / 2 < d->causedPopup.widget->x()))
- hGuess = QEffects::LeftScroll;
- }
-
-#ifndef QT_NO_MENUBAR
- if ((snapToMouse && (pos.y() + size.height() / 2 < mouse.y())) ||
- (qobject_cast<QMenuBar*>(d->causedPopup.widget) &&
- pos.y() + size.width() / 2 < d->causedPopup.widget->mapToGlobal(d->causedPopup.widget->pos()).y()))
- vGuess = QEffects::UpScroll;
-#endif
- if (QApplication::isEffectEnabled(Qt::UI_AnimateMenu)) {
- bool doChildEffects = true;
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(d->causedPopup.widget)) {
- doChildEffects = mb->d_func()->doChildEffects;
- mb->d_func()->doChildEffects = false;
- } else
-#endif
- if (QMenu *m = qobject_cast<QMenu*>(d->causedPopup.widget)) {
- doChildEffects = m->d_func()->doChildEffects;
- m->d_func()->doChildEffects = false;
- }
-
- if (doChildEffects) {
- if (QApplication::isEffectEnabled(Qt::UI_FadeMenu))
- qFadeEffect(this);
- else if (d->causedPopup.widget)
- qScrollEffect(this, qobject_cast<QMenu*>(d->causedPopup.widget) ? hGuess : vGuess);
- else
- qScrollEffect(this, hGuess | vGuess);
- } else {
- // kill any running effect
- qFadeEffect(0);
- qScrollEffect(0);
-
- show();
- }
- } else
-#endif
- {
- show();
- }
-
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::PopupMenuStart);
-#endif
-}
-
-/*!
- Executes this menu synchronously.
-
- This is equivalent to \c{exec(pos())}.
-
- This returns the triggered QAction in either the popup menu or one
- of its submenus, or 0 if no item was triggered (normally because
- the user pressed Esc).
-
- In most situations you'll want to specify the position yourself,
- for example, the current mouse position:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 0
- or aligned to a widget:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 1
- or in reaction to a QMouseEvent *e:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 2
-*/
-QAction *QMenu::exec()
-{
- return exec(pos());
-}
-
-
-/*!
- \overload
-
- Executes this menu synchronously.
-
- Pops up the menu so that the action \a action will be at the
- specified \e global position \a p. To translate a widget's local
- coordinates into global coordinates, use QWidget::mapToGlobal().
-
- This returns the triggered QAction in either the popup menu or one
- of its submenus, or 0 if no item was triggered (normally because
- the user pressed Esc).
-
- Note that all signals are emitted as usual. If you connect a
- QAction to a slot and call the menu's exec(), you get the result
- both via the signal-slot connection and in the return value of
- exec().
-
- Common usage is to position the menu at the current mouse
- position:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 3
- or aligned to a widget:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 4
- or in reaction to a QMouseEvent *e:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 5
-
- When positioning a menu with exec() or popup(), bear in mind that
- you cannot rely on the menu's current size(). For performance
- reasons, the menu adapts its size only when necessary. So in many
- cases, the size before and after the show is different. Instead,
- use sizeHint() which calculates the proper size depending on the
- menu's current contents.
-
- \sa popup(), QWidget::mapToGlobal()
-*/
-QAction *QMenu::exec(const QPoint &p, QAction *action)
-{
- Q_D(QMenu);
- createWinId();
- QEventLoop eventLoop;
- d->eventLoop = &eventLoop;
- popup(p, action);
-
- QPointer<QObject> guard = this;
- (void) eventLoop.exec();
- if (guard.isNull())
- return 0;
-
- action = d->syncAction;
- d->syncAction = 0;
- d->eventLoop = 0;
- return action;
-}
-
-/*!
- \overload
-
- Executes a menu synchronously.
-
- The menu's actions are specified by the list of \a actions. The menu will
- pop up so that the specified action, \a at, appears at global position \a
- pos. If \a at is not specified then the menu appears at position \a
- pos. \a parent is the menu's parent widget; specifying the parent will
- provide context when \a pos alone is not enough to decide where the menu
- should go (e.g., with multiple desktops or when the parent is embedded in
- QGraphicsView).
-
- The function returns the triggered QAction in either the popup
- menu or one of its submenus, or 0 if no item was triggered
- (normally because the user pressed Esc).
-
- This is equivalent to:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 6
-
- \sa popup(), QWidget::mapToGlobal()
-*/
-QAction *QMenu::exec(QList<QAction*> actions, const QPoint &pos, QAction *at, QWidget *parent)
-{
- QMenu menu(parent);
- menu.addActions(actions);
- return menu.exec(pos, at);
-}
-
-/*!
- \overload
-
- Executes a menu synchronously.
-
- The menu's actions are specified by the list of \a actions. The menu
- will pop up so that the specified action, \a at, appears at global
- position \a pos. If \a at is not specified then the menu appears
- at position \a pos.
-
- The function returns the triggered QAction in either the popup
- menu or one of its submenus, or 0 if no item was triggered
- (normally because the user pressed Esc).
-
- This is equivalent to:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenu.cpp 6
-
- \sa popup(), QWidget::mapToGlobal()
-*/
-QAction *QMenu::exec(QList<QAction*> actions, const QPoint &pos, QAction *at)
-{
- // ### Qt 5: merge
- return exec(actions, pos, at, 0);
-}
-
-/*!
- \reimp
-*/
-void QMenu::hideEvent(QHideEvent *)
-{
- Q_D(QMenu);
- emit aboutToHide();
- if (d->eventLoop)
- d->eventLoop->exit();
- d->setCurrentAction(0);
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::PopupMenuEnd);
-#endif
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(d->causedPopup.widget))
- mb->d_func()->setCurrentAction(0);
-#endif
- d->mouseDown = 0;
- d->hasHadMouse = false;
- d->causedPopup.widget = 0;
- d->causedPopup.action = 0;
- if (d->scroll)
- d->scroll->scrollTimer.stop(); //make sure the timer stops
-}
-
-/*!
- \reimp
-*/
-void QMenu::paintEvent(QPaintEvent *e)
-{
- Q_D(QMenu);
- d->updateActionRects();
- QPainter p(this);
- QRegion emptyArea = QRegion(rect());
-
- QStyleOptionMenuItem menuOpt;
- menuOpt.initFrom(this);
- menuOpt.state = QStyle::State_None;
- menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
- menuOpt.maxIconWidth = 0;
- menuOpt.tabWidth = 0;
- style()->drawPrimitive(QStyle::PE_PanelMenu, &menuOpt, &p, this);
-
- //draw the items that need updating..
- for (int i = 0; i < d->actions.count(); ++i) {
- QAction *action = d->actions.at(i);
- QRect adjustedActionRect = d->actionRects.at(i);
- if (!e->rect().intersects(adjustedActionRect)
- || d->widgetItems.value(action))
- continue;
- //set the clip region to be extra safe (and adjust for the scrollers)
- QRegion adjustedActionReg(adjustedActionRect);
- emptyArea -= adjustedActionReg;
- p.setClipRegion(adjustedActionReg);
-
- QStyleOptionMenuItem opt;
- initStyleOption(&opt, action);
- opt.rect = adjustedActionRect;
- style()->drawControl(QStyle::CE_MenuItem, &opt, &p, this);
- }
-
- const int fw = style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, this);
- //draw the scroller regions..
- if (d->scroll) {
- menuOpt.menuItemType = QStyleOptionMenuItem::Scroller;
- menuOpt.state |= QStyle::State_Enabled;
- if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp) {
- menuOpt.rect.setRect(fw, fw, width() - (fw * 2), d->scrollerHeight());
- emptyArea -= QRegion(menuOpt.rect);
- p.setClipRect(menuOpt.rect);
- style()->drawControl(QStyle::CE_MenuScroller, &menuOpt, &p, this);
- }
- if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown) {
- menuOpt.rect.setRect(fw, height() - d->scrollerHeight() - fw, width() - (fw * 2),
- d->scrollerHeight());
- emptyArea -= QRegion(menuOpt.rect);
- menuOpt.state |= QStyle::State_DownArrow;
- p.setClipRect(menuOpt.rect);
- style()->drawControl(QStyle::CE_MenuScroller, &menuOpt, &p, this);
- }
- }
- //paint the tear off..
- if (d->tearoff) {
- menuOpt.menuItemType = QStyleOptionMenuItem::TearOff;
- menuOpt.rect.setRect(fw, fw, width() - (fw * 2),
- style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, this));
- if (d->scroll && d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
- menuOpt.rect.translate(0, d->scrollerHeight());
- emptyArea -= QRegion(menuOpt.rect);
- p.setClipRect(menuOpt.rect);
- menuOpt.state = QStyle::State_None;
- if (d->tearoffHighlighted)
- menuOpt.state |= QStyle::State_Selected;
- style()->drawControl(QStyle::CE_MenuTearoff, &menuOpt, &p, this);
- }
- //draw border
- if (fw) {
- QRegion borderReg;
- borderReg += QRect(0, 0, fw, height()); //left
- borderReg += QRect(width()-fw, 0, fw, height()); //right
- borderReg += QRect(0, 0, width(), fw); //top
- borderReg += QRect(0, height()-fw, width(), fw); //bottom
- p.setClipRegion(borderReg);
- emptyArea -= borderReg;
- QStyleOptionFrame frame;
- frame.rect = rect();
- frame.palette = palette();
- frame.state = QStyle::State_None;
- frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuPanelWidth);
- frame.midLineWidth = 0;
- style()->drawPrimitive(QStyle::PE_FrameMenu, &frame, &p, this);
- }
-
- //finally the rest of the space
- p.setClipRegion(emptyArea);
- menuOpt.state = QStyle::State_None;
- menuOpt.menuItemType = QStyleOptionMenuItem::EmptyArea;
- menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
- menuOpt.rect = rect();
- menuOpt.menuRect = rect();
- style()->drawControl(QStyle::CE_MenuEmptyArea, &menuOpt, &p, this);
-}
-
-#ifndef QT_NO_WHEELEVENT
-/*!
- \reimp
-*/
-void QMenu::wheelEvent(QWheelEvent *e)
-{
- Q_D(QMenu);
- if (d->scroll && rect().contains(e->pos()))
- d->scrollMenu(e->delta() > 0 ?
- QMenuPrivate::QMenuScroller::ScrollUp : QMenuPrivate::QMenuScroller::ScrollDown);
-}
-#endif
-
-/*!
- \reimp
-*/
-void QMenu::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QMenu);
- if (d->aboutToHide || d->mouseEventTaken(e))
- return;
- if (!rect().contains(e->pos())) {
- if (d->noReplayFor
- && QRect(d->noReplayFor->mapToGlobal(QPoint()), d->noReplayFor->size()).contains(e->globalPos()))
- setAttribute(Qt::WA_NoMouseReplay);
- if (d->eventLoop) // synchronous operation
- d->syncAction = 0;
- d->hideUpToMenuBar();
- return;
- }
- d->mouseDown = this;
-
- QAction *action = d->actionAt(e->pos());
- d->setCurrentAction(action, 20);
- update();
-}
-
-/*!
- \reimp
-*/
-void QMenu::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QMenu);
- if (d->aboutToHide || d->mouseEventTaken(e))
- return;
- if(d->mouseDown != this) {
- d->mouseDown = 0;
- return;
- }
-
- d->mouseDown = 0;
- d->setSyncAction();
- QAction *action = d->actionAt(e->pos());
-
- if (action && action == d->currentAction) {
- if (!action->menu()){
-#if defined(Q_WS_WIN)
- //On Windows only context menus can be activated with the right button
- if (e->button() == Qt::LeftButton || d->topCausedWidget() == 0)
-#endif
- d->activateAction(action, QAction::Trigger);
- }
- } else if (d->hasMouseMoved(e->globalPos())) {
- d->hideUpToMenuBar();
- }
-}
-
-/*!
- \reimp
-*/
-void QMenu::changeEvent(QEvent *e)
-{
- Q_D(QMenu);
- if (e->type() == QEvent::StyleChange || e->type() == QEvent::FontChange ||
- e->type() == QEvent::LayoutDirectionChange) {
- d->itemsDirty = 1;
- setMouseTracking(style()->styleHint(QStyle::SH_Menu_MouseTracking, 0, this));
- if (isVisible())
- resize(sizeHint());
- if (!style()->styleHint(QStyle::SH_Menu_Scrollable, 0, this)) {
- delete d->scroll;
- d->scroll = 0;
- } else if (!d->scroll) {
- d->scroll = new QMenuPrivate::QMenuScroller;
- d->scroll->scrollFlags = QMenuPrivate::QMenuScroller::ScrollNone;
- }
- } else if (e->type() == QEvent::EnabledChange) {
- if (d->tornPopup) // torn-off menu
- d->tornPopup->setEnabled(isEnabled());
- d->menuAction->setEnabled(isEnabled());
-#ifdef Q_WS_MAC
- if (d->mac_menu)
- d->setMacMenuEnabled(isEnabled());
-#endif
- }
- QWidget::changeEvent(e);
-}
-
-
-/*!
- \reimp
-*/
-bool
-QMenu::event(QEvent *e)
-{
- Q_D(QMenu);
- switch (e->type()) {
- case QEvent::Polish:
- d->updateLayoutDirection();
- break;
- case QEvent::ShortcutOverride: {
- QKeyEvent *kev = static_cast<QKeyEvent*>(e);
- if (kev->key() == Qt::Key_Up || kev->key() == Qt::Key_Down
- || kev->key() == Qt::Key_Left || kev->key() == Qt::Key_Right
- || kev->key() == Qt::Key_Enter || kev->key() == Qt::Key_Return
- || kev->key() == Qt::Key_Escape) {
- e->accept();
- return true;
- }
- }
- break;
- case QEvent::KeyPress: {
- QKeyEvent *ke = (QKeyEvent*)e;
- if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
- keyPressEvent(ke);
- return true;
- }
- } break;
- case QEvent::ContextMenu:
- if(d->menuDelayTimer.isActive()) {
- d->menuDelayTimer.stop();
- internalDelayedPopup();
- }
- break;
- case QEvent::Resize: {
- QStyleHintReturnMask menuMask;
- QStyleOption option;
- option.initFrom(this);
- if (style()->styleHint(QStyle::SH_Menu_Mask, &option, this, &menuMask)) {
- setMask(menuMask.region);
- }
- d->itemsDirty = 1;
- d->updateActionRects();
- break; }
- case QEvent::Show:
- d->mouseDown = 0;
- d->updateActionRects();
- if (d->currentAction)
- d->popupAction(d->currentAction, 0, false);
- break;
-#ifndef QT_NO_WHATSTHIS
- case QEvent::QueryWhatsThis:
- e->setAccepted(d->whatsThis.size());
- if (QAction *action = d->actionAt(static_cast<QHelpEvent*>(e)->pos())) {
- if (action->whatsThis().size() || action->menu())
- e->accept();
- }
- return true;
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- case QEvent::LanguageChange: {
- d->selectAction->setText(QSoftKeyManager::standardSoftKeyText(QSoftKeyManager::SelectSoftKey));
- d->cancelAction->setText(QSoftKeyManager::standardSoftKeyText(QSoftKeyManager::CancelSoftKey));
- }
- break;
-#endif
- default:
- break;
- }
- return QWidget::event(e);
-}
-
-/*!
- \reimp
-*/
-bool QMenu::focusNextPrevChild(bool next)
-{
- setFocus();
- QKeyEvent ev(QEvent::KeyPress, next ? Qt::Key_Tab : Qt::Key_Backtab, Qt::NoModifier);
- keyPressEvent(&ev);
- return true;
-}
-
-/*!
- \reimp
-*/
-void QMenu::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QMenu);
- d->updateActionRects();
- int key = e->key();
- if (isRightToLeft()) { // in reverse mode open/close key for submenues are reversed
- if (key == Qt::Key_Left)
- key = Qt::Key_Right;
- else if (key == Qt::Key_Right)
- key = Qt::Key_Left;
- }
-#ifndef Q_WS_MAC
- if (key == Qt::Key_Tab) //means down
- key = Qt::Key_Down;
- if (key == Qt::Key_Backtab) //means up
- key = Qt::Key_Up;
-#endif
-
- bool key_consumed = false;
- switch(key) {
- case Qt::Key_Home:
- key_consumed = true;
- if (d->scroll)
- d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollTop, true);
- break;
- case Qt::Key_End:
- key_consumed = true;
- if (d->scroll)
- d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollBottom, true);
- break;
- case Qt::Key_PageUp:
- key_consumed = true;
- if (d->currentAction && d->scroll) {
- if(d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
- d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollUp, true, true);
- else
- d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollTop, true);
- }
- break;
- case Qt::Key_PageDown:
- key_consumed = true;
- if (d->currentAction && d->scroll) {
- if(d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)
- d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollDown, true, true);
- else
- d->scrollMenu(QMenuPrivate::QMenuScroller::ScrollBottom, true);
- }
- break;
- case Qt::Key_Up:
- case Qt::Key_Down: {
- key_consumed = true;
- QAction *nextAction = 0;
- QMenuPrivate::QMenuScroller::ScrollLocation scroll_loc = QMenuPrivate::QMenuScroller::ScrollStay;
- if (!d->currentAction) {
- if(key == Qt::Key_Down) {
- for(int i = 0; i < d->actions.count(); ++i) {
- QAction *act = d->actions.at(i);
- if (d->actionRects.at(i).isNull())
- continue;
- if (!act->isSeparator() &&
- (style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this)
- || act->isEnabled())) {
- nextAction = act;
- break;
- }
- }
- } else {
- for(int i = d->actions.count()-1; i >= 0; --i) {
- QAction *act = d->actions.at(i);
- if (d->actionRects.at(i).isNull())
- continue;
- if (!act->isSeparator() &&
- (style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this)
- || act->isEnabled())) {
- nextAction = act;
- break;
- }
- }
- }
- } else {
- for(int i = 0, y = 0; !nextAction && i < d->actions.count(); i++) {
- QAction *act = d->actions.at(i);
- if (act == d->currentAction) {
- if (key == Qt::Key_Up) {
- for(int next_i = i-1; true; next_i--) {
- if (next_i == -1) {
- if(!style()->styleHint(QStyle::SH_Menu_SelectionWrap, 0, this))
- break;
- if (d->scroll)
- scroll_loc = QMenuPrivate::QMenuScroller::ScrollBottom;
- next_i = d->actionRects.count()-1;
- }
- QAction *next = d->actions.at(next_i);
- if (next == d->currentAction)
- break;
- if (d->actionRects.at(next_i).isNull())
- continue;
- if (next->isSeparator() ||
- (!next->isEnabled() &&
- !style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this)))
- continue;
- nextAction = next;
- if (d->scroll && (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)) {
- int topVisible = d->scrollerHeight();
- if (d->tearoff)
- topVisible += style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, this);
- if (((y + d->scroll->scrollOffset) - topVisible) <= d->actionRects.at(next_i).height())
- scroll_loc = QMenuPrivate::QMenuScroller::ScrollTop;
- }
- break;
- }
- if (!nextAction && d->tearoff)
- d->tearoffHighlighted = 1;
- } else {
- y += d->actionRects.at(i).height();
- for(int next_i = i+1; true; next_i++) {
- if (next_i == d->actionRects.count()) {
- if(!style()->styleHint(QStyle::SH_Menu_SelectionWrap, 0, this))
- break;
- if (d->scroll)
- scroll_loc = QMenuPrivate::QMenuScroller::ScrollTop;
- next_i = 0;
- }
- QAction *next = d->actions.at(next_i);
- if (next == d->currentAction)
- break;
- if (d->actionRects.at(next_i).isNull())
- continue;
- if (next->isSeparator() ||
- (!next->isEnabled() &&
- !style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, this)))
- continue;
- nextAction = next;
- if (d->scroll && (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollDown)) {
- int bottomVisible = height() - d->scrollerHeight();
- if (d->scroll->scrollFlags & QMenuPrivate::QMenuScroller::ScrollUp)
- bottomVisible -= d->scrollerHeight();
- if (d->tearoff)
- bottomVisible -= style()->pixelMetric(QStyle::PM_MenuTearoffHeight, 0, this);
- if ((y + d->scroll->scrollOffset + d->actionRects.at(next_i).height()) > bottomVisible)
- scroll_loc = QMenuPrivate::QMenuScroller::ScrollBottom;
- }
- break;
- }
- }
- break;
- }
- y += d->actionRects.at(i).height();
- }
- }
- if (nextAction) {
- if (d->scroll && scroll_loc != QMenuPrivate::QMenuScroller::ScrollStay) {
- d->scroll->scrollTimer.stop();
- d->scrollMenu(nextAction, scroll_loc);
- }
- d->setCurrentAction(nextAction, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard);
- }
- break; }
-
- case Qt::Key_Right:
- if (d->currentAction && d->currentAction->isEnabled() && d->currentAction->menu()) {
- d->popupAction(d->currentAction, 0, true);
- key_consumed = true;
- break;
- }
- //FALL THROUGH
- case Qt::Key_Left: {
- if (d->currentAction && !d->scroll) {
- QAction *nextAction = 0;
- if (key == Qt::Key_Left) {
- QRect actionR = d->actionRect(d->currentAction);
- for(int x = actionR.left()-1; !nextAction && x >= 0; x--)
- nextAction = d->actionAt(QPoint(x, actionR.center().y()));
- } else {
- QRect actionR = d->actionRect(d->currentAction);
- for(int x = actionR.right()+1; !nextAction && x < width(); x++)
- nextAction = d->actionAt(QPoint(x, actionR.center().y()));
- }
- if (nextAction) {
- d->setCurrentAction(nextAction, /*popup*/-1, QMenuPrivate::SelectedFromKeyboard);
- key_consumed = true;
- }
- }
- if (!key_consumed && key == Qt::Key_Left && qobject_cast<QMenu*>(d->causedPopup.widget)) {
- QPointer<QWidget> caused = d->causedPopup.widget;
- d->hideMenu(this);
- if (caused)
- caused->setFocus();
- key_consumed = true;
- }
- break; }
-
- case Qt::Key_Alt:
- if (d->tornoff)
- break;
-
- key_consumed = true;
- if (style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, 0, this))
- {
- d->hideMenu(this);
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(QApplication::focusWidget())) {
- mb->d_func()->setKeyboardMode(false);
- }
-#endif
- }
- break;
-
- case Qt::Key_Escape:
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Back:
-#endif
- key_consumed = true;
- if (d->tornoff) {
- close();
- return;
- }
- {
- QPointer<QWidget> caused = d->causedPopup.widget;
- d->hideMenu(this); // hide after getting causedPopup
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(caused)) {
- mb->d_func()->setCurrentAction(d->menuAction);
- mb->d_func()->setKeyboardMode(true);
- }
-#endif
- }
- break;
-
- case Qt::Key_Space:
- if (!style()->styleHint(QStyle::SH_Menu_SpaceActivatesItem, 0, this))
- break;
- // for motif, fall through
-#ifdef QT_KEYPAD_NAVIGATION
- case Qt::Key_Select:
-#endif
- case Qt::Key_Return:
- case Qt::Key_Enter: {
- if (!d->currentAction) {
- d->setFirstActionActive();
- key_consumed = true;
- break;
- }
-
- d->setSyncAction();
-
- if (d->currentAction->menu())
- d->popupAction(d->currentAction, 0, true);
- else
- d->activateAction(d->currentAction, QAction::Trigger);
- key_consumed = true;
- break; }
-
-#ifndef QT_NO_WHATSTHIS
- case Qt::Key_F1:
- if (!d->currentAction || d->currentAction->whatsThis().isNull())
- break;
- QWhatsThis::enterWhatsThisMode();
- d->activateAction(d->currentAction, QAction::Trigger);
- return;
-#endif
- default:
- key_consumed = false;
- }
-
- if (!key_consumed) { // send to menu bar
- if ((!e->modifiers() || e->modifiers() == Qt::AltModifier || e->modifiers() == Qt::ShiftModifier) &&
- e->text().length()==1) {
- bool activateAction = false;
- QAction *nextAction = 0;
- if (style()->styleHint(QStyle::SH_Menu_KeyboardSearch, 0, this) && !e->modifiers()) {
- int best_match_count = 0;
- d->searchBufferTimer.start(2000, this);
- d->searchBuffer += e->text();
- for(int i = 0; i < d->actions.size(); ++i) {
- int match_count = 0;
- if (d->actionRects.at(i).isNull())
- continue;
- QAction *act = d->actions.at(i);
- const QString act_text = act->text();
- for(int c = 0; c < d->searchBuffer.size(); ++c) {
- if(act_text.indexOf(d->searchBuffer.at(c), 0, Qt::CaseInsensitive) != -1)
- ++match_count;
- }
- if(match_count > best_match_count) {
- best_match_count = match_count;
- nextAction = act;
- }
- }
- }
-#ifndef QT_NO_SHORTCUT
- else {
- int clashCount = 0;
- QAction *first = 0, *currentSelected = 0, *firstAfterCurrent = 0;
- QChar c = e->text().at(0).toUpper();
- for(int i = 0; i < d->actions.size(); ++i) {
- if (d->actionRects.at(i).isNull())
- continue;
- QAction *act = d->actions.at(i);
- QKeySequence sequence = QKeySequence::mnemonic(act->text());
- int key = sequence[0] & 0xffff;
- if (key == c.unicode()) {
- clashCount++;
- if (!first)
- first = act;
- if (act == d->currentAction)
- currentSelected = act;
- else if (!firstAfterCurrent && currentSelected)
- firstAfterCurrent = act;
- }
- }
- if (clashCount == 1)
- activateAction = true;
- if (clashCount >= 1) {
- if (clashCount == 1 || !currentSelected || !firstAfterCurrent)
- nextAction = first;
- else
- nextAction = firstAfterCurrent;
- }
- }
-#endif
- if (nextAction) {
- key_consumed = true;
- if(d->scroll)
- d->scrollMenu(nextAction, QMenuPrivate::QMenuScroller::ScrollCenter, false);
- d->setCurrentAction(nextAction, 20, QMenuPrivate::SelectedFromElsewhere, true);
- if (!nextAction->menu() && activateAction) {
- d->setSyncAction();
- d->activateAction(nextAction, QAction::Trigger);
- }
- }
- }
- if (!key_consumed) {
-#ifndef QT_NO_MENUBAR
- if (QMenuBar *mb = qobject_cast<QMenuBar*>(d->topCausedWidget())) {
- QAction *oldAct = mb->d_func()->currentAction;
- QApplication::sendEvent(mb, e);
- if (mb->d_func()->currentAction != oldAct)
- key_consumed = true;
- }
-#endif
- }
-
-#ifdef Q_OS_WIN32
- if (key_consumed && (e->key() == Qt::Key_Control || e->key() == Qt::Key_Shift || e->key() == Qt::Key_Meta))
- QApplication::beep();
-#endif // Q_OS_WIN32
- }
- if (key_consumed)
- e->accept();
- else
- e->ignore();
-}
-
-/*!
- \reimp
-*/
-void QMenu::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QMenu);
- if (!isVisible() || d->aboutToHide || d->mouseEventTaken(e))
- return;
- d->motions++;
- if (d->motions == 0) // ignore first mouse move event (see enterEvent())
- return;
- d->hasHadMouse = d->hasHadMouse || rect().contains(e->pos());
-
- QAction *action = d->actionAt(e->pos());
- if (!action) {
- if (d->hasHadMouse
- && (!d->currentAction
- || !(d->currentAction->menu() && d->currentAction->menu()->isVisible())))
- d->setCurrentAction(0);
- return;
- } else if(e->buttons()) {
- d->mouseDown = this;
- }
- if (d->sloppyRegion.contains(e->pos())) {
- d->sloppyAction = action;
- QMenuPrivate::sloppyDelayTimer = startTimer(style()->styleHint(QStyle::SH_Menu_SubMenuPopupDelay, 0, this)*6);
- } else if (action != d->currentAction) {
- d->setCurrentAction(action, style()->styleHint(QStyle::SH_Menu_SubMenuPopupDelay, 0, this));
- }
-}
-
-/*!
- \reimp
-*/
-void QMenu::enterEvent(QEvent *)
-{
- d_func()->motions = -1; // force us to ignore the generate mouse move in mouseMoveEvent()
-}
-
-/*!
- \reimp
-*/
-void QMenu::leaveEvent(QEvent *)
-{
- Q_D(QMenu);
- d->sloppyAction = 0;
- if (!d->sloppyRegion.isEmpty())
- d->sloppyRegion = QRegion();
- if (!d->activeMenu && d->currentAction)
- setActiveAction(0);
-}
-
-/*!
- \reimp
-*/
-void
-QMenu::timerEvent(QTimerEvent *e)
-{
- Q_D(QMenu);
- if (d->scroll && d->scroll->scrollTimer.timerId() == e->timerId()) {
- d->scrollMenu((QMenuPrivate::QMenuScroller::ScrollDirection)d->scroll->scrollDirection);
- if (d->scroll->scrollFlags == QMenuPrivate::QMenuScroller::ScrollNone)
- d->scroll->scrollTimer.stop();
- } else if(d->menuDelayTimer.timerId() == e->timerId()) {
- d->menuDelayTimer.stop();
- internalDelayedPopup();
- } else if(QMenuPrivate::sloppyDelayTimer == e->timerId()) {
- killTimer(QMenuPrivate::sloppyDelayTimer);
- QMenuPrivate::sloppyDelayTimer = 0;
- internalSetSloppyAction();
- } else if(d->searchBufferTimer.timerId() == e->timerId()) {
- d->searchBuffer.clear();
- }
-}
-
-/*!
- \reimp
-*/
-void QMenu::actionEvent(QActionEvent *e)
-{
- Q_D(QMenu);
- d->itemsDirty = 1;
- setAttribute(Qt::WA_Resized, false);
- if (d->tornPopup)
- d->tornPopup->syncWithMenu(this, e);
- if (e->type() == QEvent::ActionAdded) {
- if(!d->tornoff) {
- connect(e->action(), SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
- connect(e->action(), SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
- }
- if (QWidgetAction *wa = qobject_cast<QWidgetAction *>(e->action())) {
- QWidget *widget = wa->requestWidget(this);
- if (widget)
- d->widgetItems.insert(wa, widget);
- }
- } else if (e->type() == QEvent::ActionRemoved) {
- e->action()->disconnect(this);
- if (e->action() == d->currentAction)
- d->currentAction = 0;
- if (QWidgetAction *wa = qobject_cast<QWidgetAction *>(e->action())) {
- if (QWidget *widget = d->widgetItems.value(wa))
- wa->releaseWidget(widget);
- }
- d->widgetItems.remove(e->action());
- }
-
-#ifdef Q_WS_MAC
- if (d->mac_menu) {
- if (e->type() == QEvent::ActionAdded)
- d->mac_menu->addAction(e->action(), d->mac_menu->findAction(e->before()), d);
- else if (e->type() == QEvent::ActionRemoved)
- d->mac_menu->removeAction(e->action());
- else if (e->type() == QEvent::ActionChanged)
- d->mac_menu->syncAction(e->action());
- }
-#endif
-
-#if defined(Q_WS_WINCE) && !defined(QT_NO_MENUBAR)
- if (!d->wce_menu)
- d->wce_menu = new QMenuPrivate::QWceMenuPrivate;
- if (e->type() == QEvent::ActionAdded)
- d->wce_menu->addAction(e->action(), d->wce_menu->findAction(e->before()));
- else if (e->type() == QEvent::ActionRemoved)
- d->wce_menu->removeAction(e->action());
- else if (e->type() == QEvent::ActionChanged)
- d->wce_menu->syncAction(e->action());
-#endif
-
-#ifdef Q_WS_S60
- if (!d->symbian_menu)
- d->symbian_menu = new QMenuPrivate::QSymbianMenuPrivate;
- if (e->type() == QEvent::ActionAdded)
- d->symbian_menu->addAction(e->action(), d->symbian_menu->findAction(e->before()));
- else if (e->type() == QEvent::ActionRemoved)
- d->symbian_menu->removeAction(e->action());
- else if (e->type() == QEvent::ActionChanged)
- d->symbian_menu->syncAction(e->action());
-#endif
- if (isVisible()) {
- d->updateActionRects();
- resize(sizeHint());
- update();
- }
-}
-
-/*!
- \internal
-*/
-void QMenu::internalSetSloppyAction()
-{
- if (d_func()->sloppyAction)
- d_func()->setCurrentAction(d_func()->sloppyAction, 0);
-}
-
-/*!
- \internal
-*/
-void QMenu::internalDelayedPopup()
-{
- Q_D(QMenu);
-
- //hide the current item
- if (QMenu *menu = d->activeMenu) {
- d->activeMenu = 0;
- d->hideMenu(menu);
- }
-
- if (!d->currentAction || !d->currentAction->isEnabled() || !d->currentAction->menu() ||
- !d->currentAction->menu()->isEnabled() || d->currentAction->menu()->isVisible())
- return;
-
- //setup
- d->activeMenu = d->currentAction->menu();
- d->activeMenu->d_func()->causedPopup.widget = this;
- d->activeMenu->d_func()->causedPopup.action = d->currentAction;
-
- int subMenuOffset = style()->pixelMetric(QStyle::PM_SubMenuOverlap, 0, this);
- const QRect actionRect(d->actionRect(d->currentAction));
- const QSize menuSize(d->activeMenu->sizeHint());
- const QPoint rightPos(mapToGlobal(QPoint(actionRect.right() + subMenuOffset + 1, actionRect.top())));
- const QPoint leftPos(mapToGlobal(QPoint(actionRect.left() - subMenuOffset - menuSize.width(), actionRect.top())));
-
- QPoint pos(rightPos);
- QMenu *caused = qobject_cast<QMenu*>(d->activeMenu->d_func()->causedPopup.widget);
-
- const QRect availGeometry(d->popupGeometry(caused));
- if (isRightToLeft()) {
- pos = leftPos;
- if ((caused && caused->x() < x()) || pos.x() < availGeometry.left()) {
- if(rightPos.x() + menuSize.width() < availGeometry.right())
- pos = rightPos;
- else
- pos.rx() = availGeometry.left();
- }
- } else {
- if ((caused && caused->x() > x()) || pos.x() + menuSize.width() > availGeometry.right()) {
- if(leftPos.x() < availGeometry.left())
- pos.rx() = availGeometry.right() - menuSize.width();
- else
- pos = leftPos;
- }
- }
-
- //calc sloppy focus buffer
- if (style()->styleHint(QStyle::SH_Menu_SloppySubMenus, 0, this)) {
- QPoint cur = QCursor::pos();
- if (actionRect.contains(mapFromGlobal(cur))) {
- QPoint pts[4];
- pts[0] = QPoint(cur.x(), cur.y() - 2);
- pts[3] = QPoint(cur.x(), cur.y() + 2);
- if (pos.x() >= cur.x()) {
- pts[1] = QPoint(geometry().right(), pos.y());
- pts[2] = QPoint(geometry().right(), pos.y() + menuSize.height());
- } else {
- pts[1] = QPoint(pos.x() + menuSize.width(), pos.y());
- pts[2] = QPoint(pos.x() + menuSize.width(), pos.y() + menuSize.height());
- }
- QPolygon points(4);
- for(int i = 0; i < 4; i++)
- points.setPoint(i, mapFromGlobal(pts[i]));
- d->sloppyRegion = QRegion(points);
- }
- }
-
- //do the popup
- d->activeMenu->popup(pos);
-}
-
-/*!
- \fn void QMenu::addAction(QAction *action)
- \overload
-
- Appends the action \a action to the menu's list of actions.
-
- \sa QMenuBar::addAction(), QWidget::addAction()
-*/
-
-/*!
- \fn void QMenu::aboutToHide()
- \since 4.2
-
- This signal is emitted just before the menu is hidden from the user.
-
- \sa aboutToShow(), hide()
-*/
-
-/*!
- \fn void QMenu::aboutToShow()
-
- This signal is emitted just before the menu is shown to the user.
-
- \sa aboutToHide(), show()
-*/
-
-/*!
- \fn void QMenu::triggered(QAction *action)
-
- This signal is emitted when an action in this menu is triggered.
-
- \a action is the action that caused the signal to be emitted.
-
- Normally, you connect each menu action's \l{QAction::}{triggered()} signal
- to its own custom slot, but sometimes you will want to connect several
- actions to a single slot, for example, when you have a group of closely
- related actions, such as "left justify", "center", "right justify".
-
- \note This signal is emitted for the main parent menu in a hierarchy.
- Hence, only the parent menu needs to be connected to a slot; sub-menus need
- not be connected.
-
- \sa hovered(), QAction::triggered()
-*/
-
-/*!
- \fn void QMenu::hovered(QAction *action)
-
- This signal is emitted when a menu action is highlighted; \a action
- is the action that caused the signal to be emitted.
-
- Often this is used to update status information.
-
- \sa triggered(), QAction::hovered()
-*/
-
-
-/*!\internal
-*/
-void QMenu::setNoReplayFor(QWidget *noReplayFor)
-{
-#ifdef Q_WS_WIN
- d_func()->noReplayFor = noReplayFor;
-#else
- Q_UNUSED(noReplayFor);
-#endif
-}
-
-/*!
- \property QMenu::separatorsCollapsible
- \since 4.2
-
- \brief whether consecutive separators should be collapsed
-
- This property specifies whether consecutive separators in the menu
- should be visually collapsed to a single one. Separators at the
- beginning or the end of the menu are also hidden.
-
- By default, this property is true.
-*/
-bool QMenu::separatorsCollapsible() const
-{
- Q_D(const QMenu);
- return d->collapsibleSeparators;
-}
-
-void QMenu::setSeparatorsCollapsible(bool collapse)
-{
- Q_D(QMenu);
- if (d->collapsibleSeparators == collapse)
- return;
-
- d->collapsibleSeparators = collapse;
- d->itemsDirty = 1;
- if (isVisible()) {
- d->updateActionRects();
- update();
- }
-#ifdef Q_WS_MAC
- if (d->mac_menu)
- d->syncSeparatorsCollapsible(collapse);
-#endif
-}
-
-#ifdef QT3_SUPPORT
-
-int QMenu::insertAny(const QIcon *icon, const QString *text, const QObject *receiver, const char *member,
- const QKeySequence *shortcut, const QMenu *popup, int id, int index)
-{
- QAction *act = popup ? popup->menuAction() : new QAction(this);
- if (id != -1)
- static_cast<QMenuItem*>(act)->setId(id);
- if (icon)
- act->setIcon(*icon);
- if (text)
- act->setText(*text);
- if (shortcut)
- act->setShortcut(*shortcut);
- if (receiver && member)
- QObject::connect(act, SIGNAL(activated(int)), receiver, member);
- if (index == -1 || index >= actions().count())
- addAction(act);
- else
- insertAction(actions().value(index), act);
- return findIdForAction(act);
-}
-
-/*!
- Use insertAction() or one of the addAction() overloads instead.
-*/
-int QMenu::insertItem(QMenuItem *item, int id, int index)
-{
- if (index == -1 || index >= actions().count())
- addAction(item);
- else
- insertAction(actions().value(index), item);
- if (id > -1)
- item->d_func()->id = id;
- return findIdForAction(item);
-}
-
-/*!
- Use the insertSeparator() overload that takes a QAction *
- parameter instead.
-*/
-int QMenu::insertSeparator(int index)
-{
- QAction *act = new QAction(this);
- act->setSeparator(true);
- if (index == -1 || index >= actions().count())
- addAction(act);
- else
- insertAction(actions().value(index), act);
- return findIdForAction(act);
-}
-
-QAction *QMenu::findActionForId(int id) const
-{
- Q_D(const QMenu);
- for (int i = 0; i < d->actions.size(); ++i) {
- QAction *act = d->actions.at(i);
- if (findIdForAction(act)== id)
- return act;
- }
- return 0;
-}
-
-/*!
- Use QAction and actions() instead.
-*/
-QMenuItem *QMenu::findPopup( QMenu *popup, int *index )
-{
- QList<QAction *> list = actions();
- for (int i = 0; i < list.size(); ++i) {
- QAction *act = list.at(i);
- if (act->menu() == popup) {
- QMenuItem *item = static_cast<QMenuItem *>(act);
- if (index)
- *index = act->d_func()->id;
- return item;
- }
- }
- return 0;
-}
-
-
-/*!
- Use QAction::setData() instead.
-*/
-bool QMenu::setItemParameter(int id, int param)
-{
- if (QAction *act = findActionForId(id)) {
- act->d_func()->param = param;
- return true;
- }
- return false;
-}
-
-/*!
- Use QAction::data() instead.
-*/
-int QMenu::itemParameter(int id) const
-{
- if (QAction *act = findActionForId(id))
- return act->d_func()->param;
- return id;
-}
-
-/*!
- Use actions instead.
-*/
-void QMenu::setId(int index, int id)
-{
- if(QAction *act = actions().value(index))
- act->d_func()->id = id;
-}
-
-/*!
- Use style()->pixelMetric(QStyle::PM_MenuPanelWidth, this) instead.
-*/
-int QMenu::frameWidth() const
-{
- return style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0, this);
-}
-
-int QMenu::findIdForAction(QAction *act) const
-{
- if (!act)
- return -1;
- return act->d_func()->id;
-}
-#endif // QT3_SUPPORT
-
-/*!
- \fn uint QMenu::count() const
-
- Use actions().count() instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QString &text, const QObject *receiver, const char* member, const QKeySequence& shortcut, int id, int index)
-
- Use insertAction() or one of the addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QIcon& icon, const QString &text, const QObject *receiver, const char* member, const QKeySequence& shortcut, int id, int index)
-
- Use insertAction() or one of the addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QPixmap &pixmap, const QObject *receiver, const char* member, const QKeySequence& shortcut, int id, int index)
-
- Use insertAction() or one of the addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QString &text, int id, int index)
-
- Use insertAction() or one of the addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QIcon& icon, const QString &text, int id, int index)
-
- Use insertAction() or one of the addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QString &text, QMenu *popup, int id, int index)
-
- Use insertMenu() or one of the addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QIcon& icon, const QString &text, QMenu *popup, int id, int index)
-
- Use insertMenu() or one of the addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QPixmap &pixmap, int id, int index)
-
- Use insertAction() or one of the addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenu::insertItem(const QPixmap &pixmap, QMenu *popup, int id, int index)
-
- Use insertMenu() or one of the addMenu() overloads instead.
-*/
-
-/*!
- \fn void QMenu::removeItem(int id)
-
- Use removeAction() instead.
-*/
-
-/*!
- \fn void QMenu::removeItemAt(int index)
-
- Use removeAction() instead.
-*/
-
-/*!
- \fn QKeySequence QMenu::accel(int id) const
-
- Use shortcut() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::setAccel(const QKeySequence& key, int id)
-
- Use setShortcut() on the relevant QAction instead.
-*/
-
-/*!
- \fn QIcon QMenu::iconSet(int id) const
-
- Use icon() on the relevant QAction instead.
-*/
-
-/*!
- \fn QString QMenu::text(int id) const
-
- Use text() on the relevant QAction instead.
-*/
-
-/*!
- \fn QPixmap QMenu::pixmap(int id) const
-
- Use QPixmap(icon()) on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::setWhatsThis(int id, const QString &w)
-
- Use setWhatsThis() on the relevant QAction instead.
-*/
-
-/*!
- \fn QString QMenu::whatsThis(int id) const
-
- Use whatsThis() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::changeItem(int id, const QString &text)
-
- Use setText() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::changeItem(int id, const QPixmap &pixmap)
-
- Use setText() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::changeItem(int id, const QIcon &icon, const QString &text)
-
- Use setIcon() and setText() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenu::isItemActive(int id) const
-
- Use activeAction() instead.
-*/
-
-/*!
- \fn bool QMenu::isItemEnabled(int id) const
-
- Use isEnabled() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::setItemEnabled(int id, bool enable)
-
- Use setEnabled() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenu::isItemChecked(int id) const
-
- Use isChecked() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::setItemChecked(int id, bool check)
-
- Use setChecked() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenu::isItemVisible(int id) const
-
- Use isVisible() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::setItemVisible(int id, bool visible)
-
- Use setVisible() on the relevant QAction instead.
-*/
-
-/*!
- \fn QRect QMenu::itemGeometry(int index)
-
- Use actionGeometry() on the relevant QAction instead.
-*/
-
-/*!
- \fn QFont QMenu::itemFont(int id) const
-
- Use font() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenu::setItemFont(int id, const QFont &font)
-
- Use setFont() on the relevant QAction instead.
-*/
-
-/*!
- \fn int QMenu::indexOf(int id) const
-
- Use actions().indexOf(action) on the relevant QAction instead.
-*/
-
-/*!
- \fn int QMenu::idAt(int index) const
-
- Use actions instead.
-*/
-
-/*!
- \fn void QMenu::activateItemAt(int index)
-
- Use activate() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenu::connectItem(int id, const QObject *receiver, const char* member)
-
- Use connect() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenu::disconnectItem(int id,const QObject *receiver, const char* member)
- Use disconnect() on the relevant QAction instead.
-
-*/
-
-/*!
- \fn QMenuItem *QMenu::findItem(int id) const
-
- Use actions instead.
-*/
-
-/*!
- \fn void QMenu::popup(const QPoint & pos, int indexAtPoint)
-
- Use popup() on the relevant QAction instead.
-*/
-
-/*!
- \fn int QMenu::insertTearOffHandle(int a, int b)
-
- Use setTearOffEnabled() instead.
-*/
-
-/*!
- \fn int QMenu::itemAtPos(const QPoint &p, bool ignoreSeparator)
-
- Use actions instead.
-*/
-
-/*!
- \fn int QMenu::columns() const
-
- Use columnCount() instead.
-*/
-
-/*!
- \fn int QMenu::itemHeight(int index)
-
- Use actionGeometry(actions().value(index)).height() instead.
-*/
-
-/*!
- \fn int QMenu::itemHeight(QMenuItem *mi)
-
- Use actionGeometry() instead.
-*/
-
-/*!
- \fn void QMenu::activated(int itemId);
-
- Use triggered() instead.
-*/
-
-/*!
- \fn void QMenu::highlighted(int itemId);
-
- Use hovered() instead.
-*/
-
-/*!
- \fn void QMenu::setCheckable(bool checkable)
-
- Not necessary anymore. The \a checkable parameter is ignored.
-*/
-
-/*!
- \fn bool QMenu::isCheckable() const
-
- Not necessary anymore. Always returns true.
-*/
-
-/*!
- \fn void QMenu::setActiveItem(int id)
-
- Use setActiveAction() instead.
-*/
-
-QT_END_NAMESPACE
-
-// for private slots
-#include "moc_qmenu.cpp"
-#include "qmenu.moc"
-
-#endif // QT_NO_MENU
diff --git a/src/gui/widgets/qmenu.h b/src/gui/widgets/qmenu.h
deleted file mode 100644
index daac91632a..0000000000
--- a/src/gui/widgets/qmenu.h
+++ /dev/null
@@ -1,434 +0,0 @@
-/****************************************************************************
-**
-** 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 QMENU_H
-#define QMENU_H
-
-#include <QtGui/qwidget.h>
-#include <QtCore/qstring.h>
-#include <QtGui/qicon.h>
-#include <QtGui/qaction.h>
-
-#ifdef QT3_SUPPORT
-#include <QtGui/qpixmap.h>
-#endif
-
-#ifdef Q_WS_WINCE
-#include <windef.h> // for HMENU
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_MENU
-
-class QMenuPrivate;
-class QStyleOptionMenuItem;
-#ifdef QT3_SUPPORT
-class QMenuItem;
-#endif
-
-class Q_GUI_EXPORT QMenu : public QWidget
-{
-private:
- Q_OBJECT
- Q_DECLARE_PRIVATE(QMenu)
-
- Q_PROPERTY(bool tearOffEnabled READ isTearOffEnabled WRITE setTearOffEnabled)
- Q_PROPERTY(QString title READ title WRITE setTitle)
- Q_PROPERTY(QIcon icon READ icon WRITE setIcon)
- Q_PROPERTY(bool separatorsCollapsible READ separatorsCollapsible WRITE setSeparatorsCollapsible)
-
-public:
- explicit QMenu(QWidget *parent = 0);
- explicit QMenu(const QString &title, QWidget *parent = 0);
- ~QMenu();
-
-#ifdef Q_NO_USING_KEYWORD
- inline void addAction(QAction *action) { QWidget::addAction(action); }
-#else
- using QWidget::addAction;
-#endif
- QAction *addAction(const QString &text);
- QAction *addAction(const QIcon &icon, const QString &text);
- QAction *addAction(const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut = 0);
- QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member, const QKeySequence &shortcut = 0);
-
- QAction *addMenu(QMenu *menu);
- QMenu *addMenu(const QString &title);
- QMenu *addMenu(const QIcon &icon, const QString &title);
-
- QAction *addSeparator();
-
- QAction *insertMenu(QAction *before, QMenu *menu);
- QAction *insertSeparator(QAction *before);
-
- bool isEmpty() const;
- void clear();
-
- void setTearOffEnabled(bool);
- bool isTearOffEnabled() const;
-
- bool isTearOffMenuVisible() const;
- void hideTearOffMenu();
-
- void setDefaultAction(QAction *);
- QAction *defaultAction() const;
-
- void setActiveAction(QAction *act);
- QAction *activeAction() const;
-
- void popup(const QPoint &pos, QAction *at=0);
- QAction *exec();
- QAction *exec(const QPoint &pos, QAction *at=0);
-
- // ### Qt 5: merge
- static QAction *exec(QList<QAction*> actions, const QPoint &pos, QAction *at=0);
- static QAction *exec(QList<QAction*> actions, const QPoint &pos, QAction *at, QWidget *parent);
-
- QSize sizeHint() const;
-
- QRect actionGeometry(QAction *) const;
- QAction *actionAt(const QPoint &) const;
-
- QAction *menuAction() const;
-
- QString title() const;
- void setTitle(const QString &title);
-
- QIcon icon() const;
- void setIcon(const QIcon &icon);
-
- void setNoReplayFor(QWidget *widget);
-#ifdef Q_WS_MAC
- OSMenuRef macMenu(OSMenuRef merge=0);
-#endif
-
-#ifdef Q_WS_WINCE
- HMENU wceMenu();
-#endif
-
- bool separatorsCollapsible() const;
- void setSeparatorsCollapsible(bool collapse);
-
-Q_SIGNALS:
- void aboutToShow();
- void aboutToHide();
- void triggered(QAction *action);
- void hovered(QAction *action);
-
-protected:
- int columnCount() const;
-
- void changeEvent(QEvent *);
- void keyPressEvent(QKeyEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void mousePressEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *);
-#endif
- void enterEvent(QEvent *);
- void leaveEvent(QEvent *);
- void hideEvent(QHideEvent *);
- void paintEvent(QPaintEvent *);
- void actionEvent(QActionEvent *);
- void timerEvent(QTimerEvent *);
- bool event(QEvent *);
- bool focusNextPrevChild(bool next);
- void initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const;
-
-#ifdef Q_WS_WINCE
- QAction* wceCommands(uint command);
-#endif
-
-private Q_SLOTS:
- void internalSetSloppyAction();
- void internalDelayedPopup();
-
-private:
- Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())
- Q_PRIVATE_SLOT(d_func(), void _q_actionHovered())
- Q_PRIVATE_SLOT(d_func(), void _q_overrideMenuActionDestroyed())
-
-#ifdef QT3_SUPPORT
-public:
- //menudata
- inline QT3_SUPPORT uint count() const { return actions().count(); }
- inline QT3_SUPPORT int insertItem(const QString &text, const QObject *receiver, const char* member,
- const QKeySequence& shortcut = 0, int id = -1, int index = -1) {
- return insertAny(0, &text, receiver, member, &shortcut, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QIcon& icon, const QString &text,
- const QObject *receiver, const char* member,
- const QKeySequence& shortcut = 0, int id = -1, int index = -1) {
- return insertAny(&icon, &text, receiver, member, &shortcut, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QPixmap &pixmap, const QObject *receiver, const char* member,
- const QKeySequence& shortcut = 0, int id = -1, int index = -1) {
- QIcon icon(pixmap);
- return insertAny(&icon, 0, receiver, member, &shortcut, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QString &text, int id=-1, int index=-1) {
- return insertAny(0, &text, 0, 0, 0, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QIcon& icon, const QString &text, int id=-1, int index=-1) {
- return insertAny(&icon, &text, 0, 0, 0, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QString &text, QMenu *popup, int id=-1, int index=-1) {
- return insertAny(0, &text, 0, 0, 0, popup, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QIcon& icon, const QString &text, QMenu *popup, int id=-1, int index=-1) {
- return insertAny(&icon, &text, 0, 0, 0, popup, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QPixmap &pixmap, int id=-1, int index=-1) {
- QIcon icon(pixmap);
- return insertAny(&icon, 0, 0, 0, 0, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QPixmap &pixmap, QMenu *popup, int id=-1, int index=-1) {
- QIcon icon(pixmap);
- return insertAny(&icon, 0, 0, 0, 0, popup, id, index);
- }
- QT3_SUPPORT int insertItem(QMenuItem *item, int id=-1, int index=-1);
- QT3_SUPPORT int insertSeparator(int index=-1);
- inline QT3_SUPPORT void removeItem(int id) {
- if(QAction *act = findActionForId(id))
- removeAction(act); }
- inline QT3_SUPPORT void removeItemAt(int index) {
- if(QAction *act = actions().value(index))
- removeAction(act); }
-#ifndef QT_NO_SHORTCUT
- inline QT3_SUPPORT QKeySequence accel(int id) const {
- if(QAction *act = findActionForId(id))
- return act->shortcut();
- return QKeySequence(); }
- inline QT3_SUPPORT void setAccel(const QKeySequence& key, int id) {
- if(QAction *act = findActionForId(id))
- act->setShortcut(key);
- }
-#endif
- inline QT3_SUPPORT QIcon iconSet(int id) const {
- if(QAction *act = findActionForId(id))
- return act->icon();
- return QIcon(); }
- inline QT3_SUPPORT QString text(int id) const {
- if(QAction *act = findActionForId(id))
- return act->text();
- return QString(); }
- inline QT3_SUPPORT QPixmap pixmap(int id) const {
- if(QAction *act = findActionForId(id))
- return act->icon().pixmap(QSize(22, 22));
- return QPixmap(); }
- inline QT3_SUPPORT void setWhatsThis(int id, const QString &w) {
- if(QAction *act = findActionForId(id))
- act->setWhatsThis(w); }
- inline QT3_SUPPORT QString whatsThis(int id) const {
- if(QAction *act = findActionForId(id))
- return act->whatsThis();
- return QString(); }
-
- inline QT3_SUPPORT void changeItem(int id, const QString &text) {
- if(QAction *act = findActionForId(id))
- act->setText(text); }
- inline QT3_SUPPORT void changeItem(int id, const QPixmap &pixmap) {
- if(QAction *act = findActionForId(id))
- act->setIcon(QIcon(pixmap)); }
- inline QT3_SUPPORT void changeItem(int id, const QIcon &icon, const QString &text) {
- if(QAction *act = findActionForId(id)) {
- act->setIcon(icon);
- act->setText(text);
- }
- }
- inline QT3_SUPPORT void setActiveItem(int id) {
- setActiveAction(findActionForId(id));
- }
- inline QT3_SUPPORT bool isItemActive(int id) const {
- return findActionForId(id) == activeAction();
- }
- inline QT3_SUPPORT bool isItemEnabled(int id) const {
- if(QAction *act = findActionForId(id))
- return act->isEnabled();
- return false; }
- inline QT3_SUPPORT void setItemEnabled(int id, bool enable) {
- if(QAction *act = findActionForId(id))
- act->setEnabled(enable);
- }
- inline QT3_SUPPORT bool isItemChecked(int id) const {
- if(QAction *act = findActionForId(id))
- return act->isChecked();
- return false;
- }
- inline QT3_SUPPORT void setItemChecked(int id, bool check) {
- if(QAction *act = findActionForId(id)) {
- act->setCheckable(true);
- act->setChecked(check);
- }
- }
- inline QT3_SUPPORT bool isItemVisible(int id) const {
- if(QAction *act = findActionForId(id))
- return act->isVisible();
- return false;
- }
- inline QT3_SUPPORT void setItemVisible(int id, bool visible) {
- if(QAction *act = findActionForId(id))
- act->setVisible(visible);
- }
- inline QT3_SUPPORT QRect itemGeometry(int index) {
- if(QAction *act = actions().value(index))
- return actionGeometry(act);
- return QRect();
- }
- inline QT3_SUPPORT QFont itemFont(int id) const {
- if(QAction *act = findActionForId(id))
- return act->font();
- return QFont();
- }
- inline QT3_SUPPORT void setItemFont(int id, const QFont &font) {
- if(QAction *act = findActionForId(id))
- act->setFont(font);
- }
- inline QT3_SUPPORT int indexOf(int id) const {
- return actions().indexOf(findActionForId(id));
- }
- inline QT3_SUPPORT int idAt(int index) const {
- return findIdForAction(actions().value(index));
- }
- QT3_SUPPORT void setId (int index, int id);
- inline QT3_SUPPORT void activateItemAt(int index) {
- if(QAction *ret = actions().value(index))
- ret->activate(QAction::Trigger);
- }
- inline QT3_SUPPORT bool connectItem(int id, const QObject *receiver, const char* member) {
- if(QAction *act = findActionForId(id)) {
- QObject::connect(act, SIGNAL(activated(int)), receiver, member);
- return true;
- }
- return false;
- }
- inline QT3_SUPPORT bool disconnectItem(int id,const QObject *receiver, const char* member) {
- if(QAction *act = findActionForId(id)) {
- QObject::disconnect(act, SIGNAL(triggered()), receiver, member);
- return true;
- }
- return false;
- }
- inline QT3_SUPPORT QMenuItem *findItem(int id) const {
- return reinterpret_cast<QMenuItem*>(findActionForId(id));
- }
-
- inline QT3_SUPPORT void setCheckable(bool){}
- inline QT3_SUPPORT bool isCheckable() const {return true;}
-
- QT3_SUPPORT QMenuItem *findPopup( QMenu *popup, int *index );
-
- QT3_SUPPORT bool setItemParameter(int id, int param);
- QT3_SUPPORT int itemParameter(int id) const;
-
- //frame
- QT3_SUPPORT int frameWidth() const;
-
- //popupmenu
- inline QT3_SUPPORT void popup(const QPoint & pos, int indexAtPoint) { popup(pos, actions().value(indexAtPoint)); }
- inline QT3_SUPPORT int insertTearOffHandle(int = 0, int = 0) {
- setTearOffEnabled(true);
- return -1;
- }
-
-protected:
- inline QT3_SUPPORT int itemAtPos(const QPoint &p, bool ignoreSeparator = true) {
- QAction *ret = actionAt(p);
- if(ignoreSeparator && ret && ret->isSeparator())
- return -1;
- return findIdForAction(ret);
- }
- inline QT3_SUPPORT int columns() const { return columnCount(); }
- inline QT3_SUPPORT int itemHeight(int index) {
- return actionGeometry(actions().value(index)).height();
- }
- inline QT3_SUPPORT int itemHeight(QMenuItem *mi) {
- return actionGeometry(reinterpret_cast<QAction *>(mi)).height();
- }
-
-Q_SIGNALS:
- QT_MOC_COMPAT void activated(int itemId);
- QT_MOC_COMPAT void highlighted(int itemId);
-
-private:
- int insertAny(const QIcon *icon, const QString *text, const QObject *receiver, const char *member,
- const QKeySequence *shorcut, const QMenu *popup, int id, int index);
- QAction *findActionForId(int id) const;
- int findIdForAction(QAction*) const;
-#endif
-
-protected:
- QMenu(QMenuPrivate &dd, QWidget* parent = 0);
-
-private:
- Q_DISABLE_COPY(QMenu)
-
- friend class QMenuBar;
- friend class QMenuBarPrivate;
- friend class QTornOffMenu;
- friend class Q3PopupMenu;
- friend class QComboBox;
- friend class QAction;
- friend class QToolButtonPrivate;
-
-#ifdef Q_WS_MAC
- friend void qt_mac_trayicon_activate_action(QMenu *, QAction *action);
- friend bool qt_mac_watchingAboutToShow(QMenu *);
- friend OSStatus qt_mac_menu_event(EventHandlerCallRef, EventRef, void *);
- friend bool qt_mac_activate_action(OSMenuRef, uint, QAction::ActionEvent, bool);
- friend void qt_mac_emit_menuSignals(QMenu *, bool);
- friend void qt_mac_menu_emit_hovered(QMenu *menu, QAction *action);
-#endif
-};
-
-#endif // QT_NO_MENU
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMENU_H
diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm
deleted file mode 100644
index 2977558a75..0000000000
--- a/src/gui/widgets/qmenu_mac.mm
+++ /dev/null
@@ -1,2217 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmenu.h"
-#include "qhash.h"
-#include <qdebug.h>
-#include "qapplication.h"
-#include <private/qt_mac_p.h>
-#include "qregexp.h"
-#include "qmainwindow.h"
-#include "qdockwidget.h"
-#include "qtoolbar.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qwidgetaction.h"
-#include "qmacnativewidget_mac.h"
-
-#include <private/qapplication_p.h>
-#include <private/qcocoaapplication_mac_p.h>
-#include <private/qmenu_p.h>
-#include <private/qmenubar_p.h>
-#include <private/qcocoamenuloader_mac_p.h>
-#include <private/qcocoamenu_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#include <Cocoa/Cocoa.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
- QMenu debug facilities
- *****************************************************************************/
-
-/*****************************************************************************
- QMenu globals
- *****************************************************************************/
-bool qt_mac_no_menubar_merge = false;
-bool qt_mac_quit_menu_item_enabled = true;
-int qt_mac_menus_open_count = 0;
-
-static OSMenuRef qt_mac_create_menu(QWidget *w);
-
-#ifndef QT_MAC_USE_COCOA
-static uint qt_mac_menu_static_cmd_id = 'QT00';
-const UInt32 kMenuCreatorQt = 'cute';
-enum {
- kMenuPropertyQAction = 'QAcT',
- kMenuPropertyQWidget = 'QWId',
- kMenuPropertyCausedQWidget = 'QCAU',
- kMenuPropertyMergeMenu = 'QApP',
- kMenuPropertyMergeList = 'QAmL',
- kMenuPropertyWidgetActionWidget = 'QWid',
- kMenuPropertyWidgetMenu = 'QWMe',
-
- kHICommandAboutQt = 'AOQT',
- kHICommandCustomMerge = 'AQt0'
-};
-#endif
-
-static struct {
- QPointer<QMenuBar> qmenubar;
- bool modal;
-} qt_mac_current_menubar = { 0, false };
-
-
-
-
-/*****************************************************************************
- Externals
- *****************************************************************************/
-extern OSViewRef qt_mac_hiview_for(const QWidget *w); //qwidget_mac.cpp
-extern HIViewRef qt_mac_hiview_for(OSWindowRef w); //qwidget_mac.cpp
-extern IconRef qt_mac_create_iconref(const QPixmap &px); //qpixmap_mac.cpp
-extern QWidget * mac_keyboard_grabber; //qwidget_mac.cpp
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); //qapplication_xxx.cpp
-RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
-void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-
-/*****************************************************************************
- QMenu utility functions
- *****************************************************************************/
-bool qt_mac_watchingAboutToShow(QMenu *menu)
-{
- return menu && menu->receivers(SIGNAL(aboutToShow()));
-}
-
-static int qt_mac_CountMenuItems(OSMenuRef menu)
-{
- if (menu) {
-#ifndef QT_MAC_USE_COCOA
- int ret = 0;
- const int items = CountMenuItems(menu);
- for(int i = 0; i < items; i++) {
- MenuItemAttributes attr;
- if (GetMenuItemAttributes(menu, i+1, &attr) == noErr &&
- attr & kMenuItemAttrHidden)
- continue;
- ++ret;
- }
- return ret;
-#else
- return [menu numberOfItems];
-#endif
- }
- return 0;
-}
-
-static quint32 constructModifierMask(quint32 accel_key)
-{
- quint32 ret = 0;
- const bool dontSwap = qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta);
-#ifndef QT_MAC_USE_COCOA
- if ((accel_key & Qt::ALT) == Qt::ALT)
- ret |= kMenuOptionModifier;
- if ((accel_key & Qt::SHIFT) == Qt::SHIFT)
- ret |= kMenuShiftModifier;
- if (dontSwap) {
- if ((accel_key & Qt::META) != Qt::META)
- ret |= kMenuNoCommandModifier;
- if ((accel_key & Qt::CTRL) == Qt::CTRL)
- ret |= kMenuControlModifier;
- } else {
- if ((accel_key & Qt::CTRL) != Qt::CTRL)
- ret |= kMenuNoCommandModifier;
- if ((accel_key & Qt::META) == Qt::META)
- ret |= kMenuControlModifier;
- }
-#else
- if ((accel_key & Qt::CTRL) == Qt::CTRL)
- ret |= (dontSwap ? NSControlKeyMask : NSCommandKeyMask);
- if ((accel_key & Qt::META) == Qt::META)
- ret |= (dontSwap ? NSCommandKeyMask : NSControlKeyMask);
- if ((accel_key & Qt::ALT) == Qt::ALT)
- ret |= NSAlternateKeyMask;
- if ((accel_key & Qt::SHIFT) == Qt::SHIFT)
- ret |= NSShiftKeyMask;
-#endif
- return ret;
-}
-
-static void cancelAllMenuTracking()
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- NSMenu *mainMenu = [NSApp mainMenu];
- [mainMenu cancelTracking];
- for (NSMenuItem *item in [mainMenu itemArray]) {
- if ([item submenu]) {
- [[item submenu] cancelTracking];
- }
- }
-#else
- CancelMenuTracking(AcquireRootMenu(), true, 0);
-#endif
-}
-
-static bool actualMenuItemVisibility(const QMenuBarPrivate::QMacMenuBarPrivate *mbp,
- const QMacMenuAction *action)
-{
- bool visible = action->action->isVisible();
- if (visible && action->action->text() == QString(QChar(0x14)))
- return false;
- if (visible && action->action->menu() && !action->action->menu()->actions().isEmpty() &&
- !qt_mac_CountMenuItems(action->action->menu()->macMenu(mbp->apple_menu)) &&
- !qt_mac_watchingAboutToShow(action->action->menu())) {
- return false;
- }
- return visible;
-}
-
-#ifndef QT_MAC_USE_COCOA
-bool qt_mac_activate_action(MenuRef menu, uint command, QAction::ActionEvent action_e, bool by_accel)
-{
- //fire event
- QMacMenuAction *action = 0;
- if (GetMenuCommandProperty(menu, command, kMenuCreatorQt, kMenuPropertyQAction, sizeof(action), 0, &action) != noErr) {
- QMenuMergeList *list = 0;
- GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list);
- if (!list && qt_mac_current_menubar.qmenubar && qt_mac_current_menubar.qmenubar->isNativeMenuBar()) {
- MenuRef apple_menu = qt_mac_current_menubar.qmenubar->d_func()->mac_menubar->apple_menu;
- GetMenuItemProperty(apple_menu, 0, kMenuCreatorQt, kMenuPropertyMergeList, sizeof(list), 0, &list);
- if (list)
- menu = apple_menu;
- }
- if (list) {
- for(int i = 0; i < list->size(); ++i) {
- QMenuMergeItem item = list->at(i);
- if (item.command == command && item.action) {
- action = item.action;
- break;
- }
- }
- }
- if (!action)
- return false;
- }
-
- if (action_e == QAction::Trigger && by_accel && action->ignore_accel) //no, not a real accel (ie tab)
- return false;
-
- // Unhighlight the highlighted menu item before triggering the action to
- // prevent items from staying highlighted while a modal dialog is shown.
- // This also fixed the problem that parentless modal dialogs leave
- // the menu item highlighted (since the menu bar is cleared for these types of dialogs).
- if (action_e == QAction::Trigger)
- HiliteMenu(0);
-
- action->action->activate(action_e);
-
- //now walk up firing for each "caused" widget (like in the platform independent menu)
- QWidget *caused = 0;
- if (action_e == QAction::Hover && GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), 0, &caused) == noErr) {
- MenuRef caused_menu = 0;
- if (QMenu *qmenu2 = qobject_cast<QMenu*>(caused))
- caused_menu = qmenu2->macMenu();
- else if (QMenuBar *qmenubar2 = qobject_cast<QMenuBar*>(caused))
- caused_menu = qmenubar2->macMenu();
- else
- caused_menu = 0;
- while(caused_menu) {
- //fire
- QWidget *widget = 0;
- GetMenuItemProperty(caused_menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(widget), 0, &widget);
- if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
- action->action->showStatusText(widget);
- emit qmenu->hovered(action->action);
- } else if (QMenuBar *qmenubar = qobject_cast<QMenuBar*>(widget)) {
- action->action->showStatusText(widget);
- emit qmenubar->hovered(action->action);
- break; //nothing more..
- }
-
- //walk up
- if (GetMenuItemProperty(caused_menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget,
- sizeof(caused), 0, &caused) != noErr)
- break;
- if (QMenu *qmenu2 = qobject_cast<QMenu*>(caused))
- caused_menu = qmenu2->macMenu();
- else if (QMenuBar *qmenubar2 = qobject_cast<QMenuBar*>(caused))
- caused_menu = qmenubar2->macMenu();
- else
- caused_menu = 0;
- }
- }
- return true;
-}
-
-//lookup a QMacMenuAction in a menu
-static int qt_mac_menu_find_action(MenuRef menu, MenuCommand cmd)
-{
- MenuItemIndex ret_idx;
- MenuRef ret_menu;
- if (GetIndMenuItemWithCommandID(menu, cmd, 1, &ret_menu, &ret_idx) == noErr) {
- if (ret_menu == menu)
- return (int)ret_idx;
- }
- return -1;
-}
-static int qt_mac_menu_find_action(MenuRef menu, QMacMenuAction *action)
-{
- return qt_mac_menu_find_action(menu, action->command);
-}
-
-typedef QMultiHash<OSMenuRef, EventHandlerRef> EventHandlerHash;
-Q_GLOBAL_STATIC(EventHandlerHash, menu_eventHandlers_hash)
-
-static EventTypeSpec widget_in_menu_events[] = {
- { kEventClassMenu, kEventMenuMeasureItemWidth },
- { kEventClassMenu, kEventMenuMeasureItemHeight },
- { kEventClassMenu, kEventMenuDrawItem },
- { kEventClassMenu, kEventMenuCalculateSize }
-};
-
-static OSStatus qt_mac_widget_in_menu_eventHandler(EventHandlerCallRef er, EventRef event, void *)
-{
- UInt32 ekind = GetEventKind(event);
- UInt32 eclass = GetEventClass(event);
- OSStatus result = eventNotHandledErr;
- switch (eclass) {
- case kEventClassMenu:
- switch (ekind) {
- default:
- break;
- case kEventMenuMeasureItemWidth: {
- MenuItemIndex item;
- GetEventParameter(event, kEventParamMenuItemIndex, typeMenuItemIndex,
- 0, sizeof(item), 0, &item);
- OSMenuRef menu;
- GetEventParameter(event, kEventParamDirectObject, typeMenuRef, 0, sizeof(menu), 0, &menu);
- QWidget *widget;
- if (GetMenuItemProperty(menu, item, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
- sizeof(widget), 0, &widget) == noErr) {
- short width = short(widget->sizeHint().width());
- SetEventParameter(event, kEventParamMenuItemWidth, typeSInt16,
- sizeof(short), &width);
- result = noErr;
- }
- break; }
- case kEventMenuMeasureItemHeight: {
- MenuItemIndex item;
- GetEventParameter(event, kEventParamMenuItemIndex, typeMenuItemIndex,
- 0, sizeof(item), 0, &item);
- OSMenuRef menu;
- GetEventParameter(event, kEventParamDirectObject, typeMenuRef, 0, sizeof(menu), 0, &menu);
- QWidget *widget;
- if (GetMenuItemProperty(menu, item, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
- sizeof(widget), 0, &widget) == noErr && widget) {
- short height = short(widget->sizeHint().height());
- SetEventParameter(event, kEventParamMenuItemHeight, typeSInt16,
- sizeof(short), &height);
- result = noErr;
- }
- break; }
- case kEventMenuDrawItem:
- result = noErr;
- break;
- case kEventMenuCalculateSize: {
- result = CallNextEventHandler(er, event);
- if (result == noErr) {
- OSMenuRef menu;
- GetEventParameter(event, kEventParamDirectObject, typeMenuRef, 0, sizeof(menu), 0, &menu);
- HIViewRef content;
- HIMenuGetContentView(menu, kThemeMenuTypePullDown, &content);
- UInt16 count = CountMenuItems(menu);
- for (MenuItemIndex i = 1; i <= count; ++i) {
- QWidget *widget;
- if (GetMenuItemProperty(menu, i, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
- sizeof(widget), 0, &widget) == noErr && widget) {
- RgnHandle itemRgn = qt_mac_get_rgn();
- GetControlRegion(content, i, itemRgn);
-
- Rect bounds;
- GetRegionBounds( itemRgn, &bounds );
- qt_mac_dispose_rgn(itemRgn);
- widget->setGeometry(bounds.left, bounds.top,
- bounds.right - bounds.left, bounds.bottom - bounds.top);
- }
- }
- }
- break; }
- }
- }
- return result;
-}
-
-//handling of events for menurefs created by Qt..
-static EventTypeSpec menu_events[] = {
- { kEventClassCommand, kEventCommandProcess },
- { kEventClassMenu, kEventMenuTargetItem },
- { kEventClassMenu, kEventMenuOpening },
- { kEventClassMenu, kEventMenuClosed }
-};
-
-// Special case for kEventMenuMatchKey, see qt_mac_create_menu below.
-static EventTypeSpec menu_menu_events[] = {
- { kEventClassMenu, kEventMenuMatchKey }
-};
-
-OSStatus qt_mac_menu_event(EventHandlerCallRef er, EventRef event, void *)
-{
- QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-
- bool handled_event = true;
- UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
- switch(eclass) {
- case kEventClassCommand:
- if (ekind == kEventCommandProcess) {
- UInt32 context;
- GetEventParameter(event, kEventParamMenuContext, typeUInt32,
- 0, sizeof(context), 0, &context);
- HICommand cmd;
- GetEventParameter(event, kEventParamDirectObject, typeHICommand,
- 0, sizeof(cmd), 0, &cmd);
- if (!mac_keyboard_grabber && (context & kMenuContextKeyMatching)) {
- QMacMenuAction *action = 0;
- if (GetMenuCommandProperty(cmd.menu.menuRef, cmd.commandID, kMenuCreatorQt,
- kMenuPropertyQAction, sizeof(action), 0, &action) == noErr) {
- QWidget *widget = 0;
- if (qApp->activePopupWidget())
- widget = (qApp->activePopupWidget()->focusWidget() ?
- qApp->activePopupWidget()->focusWidget() : qApp->activePopupWidget());
- else if (QApplicationPrivate::focus_widget)
- widget = QApplicationPrivate::focus_widget;
- if (widget) {
- int key = action->action->shortcut();
- QKeyEvent accel_ev(QEvent::ShortcutOverride, (key & (~Qt::KeyboardModifierMask)),
- Qt::KeyboardModifiers(key & Qt::KeyboardModifierMask));
- accel_ev.ignore();
- qt_sendSpontaneousEvent(widget, &accel_ev);
- if (accel_ev.isAccepted()) {
- handled_event = false;
- break;
- }
- }
- }
- }
- handled_event = qt_mac_activate_action(cmd.menu.menuRef, cmd.commandID,
- QAction::Trigger, context & kMenuContextKeyMatching);
- }
- break;
- case kEventClassMenu: {
- MenuRef menu;
- GetEventParameter(event, kEventParamDirectObject, typeMenuRef, NULL, sizeof(menu), NULL, &menu);
- if (ekind == kEventMenuMatchKey) {
- // Don't activate any actions if we are showing a native modal dialog,
- // the key events should go to the dialog in this case.
- if (QApplicationPrivate::native_modal_dialog_active)
- return menuItemNotFoundErr;
-
- handled_event = false;
- } else if (ekind == kEventMenuTargetItem) {
- MenuCommand command;
- GetEventParameter(event, kEventParamMenuCommand, typeMenuCommand,
- 0, sizeof(command), 0, &command);
- handled_event = qt_mac_activate_action(menu, command, QAction::Hover, false);
- } else if (ekind == kEventMenuOpening || ekind == kEventMenuClosed) {
- qt_mac_menus_open_count += (ekind == kEventMenuOpening) ? 1 : -1;
- MenuRef mr;
- GetEventParameter(event, kEventParamDirectObject, typeMenuRef,
- 0, sizeof(mr), 0, &mr);
-
- QWidget *widget = 0;
- if (GetMenuItemProperty(mr, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(widget), 0, &widget) == noErr) {
- if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
- handled_event = true;
- if (ekind == kEventMenuOpening) {
- emit qmenu->aboutToShow();
-
- int merged = 0;
- const QMenuPrivate::QMacMenuPrivate *mac_menu = qmenu->d_func()->mac_menu;
- const int ActionItemsCount = mac_menu->actionItems.size();
- for(int i = 0; i < ActionItemsCount; ++i) {
- QMacMenuAction *action = mac_menu->actionItems.at(i);
- if (action->action->isSeparator()) {
- bool hide = false;
- if(!action->action->isVisible()) {
- hide = true;
- } else if (merged && merged == i) {
- hide = true;
- } else {
- for(int l = i+1; l < mac_menu->actionItems.size(); ++l) {
- QMacMenuAction *action = mac_menu->actionItems.at(l);
- if (action->merged) {
- hide = true;
- } else if (action->action->isSeparator()) {
- if (hide)
- break;
- } else if (!action->merged) {
- hide = false;
- break;
- }
- }
- }
-
- const int index = qt_mac_menu_find_action(mr, action);
- if (hide) {
- ++merged;
- ChangeMenuItemAttributes(mr, index, kMenuItemAttrHidden, 0);
- } else {
- ChangeMenuItemAttributes(mr, index, 0, kMenuItemAttrHidden);
- }
- } else if (action->merged) {
- ++merged;
- }
- }
- } else {
- emit qmenu->aboutToHide();
- }
- }
- }
- } else {
- handled_event = false;
- }
- break; }
- default:
- handled_event = false;
- break;
- }
- if (!handled_event) //let the event go through
- return CallNextEventHandler(er, event);
- return noErr; //we eat the event
-}
-static EventHandlerRef mac_menu_event_handler = 0;
-static EventHandlerUPP mac_menu_eventUPP = 0;
-static void qt_mac_cleanup_menu_event()
-{
- if (mac_menu_event_handler) {
- RemoveEventHandler(mac_menu_event_handler);
- mac_menu_event_handler = 0;
- }
- if (mac_menu_eventUPP) {
- DisposeEventHandlerUPP(mac_menu_eventUPP);
- mac_menu_eventUPP = 0;
- }
-}
-static inline void qt_mac_create_menu_event_handler()
-{
- if (!mac_menu_event_handler) {
- mac_menu_eventUPP = NewEventHandlerUPP(qt_mac_menu_event);
- InstallEventHandler(GetApplicationEventTarget(), mac_menu_eventUPP,
- GetEventTypeCount(menu_events), menu_events, 0,
- &mac_menu_event_handler);
- qAddPostRoutine(qt_mac_cleanup_menu_event);
- }
-}
-
-
-//enabling of commands
-static void qt_mac_command_set_enabled(MenuRef menu, UInt32 cmd, bool b)
-{
- if (cmd == kHICommandQuit)
- qt_mac_quit_menu_item_enabled = b;
-
- if (b) {
- EnableMenuCommand(menu, cmd);
- if (MenuRef dock_menu = GetApplicationDockTileMenu())
- EnableMenuCommand(dock_menu, cmd);
- } else {
- DisableMenuCommand(menu, cmd);
- if (MenuRef dock_menu = GetApplicationDockTileMenu())
- DisableMenuCommand(dock_menu, cmd);
- }
-}
-
-static bool qt_mac_auto_apple_menu(MenuCommand cmd)
-{
- return (cmd == kHICommandPreferences || cmd == kHICommandQuit);
-}
-
-static void qt_mac_get_accel(quint32 accel_key, quint32 *modif, quint32 *key) {
- if (modif) {
- *modif = constructModifierMask(accel_key);
- }
-
- accel_key &= ~(Qt::MODIFIER_MASK | Qt::UNICODE_ACCEL);
- if (key) {
- *key = 0;
- if (accel_key == Qt::Key_Return)
- *key = kMenuReturnGlyph;
- else if (accel_key == Qt::Key_Enter)
- *key = kMenuEnterGlyph;
- else if (accel_key == Qt::Key_Tab)
- *key = kMenuTabRightGlyph;
- else if (accel_key == Qt::Key_Backspace)
- *key = kMenuDeleteLeftGlyph;
- else if (accel_key == Qt::Key_Delete)
- *key = kMenuDeleteRightGlyph;
- else if (accel_key == Qt::Key_Escape)
- *key = kMenuEscapeGlyph;
- else if (accel_key == Qt::Key_PageUp)
- *key = kMenuPageUpGlyph;
- else if (accel_key == Qt::Key_PageDown)
- *key = kMenuPageDownGlyph;
- else if (accel_key == Qt::Key_Up)
- *key = kMenuUpArrowGlyph;
- else if (accel_key == Qt::Key_Down)
- *key = kMenuDownArrowGlyph;
- else if (accel_key == Qt::Key_Left)
- *key = kMenuLeftArrowGlyph;
- else if (accel_key == Qt::Key_Right)
- *key = kMenuRightArrowGlyph;
- else if (accel_key == Qt::Key_CapsLock)
- *key = kMenuCapsLockGlyph;
- else if (accel_key >= Qt::Key_F1 && accel_key <= Qt::Key_F15)
- *key = (accel_key - Qt::Key_F1) + kMenuF1Glyph;
- else if (accel_key == Qt::Key_Home)
- *key = kMenuNorthwestArrowGlyph;
- else if (accel_key == Qt::Key_End)
- *key = kMenuSoutheastArrowGlyph;
- }
-}
-#else // Cocoa
-static inline void syncNSMenuItemVisiblity(NSMenuItem *menuItem, bool actionVisibility)
-{
- [menuItem setHidden:NO];
- [menuItem setHidden:YES];
- [menuItem setHidden:!actionVisibility];
-}
-
-static inline void syncNSMenuItemEnabled(NSMenuItem *menuItem, bool enabled)
-{
- [menuItem setEnabled:NO];
- [menuItem setEnabled:YES];
- [menuItem setEnabled:enabled];
-}
-
-static inline void syncMenuBarItemsVisiblity(const QMenuBarPrivate::QMacMenuBarPrivate *mac_menubar)
-{
- const QList<QMacMenuAction *> &menubarActions = mac_menubar->actionItems;
- for (int i = 0; i < menubarActions.size(); ++i) {
- const QMacMenuAction *action = menubarActions.at(i);
- syncNSMenuItemVisiblity(action->menuItem, actualMenuItemVisibility(mac_menubar, action));
- }
-}
-
-static inline QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *getMenuLoader()
-{
- return [NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
-}
-
-static NSMenuItem *createNSMenuItem(const QString &title)
-{
- NSMenuItem *item = [[NSMenuItem alloc]
- initWithTitle:qt_mac_QStringToNSString(title)
- action:@selector(qtDispatcherToQAction:) keyEquivalent:@""];
- [item setTarget:nil];
- return item;
-}
-#endif
-
-
-
-// helper that recurses into a menu structure and en/dis-ables them
-void qt_mac_set_modal_state_helper_recursive(OSMenuRef menu, OSMenuRef merge, bool on)
-{
-#ifndef QT_MAC_USE_COCOA
- for (int i = 0; i < CountMenuItems(menu); i++) {
- OSMenuRef submenu;
- GetMenuItemHierarchicalMenu(menu, i+1, &submenu);
- if (submenu != merge) {
- if (submenu)
- qt_mac_set_modal_state_helper_recursive(submenu, merge, on);
- if (on)
- DisableMenuItem(submenu, 0);
- else
- EnableMenuItem(submenu, 0);
- }
- }
-#else
- bool modalWindowOnScreen = qApp->activeModalWidget() != 0;
- for (NSMenuItem *item in [menu itemArray]) {
- OSMenuRef submenu = [item submenu];
- if (submenu != merge) {
- if (submenu)
- qt_mac_set_modal_state_helper_recursive(submenu, merge, on);
- if (!on) {
- // The item should follow what the QAction has.
- if ([item tag]) {
- QAction *action = reinterpret_cast<QAction *>([item tag]);
- syncNSMenuItemEnabled(item, action->isEnabled());
- } else {
- syncNSMenuItemEnabled(item, YES);
- }
- // We sneak in some extra code here to handle a menu problem:
- // If there is no window on screen, we cannot set 'nil' as
- // menu item target, because then cocoa will disable the item
- // (guess it assumes that there will be no first responder to
- // catch the trigger anyway?) OTOH, If we have a modal window,
- // then setting the menu loader as target will make cocoa not
- // deliver the trigger because the loader is then seen as modally
- // shaddowed). So either way there are shortcomings. Instead, we
- // decide the target as late as possible:
- [item setTarget:modalWindowOnScreen ? nil : getMenuLoader()];
- } else {
- syncNSMenuItemEnabled(item, NO);
- }
- }
- }
-#endif
-}
-
-//toggling of modal state
-static void qt_mac_set_modal_state(OSMenuRef menu, bool on)
-{
-#ifndef QT_MAC_USE_COCOA
- OSMenuRef merge = 0;
- GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
- sizeof(merge), 0, &merge);
-
- qt_mac_set_modal_state_helper_recursive(menu, merge, on);
-
- UInt32 commands[] = { kHICommandQuit, kHICommandPreferences, kHICommandAbout, kHICommandAboutQt, 0 };
- for(int c = 0; commands[c]; c++) {
- bool enabled = !on;
- if (enabled) {
- QMacMenuAction *action = 0;
- GetMenuCommandProperty(menu, commands[c], kMenuCreatorQt, kMenuPropertyQAction,
- sizeof(action), 0, &action);
- if (!action && merge) {
- GetMenuCommandProperty(merge, commands[c], kMenuCreatorQt, kMenuPropertyQAction,
- sizeof(action), 0, &action);
- if (!action) {
- QMenuMergeList *list = 0;
- GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list);
- for(int i = 0; list && i < list->size(); ++i) {
- QMenuMergeItem item = list->at(i);
- if (item.command == commands[c] && item.action) {
- action = item.action;
- break;
- }
- }
- }
- }
-
- if (!action) {
- if (commands[c] != kHICommandQuit)
- enabled = false;
- } else {
- enabled = action->action ? action->action->isEnabled() : 0;
- }
- }
- qt_mac_command_set_enabled(menu, commands[c], enabled);
- }
-#else
- OSMenuRef merge = QMenuPrivate::mergeMenuHash.value(menu);
- qt_mac_set_modal_state_helper_recursive(menu, merge, on);
- // I'm ignoring the special items now, since they should get handled via a syncAction()
-#endif
-}
-
-bool qt_mac_menubar_is_open()
-{
- return qt_mac_menus_open_count > 0;
-}
-
-QMacMenuAction::~QMacMenuAction()
-{
-#ifdef QT_MAC_USE_COCOA
- [menu release];
- // Update the menu item if this action still owns it. For some items
- // (like 'Quit') ownership will be transferred between all menu bars...
- if (action && action.data() == reinterpret_cast<QAction *>([menuItem tag])) {
- QAction::MenuRole role = action->menuRole();
- // Check if the item is owned by Qt, and should be hidden to keep it from causing
- // problems. Do it for everything but the quit menu item since that should always
- // be visible.
- if (role > QAction::ApplicationSpecificRole && role < QAction::QuitRole) {
- [menuItem setHidden:YES];
- } else if (role == QAction::TextHeuristicRole
- && menuItem != [getMenuLoader() quitMenuItem]) {
- [menuItem setHidden:YES];
- }
- [menuItem setTag:nil];
- }
- [menuItem release];
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-static MenuCommand qt_mac_menu_merge_action(MenuRef merge, QMacMenuAction *action)
-#else
-static NSMenuItem *qt_mac_menu_merge_action(OSMenuRef merge, QMacMenuAction *action)
-#endif
-{
- if (qt_mac_no_menubar_merge || action->action->menu() || action->action->isSeparator()
- || action->action->menuRole() == QAction::NoRole)
- return 0;
-
- QString t = qt_mac_removeMnemonics(action->action->text().toLower());
- int st = t.lastIndexOf(QLatin1Char('\t'));
- if (st != -1)
- t.remove(st, t.length()-st);
- t.replace(QRegExp(QString::fromLatin1("\\.*$")), QLatin1String("")); //no ellipses
- //now the fun part
-#ifndef QT_MAC_USE_COCOA
- MenuCommand ret = 0;
-#else
- NSMenuItem *ret = 0;
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-#endif
- switch (action->action->menuRole()) {
- case QAction::NoRole:
- ret = 0;
- break;
- case QAction::ApplicationSpecificRole:
-#ifndef QT_MAC_USE_COCOA
- {
- QMenuMergeList *list = 0;
- if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list) == noErr && list) {
- MenuCommand lastCustom = kHICommandCustomMerge;
- for(int i = 0; i < list->size(); ++i) {
- QMenuMergeItem item = list->at(i);
- if (item.command == lastCustom)
- ++lastCustom;
- }
- ret = lastCustom;
- } else {
- // The list hasn't been created, so, must be the first one.
- ret = kHICommandCustomMerge;
- }
- }
-#else
- ret = [loader appSpecificMenuItem];
-#endif
- break;
- case QAction::AboutRole:
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandAbout;
-#else
- ret = [loader aboutMenuItem];
-#endif
- break;
- case QAction::AboutQtRole:
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandAboutQt;
-#else
- ret = [loader aboutQtMenuItem];
-#endif
- break;
- case QAction::QuitRole:
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandQuit;
-#else
- ret = [loader quitMenuItem];
-#endif
- break;
- case QAction::PreferencesRole:
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandPreferences;
-#else
- ret = [loader preferencesMenuItem];
-#endif
- break;
- case QAction::TextHeuristicRole: {
- QString aboutString = QMenuBar::tr("About").toLower();
- if (t.startsWith(aboutString) || t.endsWith(aboutString)) {
- if (t.indexOf(QRegExp(QString::fromLatin1("qt$"), Qt::CaseInsensitive)) == -1) {
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandAbout;
-#else
- ret = [loader aboutMenuItem];
-#endif
- } else {
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandAboutQt;
-#else
- ret = [loader aboutQtMenuItem];
-#endif
- }
- } else if (t.startsWith(QMenuBar::tr("Config").toLower())
- || t.startsWith(QMenuBar::tr("Preference").toLower())
- || t.startsWith(QMenuBar::tr("Options").toLower())
- || t.startsWith(QMenuBar::tr("Setting").toLower())
- || t.startsWith(QMenuBar::tr("Setup").toLower())) {
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandPreferences;
-#else
- ret = [loader preferencesMenuItem];
-#endif
- } else if (t.startsWith(QMenuBar::tr("Quit").toLower())
- || t.startsWith(QMenuBar::tr("Exit").toLower())) {
-#ifndef QT_MAC_USE_COCOA
- ret = kHICommandQuit;
-#else
- ret = [loader quitMenuItem];
-#endif
- }
- }
- break;
- }
-
-#ifndef QT_MAC_USE_COCOA
- QMenuMergeList *list = 0;
- if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list) == noErr && list) {
- for(int i = 0; i < list->size(); ++i) {
- QMenuMergeItem item = list->at(i);
- if (item.command == ret && item.action)
- return 0;
- }
- }
-
- QAction *cmd_action = 0;
- if (GetMenuCommandProperty(merge, ret, kMenuCreatorQt, kMenuPropertyQAction,
- sizeof(cmd_action), 0, &cmd_action) == noErr && cmd_action)
- return 0; //already taken
-#else
- if (QMenuMergeList *list = QMenuPrivate::mergeMenuItemsHash.value(merge)) {
- for(int i = 0; i < list->size(); ++i) {
- const QMenuMergeItem &item = list->at(i);
- if (item.menuItem == ret && item.action)
- return 0;
- }
- }
-
-#endif
- return ret;
-}
-
-static QString qt_mac_menu_merge_text(QMacMenuAction *action)
-{
- QString ret;
- extern QString qt_mac_applicationmenu_string(int type);
-#ifdef QT_MAC_USE_COCOA
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-#endif
- if (action->action->menuRole() == QAction::ApplicationSpecificRole)
- ret = action->action->text();
-#ifndef QT_MAC_USE_COCOA
- else if (action->command == kHICommandAbout)
- ret = qt_mac_applicationmenu_string(6).arg(qAppName());
- else if (action->command == kHICommandAboutQt)
- ret = QMenuBar::tr("About Qt");
- else if (action->command == kHICommandPreferences)
- ret = qt_mac_applicationmenu_string(4);
- else if (action->command == kHICommandQuit)
- ret = qt_mac_applicationmenu_string(5).arg(qAppName());
-#else
- else if (action->menuItem == [loader aboutMenuItem]) {
- ret = qt_mac_applicationmenu_string(6).arg(qAppName());
- } else if (action->menuItem == [loader aboutQtMenuItem]) {
- if (action->action->text() == QString("About Qt"))
- ret = QMenuBar::tr("About Qt");
- else
- ret = action->action->text();
- } else if (action->menuItem == [loader preferencesMenuItem]) {
- ret = qt_mac_applicationmenu_string(4);
- } else if (action->menuItem == [loader quitMenuItem]) {
- ret = qt_mac_applicationmenu_string(5).arg(qAppName());
- }
-#endif
- return ret;
-}
-
-static QKeySequence qt_mac_menu_merge_accel(QMacMenuAction *action)
-{
- QKeySequence ret;
-#ifdef QT_MAC_USE_COCOA
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-#endif
- if (action->action->menuRole() == QAction::ApplicationSpecificRole)
- ret = action->action->shortcut();
-#ifndef QT_MAC_USE_COCOA
- else if (action->command == kHICommandPreferences)
- ret = QKeySequence(QKeySequence::Preferences);
- else if (action->command == kHICommandQuit)
- ret = QKeySequence(QKeySequence::Quit);
-#else
- else if (action->menuItem == [loader preferencesMenuItem])
- ret = QKeySequence(QKeySequence::Preferences);
- else if (action->menuItem == [loader quitMenuItem])
- ret = QKeySequence(QKeySequence::Quit);
-#endif
- return ret;
-}
-
-void Q_GUI_EXPORT qt_mac_set_menubar_icons(bool b)
-{ QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus, !b); }
-void Q_GUI_EXPORT qt_mac_set_native_menubar(bool b)
-{ QApplication::instance()->setAttribute(Qt::AA_DontUseNativeMenuBar, !b); }
-void Q_GUI_EXPORT qt_mac_set_menubar_merge(bool b) { qt_mac_no_menubar_merge = !b; }
-
-/*****************************************************************************
- QMenu bindings
- *****************************************************************************/
-QMenuPrivate::QMacMenuPrivate::QMacMenuPrivate() : menu(0)
-{
-}
-
-QMenuPrivate::QMacMenuPrivate::~QMacMenuPrivate()
-{
-#ifndef QT_MAC_USE_COCOA
- for(QList<QMacMenuAction*>::Iterator it = actionItems.begin(); it != actionItems.end(); ++it) {
- QMacMenuAction *action = (*it);
- RemoveMenuCommandProperty(action->menu, action->command, kMenuCreatorQt, kMenuPropertyQAction);
- if (action->merged) {
- QMenuMergeList *list = 0;
- GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list);
- for(int i = 0; list && i < list->size(); ) {
- QMenuMergeItem item = list->at(i);
- if (item.action == action)
- list->removeAt(i);
- else
- ++i;
- }
- }
- delete action;
- }
- if (menu) {
- EventHandlerHash::iterator it = menu_eventHandlers_hash()->find(menu);
- while (it != menu_eventHandlers_hash()->end() && it.key() == menu) {
- RemoveEventHandler(it.value());
- ++it;
- }
- menu_eventHandlers_hash()->remove(menu);
- ReleaseMenu(menu);
- }
-#else
- QMacCocoaAutoReleasePool pool;
- while (actionItems.size()) {
- QMacMenuAction *action = actionItems.takeFirst();
- if (QMenuMergeList *list = mergeMenuItemsHash.value(action->menu)) {
- int i = 0;
- while (i < list->size()) {
- const QMenuMergeItem &item = list->at(i);
- if (item.action == action)
- list->removeAt(i);
- else
- ++i;
- }
- }
- delete action;
- }
- mergeMenuHash.remove(menu);
- mergeMenuItemsHash.remove(menu);
- [menu release];
-#endif
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::addAction(QAction *a, QMacMenuAction *before, QMenuPrivate *qmenu)
-{
- QMacMenuAction *action = new QMacMenuAction;
- action->action = a;
- action->ignore_accel = 0;
- action->merged = 0;
- action->menu = 0;
-#ifndef QT_MAC_USE_COCOA
- action->command = qt_mac_menu_static_cmd_id++;
-#endif
- addAction(action, before, qmenu);
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::addAction(QMacMenuAction *action, QMacMenuAction *before, QMenuPrivate *qmenu)
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- Q_UNUSED(qmenu);
-#endif
- if (!action)
- return;
- int before_index = actionItems.indexOf(before);
- if (before_index < 0) {
- before = 0;
- before_index = actionItems.size();
- }
- actionItems.insert(before_index, action);
-
-#ifndef QT_MAC_USE_COCOA
- int index = qt_mac_menu_find_action(menu, action);
-#else
- [menu retain];
- [action->menu release];
-#endif
- action->menu = menu;
-
- /* When the action is considered a mergable action it
- will stay that way, until removed.. */
- if (!qt_mac_no_menubar_merge) {
-#ifndef QT_MAC_USE_COCOA
- MenuRef merge = 0;
- GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
- sizeof(merge), 0, &merge);
-#else
- OSMenuRef merge = QMenuPrivate::mergeMenuHash.value(menu);
-#endif
- if (merge) {
-#ifndef QT_MAC_USE_COCOA
- if (MenuCommand cmd = qt_mac_menu_merge_action(merge, action)) {
- action->merged = 1;
- action->menu = merge;
- action->command = cmd;
- if (qt_mac_auto_apple_menu(cmd))
- index = 0; //no need
-
- QMenuMergeList *list = 0;
- if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list) != noErr || !list) {
- list = new QMenuMergeList;
- SetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), &list);
- }
- list->append(QMenuMergeItem(cmd, action));
- }
-#else
- if (NSMenuItem *cmd = qt_mac_menu_merge_action(merge, action)) {
- action->merged = 1;
- [merge retain];
- [action->menu release];
- action->menu = merge;
- [cmd retain];
- [cmd setAction:@selector(qtDispatcherToQAction:)];
- [cmd setTarget:nil];
- [action->menuItem release];
- action->menuItem = cmd;
- QMenuMergeList *list = QMenuPrivate::mergeMenuItemsHash.value(merge);
- if (!list) {
- list = new QMenuMergeList;
- QMenuPrivate::mergeMenuItemsHash.insert(merge, list);
- }
- list->append(QMenuMergeItem(cmd, action));
- }
-#endif
- }
- }
-
-#ifdef QT_MAC_USE_COCOA
- NSMenuItem *newItem = action->menuItem;
-#endif
- if (
-#ifndef QT_MAC_USE_COCOA
- index == -1
-#else
- newItem == 0
-#endif
- ) {
-#ifndef QT_MAC_USE_COCOA
- index = before_index;
- MenuItemAttributes attr = kMenuItemAttrAutoRepeat;
-#else
- newItem = createNSMenuItem(action->action->text());
- action->menuItem = newItem;
-#endif
- if (before) {
-#ifndef QT_MAC_USE_COCOA
- InsertMenuItemTextWithCFString(action->menu, 0, qMax(before_index, 0), attr, action->command);
-#else
- [menu insertItem:newItem atIndex:qMax(before_index, 0)];
-#endif
- } else {
-#ifndef QT_MAC_USE_COCOA
- // Append the menu item to the menu. If it is a kHICommandAbout or a kHICommandAboutQt append
- // a separator also (to get a separator above "Preferences"), but make sure that we don't
- // add separators between two "about" items.
-
- // Build a set of all commands that could possibly be before the separator.
- QSet<MenuCommand> mergedItems;
- mergedItems.insert(kHICommandAbout);
- mergedItems.insert(kHICommandAboutQt);
- mergedItems.insert(kHICommandCustomMerge);
-
- QMenuMergeList *list = 0;
- if (GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list) == noErr && list) {
- for (int i = 0; i < list->size(); ++i) {
- MenuCommand command = list->at(i).command;
- if (command > kHICommandCustomMerge) {
- mergedItems.insert(command);
- }
- }
- }
-
- const int itemCount = CountMenuItems(action->menu);
- MenuItemAttributes testattr;
- GetMenuItemAttributes(action->menu, itemCount , &testattr);
- if (mergedItems.contains(action->command)
- && (testattr & kMenuItemAttrSeparator)) {
- InsertMenuItemTextWithCFString(action->menu, 0, qMax(itemCount - 1, 0), attr, action->command);
- index = itemCount;
- } else {
- MenuItemIndex tmpIndex;
- AppendMenuItemTextWithCFString(action->menu, 0, attr, action->command, &tmpIndex);
- index = tmpIndex;
- if (mergedItems.contains(action->command))
- AppendMenuItemTextWithCFString(action->menu, 0, kMenuItemAttrSeparator, 0, &tmpIndex);
- }
-#else
- [menu addItem:newItem];
-#endif
- }
-
- QWidget *widget = qmenu ? qmenu->widgetItems.value(action->action) : 0;
- if (widget) {
-#ifndef QT_MAC_USE_COCOA
- ChangeMenuAttributes(action->menu, kMenuAttrDoNotCacheImage, 0);
- attr = kMenuItemAttrCustomDraw;
- SetMenuItemProperty(action->menu, index, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
- sizeof(QWidget *), &widget);
- HIViewRef content;
- HIMenuGetContentView(action->menu, kThemeMenuTypePullDown, &content);
-
- EventHandlerRef eventHandlerRef;
- InstallMenuEventHandler(action->menu, qt_mac_widget_in_menu_eventHandler,
- GetEventTypeCount(widget_in_menu_events),
- widget_in_menu_events, 0, &eventHandlerRef);
- menu_eventHandlers_hash()->insert(action->menu, eventHandlerRef);
-
- QWidget *menuWidget = 0;
- GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyWidgetMenu,
- sizeof(menuWidget), 0, &menuWidget);
- if(!menuWidget) {
- menuWidget = new QMacNativeWidget(content);
- SetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyWidgetMenu,
- sizeof(menuWidget), &menuWidget);
- menuWidget->show();
- }
- widget->setParent(menuWidget);
-#else
- QMacNativeWidget *container = new QMacNativeWidget(0);
- container->resize(widget->sizeHint());
- widget->setAttribute(Qt::WA_LayoutUsesWidgetRect);
- widget->setParent(container);
-
- NSView *containerView = qt_mac_nativeview_for(container);
- [containerView setAutoresizesSubviews:YES];
- [containerView setAutoresizingMask:NSViewWidthSizable];
- [qt_mac_nativeview_for(widget) setAutoresizingMask:NSViewWidthSizable];
-
- [newItem setView:containerView];
- container->show();
-#endif
- widget->show();
- }
-
- } else {
-#ifndef QT_MAC_USE_COCOA
- qt_mac_command_set_enabled(action->menu, action->command, !QApplicationPrivate::modalState());
-#else
- [newItem setEnabled:!QApplicationPrivate::modalState()];
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- SetMenuCommandProperty(action->menu, action->command, kMenuCreatorQt, kMenuPropertyQAction,
- sizeof(action), &action);
-#else
- [newItem setTag:long(static_cast<QAction *>(action->action))];
-#endif
- syncAction(action);
-}
-
-// return an autoreleased string given a QKeySequence (currently only looks at the first one).
-NSString *keySequenceToKeyEqivalent(const QKeySequence &accel)
-{
- quint32 accel_key = (accel[0] & ~(Qt::MODIFIER_MASK | Qt::UNICODE_ACCEL));
- extern QChar qtKey2CocoaKey(Qt::Key key);
- QChar cocoa_key = qtKey2CocoaKey(Qt::Key(accel_key));
- if (cocoa_key.isNull())
- cocoa_key = QChar(accel_key).toLower().unicode();
- return [NSString stringWithCharacters:&cocoa_key.unicode() length:1];
-}
-
-// return the cocoa modifier mask for the QKeySequence (currently only looks at the first one).
-NSUInteger keySequenceModifierMask(const QKeySequence &accel)
-{
- return constructModifierMask(accel[0]);
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::syncAction(QMacMenuAction *action)
-{
- if (!action)
- return;
-
-#ifndef QT_MAC_USE_COCOA
- const int index = qt_mac_menu_find_action(action->menu, action);
- if (index == -1)
- return;
-#else
- NSMenuItem *item = action->menuItem;
- if (!item)
- return;
-#endif
-
-#ifndef QT_MAC_USE_COCOA
- if (!action->action->isVisible()) {
- ChangeMenuItemAttributes(action->menu, index, kMenuItemAttrHidden, 0);
- return;
- }
- ChangeMenuItemAttributes(action->menu, index, 0, kMenuItemAttrHidden);
-#else
- QMacCocoaAutoReleasePool pool;
- NSMenu *menu = [item menu];
- bool actionVisible = action->action->isVisible();
- [item setHidden:!actionVisible];
- if (!actionVisible)
- return;
-#endif
-
-#ifndef QT_MAC_USE_COCOA
- if (action->action->isSeparator()) {
- ChangeMenuItemAttributes(action->menu, index, kMenuItemAttrSeparator, 0);
- return;
- }
- ChangeMenuItemAttributes(action->menu, index, 0, kMenuItemAttrSeparator);
-#else
- int itemIndex = [menu indexOfItem:item];
- Q_ASSERT(itemIndex != -1);
- if (action->action->isSeparator()) {
- action->menuItem = [NSMenuItem separatorItem];
- [action->menuItem retain];
- [menu insertItem: action->menuItem atIndex:itemIndex];
- [menu removeItem:item];
- [item release];
- item = action->menuItem;
- return;
- } else if ([item isSeparatorItem]) {
- // I'm no longer a separator...
- action->menuItem = createNSMenuItem(action->action->text());
- [menu insertItem:action->menuItem atIndex:itemIndex];
- [menu removeItem:item];
- [item release];
- item = action->menuItem;
- }
-#endif
-
- //find text (and accel)
- action->ignore_accel = 0;
- QString text = action->action->text();
- QKeySequence accel = action->action->shortcut();
- {
- int st = text.lastIndexOf(QLatin1Char('\t'));
- if (st != -1) {
- action->ignore_accel = 1;
- accel = QKeySequence(text.right(text.length()-(st+1)));
- text.remove(st, text.length()-st);
- }
- }
- {
- QString cmd_text = qt_mac_menu_merge_text(action);
- if (!cmd_text.isEmpty()) {
- text = cmd_text;
- accel = qt_mac_menu_merge_accel(action);
- }
- }
- // Show multiple key sequences as part of the menu text.
- if (accel.count() > 1)
- text += QLatin1String(" (") + accel.toString(QKeySequence::NativeText) + QLatin1String(")");
-
- QString finalString = qt_mac_removeMnemonics(text);
-
-#ifndef QT_MAC_USE_COCOA
- MenuItemDataRec data;
- memset(&data, '\0', sizeof(data));
-
- //Carbon text
- data.whichData |= kMenuItemDataCFString;
- QCFString cfstring(finalString); // Hold the reference to the end of the function.
- data.cfText = cfstring;
-
- // Carbon enabled
- data.whichData |= kMenuItemDataEnabled;
- data.enabled = action->action->isEnabled();
- // Carbon icon
- data.whichData |= kMenuItemDataIconHandle;
- if (!action->action->icon().isNull()
- && action->action->isIconVisibleInMenu()) {
- data.iconType = kMenuIconRefType;
- data.iconHandle = (Handle)qt_mac_create_iconref(action->action->icon().pixmap(16, QIcon::Normal));
- } else {
- data.iconType = kMenuNoIcon;
- }
- if (action->action->font().resolve()) { // Carbon font
- if (action->action->font().bold())
- data.style |= bold;
- if (action->action->font().underline())
- data.style |= underline;
- if (action->action->font().italic())
- data.style |= italic;
- if (data.style)
- data.whichData |= kMenuItemDataStyle;
- data.whichData |= kMenuItemDataFontID;
- data.fontID = action->action->font().macFontID();
- }
-#else
- // Cocoa Font and title
- if (action->action->font().resolve()) {
- const QFont &actionFont = action->action->font();
- NSFont *customMenuFont = [NSFont fontWithName:qt_mac_QStringToNSString(actionFont.family())
- size:actionFont.pointSize()];
- NSArray *keys = [NSArray arrayWithObjects:NSFontAttributeName, nil];
- NSArray *objects = [NSArray arrayWithObjects:customMenuFont, nil];
- NSDictionary *attributes = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
- NSAttributedString *str = [[[NSAttributedString alloc] initWithString:qt_mac_QStringToNSString(finalString)
- attributes:attributes] autorelease];
- [item setAttributedTitle: str];
- } else {
- [item setTitle: qt_mac_QStringToNSString(finalString)];
- }
-
- if (action->action->menuRole() == QAction::AboutRole || action->action->menuRole() == QAction::QuitRole)
- [item setTitle:qt_mac_QStringToNSString(text)];
- else
- [item setTitle:qt_mac_QStringToNSString(qt_mac_removeMnemonics(text))];
-
- // Cocoa Enabled
- [item setEnabled: action->action->isEnabled()];
-
- // Cocoa icon
- NSImage *nsimage = 0;
- if (!action->action->icon().isNull() && action->action->isIconVisibleInMenu()) {
- nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(action->action->icon().pixmap(16, QIcon::Normal)));
- }
- [item setImage:nsimage];
- [nsimage release];
-#endif
-
- if (action->action->menu()) { //submenu
-#ifndef QT_MAC_USE_COCOA
- data.whichData |= kMenuItemDataSubmenuHandle;
- data.submenuHandle = action->action->menu()->macMenu();
- QWidget *caused = 0;
- GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(caused), 0, &caused);
- SetMenuItemProperty(data.submenuHandle, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), &caused);
-#else
- NSMenu *subMenu = static_cast<NSMenu *>(action->action->menu()->macMenu());
- if ([subMenu supermenu] && [subMenu supermenu] != [item menu]) {
- // The menu is already a sub-menu of another one. Cocoa will throw an exception,
- // in such cases. For the time being, a new QMenu with same set of actions is the
- // only workaround.
- action->action->setEnabled(false);
- } else {
- [item setSubmenu:subMenu];
- }
-#endif
- } else { //respect some other items
-#ifndef QT_MAC_USE_COCOA
- //shortcuts (say we are setting them all so that we can also clear them).
- data.whichData |= kMenuItemDataCmdKey;
- data.whichData |= kMenuItemDataCmdKeyModifiers;
- data.whichData |= kMenuItemDataCmdKeyGlyph;
- if (accel.count() == 1) {
- qt_mac_get_accel(accel[0], (quint32*)&data.cmdKeyModifiers, (quint32*)&data.cmdKeyGlyph);
- if (data.cmdKeyGlyph == 0)
- data.cmdKey = (UniChar)accel[0];
- }
-#else
- [item setSubmenu:0];
- // No key equivalent set for multiple key QKeySequence.
- if (accel.count() == 1) {
- [item setKeyEquivalent:keySequenceToKeyEqivalent(accel)];
- [item setKeyEquivalentModifierMask:keySequenceModifierMask(accel)];
- } else {
- [item setKeyEquivalent:@""];
- [item setKeyEquivalentModifierMask:NSCommandKeyMask];
- }
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- //mark glyph
- data.whichData |= kMenuItemDataMark;
- if (action->action->isChecked()) {
-#if 0
- if (action->action->actionGroup() &&
- action->action->actionGroup()->isExclusive())
- data.mark = diamondMark;
- else
-#endif
- data.mark = checkMark;
- } else {
- data.mark = noMark;
- }
-
- //actually set it
- SetMenuItemData(action->menu, action->command, true, &data);
-
- // Free up memory
- if (data.iconHandle)
- ReleaseIconRef(IconRef(data.iconHandle));
-#else
- //mark glyph
- [item setState:action->action->isChecked() ? NSOnState : NSOffState];
-#endif
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::removeAction(QMacMenuAction *action)
-{
- if (!action)
- return;
-#ifndef QT_MAC_USE_COCOA
- if (action->command == kHICommandQuit || action->command == kHICommandPreferences)
- qt_mac_command_set_enabled(action->menu, action->command, false);
- else
- DeleteMenuItem(action->menu, qt_mac_menu_find_action(action->menu, action));
-#else
- QMacCocoaAutoReleasePool pool;
- if (action->merged) {
- if (reinterpret_cast<QAction *>([action->menuItem tag]) == action->action) {
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
- [action->menuItem setEnabled:false];
- if (action->menuItem != [loader quitMenuItem]
- && action->menuItem != [loader preferencesMenuItem]) {
- [[action->menuItem menu] removeItem:action->menuItem];
- }
- }
- } else {
- [[action->menuItem menu] removeItem:action->menuItem];
- }
-#endif
- actionItems.removeAll(action);
-}
-
-OSMenuRef
-QMenuPrivate::macMenu(OSMenuRef merge)
-{
- Q_UNUSED(merge);
- Q_Q(QMenu);
- if (mac_menu && mac_menu->menu)
- return mac_menu->menu;
- if (!mac_menu)
- mac_menu = new QMacMenuPrivate;
- mac_menu->menu = qt_mac_create_menu(q);
- if (merge) {
-#ifndef QT_MAC_USE_COCOA
- SetMenuItemProperty(mac_menu->menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu, sizeof(merge), &merge);
-#else
- mergeMenuHash.insert(mac_menu->menu, merge);
-#endif
- }
- QList<QAction*> items = q->actions();
- for(int i = 0; i < items.count(); i++)
- mac_menu->addAction(items[i], 0, this);
- syncSeparatorsCollapsible(collapsibleSeparators);
- return mac_menu->menu;
-}
-
-/*!
- \internal
-*/
-void
-QMenuPrivate::syncSeparatorsCollapsible(bool collapse)
-{
-#ifndef QT_MAC_USE_COCOA
- if (collapse)
- ChangeMenuAttributes(mac_menu->menu, kMenuAttrCondenseSeparators, 0);
- else
- ChangeMenuAttributes(mac_menu->menu, 0, kMenuAttrCondenseSeparators);
-#else
- qt_mac_menu_collapseSeparators(mac_menu->menu, collapse);
-#endif
-}
-
-
-
-/*!
- \internal
-*/
-void QMenuPrivate::setMacMenuEnabled(bool enable)
-{
- if (!macMenu(0))
- return;
-
- QMacCocoaAutoReleasePool pool;
- if (enable) {
- for (int i = 0; i < mac_menu->actionItems.count(); ++i) {
- QMacMenuAction *menuItem = mac_menu->actionItems.at(i);
- if (menuItem && menuItem->action && menuItem->action->isEnabled()) {
-#ifndef QT_MAC_USE_COCOA
- // Only enable those items which contains an enabled QAction.
- // i == 0 -> the menu itself, hence i + 1 for items.
- EnableMenuItem(mac_menu->menu, i + 1);
-#else
- [menuItem->menuItem setEnabled:true];
-#endif
- }
- }
- } else {
-#ifndef QT_MAC_USE_COCOA
- DisableAllMenuItems(mac_menu->menu);
-#else
- NSMenu *menu = mac_menu->menu;
- for (NSMenuItem *item in [menu itemArray]) {
- [item setEnabled:false];
- }
-#endif
- }
-}
-
-/*!
- \internal
-
- This function will return the OSMenuRef used to create the native menu bar
- bindings.
-
- If Qt is built against Carbon, the OSMenuRef is a MenuRef that can be used
- with Carbon's Menu Manager API.
-
- If Qt is built against Cocoa, the OSMenuRef is a NSMenu pointer.
-
- \warning This function is not portable.
-
- \sa QMenuBar::macMenu()
-*/
-OSMenuRef QMenu::macMenu(OSMenuRef merge) { return d_func()->macMenu(merge); }
-
-/*****************************************************************************
- QMenuBar bindings
- *****************************************************************************/
-typedef QHash<QWidget *, QMenuBar *> MenuBarHash;
-Q_GLOBAL_STATIC(MenuBarHash, menubars)
-static QMenuBar *fallback = 0;
-QMenuBarPrivate::QMacMenuBarPrivate::QMacMenuBarPrivate() : menu(0), apple_menu(0)
-{
-}
-
-QMenuBarPrivate::QMacMenuBarPrivate::~QMacMenuBarPrivate()
-{
- for(QList<QMacMenuAction*>::Iterator it = actionItems.begin(); it != actionItems.end(); ++it)
- delete (*it);
-#ifndef QT_MAC_USE_COCOA
- if (apple_menu) {
- QMenuMergeList *list = 0;
- GetMenuItemProperty(apple_menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list);
- if (list) {
- RemoveMenuItemProperty(apple_menu, 0, kMenuCreatorQt, kMenuPropertyMergeList);
- delete list;
- }
- ReleaseMenu(apple_menu);
- }
- if (menu)
- ReleaseMenu(menu);
-#else
- [apple_menu release];
- [menu release];
-#endif
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::addAction(QAction *a, QMacMenuAction *before)
-{
- if (a->isSeparator() || !menu)
- return;
- QMacMenuAction *action = new QMacMenuAction;
- action->action = a;
- action->ignore_accel = 1;
-#ifndef QT_MAC_USE_COCOA
- action->command = qt_mac_menu_static_cmd_id++;
-#endif
- addAction(action, before);
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::addAction(QMacMenuAction *action, QMacMenuAction *before)
-{
- if (!action || !menu)
- return;
-
- int before_index = actionItems.indexOf(before);
- if (before_index < 0) {
- before = 0;
- before_index = actionItems.size();
- }
- actionItems.insert(before_index, action);
-
- MenuItemIndex index = actionItems.size()-1;
-
- action->menu = menu;
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- [action->menu retain];
- NSMenuItem *newItem = createNSMenuItem(action->action->text());
- action->menuItem = newItem;
-#endif
- if (before) {
-#ifndef QT_MAC_USE_COCOA
- InsertMenuItemTextWithCFString(action->menu, 0, qMax(1, before_index+1), 0, action->command);
-#else
- [menu insertItem:newItem atIndex:qMax(1, before_index + 1)];
-#endif
- index = before_index;
- } else {
-#ifndef QT_MAC_USE_COCOA
- AppendMenuItemTextWithCFString(action->menu, 0, 0, action->command, &index);
-#else
- [menu addItem:newItem];
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- SetMenuItemProperty(action->menu, index, kMenuCreatorQt, kMenuPropertyQAction, sizeof(action),
- &action);
-#else
- [newItem setTag:long(static_cast<QAction *>(action->action))];
-#endif
- syncAction(action);
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::syncAction(QMacMenuAction *action)
-{
- if (!action || !menu)
- return;
-#ifndef QT_MAC_USE_COCOA
- const int index = qt_mac_menu_find_action(action->menu, action);
-#else
- QMacCocoaAutoReleasePool pool;
- NSMenuItem *item = action->menuItem;
-#endif
-
- OSMenuRef submenu = 0;
- bool release_submenu = false;
- if (action->action->menu()) {
- if ((submenu = action->action->menu()->macMenu(apple_menu))) {
-#ifndef QT_MAC_USE_COCOA
- QWidget *caused = 0;
- GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(caused), 0, &caused);
- SetMenuItemProperty(submenu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), &caused);
-#else
- if ([submenu supermenu] && [submenu supermenu] != [item menu])
- return;
- else
- [item setSubmenu:submenu];
-#endif
- }
-#ifndef QT_MAC_USE_COCOA
- } else { // create a submenu to act as menu
- release_submenu = true;
- CreateNewMenu(0, 0, &submenu);
-#endif
- }
-
- if (submenu) {
- bool visible = actualMenuItemVisibility(this, action);
-#ifndef QT_MAC_USE_COCOA
- SetMenuItemHierarchicalMenu(action->menu, index, submenu);
- SetMenuTitleWithCFString(submenu, QCFString(qt_mac_removeMnemonics(action->action->text())));
- if (visible)
- ChangeMenuAttributes(submenu, 0, kMenuAttrHidden);
- else
- ChangeMenuAttributes(submenu, kMenuAttrHidden, 0);
-#else
- [item setSubmenu: submenu];
- [submenu setTitle:qt_mac_QStringToNSString(qt_mac_removeMnemonics(action->action->text()))];
- syncNSMenuItemVisiblity(item, visible);
-#endif
- if (release_submenu) { //no pointers to it
-#ifndef QT_MAC_USE_COCOA
- ReleaseMenu(submenu);
-#else
- [submenu release];
-#endif
- }
- } else {
- qWarning("QMenu: No OSMenuRef created for popup menu");
- }
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::removeAction(QMacMenuAction *action)
-{
- if (!action || !menu)
- return;
-#ifndef QT_MAC_USE_COCOA
- DeleteMenuItem(action->menu, qt_mac_menu_find_action(action->menu, action));
-#else
- QMacCocoaAutoReleasePool pool;
- [action->menu removeItem:action->menuItem];
-#endif
- actionItems.removeAll(action);
-}
-
-bool QMenuBarPrivate::macWidgetHasNativeMenubar(QWidget *widget)
-{
- // This function is different from q->isNativeMenuBar(), as
- // it returns true only if a native menu bar is actually
- // _created_.
- if (!widget)
- return false;
- return menubars()->contains(widget->window());
-}
-
-void
-QMenuBarPrivate::macCreateMenuBar(QWidget *parent)
-{
- Q_Q(QMenuBar);
- static int dontUseNativeMenuBar = -1;
- // We call the isNativeMenuBar function here
- // because that will make sure that local overrides
- // are dealt with correctly. q->isNativeMenuBar() will, if not
- // overridden, depend on the attribute Qt::AA_DontUseNativeMenuBar:
- bool qt_mac_no_native_menubar = !q->isNativeMenuBar();
- if (qt_mac_no_native_menubar == false && dontUseNativeMenuBar < 0) {
- // The menubar is set to be native. Let's check (one time only
- // for all menubars) if this is OK with the rest of the environment.
- // As a result, Qt::AA_DontUseNativeMenuBar is set. NB: the application
- // might still choose to not respect, or change, this flag.
- bool isPlugin = QApplication::testAttribute(Qt::AA_MacPluginApplication);
- bool environmentSaysNo = !qgetenv("QT_MAC_NO_NATIVE_MENUBAR").isEmpty();
- dontUseNativeMenuBar = isPlugin || environmentSaysNo;
- QApplication::instance()->setAttribute(Qt::AA_DontUseNativeMenuBar, dontUseNativeMenuBar);
- qt_mac_no_native_menubar = !q->isNativeMenuBar();
- }
- if (qt_mac_no_native_menubar == false) {
- // INVARIANT: Use native menubar.
- extern void qt_event_request_menubarupdate(); //qapplication_mac.cpp
- qt_event_request_menubarupdate();
- if (!parent && !fallback) {
- fallback = q;
- mac_menubar = new QMacMenuBarPrivate;
- } else if (parent && parent->isWindow()) {
- menubars()->insert(q->window(), q);
- mac_menubar = new QMacMenuBarPrivate;
- }
- }
-}
-
-void QMenuBarPrivate::macDestroyMenuBar()
-{
- Q_Q(QMenuBar);
- QMacCocoaAutoReleasePool pool;
- if (fallback == q)
- fallback = 0;
- delete mac_menubar;
- QWidget *tlw = q->window();
- menubars()->remove(tlw);
- mac_menubar = 0;
-
- if (!qt_mac_current_menubar.qmenubar || qt_mac_current_menubar.qmenubar == q) {
-#ifdef QT_MAC_USE_COCOA
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
- [loader removeActionsFromAppMenu];
-#else
- cancelAllMenuTracking();
-#endif
- extern void qt_event_request_menubarupdate(); //qapplication_mac.cpp
- qt_event_request_menubarupdate();
- }
-}
-
-OSMenuRef QMenuBarPrivate::macMenu()
-{
- Q_Q(QMenuBar);
- if (!q->isNativeMenuBar() || !mac_menubar) {
- return 0;
- } else if (!mac_menubar->menu) {
- mac_menubar->menu = qt_mac_create_menu(q);
- ProcessSerialNumber mine, front;
- if (GetCurrentProcess(&mine) == noErr && GetFrontProcess(&front) == noErr) {
- if (!qt_mac_no_menubar_merge && !mac_menubar->apple_menu) {
- mac_menubar->apple_menu = qt_mac_create_menu(q);
-#ifndef QT_MAC_USE_COCOA
- MenuItemIndex index;
- AppendMenuItemTextWithCFString(mac_menubar->menu, 0, 0, 0, &index);
-
- SetMenuTitleWithCFString(mac_menubar->apple_menu, QCFString(QString(QChar(0x14))));
- SetMenuItemHierarchicalMenu(mac_menubar->menu, index, mac_menubar->apple_menu);
- SetMenuItemProperty(mac_menubar->apple_menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(q), &q);
-#else
- [mac_menubar->apple_menu setTitle:qt_mac_QStringToNSString(QString(QChar(0x14)))];
- NSMenuItem *apple_menuItem = [[NSMenuItem alloc] init];
- [apple_menuItem setSubmenu:mac_menubar->menu];
- [mac_menubar->apple_menu addItem:apple_menuItem];
- [apple_menuItem release];
-#endif
- }
- if (mac_menubar->apple_menu) {
-#ifndef QT_MAC_USE_COCOA
- SetMenuItemProperty(mac_menubar->menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
- sizeof(mac_menubar->apple_menu), &mac_menubar->apple_menu);
-#else
- QMenuPrivate::mergeMenuHash.insert(mac_menubar->menu, mac_menubar->apple_menu);
-#endif
- }
- QList<QAction*> items = q->actions();
- for(int i = 0; i < items.count(); i++)
- mac_menubar->addAction(items[i]);
- }
- }
- return mac_menubar->menu;
-}
-
-/*!
- \internal
-
- This function will return the OSMenuRef used to create the native menu bar
- bindings. This OSMenuRef is then set as the root menu for the Menu
- Manager.
-
- \warning This function is not portable.
-
- \sa QMenu::macMenu()
-*/
-OSMenuRef QMenuBar::macMenu() { return d_func()->macMenu(); }
-
-/* !
- \internal
- Ancestor function that crosses windows (QWidget::isAncestorOf
- only considers widgets within the same window).
-*/
-static bool qt_mac_is_ancestor(QWidget* possibleAncestor, QWidget *child)
-{
- if (!possibleAncestor)
- return false;
-
- QWidget * current = child->parentWidget();
- while (current != 0) {
- if (current == possibleAncestor)
- return true;
- current = current->parentWidget();
- }
- return false;
-}
-
-/* !
- \internal
- Returns true if the entries of menuBar should be disabled,
- based on the modality type of modalWidget.
-*/
-static bool qt_mac_should_disable_menu(QMenuBar *menuBar)
-{
- QWidget *modalWidget = qApp->activeModalWidget();
- if (!modalWidget)
- return false;
-
- if (menuBar && menuBar == menubars()->value(modalWidget))
- // The menu bar is owned by the modal widget.
- // In that case we should enable it:
- return false;
-
- // When there is an application modal window on screen, the entries of
- // the menubar should be disabled. The exception in Qt is that if the
- // modal window is the only window on screen, then we enable the menu bar.
- QWidget *w = modalWidget;
- QWidgetList topLevelWidgets = QApplication::topLevelWidgets();
- while (w) {
- if (w->isVisible() && w->windowModality() == Qt::ApplicationModal) {
- for (int i=0; i<topLevelWidgets.size(); ++i) {
- QWidget *top = topLevelWidgets.at(i);
- if (w != top && top->isVisible()) {
- // INVARIANT: we found another visible window
- // on screen other than our modalWidget. We therefore
- // disable the menu bar to follow normal modality logic:
- return true;
- }
- }
- // INVARIANT: We have only one window on screen that happends
- // to be application modal. We choose to enable the menu bar
- // in that case to e.g. enable the quit menu item.
- return false;
- }
- w = w->parentWidget();
- }
-
- // INVARIANT: modalWidget is window modal. Disable menu entries
- // if the menu bar belongs to an ancestor of modalWidget. If menuBar
- // is nil, we understand it as the default menu bar set by the nib:
- return menuBar ? qt_mac_is_ancestor(menuBar->parentWidget(), modalWidget) : false;
-}
-
-static QWidget *findWindowThatShouldDisplayMenubar()
-{
- QWidget *w = qApp->activeWindow();
- if (!w) {
- // We have no active window on screen. Try to
- // find a window from the list of top levels:
- QWidgetList tlws = QApplication::topLevelWidgets();
- for(int i = 0; i < tlws.size(); ++i) {
- QWidget *tlw = tlws.at(i);
- if ((tlw->isVisible() && tlw->windowType() != Qt::Tool &&
- tlw->windowType() != Qt::Popup)) {
- w = tlw;
- break;
- }
- }
- }
- return w;
-}
-
-static QMenuBar *findMenubarForWindow(QWidget *w)
-{
- QMenuBar *mb = 0;
- if (w) {
- mb = menubars()->value(w);
-#ifndef QT_NO_MAINWINDOW
- QDockWidget *dw = qobject_cast<QDockWidget *>(w);
- if (!mb && dw) {
- QMainWindow *mw = qobject_cast<QMainWindow *>(dw->parentWidget());
- if (mw && (mb = menubars()->value(mw)))
- w = mw;
- }
-#endif
- while(w && !mb)
- mb = menubars()->value((w = w->parentWidget()));
- }
-
- if (!mb) {
- // We could not find a menu bar for the window. Lets
- // check if we have a global (parentless) menu bar instead:
- mb = fallback;
- }
-
- return mb;
-}
-
-void qt_mac_clear_menubar()
-{
- if (QApplication::testAttribute(Qt::AA_MacPluginApplication))
- return;
-
-#ifndef QT_MAC_USE_COCOA
- MenuRef clear_menu = 0;
- if (CreateNewMenu(0, 0, &clear_menu) == noErr) {
- SetRootMenu(clear_menu);
- ReleaseMenu(clear_menu);
- } else {
- qWarning("QMenu: Internal error at %s:%d", __FILE__, __LINE__);
- }
- ClearMenuBar();
- qt_mac_command_set_enabled(0, kHICommandPreferences, false);
- InvalMenuBar();
-#else
- QMacCocoaAutoReleasePool pool;
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
- NSMenu *menu = [loader menu];
- [loader ensureAppMenuInMenu:menu];
- [NSApp setMainMenu:menu];
- const bool modal = qt_mac_should_disable_menu(0);
- if (qt_mac_current_menubar.qmenubar || modal != qt_mac_current_menubar.modal)
- qt_mac_set_modal_state(menu, modal);
- qt_mac_current_menubar.qmenubar = 0;
- qt_mac_current_menubar.modal = modal;
-#endif
-}
-
-/*!
- \internal
-
- This function will update the current menu bar and set it as the
- active menu bar in the Menu Manager.
-
- \warning This function is not portable.
-
- \sa QMenu::macMenu(), QMenuBar::macMenu()
-*/
-bool QMenuBar::macUpdateMenuBar()
-{
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
- qt_cocoaPostMessage(getMenuLoader(), @selector(qtUpdateMenubar));
- return true;
-#else
- return QMenuBarPrivate::macUpdateMenuBarImmediatly();
-#endif
-}
-
-bool QMenuBarPrivate::macUpdateMenuBarImmediatly()
-{
- bool ret = false;
- cancelAllMenuTracking();
- QWidget *w = findWindowThatShouldDisplayMenubar();
- QMenuBar *mb = findMenubarForWindow(w);
- extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
-
- // We need to see if we are in full screen mode, if so we need to
- // switch the full screen mode to be able to show or hide the menubar.
- if(w && mb) {
- // This case means we are creating a menubar, check if full screen
- if(w->isFullScreen()) {
- // Ok, switch to showing the menubar when hovering over it.
- SetSystemUIMode(kUIModeAllHidden, kUIOptionAutoShowMenuBar);
- qt_mac_app_fullscreen = true;
- }
- } else if(w) {
- // Removing a menubar
- if(w->isFullScreen()) {
- // Ok, switch to not showing the menubar when hovering on it
- SetSystemUIMode(kUIModeAllHidden, 0);
- qt_mac_app_fullscreen = true;
- }
- }
-
- if (mb && mb->isNativeMenuBar()) {
- bool modal = QApplicationPrivate::modalState();
-#ifdef QT_MAC_USE_COCOA
- QMacCocoaAutoReleasePool pool;
-#endif
- if (OSMenuRef menu = mb->macMenu()) {
-#ifndef QT_MAC_USE_COCOA
- SetRootMenu(menu);
-#else
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
- [loader ensureAppMenuInMenu:menu];
- [NSApp setMainMenu:menu];
- syncMenuBarItemsVisiblity(mb->d_func()->mac_menubar);
-
- if (OSMenuRef tmpMerge = QMenuPrivate::mergeMenuHash.value(menu)) {
- if (QMenuMergeList *mergeList
- = QMenuPrivate::mergeMenuItemsHash.value(tmpMerge)) {
- const int mergeListSize = mergeList->size();
-
- for (int i = 0; i < mergeListSize; ++i) {
- const QMenuMergeItem &mergeItem = mergeList->at(i);
- // Ideally we would call QMenuPrivate::syncAction, but that requires finding
- // the original QMen and likely doing more work than we need.
- // For example, enabled is handled below.
- [mergeItem.menuItem setTag:reinterpret_cast<long>(
- static_cast<QAction *>(mergeItem.action->action))];
- [mergeItem.menuItem setHidden:!(mergeItem.action->action->isVisible())];
- }
- }
- }
-#endif
- // Check if menu is modally shaddowed and should be disabled:
- modal = qt_mac_should_disable_menu(mb);
- if (mb != qt_mac_current_menubar.qmenubar || modal != qt_mac_current_menubar.modal)
- qt_mac_set_modal_state(menu, modal);
- }
- qt_mac_current_menubar.qmenubar = mb;
- qt_mac_current_menubar.modal = modal;
- ret = true;
- } else if (qt_mac_current_menubar.qmenubar && qt_mac_current_menubar.qmenubar->isNativeMenuBar()) {
- // INVARIANT: The currently active menu bar (if any) is not native. But we do have a
- // native menu bar from before. So we need to decide whether or not is should be enabled:
- const bool modal = qt_mac_should_disable_menu(qt_mac_current_menubar.qmenubar);
- if (modal != qt_mac_current_menubar.modal) {
- ret = true;
- if (OSMenuRef menu = qt_mac_current_menubar.qmenubar->macMenu()) {
-#ifndef QT_MAC_USE_COCOA
- SetRootMenu(menu);
-#else
- QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
- [loader ensureAppMenuInMenu:menu];
- [NSApp setMainMenu:menu];
- syncMenuBarItemsVisiblity(qt_mac_current_menubar.qmenubar->d_func()->mac_menubar);
-#endif
- qt_mac_set_modal_state(menu, modal);
- }
- qt_mac_current_menubar.modal = modal;
- }
- }
-
- if (!ret) {
- qt_mac_clear_menubar();
- }
- return ret;
-}
-
-QHash<OSMenuRef, OSMenuRef> QMenuPrivate::mergeMenuHash;
-QHash<OSMenuRef, QMenuMergeList*> QMenuPrivate::mergeMenuItemsHash;
-
-bool QMenuPrivate::QMacMenuPrivate::merged(const QAction *action) const
-{
-#ifndef QT_MAC_USE_COCOA
- MenuRef merge = 0;
- GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
- sizeof(merge), 0, &merge);
- if (merge) {
- QMenuMergeList *list = 0;
- if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
- sizeof(list), 0, &list) == noErr && list) {
- for(int i = 0; i < list->size(); ++i) {
- QMenuMergeItem item = list->at(i);
- if (item.action->action == action)
- return true;
- }
- }
- }
-#else
- if (OSMenuRef merge = mergeMenuHash.value(menu)) {
- if (QMenuMergeList *list = mergeMenuItemsHash.value(merge)) {
- for(int i = 0; i < list->size(); ++i) {
- const QMenuMergeItem &item = list->at(i);
- if (item.action->action == action)
- return true;
- }
- }
- }
-#endif
- return false;
-}
-
-//creation of the OSMenuRef
-static OSMenuRef qt_mac_create_menu(QWidget *w)
-{
- OSMenuRef ret;
-#ifndef QT_MAC_USE_COCOA
- ret = 0;
- if (CreateNewMenu(0, 0, &ret) == noErr) {
- qt_mac_create_menu_event_handler();
- SetMenuItemProperty(ret, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(w), &w);
-
- // kEventMenuMatchKey is only sent to the menu itself and not to
- // the application, install a separate handler for that event.
- EventHandlerRef eventHandlerRef;
- InstallMenuEventHandler(ret, qt_mac_menu_event,
- GetEventTypeCount(menu_menu_events),
- menu_menu_events, 0, &eventHandlerRef);
- menu_eventHandlers_hash()->insert(ret, eventHandlerRef);
- } else {
- qWarning("QMenu: Internal error");
- }
-#else
- if (QMenu *qmenu = qobject_cast<QMenu *>(w)){
- ret = [[QT_MANGLE_NAMESPACE(QCocoaMenu) alloc] initWithQMenu:qmenu];
- } else {
- ret = [[NSMenu alloc] init];
- }
-#endif
- return ret;
-}
-
-
-
-QT_END_NAMESPACE
-
diff --git a/src/gui/widgets/qmenu_p.h b/src/gui/widgets/qmenu_p.h
deleted file mode 100644
index b6efde34cc..0000000000
--- a/src/gui/widgets/qmenu_p.h
+++ /dev/null
@@ -1,393 +0,0 @@
-/****************************************************************************
-**
-** 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 QMENU_P_H
-#define QMENU_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qmenubar.h"
-#include "QtGui/qstyleoption.h"
-#include "QtCore/qdatetime.h"
-#include "QtCore/qmap.h"
-#include "QtCore/qhash.h"
-#include "QtCore/qbasictimer.h"
-#include "private/qwidget_p.h"
-
-#ifdef Q_WS_S60
-class CEikMenuPane;
-#define QT_SYMBIAN_FIRST_MENU_ITEM 32000
-#define QT_SYMBIAN_LAST_MENU_ITEM 41999 // 10000 items ought to be enough for anybody...
-#endif
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_MENU
-
-#ifdef Q_WS_S60
-void qt_symbian_next_menu_from_action(QWidget* actionContainer);
-void qt_symbian_show_toplevel(CEikMenuPane* menuPane);
-void qt_symbian_show_submenu(CEikMenuPane* menuPane, int id);
-#endif // Q_WS_S60
-
-class QTornOffMenu;
-class QEventLoop;
-
-#ifdef Q_WS_MAC
-# ifdef __OBJC__
-QT_END_NAMESPACE
-@class NSMenuItem;
-QT_BEGIN_NAMESPACE
-# else
-typedef void NSMenuItem;
-# endif //__OBJC__
-struct QMacMenuAction {
- QMacMenuAction()
-#ifndef QT_MAC_USE_COCOA
- : command(0)
-#else
- : menuItem(0)
-#endif
- , ignore_accel(0), merged(0), menu(0)
- {
- }
- ~QMacMenuAction();
-#ifndef QT_MAC_USE_COCOA
- uint command;
-#else
- NSMenuItem *menuItem;
-#endif
- uchar ignore_accel : 1;
- uchar merged : 1;
- QPointer<QAction> action;
- OSMenuRef menu;
-};
-
-struct QMenuMergeItem
-{
-#ifndef QT_MAC_USE_COCOA
- inline QMenuMergeItem(MenuCommand c, QMacMenuAction *a) : command(c), action(a) { }
- MenuCommand command;
-#else
- inline QMenuMergeItem(NSMenuItem *c, QMacMenuAction *a) : menuItem(c), action(a) { }
- NSMenuItem *menuItem;
-#endif
- QMacMenuAction *action;
-};
-typedef QList<QMenuMergeItem> QMenuMergeList;
-#endif
-
-#ifdef Q_WS_WINCE
-struct QWceMenuAction {
- uint command;
- QPointer<QAction> action;
- HMENU menuHandle;
- QWceMenuAction() : menuHandle(0), command(0) {}
-};
-#endif
-#ifdef Q_WS_S60
-struct QSymbianMenuAction {
- uint command;
- int parent;
- CEikMenuPane* menuPane;
- QPointer<QAction> action;
- QSymbianMenuAction() : command(0) {}
-};
-#endif
-
-class QMenuPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QMenu)
-public:
- QMenuPrivate() : itemsDirty(0), maxIconWidth(0), tabWidth(0), ncols(0),
- collapsibleSeparators(true), activationRecursionGuard(false), hasHadMouse(0), aboutToHide(0), motions(0),
- currentAction(0),
-#ifdef QT_KEYPAD_NAVIGATION
- selectAction(0),
- cancelAction(0),
-#endif
- scroll(0), eventLoop(0), tearoff(0), tornoff(0), tearoffHighlighted(0),
- hasCheckableItems(0), sloppyAction(0), doChildEffects(false)
-#ifdef Q_WS_MAC
- ,mac_menu(0)
-#endif
-#if defined(Q_WS_WINCE) && !defined(QT_NO_MENUBAR)
- ,wce_menu(0)
-#endif
-#ifdef Q_WS_S60
- ,symbian_menu(0)
-#endif
-#ifdef QT3_SUPPORT
- ,emitHighlighted(false)
-#endif
- { }
- ~QMenuPrivate()
- {
- delete scroll;
-#ifdef Q_WS_MAC
- delete mac_menu;
-#endif
-#if defined(Q_WS_WINCE) && !defined(QT_NO_MENUBAR)
- delete wce_menu;
-#endif
-#ifdef Q_WS_S60
- delete symbian_menu;
-#endif
-
- }
- void init();
-
- static QMenuPrivate *get(QMenu *m) { return m->d_func(); }
- int scrollerHeight() const;
-
- //item calculations
- mutable uint itemsDirty : 1;
- mutable uint maxIconWidth, tabWidth;
- QRect actionRect(QAction *) const;
-
- mutable QVector<QRect> actionRects;
- mutable QHash<QAction *, QWidget *> widgetItems;
- void updateActionRects() const;
- QRect popupGeometry(const QWidget *widget) const;
- QRect popupGeometry(int screen = -1) const;
- mutable uint ncols : 4; //4 bits is probably plenty
- uint collapsibleSeparators : 1;
-
- bool activationRecursionGuard;
-
- //selection
- static QMenu *mouseDown;
- QPoint mousePopupPos;
- uint hasHadMouse : 1;
- uint aboutToHide : 1;
- int motions;
- QAction *currentAction;
-#ifdef QT_KEYPAD_NAVIGATION
- QAction *selectAction;
- QAction *cancelAction;
-#endif
- QBasicTimer menuDelayTimer;
- enum SelectionReason {
- SelectedFromKeyboard,
- SelectedFromElsewhere
- };
- QWidget *topCausedWidget() const;
- QAction *actionAt(QPoint p) const;
- void setFirstActionActive();
- void setCurrentAction(QAction *, int popup = -1, SelectionReason reason = SelectedFromElsewhere, bool activateFirst = false);
- void popupAction(QAction *, int, bool);
- void setSyncAction();
-
- //scrolling support
- struct QMenuScroller {
- enum ScrollLocation { ScrollStay, ScrollBottom, ScrollTop, ScrollCenter };
- enum ScrollDirection { ScrollNone=0, ScrollUp=0x01, ScrollDown=0x02 };
- uint scrollFlags : 2, scrollDirection : 2;
- int scrollOffset;
- QBasicTimer scrollTimer;
-
- QMenuScroller() : scrollFlags(ScrollNone), scrollDirection(ScrollNone), scrollOffset(0) { }
- ~QMenuScroller() { }
- } *scroll;
- void scrollMenu(QMenuScroller::ScrollLocation location, bool active=false);
- void scrollMenu(QMenuScroller::ScrollDirection direction, bool page=false, bool active=false);
- void scrollMenu(QAction *action, QMenuScroller::ScrollLocation location, bool active=false);
-
- //synchronous operation (ie exec())
- QEventLoop *eventLoop;
- QPointer<QAction> syncAction;
-
- //search buffer
- QString searchBuffer;
- QBasicTimer searchBufferTimer;
-
- //passing of mouse events up the parent hierarchy
- QPointer<QMenu> activeMenu;
- bool mouseEventTaken(QMouseEvent *);
-
- //used to walk up the popup list
- struct QMenuCaused {
- QPointer<QWidget> widget;
- QPointer<QAction> action;
- };
- virtual QList<QPointer<QWidget> > calcCausedStack() const;
- QMenuCaused causedPopup;
- void hideUpToMenuBar();
- void hideMenu(QMenu *menu, bool justRegister = false);
-
- //index mappings
- inline QAction *actionAt(int i) const { return q_func()->actions().at(i); }
- inline int indexOf(QAction *act) const { return q_func()->actions().indexOf(act); }
-
- //tear off support
- uint tearoff : 1, tornoff : 1, tearoffHighlighted : 1;
- QPointer<QTornOffMenu> tornPopup;
-
- mutable bool hasCheckableItems;
-
- //sloppy selection
- static int sloppyDelayTimer;
- mutable QAction *sloppyAction;
- QRegion sloppyRegion;
-
- //default action
- QPointer<QAction> defaultAction;
-
- QAction *menuAction;
- QAction *defaultMenuAction;
-
- void setOverrideMenuAction(QAction *);
- void _q_overrideMenuActionDestroyed();
-
- //firing of events
- void activateAction(QAction *, QAction::ActionEvent, bool self=true);
- void activateCausedStack(const QList<QPointer<QWidget> > &, QAction *, QAction::ActionEvent, bool);
-
- void _q_actionTriggered();
- void _q_actionHovered();
-
- bool hasMouseMoved(const QPoint &globalPos);
-
- void updateLayoutDirection();
-
-
- //menu fading/scrolling effects
- bool doChildEffects;
-
-#ifdef Q_WS_MAC
- //mac menu binding
- struct QMacMenuPrivate {
- QList<QMacMenuAction*> actionItems;
- OSMenuRef menu;
- QMacMenuPrivate();
- ~QMacMenuPrivate();
-
- bool merged(const QAction *action) const;
- void addAction(QAction *, QMacMenuAction* =0, QMenuPrivate *qmenu = 0);
- void addAction(QMacMenuAction *, QMacMenuAction* =0, QMenuPrivate *qmenu = 0);
- void syncAction(QMacMenuAction *);
- inline void syncAction(QAction *a) { syncAction(findAction(a)); }
- void removeAction(QMacMenuAction *);
- inline void removeAction(QAction *a) { removeAction(findAction(a)); }
- inline QMacMenuAction *findAction(QAction *a) {
- for(int i = 0; i < actionItems.size(); i++) {
- QMacMenuAction *act = actionItems[i];
- if(a == act->action)
- return act;
- }
- return 0;
- }
- } *mac_menu;
- OSMenuRef macMenu(OSMenuRef merge);
- void setMacMenuEnabled(bool enable = true);
- void syncSeparatorsCollapsible(bool collapsible);
- static QHash<OSMenuRef, OSMenuRef> mergeMenuHash;
- static QHash<OSMenuRef, QMenuMergeList*> mergeMenuItemsHash;
-#endif
-
- QPointer<QAction> actionAboutToTrigger;
-#ifdef QT3_SUPPORT
- bool emitHighlighted;
-#endif
-
-#if defined(Q_WS_WINCE) && !defined(QT_NO_MENUBAR)
- struct QWceMenuPrivate {
- QList<QWceMenuAction*> actionItems;
- HMENU menuHandle;
- QWceMenuPrivate();
- ~QWceMenuPrivate();
- void addAction(QAction *, QWceMenuAction* =0);
- void addAction(QWceMenuAction *, QWceMenuAction* =0);
- void syncAction(QWceMenuAction *);
- inline void syncAction(QAction *a) { syncAction(findAction(a)); }
- void removeAction(QWceMenuAction *);
- void rebuild();
- inline void removeAction(QAction *a) { removeAction(findAction(a)); }
- inline QWceMenuAction *findAction(QAction *a) {
- for(int i = 0; i < actionItems.size(); i++) {
- QWceMenuAction *act = actionItems[i];
- if(a == act->action)
- return act;
- }
- return 0;
- }
- } *wce_menu;
- HMENU wceMenu();
- QAction* wceCommands(uint command);
-#endif
-#if defined(Q_WS_S60)
- struct QSymbianMenuPrivate {
- QList<QSymbianMenuAction*> actionItems;
- QSymbianMenuPrivate();
- ~QSymbianMenuPrivate();
- void addAction(QAction *, QSymbianMenuAction* =0);
- void addAction(QSymbianMenuAction *, QSymbianMenuAction* =0);
- void syncAction(QSymbianMenuAction *);
- inline void syncAction(QAction *a) { syncAction(findAction(a)); }
- void removeAction(QSymbianMenuAction *);
- void rebuild(bool reCreate = false);
- inline void removeAction(QAction *a) { removeAction(findAction(a)); }
- inline QSymbianMenuAction *findAction(QAction *a) {
- for(int i = 0; i < actionItems.size(); i++) {
- QSymbianMenuAction *act = actionItems[i];
- if(a == act->action)
- return act;
- }
- return 0;
- }
- } *symbian_menu;
-#endif
- QPointer<QWidget> noReplayFor;
-};
-
-#endif // QT_NO_MENU
-
-QT_END_NAMESPACE
-
-#endif // QMENU_P_H
diff --git a/src/gui/widgets/qmenu_symbian.cpp b/src/gui/widgets/qmenu_symbian.cpp
deleted file mode 100644
index d614bb8a77..0000000000
--- a/src/gui/widgets/qmenu_symbian.cpp
+++ /dev/null
@@ -1,464 +0,0 @@
-/****************************************************************************
-**
-** 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 S60 port 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 "qmenu.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qdebug.h"
-#include "qwidgetaction.h"
-#include <private/qapplication_p.h>
-#include <private/qmenu_p.h>
-#include <private/qmenubar_p.h>
-#include <private/qt_s60_p.h>
-#include <QtCore/qlibrary.h>
-
-#ifdef Q_WS_S60
-#include <eikmenub.h>
-#include <eikmenup.h>
-#include <eikaufty.h>
-#include <eikbtgpc.h>
-#include <avkon.rsg>
-#endif
-
-#if !defined(QT_NO_MENUBAR) && defined(Q_WS_S60)
-
-QT_BEGIN_NAMESPACE
-
-typedef QMultiHash<QWidget *, QMenuBarPrivate *> MenuBarHash;
-Q_GLOBAL_STATIC(MenuBarHash, menubars)
-
-struct SymbianMenuItem
-{
- int id;
- CEikMenuPaneItem::SData menuItemData;
- QList<SymbianMenuItem*> children;
- QAction* action;
-};
-
-Q_GLOBAL_STATIC_WITH_ARGS(QAction, contextAction, (0))
-
-static QList<SymbianMenuItem*> symbianMenus;
-static QList<QMenuBar*> nativeMenuBars;
-static uint qt_symbian_menu_static_cmd_id = QT_SYMBIAN_FIRST_MENU_ITEM;
-static QPointer<QWidget> widgetWithContextMenu;
-static QList<QAction*> contextMenuActionList;
-static QWidget* actionMenu = NULL;
-static int contexMenuCommand=0;
-
-bool menuExists()
-{
- QWidget *w = qApp->activeWindow();
- QMenuBarPrivate *mb = menubars()->value(w);
- if ((!mb) && !menubars()->count())
- return false;
- return true;
-}
-
-static bool hasContextMenu(QWidget* widget)
-{
- if (!widget)
- return false;
- const Qt::ContextMenuPolicy policy = widget->contextMenuPolicy();
- if (policy != Qt::NoContextMenu && policy != Qt::PreventContextMenu ) {
- return true;
- }
- return false;
-}
-
-static SymbianMenuItem* qt_symbian_find_menu(int id, const QList<SymbianMenuItem*> &parent)
-{
- int index=0;
- while (index < parent.count()) {
- SymbianMenuItem* temp = parent[index];
- if (temp->menuItemData.iCascadeId == id)
- return temp;
- else if (temp->menuItemData.iCascadeId != 0) {
- SymbianMenuItem* result = qt_symbian_find_menu( id, temp->children);
- if (result)
- return result;
- }
- index++;
- }
- return 0;
-}
-
-static SymbianMenuItem* qt_symbian_find_menu_item(int id, const QList<SymbianMenuItem*> &parent)
-{
- int index=0;
- while (index < parent.count()) {
- SymbianMenuItem* temp = parent[index];
- if (temp->menuItemData.iCascadeId != 0) {
- SymbianMenuItem* result = qt_symbian_find_menu_item( id, temp->children);
- if (result)
- return result;
- }
- else if (temp->menuItemData.iCommandId == id)
- return temp;
- index++;
-
- }
- return 0;
-}
-
-static void qt_symbian_insert_action(QSymbianMenuAction* action, QList<SymbianMenuItem*>* parent)
-{
- if (action->action->isVisible()) {
- if (action->action->isSeparator())
- return;
-
- Q_ASSERT_X(action->command <= QT_SYMBIAN_LAST_MENU_ITEM, "qt_symbian_insert_action",
- "Too many menu actions");
-
- const int underlineShortCut = QApplication::style()->styleHint(QStyle::SH_UnderlineShortcut);
- QString actionText;
- if (underlineShortCut)
- actionText = action->action->text().left(CEikMenuPaneItem::SData::ENominalTextLength);
- else
- actionText = action->action->iconText().left(CEikMenuPaneItem::SData::ENominalTextLength);
- TPtrC menuItemText = qt_QString2TPtrC(actionText);
- if (action->action->menu()) {
- SymbianMenuItem* menuItem = new SymbianMenuItem();
- menuItem->menuItemData.iCascadeId = action->command;
- menuItem->menuItemData.iCommandId = action->command;
- menuItem->menuItemData.iFlags = 0;
- menuItem->menuItemData.iText = menuItemText;
- menuItem->action = action->action;
- if (action->action->menu()->actions().size() == 0 || !action->action->isEnabled() )
- menuItem->menuItemData.iFlags |= EEikMenuItemDimmed;
- parent->append(menuItem);
-
- if (action->action->menu()->actions().size() > 0) {
- for (int c2= 0; c2 < action->action->menu()->actions().size(); ++c2) {
- QScopedPointer<QSymbianMenuAction> symbianAction2(new QSymbianMenuAction);
- symbianAction2->action = action->action->menu()->actions().at(c2);
- QMenu * menu = symbianAction2->action->menu();
- symbianAction2->command = qt_symbian_menu_static_cmd_id++;
- qt_symbian_insert_action(symbianAction2.data(), &(menuItem->children));
- }
- }
-
- } else {
- SymbianMenuItem* menuItem = new SymbianMenuItem();
- menuItem->menuItemData.iCascadeId = 0;
- menuItem->menuItemData.iCommandId = action->command;
- menuItem->menuItemData.iFlags = 0;
- menuItem->menuItemData.iText = menuItemText;
- menuItem->action = action->action;
- if (!action->action->isEnabled()){
- menuItem->menuItemData.iFlags += EEikMenuItemDimmed;
- }
-
- if (action->action->isCheckable()) {
- if (action->action->isChecked())
- menuItem->menuItemData.iFlags += EEikMenuItemCheckBox | EEikMenuItemSymbolOn;
- else
- menuItem->menuItemData.iFlags += EEikMenuItemCheckBox;
- }
- parent->append(menuItem);
- }
- }
-}
-
-void deleteAll(QList<SymbianMenuItem*> *items)
-{
- while (!items->isEmpty()) {
- SymbianMenuItem* temp = items->takeFirst();
- deleteAll(&temp->children);
- delete temp;
- }
-}
-
-static void rebuildMenu()
-{
- widgetWithContextMenu = 0;
- QMenuBarPrivate *mb = 0;
- QWidget *w = qApp->activeWindow();
- QWidget* focusWidget = QApplication::focusWidget();
- if (focusWidget) {
- if (hasContextMenu(focusWidget))
- widgetWithContextMenu = focusWidget;
- }
-
- if (w) {
- mb = menubars()->value(w);
- qt_symbian_menu_static_cmd_id = QT_SYMBIAN_FIRST_MENU_ITEM;
- deleteAll( &symbianMenus );
- if (!mb)
- return;
- mb->symbian_menubar->rebuild();
- }
-}
-
-#ifdef Q_WS_S60
-void qt_symbian_next_menu_from_action(QWidget *actionContainer)
-{
- actionMenu = actionContainer;
-}
-
-void qt_symbian_show_toplevel( CEikMenuPane* menuPane)
-{
- if (actionMenu) {
- QMenuBarPrivate *mb = 0;
- mb = menubars()->value(actionMenu);
- qt_symbian_menu_static_cmd_id = QT_SYMBIAN_FIRST_MENU_ITEM;
- deleteAll( &symbianMenus );
- Q_ASSERT(mb);
- mb->symbian_menubar->rebuild();
- for (int i = 0; i < symbianMenus.count(); ++i)
- QT_TRAP_THROWING(menuPane->AddMenuItemL(symbianMenus.at(i)->menuItemData));
- actionMenu = NULL;
- return;
- }
-
- if (!menuExists())
- return;
- rebuildMenu();
- for (int i = 0; i < symbianMenus.count(); ++i)
- QT_TRAP_THROWING(menuPane->AddMenuItemL(symbianMenus.at(i)->menuItemData));
-}
-
-void qt_symbian_show_submenu( CEikMenuPane* menuPane, int id)
-{
- SymbianMenuItem* menu = qt_symbian_find_menu(id, symbianMenus);
- if (menu) {
- // Normally first AddMenuItemL call for menuPane will create the item array.
- // However if we don't have any items, we still need the item array. Otherwise
- // menupane will crash. That's why we create item array here manually, and
- // AddMenuItemL will then use the existing array.
- CEikMenuPane::CItemArray* itemArray = new CEikMenuPane::CItemArray;
- Q_CHECK_PTR(itemArray);
- menuPane->SetItemArray(itemArray);
- menuPane->SetItemArrayOwnedExternally(EFalse);
-
- for (int i = 0; i < menu->children.count(); ++i)
- QT_TRAP_THROWING(menuPane->AddMenuItemL(menu->children.at(i)->menuItemData));
- }
-}
-#endif // Q_WS_S60
-
-int QMenuBarPrivate::symbianCommands(int command)
-{
- int ret = 0;
-
- if (command == contexMenuCommand && !widgetWithContextMenu.isNull()) {
- QContextMenuEvent* event = new QContextMenuEvent(QContextMenuEvent::Keyboard, QPoint(0,0));
- QCoreApplication::postEvent(widgetWithContextMenu, event);
- ret = 1;
- }
-
- int size = nativeMenuBars.size();
- for (int i = 0; i < nativeMenuBars.size(); ++i) {
- SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus);
- if (!menu)
- continue;
-
- emit nativeMenuBars.at(i)->triggered(menu->action);
- menu->action->activate(QAction::Trigger);
- ret = 1;
- break;
- }
-
- return ret;
-}
-
-void QMenuBarPrivate::symbianCreateMenuBar(QWidget *parent)
-{
- Q_Q(QMenuBar);
- if (parent) {
- if(parent->isWindow()) {
- menubars()->insert(q->window(), this);
- symbian_menubar = new QSymbianMenuBarPrivate(this);
- nativeMenuBars.append(q);
- } else {
- menubars()->insert(q->parentWidget(), this);
- symbian_menubar = new QSymbianMenuBarPrivate(this);
- nativeMenuBars.append(q);
- }
- }
-}
-
-void QMenuBarPrivate::symbianDestroyMenuBar()
-{
- Q_Q(QMenuBar);
- int index = nativeMenuBars.indexOf(q);
- nativeMenuBars.removeAt(index);
- menubars()->remove(q->window(), this);
- menubars()->remove(q->parentWidget(), this);
- rebuildMenu();
- if (symbian_menubar)
- delete symbian_menubar;
- symbian_menubar = 0;
-}
-
-void QMenuBarPrivate::reparentMenuBar(QWidget *oldParent, QWidget *newParent)
-{
- if (menubars()->contains(oldParent)) {
- QMenuBarPrivate *object = menubars()->take(oldParent);
- menubars()->insert(newParent, object);
- }
-}
-
-QMenuBarPrivate::QSymbianMenuBarPrivate::QSymbianMenuBarPrivate(QMenuBarPrivate *menubar)
-{
- d = menubar;
-}
-
-QMenuBarPrivate::QSymbianMenuBarPrivate::~QSymbianMenuBarPrivate()
-{
- qt_symbian_menu_static_cmd_id = QT_SYMBIAN_FIRST_MENU_ITEM;
- deleteAll( &symbianMenus );
- symbianMenus.clear();
- d = 0;
- rebuild();
-}
-
-QMenuPrivate::QSymbianMenuPrivate::QSymbianMenuPrivate()
-{
-}
-
-QMenuPrivate::QSymbianMenuPrivate::~QSymbianMenuPrivate()
-{
-
-}
-
-void QMenuPrivate::QSymbianMenuPrivate::addAction(QAction *a, QSymbianMenuAction *before)
-{
- QSymbianMenuAction *action = new QSymbianMenuAction;
- action->action = a;
- action->command = qt_symbian_menu_static_cmd_id++;
- addAction(action, before);
-}
-
-void QMenuPrivate::QSymbianMenuPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before)
-{
- if (!action)
- return;
- int before_index = actionItems.indexOf(before);
- if (before_index < 0) {
- before = 0;
- before_index = actionItems.size();
- }
- actionItems.insert(before_index, action);
-}
-
-
-void QMenuPrivate::QSymbianMenuPrivate::syncAction(QSymbianMenuAction *)
-{
- rebuild();
-}
-
-void QMenuPrivate::QSymbianMenuPrivate::removeAction(QSymbianMenuAction *action)
-{
- actionItems.removeAll(action);
- delete action;
- action = 0;
- rebuild();
-}
-
-void QMenuPrivate::QSymbianMenuPrivate::rebuild(bool)
-{
-}
-
-void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QAction *a, QSymbianMenuAction *before)
-{
- QSymbianMenuAction *action = new QSymbianMenuAction;
- action->action = a;
- action->command = qt_symbian_menu_static_cmd_id++;
- addAction(action, before);
-}
-
-void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before)
-{
- if (!action)
- return;
- int before_index = actionItems.indexOf(before);
- if (before_index < 0) {
- before = 0;
- before_index = actionItems.size();
- }
- actionItems.insert(before_index, action);
-}
-
-void QMenuBarPrivate::QSymbianMenuBarPrivate::syncAction(QSymbianMenuAction*)
-{
- rebuild();
-}
-
-void QMenuBarPrivate::QSymbianMenuBarPrivate::removeAction(QSymbianMenuAction *action)
-{
- actionItems.removeAll(action);
- delete action;
- rebuild();
-}
-
-void QMenuBarPrivate::QSymbianMenuBarPrivate::insertNativeMenuItems(const QList<QAction*> &actions)
-{
- for (int i = 0; i <actions.size(); ++i) {
- QScopedPointer<QSymbianMenuAction> symbianActionTopLevel(new QSymbianMenuAction);
- symbianActionTopLevel->action = actions.at(i);
- symbianActionTopLevel->parent = 0;
- symbianActionTopLevel->command = qt_symbian_menu_static_cmd_id++;
- qt_symbian_insert_action(symbianActionTopLevel.data(), &symbianMenus);
- }
-}
-
-
-
-void QMenuBarPrivate::QSymbianMenuBarPrivate::rebuild()
-{
- contexMenuCommand = 0;
- qt_symbian_menu_static_cmd_id = QT_SYMBIAN_FIRST_MENU_ITEM;
- deleteAll( &symbianMenus );
- if (d)
- insertNativeMenuItems(d->actions);
-
- contextMenuActionList.clear();
- if (widgetWithContextMenu) {
- contexMenuCommand = qt_symbian_menu_static_cmd_id; // Increased inside insertNativeMenuItems
- contextAction()->setText(QMenuBar::tr("Actions"));
- contextMenuActionList.append(contextAction());
- insertNativeMenuItems(contextMenuActionList);
- }
-}
-QT_END_NAMESPACE
-
-#endif //QT_NO_MENUBAR
diff --git a/src/gui/widgets/qmenu_wince.cpp b/src/gui/widgets/qmenu_wince.cpp
deleted file mode 100644
index 86a78ad50a..0000000000
--- a/src/gui/widgets/qmenu_wince.cpp
+++ /dev/null
@@ -1,668 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//Native menubars are only supported for Windows Mobile not the standard SDK/generic WinCE
-#ifdef Q_WS_WINCE
-#include "qmenu.h"
-#include "qt_windows.h"
-#include "qapplication.h"
-#include "qmainwindow.h"
-#include "qtoolbar.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qdebug.h"
-#include "qwidgetaction.h"
-#include <private/qapplication_p.h>
-#include <private/qmenu_p.h>
-#include <private/qmenubar_p.h>
-
-#include "qmenu_wince_resource_p.h"
-
-#include <QtCore/qlibrary.h>
-#include <commctrl.h>
-#if Q_OS_WINCE_WM
-# include <windowsm.h>
-#endif
-
-#include "qguifunctions_wince.h"
-
-#ifndef QT_NO_MENUBAR
-
-#ifndef SHCMBF_EMPTYBAR
-#define SHCMBF_EMPTYBAR 0x0001
-#endif
-
-#ifndef SHCMBM_GETSUBMENU
-#define SHCMBM_GETSUBMENU (WM_USER + 401)
-#endif
-
-#ifdef Q_OS_WINCE_WM
-# define SHMBOF_NODEFAULT 0x00000001
-# define SHMBOF_NOTIFY 0x00000002
-# define SHCMBM_OVERRIDEKEY (WM_USER + 0x193)
-#endif
-
-extern bool qt_wince_is_smartphone();//defined in qguifunctions_wce.cpp
-extern bool qt_wince_is_pocket_pc(); //defined in qguifunctions_wce.cpp
-
-QT_BEGIN_NAMESPACE
-
-static uint qt_wce_menu_static_cmd_id = 200;
-static QList<QMenuBar*> nativeMenuBars;
-
-struct qt_SHMENUBARINFO
-{
- DWORD cbSize;
- HWND hwndParent;
- DWORD dwFlags;
- UINT nToolBarId;
- HINSTANCE hInstRes;
- int nBmpId;
- int cBmpImages;
- HWND hwndMB;
- COLORREF clrBk;
-};
-
-typedef BOOL (WINAPI *AygCreateMenuBar)(qt_SHMENUBARINFO*);
-typedef HRESULT (WINAPI *AygEnableSoftKey)(HWND,UINT,BOOL,BOOL);
-
-static bool aygResolved = false;
-static AygCreateMenuBar ptrCreateMenuBar = 0;
-static AygEnableSoftKey ptrEnableSoftKey = 0;
-
-static void resolveAygLibs()
-{
- if (!aygResolved) {
- aygResolved = true;
- QLibrary aygLib(QLatin1String("aygshell"));
- ptrCreateMenuBar = (AygCreateMenuBar) aygLib.resolve("SHCreateMenuBar");
- ptrEnableSoftKey = (AygEnableSoftKey) aygLib.resolve("SHEnableSoftkey");
- }
-}
-
-static void qt_wce_enable_soft_key(HWND handle, uint command)
-{
- resolveAygLibs();
- if (ptrEnableSoftKey)
- ptrEnableSoftKey(handle, command, false, true);
-}
-
-static void qt_wce_disable_soft_key(HWND handle, uint command)
-{
- resolveAygLibs();
- if (ptrEnableSoftKey)
- ptrEnableSoftKey(handle, command, false, false);
-}
-
-static void qt_wce_delete_action_list(QList<QWceMenuAction*> *list)
-{
- for(QList<QWceMenuAction*>::Iterator it = list->begin(); it != list->end(); ++it) {
- QWceMenuAction *action = (*it);
- delete action;
- action = 0;
- }
- list->clear();
-}
-
-//search for first QuitRole in QMenuBar
-static QAction* qt_wce_get_quit_action(QList<QAction *> actionItems)
-{
- QAction *returnAction = 0;
- for (int i = 0; i < actionItems.size(); ++i) {
- QAction *action = actionItems.at(i);
- if (action->menuRole() == QAction::QuitRole)
- returnAction = action;
- else
- if (action->menu())
- returnAction = qt_wce_get_quit_action(action->menu()->actions());
- if (returnAction)
- return returnAction; //return first action found
- }
- return 0; //nothing found;
-}
-
-static QAction* qt_wce_get_quit_action(QList<QWceMenuAction*> actionItems)
-{
- for (int i = 0; i < actionItems.size(); ++i) {
- if (actionItems.at(i)->action->menuRole() == QAction::QuitRole)
- return actionItems.at(i)->action;
- else if (actionItems.at(i)->action->menu()) {
- QAction *returnAction = qt_wce_get_quit_action(actionItems.at(i)->action->menu()->actions());
- if (returnAction)
- return returnAction;
- }
- }
- return 0;
-}
-
-static HMODULE qt_wce_get_module_handle()
-{
- HMODULE module = 0; //handle to resources
- if (!(module = GetModuleHandle(L"QtGui4"))) //release dynamic
- if (!(module = GetModuleHandle(L"QtGuid4"))) //debug dynamic
- module = (HINSTANCE)qWinAppInst(); //static
- Q_ASSERT_X(module, "qt_wce_get_module_handle()", "cannot get handle to module?");
- return module;
-}
-
-static void qt_wce_change_command(HWND menuHandle, int item, int command)
-{
-TBBUTTONINFOA tbbi;
- memset(&tbbi,0,sizeof(tbbi));
- tbbi.cbSize = sizeof(tbbi);
- tbbi.dwMask = TBIF_COMMAND;
- tbbi.idCommand = command;
- SendMessage(menuHandle, TB_SETBUTTONINFO, item, (LPARAM)&tbbi);
-}
-
-static void qt_wce_rename_menu_item(HWND menuHandle, int item, const QString &newText)
-{
- TBBUTTONINFOA tbbi;
- memset(&tbbi,0,sizeof(tbbi));
- tbbi.cbSize = sizeof(tbbi);
- tbbi.dwMask = TBIF_TEXT;
- QString text = newText;
- text.remove(QChar::fromLatin1('&'));
- tbbi.pszText = (LPSTR) text.utf16();
- SendMessage(menuHandle, TB_SETBUTTONINFO, item, (LPARAM)&tbbi);
-}
-
-static HWND qt_wce_create_menubar(HWND parentHandle, HINSTANCE resourceHandle, int toolbarID, int flags = 0)
-{
- resolveAygLibs();
-
- if (ptrCreateMenuBar) {
- qt_SHMENUBARINFO mbi;
- memset(&mbi, 0, sizeof(qt_SHMENUBARINFO));
- mbi.cbSize = sizeof(qt_SHMENUBARINFO);
- mbi.hwndParent = parentHandle;
- mbi.hInstRes = resourceHandle;
- mbi.dwFlags = flags;
- mbi.nToolBarId = toolbarID;
-
- if (ptrCreateMenuBar(&mbi)) {
-#ifdef Q_OS_WINCE_WM
- // Tell the menu bar that we want to override hot key behaviour.
- LPARAM lparam = MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY,
- SHMBOF_NODEFAULT | SHMBOF_NOTIFY);
- SendMessage(mbi.hwndMB, SHCMBM_OVERRIDEKEY, VK_TBACK, lparam);
-#endif
- return mbi.hwndMB;
- }
- }
- return 0;
-}
-
-static void qt_wce_insert_action(HMENU menu, QWceMenuAction *action)
-{
- Q_ASSERT_X(menu, "AppendMenu", "menu is 0");
- if (action->action->isVisible()) {
- int flags;
- action->action->isEnabled() ? flags = MF_ENABLED : flags = MF_GRAYED;
-
- QString text = action->action->iconText();
- text.remove(QChar::fromLatin1('&'));
- if (action->action->isSeparator()) {
- AppendMenu (menu, MF_SEPARATOR , 0, 0);
- }
- else if (action->action->menu()) {
- text.remove(QChar::fromLatin1('&'));
- AppendMenu (menu, MF_STRING | flags | MF_POPUP,
- (UINT) action->action->menu()->wceMenu(), reinterpret_cast<const wchar_t *> (text.utf16()));
- }
- else {
- AppendMenu (menu, MF_STRING | flags, action->command, reinterpret_cast<const wchar_t *> (text.utf16()));
- }
- if (action->action->isCheckable())
- if (action->action->isChecked())
- CheckMenuItem(menu, action->command, MF_BYCOMMAND | MF_CHECKED);
- else
- CheckMenuItem(menu, action->command, MF_BYCOMMAND | MF_UNCHECKED);
- }
-}
-
-// Removes all items from the menu without destroying the handles.
-static void qt_wce_clear_menu(HMENU hMenu)
-{
- while (RemoveMenu(hMenu, 0, MF_BYPOSITION));
-}
-
-/*!
- \internal
-
- This function refreshes the native Windows CE menu.
-*/
-
-void QMenuBar::wceRefresh()
-{
- for (int i = 0; i < nativeMenuBars.size(); ++i)
- nativeMenuBars.at(i)->d_func()->wceRefresh();
-}
-
-void QMenuBarPrivate::wceRefresh()
-{
- DrawMenuBar(wce_menubar->menubarHandle);
-}
-
-/*!
- \internal
-
- This function sends native Windows CE commands to Qt menus.
-*/
-
-QAction* QMenu::wceCommands(uint command)
-{
- Q_D(QMenu);
- return d->wceCommands(command);
-}
-
-/*!
- \internal
-
- This function sends native Windows CE commands to Qt menu bars
- and all their child menus.
-*/
-
-void QMenuBar::wceCommands(uint command)
-{
- const HWND hwndActiveWindow = GetActiveWindow();
- for (int i = 0; i < nativeMenuBars.size(); ++i) {
- QMenuBarPrivate* nativeMenuBar = nativeMenuBars.at(i)->d_func();
- if (hwndActiveWindow == nativeMenuBar->wce_menubar->parentWindowHandle)
- nativeMenuBar->wceCommands(command);
- }
-}
-
-bool QMenuBarPrivate::wceEmitSignals(QList<QWceMenuAction*> actions, uint command)
-{
- QAction *foundAction = 0;
- for (int i = 0; i < actions.size(); ++i) {
- QWceMenuAction *action = actions.at(i);
- if (action->action->menu()) {
- foundAction = action->action->menu()->wceCommands(command);
- if (foundAction)
- break;
- }
- else if (action->command == command) {
- action->action->activate(QAction::Trigger);
- return true;
- }
- }
- if (foundAction) {
- emit q_func()->triggered(foundAction);
- return true;
- }
- return false;
-}
-
-void QMenuBarPrivate::wceCommands(uint command)
-{
- if (wceClassicMenu) {
- for (int i = 0; i < wce_menubar->actionItemsClassic.size(); ++i)
- wceEmitSignals(wce_menubar->actionItemsClassic.at(i), command);
- } else {
- if (wceEmitSignals(wce_menubar->actionItems, command)) {
- return;
- }
- else if (wce_menubar->leftButtonIsMenu) {//check if command is on the left quick button
- wceEmitSignals(wce_menubar->actionItemsLeftButton, command);
- }
- else if ((wce_menubar->leftButtonAction) && (command == wce_menubar->leftButtonCommand)) {
- emit q_func()->triggered(wce_menubar->leftButtonAction);
- wce_menubar->leftButtonAction->activate(QAction::Trigger);
- }
- }
-}
-
-QAction *QMenuPrivate::wceCommands(uint command)
-{
- QAction *foundAction = 0;
- for (int i = 0; i < wce_menu->actionItems.size(); ++i) {
- if (foundAction)
- break;
- QWceMenuAction *action = wce_menu->actionItems.at(i);
- if (action->action->menu()) {
- foundAction = action->action->menu()->d_func()->wceCommands(command);
- }
- else if (action->command == command) {
- activateAction(action->action, QAction::Trigger);
- return action->action;
- }
- }
- if (foundAction)
- emit q_func()->triggered(foundAction);
- return foundAction;
-}
-
-void QMenuBarPrivate::wceCreateMenuBar(QWidget *parent)
-{
- Q_Q(QMenuBar);
- wce_menubar = new QWceMenuBarPrivate(this);
-
- wce_menubar->parentWindowHandle = parent ? parent->winId() : q->winId();
- wce_menubar->leftButtonAction = defaultAction;
-
- wce_menubar->menubarHandle = qt_wce_create_menubar(wce_menubar->parentWindowHandle, (HINSTANCE)qWinAppInst(), 0, SHCMBF_EMPTYBAR);
- Q_ASSERT_X(wce_menubar->menubarHandle, "wceCreateMenuBar", "cannot create empty menu bar");
- DrawMenuBar(wce_menubar->menubarHandle);
- nativeMenuBars.append(q);
- wceClassicMenu = (!qt_wince_is_smartphone() && !qt_wince_is_pocket_pc());
-}
-
-void QMenuBarPrivate::wceDestroyMenuBar()
-{
- Q_Q(QMenuBar);
- int index = nativeMenuBars.indexOf(q);
- nativeMenuBars.removeAt(index);
- if (wce_menubar) {
- delete wce_menubar;
- wce_menubar = 0;
- }
-}
-
-QMenuBarPrivate::QWceMenuBarPrivate::QWceMenuBarPrivate(QMenuBarPrivate *menubar)
-: menubarHandle(0), menuHandle(0), leftButtonMenuHandle(0),
- leftButtonAction(0), leftButtonIsMenu(false), d(menubar)
-{
-}
-
-QMenuBarPrivate::QWceMenuBarPrivate::~QWceMenuBarPrivate()
-{
- if (menubarHandle)
- DestroyWindow(menubarHandle);
- qt_wce_delete_action_list(&actionItems);
- qt_wce_delete_action_list(&actionItemsLeftButton);
-
- for (int i=0; i<actionItemsClassic.size(); ++i)
- if (!actionItemsClassic.value(i).empty())
- qt_wce_delete_action_list(&actionItemsClassic[i]);
- actionItemsClassic.clear();
-
- menubarHandle = 0;
- menuHandle = 0;
- leftButtonMenuHandle = 0;
- leftButtonCommand = 0;
- QMenuBar::wceRefresh();
-}
-
-QMenuPrivate::QWceMenuPrivate::QWceMenuPrivate()
-: menuHandle(0)
-{
-}
-
-QMenuPrivate::QWceMenuPrivate::~QWceMenuPrivate()
-{
- qt_wce_delete_action_list(&actionItems);
- if (menuHandle)
- DestroyMenu(menuHandle);
-}
-
-void QMenuPrivate::QWceMenuPrivate::addAction(QAction *a, QWceMenuAction *before)
-{
- QWceMenuAction *action = new QWceMenuAction;
- action->action = a;
- action->command = qt_wce_menu_static_cmd_id++;
- addAction(action, before);
-}
-
-void QMenuPrivate::QWceMenuPrivate::addAction(QWceMenuAction *action, QWceMenuAction *before)
-{
- if (!action)
- return;
- int before_index = actionItems.indexOf(before);
- if (before_index < 0) {
- before = 0;
- before_index = actionItems.size();
- }
- actionItems.insert(before_index, action);
- rebuild();
-}
-
-/*!
- \internal
-
- This function will return the HMENU used to create the native
- Windows CE menu bar bindings.
-*/
-
-HMENU QMenu::wceMenu()
-{
- return d_func()->wceMenu();
-}
-
-HMENU QMenuPrivate::wceMenu()
-{
- if (!wce_menu)
- wce_menu = new QWceMenuPrivate;
- if (!wce_menu->menuHandle)
- wce_menu->rebuild();
- return wce_menu->menuHandle;
-}
-
-void QMenuPrivate::QWceMenuPrivate::rebuild()
-{
- if (!menuHandle)
- menuHandle = CreatePopupMenu();
- else
- qt_wce_clear_menu(menuHandle);
-
- for (int i = 0; i < actionItems.size(); ++i) {
- QWceMenuAction *action = actionItems.at(i);
- action->menuHandle = menuHandle;
- qt_wce_insert_action(menuHandle, action);
- }
- QMenuBar::wceRefresh();
-}
-
-void QMenuPrivate::QWceMenuPrivate::syncAction(QWceMenuAction *)
-{
- rebuild();
-}
-
-void QMenuPrivate::QWceMenuPrivate::removeAction(QWceMenuAction *action)
-{
- actionItems.removeAll(action);
- delete action;
- rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::addAction(QAction *a, QWceMenuAction *before)
-{
- QWceMenuAction *action = new QWceMenuAction;
- action->action = a;
- action->command = qt_wce_menu_static_cmd_id++;
- addAction(action, before);
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::addAction(QWceMenuAction *action, QWceMenuAction *before)
-{
- if (!action)
- return;
- int before_index = actionItems.indexOf(before);
- if (before_index < 0) {
- before = 0;
- before_index = actionItems.size();
- }
- actionItems.insert(before_index, action);
- rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::syncAction(QWceMenuAction*)
-{
- QMenuBar::wceRefresh();
- rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::removeAction(QWceMenuAction *action)
-{
- actionItems.removeAll(action);
- delete action;
- rebuild();
-}
-
-void QMenuBarPrivate::_q_updateDefaultAction()
-{
- if (wce_menubar)
- wce_menubar->rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::rebuild()
-{
- d->q_func()->resize(0,0);
- parentWindowHandle = d->q_func()->parentWidget() ? d->q_func()->parentWidget()->winId() : d->q_func()->winId();
- if (d->wceClassicMenu) {
- QList<QAction*> actions = d->actions;
- int maxEntries;
- int resourceHandle;
- if (actions.size() < 5) {
- maxEntries = 4;
- resourceHandle = IDR_MAIN_MENU3;
- } else if (actions.size() < 7) {
- maxEntries = 6;
- resourceHandle = IDR_MAIN_MENU4;
- }
- else {
- maxEntries = 8;
- resourceHandle = IDR_MAIN_MENU5;
- }
- Q_ASSERT_X(menubarHandle, "rebuild !created", "menubar already deleted");
- qt_wce_clear_menu(menuHandle);
- DestroyWindow(menubarHandle);
- menubarHandle = qt_wce_create_menubar(parentWindowHandle, qt_wce_get_module_handle(), resourceHandle);
- Q_ASSERT_X(menubarHandle, "rebuild classic menu", "cannot create menubar from resource");
- DrawMenuBar(menubarHandle);
- QList<int> menu_ids;
- QList<int> item_ids;
- menu_ids << IDM_MENU1 << IDM_MENU2 << IDM_MENU3 << IDM_MENU4 << IDM_MENU5 << IDM_MENU6 << IDM_MENU7 << IDM_MENU8;
- item_ids << IDM_ITEM1 << IDM_ITEM2 << IDM_ITEM3 << IDM_ITEM4 << IDM_ITEM5 << IDM_ITEM6 << IDM_ITEM7 << IDM_ITEM8;
-
- for (int i = 0; i < actionItemsClassic.size(); ++i)
- if (!actionItemsClassic.value(i).empty())
- qt_wce_delete_action_list(&actionItemsClassic[i]);
- actionItemsClassic.clear();
-
- for (int i = 0; i < actions.size(); ++i) {
- qt_wce_rename_menu_item(menubarHandle, menu_ids.at(i), actions.at(i)->text());
- QList<QAction *> subActions = actions.at(i)->menu()->actions();
- HMENU subMenuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0 , menu_ids.at(i));
- DeleteMenu(subMenuHandle, item_ids.at(i), MF_BYCOMMAND);
- for (int c = 0; c < subActions.size(); ++c) {
- QList<QWceMenuAction*> list;
- actionItemsClassic.append(list);
- QWceMenuAction *action = new QWceMenuAction;
- action->action = subActions.at(c);
- action->command = qt_wce_menu_static_cmd_id++;
- action->menuHandle = subMenuHandle;
- actionItemsClassic.last().append(action);
- qt_wce_insert_action(subMenuHandle, action);
- }
- }
- for (int i = actions.size();i<maxEntries;++i) {
- qt_wce_rename_menu_item(menubarHandle, menu_ids.at(i), QString());
- qt_wce_disable_soft_key(menubarHandle, menu_ids.at(i));
- }
- } else {
- leftButtonAction = d->defaultAction;
- if (!leftButtonAction)
- leftButtonAction = qt_wce_get_quit_action(actionItems);
-
- leftButtonIsMenu = (leftButtonAction && leftButtonAction->menu());
- Q_ASSERT_X(menubarHandle, "rebuild !created", "menubar already deleted");
- qt_wce_clear_menu(menuHandle);
- DestroyWindow(menubarHandle);
- if (leftButtonIsMenu) {
- menubarHandle = qt_wce_create_menubar(parentWindowHandle, qt_wce_get_module_handle(), IDR_MAIN_MENU2);
- Q_ASSERT_X(menubarHandle, "rebuild !created left menubar", "cannot create menubar from resource");
- menuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0,IDM_MENU);
- Q_ASSERT_X(menuHandle, "rebuild !created", "IDM_MENU not found - invalid resource?");
- DeleteMenu(menuHandle, IDM_ABOUT, MF_BYCOMMAND);
- leftButtonMenuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0,IDM_LEFTMENU);
- Q_ASSERT_X(leftButtonMenuHandle, "rebuild !created", "IDM_LEFTMENU not found - invalid resource?");
- DeleteMenu(leftButtonMenuHandle, IDM_VIEW, MF_BYCOMMAND);
- } else {
- menubarHandle = qt_wce_create_menubar(parentWindowHandle, qt_wce_get_module_handle(), IDR_MAIN_MENU);
- Q_ASSERT_X(menubarHandle, "rebuild !created no left menubar", "cannot create menubar from resource");
- menuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0,IDM_MENU);
- Q_ASSERT_X(menuHandle, "rebuild !created", "IDM_MENU not found - invalid resource?");
- DeleteMenu(menuHandle, IDM_ABOUT, MF_BYCOMMAND);
- leftButtonMenuHandle = 0;
- leftButtonCommand = qt_wce_menu_static_cmd_id++;
- qt_wce_change_command(menubarHandle, IDM_EXIT, leftButtonCommand);
- }
-
- if (actionItems.size() == 0) {
- qt_wce_rename_menu_item(menubarHandle, IDM_MENU, QLatin1String(""));
- qt_wce_disable_soft_key(menubarHandle, IDM_MENU);
- }
- for (int i = 0; i < actionItems.size(); ++i) {
- QWceMenuAction *action = actionItems.at(i);
- action->menuHandle = menuHandle;
- qt_wce_insert_action(menuHandle, action);
- }
- if (!leftButtonIsMenu) {
- if (leftButtonAction) {
- qt_wce_rename_menu_item(menubarHandle, leftButtonCommand, leftButtonAction->text());
- qt_wce_enable_soft_key(menubarHandle, leftButtonCommand);
- } else {
- qt_wce_rename_menu_item(menubarHandle, leftButtonCommand, QLatin1String(""));
- qt_wce_disable_soft_key(menubarHandle, leftButtonCommand);
- }
- } else {
- qt_wce_rename_menu_item(menubarHandle, IDM_LEFTMENU, leftButtonAction->text());
- QList<QAction *> actions = leftButtonAction->menu()->actions();
- qt_wce_delete_action_list(&actionItemsLeftButton);
- for (int i=0; i<actions.size(); ++i) {
- QWceMenuAction *action = new QWceMenuAction;
- action->action = actions.at(i);
- action->command = qt_wce_menu_static_cmd_id++;
- action->menuHandle = leftButtonMenuHandle;
- actionItemsLeftButton.append(action);
- qt_wce_insert_action(leftButtonMenuHandle, action);
- }
- }
- }
- DrawMenuBar(menubarHandle);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_MENUBAR
-#endif //Q_WS_WINCE
diff --git a/src/gui/widgets/qmenu_wince.rc b/src/gui/widgets/qmenu_wince.rc
deleted file mode 100644
index 2540d9f43a..0000000000
--- a/src/gui/widgets/qmenu_wince.rc
+++ /dev/null
@@ -1,231 +0,0 @@
-#include "qmenu_wince_resource_p.h"
-
-#include <commctrl.h>
-#include "winuser.h"
-
-#if defined (_DEBUG) && defined(QT_DLL)
-#include "QtGuid_resource.rc"
-#elif defined(QT_DLL)
-#include "QtGui_resource.rc"
-#endif
-
-#define DIALOGEX DIALOG DISCARDABLE
-#define SHMENUBAR RCDATA
-#define I_IMAGENONE (-2)
-#define NOMENU 0xFFFF
-
-IDR_MAIN_MENU MENU DISCARDABLE
-BEGIN
- POPUP "Menu"
- BEGIN
- MENUITEM "About", IDM_ABOUT
- END
-END
-
-IDR_MAIN_MENU2 MENU DISCARDABLE
-BEGIN
- POPUP "Menu"
- BEGIN
- MENUITEM "About", IDM_ABOUT
- END
- POPUP "Display"
- BEGIN
- MENUITEM "View", IDM_VIEW
- END
-END
-
-
-IDR_MAIN_MENU3 MENU DISCARDABLE
-BEGIN
- POPUP "Menu1"
- BEGIN
- MENUITEM "Item1", IDM_ITEM1
- END
- POPUP "Menu2"
- BEGIN
- MENUITEM "Item2", IDM_ITEM2
- END
- POPUP "Menu3"
- BEGIN
- MENUITEM "Item3", IDM_ITEM3
- END
- POPUP "Menu4"
- BEGIN
- MENUITEM "Item4", IDM_ITEM4
- END
-END
-
-IDR_MAIN_MENU4 MENU DISCARDABLE
-BEGIN
- POPUP "Menu1"
- BEGIN
- MENUITEM "Item1", IDM_ITEM1
- END
- POPUP "Menu2"
- BEGIN
- MENUITEM "Item2", IDM_ITEM2
- END
- POPUP "Menu3"
- BEGIN
- MENUITEM "Item3", IDM_ITEM3
- END
- POPUP "Menu4"
- BEGIN
- MENUITEM "Item4", IDM_ITEM4
- END
- POPUP "Menu5"
- BEGIN
- MENUITEM "Item5", IDM_ITEM5
- END
- POPUP "Menu6"
- BEGIN
- MENUITEM "Item6", IDM_ITEM6
- END
-END
-
-IDR_MAIN_MENU5 MENU DISCARDABLE
-BEGIN
- POPUP "Menu1"
- BEGIN
- MENUITEM "Item1", IDM_ITEM1
- END
- POPUP "Menu2"
- BEGIN
- MENUITEM "Item2", IDM_ITEM2
- END
- POPUP "Menu3"
- BEGIN
- MENUITEM "Item3", IDM_ITEM3
- END
- POPUP "Menu4"
- BEGIN
- MENUITEM "Item4", IDM_ITEM4
- END
- POPUP "Menu5"
- BEGIN
- MENUITEM "Item5", IDM_ITEM5
- END
- POPUP "Menu6"
- BEGIN
- MENUITEM "Item6", IDM_ITEM6
- END
- POPUP "Menu7"
- BEGIN
- MENUITEM "Item7", IDM_ITEM7
- END
- POPUP "Menu8"
- BEGIN
- MENUITEM "Item8", IDM_ITEM8
- END
-END
-
-STRINGTABLE
-BEGIN
- IDS_EXIT "Exit"
- IDS_MENU "Menu"
- IDS_LEFTMENU "Display"
- IDS_MENU1 "Menu__1"
- IDS_MENU2 "Menu__2"
- IDS_MENU3 "Menu__3"
- IDS_MENU4 "Menu__4"
- IDS_MENU5 "Menu__5"
- IDS_MENU6 "Menu__6"
- IDS_MENU7 "Menu__7"
- IDS_MENU8 "Menu__8"
-END
-
-IDR_MAIN_MENU SHMENUBAR DISCARDABLE
-BEGIN
- IDR_MAIN_MENU,
- 2,
-
- I_IMAGENONE, IDM_EXIT, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE,
- IDS_EXIT, 0, NOMENU,
-
- I_IMAGENONE, IDM_MENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU, 0, 0,
-END
-
-IDR_MAIN_MENU2 SHMENUBAR DISCARDABLE
-BEGIN
- IDR_MAIN_MENU2,
- 2,
-
- I_IMAGENONE, IDM_LEFTMENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_LEFTMENU, 0, 1,
-
- I_IMAGENONE, IDM_MENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU, 0, 0,
-END
-
-IDR_MAIN_MENU3 SHMENUBAR DISCARDABLE
-BEGIN
- IDR_MAIN_MENU3,
- 4,
-
- I_IMAGENONE, IDM_MENU1, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU1, 0, 0,
-
- I_IMAGENONE, IDM_MENU2, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU2, 0, 1,
-
- I_IMAGENONE, IDM_MENU3, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU3, 0, 2,
-
- I_IMAGENONE, IDM_MENU4, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU4, 0, 3,
-END
-
-IDR_MAIN_MENU4 SHMENUBAR DISCARDABLE
-BEGIN
- IDR_MAIN_MENU4,
- 6,
-
- I_IMAGENONE, IDM_MENU1, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU1, 0, 0,
-
- I_IMAGENONE, IDM_MENU2, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU2, 0, 1,
-
- I_IMAGENONE, IDM_MENU3, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU3, 0, 2,
-
- I_IMAGENONE, IDM_MENU4, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU4, 0, 3,
-
- I_IMAGENONE, IDM_MENU5, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU5, 0, 4,
-
- I_IMAGENONE, IDM_MENU6, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU6, 0, 5,
-END
-
-IDR_MAIN_MENU5 SHMENUBAR DISCARDABLE
-BEGIN
- IDR_MAIN_MENU5,
- 8,
-
- I_IMAGENONE, IDM_MENU1, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU1, 0, 0,
-
- I_IMAGENONE, IDM_MENU2, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU2, 0, 1,
-
- I_IMAGENONE, IDM_MENU3, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU3, 0, 2,
-
- I_IMAGENONE, IDM_MENU4, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU4, 0, 3,
-
- I_IMAGENONE, IDM_MENU5, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU5, 0, 4,
-
- I_IMAGENONE, IDM_MENU6, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU6, 0, 5,
-
- I_IMAGENONE, IDM_MENU7, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU7, 0, 6,
-
- I_IMAGENONE, IDM_MENU8, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
- IDS_MENU8, 0, 7,
-END
diff --git a/src/gui/widgets/qmenu_wince_resource_p.h b/src/gui/widgets/qmenu_wince_resource_p.h
deleted file mode 100644
index 80de31b015..0000000000
--- a/src/gui/widgets/qmenu_wince_resource_p.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/****************************************************************************
-**
-** 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$
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_HEADER
-
-#define IDR_MAIN_MENU 102
-#define IDR_MAIN_MENU2 103
-#define IDR_MAIN_MENU3 104
-#define IDS_EXIT 105
-#define IDS_MENU 106
-#define IDS_LEFTMENU 107
-#define IDM_ABOUT 108
-#define IDM_VIEW 109
-#define IDM_ITEM1 108
-#define IDM_ITEM2 109
-#define IDM_ITEM3 110
-#define IDM_ITEM4 111
-#define IDM_ITEM5 112
-#define IDM_ITEM6 113
-#define IDM_ITEM7 114
-#define IDM_ITEM8 115
-#define IDS_MENU1 116
-#define IDS_MENU2 117
-#define IDS_MENU3 118
-#define IDS_MENU4 119
-#define IDS_MENU5 120
-#define IDS_MENU6 121
-#define IDS_MENU7 122
-#define IDS_MENU8 123
-#define IDR_MAIN_MENU4 124
-#define IDR_MAIN_MENU5 125
-#define IDM_EXIT 40000
-#define IDM_MENU 40001
-#define IDM_LEFTMENU 40002
-#define IDM_MENU1 40003
-#define IDM_MENU2 40004
-#define IDM_MENU3 40005
-#define IDM_MENU4 40006
-#define IDM_MENU5 40007
-#define IDM_MENU6 40008
-#define IDM_MENU7 40009
-#define IDM_MENU8 40010
-
-QT_END_HEADER
-
diff --git a/src/gui/widgets/qmenubar.cpp b/src/gui/widgets/qmenubar.cpp
deleted file mode 100644
index 5bfac9a646..0000000000
--- a/src/gui/widgets/qmenubar.cpp
+++ /dev/null
@@ -1,2508 +0,0 @@
-/****************************************************************************
-**
-** 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 <qmenubar.h>
-
-#include <qstyle.h>
-#include <qlayout.h>
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#ifndef QT_NO_ACCESSIBILITY
-# include <qaccessible.h>
-#endif
-#include <qpainter.h>
-#include <qstylepainter.h>
-#include <qevent.h>
-#include <qmainwindow.h>
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qwhatsthis.h>
-
-#ifndef QT_NO_MENUBAR
-
-#ifdef QT3_SUPPORT
-#include <private/qaction_p.h>
-#include <qmenudata.h>
-#endif
-
-#include "qmenu_p.h"
-#include "qmenubar_p.h"
-#include "qdebug.h"
-
-#ifdef Q_WS_WINCE
-extern bool qt_wince_is_mobile(); //defined in qguifunctions_wce.cpp
-#endif
-
-#ifdef QT_SOFTKEYS_ENABLED
-#include <private/qsoftkeymanager_p.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QMenuBarExtension : public QToolButton
-{
-public:
- explicit QMenuBarExtension(QWidget *parent);
-
- QSize sizeHint() const;
- void paintEvent(QPaintEvent *);
-};
-
-QMenuBarExtension::QMenuBarExtension(QWidget *parent)
- : QToolButton(parent)
-{
- setObjectName(QLatin1String("qt_menubar_ext_button"));
- setAutoRaise(true);
-#ifndef QT_NO_MENU
- setPopupMode(QToolButton::InstantPopup);
-#endif
- setIcon(style()->standardIcon(QStyle::SP_ToolBarHorizontalExtensionButton, 0, parentWidget()));
-}
-
-void QMenuBarExtension::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
- // We do not need to draw both extension arrows
- opt.features &= ~QStyleOptionToolButton::HasMenu;
- p.drawComplexControl(QStyle::CC_ToolButton, opt);
-}
-
-
-QSize QMenuBarExtension::sizeHint() const
-{
- int ext = style()->pixelMetric(QStyle::PM_ToolBarExtensionExtent, 0, parentWidget());
- return QSize(ext, ext);
-}
-
-
-/*!
- \internal
-*/
-QAction *QMenuBarPrivate::actionAt(QPoint p) const
-{
- for(int i = 0; i < actions.size(); ++i) {
- if(actionRect(actions.at(i)).contains(p))
- return actions.at(i);
- }
- return 0;
-}
-
-QRect QMenuBarPrivate::menuRect(bool extVisible) const
-{
- Q_Q(const QMenuBar);
-
- int hmargin = q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q);
- QRect result = q->rect();
- result.adjust(hmargin, 0, -hmargin, 0);
-
- if (extVisible) {
- if (q->isRightToLeft())
- result.setLeft(result.left() + extension->sizeHint().width());
- else
- result.setWidth(result.width() - extension->sizeHint().width());
- }
-
- if (leftWidget && leftWidget->isVisible()) {
- QSize sz = leftWidget->sizeHint();
- if (q->isRightToLeft())
- result.setRight(result.right() - sz.width());
- else
- result.setLeft(result.left() + sz.width());
- }
-
- if (rightWidget && rightWidget->isVisible()) {
- QSize sz = rightWidget->sizeHint();
- if (q->isRightToLeft())
- result.setLeft(result.left() + sz.width());
- else
- result.setRight(result.right() - sz.width());
- }
-
- return result;
-}
-
-bool QMenuBarPrivate::isVisible(QAction *action)
-{
- return !hiddenActions.contains(action);
-}
-
-void QMenuBarPrivate::updateGeometries()
-{
- Q_Q(QMenuBar);
- if(!itemsDirty)
- return;
- int q_width = q->width()-(q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q)*2);
- int q_start = -1;
- if(leftWidget || rightWidget) {
- int vmargin = q->style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, q)
- + q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q);
- int hmargin = q->style()->pixelMetric(QStyle::PM_MenuBarHMargin, 0, q)
- + q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q);
- if (leftWidget && leftWidget->isVisible()) {
- QSize sz = leftWidget->sizeHint();
- q_width -= sz.width();
- q_start = sz.width();
- QPoint pos(hmargin, (q->height() - leftWidget->height()) / 2);
- QRect vRect = QStyle::visualRect(q->layoutDirection(), q->rect(), QRect(pos, sz));
- leftWidget->setGeometry(vRect);
- }
- if (rightWidget && rightWidget->isVisible()) {
- QSize sz = rightWidget->sizeHint();
- q_width -= sz.width();
- QPoint pos(q->width() - sz.width() - hmargin, vmargin);
- QRect vRect = QStyle::visualRect(q->layoutDirection(), q->rect(), QRect(pos, sz));
- rightWidget->setGeometry(vRect);
- }
- }
-
-#ifdef Q_WS_MAC
- if(q->isNativeMenuBar()) {//nothing to see here folks, move along..
- itemsDirty = false;
- return;
- }
-#endif
- calcActionRects(q_width, q_start);
- currentAction = 0;
-#ifndef QT_NO_SHORTCUT
- if(itemsDirty) {
- for(int j = 0; j < shortcutIndexMap.size(); ++j)
- q->releaseShortcut(shortcutIndexMap.value(j));
- shortcutIndexMap.resize(0); // faster than clear
- for(int i = 0; i < actions.count(); i++)
- shortcutIndexMap.append(q->grabShortcut(QKeySequence::mnemonic(actions.at(i)->text())));
- }
-#endif
- itemsDirty = false;
-
- hiddenActions.clear();
- //this is the menu rectangle without any extension
- QRect menuRect = this->menuRect(false);
-
- //we try to see if the actions will fit there
- bool hasHiddenActions = false;
- for (int i = 0; i < actions.count(); ++i) {
- const QRect &rect = actionRects.at(i);
- if (rect.isValid() && !menuRect.contains(rect)) {
- hasHiddenActions = true;
- break;
- }
- }
-
- //...and if not, determine the ones that fit on the menu with the extension visible
- if (hasHiddenActions) {
- menuRect = this->menuRect(true);
- for (int i = 0; i < actions.count(); ++i) {
- const QRect &rect = actionRects.at(i);
- if (rect.isValid() && !menuRect.contains(rect)) {
- hiddenActions.append(actions.at(i));
- }
- }
- }
-
- if (hiddenActions.count() > 0) {
- QMenu *pop = extension->menu();
- if (!pop) {
- pop = new QMenu(q);
- extension->setMenu(pop);
- }
- pop->clear();
- pop->addActions(hiddenActions);
-
- int vmargin = q->style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, q);
- int x = q->isRightToLeft()
- ? menuRect.left() - extension->sizeHint().width() + 1
- : menuRect.right();
- extension->setGeometry(x, vmargin, extension->sizeHint().width(), menuRect.height() - vmargin*2);
- extension->show();
- } else {
- extension->hide();
- }
- q->updateGeometry();
-#ifdef QT3_SUPPORT
- if (parent) {
- QMenubarUpdatedEvent menubarUpdated(q);
- QApplication::sendEvent(parent, &menubarUpdated);
- }
-#endif
-}
-
-QRect QMenuBarPrivate::actionRect(QAction *act) const
-{
- const int index = actions.indexOf(act);
-
- //makes sure the geometries are up-to-date
- const_cast<QMenuBarPrivate*>(this)->updateGeometries();
-
- if (index < 0 || index >= actionRects.count())
- return QRect(); // that can happen in case of native menubar
-
- return actionRects.at(index);
-}
-
-void QMenuBarPrivate::focusFirstAction()
-{
- if(!currentAction) {
- updateGeometries();
- int index = 0;
- while (index < actions.count() && actionRects.at(index).isNull()) ++index;
- if (index < actions.count())
- setCurrentAction(actions.at(index));
- }
-}
-
-void QMenuBarPrivate::setKeyboardMode(bool b)
-{
- Q_Q(QMenuBar);
- if (b && !q->style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, 0, q)) {
- setCurrentAction(0);
- return;
- }
- keyboardState = b;
- if(b) {
- QWidget *fw = QApplication::focusWidget();
- if (fw != q)
- keyboardFocusWidget = fw;
- focusFirstAction();
- q->setFocus(Qt::MenuBarFocusReason);
- } else {
- if(!popupState)
- setCurrentAction(0);
- if(keyboardFocusWidget) {
- if (QApplication::focusWidget() == q)
- keyboardFocusWidget->setFocus(Qt::MenuBarFocusReason);
- keyboardFocusWidget = 0;
- }
- }
- q->update();
-}
-
-void QMenuBarPrivate::popupAction(QAction *action, bool activateFirst)
-{
- Q_Q(QMenuBar);
- if(!action || !action->menu() || closePopupMode)
- return;
- popupState = true;
- if (action->isEnabled() && action->menu()->isEnabled()) {
- closePopupMode = 0;
- activeMenu = action->menu();
- activeMenu->d_func()->causedPopup.widget = q;
- activeMenu->d_func()->causedPopup.action = action;
-
- QRect adjustedActionRect = actionRect(action);
- QPoint pos(q->mapToGlobal(QPoint(adjustedActionRect.left(), adjustedActionRect.bottom() + 1)));
- QSize popup_size = activeMenu->sizeHint();
-
- //we put the popup menu on the screen containing the bottom-center of the action rect
- QRect screenRect = QApplication::desktop()->screenGeometry(pos + QPoint(adjustedActionRect.width() / 2, 0));
- pos = QPoint(qMax(pos.x(), screenRect.x()), qMax(pos.y(), screenRect.y()));
-
- const bool fitUp = (q->mapToGlobal(adjustedActionRect.topLeft()).y() >= popup_size.height());
- const bool fitDown = (pos.y() + popup_size.height() <= screenRect.bottom());
- const bool rtl = q->isRightToLeft();
- const int actionWidth = adjustedActionRect.width();
-
- if (!fitUp && !fitDown) { //we should shift the menu
- bool shouldShiftToRight = !rtl;
- if (rtl && popup_size.width() > pos.x())
- shouldShiftToRight = true;
- else if (actionWidth + popup_size.width() + pos.x() > screenRect.right())
- shouldShiftToRight = false;
-
- if (shouldShiftToRight) {
- pos.rx() += actionWidth + (rtl ? popup_size.width() : 0);
- } else {
- //shift to left
- if (!rtl)
- pos.rx() -= popup_size.width();
- }
- } else if (rtl) {
- pos.rx() += actionWidth;
- }
-
- if(!defaultPopDown || (fitUp && !fitDown))
- pos.setY(qMax(screenRect.y(), q->mapToGlobal(QPoint(0, adjustedActionRect.top()-popup_size.height())).y()));
- activeMenu->popup(pos);
- if(activateFirst)
- activeMenu->d_func()->setFirstActionActive();
- }
- q->update(actionRect(action));
-}
-
-void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activateFirst)
-{
- if(currentAction == action && popup == popupState)
- return;
-
- autoReleaseTimer.stop();
-
- doChildEffects = (popup && !activeMenu);
- Q_Q(QMenuBar);
- QWidget *fw = 0;
- if(QMenu *menu = activeMenu) {
- activeMenu = 0;
- if (popup) {
- fw = q->window()->focusWidget();
- q->setFocus(Qt::NoFocusReason);
- }
- menu->hide();
- }
-
- if(currentAction)
- q->update(actionRect(currentAction));
-
- popupState = popup;
-#ifndef QT_NO_STATUSTIP
- QAction *previousAction = currentAction;
-#endif
- currentAction = action;
- if (action) {
- activateAction(action, QAction::Hover);
- if(popup)
- popupAction(action, activateFirst);
- q->update(actionRect(action));
-#ifndef QT_NO_STATUSTIP
- } else if (previousAction) {
- QString empty;
- QStatusTipEvent tip(empty);
- QApplication::sendEvent(q, &tip);
-#endif
- }
- if (fw)
- fw->setFocus(Qt::NoFocusReason);
-}
-
-void QMenuBarPrivate::calcActionRects(int max_width, int start) const
-{
- Q_Q(const QMenuBar);
-
- if(!itemsDirty)
- return;
-
- //let's reinitialize the buffer
- actionRects.resize(actions.count());
- actionRects.fill(QRect());
-
- const QStyle *style = q->style();
-
- const int itemSpacing = style->pixelMetric(QStyle::PM_MenuBarItemSpacing, 0, q);
- int max_item_height = 0, separator = -1, separator_start = 0, separator_len = 0;
-
- //calculate size
- const QFontMetrics fm = q->fontMetrics();
- const int hmargin = style->pixelMetric(QStyle::PM_MenuBarHMargin, 0, q),
- vmargin = style->pixelMetric(QStyle::PM_MenuBarVMargin, 0, q),
- icone = style->pixelMetric(QStyle::PM_SmallIconSize, 0, q);
- for(int i = 0; i < actions.count(); i++) {
- QAction *action = actions.at(i);
- if(!action->isVisible())
- continue;
-
- QSize sz;
-
- //calc what I think the size is..
- if(action->isSeparator()) {
- if (style->styleHint(QStyle::SH_DrawMenuBarSeparator, 0, q))
- separator = i;
- continue; //we don't really position these!
- } else {
- const QString s = action->text();
- QIcon is = action->icon();
- // If an icon is set, only the icon is visible
- if (!is.isNull())
- sz = sz.expandedTo(QSize(icone, icone));
- else if (!s.isEmpty())
- sz = fm.size(Qt::TextShowMnemonic, s);
- }
-
- //let the style modify the above size..
- QStyleOptionMenuItem opt;
- q->initStyleOption(&opt, action);
- sz = q->style()->sizeFromContents(QStyle::CT_MenuBarItem, &opt, sz, q);
-
- if(!sz.isEmpty()) {
- { //update the separator state
- int iWidth = sz.width() + itemSpacing;
- if(separator == -1)
- separator_start += iWidth;
- else
- separator_len += iWidth;
- }
- //maximum height
- max_item_height = qMax(max_item_height, sz.height());
- //append
- actionRects[i] = QRect(0, 0, sz.width(), sz.height());
- }
- }
-
- //calculate position
- const int fw = q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, q);
- int x = fw + ((start == -1) ? hmargin : start) + itemSpacing;
- int y = fw + vmargin;
- for(int i = 0; i < actions.count(); i++) {
- QRect &rect = actionRects[i];
- if (rect.isNull())
- continue;
-
- //resize
- rect.setHeight(max_item_height);
-
- //move
- if(separator != -1 && i >= separator) { //after the separator
- int left = (max_width - separator_len - hmargin - itemSpacing) + (x - separator_start - hmargin);
- if(left < separator_start) { //wrap
- separator_start = x = hmargin;
- y += max_item_height;
- }
- rect.moveLeft(left);
- } else {
- rect.moveLeft(x);
- }
- rect.moveTop(y);
-
- //keep moving along..
- x += rect.width() + itemSpacing;
-
- //make sure we follow the layout direction
- rect = QStyle::visualRect(q->layoutDirection(), q->rect(), rect);
- }
-}
-
-void QMenuBarPrivate::activateAction(QAction *action, QAction::ActionEvent action_e)
-{
- Q_Q(QMenuBar);
- if (!action || !action->isEnabled())
- return;
- action->activate(action_e);
- if (action_e == QAction::Hover)
- action->showStatusText(q);
-
-// if(action_e == QAction::Trigger)
-// emit q->activated(action);
-// else if(action_e == QAction::Hover)
-// emit q->highlighted(action);
-}
-
-
-void QMenuBarPrivate::_q_actionTriggered()
-{
- Q_Q(QMenuBar);
- if (QAction *action = qobject_cast<QAction *>(q->sender())) {
- emit q->triggered(action);
-#ifdef QT3_SUPPORT
- emit q->activated(q->findIdForAction(action));
-#endif
- }
-}
-
-void QMenuBarPrivate::_q_actionHovered()
-{
- Q_Q(QMenuBar);
- if (QAction *action = qobject_cast<QAction *>(q->sender())) {
- emit q->hovered(action);
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- int actionIndex = actions.indexOf(action);
- ++actionIndex;
- QAccessible::updateAccessibility(q, actionIndex, QAccessible::Focus);
- QAccessible::updateAccessibility(q, actionIndex, QAccessible::Selection);
- }
-#endif //QT_NO_ACCESSIBILITY
-#ifdef QT3_SUPPORT
- emit q->highlighted(q->findIdForAction(action));
-#endif
- }
-}
-
-/*!
- Initialize \a option with the values from the menu bar and information from \a action. This method
- is useful for subclasses when they need a QStyleOptionMenuItem, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom() QMenu::initStyleOption()
-*/
-void QMenuBar::initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const
-{
- if (!option || !action)
- return;
- Q_D(const QMenuBar);
- option->palette = palette();
- option->state = QStyle::State_None;
- if (isEnabled() && action->isEnabled())
- option->state |= QStyle::State_Enabled;
- else
- option->palette.setCurrentColorGroup(QPalette::Disabled);
- option->fontMetrics = fontMetrics();
- if (d->currentAction && d->currentAction == action) {
- option->state |= QStyle::State_Selected;
- if (d->popupState && !d->closePopupMode)
- option->state |= QStyle::State_Sunken;
- }
- if (hasFocus() || d->currentAction)
- option->state |= QStyle::State_HasFocus;
- option->menuRect = rect();
- option->menuItemType = QStyleOptionMenuItem::Normal;
- option->checkType = QStyleOptionMenuItem::NotCheckable;
- option->text = action->text();
- option->icon = action->icon();
-}
-
-/*!
- \class QMenuBar
- \brief The QMenuBar class provides a horizontal menu bar.
-
- \ingroup mainwindow-classes
-
- A menu bar consists of a list of pull-down menu items. You add
- menu items with addMenu(). For example, asuming that \c menubar
- is a pointer to a QMenuBar and \c fileMenu is a pointer to a
- QMenu, the following statement inserts the menu into the menu bar:
- \snippet doc/src/snippets/code/src_gui_widgets_qmenubar.cpp 0
-
- The ampersand in the menu item's text sets Alt+F as a shortcut for
- this menu. (You can use "\&\&" to get a real ampersand in the menu
- bar.)
-
- There is no need to lay out a menu bar. It automatically sets its
- own geometry to the top of the parent widget and changes it
- appropriately whenever the parent is resized.
-
- \section1 Usage
-
- In most main window style applications you would use the
- \l{QMainWindow::}{menuBar()} function provided in QMainWindow,
- adding \l{QMenu}s to the menu bar and adding \l{QAction}s to the
- pop-up menus.
-
- Example (from the \l{mainwindows/menus}{Menus} example):
-
- \snippet examples/mainwindows/menus/mainwindow.cpp 9
-
- Menu items may be removed with removeAction().
-
- Widgets can be added to menus by using instances of the QWidgetAction
- class to hold them. These actions can then be inserted into menus
- in the usual way; see the QMenu documentation for more details.
-
- \section1 Platform Dependent Look and Feel
-
- Different platforms have different requirements for the appearance
- of menu bars and their behavior when the user interacts with them.
- For example, Windows systems are often configured so that the
- underlined character mnemonics that indicate keyboard shortcuts
- for items in the menu bar are only shown when the \gui{Alt} key is
- pressed.
-
- \table
-
- \row \o \inlineimage plastique-menubar.png A menu bar shown in the
- Plastique widget style.
-
- \o The \l{QPlastiqueStyle}{Plastique widget style}, like most
- other styles, handles the \gui{Help} menu in the same way as it
- handles any other menu.
-
- \row \o \inlineimage motif-menubar.png A menu bar shown in the
- Motif widget style.
-
- \o The \l{QMotifStyle}{Motif widget style} treats \gui{Help} menus
- in a special way, placing them at right-hand end of the menu bar.
-
- \endtable
-
- \section1 QMenuBar on Mac OS X
-
- QMenuBar on Mac OS X is a wrapper for using the system-wide menu bar.
- If you have multiple menu bars in one dialog the outermost menu bar
- (normally inside a widget with widget flag Qt::Window) will
- be used for the system-wide menu bar.
-
- Qt for Mac OS X also provides a menu bar merging feature to make
- QMenuBar conform more closely to accepted Mac OS X menu bar layout.
- The merging functionality is based on string matching the title of
- a QMenu entry. These strings are translated (using QObject::tr())
- in the "QMenuBar" context. If an entry is moved its slots will still
- fire as if it was in the original place. The table below outlines
- the strings looked for and where the entry is placed if matched:
-
- \table
- \header \i String matches \i Placement \i Notes
- \row \i about.*
- \i Application Menu | About <application name>
- \i The application name is fetched from the \c {Info.plist} file
- (see note below). If this entry is not found no About item
- will appear in the Application Menu.
- \row \i config, options, setup, settings or preferences
- \i Application Menu | Preferences
- \i If this entry is not found the Settings item will be disabled
- \row \i quit or exit
- \i Application Menu | Quit <application name>
- \i If this entry is not found a default Quit item will be
- created to call QApplication::quit()
- \endtable
-
- You can override this behavior by using the QAction::menuRole()
- property.
-
- If you want all windows in a Mac application to share one menu
- bar, you must create a menu bar that does not have a parent.
- Create a parent-less menu bar this way:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qmenubar.cpp 1
-
- \bold{Note:} Do \e{not} call QMainWindow::menuBar() to create the
- shared menu bar, because that menu bar will have the QMainWindow
- as its parent. That menu bar would only be displayed for the
- parent QMainWindow.
-
- \bold{Note:} The text used for the application name in the menu
- bar is obtained from the value set in the \c{Info.plist} file in
- the application's bundle. See \l{Deploying an Application on
- Mac OS X} for more information.
-
- \section1 QMenuBar on Windows CE
-
- QMenuBar on Windows CE is a wrapper for using the system-wide menu bar,
- similar to the Mac. This feature is activated for Windows Mobile
- and integrates QMenuBar with the native soft keys. The left soft
- key can be controlled with QMenuBar::setDefaultAction() and the
- right soft key can be used to access the menu bar.
-
- The hovered() signal is not supported for the native menu
- integration. Also, it is not possible to display an icon in a
- native menu on Windows Mobile.
-
- \section1 Examples
-
- The \l{mainwindows/menus}{Menus} example shows how to use QMenuBar
- and QMenu. The other \l{Main Window Examples}{main window
- application examples} also provide menus using these classes.
-
- \sa QMenu, QShortcut, QAction,
- {http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIntro/XHIGIntro.html}{Introduction to Apple Human Interface Guidelines},
- {fowler}{GUI Design Handbook: Menu Bar}, {Menus Example}
-*/
-
-
-void QMenuBarPrivate::init()
-{
- Q_Q(QMenuBar);
- q->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
- q->setAttribute(Qt::WA_CustomWhatsThis);
-#ifdef Q_WS_MAC
- macCreateMenuBar(q->parentWidget());
- if(mac_menubar)
- q->hide();
-#endif
-#ifdef Q_WS_WINCE
- if (qt_wince_is_mobile()) {
- wceCreateMenuBar(q->parentWidget());
- if(wce_menubar)
- q->hide();
- }
- else {
- QApplication::setAttribute(Qt::AA_DontUseNativeMenuBar, true);
- }
-#endif
- q->setBackgroundRole(QPalette::Button);
- oldWindow = oldParent = 0;
-#ifdef QT3_SUPPORT
- doAutoResize = false;
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- menuBarAction = 0;
-#endif
- handleReparent();
- q->setMouseTracking(q->style()->styleHint(QStyle::SH_MenuBar_MouseTracking, 0, q));
-
- extension = new QMenuBarExtension(q);
- extension->setFocusPolicy(Qt::NoFocus);
- extension->hide();
-}
-
-//Gets the next action for keyboard navigation
-QAction *QMenuBarPrivate::getNextAction(const int _start, const int increment) const
-{
- Q_Q(const QMenuBar);
- const_cast<QMenuBarPrivate*>(this)->updateGeometries();
- bool allowActiveAndDisabled = q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, 0, q);
- const int start = (_start == -1 && increment == -1) ? actions.count() : _start;
- const int end = increment == -1 ? 0 : actions.count() - 1;
-
- for (int i = start; i != end;) {
- i += increment;
- QAction *current = actions.at(i);
- if (!actionRects.at(i).isNull() && (allowActiveAndDisabled || current->isEnabled()))
- return current;
- }
-
- if (_start != -1) //let's try from the beginning or the end
- return getNextAction(-1, increment);
-
- return 0;
-}
-
-/*!
- Constructs a menu bar with parent \a parent.
-*/
-QMenuBar::QMenuBar(QWidget *parent) : QWidget(*new QMenuBarPrivate, parent, 0)
-{
- Q_D(QMenuBar);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QMenuBar::QMenuBar(QWidget *parent, const char *name) : QWidget(*new QMenuBarPrivate, parent, 0)
-{
- Q_D(QMenuBar);
- d->init();
- setObjectName(QString::fromAscii(name));
-}
-#endif
-
-/*!
- Destroys the menu bar.
-*/
-QMenuBar::~QMenuBar()
-{
-#ifdef Q_WS_MAC
- Q_D(QMenuBar);
- d->macDestroyMenuBar();
-#endif
-#ifdef Q_WS_WINCE
- Q_D(QMenuBar);
- if (qt_wince_is_mobile())
- d->wceDestroyMenuBar();
-#endif
-#ifdef Q_WS_S60
- Q_D(QMenuBar);
- d->symbianDestroyMenuBar();
-#endif
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with \a text.
- The function adds the newly created action to the menu's
- list of actions, and returns it.
-
- \sa QWidget::addAction(), QWidget::actions()
-*/
-QAction *QMenuBar::addAction(const QString &text)
-{
- QAction *ret = new QAction(text, this);
- addAction(ret);
- return ret;
-}
-
-/*!
- \overload
-
- This convenience function creates a new action with the given \a
- text. The action's triggered() signal is connected to the \a
- receiver's \a member slot. The function adds the newly created
- action to the menu's list of actions and returns it.
-
- \sa QWidget::addAction(), QWidget::actions()
-*/
-QAction *QMenuBar::addAction(const QString &text, const QObject *receiver, const char* member)
-{
- QAction *ret = new QAction(text, this);
- QObject::connect(ret, SIGNAL(triggered(bool)), receiver, member);
- addAction(ret);
- return ret;
-}
-
-/*!
- Appends a new QMenu with \a title to the menu bar. The menu bar
- takes ownership of the menu. Returns the new menu.
-
- \sa QWidget::addAction() QMenu::menuAction()
-*/
-QMenu *QMenuBar::addMenu(const QString &title)
-{
- QMenu *menu = new QMenu(title, this);
- addAction(menu->menuAction());
- return menu;
-}
-
-/*!
- Appends a new QMenu with \a icon and \a title to the menu bar. The menu bar
- takes ownership of the menu. Returns the new menu.
-
- \sa QWidget::addAction() QMenu::menuAction()
-*/
-QMenu *QMenuBar::addMenu(const QIcon &icon, const QString &title)
-{
- QMenu *menu = new QMenu(title, this);
- menu->setIcon(icon);
- addAction(menu->menuAction());
- return menu;
-}
-
-/*!
- Appends \a menu to the menu bar. Returns the menu's menuAction().
-
- \note The returned QAction object can be used to hide the corresponding
- menu.
-
- \sa QWidget::addAction() QMenu::menuAction()
-*/
-QAction *QMenuBar::addMenu(QMenu *menu)
-{
- QAction *action = menu->menuAction();
- addAction(action);
- return action;
-}
-
-/*!
- Appends a separator to the menu.
-*/
-QAction *QMenuBar::addSeparator()
-{
- QAction *ret = new QAction(this);
- ret->setSeparator(true);
- addAction(ret);
- return ret;
-}
-
-/*!
- This convenience function creates a new separator action, i.e. an
- action with QAction::isSeparator() returning true. The function inserts
- the newly created action into this menu bar's list of actions before
- action \a before and returns it.
-
- \sa QWidget::insertAction(), addSeparator()
-*/
-QAction *QMenuBar::insertSeparator(QAction *before)
-{
- QAction *action = new QAction(this);
- action->setSeparator(true);
- insertAction(before, action);
- return action;
-}
-
-/*!
- This convenience function inserts \a menu before action \a before
- and returns the menus menuAction().
-
- \sa QWidget::insertAction() addMenu()
-*/
-QAction *QMenuBar::insertMenu(QAction *before, QMenu *menu)
-{
- QAction *action = menu->menuAction();
- insertAction(before, action);
- return action;
-}
-
-/*!
- Returns the QAction that is currently highlighted. A null pointer
- will be returned if no action is currently selected.
-*/
-QAction *QMenuBar::activeAction() const
-{
- Q_D(const QMenuBar);
- return d->currentAction;
-}
-
-/*!
- \since 4.1
-
- Sets the currently highlighted action to \a act.
-*/
-void QMenuBar::setActiveAction(QAction *act)
-{
- Q_D(QMenuBar);
- d->setCurrentAction(act, true, false);
-}
-
-
-/*!
- Removes all the actions from the menu bar.
-
- \note On Mac OS X, menu items that have been merged to the system
- menu bar are not removed by this function. One way to handle this
- would be to remove the extra actions yourself. You can set the
- \l{QAction::MenuRole}{menu role} on the different menus, so that
- you know ahead of time which menu items get merged and which do
- not. Then decide what to recreate or remove yourself.
-
- \sa removeAction()
-*/
-void QMenuBar::clear()
-{
- QList<QAction*> acts = actions();
- for(int i = 0; i < acts.size(); i++)
- removeAction(acts[i]);
-}
-
-/*!
- \property QMenuBar::defaultUp
- \brief the popup orientation
-
- The default popup orientation. By default, menus pop "down" the
- screen. By setting the property to true, the menu will pop "up".
- You might call this for menus that are \e below the document to
- which they refer.
-
- If the menu would not fit on the screen, the other direction is
- used automatically.
-*/
-void QMenuBar::setDefaultUp(bool b)
-{
- Q_D(QMenuBar);
- d->defaultPopDown = !b;
-}
-
-bool QMenuBar::isDefaultUp() const
-{
- Q_D(const QMenuBar);
- return !d->defaultPopDown;
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::resizeEvent(QResizeEvent *)
-{
- Q_D(QMenuBar);
- d->itemsDirty = true;
- d->updateGeometries();
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::paintEvent(QPaintEvent *e)
-{
- Q_D(QMenuBar);
- QPainter p(this);
- QRegion emptyArea(rect());
-
- //draw the items
- for (int i = 0; i < d->actions.count(); ++i) {
- QAction *action = d->actions.at(i);
- QRect adjustedActionRect = d->actionRect(action);
- if (adjustedActionRect.isEmpty() || !d->isVisible(action))
- continue;
- if(!e->rect().intersects(adjustedActionRect))
- continue;
-
- emptyArea -= adjustedActionRect;
- QStyleOptionMenuItem opt;
- initStyleOption(&opt, action);
- opt.rect = adjustedActionRect;
- p.setClipRect(adjustedActionRect);
- style()->drawControl(QStyle::CE_MenuBarItem, &opt, &p, this);
- }
- //draw border
- if(int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this)) {
- QRegion borderReg;
- borderReg += QRect(0, 0, fw, height()); //left
- borderReg += QRect(width()-fw, 0, fw, height()); //right
- borderReg += QRect(0, 0, width(), fw); //top
- borderReg += QRect(0, height()-fw, width(), fw); //bottom
- p.setClipRegion(borderReg);
- emptyArea -= borderReg;
- QStyleOptionFrame frame;
- frame.rect = rect();
- frame.palette = palette();
- frame.state = QStyle::State_None;
- frame.lineWidth = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth);
- frame.midLineWidth = 0;
- style()->drawPrimitive(QStyle::PE_PanelMenuBar, &frame, &p, this);
- }
- p.setClipRegion(emptyArea);
- QStyleOptionMenuItem menuOpt;
- menuOpt.palette = palette();
- menuOpt.state = QStyle::State_None;
- menuOpt.menuItemType = QStyleOptionMenuItem::EmptyArea;
- menuOpt.checkType = QStyleOptionMenuItem::NotCheckable;
- menuOpt.rect = rect();
- menuOpt.menuRect = rect();
- style()->drawControl(QStyle::CE_MenuBarEmptyArea, &menuOpt, &p, this);
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::setVisible(bool visible)
-{
-#if defined(Q_WS_MAC) || defined(Q_OS_WINCE) || defined(Q_WS_S60)
- if (isNativeMenuBar()) {
- if (!visible)
- QWidget::setVisible(false);
- return;
- }
-#endif
- QWidget::setVisible(visible);
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QMenuBar);
- if(e->button() != Qt::LeftButton)
- return;
-
- d->mouseDown = true;
-
- QAction *action = d->actionAt(e->pos());
- if (!action || !d->isVisible(action)) {
- d->setCurrentAction(0);
-#ifndef QT_NO_WHATSTHIS
- if (QWhatsThis::inWhatsThisMode())
- QWhatsThis::showText(e->globalPos(), d->whatsThis, this);
-#endif
- return;
- }
-
- if(d->currentAction == action && d->popupState) {
- if(QMenu *menu = d->activeMenu) {
- d->activeMenu = 0;
- menu->hide();
- }
-#ifdef Q_WS_WIN
- if((d->closePopupMode = style()->styleHint(QStyle::SH_MenuBar_DismissOnSecondClick)))
- update(d->actionRect(action));
-#endif
- } else {
- d->setCurrentAction(action, true);
- }
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QMenuBar);
- if(e->button() != Qt::LeftButton || !d->mouseDown)
- return;
-
- d->mouseDown = false;
- QAction *action = d->actionAt(e->pos());
- if((d->closePopupMode && action == d->currentAction) || !action || !action->menu()) {
- //we set the current action before activating
- //so that we let the leave event set the current back to 0
- d->setCurrentAction(action, false);
- if(action)
- d->activateAction(action, QAction::Trigger);
- }
- d->closePopupMode = 0;
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QMenuBar);
- d->updateGeometries();
- int key = e->key();
- if(isRightToLeft()) { // in reverse mode open/close key for submenues are reversed
- if(key == Qt::Key_Left)
- key = Qt::Key_Right;
- else if(key == Qt::Key_Right)
- key = Qt::Key_Left;
- }
- if(key == Qt::Key_Tab) //means right
- key = Qt::Key_Right;
- else if(key == Qt::Key_Backtab) //means left
- key = Qt::Key_Left;
-
- bool key_consumed = false;
- switch(key) {
- case Qt::Key_Up:
- case Qt::Key_Down:
- case Qt::Key_Enter:
- case Qt::Key_Space:
- case Qt::Key_Return: {
- if(!style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, 0, this) || !d->currentAction)
- break;
- if(d->currentAction->menu()) {
- d->popupAction(d->currentAction, true);
- } else if(key == Qt::Key_Enter || key == Qt::Key_Return || key == Qt::Key_Space) {
- d->activateAction(d->currentAction, QAction::Trigger);
- d->setCurrentAction(d->currentAction, false);
- d->setKeyboardMode(false);
- }
- key_consumed = true;
- break; }
-
- case Qt::Key_Right:
- case Qt::Key_Left: {
- if(d->currentAction) {
- int index = d->actions.indexOf(d->currentAction);
- if (QAction *nextAction = d->getNextAction(index, key == Qt::Key_Left ? -1 : +1)) {
- d->setCurrentAction(nextAction, d->popupState, true);
- key_consumed = true;
- }
- }
- break; }
-
- case Qt::Key_Escape:
- d->setCurrentAction(0);
- d->setKeyboardMode(false);
- key_consumed = true;
- break;
-
- default:
- key_consumed = false;
- }
-
- if(!key_consumed &&
- (!e->modifiers() ||
- (e->modifiers()&(Qt::MetaModifier|Qt::AltModifier))) && e->text().length()==1 && !d->popupState) {
- int clashCount = 0;
- QAction *first = 0, *currentSelected = 0, *firstAfterCurrent = 0;
- {
- QChar c = e->text()[0].toUpper();
- for(int i = 0; i < d->actions.size(); ++i) {
- if (d->actionRects.at(i).isNull())
- continue;
- QAction *act = d->actions.at(i);
- QString s = act->text();
- if(!s.isEmpty()) {
- int ampersand = s.indexOf(QLatin1Char('&'));
- if(ampersand >= 0) {
- if(s[ampersand+1].toUpper() == c) {
- clashCount++;
- if(!first)
- first = act;
- if(act == d->currentAction)
- currentSelected = act;
- else if (!firstAfterCurrent && currentSelected)
- firstAfterCurrent = act;
- }
- }
- }
- }
- }
- QAction *next_action = 0;
- if(clashCount >= 1) {
- if(clashCount == 1 || !d->currentAction || (currentSelected && !firstAfterCurrent))
- next_action = first;
- else
- next_action = firstAfterCurrent;
- }
- if(next_action) {
- key_consumed = true;
- d->setCurrentAction(next_action, true, true);
- }
- }
- if(key_consumed)
- e->accept();
- else
- e->ignore();
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QMenuBar);
- if (!(e->buttons() & Qt::LeftButton))
- d->mouseDown = false;
- bool popupState = d->popupState || d->mouseDown;
- QAction *action = d->actionAt(e->pos());
- if ((action && d->isVisible(action)) || !popupState)
- d->setCurrentAction(action, popupState);
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::leaveEvent(QEvent *)
-{
- Q_D(QMenuBar);
- if((!hasFocus() && !d->popupState) ||
- (d->currentAction && d->currentAction->menu() == 0))
- d->setCurrentAction(0);
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::actionEvent(QActionEvent *e)
-{
- Q_D(QMenuBar);
- d->itemsDirty = true;
-#if defined (Q_WS_MAC) || defined(Q_OS_WINCE) || defined(Q_WS_S60)
- if (isNativeMenuBar()) {
-#ifdef Q_WS_MAC
- QMenuBarPrivate::QMacMenuBarPrivate *nativeMenuBar = d->mac_menubar;
-#elif defined(Q_WS_S60)
- QMenuBarPrivate::QSymbianMenuBarPrivate *nativeMenuBar = d->symbian_menubar;
-#else
- QMenuBarPrivate::QWceMenuBarPrivate *nativeMenuBar = d->wce_menubar;
-#endif
- if (!nativeMenuBar)
- return;
- if(e->type() == QEvent::ActionAdded)
- nativeMenuBar->addAction(e->action(), nativeMenuBar->findAction(e->before()));
- else if(e->type() == QEvent::ActionRemoved)
- nativeMenuBar->removeAction(e->action());
- else if(e->type() == QEvent::ActionChanged)
- nativeMenuBar->syncAction(e->action());
- }
-#endif
-
- if(e->type() == QEvent::ActionAdded) {
- connect(e->action(), SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
- connect(e->action(), SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
- } else if(e->type() == QEvent::ActionRemoved) {
- e->action()->disconnect(this);
- }
- if (isVisible()) {
- d->updateGeometries();
- update();
- }
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::focusInEvent(QFocusEvent *)
-{
- Q_D(QMenuBar);
- if(d->keyboardState)
- d->focusFirstAction();
-}
-
-/*!
- \reimp
-*/
-void QMenuBar::focusOutEvent(QFocusEvent *)
-{
- Q_D(QMenuBar);
- if(!d->popupState) {
- d->setCurrentAction(0);
- d->setKeyboardMode(false);
- }
-}
-
-/*!
- \reimp
- */
-void QMenuBar::timerEvent (QTimerEvent *e)
-{
- Q_D(QMenuBar);
- if (e->timerId() == d->autoReleaseTimer.timerId()) {
- d->autoReleaseTimer.stop();
- d->setCurrentAction(0);
- }
- QWidget::timerEvent(e);
-}
-
-
-void QMenuBarPrivate::handleReparent()
-{
- Q_Q(QMenuBar);
- QWidget *newParent = q->parentWidget();
- //Note: if parent is reparented, then window may change even if parent doesn't
-
- // we need to install an event filter on parent, and remove the old one
-
- if (oldParent != newParent) {
- if (oldParent)
- oldParent->removeEventFilter(q);
- if (newParent)
- newParent->installEventFilter(q);
- }
-
- //we also need event filter on top-level (for shortcuts)
- QWidget *newWindow = newParent ? newParent->window() : 0;
-
- if (oldWindow != newWindow) {
- if (oldParent && oldParent != oldWindow)
- oldWindow->removeEventFilter(q);
-
- if (newParent && newParent != newWindow)
- newWindow->installEventFilter(q);
- }
-
- oldParent = newParent;
- oldWindow = newWindow;
-
-#ifdef Q_WS_MAC
- if (q->isNativeMenuBar() && !macWidgetHasNativeMenubar(newParent)) {
- // If the new parent got a native menubar from before, keep that
- // menubar rather than replace it with this one (because a parents
- // menubar has precedence over children menubars).
- macDestroyMenuBar();
- macCreateMenuBar(newParent);
- }
-#endif
-
-#ifdef Q_WS_WINCE
- if (qt_wince_is_mobile() && wce_menubar)
- wce_menubar->rebuild();
-#endif
-#ifdef Q_WS_S60
-
- // Construct symbian_menubar when this code path is entered first time
- // and when newParent != NULL
- if (!symbian_menubar)
- symbianCreateMenuBar(newParent);
-
- // Reparent and rebuild menubar when parent is changed
- if (symbian_menubar) {
- if (oldParent != newParent)
- reparentMenuBar(oldParent, newParent);
- q->hide();
- symbian_menubar->rebuild();
- }
-
-#ifdef QT_SOFTKEYS_ENABLED
- // Constuct menuBarAction when this code path is entered first time
- if (!menuBarAction) {
- if (newParent) {
- menuBarAction = QSoftKeyManager::createAction(QSoftKeyManager::MenuSoftKey, newParent);
- newParent->addAction(menuBarAction);
- }
- } else {
- // If reparenting i.e. we already have menuBarAction, remove it from old parent
- // and add for a new parent
- if (oldParent)
- oldParent->removeAction(menuBarAction);
- if (newParent)
- newParent->addAction(menuBarAction);
- }
-#endif // QT_SOFTKEYS_ENABLED
-#endif // Q_WS_S60
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Sets whether the menu bar should automatically resize itself
- when its parent widget is resized.
-
- This feature is provided to help porting to Qt 4. We recommend
- against using it in new code.
-
- \sa autoGeometry()
-*/
-void QMenuBar::setAutoGeometry(bool b)
-{
- Q_D(QMenuBar);
- d->doAutoResize = b;
-}
-
-/*!
- Returns true if the menu bar automatically resizes itself
- when its parent widget is resized; otherwise returns false.
-
- This feature is provided to help porting to Qt 4. We recommend
- against using it in new code.
-
- \sa setAutoGeometry()
-*/
-bool QMenuBar::autoGeometry() const
-{
- Q_D(const QMenuBar);
- return d->doAutoResize;
-}
-#endif
-
-/*!
- \reimp
-*/
-void QMenuBar::changeEvent(QEvent *e)
-{
- Q_D(QMenuBar);
- if(e->type() == QEvent::StyleChange) {
- d->itemsDirty = true;
- setMouseTracking(style()->styleHint(QStyle::SH_MenuBar_MouseTracking, 0, this));
- if(parentWidget())
- resize(parentWidget()->width(), heightForWidth(parentWidget()->width()));
- d->updateGeometries();
- } else if (e->type() == QEvent::ParentChange) {
- d->handleReparent();
- } else if (e->type() == QEvent::FontChange
- || e->type() == QEvent::ApplicationFontChange) {
- d->itemsDirty = true;
- d->updateGeometries();
-#ifdef QT_SOFTKEYS_ENABLED
- } else if (e->type() == QEvent::LanguageChange) {
- if (d->menuBarAction)
- d->menuBarAction->setText(QSoftKeyManager::standardSoftKeyText(QSoftKeyManager::MenuSoftKey));
-#endif
- }
-
- QWidget::changeEvent(e);
-}
-
-/*!
- \reimp
-*/
-bool QMenuBar::event(QEvent *e)
-{
- Q_D(QMenuBar);
- switch (e->type()) {
- case QEvent::KeyPress: {
- QKeyEvent *ke = (QKeyEvent*)e;
-#if 0
- if(!d->keyboardState) { //all keypresses..
- d->setCurrentAction(0);
- return ;
- }
-#endif
- if(ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
- keyPressEvent(ke);
- return true;
- }
-
- } break;
-#ifndef QT_NO_SHORTCUT
- case QEvent::Shortcut: {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- int shortcutId = se->shortcutId();
- for(int j = 0; j < d->shortcutIndexMap.size(); ++j) {
- if (shortcutId == d->shortcutIndexMap.value(j))
- d->_q_internalShortcutActivated(j);
- }
- } break;
-#endif
- case QEvent::Show:
-#ifdef QT3_SUPPORT
- if(QWidget *p = parentWidget()) {
- // If itemsDirty == true, updateGeometries sends the MenubarUpdated event.
- if (!d->itemsDirty) {
- QMenubarUpdatedEvent menubarUpdated(this);
- QApplication::sendEvent(p, &menubarUpdated);
- }
- }
-#endif
- d->_q_updateLayout();
- break;
- case QEvent::ShortcutOverride: {
- QKeyEvent *kev = static_cast<QKeyEvent*>(e);
- //we only filter out escape if there is a current action
- if (kev->key() == Qt::Key_Escape && d->currentAction) {
- e->accept();
- return true;
- }
- }
- break;
-
-#ifdef QT3_SUPPORT
- case QEvent::Hide: {
- if(QWidget *p = parentWidget()) {
- QMenubarUpdatedEvent menubarUpdated(this);
- QApplication::sendEvent(p, &menubarUpdated);
- }
- } break;
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- case QEvent::QueryWhatsThis:
- e->setAccepted(d->whatsThis.size());
- if (QAction *action = d->actionAt(static_cast<QHelpEvent*>(e)->pos())) {
- if (action->whatsThis().size() || action->menu())
- e->accept();
- }
- return true;
-#endif
- case QEvent::LayoutDirectionChange:
- d->_q_updateLayout();
- break;
- default:
- break;
- }
- return QWidget::event(e);
-}
-
-/*!
- \reimp
-*/
-bool QMenuBar::eventFilter(QObject *object, QEvent *event)
-{
- Q_D(QMenuBar);
- if (object == parent() && object) {
-#ifdef QT3_SUPPORT
- if (d->doAutoResize && event->type() == QEvent::Resize) {
- QResizeEvent *e = (QResizeEvent *)event;
- int w = e->size().width();
- setGeometry(0, y(), w, heightForWidth(w));
- return false;
- }
-#endif
- if (event->type() == QEvent::ParentChange) //GrandparentChange
- d->handleReparent();
- }
- if (object == d->leftWidget || object == d->rightWidget) {
- switch (event->type()) {
- case QEvent::ShowToParent:
- case QEvent::HideToParent:
- d->_q_updateLayout();
- break;
- default:
- break;
- }
- }
-
- if (style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, 0, this)) {
- if (d->altPressed) {
- switch (event->type()) {
- case QEvent::KeyPress:
- case QEvent::KeyRelease:
- {
- QKeyEvent *kev = static_cast<QKeyEvent*>(event);
- if (kev->key() == Qt::Key_Alt || kev->key() == Qt::Key_Meta) {
- if (event->type() == QEvent::KeyPress) // Alt-press does not interest us, we have the shortcut-override event
- break;
- d->setKeyboardMode(!d->keyboardState);
- }
- }
- // fall through
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseMove:
- case QEvent::FocusIn:
- case QEvent::FocusOut:
- case QEvent::ActivationChange:
- d->altPressed = false;
- qApp->removeEventFilter(this);
- break;
- default:
- break;
- }
- } else if (isVisible()) {
- if (event->type() == QEvent::ShortcutOverride) {
- QKeyEvent *kev = static_cast<QKeyEvent*>(event);
- if ((kev->key() == Qt::Key_Alt || kev->key() == Qt::Key_Meta)
- && kev->modifiers() == Qt::AltModifier) {
- d->altPressed = true;
- qApp->installEventFilter(this);
- }
- }
- }
- }
-
- return false;
-}
-
-/*!
- Returns the QAction at \a pt. Returns 0 if there is no action at \a pt or if
-the location has a separator.
-
- \sa addAction(), addSeparator()
-*/
-QAction *QMenuBar::actionAt(const QPoint &pt) const
-{
- Q_D(const QMenuBar);
- return d->actionAt(pt);
-}
-
-/*!
- Returns the geometry of action \a act as a QRect.
-
- \sa actionAt()
-*/
-QRect QMenuBar::actionGeometry(QAction *act) const
-{
- Q_D(const QMenuBar);
- return d->actionRect(act);
-}
-
-/*!
- \reimp
-*/
-QSize QMenuBar::minimumSizeHint() const
-{
- Q_D(const QMenuBar);
-#if defined(Q_WS_MAC) || defined(Q_WS_WINCE) || defined(Q_WS_S60)
- const bool as_gui_menubar = !isNativeMenuBar();
-#else
- const bool as_gui_menubar = true;
-#endif
-
- ensurePolished();
- QSize ret(0, 0);
- const_cast<QMenuBarPrivate*>(d)->updateGeometries();
- const int hmargin = style()->pixelMetric(QStyle::PM_MenuBarHMargin, 0, this);
- const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, this);
- int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this);
- int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, 0, this);
- if(as_gui_menubar) {
- int w = parentWidget() ? parentWidget()->width() : QApplication::desktop()->width();
- d->calcActionRects(w - (2 * fw), 0);
- for (int i = 0; ret.isNull() && i < d->actions.count(); ++i)
- ret = d->actionRects.at(i).size();
- if (!d->extension->isHidden())
- ret += QSize(d->extension->sizeHint().width(), 0);
- ret += QSize(2*fw + hmargin, 2*fw + vmargin);
- }
- int margin = 2*vmargin + 2*fw + spaceBelowMenuBar;
- if(d->leftWidget) {
- QSize sz = d->leftWidget->minimumSizeHint();
- ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
- ret.setHeight(sz.height() + margin);
- }
- if(d->rightWidget) {
- QSize sz = d->rightWidget->minimumSizeHint();
- ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
- ret.setHeight(sz.height() + margin);
- }
- if(as_gui_menubar) {
- QStyleOptionMenuItem opt;
- opt.rect = rect();
- opt.menuRect = rect();
- opt.state = QStyle::State_None;
- opt.menuItemType = QStyleOptionMenuItem::Normal;
- opt.checkType = QStyleOptionMenuItem::NotCheckable;
- opt.palette = palette();
- return (style()->sizeFromContents(QStyle::CT_MenuBar, &opt,
- ret.expandedTo(QApplication::globalStrut()),
- this));
- }
- return ret;
-}
-
-/*!
- \reimp
-*/
-QSize QMenuBar::sizeHint() const
-{
- Q_D(const QMenuBar);
-#if defined(Q_WS_MAC) || defined(Q_WS_WINCE) || defined(Q_WS_S60)
- const bool as_gui_menubar = !isNativeMenuBar();
-#else
- const bool as_gui_menubar = true;
-#endif
-
-
- ensurePolished();
- QSize ret(0, 0);
- const_cast<QMenuBarPrivate*>(d)->updateGeometries();
- const int hmargin = style()->pixelMetric(QStyle::PM_MenuBarHMargin, 0, this);
- const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, this);
- int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this);
- int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, 0, this);
- if(as_gui_menubar) {
- const int w = parentWidget() ? parentWidget()->width() : QApplication::desktop()->width();
- d->calcActionRects(w - (2 * fw), 0);
- for (int i = 0; i < d->actionRects.count(); ++i) {
- const QRect &actionRect = d->actionRects.at(i);
- ret = ret.expandedTo(QSize(actionRect.x() + actionRect.width(), actionRect.y() + actionRect.height()));
- }
- //the action geometries already contain the top and left
- //margins. So we only need to add those from right and bottom.
- ret += QSize(fw + hmargin, fw + vmargin);
- }
- int margin = 2*vmargin + 2*fw + spaceBelowMenuBar;
- if(d->leftWidget) {
- QSize sz = d->leftWidget->sizeHint();
- ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
- ret.setHeight(sz.height() + margin);
- }
- if(d->rightWidget) {
- QSize sz = d->rightWidget->sizeHint();
- ret.setWidth(ret.width() + sz.width());
- if(sz.height() + margin > ret.height())
- ret.setHeight(sz.height() + margin);
- }
- if(as_gui_menubar) {
- QStyleOptionMenuItem opt;
- opt.rect = rect();
- opt.menuRect = rect();
- opt.state = QStyle::State_None;
- opt.menuItemType = QStyleOptionMenuItem::Normal;
- opt.checkType = QStyleOptionMenuItem::NotCheckable;
- opt.palette = palette();
- return (style()->sizeFromContents(QStyle::CT_MenuBar, &opt,
- ret.expandedTo(QApplication::globalStrut()),
- this));
- }
- return ret;
-}
-
-/*!
- \reimp
-*/
-int QMenuBar::heightForWidth(int) const
-{
- Q_D(const QMenuBar);
-#if defined(Q_WS_MAC) || defined(Q_WS_WINCE) || defined(Q_WS_S60)
- const bool as_gui_menubar = !isNativeMenuBar();
-#else
- const bool as_gui_menubar = true;
-#endif
-
- const_cast<QMenuBarPrivate*>(d)->updateGeometries();
- int height = 0;
- const int vmargin = style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, this);
- int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this);
- int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, 0, this);
- if(as_gui_menubar) {
- for (int i = 0; i < d->actionRects.count(); ++i)
- height = qMax(height, d->actionRects.at(i).height());
- if (height) //there is at least one non-null item
- height += spaceBelowMenuBar;
- height += 2*fw;
- height += 2*vmargin;
- }
- int margin = 2*vmargin + 2*fw + spaceBelowMenuBar;
- if(d->leftWidget)
- height = qMax(d->leftWidget->sizeHint().height() + margin, height);
- if(d->rightWidget)
- height = qMax(d->rightWidget->sizeHint().height() + margin, height);
- if(as_gui_menubar) {
- QStyleOptionMenuItem opt;
- opt.init(this);
- opt.menuRect = rect();
- opt.state = QStyle::State_None;
- opt.menuItemType = QStyleOptionMenuItem::Normal;
- opt.checkType = QStyleOptionMenuItem::NotCheckable;
- return style()->sizeFromContents(QStyle::CT_MenuBar, &opt, QSize(0, height), this).height(); //not pretty..
- }
- return height;
-}
-
-/*!
- \internal
-*/
-void QMenuBarPrivate::_q_internalShortcutActivated(int id)
-{
- Q_Q(QMenuBar);
- QAction *act = actions.at(id);
- setCurrentAction(act, true, true);
- if (act && !act->menu()) {
- activateAction(act, QAction::Trigger);
- //100 is the same as the default value in QPushButton::animateClick
- autoReleaseTimer.start(100, q);
- } else if (act && q->style()->styleHint(QStyle::SH_MenuBar_AltKeyNavigation, 0, q)) {
- // When we open a menu using a shortcut, we should end up in keyboard state
- setKeyboardMode(true);
- }
-}
-
-void QMenuBarPrivate::_q_updateLayout()
-{
- Q_Q(QMenuBar);
- itemsDirty = true;
- if (q->isVisible()) {
- updateGeometries();
- q->update();
- }
-}
-
-/*!
- \fn void QMenuBar::setCornerWidget(QWidget *widget, Qt::Corner corner)
-
- This sets the given \a widget to be shown directly on the left of the first
- menu item, or on the right of the last menu item, depending on \a corner.
-
- The menu bar takes ownership of \a widget, reparenting it into the menu bar.
- However, if the \a corner already contains a widget, this previous widget
- will no longer be managed and will still be a visible child of the menu bar.
-
- \note Using a corner other than Qt::TopRightCorner or Qt::TopLeftCorner
- will result in a warning.
-*/
-void QMenuBar::setCornerWidget(QWidget *w, Qt::Corner corner)
-{
- Q_D(QMenuBar);
- switch (corner) {
- case Qt::TopLeftCorner:
- if (d->leftWidget)
- d->leftWidget->removeEventFilter(this);
- d->leftWidget = w;
- break;
- case Qt::TopRightCorner:
- if (d->rightWidget)
- d->rightWidget->removeEventFilter(this);
- d->rightWidget = w;
- break;
- default:
- qWarning("QMenuBar::setCornerWidget: Only TopLeftCorner and TopRightCorner are supported");
- return;
- }
-
- if (w) {
- w->setParent(this);
- w->installEventFilter(this);
- }
-
- d->_q_updateLayout();
-}
-
-/*!
- Returns the widget on the left of the first or on the right of the last menu
- item, depending on \a corner.
-
- \note Using a corner other than Qt::TopRightCorner or Qt::TopLeftCorner
- will result in a warning.
-*/
-QWidget *QMenuBar::cornerWidget(Qt::Corner corner) const
-{
- Q_D(const QMenuBar);
- QWidget *w = 0;
- switch(corner) {
- case Qt::TopLeftCorner:
- w = d->leftWidget;
- break;
- case Qt::TopRightCorner:
- w = d->rightWidget;
- break;
- default:
- qWarning("QMenuBar::cornerWidget: Only TopLeftCorner and TopRightCorner are supported");
- break;
- }
-
- return w;
-}
-
-/*!
- \property QMenuBar::nativeMenuBar
- \brief Whether or not a menubar will be used as a native menubar on platforms that support it
- \since 4.6
-
- This property specifies whether or not the menubar should be used as a native menubar on platforms
- that support it. The currently supported platforms are Mac OS X and Windows CE. On these platforms
- if this property is true, the menubar is used in the native menubar and is not in the window of
- its parent, if false the menubar remains in the window. On other platforms the value of this
- attribute has no effect.
-
- The default is to follow whether the Qt::AA_DontUseNativeMenuBar attribute
- is set for the application. Explicitly settings this property overrides
- the presence (or abscence) of the attribute.
-*/
-
-void QMenuBar::setNativeMenuBar(bool nativeMenuBar)
-{
- Q_D(QMenuBar);
- if (d->nativeMenuBar == -1 || (nativeMenuBar != bool(d->nativeMenuBar))) {
- d->nativeMenuBar = nativeMenuBar;
-#ifdef Q_WS_MAC
- if (!d->nativeMenuBar) {
- extern void qt_mac_clear_menubar();
- qt_mac_clear_menubar();
- d->macDestroyMenuBar();
- const QList<QAction *> &menubarActions = actions();
- for (int i = 0; i < menubarActions.size(); ++i) {
- const QAction *action = menubarActions.at(i);
- if (QMenu *menu = action->menu()) {
- delete menu->d_func()->mac_menu;
- menu->d_func()->mac_menu = 0;
- }
- }
- } else {
- d->macCreateMenuBar(parentWidget());
- }
- macUpdateMenuBar();
- updateGeometry();
- if (!d->nativeMenuBar && parentWidget())
- setVisible(true);
-#endif
- }
-}
-
-bool QMenuBar::isNativeMenuBar() const
-{
- Q_D(const QMenuBar);
- if (d->nativeMenuBar == -1) {
- return !QApplication::instance()->testAttribute(Qt::AA_DontUseNativeMenuBar);
- }
- return d->nativeMenuBar;
-}
-
-/*!
- \since 4.4
-
- Sets the default action to \a act.
-
- The default action is assigned to the left soft key. The menu is assigned
- to the right soft key.
-
- Currently there is only support for the default action on Windows
- Mobile. On all other platforms this method is not available.
-
- \sa defaultAction()
-*/
-
-#ifdef Q_WS_WINCE
-void QMenuBar::setDefaultAction(QAction *act)
-{
- Q_D(QMenuBar);
- if (d->defaultAction == act)
- return;
-#ifdef Q_WS_WINCE
- if (qt_wince_is_mobile())
- if (d->defaultAction) {
- disconnect(d->defaultAction, SIGNAL(changed()), this, SLOT(_q_updateDefaultAction()));
- disconnect(d->defaultAction, SIGNAL(destroyed()), this, SLOT(_q_updateDefaultAction()));
- }
-#endif
- d->defaultAction = act;
-#ifdef Q_WS_WINCE
- if (qt_wince_is_mobile())
- if (d->defaultAction) {
- connect(d->defaultAction, SIGNAL(changed()), this, SLOT(_q_updateDefaultAction()));
- connect(d->defaultAction, SIGNAL(destroyed()), this, SLOT(_q_updateDefaultAction()));
- }
- if (d->wce_menubar) {
- d->wce_menubar->rebuild();
- }
-#endif
-}
-
-/*!
- \since 4.4
-
- Returns the current default action.
-
- \sa setDefaultAction()
-*/
-QAction *QMenuBar::defaultAction() const
-{
- return d_func()->defaultAction;
-}
-#endif
-
-/*!
- \fn void QMenuBar::triggered(QAction *action)
-
- This signal is emitted when an action in a menu belonging to this menubar
- is triggered as a result of a mouse click; \a action is the action that
- caused the signal to be emitted.
-
- Normally, you connect each menu action to a single slot using
- QAction::triggered(), but sometimes you will want to connect
- several items to a single slot (most often if the user selects
- from an array). This signal is useful in such cases.
-
- \sa hovered(), QAction::triggered()
-*/
-
-/*!
- \fn void QMenuBar::hovered(QAction *action)
-
- This signal is emitted when a menu action is highlighted; \a action
- is the action that caused the event to be sent.
-
- Often this is used to update status information.
-
- \sa triggered(), QAction::hovered()
-*/
-
-
-#ifdef QT3_SUPPORT
-/*!
- Use style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, this)
- instead.
-*/
-int QMenuBar::frameWidth() const
-{
- return style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, this);
-}
-
-int QMenuBar::insertAny(const QIcon *icon, const QString *text, const QObject *receiver, const char *member,
- const QKeySequence *shortcut, const QMenu *popup, int id, int index)
-{
- QAction *act = popup ? popup->menuAction() : new QAction(this);
- if(id != -1)
- static_cast<QMenuItem*>(act)->setId(id);
- if(icon)
- act->setIcon(*icon);
- if(text)
- act->setText(*text);
- if(shortcut)
- act->setShortcut(*shortcut);
- if(receiver && member)
- QObject::connect(act, SIGNAL(triggered(bool)), receiver, member);
- if(index == -1 || index >= actions().count())
- addAction(act);
- else
- insertAction(actions().value(index), act);
- return findIdForAction(act);
-}
-
-/*!
- \since 4.2
-
- Use addSeparator() or insertAction() instead.
-
- \oldcode
- menuBar->insertSeparator();
- \newcode
- menuBar->addSeparator();
- \endcode
-*/
-int QMenuBar::insertSeparator(int index)
-{
- QAction *act = new QAction(this);
- act->setSeparator(true);
- if(index == -1 || index >= actions().count())
- addAction(act);
- else
- insertAction(actions().value(index), act);
- return findIdForAction(act);
-}
-
-/*!
- Use QAction::setData() instead.
-*/
-bool QMenuBar::setItemParameter(int id, int param)
-{
- if(QAction *act = findActionForId(id)) {
- act->d_func()->param = param;
- return true;
- }
- return false;
-}
-
-/*!
- Use QAction::data() instead.
-*/
-int QMenuBar::itemParameter(int id) const
-{
- if(QAction *act = findActionForId(id))
- return act->d_func()->param;
- return id;
-}
-
-QAction *QMenuBar::findActionForId(int id) const
-{
- QList<QAction *> list = actions();
- for (int i = 0; i < list.size(); ++i) {
- QAction *act = list.at(i);
- if (findIdForAction(act) == id)
- return act;
- }
- return 0;
-}
-
-int QMenuBar::findIdForAction(QAction *act) const
-{
- Q_ASSERT(act);
- return act->d_func()->id;
-}
-#endif
-
-/*!
- \enum QMenuBar::Separator
-
- \compat
-
- \value Never
- \value InWindowsStyle
-
-*/
-
-/*!
- \fn void QMenuBar::addAction(QAction *action)
- \overload
-
- Appends the action \a action to the menu bar's list of actions.
-
- \sa QMenu::addAction(), QWidget::addAction(), QWidget::actions()
-*/
-
-/*!
- \fn uint QMenuBar::count() const
-
- Use actions().count() instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QString &text, const QObject *receiver, const char* member, const QKeySequence& shortcut, int id, int index)
-
- Use one of the insertAction() or addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QIcon& icon, const QString &text, const QObject *receiver, const char* member, const QKeySequence& shortcut, int id, int index)
-
- Use one of the insertAction() or addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QPixmap &pixmap, const QObject *receiver, const char* member, const QKeySequence& shortcut, int id, int index)
-
- Use one of the insertAction(), addAction(), insertMenu(), or
- addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QString &text, int id, int index)
-
- Use one of the insertAction() or addAction() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QIcon& icon, const QString &text, int id, int index)
-
- Use one of the insertAction(), addAction(), insertMenu(), or
- addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QString &text, QMenu *popup, int id, int index)
-
- Use one of the insertMenu(), or addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QIcon& icon, const QString &text, QMenu *popup, int id, int index)
-
- Use one of the insertMenu(), or addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QPixmap &pixmap, int id, int index)
-
- Use one of the insertAction(), addAction(), insertMenu(), or
- addMenu() overloads instead.
-*/
-
-/*!
- \fn int QMenuBar::insertItem(const QPixmap &pixmap, QMenu *popup, int id, int index)
-
- Use one of the insertMenu(), or addMenu() overloads instead.
-*/
-
-/*!
- \fn void QMenuBar::removeItem(int id)
-
- Use removeAction() instead.
-*/
-
-/*!
- \fn void QMenuBar::removeItemAt(int index)
-
- Use removeAction() instead.
-*/
-
-/*!
- \fn QKeySequence QMenuBar::accel(int id) const
-
- Use shortcut() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::setAccel(const QKeySequence& key, int id)
-
- Use setShortcut() on the relevant QAction instead.
-*/
-
-/*!
- \fn QIcon QMenuBar::iconSet(int id) const
-
- Use icon() on the relevant QAction instead.
-*/
-
-/*!
- \fn QString QMenuBar::text(int id) const
-
- Use text() on the relevant QAction instead.
-*/
-
-/*!
- \fn QPixmap QMenuBar::pixmap(int id) const
-
- Use QPixmap(icon()) on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::setWhatsThis(int id, const QString &w)
-
- Use setWhatsThis() on the relevant QAction instead.
-*/
-
-/*!
- \fn QString QMenuBar::whatsThis(int id) const
-
- Use whatsThis() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::changeItem(int id, const QString &text)
-
- Use setText() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::changeItem(int id, const QPixmap &pixmap)
-
- Use setText() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::changeItem(int id, const QIcon &icon, const QString &text)
-
- Use setIcon() and setText() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenuBar::isItemActive(int id) const
-
- Use activeAction() instead.
-*/
-
-/*!
- \fn bool QMenuBar::isItemEnabled(int id) const
-
- Use isEnabled() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::setItemEnabled(int id, bool enable)
-
- Use setEnabled() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenuBar::isItemChecked(int id) const
-
- Use isChecked() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::setItemChecked(int id, bool check)
-
- Use setChecked() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenuBar::isItemVisible(int id) const
-
- Use isVisible() on the relevant QAction instead.
-*/
-
-/*!
- \fn void QMenuBar::setItemVisible(int id, bool visible)
-
- Use setVisible() on the relevant QAction instead.
-*/
-
-/*!
- \fn int QMenuBar::indexOf(int id) const
-
- Use actions().indexOf(action) on the relevant QAction instead.
-*/
-
-/*!
- \fn int QMenuBar::idAt(int index) const
-
- Use actions instead.
-*/
-
-/*!
- \fn void QMenuBar::activateItemAt(int index)
-
- Use activate() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenuBar::connectItem(int id, const QObject *receiver, const char* member)
-
- Use connect() on the relevant QAction instead.
-*/
-
-/*!
- \fn bool QMenuBar::disconnectItem(int id,const QObject *receiver, const char* member)
-
- Use disconnect() on the relevant QAction instead.
-*/
-
-/*!
- \fn QMenuItem *QMenuBar::findItem(int id) const
-
- Use actions instead.
-*/
-
-/*!
- \fn Separator QMenuBar::separator() const
-
- This function is provided only to make old code compile.
-*/
-
-/*!
- \fn void QMenuBar::setSeparator(Separator sep)
-
- This function is provided only to make old code compile.
-*/
-
-/*!
- \fn QRect QMenuBar::itemRect(int index)
-
- Use actionGeometry() on the relevant QAction instead.
-*/
-
-/*!
- \fn int QMenuBar::itemAtPos(const QPoint &p)
-
- There is no equivalent way to achieve this in Qt 4.
-*/
-
-/*!
- \fn void QMenuBar::activated(int itemId);
-
- Use triggered() instead.
-*/
-
-/*!
- \fn void QMenuBar::highlighted(int itemId);
-
- Use hovered() instead.
-*/
-
-/*!
- \fn void QMenuBar::setFrameRect(QRect)
- \internal
-*/
-
-/*!
- \fn QRect QMenuBar::frameRect() const
- \internal
-*/
-/*!
- \enum QMenuBar::DummyFrame
- \internal
-
- \value Box
- \value Sunken
- \value Plain
- \value Raised
- \value MShadow
- \value NoFrame
- \value Panel
- \value StyledPanel
- \value HLine
- \value VLine
- \value GroupBoxPanel
- \value WinPanel
- \value ToolBarPanel
- \value MenuBarPanel
- \value PopupPanel
- \value LineEditPanel
- \value TabWidgetPanel
- \value MShape
-*/
-
-/*!
- \fn void QMenuBar::setFrameShadow(DummyFrame)
- \internal
-*/
-
-/*!
- \fn DummyFrame QMenuBar::frameShadow() const
- \internal
-*/
-
-/*!
- \fn void QMenuBar::setFrameShape(DummyFrame)
- \internal
-*/
-
-/*!
- \fn DummyFrame QMenuBar::frameShape() const
- \internal
-*/
-
-/*!
- \fn void QMenuBar::setFrameStyle(int)
- \internal
-*/
-
-/*!
- \fn int QMenuBar::frameStyle() const
- \internal
-*/
-
-/*!
- \fn void QMenuBar::setLineWidth(int)
- \internal
-*/
-
-/*!
- \fn int QMenuBar::lineWidth() const
- \internal
-*/
-
-/*!
- \fn void QMenuBar::setMargin(int margin)
- Sets the width of the margin around the contents of the widget to \a margin.
-
- Use QWidget::setContentsMargins() instead.
- \sa margin(), QWidget::setContentsMargins()
-*/
-
-/*!
- \fn int QMenuBar::margin() const
- Returns the width of the margin around the contents of the widget.
-
- Use QWidget::getContentsMargins() instead.
- \sa setMargin(), QWidget::getContentsMargins()
-*/
-
-/*!
- \fn void QMenuBar::setMidLineWidth(int)
- \internal
-*/
-
-/*!
- \fn int QMenuBar::midLineWidth() const
- \internal
-*/
-
-// for private slots
-
-
-QT_END_NAMESPACE
-
-#include <moc_qmenubar.cpp>
-
-#endif // QT_NO_MENUBAR
diff --git a/src/gui/widgets/qmenubar.h b/src/gui/widgets/qmenubar.h
deleted file mode 100644
index c22fceb8c2..0000000000
--- a/src/gui/widgets/qmenubar.h
+++ /dev/null
@@ -1,367 +0,0 @@
-/****************************************************************************
-**
-** 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 QMENUBAR_H
-#define QMENUBAR_H
-
-#include <QtGui/qmenu.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_MENUBAR
-
-class QMenuBarPrivate;
-class QStyleOptionMenuItem;
-class QWindowsStyle;
-#ifdef QT3_SUPPORT
-class QMenuItem;
-#endif
-
-class Q_GUI_EXPORT QMenuBar : public QWidget
-{
- Q_OBJECT
-
- Q_PROPERTY(bool defaultUp READ isDefaultUp WRITE setDefaultUp)
- Q_PROPERTY(bool nativeMenuBar READ isNativeMenuBar WRITE setNativeMenuBar)
-
-public:
- explicit QMenuBar(QWidget *parent = 0);
- ~QMenuBar();
-
-#ifdef Q_NO_USING_KEYWORD
- void addAction(QAction *action) { QWidget::addAction(action); }
-#else
- using QWidget::addAction;
-#endif
- QAction *addAction(const QString &text);
- QAction *addAction(const QString &text, const QObject *receiver, const char* member);
-
- QAction *addMenu(QMenu *menu);
- QMenu *addMenu(const QString &title);
- QMenu *addMenu(const QIcon &icon, const QString &title);
-
-
- QAction *addSeparator();
- QAction *insertSeparator(QAction *before);
-
- QAction *insertMenu(QAction *before, QMenu *menu);
-
- void clear();
-
- QAction *activeAction() const;
- void setActiveAction(QAction *action);
-
- void setDefaultUp(bool);
- bool isDefaultUp() const;
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
- int heightForWidth(int) const;
-
- QRect actionGeometry(QAction *) const;
- QAction *actionAt(const QPoint &) const;
-
- void setCornerWidget(QWidget *w, Qt::Corner corner = Qt::TopRightCorner);
- QWidget *cornerWidget(Qt::Corner corner = Qt::TopRightCorner) const;
-
-#ifdef Q_WS_MAC
- OSMenuRef macMenu();
- static bool macUpdateMenuBar();
-#endif
-
-#ifdef Q_WS_WINCE
- void setDefaultAction(QAction *);
- QAction *defaultAction() const;
-
- static void wceCommands(uint command);
- static void wceRefresh();
-#endif
-
- bool isNativeMenuBar() const;
- void setNativeMenuBar(bool nativeMenuBar);
-
-public Q_SLOTS:
- virtual void setVisible(bool visible);
-
-Q_SIGNALS:
- void triggered(QAction *action);
- void hovered(QAction *action);
-
-protected:
- void changeEvent(QEvent *);
- void keyPressEvent(QKeyEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void mousePressEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void leaveEvent(QEvent *);
- void paintEvent(QPaintEvent *);
- void resizeEvent(QResizeEvent *);
- void actionEvent(QActionEvent *);
- void focusOutEvent(QFocusEvent *);
- void focusInEvent(QFocusEvent *);
- void timerEvent(QTimerEvent *);
- bool eventFilter(QObject *, QEvent *);
- bool event(QEvent *);
- void initStyleOption(QStyleOptionMenuItem *option, const QAction *action) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QMenuBar(QWidget *parent, const char *name);
- inline QT3_SUPPORT uint count() const { return actions().count(); }
- inline QT3_SUPPORT int insertItem(const QString &text, const QObject *receiver, const char* member,
- const QKeySequence& shortcut = 0, int id = -1, int index = -1) {
- return insertAny(0, &text, receiver, member, &shortcut, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QIcon& icon, const QString &text,
- const QObject *receiver, const char* member,
- const QKeySequence& shortcut = 0, int id = -1, int index = -1) {
- return insertAny(&icon, &text, receiver, member, &shortcut, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QPixmap &pixmap, const QObject *receiver, const char* member,
- const QKeySequence& shortcut = 0, int id = -1, int index = -1) {
- QIcon icon(pixmap);
- return insertAny(&icon, 0, receiver, member, &shortcut, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QString &text, int id=-1, int index=-1) {
- return insertAny(0, &text, 0, 0, 0, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QIcon& icon, const QString &text, int id=-1, int index=-1) {
- return insertAny(&icon, &text, 0, 0, 0, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QString &text, QMenu *popup, int id=-1, int index=-1) {
- return insertAny(0, &text, 0, 0, 0, popup, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QIcon& icon, const QString &text, QMenu *popup, int id=-1, int index=-1) {
- return insertAny(&icon, &text, 0, 0, 0, popup, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QPixmap &pixmap, int id=-1, int index=-1) {
- QIcon icon(pixmap);
- return insertAny(&icon, 0, 0, 0, 0, 0, id, index);
- }
- inline QT3_SUPPORT int insertItem(const QPixmap &pixmap, QMenu *popup, int id=-1, int index=-1) {
- QIcon icon(pixmap);
- return insertAny(&icon, 0, 0, 0, 0, popup, id, index);
- }
- QT3_SUPPORT int insertSeparator(int index=-1);
- inline QT3_SUPPORT void removeItem(int id) {
- if(QAction *act = findActionForId(id))
- removeAction(act); }
- inline QT3_SUPPORT void removeItemAt(int index) {
- if(QAction *act = actions().value(index))
- removeAction(act); }
-#ifndef QT_NO_SHORTCUT
- inline QT3_SUPPORT QKeySequence accel(int id) const {
- if(QAction *act = findActionForId(id))
- return act->shortcut();
- return QKeySequence(); }
- inline QT3_SUPPORT void setAccel(const QKeySequence& key, int id) {
- if(QAction *act = findActionForId(id))
- act->setShortcut(key);
- }
-#endif
- inline QT3_SUPPORT QIcon iconSet(int id) const {
- if(QAction *act = findActionForId(id))
- return act->icon();
- return QIcon(); }
- inline QT3_SUPPORT QString text(int id) const {
- if(QAction *act = findActionForId(id))
- return act->text();
- return QString(); }
- inline QT3_SUPPORT QPixmap pixmap(int id) const {
- if(QAction *act = findActionForId(id))
- return act->icon().pixmap(QSize(22,22));
- return QPixmap(); }
- inline QT3_SUPPORT void setWhatsThis(int id, const QString &w) {
- if(QAction *act = findActionForId(id))
- act->setWhatsThis(w); }
- inline QT3_SUPPORT QString whatsThis(int id) const {
- if(QAction *act = findActionForId(id))
- return act->whatsThis();
- return QString(); }
-
- inline QT3_SUPPORT void changeItem(int id, const QString &text) {
- if(QAction *act = findActionForId(id))
- act->setText(text); }
- inline QT3_SUPPORT void changeItem(int id, const QPixmap &pixmap) {
- if(QAction *act = findActionForId(id))
- act->setIcon(QIcon(pixmap)); }
- inline QT3_SUPPORT void changeItem(int id, const QIcon &icon, const QString &text) {
- if(QAction *act = findActionForId(id)) {
- act->setIcon(icon);
- act->setText(text);
- }
- }
- inline QT3_SUPPORT bool isItemActive(int id) const { return findActionForId(id) == activeAction(); }
- inline QT3_SUPPORT bool isItemEnabled(int id) const {
- if(QAction *act = findActionForId(id))
- return act->isEnabled();
- return false; }
- inline QT3_SUPPORT void setItemEnabled(int id, bool enable) {
- if(QAction *act = findActionForId(id))
- act->setEnabled(enable); }
- inline QT3_SUPPORT bool isItemChecked(int id) const {
- if(QAction *act = findActionForId(id))
- return act->isChecked();
- return false; }
- inline QT3_SUPPORT void setItemChecked(int id, bool check) {
- if(QAction *act = findActionForId(id))
- act->setChecked(check); }
- inline QT3_SUPPORT bool isItemVisible(int id) const {
- if(QAction *act = findActionForId(id))
- return act->isVisible();
- return false; }
- inline QT3_SUPPORT void setItemVisible(int id, bool visible) {
- if(QAction *act = findActionForId(id))
- act->setVisible(visible); }
- inline QT3_SUPPORT int indexOf(int id) const { return actions().indexOf(findActionForId(id)); }
- inline QT3_SUPPORT int idAt(int index) const {
- return index >= 0 && index < actions().size()
- ? findIdForAction(actions().at(index))
- : -1;
- }
- inline QT3_SUPPORT void activateItemAt(int index) {
- if(QAction *ret = actions().value(index))
- setActiveAction(ret);
- }
- inline QT3_SUPPORT bool connectItem(int id, const QObject *receiver, const char* member) {
- if(QAction *act = findActionForId(id)) {
- QObject::connect(act, SIGNAL(triggered()), receiver, member);
- return true;
- }
- return false;
- }
- inline QT3_SUPPORT bool disconnectItem(int id,const QObject *receiver, const char* member) {
- if(QAction *act = findActionForId(id)) {
- QObject::disconnect(act, SIGNAL(triggered()), receiver, member);
- return true;
- }
- return false;
- }
- inline QT3_SUPPORT QMenuItem *findItem(int id) const {
- return (QMenuItem*)findActionForId(id);
- }
- QT3_SUPPORT bool setItemParameter(int id, int param);
- QT3_SUPPORT int itemParameter(int id) const;
-
- //frame
- QT3_SUPPORT int frameWidth() const;
-
- QT3_SUPPORT void setFrameRect(QRect) {}
- QT3_SUPPORT QRect frameRect() const { return QRect(); }
- enum DummyFrame { Box, Sunken, Plain, Raised, MShadow, NoFrame, Panel, StyledPanel,
- HLine, VLine, GroupBoxPanel, WinPanel, ToolBarPanel, MenuBarPanel,
- PopupPanel, LineEditPanel, TabWidgetPanel, MShape };
- QT3_SUPPORT void setFrameShadow(DummyFrame) {}
- QT3_SUPPORT DummyFrame frameShadow() const { return Plain; }
- QT3_SUPPORT void setFrameShape(DummyFrame) {}
- QT3_SUPPORT DummyFrame frameShape() const { return NoFrame; }
- QT3_SUPPORT void setFrameStyle(int) {}
- QT3_SUPPORT int frameStyle() const { return 0; }
- QT3_SUPPORT void setLineWidth(int) {}
- QT3_SUPPORT int lineWidth() const { return 0; }
- QT3_SUPPORT void setMargin(int margin) { setContentsMargins(margin, margin, margin, margin); }
- QT3_SUPPORT int margin() const
- { int margin; int dummy; getContentsMargins(&margin, &dummy, &dummy, &dummy); return margin; }
- QT3_SUPPORT void setMidLineWidth(int) {}
- QT3_SUPPORT int midLineWidth() const { return 0; }
-
- //menubar
- enum Separator { Never=0, InWindowsStyle=1 };
- inline QT3_SUPPORT Separator separator() const { return InWindowsStyle; }
- inline QT3_SUPPORT void setSeparator(Separator) { }
-
- QT3_SUPPORT void setAutoGeometry(bool);
- QT3_SUPPORT bool autoGeometry() const;
-
-Q_SIGNALS:
- QT_MOC_COMPAT void activated(int itemId);
- QT_MOC_COMPAT void highlighted(int itemId);
-
-protected:
- inline QT3_SUPPORT QRect itemRect(int index) {
- if(QAction *act = actions().value(index))
- return actionGeometry(act);
- return QRect();
- }
- inline QT3_SUPPORT int itemAtPos(const QPoint &p) {
- return findIdForAction(actionAt(p));
- }
-private:
- QAction *findActionForId(int id) const;
- int insertAny(const QIcon *icon, const QString *text, const QObject *receiver, const char *member,
- const QKeySequence *shorcut, const QMenu *popup, int id, int index);
- int findIdForAction(QAction*) const;
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QMenuBar)
- Q_DISABLE_COPY(QMenuBar)
- Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())
- Q_PRIVATE_SLOT(d_func(), void _q_actionHovered())
- Q_PRIVATE_SLOT(d_func(), void _q_internalShortcutActivated(int))
- Q_PRIVATE_SLOT(d_func(), void _q_updateLayout())
-
-#ifdef Q_WS_WINCE
- Q_PRIVATE_SLOT(d_func(), void _q_updateDefaultAction())
-#endif
-
- friend class QMenu;
- friend class QMenuPrivate;
- friend class QWindowsStyle;
-
-#ifdef Q_WS_MAC
- friend class QApplicationPrivate;
- friend class QWidgetPrivate;
- friend bool qt_mac_activate_action(MenuRef, uint, QAction::ActionEvent, bool);
-#endif
-};
-
-#endif // QT_NO_MENUBAR
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMENUBAR_H
diff --git a/src/gui/widgets/qmenubar_p.h b/src/gui/widgets/qmenubar_p.h
deleted file mode 100644
index 5afe71376d..0000000000
--- a/src/gui/widgets/qmenubar_p.h
+++ /dev/null
@@ -1,283 +0,0 @@
-/****************************************************************************
-**
-** 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 QMENUBAR_P_H
-#define QMENUBAR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QMAC_Q3MENUBAR_CPP_FILE
-#include "QtGui/qstyleoption.h"
-#include <private/qmenu_p.h> // Mac needs what in this file!
-
-#ifdef Q_WS_WINCE
-#include "qguifunctions_wince.h"
-#endif
-
-#ifndef QT_NO_MENUBAR
-#ifdef Q_WS_S60
-class CCoeControl;
-class CEikMenuBar;
-#endif
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_MENUBAR
-class QMenuBarExtension;
-class QMenuBarPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QMenuBar)
-public:
- QMenuBarPrivate() : itemsDirty(0), currentAction(0), mouseDown(0),
- closePopupMode(0), defaultPopDown(1), popupState(0), keyboardState(0), altPressed(0),
- nativeMenuBar(-1), doChildEffects(false)
-#ifdef QT3_SUPPORT
- , doAutoResize(false)
-#endif
-#ifdef Q_WS_MAC
- , mac_menubar(0)
-#endif
-
-#ifdef Q_WS_WINCE
- , wce_menubar(0), wceClassicMenu(false)
-#endif
-#ifdef Q_WS_S60
- , symbian_menubar(0)
-#endif
-
- { }
- ~QMenuBarPrivate()
- {
-#ifdef Q_WS_MAC
- delete mac_menubar;
-#endif
-#ifdef Q_WS_WINCE
- delete wce_menubar;
-#endif
-#ifdef Q_WS_S60
- delete symbian_menubar;
-#endif
- }
-
- void init();
- QAction *getNextAction(const int start, const int increment) const;
-
- //item calculations
- uint itemsDirty : 1;
-
- QVector<int> shortcutIndexMap;
- mutable QVector<QRect> actionRects;
- void calcActionRects(int max_width, int start) const;
- QRect actionRect(QAction *) const;
- void updateGeometries();
-
- //selection
- QPointer<QAction>currentAction;
- uint mouseDown : 1, closePopupMode : 1, defaultPopDown;
- QAction *actionAt(QPoint p) const;
- void setCurrentAction(QAction *, bool =false, bool =false);
- void popupAction(QAction *, bool);
-
- //active popup state
- uint popupState : 1;
- QPointer<QMenu> activeMenu;
-
- //keyboard mode for keyboard navigation
- void focusFirstAction();
- void setKeyboardMode(bool);
- uint keyboardState : 1, altPressed : 1;
- QPointer<QWidget> keyboardFocusWidget;
-
-
- int nativeMenuBar : 3; // Only has values -1, 0, and 1
- //firing of events
- void activateAction(QAction *, QAction::ActionEvent);
-
- void _q_actionTriggered();
- void _q_actionHovered();
- void _q_internalShortcutActivated(int);
- void _q_updateLayout();
-
-#ifdef Q_WS_WINCE
- void _q_updateDefaultAction();
-#endif
-
- //extra widgets in the menubar
- QPointer<QWidget> leftWidget, rightWidget;
- QMenuBarExtension *extension;
- bool isVisible(QAction *action);
-
- //menu fading/scrolling effects
- bool doChildEffects;
-
- QRect menuRect(bool) const;
-
- // reparenting
- void handleReparent();
- QWidget *oldParent;
- QWidget *oldWindow;
-
- QList<QAction*> hiddenActions;
- //default action
- QPointer<QAction> defaultAction;
-
- QBasicTimer autoReleaseTimer;
-#ifdef QT3_SUPPORT
- bool doAutoResize;
-#endif
-#ifdef Q_WS_MAC
- //mac menubar binding
- struct QMacMenuBarPrivate {
- QList<QMacMenuAction*> actionItems;
- OSMenuRef menu, apple_menu;
- QMacMenuBarPrivate();
- ~QMacMenuBarPrivate();
-
- void addAction(QAction *, QMacMenuAction* =0);
- void addAction(QMacMenuAction *, QMacMenuAction* =0);
- void syncAction(QMacMenuAction *);
- inline void syncAction(QAction *a) { syncAction(findAction(a)); }
- void removeAction(QMacMenuAction *);
- inline void removeAction(QAction *a) { removeAction(findAction(a)); }
- inline QMacMenuAction *findAction(QAction *a) {
- for(int i = 0; i < actionItems.size(); i++) {
- QMacMenuAction *act = actionItems[i];
- if(a == act->action)
- return act;
- }
- return 0;
- }
- } *mac_menubar;
- static bool macUpdateMenuBarImmediatly();
- bool macWidgetHasNativeMenubar(QWidget *widget);
- void macCreateMenuBar(QWidget *);
- void macDestroyMenuBar();
- OSMenuRef macMenu();
-#endif
-#ifdef Q_WS_WINCE
- void wceCreateMenuBar(QWidget *);
- void wceDestroyMenuBar();
- struct QWceMenuBarPrivate {
- QList<QWceMenuAction*> actionItems;
- QList<QWceMenuAction*> actionItemsLeftButton;
- QList<QList<QWceMenuAction*>> actionItemsClassic;
- HMENU menuHandle;
- HMENU leftButtonMenuHandle;
- HWND menubarHandle;
- HWND parentWindowHandle;
- bool leftButtonIsMenu;
- QPointer<QAction> leftButtonAction;
- QMenuBarPrivate *d;
- int leftButtonCommand;
-
- QWceMenuBarPrivate(QMenuBarPrivate *menubar);
- ~QWceMenuBarPrivate();
- void addAction(QAction *, QWceMenuAction* =0);
- void addAction(QWceMenuAction *, QWceMenuAction* =0);
- void syncAction(QWceMenuAction *);
- inline void syncAction(QAction *a) { syncAction(findAction(a)); }
- void removeAction(QWceMenuAction *);
- void rebuild();
- inline void removeAction(QAction *a) { removeAction(findAction(a)); }
- inline QWceMenuAction *findAction(QAction *a) {
- for(int i = 0; i < actionItems.size(); i++) {
- QWceMenuAction *act = actionItems[i];
- if(a == act->action)
- return act;
- }
- return 0;
- }
- } *wce_menubar;
- bool wceClassicMenu;
- void wceCommands(uint command);
- void wceRefresh();
- bool wceEmitSignals(QList<QWceMenuAction*> actions, uint command);
-#endif
-#ifdef Q_WS_S60
- void symbianCreateMenuBar(QWidget *);
- void symbianDestroyMenuBar();
- void reparentMenuBar(QWidget *oldParent, QWidget *newParent);
- struct QSymbianMenuBarPrivate {
- QList<QSymbianMenuAction*> actionItems;
- QMenuBarPrivate *d;
- QSymbianMenuBarPrivate(QMenuBarPrivate *menubar);
- ~QSymbianMenuBarPrivate();
- void addAction(QAction *, QSymbianMenuAction* =0);
- void addAction(QSymbianMenuAction *, QSymbianMenuAction* =0);
- void syncAction(QSymbianMenuAction *);
- inline void syncAction(QAction *a) { syncAction(findAction(a)); }
- void removeAction(QSymbianMenuAction *);
- void rebuild();
- inline void removeAction(QAction *a) { removeAction(findAction(a)); }
- inline QSymbianMenuAction *findAction(QAction *a) {
- for(int i = 0; i < actionItems.size(); i++) {
- QSymbianMenuAction *act = actionItems[i];
- if(a == act->action)
- return act;
- }
- return 0;
- }
- void insertNativeMenuItems(const QList<QAction*> &actions);
-
- } *symbian_menubar;
- static int symbianCommands(int command);
-#endif
-#ifdef QT_SOFTKEYS_ENABLED
- QAction *menuBarAction;
-#endif
-};
-#endif
-
-#endif // QT_NO_MENUBAR
-
-QT_END_NAMESPACE
-
-#endif // QMENUBAR_P_H
diff --git a/src/gui/widgets/qmenudata.cpp b/src/gui/widgets/qmenudata.cpp
deleted file mode 100644
index f302aa8d50..0000000000
--- a/src/gui/widgets/qmenudata.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** 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 "qmenudata.h"
-
-#ifdef QT3_SUPPORT
-#include <qaction.h>
-#include <private/qaction_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QMenuItem
- \brief The QMenuItem class represents an item in a menu.
-
- \compat
-
- Use QAction instead.
-*/
-
-/*!
- \compat
- Constructs a new menu item.
-*/
-QMenuItem::QMenuItem() : QAction((QWidget*)0)
-{
-}
-
-void QMenuItem::setId(int id)
-{
- d_func()->param = d_func()->id = id;
-}
-
-/*!
- \compat
- Returns the menu item's ID.
-*/
-int QMenuItem::id() const
-{
- return d_func()->id;
-}
-
-void QMenuItem::setSignalValue(int param)
-{
- d_func()->param = param;
-}
-
-/*!
- \compat
- Returns the signal value for the menu item.
-*/
-int QMenuItem::signalValue() const
-{
- return d_func()->param;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qmenudata.h b/src/gui/widgets/qmenudata.h
deleted file mode 100644
index b303f41394..0000000000
--- a/src/gui/widgets/qmenudata.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** 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 QMENUDATA_H
-#define QMENUDATA_H
-
-#include <QtCore/qglobal.h>
-
-#ifdef QT3_SUPPORT
-#include <QtGui/qaction.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class Q_GUI_EXPORT QMenuItem : public QAction
-{
- Q_OBJECT
-
-public:
- QMenuItem();
-
- QT3_SUPPORT int id() const;
- QT3_SUPPORT int signalValue() const;
-private:
- friend class QMenu;
- friend class QMenuBar;
- void setId(int);
- void setSignalValue(int);
-
- Q_DISABLE_COPY(QMenuItem)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
-
-#endif // QMENUDATA_H
diff --git a/src/gui/widgets/qplaintextedit.cpp b/src/gui/widgets/qplaintextedit.cpp
deleted file mode 100644
index 7435691bf0..0000000000
--- a/src/gui/widgets/qplaintextedit.cpp
+++ /dev/null
@@ -1,2992 +0,0 @@
-/****************************************************************************
-**
-** 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 "qplaintextedit_p.h"
-
-
-#include <qfont.h>
-#include <qpainter.h>
-#include <qevent.h>
-#include <qdebug.h>
-#include <qmime.h>
-#include <qdrag.h>
-#include <qclipboard.h>
-#include <qmenu.h>
-#include <qstyle.h>
-#include <qtimer.h>
-#include "private/qtextdocumentlayout_p.h"
-#include "private/qabstracttextdocumentlayout_p.h"
-#include "qtextdocument.h"
-#include "private/qtextdocument_p.h"
-#include "qtextlist.h"
-#include "private/qtextcontrol_p.h"
-
-#include <qtextformat.h>
-#include <qdatetime.h>
-#include <qapplication.h>
-#include <limits.h>
-#include <qtexttable.h>
-#include <qvariant.h>
-#include <qinputcontext.h>
-
-#ifndef QT_NO_TEXTEDIT
-
-QT_BEGIN_NAMESPACE
-
-static inline bool shouldEnableInputMethod(QPlainTextEdit *plaintextedit)
-{
- return !plaintextedit->isReadOnly();
-}
-
-class QPlainTextDocumentLayoutPrivate : public QAbstractTextDocumentLayoutPrivate
-{
- Q_DECLARE_PUBLIC(QPlainTextDocumentLayout)
-public:
- QPlainTextDocumentLayoutPrivate() {
- mainViewPrivate = 0;
- width = 0;
- maximumWidth = 0;
- maximumWidthBlockNumber = 0;
- blockCount = 1;
- blockUpdate = blockDocumentSizeChanged = false;
- cursorWidth = 1;
- textLayoutFlags = 0;
- }
-
- qreal width;
- qreal maximumWidth;
- int maximumWidthBlockNumber;
- int blockCount;
- QPlainTextEditPrivate *mainViewPrivate;
- bool blockUpdate;
- bool blockDocumentSizeChanged;
- int cursorWidth;
- int textLayoutFlags;
-
- void layoutBlock(const QTextBlock &block);
- qreal blockWidth(const QTextBlock &block);
-
- void relayout();
-};
-
-
-
-/*! \class QPlainTextDocumentLayout
- \since 4.4
- \brief The QPlainTextDocumentLayout class implements a plain text layout for QTextDocument
-
- \ingroup richtext-processing
-
- A QPlainTextDocumentLayout is required for text documents that can
- be display or edited in a QPlainTextEdit. See
- QTextDocument::setDocumentLayout().
-
- QPlainTextDocumentLayout uses the QAbstractTextDocumentLayout API
- that QTextDocument requires, but redefines it partially in order to
- support plain text better. For instances, it does not operate on
- vertical pixels, but on paragraphs (called blocks) instead. The
- height of a document is identical to the number of paragraphs it
- contains. The layout also doesn't support tables or nested frames,
- or any sort of advanced text layout that goes beyond a list of
- paragraphs with syntax highlighting.
-
-*/
-
-
-
-/*!
- Constructs a plain text document layout for the text \a document.
- */
-QPlainTextDocumentLayout::QPlainTextDocumentLayout(QTextDocument *document)
- :QAbstractTextDocumentLayout(* new QPlainTextDocumentLayoutPrivate, document) {
-}
-/*!
- Destructs a plain text document layout.
- */
-QPlainTextDocumentLayout::~QPlainTextDocumentLayout() {}
-
-
-/*!
- \reimp
- */
-void QPlainTextDocumentLayout::draw(QPainter *, const PaintContext &)
-{
-}
-
-/*!
- \reimp
- */
-int QPlainTextDocumentLayout::hitTest(const QPointF &, Qt::HitTestAccuracy ) const
-{
-// this function is used from
-// QAbstractTextDocumentLayout::anchorAt(), but is not
-// implementable in a plain text document layout, because the
-// layout depends on the top block and top line which depends on
-// the view
- return -1;
-}
-
-/*!
- \reimp
- */
-int QPlainTextDocumentLayout::pageCount() const
-{ return 1; }
-
-/*!
- \reimp
- */
-QSizeF QPlainTextDocumentLayout::documentSize() const
-{
- Q_D(const QPlainTextDocumentLayout);
- return QSizeF(d->maximumWidth, document()->lineCount());
-}
-
-/*!
- \reimp
- */
-QRectF QPlainTextDocumentLayout::frameBoundingRect(QTextFrame *) const
-{
- Q_D(const QPlainTextDocumentLayout);
- return QRectF(0, 0, qMax(d->width, d->maximumWidth), qreal(INT_MAX));
-}
-
-/*!
- \reimp
- */
-QRectF QPlainTextDocumentLayout::blockBoundingRect(const QTextBlock &block) const
-{
- if (!block.isValid()) { return QRectF(); }
- QTextLayout *tl = block.layout();
- if (!tl->lineCount())
- const_cast<QPlainTextDocumentLayout*>(this)->layoutBlock(block);
- QRectF br;
- if (block.isVisible()) {
- br = QRectF(QPointF(0, 0), tl->boundingRect().bottomRight());
- if (tl->lineCount() == 1)
- br.setWidth(qMax(br.width(), tl->lineAt(0).naturalTextWidth()));
- qreal margin = document()->documentMargin();
- br.adjust(0, 0, margin, 0);
- if (!block.next().isValid())
- br.adjust(0, 0, 0, margin);
- }
- return br;
-
-}
-
-/*!
- Ensures that \a block has a valid layout
- */
-void QPlainTextDocumentLayout::ensureBlockLayout(const QTextBlock &block) const
-{
- if (!block.isValid())
- return;
- QTextLayout *tl = block.layout();
- if (!tl->lineCount())
- const_cast<QPlainTextDocumentLayout*>(this)->layoutBlock(block);
-}
-
-
-/*! \property QPlainTextDocumentLayout::cursorWidth
-
- This property specifies the width of the cursor in pixels. The default value is 1.
-*/
-void QPlainTextDocumentLayout::setCursorWidth(int width)
-{
- Q_D(QPlainTextDocumentLayout);
- d->cursorWidth = width;
-}
-
-int QPlainTextDocumentLayout::cursorWidth() const
-{
- Q_D(const QPlainTextDocumentLayout);
- return d->cursorWidth;
-}
-
-QPlainTextDocumentLayoutPrivate *QPlainTextDocumentLayout::priv() const
-{
- Q_D(const QPlainTextDocumentLayout);
- return const_cast<QPlainTextDocumentLayoutPrivate*>(d);
-}
-
-
-/*!
-
- Requests a complete update on all views.
- */
-void QPlainTextDocumentLayout::requestUpdate()
-{
- emit update(QRectF(0., -document()->documentMargin(), 1000000000., 1000000000.));
-}
-
-
-void QPlainTextDocumentLayout::setTextWidth(qreal newWidth)
-{
- Q_D(QPlainTextDocumentLayout);
- d->width = d->maximumWidth = newWidth;
- d->relayout();
-}
-
-qreal QPlainTextDocumentLayout::textWidth() const
-{
- Q_D(const QPlainTextDocumentLayout);
- return d->width;
-}
-
-void QPlainTextDocumentLayoutPrivate::relayout()
-{
- Q_Q(QPlainTextDocumentLayout);
- QTextBlock block = q->document()->firstBlock();
- while (block.isValid()) {
- block.layout()->clearLayout();
- block.setLineCount(block.isVisible() ? 1 : 0);
- block = block.next();
- }
- emit q->update();
-}
-
-
-/*! \reimp
- */
-void QPlainTextDocumentLayout::documentChanged(int from, int /*charsRemoved*/, int charsAdded)
-{
- Q_D(QPlainTextDocumentLayout);
- QTextDocument *doc = document();
- int newBlockCount = doc->blockCount();
-
- QTextBlock changeStartBlock = doc->findBlock(from);
- QTextBlock changeEndBlock = doc->findBlock(qMax(0, from + charsAdded - 1));
-
- if (changeStartBlock == changeEndBlock && newBlockCount == d->blockCount) {
- QTextBlock block = changeStartBlock;
- int blockLineCount = block.layout()->lineCount();
- if (block.isValid() && blockLineCount) {
- QRectF oldBr = blockBoundingRect(block);
- layoutBlock(block);
- QRectF newBr = blockBoundingRect(block);
- if (newBr.height() == oldBr.height()) {
- if (!d->blockUpdate)
- emit updateBlock(block);
- return;
- }
- }
- } else {
- QTextBlock block = changeStartBlock;
- do {
- block.clearLayout();
- if (block == changeEndBlock)
- break;
- block = block.next();
- } while(block.isValid());
- }
-
- if (newBlockCount != d->blockCount) {
-
- int changeEnd = changeEndBlock.blockNumber();
- int blockDiff = newBlockCount - d->blockCount;
- int oldChangeEnd = changeEnd - blockDiff;
-
- if (d->maximumWidthBlockNumber > oldChangeEnd)
- d->maximumWidthBlockNumber += blockDiff;
-
- d->blockCount = newBlockCount;
- if (d->blockCount == 1)
- d->maximumWidth = blockWidth(doc->firstBlock());
-
- if (!d->blockDocumentSizeChanged)
- emit documentSizeChanged(documentSize());
-
- if (blockDiff == 1 && changeEnd == newBlockCount -1 ) {
- if (!d->blockUpdate) {
- QTextBlock b = changeStartBlock;
- for(;;) {
- emit updateBlock(b);
- if (b == changeEndBlock)
- break;
- b = b.next();
- }
- }
- return;
- }
- }
-
- if (!d->blockUpdate)
- emit update(QRectF(0., -doc->documentMargin(), 1000000000., 1000000000.)); // optimization potential
-}
-
-
-void QPlainTextDocumentLayout::layoutBlock(const QTextBlock &block)
-{
- Q_D(QPlainTextDocumentLayout);
- QTextDocument *doc = document();
- qreal margin = doc->documentMargin();
- qreal blockMaximumWidth = 0;
-
- qreal height = 0;
- QTextLayout *tl = block.layout();
- QTextOption option = doc->defaultTextOption();
- tl->setTextOption(option);
-
- int extraMargin = 0;
- if (option.flags() & QTextOption::AddSpaceForLineAndParagraphSeparators) {
- QFontMetrics fm(block.charFormat().font());
- extraMargin += fm.width(QChar(0x21B5));
- }
- tl->beginLayout();
- qreal availableWidth = d->width;
- if (availableWidth <= 0) {
- availableWidth = qreal(INT_MAX); // similar to text edit with pageSize.width == 0
- }
- availableWidth -= 2*margin + extraMargin;
- while (1) {
- QTextLine line = tl->createLine();
- if (!line.isValid())
- break;
- line.setLeadingIncluded(true);
- line.setLineWidth(availableWidth);
- line.setPosition(QPointF(margin, height));
- height += line.height();
- blockMaximumWidth = qMax(blockMaximumWidth, line.naturalTextWidth() + 2*margin);
- }
- tl->endLayout();
-
- int previousLineCount = doc->lineCount();
- const_cast<QTextBlock&>(block).setLineCount(block.isVisible() ? tl->lineCount() : 0);
- int lineCount = doc->lineCount();
-
- bool emitDocumentSizeChanged = previousLineCount != lineCount;
- if (blockMaximumWidth > d->maximumWidth) {
- // new longest line
- d->maximumWidth = blockMaximumWidth;
- d->maximumWidthBlockNumber = block.blockNumber();
- emitDocumentSizeChanged = true;
- } else if (block.blockNumber() == d->maximumWidthBlockNumber && blockMaximumWidth < d->maximumWidth) {
- // longest line shrinking
- QTextBlock b = doc->firstBlock();
- d->maximumWidth = 0;
- QTextBlock maximumBlock;
- while (b.isValid()) {
- qreal blockMaximumWidth = blockWidth(b);
- if (blockMaximumWidth > d->maximumWidth) {
- d->maximumWidth = blockMaximumWidth;
- maximumBlock = b;
- }
- b = b.next();
- }
- if (maximumBlock.isValid()) {
- d->maximumWidthBlockNumber = maximumBlock.blockNumber();
- emitDocumentSizeChanged = true;
- }
- }
- if (emitDocumentSizeChanged && !d->blockDocumentSizeChanged)
- emit documentSizeChanged(documentSize());
-}
-
-qreal QPlainTextDocumentLayout::blockWidth(const QTextBlock &block)
-{
- QTextLayout *layout = block.layout();
- if (!layout->lineCount())
- return 0; // only for layouted blocks
- qreal blockWidth = 0;
- for (int i = 0; i < layout->lineCount(); ++i) {
- QTextLine line = layout->lineAt(i);
- blockWidth = qMax(line.naturalTextWidth() + 8, blockWidth);
- }
- return blockWidth;
-}
-
-
-QPlainTextEditControl::QPlainTextEditControl(QPlainTextEdit *parent)
- : QTextControl(parent), textEdit(parent),
- topBlock(0)
-{
- setAcceptRichText(false);
-}
-
-void QPlainTextEditPrivate::_q_cursorPositionChanged()
-{
- pageUpDownLastCursorYIsValid = false;
-}
-
-void QPlainTextEditPrivate::_q_verticalScrollbarActionTriggered(int action) {
- if (action == QAbstractSlider::SliderPageStepAdd) {
- pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor, false);
- } else if (action == QAbstractSlider::SliderPageStepSub) {
- pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor, false);
- }
-}
-
-QMimeData *QPlainTextEditControl::createMimeDataFromSelection() const {
- QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(parent());
- if (!ed)
- return QTextControl::createMimeDataFromSelection();
- return ed->createMimeDataFromSelection();
- }
-bool QPlainTextEditControl::canInsertFromMimeData(const QMimeData *source) const {
- QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(parent());
- if (!ed)
- return QTextControl::canInsertFromMimeData(source);
- return ed->canInsertFromMimeData(source);
-}
-void QPlainTextEditControl::insertFromMimeData(const QMimeData *source) {
- QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(parent());
- if (!ed)
- QTextControl::insertFromMimeData(source);
- else
- ed->insertFromMimeData(source);
-}
-
-int QPlainTextEditPrivate::verticalOffset(int topBlock, int topLine) const
-{
- qreal offset = 0;
- QTextDocument *doc = control->document();
-
- if (topLine) {
- QTextBlock currentBlock = doc->findBlockByNumber(topBlock);
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
- Q_ASSERT(documentLayout);
- QRectF r = documentLayout->blockBoundingRect(currentBlock);
- QTextLayout *layout = currentBlock.layout();
- if (layout && topLine <= layout->lineCount()) {
- QTextLine line = layout->lineAt(topLine - 1);
- const QRectF lr = line.naturalTextRect();
- offset = lr.bottom();
- }
- }
- if (topBlock == 0 && topLine == 0)
- offset -= doc->documentMargin(); // top margin
- return (int)offset;
-}
-
-
-int QPlainTextEditPrivate::verticalOffset() const {
- return verticalOffset(control->topBlock, topLine);
-}
-
-
-QTextBlock QPlainTextEditControl::firstVisibleBlock() const
-{
- return document()->findBlockByNumber(topBlock);
-}
-
-
-
-int QPlainTextEditControl::hitTest(const QPointF &point, Qt::HitTestAccuracy ) const {
- int currentBlockNumber = topBlock;
- QTextBlock currentBlock = document()->findBlockByNumber(currentBlockNumber);
- if (!currentBlock.isValid())
- return -1;
-
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout());
- Q_ASSERT(documentLayout);
-
- QPointF offset;
- QRectF r = documentLayout->blockBoundingRect(currentBlock);
- while (currentBlock.next().isValid() && r.bottom() + offset.y() <= point.y()) {
- offset.ry() += r.height();
- currentBlock = currentBlock.next();
- ++currentBlockNumber;
- r = documentLayout->blockBoundingRect(currentBlock);
- }
- while (currentBlock.previous().isValid() && r.top() + offset.y() > point.y()) {
- offset.ry() -= r.height();
- currentBlock = currentBlock.previous();
- --currentBlockNumber;
- r = documentLayout->blockBoundingRect(currentBlock);
- }
-
-
- if (!currentBlock.isValid())
- return -1;
- QTextLayout *layout = currentBlock.layout();
- int off = 0;
- QPointF pos = point - offset;
- for (int i = 0; i < layout->lineCount(); ++i) {
- QTextLine line = layout->lineAt(i);
- const QRectF lr = line.naturalTextRect();
- if (lr.top() > pos.y()) {
- off = qMin(off, line.textStart());
- } else if (lr.bottom() <= pos.y()) {
- off = qMax(off, line.textStart() + line.textLength());
- } else {
- off = line.xToCursor(pos.x(), overwriteMode() ?
- QTextLine::CursorOnCharacter : QTextLine::CursorBetweenCharacters);
- break;
- }
- }
-
- return currentBlock.position() + off;
-}
-
-QRectF QPlainTextEditControl::blockBoundingRect(const QTextBlock &block) const {
- int currentBlockNumber = topBlock;
- int blockNumber = block.blockNumber();
- QTextBlock currentBlock = document()->findBlockByNumber(currentBlockNumber);
- if (!currentBlock.isValid())
- return QRectF();
- Q_ASSERT(currentBlock.blockNumber() == currentBlockNumber);
- QTextDocument *doc = document();
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
- Q_ASSERT(documentLayout);
-
- QPointF offset;
- if (!block.isValid())
- return QRectF();
- QRectF r = documentLayout->blockBoundingRect(currentBlock);
- int maxVerticalOffset = r.height();
- while (currentBlockNumber < blockNumber && offset.y() - maxVerticalOffset <= 2* textEdit->viewport()->height()) {
- offset.ry() += r.height();
- currentBlock = currentBlock.next();
- ++currentBlockNumber;
- if (!currentBlock.isVisible()) {
- currentBlock = doc->findBlockByLineNumber(currentBlock.firstLineNumber());
- currentBlockNumber = currentBlock.blockNumber();
- }
- r = documentLayout->blockBoundingRect(currentBlock);
- }
- while (currentBlockNumber > blockNumber && offset.y() + maxVerticalOffset >= -textEdit->viewport()->height()) {
- currentBlock = currentBlock.previous();
- --currentBlockNumber;
- while (!currentBlock.isVisible()) {
- currentBlock = currentBlock.previous();
- --currentBlockNumber;
- }
- if (!currentBlock.isValid())
- break;
-
- r = documentLayout->blockBoundingRect(currentBlock);
- offset.ry() -= r.height();
- }
-
- if (currentBlockNumber != blockNumber) {
- // fallback for blocks out of reach. Give it some geometry at
- // least, and ensure the layout is up to date.
- r = documentLayout->blockBoundingRect(block);
- if (currentBlockNumber > blockNumber)
- offset.ry() -= r.height();
- }
- r.translate(offset);
- return r;
-}
-
-
-void QPlainTextEditPrivate::setTopLine(int visualTopLine, int dx)
-{
- QTextDocument *doc = control->document();
- QTextBlock block = doc->findBlockByLineNumber(visualTopLine);
- int blockNumber = block.blockNumber();
- int lineNumber = visualTopLine - block.firstLineNumber();
- setTopBlock(blockNumber, lineNumber, dx);
-}
-
-void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx)
-{
- Q_Q(QPlainTextEdit);
- blockNumber = qMax(0, blockNumber);
- lineNumber = qMax(0, lineNumber);
- QTextDocument *doc = control->document();
- QTextBlock block = doc->findBlockByNumber(blockNumber);
-
- int newTopLine = block.firstLineNumber() + lineNumber;
- int maxTopLine = vbar->maximum();
-
- if (newTopLine > maxTopLine) {
- block = doc->findBlockByLineNumber(maxTopLine);
- blockNumber = block.blockNumber();
- lineNumber = maxTopLine - block.firstLineNumber();
- }
-
- bool vbarSignalsBlocked = vbar->blockSignals(true);
- vbar->setValue(newTopLine);
- vbar->blockSignals(vbarSignalsBlocked);
-
- if (!dx && blockNumber == control->topBlock && lineNumber == topLine)
- return;
-
- if (viewport->updatesEnabled() && viewport->isVisible()) {
- int dy = 0;
- if (doc->findBlockByNumber(control->topBlock).isValid()) {
- dy = (int)(-q->blockBoundingGeometry(block).y())
- + verticalOffset() - verticalOffset(blockNumber, lineNumber);
- }
- control->topBlock = blockNumber;
- topLine = lineNumber;
- if (dx || dy)
- viewport->scroll(q->isRightToLeft() ? -dx : dx, dy);
- else
- viewport->update();
- emit q->updateRequest(viewport->rect(), dy);
- } else {
- control->topBlock = blockNumber;
- topLine = lineNumber;
- }
-
-}
-
-
-
-void QPlainTextEditPrivate::ensureVisible(int position, bool center, bool forceCenter) {
- Q_Q(QPlainTextEdit);
- QRectF visible = QRectF(viewport->rect()).translated(-q->contentOffset());
- QTextBlock block = control->document()->findBlock(position);
- if (!block.isValid())
- return;
- QRectF br = control->blockBoundingRect(block);
- if (!br.isValid())
- return;
- QRectF lr = br;
- QTextLine line = block.layout()->lineForTextPosition(position - block.position());
- Q_ASSERT(line.isValid());
- lr = line.naturalTextRect().translated(br.topLeft());
-
- if (lr.bottom() >= visible.bottom() || (center && lr.top() < visible.top()) || forceCenter){
-
- qreal height = visible.height();
- if (center)
- height /= 2;
-
- qreal h = center ? line.naturalTextRect().center().y() : line.naturalTextRect().bottom();
-
- QTextBlock previousVisibleBlock = block;
- while (h < height && block.previous().isValid()) {
- previousVisibleBlock = block;
- do {
- block = block.previous();
- } while (!block.isVisible() && block.previous().isValid());
- h += q->blockBoundingRect(block).height();
- }
-
- int l = 0;
- int lineCount = block.layout()->lineCount();
- int voffset = verticalOffset(block.blockNumber(), 0);
- while (l < lineCount) {
- QRectF lineRect = block.layout()->lineAt(l).naturalTextRect();
- if (h - voffset - lineRect.top() <= height)
- break;
- ++l;
- }
-
- if (l >= lineCount) {
- block = previousVisibleBlock;
- l = 0;
- }
- setTopBlock(block.blockNumber(), l);
- } else if (lr.top() < visible.top()) {
- setTopBlock(block.blockNumber(), line.lineNumber());
- }
-
-}
-
-
-void QPlainTextEditPrivate::updateViewport()
-{
- Q_Q(QPlainTextEdit);
- viewport->update();
- emit q->updateRequest(viewport->rect(), 0);
-}
-
-QPlainTextEditPrivate::QPlainTextEditPrivate()
- : control(0),
- tabChangesFocus(false),
- lineWrap(QPlainTextEdit::WidgetWidth),
- wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere),
- clickCausedFocus(0),topLine(0),
- pageUpDownLastCursorYIsValid(false)
-{
- showCursorOnInitialShow = true;
- backgroundVisible = false;
- centerOnScroll = false;
- inDrag = false;
-}
-
-
-void QPlainTextEditPrivate::init(const QString &txt)
-{
- Q_Q(QPlainTextEdit);
- control = new QPlainTextEditControl(q);
-
- QTextDocument *doc = new QTextDocument(control);
- QAbstractTextDocumentLayout *layout = new QPlainTextDocumentLayout(doc);
- doc->setDocumentLayout(layout);
- control->setDocument(doc);
-
- control->setPalette(q->palette());
-
- QObject::connect(vbar, SIGNAL(actionTriggered(int)), q, SLOT(_q_verticalScrollbarActionTriggered(int)));
-
- QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));
- QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));
- QObject::connect(control, SIGNAL(blockCountChanged(int)), q, SIGNAL(blockCountChanged(int)));
- QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));
- QObject::connect(control, SIGNAL(modificationChanged(bool)), q, SIGNAL(modificationChanged(bool)));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));
- QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
- QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
- QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
- QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(_q_cursorPositionChanged()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorPositionChanged()));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));
-
- // set a null page size initially to avoid any relayouting until the textedit
- // is shown. relayoutDocument() will take care of setting the page size to the
- // viewport dimensions later.
- doc->setTextWidth(-1);
- doc->documentLayout()->setPaintDevice(viewport);
- doc->setDefaultFont(q->font());
-
-
- if (!txt.isEmpty())
- control->setPlainText(txt);
-
- hbar->setSingleStep(20);
- vbar->setSingleStep(1);
-
- viewport->setBackgroundRole(QPalette::Base);
- q->setAcceptDrops(true);
- q->setFocusPolicy(Qt::WheelFocus);
- q->setAttribute(Qt::WA_KeyCompression);
- q->setAttribute(Qt::WA_InputMethodEnabled);
-
-#ifndef QT_NO_CURSOR
- viewport->setCursor(Qt::IBeamCursor);
-#endif
- originalOffsetY = 0;
-#ifdef Q_WS_WIN
- setSingleFingerPanEnabled(true);
-#endif
-}
-
-void QPlainTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
-{
- Q_Q(QPlainTextEdit);
- if (!contentsRect.isValid()) {
- updateViewport();
- return;
- }
- const int xOffset = horizontalOffset();
- const int yOffset = verticalOffset();
- const QRect visibleRect(xOffset, yOffset, viewport->width(), viewport->height());
-
- QRect r = contentsRect.adjusted(-1, -1, 1, 1).intersected(visibleRect).toAlignedRect();
- if (r.isEmpty())
- return;
-
- r.translate(-xOffset, -yOffset);
- viewport->update(r);
- emit q->updateRequest(r, 0);
-}
-
-void QPlainTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode, bool moveCursor)
-{
-
- Q_Q(QPlainTextEdit);
-
- QTextCursor cursor = control->textCursor();
- if (moveCursor) {
- ensureCursorVisible();
- if (!pageUpDownLastCursorYIsValid)
- pageUpDownLastCursorY = control->cursorRect(cursor).top() - verticalOffset();
- }
-
- qreal lastY = pageUpDownLastCursorY;
-
-
- if (op == QTextCursor::Down) {
- QRectF visible = QRectF(viewport->rect()).translated(-q->contentOffset());
- QTextBlock firstVisibleBlock = q->firstVisibleBlock();
- QTextBlock block = firstVisibleBlock;
- QRectF br = q->blockBoundingRect(block);
- qreal h = 0;
- int atEnd = false;
- while (h + br.height() <= visible.bottom()) {
- if (!block.next().isValid()) {
- atEnd = true;
- lastY = visible.bottom(); // set cursor to last line
- break;
- }
- h += br.height();
- block = block.next();
- br = q->blockBoundingRect(block);
- }
-
- if (!atEnd) {
- int line = 0;
- qreal diff = visible.bottom() - h;
- int lineCount = block.layout()->lineCount();
- while (line < lineCount - 1) {
- if (block.layout()->lineAt(line).naturalTextRect().bottom() > diff) {
- // the first line that did not completely fit the screen
- break;
- }
- ++line;
- }
- setTopBlock(block.blockNumber(), line);
- }
-
- if (moveCursor) {
- // move using movePosition to keep the cursor's x
- lastY += verticalOffset();
- bool moved = false;
- do {
- moved = cursor.movePosition(op, moveMode);
- } while (moved && control->cursorRect(cursor).top() < lastY);
- }
-
- } else if (op == QTextCursor::Up) {
-
- QRectF visible = QRectF(viewport->rect()).translated(-q->contentOffset());
- visible.translate(0, -visible.height()); // previous page
- QTextBlock block = q->firstVisibleBlock();
- qreal h = 0;
- while (h >= visible.top()) {
- if (!block.previous().isValid()) {
- if (control->topBlock == 0 && topLine == 0) {
- lastY = 0; // set cursor to first line
- }
- break;
- }
- block = block.previous();
- QRectF br = q->blockBoundingRect(block);
- h -= br.height();
- }
-
- int line = 0;
- if (block.isValid()) {
- qreal diff = visible.top() - h;
- int lineCount = block.layout()->lineCount();
- while (line < lineCount) {
- if (block.layout()->lineAt(line).naturalTextRect().top() >= diff)
- break;
- ++line;
- }
- if (line == lineCount) {
- if (block.next().isValid() && block.next() != q->firstVisibleBlock()) {
- block = block.next();
- line = 0;
- } else {
- --line;
- }
- }
- }
- setTopBlock(block.blockNumber(), line);
-
- if (moveCursor) {
- cursor.setVisualNavigation(true);
- // move using movePosition to keep the cursor's x
- lastY += verticalOffset();
- bool moved = false;
- do {
- moved = cursor.movePosition(op, moveMode);
- } while (moved && control->cursorRect(cursor).top() > lastY);
- }
- }
-
- if (moveCursor) {
- control->setTextCursor(cursor);
- pageUpDownLastCursorYIsValid = true;
- }
-}
-
-#ifndef QT_NO_SCROLLBAR
-
-void QPlainTextEditPrivate::_q_adjustScrollbars()
-{
- Q_Q(QPlainTextEdit);
- QTextDocument *doc = control->document();
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
- Q_ASSERT(documentLayout);
- bool documentSizeChangedBlocked = documentLayout->priv()->blockDocumentSizeChanged;
- documentLayout->priv()->blockDocumentSizeChanged = true;
- qreal margin = doc->documentMargin();
-
- int vmax = 0;
-
- int vSliderLength = 0;
- if (!centerOnScroll && q->isVisible()) {
- QTextBlock block = doc->lastBlock();
- const qreal visible = viewport->rect().height() - margin - 1;
- qreal y = 0;
- int visibleFromBottom = 0;
-
- while (block.isValid()) {
- if (!block.isVisible()) {
- block = block.previous();
- continue;
- }
- y += documentLayout->blockBoundingRect(block).height();
-
- QTextLayout *layout = block.layout();
- int layoutLineCount = layout->lineCount();
- if (y > visible) {
- int lineNumber = 0;
- while (lineNumber < layoutLineCount) {
- QTextLine line = layout->lineAt(lineNumber);
- const QRectF lr = line.naturalTextRect();
- if (lr.top() >= y - visible)
- break;
- ++lineNumber;
- }
- if (lineNumber < layoutLineCount)
- visibleFromBottom += (layoutLineCount - lineNumber);
- break;
-
- }
- visibleFromBottom += layoutLineCount;
- block = block.previous();
- }
- vmax = qMax(0, doc->lineCount() - visibleFromBottom);
- vSliderLength = visibleFromBottom;
-
- } else {
- vmax = qMax(0, doc->lineCount() - 1);
- vSliderLength = viewport->height() / q->fontMetrics().lineSpacing();
- }
-
-
-
- QSizeF documentSize = documentLayout->documentSize();
- vbar->setRange(0, qMax(0, vmax));
- vbar->setPageStep(vSliderLength);
- int visualTopLine = vmax;
- QTextBlock firstVisibleBlock = q->firstVisibleBlock();
- if (firstVisibleBlock.isValid())
- visualTopLine = firstVisibleBlock.firstLineNumber() + topLine;
- bool vbarSignalsBlocked = vbar->blockSignals(true);
- vbar->setValue(visualTopLine);
- vbar->blockSignals(vbarSignalsBlocked);
-
- hbar->setRange(0, (int)documentSize.width() - viewport->width());
- hbar->setPageStep(viewport->width());
- documentLayout->priv()->blockDocumentSizeChanged = documentSizeChangedBlocked;
- setTopLine(vbar->value());
-}
-
-#endif
-
-
-void QPlainTextEditPrivate::ensureViewportLayouted()
-{
-}
-
-/*!
- \class QPlainTextEdit
- \since 4.4
- \brief The QPlainTextEdit class provides a widget that is used to edit and display
- plain text.
-
- \ingroup richtext-processing
-
-
- \tableofcontents
-
- \section1 Introduction and Concepts
-
- QPlainTextEdit is an advanced viewer/editor supporting plain
- text. It is optimized to handle large documents and to respond
- quickly to user input.
-
- QPlainText uses very much the same technology and concepts as
- QTextEdit, but is optimized for plain text handling.
-
- QPlainTextEdit works on paragraphs and characters. A paragraph is
- a formatted string which is word-wrapped to fit into the width of
- the widget. By default when reading plain text, one newline
- signifies a paragraph. A document consists of zero or more
- paragraphs. Paragraphs are separated by hard line breaks. Each
- character within a paragraph has its own attributes, for example,
- font and color.
-
- The shape of the mouse cursor on a QPlainTextEdit is
- Qt::IBeamCursor by default. It can be changed through the
- viewport()'s cursor property.
-
- \section1 Using QPlainTextEdit as a Display Widget
-
- The text is set or replaced using setPlainText() which deletes the
- existing text and replaces it with the text passed to setPlainText().
-
- Text can be inserted using the QTextCursor class or using the
- convenience functions insertPlainText(), appendPlainText() or
- paste().
-
- By default, the text edit wraps words at whitespace to fit within
- the text edit widget. The setLineWrapMode() function is used to
- specify the kind of line wrap you want, \l WidgetWidth or \l
- NoWrap if you don't want any wrapping. If you use word wrap to
- the widget's width \l WidgetWidth, you can specify whether to
- break on whitespace or anywhere with setWordWrapMode().
-
- The find() function can be used to find and select a given string
- within the text.
-
- If you want to limit the total number of paragraphs in a
- QPlainTextEdit, as it is for example useful in a log viewer, then
- you can use the maximumBlockCount property. The combination of
- setMaximumBlockCount() and appendPlainText() turns QPlainTextEdit
- into an efficient viewer for log text. The scrolling can be
- reduced with the centerOnScroll() property, making the log viewer
- even faster. Text can be formatted in a limited way, either using
- a syntax highlighter (see below), or by appending html-formatted
- text with appendHtml(). While QPlainTextEdit does not support
- complex rich text rendering with tables and floats, it does
- support limited paragraph-based formatting that you may need in a
- log viewer.
-
- \section2 Read-only Key Bindings
-
- When QPlainTextEdit is used read-only the key bindings are limited to
- navigation, and text may only be selected with the mouse:
- \table
- \header \i Keypresses \i Action
- \row \i Qt::UpArrow \i Moves one line up.
- \row \i Qt::DownArrow \i Moves one line down.
- \row \i Qt::LeftArrow \i Moves one character to the left.
- \row \i Qt::RightArrow \i Moves one character to the right.
- \row \i PageUp \i Moves one (viewport) page up.
- \row \i PageDown \i Moves one (viewport) page down.
- \row \i Home \i Moves to the beginning of the text.
- \row \i End \i Moves to the end of the text.
- \row \i Alt+Wheel
- \i Scrolls the page horizontally (the Wheel is the mouse wheel).
- \row \i Ctrl+Wheel \i Zooms the text.
- \row \i Ctrl+A \i Selects all text.
- \endtable
-
-
- \section1 Using QPlainTextEdit as an Editor
-
- All the information about using QPlainTextEdit as a display widget also
- applies here.
-
- Selection of text is handled by the QTextCursor class, which provides
- functionality for creating selections, retrieving the text contents or
- deleting selections. You can retrieve the object that corresponds with
- the user-visible cursor using the textCursor() method. If you want to set
- a selection in QPlainTextEdit just create one on a QTextCursor object and
- then make that cursor the visible cursor using setCursor(). The selection
- can be copied to the clipboard with copy(), or cut to the clipboard with
- cut(). The entire text can be selected using selectAll().
-
- QPlainTextEdit holds a QTextDocument object which can be retrieved using the
- document() method. You can also set your own document object using setDocument().
- QTextDocument emits a textChanged() signal if the text changes and it also
- provides a isModified() function which will return true if the text has been
- modified since it was either loaded or since the last call to setModified
- with false as argument. In addition it provides methods for undo and redo.
-
- \section2 Syntax Highlighting
-
- Just like QTextEdit, QPlainTextEdit works together with
- QSyntaxHighlighter.
-
- \section2 Editing Key Bindings
-
- The list of key bindings which are implemented for editing:
- \table
- \header \i Keypresses \i Action
- \row \i Backspace \i Deletes the character to the left of the cursor.
- \row \i Delete \i Deletes the character to the right of the cursor.
- \row \i Ctrl+C \i Copy the selected text to the clipboard.
- \row \i Ctrl+Insert \i Copy the selected text to the clipboard.
- \row \i Ctrl+K \i Deletes to the end of the line.
- \row \i Ctrl+V \i Pastes the clipboard text into text edit.
- \row \i Shift+Insert \i Pastes the clipboard text into text edit.
- \row \i Ctrl+X \i Deletes the selected text and copies it to the clipboard.
- \row \i Shift+Delete \i Deletes the selected text and copies it to the clipboard.
- \row \i Ctrl+Z \i Undoes the last operation.
- \row \i Ctrl+Y \i Redoes the last operation.
- \row \i LeftArrow \i Moves the cursor one character to the left.
- \row \i Ctrl+LeftArrow \i Moves the cursor one word to the left.
- \row \i RightArrow \i Moves the cursor one character to the right.
- \row \i Ctrl+RightArrow \i Moves the cursor one word to the right.
- \row \i UpArrow \i Moves the cursor one line up.
- \row \i Ctrl+UpArrow \i Moves the cursor one word up.
- \row \i DownArrow \i Moves the cursor one line down.
- \row \i Ctrl+Down Arrow \i Moves the cursor one word down.
- \row \i PageUp \i Moves the cursor one page up.
- \row \i PageDown \i Moves the cursor one page down.
- \row \i Home \i Moves the cursor to the beginning of the line.
- \row \i Ctrl+Home \i Moves the cursor to the beginning of the text.
- \row \i End \i Moves the cursor to the end of the line.
- \row \i Ctrl+End \i Moves the cursor to the end of the text.
- \row \i Alt+Wheel \i Scrolls the page horizontally (the Wheel is the mouse wheel).
- \row \i Ctrl+Wheel \i Zooms the text.
- \endtable
-
- To select (mark) text hold down the Shift key whilst pressing one
- of the movement keystrokes, for example, \e{Shift+Right Arrow}
- will select the character to the right, and \e{Shift+Ctrl+Right
- Arrow} will select the word to the right, etc.
-
- \section1 Differences to QTextEdit
-
- QPlainTextEdit is a thin class, implemented by using most of the
- technology that is behind QTextEdit and QTextDocument. Its
- performance benefits over QTextEdit stem mostly from using a
- different and simplified text layout called
- QPlainTextDocumentLayout on the text document (see
- QTextDocument::setDocumentLayout()). The plain text document layout
- does not support tables nor embedded frames, and \e{replaces a
- pixel-exact height calculation with a line-by-line respectively
- paragraph-by-paragraph scrolling approach}. This makes it possible
- to handle significantly larger documents, and still resize the
- editor with line wrap enabled in real time. It also makes for a
- fast log viewer (see setMaximumBlockCount()).
-
-
- \sa QTextDocument, QTextCursor, {Application Example},
- {Code Editor Example}, {Syntax Highlighter Example},
- {Rich Text Processing}
-
-*/
-
-/*!
- \property QPlainTextEdit::plainText
-
- This property gets and sets the plain text editor's contents. The previous
- contents are removed and undo/redo history is reset when this property is set.
-
- By default, for an editor with no contents, this property contains an empty string.
-*/
-
-/*!
- \property QPlainTextEdit::undoRedoEnabled
- \brief whether undo and redo are enabled
-
- Users are only able to undo or redo actions if this property is
- true, and if there is an action that can be undone (or redone).
-
- By default, this property is true.
-*/
-
-/*!
- \enum QPlainTextEdit::LineWrapMode
-
- \value NoWrap
- \value WidgetWidth
-*/
-
-
-/*!
- Constructs an empty QPlainTextEdit with parent \a
- parent.
-*/
-QPlainTextEdit::QPlainTextEdit(QWidget *parent)
- : QAbstractScrollArea(*new QPlainTextEditPrivate, parent)
-{
- Q_D(QPlainTextEdit);
- d->init();
-}
-
-/*!
- \internal
-*/
-QPlainTextEdit::QPlainTextEdit(QPlainTextEditPrivate &dd, QWidget *parent)
- : QAbstractScrollArea(dd, parent)
-{
- Q_D(QPlainTextEdit);
- d->init();
-}
-
-/*!
- Constructs a QPlainTextEdit with parent \a parent. The text edit will display
- the plain text \a text.
-*/
-QPlainTextEdit::QPlainTextEdit(const QString &text, QWidget *parent)
- : QAbstractScrollArea(*new QPlainTextEditPrivate, parent)
-{
- Q_D(QPlainTextEdit);
- d->init(text);
-}
-
-
-/*!
- Destructor.
-*/
-QPlainTextEdit::~QPlainTextEdit()
-{
- Q_D(QPlainTextEdit);
- if (d->documentLayoutPtr) {
- if (d->documentLayoutPtr->priv()->mainViewPrivate == d)
- d->documentLayoutPtr->priv()->mainViewPrivate = 0;
- }
-}
-
-/*!
- Makes \a document the new document of the text editor.
-
- The parent QObject of the provided document remains the owner
- of the object. If the current document is a child of the text
- editor, then it is deleted.
-
- The document must have a document layout that inherits
- QPlainTextDocumentLayout (see QTextDocument::setDocumentLayout()).
-
- \sa document()
-*/
-void QPlainTextEdit::setDocument(QTextDocument *document)
-{
- Q_D(QPlainTextEdit);
- QPlainTextDocumentLayout *documentLayout = 0;
-
- if (!document) {
- document = new QTextDocument(d->control);
- documentLayout = new QPlainTextDocumentLayout(document);
- document->setDocumentLayout(documentLayout);
- } else {
- documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document->documentLayout());
- if (!documentLayout) {
- qWarning("QPlainTextEdit::setDocument: Document set does not support QPlainTextDocumentLayout");
- return;
- }
- }
- d->control->setDocument(document);
- if (!documentLayout->priv()->mainViewPrivate)
- documentLayout->priv()->mainViewPrivate = d;
- d->documentLayoutPtr = documentLayout;
- d->updateDefaultTextOption();
- d->relayoutDocument();
- d->_q_adjustScrollbars();
-}
-
-/*!
- Returns a pointer to the underlying document.
-
- \sa setDocument()
-*/
-QTextDocument *QPlainTextEdit::document() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->document();
-}
-
-/*!
- Sets the visible \a cursor.
-*/
-void QPlainTextEdit::setTextCursor(const QTextCursor &cursor)
-{
- Q_D(QPlainTextEdit);
- d->control->setTextCursor(cursor);
-}
-
-/*!
- Returns a copy of the QTextCursor that represents the currently visible cursor.
- Note that changes on the returned cursor do not affect QPlainTextEdit's cursor; use
- setTextCursor() to update the visible cursor.
- */
-QTextCursor QPlainTextEdit::textCursor() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->textCursor();
-}
-
-/*!
- Returns the reference of the anchor at position \a pos, or an
- empty string if no anchor exists at that point.
-
- \since 4.7
- */
-QString QPlainTextEdit::anchorAt(const QPoint &pos) const
-{
- Q_D(const QPlainTextEdit);
- int cursorPos = d->control->hitTest(pos + QPoint(d->horizontalOffset(),
- d->verticalOffset()),
- Qt::ExactHit);
- if (cursorPos < 0)
- return QString();
-
- QTextDocumentPrivate *pieceTable = document()->docHandle();
- QTextDocumentPrivate::FragmentIterator it = pieceTable->find(cursorPos);
- QTextCharFormat fmt = pieceTable->formatCollection()->charFormat(it->format);
- return fmt.anchorHref();
-}
-
-/*!
- Undoes the last operation.
-
- If there is no operation to undo, i.e. there is no undo step in
- the undo/redo history, nothing happens.
-
- \sa redo()
-*/
-void QPlainTextEdit::undo()
-{
- Q_D(QPlainTextEdit);
- d->control->undo();
-}
-
-void QPlainTextEdit::redo()
-{
- Q_D(QPlainTextEdit);
- d->control->redo();
-}
-
-/*!
- \fn void QPlainTextEdit::redo()
-
- Redoes the last operation.
-
- If there is no operation to redo, i.e. there is no redo step in
- the undo/redo history, nothing happens.
-
- \sa undo()
-*/
-
-#ifndef QT_NO_CLIPBOARD
-/*!
- Copies the selected text to the clipboard and deletes it from
- the text edit.
-
- If there is no selected text nothing happens.
-
- \sa copy() paste()
-*/
-
-void QPlainTextEdit::cut()
-{
- Q_D(QPlainTextEdit);
- d->control->cut();
-}
-
-/*!
- Copies any selected text to the clipboard.
-
- \sa copyAvailable()
-*/
-
-void QPlainTextEdit::copy()
-{
- Q_D(QPlainTextEdit);
- d->control->copy();
-}
-
-/*!
- Pastes the text from the clipboard into the text edit at the
- current cursor position.
-
- If there is no text in the clipboard nothing happens.
-
- To change the behavior of this function, i.e. to modify what
- QPlainTextEdit can paste and how it is being pasted, reimplement the
- virtual canInsertFromMimeData() and insertFromMimeData()
- functions.
-
- \sa cut() copy()
-*/
-
-void QPlainTextEdit::paste()
-{
- Q_D(QPlainTextEdit);
- d->control->paste();
-}
-#endif
-
-/*!
- Deletes all the text in the text edit.
-
- Note that the undo/redo history is cleared by this function.
-
- \sa cut() setPlainText()
-*/
-void QPlainTextEdit::clear()
-{
- Q_D(QPlainTextEdit);
- // clears and sets empty content
- d->control->topBlock = d->topLine = 0;
- d->control->clear();
-}
-
-
-/*!
- Selects all text.
-
- \sa copy() cut() textCursor()
- */
-void QPlainTextEdit::selectAll()
-{
- Q_D(QPlainTextEdit);
- d->control->selectAll();
-}
-
-/*! \internal
-*/
-bool QPlainTextEdit::event(QEvent *e)
-{
- Q_D(QPlainTextEdit);
-
-#ifndef QT_NO_CONTEXTMENU
- if (e->type() == QEvent::ContextMenu
- && static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
- ensureCursorVisible();
- const QPoint cursorPos = cursorRect().center();
- QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
- ce.setAccepted(e->isAccepted());
- const bool result = QAbstractScrollArea::event(&ce);
- e->setAccepted(ce.isAccepted());
- return result;
- }
-#endif // QT_NO_CONTEXTMENU
- if (e->type() == QEvent::ShortcutOverride
- || e->type() == QEvent::ToolTip) {
- d->sendControlEvent(e);
- }
-#ifdef QT_KEYPAD_NAVIGATION
- else if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
- if (QApplication::keypadNavigationEnabled())
- d->sendControlEvent(e);
- }
-#endif
-#ifndef QT_NO_GESTURES
- else if (e->type() == QEvent::Gesture) {
- QGestureEvent *ge = static_cast<QGestureEvent *>(e);
- QPanGesture *g = static_cast<QPanGesture *>(ge->gesture(Qt::PanGesture));
- if (g) {
- QScrollBar *hBar = horizontalScrollBar();
- QScrollBar *vBar = verticalScrollBar();
- if (g->state() == Qt::GestureStarted)
- d->originalOffsetY = vBar->value();
- QPointF offset = g->offset();
- if (!offset.isNull()) {
- if (QApplication::isRightToLeft())
- offset.rx() *= -1;
- // QPlainTextEdit scrolls by lines only in vertical direction
- QFontMetrics fm(document()->defaultFont());
- int lineHeight = fm.height();
- int newX = hBar->value() - g->delta().x();
- int newY = d->originalOffsetY - offset.y()/lineHeight;
- hBar->setValue(newX);
- vBar->setValue(newY);
- }
- }
- return true;
- }
-#endif // QT_NO_GESTURES
- return QAbstractScrollArea::event(e);
-}
-
-/*! \internal
-*/
-
-void QPlainTextEdit::timerEvent(QTimerEvent *e)
-{
- Q_D(QPlainTextEdit);
- if (e->timerId() == d->autoScrollTimer.timerId()) {
- QRect visible = d->viewport->rect();
- QPoint pos;
- if (d->inDrag) {
- pos = d->autoScrollDragPos;
- visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
- -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
- } else {
- const QPoint globalPos = QCursor::pos();
- pos = d->viewport->mapFromGlobal(globalPos);
- QMouseEvent ev(QEvent::MouseMove, pos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
- mouseMoveEvent(&ev);
- }
- int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
- int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
- int delta = qMax(deltaX, deltaY);
- if (delta >= 0) {
- if (delta < 7)
- delta = 7;
- int timeout = 4900 / (delta * delta);
- d->autoScrollTimer.start(timeout, this);
-
- if (deltaY > 0)
- d->vbar->triggerAction(pos.y() < visible.center().y() ?
- QAbstractSlider::SliderSingleStepSub
- : QAbstractSlider::SliderSingleStepAdd);
- if (deltaX > 0)
- d->hbar->triggerAction(pos.x() < visible.center().x() ?
- QAbstractSlider::SliderSingleStepSub
- : QAbstractSlider::SliderSingleStepAdd);
- }
- }
-#ifdef QT_KEYPAD_NAVIGATION
- else if (e->timerId() == d->deleteAllTimer.timerId()) {
- d->deleteAllTimer.stop();
- clear();
- }
-#endif
-}
-
-/*!
- Changes the text of the text edit to the string \a text.
- Any previous text is removed.
-
- \a text is interpreted as plain text.
-
- Note that the undo/redo history is cleared by this function.
-
- \sa toText()
-*/
-
-void QPlainTextEdit::setPlainText(const QString &text)
-{
- Q_D(QPlainTextEdit);
- d->control->setPlainText(text);
-}
-
-/*!
- \fn QString QPlainTextEdit::toPlainText() const
-
- Returns the text of the text edit as plain text.
-
- \sa QPlainTextEdit::setPlainText()
- */
-
-/*! \reimp
-*/
-void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QPlainTextEdit);
-
-#ifdef QT_KEYPAD_NAVIGATION
- switch (e->key()) {
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- if (!(d->control->textInteractionFlags() & Qt::LinksAccessibleByKeyboard))
- setEditFocus(!hasEditFocus());
- else {
- if (!hasEditFocus())
- setEditFocus(true);
- else {
- QTextCursor cursor = d->control->textCursor();
- QTextCharFormat charFmt = cursor.charFormat();
- if (!cursor.hasSelection() || charFmt.anchorHref().isEmpty()) {
- setEditFocus(false);
- }
- }
- }
- }
- break;
- case Qt::Key_Back:
- case Qt::Key_No:
- if (!QApplication::keypadNavigationEnabled()
- || (QApplication::keypadNavigationEnabled() && !hasEditFocus())) {
- e->ignore();
- return;
- }
- break;
- default:
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
- if (e->text()[0].isPrint()) {
- setEditFocus(true);
- clear();
- } else {
- e->ignore();
- return;
- }
- }
- }
- break;
- }
-#endif
-
-#ifndef QT_NO_SHORTCUT
-
- Qt::TextInteractionFlags tif = d->control->textInteractionFlags();
-
- if (tif & Qt::TextSelectableByKeyboard){
- if (e == QKeySequence::SelectPreviousPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
- return;
- } else if (e ==QKeySequence::SelectNextPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
- return;
- }
- }
- if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
- if (e == QKeySequence::MoveToPreviousPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
- return;
- } else if (e == QKeySequence::MoveToNextPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
- return;
- }
- }
-
- if (!(tif & Qt::TextEditable)) {
- switch (e->key()) {
- case Qt::Key_Space:
- e->accept();
- if (e->modifiers() & Qt::ShiftModifier)
- d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
- else
- d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
- break;
- default:
- d->sendControlEvent(e);
- if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
- if (e->key() == Qt::Key_Home) {
- d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
- e->accept();
- } else if (e->key() == Qt::Key_End) {
- d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
- e->accept();
- }
- }
- if (!e->isAccepted()) {
- QAbstractScrollArea::keyPressEvent(e);
- }
- }
- return;
- }
-#endif // QT_NO_SHORTCUT
-
- d->sendControlEvent(e);
-#ifdef QT_KEYPAD_NAVIGATION
- if (!e->isAccepted()) {
- switch (e->key()) {
- case Qt::Key_Up:
- case Qt::Key_Down:
- if (QApplication::keypadNavigationEnabled()) {
- // Cursor position didn't change, so we want to leave
- // these keys to change focus.
- e->ignore();
- return;
- }
- break;
- case Qt::Key_Left:
- case Qt::Key_Right:
- if (QApplication::keypadNavigationEnabled()
- && QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
- // Same as for Key_Up and Key_Down.
- e->ignore();
- return;
- }
- break;
- case Qt::Key_Back:
- if (!e->isAutoRepeat()) {
- if (QApplication::keypadNavigationEnabled()) {
- if (document()->isEmpty()) {
- setEditFocus(false);
- e->accept();
- } else if (!d->deleteAllTimer.isActive()) {
- e->accept();
- d->deleteAllTimer.start(750, this);
- }
- } else {
- e->ignore();
- return;
- }
- }
- break;
- default: break;
- }
- }
-#endif
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::keyReleaseEvent(QKeyEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- Q_D(QPlainTextEdit);
- if (QApplication::keypadNavigationEnabled()) {
- if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
- && d->deleteAllTimer.isActive()) {
- d->deleteAllTimer.stop();
- QTextCursor cursor = d->control->textCursor();
- QTextBlockFormat blockFmt = cursor.blockFormat();
-
- QTextList *list = cursor.currentList();
- if (list && cursor.atBlockStart()) {
- list->remove(cursor.block());
- } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
- blockFmt.setIndent(blockFmt.indent() - 1);
- cursor.setBlockFormat(blockFmt);
- } else {
- cursor.deletePreviousChar();
- }
- setTextCursor(cursor);
- }
- }
-#else
- Q_UNUSED(e);
-#endif
-}
-
-/*!
- Loads the resource specified by the given \a type and \a name.
-
- This function is an extension of QTextDocument::loadResource().
-
- \sa QTextDocument::loadResource()
-*/
-QVariant QPlainTextEdit::loadResource(int type, const QUrl &name)
-{
- Q_UNUSED(type);
- Q_UNUSED(name);
- return QVariant();
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::resizeEvent(QResizeEvent *e)
-{
- Q_D(QPlainTextEdit);
- if (e->oldSize().width() != e->size().width())
- d->relayoutDocument();
- d->_q_adjustScrollbars();
-}
-
-void QPlainTextEditPrivate::relayoutDocument()
-{
- QTextDocument *doc = control->document();
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
- Q_ASSERT(documentLayout);
- documentLayoutPtr = documentLayout;
-
- int width = viewport->width();
-
- if (documentLayout->priv()->mainViewPrivate == 0
- || documentLayout->priv()->mainViewPrivate == this
- || width > documentLayout->textWidth()) {
- documentLayout->priv()->mainViewPrivate = this;
- documentLayout->setTextWidth(width);
- }
-}
-
-static void fillBackground(QPainter *p, const QRectF &rect, QBrush brush, QRectF gradientRect = QRectF())
-{
- p->save();
- if (brush.style() >= Qt::LinearGradientPattern && brush.style() <= Qt::ConicalGradientPattern) {
- if (!gradientRect.isNull()) {
- QTransform m = QTransform::fromTranslate(gradientRect.left(), gradientRect.top());
- m.scale(gradientRect.width(), gradientRect.height());
- brush.setTransform(m);
- const_cast<QGradient *>(brush.gradient())->setCoordinateMode(QGradient::LogicalMode);
- }
- } else {
- p->setBrushOrigin(rect.topLeft());
- }
- p->fillRect(rect, brush);
- p->restore();
-}
-
-
-
-/*! \reimp
-*/
-void QPlainTextEdit::paintEvent(QPaintEvent *e)
-{
- QPainter painter(viewport());
- Q_ASSERT(qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout()));
-
- QPointF offset(contentOffset());
-
- QRect er = e->rect();
- QRect viewportRect = viewport()->rect();
-
- bool editable = !isReadOnly();
-
- QTextBlock block = firstVisibleBlock();
- qreal maximumWidth = document()->documentLayout()->documentSize().width();
-
- // Set a brush origin so that the WaveUnderline knows where the wave started
- painter.setBrushOrigin(offset);
-
- // keep right margin clean from full-width selection
- int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth)
- - document()->documentMargin();
- er.setRight(qMin(er.right(), maxX));
- painter.setClipRect(er);
-
-
- QAbstractTextDocumentLayout::PaintContext context = getPaintContext();
-
- while (block.isValid()) {
-
- QRectF r = blockBoundingRect(block).translated(offset);
- QTextLayout *layout = block.layout();
-
- if (!block.isVisible()) {
- offset.ry() += r.height();
- block = block.next();
- continue;
- }
-
- if (r.bottom() >= er.top() && r.top() <= er.bottom()) {
-
- QTextBlockFormat blockFormat = block.blockFormat();
-
- QBrush bg = blockFormat.background();
- if (bg != Qt::NoBrush) {
- QRectF contentsRect = r;
- contentsRect.setWidth(qMax(r.width(), maximumWidth));
- fillBackground(&painter, contentsRect, bg);
- }
-
-
- QVector<QTextLayout::FormatRange> selections;
- int blpos = block.position();
- int bllen = block.length();
- for (int i = 0; i < context.selections.size(); ++i) {
- const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
- const int selStart = range.cursor.selectionStart() - blpos;
- const int selEnd = range.cursor.selectionEnd() - blpos;
- if (selStart < bllen && selEnd > 0
- && selEnd > selStart) {
- QTextLayout::FormatRange o;
- o.start = selStart;
- o.length = selEnd - selStart;
- o.format = range.format;
- selections.append(o);
- } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
- && block.contains(range.cursor.position())) {
- // for full width selections we don't require an actual selection, just
- // a position to specify the line. that's more convenience in usage.
- QTextLayout::FormatRange o;
- QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
- o.start = l.textStart();
- o.length = l.textLength();
- if (o.start + o.length == bllen - 1)
- ++o.length; // include newline
- o.format = range.format;
- selections.append(o);
- }
- }
-
- bool drawCursor = (editable
- && context.cursorPosition >= blpos
- && context.cursorPosition < blpos + bllen);
-
- bool drawCursorAsBlock = drawCursor && overwriteMode() ;
-
- if (drawCursorAsBlock) {
- if (context.cursorPosition == blpos + bllen - 1) {
- drawCursorAsBlock = false;
- } else {
- QTextLayout::FormatRange o;
- o.start = context.cursorPosition - blpos;
- o.length = 1;
- o.format.setForeground(palette().base());
- o.format.setBackground(palette().text());
- selections.append(o);
- }
- }
-
-
- layout->draw(&painter, offset, selections, er);
- if ((drawCursor && !drawCursorAsBlock)
- || (editable && context.cursorPosition < -1
- && !layout->preeditAreaText().isEmpty())) {
- int cpos = context.cursorPosition;
- if (cpos < -1)
- cpos = layout->preeditAreaPosition() - (cpos + 2);
- else
- cpos -= blpos;
- layout->drawCursor(&painter, offset, cpos, cursorWidth());
- }
- }
-
- offset.ry() += r.height();
- if (offset.y() > viewportRect.height())
- break;
- block = block.next();
- }
-
- if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom()
- && (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) {
- painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().background());
- }
-}
-
-
-void QPlainTextEditPrivate::updateDefaultTextOption()
-{
- QTextDocument *doc = control->document();
-
- QTextOption opt = doc->defaultTextOption();
- QTextOption::WrapMode oldWrapMode = opt.wrapMode();
-
- if (lineWrap == QPlainTextEdit::NoWrap)
- opt.setWrapMode(QTextOption::NoWrap);
- else
- opt.setWrapMode(wordWrap);
-
- if (opt.wrapMode() != oldWrapMode)
- doc->setDefaultTextOption(opt);
-}
-
-
-/*! \reimp
-*/
-void QPlainTextEdit::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QPlainTextEdit);
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
- setEditFocus(true);
-#endif
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->inDrag = false; // paranoia
- const QPoint pos = e->pos();
- d->sendControlEvent(e);
- if (!(e->buttons() & Qt::LeftButton))
- return;
- QRect visible = d->viewport->rect();
- if (visible.contains(pos))
- d->autoScrollTimer.stop();
- else if (!d->autoScrollTimer.isActive())
- d->autoScrollTimer.start(100, this);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->sendControlEvent(e);
- if (d->autoScrollTimer.isActive()) {
- d->autoScrollTimer.stop();
- d->ensureCursorVisible();
- }
-
- if (!isReadOnly() && rect().contains(e->pos()))
- d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
- d->clickCausedFocus = 0;
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-bool QPlainTextEdit::focusNextPrevChild(bool next)
-{
- Q_D(const QPlainTextEdit);
- if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
- return false;
- return QAbstractScrollArea::focusNextPrevChild(next);
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \fn void QPlainTextEdit::contextMenuEvent(QContextMenuEvent *event)
-
- Shows the standard context menu created with createStandardContextMenu().
-
- If you do not want the text edit to have a context menu, you can set
- its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
- customize the context menu, reimplement this function. If you want
- to extend the standard context menu, reimplement this function, call
- createStandardContextMenu() and extend the menu returned.
-
- Information about the event is passed in the \a event object.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qplaintextedit.cpp 0
-*/
-void QPlainTextEdit::contextMenuEvent(QContextMenuEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->sendControlEvent(e);
-}
-#endif // QT_NO_CONTEXTMENU
-
-#ifndef QT_NO_DRAGANDDROP
-/*! \reimp
-*/
-void QPlainTextEdit::dragEnterEvent(QDragEnterEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->inDrag = true;
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->inDrag = false;
- d->autoScrollTimer.stop();
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::dragMoveEvent(QDragMoveEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->autoScrollDragPos = e->pos();
- if (!d->autoScrollTimer.isActive())
- d->autoScrollTimer.start(100, this);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::dropEvent(QDropEvent *e)
-{
- Q_D(QPlainTextEdit);
- d->inDrag = false;
- d->autoScrollTimer.stop();
- d->sendControlEvent(e);
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*! \reimp
- */
-void QPlainTextEdit::inputMethodEvent(QInputMethodEvent *e)
-{
- Q_D(QPlainTextEdit);
-#ifdef QT_KEYPAD_NAVIGATION
- if (d->control->textInteractionFlags() & Qt::TextEditable
- && QApplication::keypadNavigationEnabled()
- && !hasEditFocus()) {
- setEditFocus(true);
- selectAll(); // so text is replaced rather than appended to
- }
-#endif
- d->sendControlEvent(e);
- ensureCursorVisible();
-}
-
-/*!\reimp
-*/
-void QPlainTextEdit::scrollContentsBy(int dx, int /*dy*/)
-{
- Q_D(QPlainTextEdit);
- d->setTopLine(d->vbar->value(), dx);
-}
-
-/*!\reimp
-*/
-QVariant QPlainTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
-{
- Q_D(const QPlainTextEdit);
- QVariant v = d->control->inputMethodQuery(property);
- const QPoint offset(-d->horizontalOffset(), -0);
- if (v.type() == QVariant::RectF)
- v = v.toRectF().toRect().translated(offset);
- else if (v.type() == QVariant::PointF)
- v = v.toPointF().toPoint() + offset;
- else if (v.type() == QVariant::Rect)
- v = v.toRect().translated(offset);
- else if (v.type() == QVariant::Point)
- v = v.toPoint() + offset;
- return v;
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::focusInEvent(QFocusEvent *e)
-{
- Q_D(QPlainTextEdit);
- if (e->reason() == Qt::MouseFocusReason) {
- d->clickCausedFocus = 1;
- }
- QAbstractScrollArea::focusInEvent(e);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::focusOutEvent(QFocusEvent *e)
-{
- Q_D(QPlainTextEdit);
- QAbstractScrollArea::focusOutEvent(e);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::showEvent(QShowEvent *)
-{
- Q_D(QPlainTextEdit);
- if (d->showCursorOnInitialShow) {
- d->showCursorOnInitialShow = false;
- ensureCursorVisible();
- }
-}
-
-/*! \reimp
-*/
-void QPlainTextEdit::changeEvent(QEvent *e)
-{
- Q_D(QPlainTextEdit);
- QAbstractScrollArea::changeEvent(e);
- if (e->type() == QEvent::ApplicationFontChange
- || e->type() == QEvent::FontChange) {
- d->control->document()->setDefaultFont(font());
- } else if(e->type() == QEvent::ActivationChange) {
- if (!isActiveWindow())
- d->autoScrollTimer.stop();
- } else if (e->type() == QEvent::EnabledChange) {
- e->setAccepted(isEnabled());
- d->sendControlEvent(e);
- } else if (e->type() == QEvent::PaletteChange) {
- d->control->setPalette(palette());
- } else if (e->type() == QEvent::LayoutDirectionChange) {
- d->sendControlEvent(e);
- }
-}
-
-/*! \reimp
-*/
-#ifndef QT_NO_WHEELEVENT
-void QPlainTextEdit::wheelEvent(QWheelEvent *e)
-{
- QAbstractScrollArea::wheelEvent(e);
- updateMicroFocus();
-}
-#endif
-
-#ifndef QT_NO_CONTEXTMENU
-/*! This function creates the standard context menu which is shown
- when the user clicks on the line edit with the right mouse
- button. It is called from the default contextMenuEvent() handler.
- The popup menu's ownership is transferred to the caller.
-*/
-
-QMenu *QPlainTextEdit::createStandardContextMenu()
-{
- Q_D(QPlainTextEdit);
- return d->control->createStandardContextMenu(QPointF(), this);
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*!
- returns a QTextCursor at position \a pos (in viewport coordinates).
-*/
-QTextCursor QPlainTextEdit::cursorForPosition(const QPoint &pos) const
-{
- Q_D(const QPlainTextEdit);
- return d->control->cursorForPosition(d->mapToContents(pos));
-}
-
-/*!
- returns a rectangle (in viewport coordinates) that includes the
- \a cursor.
- */
-QRect QPlainTextEdit::cursorRect(const QTextCursor &cursor) const
-{
- Q_D(const QPlainTextEdit);
- if (cursor.isNull())
- return QRect();
-
- QRect r = d->control->cursorRect(cursor).toRect();
- r.translate(-d->horizontalOffset(),-d->verticalOffset());
- return r;
-}
-
-/*!
- returns a rectangle (in viewport coordinates) that includes the
- cursor of the text edit.
- */
-QRect QPlainTextEdit::cursorRect() const
-{
- Q_D(const QPlainTextEdit);
- QRect r = d->control->cursorRect().toRect();
- r.translate(-d->horizontalOffset(),-d->verticalOffset());
- return r;
-}
-
-
-/*!
- \property QPlainTextEdit::overwriteMode
- \brief whether text entered by the user will overwrite existing text
-
- As with many text editors, the plain text editor widget can be configured
- to insert or overwrite existing text with new text entered by the user.
-
- If this property is true, existing text is overwritten, character-for-character
- by new text; otherwise, text is inserted at the cursor position, displacing
- existing text.
-
- By default, this property is false (new text does not overwrite existing text).
-*/
-
-bool QPlainTextEdit::overwriteMode() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->overwriteMode();
-}
-
-void QPlainTextEdit::setOverwriteMode(bool overwrite)
-{
- Q_D(QPlainTextEdit);
- d->control->setOverwriteMode(overwrite);
-}
-
-/*!
- \property QPlainTextEdit::tabStopWidth
- \brief the tab stop width in pixels
-
- By default, this property contains a value of 80.
-*/
-
-int QPlainTextEdit::tabStopWidth() const
-{
- Q_D(const QPlainTextEdit);
- return qRound(d->control->document()->defaultTextOption().tabStop());
-}
-
-void QPlainTextEdit::setTabStopWidth(int width)
-{
- Q_D(QPlainTextEdit);
- QTextOption opt = d->control->document()->defaultTextOption();
- if (opt.tabStop() == width || width < 0)
- return;
- opt.setTabStop(width);
- d->control->document()->setDefaultTextOption(opt);
-}
-
-/*!
- \property QPlainTextEdit::cursorWidth
-
- This property specifies the width of the cursor in pixels. The default value is 1.
-*/
-int QPlainTextEdit::cursorWidth() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->cursorWidth();
-}
-
-void QPlainTextEdit::setCursorWidth(int width)
-{
- Q_D(QPlainTextEdit);
- d->control->setCursorWidth(width);
-}
-
-
-
-/*!
- This function allows temporarily marking certain regions in the document
- with a given color, specified as \a selections. This can be useful for
- example in a programming editor to mark a whole line of text with a given
- background color to indicate the existence of a breakpoint.
-
- \sa QTextEdit::ExtraSelection, extraSelections()
-*/
-void QPlainTextEdit::setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections)
-{
- Q_D(QPlainTextEdit);
- d->control->setExtraSelections(selections);
-}
-
-/*!
- Returns previously set extra selections.
-
- \sa setExtraSelections()
-*/
-QList<QTextEdit::ExtraSelection> QPlainTextEdit::extraSelections() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->extraSelections();
-}
-
-/*!
- This function returns a new MIME data object to represent the contents
- of the text edit's current selection. It is called when the selection needs
- to be encapsulated into a new QMimeData object; for example, when a drag
- and drop operation is started, or when data is copied to the clipboard.
-
- If you reimplement this function, note that the ownership of the returned
- QMimeData object is passed to the caller. The selection can be retrieved
- by using the textCursor() function.
-*/
-QMimeData *QPlainTextEdit::createMimeDataFromSelection() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->QTextControl::createMimeDataFromSelection();
-}
-
-/*!
- This function returns true if the contents of the MIME data object, specified
- by \a source, can be decoded and inserted into the document. It is called
- for example when during a drag operation the mouse enters this widget and it
- is necessary to determine whether it is possible to accept the drag.
- */
-bool QPlainTextEdit::canInsertFromMimeData(const QMimeData *source) const
-{
- Q_D(const QPlainTextEdit);
- return d->control->QTextControl::canInsertFromMimeData(source);
-}
-
-/*!
- This function inserts the contents of the MIME data object, specified
- by \a source, into the text edit at the current cursor position. It is
- called whenever text is inserted as the result of a clipboard paste
- operation, or when the text edit accepts data from a drag and drop
- operation.
-*/
-void QPlainTextEdit::insertFromMimeData(const QMimeData *source)
-{
- Q_D(QPlainTextEdit);
- d->control->QTextControl::insertFromMimeData(source);
-}
-
-/*!
- \property QPlainTextEdit::readOnly
- \brief whether the text edit is read-only
-
- In a read-only text edit the user can only navigate through the
- text and select text; modifying the text is not possible.
-
- This property's default is false.
-*/
-
-bool QPlainTextEdit::isReadOnly() const
-{
- Q_D(const QPlainTextEdit);
- return !(d->control->textInteractionFlags() & Qt::TextEditable);
-}
-
-void QPlainTextEdit::setReadOnly(bool ro)
-{
- Q_D(QPlainTextEdit);
- Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
- if (ro) {
- flags = Qt::TextSelectableByMouse;
- } else {
- flags = Qt::TextEditorInteraction;
- }
- setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
- d->control->setTextInteractionFlags(flags);
-}
-
-/*!
- \property QPlainTextEdit::textInteractionFlags
-
- Specifies how the label should interact with user input if it displays text.
-
- If the flags contain either Qt::LinksAccessibleByKeyboard or Qt::TextSelectableByKeyboard
- then the focus policy is also automatically set to Qt::ClickFocus.
-
- The default value depends on whether the QPlainTextEdit is read-only
- or editable.
-*/
-
-void QPlainTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
-{
- Q_D(QPlainTextEdit);
- d->control->setTextInteractionFlags(flags);
-}
-
-Qt::TextInteractionFlags QPlainTextEdit::textInteractionFlags() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->textInteractionFlags();
-}
-
-/*!
- Merges the properties specified in \a modifier into the current character
- format by calling QTextCursor::mergeCharFormat on the editor's cursor.
- If the editor has a selection then the properties of \a modifier are
- directly applied to the selection.
-
- \sa QTextCursor::mergeCharFormat()
- */
-void QPlainTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
-{
- Q_D(QPlainTextEdit);
- d->control->mergeCurrentCharFormat(modifier);
-}
-
-/*!
- Sets the char format that is be used when inserting new text to \a
- format by calling QTextCursor::setCharFormat() on the editor's
- cursor. If the editor has a selection then the char format is
- directly applied to the selection.
- */
-void QPlainTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
-{
- Q_D(QPlainTextEdit);
- d->control->setCurrentCharFormat(format);
-}
-
-/*!
- Returns the char format that is used when inserting new text.
- */
-QTextCharFormat QPlainTextEdit::currentCharFormat() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->currentCharFormat();
-}
-
-
-
-/*!
- Convenience slot that inserts \a text at the current
- cursor position.
-
- It is equivalent to
-
- \snippet doc/src/snippets/code/src_gui_widgets_qplaintextedit.cpp 1
- */
-void QPlainTextEdit::insertPlainText(const QString &text)
-{
- Q_D(QPlainTextEdit);
- d->control->insertPlainText(text);
-}
-
-
-/*!
- Moves the cursor by performing the given \a operation.
-
- If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
- This is the same effect that the user achieves when they hold down the Shift key
- and move the cursor with the cursor keys.
-
- \sa QTextCursor::movePosition()
-*/
-void QPlainTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
-{
- Q_D(QPlainTextEdit);
- d->control->moveCursor(operation, mode);
-}
-
-/*!
- Returns whether text can be pasted from the clipboard into the textedit.
-*/
-bool QPlainTextEdit::canPaste() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->canPaste();
-}
-
-#ifndef QT_NO_PRINTER
-/*!
- Convenience function to print the text edit's document to the given \a printer. This
- is equivalent to calling the print method on the document directly except that this
- function also supports QPrinter::Selection as print range.
-
- \sa QTextDocument::print()
-*/
-void QPlainTextEdit::print(QPrinter *printer) const
-{
- Q_D(const QPlainTextEdit);
- d->control->print(printer);
-}
-#endif // QT _NO_PRINTER
-
-/*! \property QPlainTextEdit::tabChangesFocus
- \brief whether \gui Tab changes focus or is accepted as input
-
- In some occasions text edits should not allow the user to input
- tabulators or change indentation using the \gui Tab key, as this breaks
- the focus chain. The default is false.
-
-*/
-
-bool QPlainTextEdit::tabChangesFocus() const
-{
- Q_D(const QPlainTextEdit);
- return d->tabChangesFocus;
-}
-
-void QPlainTextEdit::setTabChangesFocus(bool b)
-{
- Q_D(QPlainTextEdit);
- d->tabChangesFocus = b;
-}
-
-/*!
- \property QPlainTextEdit::documentTitle
- \brief the title of the document parsed from the text.
-
- By default, this property contains an empty string.
-*/
-
-/*!
- \property QPlainTextEdit::lineWrapMode
- \brief the line wrap mode
-
- The default mode is WidgetWidth which causes words to be
- wrapped at the right edge of the text edit. Wrapping occurs at
- whitespace, keeping whole words intact. If you want wrapping to
- occur within words use setWordWrapMode().
-*/
-
-QPlainTextEdit::LineWrapMode QPlainTextEdit::lineWrapMode() const
-{
- Q_D(const QPlainTextEdit);
- return d->lineWrap;
-}
-
-void QPlainTextEdit::setLineWrapMode(LineWrapMode wrap)
-{
- Q_D(QPlainTextEdit);
- if (d->lineWrap == wrap)
- return;
- d->lineWrap = wrap;
- d->updateDefaultTextOption();
- d->relayoutDocument();
- d->_q_adjustScrollbars();
- ensureCursorVisible();
-}
-
-/*!
- \property QPlainTextEdit::wordWrapMode
- \brief the mode QPlainTextEdit will use when wrapping text by words
-
- By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
-
- \sa QTextOption::WrapMode
-*/
-
-QTextOption::WrapMode QPlainTextEdit::wordWrapMode() const
-{
- Q_D(const QPlainTextEdit);
- return d->wordWrap;
-}
-
-void QPlainTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
-{
- Q_D(QPlainTextEdit);
- if (mode == d->wordWrap)
- return;
- d->wordWrap = mode;
- d->updateDefaultTextOption();
-}
-
-/*!
- \property QPlainTextEdit::backgroundVisible
- \brief whether the palette background is visible outside the document area
-
- If set to true, the plain text edit paints the palette background
- on the viewport area not covered by the text document. Otherwise,
- if set to false, it won't. The feature makes it possible for
- the user to visually distinguish between the area of the document,
- painted with the base color of the palette, and the empty
- area not covered by any document.
-
- The default is false.
-*/
-
-bool QPlainTextEdit::backgroundVisible() const
-{
- Q_D(const QPlainTextEdit);
- return d->backgroundVisible;
-}
-
-void QPlainTextEdit::setBackgroundVisible(bool visible)
-{
- Q_D(QPlainTextEdit);
- if (visible == d->backgroundVisible)
- return;
- d->backgroundVisible = visible;
- d->updateViewport();
-}
-
-/*!
- \property QPlainTextEdit::centerOnScroll
- \brief whether the cursor should be centered on screen
-
- If set to true, the plain text edit scrolls the document
- vertically to make the cursor visible at the center of the
- viewport. This also allows the text edit to scroll below the end
- of the document. Otherwise, if set to false, the plain text edit
- scrolls the smallest amount possible to ensure the cursor is
- visible. The same algorithm is applied to any new line appended
- through appendPlainText().
-
- The default is false.
-
- \sa centerCursor(), ensureCursorVisible()
-*/
-
-bool QPlainTextEdit::centerOnScroll() const
-{
- Q_D(const QPlainTextEdit);
- return d->centerOnScroll;
-}
-
-void QPlainTextEdit::setCenterOnScroll(bool enabled)
-{
- Q_D(QPlainTextEdit);
- if (enabled == d->centerOnScroll)
- return;
- d->centerOnScroll = enabled;
-}
-
-
-
-/*!
- Finds the next occurrence of the string, \a exp, using the given
- \a options. Returns true if \a exp was found and changes the
- cursor to select the match; otherwise returns false.
-*/
-bool QPlainTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
-{
- Q_D(QPlainTextEdit);
- return d->control->find(exp, options);
-}
-
-/*!
- \fn void QPlainTextEdit::copyAvailable(bool yes)
-
- This signal is emitted when text is selected or de-selected in the
- text edit.
-
- When text is selected this signal will be emitted with \a yes set
- to true. If no text has been selected or if the selected text is
- de-selected this signal is emitted with \a yes set to false.
-
- If \a yes is true then copy() can be used to copy the selection to
- the clipboard. If \a yes is false then copy() does nothing.
-
- \sa selectionChanged()
-*/
-
-
-/*!
- \fn void QPlainTextEdit::selectionChanged()
-
- This signal is emitted whenever the selection changes.
-
- \sa copyAvailable()
-*/
-
-/*!
- \fn void QPlainTextEdit::cursorPositionChanged()
-
- This signal is emitted whenever the position of the
- cursor changed.
-*/
-
-
-
-/*!
- \fn void QPlainTextEdit::updateRequest(const QRect &rect, int dy)
-
- This signal is emitted when the text document needs an update of
- the specified \a rect. If the text is scrolled, \a rect will cover
- the entire viewport area. If the text is scrolled vertically, \a
- dy carries the amount of pixels the viewport was scrolled.
-
- The purpose of the signal is to support extra widgets in plain
- text edit subclasses that e.g. show line numbers, breakpoints, or
- other extra information.
-*/
-
-/*! \fn void QPlainTextEdit::blockCountChanged(int newBlockCount);
-
- This signal is emitted whenever the block count changes. The new
- block count is passed in \a newBlockCount.
-*/
-
-/*! \fn void QPlainTextEdit::modificationChanged(bool changed);
-
- This signal is emitted whenever the content of the document
- changes in a way that affects the modification state. If \a
- changed is true, the document has been modified; otherwise it is
- false.
-
- For example, calling setModified(false) on a document and then
- inserting text causes the signal to get emitted. If you undo that
- operation, causing the document to return to its original
- unmodified state, the signal will get emitted again.
-*/
-
-
-
-
-void QPlainTextEditPrivate::append(const QString &text, Qt::TextFormat format)
-{
- Q_Q(QPlainTextEdit);
-
- QTextDocument *document = control->document();
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document->documentLayout());
- Q_ASSERT(documentLayout);
-
- int maximumBlockCount = document->maximumBlockCount();
- if (maximumBlockCount)
- document->setMaximumBlockCount(0);
-
- const bool atBottom = q->isVisible()
- && (control->blockBoundingRect(document->lastBlock()).bottom() - verticalOffset()
- <= viewport->rect().bottom());
-
- if (!q->isVisible())
- showCursorOnInitialShow = true;
-
- bool documentSizeChangedBlocked = documentLayout->priv()->blockDocumentSizeChanged;
- documentLayout->priv()->blockDocumentSizeChanged = true;
-
- if (format == Qt::RichText)
- control->appendHtml(text);
- else if (format == Qt::PlainText)
- control->appendPlainText(text);
- else
- control->append(text);
-
- if (maximumBlockCount > 0) {
- if (document->blockCount() > maximumBlockCount) {
- bool blockUpdate = false;
- if (control->topBlock) {
- control->topBlock--;
- blockUpdate = true;
- emit q->updateRequest(viewport->rect(), 0);
- }
-
- bool updatesBlocked = documentLayout->priv()->blockUpdate;
- documentLayout->priv()->blockUpdate = blockUpdate;
- QTextCursor cursor(document);
- cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
- documentLayout->priv()->blockUpdate = updatesBlocked;
- }
- document->setMaximumBlockCount(maximumBlockCount);
- }
-
- documentLayout->priv()->blockDocumentSizeChanged = documentSizeChangedBlocked;
- _q_adjustScrollbars();
-
-
- if (atBottom) {
- const bool needScroll = !centerOnScroll
- || control->blockBoundingRect(document->lastBlock()).bottom() - verticalOffset()
- > viewport->rect().bottom();
- if (needScroll)
- vbar->setValue(vbar->maximum());
- }
-}
-
-
-/*!
- Appends a new paragraph with \a text to the end of the text edit.
-
- \sa appendHtml()
-*/
-
-void QPlainTextEdit::appendPlainText(const QString &text)
-{
- Q_D(QPlainTextEdit);
- d->append(text, Qt::PlainText);
-}
-
-/*!
- Appends a new paragraph with \a html to the end of the text edit.
-
- appendPlainText()
-*/
-
-void QPlainTextEdit::appendHtml(const QString &html)
-{
- Q_D(QPlainTextEdit);
- d->append(html, Qt::RichText);
-}
-
-void QPlainTextEditPrivate::ensureCursorVisible(bool center)
-{
- Q_Q(QPlainTextEdit);
- QRect visible = viewport->rect();
- QRect cr = q->cursorRect();
- if (cr.top() < visible.top() || cr.bottom() > visible.bottom()) {
- ensureVisible(control->textCursor().position(), center);
- }
-
- const bool rtl = q->isRightToLeft();
- if (cr.left() < visible.left() || cr.right() > visible.right()) {
- int x = cr.center().x() + horizontalOffset() - visible.width()/2;
- hbar->setValue(rtl ? hbar->maximum() - x : x);
- }
-}
-
-/*!
- Ensures that the cursor is visible by scrolling the text edit if
- necessary.
-
- \sa centerCursor(), centerOnScroll
-*/
-void QPlainTextEdit::ensureCursorVisible()
-{
- Q_D(QPlainTextEdit);
- d->ensureCursorVisible(d->centerOnScroll);
-}
-
-
-/*! Scrolls the document in order to center the cursor vertically.
-
-\sa ensureCursorVisible(), centerOnScroll
- */
-void QPlainTextEdit::centerCursor()
-{
- Q_D(QPlainTextEdit);
- d->ensureVisible(textCursor().position(), true, true);
-}
-
-/*!
- Returns the first visible block.
-
- \sa blockBoundingRect()
- */
-QTextBlock QPlainTextEdit::firstVisibleBlock() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->firstVisibleBlock();
-}
-
-/*! Returns the content's origin in viewport coordinates.
-
- The origin of the content of a plain text edit is always the top
- left corner of the first visible text block. The content offset
- is different from (0,0) when the text has been scrolled
- horizontally, or when the first visible block has been scrolled
- partially off the screen, i.e. the visible text does not start
- with the first line of the first visible block, or when the first
- visible block is the very first block and the editor displays a
- margin.
-
- \sa firstVisibleBlock(), horizontalScrollBar(), verticalScrollBar()
- */
-QPointF QPlainTextEdit::contentOffset() const
-{
- Q_D(const QPlainTextEdit);
- return QPointF(-d->horizontalOffset(), -d->verticalOffset());
-}
-
-
-/*! Returns the bounding rectangle of the text \a block in content
- coordinates. Translate the rectangle with the contentOffset() to get
- visual coordinates on the viewport.
-
- \sa firstVisibleBlock(), blockBoundingRect()
- */
-QRectF QPlainTextEdit::blockBoundingGeometry(const QTextBlock &block) const
-{
- Q_D(const QPlainTextEdit);
- return d->control->blockBoundingRect(block);
-}
-
-/*!
- Returns the bounding rectangle of the text \a block in the block's own coordinates.
-
- \sa blockBoundingGeometry()
- */
-QRectF QPlainTextEdit::blockBoundingRect(const QTextBlock &block) const
-{
- QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout());
- Q_ASSERT(documentLayout);
- return documentLayout->blockBoundingRect(block);
-}
-
-/*!
- \property QPlainTextEdit::blockCount
- \brief the number of text blocks in the document.
-
- By default, in an empty document, this property contains a value of 1.
-*/
-int QPlainTextEdit::blockCount() const
-{
- return document()->blockCount();
-}
-
-/*! Returns the paint context for the viewport(), useful only when
- reimplementing paintEvent().
- */
-QAbstractTextDocumentLayout::PaintContext QPlainTextEdit::getPaintContext() const
-{
- Q_D(const QPlainTextEdit);
- return d->control->getPaintContext(d->viewport);
-}
-
-/*!
- \property QPlainTextEdit::maximumBlockCount
- \brief the limit for blocks in the document.
-
- Specifies the maximum number of blocks the document may have. If there are
- more blocks in the document that specified with this property blocks are removed
- from the beginning of the document.
-
- A negative or zero value specifies that the document may contain an unlimited
- amount of blocks.
-
- The default value is 0.
-
- Note that setting this property will apply the limit immediately to the document
- contents. Setting this property also disables the undo redo history.
-
-*/
-
-
-/*!
- \fn void QPlainTextEdit::textChanged()
-
- This signal is emitted whenever the document's content changes; for
- example, when text is inserted or deleted, or when formatting is applied.
-*/
-
-/*!
- \fn void QPlainTextEdit::undoAvailable(bool available)
-
- This signal is emitted whenever undo operations become available
- (\a available is true) or unavailable (\a available is false).
-*/
-
-/*!
- \fn void QPlainTextEdit::redoAvailable(bool available)
-
- This signal is emitted whenever redo operations become available
- (\a available is true) or unavailable (\a available is false).
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qplaintextedit.cpp"
-#include "moc_qplaintextedit_p.cpp"
-
-#endif // QT_NO_TEXTEDIT
diff --git a/src/gui/widgets/qplaintextedit.h b/src/gui/widgets/qplaintextedit.h
deleted file mode 100644
index 737bcb80b0..0000000000
--- a/src/gui/widgets/qplaintextedit.h
+++ /dev/null
@@ -1,329 +0,0 @@
-/****************************************************************************
-**
-** 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 QPLAINTEXTEDIT_H
-#define QPLAINTEXTEDIT_H
-
-#include <QtGui/qtextedit.h>
-
-#include <QtGui/qabstractscrollarea.h>
-#include <QtGui/qtextdocument.h>
-#include <QtGui/qtextoption.h>
-#include <QtGui/qtextcursor.h>
-#include <QtGui/qtextformat.h>
-#include <QtGui/qabstracttextdocumentlayout.h>
-
-#ifndef QT_NO_TEXTEDIT
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStyleSheet;
-class QTextDocument;
-class QMenu;
-class QPlainTextEditPrivate;
-class QMimeData;
-
-
-class Q_GUI_EXPORT QPlainTextEdit : public QAbstractScrollArea
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPlainTextEdit)
- Q_ENUMS(LineWrapMode)
- Q_PROPERTY(bool tabChangesFocus READ tabChangesFocus WRITE setTabChangesFocus)
- Q_PROPERTY(QString documentTitle READ documentTitle WRITE setDocumentTitle)
- Q_PROPERTY(bool undoRedoEnabled READ isUndoRedoEnabled WRITE setUndoRedoEnabled)
- Q_PROPERTY(LineWrapMode lineWrapMode READ lineWrapMode WRITE setLineWrapMode)
- QDOC_PROPERTY(QTextOption::WrapMode wordWrapMode READ wordWrapMode WRITE setWordWrapMode)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
- Q_PROPERTY(QString plainText READ toPlainText WRITE setPlainText NOTIFY textChanged USER true)
- Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
- Q_PROPERTY(int tabStopWidth READ tabStopWidth WRITE setTabStopWidth)
- Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
- Q_PROPERTY(int blockCount READ blockCount)
- Q_PROPERTY(int maximumBlockCount READ maximumBlockCount WRITE setMaximumBlockCount)
- Q_PROPERTY(bool backgroundVisible READ backgroundVisible WRITE setBackgroundVisible)
- Q_PROPERTY(bool centerOnScroll READ centerOnScroll WRITE setCenterOnScroll)
-public:
- enum LineWrapMode {
- NoWrap,
- WidgetWidth
- };
-
- explicit QPlainTextEdit(QWidget *parent = 0);
- explicit QPlainTextEdit(const QString &text, QWidget *parent = 0);
- virtual ~QPlainTextEdit();
-
- void setDocument(QTextDocument *document);
- QTextDocument *document() const;
-
- void setTextCursor(const QTextCursor &cursor);
- QTextCursor textCursor() const;
-
- bool isReadOnly() const;
- void setReadOnly(bool ro);
-
- void setTextInteractionFlags(Qt::TextInteractionFlags flags);
- Qt::TextInteractionFlags textInteractionFlags() const;
-
- void mergeCurrentCharFormat(const QTextCharFormat &modifier);
- void setCurrentCharFormat(const QTextCharFormat &format);
- QTextCharFormat currentCharFormat() const;
-
- bool tabChangesFocus() const;
- void setTabChangesFocus(bool b);
-
- inline void setDocumentTitle(const QString &title)
- { document()->setMetaInformation(QTextDocument::DocumentTitle, title); }
- inline QString documentTitle() const
- { return document()->metaInformation(QTextDocument::DocumentTitle); }
-
- inline bool isUndoRedoEnabled() const
- { return document()->isUndoRedoEnabled(); }
- inline void setUndoRedoEnabled(bool enable)
- { document()->setUndoRedoEnabled(enable); }
-
- inline void setMaximumBlockCount(int maximum)
- { document()->setMaximumBlockCount(maximum); }
- inline int maximumBlockCount() const
- { return document()->maximumBlockCount(); }
-
-
- LineWrapMode lineWrapMode() const;
- void setLineWrapMode(LineWrapMode mode);
-
- QTextOption::WrapMode wordWrapMode() const;
- void setWordWrapMode(QTextOption::WrapMode policy);
-
- void setBackgroundVisible(bool visible);
- bool backgroundVisible() const;
-
- void setCenterOnScroll(bool enabled);
- bool centerOnScroll() const;
-
- bool find(const QString &exp, QTextDocument::FindFlags options = 0);
-
- inline QString toPlainText() const
- { return document()->toPlainText(); }
-
- void ensureCursorVisible();
-
- virtual QVariant loadResource(int type, const QUrl &name);
-#ifndef QT_NO_CONTEXTMENU
- QMenu *createStandardContextMenu();
-#endif
-
- QTextCursor cursorForPosition(const QPoint &pos) const;
- QRect cursorRect(const QTextCursor &cursor) const;
- QRect cursorRect() const;
-
- QString anchorAt(const QPoint &pos) const;
-
- bool overwriteMode() const;
- void setOverwriteMode(bool overwrite);
-
- int tabStopWidth() const;
- void setTabStopWidth(int width);
-
- int cursorWidth() const;
- void setCursorWidth(int width);
-
- void setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections);
- QList<QTextEdit::ExtraSelection> extraSelections() const;
-
- void moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor);
-
- bool canPaste() const;
-
-#ifndef QT_NO_PRINTER
- void print(QPrinter *printer) const;
-#endif
-
- int blockCount() const;
-
-public Q_SLOTS:
-
- void setPlainText(const QString &text);
-
-#ifndef QT_NO_CLIPBOARD
- void cut();
- void copy();
- void paste();
-#endif
-
- void undo();
- void redo();
-
- void clear();
- void selectAll();
-
- void insertPlainText(const QString &text);
-
- void appendPlainText(const QString &text);
- void appendHtml(const QString &html);
-
- void centerCursor();
-
-Q_SIGNALS:
- void textChanged();
- void undoAvailable(bool b);
- void redoAvailable(bool b);
- void copyAvailable(bool b);
- void selectionChanged();
- void cursorPositionChanged();
-
- void updateRequest(const QRect &rect, int dy);
- void blockCountChanged(int newBlockCount);
- void modificationChanged(bool);
-
-protected:
- virtual bool event(QEvent *e);
- virtual void timerEvent(QTimerEvent *e);
- virtual void keyPressEvent(QKeyEvent *e);
- virtual void keyReleaseEvent(QKeyEvent *e);
- virtual void resizeEvent(QResizeEvent *e);
- virtual void paintEvent(QPaintEvent *e);
- virtual void mousePressEvent(QMouseEvent *e);
- virtual void mouseMoveEvent(QMouseEvent *e);
- virtual void mouseReleaseEvent(QMouseEvent *e);
- virtual void mouseDoubleClickEvent(QMouseEvent *e);
- virtual bool focusNextPrevChild(bool next);
-#ifndef QT_NO_CONTEXTMENU
- virtual void contextMenuEvent(QContextMenuEvent *e);
-#endif
-#ifndef QT_NO_DRAGANDDROP
- virtual void dragEnterEvent(QDragEnterEvent *e);
- virtual void dragLeaveEvent(QDragLeaveEvent *e);
- virtual void dragMoveEvent(QDragMoveEvent *e);
- virtual void dropEvent(QDropEvent *e);
-#endif
- virtual void focusInEvent(QFocusEvent *e);
- virtual void focusOutEvent(QFocusEvent *e);
- virtual void showEvent(QShowEvent *);
- virtual void changeEvent(QEvent *e);
-#ifndef QT_NO_WHEELEVENT
- virtual void wheelEvent(QWheelEvent *e);
-#endif
-
- virtual QMimeData *createMimeDataFromSelection() const;
- virtual bool canInsertFromMimeData(const QMimeData *source) const;
- virtual void insertFromMimeData(const QMimeData *source);
-
- virtual void inputMethodEvent(QInputMethodEvent *);
- QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
-
- QPlainTextEdit(QPlainTextEditPrivate &dd, QWidget *parent);
-
- virtual void scrollContentsBy(int dx, int dy);
-
- QTextBlock firstVisibleBlock() const;
- QPointF contentOffset() const;
- QRectF blockBoundingRect(const QTextBlock &block) const;
- QRectF blockBoundingGeometry(const QTextBlock &block) const;
- QAbstractTextDocumentLayout::PaintContext getPaintContext() const;
-
-
-private:
- Q_DISABLE_COPY(QPlainTextEdit)
- Q_PRIVATE_SLOT(d_func(), void _q_repaintContents(const QRectF &r))
- Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars())
- Q_PRIVATE_SLOT(d_func(), void _q_verticalScrollbarActionTriggered(int))
- Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged())
-
- friend class QPlainTextEditControl;
-};
-
-
-class QPlainTextDocumentLayoutPrivate;
-class Q_GUI_EXPORT QPlainTextDocumentLayout : public QAbstractTextDocumentLayout
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPlainTextDocumentLayout)
- Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
-
-public:
- QPlainTextDocumentLayout(QTextDocument *document);
- ~QPlainTextDocumentLayout();
-
- void draw(QPainter *, const PaintContext &);
- int hitTest(const QPointF &, Qt::HitTestAccuracy ) const;
-
- int pageCount() const;
- QSizeF documentSize() const;
-
- QRectF frameBoundingRect(QTextFrame *) const;
- QRectF blockBoundingRect(const QTextBlock &block) const;
-
- void ensureBlockLayout(const QTextBlock &block) const;
-
- void setCursorWidth(int width);
- int cursorWidth() const;
-
- void requestUpdate();
-
-protected:
- void documentChanged(int from, int /*charsRemoved*/, int charsAdded);
-
-
-private:
- void setTextWidth(qreal newWidth);
- qreal textWidth() const;
- void layoutBlock(const QTextBlock &block);
- qreal blockWidth(const QTextBlock &block);
-
- QPlainTextDocumentLayoutPrivate *priv() const;
-
- friend class QPlainTextEdit;
- friend class QPlainTextEditPrivate;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-
-#endif // QT_NO_TEXTEDIT
-
-#endif // QPLAINTEXTEDIT_H
diff --git a/src/gui/widgets/qplaintextedit_p.h b/src/gui/widgets/qplaintextedit_p.h
deleted file mode 100644
index 7988ad8772..0000000000
--- a/src/gui/widgets/qplaintextedit_p.h
+++ /dev/null
@@ -1,187 +0,0 @@
-/****************************************************************************
-**
-** 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 QPLAINTEXTEDIT_P_H
-#define QPLAINTEXTEDIT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qabstractscrollarea_p.h"
-#include "QtGui/qtextdocumentfragment.h"
-#include "QtGui/qscrollbar.h"
-#include "QtGui/qtextcursor.h"
-#include "QtGui/qtextformat.h"
-#include "QtGui/qmenu.h"
-#include "QtGui/qabstracttextdocumentlayout.h"
-#include "QtCore/qbasictimer.h"
-#include "private/qtextcontrol_p.h"
-#include "qplaintextedit.h"
-
-#ifndef QT_NO_TEXTEDIT
-
-QT_BEGIN_NAMESPACE
-
-class QMimeData;
-
-class QPlainTextEdit;
-class ExtraArea;
-
-class QPlainTextEditControl : public QTextControl
-{
- Q_OBJECT
-public:
- QPlainTextEditControl(QPlainTextEdit *parent);
-
-
- QMimeData *createMimeDataFromSelection() const;
- bool canInsertFromMimeData(const QMimeData *source) const;
- void insertFromMimeData(const QMimeData *source);
- int hitTest(const QPointF &point, Qt::HitTestAccuracy = Qt::FuzzyHit) const;
- QRectF blockBoundingRect(const QTextBlock &block) const;
- inline QRectF cursorRect(const QTextCursor &cursor) const {
- QRectF r = QTextControl::cursorRect(cursor);
- r.setLeft(qMax(r.left(), (qreal) 0.));
- return r;
- }
- inline QRectF cursorRect() { return cursorRect(textCursor()); }
- void ensureCursorVisible() {
- textEdit->ensureCursorVisible();
- emit microFocusChanged();
- }
-
-
- QPlainTextEdit *textEdit;
- int topBlock;
- QTextBlock firstVisibleBlock() const;
-
- QVariant loadResource(int type, const QUrl &name) {
- return textEdit->loadResource(type, name);
- }
-
-};
-
-
-class QPlainTextEditPrivate : public QAbstractScrollAreaPrivate
-{
- Q_DECLARE_PUBLIC(QPlainTextEdit)
-public:
- QPlainTextEditPrivate();
-
- void init(const QString &txt = QString());
- void _q_repaintContents(const QRectF &contentsRect);
-
- inline QPoint mapToContents(const QPoint &point) const
- { return QPoint(point.x() + horizontalOffset(), point.y() + verticalOffset()); }
-
- void _q_adjustScrollbars();
- void _q_verticalScrollbarActionTriggered(int action);
- void ensureViewportLayouted();
- void relayoutDocument();
-
- void pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode, bool moveCursor = true);
-
- inline int horizontalOffset() const
- { return (q_func()->isRightToLeft() ? (hbar->maximum() - hbar->value()) : hbar->value()); }
- int verticalOffset(int topBlock, int topLine) const;
- int verticalOffset() const;
-
- inline void sendControlEvent(QEvent *e)
- { control->processEvent(e, QPointF(horizontalOffset(), verticalOffset()), viewport); }
-
- void updateDefaultTextOption();
-
- QPlainTextEditControl *control;
-
- bool tabChangesFocus;
-
- QBasicTimer autoScrollTimer;
- QPoint autoScrollDragPos;
-
- QPlainTextEdit::LineWrapMode lineWrap;
- QTextOption::WrapMode wordWrap;
-
- uint showCursorOnInitialShow : 1;
- uint backgroundVisible : 1;
- uint centerOnScroll : 1;
- uint inDrag : 1;
- uint clickCausedFocus : 1;
-
- int topLine;
-
- void setTopLine(int visualTopLine, int dx = 0);
- void setTopBlock(int newTopBlock, int newTopLine, int dx = 0);
-
- void ensureVisible(int position, bool center, bool forceCenter = false);
- void ensureCursorVisible(bool center = false);
- void updateViewport();
-
- QPointer<QPlainTextDocumentLayout> documentLayoutPtr;
-
- void append(const QString &text, Qt::TextFormat format = Qt::AutoText);
-
- qreal pageUpDownLastCursorY;
- bool pageUpDownLastCursorYIsValid;
-
-
-#ifdef QT_KEYPAD_NAVIGATION
- QBasicTimer deleteAllTimer;
-#endif
-
- void _q_cursorPositionChanged();
- void _q_modificationChanged(bool);
-
- int originalOffsetY;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TEXTEDIT
-
-#endif // QPLAINTEXTEDIT_P_H
diff --git a/src/gui/widgets/qprintpreviewwidget.cpp b/src/gui/widgets/qprintpreviewwidget.cpp
deleted file mode 100644
index 9da3e47698..0000000000
--- a/src/gui/widgets/qprintpreviewwidget.cpp
+++ /dev/null
@@ -1,844 +0,0 @@
-/****************************************************************************
-**
-** 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 "qprintpreviewwidget.h"
-#include "private/qwidget_p.h"
-#include <private/qprinter_p.h>
-
-#include <QtCore/qmath.h>
-#include <QtGui/qboxlayout.h>
-#include <QtGui/qgraphicsitem.h>
-#include <QtGui/qgraphicsview.h>
-#include <QtGui/qscrollbar.h>
-#include <QtGui/qstyleoption.h>
-
-#ifndef QT_NO_PRINTPREVIEWWIDGET
-
-QT_BEGIN_NAMESPACE
-
-namespace {
-class PageItem : public QGraphicsItem
-{
-public:
- PageItem(int _pageNum, const QPicture* _pagePicture, QSize _paperSize, QRect _pageRect)
- : pageNum(_pageNum), pagePicture(_pagePicture),
- paperSize(_paperSize), pageRect(_pageRect)
- {
- qreal border = qMax(paperSize.height(), paperSize.width()) / 25;
- brect = QRectF(QPointF(-border, -border),
- QSizeF(paperSize)+QSizeF(2*border, 2*border));
- setCacheMode(DeviceCoordinateCache);
- }
-
- inline QRectF boundingRect() const
- { return brect; }
-
- inline int pageNumber() const
- { return pageNum; }
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget);
-
-private:
- int pageNum;
- const QPicture* pagePicture;
- QSize paperSize;
- QRect pageRect;
- QRectF brect;
-};
-
-void PageItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
-{
- Q_UNUSED(widget);
-
-#if 0
- // Draw item bounding rect, for debugging
- painter->save();
- painter->setPen(QPen(Qt::red, 0));
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(QRectF(-border()+1.0, -border()+1.0, boundingRect().width()-2, boundingRect().height()-2));
- painter->restore();
-#endif
-
- QRectF paperRect(0,0, paperSize.width(), paperSize.height());
-
- // Draw shadow
- painter->setClipRect(option->exposedRect);
- qreal shWidth = paperRect.width()/100;
- QRectF rshadow(paperRect.topRight() + QPointF(0, shWidth),
- paperRect.bottomRight() + QPointF(shWidth, 0));
- QLinearGradient rgrad(rshadow.topLeft(), rshadow.topRight());
- rgrad.setColorAt(0.0, QColor(0,0,0,255));
- rgrad.setColorAt(1.0, QColor(0,0,0,0));
- painter->fillRect(rshadow, QBrush(rgrad));
- QRectF bshadow(paperRect.bottomLeft() + QPointF(shWidth, 0),
- paperRect.bottomRight() + QPointF(0, shWidth));
- QLinearGradient bgrad(bshadow.topLeft(), bshadow.bottomLeft());
- bgrad.setColorAt(0.0, QColor(0,0,0,255));
- bgrad.setColorAt(1.0, QColor(0,0,0,0));
- painter->fillRect(bshadow, QBrush(bgrad));
- QRectF cshadow(paperRect.bottomRight(),
- paperRect.bottomRight() + QPointF(shWidth, shWidth));
- QRadialGradient cgrad(cshadow.topLeft(), shWidth, cshadow.topLeft());
- cgrad.setColorAt(0.0, QColor(0,0,0,255));
- cgrad.setColorAt(1.0, QColor(0,0,0,0));
- painter->fillRect(cshadow, QBrush(cgrad));
-
- painter->setClipRect(paperRect & option->exposedRect);
- painter->fillRect(paperRect, Qt::white);
- if (!pagePicture)
- return;
- painter->drawPicture(pageRect.topLeft(), *pagePicture);
-
- // Effect: make anything drawn in the margins look washed out.
- QPainterPath path;
- path.addRect(paperRect);
- path.addRect(pageRect);
- painter->setPen(QPen(Qt::NoPen));
- painter->setBrush(QColor(255, 255, 255, 180));
- painter->drawPath(path);
-
-#if 0
- // Draw frame around paper.
- painter->setPen(QPen(Qt::black, 0));
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(paperRect);
-#endif
-
- // todo: drawtext "Page N" below paper
-}
-
-class GraphicsView : public QGraphicsView
-{
- Q_OBJECT
-public:
- GraphicsView(QWidget* parent = 0)
- : QGraphicsView(parent)
- {
-#ifdef Q_WS_MAC
- setFrameStyle(QFrame::NoFrame);
-#endif
- }
-signals:
- void resized();
-
-protected:
- void resizeEvent(QResizeEvent* e)
- {
- QGraphicsView::resizeEvent(e);
- emit resized();
- }
-
- void showEvent(QShowEvent* e)
- {
- QGraphicsView::showEvent(e);
- emit resized();
- }
-};
-
-} // anonymous namespace
-
-class QPrintPreviewWidgetPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QPrintPreviewWidget)
-public:
- QPrintPreviewWidgetPrivate()
- : scene(0), curPage(1),
- viewMode(QPrintPreviewWidget::SinglePageView),
- zoomMode(QPrintPreviewWidget::FitInView),
- zoomFactor(1), initialized(false), fitting(true)
- {}
-
- // private slots
- void _q_fit(bool doFitting = false);
- void _q_updateCurrentPage();
-
- void init();
- void populateScene();
- void layoutPages();
- void generatePreview();
- void setCurrentPage(int pageNumber);
- void zoom(qreal zoom);
- void setZoomFactor(qreal zoomFactor);
- int calcCurrentPage();
-
- GraphicsView *graphicsView;
- QGraphicsScene *scene;
-
- int curPage;
- QList<const QPicture *> pictures;
- QList<QGraphicsItem *> pages;
-
- QPrintPreviewWidget::ViewMode viewMode;
- QPrintPreviewWidget::ZoomMode zoomMode;
- qreal zoomFactor;
- bool ownPrinter;
- QPrinter* printer;
- bool initialized;
- bool fitting;
-};
-
-void QPrintPreviewWidgetPrivate::_q_fit(bool doFitting)
-{
- Q_Q(QPrintPreviewWidget);
-
- if (curPage < 1 || curPage > pages.count())
- return;
-
- if (!doFitting && !fitting)
- return;
-
- if (doFitting && fitting) {
- QRect viewRect = graphicsView->viewport()->rect();
- if (zoomMode == QPrintPreviewWidget::FitInView) {
- QList<QGraphicsItem*> containedItems = graphicsView->items(viewRect, Qt::ContainsItemBoundingRect);
- foreach(QGraphicsItem* item, containedItems) {
- PageItem* pg = static_cast<PageItem*>(item);
- if (pg->pageNumber() == curPage)
- return;
- }
- }
-
- int newPage = calcCurrentPage();
- if (newPage != curPage)
- curPage = newPage;
- }
-
- QRectF target = pages.at(curPage-1)->sceneBoundingRect();
- if (viewMode == QPrintPreviewWidget::FacingPagesView) {
- // fit two pages
- if (curPage % 2)
- target.setLeft(target.left() - target.width());
- else
- target.setRight(target.right() + target.width());
- } else if (viewMode == QPrintPreviewWidget::AllPagesView) {
- target = scene->itemsBoundingRect();
- }
-
- if (zoomMode == QPrintPreviewWidget::FitToWidth) {
- QTransform t;
- qreal scale = graphicsView->viewport()->width() / target.width();
- t.scale(scale, scale);
- graphicsView->setTransform(t);
- if (doFitting && fitting) {
- QRectF viewSceneRect = graphicsView->viewportTransform().mapRect(graphicsView->viewport()->rect());
- viewSceneRect.moveTop(target.top());
- graphicsView->ensureVisible(viewSceneRect); // Nah...
- }
- } else {
- graphicsView->fitInView(target, Qt::KeepAspectRatio);
- if (zoomMode == QPrintPreviewWidget::FitInView) {
- int step = qRound(graphicsView->matrix().mapRect(target).height());
- graphicsView->verticalScrollBar()->setSingleStep(step);
- graphicsView->verticalScrollBar()->setPageStep(step);
- }
- }
-
- zoomFactor = graphicsView->transform().m11() * (float(printer->logicalDpiY()) / q->logicalDpiY());
- emit q->previewChanged();
-}
-
-void QPrintPreviewWidgetPrivate::_q_updateCurrentPage()
-{
- Q_Q(QPrintPreviewWidget);
-
- if (viewMode == QPrintPreviewWidget::AllPagesView)
- return;
-
- int newPage = calcCurrentPage();
- if (newPage != curPage) {
- curPage = newPage;
- emit q->previewChanged();
- }
-}
-
-int QPrintPreviewWidgetPrivate::calcCurrentPage()
-{
- int maxArea = 0;
- int newPage = curPage;
- QRect viewRect = graphicsView->viewport()->rect();
- QList<QGraphicsItem*> items = graphicsView->items(viewRect);
- for (int i=0; i<items.size(); ++i) {
- PageItem* pg = static_cast<PageItem*>(items.at(i));
- QRect overlap = graphicsView->mapFromScene(pg->sceneBoundingRect()).boundingRect() & viewRect;
- int area = overlap.width() * overlap.height();
- if (area > maxArea) {
- maxArea = area;
- newPage = pg->pageNumber();
- } else if (area == maxArea && pg->pageNumber() < newPage) {
- newPage = pg->pageNumber();
- }
- }
- return newPage;
-}
-
-void QPrintPreviewWidgetPrivate::init()
-{
- Q_Q(QPrintPreviewWidget);
-
- graphicsView = new GraphicsView;
- graphicsView->setInteractive(false);
- graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
- graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
- QObject::connect(graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)),
- q, SLOT(_q_updateCurrentPage()));
- QObject::connect(graphicsView, SIGNAL(resized()), q, SLOT(_q_fit()));
-
- scene = new QGraphicsScene(graphicsView);
- scene->setBackgroundBrush(Qt::gray);
- graphicsView->setScene(scene);
-
- QVBoxLayout *layout = new QVBoxLayout;
- q->setLayout(layout);
- layout->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(graphicsView);
-}
-
-void QPrintPreviewWidgetPrivate::populateScene()
-{
- // remove old pages
- for (int i = 0; i < pages.size(); i++)
- scene->removeItem(pages.at(i));
- qDeleteAll(pages);
- pages.clear();
-
- int numPages = pictures.count();
- QSize paperSize = printer->paperRect().size();
- QRect pageRect = printer->pageRect();
-
- for (int i = 0; i < numPages; i++) {
- PageItem* item = new PageItem(i+1, pictures.at(i), paperSize, pageRect);
- scene->addItem(item);
- pages.append(item);
- }
-}
-
-void QPrintPreviewWidgetPrivate::layoutPages()
-{
- int numPages = pages.count();
- if (numPages < 1)
- return;
-
- int numPagePlaces = numPages;
- int cols = 1; // singleMode and default
- if (viewMode == QPrintPreviewWidget::AllPagesView) {
- if (printer->orientation() == QPrinter::Portrait)
- cols = qCeil(qSqrt((float) numPages));
- else
- cols = qFloor(qSqrt((float) numPages));
- cols += cols % 2; // Nicer with an even number of cols
- }
- else if (viewMode == QPrintPreviewWidget::FacingPagesView) {
- cols = 2;
- numPagePlaces += 1;
- }
- int rows = qCeil(qreal(numPagePlaces) / cols);
-
- qreal itemWidth = pages.at(0)->boundingRect().width();
- qreal itemHeight = pages.at(0)->boundingRect().height();
- int pageNum = 1;
- for (int i = 0; i < rows && pageNum <= numPages; i++) {
- for (int j = 0; j < cols && pageNum <= numPages; j++) {
- if (!i && !j && viewMode == QPrintPreviewWidget::FacingPagesView) {
- // Front page doesn't have a facing page
- continue;
- } else {
- pages.at(pageNum-1)->setPos(QPointF(j*itemWidth, i*itemHeight));
- pageNum++;
- }
- }
- }
- scene->setSceneRect(scene->itemsBoundingRect());
-}
-
-void QPrintPreviewWidgetPrivate::generatePreview()
-{
- //### If QPrinter::setPreviewMode() becomes public, handle the
- //### case that we have been constructed with a printer that
- //### _already_ has been preview-painted to, so we should
- //### initially just show the pages it already contains, and not
- //### emit paintRequested() until the user changes some parameter
-
- Q_Q(QPrintPreviewWidget);
- printer->d_func()->setPreviewMode(true);
- emit q->paintRequested(printer);
- printer->d_func()->setPreviewMode(false);
- pictures = printer->d_func()->previewPages();
- populateScene(); // i.e. setPreviewPrintedPictures() e.l.
- layoutPages();
- curPage = qBound(1, curPage, pages.count());
- if (fitting)
- _q_fit();
- emit q->previewChanged();
-}
-
-void QPrintPreviewWidgetPrivate::setCurrentPage(int pageNumber)
-{
- if (pageNumber < 1 || pageNumber > pages.count())
- return;
-
- int lastPage = curPage;
- curPage = pageNumber;
-
- if (lastPage != curPage && lastPage > 0 && lastPage <= pages.count()) {
- if (zoomMode != QPrintPreviewWidget::FitInView) {
- QScrollBar *hsc = graphicsView->horizontalScrollBar();
- QScrollBar *vsc = graphicsView->verticalScrollBar();
- QPointF pt = graphicsView->transform().map(pages.at(curPage-1)->pos());
- vsc->setValue(int(pt.y()) - 10);
- hsc->setValue(int(pt.x()) - 10);
- } else {
- graphicsView->centerOn(pages.at(curPage-1));
- }
- }
-}
-
-void QPrintPreviewWidgetPrivate::zoom(qreal zoom)
-{
- zoomFactor *= zoom;
- graphicsView->scale(zoom, zoom);
-}
-
-void QPrintPreviewWidgetPrivate::setZoomFactor(qreal _zoomFactor)
-{
- Q_Q(QPrintPreviewWidget);
- zoomFactor = _zoomFactor;
- graphicsView->resetTransform();
- int dpi_y = q->logicalDpiY();
- int printer_dpi_y = printer->logicalDpiY();
- graphicsView->scale(zoomFactor*(dpi_y/float(printer_dpi_y)),
- zoomFactor*(dpi_y/float(printer_dpi_y)));
-}
-
-///////////////////////////////////////
-
-/*!
- \class QPrintPreviewWidget
- \since 4.4
-
- \brief The QPrintPreviewWidget class provides a widget for
- previewing page layouts for printer output.
-
- \ingroup printing
-
- QPrintPreviewDialog uses a QPrintPreviewWidget internally, and the
- purpose of QPrintPreviewWidget is to make it possible to embed the
- preview into other widgets. It also makes it possible to build a different
- user interface around it than the default one provided with QPrintPreviewDialog.
-
- Using QPrintPreviewWidget is straightforward:
-
- \list 1
- \o Create the QPrintPreviewWidget
-
- Construct the QPrintPreviewWidget either by passing in an
- existing QPrinter object, or have QPrintPreviewWidget create a
- default constructed QPrinter object for you.
-
- \o Connect the paintRequested() signal to a slot.
-
- When the widget needs to generate a set of preview pages, a
- paintRequested() signal will be emitted from the widget. Connect a
- slot to this signal, and draw onto the QPrinter passed in as a
- signal parameter. Call QPrinter::newPage(), to start a new
- page in the preview.
-
- \endlist
-
- \sa QPrinter, QPrintDialog, QPageSetupDialog, QPrintPreviewDialog
-*/
-
-
-/*!
- \enum QPrintPreviewWidget::ViewMode
-
- This enum is used to describe the view mode of the preview widget.
-
- \value SinglePageView A mode where single pages in the preview
- is viewed.
-
- \value FacingPagesView A mode where the facing pages in the preview
- is viewed.
-
- \value AllPagesView A view mode where all the pages in the preview
- is viewed.
-*/
-
-/*!
- \enum QPrintPreviewWidget::ZoomMode
-
- This enum is used to describe zoom mode of the preview widget.
-
- \value CustomZoom The zoom is set to a custom zoom value.
-
- \value FitToWidth This mode fits the current page to the width of the view.
-
- \value FitInView This mode fits the current page inside the view.
-
-*/
-
-/*!
- Constructs a QPrintPreviewWidget based on \a printer and with \a
- parent as the parent widget. The widget flags \a flags are passed on
- to the QWidget constructor.
-
- \sa QWidget::setWindowFlags()
-*/
-QPrintPreviewWidget::QPrintPreviewWidget(QPrinter *printer, QWidget *parent, Qt::WindowFlags flags)
- : QWidget(*new QPrintPreviewWidgetPrivate, parent, flags)
-{
- Q_D(QPrintPreviewWidget);
- d->printer = printer;
- d->ownPrinter = false;
- d->init();
-}
-
-/*!
- \overload
-
- This will cause QPrintPreviewWidget to create an internal, default
- constructed QPrinter object, which will be used to generate the
- preview.
-*/
-QPrintPreviewWidget::QPrintPreviewWidget(QWidget *parent, Qt::WindowFlags flags)
- : QWidget(*new QPrintPreviewWidgetPrivate, parent, flags)
-{
- Q_D(QPrintPreviewWidget);
- d->printer = new QPrinter;
- d->ownPrinter = true;
- d->init();
-}
-
-
-/*!
- Destroys the QPrintPreviewWidget.
-*/
-QPrintPreviewWidget::~QPrintPreviewWidget()
-{
- Q_D(QPrintPreviewWidget);
- if (d->ownPrinter)
- delete d->printer;
-}
-
-/*!
- Returns the current view mode. The default view mode is SinglePageView.
-*/
-QPrintPreviewWidget::ViewMode QPrintPreviewWidget::viewMode() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->viewMode;
-}
-
-/*!
- Sets the view mode to \a mode. The default view mode is
- SinglePageView.
-*/
-void QPrintPreviewWidget::setViewMode(ViewMode mode)
-{
- Q_D(QPrintPreviewWidget);
- d->viewMode = mode;
- d->layoutPages();
- if (d->viewMode == AllPagesView) {
- d->graphicsView->fitInView(d->scene->itemsBoundingRect(), Qt::KeepAspectRatio);
- d->fitting = false;
- d->zoomMode = QPrintPreviewWidget::CustomZoom;
- d->zoomFactor = d->graphicsView->transform().m11() * (float(d->printer->logicalDpiY()) / logicalDpiY());
- emit previewChanged();
- } else {
- d->fitting = true;
- d->_q_fit();
- }
-}
-
-/*!
- Returns the current orientation of the preview. This value is
- obtained from the QPrinter object associated with the preview.
-*/
-QPrinter::Orientation QPrintPreviewWidget::orientation() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->printer->orientation();
-}
-
-/*!
- Sets the current orientation to \a orientation. This value will be
- set on the QPrinter object associated with the preview.
-*/
-void QPrintPreviewWidget::setOrientation(QPrinter::Orientation orientation)
-{
- Q_D(QPrintPreviewWidget);
- d->printer->setOrientation(orientation);
- d->generatePreview();
-}
-
-/*!
- Prints the preview to the printer associated with the preview.
-*/
-void QPrintPreviewWidget::print()
-{
- Q_D(QPrintPreviewWidget);
- // ### make use of the generated pages
- emit paintRequested(d->printer);
-}
-
-/*!
- Zooms the current view in by \a factor. The default value for \a
- factor is 1.1, which means the view will be scaled up by 10%.
-*/
-void QPrintPreviewWidget::zoomIn(qreal factor)
-{
- Q_D(QPrintPreviewWidget);
- d->fitting = false;
- d->zoomMode = QPrintPreviewWidget::CustomZoom;
- d->zoom(factor);
-}
-
-/*!
- Zooms the current view out by \a factor. The default value for \a
- factor is 1.1, which means the view will be scaled down by 10%.
-*/
-void QPrintPreviewWidget::zoomOut(qreal factor)
-{
- Q_D(QPrintPreviewWidget);
- d->fitting = false;
- d->zoomMode = QPrintPreviewWidget::CustomZoom;
- d->zoom(1/factor);
-}
-
-/*!
- Returns the zoom factor of the view.
-*/
-qreal QPrintPreviewWidget::zoomFactor() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->zoomFactor;
-}
-
-/*!
- Sets the zoom factor of the view to \a factor. For example, a
- value of 1.0 indicates an unscaled view, which is approximately
- the size the view will have on paper. A value of 0.5 will halve
- the size of the view, while a value of 2.0 will double the size of
- the view.
-*/
-void QPrintPreviewWidget::setZoomFactor(qreal factor)
-{
- Q_D(QPrintPreviewWidget);
- d->fitting = false;
- d->zoomMode = QPrintPreviewWidget::CustomZoom;
- d->setZoomFactor(factor);
-}
-
-/*!
- \obsolete
- Returns the number of pages in the preview.
- \sa pageCount()
-*/
-int QPrintPreviewWidget::numPages() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->pages.size();
-}
-
-/*!
- \since 4.6
- Returns the number of pages in the preview.
-*/
-int QPrintPreviewWidget::pageCount() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->pages.size();
-}
-
-/*!
- Returns the currently viewed page in the preview.
-*/
-int QPrintPreviewWidget::currentPage() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->curPage;
-}
-
-/*!
- Sets the current page in the preview. This will cause the view to
- skip to the beginning of \a page.
-*/
-void QPrintPreviewWidget::setCurrentPage(int page)
-{
- Q_D(QPrintPreviewWidget);
- d->setCurrentPage(page);
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setZoomMode(QPrintPreviewWidget::FitToWidth)}.
-*/
-void QPrintPreviewWidget::fitToWidth()
-{
- setZoomMode(FitToWidth);
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setZoomMode(QPrintPreviewWidget::FitInView)}.
-*/
-void QPrintPreviewWidget::fitInView()
-{
- setZoomMode(FitInView);
-}
-
-/*!
- Sets the zoom mode to \a zoomMode. The default zoom mode is FitInView.
-
- \sa zoomMode(), viewMode(), setViewMode()
-*/
-void QPrintPreviewWidget::setZoomMode(QPrintPreviewWidget::ZoomMode zoomMode)
-{
- Q_D(QPrintPreviewWidget);
- d->zoomMode = zoomMode;
- if (d->zoomMode == FitInView || d->zoomMode == FitToWidth) {
- d->fitting = true;
- d->_q_fit(true);
- } else {
- d->fitting = false;
- }
-}
-
-/*!
- Returns the current zoom mode.
-
- \sa setZoomMode(), viewMode(), setViewMode()
-*/
-QPrintPreviewWidget::ZoomMode QPrintPreviewWidget::zoomMode() const
-{
- Q_D(const QPrintPreviewWidget);
- return d->zoomMode;
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setOrientation(QPrinter::Landscape)}.
-*/
-void QPrintPreviewWidget::setLandscapeOrientation()
-{
- setOrientation(QPrinter::Landscape);
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setOrientation(QPrinter::Portrait)}.
-*/
-void QPrintPreviewWidget::setPortraitOrientation()
-{
- setOrientation(QPrinter::Portrait);
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setViewMode(QPrintPreviewWidget::SinglePageView)}.
-*/
-void QPrintPreviewWidget::setSinglePageViewMode()
-{
- setViewMode(SinglePageView);
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setViewMode(QPrintPreviewWidget::FacingPagesView)}.
-*/
-void QPrintPreviewWidget::setFacingPagesViewMode()
-{
- setViewMode(FacingPagesView);
-}
-
-/*!
- This is a convenience function and is the same as calling \c
- {setViewMode(QPrintPreviewWidget::AllPagesView)}.
-*/
-void QPrintPreviewWidget::setAllPagesViewMode()
-{
- setViewMode(AllPagesView);
-}
-
-
-/*!
- This function updates the preview, which causes the
- paintRequested() signal to be emitted.
-*/
-void QPrintPreviewWidget::updatePreview()
-{
- Q_D(QPrintPreviewWidget);
- d->initialized = true;
- d->generatePreview();
- d->graphicsView->updateGeometry();
-}
-
-/*! \reimp
-*/
-void QPrintPreviewWidget::setVisible(bool visible)
-{
- Q_D(QPrintPreviewWidget);
- if (visible && !d->initialized)
- updatePreview();
- QWidget::setVisible(visible);
-}
-
-/*!
- \fn void QPrintPreviewWidget::paintRequested(QPrinter *printer)
-
- This signal is emitted when the preview widget needs to generate a
- set of preview pages. \a printer is the printer associated with
- this preview widget.
-*/
-
-/*!
- \fn void QPrintPreviewWidget::previewChanged()
-
- This signal is emitted whenever the preview widget has changed
- some internal state, such as the orientation.
-*/
-
-
-QT_END_NAMESPACE
-
-#include "moc_qprintpreviewwidget.cpp"
-#include "qprintpreviewwidget.moc"
-
-#endif // QT_NO_PRINTPREVIEWWIDGET
diff --git a/src/gui/widgets/qprintpreviewwidget.h b/src/gui/widgets/qprintpreviewwidget.h
deleted file mode 100644
index a5d8fc6bc2..0000000000
--- a/src/gui/widgets/qprintpreviewwidget.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/****************************************************************************
-**
-** 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 QPRINTPREVIEWWIDGET_H
-#define QPRINTPREVIEWWIDGET_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qprinter.h>
-
-#ifndef QT_NO_PRINTPREVIEWWIDGET
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QPrintPreviewWidgetPrivate;
-
-class Q_GUI_EXPORT QPrintPreviewWidget : public QWidget
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QPrintPreviewWidget)
-public:
-
- enum ViewMode {
- SinglePageView,
- FacingPagesView,
- AllPagesView
- };
-
- enum ZoomMode {
- CustomZoom,
- FitToWidth,
- FitInView
- };
-
- explicit QPrintPreviewWidget(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0);
- explicit QPrintPreviewWidget(QWidget *parent = 0, Qt::WindowFlags flags = 0);
- ~QPrintPreviewWidget();
-
- qreal zoomFactor() const;
- QPrinter::Orientation orientation() const;
- ViewMode viewMode() const;
- ZoomMode zoomMode() const;
- int currentPage() const;
-#ifdef QT_DEPRECATED
- QT_DEPRECATED int numPages() const;
-#endif
- int pageCount() const;
- void setVisible(bool visible);
-
-public Q_SLOTS:
- void print();
-
- void zoomIn(qreal zoom = 1.1);
- void zoomOut(qreal zoom = 1.1);
- void setZoomFactor(qreal zoomFactor);
- void setOrientation(QPrinter::Orientation orientation);
- void setViewMode(ViewMode viewMode);
- void setZoomMode(ZoomMode zoomMode);
- void setCurrentPage(int pageNumber);
-
- void fitToWidth();
- void fitInView();
- void setLandscapeOrientation();
- void setPortraitOrientation();
- void setSinglePageViewMode();
- void setFacingPagesViewMode();
- void setAllPagesViewMode();
-
- void updatePreview();
-
-Q_SIGNALS:
- void paintRequested(QPrinter *printer);
- void previewChanged();
-
-private:
- void *dummy; // ### remove in Qt 5.0
- Q_PRIVATE_SLOT(d_func(), void _q_fit())
- Q_PRIVATE_SLOT(d_func(), void _q_updateCurrentPage())
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_PRINTPREVIEWWIDGET
-#endif // QPRINTPREVIEWWIDGET_H
diff --git a/src/gui/widgets/qprogressbar.cpp b/src/gui/widgets/qprogressbar.cpp
deleted file mode 100644
index b7350406d4..0000000000
--- a/src/gui/widgets/qprogressbar.cpp
+++ /dev/null
@@ -1,595 +0,0 @@
-/****************************************************************************
-**
-** 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 "qprogressbar.h"
-#ifndef QT_NO_PROGRESSBAR
-#include <qevent.h>
-#include <qpainter.h>
-#include <qstylepainter.h>
-#include <qstyleoption.h>
-#include <private/qwidget_p.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qaccessible.h>
-#endif
-#include <limits.h>
-
-QT_BEGIN_NAMESPACE
-
-class QProgressBarPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QProgressBar)
-
-public:
- QProgressBarPrivate();
-
- void init();
- inline void resetLayoutItemMargins();
-
- int minimum;
- int maximum;
- int value;
- Qt::Alignment alignment;
- uint textVisible : 1;
- int lastPaintedValue;
- Qt::Orientation orientation;
- bool invertedAppearance;
- QProgressBar::Direction textDirection;
- QString format;
- inline int bound(int val) const { return qMax(minimum-1, qMin(maximum, val)); }
- bool repaintRequired() const;
-};
-
-QProgressBarPrivate::QProgressBarPrivate()
- : minimum(0), maximum(100), value(-1), alignment(Qt::AlignLeft), textVisible(true),
- lastPaintedValue(-1), orientation(Qt::Horizontal), invertedAppearance(false),
- textDirection(QProgressBar::TopToBottom), format(QLatin1String("%p%"))
-{
-}
-
-void QProgressBarPrivate::init()
-{
- Q_Q(QProgressBar);
- QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Fixed);
- if (orientation == Qt::Vertical)
- sp.transpose();
- q->setSizePolicy(sp);
- q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- resetLayoutItemMargins();
-}
-
-void QProgressBarPrivate::resetLayoutItemMargins()
-{
- Q_Q(QProgressBar);
- QStyleOptionProgressBar option;
- q->initStyleOption(&option);
- setLayoutItemMargins(QStyle::SE_ProgressBarLayoutItem, &option);
-}
-
-/*!
- Initialize \a option with the values from this QProgressBar. This method is useful
- for subclasses when they need a QStyleOptionProgressBar or QStyleOptionProgressBarV2,
- but don't want to fill in all the information themselves. This function will check the version
- of the QStyleOptionProgressBar and fill in the additional values for a
- QStyleOptionProgressBarV2.
-
- \sa QStyleOption::initFrom()
-*/
-void QProgressBar::initStyleOption(QStyleOptionProgressBar *option) const
-{
- if (!option)
- return;
- Q_D(const QProgressBar);
- option->initFrom(this);
-
- if (d->orientation == Qt::Horizontal)
- option->state |= QStyle::State_Horizontal;
- option->minimum = d->minimum;
- option->maximum = d->maximum;
- option->progress = d->value;
- option->textAlignment = d->alignment;
- option->textVisible = d->textVisible;
- option->text = text();
-
- if (QStyleOptionProgressBarV2 *optionV2
- = qstyleoption_cast<QStyleOptionProgressBarV2 *>(option)) {
- optionV2->orientation = d->orientation; // ### Qt 5: use State_Horizontal instead
- optionV2->invertedAppearance = d->invertedAppearance;
- optionV2->bottomToTop = (d->textDirection == QProgressBar::BottomToTop);
- }
-}
-
-bool QProgressBarPrivate::repaintRequired() const
-{
- Q_Q(const QProgressBar);
- if (value == lastPaintedValue)
- return false;
-
- int valueDifference = qAbs(value - lastPaintedValue);
-
- // Check if the text needs to be repainted
- if (value == minimum || value == maximum)
- return true;
- if (textVisible) {
- if ((format.contains(QLatin1String("%v"))))
- return true;
- if ((format.contains(QLatin1String("%p"))
- && valueDifference >= qAbs((maximum - minimum) / 100)))
- return true;
- }
-
- // Check if the bar needs to be repainted
- QStyleOptionProgressBarV2 opt;
- q->initStyleOption(&opt);
- int cw = q->style()->pixelMetric(QStyle::PM_ProgressBarChunkWidth, &opt, q);
- QRect groove = q->style()->subElementRect(QStyle::SE_ProgressBarGroove, &opt, q);
- // This expression is basically
- // (valueDifference / (maximum - minimum) > cw / groove.width())
- // transformed to avoid integer division.
- int grooveBlock = (q->orientation() == Qt::Horizontal) ? groove.width() : groove.height();
- return (valueDifference * grooveBlock > cw * (maximum - minimum));
-}
-
-/*!
- \class QProgressBar
- \brief The QProgressBar widget provides a horizontal or vertical progress bar.
-
- \ingroup basicwidgets
-
-
- A progress bar is used to give the user an indication of the
- progress of an operation and to reassure them that the application
- is still running.
-
- The progress bar uses the concept of \e steps. You set it up by
- specifying the minimum and maximum possible step values, and it
- will display the percentage of steps that have been completed
- when you later give it the current step value. The percentage is
- calculated by dividing the progress (value() - minimum()) divided
- by maximum() - minimum().
-
- You can specify the minimum and maximum number of steps with
- setMinimum() and setMaximum. The current number of steps is set
- with setValue(). The progress bar can be rewound to the
- beginning with reset().
-
- If minimum and maximum both are set to 0, the bar shows a busy
- indicator instead of a percentage of steps. This is useful, for
- example, when using QFtp or QNetworkAccessManager to download
- items when they are unable to determine the size of the item being
- downloaded.
-
- \table
- \row \o \inlineimage macintosh-progressbar.png Screenshot of a Macintosh style progress bar
- \o A progress bar shown in the Macintosh widget style.
- \row \o \inlineimage windowsxp-progressbar.png Screenshot of a Windows XP style progress bar
- \o A progress bar shown in the Windows XP widget style.
- \row \o \inlineimage plastique-progressbar.png Screenshot of a Plastique style progress bar
- \o A progress bar shown in the Plastique widget style.
- \endtable
-
- \sa QProgressDialog, {fowler}{GUI Design Handbook: Progress Indicator}
-*/
-
-/*!
- \since 4.1
- \enum QProgressBar::Direction
- \brief Specifies the reading direction of the \l text for vertical progress bars.
-
- \value TopToBottom The text is rotated 90 degrees clockwise.
- \value BottomToTop The text is rotated 90 degrees counter-clockwise.
-
- Note that whether or not the text is drawn is dependent on the style.
- Currently CDE, CleanLooks, Motif, and Plastique draw the text. Mac, Windows
- and WindowsXP style do not.
-
- \sa textDirection
-*/
-
-/*!
- \fn void QProgressBar::valueChanged(int value)
-
- This signal is emitted when the value shown in the progress bar changes.
- \a value is the new value shown by the progress bar.
-*/
-
-/*!
- Constructs a progress bar with the given \a parent.
-
- By default, the minimum step value is set to 0, and the maximum to 100.
-
- \sa setRange()
-*/
-
-QProgressBar::QProgressBar(QWidget *parent)
- : QWidget(*(new QProgressBarPrivate), parent, 0)
-{
- d_func()->init();
-}
-
-/*!
- Reset the progress bar. The progress bar "rewinds" and shows no
- progress.
-*/
-
-void QProgressBar::reset()
-{
- Q_D(QProgressBar);
- d->value = d->minimum - 1;
- if (d->minimum == INT_MIN)
- d->value = INT_MIN;
- repaint();
-}
-
-/*!
- \property QProgressBar::minimum
- \brief the progress bar's minimum value
-
- When setting this property, the \l maximum is adjusted if
- necessary to ensure that the range remains valid. If the
- current value falls outside the new range, the progress bar is reset
- with reset().
-*/
-void QProgressBar::setMinimum(int minimum)
-{
- setRange(minimum, qMax(d_func()->maximum, minimum));
-}
-
-int QProgressBar::minimum() const
-{
- return d_func()->minimum;
-}
-
-
-/*!
- \property QProgressBar::maximum
- \brief the progress bar's maximum value
-
- When setting this property, the \l minimum is adjusted if
- necessary to ensure that the range remains valid. If the
- current value falls outside the new range, the progress bar is reset
- with reset().
-*/
-
-void QProgressBar::setMaximum(int maximum)
-{
- setRange(qMin(d_func()->minimum, maximum), maximum);
-}
-
-int QProgressBar::maximum() const
-{
- return d_func()->maximum;
-}
-
-/*!
- \property QProgressBar::value
- \brief the progress bar's current value
-
- Attempting to change the current value to one outside
- the minimum-maximum range has no effect on the current value.
-*/
-void QProgressBar::setValue(int value)
-{
- Q_D(QProgressBar);
- if (d->value == value
- || ((value > d->maximum || value < d->minimum)
- && (d->maximum != 0 || d->minimum != 0)))
- return;
- d->value = value;
- emit valueChanged(value);
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::ValueChanged);
-#endif
- if (d->repaintRequired())
- repaint();
-}
-
-int QProgressBar::value() const
-{
- return d_func()->value;
-}
-
-/*!
- Sets the progress bar's minimum and maximum values to \a minimum and
- \a maximum respectively.
-
- If \a maximum is smaller than \a minimum, \a minimum becomes the only
- legal value.
-
- If the current value falls outside the new range, the progress bar is reset
- with reset().
-
- \sa minimum maximum
-*/
-void QProgressBar::setRange(int minimum, int maximum)
-{
- Q_D(QProgressBar);
- d->minimum = minimum;
- d->maximum = qMax(minimum, maximum);
- if ( d->value <(d->minimum-1) || d->value > d->maximum)
- reset();
-}
-/*!
- \property QProgressBar::textVisible
- \brief whether the current completed percentage should be displayed
-
- This property may be ignored by the style (e.g., QMacStyle never draws the text).
-
- \sa textDirection
-*/
-void QProgressBar::setTextVisible(bool visible)
-{
- Q_D(QProgressBar);
- if (d->textVisible != visible) {
- d->textVisible = visible;
- repaint();
- }
-}
-
-bool QProgressBar::isTextVisible() const
-{
- return d_func()->textVisible;
-}
-
-/*!
- \property QProgressBar::alignment
- \brief the alignment of the progress bar
-*/
-void QProgressBar::setAlignment(Qt::Alignment alignment)
-{
- if (d_func()->alignment != alignment) {
- d_func()->alignment = alignment;
- repaint();
- }
-}
-
-Qt::Alignment QProgressBar::alignment() const
-{
- return d_func()->alignment;
-}
-
-/*!
- \reimp
-*/
-void QProgressBar::paintEvent(QPaintEvent *)
-{
- QStylePainter paint(this);
- QStyleOptionProgressBarV2 opt;
- initStyleOption(&opt);
- paint.drawControl(QStyle::CE_ProgressBar, opt);
- d_func()->lastPaintedValue = d_func()->value;
-}
-
-/*!
- \reimp
-*/
-QSize QProgressBar::sizeHint() const
-{
- ensurePolished();
- QFontMetrics fm = fontMetrics();
- QStyleOptionProgressBarV2 opt;
- initStyleOption(&opt);
- int cw = style()->pixelMetric(QStyle::PM_ProgressBarChunkWidth, &opt, this);
- QSize size = QSize(qMax(9, cw) * 7 + fm.width(QLatin1Char('0')) * 4, fm.height() + 8);
- if (opt.orientation == Qt::Vertical)
- size.transpose();
- return style()->sizeFromContents(QStyle::CT_ProgressBar, &opt, size, this);
-}
-
-/*!
- \reimp
-*/
-QSize QProgressBar::minimumSizeHint() const
-{
- QSize size;
- if (orientation() == Qt::Horizontal)
- size = QSize(sizeHint().width(), fontMetrics().height() + 2);
- else
- size = QSize(fontMetrics().height() + 2, sizeHint().height());
- return size;
-}
-
-/*!
- \property QProgressBar::text
- \brief the descriptive text shown with the progress bar
-
- The text returned is the same as the text displayed in the center
- (or in some styles, to the left) of the progress bar.
-
- The progress shown in the text may be smaller than the minimum value,
- indicating that the progress bar is in the "reset" state before any
- progress is set.
-
- In the default implementation, the text either contains a percentage
- value that indicates the progress so far, or it is blank because the
- progress bar is in the reset state.
-*/
-QString QProgressBar::text() const
-{
- Q_D(const QProgressBar);
- if ((d->maximum == 0 && d->minimum == 0) || d->value < d->minimum
- || (d->value == INT_MIN && d->minimum == INT_MIN))
- return QString();
-
- qint64 totalSteps = qint64(d->maximum) - d->minimum;
-
- QString result = d->format;
- result.replace(QLatin1String("%m"), QString::number(totalSteps));
- result.replace(QLatin1String("%v"), QString::number(d->value));
-
- // If max and min are equal and we get this far, it means that the
- // progress bar has one step and that we are on that step. Return
- // 100% here in order to avoid division by zero further down.
- if (totalSteps == 0) {
- result.replace(QLatin1String("%p"), QString::number(100));
- return result;
- }
-
- int progress = (qreal(d->value) - d->minimum) * 100.0 / totalSteps;
- result.replace(QLatin1String("%p"), QString::number(progress));
- return result;
-}
-
-/*!
- \since 4.1
- \property QProgressBar::orientation
- \brief the orientation of the progress bar
-
- The orientation must be \l Qt::Horizontal (the default) or \l
- Qt::Vertical.
-
- \sa invertedAppearance, textDirection
-*/
-
-void QProgressBar::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QProgressBar);
- if (d->orientation == orientation)
- return;
- d->orientation = orientation;
- if (!testAttribute(Qt::WA_WState_OwnSizePolicy)) {
- QSizePolicy sp = sizePolicy();
- sp.transpose();
- setSizePolicy(sp);
- setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- }
- d->resetLayoutItemMargins();
- update();
- updateGeometry();
-}
-
-Qt::Orientation QProgressBar::orientation() const
-{
- Q_D(const QProgressBar);
- return d->orientation;
-}
-
-/*!
- \since 4.1
- \property QProgressBar::invertedAppearance
- \brief whether or not a progress bar shows its progress inverted
-
- If this property is false, the progress bar grows in the other
- direction (e.g. from right to left). By default, the progress bar
- is not inverted.
-
- \sa orientation, layoutDirection
-*/
-
-void QProgressBar::setInvertedAppearance(bool invert)
-{
- Q_D(QProgressBar);
- d->invertedAppearance = invert;
- update();
-}
-
-bool QProgressBar::invertedAppearance()
-{
- Q_D(QProgressBar);
- return d->invertedAppearance;
-}
-
-/*!
- \since 4.1
- \property QProgressBar::textDirection
- \brief the reading direction of the \l text for vertical progress bars
-
- This property has no impact on horizontal progress bars.
- By default, the reading direction is QProgressBar::TopToBottom.
-
- \sa orientation, textVisible
-*/
-void QProgressBar::setTextDirection(QProgressBar::Direction textDirection)
-{
- Q_D(QProgressBar);
- d->textDirection = textDirection;
- update();
-}
-
-QProgressBar::Direction QProgressBar::textDirection()
-{
- Q_D(QProgressBar);
- return d->textDirection;
-}
-
-/*! \reimp */
-bool QProgressBar::event(QEvent *e)
-{
- Q_D(QProgressBar);
- if (e->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || e->type() == QEvent::MacSizeChange
-#endif
- )
- d->resetLayoutItemMargins();
- return QWidget::event(e);
-}
-
-/*!
- \since 4.2
- \property QProgressBar::format
- \brief the string used to generate the current text
-
- %p - is replaced by the percentage completed.
- %v - is replaced by the current value.
- %m - is replaced by the total number of steps.
-
- The default value is "%p%".
-
- \sa text()
-*/
-void QProgressBar::setFormat(const QString &format)
-{
- Q_D(QProgressBar);
- if (d->format == format)
- return;
- d->format = format;
- update();
-}
-
-QString QProgressBar::format() const
-{
- Q_D(const QProgressBar);
- return d->format;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PROGRESSBAR
diff --git a/src/gui/widgets/qprogressbar.h b/src/gui/widgets/qprogressbar.h
deleted file mode 100644
index 23bc26dc1e..0000000000
--- a/src/gui/widgets/qprogressbar.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** 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 QPROGRESSBAR_H
-#define QPROGRESSBAR_H
-
-#include <QtGui/qframe.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_PROGRESSBAR
-
-class QProgressBarPrivate;
-class QStyleOptionProgressBar;
-
-class Q_GUI_EXPORT QProgressBar : public QWidget
-{
- Q_OBJECT
- Q_ENUMS(Direction)
- Q_PROPERTY(int minimum READ minimum WRITE setMinimum)
- Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
- Q_PROPERTY(QString text READ text)
- Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
- Q_PROPERTY(bool textVisible READ isTextVisible WRITE setTextVisible)
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
- Q_PROPERTY(bool invertedAppearance READ invertedAppearance WRITE setInvertedAppearance)
- Q_PROPERTY(Direction textDirection READ textDirection WRITE setTextDirection)
- Q_PROPERTY(QString format READ format WRITE setFormat)
-
-public:
- enum Direction { TopToBottom, BottomToTop };
-
- explicit QProgressBar(QWidget *parent = 0);
-
- int minimum() const;
- int maximum() const;
-
- int value() const;
-
- virtual QString text() const;
- void setTextVisible(bool visible);
- bool isTextVisible() const;
-
- Qt::Alignment alignment() const;
- void setAlignment(Qt::Alignment alignment);
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- Qt::Orientation orientation() const;
-
- void setInvertedAppearance(bool invert);
- bool invertedAppearance(); //### Qt5 make const
- bool invertedAppearance() const { return const_cast<QProgressBar *>(this)->invertedAppearance(); }
- void setTextDirection(QProgressBar::Direction textDirection);
- QProgressBar::Direction textDirection(); //### Qt5 make const
- QProgressBar::Direction textDirection() const { return const_cast<QProgressBar *>(this)->textDirection(); }
-
- void setFormat(const QString &format);
- QString format() const;
-
-public Q_SLOTS:
- void reset();
- void setRange(int minimum, int maximum);
- void setMinimum(int minimum);
- void setMaximum(int maximum);
- void setValue(int value);
- void setOrientation(Qt::Orientation);
-
-Q_SIGNALS:
- void valueChanged(int value);
-
-protected:
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *);
- void initStyleOption(QStyleOptionProgressBar *option) const;
-
-private:
- Q_DECLARE_PRIVATE(QProgressBar)
- Q_DISABLE_COPY(QProgressBar)
-};
-
-#endif // QT_NO_PROGRESSBAR
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPROGRESSBAR_H
diff --git a/src/gui/widgets/qpushbutton.cpp b/src/gui/widgets/qpushbutton.cpp
deleted file mode 100644
index e52209bf1f..0000000000
--- a/src/gui/widgets/qpushbutton.cpp
+++ /dev/null
@@ -1,784 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qbitmap.h"
-#include "qdesktopwidget.h"
-#include "qdialog.h"
-#include <private/qdialog_p.h>
-#include "qdrawutil.h"
-#include "qevent.h"
-#include "qfontmetrics.h"
-#include "qmenu.h"
-#include "qstylepainter.h"
-#include "qpixmap.h"
-#include "qpointer.h"
-#include "qpushbutton.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qtoolbar.h"
-#include "qdebug.h"
-#include "qlayoutitem.h"
-#include "qdialogbuttonbox.h"
-#ifdef Q_WS_MAC
-#include "qmacstyle_mac.h"
-#include "private/qmacstyle_mac_p.h"
-#endif // Q_WS_MAC
-
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-
-#include "private/qmenu_p.h"
-#include "private/qpushbutton_p.h"
-
-QT_BEGIN_NAMESPACE
-
-
-/*!
- \class QPushButton
- \brief The QPushButton widget provides a command button.
-
- \ingroup basicwidgets
-
-
- The push button, or command button, is perhaps the most commonly
- used widget in any graphical user interface. Push (click) a button
- to command the computer to perform some action, or to answer a
- question. Typical buttons are OK, Apply, Cancel, Close, Yes, No
- and Help.
-
- A command button is rectangular and typically displays a text
- label describing its action. A shortcut key can be specified by
- preceding the preferred character with an ampersand in the
- text. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qpushbutton.cpp 0
-
- In this example the shortcut is \e{Alt+D}. See the \l
- {QShortcut#mnemonic}{QShortcut} documentation for details (to
- display an actual ampersand, use '&&').
-
- Push buttons display a textual label, and optionally a small
- icon. These can be set using the constructors and changed later
- using setText() and setIcon(). If the button is disabled the
- appearance of the text and icon will be manipulated with respect
- to the GUI style to make the button look "disabled".
-
- A push button emits the signal clicked() when it is activated by
- the mouse, the Spacebar or by a keyboard shortcut. Connect to
- this signal to perform the button's action. Push buttons also
- provide less commonly used signals, for example, pressed() and
- released().
-
- Command buttons in dialogs are by default auto-default buttons,
- i.e. they become the default push button automatically when they
- receive the keyboard input focus. A default button is a push
- button that is activated when the user presses the Enter or Return
- key in a dialog. You can change this with setAutoDefault(). Note
- that auto-default buttons reserve a little extra space which is
- necessary to draw a default-button indicator. If you do not want
- this space around your buttons, call setAutoDefault(false).
-
- Being so central, the button widget has grown to accommodate a
- great many variations in the past decade. The Microsoft style
- guide now shows about ten different states of Windows push buttons
- and the text implies that there are dozens more when all the
- combinations of features are taken into consideration.
-
- The most important modes or states are:
- \list
- \i Available or not (grayed out, disabled).
- \i Standard push button, toggling push button or menu button.
- \i On or off (only for toggling push buttons).
- \i Default or normal. The default button in a dialog can generally
- be "clicked" using the Enter or Return key.
- \i Auto-repeat or not.
- \i Pressed down or not.
- \endlist
-
- As a general rule, use a push button when the application or
- dialog window performs an action when the user clicks on it (such
- as Apply, Cancel, Close and Help) \e and when the widget is
- supposed to have a wide, rectangular shape with a text label.
- Small, typically square buttons that change the state of the
- window rather than performing an action (such as the buttons in
- the top-right corner of the QFileDialog) are not command buttons,
- but tool buttons. Qt provides a special class (QToolButton) for
- these buttons.
-
- If you need toggle behavior (see setCheckable()) or a button
- that auto-repeats the activation signal when being pushed down
- like the arrows in a scroll bar (see setAutoRepeat()), a command
- button is probably not what you want. When in doubt, use a tool
- button.
-
- A variation of a command button is a menu button. These provide
- not just one command, but several, since when they are clicked
- they pop up a menu of options. Use the method setMenu() to
- associate a popup menu with a push button.
-
- Other classes of buttons are option buttons (see QRadioButton) and
- check boxes (see QCheckBox).
-
- \table 100%
- \row \o \inlineimage macintosh-pushbutton.png Screenshot of a Macintosh style push button
- \o A push button shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
-
- Note that when a button's width becomes smaller than 50 or
- its height becomes smaller than 30, the button's corners are
- changed from round to square. Use the setMinimumSize()
- function to prevent this behavior.
-
- \row \o \inlineimage windowsxp-pushbutton.png Screenshot of a Windows XP style push button
- \o A push button shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage plastique-pushbutton.png Screenshot of a Plastique style push button
- \o A push button shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- In Qt, the QAbstractButton base class provides most of the modes
- and other API, and QPushButton provides GUI logic.
- See QAbstractButton for more information about the API.
-
- \sa QToolButton, QRadioButton, QCheckBox, {fowler}{GUI Design Handbook: Push Button}
-*/
-
-/*!
- \property QPushButton::autoDefault
- \brief whether the push button is an auto default button
-
- If this property is set to true then the push button is an auto
- default button.
-
- In some GUI styles a default button is drawn with an extra frame
- around it, up to 3 pixels or more. Qt automatically keeps this
- space free around auto-default buttons, i.e. auto-default buttons
- may have a slightly larger size hint.
-
- This property's default is true for buttons that have a QDialog
- parent; otherwise it defaults to false.
-
- See the \l default property for details of how \l default and
- auto-default interact.
-*/
-
-/*!
- \property QPushButton::default
- \brief whether the push button is the default button
-
- Default and autodefault buttons decide what happens when the user
- presses enter in a dialog.
-
- A button with this property set to true (i.e., the dialog's
- \e default button,) will automatically be pressed when the user presses enter,
- with one exception: if an \a autoDefault button currently has focus, the autoDefault
- button is pressed. When the dialog has \l autoDefault buttons but no default button,
- pressing enter will press either the \l autoDefault button that currently has focus, or if no
- button has focus, the next \l autoDefault button in the focus chain.
-
- In a dialog, only one push button at a time can be the default
- button. This button is then displayed with an additional frame
- (depending on the GUI style).
-
- The default button behavior is provided only in dialogs. Buttons
- can always be clicked from the keyboard by pressing Spacebar when
- the button has focus.
-
- If the default property is set to false on the current default button
- while the dialog is visible, a new default will automatically be
- assigned the next time a pushbutton in the dialog receives focus.
-
- This property's default is false.
-*/
-
-/*!
- \property QPushButton::flat
- \brief whether the button border is raised
-
- This property's default is false. If this property is set, most
- styles will not paint the button background unless the button is
- being pressed. setAutoFillBackground() can be used to ensure that
- the background is filled using the QPalette::Button brush.
-*/
-
-/*!
- Constructs a push button with no text and a \a parent.
-*/
-
-QPushButton::QPushButton(QWidget *parent)
- : QAbstractButton(*new QPushButtonPrivate, parent)
-{
- Q_D(QPushButton);
- d->init();
-}
-
-/*!
- Constructs a push button with the parent \a parent and the text \a
- text.
-*/
-
-QPushButton::QPushButton(const QString &text, QWidget *parent)
- : QAbstractButton(*new QPushButtonPrivate, parent)
-{
- Q_D(QPushButton);
- setText(text);
- d->init();
-}
-
-
-/*!
- Constructs a push button with an \a icon and a \a text, and a \a parent.
-
- Note that you can also pass a QPixmap object as an icon (thanks to
- the implicit type conversion provided by C++).
-
-*/
-QPushButton::QPushButton(const QIcon& icon, const QString &text, QWidget *parent)
- : QAbstractButton(*new QPushButtonPrivate, parent)
-{
- Q_D(QPushButton);
- setText(text);
- setIcon(icon);
- d->init();
-}
-
-/*! \internal
- */
-QPushButton::QPushButton(QPushButtonPrivate &dd, QWidget *parent)
- : QAbstractButton(dd, parent)
-{
- Q_D(QPushButton);
- d->init();
-}
-
-/*!
- Destroys the push button.
-*/
-QPushButton::~QPushButton()
-{
-}
-
-QDialog *QPushButtonPrivate::dialogParent() const
-{
- Q_Q(const QPushButton);
- const QWidget *p = q;
- while (p && !p->isWindow()) {
- p = p->parentWidget();
- if (const QDialog *dialog = qobject_cast<const QDialog *>(p))
- return const_cast<QDialog *>(dialog);
- }
- return 0;
-}
-
-/*!
- Initialize \a option with the values from this QPushButton. This method is useful
- for subclasses when they need a QStyleOptionButton, but don't want to fill
- in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QPushButton::initStyleOption(QStyleOptionButton *option) const
-{
- if (!option)
- return;
-
- Q_D(const QPushButton);
- option->initFrom(this);
- option->features = QStyleOptionButton::None;
- if (d->flat)
- option->features |= QStyleOptionButton::Flat;
-#ifndef QT_NO_MENU
- if (d->menu)
- option->features |= QStyleOptionButton::HasMenu;
-#endif
- if (autoDefault() || d->defaultButton)
- option->features |= QStyleOptionButton::AutoDefaultButton;
- if (d->defaultButton)
- option->features |= QStyleOptionButton::DefaultButton;
- if (d->down || d->menuOpen)
- option->state |= QStyle::State_Sunken;
- if (d->checked)
- option->state |= QStyle::State_On;
- if (!d->flat && !d->down)
- option->state |= QStyle::State_Raised;
- option->text = d->text;
- option->icon = d->icon;
- option->iconSize = iconSize();
-}
-
-void QPushButton::setAutoDefault(bool enable)
-{
- Q_D(QPushButton);
- uint state = enable ? QPushButtonPrivate::On : QPushButtonPrivate::Off;
- if (d->autoDefault != QPushButtonPrivate::Auto && d->autoDefault == state)
- return;
- d->autoDefault = state;
- d->sizeHint = QSize();
- update();
- updateGeometry();
-}
-
-bool QPushButton::autoDefault() const
-{
- Q_D(const QPushButton);
- if(d->autoDefault == QPushButtonPrivate::Auto)
- return ( d->dialogParent() != 0 );
- return d->autoDefault;
-}
-
-void QPushButton::setDefault(bool enable)
-{
- Q_D(QPushButton);
- if (d->defaultButton == enable)
- return;
- d->defaultButton = enable;
- if (d->defaultButton) {
- if (QDialog *dlg = d->dialogParent())
- dlg->d_func()->setMainDefault(this);
- }
- update();
-#ifndef QT_NO_ACCESSIBILITY
- QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
-#endif
-}
-
-bool QPushButton::isDefault() const
-{
- Q_D(const QPushButton);
- return d->defaultButton;
-}
-
-/*!
- \reimp
-*/
-QSize QPushButton::sizeHint() const
-{
- Q_D(const QPushButton);
- if (d->sizeHint.isValid() && d->lastAutoDefault == autoDefault())
- return d->sizeHint;
- d->lastAutoDefault = autoDefault();
- ensurePolished();
-
- int w = 0, h = 0;
-
- QStyleOptionButton opt;
- initStyleOption(&opt);
-
- // calculate contents size...
-#ifndef QT_NO_ICON
-
- bool showButtonBoxIcons = qobject_cast<QDialogButtonBox*>(parentWidget())
- && style()->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons);
-
- if (!icon().isNull() || showButtonBoxIcons) {
- int ih = opt.iconSize.height();
- int iw = opt.iconSize.width() + 4;
- w += iw;
- h = qMax(h, ih);
- }
-#endif
- QString s(text());
- bool empty = s.isEmpty();
- if (empty)
- s = QString::fromLatin1("XXXX");
- QFontMetrics fm = fontMetrics();
- QSize sz = fm.size(Qt::TextShowMnemonic, s);
- if(!empty || !w)
- w += sz.width();
- if(!empty || !h)
- h = qMax(h, sz.height());
- opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height
-#ifndef QT_NO_MENU
- if (menu())
- w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this);
-#endif
- d->sizeHint = (style()->sizeFromContents(QStyle::CT_PushButton, &opt, QSize(w, h), this).
- expandedTo(QApplication::globalStrut()));
- return d->sizeHint;
-}
-
-/*!
- \reimp
- */
-QSize QPushButton::minimumSizeHint() const
-{
- return sizeHint();
-}
-
-
-/*!\reimp
-*/
-void QPushButton::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionButton option;
- initStyleOption(&option);
- p.drawControl(QStyle::CE_PushButton, option);
-}
-
-
-/*! \reimp */
-void QPushButton::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QPushButton);
- switch (e->key()) {
- case Qt::Key_Enter:
- case Qt::Key_Return:
- if (autoDefault() || d->defaultButton) {
- click();
- break;
- }
- // fall through
- default:
- QAbstractButton::keyPressEvent(e);
- }
-}
-
-/*!
- \reimp
-*/
-void QPushButton::focusInEvent(QFocusEvent *e)
-{
- Q_D(QPushButton);
- if (e->reason() != Qt::PopupFocusReason && autoDefault() && !d->defaultButton) {
- d->defaultButton = true;
- QDialog *dlg = qobject_cast<QDialog*>(window());
- if (dlg)
- dlg->d_func()->setDefault(this);
- }
- QAbstractButton::focusInEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QPushButton::focusOutEvent(QFocusEvent *e)
-{
- Q_D(QPushButton);
- if (e->reason() != Qt::PopupFocusReason && autoDefault() && d->defaultButton) {
- QDialog *dlg = qobject_cast<QDialog*>(window());
- if (dlg)
- dlg->d_func()->setDefault(0);
- else
- d->defaultButton = false;
- }
-
- QAbstractButton::focusOutEvent(e);
-#ifndef QT_NO_MENU
- if (d->menu && d->menu->isVisible()) // restore pressed status
- setDown(true);
-#endif
-}
-
-#ifndef QT_NO_MENU
-/*!
- Associates the popup menu \a menu with this push button. This
- turns the button into a menu button, which in some styles will
- produce a small triangle to the right of the button's text.
-
- Ownership of the menu is \e not transferred to the push button.
-
- \table 100%
- \row
- \o \inlineimage plastique-pushbutton-menu.png Screenshot of a Plastique style push button with popup menu.
- \o \inlineimage cleanlooks-pushbutton-menu.png Screenshot of a Cleanlooks style push button with popup menu.
- \o Push buttons with popup menus shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}
- (left) and \l{Cleanlooks Style Widget Gallery}{Cleanlooks widget style} (right).
- \endtable
-
- \sa menu()
-*/
-void QPushButton::setMenu(QMenu* menu)
-{
- Q_D(QPushButton);
- if (menu == d->menu)
- return;
-
- if (menu && !d->menu) {
- connect(this, SIGNAL(pressed()), this, SLOT(_q_popupPressed()), Qt::UniqueConnection);
- }
- if (d->menu)
- removeAction(d->menu->menuAction());
- d->menu = menu;
- if (d->menu)
- addAction(d->menu->menuAction());
-
- d->resetLayoutItemMargins();
- d->sizeHint = QSize();
- update();
- updateGeometry();
-}
-
-/*!
- Returns the button's associated popup menu or 0 if no popup menu
- has been set.
-
- \sa setMenu()
-*/
-QMenu* QPushButton::menu() const
-{
- Q_D(const QPushButton);
- return d->menu;
-}
-
-/*!
- Shows (pops up) the associated popup menu. If there is no such
- menu, this function does nothing. This function does not return
- until the popup menu has been closed by the user.
-*/
-void QPushButton::showMenu()
-{
- Q_D(QPushButton);
- if (!d || !d->menu)
- return;
- setDown(true);
- d->_q_popupPressed();
-}
-
-void QPushButtonPrivate::_q_popupPressed()
-{
- Q_Q(QPushButton);
- if (!down || !menu)
- return;
-
- menu->setNoReplayFor(q);
-
- QPoint menuPos = adjustedMenuPosition();
-
- QPointer<QPushButton> guard(q);
- QMenuPrivate::get(menu)->causedPopup.widget = guard;
-
- //Because of a delay in menu effects, we must keep track of the
- //menu visibility to avoid flicker on button release
- menuOpen = true;
- menu->exec(menuPos);
- if (guard) {
- menuOpen = false;
- q->setDown(false);
- }
-}
-
-QPoint QPushButtonPrivate::adjustedMenuPosition()
-{
- Q_Q(QPushButton);
-
- bool horizontal = true;
-#if !defined(QT_NO_TOOLBAR)
- QToolBar *tb = qobject_cast<QToolBar*>(parent);
- if (tb && tb->orientation() == Qt::Vertical)
- horizontal = false;
-#endif
-
- QWidgetItem item(q);
- QRect rect = item.geometry();
- rect.setRect(rect.x() - q->x(), rect.y() - q->y(), rect.width(), rect.height());
-
- QSize menuSize = menu->sizeHint();
- QPoint globalPos = q->mapToGlobal(rect.topLeft());
- int x = globalPos.x();
- int y = globalPos.y();
- if (horizontal) {
- if (globalPos.y() + rect.height() + menuSize.height() <= QApplication::desktop()->availableGeometry(q).height()) {
- y += rect.height();
- } else {
- y -= menuSize.height();
- }
- if (q->layoutDirection() == Qt::RightToLeft)
- x += rect.width() - menuSize.width();
- } else {
- if (globalPos.x() + rect.width() + menu->sizeHint().width() <= QApplication::desktop()->availableGeometry(q).width())
- x += rect.width();
- else
- x -= menuSize.width();
- }
-
- return QPoint(x,y);
-}
-
-#endif // QT_NO_MENU
-
-void QPushButtonPrivate::resetLayoutItemMargins()
-{
- Q_Q(QPushButton);
- QStyleOptionButton opt;
- q->initStyleOption(&opt);
- setLayoutItemMargins(QStyle::SE_PushButtonLayoutItem, &opt);
-}
-
-void QPushButton::setFlat(bool flat)
-{
- Q_D(QPushButton);
- if (d->flat == flat)
- return;
- d->flat = flat;
- d->resetLayoutItemMargins();
- d->sizeHint = QSize();
- update();
- updateGeometry();
-}
-
-bool QPushButton::isFlat() const
-{
- Q_D(const QPushButton);
- return d->flat;
-}
-
-/*! \reimp */
-bool QPushButton::event(QEvent *e)
-{
- Q_D(QPushButton);
- if (e->type() == QEvent::ParentChange) {
- if (QDialog *dialog = d->dialogParent()) {
- if (d->defaultButton)
- dialog->d_func()->setMainDefault(this);
- }
- } else if (e->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || e->type() == QEvent::MacSizeChange
-#endif
- ) {
- d->resetLayoutItemMargins();
- updateGeometry();
- } else if (e->type() == QEvent::PolishRequest) {
- updateGeometry();
- }
- return QAbstractButton::event(e);
-}
-
-#ifdef Q_WS_MAC
-/*! \reimp */
-bool QPushButton::hitButton(const QPoint &pos) const
-{
- QStyleOptionButton opt;
- initStyleOption(&opt);
- if (qt_mac_buttonIsRenderedFlat(this, &opt))
- return QAbstractButton::hitButton(pos);
-
- // Now that we know we are using the native style, let's proceed.
- Q_D(const QPushButton);
- QPushButtonPrivate *nonConst = const_cast<QPushButtonPrivate *>(d);
- // In OSX buttons are round, which causes the hit method to be special.
- // We cannot simply relay on detecting if something is inside the rect or not,
- // we need to check if it is inside the "rounded area" or not. A point might
- // be inside the rect but not inside the rounded area.
- // Notice this method is only reimplemented for OSX.
- return nonConst->hitButton(pos);
-}
-
-bool QPushButtonPrivate::hitButton(const QPoint &pos)
-{
- Q_Q(QPushButton);
- QRect roundedRect(q->rect().left() + QMacStylePrivate::PushButtonLeftOffset,
- q->rect().top() + QMacStylePrivate::PushButtonContentPadding,
- q->rect().width() - QMacStylePrivate::PushButtonRightOffset,
- q->rect().height() - QMacStylePrivate::PushButtonBottomOffset);
- return roundedRect.contains(pos);
-}
-#endif // Q_WS_MAC
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QPushButton::QPushButton(QWidget *parent, const char *name)
- : QAbstractButton(*new QPushButtonPrivate, parent)
-{
- Q_D(QPushButton);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QPushButton::QPushButton(const QString &text, QWidget *parent, const char *name)
- : QAbstractButton(*new QPushButtonPrivate, parent)
-{
- Q_D(QPushButton);
- setObjectName(QString::fromAscii(name));
- setText(text);
- d->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QPushButton::QPushButton(const QIcon& icon, const QString &text, QWidget *parent, const char *name)
- : QAbstractButton(*new QPushButtonPrivate, parent)
-{
- Q_D(QPushButton);
- setObjectName(QString::fromAscii(name));
- setText(text);
- setIcon(icon);
- d->init();
-}
-#endif
-
-/*!
- \fn void QPushButton::openPopup()
-
- Use showMenu() instead.
-*/
-
-/*!
- \fn bool QPushButton::isMenuButton() const
-
- Use menu() != 0 instead.
-*/
-
-/*!
- \fn void QPushButton::setPopup(QMenu* popup)
-
- Use setMenu() instead.
-*/
-
-/*!
- \fn QMenu* QPushButton::popup() const
-
- Use menu() instead.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qpushbutton.cpp"
diff --git a/src/gui/widgets/qpushbutton.h b/src/gui/widgets/qpushbutton.h
deleted file mode 100644
index 59d04055f7..0000000000
--- a/src/gui/widgets/qpushbutton.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/****************************************************************************
-**
-** 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 QPUSHBUTTON_H
-#define QPUSHBUTTON_H
-
-#include <QtGui/qabstractbutton.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QPushButtonPrivate;
-class QMenu;
-class QStyleOptionButton;
-
-class Q_GUI_EXPORT QPushButton : public QAbstractButton
-{
- Q_OBJECT
-
- Q_PROPERTY(bool autoDefault READ autoDefault WRITE setAutoDefault)
- Q_PROPERTY(bool default READ isDefault WRITE setDefault)
- Q_PROPERTY(bool flat READ isFlat WRITE setFlat)
-
-public:
- explicit QPushButton(QWidget *parent=0);
- explicit QPushButton(const QString &text, QWidget *parent=0);
- QPushButton(const QIcon& icon, const QString &text, QWidget *parent=0);
- ~QPushButton();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- bool autoDefault() const;
- void setAutoDefault(bool);
- bool isDefault() const;
- void setDefault(bool);
-
-#ifndef QT_NO_MENU
- void setMenu(QMenu* menu);
- QMenu* menu() const;
-#endif
-
- void setFlat(bool);
- bool isFlat() const;
-
-public Q_SLOTS:
-#ifndef QT_NO_MENU
- void showMenu();
-#endif
-
-protected:
- bool event(QEvent *e);
-#ifdef Q_WS_MAC
- bool hitButton(const QPoint &pos) const;
-#endif // Q_WS_MAC
- void paintEvent(QPaintEvent *);
- void keyPressEvent(QKeyEvent *);
- void focusInEvent(QFocusEvent *);
- void focusOutEvent(QFocusEvent *);
- void initStyleOption(QStyleOptionButton *option) const;
- QPushButton(QPushButtonPrivate &dd, QWidget* parent = 0);
-
-public:
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QPushButton(QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QPushButton(const QString &text, QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QPushButton(const QIcon& icon, const QString &text, QWidget *parent, const char* name);
- inline QT3_SUPPORT void openPopup() { showMenu(); }
- inline QT3_SUPPORT bool isMenuButton() const { return menu() != 0; }
- inline QT3_SUPPORT void setPopup(QMenu* popup) {setMenu(popup); }
- inline QT3_SUPPORT QMenu* popup() const { return menu(); }
-#endif
-
-private:
- Q_DISABLE_COPY(QPushButton)
- Q_DECLARE_PRIVATE(QPushButton)
-#ifndef QT_NO_MENU
- Q_PRIVATE_SLOT(d_func(), void _q_popupPressed())
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QPUSHBUTTON_H
diff --git a/src/gui/widgets/qpushbutton_p.h b/src/gui/widgets/qpushbutton_p.h
deleted file mode 100644
index f6804af277..0000000000
--- a/src/gui/widgets/qpushbutton_p.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qabstractbutton_p.h"
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-QT_BEGIN_NAMESPACE
-
-class QDialog;
-class QPushButton;
-
-class QPushButtonPrivate : public QAbstractButtonPrivate
-{
- Q_DECLARE_PUBLIC(QPushButton)
-public:
- enum AutoDefaultValue { Off = 0, On = 1, Auto = 2 };
-
- QPushButtonPrivate()
- : QAbstractButtonPrivate(QSizePolicy::PushButton), autoDefault(Auto),
- defaultButton(false), flat(false), menuOpen(false), lastAutoDefault(false) {}
-
- inline void init() { resetLayoutItemMargins(); }
- static QPushButtonPrivate* get(QPushButton *b) { return b->d_func(); }
-#ifdef Q_WS_MAC
- bool hitButton(const QPoint &pos);
-#endif
-#ifndef QT_NO_MENU
- QPoint adjustedMenuPosition();
-#endif
- void resetLayoutItemMargins();
- void _q_popupPressed();
- QDialog *dialogParent() const;
-
- QPointer<QMenu> menu;
- uint autoDefault : 2;
- uint defaultButton : 1;
- uint flat : 1;
- uint menuOpen : 1;
- mutable uint lastAutoDefault : 1;
-};
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qradiobutton.cpp b/src/gui/widgets/qradiobutton.cpp
deleted file mode 100644
index bb13017dbc..0000000000
--- a/src/gui/widgets/qradiobutton.cpp
+++ /dev/null
@@ -1,296 +0,0 @@
-/****************************************************************************
-**
-** 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 "qradiobutton.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qbuttongroup.h"
-#include "qstylepainter.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qevent.h"
-
-#include "private/qabstractbutton_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QRadioButtonPrivate : public QAbstractButtonPrivate
-{
- Q_DECLARE_PUBLIC(QRadioButton)
-
-public:
- QRadioButtonPrivate() : QAbstractButtonPrivate(QSizePolicy::RadioButton), hovering(true) {}
- void init();
- uint hovering : 1;
-};
-
-/*
- Initializes the radio button.
-*/
-void QRadioButtonPrivate::init()
-{
- Q_Q(QRadioButton);
- q->setCheckable(true);
- q->setAutoExclusive(true);
- q->setMouseTracking(true);
- q->setForegroundRole(QPalette::WindowText);
- setLayoutItemMargins(QStyle::SE_RadioButtonLayoutItem);
-}
-
-/*!
- \class QRadioButton
- \brief The QRadioButton widget provides a radio button with a text label.
-
- \ingroup basicwidgets
-
-
- A QRadioButton is an option button that can be switched on (checked) or
- off (unchecked). Radio buttons typically present the user with a "one
- of many" choice. In a group of radio buttons only one radio button at
- a time can be checked; if the user selects another button, the
- previously selected button is switched off.
-
- Radio buttons are autoExclusive by default. If auto-exclusive is
- enabled, radio buttons that belong to the same parent widget
- behave as if they were part of the same exclusive button group. If
- you need multiple exclusive button groups for radio buttons that
- belong to the same parent widget, put them into a QButtonGroup.
-
- Whenever a button is switched on or off it emits the toggled() signal.
- Connect to this signal if you want to trigger an action each time the
- button changes state. Use isChecked() to see if a particular button is
- selected.
-
- Just like QPushButton, a radio button displays text, and
- optionally a small icon. The icon is set with setIcon(). The text
- can be set in the constructor or with setText(). A shortcut key
- can be specified by preceding the preferred character with an
- ampersand in the text. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qradiobutton.cpp 0
-
- In this example the shortcut is \e{Alt+c}. See the \l
- {QShortcut#mnemonic}{QShortcut} documentation for details (to
- display an actual ampersand, use '&&').
-
- Important inherited members: text(), setText(), text(),
- setDown(), isDown(), autoRepeat(), group(), setAutoRepeat(),
- toggle(), pressed(), released(), clicked(), and toggled().
-
- \table 100%
- \row \o \inlineimage plastique-radiobutton.png Screenshot of a Plastique radio button
- \o A radio button shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \row \o \inlineimage windows-radiobutton.png Screenshot of a Windows XP radio button
- \o A radio button shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage macintosh-radiobutton.png Screenshot of a Macintosh radio button
- \o A radio button shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \endtable
-
- \sa QPushButton, QToolButton, QCheckBox, {fowler}{GUI Design Handbook: Radio Button},
- {Group Box Example}
-*/
-
-
-/*!
- Constructs a radio button with the given \a parent, but with no text or
- pixmap.
-
- The \a parent argument is passed on to the QAbstractButton constructor.
-*/
-
-QRadioButton::QRadioButton(QWidget *parent)
- : QAbstractButton(*new QRadioButtonPrivate, parent)
-{
- Q_D(QRadioButton);
- d->init();
-}
-
-/*!
- Constructs a radio button with the given \a parent and a \a text string.
-
- The \a parent argument is passed on to the QAbstractButton constructor.
-*/
-
-QRadioButton::QRadioButton(const QString &text, QWidget *parent)
- : QAbstractButton(*new QRadioButtonPrivate, parent)
-{
- Q_D(QRadioButton);
- d->init();
- setText(text);
-}
-
-/*!
- Initialize \a option with the values from this QRadioButton. This method is useful
- for subclasses when they need a QStyleOptionButton, but don't want to fill
- in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QRadioButton::initStyleOption(QStyleOptionButton *option) const
-{
- if (!option)
- return;
- Q_D(const QRadioButton);
- option->initFrom(this);
- option->text = d->text;
- option->icon = d->icon;
- option->iconSize = iconSize();
- if (d->down)
- option->state |= QStyle::State_Sunken;
- option->state |= (d->checked) ? QStyle::State_On : QStyle::State_Off;
- if (testAttribute(Qt::WA_Hover) && underMouse()) {
- if (d->hovering)
- option->state |= QStyle::State_MouseOver;
- else
- option->state &= ~QStyle::State_MouseOver;
- }
-}
-
-/*!
- \reimp
-*/
-QSize QRadioButton::sizeHint() const
-{
- Q_D(const QRadioButton);
- if (d->sizeHint.isValid())
- return d->sizeHint;
- ensurePolished();
- QStyleOptionButton opt;
- initStyleOption(&opt);
- QSize sz = style()->itemTextRect(fontMetrics(), QRect(), Qt::TextShowMnemonic,
- false, text()).size();
- if (!opt.icon.isNull())
- sz = QSize(sz.width() + opt.iconSize.width() + 4, qMax(sz.height(), opt.iconSize.height()));
- d->sizeHint = (style()->sizeFromContents(QStyle::CT_RadioButton, &opt, sz, this).
- expandedTo(QApplication::globalStrut()));
- return d->sizeHint;
-}
-
-/*!
- \reimp
-*/
-QSize QRadioButton::minimumSizeHint() const
-{
- return sizeHint();
-}
-
-/*!
- \reimp
-*/
-bool QRadioButton::hitButton(const QPoint &pos) const
-{
- QStyleOptionButton opt;
- initStyleOption(&opt);
- return style()->subElementRect(QStyle::SE_RadioButtonClickRect, &opt, this).contains(pos);
-}
-
-/*!
- \reimp
-*/
-void QRadioButton::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QRadioButton);
- if (testAttribute(Qt::WA_Hover)) {
- bool hit = false;
- if (underMouse())
- hit = hitButton(e->pos());
-
- if (hit != d->hovering) {
- update();
- d->hovering = hit;
- }
- }
-
- QAbstractButton::mouseMoveEvent(e);
-}
-
-/*!\reimp
- */
-void QRadioButton::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionButton opt;
- initStyleOption(&opt);
- p.drawControl(QStyle::CE_RadioButton, opt);
-}
-
-/*! \reimp */
-bool QRadioButton::event(QEvent *e)
-{
- Q_D(QRadioButton);
- if (e->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || e->type() == QEvent::MacSizeChange
-#endif
- )
- d->setLayoutItemMargins(QStyle::SE_RadioButtonLayoutItem);
- return QAbstractButton::event(e);
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QRadioButton::QRadioButton(QWidget *parent, const char* name)
- : QAbstractButton(*new QRadioButtonPrivate, parent)
-{
- Q_D(QRadioButton);
- d->init();
- setObjectName(QString::fromAscii(name));
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QRadioButton::QRadioButton(const QString &text, QWidget *parent, const char* name)
- : QAbstractButton(*new QRadioButtonPrivate, parent)
-{
- Q_D(QRadioButton);
- d->init();
- setObjectName(QString::fromAscii(name));
- setText(text);
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qradiobutton.h b/src/gui/widgets/qradiobutton.h
deleted file mode 100644
index b720498897..0000000000
--- a/src/gui/widgets/qradiobutton.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** 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 QRADIOBUTTON_H
-#define QRADIOBUTTON_H
-
-#include <QtGui/qabstractbutton.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QRadioButtonPrivate;
-class QStyleOptionButton;
-
-class Q_GUI_EXPORT QRadioButton : public QAbstractButton
-{
- Q_OBJECT
-
-public:
- explicit QRadioButton(QWidget *parent=0);
- explicit QRadioButton(const QString &text, QWidget *parent=0);
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
-protected:
- bool event(QEvent *e);
- bool hitButton(const QPoint &) const;
- void paintEvent(QPaintEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void initStyleOption(QStyleOptionButton *button) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QRadioButton(QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QRadioButton(const QString &text, QWidget *parent, const char* name);
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QRadioButton)
- Q_DISABLE_COPY(QRadioButton)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QRADIOBUTTON_H
diff --git a/src/gui/widgets/qrubberband.cpp b/src/gui/widgets/qrubberband.cpp
deleted file mode 100644
index 55448c3116..0000000000
--- a/src/gui/widgets/qrubberband.cpp
+++ /dev/null
@@ -1,336 +0,0 @@
-/****************************************************************************
-**
-** 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 "qbitmap.h"
-#include "qevent.h"
-#include "qstylepainter.h"
-#include "qrubberband.h"
-#include "qtimer.h"
-
-#ifndef QT_NO_RUBBERBAND
-
-#include "qstyle.h"
-#include "qstyleoption.h"
-#ifdef Q_WS_MAC
-# include <private/qt_mac_p.h>
-# include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#include <qdebug.h>
-
-#include <private/qwidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-//### a rubberband window type would be a more elegant solution
-#define RUBBERBAND_WINDOW_TYPE Qt::ToolTip
-
-class QRubberBandPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QRubberBand)
-public:
- QRect rect;
- QRubberBand::Shape shape;
- QRegion clipping;
- void updateMask();
-};
-
-/*!
- Initialize \a option with the values from this QRubberBand. This method
- is useful for subclasses when they need a QStyleOptionRubberBand, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QRubberBand::initStyleOption(QStyleOptionRubberBand *option) const
-{
- if (!option)
- return;
- option->initFrom(this);
- option->shape = d_func()->shape;
-#ifndef Q_WS_MAC
- option->opaque = true;
-#else
- option->opaque = windowFlags() & RUBBERBAND_WINDOW_TYPE;
-#endif
-}
-
-/*!
- \class QRubberBand
- \brief The QRubberBand class provides a rectangle or line that can
- indicate a selection or a boundary.
-
- A rubber band is often used to show a new bounding area (as in a
- QSplitter or a QDockWidget that is undocking). Historically this has
- been implemented using a QPainter and XOR, but this approach
- doesn't always work properly since rendering can happen in the
- window below the rubber band, but before the rubber band has been
- "erased".
-
- You can create a QRubberBand whenever you need to render a rubber band
- around a given area (or to represent a single line), then call
- setGeometry(), move() or resize() to position and size it. A common
- pattern is to do this in conjunction with mouse events. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qrubberband.cpp 0
-
- If you pass a parent to QRubberBand's constructor, the rubber band will
- display only inside its parent, but stays on top of other child widgets.
- If no parent is passed, QRubberBand will act as a top-level widget.
-
- Call show() to make the rubber band visible; also when the
- rubber band is not a top-level. Hiding or destroying
- the widget will make the rubber band disappear. The rubber band
- can be a \l Rectangle or a \l Line (vertical or horizontal),
- depending on the shape() it was given when constructed.
-*/
-
-// ### DOC: How about some nice convenience constructors?
-//QRubberBand::QRubberBand(QRubberBand::Type t, const QRect &rect, QWidget *p)
-//QRubberBand::QRubberBand(QRubberBand::Type t, int x, int y, int w, int h, QWidget *p)
-
-/*!
- Constructs a rubber band of shape \a s, with parent \a p.
-
- By default a rectangular rubber band (\a s is \c Rectangle) will
- use a mask, so that a small border of the rectangle is all
- that is visible. Some styles (e.g., native Mac OS X) will
- change this and call QWidget::setWindowOpacity() to make a
- semi-transparent filled selection rectangle.
-*/
-QRubberBand::QRubberBand(Shape s, QWidget *p)
- : QWidget(*new QRubberBandPrivate, p, (p && p->windowType() != Qt::Desktop) ? Qt::Widget : RUBBERBAND_WINDOW_TYPE)
-{
- Q_D(QRubberBand);
- d->shape = s;
- setAttribute(Qt::WA_TransparentForMouseEvents);
-#ifndef Q_WS_WIN
- setAttribute(Qt::WA_NoSystemBackground);
-#endif //Q_WS_WIN
- setAttribute(Qt::WA_WState_ExplicitShowHide);
- setVisible(false);
-#ifdef Q_WS_MAC
- if (isWindow()) {
- createWinId();
- extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
- macWindowSetHasShadow(qt_mac_window_for(this), false);
- }
-#endif
-}
-
-/*!
- Destructor.
-*/
-QRubberBand::~QRubberBand()
-{
-}
-
-/*!
- \enum QRubberBand::Shape
-
- This enum specifies what shape a QRubberBand should have. This is
- a drawing hint that is passed down to the style system, and can be
- interpreted by each QStyle.
-
- \value Line A QRubberBand can represent a vertical or horizontal
- line. Geometry is still given in rect() and the line
- will fill the given geometry on most styles.
-
- \value Rectangle A QRubberBand can represent a rectangle. Some
- styles will interpret this as a filled (often
- semi-transparent) rectangle, or a rectangular
- outline.
-*/
-
-/*!
- Returns the shape of this rubber band. The shape can only be set
- upon construction.
-*/
-QRubberBand::Shape QRubberBand::shape() const
-{
- Q_D(const QRubberBand);
- return d->shape;
-}
-
-/*!
- \internal
-*/
-void QRubberBandPrivate::updateMask()
-{
- Q_Q(QRubberBand);
- QStyleHintReturnMask mask;
- QStyleOptionRubberBand opt;
- q->initStyleOption(&opt);
- if (q->style()->styleHint(QStyle::SH_RubberBand_Mask, &opt, q, &mask)) {
- q->setMask(mask.region);
- } else {
- q->clearMask();
- }
-}
-
-/*!
- \reimp
-*/
-void QRubberBand::paintEvent(QPaintEvent *)
-{
- QStylePainter painter(this);
- QStyleOptionRubberBand option;
- initStyleOption(&option);
- painter.drawControl(QStyle::CE_RubberBand, option);
-}
-
-/*!
- \reimp
-*/
-void QRubberBand::changeEvent(QEvent *e)
-{
- QWidget::changeEvent(e);
- switch (e->type()) {
- case QEvent::ParentChange:
- if (parent()) {
- setWindowFlags(windowFlags() & ~RUBBERBAND_WINDOW_TYPE);
- } else {
- setWindowFlags(windowFlags() | RUBBERBAND_WINDOW_TYPE);
- }
- break;
- default:
- break;
- }
-
- if (e->type() == QEvent::ZOrderChange)
- raise();
-}
-
-/*!
- \reimp
-*/
-void QRubberBand::showEvent(QShowEvent *e)
-{
- raise();
- e->ignore();
-}
-
-/*!
- \reimp
-*/
-void QRubberBand::resizeEvent(QResizeEvent *)
-{
- Q_D(QRubberBand);
- d->updateMask();
-}
-
-/*!
- \reimp
-*/
-void QRubberBand::moveEvent(QMoveEvent *)
-{
- Q_D(QRubberBand);
- d->updateMask();
-}
-
-/*!
- \fn void QRubberBand::move(const QPoint &p);
-
- \overload
-
- Moves the rubberband to point \a p.
-
- \sa resize()
-*/
-
-/*!
- \fn void QRubberBand::move(int x, int y);
-
- Moves the rubberband to point (\a x, \a y).
-
- \sa resize()
-*/
-
-/*!
- \fn void QRubberBand::resize(const QSize &size);
-
- \overload
-
- Resizes the rubberband so that its new size is \a size.
-
- \sa move()
-*/
-
-/*!
- \fn void QRubberBand::resize(int width, int height);
-
- Resizes the rubberband so that its width is \a width, and its
- height is \a height.
-
- \sa move()
-*/
-
-/*!
- \fn void QRubberBand::setGeometry(const QRect &rect)
-
- Sets the geometry of the rubber band to \a rect, specified in the coordinate system
- of its parent widget.
-
- \sa QWidget::geometry
-*/
-void QRubberBand::setGeometry(const QRect &geom)
-{
- QWidget::setGeometry(geom);
-}
-
-/*!
- \fn void QRubberBand::setGeometry(int x, int y, int width, int height)
- \overload
-
- Sets the geometry of the rubberband to the rectangle whose top-left corner lies at
- the point (\a x, \a y), and with dimensions specified by \a width and \a height.
- The geometry is specified in the parent widget's coordinate system.
-*/
-
-/*! \reimp */
-bool QRubberBand::event(QEvent *e)
-{
- return QWidget::event(e);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_RUBBERBAND
diff --git a/src/gui/widgets/qrubberband.h b/src/gui/widgets/qrubberband.h
deleted file mode 100644
index 85fc17fc32..0000000000
--- a/src/gui/widgets/qrubberband.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** 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 QRUBBERBAND_H
-#define QRUBBERBAND_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_RUBBERBAND
-
-class QRubberBandPrivate;
-class QStyleOptionRubberBand;
-
-class Q_GUI_EXPORT QRubberBand : public QWidget
-{
- Q_OBJECT
-
-public:
- enum Shape { Line, Rectangle };
- explicit QRubberBand(Shape, QWidget * =0);
- ~QRubberBand();
-
- Shape shape() const;
-
- void setGeometry(const QRect &r);
-
- inline void setGeometry(int x, int y, int w, int h);
- inline void move(int x, int y);
- inline void move(const QPoint &p)
- { move(p.x(), p.y()); }
- inline void resize(int w, int h)
- { setGeometry(geometry().x(), geometry().y(), w, h); }
- inline void resize(const QSize &s)
- { resize(s.width(), s.height()); }
-
-protected:
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *);
- void changeEvent(QEvent *);
- void showEvent(QShowEvent *);
- void resizeEvent(QResizeEvent *);
- void moveEvent(QMoveEvent *);
- void initStyleOption(QStyleOptionRubberBand *option) const;
-
-private:
- Q_DECLARE_PRIVATE(QRubberBand)
-};
-
-inline void QRubberBand::setGeometry(int ax, int ay, int aw, int ah)
-{ setGeometry(QRect(ax, ay, aw, ah)); }
-inline void QRubberBand::move(int ax, int ay)
-{ setGeometry(ax, ay, width(), height()); }
-
-#endif // QT_NO_RUBBERBAND
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QRUBBERBAND_H
diff --git a/src/gui/widgets/qscrollarea.cpp b/src/gui/widgets/qscrollarea.cpp
deleted file mode 100644
index d33c3ac008..0000000000
--- a/src/gui/widgets/qscrollarea.cpp
+++ /dev/null
@@ -1,522 +0,0 @@
-/****************************************************************************
-**
-** 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 "qscrollarea.h"
-#include "private/qscrollarea_p.h"
-
-#ifndef QT_NO_SCROLLAREA
-
-#include "qscrollbar.h"
-#include "qlayout.h"
-#include "qstyle.h"
-#include "qapplication.h"
-#include "qvariant.h"
-#include "qdebug.h"
-#include "private/qlayoutengine_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QScrollArea
-
- \brief The QScrollArea class provides a scrolling view onto
- another widget.
-
- \ingroup basicwidgets
-
-
- A scroll area is used to display the contents of a child widget
- within a frame. If the widget exceeds the size of the frame, the
- view can provide scroll bars so that the entire area of the child
- widget can be viewed. The child widget must be specified with
- setWidget(). For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qscrollarea.cpp 0
-
- The code above creates a scroll area (shown in the images below)
- containing an image label. When scaling the image, the scroll area
- can provide the necessary scroll bars:
-
- \table
- \row
- \o \inlineimage qscrollarea-noscrollbars.png
- \o \inlineimage qscrollarea-onescrollbar.png
- \o \inlineimage qscrollarea-twoscrollbars.png
- \endtable
-
- The scroll bars appearance depends on the currently set \l
- {Qt::ScrollBarPolicy}{scroll bar policies}. You can control the
- appearance of the scroll bars using the inherited functionality
- from QAbstractScrollArea.
-
- For example, you can set the
- QAbstractScrollArea::horizontalScrollBarPolicy and
- QAbstractScrollArea::verticalScrollBarPolicy properties. Or if you
- want the scroll bars to adjust dynamically when the contents of
- the scroll area changes, you can use the \l
- {QAbstractScrollArea::horizontalScrollBar()}{horizontalScrollBar()}
- and \l
- {QAbstractScrollArea::verticalScrollBar()}{verticalScrollBar()}
- functions (which enable you to access the scroll bars) and set the
- scroll bars' values whenever the scroll area's contents change,
- using the QScrollBar::setValue() function.
-
- You can retrieve the child widget using the widget() function. The
- view can be made to be resizable with the setWidgetResizable()
- function. The alignment of the widget can be specified with
- setAlignment().
-
- Two convenience functions ensureVisible() and
- ensureWidgetVisible() ensure a certain region of the contents is
- visible inside the viewport, by scrolling the contents if
- necessary.
-
- \section1 Size Hints and Layouts
-
- When using a scroll area to display the contents of a custom
- widget, it is important to ensure that the
- \l{QWidget::sizeHint}{size hint} of the child widget is set to a
- suitable value. If a standard QWidget is used for the child
- widget, it may be necessary to call QWidget::setMinimumSize() to
- ensure that the contents of the widget are shown correctly within
- the scroll area.
-
- If a scroll area is used to display the contents of a widget that
- contains child widgets arranged in a layout, it is important to
- realize that the size policy of the layout will also determine the
- size of the widget. This is especially useful to know if you intend
- to dynamically change the contents of the layout. In such cases,
- setting the layout's \l{QLayout::sizeConstraint}{size constraint}
- property to one which provides constraints on the minimum and/or
- maximum size of the layout (e.g., QLayout::SetMinAndMaxSize) will
- cause the size of the scroll area to be updated whenever the
- contents of the layout changes.
-
- For a complete example using the QScrollArea class, see the \l
- {widgets/imageviewer}{Image Viewer} example. The example shows how
- to combine QLabel and QScrollArea to display an image.
-
- \sa QAbstractScrollArea, QScrollBar, {Image Viewer Example}
-*/
-
-
-/*!
- Constructs an empty scroll area with the given \a parent.
-
- \sa setWidget()
-*/
-QScrollArea::QScrollArea(QWidget *parent)
- : QAbstractScrollArea(*new QScrollAreaPrivate,parent)
-{
- Q_D(QScrollArea);
- d->viewport->setBackgroundRole(QPalette::NoRole);
- d->vbar->setSingleStep(20);
- d->hbar->setSingleStep(20);
- d->layoutChildren();
-}
-
-/*!
- \internal
-*/
-QScrollArea::QScrollArea(QScrollAreaPrivate &dd, QWidget *parent)
- : QAbstractScrollArea(dd, parent)
-{
- Q_D(QScrollArea);
- d->viewport->setBackgroundRole(QPalette::NoRole);
- d->vbar->setSingleStep(20);
- d->hbar->setSingleStep(20);
- d->layoutChildren();
-}
-
-/*!
- Destroys the scroll area and its child widget.
-
- \sa setWidget()
-*/
-QScrollArea::~QScrollArea()
-{
-}
-
-void QScrollAreaPrivate::updateWidgetPosition()
-{
- Q_Q(QScrollArea);
- Qt::LayoutDirection dir = q->layoutDirection();
- QRect scrolled = QStyle::visualRect(dir, viewport->rect(), QRect(QPoint(-hbar->value(), -vbar->value()), widget->size()));
- QRect aligned = QStyle::alignedRect(dir, alignment, widget->size(), viewport->rect());
- widget->move(widget->width() < viewport->width() ? aligned.x() : scrolled.x(),
- widget->height() < viewport->height() ? aligned.y() : scrolled.y());
-}
-
-void QScrollAreaPrivate::updateScrollBars()
-{
- Q_Q(QScrollArea);
- if (!widget)
- return;
- QSize p = viewport->size();
- QSize m = q->maximumViewportSize();
-
- QSize min = qSmartMinSize(widget);
- QSize max = qSmartMaxSize(widget);
-
- if (resizable) {
- if ((widget->layout() ? widget->layout()->hasHeightForWidth() : widget->sizePolicy().hasHeightForWidth())) {
- QSize p_hfw = p.expandedTo(min).boundedTo(max);
- int h = widget->heightForWidth( p_hfw.width() );
- min = QSize(p_hfw.width(), qMax(p_hfw.height(), h));
- }
- }
-
- if ((resizable && m.expandedTo(min) == m && m.boundedTo(max) == m)
- || (!resizable && m.expandedTo(widget->size()) == m))
- p = m; // no scroll bars needed
-
- if (resizable)
- widget->resize(p.expandedTo(min).boundedTo(max));
- QSize v = widget->size();
-
- hbar->setRange(0, v.width() - p.width());
- hbar->setPageStep(p.width());
- vbar->setRange(0, v.height() - p.height());
- vbar->setPageStep(p.height());
- updateWidgetPosition();
-
-}
-
-/*!
- Returns the scroll area's widget, or 0 if there is none.
-
- \sa setWidget()
-*/
-
-QWidget *QScrollArea::widget() const
-{
- Q_D(const QScrollArea);
- return d->widget;
-}
-
-/*!
- \fn void QScrollArea::setWidget(QWidget *widget)
-
- Sets the scroll area's \a widget.
-
- The \a widget becomes a child of the scroll area, and will be
- destroyed when the scroll area is deleted or when a new widget is
- set.
-
- The widget's \l{QWidget::setAutoFillBackground()}{autoFillBackground}
- property will be set to \c{true}.
-
- If the scroll area is visible when the \a widget is
- added, you must \l{QWidget::}{show()} it explicitly.
-
- Note that You must add the layout of \a widget before you call
- this function; if you add it later, the \a widget will not be
- visible - regardless of when you \l{QWidget::}{show()} the scroll
- area. In this case, you can also not \l{QWidget::}{show()} the \a
- widget later.
-
- \sa widget()
-*/
-void QScrollArea::setWidget(QWidget *widget)
-{
- Q_D(QScrollArea);
- if (widget == d->widget || !widget)
- return;
-
- delete d->widget;
- d->widget = 0;
- d->hbar->setValue(0);
- d->vbar->setValue(0);
- if (widget->parentWidget() != d->viewport)
- widget->setParent(d->viewport);
- if (!widget->testAttribute(Qt::WA_Resized))
- widget->resize(widget->sizeHint());
- d->widget = widget;
- d->widget->setAutoFillBackground(true);
- widget->installEventFilter(this);
- d->widgetSize = QSize();
- d->updateScrollBars();
- d->widget->show();
-
-}
-
-/*!
- Removes the scroll area's widget, and passes ownership of the
- widget to the caller.
-
- \sa widget()
- */
-QWidget *QScrollArea::takeWidget()
-{
- Q_D(QScrollArea);
- QWidget *w = d->widget;
- d->widget = 0;
- if (w)
- w->setParent(0);
- return w;
-}
-
-/*!
- \reimp
- */
-bool QScrollArea::event(QEvent *e)
-{
- Q_D(QScrollArea);
- if (e->type() == QEvent::StyleChange || e->type() == QEvent::LayoutRequest) {
- d->updateScrollBars();
- }
-#ifdef QT_KEYPAD_NAVIGATION
- else if (QApplication::keypadNavigationEnabled()) {
- if (e->type() == QEvent::Show)
- QApplication::instance()->installEventFilter(this);
- else if (e->type() == QEvent::Hide)
- QApplication::instance()->removeEventFilter(this);
- }
-#endif
- return QAbstractScrollArea::event(e);
-}
-
-
-/*!
- \reimp
- */
-bool QScrollArea::eventFilter(QObject *o, QEvent *e)
-{
- Q_D(QScrollArea);
-#ifdef QT_KEYPAD_NAVIGATION
- if (d->widget && o != d->widget && e->type() == QEvent::FocusIn
- && QApplication::keypadNavigationEnabled()) {
- if (o->isWidgetType())
- ensureWidgetVisible(static_cast<QWidget *>(o));
- }
-#endif
- if (o == d->widget && e->type() == QEvent::Resize)
- d->updateScrollBars();
-
- return false;
-}
-
-/*!
- \reimp
- */
-void QScrollArea::resizeEvent(QResizeEvent *)
-{
- Q_D(QScrollArea);
- d->updateScrollBars();
-
-}
-
-
-/*!\reimp
- */
-void QScrollArea::scrollContentsBy(int, int)
-{
- Q_D(QScrollArea);
- if (!d->widget)
- return;
- d->updateWidgetPosition();
-}
-
-
-/*!
- \property QScrollArea::widgetResizable
- \brief whether the scroll area should resize the view widget
-
- If this property is set to false (the default), the scroll area
- honors the size of its widget. Regardless of this property, you
- can programmatically resize the widget using widget()->resize(),
- and the scroll area will automatically adjust itself to the new
- size.
-
- If this property is set to true, the scroll area will
- automatically resize the widget in order to avoid scroll bars
- where they can be avoided, or to take advantage of extra space.
-*/
-bool QScrollArea::widgetResizable() const
-{
- Q_D(const QScrollArea);
- return d->resizable;
-}
-
-void QScrollArea::setWidgetResizable(bool resizable)
-{
- Q_D(QScrollArea);
- d->resizable = resizable;
- updateGeometry();
- d->updateScrollBars();
-}
-
-/*!
- \reimp
- */
-QSize QScrollArea::sizeHint() const
-{
- Q_D(const QScrollArea);
- int f = 2 * d->frameWidth;
- QSize sz(f, f);
- int h = fontMetrics().height();
- if (d->widget) {
- if (!d->widgetSize.isValid())
- d->widgetSize = d->resizable ? d->widget->sizeHint() : d->widget->size();
- sz += d->widgetSize;
- } else {
- sz += QSize(12 * h, 8 * h);
- }
- if (d->vbarpolicy == Qt::ScrollBarAlwaysOn)
- sz.setWidth(sz.width() + d->vbar->sizeHint().width());
- if (d->hbarpolicy == Qt::ScrollBarAlwaysOn)
- sz.setHeight(sz.height() + d->hbar->sizeHint().height());
- return sz.boundedTo(QSize(36 * h, 24 * h));
-}
-
-
-
-/*!
- \reimp
- */
-bool QScrollArea::focusNextPrevChild(bool next)
-{
- if (QWidget::focusNextPrevChild(next)) {
- if (QWidget *fw = focusWidget())
- ensureWidgetVisible(fw);
- return true;
- }
- return false;
-}
-
-/*!
- Scrolls the contents of the scroll area so that the point (\a x, \a y) is visible
- inside the region of the viewport with margins specified in pixels by \a xmargin and
- \a ymargin. If the specified point cannot be reached, the contents are scrolled to
- the nearest valid position. The default value for both margins is 50 pixels.
-*/
-void QScrollArea::ensureVisible(int x, int y, int xmargin, int ymargin)
-{
- Q_D(QScrollArea);
-
- int logicalX = QStyle::visualPos(layoutDirection(), d->viewport->rect(), QPoint(x, y)).x();
-
- if (logicalX - xmargin < d->hbar->value()) {
- d->hbar->setValue(qMax(0, logicalX - xmargin));
- } else if (logicalX > d->hbar->value() + d->viewport->width() - xmargin) {
- d->hbar->setValue(qMin(logicalX - d->viewport->width() + xmargin, d->hbar->maximum()));
- }
-
- if (y - ymargin < d->vbar->value()) {
- d->vbar->setValue(qMax(0, y - ymargin));
- } else if (y > d->vbar->value() + d->viewport->height() - ymargin) {
- d->vbar->setValue(qMin(y - d->viewport->height() + ymargin, d->vbar->maximum()));
- }
-}
-
-/*!
- \since 4.2
-
- Scrolls the contents of the scroll area so that the \a childWidget
- of QScrollArea::widget() is visible inside the viewport with
- margins specified in pixels by \a xmargin and \a ymargin. If the
- specified point cannot be reached, the contents are scrolled to
- the nearest valid position. The default value for both margins is
- 50 pixels.
-
-*/
-void QScrollArea::ensureWidgetVisible(QWidget *childWidget, int xmargin, int ymargin)
-{
- Q_D(QScrollArea);
-
- if (!d->widget->isAncestorOf(childWidget))
- return;
-
- const QRect microFocus = childWidget->inputMethodQuery(Qt::ImMicroFocus).toRect();
- const QRect defaultMicroFocus =
- childWidget->QWidget::inputMethodQuery(Qt::ImMicroFocus).toRect();
- QRect focusRect = (microFocus != defaultMicroFocus)
- ? QRect(childWidget->mapTo(d->widget, microFocus.topLeft()), microFocus.size())
- : QRect(childWidget->mapTo(d->widget, QPoint(0,0)), childWidget->size());
- const QRect visibleRect(-d->widget->pos(), d->viewport->size());
-
- if (visibleRect.contains(focusRect))
- return;
-
- focusRect.adjust(-xmargin, -ymargin, xmargin, ymargin);
-
- if (focusRect.width() > visibleRect.width())
- d->hbar->setValue(focusRect.center().x() - d->viewport->width() / 2);
- else if (focusRect.right() > visibleRect.right())
- d->hbar->setValue(focusRect.right() - d->viewport->width());
- else if (focusRect.left() < visibleRect.left())
- d->hbar->setValue(focusRect.left());
-
- if (focusRect.height() > visibleRect.height())
- d->vbar->setValue(focusRect.center().y() - d->viewport->height() / 2);
- else if (focusRect.bottom() > visibleRect.bottom())
- d->vbar->setValue(focusRect.bottom() - d->viewport->height());
- else if (focusRect.top() < visibleRect.top())
- d->vbar->setValue(focusRect.top());
-}
-
-
-/*!
- \property QScrollArea::alignment
- \brief the alignment of the scroll area's widget
- \since 4.2
-
- By default, the widget stays rooted to the top-left corner of the
- scroll area.
-*/
-
-void QScrollArea::setAlignment(Qt::Alignment alignment)
-{
- Q_D(QScrollArea);
- d->alignment = alignment;
- if (d->widget)
- d->updateWidgetPosition();
-}
-
-Qt::Alignment QScrollArea::alignment() const
-{
- Q_D(const QScrollArea);
- return d->alignment;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SCROLLAREA
diff --git a/src/gui/widgets/qscrollarea.h b/src/gui/widgets/qscrollarea.h
deleted file mode 100644
index 0c1ef8750c..0000000000
--- a/src/gui/widgets/qscrollarea.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLAREA_H
-#define QSCROLLAREA_H
-
-#include <QtGui/qabstractscrollarea.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SCROLLAREA
-
-class QScrollAreaPrivate;
-
-class Q_GUI_EXPORT QScrollArea : public QAbstractScrollArea
-{
- Q_OBJECT
- Q_PROPERTY(bool widgetResizable READ widgetResizable WRITE setWidgetResizable)
- Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment)
-
-public:
- explicit QScrollArea(QWidget* parent=0);
- ~QScrollArea();
-
- QWidget *widget() const;
- void setWidget(QWidget *widget);
- QWidget *takeWidget();
-
- bool widgetResizable() const;
- void setWidgetResizable(bool resizable);
-
- QSize sizeHint() const;
- bool focusNextPrevChild(bool next);
-
- Qt::Alignment alignment() const;
- void setAlignment(Qt::Alignment);
-
- void ensureVisible(int x, int y, int xmargin = 50, int ymargin = 50);
- void ensureWidgetVisible(QWidget *childWidget, int xmargin = 50, int ymargin = 50);
-
-protected:
- QScrollArea(QScrollAreaPrivate &dd, QWidget *parent = 0);
- bool event(QEvent *);
- bool eventFilter(QObject *, QEvent *);
- void resizeEvent(QResizeEvent *);
- void scrollContentsBy(int dx, int dy);
-
-private:
- Q_DECLARE_PRIVATE(QScrollArea)
- Q_DISABLE_COPY(QScrollArea)
-};
-
-#endif // QT_NO_SCROLLAREA
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSCROLLAREA_H
diff --git a/src/gui/widgets/qscrollarea_p.h b/src/gui/widgets/qscrollarea_p.h
deleted file mode 100644
index cff39ea452..0000000000
--- a/src/gui/widgets/qscrollarea_p.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLAREA_P_H
-#define QSCROLLAREA_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QT_NO_SCROLLAREA
-
-#include "private/qabstractscrollarea_p.h"
-#include <QtGui/qscrollbar.h>
-
-QT_BEGIN_NAMESPACE
-
-class QScrollAreaPrivate: public QAbstractScrollAreaPrivate
-{
- Q_DECLARE_PUBLIC(QScrollArea)
-
-public:
- QScrollAreaPrivate(): resizable(false), alignment(0){}
- void updateScrollBars();
- void updateWidgetPosition();
- QPointer<QWidget> widget;
- mutable QSize widgetSize;
- bool resizable;
- Qt::Alignment alignment;
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qscrollbar.cpp b/src/gui/widgets/qscrollbar.cpp
deleted file mode 100644
index 87738a0083..0000000000
--- a/src/gui/widgets/qscrollbar.cpp
+++ /dev/null
@@ -1,764 +0,0 @@
-/****************************************************************************
-**
-** 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 "qapplication.h"
-#include "qcursor.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qscrollbar.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qmenu.h"
-#include <QtCore/qelapsedtimer.h>
-
-#ifndef QT_NO_SCROLLBAR
-
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include <limits.h>
-#include "qabstractslider_p.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QScrollBar
- \brief The QScrollBar widget provides a vertical or horizontal scroll bar.
-
- \ingroup basicwidgets
-
- A scroll bar is a control that enables the user to access parts of a
- document that is larger than the widget used to display it. It provides
- a visual indication of the user's current position within the document
- and the amount of the document that is visible. Scroll bars are usually
- equipped with other controls that enable more accurate navigation.
- Qt displays scroll bars in a way that is appropriate for each platform.
-
- If you need to provide a scrolling view onto another widget, it may be
- more convenient to use the QScrollArea class because this provides a
- viewport widget and scroll bars. QScrollBar is useful if you need to
- implement similar functionality for specialized widgets using QAbstractScrollArea;
- for example, if you decide to subclass QAbstractItemView.
- For most other situations where a slider control is used to obtain a value
- within a given range, the QSlider class may be more appropriate for your
- needs.
-
- \table
- \row \o \image qscrollbar-picture.png
- \o Scroll bars typically include four separate controls: a slider,
- scroll arrows, and a page control.
-
- \list
- \o a. The slider provides a way to quickly go to any part of the
- document, but does not support accurate navigation within large
- documents.
- \o b. The scroll arrows are push buttons which can be used to accurately
- navigate to a particular place in a document. For a vertical scroll bar
- connected to a text editor, these typically move the current position one
- "line" up or down, and adjust the position of the slider by a small
- amount. In editors and list boxes a "line" might mean one line of text;
- in an image viewer it might mean 20 pixels.
- \o c. The page control is the area over which the slider is dragged (the
- scroll bar's background). Clicking here moves the scroll bar towards
- the click by one "page". This value is usually the same as the length of
- the slider.
- \endlist
- \endtable
-
- Each scroll bar has a value that indicates how far the slider is from
- the start of the scroll bar; this is obtained with value() and set
- with setValue(). This value always lies within the range of values
- defined for the scroll bar, from \l{QAbstractSlider::minimum()}{minimum()}
- to \l{QAbstractSlider::minimum()}{maximum()} inclusive. The range of
- acceptable values can be set with setMinimum() and setMaximum().
- At the minimum value, the top edge of the slider (for a vertical scroll
- bar) or left edge (for a horizontal scroll bar) will be at the top (or
- left) end of the scroll bar. At the maximum value, the bottom (or right)
- edge of the slider will be at the bottom (or right) end of the scroll bar.
-
- The length of the slider is usually related to the value of the page step,
- and typically represents the proportion of the document area shown in a
- scrolling view. The page step is the amount that the value changes by
- when the user presses the \key{Page Up} and \key{Page Down} keys, and is
- set with setPageStep(). Smaller changes to the value defined by the
- line step are made using the cursor keys, and this quantity is set with
- \l{QAbstractSlider::}{setSingleStep()}.
-
- Note that the range of values used is independent of the actual size
- of the scroll bar widget. You do not need to take this into account when
- you choose values for the range and the page step.
-
- The range of values specified for the scroll bar are often determined
- differently to those for a QSlider because the length of the slider
- needs to be taken into account. If we have a document with 100 lines,
- and we can only show 20 lines in a widget, we may wish to construct a
- scroll bar with a page step of 20, a minimum value of 0, and a maximum
- value of 80. This would give us a scroll bar with five "pages".
-
- \table
- \row \o \inlineimage qscrollbar-values.png
- \o The relationship between a document length, the range of values used
- in a scroll bar, and the page step is simple in many common situations.
- The scroll bar's range of values is determined by subtracting a
- chosen page step from some value representing the length of the document.
- In such cases, the following equation is useful:
- \e{document length} = maximum() - minimum() + pageStep().
- \endtable
-
- QScrollBar only provides integer ranges. Note that although
- QScrollBar handles very large numbers, scroll bars on current
- screens cannot usefully represent ranges above about 100,000 pixels.
- Beyond that, it becomes difficult for the user to control the
- slider using either the keyboard or the mouse, and the scroll
- arrows will have limited use.
-
- ScrollBar inherits a comprehensive set of signals from QAbstractSlider:
- \list
- \o \l{QAbstractSlider::valueChanged()}{valueChanged()} is emitted when the
- scroll bar's value has changed. The tracking() determines whether this
- signal is emitted during user interaction.
- \o \l{QAbstractSlider::rangeChanged()}{rangeChanged()} is emitted when the
- scroll bar's range of values has changed.
- \o \l{QAbstractSlider::sliderPressed()}{sliderPressed()} is emitted when
- the user starts to drag the slider.
- \o \l{QAbstractSlider::sliderMoved()}{sliderMoved()} is emitted when the user
- drags the slider.
- \o \l{QAbstractSlider::sliderReleased()}{sliderReleased()} is emitted when
- the user releases the slider.
- \o \l{QAbstractSlider::actionTriggered()}{actionTriggered()} is emitted
- when the scroll bar is changed by user interaction or via the
- \l{QAbstractSlider::triggerAction()}{triggerAction()} function.
- \endlist
-
- A scroll bar can be controlled by the keyboard, but it has a
- default focusPolicy() of Qt::NoFocus. Use setFocusPolicy() to
- enable keyboard interaction with the scroll bar:
- \list
- \o Left/Right move a horizontal scroll bar by one single step.
- \o Up/Down move a vertical scroll bar by one single step.
- \o PageUp moves up one page.
- \o PageDown moves down one page.
- \o Home moves to the start (mininum).
- \o End moves to the end (maximum).
- \endlist
-
- The slider itself can be controlled by using the
- \l{QAbstractSlider::triggerAction()}{triggerAction()} function to simulate
- user interaction with the scroll bar controls. This is useful if you have
- many different widgets that use a common range of values.
-
- Most GUI styles use the pageStep() value to calculate the size of the
- slider.
-
- \table 100%
- \row \o \inlineimage macintosh-horizontalscrollbar.png Screenshot of a Macintosh style scroll bar
- \o A scroll bar shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row \o \inlineimage windowsxp-horizontalscrollbar.png Screenshot of a Windows XP style scroll bar
- \o A scroll bar shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage plastique-horizontalscrollbar.png Screenshot of a Plastique style scroll bar
- \o A scroll bar shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QScrollArea, QSlider, QDial, QSpinBox, {fowler}{GUI Design Handbook: Scroll Bar}, {Sliders Example}
-*/
-
-class QScrollBarPrivate : public QAbstractSliderPrivate
-{
- Q_DECLARE_PUBLIC(QScrollBar)
-public:
- QStyle::SubControl pressedControl;
- bool pointerOutsidePressedControl;
-
- int clickOffset, snapBackPosition;
-
- void activateControl(uint control, int threshold = 500);
- void stopRepeatAction();
- int pixelPosToRangeValue(int pos) const;
- void init();
- bool updateHoverControl(const QPoint &pos);
- QStyle::SubControl newHoverControl(const QPoint &pos);
-
- QStyle::SubControl hoverControl;
- QRect hoverRect;
-};
-
-bool QScrollBarPrivate::updateHoverControl(const QPoint &pos)
-{
- Q_Q(QScrollBar);
- QRect lastHoverRect = hoverRect;
- QStyle::SubControl lastHoverControl = hoverControl;
- bool doesHover = q->testAttribute(Qt::WA_Hover);
- if (lastHoverControl != newHoverControl(pos) && doesHover) {
- q->update(lastHoverRect);
- q->update(hoverRect);
- return true;
- }
- return !doesHover;
-}
-
-QStyle::SubControl QScrollBarPrivate::newHoverControl(const QPoint &pos)
-{
- Q_Q(QScrollBar);
- QStyleOptionSlider opt;
- q->initStyleOption(&opt);
- opt.subControls = QStyle::SC_All;
- hoverControl = q->style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, pos, q);
- if (hoverControl == QStyle::SC_None)
- hoverRect = QRect();
- else
- hoverRect = q->style()->subControlRect(QStyle::CC_ScrollBar, &opt, hoverControl, q);
- return hoverControl;
-}
-
-void QScrollBarPrivate::activateControl(uint control, int threshold)
-{
- QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction;
- switch (control) {
- case QStyle::SC_ScrollBarAddPage:
- action = QAbstractSlider::SliderPageStepAdd;
- break;
- case QStyle::SC_ScrollBarSubPage:
- action = QAbstractSlider::SliderPageStepSub;
- break;
- case QStyle::SC_ScrollBarAddLine:
- action = QAbstractSlider::SliderSingleStepAdd;
- break;
- case QStyle::SC_ScrollBarSubLine:
- action = QAbstractSlider::SliderSingleStepSub;
- break;
- case QStyle::SC_ScrollBarFirst:
- action = QAbstractSlider::SliderToMinimum;
- break;
- case QStyle::SC_ScrollBarLast:
- action = QAbstractSlider::SliderToMaximum;
- break;
- default:
- break;
- }
-
- if (action) {
- q_func()->setRepeatAction(action, threshold);
- q_func()->triggerAction(action);
- }
-}
-
-void QScrollBarPrivate::stopRepeatAction()
-{
- Q_Q(QScrollBar);
- QStyle::SubControl tmp = pressedControl;
- q->setRepeatAction(QAbstractSlider::SliderNoAction);
- pressedControl = QStyle::SC_None;
-
- if (tmp == QStyle::SC_ScrollBarSlider)
- q->setSliderDown(false);
-
- QStyleOptionSlider opt;
- q->initStyleOption(&opt);
- q->repaint(q->style()->subControlRect(QStyle::CC_ScrollBar, &opt, tmp, q));
-}
-
-/*!
- Initialize \a option with the values from this QScrollBar. This method
- is useful for subclasses when they need a QStyleOptionSlider, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QScrollBar::initStyleOption(QStyleOptionSlider *option) const
-{
- if (!option)
- return;
-
- Q_D(const QScrollBar);
- option->initFrom(this);
- option->subControls = QStyle::SC_None;
- option->activeSubControls = QStyle::SC_None;
- option->orientation = d->orientation;
- option->minimum = d->minimum;
- option->maximum = d->maximum;
- option->sliderPosition = d->position;
- option->sliderValue = d->value;
- option->singleStep = d->singleStep;
- option->pageStep = d->pageStep;
- option->upsideDown = d->invertedAppearance;
- if (d->orientation == Qt::Horizontal)
- option->state |= QStyle::State_Horizontal;
-}
-
-
-#define HORIZONTAL (d_func()->orientation == Qt::Horizontal)
-#define VERTICAL !HORIZONTAL
-
-/*!
- Constructs a vertical scroll bar.
-
- The \a parent argument is sent to the QWidget constructor.
-
- The \l {QAbstractSlider::minimum} {minimum} defaults to 0, the
- \l {QAbstractSlider::maximum} {maximum} to 99, with a
- \l {QAbstractSlider::singleStep} {singleStep} size of 1 and a
- \l {QAbstractSlider::pageStep} {pageStep} size of 10, and an
- initial \l {QAbstractSlider::value} {value} of 0.
-*/
-QScrollBar::QScrollBar(QWidget *parent)
- : QAbstractSlider(*new QScrollBarPrivate, parent)
-{
- d_func()->orientation = Qt::Vertical;
- d_func()->init();
-}
-
-/*!
- Constructs a scroll bar with the given \a orientation.
-
- The \a parent argument is passed to the QWidget constructor.
-
- The \l {QAbstractSlider::minimum} {minimum} defaults to 0, the
- \l {QAbstractSlider::maximum} {maximum} to 99, with a
- \l {QAbstractSlider::singleStep} {singleStep} size of 1 and a
- \l {QAbstractSlider::pageStep} {pageStep} size of 10, and an
- initial \l {QAbstractSlider::value} {value} of 0.
-*/
-QScrollBar::QScrollBar(Qt::Orientation orientation, QWidget *parent)
- : QAbstractSlider(*new QScrollBarPrivate, parent)
-{
- d_func()->orientation = orientation;
- d_func()->init();
-}
-
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QScrollBar::QScrollBar(QWidget *parent, const char *name)
- : QAbstractSlider(*new QScrollBarPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- d_func()->orientation = Qt::Vertical;
- d_func()->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QScrollBar::QScrollBar(Qt::Orientation orientation, QWidget *parent, const char *name)
- : QAbstractSlider(*new QScrollBarPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- d_func()->orientation = orientation;
- d_func()->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QScrollBar::QScrollBar(int minimum, int maximum, int lineStep, int pageStep,
- int value, Qt::Orientation orientation,
- QWidget *parent, const char *name)
- : QAbstractSlider(*new QScrollBarPrivate, parent)
-{
- Q_D(QScrollBar);
- setObjectName(QString::fromAscii(name));
- d->minimum = minimum;
- d->maximum = maximum;
- d->singleStep = lineStep;
- d->pageStep = pageStep;
- d->value = value;
- d->orientation = orientation;
- d->init();
-}
-#endif // QT3_SUPPORT
-
-/*!
- Destroys the scroll bar.
-*/
-QScrollBar::~QScrollBar()
-{
-}
-
-void QScrollBarPrivate::init()
-{
- Q_Q(QScrollBar);
- invertedControls = true;
- pressedControl = hoverControl = QStyle::SC_None;
- pointerOutsidePressedControl = false;
- q->setFocusPolicy(Qt::NoFocus);
- QSizePolicy sp(QSizePolicy::Minimum, QSizePolicy::Fixed, QSizePolicy::Slider);
- if (orientation == Qt::Vertical)
- sp.transpose();
- q->setSizePolicy(sp);
- q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- q->setAttribute(Qt::WA_OpaquePaintEvent);
-
-#if !defined(QT_NO_CONTEXTMENU) && defined(Q_WS_WINCE)
- if (!q->style()->styleHint(QStyle::SH_ScrollBar_ContextMenu, 0, q)) {
- q->setContextMenuPolicy(Qt::PreventContextMenu);
- }
-#endif
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*! \reimp */
-void QScrollBar::contextMenuEvent(QContextMenuEvent *event)
-{
- if (!style()->styleHint(QStyle::SH_ScrollBar_ContextMenu, 0, this)) {
- QAbstractSlider::contextMenuEvent(event);
- return ;
- }
-
-#ifndef QT_NO_MENU
- bool horiz = HORIZONTAL;
- QPointer<QMenu> menu = new QMenu(this);
- QAction *actScrollHere = menu->addAction(tr("Scroll here"));
- menu->addSeparator();
- QAction *actScrollTop = menu->addAction(horiz ? tr("Left edge") : tr("Top"));
- QAction *actScrollBottom = menu->addAction(horiz ? tr("Right edge") : tr("Bottom"));
- menu->addSeparator();
- QAction *actPageUp = menu->addAction(horiz ? tr("Page left") : tr("Page up"));
- QAction *actPageDn = menu->addAction(horiz ? tr("Page right") : tr("Page down"));
- menu->addSeparator();
- QAction *actScrollUp = menu->addAction(horiz ? tr("Scroll left") : tr("Scroll up"));
- QAction *actScrollDn = menu->addAction(horiz ? tr("Scroll right") : tr("Scroll down"));
- QAction *actionSelected = menu->exec(event->globalPos());
- delete menu;
- if (actionSelected == 0)
- /* do nothing */ ;
- else if (actionSelected == actScrollHere)
- setValue(d_func()->pixelPosToRangeValue(horiz ? event->pos().x() : event->pos().y()));
- else if (actionSelected == actScrollTop)
- triggerAction(QAbstractSlider::SliderToMinimum);
- else if (actionSelected == actScrollBottom)
- triggerAction(QAbstractSlider::SliderToMaximum);
- else if (actionSelected == actPageUp)
- triggerAction(QAbstractSlider::SliderPageStepSub);
- else if (actionSelected == actPageDn)
- triggerAction(QAbstractSlider::SliderPageStepAdd);
- else if (actionSelected == actScrollUp)
- triggerAction(QAbstractSlider::SliderSingleStepSub);
- else if (actionSelected == actScrollDn)
- triggerAction(QAbstractSlider::SliderSingleStepAdd);
-#endif // QT_NO_MENU
-}
-#endif // QT_NO_CONTEXTMENU
-
-
-/*! \reimp */
-QSize QScrollBar::sizeHint() const
-{
- ensurePolished();
- QStyleOptionSlider opt;
- initStyleOption(&opt);
-
- int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent, &opt, this);
- int scrollBarSliderMin = style()->pixelMetric(QStyle::PM_ScrollBarSliderMin, &opt, this);
- QSize size;
- if (opt.orientation == Qt::Horizontal)
- size = QSize(scrollBarExtent * 2 + scrollBarSliderMin, scrollBarExtent);
- else
- size = QSize(scrollBarExtent, scrollBarExtent * 2 + scrollBarSliderMin);
-
- return style()->sizeFromContents(QStyle::CT_ScrollBar, &opt, size, this)
- .expandedTo(QApplication::globalStrut());
- }
-
-/*!\reimp */
-void QScrollBar::sliderChange(SliderChange change)
-{
- QAbstractSlider::sliderChange(change);
-}
-
-/*!
- \reimp
-*/
-bool QScrollBar::event(QEvent *event)
-{
- switch(event->type()) {
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d_func()->updateHoverControl(he->pos());
- break;
-#ifndef QT_NO_WHEELEVENT
- case QEvent::Wheel: {
- event->ignore();
- // override wheel event without adding virtual function override
- QWheelEvent *ev = static_cast<QWheelEvent *>(event);
- int delta = ev->delta();
- // scrollbar is a special case - in vertical mode it reaches minimum
- // value in the upper position, however QSlider's minimum value is on
- // the bottom. So we need to invert a value, but since the scrollbar is
- // inverted by default, we need to inverse the delta value for the
- // horizontal orientation.
- if (ev->orientation() == Qt::Horizontal)
- delta = -delta;
- Q_D(QScrollBar);
- if (d->scrollByDelta(ev->orientation(), ev->modifiers(), delta))
- event->accept();
- return true;
- }
-#endif
- default:
- break;
- }
- return QAbstractSlider::event(event);
-}
-
-/*!
- \reimp
-*/
-void QScrollBar::paintEvent(QPaintEvent *)
-{
- Q_D(QScrollBar);
- QPainter p(this);
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- opt.subControls = QStyle::SC_All;
- if (d->pressedControl) {
- opt.activeSubControls = (QStyle::SubControl)d->pressedControl;
- if (!d->pointerOutsidePressedControl)
- opt.state |= QStyle::State_Sunken;
- } else {
- opt.activeSubControls = (QStyle::SubControl)d->hoverControl;
- }
- style()->drawComplexControl(QStyle::CC_ScrollBar, &opt, &p, this);
-}
-
-/*!
- \reimp
-*/
-void QScrollBar::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QScrollBar);
-
- if (d->repeatActionTimer.isActive())
- d->stopRepeatAction();
-
- bool midButtonAbsPos = style()->styleHint(QStyle::SH_ScrollBar_MiddleClickAbsolutePosition,
- 0, this);
- QStyleOptionSlider opt;
- initStyleOption(&opt);
-
- if (d->maximum == d->minimum // no range
- || (e->buttons() & (~e->button())) // another button was clicked before
- || !(e->button() == Qt::LeftButton || (midButtonAbsPos && e->button() == Qt::MidButton)))
- return;
-
- d->pressedControl = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->pos(), this);
- d->pointerOutsidePressedControl = false;
-
- QRect sr = style()->subControlRect(QStyle::CC_ScrollBar, &opt,
- QStyle::SC_ScrollBarSlider, this);
- QPoint click = e->pos();
- QPoint pressValue = click - sr.center() + sr.topLeft();
- d->pressValue = d->orientation == Qt::Horizontal ? d->pixelPosToRangeValue(pressValue.x()) :
- d->pixelPosToRangeValue(pressValue.y());
- if (d->pressedControl == QStyle::SC_ScrollBarSlider) {
- d->clickOffset = HORIZONTAL ? (click.x()-sr.x()) : (click.y()-sr.y());
- d->snapBackPosition = d->position;
- }
-
- if ((d->pressedControl == QStyle::SC_ScrollBarAddPage
- || d->pressedControl == QStyle::SC_ScrollBarSubPage)
- && ((midButtonAbsPos && e->button() == Qt::MidButton)
- || (style()->styleHint(QStyle::SH_ScrollBar_LeftClickAbsolutePosition, &opt, this)
- && e->button() == Qt::LeftButton))) {
- int sliderLength = HORIZONTAL ? sr.width() : sr.height();
- setSliderPosition(d->pixelPosToRangeValue((HORIZONTAL ? e->pos().x()
- : e->pos().y()) - sliderLength / 2));
- d->pressedControl = QStyle::SC_ScrollBarSlider;
- d->clickOffset = sliderLength / 2;
- }
- const int initialDelay = 500; // default threshold
- d->activateControl(d->pressedControl, initialDelay);
- QElapsedTimer time;
- time.start();
- repaint(style()->subControlRect(QStyle::CC_ScrollBar, &opt, d->pressedControl, this));
- if (time.elapsed() >= initialDelay && d->repeatActionTimer.isActive()) {
- // It took more than 500ms (the initial timer delay) to process the repaint(), we
- // therefore need to restart the timer in case we have a pending mouse release event;
- // otherwise we'll get a timer event right before the release event,
- // causing the repeat action to be invoked twice on a single mouse click.
- // 50ms is the default repeat time (see activateControl/setRepeatAction).
- d->repeatActionTimer.start(50, this);
- }
- if (d->pressedControl == QStyle::SC_ScrollBarSlider)
- setSliderDown(true);
-}
-
-
-/*!
- \reimp
-*/
-void QScrollBar::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QScrollBar);
- if (!d->pressedControl)
- return;
-
- if (e->buttons() & (~e->button())) // some other button is still pressed
- return;
-
- d->stopRepeatAction();
-}
-
-
-/*!
- \reimp
-*/
-void QScrollBar::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QScrollBar);
- if (!d->pressedControl)
- return;
-
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- if (!(e->buttons() & Qt::LeftButton
- || ((e->buttons() & Qt::MidButton)
- && style()->styleHint(QStyle::SH_ScrollBar_MiddleClickAbsolutePosition, &opt, this))))
- return;
-
- if (d->pressedControl == QStyle::SC_ScrollBarSlider) {
- QPoint click = e->pos();
- int newPosition = d->pixelPosToRangeValue((HORIZONTAL ? click.x() : click.y()) -d->clickOffset);
- int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &opt, this);
- if (m >= 0) {
- QRect r = rect();
- r.adjust(-m, -m, m, m);
- if (! r.contains(e->pos()))
- newPosition = d->snapBackPosition;
- }
- setSliderPosition(newPosition);
- } else if (!style()->styleHint(QStyle::SH_ScrollBar_ScrollWhenPointerLeavesControl, &opt, this)) {
-
- if (style()->styleHint(QStyle::SH_ScrollBar_RollBetweenButtons, &opt, this)
- && d->pressedControl & (QStyle::SC_ScrollBarAddLine | QStyle::SC_ScrollBarSubLine)) {
- QStyle::SubControl newSc = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->pos(), this);
- if (newSc == d->pressedControl && !d->pointerOutsidePressedControl)
- return; // nothing to do
- if (newSc & (QStyle::SC_ScrollBarAddLine | QStyle::SC_ScrollBarSubLine)) {
- d->pointerOutsidePressedControl = false;
- QRect scRect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, newSc, this);
- scRect |= style()->subControlRect(QStyle::CC_ScrollBar, &opt, d->pressedControl, this);
- d->pressedControl = newSc;
- d->activateControl(d->pressedControl, 0);
- update(scRect);
- return;
- }
- }
-
- // stop scrolling when the mouse pointer leaves a control
- // similar to push buttons
- QRect pr = style()->subControlRect(QStyle::CC_ScrollBar, &opt, d->pressedControl, this);
- if (pr.contains(e->pos()) == d->pointerOutsidePressedControl) {
- if ((d->pointerOutsidePressedControl = !d->pointerOutsidePressedControl)) {
- d->pointerOutsidePressedControl = true;
- setRepeatAction(SliderNoAction);
- repaint(pr);
- } else {
- d->activateControl(d->pressedControl);
- }
- }
- }
-}
-
-
-int QScrollBarPrivate::pixelPosToRangeValue(int pos) const
-{
- Q_Q(const QScrollBar);
- QStyleOptionSlider opt;
- q->initStyleOption(&opt);
- QRect gr = q->style()->subControlRect(QStyle::CC_ScrollBar, &opt,
- QStyle::SC_ScrollBarGroove, q);
- QRect sr = q->style()->subControlRect(QStyle::CC_ScrollBar, &opt,
- QStyle::SC_ScrollBarSlider, q);
- int sliderMin, sliderMax, sliderLength;
-
- if (orientation == Qt::Horizontal) {
- sliderLength = sr.width();
- sliderMin = gr.x();
- sliderMax = gr.right() - sliderLength + 1;
- if (q->layoutDirection() == Qt::RightToLeft)
- opt.upsideDown = !opt.upsideDown;
- } else {
- sliderLength = sr.height();
- sliderMin = gr.y();
- sliderMax = gr.bottom() - sliderLength + 1;
- }
-
- return QStyle::sliderValueFromPosition(minimum, maximum, pos - sliderMin,
- sliderMax - sliderMin, opt.upsideDown);
-}
-
-/*! \reimp
-*/
-void QScrollBar::hideEvent(QHideEvent *)
-{
- Q_D(QScrollBar);
- if (d->pressedControl) {
- d->pressedControl = QStyle::SC_None;
- setRepeatAction(SliderNoAction);
- }
-}
-
-/*!
- \fn bool QScrollBar::draggingSlider()
-
- Use isSliderDown() instead.
-*/
-
-/*! \internal
- Returns the style option for scroll bar.
-*/
-Q_GUI_EXPORT QStyleOptionSlider qt_qscrollbarStyleOption(QScrollBar *scrollbar)
-{
- QStyleOptionSlider opt;
- scrollbar->initStyleOption(&opt);
- return opt;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SCROLLBAR
diff --git a/src/gui/widgets/qscrollbar.h b/src/gui/widgets/qscrollbar.h
deleted file mode 100644
index e407f575f5..0000000000
--- a/src/gui/widgets/qscrollbar.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** 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 QSCROLLBAR_H
-#define QSCROLLBAR_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qabstractslider.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SCROLLBAR
-
-class QScrollBarPrivate;
-class QStyleOptionSlider;
-
-class Q_GUI_EXPORT QScrollBar : public QAbstractSlider
-{
- Q_OBJECT
-public:
- explicit QScrollBar(QWidget *parent=0);
- explicit QScrollBar(Qt::Orientation, QWidget *parent=0);
- ~QScrollBar();
-
- QSize sizeHint() const;
- bool event(QEvent *event);
-
-protected:
- void paintEvent(QPaintEvent *);
- void mousePressEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void hideEvent(QHideEvent*);
- void sliderChange(SliderChange change);
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *);
-#endif
- void initStyleOption(QStyleOptionSlider *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QScrollBar(QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QScrollBar(Qt::Orientation, QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QScrollBar(int minValue, int maxValue, int lineStep, int pageStep,
- int value, Qt::Orientation, QWidget *parent=0, const char* name = 0);
- inline QT3_SUPPORT bool draggingSlider() { return isSliderDown(); }
-#endif
-
-private:
- friend Q_GUI_EXPORT QStyleOptionSlider qt_qscrollbarStyleOption(QScrollBar *scrollBar);
-
- Q_DISABLE_COPY(QScrollBar)
- Q_DECLARE_PRIVATE(QScrollBar)
-};
-
-#endif // QT_NO_SCROLLBAR
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSCROLLBAR_H
diff --git a/src/gui/widgets/qsizegrip.cpp b/src/gui/widgets/qsizegrip.cpp
deleted file mode 100644
index 630aecfc09..0000000000
--- a/src/gui/widgets/qsizegrip.cpp
+++ /dev/null
@@ -1,570 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsizegrip.h"
-
-#ifndef QT_NO_SIZEGRIP
-
-#include "qapplication.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qlayout.h"
-#include "qdebug.h"
-#include <QDesktopWidget>
-
-#if defined(Q_WS_X11)
-#include <private/qt_x11_p.h>
-#elif defined (Q_WS_WIN)
-#include "qt_windows.h"
-#endif
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#endif
-
-#include <private/qwidget_p.h>
-#include <QtGui/qabstractscrollarea.h>
-
-#define SZ_SIZEBOTTOMRIGHT 0xf008
-#define SZ_SIZEBOTTOMLEFT 0xf007
-#define SZ_SIZETOPLEFT 0xf004
-#define SZ_SIZETOPRIGHT 0xf005
-
-QT_BEGIN_NAMESPACE
-
-static QWidget *qt_sizegrip_topLevelWidget(QWidget* w)
-{
- while (w && !w->isWindow() && w->windowType() != Qt::SubWindow)
- w = w->parentWidget();
- return w;
-}
-
-class QSizeGripPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QSizeGrip)
-public:
- void init();
- QPoint p;
- QRect r;
- int d;
- int dxMax;
- int dyMax;
- Qt::Corner m_corner;
- bool gotMousePress;
- QWidget *tlw;
-#ifdef Q_WS_MAC
- void updateMacSizer(bool hide) const;
-#endif
- Qt::Corner corner() const;
- inline bool atBottom() const
- {
- return m_corner == Qt::BottomRightCorner || m_corner == Qt::BottomLeftCorner;
- }
-
- inline bool atLeft() const
- {
- return m_corner == Qt::BottomLeftCorner || m_corner == Qt::TopLeftCorner;
- }
-
- void updateTopLevelWidget()
- {
- Q_Q(QSizeGrip);
- QWidget *w = qt_sizegrip_topLevelWidget(q);
- if (tlw == w)
- return;
- if (tlw)
- tlw->removeEventFilter(q);
- tlw = w;
- if (tlw)
- tlw->installEventFilter(q);
- }
-
- // This slot is invoked by QLayout when the size grip is added to
- // a layout or reparented after the tlw is shown. This re-implementation is basically
- // the same as QWidgetPrivate::_q_showIfNotHidden except that it checks
- // for Qt::WindowFullScreen and Qt::WindowMaximized as well.
- void _q_showIfNotHidden()
- {
- Q_Q(QSizeGrip);
- bool showSizeGrip = !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide));
- updateTopLevelWidget();
- if (tlw && showSizeGrip) {
- Qt::WindowStates sizeGripNotVisibleState = Qt::WindowFullScreen;
-#ifndef Q_WS_MAC
- sizeGripNotVisibleState |= Qt::WindowMaximized;
-#endif
- // Don't show the size grip if the tlw is maximized or in full screen mode.
- showSizeGrip = !(tlw->windowState() & sizeGripNotVisibleState);
- }
- if (showSizeGrip)
- q->setVisible(true);
- }
-};
-
-#ifdef Q_WS_MAC
-void QSizeGripPrivate::updateMacSizer(bool hide) const
-{
- Q_Q(const QSizeGrip);
- if (QApplication::closingDown() || !parent)
- return;
- QWidget *topLevelWindow = qt_sizegrip_topLevelWidget(const_cast<QSizeGrip *>(q));
- if(topLevelWindow && topLevelWindow->isWindow())
- QWidgetPrivate::qt_mac_update_sizer(topLevelWindow, hide ? -1 : 1);
-}
-#endif
-
-Qt::Corner QSizeGripPrivate::corner() const
-{
- Q_Q(const QSizeGrip);
- QWidget *tlw = qt_sizegrip_topLevelWidget(const_cast<QSizeGrip *>(q));
- const QPoint sizeGripPos = q->mapTo(tlw, QPoint(0, 0));
- bool isAtBottom = sizeGripPos.y() >= tlw->height() / 2;
- bool isAtLeft = sizeGripPos.x() <= tlw->width() / 2;
- if (isAtLeft)
- return isAtBottom ? Qt::BottomLeftCorner : Qt::TopLeftCorner;
- else
- return isAtBottom ? Qt::BottomRightCorner : Qt::TopRightCorner;
-}
-
-/*!
- \class QSizeGrip
-
- \brief The QSizeGrip class provides a resize handle for resizing top-level windows.
-
- \ingroup mainwindow-classes
- \ingroup basicwidgets
-
- This widget works like the standard Windows resize handle. In the
- X11 version this resize handle generally works differently from
- the one provided by the system if the X11 window manager does not
- support necessary modern post-ICCCM specifications.
-
- Put this widget anywhere in a widget tree and the user can use it
- to resize the top-level window or any widget with the Qt::SubWindow
- flag set. Generally, this should be in the lower right-hand corner.
- Note that QStatusBar already uses this widget, so if you have a
- status bar (e.g., you are using QMainWindow), then you don't need
- to use this widget explicitly.
-
- On some platforms the size grip automatically hides itself when the
- window is shown full screen or maximised.
-
- \table 50%
- \row \o \inlineimage plastique-sizegrip.png Screenshot of a Plastique style size grip
- \o A size grip widget at the bottom-right corner of a main window, shown in the
- \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- The QSizeGrip class inherits QWidget and reimplements the \l
- {QWidget::mousePressEvent()}{mousePressEvent()} and \l
- {QWidget::mouseMoveEvent()}{mouseMoveEvent()} functions to feature
- the resize functionality, and the \l
- {QWidget::paintEvent()}{paintEvent()} function to render the
- size grip widget.
-
- \sa QStatusBar QWidget::windowState()
-*/
-
-
-/*!
- Constructs a resize corner as a child widget of the given \a
- parent.
-*/
-QSizeGrip::QSizeGrip(QWidget * parent)
- : QWidget(*new QSizeGripPrivate, parent, 0)
-{
- Q_D(QSizeGrip);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \obsolete
-
- Constructs a resize corner with the given \a name, as a child
- widget of the given \a parent.
-*/
-QSizeGrip::QSizeGrip(QWidget * parent, const char* name)
- : QWidget(*new QSizeGripPrivate, parent, 0)
-{
- Q_D(QSizeGrip);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-#endif
-
-void QSizeGripPrivate::init()
-{
- Q_Q(QSizeGrip);
- dxMax = 0;
- dyMax = 0;
- tlw = 0;
- m_corner = q->isLeftToRight() ? Qt::BottomRightCorner : Qt::BottomLeftCorner;
- gotMousePress = false;
-
-#if !defined(QT_NO_CURSOR) && !defined(Q_WS_MAC)
- q->setCursor(m_corner == Qt::TopLeftCorner || m_corner == Qt::BottomRightCorner
- ? Qt::SizeFDiagCursor : Qt::SizeBDiagCursor);
-#endif
- q->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed));
- updateTopLevelWidget();
-}
-
-
-/*!
- Destroys this size grip.
-*/
-QSizeGrip::~QSizeGrip()
-{
-}
-
-/*!
- \reimp
-*/
-QSize QSizeGrip::sizeHint() const
-{
- QStyleOption opt(0);
- opt.init(this);
- return (style()->sizeFromContents(QStyle::CT_SizeGrip, &opt, QSize(13, 13), this).
- expandedTo(QApplication::globalStrut()));
-}
-
-/*!
- Paints the resize grip.
-
- Resize grips are usually rendered as small diagonal textured lines
- in the lower-right corner. The paint event is passed in the \a
- event parameter.
-*/
-void QSizeGrip::paintEvent(QPaintEvent *event)
-{
- Q_UNUSED(event);
- Q_D(QSizeGrip);
- QPainter painter(this);
- QStyleOptionSizeGrip opt;
- opt.init(this);
- opt.corner = d->m_corner;
- style()->drawControl(QStyle::CE_SizeGrip, &opt, &painter, this);
-}
-
-/*!
- \fn void QSizeGrip::mousePressEvent(QMouseEvent * event)
-
- Receives the mouse press events for the widget, and primes the
- resize operation. The mouse press event is passed in the \a event
- parameter.
-*/
-void QSizeGrip::mousePressEvent(QMouseEvent * e)
-{
- if (e->button() != Qt::LeftButton) {
- QWidget::mousePressEvent(e);
- return;
- }
-
- Q_D(QSizeGrip);
- QWidget *tlw = qt_sizegrip_topLevelWidget(this);
- d->p = e->globalPos();
- d->gotMousePress = true;
- d->r = tlw->geometry();
-
-#ifdef Q_WS_X11
- // Use a native X11 sizegrip for "real" top-level windows if supported.
- if (tlw->isWindow() && X11->isSupportedByWM(ATOM(_NET_WM_MOVERESIZE))
- && !(tlw->windowFlags() & Qt::X11BypassWindowManagerHint)
- && !tlw->testAttribute(Qt::WA_DontShowOnScreen) && !qt_widget_private(tlw)->hasHeightForWidth()) {
- XEvent xev;
- xev.xclient.type = ClientMessage;
- xev.xclient.message_type = ATOM(_NET_WM_MOVERESIZE);
- xev.xclient.display = X11->display;
- xev.xclient.window = tlw->winId();
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = e->globalPos().x();
- xev.xclient.data.l[1] = e->globalPos().y();
- if (d->atBottom())
- xev.xclient.data.l[2] = d->atLeft() ? 6 : 4; // bottomleft/bottomright
- else
- xev.xclient.data.l[2] = d->atLeft() ? 0 : 2; // topleft/topright
- xev.xclient.data.l[3] = Button1;
- xev.xclient.data.l[4] = 0;
- XUngrabPointer(X11->display, X11->time);
- XSendEvent(X11->display, QX11Info::appRootWindow(x11Info().screen()), False,
- SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- return;
- }
-#endif // Q_WS_X11
-#ifdef Q_WS_WIN
- if (tlw->isWindow() && !tlw->testAttribute(Qt::WA_DontShowOnScreen) && !qt_widget_private(tlw)->hasHeightForWidth()) {
- uint orientation = 0;
- if (d->atBottom())
- orientation = d->atLeft() ? SZ_SIZEBOTTOMLEFT : SZ_SIZEBOTTOMRIGHT;
- else
- orientation = d->atLeft() ? SZ_SIZETOPLEFT : SZ_SIZETOPRIGHT;
-
- ReleaseCapture();
- PostMessage(tlw->winId(), WM_SYSCOMMAND, orientation, 0);
- return;
- }
-#endif // Q_WS_WIN
-
- // Find available desktop/workspace geometry.
- QRect availableGeometry;
- bool hasVerticalSizeConstraint = true;
- bool hasHorizontalSizeConstraint = true;
- if (tlw->isWindow())
- availableGeometry = QApplication::desktop()->availableGeometry(tlw);
- else {
- const QWidget *tlwParent = tlw->parentWidget();
- // Check if tlw is inside QAbstractScrollArea/QScrollArea.
- // If that's the case tlw->parentWidget() will return the viewport
- // and tlw->parentWidget()->parentWidget() will return the scroll area.
-#ifndef QT_NO_SCROLLAREA
- QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(tlwParent->parentWidget());
- if (scrollArea) {
- hasHorizontalSizeConstraint = scrollArea->horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOff;
- hasVerticalSizeConstraint = scrollArea->verticalScrollBarPolicy() == Qt::ScrollBarAlwaysOff;
- }
-#endif // QT_NO_SCROLLAREA
- availableGeometry = tlwParent->contentsRect();
- }
-
- // Find frame geometries, title bar height, and decoration sizes.
- const QRect frameGeometry = tlw->frameGeometry();
- const int titleBarHeight = qMax(tlw->geometry().y() - frameGeometry.y(), 0);
- const int bottomDecoration = qMax(frameGeometry.height() - tlw->height() - titleBarHeight, 0);
- const int leftRightDecoration = qMax((frameGeometry.width() - tlw->width()) / 2, 0);
-
- // Determine dyMax depending on whether the sizegrip is at the bottom
- // of the widget or not.
- if (d->atBottom()) {
- if (hasVerticalSizeConstraint)
- d->dyMax = availableGeometry.bottom() - d->r.bottom() - bottomDecoration;
- else
- d->dyMax = INT_MAX;
- } else {
- if (hasVerticalSizeConstraint)
- d->dyMax = availableGeometry.y() - d->r.y() + titleBarHeight;
- else
- d->dyMax = -INT_MAX;
- }
-
- // In RTL mode, the size grip is to the left; find dxMax from the desktop/workspace
- // geometry, the size grip geometry and the width of the decoration.
- if (d->atLeft()) {
- if (hasHorizontalSizeConstraint)
- d->dxMax = availableGeometry.x() - d->r.x() + leftRightDecoration;
- else
- d->dxMax = -INT_MAX;
- } else {
- if (hasHorizontalSizeConstraint)
- d->dxMax = availableGeometry.right() - d->r.right() - leftRightDecoration;
- else
- d->dxMax = INT_MAX;
- }
-}
-
-
-/*!
- \fn void QSizeGrip::mouseMoveEvent(QMouseEvent * event)
- Resizes the top-level widget containing this widget. The mouse
- move event is passed in the \a event parameter.
-*/
-void QSizeGrip::mouseMoveEvent(QMouseEvent * e)
-{
- if (e->buttons() != Qt::LeftButton) {
- QWidget::mouseMoveEvent(e);
- return;
- }
-
- Q_D(QSizeGrip);
- QWidget* tlw = qt_sizegrip_topLevelWidget(this);
- if (!d->gotMousePress || tlw->testAttribute(Qt::WA_WState_ConfigPending))
- return;
-
-#ifdef Q_WS_X11
- if (tlw->isWindow() && X11->isSupportedByWM(ATOM(_NET_WM_MOVERESIZE))
- && tlw->isTopLevel() && !(tlw->windowFlags() & Qt::X11BypassWindowManagerHint)
- && !tlw->testAttribute(Qt::WA_DontShowOnScreen) && !qt_widget_private(tlw)->hasHeightForWidth())
- return;
-#endif
-#ifdef Q_WS_WIN
- if (tlw->isWindow() && GetSystemMenu(tlw->winId(), FALSE) != 0 && internalWinId()
- && !tlw->testAttribute(Qt::WA_DontShowOnScreen) && !qt_widget_private(tlw)->hasHeightForWidth()) {
- MSG msg;
- while(PeekMessage(&msg, winId(), WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
- return;
- }
-#endif
-
- QPoint np(e->globalPos());
-
- // Don't extend beyond the available geometry; bound to dyMax and dxMax.
- QSize ns;
- if (d->atBottom())
- ns.rheight() = d->r.height() + qMin(np.y() - d->p.y(), d->dyMax);
- else
- ns.rheight() = d->r.height() - qMax(np.y() - d->p.y(), d->dyMax);
-
- if (d->atLeft())
- ns.rwidth() = d->r.width() - qMax(np.x() - d->p.x(), d->dxMax);
- else
- ns.rwidth() = d->r.width() + qMin(np.x() - d->p.x(), d->dxMax);
-
- ns = QLayout::closestAcceptableSize(tlw, ns);
-
- QPoint p;
- QRect nr(p, ns);
- if (d->atBottom()) {
- if (d->atLeft())
- nr.moveTopRight(d->r.topRight());
- else
- nr.moveTopLeft(d->r.topLeft());
- } else {
- if (d->atLeft())
- nr.moveBottomRight(d->r.bottomRight());
- else
- nr.moveBottomLeft(d->r.bottomLeft());
- }
-
- tlw->setGeometry(nr);
-}
-
-/*!
- \reimp
-*/
-void QSizeGrip::mouseReleaseEvent(QMouseEvent *mouseEvent)
-{
- if (mouseEvent->button() == Qt::LeftButton) {
- Q_D(QSizeGrip);
- d->gotMousePress = false;
- d->p = QPoint();
- } else {
- QWidget::mouseReleaseEvent(mouseEvent);
- }
-}
-
-/*!
- \reimp
-*/
-void QSizeGrip::moveEvent(QMoveEvent * /*moveEvent*/)
-{
- Q_D(QSizeGrip);
- // We're inside a resize operation; no update necessary.
- if (!d->p.isNull())
- return;
-
- d->m_corner = d->corner();
-#if !defined(QT_NO_CURSOR) && !defined(Q_WS_MAC)
- setCursor(d->m_corner == Qt::TopLeftCorner || d->m_corner == Qt::BottomRightCorner
- ? Qt::SizeFDiagCursor : Qt::SizeBDiagCursor);
-#endif
-}
-
-/*!
- \reimp
-*/
-void QSizeGrip::showEvent(QShowEvent *showEvent)
-{
-#ifdef Q_WS_MAC
- d_func()->updateMacSizer(false);
-#endif
- QWidget::showEvent(showEvent);
-}
-
-/*!
- \reimp
-*/
-void QSizeGrip::hideEvent(QHideEvent *hideEvent)
-{
-#ifdef Q_WS_MAC
- d_func()->updateMacSizer(true);
-#endif
- QWidget::hideEvent(hideEvent);
-}
-
-/*!
- \reimp
-*/
-void QSizeGrip::setVisible(bool visible)
-{
- QWidget::setVisible(visible);
-}
-
-/*! \reimp */
-bool QSizeGrip::eventFilter(QObject *o, QEvent *e)
-{
- Q_D(QSizeGrip);
- if ((isHidden() && testAttribute(Qt::WA_WState_ExplicitShowHide))
- || e->type() != QEvent::WindowStateChange
- || o != d->tlw) {
- return QWidget::eventFilter(o, e);
- }
- Qt::WindowStates sizeGripNotVisibleState = Qt::WindowFullScreen;
-#ifndef Q_WS_MAC
- sizeGripNotVisibleState |= Qt::WindowMaximized;
-#endif
- // Don't show the size grip if the tlw is maximized or in full screen mode.
- setVisible(!(d->tlw->windowState() & sizeGripNotVisibleState));
- setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- return QWidget::eventFilter(o, e);
-}
-
-/*!
- \reimp
-*/
-bool QSizeGrip::event(QEvent *event)
-{
- return QWidget::event(event);
-}
-
-#ifdef Q_WS_WIN
-/*! \reimp */
-bool QSizeGrip::winEvent( MSG *m, long *result )
-{
- return QWidget::winEvent(m, result);
-}
-#endif
-
-QT_END_NAMESPACE
-
-#include "moc_qsizegrip.cpp"
-
-#endif //QT_NO_SIZEGRIP
diff --git a/src/gui/widgets/qsizegrip.h b/src/gui/widgets/qsizegrip.h
deleted file mode 100644
index 7ec0818129..0000000000
--- a/src/gui/widgets/qsizegrip.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** 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 QSIZEGRIP_H
-#define QSIZEGRIP_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SIZEGRIP
-class QSizeGripPrivate;
-class Q_GUI_EXPORT QSizeGrip : public QWidget
-{
- Q_OBJECT
-public:
- explicit QSizeGrip(QWidget *parent);
- ~QSizeGrip();
-
- QSize sizeHint() const;
- void setVisible(bool);
-
-protected:
- void paintEvent(QPaintEvent *);
- void mousePressEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *mouseEvent);
- void moveEvent(QMoveEvent *moveEvent);
- void showEvent(QShowEvent *showEvent);
- void hideEvent(QHideEvent *hideEvent);
- bool eventFilter(QObject *, QEvent *);
- bool event(QEvent *);
-#ifdef Q_WS_WIN
- bool winEvent(MSG *m, long *result);
-#endif
-
-public:
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QSizeGrip(QWidget *parent, const char *name);
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QSizeGrip)
- Q_DISABLE_COPY(QSizeGrip)
- Q_PRIVATE_SLOT(d_func(), void _q_showIfNotHidden())
-};
-#endif // QT_NO_SIZEGRIP
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSIZEGRIP_H
diff --git a/src/gui/widgets/qslider.cpp b/src/gui/widgets/qslider.cpp
deleted file mode 100644
index 1eefb9c5f1..0000000000
--- a/src/gui/widgets/qslider.cpp
+++ /dev/null
@@ -1,666 +0,0 @@
-/****************************************************************************
-**
-** 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 "qslider.h"
-#ifndef QT_NO_SLIDER
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include "qapplication.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "private/qabstractslider_p.h"
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-class QSliderPrivate : public QAbstractSliderPrivate
-{
- Q_DECLARE_PUBLIC(QSlider)
-public:
- QStyle::SubControl pressedControl;
- int tickInterval;
- QSlider::TickPosition tickPosition;
- int clickOffset;
- void init();
- void resetLayoutItemMargins();
- int pixelPosToRangeValue(int pos) const;
- inline int pick(const QPoint &pt) const;
-
- QStyle::SubControl newHoverControl(const QPoint &pos);
- bool updateHoverControl(const QPoint &pos);
- QStyle::SubControl hoverControl;
- QRect hoverRect;
-};
-
-void QSliderPrivate::init()
-{
- Q_Q(QSlider);
- pressedControl = QStyle::SC_None;
- tickInterval = 0;
- tickPosition = QSlider::NoTicks;
- hoverControl = QStyle::SC_None;
- q->setFocusPolicy(Qt::FocusPolicy(q->style()->styleHint(QStyle::SH_Button_FocusPolicy)));
- QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Fixed, QSizePolicy::Slider);
- if (orientation == Qt::Vertical)
- sp.transpose();
- q->setSizePolicy(sp);
- q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- resetLayoutItemMargins();
-}
-
-void QSliderPrivate::resetLayoutItemMargins()
-{
- Q_Q(QSlider);
- QStyleOptionSlider opt;
- q->initStyleOption(&opt);
- setLayoutItemMargins(QStyle::SE_SliderLayoutItem, &opt);
-}
-
-int QSliderPrivate::pixelPosToRangeValue(int pos) const
-{
- Q_Q(const QSlider);
- QStyleOptionSlider opt;
- q->initStyleOption(&opt);
- QRect gr = q->style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, q);
- QRect sr = q->style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, q);
- int sliderMin, sliderMax, sliderLength;
-
- if (orientation == Qt::Horizontal) {
- sliderLength = sr.width();
- sliderMin = gr.x();
- sliderMax = gr.right() - sliderLength + 1;
- } else {
- sliderLength = sr.height();
- sliderMin = gr.y();
- sliderMax = gr.bottom() - sliderLength + 1;
- }
- return QStyle::sliderValueFromPosition(minimum, maximum, pos - sliderMin,
- sliderMax - sliderMin, opt.upsideDown);
-}
-
-inline int QSliderPrivate::pick(const QPoint &pt) const
-{
- return orientation == Qt::Horizontal ? pt.x() : pt.y();
-}
-
-/*!
- Initialize \a option with the values from this QSlider. This method
- is useful for subclasses when they need a QStyleOptionSlider, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QSlider::initStyleOption(QStyleOptionSlider *option) const
-{
- if (!option)
- return;
-
- Q_D(const QSlider);
- option->initFrom(this);
- option->subControls = QStyle::SC_None;
- option->activeSubControls = QStyle::SC_None;
- option->orientation = d->orientation;
- option->maximum = d->maximum;
- option->minimum = d->minimum;
- option->tickPosition = (QSlider::TickPosition)d->tickPosition;
- option->tickInterval = d->tickInterval;
- option->upsideDown = (d->orientation == Qt::Horizontal) ?
- (d->invertedAppearance != (option->direction == Qt::RightToLeft))
- : (!d->invertedAppearance);
- option->direction = Qt::LeftToRight; // we use the upsideDown option instead
- option->sliderPosition = d->position;
- option->sliderValue = d->value;
- option->singleStep = d->singleStep;
- option->pageStep = d->pageStep;
- if (d->orientation == Qt::Horizontal)
- option->state |= QStyle::State_Horizontal;
-}
-
-bool QSliderPrivate::updateHoverControl(const QPoint &pos)
-{
- Q_Q(QSlider);
- QRect lastHoverRect = hoverRect;
- QStyle::SubControl lastHoverControl = hoverControl;
- bool doesHover = q->testAttribute(Qt::WA_Hover);
- if (lastHoverControl != newHoverControl(pos) && doesHover) {
- q->update(lastHoverRect);
- q->update(hoverRect);
- return true;
- }
- return !doesHover;
-}
-
-QStyle::SubControl QSliderPrivate::newHoverControl(const QPoint &pos)
-{
- Q_Q(QSlider);
- QStyleOptionSlider opt;
- q->initStyleOption(&opt);
- opt.subControls = QStyle::SC_All;
- QRect handleRect = q->style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, q);
- QRect grooveRect = q->style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, q);
- QRect tickmarksRect = q->style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderTickmarks, q);
-
- if (handleRect.contains(pos)) {
- hoverRect = handleRect;
- hoverControl = QStyle::SC_SliderHandle;
- } else if (grooveRect.contains(pos)) {
- hoverRect = grooveRect;
- hoverControl = QStyle::SC_SliderGroove;
- } else if (tickmarksRect.contains(pos)) {
- hoverRect = tickmarksRect;
- hoverControl = QStyle::SC_SliderTickmarks;
- } else {
- hoverRect = QRect();
- hoverControl = QStyle::SC_None;
- }
-
- return hoverControl;
-}
-
-/*!
- \class QSlider
- \brief The QSlider widget provides a vertical or horizontal slider.
-
- \ingroup basicwidgets
-
-
- The slider is the classic widget for controlling a bounded value.
- It lets the user move a slider handle along a horizontal or vertical
- groove and translates the handle's position into an integer value
- within the legal range.
-
- QSlider has very few of its own functions; most of the functionality is in
- QAbstractSlider. The most useful functions are setValue() to set
- the slider directly to some value; triggerAction() to simulate
- the effects of clicking (useful for shortcut keys);
- setSingleStep(), setPageStep() to set the steps; and setMinimum()
- and setMaximum() to define the range of the scroll bar.
-
- QSlider provides methods for controlling tickmarks. You can use
- setTickPosition() to indicate where you want the tickmarks to be,
- setTickInterval() to indicate how many of them you want. the
- currently set tick position and interval can be queried using the
- tickPosition() and tickInterval() functions, respectively.
-
- QSlider inherits a comprehensive set of signals:
- \table
- \header \o Signal \o Description
- \row \o \l valueChanged()
- \o Emitted when the slider's value has changed. The tracking()
- determines whether this signal is emitted during user
- interaction.
- \row \o \l sliderPressed()
- \o Emitted when the user starts to drag the slider.
- \row \o \l sliderMoved()
- \o Emitted when the user drags the slider.
- \row \o \l sliderReleased()
- \o Emitted when the user releases the slider.
- \endtable
-
- QSlider only provides integer ranges. Note that although
- QSlider handles very large numbers, it becomes difficult for users
- to use a slider accurately for very large ranges.
-
- A slider accepts focus on Tab and provides both a mouse wheel and a
- keyboard interface. The keyboard interface is the following:
-
- \list
- \o Left/Right move a horizontal slider by one single step.
- \o Up/Down move a vertical slider by one single step.
- \o PageUp moves up one page.
- \o PageDown moves down one page.
- \o Home moves to the start (mininum).
- \o End moves to the end (maximum).
- \endlist
-
- \table 100%
- \row \o \inlineimage macintosh-slider.png Screenshot of a Macintosh slider
- \o A slider shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \row \o \inlineimage windows-slider.png Screenshot of a Windows XP slider
- \o A slider shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage plastique-slider.png Screenshot of a Plastique slider
- \o A slider shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \endtable
-
- \sa QScrollBar, QSpinBox, QDial, {fowler}{GUI Design Handbook: Slider}, {Sliders Example}
-*/
-
-
-/*!
- \enum QSlider::TickPosition
-
- This enum specifies where the tick marks are to be drawn relative
- to the slider's groove and the handle the user moves.
-
- \value NoTicks Do not draw any tick marks.
- \value TicksBothSides Draw tick marks on both sides of the groove.
- \value TicksAbove Draw tick marks above the (horizontal) slider
- \value TicksBelow Draw tick marks below the (horizontal) slider
- \value TicksLeft Draw tick marks to the left of the (vertical) slider
- \value TicksRight Draw tick marks to the right of the (vertical) slider
-
- \omitvalue NoMarks
- \omitvalue Above
- \omitvalue Left
- \omitvalue Below
- \omitvalue Right
- \omitvalue Both
-*/
-
-
-/*!
- Constructs a vertical slider with the given \a parent.
-*/
-QSlider::QSlider(QWidget *parent)
- : QAbstractSlider(*new QSliderPrivate, parent)
-{
- d_func()->orientation = Qt::Vertical;
- d_func()->init();
-}
-
-/*!
- Constructs a slider with the given \a parent. The \a orientation
- parameter determines whether the slider is horizontal or vertical;
- the valid values are Qt::Vertical and Qt::Horizontal.
-*/
-
-QSlider::QSlider(Qt::Orientation orientation, QWidget *parent)
- : QAbstractSlider(*new QSliderPrivate, parent)
-{
- d_func()->orientation = orientation;
- d_func()->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use QSlider() and QObject::setObjectName() instead.
-
- \oldcode
- QSlider *mySlider = new QSlider(parent, name);
- \newcode
- QSlider *mySlider = new QSlider(parent);
- mySlider->setObjectName(name);
- \endcode
-*/
-QSlider::QSlider(QWidget *parent, const char *name)
- : QAbstractSlider(*new QSliderPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- d_func()->orientation = Qt::Vertical;
- d_func()->init();
-}
-
-/*!
- Use QSlider() and QObject::setObjectName() instead.
-
- \oldcode
- QSlider *mySlider = new QSlider(orientation, parent, name);
- \newcode
- QSlider *mySlider = new QSlider(orientation, parent);
- mySlider->setObjectName(name);
- \endcode
-*/
-QSlider::QSlider(Qt::Orientation orientation, QWidget *parent, const char *name)
- : QAbstractSlider(*new QSliderPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- d_func()->orientation = orientation;
- d_func()->init();
-}
-
-/*!
- Use QSlider(), QObject::setObjectName() and the functionality
- inherited from QAbstractSlider instead.
-
- \oldcode
- QSlider *mySlider = new QSlider(minValue, maxValue, pageStep,
- value, orientation, parent, name);
- \newcode
- QSlider *mySlider = new QSlider(orientation, parent);
- mySlider->setObjectName(name);
- mySlider->setMinimum(minValue);
- mySlider->setMaximum(maxValue);
- mySlider->setPageStep(pageStep);
- mySlider->setValue(value);
- \endcode
-*/
-QSlider::QSlider(int minValue, int maxValue, int pageStep, int value, Qt::Orientation orientation,
- QWidget *parent, const char *name)
- : QAbstractSlider(*new QSliderPrivate, parent)
-{
- Q_D(QSlider);
- setObjectName(QString::fromAscii(name));
- d->minimum = minValue;
- d->maximum = maxValue;
- d->pageStep = pageStep;
- d->position = d->value = value;
- d->orientation = orientation;
- d->init();
-}
-#endif
-
-/*!
- Destroys this slider.
-*/
-QSlider::~QSlider()
-{
-}
-
-/*!
- \reimp
-*/
-void QSlider::paintEvent(QPaintEvent *)
-{
- Q_D(QSlider);
- QPainter p(this);
- QStyleOptionSlider opt;
- initStyleOption(&opt);
-
- opt.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle;
- if (d->tickPosition != NoTicks)
- opt.subControls |= QStyle::SC_SliderTickmarks;
- if (d->pressedControl) {
- opt.activeSubControls = d->pressedControl;
- opt.state |= QStyle::State_Sunken;
- } else {
- opt.activeSubControls = d->hoverControl;
- }
-
- style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this);
-}
-
-/*!
- \reimp
-*/
-
-bool QSlider::event(QEvent *event)
-{
- Q_D(QSlider);
-
- switch(event->type()) {
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d->updateHoverControl(he->pos());
- break;
- case QEvent::StyleChange:
- case QEvent::MacSizeChange:
- d->resetLayoutItemMargins();
- break;
- default:
- break;
- }
- return QAbstractSlider::event(event);
-}
-
-/*!
- \reimp
-*/
-void QSlider::mousePressEvent(QMouseEvent *ev)
-{
- Q_D(QSlider);
- if (d->maximum == d->minimum || (ev->buttons() ^ ev->button())) {
- ev->ignore();
- return;
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- setEditFocus(true);
-#endif
- ev->accept();
- if ((ev->button() & style()->styleHint(QStyle::SH_Slider_AbsoluteSetButtons)) == ev->button()) {
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- const QRect sliderRect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
- const QPoint center = sliderRect.center() - sliderRect.topLeft();
- // to take half of the slider off for the setSliderPosition call we use the center - topLeft
-
- setSliderPosition(d->pixelPosToRangeValue(d->pick(ev->pos() - center)));
- triggerAction(SliderMove);
- setRepeatAction(SliderNoAction);
- d->pressedControl = QStyle::SC_SliderHandle;
- update();
- } else if ((ev->button() & style()->styleHint(QStyle::SH_Slider_PageSetButtons)) == ev->button()) {
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- d->pressedControl = style()->hitTestComplexControl(QStyle::CC_Slider,
- &opt, ev->pos(), this);
- SliderAction action = SliderNoAction;
- if (d->pressedControl == QStyle::SC_SliderGroove) {
- const QRect sliderRect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
- int pressValue = d->pixelPosToRangeValue(d->pick(ev->pos() - sliderRect.center() + sliderRect.topLeft()));
- d->pressValue = pressValue;
- if (pressValue > d->value)
- action = SliderPageStepAdd;
- else if (pressValue < d->value)
- action = SliderPageStepSub;
- if (action) {
- triggerAction(action);
- setRepeatAction(action);
- }
- }
- } else {
- ev->ignore();
- return;
- }
-
- if (d->pressedControl == QStyle::SC_SliderHandle) {
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- setRepeatAction(SliderNoAction);
- QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
- d->clickOffset = d->pick(ev->pos() - sr.topLeft());
- update(sr);
- setSliderDown(true);
- }
-}
-
-/*!
- \reimp
-*/
-void QSlider::mouseMoveEvent(QMouseEvent *ev)
-{
- Q_D(QSlider);
- if (d->pressedControl != QStyle::SC_SliderHandle) {
- ev->ignore();
- return;
- }
- ev->accept();
- int newPosition = d->pixelPosToRangeValue(d->pick(ev->pos()) - d->clickOffset);
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- setSliderPosition(newPosition);
-}
-
-
-/*!
- \reimp
-*/
-void QSlider::mouseReleaseEvent(QMouseEvent *ev)
-{
- Q_D(QSlider);
- if (d->pressedControl == QStyle::SC_None || ev->buttons()) {
- ev->ignore();
- return;
- }
- ev->accept();
- QStyle::SubControl oldPressed = QStyle::SubControl(d->pressedControl);
- d->pressedControl = QStyle::SC_None;
- setRepeatAction(SliderNoAction);
- if (oldPressed == QStyle::SC_SliderHandle)
- setSliderDown(false);
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- opt.subControls = oldPressed;
- update(style()->subControlRect(QStyle::CC_Slider, &opt, oldPressed, this));
-}
-
-/*!
- \reimp
-*/
-QSize QSlider::sizeHint() const
-{
- Q_D(const QSlider);
- ensurePolished();
- const int SliderLength = 84, TickSpace = 5;
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- int thick = style()->pixelMetric(QStyle::PM_SliderThickness, &opt, this);
- if (d->tickPosition & TicksAbove)
- thick += TickSpace;
- if (d->tickPosition & TicksBelow)
- thick += TickSpace;
- int w = thick, h = SliderLength;
- if (d->orientation == Qt::Horizontal) {
- w = SliderLength;
- h = thick;
- }
- return style()->sizeFromContents(QStyle::CT_Slider, &opt, QSize(w, h), this).expandedTo(QApplication::globalStrut());
-}
-
-/*!
- \reimp
-*/
-QSize QSlider::minimumSizeHint() const
-{
- Q_D(const QSlider);
- QSize s = sizeHint();
- QStyleOptionSlider opt;
- initStyleOption(&opt);
- int length = style()->pixelMetric(QStyle::PM_SliderLength, &opt, this);
- if (d->orientation == Qt::Horizontal)
- s.setWidth(length);
- else
- s.setHeight(length);
- return s;
-}
-
-/*!
- \property QSlider::tickPosition
- \brief the tickmark position for this slider
-
- The valid values are described by the QSlider::TickPosition enum.
-
- The default value is \l QSlider::NoTicks.
-
- \sa tickInterval
-*/
-
-void QSlider::setTickPosition(TickPosition position)
-{
- Q_D(QSlider);
- d->tickPosition = position;
- d->resetLayoutItemMargins();
- update();
- updateGeometry();
-}
-
-QSlider::TickPosition QSlider::tickPosition() const
-{
- return d_func()->tickPosition;
-}
-
-/*!
- \fn TickPosition QSlider::tickmarks() const
- \compat
-
- Use tickPosition() instead.
-*/
-
-/*!
- \fn QSlider::setTickmarks(TickPosition position)
- \compat
-
- Use setTickPosition() instead.
-*/
-
-/*!
- \property QSlider::tickInterval
- \brief the interval between tickmarks
-
- This is a value interval, not a pixel interval. If it is 0, the
- slider will choose between singleStep() and pageStep().
-
- The default value is 0.
-
- \sa tickPosition, lineStep(), pageStep()
-*/
-
-void QSlider::setTickInterval(int ts)
-{
- d_func()->tickInterval = qMax(0, ts);
- update();
-}
-
-int QSlider::tickInterval() const
-{
- return d_func()->tickInterval;
-}
-
-/*!
- \fn void QSlider::addStep()
-
- Use setValue() instead.
-*/
-
-/*!
- \fn void QSlider::subtractStep()
-
- Use setValue() instead.
-*/
-
-/*! \internal
- Returns the style option for slider.
-*/
-Q_GUI_EXPORT QStyleOptionSlider qt_qsliderStyleOption(QSlider *slider)
-{
- QStyleOptionSlider sliderOption;
- slider->initStyleOption(&sliderOption);
- return sliderOption;
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qslider.h b/src/gui/widgets/qslider.h
deleted file mode 100644
index a2201da9a2..0000000000
--- a/src/gui/widgets/qslider.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** 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 QSLIDER_H
-#define QSLIDER_H
-
-#include <QtGui/qabstractslider.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SLIDER
-
-class QSliderPrivate;
-class QStyleOptionSlider;
-class Q_GUI_EXPORT QSlider : public QAbstractSlider
-{
- Q_OBJECT
-
- Q_ENUMS(TickPosition)
- Q_PROPERTY(TickPosition tickPosition READ tickPosition WRITE setTickPosition)
- Q_PROPERTY(int tickInterval READ tickInterval WRITE setTickInterval)
-
-public:
- enum TickPosition {
- NoTicks = 0,
- TicksAbove = 1,
- TicksLeft = TicksAbove,
- TicksBelow = 2,
- TicksRight = TicksBelow,
- TicksBothSides = 3
-
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- ,NoMarks = NoTicks,
- Above = TicksAbove,
- Left = TicksAbove,
- Below = TicksBelow,
- Right = TicksRight,
- Both = TicksBothSides
-#endif
- };
-
- explicit QSlider(QWidget *parent = 0);
- explicit QSlider(Qt::Orientation orientation, QWidget *parent = 0);
-
- ~QSlider();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- void setTickPosition(TickPosition position);
- TickPosition tickPosition() const;
-
- void setTickInterval(int ti);
- int tickInterval() const;
-
- bool event(QEvent *event);
-
-protected:
- void paintEvent(QPaintEvent *ev);
- void mousePressEvent(QMouseEvent *ev);
- void mouseReleaseEvent(QMouseEvent *ev);
- void mouseMoveEvent(QMouseEvent *ev);
- void initStyleOption(QStyleOptionSlider *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QSlider(QWidget *parent, const char *name);
- QT3_SUPPORT_CONSTRUCTOR QSlider(Qt::Orientation, QWidget *parent, const char *name);
- QT3_SUPPORT_CONSTRUCTOR QSlider(int minValue, int maxValue, int pageStep, int value,
- Qt::Orientation orientation,
- QWidget *parent = 0, const char *name = 0);
- inline QT3_SUPPORT void setTickmarks(TickPosition position) { setTickPosition(position); }
- inline QT3_SUPPORT TickPosition tickmarks() const { return tickPosition(); }
-public Q_SLOTS:
- inline QT_MOC_COMPAT void addStep() { triggerAction(SliderSingleStepAdd); }
- inline QT_MOC_COMPAT void subtractStep() { triggerAction(SliderSingleStepSub); }
-#endif
-
-private:
- friend Q_GUI_EXPORT QStyleOptionSlider qt_qsliderStyleOption(QSlider *slider);
-
- Q_DISABLE_COPY(QSlider)
- Q_DECLARE_PRIVATE(QSlider)
-};
-
-#endif // QT_NO_SLIDER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSLIDER_H
diff --git a/src/gui/widgets/qspinbox.cpp b/src/gui/widgets/qspinbox.cpp
deleted file mode 100644
index 22fd2a9cc4..0000000000
--- a/src/gui/widgets/qspinbox.cpp
+++ /dev/null
@@ -1,1327 +0,0 @@
-/****************************************************************************
-**
-** 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 <private/qabstractspinbox_p.h>
-#include <qspinbox.h>
-
-#ifndef QT_NO_SPINBOX
-
-#include <qlineedit.h>
-#include <qlocale.h>
-#include <qvalidator.h>
-#include <qdebug.h>
-
-#include <math.h>
-#include <float.h>
-
-QT_BEGIN_NAMESPACE
-
-//#define QSPINBOX_QSBDEBUG
-#ifdef QSPINBOX_QSBDEBUG
-# define QSBDEBUG qDebug
-#else
-# define QSBDEBUG if (false) qDebug
-#endif
-
-class QSpinBoxPrivate : public QAbstractSpinBoxPrivate
-{
- Q_DECLARE_PUBLIC(QSpinBox)
-public:
- QSpinBoxPrivate();
- void emitSignals(EmitPolicy ep, const QVariant &);
-
- virtual QVariant valueFromText(const QString &n) const;
- virtual QString textFromValue(const QVariant &n) const;
- QVariant validateAndInterpret(QString &input, int &pos,
- QValidator::State &state) const;
-
- inline void init() {
- Q_Q(QSpinBox);
- q->setInputMethodHints(Qt::ImhDigitsOnly);
- setLayoutItemMargins(QStyle::SE_SpinBoxLayoutItem);
- }
-};
-
-class QDoubleSpinBoxPrivate : public QAbstractSpinBoxPrivate
-{
- Q_DECLARE_PUBLIC(QDoubleSpinBox)
-public:
- QDoubleSpinBoxPrivate();
- void emitSignals(EmitPolicy ep, const QVariant &);
-
- virtual QVariant valueFromText(const QString &n) const;
- virtual QString textFromValue(const QVariant &n) const;
- QVariant validateAndInterpret(QString &input, int &pos,
- QValidator::State &state) const;
- double round(double input) const;
- // variables
- int decimals;
-
- inline void init() {
- Q_Q(QDoubleSpinBox);
- q->setInputMethodHints(Qt::ImhFormattedNumbersOnly);
- }
-
- // When fiddling with the decimals property, we may lose precision in these properties.
- double actualMin;
- double actualMax;
-};
-
-
-/*!
- \class QSpinBox
- \brief The QSpinBox class provides a spin box widget.
-
- \ingroup basicwidgets
-
-
- QSpinBox is designed to handle integers and discrete sets of
- values (e.g., month names); use QDoubleSpinBox for floating point
- values.
-
- QSpinBox allows the user to choose a value by clicking the up/down
- buttons or pressing up/down on the keyboard to increase/decrease
- the value currently displayed. The user can also type the value in
- manually. The spin box supports integer values but can be extended to
- use different strings with validate(), textFromValue() and valueFromText().
-
- Every time the value changes QSpinBox emits the valueChanged()
- signals. The current value can be fetched with value() and set
- with setValue().
-
- Clicking the up/down buttons or using the keyboard accelerator's
- up and down arrows will increase or decrease the current value in
- steps of size singleStep(). If you want to change this behaviour you
- can reimplement the virtual function stepBy(). The minimum and
- maximum value and the step size can be set using one of the
- constructors, and can be changed later with setMinimum(),
- setMaximum() and setSingleStep().
-
- Most spin boxes are directional, but QSpinBox can also operate as
- a circular spin box, i.e. if the range is 0-99 and the current
- value is 99, clicking "up" will give 0 if wrapping() is set to
- true. Use setWrapping() if you want circular behavior.
-
- The displayed value can be prepended and appended with arbitrary
- strings indicating, for example, currency or the unit of
- measurement. See setPrefix() and setSuffix(). The text in the spin
- box is retrieved with text() (which includes any prefix() and
- suffix()), or with cleanText() (which has no prefix(), no suffix()
- and no leading or trailing whitespace).
-
- It is often desirable to give the user a special (often default)
- choice in addition to the range of numeric values. See
- setSpecialValueText() for how to do this with QSpinBox.
-
- \table 100%
- \row \o \inlineimage windowsxp-spinbox.png Screenshot of a Windows XP spin box
- \o A spin box shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
- \row \o \inlineimage plastique-spinbox.png Screenshot of a Plastique spin box
- \o A spin box shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
- \row \o \inlineimage macintosh-spinbox.png Screenshot of a Macintosh spin box
- \o A spin box shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
- \endtable
-
- \section1 Subclassing QSpinBox
-
- If using prefix(), suffix(), and specialValueText() don't provide
- enough control, you subclass QSpinBox and reimplement
- valueFromText() and textFromValue(). For example, here's the code
- for a custom spin box that allows the user to enter icon sizes
- (e.g., "32 x 32"):
-
- \snippet examples/widgets/icons/iconsizespinbox.cpp 1
- \codeline
- \snippet examples/widgets/icons/iconsizespinbox.cpp 2
-
- See the \l{widgets/icons}{Icons} example for the full source
- code.
-
- \sa QDoubleSpinBox, QDateTimeEdit, QSlider, {Spin Boxes Example}
-*/
-
-/*!
- \fn void QSpinBox::valueChanged(int i)
-
- This signal is emitted whenever the spin box's value is changed.
- The new value's integer value is passed in \a i.
-*/
-
-/*!
- \fn void QSpinBox::valueChanged(const QString &text)
-
- \overload
-
- The new value is passed literally in \a text with no prefix() or
- suffix().
-*/
-
-/*!
- Constructs a spin box with 0 as minimum value and 99 as maximum value, a
- step value of 1. The value is initially set to 0. It is parented to \a
- parent.
-
- \sa setMinimum(), setMaximum(), setSingleStep()
-*/
-
-QSpinBox::QSpinBox(QWidget *parent)
- : QAbstractSpinBox(*new QSpinBoxPrivate, parent)
-{
- Q_D(QSpinBox);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QSpinBox::QSpinBox(QWidget *parent, const char *name)
- : QAbstractSpinBox(*new QSpinBoxPrivate, parent)
-{
- Q_D(QSpinBox);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QSpinBox::QSpinBox(int minimum, int maximum, int step, QWidget *parent, const char *name)
- : QAbstractSpinBox(*new QSpinBoxPrivate, parent)
-{
- Q_D(QSpinBox);
- d->minimum = QVariant(qMin<int>(minimum, maximum));
- d->maximum = QVariant(qMax<int>(minimum, maximum));
- d->singleStep = QVariant(step);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-#endif
-
-/*!
- \property QSpinBox::value
- \brief the value of the spin box
-
- setValue() will emit valueChanged() if the new value is different
- from the old one.
-*/
-
-int QSpinBox::value() const
-{
- Q_D(const QSpinBox);
- return d->value.toInt();
-}
-
-void QSpinBox::setValue(int value)
-{
- Q_D(QSpinBox);
- d->setValue(QVariant(value), EmitIfChanged);
-}
-
-/*!
- \property QSpinBox::prefix
- \brief the spin box's prefix
-
- The prefix is prepended to the start of the displayed value.
- Typical use is to display a unit of measurement or a currency
- symbol. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 0
-
- To turn off the prefix display, set this property to an empty
- string. The default is no prefix. The prefix is not displayed when
- value() == minimum() and specialValueText() is set.
-
- If no prefix is set, prefix() returns an empty string.
-
- \sa suffix(), setSuffix(), specialValueText(), setSpecialValueText()
-*/
-
-QString QSpinBox::prefix() const
-{
- Q_D(const QSpinBox);
- return d->prefix;
-}
-
-void QSpinBox::setPrefix(const QString &prefix)
-{
- Q_D(QSpinBox);
-
- d->prefix = prefix;
- d->updateEdit();
-
- d->cachedSizeHint = QSize();
- updateGeometry();
-}
-
-/*!
- \property QSpinBox::suffix
- \brief the suffix of the spin box
-
- The suffix is appended to the end of the displayed value. Typical
- use is to display a unit of measurement or a currency symbol. For
- example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 1
-
- To turn off the suffix display, set this property to an empty
- string. The default is no suffix. The suffix is not displayed for
- the minimum() if specialValueText() is set.
-
- If no suffix is set, suffix() returns an empty string.
-
- \sa prefix(), setPrefix(), specialValueText(), setSpecialValueText()
-*/
-
-QString QSpinBox::suffix() const
-{
- Q_D(const QSpinBox);
-
- return d->suffix;
-}
-
-void QSpinBox::setSuffix(const QString &suffix)
-{
- Q_D(QSpinBox);
-
- d->suffix = suffix;
- d->updateEdit();
-
- d->cachedSizeHint = QSize();
- updateGeometry();
-}
-
-/*!
- \property QSpinBox::cleanText
-
- \brief the text of the spin box excluding any prefix, suffix,
- or leading or trailing whitespace.
-
- \sa text, QSpinBox::prefix, QSpinBox::suffix
-*/
-
-QString QSpinBox::cleanText() const
-{
- Q_D(const QSpinBox);
-
- return d->stripped(d->edit->displayText());
-}
-
-
-/*!
- \property QSpinBox::singleStep
- \brief the step value
-
- When the user uses the arrows to change the spin box's value the
- value will be incremented/decremented by the amount of the
- singleStep. The default value is 1. Setting a singleStep value of
- less than 0 does nothing.
-*/
-
-int QSpinBox::singleStep() const
-{
- Q_D(const QSpinBox);
-
- return d->singleStep.toInt();
-}
-
-void QSpinBox::setSingleStep(int value)
-{
- Q_D(QSpinBox);
- if (value >= 0) {
- d->singleStep = QVariant(value);
- d->updateEdit();
- }
-}
-
-/*!
- \property QSpinBox::minimum
-
- \brief the minimum value of the spin box
-
- When setting this property the \l maximum is adjusted
- if necessary to ensure that the range remains valid.
-
- The default minimum value is 0.
-
- \sa setRange() specialValueText
-*/
-
-int QSpinBox::minimum() const
-{
- Q_D(const QSpinBox);
-
- return d->minimum.toInt();
-}
-
-void QSpinBox::setMinimum(int minimum)
-{
- Q_D(QSpinBox);
- const QVariant m(minimum);
- d->setRange(m, (d->variantCompare(d->maximum, m) > 0 ? d->maximum : m));
-}
-
-/*!
- \property QSpinBox::maximum
-
- \brief the maximum value of the spin box
-
- When setting this property the \l minimum is adjusted
- if necessary, to ensure that the range remains valid.
-
- The default maximum value is 99.
-
- \sa setRange() specialValueText
-
-*/
-
-int QSpinBox::maximum() const
-{
- Q_D(const QSpinBox);
-
- return d->maximum.toInt();
-}
-
-void QSpinBox::setMaximum(int maximum)
-{
- Q_D(QSpinBox);
- const QVariant m(maximum);
- d->setRange((d->variantCompare(d->minimum, m) < 0 ? d->minimum : m), m);
-}
-
-/*!
- Convenience function to set the \a minimum, and \a maximum values
- with a single function call.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 2
- is equivalent to:
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 3
-
- \sa minimum maximum
-*/
-
-void QSpinBox::setRange(int minimum, int maximum)
-{
- Q_D(QSpinBox);
- d->setRange(QVariant(minimum), QVariant(maximum));
-}
-
-/*!
- This virtual function is used by the spin box whenever it needs to
- display the given \a value. The default implementation returns a
- string containing \a value printed in the standard way using
- QWidget::locale().toString(), but with the thousand separator
- removed. Reimplementations may return anything. (See the example
- in the detailed description.)
-
- Note: QSpinBox does not call this function for specialValueText()
- and that neither prefix() nor suffix() should be included in the
- return value.
-
- If you reimplement this, you may also need to reimplement
- valueFromText() and validate()
-
- \sa valueFromText(), validate(), QLocale::groupSeparator()
-*/
-
-QString QSpinBox::textFromValue(int value) const
-{
- QString str = locale().toString(value);
- if (qAbs(value) >= 1000 || value == INT_MIN) {
- str.remove(locale().groupSeparator());
- }
-
- return str;
-}
-
-/*!
- \fn int QSpinBox::valueFromText(const QString &text) const
-
- This virtual function is used by the spin box whenever it needs to
- interpret \a text entered by the user as a value.
-
- Subclasses that need to display spin box values in a non-numeric
- way need to reimplement this function.
-
- Note: QSpinBox handles specialValueText() separately; this
- function is only concerned with the other values.
-
- \sa textFromValue(), validate()
-*/
-
-int QSpinBox::valueFromText(const QString &text) const
-{
- Q_D(const QSpinBox);
-
- QString copy = text;
- int pos = d->edit->cursorPosition();
- QValidator::State state = QValidator::Acceptable;
- return d->validateAndInterpret(copy, pos, state).toInt();
-}
-
-/*!
- \reimp
-*/
-QValidator::State QSpinBox::validate(QString &text, int &pos) const
-{
- Q_D(const QSpinBox);
-
- QValidator::State state;
- d->validateAndInterpret(text, pos, state);
- return state;
-}
-
-
-/*!
- \reimp
-*/
-void QSpinBox::fixup(QString &input) const
-{
- input.remove(locale().groupSeparator());
-}
-
-
-// --- QDoubleSpinBox ---
-
-/*!
- \class QDoubleSpinBox
- \brief The QDoubleSpinBox class provides a spin box widget that
- takes doubles.
-
- \ingroup basicwidgets
-
-
- QDoubleSpinBox allows the user to choose a value by clicking the
- up and down buttons or by pressing Up or Down on the keyboard to
- increase or decrease the value currently displayed. The user can
- also type the value in manually. The spin box supports double
- values but can be extended to use different strings with
- validate(), textFromValue() and valueFromText().
-
- Every time the value changes QDoubleSpinBox emits the
- valueChanged() signal. The current value can be fetched with
- value() and set with setValue().
-
- Note: QDoubleSpinBox will round numbers so they can be displayed
- with the current precision. In a QDoubleSpinBox with decimals set
- to 2, calling setValue(2.555) will cause value() to return 2.56.
-
- Clicking the up and down buttons or using the keyboard accelerator's
- Up and Down arrows will increase or decrease the current value in
- steps of size singleStep(). If you want to change this behavior you
- can reimplement the virtual function stepBy(). The minimum and
- maximum value and the step size can be set using one of the
- constructors, and can be changed later with setMinimum(),
- setMaximum() and setSingleStep(). The spinbox has a default
- precision of 2 decimal places but this can be changed using
- setDecimals().
-
- Most spin boxes are directional, but QDoubleSpinBox can also
- operate as a circular spin box, i.e. if the range is 0.0-99.9 and
- the current value is 99.9, clicking "up" will give 0 if wrapping()
- is set to true. Use setWrapping() if you want circular behavior.
-
- The displayed value can be prepended and appended with arbitrary
- strings indicating, for example, currency or the unit of
- measurement. See setPrefix() and setSuffix(). The text in the spin
- box is retrieved with text() (which includes any prefix() and
- suffix()), or with cleanText() (which has no prefix(), no suffix()
- and no leading or trailing whitespace).
-
- It is often desirable to give the user a special (often default)
- choice in addition to the range of numeric values. See
- setSpecialValueText() for how to do this with QDoubleSpinBox.
-
- \sa QSpinBox, QDateTimeEdit, QSlider, {Spin Boxes Example}
-*/
-
-/*!
- \fn void QDoubleSpinBox::valueChanged(double d);
-
- This signal is emitted whenever the spin box's value is changed.
- The new value is passed in \a d.
-*/
-
-/*!
- \fn void QDoubleSpinBox::valueChanged(const QString &text);
-
- \overload
-
- The new value is passed literally in \a text with no prefix() or
- suffix().
-*/
-
-/*!
- Constructs a spin box with 0.0 as minimum value and 99.99 as maximum value,
- a step value of 1.0 and a precision of 2 decimal places. The value is
- initially set to 0.00. The spin box has the given \a parent.
-
- \sa setMinimum(), setMaximum(), setSingleStep()
-*/
-QDoubleSpinBox::QDoubleSpinBox(QWidget *parent)
- : QAbstractSpinBox(*new QDoubleSpinBoxPrivate, parent)
-{
- Q_D(QDoubleSpinBox);
- d->init();
-}
-
-/*!
- \property QDoubleSpinBox::value
- \brief the value of the spin box
-
- setValue() will emit valueChanged() if the new value is different
- from the old one.
-
- Note: The value will be rounded so it can be displayed with the
- current setting of decimals.
-
- \sa decimals
-*/
-double QDoubleSpinBox::value() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->value.toDouble();
-}
-
-void QDoubleSpinBox::setValue(double value)
-{
- Q_D(QDoubleSpinBox);
- QVariant v(d->round(value));
- d->setValue(v, EmitIfChanged);
-}
-/*!
- \property QDoubleSpinBox::prefix
- \brief the spin box's prefix
-
- The prefix is prepended to the start of the displayed value.
- Typical use is to display a unit of measurement or a currency
- symbol. For example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 4
-
- To turn off the prefix display, set this property to an empty
- string. The default is no prefix. The prefix is not displayed when
- value() == minimum() and specialValueText() is set.
-
- If no prefix is set, prefix() returns an empty string.
-
- \sa suffix(), setSuffix(), specialValueText(), setSpecialValueText()
-*/
-
-QString QDoubleSpinBox::prefix() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->prefix;
-}
-
-void QDoubleSpinBox::setPrefix(const QString &prefix)
-{
- Q_D(QDoubleSpinBox);
-
- d->prefix = prefix;
- d->updateEdit();
-}
-
-/*!
- \property QDoubleSpinBox::suffix
- \brief the suffix of the spin box
-
- The suffix is appended to the end of the displayed value. Typical
- use is to display a unit of measurement or a currency symbol. For
- example:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 5
-
- To turn off the suffix display, set this property to an empty
- string. The default is no suffix. The suffix is not displayed for
- the minimum() if specialValueText() is set.
-
- If no suffix is set, suffix() returns an empty string.
-
- \sa prefix(), setPrefix(), specialValueText(), setSpecialValueText()
-*/
-
-QString QDoubleSpinBox::suffix() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->suffix;
-}
-
-void QDoubleSpinBox::setSuffix(const QString &suffix)
-{
- Q_D(QDoubleSpinBox);
-
- d->suffix = suffix;
- d->updateEdit();
-
- d->cachedSizeHint = QSize();
- updateGeometry();
-}
-
-/*!
- \property QDoubleSpinBox::cleanText
-
- \brief the text of the spin box excluding any prefix, suffix,
- or leading or trailing whitespace.
-
- \sa text, QDoubleSpinBox::prefix, QDoubleSpinBox::suffix
-*/
-
-QString QDoubleSpinBox::cleanText() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->stripped(d->edit->displayText());
-}
-
-/*!
- \property QDoubleSpinBox::singleStep
- \brief the step value
-
- When the user uses the arrows to change the spin box's value the
- value will be incremented/decremented by the amount of the
- singleStep. The default value is 1.0. Setting a singleStep value
- of less than 0 does nothing.
-*/
-double QDoubleSpinBox::singleStep() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->singleStep.toDouble();
-}
-
-void QDoubleSpinBox::setSingleStep(double value)
-{
- Q_D(QDoubleSpinBox);
-
- if (value >= 0) {
- d->singleStep = value;
- d->updateEdit();
- }
-}
-
-/*!
- \property QDoubleSpinBox::minimum
-
- \brief the minimum value of the spin box
-
- When setting this property the \l maximum is adjusted
- if necessary to ensure that the range remains valid.
-
- The default minimum value is 0.0.
-
- Note: The minimum value will be rounded to match the decimals
- property.
-
- \sa decimals, setRange() specialValueText
-*/
-
-double QDoubleSpinBox::minimum() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->minimum.toDouble();
-}
-
-void QDoubleSpinBox::setMinimum(double minimum)
-{
- Q_D(QDoubleSpinBox);
- d->actualMin = minimum;
- const QVariant m(d->round(minimum));
- d->setRange(m, (d->variantCompare(d->maximum, m) > 0 ? d->maximum : m));
-}
-
-/*!
- \property QDoubleSpinBox::maximum
-
- \brief the maximum value of the spin box
-
- When setting this property the \l minimum is adjusted
- if necessary, to ensure that the range remains valid.
-
- The default maximum value is 99.99.
-
- Note: The maximum value will be rounded to match the decimals
- property.
-
- \sa decimals, setRange()
-*/
-
-double QDoubleSpinBox::maximum() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->maximum.toDouble();
-}
-
-void QDoubleSpinBox::setMaximum(double maximum)
-{
- Q_D(QDoubleSpinBox);
- d->actualMax = maximum;
- const QVariant m(d->round(maximum));
- d->setRange((d->variantCompare(d->minimum, m) < 0 ? d->minimum : m), m);
-}
-
-/*!
- Convenience function to set the \a minimum and \a maximum values
- with a single function call.
-
- Note: The maximum and minimum values will be rounded to match the
- decimals property.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 6
- is equivalent to:
- \snippet doc/src/snippets/code/src_gui_widgets_qspinbox.cpp 7
-
- \sa minimum maximum
-*/
-
-void QDoubleSpinBox::setRange(double minimum, double maximum)
-{
- Q_D(QDoubleSpinBox);
- d->actualMin = minimum;
- d->actualMax = maximum;
- d->setRange(QVariant(d->round(minimum)), QVariant(d->round(maximum)));
-}
-
-/*!
- \property QDoubleSpinBox::decimals
-
- \brief the precision of the spin box, in decimals
-
- Sets how many decimals the spinbox will use for displaying and
- interpreting doubles.
-
- \warning The maximum value for \a decimals is DBL_MAX_10_EXP +
- DBL_DIG (ie. 323) because of the limitations of the double type.
-
- Note: The maximum, minimum and value might change as a result of
- changing this property.
-*/
-
-int QDoubleSpinBox::decimals() const
-{
- Q_D(const QDoubleSpinBox);
-
- return d->decimals;
-}
-
-void QDoubleSpinBox::setDecimals(int decimals)
-{
- Q_D(QDoubleSpinBox);
- d->decimals = qBound(0, decimals, DBL_MAX_10_EXP + DBL_DIG);
-
- setRange(d->actualMin, d->actualMax); // make sure values are rounded
- setValue(value());
-}
-
-/*!
- This virtual function is used by the spin box whenever it needs to
- display the given \a value. The default implementation returns a string
- containing \a value printed using QWidget::locale().toString(\a value,
- QLatin1Char('f'), decimals()) and will remove the thousand
- separator. Reimplementations may return anything.
-
- Note: QDoubleSpinBox does not call this function for
- specialValueText() and that neither prefix() nor suffix() should
- be included in the return value.
-
- If you reimplement this, you may also need to reimplement
- valueFromText().
-
- \sa valueFromText(), QLocale::groupSeparator()
-*/
-
-
-QString QDoubleSpinBox::textFromValue(double value) const
-{
- Q_D(const QDoubleSpinBox);
- QString str = locale().toString(value, 'f', d->decimals);
- if (qAbs(value) >= 1000.0) {
- str.remove(locale().groupSeparator());
- }
- return str;
-}
-
-/*!
- This virtual function is used by the spin box whenever it needs to
- interpret \a text entered by the user as a value.
-
- Subclasses that need to display spin box values in a non-numeric
- way need to reimplement this function.
-
- Note: QDoubleSpinBox handles specialValueText() separately; this
- function is only concerned with the other values.
-
- \sa textFromValue(), validate()
-*/
-double QDoubleSpinBox::valueFromText(const QString &text) const
-{
- Q_D(const QDoubleSpinBox);
-
- QString copy = text;
- int pos = d->edit->cursorPosition();
- QValidator::State state = QValidator::Acceptable;
- return d->validateAndInterpret(copy, pos, state).toDouble();
-}
-
-/*!
- \reimp
-*/
-QValidator::State QDoubleSpinBox::validate(QString &text, int &pos) const
-{
- Q_D(const QDoubleSpinBox);
-
- QValidator::State state;
- d->validateAndInterpret(text, pos, state);
- return state;
-}
-
-
-/*!
- \reimp
-*/
-void QDoubleSpinBox::fixup(QString &input) const
-{
- input.remove(locale().groupSeparator());
-}
-
-// --- QSpinBoxPrivate ---
-
-/*!
- \internal
- Constructs a QSpinBoxPrivate object
-*/
-
-QSpinBoxPrivate::QSpinBoxPrivate()
-{
- minimum = QVariant((int)0);
- maximum = QVariant((int)99);
- value = minimum;
- singleStep = QVariant((int)1);
- type = QVariant::Int;
-}
-
-/*!
- \internal
- \reimp
-*/
-
-void QSpinBoxPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
-{
- Q_Q(QSpinBox);
- if (ep != NeverEmit) {
- pendingEmit = false;
- if (ep == AlwaysEmit || value != old) {
- emit q->valueChanged(edit->displayText());
- emit q->valueChanged(value.toInt());
- }
- }
-}
-
-/*!
- \internal
- \reimp
-*/
-
-QString QSpinBoxPrivate::textFromValue(const QVariant &value) const
-{
- Q_Q(const QSpinBox);
- return q->textFromValue(value.toInt());
-}
-/*!
- \internal
- \reimp
-*/
-
-QVariant QSpinBoxPrivate::valueFromText(const QString &text) const
-{
- Q_Q(const QSpinBox);
-
- return QVariant(q->valueFromText(text));
-}
-
-
-/*!
- \internal Multi purpose function that parses input, sets state to
- the appropriate state and returns the value it will be interpreted
- as.
-*/
-
-QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
- QValidator::State &state) const
-{
- if (cachedText == input && !input.isEmpty()) {
- state = cachedState;
- QSBDEBUG() << "cachedText was '" << cachedText << "' state was "
- << state << " and value was " << cachedValue;
-
- return cachedValue;
- }
- const int max = maximum.toInt();
- const int min = minimum.toInt();
-
- QString copy = stripped(input, &pos);
- QSBDEBUG() << "input" << input << "copy" << copy;
- state = QValidator::Acceptable;
- int num = min;
-
- if (max != min && (copy.isEmpty()
- || (min < 0 && copy == QLatin1String("-"))
- || (min >= 0 && copy == QLatin1String("+")))) {
- state = QValidator::Intermediate;
- QSBDEBUG() << __FILE__ << __LINE__<< "num is set to" << num;
- } else if (copy.startsWith(QLatin1Char('-')) && min >= 0) {
- state = QValidator::Invalid; // special-case -0 will be interpreted as 0 and thus not be invalid with a range from 0-100
- } else {
- bool ok = false;
- num = locale.toInt(copy, &ok, 10);
- if (!ok && copy.contains(locale.groupSeparator()) && (max >= 1000 || min <= -1000)) {
- QString copy2 = copy;
- copy2.remove(locale.groupSeparator());
- num = locale.toInt(copy2, &ok, 10);
- }
- QSBDEBUG() << __FILE__ << __LINE__<< "num is set to" << num;
- if (!ok) {
- state = QValidator::Invalid;
- } else if (num >= min && num <= max) {
- state = QValidator::Acceptable;
- } else if (max == min) {
- state = QValidator::Invalid;
- } else {
- if ((num >= 0 && num > max) || (num < 0 && num < min)) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- } else {
- state = QValidator::Intermediate;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Intermediate";
- }
- }
- }
- if (state != QValidator::Acceptable)
- num = max > 0 ? min : max;
- input = prefix + copy + suffix;
- cachedText = input;
- cachedState = state;
- cachedValue = QVariant((int)num);
-
- QSBDEBUG() << "cachedText is set to '" << cachedText << "' state is set to "
- << state << " and value is set to " << cachedValue;
- return cachedValue;
-}
-
-// --- QDoubleSpinBoxPrivate ---
-
-/*!
- \internal
- Constructs a QSpinBoxPrivate object
-*/
-
-QDoubleSpinBoxPrivate::QDoubleSpinBoxPrivate()
-{
- actualMin = 0.0;
- actualMax = 99.99;
- minimum = QVariant(actualMin);
- maximum = QVariant(actualMax);
- value = minimum;
- singleStep = QVariant(1.0);
- decimals = 2;
- type = QVariant::Double;
-}
-
-/*!
- \internal
- \reimp
-*/
-
-void QDoubleSpinBoxPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
-{
- Q_Q(QDoubleSpinBox);
- if (ep != NeverEmit) {
- pendingEmit = false;
- if (ep == AlwaysEmit || value != old) {
- emit q->valueChanged(edit->displayText());
- emit q->valueChanged(value.toDouble());
- }
- }
-}
-
-
-/*!
- \internal
- \reimp
-*/
-QVariant QDoubleSpinBoxPrivate::valueFromText(const QString &f) const
-{
- Q_Q(const QDoubleSpinBox);
- return QVariant(q->valueFromText(f));
-}
-
-/*!
- \internal
- Rounds to a double value that is restricted to decimals.
- E.g. // decimals = 2
-
- round(5.555) => 5.56
- */
-
-double QDoubleSpinBoxPrivate::round(double value) const
-{
- return QString::number(value, 'f', decimals).toDouble();
-}
-
-
-/*!
- \internal Multi purpose function that parses input, sets state to
- the appropriate state and returns the value it will be interpreted
- as.
-*/
-
-QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
- QValidator::State &state) const
-{
- if (cachedText == input && !input.isEmpty()) {
- state = cachedState;
- QSBDEBUG() << "cachedText was '" << cachedText << "' state was "
- << state << " and value was " << cachedValue;
- return cachedValue;
- }
- const double max = maximum.toDouble();
- const double min = minimum.toDouble();
-
- QString copy = stripped(input, &pos);
- QSBDEBUG() << "input" << input << "copy" << copy;
- int len = copy.size();
- double num = min;
- const bool plus = max >= 0;
- const bool minus = min <= 0;
-
- switch (len) {
- case 0:
- state = max != min ? QValidator::Intermediate : QValidator::Invalid;
- goto end;
- case 1:
- if (copy.at(0) == locale.decimalPoint()
- || (plus && copy.at(0) == QLatin1Char('+'))
- || (minus && copy.at(0) == QLatin1Char('-'))) {
- state = QValidator::Intermediate;
- goto end;
- }
- break;
- case 2:
- if (copy.at(1) == locale.decimalPoint()
- && ((plus && copy.at(0) == QLatin1Char('+')) || (minus && copy.at(0) == QLatin1Char('-')))) {
- state = QValidator::Intermediate;
- goto end;
- }
- break;
- default: break;
- }
-
- if (copy.at(0) == locale.groupSeparator()) {
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- state = QValidator::Invalid;
- goto end;
- } else if (len > 1) {
- const int dec = copy.indexOf(locale.decimalPoint());
- if (dec != -1) {
- if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) {
- copy.remove(dec + 1, 1); // typing a delimiter when you are on the delimiter
- } // should be treated as typing right arrow
-
- if (copy.size() - dec > decimals + 1) {
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- state = QValidator::Invalid;
- goto end;
- }
- for (int i=dec + 1; i<copy.size(); ++i) {
- if (copy.at(i).isSpace() || copy.at(i) == locale.groupSeparator()) {
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- state = QValidator::Invalid;
- goto end;
- }
- }
- } else {
- const QChar &last = copy.at(len - 1);
- const QChar &secondLast = copy.at(len - 2);
- if ((last == locale.groupSeparator() || last.isSpace())
- && (secondLast == locale.groupSeparator() || secondLast.isSpace())) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- goto end;
- } else if (last.isSpace() && (!locale.groupSeparator().isSpace() || secondLast.isSpace())) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- goto end;
- }
- }
- }
-
- {
- bool ok = false;
- num = locale.toDouble(copy, &ok);
- QSBDEBUG() << __FILE__ << __LINE__ << locale << copy << num << ok;
-
- if (!ok) {
- if (locale.groupSeparator().isPrint()) {
- if (max < 1000 && min > -1000 && copy.contains(locale.groupSeparator())) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- goto end;
- }
-
- const int len = copy.size();
- for (int i=0; i<len- 1; ++i) {
- if (copy.at(i) == locale.groupSeparator() && copy.at(i + 1) == locale.groupSeparator()) {
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- state = QValidator::Invalid;
- goto end;
- }
- }
-
- QString copy2 = copy;
- copy2.remove(locale.groupSeparator());
- num = locale.toDouble(copy2, &ok);
- QSBDEBUG() << locale.groupSeparator() << num << copy2 << ok;
-
- if (!ok) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- goto end;
- }
- }
- }
-
- if (!ok) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- } else if (num >= min && num <= max) {
- state = QValidator::Acceptable;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Acceptable";
- } else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- } else {
- if ((num >= 0 && num > max) || (num < 0 && num < min)) {
- state = QValidator::Invalid;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Invalid";
- } else {
- state = QValidator::Intermediate;
- QSBDEBUG() << __FILE__ << __LINE__<< "state is set to Intermediate";
- }
- }
- }
-
-end:
- if (state != QValidator::Acceptable) {
- num = max > 0 ? min : max;
- }
-
- input = prefix + copy + suffix;
- cachedText = input;
- cachedState = state;
- cachedValue = QVariant(num);
- return QVariant(num);
-}
-
-/*
- \internal
- \reimp
-*/
-
-QString QDoubleSpinBoxPrivate::textFromValue(const QVariant &f) const
-{
- Q_Q(const QDoubleSpinBox);
- return q->textFromValue(f.toDouble());
-}
-
-/*!
- \fn void QSpinBox::setLineStep(int step)
-
- Use setSingleStep() instead.
-*/
-
-/*!
- \fn void QSpinBox::setMaxValue(int value)
-
- Use setMaximum() instead.
-*/
-
-/*!
- \fn void QSpinBox::setMinValue(int value)
-
- Use setMinimum() instead.
-*/
-
-/*!
- \fn int QSpinBox::maxValue() const
-
- Use maximum() instead.
-*/
-
-/*!
- \fn int QSpinBox::minValue() const
-
- Use minimum() instead.
-*/
-
-/*! \reimp */
-bool QSpinBox::event(QEvent *event)
-{
- Q_D(QSpinBox);
- if (event->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || event->type() == QEvent::MacSizeChange
-#endif
- )
- d->setLayoutItemMargins(QStyle::SE_SpinBoxLayoutItem);
- return QAbstractSpinBox::event(event);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SPINBOX
diff --git a/src/gui/widgets/qspinbox.h b/src/gui/widgets/qspinbox.h
deleted file mode 100644
index 8c9f67b29c..0000000000
--- a/src/gui/widgets/qspinbox.h
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** 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 QSPINBOX_H
-#define QSPINBOX_H
-
-#include <QtGui/qabstractspinbox.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SPINBOX
-
-class QSpinBoxPrivate;
-class Q_GUI_EXPORT QSpinBox : public QAbstractSpinBox
-{
- Q_OBJECT
-
- Q_PROPERTY(QString suffix READ suffix WRITE setSuffix)
- Q_PROPERTY(QString prefix READ prefix WRITE setPrefix)
- Q_PROPERTY(QString cleanText READ cleanText)
- Q_PROPERTY(int minimum READ minimum WRITE setMinimum)
- Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
- Q_PROPERTY(int singleStep READ singleStep WRITE setSingleStep)
- Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged USER true)
-
-public:
- explicit QSpinBox(QWidget *parent = 0);
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QSpinBox(QWidget *parent, const char *name);
- QT3_SUPPORT_CONSTRUCTOR QSpinBox(int min, int max, int step, QWidget *parent,
- const char *name = 0);
-#endif
-
- int value() const;
-
- QString prefix() const;
- void setPrefix(const QString &prefix);
-
- QString suffix() const;
- void setSuffix(const QString &suffix);
-
- QString cleanText() const;
-
- int singleStep() const;
- void setSingleStep(int val);
-
- int minimum() const;
- void setMinimum(int min);
-
- int maximum() const;
- void setMaximum(int max);
-
- void setRange(int min, int max);
-
-#ifdef QT3_SUPPORT
- inline QT3_SUPPORT void setLineStep(int step) { setSingleStep(step); }
- inline QT3_SUPPORT void setMaxValue(int val) { setMaximum(val); }
- inline QT3_SUPPORT void setMinValue(int val) { setMinimum(val); }
- inline QT3_SUPPORT int maxValue() const { return maximum(); }
- inline QT3_SUPPORT int minValue() const { return minimum(); }
-#endif
-
-protected:
- bool event(QEvent *event);
- virtual QValidator::State validate(QString &input, int &pos) const;
- virtual int valueFromText(const QString &text) const;
- virtual QString textFromValue(int val) const;
- virtual void fixup(QString &str) const;
-
-
-public Q_SLOTS:
- void setValue(int val);
-
-Q_SIGNALS:
- void valueChanged(int);
- void valueChanged(const QString &);
-
-private:
- Q_DISABLE_COPY(QSpinBox)
- Q_DECLARE_PRIVATE(QSpinBox)
-};
-
-class QDoubleSpinBoxPrivate;
-class Q_GUI_EXPORT QDoubleSpinBox : public QAbstractSpinBox
-{
- Q_OBJECT
-
- Q_PROPERTY(QString prefix READ prefix WRITE setPrefix)
- Q_PROPERTY(QString suffix READ suffix WRITE setSuffix)
- Q_PROPERTY(QString cleanText READ cleanText)
- Q_PROPERTY(int decimals READ decimals WRITE setDecimals)
- Q_PROPERTY(double minimum READ minimum WRITE setMinimum)
- Q_PROPERTY(double maximum READ maximum WRITE setMaximum)
- Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep)
- Q_PROPERTY(double value READ value WRITE setValue NOTIFY valueChanged USER true)
-public:
- explicit QDoubleSpinBox(QWidget *parent = 0);
-
- double value() const;
-
- QString prefix() const;
- void setPrefix(const QString &prefix);
-
- QString suffix() const;
- void setSuffix(const QString &suffix);
-
- QString cleanText() const;
-
- double singleStep() const;
- void setSingleStep(double val);
-
- double minimum() const;
- void setMinimum(double min);
-
- double maximum() const;
- void setMaximum(double max);
-
- void setRange(double min, double max);
-
- int decimals() const;
- void setDecimals(int prec);
-
- virtual QValidator::State validate(QString &input, int &pos) const;
- virtual double valueFromText(const QString &text) const;
- virtual QString textFromValue(double val) const;
- virtual void fixup(QString &str) const;
-
-public Q_SLOTS:
- void setValue(double val);
-
-Q_SIGNALS:
- void valueChanged(double);
- void valueChanged(const QString &);
-
-private:
- Q_DISABLE_COPY(QDoubleSpinBox)
- Q_DECLARE_PRIVATE(QDoubleSpinBox)
-};
-
-#endif // QT_NO_SPINBOX
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSPINBOX_H
diff --git a/src/gui/widgets/qsplashscreen.cpp b/src/gui/widgets/qsplashscreen.cpp
deleted file mode 100644
index 9c486bfca4..0000000000
--- a/src/gui/widgets/qsplashscreen.cpp
+++ /dev/null
@@ -1,330 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsplashscreen.h"
-
-#ifndef QT_NO_SPLASHSCREEN
-
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qpainter.h"
-#include "qpixmap.h"
-#include "qtextdocument.h"
-#include "qtextcursor.h"
-#include <QtCore/qdebug.h>
-#include <private/qwidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSplashScreenPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QSplashScreen)
-public:
- QPixmap pixmap;
- QString currStatus;
- QColor currColor;
- int currAlign;
-
- inline QSplashScreenPrivate();
-};
-
-/*!
- \class QSplashScreen
- \brief The QSplashScreen widget provides a splash screen that can
- be shown during application startup.
-
- A splash screen is a widget that is usually displayed when an
- application is being started. Splash screens are often used for
- applications that have long start up times (e.g. database or
- networking applications that take time to establish connections) to
- provide the user with feedback that the application is loading.
-
- The splash screen appears in the center of the screen. It may be
- useful to add the Qt::WindowStaysOnTopHint to the splash widget's
- window flags if you want to keep it above all the other windows on
- the desktop.
-
- Some X11 window managers do not support the "stays on top" flag. A
- solution is to set up a timer that periodically calls raise() on
- the splash screen to simulate the "stays on top" effect.
-
- The most common usage is to show a splash screen before the main
- widget is displayed on the screen. This is illustrated in the
- following code snippet in which a splash screen is displayed and
- some initialization tasks are performed before the application's
- main window is shown:
-
- \snippet doc/src/snippets/qsplashscreen/main.cpp 0
- \dots
- \snippet doc/src/snippets/qsplashscreen/main.cpp 1
-
- The user can hide the splash screen by clicking on it with the
- mouse. Since the splash screen is typically displayed before the
- event loop has started running, it is necessary to periodically
- call QApplication::processEvents() to receive the mouse clicks.
-
- It is sometimes useful to update the splash screen with messages,
- for example, announcing connections established or modules loaded
- as the application starts up:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qsplashscreen.cpp 0
-
- QSplashScreen supports this with the showMessage() function. If you
- wish to do your own drawing you can get a pointer to the pixmap
- used in the splash screen with pixmap(). Alternatively, you can
- subclass QSplashScreen and reimplement drawContents().
-*/
-
-/*!
- Construct a splash screen that will display the \a pixmap.
-
- There should be no need to set the widget flags, \a f, except
- perhaps Qt::WindowStaysOnTopHint.
-*/
-QSplashScreen::QSplashScreen(const QPixmap &pixmap, Qt::WindowFlags f)
- : QWidget(*(new QSplashScreenPrivate()), 0, Qt::SplashScreen | Qt::FramelessWindowHint | f)
-{
- setPixmap(pixmap); // Does an implicit repaint
-}
-
-/*!
- \overload
-
- This function allows you to specify a parent for your splashscreen. The
- typical use for this constructor is if you have a multiple screens and
- prefer to have the splash screen on a different screen than your primary
- one. In that case pass the proper desktop() as the \a parent.
-*/
-QSplashScreen::QSplashScreen(QWidget *parent, const QPixmap &pixmap, Qt::WindowFlags f)
- : QWidget(*new QSplashScreenPrivate, parent, Qt::SplashScreen | f)
-{
- d_func()->pixmap = pixmap;
- setPixmap(d_func()->pixmap); // Does an implicit repaint
-}
-
-/*!
- Destructor.
-*/
-QSplashScreen::~QSplashScreen()
-{
-}
-
-/*!
- \reimp
-*/
-void QSplashScreen::mousePressEvent(QMouseEvent *)
-{
- hide();
-}
-
-/*!
- This overrides QWidget::repaint(). It differs from the standard
- repaint function in that it also calls QApplication::flush() to
- ensure the updates are displayed, even when there is no event loop
- present.
-*/
-void QSplashScreen::repaint()
-{
- QWidget::repaint();
- QApplication::flush();
-}
-
-/*!
- \fn QSplashScreen::messageChanged(const QString &message)
-
- This signal is emitted when the message on the splash screen
- changes. \a message is the new message and is a null-string
- when the message has been removed.
-
- \sa showMessage(), clearMessage()
-*/
-
-
-
-/*!
- Draws the \a message text onto the splash screen with color \a
- color and aligns the text according to the flags in \a alignment.
-
- To make sure the splash screen is repainted immediately, you can
- call \l{QCoreApplication}'s
- \l{QCoreApplication::}{processEvents()} after the call to
- showMessage(). You usually want this to make sure that the message
- is kept up to date with what your application is doing (e.g.,
- loading files).
-
- \sa Qt::Alignment, clearMessage()
-*/
-void QSplashScreen::showMessage(const QString &message, int alignment,
- const QColor &color)
-{
- Q_D(QSplashScreen);
- d->currStatus = message;
- d->currAlign = alignment;
- d->currColor = color;
- emit messageChanged(d->currStatus);
- repaint();
-}
-
-/*!
- Removes the message being displayed on the splash screen
-
- \sa showMessage()
- */
-void QSplashScreen::clearMessage()
-{
- d_func()->currStatus.clear();
- emit messageChanged(d_func()->currStatus);
- repaint();
-}
-
-/*!
- Makes the splash screen wait until the widget \a mainWin is displayed
- before calling close() on itself.
-*/
-void QSplashScreen::finish(QWidget *mainWin)
-{
- if (mainWin) {
-#if defined(Q_WS_X11)
- extern void qt_x11_wait_for_window_manager(QWidget *mainWin, bool);
- qt_x11_wait_for_window_manager(mainWin, false);
-#endif
- }
- close();
-}
-
-/*!
- Sets the pixmap that will be used as the splash screen's image to
- \a pixmap.
-*/
-void QSplashScreen::setPixmap(const QPixmap &pixmap)
-{
- Q_D(QSplashScreen);
-
- d->pixmap = pixmap;
- setAttribute(Qt::WA_TranslucentBackground, pixmap.hasAlpha());
-
- QRect r(QPoint(), d->pixmap.size());
- resize(r.size());
- move(QApplication::desktop()->screenGeometry().center() - r.center());
- if (isVisible())
- repaint();
-}
-
-/*!
- Returns the pixmap that is used in the splash screen. The image
- does not have any of the text drawn by showMessage() calls.
-*/
-const QPixmap QSplashScreen::pixmap() const
-{
- return d_func()->pixmap;
-}
-
-/*!
- \internal
-*/
-inline QSplashScreenPrivate::QSplashScreenPrivate() : currAlign(Qt::AlignLeft)
-{
-}
-
-/*!
- Draw the contents of the splash screen using painter \a painter.
- The default implementation draws the message passed by showMessage().
- Reimplement this function if you want to do your own drawing on
- the splash screen.
-*/
-void QSplashScreen::drawContents(QPainter *painter)
-{
- Q_D(QSplashScreen);
- painter->setPen(d->currColor);
- QRect r = rect().adjusted(5, 5, -5, -5);
- if (Qt::mightBeRichText(d->currStatus)) {
- QTextDocument doc;
-#ifdef QT_NO_TEXTHTMLPARSER
- doc.setPlainText(d->currStatus);
-#else
- doc.setHtml(d->currStatus);
-#endif
- doc.setTextWidth(r.width());
- QTextCursor cursor(&doc);
- cursor.select(QTextCursor::Document);
- QTextBlockFormat fmt;
- fmt.setAlignment(Qt::Alignment(d->currAlign));
- cursor.mergeBlockFormat(fmt);
- painter->save();
- painter->translate(r.topLeft());
- doc.drawContents(painter);
- painter->restore();
- } else {
- painter->drawText(r, d->currAlign, d->currStatus);
- }
-}
-
-/*!
- \fn void QSplashScreen::message(const QString &message, int alignment,
- const QColor &color)
- \compat
-
- Use showMessage() instead.
-*/
-
-/*!
- \fn void QSplashScreen::clear()
- \compat
-
- Use clearMessage() instead.
-*/
-
-/*! \reimp */
-bool QSplashScreen::event(QEvent *e)
-{
- if (e->type() == QEvent::Paint) {
- Q_D(QSplashScreen);
- QPainter painter(this);
- if (!d->pixmap.isNull())
- painter.drawPixmap(QPoint(), d->pixmap);
- drawContents(&painter);
- }
- return QWidget::event(e);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_SPLASHSCREEN
diff --git a/src/gui/widgets/qsplashscreen.h b/src/gui/widgets/qsplashscreen.h
deleted file mode 100644
index 588054f196..0000000000
--- a/src/gui/widgets/qsplashscreen.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** 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 QSPLASHSCREEN_H
-#define QSPLASHSCREEN_H
-
-#include <QtGui/qpixmap.h>
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SPLASHSCREEN
-class QSplashScreenPrivate;
-
-class Q_GUI_EXPORT QSplashScreen : public QWidget
-{
- Q_OBJECT
-public:
- explicit QSplashScreen(const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = 0);
- QSplashScreen(QWidget *parent, const QPixmap &pixmap = QPixmap(), Qt::WindowFlags f = 0);
- virtual ~QSplashScreen();
-
- void setPixmap(const QPixmap &pixmap);
- const QPixmap pixmap() const;
- void finish(QWidget *w);
- void repaint();
-
-public Q_SLOTS:
- void showMessage(const QString &message, int alignment = Qt::AlignLeft,
- const QColor &color = Qt::black);
- void clearMessage();
-#ifdef QT3_SUPPORT
- inline QT_MOC_COMPAT void message(const QString &str, int alignment = Qt::AlignLeft,
- const QColor &color = Qt::black) { showMessage(str, alignment, color); }
- inline QT_MOC_COMPAT void clear() { clearMessage(); }
-#endif
-
-Q_SIGNALS:
- void messageChanged(const QString &message);
-
-protected:
- bool event(QEvent *e);
- virtual void drawContents(QPainter *painter);
- void mousePressEvent(QMouseEvent *);
-
-private:
- Q_DISABLE_COPY(QSplashScreen)
- Q_DECLARE_PRIVATE(QSplashScreen)
-};
-
-#endif // QT_NO_SPLASHSCREEN
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSPLASHSCREEN_H
diff --git a/src/gui/widgets/qsplitter.cpp b/src/gui/widgets/qsplitter.cpp
deleted file mode 100644
index ca8fc3757a..0000000000
--- a/src/gui/widgets/qsplitter.cpp
+++ /dev/null
@@ -1,1877 +0,0 @@
-/****************************************************************************
-**
-** 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 "qsplitter.h"
-#ifndef QT_NO_SPLITTER
-
-#include "qapplication.h"
-#include "qcursor.h"
-#include "qdrawutil.h"
-#include "qevent.h"
-#include "qlayout.h"
-#include "qlist.h"
-#include "qpainter.h"
-#include "qrubberband.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qtextstream.h"
-#include "qvarlengtharray.h"
-#include "qvector.h"
-#include "private/qlayoutengine_p.h"
-#include "private/qsplitter_p.h"
-#include "qtimer.h"
-#include "qdebug.h"
-
-#include <ctype.h>
-
-QT_BEGIN_NAMESPACE
-
-//#define QSPLITTER_DEBUG
-
-/*!
- \class QSplitterHandle
- \brief The QSplitterHandle class provides handle functionality of the splitter.
-
- \ingroup organizers
-
- QSplitterHandle is typically what people think about when they think about
- a splitter. It is the handle that is used to resize the widgets.
-
- A typical developer using QSplitter will never have to worry about
- QSplitterHandle. It is provided for developers who want splitter handles
- that provide extra features, such as popup menus.
-
- The typical way one would create splitter handles is to subclass QSplitter then
- reimplement QSplitter::createHandle() to instantiate the custom splitter
- handle. For example, a minimum QSplitter subclass might look like this:
-
- \snippet doc/src/snippets/splitterhandle/splitter.h 0
-
- The \l{QSplitter::}{createHandle()} implementation simply constructs a
- custom splitter handle, called \c Splitter in this example:
-
- \snippet doc/src/snippets/splitterhandle/splitter.cpp 1
-
- Information about a given handle can be obtained using functions like
- orientation() and opaqueResize(), and is retrieved from its parent splitter.
- Details like these can be used to give custom handles different appearances
- depending on the splitter's orientation.
-
- The complexity of a custom handle subclass depends on the tasks that it
- needs to perform. A simple subclass might only provide a paintEvent()
- implementation:
-
- \snippet doc/src/snippets/splitterhandle/splitter.cpp 0
-
- In this example, a predefined gradient is set up differently depending on
- the orientation of the handle. QSplitterHandle provides a reasonable
- size hint for the handle, so the subclass does not need to provide a
- reimplementation of sizeHint() unless the handle has special size
- requirements.
-
- \sa QSplitter
-*/
-
-/*!
- Creates a QSplitter handle with the given \a orientation and
- QSplitter \a parent.
-*/
-QSplitterHandle::QSplitterHandle(Qt::Orientation orientation, QSplitter *parent)
- : QWidget(*new QSplitterHandlePrivate, parent, 0)
-{
- Q_D(QSplitterHandle);
- d->s = parent;
- setOrientation(orientation);
-}
-
-/*!
- Sets the orientation of the splitter handle to \a orientation.
- This is usually propagated from the QSplitter.
-
- \sa QSplitter::setOrientation()
-*/
-void QSplitterHandle::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QSplitterHandle);
- d->orient = orientation;
-#ifndef QT_NO_CURSOR
- setCursor(orientation == Qt::Horizontal ? Qt::SplitHCursor : Qt::SplitVCursor);
-#endif
-}
-
-/*!
- Returns the handle's orientation. This is usually propagated from the QSplitter.
-
- \sa QSplitter::orientation()
-*/
-Qt::Orientation QSplitterHandle::orientation() const
-{
- Q_D(const QSplitterHandle);
- return d->orient;
-}
-
-
-/*!
- Returns true if widgets are resized dynamically (opaquely), otherwise
- returns false. This value is controlled by the QSplitter.
-
- \sa QSplitter::opaqueResize()
-
-*/
-bool QSplitterHandle::opaqueResize() const
-{
- Q_D(const QSplitterHandle);
- return d->s->opaqueResize();
-}
-
-
-/*!
- Returns the splitter associated with this splitter handle.
-
- \sa QSplitter::handle()
-*/
-QSplitter *QSplitterHandle::splitter() const
-{
- return d_func()->s;
-}
-
-/*!
- Tells the splitter to move this handle to position \a pos, which is
- the distance from the left or top edge of the widget.
-
- Note that \a pos is also measured from the left (or top) for
- right-to-left languages. This function will map \a pos to the
- appropriate position before calling QSplitter::moveSplitter().
-
- \sa QSplitter::moveSplitter() closestLegalPosition()
-*/
-void QSplitterHandle::moveSplitter(int pos)
-{
- Q_D(QSplitterHandle);
- if (d->s->isRightToLeft() && d->orient == Qt::Horizontal)
- pos = d->s->contentsRect().width() - pos;
- d->s->moveSplitter(pos, d->s->indexOf(this));
-}
-
-/*!
- Returns the closest legal position to \a pos of the splitter
- handle. The positions are measured from the left or top edge of
- the splitter, even for right-to-left languages.
-
- \sa QSplitter::closestLegalPosition(), moveSplitter()
-*/
-
-int QSplitterHandle::closestLegalPosition(int pos)
-{
- Q_D(QSplitterHandle);
- QSplitter *s = d->s;
- if (s->isRightToLeft() && d->orient == Qt::Horizontal) {
- int w = s->contentsRect().width();
- return w - s->closestLegalPosition(w - pos, s->indexOf(this));
- }
- return s->closestLegalPosition(pos, s->indexOf(this));
-}
-
-/*!
- \reimp
-*/
-QSize QSplitterHandle::sizeHint() const
-{
- Q_D(const QSplitterHandle);
- int hw = d->s->handleWidth();
- QStyleOption opt(0);
- opt.init(d->s);
- opt.state = QStyle::State_None;
- return parentWidget()->style()->sizeFromContents(QStyle::CT_Splitter, &opt, QSize(hw, hw), d->s)
- .expandedTo(QApplication::globalStrut());
-}
-
-/*!
- \reimp
-*/
-void QSplitterHandle::resizeEvent(QResizeEvent *event)
-{
- Q_D(const QSplitterHandle);
-
- // When splitters are only 1 pixel large we increase the
- // actual grab area to five pixels
-
- // Note that QSplitter uses contentsRect for layouting
- // and ensures that handles are drawn on top of widgets
- // We simply use the contents margins for draggin and only
- // paint the mask area
- bool useTinyMode = (d->s->handleWidth() == 1);
- setAttribute(Qt::WA_MouseNoMask, useTinyMode);
- if (useTinyMode) {
- if (orientation() == Qt::Horizontal)
- setContentsMargins(2, 0, 2, 0);
- else
- setContentsMargins(0, 2, 0, 2);
- setMask(QRegion(contentsRect()));
- }
-
- QWidget::resizeEvent(event);
-}
-
-/*!
- \reimp
-*/
-bool QSplitterHandle::event(QEvent *event)
-{
- Q_D(QSplitterHandle);
- switch(event->type()) {
- case QEvent::HoverEnter:
- d->hover = true;
- update();
- break;
- case QEvent::HoverLeave:
- d->hover = false;
- update();
- break;
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-/*!
- \reimp
-*/
-void QSplitterHandle::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QSplitterHandle);
- if (!(e->buttons() & Qt::LeftButton))
- return;
- int pos = d->pick(parentWidget()->mapFromGlobal(e->globalPos()))
- - d->mouseOffset;
- if (opaqueResize()) {
- moveSplitter(pos);
- } else {
- d->s->setRubberBand(closestLegalPosition(pos));
- }
-}
-
-/*!
- \reimp
-*/
-void QSplitterHandle::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QSplitterHandle);
- if (e->button() == Qt::LeftButton) {
- d->mouseOffset = d->pick(e->pos());
- d->pressed = true;
- update();
- }
-}
-
-/*!
- \reimp
-*/
-void QSplitterHandle::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QSplitterHandle);
- if (!opaqueResize() && e->button() == Qt::LeftButton) {
- int pos = d->pick(parentWidget()->mapFromGlobal(e->globalPos()))
- - d->mouseOffset;
- d->s->setRubberBand(-1);
- moveSplitter(pos);
- }
- if (e->button() == Qt::LeftButton) {
- d->pressed = false;
- update();
- }
-}
-
-/*!
- \reimp
-*/
-void QSplitterHandle::paintEvent(QPaintEvent *)
-{
- Q_D(QSplitterHandle);
- QPainter p(this);
- QStyleOption opt(0);
- opt.rect = contentsRect();
- opt.palette = palette();
- if (orientation() == Qt::Horizontal)
- opt.state = QStyle::State_Horizontal;
- else
- opt.state = QStyle::State_None;
- if (d->hover)
- opt.state |= QStyle::State_MouseOver;
- if (d->pressed)
- opt.state |= QStyle::State_Sunken;
- if (isEnabled())
- opt.state |= QStyle::State_Enabled;
- parentWidget()->style()->drawControl(QStyle::CE_Splitter, &opt, &p, d->s);
-}
-
-
-int QSplitterLayoutStruct::getWidgetSize(Qt::Orientation orient)
-{
- if (sizer == -1) {
- QSize s = widget->sizeHint();
- const int presizer = pick(s, orient);
- const int realsize = pick(widget->size(), orient);
- if (!s.isValid() || (widget->testAttribute(Qt::WA_Resized) && (realsize > presizer))) {
- sizer = pick(widget->size(), orient);
- } else {
- sizer = presizer;
- }
- QSizePolicy p = widget->sizePolicy();
- int sf = (orient == Qt::Horizontal) ? p.horizontalStretch() : p.verticalStretch();
- if (sf > 1)
- sizer *= sf;
- }
- return sizer;
-}
-
-int QSplitterLayoutStruct::getHandleSize(Qt::Orientation orient)
-{
- return pick(handle->sizeHint(), orient);
-}
-
-void QSplitterPrivate::init()
-{
- Q_Q(QSplitter);
- QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Preferred);
- if (orient == Qt::Vertical)
- sp.transpose();
- q->setSizePolicy(sp);
- q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
-}
-
-void QSplitterPrivate::recalc(bool update)
-{
- Q_Q(QSplitter);
- int n = list.count();
- /*
- Splitter handles before the first visible widget or right
- before a hidden widget must be hidden.
- */
- bool first = true;
- bool allInvisible = n != 0;
- for (int i = 0; i < n ; ++i) {
- QSplitterLayoutStruct *s = list.at(i);
- bool widgetHidden = s->widget->isHidden();
- if (allInvisible && !widgetHidden && !s->collapsed)
- allInvisible = false;
- s->handle->setHidden(first || widgetHidden);
- if (!widgetHidden)
- first = false;
- }
-
- if (allInvisible)
- for (int i = 0; i < n ; ++i) {
- QSplitterLayoutStruct *s = list.at(i);
- if (!s->widget->isHidden()) {
- s->collapsed = false;
- break;
- }
- }
-
- int fi = 2 * q->frameWidth();
- int maxl = fi;
- int minl = fi;
- int maxt = QWIDGETSIZE_MAX;
- int mint = fi;
- /*
- calculate min/max sizes for the whole splitter
- */
- bool empty = true;
- for (int j = 0; j < n; j++) {
- QSplitterLayoutStruct *s = list.at(j);
-
- if (!s->widget->isHidden()) {
- empty = false;
- if (!s->handle->isHidden()) {
- minl += s->getHandleSize(orient);
- maxl += s->getHandleSize(orient);
- }
-
- QSize minS = qSmartMinSize(s->widget);
- minl += pick(minS);
- maxl += pick(s->widget->maximumSize());
- mint = qMax(mint, trans(minS));
- int tm = trans(s->widget->maximumSize());
- if (tm > 0)
- maxt = qMin(maxt, tm);
- }
- }
-
- if (empty) {
- if (qobject_cast<QSplitter *>(parent)) {
- // nested splitters; be nice
- maxl = maxt = 0;
- } else {
- // QSplitter with no children yet
- maxl = QWIDGETSIZE_MAX;
- }
- } else {
- maxl = qMin<int>(maxl, QWIDGETSIZE_MAX);
- }
- if (maxt < mint)
- maxt = mint;
-
- if (update) {
- if (orient == Qt::Horizontal) {
- q->setMaximumSize(maxl, maxt);
- if (q->isWindow())
- q->setMinimumSize(minl,mint);
- } else {
- q->setMaximumSize(maxt, maxl);
- if (q->isWindow())
- q->setMinimumSize(mint,minl);
- }
- doResize();
- q->updateGeometry();
- } else {
- firstShow = true;
- }
-}
-
-void QSplitterPrivate::doResize()
-{
- Q_Q(QSplitter);
- QRect r = q->contentsRect();
- int n = list.count();
- QVector<QLayoutStruct> a(n*2);
- int i;
-
- bool noStretchFactorsSet = true;
- for (i = 0; i < n; ++i) {
- QSizePolicy p = list.at(i)->widget->sizePolicy();
- int sf = orient == Qt::Horizontal ? p.horizontalStretch() : p.verticalStretch();
- if (sf != 0) {
- noStretchFactorsSet = false;
- break;
- }
- }
-
- int j=0;
- for (i = 0; i < n; ++i) {
- QSplitterLayoutStruct *s = list.at(i);
-#ifdef QSPLITTER_DEBUG
- qDebug("widget %d hidden: %d collapsed: %d handle hidden: %d", i, s->widget->isHidden(),
- s->collapsed, s->handle->isHidden());
-#endif
-
- a[j].init();
- if (s->handle->isHidden()) {
- a[j].maximumSize = 0;
- } else {
- a[j].sizeHint = a[j].minimumSize = a[j].maximumSize = s->getHandleSize(orient);
- a[j].empty = false;
- }
- ++j;
-
- a[j].init();
- if (s->widget->isHidden() || s->collapsed) {
- a[j].maximumSize = 0;
- } else {
- a[j].minimumSize = pick(qSmartMinSize(s->widget));
- a[j].maximumSize = pick(s->widget->maximumSize());
- a[j].empty = false;
-
- bool stretch = noStretchFactorsSet;
- if (!stretch) {
- QSizePolicy p = s->widget->sizePolicy();
- int sf = orient == Qt::Horizontal ? p.horizontalStretch() : p.verticalStretch();
- stretch = (sf != 0);
- }
- if (stretch) {
- a[j].stretch = s->getWidgetSize(orient);
- a[j].sizeHint = a[j].minimumSize;
- a[j].expansive = true;
- } else {
- a[j].sizeHint = qMax(s->getWidgetSize(orient), a[j].minimumSize);
- }
- }
- ++j;
- }
-
- qGeomCalc(a, 0, n*2, pick(r.topLeft()), pick(r.size()), 0);
-
-#ifdef QSPLITTER_DEBUG
- for (i = 0; i < n*2; ++i) {
- qDebug("%*s%d: stretch %d, sh %d, minS %d, maxS %d, exp %d, emp %d -> %d, %d",
- i, "", i,
- a[i].stretch,
- a[i].sizeHint,
- a[i].minimumSize,
- a[i].maximumSize,
- a[i].expansive,
- a[i].empty,
- a[i].pos,
- a[i].size);
- }
-#endif
-
- for (i = 0; i < n; ++i) {
- QSplitterLayoutStruct *s = list.at(i);
- setGeo(s, a[i*2+1].pos, a[i*2+1].size, false);
- }
-}
-
-void QSplitterPrivate::storeSizes()
-{
- for (int i = 0; i < list.size(); ++i) {
- QSplitterLayoutStruct *sls = list.at(i);
- sls->sizer = pick(sls->rect.size());
- }
-}
-
-void QSplitterPrivate::addContribution(int index, int *min, int *max, bool mayCollapse) const
-{
- QSplitterLayoutStruct *s = list.at(index);
- if (!s->widget->isHidden()) {
- if (!s->handle->isHidden()) {
- *min += s->getHandleSize(orient);
- *max += s->getHandleSize(orient);
- }
- if (mayCollapse || !s->collapsed)
- *min += pick(qSmartMinSize(s->widget));
-
- *max += pick(s->widget->maximumSize());
- }
-}
-
-int QSplitterPrivate::findWidgetJustBeforeOrJustAfter(int index, int delta, int &collapsibleSize) const
-{
- if (delta < 0)
- index += delta;
- do {
- QWidget *w = list.at(index)->widget;
- if (!w->isHidden()) {
- if (collapsible(list.at(index)))
- collapsibleSize = pick(qSmartMinSize(w));
- return index;
- }
- index += delta;
- } while (index >= 0 && index < list.count());
-
- return -1;
-}
-
-/*
- For the splitter handle with index \a index, \a min and \a max give the range without collapsing any widgets,
- and \a farMin and farMax give the range with collapsing included.
-*/
-void QSplitterPrivate::getRange(int index, int *farMin, int *min, int *max, int *farMax) const
-{
- Q_Q(const QSplitter);
- int n = list.count();
- if (index <= 0 || index >= n)
- return;
-
- int collapsibleSizeBefore = 0;
- int idJustBefore = findWidgetJustBeforeOrJustAfter(index, -1, collapsibleSizeBefore);
-
- int collapsibleSizeAfter = 0;
- int idJustAfter = findWidgetJustBeforeOrJustAfter(index, +1, collapsibleSizeAfter);
-
- int minBefore = 0;
- int minAfter = 0;
- int maxBefore = 0;
- int maxAfter = 0;
- int i;
-
- for (i = 0; i < index; ++i)
- addContribution(i, &minBefore, &maxBefore, i == idJustBefore);
- for (i = index; i < n; ++i)
- addContribution(i, &minAfter, &maxAfter, i == idJustAfter);
-
- QRect r = q->contentsRect();
- int farMinVal;
- int minVal;
- int maxVal;
- int farMaxVal;
-
- int smartMinBefore = qMax(minBefore, pick(r.size()) - maxAfter);
- int smartMaxBefore = qMin(maxBefore, pick(r.size()) - minAfter);
-
- minVal = pick(r.topLeft()) + smartMinBefore;
- maxVal = pick(r.topLeft()) + smartMaxBefore;
-
- farMinVal = minVal;
- if (minBefore - collapsibleSizeBefore >= pick(r.size()) - maxAfter)
- farMinVal -= collapsibleSizeBefore;
- farMaxVal = maxVal;
- if (pick(r.size()) - (minAfter - collapsibleSizeAfter) <= maxBefore)
- farMaxVal += collapsibleSizeAfter;
-
- if (farMin)
- *farMin = farMinVal;
- if (min)
- *min = minVal;
- if (max)
- *max = maxVal;
- if (farMax)
- *farMax = farMaxVal;
-}
-
-int QSplitterPrivate::adjustPos(int pos, int index, int *farMin, int *min, int *max, int *farMax) const
-{
- const int Threshold = 40;
-
- getRange(index, farMin, min, max, farMax);
-
- if (pos >= *min) {
- if (pos <= *max) {
- return pos;
- } else {
- int delta = pos - *max;
- int width = *farMax - *max;
-
- if (delta > width / 2 && delta >= qMin(Threshold, width)) {
- return *farMax;
- } else {
- return *max;
- }
- }
- } else {
- int delta = *min - pos;
- int width = *min - *farMin;
-
- if (delta > width / 2 && delta >= qMin(Threshold, width)) {
- return *farMin;
- } else {
- return *min;
- }
- }
-}
-
-bool QSplitterPrivate::collapsible(QSplitterLayoutStruct *s) const
-{
- if (s->collapsible != Default) {
- return (bool)s->collapsible;
- } else {
- return childrenCollapsible;
- }
-}
-
-void QSplitterPrivate::updateHandles()
-{
- Q_Q(QSplitter);
- recalc(q->isVisible());
-}
-
-void QSplitterPrivate::setSizes_helper(const QList<int> &sizes, bool clampNegativeSize)
-{
- int j = 0;
-
- for (int i = 0; i < list.size(); ++i) {
- QSplitterLayoutStruct *s = list.at(i);
-
- s->collapsed = false;
- s->sizer = sizes.value(j++);
- if (clampNegativeSize && s->sizer < 0)
- s->sizer = 0;
- int smartMinSize = pick(qSmartMinSize(s->widget));
-
- // Make sure that we reset the collapsed state.
- if (s->sizer == 0) {
- if (collapsible(s) && smartMinSize > 0) {
- s->collapsed = true;
- } else {
- s->sizer = smartMinSize;
- }
- } else {
- if (s->sizer < smartMinSize)
- s->sizer = smartMinSize;
- }
- }
- doResize();
-}
-
-void QSplitterPrivate::setGeo(QSplitterLayoutStruct *sls, int p, int s, bool allowCollapse)
-{
- Q_Q(QSplitter);
- QWidget *w = sls->widget;
- QRect r;
- QRect contents = q->contentsRect();
- if (orient == Qt::Horizontal) {
- r.setRect(p, contents.y(), s, contents.height());
- } else {
- r.setRect(contents.x(), p, contents.width(), s);
- }
- sls->rect = r;
-
- int minSize = pick(qSmartMinSize(w));
-
- if (orient == Qt::Horizontal && q->isRightToLeft())
- r.moveRight(contents.width() - r.left());
-
- if (allowCollapse)
- sls->collapsed = s <= 0 && minSize > 0 && !w->isHidden();
-
- // Hide the child widget, but without calling hide() so that
- // the splitter handle is still shown.
- if (sls->collapsed)
- r.moveTopLeft(QPoint(-r.width()-1, -r.height()-1));
-
- w->setGeometry(r);
-
- if (!sls->handle->isHidden()) {
- QSplitterHandle *h = sls->handle;
- QSize hs = h->sizeHint();
- int left, top, right, bottom;
- h->getContentsMargins(&left, &top, &right, &bottom);
- if (orient==Qt::Horizontal) {
- if (q->isRightToLeft())
- p = contents.width() - p + hs.width();
- h->setGeometry(p-hs.width() - left, contents.y(), hs.width() + left + right, contents.height());
- } else {
- h->setGeometry(contents.x(), p-hs.height() - top, contents.width(), hs.height() + top + bottom);
- }
- }
-}
-
-void QSplitterPrivate::doMove(bool backwards, int hPos, int index, int delta, bool mayCollapse,
- int *positions, int *widths)
-{
- if (index < 0 || index >= list.count())
- return;
-
-#ifdef QSPLITTER_DEBUG
- qDebug() << "QSplitterPrivate::doMove" << backwards << hPos << index << delta << mayCollapse;
-#endif
-
- QSplitterLayoutStruct *s = list.at(index);
- QWidget *w = s->widget;
-
- int nextId = backwards ? index - delta : index + delta;
-
- if (w->isHidden()) {
- doMove(backwards, hPos, nextId, delta, collapsible(nextId), positions, widths);
- } else {
- int hs =s->handle->isHidden() ? 0 : s->getHandleSize(orient);
-
- int ws = backwards ? hPos - pick(s->rect.topLeft())
- : pick(s->rect.bottomRight()) - hPos -hs + 1;
- if (ws > 0 || (!s->collapsed && !mayCollapse)) {
- ws = qMin(ws, pick(w->maximumSize()));
- ws = qMax(ws, pick(qSmartMinSize(w)));
- } else {
- ws = 0;
- }
- positions[index] = backwards ? hPos - ws : hPos + hs;
- widths[index] = ws;
- doMove(backwards, backwards ? hPos - ws - hs : hPos + hs + ws, nextId, delta,
- collapsible(nextId), positions, widths);
- }
-
-}
-
-QSplitterLayoutStruct *QSplitterPrivate::findWidget(QWidget *w) const
-{
- for (int i = 0; i < list.size(); ++i) {
- if (list.at(i)->widget == w)
- return list.at(i);
- }
- return 0;
-}
-
-#ifdef QT3_SUPPORT
-static void setStretch(QWidget *w, int sf)
-{
- QSizePolicy sp = w->sizePolicy();
- sp.setHorizontalStretch(sf);
- sp.setVerticalStretch(sf);
- w->setSizePolicy(sp);
-}
-
-static int getStretch(const QWidget *w)
-{
- QSizePolicy sp = w->sizePolicy();
- return qMax(sp.horizontalStretch(), sp.verticalStretch());
-}
-
-void QSplitter::setResizeMode(QWidget *w, ResizeMode mode)
-{
- /*
- Internal comment:
-
- This function tries to simulate the Qt 3.x ResizeMode
- behavior using QSizePolicy stretch factors. This isn't easy,
- because the default \l ResizeMode was \l Stretch, not \l
- KeepSize, whereas the default stetch factor is 0.
-
- So what we do is this: When the user calls setResizeMode()
- the first time, we iterate through all the child widgets and
- set their stretch factors to 1. Later on, if children are
- added (using addWidget()), their stretch factors are also set
- to 1.
-
- There is just one problem left: Often, setResizeMode() is
- called \e{before} addWidget(), because addWidget() is called
- from the event loop. In that case, we use a special value,
- 243, instead of 0 to prevent 0 from being overwritten with 1
- in addWidget(). This is a wicked hack, but fortunately it
- only occurs as a result of calling a \c QT3_SUPPORT function.
- */
-
- Q_D(QSplitter);
- bool metWidget = false;
- if (!d->compatMode) {
- d->compatMode = true;
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- if (s->widget == w)
- metWidget = true;
- if (getStretch(s->widget) == 0)
- setStretch(s->widget, 1);
- }
- }
- int sf;
- if (mode == KeepSize)
- sf = metWidget ? 0 : 243;
- else
- sf = 1;
- setStretch(w, sf);
-}
-
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QSplitter::QSplitter(QWidget *parent, const char *name)
- : QFrame(*new QSplitterPrivate, parent)
-{
- Q_D(QSplitter);
- setObjectName(QString::fromAscii(name));
- d->orient = Qt::Horizontal;
- d->init();
-}
-
-
-/*!
- Use one of the constructors that don't take the \a name argument
- and then use setObjectName() instead.
-*/
-QSplitter::QSplitter(Qt::Orientation orientation, QWidget *parent, const char *name)
- : QFrame(*new QSplitterPrivate, parent)
-{
- Q_D(QSplitter);
- setObjectName(QString::fromAscii(name));
- d->orient = orientation;
- d->init();
-}
-#endif
-
-/*!
- \internal
-*/
-void QSplitterPrivate::insertWidget_helper(int index, QWidget *widget, bool show)
-{
- Q_Q(QSplitter);
- QBoolBlocker b(blockChildAdd);
- bool needShow = show && q->isVisible() &&
- !(widget->isHidden() && widget->testAttribute(Qt::WA_WState_ExplicitShowHide));
- if (widget->parentWidget() != q)
- widget->setParent(q);
- if (needShow)
- widget->show();
- insertWidget(index, widget);
- recalc(q->isVisible());
-}
-
-/*
- Inserts the widget \a w at position \a index in the splitter's list of widgets.
-
- If \a w is already in the splitter, it will be moved to the new position.
-*/
-
-QSplitterLayoutStruct *QSplitterPrivate::insertWidget(int index, QWidget *w)
-{
- Q_Q(QSplitter);
- QSplitterLayoutStruct *sls = 0;
- int i;
- int last = list.count();
- for (i = 0; i < list.size(); ++i) {
- QSplitterLayoutStruct *s = list.at(i);
- if (s->widget == w) {
- sls = s;
- --last;
- break;
- }
- }
- if (index < 0 || index > last)
- index = last;
-
- if (sls) {
- list.move(i,index);
- } else {
- QSplitterHandle *newHandle = 0;
- sls = new QSplitterLayoutStruct;
- QString tmp = QLatin1String("qt_splithandle_");
- tmp += w->objectName();
- newHandle = q->createHandle();
- newHandle->setObjectName(tmp);
- sls->handle = newHandle;
- sls->widget = w;
- w->lower();
- list.insert(index,sls);
-
- if (newHandle && q->isVisible())
- newHandle->show(); // will trigger sending of post events
-
-#ifdef QT3_SUPPORT
- if (compatMode) {
- int sf = getStretch(sls->widget);
- if (sf == 243)
- setStretch(sls->widget, 0);
- else if (sf == 0)
- setStretch(sls->widget, 1);
- }
-#endif
- }
- return sls;
-}
-
-/*!
- \class QSplitter
- \brief The QSplitter class implements a splitter widget.
-
- \ingroup organizers
-
-
- A splitter lets the user control the size of child widgets by dragging the
- boundary between the children. Any number of widgets may be controlled by a
- single splitter. The typical use of a QSplitter is to create several
- widgets and add them using insertWidget() or addWidget().
-
- The following example will show a QListView, QTreeView, and
- QTextEdit side by side, with two splitter handles:
-
- \snippet doc/src/snippets/splitter/splitter.cpp 0
-
- If a widget is already inside a QSplitter when insertWidget() or
- addWidget() is called, it will move to the new position. This can be used
- to reorder widgets in the splitter later. You can use indexOf(),
- widget(), and count() to get access to the widgets inside the splitter.
-
- A default QSplitter lays out its children horizontally (side by side); you
- can use setOrientation(Qt::Vertical) to lay its
- children out vertically.
-
- By default, all widgets can be as large or as small as the user
- wishes, between the \l minimumSizeHint() (or \l minimumSize())
- and \l maximumSize() of the widgets.
-
- QSplitter resizes its children dynamically by default. If you
- would rather have QSplitter resize the children only at the end of
- a resize operation, call setOpaqueResize(false).
-
- The initial distribution of size between the widgets is determined by
- multiplying the initial size with the stretch factor.
- You can also use setSizes() to set the sizes
- of all the widgets. The function sizes() returns the sizes set by the user.
- Alternatively, you can save and restore the sizes of the widgets from a
- QByteArray using saveState() and restoreState() respectively.
-
- When you hide() a child its space will be distributed among the
- other children. It will be reinstated when you show() it again.
-
- \sa QSplitterHandle, QHBoxLayout, QVBoxLayout, QTabWidget
-*/
-
-
-/*!
- Constructs a horizontal splitter with the \a parent
- argument passed on to the QFrame constructor.
-
- \sa setOrientation()
-*/
-QSplitter::QSplitter(QWidget *parent)
- : QFrame(*new QSplitterPrivate, parent)
-{
- Q_D(QSplitter);
- d->orient = Qt::Horizontal;
- d->init();
-}
-
-
-/*!
- Constructs a splitter with the given \a orientation and \a parent.
-
- \sa setOrientation()
-*/
-QSplitter::QSplitter(Qt::Orientation orientation, QWidget *parent)
- : QFrame(*new QSplitterPrivate, parent)
-{
- Q_D(QSplitter);
- d->orient = orientation;
- d->init();
-}
-
-
-/*!
- Destroys the splitter. All children are deleted.
-*/
-
-QSplitter::~QSplitter()
-{
- Q_D(QSplitter);
- delete d->rubberBand;
- while (!d->list.isEmpty())
- delete d->list.takeFirst();
-}
-
-/*!
- Updates the splitter's state. You should not need to call this
- function.
-*/
-void QSplitter::refresh()
-{
- Q_D(QSplitter);
- d->recalc(true);
-}
-
-/*!
- \property QSplitter::orientation
- \brief the orientation of the splitter
-
- By default the orientation is horizontal (i.e., the widgets are
- laid out side by side). The possible orientations are
- Qt::Horizontal and Qt::Vertical.
-
- \sa QSplitterHandle::orientation()
-*/
-
-void QSplitter::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QSplitter);
- if (d->orient == orientation)
- return;
-
- if (!testAttribute(Qt::WA_WState_OwnSizePolicy)) {
- QSizePolicy sp = sizePolicy();
- sp.transpose();
- setSizePolicy(sp);
- setAttribute(Qt::WA_WState_OwnSizePolicy, false);
- }
-
- d->orient = orientation;
-
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- s->handle->setOrientation(orientation);
- }
- d->recalc(isVisible());
-}
-
-Qt::Orientation QSplitter::orientation() const
-{
- Q_D(const QSplitter);
- return d->orient;
-}
-
-/*!
- \property QSplitter::childrenCollapsible
- \brief whether child widgets can be resized down to size 0 by the user
-
- By default, children are collapsible. It is possible to enable
- and disable the collapsing of individual children using
- setCollapsible().
-
- \sa setCollapsible()
-*/
-
-void QSplitter::setChildrenCollapsible(bool collapse)
-{
- Q_D(QSplitter);
- d->childrenCollapsible = collapse;
-}
-
-bool QSplitter::childrenCollapsible() const
-{
- Q_D(const QSplitter);
- return d->childrenCollapsible;
-}
-
-/*!
- Sets whether the child widget at index \a index is collapsible to \a collapse.
-
- By default, children are collapsible, meaning that the user can
- resize them down to size 0, even if they have a non-zero
- minimumSize() or minimumSizeHint(). This behavior can be changed
- on a per-widget basis by calling this function, or globally for
- all the widgets in the splitter by setting the \l
- childrenCollapsible property.
-
- \sa childrenCollapsible
-*/
-
-void QSplitter::setCollapsible(int index, bool collapse)
-{
- Q_D(QSplitter);
-
- if (index < 0 || index >= d->list.size()) {
- qWarning("QSplitter::setCollapsible: Index %d out of range", index);
- return;
- }
- d->list.at(index)->collapsible = collapse ? 1 : 0;
-}
-
-/*!
- Returns true if the widget at \a index is collapsible, otherwise returns false
-*/
-bool QSplitter::isCollapsible(int index) const
-{
- Q_D(const QSplitter);
- if (index < 0 || index >= d->list.size()) {
- qWarning("QSplitter::isCollapsible: Index %d out of range", index);
- return false;
- }
- return d->list.at(index)->collapsible;
-}
-
-/*!
- \reimp
-*/
-void QSplitter::resizeEvent(QResizeEvent *)
-{
- Q_D(QSplitter);
- d->doResize();
-}
-
-/*!
- Adds the given \a widget to the splitter's layout after all the other
- items.
-
- If \a widget is already in the splitter, it will be moved to the new position.
-
- \sa insertWidget() widget() indexOf()
-*/
-void QSplitter::addWidget(QWidget *widget)
-{
- Q_D(QSplitter);
- insertWidget(d->list.count(), widget);
-}
-
-/*!
- Inserts the \a widget specified into the splitter's layout at the
- given \a index.
-
- If \a widget is already in the splitter, it will be moved to the new position.
-
- if \a index is an invalid index, then the widget will be inserted at the end.
-
- \sa addWidget() indexOf() widget()
-*/
-void QSplitter::insertWidget(int index, QWidget *widget)
-{
- Q_D(QSplitter);
- d->insertWidget_helper(index, widget, true);
-}
-
-/*!
- \fn int QSplitter::indexOf(QWidget *widget) const
-
- Returns the index in the splitter's layout of the specified \a widget. This
- also works for handles.
-
- Handles are numbered from 0. There are as many handles as there
- are child widgets, but the handle at position 0 is always hidden.
-
-
- \sa count(), widget()
-*/
-int QSplitter::indexOf(QWidget *w) const
-{
- Q_D(const QSplitter);
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- if (s->widget == w || s->handle == w)
- return i;
- }
- return -1;
-}
-
-/*!
- Returns a new splitter handle as a child widget of this splitter.
- This function can be reimplemented in subclasses to provide support
- for custom handles.
-
- \sa handle(), indexOf()
-*/
-QSplitterHandle *QSplitter::createHandle()
-{
- Q_D(QSplitter);
- return new QSplitterHandle(d->orient, this);
-}
-
-/*!
- Returns the handle to the left (or above) for the item in the
- splitter's layout at the given \a index. The handle at index 0 is
- always hidden.
-
- For right-to-left languages such as Arabic and Hebrew, the layout
- of horizontal splitters is reversed. The handle will be to the
- right of the widget at \a index.
-
- \sa count(), widget(), indexOf(), createHandle(), setHandleWidth()
-*/
-QSplitterHandle *QSplitter::handle(int index) const
-{
- Q_D(const QSplitter);
- if (index < 0 || index >= d->list.size())
- return 0;
- return d->list.at(index)->handle;
-}
-
-/*!
- Returns the widget at the given \a index in the splitter's layout.
-
- \sa count(), handle(), indexOf(), insertWidget()
-*/
-QWidget *QSplitter::widget(int index) const
-{
- Q_D(const QSplitter);
- if (index < 0 || index >= d->list.size())
- return 0;
- return d->list.at(index)->widget;
-}
-
-/*!
- Returns the number of widgets contained in the splitter's layout.
-
- \sa widget(), handle()
-*/
-int QSplitter::count() const
-{
- Q_D(const QSplitter);
- return d->list.count();
-}
-
-/*!
- \reimp
-
- Tells the splitter that the child widget described by \a c has been
- inserted or removed.
-
- This method is also used to handle the situation where a widget is created
- with the splitter as a parent but not explicitly added with insertWidget()
- or addWidget(). This is for compatibility and not the recommended way of
- putting widgets into a splitter in new code. Please use insertWidget() or
- addWidget() in new code.
-
- \sa addWidget() insertWidget()
-*/
-
-void QSplitter::childEvent(QChildEvent *c)
-{
- Q_D(QSplitter);
- if (!c->child()->isWidgetType())
- return;
- QWidget *w = static_cast<QWidget*>(c->child());
- if (c->added() && !d->blockChildAdd && !w->isWindow() && !d->findWidget(w)) {
- d->insertWidget_helper(d->list.count(), w, false);
- } else if (c->polished() && !d->blockChildAdd) {
- if (isVisible() && !(w->isHidden() && w->testAttribute(Qt::WA_WState_ExplicitShowHide)))
- w->show();
- } else if (c->type() == QEvent::ChildRemoved) {
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- if (s->widget == w) {
- d->list.removeAt(i);
- delete s;
- d->recalc(isVisible());
- return;
- }
- }
- }
-}
-
-
-/*!
- Displays a rubber band at position \a pos. If \a pos is negative, the
- rubber band is removed.
-*/
-
-void QSplitter::setRubberBand(int pos)
-{
- Q_D(QSplitter);
- if (pos < 0) {
- if (d->rubberBand)
- d->rubberBand->deleteLater();
- return;
- }
- QRect r = contentsRect();
- const int rBord = 3; // customizable?
- int hw = handleWidth();
- if (!d->rubberBand) {
- QBoolBlocker b(d->blockChildAdd);
- d->rubberBand = new QRubberBand(QRubberBand::Line, this);
- // For accessibility to identify this special widget.
- d->rubberBand->setObjectName(QLatin1String("qt_rubberband"));
- }
-
- const QRect newGeom = d->orient == Qt::Horizontal ? QRect(QPoint(pos + hw / 2 - rBord, r.y()), QSize(2 * rBord, r.height()))
- : QRect(QPoint(r.x(), pos + hw / 2 - rBord), QSize(r.width(), 2 * rBord));
- d->rubberBand->setGeometry(newGeom);
- d->rubberBand->show();
-}
-
-/*!
- \reimp
-*/
-
-bool QSplitter::event(QEvent *e)
-{
- Q_D(QSplitter);
- switch (e->type()) {
- case QEvent::Hide:
- // Reset firstShow to false here since things can be done to the splitter in between
- if (!d->firstShow)
- d->firstShow = true;
- break;
- case QEvent::Show:
- if (!d->firstShow)
- break;
- d->firstShow = false;
- // fall through
- case QEvent::HideToParent:
- case QEvent::ShowToParent:
- case QEvent::LayoutRequest:
-#ifdef QT3_SUPPORT
- case QEvent::LayoutHint:
-#endif
- d->recalc(isVisible());
- break;
- default:
- ;
- }
- return QWidget::event(e);
-}
-
-/*!
- \fn QSplitter::splitterMoved(int pos, int index)
-
- This signal is emitted when the splitter handle at a particular \a
- index has been moved to position \a pos.
-
- For right-to-left languages such as Arabic and Hebrew, the layout
- of horizontal splitters is reversed. \a pos is then the
- distance from the right edge of the widget.
-
- \sa moveSplitter()
-*/
-
-/*!
- Moves the left or top edge of the splitter handle at \a index as
- close as possible to position \a pos, which is the distance from the
- left or top edge of the widget.
-
- For right-to-left languages such as Arabic and Hebrew, the layout
- of horizontal splitters is reversed. \a pos is then the distance
- from the right edge of the widget.
-
- \sa splitterMoved(), closestLegalPosition(), getRange()
-*/
-void QSplitter::moveSplitter(int pos, int index)
-{
- Q_D(QSplitter);
- QSplitterLayoutStruct *s = d->list.at(index);
- int farMin;
- int min;
- int max;
- int farMax;
-
-#ifdef QSPLITTER_DEBUG
- int debugp = pos;
-#endif
-
- pos = d->adjustPos(pos, index, &farMin, &min, &max, &farMax);
- int oldP = d->pick(s->rect.topLeft());
-#ifdef QSPLITTER_DEBUG
- qDebug() << "QSplitter::moveSplitter" << debugp << index << "adjusted" << pos << "oldP" << oldP;
-#endif
-
- QVarLengthArray<int, 32> poss(d->list.count());
- QVarLengthArray<int, 32> ws(d->list.count());
- bool upLeft;
-
- d->doMove(false, pos, index, +1, (d->collapsible(s) && (pos > max)), poss.data(), ws.data());
- d->doMove(true, pos, index - 1, +1, (d->collapsible(index - 1) && (pos < min)), poss.data(), ws.data());
- upLeft = (pos < oldP);
-
- int wid, delta, count = d->list.count();
- if (upLeft) {
- wid = 0;
- delta = 1;
- } else {
- wid = count - 1;
- delta = -1;
- }
- for (; wid >= 0 && wid < count; wid += delta) {
- QSplitterLayoutStruct *sls = d->list.at( wid );
- if (!sls->widget->isHidden())
- d->setGeo(sls, poss[wid], ws[wid], true);
- }
- d->storeSizes();
-
- emit splitterMoved(pos, index);
-}
-
-
-/*!
- Returns the valid range of the splitter with index \a index in
- *\a{min} and *\a{max} if \a min and \a max are not 0.
-*/
-
-void QSplitter::getRange(int index, int *min, int *max) const
-{
- Q_D(const QSplitter);
- d->getRange(index, min, 0, 0, max);
-}
-
-
-/*!
- Returns the closest legal position to \a pos of the widget with index
- \a index.
-
- For right-to-left languages such as Arabic and Hebrew, the layout
- of horizontal splitters is reversed. Positions are then measured
- from the right edge of the widget.
-
- \sa getRange()
-*/
-
-int QSplitter::closestLegalPosition(int pos, int index)
-{
- Q_D(QSplitter);
- int x, i, n, u;
- return d->adjustPos(pos, index, &u, &n, &i, &x);
-}
-
-/*!
- \property QSplitter::opaqueResize
- \brief whether resizing is opaque
-
- Opaque resizing is on by default.
-*/
-
-bool QSplitter::opaqueResize() const
-{
- Q_D(const QSplitter);
- return d->opaque;
-}
-
-
-void QSplitter::setOpaqueResize(bool on)
-{
- Q_D(QSplitter);
- d->opaque = on;
-}
-
-#ifdef QT3_SUPPORT
-/*!
- \fn void QSplitter::moveToFirst(QWidget *widget)
-
- Use insertWidget(0, \a widget) instead.
-*/
-
-
-/*!
- \fn void QSplitter::moveToLast(QWidget *widget)
-
- Use addWidget(\a widget) instead.
-*/
-
-/*!
- \fn void QSplitter::setResizeMode(QWidget *widget, ResizeMode mode)
-
- Use setStretchFactor() instead.
-
- \oldcode
- splitter->setResizeMode(firstChild, QSplitter::KeepSize);
- splitter->setResizeMode(secondChild, QSplitter::Stretch);
- \newcode
- splitter->setStretchFactor(splitter->indexOf(firstChild), 0);
- splitter->setStretchFactor(splitter->indexOf(secondChild), 1);
- \endcode
-*/
-
-/*!
- \enum QSplitter::ResizeMode
- \compat
-
- This enum describes the different resizing behaviors child
- widgets can have:
-
- \value Auto The widget will be resized according to the stretch factors set in its sizePolicy().
- \value Stretch The widget will be resized when the splitter itself is resized.
- \value KeepSize QSplitter will try to keep the widget's size unchanged.
- \value FollowSizeHint QSplitter will resize the widget when the widget's size hint changes.
-
- Use setStretchFactor() instead.
-*/
-
-/*!
- \fn void QSplitter::setCollapsible(QWidget *widget, bool collapsible)
-
- Use setCollapsible(indexOf(\a widget, \a collapsible)) instead.
-*/
-
-/*!
- \fn void QSplitter::setMargin(int margin)
- Sets the width of the margin around the contents of the widget to \a margin.
-
- Use QWidget::setContentsMargins() instead.
- \sa margin(), QWidget::setContentsMargins()
-*/
-
-/*!
- \fn int QSplitter::margin() const
- Returns the width of the margin around the contents of the widget.
-
- Use QWidget::getContentsMargins() instead.
- \sa setMargin(), QWidget::getContentsMargins()
-*/
-
-#endif
-
-/*!
- \reimp
-*/
-QSize QSplitter::sizeHint() const
-{
- Q_D(const QSplitter);
- ensurePolished();
- int l = 0;
- int t = 0;
- for (int i = 0; i < d->list.size(); ++i) {
- QWidget *w = d->list.at(i)->widget;
- if (w->isHidden())
- continue;
- QSize s = w->sizeHint();
- if (s.isValid()) {
- l += d->pick(s);
- t = qMax(t, d->trans(s));
- }
- }
- return orientation() == Qt::Horizontal ? QSize(l, t) : QSize(t, l);
-}
-
-
-/*!
- \reimp
-*/
-
-QSize QSplitter::minimumSizeHint() const
-{
- Q_D(const QSplitter);
- ensurePolished();
- int l = 0;
- int t = 0;
-
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- if (!s || !s->widget)
- continue;
- if (s->widget->isHidden())
- continue;
- QSize widgetSize = qSmartMinSize(s->widget);
- if (widgetSize.isValid()) {
- l += d->pick(widgetSize);
- t = qMax(t, d->trans(widgetSize));
- }
- if (!s->handle || s->handle->isHidden())
- continue;
- QSize splitterSize = s->handle->sizeHint();
- if (splitterSize.isValid()) {
- l += d->pick(splitterSize);
- t = qMax(t, d->trans(splitterSize));
- }
- }
- return orientation() == Qt::Horizontal ? QSize(l, t) : QSize(t, l);
-}
-
-
-/*!
- Returns a list of the size parameters of all the widgets in this splitter.
-
- If the splitter's orientation is horizontal, the list contains the
- widgets width in pixels, from left to right; if the orientation is
- vertical, the list contains the widgets height in pixels,
- from top to bottom.
-
- Giving the values to another splitter's setSizes() function will
- produce a splitter with the same layout as this one.
-
- Note that invisible widgets have a size of 0.
-
- \sa setSizes()
-*/
-
-QList<int> QSplitter::sizes() const
-{
- Q_D(const QSplitter);
- ensurePolished();
-
- QList<int> list;
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- list.append(d->pick(s->rect.size()));
- }
- return list;
-}
-
-/*!
- Sets the child widgets respective sizes to the values given in the \a list.
-
- If the splitter is horizontal, the values set the widths of each
- widget in pixels, from left to right. If the splitter is vertical, the
- heights of each widget is set, from top to bottom.
-
- Extra values in the \a list are ignored. If \a list contains too few
- values, the result is undefined but the program will still be well-behaved.
-
- The overall size of the splitter widget is not affected.
- Instead, any additional/missing space is distributed amongst the
- widgets according to the relative weight of the sizes.
-
- If you specify a size of 0, the widget will be invisible. The size policies
- of the widgets are preserved. That is, a value smaller then the minimal size
- hint of the respective widget will be replaced by the value of the hint.
-
- \sa sizes()
-*/
-
-void QSplitter::setSizes(const QList<int> &list)
-{
- Q_D(QSplitter);
- d->setSizes_helper(list, true);
-}
-
-/*!
- \property QSplitter::handleWidth
- \brief the width of the splitter handles
-
- By default, this property contains a value that depends on the user's platform
- and style preferences.
-
- If you set handleWidth to 1, the actual grab area will grow to overlap a
- few pixels of it's respective widgets.
-*/
-
-int QSplitter::handleWidth() const
-{
- Q_D(const QSplitter);
- if (d->handleWidth > 0) {
- return d->handleWidth;
- } else {
- return style()->pixelMetric(QStyle::PM_SplitterWidth, 0, this);
- }
-}
-
-void QSplitter::setHandleWidth(int width)
-{
- Q_D(QSplitter);
- d->handleWidth = width;
- d->updateHandles();
-}
-
-/*!
- \reimp
-*/
-void QSplitter::changeEvent(QEvent *ev)
-{
- Q_D(QSplitter);
- if(ev->type() == QEvent::StyleChange)
- d->updateHandles();
- QFrame::changeEvent(ev);
-}
-
-static const qint32 SplitterMagic = 0xff;
-
-/*!
- Saves the state of the splitter's layout.
-
- Typically this is used in conjunction with QSettings to remember the size
- for a future session. A version number is stored as part of the data.
- Here is an example:
-
- \snippet doc/src/snippets/splitter/splitter.cpp 1
-
- \sa restoreState()
-*/
-QByteArray QSplitter::saveState() const
-{
- Q_D(const QSplitter);
- int version = 0;
- QByteArray data;
- QDataStream stream(&data, QIODevice::WriteOnly);
-
- stream << qint32(SplitterMagic);
- stream << qint32(version);
- QList<int> list;
- for (int i = 0; i < d->list.size(); ++i) {
- QSplitterLayoutStruct *s = d->list.at(i);
- list.append(s->sizer);
- }
- stream << list;
- stream << childrenCollapsible();
- stream << qint32(handleWidth());
- stream << opaqueResize();
- stream << qint32(orientation());
- return data;
-}
-
-/*!
- Restores the splitter's layout to the \a state specified.
- Returns true if the state is restored; otherwise returns false.
-
- Typically this is used in conjunction with QSettings to restore the size
- from a past session. Here is an example:
-
- Restore the splitters's state:
-
- \snippet doc/src/snippets/splitter/splitter.cpp 2
-
- A failure to restore the splitter's layout may result from either
- invalid or out-of-date data in the supplied byte array.
-
- \sa saveState()
-*/
-bool QSplitter::restoreState(const QByteArray &state)
-{
- Q_D(QSplitter);
- int version = 0;
- QByteArray sd = state;
- QDataStream stream(&sd, QIODevice::ReadOnly);
- QList<int> list;
- bool b;
- qint32 i;
- qint32 marker;
- qint32 v;
-
- stream >> marker;
- stream >> v;
- if (marker != SplitterMagic || v != version)
- return false;
-
- stream >> list;
- d->setSizes_helper(list, false);
-
- stream >> b;
- setChildrenCollapsible(b);
-
- stream >> i;
- setHandleWidth(i);
-
- stream >> b;
- setOpaqueResize(b);
-
- stream >> i;
- setOrientation(Qt::Orientation(i));
- d->doResize();
-
- return true;
-}
-
-/*!
- Updates the size policy of the widget at position \a index to
- have a stretch factor of \a stretch.
-
- \a stretch is not the effective stretch factor; the effective
- stretch factor is calculated by taking the initial size of the
- widget and multiplying it with \a stretch.
-
- This function is provided for convenience. It is equivalent to
-
- \snippet doc/src/snippets/code/src_gui_widgets_qsplitter.cpp 0
-
- \sa setSizes(), widget()
-*/
-void QSplitter::setStretchFactor(int index, int stretch)
-{
- Q_D(QSplitter);
- if (index <= -1 || index >= d->list.count())
- return;
-
- QWidget *widget = d->list.at(index)->widget;
- QSizePolicy sp = widget->sizePolicy();
- sp.setHorizontalStretch(stretch);
- sp.setVerticalStretch(stretch);
- widget->setSizePolicy(sp);
-}
-
-
-//#ifdef QT3_SUPPORT
-#ifndef QT_NO_TEXTSTREAM
-/*!
- \relates QSplitter
- \obsolete
-
- Use \a ts << \a{splitter}.saveState() instead.
-*/
-
-QTextStream& operator<<(QTextStream& ts, const QSplitter& splitter)
-{
- ts << splitter.saveState() << endl;
- return ts;
-}
-
-/*!
- \relates QSplitter
- \obsolete
-
- Use \a ts >> \a{splitter}.restoreState() instead.
-*/
-
-QTextStream& operator>>(QTextStream& ts, QSplitter& splitter)
-{
- QString line = ts.readLine();
- line = line.simplified();
- line.replace(QLatin1Char(' '), QString());
- line = line.toUpper();
-
- splitter.restoreState(line.toAscii());
- return ts;
-}
-#endif // QT_NO_TEXTSTREAM
-//#endif // QT3_SUPPORT
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SPLITTER
diff --git a/src/gui/widgets/qsplitter.h b/src/gui/widgets/qsplitter.h
deleted file mode 100644
index a3758eabe9..0000000000
--- a/src/gui/widgets/qsplitter.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/****************************************************************************
-**
-** 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 QSPLITTER_H
-#define QSPLITTER_H
-
-#include <QtGui/qframe.h>
-#include <QtGui/qsizepolicy.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_SPLITTER
-
-class QSplitterPrivate;
-class QTextStream;
-template <typename T> class QList;
-
-class QSplitterHandle;
-
-class Q_GUI_EXPORT QSplitter : public QFrame
-{
- Q_OBJECT
-
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
- Q_PROPERTY(bool opaqueResize READ opaqueResize WRITE setOpaqueResize)
- Q_PROPERTY(int handleWidth READ handleWidth WRITE setHandleWidth)
- Q_PROPERTY(bool childrenCollapsible READ childrenCollapsible WRITE setChildrenCollapsible)
-
-public:
- explicit QSplitter(QWidget* parent = 0);
- explicit QSplitter(Qt::Orientation, QWidget* parent = 0);
- ~QSplitter();
-
- void addWidget(QWidget *widget);
- void insertWidget(int index, QWidget *widget);
-
- void setOrientation(Qt::Orientation);
- Qt::Orientation orientation() const;
-
- void setChildrenCollapsible(bool);
- bool childrenCollapsible() const;
-
- void setCollapsible(int index, bool);
- bool isCollapsible(int index) const;
- void setOpaqueResize(bool opaque = true);
- bool opaqueResize() const;
- void refresh();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- QList<int> sizes() const;
- void setSizes(const QList<int> &list);
-
- QByteArray saveState() const;
- bool restoreState(const QByteArray &state);
-
- int handleWidth() const;
- void setHandleWidth(int);
-
- int indexOf(QWidget *w) const;
- QWidget *widget(int index) const;
- int count() const;
-
- void getRange(int index, int *, int *) const;
- QSplitterHandle *handle(int index) const;
-
- void setStretchFactor(int index, int stretch);
-
-Q_SIGNALS:
- void splitterMoved(int pos, int index);
-
-protected:
- virtual QSplitterHandle *createHandle();
-
- void childEvent(QChildEvent *);
-
- bool event(QEvent *);
- void resizeEvent(QResizeEvent *);
-
- void changeEvent(QEvent *);
- void moveSplitter(int pos, int index);
- void setRubberBand(int position);
- int closestLegalPosition(int, int);
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QSplitter(QWidget* parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QSplitter(Qt::Orientation, QWidget* parent, const char* name);
- enum ResizeMode { Stretch, KeepSize, FollowSizeHint, Auto };
- QT3_SUPPORT void setResizeMode(QWidget *w, ResizeMode mode);
- inline QT3_SUPPORT void moveToFirst(QWidget *w) { insertWidget(0,w); }
- inline QT3_SUPPORT void moveToLast(QWidget *w) { addWidget(w); }
- inline QT3_SUPPORT void setCollapsible(QWidget *w, bool collapse)
- { setCollapsible(indexOf(w), collapse); }
- QT3_SUPPORT void setMargin(int margin) { setContentsMargins(margin, margin, margin, margin); }
- QT3_SUPPORT int margin() const
- { int margin; int dummy; getContentsMargins(&margin, &dummy, &dummy, &dummy); return margin; }
-#endif
-
-private:
- Q_DISABLE_COPY(QSplitter)
- Q_DECLARE_PRIVATE(QSplitter)
-private:
- friend class QSplitterHandle;
-};
-
-//#ifdef QT3_SUPPORT
-#ifndef QT_NO_TEXTSTREAM
-Q_GUI_EXPORT QTextStream& operator<<(QTextStream&, const QSplitter&);
-Q_GUI_EXPORT QTextStream& operator>>(QTextStream&, QSplitter&);
-#endif
-//#endif
-
-class QSplitterHandlePrivate;
-class Q_GUI_EXPORT QSplitterHandle : public QWidget
-{
- Q_OBJECT
-public:
- QSplitterHandle(Qt::Orientation o, QSplitter *parent);
- void setOrientation(Qt::Orientation o);
- Qt::Orientation orientation() const;
- bool opaqueResize() const;
- QSplitter *splitter() const;
-
- QSize sizeHint() const;
-
-protected:
- void paintEvent(QPaintEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void mousePressEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void resizeEvent(QResizeEvent *);
- bool event(QEvent *);
-
- void moveSplitter(int p);
- int closestLegalPosition(int p);
-
-private:
- Q_DISABLE_COPY(QSplitterHandle)
- Q_DECLARE_PRIVATE(QSplitterHandle)
-};
-
-#endif // QT_NO_SPLITTER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSPLITTER_H
diff --git a/src/gui/widgets/qsplitter_p.h b/src/gui/widgets/qsplitter_p.h
deleted file mode 100644
index 1e72066194..0000000000
--- a/src/gui/widgets/qsplitter_p.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/****************************************************************************
-**
-** 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 QSPLITTER_P_H
-#define QSPLITTER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qframe_p.h"
-#include "qrubberband.h"
-
-QT_BEGIN_NAMESPACE
-
-static const uint Default = 2;
-
-class QSplitterLayoutStruct
-{
-public:
- QRect rect;
- int sizer;
- uint collapsed : 1;
- uint collapsible : 2;
- QWidget *widget;
- QSplitterHandle *handle;
-
- QSplitterLayoutStruct() : sizer(-1), collapsed(false), collapsible(Default), widget(0), handle(0) {}
- ~QSplitterLayoutStruct() { delete handle; }
- int getWidgetSize(Qt::Orientation orient);
- int getHandleSize(Qt::Orientation orient);
- int pick(const QSize &size, Qt::Orientation orient)
- { return (orient == Qt::Horizontal) ? size.width() : size.height(); }
-};
-
-class QSplitterPrivate : public QFramePrivate
-{
- Q_DECLARE_PUBLIC(QSplitter)
-public:
- QSplitterPrivate() : rubberBand(0), opaque(true), firstShow(true),
- childrenCollapsible(true), compatMode(false), handleWidth(0), blockChildAdd(false) {}
-
- QPointer<QRubberBand> rubberBand;
- mutable QList<QSplitterLayoutStruct *> list;
- Qt::Orientation orient;
- bool opaque : 8;
- bool firstShow : 8;
- bool childrenCollapsible : 8;
- bool compatMode : 8;
- int handleWidth;
- bool blockChildAdd;
-
- inline int pick(const QPoint &pos) const
- { return orient == Qt::Horizontal ? pos.x() : pos.y(); }
- inline int pick(const QSize &s) const
- { return orient == Qt::Horizontal ? s.width() : s.height(); }
-
- inline int trans(const QPoint &pos) const
- { return orient == Qt::Vertical ? pos.x() : pos.y(); }
- inline int trans(const QSize &s) const
- { return orient == Qt::Vertical ? s.width() : s.height(); }
-
- void init();
- void recalc(bool update = false);
- void doResize();
- void storeSizes();
- void getRange(int index, int *, int *, int *, int *) const;
- void addContribution(int, int *, int *, bool) const;
- int adjustPos(int, int, int *, int *, int *, int *) const;
- bool collapsible(QSplitterLayoutStruct *) const;
- bool collapsible(int index) const
- { return (index < 0 || index >= list.size()) ? true : collapsible(list.at(index)); }
- QSplitterLayoutStruct *findWidget(QWidget *) const;
- void insertWidget_helper(int index, QWidget *widget, bool show);
- QSplitterLayoutStruct *insertWidget(int index, QWidget *);
- void doMove(bool backwards, int pos, int index, int delta,
- bool mayCollapse, int *positions, int *widths);
- void setGeo(QSplitterLayoutStruct *s, int pos, int size, bool allowCollapse);
- int findWidgetJustBeforeOrJustAfter(int index, int delta, int &collapsibleSize) const;
- void updateHandles();
- void setSizes_helper(const QList<int> &sizes, bool clampNegativeSize = false);
-
-};
-
-class QSplitterHandlePrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QSplitterHandle)
-public:
- QSplitterHandlePrivate() : s(0), orient(Qt::Horizontal), mouseOffset(0), opaq(false), hover(false), pressed(false) {}
-
- inline int pick(const QPoint &pos) const
- { return orient == Qt::Horizontal ? pos.x() : pos.y(); }
-
- QSplitter *s;
- Qt::Orientation orient;
- int mouseOffset;
- bool opaq : 1;
- bool hover : 1;
- bool pressed : 1;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qstackedwidget.cpp b/src/gui/widgets/qstackedwidget.cpp
deleted file mode 100644
index a1c225bad4..0000000000
--- a/src/gui/widgets/qstackedwidget.cpp
+++ /dev/null
@@ -1,338 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstackedwidget.h"
-
-#ifndef QT_NO_STACKEDWIDGET
-
-#include <qstackedlayout.h>
-#include <qevent.h>
-#include <private/qframe_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/**
- QStackedLayout does not support height for width (simply because it does not reimplement
- heightForWidth() and hasHeightForWidth()). That is not possible to fix without breaking
- binary compatibility. (QLayout is subject to multiple inheritance).
- However, we can fix QStackedWidget by simply using a modified version of QStackedLayout
- that reimplements the hfw-related functions:
- */
-class QStackedLayoutHFW : public QStackedLayout
-{
-public:
- QStackedLayoutHFW(QWidget *parent = 0) : QStackedLayout(parent) {}
- bool hasHeightForWidth() const;
- int heightForWidth(int width) const;
-};
-
-bool QStackedLayoutHFW::hasHeightForWidth() const
-{
- const int n = count();
-
- for (int i = 0; i < n; ++i) {
- if (QLayoutItem *item = itemAt(i)) {
- if (item->hasHeightForWidth())
- return true;
- }
- }
- return false;
-}
-
-int QStackedLayoutHFW::heightForWidth(int width) const
-{
- const int n = count();
-
- int hfw = 0;
- for (int i = 0; i < n; ++i) {
- if (QLayoutItem *item = itemAt(i)) {
- hfw = qMax(hfw, item->heightForWidth(width));
- }
- }
- return hfw;
-}
-
-
-class QStackedWidgetPrivate : public QFramePrivate
-{
- Q_DECLARE_PUBLIC(QStackedWidget)
-public:
- QStackedWidgetPrivate():layout(0){}
- QStackedLayoutHFW *layout;
- bool blockChildAdd;
-};
-
-/*!
- \class QStackedWidget
- \brief The QStackedWidget class provides a stack of widgets where
- only one widget is visible at a time.
-
- \ingroup organizers
- \ingroup geomanagement
-
-
- QStackedWidget can be used to create a user interface similar to
- the one provided by QTabWidget. It is a convenience layout widget
- built on top of the QStackedLayout class.
-
- Like QStackedLayout, QStackedWidget can be constructed and
- populated with a number of child widgets ("pages"):
-
- \snippet doc/src/snippets/qstackedwidget/main.cpp 0
- \snippet doc/src/snippets/qstackedwidget/main.cpp 2
- \snippet doc/src/snippets/qstackedwidget/main.cpp 3
-
- QStackedWidget provides no intrinsic means for the user to switch
- page. This is typically done through a QComboBox or a QListWidget
- that stores the titles of the QStackedWidget's pages. For
- example:
-
- \snippet doc/src/snippets/qstackedwidget/main.cpp 1
-
- When populating a stacked widget, the widgets are added to an
- internal list. The indexOf() function returns the index of a
- widget in that list. The widgets can either be added to the end of
- the list using the addWidget() function, or inserted at a given
- index using the insertWidget() function. The removeWidget()
- function removes a widget from the stacked widget. The number of
- widgets contained in the stacked widget, can
- be obtained using the count() function.
-
- The widget() function returns the widget at a given index
- position. The index of the widget that is shown on screen is given
- by currentIndex() and can be changed using setCurrentIndex(). In a
- similar manner, the currently shown widget can be retrieved using
- the currentWidget() function, and altered using the
- setCurrentWidget() function.
-
- Whenever the current widget in the stacked widget changes or a
- widget is removed from the stacked widget, the currentChanged()
- and widgetRemoved() signals are emitted respectively.
-
- \sa QStackedLayout, QTabWidget, {Config Dialog Example}
-*/
-
-/*!
- \fn void QStackedWidget::currentChanged(int index)
-
- This signal is emitted whenever the current widget changes.
-
- The parameter holds the \a index of the new current widget, or -1
- if there isn't a new one (for example, if there are no widgets in
- the QStackedWidget).
-
- \sa currentWidget(), setCurrentWidget()
-*/
-
-/*!
- \fn void QStackedWidget::widgetRemoved(int index)
-
- This signal is emitted whenever a widget is removed. The widget's
- \a index is passed as parameter.
-
- \sa removeWidget()
-*/
-
-/*!
- Constructs a QStackedWidget with the given \a parent.
-
- \sa addWidget(), insertWidget()
-*/
-QStackedWidget::QStackedWidget(QWidget *parent)
- : QFrame(*new QStackedWidgetPrivate, parent)
-{
- Q_D(QStackedWidget);
- d->layout = new QStackedLayoutHFW(this);
- connect(d->layout, SIGNAL(widgetRemoved(int)), this, SIGNAL(widgetRemoved(int)));
- connect(d->layout, SIGNAL(currentChanged(int)), this, SIGNAL(currentChanged(int)));
-}
-
-/*!
- Destroys this stacked widget, and frees any allocated resources.
-*/
-QStackedWidget::~QStackedWidget()
-{
-}
-
-/*!
- Appends the given \a widget to the QStackedWidget and returns the
- index position. Ownership of \a widget is passed on to the
- QStackedWidget.
-
- If the QStackedWidget is empty before this function is called,
- \a widget becomes the current widget.
-
- \sa insertWidget(), removeWidget(), setCurrentWidget()
-*/
-int QStackedWidget::addWidget(QWidget *widget)
-{
- return d_func()->layout->addWidget(widget);
-}
-
-/*!
- Inserts the given \a widget at the given \a index in the
- QStackedWidget. Ownership of \a widget is passed on to the
- QStackedWidget. If \a index is out of range, the \a widget is
- appended (in which case it is the actual index of the \a widget
- that is returned).
-
- If the QStackedWidget was empty before this function is called,
- the given \a widget becomes the current widget.
-
- Inserting a new widget at an index less than or equal to the current index
- will increment the current index, but keep the current widget.
-
- \sa addWidget(), removeWidget(), setCurrentWidget()
-*/
-int QStackedWidget::insertWidget(int index, QWidget *widget)
-{
- return d_func()->layout->insertWidget(index, widget);
-}
-
-/*!
- Removes \a widget from the QStackedWidget. i.e., \a widget is \e
- not deleted but simply removed from the stacked layout, causing it
- to be hidden.
-
- \bold{Note:} Ownership of \a widget reverts to the application.
-
- \sa addWidget(), insertWidget(), currentWidget()
-*/
-void QStackedWidget::removeWidget(QWidget *widget)
-{
- d_func()->layout->removeWidget(widget);
-}
-
-/*!
- \property QStackedWidget::currentIndex
- \brief the index position of the widget that is visible
-
- The current index is -1 if there is no current widget.
-
- By default, this property contains a value of -1 because the stack
- is initially empty.
-
- \sa currentWidget(), indexOf()
-*/
-
-void QStackedWidget::setCurrentIndex(int index)
-{
- d_func()->layout->setCurrentIndex(index);
-}
-
-int QStackedWidget::currentIndex() const
-{
- return d_func()->layout->currentIndex();
-}
-
-/*!
- Returns the current widget, or 0 if there are no child widgets.
-
- \sa currentIndex(), setCurrentWidget()
-*/
-QWidget *QStackedWidget::currentWidget() const
-{
- return d_func()->layout->currentWidget();
-}
-
-
-/*!
- \fn void QStackedWidget::setCurrentWidget(QWidget *widget)
-
- Sets the current widget to be the specified \a widget. The new
- current widget must already be contained in this stacked widget.
-
- \sa currentWidget(), setCurrentIndex()
- */
-void QStackedWidget::setCurrentWidget(QWidget *widget)
-{
- Q_D(QStackedWidget);
- if (d->layout->indexOf(widget) == -1) {
- qWarning("QStackedWidget::setCurrentWidget: widget %p not contained in stack", widget);
- return;
- }
- d->layout->setCurrentWidget(widget);
-}
-
-/*!
- Returns the index of the given \a widget, or -1 if the given \a
- widget is not a child of the QStackedWidget.
-
- \sa currentIndex(), widget()
-*/
-int QStackedWidget::indexOf(QWidget *widget) const
-{
- return d_func()->layout->indexOf(widget);
-}
-
-/*!
- Returns the widget at the given \a index, or 0 if there is no such
- widget.
-
- \sa currentWidget(), indexOf()
-*/
-QWidget *QStackedWidget::widget(int index) const
-{
- return d_func()->layout->widget(index);
-}
-
-/*!
- \property QStackedWidget::count
- \brief the number of widgets contained by this stacked widget
-
- By default, this property contains a value of 0.
-
- \sa currentIndex(), widget()
-*/
-int QStackedWidget::count() const
-{
- return d_func()->layout->count();
-}
-
-/*! \reimp */
-bool QStackedWidget::event(QEvent *e)
-{
- return QFrame::event(e);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STACKEDWIDGET
diff --git a/src/gui/widgets/qstackedwidget.h b/src/gui/widgets/qstackedwidget.h
deleted file mode 100644
index 7919674aa7..0000000000
--- a/src/gui/widgets/qstackedwidget.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTACKEDWIDGET_H
-#define QSTACKEDWIDGET_H
-
-#include <QtGui/qframe.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_STACKEDWIDGET
-
-class QStackedWidgetPrivate;
-
-class Q_GUI_EXPORT QStackedWidget : public QFrame
-{
- Q_OBJECT
-
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)
- Q_PROPERTY(int count READ count)
-public:
- explicit QStackedWidget(QWidget *parent=0);
- ~QStackedWidget();
-
- int addWidget(QWidget *w);
- int insertWidget(int index, QWidget *w);
- void removeWidget(QWidget *w);
-
- QWidget *currentWidget() const;
- int currentIndex() const;
-
- int indexOf(QWidget *) const;
- QWidget *widget(int) const;
- int count() const;
-
-public Q_SLOTS:
- void setCurrentIndex(int index);
- void setCurrentWidget(QWidget *w);
-
-Q_SIGNALS:
- void currentChanged(int);
- void widgetRemoved(int index);
-
-protected:
- bool event(QEvent *e);
-
-private:
- Q_DISABLE_COPY(QStackedWidget)
- Q_DECLARE_PRIVATE(QStackedWidget)
-};
-
-#endif // QT_NO_STACKEDWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTACKEDWIDGET_H
diff --git a/src/gui/widgets/qstatusbar.cpp b/src/gui/widgets/qstatusbar.cpp
deleted file mode 100644
index ea8ff505e2..0000000000
--- a/src/gui/widgets/qstatusbar.cpp
+++ /dev/null
@@ -1,847 +0,0 @@
-/****************************************************************************
-**
-** 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 "qstatusbar.h"
-#ifndef QT_NO_STATUSBAR
-
-#include "qlist.h"
-#include "qdebug.h"
-#include "qevent.h"
-#include "qlayout.h"
-#include "qpainter.h"
-#include "qtimer.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qsizegrip.h"
-#include "qmainwindow.h"
-
-#include <private/qlayoutengine_p.h>
-#include <private/qwidget_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QStatusBarPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QStatusBar)
-public:
- QStatusBarPrivate() {}
-
- struct SBItem {
- SBItem(QWidget* widget, int stretch, bool permanent)
- : s(stretch), w(widget), p(permanent) {}
- int s;
- QWidget * w;
- bool p;
- };
-
- QList<SBItem *> items;
- QString tempItem;
-
- QBoxLayout * box;
- QTimer * timer;
-
-#ifndef QT_NO_SIZEGRIP
- QSizeGrip * resizer;
- bool showSizeGrip;
-#endif
-
- int savedStrut;
-
-#ifdef Q_WS_MAC
- QPoint dragStart;
-#endif
-
- int indexToLastNonPermanentWidget() const
- {
- int i = items.size() - 1;
- for (; i >= 0; --i) {
- SBItem *item = items.at(i);
- if (!(item && item->p))
- break;
- }
- return i;
- }
-
-#ifndef QT_NO_SIZEGRIP
- void tryToShowSizeGrip()
- {
- if (!showSizeGrip)
- return;
- showSizeGrip = false;
- if (!resizer || resizer->isVisible())
- return;
- resizer->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- QMetaObject::invokeMethod(resizer, "_q_showIfNotHidden", Qt::DirectConnection);
- resizer->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- }
-#endif
-
- QRect messageRect() const;
-};
-
-
-QRect QStatusBarPrivate::messageRect() const
-{
- Q_Q(const QStatusBar);
- bool rtl = q->layoutDirection() == Qt::RightToLeft;
-
- int left = 6;
- int right = q->width() - 12;
-
-#ifndef QT_NO_SIZEGRIP
- if (resizer && resizer->isVisible()) {
- if (rtl)
- left = resizer->x() + resizer->width();
- else
- right = resizer->x();
- }
-#endif
-
- for (int i=0; i<items.size(); ++i) {
- QStatusBarPrivate::SBItem* item = items.at(i);
- if (!item)
- break;
- if (item->p && item->w->isVisible()) {
- if (item->p) {
- if (rtl)
- left = qMax(left, item->w->x() + item->w->width() + 2);
- else
- right = qMin(right, item->w->x() - 2);
- }
- break;
- }
- }
- return QRect(left, 0, right-left, q->height());
-}
-
-
-/*!
- \class QStatusBar
- \brief The QStatusBar class provides a horizontal bar suitable for
- presenting status information.
-
- \ingroup mainwindow-classes
- \ingroup helpsystem
-
-
- Each status indicator falls into one of three categories:
-
- \list
- \o \e Temporary - briefly occupies most of the status bar. Used
- to explain tool tip texts or menu entries, for example.
- \o \e Normal - occupies part of the status bar and may be hidden
- by temporary messages. Used to display the page and line
- number in a word processor, for example.
- \o \e Permanent - is never hidden. Used for important mode
- indications, for example, some applications put a Caps Lock
- indicator in the status bar.
- \endlist
-
- QStatusBar lets you display all three types of indicators.
-
- Typically, a request for the status bar functionality occurs in
- relation to a QMainWindow object. QMainWindow provides a main
- application window, with a menu bar, tool bars, dock widgets \e
- and a status bar around a large central widget. The status bar can
- be retrieved using the QMainWindow::statusBar() function, and
- replaced using the QMainWindow::setStatusBar() function.
-
- Use the showMessage() slot to display a \e temporary message:
-
- \snippet examples/mainwindows/dockwidgets/mainwindow.cpp 8
-
- To remove a temporary message, use the clearMessage() slot, or set
- a time limit when calling showMessage(). For example:
-
- \snippet examples/mainwindows/dockwidgets/mainwindow.cpp 3
-
- Use the currentMessage() function to retrieve the temporary
- message currently shown. The QStatusBar class also provide the
- messageChanged() signal which is emitted whenever the temporary
- status message changes.
-
- \target permanent message
- \e Normal and \e Permanent messages are displayed by creating a
- small widget (QLabel, QProgressBar or even QToolButton) and then
- adding it to the status bar using the addWidget() or the
- addPermanentWidget() function. Use the removeWidget() function to
- remove such messages from the status bar.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qstatusbar.cpp 0
-
- By default QStatusBar provides a QSizeGrip in the lower-right
- corner. You can disable it using the setSizeGripEnabled()
- function. Use the isSizeGripEnabled() function to determine the
- current status of the size grip.
-
- \image plastique-statusbar.png A status bar shown in the Plastique widget style
-
- \sa QMainWindow, QStatusTipEvent, {fowler}{GUI Design Handbook:
- Status Bar}, {Application Example}
-*/
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a status bar with a size grip and the given \a parent
- and object \a name.
-
- Use the QStatusBar() constructor and the QObject::setObjectName()
- function instead.
-
- \oldcode
- QStatusBar *myStatusBar = new QStatusBar(parent, name);
- \newcode
- QStatusBar *myStatusBar = new QStatusBar(parent);
- myStatusBar->setObjectName(name);
- \endcode
-*/
-QStatusBar::QStatusBar(QWidget * parent, const char *name)
- : QWidget(*new QStatusBarPrivate, parent, 0)
-{
- Q_D(QStatusBar);
- setObjectName(QString::fromAscii(name));
- d->box = 0;
- d->timer = 0;
-
-#ifndef QT_NO_SIZEGRIP
- d->resizer = 0;
- d->showSizeGrip = false;
- setSizeGripEnabled(true); // causes reformat()
-#else
- reformat();
-#endif
-}
-
-
-/*!
- \fn void QStatusBar::addWidget(QWidget * widget, int stretch, bool permanent)
-
- Use addWidget() or addPermanentWidget() instead, depending on the
- value of the \a permanent parameter.
-
- \oldcode
- QStatusBar *myStatusBar;
- myStatusBar->addWidget(widget, stretch, permanent); // permanent == true
- \newcode
- QStatusBar *myStatusBar;
- myStatusBar->addPermanentWidget(widget, stretch);
- \endcode
- */
-
-#endif
-
-/*!
- Constructs a status bar with a size grip and the given \a parent.
-
- \sa setSizeGripEnabled()
-*/
-QStatusBar::QStatusBar(QWidget * parent)
- : QWidget(*new QStatusBarPrivate, parent, 0)
-{
- Q_D(QStatusBar);
- d->box = 0;
- d->timer = 0;
-
-#ifndef QT_NO_SIZEGRIP
- d->resizer = 0;
- setSizeGripEnabled(true); // causes reformat()
-#else
- reformat();
-#endif
-}
-
-/*!
- Destroys this status bar and frees any allocated resources and
- child widgets.
-*/
-QStatusBar::~QStatusBar()
-{
- Q_D(QStatusBar);
- while (!d->items.isEmpty())
- delete d->items.takeFirst();
-}
-
-
-/*!
- Adds the given \a widget to this status bar, reparenting the
- widget if it isn't already a child of this QStatusBar object. The
- \a stretch parameter is used to compute a suitable size for the
- given \a widget as the status bar grows and shrinks. The default
- stretch factor is 0, i.e giving the widget a minimum of space.
-
- The widget is located to the far left of the first permanent
- widget (see addPermanentWidget()) and may be obscured by temporary
- messages.
-
- \sa insertWidget(), removeWidget(), addPermanentWidget()
-*/
-
-void QStatusBar::addWidget(QWidget * widget, int stretch)
-{
- if (!widget)
- return;
- insertWidget(d_func()->indexToLastNonPermanentWidget() + 1, widget, stretch);
-}
-
-/*!
- \since 4.2
-
- Inserts the given \a widget at the given \a index to this status bar,
- reparenting the widget if it isn't already a child of this
- QStatusBar object. If \a index is out of range, the widget is appended
- (in which case it is the actual index of the widget that is returned).
-
- The \a stretch parameter is used to compute a suitable size for
- the given \a widget as the status bar grows and shrinks. The
- default stretch factor is 0, i.e giving the widget a minimum of
- space.
-
- The widget is located to the far left of the first permanent
- widget (see addPermanentWidget()) and may be obscured by temporary
- messages.
-
- \sa addWidget(), removeWidget(), addPermanentWidget()
-*/
-int QStatusBar::insertWidget(int index, QWidget *widget, int stretch)
-{
- if (!widget)
- return -1;
-
- Q_D(QStatusBar);
- QStatusBarPrivate::SBItem* item = new QStatusBarPrivate::SBItem(widget, stretch, false);
-
- int idx = d->indexToLastNonPermanentWidget();
- if (index < 0 || index > d->items.size() || (idx >= 0 && index > idx + 1)) {
- qWarning("QStatusBar::insertWidget: Index out of range (%d), appending widget", index);
- index = idx + 1;
- }
- d->items.insert(index, item);
-
- if (!d->tempItem.isEmpty())
- widget->hide();
-
- reformat();
- if (!widget->isHidden() || !widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
- widget->show();
-
- return index;
-}
-
-/*!
- Adds the given \a widget permanently to this status bar,
- reparenting the widget if it isn't already a child of this
- QStatusBar object. The \a stretch parameter is used to compute a
- suitable size for the given \a widget as the status bar grows and
- shrinks. The default stretch factor is 0, i.e giving the widget a
- minimum of space.
-
- Permanently means that the widget may not be obscured by temporary
- messages. It is is located at the far right of the status bar.
-
- \sa insertPermanentWidget(), removeWidget(), addWidget()
-*/
-
-void QStatusBar::addPermanentWidget(QWidget * widget, int stretch)
-{
- if (!widget)
- return;
- insertPermanentWidget(d_func()->items.size(), widget, stretch);
-}
-
-
-/*!
- \since 4.2
-
- Inserts the given \a widget at the given \a index permanently to this status bar,
- reparenting the widget if it isn't already a child of this
- QStatusBar object. If \a index is out of range, the widget is appended
- (in which case it is the actual index of the widget that is returned).
-
- The \a stretch parameter is used to compute a
- suitable size for the given \a widget as the status bar grows and
- shrinks. The default stretch factor is 0, i.e giving the widget a
- minimum of space.
-
- Permanently means that the widget may not be obscured by temporary
- messages. It is is located at the far right of the status bar.
-
- \sa addPermanentWidget(), removeWidget(), addWidget()
-*/
-int QStatusBar::insertPermanentWidget(int index, QWidget *widget, int stretch)
-{
- if (!widget)
- return -1;
-
- Q_D(QStatusBar);
- QStatusBarPrivate::SBItem* item = new QStatusBarPrivate::SBItem(widget, stretch, true);
-
- int idx = d->indexToLastNonPermanentWidget();
- if (index < 0 || index > d->items.size() || (idx >= 0 && index <= idx)) {
- qWarning("QStatusBar::insertPermanentWidget: Index out of range (%d), appending widget", index);
- index = d->items.size();
- }
- d->items.insert(index, item);
-
- reformat();
- if (!widget->isHidden() || !widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
- widget->show();
-
- return index;
-}
-
-/*!
- Removes the specified \a widget from the status bar.
-
- \note This function does not delete the widget but \e hides it.
- To add the widget again, you must call both the addWidget() and
- show() functions.
-
- \sa addWidget(), addPermanentWidget(), clearMessage()
-*/
-
-void QStatusBar::removeWidget(QWidget *widget)
-{
- if (!widget)
- return;
-
- Q_D(QStatusBar);
- bool found = false;
- QStatusBarPrivate::SBItem* item;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- if (item->w == widget) {
- d->items.removeAt(i);
- item->w->hide();
- delete item;
- found = true;
- break;
- }
- }
-
- if (found)
- reformat();
-#if defined(QT_DEBUG)
- else
- qDebug("QStatusBar::removeWidget(): Widget not found.");
-#endif
-}
-
-/*!
- \property QStatusBar::sizeGripEnabled
-
- \brief whether the QSizeGrip in the bottom-right corner of the
- status bar is enabled
-
- The size grip is enabled by default.
-*/
-
-bool QStatusBar::isSizeGripEnabled() const
-{
-#ifdef QT_NO_SIZEGRIP
- return false;
-#else
- Q_D(const QStatusBar);
- return !!d->resizer;
-#endif
-}
-
-void QStatusBar::setSizeGripEnabled(bool enabled)
-{
-#ifdef QT_NO_SIZEGRIP
- Q_UNUSED(enabled);
-#else
- Q_D(QStatusBar);
- if (!enabled != !d->resizer) {
- if (enabled) {
- d->resizer = new QSizeGrip(this);
- d->resizer->hide();
- d->resizer->installEventFilter(this);
- d->showSizeGrip = true;
- } else {
- delete d->resizer;
- d->resizer = 0;
- d->showSizeGrip = false;
- }
- reformat();
- if (d->resizer && isVisible())
- d->tryToShowSizeGrip();
- }
-#endif
-}
-
-
-/*!
- Changes the status bar's appearance to account for item changes.
-
- Special subclasses may need this function, but geometry management
- will usually take care of any necessary rearrangements.
-*/
-void QStatusBar::reformat()
-{
- Q_D(QStatusBar);
- if (d->box)
- delete d->box;
-
- QBoxLayout *vbox;
-#ifndef QT_NO_SIZEGRIP
- if (d->resizer) {
- d->box = new QHBoxLayout(this);
- d->box->setMargin(0);
- vbox = new QVBoxLayout;
- d->box->addLayout(vbox);
- } else
-#endif
- {
- vbox = d->box = new QVBoxLayout(this);
- d->box->setMargin(0);
- }
- vbox->addSpacing(3);
- QBoxLayout* l = new QHBoxLayout;
- vbox->addLayout(l);
- l->addSpacing(2);
- l->setSpacing(6);
-
- int maxH = fontMetrics().height();
-
- int i;
- QStatusBarPrivate::SBItem* item;
- for (i=0,item=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item || item->p)
- break;
- l->addWidget(item->w, item->s);
- int itemH = qMin(qSmartMinSize(item->w).height(), item->w->maximumHeight());
- maxH = qMax(maxH, itemH);
- }
-
- l->addStretch(0);
-
- for (item=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- l->addWidget(item->w, item->s);
- int itemH = qMin(qSmartMinSize(item->w).height(), item->w->maximumHeight());
- maxH = qMax(maxH, itemH);
- }
-#ifndef QT_NO_SIZEGRIP
- if (d->resizer) {
- maxH = qMax(maxH, d->resizer->sizeHint().height());
- d->box->addSpacing(1);
- d->box->addWidget(d->resizer, 0, Qt::AlignBottom);
- }
-#endif
- l->addStrut(maxH);
- d->savedStrut = maxH;
- vbox->addSpacing(2);
- d->box->activate();
- update();
-}
-
-/*!
-
- Hides the normal status indications and displays the given \a
- message for the specified number of milli-seconds (\a{timeout}). If
- \a{timeout} is 0 (default), the \a {message} remains displayed until
- the clearMessage() slot is called or until the showMessage() slot is
- called again to change the message.
-
- Note that showMessage() is called to show temporary explanations of
- tool tip texts, so passing a \a{timeout} of 0 is not sufficient to
- display a \l{permanent message}{permanent message}.
-
- \sa messageChanged(), currentMessage(), clearMessage()
-*/
-void QStatusBar::showMessage(const QString &message, int timeout)
-{
- Q_D(QStatusBar);
- if (d->tempItem == message)
- return;
-
- d->tempItem = message;
-
- if (timeout > 0) {
- if (!d->timer) {
- d->timer = new QTimer(this);
- connect(d->timer, SIGNAL(timeout()), this, SLOT(clearMessage()));
- }
- d->timer->start(timeout);
- } else if (d->timer) {
- delete d->timer;
- d->timer = 0;
- }
-
- hideOrShow();
-}
-
-/*!
- Removes any temporary message being shown.
-
- \sa currentMessage(), showMessage(), removeWidget()
-*/
-
-void QStatusBar::clearMessage()
-{
- Q_D(QStatusBar);
- if (d->tempItem.isEmpty())
- return;
- if (d->timer) {
- qDeleteInEventHandler(d->timer);
- d->timer = 0;
- }
- d->tempItem.clear();
- hideOrShow();
-}
-
-/*!
- Returns the temporary message currently shown,
- or an empty string if there is no such message.
-
- \sa showMessage()
-*/
-QString QStatusBar::currentMessage() const
-{
- Q_D(const QStatusBar);
- return d->tempItem;
-}
-
-/*!
- \fn void QStatusBar::message(const QString &message, int timeout)
-
- Use the showMessage() function instead.
-*/
-
-/*!
- \fn void QStatusBar::clear()
-
- Use the clearMessage() function instead.
-*/
-
-/*!
- \fn QStatusBar::messageChanged(const QString &message)
-
- This signal is emitted whenever the temporary status message
- changes. The new temporary message is passed in the \a message
- parameter which is a null-string when the message has been
- removed.
-
- \sa showMessage(), clearMessage()
-*/
-
-/*!
- Ensures that the right widgets are visible.
-
- Used by the showMessage() and clearMessage() functions.
-*/
-void QStatusBar::hideOrShow()
-{
- Q_D(QStatusBar);
- bool haveMessage = !d->tempItem.isEmpty();
-
- QStatusBarPrivate::SBItem* item = 0;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item || item->p)
- break;
- if (haveMessage && item->w->isVisible()) {
- item->w->hide();
- item->w->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
- } else if (!haveMessage && !item->w->testAttribute(Qt::WA_WState_ExplicitShowHide)) {
- item->w->show();
- }
- }
-
- emit messageChanged(d->tempItem);
- repaint(d->messageRect());
-}
-
-/*!
- \reimp
- */
-void QStatusBar::showEvent(QShowEvent *)
-{
-#ifndef QT_NO_SIZEGRIP
- Q_D(QStatusBar);
- if (d->resizer && d->showSizeGrip)
- d->tryToShowSizeGrip();
-#endif
-}
-
-/*!
- \reimp
- \fn void QStatusBar::paintEvent(QPaintEvent *event)
-
- Shows the temporary message, if appropriate, in response to the
- paint \a event.
-*/
-void QStatusBar::paintEvent(QPaintEvent *event)
-{
- Q_D(QStatusBar);
- bool haveMessage = !d->tempItem.isEmpty();
-
- QPainter p(this);
- QStyleOption opt;
- opt.initFrom(this);
- style()->drawPrimitive(QStyle::PE_PanelStatusBar, &opt, &p, this);
-
- for (int i=0; i<d->items.size(); ++i) {
- QStatusBarPrivate::SBItem* item = d->items.at(i);
- if (item && item->w->isVisible() && (!haveMessage || item->p)) {
- QRect ir = item->w->geometry().adjusted(-2, -1, 2, 1);
- if (event->rect().intersects(ir)) {
- QStyleOption opt(0);
- opt.rect = ir;
- opt.palette = palette();
- opt.state = QStyle::State_None;
- style()->drawPrimitive(QStyle::PE_FrameStatusBarItem, &opt, &p, item->w);
- }
- }
- }
- if (haveMessage) {
- p.setPen(palette().foreground().color());
- p.drawText(d->messageRect(), Qt::AlignLeading | Qt::AlignVCenter | Qt::TextSingleLine, d->tempItem);
- }
-}
-
-/*!
- \reimp
-*/
-void QStatusBar::resizeEvent(QResizeEvent * e)
-{
- QWidget::resizeEvent(e);
-}
-
-/*!
- \reimp
-*/
-
-bool QStatusBar::event(QEvent *e)
-{
- Q_D(QStatusBar);
-
- if (e->type() == QEvent::LayoutRequest
-#ifdef QT3_SUPPORT
- || e->type() == QEvent::LayoutHint
-#endif
- ) {
- // Calculate new strut height and call reformat() if it has changed
- int maxH = fontMetrics().height();
-
- QStatusBarPrivate::SBItem* item = 0;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- int itemH = qMin(qSmartMinSize(item->w).height(), item->w->maximumHeight());
- maxH = qMax(maxH, itemH);
- }
-
-#ifndef QT_NO_SIZEGRIP
- if (d->resizer)
- maxH = qMax(maxH, d->resizer->sizeHint().height());
-#endif
-
- if (maxH != d->savedStrut)
- reformat();
- else
- update();
- }
- if (e->type() == QEvent::ChildRemoved) {
- QStatusBarPrivate::SBItem* item = 0;
- for (int i=0; i<d->items.size(); ++i) {
- item = d->items.at(i);
- if (!item)
- break;
- if (item->w == ((QChildEvent*)e)->child()) {
- d->items.removeAt(i);
- delete item;
- }
- }
- }
-
-// On Mac OS X Leopard it is possible to drag the window by clicking
-// on the tool bar on most applications.
-#ifndef Q_WS_MAC
- return QWidget::event(e);
-#else
- if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_4)
- return QWidget::event(e);
-
- // Enable drag-click only if the status bar is the status bar for a
- // QMainWindow with a unifed toolbar.
- if (parent() == 0 || qobject_cast<QMainWindow *>(parent()) == 0 ||
- qobject_cast<QMainWindow *>(parent())->unifiedTitleAndToolBarOnMac() == false )
- return QWidget::event(e);
-
- // Check for mouse events.
- QMouseEvent *mouseEvent;
- if (e->type() == QEvent::MouseButtonPress ||
- e->type() == QEvent::MouseMove ||
- e->type() == QEvent::MouseButtonRelease) {
- mouseEvent = static_cast <QMouseEvent*>(e);
- } else {
- return QWidget::event(e);
- }
-
- // The following is a standard mouse drag handler.
- if (e->type() == QEvent::MouseButtonPress && (mouseEvent->button() == Qt::LeftButton)) {
- d->dragStart = mouseEvent->pos();
- } else if (e->type() == QEvent::MouseMove){
- if (d->dragStart == QPoint())
- return QWidget::event(e);
- QPoint pos = mouseEvent->pos();
- QPoint delta = (pos - d->dragStart);
- window()->move(window()->pos() + delta);
- } else if (e->type() == QEvent::MouseButtonRelease && (mouseEvent->button() == Qt::LeftButton)){
- d->dragStart = QPoint();
- } else {
- return QWidget::event(e);
- }
-
- return true;
-#endif
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qstatusbar.h b/src/gui/widgets/qstatusbar.h
deleted file mode 100644
index 598aa4b890..0000000000
--- a/src/gui/widgets/qstatusbar.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** 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 QSTATUSBAR_H
-#define QSTATUSBAR_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_STATUSBAR
-
-class QStatusBarPrivate;
-
-class Q_GUI_EXPORT QStatusBar: public QWidget
-{
- Q_OBJECT
-
- Q_PROPERTY(bool sizeGripEnabled READ isSizeGripEnabled WRITE setSizeGripEnabled)
-
-public:
- explicit QStatusBar(QWidget* parent=0);
- virtual ~QStatusBar();
-
- void addWidget(QWidget *widget, int stretch = 0);
- int insertWidget(int index, QWidget *widget, int stretch = 0);
- void addPermanentWidget(QWidget *widget, int stretch = 0);
- int insertPermanentWidget(int index, QWidget *widget, int stretch = 0);
- void removeWidget(QWidget *widget);
-
- void setSizeGripEnabled(bool);
- bool isSizeGripEnabled() const;
-
- QString currentMessage() const;
-
-public Q_SLOTS:
- void showMessage(const QString &text, int timeout = 0);
- void clearMessage();
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QStatusBar(QWidget* parent, const char* name);
- QT3_SUPPORT void addWidget(QWidget *w, int stretch, bool permanent)
- { if (permanent) addPermanentWidget(w, stretch); else addWidget(w, stretch); }
-public Q_SLOTS:
- inline QT_MOC_COMPAT void message(const QString &text, int timeout = 0) { showMessage(text, timeout); }
- inline QT_MOC_COMPAT void clear() { clearMessage(); }
-#endif
-
-Q_SIGNALS:
- void messageChanged(const QString &text);
-
-protected:
- void showEvent(QShowEvent *);
- void paintEvent(QPaintEvent *);
- void resizeEvent(QResizeEvent *);
-
- // ### Qt 5: consider making reformat() and hideOrShow() private
- void reformat();
- void hideOrShow();
- bool event(QEvent *);
-
-private:
- Q_DISABLE_COPY(QStatusBar)
- Q_DECLARE_PRIVATE(QStatusBar)
-};
-
-#endif // QT_NO_STATUSBAR
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QSTATUSBAR_H
diff --git a/src/gui/widgets/qtabbar.cpp b/src/gui/widgets/qtabbar.cpp
deleted file mode 100644
index c5d0892122..0000000000
--- a/src/gui/widgets/qtabbar.cpp
+++ /dev/null
@@ -1,2376 +0,0 @@
-/****************************************************************************
-**
-** 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 "private/qlayoutengine_p.h"
-#include "qabstractitemdelegate.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qstylepainter.h"
-#include "qtabwidget.h"
-#include "qtooltip.h"
-#include "qwhatsthis.h"
-#include "private/qtextengine_p.h"
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-
-#include "qdebug.h"
-#include "private/qtabbar_p.h"
-
-#ifndef QT_NO_TABBAR
-
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#ifndef QT_NO_STYLE_S60
-#include "qs60style.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-
-inline static bool verticalTabs(QTabBar::Shape shape)
-{
- return shape == QTabBar::RoundedWest
- || shape == QTabBar::RoundedEast
- || shape == QTabBar::TriangularWest
- || shape == QTabBar::TriangularEast;
-}
-
-void QTabBarPrivate::updateMacBorderMetrics()
-{
-#if (defined Q_WS_MAC) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
- if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
- Q_Q(QTabBar);
- ::HIContentBorderMetrics metrics;
-
- // TODO: get metrics to preserve the bottom value
- // TODO: test tab bar position
-
- OSWindowRef window = qt_mac_window_for(q);
-
- // push base line separator down to the client are so we can paint over it (Carbon)
- metrics.top = (documentMode && q->isVisible()) ? 1 : 0;
- metrics.bottom = 0;
- metrics.left = 0;
- metrics.right = 0;
- qt_mac_updateContentBorderMetricts(window, metrics);
-#if QT_MAC_USE_COCOA
- // In Cocoa we need to keep track of the drawRect method.
- // If documentMode is enabled we need to change it, unless
- // a toolbar is present.
- // Notice that all the information is kept in the window,
- // that's why we get the private widget for it instead of
- // the private widget for this widget.
- QWidgetPrivate *privateWidget = qt_widget_private(q->window());
- if(privateWidget)
- privateWidget->changeMethods = documentMode;
- // Since in Cocoa there is no simple way to remove the baseline, so we just ask the
- // top level to do the magic for us.
- privateWidget->syncUnifiedMode();
-#endif // QT_MAC_USE_COCOA
- }
-#endif
-}
-
-/*!
- Initialize \a option with the values from the tab at \a tabIndex. This method
- is useful for subclasses when they need a QStyleOptionTab, QStyleOptionTabV2,
- or QStyleOptionTabV3 but don't want to fill in all the information themselves.
- This function will check the version of the QStyleOptionTab and fill in the
- additional values for a QStyleOptionTabV2 and QStyleOptionTabV3.
-
- \sa QStyleOption::initFrom() QTabWidget::initStyleOption()
-*/
-void QTabBar::initStyleOption(QStyleOptionTab *option, int tabIndex) const
-{
- Q_D(const QTabBar);
- int totalTabs = d->tabList.size();
-
- if (!option || (tabIndex < 0 || tabIndex >= totalTabs))
- return;
-
- const QTabBarPrivate::Tab &tab = d->tabList.at(tabIndex);
- option->initFrom(this);
- option->state &= ~(QStyle::State_HasFocus | QStyle::State_MouseOver);
- option->rect = tabRect(tabIndex);
- bool isCurrent = tabIndex == d->currentIndex;
- option->row = 0;
- if (tabIndex == d->pressedIndex)
- option->state |= QStyle::State_Sunken;
- if (isCurrent)
- option->state |= QStyle::State_Selected;
- if (isCurrent && hasFocus())
- option->state |= QStyle::State_HasFocus;
- if (!tab.enabled)
- option->state &= ~QStyle::State_Enabled;
- if (isActiveWindow())
- option->state |= QStyle::State_Active;
- if (!d->dragInProgress && option->rect == d->hoverRect)
- option->state |= QStyle::State_MouseOver;
- option->shape = d->shape;
- option->text = tab.text;
-
- if (tab.textColor.isValid())
- option->palette.setColor(foregroundRole(), tab.textColor);
-
- option->icon = tab.icon;
- if (QStyleOptionTabV2 *optionV2 = qstyleoption_cast<QStyleOptionTabV2 *>(option))
- optionV2->iconSize = iconSize(); // Will get the default value then.
-
- if (QStyleOptionTabV3 *optionV3 = qstyleoption_cast<QStyleOptionTabV3 *>(option)) {
- optionV3->leftButtonSize = tab.leftWidget ? tab.leftWidget->size() : QSize();
- optionV3->rightButtonSize = tab.rightWidget ? tab.rightWidget->size() : QSize();
- optionV3->documentMode = d->documentMode;
- }
-
- if (tabIndex > 0 && tabIndex - 1 == d->currentIndex)
- option->selectedPosition = QStyleOptionTab::PreviousIsSelected;
- else if (tabIndex < totalTabs - 1 && tabIndex + 1 == d->currentIndex)
- option->selectedPosition = QStyleOptionTab::NextIsSelected;
- else
- option->selectedPosition = QStyleOptionTab::NotAdjacent;
-
- bool paintBeginning = (tabIndex == 0) || (d->dragInProgress && tabIndex == d->pressedIndex + 1);
- bool paintEnd = (tabIndex == totalTabs - 1) || (d->dragInProgress && tabIndex == d->pressedIndex - 1);
- if (paintBeginning) {
- if (paintEnd)
- option->position = QStyleOptionTab::OnlyOneTab;
- else
- option->position = QStyleOptionTab::Beginning;
- } else if (paintEnd) {
- option->position = QStyleOptionTab::End;
- } else {
- option->position = QStyleOptionTab::Middle;
- }
-
-#ifndef QT_NO_TABWIDGET
- if (const QTabWidget *tw = qobject_cast<const QTabWidget *>(parentWidget())) {
- if (tw->cornerWidget(Qt::TopLeftCorner) || tw->cornerWidget(Qt::BottomLeftCorner))
- option->cornerWidgets |= QStyleOptionTab::LeftCornerWidget;
- if (tw->cornerWidget(Qt::TopRightCorner) || tw->cornerWidget(Qt::BottomRightCorner))
- option->cornerWidgets |= QStyleOptionTab::RightCornerWidget;
- }
-#endif
-
- QRect textRect = style()->subElementRect(QStyle::SE_TabBarTabText, option, this);
- option->text = fontMetrics().elidedText(option->text, d->elideMode, textRect.width(),
- Qt::TextShowMnemonic);
-}
-
-/*!
- \class QTabBar
- \brief The QTabBar class provides a tab bar, e.g. for use in tabbed dialogs.
-
- \ingroup basicwidgets
-
-
- QTabBar is straightforward to use; it draws the tabs using one of
- the predefined \link QTabBar::Shape shapes\endlink, and emits a
- signal when a tab is selected. It can be subclassed to tailor the
- look and feel. Qt also provides a ready-made \l{QTabWidget}.
-
- Each tab has a tabText(), an optional tabIcon(), an optional
- tabToolTip(), optional tabWhatsThis() and optional tabData().
- The tabs's attributes can be changed with setTabText(), setTabIcon(),
- setTabToolTip(), setTabWhatsThis and setTabData(). Each tabs can be
- enabled or disabled individually with setTabEnabled().
-
- Each tab can display text in a distinct color. The current text color
- for a tab can be found with the tabTextColor() function. Set the text
- color for a particular tab with setTabTextColor().
-
- Tabs are added using addTab(), or inserted at particular positions
- using insertTab(). The total number of tabs is given by
- count(). Tabs can be removed from the tab bar with
- removeTab(). Combining removeTab() and insertTab() allows you to
- move tabs to different positions.
-
- The \l shape property defines the tabs' appearance. The choice of
- shape is a matter of taste, although tab dialogs (for preferences
- and similar) invariably use \l RoundedNorth.
- Tab controls in windows other than dialogs almost
- always use either \l RoundedSouth or \l TriangularSouth. Many
- spreadsheets and other tab controls in which all the pages are
- essentially similar use \l TriangularSouth, whereas \l
- RoundedSouth is used mostly when the pages are different (e.g. a
- multi-page tool palette). The default in QTabBar is \l
- RoundedNorth.
-
- The most important part of QTabBar's API is the currentChanged()
- signal. This is emitted whenever the current tab changes (even at
- startup, when the current tab changes from 'none'). There is also
- a slot, setCurrentIndex(), which can be used to select a tab
- programmatically. The function currentIndex() returns the index of
- the current tab, \l count holds the number of tabs.
-
- QTabBar creates automatic mnemonic keys in the manner of QAbstractButton;
- e.g. if a tab's label is "\&Graphics", Alt+G becomes a shortcut
- key for switching to that tab.
-
- The following virtual functions may need to be reimplemented in
- order to tailor the look and feel or store extra data with each
- tab:
-
- \list
- \i tabSizeHint() calcuates the size of a tab.
- \i tabInserted() notifies that a new tab was added.
- \i tabRemoved() notifies that a tab was removed.
- \i tabLayoutChange() notifies that the tabs have been re-laid out.
- \i paintEvent() paints all tabs.
- \endlist
-
- For subclasses, you might also need the tabRect() functions which
- returns the visual geometry of a single tab.
-
- \table 100%
- \row \o \inlineimage plastique-tabbar.png Screenshot of a Plastique style tab bar
- \o A tab bar shown in the Plastique widget style.
- \row \o \inlineimage plastique-tabbar-truncated.png Screenshot of a truncated Plastique tab bar
- \o A truncated tab bar shown in the Plastique widget style.
- \endtable
-
- \sa QTabWidget
-*/
-
-/*!
- \enum QTabBar::Shape
-
- This enum type lists the built-in shapes supported by QTabBar. Treat these
- as hints as some styles may not render some of the shapes. However,
- position should be honored.
-
- \value RoundedNorth The normal rounded look above the pages
-
- \value RoundedSouth The normal rounded look below the pages
-
- \value RoundedWest The normal rounded look on the left side of the pages
-
- \value RoundedEast The normal rounded look on the right side the pages
-
- \value TriangularNorth Triangular tabs above the pages.
-
- \value TriangularSouth Triangular tabs similar to those used in
- the Excel spreadsheet, for example
-
- \value TriangularWest Triangular tabs on the left of the pages.
-
- \value TriangularEast Triangular tabs on the right of the pages.
- \omitvalue RoundedAbove
- \omitvalue RoundedBelow
- \omitvalue TriangularAbove
- \omitvalue TriangularBelow
-*/
-
-/*!
- \fn void QTabBar::currentChanged(int index)
-
- This signal is emitted when the tab bar's current tab changes. The
- new current has the given \a index, or -1 if there isn't a new one
- (for example, if there are no tab in the QTabBar)
-*/
-
-/*!
- \fn void QTabBar::tabCloseRequested(int index)
- \since 4.5
-
- This signal is emitted when the close button on a tab is clicked.
- The \a index is the index that should be removed.
-
- \sa setTabsClosable()
-*/
-
-/*!
- \fn void QTabBar::tabMoved(int from, int to)
- \since 4.5
-
- This signal is emitted when the tab has moved the tab
- at index position \a from to index position \a to.
-
- note: QTabWidget will automatically move the page when
- this signal is emitted from its tab bar.
-
- \sa moveTab()
-*/
-
-int QTabBarPrivate::extraWidth() const
-{
- Q_Q(const QTabBar);
- return 2 * qMax(q->style()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, 0, q),
- QApplication::globalStrut().width());
-}
-
-void QTabBarPrivate::init()
-{
- Q_Q(QTabBar);
- leftB = new QToolButton(q);
- leftB->setAutoRepeat(true);
- QObject::connect(leftB, SIGNAL(clicked()), q, SLOT(_q_scrollTabs()));
- leftB->hide();
- rightB = new QToolButton(q);
- rightB->setAutoRepeat(true);
- QObject::connect(rightB, SIGNAL(clicked()), q, SLOT(_q_scrollTabs()));
- rightB->hide();
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
- leftB->setFocusPolicy(Qt::NoFocus);
- rightB->setFocusPolicy(Qt::NoFocus);
- q->setFocusPolicy(Qt::NoFocus);
- } else
-#endif
- q->setFocusPolicy(Qt::TabFocus);
- q->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
- elideMode = Qt::TextElideMode(q->style()->styleHint(QStyle::SH_TabBar_ElideMode, 0, q));
- useScrollButtons = !q->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, 0, q);
-}
-
-QTabBarPrivate::Tab *QTabBarPrivate::at(int index)
-{
- return validIndex(index)?&tabList[index]:0;
-}
-
-const QTabBarPrivate::Tab *QTabBarPrivate::at(int index) const
-{
- return validIndex(index)?&tabList[index]:0;
-}
-
-int QTabBarPrivate::indexAtPos(const QPoint &p) const
-{
- Q_Q(const QTabBar);
- if (q->tabRect(currentIndex).contains(p))
- return currentIndex;
- for (int i = 0; i < tabList.count(); ++i)
- if (tabList.at(i).enabled && q->tabRect(i).contains(p))
- return i;
- return -1;
-}
-
-void QTabBarPrivate::layoutTabs()
-{
- Q_Q(QTabBar);
- scrollOffset = 0;
- layoutDirty = false;
- QSize size = q->size();
- int last, available;
- int maxExtent;
- int i;
- bool vertTabs = verticalTabs(shape);
- int tabChainIndex = 0;
-
- Qt::Alignment tabAlignment = Qt::Alignment(q->style()->styleHint(QStyle::SH_TabBar_Alignment, 0, q));
- QVector<QLayoutStruct> tabChain(tabList.count() + 2);
-
- // We put an empty item at the front and back and set its expansive attribute
- // depending on tabAlignment.
- tabChain[tabChainIndex].init();
- tabChain[tabChainIndex].expansive = (tabAlignment != Qt::AlignLeft)
- && (tabAlignment != Qt::AlignJustify);
- tabChain[tabChainIndex].empty = true;
- ++tabChainIndex;
-
- // We now go through our list of tabs and set the minimum size and the size hint
- // This will allow us to elide text if necessary. Since we don't set
- // a maximum size, tabs will EXPAND to fill up the empty space.
- // Since tab widget is rather *ahem* strict about keeping the geometry of the
- // tab bar to its absolute minimum, this won't bleed through, but will show up
- // if you use tab bar on its own (a.k.a. not a bug, but a feature).
- // Update: if expanding is false, we DO set a maximum size to prevent the tabs
- // being wider than necessary.
- if (!vertTabs) {
- int minx = 0;
- int x = 0;
- int maxHeight = 0;
- for (i = 0; i < tabList.count(); ++i, ++tabChainIndex) {
- QSize sz = q->tabSizeHint(i);
- tabList[i].maxRect = QRect(x, 0, sz.width(), sz.height());
- x += sz.width();
- maxHeight = qMax(maxHeight, sz.height());
- sz = minimumTabSizeHint(i);
- tabList[i].minRect = QRect(minx, 0, sz.width(), sz.height());
- minx += sz.width();
- tabChain[tabChainIndex].init();
- tabChain[tabChainIndex].sizeHint = tabList.at(i).maxRect.width();
- tabChain[tabChainIndex].minimumSize = sz.width();
- tabChain[tabChainIndex].empty = false;
- tabChain[tabChainIndex].expansive = true;
-
- if (!expanding)
- tabChain[tabChainIndex].maximumSize = tabChain[tabChainIndex].sizeHint;
- }
-
- last = minx;
- available = size.width();
- maxExtent = maxHeight;
- } else {
- int miny = 0;
- int y = 0;
- int maxWidth = 0;
- for (i = 0; i < tabList.count(); ++i, ++tabChainIndex) {
- QSize sz = q->tabSizeHint(i);
- tabList[i].maxRect = QRect(0, y, sz.width(), sz.height());
- y += sz.height();
- maxWidth = qMax(maxWidth, sz.width());
- sz = minimumTabSizeHint(i);
- tabList[i].minRect = QRect(0, miny, sz.width(), sz.height());
- miny += sz.height();
- tabChain[tabChainIndex].init();
- tabChain[tabChainIndex].sizeHint = tabList.at(i).maxRect.height();
- tabChain[tabChainIndex].minimumSize = sz.height();
- tabChain[tabChainIndex].empty = false;
- tabChain[tabChainIndex].expansive = true;
-
- if (!expanding)
- tabChain[tabChainIndex].maximumSize = tabChain[tabChainIndex].sizeHint;
- }
-
- last = miny;
- available = size.height();
- maxExtent = maxWidth;
- }
-
- Q_ASSERT(tabChainIndex == tabChain.count() - 1); // add an assert just to make sure.
- // Mirror our front item.
- tabChain[tabChainIndex].init();
- tabChain[tabChainIndex].expansive = (tabAlignment != Qt::AlignRight)
- && (tabAlignment != Qt::AlignJustify);
- tabChain[tabChainIndex].empty = true;
-
- // Do the calculation
- qGeomCalc(tabChain, 0, tabChain.count(), 0, qMax(available, last), 0);
-
- // Use the results
- for (i = 0; i < tabList.count(); ++i) {
- const QLayoutStruct &lstruct = tabChain.at(i + 1);
- if (!vertTabs)
- tabList[i].rect.setRect(lstruct.pos, 0, lstruct.size, maxExtent);
- else
- tabList[i].rect.setRect(0, lstruct.pos, maxExtent, lstruct.size);
- }
-
- if (useScrollButtons && tabList.count() && last > available) {
- int extra = extraWidth();
-#ifndef QT_NO_STYLE_S60
- QS60Style *s60Style = qobject_cast<QS60Style*>(QApplication::style());
-#endif
- if (!vertTabs) {
- Qt::LayoutDirection ld = q->layoutDirection();
- QRect arrows = QStyle::visualRect(ld, q->rect(),
- QRect(available - extra, 0, extra, size.height()));
- int buttonOverlap = q->style()->pixelMetric(QStyle::PM_TabBar_ScrollButtonOverlap, 0, q);
-
- if (ld == Qt::LeftToRight) {
-// In S60style, tab scroll buttons are layoutted separately, on the sides of the tabbar.
-#ifndef QT_NO_STYLE_S60
- if (s60Style) {
- rightB->setGeometry(arrows.left() + extra / 2, arrows.top(), extra / 2, arrows.height());
- leftB->setGeometry(0, arrows.top(), extra / 2, arrows.height());
- } else {
-#endif
- leftB->setGeometry(arrows.left(), arrows.top(), extra/2, arrows.height());
- rightB->setGeometry(arrows.right() - extra/2 + buttonOverlap, arrows.top(),
- extra/2, arrows.height());
-#ifndef QT_NO_STYLE_S60
- }
-#endif
- leftB->setArrowType(Qt::LeftArrow);
- rightB->setArrowType(Qt::RightArrow);
- } else {
-#ifndef QT_NO_STYLE_S60
- if (s60Style) {
- rightB->setGeometry(arrows.left() + extra / 2, arrows.top(), extra / 2, arrows.height());
- leftB->setGeometry(0, arrows.top(), extra / 2, arrows.height());
- } else {
-#endif
- rightB->setGeometry(arrows.left(), arrows.top(), extra/2, arrows.height());
- leftB->setGeometry(arrows.right() - extra/2 + buttonOverlap, arrows.top(),
- extra/2, arrows.height());
-#ifndef QT_NO_STYLE_S60
- }
-#endif
- rightB->setArrowType(Qt::LeftArrow);
- leftB->setArrowType(Qt::RightArrow);
- }
- } else {
-#ifndef QT_NO_STYLE_S60
- if (s60Style) {
- QRect arrows = QRect(0, 0, size.width(), available );
- leftB->setGeometry(arrows.left(), arrows.top(), arrows.width(), extra / 2);
- leftB->setArrowType(Qt::UpArrow);
- rightB->setGeometry(arrows.left(), arrows.bottom() - extra / 2 + 1,
- arrows.width(), extra / 2);
- rightB->setArrowType(Qt::DownArrow);
- } else {
-#endif
- QRect arrows = QRect(0, available - extra, size.width(), extra );
- leftB->setGeometry(arrows.left(), arrows.top(), arrows.width(), extra/2);
- leftB->setArrowType(Qt::UpArrow);
- rightB->setGeometry(arrows.left(), arrows.bottom() - extra/2 + 1,
- arrows.width(), extra/2);
- rightB->setArrowType(Qt::DownArrow);
-#ifndef QT_NO_STYLE_S60
- }
-#endif
- }
- leftB->setEnabled(scrollOffset > 0);
- rightB->setEnabled(last - scrollOffset >= available - extra);
- leftB->show();
- rightB->show();
- } else {
- rightB->hide();
- leftB->hide();
- }
-
- layoutWidgets();
- q->tabLayoutChange();
-}
-
-void QTabBarPrivate::makeVisible(int index)
-{
- Q_Q(QTabBar);
- if (!validIndex(index) || leftB->isHidden())
- return;
-
- const QRect tabRect = tabList.at(index).rect;
- const int oldScrollOffset = scrollOffset;
- const bool horiz = !verticalTabs(shape);
- const int available = (horiz ? q->width() : q->height()) - extraWidth();
- const int start = horiz ? tabRect.left() : tabRect.top();
- const int end = horiz ? tabRect.right() : tabRect.bottom();
- if (start < scrollOffset) // too far left
- scrollOffset = start - (index ? 8 : 0);
- else if (end > scrollOffset + available) // too far right
- scrollOffset = end - available + 1;
-
- leftB->setEnabled(scrollOffset > 0);
- const int last = horiz ? tabList.last().rect.right() : tabList.last().rect.bottom();
- rightB->setEnabled(last - scrollOffset >= available);
- if (oldScrollOffset != scrollOffset) {
- q->update();
- layoutWidgets();
- }
-}
-
-void QTabBarPrivate::layoutTab(int index)
-{
- Q_Q(QTabBar);
- Q_ASSERT(index >= 0);
-
- Tab &tab = tabList[index];
- bool vertical = verticalTabs(shape);
- if (!(tab.leftWidget || tab.rightWidget))
- return;
-
- QStyleOptionTabV3 opt;
- q->initStyleOption(&opt, index);
- if (tab.leftWidget) {
- QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabLeftButton, &opt, q);
- QPoint p = rect.topLeft();
- if ((index == pressedIndex) || paintWithOffsets) {
- if (vertical)
- p.setY(p.y() + tabList[index].dragOffset);
- else
- p.setX(p.x() + tabList[index].dragOffset);
- }
- tab.leftWidget->move(p);
- }
- if (tab.rightWidget) {
- QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabRightButton, &opt, q);
- QPoint p = rect.topLeft();
- if ((index == pressedIndex) || paintWithOffsets) {
- if (vertical)
- p.setY(p.y() + tab.dragOffset);
- else
- p.setX(p.x() + tab.dragOffset);
- }
- tab.rightWidget->move(p);
- }
-}
-
-void QTabBarPrivate::layoutWidgets(int start)
-{
- Q_Q(QTabBar);
- for (int i = start; i < q->count(); ++i) {
- layoutTab(i);
- }
-}
-
-void QTabBarPrivate::_q_closeTab()
-{
- Q_Q(QTabBar);
- QObject *object = q->sender();
- int tabToClose = -1;
- QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition)q->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, q);
- for (int i = 0; i < tabList.count(); ++i) {
- if (closeSide == QTabBar::LeftSide) {
- if (tabList.at(i).leftWidget == object) {
- tabToClose = i;
- break;
- }
- } else {
- if (tabList.at(i).rightWidget == object) {
- tabToClose = i;
- break;
- }
- }
- }
- if (tabToClose != -1)
- emit q->tabCloseRequested(tabToClose);
-}
-
-void QTabBarPrivate::_q_scrollTabs()
-{
- Q_Q(QTabBar);
- const QObject *sender = q->sender();
- int i = -1;
- if (!verticalTabs(shape)) {
- if (sender == leftB) {
- for (i = tabList.count() - 1; i >= 0; --i) {
- if (tabList.at(i).rect.left() - scrollOffset < 0) {
- makeVisible(i);
- return;
- }
- }
- } else if (sender == rightB) {
- int availableWidth = q->width() - extraWidth();
- for (i = 0; i < tabList.count(); ++i) {
- if (tabList.at(i).rect.right() - scrollOffset > availableWidth) {
- makeVisible(i);
- return;
- }
- }
- }
- } else { // vertical
- if (sender == leftB) {
- for (i = tabList.count() - 1; i >= 0; --i) {
- if (tabList.at(i).rect.top() - scrollOffset < 0) {
- makeVisible(i);
- return;
- }
- }
- } else if (sender == rightB) {
- int available = q->height() - extraWidth();
- for (i = 0; i < tabList.count(); ++i) {
- if (tabList.at(i).rect.bottom() - scrollOffset > available) {
- makeVisible(i);
- return;
- }
- }
- }
- }
-}
-
-void QTabBarPrivate::refresh()
-{
- Q_Q(QTabBar);
-
- // be safe in case a subclass is also handling move with the tabs
- if (pressedIndex != -1
- && movable
- && QApplication::mouseButtons() == Qt::NoButton) {
- moveTabFinished(pressedIndex);
- if (!validIndex(pressedIndex))
- pressedIndex = -1;
- }
-
- if (!q->isVisible()) {
- layoutDirty = true;
- } else {
- layoutTabs();
- makeVisible(currentIndex);
- q->update();
- q->updateGeometry();
- }
-}
-
-/*!
- Creates a new tab bar with the given \a parent.
-*/
-QTabBar::QTabBar(QWidget* parent)
- :QWidget(*new QTabBarPrivate, parent, 0)
-{
- Q_D(QTabBar);
- d->init();
-}
-
-
-/*!
- Destroys the tab bar.
-*/
-QTabBar::~QTabBar()
-{
-}
-
-/*!
- \property QTabBar::shape
- \brief the shape of the tabs in the tab bar
-
- Possible values for this property are described by the Shape enum.
-*/
-
-
-QTabBar::Shape QTabBar::shape() const
-{
- Q_D(const QTabBar);
- return d->shape;
-}
-
-void QTabBar::setShape(Shape shape)
-{
- Q_D(QTabBar);
- if (d->shape == shape)
- return;
- d->shape = shape;
- d->refresh();
-}
-
-/*!
- \property QTabBar::drawBase
- \brief defines whether or not tab bar should draw its base.
-
- If true then QTabBar draws a base in relation to the styles overlab.
- Otherwise only the tabs are drawn.
-
- \sa QStyle::pixelMetric() QStyle::PM_TabBarBaseOverlap QStyleOptionTabBarBaseV2
-*/
-
-void QTabBar::setDrawBase(bool drawBase)
-{
- Q_D(QTabBar);
- if (d->drawBase == drawBase)
- return;
- d->drawBase = drawBase;
- update();
-}
-
-bool QTabBar::drawBase() const
-{
- Q_D(const QTabBar);
- return d->drawBase;
-}
-
-/*!
- Adds a new tab with text \a text. Returns the new
- tab's index.
-*/
-int QTabBar::addTab(const QString &text)
-{
- return insertTab(-1, text);
-}
-
-/*!
- \overload
-
- Adds a new tab with icon \a icon and text \a
- text. Returns the new tab's index.
-*/
-int QTabBar::addTab(const QIcon& icon, const QString &text)
-{
- return insertTab(-1, icon, text);
-}
-
-/*!
- Inserts a new tab with text \a text at position \a index. If \a
- index is out of range, the new tab is appened. Returns the new
- tab's index.
-*/
-int QTabBar::insertTab(int index, const QString &text)
-{
- return insertTab(index, QIcon(), text);
-}
-
-/*!\overload
-
- Inserts a new tab with icon \a icon and text \a text at position
- \a index. If \a index is out of range, the new tab is
- appended. Returns the new tab's index.
-
- If the QTabBar was empty before this function is called, the inserted tab
- becomes the current tab.
-
- Inserting a new tab at an index less than or equal to the current index
- will increment the current index, but keep the current tab.
-*/
-int QTabBar::insertTab(int index, const QIcon& icon, const QString &text)
-{
- Q_D(QTabBar);
- if (!d->validIndex(index)) {
- index = d->tabList.count();
- d->tabList.append(QTabBarPrivate::Tab(icon, text));
- } else {
- d->tabList.insert(index, QTabBarPrivate::Tab(icon, text));
- }
-#ifndef QT_NO_SHORTCUT
- d->tabList[index].shortcutId = grabShortcut(QKeySequence::mnemonic(text));
-#endif
- d->refresh();
- if (d->tabList.count() == 1)
- setCurrentIndex(index);
- else if (index <= d->currentIndex)
- ++d->currentIndex;
-
- if (d->closeButtonOnTabs) {
- QStyleOptionTabV3 opt;
- initStyleOption(&opt, index);
- ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, this);
- QAbstractButton *closeButton = new CloseButton(this);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(_q_closeTab()));
- setTabButton(index, closeSide, closeButton);
- }
-
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (d->tabList[i].lastTab >= index)
- ++d->tabList[i].lastTab;
- }
-
- tabInserted(index);
- return index;
-}
-
-
-/*!
- Removes the tab at position \a index.
-
- \sa SelectionBehavior
- */
-void QTabBar::removeTab(int index)
-{
- Q_D(QTabBar);
- if (d->validIndex(index)) {
-#ifndef QT_NO_SHORTCUT
- releaseShortcut(d->tabList.at(index).shortcutId);
-#endif
- if (d->tabList[index].leftWidget) {
- d->tabList[index].leftWidget->hide();
- d->tabList[index].leftWidget->deleteLater();
- d->tabList[index].leftWidget = 0;
- }
- if (d->tabList[index].rightWidget) {
- d->tabList[index].rightWidget->hide();
- d->tabList[index].rightWidget->deleteLater();
- d->tabList[index].rightWidget = 0;
- }
-
- int newIndex = d->tabList[index].lastTab;
- d->tabList.removeAt(index);
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (d->tabList[i].lastTab == index)
- d->tabList[i].lastTab = -1;
- if (d->tabList[i].lastTab > index)
- --d->tabList[i].lastTab;
- }
- if (index == d->currentIndex) {
- // The current tab is going away, in order to make sure
- // we emit that "current has changed", we need to reset this
- // around.
- d->currentIndex = -1;
- if (d->tabList.size() > 0) {
- switch(d->selectionBehaviorOnRemove) {
- case SelectPreviousTab:
- if (newIndex > index)
- newIndex--;
- if (d->validIndex(newIndex))
- break;
- // else fallthrough
- case SelectRightTab:
- newIndex = index;
- if (newIndex >= d->tabList.size())
- newIndex = d->tabList.size() - 1;
- break;
- case SelectLeftTab:
- newIndex = index - 1;
- if (newIndex < 0)
- newIndex = 0;
- break;
- default:
- break;
- }
-
- if (d->validIndex(newIndex)) {
- // don't loose newIndex's old through setCurrentIndex
- int bump = d->tabList[newIndex].lastTab;
- setCurrentIndex(newIndex);
- d->tabList[newIndex].lastTab = bump;
- }
- } else {
- emit currentChanged(-1);
- }
- } else if (index < d->currentIndex) {
- setCurrentIndex(d->currentIndex - 1);
- }
- d->refresh();
- tabRemoved(index);
- }
-}
-
-
-/*!
- Returns true if the tab at position \a index is enabled; otherwise
- returns false.
-*/
-bool QTabBar::isTabEnabled(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->enabled;
- return false;
-}
-
-/*!
- If \a enabled is true then the tab at position \a index is
- enabled; otherwise the item at position \a index is disabled.
-*/
-void QTabBar::setTabEnabled(int index, bool enabled)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index)) {
- tab->enabled = enabled;
-#ifndef QT_NO_SHORTCUT
- setShortcutEnabled(tab->shortcutId, enabled);
-#endif
- update();
- if (!enabled && index == d->currentIndex)
- setCurrentIndex(d->validIndex(index+1)?index+1:0);
- else if (enabled && !d->validIndex(d->currentIndex))
- setCurrentIndex(index);
- }
-}
-
-
-/*!
- Returns the text of the tab at position \a index, or an empty
- string if \a index is out of range.
-*/
-QString QTabBar::tabText(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->text;
- return QString();
-}
-
-/*!
- Sets the text of the tab at position \a index to \a text.
-*/
-void QTabBar::setTabText(int index, const QString &text)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index)) {
- tab->text = text;
-#ifndef QT_NO_SHORTCUT
- releaseShortcut(tab->shortcutId);
- tab->shortcutId = grabShortcut(QKeySequence::mnemonic(text));
- setShortcutEnabled(tab->shortcutId, tab->enabled);
-#endif
- d->refresh();
- }
-}
-
-/*!
- Returns the text color of the tab with the given \a index, or a invalid
- color if \a index is out of range.
-
- \sa setTabTextColor()
-*/
-QColor QTabBar::tabTextColor(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->textColor;
- return QColor();
-}
-
-/*!
- Sets the color of the text in the tab with the given \a index to the specified \a color.
-
- If an invalid color is specified, the tab will use the QTabBar foreground role instead.
-
- \sa tabTextColor()
-*/
-void QTabBar::setTabTextColor(int index, const QColor &color)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index)) {
- tab->textColor = color;
- update(tabRect(index));
- }
-}
-
-/*!
- Returns the icon of the tab at position \a index, or a null icon
- if \a index is out of range.
-*/
-QIcon QTabBar::tabIcon(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->icon;
- return QIcon();
-}
-
-/*!
- Sets the icon of the tab at position \a index to \a icon.
-*/
-void QTabBar::setTabIcon(int index, const QIcon & icon)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index)) {
- bool simpleIconChange = (!icon.isNull() && !tab->icon.isNull());
- tab->icon = icon;
- if (simpleIconChange)
- update(tabRect(index));
- else
- d->refresh();
- }
-}
-
-#ifndef QT_NO_TOOLTIP
-/*!
- Sets the tool tip of the tab at position \a index to \a tip.
-*/
-void QTabBar::setTabToolTip(int index, const QString & tip)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index))
- tab->toolTip = tip;
-}
-
-/*!
- Returns the tool tip of the tab at position \a index, or an empty
- string if \a index is out of range.
-*/
-QString QTabBar::tabToolTip(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->toolTip;
- return QString();
-}
-#endif // QT_NO_TOOLTIP
-
-#ifndef QT_NO_WHATSTHIS
-/*!
- \since 4.1
-
- Sets the What's This help text of the tab at position \a index
- to \a text.
-*/
-void QTabBar::setTabWhatsThis(int index, const QString &text)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index))
- tab->whatsThis = text;
-}
-
-/*!
- \since 4.1
-
- Returns the What's This help text of the tab at position \a index,
- or an empty string if \a index is out of range.
-*/
-QString QTabBar::tabWhatsThis(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->whatsThis;
- return QString();
-}
-
-#endif // QT_NO_WHATSTHIS
-
-/*!
- Sets the data of the tab at position \a index to \a data.
-*/
-void QTabBar::setTabData(int index, const QVariant & data)
-{
- Q_D(QTabBar);
- if (QTabBarPrivate::Tab *tab = d->at(index))
- tab->data = data;
-}
-
-/*!
- Returns the data of the tab at position \a index, or a null
- variant if \a index is out of range.
-*/
-QVariant QTabBar::tabData(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index))
- return tab->data;
- return QVariant();
-}
-
-/*!
- Returns the visual rectangle of the tab at position \a
- index, or a null rectangle if \a index is out of range.
-*/
-QRect QTabBar::tabRect(int index) const
-{
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index)) {
- if (d->layoutDirty)
- const_cast<QTabBarPrivate*>(d)->layoutTabs();
- QRect r = tab->rect;
- if (verticalTabs(d->shape))
- r.translate(0, -d->scrollOffset);
- else
- r.translate(-d->scrollOffset, 0);
- if (!verticalTabs(d->shape))
- r = QStyle::visualRect(layoutDirection(), rect(), r);
- return r;
- }
- return QRect();
-}
-
-/*!
- \since 4.3
- Returns the index of the tab that covers \a position or -1 if no
- tab covers \a position;
-*/
-
-int QTabBar::tabAt(const QPoint &position) const
-{
- Q_D(const QTabBar);
- if (d->validIndex(d->currentIndex)
- && tabRect(d->currentIndex).contains(position)) {
- return d->currentIndex;
- }
- const int max = d->tabList.size();
- for (int i = 0; i < max; ++i) {
- if (tabRect(i).contains(position)) {
- return i;
- }
- }
- return -1;
-}
-
-/*!
- \property QTabBar::currentIndex
- \brief the index of the tab bar's visible tab
-
- The current index is -1 if there is no current tab.
-*/
-
-int QTabBar::currentIndex() const
-{
- Q_D(const QTabBar);
- if (d->validIndex(d->currentIndex))
- return d->currentIndex;
- return -1;
-}
-
-
-void QTabBar::setCurrentIndex(int index)
-{
- Q_D(QTabBar);
- if (d->dragInProgress && d->pressedIndex != -1)
- return;
-
- int oldIndex = d->currentIndex;
- if (d->validIndex(index) && d->currentIndex != index) {
- d->currentIndex = index;
- update();
- d->makeVisible(index);
- d->tabList[index].lastTab = oldIndex;
- if (oldIndex >= 0 && oldIndex < count())
- d->layoutTab(oldIndex);
- d->layoutTab(index);
-#ifndef QT_NO_ACCESSIBILITY
- if (QAccessible::isActive()) {
- QAccessible::updateAccessibility(this, index + 1, QAccessible::Focus);
- QAccessible::updateAccessibility(this, index + 1, QAccessible::Selection);
- }
-#endif
-#ifdef QT3_SUPPORT
- emit selected(index);
-#endif
- emit currentChanged(index);
- }
-}
-
-/*!
- \property QTabBar::iconSize
- \brief The size for icons in the tab bar
- \since 4.1
-
- The default value is style-dependent. \c iconSize is a maximum
- size; icons that are smaller are not scaled up.
-
- \sa QTabWidget::iconSize
-*/
-QSize QTabBar::iconSize() const
-{
- Q_D(const QTabBar);
- if (d->iconSize.isValid())
- return d->iconSize;
- int iconExtent = style()->pixelMetric(QStyle::PM_TabBarIconSize, 0, this);
- return QSize(iconExtent, iconExtent);
-
-}
-
-void QTabBar::setIconSize(const QSize &size)
-{
- Q_D(QTabBar);
- d->iconSize = size;
- d->layoutDirty = true;
- update();
- updateGeometry();
-}
-
-/*!
- \property QTabBar::count
- \brief the number of tabs in the tab bar
-*/
-
-int QTabBar::count() const
-{
- Q_D(const QTabBar);
- return d->tabList.count();
-}
-
-
-/*!\reimp
- */
-QSize QTabBar::sizeHint() const
-{
- Q_D(const QTabBar);
- if (d->layoutDirty)
- const_cast<QTabBarPrivate*>(d)->layoutTabs();
- QRect r;
- for (int i = 0; i < d->tabList.count(); ++i)
- r = r.united(d->tabList.at(i).maxRect);
- QSize sz = QApplication::globalStrut();
- return r.size().expandedTo(sz);
-}
-
-/*!\reimp
- */
-QSize QTabBar::minimumSizeHint() const
-{
- Q_D(const QTabBar);
- if (d->layoutDirty)
- const_cast<QTabBarPrivate*>(d)->layoutTabs();
- if (!d->useScrollButtons) {
- QRect r;
- for (int i = 0; i < d->tabList.count(); ++i)
- r = r.united(d->tabList.at(i).minRect);
- return r.size().expandedTo(QApplication::globalStrut());
- }
- if (verticalTabs(d->shape))
- return QSize(sizeHint().width(), d->rightB->sizeHint().height() * 2 + 75);
- else
- return QSize(d->rightB->sizeHint().width() * 2 + 75, sizeHint().height());
-}
-
-// Compute the most-elided possible text, for minimumSizeHint
-static QString computeElidedText(Qt::TextElideMode mode, const QString &text)
-{
- if (text.length() <= 3)
- return text;
-
- static const QLatin1String Ellipses("...");
- QString ret;
- switch (mode) {
- case Qt::ElideRight:
- ret = text.left(2) + Ellipses;
- break;
- case Qt::ElideMiddle:
- ret = text.left(1) + Ellipses + text.right(1);
- break;
- case Qt::ElideLeft:
- ret = Ellipses + text.right(2);
- break;
- case Qt::ElideNone:
- ret = text;
- break;
- }
- return ret;
-}
-
-QSize QTabBarPrivate::minimumTabSizeHint(int index)
-{
- Q_Q(QTabBar);
- // ### Qt 5: make this a protected virtual function in QTabBar
- Tab &tab = tabList[index];
- QString oldText = tab.text;
- tab.text = computeElidedText(elideMode, oldText);
- QSize size = q->tabSizeHint(index);
- tab.text = oldText;
- return size;
-}
-
-/*!
- Returns the size hint for the tab at position \a index.
-*/
-QSize QTabBar::tabSizeHint(int index) const
-{
- //Note: this must match with the computations in QCommonStylePrivate::tabLayout
- Q_D(const QTabBar);
- if (const QTabBarPrivate::Tab *tab = d->at(index)) {
- QStyleOptionTabV3 opt;
- initStyleOption(&opt, index);
- opt.text = d->tabList.at(index).text;
- QSize iconSize = tab->icon.isNull() ? QSize(0, 0) : opt.iconSize;
- int hframe = style()->pixelMetric(QStyle::PM_TabBarTabHSpace, &opt, this);
- int vframe = style()->pixelMetric(QStyle::PM_TabBarTabVSpace, &opt, this);
- const QFontMetrics fm = fontMetrics();
-
- int maxWidgetHeight = qMax(opt.leftButtonSize.height(), opt.rightButtonSize.height());
- int maxWidgetWidth = qMax(opt.leftButtonSize.width(), opt.rightButtonSize.width());
-
- int widgetWidth = 0;
- int widgetHeight = 0;
- int padding = 0;
- if (!opt.leftButtonSize.isEmpty()) {
- padding += 4;
- widgetWidth += opt.leftButtonSize.width();
- widgetHeight += opt.leftButtonSize.height();
- }
- if (!opt.rightButtonSize.isEmpty()) {
- padding += 4;
- widgetWidth += opt.rightButtonSize.width();
- widgetHeight += opt.rightButtonSize.height();
- }
- if (!opt.icon.isNull())
- padding += 4;
-
- QSize csz;
- if (verticalTabs(d->shape)) {
- csz = QSize( qMax(maxWidgetWidth, qMax(fm.height(), iconSize.height())) + vframe,
- fm.size(Qt::TextShowMnemonic, tab->text).width() + iconSize.width() + hframe + widgetHeight + padding);
- } else {
- csz = QSize(fm.size(Qt::TextShowMnemonic, tab->text).width() + iconSize.width() + hframe
- + widgetWidth + padding,
- qMax(maxWidgetHeight, qMax(fm.height(), iconSize.height())) + vframe);
- }
-
- QSize retSize = style()->sizeFromContents(QStyle::CT_TabBarTab, &opt, csz, this);
- return retSize;
- }
- return QSize();
-}
-
-/*!
- This virtual handler is called after a new tab was added or
- inserted at position \a index.
-
- \sa tabRemoved()
- */
-void QTabBar::tabInserted(int index)
-{
- Q_UNUSED(index)
-}
-
-/*!
- This virtual handler is called after a tab was removed from
- position \a index.
-
- \sa tabInserted()
- */
-void QTabBar::tabRemoved(int index)
-{
- Q_UNUSED(index)
-}
-
-/*!
- This virtual handler is called whenever the tab layout changes.
-
- \sa tabRect()
- */
-void QTabBar::tabLayoutChange()
-{
-}
-
-
-/*!\reimp
- */
-void QTabBar::showEvent(QShowEvent *)
-{
- Q_D(QTabBar);
- if (d->layoutDirty)
- d->refresh();
- if (!d->validIndex(d->currentIndex))
- setCurrentIndex(0);
- d->updateMacBorderMetrics();
-}
-
-/*!\reimp
- */
-void QTabBar::hideEvent(QHideEvent *)
-{
- Q_D(QTabBar);
- d->updateMacBorderMetrics();
-}
-
-/*!\reimp
- */
-bool QTabBar::event(QEvent *event)
-{
- Q_D(QTabBar);
- if (event->type() == QEvent::HoverMove
- || event->type() == QEvent::HoverEnter) {
- QHoverEvent *he = static_cast<QHoverEvent *>(event);
- if (!d->hoverRect.contains(he->pos())) {
- QRect oldHoverRect = d->hoverRect;
- for (int i = 0; i < d->tabList.count(); ++i) {
- QRect area = tabRect(i);
- if (area.contains(he->pos())) {
- d->hoverRect = area;
- break;
- }
- }
- if (he->oldPos() != QPoint(-1, -1))
- update(oldHoverRect);
- update(d->hoverRect);
- }
- return true;
- } else if (event->type() == QEvent::HoverLeave ) {
- QRect oldHoverRect = d->hoverRect;
- d->hoverRect = QRect();
- update(oldHoverRect);
- return true;
-#ifndef QT_NO_TOOLTIP
- } else if (event->type() == QEvent::ToolTip) {
- if (const QTabBarPrivate::Tab *tab = d->at(tabAt(static_cast<QHelpEvent*>(event)->pos()))) {
- if (!tab->toolTip.isEmpty()) {
- QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), tab->toolTip, this);
- return true;
- }
- }
-#endif // QT_NO_TOOLTIP
-#ifndef QT_NO_WHATSTHIS
- } else if (event->type() == QEvent::QueryWhatsThis) {
- const QTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent*>(event)->pos()));
- if (!tab || tab->whatsThis.isEmpty())
- event->ignore();
- return true;
- } else if (event->type() == QEvent::WhatsThis) {
- if (const QTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent*>(event)->pos()))) {
- if (!tab->whatsThis.isEmpty()) {
- QWhatsThis::showText(static_cast<QHelpEvent*>(event)->globalPos(),
- tab->whatsThis, this);
- return true;
- }
- }
-#endif // QT_NO_WHATSTHIS
-#ifndef QT_NO_SHORTCUT
- } else if (event->type() == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(event);
- for (int i = 0; i < d->tabList.count(); ++i) {
- const QTabBarPrivate::Tab *tab = &d->tabList.at(i);
- if (tab->shortcutId == se->shortcutId()) {
- setCurrentIndex(i);
- return true;
- }
- }
-#endif
- }
- return QWidget::event(event);
-}
-
-/*!\reimp
- */
-void QTabBar::resizeEvent(QResizeEvent *)
-{
- Q_D(QTabBar);
- if (d->layoutDirty)
- updateGeometry();
- d->layoutTabs();
-
- d->makeVisible(d->currentIndex);
-}
-
-/*!\reimp
- */
-void QTabBar::paintEvent(QPaintEvent *)
-{
- Q_D(QTabBar);
-
- QStyleOptionTabBarBaseV2 optTabBase;
- QTabBarPrivate::initStyleBaseOption(&optTabBase, this, size());
-
- QStylePainter p(this);
- int selected = -1;
- int cut = -1;
- bool rtl = optTabBase.direction == Qt::RightToLeft;
- bool vertical = verticalTabs(d->shape);
- QStyleOptionTab cutTab;
- selected = d->currentIndex;
- if (d->dragInProgress)
- selected = d->pressedIndex;
-
- for (int i = 0; i < d->tabList.count(); ++i)
- optTabBase.tabBarRect |= tabRect(i);
-
- optTabBase.selectedTabRect = tabRect(selected);
-
- if (d->drawBase)
- p.drawPrimitive(QStyle::PE_FrameTabBarBase, optTabBase);
-
- for (int i = 0; i < d->tabList.count(); ++i) {
- QStyleOptionTabV3 tab;
- initStyleOption(&tab, i);
- if (d->paintWithOffsets && d->tabList[i].dragOffset != 0) {
- if (vertical) {
- tab.rect.moveTop(tab.rect.y() + d->tabList[i].dragOffset);
- } else {
- tab.rect.moveLeft(tab.rect.x() + d->tabList[i].dragOffset);
- }
- }
- if (!(tab.state & QStyle::State_Enabled)) {
- tab.palette.setCurrentColorGroup(QPalette::Disabled);
- }
- // If this tab is partially obscured, make a note of it so that we can pass the information
- // along when we draw the tear.
- if (((!vertical && (!rtl && tab.rect.left() < 0)) || (rtl && tab.rect.right() > width()))
- || (vertical && tab.rect.top() < 0)) {
- cut = i;
- cutTab = tab;
- }
- // Don't bother drawing a tab if the entire tab is outside of the visible tab bar.
- if ((!vertical && (tab.rect.right() < 0 || tab.rect.left() > width()))
- || (vertical && (tab.rect.bottom() < 0 || tab.rect.top() > height())))
- continue;
-
- optTabBase.tabBarRect |= tab.rect;
- if (i == selected)
- continue;
-
- p.drawControl(QStyle::CE_TabBarTab, tab);
- }
-
- // Draw the selected tab last to get it "on top"
- if (selected >= 0) {
- QStyleOptionTabV3 tab;
- initStyleOption(&tab, selected);
- if (d->paintWithOffsets && d->tabList[selected].dragOffset != 0) {
- if (vertical)
- tab.rect.moveTop(tab.rect.y() + d->tabList[selected].dragOffset);
- else
- tab.rect.moveLeft(tab.rect.x() + d->tabList[selected].dragOffset);
- }
- if (!d->dragInProgress)
- p.drawControl(QStyle::CE_TabBarTab, tab);
- else {
- int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0, this);
- d->movingTab->setGeometry(tab.rect.adjusted(-taboverlap, 0, taboverlap, 0));
- }
- }
-
- // Only draw the tear indicator if necessary. Most of the time we don't need too.
- if (d->leftB->isVisible() && cut >= 0) {
- cutTab.rect = rect();
- cutTab.rect = style()->subElementRect(QStyle::SE_TabBarTearIndicator, &cutTab, this);
- p.drawPrimitive(QStyle::PE_IndicatorTabTear, cutTab);
- }
-}
-
-/*
- Given that index at position from moved to position to where return where index goes.
- */
-int QTabBarPrivate::calculateNewPosition(int from, int to, int index) const
-{
- if (index == from)
- return to;
-
- int start = qMin(from, to);
- int end = qMax(from, to);
- if (index >= start && index <= end)
- index += (from < to) ? -1 : 1;
- return index;
-}
-
-/*!
- Moves the item at index position \a from to index position \a to.
- \since 4.5
-
- \sa tabMoved(), tabLayoutChange()
- */
-void QTabBar::moveTab(int from, int to)
-{
- Q_D(QTabBar);
- if (from == to
- || !d->validIndex(from)
- || !d->validIndex(to))
- return;
-
- bool vertical = verticalTabs(d->shape);
- int oldPressedPosition = 0;
- if (d->pressedIndex != -1) {
- // Record the position of the pressed tab before reordering the tabs.
- oldPressedPosition = vertical ? d->tabList[d->pressedIndex].rect.y()
- : d->tabList[d->pressedIndex].rect.x();
- }
-
- // Update the locations of the tabs first
- int start = qMin(from, to);
- int end = qMax(from, to);
- int width = vertical ? d->tabList[from].rect.height() : d->tabList[from].rect.width();
- if (from < to)
- width *= -1;
- bool rtl = isRightToLeft();
- for (int i = start; i <= end; ++i) {
- if (i == from)
- continue;
- if (vertical)
- d->tabList[i].rect.moveTop(d->tabList[i].rect.y() + width);
- else
- d->tabList[i].rect.moveLeft(d->tabList[i].rect.x() + width);
- int direction = -1;
- if (rtl && !vertical)
- direction *= -1;
- if (d->tabList[i].dragOffset != 0)
- d->tabList[i].dragOffset += (direction * width);
- }
-
- if (vertical) {
- if (from < to)
- d->tabList[from].rect.moveTop(d->tabList[to].rect.bottom() + 1);
- else
- d->tabList[from].rect.moveTop(d->tabList[to].rect.top() - width);
- } else {
- if (from < to)
- d->tabList[from].rect.moveLeft(d->tabList[to].rect.right() + 1);
- else
- d->tabList[from].rect.moveLeft(d->tabList[to].rect.left() - width);
- }
-
- // Move the actual data structures
- d->tabList.move(from, to);
-
- // update lastTab locations
- for (int i = 0; i < d->tabList.count(); ++i)
- d->tabList[i].lastTab = d->calculateNewPosition(from, to, d->tabList[i].lastTab);
-
- // update external variables
- d->currentIndex = d->calculateNewPosition(from, to, d->currentIndex);
-
- // If we are in the middle of a drag update the dragStartPosition
- if (d->pressedIndex != -1) {
- d->pressedIndex = d->calculateNewPosition(from, to, d->pressedIndex);
- int newPressedPosition = vertical ? d->tabList[d->pressedIndex].rect.top() : d->tabList[d->pressedIndex].rect.left();
- int diff = oldPressedPosition - newPressedPosition;
- if (isRightToLeft() && !vertical)
- diff *= -1;
- if (vertical)
- d->dragStartPosition.setY(d->dragStartPosition.y() - diff);
- else
- d->dragStartPosition.setX(d->dragStartPosition.x() - diff);
- }
-
- d->layoutWidgets(start);
- update();
- emit tabMoved(from, to);
- emit tabLayoutChange();
-}
-
-void QTabBarPrivate::slide(int from, int to)
-{
- Q_Q(QTabBar);
- if (from == to
- || !validIndex(from)
- || !validIndex(to))
- return;
- bool vertical = verticalTabs(shape);
- int preLocation = vertical ? q->tabRect(from).y() : q->tabRect(from).x();
- q->setUpdatesEnabled(false);
- q->moveTab(from, to);
- q->setUpdatesEnabled(true);
- int postLocation = vertical ? q->tabRect(to).y() : q->tabRect(to).x();
- int length = postLocation - preLocation;
- tabList[to].dragOffset -= length;
- tabList[to].startAnimation(this, ANIMATION_DURATION);
-}
-
-void QTabBarPrivate::moveTab(int index, int offset)
-{
- if (!validIndex(index))
- return;
- tabList[index].dragOffset = offset;
- layoutTab(index); // Make buttons follow tab
- q_func()->update();
-}
-
-/*!\reimp
-*/
-void QTabBar::mousePressEvent(QMouseEvent *event)
-{
- Q_D(QTabBar);
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
- // Be safe!
- if (d->pressedIndex != -1 && d->movable)
- d->moveTabFinished(d->pressedIndex);
-
- d->pressedIndex = d->indexAtPos(event->pos());
-#ifdef Q_WS_MAC
- d->previousPressedIndex = d->pressedIndex;
-#endif
- if (d->validIndex(d->pressedIndex)) {
- QStyleOptionTabBarBaseV2 optTabBase;
- optTabBase.init(this);
- optTabBase.documentMode = d->documentMode;
- if (event->type() == style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this))
- setCurrentIndex(d->pressedIndex);
- else
- repaint(tabRect(d->pressedIndex));
- if (d->movable) {
- d->dragStartPosition = event->pos();
- }
- }
-}
-
-/*!\reimp
- */
-void QTabBar::mouseMoveEvent(QMouseEvent *event)
-{
- Q_D(QTabBar);
- if (d->movable) {
- // Be safe!
- if (d->pressedIndex != -1
- && event->buttons() == Qt::NoButton)
- d->moveTabFinished(d->pressedIndex);
-
- // Start drag
- if (!d->dragInProgress && d->pressedIndex != -1) {
- if ((event->pos() - d->dragStartPosition).manhattanLength() > QApplication::startDragDistance()) {
- d->dragInProgress = true;
- d->setupMovableTab();
- }
- }
-
- int offset = (event->pos() - d->dragStartPosition).manhattanLength();
- if (event->buttons() == Qt::LeftButton
- && offset > QApplication::startDragDistance()
- && d->validIndex(d->pressedIndex)) {
- bool vertical = verticalTabs(d->shape);
- int dragDistance;
- if (vertical) {
- dragDistance = (event->pos().y() - d->dragStartPosition.y());
- } else {
- dragDistance = (event->pos().x() - d->dragStartPosition.x());
- }
- d->tabList[d->pressedIndex].dragOffset = dragDistance;
-
- QRect startingRect = tabRect(d->pressedIndex);
- if (vertical)
- startingRect.moveTop(startingRect.y() + dragDistance);
- else
- startingRect.moveLeft(startingRect.x() + dragDistance);
-
- int overIndex;
- if (dragDistance < 0)
- overIndex = tabAt(startingRect.topLeft());
- else
- overIndex = tabAt(startingRect.topRight());
-
- if (overIndex != d->pressedIndex && overIndex != -1) {
- int offset = 1;
- if (isRightToLeft() && !vertical)
- offset *= -1;
- if (dragDistance < 0) {
- dragDistance *= -1;
- offset *= -1;
- }
- for (int i = d->pressedIndex;
- offset > 0 ? i < overIndex : i > overIndex;
- i += offset) {
- QRect overIndexRect = tabRect(overIndex);
- int needsToBeOver = (vertical ? overIndexRect.height() : overIndexRect.width()) / 2;
- if (dragDistance > needsToBeOver)
- d->slide(i + offset, d->pressedIndex);
- }
- }
- // Buttons needs to follow the dragged tab
- d->layoutTab(d->pressedIndex);
-
- update();
- }
-#ifdef Q_WS_MAC
- } else if (!d->documentMode && event->buttons() == Qt::LeftButton && d->previousPressedIndex != -1) {
- int newPressedIndex = d->indexAtPos(event->pos());
- if (d->pressedIndex == -1 && d->previousPressedIndex == newPressedIndex) {
- d->pressedIndex = d->previousPressedIndex;
- update(tabRect(d->pressedIndex));
- } else if(d->pressedIndex != newPressedIndex) {
- d->pressedIndex = -1;
- update(tabRect(d->previousPressedIndex));
- }
-#endif
- }
-
- if (event->buttons() != Qt::LeftButton) {
- event->ignore();
- return;
- }
- QStyleOptionTabBarBaseV2 optTabBase;
- optTabBase.init(this);
- optTabBase.documentMode = d->documentMode;
-}
-
-void QTabBarPrivate::setupMovableTab()
-{
- Q_Q(QTabBar);
- if (!movingTab)
- movingTab = new QWidget(q);
-
- int taboverlap = q->style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0 ,q);
- QRect grabRect = q->tabRect(pressedIndex);
- grabRect.adjust(-taboverlap, 0, taboverlap, 0);
-
- QPixmap grabImage(grabRect.size());
- grabImage.fill(Qt::transparent);
- QStylePainter p(&grabImage, q);
- p.initFrom(q);
-
- QStyleOptionTabV3 tab;
- q->initStyleOption(&tab, pressedIndex);
- tab.rect.moveTopLeft(QPoint(taboverlap, 0));
- p.drawControl(QStyle::CE_TabBarTab, tab);
- p.end();
-
- QPalette pal;
- pal.setBrush(QPalette::All, QPalette::Window, grabImage);
- movingTab->setPalette(pal);
- movingTab->setGeometry(grabRect);
- movingTab->setAutoFillBackground(true);
- movingTab->raise();
-
- // Re-arrange widget order to avoid overlaps
- if (tabList[pressedIndex].leftWidget)
- tabList[pressedIndex].leftWidget->raise();
- if (tabList[pressedIndex].rightWidget)
- tabList[pressedIndex].rightWidget->raise();
- if (leftB)
- leftB->raise();
- if (rightB)
- rightB->raise();
- movingTab->setVisible(true);
-}
-
-void QTabBarPrivate::moveTabFinished(int index)
-{
- Q_Q(QTabBar);
- bool cleanup = (pressedIndex == index) || (pressedIndex == -1) || !validIndex(index);
- bool allAnimationsFinished = true;
-#ifndef QT_NO_ANIMATION
- for(int i = 0; allAnimationsFinished && i < tabList.count(); ++i) {
- const Tab &t = tabList.at(i);
- if (t.animation && t.animation->state() == QAbstractAnimation::Running)
- allAnimationsFinished = false;
- }
-#endif //QT_NO_ANIMATION
- if (allAnimationsFinished && cleanup) {
- if(movingTab)
- movingTab->setVisible(false); // We might not get a mouse release
- for (int i = 0; i < tabList.count(); ++i) {
- tabList[i].dragOffset = 0;
- }
- if (pressedIndex != -1 && movable) {
- pressedIndex = -1;
- dragInProgress = false;
- dragStartPosition = QPoint();
- }
- layoutWidgets();
- } else {
- if (!validIndex(index))
- return;
- tabList[index].dragOffset = 0;
- }
- q->update();
-}
-
-/*!\reimp
-*/
-void QTabBar::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_D(QTabBar);
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
-#ifdef Q_WS_MAC
- d->previousPressedIndex = -1;
-#endif
- if (d->movable && d->dragInProgress && d->validIndex(d->pressedIndex)) {
- int length = d->tabList[d->pressedIndex].dragOffset;
- int width = verticalTabs(d->shape)
- ? tabRect(d->pressedIndex).height()
- : tabRect(d->pressedIndex).width();
- int duration = qMin(ANIMATION_DURATION,
- (qAbs(length) * ANIMATION_DURATION) / width);
- d->tabList[d->pressedIndex].startAnimation(d, duration);
- d->dragInProgress = false;
- d->movingTab->setVisible(false);
- d->dragStartPosition = QPoint();
- }
-
- int i = d->indexAtPos(event->pos()) == d->pressedIndex ? d->pressedIndex : -1;
- d->pressedIndex = -1;
- QStyleOptionTabBarBaseV2 optTabBase;
- optTabBase.initFrom(this);
- optTabBase.documentMode = d->documentMode;
- if (style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this) == QEvent::MouseButtonRelease)
- setCurrentIndex(i);
-}
-
-/*!\reimp
- */
-void QTabBar::keyPressEvent(QKeyEvent *event)
-{
- Q_D(QTabBar);
- if (event->key() != Qt::Key_Left && event->key() != Qt::Key_Right) {
- event->ignore();
- return;
- }
- int offset = event->key() == (isRightToLeft() ? Qt::Key_Right : Qt::Key_Left) ? -1 : 1;
- d->setCurrentNextEnabledIndex(offset);
-}
-
-/*!\reimp
- */
-#ifndef QT_NO_WHEELEVENT
-void QTabBar::wheelEvent(QWheelEvent *event)
-{
- Q_D(QTabBar);
- int offset = event->delta() > 0 ? -1 : 1;
- d->setCurrentNextEnabledIndex(offset);
- QWidget::wheelEvent(event);
-}
-#endif //QT_NO_WHEELEVENT
-
-void QTabBarPrivate::setCurrentNextEnabledIndex(int offset)
-{
- Q_Q(QTabBar);
- for (int index = currentIndex + offset; validIndex(index); index += offset) {
- if (tabList.at(index).enabled) {
- q->setCurrentIndex(index);
- break;
- }
- }
-}
-
-/*!\reimp
- */
-void QTabBar::changeEvent(QEvent *event)
-{
- Q_D(QTabBar);
- if (event->type() == QEvent::StyleChange) {
- if (!d->elideModeSetByUser)
- d->elideMode = Qt::TextElideMode(style()->styleHint(QStyle::SH_TabBar_ElideMode, 0, this));
- if (!d->useScrollButtonsSetByUser)
- d->useScrollButtons = !style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, 0, this);
- d->refresh();
- } else if (event->type() == QEvent::FontChange) {
- d->refresh();
- }
- QWidget::changeEvent(event);
-}
-
-/*!
- \property QTabBar::elideMode
- \brief how to elide text in the tab bar
- \since 4.2
-
- This property controls how items are elided when there is not
- enough space to show them for a given tab bar size.
-
- By default the value is style dependent.
-
- \sa QTabWidget::elideMode usesScrollButtons QStyle::SH_TabBar_ElideMode
-*/
-
-Qt::TextElideMode QTabBar::elideMode() const
-{
- Q_D(const QTabBar);
- return d->elideMode;
-}
-
-void QTabBar::setElideMode(Qt::TextElideMode mode)
-{
- Q_D(QTabBar);
- d->elideMode = mode;
- d->elideModeSetByUser = true;
- d->refresh();
-}
-
-/*!
- \property QTabBar::usesScrollButtons
- \brief Whether or not a tab bar should use buttons to scroll tabs when it
- has many tabs.
- \since 4.2
-
- When there are too many tabs in a tab bar for its size, the tab bar can either choose
- to expand its size or to add buttons that allow you to scroll through the tabs.
-
- By default the value is style dependant.
-
- \sa elideMode QTabWidget::usesScrollButtons QStyle::SH_TabBar_PreferNoArrows
-*/
-bool QTabBar::usesScrollButtons() const
-{
- return d_func()->useScrollButtons;
-}
-
-void QTabBar::setUsesScrollButtons(bool useButtons)
-{
- Q_D(QTabBar);
- d->useScrollButtonsSetByUser = true;
- if (d->useScrollButtons == useButtons)
- return;
- d->useScrollButtons = useButtons;
- d->refresh();
-}
-
-/*!
- \fn void QTabBar::setCurrentTab(int index)
-
- Use setCurrentIndex() instead.
-*/
-
-/*!
- \fn void QTabBar::selected(int index);
-
- Use currentChanged() instead.
-*/
-
-
-/*!
- \property QTabBar::tabsClosable
- \brief Whether or not a tab bar should place close buttons on each tab
- \since 4.5
-
- When tabsClosable is set to true a close button will appear on the tab on
- either the left or right hand side depending upon the style. When the button
- is clicked the tab the signal tabCloseRequested will be emitted.
-
- By default the value is false.
-
- \sa setTabButton(), tabRemoved()
-*/
-
-bool QTabBar::tabsClosable() const
-{
- Q_D(const QTabBar);
- return d->closeButtonOnTabs;
-}
-
-void QTabBar::setTabsClosable(bool closable)
-{
- Q_D(QTabBar);
- if (d->closeButtonOnTabs == closable)
- return;
- d->closeButtonOnTabs = closable;
- ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, this);
- if (!closable) {
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (closeSide == LeftSide && d->tabList[i].leftWidget) {
- d->tabList[i].leftWidget->deleteLater();
- d->tabList[i].leftWidget = 0;
- }
- if (closeSide == RightSide && d->tabList[i].rightWidget) {
- d->tabList[i].rightWidget->deleteLater();
- d->tabList[i].rightWidget = 0;
- }
- }
- } else {
- bool newButtons = false;
- for (int i = 0; i < d->tabList.count(); ++i) {
- if (tabButton(i, closeSide))
- continue;
- newButtons = true;
- QAbstractButton *closeButton = new CloseButton(this);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(_q_closeTab()));
- setTabButton(i, closeSide, closeButton);
- }
- if (newButtons)
- d->layoutTabs();
- }
- update();
-}
-
-/*!
- \enum QTabBar::ButtonPosition
- \since 4.5
-
- This enum type lists the location of the widget on a tab.
-
- \value LeftSide Left side of the tab.
-
- \value RightSide Right side of the tab.
-
-*/
-
-/*!
- \enum QTabBar::SelectionBehavior
- \since 4.5
-
- This enum type lists the behavior of QTabBar when a tab is removed
- and the tab being removed is also the current tab.
-
- \value SelectLeftTab Select the tab to the left of the one being removed.
-
- \value SelectRightTab Select the tab to the right of the one being removed.
-
- \value SelectPreviousTab Select the previously selected tab.
-
-*/
-
-/*!
- \property QTabBar::selectionBehaviorOnRemove
- \brief What tab should be set as current when removeTab is called if
- the removed tab is also the current tab.
- \since 4.5
-
- By default the value is SelectRightTab.
-
- \sa removeTab()
-*/
-
-
-QTabBar::SelectionBehavior QTabBar::selectionBehaviorOnRemove() const
-{
- Q_D(const QTabBar);
- return d->selectionBehaviorOnRemove;
-}
-
-void QTabBar::setSelectionBehaviorOnRemove(QTabBar::SelectionBehavior behavior)
-{
- Q_D(QTabBar);
- d->selectionBehaviorOnRemove = behavior;
-}
-
-/*!
- \property QTabBar::expanding
- \brief When expanding is true QTabBar will expand the tabs to use the empty space.
- \since 4.5
-
- By default the value is true.
-
- \sa QTabWidget::documentMode
-*/
-
-bool QTabBar::expanding() const
-{
- Q_D(const QTabBar);
- return d->expanding;
-}
-
-void QTabBar::setExpanding(bool enabled)
-{
- Q_D(QTabBar);
- if (d->expanding == enabled)
- return;
- d->expanding = enabled;
- d->layoutTabs();
-}
-
-/*!
- \property QTabBar::movable
- \brief This property holds whether the user can move the tabs
- within the tabbar area.
-
- \since 4.5
-
- By default, this property is false;
-*/
-
-bool QTabBar::isMovable() const
-{
- Q_D(const QTabBar);
- return d->movable;
-}
-
-void QTabBar::setMovable(bool movable)
-{
- Q_D(QTabBar);
- d->movable = movable;
-}
-
-
-/*!
- \property QTabBar::documentMode
- \brief Whether or not the tab bar is rendered in a mode suitable for the main window.
- \since 4.5
-
- This property is used as a hint for styles to draw the tabs in a different
- way then they would normally look in a tab widget. On Mac OS X this will
- look similar to the tabs in Safari or Leopard's Terminal.app.
-
- \sa QTabWidget::documentMode
-*/
-bool QTabBar::documentMode() const
-{
- return d_func()->documentMode;
-}
-
-void QTabBar::setDocumentMode(bool enabled)
-{
- Q_D(QTabBar);
-
- d->documentMode = enabled;
- d->updateMacBorderMetrics();
-}
-
-/*!
- Sets \a widget on the tab \a index. The widget is placed
- on the left or right hand side depending upon the \a position.
- \since 4.5
-
- Any previously set widget in \a position is hidden.
-
- The tab bar will take ownership of the widget and so all widgets set here
- will be deleted by the tab bar when it is destroyed unless you separately
- reparent the widget after setting some other widget (or 0).
-
- \sa tabsClosable()
- */
-void QTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget)
-{
- Q_D(QTabBar);
- if (index < 0 || index >= d->tabList.count())
- return;
- if (widget) {
- widget->setParent(this);
- // make sure our left and right widgets stay on top
- widget->lower();
- widget->show();
- }
- if (position == LeftSide) {
- if (d->tabList[index].leftWidget)
- d->tabList[index].leftWidget->hide();
- d->tabList[index].leftWidget = widget;
- } else {
- if (d->tabList[index].rightWidget)
- d->tabList[index].rightWidget->hide();
- d->tabList[index].rightWidget = widget;
- }
- d->layoutTabs();
- d->refresh();
- update();
-}
-
-/*!
- Returns the widget set a tab \a index and \a position or 0 if
- one is not set.
- */
-QWidget *QTabBar::tabButton(int index, ButtonPosition position) const
-{
- Q_D(const QTabBar);
- if (index < 0 || index >= d->tabList.count())
- return 0;
- if (position == LeftSide)
- return d->tabList.at(index).leftWidget;
- else
- return d->tabList.at(index).rightWidget;
-}
-
-CloseButton::CloseButton(QWidget *parent)
- : QAbstractButton(parent)
-{
- setFocusPolicy(Qt::NoFocus);
-#ifndef QT_NO_CURSOR
- setCursor(Qt::ArrowCursor);
-#endif
-#ifndef QT_NO_TOOLTIP
- setToolTip(tr("Close Tab"));
-#endif
- resize(sizeHint());
-}
-
-QSize CloseButton::sizeHint() const
-{
- ensurePolished();
- int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this);
- int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this);
- return QSize(width, height);
-}
-
-void CloseButton::enterEvent(QEvent *event)
-{
- if (isEnabled())
- update();
- QAbstractButton::enterEvent(event);
-}
-
-void CloseButton::leaveEvent(QEvent *event)
-{
- if (isEnabled())
- update();
- QAbstractButton::leaveEvent(event);
-}
-
-void CloseButton::paintEvent(QPaintEvent *)
-{
- QPainter p(this);
- QStyleOption opt;
- opt.init(this);
- opt.state |= QStyle::State_AutoRaise;
- if (isEnabled() && underMouse() && !isChecked() && !isDown())
- opt.state |= QStyle::State_Raised;
- if (isChecked())
- opt.state |= QStyle::State_On;
- if (isDown())
- opt.state |= QStyle::State_Sunken;
-
- if (const QTabBar *tb = qobject_cast<const QTabBar *>(parent())) {
- int index = tb->currentIndex();
- QTabBar::ButtonPosition position = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tb);
- if (tb->tabButton(index, position) == this)
- opt.state |= QStyle::State_Selected;
- }
-
- style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtabbar.cpp"
-
-#endif // QT_NO_TABBAR
diff --git a/src/gui/widgets/qtabbar.h b/src/gui/widgets/qtabbar.h
deleted file mode 100644
index b558445fc9..0000000000
--- a/src/gui/widgets/qtabbar.h
+++ /dev/null
@@ -1,226 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABBAR_H
-#define QTABBAR_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TABBAR
-
-class QIcon;
-class QTabBarPrivate;
-class QStyleOptionTab;
-
-class Q_GUI_EXPORT QTabBar: public QWidget
-{
- Q_OBJECT
-
- Q_ENUMS(Shape)
- Q_PROPERTY(Shape shape READ shape WRITE setShape)
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)
- Q_PROPERTY(int count READ count)
- Q_PROPERTY(bool drawBase READ drawBase WRITE setDrawBase)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
- Q_PROPERTY(Qt::TextElideMode elideMode READ elideMode WRITE setElideMode)
- Q_PROPERTY(bool usesScrollButtons READ usesScrollButtons WRITE setUsesScrollButtons)
- Q_PROPERTY(bool tabsClosable READ tabsClosable WRITE setTabsClosable)
- Q_PROPERTY(SelectionBehavior selectionBehaviorOnRemove READ selectionBehaviorOnRemove WRITE setSelectionBehaviorOnRemove)
- Q_PROPERTY(bool expanding READ expanding WRITE setExpanding)
- Q_PROPERTY(bool movable READ isMovable WRITE setMovable)
- Q_PROPERTY(bool documentMode READ documentMode WRITE setDocumentMode)
-
-public:
- explicit QTabBar(QWidget* parent=0);
- ~QTabBar();
-
- enum Shape { RoundedNorth, RoundedSouth, RoundedWest, RoundedEast,
- TriangularNorth, TriangularSouth, TriangularWest, TriangularEast
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- , RoundedAbove = RoundedNorth, RoundedBelow = RoundedSouth,
- TriangularAbove = TriangularNorth, TriangularBelow = TriangularSouth
-#endif
- };
-
- enum ButtonPosition {
- LeftSide,
- RightSide
- };
-
- enum SelectionBehavior {
- SelectLeftTab,
- SelectRightTab,
- SelectPreviousTab
- };
-
- Shape shape() const;
- void setShape(Shape shape);
-
- int addTab(const QString &text);
- int addTab(const QIcon &icon, const QString &text);
-
- int insertTab(int index, const QString &text);
- int insertTab(int index, const QIcon&icon, const QString &text);
-
- void removeTab(int index);
- void moveTab(int from, int to);
-
- bool isTabEnabled(int index) const;
- void setTabEnabled(int index, bool);
-
- QString tabText(int index) const;
- void setTabText(int index, const QString &text);
-
- QColor tabTextColor(int index) const;
- void setTabTextColor(int index, const QColor &color);
-
- QIcon tabIcon(int index) const;
- void setTabIcon(int index, const QIcon &icon);
-
- Qt::TextElideMode elideMode() const;
- void setElideMode(Qt::TextElideMode);
-
-#ifndef QT_NO_TOOLTIP
- void setTabToolTip(int index, const QString &tip);
- QString tabToolTip(int index) const;
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- void setTabWhatsThis(int index, const QString &text);
- QString tabWhatsThis(int index) const;
-#endif
-
- void setTabData(int index, const QVariant &data);
- QVariant tabData(int index) const;
-
- QRect tabRect(int index) const;
- int tabAt(const QPoint &pos) const;
-
- int currentIndex() const;
- int count() const;
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- void setDrawBase(bool drawTheBase);
- bool drawBase() const;
-
- QSize iconSize() const;
- void setIconSize(const QSize &size);
-
- bool usesScrollButtons() const;
- void setUsesScrollButtons(bool useButtons);
-
- bool tabsClosable() const;
- void setTabsClosable(bool closable);
-
- void setTabButton(int index, ButtonPosition position, QWidget *widget);
- QWidget *tabButton(int index, ButtonPosition position) const;
-
- SelectionBehavior selectionBehaviorOnRemove() const;
- void setSelectionBehaviorOnRemove(SelectionBehavior behavior);
-
- bool expanding() const;
- void setExpanding(bool enabled);
-
- bool isMovable() const;
- void setMovable(bool movable);
-
- bool documentMode() const;
- void setDocumentMode(bool set);
-
-public Q_SLOTS:
- void setCurrentIndex(int index);
-
-Q_SIGNALS:
- void currentChanged(int index);
- void tabCloseRequested(int index);
- void tabMoved(int from, int to);
-
-protected:
- virtual QSize tabSizeHint(int index) const;
- virtual void tabInserted(int index);
- virtual void tabRemoved(int index);
- virtual void tabLayoutChange();
-
- bool event(QEvent *);
- void resizeEvent(QResizeEvent *);
- void showEvent(QShowEvent *);
- void hideEvent(QHideEvent *);
- void paintEvent(QPaintEvent *);
- void mousePressEvent (QMouseEvent *);
- void mouseMoveEvent (QMouseEvent *);
- void mouseReleaseEvent (QMouseEvent *);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *event);
-#endif
- void keyPressEvent(QKeyEvent *);
- void changeEvent(QEvent *);
- void initStyleOption(QStyleOptionTab *option, int tabIndex) const;
-
-#ifdef QT3_SUPPORT
-public Q_SLOTS:
- QT_MOC_COMPAT void setCurrentTab(int index) { setCurrentIndex(index); }
-Q_SIGNALS:
- QT_MOC_COMPAT void selected(int);
-#endif
-
- friend class QAccessibleTabBar;
-private:
- Q_DISABLE_COPY(QTabBar)
- Q_DECLARE_PRIVATE(QTabBar)
- Q_PRIVATE_SLOT(d_func(), void _q_scrollTabs())
- Q_PRIVATE_SLOT(d_func(), void _q_closeTab())
-};
-
-#endif // QT_NO_TABBAR
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTABBAR_H
diff --git a/src/gui/widgets/qtabbar_p.h b/src/gui/widgets/qtabbar_p.h
deleted file mode 100644
index 1c94d73184..0000000000
--- a/src/gui/widgets/qtabbar_p.h
+++ /dev/null
@@ -1,263 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABBAR_P_H
-#define QTABBAR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qtabbar.h"
-#include "private/qwidget_p.h"
-
-#include <qicon.h>
-#include <qtoolbutton.h>
-#include <qdebug.h>
-#include <qvariantanimation.h>
-
-#ifndef QT_NO_TABBAR
-
-#define ANIMATION_DURATION 250
-
-#include <qstyleoption.h>
-
-QT_BEGIN_NAMESPACE
-
-class QTabBarPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QTabBar)
-public:
- QTabBarPrivate()
- :currentIndex(-1), pressedIndex(-1), shape(QTabBar::RoundedNorth), layoutDirty(false),
- drawBase(true), scrollOffset(0), elideModeSetByUser(false), useScrollButtonsSetByUser(false), expanding(true), closeButtonOnTabs(false),
- selectionBehaviorOnRemove(QTabBar::SelectRightTab), paintWithOffsets(true), movable(false),
- dragInProgress(false), documentMode(false), movingTab(0)
-#ifdef Q_WS_MAC
- , previousPressedIndex(-1)
-#endif
- {}
-
- int currentIndex;
- int pressedIndex;
- QTabBar::Shape shape;
- bool layoutDirty;
- bool drawBase;
- int scrollOffset;
-
- struct Tab {
- inline Tab(const QIcon &ico, const QString &txt)
- : enabled(true) , shortcutId(0), text(txt), icon(ico),
- leftWidget(0), rightWidget(0), lastTab(-1), dragOffset(0)
-#ifndef QT_NO_ANIMATION
- , animation(0)
-#endif //QT_NO_ANIMATION
- {}
- bool operator==(const Tab &other) const { return &other == this; }
- bool enabled;
- int shortcutId;
- QString text;
-#ifndef QT_NO_TOOLTIP
- QString toolTip;
-#endif
-#ifndef QT_NO_WHATSTHIS
- QString whatsThis;
-#endif
- QIcon icon;
- QRect rect;
- QRect minRect;
- QRect maxRect;
-
- QColor textColor;
- QVariant data;
- QWidget *leftWidget;
- QWidget *rightWidget;
- int lastTab;
- int dragOffset;
-
-#ifndef QT_NO_ANIMATION
- ~Tab() { delete animation; }
- struct TabBarAnimation : public QVariantAnimation {
- TabBarAnimation(Tab *t, QTabBarPrivate *_priv) : tab(t), priv(_priv)
- { setEasingCurve(QEasingCurve::InOutQuad); }
-
- void updateCurrentValue(const QVariant &current)
- { priv->moveTab(priv->tabList.indexOf(*tab), current.toInt()); }
-
- void updateState(State, State newState)
- { if (newState == Stopped) priv->moveTabFinished(priv->tabList.indexOf(*tab)); }
- private:
- //these are needed for the callbacks
- Tab *tab;
- QTabBarPrivate *priv;
- } *animation;
-
- void startAnimation(QTabBarPrivate *priv, int duration) {
- if (!animation)
- animation = new TabBarAnimation(this, priv);
- animation->setStartValue(dragOffset);
- animation->setEndValue(0);
- animation->setDuration(duration);
- animation->start();
- }
-#else
- void startAnimation(QTabBarPrivate *priv, int duration)
- { Q_UNUSED(duration); priv->moveTabFinished(priv->tabList.indexOf(*this)); }
-#endif //QT_NO_ANIMATION
- };
- QList<Tab> tabList;
-
- int calculateNewPosition(int from, int to, int index) const;
- void slide(int from, int to);
- void init();
- int extraWidth() const;
-
- Tab *at(int index);
- const Tab *at(int index) const;
-
- int indexAtPos(const QPoint &p) const;
-
- inline bool validIndex(int index) const { return index >= 0 && index < tabList.count(); }
- void setCurrentNextEnabledIndex(int offset);
-
- QSize minimumTabSizeHint(int index);
-
- QToolButton* rightB; // right or bottom
- QToolButton* leftB; // left or top
-
- void _q_scrollTabs();
- void _q_closeTab();
- void moveTab(int index, int offset);
- void moveTabFinished(int index);
- QRect hoverRect;
-
- void refresh();
- void layoutTabs();
- void layoutWidgets(int start = 0);
- void layoutTab(int index);
- void updateMacBorderMetrics();
- void setupMovableTab();
-
- void makeVisible(int index);
- QSize iconSize;
- Qt::TextElideMode elideMode;
- bool elideModeSetByUser;
- bool useScrollButtons;
- bool useScrollButtonsSetByUser;
-
- bool expanding;
- bool closeButtonOnTabs;
- QTabBar::SelectionBehavior selectionBehaviorOnRemove;
-
- QPoint dragStartPosition;
- bool paintWithOffsets;
- bool movable;
- bool dragInProgress;
- bool documentMode;
-
- QWidget *movingTab;
-#ifdef Q_WS_MAC
- int previousPressedIndex;
-#endif
- // shared by tabwidget and qtabbar
- static void initStyleBaseOption(QStyleOptionTabBarBaseV2 *optTabBase, QTabBar *tabbar, QSize size)
- {
- QStyleOptionTab tabOverlap;
- tabOverlap.shape = tabbar->shape();
- int overlap = tabbar->style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, &tabOverlap, tabbar);
- QWidget *theParent = tabbar->parentWidget();
- optTabBase->init(tabbar);
- optTabBase->shape = tabbar->shape();
- optTabBase->documentMode = tabbar->documentMode();
- if (theParent && overlap > 0) {
- QRect rect;
- switch (tabOverlap.shape) {
- case QTabBar::RoundedNorth:
- case QTabBar::TriangularNorth:
- rect.setRect(0, size.height()-overlap, size.width(), overlap);
- break;
- case QTabBar::RoundedSouth:
- case QTabBar::TriangularSouth:
- rect.setRect(0, 0, size.width(), overlap);
- break;
- case QTabBar::RoundedEast:
- case QTabBar::TriangularEast:
- rect.setRect(0, 0, overlap, size.height());
- break;
- case QTabBar::RoundedWest:
- case QTabBar::TriangularWest:
- rect.setRect(size.width() - overlap, 0, overlap, size.height());
- break;
- }
- optTabBase->rect = rect;
- }
- }
-
-};
-
-class CloseButton : public QAbstractButton
-{
- Q_OBJECT
-
-public:
- CloseButton(QWidget *parent = 0);
-
- QSize sizeHint() const;
- inline QSize minimumSizeHint() const
- { return sizeHint(); }
- void enterEvent(QEvent *event);
- void leaveEvent(QEvent *event);
- void paintEvent(QPaintEvent *event);
-};
-
-
-QT_END_NAMESPACE
-
-#endif
-
-#endif
diff --git a/src/gui/widgets/qtabwidget.cpp b/src/gui/widgets/qtabwidget.cpp
deleted file mode 100644
index c296b77370..0000000000
--- a/src/gui/widgets/qtabwidget.cpp
+++ /dev/null
@@ -1,1516 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtabwidget.h"
-
-#ifndef QT_NO_TABWIDGET
-#include "private/qwidget_p.h"
-#include "private/qtabbar_p.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qlayout.h"
-#include "qstackedwidget.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qstylepainter.h"
-#include "qtabbar.h"
-#include "qtoolbutton.h"
-
-QT_BEGIN_NAMESPACE
-
-/*!
- \class QTabWidget
- \brief The QTabWidget class provides a stack of tabbed widgets.
-
- \ingroup organizers
- \ingroup basicwidgets
-
-
- A tab widget provides a tab bar (see QTabBar) and a "page area"
- that is used to display pages related to each tab. By default, the
- tab bar is shown above the page area, but different configurations
- are available (see \l{TabPosition}). Each tab is associated with a
- different widget (called a page). Only the current page is shown in
- the page area; all the other pages are hidden. The user can show a
- different page by clicking on its tab or by pressing its
- Alt+\e{letter} shortcut if it has one.
-
- The normal way to use QTabWidget is to do the following:
- \list 1
- \i Create a QTabWidget.
- \i Create a QWidget for each of the pages in the tab dialog, but
- do not specify parent widgets for them.
- \i Insert child widgets into the page widget, using layouts to
- position them as normal.
- \i Call addTab() or insertTab() to put the page widgets into the
- tab widget, giving each tab a suitable label with an optional
- keyboard shortcut.
- \endlist
-
- The position of the tabs is defined by \l tabPosition, their shape
- by \l tabShape.
-
- The signal currentChanged() is emitted when the user selects a
- page.
-
- The current page index is available as currentIndex(), the current
- page widget with currentWidget(). You can retrieve a pointer to a
- page widget with a given index using widget(), and can find the
- index position of a widget with indexOf(). Use setCurrentWidget()
- or setCurrentIndex() to show a particular page.
-
- You can change a tab's text and icon using setTabText() or
- setTabIcon(). A tab and its associated page can be removed with
- removeTab().
-
- Each tab is either enabled or disabled at any given time (see
- setTabEnabled()). If a tab is enabled, the tab text is drawn
- normally and the user can select that tab. If it is disabled, the
- tab is drawn in a different way and the user cannot select that
- tab. Note that even if a tab is disabled, the page can still be
- visible, for example if all of the tabs happen to be disabled.
-
- Tab widgets can be a very good way to split up a complex dialog.
- An alternative is to use a QStackedWidget for which you provide some
- means of navigating between pages, for example, a QToolBar or a
- QListWidget.
-
- Most of the functionality in QTabWidget is provided by a QTabBar
- (at the top, providing the tabs) and a QStackedWidget (most of the
- area, organizing the individual pages).
-
- \table 100%
- \row \o \inlineimage windowsxp-tabwidget.png Screenshot of a Windows XP style tab widget
- \o \inlineimage macintosh-tabwidget.png Screenshot of a Macintosh style tab widget
- \o \inlineimage plastique-tabwidget.png Screenshot of a Plastique style tab widget
- \row \o A Windows XP style tab widget.
- \o A Macintosh style tab widget.
- \o A Plastique style tab widget.
- \endtable
-
- \sa QTabBar, QStackedWidget, QToolBox, {Tab Dialog Example}
-*/
-
-/*!
- \enum QTabWidget::TabPosition
-
- This enum type defines where QTabWidget draws the tab row:
-
- \value North The tabs are drawn above the pages.
- \value South The tabs are drawn below the pages.
- \value West The tabs are drawn to the left of the pages.
- \value East The tabs are drawn to the right of the pages.
- \omitvalue Bottom
- \omitvalue Top
-*/
-
-/*!
- \enum QTabWidget::TabShape
-
- This enum type defines the shape of the tabs:
- \value Rounded The tabs are drawn with a rounded look. This is the default
- shape.
- \value Triangular The tabs are drawn with a triangular look.
-*/
-
-/*!
- \fn void QTabWidget::selected(const QString &tabLabel)
-
- This signal is emitted whenever a tab is selected (raised),
- including during the first show().
-
- You can normally use currentChanged() instead.
-*/
-
-/*!
- \fn void QTabWidget::currentChanged(int index)
-
- This signal is emitted whenever the current page index changes.
- The parameter is the new current page \a index position, or -1
- if there isn't a new one (for example, if there are no widgets
- in the QTabWidget)
-
- \sa currentWidget() currentIndex
-*/
-
-/*!
- \fn void QTabWidget::tabCloseRequested(int index)
- \since 4.5
-
- This signal is emitted when the close button on a tab is clicked.
- The \a index is the index that should be removed.
-
- \sa setTabsClosable()
-*/
-
-class QTabWidgetPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QTabWidget)
-
-public:
- QTabWidgetPrivate();
- ~QTabWidgetPrivate();
- void updateTabBarPosition();
- void _q_showTab(int);
- void _q_removeTab(int);
- void _q_tabMoved(int from, int to);
- void init();
- bool hasHeightForWidth() const;
-
- QTabBar *tabs;
- QStackedWidget *stack;
- QRect panelRect;
- bool dirty;
- QTabWidget::TabPosition pos;
- QTabWidget::TabShape shape;
- int alignment;
- QWidget *leftCornerWidget;
- QWidget *rightCornerWidget;
-};
-
-QTabWidgetPrivate::QTabWidgetPrivate()
- : tabs(0), stack(0), dirty(true),
- pos(QTabWidget::North), shape(QTabWidget::Rounded),
- leftCornerWidget(0), rightCornerWidget(0)
-{}
-
-QTabWidgetPrivate::~QTabWidgetPrivate()
-{}
-
-void QTabWidgetPrivate::init()
-{
- Q_Q(QTabWidget);
-
- stack = new QStackedWidget(q);
- stack->setObjectName(QLatin1String("qt_tabwidget_stackedwidget"));
- stack->setLineWidth(0);
- // hack so that QMacStyle::layoutSpacing() can detect tab widget pages
- stack->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::TabWidget));
-
- QObject::connect(stack, SIGNAL(widgetRemoved(int)), q, SLOT(_q_removeTab(int)));
- QTabBar *tabBar = new QTabBar(q);
- tabBar->setObjectName(QLatin1String("qt_tabwidget_tabbar"));
- tabBar->setDrawBase(false);
- q->setTabBar(tabBar);
-
- q->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding,
- QSizePolicy::TabWidget));
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
- q->setFocusPolicy(Qt::NoFocus);
- else
-#endif
- q->setFocusPolicy(Qt::TabFocus);
- q->setFocusProxy(tabs);
- q->setTabPosition(static_cast<QTabWidget::TabPosition> (q->style()->styleHint(
- QStyle::SH_TabWidget_DefaultTabPosition, 0, q )));
-
-}
-
-bool QTabWidgetPrivate::hasHeightForWidth() const
-{
- bool has = size_policy.hasHeightForWidth();
- if (!has && stack)
- has = qt_widget_private(stack)->hasHeightForWidth();
- return has;
-}
-
-
-/*!
- Initialize \a option with the values from this QTabWidget. This method is useful
- for subclasses when they need a QStyleOptionTabWidgetFrame, but don't want to fill
- in all the information themselves.
-
- \sa QStyleOption::initFrom() QTabBar::initStyleOption()
-*/
-void QTabWidget::initStyleOption(QStyleOptionTabWidgetFrame *option) const
-{
- if (!option)
- return;
-
- Q_D(const QTabWidget);
- option->initFrom(this);
-
- if (documentMode())
- option->lineWidth = 0;
- else
- option->lineWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this);
-
- int exth = style()->pixelMetric(QStyle::PM_TabBarBaseHeight, 0, this);
- QSize t(0, d->stack->frameWidth());
- if (d->tabs->isVisibleTo(const_cast<QTabWidget *>(this))) {
- t = d->tabs->sizeHint();
- if (documentMode()) {
- if (tabPosition() == East || tabPosition() == West) {
- t.setHeight(height());
- } else {
- t.setWidth(width());
- }
- }
- }
-
- if (d->rightCornerWidget) {
- const QSize rightCornerSizeHint = d->rightCornerWidget->sizeHint();
- const QSize bounds(rightCornerSizeHint.width(), t.height() - exth);
- option->rightCornerWidgetSize = rightCornerSizeHint.boundedTo(bounds);
- } else {
- option->rightCornerWidgetSize = QSize(0, 0);
- }
-
- if (d->leftCornerWidget) {
- const QSize leftCornerSizeHint = d->leftCornerWidget->sizeHint();
- const QSize bounds(leftCornerSizeHint.width(), t.height() - exth);
- option->leftCornerWidgetSize = leftCornerSizeHint.boundedTo(bounds);
- } else {
- option->leftCornerWidgetSize = QSize(0, 0);
- }
-
- switch (d->pos) {
- case QTabWidget::North:
- option->shape = d->shape == QTabWidget::Rounded ? QTabBar::RoundedNorth
- : QTabBar::TriangularNorth;
- break;
- case QTabWidget::South:
- option->shape = d->shape == QTabWidget::Rounded ? QTabBar::RoundedSouth
- : QTabBar::TriangularSouth;
- break;
- case QTabWidget::West:
- option->shape = d->shape == QTabWidget::Rounded ? QTabBar::RoundedWest
- : QTabBar::TriangularWest;
- break;
- case QTabWidget::East:
- option->shape = d->shape == QTabWidget::Rounded ? QTabBar::RoundedEast
- : QTabBar::TriangularEast;
- break;
- }
-
- option->tabBarSize = t;
-
- if (QStyleOptionTabWidgetFrameV2 *tabframe = qstyleoption_cast<QStyleOptionTabWidgetFrameV2*>(option)) {
- QRect tbRect = tabBar()->geometry();
- QRect selectedTabRect = tabBar()->tabRect(tabBar()->currentIndex());
- tabframe->tabBarRect = tbRect;
- selectedTabRect.moveTopLeft(selectedTabRect.topLeft() + tbRect.topLeft());
- tabframe->selectedTabRect = selectedTabRect;
- }
-}
-
-/*!
- Constructs a tabbed widget with parent \a parent.
-*/
-QTabWidget::QTabWidget(QWidget *parent)
- : QWidget(*new QTabWidgetPrivate, parent, 0)
-{
- Q_D(QTabWidget);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QTabWidget::QTabWidget(QWidget *parent, const char *name, Qt::WindowFlags f)
- : QWidget(*new QTabWidgetPrivate, parent, f)
-{
- Q_D(QTabWidget);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-#endif
-
-/*!
- Destroys the tabbed widget.
-*/
-QTabWidget::~QTabWidget()
-{
-}
-
-/*!
- \fn int QTabWidget::addTab(QWidget *page, const QString &label)
-
- Adds a tab with the given \a page and \a label to the tab widget,
- and returns the index of the tab in the tab bar.
-
- If the tab's \a label contains an ampersand, the letter following
- the ampersand is used as a shortcut for the tab, e.g. if the
- label is "Bro\&wse" then Alt+W becomes a shortcut which will
- move the focus to this tab.
-
- \note If you call addTab() after show(), the layout system will try
- to adjust to the changes in its widgets hierarchy and may cause
- flicker. To prevent this, you can set the QWidget::updatesEnabled
- property to false prior to changes; remember to set the property
- to true when the changes are done, making the widget receive paint
- events again.
-
- \sa insertTab()
-*/
-int QTabWidget::addTab(QWidget *child, const QString &label)
-{
- return insertTab(-1, child, label);
-}
-
-
-/*!
- \fn int QTabWidget::addTab(QWidget *page, const QIcon &icon, const QString &label)
- \overload
-
- Adds a tab with the given \a page, \a icon, and \a label to the tab
- widget, and returns the index of the tab in the tab bar.
-
- This function is the same as addTab(), but with an additional \a
- icon.
-*/
-int QTabWidget::addTab(QWidget *child, const QIcon& icon, const QString &label)
-{
- return insertTab(-1, child, icon, label);
-}
-
-
-/*!
- \fn int QTabWidget::insertTab(int index, QWidget *page, const QString &label)
-
- Inserts a tab with the given \a label and \a page into the tab
- widget at the specified \a index, and returns the index of the
- inserted tab in the tab bar.
-
- The label is displayed in the tab and may vary in appearance depending
- on the configuration of the tab widget.
-
- If the tab's \a label contains an ampersand, the letter following
- the ampersand is used as a shortcut for the tab, e.g. if the
- label is "Bro\&wse" then Alt+W becomes a shortcut which will
- move the focus to this tab.
-
- If \a index is out of range, the tab is simply appended.
- Otherwise it is inserted at the specified position.
-
- If the QTabWidget was empty before this function is called, the
- new page becomes the current page. Inserting a new tab at an index
- less than or equal to the current index will increment the current
- index, but keep the current page.
-
- \note If you call insertTab() after show(), the layout system will try
- to adjust to the changes in its widgets hierarchy and may cause
- flicker. To prevent this, you can set the QWidget::updatesEnabled
- property to false prior to changes; remember to set the property
- to true when the changes are done, making the widget receive paint
- events again.
-
- \sa addTab()
-*/
-int QTabWidget::insertTab(int index, QWidget *w, const QString &label)
-{
- return insertTab(index, w, QIcon(), label);
-}
-
-
-/*!
- \fn int QTabWidget::insertTab(int index, QWidget *page, const QIcon& icon, const QString &label)
- \overload
-
- Inserts a tab with the given \a label, \a page, and \a icon into
- the tab widget at the specified \a index, and returns the index of the
- inserted tab in the tab bar.
-
- This function is the same as insertTab(), but with an additional
- \a icon.
-*/
-int QTabWidget::insertTab(int index, QWidget *w, const QIcon& icon, const QString &label)
-{
- Q_D(QTabWidget);
- if(!w)
- return -1;
- index = d->stack->insertWidget(index, w);
- d->tabs->insertTab(index, icon, label);
- setUpLayout();
- tabInserted(index);
-
- return index;
-}
-
-
-/*!
- Defines a new \a label for the page at position \a index's tab.
-
- If the provided text contains an ampersand character ('&'), a
- shortcut is automatically created for it. The character that
- follows the '&' will be used as the shortcut key. Any previous
- shortcut will be overwritten, or cleared if no shortcut is defined
- by the text. See the \l {QShortcut#mnemonic}{QShortcut}
- documentation for details (to display an actual ampersand, use
- '&&').
-
-*/
-void QTabWidget::setTabText(int index, const QString &label)
-{
- Q_D(QTabWidget);
- d->tabs->setTabText(index, label);
- setUpLayout();
-}
-
-/*!
- Returns the label text for the tab on the page at position \a index.
-*/
-
-QString QTabWidget::tabText(int index) const
-{
- Q_D(const QTabWidget);
- return d->tabs->tabText(index);
-}
-
-/*!
- \overload
-
- Sets the \a icon for the tab at position \a index.
-*/
-void QTabWidget::setTabIcon(int index, const QIcon &icon)
-{
- Q_D(QTabWidget);
- d->tabs->setTabIcon(index, icon);
- setUpLayout();
-}
-
-/*!
- Returns the icon for the tab on the page at position \a index.
-*/
-
-QIcon QTabWidget::tabIcon(int index) const
-{
- Q_D(const QTabWidget);
- return d->tabs->tabIcon(index);
-}
-
-/*!
- Returns true if the page at position \a index is enabled; otherwise returns false.
-
- \sa setTabEnabled(), QWidget::isEnabled()
-*/
-
-bool QTabWidget::isTabEnabled(int index) const
-{
- Q_D(const QTabWidget);
- return d->tabs->isTabEnabled(index);
-}
-
-/*!
- If \a enable is true, the page at position \a index is enabled; otherwise the page at position \a index is
- disabled. The page's tab is redrawn appropriately.
-
- QTabWidget uses QWidget::setEnabled() internally, rather than
- keeping a separate flag.
-
- Note that even a disabled tab/page may be visible. If the page is
- visible already, QTabWidget will not hide it; if all the pages are
- disabled, QTabWidget will show one of them.
-
- \sa isTabEnabled(), QWidget::setEnabled()
-*/
-
-void QTabWidget::setTabEnabled(int index, bool enable)
-{
- Q_D(QTabWidget);
- d->tabs->setTabEnabled(index, enable);
- if (QWidget *widget = d->stack->widget(index))
- widget->setEnabled(enable);
-}
-
-/*!
- \fn void QTabWidget::setCornerWidget(QWidget *widget, Qt::Corner corner)
-
- Sets the given \a widget to be shown in the specified \a corner of the
- tab widget. The geometry of the widget is determined based on the widget's
- sizeHint() and the style().
-
- Only the horizontal element of the \a corner will be used.
-
- Passing 0 shows no widget in the corner.
-
- Any previously set corner widget is hidden.
-
- All widgets set here will be deleted by the tab widget when it is
- destroyed unless you separately reparent the widget after setting
- some other corner widget (or 0).
-
- Note: Corner widgets are designed for \l North and \l South tab positions;
- other orientations are known to not work properly.
-
- \sa cornerWidget(), setTabPosition()
-*/
-void QTabWidget::setCornerWidget(QWidget * widget, Qt::Corner corner)
-{
- Q_D(QTabWidget);
- if (widget && widget->parentWidget() != this)
- widget->setParent(this);
-
- if (corner & Qt::TopRightCorner) {
- if (d->rightCornerWidget)
- d->rightCornerWidget->hide();
- d->rightCornerWidget = widget;
- } else {
- if (d->leftCornerWidget)
- d->leftCornerWidget->hide();
- d->leftCornerWidget = widget;
- }
- setUpLayout();
-}
-
-/*!
- Returns the widget shown in the \a corner of the tab widget or 0.
-*/
-QWidget * QTabWidget::cornerWidget(Qt::Corner corner) const
-{
- Q_D(const QTabWidget);
- if (corner & Qt::TopRightCorner)
- return d->rightCornerWidget;
- return d->leftCornerWidget;
-}
-
-/*!
- Removes the tab at position \a index from this stack of widgets.
- The page widget itself is not deleted.
-
- \sa addTab(), insertTab()
-*/
-void QTabWidget::removeTab(int index)
-{
- Q_D(QTabWidget);
- if (QWidget *w = d->stack->widget(index))
- d->stack->removeWidget(w);
-}
-
-/*!
- Returns a pointer to the page currently being displayed by the tab
- dialog. The tab dialog does its best to make sure that this value
- is never 0 (but if you try hard enough, it can be).
-
- \sa currentIndex(), setCurrentWidget()
-*/
-
-QWidget * QTabWidget::currentWidget() const
-{
- Q_D(const QTabWidget);
- return d->stack->currentWidget();
-}
-
-/*!
- Makes \a widget the current widget. The \a widget used must be a page in
- this tab widget.
-
- \sa addTab(), setCurrentIndex(), currentWidget()
- */
-void QTabWidget::setCurrentWidget(QWidget *widget)
-{
- Q_D(const QTabWidget);
- d->tabs->setCurrentIndex(indexOf(widget));
-}
-
-
-/*!
- \property QTabWidget::currentIndex
- \brief the index position of the current tab page
-
- The current index is -1 if there is no current widget.
-
- By default, this property contains a value of -1 because there are initially
- no tabs in the widget.
-*/
-
-int QTabWidget::currentIndex() const
-{
- Q_D(const QTabWidget);
- return d->tabs->currentIndex();
-}
-
-void QTabWidget::setCurrentIndex(int index)
-{
- Q_D(QTabWidget);
- d->tabs->setCurrentIndex(index);
-}
-
-
-/*!
- Returns the index position of the page occupied by the widget \a
- w, or -1 if the widget cannot be found.
-*/
-int QTabWidget::indexOf(QWidget* w) const
-{
- Q_D(const QTabWidget);
- return d->stack->indexOf(w);
-}
-
-
-/*!
- \reimp
-*/
-void QTabWidget::resizeEvent(QResizeEvent *e)
-{
- QWidget::resizeEvent(e);
- setUpLayout();
-}
-
-/*!
- Replaces the dialog's QTabBar heading with the tab bar \a tb. Note
- that this must be called \e before any tabs have been added, or
- the behavior is undefined.
-
- \sa tabBar()
-*/
-void QTabWidget::setTabBar(QTabBar* tb)
-{
- Q_D(QTabWidget);
- Q_ASSERT(tb);
-
- if (tb->parentWidget() != this) {
- tb->setParent(this);
- tb->show();
- }
- delete d->tabs;
- d->tabs = tb;
- setFocusProxy(d->tabs);
- connect(d->tabs, SIGNAL(currentChanged(int)),
- this, SLOT(_q_showTab(int)));
- connect(d->tabs, SIGNAL(tabMoved(int,int)),
- this, SLOT(_q_tabMoved(int,int)));
- if (d->tabs->tabsClosable())
- connect(d->tabs, SIGNAL(tabCloseRequested(int)),
- this, SIGNAL(tabCloseRequested(int)));
- tb->setExpanding(!documentMode());
- setUpLayout();
-}
-
-
-/*!
- Returns the current QTabBar.
-
- \sa setTabBar()
-*/
-QTabBar* QTabWidget::tabBar() const
-{
- Q_D(const QTabWidget);
- return d->tabs;
-}
-
-/*!
- Ensures that the selected tab's page is visible and appropriately
- sized.
-*/
-
-void QTabWidgetPrivate::_q_showTab(int index)
-{
- Q_Q(QTabWidget);
- if (index < stack->count() && index >= 0)
- stack->setCurrentIndex(index);
- emit q->currentChanged(index);
-#ifdef QT3_SUPPORT
- emit q->selected(q->tabText(index));
- emit q->currentChanged(stack->widget(index));
-#endif
-}
-
-void QTabWidgetPrivate::_q_removeTab(int index)
-{
- Q_Q(QTabWidget);
- tabs->removeTab(index);
- q->setUpLayout();
- q->tabRemoved(index);
-}
-
-void QTabWidgetPrivate::_q_tabMoved(int from, int to)
-{
- stack->blockSignals(true);
- QWidget *w = stack->widget(from);
- stack->removeWidget(w);
- stack->insertWidget(to, w);
- stack->blockSignals(false);
-}
-
-/*
- Set up the layout.
- Get subrect from the current style, and set the geometry for the
- stack widget, tab bar and corner widgets.
-*/
-void QTabWidget::setUpLayout(bool onlyCheck)
-{
- Q_D(QTabWidget);
- if (onlyCheck && !d->dirty)
- return; // nothing to do
-
- QStyleOptionTabWidgetFrameV2 option;
- initStyleOption(&option);
-
- // this must be done immediately, because QWidgetItem relies on it (even if !isVisible())
- d->setLayoutItemMargins(QStyle::SE_TabWidgetLayoutItem, &option);
-
- if (!isVisible()) {
- d->dirty = true;
- return; // we'll do it later
- }
-
- QRect tabRect = style()->subElementRect(QStyle::SE_TabWidgetTabBar, &option, this);
- d->panelRect = style()->subElementRect(QStyle::SE_TabWidgetTabPane, &option, this);
- QRect contentsRect = style()->subElementRect(QStyle::SE_TabWidgetTabContents, &option, this);
- QRect leftCornerRect = style()->subElementRect(QStyle::SE_TabWidgetLeftCorner, &option, this);
- QRect rightCornerRect = style()->subElementRect(QStyle::SE_TabWidgetRightCorner, &option, this);
-
- d->tabs->setGeometry(tabRect);
- d->stack->setGeometry(contentsRect);
- if (d->leftCornerWidget)
- d->leftCornerWidget->setGeometry(leftCornerRect);
- if (d->rightCornerWidget)
- d->rightCornerWidget->setGeometry(rightCornerRect);
-
- if (!onlyCheck)
- update();
- updateGeometry();
-}
-
-/*!
- \internal
-*/
-static inline QSize basicSize(
- bool horizontal, const QSize &lc, const QSize &rc, const QSize &s, const QSize &t)
-{
- return horizontal
- ? QSize(qMax(s.width(), t.width() + rc.width() + lc.width()),
- s.height() + (qMax(rc.height(), qMax(lc.height(), t.height()))))
- : QSize(s.width() + (qMax(rc.width(), qMax(lc.width(), t.width()))),
- qMax(s.height(), t.height() + rc.height() + lc.height()));
-}
-
-/*!
- \reimp
-*/
-QSize QTabWidget::sizeHint() const
-{
- Q_D(const QTabWidget);
- QSize lc(0, 0), rc(0, 0);
- QStyleOptionTabWidgetFrameV2 opt;
- initStyleOption(&opt);
- opt.state = QStyle::State_None;
-
- if (d->leftCornerWidget)
- lc = d->leftCornerWidget->sizeHint();
- if(d->rightCornerWidget)
- rc = d->rightCornerWidget->sizeHint();
- if (!d->dirty) {
- QTabWidget *that = (QTabWidget*)this;
- that->setUpLayout(true);
- }
- QSize s(d->stack->sizeHint());
- QSize t(d->tabs->sizeHint());
- if(usesScrollButtons())
- t = t.boundedTo(QSize(200,200));
- else
- t = t.boundedTo(QApplication::desktop()->size());
-
- QSize sz = basicSize(d->pos == North || d->pos == South, lc, rc, s, t);
-
- return style()->sizeFromContents(QStyle::CT_TabWidget, &opt, sz, this)
- .expandedTo(QApplication::globalStrut());
-}
-
-
-/*!
- \reimp
-
- Returns a suitable minimum size for the tab widget.
-*/
-QSize QTabWidget::minimumSizeHint() const
-{
- Q_D(const QTabWidget);
- QSize lc(0, 0), rc(0, 0);
-
- if(d->leftCornerWidget)
- lc = d->leftCornerWidget->minimumSizeHint();
- if(d->rightCornerWidget)
- rc = d->rightCornerWidget->minimumSizeHint();
- if (!d->dirty) {
- QTabWidget *that = (QTabWidget*)this;
- that->setUpLayout(true);
- }
- QSize s(d->stack->minimumSizeHint());
- QSize t(d->tabs->minimumSizeHint());
-
- QSize sz = basicSize(d->pos == North || d->pos == South, lc, rc, s, t);
-
- QStyleOptionTabWidgetFrameV2 opt;
- initStyleOption(&opt);
- opt.palette = palette();
- opt.state = QStyle::State_None;
- return style()->sizeFromContents(QStyle::CT_TabWidget, &opt, sz, this)
- .expandedTo(QApplication::globalStrut());
-}
-
-/*
- \reimp
-*/
-int QTabWidget::heightForWidth(int width) const
-{
- Q_D(const QTabWidget);
- QStyleOptionTabWidgetFrameV2 opt;
- initStyleOption(&opt);
- opt.state = QStyle::State_None;
-
- QSize zero(0,0);
- const QSize padding = style()->sizeFromContents(QStyle::CT_TabWidget, &opt, zero, this)
- .expandedTo(QApplication::globalStrut());
-
- QSize lc(0, 0), rc(0, 0);
- if (d->leftCornerWidget)
- lc = d->leftCornerWidget->sizeHint();
- if(d->rightCornerWidget)
- rc = d->rightCornerWidget->sizeHint();
- if (!d->dirty) {
- QTabWidget *that = (QTabWidget*)this;
- that->setUpLayout(true);
- }
- QSize t(d->tabs->sizeHint());
-
- if(usesScrollButtons())
- t = t.boundedTo(QSize(200,200));
- else
- t = t.boundedTo(QApplication::desktop()->size());
-
- const bool tabIsHorizontal = (d->pos == North || d->pos == South);
- const int contentsWidth = width - padding.width();
- int stackWidth = contentsWidth;
- if (!tabIsHorizontal)
- stackWidth -= qMax(t.width(), qMax(lc.width(), rc.width()));
-
- int stackHeight = d->stack->heightForWidth(stackWidth);
- QSize s(stackWidth, stackHeight);
-
- QSize contentSize = basicSize(tabIsHorizontal, lc, rc, s, t);
- return (contentSize + padding).expandedTo(QApplication::globalStrut()).height();
-}
-
-
-/*!
- \reimp
- */
-void QTabWidget::showEvent(QShowEvent *)
-{
- setUpLayout();
-}
-
-void QTabWidgetPrivate::updateTabBarPosition()
-{
- Q_Q(QTabWidget);
- switch (pos) {
- case QTabWidget::North:
- tabs->setShape(shape == QTabWidget::Rounded ? QTabBar::RoundedNorth
- : QTabBar::TriangularNorth);
- break;
- case QTabWidget::South:
- tabs->setShape(shape == QTabWidget::Rounded ? QTabBar::RoundedSouth
- : QTabBar::TriangularSouth);
- break;
- case QTabWidget::West:
- tabs->setShape(shape == QTabWidget::Rounded ? QTabBar::RoundedWest
- : QTabBar::TriangularWest);
- break;
- case QTabWidget::East:
- tabs->setShape(shape == QTabWidget::Rounded ? QTabBar::RoundedEast
- : QTabBar::TriangularEast);
- break;
- }
- q->setUpLayout();
-}
-
-/*!
- \property QTabWidget::tabPosition
- \brief the position of the tabs in this tab widget
-
- Possible values for this property are described by the TabPosition
- enum.
-
- By default, this property is set to \l North.
-
- \sa TabPosition
-*/
-QTabWidget::TabPosition QTabWidget::tabPosition() const
-{
- Q_D(const QTabWidget);
- return d->pos;
-}
-
-void QTabWidget::setTabPosition(TabPosition pos)
-{
- Q_D(QTabWidget);
- if (d->pos == pos)
- return;
- d->pos = pos;
- d->updateTabBarPosition();
-}
-
-/*!
- \property QTabWidget::tabsClosable
- \brief whether close buttons are automatically added to each tab.
-
- \since 4.5
-
- \sa QTabBar::tabsClosable()
-*/
-bool QTabWidget::tabsClosable() const
-{
- return tabBar()->tabsClosable();
-}
-
-void QTabWidget::setTabsClosable(bool closeable)
-{
- if (tabsClosable() == closeable)
- return;
-
- tabBar()->setTabsClosable(closeable);
- if (closeable)
- connect(tabBar(), SIGNAL(tabCloseRequested(int)),
- this, SIGNAL(tabCloseRequested(int)));
- else
- disconnect(tabBar(), SIGNAL(tabCloseRequested(int)),
- this, SIGNAL(tabCloseRequested(int)));
- setUpLayout();
-}
-
-/*!
- \property QTabWidget::movable
- \brief This property holds whether the user can move the tabs
- within the tabbar area.
-
- \since 4.5
-
- By default, this property is false;
-*/
-
-bool QTabWidget::isMovable() const
-{
- return tabBar()->isMovable();
-}
-
-void QTabWidget::setMovable(bool movable)
-{
- tabBar()->setMovable(movable);
-}
-
-/*!
- \property QTabWidget::tabShape
- \brief the shape of the tabs in this tab widget
-
- Possible values for this property are QTabWidget::Rounded
- (default) or QTabWidget::Triangular.
-
- \sa TabShape
-*/
-
-QTabWidget::TabShape QTabWidget::tabShape() const
-{
- Q_D(const QTabWidget);
- return d->shape;
-}
-
-void QTabWidget::setTabShape(TabShape s)
-{
- Q_D(QTabWidget);
- if (d->shape == s)
- return;
- d->shape = s;
- d->updateTabBarPosition();
-}
-
-/*!
- \reimp
- */
-bool QTabWidget::event(QEvent *ev)
-{
- if (ev->type() == QEvent::LayoutRequest)
- setUpLayout();
- return QWidget::event(ev);
-}
-
-/*!
- \reimp
- */
-void QTabWidget::changeEvent(QEvent *ev)
-{
- if (ev->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || ev->type() == QEvent::MacSizeChange
-#endif
- )
- setUpLayout();
- QWidget::changeEvent(ev);
-}
-
-
-/*!
- \reimp
- */
-void QTabWidget::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QTabWidget);
- if (((e->key() == Qt::Key_Tab || e->key() == Qt::Key_Backtab) &&
- count() > 1 && e->modifiers() & Qt::ControlModifier)
-#ifdef QT_KEYPAD_NAVIGATION
- || QApplication::keypadNavigationEnabled() && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right) && count() > 1
-#endif
- ) {
- int pageCount = d->tabs->count();
- int page = currentIndex();
- int dx = (e->key() == Qt::Key_Backtab || e->modifiers() & Qt::ShiftModifier) ? -1 : 1;
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right))
- dx = e->key() == (isRightToLeft() ? Qt::Key_Right : Qt::Key_Left) ? -1 : 1;
-#endif
- for (int pass = 0; pass < pageCount; ++pass) {
- page+=dx;
- if (page < 0
-#ifdef QT_KEYPAD_NAVIGATION
- && !e->isAutoRepeat()
-#endif
- ) {
- page = count() - 1;
- } else if (page >= pageCount
-#ifdef QT_KEYPAD_NAVIGATION
- && !e->isAutoRepeat()
-#endif
- ) {
- page = 0;
- }
- if (d->tabs->isTabEnabled(page)) {
- setCurrentIndex(page);
- break;
- }
- }
- if (!QApplication::focusWidget())
- d->tabs->setFocus();
- } else {
- e->ignore();
- }
-}
-
-/*!
- Returns the tab page at index position \a index or 0 if the \a
- index is out of range.
-*/
-QWidget *QTabWidget::widget(int index) const
-{
- Q_D(const QTabWidget);
- return d->stack->widget(index);
-}
-
-/*!
- \property QTabWidget::count
- \brief the number of tabs in the tab bar
-
- By default, this property contains a value of 0.
-*/
-int QTabWidget::count() const
-{
- Q_D(const QTabWidget);
- return d->tabs->count();
-}
-
-#ifndef QT_NO_TOOLTIP
-/*!
- Sets the tab tool tip for the page at position \a index to \a tip.
-
- \sa tabToolTip()
-*/
-void QTabWidget::setTabToolTip(int index, const QString & tip)
-{
- Q_D(QTabWidget);
- d->tabs->setTabToolTip(index, tip);
-}
-
-/*!
- Returns the tab tool tip for the page at position \a index or
- an empty string if no tool tip has been set.
-
- \sa setTabToolTip()
-*/
-QString QTabWidget::tabToolTip(int index) const
-{
- Q_D(const QTabWidget);
- return d->tabs->tabToolTip(index);
-}
-#endif // QT_NO_TOOLTIP
-
-#ifndef QT_NO_WHATSTHIS
-/*!
- \since 4.1
-
- Sets the What's This help text for the page at position \a index
- to \a text.
-*/
-void QTabWidget::setTabWhatsThis(int index, const QString &text)
-{
- Q_D(QTabWidget);
- d->tabs->setTabWhatsThis(index, text);
-}
-
-/*!
- \since 4.1
-
- Returns the What's This help text for the page at position \a index,
- or an empty string if no help text has been set.
-*/
-QString QTabWidget::tabWhatsThis(int index) const
-{
- Q_D(const QTabWidget);
- return d->tabs->tabWhatsThis(index);
-}
-#endif // QT_NO_WHATSTHIS
-
-/*!
- This virtual handler is called after a new tab was added or
- inserted at position \a index.
-
- \sa tabRemoved()
- */
-void QTabWidget::tabInserted(int index)
-{
- Q_UNUSED(index)
-}
-
-/*!
- This virtual handler is called after a tab was removed from
- position \a index.
-
- \sa tabInserted()
- */
-void QTabWidget::tabRemoved(int index)
-{
- Q_UNUSED(index)
-}
-
-/*!
- \fn void QTabWidget::paintEvent(QPaintEvent *event)
-
- Paints the tab widget's tab bar in response to the paint \a event.
-*/
-void QTabWidget::paintEvent(QPaintEvent *)
-{
- Q_D(QTabWidget);
- if (documentMode()) {
- QStylePainter p(this, tabBar());
- if (QWidget *w = cornerWidget(Qt::TopLeftCorner)) {
- QStyleOptionTabBarBaseV2 opt;
- QTabBarPrivate::initStyleBaseOption(&opt, tabBar(), w->size());
- opt.rect.moveLeft(w->x() + opt.rect.x());
- opt.rect.moveTop(w->y() + opt.rect.y());
- p.drawPrimitive(QStyle::PE_FrameTabBarBase, opt);
- }
- if (QWidget *w = cornerWidget(Qt::TopRightCorner)) {
- QStyleOptionTabBarBaseV2 opt;
- QTabBarPrivate::initStyleBaseOption(&opt, tabBar(), w->size());
- opt.rect.moveLeft(w->x() + opt.rect.x());
- opt.rect.moveTop(w->y() + opt.rect.y());
- p.drawPrimitive(QStyle::PE_FrameTabBarBase, opt);
- }
- return;
- }
- QStylePainter p(this);
-
- QStyleOptionTabWidgetFrameV2 opt;
- initStyleOption(&opt);
- opt.rect = d->panelRect;
- p.drawPrimitive(QStyle::PE_FrameTabWidget, opt);
-}
-
-/*!
- \property QTabWidget::iconSize
- \brief The size for icons in the tab bar
- \since 4.2
-
- The default value is style-dependent. This is the maximum size
- that the icons will have. Icons are not scaled up if they are of
- smaller size.
-
- \sa QTabBar::iconSize
-*/
-QSize QTabWidget::iconSize() const
-{
- return d_func()->tabs->iconSize();
-}
-
-void QTabWidget::setIconSize(const QSize &size)
-{
- d_func()->tabs->setIconSize(size);
-}
-
-/*!
- \property QTabWidget::elideMode
- \brief how to elide text in the tab bar
- \since 4.2
-
- This property controls how items are elided when there is not
- enough space to show them for a given tab bar size.
-
- By default the value is style dependant.
-
- \sa QTabBar::elideMode usesScrollButtons QStyle::SH_TabBar_ElideMode
-*/
-Qt::TextElideMode QTabWidget::elideMode() const
-{
- return d_func()->tabs->elideMode();
-}
-
-void QTabWidget::setElideMode(Qt::TextElideMode mode)
-{
- d_func()->tabs->setElideMode(mode);
-}
-
-/*!
- \property QTabWidget::usesScrollButtons
- \brief Whether or not a tab bar should use buttons to scroll tabs when it
- has many tabs.
- \since 4.2
-
- When there are too many tabs in a tab bar for its size, the tab bar can either choose
- to expand its size or to add buttons that allow you to scroll through the tabs.
-
- By default the value is style dependant.
-
- \sa elideMode QTabBar::usesScrollButtons QStyle::SH_TabBar_PreferNoArrows
-*/
-bool QTabWidget::usesScrollButtons() const
-{
- return d_func()->tabs->usesScrollButtons();
-}
-
-void QTabWidget::setUsesScrollButtons(bool useButtons)
-{
- d_func()->tabs->setUsesScrollButtons(useButtons);
-}
-
-/*!
- \property QTabWidget::documentMode
- \brief Whether or not the tab widget is rendered in a mode suitable for document
- pages. This is the same as document mode on Mac OS X.
- \since 4.5
-
- When this property is set the tab widget frame is not rendered. This mode is useful
- for showing document-type pages where the page covers most of the tab widget
- area.
-
- \sa elideMode, QTabBar::documentMode, QTabBar::usesScrollButtons, QStyle::SH_TabBar_PreferNoArrows
-*/
-bool QTabWidget::documentMode() const
-{
- Q_D(const QTabWidget);
- return d->tabs->documentMode();
-}
-
-void QTabWidget::setDocumentMode(bool enabled)
-{
- Q_D(QTabWidget);
- d->tabs->setDocumentMode(enabled);
- d->tabs->setExpanding(!enabled);
- d->tabs->setDrawBase(enabled);
- setUpLayout();
-}
-
-/*!
- Removes all the pages, but does not delete them. Calling this function
- is equivalent to calling removeTab() until the tab widget is empty.
-*/
-void QTabWidget::clear()
-{
- // ### optimize by introduce QStackedLayout::clear()
- while (count())
- removeTab(0);
-}
-
-/*!
- \fn void QTabWidget::insertTab(QWidget *widget, const QString &label, int index)
-
- Use insertTab(index, widget, label) instead.
-*/
-
-/*!
- \fn void QTabWidget::insertTab(QWidget *widget, const QIcon& icon, const QString &label, int index)
-
- Use insertTab(index, widget, icon, label) instead.
-*/
-
-/*!
- \fn void QTabWidget::changeTab(QWidget *widget, const QString
- &label)
-
- Use setTabText() instead.
-
-*/
-
-/*!
- \fn void QTabWidget::changeTab(QWidget *widget, const QIcon& icon, const QString &label)
-
- Use setTabText() and setTabIcon() instead.
-*/
-
-/*!
- \fn bool QTabWidget::isTabEnabled( QWidget *widget) const
-
- Use isTabEnabled(tabWidget->indexOf(widget)) instead.
-*/
-
-/*!
- \fn void QTabWidget::setTabEnabled(QWidget *widget, bool b)
-
- Use setTabEnabled(tabWidget->indexOf(widget), b) instead.
-*/
-
-/*!
- \fn QString QTabWidget::tabLabel(QWidget *widget) const
-
- Use tabText(tabWidget->indexOf(widget)) instead.
-*/
-
-/*!
- \fn void QTabWidget::setTabLabel(QWidget *widget, const QString
- &label)
-
- Use setTabText(tabWidget->indexOf(widget), label) instead.
-*/
-
-/*!
- \fn QIcon QTabWidget::tabIconSet(QWidget * widget) const
-
- Use tabIcon(tabWidget->indexOf(widget)) instead.
-*/
-
-/*!
- \fn void QTabWidget::setTabIconSet(QWidget * widget, const QIcon & icon)
-
- Use setTabIcon(tabWidget->indexOf(widget), icon) instead.
-*/
-
-/*!
- \fn void QTabWidget::removeTabToolTip(QWidget * widget)
-
- Use setTabToolTip(tabWidget->indexOf(widget), QString()) instead.
-*/
-
-/*!
- \fn void QTabWidget::setTabToolTip(QWidget * widget, const QString & tip)
-
- Use setTabToolTip(tabWidget->indexOf(widget), tip) instead.
-*/
-
-/*!
- \fn QString QTabWidget::tabToolTip(QWidget * widget) const
-
- Use tabToolTip(tabWidget->indexOf(widget)) instead.
-*/
-
-/*!
- \fn QWidget * QTabWidget::currentPage() const
-
- Use currentWidget() instead.
-*/
-
-/*!
- \fn QWidget *QTabWidget::page(int index) const
-
- Use widget() instead.
-*/
-
-/*!
- \fn QString QTabWidget::label(int index) const
-
- Use tabText() instead.
-*/
-
-/*!
- \fn int QTabWidget::currentPageIndex() const
-
- Use currentIndex() instead.
-*/
-
-/*!
- \fn int QTabWidget::margin() const
-
- This function is kept only to make old code compile.
- This functionality is no longer supported by QTabWidget.
-
- \sa contentsRect(), setContentsMargins()
-*/
-
-/*!
- \fn void QTabWidget::setMargin(int margin)
-
- This function is kept only to make old code compile.
- This functionality is no longer supported by QTabWidget.
-
- \sa contentsRect(), setContentsMargins()
-*/
-
-/*!
- \fn void QTabWidget::setCurrentPage(int index)
-
- Use setCurrentIndex() instead.
-*/
-
-/*!
- \fn void QTabWidget::showPage(QWidget *widget)
-
- Use setCurrentIndex(indexOf(widget)) instead.
-*/
-
-/*!
- \fn void QTabWidget::removePage(QWidget *widget)
-
- Use removeTab(indexOf(widget)) instead.
-*/
-
-/*!
- \fn void QTabWidget::currentChanged(QWidget *widget)
-
- Use currentChanged(int) instead.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qtabwidget.cpp"
-
-#endif //QT_NO_TABWIDGET
diff --git a/src/gui/widgets/qtabwidget.h b/src/gui/widgets/qtabwidget.h
deleted file mode 100644
index b0e6fb3891..0000000000
--- a/src/gui/widgets/qtabwidget.h
+++ /dev/null
@@ -1,253 +0,0 @@
-/****************************************************************************
-**
-** 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 QTABWIDGET_H
-#define QTABWIDGET_H
-
-#include <QtGui/qwidget.h>
-#include <QtGui/qicon.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TABWIDGET
-
-class QTabBar;
-class QTabWidgetPrivate;
-class QStyleOptionTabWidgetFrame;
-
-class Q_GUI_EXPORT QTabWidget : public QWidget
-{
- Q_OBJECT
- Q_ENUMS(TabPosition TabShape)
- Q_PROPERTY(TabPosition tabPosition READ tabPosition WRITE setTabPosition)
- Q_PROPERTY(TabShape tabShape READ tabShape WRITE setTabShape)
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)
- Q_PROPERTY(int count READ count)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
- Q_PROPERTY(Qt::TextElideMode elideMode READ elideMode WRITE setElideMode)
- Q_PROPERTY(bool usesScrollButtons READ usesScrollButtons WRITE setUsesScrollButtons)
- Q_PROPERTY(bool documentMode READ documentMode WRITE setDocumentMode)
- Q_PROPERTY(bool tabsClosable READ tabsClosable WRITE setTabsClosable)
- Q_PROPERTY(bool movable READ isMovable WRITE setMovable)
-
-public:
- explicit QTabWidget(QWidget *parent = 0);
- ~QTabWidget();
-
- int addTab(QWidget *widget, const QString &);
- int addTab(QWidget *widget, const QIcon& icon, const QString &label);
-
- int insertTab(int index, QWidget *widget, const QString &);
- int insertTab(int index, QWidget *widget, const QIcon& icon, const QString &label);
-
- void removeTab(int index);
-
- bool isTabEnabled(int index) const;
- void setTabEnabled(int index, bool);
-
- QString tabText(int index) const;
- void setTabText(int index, const QString &);
-
- QIcon tabIcon(int index) const;
- void setTabIcon(int index, const QIcon & icon);
-
-#ifndef QT_NO_TOOLTIP
- void setTabToolTip(int index, const QString & tip);
- QString tabToolTip(int index) const;
-#endif
-
-#ifndef QT_NO_WHATSTHIS
- void setTabWhatsThis(int index, const QString &text);
- QString tabWhatsThis(int index) const;
-#endif
-
- int currentIndex() const;
- QWidget *currentWidget() const;
- QWidget *widget(int index) const;
- int indexOf(QWidget *widget) const;
- int count() const;
-
- enum TabPosition { North, South, West, East
-#if defined(QT3_SUPPORT) && !defined(Q_MOC_RUN)
- , Top = North, Bottom = South
-#endif
- };
- TabPosition tabPosition() const;
- void setTabPosition(TabPosition);
-
- bool tabsClosable() const;
- void setTabsClosable(bool closeable);
-
- bool isMovable() const;
- void setMovable(bool movable);
-
- enum TabShape { Rounded, Triangular };
- TabShape tabShape() const;
- void setTabShape(TabShape s);
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
- int heightForWidth(int width) const;
-
- void setCornerWidget(QWidget * w, Qt::Corner corner = Qt::TopRightCorner);
- QWidget * cornerWidget(Qt::Corner corner = Qt::TopRightCorner) const;
-
- Qt::TextElideMode elideMode() const;
- void setElideMode(Qt::TextElideMode);
-
- QSize iconSize() const;
- void setIconSize(const QSize &size);
-
- bool usesScrollButtons() const;
- void setUsesScrollButtons(bool useButtons);
-
- bool documentMode() const;
- void setDocumentMode(bool set);
-
- void clear();
-
-public Q_SLOTS:
- void setCurrentIndex(int index);
- void setCurrentWidget(QWidget *widget);
-
-Q_SIGNALS:
- void currentChanged(int index);
- void tabCloseRequested(int index);
-
-protected:
- virtual void tabInserted(int index);
- virtual void tabRemoved(int index);
-
- void showEvent(QShowEvent *);
- void resizeEvent(QResizeEvent *);
- void keyPressEvent(QKeyEvent *);
- void paintEvent(QPaintEvent *);
- void setTabBar(QTabBar *);
- QTabBar* tabBar() const;
- void changeEvent(QEvent *);
- bool event(QEvent *);
- void initStyleOption(QStyleOptionTabWidgetFrame *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QTabWidget(QWidget *parent, const char *name, Qt::WindowFlags f = 0);
-
- inline QT3_SUPPORT void insertTab(QWidget * w, const QString &s, int index = -1) { insertTab(index, w, s); }
- inline QT3_SUPPORT void insertTab(QWidget *child, const QIcon& icon,
- const QString &label, int index = -1) { insertTab(index, child, icon, label); }
-
- inline QT3_SUPPORT void changeTab(QWidget *w, const QString &s) {setTabText(indexOf(w), s); }
- inline QT3_SUPPORT void changeTab(QWidget *w, const QIcon& icon,
- const QString &label) { int idx = indexOf(w); setTabText(idx, label); setTabIcon(idx, icon); }
-
- inline QT3_SUPPORT bool isTabEnabled( QWidget *w) const {return isTabEnabled(indexOf(w)); }
- inline QT3_SUPPORT void setTabEnabled(QWidget *w, bool b) { setTabEnabled(indexOf(w), b); }
-
- inline QT3_SUPPORT QString tabLabel(QWidget *w) const {return tabText(indexOf(w)); }
- inline QT3_SUPPORT void setTabLabel(QWidget *w, const QString &l) { setTabText(indexOf(w), l); }
-
- inline QT3_SUPPORT QIcon tabIconSet(QWidget * w) const {return tabIcon(indexOf(w)); }
- inline QT3_SUPPORT void setTabIconSet(QWidget * w, const QIcon & icon) { setTabIcon(indexOf(w), icon); }
-
- inline QT3_SUPPORT void removeTabToolTip(QWidget * w) {
-#ifndef QT_NO_TOOLTIP
- setTabToolTip(indexOf(w), QString());
-#else
- Q_UNUSED(w);
-#endif
- }
- inline QT3_SUPPORT void setTabToolTip(QWidget * w, const QString & tip) {
-#ifndef QT_NO_TOOLTIP
- setTabToolTip(indexOf(w), tip);
-#else
- Q_UNUSED(w);
- Q_UNUSED(tip);
-#endif
- }
-
- inline QT3_SUPPORT QString tabToolTip(QWidget * w) const {
-#ifndef QT_NO_TOOLTIP
- return tabToolTip(indexOf(w));
-#else
- Q_UNUSED(w);
- return QString();
-#endif
- }
-
- inline QT3_SUPPORT QWidget * currentPage() const { return currentWidget(); }
- inline QT3_SUPPORT QWidget *page(int index) const { return widget(index); }
- inline QT3_SUPPORT QString label(int index) const { return tabText(index); }
- inline QT3_SUPPORT int currentPageIndex() const { return currentIndex(); }
-
- inline QT3_SUPPORT int margin() const { return 0; }
- inline QT3_SUPPORT void setMargin(int) {}
-
-public Q_SLOTS:
- inline QT_MOC_COMPAT void setCurrentPage(int index) { setCurrentIndex(index); }
- inline QT_MOC_COMPAT void showPage(QWidget *w) { setCurrentIndex(indexOf(w)); }
- inline QT_MOC_COMPAT void removePage(QWidget *w) { removeTab(indexOf(w)); }
-
-Q_SIGNALS:
- QT_MOC_COMPAT void currentChanged(QWidget *);
- QT_MOC_COMPAT void selected(const QString&);
-#endif // QT3_SUPPORT
-
-private:
- Q_DECLARE_PRIVATE(QTabWidget)
- Q_DISABLE_COPY(QTabWidget)
- Q_PRIVATE_SLOT(d_func(), void _q_showTab(int))
- Q_PRIVATE_SLOT(d_func(), void _q_removeTab(int))
- Q_PRIVATE_SLOT(d_func(), void _q_tabMoved(int, int))
- void setUpLayout(bool = false);
- friend class Q3TabDialog;
-};
-
-#endif // QT_NO_TABWIDGET
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTABWIDGET_H
diff --git a/src/gui/widgets/qtextbrowser.cpp b/src/gui/widgets/qtextbrowser.cpp
deleted file mode 100644
index 2c1fb285c4..0000000000
--- a/src/gui/widgets/qtextbrowser.cpp
+++ /dev/null
@@ -1,1275 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtextbrowser.h"
-#include "qtextedit_p.h"
-
-#ifndef QT_NO_TEXTBROWSER
-
-#include <qstack.h>
-#include <qapplication.h>
-#include <qevent.h>
-#include <qdesktopwidget.h>
-#include <qdebug.h>
-#include <qabstracttextdocumentlayout.h>
-#include "private/qtextdocumentlayout_p.h"
-#include <qtextcodec.h>
-#include <qpainter.h>
-#include <qdir.h>
-#include <qwhatsthis.h>
-#include <qtextobject.h>
-#include <qdesktopservices.h>
-
-QT_BEGIN_NAMESPACE
-
-class QTextBrowserPrivate : public QTextEditPrivate
-{
- Q_DECLARE_PUBLIC(QTextBrowser)
-public:
- inline QTextBrowserPrivate()
- : textOrSourceChanged(false), forceLoadOnSourceChange(false), openExternalLinks(false),
- openLinks(true)
-#ifdef QT_KEYPAD_NAVIGATION
- , lastKeypadScrollValue(-1)
-#endif
- {}
-
- void init();
-
- struct HistoryEntry {
- inline HistoryEntry()
- : hpos(0), vpos(0), focusIndicatorPosition(-1),
- focusIndicatorAnchor(-1) {}
- QUrl url;
- QString title;
- int hpos;
- int vpos;
- int focusIndicatorPosition, focusIndicatorAnchor;
- };
-
- HistoryEntry history(int i) const
- {
- if (i <= 0)
- if (-i < stack.count())
- return stack[stack.count()+i-1];
- else
- return HistoryEntry();
- else
- if (i <= forwardStack.count())
- return forwardStack[forwardStack.count()-i];
- else
- return HistoryEntry();
- }
-
-
- HistoryEntry createHistoryEntry() const;
- void restoreHistoryEntry(const HistoryEntry entry);
-
- QStack<HistoryEntry> stack;
- QStack<HistoryEntry> forwardStack;
- QUrl home;
- QUrl currentURL;
-
- QStringList searchPaths;
-
- /*flag necessary to give the linkClicked() signal some meaningful
- semantics when somebody connected to it calls setText() or
- setSource() */
- bool textOrSourceChanged;
- bool forceLoadOnSourceChange;
-
- bool openExternalLinks;
- bool openLinks;
-
-#ifndef QT_NO_CURSOR
- QCursor oldCursor;
-#endif
-
- QString findFile(const QUrl &name) const;
-
- inline void _q_documentModified()
- {
- textOrSourceChanged = true;
- forceLoadOnSourceChange = !currentURL.path().isEmpty();
- }
-
- void _q_activateAnchor(const QString &href);
- void _q_highlightLink(const QString &href);
-
- void setSource(const QUrl &url);
-
- // re-imlemented from QTextEditPrivate
- virtual QUrl resolveUrl(const QUrl &url) const;
- inline QUrl resolveUrl(const QString &url) const
- { return resolveUrl(QUrl::fromEncoded(url.toUtf8())); }
-
-#ifdef QT_KEYPAD_NAVIGATION
- void keypadMove(bool next);
- QTextCursor prevFocus;
- int lastKeypadScrollValue;
-#endif
-};
-
-QString QTextBrowserPrivate::findFile(const QUrl &name) const
-{
- QString fileName;
- if (name.scheme() == QLatin1String("qrc"))
- fileName = QLatin1String(":/") + name.path();
- else
- fileName = name.toLocalFile();
-
- if (QFileInfo(fileName).isAbsolute())
- return fileName;
-
- foreach (QString path, searchPaths) {
- if (!path.endsWith(QLatin1Char('/')))
- path.append(QLatin1Char('/'));
- path.append(fileName);
- if (QFileInfo(path).isReadable())
- return path;
- }
-
- return fileName;
-}
-
-QUrl QTextBrowserPrivate::resolveUrl(const QUrl &url) const
-{
- if (!url.isRelative())
- return url;
-
- // For the second case QUrl can merge "#someanchor" with "foo.html"
- // correctly to "foo.html#someanchor"
- if (!(currentURL.isRelative()
- || (currentURL.scheme() == QLatin1String("file")
- && !QFileInfo(currentURL.toLocalFile()).isAbsolute()))
- || (url.hasFragment() && url.path().isEmpty())) {
- return currentURL.resolved(url);
- }
-
- // this is our last resort when current url and new url are both relative
- // we try to resolve against the current working directory in the local
- // file system.
- QFileInfo fi(currentURL.toLocalFile());
- if (fi.exists()) {
- return QUrl::fromLocalFile(fi.absolutePath() + QDir::separator()).resolved(url);
- }
-
- return url;
-}
-
-void QTextBrowserPrivate::_q_activateAnchor(const QString &href)
-{
- if (href.isEmpty())
- return;
- Q_Q(QTextBrowser);
-
-#ifndef QT_NO_CURSOR
- viewport->setCursor(oldCursor);
-#endif
-
- const QUrl url = resolveUrl(href);
-
- if (!openLinks) {
- emit q->anchorClicked(url);
- return;
- }
-
- textOrSourceChanged = false;
-
-#ifndef QT_NO_DESKTOPSERVICES
- if ((openExternalLinks
- && url.scheme() != QLatin1String("file")
- && url.scheme() != QLatin1String("qrc")
- && !url.isRelative())
- || (url.isRelative() && !currentURL.isRelative()
- && currentURL.scheme() != QLatin1String("file")
- && currentURL.scheme() != QLatin1String("qrc"))) {
- QDesktopServices::openUrl(url);
- return;
- }
-#endif
-
- emit q->anchorClicked(url);
-
- if (textOrSourceChanged)
- return;
-
- q->setSource(url);
-}
-
-void QTextBrowserPrivate::_q_highlightLink(const QString &anchor)
-{
- Q_Q(QTextBrowser);
- if (anchor.isEmpty()) {
-#ifndef QT_NO_CURSOR
- if (viewport->cursor().shape() != Qt::PointingHandCursor)
- oldCursor = viewport->cursor();
- viewport->setCursor(oldCursor);
-#endif
- emit q->highlighted(QUrl());
- emit q->highlighted(QString());
- } else {
-#ifndef QT_NO_CURSOR
- viewport->setCursor(Qt::PointingHandCursor);
-#endif
-
- const QUrl url = resolveUrl(anchor);
- emit q->highlighted(url);
- // convenience to ease connecting to QStatusBar::showMessage(const QString &)
- emit q->highlighted(url.toString());
- }
-}
-
-void QTextBrowserPrivate::setSource(const QUrl &url)
-{
- Q_Q(QTextBrowser);
-#ifndef QT_NO_CURSOR
- if (q->isVisible())
- QApplication::setOverrideCursor(Qt::WaitCursor);
-#endif
- textOrSourceChanged = true;
-
- QString txt;
-
- bool doSetText = false;
-
- QUrl currentUrlWithoutFragment = currentURL;
- currentUrlWithoutFragment.setFragment(QString());
- QUrl newUrlWithoutFragment = currentURL.resolved(url);
- newUrlWithoutFragment.setFragment(QString());
-
- if (url.isValid()
- && (newUrlWithoutFragment != currentUrlWithoutFragment || forceLoadOnSourceChange)) {
- QVariant data = q->loadResource(QTextDocument::HtmlResource, resolveUrl(url));
- if (data.type() == QVariant::String) {
- txt = data.toString();
- } else if (data.type() == QVariant::ByteArray) {
-#ifndef QT_NO_TEXTCODEC
- QByteArray ba = data.toByteArray();
- QTextCodec *codec = Qt::codecForHtml(ba);
- txt = codec->toUnicode(ba);
-#else
- txt = data.toString();
-#endif
- }
- if (txt.isEmpty())
- qWarning("QTextBrowser: No document for %s", url.toString().toLatin1().constData());
-
- if (q->isVisible()) {
- QString firstTag = txt.left(txt.indexOf(QLatin1Char('>')) + 1);
- if (firstTag.startsWith(QLatin1String("<qt")) && firstTag.contains(QLatin1String("type")) && firstTag.contains(QLatin1String("detail"))) {
-#ifndef QT_NO_CURSOR
- QApplication::restoreOverrideCursor();
-#endif
-#ifndef QT_NO_WHATSTHIS
- QWhatsThis::showText(QCursor::pos(), txt, q);
-#endif
- return;
- }
- }
-
- currentURL = resolveUrl(url);
- doSetText = true;
- }
-
- if (!home.isValid())
- home = url;
-
- if (doSetText) {
-#ifndef QT_NO_TEXTHTMLPARSER
- q->QTextEdit::setHtml(txt);
- q->document()->setMetaInformation(QTextDocument::DocumentUrl, currentURL.toString());
-#else
- q->QTextEdit::setPlainText(txt);
-#endif
-
-#ifdef QT_KEYPAD_NAVIGATION
- prevFocus.movePosition(QTextCursor::Start);
-#endif
- }
-
- forceLoadOnSourceChange = false;
-
- if (!url.fragment().isEmpty()) {
- q->scrollToAnchor(url.fragment());
- } else {
- hbar->setValue(0);
- vbar->setValue(0);
- }
-#ifdef QT_KEYPAD_NAVIGATION
- lastKeypadScrollValue = vbar->value();
- emit q->highlighted(QUrl());
- emit q->highlighted(QString());
-#endif
-
-#ifndef QT_NO_CURSOR
- if (q->isVisible())
- QApplication::restoreOverrideCursor();
-#endif
- emit q->sourceChanged(url);
-}
-
-#ifdef QT_KEYPAD_NAVIGATION
-void QTextBrowserPrivate::keypadMove(bool next)
-{
- Q_Q(QTextBrowser);
-
- const int height = viewport->height();
- const int overlap = qBound(20, height / 5, 40); // XXX arbitrary, but a good balance
- const int visibleLinkAmount = overlap; // consistent, but maybe not the best choice (?)
- int yOffset = vbar->value();
- int scrollYOffset = qBound(0, next ? yOffset + height - overlap : yOffset - height + overlap, vbar->maximum());
-
- bool foundNextAnchor = false;
- bool focusIt = false;
- int focusedPos = -1;
-
- QTextCursor anchorToFocus;
-
- QRectF viewRect = QRectF(0, yOffset, control->size().width(), height);
- QRectF newViewRect = QRectF(0, scrollYOffset, control->size().width(), height);
- QRectF bothViewRects = viewRect.united(newViewRect);
-
- // If we don't have a previous anchor, pretend that we had the first/last character
- // on the screen selected.
- if (prevFocus.isNull()) {
- if (next)
- prevFocus = control->cursorForPosition(QPointF(0, yOffset));
- else
- prevFocus = control->cursorForPosition(QPointF(control->size().width(), yOffset + height));
- }
-
- // First, check to see if someone has moved the scroll bars independently
- if (lastKeypadScrollValue != yOffset) {
- // Someone (user or programmatically) has moved us, so we might
- // need to start looking from the current position instead of prevFocus
-
- bool findOnScreen = true;
-
- // If prevFocus is on screen at all, we just use it.
- if (prevFocus.hasSelection()) {
- QRectF prevRect = control->selectionRect(prevFocus);
- if (viewRect.intersects(prevRect))
- findOnScreen = false;
- }
-
- // Otherwise, we find a new anchor that's on screen.
- // Basically, create a cursor with the last/first character
- // on screen
- if (findOnScreen) {
- if (next)
- prevFocus = control->cursorForPosition(QPointF(0, yOffset));
- else
- prevFocus = control->cursorForPosition(QPointF(control->size().width(), yOffset + height));
- }
- foundNextAnchor = control->findNextPrevAnchor(prevFocus, next, anchorToFocus);
- } else if (prevFocus.hasSelection()) {
- // Check the pathological case that the current anchor is higher
- // than the screen, and just scroll through it in that case
- QRectF prevRect = control->selectionRect(prevFocus);
- if ((next && prevRect.bottom() > (yOffset + height)) ||
- (!next && prevRect.top() < yOffset)) {
- anchorToFocus = prevFocus;
- focusedPos = scrollYOffset;
- focusIt = true;
- } else {
- // This is the "normal" case - no scroll bar adjustments, no large anchors,
- // and no wrapping.
- foundNextAnchor = control->findNextPrevAnchor(prevFocus, next, anchorToFocus);
- }
- }
-
- // If not found yet, see if we need to wrap
- if (!focusIt && !foundNextAnchor) {
- if (next) {
- if (yOffset == vbar->maximum()) {
- prevFocus.movePosition(QTextCursor::Start);
- yOffset = scrollYOffset = 0;
-
- // Refresh the rectangles
- viewRect = QRectF(0, yOffset, control->size().width(), height);
- newViewRect = QRectF(0, scrollYOffset, control->size().width(), height);
- bothViewRects = viewRect.united(newViewRect);
- }
- } else {
- if (yOffset == 0) {
- prevFocus.movePosition(QTextCursor::End);
- yOffset = scrollYOffset = vbar->maximum();
-
- // Refresh the rectangles
- viewRect = QRectF(0, yOffset, control->size().width(), height);
- newViewRect = QRectF(0, scrollYOffset, control->size().width(), height);
- bothViewRects = viewRect.united(newViewRect);
- }
- }
-
- // Try looking now
- foundNextAnchor = control->findNextPrevAnchor(prevFocus, next, anchorToFocus);
- }
-
- // If we did actually find an anchor to use...
- if (foundNextAnchor) {
- QRectF desiredRect = control->selectionRect(anchorToFocus);
-
- // XXX This is an arbitrary heuristic
- // Decide to focus an anchor if it will be at least be
- // in the middle region of the screen after a scroll.
- // This can result in partial anchors with focus, but
- // insisting on links being completely visible before
- // selecting them causes disparities between links that
- // take up 90% of the screen height and those that take
- // up e.g. 110%
- // Obviously if a link is entirely visible, we still
- // focus it.
- if(bothViewRects.contains(desiredRect)
- || bothViewRects.adjusted(0, visibleLinkAmount, 0, -visibleLinkAmount).intersects(desiredRect)) {
- focusIt = true;
-
- // We aim to put the new link in the middle of the screen,
- // unless the link is larger than the screen (we just move to
- // display the first page of the link)
- if (desiredRect.height() > height) {
- if (next)
- focusedPos = (int) desiredRect.top();
- else
- focusedPos = (int) desiredRect.bottom() - height;
- } else
- focusedPos = (int) ((desiredRect.top() + desiredRect.bottom()) / 2 - (height / 2));
-
- // and clamp it to make sure we don't skip content.
- if (next)
- focusedPos = qBound(yOffset, focusedPos, scrollYOffset);
- else
- focusedPos = qBound(scrollYOffset, focusedPos, yOffset);
- }
- }
-
- // If we didn't get a new anchor, check if the old one is still on screen when we scroll
- // Note that big (larger than screen height) anchors also have some handling at the
- // start of this function.
- if (!focusIt && prevFocus.hasSelection()) {
- QRectF desiredRect = control->selectionRect(prevFocus);
- // XXX this may be better off also using the visibleLinkAmount value
- if(newViewRect.intersects(desiredRect)) {
- focusedPos = scrollYOffset;
- focusIt = true;
- anchorToFocus = prevFocus;
- }
- }
-
- // setTextCursor ensures that the cursor is visible. save & restore
- // the scroll bar values therefore
- const int savedXOffset = hbar->value();
-
- // Now actually process our decision
- if (focusIt && control->setFocusToAnchor(anchorToFocus)) {
- // Save the focus for next time
- prevFocus = control->textCursor();
-
- // Scroll
- vbar->setValue(focusedPos);
- lastKeypadScrollValue = focusedPos;
- hbar->setValue(savedXOffset);
-
- // Ensure that the new selection is highlighted.
- const QString href = control->anchorAtCursor();
- QUrl url = resolveUrl(href);
- emit q->highlighted(url);
- emit q->highlighted(url.toString());
- } else {
- // Scroll
- vbar->setValue(scrollYOffset);
- lastKeypadScrollValue = scrollYOffset;
-
- // now make sure we don't have a focused anchor
- QTextCursor cursor = control->textCursor();
- cursor.clearSelection();
-
- control->setTextCursor(cursor);
-
- hbar->setValue(savedXOffset);
- vbar->setValue(scrollYOffset);
-
- emit q->highlighted(QUrl());
- emit q->highlighted(QString());
- }
-}
-#endif
-
-QTextBrowserPrivate::HistoryEntry QTextBrowserPrivate::createHistoryEntry() const
-{
- HistoryEntry entry;
- entry.url = q_func()->source();
- entry.title = q_func()->documentTitle();
- entry.hpos = hbar->value();
- entry.vpos = vbar->value();
-
- const QTextCursor cursor = control->textCursor();
- if (control->cursorIsFocusIndicator()
- && cursor.hasSelection()) {
-
- entry.focusIndicatorPosition = cursor.position();
- entry.focusIndicatorAnchor = cursor.anchor();
- }
- return entry;
-}
-
-void QTextBrowserPrivate::restoreHistoryEntry(const HistoryEntry entry)
-{
- setSource(entry.url);
- hbar->setValue(entry.hpos);
- vbar->setValue(entry.vpos);
- if (entry.focusIndicatorAnchor != -1 && entry.focusIndicatorPosition != -1) {
- QTextCursor cursor(control->document());
- cursor.setPosition(entry.focusIndicatorAnchor);
- cursor.setPosition(entry.focusIndicatorPosition, QTextCursor::KeepAnchor);
- control->setTextCursor(cursor);
- control->setCursorIsFocusIndicator(true);
- }
-#ifdef QT_KEYPAD_NAVIGATION
- lastKeypadScrollValue = vbar->value();
- prevFocus = control->textCursor();
-
- Q_Q(QTextBrowser);
- const QString href = prevFocus.charFormat().anchorHref();
- QUrl url = resolveUrl(href);
- emit q->highlighted(url);
- emit q->highlighted(url.toString());
-#endif
-}
-
-/*!
- \class QTextBrowser
- \brief The QTextBrowser class provides a rich text browser with hypertext navigation.
-
- \ingroup richtext-processing
-
- This class extends QTextEdit (in read-only mode), adding some navigation
- functionality so that users can follow links in hypertext documents.
-
- If you want to provide your users with an editable rich text editor,
- use QTextEdit. If you want a text browser without hypertext navigation
- use QTextEdit, and use QTextEdit::setReadOnly() to disable
- editing. If you just need to display a small piece of rich text
- use QLabel.
-
- \section1 Document Source and Contents
-
- The contents of QTextEdit are set with setHtml() or setPlainText(),
- but QTextBrowser also implements the setSource() function, making it
- possible to use a named document as the source text. The name is looked
- up in a list of search paths and in the directory of the current document
- factory.
-
- If a document name ends with
- an anchor (for example, "\c #anchor"), the text browser automatically
- scrolls to that position (using scrollToAnchor()). When the user clicks
- on a hyperlink, the browser will call setSource() itself with the link's
- \c href value as argument. You can track the current source by connecting
- to the sourceChanged() signal.
-
- \section1 Navigation
-
- QTextBrowser provides backward() and forward() slots which you can
- use to implement Back and Forward buttons. The home() slot sets
- the text to the very first document displayed. The anchorClicked()
- signal is emitted when the user clicks an anchor. To override the
- default navigation behavior of the browser, call the setSource()
- function to supply new document text in a slot connected to this
- signal.
-
- If you want to load documents stored in the Qt resource system use
- \c{qrc} as the scheme in the URL to load. For example, for the document
- resource path \c{:/docs/index.html} use \c{qrc:/docs/index.html} as
- the URL with setSource().
-
- \sa QTextEdit, QTextDocument
-*/
-
-/*!
- \property QTextBrowser::modified
- \brief whether the contents of the text browser have been modified
-*/
-
-/*!
- \property QTextBrowser::readOnly
- \brief whether the text browser is read-only
-
- By default, this property is true.
-*/
-
-/*!
- \property QTextBrowser::undoRedoEnabled
- \brief whether the text browser supports undo/redo operations
-
- By default, this property is false.
-*/
-
-void QTextBrowserPrivate::init()
-{
- Q_Q(QTextBrowser);
- control->setTextInteractionFlags(Qt::TextBrowserInteraction);
-#ifndef QT_NO_CURSOR
- viewport->setCursor(oldCursor);
-#endif
- q->setUndoRedoEnabled(false);
- viewport->setMouseTracking(true);
- QObject::connect(q->document(), SIGNAL(contentsChanged()), q, SLOT(_q_documentModified()));
- QObject::connect(control, SIGNAL(linkActivated(QString)),
- q, SLOT(_q_activateAnchor(QString)));
- QObject::connect(control, SIGNAL(linkHovered(QString)),
- q, SLOT(_q_highlightLink(QString)));
-}
-
-/*!
- Constructs an empty QTextBrowser with parent \a parent.
-*/
-QTextBrowser::QTextBrowser(QWidget *parent)
- : QTextEdit(*new QTextBrowserPrivate, parent)
-{
- Q_D(QTextBrowser);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QTextBrowser::QTextBrowser(QWidget *parent, const char *name)
- : QTextEdit(*new QTextBrowserPrivate, parent)
-{
- setObjectName(QString::fromAscii(name));
- Q_D(QTextBrowser);
- d->init();
-}
-#endif
-
-/*!
- \internal
-*/
-QTextBrowser::~QTextBrowser()
-{
-}
-
-/*!
- \property QTextBrowser::source
- \brief the name of the displayed document.
-
- This is a an invalid url if no document is displayed or if the
- source is unknown.
-
- When setting this property QTextBrowser tries to find a document
- with the specified name in the paths of the searchPaths property
- and directory of the current source, unless the value is an absolute
- file path. It also checks for optional anchors and scrolls the document
- accordingly
-
- If the first tag in the document is \c{<qt type=detail>}, the
- document is displayed as a popup rather than as new document in
- the browser window itself. Otherwise, the document is displayed
- normally in the text browser with the text set to the contents of
- the named document with setHtml().
-
- By default, this property contains an empty URL.
-*/
-QUrl QTextBrowser::source() const
-{
- Q_D(const QTextBrowser);
- if (d->stack.isEmpty())
- return QUrl();
- else
- return d->stack.top().url;
-}
-
-/*!
- \property QTextBrowser::searchPaths
- \brief the search paths used by the text browser to find supporting
- content
-
- QTextBrowser uses this list to locate images and documents.
-
- By default, this property contains an empty string list.
-*/
-
-QStringList QTextBrowser::searchPaths() const
-{
- Q_D(const QTextBrowser);
- return d->searchPaths;
-}
-
-void QTextBrowser::setSearchPaths(const QStringList &paths)
-{
- Q_D(QTextBrowser);
- d->searchPaths = paths;
-}
-
-/*!
- Reloads the current set source.
-*/
-void QTextBrowser::reload()
-{
- Q_D(QTextBrowser);
- QUrl s = d->currentURL;
- d->currentURL = QUrl();
- setSource(s);
-}
-
-void QTextBrowser::setSource(const QUrl &url)
-{
- Q_D(QTextBrowser);
-
- const QTextBrowserPrivate::HistoryEntry historyEntry = d->createHistoryEntry();
-
- d->setSource(url);
-
- if (!url.isValid())
- return;
-
- // the same url you are already watching?
- if (!d->stack.isEmpty() && d->stack.top().url == url)
- return;
-
- if (!d->stack.isEmpty())
- d->stack.top() = historyEntry;
-
- QTextBrowserPrivate::HistoryEntry entry;
- entry.url = url;
- entry.title = documentTitle();
- entry.hpos = 0;
- entry.vpos = 0;
- d->stack.push(entry);
-
- emit backwardAvailable(d->stack.count() > 1);
-
- if (!d->forwardStack.isEmpty() && d->forwardStack.top().url == url) {
- d->forwardStack.pop();
- emit forwardAvailable(d->forwardStack.count() > 0);
- } else {
- d->forwardStack.clear();
- emit forwardAvailable(false);
- }
-
- emit historyChanged();
-}
-
-/*!
- \fn void QTextBrowser::backwardAvailable(bool available)
-
- This signal is emitted when the availability of backward()
- changes. \a available is false when the user is at home();
- otherwise it is true.
-*/
-
-/*!
- \fn void QTextBrowser::forwardAvailable(bool available)
-
- This signal is emitted when the availability of forward() changes.
- \a available is true after the user navigates backward() and false
- when the user navigates or goes forward().
-*/
-
-/*!
- \fn void QTextBrowser::historyChanged()
- \since 4.4
-
- This signal is emitted when the history changes.
-
- \sa historyTitle(), historyUrl()
-*/
-
-/*!
- \fn void QTextBrowser::sourceChanged(const QUrl &src)
-
- This signal is emitted when the source has changed, \a src
- being the new source.
-
- Source changes happen both programmatically when calling
- setSource(), forward(), backword() or home() or when the user
- clicks on links or presses the equivalent key sequences.
-*/
-
-/*! \fn void QTextBrowser::highlighted(const QUrl &link)
-
- This signal is emitted when the user has selected but not
- activated an anchor in the document. The URL referred to by the
- anchor is passed in \a link.
-*/
-
-/*! \fn void QTextBrowser::highlighted(const QString &link)
- \overload
-
- Convenience signal that allows connecting to a slot
- that takes just a QString, like for example QStatusBar's
- message().
-*/
-
-
-/*!
- \fn void QTextBrowser::anchorClicked(const QUrl &link)
-
- This signal is emitted when the user clicks an anchor. The
- URL referred to by the anchor is passed in \a link.
-
- Note that the browser will automatically handle navigation to the
- location specified by \a link unless the openLinks property
- is set to false or you call setSource() in a slot connected.
- This mechanism is used to override the default navigation features of the browser.
-*/
-
-/*!
- Changes the document displayed to the previous document in the
- list of documents built by navigating links. Does nothing if there
- is no previous document.
-
- \sa forward(), backwardAvailable()
-*/
-void QTextBrowser::backward()
-{
- Q_D(QTextBrowser);
- if (d->stack.count() <= 1)
- return;
-
- // Update the history entry
- d->forwardStack.push(d->createHistoryEntry());
- d->stack.pop(); // throw away the old version of the current entry
- d->restoreHistoryEntry(d->stack.top()); // previous entry
- emit backwardAvailable(d->stack.count() > 1);
- emit forwardAvailable(true);
- emit historyChanged();
-}
-
-/*!
- Changes the document displayed to the next document in the list of
- documents built by navigating links. Does nothing if there is no
- next document.
-
- \sa backward(), forwardAvailable()
-*/
-void QTextBrowser::forward()
-{
- Q_D(QTextBrowser);
- if (d->forwardStack.isEmpty())
- return;
- if (!d->stack.isEmpty()) {
- // Update the history entry
- d->stack.top() = d->createHistoryEntry();
- }
- d->stack.push(d->forwardStack.pop());
- d->restoreHistoryEntry(d->stack.top());
- emit backwardAvailable(true);
- emit forwardAvailable(!d->forwardStack.isEmpty());
- emit historyChanged();
-}
-
-/*!
- Changes the document displayed to be the first document from
- the history.
-*/
-void QTextBrowser::home()
-{
- Q_D(QTextBrowser);
- if (d->home.isValid())
- setSource(d->home);
-}
-
-/*!
- The event \a ev is used to provide the following keyboard shortcuts:
- \table
- \header \i Keypress \i Action
- \row \i Alt+Left Arrow \i \l backward()
- \row \i Alt+Right Arrow \i \l forward()
- \row \i Alt+Up Arrow \i \l home()
- \endtable
-*/
-void QTextBrowser::keyPressEvent(QKeyEvent *ev)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- Q_D(QTextBrowser);
- switch (ev->key()) {
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus()) {
- setEditFocus(true);
- return;
- } else {
- QTextCursor cursor = d->control->textCursor();
- QTextCharFormat charFmt = cursor.charFormat();
- if (!cursor.hasSelection() || charFmt.anchorHref().isEmpty()) {
- ev->accept();
- return;
- }
- }
- }
- break;
- case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled()) {
- if (hasEditFocus()) {
- setEditFocus(false);
- ev->accept();
- return;
- }
- }
- QTextEdit::keyPressEvent(ev);
- return;
- default:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
- ev->ignore();
- return;
- }
- }
-#endif
-
- if (ev->modifiers() & Qt::AltModifier) {
- switch (ev->key()) {
- case Qt::Key_Right:
- forward();
- ev->accept();
- return;
- case Qt::Key_Left:
- backward();
- ev->accept();
- return;
- case Qt::Key_Up:
- home();
- ev->accept();
- return;
- }
- }
-#ifdef QT_KEYPAD_NAVIGATION
- else {
- if (ev->key() == Qt::Key_Up) {
- d->keypadMove(false);
- return;
- } else if (ev->key() == Qt::Key_Down) {
- d->keypadMove(true);
- return;
- }
- }
-#endif
- QTextEdit::keyPressEvent(ev);
-}
-
-/*!
- \reimp
-*/
-void QTextBrowser::mouseMoveEvent(QMouseEvent *e)
-{
- QTextEdit::mouseMoveEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QTextBrowser::mousePressEvent(QMouseEvent *e)
-{
- QTextEdit::mousePressEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QTextBrowser::mouseReleaseEvent(QMouseEvent *e)
-{
- QTextEdit::mouseReleaseEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QTextBrowser::focusOutEvent(QFocusEvent *ev)
-{
-#ifndef QT_NO_CURSOR
- Q_D(QTextBrowser);
- d->viewport->setCursor((!(d->control->textInteractionFlags() & Qt::TextEditable)) ? d->oldCursor : Qt::IBeamCursor);
-#endif
- QTextEdit::focusOutEvent(ev);
-}
-
-/*!
- \reimp
-*/
-bool QTextBrowser::focusNextPrevChild(bool next)
-{
- Q_D(QTextBrowser);
- if (d->control->setFocusToNextOrPreviousAnchor(next)) {
-#ifdef QT_KEYPAD_NAVIGATION
- // Might need to synthesize a highlight event.
- if (d->prevFocus != d->control->textCursor() && d->control->textCursor().hasSelection()) {
- const QString href = d->control->anchorAtCursor();
- QUrl url = d->resolveUrl(href);
- emit highlighted(url);
- emit highlighted(url.toString());
- }
- d->prevFocus = d->control->textCursor();
-#endif
- return true;
- } else {
-#ifdef QT_KEYPAD_NAVIGATION
- // We assume we have no highlight now.
- emit highlighted(QUrl());
- emit highlighted(QString());
-#endif
- }
- return QTextEdit::focusNextPrevChild(next);
-}
-
-/*!
- \reimp
-*/
-void QTextBrowser::paintEvent(QPaintEvent *e)
-{
- Q_D(QTextBrowser);
- QPainter p(d->viewport);
- d->paint(&p, e);
-}
-
-/*!
- This function is called when the document is loaded and for
- each image in the document. The \a type indicates the type of resource
- to be loaded. An invalid QVariant is returned if the resource cannot be
- loaded.
-
- The default implementation ignores \a type and tries to locate
- the resources by interpreting \a name as a file name. If it is
- not an absolute path it tries to find the file in the paths of
- the \l searchPaths property and in the same directory as the
- current source. On success, the result is a QVariant that stores
- a QByteArray with the contents of the file.
-
- If you reimplement this function, you can return other QVariant
- types. The table below shows which variant types are supported
- depending on the resource type:
-
- \table
- \header \i ResourceType \i QVariant::Type
- \row \i QTextDocument::HtmlResource \i QString or QByteArray
- \row \i QTextDocument::ImageResource \i QImage, QPixmap or QByteArray
- \row \i QTextDocument::StyleSheetResource \i QString or QByteArray
- \endtable
-*/
-QVariant QTextBrowser::loadResource(int /*type*/, const QUrl &name)
-{
- Q_D(QTextBrowser);
-
- QByteArray data;
- QString fileName = d->findFile(d->resolveUrl(name));
- QFile f(fileName);
- if (f.open(QFile::ReadOnly)) {
- data = f.readAll();
- f.close();
- } else {
- return QVariant();
- }
-
- return data;
-}
-
-/*!
- \since 4.2
-
- Returns true if the text browser can go backward in the document history
- using backward().
-
- \sa backwardAvailable(), backward()
-*/
-bool QTextBrowser::isBackwardAvailable() const
-{
- Q_D(const QTextBrowser);
- return d->stack.count() > 1;
-}
-
-/*!
- \since 4.2
-
- Returns true if the text browser can go forward in the document history
- using forward().
-
- \sa forwardAvailable(), forward()
-*/
-bool QTextBrowser::isForwardAvailable() const
-{
- Q_D(const QTextBrowser);
- return !d->forwardStack.isEmpty();
-}
-
-/*!
- \since 4.2
-
- Clears the history of visited documents and disables the forward and
- backward navigation.
-
- \sa backward(), forward()
-*/
-void QTextBrowser::clearHistory()
-{
- Q_D(QTextBrowser);
- d->forwardStack.clear();
- if (!d->stack.isEmpty()) {
- QTextBrowserPrivate::HistoryEntry historyEntry = d->stack.top();
- d->stack.resize(0);
- d->stack.push(historyEntry);
- d->home = historyEntry.url;
- }
- emit forwardAvailable(false);
- emit backwardAvailable(false);
- emit historyChanged();
-}
-
-/*!
- Returns the url of the HistoryItem.
-
- \table
- \header \i Input \i Return
- \row \i \a{i} < 0 \i \l backward() history
- \row \i\a{i} == 0 \i current, see QTextBrowser::source()
- \row \i \a{i} > 0 \i \l forward() history
- \endtable
-
- \since 4.4
-*/
-QUrl QTextBrowser::historyUrl(int i) const
-{
- Q_D(const QTextBrowser);
- return d->history(i).url;
-}
-
-/*!
- Returns the documentTitle() of the HistoryItem.
-
- \table
- \header \i Input \i Return
- \row \i \a{i} < 0 \i \l backward() history
- \row \i \a{i} == 0 \i current, see QTextBrowser::source()
- \row \i \a{i} > 0 \i \l forward() history
- \endtable
-
- \snippet doc/src/snippets/code/src_gui_widgets_qtextbrowser.cpp 0
-
- \since 4.4
-*/
-QString QTextBrowser::historyTitle(int i) const
-{
- Q_D(const QTextBrowser);
- return d->history(i).title;
-}
-
-
-/*!
- Returns the number of locations forward in the history.
-
- \since 4.4
-*/
-int QTextBrowser::forwardHistoryCount() const
-{
- Q_D(const QTextBrowser);
- return d->forwardStack.count();
-}
-
-/*!
- Returns the number of locations backward in the history.
-
- \since 4.4
-*/
-int QTextBrowser::backwardHistoryCount() const
-{
- Q_D(const QTextBrowser);
- return d->stack.count()-1;
-}
-
-/*!
- \property QTextBrowser::openExternalLinks
- \since 4.2
-
- Specifies whether QTextBrowser should automatically open links to external
- sources using QDesktopServices::openUrl() instead of emitting the
- anchorClicked signal. Links are considered external if their scheme is
- neither file or qrc.
-
- The default value is false.
-*/
-bool QTextBrowser::openExternalLinks() const
-{
- Q_D(const QTextBrowser);
- return d->openExternalLinks;
-}
-
-void QTextBrowser::setOpenExternalLinks(bool open)
-{
- Q_D(QTextBrowser);
- d->openExternalLinks = open;
-}
-
-/*!
- \property QTextBrowser::openLinks
- \since 4.3
-
- This property specifies whether QTextBrowser should automatically open links the user tries to
- activate by mouse or keyboard.
-
- Regardless of the value of this property the anchorClicked signal is always emitted.
-
- The default value is true.
-*/
-
-bool QTextBrowser::openLinks() const
-{
- Q_D(const QTextBrowser);
- return d->openLinks;
-}
-
-void QTextBrowser::setOpenLinks(bool open)
-{
- Q_D(QTextBrowser);
- d->openLinks = open;
-}
-
-/*! \reimp */
-bool QTextBrowser::event(QEvent *e)
-{
- return QTextEdit::event(e);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtextbrowser.cpp"
-
-#endif // QT_NO_TEXTBROWSER
diff --git a/src/gui/widgets/qtextbrowser.h b/src/gui/widgets/qtextbrowser.h
deleted file mode 100644
index a30ce4d705..0000000000
--- a/src/gui/widgets/qtextbrowser.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** 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 QTEXTBROWSER_H
-#define QTEXTBROWSER_H
-
-#include <QtGui/qtextedit.h>
-#include <QtCore/qurl.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TEXTBROWSER
-
-class QTextBrowserPrivate;
-
-class Q_GUI_EXPORT QTextBrowser : public QTextEdit
-{
- Q_OBJECT
-
- Q_PROPERTY(QUrl source READ source WRITE setSource)
- Q_OVERRIDE(bool modified SCRIPTABLE false)
- Q_OVERRIDE(bool readOnly DESIGNABLE false SCRIPTABLE false)
- Q_OVERRIDE(bool undoRedoEnabled DESIGNABLE false SCRIPTABLE false)
- Q_PROPERTY(QStringList searchPaths READ searchPaths WRITE setSearchPaths)
- Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
- Q_PROPERTY(bool openLinks READ openLinks WRITE setOpenLinks)
-
-public:
- explicit QTextBrowser(QWidget* parent = 0);
- virtual ~QTextBrowser();
-
- QUrl source() const;
-
- QStringList searchPaths() const;
- void setSearchPaths(const QStringList &paths);
-
- virtual QVariant loadResource(int type, const QUrl &name);
-
- bool isBackwardAvailable() const;
- bool isForwardAvailable() const;
- void clearHistory();
- QString historyTitle(int) const;
- QUrl historyUrl(int) const;
- int backwardHistoryCount() const;
- int forwardHistoryCount() const;
-
- bool openExternalLinks() const;
- void setOpenExternalLinks(bool open);
-
- bool openLinks() const;
- void setOpenLinks(bool open);
-
-public Q_SLOTS:
- virtual void setSource(const QUrl &name);
- virtual void backward();
- virtual void forward();
- virtual void home();
- virtual void reload();
-
-Q_SIGNALS:
- void backwardAvailable(bool);
- void forwardAvailable(bool);
- void historyChanged();
- void sourceChanged(const QUrl &);
- void highlighted(const QUrl &);
- void highlighted(const QString &);
- void anchorClicked(const QUrl &);
-
-protected:
- bool event(QEvent *e);
- virtual void keyPressEvent(QKeyEvent *ev);
- virtual void mouseMoveEvent(QMouseEvent *ev);
- virtual void mousePressEvent(QMouseEvent *ev);
- virtual void mouseReleaseEvent(QMouseEvent *ev);
- virtual void focusOutEvent(QFocusEvent *ev);
- virtual bool focusNextPrevChild(bool next);
- virtual void paintEvent(QPaintEvent *e);
-
-#if defined(QT3_SUPPORT)
-public:
- QT3_SUPPORT_CONSTRUCTOR QTextBrowser(QWidget *parent, const char *name);
-#endif
-
-private:
- Q_DISABLE_COPY(QTextBrowser)
- Q_DECLARE_PRIVATE(QTextBrowser)
- Q_PRIVATE_SLOT(d_func(), void _q_documentModified())
- Q_PRIVATE_SLOT(d_func(), void _q_activateAnchor(const QString &))
- Q_PRIVATE_SLOT(d_func(), void _q_highlightLink(const QString &))
-};
-
-#endif // QT_NO_TEXTBROWSER
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTEXTBROWSER_H
diff --git a/src/gui/widgets/qtextedit.cpp b/src/gui/widgets/qtextedit.cpp
deleted file mode 100644
index ff924bf377..0000000000
--- a/src/gui/widgets/qtextedit.cpp
+++ /dev/null
@@ -1,2811 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtextedit_p.h"
-#include "qlineedit.h"
-#include "qtextbrowser.h"
-
-#ifndef QT_NO_TEXTEDIT
-#include <qfont.h>
-#include <qpainter.h>
-#include <qevent.h>
-#include <qdebug.h>
-#include <qmime.h>
-#include <qdrag.h>
-#include <qclipboard.h>
-#include <qmenu.h>
-#include <qstyle.h>
-#include <qtimer.h>
-#include "private/qtextdocumentlayout_p.h"
-#include "qtextdocument.h"
-#include "private/qtextdocument_p.h"
-#include "qtextlist.h"
-#include "private/qtextcontrol_p.h"
-
-#include <qtextformat.h>
-#include <qdatetime.h>
-#include <qapplication.h>
-#include <limits.h>
-#include <qtexttable.h>
-#include <qvariant.h>
-
-#include <qinputcontext.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-
-#ifndef QT_NO_TEXTEDIT
-static inline bool shouldEnableInputMethod(QTextEdit *textedit)
-{
- return !textedit->isReadOnly();
-}
-
-class QTextEditControl : public QTextControl
-{
-public:
- inline QTextEditControl(QObject *parent) : QTextControl(parent) {}
-
- virtual QMimeData *createMimeDataFromSelection() const {
- QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
- if (!ed)
- return QTextControl::createMimeDataFromSelection();
- return ed->createMimeDataFromSelection();
- }
- virtual bool canInsertFromMimeData(const QMimeData *source) const {
- QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
- if (!ed)
- return QTextControl::canInsertFromMimeData(source);
- return ed->canInsertFromMimeData(source);
- }
- virtual void insertFromMimeData(const QMimeData *source) {
- QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
- if (!ed)
- QTextControl::insertFromMimeData(source);
- else
- ed->insertFromMimeData(source);
- }
-};
-
-QTextEditPrivate::QTextEditPrivate()
- : control(0),
- autoFormatting(QTextEdit::AutoNone), tabChangesFocus(false),
- lineWrap(QTextEdit::WidgetWidth), lineWrapColumnOrWidth(0),
- wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), clickCausedFocus(0),
- textFormat(Qt::AutoText)
-{
- ignoreAutomaticScrollbarAdjustment = false;
- preferRichText = false;
- showCursorOnInitialShow = true;
- inDrag = false;
-}
-
-void QTextEditPrivate::createAutoBulletList()
-{
- QTextCursor cursor = control->textCursor();
- cursor.beginEditBlock();
-
- QTextBlockFormat blockFmt = cursor.blockFormat();
-
- QTextListFormat listFmt;
- listFmt.setStyle(QTextListFormat::ListDisc);
- listFmt.setIndent(blockFmt.indent() + 1);
-
- blockFmt.setIndent(0);
- cursor.setBlockFormat(blockFmt);
-
- cursor.createList(listFmt);
-
- cursor.endEditBlock();
- control->setTextCursor(cursor);
-}
-
-void QTextEditPrivate::init(const QString &html)
-{
- Q_Q(QTextEdit);
- control = new QTextEditControl(q);
- control->setPalette(q->palette());
-
- QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));
- QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));
- QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));
- QObject::connect(control, SIGNAL(visibilityRequest(QRectF)), q, SLOT(_q_ensureVisible(QRectF)));
- QObject::connect(control, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
- q, SLOT(_q_currentCharFormatChanged(QTextCharFormat)));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));
- QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
- QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
- QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
- QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
- QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorPositionChanged()));
-
- QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));
-
- QTextDocument *doc = control->document();
- // set a null page size initially to avoid any relayouting until the textedit
- // is shown. relayoutDocument() will take care of setting the page size to the
- // viewport dimensions later.
- doc->setPageSize(QSize(0, 0));
- doc->documentLayout()->setPaintDevice(viewport);
- doc->setDefaultFont(q->font());
- doc->setUndoRedoEnabled(false); // flush undo buffer.
- doc->setUndoRedoEnabled(true);
-
- if (!html.isEmpty())
- control->setHtml(html);
-
- hbar->setSingleStep(20);
- vbar->setSingleStep(20);
-
- viewport->setBackgroundRole(QPalette::Base);
- q->setAcceptDrops(true);
- q->setFocusPolicy(Qt::WheelFocus);
- q->setAttribute(Qt::WA_KeyCompression);
- q->setAttribute(Qt::WA_InputMethodEnabled);
-
-#ifndef QT_NO_CURSOR
- viewport->setCursor(Qt::IBeamCursor);
-#endif
-#ifdef Q_WS_WIN
- setSingleFingerPanEnabled(true);
-#endif
-}
-
-void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
-{
- if (!contentsRect.isValid()) {
- viewport->update();
- return;
- }
- const int xOffset = horizontalOffset();
- const int yOffset = verticalOffset();
- const QRectF visibleRect(xOffset, yOffset, viewport->width(), viewport->height());
-
- QRect r = contentsRect.intersected(visibleRect).toAlignedRect();
- if (r.isEmpty())
- return;
-
- r.translate(-xOffset, -yOffset);
- viewport->update(r);
-}
-
-void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
-{
- QTextCursor cursor = control->textCursor();
- bool moved = false;
- qreal lastY = control->cursorRect(cursor).top();
- qreal distance = 0;
- // move using movePosition to keep the cursor's x
- do {
- qreal y = control->cursorRect(cursor).top();
- distance += qAbs(y - lastY);
- lastY = y;
- moved = cursor.movePosition(op, moveMode);
- } while (moved && distance < viewport->height());
-
- if (moved) {
- if (op == QTextCursor::Up) {
- cursor.movePosition(QTextCursor::Down, moveMode);
- vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
- } else {
- cursor.movePosition(QTextCursor::Up, moveMode);
- vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
- }
- }
- control->setTextCursor(cursor);
-}
-
-#ifndef QT_NO_SCROLLBAR
-static QSize documentSize(QTextControl *control)
-{
- QTextDocument *doc = control->document();
- QAbstractTextDocumentLayout *layout = doc->documentLayout();
-
- QSize docSize;
-
- if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
- docSize = tlayout->dynamicDocumentSize().toSize();
- int percentageDone = tlayout->layoutStatus();
- // extrapolate height
- if (percentageDone > 0)
- docSize.setHeight(docSize.height() * 100 / percentageDone);
- } else {
- docSize = layout->documentSize().toSize();
- }
-
- return docSize;
-}
-
-void QTextEditPrivate::_q_adjustScrollbars()
-{
- if (ignoreAutomaticScrollbarAdjustment)
- return;
- ignoreAutomaticScrollbarAdjustment = true; // avoid recursion, #106108
-
- QSize viewportSize = viewport->size();
- QSize docSize = documentSize(control);
-
- // due to the recursion guard we have to repeat this step a few times,
- // as adding/removing a scroll bar will cause the document or viewport
- // size to change
- // ideally we should loop until the viewport size and doc size stabilize,
- // but in corner cases they might fluctuate, so we need to limit the
- // number of iterations
- for (int i = 0; i < 4; ++i) {
- hbar->setRange(0, docSize.width() - viewportSize.width());
- hbar->setPageStep(viewportSize.width());
-
- vbar->setRange(0, docSize.height() - viewportSize.height());
- vbar->setPageStep(viewportSize.height());
-
- // if we are in left-to-right mode widening the document due to
- // lazy layouting does not require a repaint. If in right-to-left
- // the scroll bar has the value zero and it visually has the maximum
- // value (it is visually at the right), then widening the document
- // keeps it at value zero but visually adjusts it to the new maximum
- // on the right, hence we need an update.
- if (q_func()->isRightToLeft())
- viewport->update();
-
- _q_showOrHideScrollBars();
-
- const QSize oldViewportSize = viewportSize;
- const QSize oldDocSize = docSize;
-
- // make sure the document is layouted if the viewport width changes
- viewportSize = viewport->size();
- if (viewportSize.width() != oldViewportSize.width())
- relayoutDocument();
-
- docSize = documentSize(control);
- if (viewportSize == oldViewportSize && docSize == oldDocSize)
- break;
- }
- ignoreAutomaticScrollbarAdjustment = false;
-}
-#endif
-
-// rect is in content coordinates
-void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
-{
- const QRect rect = _rect.toRect();
- if ((vbar->isVisible() && vbar->maximum() < rect.bottom())
- || (hbar->isVisible() && hbar->maximum() < rect.right()))
- _q_adjustScrollbars();
- const int visibleWidth = viewport->width();
- const int visibleHeight = viewport->height();
- const bool rtl = q_func()->isRightToLeft();
-
- if (rect.x() < horizontalOffset()) {
- if (rtl)
- hbar->setValue(hbar->maximum() - rect.x());
- else
- hbar->setValue(rect.x());
- } else if (rect.x() + rect.width() > horizontalOffset() + visibleWidth) {
- if (rtl)
- hbar->setValue(hbar->maximum() - (rect.x() + rect.width() - visibleWidth));
- else
- hbar->setValue(rect.x() + rect.width() - visibleWidth);
- }
-
- if (rect.y() < verticalOffset())
- vbar->setValue(rect.y());
- else if (rect.y() + rect.height() > verticalOffset() + visibleHeight)
- vbar->setValue(rect.y() + rect.height() - visibleHeight);
-}
-
-/*!
- \class QTextEdit
- \brief The QTextEdit class provides a widget that is used to edit and display
- both plain and rich text.
-
- \ingroup richtext-processing
-
-
- \tableofcontents
-
- \section1 Introduction and Concepts
-
- QTextEdit is an advanced WYSIWYG viewer/editor supporting rich
- text formatting using HTML-style tags. It is optimized to handle
- large documents and to respond quickly to user input.
-
- QTextEdit works on paragraphs and characters. A paragraph is a
- formatted string which is word-wrapped to fit into the width of
- the widget. By default when reading plain text, one newline
- signifies a paragraph. A document consists of zero or more
- paragraphs. The words in the paragraph are aligned in accordance
- with the paragraph's alignment. Paragraphs are separated by hard
- line breaks. Each character within a paragraph has its own
- attributes, for example, font and color.
-
- QTextEdit can display images, lists and tables. If the text is
- too large to view within the text edit's viewport, scroll bars will
- appear. The text edit can load both plain text and HTML files (a
- subset of HTML 3.2 and 4).
-
- If you just need to display a small piece of rich text use QLabel.
-
- The rich text support in Qt is designed to provide a fast, portable and
- efficient way to add reasonable online help facilities to
- applications, and to provide a basis for rich text editors. If
- you find the HTML support insufficient for your needs you may consider
- the use of QtWebKit, which provides a full-featured web browser
- widget.
-
- The shape of the mouse cursor on a QTextEdit is Qt::IBeamCursor by default.
- It can be changed through the viewport()'s cursor property.
-
- \section1 Using QTextEdit as a Display Widget
-
- QTextEdit can display a large HTML subset, including tables and
- images.
-
- The text is set or replaced using setHtml() which deletes any
- existing text and replaces it with the text passed in the
- setHtml() call. If you call setHtml() with legacy HTML, and then
- call toHtml(), the text that is returned may have different markup,
- but will render the same. The entire text can be deleted with clear().
-
- Text itself can be inserted using the QTextCursor class or using the
- convenience functions insertHtml(), insertPlainText(), append() or
- paste(). QTextCursor is also able to insert complex objects like tables
- or lists into the document, and it deals with creating selections
- and applying changes to selected text.
-
- By default the text edit wraps words at whitespace to fit within
- the text edit widget. The setLineWrapMode() function is used to
- specify the kind of line wrap you want, or \l NoWrap if you don't
- want any wrapping. Call setLineWrapMode() to set a fixed pixel width
- \l FixedPixelWidth, or character column (e.g. 80 column) \l
- FixedColumnWidth with the pixels or columns specified with
- setLineWrapColumnOrWidth(). If you use word wrap to the widget's width
- \l WidgetWidth, you can specify whether to break on whitespace or
- anywhere with setWordWrapMode().
-
- The find() function can be used to find and select a given string
- within the text.
-
- If you want to limit the total number of paragraphs in a QTextEdit,
- as it is for example open useful in a log viewer, then you can use
- QTextDocument's maximumBlockCount property for that.
-
- \section2 Read-only Key Bindings
-
- When QTextEdit is used read-only the key bindings are limited to
- navigation, and text may only be selected with the mouse:
- \table
- \header \i Keypresses \i Action
- \row \i Up \i Moves one line up.
- \row \i Down \i Moves one line down.
- \row \i Left \i Moves one character to the left.
- \row \i Right \i Moves one character to the right.
- \row \i PageUp \i Moves one (viewport) page up.
- \row \i PageDown \i Moves one (viewport) page down.
- \row \i Home \i Moves to the beginning of the text.
- \row \i End \i Moves to the end of the text.
- \row \i Alt+Wheel
- \i Scrolls the page horizontally (the Wheel is the mouse wheel).
- \row \i Ctrl+Wheel \i Zooms the text.
- \row \i Ctrl+A \i Selects all text.
- \endtable
-
- The text edit may be able to provide some meta-information. For
- example, the documentTitle() function will return the text from
- within HTML \c{<title>} tags.
-
- \section1 Using QTextEdit as an Editor
-
- All the information about using QTextEdit as a display widget also
- applies here.
-
- The current char format's attributes are set with setFontItalic(),
- setFontWeight(), setFontUnderline(), setFontFamily(),
- setFontPointSize(), setTextColor() and setCurrentFont(). The current
- paragraph's alignment is set with setAlignment().
-
- Selection of text is handled by the QTextCursor class, which provides
- functionality for creating selections, retrieving the text contents or
- deleting selections. You can retrieve the object that corresponds with
- the user-visible cursor using the textCursor() method. If you want to set
- a selection in QTextEdit just create one on a QTextCursor object and
- then make that cursor the visible cursor using setTextCursor(). The selection
- can be copied to the clipboard with copy(), or cut to the clipboard with
- cut(). The entire text can be selected using selectAll().
-
- When the cursor is moved and the underlying formatting attributes change,
- the currentCharFormatChanged() signal is emitted to reflect the new attributes
- at the new cursor position.
-
- QTextEdit holds a QTextDocument object which can be retrieved using the
- document() method. You can also set your own document object using setDocument().
- QTextDocument emits a textChanged() signal if the text changes and it also
- provides a isModified() function which will return true if the text has been
- modified since it was either loaded or since the last call to setModified
- with false as argument. In addition it provides methods for undo and redo.
-
- \section2 Drag and Drop
-
- QTextEdit also supports custom drag and drop behavior. By default,
- QTextEdit will insert plain text, HTML and rich text when the user drops
- data of these MIME types onto a document. Reimplement
- canInsertFromMimeData() and insertFromMimeData() to add support for
- additional MIME types.
-
- For example, to allow the user to drag and drop an image onto a QTextEdit,
- you could the implement these functions in the following way:
-
- \snippet doc/src/snippets/textdocument-imagedrop/textedit.cpp 0
-
- We add support for image MIME types by returning true. For all other
- MIME types, we use the default implementation.
-
- \snippet doc/src/snippets/textdocument-imagedrop/textedit.cpp 1
-
- We unpack the image from the QVariant held by the MIME source and insert
- it into the document as a resource.
-
- \section2 Editing Key Bindings
-
- The list of key bindings which are implemented for editing:
- \table
- \header \i Keypresses \i Action
- \row \i Backspace \i Deletes the character to the left of the cursor.
- \row \i Delete \i Deletes the character to the right of the cursor.
- \row \i Ctrl+C \i Copy the selected text to the clipboard.
- \row \i Ctrl+Insert \i Copy the selected text to the clipboard.
- \row \i Ctrl+K \i Deletes to the end of the line.
- \row \i Ctrl+V \i Pastes the clipboard text into text edit.
- \row \i Shift+Insert \i Pastes the clipboard text into text edit.
- \row \i Ctrl+X \i Deletes the selected text and copies it to the clipboard.
- \row \i Shift+Delete \i Deletes the selected text and copies it to the clipboard.
- \row \i Ctrl+Z \i Undoes the last operation.
- \row \i Ctrl+Y \i Redoes the last operation.
- \row \i Left \i Moves the cursor one character to the left.
- \row \i Ctrl+Left \i Moves the cursor one word to the left.
- \row \i Right \i Moves the cursor one character to the right.
- \row \i Ctrl+Right \i Moves the cursor one word to the right.
- \row \i Up \i Moves the cursor one line up.
- \row \i Down \i Moves the cursor one line down.
- \row \i PageUp \i Moves the cursor one page up.
- \row \i PageDown \i Moves the cursor one page down.
- \row \i Home \i Moves the cursor to the beginning of the line.
- \row \i Ctrl+Home \i Moves the cursor to the beginning of the text.
- \row \i End \i Moves the cursor to the end of the line.
- \row \i Ctrl+End \i Moves the cursor to the end of the text.
- \row \i Alt+Wheel \i Scrolls the page horizontally (the Wheel is the mouse wheel).
- \endtable
-
- To select (mark) text hold down the Shift key whilst pressing one
- of the movement keystrokes, for example, \e{Shift+Right}
- will select the character to the right, and \e{Shift+Ctrl+Right} will select the word to the right, etc.
-
- \sa QTextDocument, QTextCursor, {Application Example},
- {Syntax Highlighter Example}, {Rich Text Processing}
-*/
-
-/*!
- \property QTextEdit::plainText
- \since 4.3
-
- This property gets and sets the text editor's contents as plain
- text. Previous contents are removed and undo/redo history is reset
- when the property is set.
-
- If the text edit has another content type, it will not be replaced
- by plain text if you call toPlainText(). The only exception to this
- is the non-break space, \e{nbsp;}, that will be converted into
- standard space.
-
- By default, for an editor with no contents, this property contains
- an empty string.
-
- \sa html
-*/
-
-/*!
- \property QTextEdit::undoRedoEnabled
- \brief whether undo and redo are enabled
-
- Users are only able to undo or redo actions if this property is
- true, and if there is an action that can be undone (or redone).
-*/
-
-/*!
- \enum QTextEdit::LineWrapMode
-
- \value NoWrap
- \value WidgetWidth
- \value FixedPixelWidth
- \value FixedColumnWidth
-*/
-
-/*!
- \enum QTextEdit::AutoFormattingFlag
-
- \value AutoNone Don't do any automatic formatting.
- \value AutoBulletList Automatically create bullet lists (e.g. when
- the user enters an asterisk ('*') in the left most column, or
- presses Enter in an existing list item.
- \value AutoAll Apply all automatic formatting. Currently only
- automatic bullet lists are supported.
-*/
-
-#ifdef QT3_SUPPORT
-/*!
- \enum QTextEdit::CursorAction
- \compat
-
- \value MoveBackward
- \value MoveForward
- \value MoveWordBackward
- \value MoveWordForward
- \value MoveUp
- \value MoveDown
- \value MoveLineStart
- \value MoveLineEnd
- \value MoveHome
- \value MoveEnd
- \value MovePageUp
- \value MovePageDown
-
- \omitvalue MovePgUp
- \omitvalue MovePgDown
-*/
-#endif
-
-/*!
- Constructs an empty QTextEdit with parent \a
- parent.
-*/
-QTextEdit::QTextEdit(QWidget *parent)
- : QAbstractScrollArea(*new QTextEditPrivate, parent)
-{
- Q_D(QTextEdit);
- d->init();
-}
-
-/*!
- \internal
-*/
-QTextEdit::QTextEdit(QTextEditPrivate &dd, QWidget *parent)
- : QAbstractScrollArea(dd, parent)
-{
- Q_D(QTextEdit);
- d->init();
-}
-
-/*!
- Constructs a QTextEdit with parent \a parent. The text edit will display
- the text \a text. The text is interpreted as html.
-*/
-QTextEdit::QTextEdit(const QString &text, QWidget *parent)
- : QAbstractScrollArea(*new QTextEditPrivate, parent)
-{
- Q_D(QTextEdit);
- d->init(text);
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QTextEdit::QTextEdit(QWidget *parent, const char *name)
- : QAbstractScrollArea(*new QTextEditPrivate, parent)
-{
- Q_D(QTextEdit);
- d->init();
- setObjectName(QString::fromAscii(name));
-}
-#endif
-
-
-/*!
- Destructor.
-*/
-QTextEdit::~QTextEdit()
-{
-}
-
-/*!
- Returns the point size of the font of the current format.
-
- \sa setFontFamily() setCurrentFont() setFontPointSize()
-*/
-qreal QTextEdit::fontPointSize() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().fontPointSize();
-}
-
-/*!
- Returns the font family of the current format.
-
- \sa setFontFamily() setCurrentFont() setFontPointSize()
-*/
-QString QTextEdit::fontFamily() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().fontFamily();
-}
-
-/*!
- Returns the font weight of the current format.
-
- \sa setFontWeight() setCurrentFont() setFontPointSize() QFont::Weight
-*/
-int QTextEdit::fontWeight() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().fontWeight();
-}
-
-/*!
- Returns true if the font of the current format is underlined; otherwise returns
- false.
-
- \sa setFontUnderline()
-*/
-bool QTextEdit::fontUnderline() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().fontUnderline();
-}
-
-/*!
- Returns true if the font of the current format is italic; otherwise returns
- false.
-
- \sa setFontItalic()
-*/
-bool QTextEdit::fontItalic() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().fontItalic();
-}
-
-/*!
- Returns the text color of the current format.
-
- \sa setTextColor()
-*/
-QColor QTextEdit::textColor() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().foreground().color();
-}
-
-/*!
- \since 4.4
-
- Returns the text background color of the current format.
-
- \sa setTextBackgroundColor()
-*/
-QColor QTextEdit::textBackgroundColor() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().background().color();
-}
-
-/*!
- Returns the font of the current format.
-
- \sa setCurrentFont() setFontFamily() setFontPointSize()
-*/
-QFont QTextEdit::currentFont() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().charFormat().font();
-}
-
-/*!
- Sets the alignment of the current paragraph to \a a. Valid
- alignments are Qt::AlignLeft, Qt::AlignRight,
- Qt::AlignJustify and Qt::AlignCenter (which centers
- horizontally).
-*/
-void QTextEdit::setAlignment(Qt::Alignment a)
-{
- Q_D(QTextEdit);
- QTextBlockFormat fmt;
- fmt.setAlignment(a);
- QTextCursor cursor = d->control->textCursor();
- cursor.mergeBlockFormat(fmt);
- d->control->setTextCursor(cursor);
-}
-
-/*!
- Returns the alignment of the current paragraph.
-
- \sa setAlignment()
-*/
-Qt::Alignment QTextEdit::alignment() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor().blockFormat().alignment();
-}
-
-/*!
- Makes \a document the new document of the text editor.
-
- \note The editor \e{does not take ownership of the document} unless it
- is the document's parent object. The parent object of the provided document
- remains the owner of the object.
-
- The editor does not delete the current document, even if it is a child of the editor.
-
- \sa document()
-*/
-void QTextEdit::setDocument(QTextDocument *document)
-{
- Q_D(QTextEdit);
- d->control->setDocument(document);
- d->updateDefaultTextOption();
- d->relayoutDocument();
-}
-
-/*!
- Returns a pointer to the underlying document.
-
- \sa setDocument()
-*/
-QTextDocument *QTextEdit::document() const
-{
- Q_D(const QTextEdit);
- return d->control->document();
-}
-
-/*!
- Sets the visible \a cursor.
-*/
-void QTextEdit::setTextCursor(const QTextCursor &cursor)
-{
- Q_D(QTextEdit);
- d->control->setTextCursor(cursor);
-}
-
-/*!
- Returns a copy of the QTextCursor that represents the currently visible cursor.
- Note that changes on the returned cursor do not affect QTextEdit's cursor; use
- setTextCursor() to update the visible cursor.
- */
-QTextCursor QTextEdit::textCursor() const
-{
- Q_D(const QTextEdit);
- return d->control->textCursor();
-}
-
-/*!
- Sets the font family of the current format to \a fontFamily.
-
- \sa fontFamily() setCurrentFont()
-*/
-void QTextEdit::setFontFamily(const QString &fontFamily)
-{
- QTextCharFormat fmt;
- fmt.setFontFamily(fontFamily);
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- Sets the point size of the current format to \a s.
-
- Note that if \a s is zero or negative, the behavior of this
- function is not defined.
-
- \sa fontPointSize() setCurrentFont() setFontFamily()
-*/
-void QTextEdit::setFontPointSize(qreal s)
-{
- QTextCharFormat fmt;
- fmt.setFontPointSize(s);
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- \fn void QTextEdit::setFontWeight(int weight)
-
- Sets the font weight of the current format to the given \a weight,
- where the value used is in the range defined by the QFont::Weight
- enum.
-
- \sa fontWeight(), setCurrentFont(), setFontFamily()
-*/
-void QTextEdit::setFontWeight(int w)
-{
- QTextCharFormat fmt;
- fmt.setFontWeight(w);
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- If \a underline is true, sets the current format to underline;
- otherwise sets the current format to non-underline.
-
- \sa fontUnderline()
-*/
-void QTextEdit::setFontUnderline(bool underline)
-{
- QTextCharFormat fmt;
- fmt.setFontUnderline(underline);
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- If \a italic is true, sets the current format to italic;
- otherwise sets the current format to non-italic.
-
- \sa fontItalic()
-*/
-void QTextEdit::setFontItalic(bool italic)
-{
- QTextCharFormat fmt;
- fmt.setFontItalic(italic);
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- Sets the text color of the current format to \a c.
-
- \sa textColor()
-*/
-void QTextEdit::setTextColor(const QColor &c)
-{
- QTextCharFormat fmt;
- fmt.setForeground(QBrush(c));
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- \since 4.4
-
- Sets the text background color of the current format to \a c.
-
- \sa textBackgroundColor()
-*/
-void QTextEdit::setTextBackgroundColor(const QColor &c)
-{
- QTextCharFormat fmt;
- fmt.setBackground(QBrush(c));
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- Sets the font of the current format to \a f.
-
- \sa currentFont() setFontPointSize() setFontFamily()
-*/
-void QTextEdit::setCurrentFont(const QFont &f)
-{
- QTextCharFormat fmt;
- fmt.setFont(f);
- mergeCurrentCharFormat(fmt);
-}
-
-/*!
- \since 4.2
-
- Undoes the last operation.
-
- If there is no operation to undo, i.e. there is no undo step in
- the undo/redo history, nothing happens.
-
- \sa redo()
-*/
-void QTextEdit::undo()
-{
- Q_D(QTextEdit);
- d->control->undo();
-}
-
-void QTextEdit::redo()
-{
- Q_D(QTextEdit);
- d->control->redo();
-}
-
-/*!
- \fn void QTextEdit::undo() const
- \fn void QTextEdit::redo() const
- \overload
-
- Use the non-const overload instead.
-*/
-
-/*!
- \fn void QTextEdit::redo()
- \since 4.2
-
- Redoes the last operation.
-
- If there is no operation to redo, i.e. there is no redo step in
- the undo/redo history, nothing happens.
-
- \sa undo()
-*/
-
-#ifndef QT_NO_CLIPBOARD
-/*!
- Copies the selected text to the clipboard and deletes it from
- the text edit.
-
- If there is no selected text nothing happens.
-
- \sa copy() paste()
-*/
-
-void QTextEdit::cut()
-{
- Q_D(QTextEdit);
- d->control->cut();
-}
-
-/*!
- Copies any selected text to the clipboard.
-
- \sa copyAvailable()
-*/
-
-void QTextEdit::copy()
-{
- Q_D(QTextEdit);
- d->control->copy();
-}
-
-/*!
- Pastes the text from the clipboard into the text edit at the
- current cursor position.
-
- If there is no text in the clipboard nothing happens.
-
- To change the behavior of this function, i.e. to modify what
- QTextEdit can paste and how it is being pasted, reimplement the
- virtual canInsertFromMimeData() and insertFromMimeData()
- functions.
-
- \sa cut() copy()
-*/
-
-void QTextEdit::paste()
-{
- Q_D(QTextEdit);
- d->control->paste();
-}
-#endif
-
-/*!
- Deletes all the text in the text edit.
-
- Note that the undo/redo history is cleared by this function.
-
- \sa cut() setPlainText() setHtml()
-*/
-void QTextEdit::clear()
-{
- Q_D(QTextEdit);
- // clears and sets empty content
- d->control->clear();
-}
-
-
-/*!
- Selects all text.
-
- \sa copy() cut() textCursor()
- */
-void QTextEdit::selectAll()
-{
- Q_D(QTextEdit);
- d->control->selectAll();
-}
-
-/*! \internal
-*/
-bool QTextEdit::event(QEvent *e)
-{
- Q_D(QTextEdit);
-#ifndef QT_NO_CONTEXTMENU
- if (e->type() == QEvent::ContextMenu
- && static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
- Q_D(QTextEdit);
- ensureCursorVisible();
- const QPoint cursorPos = cursorRect().center();
- QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
- ce.setAccepted(e->isAccepted());
- const bool result = QAbstractScrollArea::event(&ce);
- e->setAccepted(ce.isAccepted());
- return result;
- } else if (e->type() == QEvent::ShortcutOverride
- || e->type() == QEvent::ToolTip) {
- d->sendControlEvent(e);
- }
-#endif // QT_NO_CONTEXTMENU
-#ifdef QT_KEYPAD_NAVIGATION
- if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
- if (QApplication::keypadNavigationEnabled())
- d->sendControlEvent(e);
- }
-#endif
- return QAbstractScrollArea::event(e);
-}
-
-/*! \internal
-*/
-
-void QTextEdit::timerEvent(QTimerEvent *e)
-{
- Q_D(QTextEdit);
- if (e->timerId() == d->autoScrollTimer.timerId()) {
- QRect visible = d->viewport->rect();
- QPoint pos;
- if (d->inDrag) {
- pos = d->autoScrollDragPos;
- visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
- -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
- } else {
- const QPoint globalPos = QCursor::pos();
- pos = d->viewport->mapFromGlobal(globalPos);
- QMouseEvent ev(QEvent::MouseMove, pos, globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
- mouseMoveEvent(&ev);
- }
- int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
- int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
- int delta = qMax(deltaX, deltaY);
- if (delta >= 0) {
- if (delta < 7)
- delta = 7;
- int timeout = 4900 / (delta * delta);
- d->autoScrollTimer.start(timeout, this);
-
- if (deltaY > 0)
- d->vbar->triggerAction(pos.y() < visible.center().y() ?
- QAbstractSlider::SliderSingleStepSub
- : QAbstractSlider::SliderSingleStepAdd);
- if (deltaX > 0)
- d->hbar->triggerAction(pos.x() < visible.center().x() ?
- QAbstractSlider::SliderSingleStepSub
- : QAbstractSlider::SliderSingleStepAdd);
- }
- }
-#ifdef QT_KEYPAD_NAVIGATION
- else if (e->timerId() == d->deleteAllTimer.timerId()) {
- d->deleteAllTimer.stop();
- clear();
- }
-#endif
-}
-
-/*!
- Changes the text of the text edit to the string \a text.
- Any previous text is removed.
-
- \a text is interpreted as plain text.
-
- Note that the undo/redo history is cleared by this function.
-
- \sa toPlainText()
-*/
-
-void QTextEdit::setPlainText(const QString &text)
-{
- Q_D(QTextEdit);
- d->control->setPlainText(text);
- d->preferRichText = false;
-}
-
-/*!
- \fn QString QTextEdit::toPlainText() const
-
- Returns the text of the text edit as plain text.
-
- \sa QTextEdit::setPlainText()
- */
-
-
-/*!
- \property QTextEdit::html
-
- This property provides an HTML interface to the text of the text edit.
-
- toHtml() returns the text of the text edit as html.
-
- setHtml() changes the text of the text edit. Any previous text is
- removed and the undo/redo history is cleared. The input text is
- interpreted as rich text in html format.
-
- \note It is the responsibility of the caller to make sure that the
- text is correctly decoded when a QString containing HTML is created
- and passed to setHtml().
-
- By default, for a newly-created, empty document, this property contains
- text to describe an HTML 4.0 document with no body text.
-
- \sa {Supported HTML Subset}, plainText
-*/
-
-#ifndef QT_NO_TEXTHTMLPARSER
-void QTextEdit::setHtml(const QString &text)
-{
- Q_D(QTextEdit);
- d->control->setHtml(text);
- d->preferRichText = true;
-}
-#endif
-
-/*! \reimp
-*/
-void QTextEdit::keyPressEvent(QKeyEvent *e)
-{
- Q_D(QTextEdit);
-
-#ifdef QT_KEYPAD_NAVIGATION
- switch (e->key()) {
- case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
- // code assumes linksaccessible + editable isn't meaningful
- if (d->control->textInteractionFlags() & Qt::TextEditable) {
- setEditFocus(!hasEditFocus());
- } else {
- if (!hasEditFocus())
- setEditFocus(true);
- else {
- QTextCursor cursor = d->control->textCursor();
- QTextCharFormat charFmt = cursor.charFormat();
- if (!(d->control->textInteractionFlags() & Qt::LinksAccessibleByKeyboard)
- || !cursor.hasSelection() || charFmt.anchorHref().isEmpty()) {
- e->accept();
- return;
- }
- }
- }
- }
- break;
- case Qt::Key_Back:
- case Qt::Key_No:
- if (!QApplication::keypadNavigationEnabled()
- || (QApplication::keypadNavigationEnabled() && !hasEditFocus())) {
- e->ignore();
- return;
- }
- break;
- default:
- if (QApplication::keypadNavigationEnabled()) {
- if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
- if (e->text()[0].isPrint())
- setEditFocus(true);
- else {
- e->ignore();
- return;
- }
- }
- }
- break;
- }
-#endif
-#ifndef QT_NO_SHORTCUT
-
- Qt::TextInteractionFlags tif = d->control->textInteractionFlags();
-
- if (tif & Qt::TextSelectableByKeyboard){
- if (e == QKeySequence::SelectPreviousPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
- return;
- } else if (e ==QKeySequence::SelectNextPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
- return;
- }
- }
- if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
- if (e == QKeySequence::MoveToPreviousPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
- return;
- } else if (e == QKeySequence::MoveToNextPage) {
- e->accept();
- d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
- return;
- }
- }
-
- if (!(tif & Qt::TextEditable)) {
- switch (e->key()) {
- case Qt::Key_Space:
- e->accept();
- if (e->modifiers() & Qt::ShiftModifier)
- d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
- else
- d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
- break;
- default:
- d->sendControlEvent(e);
- if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
- if (e->key() == Qt::Key_Home) {
- d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
- e->accept();
- } else if (e->key() == Qt::Key_End) {
- d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
- e->accept();
- }
- }
- if (!e->isAccepted()) {
- QAbstractScrollArea::keyPressEvent(e);
- }
- }
- return;
- }
-#endif // QT_NO_SHORTCUT
-
- {
- QTextCursor cursor = d->control->textCursor();
- const QString text = e->text();
- if (cursor.atBlockStart()
- && (d->autoFormatting & AutoBulletList)
- && (text.length() == 1)
- && (text.at(0) == QLatin1Char('-') || text.at(0) == QLatin1Char('*'))
- && (!cursor.currentList())) {
-
- d->createAutoBulletList();
- e->accept();
- return;
- }
- }
-
- d->sendControlEvent(e);
-#ifdef QT_KEYPAD_NAVIGATION
- if (!e->isAccepted()) {
- switch (e->key()) {
- case Qt::Key_Up:
- case Qt::Key_Down:
- if (QApplication::keypadNavigationEnabled()) {
- // Cursor position didn't change, so we want to leave
- // these keys to change focus.
- e->ignore();
- return;
- }
- break;
- case Qt::Key_Back:
- if (!e->isAutoRepeat()) {
- if (QApplication::keypadNavigationEnabled()) {
- if (document()->isEmpty() || !(d->control->textInteractionFlags() & Qt::TextEditable)) {
- setEditFocus(false);
- e->accept();
- } else if (!d->deleteAllTimer.isActive()) {
- e->accept();
- d->deleteAllTimer.start(750, this);
- }
- } else {
- e->ignore();
- return;
- }
- }
- break;
- default: break;
- }
- }
-#endif
-}
-
-/*! \reimp
-*/
-void QTextEdit::keyReleaseEvent(QKeyEvent *e)
-{
-#ifdef QT_KEYPAD_NAVIGATION
- Q_D(QTextEdit);
- if (QApplication::keypadNavigationEnabled()) {
- if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
- && d->deleteAllTimer.isActive()) {
- d->deleteAllTimer.stop();
- QTextCursor cursor = d->control->textCursor();
- QTextBlockFormat blockFmt = cursor.blockFormat();
-
- QTextList *list = cursor.currentList();
- if (list && cursor.atBlockStart()) {
- list->remove(cursor.block());
- } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
- blockFmt.setIndent(blockFmt.indent() - 1);
- cursor.setBlockFormat(blockFmt);
- } else {
- cursor.deletePreviousChar();
- }
- setTextCursor(cursor);
- e->accept();
- return;
- }
- }
-#endif
- e->ignore();
-}
-
-/*!
- Loads the resource specified by the given \a type and \a name.
-
- This function is an extension of QTextDocument::loadResource().
-
- \sa QTextDocument::loadResource()
-*/
-QVariant QTextEdit::loadResource(int type, const QUrl &name)
-{
- Q_UNUSED(type);
- Q_UNUSED(name);
- return QVariant();
-}
-
-/*! \reimp
-*/
-void QTextEdit::resizeEvent(QResizeEvent *e)
-{
- Q_D(QTextEdit);
-
- if (d->lineWrap == NoWrap) {
- QTextDocument *doc = d->control->document();
- QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
-
- if (!doc->pageSize().isNull()
- && alignmentProperty.type() == QVariant::Bool
- && !alignmentProperty.toBool()) {
-
- d->_q_adjustScrollbars();
- return;
- }
- }
-
- if (d->lineWrap != FixedPixelWidth
- && e->oldSize().width() != e->size().width())
- d->relayoutDocument();
- else
- d->_q_adjustScrollbars();
-}
-
-void QTextEditPrivate::relayoutDocument()
-{
- QTextDocument *doc = control->document();
- QAbstractTextDocumentLayout *layout = doc->documentLayout();
-
- if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
- if (lineWrap == QTextEdit::FixedColumnWidth)
- tlayout->setFixedColumnWidth(lineWrapColumnOrWidth);
- else
- tlayout->setFixedColumnWidth(-1);
- }
-
- QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout);
- QSize lastUsedSize;
- if (tlayout)
- lastUsedSize = tlayout->dynamicDocumentSize().toSize();
- else
- lastUsedSize = layout->documentSize().toSize();
-
- // ignore calls to _q_adjustScrollbars caused by an emission of the
- // usedSizeChanged() signal in the layout, as we're calling it
- // later on our own anyway (or deliberately not) .
- const bool oldIgnoreScrollbarAdjustment = ignoreAutomaticScrollbarAdjustment;
- ignoreAutomaticScrollbarAdjustment = true;
-
- int width = viewport->width();
- if (lineWrap == QTextEdit::FixedPixelWidth)
- width = lineWrapColumnOrWidth;
- else if (lineWrap == QTextEdit::NoWrap) {
- QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
- if (alignmentProperty.type() == QVariant::Bool && !alignmentProperty.toBool()) {
-
- width = 0;
- }
- }
-
- doc->setPageSize(QSize(width, -1));
- if (tlayout)
- tlayout->ensureLayouted(verticalOffset() + viewport->height());
-
- ignoreAutomaticScrollbarAdjustment = oldIgnoreScrollbarAdjustment;
-
- QSize usedSize;
- if (tlayout)
- usedSize = tlayout->dynamicDocumentSize().toSize();
- else
- usedSize = layout->documentSize().toSize();
-
- // this is an obscure situation in the layout that can happen:
- // if a character at the end of a line is the tallest one and therefore
- // influencing the total height of the line and the line right below it
- // is always taller though, then it can happen that if due to line breaking
- // that tall character wraps into the lower line the document not only shrinks
- // horizontally (causing the character to wrap in the first place) but also
- // vertically, because the original line is now smaller and the one below kept
- // its size. So a layout with less width _can_ take up less vertical space, too.
- // If the wider case causes a vertical scroll bar to appear and the narrower one
- // (narrower because the vertical scroll bar takes up horizontal space)) to disappear
- // again then we have an endless loop, as _q_adjustScrollBars sets new ranges on the
- // scroll bars, the QAbstractScrollArea will find out about it and try to show/hide
- // the scroll bars again. That's why we try to detect this case here and break out.
- //
- // (if you change this please also check the layoutingLoop() testcase in
- // QTextEdit's autotests)
- if (lastUsedSize.isValid()
- && !vbar->isHidden()
- && viewport->width() < lastUsedSize.width()
- && usedSize.height() < lastUsedSize.height()
- && usedSize.height() <= viewport->height())
- return;
-
- _q_adjustScrollbars();
-}
-
-void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
-{
- const int xOffset = horizontalOffset();
- const int yOffset = verticalOffset();
-
- QRect r = e->rect();
- p->translate(-xOffset, -yOffset);
- r.translate(xOffset, yOffset);
-
- QTextDocument *doc = control->document();
- QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout());
-
- // the layout might need to expand the root frame to
- // the viewport if NoWrap is set
- if (layout)
- layout->setViewport(viewport->rect());
-
- control->drawContents(p, r, q_func());
-
- if (layout)
- layout->setViewport(QRect());
-}
-
-/*! \fn void QTextEdit::paintEvent(QPaintEvent *event)
-
-This event handler can be reimplemented in a subclass to receive paint events passed in \a event.
-It is usually unnecessary to reimplement this function in a subclass of QTextEdit.
-
-\warning The underlying text document must not be modified from within a reimplementation
-of this function.
-*/
-void QTextEdit::paintEvent(QPaintEvent *e)
-{
- Q_D(QTextEdit);
- QPainter p(d->viewport);
- d->paint(&p, e);
-}
-
-void QTextEditPrivate::_q_currentCharFormatChanged(const QTextCharFormat &fmt)
-{
- Q_Q(QTextEdit);
- emit q->currentCharFormatChanged(fmt);
-#ifdef QT3_SUPPORT
- // compat signals
- emit q->currentFontChanged(fmt.font());
- emit q->currentColorChanged(fmt.foreground().color());
-#endif
-}
-
-void QTextEditPrivate::updateDefaultTextOption()
-{
- QTextDocument *doc = control->document();
-
- QTextOption opt = doc->defaultTextOption();
- QTextOption::WrapMode oldWrapMode = opt.wrapMode();
-
- if (lineWrap == QTextEdit::NoWrap)
- opt.setWrapMode(QTextOption::NoWrap);
- else
- opt.setWrapMode(wordWrap);
-
- if (opt.wrapMode() != oldWrapMode)
- doc->setDefaultTextOption(opt);
-}
-
-/*! \reimp
-*/
-void QTextEdit::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QTextEdit);
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
- setEditFocus(true);
-#endif
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QTextEdit::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QTextEdit);
- d->inDrag = false; // paranoia
- const QPoint pos = e->pos();
- d->sendControlEvent(e);
- if (!(e->buttons() & Qt::LeftButton))
- return;
- QRect visible = d->viewport->rect();
- if (visible.contains(pos))
- d->autoScrollTimer.stop();
- else if (!d->autoScrollTimer.isActive())
- d->autoScrollTimer.start(100, this);
-}
-
-/*! \reimp
-*/
-void QTextEdit::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QTextEdit);
- d->sendControlEvent(e);
- if (d->autoScrollTimer.isActive()) {
- d->autoScrollTimer.stop();
- ensureCursorVisible();
- }
- if (!isReadOnly() && rect().contains(e->pos()))
- d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
- d->clickCausedFocus = 0;
-}
-
-/*! \reimp
-*/
-void QTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
-{
- Q_D(QTextEdit);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-bool QTextEdit::focusNextPrevChild(bool next)
-{
- Q_D(const QTextEdit);
- if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
- return false;
- return QAbstractScrollArea::focusNextPrevChild(next);
-}
-
-#ifndef QT_NO_CONTEXTMENU
-/*!
- \fn void QTextEdit::contextMenuEvent(QContextMenuEvent *event)
-
- Shows the standard context menu created with createStandardContextMenu().
-
- If you do not want the text edit to have a context menu, you can set
- its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
- customize the context menu, reimplement this function. If you want
- to extend the standard context menu, reimplement this function, call
- createStandardContextMenu() and extend the menu returned.
-
- Information about the event is passed in the \a event object.
-
- \snippet doc/src/snippets/code/src_gui_widgets_qtextedit.cpp 0
-*/
-void QTextEdit::contextMenuEvent(QContextMenuEvent *e)
-{
- Q_D(QTextEdit);
- d->sendControlEvent(e);
-}
-#endif // QT_NO_CONTEXTMENU
-
-#ifndef QT_NO_DRAGANDDROP
-/*! \reimp
-*/
-void QTextEdit::dragEnterEvent(QDragEnterEvent *e)
-{
- Q_D(QTextEdit);
- d->inDrag = true;
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
-{
- Q_D(QTextEdit);
- d->inDrag = false;
- d->autoScrollTimer.stop();
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QTextEdit::dragMoveEvent(QDragMoveEvent *e)
-{
- Q_D(QTextEdit);
- d->autoScrollDragPos = e->pos();
- if (!d->autoScrollTimer.isActive())
- d->autoScrollTimer.start(100, this);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QTextEdit::dropEvent(QDropEvent *e)
-{
- Q_D(QTextEdit);
- d->inDrag = false;
- d->autoScrollTimer.stop();
- d->sendControlEvent(e);
-}
-
-#endif // QT_NO_DRAGANDDROP
-
-/*! \reimp
- */
-void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
-{
- Q_D(QTextEdit);
-#ifdef QT_KEYPAD_NAVIGATION
- if (d->control->textInteractionFlags() & Qt::TextEditable
- && QApplication::keypadNavigationEnabled()
- && !hasEditFocus())
- setEditFocus(true);
-#endif
- d->sendControlEvent(e);
- ensureCursorVisible();
-}
-
-/*!\reimp
-*/
-void QTextEdit::scrollContentsBy(int dx, int dy)
-{
- Q_D(QTextEdit);
- if (isRightToLeft())
- dx = -dx;
- d->viewport->scroll(dx, dy);
-}
-
-/*!\reimp
-*/
-QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
-{
- Q_D(const QTextEdit);
- QVariant v = d->control->inputMethodQuery(property);
- const QPoint offset(-d->horizontalOffset(), -d->verticalOffset());
- if (v.type() == QVariant::RectF)
- v = v.toRectF().toRect().translated(offset);
- else if (v.type() == QVariant::PointF)
- v = v.toPointF().toPoint() + offset;
- else if (v.type() == QVariant::Rect)
- v = v.toRect().translated(offset);
- else if (v.type() == QVariant::Point)
- v = v.toPoint() + offset;
- return v;
-}
-
-/*! \reimp
-*/
-void QTextEdit::focusInEvent(QFocusEvent *e)
-{
- Q_D(QTextEdit);
- if (e->reason() == Qt::MouseFocusReason) {
- d->clickCausedFocus = 1;
- }
- QAbstractScrollArea::focusInEvent(e);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QTextEdit::focusOutEvent(QFocusEvent *e)
-{
- Q_D(QTextEdit);
- QAbstractScrollArea::focusOutEvent(e);
- d->sendControlEvent(e);
-}
-
-/*! \reimp
-*/
-void QTextEdit::showEvent(QShowEvent *)
-{
- Q_D(QTextEdit);
- if (!d->anchorToScrollToWhenVisible.isEmpty()) {
- scrollToAnchor(d->anchorToScrollToWhenVisible);
- d->anchorToScrollToWhenVisible.clear();
- d->showCursorOnInitialShow = false;
- } else if (d->showCursorOnInitialShow) {
- d->showCursorOnInitialShow = false;
- ensureCursorVisible();
- }
-}
-
-/*! \reimp
-*/
-void QTextEdit::changeEvent(QEvent *e)
-{
- Q_D(QTextEdit);
- QAbstractScrollArea::changeEvent(e);
- if (e->type() == QEvent::ApplicationFontChange
- || e->type() == QEvent::FontChange) {
- d->control->document()->setDefaultFont(font());
- } else if(e->type() == QEvent::ActivationChange) {
- if (!isActiveWindow())
- d->autoScrollTimer.stop();
- } else if (e->type() == QEvent::EnabledChange) {
- e->setAccepted(isEnabled());
- d->control->setPalette(palette());
- d->sendControlEvent(e);
- } else if (e->type() == QEvent::PaletteChange) {
- d->control->setPalette(palette());
- } else if (e->type() == QEvent::LayoutDirectionChange) {
- d->sendControlEvent(e);
- }
-}
-
-/*! \reimp
-*/
-#ifndef QT_NO_WHEELEVENT
-void QTextEdit::wheelEvent(QWheelEvent *e)
-{
- Q_D(QTextEdit);
- if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
- if (e->modifiers() & Qt::ControlModifier) {
- const int delta = e->delta();
- if (delta < 0)
- zoomOut();
- else if (delta > 0)
- zoomIn();
- return;
- }
- }
- QAbstractScrollArea::wheelEvent(e);
- updateMicroFocus();
-}
-#endif
-
-#ifndef QT_NO_CONTEXTMENU
-/*! This function creates the standard context menu which is shown
- when the user clicks on the text edit with the right mouse
- button. It is called from the default contextMenuEvent() handler.
- The popup menu's ownership is transferred to the caller.
-
- We recommend that you use the createStandardContextMenu(QPoint) version instead
- which will enable the actions that are sensitive to where the user clicked.
-*/
-
-QMenu *QTextEdit::createStandardContextMenu()
-{
- Q_D(QTextEdit);
- return d->control->createStandardContextMenu(QPointF(), this);
-}
-
-/*!
- \since 4.4
- This function creates the standard context menu which is shown
- when the user clicks on the text edit with the right mouse
- button. It is called from the default contextMenuEvent() handler
- and it takes the \a position of where the mouse click was.
- This can enable actions that are sensitive to the position where the user clicked.
- The popup menu's ownership is transferred to the caller.
-*/
-
-QMenu *QTextEdit::createStandardContextMenu(const QPoint &position)
-{
- Q_D(QTextEdit);
- return d->control->createStandardContextMenu(position, this);
-}
-#endif // QT_NO_CONTEXTMENU
-
-/*!
- returns a QTextCursor at position \a pos (in viewport coordinates).
-*/
-QTextCursor QTextEdit::cursorForPosition(const QPoint &pos) const
-{
- Q_D(const QTextEdit);
- return d->control->cursorForPosition(d->mapToContents(pos));
-}
-
-/*!
- returns a rectangle (in viewport coordinates) that includes the
- \a cursor.
- */
-QRect QTextEdit::cursorRect(const QTextCursor &cursor) const
-{
- Q_D(const QTextEdit);
- if (cursor.isNull())
- return QRect();
-
- QRect r = d->control->cursorRect(cursor).toRect();
- r.translate(-d->horizontalOffset(),-d->verticalOffset());
- return r;
-}
-
-/*!
- returns a rectangle (in viewport coordinates) that includes the
- cursor of the text edit.
- */
-QRect QTextEdit::cursorRect() const
-{
- Q_D(const QTextEdit);
- QRect r = d->control->cursorRect().toRect();
- r.translate(-d->horizontalOffset(),-d->verticalOffset());
- return r;
-}
-
-
-/*!
- Returns the reference of the anchor at position \a pos, or an
- empty string if no anchor exists at that point.
-*/
-QString QTextEdit::anchorAt(const QPoint& pos) const
-{
- Q_D(const QTextEdit);
- return d->control->anchorAt(d->mapToContents(pos));
-}
-
-/*!
- \property QTextEdit::overwriteMode
- \since 4.1
- \brief whether text entered by the user will overwrite existing text
-
- As with many text editors, the text editor widget can be configured
- to insert or overwrite existing text with new text entered by the user.
-
- If this property is true, existing text is overwritten, character-for-character
- by new text; otherwise, text is inserted at the cursor position, displacing
- existing text.
-
- By default, this property is false (new text does not overwrite existing text).
-*/
-
-bool QTextEdit::overwriteMode() const
-{
- Q_D(const QTextEdit);
- return d->control->overwriteMode();
-}
-
-void QTextEdit::setOverwriteMode(bool overwrite)
-{
- Q_D(QTextEdit);
- d->control->setOverwriteMode(overwrite);
-}
-
-/*!
- \property QTextEdit::tabStopWidth
- \brief the tab stop width in pixels
- \since 4.1
-
- By default, this property contains a value of 80 pixels.
-*/
-
-int QTextEdit::tabStopWidth() const
-{
- Q_D(const QTextEdit);
- return qRound(d->control->document()->defaultTextOption().tabStop());
-}
-
-void QTextEdit::setTabStopWidth(int width)
-{
- Q_D(QTextEdit);
- QTextOption opt = d->control->document()->defaultTextOption();
- if (opt.tabStop() == width || width < 0)
- return;
- opt.setTabStop(width);
- d->control->document()->setDefaultTextOption(opt);
-}
-
-/*!
- \since 4.2
- \property QTextEdit::cursorWidth
-
- This property specifies the width of the cursor in pixels. The default value is 1.
-*/
-int QTextEdit::cursorWidth() const
-{
- Q_D(const QTextEdit);
- return d->control->cursorWidth();
-}
-
-void QTextEdit::setCursorWidth(int width)
-{
- Q_D(QTextEdit);
- d->control->setCursorWidth(width);
-}
-
-/*!
- \property QTextEdit::acceptRichText
- \brief whether the text edit accepts rich text insertions by the user
- \since 4.1
-
- When this propery is set to false text edit will accept only
- plain text input from the user. For example through clipboard or drag and drop.
-
- This property's default is true.
-*/
-
-bool QTextEdit::acceptRichText() const
-{
- Q_D(const QTextEdit);
- return d->control->acceptRichText();
-}
-
-void QTextEdit::setAcceptRichText(bool accept)
-{
- Q_D(QTextEdit);
- d->control->setAcceptRichText(accept);
-}
-
-/*!
- \class QTextEdit::ExtraSelection
- \since 4.2
- \brief The QTextEdit::ExtraSelection structure provides a way of specifying a
- character format for a given selection in a document
-*/
-
-/*!
- \variable QTextEdit::ExtraSelection::cursor
- A cursor that contains a selection in a QTextDocument
-*/
-
-/*!
- \variable QTextEdit::ExtraSelection::format
- A format that is used to specify a foreground or background brush/color
- for the selection.
-*/
-
-/*!
- \since 4.2
- This function allows temporarily marking certain regions in the document
- with a given color, specified as \a selections. This can be useful for
- example in a programming editor to mark a whole line of text with a given
- background color to indicate the existence of a breakpoint.
-
- \sa QTextEdit::ExtraSelection, extraSelections()
-*/
-void QTextEdit::setExtraSelections(const QList<ExtraSelection> &selections)
-{
- Q_D(QTextEdit);
- d->control->setExtraSelections(selections);
-}
-
-/*!
- \since 4.2
- Returns previously set extra selections.
-
- \sa setExtraSelections()
-*/
-QList<QTextEdit::ExtraSelection> QTextEdit::extraSelections() const
-{
- Q_D(const QTextEdit);
- return d->control->extraSelections();
-}
-
-/*!
- This function returns a new MIME data object to represent the contents
- of the text edit's current selection. It is called when the selection needs
- to be encapsulated into a new QMimeData object; for example, when a drag
- and drop operation is started, or when data is copyied to the clipboard.
-
- If you reimplement this function, note that the ownership of the returned
- QMimeData object is passed to the caller. The selection can be retrieved
- by using the textCursor() function.
-*/
-QMimeData *QTextEdit::createMimeDataFromSelection() const
-{
- Q_D(const QTextEdit);
- return d->control->QTextControl::createMimeDataFromSelection();
-}
-
-/*!
- This function returns true if the contents of the MIME data object, specified
- by \a source, can be decoded and inserted into the document. It is called
- for example when during a drag operation the mouse enters this widget and it
- is necessary to determine whether it is possible to accept the drag and drop
- operation.
-
- Reimplement this function to enable drag and drop support for additional MIME types.
- */
-bool QTextEdit::canInsertFromMimeData(const QMimeData *source) const
-{
- Q_D(const QTextEdit);
- return d->control->QTextControl::canInsertFromMimeData(source);
-}
-
-/*!
- This function inserts the contents of the MIME data object, specified
- by \a source, into the text edit at the current cursor position. It is
- called whenever text is inserted as the result of a clipboard paste
- operation, or when the text edit accepts data from a drag and drop
- operation.
-
- Reimplement this function to enable drag and drop support for additional MIME types.
- */
-void QTextEdit::insertFromMimeData(const QMimeData *source)
-{
- Q_D(QTextEdit);
- d->control->QTextControl::insertFromMimeData(source);
-}
-
-/*!
- \property QTextEdit::readOnly
- \brief whether the text edit is read-only
-
- In a read-only text edit the user can only navigate through the
- text and select text; modifying the text is not possible.
-
- This property's default is false.
-*/
-
-bool QTextEdit::isReadOnly() const
-{
- Q_D(const QTextEdit);
- return !(d->control->textInteractionFlags() & Qt::TextEditable);
-}
-
-void QTextEdit::setReadOnly(bool ro)
-{
- Q_D(QTextEdit);
- Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
- if (ro) {
- flags = Qt::TextSelectableByMouse;
-#ifndef QT_NO_TEXTBROWSER
- if (qobject_cast<QTextBrowser *>(this))
- flags |= Qt::TextBrowserInteraction;
-#endif
- } else {
- flags = Qt::TextEditorInteraction;
- }
- d->control->setTextInteractionFlags(flags);
- setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
-}
-
-/*!
- \property QTextEdit::textInteractionFlags
- \since 4.2
-
- Specifies how the widget should interact with user input.
-
- The default value depends on whether the QTextEdit is read-only
- or editable, and whether it is a QTextBrowser or not.
-*/
-
-void QTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
-{
- Q_D(QTextEdit);
- d->control->setTextInteractionFlags(flags);
-}
-
-Qt::TextInteractionFlags QTextEdit::textInteractionFlags() const
-{
- Q_D(const QTextEdit);
- return d->control->textInteractionFlags();
-}
-
-/*!
- Merges the properties specified in \a modifier into the current character
- format by calling QTextCursor::mergeCharFormat on the editor's cursor.
- If the editor has a selection then the properties of \a modifier are
- directly applied to the selection.
-
- \sa QTextCursor::mergeCharFormat()
- */
-void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
-{
- Q_D(QTextEdit);
- d->control->mergeCurrentCharFormat(modifier);
-}
-
-/*!
- Sets the char format that is be used when inserting new text to \a
- format by calling QTextCursor::setCharFormat() on the editor's
- cursor. If the editor has a selection then the char format is
- directly applied to the selection.
- */
-void QTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
-{
- Q_D(QTextEdit);
- d->control->setCurrentCharFormat(format);
-}
-
-/*!
- Returns the char format that is used when inserting new text.
- */
-QTextCharFormat QTextEdit::currentCharFormat() const
-{
- Q_D(const QTextEdit);
- return d->control->currentCharFormat();
-}
-
-/*!
- \property QTextEdit::autoFormatting
- \brief the enabled set of auto formatting features
-
- The value can be any combination of the values in the
- AutoFormattingFlag enum. The default is AutoNone. Choose
- AutoAll to enable all automatic formatting.
-
- Currently, the only automatic formatting feature provided is
- AutoBulletList; future versions of Qt may offer more.
-*/
-
-QTextEdit::AutoFormatting QTextEdit::autoFormatting() const
-{
- Q_D(const QTextEdit);
- return d->autoFormatting;
-}
-
-void QTextEdit::setAutoFormatting(AutoFormatting features)
-{
- Q_D(QTextEdit);
- d->autoFormatting = features;
-}
-
-/*!
- Convenience slot that inserts \a text at the current
- cursor position.
-
- It is equivalent to
-
- \snippet doc/src/snippets/code/src_gui_widgets_qtextedit.cpp 1
- */
-void QTextEdit::insertPlainText(const QString &text)
-{
- Q_D(QTextEdit);
- d->control->insertPlainText(text);
-}
-
-/*!
- Convenience slot that inserts \a text which is assumed to be of
- html formatting at the current cursor position.
-
- It is equivalent to:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qtextedit.cpp 2
-
- \note When using this function with a style sheet, the style sheet will
- only apply to the current block in the document. In order to apply a style
- sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
- instead.
- */
-#ifndef QT_NO_TEXTHTMLPARSER
-void QTextEdit::insertHtml(const QString &text)
-{
- Q_D(QTextEdit);
- d->control->insertHtml(text);
-}
-#endif // QT_NO_TEXTHTMLPARSER
-
-/*!
- Scrolls the text edit so that the anchor with the given \a name is
- visible; does nothing if the \a name is empty, or is already
- visible, or isn't found.
-*/
-void QTextEdit::scrollToAnchor(const QString &name)
-{
- Q_D(QTextEdit);
- if (name.isEmpty())
- return;
-
- if (!isVisible()) {
- d->anchorToScrollToWhenVisible = name;
- return;
- }
-
- QPointF p = d->control->anchorPosition(name);
- const int newPosition = qRound(p.y());
- if ( d->vbar->maximum() < newPosition )
- d->_q_adjustScrollbars();
- d->vbar->setValue(newPosition);
-}
-
-/*!
- \fn QTextEdit::zoomIn(int range)
-
- Zooms in on the text by making the base font size \a range
- points larger and recalculating all font sizes to be the new size.
- This does not change the size of any images.
-
- \sa zoomOut()
-*/
-void QTextEdit::zoomIn(int range)
-{
- QFont f = font();
- const int newSize = f.pointSize() + range;
- if (newSize <= 0)
- return;
- f.setPointSize(newSize);
- setFont(f);
-}
-
-/*!
- \fn QTextEdit::zoomOut(int range)
-
- \overload
-
- Zooms out on the text by making the base font size \a range points
- smaller and recalculating all font sizes to be the new size. This
- does not change the size of any images.
-
- \sa zoomIn()
-*/
-void QTextEdit::zoomOut(int range)
-{
- zoomIn(-range);
-}
-
-/*!
- \since 4.2
- Moves the cursor by performing the given \a operation.
-
- If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
- This is the same effect that the user achieves when they hold down the Shift key
- and move the cursor with the cursor keys.
-
- \sa QTextCursor::movePosition()
-*/
-void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
-{
- Q_D(QTextEdit);
- d->control->moveCursor(operation, mode);
-}
-
-/*!
- \since 4.2
- Returns whether text can be pasted from the clipboard into the textedit.
-*/
-bool QTextEdit::canPaste() const
-{
- Q_D(const QTextEdit);
- return d->control->canPaste();
-}
-
-#ifndef QT_NO_PRINTER
-/*!
- \since 4.3
- Convenience function to print the text edit's document to the given \a printer. This
- is equivalent to calling the print method on the document directly except that this
- function also supports QPrinter::Selection as print range.
-
- \sa QTextDocument::print()
-*/
-void QTextEdit::print(QPrinter *printer) const
-{
- Q_D(const QTextEdit);
- d->control->print(printer);
-}
-#endif // QT _NO_PRINTER
-
-/*! \property QTextEdit::tabChangesFocus
- \brief whether \gui Tab changes focus or is accepted as input
-
- In some occasions text edits should not allow the user to input
- tabulators or change indentation using the \gui Tab key, as this breaks
- the focus chain. The default is false.
-
-*/
-
-bool QTextEdit::tabChangesFocus() const
-{
- Q_D(const QTextEdit);
- return d->tabChangesFocus;
-}
-
-void QTextEdit::setTabChangesFocus(bool b)
-{
- Q_D(QTextEdit);
- d->tabChangesFocus = b;
-}
-
-/*!
- \property QTextEdit::documentTitle
- \brief the title of the document parsed from the text.
-
- By default, for a newly-created, empty document, this property contains
- an empty string.
-*/
-
-/*!
- \property QTextEdit::lineWrapMode
- \brief the line wrap mode
-
- The default mode is WidgetWidth which causes words to be
- wrapped at the right edge of the text edit. Wrapping occurs at
- whitespace, keeping whole words intact. If you want wrapping to
- occur within words use setWordWrapMode(). If you set a wrap mode of
- FixedPixelWidth or FixedColumnWidth you should also call
- setLineWrapColumnOrWidth() with the width you want.
-
- \sa lineWrapColumnOrWidth
-*/
-
-QTextEdit::LineWrapMode QTextEdit::lineWrapMode() const
-{
- Q_D(const QTextEdit);
- return d->lineWrap;
-}
-
-void QTextEdit::setLineWrapMode(LineWrapMode wrap)
-{
- Q_D(QTextEdit);
- if (d->lineWrap == wrap)
- return;
- d->lineWrap = wrap;
- d->updateDefaultTextOption();
- d->relayoutDocument();
-}
-
-/*!
- \property QTextEdit::lineWrapColumnOrWidth
- \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped
-
- If the wrap mode is FixedPixelWidth, the value is the number of
- pixels from the left edge of the text edit at which text should be
- wrapped. If the wrap mode is FixedColumnWidth, the value is the
- column number (in character columns) from the left edge of the
- text edit at which text should be wrapped.
-
- By default, this property contains a value of 0.
-
- \sa lineWrapMode
-*/
-
-int QTextEdit::lineWrapColumnOrWidth() const
-{
- Q_D(const QTextEdit);
- return d->lineWrapColumnOrWidth;
-}
-
-void QTextEdit::setLineWrapColumnOrWidth(int w)
-{
- Q_D(QTextEdit);
- d->lineWrapColumnOrWidth = w;
- d->relayoutDocument();
-}
-
-/*!
- \property QTextEdit::wordWrapMode
- \brief the mode QTextEdit will use when wrapping text by words
-
- By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
-
- \sa QTextOption::WrapMode
-*/
-
-QTextOption::WrapMode QTextEdit::wordWrapMode() const
-{
- Q_D(const QTextEdit);
- return d->wordWrap;
-}
-
-void QTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
-{
- Q_D(QTextEdit);
- if (mode == d->wordWrap)
- return;
- d->wordWrap = mode;
- d->updateDefaultTextOption();
-}
-
-/*!
- Finds the next occurrence of the string, \a exp, using the given
- \a options. Returns true if \a exp was found and changes the
- cursor to select the match; otherwise returns false.
-*/
-bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
-{
- Q_D(QTextEdit);
- return d->control->find(exp, options);
-}
-
-/*!
- \fn void QTextEdit::copyAvailable(bool yes)
-
- This signal is emitted when text is selected or de-selected in the
- text edit.
-
- When text is selected this signal will be emitted with \a yes set
- to true. If no text has been selected or if the selected text is
- de-selected this signal is emitted with \a yes set to false.
-
- If \a yes is true then copy() can be used to copy the selection to
- the clipboard. If \a yes is false then copy() does nothing.
-
- \sa selectionChanged()
-*/
-
-/*!
- \fn void QTextEdit::currentCharFormatChanged(const QTextCharFormat &f)
-
- This signal is emitted if the current character format has changed, for
- example caused by a change of the cursor position.
-
- The new format is \a f.
-
- \sa setCurrentCharFormat()
-*/
-
-/*!
- \fn void QTextEdit::selectionChanged()
-
- This signal is emitted whenever the selection changes.
-
- \sa copyAvailable()
-*/
-
-/*!
- \fn void QTextEdit::cursorPositionChanged()
-
- This signal is emitted whenever the position of the
- cursor changed.
-*/
-
-/*!
- \since 4.2
-
- Sets the text edit's \a text. The text can be plain text or HTML
- and the text edit will try to guess the right format.
-
- Use setHtml() or setPlainText() directly to avoid text edit's guessing.
-*/
-void QTextEdit::setText(const QString &text)
-{
- Q_D(QTextEdit);
- Qt::TextFormat format = d->textFormat;
- if (d->textFormat == Qt::AutoText)
- format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
-#ifndef QT_NO_TEXTHTMLPARSER
- if (format == Qt::RichText || format == Qt::LogText)
- setHtml(text);
- else
-#endif
- setPlainText(text);
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use the QTextCursor class instead.
-*/
-void QTextEdit::moveCursor(CursorAction action, QTextCursor::MoveMode mode)
-{
- Q_D(QTextEdit);
- if (action == MovePageUp) {
- d->pageUpDown(QTextCursor::Up, mode);
- return;
- } else if (action == MovePageDown) {
- d->pageUpDown(QTextCursor::Down, mode);
- return;
- }
-
- QTextCursor cursor = d->control->textCursor();
- QTextCursor::MoveOperation op = QTextCursor::NoMove;
- switch (action) {
- case MoveBackward: op = QTextCursor::Left; break;
- case MoveForward: op = QTextCursor::Right; break;
- case MoveWordBackward: op = QTextCursor::WordLeft; break;
- case MoveWordForward: op = QTextCursor::WordRight; break;
- case MoveUp: op = QTextCursor::Up; break;
- case MoveDown: op = QTextCursor::Down; break;
- case MoveLineStart: op = QTextCursor::StartOfLine; break;
- case MoveLineEnd: op = QTextCursor::EndOfLine; break;
- case MoveHome: op = QTextCursor::Start; break;
- case MoveEnd: op = QTextCursor::End; break;
- default: return;
- }
- cursor.movePosition(op, mode);
- d->control->setTextCursor(cursor);
-}
-
-/*!
- Use the QTextCursor class instead.
-*/
-void QTextEdit::moveCursor(CursorAction action, bool select)
-{
- moveCursor(action, select ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
-}
-
-/*!
- Executes keyboard action \a action.
-
- Use the QTextCursor class instead.
-
- \sa textCursor()
-*/
-void QTextEdit::doKeyboardAction(KeyboardAction action)
-{
- Q_D(QTextEdit);
- QTextCursor cursor = d->control->textCursor();
- switch (action) {
- case ActionBackspace: cursor.deletePreviousChar(); break;
- case ActionDelete: cursor.deleteChar(); break;
- case ActionReturn: cursor.insertBlock(); break;
- case ActionKill: {
- QTextBlock block = cursor.block();
- if (cursor.position() == block.position() + block.length() - 2)
- cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
- else
- cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
- cursor.deleteChar();
- break;
- }
- case ActionWordBackspace:
- cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
- cursor.deletePreviousChar();
- break;
- case ActionWordDelete:
- cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
- cursor.deleteChar();
- break;
- }
- d->control->setTextCursor(cursor);
-}
-
-/*!
- Returns all the text in the text edit as plain text.
-*/
-QString QTextEdit::text() const
-{
- Q_D(const QTextEdit);
- if (d->textFormat == Qt::RichText || d->textFormat == Qt::LogText || (d->textFormat == Qt::AutoText && d->preferRichText))
- return d->control->toHtml();
- else
- return d->control->toPlainText();
-}
-
-
-/*!
- Sets the text format to format \a f.
-
- \sa textFormat()
-*/
-void QTextEdit::setTextFormat(Qt::TextFormat f)
-{
- Q_D(QTextEdit);
- d->textFormat = f;
-}
-
-/*!
- Returns the text format.
-
- \sa setTextFormat()
-*/
-Qt::TextFormat QTextEdit::textFormat() const
-{
- Q_D(const QTextEdit);
- return d->textFormat;
-}
-
-#endif // QT3_SUPPORT
-
-/*!
- Appends a new paragraph with \a text to the end of the text edit.
-
- \note The new paragraph appended will have the same character format and
- block format as the current paragraph, determined by the position of the cursor.
-
- \sa currentCharFormat(), QTextCursor::blockFormat()
-*/
-
-void QTextEdit::append(const QString &text)
-{
- Q_D(QTextEdit);
- QTextBlock lastBlock = d->control->document()->lastBlock();
- const bool atBottom = isReadOnly() ? d->verticalOffset() >= d->vbar->maximum() :
- d->control->textCursor().atEnd();
- d->control->append(text);
- if (atBottom)
- d->vbar->setValue(d->vbar->maximum());
-}
-
-/*!
- Ensures that the cursor is visible by scrolling the text edit if
- necessary.
-*/
-void QTextEdit::ensureCursorVisible()
-{
- Q_D(QTextEdit);
- d->control->ensureCursorVisible();
-}
-
-/*!
- \enum QTextEdit::KeyboardAction
-
- \compat
-
- \value ActionBackspace
- \value ActionDelete
- \value ActionReturn
- \value ActionKill
- \value ActionWordBackspace
- \value ActionWordDelete
-*/
-
-/*!
- \fn bool QTextEdit::find(const QString &exp, bool cs, bool wo)
-
- Use the find() overload that takes a QTextDocument::FindFlags
- argument.
-*/
-
-/*!
- \fn void QTextEdit::sync()
-
- Does nothing.
-*/
-
-/*!
- \fn void QTextEdit::setBold(bool b)
-
- Use setFontWeight() instead.
-*/
-
-/*!
- \fn void QTextEdit::setUnderline(bool b)
-
- Use setFontUnderline() instead.
-*/
-
-/*!
- \fn void QTextEdit::setItalic(bool i)
-
- Use setFontItalic() instead.
-*/
-
-/*!
- \fn void QTextEdit::setFamily(const QString &family)
-
- Use setFontFamily() instead.
-*/
-
-/*!
- \fn void QTextEdit::setPointSize(int size)
-
- Use setFontPointSize() instead.
-*/
-
-/*!
- \fn bool QTextEdit::italic() const
-
- Use fontItalic() instead.
-*/
-
-/*!
- \fn bool QTextEdit::bold() const
-
- Use fontWeight() >= QFont::Bold instead.
-*/
-
-/*!
- \fn bool QTextEdit::underline() const
-
- Use fontUnderline() instead.
-*/
-
-/*!
- \fn QString QTextEdit::family() const
-
- Use fontFamily() instead.
-*/
-
-/*!
- \fn int QTextEdit::pointSize() const
-
- Use int(fontPointSize()+0.5) instead.
-*/
-
-/*!
- \fn bool QTextEdit::hasSelectedText() const
-
- Use textCursor().hasSelection() instead.
-*/
-
-/*!
- \fn QString QTextEdit::selectedText() const
-
- Use textCursor().selectedText() instead.
-*/
-
-/*!
- \fn bool QTextEdit::isUndoAvailable() const
-
- Use document()->isUndoAvailable() instead.
-*/
-
-/*!
- \fn bool QTextEdit::isRedoAvailable() const
-
- Use document()->isRedoAvailable() instead.
-*/
-
-/*!
- \fn void QTextEdit::insert(const QString &text)
-
- Use insertPlainText() instead.
-*/
-
-/*!
- \fn bool QTextEdit::isModified() const
-
- Use document()->isModified() instead.
-*/
-
-/*!
- \fn QColor QTextEdit::color() const
-
- Use textColor() instead.
-*/
-
-/*!
- \fn void QTextEdit::textChanged()
-
- This signal is emitted whenever the document's content changes; for
- example, when text is inserted or deleted, or when formatting is applied.
-*/
-
-/*!
- \fn void QTextEdit::undoAvailable(bool available)
-
- This signal is emitted whenever undo operations become available
- (\a available is true) or unavailable (\a available is false).
-*/
-
-/*!
- \fn void QTextEdit::redoAvailable(bool available)
-
- This signal is emitted whenever redo operations become available
- (\a available is true) or unavailable (\a available is false).
-*/
-
-/*!
- \fn void QTextEdit::currentFontChanged(const QFont &font)
-
- Use currentCharFormatChanged() instead.
-*/
-
-/*!
- \fn void QTextEdit::currentColorChanged(const QColor &color)
-
- Use currentCharFormatChanged() instead.
-*/
-
-/*!
- \fn void QTextEdit::setModified(bool m)
-
- Use document->setModified() instead.
-*/
-
-/*!
- \fn void QTextEdit::setColor(const QColor &color)
-
- Use setTextColor() instead.
-*/
-#endif // QT_NO_TEXTEDIT
-
-QT_END_NAMESPACE
-
-#include "moc_qtextedit.cpp"
diff --git a/src/gui/widgets/qtextedit.h b/src/gui/widgets/qtextedit.h
deleted file mode 100644
index 459f9bdd5e..0000000000
--- a/src/gui/widgets/qtextedit.h
+++ /dev/null
@@ -1,431 +0,0 @@
-/****************************************************************************
-**
-** 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 QTEXTEDIT_H
-#define QTEXTEDIT_H
-
-#include <QtGui/qabstractscrollarea.h>
-#include <QtGui/qtextdocument.h>
-#include <QtGui/qtextoption.h>
-#include <QtGui/qtextcursor.h>
-#include <QtGui/qtextformat.h>
-
-#ifndef QT_NO_TEXTEDIT
-
-#ifdef QT3_SUPPORT
-#include <QtGui/qtextobject.h>
-#include <QtGui/qtextlayout.h>
-#endif
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-class QStyleSheet;
-class QTextDocument;
-class QMenu;
-class QTextEditPrivate;
-class QMimeData;
-
-class Q_GUI_EXPORT QTextEdit : public QAbstractScrollArea
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QTextEdit)
- Q_FLAGS(AutoFormatting)
- Q_ENUMS(LineWrapMode)
- Q_PROPERTY(AutoFormatting autoFormatting READ autoFormatting WRITE setAutoFormatting)
- Q_PROPERTY(bool tabChangesFocus READ tabChangesFocus WRITE setTabChangesFocus)
- Q_PROPERTY(QString documentTitle READ documentTitle WRITE setDocumentTitle)
- Q_PROPERTY(bool undoRedoEnabled READ isUndoRedoEnabled WRITE setUndoRedoEnabled)
- Q_PROPERTY(LineWrapMode lineWrapMode READ lineWrapMode WRITE setLineWrapMode)
- QDOC_PROPERTY(QTextOption::WrapMode wordWrapMode READ wordWrapMode WRITE setWordWrapMode)
- Q_PROPERTY(int lineWrapColumnOrWidth READ lineWrapColumnOrWidth WRITE setLineWrapColumnOrWidth)
- Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
-#ifndef QT_NO_TEXTHTMLPARSER
- Q_PROPERTY(QString html READ toHtml WRITE setHtml NOTIFY textChanged USER true)
-#endif
- Q_PROPERTY(QString plainText READ toPlainText WRITE setPlainText DESIGNABLE false)
- Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode)
- Q_PROPERTY(int tabStopWidth READ tabStopWidth WRITE setTabStopWidth)
- Q_PROPERTY(bool acceptRichText READ acceptRichText WRITE setAcceptRichText)
- Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
- Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
- Q_PROPERTY(QObject *document READ document)
-public:
- enum LineWrapMode {
- NoWrap,
- WidgetWidth,
- FixedPixelWidth,
- FixedColumnWidth
- };
-
- enum AutoFormattingFlag {
- AutoNone = 0,
- AutoBulletList = 0x00000001,
- AutoAll = 0xffffffff
- };
-
- Q_DECLARE_FLAGS(AutoFormatting, AutoFormattingFlag)
-
-#if defined(QT3_SUPPORT)
- enum CursorAction {
- MoveBackward,
- MoveForward,
- MoveWordBackward,
- MoveWordForward,
- MoveUp,
- MoveDown,
- MoveLineStart,
- MoveLineEnd,
- MoveHome,
- MoveEnd,
- MovePageUp,
- MovePageDown
-#if !defined(Q_MOC_RUN)
- ,
- MovePgUp = MovePageUp,
- MovePgDown = MovePageDown
-#endif
- };
-#endif
-
- explicit QTextEdit(QWidget *parent = 0);
- explicit QTextEdit(const QString &text, QWidget *parent = 0);
- virtual ~QTextEdit();
-
- void setDocument(QTextDocument *document);
- QTextDocument *document() const;
-
- void setTextCursor(const QTextCursor &cursor);
- QTextCursor textCursor() const;
-
- bool isReadOnly() const;
- void setReadOnly(bool ro);
-
- void setTextInteractionFlags(Qt::TextInteractionFlags flags);
- Qt::TextInteractionFlags textInteractionFlags() const;
-
- qreal fontPointSize() const;
- QString fontFamily() const;
- int fontWeight() const;
- bool fontUnderline() const;
- bool fontItalic() const;
- QColor textColor() const;
- QColor textBackgroundColor() const;
- QFont currentFont() const;
- Qt::Alignment alignment() const;
-
- void mergeCurrentCharFormat(const QTextCharFormat &modifier);
-
- void setCurrentCharFormat(const QTextCharFormat &format);
- QTextCharFormat currentCharFormat() const;
-
- AutoFormatting autoFormatting() const;
- void setAutoFormatting(AutoFormatting features);
-
- bool tabChangesFocus() const;
- void setTabChangesFocus(bool b);
-
- inline void setDocumentTitle(const QString &title)
- { document()->setMetaInformation(QTextDocument::DocumentTitle, title); }
- inline QString documentTitle() const
- { return document()->metaInformation(QTextDocument::DocumentTitle); }
-
- inline bool isUndoRedoEnabled() const
- { return document()->isUndoRedoEnabled(); }
- inline void setUndoRedoEnabled(bool enable)
- { document()->setUndoRedoEnabled(enable); }
-
- LineWrapMode lineWrapMode() const;
- void setLineWrapMode(LineWrapMode mode);
-
- int lineWrapColumnOrWidth() const;
- void setLineWrapColumnOrWidth(int w);
-
- QTextOption::WrapMode wordWrapMode() const;
- void setWordWrapMode(QTextOption::WrapMode policy);
-
- bool find(const QString &exp, QTextDocument::FindFlags options = 0);
-
- inline QString toPlainText() const
- { return document()->toPlainText(); }
-#ifndef QT_NO_TEXTHTMLPARSER
- inline QString toHtml() const
- { return document()->toHtml(); }
-#endif
-
- void ensureCursorVisible();
-
- virtual QVariant loadResource(int type, const QUrl &name);
-#ifndef QT_NO_CONTEXTMENU
- QMenu *createStandardContextMenu();
- QMenu *createStandardContextMenu(const QPoint &position);
-#endif
-
- QTextCursor cursorForPosition(const QPoint &pos) const;
- QRect cursorRect(const QTextCursor &cursor) const;
- QRect cursorRect() const;
-
- QString anchorAt(const QPoint& pos) const;
-
- bool overwriteMode() const;
- void setOverwriteMode(bool overwrite);
-
- int tabStopWidth() const;
- void setTabStopWidth(int width);
-
- int cursorWidth() const;
- void setCursorWidth(int width);
-
- bool acceptRichText() const;
- void setAcceptRichText(bool accept);
-
- struct ExtraSelection
- {
- QTextCursor cursor;
- QTextCharFormat format;
- };
- void setExtraSelections(const QList<ExtraSelection> &selections);
- QList<ExtraSelection> extraSelections() const;
-
- void moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor);
-
- bool canPaste() const;
-
-#ifndef QT_NO_PRINTER
- void print(QPrinter *printer) const;
-#endif
-
-public Q_SLOTS:
- void setFontPointSize(qreal s);
- void setFontFamily(const QString &fontFamily);
- void setFontWeight(int w);
- void setFontUnderline(bool b);
- void setFontItalic(bool b);
- void setTextColor(const QColor &c);
- void setTextBackgroundColor(const QColor &c);
- void setCurrentFont(const QFont &f);
- void setAlignment(Qt::Alignment a);
-
- void setPlainText(const QString &text);
-#ifndef QT_NO_TEXTHTMLPARSER
- void setHtml(const QString &text);
-#endif
- void setText(const QString &text);
-
-#ifndef QT_NO_CLIPBOARD
- void cut();
- void copy();
- void paste();
-#endif
-
- void undo();
- void redo();
-
- void clear();
- void selectAll();
-
- void insertPlainText(const QString &text);
-#ifndef QT_NO_TEXTHTMLPARSER
- void insertHtml(const QString &text);
-#endif // QT_NO_TEXTHTMLPARSER
-
- void append(const QString &text);
-
- void scrollToAnchor(const QString &name);
-
- void zoomIn(int range = 1);
- void zoomOut(int range = 1);
-
-Q_SIGNALS:
- void textChanged();
- void undoAvailable(bool b);
- void redoAvailable(bool b);
- void currentCharFormatChanged(const QTextCharFormat &format);
- void copyAvailable(bool b);
- void selectionChanged();
- void cursorPositionChanged();
-
-protected:
- virtual bool event(QEvent *e);
- virtual void timerEvent(QTimerEvent *e);
- virtual void keyPressEvent(QKeyEvent *e);
- virtual void keyReleaseEvent(QKeyEvent *e);
- virtual void resizeEvent(QResizeEvent *e);
- virtual void paintEvent(QPaintEvent *e);
- virtual void mousePressEvent(QMouseEvent *e);
- virtual void mouseMoveEvent(QMouseEvent *e);
- virtual void mouseReleaseEvent(QMouseEvent *e);
- virtual void mouseDoubleClickEvent(QMouseEvent *e);
- virtual bool focusNextPrevChild(bool next);
-#ifndef QT_NO_CONTEXTMENU
- virtual void contextMenuEvent(QContextMenuEvent *e);
-#endif
-#ifndef QT_NO_DRAGANDDROP
- virtual void dragEnterEvent(QDragEnterEvent *e);
- virtual void dragLeaveEvent(QDragLeaveEvent *e);
- virtual void dragMoveEvent(QDragMoveEvent *e);
- virtual void dropEvent(QDropEvent *e);
-#endif
- virtual void focusInEvent(QFocusEvent *e);
- virtual void focusOutEvent(QFocusEvent *e);
- virtual void showEvent(QShowEvent *);
- virtual void changeEvent(QEvent *e);
-#ifndef QT_NO_WHEELEVENT
- virtual void wheelEvent(QWheelEvent *e);
-#endif
-
- virtual QMimeData *createMimeDataFromSelection() const;
- virtual bool canInsertFromMimeData(const QMimeData *source) const;
- virtual void insertFromMimeData(const QMimeData *source);
-
- virtual void inputMethodEvent(QInputMethodEvent *);
- QVariant inputMethodQuery(Qt::InputMethodQuery property) const;
-
- QTextEdit(QTextEditPrivate &dd, QWidget *parent);
-
- virtual void scrollContentsBy(int dx, int dy);
-
-#ifdef QT3_SUPPORT
-Q_SIGNALS:
- QT_MOC_COMPAT void currentFontChanged(const QFont &f);
- QT_MOC_COMPAT void currentColorChanged(const QColor &c);
-
-public:
- QT3_SUPPORT_CONSTRUCTOR QTextEdit(QWidget *parent, const char *name);
- inline QT3_SUPPORT bool find(const QString &exp, bool cs, bool wo)
- {
- QTextDocument::FindFlags flags = 0;
- if (cs)
- flags |= QTextDocument::FindCaseSensitively;
- if (wo)
- flags |= QTextDocument::FindWholeWords;
- return find(exp, flags);
- }
-
- inline QT3_SUPPORT void sync() {}
-
- QT3_SUPPORT void moveCursor(CursorAction action, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor);
- QT3_SUPPORT void moveCursor(CursorAction action, bool select);
-
- enum KeyboardAction {
- ActionBackspace,
- ActionDelete,
- ActionReturn,
- ActionKill,
- ActionWordBackspace,
- ActionWordDelete
- };
-
- QT3_SUPPORT void doKeyboardAction(KeyboardAction action);
-
- QT3_SUPPORT QString text() const;
- QT3_SUPPORT void setTextFormat(Qt::TextFormat);
- QT3_SUPPORT Qt::TextFormat textFormat() const;
-
- inline QT3_SUPPORT void setBold(bool b) { setFontWeight(b ? QFont::Bold : QFont::Normal); }
- inline QT3_SUPPORT void setUnderline(bool b) { setFontUnderline(b); }
- inline QT3_SUPPORT void setItalic(bool i) { setFontItalic(i); }
- inline QT3_SUPPORT void setFamily(const QString &family) { setFontFamily(family); }
- inline QT3_SUPPORT void setPointSize(int size) { setFontPointSize(size); }
-
- inline QT3_SUPPORT bool italic() const { return fontItalic(); }
- inline QT3_SUPPORT bool bold() const { return fontWeight() >= QFont::Bold; }
- inline QT3_SUPPORT bool underline() const { return fontUnderline(); }
- inline QT3_SUPPORT QString family() const { return fontFamily(); }
- inline QT3_SUPPORT int pointSize() const { return (int)(fontPointSize()+0.5); }
-
- inline QT3_SUPPORT bool hasSelectedText() const
- { return textCursor().hasSelection(); }
- inline QT3_SUPPORT QString selectedText() const
- { return textCursor().selectedText(); }
-
- inline QT3_SUPPORT bool isUndoAvailable() const
- { return document()->isUndoAvailable(); }
- inline QT3_SUPPORT bool isRedoAvailable() const
- { return document()->isRedoAvailable(); }
-
- inline QT3_SUPPORT void insert(const QString &text)
- { insertPlainText(text); }
-
- inline QT3_SUPPORT bool isModified() const
- { return document()->isModified(); }
-
- inline QT3_SUPPORT QColor color() const
- { return textColor(); }
-
-public Q_SLOTS:
- inline QT_MOC_COMPAT void setModified(bool m = true)
- { document()->setModified(m); }
-public:
- inline QT3_SUPPORT void undo() const
- { document()->undo(); }
- inline QT3_SUPPORT void redo() const
- { document()->redo(); }
-
-public Q_SLOTS:
- inline QT_MOC_COMPAT void setColor(const QColor &c)
- { setTextColor(c); }
-
-#endif
-
-private:
- Q_DISABLE_COPY(QTextEdit)
- Q_PRIVATE_SLOT(d_func(), void _q_repaintContents(const QRectF &r))
- Q_PRIVATE_SLOT(d_func(), void _q_currentCharFormatChanged(const QTextCharFormat &))
- Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars())
- Q_PRIVATE_SLOT(d_func(), void _q_ensureVisible(const QRectF &))
- friend class QTextEditControl;
- friend class QTextDocument;
- friend class QTextControl;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(QTextEdit::AutoFormatting)
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QT_NO_TEXTEDIT
-
-#endif // QTEXTEDIT_H
diff --git a/src/gui/widgets/qtextedit_p.h b/src/gui/widgets/qtextedit_p.h
deleted file mode 100644
index 63941142a2..0000000000
--- a/src/gui/widgets/qtextedit_p.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** 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 QTEXTEDIT_P_H
-#define QTEXTEDIT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "private/qabstractscrollarea_p.h"
-#include "QtGui/qtextdocumentfragment.h"
-#include "QtGui/qscrollbar.h"
-#include "QtGui/qtextcursor.h"
-#include "QtGui/qtextformat.h"
-#include "QtGui/qmenu.h"
-#include "QtGui/qabstracttextdocumentlayout.h"
-#include "QtCore/qbasictimer.h"
-#include "QtCore/qurl.h"
-#include "private/qtextcontrol_p.h"
-#include "qtextedit.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_TEXTEDIT
-
-class QMimeData;
-class QTextEditPrivate : public QAbstractScrollAreaPrivate
-{
- Q_DECLARE_PUBLIC(QTextEdit)
-public:
- QTextEditPrivate();
-
- void init(const QString &html = QString());
- void paint(QPainter *p, QPaintEvent *e);
- void _q_repaintContents(const QRectF &contentsRect);
-
- inline QPoint mapToContents(const QPoint &point) const
- { return QPoint(point.x() + horizontalOffset(), point.y() + verticalOffset()); }
-
- void _q_adjustScrollbars();
- void _q_ensureVisible(const QRectF &rect);
- void relayoutDocument();
-
- void createAutoBulletList();
- void pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode);
-
- inline int horizontalOffset() const
- { return q_func()->isRightToLeft() ? (hbar->maximum() - hbar->value()) : hbar->value(); }
- inline int verticalOffset() const
- { return vbar->value(); }
-
- inline void sendControlEvent(QEvent *e)
- { control->processEvent(e, QPointF(horizontalOffset(), verticalOffset()), viewport); }
-
- void _q_currentCharFormatChanged(const QTextCharFormat &format);
-
- void updateDefaultTextOption();
-
- // re-implemented by QTextBrowser, called by QTextDocument::loadResource
- virtual QUrl resolveUrl(const QUrl &url) const
- { return url; }
-
- QTextControl *control;
-
- QTextEdit::AutoFormatting autoFormatting;
- bool tabChangesFocus;
-
- QBasicTimer autoScrollTimer;
- QPoint autoScrollDragPos;
-
- QTextEdit::LineWrapMode lineWrap;
- int lineWrapColumnOrWidth;
- QTextOption::WrapMode wordWrap;
-
- uint ignoreAutomaticScrollbarAdjustment : 1;
- uint preferRichText : 1;
- uint showCursorOnInitialShow : 1;
- uint inDrag : 1;
- uint clickCausedFocus : 1;
-
- // Qt3 COMPAT only, for setText
- Qt::TextFormat textFormat;
-
- QString anchorToScrollToWhenVisible;
-
-#ifdef QT_KEYPAD_NAVIGATION
- QBasicTimer deleteAllTimer;
-#endif
-};
-#endif // QT_NO_TEXTEDIT
-
-
-QT_END_NAMESPACE
-
-#endif // QTEXTEDIT_P_H
diff --git a/src/gui/widgets/qtoolbar.cpp b/src/gui/widgets/qtoolbar.cpp
deleted file mode 100644
index e19ef69442..0000000000
--- a/src/gui/widgets/qtoolbar.cpp
+++ /dev/null
@@ -1,1349 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtoolbar.h"
-
-#ifndef QT_NO_TOOLBAR
-
-#include <qapplication.h>
-#include <qcombobox.h>
-#include <qevent.h>
-#include <qlayout.h>
-#include <qmainwindow.h>
-#include <qmenu.h>
-#include <qmenubar.h>
-#include <qrubberband.h>
-#include <qsignalmapper.h>
-#include <qstylepainter.h>
-#include <qtoolbutton.h>
-#include <qwidgetaction.h>
-#include <qtimer.h>
-#include <private/qwidgetaction_p.h>
-#ifdef Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
-#include <private/qmainwindowlayout_p.h>
-
-#include "qtoolbar_p.h"
-#include "qtoolbarseparator_p.h"
-#include "qtoolbarlayout_p.h"
-
-#include "qdebug.h"
-
-#define POPUP_TIMER_INTERVAL 500
-
-QT_BEGIN_NAMESPACE
-
-#ifdef Q_WS_MAC
-static void qt_mac_updateToolBarButtonHint(QWidget *parentWidget)
-{
- if (!(parentWidget->windowFlags() & Qt::CustomizeWindowHint))
- parentWidget->setWindowFlags(parentWidget->windowFlags() | Qt::MacWindowToolBarButtonHint);
-}
-#endif
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-/******************************************************************************
-** QToolBarPrivate
-*/
-
-void QToolBarPrivate::init()
-{
- Q_Q(QToolBar);
- q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed));
- q->setBackgroundRole(QPalette::Button);
- q->setAttribute(Qt::WA_Hover);
- q->setAttribute(Qt::WA_X11NetWmWindowTypeToolBar);
-
- QStyle *style = q->style();
- int e = style->pixelMetric(QStyle::PM_ToolBarIconSize, 0, q);
- iconSize = QSize(e, e);
-
- layout = new QToolBarLayout(q);
- layout->updateMarginAndSpacing();
-
-#ifdef Q_WS_MAC
- if (q->parentWidget() && q->parentWidget()->isWindow()) {
- // Make sure that the window has the "toolbar" button.
- QWidget *parentWidget = q->parentWidget();
- qt_mac_updateToolBarButtonHint(parentWidget);
- reinterpret_cast<QToolBar *>(parentWidget)->d_func()->createWinId(); // Please let me create your winId...
- extern OSWindowRef qt_mac_window_for(const QWidget *); // qwidget_mac.cpp
- macWindowToolbarShow(q->parentWidget(), true);
- }
-#endif
-
- toggleViewAction = new QAction(q);
- toggleViewAction->setCheckable(true);
- q->setMovable(q->style()->styleHint(QStyle::SH_ToolBar_Movable, 0, q ));
- QObject::connect(toggleViewAction, SIGNAL(triggered(bool)), q, SLOT(_q_toggleView(bool)));
-}
-
-void QToolBarPrivate::_q_toggleView(bool b)
-{
- Q_Q(QToolBar);
- if (b == q->isHidden()) {
- if (b)
- q->show();
- else
- q->close();
- }
-}
-
-void QToolBarPrivate::_q_updateIconSize(const QSize &sz)
-{
- Q_Q(QToolBar);
- if (!explicitIconSize) {
- // iconSize not explicitly set
- q->setIconSize(sz);
- explicitIconSize = false;
- }
-}
-
-void QToolBarPrivate::_q_updateToolButtonStyle(Qt::ToolButtonStyle style)
-{
- Q_Q(QToolBar);
- if (!explicitToolButtonStyle) {
- q->setToolButtonStyle(style);
- explicitToolButtonStyle = false;
- }
-}
-
-void QToolBarPrivate::updateWindowFlags(bool floating, bool unplug)
-{
- Q_Q(QToolBar);
- Qt::WindowFlags flags = floating ? Qt::Tool : Qt::Widget;
-
- flags |= Qt::FramelessWindowHint;
-
- if (unplug) {
- flags |= Qt::X11BypassWindowManagerHint;
-#ifdef Q_WS_MAC
- flags |= Qt::WindowStaysOnTopHint;
-#endif
- }
-
- q->setWindowFlags(flags);
-}
-
-void QToolBarPrivate::setWindowState(bool floating, bool unplug, const QRect &rect)
-{
- Q_Q(QToolBar);
- bool visible = !q->isHidden();
- bool wasFloating = q->isFloating(); // ...is also currently using popup menus
-
- q->hide();
-
- updateWindowFlags(floating, unplug);
-
- if (floating != wasFloating)
- layout->checkUsePopupMenu();
-
- if (!rect.isNull())
- q->setGeometry(rect);
-
- if (visible)
- q->show();
-
- if (floating != wasFloating)
- emit q->topLevelChanged(floating);
-}
-
-void QToolBarPrivate::initDrag(const QPoint &pos)
-{
- Q_Q(QToolBar);
-
- if (state != 0)
- return;
-
- QMainWindow *win = qobject_cast<QMainWindow*>(parent);
- Q_ASSERT(win != 0);
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
- Q_ASSERT(layout != 0);
- if (layout->pluggingWidget != 0) // the main window is animating a docking operation
- return;
-
- state = new DragState;
- state->pressPos = pos;
- state->dragging = false;
- state->moving = false;
- state->widgetItem = 0;
-
- if (q->isRightToLeft())
- state->pressPos = QPoint(q->width() - state->pressPos.x(), state->pressPos.y());
-}
-
-void QToolBarPrivate::startDrag(bool moving)
-{
- Q_Q(QToolBar);
-
- Q_ASSERT(state != 0);
-
- if ((moving && state->moving) || state->dragging)
- return;
-
- QMainWindow *win = qobject_cast<QMainWindow*>(parent);
- Q_ASSERT(win != 0);
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
- Q_ASSERT(layout != 0);
-
- if (!moving) {
- state->widgetItem = layout->unplug(q);
-#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
- if (q->isWindow()) {
- setWindowState(true, true); //set it to floating
- }
-#endif
- Q_ASSERT(state->widgetItem != 0);
- }
- state->dragging = !moving;
- state->moving = moving;
-}
-
-void QToolBarPrivate::endDrag()
-{
- Q_Q(QToolBar);
- Q_ASSERT(state != 0);
-
- q->releaseMouse();
-
- if (state->dragging) {
- QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
- Q_ASSERT(layout != 0);
-
- if (!layout->plug(state->widgetItem)) {
- if (q->isFloatable()) {
- layout->restore();
-#if defined(Q_WS_X11) || defined(Q_WS_MAC)
- setWindowState(true); // gets rid of the X11BypassWindowManager window flag
- // and activates the resizer
-#endif
- q->activateWindow();
- } else {
- layout->revert(state->widgetItem);
- }
- }
- }
-
- delete state;
- state = 0;
-}
-
-bool QToolBarPrivate::mousePressEvent(QMouseEvent *event)
-{
- Q_Q(QToolBar);
- QStyleOptionToolBar opt;
- q->initStyleOption(&opt);
- if (q->style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, q).contains(event->pos()) == false) {
-#ifdef Q_WS_MAC
- // When using the unified toolbar on Mac OS X the user can can click and
- // drag between toolbar contents to move the window. Make this work by
- // implementing the standard mouse-dragging code and then call
- // window->move() in mouseMoveEvent below.
- if (QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parent)) {
- if (mainWindow->toolBarArea(q) == Qt::TopToolBarArea
- && mainWindow->unifiedTitleAndToolBarOnMac()
- && q->childAt(event->pos()) == 0) {
- macWindowDragging = true;
- macWindowDragPressPosition = event->pos();
- return true;
- }
- }
-#endif
- return false;
- }
-
- if (event->button() != Qt::LeftButton)
- return true;
-
- if (!layout->movable())
- return true;
-
- initDrag(event->pos());
- return true;
-}
-
-bool QToolBarPrivate::mouseReleaseEvent(QMouseEvent*)
-{
- if (state != 0) {
- endDrag();
- return true;
- } else {
-#ifdef Q_WS_MAC
- if (!macWindowDragging)
- return false;
- macWindowDragging = false;
- macWindowDragPressPosition = QPoint();
- return true;
-#endif
- return false;
- }
-}
-
-bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
-{
- Q_Q(QToolBar);
-
- if (!state) {
-#ifdef Q_WS_MAC
- if (!macWindowDragging)
- return false;
- QWidget *w = q->window();
- const QPoint delta = event->pos() - macWindowDragPressPosition;
- w->move(w->pos() + delta);
- return true;
-#endif
- return false;
- }
-
- QMainWindow *win = qobject_cast<QMainWindow*>(parent);
- if (win == 0)
- return true;
-
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
- Q_ASSERT(layout != 0);
-
- if (layout->pluggingWidget == 0
- && (event->pos() - state->pressPos).manhattanLength() > QApplication::startDragDistance()) {
- const bool wasDragging = state->dragging;
- const bool moving = !q->isWindow() && (orientation == Qt::Vertical ?
- event->x() >= 0 && event->x() < q->width() :
- event->y() >= 0 && event->y() < q->height());
-
- startDrag(moving);
- if (!moving && !wasDragging) {
-#ifdef Q_OS_WIN
- grabMouseWhileInWindow();
-#else
- q->grabMouse();
-#endif
- }
- }
-
- if (state->dragging) {
- QPoint pos = event->globalPos();
- // if we are right-to-left, we move so as to keep the right edge the same distance
- // from the mouse
- if (q->isLeftToRight())
- pos -= state->pressPos;
- else
- pos += QPoint(state->pressPos.x() - q->width(), -state->pressPos.y());
-
- q->move(pos);
- layout->hover(state->widgetItem, event->globalPos());
- } else if (state->moving) {
-
- const QPoint rtl(q->width() - state->pressPos.x(), state->pressPos.y()); //for RTL
- const QPoint globalPressPos = q->mapToGlobal(q->isRightToLeft() ? rtl : state->pressPos);
- int pos = 0;
-
- QPoint delta = event->globalPos() - globalPressPos;
- if (orientation == Qt::Vertical) {
- pos = q->y() + delta.y();
- } else {
- if (q->isRightToLeft()) {
- pos = win->width() - q->width() - q->x() - delta.x();
- } else {
- pos = q->x() + delta.x();
- }
- }
-
- layout->moveToolBar(q, pos);
- }
- return true;
-}
-
-void QToolBarPrivate::unplug(const QRect &_r)
-{
- Q_Q(QToolBar);
- QRect r = _r;
- r.moveTopLeft(q->mapToGlobal(QPoint(0, 0)));
- setWindowState(true, true, r);
- layout->setExpanded(false);
-}
-
-void QToolBarPrivate::plug(const QRect &r)
-{
- setWindowState(false, false, r);
-}
-
-/******************************************************************************
-** QToolBar
-*/
-
-/*!
- \class QToolBar
-
- \brief The QToolBar class provides a movable panel that contains a
- set of controls.
-
- \ingroup mainwindow-classes
-
-
- Toolbar buttons are added by adding \e actions, using addAction()
- or insertAction(). Groups of buttons can be separated using
- addSeparator() or insertSeparator(). If a toolbar button is not
- appropriate, a widget can be inserted instead using addWidget() or
- insertWidget(); examples of suitable widgets are QSpinBox,
- QDoubleSpinBox, and QComboBox. When a toolbar button is pressed it
- emits the actionTriggered() signal.
-
- A toolbar can be fixed in place in a particular area (e.g. at the
- top of the window), or it can be movable (isMovable()) between
- toolbar areas; see allowedAreas() and isAreaAllowed().
-
- When a toolbar is resized in such a way that it is too small to
- show all the items it contains, an extension button will appear as
- the last item in the toolbar. Pressing the extension button will
- pop up a menu containing the items that does not currently fit in
- the toolbar.
-
- When a QToolBar is not a child of a QMainWindow, it looses the ability
- to populate the extension pop up with widgets added to the toolbar using
- addWidget(). Please use widget actions created by inheriting QWidgetAction
- and implementing QWidgetAction::createWidget() instead.
-
- \sa QToolButton, QMenu, QAction, {Application Example}
-*/
-
-/*!
- \fn bool QToolBar::isAreaAllowed(Qt::ToolBarArea area) const
-
- Returns true if this toolbar is dockable in the given \a area;
- otherwise returns false.
-*/
-
-/*!
- \fn void QToolBar::addAction(QAction *action)
- \overload
-
- Appends the action \a action to the toolbar's list of actions.
-
- \sa QMenu::addAction(), QWidget::addAction()
-*/
-
-/*!
- \fn void QToolBar::actionTriggered(QAction *action)
-
- This signal is emitted when an action in this toolbar is triggered.
- This happens when the action's tool button is pressed, or when the
- action is triggered in some other way outside the tool bar. The parameter
- holds the triggered \a action.
-*/
-
-/*!
- \fn void QToolBar::allowedAreasChanged(Qt::ToolBarAreas allowedAreas)
-
- This signal is emitted when the collection of allowed areas for the
- toolbar is changed. The new areas in which the toolbar can be positioned
- are specified by \a allowedAreas.
-
- \sa allowedAreas
-*/
-
-/*!
- \fn void QToolBar::iconSizeChanged(const QSize &iconSize)
-
- This signal is emitted when the icon size is changed. The \a
- iconSize parameter holds the toolbar's new icon size.
-
- \sa iconSize QMainWindow::iconSize
-*/
-
-/*!
- \fn void QToolBar::movableChanged(bool movable)
-
- This signal is emitted when the toolbar becomes movable or fixed.
- If the toolbar can be moved, \a movable is true; otherwise it is
- false.
-
- \sa movable
-*/
-
-/*!
- \fn void QToolBar::orientationChanged(Qt::Orientation orientation)
-
- This signal is emitted when the orientation of the toolbar changes.
- The new orientation is specified by the \a orientation given.
-
- \sa orientation
-*/
-
-/*!
- \fn void QToolBar::toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle)
-
- This signal is emitted when the tool button style is changed. The
- \a toolButtonStyle parameter holds the toolbar's new tool button
- style.
-
- \sa toolButtonStyle QMainWindow::toolButtonStyle
-*/
-
-/*!
- \since 4.6
-
- \fn void QToolBar::topLevelChanged(bool topLevel)
-
- This signal is emitted when the \l floating property changes.
- The \a topLevel parameter is true if the toolbar is now floating;
- otherwise it is false.
-
- \sa isWindow()
-*/
-
-
-/*!
- \fn void QToolBar::visibilityChanged(bool visible)
- \since 4.7
-
- This signal is emitted when the toolbar becomes \a visible (or
- invisible). This happens when the widget is hidden or shown.
-*/
-
-/*!
- Constructs a QToolBar with the given \a parent.
-*/
-QToolBar::QToolBar(QWidget *parent)
- : QWidget(*new QToolBarPrivate, parent, 0)
-{
- Q_D(QToolBar);
- d->init();
-}
-
-/*!
- Constructs a QToolBar with the given \a parent.
-
- The given window \a title identifies the toolbar and is shown in
- the context menu provided by QMainWindow.
-
- \sa setWindowTitle()
-*/
-QToolBar::QToolBar(const QString &title, QWidget *parent)
- : QWidget(*new QToolBarPrivate, parent, 0)
-{
- Q_D(QToolBar);
- d->init();
- setWindowTitle(title);
-}
-
-#ifdef QT3_SUPPORT
-/*! \obsolete
- Constructs a QToolBar with the given \a parent and \a name.
-*/
-QToolBar::QToolBar(QWidget *parent, const char *name)
- : QWidget(*new QToolBarPrivate, parent, 0)
-{
- Q_D(QToolBar);
- d->init();
- setObjectName(QString::fromAscii(name));
-}
-#endif
-
-/*!
- Destroys the toolbar.
-*/
-QToolBar::~QToolBar()
-{
- // Remove the toolbar button if there is nothing left.
- QMainWindow *mainwindow = qobject_cast<QMainWindow *>(parentWidget());
- if (mainwindow) {
-#ifdef Q_WS_MAC
- QMainWindowLayout *mainwin_layout = qt_mainwindow_layout(mainwindow);
- if (mainwin_layout && mainwin_layout->layoutState.toolBarAreaLayout.isEmpty()
- && mainwindow->testAttribute(Qt::WA_WState_Created))
- macWindowToolbarShow(mainwindow, false);
-#endif
- }
-}
-
-/*! \property QToolBar::movable
- \brief whether the user can move the toolbar within the toolbar area,
- or between toolbar areas
-
- By default, this property is true.
-
- This property only makes sense if the toolbar is in a
- QMainWindow.
-
- \sa allowedAreas
-*/
-
-void QToolBar::setMovable(bool movable)
-{
- Q_D(QToolBar);
- if (!movable == !d->movable)
- return;
- d->movable = movable;
- d->layout->invalidate();
- emit movableChanged(d->movable);
-}
-
-bool QToolBar::isMovable() const
-{
- Q_D(const QToolBar);
- return d->movable;
-}
-
-/*!
- \property QToolBar::floatable
- \brief whether the toolbar can be dragged and dropped as an independent window.
-
- The default is true.
-*/
-bool QToolBar::isFloatable() const
-{
- Q_D(const QToolBar);
- return d->floatable;
-}
-
-void QToolBar::setFloatable(bool floatable)
-{
- Q_D(QToolBar);
- d->floatable = floatable;
-}
-
-/*!
- \property QToolBar::floating
- \brief whether the toolbar is an independent window.
-
- By default, this property is true.
-
- \sa QWidget::isWindow()
-*/
-bool QToolBar::isFloating() const
-{
- return isWindow();
-}
-
-/*!
- \property QToolBar::allowedAreas
- \brief areas where the toolbar may be placed
-
- The default is Qt::AllToolBarAreas.
-
- This property only makes sense if the toolbar is in a
- QMainWindow.
-
- \sa movable
-*/
-
-void QToolBar::setAllowedAreas(Qt::ToolBarAreas areas)
-{
- Q_D(QToolBar);
- areas &= Qt::ToolBarArea_Mask;
- if (areas == d->allowedAreas)
- return;
- d->allowedAreas = areas;
- emit allowedAreasChanged(d->allowedAreas);
-}
-
-Qt::ToolBarAreas QToolBar::allowedAreas() const
-{
- Q_D(const QToolBar);
-#ifdef Q_WS_MAC
- if (QMainWindow *window = qobject_cast<QMainWindow *>(parentWidget())) {
- if (window->unifiedTitleAndToolBarOnMac()) // Don't allow drags to the top (for now).
- return (d->allowedAreas & ~Qt::TopToolBarArea);
- }
-#endif
- return d->allowedAreas;
-}
-
-/*! \property QToolBar::orientation
- \brief orientation of the toolbar
-
- The default is Qt::Horizontal.
-
- This function should not be used when the toolbar is managed
- by QMainWindow. You can use QMainWindow::addToolBar() or
- QMainWindow::insertToolBar() if you wish to move a toolbar (that
- is already added to a main window) to another Qt::ToolBarArea.
-*/
-
-void QToolBar::setOrientation(Qt::Orientation orientation)
-{
- Q_D(QToolBar);
- if (orientation == d->orientation)
- return;
-
- d->orientation = orientation;
-
- if (orientation == Qt::Vertical)
- setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred));
- else
- setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed));
-
- d->layout->invalidate();
- d->layout->activate();
-
- emit orientationChanged(d->orientation);
-}
-
-Qt::Orientation QToolBar::orientation() const
-{ Q_D(const QToolBar); return d->orientation; }
-
-/*!
- \property QToolBar::iconSize
- \brief size of icons in the toolbar.
-
- The default size is determined by the application's style and is
- derived from the QStyle::PM_ToolBarIconSize pixel metric. It is
- the maximum size an icon can have. Icons of smaller size will not
- be scaled up.
-*/
-
-QSize QToolBar::iconSize() const
-{ Q_D(const QToolBar); return d->iconSize; }
-
-void QToolBar::setIconSize(const QSize &iconSize)
-{
- Q_D(QToolBar);
- QSize sz = iconSize;
- if (!sz.isValid()) {
- QMainWindow *mw = qobject_cast<QMainWindow *>(parentWidget());
- if (mw && mw->layout()) {
- QLayout *layout = mw->layout();
- int i = 0;
- QLayoutItem *item = 0;
- do {
- item = layout->itemAt(i++);
- if (item && (item->widget() == this))
- sz = mw->iconSize();
- } while (!sz.isValid() && item != 0);
- }
- }
- if (!sz.isValid()) {
- const int metric = style()->pixelMetric(QStyle::PM_ToolBarIconSize, 0, this);
- sz = QSize(metric, metric);
- }
- if (d->iconSize != sz) {
- d->iconSize = sz;
- setMinimumSize(0, 0);
- emit iconSizeChanged(d->iconSize);
- }
- d->explicitIconSize = iconSize.isValid();
-
- d->layout->invalidate();
-}
-
-/*!
- \property QToolBar::toolButtonStyle
- \brief the style of toolbar buttons
-
- This property defines the style of all tool buttons that are added
- as \l{QAction}s. Note that if you add a QToolButton with the
- addWidget() method, it will not get this button style.
-
- The default is Qt::ToolButtonIconOnly.
-*/
-
-Qt::ToolButtonStyle QToolBar::toolButtonStyle() const
-{ Q_D(const QToolBar); return d->toolButtonStyle; }
-
-void QToolBar::setToolButtonStyle(Qt::ToolButtonStyle toolButtonStyle)
-{
- Q_D(QToolBar);
- d->explicitToolButtonStyle = true;
- if (d->toolButtonStyle == toolButtonStyle)
- return;
- d->toolButtonStyle = toolButtonStyle;
- setMinimumSize(0, 0);
- emit toolButtonStyleChanged(d->toolButtonStyle);
-}
-
-/*!
- Removes all actions from the toolbar.
-
- \sa removeAction()
-*/
-void QToolBar::clear()
-{
- QList<QAction *> actions = this->actions();
- for(int i = 0; i < actions.size(); i++)
- removeAction(actions.at(i));
-}
-
-/*!
- \overload
-
- Creates a new action with the given \a text. This action is added to
- the end of the toolbar.
-*/
-QAction *QToolBar::addAction(const QString &text)
-{
- QAction *action = new QAction(text, this);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- Creates a new action with the given \a icon and \a text. This
- action is added to the end of the toolbar.
-*/
-QAction *QToolBar::addAction(const QIcon &icon, const QString &text)
-{
- QAction *action = new QAction(icon, text, this);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- Creates a new action with the given \a text. This action is added to
- the end of the toolbar. The action's \link QAction::triggered()
- triggered()\endlink signal is connected to \a member in \a
- receiver.
-*/
-QAction *QToolBar::addAction(const QString &text,
- const QObject *receiver, const char* member)
-{
- QAction *action = new QAction(text, this);
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
-}
-
-/*!
- \overload
-
- Creates a new action with the icon \a icon and text \a text. This
- action is added to the end of the toolbar. The action's \link
- QAction::triggered() triggered()\endlink signal is connected to \a
- member in \a receiver.
-*/
-QAction *QToolBar::addAction(const QIcon &icon, const QString &text,
- const QObject *receiver, const char* member)
-{
- QAction *action = new QAction(icon, text, this);
- QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
- addAction(action);
- return action;
-}
-
-/*!
- Adds a separator to the end of the toolbar.
-
- \sa insertSeparator()
-*/
-QAction *QToolBar::addSeparator()
-{
- QAction *action = new QAction(this);
- action->setSeparator(true);
- addAction(action);
- return action;
-}
-
-/*!
- Inserts a separator into the toolbar in front of the toolbar
- item associated with the \a before action.
-
- \sa addSeparator()
-*/
-QAction *QToolBar::insertSeparator(QAction *before)
-{
- QAction *action = new QAction(this);
- action->setSeparator(true);
- insertAction(before, action);
- return action;
-}
-
-/*!
- Adds the given \a widget to the toolbar as the toolbar's last
- item.
-
- The toolbar takes ownership of \a widget.
-
- If you add a QToolButton with this method, the tools bar's
- Qt::ToolButtonStyle will not be respected.
-
- \note You should use QAction::setVisible() to change the
- visibility of the widget. Using QWidget::setVisible(),
- QWidget::show() and QWidget::hide() does not work.
-
- \sa insertWidget()
-*/
-QAction *QToolBar::addWidget(QWidget *widget)
-{
- QWidgetAction *action = new QWidgetAction(this);
- action->setDefaultWidget(widget);
- action->d_func()->autoCreated = true;
- addAction(action);
- return action;
-}
-
-/*!
- Inserts the given \a widget in front of the toolbar item
- associated with the \a before action.
-
- Note: You should use QAction::setVisible() to change the
- visibility of the widget. Using QWidget::setVisible(),
- QWidget::show() and QWidget::hide() does not work.
-
- \sa addWidget()
-*/
-QAction *QToolBar::insertWidget(QAction *before, QWidget *widget)
-{
- QWidgetAction *action = new QWidgetAction(this);
- action->setDefaultWidget(widget);
- action->d_func()->autoCreated = true;
- insertAction(before, action);
- return action;
-}
-
-/*!
- \internal
-
- Returns the geometry of the toolbar item associated with the given
- \a action, or an invalid QRect if no matching item is found.
-*/
-QRect QToolBar::actionGeometry(QAction *action) const
-{
- Q_D(const QToolBar);
-
- int index = d->layout->indexOf(action);
- if (index == -1)
- return QRect();
- return d->layout->itemAt(index)->widget()->geometry();
-}
-
-/*!
- Returns the action at point \a p. This function returns zero if no
- action was found.
-
- \sa QWidget::childAt()
-*/
-QAction *QToolBar::actionAt(const QPoint &p) const
-{
- Q_D(const QToolBar);
- QWidget *widget = childAt(p);
- int index = d->layout->indexOf(widget);
- if (index == -1)
- return 0;
- QLayoutItem *item = d->layout->itemAt(index);
- return static_cast<QToolBarItem*>(item)->action;
-}
-
-/*! \fn QAction *QToolBar::actionAt(int x, int y) const
- \overload
-
- Returns the action at the point \a x, \a y. This function returns
- zero if no action was found.
-*/
-
-/*! \reimp */
-void QToolBar::actionEvent(QActionEvent *event)
-{
- Q_D(QToolBar);
- QAction *action = event->action();
- QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(action);
-
- switch (event->type()) {
- case QEvent::ActionAdded: {
- Q_ASSERT_X(widgetAction == 0 || d->layout->indexOf(widgetAction) == -1,
- "QToolBar", "widgets cannot be inserted multiple times");
-
- // reparent the action to this toolbar if it has been created
- // using the addAction(text) etc. convenience functions, to
- // preserve Qt 4.1.x behavior. The widget is already
- // reparented to us due to the createWidget call inside
- // createItem()
- if (widgetAction != 0 && widgetAction->d_func()->autoCreated)
- widgetAction->setParent(this);
-
- int index = d->layout->count();
- if (event->before()) {
- index = d->layout->indexOf(event->before());
- Q_ASSERT_X(index != -1, "QToolBar::insertAction", "internal error");
- }
- d->layout->insertAction(index, action);
- break;
- }
-
- case QEvent::ActionChanged:
- d->layout->invalidate();
- break;
-
- case QEvent::ActionRemoved: {
- int index = d->layout->indexOf(action);
- if (index != -1) {
- delete d->layout->takeAt(index);
- }
- break;
- }
-
- default:
- Q_ASSERT_X(false, "QToolBar::actionEvent", "internal error");
- }
-}
-
-/*! \reimp */
-void QToolBar::changeEvent(QEvent *event)
-{
- Q_D(QToolBar);
- switch (event->type()) {
- case QEvent::WindowTitleChange:
- d->toggleViewAction->setText(windowTitle());
- break;
- case QEvent::StyleChange:
- d->layout->invalidate();
- if (!d->explicitIconSize)
- setIconSize(QSize());
- d->layout->updateMarginAndSpacing();
- break;
- case QEvent::LayoutDirectionChange:
- d->layout->invalidate();
- break;
- default:
- break;
- }
- QWidget::changeEvent(event);
-}
-
-/*! \reimp */
-void QToolBar::paintEvent(QPaintEvent *)
-{
- Q_D(QToolBar);
-
- QPainter p(this);
- QStyle *style = this->style();
- QStyleOptionToolBar opt;
- initStyleOption(&opt);
-
- if (d->layout->expanded || d->layout->animating || isWindow()) {
- //if the toolbar is expended, we need to fill the background with the window color
- //because some styles may expects that.
- p.fillRect(opt.rect, palette().background());
- style->drawControl(QStyle::CE_ToolBar, &opt, &p, this);
- style->drawPrimitive(QStyle::PE_FrameMenu, &opt, &p, this);
- } else {
- style->drawControl(QStyle::CE_ToolBar, &opt, &p, this);
- }
-
- opt.rect = style->subElementRect(QStyle::SE_ToolBarHandle, &opt, this);
- if (opt.rect.isValid())
- style->drawPrimitive(QStyle::PE_IndicatorToolBarHandle, &opt, &p, this);
-}
-
-/*
- Checks if an expanded toolbar has to wait for this popup to close before
- the toolbar collapses. This is true if
- 1) the popup has the toolbar in its parent chain,
- 2) the popup is a menu whose menuAction is somewhere in the toolbar.
-*/
-static bool waitForPopup(QToolBar *tb, QWidget *popup)
-{
- if (popup == 0 || popup->isHidden())
- return false;
-
- QWidget *w = popup;
- while (w != 0) {
- if (w == tb)
- return true;
- w = w->parentWidget();
- }
-
- QMenu *menu = qobject_cast<QMenu*>(popup);
- if (menu == 0)
- return false;
-
- QAction *action = menu->menuAction();
- QList<QWidget*> widgets = action->associatedWidgets();
- for (int i = 0; i < widgets.count(); ++i) {
- if (waitForPopup(tb, widgets.at(i)))
- return true;
- }
-
- return false;
-}
-
-#if defined(Q_WS_MAC)
-static bool toolbarInUnifiedToolBar(QToolBar *toolbar)
-{
- const QMainWindow *mainWindow = qobject_cast<const QMainWindow *>(toolbar->parentWidget());
- return mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()
- && mainWindow->toolBarArea(toolbar) == Qt::TopToolBarArea;
-}
-#endif
-
-/*! \reimp */
-bool QToolBar::event(QEvent *event)
-{
- Q_D(QToolBar);
-
- switch (event->type()) {
- case QEvent::Timer:
- if (d->waitForPopupTimer.timerId() == static_cast<QTimerEvent*>(event)->timerId()) {
- QWidget *w = QApplication::activePopupWidget();
- if (!waitForPopup(this, w)) {
- d->waitForPopupTimer.stop();
- if (!this->underMouse())
- d->layout->setExpanded(false);
- }
- }
- break;
- case QEvent::Hide:
- if (!isHidden())
- break;
- // fallthrough intended
- case QEvent::Show:
- d->toggleViewAction->setChecked(event->type() == QEvent::Show);
- emit visibilityChanged(event->type() == QEvent::Show);
-#if defined(Q_WS_MAC)
- if (toolbarInUnifiedToolBar(this)) {
- // I can static_cast because I did the qobject_cast in the if above, therefore
- // we must have a QMainWindowLayout here.
- QMainWindowLayout *mwLayout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(parentWidget()));
- mwLayout->fixSizeInUnifiedToolbar(this);
- mwLayout->syncUnifiedToolbarVisibility();
- }
-# if !defined(QT_MAC_USE_COCOA)
- // Fall through
- case QEvent::LayoutRequest: {
- // There's currently no way to invalidate the size and let
- // HIToolbar know about it. This forces a re-check.
- int earlyResult = -1;
- if (QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parentWidget())) {
- bool needUpdate = true;
- if (event->type() == QEvent::LayoutRequest) {
- QSize oldSizeHint = sizeHint();
- earlyResult = QWidget::event(event) ? 1 : 0;
- needUpdate = oldSizeHint != sizeHint();
- }
-
- if (needUpdate) {
- OSWindowRef windowRef = qt_mac_window_for(mainWindow);
- if (toolbarInUnifiedToolBar(this)
- && macWindowToolbarIsVisible(windowRef)) {
- DisableScreenUpdates();
- macWindowToolbarShow(this, false);
- macWindowToolbarShow(this, true);
- EnableScreenUpdates();
- }
- }
-
- if (earlyResult != -1)
- return earlyResult;
- }
- }
-# endif // !QT_MAC_USE_COCOA
-#endif // Q_WS_MAC
- break;
- case QEvent::ParentChange:
- d->layout->checkUsePopupMenu();
-#if defined(Q_WS_MAC)
- if (parentWidget() && parentWidget()->isWindow())
- qt_mac_updateToolBarButtonHint(parentWidget());
-#endif
- break;
-
- case QEvent::MouseButtonPress: {
- if (d->mousePressEvent(static_cast<QMouseEvent*>(event)))
- return true;
- break;
- }
- case QEvent::MouseButtonRelease:
- if (d->mouseReleaseEvent(static_cast<QMouseEvent*>(event)))
- return true;
- break;
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- // there's nothing special to do here and we don't want to update the whole widget
- return true;
- case QEvent::HoverMove: {
-#ifndef QT_NO_CURSOR
- QHoverEvent *e = static_cast<QHoverEvent*>(event);
- QStyleOptionToolBar opt;
- initStyleOption(&opt);
- if (style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, this).contains(e->pos()))
- setCursor(Qt::SizeAllCursor);
- else
- unsetCursor();
-#endif
- break;
- }
- case QEvent::MouseMove:
- if (d->mouseMoveEvent(static_cast<QMouseEvent*>(event)))
- return true;
- break;
-#ifdef Q_WS_WINCE
- case QEvent::ContextMenu:
- {
- QContextMenuEvent* contextMenuEvent = static_cast<QContextMenuEvent*>(event);
- QWidget* child = childAt(contextMenuEvent->pos());
- QAbstractButton* button = qobject_cast<QAbstractButton*>(child);
- if (button)
- button->setDown(false);
- }
- break;
-#endif
- case QEvent::Leave:
- if (d->state != 0 && d->state->dragging) {
-#ifdef Q_OS_WIN
- // This is a workaround for loosing the mouse on Vista.
- QPoint pos = QCursor::pos();
- QMouseEvent fake(QEvent::MouseMove, mapFromGlobal(pos), pos, Qt::NoButton,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- d->mouseMoveEvent(&fake);
-#endif
- } else {
- if (!d->layout->expanded)
- break;
-
- QWidget *w = QApplication::activePopupWidget();
- if (waitForPopup(this, w)) {
- d->waitForPopupTimer.start(POPUP_TIMER_INTERVAL, this);
- break;
- }
-
- d->waitForPopupTimer.stop();
- d->layout->setExpanded(false);
- break;
- }
- default:
- break;
- }
- return QWidget::event(event);
-}
-
-/*!
- Returns a checkable action that can be used to show or hide this
- toolbar.
-
- The action's text is set to the toolbar's window title.
-
- \sa QAction::text QWidget::windowTitle
-*/
-QAction *QToolBar::toggleViewAction() const
-{ Q_D(const QToolBar); return d->toggleViewAction; }
-
-/*!
- \fn void QToolBar::setLabel(const QString &label)
-
- Use setWindowTitle() instead.
-*/
-
-/*!
- \fn QString QToolBar::label() const
-
- Use windowTitle() instead.
-*/
-
-/*!
- \since 4.2
-
- Returns the widget associated with the specified \a action.
-
- \sa addWidget()
-*/
-QWidget *QToolBar::widgetForAction(QAction *action) const
-{
- Q_D(const QToolBar);
-
- int index = d->layout->indexOf(action);
- if (index == -1)
- return 0;
-
- return d->layout->itemAt(index)->widget();
-}
-
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-/*!
- \internal
-*/
-void QToolBar::initStyleOption(QStyleOptionToolBar *option) const
-{
- Q_D(const QToolBar);
-
- if (!option)
- return;
-
- option->initFrom(this);
- if (orientation() == Qt::Horizontal)
- option->state |= QStyle::State_Horizontal;
- option->lineWidth = style()->pixelMetric(QStyle::PM_ToolBarFrameWidth, 0, this);
- option->features = d->layout->movable()
- ? QStyleOptionToolBar::Movable
- : QStyleOptionToolBar::None;
- // if the tool bar is not in a QMainWindow, this will make the painting right
- option->toolBarArea = Qt::NoToolBarArea;
-
- // Add more styleoptions if the toolbar has been added to a mainwindow.
- QMainWindow *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
-
- if (!mainWindow)
- return;
-
- QMainWindowLayout *layout = qt_mainwindow_layout(mainWindow);
- Q_ASSERT_X(layout != 0, "QToolBar::initStyleOption()",
- "QMainWindow->layout() != QMainWindowLayout");
-
- layout->getStyleOptionInfo(option, const_cast<QToolBar *>(this));
-}
-
-/*!
- \reimp
-*/
-void QToolBar::childEvent(QChildEvent *event) // ### remove me in 5.0
-{
- QWidget::childEvent(event);
-}
-
-/*!
- \reimp
-*/
-void QToolBar::resizeEvent(QResizeEvent *event) // ### remove me in 5.0
-{
- QWidget::resizeEvent(event);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtoolbar.cpp"
-
-#endif // QT_NO_TOOLBAR
diff --git a/src/gui/widgets/qtoolbar.h b/src/gui/widgets/qtoolbar.h
deleted file mode 100644
index 116086ae7a..0000000000
--- a/src/gui/widgets/qtoolbar.h
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICTOOLBAR_H
-#define QDYNAMICTOOLBAR_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TOOLBAR
-
-class QToolBarPrivate;
-
-class QAction;
-class QIcon;
-class QMainWindow;
-class QStyleOptionToolBar;
-
-class Q_GUI_EXPORT QToolBar : public QWidget
-{
- Q_OBJECT
-
- Q_PROPERTY(bool movable READ isMovable WRITE setMovable
- DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) != 0)
- NOTIFY movableChanged)
- Q_PROPERTY(Qt::ToolBarAreas allowedAreas READ allowedAreas WRITE setAllowedAreas
- DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) != 0)
- NOTIFY allowedAreasChanged)
- Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation
- DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) == 0)
- NOTIFY orientationChanged)
- Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize NOTIFY iconSizeChanged)
- Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle
- NOTIFY toolButtonStyleChanged)
- Q_PROPERTY(bool floating READ isFloating)
- Q_PROPERTY(bool floatable READ isFloatable WRITE setFloatable)
-
-public:
- explicit QToolBar(const QString &title, QWidget *parent = 0);
- explicit QToolBar(QWidget *parent = 0);
- ~QToolBar();
-
- void setMovable(bool movable);
- bool isMovable() const;
-
- void setAllowedAreas(Qt::ToolBarAreas areas);
- Qt::ToolBarAreas allowedAreas() const;
-
- inline bool isAreaAllowed(Qt::ToolBarArea area) const
- { return (allowedAreas() & area) == area; }
-
- void setOrientation(Qt::Orientation orientation);
- Qt::Orientation orientation() const;
-
- void clear();
-
-#ifdef Q_NO_USING_KEYWORD
- inline void addAction(QAction *action)
- { QWidget::addAction(action); }
-#else
- using QWidget::addAction;
-#endif
-
- QAction *addAction(const QString &text);
- QAction *addAction(const QIcon &icon, const QString &text);
- QAction *addAction(const QString &text, const QObject *receiver, const char* member);
- QAction *addAction(const QIcon &icon, const QString &text,
- const QObject *receiver, const char* member);
-
- QAction *addSeparator();
- QAction *insertSeparator(QAction *before);
-
- QAction *addWidget(QWidget *widget);
- QAction *insertWidget(QAction *before, QWidget *widget);
-
- QRect actionGeometry(QAction *action) const;
- QAction *actionAt(const QPoint &p) const;
- inline QAction *actionAt(int x, int y) const;
-
- QAction *toggleViewAction() const;
-
- QSize iconSize() const;
- Qt::ToolButtonStyle toolButtonStyle() const;
-
- QWidget *widgetForAction(QAction *action) const;
-
- bool isFloatable() const;
- void setFloatable(bool floatable);
- bool isFloating() const;
-
-public Q_SLOTS:
- void setIconSize(const QSize &iconSize);
- void setToolButtonStyle(Qt::ToolButtonStyle toolButtonStyle);
-
-Q_SIGNALS:
- void actionTriggered(QAction *action);
- void movableChanged(bool movable);
- void allowedAreasChanged(Qt::ToolBarAreas allowedAreas);
- void orientationChanged(Qt::Orientation orientation);
- void iconSizeChanged(const QSize &iconSize);
- void toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle);
- void topLevelChanged(bool topLevel);
- void visibilityChanged(bool visible);
-
-protected:
- void actionEvent(QActionEvent *event);
- void changeEvent(QEvent *event);
- void childEvent(QChildEvent *event);
- void paintEvent(QPaintEvent *event);
- void resizeEvent(QResizeEvent *event);
- bool event(QEvent *event);
- void initStyleOption(QStyleOptionToolBar *option) const;
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QToolBar(QWidget *parent, const char *name);
- inline QT3_SUPPORT void setLabel(const QString &label)
- { setWindowTitle(label); }
- inline QT3_SUPPORT QString label() const
- { return windowTitle(); }
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QToolBar)
- Q_DISABLE_COPY(QToolBar)
- Q_PRIVATE_SLOT(d_func(), void _q_toggleView(bool))
- Q_PRIVATE_SLOT(d_func(), void _q_updateIconSize(const QSize &))
- Q_PRIVATE_SLOT(d_func(), void _q_updateToolButtonStyle(Qt::ToolButtonStyle))
-
- friend class QMainWindow;
- friend class QMainWindowLayout;
- friend class QToolBarLayout;
- friend class QToolBarAreaLayout;
-};
-
-inline QAction *QToolBar::actionAt(int ax, int ay) const
-{ return actionAt(QPoint(ax, ay)); }
-
-#endif // QT_NO_TOOLBAR
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QDYNAMICTOOLBAR_H
diff --git a/src/gui/widgets/qtoolbar_p.h b/src/gui/widgets/qtoolbar_p.h
deleted file mode 100644
index 3970c359e1..0000000000
--- a/src/gui/widgets/qtoolbar_p.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICTOOLBAR_P_H
-#define QDYNAMICTOOLBAR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qtoolbar.h"
-#include "QtGui/qaction.h"
-#include "private/qwidget_p.h"
-#include <QtCore/qbasictimer.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_TOOLBAR
-
-class QToolBarLayout;
-class QTimer;
-
-class QToolBarPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QToolBar)
-
-public:
- inline QToolBarPrivate()
- : explicitIconSize(false), explicitToolButtonStyle(false), movable(true), floatable(true),
- allowedAreas(Qt::AllToolBarAreas), orientation(Qt::Horizontal),
- toolButtonStyle(Qt::ToolButtonIconOnly),
- layout(0), state(0)
-#ifdef Q_WS_MAC
- , macWindowDragging(false)
-#endif
- { }
-
- void init();
- void actionTriggered();
- void _q_toggleView(bool b);
- void _q_updateIconSize(const QSize &sz);
- void _q_updateToolButtonStyle(Qt::ToolButtonStyle style);
-
- bool explicitIconSize;
- bool explicitToolButtonStyle;
- bool movable;
- bool floatable;
- Qt::ToolBarAreas allowedAreas;
- Qt::Orientation orientation;
- Qt::ToolButtonStyle toolButtonStyle;
- QSize iconSize;
-
- QAction *toggleViewAction;
-
- QToolBarLayout *layout;
-
- struct DragState {
- QPoint pressPos;
- bool dragging;
- bool moving;
- QLayoutItem *widgetItem;
- };
- DragState *state;
-
-#ifdef Q_WS_MAC
- bool macWindowDragging;
- QPoint macWindowDragPressPosition;
-#endif
-
- bool mousePressEvent(QMouseEvent *e);
- bool mouseReleaseEvent(QMouseEvent *e);
- bool mouseMoveEvent(QMouseEvent *e);
-
- void updateWindowFlags(bool floating, bool unplug = false);
- void setWindowState(bool floating, bool unplug = false, const QRect &rect = QRect());
- void initDrag(const QPoint &pos);
- void startDrag(bool moving = false);
- void endDrag();
-
- void unplug(const QRect &r);
- void plug(const QRect &r);
-
- QBasicTimer waitForPopupTimer;
-};
-
-#endif // QT_NO_TOOLBAR
-
-QT_END_NAMESPACE
-
-#endif // QDYNAMICTOOLBAR_P_H
diff --git a/src/gui/widgets/qtoolbararealayout.cpp b/src/gui/widgets/qtoolbararealayout.cpp
deleted file mode 100644
index 05986e4ac5..0000000000
--- a/src/gui/widgets/qtoolbararealayout.cpp
+++ /dev/null
@@ -1,1391 +0,0 @@
-/****************************************************************************
-**
-** 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 <QWidgetItem>
-#include <QToolBar>
-#include <QStyleOption>
-#include <QApplication>
-#include <qdebug.h>
-
-#include "qtoolbararealayout_p.h"
-#include "qmainwindowlayout_p.h"
-#include "qwidgetanimator_p.h"
-#include "qtoolbarlayout_p.h"
-#include "qtoolbar_p.h"
-
-/******************************************************************************
-** QToolBarAreaLayoutItem
-*/
-
-#ifndef QT_NO_TOOLBAR
-
-QT_BEGIN_NAMESPACE
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *mainWindow);
-
-QSize QToolBarAreaLayoutItem::minimumSize() const
-{
- if (skip())
- return QSize(0, 0);
- return qSmartMinSize(static_cast<QWidgetItem*>(widgetItem));
-}
-
-QSize QToolBarAreaLayoutItem::sizeHint() const
-{
- if (skip())
- return QSize(0, 0);
-
- return realSizeHint();
-}
-
-//returns the real size hint not taking into account the visibility of the widget
-QSize QToolBarAreaLayoutItem::realSizeHint() const
-{
- QWidget *wid = widgetItem->widget();
- QSize s = wid->sizeHint().expandedTo(wid->minimumSizeHint());
- if (wid->sizePolicy().horizontalPolicy() == QSizePolicy::Ignored)
- s.setWidth(0);
- if (wid->sizePolicy().verticalPolicy() == QSizePolicy::Ignored)
- s.setHeight(0);
- s = s.boundedTo(wid->maximumSize())
- .expandedTo(wid->minimumSize());
- return s;
-}
-
-bool QToolBarAreaLayoutItem::skip() const
-{
- if (gap)
- return false;
- return widgetItem == 0 || widgetItem->isEmpty();
-}
-
-/******************************************************************************
-** QToolBarAreaLayoutLine
-*/
-
-QToolBarAreaLayoutLine::QToolBarAreaLayoutLine(Qt::Orientation orientation)
- : o(orientation)
-{
-}
-
-QSize QToolBarAreaLayoutLine::sizeHint() const
-{
- int a = 0, b = 0;
- for (int i = 0; i < toolBarItems.count(); ++i) {
- const QToolBarAreaLayoutItem &item = toolBarItems.at(i);
- if (item.skip())
- continue;
-
- QSize sh = item.sizeHint();
- a += item.preferredSize > 0 ? item.preferredSize : pick(o, sh);
- b = qMax(b, perp(o, sh));
- }
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
- return result;
-}
-
-QSize QToolBarAreaLayoutLine::minimumSize() const
-{
- int a = 0, b = 0;
- for (int i = 0; i < toolBarItems.count(); ++i) {
- const QToolBarAreaLayoutItem &item = toolBarItems[i];
- if (item.skip())
- continue;
-
- QSize ms = item.minimumSize();
- a += pick(o, ms);
- b = qMax(b, perp(o, ms));
- }
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
- return result;
-}
-
-void QToolBarAreaLayoutLine::fitLayout()
-{
- int last = -1;
- int min = pick(o, minimumSize());
- int space = pick(o, rect.size());
- int extra = qMax(0, space - min);
-
- for (int i = 0; i < toolBarItems.count(); ++i) {
- QToolBarAreaLayoutItem &item = toolBarItems[i];
- if (item.skip())
- continue;
-
- if (QToolBarLayout *tblayout = qobject_cast<QToolBarLayout*>(item.widgetItem->widget()->layout()))
- tblayout->checkUsePopupMenu();
-
- const int itemMin = pick(o, item.minimumSize());
- //preferredSize is the default if it is set, otherwise, we take the sizehint
- item.size = item.preferredSize > 0 ? item.preferredSize : pick(o, item.sizeHint());
-
- //the extraspace is the space above the item minimum sizehint
- const int extraSpace = qMin(item.size - itemMin, extra);
- item.size = itemMin + extraSpace; //that is the real size
-
- extra -= extraSpace;
-
- last = i;
- }
-
- // calculate the positions from the sizes
- int pos = 0;
- for (int i = 0; i < toolBarItems.count(); ++i) {
- QToolBarAreaLayoutItem &item = toolBarItems[i];
- if (item.skip())
- continue;
-
- item.pos = pos;
- if (i == last) // stretch the last item to the end of the line
- item.size = qMax(0, pick(o, rect.size()) - item.pos);
- pos += item.size;
- }
-}
-
-bool QToolBarAreaLayoutLine::skip() const
-{
- for (int i = 0; i < toolBarItems.count(); ++i) {
- if (!toolBarItems.at(i).skip())
- return false;
- }
- return true;
-}
-
-/******************************************************************************
-** QToolBarAreaLayoutInfo
-*/
-
-QToolBarAreaLayoutInfo::QToolBarAreaLayoutInfo(QInternal::DockPosition pos)
- : dockPos(pos), dirty(false)
-{
- switch (pos) {
- case QInternal::LeftDock:
- case QInternal::RightDock:
- o = Qt::Vertical;
- break;
- case QInternal::TopDock:
- case QInternal::BottomDock:
- o = Qt::Horizontal;
- break;
- default:
- o = Qt::Horizontal;
- break;
- }
-}
-
-QSize QToolBarAreaLayoutInfo::sizeHint() const
-{
- int a = 0, b = 0;
- for (int i = 0; i < lines.count(); ++i) {
- const QToolBarAreaLayoutLine &l = lines.at(i);
- if (l.skip())
- continue;
-
- QSize hint = l.sizeHint();
- a = qMax(a, pick(o, hint));
- b += perp(o, hint);
- }
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
- return result;
-}
-
-QSize QToolBarAreaLayoutInfo::minimumSize() const
-{
- int a = 0, b = 0;
- for (int i = 0; i < lines.count(); ++i) {
- const QToolBarAreaLayoutLine &l = lines.at(i);
- if (l.skip())
- continue;
-
- QSize m = l.minimumSize();
- a = qMax(a, pick(o, m));
- b += perp(o, m);
- }
-
- QSize result;
- rpick(o, result) = a;
- rperp(o, result) = b;
-
- return result;
-}
-
-void QToolBarAreaLayoutInfo::fitLayout()
-{
- dirty = false;
-
- int b = 0;
-
- bool reverse = dockPos == QInternal::RightDock || dockPos == QInternal::BottomDock;
-
- int i = reverse ? lines.count() - 1 : 0;
- for (;;) {
- if ((reverse && i < 0) || (!reverse && i == lines.count()))
- break;
-
- QToolBarAreaLayoutLine &l = lines[i];
- if (!l.skip()) {
- if (o == Qt::Horizontal) {
- l.rect.setLeft(rect.left());
- l.rect.setRight(rect.right());
- l.rect.setTop(b + rect.top());
- b += l.sizeHint().height();
- l.rect.setBottom(b - 1 + rect.top());
- } else {
- l.rect.setTop(rect.top());
- l.rect.setBottom(rect.bottom());
- l.rect.setLeft(b + rect.left());
- b += l.sizeHint().width();
- l.rect.setRight(b - 1 + rect.left());
- }
-
- l.fitLayout();
- }
-
- i += reverse ? -1 : 1;
- }
-}
-
-QLayoutItem *QToolBarAreaLayoutInfo::insertToolBar(QToolBar *before, QToolBar *toolBar)
-{
- toolBar->setOrientation(o);
- QLayoutItem *item = new QWidgetItemV2(toolBar);
- insertItem(before, item);
- return item;
-}
-
-void QToolBarAreaLayoutInfo::insertItem(QToolBar *before, QLayoutItem *item)
-{
- if (before == 0) {
- if (lines.isEmpty())
- lines.append(QToolBarAreaLayoutLine(o));
- lines.last().toolBarItems.append(item);
- return;
- }
-
- for (int j = 0; j < lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if (line.toolBarItems.at(k).widgetItem->widget() == before) {
- line.toolBarItems.insert(k, item);
- return;
- }
- }
- }
-}
-
-void QToolBarAreaLayoutInfo::removeToolBar(QToolBar *toolBar)
-{
- for (int j = 0; j < lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- QToolBarAreaLayoutItem &item = line.toolBarItems[k];
- if (item.widgetItem->widget() == toolBar) {
- delete item.widgetItem;
- item.widgetItem = 0;
- line.toolBarItems.removeAt(k);
-
- if (line.toolBarItems.isEmpty() && j < lines.count() - 1)
- lines.removeAt(j);
-
- return;
- }
- }
- }
-}
-
-void QToolBarAreaLayoutInfo::insertToolBarBreak(QToolBar *before)
-{
- if (before == 0) {
- if (!lines.isEmpty() && lines.last().toolBarItems.isEmpty())
- return;
- lines.append(QToolBarAreaLayoutLine(o));
- return;
- }
-
- for (int j = 0; j < lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if (line.toolBarItems.at(k).widgetItem->widget() == before) {
- if (k == 0)
- return;
-
- QToolBarAreaLayoutLine newLine(o);
- newLine.toolBarItems = line.toolBarItems.mid(k);
- line.toolBarItems = line.toolBarItems.mid(0, k);
- lines.insert(j + 1, newLine);
-
- return;
- }
- }
- }
-}
-
-void QToolBarAreaLayoutInfo::removeToolBarBreak(QToolBar *before)
-{
- for (int j = 0; j < lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = lines.at(j);
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if (line.toolBarItems.at(k).widgetItem->widget() == before) {
- if (k != 0)
- return;
- if (j == 0)
- return;
-
- lines[j - 1].toolBarItems += lines[j].toolBarItems;
- lines.removeAt(j);
-
- return;
- }
- }
- }
-}
-
-void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos)
-{
- if (dirty)
- fitLayout();
-
- dirty = true;
-
- if (o == Qt::Vertical)
- pos -= rect.top();
-
- //here we actually update the preferredSize for the line containing the toolbar so that we move it
- for (int j = 0; j < lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = lines[j];
-
- int previousIndex = -1;
- int minPos = 0;
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- QToolBarAreaLayoutItem &current = line.toolBarItems[k];
- if (current.widgetItem->widget() == toolbar) {
- int newPos = current.pos;
-
- if (previousIndex >= 0) {
- QToolBarAreaLayoutItem &previous = line.toolBarItems[previousIndex];
- if (pos < current.pos) {
- newPos = qMax(pos, minPos);
- } else {
- //we check the max value for the position (until everything at the right is "compressed")
- int maxPos = pick(o, rect.size());
- for(int l = k; l < line.toolBarItems.count(); ++l) {
- const QToolBarAreaLayoutItem &item = line.toolBarItems.at(l);
- if (!item.skip()) {
- maxPos -= pick(o, item.minimumSize());
- }
- }
- newPos = qMin(pos, maxPos);
- }
-
- //extra is the number of pixels to add to the previous toolbar
- int extra = newPos - current.pos;
-
- //we check if the previous is near its size hint
- //in which case we try to stick to it
- const int diff = pick(o, previous.sizeHint()) - (previous.size + extra);
- if (qAbs(diff) < QApplication::startDragDistance()) {
- //we stick to the default place and size
- extra += diff;
- }
-
- //update for the current item
- current.extendSize(line.o, -extra);
-
- if (extra >= 0) {
- previous.extendSize(line.o, extra);
- } else {
- //we need to push the toolbars on the left starting with previous
- extra = -extra; // we just need to know the number of pixels
- ///at this point we need to get extra pixels from the toolbars at the left
- for(int l = previousIndex; l >=0; --l) {
- QToolBarAreaLayoutItem &item = line.toolBarItems[l];
- if (!item.skip()) {
- const int minPreferredSize = pick(o, item.minimumSize());
- const int margin = item.size - minPreferredSize;
- if (margin < extra) {
- item.resize(line.o, minPreferredSize);
- extra -= margin;
- } else {
- item.extendSize(line.o, -extra);
- extra = 0;
- }
- }
- }
- Q_ASSERT(extra == 0);
- }
- } else {
- //the item is the first one, it should be at position 0
- }
-
- return;
-
- } else if (!current.skip()) {
- previousIndex = k;
- minPos += pick(o, current.minimumSize());
- }
- }
- }
-}
-
-
-QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance) const
-{
- int p = pick(o, pos);
-
- if (rect.contains(pos)) {
- for (int j = 0; j < lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = lines.at(j);
- if (line.skip())
- continue;
- if (!line.rect.contains(pos))
- continue;
-
- int k = 0;
- for (; k < line.toolBarItems.count(); ++k) {
- const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
- if (item.skip())
- continue;
-
- int size = qMin(item.size, pick(o, item.sizeHint()));
-
- if (p > item.pos + size)
- continue;
- if (p > item.pos + size/2)
- ++k;
- break;
- }
-
- QList<int> result;
- result << j << k;
- *minDistance = 0; //we found a perfect match
- return result;
- }
- } else {
- const int dist = distance(pos);
- //it will only return a path if the minDistance is higher than the current distance
- if (dist >= 0 && *minDistance > dist) {
- *minDistance = dist;
-
- QList<int> result;
- result << lines.count() << 0;
- return result;
- }
- }
-
- return QList<int>();
-}
-
-bool QToolBarAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *item)
-{
- Q_ASSERT(path.count() == 2);
- int j = path.first();
- if (j == lines.count())
- lines.append(QToolBarAreaLayoutLine(o));
-
- QToolBarAreaLayoutLine &line = lines[j];
- const int k = path.at(1);
-
- QToolBarAreaLayoutItem gap_item;
- gap_item.gap = true;
- gap_item.widgetItem = item;
-
- //update the previous item's preferred size
- for(int p = k - 1 ; p >= 0; --p) {
- QToolBarAreaLayoutItem &previous = line.toolBarItems[p];
- if (!previous.skip()) {
- //we found the previous one
- int previousSizeHint = pick(line.o, previous.sizeHint());
- int previousExtraSpace = previous.size - previousSizeHint;
-
- if (previousExtraSpace > 0) {
- //in this case we reset the space
- previous.preferredSize = -1;
- previous.size = previousSizeHint;
-
- gap_item.resize(o, previousExtraSpace);
- }
-
- break;
- }
- }
-
- line.toolBarItems.insert(k, gap_item);
- return true;
-
-}
-
-void QToolBarAreaLayoutInfo::clear()
-{
- lines.clear();
- rect = QRect();
-}
-
-QRect QToolBarAreaLayoutInfo::itemRect(const QList<int> &path) const
-{
- Q_ASSERT(path.count() == 2);
- int j = path.at(0);
- int k = path.at(1);
-
- const QToolBarAreaLayoutLine &line = lines.at(j);
- const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
-
- QRect result = line.rect;
-
- if (o == Qt::Horizontal) {
- result.setLeft(item.pos + line.rect.left());
- result.setWidth(item.size);
- } else {
- result.setTop(item.pos + line.rect.top());
- result.setHeight(item.size);
- }
-
- return result;
-}
-
-int QToolBarAreaLayoutInfo::distance(const QPoint &pos) const
-{
- switch (dockPos) {
- case QInternal::LeftDock:
- if (pos.y() < rect.bottom())
- return pos.x() - rect.right();
- case QInternal::RightDock:
- if (pos.y() < rect.bottom())
- return rect.left() - pos.x();
- case QInternal::TopDock:
- if (pos.x() < rect.right())
- return pos.y() - rect.bottom();
- case QInternal::BottomDock:
- if (pos.x() < rect.right())
- return rect.top() - pos.y();
- default:
- break;
- }
- return -1;
-}
-
-/******************************************************************************
-** QToolBarAreaLayout
-*/
-
-QToolBarAreaLayout::QToolBarAreaLayout(const QMainWindow *win) : mainWindow(win), visible(true)
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QInternal::DockPosition pos = static_cast<QInternal::DockPosition>(i);
- docks[i] = QToolBarAreaLayoutInfo(pos);
- }
-}
-
-QRect QToolBarAreaLayout::fitLayout()
-{
- if (!visible)
- return rect;
-
- QSize left_hint = docks[QInternal::LeftDock].sizeHint();
- QSize right_hint = docks[QInternal::RightDock].sizeHint();
- QSize top_hint = docks[QInternal::TopDock].sizeHint();
- QSize bottom_hint = docks[QInternal::BottomDock].sizeHint();
-
- QRect center = rect.adjusted(left_hint.width(), top_hint.height(),
- -right_hint.width(), -bottom_hint.height());
-
- docks[QInternal::TopDock].rect = QRect(rect.left(), rect.top(),
- rect.width(), top_hint.height());
- docks[QInternal::LeftDock].rect = QRect(rect.left(), center.top(),
- left_hint.width(), center.height());
- docks[QInternal::RightDock].rect = QRect(center.right() + 1, center.top(),
- right_hint.width(), center.height());
- docks[QInternal::BottomDock].rect = QRect(rect.left(), center.bottom() + 1,
- rect.width(), bottom_hint.height());
-
- if (!mainWindow->unifiedTitleAndToolBarOnMac()) {
- docks[QInternal::TopDock].fitLayout();
- }
- docks[QInternal::LeftDock].fitLayout();
- docks[QInternal::RightDock].fitLayout();
- docks[QInternal::BottomDock].fitLayout();
-
- return center;
-}
-
-QSize QToolBarAreaLayout::minimumSize(const QSize &centerMin) const
-{
- if (!visible)
- return centerMin;
-
- QSize result = centerMin;
-
- QSize left_min = docks[QInternal::LeftDock].minimumSize();
- QSize right_min = docks[QInternal::RightDock].minimumSize();
- QSize top_min = docks[QInternal::TopDock].minimumSize();
- QSize bottom_min = docks[QInternal::BottomDock].minimumSize();
-
- result.setWidth(qMax(top_min.width(), result.width()));
- result.setWidth(qMax(bottom_min.width(), result.width()));
- result.setHeight(qMax(left_min.height(), result.height()));
- result.setHeight(qMax(right_min.height(), result.height()));
-
- result.rwidth() += left_min.width() + right_min.width();
- result.rheight() += top_min.height() + bottom_min.height();
-
- return result;
-}
-
-QSize QToolBarAreaLayout::sizeHint(const QSize &centerHint) const
-{
- if (!visible)
- return centerHint;
-
- QSize result = centerHint;
-
- QSize left_hint = docks[QInternal::LeftDock].sizeHint();
- QSize right_hint = docks[QInternal::RightDock].sizeHint();
- QSize top_hint = docks[QInternal::TopDock].sizeHint();
- QSize bottom_hint = docks[QInternal::BottomDock].sizeHint();
-
- result.setWidth(qMax(top_hint.width(), result.width()));
- result.setWidth(qMax(bottom_hint.width(), result.width()));
- result.setHeight(qMax(left_hint.height(), result.height()));
- result.setHeight(qMax(right_hint.height(), result.height()));
-
- result.rwidth() += left_hint.width() + right_hint.width();
- result.rheight() += top_hint.height() + bottom_hint.height();
-
- return result;
-}
-
-QRect QToolBarAreaLayout::rectHint(const QRect &r) const
-{
- int coef = visible ? 1 : -1;
-
- QRect result = r;
-
- QSize left_hint = docks[QInternal::LeftDock].sizeHint();
- QSize right_hint = docks[QInternal::RightDock].sizeHint();
- QSize top_hint = docks[QInternal::TopDock].sizeHint();
- QSize bottom_hint = docks[QInternal::BottomDock].sizeHint();
-
- result.adjust(-left_hint.width()*coef, -top_hint.height()*coef,
- right_hint.width()*coef, bottom_hint.height()*coef);
-
- return result;
-}
-
-QLayoutItem *QToolBarAreaLayout::itemAt(int *x, int index) const
-{
- Q_ASSERT(x != 0);
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if ((*x)++ == index)
- return line.toolBarItems.at(k).widgetItem;
- }
- }
- }
-
- return 0;
-}
-
-QLayoutItem *QToolBarAreaLayout::takeAt(int *x, int index)
-{
- Q_ASSERT(x != 0);
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = dock.lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if ((*x)++ == index) {
- QLayoutItem *result = line.toolBarItems.takeAt(k).widgetItem;
- if (line.toolBarItems.isEmpty())
- dock.lines.removeAt(j);
- return result;
- }
- }
- }
- }
-
- return 0;
-}
-
-void QToolBarAreaLayout::deleteAllLayoutItems()
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = dock.lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- QToolBarAreaLayoutItem &item = line.toolBarItems[k];
- if (!item.gap)
- delete item.widgetItem;
- item.widgetItem = 0;
- }
- }
- }
-}
-
-QInternal::DockPosition QToolBarAreaLayout::findToolBar(QToolBar *toolBar) const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if (line.toolBarItems.at(k).widgetItem->widget() == toolBar)
- return static_cast<QInternal::DockPosition>(i);
- }
- }
- }
-
- return QInternal::DockCount;
-}
-
-QLayoutItem *QToolBarAreaLayout::insertToolBar(QToolBar *before, QToolBar *toolBar)
-{
- QInternal::DockPosition pos = findToolBar(before);
- if (pos == QInternal::DockCount)
- return 0;
-
- return docks[pos].insertToolBar(before, toolBar);
-}
-
-void QToolBarAreaLayout::removeToolBar(QToolBar *toolBar)
-{
- QInternal::DockPosition pos = findToolBar(toolBar);
- if (pos == QInternal::DockCount)
- return;
- docks[pos].removeToolBar(toolBar);
-}
-
-QLayoutItem *QToolBarAreaLayout::addToolBar(QInternal::DockPosition pos, QToolBar *toolBar)
-{
- return docks[pos].insertToolBar(0, toolBar);
-}
-
-void QToolBarAreaLayout::insertToolBarBreak(QToolBar *before)
-{
- QInternal::DockPosition pos = findToolBar(before);
- if (pos == QInternal::DockCount)
- return;
- docks[pos].insertToolBarBreak(before);
-}
-
-void QToolBarAreaLayout::removeToolBarBreak(QToolBar *before)
-{
- QInternal::DockPosition pos = findToolBar(before);
- if (pos == QInternal::DockCount)
- return;
- docks[pos].removeToolBarBreak(before);
-}
-
-void QToolBarAreaLayout::addToolBarBreak(QInternal::DockPosition pos)
-{
- docks[pos].insertToolBarBreak(0);
-}
-
-void QToolBarAreaLayout::moveToolBar(QToolBar *toolbar, int p)
-{
- QInternal::DockPosition pos = findToolBar(toolbar);
- if (pos == QInternal::DockCount)
- return;
- docks[pos].moveToolBar(toolbar, p);
-}
-
-
-void QToolBarAreaLayout::insertItem(QInternal::DockPosition pos, QLayoutItem *item)
-{
- if (docks[pos].lines.isEmpty())
- docks[pos].lines.append(QToolBarAreaLayoutLine(docks[pos].o));
- docks[pos].lines.last().toolBarItems.append(item);
-}
-
-void QToolBarAreaLayout::insertItem(QToolBar *before, QLayoutItem *item)
-{
- QInternal::DockPosition pos = findToolBar(before);
- if (pos == QInternal::DockCount)
- return;
-
- docks[pos].insertItem(before, item);
-}
-
-void QToolBarAreaLayout::apply(bool animate)
-{
- QMainWindowLayout *layout = qt_mainwindow_layout(mainWindow);
- Q_ASSERT(layout != 0);
-
- Qt::LayoutDirection dir = mainWindow->layoutDirection();
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
- if (line.skip())
- continue;
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
- if (item.skip() || item.gap)
- continue;
-
- QRect geo;
- if (visible) {
- if (line.o == Qt::Horizontal) {
- geo.setTop(line.rect.top());
- geo.setBottom(line.rect.bottom());
- geo.setLeft(line.rect.left() + item.pos);
- geo.setRight(line.rect.left() + item.pos + item.size - 1);
- } else {
- geo.setLeft(line.rect.left());
- geo.setRight(line.rect.right());
- geo.setTop(line.rect.top() + item.pos);
- geo.setBottom(line.rect.top() + item.pos + item.size - 1);
- }
- }
-
- QWidget *widget = item.widgetItem->widget();
- if (QToolBar *toolBar = qobject_cast<QToolBar*>(widget)) {
- QToolBarLayout *tbl = qobject_cast<QToolBarLayout*>(toolBar->layout());
- if (tbl->expanded) {
- QPoint tr = geo.topRight();
- QSize size = tbl->expandedSize(geo.size());
- geo.setSize(size);
- geo.moveTopRight(tr);
- if (geo.bottom() > rect.bottom())
- geo.moveBottom(rect.bottom());
- if (geo.right() > rect.right())
- geo.moveRight(rect.right());
- if (geo.left() < 0)
- geo.moveLeft(0);
- if (geo.top() < 0)
- geo.moveTop(0);
- }
- }
-
- if (visible && dock.o == Qt::Horizontal)
- geo = QStyle::visualRect(dir, line.rect, geo);
-
- layout->widgetAnimator.animate(widget, geo, animate);
- }
- }
- }
-}
-
-bool QToolBarAreaLayout::toolBarBreak(QToolBar *toolBar) const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if (line.toolBarItems.at(k).widgetItem->widget() == toolBar)
- return j > 0 && k == 0;
- }
- }
- }
-
- return false;
-}
-
-void QToolBarAreaLayout::getStyleOptionInfo(QStyleOptionToolBar *option, QToolBar *toolBar) const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- if (line.toolBarItems.at(k).widgetItem->widget() == toolBar) {
- if (line.toolBarItems.count() == 1)
- option->positionWithinLine = QStyleOptionToolBar::OnlyOne;
- else if (k == 0)
- option->positionWithinLine = QStyleOptionToolBar::Beginning;
- else if (k == line.toolBarItems.count() - 1)
- option->positionWithinLine = QStyleOptionToolBar::End;
- else
- option->positionWithinLine = QStyleOptionToolBar::Middle;
-
- if (dock.lines.count() == 1)
- option->positionOfLine = QStyleOptionToolBar::OnlyOne;
- else if (j == 0)
- option->positionOfLine = QStyleOptionToolBar::Beginning;
- else if (j == dock.lines.count() - 1)
- option->positionOfLine = QStyleOptionToolBar::End;
- else
- option->positionOfLine = QStyleOptionToolBar::Middle;
-
- return;
- }
- }
- }
- }
-}
-
-QList<int> QToolBarAreaLayout::indexOf(QWidget *toolBar) const
-{
- QList<int> result;
-
- bool found = false;
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
- if (!item.gap && item.widgetItem->widget() == toolBar) {
- found = true;
- result.prepend(k);
- break;
- }
- }
-
- if (found) {
- result.prepend(j);
- break;
- }
- }
-
- if (found) {
- result.prepend(i);
- break;
- }
- }
-
- return result;
-}
-
-//this functions returns the path to the possible gapindex for the position pos
-QList<int> QToolBarAreaLayout::gapIndex(const QPoint &pos) const
-{
- Qt::LayoutDirection dir = mainWindow->layoutDirection();
- int minDistance = 80; // when a dock area is empty, how "wide" is it?
- QList<int> ret; //return value
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QPoint p = pos;
- if (docks[i].o == Qt::Horizontal)
- p = QStyle::visualPos(dir, docks[i].rect, p);
- QList<int> result = docks[i].gapIndex(p, &minDistance);
- if (!result.isEmpty()) {
- result.prepend(i);
- ret = result;
- }
- }
-
- return ret;
-}
-
-QList<int> QToolBarAreaLayout::currentGapIndex() const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); k++) {
- if (line.toolBarItems[k].gap) {
- QList<int> result;
- result << i << j << k;
- return result;
- }
- }
- }
- }
- return QList<int>();
-}
-
-bool QToolBarAreaLayout::insertGap(const QList<int> &path, QLayoutItem *item)
-{
- Q_ASSERT(path.count() == 3);
- const int i = path.first();
- Q_ASSERT(i >= 0 && i < QInternal::DockCount);
- return docks[i].insertGap(path.mid(1), item);
-}
-
-void QToolBarAreaLayout::remove(const QList<int> &path)
-{
- Q_ASSERT(path.count() == 3);
- docks[path.at(0)].lines[path.at(1)].toolBarItems.removeAt(path.at(2));
-}
-
-void QToolBarAreaLayout::remove(QLayoutItem *item)
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- QToolBarAreaLayoutLine &line = dock.lines[j];
-
- for (int k = 0; k < line.toolBarItems.count(); k++) {
- if (line.toolBarItems[k].widgetItem == item) {
- line.toolBarItems.removeAt(k);
- if (line.toolBarItems.isEmpty())
- dock.lines.removeAt(j);
- return;
- }
- }
- }
- }
-}
-
-void QToolBarAreaLayout::clear()
-{
- for (int i = 0; i < QInternal::DockCount; ++i)
- docks[i].clear();
- rect = QRect();
-}
-
-QToolBarAreaLayoutItem &QToolBarAreaLayout::item(const QList<int> &path)
-{
- Q_ASSERT(path.count() == 3);
-
- Q_ASSERT(path.at(0) >= 0 && path.at(0) < QInternal::DockCount);
- QToolBarAreaLayoutInfo &info = docks[path.at(0)];
- Q_ASSERT(path.at(1) >= 0 && path.at(1) < info.lines.count());
- QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
- Q_ASSERT(path.at(2) >= 0 && path.at(2) < line.toolBarItems.count());
- return line.toolBarItems[path.at(2)];
-}
-
-QRect QToolBarAreaLayout::itemRect(const QList<int> &path) const
-{
- const int i = path.first();
-
- QRect r = docks[i].itemRect(path.mid(1));
- if (docks[i].o == Qt::Horizontal)
- r = QStyle::visualRect(mainWindow->layoutDirection(),
- docks[i].rect, r);
- return r;
-}
-
-QLayoutItem *QToolBarAreaLayout::plug(const QList<int> &path)
-{
- QToolBarAreaLayoutItem &item = this->item(path);
- Q_ASSERT(item.gap);
- Q_ASSERT(item.widgetItem != 0);
- item.gap = false;
- return item.widgetItem;
-}
-
-QLayoutItem *QToolBarAreaLayout::unplug(const QList<int> &path, QToolBarAreaLayout *other)
-{
- //other needs to be update as well
- Q_ASSERT(path.count() == 3);
- QToolBarAreaLayoutItem &item = this->item(path);
-
- //update the leading space here
- QToolBarAreaLayoutInfo &info = docks[path.at(0)];
- QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
- if (item.size != pick(line.o, item.realSizeHint())) {
- //the item doesn't have its default size
- //so we'll give this to the next item
- int newExtraSpace = 0;
- //let's iterate over the siblings of the current item that pare placed before it
- //we need to find just the one before
- for (int i = path.at(2) - 1; i >= 0; --i) {
- QToolBarAreaLayoutItem &previous = line.toolBarItems[i];
- if (!previous.skip()) {
- //we need to check if it has a previous element and a next one
- //the previous will get its size changed
- for (int j = path.at(2) + 1; j < line.toolBarItems.count(); ++j) {
- const QToolBarAreaLayoutItem &next = line.toolBarItems.at(j);
- if (!next.skip()) {
- newExtraSpace = next.pos - previous.pos - pick(line.o, previous.sizeHint());
- previous.resize(line.o, next.pos - previous.pos);
- break;
- }
- }
- break;
- }
- }
-
- if (other) {
- QToolBarAreaLayoutInfo &info = other->docks[path.at(0)];
- QToolBarAreaLayoutLine &line = info.lines[path.at(1)];
- for (int i = path.at(2) - 1; i >= 0; --i) {
- QToolBarAreaLayoutItem &previous = line.toolBarItems[i];
- if (!previous.skip()) {
- previous.resize(line.o, pick(line.o, previous.sizeHint()) + newExtraSpace);
- break;
- }
- }
-
- }
- }
-
- Q_ASSERT(!item.gap);
- item.gap = true;
- return item.widgetItem;
-}
-
-static QRect unpackRect(uint geom0, uint geom1, bool *floating)
-{
- *floating = geom0 & 1;
- if (!*floating)
- return QRect();
-
- geom0 >>= 1;
-
- int x = (int)(geom0 & 0x0000ffff) - 0x7FFF;
- int y = (int)(geom1 & 0x0000ffff) - 0x7FFF;
-
- geom0 >>= 16;
- geom1 >>= 16;
-
- int w = geom0 & 0x0000ffff;
- int h = geom1 & 0x0000ffff;
-
- return QRect(x, y, w, h);
-}
-
-static void packRect(uint *geom0, uint *geom1, const QRect &rect, bool floating)
-{
- *geom0 = 0;
- *geom1 = 0;
-
- if (!floating)
- return;
-
- // The 0x7FFF is half of 0xFFFF. We add it so we can handle negative coordinates on
- // dual monitors. It's subtracted when unpacking.
-
- *geom0 |= qMax(0, rect.width()) & 0x0000ffff;
- *geom1 |= qMax(0, rect.height()) & 0x0000ffff;
-
- *geom0 <<= 16;
- *geom1 <<= 16;
-
- *geom0 |= qMax(0, rect.x() + 0x7FFF) & 0x0000ffff;
- *geom1 |= qMax(0, rect.y() + 0x7FFF) & 0x0000ffff;
-
- // yeah, we chop one bit off the width, but it still has a range up to 32512
-
- *geom0 <<= 1;
- *geom0 |= 1;
-}
-
-
-void QToolBarAreaLayout::saveState(QDataStream &stream) const
-{
- // save toolbar state
- stream << (uchar) ToolBarStateMarkerEx;
-
- int lineCount = 0;
- for (int i = 0; i < QInternal::DockCount; ++i)
- lineCount += docks[i].lines.count();
-
- stream << lineCount;
-
- for (int i = 0; i < QInternal::DockCount; ++i) {
- const QToolBarAreaLayoutInfo &dock = docks[i];
-
- for (int j = 0; j < dock.lines.count(); ++j) {
- const QToolBarAreaLayoutLine &line = dock.lines.at(j);
-
- stream << i << line.toolBarItems.count();
-
- for (int k = 0; k < line.toolBarItems.count(); ++k) {
- const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k);
- QWidget *widget = const_cast<QLayoutItem*>(item.widgetItem)->widget();
- QString objectName = widget->objectName();
- if (objectName.isEmpty()) {
- qWarning("QMainWindow::saveState(): 'objectName' not set for QToolBar %p '%s'",
- widget, widget->windowTitle().toLocal8Bit().constData());
- }
- stream << objectName;
- // we store information as:
- // 1st bit: 1 if shown
- // 2nd bit: 1 if orientation is vertical (default is horizontal)
- uchar shownOrientation = (uchar)!widget->isHidden();
- if (QToolBar * tb= qobject_cast<QToolBar*>(widget)) {
- if (tb->orientation() == Qt::Vertical)
- shownOrientation |= 2;
- }
- stream << shownOrientation;
- stream << item.pos;
- //we store the preferred size. If the use rdidn't resize the toolbars it will be -1
- stream << item.preferredSize;
-
- uint geom0, geom1;
- packRect(&geom0, &geom1, widget->geometry(), widget->isWindow());
- stream << geom0 << geom1;
- }
- }
- }
-}
-
-static inline int getInt(QDataStream &stream, Qt::Orientation o, bool pre43)
-{
- if (pre43) {
- QPoint p;
- stream >> p;
- return pick(o, p);
- } else {
- int x;
- stream >> x;
- return x;
- }
-}
-
-
-bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QList<QToolBar*> &_toolBars, uchar tmarker, bool pre43, bool testing)
-{
- QList<QToolBar*> toolBars = _toolBars;
- int lines;
- stream >> lines;
- if (!testing)
- testing = mainWindow->unifiedTitleAndToolBarOnMac();
-
- for (int j = 0; j < lines; ++j) {
- int pos;
- stream >> pos;
- if (pos < 0 || pos >= QInternal::DockCount)
- return false;
- int cnt;
- stream >> cnt;
-
- QToolBarAreaLayoutInfo &dock = docks[pos];
- const bool applyingLayout = !testing && !(pos == QInternal::TopDock && mainWindow->unifiedTitleAndToolBarOnMac());
- QToolBarAreaLayoutLine line(dock.o);
-
- for (int k = 0; k < cnt; ++k) {
- QToolBarAreaLayoutItem item;
-
- QString objectName;
- stream >> objectName;
- uchar shown;
- stream >> shown;
- item.pos = getInt(stream, dock.o, pre43);
- item.size = getInt(stream, dock.o, pre43);
-
- /*
- 4.3.0 added floating toolbars, but failed to add the ability to restore them.
- We need to store there geometry (four ints). We cannot change the format in a
- patch release (4.3.1) by adding ToolBarStateMarkerEx2 to signal extra data. So
- for now we'll pack it in the two legacy ints we no longer used in Qt4.3.0.
- In 4.4, we should add ToolBarStateMarkerEx2 and fix this properly.
- */
-
- QRect rect;
- bool floating = false;
- uint geom0, geom1;
- geom0 = getInt(stream, dock.o, pre43);
- if (tmarker == ToolBarStateMarkerEx) {
- geom1 = getInt(stream, dock.o, pre43);
- rect = unpackRect(geom0, geom1, &floating);
- }
-
- QToolBar *toolBar = 0;
- for (int x = 0; x < toolBars.count(); ++x) {
- if (toolBars.at(x)->objectName() == objectName) {
- toolBar = toolBars.takeAt(x);
- break;
- }
- }
- if (toolBar == 0) {
- continue;
- }
-
- if (applyingLayout) {
- item.widgetItem = new QWidgetItemV2(toolBar);
- toolBar->setOrientation(floating ? ((shown & 2) ? Qt::Vertical : Qt::Horizontal) : dock.o);
- toolBar->setVisible(shown & 1);
- toolBar->d_func()->setWindowState(floating, true, rect);
-
- item.preferredSize = item.size;
- line.toolBarItems.append(item);
- }
- }
-
- if (applyingLayout) {
- dock.lines.append(line);
- }
- }
-
-
- return stream.status() == QDataStream::Ok;
-}
-
-bool QToolBarAreaLayout::isEmpty() const
-{
- for (int i = 0; i < QInternal::DockCount; ++i) {
- if (!docks[i].lines.isEmpty())
- return false;
- }
- return true;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TOOLBAR
diff --git a/src/gui/widgets/qtoolbararealayout_p.h b/src/gui/widgets/qtoolbararealayout_p.h
deleted file mode 100644
index cace88b2ed..0000000000
--- a/src/gui/widgets/qtoolbararealayout_p.h
+++ /dev/null
@@ -1,248 +0,0 @@
-/****************************************************************************
-**
-** 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 QTOOLBARAREALAYOUT_P_H
-#define QTOOLBARAREALAYOUT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QList>
-#include <QSize>
-#include <QRect>
-
-QT_BEGIN_NAMESPACE
-
-static inline int pick(Qt::Orientation o, const QPoint &pos)
-{ return o == Qt::Horizontal ? pos.x() : pos.y(); }
-
-static inline int pick(Qt::Orientation o, const QSize &size)
-{ return o == Qt::Horizontal ? size.width() : size.height(); }
-
-static inline int &rpick(Qt::Orientation o, QPoint &pos)
-{ return o == Qt::Horizontal ? pos.rx() : pos.ry(); }
-
-static inline int &rpick(Qt::Orientation o, QSize &size)
-{ return o == Qt::Horizontal ? size.rwidth() : size.rheight(); }
-
-static inline QSizePolicy::Policy pick(Qt::Orientation o, const QSizePolicy &policy)
-{ return o == Qt::Horizontal ? policy.horizontalPolicy() : policy.verticalPolicy(); }
-
-static inline int perp(Qt::Orientation o, const QPoint &pos)
-{ return o == Qt::Vertical ? pos.x() : pos.y(); }
-
-static inline int perp(Qt::Orientation o, const QSize &size)
-{ return o == Qt::Vertical ? size.width() : size.height(); }
-
-static inline int &rperp(Qt::Orientation o, QPoint &pos)
-{ return o == Qt::Vertical ? pos.rx() : pos.ry(); }
-
-static inline int &rperp(Qt::Orientation o, QSize &size)
-{ return o == Qt::Vertical ? size.rwidth() : size.rheight(); }
-
-#ifndef QT_NO_TOOLBAR
-
-class QToolBar;
-class QLayoutItem;
-class QMainWindow;
-class QStyleOptionToolBar;
-
-class QToolBarAreaLayoutItem
-{
-public:
- QToolBarAreaLayoutItem(QLayoutItem *item = 0)
- : widgetItem(item), pos(0), size(-1), preferredSize(-1), gap(false) {}
-
- bool skip() const;
- QSize minimumSize() const;
- QSize sizeHint() const;
- QSize realSizeHint() const;
-
- void resize(Qt::Orientation o, int newSize)
- {
- newSize = qMax(pick(o, minimumSize()), newSize);
- int sizeh = pick(o, sizeHint());
- if (newSize == sizeh) {
- preferredSize = -1;
- size = sizeh;
- } else {
- preferredSize = newSize;
- }
- }
-
- void extendSize(Qt::Orientation o, int extent)
- {
- int newSize = qMax(pick(o, minimumSize()), (preferredSize > 0 ? preferredSize : pick(o, sizeHint())) + extent);
- int sizeh = pick(o, sizeHint());
- if (newSize == sizeh) {
- preferredSize = -1;
- size = sizeh;
- } else {
- preferredSize = newSize;
- }
- }
-
- QLayoutItem *widgetItem;
- int pos;
- int size;
- int preferredSize;
- bool gap;
-};
-
-class QToolBarAreaLayoutLine
-{
-public:
- QToolBarAreaLayoutLine(Qt::Orientation orientation);
-
- QSize sizeHint() const;
- QSize minimumSize() const;
-
- void fitLayout();
- bool skip() const;
-
- QRect rect;
- Qt::Orientation o;
-
- QList<QToolBarAreaLayoutItem> toolBarItems;
-};
-
-class QToolBarAreaLayoutInfo
-{
-public:
- QToolBarAreaLayoutInfo(QInternal::DockPosition pos = QInternal::TopDock);
-
- QList<QToolBarAreaLayoutLine> lines;
-
- QSize sizeHint() const;
- QSize minimumSize() const;
-
- void fitLayout();
-
- QLayoutItem *insertToolBar(QToolBar *before, QToolBar *toolBar);
- void insertItem(QToolBar *before, QLayoutItem *item);
- void removeToolBar(QToolBar *toolBar);
- void insertToolBarBreak(QToolBar *before);
- void removeToolBarBreak(QToolBar *before);
- void moveToolBar(QToolBar *toolbar, int pos);
-
- QList<int> gapIndex(const QPoint &pos, int *maxDistance) const;
- bool insertGap(const QList<int> &path, QLayoutItem *item);
- void clear();
- QRect itemRect(const QList<int> &path) const;
- int distance(const QPoint &pos) const;
-
- QRect rect;
- Qt::Orientation o;
- QInternal::DockPosition dockPos;
- bool dirty;
-};
-
-class QToolBarAreaLayout
-{
-public:
- enum { // sentinel values used to validate state data
- ToolBarStateMarker = 0xfe,
- ToolBarStateMarkerEx = 0xfc
- };
-
- QRect rect;
- const QMainWindow *mainWindow;
- QToolBarAreaLayoutInfo docks[4];
- bool visible;
-
- QToolBarAreaLayout(const QMainWindow *win);
-
- QRect fitLayout();
-
- QSize minimumSize(const QSize &centerMin) const;
- QRect rectHint(const QRect &r) const;
- QSize sizeHint(const QSize &center) const;
- void apply(bool animate);
-
- QLayoutItem *itemAt(int *x, int index) const;
- QLayoutItem *takeAt(int *x, int index);
- void deleteAllLayoutItems();
-
- QLayoutItem *insertToolBar(QToolBar *before, QToolBar *toolBar);
- void removeToolBar(QToolBar *toolBar);
- QLayoutItem *addToolBar(QInternal::DockPosition pos, QToolBar *toolBar);
- void insertToolBarBreak(QToolBar *before);
- void removeToolBarBreak(QToolBar *before);
- void addToolBarBreak(QInternal::DockPosition pos);
- void moveToolBar(QToolBar *toolbar, int pos);
-
- void insertItem(QInternal::DockPosition pos, QLayoutItem *item);
- void insertItem(QToolBar *before, QLayoutItem *item);
-
- QInternal::DockPosition findToolBar(QToolBar *toolBar) const;
- bool toolBarBreak(QToolBar *toolBar) const;
-
- void getStyleOptionInfo(QStyleOptionToolBar *option, QToolBar *toolBar) const;
-
- QList<int> indexOf(QWidget *toolBar) const;
- QList<int> gapIndex(const QPoint &pos) const;
- QList<int> currentGapIndex() const;
- bool insertGap(const QList<int> &path, QLayoutItem *item);
- void remove(const QList<int> &path);
- void remove(QLayoutItem *item);
- void clear();
- QToolBarAreaLayoutItem &item(const QList<int> &path);
- QRect itemRect(const QList<int> &path) const;
- QLayoutItem *plug(const QList<int> &path);
- QLayoutItem *unplug(const QList<int> &path, QToolBarAreaLayout *other);
-
- void saveState(QDataStream &stream) const;
- bool restoreState(QDataStream &stream, const QList<QToolBar*> &toolBars, uchar tmarker, bool pre43, bool testing = false);
- bool isEmpty() const;
-};
-
-
-QT_END_NAMESPACE
-#endif // QT_NO_TOOLBAR
-#endif // QTOOLBARAREALAYOUT_P_H
diff --git a/src/gui/widgets/qtoolbarextension.cpp b/src/gui/widgets/qtoolbarextension.cpp
deleted file mode 100644
index 720c153d0f..0000000000
--- a/src/gui/widgets/qtoolbarextension.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtoolbarextension_p.h"
-#include <qpixmap.h>
-#include <qstyle.h>
-#include <qstylepainter.h>
-#include <qstyleoption.h>
-
-#ifndef QT_NO_TOOLBUTTON
-
-QT_BEGIN_NAMESPACE
-
-QToolBarExtension::QToolBarExtension(QWidget *parent)
- : QToolButton(parent)
-{
- setObjectName(QLatin1String("qt_toolbar_ext_button"));
- setAutoRaise(true);
- setOrientation(Qt::Horizontal);
- setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
- setCheckable(true);
-}
-
-void QToolBarExtension::setOrientation(Qt::Orientation o)
-{
- QStyleOption opt;
- opt.init(this);
- if (o == Qt::Horizontal) {
- setIcon(style()->standardIcon(QStyle::SP_ToolBarHorizontalExtensionButton, &opt));
- } else {
- setIcon(style()->standardIcon(QStyle::SP_ToolBarVerticalExtensionButton, &opt));
- }
-}
-
-void QToolBarExtension::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
- // We do not need to draw both extension arrows
- opt.features &= ~QStyleOptionToolButton::HasMenu;
- p.drawComplexControl(QStyle::CC_ToolButton, opt);
-}
-
-
-QSize QToolBarExtension::sizeHint() const
-{
- int ext = style()->pixelMetric(QStyle::PM_ToolBarExtensionExtent);
- return QSize(ext, ext);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TOOLBUTTON
diff --git a/src/gui/widgets/qtoolbarextension_p.h b/src/gui/widgets/qtoolbarextension_p.h
deleted file mode 100644
index 533adf1c4f..0000000000
--- a/src/gui/widgets/qtoolbarextension_p.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICTOOLBAREXTENSION_P_H
-#define QDYNAMICTOOLBAREXTENSION_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qtoolbutton.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_TOOLBUTTON
-
-class Q_AUTOTEST_EXPORT QToolBarExtension : public QToolButton
-{
- Q_OBJECT
- Qt::Orientation orientation;
-
-public:
- explicit QToolBarExtension(QWidget *parent);
- void paintEvent(QPaintEvent *);
- QSize sizeHint() const;
-
-public Q_SLOTS:
- void setOrientation(Qt::Orientation o);
-};
-
-#endif // QT_NO_TOOLBUTTON
-
-QT_END_NAMESPACE
-
-#endif // QDYNAMICTOOLBAREXTENSION_P_H
diff --git a/src/gui/widgets/qtoolbarlayout.cpp b/src/gui/widgets/qtoolbarlayout.cpp
deleted file mode 100644
index 531acb453f..0000000000
--- a/src/gui/widgets/qtoolbarlayout.cpp
+++ /dev/null
@@ -1,742 +0,0 @@
-/****************************************************************************
-**
-** 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 <qwidgetaction.h>
-#include <qtoolbar.h>
-#include <qstyleoption.h>
-#include <qtoolbutton.h>
-#include <qmenu.h>
-#include <qdebug.h>
-#include <qmath.h>
-
-#include "qmainwindowlayout_p.h"
-#include "qtoolbarextension_p.h"
-#include "qtoolbarlayout_p.h"
-#include "qtoolbarseparator_p.h"
-
-#ifndef QT_NO_TOOLBAR
-
-QT_BEGIN_NAMESPACE
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-/******************************************************************************
-** QToolBarItem
-*/
-
-QToolBarItem::QToolBarItem(QWidget *widget)
- : QWidgetItem(widget), action(0), customWidget(false)
-{
-}
-
-bool QToolBarItem::isEmpty() const
-{
- return action == 0 || !action->isVisible();
-}
-
-/******************************************************************************
-** QToolBarLayout
-*/
-
-QToolBarLayout::QToolBarLayout(QWidget *parent)
- : QLayout(parent), expanded(false), animating(false), dirty(true),
- expanding(false), empty(true), expandFlag(false), popupMenu(0)
-{
- QToolBar *tb = qobject_cast<QToolBar*>(parent);
- if (!tb)
- return;
-
- extension = new QToolBarExtension(tb);
- extension->setFocusPolicy(Qt::NoFocus);
- extension->hide();
- QObject::connect(tb, SIGNAL(orientationChanged(Qt::Orientation)),
- extension, SLOT(setOrientation(Qt::Orientation)));
-
- setUsePopupMenu(qobject_cast<QMainWindow*>(tb->parentWidget()) == 0);
-}
-
-QToolBarLayout::~QToolBarLayout()
-{
- while (!items.isEmpty()) {
- QToolBarItem *item = items.takeFirst();
- if (QWidgetAction *widgetAction = qobject_cast<QWidgetAction*>(item->action)) {
- if (item->customWidget)
- widgetAction->releaseWidget(item->widget());
- }
- delete item;
- }
-}
-
-void QToolBarLayout::updateMarginAndSpacing()
-{
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return;
- QStyle *style = tb->style();
- QStyleOptionToolBar opt;
- tb->initStyleOption(&opt);
- setMargin(style->pixelMetric(QStyle::PM_ToolBarItemMargin, &opt, tb)
- + style->pixelMetric(QStyle::PM_ToolBarFrameWidth, &opt, tb));
- setSpacing(style->pixelMetric(QStyle::PM_ToolBarItemSpacing, &opt, tb));
-}
-
-bool QToolBarLayout::hasExpandFlag() const
-{
- return expandFlag;
-}
-
-void QToolBarLayout::setUsePopupMenu(bool set)
-{
- if (!dirty && ((popupMenu == 0) == set))
- invalidate();
- if (!set) {
- QObject::connect(extension, SIGNAL(clicked(bool)),
- this, SLOT(setExpanded(bool)), Qt::UniqueConnection);
- extension->setPopupMode(QToolButton::DelayedPopup);
- extension->setMenu(0);
- delete popupMenu;
- popupMenu = 0;
- } else {
- QObject::disconnect(extension, SIGNAL(clicked(bool)),
- this, SLOT(setExpanded(bool)));
- extension->setPopupMode(QToolButton::InstantPopup);
- if (!popupMenu) {
- popupMenu = new QMenu(extension);
- }
- extension->setMenu(popupMenu);
- }
-}
-
-void QToolBarLayout::checkUsePopupMenu()
-{
- QToolBar *tb = static_cast<QToolBar *>(parent());
- QMainWindow *mw = qobject_cast<QMainWindow *>(tb->parent());
- Qt::Orientation o = tb->orientation();
- setUsePopupMenu(!mw || tb->isFloating() || perp(o, expandedSize(mw->size())) >= perp(o, mw->size()));
-}
-
-void QToolBarLayout::addItem(QLayoutItem*)
-{
- qWarning() << "QToolBarLayout::addItem(): please use addAction() instead";
- return;
-}
-
-QLayoutItem *QToolBarLayout::itemAt(int index) const
-{
- if (index < 0 || index >= items.count())
- return 0;
- return items.at(index);
-}
-
-QLayoutItem *QToolBarLayout::takeAt(int index)
-{
- if (index < 0 || index >= items.count())
- return 0;
- QToolBarItem *item = items.takeAt(index);
-
- if (popupMenu)
- popupMenu->removeAction(item->action);
-
- QWidgetAction *widgetAction = qobject_cast<QWidgetAction*>(item->action);
- if (widgetAction != 0 && item->customWidget) {
- widgetAction->releaseWidget(item->widget());
- } else {
- // destroy the QToolButton/QToolBarSeparator
- item->widget()->hide();
- item->widget()->deleteLater();
- }
-
- invalidate();
- return item;
-}
-
-void QToolBarLayout::insertAction(int index, QAction *action)
-{
- index = qMax(0, index);
- index = qMin(items.count(), index);
-
- QToolBarItem *item = createItem(action);
- if (item) {
- items.insert(index, item);
- invalidate();
- }
-}
-
-int QToolBarLayout::indexOf(QAction *action) const
-{
- for (int i = 0; i < items.count(); ++i) {
- if (items.at(i)->action == action)
- return i;
- }
- return -1;
-}
-
-int QToolBarLayout::count() const
-{
- return items.count();
-}
-
-bool QToolBarLayout::isEmpty() const
-{
- if (dirty)
- updateGeomArray();
- return empty;
-}
-
-void QToolBarLayout::invalidate()
-{
- dirty = true;
- QLayout::invalidate();
-}
-
-Qt::Orientations QToolBarLayout::expandingDirections() const
-{
- if (dirty)
- updateGeomArray();
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return Qt::Orientations(0);
- Qt::Orientation o = tb->orientation();
- return expanding ? Qt::Orientations(o) : Qt::Orientations(0);
-}
-
-bool QToolBarLayout::movable() const
-{
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return false;
- QMainWindow *win = qobject_cast<QMainWindow*>(tb->parentWidget());
- return tb->isMovable() && win != 0;
-}
-
-void QToolBarLayout::updateGeomArray() const
-{
- if (!dirty)
- return;
-
- QToolBarLayout *that = const_cast<QToolBarLayout*>(this);
-
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return;
- QStyle *style = tb->style();
- QStyleOptionToolBar opt;
- tb->initStyleOption(&opt);
- const int handleExtent = movable()
- ? style->pixelMetric(QStyle::PM_ToolBarHandleExtent, &opt, tb) : 0;
- const int margin = this->margin();
- const int spacing = this->spacing();
- const int extensionExtent = style->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt, tb);
- Qt::Orientation o = tb->orientation();
-
- that->minSize = QSize(0, 0);
- that->hint = QSize(0, 0);
- rperp(o, that->minSize) = style->pixelMetric(QStyle::PM_ToolBarHandleExtent, &opt, tb);
- rperp(o, that->hint) = style->pixelMetric(QStyle::PM_ToolBarHandleExtent, &opt, tb);
-
- that->expanding = false;
- that->empty = false;
-
- QVector<QLayoutStruct> a(items.count() + 1); // + 1 for the stretch
-
- int count = 0;
- for (int i = 0; i < items.count(); ++i) {
- QToolBarItem *item = items.at(i);
-
- QSize max = item->maximumSize();
- QSize min = item->minimumSize();
- QSize hint = item->sizeHint();
- Qt::Orientations exp = item->expandingDirections();
- bool empty = item->isEmpty();
-
- that->expanding = expanding || exp & o;
-
-
- if (item->widget()) {
- if ((item->widget()->sizePolicy().horizontalPolicy() & QSizePolicy::ExpandFlag)) {
- that->expandFlag = true;
- }
- }
-
- if (!empty) {
- if (count == 0) // the minimum size only displays one widget
- rpick(o, that->minSize) += pick(o, min);
- int s = perp(o, minSize);
- rperp(o, that->minSize) = qMax(s, perp(o, min));
-
- //we only add spacing before item (ie never before the first one)
- rpick(o, that->hint) += (count == 0 ? 0 : spacing) + pick(o, hint);
- s = perp(o, that->hint);
- rperp(o, that->hint) = qMax(s, perp(o, hint));
- ++count;
- }
-
- a[i].sizeHint = pick(o, hint);
- a[i].maximumSize = pick(o, max);
- a[i].minimumSize = pick(o, min);
- a[i].expansive = exp & o;
- if (o == Qt::Horizontal)
- a[i].stretch = item->widget()->sizePolicy().horizontalStretch();
- else
- a[i].stretch = item->widget()->sizePolicy().verticalStretch();
- a[i].empty = empty;
- }
-
- that->geomArray = a;
- that->empty = count == 0;
-
- rpick(o, that->minSize) += handleExtent;
- that->minSize += QSize(2*margin, 2*margin);
- if (items.count() > 1)
- rpick(o, that->minSize) += spacing + extensionExtent;
-
- rpick(o, that->hint) += handleExtent;
- that->hint += QSize(2*margin, 2*margin);
- that->dirty = false;
-#ifdef Q_WS_MAC
- if (QMainWindow *mw = qobject_cast<QMainWindow *>(parentWidget()->parentWidget())) {
- if (mw->unifiedTitleAndToolBarOnMac()
- && mw->toolBarArea(static_cast<QToolBar *>(parentWidget())) == Qt::TopToolBarArea) {
- if (expandFlag) {
- tb->setMaximumSize(0xFFFFFF, 0xFFFFFF);
- } else {
- tb->setMaximumSize(hint);
- }
- }
- }
-#endif
-
- that->dirty = false;
-}
-
-static bool defaultWidgetAction(QToolBarItem *item)
-{
- QWidgetAction *a = qobject_cast<QWidgetAction*>(item->action);
- return a != 0 && a->defaultWidget() == item->widget();
-}
-
-void QToolBarLayout::setGeometry(const QRect &rect)
-{
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return;
- QStyle *style = tb->style();
- QStyleOptionToolBar opt;
- tb->initStyleOption(&opt);
- const int margin = this->margin();
- const int extensionExtent = style->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt, tb);
- Qt::Orientation o = tb->orientation();
-
- QLayout::setGeometry(rect);
-
- bool ranOutOfSpace = false;
- if (!animating)
- ranOutOfSpace = layoutActions(rect.size());
-
- if (expanded || animating || ranOutOfSpace) {
- Qt::ToolBarArea area = Qt::TopToolBarArea;
- if (QMainWindow *win = qobject_cast<QMainWindow*>(tb->parentWidget()))
- area = win->toolBarArea(tb);
- QSize hint = sizeHint();
-
- QPoint pos;
- rpick(o, pos) = pick(o, rect.bottomRight()) - margin - extensionExtent + 2;
- if (area == Qt::LeftToolBarArea || area == Qt::TopToolBarArea)
- rperp(o, pos) = perp(o, rect.topLeft()) + margin;
- else
- rperp(o, pos) = perp(o, rect.bottomRight()) - margin - (perp(o, hint) - 2*margin) + 1;
- QSize size;
- rpick(o, size) = extensionExtent;
- rperp(o, size) = perp(o, hint) - 2*margin;
- QRect r(pos, size);
-
- if (o == Qt::Horizontal)
- r = QStyle::visualRect(parentWidget()->layoutDirection(), rect, r);
-
- extension->setGeometry(r);
-
- if (extension->isHidden())
- extension->show();
- } else {
- if (!extension->isHidden())
- extension->hide();
- }
-#ifdef Q_WS_MAC
- // Nothing to do for Carbon... probably
-# ifdef QT_MAC_USE_COCOA
- if (QMainWindow *win = qobject_cast<QMainWindow*>(tb->parentWidget())) {
- Qt::ToolBarArea area = win->toolBarArea(tb);
- if (win->unifiedTitleAndToolBarOnMac() && area == Qt::TopToolBarArea) {
- qt_mainwindow_layout(win)->fixSizeInUnifiedToolbar(tb);
- }
- }
-# endif
-#endif
-
-}
-
-bool QToolBarLayout::layoutActions(const QSize &size)
-{
- if (dirty)
- updateGeomArray();
-
- QRect rect(0, 0, size.width(), size.height());
-
- QList<QWidget*> showWidgets, hideWidgets;
-
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return false;
- QStyle *style = tb->style();
- QStyleOptionToolBar opt;
- tb->initStyleOption(&opt);
- const int handleExtent = movable()
- ? style->pixelMetric(QStyle::PM_ToolBarHandleExtent, &opt, tb) : 0;
- const int margin = this->margin();
- const int spacing = this->spacing();
- const int extensionExtent = style->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt, tb);
- Qt::Orientation o = tb->orientation();
- bool extensionMenuContainsOnlyWidgetActions = true;
-
- int space = pick(o, rect.size()) - 2*margin - handleExtent;
- if (space <= 0)
- return false; // nothing to do.
-
- if(popupMenu)
- popupMenu->clear();
-
- bool ranOutOfSpace = false;
- int rows = 0;
- int rowPos = perp(o, rect.topLeft()) + margin;
- int i = 0;
- while (i < items.count()) {
- QVector<QLayoutStruct> a = geomArray;
-
- int start = i;
- int size = 0;
- int prev = -1;
- int rowHeight = 0;
- int count = 0;
- int maximumSize = 0;
- bool expansiveRow = false;
- for (; i < items.count(); ++i) {
- if (a[i].empty)
- continue;
-
- int newSize = size + (count == 0 ? 0 : spacing) + a[i].minimumSize;
- if (prev != -1 && newSize > space) {
- if (rows == 0)
- ranOutOfSpace = true;
- // do we have to move the previous item to the next line to make space for
- // the extension button?
- if (count > 1 && size + spacing + extensionExtent > space)
- i = prev;
- break;
- }
-
- if (expanded)
- rowHeight = qMax(rowHeight, perp(o, items.at(i)->sizeHint()));
- expansiveRow = expansiveRow || a[i].expansive;
- size = newSize;
- maximumSize += spacing + (a[i].expansive ? a[i].maximumSize : a[i].smartSizeHint());
- prev = i;
- ++count;
- }
-
- // stretch at the end
- a[i].sizeHint = 0;
- a[i].maximumSize = QWIDGETSIZE_MAX;
- a[i].minimumSize = 0;
- a[i].expansive = true;
- a[i].stretch = 0;
- a[i].empty = true;
-
- if (expansiveRow && maximumSize < space) {
- expansiveRow = false;
- a[i].maximumSize = space - maximumSize;
- }
-
- qGeomCalc(a, start, i - start + (expansiveRow ? 0 : 1), 0,
- space - (ranOutOfSpace ? (extensionExtent + spacing) : 0),
- spacing);
-
- for (int j = start; j < i; ++j) {
- QToolBarItem *item = items.at(j);
-
- if (a[j].empty) {
- if (!item->widget()->isHidden())
- hideWidgets << item->widget();
- continue;
- }
-
- QPoint pos;
- rpick(o, pos) = margin + handleExtent + a[j].pos;
- rperp(o, pos) = rowPos;
- QSize size;
- rpick(o, size) = a[j].size;
- if (expanded)
- rperp(o, size) = rowHeight;
- else
- rperp(o, size) = perp(o, rect.size()) - 2*margin;
- QRect r(pos, size);
-
- if (o == Qt::Horizontal)
- r = QStyle::visualRect(parentWidget()->layoutDirection(), rect, r);
-
- item->setGeometry(r);
-
- if (item->widget()->isHidden())
- showWidgets << item->widget();
- }
-
- if (!expanded) {
- for (int j = i; j < items.count(); ++j) {
- QToolBarItem *item = items.at(j);
- if (!item->widget()->isHidden())
- hideWidgets << item->widget();
- if (popupMenu) {
- if (!defaultWidgetAction(item)) {
- popupMenu->addAction(item->action);
- extensionMenuContainsOnlyWidgetActions = false;
- }
- }
- }
- break;
- }
-
- rowPos += rowHeight + spacing;
- ++rows;
- }
-
- // if we are using a popup menu, not the expadning toolbar effect, we cannot move custom
- // widgets into the menu. If only custom widget actions are chopped off, the popup menu
- // is empty. So we show the little extension button to show something is chopped off,
- // but we make it disabled.
- extension->setEnabled(popupMenu == 0 || !extensionMenuContainsOnlyWidgetActions);
-
- // we have to do the show/hide here, because it triggers more calls to setGeometry :(
- for (int i = 0; i < showWidgets.count(); ++i)
- showWidgets.at(i)->show();
- for (int i = 0; i < hideWidgets.count(); ++i)
- hideWidgets.at(i)->hide();
-
- return ranOutOfSpace;
-}
-
-QSize QToolBarLayout::expandedSize(const QSize &size) const
-{
- if (dirty)
- updateGeomArray();
-
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return QSize(0, 0);
- QMainWindow *win = qobject_cast<QMainWindow*>(tb->parentWidget());
- Qt::Orientation o = tb->orientation();
- QStyle *style = tb->style();
- QStyleOptionToolBar opt;
- tb->initStyleOption(&opt);
- const int handleExtent = movable()
- ? style->pixelMetric(QStyle::PM_ToolBarHandleExtent, &opt, tb) : 0;
- const int margin = this->margin();
- const int spacing = this->spacing();
- const int extensionExtent = style->pixelMetric(QStyle::PM_ToolBarExtensionExtent, &opt, tb);
-
- int total_w = 0;
- int count = 0;
- for (int x = 0; x < items.count(); ++x) {
- if (!geomArray[x].empty) {
- total_w += (count == 0 ? 0 : spacing) + geomArray[x].minimumSize;
- ++count;
- }
- }
- if (count == 0)
- return QSize(0, 0);
-
- int min_w = pick(o, size);
- int rows = (int)qSqrt(qreal(count));
- if (rows == 1)
- ++rows; // we want to expand to at least two rows
- int space = total_w/rows + spacing + extensionExtent;
- space = qMax(space, min_w - 2*margin - handleExtent);
- if (win != 0)
- space = qMin(space, pick(o, win->size()) - 2*margin - handleExtent);
-
- int w = 0;
- int h = 0;
- int i = 0;
- while (i < items.count()) {
- int count = 0;
- int size = 0;
- int prev = -1;
- int rowHeight = 0;
- for (; i < items.count(); ++i) {
- if (geomArray[i].empty)
- continue;
-
- int newSize = size + (count == 0 ? 0 : spacing) + geomArray[i].minimumSize;
- rowHeight = qMax(rowHeight, perp(o, items.at(i)->sizeHint()));
- if (prev != -1 && newSize > space) {
- if (count > 1 && size + spacing + extensionExtent > space) {
- size -= spacing + geomArray[prev].minimumSize;
- i = prev;
- }
- break;
- }
-
- size = newSize;
- prev = i;
- ++count;
- }
-
- w = qMax(size, w);
- h += rowHeight + spacing;
- }
-
- w += 2*margin + handleExtent + spacing + extensionExtent;
- w = qMax(w, min_w);
- if (win != 0)
- w = qMin(w, pick(o, win->size()));
- h += 2*margin - spacing; //there is no spacing before the first row
-
- QSize result;
- rpick(o, result) = w;
- rperp(o, result) = h;
- return result;
-}
-
-void QToolBarLayout::setExpanded(bool exp)
-{
- QWidget *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return;
- if (exp == expanded && !tb->isWindow())
- return;
-
- expanded = exp;
- extension->setChecked(expanded);
-
- if (QMainWindow *win = qobject_cast<QMainWindow*>(tb->parentWidget())) {
-#ifdef QT_NO_DOCKWIDGET
- animating = false;
-#else
- animating = !tb->isWindow() && win->isAnimated();
-#endif
- QMainWindowLayout *layout = qt_mainwindow_layout(win);
- if (expanded) {
- tb->raise();
- } else {
- QList<int> path = layout->layoutState.indexOf(tb);
- if (!path.isEmpty()) {
- QRect rect = layout->layoutState.itemRect(path);
- layoutActions(rect.size());
- }
- }
- layout->layoutState.toolBarAreaLayout.apply(animating);
- }
-}
-
-QSize QToolBarLayout::minimumSize() const
-{
- if (dirty)
- updateGeomArray();
- return minSize;
-}
-
-QSize QToolBarLayout::sizeHint() const
-{
- if (dirty)
- updateGeomArray();
- return hint;
-}
-
-QToolBarItem *QToolBarLayout::createItem(QAction *action)
-{
- bool customWidget = false;
- bool standardButtonWidget = false;
- QWidget *widget = 0;
- QToolBar *tb = qobject_cast<QToolBar*>(parentWidget());
- if (!tb)
- return (QToolBarItem *)0;
-
- if (QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(action)) {
- widget = widgetAction->requestWidget(tb);
- if (widget != 0) {
- widget->setAttribute(Qt::WA_LayoutUsesWidgetRect);
- customWidget = true;
- }
- } else if (action->isSeparator()) {
- QToolBarSeparator *sep = new QToolBarSeparator(tb);
- connect(tb, SIGNAL(orientationChanged(Qt::Orientation)),
- sep, SLOT(setOrientation(Qt::Orientation)));
- widget = sep;
- }
-
- if (!widget) {
- QToolButton *button = new QToolButton(tb);
- button->setAutoRaise(true);
- button->setFocusPolicy(Qt::NoFocus);
- button->setIconSize(tb->iconSize());
- button->setToolButtonStyle(tb->toolButtonStyle());
- QObject::connect(tb, SIGNAL(iconSizeChanged(QSize)),
- button, SLOT(setIconSize(QSize)));
- QObject::connect(tb, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
- button, SLOT(setToolButtonStyle(Qt::ToolButtonStyle)));
- button->setDefaultAction(action);
- QObject::connect(button, SIGNAL(triggered(QAction*)), tb, SIGNAL(actionTriggered(QAction*)));
- widget = button;
- standardButtonWidget = true;
- }
-
- widget->hide();
- QToolBarItem *result = new QToolBarItem(widget);
- if (standardButtonWidget)
- result->setAlignment(Qt::AlignJustify);
- result->customWidget = customWidget;
- result->action = action;
- return result;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TOOLBAR
diff --git a/src/gui/widgets/qtoolbarlayout_p.h b/src/gui/widgets/qtoolbarlayout_p.h
deleted file mode 100644
index 5b234d69ad..0000000000
--- a/src/gui/widgets/qtoolbarlayout_p.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** 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 QTOOLBARLAYOUT_P_H
-#define QTOOLBARLAYOUT_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtGui/qlayout.h>
-#include <private/qlayoutengine_p.h>
-#include <QVector>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_TOOLBAR
-
-class QAction;
-class QToolBarExtension;
-class QMenu;
-
-class QToolBarItem : public QWidgetItem
-{
-public:
- QToolBarItem(QWidget *widget);
- bool isEmpty() const;
-
- QAction *action;
- bool customWidget;
-};
-
-class QToolBarLayout : public QLayout
-{
- Q_OBJECT
-
-public:
- QToolBarLayout(QWidget *parent = 0);
- ~QToolBarLayout();
-
- void addItem(QLayoutItem *item);
- QLayoutItem *itemAt(int index) const;
- QLayoutItem *takeAt(int index);
- int count() const;
-
- bool isEmpty() const;
- void invalidate();
- Qt::Orientations expandingDirections() const;
-
- void setGeometry(const QRect &r);
- QSize minimumSize() const;
- QSize sizeHint() const;
-
- void insertAction(int index, QAction *action);
- int indexOf(QAction *action) const;
- int indexOf(QWidget *widget) const { return QLayout::indexOf(widget); }
-
- bool layoutActions(const QSize &size);
- QSize expandedSize(const QSize &size) const;
- bool expanded, animating;
-
- void setUsePopupMenu(bool set); // Yeah, there's no getter, but it's internal.
- void checkUsePopupMenu();
-
- bool movable() const;
- void updateMarginAndSpacing();
- bool hasExpandFlag() const;
-
-public Q_SLOTS:
- void setExpanded(bool b);
-
-private:
- QList<QToolBarItem*> items;
- QSize hint, minSize;
- bool dirty, expanding, empty, expandFlag;
- QVector<QLayoutStruct> geomArray;
- QRect handRect;
- QToolBarExtension *extension;
-
- void updateGeomArray() const;
- QToolBarItem *createItem(QAction *action);
- QMenu *popupMenu;
-};
-
-#endif // QT_NO_TOOLBAR
-
-QT_END_NAMESPACE
-
-#endif // QTOOLBARLAYOUT_P_H
diff --git a/src/gui/widgets/qtoolbarseparator.cpp b/src/gui/widgets/qtoolbarseparator.cpp
deleted file mode 100644
index 9ce523a48d..0000000000
--- a/src/gui/widgets/qtoolbarseparator.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtoolbarseparator_p.h"
-
-#ifndef QT_NO_TOOLBAR
-
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qtoolbar.h>
-#include <qpainter.h>
-
-QT_BEGIN_NAMESPACE
-
-void QToolBarSeparator::initStyleOption(QStyleOption *option) const
-{
- option->initFrom(this);
- if (orientation() == Qt::Horizontal)
- option->state |= QStyle::State_Horizontal;
-}
-
-QToolBarSeparator::QToolBarSeparator(QToolBar *parent)
- : QWidget(parent), orient(parent->orientation())
-{ setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); }
-
-void QToolBarSeparator::setOrientation(Qt::Orientation orientation)
-{
- orient = orientation;
- update();
-}
-
-Qt::Orientation QToolBarSeparator::orientation() const
-{ return orient; }
-
-QSize QToolBarSeparator::sizeHint() const
-{
- QStyleOption opt;
- initStyleOption(&opt);
- const int extent = style()->pixelMetric(QStyle::PM_ToolBarSeparatorExtent, &opt, parentWidget());
- return QSize(extent, extent);
-}
-
-void QToolBarSeparator::paintEvent(QPaintEvent *)
-{
- QPainter p(this);
- QStyleOption opt;
- initStyleOption(&opt);
- style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &opt, &p, parentWidget());
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_TOOLBAR
diff --git a/src/gui/widgets/qtoolbarseparator_p.h b/src/gui/widgets/qtoolbarseparator_p.h
deleted file mode 100644
index b2029fa53d..0000000000
--- a/src/gui/widgets/qtoolbarseparator_p.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** 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 QDYNAMICTOOLBARSEPARATOR_P_H
-#define QDYNAMICTOOLBARSEPARATOR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "QtGui/qwidget.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_TOOLBAR
-
-class QStyleOption;
-class QToolBar;
-
-class QToolBarSeparator : public QWidget
-{
- Q_OBJECT
- Qt::Orientation orient;
-
-public:
- explicit QToolBarSeparator(QToolBar *parent);
-
- Qt::Orientation orientation() const;
-
- QSize sizeHint() const;
-
- void paintEvent(QPaintEvent *);
- void initStyleOption(QStyleOption *option) const;
-
-public Q_SLOTS:
- void setOrientation(Qt::Orientation orientation);
-};
-
-#endif // QT_NO_TOOLBAR
-
-QT_END_NAMESPACE
-
-#endif // QDYNAMICTOOLBARSEPARATOR_P_H
diff --git a/src/gui/widgets/qtoolbox.cpp b/src/gui/widgets/qtoolbox.cpp
deleted file mode 100644
index 1d0a26740b..0000000000
--- a/src/gui/widgets/qtoolbox.cpp
+++ /dev/null
@@ -1,822 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtoolbox.h"
-
-#ifndef QT_NO_TOOLBOX
-
-#include <qapplication.h>
-#include <qeventloop.h>
-#include <qlayout.h>
-#include <qlist.h>
-#include <qpainter.h>
-#include <qscrollarea.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qtooltip.h>
-#include <qabstractbutton.h>
-
-#include "qframe_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QToolBoxButton : public QAbstractButton
-{
- Q_OBJECT
-public:
- QToolBoxButton(QWidget *parent)
- : QAbstractButton(parent), selected(false), indexInPage(-1)
- {
- setBackgroundRole(QPalette::Window);
- setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
- setFocusPolicy(Qt::NoFocus);
- }
-
- inline void setSelected(bool b) { selected = b; update(); }
- inline void setIndex(int newIndex) { indexInPage = newIndex; }
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
-protected:
- void initStyleOption(QStyleOptionToolBox *opt) const;
- void paintEvent(QPaintEvent *);
-
-private:
- bool selected;
- int indexInPage;
-};
-
-
-class QToolBoxPrivate : public QFramePrivate
-{
- Q_DECLARE_PUBLIC(QToolBox)
-public:
- struct Page
- {
- QToolBoxButton *button;
- QScrollArea *sv;
- QWidget *widget;
-
- inline void setText(const QString &text) { button->setText(text); }
- inline void setIcon(const QIcon &is) { button->setIcon(is); }
-#ifndef QT_NO_TOOLTIP
- inline void setToolTip(const QString &tip) { button->setToolTip(tip); }
- inline QString toolTip() const { return button->toolTip(); }
-#endif
- inline QString text() const { return button->text(); }
- inline QIcon icon() const { return button->icon(); }
-
- inline bool operator==(const Page& other) const
- {
- return widget == other.widget;
- }
- };
- typedef QList<Page> PageList;
-
- inline QToolBoxPrivate()
- : currentPage(0)
- {
- }
- void _q_buttonClicked();
- void _q_widgetDestroyed(QObject*);
-
- Page *page(QWidget *widget) const;
- const Page *page(int index) const;
- Page *page(int index);
-
- void updateTabs();
- void relayout();
-
- PageList pageList;
- QVBoxLayout *layout;
- Page *currentPage;
-};
-
-QToolBoxPrivate::Page *QToolBoxPrivate::page(QWidget *widget) const
-{
- if (!widget)
- return 0;
-
- for (PageList::ConstIterator i = pageList.constBegin(); i != pageList.constEnd(); ++i)
- if ((*i).widget == widget)
- return (Page*) &(*i);
- return 0;
-}
-
-QToolBoxPrivate::Page *QToolBoxPrivate::page(int index)
-{
- if (index >= 0 && index < pageList.size())
- return &pageList[index];
- return 0;
-}
-
-const QToolBoxPrivate::Page *QToolBoxPrivate::page(int index) const
-{
- if (index >= 0 && index < pageList.size())
- return &pageList.at(index);
- return 0;
-}
-
-void QToolBoxPrivate::updateTabs()
-{
- QToolBoxButton *lastButton = currentPage ? currentPage->button : 0;
- bool after = false;
- int index = 0;
- for (index = 0; index < pageList.count(); ++index) {
- const Page &page = pageList.at(index);
- QToolBoxButton *tB = page.button;
- // update indexes, since the updates are delayed, the indexes will be correct
- // when we actually paint.
- tB->setIndex(index);
- QWidget *tW = page.widget;
- if (after) {
- QPalette p = tB->palette();
- p.setColor(tB->backgroundRole(), tW->palette().color(tW->backgroundRole()));
- tB->setPalette(p);
- tB->update();
- } else if (tB->backgroundRole() != QPalette::Window) {
- tB->setBackgroundRole(QPalette::Window);
- tB->update();
- }
- after = tB == lastButton;
- }
-}
-
-QSize QToolBoxButton::sizeHint() const
-{
- QSize iconSize(8, 8);
- if (!icon().isNull()) {
- int icone = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, parentWidget() /* QToolBox */);
- iconSize += QSize(icone + 2, icone);
- }
- QSize textSize = fontMetrics().size(Qt::TextShowMnemonic, text()) + QSize(0, 8);
-
- QSize total(iconSize.width() + textSize.width(), qMax(iconSize.height(), textSize.height()));
- return total.expandedTo(QApplication::globalStrut());
-}
-
-QSize QToolBoxButton::minimumSizeHint() const
-{
- if (icon().isNull())
- return QSize();
- int icone = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, parentWidget() /* QToolBox */);
- return QSize(icone + 8, icone + 8);
-}
-
-void QToolBoxButton::initStyleOption(QStyleOptionToolBox *option) const
-{
- if (!option)
- return;
- option->initFrom(this);
- if (selected)
- option->state |= QStyle::State_Selected;
- if (isDown())
- option->state |= QStyle::State_Sunken;
- option->text = text();
- option->icon = icon();
-
- if (QStyleOptionToolBoxV2 *optionV2 = qstyleoption_cast<QStyleOptionToolBoxV2 *>(option)) {
- QToolBox *toolBox = static_cast<QToolBox *>(parentWidget()); // I know I'm in a tool box.
- int widgetCount = toolBox->count();
- int currIndex = toolBox->currentIndex();
- if (widgetCount == 1) {
- optionV2->position = QStyleOptionToolBoxV2::OnlyOneTab;
- } else if (indexInPage == 0) {
- optionV2->position = QStyleOptionToolBoxV2::Beginning;
- } else if (indexInPage == widgetCount - 1) {
- optionV2->position = QStyleOptionToolBoxV2::End;
- } else {
- optionV2->position = QStyleOptionToolBoxV2::Middle;
- }
- if (currIndex == indexInPage - 1) {
- optionV2->selectedPosition = QStyleOptionToolBoxV2::PreviousIsSelected;
- } else if (currIndex == indexInPage + 1) {
- optionV2->selectedPosition = QStyleOptionToolBoxV2::NextIsSelected;
- } else {
- optionV2->selectedPosition = QStyleOptionToolBoxV2::NotAdjacent;
- }
- }
-}
-
-void QToolBoxButton::paintEvent(QPaintEvent *)
-{
- QPainter paint(this);
- QString text = QAbstractButton::text();
- QPainter *p = &paint;
- QStyleOptionToolBoxV2 opt;
- initStyleOption(&opt);
- style()->drawControl(QStyle::CE_ToolBoxTab, &opt, p, parentWidget());
-}
-
-/*!
- \class QToolBox
-
- \brief The QToolBox class provides a column of tabbed widget items.
-
-
- \ingroup basicwidgets
-
- A toolbox is a widget that displays a column of tabs one above the
- other, with the current item displayed below the current tab.
- Every tab has an index position within the column of tabs. A tab's
- item is a QWidget.
-
- Each item has an itemText(), an optional itemIcon(), an optional
- itemToolTip(), and a widget(). The item's attributes can be
- changed with setItemText(), setItemIcon(), and
- setItemToolTip(). Each item can be enabled or disabled
- individually with setItemEnabled().
-
- Items are added using addItem(), or inserted at particular
- positions using insertItem(). The total number of items is given
- by count(). Items can be deleted with delete, or removed from the
- toolbox with removeItem(). Combining removeItem() and insertItem()
- allows you to move items to different positions.
-
- The index of the current item widget is returned by currentIndex(),
- and set with setCurrentIndex(). The index of a particular item can
- be found using indexOf(), and the item at a given index is returned
- by item().
-
- The currentChanged() signal is emitted when the current item is
- changed.
-
- \sa QTabWidget
-*/
-
-/*!
- \fn void QToolBox::currentChanged(int index)
-
- This signal is emitted when the current item is changed. The new
- current item's index is passed in \a index, or -1 if there is no
- current item.
-*/
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs a toolbox called \a name with parent \a parent and flags \a f.
-*/
-QToolBox::QToolBox(QWidget *parent, const char *name, Qt::WindowFlags f)
- : QFrame(*new QToolBoxPrivate, parent, f)
-{
- Q_D(QToolBox);
- setObjectName(QString::fromAscii(name));
- d->layout = new QVBoxLayout(this);
- d->layout->setMargin(0);
- setBackgroundRole(QPalette::Button);
-}
-#endif
-
-/*!
- Constructs a new toolbox with the given \a parent and the flags, \a f.
-*/
-QToolBox::QToolBox(QWidget *parent, Qt::WindowFlags f)
- : QFrame(*new QToolBoxPrivate, parent, f)
-{
- Q_D(QToolBox);
- d->layout = new QVBoxLayout(this);
- d->layout->setMargin(0);
- setBackgroundRole(QPalette::Button);
-}
-
-/*!
- Destroys the toolbox.
-*/
-
-QToolBox::~QToolBox()
-{
-}
-
-/*!
- \fn int QToolBox::addItem(QWidget *w, const QString &text)
- \overload
-
- Adds the widget \a w in a new tab at bottom of the toolbox. The
- new tab's text is set to \a text. Returns the new tab's index.
-*/
-
-/*!
- \fn int QToolBox::addItem(QWidget *widget, const QIcon &iconSet,const QString &text)
- Adds the \a widget in a new tab at bottom of the toolbox. The
- new tab's text is set to \a text, and the \a iconSet is
- displayed to the left of the \a text. Returns the new tab's index.
-*/
-
-/*!
- \fn int QToolBox::insertItem(int index, QWidget *widget, const QString &text)
- \overload
-
- Inserts the \a widget at position \a index, or at the bottom
- of the toolbox if \a index is out of range. The new item's text is
- set to \a text. Returns the new item's index.
-*/
-
-/*!
- Inserts the \a widget at position \a index, or at the bottom
- of the toolbox if \a index is out of range. The new item's text
- is set to \a text, and the \a icon is displayed to the left of
- the \a text. Returns the new item's index.
-*/
-
-int QToolBox::insertItem(int index, QWidget *widget, const QIcon &icon, const QString &text)
-{
- if (!widget)
- return -1;
-
- Q_D(QToolBox);
- connect(widget, SIGNAL(destroyed(QObject*)), this, SLOT(_q_widgetDestroyed(QObject*)));
-
- QToolBoxPrivate::Page c;
- c.widget = widget;
- c.button = new QToolBoxButton(this);
- c.button->setObjectName(QLatin1String("qt_toolbox_toolboxbutton"));
- connect(c.button, SIGNAL(clicked()), this, SLOT(_q_buttonClicked()));
-
- c.sv = new QScrollArea(this);
- c.sv->setWidget(widget);
- c.sv->setWidgetResizable(true);
- c.sv->hide();
- c.sv->setFrameStyle(QFrame::NoFrame);
-
- c.setText(text);
- c.setIcon(icon);
-
- if (index < 0 || index >= (int)d->pageList.count()) {
- index = d->pageList.count();
- d->pageList.append(c);
- d->layout->addWidget(c.button);
- d->layout->addWidget(c.sv);
- if (index == 0)
- setCurrentIndex(index);
- } else {
- d->pageList.insert(index, c);
- d->relayout();
- if (d->currentPage) {
- QWidget *current = d->currentPage->widget;
- int oldindex = indexOf(current);
- if (index <= oldindex) {
- d->currentPage = 0; // trigger change
- setCurrentIndex(oldindex);
- }
- }
- }
-
- c.button->show();
-
- d->updateTabs();
- itemInserted(index);
- return index;
-}
-
-void QToolBoxPrivate::_q_buttonClicked()
-{
- Q_Q(QToolBox);
- QToolBoxButton *tb = qobject_cast<QToolBoxButton*>(q->sender());
- QWidget* item = 0;
- for (QToolBoxPrivate::PageList::ConstIterator i = pageList.constBegin(); i != pageList.constEnd(); ++i)
- if ((*i).button == tb) {
- item = (*i).widget;
- break;
- }
-
- q->setCurrentIndex(q->indexOf(item));
-}
-
-/*!
- \property QToolBox::count
- \brief The number of items contained in the toolbox.
-
- By default, this property has a value of 0.
-*/
-
-int QToolBox::count() const
-{
- Q_D(const QToolBox);
- return d->pageList.count();
-}
-
-void QToolBox::setCurrentIndex(int index)
-{
- Q_D(QToolBox);
- QToolBoxPrivate::Page *c = d->page(index);
- if (!c || d->currentPage == c)
- return;
-
- c->button->setSelected(true);
- if (d->currentPage) {
- d->currentPage->sv->hide();
- d->currentPage->button->setSelected(false);
- }
- d->currentPage = c;
- d->currentPage->sv->show();
- d->updateTabs();
- emit currentChanged(index);
-}
-
-void QToolBoxPrivate::relayout()
-{
- Q_Q(QToolBox);
- delete layout;
- layout = new QVBoxLayout(q);
- layout->setMargin(0);
- for (QToolBoxPrivate::PageList::ConstIterator i = pageList.constBegin(); i != pageList.constEnd(); ++i) {
- layout->addWidget((*i).button);
- layout->addWidget((*i).sv);
- }
-}
-
-void QToolBoxPrivate::_q_widgetDestroyed(QObject *object)
-{
- Q_Q(QToolBox);
- // no verification - vtbl corrupted already
- QWidget *p = (QWidget*)object;
-
- QToolBoxPrivate::Page *c = page(p);
- if (!p || !c)
- return;
-
- layout->removeWidget(c->sv);
- layout->removeWidget(c->button);
- c->sv->deleteLater(); // page might still be a child of sv
- delete c->button;
-
- bool removeCurrent = c == currentPage;
- pageList.removeAll(*c);
-
- if (!pageList.count()) {
- currentPage = 0;
- emit q->currentChanged(-1);
- } else if (removeCurrent) {
- currentPage = 0;
- q->setCurrentIndex(0);
- }
-}
-
-/*!
- Removes the item at position \a index from the toolbox. Note that
- the widget is \e not deleted.
-*/
-
-void QToolBox::removeItem(int index)
-{
- Q_D(QToolBox);
- if (QWidget *w = widget(index)) {
- disconnect(w, SIGNAL(destroyed(QObject*)), this, SLOT(_q_widgetDestroyed(QObject*)));
- w->setParent(this);
- // destroy internal data
- d->_q_widgetDestroyed(w);
- itemRemoved(index);
- }
-}
-
-
-/*!
- \property QToolBox::currentIndex
- \brief the index of the current item
-
- By default, for an empty toolbox, this property has a value of -1.
-
- \sa indexOf(), widget()
-*/
-
-
-int QToolBox::currentIndex() const
-{
- Q_D(const QToolBox);
- return d->currentPage ? indexOf(d->currentPage->widget) : -1;
-}
-
-/*!
- Returns a pointer to the current widget, or 0 if there is no such item.
-
- \sa currentIndex(), setCurrentWidget()
-*/
-
-QWidget * QToolBox::currentWidget() const
-{
- Q_D(const QToolBox);
- return d->currentPage ? d->currentPage->widget : 0;
-}
-
-/*!
- Makes\a widget the current widget. The \a widget must be an item in this tool box.
-
- \sa addItem(), setCurrentIndex(), currentWidget()
- */
-void QToolBox::setCurrentWidget(QWidget *widget)
-{
- int i = indexOf(widget);
- if (i >= 0)
- setCurrentIndex(i);
- else
- qWarning("QToolBox::setCurrentWidget: widget not contained in tool box");
-}
-
-/*!
- Returns the widget at position \a index, or 0 if there is no such
- item.
-*/
-
-QWidget *QToolBox::widget(int index) const
-{
- Q_D(const QToolBox);
- if (index < 0 || index >= (int) d->pageList.size())
- return 0;
- return d->pageList.at(index).widget;
-}
-
-/*!
- Returns the index of \a widget, or -1 if the item does not
- exist.
-*/
-
-int QToolBox::indexOf(QWidget *widget) const
-{
- Q_D(const QToolBox);
- QToolBoxPrivate::Page *c = (widget ? d->page(widget) : 0);
- return c ? d->pageList.indexOf(*c) : -1;
-}
-
-/*!
- If \a enabled is true then the item at position \a index is enabled; otherwise
- the item at position \a index is disabled.
-*/
-
-void QToolBox::setItemEnabled(int index, bool enabled)
-{
- Q_D(QToolBox);
- QToolBoxPrivate::Page *c = d->page(index);
- if (!c)
- return;
-
- c->button->setEnabled(enabled);
- if (!enabled && c == d->currentPage) {
- int curIndexUp = index;
- int curIndexDown = curIndexUp;
- const int count = d->pageList.count();
- while (curIndexUp > 0 || curIndexDown < count-1) {
- if (curIndexDown < count-1) {
- if (d->page(++curIndexDown)->button->isEnabled()) {
- index = curIndexDown;
- break;
- }
- }
- if (curIndexUp > 0) {
- if (d->page(--curIndexUp)->button->isEnabled()) {
- index = curIndexUp;
- break;
- }
- }
- }
- setCurrentIndex(index);
- }
-}
-
-
-/*!
- Sets the text of the item at position \a index to \a text.
-
- If the provided text contains an ampersand character ('&'), a
- mnemonic is automatically created for it. The character that
- follows the '&' will be used as the shortcut key. Any previous
- mnemonic will be overwritten, or cleared if no mnemonic is defined
- by the text. See the \l {QShortcut#mnemonic}{QShortcut}
- documentation for details (to display an actual ampersand, use
- '&&').
-*/
-
-void QToolBox::setItemText(int index, const QString &text)
-{
- Q_D(QToolBox);
- QToolBoxPrivate::Page *c = d->page(index);
- if (c)
- c->setText(text);
-}
-
-/*!
- Sets the icon of the item at position \a index to \a icon.
-*/
-
-void QToolBox::setItemIcon(int index, const QIcon &icon)
-{
- Q_D(QToolBox);
- QToolBoxPrivate::Page *c = d->page(index);
- if (c)
- c->setIcon(icon);
-}
-
-#ifndef QT_NO_TOOLTIP
-/*!
- Sets the tooltip of the item at position \a index to \a toolTip.
-*/
-
-void QToolBox::setItemToolTip(int index, const QString &toolTip)
-{
- Q_D(QToolBox);
- QToolBoxPrivate::Page *c = d->page(index);
- if (c)
- c->setToolTip(toolTip);
-}
-#endif // QT_NO_TOOLTIP
-
-/*!
- Returns true if the item at position \a index is enabled; otherwise returns false.
-*/
-
-bool QToolBox::isItemEnabled(int index) const
-{
- Q_D(const QToolBox);
- const QToolBoxPrivate::Page *c = d->page(index);
- return c && c->button->isEnabled();
-}
-
-/*!
- Returns the text of the item at position \a index, or an empty string if
- \a index is out of range.
-*/
-
-QString QToolBox::itemText(int index) const
-{
- Q_D(const QToolBox);
- const QToolBoxPrivate::Page *c = d->page(index);
- return (c ? c->text() : QString());
-}
-
-/*!
- Returns the icon of the item at position \a index, or a null
- icon if \a index is out of range.
-*/
-
-QIcon QToolBox::itemIcon(int index) const
-{
- Q_D(const QToolBox);
- const QToolBoxPrivate::Page *c = d->page(index);
- return (c ? c->icon() : QIcon());
-}
-
-#ifndef QT_NO_TOOLTIP
-/*!
- Returns the tooltip of the item at position \a index, or an
- empty string if \a index is out of range.
-*/
-
-QString QToolBox::itemToolTip(int index) const
-{
- Q_D(const QToolBox);
- const QToolBoxPrivate::Page *c = d->page(index);
- return (c ? c->toolTip() : QString());
-}
-#endif // QT_NO_TOOLTIP
-
-/*! \reimp */
-void QToolBox::showEvent(QShowEvent *e)
-{
- QWidget::showEvent(e);
-}
-
-/*! \reimp */
-void QToolBox::changeEvent(QEvent *ev)
-{
- Q_D(QToolBox);
- if(ev->type() == QEvent::StyleChange)
- d->updateTabs();
- QFrame::changeEvent(ev);
-}
-
-/*!
- This virtual handler is called after a new item was added or
- inserted at position \a index.
-
- \sa itemRemoved()
- */
-void QToolBox::itemInserted(int index)
-{
- Q_UNUSED(index)
-}
-
-/*!
- This virtual handler is called after an item was removed from
- position \a index.
-
- \sa itemInserted()
- */
-void QToolBox::itemRemoved(int index)
-{
- Q_UNUSED(index)
-}
-
-/*!
- \fn void QToolBox::setItemLabel(int index, const QString &text)
-
- Use setItemText() instead.
-*/
-
-/*!
- \fn QString QToolBox::itemLabel(int index) const
-
- Use itemText() instead.
-*/
-
-/*!
- \fn QWidget *QToolBox::currentItem() const
-
- Use widget(currentIndex()) instead.
-*/
-
-/*!
- \fn void QToolBox::setCurrentItem(QWidget *widget)
-
- Use setCurrentIndex(indexOf(widget)) instead.
-*/
-
-/*!
- \fn void QToolBox::setItemIconSet(int index, const QIcon &icon)
-
- Use setItemIcon() instead.
-*/
-
-/*!
- \fn QIcon QToolBox::itemIconSet(int index) const
-
- Use itemIcon() instead.
-*/
-
-/*!
- \fn int QToolBox::removeItem(QWidget *widget)
-
- Use toolbox->removeItem(toolbox->indexOf(widget)) instead.
-*/
-
-/*!
- \fn QWidget *QToolBox::item(int index) const
-
- Use widget() instead.
-*/
-
-/*!
- \fn void QToolBox::setMargin(int margin)
- Sets the width of the margin around the contents of the widget to \a margin.
-
- Use QWidget::setContentsMargins() instead.
- \sa margin(), QWidget::setContentsMargins()
-*/
-
-/*!
- \fn int QToolBox::margin() const
- Returns the width of the margin around the contents of the widget.
-
- Use QWidget::getContentsMargins() instead.
- \sa setMargin(), QWidget::getContentsMargins()
-*/
-
-/*! \reimp */
-bool QToolBox::event(QEvent *e)
-{
- return QFrame::event(e);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qtoolbox.cpp"
-#include "qtoolbox.moc"
-
-#endif //QT_NO_TOOLBOX
diff --git a/src/gui/widgets/qtoolbox.h b/src/gui/widgets/qtoolbox.h
deleted file mode 100644
index f004ee7b04..0000000000
--- a/src/gui/widgets/qtoolbox.h
+++ /dev/null
@@ -1,148 +0,0 @@
-/****************************************************************************
-**
-** 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 QTOOLBOX_H
-#define QTOOLBOX_H
-
-#include <QtGui/qframe.h>
-#include <QtGui/qicon.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TOOLBOX
-
-class QToolBoxPrivate;
-
-class Q_GUI_EXPORT QToolBox : public QFrame
-{
- Q_OBJECT
- Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentChanged)
- Q_PROPERTY(int count READ count)
-
-public:
- explicit QToolBox(QWidget *parent = 0, Qt::WindowFlags f = 0);
- ~QToolBox();
-
- int addItem(QWidget *widget, const QString &text);
- int addItem(QWidget *widget, const QIcon &icon, const QString &text);
- int insertItem(int index, QWidget *widget, const QString &text);
- int insertItem(int index, QWidget *widget, const QIcon &icon, const QString &text);
-
- void removeItem(int index);
-
- void setItemEnabled(int index, bool enabled);
- bool isItemEnabled(int index) const;
-
- void setItemText(int index, const QString &text);
- QString itemText(int index) const;
-
- void setItemIcon(int index, const QIcon &icon);
- QIcon itemIcon(int index) const;
-
-#ifndef QT_NO_TOOLTIP
- void setItemToolTip(int index, const QString &toolTip);
- QString itemToolTip(int index) const;
-#endif
-
- int currentIndex() const;
- QWidget *currentWidget() const;
- QWidget *widget(int index) const;
- int indexOf(QWidget *widget) const;
- int count() const;
-
-public Q_SLOTS:
- void setCurrentIndex(int index);
- void setCurrentWidget(QWidget *widget);
-
-Q_SIGNALS:
- void currentChanged(int index);
-
-protected:
- bool event(QEvent *e);
- virtual void itemInserted(int index);
- virtual void itemRemoved(int index);
- void showEvent(QShowEvent *e);
- void changeEvent(QEvent *);
-
-#ifdef QT3_SUPPORT
-public:
- QT3_SUPPORT_CONSTRUCTOR QToolBox(QWidget *parent, const char *name, Qt::WindowFlags f = 0);
- inline QT3_SUPPORT void setItemLabel(int index, const QString &text) { setItemText(index, text); }
- inline QT3_SUPPORT QString itemLabel(int index) const { return itemText(index); }
- inline QT3_SUPPORT QWidget *currentItem() const { return widget(currentIndex()); }
- inline QT3_SUPPORT void setCurrentItem(QWidget *item) { setCurrentIndex(indexOf(item)); }
- inline QT3_SUPPORT void setItemIconSet(int index, const QIcon &icon) { setItemIcon(index, icon); }
- inline QT3_SUPPORT QIcon itemIconSet(int index) const { return itemIcon(index); }
- inline QT3_SUPPORT int removeItem(QWidget *item)
- { int i = indexOf(item); removeItem(i); return i; }
- inline QT3_SUPPORT QWidget *item(int index) const { return widget(index); }
- QT3_SUPPORT void setMargin(int margin) { setContentsMargins(margin, margin, margin, margin); }
- QT3_SUPPORT int margin() const
- { int margin; int dummy; getContentsMargins(&margin, &dummy, &dummy, &dummy); return margin; }
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QToolBox)
- Q_DISABLE_COPY(QToolBox)
- Q_PRIVATE_SLOT(d_func(), void _q_buttonClicked())
- Q_PRIVATE_SLOT(d_func(), void _q_widgetDestroyed(QObject*))
-};
-
-
-inline int QToolBox::addItem(QWidget *item, const QString &text)
-{ return insertItem(-1, item, QIcon(), text); }
-inline int QToolBox::addItem(QWidget *item, const QIcon &iconSet,
- const QString &text)
-{ return insertItem(-1, item, iconSet, text); }
-inline int QToolBox::insertItem(int index, QWidget *item, const QString &text)
-{ return insertItem(index, item, QIcon(), text); }
-
-#endif // QT_NO_TOOLBOX
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTOOLBOX_H
diff --git a/src/gui/widgets/qtoolbutton.cpp b/src/gui/widgets/qtoolbutton.cpp
deleted file mode 100644
index 2c9f15cfd9..0000000000
--- a/src/gui/widgets/qtoolbutton.cpp
+++ /dev/null
@@ -1,1260 +0,0 @@
-/****************************************************************************
-**
-** 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 "qtoolbutton.h"
-#ifndef QT_NO_TOOLBUTTON
-
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <qdrawutil.h>
-#include <qevent.h>
-#include <qicon.h>
-#include <qmenu.h>
-#include <qpainter.h>
-#include <qpointer.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qtooltip.h>
-#include <qmainwindow.h>
-#include <qtoolbar.h>
-#include <qvariant.h>
-#include <qstylepainter.h>
-#include <private/qabstractbutton_p.h>
-#include <private/qaction_p.h>
-#include <private/qmenu_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QToolButtonPrivate : public QAbstractButtonPrivate
-{
- Q_DECLARE_PUBLIC(QToolButton)
-public:
- void init();
-#ifndef QT_NO_MENU
- void _q_buttonPressed();
- void popupTimerDone();
- void _q_updateButtonDown();
- void _q_menuTriggered(QAction *);
-#endif
- bool updateHoverControl(const QPoint &pos);
- void _q_actionTriggered();
- QStyle::SubControl newHoverControl(const QPoint &pos);
- QStyle::SubControl hoverControl;
- QRect hoverRect;
- QPointer<QAction> menuAction; //the menu set by the user (setMenu)
- QBasicTimer popupTimer;
- int delay;
- Qt::ArrowType arrowType;
- Qt::ToolButtonStyle toolButtonStyle;
- QToolButton::ToolButtonPopupMode popupMode;
- enum { NoButtonPressed=0, MenuButtonPressed=1, ToolButtonPressed=2 };
- uint buttonPressed : 2;
- uint menuButtonDown : 1;
- uint autoRaise : 1;
- uint repeat : 1;
- QAction *defaultAction;
-#ifndef QT_NO_MENU
- bool hasMenu() const;
- //workaround for task 177850
- QList<QAction *> actionsCopy;
-#endif
-#ifdef QT3_SUPPORT
- bool userDefinedPopupDelay;
-#endif
-};
-
-#ifndef QT_NO_MENU
-bool QToolButtonPrivate::hasMenu() const
-{
- return ((defaultAction && defaultAction->menu())
- || (menuAction && menuAction->menu())
- || actions.size() > (defaultAction ? 1 : 0));
-}
-#endif
-
-/*!
- \class QToolButton
- \brief The QToolButton class provides a quick-access button to
- commands or options, usually used inside a QToolBar.
-
- \ingroup basicwidgets
-
-
- A tool button is a special button that provides quick-access to
- specific commands or options. As opposed to a normal command
- button, a tool button usually doesn't show a text label, but shows
- an icon instead.
-
- Tool buttons are normally created when new QAction instances are
- created with QToolBar::addAction() or existing actions are added
- to a toolbar with QToolBar::addAction(). It is also possible to
- construct tool buttons in the same way as any other widget, and
- arrange them alongside other widgets in layouts.
-
- One classic use of a tool button is to select tools; for example,
- the "pen" tool in a drawing program. This would be implemented
- by using a QToolButton as a toggle button (see setToggleButton()).
-
- QToolButton supports auto-raising. In auto-raise mode, the button
- draws a 3D frame only when the mouse points at it. The feature is
- automatically turned on when a button is used inside a QToolBar.
- Change it with setAutoRaise().
-
- A tool button's icon is set as QIcon. This makes it possible to
- specify different pixmaps for the disabled and active state. The
- disabled pixmap is used when the button's functionality is not
- available. The active pixmap is displayed when the button is
- auto-raised because the mouse pointer is hovering over it.
-
- The button's look and dimension is adjustable with
- setToolButtonStyle() and setIconSize(). When used inside a
- QToolBar in a QMainWindow, the button automatically adjusts to
- QMainWindow's settings (see QMainWindow::setToolButtonStyle() and
- QMainWindow::setIconSize()). Instead of an icon, a tool button can
- also display an arrow symbol, specified with
- \l{QToolButton::arrowType} {arrowType}.
-
- A tool button can offer additional choices in a popup menu. The
- popup menu can be set using setMenu(). Use setPopupMode() to
- configure the different modes available for tool buttons with a
- menu set. The default mode is DelayedPopupMode which is sometimes
- used with the "Back" button in a web browser. After pressing and
- holding the button down for a while, a menu pops up showing a list
- of possible pages to jump to. The default delay is 600 ms; you can
- adjust it with setPopupDelay().
-
- \table 100%
- \row \o \inlineimage assistant-toolbar.png Qt Assistant's toolbar with tool buttons
- \row \o Qt Assistant's toolbar contains tool buttons that are associated
- with actions used in other parts of the main window.
- \endtable
-
- \sa QPushButton, QToolBar, QMainWindow, QAction,
- {fowler}{GUI Design Handbook: Push Button}
-*/
-
-/*!
- \fn void QToolButton::triggered(QAction *action)
-
- This signal is emitted when the given \a action is triggered.
-
- The action may also be associated with other parts of the user interface,
- such as menu items and keyboard shortcuts. Sharing actions in this
- way helps make the user interface more consistent and is often less work
- to implement.
-*/
-
-/*!
- Constructs an empty tool button with parent \a
- parent.
-*/
-QToolButton::QToolButton(QWidget * parent)
- : QAbstractButton(*new QToolButtonPrivate, parent)
-{
- Q_D(QToolButton);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Constructs an empty tool button called \a name, with parent \a
- parent.
-*/
-
-QToolButton::QToolButton(QWidget * parent, const char *name)
- : QAbstractButton(*new QToolButtonPrivate, parent)
-{
- Q_D(QToolButton);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-
-/*!
- Constructs a tool button called \a name, that is a child of \a
- parent.
-
- The tool button will display the given \a icon, with its text
- label and tool tip set to \a textLabel and its status bar message
- set to \a statusTip. It will be connected to the \a slot in
- object \a receiver.
-*/
-
-QToolButton::QToolButton(const QIcon& icon, const QString &textLabel,
- const QString& statusTip,
- QObject * receiver, const char *slot,
- QWidget * parent, const char *name)
- : QAbstractButton(*new QToolButtonPrivate, parent)
-{
- Q_D(QToolButton);
- setObjectName(QString::fromAscii(name));
- d->init();
- setIcon(icon);
- setText(textLabel);
- if (receiver && slot)
- connect(this, SIGNAL(clicked()), receiver, slot);
-#ifndef QT_NO_TOOLTIP
- if (!textLabel.isEmpty())
- setToolTip(textLabel);
-#endif
-#ifndef QT_NO_STATUSTIP
- if (!statusTip.isEmpty())
- setStatusTip(statusTip);
-#else
- Q_UNUSED(statusTip);
-#endif
-}
-
-
-/*!
- Constructs a tool button as an arrow button. The Qt::ArrowType \a
- type defines the arrow direction. Possible values are
- Qt::LeftArrow, Qt::RightArrow, Qt::UpArrow, and Qt::DownArrow.
-
- An arrow button has auto-repeat turned on by default.
-
- The \a parent and \a name arguments are sent to the QWidget
- constructor.
-*/
-QToolButton::QToolButton(Qt::ArrowType type, QWidget *parent, const char *name)
- : QAbstractButton(*new QToolButtonPrivate, parent)
-{
- Q_D(QToolButton);
- setObjectName(QString::fromAscii(name));
- d->init();
- setAutoRepeat(true);
- d->arrowType = type;
-}
-
-#endif
-
-
-/* Set-up code common to all the constructors */
-
-void QToolButtonPrivate::init()
-{
- Q_Q(QToolButton);
- delay = q->style()->styleHint(QStyle::SH_ToolButton_PopupDelay, 0, q);
-#ifdef QT3_SUPPORT
- userDefinedPopupDelay = false;
-#endif
- defaultAction = 0;
-#ifndef QT_NO_TOOLBAR
- if (qobject_cast<QToolBar*>(parent))
- autoRaise = true;
- else
-#endif
- autoRaise = false;
- arrowType = Qt::NoArrow;
- menuButtonDown = false;
- popupMode = QToolButton::DelayedPopup;
- buttonPressed = QToolButtonPrivate::NoButtonPressed;
-
- toolButtonStyle = Qt::ToolButtonIconOnly;
- hoverControl = QStyle::SC_None;
-
- q->setFocusPolicy(Qt::TabFocus);
- q->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed,
- QSizePolicy::ToolButton));
-
-#ifndef QT_NO_MENU
- QObject::connect(q, SIGNAL(pressed()), q, SLOT(_q_buttonPressed()));
-#endif
-
- setLayoutItemMargins(QStyle::SE_ToolButtonLayoutItem);
-
-}
-
-/*!
- Initialize \a option with the values from this QToolButton. This method
- is useful for subclasses when they need a QStyleOptionToolButton, but don't want
- to fill in all the information themselves.
-
- \sa QStyleOption::initFrom()
-*/
-void QToolButton::initStyleOption(QStyleOptionToolButton *option) const
-{
- if (!option)
- return;
-
- Q_D(const QToolButton);
- option->initFrom(this);
- bool forceNoText = false;
- option->iconSize = iconSize(); //default value
-
-#ifndef QT_NO_TOOLBAR
- if (parentWidget()) {
- if (QToolBar *toolBar = qobject_cast<QToolBar *>(parentWidget())) {
- option->iconSize = toolBar->iconSize();
- }
-#ifdef QT3_SUPPORT
- else if (parentWidget()->inherits("Q3ToolBar")) {
- if (!option->iconSize.isValid()) {
- int iconSize = style()->pixelMetric(QStyle::PM_ToolBarIconSize, option, this);
- option->iconSize = d->icon.actualSize(QSize(iconSize, iconSize));
- }
- forceNoText = d->toolButtonStyle == Qt::ToolButtonIconOnly;
- }
-#endif
- }
-#endif // QT_NO_TOOLBAR
-
- if (!forceNoText)
- option->text = d->text;
- option->icon = d->icon;
- option->arrowType = d->arrowType;
- if (d->down)
- option->state |= QStyle::State_Sunken;
- if (d->checked)
- option->state |= QStyle::State_On;
- if (d->autoRaise)
- option->state |= QStyle::State_AutoRaise;
- if (!d->checked && !d->down)
- option->state |= QStyle::State_Raised;
-
- option->subControls = QStyle::SC_ToolButton;
- option->activeSubControls = QStyle::SC_None;
-
- option->features = QStyleOptionToolButton::None;
- if (d->popupMode == QToolButton::MenuButtonPopup) {
- option->subControls |= QStyle::SC_ToolButtonMenu;
- option->features |= QStyleOptionToolButton::MenuButtonPopup;
- }
- if (option->state & QStyle::State_MouseOver) {
- option->activeSubControls = d->hoverControl;
- }
- if (d->menuButtonDown) {
- option->state |= QStyle::State_Sunken;
- option->activeSubControls |= QStyle::SC_ToolButtonMenu;
- }
- if (d->down) {
- option->state |= QStyle::State_Sunken;
- option->activeSubControls |= QStyle::SC_ToolButton;
- }
-
-
- if (d->arrowType != Qt::NoArrow)
- option->features |= QStyleOptionToolButton::Arrow;
- if (d->popupMode == QToolButton::DelayedPopup)
- option->features |= QStyleOptionToolButton::PopupDelay;
-#ifndef QT_NO_MENU
- if (d->hasMenu())
- option->features |= QStyleOptionToolButton::HasMenu;
-#endif
- if (d->toolButtonStyle == Qt::ToolButtonFollowStyle) {
- option->toolButtonStyle = Qt::ToolButtonStyle(style()->styleHint(QStyle::SH_ToolButtonStyle, option, this));
- } else
- option->toolButtonStyle = d->toolButtonStyle;
-
- if (option->toolButtonStyle == Qt::ToolButtonTextBesideIcon) {
- // If the action is not prioritized, remove the text label to save space
- if (d->defaultAction && d->defaultAction->priority() < QAction::NormalPriority)
- option->toolButtonStyle = Qt::ToolButtonIconOnly;
- }
-
- if (d->icon.isNull() && d->arrowType == Qt::NoArrow && !forceNoText) {
- if (!d->text.isEmpty())
- option->toolButtonStyle = Qt::ToolButtonTextOnly;
- else if (option->toolButtonStyle != Qt::ToolButtonTextOnly)
- option->toolButtonStyle = Qt::ToolButtonIconOnly;
- }
-
- option->pos = pos();
- option->font = font();
-}
-
-/*!
- Destroys the object and frees any allocated resources.
-*/
-
-QToolButton::~QToolButton()
-{
-}
-
-/*!
- \reimp
-*/
-QSize QToolButton::sizeHint() const
-{
- Q_D(const QToolButton);
- if (d->sizeHint.isValid())
- return d->sizeHint;
- ensurePolished();
-
- int w = 0, h = 0;
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
-
- QFontMetrics fm = fontMetrics();
- if (opt.toolButtonStyle != Qt::ToolButtonTextOnly) {
- QSize icon = opt.iconSize;
- w = icon.width();
- h = icon.height();
- }
-
- if (opt.toolButtonStyle != Qt::ToolButtonIconOnly) {
- QSize textSize = fm.size(Qt::TextShowMnemonic, text());
- textSize.setWidth(textSize.width() + fm.width(QLatin1Char(' '))*2);
- if (opt.toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
- h += 4 + textSize.height();
- if (textSize.width() > w)
- w = textSize.width();
- } else if (opt.toolButtonStyle == Qt::ToolButtonTextBesideIcon) {
- w += 4 + textSize.width();
- if (textSize.height() > h)
- h = textSize.height();
- } else { // TextOnly
- w = textSize.width();
- h = textSize.height();
- }
- }
-
- opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height
- if (d->popupMode == MenuButtonPopup)
- w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this);
-
- d->sizeHint = style()->sizeFromContents(QStyle::CT_ToolButton, &opt, QSize(w, h), this).
- expandedTo(QApplication::globalStrut());
- return d->sizeHint;
-}
-
-/*!
- \reimp
- */
-QSize QToolButton::minimumSizeHint() const
-{
- return sizeHint();
-}
-
-/*!
- \enum QToolButton::TextPosition
- \compat
-
- This enum describes the position of the tool button's text label in
- relation to the tool button's icon.
-
- \value BesideIcon The text appears beside the icon.
- \value BelowIcon The text appears below the icon.
- \omitvalue Right
- \omitvalue Under
-*/
-
-/*!
- \property QToolButton::toolButtonStyle
- \brief whether the tool button displays an icon only, text only,
- or text beside/below the icon.
-
- The default is Qt::ToolButtonIconOnly.
-
- To have the style of toolbuttons follow the system settings (as available
- in GNOME and KDE desktop environments), set this property to Qt::ToolButtonFollowStyle.
-
- QToolButton automatically connects this slot to the relevant
- signal in the QMainWindow in which is resides.
-*/
-
-/*!
- \property QToolButton::arrowType
- \brief whether the button displays an arrow instead of a normal icon
-
- This displays an arrow as the icon for the QToolButton.
-
- By default, this property is set to Qt::NoArrow.
-*/
-
-Qt::ToolButtonStyle QToolButton::toolButtonStyle() const
-{
- Q_D(const QToolButton);
- return d->toolButtonStyle;
-}
-
-Qt::ArrowType QToolButton::arrowType() const
-{
- Q_D(const QToolButton);
- return d->arrowType;
-}
-
-
-void QToolButton::setToolButtonStyle(Qt::ToolButtonStyle style)
-{
- Q_D(QToolButton);
- if (d->toolButtonStyle == style)
- return;
-
- d->toolButtonStyle = style;
- d->sizeHint = QSize();
- updateGeometry();
- if (isVisible()) {
- update();
- }
-}
-
-void QToolButton::setArrowType(Qt::ArrowType type)
-{
- Q_D(QToolButton);
- if (d->arrowType == type)
- return;
-
- d->arrowType = type;
- d->sizeHint = QSize();
- updateGeometry();
- if (isVisible()) {
- update();
- }
-}
-
-/*!
- \fn void QToolButton::paintEvent(QPaintEvent *event)
-
- Paints the button in response to the paint \a event.
-*/
-void QToolButton::paintEvent(QPaintEvent *)
-{
- QStylePainter p(this);
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
- p.drawComplexControl(QStyle::CC_ToolButton, opt);
-}
-
-/*!
- \reimp
- */
-void QToolButton::actionEvent(QActionEvent *event)
-{
- Q_D(QToolButton);
- QAction *action = event->action();
- switch (event->type()) {
- case QEvent::ActionChanged:
- if (action == d->defaultAction)
- setDefaultAction(action); // update button state
- break;
- case QEvent::ActionAdded:
- connect(action, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
- break;
- case QEvent::ActionRemoved:
- if (d->defaultAction == action)
- d->defaultAction = 0;
-#ifndef QT_NO_MENU
- if (action == d->menuAction)
- d->menuAction = 0;
-#endif
- action->disconnect(this);
- break;
- default:
- ;
- }
- QAbstractButton::actionEvent(event);
-}
-
-QStyle::SubControl QToolButtonPrivate::newHoverControl(const QPoint &pos)
-{
- Q_Q(QToolButton);
- QStyleOptionToolButton opt;
- q->initStyleOption(&opt);
- opt.subControls = QStyle::SC_All;
- hoverControl = q->style()->hitTestComplexControl(QStyle::CC_ToolButton, &opt, pos, q);
- if (hoverControl == QStyle::SC_None)
- hoverRect = QRect();
- else
- hoverRect = q->style()->subControlRect(QStyle::CC_ToolButton, &opt, hoverControl, q);
- return hoverControl;
-}
-
-bool QToolButtonPrivate::updateHoverControl(const QPoint &pos)
-{
- Q_Q(QToolButton);
- QRect lastHoverRect = hoverRect;
- QStyle::SubControl lastHoverControl = hoverControl;
- bool doesHover = q->testAttribute(Qt::WA_Hover);
- if (lastHoverControl != newHoverControl(pos) && doesHover) {
- q->update(lastHoverRect);
- q->update(hoverRect);
- return true;
- }
- return !doesHover;
-}
-
-void QToolButtonPrivate::_q_actionTriggered()
-{
- Q_Q(QToolButton);
- if (QAction *action = qobject_cast<QAction *>(q->sender()))
- emit q->triggered(action);
-}
-
-/*!
- \reimp
- */
-void QToolButton::enterEvent(QEvent * e)
-{
- Q_D(QToolButton);
- if (d->autoRaise)
- update();
- if (d->defaultAction)
- d->defaultAction->hover();
- QAbstractButton::enterEvent(e);
-}
-
-
-/*!
- \reimp
- */
-void QToolButton::leaveEvent(QEvent * e)
-{
- Q_D(QToolButton);
- if (d->autoRaise)
- update();
-
- QAbstractButton::leaveEvent(e);
-}
-
-
-/*!
- \reimp
- */
-void QToolButton::timerEvent(QTimerEvent *e)
-{
-#ifndef QT_NO_MENU
- Q_D(QToolButton);
- if (e->timerId() == d->popupTimer.timerId()) {
- d->popupTimerDone();
- return;
- }
-#endif
- QAbstractButton::timerEvent(e);
-}
-
-
-/*!
- \reimp
-*/
-void QToolButton::changeEvent(QEvent *e)
-{
-#ifndef QT_NO_TOOLBAR
- Q_D(QToolButton);
- if (e->type() == QEvent::ParentChange) {
- if (qobject_cast<QToolBar*>(parentWidget()))
- d->autoRaise = true;
- } else if (e->type() == QEvent::StyleChange
-#ifdef Q_WS_MAC
- || e->type() == QEvent::MacSizeChange
-#endif
- ) {
-#ifdef QT3_SUPPORT
- if (!d->userDefinedPopupDelay)
-#endif
- d->delay = style()->styleHint(QStyle::SH_ToolButton_PopupDelay, 0, this);
- d->setLayoutItemMargins(QStyle::SE_ToolButtonLayoutItem);
- }
-#endif
- QAbstractButton::changeEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QToolButton::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QToolButton);
-#ifndef QT_NO_MENU
- QStyleOptionToolButton opt;
- initStyleOption(&opt);
- if (e->button() == Qt::LeftButton && (d->popupMode == MenuButtonPopup)) {
- QRect popupr = style()->subControlRect(QStyle::CC_ToolButton, &opt,
- QStyle::SC_ToolButtonMenu, this);
- if (popupr.isValid() && popupr.contains(e->pos())) {
- d->buttonPressed = QToolButtonPrivate::MenuButtonPressed;
- showMenu();
- return;
- }
- }
-#endif
- d->buttonPressed = QToolButtonPrivate::ToolButtonPressed;
- QAbstractButton::mousePressEvent(e);
-}
-
-/*!
- \reimp
-*/
-void QToolButton::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QToolButton);
- QAbstractButton::mouseReleaseEvent(e);
- d->buttonPressed = QToolButtonPrivate::NoButtonPressed;
-}
-
-/*!
- \reimp
-*/
-bool QToolButton::hitButton(const QPoint &pos) const
-{
- Q_D(const QToolButton);
- if(QAbstractButton::hitButton(pos))
- return (d->buttonPressed != QToolButtonPrivate::MenuButtonPressed);
- return false;
-}
-
-#ifdef QT3_SUPPORT
-
-/*!
- Use icon() instead.
-*/
-QIcon QToolButton::onIconSet() const
-{
- return icon();
-}
-
-/*!
- Use icon() instead.
-*/
-QIcon QToolButton::offIconSet() const
-{
- return icon();
-}
-
-
-/*!
- \obsolete
-
- Use setIcon() instead.
-*/
-void QToolButton::setOnIconSet(const QIcon& set)
-{
- setIcon(set);
-}
-
-/*!
- \obsolete
-
- Use setIcon() instead.
-*/
-void QToolButton::setOffIconSet(const QIcon& set)
-{
- setIcon(set);
-}
-
-
-/*! \overload
- \obsolete
-
- Since Qt 3.0, QIcon contains both the On and Off icons.
-
- For ease of porting, this function ignores the \a on parameter and
- sets the \l{QAbstractButton::icon} {icon} property. If you relied on
- the \a on parameter, you probably want to update your code to use
- the QIcon On/Off mechanism.
-
- \sa icon QIcon::State
-*/
-
-void QToolButton::setIconSet(const QIcon & set, bool /* on */)
-{
- QAbstractButton::setIcon(set);
-}
-
-/*! \overload
- \obsolete
-
- Since Qt 3.0, QIcon contains both the On and Off icons.
-
- For ease of porting, this function ignores the \a on parameter and
- returns the \l{QAbstractButton::icon} {icon} property. If you relied
- on the \a on parameter, you probably want to update your code to use
- the QIcon On/Off mechanism.
-*/
-QIcon QToolButton::iconSet(bool /* on */) const
-{
- return QAbstractButton::icon();
-}
-
-#endif
-
-#ifndef QT_NO_MENU
-/*!
- Associates the given \a menu with this tool button.
-
- The menu will be shown according to the button's \l popupMode.
-
- Ownership of the menu is not transferred to the tool button.
-
- \sa menu()
-*/
-void QToolButton::setMenu(QMenu* menu)
-{
- Q_D(QToolButton);
-
- if (d->menuAction)
- removeAction(d->menuAction);
-
- if (menu) {
- d->menuAction = menu->menuAction();
- addAction(d->menuAction);
- } else {
- d->menuAction = 0;
- }
- update();
-}
-
-/*!
- Returns the associated menu, or 0 if no menu has been defined.
-
- \sa setMenu()
-*/
-QMenu* QToolButton::menu() const
-{
- Q_D(const QToolButton);
- if (d->menuAction)
- return d->menuAction->menu();
- return 0;
-}
-
-/*!
- Shows (pops up) the associated popup menu. If there is no such
- menu, this function does nothing. This function does not return
- until the popup menu has been closed by the user.
-*/
-void QToolButton::showMenu()
-{
- Q_D(QToolButton);
- if (!d->hasMenu()) {
- d->menuButtonDown = false;
- return; // no menu to show
- }
-
- d->menuButtonDown = true;
- repaint();
- d->popupTimer.stop();
- d->popupTimerDone();
-}
-
-void QToolButtonPrivate::_q_buttonPressed()
-{
- Q_Q(QToolButton);
- if (!hasMenu())
- return; // no menu to show
- if (popupMode == QToolButton::MenuButtonPopup)
- return;
- else if (delay > 0 && !popupTimer.isActive() && popupMode == QToolButton::DelayedPopup)
- popupTimer.start(delay, q);
- else if (delay == 0 || popupMode == QToolButton::InstantPopup)
- q->showMenu();
-}
-
-void QToolButtonPrivate::popupTimerDone()
-{
- Q_Q(QToolButton);
- popupTimer.stop();
- if (!menuButtonDown && !down)
- return;
-
- menuButtonDown = true;
- QPointer<QMenu> actualMenu;
- bool mustDeleteActualMenu = false;
- if(menuAction) {
- actualMenu = menuAction->menu();
- } else if (defaultAction && defaultAction->menu()) {
- actualMenu = defaultAction->menu();
- } else {
- actualMenu = new QMenu(q);
- mustDeleteActualMenu = true;
- for(int i = 0; i < actions.size(); i++)
- actualMenu->addAction(actions.at(i));
- }
- repeat = q->autoRepeat();
- q->setAutoRepeat(false);
- bool horizontal = true;
-#if !defined(QT_NO_TOOLBAR)
- QToolBar *tb = qobject_cast<QToolBar*>(parent);
- if (tb && tb->orientation() == Qt::Vertical)
- horizontal = false;
-#endif
- QPoint p;
- QRect screen = QApplication::desktop()->availableGeometry(q);
- QSize sh = ((QToolButton*)(QMenu*)actualMenu)->receivers(SIGNAL(aboutToShow()))? QSize() : actualMenu->sizeHint();
- QRect rect = q->rect();
- if (horizontal) {
- if (q->isRightToLeft()) {
- if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
- p = q->mapToGlobal(rect.bottomRight());
- } else {
- p = q->mapToGlobal(rect.topRight() - QPoint(0, sh.height()));
- }
- p.rx() -= sh.width();
- } else {
- if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
- p = q->mapToGlobal(rect.bottomLeft());
- } else {
- p = q->mapToGlobal(rect.topLeft() - QPoint(0, sh.height()));
- }
- }
- } else {
- if (q->isRightToLeft()) {
- if (q->mapToGlobal(QPoint(rect.left(), 0)).x() - sh.width() <= screen.x()) {
- p = q->mapToGlobal(rect.topRight());
- } else {
- p = q->mapToGlobal(rect.topLeft());
- p.rx() -= sh.width();
- }
- } else {
- if (q->mapToGlobal(QPoint(rect.right(), 0)).x() + sh.width() <= screen.right()) {
- p = q->mapToGlobal(rect.topRight());
- } else {
- p = q->mapToGlobal(rect.topLeft() - QPoint(sh.width(), 0));
- }
- }
- }
- p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
- p.ry() += 1;
- QPointer<QToolButton> that = q;
- actualMenu->setNoReplayFor(q);
- if (!mustDeleteActualMenu) //only if action are not in this widget
- QObject::connect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
- QObject::connect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
- actualMenu->d_func()->causedPopup.widget = q;
- actualMenu->d_func()->causedPopup.action = defaultAction;
- actionsCopy = q->actions(); //(the list of action may be modified in slots)
- actualMenu->exec(p);
- QObject::disconnect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
- if (mustDeleteActualMenu)
- delete actualMenu;
- else
- QObject::disconnect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
-
- if (!that)
- return;
-
- actionsCopy.clear();
-
- if (repeat)
- q->setAutoRepeat(true);
-}
-
-void QToolButtonPrivate::_q_updateButtonDown()
-{
- Q_Q(QToolButton);
- menuButtonDown = false;
- if (q->isDown())
- q->setDown(false);
- else
- q->repaint();
-}
-
-void QToolButtonPrivate::_q_menuTriggered(QAction *action)
-{
- Q_Q(QToolButton);
- if (action && !actionsCopy.contains(action))
- emit q->triggered(action);
-}
-#endif // QT_NO_MENU
-
-#ifdef QT3_SUPPORT
-/*!
- \fn void QToolButton::setPopupDelay(int delay)
-
- Use the style hint QStyle::SH_ToolButton_PopupDelay instead.
-*/
-void QToolButton::setPopupDelay(int delay)
-{
- Q_D(QToolButton);
- d->userDefinedPopupDelay = true;
- d->delay = delay;
-
- update();
-}
-
-/*!
- Use the style hint QStyle::SH_ToolButton_PopupDelay instead.
-*/
-int QToolButton::popupDelay() const
-{
- Q_D(const QToolButton);
- return d->delay;
-}
-#endif
-
-#ifndef QT_NO_MENU
-/*! \enum QToolButton::ToolButtonPopupMode
-
- Describes how a menu should be popped up for tool buttons that has
- a menu set or contains a list of actions.
-
- \value DelayedPopup After pressing and holding the tool button
- down for a certain amount of time (the timeout is style dependant,
- see QStyle::SH_ToolButton_PopupDelay), the menu is displayed. A
- typical application example is the "back" button in some web
- browsers's tool bars. If the user clicks it, the browser simply
- browses back to the previous page. If the user presses and holds
- the button down for a while, the tool button shows a menu
- containing the current history list
-
- \value MenuButtonPopup In this mode the tool button displays a
- special arrow to indicate that a menu is present. The menu is
- displayed when the arrow part of the button is pressed.
-
- \value InstantPopup The menu is displayed, without delay, when
- the tool button is pressed. In this mode, the button's own action
- is not triggered.
-*/
-
-/*!
- \property QToolButton::popupMode
- \brief describes the way that popup menus are used with tool buttons
-
- By default, this property is set to \l DelayedPopup.
-*/
-
-void QToolButton::setPopupMode(ToolButtonPopupMode mode)
-{
- Q_D(QToolButton);
- d->popupMode = mode;
-}
-
-QToolButton::ToolButtonPopupMode QToolButton::popupMode() const
-{
- Q_D(const QToolButton);
- return d->popupMode;
-}
-#endif
-
-/*!
- \property QToolButton::autoRaise
- \brief whether auto-raising is enabled or not.
-
- The default is disabled (i.e. false).
-
- This property is currently ignored on Mac OS X when using QMacStyle.
-*/
-void QToolButton::setAutoRaise(bool enable)
-{
- Q_D(QToolButton);
- d->autoRaise = enable;
-
- update();
-}
-
-bool QToolButton::autoRaise() const
-{
- Q_D(const QToolButton);
- return d->autoRaise;
-}
-
-/*!
- Sets the default action to \a action.
-
- If a tool button has a default action, the action defines the
- button's properties like text, icon, tool tip, etc.
- */
-void QToolButton::setDefaultAction(QAction *action)
-{
- Q_D(QToolButton);
-#ifndef QT_NO_MENU
- bool hadMenu = false;
- hadMenu = d->hasMenu();
-#endif
- d->defaultAction = action;
- if (!action)
- return;
- if (!actions().contains(action))
- addAction(action);
- setText(action->iconText());
- setIcon(action->icon());
-#ifndef QT_NO_TOOLTIP
- setToolTip(action->toolTip());
-#endif
-#ifndef QT_NO_STATUSTIP
- setStatusTip(action->statusTip());
-#endif
-#ifndef QT_NO_WHATSTHIS
- setWhatsThis(action->whatsThis());
-#endif
-#ifndef QT_NO_MENU
- if (action->menu() && !hadMenu) {
- // new 'default' popup mode defined introduced by tool bar. We
- // should have changed QToolButton's default instead. Do that
- // in 4.2.
- setPopupMode(QToolButton::MenuButtonPopup);
- }
-#endif
- setCheckable(action->isCheckable());
- setChecked(action->isChecked());
- setEnabled(action->isEnabled());
- if (action->d_func()->fontSet)
- setFont(action->font());
-}
-
-
-/*!
- Returns the default action.
-
- \sa setDefaultAction()
- */
-QAction *QToolButton::defaultAction() const
-{
- Q_D(const QToolButton);
- return d->defaultAction;
-}
-
-
-
-/*!
- \reimp
- */
-void QToolButton::nextCheckState()
-{
- Q_D(QToolButton);
- if (!d->defaultAction)
- QAbstractButton::nextCheckState();
- else
- d->defaultAction->trigger();
-}
-
-/*! \reimp */
-bool QToolButton::event(QEvent *event)
-{
- switch(event->type()) {
- case QEvent::HoverEnter:
- case QEvent::HoverLeave:
- case QEvent::HoverMove:
- if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event))
- d_func()->updateHoverControl(he->pos());
- break;
- default:
- break;
- }
- return QAbstractButton::event(event);
-}
-
-/*! \internal
- */
-QToolButton::QToolButton(QToolButtonPrivate &dd, QWidget *parent)
- :QAbstractButton(dd, parent)
-{
- Q_D(QToolButton);
- d->init();
-}
-
-/*!
- \fn void QToolButton::setPixmap(const QPixmap &pixmap)
-
- Use setIcon(QIcon(pixmap)) instead.
-*/
-
-/*!
- \fn void QToolButton::setIconSet(const QIcon &icon)
-
- Use setIcon() instead.
-*/
-
-/*!
- \fn void QToolButton::setTextLabel(const QString &text, bool tooltip)
-
- Use setText() and setToolTip() instead.
-*/
-
-/*!
- \fn QString QToolButton::textLabel() const
-
- Use text() instead.
-*/
-
-/*!
- \fn QIcon QToolButton::iconSet() const
-
- Use icon() instead.
-*/
-
-/*!
- \fn void QToolButton::openPopup()
-
- Use showMenu() instead.
-*/
-
-/*!
- \fn void QToolButton::setPopup(QMenu* popup)
-
- Use setMenu() instead.
-*/
-
-/*!
- \fn QMenu* QToolButton::popup() const
-
- Use menu() instead.
-*/
-
-/*!
- \fn TextPosition QToolButton::textPosition() const
-
- Use toolButtonStyle() instead.
-*/
-
-/*!
- \fn void QToolButton::setTextPosition(QToolButton::TextPosition pos)
-
- Use setToolButtonStyle() instead.
-*/
-
-/*!
- \fn bool QToolButton::usesBigPixmap() const
-
- Use iconSize() instead.
-*/
-
-/*!
- \fn void QToolButton::setUsesBigPixmap(bool enable)
-
- Use setIconSize() instead.
-*/
-
-/*!
- \fn bool QToolButton::usesTextLabel() const
-
- Use toolButtonStyle() instead.
-*/
-
-/*!
- \fn void QToolButton::setUsesTextLabel(bool enable)
-
- Use setToolButtonStyle() instead.
-*/
-
-QT_END_NAMESPACE
-
-#include "moc_qtoolbutton.cpp"
-
-#endif
diff --git a/src/gui/widgets/qtoolbutton.h b/src/gui/widgets/qtoolbutton.h
deleted file mode 100644
index 6b5f70210e..0000000000
--- a/src/gui/widgets/qtoolbutton.h
+++ /dev/null
@@ -1,199 +0,0 @@
-/****************************************************************************
-**
-** 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 QTOOLBUTTON_H
-#define QTOOLBUTTON_H
-
-#include <QtGui/qabstractbutton.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_TOOLBUTTON
-
-class QToolButtonPrivate;
-class QMenu;
-class QStyleOptionToolButton;
-
-class Q_GUI_EXPORT QToolButton : public QAbstractButton
-{
- Q_OBJECT
- Q_ENUMS(Qt::ToolButtonStyle Qt::ArrowType ToolButtonPopupMode)
-#ifndef QT_NO_MENU
- Q_PROPERTY(ToolButtonPopupMode popupMode READ popupMode WRITE setPopupMode)
-#endif
- Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle)
- Q_PROPERTY(bool autoRaise READ autoRaise WRITE setAutoRaise)
- Q_PROPERTY(Qt::ArrowType arrowType READ arrowType WRITE setArrowType)
-
-public:
- enum ToolButtonPopupMode {
- DelayedPopup,
- MenuButtonPopup,
- InstantPopup
- };
-
- explicit QToolButton(QWidget * parent=0);
- ~QToolButton();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- Qt::ToolButtonStyle toolButtonStyle() const;
-
- Qt::ArrowType arrowType() const;
- void setArrowType(Qt::ArrowType type);
-
-#ifndef QT_NO_MENU
- void setMenu(QMenu* menu);
- QMenu* menu() const;
-
- void setPopupMode(ToolButtonPopupMode mode);
- ToolButtonPopupMode popupMode() const;
-#endif
-
- QAction *defaultAction() const;
-
- void setAutoRaise(bool enable);
- bool autoRaise() const;
-
-public Q_SLOTS:
-#ifndef QT_NO_MENU
- void showMenu();
-#endif
- void setToolButtonStyle(Qt::ToolButtonStyle style);
- void setDefaultAction(QAction *);
-
-Q_SIGNALS:
- void triggered(QAction *);
-
-protected:
- QToolButton(QToolButtonPrivate &, QWidget* parent);
- bool event(QEvent *e);
- void mousePressEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void paintEvent(QPaintEvent *);
- void actionEvent(QActionEvent *);
-
- void enterEvent(QEvent *);
- void leaveEvent(QEvent *);
- void timerEvent(QTimerEvent *);
- void changeEvent(QEvent *);
-
- bool hitButton(const QPoint &pos) const;
- void nextCheckState();
- void initStyleOption(QStyleOptionToolButton *option) const;
-
-private:
- Q_DISABLE_COPY(QToolButton)
- Q_DECLARE_PRIVATE(QToolButton)
-#ifndef QT_NO_MENU
- Q_PRIVATE_SLOT(d_func(), void _q_buttonPressed())
- Q_PRIVATE_SLOT(d_func(), void _q_updateButtonDown())
- Q_PRIVATE_SLOT(d_func(), void _q_menuTriggered(QAction*))
-#endif
- Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())
-
-#ifdef QT3_SUPPORT
-public:
- enum TextPosition {
- BesideIcon,
- BelowIcon
- , Right = BesideIcon,
- Under = BelowIcon
- };
-
- QT3_SUPPORT_CONSTRUCTOR QToolButton(QWidget * parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QToolButton(Qt::ArrowType type, QWidget *parent, const char* name);
- QT3_SUPPORT_CONSTRUCTOR QToolButton( const QIcon& s, const QString &textLabel,
- const QString& grouptext,
- QObject * receiver, const char* slot,
- QWidget * parent, const char* name=0 );
- inline QT3_SUPPORT void setPixmap(const QPixmap &pixmap) { setIcon(static_cast<QIcon>(pixmap)); }
- QT3_SUPPORT void setOnIconSet(const QIcon&);
- QT3_SUPPORT void setOffIconSet(const QIcon&);
- inline QT3_SUPPORT void setIconSet(const QIcon &icon){setIcon(icon);}
- QT3_SUPPORT void setIconSet(const QIcon &, bool on);
- inline QT3_SUPPORT void setTextLabel(const QString &text, bool tooltip = true) {
- setText(text);
-#ifndef QT_NO_TOOLTIP
- if (tooltip)
- setToolTip(text);
-#else
- Q_UNUSED(tooltip);
-#endif
- }
- inline QT3_SUPPORT QString textLabel() const { return text(); }
- QT3_SUPPORT QIcon onIconSet() const;
- QT3_SUPPORT QIcon offIconSet() const;
- QT3_SUPPORT QIcon iconSet(bool on) const;
- inline QT3_SUPPORT QIcon iconSet() const { return icon(); }
- inline QT3_SUPPORT void openPopup() { showMenu(); }
- inline QT3_SUPPORT void setPopup(QMenu* popup) {setMenu(popup); }
- inline QT3_SUPPORT QMenu* popup() const { return menu(); }
- inline QT3_SUPPORT bool usesBigPixmap() const { return iconSize().height() > 22; }
- inline QT3_SUPPORT bool usesTextLabel() const { return toolButtonStyle() != Qt::ToolButtonIconOnly; }
- inline QT3_SUPPORT TextPosition textPosition() const
- { return toolButtonStyle() == Qt::ToolButtonTextUnderIcon ? BelowIcon : BesideIcon; }
- QT3_SUPPORT void setPopupDelay(int delay);
- QT3_SUPPORT int popupDelay() const;
-
-public Q_SLOTS:
- QT_MOC_COMPAT void setUsesBigPixmap(bool enable)
- { setIconSize(enable?QSize(32,32):QSize(22,22)); }
- QT_MOC_COMPAT void setUsesTextLabel(bool enable)
- { setToolButtonStyle(enable?Qt::ToolButtonTextUnderIcon : Qt::ToolButtonIconOnly); }
- QT_MOC_COMPAT void setTextPosition(QToolButton::TextPosition pos)
- { setToolButtonStyle(pos == BesideIcon ? Qt::ToolButtonTextBesideIcon : Qt::ToolButtonTextUnderIcon); }
-
-#endif
-};
-
-#endif // QT_NO_TOOLBUTTON
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QTOOLBUTTON_H
diff --git a/src/gui/widgets/qwidgetanimator.cpp b/src/gui/widgets/qwidgetanimator.cpp
deleted file mode 100644
index 7530412c09..0000000000
--- a/src/gui/widgets/qwidgetanimator.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/****************************************************************************
-**
-** 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 <QtCore/qpropertyanimation.h>
-#include <QtGui/qwidget.h>
-#include <QtGui/private/qmainwindowlayout_p.h>
-
-#include "qwidgetanimator_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QWidgetAnimator::QWidgetAnimator(QMainWindowLayout *layout) : m_mainWindowLayout(layout)
-{
-}
-
-void QWidgetAnimator::abort(QWidget *w)
-{
-#ifndef QT_NO_ANIMATION
- AnimationMap::iterator it = m_animation_map.find(w);
- if (it == m_animation_map.end())
- return;
- QPropertyAnimation *anim = *it;
- m_animation_map.erase(it);
- anim->stop();
-#ifndef QT_NO_MAINWINDOW
- m_mainWindowLayout->animationFinished(w);
-#endif
-#else
- Q_UNUSED(w); //there is no animation to abort
-#endif //QT_NO_ANIMATION
-}
-
-#ifndef QT_NO_ANIMATION
-void QWidgetAnimator::animationFinished()
-{
- QPropertyAnimation *anim = qobject_cast<QPropertyAnimation*>(sender());
- abort(static_cast<QWidget*>(anim->targetObject()));
-}
-#endif //QT_NO_ANIMATION
-
-void QWidgetAnimator::animate(QWidget *widget, const QRect &_final_geometry, bool animate)
-{
- QRect r = widget->geometry();
- if (r.right() < 0 || r.bottom() < 0)
- r = QRect();
-
- animate = animate && !r.isNull() && !_final_geometry.isNull();
-
- // might make the wigdet go away by sending it to negative space
- const QRect final_geometry = _final_geometry.isValid() || widget->isWindow() ? _final_geometry :
- QRect(QPoint(-500 - widget->width(), -500 - widget->height()), widget->size());
-
-#ifndef QT_NO_ANIMATION
- AnimationMap::const_iterator it = m_animation_map.constFind(widget);
- if (it != m_animation_map.constEnd() && (*it)->endValue().toRect() == final_geometry)
- return;
-
- QPropertyAnimation *anim = new QPropertyAnimation(widget, "geometry", widget);
- anim->setDuration(animate ? 200 : 0);
- anim->setEasingCurve(QEasingCurve::InOutQuad);
- anim->setEndValue(final_geometry);
- m_animation_map[widget] = anim;
- connect(anim, SIGNAL(finished()), SLOT(animationFinished()));
- anim->start(QPropertyAnimation::DeleteWhenStopped);
-#else
- //we do it in one shot
- widget->setGeometry(final_geometry);
-#ifndef QT_NO_MAINWINDOW
- m_mainWindowLayout->animationFinished(widget);
-#endif //QT_NO_MAINWINDOW
-#endif //QT_NO_ANIMATION
-}
-
-bool QWidgetAnimator::animating() const
-{
- return !m_animation_map.isEmpty();
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qwidgetanimator_p.h b/src/gui/widgets/qwidgetanimator_p.h
deleted file mode 100644
index 37201c3207..0000000000
--- a/src/gui/widgets/qwidgetanimator_p.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGET_ANIMATOR_P_H
-#define QWIDGET_ANIMATOR_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of the QLibrary class. This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qobject.h>
-#include <qmap.h>
-
-QT_BEGIN_NAMESPACE
-
-class QWidget;
-class QMainWindowLayout;
-class QPropertyAnimation;
-class QRect;
-
-class QWidgetAnimator : public QObject
-{
- Q_OBJECT
-public:
- QWidgetAnimator(QMainWindowLayout *layout);
- void animate(QWidget *widget, const QRect &final_geometry, bool animate);
- bool animating() const;
-
- void abort(QWidget *widget);
-
-#ifndef QT_NO_ANIMATION
-private Q_SLOTS:
- void animationFinished();
-#endif
-
-private:
- typedef QMap<QWidget*, QPropertyAnimation*> AnimationMap;
- AnimationMap m_animation_map;
- QMainWindowLayout *m_mainWindowLayout;
-};
-
-QT_END_NAMESPACE
-
-#endif // QWIDGET_ANIMATOR_P_H
diff --git a/src/gui/widgets/qwidgetresizehandler.cpp b/src/gui/widgets/qwidgetresizehandler.cpp
deleted file mode 100644
index 2d459ec1f0..0000000000
--- a/src/gui/widgets/qwidgetresizehandler.cpp
+++ /dev/null
@@ -1,547 +0,0 @@
-/****************************************************************************
-**
-** 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 "qwidgetresizehandler_p.h"
-
-#ifndef QT_NO_RESIZEHANDLER
-#include "qframe.h"
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qcursor.h"
-#include "qsizegrip.h"
-#include "qevent.h"
-#if defined(Q_WS_WIN)
-#include "qt_windows.h"
-#endif
-#include "qdebug.h"
-#include "private/qlayoutengine_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#define RANGE 4
-
-static bool resizeHorizontalDirectionFixed = false;
-static bool resizeVerticalDirectionFixed = false;
-
-QWidgetResizeHandler::QWidgetResizeHandler(QWidget *parent, QWidget *cw)
- : QObject(parent), widget(parent), childWidget(cw ? cw : parent),
- fw(0), extrahei(0), buttonDown(false), moveResizeMode(false), sizeprotect(true), movingEnabled(true)
-{
- mode = Nowhere;
- widget->setMouseTracking(true);
- QFrame *frame = qobject_cast<QFrame*>(widget);
- range = frame ? frame->frameWidth() : RANGE;
- range = qMax(RANGE, range);
- activeForMove = activeForResize = true;
- widget->installEventFilter(this);
-}
-
-void QWidgetResizeHandler::setActive(Action ac, bool b)
-{
- if (ac & Move)
- activeForMove = b;
- if (ac & Resize)
- activeForResize = b;
-
- if (!isActive())
- setMouseCursor(Nowhere);
-}
-
-bool QWidgetResizeHandler::isActive(Action ac) const
-{
- bool b = false;
- if (ac & Move) b = activeForMove;
- if (ac & Resize) b |= activeForResize;
-
- return b;
-}
-
-bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee)
-{
- if (!isActive()
- || (ee->type() != QEvent::MouseButtonPress
- && ee->type() != QEvent::MouseButtonRelease
- && ee->type() != QEvent::MouseMove
- && ee->type() != QEvent::KeyPress
- && ee->type() != QEvent::ShortcutOverride)
- )
- return false;
-
- Q_ASSERT(o == widget);
- QWidget *w = widget;
- if (QApplication::activePopupWidget()) {
- if (buttonDown && ee->type() == QEvent::MouseButtonRelease)
- buttonDown = false;
- return false;
- }
-
- QMouseEvent *e = (QMouseEvent*)ee;
- switch (e->type()) {
- case QEvent::MouseButtonPress: {
- if (w->isMaximized())
- break;
- if (!widget->rect().contains(widget->mapFromGlobal(e->globalPos())))
- return false;
- if (e->button() == Qt::LeftButton) {
-#if defined(Q_WS_X11)
- /*
- Implicit grabs do not stop the X server from changing
- the cursor in children, which looks *really* bad when
- doing resizingk, so we grab the cursor. Note that we do
- not do this on Windows since double clicks are lost due
- to the grab (see change 198463).
- */
- if (e->spontaneous())
-# if !defined(QT_NO_CURSOR)
- widget->grabMouse(widget->cursor());
-# else
- widget->grabMouse();
-# endif // QT_NO_CURSOR
-#endif // Q_WS_X11
- buttonDown = false;
- emit activate();
- bool me = movingEnabled;
- movingEnabled = (me && o == widget);
- mouseMoveEvent(e);
- movingEnabled = me;
- buttonDown = true;
- moveOffset = widget->mapFromGlobal(e->globalPos());
- invertedMoveOffset = widget->rect().bottomRight() - moveOffset;
- if (mode == Center) {
- if (movingEnabled)
- return true;
- } else {
- return true;
- }
- }
- } break;
- case QEvent::MouseButtonRelease:
- if (w->isMaximized())
- break;
- if (e->button() == Qt::LeftButton) {
- moveResizeMode = false;
- buttonDown = false;
- widget->releaseMouse();
- widget->releaseKeyboard();
- if (mode == Center) {
- if (movingEnabled)
- return true;
- } else {
- return true;
- }
- }
- break;
- case QEvent::MouseMove: {
- if (w->isMaximized())
- break;
- buttonDown = buttonDown && (e->buttons() & Qt::LeftButton); // safety, state machine broken!
- bool me = movingEnabled;
- movingEnabled = (me && o == widget && (buttonDown || moveResizeMode));
- mouseMoveEvent(e);
- movingEnabled = me;
- if (mode == Center) {
- if (movingEnabled)
- return true;
- } else {
- return true;
- }
- } break;
- case QEvent::KeyPress:
- keyPressEvent((QKeyEvent*)e);
- break;
- case QEvent::ShortcutOverride:
- if (buttonDown) {
- ((QKeyEvent*)ee)->accept();
- return true;
- }
- break;
- default:
- break;
- }
-
- return false;
-}
-
-void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e)
-{
- QPoint pos = widget->mapFromGlobal(e->globalPos());
- if (!moveResizeMode && !buttonDown) {
- if (pos.y() <= range && pos.x() <= range)
- mode = TopLeft;
- else if (pos.y() >= widget->height()-range && pos.x() >= widget->width()-range)
- mode = BottomRight;
- else if (pos.y() >= widget->height()-range && pos.x() <= range)
- mode = BottomLeft;
- else if (pos.y() <= range && pos.x() >= widget->width()-range)
- mode = TopRight;
- else if (pos.y() <= range)
- mode = Top;
- else if (pos.y() >= widget->height()-range)
- mode = Bottom;
- else if (pos.x() <= range)
- mode = Left;
- else if ( pos.x() >= widget->width()-range)
- mode = Right;
- else if (widget->rect().contains(pos))
- mode = Center;
- else
- mode = Nowhere;
-
- if (widget->isMinimized() || !isActive(Resize))
- mode = Center;
-#ifndef QT_NO_CURSOR
- setMouseCursor(mode);
-#endif
- return;
- }
-
- if (mode == Center && !movingEnabled)
- return;
-
- if (widget->testAttribute(Qt::WA_WState_ConfigPending))
- return;
-
-
- QPoint globalPos = (!widget->isWindow() && widget->parentWidget()) ?
- widget->parentWidget()->mapFromGlobal(e->globalPos()) : e->globalPos();
- if (!widget->isWindow() && !widget->parentWidget()->rect().contains(globalPos)) {
- if (globalPos.x() < 0)
- globalPos.rx() = 0;
- if (globalPos.y() < 0)
- globalPos.ry() = 0;
- if (sizeprotect && globalPos.x() > widget->parentWidget()->width())
- globalPos.rx() = widget->parentWidget()->width();
- if (sizeprotect && globalPos.y() > widget->parentWidget()->height())
- globalPos.ry() = widget->parentWidget()->height();
- }
-
- QPoint p = globalPos + invertedMoveOffset;
- QPoint pp = globalPos - moveOffset;
-
-#ifdef Q_WS_X11
- // Workaround for window managers which refuse to move a tool window partially offscreen.
- QRect desktop = QApplication::desktop()->availableGeometry(widget);
- pp.rx() = qMax(pp.x(), desktop.left());
- pp.ry() = qMax(pp.y(), desktop.top());
- p.rx() = qMin(p.x(), desktop.right());
- p.ry() = qMin(p.y(), desktop.bottom());
-#endif
-
- QSize ms = qSmartMinSize(childWidget);
- int mw = ms.width();
- int mh = ms.height();
- if (childWidget != widget) {
- mw += 2 * fw;
- mh += 2 * fw + extrahei;
- }
-
- QSize maxsize(childWidget->maximumSize());
- if (childWidget != widget)
- maxsize += QSize(2 * fw, 2 * fw + extrahei);
- QSize mpsize(widget->geometry().right() - pp.x() + 1,
- widget->geometry().bottom() - pp.y() + 1);
- mpsize = mpsize.expandedTo(widget->minimumSize()).expandedTo(QSize(mw, mh))
- .boundedTo(maxsize);
- QPoint mp(widget->geometry().right() - mpsize.width() + 1,
- widget->geometry().bottom() - mpsize.height() + 1);
-
- QRect geom = widget->geometry();
-
- switch (mode) {
- case TopLeft:
- geom = QRect(mp, widget->geometry().bottomRight()) ;
- break;
- case BottomRight:
- geom = QRect(widget->geometry().topLeft(), p) ;
- break;
- case BottomLeft:
- geom = QRect(QPoint(mp.x(), widget->geometry().y()), QPoint(widget->geometry().right(), p.y())) ;
- break;
- case TopRight:
- geom = QRect(QPoint(widget->geometry().x(), mp.y()), QPoint(p.x(), widget->geometry().bottom())) ;
- break;
- case Top:
- geom = QRect(QPoint(widget->geometry().left(), mp.y()), widget->geometry().bottomRight()) ;
- break;
- case Bottom:
- geom = QRect(widget->geometry().topLeft(), QPoint(widget->geometry().right(), p.y())) ;
- break;
- case Left:
- geom = QRect(QPoint(mp.x(), widget->geometry().top()), widget->geometry().bottomRight()) ;
- break;
- case Right:
- geom = QRect(widget->geometry().topLeft(), QPoint(p.x(), widget->geometry().bottom())) ;
- break;
- case Center:
- geom.moveTopLeft(pp);
- break;
- default:
- break;
- }
-
- geom = QRect(geom.topLeft(),
- geom.size().expandedTo(widget->minimumSize())
- .expandedTo(QSize(mw, mh))
- .boundedTo(maxsize));
-
- if (geom != widget->geometry() &&
- (widget->isWindow() || widget->parentWidget()->rect().intersects(geom))) {
- if (mode == Center)
- widget->move(geom.topLeft());
- else
- widget->setGeometry(geom);
- }
-
- QApplication::syncX();
-}
-
-void QWidgetResizeHandler::setMouseCursor(MousePosition m)
-{
-#ifdef QT_NO_CURSOR
- Q_UNUSED(m);
-#else
- QObjectList children = widget->children();
- for (int i = 0; i < children.size(); ++i) {
- if (QWidget *w = qobject_cast<QWidget*>(children.at(i))) {
- if (!w->testAttribute(Qt::WA_SetCursor) && !w->inherits("QWorkspaceTitleBar")) {
- w->setCursor(Qt::ArrowCursor);
- }
- }
- }
-
- switch (m) {
- case TopLeft:
- case BottomRight:
- widget->setCursor(Qt::SizeFDiagCursor);
- break;
- case BottomLeft:
- case TopRight:
- widget->setCursor(Qt::SizeBDiagCursor);
- break;
- case Top:
- case Bottom:
- widget->setCursor(Qt::SizeVerCursor);
- break;
- case Left:
- case Right:
- widget->setCursor(Qt::SizeHorCursor);
- break;
- default:
- widget->setCursor(Qt::ArrowCursor);
- break;
- }
-#endif // QT_NO_CURSOR
-}
-
-void QWidgetResizeHandler::keyPressEvent(QKeyEvent * e)
-{
- if (!isMove() && !isResize())
- return;
- bool is_control = e->modifiers() & Qt::ControlModifier;
- int delta = is_control?1:8;
- QPoint pos = QCursor::pos();
- switch (e->key()) {
- case Qt::Key_Left:
- pos.rx() -= delta;
- if (pos.x() <= QApplication::desktop()->geometry().left()) {
- if (mode == TopLeft || mode == BottomLeft) {
- moveOffset.rx() += delta;
- invertedMoveOffset.rx() += delta;
- } else {
- moveOffset.rx() -= delta;
- invertedMoveOffset.rx() -= delta;
- }
- }
- if (isResize() && !resizeHorizontalDirectionFixed) {
- resizeHorizontalDirectionFixed = true;
- if (mode == BottomRight)
- mode = BottomLeft;
- else if (mode == TopRight)
- mode = TopLeft;
-#ifndef QT_NO_CURSOR
- setMouseCursor(mode);
- widget->grabMouse(widget->cursor());
-#else
- widget->grabMouse();
-#endif
- }
- break;
- case Qt::Key_Right:
- pos.rx() += delta;
- if (pos.x() >= QApplication::desktop()->geometry().right()) {
- if (mode == TopRight || mode == BottomRight) {
- moveOffset.rx() += delta;
- invertedMoveOffset.rx() += delta;
- } else {
- moveOffset.rx() -= delta;
- invertedMoveOffset.rx() -= delta;
- }
- }
- if (isResize() && !resizeHorizontalDirectionFixed) {
- resizeHorizontalDirectionFixed = true;
- if (mode == BottomLeft)
- mode = BottomRight;
- else if (mode == TopLeft)
- mode = TopRight;
-#ifndef QT_NO_CURSOR
- setMouseCursor(mode);
- widget->grabMouse(widget->cursor());
-#else
- widget->grabMouse();
-#endif
- }
- break;
- case Qt::Key_Up:
- pos.ry() -= delta;
- if (pos.y() <= QApplication::desktop()->geometry().top()) {
- if (mode == TopLeft || mode == TopRight) {
- moveOffset.ry() += delta;
- invertedMoveOffset.ry() += delta;
- } else {
- moveOffset.ry() -= delta;
- invertedMoveOffset.ry() -= delta;
- }
- }
- if (isResize() && !resizeVerticalDirectionFixed) {
- resizeVerticalDirectionFixed = true;
- if (mode == BottomLeft)
- mode = TopLeft;
- else if (mode == BottomRight)
- mode = TopRight;
-#ifndef QT_NO_CURSOR
- setMouseCursor(mode);
- widget->grabMouse(widget->cursor());
-#else
- widget->grabMouse();
-#endif
- }
- break;
- case Qt::Key_Down:
- pos.ry() += delta;
- if (pos.y() >= QApplication::desktop()->geometry().bottom()) {
- if (mode == BottomLeft || mode == BottomRight) {
- moveOffset.ry() += delta;
- invertedMoveOffset.ry() += delta;
- } else {
- moveOffset.ry() -= delta;
- invertedMoveOffset.ry() -= delta;
- }
- }
- if (isResize() && !resizeVerticalDirectionFixed) {
- resizeVerticalDirectionFixed = true;
- if (mode == TopLeft)
- mode = BottomLeft;
- else if (mode == TopRight)
- mode = BottomRight;
-#ifndef QT_NO_CURSOR
- setMouseCursor(mode);
- widget->grabMouse(widget->cursor());
-#else
- widget->grabMouse();
-#endif
- }
- break;
- case Qt::Key_Space:
- case Qt::Key_Return:
- case Qt::Key_Enter:
- case Qt::Key_Escape:
- moveResizeMode = false;
- widget->releaseMouse();
- widget->releaseKeyboard();
- buttonDown = false;
- break;
- default:
- return;
- }
- QCursor::setPos(pos);
-}
-
-
-void QWidgetResizeHandler::doResize()
-{
- if (!activeForResize)
- return;
-
- moveResizeMode = true;
- moveOffset = widget->mapFromGlobal(QCursor::pos());
- if (moveOffset.x() < widget->width()/2) {
- if (moveOffset.y() < widget->height()/2)
- mode = TopLeft;
- else
- mode = BottomLeft;
- } else {
- if (moveOffset.y() < widget->height()/2)
- mode = TopRight;
- else
- mode = BottomRight;
- }
- invertedMoveOffset = widget->rect().bottomRight() - moveOffset;
-#ifndef QT_NO_CURSOR
- setMouseCursor(mode);
- widget->grabMouse(widget->cursor() );
-#else
- widget->grabMouse();
-#endif
- widget->grabKeyboard();
- resizeHorizontalDirectionFixed = false;
- resizeVerticalDirectionFixed = false;
-}
-
-void QWidgetResizeHandler::doMove()
-{
- if (!activeForMove)
- return;
-
- mode = Center;
- moveResizeMode = true;
- moveOffset = widget->mapFromGlobal(QCursor::pos());
- invertedMoveOffset = widget->rect().bottomRight() - moveOffset;
-#ifndef QT_NO_CURSOR
- widget->grabMouse(Qt::SizeAllCursor);
-#else
- widget->grabMouse();
-#endif
- widget->grabKeyboard();
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_RESIZEHANDLER
diff --git a/src/gui/widgets/qwidgetresizehandler_p.h b/src/gui/widgets/qwidgetresizehandler_p.h
deleted file mode 100644
index 25ac361a4d..0000000000
--- a/src/gui/widgets/qwidgetresizehandler_p.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** 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 QWIDGETRESIZEHANDLER_P_H
-#define QWIDGETRESIZEHANDLER_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. This header file may
-// change from version to version without notice, or even be
-// removed.
-//
-// We mean it.
-//
-
-#include "QtCore/qobject.h"
-#include "QtCore/qpoint.h"
-
-#ifndef QT_NO_RESIZEHANDLER
-
-QT_BEGIN_NAMESPACE
-
-class QMouseEvent;
-class QKeyEvent;
-
-class Q_GUI_EXPORT QWidgetResizeHandler : public QObject
-{
- Q_OBJECT
-
-public:
- enum Action {
- Move = 0x01,
- Resize = 0x02,
- Any = Move|Resize
- };
-
- explicit QWidgetResizeHandler(QWidget *parent, QWidget *cw = 0);
- void setActive(bool b) { setActive(Any, b); }
- void setActive(Action ac, bool b);
- bool isActive() const { return isActive(Any); }
- bool isActive(Action ac) const;
- void setMovingEnabled(bool b) { movingEnabled = b; }
- bool isMovingEnabled() const { return movingEnabled; }
-
- bool isButtonDown() const { return buttonDown; }
-
- void setExtraHeight(int h) { extrahei = h; }
- void setSizeProtection(bool b) { sizeprotect = b; }
-
- void setFrameWidth(int w) { fw = w; }
-
- void doResize();
- void doMove();
-
-Q_SIGNALS:
- void activate();
-
-protected:
- bool eventFilter(QObject *o, QEvent *e);
- void mouseMoveEvent(QMouseEvent *e);
- void keyPressEvent(QKeyEvent *e);
-
-private:
- Q_DISABLE_COPY(QWidgetResizeHandler)
-
- enum MousePosition {
- Nowhere,
- TopLeft, BottomRight, BottomLeft, TopRight,
- Top, Bottom, Left, Right,
- Center
- };
-
- QWidget *widget;
- QWidget *childWidget;
- QPoint moveOffset;
- QPoint invertedMoveOffset;
- MousePosition mode;
- int fw;
- int extrahei;
- int range;
- uint buttonDown :1;
- uint moveResizeMode :1;
- uint activeForResize :1;
- uint sizeprotect :1;
- uint movingEnabled :1;
- uint activeForMove :1;
-
- void setMouseCursor(MousePosition m);
- bool isMove() const {
- return moveResizeMode && mode == Center;
- }
- bool isResize() const {
- return moveResizeMode && !isMove();
- }
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_RESIZEHANDLER
-
-#endif // QWIDGETRESIZEHANDLER_P_H
diff --git a/src/gui/widgets/qworkspace.cpp b/src/gui/widgets/qworkspace.cpp
deleted file mode 100644
index bf50d07947..0000000000
--- a/src/gui/widgets/qworkspace.cpp
+++ /dev/null
@@ -1,3377 +0,0 @@
-/****************************************************************************
-**
-** 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 "qworkspace.h"
-#ifndef QT_NO_WORKSPACE
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qhash.h"
-#include "qicon.h"
-#include "qimage.h"
-#include "qlabel.h"
-#include "qlayout.h"
-#include "qmenubar.h"
-#include "qmenu.h"
-#include "qpainter.h"
-#include "qpointer.h"
-#include "qscrollbar.h"
-#include "qstyle.h"
-#include "qstyleoption.h"
-#include "qelapsedtimer.h"
-#include "qtooltip.h"
-#include "qdebug.h"
-#include <private/qwidget_p.h>
-#include <private/qwidgetresizehandler_p.h>
-#include <private/qlayoutengine_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QWorkspaceTitleBarPrivate;
-
-
-/**************************************************************
-* QMDIControl
-*
-* Used for displaying MDI controls in a maximized MDI window
-*
-*/
-class QMDIControl : public QWidget
-{
- Q_OBJECT
-signals:
- void _q_minimize();
- void _q_restore();
- void _q_close();
-
-public:
- QMDIControl(QWidget *widget);
-
-private:
- QSize sizeHint() const;
- void paintEvent(QPaintEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void leaveEvent(QEvent *event);
- bool event(QEvent *event);
- void initStyleOption(QStyleOptionComplex *option) const;
- QStyle::SubControl activeControl; //control locked by pressing and holding the mouse
- QStyle::SubControl hoverControl; //previously active hover control, used for tracking repaints
-};
-
-bool QMDIControl::event(QEvent *event)
-{
- if (event->type() == QEvent::ToolTip) {
- QStyleOptionComplex opt;
- initStyleOption(&opt);
-#ifndef QT_NO_TOOLTIP
- QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
- QStyle::SubControl ctrl = style()->hitTestComplexControl(QStyle::CC_MdiControls, &opt,
- helpEvent->pos(), this);
- if (ctrl == QStyle::SC_MdiCloseButton)
- QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Close"), this);
- else if (ctrl == QStyle::SC_MdiMinButton)
- QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Minimize"), this);
- else if (ctrl == QStyle::SC_MdiNormalButton)
- QToolTip::showText(helpEvent->globalPos(), QWorkspace::tr("Restore Down"), this);
- else
- QToolTip::hideText();
-#endif // QT_NO_TOOLTIP
- }
- return QWidget::event(event);
-}
-
-void QMDIControl::initStyleOption(QStyleOptionComplex *option) const
-{
- option->initFrom(this);
- option->subControls = QStyle::SC_All;
- option->activeSubControls = QStyle::SC_None;
-}
-
-QMDIControl::QMDIControl(QWidget *widget)
- : QWidget(widget), activeControl(QStyle::SC_None),
- hoverControl(QStyle::SC_None)
-{
- setObjectName(QLatin1String("qt_maxcontrols"));
- setFocusPolicy(Qt::NoFocus);
- setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
- setMouseTracking(true);
-}
-
-QSize QMDIControl::sizeHint() const
-{
- ensurePolished();
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- QSize size(48, 16);
- return style()->sizeFromContents(QStyle::CT_MdiControls, &opt, size, this);
-}
-
-void QMDIControl::mousePressEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- QStyle::SubControl ctrl = style()->hitTestComplexControl(QStyle::CC_MdiControls, &opt,
- event->pos(), this);
- activeControl = ctrl;
- update();
-}
-
-void QMDIControl::mouseReleaseEvent(QMouseEvent *event)
-{
- if (event->button() != Qt::LeftButton) {
- event->ignore();
- return;
- }
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QStyle::SubControl under_mouse = style()->hitTestComplexControl(QStyle::CC_MdiControls, &opt,
- event->pos(), this);
- if (under_mouse == activeControl) {
- switch (activeControl) {
- case QStyle::SC_MdiCloseButton:
- emit _q_close();
- break;
- case QStyle::SC_MdiNormalButton:
- emit _q_restore();
- break;
- case QStyle::SC_MdiMinButton:
- emit _q_minimize();
- break;
- default:
- break;
- }
- }
- activeControl = QStyle::SC_None;
- update();
-}
-
-void QMDIControl::leaveEvent(QEvent * /*event*/)
-{
- hoverControl = QStyle::SC_None;
- update();
-}
-
-void QMDIControl::mouseMoveEvent(QMouseEvent *event)
-{
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QStyle::SubControl under_mouse = style()->hitTestComplexControl(QStyle::CC_MdiControls, &opt,
- event->pos(), this);
- //test if hover state changes
- if (hoverControl != under_mouse) {
- hoverControl = under_mouse;
- update();
- }
-}
-
-void QMDIControl::paintEvent(QPaintEvent *)
-{
- QPainter p(this);
- QStyleOptionComplex opt;
- initStyleOption(&opt);
- if (activeControl == hoverControl) {
- opt.activeSubControls = activeControl;
- opt.state |= QStyle::State_Sunken;
- } else if (hoverControl != QStyle::SC_None && (activeControl == QStyle::SC_None)) {
- opt.activeSubControls = hoverControl;
- opt.state |= QStyle::State_MouseOver;
- }
- style()->drawComplexControl(QStyle::CC_MdiControls, &opt, &p, this);
-}
-
-class QWorkspaceTitleBar : public QWidget
-{
- Q_OBJECT
- Q_DECLARE_PRIVATE(QWorkspaceTitleBar)
- Q_PROPERTY(bool autoRaise READ autoRaise WRITE setAutoRaise)
- Q_PROPERTY(bool movable READ isMovable WRITE setMovable)
-
-public:
- QWorkspaceTitleBar (QWidget *w, QWidget *parent, Qt::WindowFlags f = 0);
- ~QWorkspaceTitleBar();
-
- bool isActive() const;
- bool usesActiveColor() const;
-
- bool isMovable() const;
- void setMovable(bool);
-
- bool autoRaise() const;
- void setAutoRaise(bool);
-
- QWidget *window() const;
- bool isTool() const;
-
- QSize sizeHint() const;
- void initStyleOption(QStyleOptionTitleBar *option) const;
-
-public slots:
- void setActive(bool);
-
-signals:
- void doActivate();
- void doNormal();
- void doClose();
- void doMaximize();
- void doMinimize();
- void doShade();
- void showOperationMenu();
- void popupOperationMenu(const QPoint&);
- void doubleClicked();
-
-protected:
- bool event(QEvent *);
-#ifndef QT_NO_CONTEXTMENU
- void contextMenuEvent(QContextMenuEvent *);
-#endif
- void mousePressEvent(QMouseEvent *);
- void mouseDoubleClickEvent(QMouseEvent *);
- void mouseReleaseEvent(QMouseEvent *);
- void mouseMoveEvent(QMouseEvent *);
- void enterEvent(QEvent *e);
- void leaveEvent(QEvent *e);
- void paintEvent(QPaintEvent *p);
-
-private:
- Q_DISABLE_COPY(QWorkspaceTitleBar)
-};
-
-
-class QWorkspaceTitleBarPrivate : public QWidgetPrivate
-{
- Q_DECLARE_PUBLIC(QWorkspaceTitleBar)
-public:
- QWorkspaceTitleBarPrivate()
- :
- lastControl(QStyle::SC_None),
-#ifndef QT_NO_TOOLTIP
- toolTip(0),
-#endif
- act(0), window(0), movable(1), pressed(0), autoraise(0), moving(0)
- {
- }
-
- Qt::WindowFlags flags;
- QStyle::SubControl buttonDown;
- QStyle::SubControl lastControl;
- QPoint moveOffset;
-#ifndef QT_NO_TOOLTIP
- QToolTip *toolTip;
-#endif
- bool act :1;
- QPointer<QWidget> window;
- bool movable :1;
- bool pressed :1;
- bool autoraise :1;
- bool moving : 1;
-
- int titleBarState() const;
- void readColors();
-};
-
-inline int QWorkspaceTitleBarPrivate::titleBarState() const
-{
- Q_Q(const QWorkspaceTitleBar);
- uint state = window ? window->windowState() : static_cast<Qt::WindowStates>(Qt::WindowNoState);
- state |= uint((act && q->isActiveWindow()) ? QStyle::State_Active : QStyle::State_None);
- return (int)state;
-}
-
-void QWorkspaceTitleBar::initStyleOption(QStyleOptionTitleBar *option) const
-{
- Q_D(const QWorkspaceTitleBar);
- option->initFrom(this);
- //################
- if (d->window && (d->flags & Qt::WindowTitleHint)) {
- option->text = d->window->windowTitle();
- QIcon icon = d->window->windowIcon();
- QSize s = icon.actualSize(QSize(64, 64));
- option->icon = icon.pixmap(s);
- }
- option->subControls = QStyle::SC_All;
- option->activeSubControls = QStyle::SC_None;
- option->titleBarState = d->titleBarState();
- option->titleBarFlags = d->flags;
- option->state &= ~QStyle::State_MouseOver;
-}
-
-QWorkspaceTitleBar::QWorkspaceTitleBar(QWidget *w, QWidget *parent, Qt::WindowFlags f)
- : QWidget(*new QWorkspaceTitleBarPrivate, parent, Qt::FramelessWindowHint)
-{
- Q_D(QWorkspaceTitleBar);
- if (f == 0 && w)
- f = w->windowFlags();
- d->flags = f;
- d->window = w;
- d->buttonDown = QStyle::SC_None;
- d->act = 0;
- if (w) {
- if (w->maximumSize() != QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX))
- d->flags &= ~Qt::WindowMaximizeButtonHint;
- setWindowTitle(w->windowTitle());
- }
-
- d->readColors();
- setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
- setMouseTracking(true);
- setAutoRaise(style()->styleHint(QStyle::SH_TitleBar_AutoRaise, 0, this));
-}
-
-QWorkspaceTitleBar::~QWorkspaceTitleBar()
-{
-}
-
-
-#ifdef Q_WS_WIN
-static inline QRgb colorref2qrgb(COLORREF col)
-{
- return qRgb(GetRValue(col),GetGValue(col),GetBValue(col));
-}
-#endif
-
-void QWorkspaceTitleBarPrivate::readColors()
-{
- Q_Q(QWorkspaceTitleBar);
- QPalette pal = q->palette();
-
- bool colorsInitialized = false;
-
-#ifdef Q_WS_WIN // ask system properties on windows
-#ifndef SPI_GETGRADIENTCAPTIONS
-#define SPI_GETGRADIENTCAPTIONS 0x1008
-#endif
-#ifndef COLOR_GRADIENTACTIVECAPTION
-#define COLOR_GRADIENTACTIVECAPTION 27
-#endif
-#ifndef COLOR_GRADIENTINACTIVECAPTION
-#define COLOR_GRADIENTINACTIVECAPTION 28
-#endif
- if (QApplication::desktopSettingsAware()) {
- pal.setColor(QPalette::Active, QPalette::Highlight, colorref2qrgb(GetSysColor(COLOR_ACTIVECAPTION)));
- pal.setColor(QPalette::Inactive, QPalette::Highlight, colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTION)));
- pal.setColor(QPalette::Active, QPalette::HighlightedText, colorref2qrgb(GetSysColor(COLOR_CAPTIONTEXT)));
- pal.setColor(QPalette::Inactive, QPalette::HighlightedText, colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTIONTEXT)));
-
- colorsInitialized = true;
- BOOL gradient = false;
- SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &gradient, 0);
-
- if (gradient) {
- pal.setColor(QPalette::Active, QPalette::Base, colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION)));
- pal.setColor(QPalette::Inactive, QPalette::Base, colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION)));
- } else {
- pal.setColor(QPalette::Active, QPalette::Base, pal.color(QPalette::Active, QPalette::Highlight));
- pal.setColor(QPalette::Inactive, QPalette::Base, pal.color(QPalette::Inactive, QPalette::Highlight));
- }
- }
-#endif // Q_WS_WIN
- if (!colorsInitialized) {
- pal.setColor(QPalette::Active, QPalette::Highlight,
- pal.color(QPalette::Active, QPalette::Highlight));
- pal.setColor(QPalette::Active, QPalette::Base,
- pal.color(QPalette::Active, QPalette::Highlight));
- pal.setColor(QPalette::Inactive, QPalette::Highlight,
- pal.color(QPalette::Inactive, QPalette::Dark));
- pal.setColor(QPalette::Inactive, QPalette::Base,
- pal.color(QPalette::Inactive, QPalette::Dark));
- pal.setColor(QPalette::Inactive, QPalette::HighlightedText,
- pal.color(QPalette::Inactive, QPalette::Window));
- }
-
- q->setPalette(pal);
- q->setActive(act);
-}
-
-void QWorkspaceTitleBar::mousePressEvent(QMouseEvent *e)
-{
- Q_D(QWorkspaceTitleBar);
- if (!d->act)
- emit doActivate();
- if (e->button() == Qt::LeftButton) {
- if (style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, 0)
- && !rect().adjusted(5, 5, -5, 0).contains(e->pos())) {
- // propagate border events to the QWidgetResizeHandler
- e->ignore();
- return;
- }
-
- d->pressed = true;
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QStyle::SubControl ctrl = style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt,
- e->pos(), this);
- switch (ctrl) {
- case QStyle::SC_TitleBarSysMenu:
- if (d->flags & Qt::WindowSystemMenuHint) {
- d->buttonDown = QStyle::SC_None;
- static QElapsedTimer *t = 0;
- static QWorkspaceTitleBar *tc = 0;
- if (!t)
- t = new QElapsedTimer;
- if (tc != this || t->elapsed() > QApplication::doubleClickInterval()) {
- emit showOperationMenu();
- t->start();
- tc = this;
- } else {
- tc = 0;
- emit doClose();
- return;
- }
- }
- break;
-
- case QStyle::SC_TitleBarShadeButton:
- case QStyle::SC_TitleBarUnshadeButton:
- if (d->flags & Qt::WindowShadeButtonHint)
- d->buttonDown = ctrl;
- break;
-
- case QStyle::SC_TitleBarNormalButton:
- d->buttonDown = ctrl;
- break;
-
- case QStyle::SC_TitleBarMinButton:
- if (d->flags & Qt::WindowMinimizeButtonHint)
- d->buttonDown = ctrl;
- break;
-
- case QStyle::SC_TitleBarMaxButton:
- if (d->flags & Qt::WindowMaximizeButtonHint)
- d->buttonDown = ctrl;
- break;
-
- case QStyle::SC_TitleBarCloseButton:
- if (d->flags & Qt::WindowSystemMenuHint)
- d->buttonDown = ctrl;
- break;
-
- case QStyle::SC_TitleBarLabel:
- d->buttonDown = ctrl;
- d->moveOffset = mapToParent(e->pos());
- break;
-
- default:
- break;
- }
- update();
- } else {
- d->pressed = false;
- }
-}
-
-#ifndef QT_NO_CONTEXTMENU
-void QWorkspaceTitleBar::contextMenuEvent(QContextMenuEvent *e)
-{
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QStyle::SubControl ctrl = style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt, e->pos(),
- this);
- if(ctrl == QStyle::SC_TitleBarLabel || ctrl == QStyle::SC_TitleBarSysMenu) {
- e->accept();
- emit popupOperationMenu(e->globalPos());
- } else {
- e->ignore();
- }
-}
-#endif // QT_NO_CONTEXTMENU
-
-void QWorkspaceTitleBar::mouseReleaseEvent(QMouseEvent *e)
-{
- Q_D(QWorkspaceTitleBar);
- if (!d->window) {
- // could have been deleted as part of a double click event on the sysmenu
- return;
- }
- if (e->button() == Qt::LeftButton && d->pressed) {
- if (style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, 0)
- && !rect().adjusted(5, 5, -5, 0).contains(e->pos())) {
- // propagate border events to the QWidgetResizeHandler
- e->ignore();
- d->buttonDown = QStyle::SC_None;
- d->pressed = false;
- return;
- }
- e->accept();
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QStyle::SubControl ctrl = style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt,
- e->pos(), this);
-
- if (d->pressed) {
- update();
- d->pressed = false;
- d->moving = false;
- }
- if (ctrl == d->buttonDown) {
- d->buttonDown = QStyle::SC_None;
- switch(ctrl) {
- case QStyle::SC_TitleBarShadeButton:
- case QStyle::SC_TitleBarUnshadeButton:
- if(d->flags & Qt::WindowShadeButtonHint)
- emit doShade();
- break;
-
- case QStyle::SC_TitleBarNormalButton:
- if(d->flags & Qt::WindowMinMaxButtonsHint)
- emit doNormal();
- break;
-
- case QStyle::SC_TitleBarMinButton:
- if(d->flags & Qt::WindowMinimizeButtonHint) {
- if (d->window && d->window->isMinimized())
- emit doNormal();
- else
- emit doMinimize();
- }
- break;
-
- case QStyle::SC_TitleBarMaxButton:
- if(d->flags & Qt::WindowMaximizeButtonHint) {
- if(d->window && d->window->isMaximized())
- emit doNormal();
- else
- emit doMaximize();
- }
- break;
-
- case QStyle::SC_TitleBarCloseButton:
- if(d->flags & Qt::WindowSystemMenuHint) {
- d->buttonDown = QStyle::SC_None;
- emit doClose();
- return;
- }
- break;
-
- default:
- break;
- }
- }
- } else {
- e->ignore();
- }
-}
-
-void QWorkspaceTitleBar::mouseMoveEvent(QMouseEvent *e)
-{
- Q_D(QWorkspaceTitleBar);
- e->ignore();
- if ((e->buttons() & Qt::LeftButton) && style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, 0)
- && !rect().adjusted(5, 5, -5, 0).contains(e->pos()) && !d->pressed) {
- // propagate border events to the QWidgetResizeHandler
- return;
- }
-
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QStyle::SubControl under_mouse = style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt,
- e->pos(), this);
- if(under_mouse != d->lastControl) {
- d->lastControl = under_mouse;
- update();
- }
-
- switch (d->buttonDown) {
- case QStyle::SC_None:
- break;
- case QStyle::SC_TitleBarSysMenu:
- break;
- case QStyle::SC_TitleBarLabel:
- if (d->buttonDown == QStyle::SC_TitleBarLabel && d->movable && d->pressed) {
- if (d->moving || (d->moveOffset - mapToParent(e->pos())).manhattanLength() >= 4) {
- d->moving = true;
- QPoint p = mapFromGlobal(e->globalPos());
-
- QWidget *parent = d->window ? d->window->parentWidget() : 0;
- if(parent && parent->inherits("QWorkspaceChild")) {
- QWidget *workspace = parent->parentWidget();
- p = workspace->mapFromGlobal(e->globalPos());
- if (!workspace->rect().contains(p)) {
- if (p.x() < 0)
- p.rx() = 0;
- if (p.y() < 0)
- p.ry() = 0;
- if (p.x() > workspace->width())
- p.rx() = workspace->width();
- if (p.y() > workspace->height())
- p.ry() = workspace->height();
- }
- }
-
- QPoint pp = p - d->moveOffset;
- if (!parentWidget()->isMaximized())
- parentWidget()->move(pp);
- }
- }
- e->accept();
- break;
- default:
- break;
- }
-}
-
-bool QWorkspaceTitleBar::isTool() const
-{
- Q_D(const QWorkspaceTitleBar);
- return (d->flags & Qt::WindowType_Mask) == Qt::Tool;
-}
-
-// from qwidget.cpp
-extern QString qt_setWindowTitle_helperHelper(const QString &, const QWidget*);
-
-void QWorkspaceTitleBar::paintEvent(QPaintEvent *)
-{
- Q_D(QWorkspaceTitleBar);
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- opt.subControls = QStyle::SC_TitleBarLabel;
- opt.activeSubControls = d->buttonDown;
-
- if (d->window && (d->flags & Qt::WindowTitleHint)) {
- QString title = qt_setWindowTitle_helperHelper(opt.text, d->window);
- int maxw = style()->subControlRect(QStyle::CC_TitleBar, &opt, QStyle::SC_TitleBarLabel,
- this).width();
- opt.text = fontMetrics().elidedText(title, Qt::ElideRight, maxw);
- }
-
- if (d->flags & Qt::WindowSystemMenuHint) {
- opt.subControls |= QStyle::SC_TitleBarSysMenu | QStyle::SC_TitleBarCloseButton;
- if (d->window && (d->flags & Qt::WindowShadeButtonHint)) {
- if (d->window->isMinimized())
- opt.subControls |= QStyle::SC_TitleBarUnshadeButton;
- else
- opt.subControls |= QStyle::SC_TitleBarShadeButton;
- }
- if (d->window && (d->flags & Qt::WindowMinMaxButtonsHint)) {
- if(d->window && d->window->isMinimized())
- opt.subControls |= QStyle::SC_TitleBarNormalButton;
- else
- opt.subControls |= QStyle::SC_TitleBarMinButton;
- }
- if (d->window && (d->flags & Qt::WindowMaximizeButtonHint) && !d->window->isMaximized())
- opt.subControls |= QStyle::SC_TitleBarMaxButton;
- }
-
- QStyle::SubControl under_mouse = QStyle::SC_None;
- under_mouse = style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt,
- mapFromGlobal(QCursor::pos()), this);
- if ((d->buttonDown == under_mouse) && d->pressed) {
- opt.state |= QStyle::State_Sunken;
- } else if( autoRaise() && under_mouse != QStyle::SC_None && !d->pressed) {
- opt.activeSubControls = under_mouse;
- opt.state |= QStyle::State_MouseOver;
- }
- opt.palette.setCurrentColorGroup(usesActiveColor() ? QPalette::Active : QPalette::Inactive);
-
- QPainter p(this);
- style()->drawComplexControl(QStyle::CC_TitleBar, &opt, &p, this);
-}
-
-void QWorkspaceTitleBar::mouseDoubleClickEvent(QMouseEvent *e)
-{
- Q_D(QWorkspaceTitleBar);
- if (e->button() != Qt::LeftButton) {
- e->ignore();
- return;
- }
- e->accept();
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- switch (style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt, e->pos(), this)) {
- case QStyle::SC_TitleBarLabel:
- emit doubleClicked();
- break;
-
- case QStyle::SC_TitleBarSysMenu:
- if (d->flags & Qt::WindowSystemMenuHint)
- emit doClose();
- break;
-
- default:
- break;
- }
-}
-
-void QWorkspaceTitleBar::leaveEvent(QEvent *)
-{
- Q_D(QWorkspaceTitleBar);
- d->lastControl = QStyle::SC_None;
- if(autoRaise() && !d->pressed)
- update();
-}
-
-void QWorkspaceTitleBar::enterEvent(QEvent *)
-{
- Q_D(QWorkspaceTitleBar);
- if(autoRaise() && !d->pressed)
- update();
- QEvent e(QEvent::Leave);
- QApplication::sendEvent(parentWidget(), &e);
-}
-
-void QWorkspaceTitleBar::setActive(bool active)
-{
- Q_D(QWorkspaceTitleBar);
- if (d->act == active)
- return ;
-
- d->act = active;
- update();
-}
-
-bool QWorkspaceTitleBar::isActive() const
-{
- Q_D(const QWorkspaceTitleBar);
- return d->act;
-}
-
-bool QWorkspaceTitleBar::usesActiveColor() const
-{
- return (isActive() && isActiveWindow()) ||
- (!window() && QWidget::window()->isActiveWindow());
-}
-
-QWidget *QWorkspaceTitleBar::window() const
-{
- Q_D(const QWorkspaceTitleBar);
- return d->window;
-}
-
-bool QWorkspaceTitleBar::event(QEvent *e)
-{
- Q_D(QWorkspaceTitleBar);
- if (e->type() == QEvent::ApplicationPaletteChange) {
- d->readColors();
- } else if (e->type() == QEvent::WindowActivate
- || e->type() == QEvent::WindowDeactivate) {
- if (d->act)
- update();
- }
- return QWidget::event(e);
-}
-
-void QWorkspaceTitleBar::setMovable(bool b)
-{
- Q_D(QWorkspaceTitleBar);
- d->movable = b;
-}
-
-bool QWorkspaceTitleBar::isMovable() const
-{
- Q_D(const QWorkspaceTitleBar);
- return d->movable;
-}
-
-void QWorkspaceTitleBar::setAutoRaise(bool b)
-{
- Q_D(QWorkspaceTitleBar);
- d->autoraise = b;
-}
-
-bool QWorkspaceTitleBar::autoRaise() const
-{
- Q_D(const QWorkspaceTitleBar);
- return d->autoraise;
-}
-
-QSize QWorkspaceTitleBar::sizeHint() const
-{
- ensurePolished();
- QStyleOptionTitleBar opt;
- initStyleOption(&opt);
- QRect menur = style()->subControlRect(QStyle::CC_TitleBar, &opt,
- QStyle::SC_TitleBarSysMenu, this);
- return QSize(menur.width(), style()->pixelMetric(QStyle::PM_TitleBarHeight, &opt, this));
-}
-
-/*!
- \class QWorkspace
- \obsolete
- \brief The QWorkspace widget provides a workspace window that can be
- used in an MDI application.
-
- This class is deprecated. Use QMdiArea instead.
-
- Multiple Document Interface (MDI) applications are typically
- composed of a main window containing a menu bar, a toolbar, and
- a central QWorkspace widget. The workspace itself is used to display
- a number of child windows, each of which is a widget.
-
- The workspace itself is an ordinary Qt widget. It has a standard
- constructor that takes a parent widget.
- Workspaces can be placed in any layout, but are typically given
- as the central widget in a QMainWindow:
-
- \snippet doc/src/snippets/code/src_gui_widgets_qworkspace.cpp 0
-
- Child windows (MDI windows) are standard Qt widgets that are
- inserted into the workspace with addWindow(). As with top-level
- widgets, you can call functions such as show(), hide(),
- showMaximized(), and setWindowTitle() on a child window to change
- its appearance within the workspace. You can also provide widget
- flags to determine the layout of the decoration or the behavior of
- the widget itself.
-
- To change or retrieve the geometry of a child window, you must
- operate on its parentWidget(). The parentWidget() provides
- access to the decorated frame that contains the child window
- widget. When a child window is maximised, its decorated frame
- is hidden. If the top-level widget contains a menu bar, it will display
- the maximised window's operations menu to the left of the menu
- entries, and the window's controls to the right.
-
- A child window becomes active when it gets the keyboard focus,
- or when setFocus() is called. The user can activate a window by moving
- focus in the usual ways, for example by clicking a window or by pressing
- Tab. The workspace emits a signal windowActivated() when the active
- window changes, and the function activeWindow() returns a pointer to the
- active child window, or 0 if no window is active.
-
- The convenience function windowList() returns a list of all child
- windows. This information could be used in a popup menu
- containing a list of windows, for example. This feature is also
- available as part of the \l{Window Menu} Solution.
-
- QWorkspace provides two built-in layout strategies for child
- windows: cascade() and tile(). Both are slots so you can easily
- connect menu entries to them.
-
- \table
- \row \o \inlineimage mdi-cascade.png
- \o \inlineimage mdi-tile.png
- \endtable
-
- If you want your users to be able to work with child windows
- larger than the visible workspace area, set the scrollBarsEnabled
- property to true.
-
- \sa QDockWidget, {MDI Example}
-*/
-
-
-class QWorkspaceChild : public QWidget
-{
- Q_OBJECT
-
- friend class QWorkspacePrivate;
- friend class QWorkspace;
- friend class QWorkspaceTitleBar;
-
-public:
- QWorkspaceChild(QWidget* window, QWorkspace* parent=0, Qt::WindowFlags flags = 0);
- ~QWorkspaceChild();
-
- void setActive(bool);
- bool isActive() const;
-
- void adjustToFullscreen();
-
- QWidget* windowWidget() const;
- QWidget* iconWidget() const;
-
- void doResize();
- void doMove();
-
- QSize sizeHint() const;
- QSize minimumSizeHint() const;
-
- QSize baseSize() const;
-
- int frameWidth() const;
-
- void show();
-
- bool isWindowOrIconVisible() const;
-
-signals:
- void showOperationMenu();
- void popupOperationMenu(const QPoint&);
-
-public slots:
- void activate();
- void showMinimized();
- void showMaximized();
- void showNormal();
- void showShaded();
- void internalRaise();
- void titleBarDoubleClicked();
-
-protected:
- void enterEvent(QEvent *);
- void leaveEvent(QEvent *);
- void childEvent(QChildEvent*);
- void resizeEvent(QResizeEvent *);
- void moveEvent(QMoveEvent *);
- bool eventFilter(QObject *, QEvent *);
-
- void paintEvent(QPaintEvent *);
- void changeEvent(QEvent *);
-
-private:
- void updateMask();
-
- Q_DISABLE_COPY(QWorkspaceChild)
-
- QWidget *childWidget;
- QWidgetResizeHandler *widgetResizeHandler;
- QWorkspaceTitleBar *titlebar;
- QPointer<QWorkspaceTitleBar> iconw;
- QSize windowSize;
- QSize shadeRestore;
- QSize shadeRestoreMin;
- bool act :1;
- bool shademode :1;
-};
-
-int QWorkspaceChild::frameWidth() const
-{
- return contentsRect().left();
-}
-
-
-
-class QWorkspacePrivate : public QWidgetPrivate {
- Q_DECLARE_PUBLIC(QWorkspace)
-public:
- QWorkspaceChild* active;
- QList<QWorkspaceChild *> windows;
- QList<QWorkspaceChild *> focus;
- QList<QWidget *> icons;
- QWorkspaceChild* maxWindow;
- QRect maxRestore;
- QPointer<QMDIControl> maxcontrols;
- QPointer<QMenuBar> maxmenubar;
- QHash<int, const char*> shortcutMap;
-
- int px;
- int py;
- QWidget *becomeActive;
- QPointer<QLabel> maxtools;
- QString topTitle;
-
- QMenu *popup, *toolPopup;
- enum WSActs { RestoreAct, MoveAct, ResizeAct, MinimizeAct, MaximizeAct, CloseAct, StaysOnTopAct, ShadeAct, NCountAct };
- QAction *actions[NCountAct];
-
- QScrollBar *vbar, *hbar;
- QWidget *corner;
- int yoffset, xoffset;
- QBrush background;
-
- void init();
- void insertIcon(QWidget* w);
- void removeIcon(QWidget* w);
- void place(QWidget*);
-
- QWorkspaceChild* findChild(QWidget* w);
- void showMaximizeControls();
- void hideMaximizeControls();
- void activateWindow(QWidget* w, bool change_focus = true);
- void hideChild(QWorkspaceChild *c);
- void showWindow(QWidget* w);
- void maximizeWindow(QWidget* w);
- void minimizeWindow(QWidget* w);
- void normalizeWindow(QWidget* w);
-
- QRect updateWorkspace();
-
-private:
- void _q_normalizeActiveWindow();
- void _q_minimizeActiveWindow();
- void _q_showOperationMenu();
- void _q_popupOperationMenu(const QPoint&);
- void _q_operationMenuActivated(QAction *);
- void _q_scrollBarChanged();
- void _q_updateActions();
- bool inTitleChange;
-};
-
-static bool isChildOf(QWidget * child, QWidget * parent)
-{
- if (!parent || !child)
- return false;
- QWidget * w = child;
- while(w && w != parent)
- w = w->parentWidget();
- return w != 0;
-}
-
-/*!
- Constructs a workspace with the given \a parent.
-*/
-QWorkspace::QWorkspace(QWidget *parent)
- : QWidget(*new QWorkspacePrivate, parent, 0)
-{
- Q_D(QWorkspace);
- d->init();
-}
-
-#ifdef QT3_SUPPORT
-/*!
- Use one of the constructors that doesn't take the \a name
- argument and then use setObjectName() instead.
-*/
-QWorkspace::QWorkspace(QWidget *parent, const char *name)
- : QWidget(*new QWorkspacePrivate, parent, 0)
-{
- Q_D(QWorkspace);
- setObjectName(QString::fromAscii(name));
- d->init();
-}
-#endif // QT3_SUPPORT
-
-/*!
- \internal
-*/
-void
-QWorkspacePrivate::init()
-{
- Q_Q(QWorkspace);
-
- maxcontrols = 0;
- active = 0;
- maxWindow = 0;
- maxtools = 0;
- px = 0;
- py = 0;
- becomeActive = 0;
- popup = new QMenu(q);
- toolPopup = new QMenu(q);
- popup->setObjectName(QLatin1String("qt_internal_mdi_popup"));
- toolPopup->setObjectName(QLatin1String("qt_internal_mdi_tool_popup"));
-
- actions[QWorkspacePrivate::RestoreAct] = new QAction(QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarNormalButton, 0, q)),
- QWorkspace::tr("&Restore"), q);
- actions[QWorkspacePrivate::MoveAct] = new QAction(QWorkspace::tr("&Move"), q);
- actions[QWorkspacePrivate::ResizeAct] = new QAction(QWorkspace::tr("&Size"), q);
- actions[QWorkspacePrivate::MinimizeAct] = new QAction(QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarMinButton, 0, q)),
- QWorkspace::tr("Mi&nimize"), q);
- actions[QWorkspacePrivate::MaximizeAct] = new QAction(QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarMaxButton, 0, q)),
- QWorkspace::tr("Ma&ximize"), q);
- actions[QWorkspacePrivate::CloseAct] = new QAction(QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarCloseButton, 0, q)),
- QWorkspace::tr("&Close")
-#ifndef QT_NO_SHORTCUT
- +QLatin1Char('\t')+(QString)QKeySequence(Qt::CTRL+Qt::Key_F4)
-#endif
- ,q);
- QObject::connect(actions[QWorkspacePrivate::CloseAct], SIGNAL(triggered()), q, SLOT(closeActiveWindow()));
- actions[QWorkspacePrivate::StaysOnTopAct] = new QAction(QWorkspace::tr("Stay on &Top"), q);
- actions[QWorkspacePrivate::StaysOnTopAct]->setChecked(true);
- actions[QWorkspacePrivate::ShadeAct] = new QAction(QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarShadeButton, 0, q)),
- QWorkspace::tr("Sh&ade"), q);
-
- QObject::connect(popup, SIGNAL(aboutToShow()), q, SLOT(_q_updateActions()));
- QObject::connect(popup, SIGNAL(triggered(QAction*)), q, SLOT(_q_operationMenuActivated(QAction*)));
- popup->addAction(actions[QWorkspacePrivate::RestoreAct]);
- popup->addAction(actions[QWorkspacePrivate::MoveAct]);
- popup->addAction(actions[QWorkspacePrivate::ResizeAct]);
- popup->addAction(actions[QWorkspacePrivate::MinimizeAct]);
- popup->addAction(actions[QWorkspacePrivate::MaximizeAct]);
- popup->addSeparator();
- popup->addAction(actions[QWorkspacePrivate::CloseAct]);
-
- QObject::connect(toolPopup, SIGNAL(aboutToShow()), q, SLOT(_q_updateActions()));
- QObject::connect(toolPopup, SIGNAL(triggered(QAction*)), q, SLOT(_q_operationMenuActivated(QAction*)));
- toolPopup->addAction(actions[QWorkspacePrivate::MoveAct]);
- toolPopup->addAction(actions[QWorkspacePrivate::ResizeAct]);
- toolPopup->addAction(actions[QWorkspacePrivate::StaysOnTopAct]);
- toolPopup->addSeparator();
- toolPopup->addAction(actions[QWorkspacePrivate::ShadeAct]);
- toolPopup->addAction(actions[QWorkspacePrivate::CloseAct]);
-
-#ifndef QT_NO_SHORTCUT
- // Set up shortcut bindings (id -> slot), most used first
- QList <QKeySequence> shortcuts = QKeySequence::keyBindings(QKeySequence::NextChild);
- foreach (const QKeySequence &seq, shortcuts)
- shortcutMap.insert(q->grabShortcut(seq), "activateNextWindow");
-
- shortcuts = QKeySequence::keyBindings(QKeySequence::PreviousChild);
- foreach (const QKeySequence &seq, shortcuts)
- shortcutMap.insert(q->grabShortcut(seq), "activatePreviousWindow");
-
- shortcuts = QKeySequence::keyBindings(QKeySequence::Close);
- foreach (const QKeySequence &seq, shortcuts)
- shortcutMap.insert(q->grabShortcut(seq), "closeActiveWindow");
-
- shortcutMap.insert(q->grabShortcut(QKeySequence(QLatin1String("ALT+-"))), "_q_showOperationMenu");
-#endif // QT_NO_SHORTCUT
-
- q->setBackgroundRole(QPalette::Dark);
- q->setAutoFillBackground(true);
- q->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
-
- hbar = vbar = 0;
- corner = 0;
- xoffset = yoffset = 0;
-
- q->window()->installEventFilter(q);
-
- inTitleChange = false;
- updateWorkspace();
-}
-
-/*!
- Destroys the workspace and frees any allocated resources.
-*/
-
-QWorkspace::~QWorkspace()
-{
-}
-
-/*! \reimp */
-QSize QWorkspace::sizeHint() const
-{
- QSize s(QApplication::desktop()->size());
- return QSize(s.width()*2/3, s.height()*2/3);
-}
-
-
-#ifdef QT3_SUPPORT
-/*!
- Sets the background color to \a c.
- Use setBackground() instead.
-*/
-void QWorkspace::setPaletteBackgroundColor(const QColor & c)
-{
- setBackground(c);
-}
-
-/*!
- Sets the background pixmap to \a pm.
- Use setBackground() instead.
-*/
-void QWorkspace::setPaletteBackgroundPixmap(const QPixmap & pm)
-{
- setBackground(pm);
-}
-#endif // QT3_SUPPORT
-
-/*!
- \property QWorkspace::background
- \brief the workspace's background
-*/
-QBrush QWorkspace::background() const
-{
- Q_D(const QWorkspace);
- if (d->background.style() == Qt::NoBrush)
- return palette().dark();
- return d->background;
-}
-
-void QWorkspace::setBackground(const QBrush &background)
-{
- Q_D(QWorkspace);
- d->background = background;
- setAttribute(Qt::WA_OpaquePaintEvent, background.style() == Qt::NoBrush);
- update();
-}
-
-/*!
- Adds widget \a w as new sub window to the workspace. If \a flags
- are non-zero, they will override the flags set on the widget.
-
- Returns the widget used for the window frame.
-
- To remove the widget \a w from the workspace, simply call
- setParent() with the new parent (or 0 to make it a stand-alone
- window).
-*/
-QWidget * QWorkspace::addWindow(QWidget *w, Qt::WindowFlags flags)
-{
- Q_D(QWorkspace);
- if (!w)
- return 0;
-
- w->setAutoFillBackground(true);
-
- QWidgetPrivate::adjustFlags(flags);
-
-#if 0
- bool wasMaximized = w->isMaximized();
- bool wasMinimized = w->isMinimized();
-#endif
- bool hasSize = w->testAttribute(Qt::WA_Resized);
- int x = w->x();
- int y = w->y();
- bool hasPos = w->testAttribute(Qt::WA_Moved);
- QSize s = w->size().expandedTo(qSmartMinSize(w));
- if (!hasSize && w->sizeHint().isValid())
- w->adjustSize();
-
- QWorkspaceChild* child = new QWorkspaceChild(w, this, flags);
- child->setObjectName(QLatin1String("qt_workspacechild"));
- child->installEventFilter(this);
-
- connect(child, SIGNAL(popupOperationMenu(QPoint)),
- this, SLOT(_q_popupOperationMenu(QPoint)));
- connect(child, SIGNAL(showOperationMenu()),
- this, SLOT(_q_showOperationMenu()));
- d->windows.append(child);
- if (child->isVisibleTo(this))
- d->focus.append(child);
- child->internalRaise();
-
- if (!hasPos)
- d->place(child);
- if (!hasSize)
- child->adjustSize();
- if (hasPos)
- child->move(x, y);
-
- return child;
-
-#if 0
- if (wasMaximized)
- w->showMaximized();
- else if (wasMinimized)
- w->showMinimized();
- else if (!hasBeenHidden)
- d->activateWindow(w);
-
- d->updateWorkspace();
- return child;
-#endif
-}
-
-/*! \reimp */
-void QWorkspace::childEvent(QChildEvent * e)
-{
- Q_D(QWorkspace);
- if (e->removed()) {
- if (d->windows.removeAll(static_cast<QWorkspaceChild*>(e->child()))) {
- d->focus.removeAll(static_cast<QWorkspaceChild*>(e->child()));
- if (d->maxWindow == e->child())
- d->maxWindow = 0;
- d->updateWorkspace();
- }
- }
-}
-
-/*! \reimp */
-#ifndef QT_NO_WHEELEVENT
-void QWorkspace::wheelEvent(QWheelEvent *e)
-{
- Q_D(QWorkspace);
- if (!scrollBarsEnabled())
- return;
- // the scroll bars are children of the workspace, so if we receive
- // a wheel event we redirect to the scroll bars using a direct event
- // call, /not/ using sendEvent() because if the scroll bar ignores the
- // event QApplication::sendEvent() will propagate the event to the parent widget,
- // which is us, who /just/ sent it.
- if (d->vbar && d->vbar->isVisible() && !(e->modifiers() & Qt::AltModifier))
- d->vbar->event(e);
- else if (d->hbar && d->hbar->isVisible())
- d->hbar->event(e);
-}
-#endif
-
-void QWorkspacePrivate::activateWindow(QWidget* w, bool change_focus)
-{
- Q_Q(QWorkspace);
- if (!w) {
- active = 0;
- emit q->windowActivated(0);
- return;
- }
- if (!q->isVisible()) {
- becomeActive = w;
- return;
- }
-
- if (active && active->windowWidget() == w) {
- if (!isChildOf(q->focusWidget(), w)) // child window does not have focus
- active->setActive(true);
- return;
- }
-
- active = 0;
- // First deactivate all other workspace clients
- QList<QWorkspaceChild *>::Iterator it(windows.begin());
- while (it != windows.end()) {
- QWorkspaceChild* c = *it;
- ++it;
- if (c->windowWidget() == w)
- active = c;
- else
- c->setActive(false);
- }
-
- if (!active)
- return;
-
- // Then activate the new one, so the focus is stored correctly
- active->setActive(true);
-
- if (!active)
- return;
-
- if (maxWindow && maxWindow != active && active->windowWidget() &&
- (active->windowWidget()->windowFlags() & Qt::WindowMaximizeButtonHint))
- active->showMaximized();
-
- active->internalRaise();
-
- if (change_focus) {
- int from = focus.indexOf(active);
- if (from >= 0)
- focus.move(from, focus.size() - 1);
- }
-
- updateWorkspace();
- emit q->windowActivated(w);
-}
-
-
-/*!
- Returns a pointer to the widget corresponding to the active child
- window, or 0 if no window is active.
-
- \sa setActiveWindow()
-*/
-QWidget* QWorkspace::activeWindow() const
-{
- Q_D(const QWorkspace);
- return d->active? d->active->windowWidget() : 0;
-}
-
-/*!
- Makes the child window that contains \a w the active child window.
-
- \sa activeWindow()
-*/
-void QWorkspace::setActiveWindow(QWidget *w)
-{
- Q_D(QWorkspace);
- d->activateWindow(w, true);
- if (w && w->isMinimized())
- w->setWindowState(w->windowState() & ~Qt::WindowMinimized);
-}
-
-void QWorkspacePrivate::place(QWidget *w)
-{
- Q_Q(QWorkspace);
-
- QList<QWidget *> widgets;
- for (QList<QWorkspaceChild *>::Iterator it(windows.begin()); it != windows.end(); ++it)
- if (*it != w)
- widgets.append(*it);
-
- int overlap, minOverlap = 0;
- int possible;
-
- QRect r1(0, 0, 0, 0);
- QRect r2(0, 0, 0, 0);
- QRect maxRect = q->rect();
- int x = maxRect.left(), y = maxRect.top();
- QPoint wpos(maxRect.left(), maxRect.top());
-
- bool firstPass = true;
-
- do {
- if (y + w->height() > maxRect.bottom()) {
- overlap = -1;
- } else if(x + w->width() > maxRect.right()) {
- overlap = -2;
- } else {
- overlap = 0;
-
- r1.setRect(x, y, w->width(), w->height());
-
- QWidget *l;
- QList<QWidget *>::Iterator it(widgets.begin());
- while (it != widgets.end()) {
- l = *it;
- ++it;
-
- if (maxWindow == l)
- r2 = QStyle::visualRect(q->layoutDirection(), maxRect, maxRestore);
- else
- r2 = QStyle::visualRect(q->layoutDirection(), maxRect,
- QRect(l->x(), l->y(), l->width(), l->height()));
-
- if (r2.intersects(r1)) {
- r2.setCoords(qMax(r1.left(), r2.left()),
- qMax(r1.top(), r2.top()),
- qMin(r1.right(), r2.right()),
- qMin(r1.bottom(), r2.bottom())
- );
-
- overlap += (r2.right() - r2.left()) *
- (r2.bottom() - r2.top());
- }
- }
- }
-
- if (overlap == 0) {
- wpos = QPoint(x, y);
- break;
- }
-
- if (firstPass) {
- firstPass = false;
- minOverlap = overlap;
- } else if (overlap >= 0 && overlap < minOverlap) {
- minOverlap = overlap;
- wpos = QPoint(x, y);
- }
-
- if (overlap > 0) {
- possible = maxRect.right();
- if (possible - w->width() > x) possible -= w->width();
-
- QWidget *l;
- QList<QWidget *>::Iterator it(widgets.begin());
- while (it != widgets.end()) {
- l = *it;
- ++it;
- if (maxWindow == l)
- r2 = QStyle::visualRect(q->layoutDirection(), maxRect, maxRestore);
- else
- r2 = QStyle::visualRect(q->layoutDirection(), maxRect,
- QRect(l->x(), l->y(), l->width(), l->height()));
-
- if((y < r2.bottom()) && (r2.top() < w->height() + y)) {
- if(r2.right() > x)
- possible = possible < r2.right() ?
- possible : r2.right();
-
- if(r2.left() - w->width() > x)
- possible = possible < r2.left() - w->width() ?
- possible : r2.left() - w->width();
- }
- }
-
- x = possible;
- } else if (overlap == -2) {
- x = maxRect.left();
- possible = maxRect.bottom();
-
- if (possible - w->height() > y) possible -= w->height();
-
- QWidget *l;
- QList<QWidget *>::Iterator it(widgets.begin());
- while (it != widgets.end()) {
- l = *it;
- ++it;
- if (maxWindow == l)
- r2 = QStyle::visualRect(q->layoutDirection(), maxRect, maxRestore);
- else
- r2 = QStyle::visualRect(q->layoutDirection(), maxRect,
- QRect(l->x(), l->y(), l->width(), l->height()));
-
- if(r2.bottom() > y)
- possible = possible < r2.bottom() ?
- possible : r2.bottom();
-
- if(r2.top() - w->height() > y)
- possible = possible < r2.top() - w->height() ?
- possible : r2.top() - w->height();
- }
-
- y = possible;
- }
- }
- while(overlap != 0 && overlap != -1);
-
- QRect resultRect = w->geometry();
- resultRect.moveTo(wpos);
- w->setGeometry(QStyle::visualRect(q->layoutDirection(), maxRect, resultRect));
- updateWorkspace();
-}
-
-
-void QWorkspacePrivate::insertIcon(QWidget* w)
-{
- Q_Q(QWorkspace);
- if (!w || icons.contains(w))
- return;
- icons.append(w);
- if (w->parentWidget() != q) {
- w->setParent(q, 0);
- w->move(0,0);
- }
- QRect cr = updateWorkspace();
- int x = 0;
- int y = cr.height() - w->height();
-
- QList<QWidget *>::Iterator it(icons.begin());
- while (it != icons.end()) {
- QWidget* i = *it;
- ++it;
- if (x > 0 && x + i->width() > cr.width()){
- x = 0;
- y -= i->height();
- }
-
- if (i != w &&
- i->geometry().intersects(QRect(x, y, w->width(), w->height())))
- x += i->width();
- }
- w->move(x, y);
-
- if (q->isVisibleTo(q->parentWidget())) {
- w->show();
- w->lower();
- }
- updateWorkspace();
-}
-
-
-void QWorkspacePrivate::removeIcon(QWidget* w)
-{
- if (icons.removeAll(w))
- w->hide();
-}
-
-
-/*! \reimp */
-void QWorkspace::resizeEvent(QResizeEvent *)
-{
- Q_D(QWorkspace);
- if (d->maxWindow) {
- d->maxWindow->adjustToFullscreen();
- if (d->maxWindow->windowWidget())
- d->maxWindow->windowWidget()->overrideWindowState(Qt::WindowMaximized);
- }
- d->updateWorkspace();
-}
-
-/*! \reimp */
-void QWorkspace::showEvent(QShowEvent *e)
-{
- Q_D(QWorkspace);
- if (d->maxWindow)
- d->showMaximizeControls();
- QWidget::showEvent(e);
- if (d->becomeActive) {
- d->activateWindow(d->becomeActive);
- d->becomeActive = 0;
- } else if (d->windows.count() > 0 && !d->active) {
- d->activateWindow(d->windows.first()->windowWidget());
- }
-
-// // force a frame repaint - this is a workaround for what seems to be a bug
-// // introduced when changing the QWidget::show() implementation. Might be
-// // a windows bug as well though.
-// for (int i = 0; i < d->windows.count(); ++i) {
-// QWorkspaceChild* c = d->windows.at(i);
-// c->update(c->rect());
-// }
-
- d->updateWorkspace();
-}
-
-/*! \reimp */
-void QWorkspace::hideEvent(QHideEvent *)
-{
- Q_D(QWorkspace);
- if (!isVisible())
- d->hideMaximizeControls();
-}
-
-/*! \reimp */
-void QWorkspace::paintEvent(QPaintEvent *)
-{
- Q_D(QWorkspace);
-
- if (d->background.style() != Qt::NoBrush) {
- QPainter p(this);
- p.fillRect(0, 0, width(), height(), d->background);
- }
-}
-
-void QWorkspacePrivate::minimizeWindow(QWidget* w)
-{
- QWorkspaceChild* c = findChild(w);
-
- if (!w || !(w->windowFlags() & Qt::WindowMinimizeButtonHint))
- return;
-
- if (c) {
- bool wasMax = false;
- if (c == maxWindow) {
- wasMax = true;
- maxWindow = 0;
- hideMaximizeControls();
- for (QList<QWorkspaceChild *>::Iterator it(windows.begin()); it != windows.end(); ++it) {
- QWorkspaceChild* c = *it;
- if (c->titlebar)
- c->titlebar->setMovable(true);
- c->widgetResizeHandler->setActive(true);
- }
- }
- c->hide();
- if (wasMax)
- c->setGeometry(maxRestore);
- if (!focus.contains(c))
- focus.append(c);
- insertIcon(c->iconWidget());
-
- if (!maxWindow)
- activateWindow(w);
-
- updateWorkspace();
-
- w->overrideWindowState(Qt::WindowMinimized);
- c->overrideWindowState(Qt::WindowMinimized);
- }
-}
-
-void QWorkspacePrivate::normalizeWindow(QWidget* w)
-{
- Q_Q(QWorkspace);
- QWorkspaceChild* c = findChild(w);
- if (!w)
- return;
- if (c) {
- w->overrideWindowState(Qt::WindowNoState);
- hideMaximizeControls();
- if (!maxmenubar || q->style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, q) || !maxWindow) {
- if (w->minimumSize() != w->maximumSize())
- c->widgetResizeHandler->setActive(true);
- if (c->titlebar)
- c->titlebar->setMovable(true);
- }
- w->overrideWindowState(Qt::WindowNoState);
- c->overrideWindowState(Qt::WindowNoState);
-
- if (c == maxWindow) {
- c->setGeometry(maxRestore);
- maxWindow = 0;
- } else {
- if (c->iconw)
- removeIcon(c->iconw->parentWidget());
- c->show();
- }
-
- hideMaximizeControls();
- for (QList<QWorkspaceChild *>::Iterator it(windows.begin()); it != windows.end(); ++it) {
- QWorkspaceChild* c = *it;
- if (c->titlebar)
- c->titlebar->setMovable(true);
- if (c->childWidget && c->childWidget->minimumSize() != c->childWidget->maximumSize())
- c->widgetResizeHandler->setActive(true);
- }
- activateWindow(w, true);
- updateWorkspace();
- }
-}
-
-void QWorkspacePrivate::maximizeWindow(QWidget* w)
-{
- Q_Q(QWorkspace);
- QWorkspaceChild* c = findChild(w);
-
- if (!w || !(w->windowFlags() & Qt::WindowMaximizeButtonHint))
- return;
-
- if (!c || c == maxWindow)
- return;
-
- bool updatesEnabled = q->updatesEnabled();
- q->setUpdatesEnabled(false);
-
- if (c->iconw && icons.contains(c->iconw->parentWidget()))
- normalizeWindow(w);
- QRect r(c->geometry());
- QWorkspaceChild *oldMaxWindow = maxWindow;
- maxWindow = c;
-
- showMaximizeControls();
-
- c->adjustToFullscreen();
- c->show();
- c->internalRaise();
- if (oldMaxWindow != c) {
- if (oldMaxWindow) {
- oldMaxWindow->setGeometry(maxRestore);
- oldMaxWindow->overrideWindowState(Qt::WindowNoState);
- if(oldMaxWindow->windowWidget())
- oldMaxWindow->windowWidget()->overrideWindowState(Qt::WindowNoState);
- }
- maxRestore = r;
- }
-
- activateWindow(w);
-
- if(!maxmenubar || q->style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, q)) {
- if (!active && becomeActive) {
- active = (QWorkspaceChild*)becomeActive->parentWidget();
- active->setActive(true);
- becomeActive = 0;
- emit q->windowActivated(active->windowWidget());
- }
- c->widgetResizeHandler->setActive(false);
- if (c->titlebar)
- c->titlebar->setMovable(false);
- }
- updateWorkspace();
-
- w->overrideWindowState(Qt::WindowMaximized);
- c->overrideWindowState(Qt::WindowMaximized);
- q->setUpdatesEnabled(updatesEnabled);
-}
-
-void QWorkspacePrivate::showWindow(QWidget* w)
-{
- if (w->isMinimized() && (w->windowFlags() & Qt::WindowMinimizeButtonHint))
- minimizeWindow(w);
- else if ((maxWindow || w->isMaximized()) && w->windowFlags() & Qt::WindowMaximizeButtonHint)
- maximizeWindow(w);
- else if (w->windowFlags() & Qt::WindowMaximizeButtonHint)
- normalizeWindow(w);
- else
- w->parentWidget()->show();
- if (maxWindow)
- maxWindow->internalRaise();
- updateWorkspace();
-}
-
-
-QWorkspaceChild* QWorkspacePrivate::findChild(QWidget* w)
-{
- QList<QWorkspaceChild *>::Iterator it(windows.begin());
- while (it != windows.end()) {
- QWorkspaceChild* c = *it;
- ++it;
- if (c->windowWidget() == w)
- return c;
- }
- return 0;
-}
-
-/*!
- Returns a list of all visible or minimized child windows. If \a
- order is CreationOrder (the default), the windows are listed in
- the order in which they were inserted into the workspace. If \a
- order is StackingOrder, the windows are listed in their stacking
- order, with the topmost window as the last item in the list.
-*/
-QWidgetList QWorkspace::windowList(WindowOrder order) const
-{
- Q_D(const QWorkspace);
- QWidgetList windows;
- if (order == StackingOrder) {
- QObjectList cl = children();
- for (int i = 0; i < cl.size(); ++i) {
- QWorkspaceChild *c = qobject_cast<QWorkspaceChild*>(cl.at(i));
- if (c && c->isWindowOrIconVisible())
- windows.append(c->windowWidget());
- }
- } else {
- QList<QWorkspaceChild *>::ConstIterator it(d->windows.begin());
- while (it != d->windows.end()) {
- QWorkspaceChild* c = *it;
- ++it;
- if (c && c->isWindowOrIconVisible())
- windows.append(c->windowWidget());
- }
- }
- return windows;
-}
-
-
-/*! \reimp */
-bool QWorkspace::event(QEvent *e)
-{
-#ifndef QT_NO_SHORTCUT
- Q_D(QWorkspace);
- if (e->type() == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
- const char *theSlot = d->shortcutMap.value(se->shortcutId(), 0);
- if (theSlot)
- QMetaObject::invokeMethod(this, theSlot);
- } else
-#endif
- if (e->type() == QEvent::FocusIn || e->type() == QEvent::FocusOut){
- return true;
- }
- return QWidget::event(e);
-}
-
-/*! \reimp */
-bool QWorkspace::eventFilter(QObject *o, QEvent * e)
-{
- Q_D(QWorkspace);
- static QElapsedTimer* t = 0;
- static QWorkspace* tc = 0;
- if (o == d->maxtools) {
- switch (e->type()) {
- case QEvent::MouseButtonPress:
- {
- QMenuBar* b = (QMenuBar*)o->parent();
- if (!t)
- t = new QElapsedTimer;
- if (tc != this || t->elapsed() > QApplication::doubleClickInterval()) {
- if (isRightToLeft()) {
- QPoint p = b->mapToGlobal(QPoint(b->x() + b->width(), b->y() + b->height()));
- p.rx() -= d->popup->sizeHint().width();
- d->_q_popupOperationMenu(p);
- } else {
- d->_q_popupOperationMenu(b->mapToGlobal(QPoint(b->x(), b->y() + b->height())));
- }
- t->start();
- tc = this;
- } else {
- tc = 0;
- closeActiveWindow();
- }
- return true;
- }
- default:
- break;
- }
- return QWidget::eventFilter(o, e);
- }
- switch (e->type()) {
- case QEvent::HideToParent:
- break;
- case QEvent::ShowToParent:
- if (QWorkspaceChild *c = qobject_cast<QWorkspaceChild*>(o))
- if (!d->focus.contains(c))
- d->focus.append(c);
- d->updateWorkspace();
- break;
- case QEvent::WindowTitleChange:
- if (!d->inTitleChange) {
- if (o == window())
- d->topTitle = window()->windowTitle();
- if (d->maxWindow && d->maxWindow->windowWidget() && d->topTitle.size()) {
- d->inTitleChange = true;
- window()->setWindowTitle(tr("%1 - [%2]")
- .arg(d->topTitle).arg(d->maxWindow->windowWidget()->windowTitle()));
- d->inTitleChange = false;
- }
- }
- break;
-
- case QEvent::ModifiedChange:
- if (o == d->maxWindow)
- window()->setWindowModified(d->maxWindow->isWindowModified());
- break;
-
- case QEvent::Close:
- if (o == window())
- {
- QList<QWorkspaceChild *>::Iterator it(d->windows.begin());
- while (it != d->windows.end()) {
- QWorkspaceChild* c = *it;
- ++it;
- if (c->shademode)
- c->showShaded();
- }
- } else if (qobject_cast<QWorkspaceChild*>(o)) {
- d->popup->hide();
- }
- d->updateWorkspace();
- break;
- default:
- break;
- }
- return QWidget::eventFilter(o, e);
-}
-
-static QMenuBar *findMenuBar(QWidget *w)
-{
- // don't search recursively to avoid finding a menu bar of a
- // mainwindow that happens to be a workspace window (like
- // a mainwindow in designer)
- QList<QObject *> children = w->children();
- for (int i = 0; i < children.count(); ++i) {
- QMenuBar *bar = qobject_cast<QMenuBar *>(children.at(i));
- if (bar)
- return bar;
- }
- return 0;
-}
-
-void QWorkspacePrivate::showMaximizeControls()
-{
- Q_Q(QWorkspace);
- Q_ASSERT(maxWindow);
-
- // merge windowtitle and modified state
- if (!topTitle.size())
- topTitle = q->window()->windowTitle();
-
- if (maxWindow->windowWidget()) {
- QString docTitle = maxWindow->windowWidget()->windowTitle();
- if (topTitle.size() && docTitle.size()) {
- inTitleChange = true;
- q->window()->setWindowTitle(QWorkspace::tr("%1 - [%2]").arg(topTitle).arg(docTitle));
- inTitleChange = false;
- }
- q->window()->setWindowModified(maxWindow->windowWidget()->isWindowModified());
- }
-
- if (!q->style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, q)) {
- QMenuBar* b = 0;
-
- // Do a breadth-first search first on every parent,
- QWidget* w = q->parentWidget();
- while (w) {
- b = findMenuBar(w);
- if (b)
- break;
- w = w->parentWidget();
- }
-
- // last attempt.
- if (!b)
- b = findMenuBar(q->window());
-
- if (!b)
- return;
-
- if (!maxcontrols) {
- maxmenubar = b;
- maxcontrols = new QMDIControl(b);
- QObject::connect(maxcontrols, SIGNAL(_q_minimize()),
- q, SLOT(_q_minimizeActiveWindow()));
- QObject::connect(maxcontrols, SIGNAL(_q_restore()),
- q, SLOT(_q_normalizeActiveWindow()));
- QObject::connect(maxcontrols, SIGNAL(_q_close()),
- q, SLOT(closeActiveWindow()));
- }
-
- b->setCornerWidget(maxcontrols);
- if (b->isVisible())
- maxcontrols->show();
- if (!active && becomeActive) {
- active = (QWorkspaceChild*)becomeActive->parentWidget();
- active->setActive(true);
- becomeActive = 0;
- emit q->windowActivated(active->windowWidget());
- }
- if (active) {
- if (!maxtools) {
- maxtools = new QLabel(q->window());
- maxtools->setObjectName(QLatin1String("qt_maxtools"));
- maxtools->installEventFilter(q);
- }
- if (active->windowWidget() && !active->windowWidget()->windowIcon().isNull()) {
- QIcon icon = active->windowWidget()->windowIcon();
- int iconSize = maxcontrols->size().height();
- maxtools->setPixmap(icon.pixmap(QSize(iconSize, iconSize)));
- } else {
- QPixmap pm = q->style()->standardPixmap(QStyle::SP_TitleBarMenuButton, 0, q);
- if (pm.isNull()) {
- pm = QPixmap(14,14);
- pm.fill(Qt::black);
- }
- maxtools->setPixmap(pm);
- }
- b->setCornerWidget(maxtools, Qt::TopLeftCorner);
- if (b->isVisible())
- maxtools->show();
- }
- }
-}
-
-
-void QWorkspacePrivate::hideMaximizeControls()
-{
- Q_Q(QWorkspace);
- if (maxmenubar && !q->style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, q)) {
- if (maxmenubar) {
- maxmenubar->setCornerWidget(0, Qt::TopLeftCorner);
- maxmenubar->setCornerWidget(0, Qt::TopRightCorner);
- }
- if (maxcontrols) {
- maxcontrols->deleteLater();
- maxcontrols = 0;
- }
- if (maxtools) {
- maxtools->deleteLater();
- maxtools = 0;
- }
- }
-
- //unmerge the title bar/modification state
- if (topTitle.size()) {
- inTitleChange = true;
- q->window()->setWindowTitle(topTitle);
- inTitleChange = false;
- }
- q->window()->setWindowModified(false);
-}
-
-/*!
- Closes the child window that is currently active.
-
- \sa closeAllWindows()
-*/
-void QWorkspace::closeActiveWindow()
-{
- Q_D(QWorkspace);
- if (d->maxWindow && d->maxWindow->windowWidget())
- d->maxWindow->windowWidget()->close();
- else if (d->active && d->active->windowWidget())
- d->active->windowWidget()->close();
- d->updateWorkspace();
-}
-
-/*!
- Closes all child windows.
-
- If any child window fails to accept the close event, the remaining windows
- will remain open.
-
- \sa closeActiveWindow()
-*/
-void QWorkspace::closeAllWindows()
-{
- Q_D(QWorkspace);
- bool did_close = true;
- QList<QWorkspaceChild *>::const_iterator it = d->windows.constBegin();
- while (it != d->windows.constEnd() && did_close) {
- QWorkspaceChild *c = *it;
- ++it;
- if (c->windowWidget() && !c->windowWidget()->isHidden())
- did_close = c->windowWidget()->close();
- }
-}
-
-void QWorkspacePrivate::_q_normalizeActiveWindow()
-{
- if (maxWindow)
- maxWindow->showNormal();
- else if (active)
- active->showNormal();
-}
-
-void QWorkspacePrivate::_q_minimizeActiveWindow()
-{
- if (maxWindow)
- maxWindow->showMinimized();
- else if (active)
- active->showMinimized();
-}
-
-void QWorkspacePrivate::_q_showOperationMenu()
-{
- Q_Q(QWorkspace);
- if (!active || !active->windowWidget())
- return;
- Q_ASSERT((active->windowWidget()->windowFlags() & Qt::WindowSystemMenuHint));
- QPoint p;
- QMenu *popup = (active->titlebar && active->titlebar->isTool()) ? toolPopup : this->popup;
- if (q->isRightToLeft()) {
- p = QPoint(active->windowWidget()->mapToGlobal(QPoint(active->windowWidget()->width(),0)));
- p.rx() -= popup->sizeHint().width();
- } else {
- p = QPoint(active->windowWidget()->mapToGlobal(QPoint(0,0)));
- }
- if (!active->isVisible()) {
- p = active->iconWidget()->mapToGlobal(QPoint(0,0));
- p.ry() -= popup->sizeHint().height();
- }
- _q_popupOperationMenu(p);
-}
-
-void QWorkspacePrivate::_q_popupOperationMenu(const QPoint& p)
-{
- if (!active || !active->windowWidget() || !(active->windowWidget()->windowFlags() & Qt::WindowSystemMenuHint))
- return;
- if (active->titlebar && active->titlebar->isTool())
- toolPopup->popup(p);
- else
- popup->popup(p);
-}
-
-void QWorkspacePrivate::_q_updateActions()
-{
- Q_Q(QWorkspace);
- for (int i = 1; i < NCountAct-1; i++) {
- bool enable = active != 0;
- actions[i]->setEnabled(enable);
- }
-
- if (!active || !active->windowWidget())
- return;
-
- QWidget *windowWidget = active->windowWidget();
- bool canResize = windowWidget->maximumSize() != windowWidget->minimumSize();
- actions[QWorkspacePrivate::ResizeAct]->setEnabled(canResize);
- actions[QWorkspacePrivate::MinimizeAct]->setEnabled((windowWidget->windowFlags() & Qt::WindowMinimizeButtonHint));
- actions[QWorkspacePrivate::MaximizeAct]->setEnabled((windowWidget->windowFlags() & Qt::WindowMaximizeButtonHint) && canResize);
-
- if (active == maxWindow) {
- actions[QWorkspacePrivate::MoveAct]->setEnabled(false);
- actions[QWorkspacePrivate::ResizeAct]->setEnabled(false);
- actions[QWorkspacePrivate::MaximizeAct]->setEnabled(false);
- actions[QWorkspacePrivate::RestoreAct]->setEnabled(true);
- } else if (active->isVisible()){
- actions[QWorkspacePrivate::RestoreAct]->setEnabled(false);
- } else {
- actions[QWorkspacePrivate::MoveAct]->setEnabled(false);
- actions[QWorkspacePrivate::ResizeAct]->setEnabled(false);
- actions[QWorkspacePrivate::MinimizeAct]->setEnabled(false);
- actions[QWorkspacePrivate::RestoreAct]->setEnabled(true);
- }
- if (active->shademode) {
- actions[QWorkspacePrivate::ShadeAct]->setIcon(
- QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarUnshadeButton, 0, q)));
- actions[QWorkspacePrivate::ShadeAct]->setText(QWorkspace::tr("&Unshade"));
- } else {
- actions[QWorkspacePrivate::ShadeAct]->setIcon(
- QIcon(q->style()->standardPixmap(QStyle::SP_TitleBarShadeButton, 0, q)));
- actions[QWorkspacePrivate::ShadeAct]->setText(QWorkspace::tr("Sh&ade"));
- }
- actions[QWorkspacePrivate::StaysOnTopAct]->setEnabled(!active->shademode && canResize);
- actions[QWorkspacePrivate::StaysOnTopAct]->setChecked(
- (active->windowWidget()->windowFlags() & Qt::WindowStaysOnTopHint));
-}
-
-void QWorkspacePrivate::_q_operationMenuActivated(QAction *action)
-{
- if (!active)
- return;
- if(action == actions[QWorkspacePrivate::RestoreAct]) {
- active->showNormal();
- } else if(action == actions[QWorkspacePrivate::MoveAct]) {
- active->doMove();
- } else if(action == actions[QWorkspacePrivate::ResizeAct]) {
- if (active->shademode)
- active->showShaded();
- active->doResize();
- } else if(action == actions[QWorkspacePrivate::MinimizeAct]) {
- active->showMinimized();
- } else if(action == actions[QWorkspacePrivate::MaximizeAct]) {
- active->showMaximized();
- } else if(action == actions[QWorkspacePrivate::ShadeAct]) {
- active->showShaded();
- } else if(action == actions[QWorkspacePrivate::StaysOnTopAct]) {
- if(QWidget* w = active->windowWidget()) {
- if ((w->windowFlags() & Qt::WindowStaysOnTopHint)) {
- w->overrideWindowFlags(w->windowFlags() & ~Qt::WindowStaysOnTopHint);
- } else {
- w->overrideWindowFlags(w->windowFlags() | Qt::WindowStaysOnTopHint);
- w->parentWidget()->raise();
- }
- }
- }
-}
-
-
-void QWorkspacePrivate::hideChild(QWorkspaceChild *c)
-{
- Q_Q(QWorkspace);
-
-// bool updatesEnabled = q->updatesEnabled();
-// q->setUpdatesEnabled(false);
- focus.removeAll(c);
- QRect restore;
- if (maxWindow == c)
- restore = maxRestore;
- if (active == c) {
- q->setFocus();
- q->activatePreviousWindow();
- }
- if (active == c)
- activateWindow(0);
- if (maxWindow == c) {
- hideMaximizeControls();
- maxWindow = 0;
- }
- c->hide();
- if (!restore.isEmpty())
- c->setGeometry(restore);
-// q->setUpdatesEnabled(updatesEnabled);
-}
-
-/*!
- Gives the input focus to the next window in the list of child
- windows.
-
- \sa activatePreviousWindow()
-*/
-void QWorkspace::activateNextWindow()
-{
- Q_D(QWorkspace);
-
- if (d->focus.isEmpty())
- return;
- if (!d->active) {
- if (d->focus.first())
- d->activateWindow(d->focus.first()->windowWidget(), false);
- return;
- }
-
- int a = d->focus.indexOf(d->active) + 1;
-
- a = a % d->focus.count();
-
- if (d->focus.at(a))
- d->activateWindow(d->focus.at(a)->windowWidget(), false);
- else
- d->activateWindow(0);
-}
-
-/*!
- Gives the input focus to the previous window in the list of child
- windows.
-
- \sa activateNextWindow()
-*/
-void QWorkspace::activatePreviousWindow()
-{
- Q_D(QWorkspace);
-
- if (d->focus.isEmpty())
- return;
- if (!d->active) {
- if (d->focus.last())
- d->activateWindow(d->focus.first()->windowWidget(), false);
- else
- d->activateWindow(0);
- return;
- }
-
- int a = d->focus.indexOf(d->active) - 1;
- if (a < 0)
- a = d->focus.count()-1;
-
- if (d->focus.at(a))
- d->activateWindow(d->focus.at(a)->windowWidget(), false);
- else
- d->activateWindow(0);
-}
-
-
-/*!
- \fn void QWorkspace::windowActivated(QWidget* w)
-
- This signal is emitted when the child window \a w becomes active.
- Note that \a w can be 0, and that more than one signal may be
- emitted for a single activation event.
-
- \sa activeWindow(), windowList()
-*/
-
-/*!
- Arranges all the child windows in a cascade pattern.
-
- \sa tile(), arrangeIcons()
-*/
-void QWorkspace::cascade()
-{
- Q_D(QWorkspace);
- blockSignals(true);
- if (d->maxWindow)
- d->maxWindow->showNormal();
-
- if (d->vbar) {
- d->vbar->blockSignals(true);
- d->vbar->setValue(0);
- d->vbar->blockSignals(false);
- d->hbar->blockSignals(true);
- d->hbar->setValue(0);
- d->hbar->blockSignals(false);
- d->_q_scrollBarChanged();
- }
-
- const int xoffset = 13;
- const int yoffset = 20;
-
- // make a list of all relevant mdi clients
- QList<QWorkspaceChild *> widgets;
- QList<QWorkspaceChild *>::Iterator it(d->windows.begin());
- QWorkspaceChild* wc = 0;
-
- for (it = d->focus.begin(); it != d->focus.end(); ++it) {
- wc = *it;
- if (wc->windowWidget()->isVisibleTo(this) && !(wc->titlebar && wc->titlebar->isTool()))
- widgets.append(wc);
- }
-
- int x = 0;
- int y = 0;
-
- it = widgets.begin();
- while (it != widgets.end()) {
- QWorkspaceChild *child = *it;
- ++it;
-
- QSize prefSize = child->windowWidget()->sizeHint().expandedTo(qSmartMinSize(child->windowWidget()));
- if (!prefSize.isValid())
- prefSize = child->windowWidget()->size();
- prefSize = prefSize.expandedTo(qSmartMinSize(child->windowWidget()));
- if (prefSize.isValid())
- prefSize += QSize(child->baseSize().width(), child->baseSize().height());
-
- int w = prefSize.width();
- int h = prefSize.height();
-
- child->showNormal();
- if (y + h > height())
- y = 0;
- if (x + w > width())
- x = 0;
- child->setGeometry(x, y, w, h);
- x += xoffset;
- y += yoffset;
- child->internalRaise();
- }
- d->updateWorkspace();
- blockSignals(false);
-}
-
-/*!
- Arranges all child windows in a tile pattern.
-
- \sa cascade(), arrangeIcons()
-*/
-void QWorkspace::tile()
-{
- Q_D(QWorkspace);
- blockSignals(true);
- QWidget *oldActive = d->active ? d->active->windowWidget() : 0;
- if (d->maxWindow)
- d->maxWindow->showNormal();
-
- if (d->vbar) {
- d->vbar->blockSignals(true);
- d->vbar->setValue(0);
- d->vbar->blockSignals(false);
- d->hbar->blockSignals(true);
- d->hbar->setValue(0);
- d->hbar->blockSignals(false);
- d->_q_scrollBarChanged();
- }
-
- int rows = 1;
- int cols = 1;
- int n = 0;
- QWorkspaceChild* c;
-
- QList<QWorkspaceChild *>::Iterator it(d->windows.begin());
- while (it != d->windows.end()) {
- c = *it;
- ++it;
- if (!c->windowWidget()->isHidden()
- && !(c->windowWidget()->windowFlags() & Qt::WindowStaysOnTopHint)
- && !c->iconw)
- n++;
- }
-
- while (rows * cols < n) {
- if (cols <= rows)
- cols++;
- else
- rows++;
- }
- int add = cols * rows - n;
- bool* used = new bool[cols*rows];
- for (int i = 0; i < rows*cols; i++)
- used[i] = false;
-
- int row = 0;
- int col = 0;
- int w = width() / cols;
- int h = height() / rows;
-
- it = d->windows.begin();
- while (it != d->windows.end()) {
- c = *it;
- ++it;
- if (c->iconw || c->windowWidget()->isHidden() || (c->titlebar && c->titlebar->isTool()))
- continue;
- if (!row && !col) {
- w -= c->baseSize().width();
- h -= c->baseSize().height();
- }
- if ((c->windowWidget()->windowFlags() & Qt::WindowStaysOnTopHint)) {
- QPoint p = c->pos();
- if (p.x()+c->width() < 0)
- p.setX(0);
- if (p.x() > width())
- p.setX(width() - c->width());
- if (p.y() + 10 < 0)
- p.setY(0);
- if (p.y() > height())
- p.setY(height() - c->height());
-
- if (p != c->pos())
- c->QWidget::move(p);
- } else {
- c->showNormal();
- used[row*cols+col] = true;
- QSize sz(w, h);
- QSize bsize(c->baseSize());
- sz = sz.expandedTo(c->windowWidget()->minimumSize()).boundedTo(c->windowWidget()->maximumSize());
- sz += bsize;
-
- if ( add ) {
- if (sz.height() == h + bsize.height()) // no relevant constrains
- sz.rheight() *= 2;
- used[(row+1)*cols+col] = true;
- add--;
- }
-
- c->setGeometry(col*w + col*bsize.width(), row*h + row*bsize.height(), sz.width(), sz.height());
-
- while(row < rows && col < cols && used[row*cols+col]) {
- col++;
- if (col == cols) {
- col = 0;
- row++;
- }
- }
- }
- }
- delete [] used;
-
- d->activateWindow(oldActive);
- d->updateWorkspace();
- blockSignals(false);
-}
-
-/*!
- Arranges all iconified windows at the bottom of the workspace.
-
- \sa cascade(), tile()
-*/
-void QWorkspace::arrangeIcons()
-{
- Q_D(QWorkspace);
-
- QRect cr = d->updateWorkspace();
- int x = 0;
- int y = -1;
-
- QList<QWidget *>::Iterator it(d->icons.begin());
- while (it != d->icons.end()) {
- QWidget* i = *it;
- if (y == -1)
- y = cr.height() - i->height();
- if (x > 0 && x + i->width() > cr.width()) {
- x = 0;
- y -= i->height();
- }
- i->move(x, y);
- x += i->width();
- ++it;
- }
- d->updateWorkspace();
-}
-
-
-QWorkspaceChild::QWorkspaceChild(QWidget* window, QWorkspace *parent, Qt::WindowFlags flags)
- : QWidget(parent,
- Qt::FramelessWindowHint | Qt::SubWindow)
-{
- setAttribute(Qt::WA_DeleteOnClose);
- setAttribute(Qt::WA_NoMousePropagation);
- setMouseTracking(true);
- act = false;
- iconw = 0;
- shademode = false;
- titlebar = 0;
- setAutoFillBackground(true);
-
- setBackgroundRole(QPalette::Window);
- if (window) {
- flags |= (window->windowFlags() & Qt::MSWindowsOwnDC);
- if (flags)
- window->setParent(this, flags & ~Qt::WindowType_Mask);
- else
- window->setParent(this);
- }
-
- if (window && (flags & (Qt::WindowTitleHint
- | Qt::WindowSystemMenuHint
- | Qt::WindowMinimizeButtonHint
- | Qt::WindowMaximizeButtonHint
- | Qt::WindowContextHelpButtonHint))) {
- titlebar = new QWorkspaceTitleBar(window, this, flags);
- connect(titlebar, SIGNAL(doActivate()),
- this, SLOT(activate()));
- connect(titlebar, SIGNAL(doClose()),
- window, SLOT(close()));
- connect(titlebar, SIGNAL(doMinimize()),
- this, SLOT(showMinimized()));
- connect(titlebar, SIGNAL(doNormal()),
- this, SLOT(showNormal()));
- connect(titlebar, SIGNAL(doMaximize()),
- this, SLOT(showMaximized()));
- connect(titlebar, SIGNAL(popupOperationMenu(QPoint)),
- this, SIGNAL(popupOperationMenu(QPoint)));
- connect(titlebar, SIGNAL(showOperationMenu()),
- this, SIGNAL(showOperationMenu()));
- connect(titlebar, SIGNAL(doShade()),
- this, SLOT(showShaded()));
- connect(titlebar, SIGNAL(doubleClicked()),
- this, SLOT(titleBarDoubleClicked()));
- }
-
- setMinimumSize(128, 0);
- int fw = style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, this);
- setContentsMargins(fw, fw, fw, fw);
-
- childWidget = window;
- if (!childWidget)
- return;
-
- setWindowTitle(childWidget->windowTitle());
-
- QPoint p;
- QSize s;
- QSize cs;
-
- bool hasBeenResized = childWidget->testAttribute(Qt::WA_Resized);
-
- if (!hasBeenResized)
- cs = childWidget->sizeHint().expandedTo(childWidget->minimumSizeHint()).expandedTo(childWidget->minimumSize()).boundedTo(childWidget->maximumSize());
- else
- cs = childWidget->size();
-
- windowSize = cs;
-
- int th = titlebar ? titlebar->sizeHint().height() : 0;
- if (titlebar) {
- if (!childWidget->windowIcon().isNull())
- titlebar->setWindowIcon(childWidget->windowIcon());
-
- if (style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar))
- th -= contentsRect().y();
-
- p = QPoint(contentsRect().x(),
- th + contentsRect().y());
- s = QSize(cs.width() + 2*frameWidth(),
- cs.height() + 2*frameWidth() + th);
- } else {
- p = QPoint(contentsRect().x(), contentsRect().y());
- s = QSize(cs.width() + 2*frameWidth(),
- cs.height() + 2*frameWidth());
- }
-
- childWidget->move(p);
- resize(s);
-
- childWidget->installEventFilter(this);
-
- widgetResizeHandler = new QWidgetResizeHandler(this, window);
- widgetResizeHandler->setSizeProtection(!parent->scrollBarsEnabled());
- widgetResizeHandler->setFrameWidth(frameWidth());
- connect(widgetResizeHandler, SIGNAL(activate()),
- this, SLOT(activate()));
- if (!style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar))
- widgetResizeHandler->setExtraHeight(th + contentsRect().y() - 2*frameWidth());
- else
- widgetResizeHandler->setExtraHeight(th + contentsRect().y() - frameWidth());
- if (childWidget->minimumSize() == childWidget->maximumSize())
- widgetResizeHandler->setActive(QWidgetResizeHandler::Resize, false);
- setBaseSize(baseSize());
-}
-
-QWorkspaceChild::~QWorkspaceChild()
-{
- QWorkspace *workspace = qobject_cast<QWorkspace*>(parentWidget());
- if (iconw) {
- if (workspace)
- workspace->d_func()->removeIcon(iconw->parentWidget());
- delete iconw->parentWidget();
- }
-
- if (workspace) {
- workspace->d_func()->focus.removeAll(this);
- if (workspace->d_func()->active == this)
- workspace->activatePreviousWindow();
- if (workspace->d_func()->active == this)
- workspace->d_func()->activateWindow(0);
- if (workspace->d_func()->maxWindow == this) {
- workspace->d_func()->hideMaximizeControls();
- workspace->d_func()->maxWindow = 0;
- }
- }
-}
-
-void QWorkspaceChild::moveEvent(QMoveEvent *)
-{
- ((QWorkspace*)parentWidget())->d_func()->updateWorkspace();
-}
-
-void QWorkspaceChild::resizeEvent(QResizeEvent *)
-{
- bool wasMax = isMaximized();
- QRect r = contentsRect();
- QRect cr;
-
- updateMask();
-
- if (titlebar) {
- int th = titlebar->sizeHint().height();
- QRect tbrect(0, 0, width(), th);
- if (!style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar))
- tbrect = QRect(r.x(), r.y(), r.width(), th);
- titlebar->setGeometry(tbrect);
-
- if (style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar))
- th -= frameWidth();
- cr = QRect(r.x(), r.y() + th + (shademode ? (frameWidth() * 3) : 0),
- r.width(), r.height() - th);
- } else {
- cr = r;
- }
-
- if (!childWidget)
- return;
-
- bool doContentsResize = (windowSize == childWidget->size()
- || !(childWidget->testAttribute(Qt::WA_Resized) && childWidget->testAttribute(Qt::WA_PendingResizeEvent))
- ||childWidget->isMaximized());
-
- windowSize = cr.size();
- childWidget->move(cr.topLeft());
- if (doContentsResize)
- childWidget->resize(cr.size());
- ((QWorkspace*)parentWidget())->d_func()->updateWorkspace();
-
- if (wasMax) {
- overrideWindowState(Qt::WindowMaximized);
- childWidget->overrideWindowState(Qt::WindowMaximized);
- }
-}
-
-QSize QWorkspaceChild::baseSize() const
-{
- int th = titlebar ? titlebar->sizeHint().height() : 0;
- if (style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar))
- th -= frameWidth();
- return QSize(2*frameWidth(), 2*frameWidth() + th);
-}
-
-QSize QWorkspaceChild::sizeHint() const
-{
- if (!childWidget)
- return QWidget::sizeHint() + baseSize();
-
- QSize prefSize = windowWidget()->sizeHint().expandedTo(windowWidget()->minimumSizeHint());
- prefSize = prefSize.expandedTo(windowWidget()->minimumSize()).boundedTo(windowWidget()->maximumSize());
- prefSize += baseSize();
-
- return prefSize;
-}
-
-QSize QWorkspaceChild::minimumSizeHint() const
-{
- if (!childWidget)
- return QWidget::minimumSizeHint() + baseSize();
- QSize s = childWidget->minimumSize();
- if (s.isEmpty())
- s = childWidget->minimumSizeHint();
- return s + baseSize();
-}
-
-void QWorkspaceChild::activate()
-{
- ((QWorkspace*)parentWidget())->d_func()->activateWindow(windowWidget());
-}
-
-bool QWorkspaceChild::eventFilter(QObject * o, QEvent * e)
-{
- if (!isActive()
- && (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::FocusIn)) {
- if (iconw) {
- ((QWorkspace*)parentWidget())->d_func()->normalizeWindow(windowWidget());
- if (iconw) {
- ((QWorkspace*)parentWidget())->d_func()->removeIcon(iconw->parentWidget());
- delete iconw->parentWidget();
- iconw = 0;
- }
- }
- activate();
- }
-
- // for all widgets except the window, that's the only thing we
- // process, and if we have no childWidget we skip totally
- if (o != childWidget || childWidget == 0)
- return false;
-
- switch (e->type()) {
- case QEvent::ShowToParent:
- if (((QWorkspace*)parentWidget())->d_func()->focus.indexOf(this) < 0)
- ((QWorkspace*)parentWidget())->d_func()->focus.append(this);
-
- if (windowWidget() && (windowWidget()->windowFlags() & Qt::WindowStaysOnTopHint)) {
- internalRaise();
- show();
- }
- ((QWorkspace*)parentWidget())->d_func()->showWindow(windowWidget());
- break;
- case QEvent::WindowStateChange: {
- if (static_cast<QWindowStateChangeEvent*>(e)->isOverride())
- break;
- Qt::WindowStates state = windowWidget()->windowState();
-
- if (state & Qt::WindowMinimized) {
- ((QWorkspace*)parentWidget())->d_func()->minimizeWindow(windowWidget());
- } else if (state & Qt::WindowMaximized) {
- if (windowWidget()->maximumSize().isValid() &&
- (windowWidget()->maximumWidth() < parentWidget()->width() ||
- windowWidget()->maximumHeight() < parentWidget()->height())) {
- windowWidget()->resize(windowWidget()->maximumSize());
- windowWidget()->overrideWindowState(Qt::WindowNoState);
- if (titlebar)
- titlebar->update();
- break;
- }
- if ((windowWidget()->windowFlags() & Qt::WindowMaximizeButtonHint))
- ((QWorkspace*)parentWidget())->d_func()->maximizeWindow(windowWidget());
- else
- ((QWorkspace*)parentWidget())->d_func()->normalizeWindow(windowWidget());
- } else {
- ((QWorkspace*)parentWidget())->d_func()->normalizeWindow(windowWidget());
- if (iconw) {
- ((QWorkspace*)parentWidget())->d_func()->removeIcon(iconw->parentWidget());
- delete iconw->parentWidget();
- }
- }
- } break;
- case QEvent::HideToParent:
- {
- QWidget * w = iconw;
- if (w && (w = w->parentWidget())) {
- ((QWorkspace*)parentWidget())->d_func()->removeIcon(w);
- delete w;
- }
- ((QWorkspace*)parentWidget())->d_func()->hideChild(this);
- } break;
- case QEvent::WindowIconChange:
- {
- QWorkspace* ws = (QWorkspace*)parentWidget();
- if (ws->d_func()->maxtools && ws->d_func()->maxWindow == this) {
- int iconSize = ws->d_func()->maxtools->size().height();
- ws->d_func()->maxtools->setPixmap(childWidget->windowIcon().pixmap(QSize(iconSize, iconSize)));
- }
- }
- // fall through
- case QEvent::WindowTitleChange:
- setWindowTitle(windowWidget()->windowTitle());
- if (titlebar)
- titlebar->update();
- if (iconw)
- iconw->update();
- break;
- case QEvent::ModifiedChange:
- setWindowModified(windowWidget()->isWindowModified());
- if (titlebar)
- titlebar->update();
- if (iconw)
- iconw->update();
- break;
- case QEvent::Resize:
- {
- QResizeEvent* re = (QResizeEvent*)e;
- if (re->size() != windowSize && !shademode) {
- resize(re->size() + baseSize());
- childWidget->update(); //workaround
- }
- }
- break;
-
- case QEvent::WindowDeactivate:
- if (titlebar && titlebar->isActive()) {
- update();
- }
- break;
-
- case QEvent::WindowActivate:
- if (titlebar && titlebar->isActive()) {
- update();
- }
- break;
-
- default:
- break;
- }
-
- return QWidget::eventFilter(o, e);
-}
-
-void QWorkspaceChild::childEvent(QChildEvent* e)
-{
- if (e->type() == QEvent::ChildRemoved && e->child() == childWidget) {
- childWidget = 0;
- if (iconw) {
- ((QWorkspace*)parentWidget())->d_func()->removeIcon(iconw->parentWidget());
- delete iconw->parentWidget();
- }
- close();
- }
-}
-
-
-void QWorkspaceChild::doResize()
-{
- widgetResizeHandler->doResize();
-}
-
-void QWorkspaceChild::doMove()
-{
- widgetResizeHandler->doMove();
-}
-
-void QWorkspaceChild::enterEvent(QEvent *)
-{
-}
-
-void QWorkspaceChild::leaveEvent(QEvent *)
-{
-#ifndef QT_NO_CURSOR
- if (!widgetResizeHandler->isButtonDown())
- setCursor(Qt::ArrowCursor);
-#endif
-}
-
-void QWorkspaceChild::paintEvent(QPaintEvent *)
-{
- QPainter p(this);
- QStyleOptionFrame opt;
- opt.rect = rect();
- opt.palette = palette();
- opt.state = QStyle::State_None;
- opt.lineWidth = style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, this);
- opt.midLineWidth = 1;
-
- if (titlebar && titlebar->isActive() && isActiveWindow())
- opt.state |= QStyle::State_Active;
-
- style()->drawPrimitive(QStyle::PE_FrameWindow, &opt, &p, this);
-}
-
-void QWorkspaceChild::changeEvent(QEvent *ev)
-{
- if(ev->type() == QEvent::StyleChange) {
- resizeEvent(0);
- if (iconw) {
- QFrame *frame = qobject_cast<QFrame*>(iconw->parentWidget());
- Q_ASSERT(frame);
- if (!style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar)) {
- frame->setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
- frame->resize(196+2*frame->frameWidth(), 20 + 2*frame->frameWidth());
- } else {
- frame->resize(196, 20);
- }
- }
- updateMask();
- }
- QWidget::changeEvent(ev);
-}
-
-void QWorkspaceChild::setActive(bool b)
-{
- if (!childWidget)
- return;
-
- bool hasFocus = isChildOf(window()->focusWidget(), this);
- if (act == b && (act == hasFocus))
- return;
-
- act = b;
-
- if (titlebar)
- titlebar->setActive(act);
- if (iconw)
- iconw->setActive(act);
- update();
-
- QList<QWidget*> wl = childWidget->findChildren<QWidget*>();
- if (act) {
- for (int i = 0; i < wl.size(); ++i) {
- QWidget *w = wl.at(i);
- w->removeEventFilter(this);
- }
- if (!hasFocus) {
- QWidget *lastfocusw = childWidget->focusWidget();
- if (lastfocusw && lastfocusw->focusPolicy() != Qt::NoFocus) {
- lastfocusw->setFocus();
- } else if (childWidget->focusPolicy() != Qt::NoFocus) {
- childWidget->setFocus();
- } else {
- // find something, anything, that accepts focus, and use that.
- for (int i = 0; i < wl.size(); ++i) {
- QWidget *w = wl.at(i);
- if(w->focusPolicy() != Qt::NoFocus) {
- w->setFocus();
- hasFocus = true;
- break;
- }
- }
- if (!hasFocus)
- setFocus();
- }
- }
- } else {
- for (int i = 0; i < wl.size(); ++i) {
- QWidget *w = wl.at(i);
- w->removeEventFilter(this);
- w->installEventFilter(this);
- }
- }
-}
-
-bool QWorkspaceChild::isActive() const
-{
- return act;
-}
-
-QWidget* QWorkspaceChild::windowWidget() const
-{
- return childWidget;
-}
-
-bool QWorkspaceChild::isWindowOrIconVisible() const
-{
- return childWidget && (!isHidden() || (iconw && !iconw->isHidden()));
-}
-
-void QWorkspaceChild::updateMask()
-{
- QStyleOptionTitleBar titleBarOptions;
- titleBarOptions.rect = rect();
- titleBarOptions.titleBarFlags = windowFlags();
- titleBarOptions.titleBarState = windowState();
-
- QStyleHintReturnMask frameMask;
- if (style()->styleHint(QStyle::SH_WindowFrame_Mask, &titleBarOptions, this, &frameMask)) {
- setMask(frameMask.region);
- } else if (!mask().isEmpty()) {
- clearMask();
- }
-
- if (iconw) {
- QFrame *frame = qobject_cast<QFrame *>(iconw->parentWidget());
- Q_ASSERT(frame);
-
- titleBarOptions.rect = frame->rect();
- titleBarOptions.titleBarFlags = frame->windowFlags();
- titleBarOptions.titleBarState = frame->windowState() | Qt::WindowMinimized;
- if (style()->styleHint(QStyle::SH_WindowFrame_Mask, &titleBarOptions, frame, &frameMask)) {
- frame->setMask(frameMask.region);
- } else if (!frame->mask().isEmpty()) {
- frame->clearMask();
- }
- }
-}
-
-QWidget* QWorkspaceChild::iconWidget() const
-{
- if (!iconw) {
- QWorkspaceChild* that = (QWorkspaceChild*) this;
-
- QFrame* frame = new QFrame(that, Qt::Window);
- QVBoxLayout *vbox = new QVBoxLayout(frame);
- vbox->setMargin(0);
- QWorkspaceTitleBar *tb = new QWorkspaceTitleBar(windowWidget(), frame);
- vbox->addWidget(tb);
- tb->setObjectName(QLatin1String("_workspacechild_icon_"));
- QStyleOptionTitleBar opt;
- tb->initStyleOption(&opt);
- int th = style()->pixelMetric(QStyle::PM_TitleBarHeight, &opt, tb);
- int iconSize = style()->pixelMetric(QStyle::PM_MdiSubWindowMinimizedWidth, 0, this);
- if (!style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar)) {
- frame->setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
- frame->resize(iconSize+2*frame->frameWidth(), th+2*frame->frameWidth());
- } else {
- frame->resize(iconSize, th);
- }
-
- that->iconw = tb;
- that->updateMask();
- iconw->setActive(isActive());
-
- connect(iconw, SIGNAL(doActivate()),
- this, SLOT(activate()));
- connect(iconw, SIGNAL(doClose()),
- windowWidget(), SLOT(close()));
- connect(iconw, SIGNAL(doNormal()),
- this, SLOT(showNormal()));
- connect(iconw, SIGNAL(doMaximize()),
- this, SLOT(showMaximized()));
- connect(iconw, SIGNAL(popupOperationMenu(QPoint)),
- this, SIGNAL(popupOperationMenu(QPoint)));
- connect(iconw, SIGNAL(showOperationMenu()),
- this, SIGNAL(showOperationMenu()));
- connect(iconw, SIGNAL(doubleClicked()),
- this, SLOT(titleBarDoubleClicked()));
- }
- if (windowWidget()) {
- iconw->setWindowTitle(windowWidget()->windowTitle());
- }
- return iconw->parentWidget();
-}
-
-void QWorkspaceChild::showMinimized()
-{
- windowWidget()->setWindowState(Qt::WindowMinimized | (windowWidget()->windowState() & ~Qt::WindowMaximized));
-}
-
-void QWorkspaceChild::showMaximized()
-{
- windowWidget()->setWindowState(Qt::WindowMaximized | (windowWidget()->windowState() & ~Qt::WindowMinimized));
-}
-
-void QWorkspaceChild::showNormal()
-{
- windowWidget()->setWindowState(windowWidget()->windowState() & ~(Qt::WindowMinimized|Qt::WindowMaximized));
-}
-
-void QWorkspaceChild::showShaded()
-{
- if (!titlebar)
- return;
- ((QWorkspace*)parentWidget())->d_func()->activateWindow(windowWidget());
- QWidget* w = windowWidget();
- if (shademode) {
- w->overrideWindowState(Qt::WindowNoState);
- overrideWindowState(Qt::WindowNoState);
-
- shademode = false;
- resize(shadeRestore.expandedTo(minimumSizeHint()));
- setMinimumSize(shadeRestoreMin);
- style()->polish(this);
- } else {
- shadeRestore = size();
- shadeRestoreMin = minimumSize();
- setMinimumHeight(0);
- shademode = true;
- w->overrideWindowState(Qt::WindowMinimized);
- overrideWindowState(Qt::WindowMinimized);
-
- if (style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar))
- resize(width(), titlebar->height());
- else
- resize(width(), titlebar->height() + 2*frameWidth() + 1);
- style()->polish(this);
- }
- titlebar->update();
-}
-
-void QWorkspaceChild::titleBarDoubleClicked()
-{
- if (!windowWidget())
- return;
- if (iconw)
- showNormal();
- else if (windowWidget()->windowFlags() & Qt::WindowShadeButtonHint)
- showShaded();
- else if (windowWidget()->windowFlags() & Qt::WindowMaximizeButtonHint)
- showMaximized();
-}
-
-void QWorkspaceChild::adjustToFullscreen()
-{
- if (!childWidget)
- return;
-
- if(!((QWorkspace*)parentWidget())->d_func()->maxmenubar || style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, this)) {
- setGeometry(parentWidget()->rect());
- } else {
- int fw = style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, 0, this);
- bool noBorder = style()->styleHint(QStyle::SH_TitleBar_NoBorder, 0, titlebar);
- int th = titlebar ? titlebar->sizeHint().height() : 0;
- int w = parentWidget()->width() + 2*fw;
- int h = parentWidget()->height() + (noBorder ? fw : 2*fw) + th;
- w = qMax(w, childWidget->minimumWidth());
- h = qMax(h, childWidget->minimumHeight());
- setGeometry(-fw, (noBorder ? 0 : -fw) - th, w, h);
- }
- childWidget->overrideWindowState(Qt::WindowMaximized);
- overrideWindowState(Qt::WindowMaximized);
-}
-
-void QWorkspaceChild::internalRaise()
-{
-
- QWidget *stackUnderWidget = 0;
- if (!windowWidget() || (windowWidget()->windowFlags() & Qt::WindowStaysOnTopHint) == 0) {
-
- QList<QWorkspaceChild *>::Iterator it(((QWorkspace*)parent())->d_func()->windows.begin());
- while (it != ((QWorkspace*)parent())->d_func()->windows.end()) {
- QWorkspaceChild* c = *it;
- ++it;
- if (c->windowWidget() &&
- !c->windowWidget()->isHidden() &&
- (c->windowWidget()->windowFlags() & Qt::WindowStaysOnTopHint)) {
- if (stackUnderWidget)
- c->stackUnder(stackUnderWidget);
- else
- c->raise();
- stackUnderWidget = c;
- }
- }
- }
-
- if (stackUnderWidget) {
- if (iconw)
- iconw->parentWidget()->stackUnder(stackUnderWidget);
- stackUnder(stackUnderWidget);
- } else {
- if (iconw)
- iconw->parentWidget()->raise();
- raise();
- }
-
-}
-
-void QWorkspaceChild::show()
-{
- if (childWidget && childWidget->isHidden())
- childWidget->show();
- QWidget::show();
-}
-
-bool QWorkspace::scrollBarsEnabled() const
-{
- Q_D(const QWorkspace);
- return d->vbar != 0;
-}
-
-/*!
- \property QWorkspace::scrollBarsEnabled
- \brief whether the workspace provides scroll bars
-
- If this property is true, the workspace will provide scroll bars if any
- of the child windows extend beyond the edges of the visible
- workspace. The workspace area will automatically increase to
- contain child windows if they are resized beyond the right or
- bottom edges of the visible area.
-
- If this property is false (the default), resizing child windows
- out of the visible area of the workspace is not permitted, although
- it is still possible to position them partially outside the visible area.
-*/
-void QWorkspace::setScrollBarsEnabled(bool enable)
-{
- Q_D(QWorkspace);
- if ((d->vbar != 0) == enable)
- return;
-
- d->xoffset = d->yoffset = 0;
- if (enable) {
- d->vbar = new QScrollBar(Qt::Vertical, this);
- d->vbar->setObjectName(QLatin1String("vertical scrollbar"));
- connect(d->vbar, SIGNAL(valueChanged(int)), this, SLOT(_q_scrollBarChanged()));
- d->hbar = new QScrollBar(Qt::Horizontal, this);
- d->hbar->setObjectName(QLatin1String("horizontal scrollbar"));
- connect(d->hbar, SIGNAL(valueChanged(int)), this, SLOT(_q_scrollBarChanged()));
- d->corner = new QWidget(this);
- d->corner->setBackgroundRole(QPalette::Window);
- d->corner->setObjectName(QLatin1String("qt_corner"));
- d->updateWorkspace();
- } else {
- delete d->vbar;
- delete d->hbar;
- delete d->corner;
- d->vbar = d->hbar = 0;
- d->corner = 0;
- }
-
- QList<QWorkspaceChild *>::Iterator it(d->windows.begin());
- while (it != d->windows.end()) {
- QWorkspaceChild *child = *it;
- ++it;
- child->widgetResizeHandler->setSizeProtection(!enable);
- }
-}
-
-QRect QWorkspacePrivate::updateWorkspace()
-{
- Q_Q(QWorkspace);
- QRect cr(q->rect());
-
- if (q->scrollBarsEnabled() && !maxWindow) {
- corner->raise();
- vbar->raise();
- hbar->raise();
- if (maxWindow)
- maxWindow->internalRaise();
-
- QRect r(0, 0, 0, 0);
- QList<QWorkspaceChild *>::Iterator it(windows.begin());
- while (it != windows.end()) {
- QWorkspaceChild *child = *it;
- ++it;
- if (!child->isHidden())
- r = r.unite(child->geometry());
- }
- vbar->blockSignals(true);
- hbar->blockSignals(true);
-
- int hsbExt = hbar->sizeHint().height();
- int vsbExt = vbar->sizeHint().width();
-
-
- bool showv = yoffset || yoffset + r.bottom() - q->height() + 1 > 0 || yoffset + r.top() < 0;
- bool showh = xoffset || xoffset + r.right() - q->width() + 1 > 0 || xoffset + r.left() < 0;
-
- if (showh && !showv)
- showv = yoffset + r.bottom() - q->height() + hsbExt + 1 > 0;
- if (showv && !showh)
- showh = xoffset + r.right() - q->width() + vsbExt + 1 > 0;
-
- if (!showh)
- hsbExt = 0;
- if (!showv)
- vsbExt = 0;
-
- if (showv) {
- vbar->setSingleStep(qMax(q->height() / 12, 30));
- vbar->setPageStep(q->height() - hsbExt);
- vbar->setMinimum(qMin(0, yoffset + qMin(0, r.top())));
- vbar->setMaximum(qMax(0, yoffset + qMax(0, r.bottom() - q->height() + hsbExt + 1)));
- vbar->setGeometry(q->width() - vsbExt, 0, vsbExt, q->height() - hsbExt);
- vbar->setValue(yoffset);
- vbar->show();
- } else {
- vbar->hide();
- }
-
- if (showh) {
- hbar->setSingleStep(qMax(q->width() / 12, 30));
- hbar->setPageStep(q->width() - vsbExt);
- hbar->setMinimum(qMin(0, xoffset + qMin(0, r.left())));
- hbar->setMaximum(qMax(0, xoffset + qMax(0, r.right() - q->width() + vsbExt + 1)));
- hbar->setGeometry(0, q->height() - hsbExt, q->width() - vsbExt, hsbExt);
- hbar->setValue(xoffset);
- hbar->show();
- } else {
- hbar->hide();
- }
-
- if (showh && showv) {
- corner->setGeometry(q->width() - vsbExt, q->height() - hsbExt, vsbExt, hsbExt);
- corner->show();
- } else {
- corner->hide();
- }
-
- vbar->blockSignals(false);
- hbar->blockSignals(false);
-
- cr.setRect(0, 0, q->width() - vsbExt, q->height() - hsbExt);
- }
-
- QList<QWidget *>::Iterator ii(icons.begin());
- while (ii != icons.end()) {
- QWidget* w = *ii;
- ++ii;
- int x = w->x();
- int y = w->y();
- bool m = false;
- if (x+w->width() > cr.width()) {
- m = true;
- x = cr.width() - w->width();
- }
- if (y+w->height() > cr.height()) {
- y = cr.height() - w->height();
- m = true;
- }
- if (m) {
- if (QWorkspaceChild *child = qobject_cast<QWorkspaceChild*>(w))
- child->move(x, y);
- else
- w->move(x, y);
- }
- }
-
- return cr;
-
-}
-
-void QWorkspacePrivate::_q_scrollBarChanged()
-{
- int ver = yoffset - vbar->value();
- int hor = xoffset - hbar->value();
- yoffset = vbar->value();
- xoffset = hbar->value();
-
- QList<QWorkspaceChild *>::Iterator it(windows.begin());
- while (it != windows.end()) {
- QWorkspaceChild *child = *it;
- ++it;
- // we do not use move() due to the reimplementation in QWorkspaceChild
- child->setGeometry(child->x() + hor, child->y() + ver, child->width(), child->height());
- }
- updateWorkspace();
-}
-
-/*!
- \enum QWorkspace::WindowOrder
-
- Specifies the order in which child windows are returned from windowList().
-
- \value CreationOrder The windows are returned in the order of their creation
- \value StackingOrder The windows are returned in the order of their stacking
-*/
-
-/*!\reimp */
-void QWorkspace::changeEvent(QEvent *ev)
-{
- Q_D(QWorkspace);
- if(ev->type() == QEvent::StyleChange) {
- if (isVisible() && d->maxWindow && d->maxmenubar) {
- if(style()->styleHint(QStyle::SH_Workspace_FillSpaceOnMaximize, 0, this)) {
- d->hideMaximizeControls(); //hide any visible maximized controls
- d->showMaximizeControls(); //updates the modification state as well
- }
- }
- }
- QWidget::changeEvent(ev);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qworkspace.cpp"
-
-#include "qworkspace.moc"
-
-#endif // QT_NO_WORKSPACE
diff --git a/src/gui/widgets/qworkspace.h b/src/gui/widgets/qworkspace.h
deleted file mode 100644
index f0b7c26867..0000000000
--- a/src/gui/widgets/qworkspace.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/****************************************************************************
-**
-** 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 QWORKSPACE_H
-#define QWORKSPACE_H
-
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Gui)
-
-#ifndef QT_NO_WORKSPACE
-
-class QAction;
-class QWorkspaceChild;
-class QShowEvent;
-class QWorkspacePrivate;
-
-class Q_GUI_EXPORT QWorkspace : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(bool scrollBarsEnabled READ scrollBarsEnabled WRITE setScrollBarsEnabled)
- Q_PROPERTY(QBrush background READ background WRITE setBackground)
-
-public:
- explicit QWorkspace(QWidget* parent=0);
- ~QWorkspace();
-
- enum WindowOrder { CreationOrder, StackingOrder };
-
- QWidget* activeWindow() const;
- QWidgetList windowList(WindowOrder order = CreationOrder) const;
-
- QWidget * addWindow(QWidget *w, Qt::WindowFlags flags = 0);
-
- QSize sizeHint() const;
-
- bool scrollBarsEnabled() const;
- void setScrollBarsEnabled(bool enable);
-
-#ifdef QT3_SUPPORT
- QT3_SUPPORT_CONSTRUCTOR QWorkspace(QWidget* parent, const char* name);
- QT3_SUPPORT void setPaletteBackgroundColor(const QColor &);
- QT3_SUPPORT void setPaletteBackgroundPixmap(const QPixmap &);
-#endif
-
- void setBackground(const QBrush &background);
- QBrush background() const;
-
-Q_SIGNALS:
- void windowActivated(QWidget* w);
-
-public Q_SLOTS:
- void setActiveWindow(QWidget *w);
- void cascade();
- void tile();
- void arrangeIcons();
- void closeActiveWindow();
- void closeAllWindows();
- void activateNextWindow();
- void activatePreviousWindow();
-
-protected:
- bool event(QEvent *e);
- void paintEvent(QPaintEvent *e);
- void changeEvent(QEvent *);
- void childEvent(QChildEvent *);
- void resizeEvent(QResizeEvent *);
- bool eventFilter(QObject *, QEvent *);
- void showEvent(QShowEvent *e);
- void hideEvent(QHideEvent *e);
-#ifndef QT_NO_WHEELEVENT
- void wheelEvent(QWheelEvent *e);
-#endif
-
-private:
- Q_DECLARE_PRIVATE(QWorkspace)
- Q_DISABLE_COPY(QWorkspace)
- Q_PRIVATE_SLOT(d_func(), void _q_normalizeActiveWindow())
- Q_PRIVATE_SLOT(d_func(), void _q_minimizeActiveWindow())
- Q_PRIVATE_SLOT(d_func(), void _q_showOperationMenu())
- Q_PRIVATE_SLOT(d_func(), void _q_popupOperationMenu(const QPoint&))
- Q_PRIVATE_SLOT(d_func(), void _q_operationMenuActivated(QAction *))
- Q_PRIVATE_SLOT(d_func(), void _q_updateActions())
- Q_PRIVATE_SLOT(d_func(), void _q_scrollBarChanged())
-
- friend class QWorkspaceChild;
-};
-
-#endif // QT_NO_WORKSPACE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWORKSPACE_H
diff --git a/src/gui/widgets/widgets.pri b/src/gui/widgets/widgets.pri
deleted file mode 100644
index a991ff1fac..0000000000
--- a/src/gui/widgets/widgets.pri
+++ /dev/null
@@ -1,165 +0,0 @@
-# Qt widgets module
-
-HEADERS += \
- widgets/qbuttongroup.h \
- widgets/qabstractbutton.h \
- widgets/qabstractbutton_p.h \
- widgets/qabstractslider.h \
- widgets/qabstractslider_p.h \
- widgets/qabstractspinbox.h \
- widgets/qabstractspinbox_p.h \
- widgets/qcalendartextnavigator_p.h \
- widgets/qcalendarwidget.h \
- widgets/qcheckbox.h \
- widgets/qcombobox.h \
- widgets/qcombobox_p.h \
- widgets/qcommandlinkbutton.h \
- widgets/qdatetimeedit.h \
- widgets/qdatetimeedit_p.h \
- widgets/qdial.h \
- widgets/qdialogbuttonbox.h \
- widgets/qdockwidget.h \
- widgets/qdockwidget_p.h \
- widgets/qdockarealayout_p.h \
- widgets/qfontcombobox.h \
- widgets/qframe.h \
- widgets/qframe_p.h \
- widgets/qgroupbox.h \
- widgets/qlabel.h \
- widgets/qlabel_p.h \
- widgets/qlcdnumber.h \
- widgets/qlineedit.h \
- widgets/qlineedit_p.h \
- widgets/qmainwindow.h \
- widgets/qmainwindowlayout_p.h \
- widgets/qmdiarea.h \
- widgets/qmdiarea_p.h \
- widgets/qmdisubwindow.h \
- widgets/qmdisubwindow_p.h \
- widgets/qmenu.h \
- widgets/qmenu_p.h \
- widgets/qmenubar.h \
- widgets/qmenubar_p.h \
- widgets/qmenudata.h \
- widgets/qprogressbar.h \
- widgets/qpushbutton.h \
- widgets/qpushbutton_p.h \
- widgets/qradiobutton.h \
- widgets/qrubberband.h \
- widgets/qscrollbar.h \
- widgets/qscrollarea_p.h \
- widgets/qsizegrip.h \
- widgets/qslider.h \
- widgets/qspinbox.h \
- widgets/qsplashscreen.h \
- widgets/qsplitter.h \
- widgets/qsplitter_p.h \
- widgets/qstackedwidget.h \
- widgets/qstatusbar.h \
- widgets/qtabbar.h \
- widgets/qtabbar_p.h \
- widgets/qtabwidget.h \
- widgets/qtextedit.h \
- widgets/qtextedit_p.h \
- widgets/qtextbrowser.h \
- widgets/qtoolbar.h \
- widgets/qtoolbar_p.h \
- widgets/qtoolbarlayout_p.h \
- widgets/qtoolbarextension_p.h \
- widgets/qtoolbarseparator_p.h \
- widgets/qtoolbox.h \
- widgets/qtoolbutton.h \
- widgets/qabstractscrollarea.h \
- widgets/qabstractscrollarea_p.h \
- widgets/qwidgetresizehandler_p.h \
- widgets/qfocusframe.h \
- widgets/qscrollarea.h \
- widgets/qworkspace.h \
- widgets/qwidgetanimator_p.h \
- widgets/qtoolbararealayout_p.h \
- widgets/qplaintextedit.h \
- widgets/qplaintextedit_p.h \
- widgets/qprintpreviewwidget.h
-SOURCES += \
- widgets/qabstractbutton.cpp \
- widgets/qabstractslider.cpp \
- widgets/qabstractspinbox.cpp \
- widgets/qcalendarwidget.cpp \
- widgets/qcheckbox.cpp \
- widgets/qcombobox.cpp \
- widgets/qcommandlinkbutton.cpp \
- widgets/qdatetimeedit.cpp \
- widgets/qdial.cpp \
- widgets/qdialogbuttonbox.cpp \
- widgets/qdockwidget.cpp \
- widgets/qdockarealayout.cpp \
- widgets/qeffects.cpp \
- widgets/qfontcombobox.cpp \
- widgets/qframe.cpp \
- widgets/qgroupbox.cpp \
- widgets/qlabel.cpp \
- widgets/qlcdnumber.cpp \
- widgets/qlineedit_p.cpp \
- widgets/qlineedit.cpp \
- widgets/qmainwindow.cpp \
- widgets/qmainwindowlayout.cpp \
- widgets/qmdiarea.cpp \
- widgets/qmdisubwindow.cpp \
- widgets/qmenu.cpp \
- widgets/qmenubar.cpp \
- widgets/qmenudata.cpp \
- widgets/qprogressbar.cpp \
- widgets/qpushbutton.cpp \
- widgets/qradiobutton.cpp \
- widgets/qrubberband.cpp \
- widgets/qscrollbar.cpp \
- widgets/qsizegrip.cpp \
- widgets/qslider.cpp \
- widgets/qspinbox.cpp \
- widgets/qsplashscreen.cpp \
- widgets/qsplitter.cpp \
- widgets/qstackedwidget.cpp \
- widgets/qstatusbar.cpp \
- widgets/qtabbar.cpp \
- widgets/qtabwidget.cpp \
- widgets/qtextedit.cpp \
- widgets/qtextbrowser.cpp \
- widgets/qtoolbar.cpp \
- widgets/qtoolbarlayout.cpp \
- widgets/qtoolbarextension.cpp \
- widgets/qtoolbarseparator.cpp \
- widgets/qtoolbox.cpp \
- widgets/qtoolbutton.cpp \
- widgets/qabstractscrollarea.cpp \
- widgets/qwidgetresizehandler.cpp \
- widgets/qfocusframe.cpp \
- widgets/qscrollarea.cpp \
- widgets/qworkspace.cpp \
- widgets/qwidgetanimator.cpp \
- widgets/qtoolbararealayout.cpp \
- widgets/qplaintextedit.cpp \
- widgets/qprintpreviewwidget.cpp
-
-!qpa:mac {
- HEADERS += widgets/qmacnativewidget_mac.h \
- widgets/qmaccocoaviewcontainer_mac.h
- OBJECTIVE_HEADERS += widgets/qcocoatoolbardelegate_mac_p.h \
- widgets/qcocoamenu_mac_p.h
- OBJECTIVE_SOURCES += widgets/qmenu_mac.mm \
- widgets/qmaccocoaviewcontainer_mac.mm \
- widgets/qcocoatoolbardelegate_mac.mm \
- widgets/qmainwindowlayout_mac.mm \
- widgets/qmacnativewidget_mac.mm \
- widgets/qcocoamenu_mac.mm
-}
-
-wince*: {
- SOURCES += widgets/qmenu_wince.cpp
- HEADERS += widgets/qmenu_wince_resource_p.h
- RC_FILE = widgets/qmenu_wince.rc
- !static: QMAKE_WRITE_DEFAULT_RC = 1
-}
-
-symbian: {
- SOURCES += widgets/qmenu_symbian.cpp
-}